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.

277153 lines
7.4MB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library - "Jules' Utility Class Extensions"
  4. Copyright 2004-9 by Raw Material Software Ltd.
  5. ------------------------------------------------------------------------------
  6. JUCE can be redistributed and/or modified under the terms of the GNU General
  7. Public License (Version 2), as published by the Free Software Foundation.
  8. A copy of the license is included in the JUCE distribution, or can be found
  9. online at www.gnu.org/licenses.
  10. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  11. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  12. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  13. ------------------------------------------------------------------------------
  14. To release a closed-source product which uses JUCE, commercial licenses are
  15. available: visit www.rawmaterialsoftware.com/juce for more information.
  16. ==============================================================================
  17. */
  18. /*
  19. This monolithic file contains the entire Juce source tree!
  20. To build an app which uses Juce, all you need to do is to add this
  21. file to your project, and include juce.h in your own cpp files.
  22. */
  23. #ifdef __JUCE_JUCEHEADER__
  24. /* When you add the amalgamated cpp file to your project, you mustn't include it in
  25. a file where you've already included juce.h - just put it inside a file on its own,
  26. possibly with your config flags preceding it, but don't include anything else. */
  27. #error
  28. #endif
  29. /*** Start of inlined file: juce_TargetPlatform.h ***/
  30. #ifndef __JUCE_TARGETPLATFORM_JUCEHEADER__
  31. #define __JUCE_TARGETPLATFORM_JUCEHEADER__
  32. /* This file figures out which platform is being built, and defines some macros
  33. that the rest of the code can use for OS-specific compilation.
  34. Macros that will be set here are:
  35. - One of JUCE_WINDOWS, JUCE_MAC or JUCE_LINUX.
  36. - Either JUCE_32BIT or JUCE_64BIT, depending on the architecture.
  37. - Either JUCE_LITTLE_ENDIAN or JUCE_BIG_ENDIAN.
  38. - Either JUCE_INTEL or JUCE_PPC
  39. - Either JUCE_GCC or JUCE_MSVC
  40. */
  41. #if (defined (_WIN32) || defined (_WIN64))
  42. #define JUCE_WIN32 1
  43. #define JUCE_WINDOWS 1
  44. #elif defined (LINUX) || defined (__linux__)
  45. #define JUCE_LINUX 1
  46. #elif defined(__APPLE_CPP__) || defined(__APPLE_CC__)
  47. #include <CoreFoundation/CoreFoundation.h> // (needed to find out what platform we're using)
  48. #if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
  49. #define JUCE_IPHONE 1
  50. #else
  51. #define JUCE_MAC 1
  52. #endif
  53. #else
  54. #error "Unknown platform!"
  55. #endif
  56. #if JUCE_WINDOWS
  57. #ifdef _MSC_VER
  58. #ifdef _WIN64
  59. #define JUCE_64BIT 1
  60. #else
  61. #define JUCE_32BIT 1
  62. #endif
  63. #endif
  64. #ifdef _DEBUG
  65. #define JUCE_DEBUG 1
  66. #endif
  67. #ifdef __MINGW32__
  68. #define JUCE_MINGW 1
  69. #endif
  70. /** If defined, this indicates that the processor is little-endian. */
  71. #define JUCE_LITTLE_ENDIAN 1
  72. #define JUCE_INTEL 1
  73. #endif
  74. #if JUCE_MAC
  75. #ifndef NDEBUG
  76. #define JUCE_DEBUG 1
  77. #endif
  78. #ifdef __LITTLE_ENDIAN__
  79. #define JUCE_LITTLE_ENDIAN 1
  80. #else
  81. #define JUCE_BIG_ENDIAN 1
  82. #endif
  83. #if defined (__ppc__) || defined (__ppc64__)
  84. #define JUCE_PPC 1
  85. #else
  86. #define JUCE_INTEL 1
  87. #endif
  88. #ifdef __LP64__
  89. #define JUCE_64BIT 1
  90. #else
  91. #define JUCE_32BIT 1
  92. #endif
  93. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_4
  94. #error "Building for OSX 10.3 is no longer supported!"
  95. #endif
  96. #ifndef MAC_OS_X_VERSION_10_5
  97. #error "To build with 10.4 compatibility, use a 10.5 or 10.6 SDK and set the deployment target to 10.4"
  98. #endif
  99. #endif
  100. #if JUCE_IPHONE
  101. #ifndef NDEBUG
  102. #define JUCE_DEBUG 1
  103. #endif
  104. #ifdef __LITTLE_ENDIAN__
  105. #define JUCE_LITTLE_ENDIAN 1
  106. #else
  107. #define JUCE_BIG_ENDIAN 1
  108. #endif
  109. #endif
  110. #if JUCE_LINUX
  111. #ifdef _DEBUG
  112. #define JUCE_DEBUG 1
  113. #endif
  114. // Allow override for big-endian Linux platforms
  115. #ifndef JUCE_BIG_ENDIAN
  116. #define JUCE_LITTLE_ENDIAN 1
  117. #endif
  118. #if defined (__LP64__) || defined (_LP64)
  119. #define JUCE_64BIT 1
  120. #else
  121. #define JUCE_32BIT 1
  122. #endif
  123. #define JUCE_INTEL 1
  124. #endif
  125. // Compiler type macros.
  126. #ifdef __GNUC__
  127. #define JUCE_GCC 1
  128. #elif defined (_MSC_VER)
  129. #define JUCE_MSVC 1
  130. #if _MSC_VER >= 1400
  131. #define JUCE_USE_INTRINSICS 1
  132. #endif
  133. #else
  134. #error unknown compiler
  135. #endif
  136. #endif // __JUCE_TARGETPLATFORM_JUCEHEADER__
  137. /*** End of inlined file: juce_TargetPlatform.h ***/
  138. // FORCE_AMALGAMATOR_INCLUDE
  139. /*** Start of inlined file: juce_Config.h ***/
  140. #ifndef __JUCE_CONFIG_JUCEHEADER__
  141. #define __JUCE_CONFIG_JUCEHEADER__
  142. /*
  143. This file contains macros that enable/disable various JUCE features.
  144. */
  145. /** The name of the namespace that all Juce classes and functions will be
  146. put inside. If this is not defined, no namespace will be used.
  147. */
  148. #ifndef JUCE_NAMESPACE
  149. #define JUCE_NAMESPACE juce
  150. #endif
  151. /** JUCE_FORCE_DEBUG: Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and
  152. project settings, but if you define this value, you can override this to force
  153. it to be true or false.
  154. */
  155. #ifndef JUCE_FORCE_DEBUG
  156. //#define JUCE_FORCE_DEBUG 0
  157. #endif
  158. /** JUCE_LOG_ASSERTIONS: If this flag is enabled, the the jassert and jassertfalse
  159. macros will always use Logger::writeToLog() to write a message when an assertion happens.
  160. Enabling it will also leave this turned on in release builds. When it's disabled,
  161. however, the jassert and jassertfalse macros will not be compiled in a
  162. release build.
  163. @see jassert, jassertfalse, Logger
  164. */
  165. #ifndef JUCE_LOG_ASSERTIONS
  166. #define JUCE_LOG_ASSERTIONS 0
  167. #endif
  168. /** JUCE_ASIO: Enables ASIO audio devices (MS Windows only).
  169. Turning this on means that you'll need to have the Steinberg ASIO SDK installed
  170. on your Windows build machine.
  171. See the comments in the ASIOAudioIODevice class's header file for more
  172. info about this.
  173. */
  174. #ifndef JUCE_ASIO
  175. #define JUCE_ASIO 0
  176. #endif
  177. /** JUCE_WASAPI: Enables WASAPI audio devices (Windows Vista and above).
  178. */
  179. #ifndef JUCE_WASAPI
  180. #define JUCE_WASAPI 0
  181. #endif
  182. /** JUCE_DIRECTSOUND: Enables DirectSound audio (MS Windows only).
  183. */
  184. #ifndef JUCE_DIRECTSOUND
  185. #define JUCE_DIRECTSOUND 1
  186. #endif
  187. /** JUCE_ALSA: Enables ALSA audio devices (Linux only). */
  188. #ifndef JUCE_ALSA
  189. #define JUCE_ALSA 1
  190. #endif
  191. /** JUCE_JACK: Enables JACK audio devices (Linux only). */
  192. #ifndef JUCE_JACK
  193. #define JUCE_JACK 0
  194. #endif
  195. /** JUCE_QUICKTIME: Enables the QuickTimeMovieComponent class (Mac and Windows).
  196. If you're building on Windows, you'll need to have the Apple QuickTime SDK
  197. installed, and its header files will need to be on your include path.
  198. */
  199. #if ! (defined (JUCE_QUICKTIME) || JUCE_LINUX || JUCE_IPHONE || (JUCE_WINDOWS && ! JUCE_MSVC))
  200. #define JUCE_QUICKTIME 0
  201. #endif
  202. #if (JUCE_IPHONE || JUCE_LINUX) && JUCE_QUICKTIME
  203. #undef JUCE_QUICKTIME
  204. #endif
  205. /** JUCE_OPENGL: Enables the OpenGLComponent class (available on all platforms).
  206. If you're not using OpenGL, you might want to turn this off to reduce your binary's size.
  207. */
  208. #ifndef JUCE_OPENGL
  209. #define JUCE_OPENGL 1
  210. #endif
  211. /** JUCE_USE_FLAC: Enables the FLAC audio codec classes (available on all platforms).
  212. If your app doesn't need to read FLAC files, you might want to disable this to
  213. reduce the size of your codebase and build time.
  214. */
  215. #ifndef JUCE_USE_FLAC
  216. #define JUCE_USE_FLAC 1
  217. #endif
  218. /** JUCE_USE_OGGVORBIS: Enables the Ogg-Vorbis audio codec classes (available on all platforms).
  219. If your app doesn't need to read Ogg-Vorbis files, you might want to disable this to
  220. reduce the size of your codebase and build time.
  221. */
  222. #ifndef JUCE_USE_OGGVORBIS
  223. #define JUCE_USE_OGGVORBIS 1
  224. #endif
  225. /** JUCE_USE_CDBURNER: Enables the audio CD reader code (Mac and Windows only).
  226. Unless you're using CD-burning, you should probably turn this flag off to
  227. reduce code size.
  228. */
  229. #if (! defined (JUCE_USE_CDBURNER)) && ! (JUCE_WINDOWS && ! JUCE_MSVC)
  230. #define JUCE_USE_CDBURNER 0
  231. #endif
  232. /** JUCE_USE_CDREADER: Enables the audio CD reader code (Mac and Windows only).
  233. Unless you're using CD-reading, you should probably turn this flag off to
  234. reduce code size.
  235. */
  236. #ifndef JUCE_USE_CDREADER
  237. #define JUCE_USE_CDREADER 0
  238. #endif
  239. /** JUCE_USE_CAMERA: Enables web-cam support using the CameraDevice class (Mac and Windows).
  240. */
  241. #if (JUCE_QUICKTIME || JUCE_WINDOWS) && ! defined (JUCE_USE_CAMERA)
  242. #define JUCE_USE_CAMERA 0
  243. #endif
  244. /** JUCE_ENABLE_REPAINT_DEBUGGING: If this option is turned on, each area of the screen that
  245. gets repainted will flash in a random colour, so that you can check exactly how much and how
  246. often your components are being drawn.
  247. */
  248. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  249. #define JUCE_ENABLE_REPAINT_DEBUGGING 0
  250. #endif
  251. /** JUCE_USE_XINERAMA: Enables Xinerama multi-monitor support (Linux only).
  252. Unless you specifically want to disable this, it's best to leave this option turned on.
  253. */
  254. #ifndef JUCE_USE_XINERAMA
  255. #define JUCE_USE_XINERAMA 1
  256. #endif
  257. /** JUCE_USE_XSHM: Enables X shared memory for faster rendering on Linux. This is best left
  258. turned on unless you have a good reason to disable it.
  259. */
  260. #ifndef JUCE_USE_XSHM
  261. #define JUCE_USE_XSHM 1
  262. #endif
  263. /** JUCE_USE_XRENDER: Uses XRender to allow semi-transparent windowing on Linux.
  264. */
  265. #ifndef JUCE_USE_XRENDER
  266. #define JUCE_USE_XRENDER 0
  267. #endif
  268. /** JUCE_USE_XCURSOR: Uses XCursor to allow ARGB cursor on Linux. This is best left turned on
  269. unless you have a good reason to disable it.
  270. */
  271. #ifndef JUCE_USE_XCURSOR
  272. #define JUCE_USE_XCURSOR 1
  273. #endif
  274. /** JUCE_PLUGINHOST_VST: Enables the VST audio plugin hosting classes. This requires the
  275. Steinberg VST SDK to be installed on your machine, and should be left turned off unless
  276. you're building a plugin hosting app.
  277. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  278. */
  279. #ifndef JUCE_PLUGINHOST_VST
  280. #define JUCE_PLUGINHOST_VST 0
  281. #endif
  282. /** JUCE_PLUGINHOST_AU: Enables the AudioUnit plugin hosting classes. This is Mac-only,
  283. of course, and should only be enabled if you're building a plugin hosting app.
  284. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  285. */
  286. #ifndef JUCE_PLUGINHOST_AU
  287. #define JUCE_PLUGINHOST_AU 0
  288. #endif
  289. /** JUCE_ONLY_BUILD_CORE_LIBRARY: Enabling this will avoid including any UI classes in the build.
  290. This should be enabled if you're writing a console application.
  291. */
  292. #ifndef JUCE_ONLY_BUILD_CORE_LIBRARY
  293. #define JUCE_ONLY_BUILD_CORE_LIBRARY 0
  294. #endif
  295. /** JUCE_WEB_BROWSER: This lets you disable the WebBrowserComponent class (Mac and Windows).
  296. If you're not using any embedded web-pages, turning this off may reduce your code size.
  297. */
  298. #ifndef JUCE_WEB_BROWSER
  299. #define JUCE_WEB_BROWSER 1
  300. #endif
  301. /** JUCE_SUPPORT_CARBON: Enabling this allows the Mac code to use old Carbon library functions.
  302. Carbon isn't required for a normal app, but may be needed by specialised classes like
  303. plugin-hosts, which support older APIs.
  304. */
  305. #ifndef JUCE_SUPPORT_CARBON
  306. #define JUCE_SUPPORT_CARBON 1
  307. #endif
  308. /* JUCE_INCLUDE_ZLIB_CODE: Can be used to disable Juce's embedded 3rd-party zlib code.
  309. You might need to tweak this if you're linking to an external zlib library in your app,
  310. but for normal apps, this option should be left alone.
  311. */
  312. #ifndef JUCE_INCLUDE_ZLIB_CODE
  313. #define JUCE_INCLUDE_ZLIB_CODE 1
  314. #endif
  315. #ifndef JUCE_INCLUDE_FLAC_CODE
  316. #define JUCE_INCLUDE_FLAC_CODE 1
  317. #endif
  318. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  319. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  320. #endif
  321. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  322. #define JUCE_INCLUDE_PNGLIB_CODE 1
  323. #endif
  324. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  325. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  326. #endif
  327. /** JUCE_CHECK_MEMORY_LEAKS: Enables a memory-leak check when an app terminates.
  328. (Currently, this only affects Windows builds in debug mode).
  329. */
  330. #ifndef JUCE_CHECK_MEMORY_LEAKS
  331. #define JUCE_CHECK_MEMORY_LEAKS 1
  332. #endif
  333. /** JUCE_CATCH_UNHANDLED_EXCEPTIONS: Turn on juce's internal catching of exceptions
  334. that are thrown by the message dispatch loop. With it enabled, any unhandled exceptions
  335. are passed to the JUCEApplication::unhandledException() callback for logging.
  336. */
  337. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  338. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  339. #endif
  340. // If only building the core classes, we can explicitly turn off some features to avoid including them:
  341. #if JUCE_ONLY_BUILD_CORE_LIBRARY
  342. #undef JUCE_QUICKTIME
  343. #define JUCE_QUICKTIME 0
  344. #undef JUCE_OPENGL
  345. #define JUCE_OPENGL 0
  346. #undef JUCE_USE_CDBURNER
  347. #define JUCE_USE_CDBURNER 0
  348. #undef JUCE_USE_CDREADER
  349. #define JUCE_USE_CDREADER 0
  350. #undef JUCE_WEB_BROWSER
  351. #define JUCE_WEB_BROWSER 0
  352. #undef JUCE_PLUGINHOST_AU
  353. #define JUCE_PLUGINHOST_AU 0
  354. #undef JUCE_PLUGINHOST_VST
  355. #define JUCE_PLUGINHOST_VST 0
  356. #endif
  357. #endif
  358. /*** End of inlined file: juce_Config.h ***/
  359. // FORCE_AMALGAMATOR_INCLUDE
  360. #ifndef JUCE_BUILD_CORE
  361. #define JUCE_BUILD_CORE 1
  362. #endif
  363. #ifndef JUCE_BUILD_MISC
  364. #define JUCE_BUILD_MISC 1
  365. #endif
  366. #ifndef JUCE_BUILD_GUI
  367. #define JUCE_BUILD_GUI 1
  368. #endif
  369. #ifndef JUCE_BUILD_NATIVE
  370. #define JUCE_BUILD_NATIVE 1
  371. #endif
  372. #if JUCE_ONLY_BUILD_CORE_LIBRARY
  373. #undef JUCE_BUILD_MISC
  374. #undef JUCE_BUILD_GUI
  375. #endif
  376. //==============================================================================
  377. #if JUCE_BUILD_NATIVE || JUCE_BUILD_CORE || (JUCE_BUILD_MISC && (JUCE_PLUGINHOST_VST || JUCE_PLUGINHOST_AU))
  378. #if JUCE_WINDOWS
  379. /*** Start of inlined file: juce_win32_NativeIncludes.h ***/
  380. #ifndef __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  381. #define __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  382. #ifndef STRICT
  383. #define STRICT 1
  384. #endif
  385. #undef WIN32_LEAN_AND_MEAN
  386. #define WIN32_LEAN_AND_MEAN 1
  387. #if JUCE_MSVC
  388. #pragma warning (push)
  389. #pragma warning (disable : 4100 4201 4514 4312 4995)
  390. #endif
  391. #define _WIN32_WINNT 0x0500
  392. #define _UNICODE 1
  393. #define UNICODE 1
  394. #ifndef _WIN32_IE
  395. #define _WIN32_IE 0x0400
  396. #endif
  397. #include <windows.h>
  398. #include <windowsx.h>
  399. #include <commdlg.h>
  400. #include <shellapi.h>
  401. #include <mmsystem.h>
  402. #include <vfw.h>
  403. #include <tchar.h>
  404. #include <stddef.h>
  405. #include <ctime>
  406. #include <wininet.h>
  407. #include <nb30.h>
  408. #include <iphlpapi.h>
  409. #include <mapi.h>
  410. #include <float.h>
  411. #include <process.h>
  412. #include <Exdisp.h>
  413. #include <exdispid.h>
  414. #include <shlobj.h>
  415. #if ! JUCE_MINGW
  416. #include <crtdbg.h>
  417. #include <comutil.h>
  418. #endif
  419. #if JUCE_OPENGL
  420. #include <gl/gl.h>
  421. #endif
  422. #undef PACKED
  423. #if JUCE_ASIO
  424. /*
  425. This is very frustrating - we only need to use a handful of definitions from
  426. a couple of the header files in Steinberg's ASIO SDK, and it'd be easy to copy
  427. about 30 lines of code into this cpp file to create a fully stand-alone ASIO
  428. implementation...
  429. ..unfortunately that would break Steinberg's license agreement for use of
  430. their SDK, so I'm not allowed to do this.
  431. This means that anyone who wants to use JUCE's ASIO abilities will have to:
  432. 1) Agree to Steinberg's licensing terms and download the ASIO SDK
  433. (see www.steinberg.net/Steinberg/Developers.asp).
  434. 2) Rebuild the whole of JUCE, setting the global definition JUCE_ASIO (you
  435. can un-comment the "#define JUCE_ASIO" line in juce_Config.h
  436. if you prefer). Make sure that your header search path will find the
  437. iasiodrv.h file that comes with the SDK. (Only about 2-3 of the SDK header
  438. files are actually needed - so to simplify things, you could just copy
  439. these into your JUCE directory).
  440. If you're compiling and you get an error here because you don't have the
  441. ASIO SDK installed, you can disable ASIO support by commenting-out the
  442. "#define JUCE_ASIO" line in juce_Config.h, and rebuild your Juce library.
  443. */
  444. #include "iasiodrv.h"
  445. #endif
  446. #if JUCE_USE_CDBURNER
  447. /* You'll need the Platform SDK for these headers - if you don't have it and don't
  448. need to use CD-burning, then you might just want to disable the JUCE_USE_CDBURNER
  449. flag in juce_Config.h to avoid these includes.
  450. */
  451. #include <imapi.h>
  452. #include <imapierror.h>
  453. #endif
  454. #if JUCE_USE_CAMERA
  455. /* If you're using the camera classes, you'll need access to a few DirectShow headers.
  456. These files are provided in the normal Windows SDK, but some Microsoft plonker
  457. didn't realise that qedit.h doesn't actually compile without the rest of the DirectShow SDK..
  458. Microsoft's suggested fix for this is to hack their qedit.h file! See:
  459. http://social.msdn.microsoft.com/Forums/en-US/windowssdk/thread/ed097d2c-3d68-4f48-8448-277eaaf68252
  460. .. which is a bit of a bodge, but a lot less hassle than installing the full DShow SDK.
  461. An alternative workaround is to create a dummy dxtrans.h file and put it in your include path.
  462. The dummy file just needs to contain the following content:
  463. #define __IDxtCompositor_INTERFACE_DEFINED__
  464. #define __IDxtAlphaSetter_INTERFACE_DEFINED__
  465. #define __IDxtJpeg_INTERFACE_DEFINED__
  466. #define __IDxtKey_INTERFACE_DEFINED__
  467. ..and that should be enough to convince qedit.h that you have the SDK!
  468. */
  469. #include <dshow.h>
  470. #include <qedit.h>
  471. #include <dshowasf.h>
  472. #endif
  473. #if JUCE_WASAPI
  474. #include <MMReg.h>
  475. #include <mmdeviceapi.h>
  476. #include <Audioclient.h>
  477. #include <Avrt.h>
  478. #include <functiondiscoverykeys.h>
  479. #endif
  480. #if JUCE_QUICKTIME
  481. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  482. add its header directory to your include path.
  483. Alternatively, if you don't need any QuickTime services, just turn off the JUCE_QUICKTIME
  484. flag in juce_Config.h
  485. */
  486. #include <Movies.h>
  487. #include <QTML.h>
  488. #include <QuickTimeComponents.h>
  489. #include <MediaHandlers.h>
  490. #include <ImageCodec.h>
  491. /* If you've got QuickTime 7 installed, then these COM objects should be found in
  492. the "\Program Files\Quicktime" directory. You'll need to add this directory to
  493. your include search path to make these import statements work.
  494. */
  495. #import <QTOLibrary.dll>
  496. #import <QTOControl.dll>
  497. #endif
  498. #if JUCE_MSVC
  499. #pragma warning (pop)
  500. #endif
  501. /** A simple COM smart pointer.
  502. Avoids having to include ATL just to get one of these.
  503. */
  504. template <class ComClass>
  505. class ComSmartPtr
  506. {
  507. public:
  508. ComSmartPtr() throw() : p (0) {}
  509. ComSmartPtr (ComClass* const p_) : p (p_) { if (p_ != 0) p_->AddRef(); }
  510. ComSmartPtr (const ComSmartPtr<ComClass>& p_) : p (p_.p) { if (p != 0) p->AddRef(); }
  511. ~ComSmartPtr() { if (p != 0) p->Release(); }
  512. operator ComClass*() const throw() { return p; }
  513. ComClass& operator*() const throw() { return *p; }
  514. ComClass** operator&() throw() { return &p; }
  515. ComClass* operator->() const throw() { return p; }
  516. ComClass* operator= (ComClass* const newP)
  517. {
  518. if (newP != 0) newP->AddRef();
  519. if (p != 0) p->Release();
  520. p = newP;
  521. return newP;
  522. }
  523. ComClass* operator= (const ComSmartPtr<ComClass>& newP) { return operator= (newP.p); }
  524. HRESULT CoCreateInstance (REFCLSID rclsid, DWORD dwClsContext = CLSCTX_INPROC_SERVER)
  525. {
  526. #ifndef __MINGW32__
  527. operator= (0);
  528. return ::CoCreateInstance (rclsid, 0, dwClsContext, __uuidof (ComClass), (void**) &p);
  529. #else
  530. return S_FALSE;
  531. #endif
  532. }
  533. private:
  534. ComClass* p;
  535. };
  536. /** Handy base class for writing COM objects, providing ref-counting and a basic QueryInterface method.
  537. */
  538. template <class ComClass>
  539. class ComBaseClassHelper : public ComClass
  540. {
  541. public:
  542. ComBaseClassHelper() : refCount (1) {}
  543. virtual ~ComBaseClassHelper() {}
  544. HRESULT __stdcall QueryInterface (REFIID refId, void __RPC_FAR* __RPC_FAR* result)
  545. {
  546. if (refId == __uuidof (ComClass)) { AddRef(); *result = dynamic_cast <ComClass*> (this); return S_OK; }
  547. if (refId == IID_IUnknown) { AddRef(); *result = dynamic_cast <IUnknown*> (this); return S_OK; }
  548. *result = 0;
  549. return E_NOINTERFACE;
  550. }
  551. ULONG __stdcall AddRef() { return ++refCount; }
  552. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  553. protected:
  554. int refCount;
  555. };
  556. #endif // __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  557. /*** End of inlined file: juce_win32_NativeIncludes.h ***/
  558. #elif JUCE_LINUX
  559. /*** Start of inlined file: juce_linux_NativeIncludes.h ***/
  560. #ifndef __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  561. #define __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  562. /*
  563. This file wraps together all the linux-specific headers, so
  564. that we can include them all just once, and compile all our
  565. platform-specific stuff in one big lump, keeping it out of the
  566. way of the rest of the codebase.
  567. */
  568. #include <sched.h>
  569. #include <pthread.h>
  570. #include <sys/time.h>
  571. #include <errno.h>
  572. #include <sys/stat.h>
  573. #include <sys/dir.h>
  574. #include <sys/ptrace.h>
  575. #include <sys/vfs.h>
  576. #include <sys/wait.h>
  577. #include <fnmatch.h>
  578. #include <utime.h>
  579. #include <pwd.h>
  580. #include <fcntl.h>
  581. #include <dlfcn.h>
  582. #include <netdb.h>
  583. #include <arpa/inet.h>
  584. #include <netinet/in.h>
  585. #include <sys/types.h>
  586. #include <sys/ioctl.h>
  587. #include <sys/socket.h>
  588. #include <linux/if.h>
  589. #include <sys/sysinfo.h>
  590. #include <sys/file.h>
  591. #include <signal.h>
  592. /* Got a build error here? You'll need to install the freetype library...
  593. The name of the package to install is "libfreetype6-dev".
  594. */
  595. #include <ft2build.h>
  596. #include FT_FREETYPE_H
  597. #include <X11/Xlib.h>
  598. #include <X11/Xatom.h>
  599. #include <X11/Xresource.h>
  600. #include <X11/Xutil.h>
  601. #include <X11/Xmd.h>
  602. #include <X11/keysym.h>
  603. #include <X11/cursorfont.h>
  604. #if JUCE_USE_XINERAMA
  605. /* If you're trying to use Xinerama, you'll need to install the "libxinerama-dev" package.. */
  606. #include <X11/extensions/Xinerama.h>
  607. #endif
  608. #if JUCE_USE_XSHM
  609. #include <X11/extensions/XShm.h>
  610. #include <sys/shm.h>
  611. #include <sys/ipc.h>
  612. #endif
  613. #if JUCE_USE_XRENDER
  614. // If you're missing these headers, try installing the libxrender-dev and libxcomposite-dev
  615. #include <X11/extensions/Xrender.h>
  616. #include <X11/extensions/Xcomposite.h>
  617. #endif
  618. #if JUCE_USE_XCURSOR
  619. // If you're missing this header, try installing the libxcursor-dev package
  620. #include <X11/Xcursor/Xcursor.h>
  621. #endif
  622. #if JUCE_OPENGL
  623. /* Got an include error here?
  624. If you want to install OpenGL support, the packages to get are "mesa-common-dev"
  625. and "freeglut3-dev".
  626. Alternatively, you can turn off the JUCE_OPENGL flag in juce_Config.h if you
  627. want to disable it.
  628. */
  629. #include <GL/glx.h>
  630. #endif
  631. #undef KeyPress
  632. #if JUCE_ALSA
  633. /* Got an include error here? If so, you've either not got ALSA installed, or you've
  634. not got your paths set up correctly to find its header files.
  635. The package you need to install to get ASLA support is "libasound2-dev".
  636. If you don't have the ALSA library and don't want to build Juce with audio support,
  637. just disable the JUCE_ALSA flag in juce_Config.h
  638. */
  639. #include <alsa/asoundlib.h>
  640. #endif
  641. #if JUCE_JACK
  642. /* Got an include error here? If so, you've either not got jack-audio-connection-kit
  643. installed, or you've not got your paths set up correctly to find its header files.
  644. The package you need to install to get JACK support is "libjack-dev".
  645. If you don't have the jack-audio-connection-kit library and don't want to build
  646. Juce with low latency audio support, just disable the JUCE_JACK flag in juce_Config.h
  647. */
  648. #include <jack/jack.h>
  649. //#include <jack/transport.h>
  650. #endif
  651. #undef SIZEOF
  652. #endif // __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  653. /*** End of inlined file: juce_linux_NativeIncludes.h ***/
  654. #elif JUCE_MAC || JUCE_IPHONE
  655. /*** Start of inlined file: juce_mac_NativeIncludes.h ***/
  656. #ifndef __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  657. #define __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  658. /*
  659. This file wraps together all the mac-specific code, so that
  660. we can include all the native headers just once, and compile all our
  661. platform-specific stuff in one big lump, keeping it out of the way of
  662. the rest of the codebase.
  663. */
  664. #define USE_COREGRAPHICS_RENDERING 1
  665. #if JUCE_IPHONE
  666. #import <Foundation/Foundation.h>
  667. #import <UIKit/UIKit.h>
  668. #import <AudioToolbox/AudioToolbox.h>
  669. #import <AVFoundation/AVFoundation.h>
  670. #import <CoreData/CoreData.h>
  671. #import <MobileCoreServices/MobileCoreServices.h>
  672. #import <QuartzCore/QuartzCore.h>
  673. #include <sys/fcntl.h>
  674. #if JUCE_OPENGL
  675. #include <OpenGLES/ES1/gl.h>
  676. #include <OpenGLES/ES1/glext.h>
  677. #endif
  678. #else
  679. #import <Cocoa/Cocoa.h>
  680. #import <CoreAudio/HostTime.h>
  681. #import <CoreAudio/AudioHardware.h>
  682. #import <CoreMIDI/MIDIServices.h>
  683. #import <QTKit/QTKit.h>
  684. #import <WebKit/WebKit.h>
  685. #import <DiscRecording/DiscRecording.h>
  686. #import <IOKit/IOKitLib.h>
  687. #import <IOKit/IOCFPlugIn.h>
  688. #import <IOKit/hid/IOHIDLib.h>
  689. #import <IOKit/hid/IOHIDKeys.h>
  690. #import <IOKit/pwr_mgt/IOPMLib.h>
  691. #include <Carbon/Carbon.h>
  692. #include <sys/dir.h>
  693. #endif
  694. #include <sys/socket.h>
  695. #include <sys/sysctl.h>
  696. #include <sys/stat.h>
  697. #include <sys/param.h>
  698. #include <sys/mount.h>
  699. #include <fnmatch.h>
  700. #include <utime.h>
  701. #include <dlfcn.h>
  702. #include <ifaddrs.h>
  703. #include <net/if_dl.h>
  704. #include <mach/mach_time.h>
  705. #if MACOS_10_4_OR_EARLIER
  706. #include <GLUT/glut.h>
  707. #endif
  708. #if ! CGFLOAT_DEFINED
  709. #define CGFloat float
  710. #endif
  711. #endif // __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  712. /*** End of inlined file: juce_mac_NativeIncludes.h ***/
  713. #else
  714. #error "Unknown platform!"
  715. #endif
  716. #endif
  717. //==============================================================================
  718. #define DONT_SET_USING_JUCE_NAMESPACE 1
  719. #undef max
  720. #undef min
  721. #define NO_DUMMY_DECL
  722. #if JUCE_BUILD_NATIVE
  723. #include "juce_amalgamated.h" // FORCE_AMALGAMATOR_INCLUDE
  724. #endif
  725. #if (defined(_MSC_VER) && (_MSC_VER <= 1200))
  726. #pragma warning (disable: 4309 4305)
  727. #endif
  728. #if JUCE_MAC && JUCE_32BIT && JUCE_SUPPORT_CARBON && JUCE_BUILD_NATIVE && ! JUCE_ONLY_BUILD_CORE_LIBRARY
  729. BEGIN_JUCE_NAMESPACE
  730. /*** Start of inlined file: juce_mac_CarbonViewWrapperComponent.h ***/
  731. #ifndef __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  732. #define __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  733. /**
  734. Creates a floating carbon window that can be used to hold a carbon UI.
  735. This is a handy class that's designed to be inlined where needed, e.g.
  736. in the audio plugin hosting code.
  737. */
  738. class CarbonViewWrapperComponent : public Component,
  739. public ComponentMovementWatcher,
  740. public Timer
  741. {
  742. public:
  743. CarbonViewWrapperComponent()
  744. : ComponentMovementWatcher (this),
  745. wrapperWindow (0),
  746. embeddedView (0),
  747. recursiveResize (false)
  748. {
  749. }
  750. virtual ~CarbonViewWrapperComponent()
  751. {
  752. jassert (embeddedView == 0); // must call deleteWindow() in the subclass's destructor!
  753. }
  754. virtual HIViewRef attachView (WindowRef windowRef, HIViewRef rootView) = 0;
  755. virtual void removeView (HIViewRef embeddedView) = 0;
  756. virtual void mouseDown (int, int) {}
  757. virtual void paint() {}
  758. virtual bool getEmbeddedViewSize (int& w, int& h)
  759. {
  760. if (embeddedView == 0)
  761. return false;
  762. HIRect bounds;
  763. HIViewGetBounds (embeddedView, &bounds);
  764. w = jmax (1, roundToInt (bounds.size.width));
  765. h = jmax (1, roundToInt (bounds.size.height));
  766. return true;
  767. }
  768. void createWindow()
  769. {
  770. if (wrapperWindow == 0)
  771. {
  772. Rect r;
  773. r.left = getScreenX();
  774. r.top = getScreenY();
  775. r.right = r.left + getWidth();
  776. r.bottom = r.top + getHeight();
  777. CreateNewWindow (kDocumentWindowClass,
  778. (WindowAttributes) (kWindowStandardHandlerAttribute | kWindowCompositingAttribute
  779. | kWindowNoShadowAttribute | kWindowNoTitleBarAttribute),
  780. &r, &wrapperWindow);
  781. jassert (wrapperWindow != 0);
  782. if (wrapperWindow == 0)
  783. return;
  784. NSWindow* carbonWindow = [[NSWindow alloc] initWithWindowRef: wrapperWindow];
  785. NSWindow* ownerWindow = [((NSView*) getWindowHandle()) window];
  786. [ownerWindow addChildWindow: carbonWindow
  787. ordered: NSWindowAbove];
  788. embeddedView = attachView (wrapperWindow, HIViewGetRoot (wrapperWindow));
  789. EventTypeSpec windowEventTypes[] = { { kEventClassWindow, kEventWindowGetClickActivation },
  790. { kEventClassWindow, kEventWindowHandleDeactivate } };
  791. EventHandlerUPP upp = NewEventHandlerUPP (carbonEventCallback);
  792. InstallWindowEventHandler (wrapperWindow, upp,
  793. sizeof (windowEventTypes) / sizeof (EventTypeSpec),
  794. windowEventTypes, this, &eventHandlerRef);
  795. setOurSizeToEmbeddedViewSize();
  796. setEmbeddedWindowToOurSize();
  797. creationTime = Time::getCurrentTime();
  798. }
  799. }
  800. void deleteWindow()
  801. {
  802. removeView (embeddedView);
  803. embeddedView = 0;
  804. if (wrapperWindow != 0)
  805. {
  806. RemoveEventHandler (eventHandlerRef);
  807. DisposeWindow (wrapperWindow);
  808. wrapperWindow = 0;
  809. }
  810. }
  811. void setOurSizeToEmbeddedViewSize()
  812. {
  813. int w, h;
  814. if (getEmbeddedViewSize (w, h))
  815. {
  816. if (w != getWidth() || h != getHeight())
  817. {
  818. startTimer (50);
  819. setSize (w, h);
  820. if (getParentComponent() != 0)
  821. getParentComponent()->setSize (w, h);
  822. }
  823. else
  824. {
  825. startTimer (jlimit (50, 500, getTimerInterval() + 20));
  826. }
  827. }
  828. else
  829. {
  830. stopTimer();
  831. }
  832. }
  833. void setEmbeddedWindowToOurSize()
  834. {
  835. if (! recursiveResize)
  836. {
  837. recursiveResize = true;
  838. if (embeddedView != 0)
  839. {
  840. HIRect r;
  841. r.origin.x = 0;
  842. r.origin.y = 0;
  843. r.size.width = (float) getWidth();
  844. r.size.height = (float) getHeight();
  845. HIViewSetFrame (embeddedView, &r);
  846. }
  847. if (wrapperWindow != 0)
  848. {
  849. Rect wr;
  850. wr.left = getScreenX();
  851. wr.top = getScreenY();
  852. wr.right = wr.left + getWidth();
  853. wr.bottom = wr.top + getHeight();
  854. SetWindowBounds (wrapperWindow, kWindowContentRgn, &wr);
  855. ShowWindow (wrapperWindow);
  856. }
  857. recursiveResize = false;
  858. }
  859. }
  860. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  861. {
  862. setEmbeddedWindowToOurSize();
  863. }
  864. void componentPeerChanged()
  865. {
  866. deleteWindow();
  867. createWindow();
  868. }
  869. void componentVisibilityChanged (Component&)
  870. {
  871. if (isShowing())
  872. createWindow();
  873. else
  874. deleteWindow();
  875. setEmbeddedWindowToOurSize();
  876. }
  877. static void recursiveHIViewRepaint (HIViewRef view)
  878. {
  879. HIViewSetNeedsDisplay (view, true);
  880. HIViewRef child = HIViewGetFirstSubview (view);
  881. while (child != 0)
  882. {
  883. recursiveHIViewRepaint (child);
  884. child = HIViewGetNextView (child);
  885. }
  886. }
  887. void timerCallback()
  888. {
  889. setOurSizeToEmbeddedViewSize();
  890. // To avoid strange overpainting problems when the UI is first opened, we'll
  891. // repaint it a few times during the first second that it's on-screen..
  892. if ((Time::getCurrentTime() - creationTime).inMilliseconds() < 1000)
  893. recursiveHIViewRepaint (HIViewGetRoot (wrapperWindow));
  894. }
  895. OSStatus carbonEventHandler (EventHandlerCallRef /*nextHandlerRef*/,
  896. EventRef event)
  897. {
  898. switch (GetEventKind (event))
  899. {
  900. case kEventWindowHandleDeactivate:
  901. ActivateWindow (wrapperWindow, TRUE);
  902. break;
  903. case kEventWindowGetClickActivation:
  904. {
  905. getTopLevelComponent()->toFront (false);
  906. ClickActivationResult howToHandleClick = kActivateAndHandleClick;
  907. SetEventParameter (event, kEventParamClickActivation, typeClickActivationResult,
  908. sizeof (ClickActivationResult), &howToHandleClick);
  909. HIViewSetNeedsDisplay (embeddedView, true);
  910. }
  911. break;
  912. }
  913. return noErr;
  914. }
  915. static pascal OSStatus carbonEventCallback (EventHandlerCallRef nextHandlerRef,
  916. EventRef event, void* userData)
  917. {
  918. return ((CarbonViewWrapperComponent*) userData)->carbonEventHandler (nextHandlerRef, event);
  919. }
  920. protected:
  921. WindowRef wrapperWindow;
  922. HIViewRef embeddedView;
  923. bool recursiveResize;
  924. Time creationTime;
  925. EventHandlerRef eventHandlerRef;
  926. };
  927. #endif // __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  928. /*** End of inlined file: juce_mac_CarbonViewWrapperComponent.h ***/
  929. END_JUCE_NAMESPACE
  930. #endif
  931. #define JUCE_AMALGAMATED_TEMPLATE 1
  932. //==============================================================================
  933. #if JUCE_BUILD_CORE
  934. /*** Start of inlined file: juce_FileLogger.cpp ***/
  935. BEGIN_JUCE_NAMESPACE
  936. FileLogger::FileLogger (const File& logFile_,
  937. const String& welcomeMessage,
  938. const int maxInitialFileSizeBytes)
  939. : logFile (logFile_)
  940. {
  941. if (maxInitialFileSizeBytes >= 0)
  942. trimFileSize (maxInitialFileSizeBytes);
  943. if (! logFile_.exists())
  944. {
  945. // do this so that the parent directories get created..
  946. logFile_.create();
  947. }
  948. logStream = logFile_.createOutputStream (256);
  949. jassert (logStream != 0);
  950. String welcome;
  951. welcome << "\r\n**********************************************************\r\n"
  952. << welcomeMessage
  953. << "\r\nLog started: " << Time::getCurrentTime().toString (true, true)
  954. << "\r\n";
  955. logMessage (welcome);
  956. }
  957. FileLogger::~FileLogger()
  958. {
  959. }
  960. void FileLogger::logMessage (const String& message)
  961. {
  962. if (logStream != 0)
  963. {
  964. DBG (message);
  965. const ScopedLock sl (logLock);
  966. (*logStream) << message << "\r\n";
  967. logStream->flush();
  968. }
  969. }
  970. void FileLogger::trimFileSize (int maxFileSizeBytes) const
  971. {
  972. if (maxFileSizeBytes <= 0)
  973. {
  974. logFile.deleteFile();
  975. }
  976. else
  977. {
  978. const int64 fileSize = logFile.getSize();
  979. if (fileSize > maxFileSizeBytes)
  980. {
  981. ScopedPointer <FileInputStream> in (logFile.createInputStream());
  982. jassert (in != 0);
  983. if (in != 0)
  984. {
  985. in->setPosition (fileSize - maxFileSizeBytes);
  986. String content;
  987. {
  988. MemoryBlock contentToSave;
  989. contentToSave.setSize (maxFileSizeBytes + 4);
  990. contentToSave.fillWith (0);
  991. in->read (contentToSave.getData(), maxFileSizeBytes);
  992. in = 0;
  993. content = contentToSave.toString();
  994. }
  995. int newStart = 0;
  996. while (newStart < fileSize
  997. && content[newStart] != '\n'
  998. && content[newStart] != '\r')
  999. ++newStart;
  1000. logFile.deleteFile();
  1001. logFile.appendText (content.substring (newStart), false, false);
  1002. }
  1003. }
  1004. }
  1005. }
  1006. FileLogger* FileLogger::createDefaultAppLogger (const String& logFileSubDirectoryName,
  1007. const String& logFileName,
  1008. const String& welcomeMessage,
  1009. const int maxInitialFileSizeBytes)
  1010. {
  1011. #if JUCE_MAC
  1012. File logFile ("~/Library/Logs");
  1013. logFile = logFile.getChildFile (logFileSubDirectoryName)
  1014. .getChildFile (logFileName);
  1015. #else
  1016. File logFile (File::getSpecialLocation (File::userApplicationDataDirectory));
  1017. if (logFile.isDirectory())
  1018. {
  1019. logFile = logFile.getChildFile (logFileSubDirectoryName)
  1020. .getChildFile (logFileName);
  1021. }
  1022. #endif
  1023. return new FileLogger (logFile, welcomeMessage, maxInitialFileSizeBytes);
  1024. }
  1025. END_JUCE_NAMESPACE
  1026. /*** End of inlined file: juce_FileLogger.cpp ***/
  1027. /*** Start of inlined file: juce_Logger.cpp ***/
  1028. BEGIN_JUCE_NAMESPACE
  1029. Logger::Logger()
  1030. {
  1031. }
  1032. Logger::~Logger()
  1033. {
  1034. }
  1035. static Logger* currentLogger = 0;
  1036. void Logger::setCurrentLogger (Logger* const newLogger,
  1037. const bool deleteOldLogger)
  1038. {
  1039. Logger* const oldLogger = currentLogger;
  1040. currentLogger = newLogger;
  1041. if (deleteOldLogger)
  1042. delete oldLogger;
  1043. }
  1044. void Logger::writeToLog (const String& message)
  1045. {
  1046. if (currentLogger != 0)
  1047. currentLogger->logMessage (message);
  1048. else
  1049. outputDebugString (message);
  1050. }
  1051. #if JUCE_LOG_ASSERTIONS
  1052. void JUCE_API juce_LogAssertion (const char* filename, const int lineNum) throw()
  1053. {
  1054. String m ("JUCE Assertion failure in ");
  1055. m << filename << ", line " << lineNum;
  1056. Logger::writeToLog (m);
  1057. }
  1058. #endif
  1059. END_JUCE_NAMESPACE
  1060. /*** End of inlined file: juce_Logger.cpp ***/
  1061. /*** Start of inlined file: juce_Random.cpp ***/
  1062. BEGIN_JUCE_NAMESPACE
  1063. Random::Random (const int64 seedValue) throw()
  1064. : seed (seedValue)
  1065. {
  1066. }
  1067. Random::~Random() throw()
  1068. {
  1069. }
  1070. void Random::setSeed (const int64 newSeed) throw()
  1071. {
  1072. seed = newSeed;
  1073. }
  1074. void Random::combineSeed (const int64 seedValue) throw()
  1075. {
  1076. seed ^= nextInt64() ^ seedValue;
  1077. }
  1078. void Random::setSeedRandomly()
  1079. {
  1080. combineSeed ((int64) (pointer_sized_int) this);
  1081. combineSeed (Time::getMillisecondCounter());
  1082. combineSeed (Time::getHighResolutionTicks());
  1083. combineSeed (Time::getHighResolutionTicksPerSecond());
  1084. combineSeed (Time::currentTimeMillis());
  1085. }
  1086. int Random::nextInt() throw()
  1087. {
  1088. seed = (seed * literal64bit (0x5deece66d) + 11) & literal64bit (0xffffffffffff);
  1089. return (int) (seed >> 16);
  1090. }
  1091. int Random::nextInt (const int maxValue) throw()
  1092. {
  1093. jassert (maxValue > 0);
  1094. return (nextInt() & 0x7fffffff) % maxValue;
  1095. }
  1096. int64 Random::nextInt64() throw()
  1097. {
  1098. return (((int64) nextInt()) << 32) | (int64) (uint64) (uint32) nextInt();
  1099. }
  1100. bool Random::nextBool() throw()
  1101. {
  1102. return (nextInt() & 0x80000000) != 0;
  1103. }
  1104. float Random::nextFloat() throw()
  1105. {
  1106. return static_cast <uint32> (nextInt()) / (float) 0xffffffff;
  1107. }
  1108. double Random::nextDouble() throw()
  1109. {
  1110. return static_cast <uint32> (nextInt()) / (double) 0xffffffff;
  1111. }
  1112. const BigInteger Random::nextLargeNumber (const BigInteger& maximumValue)
  1113. {
  1114. BigInteger n;
  1115. do
  1116. {
  1117. fillBitsRandomly (n, 0, maximumValue.getHighestBit() + 1);
  1118. }
  1119. while (n >= maximumValue);
  1120. return n;
  1121. }
  1122. void Random::fillBitsRandomly (BigInteger& arrayToChange, int startBit, int numBits)
  1123. {
  1124. arrayToChange.setBit (startBit + numBits - 1, true); // to force the array to pre-allocate space
  1125. while ((startBit & 31) != 0 && numBits > 0)
  1126. {
  1127. arrayToChange.setBit (startBit++, nextBool());
  1128. --numBits;
  1129. }
  1130. while (numBits >= 32)
  1131. {
  1132. arrayToChange.setBitRangeAsInt (startBit, 32, (unsigned int) nextInt());
  1133. startBit += 32;
  1134. numBits -= 32;
  1135. }
  1136. while (--numBits >= 0)
  1137. arrayToChange.setBit (startBit + numBits, nextBool());
  1138. }
  1139. Random& Random::getSystemRandom() throw()
  1140. {
  1141. static Random sysRand (1);
  1142. return sysRand;
  1143. }
  1144. END_JUCE_NAMESPACE
  1145. /*** End of inlined file: juce_Random.cpp ***/
  1146. /*** Start of inlined file: juce_RelativeTime.cpp ***/
  1147. BEGIN_JUCE_NAMESPACE
  1148. RelativeTime::RelativeTime (const double seconds_) throw()
  1149. : seconds (seconds_)
  1150. {
  1151. }
  1152. RelativeTime::RelativeTime (const RelativeTime& other) throw()
  1153. : seconds (other.seconds)
  1154. {
  1155. }
  1156. RelativeTime::~RelativeTime() throw()
  1157. {
  1158. }
  1159. const RelativeTime RelativeTime::milliseconds (const int milliseconds) throw()
  1160. {
  1161. return RelativeTime (milliseconds * 0.001);
  1162. }
  1163. const RelativeTime RelativeTime::milliseconds (const int64 milliseconds) throw()
  1164. {
  1165. return RelativeTime (milliseconds * 0.001);
  1166. }
  1167. const RelativeTime RelativeTime::minutes (const double numberOfMinutes) throw()
  1168. {
  1169. return RelativeTime (numberOfMinutes * 60.0);
  1170. }
  1171. const RelativeTime RelativeTime::hours (const double numberOfHours) throw()
  1172. {
  1173. return RelativeTime (numberOfHours * (60.0 * 60.0));
  1174. }
  1175. const RelativeTime RelativeTime::days (const double numberOfDays) throw()
  1176. {
  1177. return RelativeTime (numberOfDays * (60.0 * 60.0 * 24.0));
  1178. }
  1179. const RelativeTime RelativeTime::weeks (const double numberOfWeeks) throw()
  1180. {
  1181. return RelativeTime (numberOfWeeks * (60.0 * 60.0 * 24.0 * 7.0));
  1182. }
  1183. int64 RelativeTime::inMilliseconds() const throw()
  1184. {
  1185. return (int64)(seconds * 1000.0);
  1186. }
  1187. double RelativeTime::inMinutes() const throw()
  1188. {
  1189. return seconds / 60.0;
  1190. }
  1191. double RelativeTime::inHours() const throw()
  1192. {
  1193. return seconds / (60.0 * 60.0);
  1194. }
  1195. double RelativeTime::inDays() const throw()
  1196. {
  1197. return seconds / (60.0 * 60.0 * 24.0);
  1198. }
  1199. double RelativeTime::inWeeks() const throw()
  1200. {
  1201. return seconds / (60.0 * 60.0 * 24.0 * 7.0);
  1202. }
  1203. const String RelativeTime::getDescription (const String& returnValueForZeroTime) const throw()
  1204. {
  1205. if (seconds < 0.001 && seconds > -0.001)
  1206. return returnValueForZeroTime;
  1207. String result;
  1208. if (seconds < 0)
  1209. result = "-";
  1210. int fieldsShown = 0;
  1211. int n = abs ((int) inWeeks());
  1212. if (n > 0)
  1213. {
  1214. result << n << ((n == 1) ? TRANS(" week ")
  1215. : TRANS(" weeks "));
  1216. ++fieldsShown;
  1217. }
  1218. n = abs ((int) inDays()) % 7;
  1219. if (n > 0)
  1220. {
  1221. result << n << ((n == 1) ? TRANS(" day ")
  1222. : TRANS(" days "));
  1223. ++fieldsShown;
  1224. }
  1225. if (fieldsShown < 2)
  1226. {
  1227. n = abs ((int) inHours()) % 24;
  1228. if (n > 0)
  1229. {
  1230. result << n << ((n == 1) ? TRANS(" hr ")
  1231. : TRANS(" hrs "));
  1232. ++fieldsShown;
  1233. }
  1234. if (fieldsShown < 2)
  1235. {
  1236. n = abs ((int) inMinutes()) % 60;
  1237. if (n > 0)
  1238. {
  1239. result << n << ((n == 1) ? TRANS(" min ")
  1240. : TRANS(" mins "));
  1241. ++fieldsShown;
  1242. }
  1243. if (fieldsShown < 2)
  1244. {
  1245. n = abs ((int) inSeconds()) % 60;
  1246. if (n > 0)
  1247. {
  1248. result << n << ((n == 1) ? TRANS(" sec ")
  1249. : TRANS(" secs "));
  1250. ++fieldsShown;
  1251. }
  1252. if (fieldsShown < 1)
  1253. {
  1254. n = abs ((int) inMilliseconds()) % 1000;
  1255. if (n > 0)
  1256. {
  1257. result << n << TRANS(" ms");
  1258. ++fieldsShown;
  1259. }
  1260. }
  1261. }
  1262. }
  1263. }
  1264. return result.trimEnd();
  1265. }
  1266. RelativeTime& RelativeTime::operator= (const RelativeTime& other) throw()
  1267. {
  1268. seconds = other.seconds;
  1269. return *this;
  1270. }
  1271. bool RelativeTime::operator== (const RelativeTime& other) const throw()
  1272. {
  1273. return seconds == other.seconds;
  1274. }
  1275. bool RelativeTime::operator!= (const RelativeTime& other) const throw()
  1276. {
  1277. return seconds != other.seconds;
  1278. }
  1279. bool RelativeTime::operator> (const RelativeTime& other) const throw()
  1280. {
  1281. return seconds > other.seconds;
  1282. }
  1283. bool RelativeTime::operator< (const RelativeTime& other) const throw()
  1284. {
  1285. return seconds < other.seconds;
  1286. }
  1287. bool RelativeTime::operator>= (const RelativeTime& other) const throw()
  1288. {
  1289. return seconds >= other.seconds;
  1290. }
  1291. bool RelativeTime::operator<= (const RelativeTime& other) const throw()
  1292. {
  1293. return seconds <= other.seconds;
  1294. }
  1295. const RelativeTime RelativeTime::operator+ (const RelativeTime& timeToAdd) const throw()
  1296. {
  1297. return RelativeTime (seconds + timeToAdd.seconds);
  1298. }
  1299. const RelativeTime RelativeTime::operator- (const RelativeTime& timeToSubtract) const throw()
  1300. {
  1301. return RelativeTime (seconds - timeToSubtract.seconds);
  1302. }
  1303. const RelativeTime RelativeTime::operator+ (const double secondsToAdd) const throw()
  1304. {
  1305. return RelativeTime (seconds + secondsToAdd);
  1306. }
  1307. const RelativeTime RelativeTime::operator- (const double secondsToSubtract) const throw()
  1308. {
  1309. return RelativeTime (seconds - secondsToSubtract);
  1310. }
  1311. const RelativeTime& RelativeTime::operator+= (const RelativeTime& timeToAdd) throw()
  1312. {
  1313. seconds += timeToAdd.seconds;
  1314. return *this;
  1315. }
  1316. const RelativeTime& RelativeTime::operator-= (const RelativeTime& timeToSubtract) throw()
  1317. {
  1318. seconds -= timeToSubtract.seconds;
  1319. return *this;
  1320. }
  1321. const RelativeTime& RelativeTime::operator+= (const double secondsToAdd) throw()
  1322. {
  1323. seconds += secondsToAdd;
  1324. return *this;
  1325. }
  1326. const RelativeTime& RelativeTime::operator-= (const double secondsToSubtract) throw()
  1327. {
  1328. seconds -= secondsToSubtract;
  1329. return *this;
  1330. }
  1331. END_JUCE_NAMESPACE
  1332. /*** End of inlined file: juce_RelativeTime.cpp ***/
  1333. /*** Start of inlined file: juce_SystemStats.cpp ***/
  1334. BEGIN_JUCE_NAMESPACE
  1335. const String SystemStats::getJUCEVersion()
  1336. {
  1337. return "JUCE v" + String (JUCE_MAJOR_VERSION)
  1338. + "." + String (JUCE_MINOR_VERSION)
  1339. + "." + String (JUCE_BUILDNUMBER);
  1340. }
  1341. const StringArray SystemStats::getMACAddressStrings()
  1342. {
  1343. int64 macAddresses [16];
  1344. const int numAddresses = getMACAddresses (macAddresses, numElementsInArray (macAddresses), false);
  1345. StringArray s;
  1346. for (int i = 0; i < numAddresses; ++i)
  1347. {
  1348. s.add (String::toHexString (0xff & (int) (macAddresses [i] >> 40)).paddedLeft ('0', 2)
  1349. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 32)).paddedLeft ('0', 2)
  1350. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 24)).paddedLeft ('0', 2)
  1351. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 16)).paddedLeft ('0', 2)
  1352. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 8)).paddedLeft ('0', 2)
  1353. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 0)).paddedLeft ('0', 2));
  1354. }
  1355. return s;
  1356. }
  1357. static bool juceInitialisedNonGUI = false;
  1358. #if JUCE_DEBUG
  1359. template <typename Type>
  1360. static void juce_testAtomicType (Type)
  1361. {
  1362. Atomic<Type> a, b;
  1363. a.set ((Type) 10);
  1364. a += (Type) 15;
  1365. a.memoryBarrier();
  1366. a -= (Type) 5;
  1367. ++a;
  1368. ++a;
  1369. --a;
  1370. a.memoryBarrier();
  1371. /* These are some simple test cases to check the atomics - let me know
  1372. if any of these assertions fail on your system!
  1373. */
  1374. jassert (a.get() == (Type) 21);
  1375. jassert (a.compareAndSetValue ((Type) 100, (Type) 50) == (Type) 21);
  1376. jassert (a.get() == (Type) 21);
  1377. jassert (a.compareAndSetValue ((Type) 101, a.get()) == (Type) 21);
  1378. jassert (a.get() == (Type) 101);
  1379. jassert (! a.compareAndSetBool ((Type) 300, (Type) 200));
  1380. jassert (a.get() == (Type) 101);
  1381. jassert (a.compareAndSetBool ((Type) 200, a.get()));
  1382. jassert (a.get() == (Type) 200);
  1383. jassert (a.exchange ((Type) 300) == (Type) 200);
  1384. jassert (a.get() == (Type) 300);
  1385. b = a;
  1386. jassert (b.get() == a.get());
  1387. }
  1388. static void juce_testAtomics()
  1389. {
  1390. juce_testAtomicType ((int) 0);
  1391. juce_testAtomicType ((unsigned int) 0);
  1392. juce_testAtomicType ((int32) 0);
  1393. juce_testAtomicType ((uint32) 0);
  1394. juce_testAtomicType ((long) 0);
  1395. juce_testAtomicType ((void*) 0);
  1396. juce_testAtomicType ((int*) 0);
  1397. #if ! JUCE_64BIT_ATOMICS_UNAVAILABLE // 64-bit intrinsics aren't available on some old platforms
  1398. juce_testAtomicType ((int64) 0);
  1399. juce_testAtomicType ((uint64) 0);
  1400. #endif
  1401. }
  1402. #endif
  1403. void JUCE_PUBLIC_FUNCTION initialiseJuce_NonGUI()
  1404. {
  1405. if (! juceInitialisedNonGUI)
  1406. {
  1407. #if JUCE_MAC || JUCE_IPHONE
  1408. const ScopedAutoReleasePool pool;
  1409. #endif
  1410. #if JUCE_DEBUG
  1411. {
  1412. // Some simple test code to keep an eye on things and make sure these functions
  1413. // work ok on all platforms. Let me know if any of these assertions fail!
  1414. static_jassert (sizeof (pointer_sized_int) == sizeof (void*));
  1415. static_jassert (sizeof (int8) == 1);
  1416. static_jassert (sizeof (uint8) == 1);
  1417. static_jassert (sizeof (int16) == 2);
  1418. static_jassert (sizeof (uint16) == 2);
  1419. static_jassert (sizeof (int32) == 4);
  1420. static_jassert (sizeof (uint32) == 4);
  1421. static_jassert (sizeof (int64) == 8);
  1422. static_jassert (sizeof (uint64) == 8);
  1423. char a1[7];
  1424. jassert (numElementsInArray(a1) == 7);
  1425. int a2[3];
  1426. jassert (numElementsInArray(a2) == 3);
  1427. juce_testAtomics();
  1428. jassert (ByteOrder::swap ((uint16) 0x1122) == 0x2211);
  1429. jassert (ByteOrder::swap ((uint32) 0x11223344) == 0x44332211);
  1430. // Some quick stream tests..
  1431. int randomInt = Random::getSystemRandom().nextInt();
  1432. int64 randomInt64 = Random::getSystemRandom().nextInt64();
  1433. double randomDouble = Random::getSystemRandom().nextDouble();
  1434. String randomString;
  1435. for (int i = 50; --i >= 0;)
  1436. randomString << (juce_wchar) (Random::getSystemRandom().nextInt() & 0xffff);
  1437. MemoryOutputStream mo;
  1438. mo.writeInt (randomInt);
  1439. mo.writeIntBigEndian (randomInt);
  1440. mo.writeCompressedInt (randomInt);
  1441. mo.writeString (randomString);
  1442. mo.writeInt64 (randomInt64);
  1443. mo.writeInt64BigEndian (randomInt64);
  1444. mo.writeDouble (randomDouble);
  1445. mo.writeDoubleBigEndian (randomDouble);
  1446. MemoryInputStream mi (mo.getData(), mo.getDataSize(), false);
  1447. jassert (mi.readInt() == randomInt);
  1448. jassert (mi.readIntBigEndian() == randomInt);
  1449. jassert (mi.readCompressedInt() == randomInt);
  1450. jassert (mi.readString() == randomString);
  1451. jassert (mi.readInt64() == randomInt64);
  1452. jassert (mi.readInt64BigEndian() == randomInt64);
  1453. jassert (mi.readDouble() == randomDouble);
  1454. jassert (mi.readDoubleBigEndian() == randomDouble);
  1455. }
  1456. #endif
  1457. // Now the real initialisation..
  1458. juceInitialisedNonGUI = true;
  1459. DBG (SystemStats::getJUCEVersion());
  1460. SystemStats::initialiseStats();
  1461. Random::getSystemRandom().setSeedRandomly(); // (mustn't call this before initialiseStats() because it relies on the time being set up)
  1462. }
  1463. }
  1464. #if JUCE_WINDOWS
  1465. // This is imported from the sockets code..
  1466. typedef int (__stdcall juce_CloseWin32SocketLibCall) (void);
  1467. extern juce_CloseWin32SocketLibCall* juce_CloseWin32SocketLib;
  1468. #endif
  1469. #if JUCE_DEBUG
  1470. extern void juce_CheckForDanglingStreams();
  1471. #endif
  1472. void JUCE_PUBLIC_FUNCTION shutdownJuce_NonGUI()
  1473. {
  1474. if (juceInitialisedNonGUI)
  1475. {
  1476. #if JUCE_MAC || JUCE_IPHONE
  1477. const ScopedAutoReleasePool pool;
  1478. #endif
  1479. #if JUCE_WINDOWS
  1480. // need to shut down sockets if they were used..
  1481. if (juce_CloseWin32SocketLib != 0)
  1482. (*juce_CloseWin32SocketLib)();
  1483. #endif
  1484. LocalisedStrings::setCurrentMappings (0);
  1485. Thread::stopAllThreads (3000);
  1486. #if JUCE_DEBUG
  1487. juce_CheckForDanglingStreams();
  1488. #endif
  1489. juceInitialisedNonGUI = false;
  1490. }
  1491. }
  1492. #ifdef JUCE_DLL
  1493. void* juce_Malloc (const int size)
  1494. {
  1495. return malloc (size);
  1496. }
  1497. void* juce_Calloc (const int size)
  1498. {
  1499. return calloc (1, size);
  1500. }
  1501. void* juce_Realloc (void* const block, const int size)
  1502. {
  1503. return realloc (block, size);
  1504. }
  1505. void juce_Free (void* const block)
  1506. {
  1507. free (block);
  1508. }
  1509. #if JUCE_DEBUG && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  1510. void* juce_DebugMalloc (const int size, const char* file, const int line)
  1511. {
  1512. return _malloc_dbg (size, _NORMAL_BLOCK, file, line);
  1513. }
  1514. void* juce_DebugCalloc (const int size, const char* file, const int line)
  1515. {
  1516. return _calloc_dbg (1, size, _NORMAL_BLOCK, file, line);
  1517. }
  1518. void* juce_DebugRealloc (void* const block, const int size, const char* file, const int line)
  1519. {
  1520. return _realloc_dbg (block, size, _NORMAL_BLOCK, file, line);
  1521. }
  1522. void juce_DebugFree (void* const block)
  1523. {
  1524. _free_dbg (block, _NORMAL_BLOCK);
  1525. }
  1526. #endif
  1527. #endif
  1528. END_JUCE_NAMESPACE
  1529. /*** End of inlined file: juce_SystemStats.cpp ***/
  1530. /*** Start of inlined file: juce_Time.cpp ***/
  1531. #if JUCE_MSVC
  1532. #pragma warning (push)
  1533. #pragma warning (disable: 4514)
  1534. #endif
  1535. #ifndef JUCE_WINDOWS
  1536. #include <sys/time.h>
  1537. #else
  1538. #include <ctime>
  1539. #endif
  1540. #include <sys/timeb.h>
  1541. #if JUCE_MSVC
  1542. #pragma warning (pop)
  1543. #ifdef _INC_TIME_INL
  1544. #define USE_NEW_SECURE_TIME_FNS
  1545. #endif
  1546. #endif
  1547. BEGIN_JUCE_NAMESPACE
  1548. namespace TimeHelpers
  1549. {
  1550. static struct tm millisToLocal (const int64 millis) throw()
  1551. {
  1552. struct tm result;
  1553. const int64 seconds = millis / 1000;
  1554. if (seconds < literal64bit (86400) || seconds >= literal64bit (2145916800))
  1555. {
  1556. // use extended maths for dates beyond 1970 to 2037..
  1557. const int timeZoneAdjustment = 31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000);
  1558. const int64 jdm = seconds + timeZoneAdjustment + literal64bit (210866803200);
  1559. const int days = (int) (jdm / literal64bit (86400));
  1560. const int a = 32044 + days;
  1561. const int b = (4 * a + 3) / 146097;
  1562. const int c = a - (b * 146097) / 4;
  1563. const int d = (4 * c + 3) / 1461;
  1564. const int e = c - (d * 1461) / 4;
  1565. const int m = (5 * e + 2) / 153;
  1566. result.tm_mday = e - (153 * m + 2) / 5 + 1;
  1567. result.tm_mon = m + 2 - 12 * (m / 10);
  1568. result.tm_year = b * 100 + d - 6700 + (m / 10);
  1569. result.tm_wday = (days + 1) % 7;
  1570. result.tm_yday = -1;
  1571. int t = (int) (jdm % literal64bit (86400));
  1572. result.tm_hour = t / 3600;
  1573. t %= 3600;
  1574. result.tm_min = t / 60;
  1575. result.tm_sec = t % 60;
  1576. result.tm_isdst = -1;
  1577. }
  1578. else
  1579. {
  1580. time_t now = static_cast <time_t> (seconds);
  1581. #if JUCE_WINDOWS
  1582. #ifdef USE_NEW_SECURE_TIME_FNS
  1583. if (now >= 0 && now <= 0x793406fff)
  1584. localtime_s (&result, &now);
  1585. else
  1586. zeromem (&result, sizeof (result));
  1587. #else
  1588. result = *localtime (&now);
  1589. #endif
  1590. #else
  1591. // more thread-safe
  1592. localtime_r (&now, &result);
  1593. #endif
  1594. }
  1595. return result;
  1596. }
  1597. static int extendedModulo (const int64 value, const int modulo) throw()
  1598. {
  1599. return (int) (value >= 0 ? (value % modulo)
  1600. : (value - ((value / modulo) + 1) * modulo));
  1601. }
  1602. static uint32 lastMSCounterValue = 0;
  1603. }
  1604. Time::Time() throw()
  1605. : millisSinceEpoch (0)
  1606. {
  1607. }
  1608. Time::Time (const Time& other) throw()
  1609. : millisSinceEpoch (other.millisSinceEpoch)
  1610. {
  1611. }
  1612. Time::Time (const int64 ms) throw()
  1613. : millisSinceEpoch (ms)
  1614. {
  1615. }
  1616. Time::Time (const int year,
  1617. const int month,
  1618. const int day,
  1619. const int hours,
  1620. const int minutes,
  1621. const int seconds,
  1622. const int milliseconds,
  1623. const bool useLocalTime) throw()
  1624. {
  1625. jassert (year > 100); // year must be a 4-digit version
  1626. if (year < 1971 || year >= 2038 || ! useLocalTime)
  1627. {
  1628. // use extended maths for dates beyond 1970 to 2037..
  1629. const int timeZoneAdjustment = useLocalTime ? (31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000))
  1630. : 0;
  1631. const int a = (13 - month) / 12;
  1632. const int y = year + 4800 - a;
  1633. const int jd = day + (153 * (month + 12 * a - 2) + 2) / 5
  1634. + (y * 365) + (y / 4) - (y / 100) + (y / 400)
  1635. - 32045;
  1636. const int64 s = ((int64) jd) * literal64bit (86400) - literal64bit (210866803200);
  1637. millisSinceEpoch = 1000 * (s + (hours * 3600 + minutes * 60 + seconds - timeZoneAdjustment))
  1638. + milliseconds;
  1639. }
  1640. else
  1641. {
  1642. struct tm t;
  1643. t.tm_year = year - 1900;
  1644. t.tm_mon = month;
  1645. t.tm_mday = day;
  1646. t.tm_hour = hours;
  1647. t.tm_min = minutes;
  1648. t.tm_sec = seconds;
  1649. t.tm_isdst = -1;
  1650. millisSinceEpoch = 1000 * (int64) mktime (&t);
  1651. if (millisSinceEpoch < 0)
  1652. millisSinceEpoch = 0;
  1653. else
  1654. millisSinceEpoch += milliseconds;
  1655. }
  1656. }
  1657. Time::~Time() throw()
  1658. {
  1659. }
  1660. Time& Time::operator= (const Time& other) throw()
  1661. {
  1662. millisSinceEpoch = other.millisSinceEpoch;
  1663. return *this;
  1664. }
  1665. int64 Time::currentTimeMillis() throw()
  1666. {
  1667. static uint32 lastCounterResult = 0xffffffff;
  1668. static int64 correction = 0;
  1669. const uint32 now = getMillisecondCounter();
  1670. // check the counter hasn't wrapped (also triggered the first time this function is called)
  1671. if (now < lastCounterResult)
  1672. {
  1673. // double-check it's actually wrapped, in case multi-cpu machines have timers that drift a bit.
  1674. if (lastCounterResult == 0xffffffff || now < lastCounterResult - 10)
  1675. {
  1676. // get the time once using normal library calls, and store the difference needed to
  1677. // turn the millisecond counter into a real time.
  1678. #if JUCE_WINDOWS
  1679. struct _timeb t;
  1680. #ifdef USE_NEW_SECURE_TIME_FNS
  1681. _ftime_s (&t);
  1682. #else
  1683. _ftime (&t);
  1684. #endif
  1685. correction = (((int64) t.time) * 1000 + t.millitm) - now;
  1686. #else
  1687. struct timeval tv;
  1688. struct timezone tz;
  1689. gettimeofday (&tv, &tz);
  1690. correction = (((int64) tv.tv_sec) * 1000 + tv.tv_usec / 1000) - now;
  1691. #endif
  1692. }
  1693. }
  1694. lastCounterResult = now;
  1695. return correction + now;
  1696. }
  1697. uint32 juce_millisecondsSinceStartup() throw();
  1698. uint32 Time::getMillisecondCounter() throw()
  1699. {
  1700. const uint32 now = juce_millisecondsSinceStartup();
  1701. if (now < TimeHelpers::lastMSCounterValue)
  1702. {
  1703. // in multi-threaded apps this might be called concurrently, so
  1704. // make sure that our last counter value only increases and doesn't
  1705. // go backwards..
  1706. if (now < TimeHelpers::lastMSCounterValue - 1000)
  1707. TimeHelpers::lastMSCounterValue = now;
  1708. }
  1709. else
  1710. {
  1711. TimeHelpers::lastMSCounterValue = now;
  1712. }
  1713. return now;
  1714. }
  1715. uint32 Time::getApproximateMillisecondCounter() throw()
  1716. {
  1717. jassert (TimeHelpers::lastMSCounterValue != 0);
  1718. return TimeHelpers::lastMSCounterValue;
  1719. }
  1720. void Time::waitForMillisecondCounter (const uint32 targetTime) throw()
  1721. {
  1722. for (;;)
  1723. {
  1724. const uint32 now = getMillisecondCounter();
  1725. if (now >= targetTime)
  1726. break;
  1727. const int toWait = targetTime - now;
  1728. if (toWait > 2)
  1729. {
  1730. Thread::sleep (jmin (20, toWait >> 1));
  1731. }
  1732. else
  1733. {
  1734. // xxx should consider using mutex_pause on the mac as it apparently
  1735. // makes it seem less like a spinlock and avoids lowering the thread pri.
  1736. for (int i = 10; --i >= 0;)
  1737. Thread::yield();
  1738. }
  1739. }
  1740. }
  1741. double Time::highResolutionTicksToSeconds (const int64 ticks) throw()
  1742. {
  1743. return ticks / (double) getHighResolutionTicksPerSecond();
  1744. }
  1745. int64 Time::secondsToHighResolutionTicks (const double seconds) throw()
  1746. {
  1747. return (int64) (seconds * (double) getHighResolutionTicksPerSecond());
  1748. }
  1749. const Time JUCE_CALLTYPE Time::getCurrentTime() throw()
  1750. {
  1751. return Time (currentTimeMillis());
  1752. }
  1753. const String Time::toString (const bool includeDate,
  1754. const bool includeTime,
  1755. const bool includeSeconds,
  1756. const bool use24HourClock) const throw()
  1757. {
  1758. String result;
  1759. if (includeDate)
  1760. {
  1761. result << getDayOfMonth() << ' '
  1762. << getMonthName (true) << ' '
  1763. << getYear();
  1764. if (includeTime)
  1765. result << ' ';
  1766. }
  1767. if (includeTime)
  1768. {
  1769. const int mins = getMinutes();
  1770. result << (use24HourClock ? getHours() : getHoursInAmPmFormat())
  1771. << (mins < 10 ? ":0" : ":") << mins;
  1772. if (includeSeconds)
  1773. {
  1774. const int secs = getSeconds();
  1775. result << (secs < 10 ? ":0" : ":") << secs;
  1776. }
  1777. if (! use24HourClock)
  1778. result << (isAfternoon() ? "pm" : "am");
  1779. }
  1780. return result.trimEnd();
  1781. }
  1782. const String Time::formatted (const String& format) const throw()
  1783. {
  1784. String buffer;
  1785. int bufferSize = 128;
  1786. buffer.preallocateStorage (bufferSize);
  1787. struct tm t (TimeHelpers::millisToLocal (millisSinceEpoch));
  1788. while (CharacterFunctions::ftime (static_cast <juce_wchar*> (buffer), bufferSize, format, &t) <= 0)
  1789. {
  1790. bufferSize += 128;
  1791. buffer.preallocateStorage (bufferSize);
  1792. }
  1793. return buffer;
  1794. }
  1795. int Time::getYear() const throw()
  1796. {
  1797. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_year + 1900;
  1798. }
  1799. int Time::getMonth() const throw()
  1800. {
  1801. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_mon;
  1802. }
  1803. int Time::getDayOfMonth() const throw()
  1804. {
  1805. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_mday;
  1806. }
  1807. int Time::getDayOfWeek() const throw()
  1808. {
  1809. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_wday;
  1810. }
  1811. int Time::getHours() const throw()
  1812. {
  1813. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_hour;
  1814. }
  1815. int Time::getHoursInAmPmFormat() const throw()
  1816. {
  1817. const int hours = getHours();
  1818. if (hours == 0)
  1819. return 12;
  1820. else if (hours <= 12)
  1821. return hours;
  1822. else
  1823. return hours - 12;
  1824. }
  1825. bool Time::isAfternoon() const throw()
  1826. {
  1827. return getHours() >= 12;
  1828. }
  1829. int Time::getMinutes() const throw()
  1830. {
  1831. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_min;
  1832. }
  1833. int Time::getSeconds() const throw()
  1834. {
  1835. return TimeHelpers::extendedModulo (millisSinceEpoch / 1000, 60);
  1836. }
  1837. int Time::getMilliseconds() const throw()
  1838. {
  1839. return TimeHelpers::extendedModulo (millisSinceEpoch, 1000);
  1840. }
  1841. bool Time::isDaylightSavingTime() const throw()
  1842. {
  1843. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_isdst != 0;
  1844. }
  1845. const String Time::getTimeZone() const throw()
  1846. {
  1847. String zone[2];
  1848. #if JUCE_WINDOWS
  1849. _tzset();
  1850. #ifdef USE_NEW_SECURE_TIME_FNS
  1851. {
  1852. char name [128];
  1853. size_t length;
  1854. for (int i = 0; i < 2; ++i)
  1855. {
  1856. zeromem (name, sizeof (name));
  1857. _get_tzname (&length, name, 127, i);
  1858. zone[i] = name;
  1859. }
  1860. }
  1861. #else
  1862. const char** const zonePtr = (const char**) _tzname;
  1863. zone[0] = zonePtr[0];
  1864. zone[1] = zonePtr[1];
  1865. #endif
  1866. #else
  1867. tzset();
  1868. const char** const zonePtr = (const char**) tzname;
  1869. zone[0] = zonePtr[0];
  1870. zone[1] = zonePtr[1];
  1871. #endif
  1872. if (isDaylightSavingTime())
  1873. {
  1874. zone[0] = zone[1];
  1875. if (zone[0].length() > 3
  1876. && zone[0].containsIgnoreCase ("daylight")
  1877. && zone[0].contains ("GMT"))
  1878. zone[0] = "BST";
  1879. }
  1880. return zone[0].substring (0, 3);
  1881. }
  1882. const String Time::getMonthName (const bool threeLetterVersion) const throw()
  1883. {
  1884. return getMonthName (getMonth(), threeLetterVersion);
  1885. }
  1886. const String Time::getWeekdayName (const bool threeLetterVersion) const throw()
  1887. {
  1888. return getWeekdayName (getDayOfWeek(), threeLetterVersion);
  1889. }
  1890. const String Time::getMonthName (int monthNumber, const bool threeLetterVersion) throw()
  1891. {
  1892. const char* const shortMonthNames[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  1893. const char* const longMonthNames[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
  1894. monthNumber %= 12;
  1895. return TRANS (threeLetterVersion ? shortMonthNames [monthNumber]
  1896. : longMonthNames [monthNumber]);
  1897. }
  1898. const String Time::getWeekdayName (int day, const bool threeLetterVersion) throw()
  1899. {
  1900. const char* const shortDayNames[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
  1901. const char* const longDayNames[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
  1902. day %= 7;
  1903. return TRANS (threeLetterVersion ? shortDayNames [day]
  1904. : longDayNames [day]);
  1905. }
  1906. END_JUCE_NAMESPACE
  1907. /*** End of inlined file: juce_Time.cpp ***/
  1908. /*** Start of inlined file: juce_BigInteger.cpp ***/
  1909. BEGIN_JUCE_NAMESPACE
  1910. BigInteger::BigInteger()
  1911. : numValues (4),
  1912. highestBit (-1),
  1913. negative (false)
  1914. {
  1915. values.calloc (numValues + 1);
  1916. }
  1917. BigInteger::BigInteger (const int value)
  1918. : numValues (4),
  1919. highestBit (31),
  1920. negative (value < 0)
  1921. {
  1922. values.calloc (numValues + 1);
  1923. values[0] = abs (value);
  1924. highestBit = getHighestBit();
  1925. }
  1926. BigInteger::BigInteger (int64 value)
  1927. : numValues (4),
  1928. highestBit (63),
  1929. negative (value < 0)
  1930. {
  1931. values.calloc (numValues + 1);
  1932. if (value < 0)
  1933. value = -value;
  1934. values[0] = (unsigned int) value;
  1935. values[1] = (unsigned int) (value >> 32);
  1936. highestBit = getHighestBit();
  1937. }
  1938. BigInteger::BigInteger (const unsigned int value)
  1939. : numValues (4),
  1940. highestBit (31),
  1941. negative (false)
  1942. {
  1943. values.calloc (numValues + 1);
  1944. values[0] = value;
  1945. highestBit = getHighestBit();
  1946. }
  1947. BigInteger::BigInteger (const BigInteger& other)
  1948. : numValues (jmax (4, (other.highestBit >> 5) + 1)),
  1949. highestBit (other.getHighestBit()),
  1950. negative (other.negative)
  1951. {
  1952. values.malloc (numValues + 1);
  1953. memcpy (values, other.values, sizeof (unsigned int) * (numValues + 1));
  1954. }
  1955. BigInteger::~BigInteger()
  1956. {
  1957. }
  1958. void BigInteger::swapWith (BigInteger& other) throw()
  1959. {
  1960. values.swapWith (other.values);
  1961. swapVariables (numValues, other.numValues);
  1962. swapVariables (highestBit, other.highestBit);
  1963. swapVariables (negative, other.negative);
  1964. }
  1965. BigInteger& BigInteger::operator= (const BigInteger& other)
  1966. {
  1967. if (this != &other)
  1968. {
  1969. highestBit = other.getHighestBit();
  1970. numValues = jmax (4, (highestBit >> 5) + 1);
  1971. negative = other.negative;
  1972. values.malloc (numValues + 1);
  1973. memcpy (values, other.values, sizeof (unsigned int) * (numValues + 1));
  1974. }
  1975. return *this;
  1976. }
  1977. void BigInteger::ensureSize (const int numVals)
  1978. {
  1979. if (numVals + 2 >= numValues)
  1980. {
  1981. int oldSize = numValues;
  1982. numValues = ((numVals + 2) * 3) / 2;
  1983. values.realloc (numValues + 1);
  1984. while (oldSize < numValues)
  1985. values [oldSize++] = 0;
  1986. }
  1987. }
  1988. bool BigInteger::operator[] (const int bit) const throw()
  1989. {
  1990. return bit <= highestBit && bit >= 0
  1991. && ((values [bit >> 5] & (1 << (bit & 31))) != 0);
  1992. }
  1993. int BigInteger::toInteger() const throw()
  1994. {
  1995. const int n = (int) (values[0] & 0x7fffffff);
  1996. return negative ? -n : n;
  1997. }
  1998. const BigInteger BigInteger::getBitRange (int startBit, int numBits) const
  1999. {
  2000. BigInteger r;
  2001. numBits = jmin (numBits, getHighestBit() + 1 - startBit);
  2002. r.ensureSize (numBits >> 5);
  2003. r.highestBit = numBits;
  2004. int i = 0;
  2005. while (numBits > 0)
  2006. {
  2007. r.values[i++] = getBitRangeAsInt (startBit, jmin (32, numBits));
  2008. numBits -= 32;
  2009. startBit += 32;
  2010. }
  2011. r.highestBit = r.getHighestBit();
  2012. return r;
  2013. }
  2014. int BigInteger::getBitRangeAsInt (const int startBit, int numBits) const throw()
  2015. {
  2016. if (numBits > 32)
  2017. {
  2018. jassertfalse; // use getBitRange() if you need more than 32 bits..
  2019. numBits = 32;
  2020. }
  2021. numBits = jmin (numBits, highestBit + 1 - startBit);
  2022. if (numBits <= 0)
  2023. return 0;
  2024. const int pos = startBit >> 5;
  2025. const int offset = startBit & 31;
  2026. const int endSpace = 32 - numBits;
  2027. uint32 n = ((uint32) values [pos]) >> offset;
  2028. if (offset > endSpace)
  2029. n |= ((uint32) values [pos + 1]) << (32 - offset);
  2030. return (int) (n & (((uint32) 0xffffffff) >> endSpace));
  2031. }
  2032. void BigInteger::setBitRangeAsInt (const int startBit, int numBits, unsigned int valueToSet)
  2033. {
  2034. if (numBits > 32)
  2035. {
  2036. jassertfalse;
  2037. numBits = 32;
  2038. }
  2039. for (int i = 0; i < numBits; ++i)
  2040. {
  2041. setBit (startBit + i, (valueToSet & 1) != 0);
  2042. valueToSet >>= 1;
  2043. }
  2044. }
  2045. void BigInteger::clear()
  2046. {
  2047. if (numValues > 16)
  2048. {
  2049. numValues = 4;
  2050. values.calloc (numValues + 1);
  2051. }
  2052. else
  2053. {
  2054. zeromem (values, sizeof (unsigned int) * (numValues + 1));
  2055. }
  2056. highestBit = -1;
  2057. negative = false;
  2058. }
  2059. void BigInteger::setBit (const int bit)
  2060. {
  2061. if (bit >= 0)
  2062. {
  2063. if (bit > highestBit)
  2064. {
  2065. ensureSize (bit >> 5);
  2066. highestBit = bit;
  2067. }
  2068. values [bit >> 5] |= (1 << (bit & 31));
  2069. }
  2070. }
  2071. void BigInteger::setBit (const int bit, const bool shouldBeSet)
  2072. {
  2073. if (shouldBeSet)
  2074. setBit (bit);
  2075. else
  2076. clearBit (bit);
  2077. }
  2078. void BigInteger::clearBit (const int bit) throw()
  2079. {
  2080. if (bit >= 0 && bit <= highestBit)
  2081. values [bit >> 5] &= ~(1 << (bit & 31));
  2082. }
  2083. void BigInteger::setRange (int startBit, int numBits, const bool shouldBeSet)
  2084. {
  2085. while (--numBits >= 0)
  2086. setBit (startBit++, shouldBeSet);
  2087. }
  2088. void BigInteger::insertBit (const int bit, const bool shouldBeSet)
  2089. {
  2090. if (bit >= 0)
  2091. shiftBits (1, bit);
  2092. setBit (bit, shouldBeSet);
  2093. }
  2094. bool BigInteger::isZero() const throw()
  2095. {
  2096. return getHighestBit() < 0;
  2097. }
  2098. bool BigInteger::isOne() const throw()
  2099. {
  2100. return getHighestBit() == 0 && ! negative;
  2101. }
  2102. bool BigInteger::isNegative() const throw()
  2103. {
  2104. return negative && ! isZero();
  2105. }
  2106. void BigInteger::setNegative (const bool neg) throw()
  2107. {
  2108. negative = neg;
  2109. }
  2110. void BigInteger::negate() throw()
  2111. {
  2112. negative = (! negative) && ! isZero();
  2113. }
  2114. int BigInteger::countNumberOfSetBits() const throw()
  2115. {
  2116. int total = 0;
  2117. for (int i = (highestBit >> 5) + 1; --i >= 0;)
  2118. {
  2119. unsigned int n = values[i];
  2120. if (n == 0xffffffff)
  2121. {
  2122. total += 32;
  2123. }
  2124. else
  2125. {
  2126. while (n != 0)
  2127. {
  2128. total += (n & 1);
  2129. n >>= 1;
  2130. }
  2131. }
  2132. }
  2133. return total;
  2134. }
  2135. int BigInteger::getHighestBit() const throw()
  2136. {
  2137. for (int i = highestBit + 1; --i >= 0;)
  2138. if ((values [i >> 5] & (1 << (i & 31))) != 0)
  2139. return i;
  2140. return -1;
  2141. }
  2142. int BigInteger::findNextSetBit (int i) const throw()
  2143. {
  2144. for (; i <= highestBit; ++i)
  2145. if ((values [i >> 5] & (1 << (i & 31))) != 0)
  2146. return i;
  2147. return -1;
  2148. }
  2149. int BigInteger::findNextClearBit (int i) const throw()
  2150. {
  2151. for (; i <= highestBit; ++i)
  2152. if ((values [i >> 5] & (1 << (i & 31))) == 0)
  2153. break;
  2154. return i;
  2155. }
  2156. BigInteger& BigInteger::operator+= (const BigInteger& other)
  2157. {
  2158. if (other.isNegative())
  2159. return operator-= (-other);
  2160. if (isNegative())
  2161. {
  2162. if (compareAbsolute (other) < 0)
  2163. {
  2164. BigInteger temp (*this);
  2165. temp.negate();
  2166. *this = other;
  2167. operator-= (temp);
  2168. }
  2169. else
  2170. {
  2171. negate();
  2172. operator-= (other);
  2173. negate();
  2174. }
  2175. }
  2176. else
  2177. {
  2178. if (other.highestBit > highestBit)
  2179. highestBit = other.highestBit;
  2180. ++highestBit;
  2181. const int numInts = (highestBit >> 5) + 1;
  2182. ensureSize (numInts);
  2183. int64 remainder = 0;
  2184. for (int i = 0; i <= numInts; ++i)
  2185. {
  2186. if (i < numValues)
  2187. remainder += values[i];
  2188. if (i < other.numValues)
  2189. remainder += other.values[i];
  2190. values[i] = (unsigned int) remainder;
  2191. remainder >>= 32;
  2192. }
  2193. jassert (remainder == 0);
  2194. highestBit = getHighestBit();
  2195. }
  2196. return *this;
  2197. }
  2198. BigInteger& BigInteger::operator-= (const BigInteger& other)
  2199. {
  2200. if (other.isNegative())
  2201. return operator+= (-other);
  2202. if (! isNegative())
  2203. {
  2204. if (compareAbsolute (other) < 0)
  2205. {
  2206. BigInteger temp (other);
  2207. swapWith (temp);
  2208. operator-= (temp);
  2209. negate();
  2210. return *this;
  2211. }
  2212. }
  2213. else
  2214. {
  2215. negate();
  2216. operator+= (other);
  2217. negate();
  2218. return *this;
  2219. }
  2220. const int numInts = (highestBit >> 5) + 1;
  2221. const int maxOtherInts = (other.highestBit >> 5) + 1;
  2222. int64 amountToSubtract = 0;
  2223. for (int i = 0; i <= numInts; ++i)
  2224. {
  2225. if (i <= maxOtherInts)
  2226. amountToSubtract += (int64) other.values[i];
  2227. if (values[i] >= amountToSubtract)
  2228. {
  2229. values[i] = (unsigned int) (values[i] - amountToSubtract);
  2230. amountToSubtract = 0;
  2231. }
  2232. else
  2233. {
  2234. const int64 n = ((int64) values[i] + (((int64) 1) << 32)) - amountToSubtract;
  2235. values[i] = (unsigned int) n;
  2236. amountToSubtract = 1;
  2237. }
  2238. }
  2239. return *this;
  2240. }
  2241. BigInteger& BigInteger::operator*= (const BigInteger& other)
  2242. {
  2243. BigInteger total;
  2244. highestBit = getHighestBit();
  2245. const bool wasNegative = isNegative();
  2246. setNegative (false);
  2247. for (int i = 0; i <= highestBit; ++i)
  2248. {
  2249. if (operator[](i))
  2250. {
  2251. BigInteger n (other);
  2252. n.setNegative (false);
  2253. n <<= i;
  2254. total += n;
  2255. }
  2256. }
  2257. total.setNegative (wasNegative ^ other.isNegative());
  2258. swapWith (total);
  2259. return *this;
  2260. }
  2261. void BigInteger::divideBy (const BigInteger& divisor, BigInteger& remainder)
  2262. {
  2263. jassert (this != &remainder); // (can't handle passing itself in to get the remainder)
  2264. const int divHB = divisor.getHighestBit();
  2265. const int ourHB = getHighestBit();
  2266. if (divHB < 0 || ourHB < 0)
  2267. {
  2268. // division by zero
  2269. remainder.clear();
  2270. clear();
  2271. }
  2272. else
  2273. {
  2274. const bool wasNegative = isNegative();
  2275. swapWith (remainder);
  2276. remainder.setNegative (false);
  2277. clear();
  2278. BigInteger temp (divisor);
  2279. temp.setNegative (false);
  2280. int leftShift = ourHB - divHB;
  2281. temp <<= leftShift;
  2282. while (leftShift >= 0)
  2283. {
  2284. if (remainder.compareAbsolute (temp) >= 0)
  2285. {
  2286. remainder -= temp;
  2287. setBit (leftShift);
  2288. }
  2289. if (--leftShift >= 0)
  2290. temp >>= 1;
  2291. }
  2292. negative = wasNegative ^ divisor.isNegative();
  2293. remainder.setNegative (wasNegative);
  2294. }
  2295. }
  2296. BigInteger& BigInteger::operator/= (const BigInteger& other)
  2297. {
  2298. BigInteger remainder;
  2299. divideBy (other, remainder);
  2300. return *this;
  2301. }
  2302. BigInteger& BigInteger::operator|= (const BigInteger& other)
  2303. {
  2304. // this operation doesn't take into account negative values..
  2305. jassert (isNegative() == other.isNegative());
  2306. if (other.highestBit >= 0)
  2307. {
  2308. ensureSize (other.highestBit >> 5);
  2309. int n = (other.highestBit >> 5) + 1;
  2310. while (--n >= 0)
  2311. values[n] |= other.values[n];
  2312. if (other.highestBit > highestBit)
  2313. highestBit = other.highestBit;
  2314. highestBit = getHighestBit();
  2315. }
  2316. return *this;
  2317. }
  2318. BigInteger& BigInteger::operator&= (const BigInteger& other)
  2319. {
  2320. // this operation doesn't take into account negative values..
  2321. jassert (isNegative() == other.isNegative());
  2322. int n = numValues;
  2323. while (n > other.numValues)
  2324. values[--n] = 0;
  2325. while (--n >= 0)
  2326. values[n] &= other.values[n];
  2327. if (other.highestBit < highestBit)
  2328. highestBit = other.highestBit;
  2329. highestBit = getHighestBit();
  2330. return *this;
  2331. }
  2332. BigInteger& BigInteger::operator^= (const BigInteger& other)
  2333. {
  2334. // this operation will only work with the absolute values
  2335. jassert (isNegative() == other.isNegative());
  2336. if (other.highestBit >= 0)
  2337. {
  2338. ensureSize (other.highestBit >> 5);
  2339. int n = (other.highestBit >> 5) + 1;
  2340. while (--n >= 0)
  2341. values[n] ^= other.values[n];
  2342. if (other.highestBit > highestBit)
  2343. highestBit = other.highestBit;
  2344. highestBit = getHighestBit();
  2345. }
  2346. return *this;
  2347. }
  2348. BigInteger& BigInteger::operator%= (const BigInteger& divisor)
  2349. {
  2350. BigInteger remainder;
  2351. divideBy (divisor, remainder);
  2352. swapWith (remainder);
  2353. return *this;
  2354. }
  2355. BigInteger& BigInteger::operator<<= (int numBitsToShift)
  2356. {
  2357. shiftBits (numBitsToShift, 0);
  2358. return *this;
  2359. }
  2360. BigInteger& BigInteger::operator>>= (int numBitsToShift)
  2361. {
  2362. return operator<<= (-numBitsToShift);
  2363. }
  2364. BigInteger& BigInteger::operator++() { return operator+= (1); }
  2365. BigInteger& BigInteger::operator--() { return operator-= (1); }
  2366. const BigInteger BigInteger::operator++ (int) { const BigInteger old (*this); operator+= (1); return old; }
  2367. const BigInteger BigInteger::operator-- (int) { const BigInteger old (*this); operator-= (1); return old; }
  2368. const BigInteger BigInteger::operator+ (const BigInteger& other) const { BigInteger b (*this); return b += other; }
  2369. const BigInteger BigInteger::operator- (const BigInteger& other) const { BigInteger b (*this); return b -= other; }
  2370. const BigInteger BigInteger::operator* (const BigInteger& other) const { BigInteger b (*this); return b *= other; }
  2371. const BigInteger BigInteger::operator/ (const BigInteger& other) const { BigInteger b (*this); return b /= other; }
  2372. const BigInteger BigInteger::operator| (const BigInteger& other) const { BigInteger b (*this); return b |= other; }
  2373. const BigInteger BigInteger::operator& (const BigInteger& other) const { BigInteger b (*this); return b &= other; }
  2374. const BigInteger BigInteger::operator^ (const BigInteger& other) const { BigInteger b (*this); return b ^= other; }
  2375. const BigInteger BigInteger::operator% (const BigInteger& other) const { BigInteger b (*this); return b %= other; }
  2376. const BigInteger BigInteger::operator<< (const int numBits) const { BigInteger b (*this); return b <<= numBits; }
  2377. const BigInteger BigInteger::operator>> (const int numBits) const { BigInteger b (*this); return b >>= numBits; }
  2378. const BigInteger BigInteger::operator-() const { BigInteger b (*this); b.negate(); return b; }
  2379. int BigInteger::compare (const BigInteger& other) const throw()
  2380. {
  2381. if (isNegative() == other.isNegative())
  2382. {
  2383. const int absComp = compareAbsolute (other);
  2384. return isNegative() ? -absComp : absComp;
  2385. }
  2386. else
  2387. {
  2388. return isNegative() ? -1 : 1;
  2389. }
  2390. }
  2391. int BigInteger::compareAbsolute (const BigInteger& other) const throw()
  2392. {
  2393. const int h1 = getHighestBit();
  2394. const int h2 = other.getHighestBit();
  2395. if (h1 > h2)
  2396. return 1;
  2397. else if (h1 < h2)
  2398. return -1;
  2399. for (int i = (h1 >> 5) + 1; --i >= 0;)
  2400. if (values[i] != other.values[i])
  2401. return (values[i] > other.values[i]) ? 1 : -1;
  2402. return 0;
  2403. }
  2404. bool BigInteger::operator== (const BigInteger& other) const throw() { return compare (other) == 0; }
  2405. bool BigInteger::operator!= (const BigInteger& other) const throw() { return compare (other) != 0; }
  2406. bool BigInteger::operator< (const BigInteger& other) const throw() { return compare (other) < 0; }
  2407. bool BigInteger::operator<= (const BigInteger& other) const throw() { return compare (other) <= 0; }
  2408. bool BigInteger::operator> (const BigInteger& other) const throw() { return compare (other) > 0; }
  2409. bool BigInteger::operator>= (const BigInteger& other) const throw() { return compare (other) >= 0; }
  2410. void BigInteger::shiftBits (int bits, const int startBit)
  2411. {
  2412. if (highestBit < 0)
  2413. return;
  2414. if (startBit > 0)
  2415. {
  2416. if (bits < 0)
  2417. {
  2418. // right shift
  2419. for (int i = startBit; i <= highestBit; ++i)
  2420. setBit (i, operator[] (i - bits));
  2421. highestBit = getHighestBit();
  2422. }
  2423. else if (bits > 0)
  2424. {
  2425. // left shift
  2426. for (int i = highestBit + 1; --i >= startBit;)
  2427. setBit (i + bits, operator[] (i));
  2428. while (--bits >= 0)
  2429. clearBit (bits + startBit);
  2430. }
  2431. }
  2432. else
  2433. {
  2434. if (bits < 0)
  2435. {
  2436. // right shift
  2437. bits = -bits;
  2438. if (bits > highestBit)
  2439. {
  2440. clear();
  2441. }
  2442. else
  2443. {
  2444. const int wordsToMove = bits >> 5;
  2445. int top = 1 + (highestBit >> 5) - wordsToMove;
  2446. highestBit -= bits;
  2447. if (wordsToMove > 0)
  2448. {
  2449. int i;
  2450. for (i = 0; i < top; ++i)
  2451. values [i] = values [i + wordsToMove];
  2452. for (i = 0; i < wordsToMove; ++i)
  2453. values [top + i] = 0;
  2454. bits &= 31;
  2455. }
  2456. if (bits != 0)
  2457. {
  2458. const int invBits = 32 - bits;
  2459. --top;
  2460. for (int i = 0; i < top; ++i)
  2461. values[i] = (values[i] >> bits) | (values [i + 1] << invBits);
  2462. values[top] = (values[top] >> bits);
  2463. }
  2464. highestBit = getHighestBit();
  2465. }
  2466. }
  2467. else if (bits > 0)
  2468. {
  2469. // left shift
  2470. ensureSize (((highestBit + bits) >> 5) + 1);
  2471. const int wordsToMove = bits >> 5;
  2472. int top = 1 + (highestBit >> 5);
  2473. highestBit += bits;
  2474. if (wordsToMove > 0)
  2475. {
  2476. int i;
  2477. for (i = top; --i >= 0;)
  2478. values [i + wordsToMove] = values [i];
  2479. for (i = 0; i < wordsToMove; ++i)
  2480. values [i] = 0;
  2481. bits &= 31;
  2482. }
  2483. if (bits != 0)
  2484. {
  2485. const int invBits = 32 - bits;
  2486. for (int i = top + 1 + wordsToMove; --i > wordsToMove;)
  2487. values[i] = (values[i] << bits) | (values [i - 1] >> invBits);
  2488. values [wordsToMove] = values [wordsToMove] << bits;
  2489. }
  2490. highestBit = getHighestBit();
  2491. }
  2492. }
  2493. }
  2494. const BigInteger BigInteger::simpleGCD (BigInteger* m, BigInteger* n)
  2495. {
  2496. while (! m->isZero())
  2497. {
  2498. if (n->compareAbsolute (*m) > 0)
  2499. swapVariables (m, n);
  2500. *m -= *n;
  2501. }
  2502. return *n;
  2503. }
  2504. const BigInteger BigInteger::findGreatestCommonDivisor (BigInteger n) const
  2505. {
  2506. BigInteger m (*this);
  2507. while (! n.isZero())
  2508. {
  2509. if (abs (m.getHighestBit() - n.getHighestBit()) <= 16)
  2510. return simpleGCD (&m, &n);
  2511. BigInteger temp1 (m), temp2;
  2512. temp1.divideBy (n, temp2);
  2513. m = n;
  2514. n = temp2;
  2515. }
  2516. return m;
  2517. }
  2518. void BigInteger::exponentModulo (const BigInteger& exponent, const BigInteger& modulus)
  2519. {
  2520. BigInteger exp (exponent);
  2521. exp %= modulus;
  2522. BigInteger value (1);
  2523. swapWith (value);
  2524. value %= modulus;
  2525. while (! exp.isZero())
  2526. {
  2527. if (exp [0])
  2528. {
  2529. operator*= (value);
  2530. operator%= (modulus);
  2531. }
  2532. value *= value;
  2533. value %= modulus;
  2534. exp >>= 1;
  2535. }
  2536. }
  2537. void BigInteger::inverseModulo (const BigInteger& modulus)
  2538. {
  2539. if (modulus.isOne() || modulus.isNegative())
  2540. {
  2541. clear();
  2542. return;
  2543. }
  2544. if (isNegative() || compareAbsolute (modulus) >= 0)
  2545. operator%= (modulus);
  2546. if (isOne())
  2547. return;
  2548. if (! (*this)[0])
  2549. {
  2550. // not invertible
  2551. clear();
  2552. return;
  2553. }
  2554. BigInteger a1 (modulus);
  2555. BigInteger a2 (*this);
  2556. BigInteger b1 (modulus);
  2557. BigInteger b2 (1);
  2558. while (! a2.isOne())
  2559. {
  2560. BigInteger temp1, temp2, multiplier (a1);
  2561. multiplier.divideBy (a2, temp1);
  2562. temp1 = a2;
  2563. temp1 *= multiplier;
  2564. temp2 = a1;
  2565. temp2 -= temp1;
  2566. a1 = a2;
  2567. a2 = temp2;
  2568. temp1 = b2;
  2569. temp1 *= multiplier;
  2570. temp2 = b1;
  2571. temp2 -= temp1;
  2572. b1 = b2;
  2573. b2 = temp2;
  2574. }
  2575. while (b2.isNegative())
  2576. b2 += modulus;
  2577. b2 %= modulus;
  2578. swapWith (b2);
  2579. }
  2580. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const BigInteger& value)
  2581. {
  2582. return stream << value.toString (10);
  2583. }
  2584. const String BigInteger::toString (const int base, const int minimumNumCharacters) const
  2585. {
  2586. String s;
  2587. BigInteger v (*this);
  2588. if (base == 2 || base == 8 || base == 16)
  2589. {
  2590. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2591. static const char* const hexDigits = "0123456789abcdef";
  2592. for (;;)
  2593. {
  2594. const int remainder = v.getBitRangeAsInt (0, bits);
  2595. v >>= bits;
  2596. if (remainder == 0 && v.isZero())
  2597. break;
  2598. s = String::charToString (hexDigits [remainder]) + s;
  2599. }
  2600. }
  2601. else if (base == 10)
  2602. {
  2603. const BigInteger ten (10);
  2604. BigInteger remainder;
  2605. for (;;)
  2606. {
  2607. v.divideBy (ten, remainder);
  2608. if (remainder.isZero() && v.isZero())
  2609. break;
  2610. s = String (remainder.getBitRangeAsInt (0, 8)) + s;
  2611. }
  2612. }
  2613. else
  2614. {
  2615. jassertfalse; // can't do the specified base!
  2616. return String::empty;
  2617. }
  2618. s = s.paddedLeft ('0', minimumNumCharacters);
  2619. return isNegative() ? "-" + s : s;
  2620. }
  2621. void BigInteger::parseString (const String& text, const int base)
  2622. {
  2623. clear();
  2624. const juce_wchar* t = text;
  2625. if (base == 2 || base == 8 || base == 16)
  2626. {
  2627. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2628. for (;;)
  2629. {
  2630. const juce_wchar c = *t++;
  2631. const int digit = CharacterFunctions::getHexDigitValue (c);
  2632. if (((unsigned int) digit) < (unsigned int) base)
  2633. {
  2634. operator<<= (bits);
  2635. operator+= (digit);
  2636. }
  2637. else if (c == 0)
  2638. {
  2639. break;
  2640. }
  2641. }
  2642. }
  2643. else if (base == 10)
  2644. {
  2645. const BigInteger ten ((unsigned int) 10);
  2646. for (;;)
  2647. {
  2648. const juce_wchar c = *t++;
  2649. if (c >= '0' && c <= '9')
  2650. {
  2651. operator*= (ten);
  2652. operator+= ((int) (c - '0'));
  2653. }
  2654. else if (c == 0)
  2655. {
  2656. break;
  2657. }
  2658. }
  2659. }
  2660. setNegative (text.trimStart().startsWithChar ('-'));
  2661. }
  2662. const MemoryBlock BigInteger::toMemoryBlock() const
  2663. {
  2664. const int numBytes = (getHighestBit() + 8) >> 3;
  2665. MemoryBlock mb ((size_t) numBytes);
  2666. for (int i = 0; i < numBytes; ++i)
  2667. mb[i] = (uint8) getBitRangeAsInt (i << 3, 8);
  2668. return mb;
  2669. }
  2670. void BigInteger::loadFromMemoryBlock (const MemoryBlock& data)
  2671. {
  2672. clear();
  2673. for (int i = (int) data.getSize(); --i >= 0;)
  2674. this->setBitRangeAsInt ((int) (i << 3), 8, data [i]);
  2675. }
  2676. END_JUCE_NAMESPACE
  2677. /*** End of inlined file: juce_BigInteger.cpp ***/
  2678. /*** Start of inlined file: juce_MemoryBlock.cpp ***/
  2679. BEGIN_JUCE_NAMESPACE
  2680. MemoryBlock::MemoryBlock() throw()
  2681. : size (0)
  2682. {
  2683. }
  2684. MemoryBlock::MemoryBlock (const size_t initialSize,
  2685. const bool initialiseToZero) throw()
  2686. {
  2687. if (initialSize > 0)
  2688. {
  2689. size = initialSize;
  2690. data.allocate (initialSize, initialiseToZero);
  2691. }
  2692. else
  2693. {
  2694. size = 0;
  2695. }
  2696. }
  2697. MemoryBlock::MemoryBlock (const MemoryBlock& other) throw()
  2698. : size (other.size)
  2699. {
  2700. if (size > 0)
  2701. {
  2702. jassert (other.data != 0);
  2703. data.malloc (size);
  2704. memcpy (data, other.data, size);
  2705. }
  2706. }
  2707. MemoryBlock::MemoryBlock (const void* const dataToInitialiseFrom,
  2708. const size_t sizeInBytes) throw()
  2709. : size (jmax ((size_t) 0, sizeInBytes))
  2710. {
  2711. jassert (sizeInBytes >= 0);
  2712. if (size > 0)
  2713. {
  2714. jassert (dataToInitialiseFrom != 0); // non-zero size, but a zero pointer passed-in?
  2715. data.malloc (size);
  2716. if (dataToInitialiseFrom != 0)
  2717. memcpy (data, dataToInitialiseFrom, size);
  2718. }
  2719. }
  2720. MemoryBlock::~MemoryBlock() throw()
  2721. {
  2722. jassert (size >= 0); // should never happen
  2723. jassert (size == 0 || data != 0); // non-zero size but no data allocated?
  2724. }
  2725. MemoryBlock& MemoryBlock::operator= (const MemoryBlock& other) throw()
  2726. {
  2727. if (this != &other)
  2728. {
  2729. setSize (other.size, false);
  2730. memcpy (data, other.data, size);
  2731. }
  2732. return *this;
  2733. }
  2734. bool MemoryBlock::operator== (const MemoryBlock& other) const throw()
  2735. {
  2736. return matches (other.data, other.size);
  2737. }
  2738. bool MemoryBlock::operator!= (const MemoryBlock& other) const throw()
  2739. {
  2740. return ! operator== (other);
  2741. }
  2742. bool MemoryBlock::matches (const void* dataToCompare, size_t dataSize) const throw()
  2743. {
  2744. return size == dataSize
  2745. && memcmp (data, dataToCompare, size) == 0;
  2746. }
  2747. // this will resize the block to this size
  2748. void MemoryBlock::setSize (const size_t newSize,
  2749. const bool initialiseToZero) throw()
  2750. {
  2751. if (size != newSize)
  2752. {
  2753. if (newSize <= 0)
  2754. {
  2755. data.free();
  2756. size = 0;
  2757. }
  2758. else
  2759. {
  2760. if (data != 0)
  2761. {
  2762. data.realloc (newSize);
  2763. if (initialiseToZero && (newSize > size))
  2764. zeromem (data + size, newSize - size);
  2765. }
  2766. else
  2767. {
  2768. data.allocate (newSize, initialiseToZero);
  2769. }
  2770. size = newSize;
  2771. }
  2772. }
  2773. }
  2774. void MemoryBlock::ensureSize (const size_t minimumSize,
  2775. const bool initialiseToZero) throw()
  2776. {
  2777. if (size < minimumSize)
  2778. setSize (minimumSize, initialiseToZero);
  2779. }
  2780. void MemoryBlock::swapWith (MemoryBlock& other) throw()
  2781. {
  2782. swapVariables (size, other.size);
  2783. data.swapWith (other.data);
  2784. }
  2785. void MemoryBlock::fillWith (const uint8 value) throw()
  2786. {
  2787. memset (data, (int) value, size);
  2788. }
  2789. void MemoryBlock::append (const void* const srcData,
  2790. const size_t numBytes) throw()
  2791. {
  2792. if (numBytes > 0)
  2793. {
  2794. const size_t oldSize = size;
  2795. setSize (size + numBytes);
  2796. memcpy (data + oldSize, srcData, numBytes);
  2797. }
  2798. }
  2799. void MemoryBlock::copyFrom (const void* const src, int offset, size_t num) throw()
  2800. {
  2801. const char* d = static_cast<const char*> (src);
  2802. if (offset < 0)
  2803. {
  2804. d -= offset;
  2805. num -= offset;
  2806. offset = 0;
  2807. }
  2808. if (offset + num > size)
  2809. num = size - offset;
  2810. if (num > 0)
  2811. memcpy (data + offset, d, num);
  2812. }
  2813. void MemoryBlock::copyTo (void* const dst, int offset, size_t num) const throw()
  2814. {
  2815. char* d = static_cast<char*> (dst);
  2816. if (offset < 0)
  2817. {
  2818. zeromem (d, -offset);
  2819. d -= offset;
  2820. num += offset;
  2821. offset = 0;
  2822. }
  2823. if (offset + num > size)
  2824. {
  2825. const size_t newNum = size - offset;
  2826. zeromem (d + newNum, num - newNum);
  2827. num = newNum;
  2828. }
  2829. if (num > 0)
  2830. memcpy (d, data + offset, num);
  2831. }
  2832. void MemoryBlock::removeSection (size_t startByte, size_t numBytesToRemove) throw()
  2833. {
  2834. if (startByte < 0)
  2835. {
  2836. numBytesToRemove += startByte;
  2837. startByte = 0;
  2838. }
  2839. if (startByte + numBytesToRemove >= size)
  2840. {
  2841. setSize (startByte);
  2842. }
  2843. else if (numBytesToRemove > 0)
  2844. {
  2845. memmove (data + startByte,
  2846. data + startByte + numBytesToRemove,
  2847. size - (startByte + numBytesToRemove));
  2848. setSize (size - numBytesToRemove);
  2849. }
  2850. }
  2851. const String MemoryBlock::toString() const throw()
  2852. {
  2853. return String (static_cast <const char*> (getData()), size);
  2854. }
  2855. int MemoryBlock::getBitRange (const size_t bitRangeStart, size_t numBits) const throw()
  2856. {
  2857. int res = 0;
  2858. size_t byte = bitRangeStart >> 3;
  2859. int offsetInByte = (int) bitRangeStart & 7;
  2860. size_t bitsSoFar = 0;
  2861. while (numBits > 0 && (size_t) byte < size)
  2862. {
  2863. const int bitsThisTime = jmin ((int) numBits, 8 - offsetInByte);
  2864. const int mask = (0xff >> (8 - bitsThisTime)) << offsetInByte;
  2865. res |= (((data[byte] & mask) >> offsetInByte) << bitsSoFar);
  2866. bitsSoFar += bitsThisTime;
  2867. numBits -= bitsThisTime;
  2868. ++byte;
  2869. offsetInByte = 0;
  2870. }
  2871. return res;
  2872. }
  2873. void MemoryBlock::setBitRange (const size_t bitRangeStart, size_t numBits, int bitsToSet) throw()
  2874. {
  2875. size_t byte = bitRangeStart >> 3;
  2876. int offsetInByte = (int) bitRangeStart & 7;
  2877. unsigned int mask = ~((((unsigned int) 0xffffffff) << (32 - numBits)) >> (32 - numBits));
  2878. while (numBits > 0 && (size_t) byte < size)
  2879. {
  2880. const int bitsThisTime = jmin ((int) numBits, 8 - offsetInByte);
  2881. const unsigned int tempMask = (mask << offsetInByte) | ~((((unsigned int) 0xffffffff) >> offsetInByte) << offsetInByte);
  2882. const unsigned int tempBits = bitsToSet << offsetInByte;
  2883. data[byte] = (char) ((data[byte] & tempMask) | tempBits);
  2884. ++byte;
  2885. numBits -= bitsThisTime;
  2886. bitsToSet >>= bitsThisTime;
  2887. mask >>= bitsThisTime;
  2888. offsetInByte = 0;
  2889. }
  2890. }
  2891. void MemoryBlock::loadFromHexString (const String& hex) throw()
  2892. {
  2893. ensureSize (hex.length() >> 1);
  2894. char* dest = data;
  2895. int i = 0;
  2896. for (;;)
  2897. {
  2898. int byte = 0;
  2899. for (int loop = 2; --loop >= 0;)
  2900. {
  2901. byte <<= 4;
  2902. for (;;)
  2903. {
  2904. const juce_wchar c = hex [i++];
  2905. if (c >= '0' && c <= '9')
  2906. {
  2907. byte |= c - '0';
  2908. break;
  2909. }
  2910. else if (c >= 'a' && c <= 'z')
  2911. {
  2912. byte |= c - ('a' - 10);
  2913. break;
  2914. }
  2915. else if (c >= 'A' && c <= 'Z')
  2916. {
  2917. byte |= c - ('A' - 10);
  2918. break;
  2919. }
  2920. else if (c == 0)
  2921. {
  2922. setSize (static_cast <size_t> (dest - data));
  2923. return;
  2924. }
  2925. }
  2926. }
  2927. *dest++ = (char) byte;
  2928. }
  2929. }
  2930. static const char* const encodingTable
  2931. = ".ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+";
  2932. const String MemoryBlock::toBase64Encoding() const throw()
  2933. {
  2934. const size_t numChars = ((size << 3) + 5) / 6;
  2935. String destString ((unsigned int) size); // store the length, followed by a '.', and then the data.
  2936. const int initialLen = destString.length();
  2937. destString.preallocateStorage (initialLen + 2 + numChars);
  2938. juce_wchar* d = destString;
  2939. d += initialLen;
  2940. *d++ = '.';
  2941. for (size_t i = 0; i < numChars; ++i)
  2942. *d++ = encodingTable [getBitRange (i * 6, 6)];
  2943. *d++ = 0;
  2944. return destString;
  2945. }
  2946. bool MemoryBlock::fromBase64Encoding (const String& s) throw()
  2947. {
  2948. const int startPos = s.indexOfChar ('.') + 1;
  2949. if (startPos <= 0)
  2950. return false;
  2951. const int numBytesNeeded = s.substring (0, startPos - 1).getIntValue();
  2952. setSize (numBytesNeeded, true);
  2953. const int numChars = s.length() - startPos;
  2954. const juce_wchar* srcChars = s;
  2955. srcChars += startPos;
  2956. int pos = 0;
  2957. for (int i = 0; i < numChars; ++i)
  2958. {
  2959. const char c = (char) srcChars[i];
  2960. for (int j = 0; j < 64; ++j)
  2961. {
  2962. if (encodingTable[j] == c)
  2963. {
  2964. setBitRange (pos, 6, j);
  2965. pos += 6;
  2966. break;
  2967. }
  2968. }
  2969. }
  2970. return true;
  2971. }
  2972. END_JUCE_NAMESPACE
  2973. /*** End of inlined file: juce_MemoryBlock.cpp ***/
  2974. /*** Start of inlined file: juce_PropertySet.cpp ***/
  2975. BEGIN_JUCE_NAMESPACE
  2976. PropertySet::PropertySet (const bool ignoreCaseOfKeyNames) throw()
  2977. : properties (ignoreCaseOfKeyNames),
  2978. fallbackProperties (0),
  2979. ignoreCaseOfKeys (ignoreCaseOfKeyNames)
  2980. {
  2981. }
  2982. PropertySet::PropertySet (const PropertySet& other) throw()
  2983. : properties (other.properties),
  2984. fallbackProperties (other.fallbackProperties),
  2985. ignoreCaseOfKeys (other.ignoreCaseOfKeys)
  2986. {
  2987. }
  2988. PropertySet& PropertySet::operator= (const PropertySet& other) throw()
  2989. {
  2990. properties = other.properties;
  2991. fallbackProperties = other.fallbackProperties;
  2992. ignoreCaseOfKeys = other.ignoreCaseOfKeys;
  2993. propertyChanged();
  2994. return *this;
  2995. }
  2996. PropertySet::~PropertySet()
  2997. {
  2998. }
  2999. void PropertySet::clear()
  3000. {
  3001. const ScopedLock sl (lock);
  3002. if (properties.size() > 0)
  3003. {
  3004. properties.clear();
  3005. propertyChanged();
  3006. }
  3007. }
  3008. const String PropertySet::getValue (const String& keyName,
  3009. const String& defaultValue) const throw()
  3010. {
  3011. const ScopedLock sl (lock);
  3012. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3013. if (index >= 0)
  3014. return properties.getAllValues() [index];
  3015. return fallbackProperties != 0 ? fallbackProperties->getValue (keyName, defaultValue)
  3016. : defaultValue;
  3017. }
  3018. int PropertySet::getIntValue (const String& keyName,
  3019. const int defaultValue) const throw()
  3020. {
  3021. const ScopedLock sl (lock);
  3022. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3023. if (index >= 0)
  3024. return properties.getAllValues() [index].getIntValue();
  3025. return fallbackProperties != 0 ? fallbackProperties->getIntValue (keyName, defaultValue)
  3026. : defaultValue;
  3027. }
  3028. double PropertySet::getDoubleValue (const String& keyName,
  3029. const double defaultValue) const throw()
  3030. {
  3031. const ScopedLock sl (lock);
  3032. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3033. if (index >= 0)
  3034. return properties.getAllValues()[index].getDoubleValue();
  3035. return fallbackProperties != 0 ? fallbackProperties->getDoubleValue (keyName, defaultValue)
  3036. : defaultValue;
  3037. }
  3038. bool PropertySet::getBoolValue (const String& keyName,
  3039. const bool defaultValue) const throw()
  3040. {
  3041. const ScopedLock sl (lock);
  3042. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3043. if (index >= 0)
  3044. return properties.getAllValues() [index].getIntValue() != 0;
  3045. return fallbackProperties != 0 ? fallbackProperties->getBoolValue (keyName, defaultValue)
  3046. : defaultValue;
  3047. }
  3048. XmlElement* PropertySet::getXmlValue (const String& keyName) const
  3049. {
  3050. XmlDocument doc (getValue (keyName));
  3051. return doc.getDocumentElement();
  3052. }
  3053. void PropertySet::setValue (const String& keyName,
  3054. const String& value) throw()
  3055. {
  3056. jassert (keyName.isNotEmpty()); // shouldn't use an empty key name!
  3057. if (keyName.isNotEmpty())
  3058. {
  3059. const ScopedLock sl (lock);
  3060. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3061. if (index < 0 || properties.getAllValues() [index] != value)
  3062. {
  3063. properties.set (keyName, value);
  3064. propertyChanged();
  3065. }
  3066. }
  3067. }
  3068. void PropertySet::removeValue (const String& keyName) throw()
  3069. {
  3070. if (keyName.isNotEmpty())
  3071. {
  3072. const ScopedLock sl (lock);
  3073. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3074. if (index >= 0)
  3075. {
  3076. properties.remove (keyName);
  3077. propertyChanged();
  3078. }
  3079. }
  3080. }
  3081. void PropertySet::setValue (const String& keyName, const int value) throw()
  3082. {
  3083. setValue (keyName, String (value));
  3084. }
  3085. void PropertySet::setValue (const String& keyName, const double value) throw()
  3086. {
  3087. setValue (keyName, String (value));
  3088. }
  3089. void PropertySet::setValue (const String& keyName, const bool value) throw()
  3090. {
  3091. setValue (keyName, String (value ? "1" : "0"));
  3092. }
  3093. void PropertySet::setValue (const String& keyName, const XmlElement* const xml)
  3094. {
  3095. setValue (keyName, (xml == 0) ? String::empty
  3096. : xml->createDocument (String::empty, true));
  3097. }
  3098. bool PropertySet::containsKey (const String& keyName) const throw()
  3099. {
  3100. const ScopedLock sl (lock);
  3101. return properties.getAllKeys().contains (keyName, ignoreCaseOfKeys);
  3102. }
  3103. void PropertySet::setFallbackPropertySet (PropertySet* fallbackProperties_) throw()
  3104. {
  3105. const ScopedLock sl (lock);
  3106. fallbackProperties = fallbackProperties_;
  3107. }
  3108. XmlElement* PropertySet::createXml (const String& nodeName) const throw()
  3109. {
  3110. const ScopedLock sl (lock);
  3111. XmlElement* const xml = new XmlElement (nodeName);
  3112. for (int i = 0; i < properties.getAllKeys().size(); ++i)
  3113. {
  3114. XmlElement* const e = xml->createNewChildElement ("VALUE");
  3115. e->setAttribute ("name", properties.getAllKeys()[i]);
  3116. e->setAttribute ("val", properties.getAllValues()[i]);
  3117. }
  3118. return xml;
  3119. }
  3120. void PropertySet::restoreFromXml (const XmlElement& xml) throw()
  3121. {
  3122. const ScopedLock sl (lock);
  3123. clear();
  3124. forEachXmlChildElementWithTagName (xml, e, "VALUE")
  3125. {
  3126. if (e->hasAttribute ("name")
  3127. && e->hasAttribute ("val"))
  3128. {
  3129. properties.set (e->getStringAttribute ("name"),
  3130. e->getStringAttribute ("val"));
  3131. }
  3132. }
  3133. if (properties.size() > 0)
  3134. propertyChanged();
  3135. }
  3136. void PropertySet::propertyChanged()
  3137. {
  3138. }
  3139. END_JUCE_NAMESPACE
  3140. /*** End of inlined file: juce_PropertySet.cpp ***/
  3141. /*** Start of inlined file: juce_Identifier.cpp ***/
  3142. BEGIN_JUCE_NAMESPACE
  3143. StringPool& Identifier::getPool()
  3144. {
  3145. static StringPool pool;
  3146. return pool;
  3147. }
  3148. Identifier::Identifier() throw()
  3149. : name (0)
  3150. {
  3151. }
  3152. Identifier::Identifier (const Identifier& other) throw()
  3153. : name (other.name)
  3154. {
  3155. }
  3156. Identifier& Identifier::operator= (const Identifier& other) throw()
  3157. {
  3158. name = other.name;
  3159. return *this;
  3160. }
  3161. Identifier::Identifier (const String& name_)
  3162. : name (Identifier::getPool().getPooledString (name_))
  3163. {
  3164. /* An Identifier string must be suitable for use as a script variable or XML
  3165. attribute, so it can only contain this limited set of characters.. */
  3166. jassert (name_.containsOnly ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") && name_.isNotEmpty());
  3167. }
  3168. Identifier::Identifier (const char* const name_)
  3169. : name (Identifier::getPool().getPooledString (name_))
  3170. {
  3171. /* An Identifier string must be suitable for use as a script variable or XML
  3172. attribute, so it can only contain this limited set of characters.. */
  3173. jassert (toString().containsOnly ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") && toString().isNotEmpty());
  3174. }
  3175. Identifier::~Identifier()
  3176. {
  3177. }
  3178. END_JUCE_NAMESPACE
  3179. /*** End of inlined file: juce_Identifier.cpp ***/
  3180. /*** Start of inlined file: juce_Variant.cpp ***/
  3181. BEGIN_JUCE_NAMESPACE
  3182. var::var() throw()
  3183. : type (voidType)
  3184. {
  3185. value.doubleValue = 0;
  3186. }
  3187. var::~var() throw()
  3188. {
  3189. if (type == stringType)
  3190. delete value.stringValue;
  3191. else if (type == objectType && value.objectValue != 0)
  3192. value.objectValue->decReferenceCount();
  3193. }
  3194. const var var::null;
  3195. var::var (const var& valueToCopy)
  3196. : type (valueToCopy.type),
  3197. value (valueToCopy.value)
  3198. {
  3199. if (type == stringType)
  3200. value.stringValue = new String (*(value.stringValue));
  3201. else if (type == objectType && value.objectValue != 0)
  3202. value.objectValue->incReferenceCount();
  3203. }
  3204. var::var (const int value_) throw()
  3205. : type (intType)
  3206. {
  3207. value.intValue = value_;
  3208. }
  3209. var::var (const bool value_) throw()
  3210. : type (boolType)
  3211. {
  3212. value.boolValue = value_;
  3213. }
  3214. var::var (const double value_) throw()
  3215. : type (doubleType)
  3216. {
  3217. value.doubleValue = value_;
  3218. }
  3219. var::var (const String& value_)
  3220. : type (stringType)
  3221. {
  3222. value.stringValue = new String (value_);
  3223. }
  3224. var::var (const char* const value_)
  3225. : type (stringType)
  3226. {
  3227. value.stringValue = new String (value_);
  3228. }
  3229. var::var (const juce_wchar* const value_)
  3230. : type (stringType)
  3231. {
  3232. value.stringValue = new String (value_);
  3233. }
  3234. var::var (DynamicObject* const object)
  3235. : type (objectType)
  3236. {
  3237. value.objectValue = object;
  3238. if (object != 0)
  3239. object->incReferenceCount();
  3240. }
  3241. var::var (MethodFunction method_) throw()
  3242. : type (methodType)
  3243. {
  3244. value.methodValue = method_;
  3245. }
  3246. void var::swapWith (var& other) throw()
  3247. {
  3248. swapVariables (type, other.type);
  3249. swapVariables (value, other.value);
  3250. }
  3251. var& var::operator= (const var& value_) { var newValue (value_); swapWith (newValue); return *this; }
  3252. var& var::operator= (int value_) { var newValue (value_); swapWith (newValue); return *this; }
  3253. var& var::operator= (bool value_) { var newValue (value_); swapWith (newValue); return *this; }
  3254. var& var::operator= (double value_) { var newValue (value_); swapWith (newValue); return *this; }
  3255. var& var::operator= (const char* value_) { var newValue (value_); swapWith (newValue); return *this; }
  3256. var& var::operator= (const juce_wchar* value_) { var newValue (value_); swapWith (newValue); return *this; }
  3257. var& var::operator= (const String& value_) { var newValue (value_); swapWith (newValue); return *this; }
  3258. var& var::operator= (DynamicObject* value_) { var newValue (value_); swapWith (newValue); return *this; }
  3259. var& var::operator= (MethodFunction value_) { var newValue (value_); swapWith (newValue); return *this; }
  3260. var::operator int() const
  3261. {
  3262. switch (type)
  3263. {
  3264. case voidType: break;
  3265. case intType: return value.intValue;
  3266. case boolType: return value.boolValue ? 1 : 0;
  3267. case doubleType: return static_cast <int> (value.doubleValue);
  3268. case stringType: return value.stringValue->getIntValue();
  3269. case objectType: break;
  3270. default: jassertfalse; break;
  3271. }
  3272. return 0;
  3273. }
  3274. var::operator bool() const
  3275. {
  3276. switch (type)
  3277. {
  3278. case voidType: break;
  3279. case intType: return value.intValue != 0;
  3280. case boolType: return value.boolValue;
  3281. case doubleType: return value.doubleValue != 0;
  3282. case stringType: return value.stringValue->getIntValue() != 0
  3283. || value.stringValue->trim().equalsIgnoreCase ("true")
  3284. || value.stringValue->trim().equalsIgnoreCase ("yes");
  3285. case objectType: return value.objectValue != 0;
  3286. default: jassertfalse; break;
  3287. }
  3288. return false;
  3289. }
  3290. var::operator float() const
  3291. {
  3292. return (float) operator double();
  3293. }
  3294. var::operator double() const
  3295. {
  3296. switch (type)
  3297. {
  3298. case voidType: break;
  3299. case intType: return value.intValue;
  3300. case boolType: return value.boolValue ? 1.0 : 0.0;
  3301. case doubleType: return value.doubleValue;
  3302. case stringType: return value.stringValue->getDoubleValue();
  3303. case objectType: break;
  3304. default: jassertfalse; break;
  3305. }
  3306. return 0.0;
  3307. }
  3308. const String var::toString() const
  3309. {
  3310. switch (type)
  3311. {
  3312. case voidType: return String::empty;
  3313. case intType: return String (value.intValue);
  3314. case boolType: return String::charToString (value.boolValue ? '1' : '0');
  3315. case doubleType: return String (value.doubleValue);
  3316. case stringType: return *(value.stringValue);
  3317. case objectType: return "Object 0x" + String::toHexString ((int) (pointer_sized_int) value.objectValue);
  3318. case methodType: return "Method";
  3319. default: jassertfalse; break;
  3320. }
  3321. return String::empty;
  3322. }
  3323. var::operator const String() const
  3324. {
  3325. return toString();
  3326. }
  3327. DynamicObject* var::getObject() const
  3328. {
  3329. return type == objectType ? value.objectValue : 0;
  3330. }
  3331. bool var::equals (const var& other) const throw()
  3332. {
  3333. switch (type)
  3334. {
  3335. case voidType: return other.isVoid();
  3336. case intType: return value.intValue == static_cast <int> (other);
  3337. case boolType: return value.boolValue == static_cast <bool> (other);
  3338. case doubleType: return value.doubleValue == static_cast <double> (other);
  3339. case stringType: return (*(value.stringValue)) == other.toString();
  3340. case objectType: return value.objectValue == other.getObject();
  3341. case methodType: return value.methodValue == other.value.methodValue && other.isMethod();
  3342. default: jassertfalse; break;
  3343. }
  3344. return false;
  3345. }
  3346. bool operator== (const var& v1, const var& v2) throw() { return v1.equals (v2); }
  3347. bool operator!= (const var& v1, const var& v2) throw() { return ! v1.equals (v2); }
  3348. bool operator== (const var& v1, const String& v2) throw() { return v1.toString() == v2; }
  3349. bool operator!= (const var& v1, const String& v2) throw() { return v1.toString() != v2; }
  3350. void var::writeToStream (OutputStream& output) const
  3351. {
  3352. switch (type)
  3353. {
  3354. case voidType: output.writeCompressedInt (0); break;
  3355. case intType: output.writeCompressedInt (5); output.writeByte (1); output.writeInt (value.intValue); break;
  3356. case boolType: output.writeCompressedInt (1); output.writeByte (value.boolValue ? 2 : 3); break;
  3357. case doubleType: output.writeCompressedInt (9); output.writeByte (4); output.writeDouble (value.doubleValue); break;
  3358. case stringType:
  3359. {
  3360. const int len = value.stringValue->getNumBytesAsUTF8() + 1;
  3361. output.writeCompressedInt (len + 1);
  3362. output.writeByte (5);
  3363. HeapBlock<char> temp (len);
  3364. value.stringValue->copyToUTF8 (temp, len);
  3365. output.write (temp, len);
  3366. break;
  3367. }
  3368. case objectType:
  3369. case methodType: output.writeCompressedInt (0); jassertfalse; break; // Can't write an object to a stream!
  3370. default: jassertfalse; break; // Is this a corrupted object?
  3371. }
  3372. }
  3373. const var var::readFromStream (InputStream& input)
  3374. {
  3375. const int numBytes = input.readCompressedInt();
  3376. if (numBytes > 0)
  3377. {
  3378. switch (input.readByte())
  3379. {
  3380. case 1: return var (input.readInt());
  3381. case 2: return var (true);
  3382. case 3: return var (false);
  3383. case 4: return var (input.readDouble());
  3384. case 5:
  3385. {
  3386. MemoryBlock mb;
  3387. input.readIntoMemoryBlock (mb, numBytes - 1);
  3388. return var (String::fromUTF8 (static_cast <const char*> (mb.getData()), (int) mb.getSize()));
  3389. }
  3390. default: input.skipNextBytes (numBytes - 1); break;
  3391. }
  3392. }
  3393. return var::null;
  3394. }
  3395. const var var::operator[] (const Identifier& propertyName) const
  3396. {
  3397. if (type == objectType && value.objectValue != 0)
  3398. return value.objectValue->getProperty (propertyName);
  3399. return var::null;
  3400. }
  3401. const var var::invoke (const Identifier& method, const var* arguments, int numArguments) const
  3402. {
  3403. if (type == objectType && value.objectValue != 0)
  3404. return value.objectValue->invokeMethod (method, arguments, numArguments);
  3405. return var::null;
  3406. }
  3407. const var var::invoke (const var& targetObject, const var* arguments, int numArguments) const
  3408. {
  3409. if (isMethod())
  3410. {
  3411. DynamicObject* const target = targetObject.getObject();
  3412. if (target != 0)
  3413. return (target->*(value.methodValue)) (arguments, numArguments);
  3414. }
  3415. return var::null;
  3416. }
  3417. const var var::call (const Identifier& method) const
  3418. {
  3419. return invoke (method, 0, 0);
  3420. }
  3421. const var var::call (const Identifier& method, const var& arg1) const
  3422. {
  3423. return invoke (method, &arg1, 1);
  3424. }
  3425. const var var::call (const Identifier& method, const var& arg1, const var& arg2) const
  3426. {
  3427. var args[] = { arg1, arg2 };
  3428. return invoke (method, args, 2);
  3429. }
  3430. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3)
  3431. {
  3432. var args[] = { arg1, arg2, arg3 };
  3433. return invoke (method, args, 3);
  3434. }
  3435. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4) const
  3436. {
  3437. var args[] = { arg1, arg2, arg3, arg4 };
  3438. return invoke (method, args, 4);
  3439. }
  3440. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4, const var& arg5) const
  3441. {
  3442. var args[] = { arg1, arg2, arg3, arg4, arg5 };
  3443. return invoke (method, args, 5);
  3444. }
  3445. END_JUCE_NAMESPACE
  3446. /*** End of inlined file: juce_Variant.cpp ***/
  3447. /*** Start of inlined file: juce_NamedValueSet.cpp ***/
  3448. BEGIN_JUCE_NAMESPACE
  3449. NamedValueSet::NamedValue::NamedValue() throw()
  3450. {
  3451. }
  3452. inline NamedValueSet::NamedValue::NamedValue (const Identifier& name_, const var& value_)
  3453. : name (name_), value (value_)
  3454. {
  3455. }
  3456. bool NamedValueSet::NamedValue::operator== (const NamedValueSet::NamedValue& other) const throw()
  3457. {
  3458. return name == other.name && value == other.value;
  3459. }
  3460. NamedValueSet::NamedValueSet() throw()
  3461. {
  3462. }
  3463. NamedValueSet::NamedValueSet (const NamedValueSet& other)
  3464. : values (other.values)
  3465. {
  3466. }
  3467. NamedValueSet& NamedValueSet::operator= (const NamedValueSet& other)
  3468. {
  3469. values = other.values;
  3470. return *this;
  3471. }
  3472. NamedValueSet::~NamedValueSet()
  3473. {
  3474. }
  3475. bool NamedValueSet::operator== (const NamedValueSet& other) const
  3476. {
  3477. return values == other.values;
  3478. }
  3479. bool NamedValueSet::operator!= (const NamedValueSet& other) const
  3480. {
  3481. return ! operator== (other);
  3482. }
  3483. int NamedValueSet::size() const throw()
  3484. {
  3485. return values.size();
  3486. }
  3487. const var& NamedValueSet::operator[] (const Identifier& name) const
  3488. {
  3489. for (int i = values.size(); --i >= 0;)
  3490. {
  3491. const NamedValue& v = values.getReference(i);
  3492. if (v.name == name)
  3493. return v.value;
  3494. }
  3495. return var::null;
  3496. }
  3497. const var NamedValueSet::getWithDefault (const Identifier& name, const var& defaultReturnValue) const
  3498. {
  3499. const var* v = getItem (name);
  3500. return v != 0 ? *v : defaultReturnValue;
  3501. }
  3502. var* NamedValueSet::getItem (const Identifier& name) const
  3503. {
  3504. for (int i = values.size(); --i >= 0;)
  3505. {
  3506. NamedValue& v = values.getReference(i);
  3507. if (v.name == name)
  3508. return &(v.value);
  3509. }
  3510. return 0;
  3511. }
  3512. bool NamedValueSet::set (const Identifier& name, const var& newValue)
  3513. {
  3514. for (int i = values.size(); --i >= 0;)
  3515. {
  3516. NamedValue& v = values.getReference(i);
  3517. if (v.name == name)
  3518. {
  3519. if (v.value == newValue)
  3520. return false;
  3521. v.value = newValue;
  3522. return true;
  3523. }
  3524. }
  3525. values.add (NamedValue (name, newValue));
  3526. return true;
  3527. }
  3528. bool NamedValueSet::contains (const Identifier& name) const
  3529. {
  3530. return getItem (name) != 0;
  3531. }
  3532. bool NamedValueSet::remove (const Identifier& name)
  3533. {
  3534. for (int i = values.size(); --i >= 0;)
  3535. {
  3536. if (values.getReference(i).name == name)
  3537. {
  3538. values.remove (i);
  3539. return true;
  3540. }
  3541. }
  3542. return false;
  3543. }
  3544. const Identifier NamedValueSet::getName (const int index) const
  3545. {
  3546. jassert (((unsigned int) index) < (unsigned int) values.size());
  3547. return values [index].name;
  3548. }
  3549. const var NamedValueSet::getValueAt (const int index) const
  3550. {
  3551. jassert (((unsigned int) index) < (unsigned int) values.size());
  3552. return values [index].value;
  3553. }
  3554. void NamedValueSet::clear()
  3555. {
  3556. values.clear();
  3557. }
  3558. END_JUCE_NAMESPACE
  3559. /*** End of inlined file: juce_NamedValueSet.cpp ***/
  3560. /*** Start of inlined file: juce_DynamicObject.cpp ***/
  3561. BEGIN_JUCE_NAMESPACE
  3562. DynamicObject::DynamicObject()
  3563. {
  3564. }
  3565. DynamicObject::~DynamicObject()
  3566. {
  3567. }
  3568. bool DynamicObject::hasProperty (const Identifier& propertyName) const
  3569. {
  3570. var* const v = properties.getItem (propertyName);
  3571. return v != 0 && ! v->isMethod();
  3572. }
  3573. const var DynamicObject::getProperty (const Identifier& propertyName) const
  3574. {
  3575. return properties [propertyName];
  3576. }
  3577. void DynamicObject::setProperty (const Identifier& propertyName, const var& newValue)
  3578. {
  3579. properties.set (propertyName, newValue);
  3580. }
  3581. void DynamicObject::removeProperty (const Identifier& propertyName)
  3582. {
  3583. properties.remove (propertyName);
  3584. }
  3585. bool DynamicObject::hasMethod (const Identifier& methodName) const
  3586. {
  3587. return getProperty (methodName).isMethod();
  3588. }
  3589. const var DynamicObject::invokeMethod (const Identifier& methodName,
  3590. const var* parameters,
  3591. int numParameters)
  3592. {
  3593. return properties [methodName].invoke (var (this), parameters, numParameters);
  3594. }
  3595. void DynamicObject::setMethod (const Identifier& name,
  3596. var::MethodFunction methodFunction)
  3597. {
  3598. properties.set (name, var (methodFunction));
  3599. }
  3600. void DynamicObject::clear()
  3601. {
  3602. properties.clear();
  3603. }
  3604. END_JUCE_NAMESPACE
  3605. /*** End of inlined file: juce_DynamicObject.cpp ***/
  3606. /*** Start of inlined file: juce_BlowFish.cpp ***/
  3607. BEGIN_JUCE_NAMESPACE
  3608. BlowFish::BlowFish (const void* const keyData, const int keyBytes)
  3609. {
  3610. jassert (keyData != 0);
  3611. jassert (keyBytes > 0);
  3612. static const uint32 initialPValues [18] =
  3613. {
  3614. 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89,
  3615. 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917,
  3616. 0x9216d5d9, 0x8979fb1b
  3617. };
  3618. static const uint32 initialSValues [4 * 256] =
  3619. {
  3620. 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99,
  3621. 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e,
  3622. 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
  3623. 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e,
  3624. 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440,
  3625. 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
  3626. 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677,
  3627. 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032,
  3628. 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
  3629. 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0,
  3630. 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98,
  3631. 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
  3632. 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d,
  3633. 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7,
  3634. 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
  3635. 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09,
  3636. 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb,
  3637. 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
  3638. 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82,
  3639. 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573,
  3640. 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
  3641. 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8,
  3642. 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0,
  3643. 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
  3644. 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1,
  3645. 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9,
  3646. 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
  3647. 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af,
  3648. 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5,
  3649. 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
  3650. 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915,
  3651. 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a,
  3652. 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266,
  3653. 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e,
  3654. 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
  3655. 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1,
  3656. 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8,
  3657. 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
  3658. 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7,
  3659. 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331,
  3660. 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
  3661. 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87,
  3662. 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2,
  3663. 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
  3664. 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509,
  3665. 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3,
  3666. 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
  3667. 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960,
  3668. 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28,
  3669. 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
  3670. 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf,
  3671. 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e,
  3672. 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
  3673. 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281,
  3674. 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696,
  3675. 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
  3676. 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0,
  3677. 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250,
  3678. 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
  3679. 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061,
  3680. 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e,
  3681. 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
  3682. 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340,
  3683. 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7,
  3684. 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068,
  3685. 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840,
  3686. 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
  3687. 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb,
  3688. 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6,
  3689. 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
  3690. 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb,
  3691. 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b,
  3692. 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
  3693. 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc,
  3694. 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564,
  3695. 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
  3696. 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728,
  3697. 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e,
  3698. 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
  3699. 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b,
  3700. 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb,
  3701. 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
  3702. 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9,
  3703. 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe,
  3704. 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
  3705. 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61,
  3706. 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9,
  3707. 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,
  3708. 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633,
  3709. 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169,
  3710. 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
  3711. 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62,
  3712. 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76,
  3713. 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
  3714. 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c,
  3715. 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0,
  3716. 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe,
  3717. 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4,
  3718. 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
  3719. 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22,
  3720. 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6,
  3721. 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
  3722. 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51,
  3723. 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c,
  3724. 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
  3725. 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd,
  3726. 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319,
  3727. 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
  3728. 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32,
  3729. 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166,
  3730. 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
  3731. 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47,
  3732. 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d,
  3733. 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
  3734. 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd,
  3735. 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7,
  3736. 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
  3737. 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525,
  3738. 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442,
  3739. 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
  3740. 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d,
  3741. 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299,
  3742. 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
  3743. 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a,
  3744. 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b,
  3745. 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
  3746. 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9,
  3747. 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6
  3748. };
  3749. memcpy (p, initialPValues, sizeof (p));
  3750. int i, j = 0;
  3751. for (i = 4; --i >= 0;)
  3752. {
  3753. s[i].malloc (256);
  3754. memcpy (s[i], initialSValues + i * 256, 256 * sizeof (uint32));
  3755. }
  3756. for (i = 0; i < 18; ++i)
  3757. {
  3758. uint32 d = 0;
  3759. for (int k = 0; k < 4; ++k)
  3760. {
  3761. d = (d << 8) | static_cast <const uint8*> (keyData)[j];
  3762. if (++j >= keyBytes)
  3763. j = 0;
  3764. }
  3765. p[i] = initialPValues[i] ^ d;
  3766. }
  3767. uint32 l = 0, r = 0;
  3768. for (i = 0; i < 18; i += 2)
  3769. {
  3770. encrypt (l, r);
  3771. p[i] = l;
  3772. p[i + 1] = r;
  3773. }
  3774. for (i = 0; i < 4; ++i)
  3775. {
  3776. for (j = 0; j < 256; j += 2)
  3777. {
  3778. encrypt (l, r);
  3779. s[i][j] = l;
  3780. s[i][j + 1] = r;
  3781. }
  3782. }
  3783. }
  3784. BlowFish::BlowFish (const BlowFish& other)
  3785. {
  3786. for (int i = 4; --i >= 0;)
  3787. s[i].malloc (256);
  3788. operator= (other);
  3789. }
  3790. BlowFish& BlowFish::operator= (const BlowFish& other)
  3791. {
  3792. memcpy (p, other.p, sizeof (p));
  3793. for (int i = 4; --i >= 0;)
  3794. memcpy (s[i], other.s[i], 256 * sizeof (uint32));
  3795. return *this;
  3796. }
  3797. BlowFish::~BlowFish()
  3798. {
  3799. }
  3800. uint32 BlowFish::F (const uint32 x) const throw()
  3801. {
  3802. return ((s[0][(x >> 24) & 0xff] + s[1][(x >> 16) & 0xff])
  3803. ^ s[2][(x >> 8) & 0xff]) + s[3][x & 0xff];
  3804. }
  3805. void BlowFish::encrypt (uint32& data1, uint32& data2) const throw()
  3806. {
  3807. uint32 l = data1;
  3808. uint32 r = data2;
  3809. for (int i = 0; i < 16; ++i)
  3810. {
  3811. l ^= p[i];
  3812. r ^= F(l);
  3813. swapVariables (l, r);
  3814. }
  3815. data1 = r ^ p[17];
  3816. data2 = l ^ p[16];
  3817. }
  3818. void BlowFish::decrypt (uint32& data1, uint32& data2) const throw()
  3819. {
  3820. uint32 l = data1;
  3821. uint32 r = data2;
  3822. for (int i = 17; i > 1; --i)
  3823. {
  3824. l ^= p[i];
  3825. r ^= F(l);
  3826. swapVariables (l, r);
  3827. }
  3828. data1 = r ^ p[0];
  3829. data2 = l ^ p[1];
  3830. }
  3831. END_JUCE_NAMESPACE
  3832. /*** End of inlined file: juce_BlowFish.cpp ***/
  3833. /*** Start of inlined file: juce_MD5.cpp ***/
  3834. BEGIN_JUCE_NAMESPACE
  3835. MD5::MD5()
  3836. {
  3837. zerostruct (result);
  3838. }
  3839. MD5::MD5 (const MD5& other)
  3840. {
  3841. memcpy (result, other.result, sizeof (result));
  3842. }
  3843. MD5& MD5::operator= (const MD5& other)
  3844. {
  3845. memcpy (result, other.result, sizeof (result));
  3846. return *this;
  3847. }
  3848. MD5::MD5 (const MemoryBlock& data)
  3849. {
  3850. ProcessContext context;
  3851. context.processBlock (data.getData(), data.getSize());
  3852. context.finish (result);
  3853. }
  3854. MD5::MD5 (const void* data, const size_t numBytes)
  3855. {
  3856. ProcessContext context;
  3857. context.processBlock (data, numBytes);
  3858. context.finish (result);
  3859. }
  3860. MD5::MD5 (const String& text)
  3861. {
  3862. ProcessContext context;
  3863. const int len = text.length();
  3864. const juce_wchar* const t = text;
  3865. for (int i = 0; i < len; ++i)
  3866. {
  3867. // force the string into integer-sized unicode characters, to try to make it
  3868. // get the same results on all platforms + compilers.
  3869. uint32 unicodeChar = ByteOrder::swapIfBigEndian ((uint32) t[i]);
  3870. context.processBlock (&unicodeChar, sizeof (unicodeChar));
  3871. }
  3872. context.finish (result);
  3873. }
  3874. void MD5::processStream (InputStream& input, int64 numBytesToRead)
  3875. {
  3876. ProcessContext context;
  3877. if (numBytesToRead < 0)
  3878. numBytesToRead = std::numeric_limits<int64>::max();
  3879. while (numBytesToRead > 0)
  3880. {
  3881. uint8 tempBuffer [512];
  3882. const int bytesRead = input.read (tempBuffer, (int) jmin (numBytesToRead, (int64) sizeof (tempBuffer)));
  3883. if (bytesRead <= 0)
  3884. break;
  3885. numBytesToRead -= bytesRead;
  3886. context.processBlock (tempBuffer, bytesRead);
  3887. }
  3888. context.finish (result);
  3889. }
  3890. MD5::MD5 (InputStream& input, int64 numBytesToRead)
  3891. {
  3892. processStream (input, numBytesToRead);
  3893. }
  3894. MD5::MD5 (const File& file)
  3895. {
  3896. const ScopedPointer <FileInputStream> fin (file.createInputStream());
  3897. if (fin != 0)
  3898. processStream (*fin, -1);
  3899. else
  3900. zerostruct (result);
  3901. }
  3902. MD5::~MD5()
  3903. {
  3904. }
  3905. namespace MD5Functions
  3906. {
  3907. static void encode (void* const output, const void* const input, const int numBytes) throw()
  3908. {
  3909. for (int i = 0; i < (numBytes >> 2); ++i)
  3910. static_cast<uint32*> (output)[i] = ByteOrder::swapIfBigEndian (static_cast<const uint32*> (input) [i]);
  3911. }
  3912. static inline uint32 F (const uint32 x, const uint32 y, const uint32 z) throw() { return (x & y) | (~x & z); }
  3913. static inline uint32 G (const uint32 x, const uint32 y, const uint32 z) throw() { return (x & z) | (y & ~z); }
  3914. static inline uint32 H (const uint32 x, const uint32 y, const uint32 z) throw() { return x ^ y ^ z; }
  3915. static inline uint32 I (const uint32 x, const uint32 y, const uint32 z) throw() { return y ^ (x | ~z); }
  3916. static inline uint32 rotateLeft (const uint32 x, const uint32 n) throw() { return (x << n) | (x >> (32 - n)); }
  3917. static void FF (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  3918. {
  3919. a += F (b, c, d) + x + ac;
  3920. a = rotateLeft (a, s) + b;
  3921. }
  3922. static void GG (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  3923. {
  3924. a += G (b, c, d) + x + ac;
  3925. a = rotateLeft (a, s) + b;
  3926. }
  3927. static void HH (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  3928. {
  3929. a += H (b, c, d) + x + ac;
  3930. a = rotateLeft (a, s) + b;
  3931. }
  3932. static void II (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  3933. {
  3934. a += I (b, c, d) + x + ac;
  3935. a = rotateLeft (a, s) + b;
  3936. }
  3937. }
  3938. MD5::ProcessContext::ProcessContext()
  3939. {
  3940. state[0] = 0x67452301;
  3941. state[1] = 0xefcdab89;
  3942. state[2] = 0x98badcfe;
  3943. state[3] = 0x10325476;
  3944. count[0] = 0;
  3945. count[1] = 0;
  3946. }
  3947. void MD5::ProcessContext::processBlock (const void* const data, const size_t dataSize)
  3948. {
  3949. int bufferPos = ((count[0] >> 3) & 0x3F);
  3950. count[0] += (uint32) (dataSize << 3);
  3951. if (count[0] < ((uint32) dataSize << 3))
  3952. count[1]++;
  3953. count[1] += (uint32) (dataSize >> 29);
  3954. const size_t spaceLeft = 64 - bufferPos;
  3955. size_t i = 0;
  3956. if (dataSize >= spaceLeft)
  3957. {
  3958. memcpy (buffer + bufferPos, data, spaceLeft);
  3959. transform (buffer);
  3960. for (i = spaceLeft; i + 64 <= dataSize; i += 64)
  3961. transform (static_cast <const char*> (data) + i);
  3962. bufferPos = 0;
  3963. }
  3964. memcpy (buffer + bufferPos, static_cast <const char*> (data) + i, dataSize - i);
  3965. }
  3966. void MD5::ProcessContext::finish (void* const result)
  3967. {
  3968. unsigned char encodedLength[8];
  3969. MD5Functions::encode (encodedLength, count, 8);
  3970. // Pad out to 56 mod 64.
  3971. const int index = (uint32) ((count[0] >> 3) & 0x3f);
  3972. const int paddingLength = (index < 56) ? (56 - index)
  3973. : (120 - index);
  3974. uint8 paddingBuffer [64];
  3975. zeromem (paddingBuffer, paddingLength);
  3976. paddingBuffer [0] = 0x80;
  3977. processBlock (paddingBuffer, paddingLength);
  3978. processBlock (encodedLength, 8);
  3979. MD5Functions::encode (result, state, 16);
  3980. zerostruct (buffer);
  3981. }
  3982. void MD5::ProcessContext::transform (const void* const bufferToTransform)
  3983. {
  3984. using namespace MD5Functions;
  3985. uint32 a = state[0];
  3986. uint32 b = state[1];
  3987. uint32 c = state[2];
  3988. uint32 d = state[3];
  3989. uint32 x[16];
  3990. encode (x, bufferToTransform, 64);
  3991. enum Constants
  3992. {
  3993. S11 = 7, S12 = 12, S13 = 17, S14 = 22, S21 = 5, S22 = 9, S23 = 14, S24 = 20,
  3994. S31 = 4, S32 = 11, S33 = 16, S34 = 23, S41 = 6, S42 = 10, S43 = 15, S44 = 21
  3995. };
  3996. FF (a, b, c, d, x[ 0], S11, 0xd76aa478); FF (d, a, b, c, x[ 1], S12, 0xe8c7b756);
  3997. FF (c, d, a, b, x[ 2], S13, 0x242070db); FF (b, c, d, a, x[ 3], S14, 0xc1bdceee);
  3998. FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); FF (d, a, b, c, x[ 5], S12, 0x4787c62a);
  3999. FF (c, d, a, b, x[ 6], S13, 0xa8304613); FF (b, c, d, a, x[ 7], S14, 0xfd469501);
  4000. FF (a, b, c, d, x[ 8], S11, 0x698098d8); FF (d, a, b, c, x[ 9], S12, 0x8b44f7af);
  4001. FF (c, d, a, b, x[10], S13, 0xffff5bb1); FF (b, c, d, a, x[11], S14, 0x895cd7be);
  4002. FF (a, b, c, d, x[12], S11, 0x6b901122); FF (d, a, b, c, x[13], S12, 0xfd987193);
  4003. FF (c, d, a, b, x[14], S13, 0xa679438e); FF (b, c, d, a, x[15], S14, 0x49b40821);
  4004. GG (a, b, c, d, x[ 1], S21, 0xf61e2562); GG (d, a, b, c, x[ 6], S22, 0xc040b340);
  4005. GG (c, d, a, b, x[11], S23, 0x265e5a51); GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa);
  4006. GG (a, b, c, d, x[ 5], S21, 0xd62f105d); GG (d, a, b, c, x[10], S22, 0x02441453);
  4007. GG (c, d, a, b, x[15], S23, 0xd8a1e681); GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8);
  4008. GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); GG (d, a, b, c, x[14], S22, 0xc33707d6);
  4009. GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); GG (b, c, d, a, x[ 8], S24, 0x455a14ed);
  4010. GG (a, b, c, d, x[13], S21, 0xa9e3e905); GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8);
  4011. GG (c, d, a, b, x[ 7], S23, 0x676f02d9); GG (b, c, d, a, x[12], S24, 0x8d2a4c8a);
  4012. HH (a, b, c, d, x[ 5], S31, 0xfffa3942); HH (d, a, b, c, x[ 8], S32, 0x8771f681);
  4013. HH (c, d, a, b, x[11], S33, 0x6d9d6122); HH (b, c, d, a, x[14], S34, 0xfde5380c);
  4014. HH (a, b, c, d, x[ 1], S31, 0xa4beea44); HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9);
  4015. HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); HH (b, c, d, a, x[10], S34, 0xbebfbc70);
  4016. HH (a, b, c, d, x[13], S31, 0x289b7ec6); HH (d, a, b, c, x[ 0], S32, 0xeaa127fa);
  4017. HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); HH (b, c, d, a, x[ 6], S34, 0x04881d05);
  4018. HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); HH (d, a, b, c, x[12], S32, 0xe6db99e5);
  4019. HH (c, d, a, b, x[15], S33, 0x1fa27cf8); HH (b, c, d, a, x[ 2], S34, 0xc4ac5665);
  4020. II (a, b, c, d, x[ 0], S41, 0xf4292244); II (d, a, b, c, x[ 7], S42, 0x432aff97);
  4021. II (c, d, a, b, x[14], S43, 0xab9423a7); II (b, c, d, a, x[ 5], S44, 0xfc93a039);
  4022. II (a, b, c, d, x[12], S41, 0x655b59c3); II (d, a, b, c, x[ 3], S42, 0x8f0ccc92);
  4023. II (c, d, a, b, x[10], S43, 0xffeff47d); II (b, c, d, a, x[ 1], S44, 0x85845dd1);
  4024. II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); II (d, a, b, c, x[15], S42, 0xfe2ce6e0);
  4025. II (c, d, a, b, x[ 6], S43, 0xa3014314); II (b, c, d, a, x[13], S44, 0x4e0811a1);
  4026. II (a, b, c, d, x[ 4], S41, 0xf7537e82); II (d, a, b, c, x[11], S42, 0xbd3af235);
  4027. II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); II (b, c, d, a, x[ 9], S44, 0xeb86d391);
  4028. state[0] += a;
  4029. state[1] += b;
  4030. state[2] += c;
  4031. state[3] += d;
  4032. zerostruct (x);
  4033. }
  4034. const MemoryBlock MD5::getRawChecksumData() const
  4035. {
  4036. return MemoryBlock (result, sizeof (result));
  4037. }
  4038. const String MD5::toHexString() const
  4039. {
  4040. return String::toHexString (result, sizeof (result), 0);
  4041. }
  4042. bool MD5::operator== (const MD5& other) const
  4043. {
  4044. return memcmp (result, other.result, sizeof (result)) == 0;
  4045. }
  4046. bool MD5::operator!= (const MD5& other) const
  4047. {
  4048. return ! operator== (other);
  4049. }
  4050. END_JUCE_NAMESPACE
  4051. /*** End of inlined file: juce_MD5.cpp ***/
  4052. /*** Start of inlined file: juce_Primes.cpp ***/
  4053. BEGIN_JUCE_NAMESPACE
  4054. namespace PrimesHelpers
  4055. {
  4056. static void createSmallSieve (const int numBits, BigInteger& result)
  4057. {
  4058. result.setBit (numBits);
  4059. result.clearBit (numBits); // to enlarge the array
  4060. result.setBit (0);
  4061. int n = 2;
  4062. do
  4063. {
  4064. for (int i = n + n; i < numBits; i += n)
  4065. result.setBit (i);
  4066. n = result.findNextClearBit (n + 1);
  4067. }
  4068. while (n <= (numBits >> 1));
  4069. }
  4070. static void bigSieve (const BigInteger& base, const int numBits, BigInteger& result,
  4071. const BigInteger& smallSieve, const int smallSieveSize)
  4072. {
  4073. jassert (! base[0]); // must be even!
  4074. result.setBit (numBits);
  4075. result.clearBit (numBits); // to enlarge the array
  4076. int index = smallSieve.findNextClearBit (0);
  4077. do
  4078. {
  4079. const int prime = (index << 1) + 1;
  4080. BigInteger r (base), remainder;
  4081. r.divideBy (prime, remainder);
  4082. int i = prime - remainder.getBitRangeAsInt (0, 32);
  4083. if (r.isZero())
  4084. i += prime;
  4085. if ((i & 1) == 0)
  4086. i += prime;
  4087. i = (i - 1) >> 1;
  4088. while (i < numBits)
  4089. {
  4090. result.setBit (i);
  4091. i += prime;
  4092. }
  4093. index = smallSieve.findNextClearBit (index + 1);
  4094. }
  4095. while (index < smallSieveSize);
  4096. }
  4097. static bool findCandidate (const BigInteger& base, const BigInteger& sieve,
  4098. const int numBits, BigInteger& result, const int certainty)
  4099. {
  4100. for (int i = 0; i < numBits; ++i)
  4101. {
  4102. if (! sieve[i])
  4103. {
  4104. result = base + (unsigned int) ((i << 1) + 1);
  4105. if (Primes::isProbablyPrime (result, certainty))
  4106. return true;
  4107. }
  4108. }
  4109. return false;
  4110. }
  4111. static bool passesMillerRabin (const BigInteger& n, int iterations)
  4112. {
  4113. const BigInteger one (1), two (2);
  4114. const BigInteger nMinusOne (n - one);
  4115. BigInteger d (nMinusOne);
  4116. const int s = d.findNextSetBit (0);
  4117. d >>= s;
  4118. BigInteger smallPrimes;
  4119. int numBitsInSmallPrimes = 0;
  4120. for (;;)
  4121. {
  4122. numBitsInSmallPrimes += 256;
  4123. createSmallSieve (numBitsInSmallPrimes, smallPrimes);
  4124. const int numPrimesFound = numBitsInSmallPrimes - smallPrimes.countNumberOfSetBits();
  4125. if (numPrimesFound > iterations + 1)
  4126. break;
  4127. }
  4128. int smallPrime = 2;
  4129. while (--iterations >= 0)
  4130. {
  4131. smallPrime = smallPrimes.findNextClearBit (smallPrime + 1);
  4132. BigInteger r (smallPrime);
  4133. r.exponentModulo (d, n);
  4134. if (r != one && r != nMinusOne)
  4135. {
  4136. for (int j = 0; j < s; ++j)
  4137. {
  4138. r.exponentModulo (two, n);
  4139. if (r == nMinusOne)
  4140. break;
  4141. }
  4142. if (r != nMinusOne)
  4143. return false;
  4144. }
  4145. }
  4146. return true;
  4147. }
  4148. }
  4149. const BigInteger Primes::createProbablePrime (const int bitLength,
  4150. const int certainty,
  4151. const int* randomSeeds,
  4152. int numRandomSeeds)
  4153. {
  4154. using namespace PrimesHelpers;
  4155. int defaultSeeds [16];
  4156. if (numRandomSeeds <= 0)
  4157. {
  4158. randomSeeds = defaultSeeds;
  4159. numRandomSeeds = numElementsInArray (defaultSeeds);
  4160. Random r (0);
  4161. for (int j = 10; --j >= 0;)
  4162. {
  4163. r.setSeedRandomly();
  4164. for (int i = numRandomSeeds; --i >= 0;)
  4165. defaultSeeds[i] ^= r.nextInt() ^ Random::getSystemRandom().nextInt();
  4166. }
  4167. }
  4168. BigInteger smallSieve;
  4169. const int smallSieveSize = 15000;
  4170. createSmallSieve (smallSieveSize, smallSieve);
  4171. BigInteger p;
  4172. for (int i = numRandomSeeds; --i >= 0;)
  4173. {
  4174. BigInteger p2;
  4175. Random r (randomSeeds[i]);
  4176. r.fillBitsRandomly (p2, 0, bitLength);
  4177. p ^= p2;
  4178. }
  4179. p.setBit (bitLength - 1);
  4180. p.clearBit (0);
  4181. const int searchLen = jmax (1024, (bitLength / 20) * 64);
  4182. while (p.getHighestBit() < bitLength)
  4183. {
  4184. p += 2 * searchLen;
  4185. BigInteger sieve;
  4186. bigSieve (p, searchLen, sieve,
  4187. smallSieve, smallSieveSize);
  4188. BigInteger candidate;
  4189. if (findCandidate (p, sieve, searchLen, candidate, certainty))
  4190. return candidate;
  4191. }
  4192. jassertfalse;
  4193. return BigInteger();
  4194. }
  4195. bool Primes::isProbablyPrime (const BigInteger& number, const int certainty)
  4196. {
  4197. using namespace PrimesHelpers;
  4198. if (! number[0])
  4199. return false;
  4200. if (number.getHighestBit() <= 10)
  4201. {
  4202. const int num = number.getBitRangeAsInt (0, 10);
  4203. for (int i = num / 2; --i > 1;)
  4204. if (num % i == 0)
  4205. return false;
  4206. return true;
  4207. }
  4208. else
  4209. {
  4210. if (number.findGreatestCommonDivisor (2 * 3 * 5 * 7 * 11 * 13 * 17 * 19 * 23) != 1)
  4211. return false;
  4212. return passesMillerRabin (number, certainty);
  4213. }
  4214. }
  4215. END_JUCE_NAMESPACE
  4216. /*** End of inlined file: juce_Primes.cpp ***/
  4217. /*** Start of inlined file: juce_RSAKey.cpp ***/
  4218. BEGIN_JUCE_NAMESPACE
  4219. RSAKey::RSAKey()
  4220. {
  4221. }
  4222. RSAKey::RSAKey (const String& s)
  4223. {
  4224. if (s.containsChar (','))
  4225. {
  4226. part1.parseString (s.upToFirstOccurrenceOf (",", false, false), 16);
  4227. part2.parseString (s.fromFirstOccurrenceOf (",", false, false), 16);
  4228. }
  4229. else
  4230. {
  4231. // the string needs to be two hex numbers, comma-separated..
  4232. jassertfalse;
  4233. }
  4234. }
  4235. RSAKey::~RSAKey()
  4236. {
  4237. }
  4238. bool RSAKey::operator== (const RSAKey& other) const throw()
  4239. {
  4240. return part1 == other.part1 && part2 == other.part2;
  4241. }
  4242. bool RSAKey::operator!= (const RSAKey& other) const throw()
  4243. {
  4244. return ! operator== (other);
  4245. }
  4246. const String RSAKey::toString() const
  4247. {
  4248. return part1.toString (16) + "," + part2.toString (16);
  4249. }
  4250. bool RSAKey::applyToValue (BigInteger& value) const
  4251. {
  4252. if (part1.isZero() || part2.isZero() || value <= 0)
  4253. {
  4254. jassertfalse; // using an uninitialised key
  4255. value.clear();
  4256. return false;
  4257. }
  4258. BigInteger result;
  4259. while (! value.isZero())
  4260. {
  4261. result *= part2;
  4262. BigInteger remainder;
  4263. value.divideBy (part2, remainder);
  4264. remainder.exponentModulo (part1, part2);
  4265. result += remainder;
  4266. }
  4267. value.swapWith (result);
  4268. return true;
  4269. }
  4270. static const BigInteger findBestCommonDivisor (const BigInteger& p, const BigInteger& q)
  4271. {
  4272. // try 3, 5, 9, 17, etc first because these only contain 2 bits and so
  4273. // are fast to divide + multiply
  4274. for (int i = 2; i <= 65536; i *= 2)
  4275. {
  4276. const BigInteger e (1 + i);
  4277. if (e.findGreatestCommonDivisor (p).isOne() && e.findGreatestCommonDivisor (q).isOne())
  4278. return e;
  4279. }
  4280. BigInteger e (4);
  4281. while (! (e.findGreatestCommonDivisor (p).isOne() && e.findGreatestCommonDivisor (q).isOne()))
  4282. ++e;
  4283. return e;
  4284. }
  4285. void RSAKey::createKeyPair (RSAKey& publicKey, RSAKey& privateKey,
  4286. const int numBits, const int* randomSeeds, const int numRandomSeeds)
  4287. {
  4288. jassert (numBits > 16); // not much point using less than this..
  4289. BigInteger p (Primes::createProbablePrime (numBits / 2, 30, randomSeeds, numRandomSeeds));
  4290. BigInteger q (Primes::createProbablePrime (numBits - numBits / 2, 30, randomSeeds, numRandomSeeds));
  4291. const BigInteger n (p * q);
  4292. const BigInteger m (--p * --q);
  4293. const BigInteger e (findBestCommonDivisor (p, q));
  4294. BigInteger d (e);
  4295. d.inverseModulo (m);
  4296. publicKey.part1 = e;
  4297. publicKey.part2 = n;
  4298. privateKey.part1 = d;
  4299. privateKey.part2 = n;
  4300. }
  4301. END_JUCE_NAMESPACE
  4302. /*** End of inlined file: juce_RSAKey.cpp ***/
  4303. /*** Start of inlined file: juce_InputStream.cpp ***/
  4304. BEGIN_JUCE_NAMESPACE
  4305. char InputStream::readByte()
  4306. {
  4307. char temp = 0;
  4308. read (&temp, 1);
  4309. return temp;
  4310. }
  4311. bool InputStream::readBool()
  4312. {
  4313. return readByte() != 0;
  4314. }
  4315. short InputStream::readShort()
  4316. {
  4317. char temp[2];
  4318. if (read (temp, 2) == 2)
  4319. return (short) ByteOrder::littleEndianShort (temp);
  4320. return 0;
  4321. }
  4322. short InputStream::readShortBigEndian()
  4323. {
  4324. char temp[2];
  4325. if (read (temp, 2) == 2)
  4326. return (short) ByteOrder::bigEndianShort (temp);
  4327. return 0;
  4328. }
  4329. int InputStream::readInt()
  4330. {
  4331. char temp[4];
  4332. if (read (temp, 4) == 4)
  4333. return (int) ByteOrder::littleEndianInt (temp);
  4334. return 0;
  4335. }
  4336. int InputStream::readIntBigEndian()
  4337. {
  4338. char temp[4];
  4339. if (read (temp, 4) == 4)
  4340. return (int) ByteOrder::bigEndianInt (temp);
  4341. return 0;
  4342. }
  4343. int InputStream::readCompressedInt()
  4344. {
  4345. const unsigned char sizeByte = readByte();
  4346. if (sizeByte == 0)
  4347. return 0;
  4348. const int numBytes = (sizeByte & 0x7f);
  4349. if (numBytes > 4)
  4350. {
  4351. jassertfalse; // trying to read corrupt data - this method must only be used
  4352. // to read data that was written by OutputStream::writeCompressedInt()
  4353. return 0;
  4354. }
  4355. char bytes[4] = { 0, 0, 0, 0 };
  4356. if (read (bytes, numBytes) != numBytes)
  4357. return 0;
  4358. const int num = (int) ByteOrder::littleEndianInt (bytes);
  4359. return (sizeByte >> 7) ? -num : num;
  4360. }
  4361. int64 InputStream::readInt64()
  4362. {
  4363. union { uint8 asBytes[8]; uint64 asInt64; } n;
  4364. if (read (n.asBytes, 8) == 8)
  4365. return (int64) ByteOrder::swapIfBigEndian (n.asInt64);
  4366. return 0;
  4367. }
  4368. int64 InputStream::readInt64BigEndian()
  4369. {
  4370. union { uint8 asBytes[8]; uint64 asInt64; } n;
  4371. if (read (n.asBytes, 8) == 8)
  4372. return (int64) ByteOrder::swapIfLittleEndian (n.asInt64);
  4373. return 0;
  4374. }
  4375. float InputStream::readFloat()
  4376. {
  4377. // the union below relies on these types being the same size...
  4378. static_jassert (sizeof (int32) == sizeof (float));
  4379. union { int32 asInt; float asFloat; } n;
  4380. n.asInt = (int32) readInt();
  4381. return n.asFloat;
  4382. }
  4383. float InputStream::readFloatBigEndian()
  4384. {
  4385. union { int32 asInt; float asFloat; } n;
  4386. n.asInt = (int32) readIntBigEndian();
  4387. return n.asFloat;
  4388. }
  4389. double InputStream::readDouble()
  4390. {
  4391. union { int64 asInt; double asDouble; } n;
  4392. n.asInt = readInt64();
  4393. return n.asDouble;
  4394. }
  4395. double InputStream::readDoubleBigEndian()
  4396. {
  4397. union { int64 asInt; double asDouble; } n;
  4398. n.asInt = readInt64BigEndian();
  4399. return n.asDouble;
  4400. }
  4401. const String InputStream::readString()
  4402. {
  4403. MemoryBlock buffer (256);
  4404. char* data = static_cast<char*> (buffer.getData());
  4405. size_t i = 0;
  4406. while ((data[i] = readByte()) != 0)
  4407. {
  4408. if (++i >= buffer.getSize())
  4409. {
  4410. buffer.setSize (buffer.getSize() + 512);
  4411. data = static_cast<char*> (buffer.getData());
  4412. }
  4413. }
  4414. return String::fromUTF8 (data, (int) i);
  4415. }
  4416. const String InputStream::readNextLine()
  4417. {
  4418. MemoryBlock buffer (256);
  4419. char* data = static_cast<char*> (buffer.getData());
  4420. size_t i = 0;
  4421. while ((data[i] = readByte()) != 0)
  4422. {
  4423. if (data[i] == '\n')
  4424. break;
  4425. if (data[i] == '\r')
  4426. {
  4427. const int64 lastPos = getPosition();
  4428. if (readByte() != '\n')
  4429. setPosition (lastPos);
  4430. break;
  4431. }
  4432. if (++i >= buffer.getSize())
  4433. {
  4434. buffer.setSize (buffer.getSize() + 512);
  4435. data = static_cast<char*> (buffer.getData());
  4436. }
  4437. }
  4438. return String::fromUTF8 (data, (int) i);
  4439. }
  4440. int InputStream::readIntoMemoryBlock (MemoryBlock& block, int numBytes)
  4441. {
  4442. const int64 totalLength = getTotalLength();
  4443. if (totalLength >= 0)
  4444. {
  4445. const int totalBytesRemaining = (int) jmin ((int64) 0x7fffffff,
  4446. totalLength - getPosition());
  4447. if (numBytes < 0)
  4448. numBytes = totalBytesRemaining;
  4449. else if (numBytes > 0)
  4450. numBytes = jmin (numBytes, totalBytesRemaining);
  4451. else
  4452. return 0;
  4453. }
  4454. const size_t originalBlockSize = block.getSize();
  4455. int totalBytesRead = 0;
  4456. if (numBytes > 0)
  4457. {
  4458. // know how many bytes we want, so we can resize the block first..
  4459. block.setSize (originalBlockSize + numBytes, false);
  4460. totalBytesRead = read (static_cast<char*> (block.getData()) + originalBlockSize, numBytes);
  4461. }
  4462. else
  4463. {
  4464. // read until end of stram..
  4465. const int chunkSize = 32768;
  4466. for (;;)
  4467. {
  4468. block.ensureSize (originalBlockSize + totalBytesRead + chunkSize, false);
  4469. const int bytesJustIn = read (static_cast<char*> (block.getData())
  4470. + originalBlockSize
  4471. + totalBytesRead,
  4472. chunkSize);
  4473. if (bytesJustIn == 0)
  4474. break;
  4475. totalBytesRead += bytesJustIn;
  4476. }
  4477. }
  4478. // trim off any excess left at the end
  4479. block.setSize (originalBlockSize + totalBytesRead, false);
  4480. return totalBytesRead;
  4481. }
  4482. const String InputStream::readEntireStreamAsString()
  4483. {
  4484. MemoryBlock mb;
  4485. const int size = readIntoMemoryBlock (mb);
  4486. return String::createStringFromData (static_cast<const char*> (mb.getData()), size);
  4487. }
  4488. void InputStream::skipNextBytes (int64 numBytesToSkip)
  4489. {
  4490. if (numBytesToSkip > 0)
  4491. {
  4492. const int skipBufferSize = (int) jmin (numBytesToSkip, (int64) 16384);
  4493. HeapBlock<char> temp (skipBufferSize);
  4494. while (numBytesToSkip > 0 && ! isExhausted())
  4495. numBytesToSkip -= read (temp, (int) jmin (numBytesToSkip, (int64) skipBufferSize));
  4496. }
  4497. }
  4498. END_JUCE_NAMESPACE
  4499. /*** End of inlined file: juce_InputStream.cpp ***/
  4500. /*** Start of inlined file: juce_OutputStream.cpp ***/
  4501. BEGIN_JUCE_NAMESPACE
  4502. #if JUCE_DEBUG
  4503. static CriticalSection activeStreamLock;
  4504. static Array<void*> activeStreams;
  4505. void juce_CheckForDanglingStreams()
  4506. {
  4507. /*
  4508. It's always a bad idea to leak any object, but if you're leaking output
  4509. streams, then there's a good chance that you're failing to flush a file
  4510. to disk properly, which could result in corrupted data and other similar
  4511. nastiness..
  4512. */
  4513. jassert (activeStreams.size() == 0);
  4514. };
  4515. #endif
  4516. OutputStream::OutputStream()
  4517. {
  4518. #if JUCE_DEBUG
  4519. const ScopedLock sl (activeStreamLock);
  4520. activeStreams.add (this);
  4521. #endif
  4522. }
  4523. OutputStream::~OutputStream()
  4524. {
  4525. #if JUCE_DEBUG
  4526. const ScopedLock sl (activeStreamLock);
  4527. activeStreams.removeValue (this);
  4528. #endif
  4529. }
  4530. void OutputStream::writeBool (const bool b)
  4531. {
  4532. writeByte (b ? (char) 1
  4533. : (char) 0);
  4534. }
  4535. void OutputStream::writeByte (char byte)
  4536. {
  4537. write (&byte, 1);
  4538. }
  4539. void OutputStream::writeShort (short value)
  4540. {
  4541. const unsigned short v = ByteOrder::swapIfBigEndian ((unsigned short) value);
  4542. write (&v, 2);
  4543. }
  4544. void OutputStream::writeShortBigEndian (short value)
  4545. {
  4546. const unsigned short v = ByteOrder::swapIfLittleEndian ((unsigned short) value);
  4547. write (&v, 2);
  4548. }
  4549. void OutputStream::writeInt (int value)
  4550. {
  4551. const unsigned int v = ByteOrder::swapIfBigEndian ((unsigned int) value);
  4552. write (&v, 4);
  4553. }
  4554. void OutputStream::writeIntBigEndian (int value)
  4555. {
  4556. const unsigned int v = ByteOrder::swapIfLittleEndian ((unsigned int) value);
  4557. write (&v, 4);
  4558. }
  4559. void OutputStream::writeCompressedInt (int value)
  4560. {
  4561. unsigned int un = (value < 0) ? (unsigned int) -value
  4562. : (unsigned int) value;
  4563. uint8 data[5];
  4564. int num = 0;
  4565. while (un > 0)
  4566. {
  4567. data[++num] = (uint8) un;
  4568. un >>= 8;
  4569. }
  4570. data[0] = (uint8) num;
  4571. if (value < 0)
  4572. data[0] |= 0x80;
  4573. write (data, num + 1);
  4574. }
  4575. void OutputStream::writeInt64 (int64 value)
  4576. {
  4577. const uint64 v = ByteOrder::swapIfBigEndian ((uint64) value);
  4578. write (&v, 8);
  4579. }
  4580. void OutputStream::writeInt64BigEndian (int64 value)
  4581. {
  4582. const uint64 v = ByteOrder::swapIfLittleEndian ((uint64) value);
  4583. write (&v, 8);
  4584. }
  4585. void OutputStream::writeFloat (float value)
  4586. {
  4587. union { int asInt; float asFloat; } n;
  4588. n.asFloat = value;
  4589. writeInt (n.asInt);
  4590. }
  4591. void OutputStream::writeFloatBigEndian (float value)
  4592. {
  4593. union { int asInt; float asFloat; } n;
  4594. n.asFloat = value;
  4595. writeIntBigEndian (n.asInt);
  4596. }
  4597. void OutputStream::writeDouble (double value)
  4598. {
  4599. union { int64 asInt; double asDouble; } n;
  4600. n.asDouble = value;
  4601. writeInt64 (n.asInt);
  4602. }
  4603. void OutputStream::writeDoubleBigEndian (double value)
  4604. {
  4605. union { int64 asInt; double asDouble; } n;
  4606. n.asDouble = value;
  4607. writeInt64BigEndian (n.asInt);
  4608. }
  4609. void OutputStream::writeString (const String& text)
  4610. {
  4611. // (This avoids using toUTF8() to prevent the memory bloat that it would leave behind
  4612. // if lots of large, persistent strings were to be written to streams).
  4613. const int numBytes = text.getNumBytesAsUTF8() + 1;
  4614. HeapBlock<char> temp (numBytes);
  4615. text.copyToUTF8 (temp, numBytes);
  4616. write (temp, numBytes);
  4617. }
  4618. void OutputStream::writeText (const String& text, const bool asUnicode,
  4619. const bool writeUnicodeHeaderBytes)
  4620. {
  4621. if (asUnicode)
  4622. {
  4623. if (writeUnicodeHeaderBytes)
  4624. write ("\x0ff\x0fe", 2);
  4625. const juce_wchar* src = text;
  4626. bool lastCharWasReturn = false;
  4627. while (*src != 0)
  4628. {
  4629. if (*src == L'\n' && ! lastCharWasReturn)
  4630. writeShort ((short) L'\r');
  4631. lastCharWasReturn = (*src == L'\r');
  4632. writeShort ((short) *src++);
  4633. }
  4634. }
  4635. else
  4636. {
  4637. const char* src = text.toUTF8();
  4638. const char* t = src;
  4639. for (;;)
  4640. {
  4641. if (*t == '\n')
  4642. {
  4643. if (t > src)
  4644. write (src, (int) (t - src));
  4645. write ("\r\n", 2);
  4646. src = t + 1;
  4647. }
  4648. else if (*t == '\r')
  4649. {
  4650. if (t[1] == '\n')
  4651. ++t;
  4652. }
  4653. else if (*t == 0)
  4654. {
  4655. if (t > src)
  4656. write (src, (int) (t - src));
  4657. break;
  4658. }
  4659. ++t;
  4660. }
  4661. }
  4662. }
  4663. int OutputStream::writeFromInputStream (InputStream& source, int64 numBytesToWrite)
  4664. {
  4665. if (numBytesToWrite < 0)
  4666. numBytesToWrite = std::numeric_limits<int64>::max();
  4667. int numWritten = 0;
  4668. while (numBytesToWrite > 0 && ! source.isExhausted())
  4669. {
  4670. char buffer [8192];
  4671. const int num = source.read (buffer, (int) jmin (numBytesToWrite, (int64) sizeof (buffer)));
  4672. if (num <= 0)
  4673. break;
  4674. write (buffer, num);
  4675. numBytesToWrite -= num;
  4676. numWritten += num;
  4677. }
  4678. return numWritten;
  4679. }
  4680. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const int number)
  4681. {
  4682. return stream << String (number);
  4683. }
  4684. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const double number)
  4685. {
  4686. return stream << String (number);
  4687. }
  4688. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char character)
  4689. {
  4690. stream.writeByte (character);
  4691. return stream;
  4692. }
  4693. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char* const text)
  4694. {
  4695. stream.write (text, (int) strlen (text));
  4696. return stream;
  4697. }
  4698. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryBlock& data)
  4699. {
  4700. stream.write (data.getData(), (int) data.getSize());
  4701. return stream;
  4702. }
  4703. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const File& fileToRead)
  4704. {
  4705. const ScopedPointer<FileInputStream> in (fileToRead.createInputStream());
  4706. if (in != 0)
  4707. stream.writeFromInputStream (*in, -1);
  4708. return stream;
  4709. }
  4710. END_JUCE_NAMESPACE
  4711. /*** End of inlined file: juce_OutputStream.cpp ***/
  4712. /*** Start of inlined file: juce_DirectoryIterator.cpp ***/
  4713. BEGIN_JUCE_NAMESPACE
  4714. DirectoryIterator::DirectoryIterator (const File& directory,
  4715. bool isRecursive_,
  4716. const String& wildCard_,
  4717. const int whatToLookFor_)
  4718. : fileFinder (directory, isRecursive_ ? "*" : wildCard_),
  4719. wildCard (wildCard_),
  4720. path (File::addTrailingSeparator (directory.getFullPathName())),
  4721. index (-1),
  4722. totalNumFiles (-1),
  4723. whatToLookFor (whatToLookFor_),
  4724. isRecursive (isRecursive_)
  4725. {
  4726. // you have to specify the type of files you're looking for!
  4727. jassert ((whatToLookFor_ & (File::findFiles | File::findDirectories)) != 0);
  4728. jassert (whatToLookFor_ > 0 && whatToLookFor_ <= 7);
  4729. }
  4730. DirectoryIterator::~DirectoryIterator()
  4731. {
  4732. }
  4733. bool DirectoryIterator::next()
  4734. {
  4735. return next (0, 0, 0, 0, 0, 0);
  4736. }
  4737. bool DirectoryIterator::next (bool* const isDirResult, bool* const isHiddenResult, int64* const fileSize,
  4738. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  4739. {
  4740. if (subIterator != 0)
  4741. {
  4742. if (subIterator->next (isDirResult, isHiddenResult, fileSize, modTime, creationTime, isReadOnly))
  4743. return true;
  4744. subIterator = 0;
  4745. }
  4746. String filename;
  4747. bool isDirectory, isHidden;
  4748. while (fileFinder.next (filename, &isDirectory, &isHidden, fileSize, modTime, creationTime, isReadOnly))
  4749. {
  4750. ++index;
  4751. if (! filename.containsOnly ("."))
  4752. {
  4753. const File fileFound (path + filename, 0);
  4754. bool matches = false;
  4755. if (isDirectory)
  4756. {
  4757. if (isRecursive && ((whatToLookFor & File::ignoreHiddenFiles) == 0 || ! isHidden))
  4758. subIterator = new DirectoryIterator (fileFound, true, wildCard, whatToLookFor);
  4759. matches = (whatToLookFor & File::findDirectories) != 0;
  4760. }
  4761. else
  4762. {
  4763. matches = (whatToLookFor & File::findFiles) != 0;
  4764. }
  4765. // if recursive, we're not relying on the OS iterator to do the wildcard match, so do it now..
  4766. if (matches && isRecursive)
  4767. matches = filename.matchesWildcard (wildCard, ! File::areFileNamesCaseSensitive());
  4768. if (matches && (whatToLookFor & File::ignoreHiddenFiles) != 0)
  4769. matches = ! isHidden;
  4770. if (matches)
  4771. {
  4772. currentFile = fileFound;
  4773. if (isHiddenResult != 0) *isHiddenResult = isHidden;
  4774. if (isDirResult != 0) *isDirResult = isDirectory;
  4775. return true;
  4776. }
  4777. else if (subIterator != 0)
  4778. {
  4779. return next();
  4780. }
  4781. }
  4782. }
  4783. return false;
  4784. }
  4785. const File DirectoryIterator::getFile() const
  4786. {
  4787. if (subIterator != 0)
  4788. return subIterator->getFile();
  4789. return currentFile;
  4790. }
  4791. float DirectoryIterator::getEstimatedProgress() const
  4792. {
  4793. if (totalNumFiles < 0)
  4794. totalNumFiles = File (path).getNumberOfChildFiles (File::findFilesAndDirectories);
  4795. if (totalNumFiles <= 0)
  4796. return 0.0f;
  4797. const float detailedIndex = (subIterator != 0) ? index + subIterator->getEstimatedProgress()
  4798. : (float) index;
  4799. return detailedIndex / totalNumFiles;
  4800. }
  4801. END_JUCE_NAMESPACE
  4802. /*** End of inlined file: juce_DirectoryIterator.cpp ***/
  4803. /*** Start of inlined file: juce_File.cpp ***/
  4804. #if ! JUCE_WINDOWS
  4805. #include <pwd.h>
  4806. #endif
  4807. BEGIN_JUCE_NAMESPACE
  4808. File::File (const String& fullPathName)
  4809. : fullPath (parseAbsolutePath (fullPathName))
  4810. {
  4811. }
  4812. File::File (const String& path, int)
  4813. : fullPath (path)
  4814. {
  4815. }
  4816. const File File::createFileWithoutCheckingPath (const String& path)
  4817. {
  4818. return File (path, 0);
  4819. }
  4820. File::File (const File& other)
  4821. : fullPath (other.fullPath)
  4822. {
  4823. }
  4824. File& File::operator= (const String& newPath)
  4825. {
  4826. fullPath = parseAbsolutePath (newPath);
  4827. return *this;
  4828. }
  4829. File& File::operator= (const File& other)
  4830. {
  4831. fullPath = other.fullPath;
  4832. return *this;
  4833. }
  4834. const File File::nonexistent;
  4835. const String File::parseAbsolutePath (const String& p)
  4836. {
  4837. if (p.isEmpty())
  4838. return String::empty;
  4839. #if JUCE_WINDOWS
  4840. // Windows..
  4841. String path (p.replaceCharacter ('/', '\\'));
  4842. if (path.startsWithChar (File::separator))
  4843. {
  4844. if (path[1] != File::separator)
  4845. {
  4846. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  4847. If you're trying to parse a string that may be either a relative path or an absolute path,
  4848. you MUST provide a context against which the partial path can be evaluated - you can do
  4849. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  4850. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  4851. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  4852. */
  4853. jassertfalse;
  4854. path = File::getCurrentWorkingDirectory().getFullPathName().substring (0, 2) + path;
  4855. }
  4856. }
  4857. else if (! path.containsChar (':'))
  4858. {
  4859. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  4860. If you're trying to parse a string that may be either a relative path or an absolute path,
  4861. you MUST provide a context against which the partial path can be evaluated - you can do
  4862. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  4863. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  4864. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  4865. */
  4866. jassertfalse;
  4867. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  4868. }
  4869. #else
  4870. // Mac or Linux..
  4871. String path (p.replaceCharacter ('\\', '/'));
  4872. if (path.startsWithChar ('~'))
  4873. {
  4874. if (path[1] == File::separator || path[1] == 0)
  4875. {
  4876. // expand a name of the form "~/abc"
  4877. path = File::getSpecialLocation (File::userHomeDirectory).getFullPathName()
  4878. + path.substring (1);
  4879. }
  4880. else
  4881. {
  4882. // expand a name of type "~dave/abc"
  4883. const String userName (path.substring (1).upToFirstOccurrenceOf ("/", false, false));
  4884. struct passwd* const pw = getpwnam (userName.toUTF8());
  4885. if (pw != 0)
  4886. path = addTrailingSeparator (pw->pw_dir) + path.fromFirstOccurrenceOf ("/", false, false);
  4887. }
  4888. }
  4889. else if (! path.startsWithChar (File::separator))
  4890. {
  4891. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  4892. If you're trying to parse a string that may be either a relative path or an absolute path,
  4893. you MUST provide a context against which the partial path can be evaluated - you can do
  4894. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  4895. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  4896. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  4897. */
  4898. jassert (path.startsWith ("./") || path.startsWith ("../")); // (assume that a path "./xyz" is deliberately intended to be relative to the CWD)
  4899. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  4900. }
  4901. #endif
  4902. return path.trimCharactersAtEnd (separatorString);
  4903. }
  4904. const String File::addTrailingSeparator (const String& path)
  4905. {
  4906. return path.endsWithChar (File::separator) ? path
  4907. : path + File::separator;
  4908. }
  4909. #if JUCE_LINUX
  4910. #define NAMES_ARE_CASE_SENSITIVE 1
  4911. #endif
  4912. bool File::areFileNamesCaseSensitive()
  4913. {
  4914. #if NAMES_ARE_CASE_SENSITIVE
  4915. return true;
  4916. #else
  4917. return false;
  4918. #endif
  4919. }
  4920. bool File::operator== (const File& other) const
  4921. {
  4922. #if NAMES_ARE_CASE_SENSITIVE
  4923. return fullPath == other.fullPath;
  4924. #else
  4925. return fullPath.equalsIgnoreCase (other.fullPath);
  4926. #endif
  4927. }
  4928. bool File::operator!= (const File& other) const
  4929. {
  4930. return ! operator== (other);
  4931. }
  4932. bool File::operator< (const File& other) const
  4933. {
  4934. #if NAMES_ARE_CASE_SENSITIVE
  4935. return fullPath < other.fullPath;
  4936. #else
  4937. return fullPath.compareIgnoreCase (other.fullPath) < 0;
  4938. #endif
  4939. }
  4940. bool File::operator> (const File& other) const
  4941. {
  4942. #if NAMES_ARE_CASE_SENSITIVE
  4943. return fullPath > other.fullPath;
  4944. #else
  4945. return fullPath.compareIgnoreCase (other.fullPath) > 0;
  4946. #endif
  4947. }
  4948. bool File::setReadOnly (const bool shouldBeReadOnly,
  4949. const bool applyRecursively) const
  4950. {
  4951. bool worked = true;
  4952. if (applyRecursively && isDirectory())
  4953. {
  4954. Array <File> subFiles;
  4955. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  4956. for (int i = subFiles.size(); --i >= 0;)
  4957. worked = subFiles.getReference(i).setReadOnly (shouldBeReadOnly, true) && worked;
  4958. }
  4959. return setFileReadOnlyInternal (shouldBeReadOnly) && worked;
  4960. }
  4961. bool File::deleteRecursively() const
  4962. {
  4963. bool worked = true;
  4964. if (isDirectory())
  4965. {
  4966. Array<File> subFiles;
  4967. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  4968. for (int i = subFiles.size(); --i >= 0;)
  4969. worked = subFiles.getReference(i).deleteRecursively() && worked;
  4970. }
  4971. return deleteFile() && worked;
  4972. }
  4973. bool File::moveFileTo (const File& newFile) const
  4974. {
  4975. if (newFile.fullPath == fullPath)
  4976. return true;
  4977. #if ! NAMES_ARE_CASE_SENSITIVE
  4978. if (*this != newFile)
  4979. #endif
  4980. if (! newFile.deleteFile())
  4981. return false;
  4982. return moveInternal (newFile);
  4983. }
  4984. bool File::copyFileTo (const File& newFile) const
  4985. {
  4986. return (*this == newFile)
  4987. || (exists() && newFile.deleteFile() && copyInternal (newFile));
  4988. }
  4989. bool File::copyDirectoryTo (const File& newDirectory) const
  4990. {
  4991. if (isDirectory() && newDirectory.createDirectory())
  4992. {
  4993. Array<File> subFiles;
  4994. findChildFiles (subFiles, File::findFiles, false);
  4995. int i;
  4996. for (i = 0; i < subFiles.size(); ++i)
  4997. if (! subFiles.getReference(i).copyFileTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  4998. return false;
  4999. subFiles.clear();
  5000. findChildFiles (subFiles, File::findDirectories, false);
  5001. for (i = 0; i < subFiles.size(); ++i)
  5002. if (! subFiles.getReference(i).copyDirectoryTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  5003. return false;
  5004. return true;
  5005. }
  5006. return false;
  5007. }
  5008. const String File::getPathUpToLastSlash() const
  5009. {
  5010. const int lastSlash = fullPath.lastIndexOfChar (separator);
  5011. if (lastSlash > 0)
  5012. return fullPath.substring (0, lastSlash);
  5013. else if (lastSlash == 0)
  5014. return separatorString;
  5015. else
  5016. return fullPath;
  5017. }
  5018. const File File::getParentDirectory() const
  5019. {
  5020. return File (getPathUpToLastSlash(), (int) 0);
  5021. }
  5022. const String File::getFileName() const
  5023. {
  5024. return fullPath.substring (fullPath.lastIndexOfChar (separator) + 1);
  5025. }
  5026. int File::hashCode() const
  5027. {
  5028. return fullPath.hashCode();
  5029. }
  5030. int64 File::hashCode64() const
  5031. {
  5032. return fullPath.hashCode64();
  5033. }
  5034. const String File::getFileNameWithoutExtension() const
  5035. {
  5036. const int lastSlash = fullPath.lastIndexOfChar (separator) + 1;
  5037. const int lastDot = fullPath.lastIndexOfChar ('.');
  5038. if (lastDot > lastSlash)
  5039. return fullPath.substring (lastSlash, lastDot);
  5040. else
  5041. return fullPath.substring (lastSlash);
  5042. }
  5043. bool File::isAChildOf (const File& potentialParent) const
  5044. {
  5045. if (potentialParent == File::nonexistent)
  5046. return false;
  5047. const String ourPath (getPathUpToLastSlash());
  5048. #if NAMES_ARE_CASE_SENSITIVE
  5049. if (potentialParent.fullPath == ourPath)
  5050. #else
  5051. if (potentialParent.fullPath.equalsIgnoreCase (ourPath))
  5052. #endif
  5053. {
  5054. return true;
  5055. }
  5056. else if (potentialParent.fullPath.length() >= ourPath.length())
  5057. {
  5058. return false;
  5059. }
  5060. else
  5061. {
  5062. return getParentDirectory().isAChildOf (potentialParent);
  5063. }
  5064. }
  5065. bool File::isAbsolutePath (const String& path)
  5066. {
  5067. return path.startsWithChar ('/') || path.startsWithChar ('\\')
  5068. #if JUCE_WINDOWS
  5069. || (path.isNotEmpty() && path[1] == ':');
  5070. #else
  5071. || path.startsWithChar ('~');
  5072. #endif
  5073. }
  5074. const File File::getChildFile (String relativePath) const
  5075. {
  5076. if (isAbsolutePath (relativePath))
  5077. {
  5078. // the path is really absolute..
  5079. return File (relativePath);
  5080. }
  5081. else
  5082. {
  5083. // it's relative, so remove any ../ or ./ bits at the start.
  5084. String path (fullPath);
  5085. if (relativePath[0] == '.')
  5086. {
  5087. #if JUCE_WINDOWS
  5088. relativePath = relativePath.replaceCharacter ('/', '\\').trimStart();
  5089. #else
  5090. relativePath = relativePath.replaceCharacter ('\\', '/').trimStart();
  5091. #endif
  5092. while (relativePath[0] == '.')
  5093. {
  5094. if (relativePath[1] == '.')
  5095. {
  5096. if (relativePath [2] == 0 || relativePath[2] == separator)
  5097. {
  5098. const int lastSlash = path.lastIndexOfChar (separator);
  5099. if (lastSlash >= 0)
  5100. path = path.substring (0, lastSlash);
  5101. relativePath = relativePath.substring (3);
  5102. }
  5103. else
  5104. {
  5105. break;
  5106. }
  5107. }
  5108. else if (relativePath[1] == separator)
  5109. {
  5110. relativePath = relativePath.substring (2);
  5111. }
  5112. else
  5113. {
  5114. break;
  5115. }
  5116. }
  5117. }
  5118. return File (addTrailingSeparator (path) + relativePath);
  5119. }
  5120. }
  5121. const File File::getSiblingFile (const String& fileName) const
  5122. {
  5123. return getParentDirectory().getChildFile (fileName);
  5124. }
  5125. const String File::descriptionOfSizeInBytes (const int64 bytes)
  5126. {
  5127. if (bytes == 1)
  5128. {
  5129. return "1 byte";
  5130. }
  5131. else if (bytes < 1024)
  5132. {
  5133. return String ((int) bytes) + " bytes";
  5134. }
  5135. else if (bytes < 1024 * 1024)
  5136. {
  5137. return String (bytes / 1024.0, 1) + " KB";
  5138. }
  5139. else if (bytes < 1024 * 1024 * 1024)
  5140. {
  5141. return String (bytes / (1024.0 * 1024.0), 1) + " MB";
  5142. }
  5143. else
  5144. {
  5145. return String (bytes / (1024.0 * 1024.0 * 1024.0), 1) + " GB";
  5146. }
  5147. }
  5148. bool File::create() const
  5149. {
  5150. if (exists())
  5151. return true;
  5152. {
  5153. const File parentDir (getParentDirectory());
  5154. if (parentDir == *this || ! parentDir.createDirectory())
  5155. return false;
  5156. FileOutputStream fo (*this, 8);
  5157. }
  5158. return exists();
  5159. }
  5160. bool File::createDirectory() const
  5161. {
  5162. if (! isDirectory())
  5163. {
  5164. const File parentDir (getParentDirectory());
  5165. if (parentDir == *this || ! parentDir.createDirectory())
  5166. return false;
  5167. createDirectoryInternal (fullPath.trimCharactersAtEnd (separatorString));
  5168. return isDirectory();
  5169. }
  5170. return true;
  5171. }
  5172. const Time File::getCreationTime() const
  5173. {
  5174. int64 m, a, c;
  5175. getFileTimesInternal (m, a, c);
  5176. return Time (c);
  5177. }
  5178. const Time File::getLastModificationTime() const
  5179. {
  5180. int64 m, a, c;
  5181. getFileTimesInternal (m, a, c);
  5182. return Time (m);
  5183. }
  5184. const Time File::getLastAccessTime() const
  5185. {
  5186. int64 m, a, c;
  5187. getFileTimesInternal (m, a, c);
  5188. return Time (a);
  5189. }
  5190. bool File::setLastModificationTime (const Time& t) const { return setFileTimesInternal (t.toMilliseconds(), 0, 0); }
  5191. bool File::setLastAccessTime (const Time& t) const { return setFileTimesInternal (0, t.toMilliseconds(), 0); }
  5192. bool File::setCreationTime (const Time& t) const { return setFileTimesInternal (0, 0, t.toMilliseconds()); }
  5193. bool File::loadFileAsData (MemoryBlock& destBlock) const
  5194. {
  5195. if (! existsAsFile())
  5196. return false;
  5197. FileInputStream in (*this);
  5198. return getSize() == in.readIntoMemoryBlock (destBlock);
  5199. }
  5200. const String File::loadFileAsString() const
  5201. {
  5202. if (! existsAsFile())
  5203. return String::empty;
  5204. FileInputStream in (*this);
  5205. return in.readEntireStreamAsString();
  5206. }
  5207. bool File::fileTypeMatches (const int whatToLookFor, const bool isDir, const bool isHidden)
  5208. {
  5209. return (whatToLookFor & (isDir ? findDirectories
  5210. : findFiles)) != 0
  5211. && ((! isHidden) || (whatToLookFor & File::ignoreHiddenFiles) == 0);
  5212. }
  5213. int File::findChildFiles (Array<File>& results,
  5214. const int whatToLookFor,
  5215. const bool searchRecursively,
  5216. const String& wildCardPattern) const
  5217. {
  5218. // you have to specify the type of files you're looking for!
  5219. jassert ((whatToLookFor & (findFiles | findDirectories)) != 0);
  5220. int total = 0;
  5221. if (isDirectory())
  5222. {
  5223. // find child files or directories in this directory first..
  5224. String path (addTrailingSeparator (fullPath)), filename;
  5225. bool itemIsDirectory, itemIsHidden;
  5226. DirectoryIterator::NativeIterator i (path, wildCardPattern);
  5227. while (i.next (filename, &itemIsDirectory, &itemIsHidden, 0, 0, 0, 0))
  5228. {
  5229. if (! filename.containsOnly ("."))
  5230. {
  5231. const File fileFound (path + filename, 0);
  5232. if (fileTypeMatches (whatToLookFor, itemIsDirectory, itemIsHidden))
  5233. {
  5234. results.add (fileFound);
  5235. ++total;
  5236. }
  5237. if (searchRecursively && itemIsDirectory
  5238. && fileTypeMatches (whatToLookFor | findDirectories, true, itemIsHidden))
  5239. {
  5240. total += fileFound.findChildFiles (results, whatToLookFor, true, wildCardPattern);
  5241. }
  5242. }
  5243. }
  5244. }
  5245. return total;
  5246. }
  5247. int File::getNumberOfChildFiles (const int whatToLookFor,
  5248. const String& wildCardPattern) const
  5249. {
  5250. // you have to specify the type of files you're looking for!
  5251. jassert (whatToLookFor > 0 && whatToLookFor <= 3);
  5252. int count = 0;
  5253. if (isDirectory())
  5254. {
  5255. String filename;
  5256. bool itemIsDirectory, itemIsHidden;
  5257. DirectoryIterator::NativeIterator i (*this, wildCardPattern);
  5258. while (i.next (filename, &itemIsDirectory, &itemIsHidden, 0, 0, 0, 0))
  5259. if (fileTypeMatches (whatToLookFor, itemIsDirectory, itemIsHidden)
  5260. && ! filename.containsOnly ("."))
  5261. ++count;
  5262. }
  5263. else
  5264. {
  5265. // trying to search for files inside a non-directory?
  5266. jassertfalse;
  5267. }
  5268. return count;
  5269. }
  5270. bool File::containsSubDirectories() const
  5271. {
  5272. if (isDirectory())
  5273. {
  5274. String filename;
  5275. bool itemIsDirectory;
  5276. DirectoryIterator::NativeIterator i (*this, "*");
  5277. while (i.next (filename, &itemIsDirectory, 0, 0, 0, 0, 0))
  5278. if (itemIsDirectory)
  5279. return true;
  5280. }
  5281. return false;
  5282. }
  5283. const File File::getNonexistentChildFile (const String& prefix_,
  5284. const String& suffix,
  5285. bool putNumbersInBrackets) const
  5286. {
  5287. File f (getChildFile (prefix_ + suffix));
  5288. if (f.exists())
  5289. {
  5290. int num = 2;
  5291. String prefix (prefix_);
  5292. // remove any bracketed numbers that may already be on the end..
  5293. if (prefix.trim().endsWithChar (')'))
  5294. {
  5295. putNumbersInBrackets = true;
  5296. const int openBracks = prefix.lastIndexOfChar ('(');
  5297. const int closeBracks = prefix.lastIndexOfChar (')');
  5298. if (openBracks > 0
  5299. && closeBracks > openBracks
  5300. && prefix.substring (openBracks + 1, closeBracks).containsOnly ("0123456789"))
  5301. {
  5302. num = prefix.substring (openBracks + 1, closeBracks).getIntValue() + 1;
  5303. prefix = prefix.substring (0, openBracks);
  5304. }
  5305. }
  5306. // also use brackets if it ends in a digit.
  5307. putNumbersInBrackets = putNumbersInBrackets
  5308. || CharacterFunctions::isDigit (prefix.getLastCharacter());
  5309. do
  5310. {
  5311. if (putNumbersInBrackets)
  5312. f = getChildFile (prefix + '(' + String (num++) + ')' + suffix);
  5313. else
  5314. f = getChildFile (prefix + String (num++) + suffix);
  5315. } while (f.exists());
  5316. }
  5317. return f;
  5318. }
  5319. const File File::getNonexistentSibling (const bool putNumbersInBrackets) const
  5320. {
  5321. if (exists())
  5322. {
  5323. return getParentDirectory()
  5324. .getNonexistentChildFile (getFileNameWithoutExtension(),
  5325. getFileExtension(),
  5326. putNumbersInBrackets);
  5327. }
  5328. else
  5329. {
  5330. return *this;
  5331. }
  5332. }
  5333. const String File::getFileExtension() const
  5334. {
  5335. String ext;
  5336. if (! isDirectory())
  5337. {
  5338. const int indexOfDot = fullPath.lastIndexOfChar ('.');
  5339. if (indexOfDot > fullPath.lastIndexOfChar (separator))
  5340. ext = fullPath.substring (indexOfDot);
  5341. }
  5342. return ext;
  5343. }
  5344. bool File::hasFileExtension (const String& possibleSuffix) const
  5345. {
  5346. if (possibleSuffix.isEmpty())
  5347. return fullPath.lastIndexOfChar ('.') <= fullPath.lastIndexOfChar (separator);
  5348. const int semicolon = possibleSuffix.indexOfChar (0, ';');
  5349. if (semicolon >= 0)
  5350. {
  5351. return hasFileExtension (possibleSuffix.substring (0, semicolon).trimEnd())
  5352. || hasFileExtension (possibleSuffix.substring (semicolon + 1).trimStart());
  5353. }
  5354. else
  5355. {
  5356. if (fullPath.endsWithIgnoreCase (possibleSuffix))
  5357. {
  5358. if (possibleSuffix.startsWithChar ('.'))
  5359. return true;
  5360. const int dotPos = fullPath.length() - possibleSuffix.length() - 1;
  5361. if (dotPos >= 0)
  5362. return fullPath [dotPos] == '.';
  5363. }
  5364. }
  5365. return false;
  5366. }
  5367. const File File::withFileExtension (const String& newExtension) const
  5368. {
  5369. if (fullPath.isEmpty())
  5370. return File::nonexistent;
  5371. String filePart (getFileName());
  5372. int i = filePart.lastIndexOfChar ('.');
  5373. if (i >= 0)
  5374. filePart = filePart.substring (0, i);
  5375. if (newExtension.isNotEmpty() && ! newExtension.startsWithChar ('.'))
  5376. filePart << '.';
  5377. return getSiblingFile (filePart + newExtension);
  5378. }
  5379. bool File::startAsProcess (const String& parameters) const
  5380. {
  5381. return exists() && PlatformUtilities::openDocument (fullPath, parameters);
  5382. }
  5383. FileInputStream* File::createInputStream() const
  5384. {
  5385. if (existsAsFile())
  5386. return new FileInputStream (*this);
  5387. return 0;
  5388. }
  5389. FileOutputStream* File::createOutputStream (const int bufferSize) const
  5390. {
  5391. ScopedPointer <FileOutputStream> out (new FileOutputStream (*this, bufferSize));
  5392. if (out->failedToOpen())
  5393. return 0;
  5394. return out.release();
  5395. }
  5396. bool File::appendData (const void* const dataToAppend,
  5397. const int numberOfBytes) const
  5398. {
  5399. if (numberOfBytes > 0)
  5400. {
  5401. const ScopedPointer <FileOutputStream> out (createOutputStream());
  5402. if (out == 0)
  5403. return false;
  5404. out->write (dataToAppend, numberOfBytes);
  5405. }
  5406. return true;
  5407. }
  5408. bool File::replaceWithData (const void* const dataToWrite,
  5409. const int numberOfBytes) const
  5410. {
  5411. jassert (numberOfBytes >= 0); // a negative number of bytes??
  5412. if (numberOfBytes <= 0)
  5413. return deleteFile();
  5414. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  5415. tempFile.getFile().appendData (dataToWrite, numberOfBytes);
  5416. return tempFile.overwriteTargetFileWithTemporary();
  5417. }
  5418. bool File::appendText (const String& text,
  5419. const bool asUnicode,
  5420. const bool writeUnicodeHeaderBytes) const
  5421. {
  5422. const ScopedPointer <FileOutputStream> out (createOutputStream());
  5423. if (out != 0)
  5424. {
  5425. out->writeText (text, asUnicode, writeUnicodeHeaderBytes);
  5426. return true;
  5427. }
  5428. return false;
  5429. }
  5430. bool File::replaceWithText (const String& textToWrite,
  5431. const bool asUnicode,
  5432. const bool writeUnicodeHeaderBytes) const
  5433. {
  5434. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  5435. tempFile.getFile().appendText (textToWrite, asUnicode, writeUnicodeHeaderBytes);
  5436. return tempFile.overwriteTargetFileWithTemporary();
  5437. }
  5438. bool File::hasIdenticalContentTo (const File& other) const
  5439. {
  5440. if (other == *this)
  5441. return true;
  5442. if (getSize() == other.getSize() && existsAsFile() && other.existsAsFile())
  5443. {
  5444. FileInputStream in1 (*this), in2 (other);
  5445. const int bufferSize = 4096;
  5446. HeapBlock <char> buffer1, buffer2;
  5447. buffer1.malloc (bufferSize);
  5448. buffer2.malloc (bufferSize);
  5449. for (;;)
  5450. {
  5451. const int num1 = in1.read (buffer1, bufferSize);
  5452. const int num2 = in2.read (buffer2, bufferSize);
  5453. if (num1 != num2)
  5454. break;
  5455. if (num1 <= 0)
  5456. return true;
  5457. if (memcmp (buffer1, buffer2, num1) != 0)
  5458. break;
  5459. }
  5460. }
  5461. return false;
  5462. }
  5463. const String File::createLegalPathName (const String& original)
  5464. {
  5465. String s (original);
  5466. String start;
  5467. if (s[1] == ':')
  5468. {
  5469. start = s.substring (0, 2);
  5470. s = s.substring (2);
  5471. }
  5472. return start + s.removeCharacters ("\"#@,;:<>*^|?")
  5473. .substring (0, 1024);
  5474. }
  5475. const String File::createLegalFileName (const String& original)
  5476. {
  5477. String s (original.removeCharacters ("\"#@,;:<>*^|?\\/"));
  5478. const int maxLength = 128; // only the length of the filename, not the whole path
  5479. const int len = s.length();
  5480. if (len > maxLength)
  5481. {
  5482. const int lastDot = s.lastIndexOfChar ('.');
  5483. if (lastDot > jmax (0, len - 12))
  5484. {
  5485. s = s.substring (0, maxLength - (len - lastDot))
  5486. + s.substring (lastDot);
  5487. }
  5488. else
  5489. {
  5490. s = s.substring (0, maxLength);
  5491. }
  5492. }
  5493. return s;
  5494. }
  5495. const String File::getRelativePathFrom (const File& dir) const
  5496. {
  5497. String thisPath (fullPath);
  5498. {
  5499. int len = thisPath.length();
  5500. while (--len >= 0 && thisPath [len] == File::separator)
  5501. thisPath [len] = 0;
  5502. }
  5503. String dirPath (addTrailingSeparator (dir.existsAsFile() ? dir.getParentDirectory().getFullPathName()
  5504. : dir.fullPath));
  5505. const int len = jmin (thisPath.length(), dirPath.length());
  5506. int commonBitLength = 0;
  5507. for (int i = 0; i < len; ++i)
  5508. {
  5509. #if NAMES_ARE_CASE_SENSITIVE
  5510. if (thisPath[i] != dirPath[i])
  5511. #else
  5512. if (CharacterFunctions::toLowerCase (thisPath[i])
  5513. != CharacterFunctions::toLowerCase (dirPath[i]))
  5514. #endif
  5515. {
  5516. break;
  5517. }
  5518. ++commonBitLength;
  5519. }
  5520. while (commonBitLength > 0 && thisPath [commonBitLength - 1] != File::separator)
  5521. --commonBitLength;
  5522. // if the only common bit is the root, then just return the full path..
  5523. if (commonBitLength <= 0
  5524. || (commonBitLength == 1 && thisPath [1] == File::separator))
  5525. return fullPath;
  5526. thisPath = thisPath.substring (commonBitLength);
  5527. dirPath = dirPath.substring (commonBitLength);
  5528. while (dirPath.isNotEmpty())
  5529. {
  5530. #if JUCE_WINDOWS
  5531. thisPath = "..\\" + thisPath;
  5532. #else
  5533. thisPath = "../" + thisPath;
  5534. #endif
  5535. const int sep = dirPath.indexOfChar (separator);
  5536. if (sep >= 0)
  5537. dirPath = dirPath.substring (sep + 1);
  5538. else
  5539. dirPath = String::empty;
  5540. }
  5541. return thisPath;
  5542. }
  5543. const File File::createTempFile (const String& fileNameEnding)
  5544. {
  5545. const File tempFile (getSpecialLocation (tempDirectory)
  5546. .getChildFile ("temp_" + String (Random::getSystemRandom().nextInt()))
  5547. .withFileExtension (fileNameEnding));
  5548. if (tempFile.exists())
  5549. return createTempFile (fileNameEnding);
  5550. else
  5551. return tempFile;
  5552. }
  5553. END_JUCE_NAMESPACE
  5554. /*** End of inlined file: juce_File.cpp ***/
  5555. /*** Start of inlined file: juce_FileInputStream.cpp ***/
  5556. BEGIN_JUCE_NAMESPACE
  5557. void* juce_fileOpen (const File& file, bool forWriting);
  5558. void juce_fileClose (void* handle);
  5559. int juce_fileRead (void* handle, void* buffer, int size);
  5560. int64 juce_fileSetPosition (void* handle, int64 pos);
  5561. FileInputStream::FileInputStream (const File& f)
  5562. : file (f),
  5563. currentPosition (0),
  5564. needToSeek (true)
  5565. {
  5566. totalSize = f.getSize();
  5567. fileHandle = juce_fileOpen (f, false);
  5568. }
  5569. FileInputStream::~FileInputStream()
  5570. {
  5571. juce_fileClose (fileHandle);
  5572. }
  5573. int64 FileInputStream::getTotalLength()
  5574. {
  5575. return totalSize;
  5576. }
  5577. int FileInputStream::read (void* buffer, int bytesToRead)
  5578. {
  5579. int num = 0;
  5580. if (needToSeek)
  5581. {
  5582. if (juce_fileSetPosition (fileHandle, currentPosition) < 0)
  5583. return 0;
  5584. needToSeek = false;
  5585. }
  5586. num = juce_fileRead (fileHandle, buffer, bytesToRead);
  5587. currentPosition += num;
  5588. return num;
  5589. }
  5590. bool FileInputStream::isExhausted()
  5591. {
  5592. return currentPosition >= totalSize;
  5593. }
  5594. int64 FileInputStream::getPosition()
  5595. {
  5596. return currentPosition;
  5597. }
  5598. bool FileInputStream::setPosition (int64 pos)
  5599. {
  5600. pos = jlimit ((int64) 0, totalSize, pos);
  5601. needToSeek |= (currentPosition != pos);
  5602. currentPosition = pos;
  5603. return true;
  5604. }
  5605. END_JUCE_NAMESPACE
  5606. /*** End of inlined file: juce_FileInputStream.cpp ***/
  5607. /*** Start of inlined file: juce_FileOutputStream.cpp ***/
  5608. BEGIN_JUCE_NAMESPACE
  5609. void* juce_fileOpen (const File& file, bool forWriting);
  5610. void juce_fileClose (void* handle);
  5611. int juce_fileWrite (void* handle, const void* buffer, int size);
  5612. int64 juce_fileSetPosition (void* handle, int64 pos);
  5613. FileOutputStream::FileOutputStream (const File& f,
  5614. const int bufferSize_)
  5615. : file (f),
  5616. bufferSize (bufferSize_),
  5617. bytesInBuffer (0)
  5618. {
  5619. fileHandle = juce_fileOpen (f, true);
  5620. if (fileHandle != 0)
  5621. {
  5622. currentPosition = getPositionInternal();
  5623. if (currentPosition < 0)
  5624. {
  5625. jassertfalse;
  5626. juce_fileClose (fileHandle);
  5627. fileHandle = 0;
  5628. }
  5629. }
  5630. buffer.malloc (jmax (bufferSize_, 16));
  5631. }
  5632. FileOutputStream::~FileOutputStream()
  5633. {
  5634. flush();
  5635. juce_fileClose (fileHandle);
  5636. }
  5637. int64 FileOutputStream::getPosition()
  5638. {
  5639. return currentPosition;
  5640. }
  5641. bool FileOutputStream::setPosition (int64 newPosition)
  5642. {
  5643. if (newPosition != currentPosition)
  5644. {
  5645. flush();
  5646. currentPosition = juce_fileSetPosition (fileHandle, newPosition);
  5647. }
  5648. return newPosition == currentPosition;
  5649. }
  5650. void FileOutputStream::flush()
  5651. {
  5652. if (bytesInBuffer > 0)
  5653. {
  5654. juce_fileWrite (fileHandle, buffer, bytesInBuffer);
  5655. bytesInBuffer = 0;
  5656. }
  5657. flushInternal();
  5658. }
  5659. bool FileOutputStream::write (const void* const src, const int numBytes)
  5660. {
  5661. if (bytesInBuffer + numBytes < bufferSize)
  5662. {
  5663. memcpy (buffer + bytesInBuffer, src, numBytes);
  5664. bytesInBuffer += numBytes;
  5665. currentPosition += numBytes;
  5666. }
  5667. else
  5668. {
  5669. if (bytesInBuffer > 0)
  5670. {
  5671. // flush the reservoir
  5672. const bool wroteOk = (juce_fileWrite (fileHandle, buffer, bytesInBuffer) == bytesInBuffer);
  5673. bytesInBuffer = 0;
  5674. if (! wroteOk)
  5675. return false;
  5676. }
  5677. if (numBytes < bufferSize)
  5678. {
  5679. memcpy (buffer + bytesInBuffer, src, numBytes);
  5680. bytesInBuffer += numBytes;
  5681. currentPosition += numBytes;
  5682. }
  5683. else
  5684. {
  5685. const int bytesWritten = juce_fileWrite (fileHandle, src, numBytes);
  5686. currentPosition += bytesWritten;
  5687. return bytesWritten == numBytes;
  5688. }
  5689. }
  5690. return true;
  5691. }
  5692. END_JUCE_NAMESPACE
  5693. /*** End of inlined file: juce_FileOutputStream.cpp ***/
  5694. /*** Start of inlined file: juce_FileSearchPath.cpp ***/
  5695. BEGIN_JUCE_NAMESPACE
  5696. FileSearchPath::FileSearchPath()
  5697. {
  5698. }
  5699. FileSearchPath::FileSearchPath (const String& path)
  5700. {
  5701. init (path);
  5702. }
  5703. FileSearchPath::FileSearchPath (const FileSearchPath& other)
  5704. : directories (other.directories)
  5705. {
  5706. }
  5707. FileSearchPath::~FileSearchPath()
  5708. {
  5709. }
  5710. FileSearchPath& FileSearchPath::operator= (const String& path)
  5711. {
  5712. init (path);
  5713. return *this;
  5714. }
  5715. void FileSearchPath::init (const String& path)
  5716. {
  5717. directories.clear();
  5718. directories.addTokens (path, ";", "\"");
  5719. directories.trim();
  5720. directories.removeEmptyStrings();
  5721. for (int i = directories.size(); --i >= 0;)
  5722. directories.set (i, directories[i].unquoted());
  5723. }
  5724. int FileSearchPath::getNumPaths() const
  5725. {
  5726. return directories.size();
  5727. }
  5728. const File FileSearchPath::operator[] (const int index) const
  5729. {
  5730. return File (directories [index]);
  5731. }
  5732. const String FileSearchPath::toString() const
  5733. {
  5734. StringArray directories2 (directories);
  5735. for (int i = directories2.size(); --i >= 0;)
  5736. if (directories2[i].containsChar (';'))
  5737. directories2.set (i, directories2[i].quoted());
  5738. return directories2.joinIntoString (";");
  5739. }
  5740. void FileSearchPath::add (const File& dir, const int insertIndex)
  5741. {
  5742. directories.insert (insertIndex, dir.getFullPathName());
  5743. }
  5744. void FileSearchPath::addIfNotAlreadyThere (const File& dir)
  5745. {
  5746. for (int i = 0; i < directories.size(); ++i)
  5747. if (File (directories[i]) == dir)
  5748. return;
  5749. add (dir);
  5750. }
  5751. void FileSearchPath::remove (const int index)
  5752. {
  5753. directories.remove (index);
  5754. }
  5755. void FileSearchPath::addPath (const FileSearchPath& other)
  5756. {
  5757. for (int i = 0; i < other.getNumPaths(); ++i)
  5758. addIfNotAlreadyThere (other[i]);
  5759. }
  5760. void FileSearchPath::removeRedundantPaths()
  5761. {
  5762. for (int i = directories.size(); --i >= 0;)
  5763. {
  5764. const File d1 (directories[i]);
  5765. for (int j = directories.size(); --j >= 0;)
  5766. {
  5767. const File d2 (directories[j]);
  5768. if ((i != j) && (d1.isAChildOf (d2) || d1 == d2))
  5769. {
  5770. directories.remove (i);
  5771. break;
  5772. }
  5773. }
  5774. }
  5775. }
  5776. void FileSearchPath::removeNonExistentPaths()
  5777. {
  5778. for (int i = directories.size(); --i >= 0;)
  5779. if (! File (directories[i]).isDirectory())
  5780. directories.remove (i);
  5781. }
  5782. int FileSearchPath::findChildFiles (Array<File>& results,
  5783. const int whatToLookFor,
  5784. const bool searchRecursively,
  5785. const String& wildCardPattern) const
  5786. {
  5787. int total = 0;
  5788. for (int i = 0; i < directories.size(); ++i)
  5789. total += operator[] (i).findChildFiles (results,
  5790. whatToLookFor,
  5791. searchRecursively,
  5792. wildCardPattern);
  5793. return total;
  5794. }
  5795. bool FileSearchPath::isFileInPath (const File& fileToCheck,
  5796. const bool checkRecursively) const
  5797. {
  5798. for (int i = directories.size(); --i >= 0;)
  5799. {
  5800. const File d (directories[i]);
  5801. if (checkRecursively)
  5802. {
  5803. if (fileToCheck.isAChildOf (d))
  5804. return true;
  5805. }
  5806. else
  5807. {
  5808. if (fileToCheck.getParentDirectory() == d)
  5809. return true;
  5810. }
  5811. }
  5812. return false;
  5813. }
  5814. END_JUCE_NAMESPACE
  5815. /*** End of inlined file: juce_FileSearchPath.cpp ***/
  5816. /*** Start of inlined file: juce_NamedPipe.cpp ***/
  5817. BEGIN_JUCE_NAMESPACE
  5818. NamedPipe::NamedPipe()
  5819. : internal (0)
  5820. {
  5821. }
  5822. NamedPipe::~NamedPipe()
  5823. {
  5824. close();
  5825. }
  5826. bool NamedPipe::openExisting (const String& pipeName)
  5827. {
  5828. currentPipeName = pipeName;
  5829. return openInternal (pipeName, false);
  5830. }
  5831. bool NamedPipe::createNewPipe (const String& pipeName)
  5832. {
  5833. currentPipeName = pipeName;
  5834. return openInternal (pipeName, true);
  5835. }
  5836. bool NamedPipe::isOpen() const
  5837. {
  5838. return internal != 0;
  5839. }
  5840. const String NamedPipe::getName() const
  5841. {
  5842. return currentPipeName;
  5843. }
  5844. // other methods for this class are implemented in the platform-specific files
  5845. END_JUCE_NAMESPACE
  5846. /*** End of inlined file: juce_NamedPipe.cpp ***/
  5847. /*** Start of inlined file: juce_TemporaryFile.cpp ***/
  5848. BEGIN_JUCE_NAMESPACE
  5849. TemporaryFile::TemporaryFile (const String& suffix, const int optionFlags)
  5850. {
  5851. createTempFile (File::getSpecialLocation (File::tempDirectory),
  5852. "temp_" + String (Random::getSystemRandom().nextInt()),
  5853. suffix,
  5854. optionFlags);
  5855. }
  5856. TemporaryFile::TemporaryFile (const File& targetFile_, const int optionFlags)
  5857. : targetFile (targetFile_)
  5858. {
  5859. // If you use this constructor, you need to give it a valid target file!
  5860. jassert (targetFile != File::nonexistent);
  5861. createTempFile (targetFile.getParentDirectory(),
  5862. targetFile.getFileNameWithoutExtension() + "_temp" + String (Random::getSystemRandom().nextInt()),
  5863. targetFile.getFileExtension(),
  5864. optionFlags);
  5865. }
  5866. void TemporaryFile::createTempFile (const File& parentDirectory, String name,
  5867. const String& suffix, const int optionFlags)
  5868. {
  5869. if ((optionFlags & useHiddenFile) != 0)
  5870. name = "." + name;
  5871. temporaryFile = parentDirectory.getNonexistentChildFile (name, suffix, (optionFlags & putNumbersInBrackets) != 0);
  5872. }
  5873. TemporaryFile::~TemporaryFile()
  5874. {
  5875. // Have a few attempts at deleting the file before giving up..
  5876. for (int i = 5; --i >= 0;)
  5877. {
  5878. if (temporaryFile.deleteFile())
  5879. return;
  5880. Thread::sleep (50);
  5881. }
  5882. // Failed to delete our temporary file! Check that you've deleted all the
  5883. // file output streams that were using it!
  5884. jassertfalse;
  5885. }
  5886. bool TemporaryFile::overwriteTargetFileWithTemporary() const
  5887. {
  5888. // This method only works if you created this object with the constructor
  5889. // that takes a target file!
  5890. jassert (targetFile != File::nonexistent);
  5891. if (temporaryFile.exists())
  5892. {
  5893. // Have a few attempts at overwriting the file before giving up..
  5894. for (int i = 5; --i >= 0;)
  5895. {
  5896. if (temporaryFile.moveFileTo (targetFile))
  5897. return true;
  5898. Thread::sleep (100);
  5899. }
  5900. }
  5901. else
  5902. {
  5903. // There's no temporary file to use. If your write failed, you should
  5904. // probably check, and not bother calling this method.
  5905. jassertfalse;
  5906. }
  5907. return false;
  5908. }
  5909. END_JUCE_NAMESPACE
  5910. /*** End of inlined file: juce_TemporaryFile.cpp ***/
  5911. /*** Start of inlined file: juce_Socket.cpp ***/
  5912. #if JUCE_WINDOWS
  5913. #include <winsock2.h>
  5914. #if JUCE_MSVC
  5915. #pragma warning (push)
  5916. #pragma warning (disable : 4127 4389 4018)
  5917. #endif
  5918. #else
  5919. #if JUCE_LINUX
  5920. #include <sys/types.h>
  5921. #include <sys/socket.h>
  5922. #include <sys/errno.h>
  5923. #include <unistd.h>
  5924. #include <netinet/in.h>
  5925. #elif (MACOSX_DEPLOYMENT_TARGET <= MAC_OS_X_VERSION_10_4) && ! JUCE_IPHONE
  5926. #include <CoreServices/CoreServices.h>
  5927. #endif
  5928. #include <fcntl.h>
  5929. #include <netdb.h>
  5930. #include <arpa/inet.h>
  5931. #include <netinet/tcp.h>
  5932. #endif
  5933. BEGIN_JUCE_NAMESPACE
  5934. #if defined (JUCE_LINUX) || defined (JUCE_MAC) || defined (JUCE_IPHONE)
  5935. typedef socklen_t juce_socklen_t;
  5936. #else
  5937. typedef int juce_socklen_t;
  5938. #endif
  5939. #if JUCE_WINDOWS
  5940. typedef int (__stdcall juce_CloseWin32SocketLibCall) (void);
  5941. juce_CloseWin32SocketLibCall* juce_CloseWin32SocketLib = 0;
  5942. static void initWin32Sockets()
  5943. {
  5944. static CriticalSection lock;
  5945. const ScopedLock sl (lock);
  5946. if (juce_CloseWin32SocketLib == 0)
  5947. {
  5948. WSADATA wsaData;
  5949. const WORD wVersionRequested = MAKEWORD (1, 1);
  5950. WSAStartup (wVersionRequested, &wsaData);
  5951. juce_CloseWin32SocketLib = &WSACleanup;
  5952. }
  5953. }
  5954. #endif
  5955. static bool resetSocketOptions (const int handle, const bool isDatagram, const bool allowBroadcast) throw()
  5956. {
  5957. const int sndBufSize = 65536;
  5958. const int rcvBufSize = 65536;
  5959. const int one = 1;
  5960. return handle > 0
  5961. && setsockopt (handle, SOL_SOCKET, SO_RCVBUF, (const char*) &rcvBufSize, sizeof (rcvBufSize)) == 0
  5962. && setsockopt (handle, SOL_SOCKET, SO_SNDBUF, (const char*) &sndBufSize, sizeof (sndBufSize)) == 0
  5963. && (isDatagram ? ((! allowBroadcast) || setsockopt (handle, SOL_SOCKET, SO_BROADCAST, (const char*) &one, sizeof (one)) == 0)
  5964. : (setsockopt (handle, IPPROTO_TCP, TCP_NODELAY, (const char*) &one, sizeof (one)) == 0));
  5965. }
  5966. static bool bindSocketToPort (const int handle, const int port) throw()
  5967. {
  5968. if (handle <= 0 || port <= 0)
  5969. return false;
  5970. struct sockaddr_in servTmpAddr;
  5971. zerostruct (servTmpAddr);
  5972. servTmpAddr.sin_family = PF_INET;
  5973. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  5974. servTmpAddr.sin_port = htons ((uint16) port);
  5975. return bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) >= 0;
  5976. }
  5977. static int readSocket (const int handle,
  5978. void* const destBuffer, const int maxBytesToRead,
  5979. bool volatile& connected,
  5980. const bool blockUntilSpecifiedAmountHasArrived) throw()
  5981. {
  5982. int bytesRead = 0;
  5983. while (bytesRead < maxBytesToRead)
  5984. {
  5985. int bytesThisTime;
  5986. #if JUCE_WINDOWS
  5987. bytesThisTime = recv (handle, ((char*) destBuffer) + bytesRead, maxBytesToRead - bytesRead, 0);
  5988. #else
  5989. while ((bytesThisTime = (int) ::read (handle, ((char*) destBuffer) + bytesRead, maxBytesToRead - bytesRead)) < 0
  5990. && errno == EINTR
  5991. && connected)
  5992. {
  5993. }
  5994. #endif
  5995. if (bytesThisTime <= 0 || ! connected)
  5996. {
  5997. if (bytesRead == 0)
  5998. bytesRead = -1;
  5999. break;
  6000. }
  6001. bytesRead += bytesThisTime;
  6002. if (! blockUntilSpecifiedAmountHasArrived)
  6003. break;
  6004. }
  6005. return bytesRead;
  6006. }
  6007. static int waitForReadiness (const int handle, const bool forReading,
  6008. const int timeoutMsecs) throw()
  6009. {
  6010. struct timeval timeout;
  6011. struct timeval* timeoutp;
  6012. if (timeoutMsecs >= 0)
  6013. {
  6014. timeout.tv_sec = timeoutMsecs / 1000;
  6015. timeout.tv_usec = (timeoutMsecs % 1000) * 1000;
  6016. timeoutp = &timeout;
  6017. }
  6018. else
  6019. {
  6020. timeoutp = 0;
  6021. }
  6022. fd_set rset, wset;
  6023. FD_ZERO (&rset);
  6024. FD_SET (handle, &rset);
  6025. FD_ZERO (&wset);
  6026. FD_SET (handle, &wset);
  6027. fd_set* const prset = forReading ? &rset : 0;
  6028. fd_set* const pwset = forReading ? 0 : &wset;
  6029. #if JUCE_WINDOWS
  6030. if (select (handle + 1, prset, pwset, 0, timeoutp) < 0)
  6031. return -1;
  6032. #else
  6033. {
  6034. int result;
  6035. while ((result = select (handle + 1, prset, pwset, 0, timeoutp)) < 0
  6036. && errno == EINTR)
  6037. {
  6038. }
  6039. if (result < 0)
  6040. return -1;
  6041. }
  6042. #endif
  6043. {
  6044. int opt;
  6045. juce_socklen_t len = sizeof (opt);
  6046. if (getsockopt (handle, SOL_SOCKET, SO_ERROR, (char*) &opt, &len) < 0
  6047. || opt != 0)
  6048. return -1;
  6049. }
  6050. if ((forReading && FD_ISSET (handle, &rset))
  6051. || ((! forReading) && FD_ISSET (handle, &wset)))
  6052. return 1;
  6053. return 0;
  6054. }
  6055. static bool setSocketBlockingState (const int handle, const bool shouldBlock) throw()
  6056. {
  6057. #if JUCE_WINDOWS
  6058. u_long nonBlocking = shouldBlock ? 0 : 1;
  6059. if (ioctlsocket (handle, FIONBIO, &nonBlocking) != 0)
  6060. return false;
  6061. #else
  6062. int socketFlags = fcntl (handle, F_GETFL, 0);
  6063. if (socketFlags == -1)
  6064. return false;
  6065. if (shouldBlock)
  6066. socketFlags &= ~O_NONBLOCK;
  6067. else
  6068. socketFlags |= O_NONBLOCK;
  6069. if (fcntl (handle, F_SETFL, socketFlags) != 0)
  6070. return false;
  6071. #endif
  6072. return true;
  6073. }
  6074. static bool connectSocket (int volatile& handle,
  6075. const bool isDatagram,
  6076. void** serverAddress,
  6077. const String& hostName,
  6078. const int portNumber,
  6079. const int timeOutMillisecs) throw()
  6080. {
  6081. struct hostent* const hostEnt = gethostbyname (hostName.toUTF8());
  6082. if (hostEnt == 0)
  6083. return false;
  6084. struct in_addr targetAddress;
  6085. memcpy (&targetAddress.s_addr,
  6086. *(hostEnt->h_addr_list),
  6087. sizeof (targetAddress.s_addr));
  6088. struct sockaddr_in servTmpAddr;
  6089. zerostruct (servTmpAddr);
  6090. servTmpAddr.sin_family = PF_INET;
  6091. servTmpAddr.sin_addr = targetAddress;
  6092. servTmpAddr.sin_port = htons ((uint16) portNumber);
  6093. if (handle < 0)
  6094. handle = (int) socket (AF_INET, isDatagram ? SOCK_DGRAM : SOCK_STREAM, 0);
  6095. if (handle < 0)
  6096. return false;
  6097. if (isDatagram)
  6098. {
  6099. *serverAddress = new struct sockaddr_in();
  6100. *((struct sockaddr_in*) *serverAddress) = servTmpAddr;
  6101. return true;
  6102. }
  6103. setSocketBlockingState (handle, false);
  6104. const int result = ::connect (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in));
  6105. if (result < 0)
  6106. {
  6107. #if JUCE_WINDOWS
  6108. if (result == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK)
  6109. #else
  6110. if (errno == EINPROGRESS)
  6111. #endif
  6112. {
  6113. if (waitForReadiness (handle, false, timeOutMillisecs) != 1)
  6114. {
  6115. setSocketBlockingState (handle, true);
  6116. return false;
  6117. }
  6118. }
  6119. }
  6120. setSocketBlockingState (handle, true);
  6121. resetSocketOptions (handle, false, false);
  6122. return true;
  6123. }
  6124. StreamingSocket::StreamingSocket()
  6125. : portNumber (0),
  6126. handle (-1),
  6127. connected (false),
  6128. isListener (false)
  6129. {
  6130. #if JUCE_WINDOWS
  6131. initWin32Sockets();
  6132. #endif
  6133. }
  6134. StreamingSocket::StreamingSocket (const String& hostName_,
  6135. const int portNumber_,
  6136. const int handle_)
  6137. : hostName (hostName_),
  6138. portNumber (portNumber_),
  6139. handle (handle_),
  6140. connected (true),
  6141. isListener (false)
  6142. {
  6143. #if JUCE_WINDOWS
  6144. initWin32Sockets();
  6145. #endif
  6146. resetSocketOptions (handle_, false, false);
  6147. }
  6148. StreamingSocket::~StreamingSocket()
  6149. {
  6150. close();
  6151. }
  6152. int StreamingSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  6153. {
  6154. return (connected && ! isListener) ? readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  6155. : -1;
  6156. }
  6157. int StreamingSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  6158. {
  6159. if (isListener || ! connected)
  6160. return -1;
  6161. #if JUCE_WINDOWS
  6162. return send (handle, (const char*) sourceBuffer, numBytesToWrite, 0);
  6163. #else
  6164. int result;
  6165. while ((result = (int) ::write (handle, sourceBuffer, numBytesToWrite)) < 0
  6166. && errno == EINTR)
  6167. {
  6168. }
  6169. return result;
  6170. #endif
  6171. }
  6172. int StreamingSocket::waitUntilReady (const bool readyForReading,
  6173. const int timeoutMsecs) const
  6174. {
  6175. return connected ? waitForReadiness (handle, readyForReading, timeoutMsecs)
  6176. : -1;
  6177. }
  6178. bool StreamingSocket::bindToPort (const int port)
  6179. {
  6180. return bindSocketToPort (handle, port);
  6181. }
  6182. bool StreamingSocket::connect (const String& remoteHostName,
  6183. const int remotePortNumber,
  6184. const int timeOutMillisecs)
  6185. {
  6186. if (isListener)
  6187. {
  6188. jassertfalse; // a listener socket can't connect to another one!
  6189. return false;
  6190. }
  6191. if (connected)
  6192. close();
  6193. hostName = remoteHostName;
  6194. portNumber = remotePortNumber;
  6195. isListener = false;
  6196. connected = connectSocket (handle, false, 0, remoteHostName,
  6197. remotePortNumber, timeOutMillisecs);
  6198. if (! (connected && resetSocketOptions (handle, false, false)))
  6199. {
  6200. close();
  6201. return false;
  6202. }
  6203. return true;
  6204. }
  6205. void StreamingSocket::close()
  6206. {
  6207. #if JUCE_WINDOWS
  6208. if (handle != SOCKET_ERROR || connected)
  6209. closesocket (handle);
  6210. connected = false;
  6211. #else
  6212. if (connected)
  6213. {
  6214. connected = false;
  6215. if (isListener)
  6216. {
  6217. // need to do this to interrupt the accept() function..
  6218. StreamingSocket temp;
  6219. temp.connect ("localhost", portNumber, 1000);
  6220. }
  6221. }
  6222. if (handle != -1)
  6223. ::close (handle);
  6224. #endif
  6225. hostName = String::empty;
  6226. portNumber = 0;
  6227. handle = -1;
  6228. isListener = false;
  6229. }
  6230. bool StreamingSocket::createListener (const int newPortNumber, const String& localHostName)
  6231. {
  6232. if (connected)
  6233. close();
  6234. hostName = "listener";
  6235. portNumber = newPortNumber;
  6236. isListener = true;
  6237. struct sockaddr_in servTmpAddr;
  6238. zerostruct (servTmpAddr);
  6239. servTmpAddr.sin_family = PF_INET;
  6240. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  6241. if (localHostName.isNotEmpty())
  6242. servTmpAddr.sin_addr.s_addr = ::inet_addr (localHostName.toUTF8());
  6243. servTmpAddr.sin_port = htons ((uint16) portNumber);
  6244. handle = (int) socket (AF_INET, SOCK_STREAM, 0);
  6245. if (handle < 0)
  6246. return false;
  6247. const int reuse = 1;
  6248. setsockopt (handle, SOL_SOCKET, SO_REUSEADDR, (const char*) &reuse, sizeof (reuse));
  6249. if (bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) < 0
  6250. || listen (handle, SOMAXCONN) < 0)
  6251. {
  6252. close();
  6253. return false;
  6254. }
  6255. connected = true;
  6256. return true;
  6257. }
  6258. StreamingSocket* StreamingSocket::waitForNextConnection() const
  6259. {
  6260. jassert (isListener || ! connected); // to call this method, you first have to use createListener() to
  6261. // prepare this socket as a listener.
  6262. if (connected && isListener)
  6263. {
  6264. struct sockaddr address;
  6265. juce_socklen_t len = sizeof (sockaddr);
  6266. const int newSocket = (int) accept (handle, &address, &len);
  6267. if (newSocket >= 0 && connected)
  6268. return new StreamingSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  6269. portNumber, newSocket);
  6270. }
  6271. return 0;
  6272. }
  6273. bool StreamingSocket::isLocal() const throw()
  6274. {
  6275. return hostName == "127.0.0.1";
  6276. }
  6277. DatagramSocket::DatagramSocket (const int localPortNumber, const bool allowBroadcast_)
  6278. : portNumber (0),
  6279. handle (-1),
  6280. connected (true),
  6281. allowBroadcast (allowBroadcast_),
  6282. serverAddress (0)
  6283. {
  6284. #if JUCE_WINDOWS
  6285. initWin32Sockets();
  6286. #endif
  6287. handle = (int) socket (AF_INET, SOCK_DGRAM, 0);
  6288. bindToPort (localPortNumber);
  6289. }
  6290. DatagramSocket::DatagramSocket (const String& hostName_, const int portNumber_,
  6291. const int handle_, const int localPortNumber)
  6292. : hostName (hostName_),
  6293. portNumber (portNumber_),
  6294. handle (handle_),
  6295. connected (true),
  6296. allowBroadcast (false),
  6297. serverAddress (0)
  6298. {
  6299. #if JUCE_WINDOWS
  6300. initWin32Sockets();
  6301. #endif
  6302. resetSocketOptions (handle_, true, allowBroadcast);
  6303. bindToPort (localPortNumber);
  6304. }
  6305. DatagramSocket::~DatagramSocket()
  6306. {
  6307. close();
  6308. delete ((struct sockaddr_in*) serverAddress);
  6309. serverAddress = 0;
  6310. }
  6311. void DatagramSocket::close()
  6312. {
  6313. #if JUCE_WINDOWS
  6314. closesocket (handle);
  6315. connected = false;
  6316. #else
  6317. connected = false;
  6318. ::close (handle);
  6319. #endif
  6320. hostName = String::empty;
  6321. portNumber = 0;
  6322. handle = -1;
  6323. }
  6324. bool DatagramSocket::bindToPort (const int port)
  6325. {
  6326. return bindSocketToPort (handle, port);
  6327. }
  6328. bool DatagramSocket::connect (const String& remoteHostName,
  6329. const int remotePortNumber,
  6330. const int timeOutMillisecs)
  6331. {
  6332. if (connected)
  6333. close();
  6334. hostName = remoteHostName;
  6335. portNumber = remotePortNumber;
  6336. connected = connectSocket (handle, true, &serverAddress,
  6337. remoteHostName, remotePortNumber,
  6338. timeOutMillisecs);
  6339. if (! (connected && resetSocketOptions (handle, true, allowBroadcast)))
  6340. {
  6341. close();
  6342. return false;
  6343. }
  6344. return true;
  6345. }
  6346. DatagramSocket* DatagramSocket::waitForNextConnection() const
  6347. {
  6348. struct sockaddr address;
  6349. juce_socklen_t len = sizeof (sockaddr);
  6350. while (waitUntilReady (true, -1) == 1)
  6351. {
  6352. char buf[1];
  6353. if (recvfrom (handle, buf, 0, 0, &address, &len) > 0)
  6354. {
  6355. return new DatagramSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  6356. ntohs (((struct sockaddr_in*) &address)->sin_port),
  6357. -1, -1);
  6358. }
  6359. }
  6360. return 0;
  6361. }
  6362. int DatagramSocket::waitUntilReady (const bool readyForReading,
  6363. const int timeoutMsecs) const
  6364. {
  6365. return connected ? waitForReadiness (handle, readyForReading, timeoutMsecs)
  6366. : -1;
  6367. }
  6368. int DatagramSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  6369. {
  6370. return connected ? readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  6371. : -1;
  6372. }
  6373. int DatagramSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  6374. {
  6375. // You need to call connect() first to set the server address..
  6376. jassert (serverAddress != 0 && connected);
  6377. return connected ? (int) sendto (handle, (const char*) sourceBuffer,
  6378. numBytesToWrite, 0,
  6379. (const struct sockaddr*) serverAddress,
  6380. sizeof (struct sockaddr_in))
  6381. : -1;
  6382. }
  6383. bool DatagramSocket::isLocal() const throw()
  6384. {
  6385. return hostName == "127.0.0.1";
  6386. }
  6387. #if JUCE_MSVC
  6388. #pragma warning (pop)
  6389. #endif
  6390. END_JUCE_NAMESPACE
  6391. /*** End of inlined file: juce_Socket.cpp ***/
  6392. /*** Start of inlined file: juce_URL.cpp ***/
  6393. BEGIN_JUCE_NAMESPACE
  6394. URL::URL()
  6395. {
  6396. }
  6397. URL::URL (const String& url_)
  6398. : url (url_)
  6399. {
  6400. int i = url.indexOfChar ('?');
  6401. if (i >= 0)
  6402. {
  6403. do
  6404. {
  6405. const int nextAmp = url.indexOfChar (i + 1, '&');
  6406. const int equalsPos = url.indexOfChar (i + 1, '=');
  6407. if (equalsPos > i + 1)
  6408. {
  6409. if (nextAmp < 0)
  6410. {
  6411. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  6412. removeEscapeChars (url.substring (equalsPos + 1)));
  6413. }
  6414. else if (nextAmp > 0 && equalsPos < nextAmp)
  6415. {
  6416. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  6417. removeEscapeChars (url.substring (equalsPos + 1, nextAmp)));
  6418. }
  6419. }
  6420. i = nextAmp;
  6421. }
  6422. while (i >= 0);
  6423. url = url.upToFirstOccurrenceOf ("?", false, false);
  6424. }
  6425. }
  6426. URL::URL (const URL& other)
  6427. : url (other.url),
  6428. postData (other.postData),
  6429. parameters (other.parameters),
  6430. filesToUpload (other.filesToUpload),
  6431. mimeTypes (other.mimeTypes)
  6432. {
  6433. }
  6434. URL& URL::operator= (const URL& other)
  6435. {
  6436. url = other.url;
  6437. postData = other.postData;
  6438. parameters = other.parameters;
  6439. filesToUpload = other.filesToUpload;
  6440. mimeTypes = other.mimeTypes;
  6441. return *this;
  6442. }
  6443. URL::~URL()
  6444. {
  6445. }
  6446. static const String getMangledParameters (const StringPairArray& parameters)
  6447. {
  6448. String p;
  6449. for (int i = 0; i < parameters.size(); ++i)
  6450. {
  6451. if (i > 0)
  6452. p += '&';
  6453. p << URL::addEscapeChars (parameters.getAllKeys() [i], true)
  6454. << '='
  6455. << URL::addEscapeChars (parameters.getAllValues() [i], true);
  6456. }
  6457. return p;
  6458. }
  6459. const String URL::toString (const bool includeGetParameters) const
  6460. {
  6461. if (includeGetParameters && parameters.size() > 0)
  6462. return url + "?" + getMangledParameters (parameters);
  6463. else
  6464. return url;
  6465. }
  6466. bool URL::isWellFormed() const
  6467. {
  6468. //xxx TODO
  6469. return url.isNotEmpty();
  6470. }
  6471. static int findStartOfDomain (const String& url)
  6472. {
  6473. int i = 0;
  6474. while (CharacterFunctions::isLetterOrDigit (url[i])
  6475. || CharacterFunctions::indexOfChar (L"+-.", url[i], false) >= 0)
  6476. ++i;
  6477. return url[i] == ':' ? i + 1 : 0;
  6478. }
  6479. const String URL::getDomain() const
  6480. {
  6481. int start = findStartOfDomain (url);
  6482. while (url[start] == '/')
  6483. ++start;
  6484. const int end1 = url.indexOfChar (start, '/');
  6485. const int end2 = url.indexOfChar (start, ':');
  6486. const int end = (end1 < 0 || end2 < 0) ? jmax (end1, end2)
  6487. : jmin (end1, end2);
  6488. return url.substring (start, end);
  6489. }
  6490. const String URL::getSubPath() const
  6491. {
  6492. int start = findStartOfDomain (url);
  6493. while (url[start] == '/')
  6494. ++start;
  6495. const int startOfPath = url.indexOfChar (start, '/') + 1;
  6496. return startOfPath <= 0 ? String::empty
  6497. : url.substring (startOfPath);
  6498. }
  6499. const String URL::getScheme() const
  6500. {
  6501. return url.substring (0, findStartOfDomain (url) - 1);
  6502. }
  6503. const URL URL::withNewSubPath (const String& newPath) const
  6504. {
  6505. int start = findStartOfDomain (url);
  6506. while (url[start] == '/')
  6507. ++start;
  6508. const int startOfPath = url.indexOfChar (start, '/') + 1;
  6509. URL u (*this);
  6510. if (startOfPath > 0)
  6511. u.url = url.substring (0, startOfPath);
  6512. if (! u.url.endsWithChar ('/'))
  6513. u.url << '/';
  6514. if (newPath.startsWithChar ('/'))
  6515. u.url << newPath.substring (1);
  6516. else
  6517. u.url << newPath;
  6518. return u;
  6519. }
  6520. bool URL::isProbablyAWebsiteURL (const String& possibleURL)
  6521. {
  6522. if (possibleURL.startsWithIgnoreCase ("http:")
  6523. || possibleURL.startsWithIgnoreCase ("ftp:"))
  6524. return true;
  6525. if (possibleURL.startsWithIgnoreCase ("file:")
  6526. || possibleURL.containsChar ('@')
  6527. || possibleURL.endsWithChar ('.')
  6528. || (! possibleURL.containsChar ('.')))
  6529. return false;
  6530. if (possibleURL.startsWithIgnoreCase ("www.")
  6531. && possibleURL.substring (5).containsChar ('.'))
  6532. return true;
  6533. const char* commonTLDs[] = { "com", "net", "org", "uk", "de", "fr", "jp" };
  6534. for (int i = 0; i < numElementsInArray (commonTLDs); ++i)
  6535. if ((possibleURL + "/").containsIgnoreCase ("." + String (commonTLDs[i]) + "/"))
  6536. return true;
  6537. return false;
  6538. }
  6539. bool URL::isProbablyAnEmailAddress (const String& possibleEmailAddress)
  6540. {
  6541. const int atSign = possibleEmailAddress.indexOfChar ('@');
  6542. return atSign > 0
  6543. && possibleEmailAddress.lastIndexOfChar ('.') > (atSign + 1)
  6544. && (! possibleEmailAddress.endsWithChar ('.'));
  6545. }
  6546. void* juce_openInternetFile (const String& url,
  6547. const String& headers,
  6548. const MemoryBlock& optionalPostData,
  6549. const bool isPost,
  6550. URL::OpenStreamProgressCallback* callback,
  6551. void* callbackContext,
  6552. int timeOutMs);
  6553. void juce_closeInternetFile (void* handle);
  6554. int juce_readFromInternetFile (void* handle, void* dest, int bytesToRead);
  6555. int juce_seekInInternetFile (void* handle, int newPosition);
  6556. int64 juce_getInternetFileContentLength (void* handle);
  6557. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers);
  6558. class WebInputStream : public InputStream
  6559. {
  6560. public:
  6561. WebInputStream (const URL& url,
  6562. const bool isPost_,
  6563. URL::OpenStreamProgressCallback* const progressCallback_,
  6564. void* const progressCallbackContext_,
  6565. const String& extraHeaders,
  6566. const int timeOutMs_,
  6567. StringPairArray* const responseHeaders)
  6568. : position (0),
  6569. finished (false),
  6570. isPost (isPost_),
  6571. progressCallback (progressCallback_),
  6572. progressCallbackContext (progressCallbackContext_),
  6573. timeOutMs (timeOutMs_)
  6574. {
  6575. server = url.toString (! isPost);
  6576. if (isPost_)
  6577. createHeadersAndPostData (url);
  6578. headers += extraHeaders;
  6579. if (! headers.endsWithChar ('\n'))
  6580. headers << "\r\n";
  6581. handle = juce_openInternetFile (server, headers, postData, isPost,
  6582. progressCallback_, progressCallbackContext_,
  6583. timeOutMs);
  6584. if (responseHeaders != 0)
  6585. juce_getInternetFileHeaders (handle, *responseHeaders);
  6586. }
  6587. ~WebInputStream()
  6588. {
  6589. juce_closeInternetFile (handle);
  6590. }
  6591. bool isError() const { return handle == 0; }
  6592. int64 getTotalLength() { return juce_getInternetFileContentLength (handle); }
  6593. bool isExhausted() { return finished; }
  6594. int64 getPosition() { return position; }
  6595. int read (void* dest, int bytes)
  6596. {
  6597. if (finished || isError())
  6598. {
  6599. return 0;
  6600. }
  6601. else
  6602. {
  6603. const int bytesRead = juce_readFromInternetFile (handle, dest, bytes);
  6604. position += bytesRead;
  6605. if (bytesRead == 0)
  6606. finished = true;
  6607. return bytesRead;
  6608. }
  6609. }
  6610. bool setPosition (int64 wantedPos)
  6611. {
  6612. if (wantedPos != position)
  6613. {
  6614. finished = false;
  6615. const int actualPos = juce_seekInInternetFile (handle, (int) wantedPos);
  6616. if (actualPos == wantedPos)
  6617. {
  6618. position = wantedPos;
  6619. }
  6620. else
  6621. {
  6622. if (wantedPos < position)
  6623. {
  6624. juce_closeInternetFile (handle);
  6625. position = 0;
  6626. finished = false;
  6627. handle = juce_openInternetFile (server, headers, postData, isPost,
  6628. progressCallback, progressCallbackContext,
  6629. timeOutMs);
  6630. }
  6631. skipNextBytes (wantedPos - position);
  6632. }
  6633. }
  6634. return true;
  6635. }
  6636. juce_UseDebuggingNewOperator
  6637. private:
  6638. String server, headers;
  6639. MemoryBlock postData;
  6640. int64 position;
  6641. bool finished;
  6642. const bool isPost;
  6643. void* handle;
  6644. URL::OpenStreamProgressCallback* const progressCallback;
  6645. void* const progressCallbackContext;
  6646. const int timeOutMs;
  6647. void createHeadersAndPostData (const URL& url)
  6648. {
  6649. MemoryOutputStream data (256, 256, &postData);
  6650. if (url.getFilesToUpload().size() > 0)
  6651. {
  6652. // need to upload some files, so do it as multi-part...
  6653. const String boundary (String::toHexString (Random::getSystemRandom().nextInt64()));
  6654. headers << "Content-Type: multipart/form-data; boundary=" << boundary << "\r\n";
  6655. data << "--" << boundary;
  6656. int i;
  6657. for (i = 0; i < url.getParameters().size(); ++i)
  6658. {
  6659. data << "\r\nContent-Disposition: form-data; name=\""
  6660. << url.getParameters().getAllKeys() [i]
  6661. << "\"\r\n\r\n"
  6662. << url.getParameters().getAllValues() [i]
  6663. << "\r\n--"
  6664. << boundary;
  6665. }
  6666. for (i = 0; i < url.getFilesToUpload().size(); ++i)
  6667. {
  6668. const File file (url.getFilesToUpload().getAllValues() [i]);
  6669. const String paramName (url.getFilesToUpload().getAllKeys() [i]);
  6670. data << "\r\nContent-Disposition: form-data; name=\"" << paramName
  6671. << "\"; filename=\"" << file.getFileName() << "\"\r\n";
  6672. const String mimeType (url.getMimeTypesOfUploadFiles()
  6673. .getValue (paramName, String::empty));
  6674. if (mimeType.isNotEmpty())
  6675. data << "Content-Type: " << mimeType << "\r\n";
  6676. data << "Content-Transfer-Encoding: binary\r\n\r\n"
  6677. << file << "\r\n--" << boundary;
  6678. }
  6679. data << "--\r\n";
  6680. data.flush();
  6681. }
  6682. else
  6683. {
  6684. data << getMangledParameters (url.getParameters())
  6685. << url.getPostData();
  6686. data.flush();
  6687. // just a short text attachment, so use simple url encoding..
  6688. headers = "Content-Type: application/x-www-form-urlencoded\r\nContent-length: "
  6689. + String ((unsigned int) postData.getSize())
  6690. + "\r\n";
  6691. }
  6692. }
  6693. WebInputStream (const WebInputStream&);
  6694. WebInputStream& operator= (const WebInputStream&);
  6695. };
  6696. InputStream* URL::createInputStream (const bool usePostCommand,
  6697. OpenStreamProgressCallback* const progressCallback,
  6698. void* const progressCallbackContext,
  6699. const String& extraHeaders,
  6700. const int timeOutMs,
  6701. StringPairArray* const responseHeaders) const
  6702. {
  6703. ScopedPointer <WebInputStream> wi (new WebInputStream (*this, usePostCommand,
  6704. progressCallback, progressCallbackContext,
  6705. extraHeaders, timeOutMs, responseHeaders));
  6706. return wi->isError() ? 0 : wi.release();
  6707. }
  6708. bool URL::readEntireBinaryStream (MemoryBlock& destData,
  6709. const bool usePostCommand) const
  6710. {
  6711. const ScopedPointer <InputStream> in (createInputStream (usePostCommand));
  6712. if (in != 0)
  6713. {
  6714. in->readIntoMemoryBlock (destData, -1);
  6715. return true;
  6716. }
  6717. return false;
  6718. }
  6719. const String URL::readEntireTextStream (const bool usePostCommand) const
  6720. {
  6721. const ScopedPointer <InputStream> in (createInputStream (usePostCommand));
  6722. if (in != 0)
  6723. return in->readEntireStreamAsString();
  6724. return String::empty;
  6725. }
  6726. XmlElement* URL::readEntireXmlStream (const bool usePostCommand) const
  6727. {
  6728. XmlDocument doc (readEntireTextStream (usePostCommand));
  6729. return doc.getDocumentElement();
  6730. }
  6731. const URL URL::withParameter (const String& parameterName,
  6732. const String& parameterValue) const
  6733. {
  6734. URL u (*this);
  6735. u.parameters.set (parameterName, parameterValue);
  6736. return u;
  6737. }
  6738. const URL URL::withFileToUpload (const String& parameterName,
  6739. const File& fileToUpload,
  6740. const String& mimeType) const
  6741. {
  6742. jassert (mimeType.isNotEmpty()); // You need to supply a mime type!
  6743. URL u (*this);
  6744. u.filesToUpload.set (parameterName, fileToUpload.getFullPathName());
  6745. u.mimeTypes.set (parameterName, mimeType);
  6746. return u;
  6747. }
  6748. const URL URL::withPOSTData (const String& postData_) const
  6749. {
  6750. URL u (*this);
  6751. u.postData = postData_;
  6752. return u;
  6753. }
  6754. const StringPairArray& URL::getParameters() const
  6755. {
  6756. return parameters;
  6757. }
  6758. const StringPairArray& URL::getFilesToUpload() const
  6759. {
  6760. return filesToUpload;
  6761. }
  6762. const StringPairArray& URL::getMimeTypesOfUploadFiles() const
  6763. {
  6764. return mimeTypes;
  6765. }
  6766. const String URL::removeEscapeChars (const String& s)
  6767. {
  6768. String result (s.replaceCharacter ('+', ' '));
  6769. int nextPercent = 0;
  6770. for (;;)
  6771. {
  6772. nextPercent = result.indexOfChar (nextPercent, '%');
  6773. if (nextPercent < 0)
  6774. break;
  6775. juce_wchar replacementChar = (juce_wchar) result.substring (nextPercent + 1, nextPercent + 3).getHexValue32();
  6776. result = result.replaceSection (nextPercent, 3, String::charToString (replacementChar));
  6777. ++nextPercent;
  6778. }
  6779. return result;
  6780. }
  6781. const String URL::addEscapeChars (const String& s, const bool isParameter)
  6782. {
  6783. String result;
  6784. result.preallocateStorage (s.length() + 8);
  6785. const char* utf8 = s.toUTF8();
  6786. const char* legalChars = isParameter ? "_-.*!'()"
  6787. : "_-$.*!'(),";
  6788. while (*utf8 != 0)
  6789. {
  6790. const char c = *utf8++;
  6791. if (CharacterFunctions::isLetterOrDigit (c)
  6792. || CharacterFunctions::indexOfChar (legalChars, c, false) >= 0)
  6793. {
  6794. result << c;
  6795. }
  6796. else
  6797. {
  6798. const int v = (int) (uint8) c;
  6799. result << (v < 0x10 ? "%0" : "%") << String::toHexString (v);
  6800. }
  6801. }
  6802. return result;
  6803. }
  6804. bool URL::launchInDefaultBrowser() const
  6805. {
  6806. String u (toString (true));
  6807. if (u.containsChar ('@') && ! u.containsChar (':'))
  6808. u = "mailto:" + u;
  6809. return PlatformUtilities::openDocument (u, String::empty);
  6810. }
  6811. END_JUCE_NAMESPACE
  6812. /*** End of inlined file: juce_URL.cpp ***/
  6813. /*** Start of inlined file: juce_BufferedInputStream.cpp ***/
  6814. BEGIN_JUCE_NAMESPACE
  6815. BufferedInputStream::BufferedInputStream (InputStream* const source_,
  6816. const int bufferSize_,
  6817. const bool deleteSourceWhenDestroyed)
  6818. : source (source_),
  6819. sourceToDelete (deleteSourceWhenDestroyed ? source_ : 0),
  6820. bufferSize (jmax (256, bufferSize_)),
  6821. position (source_->getPosition()),
  6822. lastReadPos (0),
  6823. bufferOverlap (128)
  6824. {
  6825. const int sourceSize = (int) source_->getTotalLength();
  6826. if (sourceSize >= 0)
  6827. bufferSize = jmin (jmax (32, sourceSize), bufferSize);
  6828. bufferStart = position;
  6829. buffer.malloc (bufferSize);
  6830. }
  6831. BufferedInputStream::~BufferedInputStream()
  6832. {
  6833. }
  6834. int64 BufferedInputStream::getTotalLength()
  6835. {
  6836. return source->getTotalLength();
  6837. }
  6838. int64 BufferedInputStream::getPosition()
  6839. {
  6840. return position;
  6841. }
  6842. bool BufferedInputStream::setPosition (int64 newPosition)
  6843. {
  6844. position = jmax ((int64) 0, newPosition);
  6845. return true;
  6846. }
  6847. bool BufferedInputStream::isExhausted()
  6848. {
  6849. return (position >= lastReadPos)
  6850. && source->isExhausted();
  6851. }
  6852. void BufferedInputStream::ensureBuffered()
  6853. {
  6854. const int64 bufferEndOverlap = lastReadPos - bufferOverlap;
  6855. if (position < bufferStart || position >= bufferEndOverlap)
  6856. {
  6857. int bytesRead;
  6858. if (position < lastReadPos
  6859. && position >= bufferEndOverlap
  6860. && position >= bufferStart)
  6861. {
  6862. const int bytesToKeep = (int) (lastReadPos - position);
  6863. memmove (buffer, buffer + (int) (position - bufferStart), bytesToKeep);
  6864. bufferStart = position;
  6865. bytesRead = source->read (buffer + bytesToKeep,
  6866. bufferSize - bytesToKeep);
  6867. lastReadPos += bytesRead;
  6868. bytesRead += bytesToKeep;
  6869. }
  6870. else
  6871. {
  6872. bufferStart = position;
  6873. source->setPosition (bufferStart);
  6874. bytesRead = source->read (buffer, bufferSize);
  6875. lastReadPos = bufferStart + bytesRead;
  6876. }
  6877. while (bytesRead < bufferSize)
  6878. buffer [bytesRead++] = 0;
  6879. }
  6880. }
  6881. int BufferedInputStream::read (void* destBuffer, int maxBytesToRead)
  6882. {
  6883. if (position >= bufferStart
  6884. && position + maxBytesToRead <= lastReadPos)
  6885. {
  6886. memcpy (destBuffer, buffer + (int) (position - bufferStart), maxBytesToRead);
  6887. position += maxBytesToRead;
  6888. return maxBytesToRead;
  6889. }
  6890. else
  6891. {
  6892. if (position < bufferStart || position >= lastReadPos)
  6893. ensureBuffered();
  6894. int bytesRead = 0;
  6895. while (maxBytesToRead > 0)
  6896. {
  6897. const int bytesAvailable = jmin (maxBytesToRead, (int) (lastReadPos - position));
  6898. if (bytesAvailable > 0)
  6899. {
  6900. memcpy (destBuffer, buffer + (int) (position - bufferStart), bytesAvailable);
  6901. maxBytesToRead -= bytesAvailable;
  6902. bytesRead += bytesAvailable;
  6903. position += bytesAvailable;
  6904. destBuffer = static_cast <char*> (destBuffer) + bytesAvailable;
  6905. }
  6906. const int64 oldLastReadPos = lastReadPos;
  6907. ensureBuffered();
  6908. if (oldLastReadPos == lastReadPos)
  6909. break; // if ensureBuffered() failed to read any more data, bail out
  6910. if (isExhausted())
  6911. break;
  6912. }
  6913. return bytesRead;
  6914. }
  6915. }
  6916. const String BufferedInputStream::readString()
  6917. {
  6918. if (position >= bufferStart
  6919. && position < lastReadPos)
  6920. {
  6921. const int maxChars = (int) (lastReadPos - position);
  6922. const char* const src = buffer + (int) (position - bufferStart);
  6923. for (int i = 0; i < maxChars; ++i)
  6924. {
  6925. if (src[i] == 0)
  6926. {
  6927. position += i + 1;
  6928. return String::fromUTF8 (src, i);
  6929. }
  6930. }
  6931. }
  6932. return InputStream::readString();
  6933. }
  6934. END_JUCE_NAMESPACE
  6935. /*** End of inlined file: juce_BufferedInputStream.cpp ***/
  6936. /*** Start of inlined file: juce_FileInputSource.cpp ***/
  6937. BEGIN_JUCE_NAMESPACE
  6938. FileInputSource::FileInputSource (const File& file_)
  6939. : file (file_)
  6940. {
  6941. }
  6942. FileInputSource::~FileInputSource()
  6943. {
  6944. }
  6945. InputStream* FileInputSource::createInputStream()
  6946. {
  6947. return file.createInputStream();
  6948. }
  6949. InputStream* FileInputSource::createInputStreamFor (const String& relatedItemPath)
  6950. {
  6951. return file.getSiblingFile (relatedItemPath).createInputStream();
  6952. }
  6953. int64 FileInputSource::hashCode() const
  6954. {
  6955. return file.hashCode();
  6956. }
  6957. END_JUCE_NAMESPACE
  6958. /*** End of inlined file: juce_FileInputSource.cpp ***/
  6959. /*** Start of inlined file: juce_MemoryInputStream.cpp ***/
  6960. BEGIN_JUCE_NAMESPACE
  6961. MemoryInputStream::MemoryInputStream (const void* const sourceData,
  6962. const size_t sourceDataSize,
  6963. const bool keepInternalCopy)
  6964. : data (static_cast <const char*> (sourceData)),
  6965. dataSize (sourceDataSize),
  6966. position (0)
  6967. {
  6968. if (keepInternalCopy)
  6969. {
  6970. internalCopy.append (data, sourceDataSize);
  6971. data = static_cast <const char*> (internalCopy.getData());
  6972. }
  6973. }
  6974. MemoryInputStream::MemoryInputStream (const MemoryBlock& sourceData,
  6975. const bool keepInternalCopy)
  6976. : data (static_cast <const char*> (sourceData.getData())),
  6977. dataSize (sourceData.getSize()),
  6978. position (0)
  6979. {
  6980. if (keepInternalCopy)
  6981. {
  6982. internalCopy = sourceData;
  6983. data = static_cast <const char*> (internalCopy.getData());
  6984. }
  6985. }
  6986. MemoryInputStream::~MemoryInputStream()
  6987. {
  6988. }
  6989. int64 MemoryInputStream::getTotalLength()
  6990. {
  6991. return dataSize;
  6992. }
  6993. int MemoryInputStream::read (void* const buffer, const int howMany)
  6994. {
  6995. jassert (howMany >= 0);
  6996. const int num = jmin (howMany, (int) (dataSize - position));
  6997. memcpy (buffer, data + position, num);
  6998. position += num;
  6999. return (int) num;
  7000. }
  7001. bool MemoryInputStream::isExhausted()
  7002. {
  7003. return (position >= dataSize);
  7004. }
  7005. bool MemoryInputStream::setPosition (const int64 pos)
  7006. {
  7007. position = (int) jlimit ((int64) 0, (int64) dataSize, pos);
  7008. return true;
  7009. }
  7010. int64 MemoryInputStream::getPosition()
  7011. {
  7012. return position;
  7013. }
  7014. END_JUCE_NAMESPACE
  7015. /*** End of inlined file: juce_MemoryInputStream.cpp ***/
  7016. /*** Start of inlined file: juce_MemoryOutputStream.cpp ***/
  7017. BEGIN_JUCE_NAMESPACE
  7018. MemoryOutputStream::MemoryOutputStream (const size_t initialSize,
  7019. const size_t blockSizeToIncreaseBy,
  7020. MemoryBlock* const memoryBlockToWriteTo)
  7021. : data (memoryBlockToWriteTo),
  7022. position (0),
  7023. size (0),
  7024. blockSize (jmax ((size_t) 16, blockSizeToIncreaseBy))
  7025. {
  7026. if (data == 0)
  7027. dataToDelete = data = new MemoryBlock (initialSize);
  7028. else
  7029. data->setSize (initialSize, false);
  7030. }
  7031. MemoryOutputStream::~MemoryOutputStream()
  7032. {
  7033. flush();
  7034. }
  7035. void MemoryOutputStream::flush()
  7036. {
  7037. if (dataToDelete == 0)
  7038. data->setSize (size, false);
  7039. }
  7040. void MemoryOutputStream::reset() throw()
  7041. {
  7042. position = 0;
  7043. size = 0;
  7044. }
  7045. bool MemoryOutputStream::write (const void* const buffer, int howMany)
  7046. {
  7047. if (howMany > 0)
  7048. {
  7049. size_t storageNeeded = position + howMany;
  7050. if (storageNeeded >= data->getSize())
  7051. {
  7052. // if we need more space, increase the block by at least 10%..
  7053. storageNeeded += jmax (blockSize, storageNeeded / 10);
  7054. storageNeeded = storageNeeded - (storageNeeded % blockSize) + blockSize;
  7055. data->ensureSize (storageNeeded);
  7056. }
  7057. data->copyFrom (buffer, (int) position, howMany);
  7058. position += howMany;
  7059. size = jmax (size, position);
  7060. }
  7061. return true;
  7062. }
  7063. const char* MemoryOutputStream::getData() const throw()
  7064. {
  7065. char* const d = static_cast <char*> (data->getData());
  7066. if (data->getSize() > size)
  7067. d [size] = 0;
  7068. return d;
  7069. }
  7070. bool MemoryOutputStream::setPosition (int64 newPosition)
  7071. {
  7072. if (newPosition <= (int64) size)
  7073. {
  7074. // ok to seek backwards
  7075. position = jlimit ((size_t) 0, size, (size_t) newPosition);
  7076. return true;
  7077. }
  7078. else
  7079. {
  7080. // trying to make it bigger isn't a good thing to do..
  7081. return false;
  7082. }
  7083. }
  7084. const String MemoryOutputStream::toUTF8() const
  7085. {
  7086. return String (getData(), getDataSize());
  7087. }
  7088. END_JUCE_NAMESPACE
  7089. /*** End of inlined file: juce_MemoryOutputStream.cpp ***/
  7090. /*** Start of inlined file: juce_SubregionStream.cpp ***/
  7091. BEGIN_JUCE_NAMESPACE
  7092. SubregionStream::SubregionStream (InputStream* const sourceStream,
  7093. const int64 startPositionInSourceStream_,
  7094. const int64 lengthOfSourceStream_,
  7095. const bool deleteSourceWhenDestroyed)
  7096. : source (sourceStream),
  7097. startPositionInSourceStream (startPositionInSourceStream_),
  7098. lengthOfSourceStream (lengthOfSourceStream_)
  7099. {
  7100. if (deleteSourceWhenDestroyed)
  7101. sourceToDelete = source;
  7102. setPosition (0);
  7103. }
  7104. SubregionStream::~SubregionStream()
  7105. {
  7106. }
  7107. int64 SubregionStream::getTotalLength()
  7108. {
  7109. const int64 srcLen = source->getTotalLength() - startPositionInSourceStream;
  7110. return (lengthOfSourceStream >= 0) ? jmin (lengthOfSourceStream, srcLen)
  7111. : srcLen;
  7112. }
  7113. int64 SubregionStream::getPosition()
  7114. {
  7115. return source->getPosition() - startPositionInSourceStream;
  7116. }
  7117. bool SubregionStream::setPosition (int64 newPosition)
  7118. {
  7119. return source->setPosition (jmax ((int64) 0, newPosition + startPositionInSourceStream));
  7120. }
  7121. int SubregionStream::read (void* destBuffer, int maxBytesToRead)
  7122. {
  7123. if (lengthOfSourceStream < 0)
  7124. {
  7125. return source->read (destBuffer, maxBytesToRead);
  7126. }
  7127. else
  7128. {
  7129. maxBytesToRead = (int) jmin ((int64) maxBytesToRead, lengthOfSourceStream - getPosition());
  7130. if (maxBytesToRead <= 0)
  7131. return 0;
  7132. return source->read (destBuffer, maxBytesToRead);
  7133. }
  7134. }
  7135. bool SubregionStream::isExhausted()
  7136. {
  7137. if (lengthOfSourceStream >= 0)
  7138. return (getPosition() >= lengthOfSourceStream) || source->isExhausted();
  7139. else
  7140. return source->isExhausted();
  7141. }
  7142. END_JUCE_NAMESPACE
  7143. /*** End of inlined file: juce_SubregionStream.cpp ***/
  7144. /*** Start of inlined file: juce_PerformanceCounter.cpp ***/
  7145. BEGIN_JUCE_NAMESPACE
  7146. PerformanceCounter::PerformanceCounter (const String& name_,
  7147. int runsPerPrintout,
  7148. const File& loggingFile)
  7149. : name (name_),
  7150. numRuns (0),
  7151. runsPerPrint (runsPerPrintout),
  7152. totalTime (0),
  7153. outputFile (loggingFile)
  7154. {
  7155. if (outputFile != File::nonexistent)
  7156. {
  7157. String s ("**** Counter for \"");
  7158. s << name_ << "\" started at: "
  7159. << Time::getCurrentTime().toString (true, true)
  7160. << "\r\n";
  7161. outputFile.appendText (s, false, false);
  7162. }
  7163. }
  7164. PerformanceCounter::~PerformanceCounter()
  7165. {
  7166. printStatistics();
  7167. }
  7168. void PerformanceCounter::start()
  7169. {
  7170. started = Time::getHighResolutionTicks();
  7171. }
  7172. void PerformanceCounter::stop()
  7173. {
  7174. const int64 now = Time::getHighResolutionTicks();
  7175. totalTime += 1000.0 * Time::highResolutionTicksToSeconds (now - started);
  7176. if (++numRuns == runsPerPrint)
  7177. printStatistics();
  7178. }
  7179. void PerformanceCounter::printStatistics()
  7180. {
  7181. if (numRuns > 0)
  7182. {
  7183. String s ("Performance count for \"");
  7184. s << name << "\" - average over " << numRuns << " run(s) = ";
  7185. const int micros = (int) (totalTime * (1000.0 / numRuns));
  7186. if (micros > 10000)
  7187. s << (micros/1000) << " millisecs";
  7188. else
  7189. s << micros << " microsecs";
  7190. s << ", total = " << String (totalTime / 1000, 5) << " seconds";
  7191. Logger::outputDebugString (s);
  7192. s << "\r\n";
  7193. if (outputFile != File::nonexistent)
  7194. outputFile.appendText (s, false, false);
  7195. numRuns = 0;
  7196. totalTime = 0;
  7197. }
  7198. }
  7199. END_JUCE_NAMESPACE
  7200. /*** End of inlined file: juce_PerformanceCounter.cpp ***/
  7201. /*** Start of inlined file: juce_Uuid.cpp ***/
  7202. BEGIN_JUCE_NAMESPACE
  7203. Uuid::Uuid()
  7204. {
  7205. // Mix up any available MAC addresses with some time-based pseudo-random numbers
  7206. // to make it very very unlikely that two UUIDs will ever be the same..
  7207. static int64 macAddresses[2];
  7208. static bool hasCheckedMacAddresses = false;
  7209. if (! hasCheckedMacAddresses)
  7210. {
  7211. hasCheckedMacAddresses = true;
  7212. SystemStats::getMACAddresses (macAddresses, 2);
  7213. }
  7214. value.asInt64[0] = macAddresses[0];
  7215. value.asInt64[1] = macAddresses[1];
  7216. // We'll use both a local RNG that is re-seeded, plus the shared RNG,
  7217. // whose seed will carry over between calls to this method.
  7218. Random r (macAddresses[0] ^ macAddresses[1]
  7219. ^ Random::getSystemRandom().nextInt64());
  7220. for (int i = 4; --i >= 0;)
  7221. {
  7222. r.setSeedRandomly(); // calling this repeatedly improves randomness
  7223. value.asInt[i] ^= r.nextInt();
  7224. value.asInt[i] ^= Random::getSystemRandom().nextInt();
  7225. }
  7226. }
  7227. Uuid::~Uuid() throw()
  7228. {
  7229. }
  7230. Uuid::Uuid (const Uuid& other)
  7231. : value (other.value)
  7232. {
  7233. }
  7234. Uuid& Uuid::operator= (const Uuid& other)
  7235. {
  7236. value = other.value;
  7237. return *this;
  7238. }
  7239. bool Uuid::operator== (const Uuid& other) const
  7240. {
  7241. return value.asInt64[0] == other.value.asInt64[0]
  7242. && value.asInt64[1] == other.value.asInt64[1];
  7243. }
  7244. bool Uuid::operator!= (const Uuid& other) const
  7245. {
  7246. return ! operator== (other);
  7247. }
  7248. bool Uuid::isNull() const throw()
  7249. {
  7250. return (value.asInt64 [0] == 0) && (value.asInt64 [1] == 0);
  7251. }
  7252. const String Uuid::toString() const
  7253. {
  7254. return String::toHexString (value.asBytes, sizeof (value.asBytes), 0);
  7255. }
  7256. Uuid::Uuid (const String& uuidString)
  7257. {
  7258. operator= (uuidString);
  7259. }
  7260. Uuid& Uuid::operator= (const String& uuidString)
  7261. {
  7262. MemoryBlock mb;
  7263. mb.loadFromHexString (uuidString);
  7264. mb.ensureSize (sizeof (value.asBytes), true);
  7265. mb.copyTo (value.asBytes, 0, sizeof (value.asBytes));
  7266. return *this;
  7267. }
  7268. Uuid::Uuid (const uint8* const rawData)
  7269. {
  7270. operator= (rawData);
  7271. }
  7272. Uuid& Uuid::operator= (const uint8* const rawData)
  7273. {
  7274. if (rawData != 0)
  7275. memcpy (value.asBytes, rawData, sizeof (value.asBytes));
  7276. else
  7277. zeromem (value.asBytes, sizeof (value.asBytes));
  7278. return *this;
  7279. }
  7280. END_JUCE_NAMESPACE
  7281. /*** End of inlined file: juce_Uuid.cpp ***/
  7282. /*** Start of inlined file: juce_ZipFile.cpp ***/
  7283. BEGIN_JUCE_NAMESPACE
  7284. class ZipFile::ZipEntryInfo
  7285. {
  7286. public:
  7287. ZipFile::ZipEntry entry;
  7288. int streamOffset;
  7289. int compressedSize;
  7290. bool compressed;
  7291. };
  7292. class ZipFile::ZipInputStream : public InputStream
  7293. {
  7294. public:
  7295. ZipInputStream (ZipFile& file_, ZipFile::ZipEntryInfo& zei)
  7296. : file (file_),
  7297. zipEntryInfo (zei),
  7298. pos (0),
  7299. headerSize (0),
  7300. inputStream (0)
  7301. {
  7302. inputStream = file_.inputStream;
  7303. if (file_.inputSource != 0)
  7304. {
  7305. inputStream = file.inputSource->createInputStream();
  7306. }
  7307. else
  7308. {
  7309. #if JUCE_DEBUG
  7310. file_.numOpenStreams++;
  7311. #endif
  7312. }
  7313. char buffer [30];
  7314. if (inputStream != 0
  7315. && inputStream->setPosition (zei.streamOffset)
  7316. && inputStream->read (buffer, 30) == 30
  7317. && ByteOrder::littleEndianInt (buffer) == 0x04034b50)
  7318. {
  7319. headerSize = 30 + ByteOrder::littleEndianShort (buffer + 26)
  7320. + ByteOrder::littleEndianShort (buffer + 28);
  7321. }
  7322. }
  7323. ~ZipInputStream() throw()
  7324. {
  7325. #if JUCE_DEBUG
  7326. if (inputStream != 0 && inputStream == file.inputStream)
  7327. file.numOpenStreams--;
  7328. #endif
  7329. if (inputStream != file.inputStream)
  7330. delete inputStream;
  7331. }
  7332. int64 getTotalLength() throw()
  7333. {
  7334. return zipEntryInfo.compressedSize;
  7335. }
  7336. int read (void* buffer, int howMany) throw()
  7337. {
  7338. if (headerSize <= 0)
  7339. return 0;
  7340. howMany = (int) jmin ((int64) howMany, zipEntryInfo.compressedSize - pos);
  7341. if (inputStream == 0)
  7342. return 0;
  7343. int num;
  7344. if (inputStream == file.inputStream)
  7345. {
  7346. const ScopedLock sl (file.lock);
  7347. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  7348. num = inputStream->read (buffer, howMany);
  7349. }
  7350. else
  7351. {
  7352. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  7353. num = inputStream->read (buffer, howMany);
  7354. }
  7355. pos += num;
  7356. return num;
  7357. }
  7358. bool isExhausted() throw()
  7359. {
  7360. return headerSize <= 0 || pos >= zipEntryInfo.compressedSize;
  7361. }
  7362. int64 getPosition() throw()
  7363. {
  7364. return pos;
  7365. }
  7366. bool setPosition (int64 newPos) throw()
  7367. {
  7368. pos = jlimit ((int64) 0, (int64) zipEntryInfo.compressedSize, newPos);
  7369. return true;
  7370. }
  7371. private:
  7372. ZipFile& file;
  7373. ZipEntryInfo zipEntryInfo;
  7374. int64 pos;
  7375. int headerSize;
  7376. InputStream* inputStream;
  7377. ZipInputStream (const ZipInputStream&);
  7378. ZipInputStream& operator= (const ZipInputStream&);
  7379. };
  7380. ZipFile::ZipFile (InputStream* const source_,
  7381. const bool deleteStreamWhenDestroyed) throw()
  7382. : inputStream (source_)
  7383. #if JUCE_DEBUG
  7384. , numOpenStreams (0)
  7385. #endif
  7386. {
  7387. if (deleteStreamWhenDestroyed)
  7388. streamToDelete = inputStream;
  7389. init();
  7390. }
  7391. ZipFile::ZipFile (const File& file)
  7392. : inputStream (0)
  7393. #if JUCE_DEBUG
  7394. , numOpenStreams (0)
  7395. #endif
  7396. {
  7397. inputSource = new FileInputSource (file);
  7398. init();
  7399. }
  7400. ZipFile::ZipFile (InputSource* const inputSource_)
  7401. : inputStream (0),
  7402. inputSource (inputSource_)
  7403. #if JUCE_DEBUG
  7404. , numOpenStreams (0)
  7405. #endif
  7406. {
  7407. init();
  7408. }
  7409. ZipFile::~ZipFile() throw()
  7410. {
  7411. #if JUCE_DEBUG
  7412. entries.clear();
  7413. // If you hit this assertion, it means you've created a stream to read
  7414. // one of the items in the zipfile, but you've forgotten to delete that
  7415. // stream object before deleting the file.. Streams can't be kept open
  7416. // after the file is deleted because they need to share the input
  7417. // stream that the file uses to read itself.
  7418. jassert (numOpenStreams == 0);
  7419. #endif
  7420. }
  7421. int ZipFile::getNumEntries() const throw()
  7422. {
  7423. return entries.size();
  7424. }
  7425. const ZipFile::ZipEntry* ZipFile::getEntry (const int index) const throw()
  7426. {
  7427. ZipEntryInfo* const zei = entries [index];
  7428. return zei != 0 ? &(zei->entry) : 0;
  7429. }
  7430. int ZipFile::getIndexOfFileName (const String& fileName) const throw()
  7431. {
  7432. for (int i = 0; i < entries.size(); ++i)
  7433. if (entries.getUnchecked (i)->entry.filename == fileName)
  7434. return i;
  7435. return -1;
  7436. }
  7437. const ZipFile::ZipEntry* ZipFile::getEntry (const String& fileName) const throw()
  7438. {
  7439. return getEntry (getIndexOfFileName (fileName));
  7440. }
  7441. InputStream* ZipFile::createStreamForEntry (const int index)
  7442. {
  7443. ZipEntryInfo* const zei = entries[index];
  7444. InputStream* stream = 0;
  7445. if (zei != 0)
  7446. {
  7447. stream = new ZipInputStream (*this, *zei);
  7448. if (zei->compressed)
  7449. {
  7450. stream = new GZIPDecompressorInputStream (stream, true, true,
  7451. zei->entry.uncompressedSize);
  7452. // (much faster to unzip in big blocks using a buffer..)
  7453. stream = new BufferedInputStream (stream, 32768, true);
  7454. }
  7455. }
  7456. return stream;
  7457. }
  7458. class ZipFile::ZipFilenameComparator
  7459. {
  7460. public:
  7461. int compareElements (const ZipFile::ZipEntryInfo* first, const ZipFile::ZipEntryInfo* second)
  7462. {
  7463. return first->entry.filename.compare (second->entry.filename);
  7464. }
  7465. };
  7466. void ZipFile::sortEntriesByFilename()
  7467. {
  7468. ZipFilenameComparator sorter;
  7469. entries.sort (sorter);
  7470. }
  7471. void ZipFile::init()
  7472. {
  7473. ScopedPointer <InputStream> toDelete;
  7474. InputStream* in = inputStream;
  7475. if (inputSource != 0)
  7476. {
  7477. in = inputSource->createInputStream();
  7478. toDelete = in;
  7479. }
  7480. if (in != 0)
  7481. {
  7482. int numEntries = 0;
  7483. int pos = findEndOfZipEntryTable (in, numEntries);
  7484. if (pos >= 0 && pos < in->getTotalLength())
  7485. {
  7486. const int size = (int) (in->getTotalLength() - pos);
  7487. in->setPosition (pos);
  7488. MemoryBlock headerData;
  7489. if (in->readIntoMemoryBlock (headerData, size) == size)
  7490. {
  7491. pos = 0;
  7492. for (int i = 0; i < numEntries; ++i)
  7493. {
  7494. if (pos + 46 > size)
  7495. break;
  7496. const char* const buffer = static_cast <const char*> (headerData.getData()) + pos;
  7497. const int fileNameLen = ByteOrder::littleEndianShort (buffer + 28);
  7498. if (pos + 46 + fileNameLen > size)
  7499. break;
  7500. ZipEntryInfo* const zei = new ZipEntryInfo();
  7501. zei->entry.filename = String::fromUTF8 (buffer + 46, fileNameLen);
  7502. const int time = ByteOrder::littleEndianShort (buffer + 12);
  7503. const int date = ByteOrder::littleEndianShort (buffer + 14);
  7504. const int year = 1980 + (date >> 9);
  7505. const int month = ((date >> 5) & 15) - 1;
  7506. const int day = date & 31;
  7507. const int hours = time >> 11;
  7508. const int minutes = (time >> 5) & 63;
  7509. const int seconds = (time & 31) << 1;
  7510. zei->entry.fileTime = Time (year, month, day, hours, minutes, seconds);
  7511. zei->compressed = ByteOrder::littleEndianShort (buffer + 10) != 0;
  7512. zei->compressedSize = ByteOrder::littleEndianInt (buffer + 20);
  7513. zei->entry.uncompressedSize = ByteOrder::littleEndianInt (buffer + 24);
  7514. zei->streamOffset = ByteOrder::littleEndianInt (buffer + 42);
  7515. entries.add (zei);
  7516. pos += 46 + fileNameLen
  7517. + ByteOrder::littleEndianShort (buffer + 30)
  7518. + ByteOrder::littleEndianShort (buffer + 32);
  7519. }
  7520. }
  7521. }
  7522. }
  7523. }
  7524. int ZipFile::findEndOfZipEntryTable (InputStream* input, int& numEntries)
  7525. {
  7526. BufferedInputStream in (input, 8192, false);
  7527. in.setPosition (in.getTotalLength());
  7528. int64 pos = in.getPosition();
  7529. const int64 lowestPos = jmax ((int64) 0, pos - 1024);
  7530. char buffer [32];
  7531. zeromem (buffer, sizeof (buffer));
  7532. while (pos > lowestPos)
  7533. {
  7534. in.setPosition (pos - 22);
  7535. pos = in.getPosition();
  7536. memcpy (buffer + 22, buffer, 4);
  7537. if (in.read (buffer, 22) != 22)
  7538. return 0;
  7539. for (int i = 0; i < 22; ++i)
  7540. {
  7541. if (ByteOrder::littleEndianInt (buffer + i) == 0x06054b50)
  7542. {
  7543. in.setPosition (pos + i);
  7544. in.read (buffer, 22);
  7545. numEntries = ByteOrder::littleEndianShort (buffer + 10);
  7546. return ByteOrder::littleEndianInt (buffer + 16);
  7547. }
  7548. }
  7549. }
  7550. return 0;
  7551. }
  7552. void ZipFile::uncompressTo (const File& targetDirectory,
  7553. const bool shouldOverwriteFiles)
  7554. {
  7555. for (int i = 0; i < entries.size(); ++i)
  7556. {
  7557. const ZipEntry& zei = entries.getUnchecked(i)->entry;
  7558. const File targetFile (targetDirectory.getChildFile (zei.filename));
  7559. if (zei.filename.endsWithChar ('/'))
  7560. {
  7561. targetFile.createDirectory(); // (entry is a directory, not a file)
  7562. }
  7563. else
  7564. {
  7565. ScopedPointer <InputStream> in (createStreamForEntry (i));
  7566. if (in != 0)
  7567. {
  7568. if (shouldOverwriteFiles)
  7569. targetFile.deleteFile();
  7570. if ((! targetFile.exists())
  7571. && targetFile.getParentDirectory().createDirectory())
  7572. {
  7573. ScopedPointer <FileOutputStream> out (targetFile.createOutputStream());
  7574. if (out != 0)
  7575. {
  7576. out->writeFromInputStream (*in, -1);
  7577. out = 0;
  7578. targetFile.setCreationTime (zei.fileTime);
  7579. targetFile.setLastModificationTime (zei.fileTime);
  7580. targetFile.setLastAccessTime (zei.fileTime);
  7581. }
  7582. }
  7583. }
  7584. }
  7585. }
  7586. }
  7587. END_JUCE_NAMESPACE
  7588. /*** End of inlined file: juce_ZipFile.cpp ***/
  7589. /*** Start of inlined file: juce_CharacterFunctions.cpp ***/
  7590. #if JUCE_MSVC
  7591. #pragma warning (push)
  7592. #pragma warning (disable: 4514 4996)
  7593. #endif
  7594. #include <cwctype>
  7595. #include <cctype>
  7596. #include <ctime>
  7597. BEGIN_JUCE_NAMESPACE
  7598. int CharacterFunctions::length (const char* const s) throw()
  7599. {
  7600. return (int) strlen (s);
  7601. }
  7602. int CharacterFunctions::length (const juce_wchar* const s) throw()
  7603. {
  7604. return (int) wcslen (s);
  7605. }
  7606. void CharacterFunctions::copy (char* dest, const char* src, const int maxChars) throw()
  7607. {
  7608. strncpy (dest, src, maxChars);
  7609. }
  7610. void CharacterFunctions::copy (juce_wchar* dest, const juce_wchar* src, int maxChars) throw()
  7611. {
  7612. wcsncpy (dest, src, maxChars);
  7613. }
  7614. void CharacterFunctions::copy (juce_wchar* dest, const char* src, const int maxChars) throw()
  7615. {
  7616. mbstowcs (dest, src, maxChars);
  7617. }
  7618. void CharacterFunctions::copy (char* dest, const juce_wchar* src, const int maxChars) throw()
  7619. {
  7620. wcstombs (dest, src, maxChars);
  7621. }
  7622. int CharacterFunctions::bytesRequiredForCopy (const juce_wchar* src) throw()
  7623. {
  7624. return (int) wcstombs (0, src, 0);
  7625. }
  7626. void CharacterFunctions::append (char* dest, const char* src) throw()
  7627. {
  7628. strcat (dest, src);
  7629. }
  7630. void CharacterFunctions::append (juce_wchar* dest, const juce_wchar* src) throw()
  7631. {
  7632. wcscat (dest, src);
  7633. }
  7634. int CharacterFunctions::compare (const char* const s1, const char* const s2) throw()
  7635. {
  7636. return strcmp (s1, s2);
  7637. }
  7638. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2) throw()
  7639. {
  7640. jassert (s1 != 0 && s2 != 0);
  7641. return wcscmp (s1, s2);
  7642. }
  7643. int CharacterFunctions::compare (const char* const s1, const char* const s2, const int maxChars) throw()
  7644. {
  7645. jassert (s1 != 0 && s2 != 0);
  7646. return strncmp (s1, s2, maxChars);
  7647. }
  7648. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  7649. {
  7650. jassert (s1 != 0 && s2 != 0);
  7651. return wcsncmp (s1, s2, maxChars);
  7652. }
  7653. int CharacterFunctions::compare (const juce_wchar* s1, const char* s2) throw()
  7654. {
  7655. jassert (s1 != 0 && s2 != 0);
  7656. for (;;)
  7657. {
  7658. const int diff = (int) (*s1 - (juce_wchar) (unsigned char) *s2);
  7659. if (diff != 0)
  7660. return diff;
  7661. else if (*s1 == 0)
  7662. break;
  7663. ++s1;
  7664. ++s2;
  7665. }
  7666. return 0;
  7667. }
  7668. int CharacterFunctions::compare (const char* s1, const juce_wchar* s2) throw()
  7669. {
  7670. return -compare (s2, s1);
  7671. }
  7672. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2) throw()
  7673. {
  7674. jassert (s1 != 0 && s2 != 0);
  7675. #if JUCE_WINDOWS
  7676. return stricmp (s1, s2);
  7677. #else
  7678. return strcasecmp (s1, s2);
  7679. #endif
  7680. }
  7681. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2) throw()
  7682. {
  7683. jassert (s1 != 0 && s2 != 0);
  7684. #if JUCE_WINDOWS
  7685. return _wcsicmp (s1, s2);
  7686. #else
  7687. for (;;)
  7688. {
  7689. if (*s1 != *s2)
  7690. {
  7691. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  7692. if (diff != 0)
  7693. return diff < 0 ? -1 : 1;
  7694. }
  7695. else if (*s1 == 0)
  7696. break;
  7697. ++s1;
  7698. ++s2;
  7699. }
  7700. return 0;
  7701. #endif
  7702. }
  7703. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const char* s2) throw()
  7704. {
  7705. jassert (s1 != 0 && s2 != 0);
  7706. for (;;)
  7707. {
  7708. if (*s1 != *s2)
  7709. {
  7710. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  7711. if (diff != 0)
  7712. return diff < 0 ? -1 : 1;
  7713. }
  7714. else if (*s1 == 0)
  7715. break;
  7716. ++s1;
  7717. ++s2;
  7718. }
  7719. return 0;
  7720. }
  7721. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2, const int maxChars) throw()
  7722. {
  7723. jassert (s1 != 0 && s2 != 0);
  7724. #if JUCE_WINDOWS
  7725. return strnicmp (s1, s2, maxChars);
  7726. #else
  7727. return strncasecmp (s1, s2, maxChars);
  7728. #endif
  7729. }
  7730. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  7731. {
  7732. jassert (s1 != 0 && s2 != 0);
  7733. #if JUCE_WINDOWS
  7734. return _wcsnicmp (s1, s2, maxChars);
  7735. #else
  7736. while (--maxChars >= 0)
  7737. {
  7738. if (*s1 != *s2)
  7739. {
  7740. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  7741. if (diff != 0)
  7742. return diff < 0 ? -1 : 1;
  7743. }
  7744. else if (*s1 == 0)
  7745. break;
  7746. ++s1;
  7747. ++s2;
  7748. }
  7749. return 0;
  7750. #endif
  7751. }
  7752. const char* CharacterFunctions::find (const char* const haystack, const char* const needle) throw()
  7753. {
  7754. return strstr (haystack, needle);
  7755. }
  7756. const juce_wchar* CharacterFunctions::find (const juce_wchar* haystack, const juce_wchar* const needle) throw()
  7757. {
  7758. return wcsstr (haystack, needle);
  7759. }
  7760. int CharacterFunctions::indexOfChar (const char* const haystack, const char needle, const bool ignoreCase) throw()
  7761. {
  7762. if (haystack != 0)
  7763. {
  7764. int i = 0;
  7765. if (ignoreCase)
  7766. {
  7767. const char n1 = toLowerCase (needle);
  7768. const char n2 = toUpperCase (needle);
  7769. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  7770. {
  7771. while (haystack[i] != 0)
  7772. {
  7773. if (haystack[i] == n1 || haystack[i] == n2)
  7774. return i;
  7775. ++i;
  7776. }
  7777. return -1;
  7778. }
  7779. jassert (n1 == needle);
  7780. }
  7781. while (haystack[i] != 0)
  7782. {
  7783. if (haystack[i] == needle)
  7784. return i;
  7785. ++i;
  7786. }
  7787. }
  7788. return -1;
  7789. }
  7790. int CharacterFunctions::indexOfChar (const juce_wchar* const haystack, const juce_wchar needle, const bool ignoreCase) throw()
  7791. {
  7792. if (haystack != 0)
  7793. {
  7794. int i = 0;
  7795. if (ignoreCase)
  7796. {
  7797. const juce_wchar n1 = toLowerCase (needle);
  7798. const juce_wchar n2 = toUpperCase (needle);
  7799. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  7800. {
  7801. while (haystack[i] != 0)
  7802. {
  7803. if (haystack[i] == n1 || haystack[i] == n2)
  7804. return i;
  7805. ++i;
  7806. }
  7807. return -1;
  7808. }
  7809. jassert (n1 == needle);
  7810. }
  7811. while (haystack[i] != 0)
  7812. {
  7813. if (haystack[i] == needle)
  7814. return i;
  7815. ++i;
  7816. }
  7817. }
  7818. return -1;
  7819. }
  7820. int CharacterFunctions::indexOfCharFast (const char* const haystack, const char needle) throw()
  7821. {
  7822. jassert (haystack != 0);
  7823. int i = 0;
  7824. while (haystack[i] != 0)
  7825. {
  7826. if (haystack[i] == needle)
  7827. return i;
  7828. ++i;
  7829. }
  7830. return -1;
  7831. }
  7832. int CharacterFunctions::indexOfCharFast (const juce_wchar* const haystack, const juce_wchar needle) throw()
  7833. {
  7834. jassert (haystack != 0);
  7835. int i = 0;
  7836. while (haystack[i] != 0)
  7837. {
  7838. if (haystack[i] == needle)
  7839. return i;
  7840. ++i;
  7841. }
  7842. return -1;
  7843. }
  7844. int CharacterFunctions::getIntialSectionContainingOnly (const char* const text, const char* const allowedChars) throw()
  7845. {
  7846. return allowedChars == 0 ? 0 : (int) strspn (text, allowedChars);
  7847. }
  7848. int CharacterFunctions::getIntialSectionContainingOnly (const juce_wchar* const text, const juce_wchar* const allowedChars) throw()
  7849. {
  7850. if (allowedChars == 0)
  7851. return 0;
  7852. int i = 0;
  7853. for (;;)
  7854. {
  7855. if (indexOfCharFast (allowedChars, text[i]) < 0)
  7856. break;
  7857. ++i;
  7858. }
  7859. return i;
  7860. }
  7861. int CharacterFunctions::ftime (char* const dest, const int maxChars, const char* const format, const struct tm* const tm) throw()
  7862. {
  7863. return (int) strftime (dest, maxChars, format, tm);
  7864. }
  7865. int CharacterFunctions::ftime (juce_wchar* const dest, const int maxChars, const juce_wchar* const format, const struct tm* const tm) throw()
  7866. {
  7867. return (int) wcsftime (dest, maxChars, format, tm);
  7868. }
  7869. int CharacterFunctions::getIntValue (const char* const s) throw()
  7870. {
  7871. return atoi (s);
  7872. }
  7873. int CharacterFunctions::getIntValue (const juce_wchar* s) throw()
  7874. {
  7875. #if JUCE_WINDOWS
  7876. return _wtoi (s);
  7877. #else
  7878. int v = 0;
  7879. while (isWhitespace (*s))
  7880. ++s;
  7881. const bool isNeg = *s == '-';
  7882. if (isNeg)
  7883. ++s;
  7884. for (;;)
  7885. {
  7886. const wchar_t c = *s++;
  7887. if (c >= '0' && c <= '9')
  7888. v = v * 10 + (int) (c - '0');
  7889. else
  7890. break;
  7891. }
  7892. return isNeg ? -v : v;
  7893. #endif
  7894. }
  7895. int64 CharacterFunctions::getInt64Value (const char* s) throw()
  7896. {
  7897. #if JUCE_LINUX
  7898. return atoll (s);
  7899. #elif JUCE_WINDOWS
  7900. return _atoi64 (s);
  7901. #else
  7902. int64 v = 0;
  7903. while (isWhitespace (*s))
  7904. ++s;
  7905. const bool isNeg = *s == '-';
  7906. if (isNeg)
  7907. ++s;
  7908. for (;;)
  7909. {
  7910. const char c = *s++;
  7911. if (c >= '0' && c <= '9')
  7912. v = v * 10 + (int64) (c - '0');
  7913. else
  7914. break;
  7915. }
  7916. return isNeg ? -v : v;
  7917. #endif
  7918. }
  7919. int64 CharacterFunctions::getInt64Value (const juce_wchar* s) throw()
  7920. {
  7921. #if JUCE_WINDOWS
  7922. return _wtoi64 (s);
  7923. #else
  7924. int64 v = 0;
  7925. while (isWhitespace (*s))
  7926. ++s;
  7927. const bool isNeg = *s == '-';
  7928. if (isNeg)
  7929. ++s;
  7930. for (;;)
  7931. {
  7932. const juce_wchar c = *s++;
  7933. if (c >= '0' && c <= '9')
  7934. v = v * 10 + (int64) (c - '0');
  7935. else
  7936. break;
  7937. }
  7938. return isNeg ? -v : v;
  7939. #endif
  7940. }
  7941. static double juce_mulexp10 (const double value, int exponent) throw()
  7942. {
  7943. if (exponent == 0)
  7944. return value;
  7945. if (value == 0)
  7946. return 0;
  7947. const bool negative = (exponent < 0);
  7948. if (negative)
  7949. exponent = -exponent;
  7950. double result = 1.0, power = 10.0;
  7951. for (int bit = 1; exponent != 0; bit <<= 1)
  7952. {
  7953. if ((exponent & bit) != 0)
  7954. {
  7955. exponent ^= bit;
  7956. result *= power;
  7957. if (exponent == 0)
  7958. break;
  7959. }
  7960. power *= power;
  7961. }
  7962. return negative ? (value / result) : (value * result);
  7963. }
  7964. template <class CharType>
  7965. double juce_atof (const CharType* const original) throw()
  7966. {
  7967. double result[3] = { 0, 0, 0 }, accumulator[2] = { 0, 0 };
  7968. int exponentAdjustment[2] = { 0, 0 }, exponentAccumulator[2] = { -1, -1 };
  7969. int exponent = 0, decPointIndex = 0, digit = 0;
  7970. int lastDigit = 0, numSignificantDigits = 0;
  7971. bool isNegative = false, digitsFound = false;
  7972. const int maxSignificantDigits = 15 + 2;
  7973. const CharType* s = original;
  7974. while (CharacterFunctions::isWhitespace (*s))
  7975. ++s;
  7976. switch (*s)
  7977. {
  7978. case '-': isNegative = true; // fall-through..
  7979. case '+': ++s;
  7980. }
  7981. if (*s == 'n' || *s == 'N' || *s == 'i' || *s == 'I')
  7982. return atof (String (original).toUTF8()); // Let the c library deal with NAN and INF
  7983. for (;;)
  7984. {
  7985. if (CharacterFunctions::isDigit (*s))
  7986. {
  7987. lastDigit = digit;
  7988. digit = *s++ - '0';
  7989. digitsFound = true;
  7990. if (decPointIndex != 0)
  7991. exponentAdjustment[1]++;
  7992. if (numSignificantDigits == 0 && digit == 0)
  7993. continue;
  7994. if (++numSignificantDigits > maxSignificantDigits)
  7995. {
  7996. if (digit > 5)
  7997. ++accumulator [decPointIndex];
  7998. else if (digit == 5 && (lastDigit & 1) != 0)
  7999. ++accumulator [decPointIndex];
  8000. if (decPointIndex > 0)
  8001. exponentAdjustment[1]--;
  8002. else
  8003. exponentAdjustment[0]++;
  8004. while (CharacterFunctions::isDigit (*s))
  8005. {
  8006. ++s;
  8007. if (decPointIndex == 0)
  8008. exponentAdjustment[0]++;
  8009. }
  8010. }
  8011. else
  8012. {
  8013. const double maxAccumulatorValue = (double) ((std::numeric_limits<unsigned int>::max() - 9) / 10);
  8014. if (accumulator [decPointIndex] > maxAccumulatorValue)
  8015. {
  8016. result [decPointIndex] = juce_mulexp10 (result [decPointIndex], exponentAccumulator [decPointIndex])
  8017. + accumulator [decPointIndex];
  8018. accumulator [decPointIndex] = 0;
  8019. exponentAccumulator [decPointIndex] = 0;
  8020. }
  8021. accumulator [decPointIndex] = accumulator[decPointIndex] * 10 + digit;
  8022. exponentAccumulator [decPointIndex]++;
  8023. }
  8024. }
  8025. else if (decPointIndex == 0 && *s == '.')
  8026. {
  8027. ++s;
  8028. decPointIndex = 1;
  8029. if (numSignificantDigits > maxSignificantDigits)
  8030. {
  8031. while (CharacterFunctions::isDigit (*s))
  8032. ++s;
  8033. break;
  8034. }
  8035. }
  8036. else
  8037. {
  8038. break;
  8039. }
  8040. }
  8041. result[0] = juce_mulexp10 (result[0], exponentAccumulator[0]) + accumulator[0];
  8042. if (decPointIndex != 0)
  8043. result[1] = juce_mulexp10 (result[1], exponentAccumulator[1]) + accumulator[1];
  8044. if ((*s == 'e' || *s == 'E') && digitsFound)
  8045. {
  8046. bool negativeExponent = false;
  8047. switch (*++s)
  8048. {
  8049. case '-': negativeExponent = true; // fall-through..
  8050. case '+': ++s;
  8051. }
  8052. while (CharacterFunctions::isDigit (*s))
  8053. exponent = (exponent * 10) + (*s++ - '0');
  8054. if (negativeExponent)
  8055. exponent = -exponent;
  8056. }
  8057. double r = juce_mulexp10 (result[0], exponent + exponentAdjustment[0]);
  8058. if (decPointIndex != 0)
  8059. r += juce_mulexp10 (result[1], exponent - exponentAdjustment[1]);
  8060. return isNegative ? -r : r;
  8061. }
  8062. double CharacterFunctions::getDoubleValue (const char* const s) throw()
  8063. {
  8064. return juce_atof <char> (s);
  8065. }
  8066. double CharacterFunctions::getDoubleValue (const juce_wchar* const s) throw()
  8067. {
  8068. return juce_atof <juce_wchar> (s);
  8069. }
  8070. char CharacterFunctions::toUpperCase (const char character) throw()
  8071. {
  8072. return (char) toupper (character);
  8073. }
  8074. juce_wchar CharacterFunctions::toUpperCase (const juce_wchar character) throw()
  8075. {
  8076. return towupper (character);
  8077. }
  8078. void CharacterFunctions::toUpperCase (char* s) throw()
  8079. {
  8080. #if JUCE_WINDOWS
  8081. strupr (s);
  8082. #else
  8083. while (*s != 0)
  8084. {
  8085. *s = toUpperCase (*s);
  8086. ++s;
  8087. }
  8088. #endif
  8089. }
  8090. void CharacterFunctions::toUpperCase (juce_wchar* s) throw()
  8091. {
  8092. #if JUCE_WINDOWS
  8093. _wcsupr (s);
  8094. #else
  8095. while (*s != 0)
  8096. {
  8097. *s = toUpperCase (*s);
  8098. ++s;
  8099. }
  8100. #endif
  8101. }
  8102. bool CharacterFunctions::isUpperCase (const char character) throw()
  8103. {
  8104. return isupper (character) != 0;
  8105. }
  8106. bool CharacterFunctions::isUpperCase (const juce_wchar character) throw()
  8107. {
  8108. #if JUCE_WINDOWS
  8109. return iswupper (character) != 0;
  8110. #else
  8111. return toLowerCase (character) != character;
  8112. #endif
  8113. }
  8114. char CharacterFunctions::toLowerCase (const char character) throw()
  8115. {
  8116. return (char) tolower (character);
  8117. }
  8118. juce_wchar CharacterFunctions::toLowerCase (const juce_wchar character) throw()
  8119. {
  8120. return towlower (character);
  8121. }
  8122. void CharacterFunctions::toLowerCase (char* s) throw()
  8123. {
  8124. #if JUCE_WINDOWS
  8125. strlwr (s);
  8126. #else
  8127. while (*s != 0)
  8128. {
  8129. *s = toLowerCase (*s);
  8130. ++s;
  8131. }
  8132. #endif
  8133. }
  8134. void CharacterFunctions::toLowerCase (juce_wchar* s) throw()
  8135. {
  8136. #if JUCE_WINDOWS
  8137. _wcslwr (s);
  8138. #else
  8139. while (*s != 0)
  8140. {
  8141. *s = toLowerCase (*s);
  8142. ++s;
  8143. }
  8144. #endif
  8145. }
  8146. bool CharacterFunctions::isLowerCase (const char character) throw()
  8147. {
  8148. return islower (character) != 0;
  8149. }
  8150. bool CharacterFunctions::isLowerCase (const juce_wchar character) throw()
  8151. {
  8152. #if JUCE_WINDOWS
  8153. return iswlower (character) != 0;
  8154. #else
  8155. return toUpperCase (character) != character;
  8156. #endif
  8157. }
  8158. bool CharacterFunctions::isWhitespace (const char character) throw()
  8159. {
  8160. return character == ' ' || (character <= 13 && character >= 9);
  8161. }
  8162. bool CharacterFunctions::isWhitespace (const juce_wchar character) throw()
  8163. {
  8164. return iswspace (character) != 0;
  8165. }
  8166. bool CharacterFunctions::isDigit (const char character) throw()
  8167. {
  8168. return (character >= '0' && character <= '9');
  8169. }
  8170. bool CharacterFunctions::isDigit (const juce_wchar character) throw()
  8171. {
  8172. return iswdigit (character) != 0;
  8173. }
  8174. bool CharacterFunctions::isLetter (const char character) throw()
  8175. {
  8176. return (character >= 'a' && character <= 'z')
  8177. || (character >= 'A' && character <= 'Z');
  8178. }
  8179. bool CharacterFunctions::isLetter (const juce_wchar character) throw()
  8180. {
  8181. return iswalpha (character) != 0;
  8182. }
  8183. bool CharacterFunctions::isLetterOrDigit (const char character) throw()
  8184. {
  8185. return (character >= 'a' && character <= 'z')
  8186. || (character >= 'A' && character <= 'Z')
  8187. || (character >= '0' && character <= '9');
  8188. }
  8189. bool CharacterFunctions::isLetterOrDigit (const juce_wchar character) throw()
  8190. {
  8191. return iswalnum (character) != 0;
  8192. }
  8193. int CharacterFunctions::getHexDigitValue (const juce_wchar digit) throw()
  8194. {
  8195. unsigned int d = digit - '0';
  8196. if (d < (unsigned int) 10)
  8197. return (int) d;
  8198. d += (unsigned int) ('0' - 'a');
  8199. if (d < (unsigned int) 6)
  8200. return (int) d + 10;
  8201. d += (unsigned int) ('a' - 'A');
  8202. if (d < (unsigned int) 6)
  8203. return (int) d + 10;
  8204. return -1;
  8205. }
  8206. #if JUCE_MSVC
  8207. #pragma warning (pop)
  8208. #endif
  8209. END_JUCE_NAMESPACE
  8210. /*** End of inlined file: juce_CharacterFunctions.cpp ***/
  8211. /*** Start of inlined file: juce_LocalisedStrings.cpp ***/
  8212. BEGIN_JUCE_NAMESPACE
  8213. LocalisedStrings::LocalisedStrings (const String& fileContents)
  8214. {
  8215. loadFromText (fileContents);
  8216. }
  8217. LocalisedStrings::LocalisedStrings (const File& fileToLoad)
  8218. {
  8219. loadFromText (fileToLoad.loadFileAsString());
  8220. }
  8221. LocalisedStrings::~LocalisedStrings()
  8222. {
  8223. }
  8224. const String LocalisedStrings::translate (const String& text) const
  8225. {
  8226. return translations.getValue (text, text);
  8227. }
  8228. static int findCloseQuote (const String& text, int startPos)
  8229. {
  8230. juce_wchar lastChar = 0;
  8231. for (;;)
  8232. {
  8233. const juce_wchar c = text [startPos];
  8234. if (c == 0 || (c == '"' && lastChar != '\\'))
  8235. break;
  8236. lastChar = c;
  8237. ++startPos;
  8238. }
  8239. return startPos;
  8240. }
  8241. static const String unescapeString (const String& s)
  8242. {
  8243. return s.replace ("\\\"", "\"")
  8244. .replace ("\\\'", "\'")
  8245. .replace ("\\t", "\t")
  8246. .replace ("\\r", "\r")
  8247. .replace ("\\n", "\n");
  8248. }
  8249. void LocalisedStrings::loadFromText (const String& fileContents)
  8250. {
  8251. StringArray lines;
  8252. lines.addLines (fileContents);
  8253. for (int i = 0; i < lines.size(); ++i)
  8254. {
  8255. String line (lines[i].trim());
  8256. if (line.startsWithChar ('"'))
  8257. {
  8258. int closeQuote = findCloseQuote (line, 1);
  8259. const String originalText (unescapeString (line.substring (1, closeQuote)));
  8260. if (originalText.isNotEmpty())
  8261. {
  8262. const int openingQuote = findCloseQuote (line, closeQuote + 1);
  8263. closeQuote = findCloseQuote (line, openingQuote + 1);
  8264. const String newText (unescapeString (line.substring (openingQuote + 1, closeQuote)));
  8265. if (newText.isNotEmpty())
  8266. translations.set (originalText, newText);
  8267. }
  8268. }
  8269. else if (line.startsWithIgnoreCase ("language:"))
  8270. {
  8271. languageName = line.substring (9).trim();
  8272. }
  8273. else if (line.startsWithIgnoreCase ("countries:"))
  8274. {
  8275. countryCodes.addTokens (line.substring (10).trim(), true);
  8276. countryCodes.trim();
  8277. countryCodes.removeEmptyStrings();
  8278. }
  8279. }
  8280. }
  8281. void LocalisedStrings::setIgnoresCase (const bool shouldIgnoreCase)
  8282. {
  8283. translations.setIgnoresCase (shouldIgnoreCase);
  8284. }
  8285. static CriticalSection currentMappingsLock;
  8286. static LocalisedStrings* currentMappings = 0;
  8287. void LocalisedStrings::setCurrentMappings (LocalisedStrings* newTranslations)
  8288. {
  8289. const ScopedLock sl (currentMappingsLock);
  8290. delete currentMappings;
  8291. currentMappings = newTranslations;
  8292. }
  8293. LocalisedStrings* LocalisedStrings::getCurrentMappings()
  8294. {
  8295. return currentMappings;
  8296. }
  8297. const String LocalisedStrings::translateWithCurrentMappings (const String& text)
  8298. {
  8299. const ScopedLock sl (currentMappingsLock);
  8300. if (currentMappings != 0)
  8301. return currentMappings->translate (text);
  8302. return text;
  8303. }
  8304. const String LocalisedStrings::translateWithCurrentMappings (const char* text)
  8305. {
  8306. return translateWithCurrentMappings (String (text));
  8307. }
  8308. END_JUCE_NAMESPACE
  8309. /*** End of inlined file: juce_LocalisedStrings.cpp ***/
  8310. /*** Start of inlined file: juce_String.cpp ***/
  8311. #if JUCE_MSVC
  8312. #pragma warning (push)
  8313. #pragma warning (disable: 4514)
  8314. #endif
  8315. #include <locale>
  8316. BEGIN_JUCE_NAMESPACE
  8317. #if JUCE_MSVC
  8318. #pragma warning (pop)
  8319. #endif
  8320. #if defined (JUCE_STRINGS_ARE_UNICODE) && ! JUCE_STRINGS_ARE_UNICODE
  8321. #error "JUCE_STRINGS_ARE_UNICODE is deprecated! All strings are now unicode by default."
  8322. #endif
  8323. class StringHolder
  8324. {
  8325. public:
  8326. StringHolder()
  8327. : refCount (0x3fffffff), allocatedNumChars (0)
  8328. {
  8329. text[0] = 0;
  8330. }
  8331. static juce_wchar* createUninitialised (const size_t numChars)
  8332. {
  8333. StringHolder* const s = reinterpret_cast <StringHolder*> (new char [sizeof (StringHolder) + numChars * sizeof (juce_wchar)]);
  8334. s->refCount.value = 0;
  8335. s->allocatedNumChars = numChars;
  8336. return &(s->text[0]);
  8337. }
  8338. static juce_wchar* createCopy (const juce_wchar* const src, const size_t numChars)
  8339. {
  8340. juce_wchar* const dest = createUninitialised (numChars);
  8341. copyChars (dest, src, numChars);
  8342. return dest;
  8343. }
  8344. static juce_wchar* createCopy (const char* const src, const size_t numChars)
  8345. {
  8346. juce_wchar* const dest = createUninitialised (numChars);
  8347. CharacterFunctions::copy (dest, src, (int) numChars);
  8348. dest [numChars] = 0;
  8349. return dest;
  8350. }
  8351. static inline juce_wchar* getEmpty() throw()
  8352. {
  8353. return &(empty.text[0]);
  8354. }
  8355. static void retain (juce_wchar* const text) throw()
  8356. {
  8357. ++(bufferFromText (text)->refCount);
  8358. }
  8359. static inline void release (StringHolder* const b) throw()
  8360. {
  8361. if (--(b->refCount) == -1 && b != &empty)
  8362. delete[] reinterpret_cast <char*> (b);
  8363. }
  8364. static void release (juce_wchar* const text) throw()
  8365. {
  8366. release (bufferFromText (text));
  8367. }
  8368. static juce_wchar* makeUnique (juce_wchar* const text)
  8369. {
  8370. StringHolder* const b = bufferFromText (text);
  8371. if (b->refCount.get() <= 0)
  8372. return text;
  8373. juce_wchar* const newText = createCopy (text, b->allocatedNumChars);
  8374. release (b);
  8375. return newText;
  8376. }
  8377. static juce_wchar* makeUniqueWithSize (juce_wchar* const text, size_t numChars)
  8378. {
  8379. StringHolder* const b = bufferFromText (text);
  8380. if (b->refCount.get() <= 0 && b->allocatedNumChars >= numChars)
  8381. return text;
  8382. juce_wchar* const newText = createUninitialised (jmax (b->allocatedNumChars, numChars));
  8383. copyChars (newText, text, b->allocatedNumChars);
  8384. release (b);
  8385. return newText;
  8386. }
  8387. static size_t getAllocatedNumChars (juce_wchar* const text) throw()
  8388. {
  8389. return bufferFromText (text)->allocatedNumChars;
  8390. }
  8391. static void copyChars (juce_wchar* const dest, const juce_wchar* const src, const size_t numChars) throw()
  8392. {
  8393. memcpy (dest, src, numChars * sizeof (juce_wchar));
  8394. dest [numChars] = 0;
  8395. }
  8396. Atomic<int> refCount;
  8397. size_t allocatedNumChars;
  8398. juce_wchar text[1];
  8399. static StringHolder empty;
  8400. private:
  8401. static inline StringHolder* bufferFromText (void* const text) throw()
  8402. {
  8403. // (Can't use offsetof() here because of warnings about this not being a POD)
  8404. return reinterpret_cast <StringHolder*> (static_cast <char*> (text)
  8405. - (reinterpret_cast <size_t> (reinterpret_cast <StringHolder*> (1)->text) - 1));
  8406. }
  8407. };
  8408. StringHolder StringHolder::empty;
  8409. const String String::empty;
  8410. void String::createInternal (const juce_wchar* const t, const size_t numChars)
  8411. {
  8412. jassert (t[numChars] == 0); // must have a null terminator
  8413. text = StringHolder::createCopy (t, numChars);
  8414. }
  8415. void String::appendInternal (const juce_wchar* const newText, const int numExtraChars)
  8416. {
  8417. if (numExtraChars > 0)
  8418. {
  8419. const int oldLen = length();
  8420. const int newTotalLen = oldLen + numExtraChars;
  8421. text = StringHolder::makeUniqueWithSize (text, newTotalLen);
  8422. StringHolder::copyChars (text + oldLen, newText, numExtraChars);
  8423. }
  8424. }
  8425. void String::preallocateStorage (const size_t numChars)
  8426. {
  8427. text = StringHolder::makeUniqueWithSize (text, numChars);
  8428. }
  8429. String::String() throw()
  8430. : text (StringHolder::getEmpty())
  8431. {
  8432. }
  8433. String::~String() throw()
  8434. {
  8435. StringHolder::release (text);
  8436. }
  8437. String::String (const String& other) throw()
  8438. : text (other.text)
  8439. {
  8440. StringHolder::retain (text);
  8441. }
  8442. void String::swapWith (String& other) throw()
  8443. {
  8444. swapVariables (text, other.text);
  8445. }
  8446. String& String::operator= (const String& other) throw()
  8447. {
  8448. juce_wchar* const newText = other.text;
  8449. StringHolder::retain (newText);
  8450. StringHolder::release (reinterpret_cast <Atomic<juce_wchar*>*> (&text)->exchange (newText));
  8451. return *this;
  8452. }
  8453. String::String (const size_t numChars, const int /*dummyVariable*/)
  8454. : text (StringHolder::createUninitialised (numChars))
  8455. {
  8456. }
  8457. String::String (const String& stringToCopy, const size_t charsToAllocate)
  8458. {
  8459. const size_t otherSize = StringHolder::getAllocatedNumChars (stringToCopy.text);
  8460. text = StringHolder::createUninitialised (jmax (charsToAllocate, otherSize));
  8461. StringHolder::copyChars (text, stringToCopy.text, otherSize);
  8462. }
  8463. String::String (const char* const t)
  8464. {
  8465. if (t != 0 && *t != 0)
  8466. text = StringHolder::createCopy (t, CharacterFunctions::length (t));
  8467. else
  8468. text = StringHolder::getEmpty();
  8469. }
  8470. String::String (const juce_wchar* const t)
  8471. {
  8472. if (t != 0 && *t != 0)
  8473. text = StringHolder::createCopy (t, CharacterFunctions::length (t));
  8474. else
  8475. text = StringHolder::getEmpty();
  8476. }
  8477. String::String (const char* const t, const size_t maxChars)
  8478. {
  8479. int i;
  8480. for (i = 0; (size_t) i < maxChars; ++i)
  8481. if (t[i] == 0)
  8482. break;
  8483. if (i > 0)
  8484. text = StringHolder::createCopy (t, i);
  8485. else
  8486. text = StringHolder::getEmpty();
  8487. }
  8488. String::String (const juce_wchar* const t, const size_t maxChars)
  8489. {
  8490. int i;
  8491. for (i = 0; (size_t) i < maxChars; ++i)
  8492. if (t[i] == 0)
  8493. break;
  8494. if (i > 0)
  8495. text = StringHolder::createCopy (t, i);
  8496. else
  8497. text = StringHolder::getEmpty();
  8498. }
  8499. const String String::charToString (const juce_wchar character)
  8500. {
  8501. String result ((size_t) 1, (int) 0);
  8502. result.text[0] = character;
  8503. result.text[1] = 0;
  8504. return result;
  8505. }
  8506. namespace NumberToStringConverters
  8507. {
  8508. // pass in a pointer to the END of a buffer..
  8509. static juce_wchar* int64ToString (juce_wchar* t, const int64 n) throw()
  8510. {
  8511. *--t = 0;
  8512. int64 v = (n >= 0) ? n : -n;
  8513. do
  8514. {
  8515. *--t = (juce_wchar) ('0' + (int) (v % 10));
  8516. v /= 10;
  8517. } while (v > 0);
  8518. if (n < 0)
  8519. *--t = '-';
  8520. return t;
  8521. }
  8522. static juce_wchar* uint64ToString (juce_wchar* t, int64 v) throw()
  8523. {
  8524. *--t = 0;
  8525. do
  8526. {
  8527. *--t = (juce_wchar) ('0' + (int) (v % 10));
  8528. v /= 10;
  8529. } while (v > 0);
  8530. return t;
  8531. }
  8532. static juce_wchar* intToString (juce_wchar* t, const int n) throw()
  8533. {
  8534. if (n == (int) 0x80000000) // (would cause an overflow)
  8535. return int64ToString (t, n);
  8536. *--t = 0;
  8537. int v = abs (n);
  8538. do
  8539. {
  8540. *--t = (juce_wchar) ('0' + (v % 10));
  8541. v /= 10;
  8542. } while (v > 0);
  8543. if (n < 0)
  8544. *--t = '-';
  8545. return t;
  8546. }
  8547. static juce_wchar* uintToString (juce_wchar* t, unsigned int v) throw()
  8548. {
  8549. *--t = 0;
  8550. do
  8551. {
  8552. *--t = (juce_wchar) ('0' + (v % 10));
  8553. v /= 10;
  8554. } while (v > 0);
  8555. return t;
  8556. }
  8557. static juce_wchar getDecimalPoint()
  8558. {
  8559. #if JUCE_WINDOWS && _MSC_VER < 1400
  8560. static juce_wchar dp = std::_USE (std::locale(), std::numpunct <wchar_t>).decimal_point();
  8561. #else
  8562. static juce_wchar dp = std::use_facet <std::numpunct <wchar_t> > (std::locale()).decimal_point();
  8563. #endif
  8564. return dp;
  8565. }
  8566. static juce_wchar* doubleToString (juce_wchar* buffer, int numChars, double n, int numDecPlaces, size_t& len) throw()
  8567. {
  8568. if (numDecPlaces > 0 && n > -1.0e20 && n < 1.0e20)
  8569. {
  8570. juce_wchar* const end = buffer + numChars;
  8571. juce_wchar* t = end;
  8572. int64 v = (int64) (pow (10.0, numDecPlaces) * std::abs (n) + 0.5);
  8573. *--t = (juce_wchar) 0;
  8574. while (numDecPlaces >= 0 || v > 0)
  8575. {
  8576. if (numDecPlaces == 0)
  8577. *--t = getDecimalPoint();
  8578. *--t = (juce_wchar) ('0' + (v % 10));
  8579. v /= 10;
  8580. --numDecPlaces;
  8581. }
  8582. if (n < 0)
  8583. *--t = '-';
  8584. len = end - t - 1;
  8585. return t;
  8586. }
  8587. else
  8588. {
  8589. #if JUCE_WINDOWS
  8590. #if _MSC_VER <= 1400
  8591. len = _snwprintf (buffer, numChars, L"%.9g", n);
  8592. #else
  8593. len = _snwprintf_s (buffer, numChars, _TRUNCATE, L"%.9g", n);
  8594. #endif
  8595. #else
  8596. len = swprintf (buffer, numChars, L"%.9g", n);
  8597. #endif
  8598. return buffer;
  8599. }
  8600. }
  8601. }
  8602. String::String (const int number)
  8603. {
  8604. juce_wchar buffer [16];
  8605. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8606. juce_wchar* const start = NumberToStringConverters::intToString (end, number);
  8607. createInternal (start, end - start - 1);
  8608. }
  8609. String::String (const unsigned int number)
  8610. {
  8611. juce_wchar buffer [16];
  8612. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8613. juce_wchar* const start = NumberToStringConverters::uintToString (end, number);
  8614. createInternal (start, end - start - 1);
  8615. }
  8616. String::String (const short number)
  8617. {
  8618. juce_wchar buffer [16];
  8619. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8620. juce_wchar* const start = NumberToStringConverters::intToString (end, (int) number);
  8621. createInternal (start, end - start - 1);
  8622. }
  8623. String::String (const unsigned short number)
  8624. {
  8625. juce_wchar buffer [16];
  8626. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8627. juce_wchar* const start = NumberToStringConverters::uintToString (end, (unsigned int) number);
  8628. createInternal (start, end - start - 1);
  8629. }
  8630. String::String (const int64 number)
  8631. {
  8632. juce_wchar buffer [32];
  8633. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8634. juce_wchar* const start = NumberToStringConverters::int64ToString (end, number);
  8635. createInternal (start, end - start - 1);
  8636. }
  8637. String::String (const uint64 number)
  8638. {
  8639. juce_wchar buffer [32];
  8640. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8641. juce_wchar* const start = NumberToStringConverters::uint64ToString (end, number);
  8642. createInternal (start, end - start - 1);
  8643. }
  8644. String::String (const float number, const int numberOfDecimalPlaces)
  8645. {
  8646. juce_wchar buffer [48];
  8647. size_t len;
  8648. juce_wchar* start = NumberToStringConverters::doubleToString (buffer, numElementsInArray (buffer), (double) number, numberOfDecimalPlaces, len);
  8649. createInternal (start, len);
  8650. }
  8651. String::String (const double number, const int numberOfDecimalPlaces)
  8652. {
  8653. juce_wchar buffer [48];
  8654. size_t len;
  8655. juce_wchar* start = NumberToStringConverters::doubleToString (buffer, numElementsInArray (buffer), number, numberOfDecimalPlaces, len);
  8656. createInternal (start, len);
  8657. }
  8658. int String::length() const throw()
  8659. {
  8660. return CharacterFunctions::length (text);
  8661. }
  8662. int String::hashCode() const throw()
  8663. {
  8664. const juce_wchar* t = text;
  8665. int result = 0;
  8666. while (*t != (juce_wchar) 0)
  8667. result = 31 * result + *t++;
  8668. return result;
  8669. }
  8670. int64 String::hashCode64() const throw()
  8671. {
  8672. const juce_wchar* t = text;
  8673. int64 result = 0;
  8674. while (*t != (juce_wchar) 0)
  8675. result = 101 * result + *t++;
  8676. return result;
  8677. }
  8678. bool JUCE_CALLTYPE operator== (const String& string1, const String& string2) throw()
  8679. {
  8680. return string1.compare (string2) == 0;
  8681. }
  8682. bool JUCE_CALLTYPE operator== (const String& string1, const char* string2) throw()
  8683. {
  8684. return string1.compare (string2) == 0;
  8685. }
  8686. bool JUCE_CALLTYPE operator== (const String& string1, const juce_wchar* string2) throw()
  8687. {
  8688. return string1.compare (string2) == 0;
  8689. }
  8690. bool JUCE_CALLTYPE operator!= (const String& string1, const String& string2) throw()
  8691. {
  8692. return string1.compare (string2) != 0;
  8693. }
  8694. bool JUCE_CALLTYPE operator!= (const String& string1, const char* string2) throw()
  8695. {
  8696. return string1.compare (string2) != 0;
  8697. }
  8698. bool JUCE_CALLTYPE operator!= (const String& string1, const juce_wchar* string2) throw()
  8699. {
  8700. return string1.compare (string2) != 0;
  8701. }
  8702. bool JUCE_CALLTYPE operator> (const String& string1, const String& string2) throw()
  8703. {
  8704. return string1.compare (string2) > 0;
  8705. }
  8706. bool JUCE_CALLTYPE operator< (const String& string1, const String& string2) throw()
  8707. {
  8708. return string1.compare (string2) < 0;
  8709. }
  8710. bool JUCE_CALLTYPE operator>= (const String& string1, const String& string2) throw()
  8711. {
  8712. return string1.compare (string2) >= 0;
  8713. }
  8714. bool JUCE_CALLTYPE operator<= (const String& string1, const String& string2) throw()
  8715. {
  8716. return string1.compare (string2) <= 0;
  8717. }
  8718. bool String::equalsIgnoreCase (const juce_wchar* t) const throw()
  8719. {
  8720. return t != 0 ? CharacterFunctions::compareIgnoreCase (text, t) == 0
  8721. : isEmpty();
  8722. }
  8723. bool String::equalsIgnoreCase (const char* t) const throw()
  8724. {
  8725. return t != 0 ? CharacterFunctions::compareIgnoreCase (text, t) == 0
  8726. : isEmpty();
  8727. }
  8728. bool String::equalsIgnoreCase (const String& other) const throw()
  8729. {
  8730. return text == other.text
  8731. || CharacterFunctions::compareIgnoreCase (text, other.text) == 0;
  8732. }
  8733. int String::compare (const String& other) const throw()
  8734. {
  8735. return (text == other.text) ? 0 : CharacterFunctions::compare (text, other.text);
  8736. }
  8737. int String::compare (const char* other) const throw()
  8738. {
  8739. return other == 0 ? isEmpty() : CharacterFunctions::compare (text, other);
  8740. }
  8741. int String::compare (const juce_wchar* other) const throw()
  8742. {
  8743. return other == 0 ? isEmpty() : CharacterFunctions::compare (text, other);
  8744. }
  8745. int String::compareIgnoreCase (const String& other) const throw()
  8746. {
  8747. return (text == other.text) ? 0 : CharacterFunctions::compareIgnoreCase (text, other.text);
  8748. }
  8749. int String::compareLexicographically (const String& other) const throw()
  8750. {
  8751. const juce_wchar* s1 = text;
  8752. while (*s1 != 0 && ! CharacterFunctions::isLetterOrDigit (*s1))
  8753. ++s1;
  8754. const juce_wchar* s2 = other.text;
  8755. while (*s2 != 0 && ! CharacterFunctions::isLetterOrDigit (*s2))
  8756. ++s2;
  8757. return CharacterFunctions::compareIgnoreCase (s1, s2);
  8758. }
  8759. String& String::operator+= (const juce_wchar* const t)
  8760. {
  8761. if (t != 0)
  8762. appendInternal (t, CharacterFunctions::length (t));
  8763. return *this;
  8764. }
  8765. String& String::operator+= (const String& other)
  8766. {
  8767. if (isEmpty())
  8768. operator= (other);
  8769. else
  8770. appendInternal (other.text, other.length());
  8771. return *this;
  8772. }
  8773. String& String::operator+= (const char ch)
  8774. {
  8775. const juce_wchar asString[] = { (juce_wchar) ch, 0 };
  8776. return operator+= (static_cast <const juce_wchar*> (asString));
  8777. }
  8778. String& String::operator+= (const juce_wchar ch)
  8779. {
  8780. const juce_wchar asString[] = { (juce_wchar) ch, 0 };
  8781. return operator+= (static_cast <const juce_wchar*> (asString));
  8782. }
  8783. String& String::operator+= (const int number)
  8784. {
  8785. juce_wchar buffer [16];
  8786. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8787. juce_wchar* const start = NumberToStringConverters::intToString (end, number);
  8788. appendInternal (start, (int) (end - start));
  8789. return *this;
  8790. }
  8791. String& String::operator+= (const unsigned int number)
  8792. {
  8793. juce_wchar buffer [16];
  8794. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8795. juce_wchar* const start = NumberToStringConverters::uintToString (end, number);
  8796. appendInternal (start, (int) (end - start));
  8797. return *this;
  8798. }
  8799. void String::append (const juce_wchar* const other, const int howMany)
  8800. {
  8801. if (howMany > 0)
  8802. {
  8803. int i;
  8804. for (i = 0; i < howMany; ++i)
  8805. if (other[i] == 0)
  8806. break;
  8807. appendInternal (other, i);
  8808. }
  8809. }
  8810. const String JUCE_CALLTYPE operator+ (const char* const string1, const String& string2)
  8811. {
  8812. String s (string1);
  8813. return s += string2;
  8814. }
  8815. const String JUCE_CALLTYPE operator+ (const juce_wchar* const string1, const String& string2)
  8816. {
  8817. String s (string1);
  8818. return s += string2;
  8819. }
  8820. const String JUCE_CALLTYPE operator+ (const char string1, const String& string2)
  8821. {
  8822. return String::charToString (string1) + string2;
  8823. }
  8824. const String JUCE_CALLTYPE operator+ (const juce_wchar string1, const String& string2)
  8825. {
  8826. return String::charToString (string1) + string2;
  8827. }
  8828. const String JUCE_CALLTYPE operator+ (String string1, const String& string2)
  8829. {
  8830. return string1 += string2;
  8831. }
  8832. const String JUCE_CALLTYPE operator+ (String string1, const char* const string2)
  8833. {
  8834. return string1 += string2;
  8835. }
  8836. const String JUCE_CALLTYPE operator+ (String string1, const juce_wchar* const string2)
  8837. {
  8838. return string1 += string2;
  8839. }
  8840. const String JUCE_CALLTYPE operator+ (String string1, const char string2)
  8841. {
  8842. return string1 += string2;
  8843. }
  8844. const String JUCE_CALLTYPE operator+ (String string1, const juce_wchar string2)
  8845. {
  8846. return string1 += string2;
  8847. }
  8848. String& JUCE_CALLTYPE operator<< (String& string1, const char characterToAppend)
  8849. {
  8850. return string1 += characterToAppend;
  8851. }
  8852. String& JUCE_CALLTYPE operator<< (String& string1, const juce_wchar characterToAppend)
  8853. {
  8854. return string1 += characterToAppend;
  8855. }
  8856. String& JUCE_CALLTYPE operator<< (String& string1, const char* const string2)
  8857. {
  8858. return string1 += string2;
  8859. }
  8860. String& JUCE_CALLTYPE operator<< (String& string1, const juce_wchar* const string2)
  8861. {
  8862. return string1 += string2;
  8863. }
  8864. String& JUCE_CALLTYPE operator<< (String& string1, const String& string2)
  8865. {
  8866. return string1 += string2;
  8867. }
  8868. String& JUCE_CALLTYPE operator<< (String& string1, const short number)
  8869. {
  8870. return string1 += (int) number;
  8871. }
  8872. String& JUCE_CALLTYPE operator<< (String& string1, const int number)
  8873. {
  8874. return string1 += number;
  8875. }
  8876. String& JUCE_CALLTYPE operator<< (String& string1, const unsigned int number)
  8877. {
  8878. return string1 += number;
  8879. }
  8880. String& JUCE_CALLTYPE operator<< (String& string1, const long number)
  8881. {
  8882. return string1 += (int) number;
  8883. }
  8884. String& JUCE_CALLTYPE operator<< (String& string1, const unsigned long number)
  8885. {
  8886. return string1 += (unsigned int) number;
  8887. }
  8888. String& JUCE_CALLTYPE operator<< (String& string1, const float number)
  8889. {
  8890. return string1 += String (number);
  8891. }
  8892. String& JUCE_CALLTYPE operator<< (String& string1, const double number)
  8893. {
  8894. return string1 += String (number);
  8895. }
  8896. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const String& text)
  8897. {
  8898. // (This avoids using toUTF8() to prevent the memory bloat that it would leave behind
  8899. // if lots of large, persistent strings were to be written to streams).
  8900. const int numBytes = text.getNumBytesAsUTF8();
  8901. HeapBlock<char> temp (numBytes + 1);
  8902. text.copyToUTF8 (temp, numBytes + 1);
  8903. stream.write (temp, numBytes);
  8904. return stream;
  8905. }
  8906. int String::indexOfChar (const juce_wchar character) const throw()
  8907. {
  8908. const juce_wchar* t = text;
  8909. for (;;)
  8910. {
  8911. if (*t == character)
  8912. return (int) (t - text);
  8913. if (*t++ == 0)
  8914. return -1;
  8915. }
  8916. }
  8917. int String::lastIndexOfChar (const juce_wchar character) const throw()
  8918. {
  8919. for (int i = length(); --i >= 0;)
  8920. if (text[i] == character)
  8921. return i;
  8922. return -1;
  8923. }
  8924. int String::indexOf (const String& t) const throw()
  8925. {
  8926. const juce_wchar* const r = CharacterFunctions::find (text, t.text);
  8927. return r == 0 ? -1 : (int) (r - text);
  8928. }
  8929. int String::indexOfChar (const int startIndex,
  8930. const juce_wchar character) const throw()
  8931. {
  8932. if (startIndex > 0 && startIndex >= length())
  8933. return -1;
  8934. const juce_wchar* t = text + jmax (0, startIndex);
  8935. for (;;)
  8936. {
  8937. if (*t == character)
  8938. return (int) (t - text);
  8939. if (*t == 0)
  8940. return -1;
  8941. ++t;
  8942. }
  8943. }
  8944. int String::indexOfAnyOf (const String& charactersToLookFor,
  8945. const int startIndex,
  8946. const bool ignoreCase) const throw()
  8947. {
  8948. if (startIndex > 0 && startIndex >= length())
  8949. return -1;
  8950. const juce_wchar* t = text + jmax (0, startIndex);
  8951. while (*t != 0)
  8952. {
  8953. if (CharacterFunctions::indexOfChar (charactersToLookFor.text, *t, ignoreCase) >= 0)
  8954. return (int) (t - text);
  8955. ++t;
  8956. }
  8957. return -1;
  8958. }
  8959. int String::indexOf (const int startIndex, const String& other) const throw()
  8960. {
  8961. if (startIndex > 0 && startIndex >= length())
  8962. return -1;
  8963. const juce_wchar* const found = CharacterFunctions::find (text + jmax (0, startIndex), other.text);
  8964. return found == 0 ? -1 : (int) (found - text);
  8965. }
  8966. int String::indexOfIgnoreCase (const String& other) const throw()
  8967. {
  8968. if (other.isNotEmpty())
  8969. {
  8970. const int len = other.length();
  8971. const int end = length() - len;
  8972. for (int i = 0; i <= end; ++i)
  8973. if (CharacterFunctions::compareIgnoreCase (text + i, other.text, len) == 0)
  8974. return i;
  8975. }
  8976. return -1;
  8977. }
  8978. int String::indexOfIgnoreCase (const int startIndex, const String& other) const throw()
  8979. {
  8980. if (other.isNotEmpty())
  8981. {
  8982. const int len = other.length();
  8983. const int end = length() - len;
  8984. for (int i = jmax (0, startIndex); i <= end; ++i)
  8985. if (CharacterFunctions::compareIgnoreCase (text + i, other.text, len) == 0)
  8986. return i;
  8987. }
  8988. return -1;
  8989. }
  8990. int String::lastIndexOf (const String& other) const throw()
  8991. {
  8992. if (other.isNotEmpty())
  8993. {
  8994. const int len = other.length();
  8995. int i = length() - len;
  8996. if (i >= 0)
  8997. {
  8998. const juce_wchar* n = text + i;
  8999. while (i >= 0)
  9000. {
  9001. if (CharacterFunctions::compare (n--, other.text, len) == 0)
  9002. return i;
  9003. --i;
  9004. }
  9005. }
  9006. }
  9007. return -1;
  9008. }
  9009. int String::lastIndexOfIgnoreCase (const String& other) const throw()
  9010. {
  9011. if (other.isNotEmpty())
  9012. {
  9013. const int len = other.length();
  9014. int i = length() - len;
  9015. if (i >= 0)
  9016. {
  9017. const juce_wchar* n = text + i;
  9018. while (i >= 0)
  9019. {
  9020. if (CharacterFunctions::compareIgnoreCase (n--, other.text, len) == 0)
  9021. return i;
  9022. --i;
  9023. }
  9024. }
  9025. }
  9026. return -1;
  9027. }
  9028. int String::lastIndexOfAnyOf (const String& charactersToLookFor, const bool ignoreCase) const throw()
  9029. {
  9030. for (int i = length(); --i >= 0;)
  9031. if (CharacterFunctions::indexOfChar (charactersToLookFor.text, text[i], ignoreCase) >= 0)
  9032. return i;
  9033. return -1;
  9034. }
  9035. bool String::contains (const String& other) const throw()
  9036. {
  9037. return indexOf (other) >= 0;
  9038. }
  9039. bool String::containsChar (const juce_wchar character) const throw()
  9040. {
  9041. const juce_wchar* t = text;
  9042. for (;;)
  9043. {
  9044. if (*t == 0)
  9045. return false;
  9046. if (*t == character)
  9047. return true;
  9048. ++t;
  9049. }
  9050. }
  9051. bool String::containsIgnoreCase (const String& t) const throw()
  9052. {
  9053. return indexOfIgnoreCase (t) >= 0;
  9054. }
  9055. int String::indexOfWholeWord (const String& word) const throw()
  9056. {
  9057. if (word.isNotEmpty())
  9058. {
  9059. const int wordLen = word.length();
  9060. const int end = length() - wordLen;
  9061. const juce_wchar* t = text;
  9062. for (int i = 0; i <= end; ++i)
  9063. {
  9064. if (CharacterFunctions::compare (t, word.text, wordLen) == 0
  9065. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  9066. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  9067. {
  9068. return i;
  9069. }
  9070. ++t;
  9071. }
  9072. }
  9073. return -1;
  9074. }
  9075. int String::indexOfWholeWordIgnoreCase (const String& word) const throw()
  9076. {
  9077. if (word.isNotEmpty())
  9078. {
  9079. const int wordLen = word.length();
  9080. const int end = length() - wordLen;
  9081. const juce_wchar* t = text;
  9082. for (int i = 0; i <= end; ++i)
  9083. {
  9084. if (CharacterFunctions::compareIgnoreCase (t, word.text, wordLen) == 0
  9085. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  9086. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  9087. {
  9088. return i;
  9089. }
  9090. ++t;
  9091. }
  9092. }
  9093. return -1;
  9094. }
  9095. bool String::containsWholeWord (const String& wordToLookFor) const throw()
  9096. {
  9097. return indexOfWholeWord (wordToLookFor) >= 0;
  9098. }
  9099. bool String::containsWholeWordIgnoreCase (const String& wordToLookFor) const throw()
  9100. {
  9101. return indexOfWholeWordIgnoreCase (wordToLookFor) >= 0;
  9102. }
  9103. static int indexOfMatch (const juce_wchar* const wildcard,
  9104. const juce_wchar* const test,
  9105. const bool ignoreCase) throw()
  9106. {
  9107. int start = 0;
  9108. while (test [start] != 0)
  9109. {
  9110. int i = 0;
  9111. for (;;)
  9112. {
  9113. const juce_wchar wc = wildcard [i];
  9114. const juce_wchar c = test [i + start];
  9115. if (wc == c
  9116. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  9117. || (wc == '?' && c != 0))
  9118. {
  9119. if (wc == 0)
  9120. return start;
  9121. ++i;
  9122. }
  9123. else
  9124. {
  9125. if (wc == '*' && (wildcard [i + 1] == 0
  9126. || indexOfMatch (wildcard + i + 1, test + start + i, ignoreCase) >= 0))
  9127. {
  9128. return start;
  9129. }
  9130. break;
  9131. }
  9132. }
  9133. ++start;
  9134. }
  9135. return -1;
  9136. }
  9137. bool String::matchesWildcard (const String& wildcard, const bool ignoreCase) const throw()
  9138. {
  9139. int i = 0;
  9140. for (;;)
  9141. {
  9142. const juce_wchar wc = wildcard.text [i];
  9143. const juce_wchar c = text [i];
  9144. if (wc == c
  9145. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  9146. || (wc == '?' && c != 0))
  9147. {
  9148. if (wc == 0)
  9149. return true;
  9150. ++i;
  9151. }
  9152. else
  9153. {
  9154. return wc == '*' && (wildcard [i + 1] == 0
  9155. || indexOfMatch (wildcard.text + i + 1, text + i, ignoreCase) >= 0);
  9156. }
  9157. }
  9158. }
  9159. const String String::repeatedString (const String& stringToRepeat, int numberOfTimesToRepeat)
  9160. {
  9161. const int len = stringToRepeat.length();
  9162. String result ((size_t) (len * numberOfTimesToRepeat + 1), (int) 0);
  9163. juce_wchar* n = result.text;
  9164. *n = 0;
  9165. while (--numberOfTimesToRepeat >= 0)
  9166. {
  9167. StringHolder::copyChars (n, stringToRepeat.text, len);
  9168. n += len;
  9169. }
  9170. return result;
  9171. }
  9172. const String String::paddedLeft (const juce_wchar padCharacter, int minimumLength) const
  9173. {
  9174. jassert (padCharacter != 0);
  9175. const int len = length();
  9176. if (len >= minimumLength || padCharacter == 0)
  9177. return *this;
  9178. String result ((size_t) minimumLength + 1, (int) 0);
  9179. juce_wchar* n = result.text;
  9180. minimumLength -= len;
  9181. while (--minimumLength >= 0)
  9182. *n++ = padCharacter;
  9183. StringHolder::copyChars (n, text, len);
  9184. return result;
  9185. }
  9186. const String String::paddedRight (const juce_wchar padCharacter, int minimumLength) const
  9187. {
  9188. jassert (padCharacter != 0);
  9189. const int len = length();
  9190. if (len >= minimumLength || padCharacter == 0)
  9191. return *this;
  9192. String result (*this, (size_t) minimumLength);
  9193. juce_wchar* n = result.text + len;
  9194. minimumLength -= len;
  9195. while (--minimumLength >= 0)
  9196. *n++ = padCharacter;
  9197. *n = 0;
  9198. return result;
  9199. }
  9200. const String String::replaceSection (int index, int numCharsToReplace, const String& stringToInsert) const
  9201. {
  9202. if (index < 0)
  9203. {
  9204. // a negative index to replace from?
  9205. jassertfalse;
  9206. index = 0;
  9207. }
  9208. if (numCharsToReplace < 0)
  9209. {
  9210. // replacing a negative number of characters?
  9211. numCharsToReplace = 0;
  9212. jassertfalse;
  9213. }
  9214. const int len = length();
  9215. if (index + numCharsToReplace > len)
  9216. {
  9217. if (index > len)
  9218. {
  9219. // replacing beyond the end of the string?
  9220. index = len;
  9221. jassertfalse;
  9222. }
  9223. numCharsToReplace = len - index;
  9224. }
  9225. const int newStringLen = stringToInsert.length();
  9226. const int newTotalLen = len + newStringLen - numCharsToReplace;
  9227. if (newTotalLen <= 0)
  9228. return String::empty;
  9229. String result ((size_t) newTotalLen, (int) 0);
  9230. StringHolder::copyChars (result.text, text, index);
  9231. if (newStringLen > 0)
  9232. StringHolder::copyChars (result.text + index, stringToInsert.text, newStringLen);
  9233. const int endStringLen = newTotalLen - (index + newStringLen);
  9234. if (endStringLen > 0)
  9235. StringHolder::copyChars (result.text + (index + newStringLen),
  9236. text + (index + numCharsToReplace),
  9237. endStringLen);
  9238. return result;
  9239. }
  9240. const String String::replace (const String& stringToReplace, const String& stringToInsert, const bool ignoreCase) const
  9241. {
  9242. const int stringToReplaceLen = stringToReplace.length();
  9243. const int stringToInsertLen = stringToInsert.length();
  9244. int i = 0;
  9245. String result (*this);
  9246. while ((i = (ignoreCase ? result.indexOfIgnoreCase (i, stringToReplace)
  9247. : result.indexOf (i, stringToReplace))) >= 0)
  9248. {
  9249. result = result.replaceSection (i, stringToReplaceLen, stringToInsert);
  9250. i += stringToInsertLen;
  9251. }
  9252. return result;
  9253. }
  9254. const String String::replaceCharacter (const juce_wchar charToReplace, const juce_wchar charToInsert) const
  9255. {
  9256. const int index = indexOfChar (charToReplace);
  9257. if (index < 0)
  9258. return *this;
  9259. String result (*this, size_t());
  9260. juce_wchar* t = result.text + index;
  9261. while (*t != 0)
  9262. {
  9263. if (*t == charToReplace)
  9264. *t = charToInsert;
  9265. ++t;
  9266. }
  9267. return result;
  9268. }
  9269. const String String::replaceCharacters (const String& charactersToReplace,
  9270. const String& charactersToInsertInstead) const
  9271. {
  9272. String result (*this, size_t());
  9273. juce_wchar* t = result.text;
  9274. const int len2 = charactersToInsertInstead.length();
  9275. // the two strings passed in are supposed to be the same length!
  9276. jassert (len2 == charactersToReplace.length());
  9277. while (*t != 0)
  9278. {
  9279. const int index = charactersToReplace.indexOfChar (*t);
  9280. if (((unsigned int) index) < (unsigned int) len2)
  9281. *t = charactersToInsertInstead [index];
  9282. ++t;
  9283. }
  9284. return result;
  9285. }
  9286. bool String::startsWith (const String& other) const throw()
  9287. {
  9288. return CharacterFunctions::compare (text, other.text, other.length()) == 0;
  9289. }
  9290. bool String::startsWithIgnoreCase (const String& other) const throw()
  9291. {
  9292. return CharacterFunctions::compareIgnoreCase (text, other.text, other.length()) == 0;
  9293. }
  9294. bool String::startsWithChar (const juce_wchar character) const throw()
  9295. {
  9296. jassert (character != 0); // strings can't contain a null character!
  9297. return text[0] == character;
  9298. }
  9299. bool String::endsWithChar (const juce_wchar character) const throw()
  9300. {
  9301. jassert (character != 0); // strings can't contain a null character!
  9302. return text[0] != 0
  9303. && text [length() - 1] == character;
  9304. }
  9305. bool String::endsWith (const String& other) const throw()
  9306. {
  9307. const int thisLen = length();
  9308. const int otherLen = other.length();
  9309. return thisLen >= otherLen
  9310. && CharacterFunctions::compare (text + thisLen - otherLen, other.text) == 0;
  9311. }
  9312. bool String::endsWithIgnoreCase (const String& other) const throw()
  9313. {
  9314. const int thisLen = length();
  9315. const int otherLen = other.length();
  9316. return thisLen >= otherLen
  9317. && CharacterFunctions::compareIgnoreCase (text + thisLen - otherLen, other.text) == 0;
  9318. }
  9319. const String String::toUpperCase() const
  9320. {
  9321. String result (*this, size_t());
  9322. CharacterFunctions::toUpperCase (result.text);
  9323. return result;
  9324. }
  9325. const String String::toLowerCase() const
  9326. {
  9327. String result (*this, size_t());
  9328. CharacterFunctions::toLowerCase (result.text);
  9329. return result;
  9330. }
  9331. juce_wchar& String::operator[] (const int index)
  9332. {
  9333. jassert (((unsigned int) index) <= (unsigned int) length());
  9334. text = StringHolder::makeUnique (text);
  9335. return text [index];
  9336. }
  9337. juce_wchar String::getLastCharacter() const throw()
  9338. {
  9339. return isEmpty() ? juce_wchar() : text [length() - 1];
  9340. }
  9341. const String String::substring (int start, int end) const
  9342. {
  9343. if (start < 0)
  9344. start = 0;
  9345. else if (end <= start)
  9346. return empty;
  9347. int len = 0;
  9348. while (len <= end && text [len] != 0)
  9349. ++len;
  9350. if (end >= len)
  9351. {
  9352. if (start == 0)
  9353. return *this;
  9354. end = len;
  9355. }
  9356. return String (text + start, end - start);
  9357. }
  9358. const String String::substring (const int start) const
  9359. {
  9360. if (start <= 0)
  9361. return *this;
  9362. const int len = length();
  9363. if (start >= len)
  9364. return empty;
  9365. return String (text + start, len - start);
  9366. }
  9367. const String String::dropLastCharacters (const int numberToDrop) const
  9368. {
  9369. return String (text, jmax (0, length() - numberToDrop));
  9370. }
  9371. const String String::getLastCharacters (const int numCharacters) const
  9372. {
  9373. return String (text + jmax (0, length() - jmax (0, numCharacters)));
  9374. }
  9375. const String String::fromFirstOccurrenceOf (const String& sub,
  9376. const bool includeSubString,
  9377. const bool ignoreCase) const
  9378. {
  9379. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  9380. : indexOf (sub);
  9381. if (i < 0)
  9382. return empty;
  9383. return substring (includeSubString ? i : i + sub.length());
  9384. }
  9385. const String String::fromLastOccurrenceOf (const String& sub,
  9386. const bool includeSubString,
  9387. const bool ignoreCase) const
  9388. {
  9389. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  9390. : lastIndexOf (sub);
  9391. if (i < 0)
  9392. return *this;
  9393. return substring (includeSubString ? i : i + sub.length());
  9394. }
  9395. const String String::upToFirstOccurrenceOf (const String& sub,
  9396. const bool includeSubString,
  9397. const bool ignoreCase) const
  9398. {
  9399. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  9400. : indexOf (sub);
  9401. if (i < 0)
  9402. return *this;
  9403. return substring (0, includeSubString ? i + sub.length() : i);
  9404. }
  9405. const String String::upToLastOccurrenceOf (const String& sub,
  9406. const bool includeSubString,
  9407. const bool ignoreCase) const
  9408. {
  9409. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  9410. : lastIndexOf (sub);
  9411. if (i < 0)
  9412. return *this;
  9413. return substring (0, includeSubString ? i + sub.length() : i);
  9414. }
  9415. bool String::isQuotedString() const
  9416. {
  9417. const String trimmed (trimStart());
  9418. return trimmed[0] == '"'
  9419. || trimmed[0] == '\'';
  9420. }
  9421. const String String::unquoted() const
  9422. {
  9423. String s (*this);
  9424. if (s.text[0] == '"' || s.text[0] == '\'')
  9425. s = s.substring (1);
  9426. const int lastCharIndex = s.length() - 1;
  9427. if (lastCharIndex >= 0
  9428. && (s [lastCharIndex] == '"' || s[lastCharIndex] == '\''))
  9429. s [lastCharIndex] = 0;
  9430. return s;
  9431. }
  9432. const String String::quoted (const juce_wchar quoteCharacter) const
  9433. {
  9434. if (isEmpty())
  9435. return charToString (quoteCharacter) + quoteCharacter;
  9436. String t (*this);
  9437. if (! t.startsWithChar (quoteCharacter))
  9438. t = charToString (quoteCharacter) + t;
  9439. if (! t.endsWithChar (quoteCharacter))
  9440. t += quoteCharacter;
  9441. return t;
  9442. }
  9443. const String String::trim() const
  9444. {
  9445. if (isEmpty())
  9446. return empty;
  9447. int start = 0;
  9448. while (CharacterFunctions::isWhitespace (text [start]))
  9449. ++start;
  9450. const int len = length();
  9451. int end = len - 1;
  9452. while ((end >= start) && CharacterFunctions::isWhitespace (text [end]))
  9453. --end;
  9454. ++end;
  9455. if (end <= start)
  9456. return empty;
  9457. else if (start > 0 || end < len)
  9458. return String (text + start, end - start);
  9459. return *this;
  9460. }
  9461. const String String::trimStart() const
  9462. {
  9463. if (isEmpty())
  9464. return empty;
  9465. const juce_wchar* t = text;
  9466. while (CharacterFunctions::isWhitespace (*t))
  9467. ++t;
  9468. if (t == text)
  9469. return *this;
  9470. return String (t);
  9471. }
  9472. const String String::trimEnd() const
  9473. {
  9474. if (isEmpty())
  9475. return empty;
  9476. const juce_wchar* endT = text + (length() - 1);
  9477. while ((endT >= text) && CharacterFunctions::isWhitespace (*endT))
  9478. --endT;
  9479. return String (text, (int) (++endT - text));
  9480. }
  9481. const String String::trimCharactersAtStart (const String& charactersToTrim) const
  9482. {
  9483. const juce_wchar* t = text;
  9484. while (charactersToTrim.containsChar (*t))
  9485. ++t;
  9486. return t == text ? *this : String (t);
  9487. }
  9488. const String String::trimCharactersAtEnd (const String& charactersToTrim) const
  9489. {
  9490. if (isEmpty())
  9491. return empty;
  9492. const int len = length();
  9493. const juce_wchar* endT = text + (len - 1);
  9494. int numToRemove = 0;
  9495. while (numToRemove < len && charactersToTrim.containsChar (*endT))
  9496. {
  9497. ++numToRemove;
  9498. --endT;
  9499. }
  9500. return numToRemove > 0 ? String (text, len - numToRemove) : *this;
  9501. }
  9502. const String String::retainCharacters (const String& charactersToRetain) const
  9503. {
  9504. if (isEmpty())
  9505. return empty;
  9506. String result (StringHolder::getAllocatedNumChars (text), (int) 0);
  9507. juce_wchar* dst = result.text;
  9508. const juce_wchar* src = text;
  9509. while (*src != 0)
  9510. {
  9511. if (charactersToRetain.containsChar (*src))
  9512. *dst++ = *src;
  9513. ++src;
  9514. }
  9515. *dst = 0;
  9516. return result;
  9517. }
  9518. const String String::removeCharacters (const String& charactersToRemove) const
  9519. {
  9520. if (isEmpty())
  9521. return empty;
  9522. String result (StringHolder::getAllocatedNumChars (text), (int) 0);
  9523. juce_wchar* dst = result.text;
  9524. const juce_wchar* src = text;
  9525. while (*src != 0)
  9526. {
  9527. if (! charactersToRemove.containsChar (*src))
  9528. *dst++ = *src;
  9529. ++src;
  9530. }
  9531. *dst = 0;
  9532. return result;
  9533. }
  9534. const String String::initialSectionContainingOnly (const String& permittedCharacters) const
  9535. {
  9536. int i = 0;
  9537. for (;;)
  9538. {
  9539. if (! permittedCharacters.containsChar (text[i]))
  9540. break;
  9541. ++i;
  9542. }
  9543. return substring (0, i);
  9544. }
  9545. const String String::initialSectionNotContaining (const String& charactersToStopAt) const
  9546. {
  9547. const juce_wchar* const t = text;
  9548. int i = 0;
  9549. while (t[i] != 0)
  9550. {
  9551. if (charactersToStopAt.containsChar (t[i]))
  9552. return String (text, i);
  9553. ++i;
  9554. }
  9555. return empty;
  9556. }
  9557. bool String::containsOnly (const String& chars) const throw()
  9558. {
  9559. const juce_wchar* t = text;
  9560. while (*t != 0)
  9561. if (! chars.containsChar (*t++))
  9562. return false;
  9563. return true;
  9564. }
  9565. bool String::containsAnyOf (const String& chars) const throw()
  9566. {
  9567. const juce_wchar* t = text;
  9568. while (*t != 0)
  9569. if (chars.containsChar (*t++))
  9570. return true;
  9571. return false;
  9572. }
  9573. bool String::containsNonWhitespaceChars() const throw()
  9574. {
  9575. const juce_wchar* t = text;
  9576. while (*t != 0)
  9577. if (! CharacterFunctions::isWhitespace (*t++))
  9578. return true;
  9579. return false;
  9580. }
  9581. const String String::formatted (const juce_wchar* const pf, ... )
  9582. {
  9583. jassert (pf != 0);
  9584. va_list args;
  9585. va_start (args, pf);
  9586. size_t bufferSize = 256;
  9587. String result (bufferSize, (int) 0);
  9588. result.text[0] = 0;
  9589. for (;;)
  9590. {
  9591. #if JUCE_LINUX && JUCE_64BIT
  9592. va_list tempArgs;
  9593. va_copy (tempArgs, args);
  9594. const int num = (int) vswprintf (result.text, bufferSize - 1, pf, tempArgs);
  9595. va_end (tempArgs);
  9596. #elif JUCE_WINDOWS
  9597. #if JUCE_MSVC
  9598. #pragma warning (push)
  9599. #pragma warning (disable: 4996)
  9600. #endif
  9601. const int num = (int) _vsnwprintf (result.text, bufferSize - 1, pf, args);
  9602. #if JUCE_MSVC
  9603. #pragma warning (pop)
  9604. #endif
  9605. #else
  9606. const int num = (int) vswprintf (result.text, bufferSize - 1, pf, args);
  9607. #endif
  9608. if (num > 0)
  9609. return result;
  9610. bufferSize += 256;
  9611. if (num == 0 || bufferSize > 65536) // the upper limit is a sanity check to avoid situations where vprintf repeatedly
  9612. break; // returns -1 because of an error rather than because it needs more space.
  9613. result.preallocateStorage (bufferSize);
  9614. }
  9615. return empty;
  9616. }
  9617. int String::getIntValue() const throw()
  9618. {
  9619. return CharacterFunctions::getIntValue (text);
  9620. }
  9621. int String::getTrailingIntValue() const throw()
  9622. {
  9623. int n = 0;
  9624. int mult = 1;
  9625. const juce_wchar* t = text + length();
  9626. while (--t >= text)
  9627. {
  9628. const juce_wchar c = *t;
  9629. if (! CharacterFunctions::isDigit (c))
  9630. {
  9631. if (c == '-')
  9632. n = -n;
  9633. break;
  9634. }
  9635. n += mult * (c - '0');
  9636. mult *= 10;
  9637. }
  9638. return n;
  9639. }
  9640. int64 String::getLargeIntValue() const throw()
  9641. {
  9642. return CharacterFunctions::getInt64Value (text);
  9643. }
  9644. float String::getFloatValue() const throw()
  9645. {
  9646. return (float) CharacterFunctions::getDoubleValue (text);
  9647. }
  9648. double String::getDoubleValue() const throw()
  9649. {
  9650. return CharacterFunctions::getDoubleValue (text);
  9651. }
  9652. static const juce_wchar* const hexDigits = JUCE_T("0123456789abcdef");
  9653. const String String::toHexString (const int number)
  9654. {
  9655. juce_wchar buffer[32];
  9656. juce_wchar* const end = buffer + 32;
  9657. juce_wchar* t = end;
  9658. *--t = 0;
  9659. unsigned int v = (unsigned int) number;
  9660. do
  9661. {
  9662. *--t = hexDigits [v & 15];
  9663. v >>= 4;
  9664. } while (v != 0);
  9665. return String (t, (int) (((char*) end) - (char*) t) - 1);
  9666. }
  9667. const String String::toHexString (const int64 number)
  9668. {
  9669. juce_wchar buffer[32];
  9670. juce_wchar* const end = buffer + 32;
  9671. juce_wchar* t = end;
  9672. *--t = 0;
  9673. uint64 v = (uint64) number;
  9674. do
  9675. {
  9676. *--t = hexDigits [(int) (v & 15)];
  9677. v >>= 4;
  9678. } while (v != 0);
  9679. return String (t, (int) (((char*) end) - (char*) t));
  9680. }
  9681. const String String::toHexString (const short number)
  9682. {
  9683. return toHexString ((int) (unsigned short) number);
  9684. }
  9685. const String String::toHexString (const unsigned char* data,
  9686. const int size,
  9687. const int groupSize)
  9688. {
  9689. if (size <= 0)
  9690. return empty;
  9691. int numChars = (size * 2) + 2;
  9692. if (groupSize > 0)
  9693. numChars += size / groupSize;
  9694. String s ((size_t) numChars, (int) 0);
  9695. juce_wchar* d = s.text;
  9696. for (int i = 0; i < size; ++i)
  9697. {
  9698. *d++ = hexDigits [(*data) >> 4];
  9699. *d++ = hexDigits [(*data) & 0xf];
  9700. ++data;
  9701. if (groupSize > 0 && (i % groupSize) == (groupSize - 1) && i < (size - 1))
  9702. *d++ = ' ';
  9703. }
  9704. *d = 0;
  9705. return s;
  9706. }
  9707. int String::getHexValue32() const throw()
  9708. {
  9709. int result = 0;
  9710. const juce_wchar* c = text;
  9711. for (;;)
  9712. {
  9713. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  9714. if (hexValue >= 0)
  9715. result = (result << 4) | hexValue;
  9716. else if (*c == 0)
  9717. break;
  9718. ++c;
  9719. }
  9720. return result;
  9721. }
  9722. int64 String::getHexValue64() const throw()
  9723. {
  9724. int64 result = 0;
  9725. const juce_wchar* c = text;
  9726. for (;;)
  9727. {
  9728. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  9729. if (hexValue >= 0)
  9730. result = (result << 4) | hexValue;
  9731. else if (*c == 0)
  9732. break;
  9733. ++c;
  9734. }
  9735. return result;
  9736. }
  9737. const String String::createStringFromData (const void* const data_, const int size)
  9738. {
  9739. const char* const data = static_cast <const char*> (data_);
  9740. if (size <= 0 || data == 0)
  9741. {
  9742. return empty;
  9743. }
  9744. else if (size < 2)
  9745. {
  9746. return charToString (data[0]);
  9747. }
  9748. else if ((data[0] == (char)-2 && data[1] == (char)-1)
  9749. || (data[0] == (char)-1 && data[1] == (char)-2))
  9750. {
  9751. // assume it's 16-bit unicode
  9752. const bool bigEndian = (data[0] == (char)-2);
  9753. const int numChars = size / 2 - 1;
  9754. String result;
  9755. result.preallocateStorage (numChars + 2);
  9756. const uint16* const src = (const uint16*) (data + 2);
  9757. juce_wchar* const dst = const_cast <juce_wchar*> (static_cast <const juce_wchar*> (result));
  9758. if (bigEndian)
  9759. {
  9760. for (int i = 0; i < numChars; ++i)
  9761. dst[i] = (juce_wchar) ByteOrder::swapIfLittleEndian (src[i]);
  9762. }
  9763. else
  9764. {
  9765. for (int i = 0; i < numChars; ++i)
  9766. dst[i] = (juce_wchar) ByteOrder::swapIfBigEndian (src[i]);
  9767. }
  9768. dst [numChars] = 0;
  9769. return result;
  9770. }
  9771. else
  9772. {
  9773. return String::fromUTF8 (data, size);
  9774. }
  9775. }
  9776. const char* String::toUTF8() const
  9777. {
  9778. if (isEmpty())
  9779. {
  9780. return reinterpret_cast <const char*> (text);
  9781. }
  9782. else
  9783. {
  9784. const int currentLen = length() + 1;
  9785. const int utf8BytesNeeded = getNumBytesAsUTF8();
  9786. String* const mutableThis = const_cast <String*> (this);
  9787. mutableThis->text = StringHolder::makeUniqueWithSize (mutableThis->text, currentLen + 1 + utf8BytesNeeded / sizeof (juce_wchar));
  9788. char* const otherCopy = reinterpret_cast <char*> (mutableThis->text + currentLen);
  9789. copyToUTF8 (otherCopy, std::numeric_limits<int>::max());
  9790. return otherCopy;
  9791. }
  9792. }
  9793. int String::copyToUTF8 (char* const buffer, const int maxBufferSizeBytes) const throw()
  9794. {
  9795. jassert (maxBufferSizeBytes >= 0); // keep this value positive, or no characters will be copied!
  9796. int num = 0, index = 0;
  9797. for (;;)
  9798. {
  9799. const uint32 c = (uint32) text [index++];
  9800. if (c >= 0x80)
  9801. {
  9802. int numExtraBytes = 1;
  9803. if (c >= 0x800)
  9804. {
  9805. ++numExtraBytes;
  9806. if (c >= 0x10000)
  9807. {
  9808. ++numExtraBytes;
  9809. if (c >= 0x200000)
  9810. {
  9811. ++numExtraBytes;
  9812. if (c >= 0x4000000)
  9813. ++numExtraBytes;
  9814. }
  9815. }
  9816. }
  9817. if (buffer != 0)
  9818. {
  9819. if (num + numExtraBytes >= maxBufferSizeBytes)
  9820. {
  9821. buffer [num++] = 0;
  9822. break;
  9823. }
  9824. else
  9825. {
  9826. buffer [num++] = (uint8) ((0xff << (7 - numExtraBytes)) | (c >> (numExtraBytes * 6)));
  9827. while (--numExtraBytes >= 0)
  9828. buffer [num++] = (uint8) (0x80 | (0x3f & (c >> (numExtraBytes * 6))));
  9829. }
  9830. }
  9831. else
  9832. {
  9833. num += numExtraBytes + 1;
  9834. }
  9835. }
  9836. else
  9837. {
  9838. if (buffer != 0)
  9839. {
  9840. if (num + 1 >= maxBufferSizeBytes)
  9841. {
  9842. buffer [num++] = 0;
  9843. break;
  9844. }
  9845. buffer [num] = (uint8) c;
  9846. }
  9847. ++num;
  9848. }
  9849. if (c == 0)
  9850. break;
  9851. }
  9852. return num;
  9853. }
  9854. int String::getNumBytesAsUTF8() const throw()
  9855. {
  9856. int num = 0;
  9857. const juce_wchar* t = text;
  9858. for (;;)
  9859. {
  9860. const uint32 c = (uint32) *t;
  9861. if (c >= 0x80)
  9862. {
  9863. ++num;
  9864. if (c >= 0x800)
  9865. {
  9866. ++num;
  9867. if (c >= 0x10000)
  9868. {
  9869. ++num;
  9870. if (c >= 0x200000)
  9871. {
  9872. ++num;
  9873. if (c >= 0x4000000)
  9874. ++num;
  9875. }
  9876. }
  9877. }
  9878. }
  9879. else if (c == 0)
  9880. break;
  9881. ++num;
  9882. ++t;
  9883. }
  9884. return num;
  9885. }
  9886. const String String::fromUTF8 (const char* const buffer, int bufferSizeBytes)
  9887. {
  9888. if (buffer == 0)
  9889. return empty;
  9890. if (bufferSizeBytes < 0)
  9891. bufferSizeBytes = std::numeric_limits<int>::max();
  9892. size_t numBytes;
  9893. for (numBytes = 0; numBytes < (size_t) bufferSizeBytes; ++numBytes)
  9894. if (buffer [numBytes] == 0)
  9895. break;
  9896. String result ((size_t) numBytes + 1, (int) 0);
  9897. juce_wchar* dest = result.text;
  9898. size_t i = 0;
  9899. while (i < numBytes)
  9900. {
  9901. const char c = buffer [i++];
  9902. if (c < 0)
  9903. {
  9904. unsigned int mask = 0x7f;
  9905. int bit = 0x40;
  9906. int numExtraValues = 0;
  9907. while (bit != 0 && (c & bit) != 0)
  9908. {
  9909. bit >>= 1;
  9910. mask >>= 1;
  9911. ++numExtraValues;
  9912. }
  9913. int n = (mask & (unsigned char) c);
  9914. while (--numExtraValues >= 0 && i < (size_t) bufferSizeBytes)
  9915. {
  9916. const char nextByte = buffer[i];
  9917. if ((nextByte & 0xc0) != 0x80)
  9918. break;
  9919. n <<= 6;
  9920. n |= (nextByte & 0x3f);
  9921. ++i;
  9922. }
  9923. *dest++ = (juce_wchar) n;
  9924. }
  9925. else
  9926. {
  9927. *dest++ = (juce_wchar) c;
  9928. }
  9929. }
  9930. *dest = 0;
  9931. return result;
  9932. }
  9933. const char* String::toCString() const
  9934. {
  9935. if (isEmpty())
  9936. {
  9937. return reinterpret_cast <const char*> (text);
  9938. }
  9939. else
  9940. {
  9941. const int len = length();
  9942. String* const mutableThis = const_cast <String*> (this);
  9943. mutableThis->text = StringHolder::makeUniqueWithSize (mutableThis->text, (len + 1) * 2);
  9944. char* otherCopy = reinterpret_cast <char*> (mutableThis->text + len + 1);
  9945. CharacterFunctions::copy (otherCopy, text, len);
  9946. otherCopy [len] = 0;
  9947. return otherCopy;
  9948. }
  9949. }
  9950. #if JUCE_MSVC
  9951. #pragma warning (push)
  9952. #pragma warning (disable: 4514 4996)
  9953. #endif
  9954. int String::getNumBytesAsCString() const throw()
  9955. {
  9956. return (int) wcstombs (0, text, 0);
  9957. }
  9958. int String::copyToCString (char* destBuffer, const int maxBufferSizeBytes) const throw()
  9959. {
  9960. const int numBytes = (int) wcstombs (destBuffer, text, maxBufferSizeBytes);
  9961. if (destBuffer != 0 && numBytes >= 0)
  9962. destBuffer [numBytes] = 0;
  9963. return numBytes;
  9964. }
  9965. #if JUCE_MSVC
  9966. #pragma warning (pop)
  9967. #endif
  9968. void String::copyToUnicode (juce_wchar* const destBuffer, const int maxCharsToCopy) const throw()
  9969. {
  9970. StringHolder::copyChars (destBuffer, text, jmin (maxCharsToCopy, length()));
  9971. }
  9972. String::Concatenator::Concatenator (String& stringToAppendTo)
  9973. : result (stringToAppendTo),
  9974. nextIndex (stringToAppendTo.length())
  9975. {
  9976. }
  9977. String::Concatenator::~Concatenator()
  9978. {
  9979. }
  9980. void String::Concatenator::append (const String& s)
  9981. {
  9982. const int len = s.length();
  9983. if (len > 0)
  9984. {
  9985. result.preallocateStorage (nextIndex + len);
  9986. s.copyToUnicode (static_cast <juce_wchar*> (result) + nextIndex, len);
  9987. nextIndex += len;
  9988. }
  9989. }
  9990. END_JUCE_NAMESPACE
  9991. /*** End of inlined file: juce_String.cpp ***/
  9992. /*** Start of inlined file: juce_StringArray.cpp ***/
  9993. BEGIN_JUCE_NAMESPACE
  9994. StringArray::StringArray() throw()
  9995. {
  9996. }
  9997. StringArray::StringArray (const StringArray& other)
  9998. : strings (other.strings)
  9999. {
  10000. }
  10001. StringArray::StringArray (const String& firstValue)
  10002. {
  10003. strings.add (firstValue);
  10004. }
  10005. StringArray::StringArray (const juce_wchar* const* const initialStrings,
  10006. const int numberOfStrings)
  10007. {
  10008. for (int i = 0; i < numberOfStrings; ++i)
  10009. strings.add (initialStrings [i]);
  10010. }
  10011. StringArray::StringArray (const char* const* const initialStrings,
  10012. const int numberOfStrings)
  10013. {
  10014. for (int i = 0; i < numberOfStrings; ++i)
  10015. strings.add (initialStrings [i]);
  10016. }
  10017. StringArray::StringArray (const juce_wchar* const* const initialStrings)
  10018. {
  10019. int i = 0;
  10020. while (initialStrings[i] != 0)
  10021. strings.add (initialStrings [i++]);
  10022. }
  10023. StringArray::StringArray (const char* const* const initialStrings)
  10024. {
  10025. int i = 0;
  10026. while (initialStrings[i] != 0)
  10027. strings.add (initialStrings [i++]);
  10028. }
  10029. StringArray& StringArray::operator= (const StringArray& other)
  10030. {
  10031. strings = other.strings;
  10032. return *this;
  10033. }
  10034. StringArray::~StringArray()
  10035. {
  10036. }
  10037. bool StringArray::operator== (const StringArray& other) const throw()
  10038. {
  10039. if (other.size() != size())
  10040. return false;
  10041. for (int i = size(); --i >= 0;)
  10042. if (other.strings.getReference(i) != strings.getReference(i))
  10043. return false;
  10044. return true;
  10045. }
  10046. bool StringArray::operator!= (const StringArray& other) const throw()
  10047. {
  10048. return ! operator== (other);
  10049. }
  10050. void StringArray::clear()
  10051. {
  10052. strings.clear();
  10053. }
  10054. const String& StringArray::operator[] (const int index) const throw()
  10055. {
  10056. if (((unsigned int) index) < (unsigned int) strings.size())
  10057. return strings.getReference (index);
  10058. return String::empty;
  10059. }
  10060. String& StringArray::getReference (const int index) throw()
  10061. {
  10062. jassert (((unsigned int) index) < (unsigned int) strings.size());
  10063. return strings.getReference (index);
  10064. }
  10065. void StringArray::add (const String& newString)
  10066. {
  10067. strings.add (newString);
  10068. }
  10069. void StringArray::insert (const int index, const String& newString)
  10070. {
  10071. strings.insert (index, newString);
  10072. }
  10073. void StringArray::addIfNotAlreadyThere (const String& newString, const bool ignoreCase)
  10074. {
  10075. if (! contains (newString, ignoreCase))
  10076. add (newString);
  10077. }
  10078. void StringArray::addArray (const StringArray& otherArray, int startIndex, int numElementsToAdd)
  10079. {
  10080. if (startIndex < 0)
  10081. {
  10082. jassertfalse;
  10083. startIndex = 0;
  10084. }
  10085. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > otherArray.size())
  10086. numElementsToAdd = otherArray.size() - startIndex;
  10087. while (--numElementsToAdd >= 0)
  10088. strings.add (otherArray.strings.getReference (startIndex++));
  10089. }
  10090. void StringArray::set (const int index, const String& newString)
  10091. {
  10092. strings.set (index, newString);
  10093. }
  10094. bool StringArray::contains (const String& stringToLookFor, const bool ignoreCase) const
  10095. {
  10096. if (ignoreCase)
  10097. {
  10098. for (int i = size(); --i >= 0;)
  10099. if (strings.getReference(i).equalsIgnoreCase (stringToLookFor))
  10100. return true;
  10101. }
  10102. else
  10103. {
  10104. for (int i = size(); --i >= 0;)
  10105. if (stringToLookFor == strings.getReference(i))
  10106. return true;
  10107. }
  10108. return false;
  10109. }
  10110. int StringArray::indexOf (const String& stringToLookFor, const bool ignoreCase, int i) const
  10111. {
  10112. if (i < 0)
  10113. i = 0;
  10114. const int numElements = size();
  10115. if (ignoreCase)
  10116. {
  10117. while (i < numElements)
  10118. {
  10119. if (strings.getReference(i).equalsIgnoreCase (stringToLookFor))
  10120. return i;
  10121. ++i;
  10122. }
  10123. }
  10124. else
  10125. {
  10126. while (i < numElements)
  10127. {
  10128. if (stringToLookFor == strings.getReference (i))
  10129. return i;
  10130. ++i;
  10131. }
  10132. }
  10133. return -1;
  10134. }
  10135. void StringArray::remove (const int index)
  10136. {
  10137. strings.remove (index);
  10138. }
  10139. void StringArray::removeString (const String& stringToRemove,
  10140. const bool ignoreCase)
  10141. {
  10142. if (ignoreCase)
  10143. {
  10144. for (int i = size(); --i >= 0;)
  10145. if (strings.getReference(i).equalsIgnoreCase (stringToRemove))
  10146. strings.remove (i);
  10147. }
  10148. else
  10149. {
  10150. for (int i = size(); --i >= 0;)
  10151. if (stringToRemove == strings.getReference (i))
  10152. strings.remove (i);
  10153. }
  10154. }
  10155. void StringArray::removeRange (int startIndex, int numberToRemove)
  10156. {
  10157. strings.removeRange (startIndex, numberToRemove);
  10158. }
  10159. void StringArray::removeEmptyStrings (const bool removeWhitespaceStrings)
  10160. {
  10161. if (removeWhitespaceStrings)
  10162. {
  10163. for (int i = size(); --i >= 0;)
  10164. if (! strings.getReference(i).containsNonWhitespaceChars())
  10165. strings.remove (i);
  10166. }
  10167. else
  10168. {
  10169. for (int i = size(); --i >= 0;)
  10170. if (strings.getReference(i).isEmpty())
  10171. strings.remove (i);
  10172. }
  10173. }
  10174. void StringArray::trim()
  10175. {
  10176. for (int i = size(); --i >= 0;)
  10177. {
  10178. String& s = strings.getReference(i);
  10179. s = s.trim();
  10180. }
  10181. }
  10182. class InternalStringArrayComparator_CaseSensitive
  10183. {
  10184. public:
  10185. static int compareElements (String& first, String& second) { return first.compare (second); }
  10186. };
  10187. class InternalStringArrayComparator_CaseInsensitive
  10188. {
  10189. public:
  10190. static int compareElements (String& first, String& second) { return first.compareIgnoreCase (second); }
  10191. };
  10192. void StringArray::sort (const bool ignoreCase)
  10193. {
  10194. if (ignoreCase)
  10195. {
  10196. InternalStringArrayComparator_CaseInsensitive comp;
  10197. strings.sort (comp);
  10198. }
  10199. else
  10200. {
  10201. InternalStringArrayComparator_CaseSensitive comp;
  10202. strings.sort (comp);
  10203. }
  10204. }
  10205. void StringArray::move (const int currentIndex, int newIndex) throw()
  10206. {
  10207. strings.move (currentIndex, newIndex);
  10208. }
  10209. const String StringArray::joinIntoString (const String& separator, int start, int numberToJoin) const
  10210. {
  10211. const int last = (numberToJoin < 0) ? size()
  10212. : jmin (size(), start + numberToJoin);
  10213. if (start < 0)
  10214. start = 0;
  10215. if (start >= last)
  10216. return String::empty;
  10217. if (start == last - 1)
  10218. return strings.getReference (start);
  10219. const int separatorLen = separator.length();
  10220. int charsNeeded = separatorLen * (last - start - 1);
  10221. for (int i = start; i < last; ++i)
  10222. charsNeeded += strings.getReference(i).length();
  10223. String result;
  10224. result.preallocateStorage (charsNeeded);
  10225. juce_wchar* dest = result;
  10226. while (start < last)
  10227. {
  10228. const String& s = strings.getReference (start);
  10229. const int len = s.length();
  10230. if (len > 0)
  10231. {
  10232. s.copyToUnicode (dest, len);
  10233. dest += len;
  10234. }
  10235. if (++start < last && separatorLen > 0)
  10236. {
  10237. separator.copyToUnicode (dest, separatorLen);
  10238. dest += separatorLen;
  10239. }
  10240. }
  10241. *dest = 0;
  10242. return result;
  10243. }
  10244. int StringArray::addTokens (const String& text, const bool preserveQuotedStrings)
  10245. {
  10246. return addTokens (text, " \n\r\t", preserveQuotedStrings ? "\"" : "");
  10247. }
  10248. int StringArray::addTokens (const String& text, const String& breakCharacters, const String& quoteCharacters)
  10249. {
  10250. int num = 0;
  10251. if (text.isNotEmpty())
  10252. {
  10253. bool insideQuotes = false;
  10254. juce_wchar currentQuoteChar = 0;
  10255. int i = 0;
  10256. int tokenStart = 0;
  10257. for (;;)
  10258. {
  10259. const juce_wchar c = text[i];
  10260. const bool isBreak = (c == 0) || ((! insideQuotes) && breakCharacters.containsChar (c));
  10261. if (! isBreak)
  10262. {
  10263. if (quoteCharacters.containsChar (c))
  10264. {
  10265. if (insideQuotes)
  10266. {
  10267. // only break out of quotes-mode if we find a matching quote to the
  10268. // one that we opened with..
  10269. if (currentQuoteChar == c)
  10270. insideQuotes = false;
  10271. }
  10272. else
  10273. {
  10274. insideQuotes = true;
  10275. currentQuoteChar = c;
  10276. }
  10277. }
  10278. }
  10279. else
  10280. {
  10281. add (String (static_cast <const juce_wchar*> (text) + tokenStart, i - tokenStart));
  10282. ++num;
  10283. tokenStart = i + 1;
  10284. }
  10285. if (c == 0)
  10286. break;
  10287. ++i;
  10288. }
  10289. }
  10290. return num;
  10291. }
  10292. int StringArray::addLines (const String& sourceText)
  10293. {
  10294. int numLines = 0;
  10295. const juce_wchar* text = sourceText;
  10296. while (*text != 0)
  10297. {
  10298. const juce_wchar* const startOfLine = text;
  10299. while (*text != 0)
  10300. {
  10301. if (*text == '\r')
  10302. {
  10303. ++text;
  10304. if (*text == '\n')
  10305. ++text;
  10306. break;
  10307. }
  10308. if (*text == '\n')
  10309. {
  10310. ++text;
  10311. break;
  10312. }
  10313. ++text;
  10314. }
  10315. const juce_wchar* endOfLine = text;
  10316. if (endOfLine > startOfLine && (*(endOfLine - 1) == '\r' || *(endOfLine - 1) == '\n'))
  10317. --endOfLine;
  10318. if (endOfLine > startOfLine && (*(endOfLine - 1) == '\r' || *(endOfLine - 1) == '\n'))
  10319. --endOfLine;
  10320. add (String (startOfLine, jmax (0, (int) (endOfLine - startOfLine))));
  10321. ++numLines;
  10322. }
  10323. return numLines;
  10324. }
  10325. void StringArray::removeDuplicates (const bool ignoreCase)
  10326. {
  10327. for (int i = 0; i < size() - 1; ++i)
  10328. {
  10329. const String s (strings.getReference(i));
  10330. int nextIndex = i + 1;
  10331. for (;;)
  10332. {
  10333. nextIndex = indexOf (s, ignoreCase, nextIndex);
  10334. if (nextIndex < 0)
  10335. break;
  10336. strings.remove (nextIndex);
  10337. }
  10338. }
  10339. }
  10340. void StringArray::appendNumbersToDuplicates (const bool ignoreCase,
  10341. const bool appendNumberToFirstInstance,
  10342. const juce_wchar* preNumberString,
  10343. const juce_wchar* postNumberString)
  10344. {
  10345. if (preNumberString == 0)
  10346. preNumberString = L" (";
  10347. if (postNumberString == 0)
  10348. postNumberString = L")";
  10349. for (int i = 0; i < size() - 1; ++i)
  10350. {
  10351. String& s = strings.getReference(i);
  10352. int nextIndex = indexOf (s, ignoreCase, i + 1);
  10353. if (nextIndex >= 0)
  10354. {
  10355. const String original (s);
  10356. int number = 0;
  10357. if (appendNumberToFirstInstance)
  10358. s = original + preNumberString + String (++number) + postNumberString;
  10359. else
  10360. ++number;
  10361. while (nextIndex >= 0)
  10362. {
  10363. set (nextIndex, (*this)[nextIndex] + preNumberString + String (++number) + postNumberString);
  10364. nextIndex = indexOf (original, ignoreCase, nextIndex + 1);
  10365. }
  10366. }
  10367. }
  10368. }
  10369. void StringArray::minimiseStorageOverheads()
  10370. {
  10371. strings.minimiseStorageOverheads();
  10372. }
  10373. END_JUCE_NAMESPACE
  10374. /*** End of inlined file: juce_StringArray.cpp ***/
  10375. /*** Start of inlined file: juce_StringPairArray.cpp ***/
  10376. BEGIN_JUCE_NAMESPACE
  10377. StringPairArray::StringPairArray (const bool ignoreCase_)
  10378. : ignoreCase (ignoreCase_)
  10379. {
  10380. }
  10381. StringPairArray::StringPairArray (const StringPairArray& other)
  10382. : keys (other.keys),
  10383. values (other.values),
  10384. ignoreCase (other.ignoreCase)
  10385. {
  10386. }
  10387. StringPairArray::~StringPairArray()
  10388. {
  10389. }
  10390. StringPairArray& StringPairArray::operator= (const StringPairArray& other)
  10391. {
  10392. keys = other.keys;
  10393. values = other.values;
  10394. return *this;
  10395. }
  10396. bool StringPairArray::operator== (const StringPairArray& other) const
  10397. {
  10398. for (int i = keys.size(); --i >= 0;)
  10399. if (other [keys[i]] != values[i])
  10400. return false;
  10401. return true;
  10402. }
  10403. bool StringPairArray::operator!= (const StringPairArray& other) const
  10404. {
  10405. return ! operator== (other);
  10406. }
  10407. const String& StringPairArray::operator[] (const String& key) const
  10408. {
  10409. return values [keys.indexOf (key, ignoreCase)];
  10410. }
  10411. const String StringPairArray::getValue (const String& key, const String& defaultReturnValue) const
  10412. {
  10413. const int i = keys.indexOf (key, ignoreCase);
  10414. if (i >= 0)
  10415. return values[i];
  10416. return defaultReturnValue;
  10417. }
  10418. void StringPairArray::set (const String& key, const String& value)
  10419. {
  10420. const int i = keys.indexOf (key, ignoreCase);
  10421. if (i >= 0)
  10422. {
  10423. values.set (i, value);
  10424. }
  10425. else
  10426. {
  10427. keys.add (key);
  10428. values.add (value);
  10429. }
  10430. }
  10431. void StringPairArray::addArray (const StringPairArray& other)
  10432. {
  10433. for (int i = 0; i < other.size(); ++i)
  10434. set (other.keys[i], other.values[i]);
  10435. }
  10436. void StringPairArray::clear()
  10437. {
  10438. keys.clear();
  10439. values.clear();
  10440. }
  10441. void StringPairArray::remove (const String& key)
  10442. {
  10443. remove (keys.indexOf (key, ignoreCase));
  10444. }
  10445. void StringPairArray::remove (const int index)
  10446. {
  10447. keys.remove (index);
  10448. values.remove (index);
  10449. }
  10450. void StringPairArray::setIgnoresCase (const bool shouldIgnoreCase)
  10451. {
  10452. ignoreCase = shouldIgnoreCase;
  10453. }
  10454. const String StringPairArray::getDescription() const
  10455. {
  10456. String s;
  10457. for (int i = 0; i < keys.size(); ++i)
  10458. {
  10459. s << keys[i] << " = " << values[i];
  10460. if (i < keys.size())
  10461. s << ", ";
  10462. }
  10463. return s;
  10464. }
  10465. void StringPairArray::minimiseStorageOverheads()
  10466. {
  10467. keys.minimiseStorageOverheads();
  10468. values.minimiseStorageOverheads();
  10469. }
  10470. END_JUCE_NAMESPACE
  10471. /*** End of inlined file: juce_StringPairArray.cpp ***/
  10472. /*** Start of inlined file: juce_StringPool.cpp ***/
  10473. BEGIN_JUCE_NAMESPACE
  10474. StringPool::StringPool() throw() {}
  10475. StringPool::~StringPool() {}
  10476. template <class StringType>
  10477. static const juce_wchar* getPooledStringFromArray (Array<String>& strings, StringType newString)
  10478. {
  10479. int start = 0;
  10480. int end = strings.size();
  10481. for (;;)
  10482. {
  10483. if (start >= end)
  10484. {
  10485. jassert (start <= end);
  10486. strings.insert (start, newString);
  10487. return strings.getReference (start);
  10488. }
  10489. else
  10490. {
  10491. const String& startString = strings.getReference (start);
  10492. if (startString == newString)
  10493. return startString;
  10494. const int halfway = (start + end) >> 1;
  10495. if (halfway == start)
  10496. {
  10497. if (startString.compare (newString) < 0)
  10498. ++start;
  10499. strings.insert (start, newString);
  10500. return strings.getReference (start);
  10501. }
  10502. const int comp = strings.getReference (halfway).compare (newString);
  10503. if (comp == 0)
  10504. return strings.getReference (halfway);
  10505. else if (comp < 0)
  10506. start = halfway;
  10507. else
  10508. end = halfway;
  10509. }
  10510. }
  10511. }
  10512. const juce_wchar* StringPool::getPooledString (const String& s)
  10513. {
  10514. if (s.isEmpty())
  10515. return String::empty;
  10516. return getPooledStringFromArray (strings, s);
  10517. }
  10518. const juce_wchar* StringPool::getPooledString (const char* const s)
  10519. {
  10520. if (s == 0 || *s == 0)
  10521. return String::empty;
  10522. return getPooledStringFromArray (strings, s);
  10523. }
  10524. const juce_wchar* StringPool::getPooledString (const juce_wchar* const s)
  10525. {
  10526. if (s == 0 || *s == 0)
  10527. return String::empty;
  10528. return getPooledStringFromArray (strings, s);
  10529. }
  10530. int StringPool::size() const throw()
  10531. {
  10532. return strings.size();
  10533. }
  10534. const juce_wchar* StringPool::operator[] (const int index) const throw()
  10535. {
  10536. return strings [index];
  10537. }
  10538. END_JUCE_NAMESPACE
  10539. /*** End of inlined file: juce_StringPool.cpp ***/
  10540. /*** Start of inlined file: juce_XmlDocument.cpp ***/
  10541. BEGIN_JUCE_NAMESPACE
  10542. XmlDocument::XmlDocument (const String& documentText)
  10543. : originalText (documentText),
  10544. ignoreEmptyTextElements (true)
  10545. {
  10546. }
  10547. XmlDocument::XmlDocument (const File& file)
  10548. : ignoreEmptyTextElements (true)
  10549. {
  10550. inputSource = new FileInputSource (file);
  10551. }
  10552. XmlDocument::~XmlDocument()
  10553. {
  10554. }
  10555. void XmlDocument::setInputSource (InputSource* const newSource) throw()
  10556. {
  10557. inputSource = newSource;
  10558. }
  10559. void XmlDocument::setEmptyTextElementsIgnored (const bool shouldBeIgnored) throw()
  10560. {
  10561. ignoreEmptyTextElements = shouldBeIgnored;
  10562. }
  10563. bool XmlDocument::isXmlIdentifierCharSlow (const juce_wchar c) throw()
  10564. {
  10565. return CharacterFunctions::isLetterOrDigit (c)
  10566. || c == '_' || c == '-' || c == ':' || c == '.';
  10567. }
  10568. inline bool XmlDocument::isXmlIdentifierChar (const juce_wchar c) const throw()
  10569. {
  10570. return (c > 0 && c <= 127) ? identifierLookupTable [(int) c]
  10571. : isXmlIdentifierCharSlow (c);
  10572. }
  10573. XmlElement* XmlDocument::getDocumentElement (const bool onlyReadOuterDocumentElement)
  10574. {
  10575. String textToParse (originalText);
  10576. if (textToParse.isEmpty() && inputSource != 0)
  10577. {
  10578. ScopedPointer <InputStream> in (inputSource->createInputStream());
  10579. if (in != 0)
  10580. {
  10581. MemoryBlock data;
  10582. in->readIntoMemoryBlock (data, onlyReadOuterDocumentElement ? 8192 : -1);
  10583. if (data.getSize() >= 2
  10584. && ((data[0] == (char)-2 && data[1] == (char)-1)
  10585. || (data[0] == (char)-1 && data[1] == (char)-2)))
  10586. {
  10587. textToParse = String::createStringFromData (static_cast <const char*> (data.getData()), (int) data.getSize());
  10588. }
  10589. else
  10590. {
  10591. textToParse = String::fromUTF8 (static_cast <const char*> (data.getData()), (int) data.getSize());
  10592. }
  10593. if (! onlyReadOuterDocumentElement)
  10594. originalText = textToParse;
  10595. }
  10596. }
  10597. input = textToParse;
  10598. lastError = String::empty;
  10599. errorOccurred = false;
  10600. outOfData = false;
  10601. needToLoadDTD = true;
  10602. for (int i = 0; i < 128; ++i)
  10603. identifierLookupTable[i] = isXmlIdentifierCharSlow ((juce_wchar) i);
  10604. if (textToParse.isEmpty())
  10605. {
  10606. lastError = "not enough input";
  10607. }
  10608. else
  10609. {
  10610. skipHeader();
  10611. if (input != 0)
  10612. {
  10613. ScopedPointer <XmlElement> result (readNextElement (! onlyReadOuterDocumentElement));
  10614. if (! errorOccurred)
  10615. return result.release();
  10616. }
  10617. else
  10618. {
  10619. lastError = "incorrect xml header";
  10620. }
  10621. }
  10622. return 0;
  10623. }
  10624. const String& XmlDocument::getLastParseError() const throw()
  10625. {
  10626. return lastError;
  10627. }
  10628. void XmlDocument::setLastError (const String& desc, const bool carryOn)
  10629. {
  10630. lastError = desc;
  10631. errorOccurred = ! carryOn;
  10632. }
  10633. const String XmlDocument::getFileContents (const String& filename) const
  10634. {
  10635. if (inputSource != 0)
  10636. {
  10637. const ScopedPointer <InputStream> in (inputSource->createInputStreamFor (filename.trim().unquoted()));
  10638. if (in != 0)
  10639. return in->readEntireStreamAsString();
  10640. }
  10641. return String::empty;
  10642. }
  10643. juce_wchar XmlDocument::readNextChar() throw()
  10644. {
  10645. if (*input != 0)
  10646. {
  10647. return *input++;
  10648. }
  10649. else
  10650. {
  10651. outOfData = true;
  10652. return 0;
  10653. }
  10654. }
  10655. int XmlDocument::findNextTokenLength() throw()
  10656. {
  10657. int len = 0;
  10658. juce_wchar c = *input;
  10659. while (isXmlIdentifierChar (c))
  10660. c = input [++len];
  10661. return len;
  10662. }
  10663. void XmlDocument::skipHeader()
  10664. {
  10665. const juce_wchar* const found = CharacterFunctions::find (input, JUCE_T("<?xml"));
  10666. if (found != 0)
  10667. {
  10668. input = found;
  10669. input = CharacterFunctions::find (input, JUCE_T("?>"));
  10670. if (input == 0)
  10671. return;
  10672. input += 2;
  10673. }
  10674. skipNextWhiteSpace();
  10675. const juce_wchar* docType = CharacterFunctions::find (input, JUCE_T("<!DOCTYPE"));
  10676. if (docType == 0)
  10677. return;
  10678. input = docType + 9;
  10679. int n = 1;
  10680. while (n > 0)
  10681. {
  10682. const juce_wchar c = readNextChar();
  10683. if (outOfData)
  10684. return;
  10685. if (c == '<')
  10686. ++n;
  10687. else if (c == '>')
  10688. --n;
  10689. }
  10690. docType += 9;
  10691. dtdText = String (docType, (int) (input - (docType + 1))).trim();
  10692. }
  10693. void XmlDocument::skipNextWhiteSpace()
  10694. {
  10695. for (;;)
  10696. {
  10697. juce_wchar c = *input;
  10698. while (CharacterFunctions::isWhitespace (c))
  10699. c = *++input;
  10700. if (c == 0)
  10701. {
  10702. outOfData = true;
  10703. break;
  10704. }
  10705. else if (c == '<')
  10706. {
  10707. if (input[1] == '!'
  10708. && input[2] == '-'
  10709. && input[3] == '-')
  10710. {
  10711. const juce_wchar* const closeComment = CharacterFunctions::find (input, JUCE_T("-->"));
  10712. if (closeComment == 0)
  10713. {
  10714. outOfData = true;
  10715. break;
  10716. }
  10717. input = closeComment + 3;
  10718. continue;
  10719. }
  10720. else if (input[1] == '?')
  10721. {
  10722. const juce_wchar* const closeBracket = CharacterFunctions::find (input, JUCE_T("?>"));
  10723. if (closeBracket == 0)
  10724. {
  10725. outOfData = true;
  10726. break;
  10727. }
  10728. input = closeBracket + 2;
  10729. continue;
  10730. }
  10731. }
  10732. break;
  10733. }
  10734. }
  10735. void XmlDocument::readQuotedString (String& result)
  10736. {
  10737. const juce_wchar quote = readNextChar();
  10738. while (! outOfData)
  10739. {
  10740. const juce_wchar c = readNextChar();
  10741. if (c == quote)
  10742. break;
  10743. if (c == '&')
  10744. {
  10745. --input;
  10746. readEntity (result);
  10747. }
  10748. else
  10749. {
  10750. --input;
  10751. const juce_wchar* const start = input;
  10752. for (;;)
  10753. {
  10754. const juce_wchar character = *input;
  10755. if (character == quote)
  10756. {
  10757. result.append (start, (int) (input - start));
  10758. ++input;
  10759. return;
  10760. }
  10761. else if (character == '&')
  10762. {
  10763. result.append (start, (int) (input - start));
  10764. break;
  10765. }
  10766. else if (character == 0)
  10767. {
  10768. outOfData = true;
  10769. setLastError ("unmatched quotes", false);
  10770. break;
  10771. }
  10772. ++input;
  10773. }
  10774. }
  10775. }
  10776. }
  10777. XmlElement* XmlDocument::readNextElement (const bool alsoParseSubElements)
  10778. {
  10779. XmlElement* node = 0;
  10780. skipNextWhiteSpace();
  10781. if (outOfData)
  10782. return 0;
  10783. input = CharacterFunctions::find (input, JUCE_T("<"));
  10784. if (input != 0)
  10785. {
  10786. ++input;
  10787. int tagLen = findNextTokenLength();
  10788. if (tagLen == 0)
  10789. {
  10790. // no tag name - but allow for a gap after the '<' before giving an error
  10791. skipNextWhiteSpace();
  10792. tagLen = findNextTokenLength();
  10793. if (tagLen == 0)
  10794. {
  10795. setLastError ("tag name missing", false);
  10796. return node;
  10797. }
  10798. }
  10799. node = new XmlElement (String (input, tagLen));
  10800. input += tagLen;
  10801. XmlElement::XmlAttributeNode* lastAttribute = 0;
  10802. // look for attributes
  10803. for (;;)
  10804. {
  10805. skipNextWhiteSpace();
  10806. const juce_wchar c = *input;
  10807. // empty tag..
  10808. if (c == '/' && input[1] == '>')
  10809. {
  10810. input += 2;
  10811. break;
  10812. }
  10813. // parse the guts of the element..
  10814. if (c == '>')
  10815. {
  10816. ++input;
  10817. skipNextWhiteSpace();
  10818. if (alsoParseSubElements)
  10819. readChildElements (node);
  10820. break;
  10821. }
  10822. // get an attribute..
  10823. if (isXmlIdentifierChar (c))
  10824. {
  10825. const int attNameLen = findNextTokenLength();
  10826. if (attNameLen > 0)
  10827. {
  10828. const juce_wchar* attNameStart = input;
  10829. input += attNameLen;
  10830. skipNextWhiteSpace();
  10831. if (readNextChar() == '=')
  10832. {
  10833. skipNextWhiteSpace();
  10834. const juce_wchar nextChar = *input;
  10835. if (nextChar == '"' || nextChar == '\'')
  10836. {
  10837. XmlElement::XmlAttributeNode* const newAtt
  10838. = new XmlElement::XmlAttributeNode (String (attNameStart, attNameLen),
  10839. String::empty);
  10840. readQuotedString (newAtt->value);
  10841. if (lastAttribute == 0)
  10842. node->attributes = newAtt;
  10843. else
  10844. lastAttribute->next = newAtt;
  10845. lastAttribute = newAtt;
  10846. continue;
  10847. }
  10848. }
  10849. }
  10850. }
  10851. else
  10852. {
  10853. if (! outOfData)
  10854. setLastError ("illegal character found in " + node->getTagName() + ": '" + c + "'", false);
  10855. }
  10856. break;
  10857. }
  10858. }
  10859. return node;
  10860. }
  10861. void XmlDocument::readChildElements (XmlElement* parent)
  10862. {
  10863. XmlElement* lastChildNode = 0;
  10864. for (;;)
  10865. {
  10866. skipNextWhiteSpace();
  10867. if (outOfData)
  10868. {
  10869. setLastError ("unmatched tags", false);
  10870. break;
  10871. }
  10872. if (*input == '<')
  10873. {
  10874. if (input[1] == '/')
  10875. {
  10876. // our close tag..
  10877. input = CharacterFunctions::find (input, JUCE_T(">"));
  10878. ++input;
  10879. break;
  10880. }
  10881. else if (input[1] == '!'
  10882. && input[2] == '['
  10883. && input[3] == 'C'
  10884. && input[4] == 'D'
  10885. && input[5] == 'A'
  10886. && input[6] == 'T'
  10887. && input[7] == 'A'
  10888. && input[8] == '[')
  10889. {
  10890. input += 9;
  10891. const juce_wchar* const inputStart = input;
  10892. int len = 0;
  10893. for (;;)
  10894. {
  10895. if (*input == 0)
  10896. {
  10897. setLastError ("unterminated CDATA section", false);
  10898. outOfData = true;
  10899. break;
  10900. }
  10901. else if (input[0] == ']'
  10902. && input[1] == ']'
  10903. && input[2] == '>')
  10904. {
  10905. input += 3;
  10906. break;
  10907. }
  10908. ++input;
  10909. ++len;
  10910. }
  10911. XmlElement* const e = new XmlElement ((int) 0);
  10912. e->setText (String (inputStart, len));
  10913. if (lastChildNode != 0)
  10914. lastChildNode->nextElement = e;
  10915. else
  10916. parent->addChildElement (e);
  10917. lastChildNode = e;
  10918. }
  10919. else
  10920. {
  10921. // this is some other element, so parse and add it..
  10922. XmlElement* const n = readNextElement (true);
  10923. if (n != 0)
  10924. {
  10925. if (lastChildNode == 0)
  10926. parent->addChildElement (n);
  10927. else
  10928. lastChildNode->nextElement = n;
  10929. lastChildNode = n;
  10930. }
  10931. else
  10932. {
  10933. return;
  10934. }
  10935. }
  10936. }
  10937. else
  10938. {
  10939. // read character block..
  10940. XmlElement* const e = new XmlElement ((int)0);
  10941. if (lastChildNode != 0)
  10942. lastChildNode->nextElement = e;
  10943. else
  10944. parent->addChildElement (e);
  10945. lastChildNode = e;
  10946. String textElementContent;
  10947. for (;;)
  10948. {
  10949. const juce_wchar c = *input;
  10950. if (c == '<')
  10951. break;
  10952. if (c == 0)
  10953. {
  10954. setLastError ("unmatched tags", false);
  10955. outOfData = true;
  10956. return;
  10957. }
  10958. if (c == '&')
  10959. {
  10960. String entity;
  10961. readEntity (entity);
  10962. if (entity.startsWithChar ('<') && entity [1] != 0)
  10963. {
  10964. const juce_wchar* const oldInput = input;
  10965. const bool oldOutOfData = outOfData;
  10966. input = entity;
  10967. outOfData = false;
  10968. for (;;)
  10969. {
  10970. XmlElement* const n = readNextElement (true);
  10971. if (n == 0)
  10972. break;
  10973. if (lastChildNode == 0)
  10974. parent->addChildElement (n);
  10975. else
  10976. lastChildNode->nextElement = n;
  10977. lastChildNode = n;
  10978. }
  10979. input = oldInput;
  10980. outOfData = oldOutOfData;
  10981. }
  10982. else
  10983. {
  10984. textElementContent += entity;
  10985. }
  10986. }
  10987. else
  10988. {
  10989. const juce_wchar* start = input;
  10990. int len = 0;
  10991. for (;;)
  10992. {
  10993. const juce_wchar nextChar = *input;
  10994. if (nextChar == '<' || nextChar == '&')
  10995. {
  10996. break;
  10997. }
  10998. else if (nextChar == 0)
  10999. {
  11000. setLastError ("unmatched tags", false);
  11001. outOfData = true;
  11002. return;
  11003. }
  11004. ++input;
  11005. ++len;
  11006. }
  11007. textElementContent.append (start, len);
  11008. }
  11009. }
  11010. if (ignoreEmptyTextElements ? textElementContent.containsNonWhitespaceChars()
  11011. : textElementContent.isNotEmpty())
  11012. e->setText (textElementContent);
  11013. }
  11014. }
  11015. }
  11016. void XmlDocument::readEntity (String& result)
  11017. {
  11018. // skip over the ampersand
  11019. ++input;
  11020. if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("amp;"), 4) == 0)
  11021. {
  11022. input += 4;
  11023. result += '&';
  11024. }
  11025. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("quot;"), 5) == 0)
  11026. {
  11027. input += 5;
  11028. result += '"';
  11029. }
  11030. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("apos;"), 5) == 0)
  11031. {
  11032. input += 5;
  11033. result += '\'';
  11034. }
  11035. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("lt;"), 3) == 0)
  11036. {
  11037. input += 3;
  11038. result += '<';
  11039. }
  11040. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("gt;"), 3) == 0)
  11041. {
  11042. input += 3;
  11043. result += '>';
  11044. }
  11045. else if (*input == '#')
  11046. {
  11047. int charCode = 0;
  11048. ++input;
  11049. if (*input == 'x' || *input == 'X')
  11050. {
  11051. ++input;
  11052. int numChars = 0;
  11053. while (input[0] != ';')
  11054. {
  11055. const int hexValue = CharacterFunctions::getHexDigitValue (input[0]);
  11056. if (hexValue < 0 || ++numChars > 8)
  11057. {
  11058. setLastError ("illegal escape sequence", true);
  11059. break;
  11060. }
  11061. charCode = (charCode << 4) | hexValue;
  11062. ++input;
  11063. }
  11064. ++input;
  11065. }
  11066. else if (input[0] >= '0' && input[0] <= '9')
  11067. {
  11068. int numChars = 0;
  11069. while (input[0] != ';')
  11070. {
  11071. if (++numChars > 12)
  11072. {
  11073. setLastError ("illegal escape sequence", true);
  11074. break;
  11075. }
  11076. charCode = charCode * 10 + (input[0] - '0');
  11077. ++input;
  11078. }
  11079. ++input;
  11080. }
  11081. else
  11082. {
  11083. setLastError ("illegal escape sequence", true);
  11084. result += '&';
  11085. return;
  11086. }
  11087. result << (juce_wchar) charCode;
  11088. }
  11089. else
  11090. {
  11091. const juce_wchar* const entityNameStart = input;
  11092. const juce_wchar* const closingSemiColon = CharacterFunctions::find (input, JUCE_T(";"));
  11093. if (closingSemiColon == 0)
  11094. {
  11095. outOfData = true;
  11096. result += '&';
  11097. }
  11098. else
  11099. {
  11100. input = closingSemiColon + 1;
  11101. result += expandExternalEntity (String (entityNameStart,
  11102. (int) (closingSemiColon - entityNameStart)));
  11103. }
  11104. }
  11105. }
  11106. const String XmlDocument::expandEntity (const String& ent)
  11107. {
  11108. if (ent.equalsIgnoreCase ("amp"))
  11109. return String::charToString ('&');
  11110. if (ent.equalsIgnoreCase ("quot"))
  11111. return String::charToString ('"');
  11112. if (ent.equalsIgnoreCase ("apos"))
  11113. return String::charToString ('\'');
  11114. if (ent.equalsIgnoreCase ("lt"))
  11115. return String::charToString ('<');
  11116. if (ent.equalsIgnoreCase ("gt"))
  11117. return String::charToString ('>');
  11118. if (ent[0] == '#')
  11119. {
  11120. if (ent[1] == 'x' || ent[1] == 'X')
  11121. return String::charToString (static_cast <juce_wchar> (ent.substring (2).getHexValue32()));
  11122. if (ent[1] >= '0' && ent[1] <= '9')
  11123. return String::charToString (static_cast <juce_wchar> (ent.substring (1).getIntValue()));
  11124. setLastError ("illegal escape sequence", false);
  11125. return String::charToString ('&');
  11126. }
  11127. return expandExternalEntity (ent);
  11128. }
  11129. const String XmlDocument::expandExternalEntity (const String& entity)
  11130. {
  11131. if (needToLoadDTD)
  11132. {
  11133. if (dtdText.isNotEmpty())
  11134. {
  11135. dtdText = dtdText.trimCharactersAtEnd (">");
  11136. tokenisedDTD.addTokens (dtdText, true);
  11137. if (tokenisedDTD [tokenisedDTD.size() - 2].equalsIgnoreCase ("system")
  11138. && tokenisedDTD [tokenisedDTD.size() - 1].isQuotedString())
  11139. {
  11140. const String fn (tokenisedDTD [tokenisedDTD.size() - 1]);
  11141. tokenisedDTD.clear();
  11142. tokenisedDTD.addTokens (getFileContents (fn), true);
  11143. }
  11144. else
  11145. {
  11146. tokenisedDTD.clear();
  11147. const int openBracket = dtdText.indexOfChar ('[');
  11148. if (openBracket > 0)
  11149. {
  11150. const int closeBracket = dtdText.lastIndexOfChar (']');
  11151. if (closeBracket > openBracket)
  11152. tokenisedDTD.addTokens (dtdText.substring (openBracket + 1,
  11153. closeBracket), true);
  11154. }
  11155. }
  11156. for (int i = tokenisedDTD.size(); --i >= 0;)
  11157. {
  11158. if (tokenisedDTD[i].startsWithChar ('%')
  11159. && tokenisedDTD[i].endsWithChar (';'))
  11160. {
  11161. const String parsed (getParameterEntity (tokenisedDTD[i].substring (1, tokenisedDTD[i].length() - 1)));
  11162. StringArray newToks;
  11163. newToks.addTokens (parsed, true);
  11164. tokenisedDTD.remove (i);
  11165. for (int j = newToks.size(); --j >= 0;)
  11166. tokenisedDTD.insert (i, newToks[j]);
  11167. }
  11168. }
  11169. }
  11170. needToLoadDTD = false;
  11171. }
  11172. for (int i = 0; i < tokenisedDTD.size(); ++i)
  11173. {
  11174. if (tokenisedDTD[i] == entity)
  11175. {
  11176. if (tokenisedDTD[i - 1].equalsIgnoreCase ("<!entity"))
  11177. {
  11178. String ent (tokenisedDTD [i + 1].trimCharactersAtEnd (">").trim().unquoted());
  11179. // check for sub-entities..
  11180. int ampersand = ent.indexOfChar ('&');
  11181. while (ampersand >= 0)
  11182. {
  11183. const int semiColon = ent.indexOf (i + 1, ";");
  11184. if (semiColon < 0)
  11185. {
  11186. setLastError ("entity without terminating semi-colon", false);
  11187. break;
  11188. }
  11189. const String resolved (expandEntity (ent.substring (i + 1, semiColon)));
  11190. ent = ent.substring (0, ampersand)
  11191. + resolved
  11192. + ent.substring (semiColon + 1);
  11193. ampersand = ent.indexOfChar (semiColon + 1, '&');
  11194. }
  11195. return ent;
  11196. }
  11197. }
  11198. }
  11199. setLastError ("unknown entity", true);
  11200. return entity;
  11201. }
  11202. const String XmlDocument::getParameterEntity (const String& entity)
  11203. {
  11204. for (int i = 0; i < tokenisedDTD.size(); ++i)
  11205. {
  11206. if (tokenisedDTD[i] == entity)
  11207. {
  11208. if (tokenisedDTD [i - 1] == "%"
  11209. && tokenisedDTD [i - 2].equalsIgnoreCase ("<!entity"))
  11210. {
  11211. const String ent (tokenisedDTD [i + 1].trimCharactersAtEnd (">"));
  11212. if (ent.equalsIgnoreCase ("system"))
  11213. return getFileContents (tokenisedDTD [i + 2].trimCharactersAtEnd (">"));
  11214. else
  11215. return ent.trim().unquoted();
  11216. }
  11217. }
  11218. }
  11219. return entity;
  11220. }
  11221. END_JUCE_NAMESPACE
  11222. /*** End of inlined file: juce_XmlDocument.cpp ***/
  11223. /*** Start of inlined file: juce_XmlElement.cpp ***/
  11224. BEGIN_JUCE_NAMESPACE
  11225. XmlElement::XmlAttributeNode::XmlAttributeNode (const XmlAttributeNode& other) throw()
  11226. : name (other.name),
  11227. value (other.value),
  11228. next (0)
  11229. {
  11230. }
  11231. XmlElement::XmlAttributeNode::XmlAttributeNode (const String& name_, const String& value_) throw()
  11232. : name (name_),
  11233. value (value_),
  11234. next (0)
  11235. {
  11236. }
  11237. XmlElement::XmlElement (const String& tagName_) throw()
  11238. : tagName (tagName_),
  11239. firstChildElement (0),
  11240. nextElement (0),
  11241. attributes (0)
  11242. {
  11243. // the tag name mustn't be empty, or it'll look like a text element!
  11244. jassert (tagName_.containsNonWhitespaceChars())
  11245. // The tag can't contain spaces or other characters that would create invalid XML!
  11246. jassert (! tagName_.containsAnyOf (" <>/&"));
  11247. }
  11248. XmlElement::XmlElement (int /*dummy*/) throw()
  11249. : firstChildElement (0),
  11250. nextElement (0),
  11251. attributes (0)
  11252. {
  11253. }
  11254. XmlElement::XmlElement (const XmlElement& other)
  11255. : tagName (other.tagName),
  11256. firstChildElement (0),
  11257. nextElement (0),
  11258. attributes (0)
  11259. {
  11260. copyChildrenAndAttributesFrom (other);
  11261. }
  11262. XmlElement& XmlElement::operator= (const XmlElement& other)
  11263. {
  11264. if (this != &other)
  11265. {
  11266. removeAllAttributes();
  11267. deleteAllChildElements();
  11268. tagName = other.tagName;
  11269. copyChildrenAndAttributesFrom (other);
  11270. }
  11271. return *this;
  11272. }
  11273. void XmlElement::copyChildrenAndAttributesFrom (const XmlElement& other)
  11274. {
  11275. XmlElement* child = other.firstChildElement;
  11276. XmlElement* lastChild = 0;
  11277. while (child != 0)
  11278. {
  11279. XmlElement* const copiedChild = new XmlElement (*child);
  11280. if (lastChild != 0)
  11281. lastChild->nextElement = copiedChild;
  11282. else
  11283. firstChildElement = copiedChild;
  11284. lastChild = copiedChild;
  11285. child = child->nextElement;
  11286. }
  11287. const XmlAttributeNode* att = other.attributes;
  11288. XmlAttributeNode* lastAtt = 0;
  11289. while (att != 0)
  11290. {
  11291. XmlAttributeNode* const newAtt = new XmlAttributeNode (*att);
  11292. if (lastAtt != 0)
  11293. lastAtt->next = newAtt;
  11294. else
  11295. attributes = newAtt;
  11296. lastAtt = newAtt;
  11297. att = att->next;
  11298. }
  11299. }
  11300. XmlElement::~XmlElement() throw()
  11301. {
  11302. XmlElement* child = firstChildElement;
  11303. while (child != 0)
  11304. {
  11305. XmlElement* const nextChild = child->nextElement;
  11306. delete child;
  11307. child = nextChild;
  11308. }
  11309. XmlAttributeNode* att = attributes;
  11310. while (att != 0)
  11311. {
  11312. XmlAttributeNode* const nextAtt = att->next;
  11313. delete att;
  11314. att = nextAtt;
  11315. }
  11316. }
  11317. namespace XmlOutputFunctions
  11318. {
  11319. /*static bool isLegalXmlCharSlow (const juce_wchar character) throw()
  11320. {
  11321. if ((character >= 'a' && character <= 'z')
  11322. || (character >= 'A' && character <= 'Z')
  11323. || (character >= '0' && character <= '9'))
  11324. return true;
  11325. const char* t = " .,;:-()_+=?!'#@[]/\\*%~{}";
  11326. do
  11327. {
  11328. if (((juce_wchar) (uint8) *t) == character)
  11329. return true;
  11330. }
  11331. while (*++t != 0);
  11332. return false;
  11333. }
  11334. static void generateLegalCharConstants()
  11335. {
  11336. uint8 n[32];
  11337. zerostruct (n);
  11338. for (int i = 0; i < 256; ++i)
  11339. if (isLegalXmlCharSlow (i))
  11340. n[i >> 3] |= (1 << (i & 7));
  11341. String s;
  11342. for (int i = 0; i < 32; ++i)
  11343. s << (int) n[i] << ", ";
  11344. DBG (s);
  11345. }*/
  11346. static bool isLegalXmlChar (const uint32 c) throw()
  11347. {
  11348. static const unsigned char legalChars[] = { 0, 0, 0, 0, 171, 255, 255, 175, 255, 255, 255, 191, 254, 255, 255, 111 };
  11349. return c < sizeof (legalChars) * 8
  11350. && (legalChars [c >> 3] & (1 << (c & 7))) != 0;
  11351. }
  11352. static void escapeIllegalXmlChars (OutputStream& outputStream, const String& text, const bool changeNewLines)
  11353. {
  11354. const juce_wchar* t = text;
  11355. for (;;)
  11356. {
  11357. const juce_wchar character = *t++;
  11358. if (character == 0)
  11359. {
  11360. break;
  11361. }
  11362. else if (isLegalXmlChar ((uint32) character))
  11363. {
  11364. outputStream << (char) character;
  11365. }
  11366. else
  11367. {
  11368. switch (character)
  11369. {
  11370. case '&': outputStream << "&amp;"; break;
  11371. case '"': outputStream << "&quot;"; break;
  11372. case '>': outputStream << "&gt;"; break;
  11373. case '<': outputStream << "&lt;"; break;
  11374. case '\n':
  11375. if (changeNewLines)
  11376. outputStream << "&#10;";
  11377. else
  11378. outputStream << (char) character;
  11379. break;
  11380. case '\r':
  11381. if (changeNewLines)
  11382. outputStream << "&#13;";
  11383. else
  11384. outputStream << (char) character;
  11385. break;
  11386. default:
  11387. outputStream << "&#" << ((int) (unsigned int) character) << ';';
  11388. break;
  11389. }
  11390. }
  11391. }
  11392. }
  11393. static void writeSpaces (OutputStream& out, int numSpaces)
  11394. {
  11395. if (numSpaces > 0)
  11396. {
  11397. const char* const blanks = " ";
  11398. const int blankSize = (int) sizeof (blanks) - 1;
  11399. while (numSpaces > blankSize)
  11400. {
  11401. out.write (blanks, blankSize);
  11402. numSpaces -= blankSize;
  11403. }
  11404. out.write (blanks, numSpaces);
  11405. }
  11406. }
  11407. }
  11408. void XmlElement::writeElementAsText (OutputStream& outputStream,
  11409. const int indentationLevel,
  11410. const int lineWrapLength) const
  11411. {
  11412. using namespace XmlOutputFunctions;
  11413. writeSpaces (outputStream, indentationLevel);
  11414. if (! isTextElement())
  11415. {
  11416. outputStream.writeByte ('<');
  11417. outputStream << tagName;
  11418. const int attIndent = indentationLevel + tagName.length() + 1;
  11419. int lineLen = 0;
  11420. const XmlAttributeNode* att = attributes;
  11421. while (att != 0)
  11422. {
  11423. if (lineLen > lineWrapLength && indentationLevel >= 0)
  11424. {
  11425. outputStream.write ("\r\n", 2);
  11426. writeSpaces (outputStream, attIndent);
  11427. lineLen = 0;
  11428. }
  11429. const int64 startPos = outputStream.getPosition();
  11430. outputStream.writeByte (' ');
  11431. outputStream << att->name;
  11432. outputStream.write ("=\"", 2);
  11433. escapeIllegalXmlChars (outputStream, att->value, true);
  11434. outputStream.writeByte ('"');
  11435. lineLen += (int) (outputStream.getPosition() - startPos);
  11436. att = att->next;
  11437. }
  11438. if (firstChildElement != 0)
  11439. {
  11440. XmlElement* child = firstChildElement;
  11441. if (child->nextElement == 0 && child->isTextElement())
  11442. {
  11443. outputStream.writeByte ('>');
  11444. escapeIllegalXmlChars (outputStream, child->getText(), false);
  11445. }
  11446. else
  11447. {
  11448. if (indentationLevel >= 0)
  11449. outputStream.write (">\r\n", 3);
  11450. else
  11451. outputStream.writeByte ('>');
  11452. bool lastWasTextNode = false;
  11453. while (child != 0)
  11454. {
  11455. if (child->isTextElement())
  11456. {
  11457. if ((! lastWasTextNode) && (indentationLevel >= 0))
  11458. writeSpaces (outputStream, indentationLevel + 2);
  11459. escapeIllegalXmlChars (outputStream, child->getText(), false);
  11460. lastWasTextNode = true;
  11461. }
  11462. else
  11463. {
  11464. if (indentationLevel >= 0)
  11465. {
  11466. if (lastWasTextNode)
  11467. outputStream.write ("\r\n", 2);
  11468. child->writeElementAsText (outputStream, indentationLevel + 2, lineWrapLength);
  11469. }
  11470. else
  11471. {
  11472. child->writeElementAsText (outputStream, indentationLevel, lineWrapLength);
  11473. }
  11474. lastWasTextNode = false;
  11475. }
  11476. child = child->nextElement;
  11477. }
  11478. if (indentationLevel >= 0)
  11479. {
  11480. if (lastWasTextNode)
  11481. outputStream.write ("\r\n", 2);
  11482. writeSpaces (outputStream, indentationLevel);
  11483. }
  11484. }
  11485. outputStream.write ("</", 2);
  11486. outputStream << tagName;
  11487. if (indentationLevel >= 0)
  11488. outputStream.write (">\r\n", 3);
  11489. else
  11490. outputStream.writeByte ('>');
  11491. }
  11492. else
  11493. {
  11494. if (indentationLevel >= 0)
  11495. outputStream.write ("/>\r\n", 4);
  11496. else
  11497. outputStream.write ("/>", 2);
  11498. }
  11499. }
  11500. else
  11501. {
  11502. if (indentationLevel >= 0)
  11503. writeSpaces (outputStream, indentationLevel + 2);
  11504. escapeIllegalXmlChars (outputStream, getText(), false);
  11505. }
  11506. }
  11507. const String XmlElement::createDocument (const String& dtdToUse,
  11508. const bool allOnOneLine,
  11509. const bool includeXmlHeader,
  11510. const String& encodingType,
  11511. const int lineWrapLength) const
  11512. {
  11513. MemoryOutputStream mem (2048, 4096);
  11514. writeToStream (mem, dtdToUse, allOnOneLine, includeXmlHeader, encodingType, lineWrapLength);
  11515. return mem.toUTF8();
  11516. }
  11517. void XmlElement::writeToStream (OutputStream& output,
  11518. const String& dtdToUse,
  11519. const bool allOnOneLine,
  11520. const bool includeXmlHeader,
  11521. const String& encodingType,
  11522. const int lineWrapLength) const
  11523. {
  11524. if (includeXmlHeader)
  11525. output << "<?xml version=\"1.0\" encoding=\"" << encodingType
  11526. << (allOnOneLine ? "\"?> " : "\"?>\r\n\r\n");
  11527. if (dtdToUse.isNotEmpty())
  11528. output << dtdToUse << (allOnOneLine ? " " : "\r\n");
  11529. writeElementAsText (output, allOnOneLine ? -1 : 0, lineWrapLength);
  11530. }
  11531. bool XmlElement::writeToFile (const File& file,
  11532. const String& dtdToUse,
  11533. const String& encodingType,
  11534. const int lineWrapLength) const
  11535. {
  11536. if (file.hasWriteAccess())
  11537. {
  11538. TemporaryFile tempFile (file);
  11539. ScopedPointer <FileOutputStream> out (tempFile.getFile().createOutputStream());
  11540. if (out != 0)
  11541. {
  11542. writeToStream (*out, dtdToUse, false, true, encodingType, lineWrapLength);
  11543. out = 0;
  11544. return tempFile.overwriteTargetFileWithTemporary();
  11545. }
  11546. }
  11547. return false;
  11548. }
  11549. bool XmlElement::hasTagName (const String& tagNameWanted) const throw()
  11550. {
  11551. #if JUCE_DEBUG
  11552. // if debugging, check that the case is actually the same, because
  11553. // valid xml is case-sensitive, and although this lets it pass, it's
  11554. // better not to..
  11555. if (tagName.equalsIgnoreCase (tagNameWanted))
  11556. {
  11557. jassert (tagName == tagNameWanted);
  11558. return true;
  11559. }
  11560. else
  11561. {
  11562. return false;
  11563. }
  11564. #else
  11565. return tagName.equalsIgnoreCase (tagNameWanted);
  11566. #endif
  11567. }
  11568. XmlElement* XmlElement::getNextElementWithTagName (const String& requiredTagName) const
  11569. {
  11570. XmlElement* e = nextElement;
  11571. while (e != 0 && ! e->hasTagName (requiredTagName))
  11572. e = e->nextElement;
  11573. return e;
  11574. }
  11575. int XmlElement::getNumAttributes() const throw()
  11576. {
  11577. const XmlAttributeNode* att = attributes;
  11578. int count = 0;
  11579. while (att != 0)
  11580. {
  11581. att = att->next;
  11582. ++count;
  11583. }
  11584. return count;
  11585. }
  11586. const String& XmlElement::getAttributeName (const int index) const throw()
  11587. {
  11588. const XmlAttributeNode* att = attributes;
  11589. int count = 0;
  11590. while (att != 0)
  11591. {
  11592. if (count == index)
  11593. return att->name;
  11594. att = att->next;
  11595. ++count;
  11596. }
  11597. return String::empty;
  11598. }
  11599. const String& XmlElement::getAttributeValue (const int index) const throw()
  11600. {
  11601. const XmlAttributeNode* att = attributes;
  11602. int count = 0;
  11603. while (att != 0)
  11604. {
  11605. if (count == index)
  11606. return att->value;
  11607. att = att->next;
  11608. ++count;
  11609. }
  11610. return String::empty;
  11611. }
  11612. bool XmlElement::hasAttribute (const String& attributeName) const throw()
  11613. {
  11614. const XmlAttributeNode* att = attributes;
  11615. while (att != 0)
  11616. {
  11617. if (att->name.equalsIgnoreCase (attributeName))
  11618. return true;
  11619. att = att->next;
  11620. }
  11621. return false;
  11622. }
  11623. const String& XmlElement::getStringAttribute (const String& attributeName) const throw()
  11624. {
  11625. const XmlAttributeNode* att = attributes;
  11626. while (att != 0)
  11627. {
  11628. if (att->name.equalsIgnoreCase (attributeName))
  11629. return att->value;
  11630. att = att->next;
  11631. }
  11632. return String::empty;
  11633. }
  11634. const String XmlElement::getStringAttribute (const String& attributeName, const String& defaultReturnValue) const
  11635. {
  11636. const XmlAttributeNode* att = attributes;
  11637. while (att != 0)
  11638. {
  11639. if (att->name.equalsIgnoreCase (attributeName))
  11640. return att->value;
  11641. att = att->next;
  11642. }
  11643. return defaultReturnValue;
  11644. }
  11645. int XmlElement::getIntAttribute (const String& attributeName, const int defaultReturnValue) const
  11646. {
  11647. const XmlAttributeNode* att = attributes;
  11648. while (att != 0)
  11649. {
  11650. if (att->name.equalsIgnoreCase (attributeName))
  11651. return att->value.getIntValue();
  11652. att = att->next;
  11653. }
  11654. return defaultReturnValue;
  11655. }
  11656. double XmlElement::getDoubleAttribute (const String& attributeName, const double defaultReturnValue) const
  11657. {
  11658. const XmlAttributeNode* att = attributes;
  11659. while (att != 0)
  11660. {
  11661. if (att->name.equalsIgnoreCase (attributeName))
  11662. return att->value.getDoubleValue();
  11663. att = att->next;
  11664. }
  11665. return defaultReturnValue;
  11666. }
  11667. bool XmlElement::getBoolAttribute (const String& attributeName, const bool defaultReturnValue) const
  11668. {
  11669. const XmlAttributeNode* att = attributes;
  11670. while (att != 0)
  11671. {
  11672. if (att->name.equalsIgnoreCase (attributeName))
  11673. {
  11674. juce_wchar firstChar = att->value[0];
  11675. if (CharacterFunctions::isWhitespace (firstChar))
  11676. firstChar = att->value.trimStart() [0];
  11677. return firstChar == '1'
  11678. || firstChar == 't'
  11679. || firstChar == 'y'
  11680. || firstChar == 'T'
  11681. || firstChar == 'Y';
  11682. }
  11683. att = att->next;
  11684. }
  11685. return defaultReturnValue;
  11686. }
  11687. bool XmlElement::compareAttribute (const String& attributeName,
  11688. const String& stringToCompareAgainst,
  11689. const bool ignoreCase) const throw()
  11690. {
  11691. const XmlAttributeNode* att = attributes;
  11692. while (att != 0)
  11693. {
  11694. if (att->name.equalsIgnoreCase (attributeName))
  11695. {
  11696. if (ignoreCase)
  11697. return att->value.equalsIgnoreCase (stringToCompareAgainst);
  11698. else
  11699. return att->value == stringToCompareAgainst;
  11700. }
  11701. att = att->next;
  11702. }
  11703. return false;
  11704. }
  11705. void XmlElement::setAttribute (const String& attributeName, const String& value)
  11706. {
  11707. #if JUCE_DEBUG
  11708. // check the identifier being passed in is legal..
  11709. const juce_wchar* t = attributeName;
  11710. while (*t != 0)
  11711. {
  11712. jassert (CharacterFunctions::isLetterOrDigit (*t)
  11713. || *t == '_'
  11714. || *t == '-'
  11715. || *t == ':');
  11716. ++t;
  11717. }
  11718. #endif
  11719. if (attributes == 0)
  11720. {
  11721. attributes = new XmlAttributeNode (attributeName, value);
  11722. }
  11723. else
  11724. {
  11725. XmlAttributeNode* att = attributes;
  11726. for (;;)
  11727. {
  11728. if (att->name.equalsIgnoreCase (attributeName))
  11729. {
  11730. att->value = value;
  11731. break;
  11732. }
  11733. else if (att->next == 0)
  11734. {
  11735. att->next = new XmlAttributeNode (attributeName, value);
  11736. break;
  11737. }
  11738. att = att->next;
  11739. }
  11740. }
  11741. }
  11742. void XmlElement::setAttribute (const String& attributeName, const int number)
  11743. {
  11744. setAttribute (attributeName, String (number));
  11745. }
  11746. void XmlElement::setAttribute (const String& attributeName, const double number)
  11747. {
  11748. setAttribute (attributeName, String (number));
  11749. }
  11750. void XmlElement::removeAttribute (const String& attributeName) throw()
  11751. {
  11752. XmlAttributeNode* att = attributes;
  11753. XmlAttributeNode* lastAtt = 0;
  11754. while (att != 0)
  11755. {
  11756. if (att->name.equalsIgnoreCase (attributeName))
  11757. {
  11758. if (lastAtt == 0)
  11759. attributes = att->next;
  11760. else
  11761. lastAtt->next = att->next;
  11762. delete att;
  11763. break;
  11764. }
  11765. lastAtt = att;
  11766. att = att->next;
  11767. }
  11768. }
  11769. void XmlElement::removeAllAttributes() throw()
  11770. {
  11771. while (attributes != 0)
  11772. {
  11773. XmlAttributeNode* const nextAtt = attributes->next;
  11774. delete attributes;
  11775. attributes = nextAtt;
  11776. }
  11777. }
  11778. int XmlElement::getNumChildElements() const throw()
  11779. {
  11780. int count = 0;
  11781. const XmlElement* child = firstChildElement;
  11782. while (child != 0)
  11783. {
  11784. ++count;
  11785. child = child->nextElement;
  11786. }
  11787. return count;
  11788. }
  11789. XmlElement* XmlElement::getChildElement (const int index) const throw()
  11790. {
  11791. int count = 0;
  11792. XmlElement* child = firstChildElement;
  11793. while (child != 0 && count < index)
  11794. {
  11795. child = child->nextElement;
  11796. ++count;
  11797. }
  11798. return child;
  11799. }
  11800. XmlElement* XmlElement::getChildByName (const String& childName) const throw()
  11801. {
  11802. XmlElement* child = firstChildElement;
  11803. while (child != 0)
  11804. {
  11805. if (child->hasTagName (childName))
  11806. break;
  11807. child = child->nextElement;
  11808. }
  11809. return child;
  11810. }
  11811. void XmlElement::addChildElement (XmlElement* const newNode) throw()
  11812. {
  11813. if (newNode != 0)
  11814. {
  11815. if (firstChildElement == 0)
  11816. {
  11817. firstChildElement = newNode;
  11818. }
  11819. else
  11820. {
  11821. XmlElement* child = firstChildElement;
  11822. while (child->nextElement != 0)
  11823. child = child->nextElement;
  11824. child->nextElement = newNode;
  11825. // if this is non-zero, then something's probably
  11826. // gone wrong..
  11827. jassert (newNode->nextElement == 0);
  11828. }
  11829. }
  11830. }
  11831. void XmlElement::insertChildElement (XmlElement* const newNode,
  11832. int indexToInsertAt) throw()
  11833. {
  11834. if (newNode != 0)
  11835. {
  11836. removeChildElement (newNode, false);
  11837. if (indexToInsertAt == 0)
  11838. {
  11839. newNode->nextElement = firstChildElement;
  11840. firstChildElement = newNode;
  11841. }
  11842. else
  11843. {
  11844. if (firstChildElement == 0)
  11845. {
  11846. firstChildElement = newNode;
  11847. }
  11848. else
  11849. {
  11850. if (indexToInsertAt < 0)
  11851. indexToInsertAt = std::numeric_limits<int>::max();
  11852. XmlElement* child = firstChildElement;
  11853. while (child->nextElement != 0 && --indexToInsertAt > 0)
  11854. child = child->nextElement;
  11855. newNode->nextElement = child->nextElement;
  11856. child->nextElement = newNode;
  11857. }
  11858. }
  11859. }
  11860. }
  11861. XmlElement* XmlElement::createNewChildElement (const String& childTagName)
  11862. {
  11863. XmlElement* const newElement = new XmlElement (childTagName);
  11864. addChildElement (newElement);
  11865. return newElement;
  11866. }
  11867. bool XmlElement::replaceChildElement (XmlElement* const currentChildElement,
  11868. XmlElement* const newNode) throw()
  11869. {
  11870. if (newNode != 0)
  11871. {
  11872. XmlElement* child = firstChildElement;
  11873. XmlElement* previousNode = 0;
  11874. while (child != 0)
  11875. {
  11876. if (child == currentChildElement)
  11877. {
  11878. if (child != newNode)
  11879. {
  11880. if (previousNode == 0)
  11881. firstChildElement = newNode;
  11882. else
  11883. previousNode->nextElement = newNode;
  11884. newNode->nextElement = child->nextElement;
  11885. delete child;
  11886. }
  11887. return true;
  11888. }
  11889. previousNode = child;
  11890. child = child->nextElement;
  11891. }
  11892. }
  11893. return false;
  11894. }
  11895. void XmlElement::removeChildElement (XmlElement* const childToRemove,
  11896. const bool shouldDeleteTheChild) throw()
  11897. {
  11898. if (childToRemove != 0)
  11899. {
  11900. if (firstChildElement == childToRemove)
  11901. {
  11902. firstChildElement = childToRemove->nextElement;
  11903. childToRemove->nextElement = 0;
  11904. }
  11905. else
  11906. {
  11907. XmlElement* child = firstChildElement;
  11908. XmlElement* last = 0;
  11909. while (child != 0)
  11910. {
  11911. if (child == childToRemove)
  11912. {
  11913. if (last == 0)
  11914. firstChildElement = child->nextElement;
  11915. else
  11916. last->nextElement = child->nextElement;
  11917. childToRemove->nextElement = 0;
  11918. break;
  11919. }
  11920. last = child;
  11921. child = child->nextElement;
  11922. }
  11923. }
  11924. if (shouldDeleteTheChild)
  11925. delete childToRemove;
  11926. }
  11927. }
  11928. bool XmlElement::isEquivalentTo (const XmlElement* const other,
  11929. const bool ignoreOrderOfAttributes) const throw()
  11930. {
  11931. if (this != other)
  11932. {
  11933. if (other == 0 || tagName != other->tagName)
  11934. {
  11935. return false;
  11936. }
  11937. if (ignoreOrderOfAttributes)
  11938. {
  11939. int totalAtts = 0;
  11940. const XmlAttributeNode* att = attributes;
  11941. while (att != 0)
  11942. {
  11943. if (! other->compareAttribute (att->name, att->value))
  11944. return false;
  11945. att = att->next;
  11946. ++totalAtts;
  11947. }
  11948. if (totalAtts != other->getNumAttributes())
  11949. return false;
  11950. }
  11951. else
  11952. {
  11953. const XmlAttributeNode* thisAtt = attributes;
  11954. const XmlAttributeNode* otherAtt = other->attributes;
  11955. for (;;)
  11956. {
  11957. if (thisAtt == 0 || otherAtt == 0)
  11958. {
  11959. if (thisAtt == otherAtt) // both 0, so it's a match
  11960. break;
  11961. return false;
  11962. }
  11963. if (thisAtt->name != otherAtt->name
  11964. || thisAtt->value != otherAtt->value)
  11965. {
  11966. return false;
  11967. }
  11968. thisAtt = thisAtt->next;
  11969. otherAtt = otherAtt->next;
  11970. }
  11971. }
  11972. const XmlElement* thisChild = firstChildElement;
  11973. const XmlElement* otherChild = other->firstChildElement;
  11974. for (;;)
  11975. {
  11976. if (thisChild == 0 || otherChild == 0)
  11977. {
  11978. if (thisChild == otherChild) // both 0, so it's a match
  11979. break;
  11980. return false;
  11981. }
  11982. if (! thisChild->isEquivalentTo (otherChild, ignoreOrderOfAttributes))
  11983. return false;
  11984. thisChild = thisChild->nextElement;
  11985. otherChild = otherChild->nextElement;
  11986. }
  11987. }
  11988. return true;
  11989. }
  11990. void XmlElement::deleteAllChildElements() throw()
  11991. {
  11992. while (firstChildElement != 0)
  11993. {
  11994. XmlElement* const nextChild = firstChildElement->nextElement;
  11995. delete firstChildElement;
  11996. firstChildElement = nextChild;
  11997. }
  11998. }
  11999. void XmlElement::deleteAllChildElementsWithTagName (const String& name) throw()
  12000. {
  12001. XmlElement* child = firstChildElement;
  12002. while (child != 0)
  12003. {
  12004. if (child->hasTagName (name))
  12005. {
  12006. XmlElement* const nextChild = child->nextElement;
  12007. removeChildElement (child, true);
  12008. child = nextChild;
  12009. }
  12010. else
  12011. {
  12012. child = child->nextElement;
  12013. }
  12014. }
  12015. }
  12016. bool XmlElement::containsChildElement (const XmlElement* const possibleChild) const throw()
  12017. {
  12018. const XmlElement* child = firstChildElement;
  12019. while (child != 0)
  12020. {
  12021. if (child == possibleChild)
  12022. return true;
  12023. child = child->nextElement;
  12024. }
  12025. return false;
  12026. }
  12027. XmlElement* XmlElement::findParentElementOf (const XmlElement* const elementToLookFor) throw()
  12028. {
  12029. if (this == elementToLookFor || elementToLookFor == 0)
  12030. return 0;
  12031. XmlElement* child = firstChildElement;
  12032. while (child != 0)
  12033. {
  12034. if (elementToLookFor == child)
  12035. return this;
  12036. XmlElement* const found = child->findParentElementOf (elementToLookFor);
  12037. if (found != 0)
  12038. return found;
  12039. child = child->nextElement;
  12040. }
  12041. return 0;
  12042. }
  12043. void XmlElement::getChildElementsAsArray (XmlElement** elems) const throw()
  12044. {
  12045. XmlElement* e = firstChildElement;
  12046. while (e != 0)
  12047. {
  12048. *elems++ = e;
  12049. e = e->nextElement;
  12050. }
  12051. }
  12052. void XmlElement::reorderChildElements (XmlElement** const elems, const int num) throw()
  12053. {
  12054. XmlElement* e = firstChildElement = elems[0];
  12055. for (int i = 1; i < num; ++i)
  12056. {
  12057. e->nextElement = elems[i];
  12058. e = e->nextElement;
  12059. }
  12060. e->nextElement = 0;
  12061. }
  12062. bool XmlElement::isTextElement() const throw()
  12063. {
  12064. return tagName.isEmpty();
  12065. }
  12066. static const juce_wchar* const juce_xmltextContentAttributeName = L"text";
  12067. const String& XmlElement::getText() const throw()
  12068. {
  12069. jassert (isTextElement()); // you're trying to get the text from an element that
  12070. // isn't actually a text element.. If this contains text sub-nodes, you
  12071. // probably want to use getAllSubText instead.
  12072. return getStringAttribute (juce_xmltextContentAttributeName);
  12073. }
  12074. void XmlElement::setText (const String& newText)
  12075. {
  12076. if (isTextElement())
  12077. setAttribute (juce_xmltextContentAttributeName, newText);
  12078. else
  12079. jassertfalse; // you can only change the text in a text element, not a normal one.
  12080. }
  12081. const String XmlElement::getAllSubText() const
  12082. {
  12083. String result;
  12084. String::Concatenator concatenator (result);
  12085. const XmlElement* child = firstChildElement;
  12086. while (child != 0)
  12087. {
  12088. if (child->isTextElement())
  12089. concatenator.append (child->getText());
  12090. child = child->nextElement;
  12091. }
  12092. return result;
  12093. }
  12094. const String XmlElement::getChildElementAllSubText (const String& childTagName,
  12095. const String& defaultReturnValue) const
  12096. {
  12097. const XmlElement* const child = getChildByName (childTagName);
  12098. if (child != 0)
  12099. return child->getAllSubText();
  12100. return defaultReturnValue;
  12101. }
  12102. XmlElement* XmlElement::createTextElement (const String& text)
  12103. {
  12104. XmlElement* const e = new XmlElement ((int) 0);
  12105. e->setAttribute (juce_xmltextContentAttributeName, text);
  12106. return e;
  12107. }
  12108. void XmlElement::addTextElement (const String& text)
  12109. {
  12110. addChildElement (createTextElement (text));
  12111. }
  12112. void XmlElement::deleteAllTextElements() throw()
  12113. {
  12114. XmlElement* child = firstChildElement;
  12115. while (child != 0)
  12116. {
  12117. XmlElement* const next = child->nextElement;
  12118. if (child->isTextElement())
  12119. removeChildElement (child, true);
  12120. child = next;
  12121. }
  12122. }
  12123. END_JUCE_NAMESPACE
  12124. /*** End of inlined file: juce_XmlElement.cpp ***/
  12125. /*** Start of inlined file: juce_ReadWriteLock.cpp ***/
  12126. BEGIN_JUCE_NAMESPACE
  12127. ReadWriteLock::ReadWriteLock() throw()
  12128. : numWaitingWriters (0),
  12129. numWriters (0),
  12130. writerThreadId (0)
  12131. {
  12132. }
  12133. ReadWriteLock::~ReadWriteLock() throw()
  12134. {
  12135. jassert (readerThreads.size() == 0);
  12136. jassert (numWriters == 0);
  12137. }
  12138. void ReadWriteLock::enterRead() const throw()
  12139. {
  12140. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12141. const ScopedLock sl (accessLock);
  12142. for (;;)
  12143. {
  12144. jassert (readerThreads.size() % 2 == 0);
  12145. int i;
  12146. for (i = 0; i < readerThreads.size(); i += 2)
  12147. if (readerThreads.getUnchecked(i) == threadId)
  12148. break;
  12149. if (i < readerThreads.size()
  12150. || numWriters + numWaitingWriters == 0
  12151. || (threadId == writerThreadId && numWriters > 0))
  12152. {
  12153. if (i < readerThreads.size())
  12154. {
  12155. readerThreads.set (i + 1, (Thread::ThreadID) (1 + (pointer_sized_int) readerThreads.getUnchecked (i + 1)));
  12156. }
  12157. else
  12158. {
  12159. readerThreads.add (threadId);
  12160. readerThreads.add ((Thread::ThreadID) 1);
  12161. }
  12162. return;
  12163. }
  12164. const ScopedUnlock ul (accessLock);
  12165. waitEvent.wait (100);
  12166. }
  12167. }
  12168. void ReadWriteLock::exitRead() const throw()
  12169. {
  12170. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12171. const ScopedLock sl (accessLock);
  12172. for (int i = 0; i < readerThreads.size(); i += 2)
  12173. {
  12174. if (readerThreads.getUnchecked(i) == threadId)
  12175. {
  12176. const pointer_sized_int newCount = ((pointer_sized_int) readerThreads.getUnchecked (i + 1)) - 1;
  12177. if (newCount == 0)
  12178. {
  12179. readerThreads.removeRange (i, 2);
  12180. waitEvent.signal();
  12181. }
  12182. else
  12183. {
  12184. readerThreads.set (i + 1, (Thread::ThreadID) newCount);
  12185. }
  12186. return;
  12187. }
  12188. }
  12189. jassertfalse; // unlocking a lock that wasn't locked..
  12190. }
  12191. void ReadWriteLock::enterWrite() const throw()
  12192. {
  12193. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12194. const ScopedLock sl (accessLock);
  12195. for (;;)
  12196. {
  12197. if (readerThreads.size() + numWriters == 0
  12198. || threadId == writerThreadId
  12199. || (readerThreads.size() == 2
  12200. && readerThreads.getUnchecked(0) == threadId))
  12201. {
  12202. writerThreadId = threadId;
  12203. ++numWriters;
  12204. break;
  12205. }
  12206. ++numWaitingWriters;
  12207. accessLock.exit();
  12208. waitEvent.wait (100);
  12209. accessLock.enter();
  12210. --numWaitingWriters;
  12211. }
  12212. }
  12213. bool ReadWriteLock::tryEnterWrite() const throw()
  12214. {
  12215. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12216. const ScopedLock sl (accessLock);
  12217. if (readerThreads.size() + numWriters == 0
  12218. || threadId == writerThreadId
  12219. || (readerThreads.size() == 2
  12220. && readerThreads.getUnchecked(0) == threadId))
  12221. {
  12222. writerThreadId = threadId;
  12223. ++numWriters;
  12224. return true;
  12225. }
  12226. return false;
  12227. }
  12228. void ReadWriteLock::exitWrite() const throw()
  12229. {
  12230. const ScopedLock sl (accessLock);
  12231. // check this thread actually had the lock..
  12232. jassert (numWriters > 0 && writerThreadId == Thread::getCurrentThreadId());
  12233. if (--numWriters == 0)
  12234. {
  12235. writerThreadId = 0;
  12236. waitEvent.signal();
  12237. }
  12238. }
  12239. END_JUCE_NAMESPACE
  12240. /*** End of inlined file: juce_ReadWriteLock.cpp ***/
  12241. /*** Start of inlined file: juce_Thread.cpp ***/
  12242. BEGIN_JUCE_NAMESPACE
  12243. // these functions are implemented in the platform-specific code.
  12244. void* juce_createThread (void* userData);
  12245. void juce_killThread (void* handle);
  12246. bool juce_setThreadPriority (void* handle, int priority);
  12247. void juce_setCurrentThreadName (const String& name);
  12248. #if JUCE_WINDOWS
  12249. void juce_CloseThreadHandle (void* handle);
  12250. #endif
  12251. void Thread::threadEntryPoint (Thread* const thread)
  12252. {
  12253. {
  12254. const ScopedLock sl (runningThreadsLock);
  12255. runningThreads.add (thread);
  12256. }
  12257. JUCE_TRY
  12258. {
  12259. thread->threadId_ = Thread::getCurrentThreadId();
  12260. if (thread->threadName_.isNotEmpty())
  12261. juce_setCurrentThreadName (thread->threadName_);
  12262. if (thread->startSuspensionEvent_.wait (10000))
  12263. {
  12264. if (thread->affinityMask_ != 0)
  12265. setCurrentThreadAffinityMask (thread->affinityMask_);
  12266. thread->run();
  12267. }
  12268. }
  12269. JUCE_CATCH_ALL_ASSERT
  12270. {
  12271. const ScopedLock sl (runningThreadsLock);
  12272. jassert (runningThreads.contains (thread));
  12273. runningThreads.removeValue (thread);
  12274. }
  12275. #if JUCE_WINDOWS
  12276. juce_CloseThreadHandle (thread->threadHandle_);
  12277. #endif
  12278. thread->threadHandle_ = 0;
  12279. thread->threadId_ = 0;
  12280. }
  12281. // used to wrap the incoming call from the platform-specific code
  12282. void JUCE_API juce_threadEntryPoint (void* userData)
  12283. {
  12284. Thread::threadEntryPoint (static_cast <Thread*> (userData));
  12285. }
  12286. Thread::Thread (const String& threadName)
  12287. : threadName_ (threadName),
  12288. threadHandle_ (0),
  12289. threadPriority_ (5),
  12290. threadId_ (0),
  12291. affinityMask_ (0),
  12292. threadShouldExit_ (false)
  12293. {
  12294. }
  12295. Thread::~Thread()
  12296. {
  12297. stopThread (100);
  12298. }
  12299. void Thread::startThread()
  12300. {
  12301. const ScopedLock sl (startStopLock);
  12302. threadShouldExit_ = false;
  12303. if (threadHandle_ == 0)
  12304. {
  12305. threadHandle_ = juce_createThread (this);
  12306. juce_setThreadPriority (threadHandle_, threadPriority_);
  12307. startSuspensionEvent_.signal();
  12308. }
  12309. }
  12310. void Thread::startThread (const int priority)
  12311. {
  12312. const ScopedLock sl (startStopLock);
  12313. if (threadHandle_ == 0)
  12314. {
  12315. threadPriority_ = priority;
  12316. startThread();
  12317. }
  12318. else
  12319. {
  12320. setPriority (priority);
  12321. }
  12322. }
  12323. bool Thread::isThreadRunning() const
  12324. {
  12325. return threadHandle_ != 0;
  12326. }
  12327. void Thread::signalThreadShouldExit()
  12328. {
  12329. threadShouldExit_ = true;
  12330. }
  12331. bool Thread::waitForThreadToExit (const int timeOutMilliseconds) const
  12332. {
  12333. // Doh! So how exactly do you expect this thread to wait for itself to stop??
  12334. jassert (getThreadId() != getCurrentThreadId());
  12335. const int sleepMsPerIteration = 5;
  12336. int count = timeOutMilliseconds / sleepMsPerIteration;
  12337. while (isThreadRunning())
  12338. {
  12339. if (timeOutMilliseconds > 0 && --count < 0)
  12340. return false;
  12341. sleep (sleepMsPerIteration);
  12342. }
  12343. return true;
  12344. }
  12345. void Thread::stopThread (const int timeOutMilliseconds)
  12346. {
  12347. // agh! You can't stop the thread that's calling this method! How on earth
  12348. // would that work??
  12349. jassert (getCurrentThreadId() != getThreadId());
  12350. const ScopedLock sl (startStopLock);
  12351. if (isThreadRunning())
  12352. {
  12353. signalThreadShouldExit();
  12354. notify();
  12355. if (timeOutMilliseconds != 0)
  12356. waitForThreadToExit (timeOutMilliseconds);
  12357. if (isThreadRunning())
  12358. {
  12359. // very bad karma if this point is reached, as
  12360. // there are bound to be locks and events left in
  12361. // silly states when a thread is killed by force..
  12362. jassertfalse;
  12363. Logger::writeToLog ("!! killing thread by force !!");
  12364. juce_killThread (threadHandle_);
  12365. threadHandle_ = 0;
  12366. threadId_ = 0;
  12367. const ScopedLock sl2 (runningThreadsLock);
  12368. runningThreads.removeValue (this);
  12369. }
  12370. }
  12371. }
  12372. bool Thread::setPriority (const int priority)
  12373. {
  12374. const ScopedLock sl (startStopLock);
  12375. const bool worked = juce_setThreadPriority (threadHandle_, priority);
  12376. if (worked)
  12377. threadPriority_ = priority;
  12378. return worked;
  12379. }
  12380. bool Thread::setCurrentThreadPriority (const int priority)
  12381. {
  12382. return juce_setThreadPriority (0, priority);
  12383. }
  12384. void Thread::setAffinityMask (const uint32 affinityMask)
  12385. {
  12386. affinityMask_ = affinityMask;
  12387. }
  12388. bool Thread::wait (const int timeOutMilliseconds) const
  12389. {
  12390. return defaultEvent_.wait (timeOutMilliseconds);
  12391. }
  12392. void Thread::notify() const
  12393. {
  12394. defaultEvent_.signal();
  12395. }
  12396. int Thread::getNumRunningThreads()
  12397. {
  12398. return runningThreads.size();
  12399. }
  12400. Thread* Thread::getCurrentThread()
  12401. {
  12402. const ThreadID thisId = getCurrentThreadId();
  12403. const ScopedLock sl (runningThreadsLock);
  12404. for (int i = runningThreads.size(); --i >= 0;)
  12405. {
  12406. Thread* const t = runningThreads.getUnchecked(i);
  12407. if (t->threadId_ == thisId)
  12408. return t;
  12409. }
  12410. return 0;
  12411. }
  12412. void Thread::stopAllThreads (const int timeOutMilliseconds)
  12413. {
  12414. {
  12415. const ScopedLock sl (runningThreadsLock);
  12416. for (int i = runningThreads.size(); --i >= 0;)
  12417. runningThreads.getUnchecked(i)->signalThreadShouldExit();
  12418. }
  12419. for (;;)
  12420. {
  12421. Thread* firstThread;
  12422. {
  12423. const ScopedLock sl (runningThreadsLock);
  12424. firstThread = runningThreads.getFirst();
  12425. }
  12426. if (firstThread == 0)
  12427. break;
  12428. firstThread->stopThread (timeOutMilliseconds);
  12429. }
  12430. }
  12431. Array<Thread*> Thread::runningThreads;
  12432. CriticalSection Thread::runningThreadsLock;
  12433. END_JUCE_NAMESPACE
  12434. /*** End of inlined file: juce_Thread.cpp ***/
  12435. /*** Start of inlined file: juce_ThreadPool.cpp ***/
  12436. BEGIN_JUCE_NAMESPACE
  12437. ThreadPoolJob::ThreadPoolJob (const String& name)
  12438. : jobName (name),
  12439. pool (0),
  12440. shouldStop (false),
  12441. isActive (false),
  12442. shouldBeDeleted (false)
  12443. {
  12444. }
  12445. ThreadPoolJob::~ThreadPoolJob()
  12446. {
  12447. // you mustn't delete a job while it's still in a pool! Use ThreadPool::removeJob()
  12448. // to remove it first!
  12449. jassert (pool == 0 || ! pool->contains (this));
  12450. }
  12451. const String ThreadPoolJob::getJobName() const
  12452. {
  12453. return jobName;
  12454. }
  12455. void ThreadPoolJob::setJobName (const String& newName)
  12456. {
  12457. jobName = newName;
  12458. }
  12459. void ThreadPoolJob::signalJobShouldExit()
  12460. {
  12461. shouldStop = true;
  12462. }
  12463. class ThreadPool::ThreadPoolThread : public Thread
  12464. {
  12465. public:
  12466. ThreadPoolThread (ThreadPool& pool_)
  12467. : Thread ("Pool"),
  12468. pool (pool_),
  12469. busy (false)
  12470. {
  12471. }
  12472. ~ThreadPoolThread()
  12473. {
  12474. }
  12475. void run()
  12476. {
  12477. while (! threadShouldExit())
  12478. {
  12479. if (! pool.runNextJob())
  12480. wait (500);
  12481. }
  12482. }
  12483. private:
  12484. ThreadPool& pool;
  12485. bool volatile busy;
  12486. ThreadPoolThread (const ThreadPoolThread&);
  12487. ThreadPoolThread& operator= (const ThreadPoolThread&);
  12488. };
  12489. ThreadPool::ThreadPool (const int numThreads,
  12490. const bool startThreadsOnlyWhenNeeded,
  12491. const int stopThreadsWhenNotUsedTimeoutMs)
  12492. : threadStopTimeout (stopThreadsWhenNotUsedTimeoutMs),
  12493. priority (5)
  12494. {
  12495. jassert (numThreads > 0); // not much point having one of these with no threads in it.
  12496. for (int i = jmax (1, numThreads); --i >= 0;)
  12497. threads.add (new ThreadPoolThread (*this));
  12498. if (! startThreadsOnlyWhenNeeded)
  12499. for (int i = threads.size(); --i >= 0;)
  12500. threads.getUnchecked(i)->startThread (priority);
  12501. }
  12502. ThreadPool::~ThreadPool()
  12503. {
  12504. removeAllJobs (true, 4000);
  12505. int i;
  12506. for (i = threads.size(); --i >= 0;)
  12507. threads.getUnchecked(i)->signalThreadShouldExit();
  12508. for (i = threads.size(); --i >= 0;)
  12509. threads.getUnchecked(i)->stopThread (500);
  12510. }
  12511. void ThreadPool::addJob (ThreadPoolJob* const job)
  12512. {
  12513. jassert (job != 0);
  12514. jassert (job->pool == 0);
  12515. if (job->pool == 0)
  12516. {
  12517. job->pool = this;
  12518. job->shouldStop = false;
  12519. job->isActive = false;
  12520. {
  12521. const ScopedLock sl (lock);
  12522. jobs.add (job);
  12523. int numRunning = 0;
  12524. for (int i = threads.size(); --i >= 0;)
  12525. if (threads.getUnchecked(i)->isThreadRunning() && ! threads.getUnchecked(i)->threadShouldExit())
  12526. ++numRunning;
  12527. if (numRunning < threads.size())
  12528. {
  12529. bool startedOne = false;
  12530. int n = 1000;
  12531. while (--n >= 0 && ! startedOne)
  12532. {
  12533. for (int i = threads.size(); --i >= 0;)
  12534. {
  12535. if (! threads.getUnchecked(i)->isThreadRunning())
  12536. {
  12537. threads.getUnchecked(i)->startThread (priority);
  12538. startedOne = true;
  12539. break;
  12540. }
  12541. }
  12542. if (! startedOne)
  12543. Thread::sleep (2);
  12544. }
  12545. }
  12546. }
  12547. for (int i = threads.size(); --i >= 0;)
  12548. threads.getUnchecked(i)->notify();
  12549. }
  12550. }
  12551. int ThreadPool::getNumJobs() const
  12552. {
  12553. return jobs.size();
  12554. }
  12555. ThreadPoolJob* ThreadPool::getJob (const int index) const
  12556. {
  12557. const ScopedLock sl (lock);
  12558. return jobs [index];
  12559. }
  12560. bool ThreadPool::contains (const ThreadPoolJob* const job) const
  12561. {
  12562. const ScopedLock sl (lock);
  12563. return jobs.contains (const_cast <ThreadPoolJob*> (job));
  12564. }
  12565. bool ThreadPool::isJobRunning (const ThreadPoolJob* const job) const
  12566. {
  12567. const ScopedLock sl (lock);
  12568. return jobs.contains (const_cast <ThreadPoolJob*> (job)) && job->isActive;
  12569. }
  12570. bool ThreadPool::waitForJobToFinish (const ThreadPoolJob* const job,
  12571. const int timeOutMs) const
  12572. {
  12573. if (job != 0)
  12574. {
  12575. const uint32 start = Time::getMillisecondCounter();
  12576. while (contains (job))
  12577. {
  12578. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  12579. return false;
  12580. jobFinishedSignal.wait (2);
  12581. }
  12582. }
  12583. return true;
  12584. }
  12585. bool ThreadPool::removeJob (ThreadPoolJob* const job,
  12586. const bool interruptIfRunning,
  12587. const int timeOutMs)
  12588. {
  12589. bool dontWait = true;
  12590. if (job != 0)
  12591. {
  12592. const ScopedLock sl (lock);
  12593. if (jobs.contains (job))
  12594. {
  12595. if (job->isActive)
  12596. {
  12597. if (interruptIfRunning)
  12598. job->signalJobShouldExit();
  12599. dontWait = false;
  12600. }
  12601. else
  12602. {
  12603. jobs.removeValue (job);
  12604. }
  12605. }
  12606. }
  12607. return dontWait || waitForJobToFinish (job, timeOutMs);
  12608. }
  12609. bool ThreadPool::removeAllJobs (const bool interruptRunningJobs,
  12610. const int timeOutMs,
  12611. const bool deleteInactiveJobs,
  12612. ThreadPool::JobSelector* selectedJobsToRemove)
  12613. {
  12614. Array <ThreadPoolJob*> jobsToWaitFor;
  12615. {
  12616. const ScopedLock sl (lock);
  12617. for (int i = jobs.size(); --i >= 0;)
  12618. {
  12619. ThreadPoolJob* const job = jobs.getUnchecked(i);
  12620. if (selectedJobsToRemove == 0 || selectedJobsToRemove->isJobSuitable (job))
  12621. {
  12622. if (job->isActive)
  12623. {
  12624. jobsToWaitFor.add (job);
  12625. if (interruptRunningJobs)
  12626. job->signalJobShouldExit();
  12627. }
  12628. else
  12629. {
  12630. jobs.remove (i);
  12631. if (deleteInactiveJobs)
  12632. delete job;
  12633. }
  12634. }
  12635. }
  12636. }
  12637. const uint32 start = Time::getMillisecondCounter();
  12638. for (;;)
  12639. {
  12640. for (int i = jobsToWaitFor.size(); --i >= 0;)
  12641. if (! isJobRunning (jobsToWaitFor.getUnchecked (i)))
  12642. jobsToWaitFor.remove (i);
  12643. if (jobsToWaitFor.size() == 0)
  12644. break;
  12645. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  12646. return false;
  12647. jobFinishedSignal.wait (20);
  12648. }
  12649. return true;
  12650. }
  12651. const StringArray ThreadPool::getNamesOfAllJobs (const bool onlyReturnActiveJobs) const
  12652. {
  12653. StringArray s;
  12654. const ScopedLock sl (lock);
  12655. for (int i = 0; i < jobs.size(); ++i)
  12656. {
  12657. const ThreadPoolJob* const job = jobs.getUnchecked(i);
  12658. if (job->isActive || ! onlyReturnActiveJobs)
  12659. s.add (job->getJobName());
  12660. }
  12661. return s;
  12662. }
  12663. bool ThreadPool::setThreadPriorities (const int newPriority)
  12664. {
  12665. bool ok = true;
  12666. if (priority != newPriority)
  12667. {
  12668. priority = newPriority;
  12669. for (int i = threads.size(); --i >= 0;)
  12670. if (! threads.getUnchecked(i)->setPriority (newPriority))
  12671. ok = false;
  12672. }
  12673. return ok;
  12674. }
  12675. bool ThreadPool::runNextJob()
  12676. {
  12677. ThreadPoolJob* job = 0;
  12678. {
  12679. const ScopedLock sl (lock);
  12680. for (int i = 0; i < jobs.size(); ++i)
  12681. {
  12682. job = jobs[i];
  12683. if (job != 0 && ! (job->isActive || job->shouldStop))
  12684. break;
  12685. job = 0;
  12686. }
  12687. if (job != 0)
  12688. job->isActive = true;
  12689. }
  12690. if (job != 0)
  12691. {
  12692. JUCE_TRY
  12693. {
  12694. ThreadPoolJob::JobStatus result = job->runJob();
  12695. lastJobEndTime = Time::getApproximateMillisecondCounter();
  12696. const ScopedLock sl (lock);
  12697. if (jobs.contains (job))
  12698. {
  12699. job->isActive = false;
  12700. if (result != ThreadPoolJob::jobNeedsRunningAgain || job->shouldStop)
  12701. {
  12702. job->pool = 0;
  12703. job->shouldStop = true;
  12704. jobs.removeValue (job);
  12705. if (result == ThreadPoolJob::jobHasFinishedAndShouldBeDeleted)
  12706. delete job;
  12707. jobFinishedSignal.signal();
  12708. }
  12709. else
  12710. {
  12711. // move the job to the end of the queue if it wants another go
  12712. jobs.move (jobs.indexOf (job), -1);
  12713. }
  12714. }
  12715. }
  12716. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  12717. catch (...)
  12718. {
  12719. const ScopedLock sl (lock);
  12720. jobs.removeValue (job);
  12721. }
  12722. #endif
  12723. }
  12724. else
  12725. {
  12726. if (threadStopTimeout > 0
  12727. && Time::getApproximateMillisecondCounter() > lastJobEndTime + threadStopTimeout)
  12728. {
  12729. const ScopedLock sl (lock);
  12730. if (jobs.size() == 0)
  12731. for (int i = threads.size(); --i >= 0;)
  12732. threads.getUnchecked(i)->signalThreadShouldExit();
  12733. }
  12734. else
  12735. {
  12736. return false;
  12737. }
  12738. }
  12739. return true;
  12740. }
  12741. END_JUCE_NAMESPACE
  12742. /*** End of inlined file: juce_ThreadPool.cpp ***/
  12743. /*** Start of inlined file: juce_TimeSliceThread.cpp ***/
  12744. BEGIN_JUCE_NAMESPACE
  12745. TimeSliceThread::TimeSliceThread (const String& threadName)
  12746. : Thread (threadName),
  12747. index (0),
  12748. clientBeingCalled (0),
  12749. clientsChanged (false)
  12750. {
  12751. }
  12752. TimeSliceThread::~TimeSliceThread()
  12753. {
  12754. stopThread (2000);
  12755. }
  12756. void TimeSliceThread::addTimeSliceClient (TimeSliceClient* const client)
  12757. {
  12758. const ScopedLock sl (listLock);
  12759. clients.addIfNotAlreadyThere (client);
  12760. clientsChanged = true;
  12761. notify();
  12762. }
  12763. void TimeSliceThread::removeTimeSliceClient (TimeSliceClient* const client)
  12764. {
  12765. const ScopedLock sl1 (listLock);
  12766. clientsChanged = true;
  12767. // if there's a chance we're in the middle of calling this client, we need to
  12768. // also lock the outer lock..
  12769. if (clientBeingCalled == client)
  12770. {
  12771. const ScopedUnlock ul (listLock); // unlock first to get the order right..
  12772. const ScopedLock sl2 (callbackLock);
  12773. const ScopedLock sl3 (listLock);
  12774. clients.removeValue (client);
  12775. }
  12776. else
  12777. {
  12778. clients.removeValue (client);
  12779. }
  12780. }
  12781. int TimeSliceThread::getNumClients() const
  12782. {
  12783. return clients.size();
  12784. }
  12785. TimeSliceClient* TimeSliceThread::getClient (const int i) const
  12786. {
  12787. const ScopedLock sl (listLock);
  12788. return clients [i];
  12789. }
  12790. void TimeSliceThread::run()
  12791. {
  12792. int numCallsSinceBusy = 0;
  12793. while (! threadShouldExit())
  12794. {
  12795. int timeToWait = 500;
  12796. {
  12797. const ScopedLock sl (callbackLock);
  12798. {
  12799. const ScopedLock sl2 (listLock);
  12800. if (clients.size() > 0)
  12801. {
  12802. index = (index + 1) % clients.size();
  12803. clientBeingCalled = clients [index];
  12804. }
  12805. else
  12806. {
  12807. index = 0;
  12808. clientBeingCalled = 0;
  12809. }
  12810. if (clientsChanged)
  12811. {
  12812. clientsChanged = false;
  12813. numCallsSinceBusy = 0;
  12814. }
  12815. }
  12816. if (clientBeingCalled != 0)
  12817. {
  12818. if (clientBeingCalled->useTimeSlice())
  12819. numCallsSinceBusy = 0;
  12820. else
  12821. ++numCallsSinceBusy;
  12822. if (numCallsSinceBusy >= clients.size())
  12823. timeToWait = 500;
  12824. else if (index == 0)
  12825. timeToWait = 1; // throw in an occasional pause, to stop everything locking up
  12826. else
  12827. timeToWait = 0;
  12828. }
  12829. }
  12830. if (timeToWait > 0)
  12831. wait (timeToWait);
  12832. }
  12833. }
  12834. END_JUCE_NAMESPACE
  12835. /*** End of inlined file: juce_TimeSliceThread.cpp ***/
  12836. /*** Start of inlined file: juce_DeletedAtShutdown.cpp ***/
  12837. BEGIN_JUCE_NAMESPACE
  12838. DeletedAtShutdown::DeletedAtShutdown()
  12839. {
  12840. const ScopedLock sl (getLock());
  12841. getObjects().add (this);
  12842. }
  12843. DeletedAtShutdown::~DeletedAtShutdown()
  12844. {
  12845. const ScopedLock sl (getLock());
  12846. getObjects().removeValue (this);
  12847. }
  12848. void DeletedAtShutdown::deleteAll()
  12849. {
  12850. // make a local copy of the array, so it can't get into a loop if something
  12851. // creates another DeletedAtShutdown object during its destructor.
  12852. Array <DeletedAtShutdown*> localCopy;
  12853. {
  12854. const ScopedLock sl (getLock());
  12855. localCopy = getObjects();
  12856. }
  12857. for (int i = localCopy.size(); --i >= 0;)
  12858. {
  12859. JUCE_TRY
  12860. {
  12861. DeletedAtShutdown* deletee = localCopy.getUnchecked(i);
  12862. // double-check that it's not already been deleted during another object's destructor.
  12863. {
  12864. const ScopedLock sl (getLock());
  12865. if (! getObjects().contains (deletee))
  12866. deletee = 0;
  12867. }
  12868. delete deletee;
  12869. }
  12870. JUCE_CATCH_EXCEPTION
  12871. }
  12872. // if no objects got re-created during shutdown, this should have been emptied by their
  12873. // destructors
  12874. jassert (getObjects().size() == 0);
  12875. getObjects().clear(); // just to make sure the array doesn't have any memory still allocated
  12876. }
  12877. CriticalSection& DeletedAtShutdown::getLock()
  12878. {
  12879. static CriticalSection lock;
  12880. return lock;
  12881. }
  12882. Array <DeletedAtShutdown*>& DeletedAtShutdown::getObjects()
  12883. {
  12884. static Array <DeletedAtShutdown*> objects;
  12885. return objects;
  12886. }
  12887. END_JUCE_NAMESPACE
  12888. /*** End of inlined file: juce_DeletedAtShutdown.cpp ***/
  12889. #endif
  12890. #if JUCE_BUILD_MISC
  12891. /*** Start of inlined file: juce_ValueTree.cpp ***/
  12892. BEGIN_JUCE_NAMESPACE
  12893. class ValueTree::SetPropertyAction : public UndoableAction
  12894. {
  12895. public:
  12896. SetPropertyAction (const SharedObjectPtr& target_, const Identifier& name_,
  12897. const var& newValue_, const var& oldValue_,
  12898. const bool isAddingNewProperty_, const bool isDeletingProperty_)
  12899. : target (target_), name (name_), newValue (newValue_), oldValue (oldValue_),
  12900. isAddingNewProperty (isAddingNewProperty_), isDeletingProperty (isDeletingProperty_)
  12901. {
  12902. }
  12903. ~SetPropertyAction() {}
  12904. bool perform()
  12905. {
  12906. jassert (! (isAddingNewProperty && target->hasProperty (name)));
  12907. if (isDeletingProperty)
  12908. target->removeProperty (name, 0);
  12909. else
  12910. target->setProperty (name, newValue, 0);
  12911. return true;
  12912. }
  12913. bool undo()
  12914. {
  12915. if (isAddingNewProperty)
  12916. target->removeProperty (name, 0);
  12917. else
  12918. target->setProperty (name, oldValue, 0);
  12919. return true;
  12920. }
  12921. int getSizeInUnits()
  12922. {
  12923. return (int) sizeof (*this); //xxx should be more accurate
  12924. }
  12925. UndoableAction* createCoalescedAction (UndoableAction* nextAction)
  12926. {
  12927. if (! (isAddingNewProperty || isDeletingProperty))
  12928. {
  12929. SetPropertyAction* next = dynamic_cast <SetPropertyAction*> (nextAction);
  12930. if (next != 0 && next->target == target && next->name == name
  12931. && ! (next->isAddingNewProperty || next->isDeletingProperty))
  12932. {
  12933. return new SetPropertyAction (target, name, next->newValue, oldValue, false, false);
  12934. }
  12935. }
  12936. return 0;
  12937. }
  12938. private:
  12939. const SharedObjectPtr target;
  12940. const Identifier name;
  12941. const var newValue;
  12942. var oldValue;
  12943. const bool isAddingNewProperty : 1, isDeletingProperty : 1;
  12944. SetPropertyAction (const SetPropertyAction&);
  12945. SetPropertyAction& operator= (const SetPropertyAction&);
  12946. };
  12947. class ValueTree::AddOrRemoveChildAction : public UndoableAction
  12948. {
  12949. public:
  12950. AddOrRemoveChildAction (const SharedObjectPtr& target_, const int childIndex_,
  12951. const SharedObjectPtr& newChild_)
  12952. : target (target_),
  12953. child (newChild_ != 0 ? newChild_ : target_->children [childIndex_]),
  12954. childIndex (childIndex_),
  12955. isDeleting (newChild_ == 0)
  12956. {
  12957. jassert (child != 0);
  12958. }
  12959. ~AddOrRemoveChildAction() {}
  12960. bool perform()
  12961. {
  12962. if (isDeleting)
  12963. target->removeChild (childIndex, 0);
  12964. else
  12965. target->addChild (child, childIndex, 0);
  12966. return true;
  12967. }
  12968. bool undo()
  12969. {
  12970. if (isDeleting)
  12971. {
  12972. target->addChild (child, childIndex, 0);
  12973. }
  12974. else
  12975. {
  12976. // If you hit this, it seems that your object's state is getting confused - probably
  12977. // because you've interleaved some undoable and non-undoable operations?
  12978. jassert (childIndex < target->children.size());
  12979. target->removeChild (childIndex, 0);
  12980. }
  12981. return true;
  12982. }
  12983. int getSizeInUnits()
  12984. {
  12985. return (int) sizeof (*this); //xxx should be more accurate
  12986. }
  12987. private:
  12988. const SharedObjectPtr target, child;
  12989. const int childIndex;
  12990. const bool isDeleting;
  12991. AddOrRemoveChildAction (const AddOrRemoveChildAction&);
  12992. AddOrRemoveChildAction& operator= (const AddOrRemoveChildAction&);
  12993. };
  12994. class ValueTree::MoveChildAction : public UndoableAction
  12995. {
  12996. public:
  12997. MoveChildAction (const SharedObjectPtr& target_,
  12998. const int startIndex_, const int endIndex_)
  12999. : target (target_),
  13000. startIndex (startIndex_),
  13001. endIndex (endIndex_)
  13002. {
  13003. }
  13004. ~MoveChildAction() {}
  13005. bool perform()
  13006. {
  13007. target->moveChild (startIndex, endIndex, 0);
  13008. return true;
  13009. }
  13010. bool undo()
  13011. {
  13012. target->moveChild (endIndex, startIndex, 0);
  13013. return true;
  13014. }
  13015. int getSizeInUnits()
  13016. {
  13017. return (int) sizeof (*this); //xxx should be more accurate
  13018. }
  13019. UndoableAction* createCoalescedAction (UndoableAction* nextAction)
  13020. {
  13021. MoveChildAction* next = dynamic_cast <MoveChildAction*> (nextAction);
  13022. if (next != 0 && next->target == target && next->child == child)
  13023. return new MoveChildAction (target, startIndex, next->endIndex);
  13024. return 0;
  13025. }
  13026. private:
  13027. const SharedObjectPtr target, child;
  13028. const int startIndex, endIndex;
  13029. MoveChildAction (const MoveChildAction&);
  13030. MoveChildAction& operator= (const MoveChildAction&);
  13031. };
  13032. ValueTree::SharedObject::SharedObject (const Identifier& type_)
  13033. : type (type_), parent (0)
  13034. {
  13035. }
  13036. ValueTree::SharedObject::SharedObject (const SharedObject& other)
  13037. : type (other.type), properties (other.properties), parent (0)
  13038. {
  13039. for (int i = 0; i < other.children.size(); ++i)
  13040. {
  13041. SharedObject* const child = new SharedObject (*other.children.getUnchecked(i));
  13042. child->parent = this;
  13043. children.add (child);
  13044. }
  13045. }
  13046. ValueTree::SharedObject::~SharedObject()
  13047. {
  13048. jassert (parent == 0); // this should never happen unless something isn't obeying the ref-counting!
  13049. for (int i = children.size(); --i >= 0;)
  13050. {
  13051. const SharedObjectPtr c (children.getUnchecked(i));
  13052. c->parent = 0;
  13053. children.remove (i);
  13054. c->sendParentChangeMessage();
  13055. }
  13056. }
  13057. void ValueTree::SharedObject::sendPropertyChangeMessage (ValueTree& tree, const Identifier& property)
  13058. {
  13059. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  13060. {
  13061. ValueTree* const v = valueTreesWithListeners[i];
  13062. if (v != 0)
  13063. v->listeners.call (&ValueTree::Listener::valueTreePropertyChanged, tree, property);
  13064. }
  13065. }
  13066. void ValueTree::SharedObject::sendPropertyChangeMessage (const Identifier& property)
  13067. {
  13068. ValueTree tree (this);
  13069. ValueTree::SharedObject* t = this;
  13070. while (t != 0)
  13071. {
  13072. t->sendPropertyChangeMessage (tree, property);
  13073. t = t->parent;
  13074. }
  13075. }
  13076. void ValueTree::SharedObject::sendChildChangeMessage (ValueTree& tree)
  13077. {
  13078. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  13079. {
  13080. ValueTree* const v = valueTreesWithListeners[i];
  13081. if (v != 0)
  13082. v->listeners.call (&ValueTree::Listener::valueTreeChildrenChanged, tree);
  13083. }
  13084. }
  13085. void ValueTree::SharedObject::sendChildChangeMessage()
  13086. {
  13087. ValueTree tree (this);
  13088. ValueTree::SharedObject* t = this;
  13089. while (t != 0)
  13090. {
  13091. t->sendChildChangeMessage (tree);
  13092. t = t->parent;
  13093. }
  13094. }
  13095. void ValueTree::SharedObject::sendParentChangeMessage()
  13096. {
  13097. ValueTree tree (this);
  13098. int i;
  13099. for (i = children.size(); --i >= 0;)
  13100. {
  13101. SharedObject* const t = children[i];
  13102. if (t != 0)
  13103. t->sendParentChangeMessage();
  13104. }
  13105. for (i = valueTreesWithListeners.size(); --i >= 0;)
  13106. {
  13107. ValueTree* const v = valueTreesWithListeners[i];
  13108. if (v != 0)
  13109. v->listeners.call (&ValueTree::Listener::valueTreeParentChanged, tree);
  13110. }
  13111. }
  13112. const var& ValueTree::SharedObject::getProperty (const Identifier& name) const
  13113. {
  13114. return properties [name];
  13115. }
  13116. const var ValueTree::SharedObject::getProperty (const Identifier& name, const var& defaultReturnValue) const
  13117. {
  13118. return properties.getWithDefault (name, defaultReturnValue);
  13119. }
  13120. void ValueTree::SharedObject::setProperty (const Identifier& name, const var& newValue, UndoManager* const undoManager)
  13121. {
  13122. if (undoManager == 0)
  13123. {
  13124. if (properties.set (name, newValue))
  13125. sendPropertyChangeMessage (name);
  13126. }
  13127. else
  13128. {
  13129. var* const existingValue = properties.getItem (name);
  13130. if (existingValue != 0)
  13131. {
  13132. if (*existingValue != newValue)
  13133. undoManager->perform (new SetPropertyAction (this, name, newValue, properties [name], false, false));
  13134. }
  13135. else
  13136. {
  13137. undoManager->perform (new SetPropertyAction (this, name, newValue, var::null, true, false));
  13138. }
  13139. }
  13140. }
  13141. bool ValueTree::SharedObject::hasProperty (const Identifier& name) const
  13142. {
  13143. return properties.contains (name);
  13144. }
  13145. void ValueTree::SharedObject::removeProperty (const Identifier& name, UndoManager* const undoManager)
  13146. {
  13147. if (undoManager == 0)
  13148. {
  13149. if (properties.remove (name))
  13150. sendPropertyChangeMessage (name);
  13151. }
  13152. else
  13153. {
  13154. if (properties.contains (name))
  13155. undoManager->perform (new SetPropertyAction (this, name, var::null, properties [name], false, true));
  13156. }
  13157. }
  13158. void ValueTree::SharedObject::removeAllProperties (UndoManager* const undoManager)
  13159. {
  13160. if (undoManager == 0)
  13161. {
  13162. while (properties.size() > 0)
  13163. {
  13164. const Identifier name (properties.getName (properties.size() - 1));
  13165. properties.remove (name);
  13166. sendPropertyChangeMessage (name);
  13167. }
  13168. }
  13169. else
  13170. {
  13171. for (int i = properties.size(); --i >= 0;)
  13172. undoManager->perform (new SetPropertyAction (this, properties.getName(i), var::null, properties.getValueAt(i), false, true));
  13173. }
  13174. }
  13175. ValueTree ValueTree::SharedObject::getChildWithName (const Identifier& typeToMatch) const
  13176. {
  13177. for (int i = 0; i < children.size(); ++i)
  13178. if (children.getUnchecked(i)->type == typeToMatch)
  13179. return ValueTree (static_cast <SharedObject*> (children.getUnchecked(i)));
  13180. return ValueTree::invalid;
  13181. }
  13182. ValueTree ValueTree::SharedObject::getOrCreateChildWithName (const Identifier& typeToMatch, UndoManager* undoManager)
  13183. {
  13184. for (int i = 0; i < children.size(); ++i)
  13185. if (children.getUnchecked(i)->type == typeToMatch)
  13186. return ValueTree (static_cast <SharedObject*> (children.getUnchecked(i)));
  13187. SharedObject* const newObject = new SharedObject (typeToMatch);
  13188. addChild (newObject, -1, undoManager);
  13189. return ValueTree (newObject);
  13190. }
  13191. ValueTree ValueTree::SharedObject::getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const
  13192. {
  13193. for (int i = 0; i < children.size(); ++i)
  13194. if (children.getUnchecked(i)->getProperty (propertyName) == propertyValue)
  13195. return ValueTree (static_cast <SharedObject*> (children.getUnchecked(i)));
  13196. return ValueTree::invalid;
  13197. }
  13198. bool ValueTree::SharedObject::isAChildOf (const SharedObject* const possibleParent) const
  13199. {
  13200. const SharedObject* p = parent;
  13201. while (p != 0)
  13202. {
  13203. if (p == possibleParent)
  13204. return true;
  13205. p = p->parent;
  13206. }
  13207. return false;
  13208. }
  13209. int ValueTree::SharedObject::indexOf (const ValueTree& child) const
  13210. {
  13211. return children.indexOf (child.object);
  13212. }
  13213. void ValueTree::SharedObject::addChild (SharedObject* child, int index, UndoManager* const undoManager)
  13214. {
  13215. if (child != 0 && child->parent != this)
  13216. {
  13217. if (child != this && ! isAChildOf (child))
  13218. {
  13219. // You should always make sure that a child is removed from its previous parent before
  13220. // adding it somewhere else - otherwise, it's ambiguous as to whether a different
  13221. // undomanager should be used when removing it from its current parent..
  13222. jassert (child->parent == 0);
  13223. if (child->parent != 0)
  13224. {
  13225. jassert (child->parent->children.indexOf (child) >= 0);
  13226. child->parent->removeChild (child->parent->children.indexOf (child), undoManager);
  13227. }
  13228. if (undoManager == 0)
  13229. {
  13230. children.insert (index, child);
  13231. child->parent = this;
  13232. sendChildChangeMessage();
  13233. child->sendParentChangeMessage();
  13234. }
  13235. else
  13236. {
  13237. if (index < 0)
  13238. index = children.size();
  13239. undoManager->perform (new AddOrRemoveChildAction (this, index, child));
  13240. }
  13241. }
  13242. else
  13243. {
  13244. // You're attempting to create a recursive loop! A node
  13245. // can't be a child of one of its own children!
  13246. jassertfalse;
  13247. }
  13248. }
  13249. }
  13250. void ValueTree::SharedObject::removeChild (const int childIndex, UndoManager* const undoManager)
  13251. {
  13252. const SharedObjectPtr child (children [childIndex]);
  13253. if (child != 0)
  13254. {
  13255. if (undoManager == 0)
  13256. {
  13257. children.remove (childIndex);
  13258. child->parent = 0;
  13259. sendChildChangeMessage();
  13260. child->sendParentChangeMessage();
  13261. }
  13262. else
  13263. {
  13264. undoManager->perform (new AddOrRemoveChildAction (this, childIndex, 0));
  13265. }
  13266. }
  13267. }
  13268. void ValueTree::SharedObject::removeAllChildren (UndoManager* const undoManager)
  13269. {
  13270. while (children.size() > 0)
  13271. removeChild (children.size() - 1, undoManager);
  13272. }
  13273. void ValueTree::SharedObject::moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  13274. {
  13275. // The source index must be a valid index!
  13276. jassert (((unsigned int) currentIndex) < (unsigned int) children.size());
  13277. if (currentIndex != newIndex
  13278. && ((unsigned int) currentIndex) < (unsigned int) children.size())
  13279. {
  13280. if (undoManager == 0)
  13281. {
  13282. children.move (currentIndex, newIndex);
  13283. sendChildChangeMessage();
  13284. }
  13285. else
  13286. {
  13287. if (((unsigned int) newIndex) >= (unsigned int) children.size())
  13288. newIndex = children.size() - 1;
  13289. undoManager->perform (new MoveChildAction (this, currentIndex, newIndex));
  13290. }
  13291. }
  13292. }
  13293. bool ValueTree::SharedObject::isEquivalentTo (const SharedObject& other) const
  13294. {
  13295. if (type != other.type
  13296. || properties.size() != other.properties.size()
  13297. || children.size() != other.children.size()
  13298. || properties != other.properties)
  13299. return false;
  13300. for (int i = 0; i < children.size(); ++i)
  13301. if (! children.getUnchecked(i)->isEquivalentTo (*other.children.getUnchecked(i)))
  13302. return false;
  13303. return true;
  13304. }
  13305. ValueTree::ValueTree() throw()
  13306. : object (0)
  13307. {
  13308. }
  13309. const ValueTree ValueTree::invalid;
  13310. ValueTree::ValueTree (const Identifier& type_)
  13311. : object (new ValueTree::SharedObject (type_))
  13312. {
  13313. jassert (type_.toString().isNotEmpty()); // All objects should be given a sensible type name!
  13314. }
  13315. ValueTree::ValueTree (SharedObject* const object_)
  13316. : object (object_)
  13317. {
  13318. }
  13319. ValueTree::ValueTree (const ValueTree& other)
  13320. : object (other.object)
  13321. {
  13322. }
  13323. ValueTree& ValueTree::operator= (const ValueTree& other)
  13324. {
  13325. if (listeners.size() > 0)
  13326. {
  13327. if (object != 0)
  13328. object->valueTreesWithListeners.removeValue (this);
  13329. if (other.object != 0)
  13330. other.object->valueTreesWithListeners.add (this);
  13331. }
  13332. object = other.object;
  13333. return *this;
  13334. }
  13335. ValueTree::~ValueTree()
  13336. {
  13337. if (listeners.size() > 0 && object != 0)
  13338. object->valueTreesWithListeners.removeValue (this);
  13339. }
  13340. bool ValueTree::operator== (const ValueTree& other) const throw()
  13341. {
  13342. return object == other.object;
  13343. }
  13344. bool ValueTree::operator!= (const ValueTree& other) const throw()
  13345. {
  13346. return object != other.object;
  13347. }
  13348. bool ValueTree::isEquivalentTo (const ValueTree& other) const
  13349. {
  13350. return object == other.object
  13351. || (object != 0 && other.object != 0 && object->isEquivalentTo (*other.object));
  13352. }
  13353. ValueTree ValueTree::createCopy() const
  13354. {
  13355. return ValueTree (object != 0 ? new SharedObject (*object) : 0);
  13356. }
  13357. bool ValueTree::hasType (const Identifier& typeName) const
  13358. {
  13359. return object != 0 && object->type == typeName;
  13360. }
  13361. const Identifier ValueTree::getType() const
  13362. {
  13363. return object != 0 ? object->type : Identifier();
  13364. }
  13365. ValueTree ValueTree::getParent() const
  13366. {
  13367. return ValueTree (object != 0 ? object->parent : (SharedObject*) 0);
  13368. }
  13369. const var& ValueTree::operator[] (const Identifier& name) const
  13370. {
  13371. return object == 0 ? var::null : object->getProperty (name);
  13372. }
  13373. const var& ValueTree::getProperty (const Identifier& name) const
  13374. {
  13375. return object == 0 ? var::null : object->getProperty (name);
  13376. }
  13377. const var ValueTree::getProperty (const Identifier& name, const var& defaultReturnValue) const
  13378. {
  13379. return object == 0 ? defaultReturnValue : object->getProperty (name, defaultReturnValue);
  13380. }
  13381. void ValueTree::setProperty (const Identifier& name, const var& newValue, UndoManager* const undoManager)
  13382. {
  13383. jassert (name.toString().isNotEmpty());
  13384. if (object != 0 && name.toString().isNotEmpty())
  13385. object->setProperty (name, newValue, undoManager);
  13386. }
  13387. bool ValueTree::hasProperty (const Identifier& name) const
  13388. {
  13389. return object != 0 && object->hasProperty (name);
  13390. }
  13391. void ValueTree::removeProperty (const Identifier& name, UndoManager* const undoManager)
  13392. {
  13393. if (object != 0)
  13394. object->removeProperty (name, undoManager);
  13395. }
  13396. void ValueTree::removeAllProperties (UndoManager* const undoManager)
  13397. {
  13398. if (object != 0)
  13399. object->removeAllProperties (undoManager);
  13400. }
  13401. int ValueTree::getNumProperties() const
  13402. {
  13403. return object == 0 ? 0 : object->properties.size();
  13404. }
  13405. const Identifier ValueTree::getPropertyName (const int index) const
  13406. {
  13407. return object == 0 ? Identifier()
  13408. : object->properties.getName (index);
  13409. }
  13410. class ValueTreePropertyValueSource : public Value::ValueSource,
  13411. public ValueTree::Listener
  13412. {
  13413. public:
  13414. ValueTreePropertyValueSource (const ValueTree& tree_,
  13415. const Identifier& property_,
  13416. UndoManager* const undoManager_)
  13417. : tree (tree_),
  13418. property (property_),
  13419. undoManager (undoManager_)
  13420. {
  13421. tree.addListener (this);
  13422. }
  13423. ~ValueTreePropertyValueSource()
  13424. {
  13425. tree.removeListener (this);
  13426. }
  13427. const var getValue() const
  13428. {
  13429. return tree [property];
  13430. }
  13431. void setValue (const var& newValue)
  13432. {
  13433. tree.setProperty (property, newValue, undoManager);
  13434. }
  13435. void valueTreePropertyChanged (ValueTree& treeWhosePropertyHasChanged, const Identifier& changedProperty)
  13436. {
  13437. if (tree == treeWhosePropertyHasChanged && property == changedProperty)
  13438. sendChangeMessage (false);
  13439. }
  13440. void valueTreeChildrenChanged (ValueTree&) {}
  13441. void valueTreeParentChanged (ValueTree&) {}
  13442. private:
  13443. ValueTree tree;
  13444. const Identifier property;
  13445. UndoManager* const undoManager;
  13446. ValueTreePropertyValueSource& operator= (const ValueTreePropertyValueSource&);
  13447. };
  13448. Value ValueTree::getPropertyAsValue (const Identifier& name, UndoManager* const undoManager) const
  13449. {
  13450. return Value (new ValueTreePropertyValueSource (*this, name, undoManager));
  13451. }
  13452. int ValueTree::getNumChildren() const
  13453. {
  13454. return object == 0 ? 0 : object->children.size();
  13455. }
  13456. ValueTree ValueTree::getChild (int index) const
  13457. {
  13458. return ValueTree (object != 0 ? (SharedObject*) object->children [index] : (SharedObject*) 0);
  13459. }
  13460. ValueTree ValueTree::getChildWithName (const Identifier& type) const
  13461. {
  13462. return object != 0 ? object->getChildWithName (type) : ValueTree::invalid;
  13463. }
  13464. ValueTree ValueTree::getOrCreateChildWithName (const Identifier& type, UndoManager* undoManager)
  13465. {
  13466. return object != 0 ? object->getOrCreateChildWithName (type, undoManager) : ValueTree::invalid;
  13467. }
  13468. ValueTree ValueTree::getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const
  13469. {
  13470. return object != 0 ? object->getChildWithProperty (propertyName, propertyValue) : ValueTree::invalid;
  13471. }
  13472. bool ValueTree::isAChildOf (const ValueTree& possibleParent) const
  13473. {
  13474. return object != 0 && object->isAChildOf (possibleParent.object);
  13475. }
  13476. int ValueTree::indexOf (const ValueTree& child) const
  13477. {
  13478. return object != 0 ? object->indexOf (child) : -1;
  13479. }
  13480. void ValueTree::addChild (const ValueTree& child, int index, UndoManager* const undoManager)
  13481. {
  13482. if (object != 0)
  13483. object->addChild (child.object, index, undoManager);
  13484. }
  13485. void ValueTree::removeChild (const int childIndex, UndoManager* const undoManager)
  13486. {
  13487. if (object != 0)
  13488. object->removeChild (childIndex, undoManager);
  13489. }
  13490. void ValueTree::removeChild (const ValueTree& child, UndoManager* const undoManager)
  13491. {
  13492. if (object != 0)
  13493. object->removeChild (object->children.indexOf (child.object), undoManager);
  13494. }
  13495. void ValueTree::removeAllChildren (UndoManager* const undoManager)
  13496. {
  13497. if (object != 0)
  13498. object->removeAllChildren (undoManager);
  13499. }
  13500. void ValueTree::moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  13501. {
  13502. if (object != 0)
  13503. object->moveChild (currentIndex, newIndex, undoManager);
  13504. }
  13505. void ValueTree::addListener (Listener* listener)
  13506. {
  13507. if (listener != 0)
  13508. {
  13509. if (listeners.size() == 0 && object != 0)
  13510. object->valueTreesWithListeners.add (this);
  13511. listeners.add (listener);
  13512. }
  13513. }
  13514. void ValueTree::removeListener (Listener* listener)
  13515. {
  13516. listeners.remove (listener);
  13517. if (listeners.size() == 0 && object != 0)
  13518. object->valueTreesWithListeners.removeValue (this);
  13519. }
  13520. XmlElement* ValueTree::SharedObject::createXml() const
  13521. {
  13522. XmlElement* xml = new XmlElement (type.toString());
  13523. int i;
  13524. for (i = 0; i < properties.size(); ++i)
  13525. {
  13526. Identifier name (properties.getName(i));
  13527. const var& v = properties [name];
  13528. jassert (! v.isObject()); // DynamicObjects can't be stored as XML!
  13529. xml->setAttribute (name.toString(), v.toString());
  13530. }
  13531. for (i = 0; i < children.size(); ++i)
  13532. xml->addChildElement (children.getUnchecked(i)->createXml());
  13533. return xml;
  13534. }
  13535. XmlElement* ValueTree::createXml() const
  13536. {
  13537. return object != 0 ? object->createXml() : 0;
  13538. }
  13539. ValueTree ValueTree::fromXml (const XmlElement& xml)
  13540. {
  13541. ValueTree v (xml.getTagName());
  13542. const int numAtts = xml.getNumAttributes(); // xxx inefficient - should write an att iterator..
  13543. for (int i = 0; i < numAtts; ++i)
  13544. v.setProperty (xml.getAttributeName (i), var (xml.getAttributeValue (i)), 0);
  13545. forEachXmlChildElement (xml, e)
  13546. {
  13547. v.addChild (fromXml (*e), -1, 0);
  13548. }
  13549. return v;
  13550. }
  13551. void ValueTree::writeToStream (OutputStream& output)
  13552. {
  13553. output.writeString (getType().toString());
  13554. const int numProps = getNumProperties();
  13555. output.writeCompressedInt (numProps);
  13556. int i;
  13557. for (i = 0; i < numProps; ++i)
  13558. {
  13559. const Identifier name (getPropertyName(i));
  13560. output.writeString (name.toString());
  13561. getProperty(name).writeToStream (output);
  13562. }
  13563. const int numChildren = getNumChildren();
  13564. output.writeCompressedInt (numChildren);
  13565. for (i = 0; i < numChildren; ++i)
  13566. getChild (i).writeToStream (output);
  13567. }
  13568. ValueTree ValueTree::readFromStream (InputStream& input)
  13569. {
  13570. const String type (input.readString());
  13571. if (type.isEmpty())
  13572. return ValueTree::invalid;
  13573. ValueTree v (type);
  13574. const int numProps = input.readCompressedInt();
  13575. if (numProps < 0)
  13576. {
  13577. jassertfalse; // trying to read corrupted data!
  13578. return v;
  13579. }
  13580. int i;
  13581. for (i = 0; i < numProps; ++i)
  13582. {
  13583. const String name (input.readString());
  13584. jassert (name.isNotEmpty());
  13585. const var value (var::readFromStream (input));
  13586. v.setProperty (name, value, 0);
  13587. }
  13588. const int numChildren = input.readCompressedInt();
  13589. for (i = 0; i < numChildren; ++i)
  13590. v.addChild (readFromStream (input), -1, 0);
  13591. return v;
  13592. }
  13593. ValueTree ValueTree::readFromData (const void* const data, const size_t numBytes)
  13594. {
  13595. MemoryInputStream in (data, numBytes, false);
  13596. return readFromStream (in);
  13597. }
  13598. END_JUCE_NAMESPACE
  13599. /*** End of inlined file: juce_ValueTree.cpp ***/
  13600. /*** Start of inlined file: juce_Value.cpp ***/
  13601. BEGIN_JUCE_NAMESPACE
  13602. Value::ValueSource::ValueSource()
  13603. {
  13604. }
  13605. Value::ValueSource::~ValueSource()
  13606. {
  13607. }
  13608. void Value::ValueSource::sendChangeMessage (const bool synchronous)
  13609. {
  13610. if (synchronous)
  13611. {
  13612. for (int i = valuesWithListeners.size(); --i >= 0;)
  13613. {
  13614. Value* const v = valuesWithListeners[i];
  13615. if (v != 0)
  13616. v->callListeners();
  13617. }
  13618. }
  13619. else
  13620. {
  13621. triggerAsyncUpdate();
  13622. }
  13623. }
  13624. void Value::ValueSource::handleAsyncUpdate()
  13625. {
  13626. sendChangeMessage (true);
  13627. }
  13628. class SimpleValueSource : public Value::ValueSource
  13629. {
  13630. public:
  13631. SimpleValueSource()
  13632. {
  13633. }
  13634. SimpleValueSource (const var& initialValue)
  13635. : value (initialValue)
  13636. {
  13637. }
  13638. ~SimpleValueSource()
  13639. {
  13640. }
  13641. const var getValue() const
  13642. {
  13643. return value;
  13644. }
  13645. void setValue (const var& newValue)
  13646. {
  13647. if (newValue != value)
  13648. {
  13649. value = newValue;
  13650. sendChangeMessage (false);
  13651. }
  13652. }
  13653. private:
  13654. var value;
  13655. SimpleValueSource (const SimpleValueSource&);
  13656. SimpleValueSource& operator= (const SimpleValueSource&);
  13657. };
  13658. Value::Value()
  13659. : value (new SimpleValueSource())
  13660. {
  13661. }
  13662. Value::Value (ValueSource* const value_)
  13663. : value (value_)
  13664. {
  13665. jassert (value_ != 0);
  13666. }
  13667. Value::Value (const var& initialValue)
  13668. : value (new SimpleValueSource (initialValue))
  13669. {
  13670. }
  13671. Value::Value (const Value& other)
  13672. : value (other.value)
  13673. {
  13674. }
  13675. Value& Value::operator= (const Value& other)
  13676. {
  13677. value = other.value;
  13678. return *this;
  13679. }
  13680. Value::~Value()
  13681. {
  13682. if (listeners.size() > 0)
  13683. value->valuesWithListeners.removeValue (this);
  13684. }
  13685. const var Value::getValue() const
  13686. {
  13687. return value->getValue();
  13688. }
  13689. Value::operator const var() const
  13690. {
  13691. return getValue();
  13692. }
  13693. void Value::setValue (const var& newValue)
  13694. {
  13695. value->setValue (newValue);
  13696. }
  13697. const String Value::toString() const
  13698. {
  13699. return value->getValue().toString();
  13700. }
  13701. Value& Value::operator= (const var& newValue)
  13702. {
  13703. value->setValue (newValue);
  13704. return *this;
  13705. }
  13706. void Value::referTo (const Value& valueToReferTo)
  13707. {
  13708. if (valueToReferTo.value != value)
  13709. {
  13710. if (listeners.size() > 0)
  13711. {
  13712. value->valuesWithListeners.removeValue (this);
  13713. valueToReferTo.value->valuesWithListeners.add (this);
  13714. }
  13715. value = valueToReferTo.value;
  13716. callListeners();
  13717. }
  13718. }
  13719. bool Value::refersToSameSourceAs (const Value& other) const
  13720. {
  13721. return value == other.value;
  13722. }
  13723. bool Value::operator== (const Value& other) const
  13724. {
  13725. return value == other.value || value->getValue() == other.getValue();
  13726. }
  13727. bool Value::operator!= (const Value& other) const
  13728. {
  13729. return value != other.value && value->getValue() != other.getValue();
  13730. }
  13731. void Value::addListener (Listener* const listener)
  13732. {
  13733. if (listener != 0)
  13734. {
  13735. if (listeners.size() == 0)
  13736. value->valuesWithListeners.add (this);
  13737. listeners.add (listener);
  13738. }
  13739. }
  13740. void Value::removeListener (Listener* const listener)
  13741. {
  13742. listeners.remove (listener);
  13743. if (listeners.size() == 0)
  13744. value->valuesWithListeners.removeValue (this);
  13745. }
  13746. void Value::callListeners()
  13747. {
  13748. Value v (*this); // (create a copy in case this gets deleted by a callback)
  13749. listeners.call (&Listener::valueChanged, v);
  13750. }
  13751. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const Value& value)
  13752. {
  13753. return stream << value.toString();
  13754. }
  13755. END_JUCE_NAMESPACE
  13756. /*** End of inlined file: juce_Value.cpp ***/
  13757. /*** Start of inlined file: juce_Application.cpp ***/
  13758. #if JUCE_MSVC
  13759. #pragma warning (push)
  13760. #pragma warning (disable: 4245 4514 4100)
  13761. #include <crtdbg.h>
  13762. #pragma warning (pop)
  13763. #endif
  13764. BEGIN_JUCE_NAMESPACE
  13765. void juce_setCurrentThreadName (const String& name);
  13766. static JUCEApplication* appInstance = 0;
  13767. JUCEApplication::JUCEApplication()
  13768. : appReturnValue (0),
  13769. stillInitialising (true)
  13770. {
  13771. }
  13772. JUCEApplication::~JUCEApplication()
  13773. {
  13774. if (appLock != 0)
  13775. {
  13776. appLock->exit();
  13777. appLock = 0;
  13778. }
  13779. }
  13780. JUCEApplication* JUCEApplication::getInstance() throw()
  13781. {
  13782. return appInstance;
  13783. }
  13784. bool JUCEApplication::isInitialising() const throw()
  13785. {
  13786. return stillInitialising;
  13787. }
  13788. const String JUCEApplication::getApplicationVersion()
  13789. {
  13790. return String::empty;
  13791. }
  13792. bool JUCEApplication::moreThanOneInstanceAllowed()
  13793. {
  13794. return true;
  13795. }
  13796. void JUCEApplication::anotherInstanceStarted (const String&)
  13797. {
  13798. }
  13799. void JUCEApplication::systemRequestedQuit()
  13800. {
  13801. quit();
  13802. }
  13803. void JUCEApplication::quit()
  13804. {
  13805. MessageManager::getInstance()->stopDispatchLoop();
  13806. }
  13807. void JUCEApplication::setApplicationReturnValue (const int newReturnValue) throw()
  13808. {
  13809. appReturnValue = newReturnValue;
  13810. }
  13811. void JUCEApplication::unhandledException (const std::exception*,
  13812. const String&,
  13813. const int)
  13814. {
  13815. jassertfalse;
  13816. }
  13817. void JUCEApplication::sendUnhandledException (const std::exception* const e,
  13818. const char* const sourceFile,
  13819. const int lineNumber)
  13820. {
  13821. if (appInstance != 0)
  13822. appInstance->unhandledException (e, sourceFile, lineNumber);
  13823. }
  13824. ApplicationCommandTarget* JUCEApplication::getNextCommandTarget()
  13825. {
  13826. return 0;
  13827. }
  13828. void JUCEApplication::getAllCommands (Array <CommandID>& commands)
  13829. {
  13830. commands.add (StandardApplicationCommandIDs::quit);
  13831. }
  13832. void JUCEApplication::getCommandInfo (const CommandID commandID, ApplicationCommandInfo& result)
  13833. {
  13834. if (commandID == StandardApplicationCommandIDs::quit)
  13835. {
  13836. result.setInfo (TRANS("Quit"),
  13837. TRANS("Quits the application"),
  13838. "Application",
  13839. 0);
  13840. result.defaultKeypresses.add (KeyPress ('q', ModifierKeys::commandModifier, 0));
  13841. }
  13842. }
  13843. bool JUCEApplication::perform (const InvocationInfo& info)
  13844. {
  13845. if (info.commandID == StandardApplicationCommandIDs::quit)
  13846. {
  13847. systemRequestedQuit();
  13848. return true;
  13849. }
  13850. return false;
  13851. }
  13852. int JUCEApplication::main (String& commandLine, JUCEApplication* const app)
  13853. {
  13854. if (! app->initialiseApp (commandLine))
  13855. return 0;
  13856. // now loop until a quit message is received..
  13857. JUCE_TRY
  13858. {
  13859. MessageManager::getInstance()->runDispatchLoop();
  13860. }
  13861. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  13862. catch (const std::exception& e)
  13863. {
  13864. app->unhandledException (&e, __FILE__, __LINE__);
  13865. }
  13866. catch (...)
  13867. {
  13868. app->unhandledException (0, __FILE__, __LINE__);
  13869. }
  13870. #endif
  13871. return shutdownAppAndClearUp();
  13872. }
  13873. bool JUCEApplication::initialiseApp (String& commandLine)
  13874. {
  13875. jassert (appInstance == 0);
  13876. appInstance = this;
  13877. commandLineParameters = commandLine.trim();
  13878. commandLine = String::empty;
  13879. initialiseJuce_GUI();
  13880. #if ! JUCE_IPHONE
  13881. jassert (appLock == 0); // initialiseApp must only be called once!
  13882. if (! moreThanOneInstanceAllowed())
  13883. {
  13884. appLock = new InterProcessLock ("juceAppLock_" + getApplicationName());
  13885. if (! appLock->enter(0))
  13886. {
  13887. MessageManager::broadcastMessage (getApplicationName() + "/" + commandLineParameters);
  13888. delete appInstance;
  13889. appInstance = 0;
  13890. DBG ("Another instance is running - quitting...");
  13891. return false;
  13892. }
  13893. }
  13894. #endif
  13895. // let the app do its setting-up..
  13896. initialise (commandLineParameters);
  13897. // register for broadcast new app messages
  13898. MessageManager::getInstance()->registerBroadcastListener (this);
  13899. stillInitialising = false;
  13900. return true;
  13901. }
  13902. int JUCEApplication::shutdownAppAndClearUp()
  13903. {
  13904. jassert (appInstance != 0);
  13905. ScopedPointer<JUCEApplication> app (appInstance);
  13906. int returnValue = 0;
  13907. MessageManager::getInstance()->deregisterBroadcastListener (static_cast <JUCEApplication*> (app));
  13908. static bool reentrancyCheck = false;
  13909. if (! reentrancyCheck)
  13910. {
  13911. reentrancyCheck = true;
  13912. JUCE_TRY
  13913. {
  13914. // give the app a chance to clean up..
  13915. app->shutdown();
  13916. }
  13917. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  13918. catch (const std::exception& e)
  13919. {
  13920. app->unhandledException (&e, __FILE__, __LINE__);
  13921. }
  13922. catch (...)
  13923. {
  13924. app->unhandledException (0, __FILE__, __LINE__);
  13925. }
  13926. #endif
  13927. JUCE_TRY
  13928. {
  13929. shutdownJuce_GUI();
  13930. returnValue = app->getApplicationReturnValue();
  13931. appInstance = 0;
  13932. app = 0;
  13933. }
  13934. JUCE_CATCH_ALL_ASSERT
  13935. reentrancyCheck = false;
  13936. }
  13937. return returnValue;
  13938. }
  13939. #if JUCE_IPHONE
  13940. extern int juce_IPhoneMain (int argc, const char* argv[], JUCEApplication* app);
  13941. #endif
  13942. #if ! JUCE_WINDOWS
  13943. extern const char* juce_Argv0;
  13944. #endif
  13945. int JUCEApplication::main (int argc, const char* argv[], JUCEApplication* const newApp)
  13946. {
  13947. #if ! JUCE_WINDOWS
  13948. juce_Argv0 = argv[0];
  13949. #endif
  13950. #if JUCE_IPHONE
  13951. const ScopedAutoReleasePool pool;
  13952. return juce_IPhoneMain (argc, argv, newApp);
  13953. #else
  13954. #if JUCE_MAC
  13955. const ScopedAutoReleasePool pool;
  13956. #endif
  13957. String cmd;
  13958. for (int i = 1; i < argc; ++i)
  13959. cmd << argv[i] << ' ';
  13960. return JUCEApplication::main (cmd, newApp);
  13961. #endif
  13962. }
  13963. void JUCEApplication::actionListenerCallback (const String& message)
  13964. {
  13965. if (message.startsWith (getApplicationName() + "/"))
  13966. anotherInstanceStarted (message.substring (getApplicationName().length() + 1));
  13967. }
  13968. static bool juceInitialisedGUI = false;
  13969. void JUCE_PUBLIC_FUNCTION initialiseJuce_GUI()
  13970. {
  13971. if (! juceInitialisedGUI)
  13972. {
  13973. #if JUCE_MAC || JUCE_IPHONE
  13974. const ScopedAutoReleasePool pool;
  13975. #endif
  13976. juceInitialisedGUI = true;
  13977. initialiseJuce_NonGUI();
  13978. MessageManager::getInstance();
  13979. LookAndFeel::setDefaultLookAndFeel (0);
  13980. juce_setCurrentThreadName ("Juce Message Thread");
  13981. #if JUCE_WINDOWS && JUCE_DEBUG
  13982. // This section is just for catching people who mess up their project settings and
  13983. // turn RTTI off..
  13984. try
  13985. {
  13986. TextButton tb (String::empty);
  13987. Component* c = &tb;
  13988. // Got an exception here? Then TURN ON RTTI in your compiler settings!!
  13989. c = dynamic_cast <Button*> (c);
  13990. }
  13991. catch (...)
  13992. {
  13993. // Ended up here? If so, TURN ON RTTI in your compiler settings!! And if you
  13994. // got as far as this catch statement, then why haven't you got exception catching
  13995. // turned on in the debugger???
  13996. jassertfalse;
  13997. }
  13998. #endif
  13999. }
  14000. }
  14001. void JUCE_PUBLIC_FUNCTION shutdownJuce_GUI()
  14002. {
  14003. if (juceInitialisedGUI)
  14004. {
  14005. #if JUCE_MAC
  14006. const ScopedAutoReleasePool pool;
  14007. #endif
  14008. {
  14009. DeletedAtShutdown::deleteAll();
  14010. LookAndFeel::clearDefaultLookAndFeel();
  14011. }
  14012. delete MessageManager::getInstance();
  14013. shutdownJuce_NonGUI();
  14014. juceInitialisedGUI = false;
  14015. }
  14016. }
  14017. END_JUCE_NAMESPACE
  14018. /*** End of inlined file: juce_Application.cpp ***/
  14019. /*** Start of inlined file: juce_ApplicationCommandInfo.cpp ***/
  14020. BEGIN_JUCE_NAMESPACE
  14021. ApplicationCommandInfo::ApplicationCommandInfo (const CommandID commandID_) throw()
  14022. : commandID (commandID_),
  14023. flags (0)
  14024. {
  14025. }
  14026. void ApplicationCommandInfo::setInfo (const String& shortName_,
  14027. const String& description_,
  14028. const String& categoryName_,
  14029. const int flags_) throw()
  14030. {
  14031. shortName = shortName_;
  14032. description = description_;
  14033. categoryName = categoryName_;
  14034. flags = flags_;
  14035. }
  14036. void ApplicationCommandInfo::setActive (const bool b) throw()
  14037. {
  14038. if (b)
  14039. flags &= ~isDisabled;
  14040. else
  14041. flags |= isDisabled;
  14042. }
  14043. void ApplicationCommandInfo::setTicked (const bool b) throw()
  14044. {
  14045. if (b)
  14046. flags |= isTicked;
  14047. else
  14048. flags &= ~isTicked;
  14049. }
  14050. void ApplicationCommandInfo::addDefaultKeypress (const int keyCode, const ModifierKeys& modifiers) throw()
  14051. {
  14052. defaultKeypresses.add (KeyPress (keyCode, modifiers, 0));
  14053. }
  14054. END_JUCE_NAMESPACE
  14055. /*** End of inlined file: juce_ApplicationCommandInfo.cpp ***/
  14056. /*** Start of inlined file: juce_ApplicationCommandManager.cpp ***/
  14057. BEGIN_JUCE_NAMESPACE
  14058. ApplicationCommandManager::ApplicationCommandManager()
  14059. : firstTarget (0)
  14060. {
  14061. keyMappings = new KeyPressMappingSet (this);
  14062. Desktop::getInstance().addFocusChangeListener (this);
  14063. }
  14064. ApplicationCommandManager::~ApplicationCommandManager()
  14065. {
  14066. Desktop::getInstance().removeFocusChangeListener (this);
  14067. keyMappings = 0;
  14068. }
  14069. void ApplicationCommandManager::clearCommands()
  14070. {
  14071. commands.clear();
  14072. keyMappings->clearAllKeyPresses();
  14073. triggerAsyncUpdate();
  14074. }
  14075. void ApplicationCommandManager::registerCommand (const ApplicationCommandInfo& newCommand)
  14076. {
  14077. // zero isn't a valid command ID!
  14078. jassert (newCommand.commandID != 0);
  14079. // the name isn't optional!
  14080. jassert (newCommand.shortName.isNotEmpty());
  14081. if (getCommandForID (newCommand.commandID) == 0)
  14082. {
  14083. ApplicationCommandInfo* const newInfo = new ApplicationCommandInfo (newCommand);
  14084. newInfo->flags &= ~ApplicationCommandInfo::isTicked;
  14085. commands.add (newInfo);
  14086. keyMappings->resetToDefaultMapping (newCommand.commandID);
  14087. triggerAsyncUpdate();
  14088. }
  14089. else
  14090. {
  14091. // trying to re-register the same command with different parameters?
  14092. jassert (newCommand.shortName == getCommandForID (newCommand.commandID)->shortName
  14093. && (newCommand.description == getCommandForID (newCommand.commandID)->description || newCommand.description.isEmpty())
  14094. && newCommand.categoryName == getCommandForID (newCommand.commandID)->categoryName
  14095. && newCommand.defaultKeypresses == getCommandForID (newCommand.commandID)->defaultKeypresses
  14096. && (newCommand.flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor))
  14097. == (getCommandForID (newCommand.commandID)->flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor)));
  14098. }
  14099. }
  14100. void ApplicationCommandManager::registerAllCommandsForTarget (ApplicationCommandTarget* target)
  14101. {
  14102. if (target != 0)
  14103. {
  14104. Array <CommandID> commandIDs;
  14105. target->getAllCommands (commandIDs);
  14106. for (int i = 0; i < commandIDs.size(); ++i)
  14107. {
  14108. ApplicationCommandInfo info (commandIDs.getUnchecked(i));
  14109. target->getCommandInfo (info.commandID, info);
  14110. registerCommand (info);
  14111. }
  14112. }
  14113. }
  14114. void ApplicationCommandManager::removeCommand (const CommandID commandID)
  14115. {
  14116. for (int i = commands.size(); --i >= 0;)
  14117. {
  14118. if (commands.getUnchecked (i)->commandID == commandID)
  14119. {
  14120. commands.remove (i);
  14121. triggerAsyncUpdate();
  14122. const Array <KeyPress> keys (keyMappings->getKeyPressesAssignedToCommand (commandID));
  14123. for (int j = keys.size(); --j >= 0;)
  14124. keyMappings->removeKeyPress (keys.getReference (j));
  14125. }
  14126. }
  14127. }
  14128. void ApplicationCommandManager::commandStatusChanged()
  14129. {
  14130. triggerAsyncUpdate();
  14131. }
  14132. const ApplicationCommandInfo* ApplicationCommandManager::getCommandForID (const CommandID commandID) const throw()
  14133. {
  14134. for (int i = commands.size(); --i >= 0;)
  14135. if (commands.getUnchecked(i)->commandID == commandID)
  14136. return commands.getUnchecked(i);
  14137. return 0;
  14138. }
  14139. const String ApplicationCommandManager::getNameOfCommand (const CommandID commandID) const throw()
  14140. {
  14141. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  14142. return (ci != 0) ? ci->shortName : String::empty;
  14143. }
  14144. const String ApplicationCommandManager::getDescriptionOfCommand (const CommandID commandID) const throw()
  14145. {
  14146. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  14147. return (ci != 0) ? (ci->description.isNotEmpty() ? ci->description : ci->shortName)
  14148. : String::empty;
  14149. }
  14150. const StringArray ApplicationCommandManager::getCommandCategories() const throw()
  14151. {
  14152. StringArray s;
  14153. for (int i = 0; i < commands.size(); ++i)
  14154. s.addIfNotAlreadyThere (commands.getUnchecked(i)->categoryName, false);
  14155. return s;
  14156. }
  14157. const Array <CommandID> ApplicationCommandManager::getCommandsInCategory (const String& categoryName) const throw()
  14158. {
  14159. Array <CommandID> results;
  14160. for (int i = 0; i < commands.size(); ++i)
  14161. if (commands.getUnchecked(i)->categoryName == categoryName)
  14162. results.add (commands.getUnchecked(i)->commandID);
  14163. return results;
  14164. }
  14165. bool ApplicationCommandManager::invokeDirectly (const CommandID commandID, const bool asynchronously)
  14166. {
  14167. ApplicationCommandTarget::InvocationInfo info (commandID);
  14168. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  14169. return invoke (info, asynchronously);
  14170. }
  14171. bool ApplicationCommandManager::invoke (const ApplicationCommandTarget::InvocationInfo& info_, const bool asynchronously)
  14172. {
  14173. // This call isn't thread-safe for use from a non-UI thread without locking the message
  14174. // manager first..
  14175. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  14176. ApplicationCommandTarget* const target = getFirstCommandTarget (info_.commandID);
  14177. if (target == 0)
  14178. return false;
  14179. ApplicationCommandInfo commandInfo (0);
  14180. target->getCommandInfo (info_.commandID, commandInfo);
  14181. ApplicationCommandTarget::InvocationInfo info (info_);
  14182. info.commandFlags = commandInfo.flags;
  14183. sendListenerInvokeCallback (info);
  14184. const bool ok = target->invoke (info, asynchronously);
  14185. commandStatusChanged();
  14186. return ok;
  14187. }
  14188. ApplicationCommandTarget* ApplicationCommandManager::getFirstCommandTarget (const CommandID)
  14189. {
  14190. return firstTarget != 0 ? firstTarget
  14191. : findDefaultComponentTarget();
  14192. }
  14193. void ApplicationCommandManager::setFirstCommandTarget (ApplicationCommandTarget* const newTarget) throw()
  14194. {
  14195. firstTarget = newTarget;
  14196. }
  14197. ApplicationCommandTarget* ApplicationCommandManager::getTargetForCommand (const CommandID commandID,
  14198. ApplicationCommandInfo& upToDateInfo)
  14199. {
  14200. ApplicationCommandTarget* target = getFirstCommandTarget (commandID);
  14201. if (target == 0)
  14202. target = JUCEApplication::getInstance();
  14203. if (target != 0)
  14204. target = target->getTargetForCommand (commandID);
  14205. if (target != 0)
  14206. target->getCommandInfo (commandID, upToDateInfo);
  14207. return target;
  14208. }
  14209. ApplicationCommandTarget* ApplicationCommandManager::findTargetForComponent (Component* c)
  14210. {
  14211. ApplicationCommandTarget* target = dynamic_cast <ApplicationCommandTarget*> (c);
  14212. if (target == 0 && c != 0)
  14213. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  14214. target = c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  14215. return target;
  14216. }
  14217. ApplicationCommandTarget* ApplicationCommandManager::findDefaultComponentTarget()
  14218. {
  14219. Component* c = Component::getCurrentlyFocusedComponent();
  14220. if (c == 0)
  14221. {
  14222. TopLevelWindow* const activeWindow = TopLevelWindow::getActiveTopLevelWindow();
  14223. if (activeWindow != 0)
  14224. {
  14225. c = activeWindow->getPeer()->getLastFocusedSubcomponent();
  14226. if (c == 0)
  14227. c = activeWindow;
  14228. }
  14229. }
  14230. if (c == 0 && Process::isForegroundProcess())
  14231. {
  14232. // getting a bit desperate now - try all desktop comps..
  14233. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  14234. {
  14235. ApplicationCommandTarget* const target
  14236. = findTargetForComponent (Desktop::getInstance().getComponent (i)
  14237. ->getPeer()->getLastFocusedSubcomponent());
  14238. if (target != 0)
  14239. return target;
  14240. }
  14241. }
  14242. if (c != 0)
  14243. {
  14244. ResizableWindow* const resizableWindow = dynamic_cast <ResizableWindow*> (c);
  14245. // if we're focused on a ResizableWindow, chances are that it's the content
  14246. // component that really should get the event. And if not, the event will
  14247. // still be passed up to the top level window anyway, so let's send it to the
  14248. // content comp.
  14249. if (resizableWindow != 0 && resizableWindow->getContentComponent() != 0)
  14250. c = resizableWindow->getContentComponent();
  14251. ApplicationCommandTarget* const target = findTargetForComponent (c);
  14252. if (target != 0)
  14253. return target;
  14254. }
  14255. return JUCEApplication::getInstance();
  14256. }
  14257. void ApplicationCommandManager::addListener (ApplicationCommandManagerListener* const listener) throw()
  14258. {
  14259. listeners.add (listener);
  14260. }
  14261. void ApplicationCommandManager::removeListener (ApplicationCommandManagerListener* const listener) throw()
  14262. {
  14263. listeners.remove (listener);
  14264. }
  14265. void ApplicationCommandManager::sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info)
  14266. {
  14267. listeners.call (&ApplicationCommandManagerListener::applicationCommandInvoked, info);
  14268. }
  14269. void ApplicationCommandManager::handleAsyncUpdate()
  14270. {
  14271. listeners.call (&ApplicationCommandManagerListener::applicationCommandListChanged);
  14272. }
  14273. void ApplicationCommandManager::globalFocusChanged (Component*)
  14274. {
  14275. commandStatusChanged();
  14276. }
  14277. END_JUCE_NAMESPACE
  14278. /*** End of inlined file: juce_ApplicationCommandManager.cpp ***/
  14279. /*** Start of inlined file: juce_ApplicationCommandTarget.cpp ***/
  14280. BEGIN_JUCE_NAMESPACE
  14281. ApplicationCommandTarget::ApplicationCommandTarget()
  14282. {
  14283. }
  14284. ApplicationCommandTarget::~ApplicationCommandTarget()
  14285. {
  14286. messageInvoker = 0;
  14287. }
  14288. bool ApplicationCommandTarget::tryToInvoke (const InvocationInfo& info, const bool async)
  14289. {
  14290. if (isCommandActive (info.commandID))
  14291. {
  14292. if (async)
  14293. {
  14294. if (messageInvoker == 0)
  14295. messageInvoker = new CommandTargetMessageInvoker (this);
  14296. messageInvoker->postMessage (new Message (0, 0, 0, new ApplicationCommandTarget::InvocationInfo (info)));
  14297. return true;
  14298. }
  14299. else
  14300. {
  14301. const bool success = perform (info);
  14302. jassert (success); // hmm - your target should have been able to perform this command. If it can't
  14303. // do it at the moment for some reason, it should clear the 'isActive' flag when it
  14304. // returns the command's info.
  14305. return success;
  14306. }
  14307. }
  14308. return false;
  14309. }
  14310. ApplicationCommandTarget* ApplicationCommandTarget::findFirstTargetParentComponent()
  14311. {
  14312. Component* c = dynamic_cast <Component*> (this);
  14313. if (c != 0)
  14314. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  14315. return c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  14316. return 0;
  14317. }
  14318. ApplicationCommandTarget* ApplicationCommandTarget::getTargetForCommand (const CommandID commandID)
  14319. {
  14320. ApplicationCommandTarget* target = this;
  14321. int depth = 0;
  14322. while (target != 0)
  14323. {
  14324. Array <CommandID> commandIDs;
  14325. target->getAllCommands (commandIDs);
  14326. if (commandIDs.contains (commandID))
  14327. return target;
  14328. target = target->getNextCommandTarget();
  14329. ++depth;
  14330. jassert (depth < 100); // could be a recursive command chain??
  14331. jassert (target != this); // definitely a recursive command chain!
  14332. if (depth > 100 || target == this)
  14333. break;
  14334. }
  14335. if (target == 0)
  14336. {
  14337. target = JUCEApplication::getInstance();
  14338. if (target != 0)
  14339. {
  14340. Array <CommandID> commandIDs;
  14341. target->getAllCommands (commandIDs);
  14342. if (commandIDs.contains (commandID))
  14343. return target;
  14344. }
  14345. }
  14346. return 0;
  14347. }
  14348. bool ApplicationCommandTarget::isCommandActive (const CommandID commandID)
  14349. {
  14350. ApplicationCommandInfo info (commandID);
  14351. info.flags = ApplicationCommandInfo::isDisabled;
  14352. getCommandInfo (commandID, info);
  14353. return (info.flags & ApplicationCommandInfo::isDisabled) == 0;
  14354. }
  14355. bool ApplicationCommandTarget::invoke (const InvocationInfo& info, const bool async)
  14356. {
  14357. ApplicationCommandTarget* target = this;
  14358. int depth = 0;
  14359. while (target != 0)
  14360. {
  14361. if (target->tryToInvoke (info, async))
  14362. return true;
  14363. target = target->getNextCommandTarget();
  14364. ++depth;
  14365. jassert (depth < 100); // could be a recursive command chain??
  14366. jassert (target != this); // definitely a recursive command chain!
  14367. if (depth > 100 || target == this)
  14368. break;
  14369. }
  14370. if (target == 0)
  14371. {
  14372. target = JUCEApplication::getInstance();
  14373. if (target != 0)
  14374. return target->tryToInvoke (info, async);
  14375. }
  14376. return false;
  14377. }
  14378. bool ApplicationCommandTarget::invokeDirectly (const CommandID commandID, const bool asynchronously)
  14379. {
  14380. ApplicationCommandTarget::InvocationInfo info (commandID);
  14381. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  14382. return invoke (info, asynchronously);
  14383. }
  14384. ApplicationCommandTarget::InvocationInfo::InvocationInfo (const CommandID commandID_) throw()
  14385. : commandID (commandID_),
  14386. commandFlags (0),
  14387. invocationMethod (direct),
  14388. originatingComponent (0),
  14389. isKeyDown (false),
  14390. millisecsSinceKeyPressed (0)
  14391. {
  14392. }
  14393. ApplicationCommandTarget::CommandTargetMessageInvoker::CommandTargetMessageInvoker (ApplicationCommandTarget* const owner_)
  14394. : owner (owner_)
  14395. {
  14396. }
  14397. ApplicationCommandTarget::CommandTargetMessageInvoker::~CommandTargetMessageInvoker()
  14398. {
  14399. }
  14400. void ApplicationCommandTarget::CommandTargetMessageInvoker::handleMessage (const Message& message)
  14401. {
  14402. const ScopedPointer <InvocationInfo> info (static_cast <InvocationInfo*> (message.pointerParameter));
  14403. owner->tryToInvoke (*info, false);
  14404. }
  14405. END_JUCE_NAMESPACE
  14406. /*** End of inlined file: juce_ApplicationCommandTarget.cpp ***/
  14407. /*** Start of inlined file: juce_ApplicationProperties.cpp ***/
  14408. BEGIN_JUCE_NAMESPACE
  14409. juce_ImplementSingleton (ApplicationProperties)
  14410. ApplicationProperties::ApplicationProperties() throw()
  14411. : msBeforeSaving (3000),
  14412. options (PropertiesFile::storeAsBinary),
  14413. commonSettingsAreReadOnly (0)
  14414. {
  14415. }
  14416. ApplicationProperties::~ApplicationProperties()
  14417. {
  14418. closeFiles();
  14419. clearSingletonInstance();
  14420. }
  14421. void ApplicationProperties::setStorageParameters (const String& applicationName,
  14422. const String& fileNameSuffix,
  14423. const String& folderName_,
  14424. const int millisecondsBeforeSaving,
  14425. const int propertiesFileOptions) throw()
  14426. {
  14427. appName = applicationName;
  14428. fileSuffix = fileNameSuffix;
  14429. folderName = folderName_;
  14430. msBeforeSaving = millisecondsBeforeSaving;
  14431. options = propertiesFileOptions;
  14432. }
  14433. bool ApplicationProperties::testWriteAccess (const bool testUserSettings,
  14434. const bool testCommonSettings,
  14435. const bool showWarningDialogOnFailure)
  14436. {
  14437. const bool userOk = (! testUserSettings) || getUserSettings()->save();
  14438. const bool commonOk = (! testCommonSettings) || getCommonSettings (false)->save();
  14439. if (! (userOk && commonOk))
  14440. {
  14441. if (showWarningDialogOnFailure)
  14442. {
  14443. String filenames;
  14444. if (userProps != 0 && ! userOk)
  14445. filenames << '\n' << userProps->getFile().getFullPathName();
  14446. if (commonProps != 0 && ! commonOk)
  14447. filenames << '\n' << commonProps->getFile().getFullPathName();
  14448. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  14449. appName + TRANS(" - Unable to save settings"),
  14450. TRANS("An error occurred when trying to save the application's settings file...\n\nIn order to save and restore its settings, ")
  14451. + appName + TRANS(" needs to be able to write to the following files:\n")
  14452. + filenames
  14453. + TRANS("\n\nMake sure that these files aren't read-only, and that the disk isn't full."));
  14454. }
  14455. return false;
  14456. }
  14457. return true;
  14458. }
  14459. void ApplicationProperties::openFiles() throw()
  14460. {
  14461. // You need to call setStorageParameters() before trying to get hold of the
  14462. // properties!
  14463. jassert (appName.isNotEmpty());
  14464. if (appName.isNotEmpty())
  14465. {
  14466. if (userProps == 0)
  14467. userProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  14468. false, msBeforeSaving, options);
  14469. if (commonProps == 0)
  14470. commonProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  14471. true, msBeforeSaving, options);
  14472. userProps->setFallbackPropertySet (commonProps);
  14473. }
  14474. }
  14475. PropertiesFile* ApplicationProperties::getUserSettings() throw()
  14476. {
  14477. if (userProps == 0)
  14478. openFiles();
  14479. return userProps;
  14480. }
  14481. PropertiesFile* ApplicationProperties::getCommonSettings (const bool returnUserPropsIfReadOnly) throw()
  14482. {
  14483. if (commonProps == 0)
  14484. openFiles();
  14485. if (returnUserPropsIfReadOnly)
  14486. {
  14487. if (commonSettingsAreReadOnly == 0)
  14488. commonSettingsAreReadOnly = commonProps->save() ? -1 : 1;
  14489. if (commonSettingsAreReadOnly > 0)
  14490. return userProps;
  14491. }
  14492. return commonProps;
  14493. }
  14494. bool ApplicationProperties::saveIfNeeded()
  14495. {
  14496. return (userProps == 0 || userProps->saveIfNeeded())
  14497. && (commonProps == 0 || commonProps->saveIfNeeded());
  14498. }
  14499. void ApplicationProperties::closeFiles()
  14500. {
  14501. userProps = 0;
  14502. commonProps = 0;
  14503. }
  14504. END_JUCE_NAMESPACE
  14505. /*** End of inlined file: juce_ApplicationProperties.cpp ***/
  14506. /*** Start of inlined file: juce_PropertiesFile.cpp ***/
  14507. BEGIN_JUCE_NAMESPACE
  14508. namespace PropertyFileConstants
  14509. {
  14510. static const int magicNumber = (int) ByteOrder::littleEndianInt ("PROP");
  14511. static const int magicNumberCompressed = (int) ByteOrder::littleEndianInt ("CPRP");
  14512. static const char* const fileTag = "PROPERTIES";
  14513. static const char* const valueTag = "VALUE";
  14514. static const char* const nameAttribute = "name";
  14515. static const char* const valueAttribute = "val";
  14516. }
  14517. PropertiesFile::PropertiesFile (const File& f, const int millisecondsBeforeSaving,
  14518. const int options_, InterProcessLock* const processLock_)
  14519. : PropertySet (ignoreCaseOfKeyNames),
  14520. file (f),
  14521. timerInterval (millisecondsBeforeSaving),
  14522. options (options_),
  14523. loadedOk (false),
  14524. needsWriting (false),
  14525. processLock (processLock_)
  14526. {
  14527. // You need to correctly specify just one storage format for the file
  14528. jassert ((options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsBinary
  14529. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsCompressedBinary
  14530. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsXML);
  14531. ProcessScopedLock pl (createProcessLock());
  14532. if (pl != 0 && ! pl->isLocked())
  14533. return; // locking failure..
  14534. ScopedPointer<InputStream> fileStream (f.createInputStream());
  14535. if (fileStream != 0)
  14536. {
  14537. int magicNumber = fileStream->readInt();
  14538. if (magicNumber == PropertyFileConstants::magicNumberCompressed)
  14539. {
  14540. fileStream = new GZIPDecompressorInputStream (new SubregionStream (fileStream.release(), 4, -1, true), true);
  14541. magicNumber = PropertyFileConstants::magicNumber;
  14542. }
  14543. if (magicNumber == PropertyFileConstants::magicNumber)
  14544. {
  14545. loadedOk = true;
  14546. BufferedInputStream in (fileStream.release(), 2048, true);
  14547. int numValues = in.readInt();
  14548. while (--numValues >= 0 && ! in.isExhausted())
  14549. {
  14550. const String key (in.readString());
  14551. const String value (in.readString());
  14552. jassert (key.isNotEmpty());
  14553. if (key.isNotEmpty())
  14554. getAllProperties().set (key, value);
  14555. }
  14556. }
  14557. else
  14558. {
  14559. // Not a binary props file - let's see if it's XML..
  14560. fileStream = 0;
  14561. XmlDocument parser (f);
  14562. ScopedPointer<XmlElement> doc (parser.getDocumentElement (true));
  14563. if (doc != 0 && doc->hasTagName (PropertyFileConstants::fileTag))
  14564. {
  14565. doc = parser.getDocumentElement();
  14566. if (doc != 0)
  14567. {
  14568. loadedOk = true;
  14569. forEachXmlChildElementWithTagName (*doc, e, PropertyFileConstants::valueTag)
  14570. {
  14571. const String name (e->getStringAttribute (PropertyFileConstants::nameAttribute));
  14572. if (name.isNotEmpty())
  14573. {
  14574. getAllProperties().set (name,
  14575. e->getFirstChildElement() != 0
  14576. ? e->getFirstChildElement()->createDocument (String::empty, true)
  14577. : e->getStringAttribute (PropertyFileConstants::valueAttribute));
  14578. }
  14579. }
  14580. }
  14581. else
  14582. {
  14583. // must be a pretty broken XML file we're trying to parse here,
  14584. // or a sign that this object needs an InterProcessLock,
  14585. // or just a failure reading the file. This last reason is why
  14586. // we don't jassertfalse here.
  14587. }
  14588. }
  14589. }
  14590. }
  14591. else
  14592. {
  14593. loadedOk = ! f.exists();
  14594. }
  14595. }
  14596. PropertiesFile::~PropertiesFile()
  14597. {
  14598. if (! saveIfNeeded())
  14599. jassertfalse;
  14600. }
  14601. InterProcessLock::ScopedLockType* PropertiesFile::createProcessLock() const
  14602. {
  14603. return processLock != 0 ? new InterProcessLock::ScopedLockType (*processLock) : 0;
  14604. }
  14605. bool PropertiesFile::saveIfNeeded()
  14606. {
  14607. const ScopedLock sl (getLock());
  14608. return (! needsWriting) || save();
  14609. }
  14610. bool PropertiesFile::needsToBeSaved() const
  14611. {
  14612. const ScopedLock sl (getLock());
  14613. return needsWriting;
  14614. }
  14615. void PropertiesFile::setNeedsToBeSaved (const bool needsToBeSaved_)
  14616. {
  14617. const ScopedLock sl (getLock());
  14618. needsWriting = needsToBeSaved_;
  14619. }
  14620. bool PropertiesFile::save()
  14621. {
  14622. const ScopedLock sl (getLock());
  14623. stopTimer();
  14624. if (file == File::nonexistent
  14625. || file.isDirectory()
  14626. || ! file.getParentDirectory().createDirectory())
  14627. return false;
  14628. if ((options & storeAsXML) != 0)
  14629. {
  14630. XmlElement doc (PropertyFileConstants::fileTag);
  14631. for (int i = 0; i < getAllProperties().size(); ++i)
  14632. {
  14633. XmlElement* const e = doc.createNewChildElement (PropertyFileConstants::valueTag);
  14634. e->setAttribute (PropertyFileConstants::nameAttribute, getAllProperties().getAllKeys() [i]);
  14635. // if the value seems to contain xml, store it as such..
  14636. XmlDocument xmlContent (getAllProperties().getAllValues() [i]);
  14637. XmlElement* const childElement = xmlContent.getDocumentElement();
  14638. if (childElement != 0)
  14639. e->addChildElement (childElement);
  14640. else
  14641. e->setAttribute (PropertyFileConstants::valueAttribute,
  14642. getAllProperties().getAllValues() [i]);
  14643. }
  14644. ProcessScopedLock pl (createProcessLock());
  14645. if (pl != 0 && ! pl->isLocked())
  14646. return false; // locking failure..
  14647. if (doc.writeToFile (file, String::empty))
  14648. {
  14649. needsWriting = false;
  14650. return true;
  14651. }
  14652. }
  14653. else
  14654. {
  14655. ProcessScopedLock pl (createProcessLock());
  14656. if (pl != 0 && ! pl->isLocked())
  14657. return false; // locking failure..
  14658. TemporaryFile tempFile (file);
  14659. ScopedPointer <OutputStream> out (tempFile.getFile().createOutputStream());
  14660. if (out != 0)
  14661. {
  14662. if ((options & storeAsCompressedBinary) != 0)
  14663. {
  14664. out->writeInt (PropertyFileConstants::magicNumberCompressed);
  14665. out->flush();
  14666. out = new GZIPCompressorOutputStream (out.release(), 9, true);
  14667. }
  14668. else
  14669. {
  14670. // have you set up the storage option flags correctly?
  14671. jassert ((options & storeAsBinary) != 0);
  14672. out->writeInt (PropertyFileConstants::magicNumber);
  14673. }
  14674. const int numProperties = getAllProperties().size();
  14675. out->writeInt (numProperties);
  14676. for (int i = 0; i < numProperties; ++i)
  14677. {
  14678. out->writeString (getAllProperties().getAllKeys() [i]);
  14679. out->writeString (getAllProperties().getAllValues() [i]);
  14680. }
  14681. out = 0;
  14682. if (tempFile.overwriteTargetFileWithTemporary())
  14683. {
  14684. needsWriting = false;
  14685. return true;
  14686. }
  14687. }
  14688. }
  14689. return false;
  14690. }
  14691. void PropertiesFile::timerCallback()
  14692. {
  14693. saveIfNeeded();
  14694. }
  14695. void PropertiesFile::propertyChanged()
  14696. {
  14697. sendChangeMessage (this);
  14698. needsWriting = true;
  14699. if (timerInterval > 0)
  14700. startTimer (timerInterval);
  14701. else if (timerInterval == 0)
  14702. saveIfNeeded();
  14703. }
  14704. const File PropertiesFile::getDefaultAppSettingsFile (const String& applicationName,
  14705. const String& fileNameSuffix,
  14706. const String& folderName,
  14707. const bool commonToAllUsers)
  14708. {
  14709. // mustn't have illegal characters in this name..
  14710. jassert (applicationName == File::createLegalFileName (applicationName));
  14711. #if JUCE_MAC || JUCE_IPHONE
  14712. File dir (commonToAllUsers ? "/Library/Preferences"
  14713. : "~/Library/Preferences");
  14714. if (folderName.isNotEmpty())
  14715. dir = dir.getChildFile (folderName);
  14716. #endif
  14717. #ifdef JUCE_LINUX
  14718. const File dir ((commonToAllUsers ? "/var/" : "~/")
  14719. + (folderName.isNotEmpty() ? folderName
  14720. : ("." + applicationName)));
  14721. #endif
  14722. #if JUCE_WINDOWS
  14723. File dir (File::getSpecialLocation (commonToAllUsers ? File::commonApplicationDataDirectory
  14724. : File::userApplicationDataDirectory));
  14725. if (dir == File::nonexistent)
  14726. return File::nonexistent;
  14727. dir = dir.getChildFile (folderName.isNotEmpty() ? folderName
  14728. : applicationName);
  14729. #endif
  14730. return dir.getChildFile (applicationName)
  14731. .withFileExtension (fileNameSuffix);
  14732. }
  14733. PropertiesFile* PropertiesFile::createDefaultAppPropertiesFile (const String& applicationName,
  14734. const String& fileNameSuffix,
  14735. const String& folderName,
  14736. const bool commonToAllUsers,
  14737. const int millisecondsBeforeSaving,
  14738. const int propertiesFileOptions,
  14739. InterProcessLock* processLock_)
  14740. {
  14741. const File file (getDefaultAppSettingsFile (applicationName,
  14742. fileNameSuffix,
  14743. folderName,
  14744. commonToAllUsers));
  14745. jassert (file != File::nonexistent);
  14746. if (file == File::nonexistent)
  14747. return 0;
  14748. return new PropertiesFile (file, millisecondsBeforeSaving, propertiesFileOptions,processLock_);
  14749. }
  14750. END_JUCE_NAMESPACE
  14751. /*** End of inlined file: juce_PropertiesFile.cpp ***/
  14752. /*** Start of inlined file: juce_FileBasedDocument.cpp ***/
  14753. BEGIN_JUCE_NAMESPACE
  14754. FileBasedDocument::FileBasedDocument (const String& fileExtension_,
  14755. const String& fileWildcard_,
  14756. const String& openFileDialogTitle_,
  14757. const String& saveFileDialogTitle_)
  14758. : changedSinceSave (false),
  14759. fileExtension (fileExtension_),
  14760. fileWildcard (fileWildcard_),
  14761. openFileDialogTitle (openFileDialogTitle_),
  14762. saveFileDialogTitle (saveFileDialogTitle_)
  14763. {
  14764. }
  14765. FileBasedDocument::~FileBasedDocument()
  14766. {
  14767. }
  14768. void FileBasedDocument::setChangedFlag (const bool hasChanged)
  14769. {
  14770. if (changedSinceSave != hasChanged)
  14771. {
  14772. changedSinceSave = hasChanged;
  14773. sendChangeMessage (this);
  14774. }
  14775. }
  14776. void FileBasedDocument::changed()
  14777. {
  14778. changedSinceSave = true;
  14779. sendChangeMessage (this);
  14780. }
  14781. void FileBasedDocument::setFile (const File& newFile)
  14782. {
  14783. if (documentFile != newFile)
  14784. {
  14785. documentFile = newFile;
  14786. changed();
  14787. }
  14788. }
  14789. bool FileBasedDocument::loadFrom (const File& newFile,
  14790. const bool showMessageOnFailure)
  14791. {
  14792. MouseCursor::showWaitCursor();
  14793. const File oldFile (documentFile);
  14794. documentFile = newFile;
  14795. String error;
  14796. if (newFile.existsAsFile())
  14797. {
  14798. error = loadDocument (newFile);
  14799. if (error.isEmpty())
  14800. {
  14801. setChangedFlag (false);
  14802. MouseCursor::hideWaitCursor();
  14803. setLastDocumentOpened (newFile);
  14804. return true;
  14805. }
  14806. }
  14807. else
  14808. {
  14809. error = "The file doesn't exist";
  14810. }
  14811. documentFile = oldFile;
  14812. MouseCursor::hideWaitCursor();
  14813. if (showMessageOnFailure)
  14814. {
  14815. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  14816. TRANS("Failed to open file..."),
  14817. TRANS("There was an error while trying to load the file:\n\n")
  14818. + newFile.getFullPathName()
  14819. + "\n\n"
  14820. + error);
  14821. }
  14822. return false;
  14823. }
  14824. bool FileBasedDocument::loadFromUserSpecifiedFile (const bool showMessageOnFailure)
  14825. {
  14826. FileChooser fc (openFileDialogTitle,
  14827. getLastDocumentOpened(),
  14828. fileWildcard);
  14829. if (fc.browseForFileToOpen())
  14830. return loadFrom (fc.getResult(), showMessageOnFailure);
  14831. return false;
  14832. }
  14833. FileBasedDocument::SaveResult FileBasedDocument::save (const bool askUserForFileIfNotSpecified,
  14834. const bool showMessageOnFailure)
  14835. {
  14836. return saveAs (documentFile,
  14837. false,
  14838. askUserForFileIfNotSpecified,
  14839. showMessageOnFailure);
  14840. }
  14841. FileBasedDocument::SaveResult FileBasedDocument::saveAs (const File& newFile,
  14842. const bool warnAboutOverwritingExistingFiles,
  14843. const bool askUserForFileIfNotSpecified,
  14844. const bool showMessageOnFailure)
  14845. {
  14846. if (newFile == File::nonexistent)
  14847. {
  14848. if (askUserForFileIfNotSpecified)
  14849. {
  14850. return saveAsInteractive (true);
  14851. }
  14852. else
  14853. {
  14854. // can't save to an unspecified file
  14855. jassertfalse;
  14856. return failedToWriteToFile;
  14857. }
  14858. }
  14859. if (warnAboutOverwritingExistingFiles && newFile.exists())
  14860. {
  14861. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  14862. TRANS("File already exists"),
  14863. TRANS("There's already a file called:\n\n")
  14864. + newFile.getFullPathName()
  14865. + TRANS("\n\nAre you sure you want to overwrite it?"),
  14866. TRANS("overwrite"),
  14867. TRANS("cancel")))
  14868. {
  14869. return userCancelledSave;
  14870. }
  14871. }
  14872. MouseCursor::showWaitCursor();
  14873. const File oldFile (documentFile);
  14874. documentFile = newFile;
  14875. String error (saveDocument (newFile));
  14876. if (error.isEmpty())
  14877. {
  14878. setChangedFlag (false);
  14879. MouseCursor::hideWaitCursor();
  14880. return savedOk;
  14881. }
  14882. documentFile = oldFile;
  14883. MouseCursor::hideWaitCursor();
  14884. if (showMessageOnFailure)
  14885. {
  14886. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  14887. TRANS("Error writing to file..."),
  14888. TRANS("An error occurred while trying to save \"")
  14889. + getDocumentTitle()
  14890. + TRANS("\" to the file:\n\n")
  14891. + newFile.getFullPathName()
  14892. + "\n\n"
  14893. + error);
  14894. }
  14895. return failedToWriteToFile;
  14896. }
  14897. FileBasedDocument::SaveResult FileBasedDocument::saveIfNeededAndUserAgrees()
  14898. {
  14899. if (! hasChangedSinceSaved())
  14900. return savedOk;
  14901. const int r = AlertWindow::showYesNoCancelBox (AlertWindow::QuestionIcon,
  14902. TRANS("Closing document..."),
  14903. TRANS("Do you want to save the changes to \"")
  14904. + getDocumentTitle() + "\"?",
  14905. TRANS("save"),
  14906. TRANS("discard changes"),
  14907. TRANS("cancel"));
  14908. if (r == 1)
  14909. {
  14910. // save changes
  14911. return save (true, true);
  14912. }
  14913. else if (r == 2)
  14914. {
  14915. // discard changes
  14916. return savedOk;
  14917. }
  14918. return userCancelledSave;
  14919. }
  14920. FileBasedDocument::SaveResult FileBasedDocument::saveAsInteractive (const bool warnAboutOverwritingExistingFiles)
  14921. {
  14922. File f;
  14923. if (documentFile.existsAsFile())
  14924. f = documentFile;
  14925. else
  14926. f = getLastDocumentOpened();
  14927. String legalFilename (File::createLegalFileName (getDocumentTitle()));
  14928. if (legalFilename.isEmpty())
  14929. legalFilename = "unnamed";
  14930. if (f.existsAsFile() || f.getParentDirectory().isDirectory())
  14931. f = f.getSiblingFile (legalFilename);
  14932. else
  14933. f = File::getSpecialLocation (File::userDocumentsDirectory).getChildFile (legalFilename);
  14934. f = f.withFileExtension (fileExtension)
  14935. .getNonexistentSibling (true);
  14936. FileChooser fc (saveFileDialogTitle, f, fileWildcard);
  14937. if (fc.browseForFileToSave (warnAboutOverwritingExistingFiles))
  14938. {
  14939. setLastDocumentOpened (fc.getResult());
  14940. File chosen (fc.getResult());
  14941. if (chosen.getFileExtension().isEmpty())
  14942. {
  14943. chosen = chosen.withFileExtension (fileExtension);
  14944. if (chosen.exists())
  14945. {
  14946. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  14947. TRANS("File already exists"),
  14948. TRANS("There's already a file called:")
  14949. + "\n\n" + chosen.getFullPathName()
  14950. + "\n\n" + TRANS("Are you sure you want to overwrite it?"),
  14951. TRANS("overwrite"),
  14952. TRANS("cancel")))
  14953. {
  14954. return userCancelledSave;
  14955. }
  14956. }
  14957. }
  14958. return saveAs (chosen, false, false, true);
  14959. }
  14960. return userCancelledSave;
  14961. }
  14962. END_JUCE_NAMESPACE
  14963. /*** End of inlined file: juce_FileBasedDocument.cpp ***/
  14964. /*** Start of inlined file: juce_RecentlyOpenedFilesList.cpp ***/
  14965. BEGIN_JUCE_NAMESPACE
  14966. RecentlyOpenedFilesList::RecentlyOpenedFilesList()
  14967. : maxNumberOfItems (10)
  14968. {
  14969. }
  14970. RecentlyOpenedFilesList::~RecentlyOpenedFilesList()
  14971. {
  14972. }
  14973. void RecentlyOpenedFilesList::setMaxNumberOfItems (const int newMaxNumber)
  14974. {
  14975. maxNumberOfItems = jmax (1, newMaxNumber);
  14976. while (getNumFiles() > maxNumberOfItems)
  14977. files.remove (getNumFiles() - 1);
  14978. }
  14979. int RecentlyOpenedFilesList::getNumFiles() const
  14980. {
  14981. return files.size();
  14982. }
  14983. const File RecentlyOpenedFilesList::getFile (const int index) const
  14984. {
  14985. return File (files [index]);
  14986. }
  14987. void RecentlyOpenedFilesList::clear()
  14988. {
  14989. files.clear();
  14990. }
  14991. void RecentlyOpenedFilesList::addFile (const File& file)
  14992. {
  14993. const String path (file.getFullPathName());
  14994. files.removeString (path, true);
  14995. files.insert (0, path);
  14996. setMaxNumberOfItems (maxNumberOfItems);
  14997. }
  14998. void RecentlyOpenedFilesList::removeNonExistentFiles()
  14999. {
  15000. for (int i = getNumFiles(); --i >= 0;)
  15001. if (! getFile(i).exists())
  15002. files.remove (i);
  15003. }
  15004. int RecentlyOpenedFilesList::createPopupMenuItems (PopupMenu& menuToAddTo,
  15005. const int baseItemId,
  15006. const bool showFullPaths,
  15007. const bool dontAddNonExistentFiles,
  15008. const File** filesToAvoid)
  15009. {
  15010. int num = 0;
  15011. for (int i = 0; i < getNumFiles(); ++i)
  15012. {
  15013. const File f (getFile(i));
  15014. if ((! dontAddNonExistentFiles) || f.exists())
  15015. {
  15016. bool needsAvoiding = false;
  15017. if (filesToAvoid != 0)
  15018. {
  15019. const File** avoid = filesToAvoid;
  15020. while (*avoid != 0)
  15021. {
  15022. if (f == **avoid)
  15023. {
  15024. needsAvoiding = true;
  15025. break;
  15026. }
  15027. ++avoid;
  15028. }
  15029. }
  15030. if (! needsAvoiding)
  15031. {
  15032. menuToAddTo.addItem (baseItemId + i,
  15033. showFullPaths ? f.getFullPathName()
  15034. : f.getFileName());
  15035. ++num;
  15036. }
  15037. }
  15038. }
  15039. return num;
  15040. }
  15041. const String RecentlyOpenedFilesList::toString() const
  15042. {
  15043. return files.joinIntoString ("\n");
  15044. }
  15045. void RecentlyOpenedFilesList::restoreFromString (const String& stringifiedVersion)
  15046. {
  15047. clear();
  15048. files.addLines (stringifiedVersion);
  15049. setMaxNumberOfItems (maxNumberOfItems);
  15050. }
  15051. END_JUCE_NAMESPACE
  15052. /*** End of inlined file: juce_RecentlyOpenedFilesList.cpp ***/
  15053. /*** Start of inlined file: juce_UndoManager.cpp ***/
  15054. BEGIN_JUCE_NAMESPACE
  15055. UndoManager::UndoManager (const int maxNumberOfUnitsToKeep,
  15056. const int minimumTransactions)
  15057. : totalUnitsStored (0),
  15058. nextIndex (0),
  15059. newTransaction (true),
  15060. reentrancyCheck (false)
  15061. {
  15062. setMaxNumberOfStoredUnits (maxNumberOfUnitsToKeep,
  15063. minimumTransactions);
  15064. }
  15065. UndoManager::~UndoManager()
  15066. {
  15067. clearUndoHistory();
  15068. }
  15069. void UndoManager::clearUndoHistory()
  15070. {
  15071. transactions.clear();
  15072. transactionNames.clear();
  15073. totalUnitsStored = 0;
  15074. nextIndex = 0;
  15075. sendChangeMessage (this);
  15076. }
  15077. int UndoManager::getNumberOfUnitsTakenUpByStoredCommands() const
  15078. {
  15079. return totalUnitsStored;
  15080. }
  15081. void UndoManager::setMaxNumberOfStoredUnits (const int maxNumberOfUnitsToKeep,
  15082. const int minimumTransactions)
  15083. {
  15084. maxNumUnitsToKeep = jmax (1, maxNumberOfUnitsToKeep);
  15085. minimumTransactionsToKeep = jmax (1, minimumTransactions);
  15086. }
  15087. bool UndoManager::perform (UndoableAction* const command_, const String& actionName)
  15088. {
  15089. if (command_ != 0)
  15090. {
  15091. ScopedPointer<UndoableAction> command (command_);
  15092. if (actionName.isNotEmpty())
  15093. currentTransactionName = actionName;
  15094. if (reentrancyCheck)
  15095. {
  15096. jassertfalse; // don't call perform() recursively from the UndoableAction::perform() or
  15097. // undo() methods, or else these actions won't actually get done.
  15098. return false;
  15099. }
  15100. else if (command->perform())
  15101. {
  15102. OwnedArray<UndoableAction>* commandSet = transactions [nextIndex - 1];
  15103. if (commandSet != 0 && ! newTransaction)
  15104. {
  15105. UndoableAction* lastAction = commandSet->getLast();
  15106. if (lastAction != 0)
  15107. {
  15108. UndoableAction* coalescedAction = lastAction->createCoalescedAction (command);
  15109. if (coalescedAction != 0)
  15110. {
  15111. command = coalescedAction;
  15112. totalUnitsStored -= lastAction->getSizeInUnits();
  15113. commandSet->removeLast();
  15114. }
  15115. }
  15116. }
  15117. else
  15118. {
  15119. commandSet = new OwnedArray<UndoableAction>();
  15120. transactions.insert (nextIndex, commandSet);
  15121. transactionNames.insert (nextIndex, currentTransactionName);
  15122. ++nextIndex;
  15123. }
  15124. totalUnitsStored += command->getSizeInUnits();
  15125. commandSet->add (command.release());
  15126. newTransaction = false;
  15127. while (nextIndex < transactions.size())
  15128. {
  15129. const OwnedArray <UndoableAction>* const lastSet = transactions.getLast();
  15130. for (int i = lastSet->size(); --i >= 0;)
  15131. totalUnitsStored -= lastSet->getUnchecked (i)->getSizeInUnits();
  15132. transactions.removeLast();
  15133. transactionNames.remove (transactionNames.size() - 1);
  15134. }
  15135. while (nextIndex > 0
  15136. && totalUnitsStored > maxNumUnitsToKeep
  15137. && transactions.size() > minimumTransactionsToKeep)
  15138. {
  15139. const OwnedArray <UndoableAction>* const firstSet = transactions.getFirst();
  15140. for (int i = firstSet->size(); --i >= 0;)
  15141. totalUnitsStored -= firstSet->getUnchecked (i)->getSizeInUnits();
  15142. jassert (totalUnitsStored >= 0); // something fishy going on if this fails!
  15143. transactions.remove (0);
  15144. transactionNames.remove (0);
  15145. --nextIndex;
  15146. }
  15147. sendChangeMessage (this);
  15148. return true;
  15149. }
  15150. }
  15151. return false;
  15152. }
  15153. void UndoManager::beginNewTransaction (const String& actionName)
  15154. {
  15155. newTransaction = true;
  15156. currentTransactionName = actionName;
  15157. }
  15158. void UndoManager::setCurrentTransactionName (const String& newName)
  15159. {
  15160. currentTransactionName = newName;
  15161. }
  15162. bool UndoManager::canUndo() const
  15163. {
  15164. return nextIndex > 0;
  15165. }
  15166. bool UndoManager::canRedo() const
  15167. {
  15168. return nextIndex < transactions.size();
  15169. }
  15170. const String UndoManager::getUndoDescription() const
  15171. {
  15172. return transactionNames [nextIndex - 1];
  15173. }
  15174. const String UndoManager::getRedoDescription() const
  15175. {
  15176. return transactionNames [nextIndex];
  15177. }
  15178. bool UndoManager::undo()
  15179. {
  15180. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex - 1];
  15181. if (commandSet == 0)
  15182. return false;
  15183. reentrancyCheck = true;
  15184. bool failed = false;
  15185. for (int i = commandSet->size(); --i >= 0;)
  15186. {
  15187. if (! commandSet->getUnchecked(i)->undo())
  15188. {
  15189. jassertfalse;
  15190. failed = true;
  15191. break;
  15192. }
  15193. }
  15194. reentrancyCheck = false;
  15195. if (failed)
  15196. clearUndoHistory();
  15197. else
  15198. --nextIndex;
  15199. beginNewTransaction();
  15200. sendChangeMessage (this);
  15201. return true;
  15202. }
  15203. bool UndoManager::redo()
  15204. {
  15205. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex];
  15206. if (commandSet == 0)
  15207. return false;
  15208. reentrancyCheck = true;
  15209. bool failed = false;
  15210. for (int i = 0; i < commandSet->size(); ++i)
  15211. {
  15212. if (! commandSet->getUnchecked(i)->perform())
  15213. {
  15214. jassertfalse;
  15215. failed = true;
  15216. break;
  15217. }
  15218. }
  15219. reentrancyCheck = false;
  15220. if (failed)
  15221. clearUndoHistory();
  15222. else
  15223. ++nextIndex;
  15224. beginNewTransaction();
  15225. sendChangeMessage (this);
  15226. return true;
  15227. }
  15228. bool UndoManager::undoCurrentTransactionOnly()
  15229. {
  15230. return newTransaction ? false : undo();
  15231. }
  15232. void UndoManager::getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const
  15233. {
  15234. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  15235. if (commandSet != 0 && ! newTransaction)
  15236. {
  15237. for (int i = 0; i < commandSet->size(); ++i)
  15238. actionsFound.add (commandSet->getUnchecked(i));
  15239. }
  15240. }
  15241. int UndoManager::getNumActionsInCurrentTransaction() const
  15242. {
  15243. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  15244. if (commandSet != 0 && ! newTransaction)
  15245. return commandSet->size();
  15246. return 0;
  15247. }
  15248. END_JUCE_NAMESPACE
  15249. /*** End of inlined file: juce_UndoManager.cpp ***/
  15250. /*** Start of inlined file: juce_AiffAudioFormat.cpp ***/
  15251. BEGIN_JUCE_NAMESPACE
  15252. static const char* const aiffFormatName = "AIFF file";
  15253. static const char* const aiffExtensions[] = { ".aiff", ".aif", 0 };
  15254. class AiffAudioFormatReader : public AudioFormatReader
  15255. {
  15256. public:
  15257. int bytesPerFrame;
  15258. int64 dataChunkStart;
  15259. bool littleEndian;
  15260. AiffAudioFormatReader (InputStream* in)
  15261. : AudioFormatReader (in, TRANS (aiffFormatName))
  15262. {
  15263. if (input->readInt() == chunkName ("FORM"))
  15264. {
  15265. const int len = input->readIntBigEndian();
  15266. const int64 end = input->getPosition() + len;
  15267. const int nextType = input->readInt();
  15268. if (nextType == chunkName ("AIFF") || nextType == chunkName ("AIFC"))
  15269. {
  15270. bool hasGotVer = false;
  15271. bool hasGotData = false;
  15272. bool hasGotType = false;
  15273. while (input->getPosition() < end)
  15274. {
  15275. const int type = input->readInt();
  15276. const uint32 length = (uint32) input->readIntBigEndian();
  15277. const int64 chunkEnd = input->getPosition() + length;
  15278. if (type == chunkName ("FVER"))
  15279. {
  15280. hasGotVer = true;
  15281. const int ver = input->readIntBigEndian();
  15282. if (ver != 0 && ver != (int)0xa2805140)
  15283. break;
  15284. }
  15285. else if (type == chunkName ("COMM"))
  15286. {
  15287. hasGotType = true;
  15288. numChannels = (unsigned int)input->readShortBigEndian();
  15289. lengthInSamples = input->readIntBigEndian();
  15290. bitsPerSample = input->readShortBigEndian();
  15291. bytesPerFrame = (numChannels * bitsPerSample) >> 3;
  15292. unsigned char sampleRateBytes[10];
  15293. input->read (sampleRateBytes, 10);
  15294. const int byte0 = sampleRateBytes[0];
  15295. if ((byte0 & 0x80) != 0
  15296. || byte0 <= 0x3F || byte0 > 0x40
  15297. || (byte0 == 0x40 && sampleRateBytes[1] > 0x1C))
  15298. break;
  15299. unsigned int sampRate = ByteOrder::bigEndianInt (sampleRateBytes + 2);
  15300. sampRate >>= (16414 - ByteOrder::bigEndianShort (sampleRateBytes));
  15301. sampleRate = (int) sampRate;
  15302. if (length <= 18)
  15303. {
  15304. // some types don't have a chunk large enough to include a compression
  15305. // type, so assume it's just big-endian pcm
  15306. littleEndian = false;
  15307. }
  15308. else
  15309. {
  15310. const int compType = input->readInt();
  15311. if (compType == chunkName ("NONE") || compType == chunkName ("twos"))
  15312. {
  15313. littleEndian = false;
  15314. }
  15315. else if (compType == chunkName ("sowt"))
  15316. {
  15317. littleEndian = true;
  15318. }
  15319. else
  15320. {
  15321. sampleRate = 0;
  15322. break;
  15323. }
  15324. }
  15325. }
  15326. else if (type == chunkName ("SSND"))
  15327. {
  15328. hasGotData = true;
  15329. const int offset = input->readIntBigEndian();
  15330. dataChunkStart = input->getPosition() + 4 + offset;
  15331. lengthInSamples = (bytesPerFrame > 0) ? jmin (lengthInSamples, (int64) (length / bytesPerFrame)) : 0;
  15332. }
  15333. else if ((hasGotVer && hasGotData && hasGotType)
  15334. || chunkEnd < input->getPosition()
  15335. || input->isExhausted())
  15336. {
  15337. break;
  15338. }
  15339. input->setPosition (chunkEnd);
  15340. }
  15341. }
  15342. }
  15343. }
  15344. ~AiffAudioFormatReader()
  15345. {
  15346. }
  15347. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  15348. int64 startSampleInFile, int numSamples)
  15349. {
  15350. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  15351. if (samplesAvailable < numSamples)
  15352. {
  15353. for (int i = numDestChannels; --i >= 0;)
  15354. if (destSamples[i] != 0)
  15355. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  15356. numSamples = (int) samplesAvailable;
  15357. }
  15358. if (numSamples <= 0)
  15359. return true;
  15360. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  15361. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  15362. char tempBuffer [tempBufSize];
  15363. while (numSamples > 0)
  15364. {
  15365. int* left = destSamples[0];
  15366. if (left != 0)
  15367. left += startOffsetInDestBuffer;
  15368. int* right = numDestChannels > 1 ? destSamples[1] : 0;
  15369. if (right != 0)
  15370. right += startOffsetInDestBuffer;
  15371. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  15372. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  15373. if (bytesRead < numThisTime * bytesPerFrame)
  15374. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  15375. if (bitsPerSample == 16)
  15376. {
  15377. if (littleEndian)
  15378. {
  15379. const short* src = reinterpret_cast <const short*> (tempBuffer);
  15380. if (numChannels > 1)
  15381. {
  15382. if (left == 0)
  15383. {
  15384. for (int i = numThisTime; --i >= 0;)
  15385. {
  15386. *right++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  15387. ++src;
  15388. }
  15389. }
  15390. else if (right == 0)
  15391. {
  15392. for (int i = numThisTime; --i >= 0;)
  15393. {
  15394. ++src;
  15395. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  15396. }
  15397. }
  15398. else
  15399. {
  15400. for (int i = numThisTime; --i >= 0;)
  15401. {
  15402. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  15403. *right++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  15404. }
  15405. }
  15406. }
  15407. else
  15408. {
  15409. for (int i = numThisTime; --i >= 0;)
  15410. {
  15411. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  15412. }
  15413. }
  15414. }
  15415. else
  15416. {
  15417. const char* src = tempBuffer;
  15418. if (numChannels > 1)
  15419. {
  15420. if (left == 0)
  15421. {
  15422. for (int i = numThisTime; --i >= 0;)
  15423. {
  15424. *right++ = ByteOrder::bigEndianShort (src) << 16;
  15425. src += 4;
  15426. }
  15427. }
  15428. else if (right == 0)
  15429. {
  15430. for (int i = numThisTime; --i >= 0;)
  15431. {
  15432. src += 2;
  15433. *left++ = ByteOrder::bigEndianShort (src) << 16;
  15434. src += 2;
  15435. }
  15436. }
  15437. else
  15438. {
  15439. for (int i = numThisTime; --i >= 0;)
  15440. {
  15441. *left++ = ByteOrder::bigEndianShort (src) << 16;
  15442. src += 2;
  15443. *right++ = ByteOrder::bigEndianShort (src) << 16;
  15444. src += 2;
  15445. }
  15446. }
  15447. }
  15448. else
  15449. {
  15450. for (int i = numThisTime; --i >= 0;)
  15451. {
  15452. *left++ = ByteOrder::bigEndianShort (src) << 16;
  15453. src += 2;
  15454. }
  15455. }
  15456. }
  15457. }
  15458. else if (bitsPerSample == 24)
  15459. {
  15460. const char* src = (const char*)tempBuffer;
  15461. if (littleEndian)
  15462. {
  15463. if (numChannels > 1)
  15464. {
  15465. if (left == 0)
  15466. {
  15467. for (int i = numThisTime; --i >= 0;)
  15468. {
  15469. *right++ = ByteOrder::littleEndian24Bit (src) << 8;
  15470. src += 6;
  15471. }
  15472. }
  15473. else if (right == 0)
  15474. {
  15475. for (int i = numThisTime; --i >= 0;)
  15476. {
  15477. src += 3;
  15478. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  15479. src += 3;
  15480. }
  15481. }
  15482. else
  15483. {
  15484. for (int i = numThisTime; --i >= 0;)
  15485. {
  15486. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  15487. src += 3;
  15488. *right++ = ByteOrder::littleEndian24Bit (src) << 8;
  15489. src += 3;
  15490. }
  15491. }
  15492. }
  15493. else
  15494. {
  15495. for (int i = numThisTime; --i >= 0;)
  15496. {
  15497. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  15498. src += 3;
  15499. }
  15500. }
  15501. }
  15502. else
  15503. {
  15504. if (numChannels > 1)
  15505. {
  15506. if (left == 0)
  15507. {
  15508. for (int i = numThisTime; --i >= 0;)
  15509. {
  15510. *right++ = ByteOrder::bigEndian24Bit (src) << 8;
  15511. src += 6;
  15512. }
  15513. }
  15514. else if (right == 0)
  15515. {
  15516. for (int i = numThisTime; --i >= 0;)
  15517. {
  15518. src += 3;
  15519. *left++ = ByteOrder::bigEndian24Bit (src) << 8;
  15520. src += 3;
  15521. }
  15522. }
  15523. else
  15524. {
  15525. for (int i = numThisTime; --i >= 0;)
  15526. {
  15527. *left++ = ByteOrder::bigEndian24Bit (src) << 8;
  15528. src += 3;
  15529. *right++ = ByteOrder::bigEndian24Bit (src) << 8;
  15530. src += 3;
  15531. }
  15532. }
  15533. }
  15534. else
  15535. {
  15536. for (int i = numThisTime; --i >= 0;)
  15537. {
  15538. *left++ = ByteOrder::bigEndian24Bit (src) << 8;
  15539. src += 3;
  15540. }
  15541. }
  15542. }
  15543. }
  15544. else if (bitsPerSample == 32)
  15545. {
  15546. const unsigned int* src = reinterpret_cast <const unsigned int*> (tempBuffer);
  15547. unsigned int* l = reinterpret_cast <unsigned int*> (left);
  15548. unsigned int* r = reinterpret_cast <unsigned int*> (right);
  15549. if (littleEndian)
  15550. {
  15551. if (numChannels > 1)
  15552. {
  15553. if (l == 0)
  15554. {
  15555. for (int i = numThisTime; --i >= 0;)
  15556. {
  15557. ++src;
  15558. *r++ = ByteOrder::swapIfBigEndian (*src++);
  15559. }
  15560. }
  15561. else if (r == 0)
  15562. {
  15563. for (int i = numThisTime; --i >= 0;)
  15564. {
  15565. *l++ = ByteOrder::swapIfBigEndian (*src++);
  15566. ++src;
  15567. }
  15568. }
  15569. else
  15570. {
  15571. for (int i = numThisTime; --i >= 0;)
  15572. {
  15573. *l++ = ByteOrder::swapIfBigEndian (*src++);
  15574. *r++ = ByteOrder::swapIfBigEndian (*src++);
  15575. }
  15576. }
  15577. }
  15578. else
  15579. {
  15580. for (int i = numThisTime; --i >= 0;)
  15581. {
  15582. *l++ = ByteOrder::swapIfBigEndian (*src++);
  15583. }
  15584. }
  15585. }
  15586. else
  15587. {
  15588. if (numChannels > 1)
  15589. {
  15590. if (l == 0)
  15591. {
  15592. for (int i = numThisTime; --i >= 0;)
  15593. {
  15594. ++src;
  15595. *r++ = ByteOrder::swapIfLittleEndian (*src++);
  15596. }
  15597. }
  15598. else if (r == 0)
  15599. {
  15600. for (int i = numThisTime; --i >= 0;)
  15601. {
  15602. *l++ = ByteOrder::swapIfLittleEndian (*src++);
  15603. ++src;
  15604. }
  15605. }
  15606. else
  15607. {
  15608. for (int i = numThisTime; --i >= 0;)
  15609. {
  15610. *l++ = ByteOrder::swapIfLittleEndian (*src++);
  15611. *r++ = ByteOrder::swapIfLittleEndian (*src++);
  15612. }
  15613. }
  15614. }
  15615. else
  15616. {
  15617. for (int i = numThisTime; --i >= 0;)
  15618. {
  15619. *l++ = ByteOrder::swapIfLittleEndian (*src++);
  15620. }
  15621. }
  15622. }
  15623. left = reinterpret_cast <int*> (l);
  15624. right = reinterpret_cast <int*> (r);
  15625. }
  15626. else if (bitsPerSample == 8)
  15627. {
  15628. const char* src = tempBuffer;
  15629. if (numChannels > 1)
  15630. {
  15631. if (left == 0)
  15632. {
  15633. for (int i = numThisTime; --i >= 0;)
  15634. {
  15635. *right++ = ((int) *src++) << 24;
  15636. ++src;
  15637. }
  15638. }
  15639. else if (right == 0)
  15640. {
  15641. for (int i = numThisTime; --i >= 0;)
  15642. {
  15643. ++src;
  15644. *left++ = ((int) *src++) << 24;
  15645. }
  15646. }
  15647. else
  15648. {
  15649. for (int i = numThisTime; --i >= 0;)
  15650. {
  15651. *left++ = ((int) *src++) << 24;
  15652. *right++ = ((int) *src++) << 24;
  15653. }
  15654. }
  15655. }
  15656. else
  15657. {
  15658. for (int i = numThisTime; --i >= 0;)
  15659. {
  15660. *left++ = ((int) *src++) << 24;
  15661. }
  15662. }
  15663. }
  15664. startOffsetInDestBuffer += numThisTime;
  15665. numSamples -= numThisTime;
  15666. }
  15667. if (numSamples > 0)
  15668. {
  15669. for (int i = numDestChannels; --i >= 0;)
  15670. if (destSamples[i] != 0)
  15671. zeromem (destSamples[i] + startOffsetInDestBuffer,
  15672. sizeof (int) * numSamples);
  15673. }
  15674. return true;
  15675. }
  15676. juce_UseDebuggingNewOperator
  15677. private:
  15678. AiffAudioFormatReader (const AiffAudioFormatReader&);
  15679. AiffAudioFormatReader& operator= (const AiffAudioFormatReader&);
  15680. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  15681. };
  15682. class AiffAudioFormatWriter : public AudioFormatWriter
  15683. {
  15684. MemoryBlock tempBlock;
  15685. uint32 lengthInSamples, bytesWritten;
  15686. int64 headerPosition;
  15687. bool writeFailed;
  15688. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  15689. AiffAudioFormatWriter (const AiffAudioFormatWriter&);
  15690. AiffAudioFormatWriter& operator= (const AiffAudioFormatWriter&);
  15691. void writeHeader()
  15692. {
  15693. const bool couldSeekOk = output->setPosition (headerPosition);
  15694. (void) couldSeekOk;
  15695. // if this fails, you've given it an output stream that can't seek! It needs
  15696. // to be able to seek back to write the header
  15697. jassert (couldSeekOk);
  15698. const int headerLen = 54;
  15699. int audioBytes = lengthInSamples * ((bitsPerSample * numChannels) / 8);
  15700. audioBytes += (audioBytes & 1);
  15701. output->writeInt (chunkName ("FORM"));
  15702. output->writeIntBigEndian (headerLen + audioBytes - 8);
  15703. output->writeInt (chunkName ("AIFF"));
  15704. output->writeInt (chunkName ("COMM"));
  15705. output->writeIntBigEndian (18);
  15706. output->writeShortBigEndian ((short) numChannels);
  15707. output->writeIntBigEndian (lengthInSamples);
  15708. output->writeShortBigEndian ((short) bitsPerSample);
  15709. uint8 sampleRateBytes[10];
  15710. zeromem (sampleRateBytes, 10);
  15711. if (sampleRate <= 1)
  15712. {
  15713. sampleRateBytes[0] = 0x3f;
  15714. sampleRateBytes[1] = 0xff;
  15715. sampleRateBytes[2] = 0x80;
  15716. }
  15717. else
  15718. {
  15719. int mask = 0x40000000;
  15720. sampleRateBytes[0] = 0x40;
  15721. if (sampleRate >= mask)
  15722. {
  15723. jassertfalse;
  15724. sampleRateBytes[1] = 0x1d;
  15725. }
  15726. else
  15727. {
  15728. int n = (int) sampleRate;
  15729. int i;
  15730. for (i = 0; i <= 32 ; ++i)
  15731. {
  15732. if ((n & mask) != 0)
  15733. break;
  15734. mask >>= 1;
  15735. }
  15736. n = n << (i + 1);
  15737. sampleRateBytes[1] = (uint8) (29 - i);
  15738. sampleRateBytes[2] = (uint8) ((n >> 24) & 0xff);
  15739. sampleRateBytes[3] = (uint8) ((n >> 16) & 0xff);
  15740. sampleRateBytes[4] = (uint8) ((n >> 8) & 0xff);
  15741. sampleRateBytes[5] = (uint8) (n & 0xff);
  15742. }
  15743. }
  15744. output->write (sampleRateBytes, 10);
  15745. output->writeInt (chunkName ("SSND"));
  15746. output->writeIntBigEndian (audioBytes + 8);
  15747. output->writeInt (0);
  15748. output->writeInt (0);
  15749. jassert (output->getPosition() == headerLen);
  15750. }
  15751. public:
  15752. AiffAudioFormatWriter (OutputStream* out,
  15753. const double sampleRate_,
  15754. const unsigned int chans,
  15755. const int bits)
  15756. : AudioFormatWriter (out,
  15757. TRANS (aiffFormatName),
  15758. sampleRate_,
  15759. chans,
  15760. bits),
  15761. lengthInSamples (0),
  15762. bytesWritten (0),
  15763. writeFailed (false)
  15764. {
  15765. headerPosition = out->getPosition();
  15766. writeHeader();
  15767. }
  15768. ~AiffAudioFormatWriter()
  15769. {
  15770. if ((bytesWritten & 1) != 0)
  15771. output->writeByte (0);
  15772. writeHeader();
  15773. }
  15774. bool write (const int** data, int numSamples)
  15775. {
  15776. if (writeFailed)
  15777. return false;
  15778. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  15779. tempBlock.ensureSize (bytes, false);
  15780. char* buffer = static_cast <char*> (tempBlock.getData());
  15781. const int* left = data[0];
  15782. const int* right = data[1];
  15783. if (right == 0)
  15784. right = left;
  15785. if (bitsPerSample == 16)
  15786. {
  15787. short* b = reinterpret_cast <short*> (buffer);
  15788. if (numChannels > 1)
  15789. {
  15790. for (int i = numSamples; --i >= 0;)
  15791. {
  15792. *b++ = (short) ByteOrder::swapIfLittleEndian ((uint16) (*left++ >> 16));
  15793. *b++ = (short) ByteOrder::swapIfLittleEndian ((uint16) (*right++ >> 16));
  15794. }
  15795. }
  15796. else
  15797. {
  15798. for (int i = numSamples; --i >= 0;)
  15799. {
  15800. *b++ = (short) ByteOrder::swapIfLittleEndian ((uint16) (*left++ >> 16));
  15801. }
  15802. }
  15803. }
  15804. else if (bitsPerSample == 24)
  15805. {
  15806. char* b = buffer;
  15807. if (numChannels > 1)
  15808. {
  15809. for (int i = numSamples; --i >= 0;)
  15810. {
  15811. ByteOrder::bigEndian24BitToChars (*left++ >> 8, b);
  15812. b += 3;
  15813. ByteOrder::bigEndian24BitToChars (*right++ >> 8, b);
  15814. b += 3;
  15815. }
  15816. }
  15817. else
  15818. {
  15819. for (int i = numSamples; --i >= 0;)
  15820. {
  15821. ByteOrder::bigEndian24BitToChars (*left++ >> 8, b);
  15822. b += 3;
  15823. }
  15824. }
  15825. }
  15826. else if (bitsPerSample == 32)
  15827. {
  15828. uint32* b = reinterpret_cast <uint32*> (buffer);
  15829. if (numChannels > 1)
  15830. {
  15831. for (int i = numSamples; --i >= 0;)
  15832. {
  15833. *b++ = ByteOrder::swapIfLittleEndian ((uint32) *left++);
  15834. *b++ = ByteOrder::swapIfLittleEndian ((uint32) *right++);
  15835. }
  15836. }
  15837. else
  15838. {
  15839. for (int i = numSamples; --i >= 0;)
  15840. {
  15841. *b++ = ByteOrder::swapIfLittleEndian ((uint32) *left++);
  15842. }
  15843. }
  15844. }
  15845. else if (bitsPerSample == 8)
  15846. {
  15847. char* b = buffer;
  15848. if (numChannels > 1)
  15849. {
  15850. for (int i = numSamples; --i >= 0;)
  15851. {
  15852. *b++ = (char) (*left++ >> 24);
  15853. *b++ = (char) (*right++ >> 24);
  15854. }
  15855. }
  15856. else
  15857. {
  15858. for (int i = numSamples; --i >= 0;)
  15859. {
  15860. *b++ = (char) (*left++ >> 24);
  15861. }
  15862. }
  15863. }
  15864. if (bytesWritten + bytes >= (uint32) 0xfff00000
  15865. || ! output->write (buffer, bytes))
  15866. {
  15867. // failed to write to disk, so let's try writing the header.
  15868. // If it's just run out of disk space, then if it does manage
  15869. // to write the header, we'll still have a useable file..
  15870. writeHeader();
  15871. writeFailed = true;
  15872. return false;
  15873. }
  15874. else
  15875. {
  15876. bytesWritten += bytes;
  15877. lengthInSamples += numSamples;
  15878. return true;
  15879. }
  15880. }
  15881. juce_UseDebuggingNewOperator
  15882. };
  15883. AiffAudioFormat::AiffAudioFormat()
  15884. : AudioFormat (TRANS (aiffFormatName), StringArray (aiffExtensions))
  15885. {
  15886. }
  15887. AiffAudioFormat::~AiffAudioFormat()
  15888. {
  15889. }
  15890. const Array <int> AiffAudioFormat::getPossibleSampleRates()
  15891. {
  15892. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  15893. return Array <int> (rates);
  15894. }
  15895. const Array <int> AiffAudioFormat::getPossibleBitDepths()
  15896. {
  15897. const int depths[] = { 8, 16, 24, 0 };
  15898. return Array <int> (depths);
  15899. }
  15900. bool AiffAudioFormat::canDoStereo()
  15901. {
  15902. return true;
  15903. }
  15904. bool AiffAudioFormat::canDoMono()
  15905. {
  15906. return true;
  15907. }
  15908. #if JUCE_MAC
  15909. bool AiffAudioFormat::canHandleFile (const File& f)
  15910. {
  15911. if (AudioFormat::canHandleFile (f))
  15912. return true;
  15913. const OSType type = PlatformUtilities::getTypeOfFile (f.getFullPathName());
  15914. return type == 'AIFF' || type == 'AIFC'
  15915. || type == 'aiff' || type == 'aifc';
  15916. }
  15917. #endif
  15918. AudioFormatReader* AiffAudioFormat::createReaderFor (InputStream* sourceStream,
  15919. const bool deleteStreamIfOpeningFails)
  15920. {
  15921. ScopedPointer <AiffAudioFormatReader> w (new AiffAudioFormatReader (sourceStream));
  15922. if (w->sampleRate != 0)
  15923. return w.release();
  15924. if (! deleteStreamIfOpeningFails)
  15925. w->input = 0;
  15926. return 0;
  15927. }
  15928. AudioFormatWriter* AiffAudioFormat::createWriterFor (OutputStream* out,
  15929. double sampleRate,
  15930. unsigned int chans,
  15931. int bitsPerSample,
  15932. const StringPairArray& /*metadataValues*/,
  15933. int /*qualityOptionIndex*/)
  15934. {
  15935. if (getPossibleBitDepths().contains (bitsPerSample))
  15936. {
  15937. return new AiffAudioFormatWriter (out,
  15938. sampleRate,
  15939. chans,
  15940. bitsPerSample);
  15941. }
  15942. return 0;
  15943. }
  15944. END_JUCE_NAMESPACE
  15945. /*** End of inlined file: juce_AiffAudioFormat.cpp ***/
  15946. /*** Start of inlined file: juce_AudioFormat.cpp ***/
  15947. BEGIN_JUCE_NAMESPACE
  15948. AudioFormatReader::AudioFormatReader (InputStream* const in,
  15949. const String& formatName_)
  15950. : sampleRate (0),
  15951. bitsPerSample (0),
  15952. lengthInSamples (0),
  15953. numChannels (0),
  15954. usesFloatingPointData (false),
  15955. input (in),
  15956. formatName (formatName_)
  15957. {
  15958. }
  15959. AudioFormatReader::~AudioFormatReader()
  15960. {
  15961. delete input;
  15962. }
  15963. bool AudioFormatReader::read (int** destSamples,
  15964. int numDestChannels,
  15965. int64 startSampleInSource,
  15966. int numSamplesToRead,
  15967. const bool fillLeftoverChannelsWithCopies)
  15968. {
  15969. jassert (numDestChannels > 0); // you have to actually give this some channels to work with!
  15970. int startOffsetInDestBuffer = 0;
  15971. if (startSampleInSource < 0)
  15972. {
  15973. const int silence = (int) jmin (-startSampleInSource, (int64) numSamplesToRead);
  15974. for (int i = numDestChannels; --i >= 0;)
  15975. if (destSamples[i] != 0)
  15976. zeromem (destSamples[i], sizeof (int) * silence);
  15977. startOffsetInDestBuffer += silence;
  15978. numSamplesToRead -= silence;
  15979. startSampleInSource = 0;
  15980. }
  15981. if (numSamplesToRead <= 0)
  15982. return true;
  15983. if (! readSamples (destSamples, jmin ((int) numChannels, numDestChannels), startOffsetInDestBuffer,
  15984. startSampleInSource, numSamplesToRead))
  15985. return false;
  15986. if (numDestChannels > (int) numChannels)
  15987. {
  15988. if (fillLeftoverChannelsWithCopies)
  15989. {
  15990. int* lastFullChannel = destSamples[0];
  15991. for (int i = numDestChannels; --i > 0;)
  15992. {
  15993. if (destSamples[i] != 0)
  15994. {
  15995. lastFullChannel = destSamples[i];
  15996. break;
  15997. }
  15998. }
  15999. if (lastFullChannel != 0)
  16000. for (int i = numChannels; i < numDestChannels; ++i)
  16001. if (destSamples[i] != 0)
  16002. memcpy (destSamples[i], lastFullChannel, sizeof (int) * numSamplesToRead);
  16003. }
  16004. else
  16005. {
  16006. for (int i = numChannels; i < numDestChannels; ++i)
  16007. if (destSamples[i] != 0)
  16008. zeromem (destSamples[i], sizeof (int) * numSamplesToRead);
  16009. }
  16010. }
  16011. return true;
  16012. }
  16013. static void findAudioBufferMaxMin (const float* const buffer, const int num, float& maxVal, float& minVal) throw()
  16014. {
  16015. float mn = buffer[0];
  16016. float mx = mn;
  16017. for (int i = 1; i < num; ++i)
  16018. {
  16019. const float s = buffer[i];
  16020. if (s > mx) mx = s;
  16021. if (s < mn) mn = s;
  16022. }
  16023. maxVal = mx;
  16024. minVal = mn;
  16025. }
  16026. void AudioFormatReader::readMaxLevels (int64 startSampleInFile,
  16027. int64 numSamples,
  16028. float& lowestLeft, float& highestLeft,
  16029. float& lowestRight, float& highestRight)
  16030. {
  16031. if (numSamples <= 0)
  16032. {
  16033. lowestLeft = 0;
  16034. lowestRight = 0;
  16035. highestLeft = 0;
  16036. highestRight = 0;
  16037. return;
  16038. }
  16039. const int bufferSize = (int) jmin (numSamples, (int64) 4096);
  16040. MemoryBlock tempSpace (bufferSize * sizeof (int) * 2 + 64);
  16041. int* tempBuffer[3];
  16042. tempBuffer[0] = (int*) tempSpace.getData();
  16043. tempBuffer[1] = ((int*) tempSpace.getData()) + bufferSize;
  16044. tempBuffer[2] = 0;
  16045. if (usesFloatingPointData)
  16046. {
  16047. float lmin = 1.0e6f;
  16048. float lmax = -lmin;
  16049. float rmin = lmin;
  16050. float rmax = lmax;
  16051. while (numSamples > 0)
  16052. {
  16053. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  16054. read ((int**) tempBuffer, 2, startSampleInFile, numToDo, false);
  16055. numSamples -= numToDo;
  16056. startSampleInFile += numToDo;
  16057. float bufmin, bufmax;
  16058. findAudioBufferMaxMin ((float*) tempBuffer[0], numToDo, bufmax, bufmin);
  16059. lmin = jmin (lmin, bufmin);
  16060. lmax = jmax (lmax, bufmax);
  16061. if (numChannels > 1)
  16062. {
  16063. findAudioBufferMaxMin ((float*) tempBuffer[1], numToDo, bufmax, bufmin);
  16064. rmin = jmin (rmin, bufmin);
  16065. rmax = jmax (rmax, bufmax);
  16066. }
  16067. }
  16068. if (numChannels <= 1)
  16069. {
  16070. rmax = lmax;
  16071. rmin = lmin;
  16072. }
  16073. lowestLeft = lmin;
  16074. highestLeft = lmax;
  16075. lowestRight = rmin;
  16076. highestRight = rmax;
  16077. }
  16078. else
  16079. {
  16080. int lmax = std::numeric_limits<int>::min();
  16081. int lmin = std::numeric_limits<int>::max();
  16082. int rmax = std::numeric_limits<int>::min();
  16083. int rmin = std::numeric_limits<int>::max();
  16084. while (numSamples > 0)
  16085. {
  16086. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  16087. read ((int**) tempBuffer, 2, startSampleInFile, numToDo, false);
  16088. numSamples -= numToDo;
  16089. startSampleInFile += numToDo;
  16090. for (int j = numChannels; --j >= 0;)
  16091. {
  16092. int bufMax = std::numeric_limits<int>::min();
  16093. int bufMin = std::numeric_limits<int>::max();
  16094. const int* const b = tempBuffer[j];
  16095. for (int i = 0; i < numToDo; ++i)
  16096. {
  16097. const int samp = b[i];
  16098. if (samp < bufMin)
  16099. bufMin = samp;
  16100. if (samp > bufMax)
  16101. bufMax = samp;
  16102. }
  16103. if (j == 0)
  16104. {
  16105. lmax = jmax (lmax, bufMax);
  16106. lmin = jmin (lmin, bufMin);
  16107. }
  16108. else
  16109. {
  16110. rmax = jmax (rmax, bufMax);
  16111. rmin = jmin (rmin, bufMin);
  16112. }
  16113. }
  16114. }
  16115. if (numChannels <= 1)
  16116. {
  16117. rmax = lmax;
  16118. rmin = lmin;
  16119. }
  16120. lowestLeft = lmin / (float) std::numeric_limits<int>::max();
  16121. highestLeft = lmax / (float) std::numeric_limits<int>::max();
  16122. lowestRight = rmin / (float) std::numeric_limits<int>::max();
  16123. highestRight = rmax / (float) std::numeric_limits<int>::max();
  16124. }
  16125. }
  16126. int64 AudioFormatReader::searchForLevel (int64 startSample,
  16127. int64 numSamplesToSearch,
  16128. const double magnitudeRangeMinimum,
  16129. const double magnitudeRangeMaximum,
  16130. const int minimumConsecutiveSamples)
  16131. {
  16132. if (numSamplesToSearch == 0)
  16133. return -1;
  16134. const int bufferSize = 4096;
  16135. MemoryBlock tempSpace (bufferSize * sizeof (int) * 2 + 64);
  16136. int* tempBuffer[3];
  16137. tempBuffer[0] = (int*) tempSpace.getData();
  16138. tempBuffer[1] = ((int*) tempSpace.getData()) + bufferSize;
  16139. tempBuffer[2] = 0;
  16140. int consecutive = 0;
  16141. int64 firstMatchPos = -1;
  16142. jassert (magnitudeRangeMaximum > magnitudeRangeMinimum);
  16143. const double doubleMin = jlimit (0.0, (double) std::numeric_limits<int>::max(), magnitudeRangeMinimum * std::numeric_limits<int>::max());
  16144. const double doubleMax = jlimit (doubleMin, (double) std::numeric_limits<int>::max(), magnitudeRangeMaximum * std::numeric_limits<int>::max());
  16145. const int intMagnitudeRangeMinimum = roundToInt (doubleMin);
  16146. const int intMagnitudeRangeMaximum = roundToInt (doubleMax);
  16147. while (numSamplesToSearch != 0)
  16148. {
  16149. const int numThisTime = (int) jmin (abs64 (numSamplesToSearch), (int64) bufferSize);
  16150. int64 bufferStart = startSample;
  16151. if (numSamplesToSearch < 0)
  16152. bufferStart -= numThisTime;
  16153. if (bufferStart >= (int) lengthInSamples)
  16154. break;
  16155. read ((int**) tempBuffer, 2, bufferStart, numThisTime, false);
  16156. int num = numThisTime;
  16157. while (--num >= 0)
  16158. {
  16159. if (numSamplesToSearch < 0)
  16160. --startSample;
  16161. bool matches = false;
  16162. const int index = (int) (startSample - bufferStart);
  16163. if (usesFloatingPointData)
  16164. {
  16165. const float sample1 = std::abs (((float*) tempBuffer[0]) [index]);
  16166. if (sample1 >= magnitudeRangeMinimum
  16167. && sample1 <= magnitudeRangeMaximum)
  16168. {
  16169. matches = true;
  16170. }
  16171. else if (numChannels > 1)
  16172. {
  16173. const float sample2 = std::abs (((float*) tempBuffer[1]) [index]);
  16174. matches = (sample2 >= magnitudeRangeMinimum
  16175. && sample2 <= magnitudeRangeMaximum);
  16176. }
  16177. }
  16178. else
  16179. {
  16180. const int sample1 = abs (tempBuffer[0] [index]);
  16181. if (sample1 >= intMagnitudeRangeMinimum
  16182. && sample1 <= intMagnitudeRangeMaximum)
  16183. {
  16184. matches = true;
  16185. }
  16186. else if (numChannels > 1)
  16187. {
  16188. const int sample2 = abs (tempBuffer[1][index]);
  16189. matches = (sample2 >= intMagnitudeRangeMinimum
  16190. && sample2 <= intMagnitudeRangeMaximum);
  16191. }
  16192. }
  16193. if (matches)
  16194. {
  16195. if (firstMatchPos < 0)
  16196. firstMatchPos = startSample;
  16197. if (++consecutive >= minimumConsecutiveSamples)
  16198. {
  16199. if (firstMatchPos < 0 || firstMatchPos >= lengthInSamples)
  16200. return -1;
  16201. return firstMatchPos;
  16202. }
  16203. }
  16204. else
  16205. {
  16206. consecutive = 0;
  16207. firstMatchPos = -1;
  16208. }
  16209. if (numSamplesToSearch > 0)
  16210. ++startSample;
  16211. }
  16212. if (numSamplesToSearch > 0)
  16213. numSamplesToSearch -= numThisTime;
  16214. else
  16215. numSamplesToSearch += numThisTime;
  16216. }
  16217. return -1;
  16218. }
  16219. AudioFormatWriter::AudioFormatWriter (OutputStream* const out,
  16220. const String& formatName_,
  16221. const double rate,
  16222. const unsigned int numChannels_,
  16223. const unsigned int bitsPerSample_)
  16224. : sampleRate (rate),
  16225. numChannels (numChannels_),
  16226. bitsPerSample (bitsPerSample_),
  16227. usesFloatingPointData (false),
  16228. output (out),
  16229. formatName (formatName_)
  16230. {
  16231. }
  16232. AudioFormatWriter::~AudioFormatWriter()
  16233. {
  16234. delete output;
  16235. }
  16236. bool AudioFormatWriter::writeFromAudioReader (AudioFormatReader& reader,
  16237. int64 startSample,
  16238. int64 numSamplesToRead)
  16239. {
  16240. const int bufferSize = 16384;
  16241. AudioSampleBuffer tempBuffer (numChannels, bufferSize);
  16242. int* buffers [128];
  16243. zerostruct (buffers);
  16244. for (int i = tempBuffer.getNumChannels(); --i >= 0;)
  16245. buffers[i] = (int*) tempBuffer.getSampleData (i, 0);
  16246. if (numSamplesToRead < 0)
  16247. numSamplesToRead = reader.lengthInSamples;
  16248. while (numSamplesToRead > 0)
  16249. {
  16250. const int numToDo = (int) jmin (numSamplesToRead, (int64) bufferSize);
  16251. if (! reader.read (buffers, numChannels, startSample, numToDo, false))
  16252. return false;
  16253. if (reader.usesFloatingPointData != isFloatingPoint())
  16254. {
  16255. int** bufferChan = buffers;
  16256. while (*bufferChan != 0)
  16257. {
  16258. int* b = *bufferChan++;
  16259. if (isFloatingPoint())
  16260. {
  16261. // int -> float
  16262. const double factor = 1.0 / std::numeric_limits<int>::max();
  16263. for (int i = 0; i < numToDo; ++i)
  16264. ((float*) b)[i] = (float) (factor * b[i]);
  16265. }
  16266. else
  16267. {
  16268. // float -> int
  16269. for (int i = 0; i < numToDo; ++i)
  16270. {
  16271. const double samp = *(const float*) b;
  16272. if (samp <= -1.0)
  16273. *b++ = std::numeric_limits<int>::min();
  16274. else if (samp >= 1.0)
  16275. *b++ = std::numeric_limits<int>::max();
  16276. else
  16277. *b++ = roundToInt (std::numeric_limits<int>::max() * samp);
  16278. }
  16279. }
  16280. }
  16281. }
  16282. if (! write ((const int**) buffers, numToDo))
  16283. return false;
  16284. numSamplesToRead -= numToDo;
  16285. startSample += numToDo;
  16286. }
  16287. return true;
  16288. }
  16289. bool AudioFormatWriter::writeFromAudioSource (AudioSource& source,
  16290. int numSamplesToRead,
  16291. const int samplesPerBlock)
  16292. {
  16293. AudioSampleBuffer tempBuffer (getNumChannels(), samplesPerBlock);
  16294. int* buffers [128];
  16295. zerostruct (buffers);
  16296. for (int i = tempBuffer.getNumChannels(); --i >= 0;)
  16297. buffers[i] = (int*) tempBuffer.getSampleData (i, 0);
  16298. while (numSamplesToRead > 0)
  16299. {
  16300. const int numToDo = jmin (numSamplesToRead, samplesPerBlock);
  16301. AudioSourceChannelInfo info;
  16302. info.buffer = &tempBuffer;
  16303. info.startSample = 0;
  16304. info.numSamples = numToDo;
  16305. info.clearActiveBufferRegion();
  16306. source.getNextAudioBlock (info);
  16307. if (! isFloatingPoint())
  16308. {
  16309. int** bufferChan = buffers;
  16310. while (*bufferChan != 0)
  16311. {
  16312. int* b = *bufferChan++;
  16313. // float -> int
  16314. for (int j = numToDo; --j >= 0;)
  16315. {
  16316. const double samp = *(const float*) b;
  16317. if (samp <= -1.0)
  16318. *b++ = std::numeric_limits<int>::min();
  16319. else if (samp >= 1.0)
  16320. *b++ = std::numeric_limits<int>::max();
  16321. else
  16322. *b++ = roundToInt (std::numeric_limits<int>::max() * samp);
  16323. }
  16324. }
  16325. }
  16326. if (! write ((const int**) buffers, numToDo))
  16327. return false;
  16328. numSamplesToRead -= numToDo;
  16329. }
  16330. return true;
  16331. }
  16332. AudioFormat::AudioFormat (const String& name,
  16333. const StringArray& extensions)
  16334. : formatName (name),
  16335. fileExtensions (extensions)
  16336. {
  16337. }
  16338. AudioFormat::~AudioFormat()
  16339. {
  16340. }
  16341. const String& AudioFormat::getFormatName() const
  16342. {
  16343. return formatName;
  16344. }
  16345. const StringArray& AudioFormat::getFileExtensions() const
  16346. {
  16347. return fileExtensions;
  16348. }
  16349. bool AudioFormat::canHandleFile (const File& f)
  16350. {
  16351. for (int i = 0; i < fileExtensions.size(); ++i)
  16352. if (f.hasFileExtension (fileExtensions[i]))
  16353. return true;
  16354. return false;
  16355. }
  16356. bool AudioFormat::isCompressed()
  16357. {
  16358. return false;
  16359. }
  16360. const StringArray AudioFormat::getQualityOptions()
  16361. {
  16362. return StringArray();
  16363. }
  16364. END_JUCE_NAMESPACE
  16365. /*** End of inlined file: juce_AudioFormat.cpp ***/
  16366. /*** Start of inlined file: juce_AudioFormatManager.cpp ***/
  16367. BEGIN_JUCE_NAMESPACE
  16368. AudioFormatManager::AudioFormatManager()
  16369. : defaultFormatIndex (0)
  16370. {
  16371. }
  16372. AudioFormatManager::~AudioFormatManager()
  16373. {
  16374. clearFormats();
  16375. clearSingletonInstance();
  16376. }
  16377. juce_ImplementSingleton (AudioFormatManager);
  16378. void AudioFormatManager::registerFormat (AudioFormat* newFormat,
  16379. const bool makeThisTheDefaultFormat)
  16380. {
  16381. jassert (newFormat != 0);
  16382. if (newFormat != 0)
  16383. {
  16384. #if JUCE_DEBUG
  16385. for (int i = getNumKnownFormats(); --i >= 0;)
  16386. {
  16387. if (getKnownFormat (i)->getFormatName() == newFormat->getFormatName())
  16388. {
  16389. jassertfalse; // trying to add the same format twice!
  16390. }
  16391. }
  16392. #endif
  16393. if (makeThisTheDefaultFormat)
  16394. defaultFormatIndex = getNumKnownFormats();
  16395. knownFormats.add (newFormat);
  16396. }
  16397. }
  16398. void AudioFormatManager::registerBasicFormats()
  16399. {
  16400. #if JUCE_MAC
  16401. registerFormat (new AiffAudioFormat(), true);
  16402. registerFormat (new WavAudioFormat(), false);
  16403. #else
  16404. registerFormat (new WavAudioFormat(), true);
  16405. registerFormat (new AiffAudioFormat(), false);
  16406. #endif
  16407. #if JUCE_USE_FLAC
  16408. registerFormat (new FlacAudioFormat(), false);
  16409. #endif
  16410. #if JUCE_USE_OGGVORBIS
  16411. registerFormat (new OggVorbisAudioFormat(), false);
  16412. #endif
  16413. }
  16414. void AudioFormatManager::clearFormats()
  16415. {
  16416. knownFormats.clear();
  16417. defaultFormatIndex = 0;
  16418. }
  16419. int AudioFormatManager::getNumKnownFormats() const
  16420. {
  16421. return knownFormats.size();
  16422. }
  16423. AudioFormat* AudioFormatManager::getKnownFormat (const int index) const
  16424. {
  16425. return knownFormats [index];
  16426. }
  16427. AudioFormat* AudioFormatManager::getDefaultFormat() const
  16428. {
  16429. return getKnownFormat (defaultFormatIndex);
  16430. }
  16431. AudioFormat* AudioFormatManager::findFormatForFileExtension (const String& fileExtension) const
  16432. {
  16433. String e (fileExtension);
  16434. if (! e.startsWithChar ('.'))
  16435. e = "." + e;
  16436. for (int i = 0; i < getNumKnownFormats(); ++i)
  16437. if (getKnownFormat(i)->getFileExtensions().contains (e, true))
  16438. return getKnownFormat(i);
  16439. return 0;
  16440. }
  16441. const String AudioFormatManager::getWildcardForAllFormats() const
  16442. {
  16443. StringArray allExtensions;
  16444. int i;
  16445. for (i = 0; i < getNumKnownFormats(); ++i)
  16446. allExtensions.addArray (getKnownFormat (i)->getFileExtensions());
  16447. allExtensions.trim();
  16448. allExtensions.removeEmptyStrings();
  16449. String s;
  16450. for (i = 0; i < allExtensions.size(); ++i)
  16451. {
  16452. s << '*';
  16453. if (! allExtensions[i].startsWithChar ('.'))
  16454. s << '.';
  16455. s << allExtensions[i];
  16456. if (i < allExtensions.size() - 1)
  16457. s << ';';
  16458. }
  16459. return s;
  16460. }
  16461. AudioFormatReader* AudioFormatManager::createReaderFor (const File& file)
  16462. {
  16463. // you need to actually register some formats before the manager can
  16464. // use them to open a file!
  16465. jassert (getNumKnownFormats() > 0);
  16466. for (int i = 0; i < getNumKnownFormats(); ++i)
  16467. {
  16468. AudioFormat* const af = getKnownFormat(i);
  16469. if (af->canHandleFile (file))
  16470. {
  16471. InputStream* const in = file.createInputStream();
  16472. if (in != 0)
  16473. {
  16474. AudioFormatReader* const r = af->createReaderFor (in, true);
  16475. if (r != 0)
  16476. return r;
  16477. }
  16478. }
  16479. }
  16480. return 0;
  16481. }
  16482. AudioFormatReader* AudioFormatManager::createReaderFor (InputStream* audioFileStream)
  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. ScopedPointer <InputStream> in (audioFileStream);
  16488. if (in != 0)
  16489. {
  16490. const int64 originalStreamPos = in->getPosition();
  16491. for (int i = 0; i < getNumKnownFormats(); ++i)
  16492. {
  16493. AudioFormatReader* const r = getKnownFormat(i)->createReaderFor (in, false);
  16494. if (r != 0)
  16495. {
  16496. in.release();
  16497. return r;
  16498. }
  16499. in->setPosition (originalStreamPos);
  16500. // the stream that is passed-in must be capable of being repositioned so
  16501. // that all the formats can have a go at opening it.
  16502. jassert (in->getPosition() == originalStreamPos);
  16503. }
  16504. }
  16505. return 0;
  16506. }
  16507. END_JUCE_NAMESPACE
  16508. /*** End of inlined file: juce_AudioFormatManager.cpp ***/
  16509. /*** Start of inlined file: juce_AudioSubsectionReader.cpp ***/
  16510. BEGIN_JUCE_NAMESPACE
  16511. AudioSubsectionReader::AudioSubsectionReader (AudioFormatReader* const source_,
  16512. const int64 startSample_,
  16513. const int64 length_,
  16514. const bool deleteSourceWhenDeleted_)
  16515. : AudioFormatReader (0, source_->getFormatName()),
  16516. source (source_),
  16517. startSample (startSample_),
  16518. deleteSourceWhenDeleted (deleteSourceWhenDeleted_)
  16519. {
  16520. length = jmin (jmax ((int64) 0, source->lengthInSamples - startSample), length_);
  16521. sampleRate = source->sampleRate;
  16522. bitsPerSample = source->bitsPerSample;
  16523. lengthInSamples = length;
  16524. numChannels = source->numChannels;
  16525. usesFloatingPointData = source->usesFloatingPointData;
  16526. }
  16527. AudioSubsectionReader::~AudioSubsectionReader()
  16528. {
  16529. if (deleteSourceWhenDeleted)
  16530. delete source;
  16531. }
  16532. bool AudioSubsectionReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  16533. int64 startSampleInFile, int numSamples)
  16534. {
  16535. if (startSampleInFile + numSamples > length)
  16536. {
  16537. for (int i = numDestChannels; --i >= 0;)
  16538. if (destSamples[i] != 0)
  16539. zeromem (destSamples[i], sizeof (int) * numSamples);
  16540. numSamples = jmin (numSamples, (int) (length - startSampleInFile));
  16541. if (numSamples <= 0)
  16542. return true;
  16543. }
  16544. return source->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer,
  16545. startSampleInFile + startSample, numSamples);
  16546. }
  16547. void AudioSubsectionReader::readMaxLevels (int64 startSampleInFile,
  16548. int64 numSamples,
  16549. float& lowestLeft,
  16550. float& highestLeft,
  16551. float& lowestRight,
  16552. float& highestRight)
  16553. {
  16554. startSampleInFile = jmax ((int64) 0, startSampleInFile);
  16555. numSamples = jmax ((int64) 0, jmin (numSamples, length - startSampleInFile));
  16556. source->readMaxLevels (startSampleInFile + startSample,
  16557. numSamples,
  16558. lowestLeft,
  16559. highestLeft,
  16560. lowestRight,
  16561. highestRight);
  16562. }
  16563. END_JUCE_NAMESPACE
  16564. /*** End of inlined file: juce_AudioSubsectionReader.cpp ***/
  16565. /*** Start of inlined file: juce_AudioThumbnail.cpp ***/
  16566. BEGIN_JUCE_NAMESPACE
  16567. const int timeBeforeDeletingReader = 2000;
  16568. struct AudioThumbnailDataFormat
  16569. {
  16570. char thumbnailMagic[4];
  16571. int samplesPerThumbSample;
  16572. int64 totalSamples; // source samples
  16573. int64 numFinishedSamples; // source samples
  16574. int numThumbnailSamples;
  16575. int numChannels;
  16576. int sampleRate;
  16577. char future[16];
  16578. char data[1];
  16579. void swapEndiannessIfNeeded() throw()
  16580. {
  16581. #if JUCE_BIG_ENDIAN
  16582. flip (samplesPerThumbSample);
  16583. flip (totalSamples);
  16584. flip (numFinishedSamples);
  16585. flip (numThumbnailSamples);
  16586. flip (numChannels);
  16587. flip (sampleRate);
  16588. #endif
  16589. }
  16590. private:
  16591. #if JUCE_BIG_ENDIAN
  16592. static void flip (int& n) { n = (int) ByteOrder::swap ((uint32) n); }
  16593. static void flip (int64& n) { n = (int64) ByteOrder::swap ((uint64) n); }
  16594. #endif
  16595. };
  16596. AudioThumbnail::AudioThumbnail (const int orginalSamplesPerThumbnailSample_,
  16597. AudioFormatManager& formatManagerToUse_,
  16598. AudioThumbnailCache& cacheToUse)
  16599. : formatManagerToUse (formatManagerToUse_),
  16600. cache (cacheToUse),
  16601. orginalSamplesPerThumbnailSample (orginalSamplesPerThumbnailSample_)
  16602. {
  16603. clear();
  16604. }
  16605. AudioThumbnail::~AudioThumbnail()
  16606. {
  16607. cache.removeThumbnail (this);
  16608. const ScopedLock sl (readerLock);
  16609. reader = 0;
  16610. }
  16611. void AudioThumbnail::setSource (InputSource* const newSource)
  16612. {
  16613. cache.removeThumbnail (this);
  16614. timerCallback(); // stops the timer and deletes the reader
  16615. source = newSource;
  16616. clear();
  16617. if (newSource != 0
  16618. && ! (cache.loadThumb (*this, newSource->hashCode())
  16619. && isFullyLoaded()))
  16620. {
  16621. {
  16622. const ScopedLock sl (readerLock);
  16623. reader = createReader();
  16624. }
  16625. if (reader != 0)
  16626. {
  16627. initialiseFromAudioFile (*reader);
  16628. cache.addThumbnail (this);
  16629. }
  16630. }
  16631. sendChangeMessage (this);
  16632. }
  16633. bool AudioThumbnail::useTimeSlice()
  16634. {
  16635. const ScopedLock sl (readerLock);
  16636. if (isFullyLoaded())
  16637. {
  16638. if (reader != 0)
  16639. startTimer (timeBeforeDeletingReader);
  16640. cache.removeThumbnail (this);
  16641. return false;
  16642. }
  16643. if (reader == 0)
  16644. reader = createReader();
  16645. if (reader != 0)
  16646. {
  16647. readNextBlockFromAudioFile (*reader);
  16648. stopTimer();
  16649. sendChangeMessage (this);
  16650. const bool justFinished = isFullyLoaded();
  16651. if (justFinished)
  16652. cache.storeThumb (*this, source->hashCode());
  16653. return ! justFinished;
  16654. }
  16655. return false;
  16656. }
  16657. AudioFormatReader* AudioThumbnail::createReader() const
  16658. {
  16659. if (source != 0)
  16660. {
  16661. InputStream* const audioFileStream = source->createInputStream();
  16662. if (audioFileStream != 0)
  16663. return formatManagerToUse.createReaderFor (audioFileStream);
  16664. }
  16665. return 0;
  16666. }
  16667. void AudioThumbnail::timerCallback()
  16668. {
  16669. stopTimer();
  16670. const ScopedLock sl (readerLock);
  16671. reader = 0;
  16672. }
  16673. void AudioThumbnail::clear()
  16674. {
  16675. data.setSize (sizeof (AudioThumbnailDataFormat) + 3);
  16676. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16677. d->thumbnailMagic[0] = 'j';
  16678. d->thumbnailMagic[1] = 'a';
  16679. d->thumbnailMagic[2] = 't';
  16680. d->thumbnailMagic[3] = 'm';
  16681. d->samplesPerThumbSample = orginalSamplesPerThumbnailSample;
  16682. d->totalSamples = 0;
  16683. d->numFinishedSamples = 0;
  16684. d->numThumbnailSamples = 0;
  16685. d->numChannels = 0;
  16686. d->sampleRate = 0;
  16687. numSamplesCached = 0;
  16688. cacheNeedsRefilling = true;
  16689. }
  16690. void AudioThumbnail::loadFrom (InputStream& input)
  16691. {
  16692. const ScopedLock sl (readerLock);
  16693. data.setSize (0);
  16694. input.readIntoMemoryBlock (data);
  16695. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16696. d->swapEndiannessIfNeeded();
  16697. if (! (d->thumbnailMagic[0] == 'j'
  16698. && d->thumbnailMagic[1] == 'a'
  16699. && d->thumbnailMagic[2] == 't'
  16700. && d->thumbnailMagic[3] == 'm'))
  16701. {
  16702. clear();
  16703. }
  16704. numSamplesCached = 0;
  16705. cacheNeedsRefilling = true;
  16706. }
  16707. void AudioThumbnail::saveTo (OutputStream& output) const
  16708. {
  16709. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16710. d->swapEndiannessIfNeeded();
  16711. output.write (data.getData(), (int) data.getSize());
  16712. d->swapEndiannessIfNeeded();
  16713. }
  16714. bool AudioThumbnail::initialiseFromAudioFile (AudioFormatReader& fileReader)
  16715. {
  16716. AudioThumbnailDataFormat* d = (AudioThumbnailDataFormat*) data.getData();
  16717. d->totalSamples = fileReader.lengthInSamples;
  16718. d->numChannels = jmin ((uint32) 2, fileReader.numChannels);
  16719. d->numFinishedSamples = 0;
  16720. d->sampleRate = roundToInt (fileReader.sampleRate);
  16721. d->numThumbnailSamples = (int) (d->totalSamples / d->samplesPerThumbSample) + 1;
  16722. data.setSize (sizeof (AudioThumbnailDataFormat) + 3 + d->numThumbnailSamples * d->numChannels * 2);
  16723. d = (AudioThumbnailDataFormat*) data.getData();
  16724. zeromem (&(d->data[0]), d->numThumbnailSamples * d->numChannels * 2);
  16725. return d->totalSamples > 0;
  16726. }
  16727. bool AudioThumbnail::readNextBlockFromAudioFile (AudioFormatReader& fileReader)
  16728. {
  16729. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16730. if (d->numFinishedSamples < d->totalSamples)
  16731. {
  16732. const int numToDo = (int) jmin ((int64) 65536, d->totalSamples - d->numFinishedSamples);
  16733. generateSection (fileReader,
  16734. d->numFinishedSamples,
  16735. numToDo);
  16736. d->numFinishedSamples += numToDo;
  16737. }
  16738. cacheNeedsRefilling = true;
  16739. return (d->numFinishedSamples < d->totalSamples);
  16740. }
  16741. int AudioThumbnail::getNumChannels() const throw()
  16742. {
  16743. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  16744. jassert (d != 0);
  16745. return d->numChannels;
  16746. }
  16747. double AudioThumbnail::getTotalLength() const throw()
  16748. {
  16749. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  16750. jassert (d != 0);
  16751. if (d->sampleRate > 0)
  16752. return d->totalSamples / (double)d->sampleRate;
  16753. else
  16754. return 0.0;
  16755. }
  16756. void AudioThumbnail::generateSection (AudioFormatReader& fileReader,
  16757. int64 startSample,
  16758. int numSamples)
  16759. {
  16760. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16761. jassert (d != 0);
  16762. int firstDataPos = (int) (startSample / d->samplesPerThumbSample);
  16763. int lastDataPos = (int) ((startSample + numSamples) / d->samplesPerThumbSample);
  16764. char* l = getChannelData (0);
  16765. char* r = getChannelData (1);
  16766. for (int i = firstDataPos; i < lastDataPos; ++i)
  16767. {
  16768. const int sourceStart = i * d->samplesPerThumbSample;
  16769. const int sourceEnd = sourceStart + d->samplesPerThumbSample;
  16770. float lowestLeft, highestLeft, lowestRight, highestRight;
  16771. fileReader.readMaxLevels (sourceStart,
  16772. sourceEnd - sourceStart,
  16773. lowestLeft,
  16774. highestLeft,
  16775. lowestRight,
  16776. highestRight);
  16777. int n = i * 2;
  16778. if (r != 0)
  16779. {
  16780. l [n] = (char) jlimit (-128.0f, 127.0f, lowestLeft * 127.0f);
  16781. r [n++] = (char) jlimit (-128.0f, 127.0f, lowestRight * 127.0f);
  16782. l [n] = (char) jlimit (-128.0f, 127.0f, highestLeft * 127.0f);
  16783. r [n++] = (char) jlimit (-128.0f, 127.0f, highestRight * 127.0f);
  16784. }
  16785. else
  16786. {
  16787. l [n++] = (char) jlimit (-128.0f, 127.0f, lowestLeft * 127.0f);
  16788. l [n++] = (char) jlimit (-128.0f, 127.0f, highestLeft * 127.0f);
  16789. }
  16790. }
  16791. }
  16792. char* AudioThumbnail::getChannelData (int channel) const
  16793. {
  16794. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16795. jassert (d != 0);
  16796. if (channel >= 0 && channel < d->numChannels)
  16797. return d->data + (channel * 2 * d->numThumbnailSamples);
  16798. return 0;
  16799. }
  16800. bool AudioThumbnail::isFullyLoaded() const throw()
  16801. {
  16802. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  16803. jassert (d != 0);
  16804. return d->numFinishedSamples >= d->totalSamples;
  16805. }
  16806. void AudioThumbnail::refillCache (const int numSamples,
  16807. double startTime,
  16808. const double timePerPixel)
  16809. {
  16810. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  16811. jassert (d != 0);
  16812. if (numSamples <= 0
  16813. || timePerPixel <= 0.0
  16814. || d->sampleRate <= 0)
  16815. {
  16816. numSamplesCached = 0;
  16817. cacheNeedsRefilling = true;
  16818. return;
  16819. }
  16820. if (numSamples == numSamplesCached
  16821. && numChannelsCached == d->numChannels
  16822. && startTime == cachedStart
  16823. && timePerPixel == cachedTimePerPixel
  16824. && ! cacheNeedsRefilling)
  16825. {
  16826. return;
  16827. }
  16828. numSamplesCached = numSamples;
  16829. numChannelsCached = d->numChannels;
  16830. cachedStart = startTime;
  16831. cachedTimePerPixel = timePerPixel;
  16832. cachedLevels.ensureSize (2 * numChannelsCached * numSamples);
  16833. const bool needExtraDetail = (timePerPixel * d->sampleRate <= d->samplesPerThumbSample);
  16834. const ScopedLock sl (readerLock);
  16835. cacheNeedsRefilling = false;
  16836. if (needExtraDetail && reader == 0)
  16837. reader = createReader();
  16838. if (reader != 0 && timePerPixel * d->sampleRate <= d->samplesPerThumbSample)
  16839. {
  16840. startTimer (timeBeforeDeletingReader);
  16841. char* cacheData = static_cast <char*> (cachedLevels.getData());
  16842. int sample = roundToInt (startTime * d->sampleRate);
  16843. for (int i = numSamples; --i >= 0;)
  16844. {
  16845. const int nextSample = roundToInt ((startTime + timePerPixel) * d->sampleRate);
  16846. if (sample >= 0)
  16847. {
  16848. if (sample >= reader->lengthInSamples)
  16849. break;
  16850. float lmin, lmax, rmin, rmax;
  16851. reader->readMaxLevels (sample,
  16852. jmax (1, nextSample - sample),
  16853. lmin, lmax, rmin, rmax);
  16854. cacheData[0] = (char) jlimit (-128, 127, roundFloatToInt (lmin * 127.0f));
  16855. cacheData[1] = (char) jlimit (-128, 127, roundFloatToInt (lmax * 127.0f));
  16856. if (numChannelsCached > 1)
  16857. {
  16858. cacheData[2] = (char) jlimit (-128, 127, roundFloatToInt (rmin * 127.0f));
  16859. cacheData[3] = (char) jlimit (-128, 127, roundFloatToInt (rmax * 127.0f));
  16860. }
  16861. cacheData += 2 * numChannelsCached;
  16862. }
  16863. startTime += timePerPixel;
  16864. sample = nextSample;
  16865. }
  16866. }
  16867. else
  16868. {
  16869. for (int channelNum = 0; channelNum < numChannelsCached; ++channelNum)
  16870. {
  16871. char* const channelData = getChannelData (channelNum);
  16872. char* cacheData = static_cast <char*> (cachedLevels.getData()) + channelNum * 2;
  16873. const double timeToThumbSampleFactor = d->sampleRate / (double) d->samplesPerThumbSample;
  16874. startTime = cachedStart;
  16875. int sample = roundToInt (startTime * timeToThumbSampleFactor);
  16876. const int numFinished = (int) (d->numFinishedSamples / d->samplesPerThumbSample);
  16877. for (int i = numSamples; --i >= 0;)
  16878. {
  16879. const int nextSample = roundToInt ((startTime + timePerPixel) * timeToThumbSampleFactor);
  16880. if (sample >= 0 && channelData != 0)
  16881. {
  16882. char mx = -128;
  16883. char mn = 127;
  16884. while (sample <= nextSample)
  16885. {
  16886. if (sample >= numFinished)
  16887. break;
  16888. const int n = sample << 1;
  16889. const char sampMin = channelData [n];
  16890. const char sampMax = channelData [n + 1];
  16891. if (sampMin < mn)
  16892. mn = sampMin;
  16893. if (sampMax > mx)
  16894. mx = sampMax;
  16895. ++sample;
  16896. }
  16897. if (mn <= mx)
  16898. {
  16899. cacheData[0] = mn;
  16900. cacheData[1] = mx;
  16901. }
  16902. else
  16903. {
  16904. cacheData[0] = 1;
  16905. cacheData[1] = 0;
  16906. }
  16907. }
  16908. else
  16909. {
  16910. cacheData[0] = 1;
  16911. cacheData[1] = 0;
  16912. }
  16913. cacheData += numChannelsCached * 2;
  16914. startTime += timePerPixel;
  16915. sample = nextSample;
  16916. }
  16917. }
  16918. }
  16919. }
  16920. void AudioThumbnail::drawChannel (Graphics& g,
  16921. int x, int y, int w, int h,
  16922. double startTime,
  16923. double endTime,
  16924. int channelNum,
  16925. const float verticalZoomFactor)
  16926. {
  16927. refillCache (w, startTime, (endTime - startTime) / w);
  16928. if (numSamplesCached >= w
  16929. && channelNum >= 0
  16930. && channelNum < numChannelsCached)
  16931. {
  16932. const float topY = (float) y;
  16933. const float bottomY = topY + h;
  16934. const float midY = topY + h * 0.5f;
  16935. const float vscale = verticalZoomFactor * h / 256.0f;
  16936. const Rectangle<int> clip (g.getClipBounds());
  16937. const int skipLeft = jlimit (0, w, clip.getX() - x);
  16938. w -= skipLeft;
  16939. x += skipLeft;
  16940. const char* cacheData = static_cast <const char*> (cachedLevels.getData())
  16941. + (channelNum << 1)
  16942. + skipLeft * (numChannelsCached << 1);
  16943. while (--w >= 0)
  16944. {
  16945. const char mn = cacheData[0];
  16946. const char mx = cacheData[1];
  16947. cacheData += numChannelsCached << 1;
  16948. if (mn <= mx) // if the wrong way round, signifies that the sample's not yet known
  16949. g.drawLine ((float) x, jmax (midY - mx * vscale - 0.3f, topY),
  16950. (float) x, jmin (midY - mn * vscale + 0.3f, bottomY));
  16951. ++x;
  16952. if (x >= clip.getRight())
  16953. break;
  16954. }
  16955. }
  16956. }
  16957. END_JUCE_NAMESPACE
  16958. /*** End of inlined file: juce_AudioThumbnail.cpp ***/
  16959. /*** Start of inlined file: juce_AudioThumbnailCache.cpp ***/
  16960. BEGIN_JUCE_NAMESPACE
  16961. struct ThumbnailCacheEntry
  16962. {
  16963. int64 hash;
  16964. uint32 lastUsed;
  16965. MemoryBlock data;
  16966. juce_UseDebuggingNewOperator
  16967. };
  16968. AudioThumbnailCache::AudioThumbnailCache (const int maxNumThumbsToStore_)
  16969. : TimeSliceThread ("thumb cache"),
  16970. maxNumThumbsToStore (maxNumThumbsToStore_)
  16971. {
  16972. startThread (2);
  16973. }
  16974. AudioThumbnailCache::~AudioThumbnailCache()
  16975. {
  16976. }
  16977. bool AudioThumbnailCache::loadThumb (AudioThumbnail& thumb, const int64 hashCode)
  16978. {
  16979. for (int i = thumbs.size(); --i >= 0;)
  16980. {
  16981. if (thumbs[i]->hash == hashCode)
  16982. {
  16983. MemoryInputStream in (thumbs[i]->data, false);
  16984. thumb.loadFrom (in);
  16985. thumbs[i]->lastUsed = Time::getMillisecondCounter();
  16986. return true;
  16987. }
  16988. }
  16989. return false;
  16990. }
  16991. void AudioThumbnailCache::storeThumb (const AudioThumbnail& thumb,
  16992. const int64 hashCode)
  16993. {
  16994. MemoryOutputStream out;
  16995. thumb.saveTo (out);
  16996. ThumbnailCacheEntry* te = 0;
  16997. for (int i = thumbs.size(); --i >= 0;)
  16998. {
  16999. if (thumbs[i]->hash == hashCode)
  17000. {
  17001. te = thumbs[i];
  17002. break;
  17003. }
  17004. }
  17005. if (te == 0)
  17006. {
  17007. te = new ThumbnailCacheEntry();
  17008. te->hash = hashCode;
  17009. if (thumbs.size() < maxNumThumbsToStore)
  17010. {
  17011. thumbs.add (te);
  17012. }
  17013. else
  17014. {
  17015. int oldest = 0;
  17016. unsigned int oldestTime = Time::getMillisecondCounter() + 1;
  17017. int i;
  17018. for (i = thumbs.size(); --i >= 0;)
  17019. if (thumbs[i]->lastUsed < oldestTime)
  17020. oldest = i;
  17021. thumbs.set (i, te);
  17022. }
  17023. }
  17024. te->lastUsed = Time::getMillisecondCounter();
  17025. te->data.setSize (0);
  17026. te->data.append (out.getData(), out.getDataSize());
  17027. }
  17028. void AudioThumbnailCache::clear()
  17029. {
  17030. thumbs.clear();
  17031. }
  17032. void AudioThumbnailCache::addThumbnail (AudioThumbnail* const thumb)
  17033. {
  17034. addTimeSliceClient (thumb);
  17035. }
  17036. void AudioThumbnailCache::removeThumbnail (AudioThumbnail* const thumb)
  17037. {
  17038. removeTimeSliceClient (thumb);
  17039. }
  17040. END_JUCE_NAMESPACE
  17041. /*** End of inlined file: juce_AudioThumbnailCache.cpp ***/
  17042. /*** Start of inlined file: juce_QuickTimeAudioFormat.cpp ***/
  17043. #if JUCE_QUICKTIME && ! (JUCE_64BIT || JUCE_IPHONE)
  17044. #if ! JUCE_WINDOWS
  17045. #include <QuickTime/Movies.h>
  17046. #include <QuickTime/QTML.h>
  17047. #include <QuickTime/QuickTimeComponents.h>
  17048. #include <QuickTime/MediaHandlers.h>
  17049. #include <QuickTime/ImageCodec.h>
  17050. #else
  17051. #if JUCE_MSVC
  17052. #pragma warning (push)
  17053. #pragma warning (disable : 4100)
  17054. #endif
  17055. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  17056. add its header directory to your include path.
  17057. Alternatively, if you don't need any QuickTime services, just turn off the JUC_QUICKTIME
  17058. flag in juce_Config.h
  17059. */
  17060. #include <Movies.h>
  17061. #include <QTML.h>
  17062. #include <QuickTimeComponents.h>
  17063. #include <MediaHandlers.h>
  17064. #include <ImageCodec.h>
  17065. #if JUCE_MSVC
  17066. #pragma warning (pop)
  17067. #endif
  17068. #endif
  17069. BEGIN_JUCE_NAMESPACE
  17070. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  17071. static const char* const quickTimeFormatName = "QuickTime file";
  17072. static const char* const quickTimeExtensions[] = { ".mov", ".mp3", ".mp4", 0 };
  17073. class QTAudioReader : public AudioFormatReader
  17074. {
  17075. public:
  17076. QTAudioReader (InputStream* const input_, const int trackNum_)
  17077. : AudioFormatReader (input_, TRANS (quickTimeFormatName)),
  17078. ok (false),
  17079. movie (0),
  17080. trackNum (trackNum_),
  17081. lastSampleRead (0),
  17082. lastThreadId (0),
  17083. extractor (0),
  17084. dataHandle (0)
  17085. {
  17086. bufferList.calloc (256, 1);
  17087. #if JUCE_WINDOWS
  17088. if (InitializeQTML (0) != noErr)
  17089. return;
  17090. #endif
  17091. if (EnterMovies() != noErr)
  17092. return;
  17093. bool opened = juce_OpenQuickTimeMovieFromStream (input_, movie, dataHandle);
  17094. if (! opened)
  17095. return;
  17096. {
  17097. const int numTracks = GetMovieTrackCount (movie);
  17098. int trackCount = 0;
  17099. for (int i = 1; i <= numTracks; ++i)
  17100. {
  17101. track = GetMovieIndTrack (movie, i);
  17102. media = GetTrackMedia (track);
  17103. OSType mediaType;
  17104. GetMediaHandlerDescription (media, &mediaType, 0, 0);
  17105. if (mediaType == SoundMediaType
  17106. && trackCount++ == trackNum_)
  17107. {
  17108. ok = true;
  17109. break;
  17110. }
  17111. }
  17112. }
  17113. if (! ok)
  17114. return;
  17115. ok = false;
  17116. lengthInSamples = GetMediaDecodeDuration (media);
  17117. usesFloatingPointData = false;
  17118. samplesPerFrame = (int) (GetMediaDecodeDuration (media) / GetMediaSampleCount (media));
  17119. trackUnitsPerFrame = GetMovieTimeScale (movie) * samplesPerFrame
  17120. / GetMediaTimeScale (media);
  17121. OSStatus err = MovieAudioExtractionBegin (movie, 0, &extractor);
  17122. unsigned long output_layout_size;
  17123. err = MovieAudioExtractionGetPropertyInfo (extractor,
  17124. kQTPropertyClass_MovieAudioExtraction_Audio,
  17125. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  17126. 0, &output_layout_size, 0);
  17127. if (err != noErr)
  17128. return;
  17129. HeapBlock <AudioChannelLayout> qt_audio_channel_layout;
  17130. qt_audio_channel_layout.calloc (output_layout_size, 1);
  17131. err = MovieAudioExtractionGetProperty (extractor,
  17132. kQTPropertyClass_MovieAudioExtraction_Audio,
  17133. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  17134. output_layout_size, qt_audio_channel_layout, 0);
  17135. qt_audio_channel_layout[0].mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  17136. err = MovieAudioExtractionSetProperty (extractor,
  17137. kQTPropertyClass_MovieAudioExtraction_Audio,
  17138. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  17139. output_layout_size,
  17140. qt_audio_channel_layout);
  17141. err = MovieAudioExtractionGetProperty (extractor,
  17142. kQTPropertyClass_MovieAudioExtraction_Audio,
  17143. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  17144. sizeof (inputStreamDesc),
  17145. &inputStreamDesc, 0);
  17146. if (err != noErr)
  17147. return;
  17148. inputStreamDesc.mFormatFlags = kAudioFormatFlagIsSignedInteger
  17149. | kAudioFormatFlagIsPacked
  17150. | kAudioFormatFlagsNativeEndian;
  17151. inputStreamDesc.mBitsPerChannel = sizeof (SInt16) * 8;
  17152. inputStreamDesc.mChannelsPerFrame = jmin ((UInt32) 2, inputStreamDesc.mChannelsPerFrame);
  17153. inputStreamDesc.mBytesPerFrame = sizeof (SInt16) * inputStreamDesc.mChannelsPerFrame;
  17154. inputStreamDesc.mBytesPerPacket = inputStreamDesc.mBytesPerFrame;
  17155. err = MovieAudioExtractionSetProperty (extractor,
  17156. kQTPropertyClass_MovieAudioExtraction_Audio,
  17157. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  17158. sizeof (inputStreamDesc),
  17159. &inputStreamDesc);
  17160. if (err != noErr)
  17161. return;
  17162. Boolean allChannelsDiscrete = false;
  17163. err = MovieAudioExtractionSetProperty (extractor,
  17164. kQTPropertyClass_MovieAudioExtraction_Movie,
  17165. kQTMovieAudioExtractionMoviePropertyID_AllChannelsDiscrete,
  17166. sizeof (allChannelsDiscrete),
  17167. &allChannelsDiscrete);
  17168. if (err != noErr)
  17169. return;
  17170. bufferList->mNumberBuffers = 1;
  17171. bufferList->mBuffers[0].mNumberChannels = inputStreamDesc.mChannelsPerFrame;
  17172. bufferList->mBuffers[0].mDataByteSize = (UInt32) (samplesPerFrame * inputStreamDesc.mBytesPerFrame) + 16;
  17173. dataBuffer.malloc (bufferList->mBuffers[0].mDataByteSize);
  17174. bufferList->mBuffers[0].mData = dataBuffer;
  17175. sampleRate = inputStreamDesc.mSampleRate;
  17176. bitsPerSample = 16;
  17177. numChannels = inputStreamDesc.mChannelsPerFrame;
  17178. detachThread();
  17179. ok = true;
  17180. }
  17181. ~QTAudioReader()
  17182. {
  17183. if (dataHandle != 0)
  17184. DisposeHandle (dataHandle);
  17185. if (extractor != 0)
  17186. {
  17187. MovieAudioExtractionEnd (extractor);
  17188. extractor = 0;
  17189. }
  17190. checkThreadIsAttached();
  17191. DisposeMovie (movie);
  17192. #if JUCE_MAC
  17193. ExitMoviesOnThread ();
  17194. #endif
  17195. }
  17196. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  17197. int64 startSampleInFile, int numSamples)
  17198. {
  17199. checkThreadIsAttached();
  17200. while (numSamples > 0)
  17201. {
  17202. if (! loadFrame ((int) startSampleInFile))
  17203. return false;
  17204. const int numToDo = jmin (numSamples, samplesPerFrame);
  17205. for (int j = numDestChannels; --j >= 0;)
  17206. {
  17207. if (destSamples[j] != 0)
  17208. {
  17209. const short* const src = ((const short*) bufferList->mBuffers[0].mData) + j;
  17210. for (int i = 0; i < numToDo; ++i)
  17211. destSamples[j][startOffsetInDestBuffer + i] = src [i << 1] << 16;
  17212. }
  17213. }
  17214. startOffsetInDestBuffer += numToDo;
  17215. startSampleInFile += numToDo;
  17216. numSamples -= numToDo;
  17217. }
  17218. detachThread();
  17219. return true;
  17220. }
  17221. bool loadFrame (const int sampleNum)
  17222. {
  17223. if (lastSampleRead != sampleNum)
  17224. {
  17225. TimeRecord time;
  17226. time.scale = (TimeScale) inputStreamDesc.mSampleRate;
  17227. time.base = 0;
  17228. time.value.hi = 0;
  17229. time.value.lo = (UInt32) sampleNum;
  17230. OSStatus err = MovieAudioExtractionSetProperty (extractor,
  17231. kQTPropertyClass_MovieAudioExtraction_Movie,
  17232. kQTMovieAudioExtractionMoviePropertyID_CurrentTime,
  17233. sizeof (time), &time);
  17234. if (err != noErr)
  17235. return false;
  17236. }
  17237. bufferList->mBuffers[0].mDataByteSize = inputStreamDesc.mBytesPerFrame * samplesPerFrame;
  17238. UInt32 outFlags = 0;
  17239. UInt32 actualNumSamples = samplesPerFrame;
  17240. OSStatus err = MovieAudioExtractionFillBuffer (extractor, &actualNumSamples,
  17241. bufferList, &outFlags);
  17242. lastSampleRead = sampleNum + samplesPerFrame;
  17243. return err == noErr;
  17244. }
  17245. juce_UseDebuggingNewOperator
  17246. bool ok;
  17247. private:
  17248. Movie movie;
  17249. Media media;
  17250. Track track;
  17251. const int trackNum;
  17252. double trackUnitsPerFrame;
  17253. int samplesPerFrame;
  17254. int lastSampleRead;
  17255. Thread::ThreadID lastThreadId;
  17256. MovieAudioExtractionRef extractor;
  17257. AudioStreamBasicDescription inputStreamDesc;
  17258. HeapBlock <AudioBufferList> bufferList;
  17259. HeapBlock <char> dataBuffer;
  17260. Handle dataHandle;
  17261. void checkThreadIsAttached()
  17262. {
  17263. #if JUCE_MAC
  17264. if (Thread::getCurrentThreadId() != lastThreadId)
  17265. EnterMoviesOnThread (0);
  17266. AttachMovieToCurrentThread (movie);
  17267. #endif
  17268. }
  17269. void detachThread()
  17270. {
  17271. #if JUCE_MAC
  17272. DetachMovieFromCurrentThread (movie);
  17273. #endif
  17274. }
  17275. QTAudioReader (const QTAudioReader&);
  17276. QTAudioReader& operator= (const QTAudioReader&);
  17277. };
  17278. QuickTimeAudioFormat::QuickTimeAudioFormat()
  17279. : AudioFormat (TRANS (quickTimeFormatName), StringArray (quickTimeExtensions))
  17280. {
  17281. }
  17282. QuickTimeAudioFormat::~QuickTimeAudioFormat()
  17283. {
  17284. }
  17285. const Array <int> QuickTimeAudioFormat::getPossibleSampleRates()
  17286. {
  17287. return Array<int>();
  17288. }
  17289. const Array <int> QuickTimeAudioFormat::getPossibleBitDepths()
  17290. {
  17291. return Array<int>();
  17292. }
  17293. bool QuickTimeAudioFormat::canDoStereo()
  17294. {
  17295. return true;
  17296. }
  17297. bool QuickTimeAudioFormat::canDoMono()
  17298. {
  17299. return true;
  17300. }
  17301. AudioFormatReader* QuickTimeAudioFormat::createReaderFor (InputStream* sourceStream,
  17302. const bool deleteStreamIfOpeningFails)
  17303. {
  17304. ScopedPointer <QTAudioReader> r (new QTAudioReader (sourceStream, 0));
  17305. if (r->ok)
  17306. return r.release();
  17307. if (! deleteStreamIfOpeningFails)
  17308. r->input = 0;
  17309. return 0;
  17310. }
  17311. AudioFormatWriter* QuickTimeAudioFormat::createWriterFor (OutputStream* /*streamToWriteTo*/,
  17312. double /*sampleRateToUse*/,
  17313. unsigned int /*numberOfChannels*/,
  17314. int /*bitsPerSample*/,
  17315. const StringPairArray& /*metadataValues*/,
  17316. int /*qualityOptionIndex*/)
  17317. {
  17318. jassertfalse; // not yet implemented!
  17319. return 0;
  17320. }
  17321. END_JUCE_NAMESPACE
  17322. #endif
  17323. /*** End of inlined file: juce_QuickTimeAudioFormat.cpp ***/
  17324. /*** Start of inlined file: juce_WavAudioFormat.cpp ***/
  17325. BEGIN_JUCE_NAMESPACE
  17326. static const char* const wavFormatName = "WAV file";
  17327. static const char* const wavExtensions[] = { ".wav", ".bwf", 0 };
  17328. const char* const WavAudioFormat::bwavDescription = "bwav description";
  17329. const char* const WavAudioFormat::bwavOriginator = "bwav originator";
  17330. const char* const WavAudioFormat::bwavOriginatorRef = "bwav originator ref";
  17331. const char* const WavAudioFormat::bwavOriginationDate = "bwav origination date";
  17332. const char* const WavAudioFormat::bwavOriginationTime = "bwav origination time";
  17333. const char* const WavAudioFormat::bwavTimeReference = "bwav time reference";
  17334. const char* const WavAudioFormat::bwavCodingHistory = "bwav coding history";
  17335. const StringPairArray WavAudioFormat::createBWAVMetadata (const String& description,
  17336. const String& originator,
  17337. const String& originatorRef,
  17338. const Time& date,
  17339. const int64 timeReferenceSamples,
  17340. const String& codingHistory)
  17341. {
  17342. StringPairArray m;
  17343. m.set (bwavDescription, description);
  17344. m.set (bwavOriginator, originator);
  17345. m.set (bwavOriginatorRef, originatorRef);
  17346. m.set (bwavOriginationDate, date.formatted ("%Y-%m-%d"));
  17347. m.set (bwavOriginationTime, date.formatted ("%H:%M:%S"));
  17348. m.set (bwavTimeReference, String (timeReferenceSamples));
  17349. m.set (bwavCodingHistory, codingHistory);
  17350. return m;
  17351. }
  17352. #if JUCE_MSVC
  17353. #pragma pack (push, 1)
  17354. #define PACKED
  17355. #elif JUCE_GCC
  17356. #define PACKED __attribute__((packed))
  17357. #else
  17358. #define PACKED
  17359. #endif
  17360. struct BWAVChunk
  17361. {
  17362. char description [256];
  17363. char originator [32];
  17364. char originatorRef [32];
  17365. char originationDate [10];
  17366. char originationTime [8];
  17367. uint32 timeRefLow;
  17368. uint32 timeRefHigh;
  17369. uint16 version;
  17370. uint8 umid[64];
  17371. uint8 reserved[190];
  17372. char codingHistory[1];
  17373. void copyTo (StringPairArray& values) const
  17374. {
  17375. values.set (WavAudioFormat::bwavDescription, String::fromUTF8 (description, 256));
  17376. values.set (WavAudioFormat::bwavOriginator, String::fromUTF8 (originator, 32));
  17377. values.set (WavAudioFormat::bwavOriginatorRef, String::fromUTF8 (originatorRef, 32));
  17378. values.set (WavAudioFormat::bwavOriginationDate, String::fromUTF8 (originationDate, 10));
  17379. values.set (WavAudioFormat::bwavOriginationTime, String::fromUTF8 (originationTime, 8));
  17380. const uint32 timeLow = ByteOrder::swapIfBigEndian (timeRefLow);
  17381. const uint32 timeHigh = ByteOrder::swapIfBigEndian (timeRefHigh);
  17382. const int64 time = (((int64)timeHigh) << 32) + timeLow;
  17383. values.set (WavAudioFormat::bwavTimeReference, String (time));
  17384. values.set (WavAudioFormat::bwavCodingHistory, String::fromUTF8 (codingHistory));
  17385. }
  17386. static MemoryBlock createFrom (const StringPairArray& values)
  17387. {
  17388. const size_t sizeNeeded = sizeof (BWAVChunk) + values [WavAudioFormat::bwavCodingHistory].getNumBytesAsUTF8();
  17389. MemoryBlock data ((sizeNeeded + 3) & ~3);
  17390. data.fillWith (0);
  17391. BWAVChunk* b = (BWAVChunk*) data.getData();
  17392. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  17393. // as they get called in the right order..
  17394. values [WavAudioFormat::bwavDescription].copyToUTF8 (b->description, 257);
  17395. values [WavAudioFormat::bwavOriginator].copyToUTF8 (b->originator, 33);
  17396. values [WavAudioFormat::bwavOriginatorRef].copyToUTF8 (b->originatorRef, 33);
  17397. values [WavAudioFormat::bwavOriginationDate].copyToUTF8 (b->originationDate, 11);
  17398. values [WavAudioFormat::bwavOriginationTime].copyToUTF8 (b->originationTime, 9);
  17399. const int64 time = values [WavAudioFormat::bwavTimeReference].getLargeIntValue();
  17400. b->timeRefLow = ByteOrder::swapIfBigEndian ((uint32) (time & 0xffffffff));
  17401. b->timeRefHigh = ByteOrder::swapIfBigEndian ((uint32) (time >> 32));
  17402. values [WavAudioFormat::bwavCodingHistory].copyToUTF8 (b->codingHistory, 0x7fffffff);
  17403. if (b->description[0] != 0
  17404. || b->originator[0] != 0
  17405. || b->originationDate[0] != 0
  17406. || b->originationTime[0] != 0
  17407. || b->codingHistory[0] != 0
  17408. || time != 0)
  17409. {
  17410. return data;
  17411. }
  17412. return MemoryBlock();
  17413. }
  17414. } PACKED;
  17415. struct SMPLChunk
  17416. {
  17417. struct SampleLoop
  17418. {
  17419. uint32 identifier;
  17420. uint32 type;
  17421. uint32 start;
  17422. uint32 end;
  17423. uint32 fraction;
  17424. uint32 playCount;
  17425. } PACKED;
  17426. uint32 manufacturer;
  17427. uint32 product;
  17428. uint32 samplePeriod;
  17429. uint32 midiUnityNote;
  17430. uint32 midiPitchFraction;
  17431. uint32 smpteFormat;
  17432. uint32 smpteOffset;
  17433. uint32 numSampleLoops;
  17434. uint32 samplerData;
  17435. SampleLoop loops[1];
  17436. void copyTo (StringPairArray& values, const int totalSize) const
  17437. {
  17438. values.set ("Manufacturer", String (ByteOrder::swapIfBigEndian (manufacturer)));
  17439. values.set ("Product", String (ByteOrder::swapIfBigEndian (product)));
  17440. values.set ("SamplePeriod", String (ByteOrder::swapIfBigEndian (samplePeriod)));
  17441. values.set ("MidiUnityNote", String (ByteOrder::swapIfBigEndian (midiUnityNote)));
  17442. values.set ("MidiPitchFraction", String (ByteOrder::swapIfBigEndian (midiPitchFraction)));
  17443. values.set ("SmpteFormat", String (ByteOrder::swapIfBigEndian (smpteFormat)));
  17444. values.set ("SmpteOffset", String (ByteOrder::swapIfBigEndian (smpteOffset)));
  17445. values.set ("NumSampleLoops", String (ByteOrder::swapIfBigEndian (numSampleLoops)));
  17446. values.set ("SamplerData", String (ByteOrder::swapIfBigEndian (samplerData)));
  17447. for (uint32 i = 0; i < numSampleLoops; ++i)
  17448. {
  17449. if ((uint8*) (loops + (i + 1)) > ((uint8*) this) + totalSize)
  17450. break;
  17451. const String prefix ("Loop" + String(i));
  17452. values.set (prefix + "Identifier", String (ByteOrder::swapIfBigEndian (loops[i].identifier)));
  17453. values.set (prefix + "Type", String (ByteOrder::swapIfBigEndian (loops[i].type)));
  17454. values.set (prefix + "Start", String (ByteOrder::swapIfBigEndian (loops[i].start)));
  17455. values.set (prefix + "End", String (ByteOrder::swapIfBigEndian (loops[i].end)));
  17456. values.set (prefix + "Fraction", String (ByteOrder::swapIfBigEndian (loops[i].fraction)));
  17457. values.set (prefix + "PlayCount", String (ByteOrder::swapIfBigEndian (loops[i].playCount)));
  17458. }
  17459. }
  17460. static MemoryBlock createFrom (const StringPairArray& values)
  17461. {
  17462. const int numLoops = jmin (64, values.getValue ("NumSampleLoops", "0").getIntValue());
  17463. if (numLoops <= 0)
  17464. return MemoryBlock();
  17465. const size_t sizeNeeded = sizeof (SMPLChunk) + (numLoops - 1) * sizeof (SampleLoop);
  17466. MemoryBlock data ((sizeNeeded + 3) & ~3);
  17467. data.fillWith (0);
  17468. SMPLChunk* s = (SMPLChunk*) data.getData();
  17469. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  17470. // as they get called in the right order..
  17471. s->manufacturer = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("Manufacturer", "0").getIntValue());
  17472. s->product = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("Product", "0").getIntValue());
  17473. s->samplePeriod = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SamplePeriod", "0").getIntValue());
  17474. s->midiUnityNote = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("MidiUnityNote", "60").getIntValue());
  17475. s->midiPitchFraction = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("MidiPitchFraction", "0").getIntValue());
  17476. s->smpteFormat = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SmpteFormat", "0").getIntValue());
  17477. s->smpteOffset = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SmpteOffset", "0").getIntValue());
  17478. s->numSampleLoops = ByteOrder::swapIfBigEndian ((uint32) numLoops);
  17479. s->samplerData = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SamplerData", "0").getIntValue());
  17480. for (int i = 0; i < numLoops; ++i)
  17481. {
  17482. const String prefix ("Loop" + String(i));
  17483. s->loops[i].identifier = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Identifier", "0").getIntValue());
  17484. s->loops[i].type = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Type", "0").getIntValue());
  17485. s->loops[i].start = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Start", "0").getIntValue());
  17486. s->loops[i].end = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "End", "0").getIntValue());
  17487. s->loops[i].fraction = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Fraction", "0").getIntValue());
  17488. s->loops[i].playCount = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "PlayCount", "0").getIntValue());
  17489. }
  17490. return data;
  17491. }
  17492. } PACKED;
  17493. struct ExtensibleWavSubFormat
  17494. {
  17495. uint32 data1;
  17496. uint16 data2;
  17497. uint16 data3;
  17498. uint8 data4[8];
  17499. } PACKED;
  17500. #if JUCE_MSVC
  17501. #pragma pack (pop)
  17502. #endif
  17503. #undef PACKED
  17504. class WavAudioFormatReader : public AudioFormatReader
  17505. {
  17506. int bytesPerFrame;
  17507. int64 dataChunkStart, dataLength;
  17508. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  17509. WavAudioFormatReader (const WavAudioFormatReader&);
  17510. WavAudioFormatReader& operator= (const WavAudioFormatReader&);
  17511. public:
  17512. int64 bwavChunkStart, bwavSize;
  17513. WavAudioFormatReader (InputStream* const in)
  17514. : AudioFormatReader (in, TRANS (wavFormatName)),
  17515. dataLength (0),
  17516. bwavChunkStart (0),
  17517. bwavSize (0)
  17518. {
  17519. if (input->readInt() == chunkName ("RIFF"))
  17520. {
  17521. const uint32 len = (uint32) input->readInt();
  17522. const int64 end = input->getPosition() + len;
  17523. bool hasGotType = false;
  17524. bool hasGotData = false;
  17525. if (input->readInt() == chunkName ("WAVE"))
  17526. {
  17527. while (input->getPosition() < end
  17528. && ! input->isExhausted())
  17529. {
  17530. const int chunkType = input->readInt();
  17531. uint32 length = (uint32) input->readInt();
  17532. const int64 chunkEnd = input->getPosition() + length + (length & 1);
  17533. if (chunkType == chunkName ("fmt "))
  17534. {
  17535. // read the format chunk
  17536. const unsigned short format = input->readShort();
  17537. const short numChans = input->readShort();
  17538. sampleRate = input->readInt();
  17539. const int bytesPerSec = input->readInt();
  17540. numChannels = numChans;
  17541. bytesPerFrame = bytesPerSec / (int)sampleRate;
  17542. bitsPerSample = 8 * bytesPerFrame / numChans;
  17543. if (format == 3)
  17544. {
  17545. usesFloatingPointData = true;
  17546. }
  17547. else if (format == 0xfffe /*WAVE_FORMAT_EXTENSIBLE*/)
  17548. {
  17549. if (length < 40) // too short
  17550. {
  17551. bytesPerFrame = 0;
  17552. }
  17553. else
  17554. {
  17555. input->skipNextBytes (12); // skip over blockAlign, bitsPerSample and speakerPosition mask
  17556. ExtensibleWavSubFormat subFormat;
  17557. subFormat.data1 = input->readInt();
  17558. subFormat.data2 = input->readShort();
  17559. subFormat.data3 = input->readShort();
  17560. input->read (subFormat.data4, sizeof (subFormat.data4));
  17561. const ExtensibleWavSubFormat pcmFormat
  17562. = { 0x00000001, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  17563. if (memcmp (&subFormat, &pcmFormat, sizeof (subFormat)) != 0)
  17564. {
  17565. const ExtensibleWavSubFormat ambisonicFormat
  17566. = { 0x00000001, 0x0721, 0x11d3, { 0x86, 0x44, 0xC8, 0xC1, 0xCA, 0x00, 0x00, 0x00 } };
  17567. if (memcmp (&subFormat, &ambisonicFormat, sizeof (subFormat)) != 0)
  17568. bytesPerFrame = 0;
  17569. }
  17570. }
  17571. }
  17572. else if (format != 1)
  17573. {
  17574. bytesPerFrame = 0;
  17575. }
  17576. hasGotType = true;
  17577. }
  17578. else if (chunkType == chunkName ("data"))
  17579. {
  17580. // get the data chunk's position
  17581. dataLength = length;
  17582. dataChunkStart = input->getPosition();
  17583. lengthInSamples = (bytesPerFrame > 0) ? (dataLength / bytesPerFrame) : 0;
  17584. hasGotData = true;
  17585. }
  17586. else if (chunkType == chunkName ("bext"))
  17587. {
  17588. bwavChunkStart = input->getPosition();
  17589. bwavSize = length;
  17590. // Broadcast-wav extension chunk..
  17591. HeapBlock <BWAVChunk> bwav;
  17592. bwav.calloc (jmax ((size_t) length + 1, sizeof (BWAVChunk)), 1);
  17593. input->read (bwav, length);
  17594. bwav->copyTo (metadataValues);
  17595. }
  17596. else if (chunkType == chunkName ("smpl"))
  17597. {
  17598. HeapBlock <SMPLChunk> smpl;
  17599. smpl.calloc (jmax ((size_t) length + 1, sizeof (SMPLChunk)), 1);
  17600. input->read (smpl, length);
  17601. smpl->copyTo (metadataValues, length);
  17602. }
  17603. else if (chunkEnd <= input->getPosition())
  17604. {
  17605. break;
  17606. }
  17607. input->setPosition (chunkEnd);
  17608. }
  17609. }
  17610. }
  17611. }
  17612. ~WavAudioFormatReader()
  17613. {
  17614. }
  17615. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  17616. int64 startSampleInFile, int numSamples)
  17617. {
  17618. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  17619. if (samplesAvailable < numSamples)
  17620. {
  17621. for (int i = numDestChannels; --i >= 0;)
  17622. if (destSamples[i] != 0)
  17623. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  17624. numSamples = (int) samplesAvailable;
  17625. }
  17626. if (numSamples <= 0)
  17627. return true;
  17628. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  17629. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  17630. char tempBuffer [tempBufSize];
  17631. while (numSamples > 0)
  17632. {
  17633. int* left = destSamples[0];
  17634. if (left != 0)
  17635. left += startOffsetInDestBuffer;
  17636. int* right = numDestChannels > 1 ? destSamples[1] : 0;
  17637. if (right != 0)
  17638. right += startOffsetInDestBuffer;
  17639. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  17640. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  17641. if (bytesRead < numThisTime * bytesPerFrame)
  17642. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  17643. if (bitsPerSample == 16)
  17644. {
  17645. const short* src = reinterpret_cast <const short*> (tempBuffer);
  17646. if (numChannels > 1)
  17647. {
  17648. if (left == 0)
  17649. {
  17650. for (int i = numThisTime; --i >= 0;)
  17651. {
  17652. ++src;
  17653. *right++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  17654. }
  17655. }
  17656. else if (right == 0)
  17657. {
  17658. for (int i = numThisTime; --i >= 0;)
  17659. {
  17660. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  17661. ++src;
  17662. }
  17663. }
  17664. else
  17665. {
  17666. for (int i = numThisTime; --i >= 0;)
  17667. {
  17668. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  17669. *right++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  17670. }
  17671. }
  17672. }
  17673. else
  17674. {
  17675. for (int i = numThisTime; --i >= 0;)
  17676. {
  17677. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  17678. }
  17679. }
  17680. }
  17681. else if (bitsPerSample == 24)
  17682. {
  17683. const char* src = tempBuffer;
  17684. if (numChannels > 1)
  17685. {
  17686. if (left == 0)
  17687. {
  17688. for (int i = numThisTime; --i >= 0;)
  17689. {
  17690. src += 3;
  17691. *right++ = ByteOrder::littleEndian24Bit (src) << 8;
  17692. src += 3;
  17693. }
  17694. }
  17695. else if (right == 0)
  17696. {
  17697. for (int i = numThisTime; --i >= 0;)
  17698. {
  17699. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  17700. src += 6;
  17701. }
  17702. }
  17703. else
  17704. {
  17705. for (int i = 0; i < numThisTime; ++i)
  17706. {
  17707. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  17708. src += 3;
  17709. *right++ = ByteOrder::littleEndian24Bit (src) << 8;
  17710. src += 3;
  17711. }
  17712. }
  17713. }
  17714. else
  17715. {
  17716. for (int i = 0; i < numThisTime; ++i)
  17717. {
  17718. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  17719. src += 3;
  17720. }
  17721. }
  17722. }
  17723. else if (bitsPerSample == 32)
  17724. {
  17725. const unsigned int* src = (const unsigned int*) tempBuffer;
  17726. unsigned int* l = (unsigned int*) left;
  17727. unsigned int* r = (unsigned int*) right;
  17728. if (numChannels > 1)
  17729. {
  17730. if (l == 0)
  17731. {
  17732. for (int i = numThisTime; --i >= 0;)
  17733. {
  17734. ++src;
  17735. *r++ = ByteOrder::swapIfBigEndian (*src++);
  17736. }
  17737. }
  17738. else if (r == 0)
  17739. {
  17740. for (int i = numThisTime; --i >= 0;)
  17741. {
  17742. *l++ = ByteOrder::swapIfBigEndian (*src++);
  17743. ++src;
  17744. }
  17745. }
  17746. else
  17747. {
  17748. for (int i = numThisTime; --i >= 0;)
  17749. {
  17750. *l++ = ByteOrder::swapIfBigEndian (*src++);
  17751. *r++ = ByteOrder::swapIfBigEndian (*src++);
  17752. }
  17753. }
  17754. }
  17755. else
  17756. {
  17757. for (int i = numThisTime; --i >= 0;)
  17758. {
  17759. *l++ = ByteOrder::swapIfBigEndian (*src++);
  17760. }
  17761. }
  17762. left = (int*)l;
  17763. right = (int*)r;
  17764. }
  17765. else if (bitsPerSample == 8)
  17766. {
  17767. const unsigned char* src = (const unsigned char*) tempBuffer;
  17768. if (numChannels > 1)
  17769. {
  17770. if (left == 0)
  17771. {
  17772. for (int i = numThisTime; --i >= 0;)
  17773. {
  17774. ++src;
  17775. *right++ = ((int) *src++ - 128) << 24;
  17776. }
  17777. }
  17778. else if (right == 0)
  17779. {
  17780. for (int i = numThisTime; --i >= 0;)
  17781. {
  17782. *left++ = ((int) *src++ - 128) << 24;
  17783. ++src;
  17784. }
  17785. }
  17786. else
  17787. {
  17788. for (int i = numThisTime; --i >= 0;)
  17789. {
  17790. *left++ = ((int) *src++ - 128) << 24;
  17791. *right++ = ((int) *src++ - 128) << 24;
  17792. }
  17793. }
  17794. }
  17795. else
  17796. {
  17797. for (int i = numThisTime; --i >= 0;)
  17798. {
  17799. *left++ = ((int)*src++ - 128) << 24;
  17800. }
  17801. }
  17802. }
  17803. startOffsetInDestBuffer += numThisTime;
  17804. numSamples -= numThisTime;
  17805. }
  17806. if (numSamples > 0)
  17807. {
  17808. for (int i = numDestChannels; --i >= 0;)
  17809. if (destSamples[i] != 0)
  17810. zeromem (destSamples[i] + startOffsetInDestBuffer,
  17811. sizeof (int) * numSamples);
  17812. }
  17813. return true;
  17814. }
  17815. juce_UseDebuggingNewOperator
  17816. };
  17817. class WavAudioFormatWriter : public AudioFormatWriter
  17818. {
  17819. MemoryBlock tempBlock, bwavChunk, smplChunk;
  17820. uint32 lengthInSamples, bytesWritten;
  17821. int64 headerPosition;
  17822. bool writeFailed;
  17823. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  17824. WavAudioFormatWriter (const WavAudioFormatWriter&);
  17825. WavAudioFormatWriter& operator= (const WavAudioFormatWriter&);
  17826. void writeHeader()
  17827. {
  17828. const bool seekedOk = output->setPosition (headerPosition);
  17829. (void) seekedOk;
  17830. // if this fails, you've given it an output stream that can't seek! It needs
  17831. // to be able to seek back to write the header
  17832. jassert (seekedOk);
  17833. const int bytesPerFrame = numChannels * bitsPerSample / 8;
  17834. output->writeInt (chunkName ("RIFF"));
  17835. output->writeInt ((int) (lengthInSamples * bytesPerFrame
  17836. + ((bwavChunk.getSize() > 0) ? (44 + bwavChunk.getSize()) : 36)));
  17837. output->writeInt (chunkName ("WAVE"));
  17838. output->writeInt (chunkName ("fmt "));
  17839. output->writeInt (16);
  17840. output->writeShort ((bitsPerSample < 32) ? (short) 1 /*WAVE_FORMAT_PCM*/
  17841. : (short) 3 /*WAVE_FORMAT_IEEE_FLOAT*/);
  17842. output->writeShort ((short) numChannels);
  17843. output->writeInt ((int) sampleRate);
  17844. output->writeInt (bytesPerFrame * (int) sampleRate);
  17845. output->writeShort ((short) bytesPerFrame);
  17846. output->writeShort ((short) bitsPerSample);
  17847. if (bwavChunk.getSize() > 0)
  17848. {
  17849. output->writeInt (chunkName ("bext"));
  17850. output->writeInt ((int) bwavChunk.getSize());
  17851. output->write (bwavChunk.getData(), (int) bwavChunk.getSize());
  17852. }
  17853. if (smplChunk.getSize() > 0)
  17854. {
  17855. output->writeInt (chunkName ("smpl"));
  17856. output->writeInt ((int) smplChunk.getSize());
  17857. output->write (smplChunk.getData(), (int) smplChunk.getSize());
  17858. }
  17859. output->writeInt (chunkName ("data"));
  17860. output->writeInt (lengthInSamples * bytesPerFrame);
  17861. usesFloatingPointData = (bitsPerSample == 32);
  17862. }
  17863. public:
  17864. WavAudioFormatWriter (OutputStream* const out,
  17865. const double sampleRate_,
  17866. const unsigned int numChannels_,
  17867. const int bits,
  17868. const StringPairArray& metadataValues)
  17869. : AudioFormatWriter (out,
  17870. TRANS (wavFormatName),
  17871. sampleRate_,
  17872. numChannels_,
  17873. bits),
  17874. lengthInSamples (0),
  17875. bytesWritten (0),
  17876. writeFailed (false)
  17877. {
  17878. if (metadataValues.size() > 0)
  17879. {
  17880. bwavChunk = BWAVChunk::createFrom (metadataValues);
  17881. smplChunk = SMPLChunk::createFrom (metadataValues);
  17882. }
  17883. headerPosition = out->getPosition();
  17884. writeHeader();
  17885. }
  17886. ~WavAudioFormatWriter()
  17887. {
  17888. writeHeader();
  17889. }
  17890. bool write (const int** data, int numSamples)
  17891. {
  17892. if (writeFailed)
  17893. return false;
  17894. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  17895. tempBlock.ensureSize (bytes, false);
  17896. char* buffer = static_cast <char*> (tempBlock.getData());
  17897. const int* left = data[0];
  17898. const int* right = data[1];
  17899. if (right == 0)
  17900. right = left;
  17901. if (bitsPerSample == 16)
  17902. {
  17903. short* b = (short*) buffer;
  17904. if (numChannels > 1)
  17905. {
  17906. for (int i = numSamples; --i >= 0;)
  17907. {
  17908. *b++ = (short) ByteOrder::swapIfBigEndian ((unsigned short) (*left++ >> 16));
  17909. *b++ = (short) ByteOrder::swapIfBigEndian ((unsigned short) (*right++ >> 16));
  17910. }
  17911. }
  17912. else
  17913. {
  17914. for (int i = numSamples; --i >= 0;)
  17915. {
  17916. *b++ = (short) ByteOrder::swapIfBigEndian ((unsigned short) (*left++ >> 16));
  17917. }
  17918. }
  17919. }
  17920. else if (bitsPerSample == 24)
  17921. {
  17922. char* b = buffer;
  17923. if (numChannels > 1)
  17924. {
  17925. for (int i = numSamples; --i >= 0;)
  17926. {
  17927. ByteOrder::littleEndian24BitToChars ((*left++) >> 8, b);
  17928. b += 3;
  17929. ByteOrder::littleEndian24BitToChars ((*right++) >> 8, b);
  17930. b += 3;
  17931. }
  17932. }
  17933. else
  17934. {
  17935. for (int i = numSamples; --i >= 0;)
  17936. {
  17937. ByteOrder::littleEndian24BitToChars ((*left++) >> 8, b);
  17938. b += 3;
  17939. }
  17940. }
  17941. }
  17942. else if (bitsPerSample == 32)
  17943. {
  17944. unsigned int* b = (unsigned int*) buffer;
  17945. if (numChannels > 1)
  17946. {
  17947. for (int i = numSamples; --i >= 0;)
  17948. {
  17949. *b++ = ByteOrder::swapIfBigEndian ((unsigned int) *left++);
  17950. *b++ = ByteOrder::swapIfBigEndian ((unsigned int) *right++);
  17951. }
  17952. }
  17953. else
  17954. {
  17955. for (int i = numSamples; --i >= 0;)
  17956. {
  17957. *b++ = ByteOrder::swapIfBigEndian ((unsigned int) *left++);
  17958. }
  17959. }
  17960. }
  17961. else if (bitsPerSample == 8)
  17962. {
  17963. unsigned char* b = (unsigned char*) buffer;
  17964. if (numChannels > 1)
  17965. {
  17966. for (int i = numSamples; --i >= 0;)
  17967. {
  17968. *b++ = (unsigned char) (128 + (*left++ >> 24));
  17969. *b++ = (unsigned char) (128 + (*right++ >> 24));
  17970. }
  17971. }
  17972. else
  17973. {
  17974. for (int i = numSamples; --i >= 0;)
  17975. {
  17976. *b++ = (unsigned char) (128 + (*left++ >> 24));
  17977. }
  17978. }
  17979. }
  17980. if (bytesWritten + bytes >= (uint32) 0xfff00000
  17981. || ! output->write (buffer, bytes))
  17982. {
  17983. // failed to write to disk, so let's try writing the header.
  17984. // If it's just run out of disk space, then if it does manage
  17985. // to write the header, we'll still have a useable file..
  17986. writeHeader();
  17987. writeFailed = true;
  17988. return false;
  17989. }
  17990. else
  17991. {
  17992. bytesWritten += bytes;
  17993. lengthInSamples += numSamples;
  17994. return true;
  17995. }
  17996. }
  17997. juce_UseDebuggingNewOperator
  17998. };
  17999. WavAudioFormat::WavAudioFormat()
  18000. : AudioFormat (TRANS (wavFormatName), StringArray (wavExtensions))
  18001. {
  18002. }
  18003. WavAudioFormat::~WavAudioFormat()
  18004. {
  18005. }
  18006. const Array <int> WavAudioFormat::getPossibleSampleRates()
  18007. {
  18008. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  18009. return Array <int> (rates);
  18010. }
  18011. const Array <int> WavAudioFormat::getPossibleBitDepths()
  18012. {
  18013. const int depths[] = { 8, 16, 24, 32, 0 };
  18014. return Array <int> (depths);
  18015. }
  18016. bool WavAudioFormat::canDoStereo()
  18017. {
  18018. return true;
  18019. }
  18020. bool WavAudioFormat::canDoMono()
  18021. {
  18022. return true;
  18023. }
  18024. AudioFormatReader* WavAudioFormat::createReaderFor (InputStream* sourceStream,
  18025. const bool deleteStreamIfOpeningFails)
  18026. {
  18027. ScopedPointer <WavAudioFormatReader> r (new WavAudioFormatReader (sourceStream));
  18028. if (r->sampleRate != 0)
  18029. return r.release();
  18030. if (! deleteStreamIfOpeningFails)
  18031. r->input = 0;
  18032. return 0;
  18033. }
  18034. AudioFormatWriter* WavAudioFormat::createWriterFor (OutputStream* out,
  18035. double sampleRate,
  18036. unsigned int numChannels,
  18037. int bitsPerSample,
  18038. const StringPairArray& metadataValues,
  18039. int /*qualityOptionIndex*/)
  18040. {
  18041. if (getPossibleBitDepths().contains (bitsPerSample))
  18042. {
  18043. return new WavAudioFormatWriter (out,
  18044. sampleRate,
  18045. numChannels,
  18046. bitsPerSample,
  18047. metadataValues);
  18048. }
  18049. return 0;
  18050. }
  18051. static bool juce_slowCopyOfWavFileWithNewMetadata (const File& file, const StringPairArray& metadata)
  18052. {
  18053. TemporaryFile tempFile (file);
  18054. WavAudioFormat wav;
  18055. ScopedPointer <AudioFormatReader> reader (wav.createReaderFor (file.createInputStream(), true));
  18056. if (reader != 0)
  18057. {
  18058. ScopedPointer <OutputStream> outStream (tempFile.getFile().createOutputStream());
  18059. if (outStream != 0)
  18060. {
  18061. ScopedPointer <AudioFormatWriter> writer (wav.createWriterFor (outStream, reader->sampleRate,
  18062. reader->numChannels, reader->bitsPerSample,
  18063. metadata, 0));
  18064. if (writer != 0)
  18065. {
  18066. outStream.release();
  18067. bool ok = writer->writeFromAudioReader (*reader, 0, -1);
  18068. writer = 0;
  18069. reader = 0;
  18070. return ok && tempFile.overwriteTargetFileWithTemporary();
  18071. }
  18072. }
  18073. }
  18074. return false;
  18075. }
  18076. bool WavAudioFormat::replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata)
  18077. {
  18078. ScopedPointer <WavAudioFormatReader> reader ((WavAudioFormatReader*) createReaderFor (wavFile.createInputStream(), true));
  18079. if (reader != 0)
  18080. {
  18081. const int64 bwavPos = reader->bwavChunkStart;
  18082. const int64 bwavSize = reader->bwavSize;
  18083. reader = 0;
  18084. if (bwavSize > 0)
  18085. {
  18086. MemoryBlock chunk = BWAVChunk::createFrom (newMetadata);
  18087. if (chunk.getSize() <= (size_t) bwavSize)
  18088. {
  18089. // the new one will fit in the space available, so write it directly..
  18090. const int64 oldSize = wavFile.getSize();
  18091. {
  18092. ScopedPointer <FileOutputStream> out (wavFile.createOutputStream());
  18093. out->setPosition (bwavPos);
  18094. out->write (chunk.getData(), (int) chunk.getSize());
  18095. out->setPosition (oldSize);
  18096. }
  18097. jassert (wavFile.getSize() == oldSize);
  18098. return true;
  18099. }
  18100. }
  18101. }
  18102. return juce_slowCopyOfWavFileWithNewMetadata (wavFile, newMetadata);
  18103. }
  18104. END_JUCE_NAMESPACE
  18105. /*** End of inlined file: juce_WavAudioFormat.cpp ***/
  18106. /*** Start of inlined file: juce_AudioFormatReaderSource.cpp ***/
  18107. BEGIN_JUCE_NAMESPACE
  18108. AudioFormatReaderSource::AudioFormatReaderSource (AudioFormatReader* const reader_,
  18109. const bool deleteReaderWhenThisIsDeleted)
  18110. : reader (reader_),
  18111. deleteReader (deleteReaderWhenThisIsDeleted),
  18112. nextPlayPos (0),
  18113. looping (false)
  18114. {
  18115. jassert (reader != 0);
  18116. }
  18117. AudioFormatReaderSource::~AudioFormatReaderSource()
  18118. {
  18119. releaseResources();
  18120. if (deleteReader)
  18121. delete reader;
  18122. }
  18123. void AudioFormatReaderSource::setNextReadPosition (int newPosition)
  18124. {
  18125. nextPlayPos = newPosition;
  18126. }
  18127. void AudioFormatReaderSource::setLooping (const bool shouldLoop) throw()
  18128. {
  18129. looping = shouldLoop;
  18130. }
  18131. int AudioFormatReaderSource::getNextReadPosition() const
  18132. {
  18133. return (looping) ? (nextPlayPos % (int) reader->lengthInSamples)
  18134. : nextPlayPos;
  18135. }
  18136. int AudioFormatReaderSource::getTotalLength() const
  18137. {
  18138. return (int) reader->lengthInSamples;
  18139. }
  18140. void AudioFormatReaderSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  18141. double /*sampleRate*/)
  18142. {
  18143. }
  18144. void AudioFormatReaderSource::releaseResources()
  18145. {
  18146. }
  18147. void AudioFormatReaderSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  18148. {
  18149. if (info.numSamples > 0)
  18150. {
  18151. const int start = nextPlayPos;
  18152. if (looping)
  18153. {
  18154. const int newStart = start % (int) reader->lengthInSamples;
  18155. const int newEnd = (start + info.numSamples) % (int) reader->lengthInSamples;
  18156. if (newEnd > newStart)
  18157. {
  18158. info.buffer->readFromAudioReader (reader,
  18159. info.startSample,
  18160. newEnd - newStart,
  18161. newStart,
  18162. true, true);
  18163. }
  18164. else
  18165. {
  18166. const int endSamps = (int) reader->lengthInSamples - newStart;
  18167. info.buffer->readFromAudioReader (reader,
  18168. info.startSample,
  18169. endSamps,
  18170. newStart,
  18171. true, true);
  18172. info.buffer->readFromAudioReader (reader,
  18173. info.startSample + endSamps,
  18174. newEnd,
  18175. 0,
  18176. true, true);
  18177. }
  18178. nextPlayPos = newEnd;
  18179. }
  18180. else
  18181. {
  18182. info.buffer->readFromAudioReader (reader,
  18183. info.startSample,
  18184. info.numSamples,
  18185. start,
  18186. true, true);
  18187. nextPlayPos += info.numSamples;
  18188. }
  18189. }
  18190. }
  18191. END_JUCE_NAMESPACE
  18192. /*** End of inlined file: juce_AudioFormatReaderSource.cpp ***/
  18193. /*** Start of inlined file: juce_AudioSourcePlayer.cpp ***/
  18194. BEGIN_JUCE_NAMESPACE
  18195. AudioSourcePlayer::AudioSourcePlayer()
  18196. : source (0),
  18197. sampleRate (0),
  18198. bufferSize (0),
  18199. tempBuffer (2, 8),
  18200. lastGain (1.0f),
  18201. gain (1.0f)
  18202. {
  18203. }
  18204. AudioSourcePlayer::~AudioSourcePlayer()
  18205. {
  18206. setSource (0);
  18207. }
  18208. void AudioSourcePlayer::setSource (AudioSource* newSource)
  18209. {
  18210. if (source != newSource)
  18211. {
  18212. AudioSource* const oldSource = source;
  18213. if (newSource != 0 && bufferSize > 0 && sampleRate > 0)
  18214. newSource->prepareToPlay (bufferSize, sampleRate);
  18215. {
  18216. const ScopedLock sl (readLock);
  18217. source = newSource;
  18218. }
  18219. if (oldSource != 0)
  18220. oldSource->releaseResources();
  18221. }
  18222. }
  18223. void AudioSourcePlayer::setGain (const float newGain) throw()
  18224. {
  18225. gain = newGain;
  18226. }
  18227. void AudioSourcePlayer::audioDeviceIOCallback (const float** inputChannelData,
  18228. int totalNumInputChannels,
  18229. float** outputChannelData,
  18230. int totalNumOutputChannels,
  18231. int numSamples)
  18232. {
  18233. // these should have been prepared by audioDeviceAboutToStart()...
  18234. jassert (sampleRate > 0 && bufferSize > 0);
  18235. const ScopedLock sl (readLock);
  18236. if (source != 0)
  18237. {
  18238. AudioSourceChannelInfo info;
  18239. int i, numActiveChans = 0, numInputs = 0, numOutputs = 0;
  18240. // messy stuff needed to compact the channels down into an array
  18241. // of non-zero pointers..
  18242. for (i = 0; i < totalNumInputChannels; ++i)
  18243. {
  18244. if (inputChannelData[i] != 0)
  18245. {
  18246. inputChans [numInputs++] = inputChannelData[i];
  18247. if (numInputs >= numElementsInArray (inputChans))
  18248. break;
  18249. }
  18250. }
  18251. for (i = 0; i < totalNumOutputChannels; ++i)
  18252. {
  18253. if (outputChannelData[i] != 0)
  18254. {
  18255. outputChans [numOutputs++] = outputChannelData[i];
  18256. if (numOutputs >= numElementsInArray (outputChans))
  18257. break;
  18258. }
  18259. }
  18260. if (numInputs > numOutputs)
  18261. {
  18262. // if there aren't enough output channels for the number of
  18263. // inputs, we need to create some temporary extra ones (can't
  18264. // use the input data in case it gets written to)
  18265. tempBuffer.setSize (numInputs - numOutputs, numSamples,
  18266. false, false, true);
  18267. for (i = 0; i < numOutputs; ++i)
  18268. {
  18269. channels[numActiveChans] = outputChans[i];
  18270. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  18271. ++numActiveChans;
  18272. }
  18273. for (i = numOutputs; i < numInputs; ++i)
  18274. {
  18275. channels[numActiveChans] = tempBuffer.getSampleData (i - numOutputs, 0);
  18276. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  18277. ++numActiveChans;
  18278. }
  18279. }
  18280. else
  18281. {
  18282. for (i = 0; i < numInputs; ++i)
  18283. {
  18284. channels[numActiveChans] = outputChans[i];
  18285. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  18286. ++numActiveChans;
  18287. }
  18288. for (i = numInputs; i < numOutputs; ++i)
  18289. {
  18290. channels[numActiveChans] = outputChans[i];
  18291. zeromem (channels[numActiveChans], sizeof (float) * numSamples);
  18292. ++numActiveChans;
  18293. }
  18294. }
  18295. AudioSampleBuffer buffer (channels, numActiveChans, numSamples);
  18296. info.buffer = &buffer;
  18297. info.startSample = 0;
  18298. info.numSamples = numSamples;
  18299. source->getNextAudioBlock (info);
  18300. for (i = info.buffer->getNumChannels(); --i >= 0;)
  18301. info.buffer->applyGainRamp (i, info.startSample, info.numSamples, lastGain, gain);
  18302. lastGain = gain;
  18303. }
  18304. else
  18305. {
  18306. for (int i = 0; i < totalNumOutputChannels; ++i)
  18307. if (outputChannelData[i] != 0)
  18308. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  18309. }
  18310. }
  18311. void AudioSourcePlayer::audioDeviceAboutToStart (AudioIODevice* device)
  18312. {
  18313. sampleRate = device->getCurrentSampleRate();
  18314. bufferSize = device->getCurrentBufferSizeSamples();
  18315. zeromem (channels, sizeof (channels));
  18316. if (source != 0)
  18317. source->prepareToPlay (bufferSize, sampleRate);
  18318. }
  18319. void AudioSourcePlayer::audioDeviceStopped()
  18320. {
  18321. if (source != 0)
  18322. source->releaseResources();
  18323. sampleRate = 0.0;
  18324. bufferSize = 0;
  18325. tempBuffer.setSize (2, 8);
  18326. }
  18327. END_JUCE_NAMESPACE
  18328. /*** End of inlined file: juce_AudioSourcePlayer.cpp ***/
  18329. /*** Start of inlined file: juce_AudioTransportSource.cpp ***/
  18330. BEGIN_JUCE_NAMESPACE
  18331. AudioTransportSource::AudioTransportSource()
  18332. : source (0),
  18333. resamplerSource (0),
  18334. bufferingSource (0),
  18335. positionableSource (0),
  18336. masterSource (0),
  18337. gain (1.0f),
  18338. lastGain (1.0f),
  18339. playing (false),
  18340. stopped (true),
  18341. sampleRate (44100.0),
  18342. sourceSampleRate (0.0),
  18343. blockSize (128),
  18344. readAheadBufferSize (0),
  18345. isPrepared (false),
  18346. inputStreamEOF (false)
  18347. {
  18348. }
  18349. AudioTransportSource::~AudioTransportSource()
  18350. {
  18351. setSource (0);
  18352. releaseResources();
  18353. }
  18354. void AudioTransportSource::setSource (PositionableAudioSource* const newSource,
  18355. int readAheadBufferSize_,
  18356. double sourceSampleRateToCorrectFor)
  18357. {
  18358. if (source == newSource)
  18359. {
  18360. if (source == 0)
  18361. return;
  18362. setSource (0, 0, 0); // deselect and reselect to avoid releasing resources wrongly
  18363. }
  18364. readAheadBufferSize = readAheadBufferSize_;
  18365. sourceSampleRate = sourceSampleRateToCorrectFor;
  18366. ResamplingAudioSource* newResamplerSource = 0;
  18367. BufferingAudioSource* newBufferingSource = 0;
  18368. PositionableAudioSource* newPositionableSource = 0;
  18369. AudioSource* newMasterSource = 0;
  18370. ScopedPointer <ResamplingAudioSource> oldResamplerSource (resamplerSource);
  18371. ScopedPointer <BufferingAudioSource> oldBufferingSource (bufferingSource);
  18372. AudioSource* oldMasterSource = masterSource;
  18373. if (newSource != 0)
  18374. {
  18375. newPositionableSource = newSource;
  18376. if (readAheadBufferSize_ > 0)
  18377. newPositionableSource = newBufferingSource
  18378. = new BufferingAudioSource (newPositionableSource, false, readAheadBufferSize_);
  18379. newPositionableSource->setNextReadPosition (0);
  18380. if (sourceSampleRateToCorrectFor != 0)
  18381. newMasterSource = newResamplerSource
  18382. = new ResamplingAudioSource (newPositionableSource, false);
  18383. else
  18384. newMasterSource = newPositionableSource;
  18385. if (isPrepared)
  18386. {
  18387. if (newResamplerSource != 0 && sourceSampleRate > 0 && sampleRate > 0)
  18388. newResamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  18389. newMasterSource->prepareToPlay (blockSize, sampleRate);
  18390. }
  18391. }
  18392. {
  18393. const ScopedLock sl (callbackLock);
  18394. source = newSource;
  18395. resamplerSource = newResamplerSource;
  18396. bufferingSource = newBufferingSource;
  18397. masterSource = newMasterSource;
  18398. positionableSource = newPositionableSource;
  18399. playing = false;
  18400. }
  18401. if (oldMasterSource != 0)
  18402. oldMasterSource->releaseResources();
  18403. }
  18404. void AudioTransportSource::start()
  18405. {
  18406. if ((! playing) && masterSource != 0)
  18407. {
  18408. {
  18409. const ScopedLock sl (callbackLock);
  18410. playing = true;
  18411. stopped = false;
  18412. inputStreamEOF = false;
  18413. }
  18414. sendChangeMessage (this);
  18415. }
  18416. }
  18417. void AudioTransportSource::stop()
  18418. {
  18419. if (playing)
  18420. {
  18421. {
  18422. const ScopedLock sl (callbackLock);
  18423. playing = false;
  18424. }
  18425. int n = 500;
  18426. while (--n >= 0 && ! stopped)
  18427. Thread::sleep (2);
  18428. sendChangeMessage (this);
  18429. }
  18430. }
  18431. void AudioTransportSource::setPosition (double newPosition)
  18432. {
  18433. if (sampleRate > 0.0)
  18434. setNextReadPosition (roundToInt (newPosition * sampleRate));
  18435. }
  18436. double AudioTransportSource::getCurrentPosition() const
  18437. {
  18438. if (sampleRate > 0.0)
  18439. return getNextReadPosition() / sampleRate;
  18440. else
  18441. return 0.0;
  18442. }
  18443. void AudioTransportSource::setNextReadPosition (int newPosition)
  18444. {
  18445. if (positionableSource != 0)
  18446. {
  18447. if (sampleRate > 0 && sourceSampleRate > 0)
  18448. newPosition = roundToInt (newPosition * sourceSampleRate / sampleRate);
  18449. positionableSource->setNextReadPosition (newPosition);
  18450. }
  18451. }
  18452. int AudioTransportSource::getNextReadPosition() const
  18453. {
  18454. if (positionableSource != 0)
  18455. {
  18456. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  18457. return roundToInt (positionableSource->getNextReadPosition() * ratio);
  18458. }
  18459. return 0;
  18460. }
  18461. int AudioTransportSource::getTotalLength() const
  18462. {
  18463. const ScopedLock sl (callbackLock);
  18464. if (positionableSource != 0)
  18465. {
  18466. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  18467. return roundToInt (positionableSource->getTotalLength() * ratio);
  18468. }
  18469. return 0;
  18470. }
  18471. bool AudioTransportSource::isLooping() const
  18472. {
  18473. const ScopedLock sl (callbackLock);
  18474. return positionableSource != 0
  18475. && positionableSource->isLooping();
  18476. }
  18477. void AudioTransportSource::setGain (const float newGain) throw()
  18478. {
  18479. gain = newGain;
  18480. }
  18481. void AudioTransportSource::prepareToPlay (int samplesPerBlockExpected,
  18482. double sampleRate_)
  18483. {
  18484. const ScopedLock sl (callbackLock);
  18485. sampleRate = sampleRate_;
  18486. blockSize = samplesPerBlockExpected;
  18487. if (masterSource != 0)
  18488. masterSource->prepareToPlay (samplesPerBlockExpected, sampleRate);
  18489. if (resamplerSource != 0 && sourceSampleRate != 0)
  18490. resamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  18491. isPrepared = true;
  18492. }
  18493. void AudioTransportSource::releaseResources()
  18494. {
  18495. const ScopedLock sl (callbackLock);
  18496. if (masterSource != 0)
  18497. masterSource->releaseResources();
  18498. isPrepared = false;
  18499. }
  18500. void AudioTransportSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  18501. {
  18502. const ScopedLock sl (callbackLock);
  18503. inputStreamEOF = false;
  18504. if (masterSource != 0 && ! stopped)
  18505. {
  18506. masterSource->getNextAudioBlock (info);
  18507. if (! playing)
  18508. {
  18509. // just stopped playing, so fade out the last block..
  18510. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  18511. info.buffer->applyGainRamp (i, info.startSample, jmin (256, info.numSamples), 1.0f, 0.0f);
  18512. if (info.numSamples > 256)
  18513. info.buffer->clear (info.startSample + 256, info.numSamples - 256);
  18514. }
  18515. if (positionableSource->getNextReadPosition() > positionableSource->getTotalLength() + 1
  18516. && ! positionableSource->isLooping())
  18517. {
  18518. playing = false;
  18519. inputStreamEOF = true;
  18520. sendChangeMessage (this);
  18521. }
  18522. stopped = ! playing;
  18523. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  18524. {
  18525. info.buffer->applyGainRamp (i, info.startSample, info.numSamples,
  18526. lastGain, gain);
  18527. }
  18528. }
  18529. else
  18530. {
  18531. info.clearActiveBufferRegion();
  18532. stopped = true;
  18533. }
  18534. lastGain = gain;
  18535. }
  18536. END_JUCE_NAMESPACE
  18537. /*** End of inlined file: juce_AudioTransportSource.cpp ***/
  18538. /*** Start of inlined file: juce_BufferingAudioSource.cpp ***/
  18539. BEGIN_JUCE_NAMESPACE
  18540. class SharedBufferingAudioSourceThread : public DeletedAtShutdown,
  18541. public Thread,
  18542. private Timer
  18543. {
  18544. public:
  18545. SharedBufferingAudioSourceThread()
  18546. : Thread ("Audio Buffer")
  18547. {
  18548. }
  18549. ~SharedBufferingAudioSourceThread()
  18550. {
  18551. stopThread (10000);
  18552. clearSingletonInstance();
  18553. }
  18554. juce_DeclareSingleton (SharedBufferingAudioSourceThread, false)
  18555. void addSource (BufferingAudioSource* source)
  18556. {
  18557. const ScopedLock sl (lock);
  18558. if (! sources.contains (source))
  18559. {
  18560. sources.add (source);
  18561. startThread();
  18562. stopTimer();
  18563. }
  18564. notify();
  18565. }
  18566. void removeSource (BufferingAudioSource* source)
  18567. {
  18568. const ScopedLock sl (lock);
  18569. sources.removeValue (source);
  18570. if (sources.size() == 0)
  18571. startTimer (5000);
  18572. }
  18573. private:
  18574. Array <BufferingAudioSource*> sources;
  18575. CriticalSection lock;
  18576. void run()
  18577. {
  18578. while (! threadShouldExit())
  18579. {
  18580. bool busy = false;
  18581. for (int i = sources.size(); --i >= 0;)
  18582. {
  18583. if (threadShouldExit())
  18584. return;
  18585. const ScopedLock sl (lock);
  18586. BufferingAudioSource* const b = sources[i];
  18587. if (b != 0 && b->readNextBufferChunk())
  18588. busy = true;
  18589. }
  18590. if (! busy)
  18591. wait (500);
  18592. }
  18593. }
  18594. void timerCallback()
  18595. {
  18596. stopTimer();
  18597. if (sources.size() == 0)
  18598. deleteInstance();
  18599. }
  18600. SharedBufferingAudioSourceThread (const SharedBufferingAudioSourceThread&);
  18601. SharedBufferingAudioSourceThread& operator= (const SharedBufferingAudioSourceThread&);
  18602. };
  18603. juce_ImplementSingleton (SharedBufferingAudioSourceThread)
  18604. BufferingAudioSource::BufferingAudioSource (PositionableAudioSource* source_,
  18605. const bool deleteSourceWhenDeleted_,
  18606. int numberOfSamplesToBuffer_)
  18607. : source (source_),
  18608. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  18609. numberOfSamplesToBuffer (jmax (1024, numberOfSamplesToBuffer_)),
  18610. buffer (2, 0),
  18611. bufferValidStart (0),
  18612. bufferValidEnd (0),
  18613. nextPlayPos (0),
  18614. wasSourceLooping (false)
  18615. {
  18616. jassert (source_ != 0);
  18617. jassert (numberOfSamplesToBuffer_ > 1024); // not much point using this class if you're
  18618. // not using a larger buffer..
  18619. }
  18620. BufferingAudioSource::~BufferingAudioSource()
  18621. {
  18622. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  18623. if (thread != 0)
  18624. thread->removeSource (this);
  18625. if (deleteSourceWhenDeleted)
  18626. delete source;
  18627. }
  18628. void BufferingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate_)
  18629. {
  18630. source->prepareToPlay (samplesPerBlockExpected, sampleRate_);
  18631. sampleRate = sampleRate_;
  18632. buffer.setSize (2, jmax (samplesPerBlockExpected * 2, numberOfSamplesToBuffer));
  18633. buffer.clear();
  18634. bufferValidStart = 0;
  18635. bufferValidEnd = 0;
  18636. SharedBufferingAudioSourceThread::getInstance()->addSource (this);
  18637. while (bufferValidEnd - bufferValidStart < jmin (((int) sampleRate_) / 4,
  18638. buffer.getNumSamples() / 2))
  18639. {
  18640. SharedBufferingAudioSourceThread::getInstance()->notify();
  18641. Thread::sleep (5);
  18642. }
  18643. }
  18644. void BufferingAudioSource::releaseResources()
  18645. {
  18646. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  18647. if (thread != 0)
  18648. thread->removeSource (this);
  18649. buffer.setSize (2, 0);
  18650. source->releaseResources();
  18651. }
  18652. void BufferingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  18653. {
  18654. const ScopedLock sl (bufferStartPosLock);
  18655. const int validStart = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos) - nextPlayPos;
  18656. const int validEnd = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos + info.numSamples) - nextPlayPos;
  18657. if (validStart == validEnd)
  18658. {
  18659. // total cache miss
  18660. info.clearActiveBufferRegion();
  18661. }
  18662. else
  18663. {
  18664. if (validStart > 0)
  18665. info.buffer->clear (info.startSample, validStart); // partial cache miss at start
  18666. if (validEnd < info.numSamples)
  18667. info.buffer->clear (info.startSample + validEnd,
  18668. info.numSamples - validEnd); // partial cache miss at end
  18669. if (validStart < validEnd)
  18670. {
  18671. for (int chan = jmin (2, info.buffer->getNumChannels()); --chan >= 0;)
  18672. {
  18673. const int startBufferIndex = (validStart + nextPlayPos) % buffer.getNumSamples();
  18674. const int endBufferIndex = (validEnd + nextPlayPos) % buffer.getNumSamples();
  18675. if (startBufferIndex < endBufferIndex)
  18676. {
  18677. info.buffer->copyFrom (chan, info.startSample + validStart,
  18678. buffer,
  18679. chan, startBufferIndex,
  18680. validEnd - validStart);
  18681. }
  18682. else
  18683. {
  18684. const int initialSize = buffer.getNumSamples() - startBufferIndex;
  18685. info.buffer->copyFrom (chan, info.startSample + validStart,
  18686. buffer,
  18687. chan, startBufferIndex,
  18688. initialSize);
  18689. info.buffer->copyFrom (chan, info.startSample + validStart + initialSize,
  18690. buffer,
  18691. chan, 0,
  18692. (validEnd - validStart) - initialSize);
  18693. }
  18694. }
  18695. }
  18696. nextPlayPos += info.numSamples;
  18697. if (source->isLooping() && nextPlayPos > 0)
  18698. nextPlayPos %= source->getTotalLength();
  18699. }
  18700. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  18701. if (thread != 0)
  18702. thread->notify();
  18703. }
  18704. int BufferingAudioSource::getNextReadPosition() const
  18705. {
  18706. return (source->isLooping() && nextPlayPos > 0)
  18707. ? nextPlayPos % source->getTotalLength()
  18708. : nextPlayPos;
  18709. }
  18710. void BufferingAudioSource::setNextReadPosition (int newPosition)
  18711. {
  18712. const ScopedLock sl (bufferStartPosLock);
  18713. nextPlayPos = newPosition;
  18714. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  18715. if (thread != 0)
  18716. thread->notify();
  18717. }
  18718. bool BufferingAudioSource::readNextBufferChunk()
  18719. {
  18720. int newBVS, newBVE, sectionToReadStart, sectionToReadEnd;
  18721. {
  18722. const ScopedLock sl (bufferStartPosLock);
  18723. if (wasSourceLooping != isLooping())
  18724. {
  18725. wasSourceLooping = isLooping();
  18726. bufferValidStart = 0;
  18727. bufferValidEnd = 0;
  18728. }
  18729. newBVS = jmax (0, nextPlayPos);
  18730. newBVE = newBVS + buffer.getNumSamples() - 4;
  18731. sectionToReadStart = 0;
  18732. sectionToReadEnd = 0;
  18733. const int maxChunkSize = 2048;
  18734. if (newBVS < bufferValidStart || newBVS >= bufferValidEnd)
  18735. {
  18736. newBVE = jmin (newBVE, newBVS + maxChunkSize);
  18737. sectionToReadStart = newBVS;
  18738. sectionToReadEnd = newBVE;
  18739. bufferValidStart = 0;
  18740. bufferValidEnd = 0;
  18741. }
  18742. else if (abs (newBVS - bufferValidStart) > 512
  18743. || abs (newBVE - bufferValidEnd) > 512)
  18744. {
  18745. newBVE = jmin (newBVE, bufferValidEnd + maxChunkSize);
  18746. sectionToReadStart = bufferValidEnd;
  18747. sectionToReadEnd = newBVE;
  18748. bufferValidStart = newBVS;
  18749. bufferValidEnd = jmin (bufferValidEnd, newBVE);
  18750. }
  18751. }
  18752. if (sectionToReadStart != sectionToReadEnd)
  18753. {
  18754. const int bufferIndexStart = sectionToReadStart % buffer.getNumSamples();
  18755. const int bufferIndexEnd = sectionToReadEnd % buffer.getNumSamples();
  18756. if (bufferIndexStart < bufferIndexEnd)
  18757. {
  18758. readBufferSection (sectionToReadStart,
  18759. sectionToReadEnd - sectionToReadStart,
  18760. bufferIndexStart);
  18761. }
  18762. else
  18763. {
  18764. const int initialSize = buffer.getNumSamples() - bufferIndexStart;
  18765. readBufferSection (sectionToReadStart,
  18766. initialSize,
  18767. bufferIndexStart);
  18768. readBufferSection (sectionToReadStart + initialSize,
  18769. (sectionToReadEnd - sectionToReadStart) - initialSize,
  18770. 0);
  18771. }
  18772. const ScopedLock sl2 (bufferStartPosLock);
  18773. bufferValidStart = newBVS;
  18774. bufferValidEnd = newBVE;
  18775. return true;
  18776. }
  18777. else
  18778. {
  18779. return false;
  18780. }
  18781. }
  18782. void BufferingAudioSource::readBufferSection (int start, int length, int bufferOffset)
  18783. {
  18784. if (source->getNextReadPosition() != start)
  18785. source->setNextReadPosition (start);
  18786. AudioSourceChannelInfo info;
  18787. info.buffer = &buffer;
  18788. info.startSample = bufferOffset;
  18789. info.numSamples = length;
  18790. source->getNextAudioBlock (info);
  18791. }
  18792. END_JUCE_NAMESPACE
  18793. /*** End of inlined file: juce_BufferingAudioSource.cpp ***/
  18794. /*** Start of inlined file: juce_ChannelRemappingAudioSource.cpp ***/
  18795. BEGIN_JUCE_NAMESPACE
  18796. ChannelRemappingAudioSource::ChannelRemappingAudioSource (AudioSource* const source_,
  18797. const bool deleteSourceWhenDeleted_)
  18798. : requiredNumberOfChannels (2),
  18799. source (source_),
  18800. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  18801. buffer (2, 16)
  18802. {
  18803. remappedInfo.buffer = &buffer;
  18804. remappedInfo.startSample = 0;
  18805. }
  18806. ChannelRemappingAudioSource::~ChannelRemappingAudioSource()
  18807. {
  18808. if (deleteSourceWhenDeleted)
  18809. delete source;
  18810. }
  18811. void ChannelRemappingAudioSource::setNumberOfChannelsToProduce (const int requiredNumberOfChannels_) throw()
  18812. {
  18813. const ScopedLock sl (lock);
  18814. requiredNumberOfChannels = requiredNumberOfChannels_;
  18815. }
  18816. void ChannelRemappingAudioSource::clearAllMappings() throw()
  18817. {
  18818. const ScopedLock sl (lock);
  18819. remappedInputs.clear();
  18820. remappedOutputs.clear();
  18821. }
  18822. void ChannelRemappingAudioSource::setInputChannelMapping (const int destIndex, const int sourceIndex) throw()
  18823. {
  18824. const ScopedLock sl (lock);
  18825. while (remappedInputs.size() < destIndex)
  18826. remappedInputs.add (-1);
  18827. remappedInputs.set (destIndex, sourceIndex);
  18828. }
  18829. void ChannelRemappingAudioSource::setOutputChannelMapping (const int sourceIndex, const int destIndex) throw()
  18830. {
  18831. const ScopedLock sl (lock);
  18832. while (remappedOutputs.size() < sourceIndex)
  18833. remappedOutputs.add (-1);
  18834. remappedOutputs.set (sourceIndex, destIndex);
  18835. }
  18836. int ChannelRemappingAudioSource::getRemappedInputChannel (const int inputChannelIndex) const throw()
  18837. {
  18838. const ScopedLock sl (lock);
  18839. if (inputChannelIndex >= 0 && inputChannelIndex < remappedInputs.size())
  18840. return remappedInputs.getUnchecked (inputChannelIndex);
  18841. return -1;
  18842. }
  18843. int ChannelRemappingAudioSource::getRemappedOutputChannel (const int outputChannelIndex) const throw()
  18844. {
  18845. const ScopedLock sl (lock);
  18846. if (outputChannelIndex >= 0 && outputChannelIndex < remappedOutputs.size())
  18847. return remappedOutputs .getUnchecked (outputChannelIndex);
  18848. return -1;
  18849. }
  18850. void ChannelRemappingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  18851. {
  18852. source->prepareToPlay (samplesPerBlockExpected, sampleRate);
  18853. }
  18854. void ChannelRemappingAudioSource::releaseResources()
  18855. {
  18856. source->releaseResources();
  18857. }
  18858. void ChannelRemappingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  18859. {
  18860. const ScopedLock sl (lock);
  18861. buffer.setSize (requiredNumberOfChannels, bufferToFill.numSamples, false, false, true);
  18862. const int numChans = bufferToFill.buffer->getNumChannels();
  18863. int i;
  18864. for (i = 0; i < buffer.getNumChannels(); ++i)
  18865. {
  18866. const int remappedChan = getRemappedInputChannel (i);
  18867. if (remappedChan >= 0 && remappedChan < numChans)
  18868. {
  18869. buffer.copyFrom (i, 0, *bufferToFill.buffer,
  18870. remappedChan,
  18871. bufferToFill.startSample,
  18872. bufferToFill.numSamples);
  18873. }
  18874. else
  18875. {
  18876. buffer.clear (i, 0, bufferToFill.numSamples);
  18877. }
  18878. }
  18879. remappedInfo.numSamples = bufferToFill.numSamples;
  18880. source->getNextAudioBlock (remappedInfo);
  18881. bufferToFill.clearActiveBufferRegion();
  18882. for (i = 0; i < requiredNumberOfChannels; ++i)
  18883. {
  18884. const int remappedChan = getRemappedOutputChannel (i);
  18885. if (remappedChan >= 0 && remappedChan < numChans)
  18886. {
  18887. bufferToFill.buffer->addFrom (remappedChan, bufferToFill.startSample,
  18888. buffer, i, 0, bufferToFill.numSamples);
  18889. }
  18890. }
  18891. }
  18892. XmlElement* ChannelRemappingAudioSource::createXml() const throw()
  18893. {
  18894. XmlElement* e = new XmlElement ("MAPPINGS");
  18895. String ins, outs;
  18896. int i;
  18897. const ScopedLock sl (lock);
  18898. for (i = 0; i < remappedInputs.size(); ++i)
  18899. ins << remappedInputs.getUnchecked(i) << ' ';
  18900. for (i = 0; i < remappedOutputs.size(); ++i)
  18901. outs << remappedOutputs.getUnchecked(i) << ' ';
  18902. e->setAttribute ("inputs", ins.trimEnd());
  18903. e->setAttribute ("outputs", outs.trimEnd());
  18904. return e;
  18905. }
  18906. void ChannelRemappingAudioSource::restoreFromXml (const XmlElement& e) throw()
  18907. {
  18908. if (e.hasTagName ("MAPPINGS"))
  18909. {
  18910. const ScopedLock sl (lock);
  18911. clearAllMappings();
  18912. StringArray ins, outs;
  18913. ins.addTokens (e.getStringAttribute ("inputs"), false);
  18914. outs.addTokens (e.getStringAttribute ("outputs"), false);
  18915. int i;
  18916. for (i = 0; i < ins.size(); ++i)
  18917. remappedInputs.add (ins[i].getIntValue());
  18918. for (i = 0; i < outs.size(); ++i)
  18919. remappedOutputs.add (outs[i].getIntValue());
  18920. }
  18921. }
  18922. END_JUCE_NAMESPACE
  18923. /*** End of inlined file: juce_ChannelRemappingAudioSource.cpp ***/
  18924. /*** Start of inlined file: juce_IIRFilterAudioSource.cpp ***/
  18925. BEGIN_JUCE_NAMESPACE
  18926. IIRFilterAudioSource::IIRFilterAudioSource (AudioSource* const inputSource,
  18927. const bool deleteInputWhenDeleted_)
  18928. : input (inputSource),
  18929. deleteInputWhenDeleted (deleteInputWhenDeleted_)
  18930. {
  18931. jassert (inputSource != 0);
  18932. for (int i = 2; --i >= 0;)
  18933. iirFilters.add (new IIRFilter());
  18934. }
  18935. IIRFilterAudioSource::~IIRFilterAudioSource()
  18936. {
  18937. if (deleteInputWhenDeleted)
  18938. delete input;
  18939. }
  18940. void IIRFilterAudioSource::setFilterParameters (const IIRFilter& newSettings)
  18941. {
  18942. for (int i = iirFilters.size(); --i >= 0;)
  18943. iirFilters.getUnchecked(i)->copyCoefficientsFrom (newSettings);
  18944. }
  18945. void IIRFilterAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  18946. {
  18947. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  18948. for (int i = iirFilters.size(); --i >= 0;)
  18949. iirFilters.getUnchecked(i)->reset();
  18950. }
  18951. void IIRFilterAudioSource::releaseResources()
  18952. {
  18953. input->releaseResources();
  18954. }
  18955. void IIRFilterAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  18956. {
  18957. input->getNextAudioBlock (bufferToFill);
  18958. const int numChannels = bufferToFill.buffer->getNumChannels();
  18959. while (numChannels > iirFilters.size())
  18960. iirFilters.add (new IIRFilter (*iirFilters.getUnchecked (0)));
  18961. for (int i = 0; i < numChannels; ++i)
  18962. iirFilters.getUnchecked(i)
  18963. ->processSamples (bufferToFill.buffer->getSampleData (i, bufferToFill.startSample),
  18964. bufferToFill.numSamples);
  18965. }
  18966. END_JUCE_NAMESPACE
  18967. /*** End of inlined file: juce_IIRFilterAudioSource.cpp ***/
  18968. /*** Start of inlined file: juce_MixerAudioSource.cpp ***/
  18969. BEGIN_JUCE_NAMESPACE
  18970. MixerAudioSource::MixerAudioSource()
  18971. : tempBuffer (2, 0),
  18972. currentSampleRate (0.0),
  18973. bufferSizeExpected (0)
  18974. {
  18975. }
  18976. MixerAudioSource::~MixerAudioSource()
  18977. {
  18978. removeAllInputs();
  18979. }
  18980. void MixerAudioSource::addInputSource (AudioSource* input, const bool deleteWhenRemoved)
  18981. {
  18982. if (input != 0 && ! inputs.contains (input))
  18983. {
  18984. double localRate;
  18985. int localBufferSize;
  18986. {
  18987. const ScopedLock sl (lock);
  18988. localRate = currentSampleRate;
  18989. localBufferSize = bufferSizeExpected;
  18990. }
  18991. if (localRate != 0.0)
  18992. input->prepareToPlay (localBufferSize, localRate);
  18993. const ScopedLock sl (lock);
  18994. inputsToDelete.setBit (inputs.size(), deleteWhenRemoved);
  18995. inputs.add (input);
  18996. }
  18997. }
  18998. void MixerAudioSource::removeInputSource (AudioSource* input, const bool deleteInput)
  18999. {
  19000. if (input != 0)
  19001. {
  19002. int index;
  19003. {
  19004. const ScopedLock sl (lock);
  19005. index = inputs.indexOf (input);
  19006. if (index >= 0)
  19007. {
  19008. inputsToDelete.shiftBits (index, 1);
  19009. inputs.remove (index);
  19010. }
  19011. }
  19012. if (index >= 0)
  19013. {
  19014. input->releaseResources();
  19015. if (deleteInput)
  19016. delete input;
  19017. }
  19018. }
  19019. }
  19020. void MixerAudioSource::removeAllInputs()
  19021. {
  19022. OwnedArray<AudioSource> toDelete;
  19023. {
  19024. const ScopedLock sl (lock);
  19025. for (int i = inputs.size(); --i >= 0;)
  19026. if (inputsToDelete[i])
  19027. toDelete.add (inputs.getUnchecked(i));
  19028. }
  19029. }
  19030. void MixerAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19031. {
  19032. tempBuffer.setSize (2, samplesPerBlockExpected);
  19033. const ScopedLock sl (lock);
  19034. currentSampleRate = sampleRate;
  19035. bufferSizeExpected = samplesPerBlockExpected;
  19036. for (int i = inputs.size(); --i >= 0;)
  19037. inputs.getUnchecked(i)->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19038. }
  19039. void MixerAudioSource::releaseResources()
  19040. {
  19041. const ScopedLock sl (lock);
  19042. for (int i = inputs.size(); --i >= 0;)
  19043. inputs.getUnchecked(i)->releaseResources();
  19044. tempBuffer.setSize (2, 0);
  19045. currentSampleRate = 0;
  19046. bufferSizeExpected = 0;
  19047. }
  19048. void MixerAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19049. {
  19050. const ScopedLock sl (lock);
  19051. if (inputs.size() > 0)
  19052. {
  19053. inputs.getUnchecked(0)->getNextAudioBlock (info);
  19054. if (inputs.size() > 1)
  19055. {
  19056. tempBuffer.setSize (jmax (1, info.buffer->getNumChannels()),
  19057. info.buffer->getNumSamples());
  19058. AudioSourceChannelInfo info2;
  19059. info2.buffer = &tempBuffer;
  19060. info2.numSamples = info.numSamples;
  19061. info2.startSample = 0;
  19062. for (int i = 1; i < inputs.size(); ++i)
  19063. {
  19064. inputs.getUnchecked(i)->getNextAudioBlock (info2);
  19065. for (int chan = 0; chan < info.buffer->getNumChannels(); ++chan)
  19066. info.buffer->addFrom (chan, info.startSample, tempBuffer, chan, 0, info.numSamples);
  19067. }
  19068. }
  19069. }
  19070. else
  19071. {
  19072. info.clearActiveBufferRegion();
  19073. }
  19074. }
  19075. END_JUCE_NAMESPACE
  19076. /*** End of inlined file: juce_MixerAudioSource.cpp ***/
  19077. /*** Start of inlined file: juce_ResamplingAudioSource.cpp ***/
  19078. BEGIN_JUCE_NAMESPACE
  19079. ResamplingAudioSource::ResamplingAudioSource (AudioSource* const inputSource,
  19080. const bool deleteInputWhenDeleted_)
  19081. : input (inputSource),
  19082. deleteInputWhenDeleted (deleteInputWhenDeleted_),
  19083. ratio (1.0),
  19084. lastRatio (1.0),
  19085. buffer (2, 0),
  19086. sampsInBuffer (0)
  19087. {
  19088. jassert (input != 0);
  19089. }
  19090. ResamplingAudioSource::~ResamplingAudioSource()
  19091. {
  19092. if (deleteInputWhenDeleted)
  19093. delete input;
  19094. }
  19095. void ResamplingAudioSource::setResamplingRatio (const double samplesInPerOutputSample)
  19096. {
  19097. jassert (samplesInPerOutputSample > 0);
  19098. const ScopedLock sl (ratioLock);
  19099. ratio = jmax (0.0, samplesInPerOutputSample);
  19100. }
  19101. void ResamplingAudioSource::prepareToPlay (int samplesPerBlockExpected,
  19102. double sampleRate)
  19103. {
  19104. const ScopedLock sl (ratioLock);
  19105. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19106. buffer.setSize (2, roundToInt (samplesPerBlockExpected * ratio) + 32);
  19107. buffer.clear();
  19108. sampsInBuffer = 0;
  19109. bufferPos = 0;
  19110. subSampleOffset = 0.0;
  19111. createLowPass (ratio);
  19112. resetFilters();
  19113. }
  19114. void ResamplingAudioSource::releaseResources()
  19115. {
  19116. input->releaseResources();
  19117. buffer.setSize (2, 0);
  19118. }
  19119. void ResamplingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19120. {
  19121. const ScopedLock sl (ratioLock);
  19122. if (lastRatio != ratio)
  19123. {
  19124. createLowPass (ratio);
  19125. lastRatio = ratio;
  19126. }
  19127. const int sampsNeeded = roundToInt (info.numSamples * ratio) + 2;
  19128. int bufferSize = buffer.getNumSamples();
  19129. if (bufferSize < sampsNeeded + 8)
  19130. {
  19131. bufferPos %= bufferSize;
  19132. bufferSize = sampsNeeded + 32;
  19133. buffer.setSize (buffer.getNumChannels(), bufferSize, true, true);
  19134. }
  19135. bufferPos %= bufferSize;
  19136. int endOfBufferPos = bufferPos + sampsInBuffer;
  19137. while (sampsNeeded > sampsInBuffer)
  19138. {
  19139. endOfBufferPos %= bufferSize;
  19140. int numToDo = jmin (sampsNeeded - sampsInBuffer,
  19141. bufferSize - endOfBufferPos);
  19142. AudioSourceChannelInfo readInfo;
  19143. readInfo.buffer = &buffer;
  19144. readInfo.numSamples = numToDo;
  19145. readInfo.startSample = endOfBufferPos;
  19146. input->getNextAudioBlock (readInfo);
  19147. if (ratio > 1.0001)
  19148. {
  19149. // for down-sampling, pre-apply the filter..
  19150. for (int i = jmin (2, info.buffer->getNumChannels()); --i >= 0;)
  19151. applyFilter (buffer.getSampleData (i, endOfBufferPos), numToDo, filterStates[i]);
  19152. }
  19153. sampsInBuffer += numToDo;
  19154. endOfBufferPos += numToDo;
  19155. }
  19156. float* dl = info.buffer->getSampleData (0, info.startSample);
  19157. float* dr = (info.buffer->getNumChannels() > 1) ? info.buffer->getSampleData (1, info.startSample) : 0;
  19158. const float* const bl = buffer.getSampleData (0, 0);
  19159. const float* const br = buffer.getSampleData (1, 0);
  19160. int nextPos = (bufferPos + 1) % bufferSize;
  19161. for (int m = info.numSamples; --m >= 0;)
  19162. {
  19163. const float alpha = (float) subSampleOffset;
  19164. const float invAlpha = 1.0f - alpha;
  19165. *dl++ = bl [bufferPos] * invAlpha + bl [nextPos] * alpha;
  19166. if (dr != 0)
  19167. *dr++ = br [bufferPos] * invAlpha + br [nextPos] * alpha;
  19168. subSampleOffset += ratio;
  19169. jassert (sampsInBuffer > 0);
  19170. while (subSampleOffset >= 1.0)
  19171. {
  19172. if (++bufferPos >= bufferSize)
  19173. bufferPos = 0;
  19174. --sampsInBuffer;
  19175. nextPos = (bufferPos + 1) % bufferSize;
  19176. subSampleOffset -= 1.0;
  19177. }
  19178. }
  19179. if (ratio < 0.9999)
  19180. {
  19181. // for up-sampling, apply the filter after transposing..
  19182. for (int i = jmin (2, info.buffer->getNumChannels()); --i >= 0;)
  19183. applyFilter (info.buffer->getSampleData (i, info.startSample), info.numSamples, filterStates[i]);
  19184. }
  19185. else if (ratio <= 1.0001)
  19186. {
  19187. // if the filter's not currently being applied, keep it stoked with the last couple of samples to avoid discontinuities
  19188. for (int i = jmin (2, info.buffer->getNumChannels()); --i >= 0;)
  19189. {
  19190. const float* const endOfBuffer = info.buffer->getSampleData (i, info.startSample + info.numSamples - 1);
  19191. FilterState& fs = filterStates[i];
  19192. if (info.numSamples > 1)
  19193. {
  19194. fs.y2 = fs.x2 = *(endOfBuffer - 1);
  19195. }
  19196. else
  19197. {
  19198. fs.y2 = fs.y1;
  19199. fs.x2 = fs.x1;
  19200. }
  19201. fs.y1 = fs.x1 = *endOfBuffer;
  19202. }
  19203. }
  19204. jassert (sampsInBuffer >= 0);
  19205. }
  19206. void ResamplingAudioSource::createLowPass (const double frequencyRatio)
  19207. {
  19208. const double proportionalRate = (frequencyRatio > 1.0) ? 0.5 / frequencyRatio
  19209. : 0.5 * frequencyRatio;
  19210. const double n = 1.0 / tan (double_Pi * jmax (0.001, proportionalRate));
  19211. const double nSquared = n * n;
  19212. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  19213. setFilterCoefficients (c1,
  19214. c1 * 2.0f,
  19215. c1,
  19216. 1.0,
  19217. c1 * 2.0 * (1.0 - nSquared),
  19218. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  19219. }
  19220. void ResamplingAudioSource::setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6)
  19221. {
  19222. const double a = 1.0 / c4;
  19223. c1 *= a;
  19224. c2 *= a;
  19225. c3 *= a;
  19226. c5 *= a;
  19227. c6 *= a;
  19228. coefficients[0] = c1;
  19229. coefficients[1] = c2;
  19230. coefficients[2] = c3;
  19231. coefficients[3] = c4;
  19232. coefficients[4] = c5;
  19233. coefficients[5] = c6;
  19234. }
  19235. void ResamplingAudioSource::resetFilters()
  19236. {
  19237. zeromem (filterStates, sizeof (filterStates));
  19238. }
  19239. void ResamplingAudioSource::applyFilter (float* samples, int num, FilterState& fs)
  19240. {
  19241. while (--num >= 0)
  19242. {
  19243. const double in = *samples;
  19244. double out = coefficients[0] * in
  19245. + coefficients[1] * fs.x1
  19246. + coefficients[2] * fs.x2
  19247. - coefficients[4] * fs.y1
  19248. - coefficients[5] * fs.y2;
  19249. #if JUCE_INTEL
  19250. if (! (out < -1.0e-8 || out > 1.0e-8))
  19251. out = 0;
  19252. #endif
  19253. fs.x2 = fs.x1;
  19254. fs.x1 = in;
  19255. fs.y2 = fs.y1;
  19256. fs.y1 = out;
  19257. *samples++ = (float) out;
  19258. }
  19259. }
  19260. END_JUCE_NAMESPACE
  19261. /*** End of inlined file: juce_ResamplingAudioSource.cpp ***/
  19262. /*** Start of inlined file: juce_ToneGeneratorAudioSource.cpp ***/
  19263. BEGIN_JUCE_NAMESPACE
  19264. ToneGeneratorAudioSource::ToneGeneratorAudioSource()
  19265. : frequency (1000.0),
  19266. sampleRate (44100.0),
  19267. currentPhase (0.0),
  19268. phasePerSample (0.0),
  19269. amplitude (0.5f)
  19270. {
  19271. }
  19272. ToneGeneratorAudioSource::~ToneGeneratorAudioSource()
  19273. {
  19274. }
  19275. void ToneGeneratorAudioSource::setAmplitude (const float newAmplitude)
  19276. {
  19277. amplitude = newAmplitude;
  19278. }
  19279. void ToneGeneratorAudioSource::setFrequency (const double newFrequencyHz)
  19280. {
  19281. frequency = newFrequencyHz;
  19282. phasePerSample = 0.0;
  19283. }
  19284. void ToneGeneratorAudioSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  19285. double sampleRate_)
  19286. {
  19287. currentPhase = 0.0;
  19288. phasePerSample = 0.0;
  19289. sampleRate = sampleRate_;
  19290. }
  19291. void ToneGeneratorAudioSource::releaseResources()
  19292. {
  19293. }
  19294. void ToneGeneratorAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19295. {
  19296. if (phasePerSample == 0.0)
  19297. phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  19298. for (int i = 0; i < info.numSamples; ++i)
  19299. {
  19300. const float sample = amplitude * (float) std::sin (currentPhase);
  19301. currentPhase += phasePerSample;
  19302. for (int j = info.buffer->getNumChannels(); --j >= 0;)
  19303. *info.buffer->getSampleData (j, info.startSample + i) = sample;
  19304. }
  19305. }
  19306. END_JUCE_NAMESPACE
  19307. /*** End of inlined file: juce_ToneGeneratorAudioSource.cpp ***/
  19308. /*** Start of inlined file: juce_AudioDeviceManager.cpp ***/
  19309. BEGIN_JUCE_NAMESPACE
  19310. AudioDeviceManager::AudioDeviceSetup::AudioDeviceSetup()
  19311. : sampleRate (0),
  19312. bufferSize (0),
  19313. useDefaultInputChannels (true),
  19314. useDefaultOutputChannels (true)
  19315. {
  19316. }
  19317. bool AudioDeviceManager::AudioDeviceSetup::operator== (const AudioDeviceManager::AudioDeviceSetup& other) const
  19318. {
  19319. return outputDeviceName == other.outputDeviceName
  19320. && inputDeviceName == other.inputDeviceName
  19321. && sampleRate == other.sampleRate
  19322. && bufferSize == other.bufferSize
  19323. && inputChannels == other.inputChannels
  19324. && useDefaultInputChannels == other.useDefaultInputChannels
  19325. && outputChannels == other.outputChannels
  19326. && useDefaultOutputChannels == other.useDefaultOutputChannels;
  19327. }
  19328. AudioDeviceManager::AudioDeviceManager()
  19329. : currentAudioDevice (0),
  19330. numInputChansNeeded (0),
  19331. numOutputChansNeeded (2),
  19332. listNeedsScanning (true),
  19333. useInputNames (false),
  19334. inputLevelMeasurementEnabledCount (0),
  19335. inputLevel (0),
  19336. tempBuffer (2, 2),
  19337. defaultMidiOutput (0),
  19338. cpuUsageMs (0),
  19339. timeToCpuScale (0)
  19340. {
  19341. callbackHandler.owner = this;
  19342. }
  19343. AudioDeviceManager::~AudioDeviceManager()
  19344. {
  19345. currentAudioDevice = 0;
  19346. defaultMidiOutput = 0;
  19347. }
  19348. void AudioDeviceManager::createDeviceTypesIfNeeded()
  19349. {
  19350. if (availableDeviceTypes.size() == 0)
  19351. {
  19352. createAudioDeviceTypes (availableDeviceTypes);
  19353. while (lastDeviceTypeConfigs.size() < availableDeviceTypes.size())
  19354. lastDeviceTypeConfigs.add (new AudioDeviceSetup());
  19355. if (availableDeviceTypes.size() > 0)
  19356. currentDeviceType = availableDeviceTypes.getUnchecked(0)->getTypeName();
  19357. }
  19358. }
  19359. const OwnedArray <AudioIODeviceType>& AudioDeviceManager::getAvailableDeviceTypes()
  19360. {
  19361. scanDevicesIfNeeded();
  19362. return availableDeviceTypes;
  19363. }
  19364. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio();
  19365. AudioIODeviceType* juce_createAudioIODeviceType_iPhoneAudio();
  19366. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI();
  19367. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound();
  19368. AudioIODeviceType* juce_createAudioIODeviceType_ASIO();
  19369. AudioIODeviceType* juce_createAudioIODeviceType_ALSA();
  19370. AudioIODeviceType* juce_createAudioIODeviceType_JACK();
  19371. void AudioDeviceManager::createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& list)
  19372. {
  19373. (void) list; // (to avoid 'unused param' warnings)
  19374. #if JUCE_WINDOWS
  19375. #if JUCE_WASAPI
  19376. if (SystemStats::getOperatingSystemType() >= SystemStats::WinVista)
  19377. list.add (juce_createAudioIODeviceType_WASAPI());
  19378. #endif
  19379. #if JUCE_DIRECTSOUND
  19380. list.add (juce_createAudioIODeviceType_DirectSound());
  19381. #endif
  19382. #if JUCE_ASIO
  19383. list.add (juce_createAudioIODeviceType_ASIO());
  19384. #endif
  19385. #endif
  19386. #if JUCE_MAC
  19387. list.add (juce_createAudioIODeviceType_CoreAudio());
  19388. #endif
  19389. #if JUCE_IPHONE
  19390. list.add (juce_createAudioIODeviceType_iPhoneAudio());
  19391. #endif
  19392. #if JUCE_LINUX && JUCE_ALSA
  19393. list.add (juce_createAudioIODeviceType_ALSA());
  19394. #endif
  19395. #if JUCE_LINUX && JUCE_JACK
  19396. list.add (juce_createAudioIODeviceType_JACK());
  19397. #endif
  19398. }
  19399. const String AudioDeviceManager::initialise (const int numInputChannelsNeeded,
  19400. const int numOutputChannelsNeeded,
  19401. const XmlElement* const e,
  19402. const bool selectDefaultDeviceOnFailure,
  19403. const String& preferredDefaultDeviceName,
  19404. const AudioDeviceSetup* preferredSetupOptions)
  19405. {
  19406. scanDevicesIfNeeded();
  19407. numInputChansNeeded = numInputChannelsNeeded;
  19408. numOutputChansNeeded = numOutputChannelsNeeded;
  19409. if (e != 0 && e->hasTagName ("DEVICESETUP"))
  19410. {
  19411. lastExplicitSettings = new XmlElement (*e);
  19412. String error;
  19413. AudioDeviceSetup setup;
  19414. if (preferredSetupOptions != 0)
  19415. setup = *preferredSetupOptions;
  19416. if (e->getStringAttribute ("audioDeviceName").isNotEmpty())
  19417. {
  19418. setup.inputDeviceName = setup.outputDeviceName
  19419. = e->getStringAttribute ("audioDeviceName");
  19420. }
  19421. else
  19422. {
  19423. setup.inputDeviceName = e->getStringAttribute ("audioInputDeviceName");
  19424. setup.outputDeviceName = e->getStringAttribute ("audioOutputDeviceName");
  19425. }
  19426. currentDeviceType = e->getStringAttribute ("deviceType");
  19427. if (currentDeviceType.isEmpty())
  19428. {
  19429. AudioIODeviceType* const type = findType (setup.inputDeviceName, setup.outputDeviceName);
  19430. if (type != 0)
  19431. currentDeviceType = type->getTypeName();
  19432. else if (availableDeviceTypes.size() > 0)
  19433. currentDeviceType = availableDeviceTypes[0]->getTypeName();
  19434. }
  19435. setup.bufferSize = e->getIntAttribute ("audioDeviceBufferSize");
  19436. setup.sampleRate = e->getDoubleAttribute ("audioDeviceRate");
  19437. setup.inputChannels.parseString (e->getStringAttribute ("audioDeviceInChans", "11"), 2);
  19438. setup.outputChannels.parseString (e->getStringAttribute ("audioDeviceOutChans", "11"), 2);
  19439. setup.useDefaultInputChannels = ! e->hasAttribute ("audioDeviceInChans");
  19440. setup.useDefaultOutputChannels = ! e->hasAttribute ("audioDeviceOutChans");
  19441. error = setAudioDeviceSetup (setup, true);
  19442. midiInsFromXml.clear();
  19443. forEachXmlChildElementWithTagName (*e, c, "MIDIINPUT")
  19444. midiInsFromXml.add (c->getStringAttribute ("name"));
  19445. const StringArray allMidiIns (MidiInput::getDevices());
  19446. for (int i = allMidiIns.size(); --i >= 0;)
  19447. setMidiInputEnabled (allMidiIns[i], midiInsFromXml.contains (allMidiIns[i]));
  19448. if (error.isNotEmpty() && selectDefaultDeviceOnFailure)
  19449. error = initialise (numInputChannelsNeeded, numOutputChannelsNeeded, 0,
  19450. false, preferredDefaultDeviceName);
  19451. setDefaultMidiOutput (e->getStringAttribute ("defaultMidiOutput"));
  19452. return error;
  19453. }
  19454. else
  19455. {
  19456. AudioDeviceSetup setup;
  19457. if (preferredSetupOptions != 0)
  19458. {
  19459. setup = *preferredSetupOptions;
  19460. }
  19461. else if (preferredDefaultDeviceName.isNotEmpty())
  19462. {
  19463. for (int j = availableDeviceTypes.size(); --j >= 0;)
  19464. {
  19465. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(j);
  19466. StringArray outs (type->getDeviceNames (false));
  19467. int i;
  19468. for (i = 0; i < outs.size(); ++i)
  19469. {
  19470. if (outs[i].matchesWildcard (preferredDefaultDeviceName, true))
  19471. {
  19472. setup.outputDeviceName = outs[i];
  19473. break;
  19474. }
  19475. }
  19476. StringArray ins (type->getDeviceNames (true));
  19477. for (i = 0; i < ins.size(); ++i)
  19478. {
  19479. if (ins[i].matchesWildcard (preferredDefaultDeviceName, true))
  19480. {
  19481. setup.inputDeviceName = ins[i];
  19482. break;
  19483. }
  19484. }
  19485. }
  19486. }
  19487. insertDefaultDeviceNames (setup);
  19488. return setAudioDeviceSetup (setup, false);
  19489. }
  19490. }
  19491. void AudioDeviceManager::insertDefaultDeviceNames (AudioDeviceSetup& setup) const
  19492. {
  19493. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  19494. if (type != 0)
  19495. {
  19496. if (setup.outputDeviceName.isEmpty())
  19497. setup.outputDeviceName = type->getDeviceNames (false) [type->getDefaultDeviceIndex (false)];
  19498. if (setup.inputDeviceName.isEmpty())
  19499. setup.inputDeviceName = type->getDeviceNames (true) [type->getDefaultDeviceIndex (true)];
  19500. }
  19501. }
  19502. XmlElement* AudioDeviceManager::createStateXml() const
  19503. {
  19504. return lastExplicitSettings != 0 ? new XmlElement (*lastExplicitSettings) : 0;
  19505. }
  19506. void AudioDeviceManager::scanDevicesIfNeeded()
  19507. {
  19508. if (listNeedsScanning)
  19509. {
  19510. listNeedsScanning = false;
  19511. createDeviceTypesIfNeeded();
  19512. for (int i = availableDeviceTypes.size(); --i >= 0;)
  19513. availableDeviceTypes.getUnchecked(i)->scanForDevices();
  19514. }
  19515. }
  19516. AudioIODeviceType* AudioDeviceManager::findType (const String& inputName, const String& outputName)
  19517. {
  19518. scanDevicesIfNeeded();
  19519. for (int i = availableDeviceTypes.size(); --i >= 0;)
  19520. {
  19521. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(i);
  19522. if ((inputName.isNotEmpty() && type->getDeviceNames (true).contains (inputName, true))
  19523. || (outputName.isNotEmpty() && type->getDeviceNames (false).contains (outputName, true)))
  19524. {
  19525. return type;
  19526. }
  19527. }
  19528. return 0;
  19529. }
  19530. void AudioDeviceManager::getAudioDeviceSetup (AudioDeviceSetup& setup)
  19531. {
  19532. setup = currentSetup;
  19533. }
  19534. void AudioDeviceManager::deleteCurrentDevice()
  19535. {
  19536. currentAudioDevice = 0;
  19537. currentSetup.inputDeviceName = String::empty;
  19538. currentSetup.outputDeviceName = String::empty;
  19539. }
  19540. void AudioDeviceManager::setCurrentAudioDeviceType (const String& type,
  19541. const bool treatAsChosenDevice)
  19542. {
  19543. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  19544. {
  19545. if (availableDeviceTypes.getUnchecked(i)->getTypeName() == type
  19546. && currentDeviceType != type)
  19547. {
  19548. currentDeviceType = type;
  19549. AudioDeviceSetup s (*lastDeviceTypeConfigs.getUnchecked(i));
  19550. insertDefaultDeviceNames (s);
  19551. setAudioDeviceSetup (s, treatAsChosenDevice);
  19552. sendChangeMessage (this);
  19553. break;
  19554. }
  19555. }
  19556. }
  19557. AudioIODeviceType* AudioDeviceManager::getCurrentDeviceTypeObject() const
  19558. {
  19559. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  19560. if (availableDeviceTypes[i]->getTypeName() == currentDeviceType)
  19561. return availableDeviceTypes[i];
  19562. return availableDeviceTypes[0];
  19563. }
  19564. const String AudioDeviceManager::setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  19565. const bool treatAsChosenDevice)
  19566. {
  19567. jassert (&newSetup != &currentSetup); // this will have no effect
  19568. if (newSetup == currentSetup && currentAudioDevice != 0)
  19569. return String::empty;
  19570. if (! (newSetup == currentSetup))
  19571. sendChangeMessage (this);
  19572. stopDevice();
  19573. const String newInputDeviceName (numInputChansNeeded == 0 ? String::empty : newSetup.inputDeviceName);
  19574. const String newOutputDeviceName (numOutputChansNeeded == 0 ? String::empty : newSetup.outputDeviceName);
  19575. String error;
  19576. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  19577. if (type == 0 || (newInputDeviceName.isEmpty() && newOutputDeviceName.isEmpty()))
  19578. {
  19579. deleteCurrentDevice();
  19580. if (treatAsChosenDevice)
  19581. updateXml();
  19582. return String::empty;
  19583. }
  19584. if (currentSetup.inputDeviceName != newInputDeviceName
  19585. || currentSetup.outputDeviceName != newOutputDeviceName
  19586. || currentAudioDevice == 0)
  19587. {
  19588. deleteCurrentDevice();
  19589. scanDevicesIfNeeded();
  19590. if (newOutputDeviceName.isNotEmpty()
  19591. && ! type->getDeviceNames (false).contains (newOutputDeviceName))
  19592. {
  19593. return "No such device: " + newOutputDeviceName;
  19594. }
  19595. if (newInputDeviceName.isNotEmpty()
  19596. && ! type->getDeviceNames (true).contains (newInputDeviceName))
  19597. {
  19598. return "No such device: " + newInputDeviceName;
  19599. }
  19600. currentAudioDevice = type->createDevice (newOutputDeviceName, newInputDeviceName);
  19601. if (currentAudioDevice == 0)
  19602. 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!";
  19603. else
  19604. error = currentAudioDevice->getLastError();
  19605. if (error.isNotEmpty())
  19606. {
  19607. deleteCurrentDevice();
  19608. return error;
  19609. }
  19610. if (newSetup.useDefaultInputChannels)
  19611. {
  19612. inputChannels.clear();
  19613. inputChannels.setRange (0, numInputChansNeeded, true);
  19614. }
  19615. if (newSetup.useDefaultOutputChannels)
  19616. {
  19617. outputChannels.clear();
  19618. outputChannels.setRange (0, numOutputChansNeeded, true);
  19619. }
  19620. if (newInputDeviceName.isEmpty())
  19621. inputChannels.clear();
  19622. if (newOutputDeviceName.isEmpty())
  19623. outputChannels.clear();
  19624. }
  19625. if (! newSetup.useDefaultInputChannels)
  19626. inputChannels = newSetup.inputChannels;
  19627. if (! newSetup.useDefaultOutputChannels)
  19628. outputChannels = newSetup.outputChannels;
  19629. currentSetup = newSetup;
  19630. currentSetup.sampleRate = chooseBestSampleRate (newSetup.sampleRate);
  19631. error = currentAudioDevice->open (inputChannels,
  19632. outputChannels,
  19633. currentSetup.sampleRate,
  19634. currentSetup.bufferSize);
  19635. if (error.isEmpty())
  19636. {
  19637. currentDeviceType = currentAudioDevice->getTypeName();
  19638. currentAudioDevice->start (&callbackHandler);
  19639. currentSetup.sampleRate = currentAudioDevice->getCurrentSampleRate();
  19640. currentSetup.bufferSize = currentAudioDevice->getCurrentBufferSizeSamples();
  19641. currentSetup.inputChannels = currentAudioDevice->getActiveInputChannels();
  19642. currentSetup.outputChannels = currentAudioDevice->getActiveOutputChannels();
  19643. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  19644. if (availableDeviceTypes.getUnchecked (i)->getTypeName() == currentDeviceType)
  19645. *(lastDeviceTypeConfigs.getUnchecked (i)) = currentSetup;
  19646. if (treatAsChosenDevice)
  19647. updateXml();
  19648. }
  19649. else
  19650. {
  19651. deleteCurrentDevice();
  19652. }
  19653. return error;
  19654. }
  19655. double AudioDeviceManager::chooseBestSampleRate (double rate) const
  19656. {
  19657. jassert (currentAudioDevice != 0);
  19658. if (rate > 0)
  19659. {
  19660. bool ok = false;
  19661. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  19662. {
  19663. const double sr = currentAudioDevice->getSampleRate (i);
  19664. if (sr == rate)
  19665. ok = true;
  19666. }
  19667. if (! ok)
  19668. rate = 0;
  19669. }
  19670. if (rate == 0)
  19671. {
  19672. double lowestAbove44 = 0.0;
  19673. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  19674. {
  19675. const double sr = currentAudioDevice->getSampleRate (i);
  19676. if (sr >= 44100.0 && (lowestAbove44 == 0 || sr < lowestAbove44))
  19677. lowestAbove44 = sr;
  19678. }
  19679. if (lowestAbove44 == 0.0)
  19680. rate = currentAudioDevice->getSampleRate (0);
  19681. else
  19682. rate = lowestAbove44;
  19683. }
  19684. return rate;
  19685. }
  19686. void AudioDeviceManager::stopDevice()
  19687. {
  19688. if (currentAudioDevice != 0)
  19689. currentAudioDevice->stop();
  19690. testSound = 0;
  19691. }
  19692. void AudioDeviceManager::closeAudioDevice()
  19693. {
  19694. stopDevice();
  19695. currentAudioDevice = 0;
  19696. }
  19697. void AudioDeviceManager::restartLastAudioDevice()
  19698. {
  19699. if (currentAudioDevice == 0)
  19700. {
  19701. if (currentSetup.inputDeviceName.isEmpty()
  19702. && currentSetup.outputDeviceName.isEmpty())
  19703. {
  19704. // This method will only reload the last device that was running
  19705. // before closeAudioDevice() was called - you need to actually open
  19706. // one first, with setAudioDevice().
  19707. jassertfalse;
  19708. return;
  19709. }
  19710. AudioDeviceSetup s (currentSetup);
  19711. setAudioDeviceSetup (s, false);
  19712. }
  19713. }
  19714. void AudioDeviceManager::updateXml()
  19715. {
  19716. lastExplicitSettings = new XmlElement ("DEVICESETUP");
  19717. lastExplicitSettings->setAttribute ("deviceType", currentDeviceType);
  19718. lastExplicitSettings->setAttribute ("audioOutputDeviceName", currentSetup.outputDeviceName);
  19719. lastExplicitSettings->setAttribute ("audioInputDeviceName", currentSetup.inputDeviceName);
  19720. if (currentAudioDevice != 0)
  19721. {
  19722. lastExplicitSettings->setAttribute ("audioDeviceRate", currentAudioDevice->getCurrentSampleRate());
  19723. if (currentAudioDevice->getDefaultBufferSize() != currentAudioDevice->getCurrentBufferSizeSamples())
  19724. lastExplicitSettings->setAttribute ("audioDeviceBufferSize", currentAudioDevice->getCurrentBufferSizeSamples());
  19725. if (! currentSetup.useDefaultInputChannels)
  19726. lastExplicitSettings->setAttribute ("audioDeviceInChans", currentSetup.inputChannels.toString (2));
  19727. if (! currentSetup.useDefaultOutputChannels)
  19728. lastExplicitSettings->setAttribute ("audioDeviceOutChans", currentSetup.outputChannels.toString (2));
  19729. }
  19730. for (int i = 0; i < enabledMidiInputs.size(); ++i)
  19731. {
  19732. XmlElement* const m = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  19733. m->setAttribute ("name", enabledMidiInputs[i]->getName());
  19734. }
  19735. if (midiInsFromXml.size() > 0)
  19736. {
  19737. // Add any midi devices that have been enabled before, but which aren't currently
  19738. // open because the device has been disconnected.
  19739. const StringArray availableMidiDevices (MidiInput::getDevices());
  19740. for (int i = 0; i < midiInsFromXml.size(); ++i)
  19741. {
  19742. if (! availableMidiDevices.contains (midiInsFromXml[i], true))
  19743. {
  19744. XmlElement* const m = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  19745. m->setAttribute ("name", midiInsFromXml[i]);
  19746. }
  19747. }
  19748. }
  19749. if (defaultMidiOutputName.isNotEmpty())
  19750. lastExplicitSettings->setAttribute ("defaultMidiOutput", defaultMidiOutputName);
  19751. }
  19752. void AudioDeviceManager::addAudioCallback (AudioIODeviceCallback* newCallback)
  19753. {
  19754. {
  19755. const ScopedLock sl (audioCallbackLock);
  19756. if (callbacks.contains (newCallback))
  19757. return;
  19758. }
  19759. if (currentAudioDevice != 0 && newCallback != 0)
  19760. newCallback->audioDeviceAboutToStart (currentAudioDevice);
  19761. const ScopedLock sl (audioCallbackLock);
  19762. callbacks.add (newCallback);
  19763. }
  19764. void AudioDeviceManager::removeAudioCallback (AudioIODeviceCallback* callback)
  19765. {
  19766. if (callback != 0)
  19767. {
  19768. bool needsDeinitialising = currentAudioDevice != 0;
  19769. {
  19770. const ScopedLock sl (audioCallbackLock);
  19771. needsDeinitialising = needsDeinitialising && callbacks.contains (callback);
  19772. callbacks.removeValue (callback);
  19773. }
  19774. if (needsDeinitialising)
  19775. callback->audioDeviceStopped();
  19776. }
  19777. }
  19778. void AudioDeviceManager::audioDeviceIOCallbackInt (const float** inputChannelData,
  19779. int numInputChannels,
  19780. float** outputChannelData,
  19781. int numOutputChannels,
  19782. int numSamples)
  19783. {
  19784. const ScopedLock sl (audioCallbackLock);
  19785. if (inputLevelMeasurementEnabledCount > 0)
  19786. {
  19787. for (int j = 0; j < numSamples; ++j)
  19788. {
  19789. float s = 0;
  19790. for (int i = 0; i < numInputChannels; ++i)
  19791. s += std::abs (inputChannelData[i][j]);
  19792. s /= numInputChannels;
  19793. const double decayFactor = 0.99992;
  19794. if (s > inputLevel)
  19795. inputLevel = s;
  19796. else if (inputLevel > 0.001f)
  19797. inputLevel *= decayFactor;
  19798. else
  19799. inputLevel = 0;
  19800. }
  19801. }
  19802. if (callbacks.size() > 0)
  19803. {
  19804. const double callbackStartTime = Time::getMillisecondCounterHiRes();
  19805. tempBuffer.setSize (jmax (1, numOutputChannels), jmax (1, numSamples), false, false, true);
  19806. callbacks.getUnchecked(0)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  19807. outputChannelData, numOutputChannels, numSamples);
  19808. float** const tempChans = tempBuffer.getArrayOfChannels();
  19809. for (int i = callbacks.size(); --i > 0;)
  19810. {
  19811. callbacks.getUnchecked(i)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  19812. tempChans, numOutputChannels, numSamples);
  19813. for (int chan = 0; chan < numOutputChannels; ++chan)
  19814. {
  19815. const float* const src = tempChans [chan];
  19816. float* const dst = outputChannelData [chan];
  19817. if (src != 0 && dst != 0)
  19818. for (int j = 0; j < numSamples; ++j)
  19819. dst[j] += src[j];
  19820. }
  19821. }
  19822. const double msTaken = Time::getMillisecondCounterHiRes() - callbackStartTime;
  19823. const double filterAmount = 0.2;
  19824. cpuUsageMs += filterAmount * (msTaken - cpuUsageMs);
  19825. }
  19826. else
  19827. {
  19828. for (int i = 0; i < numOutputChannels; ++i)
  19829. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  19830. }
  19831. if (testSound != 0)
  19832. {
  19833. const int numSamps = jmin (numSamples, testSound->getNumSamples() - testSoundPosition);
  19834. const float* const src = testSound->getSampleData (0, testSoundPosition);
  19835. for (int i = 0; i < numOutputChannels; ++i)
  19836. for (int j = 0; j < numSamps; ++j)
  19837. outputChannelData [i][j] += src[j];
  19838. testSoundPosition += numSamps;
  19839. if (testSoundPosition >= testSound->getNumSamples())
  19840. testSound = 0;
  19841. }
  19842. }
  19843. void AudioDeviceManager::audioDeviceAboutToStartInt (AudioIODevice* const device)
  19844. {
  19845. cpuUsageMs = 0;
  19846. const double sampleRate = device->getCurrentSampleRate();
  19847. const int blockSize = device->getCurrentBufferSizeSamples();
  19848. if (sampleRate > 0.0 && blockSize > 0)
  19849. {
  19850. const double msPerBlock = 1000.0 * blockSize / sampleRate;
  19851. timeToCpuScale = (msPerBlock > 0.0) ? (1.0 / msPerBlock) : 0.0;
  19852. }
  19853. {
  19854. const ScopedLock sl (audioCallbackLock);
  19855. for (int i = callbacks.size(); --i >= 0;)
  19856. callbacks.getUnchecked(i)->audioDeviceAboutToStart (device);
  19857. }
  19858. sendChangeMessage (this);
  19859. }
  19860. void AudioDeviceManager::audioDeviceStoppedInt()
  19861. {
  19862. cpuUsageMs = 0;
  19863. timeToCpuScale = 0;
  19864. sendChangeMessage (this);
  19865. const ScopedLock sl (audioCallbackLock);
  19866. for (int i = callbacks.size(); --i >= 0;)
  19867. callbacks.getUnchecked(i)->audioDeviceStopped();
  19868. }
  19869. double AudioDeviceManager::getCpuUsage() const
  19870. {
  19871. return jlimit (0.0, 1.0, timeToCpuScale * cpuUsageMs);
  19872. }
  19873. void AudioDeviceManager::setMidiInputEnabled (const String& name,
  19874. const bool enabled)
  19875. {
  19876. if (enabled != isMidiInputEnabled (name))
  19877. {
  19878. if (enabled)
  19879. {
  19880. const int index = MidiInput::getDevices().indexOf (name);
  19881. if (index >= 0)
  19882. {
  19883. MidiInput* const min = MidiInput::openDevice (index, &callbackHandler);
  19884. if (min != 0)
  19885. {
  19886. enabledMidiInputs.add (min);
  19887. min->start();
  19888. }
  19889. }
  19890. }
  19891. else
  19892. {
  19893. for (int i = enabledMidiInputs.size(); --i >= 0;)
  19894. if (enabledMidiInputs[i]->getName() == name)
  19895. enabledMidiInputs.remove (i);
  19896. }
  19897. updateXml();
  19898. sendChangeMessage (this);
  19899. }
  19900. }
  19901. bool AudioDeviceManager::isMidiInputEnabled (const String& name) const
  19902. {
  19903. for (int i = enabledMidiInputs.size(); --i >= 0;)
  19904. if (enabledMidiInputs[i]->getName() == name)
  19905. return true;
  19906. return false;
  19907. }
  19908. void AudioDeviceManager::addMidiInputCallback (const String& name,
  19909. MidiInputCallback* callback)
  19910. {
  19911. removeMidiInputCallback (name, callback);
  19912. if (name.isEmpty())
  19913. {
  19914. midiCallbacks.add (callback);
  19915. midiCallbackDevices.add (0);
  19916. }
  19917. else
  19918. {
  19919. for (int i = enabledMidiInputs.size(); --i >= 0;)
  19920. {
  19921. if (enabledMidiInputs[i]->getName() == name)
  19922. {
  19923. const ScopedLock sl (midiCallbackLock);
  19924. midiCallbacks.add (callback);
  19925. midiCallbackDevices.add (enabledMidiInputs[i]);
  19926. break;
  19927. }
  19928. }
  19929. }
  19930. }
  19931. void AudioDeviceManager::removeMidiInputCallback (const String& name,
  19932. MidiInputCallback* /*callback*/)
  19933. {
  19934. const ScopedLock sl (midiCallbackLock);
  19935. for (int i = midiCallbacks.size(); --i >= 0;)
  19936. {
  19937. String devName;
  19938. if (midiCallbackDevices.getUnchecked(i) != 0)
  19939. devName = midiCallbackDevices.getUnchecked(i)->getName();
  19940. if (devName == name)
  19941. {
  19942. midiCallbacks.remove (i);
  19943. midiCallbackDevices.remove (i);
  19944. }
  19945. }
  19946. }
  19947. void AudioDeviceManager::handleIncomingMidiMessageInt (MidiInput* source,
  19948. const MidiMessage& message)
  19949. {
  19950. if (! message.isActiveSense())
  19951. {
  19952. const bool isDefaultSource = (source == 0 || source == enabledMidiInputs.getFirst());
  19953. const ScopedLock sl (midiCallbackLock);
  19954. for (int i = midiCallbackDevices.size(); --i >= 0;)
  19955. {
  19956. MidiInput* const md = midiCallbackDevices.getUnchecked(i);
  19957. if (md == source || (md == 0 && isDefaultSource))
  19958. midiCallbacks.getUnchecked(i)->handleIncomingMidiMessage (source, message);
  19959. }
  19960. }
  19961. }
  19962. void AudioDeviceManager::setDefaultMidiOutput (const String& deviceName)
  19963. {
  19964. if (defaultMidiOutputName != deviceName)
  19965. {
  19966. SortedSet <AudioIODeviceCallback*> oldCallbacks;
  19967. {
  19968. const ScopedLock sl (audioCallbackLock);
  19969. oldCallbacks = callbacks;
  19970. callbacks.clear();
  19971. }
  19972. if (currentAudioDevice != 0)
  19973. for (int i = oldCallbacks.size(); --i >= 0;)
  19974. oldCallbacks.getUnchecked(i)->audioDeviceStopped();
  19975. defaultMidiOutput = 0;
  19976. defaultMidiOutputName = deviceName;
  19977. if (deviceName.isNotEmpty())
  19978. defaultMidiOutput = MidiOutput::openDevice (MidiOutput::getDevices().indexOf (deviceName));
  19979. if (currentAudioDevice != 0)
  19980. for (int i = oldCallbacks.size(); --i >= 0;)
  19981. oldCallbacks.getUnchecked(i)->audioDeviceAboutToStart (currentAudioDevice);
  19982. {
  19983. const ScopedLock sl (audioCallbackLock);
  19984. callbacks = oldCallbacks;
  19985. }
  19986. updateXml();
  19987. sendChangeMessage (this);
  19988. }
  19989. }
  19990. void AudioDeviceManager::CallbackHandler::audioDeviceIOCallback (const float** inputChannelData,
  19991. int numInputChannels,
  19992. float** outputChannelData,
  19993. int numOutputChannels,
  19994. int numSamples)
  19995. {
  19996. owner->audioDeviceIOCallbackInt (inputChannelData, numInputChannels, outputChannelData, numOutputChannels, numSamples);
  19997. }
  19998. void AudioDeviceManager::CallbackHandler::audioDeviceAboutToStart (AudioIODevice* device)
  19999. {
  20000. owner->audioDeviceAboutToStartInt (device);
  20001. }
  20002. void AudioDeviceManager::CallbackHandler::audioDeviceStopped()
  20003. {
  20004. owner->audioDeviceStoppedInt();
  20005. }
  20006. void AudioDeviceManager::CallbackHandler::handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message)
  20007. {
  20008. owner->handleIncomingMidiMessageInt (source, message);
  20009. }
  20010. void AudioDeviceManager::playTestSound()
  20011. {
  20012. { // cunningly nested to swap, unlock and delete in that order.
  20013. ScopedPointer <AudioSampleBuffer> oldSound;
  20014. {
  20015. const ScopedLock sl (audioCallbackLock);
  20016. oldSound = testSound;
  20017. }
  20018. }
  20019. testSoundPosition = 0;
  20020. if (currentAudioDevice != 0)
  20021. {
  20022. const double sampleRate = currentAudioDevice->getCurrentSampleRate();
  20023. const int soundLength = (int) sampleRate;
  20024. AudioSampleBuffer* const newSound = new AudioSampleBuffer (1, soundLength);
  20025. float* samples = newSound->getSampleData (0);
  20026. const double frequency = MidiMessage::getMidiNoteInHertz (80);
  20027. const float amplitude = 0.5f;
  20028. const double phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  20029. for (int i = 0; i < soundLength; ++i)
  20030. samples[i] = amplitude * (float) std::sin (i * phasePerSample);
  20031. newSound->applyGainRamp (0, 0, soundLength / 10, 0.0f, 1.0f);
  20032. newSound->applyGainRamp (0, soundLength - soundLength / 4, soundLength / 4, 1.0f, 0.0f);
  20033. const ScopedLock sl (audioCallbackLock);
  20034. testSound = newSound;
  20035. }
  20036. }
  20037. void AudioDeviceManager::enableInputLevelMeasurement (const bool enableMeasurement)
  20038. {
  20039. const ScopedLock sl (audioCallbackLock);
  20040. if (enableMeasurement)
  20041. ++inputLevelMeasurementEnabledCount;
  20042. else
  20043. --inputLevelMeasurementEnabledCount;
  20044. inputLevel = 0;
  20045. }
  20046. double AudioDeviceManager::getCurrentInputLevel() const
  20047. {
  20048. jassert (inputLevelMeasurementEnabledCount > 0); // you need to call enableInputLevelMeasurement() before using this!
  20049. return inputLevel;
  20050. }
  20051. END_JUCE_NAMESPACE
  20052. /*** End of inlined file: juce_AudioDeviceManager.cpp ***/
  20053. /*** Start of inlined file: juce_AudioIODevice.cpp ***/
  20054. BEGIN_JUCE_NAMESPACE
  20055. AudioIODevice::AudioIODevice (const String& deviceName, const String& typeName_)
  20056. : name (deviceName),
  20057. typeName (typeName_)
  20058. {
  20059. }
  20060. AudioIODevice::~AudioIODevice()
  20061. {
  20062. }
  20063. bool AudioIODevice::hasControlPanel() const
  20064. {
  20065. return false;
  20066. }
  20067. bool AudioIODevice::showControlPanel()
  20068. {
  20069. jassertfalse; // this should only be called for devices which return true from
  20070. // their hasControlPanel() method.
  20071. return false;
  20072. }
  20073. END_JUCE_NAMESPACE
  20074. /*** End of inlined file: juce_AudioIODevice.cpp ***/
  20075. /*** Start of inlined file: juce_AudioIODeviceType.cpp ***/
  20076. BEGIN_JUCE_NAMESPACE
  20077. AudioIODeviceType::AudioIODeviceType (const String& name)
  20078. : typeName (name)
  20079. {
  20080. }
  20081. AudioIODeviceType::~AudioIODeviceType()
  20082. {
  20083. }
  20084. END_JUCE_NAMESPACE
  20085. /*** End of inlined file: juce_AudioIODeviceType.cpp ***/
  20086. /*** Start of inlined file: juce_MidiOutput.cpp ***/
  20087. BEGIN_JUCE_NAMESPACE
  20088. MidiOutput::MidiOutput()
  20089. : Thread ("midi out"),
  20090. internal (0),
  20091. firstMessage (0)
  20092. {
  20093. }
  20094. MidiOutput::PendingMessage::PendingMessage (const uint8* const data, const int len,
  20095. const double sampleNumber)
  20096. : message (data, len, sampleNumber)
  20097. {
  20098. }
  20099. void MidiOutput::sendBlockOfMessages (const MidiBuffer& buffer,
  20100. const double millisecondCounterToStartAt,
  20101. double samplesPerSecondForBuffer)
  20102. {
  20103. // You've got to call startBackgroundThread() for this to actually work..
  20104. jassert (isThreadRunning());
  20105. // this needs to be a value in the future - RTFM for this method!
  20106. jassert (millisecondCounterToStartAt > 0);
  20107. const double timeScaleFactor = 1000.0 / samplesPerSecondForBuffer;
  20108. MidiBuffer::Iterator i (buffer);
  20109. const uint8* data;
  20110. int len, time;
  20111. while (i.getNextEvent (data, len, time))
  20112. {
  20113. const double eventTime = millisecondCounterToStartAt + timeScaleFactor * time;
  20114. PendingMessage* const m
  20115. = new PendingMessage (data, len, eventTime);
  20116. const ScopedLock sl (lock);
  20117. if (firstMessage == 0 || firstMessage->message.getTimeStamp() > eventTime)
  20118. {
  20119. m->next = firstMessage;
  20120. firstMessage = m;
  20121. }
  20122. else
  20123. {
  20124. PendingMessage* mm = firstMessage;
  20125. while (mm->next != 0 && mm->next->message.getTimeStamp() <= eventTime)
  20126. mm = mm->next;
  20127. m->next = mm->next;
  20128. mm->next = m;
  20129. }
  20130. }
  20131. notify();
  20132. }
  20133. void MidiOutput::clearAllPendingMessages()
  20134. {
  20135. const ScopedLock sl (lock);
  20136. while (firstMessage != 0)
  20137. {
  20138. PendingMessage* const m = firstMessage;
  20139. firstMessage = firstMessage->next;
  20140. delete m;
  20141. }
  20142. }
  20143. void MidiOutput::startBackgroundThread()
  20144. {
  20145. startThread (9);
  20146. }
  20147. void MidiOutput::stopBackgroundThread()
  20148. {
  20149. stopThread (5000);
  20150. }
  20151. void MidiOutput::run()
  20152. {
  20153. while (! threadShouldExit())
  20154. {
  20155. uint32 now = Time::getMillisecondCounter();
  20156. uint32 eventTime = 0;
  20157. uint32 timeToWait = 500;
  20158. PendingMessage* message;
  20159. {
  20160. const ScopedLock sl (lock);
  20161. message = firstMessage;
  20162. if (message != 0)
  20163. {
  20164. eventTime = roundToInt (message->message.getTimeStamp());
  20165. if (eventTime > now + 20)
  20166. {
  20167. timeToWait = eventTime - (now + 20);
  20168. message = 0;
  20169. }
  20170. else
  20171. {
  20172. firstMessage = message->next;
  20173. }
  20174. }
  20175. }
  20176. if (message != 0)
  20177. {
  20178. if (eventTime > now)
  20179. {
  20180. Time::waitForMillisecondCounter (eventTime);
  20181. if (threadShouldExit())
  20182. break;
  20183. }
  20184. if (eventTime > now - 200)
  20185. sendMessageNow (message->message);
  20186. delete message;
  20187. }
  20188. else
  20189. {
  20190. jassert (timeToWait < 1000 * 30);
  20191. wait (timeToWait);
  20192. }
  20193. }
  20194. clearAllPendingMessages();
  20195. }
  20196. END_JUCE_NAMESPACE
  20197. /*** End of inlined file: juce_MidiOutput.cpp ***/
  20198. /*** Start of inlined file: juce_AudioDataConverters.cpp ***/
  20199. BEGIN_JUCE_NAMESPACE
  20200. void AudioDataConverters::convertFloatToInt16LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20201. {
  20202. const double maxVal = (double) 0x7fff;
  20203. char* intData = static_cast <char*> (dest);
  20204. if (dest != (void*) source || destBytesPerSample <= 4)
  20205. {
  20206. for (int i = 0; i < numSamples; ++i)
  20207. {
  20208. *(uint16*) intData = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20209. intData += destBytesPerSample;
  20210. }
  20211. }
  20212. else
  20213. {
  20214. intData += destBytesPerSample * numSamples;
  20215. for (int i = numSamples; --i >= 0;)
  20216. {
  20217. intData -= destBytesPerSample;
  20218. *(uint16*) intData = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20219. }
  20220. }
  20221. }
  20222. void AudioDataConverters::convertFloatToInt16BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20223. {
  20224. const double maxVal = (double) 0x7fff;
  20225. char* intData = static_cast <char*> (dest);
  20226. if (dest != (void*) source || destBytesPerSample <= 4)
  20227. {
  20228. for (int i = 0; i < numSamples; ++i)
  20229. {
  20230. *(uint16*) intData = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20231. intData += destBytesPerSample;
  20232. }
  20233. }
  20234. else
  20235. {
  20236. intData += destBytesPerSample * numSamples;
  20237. for (int i = numSamples; --i >= 0;)
  20238. {
  20239. intData -= destBytesPerSample;
  20240. *(uint16*) intData = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20241. }
  20242. }
  20243. }
  20244. void AudioDataConverters::convertFloatToInt24LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20245. {
  20246. const double maxVal = (double) 0x7fffff;
  20247. char* intData = static_cast <char*> (dest);
  20248. if (dest != (void*) source || destBytesPerSample <= 4)
  20249. {
  20250. for (int i = 0; i < numSamples; ++i)
  20251. {
  20252. ByteOrder::littleEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  20253. intData += destBytesPerSample;
  20254. }
  20255. }
  20256. else
  20257. {
  20258. intData += destBytesPerSample * numSamples;
  20259. for (int i = numSamples; --i >= 0;)
  20260. {
  20261. intData -= destBytesPerSample;
  20262. ByteOrder::littleEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  20263. }
  20264. }
  20265. }
  20266. void AudioDataConverters::convertFloatToInt24BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20267. {
  20268. const double maxVal = (double) 0x7fffff;
  20269. char* intData = static_cast <char*> (dest);
  20270. if (dest != (void*) source || destBytesPerSample <= 4)
  20271. {
  20272. for (int i = 0; i < numSamples; ++i)
  20273. {
  20274. ByteOrder::bigEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  20275. intData += destBytesPerSample;
  20276. }
  20277. }
  20278. else
  20279. {
  20280. intData += destBytesPerSample * numSamples;
  20281. for (int i = numSamples; --i >= 0;)
  20282. {
  20283. intData -= destBytesPerSample;
  20284. ByteOrder::bigEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  20285. }
  20286. }
  20287. }
  20288. void AudioDataConverters::convertFloatToInt32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20289. {
  20290. const double maxVal = (double) 0x7fffffff;
  20291. char* intData = static_cast <char*> (dest);
  20292. if (dest != (void*) source || destBytesPerSample <= 4)
  20293. {
  20294. for (int i = 0; i < numSamples; ++i)
  20295. {
  20296. *(uint32*)intData = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20297. intData += destBytesPerSample;
  20298. }
  20299. }
  20300. else
  20301. {
  20302. intData += destBytesPerSample * numSamples;
  20303. for (int i = numSamples; --i >= 0;)
  20304. {
  20305. intData -= destBytesPerSample;
  20306. *(uint32*)intData = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20307. }
  20308. }
  20309. }
  20310. void AudioDataConverters::convertFloatToInt32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20311. {
  20312. const double maxVal = (double) 0x7fffffff;
  20313. char* intData = static_cast <char*> (dest);
  20314. if (dest != (void*) source || destBytesPerSample <= 4)
  20315. {
  20316. for (int i = 0; i < numSamples; ++i)
  20317. {
  20318. *(uint32*)intData = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20319. intData += destBytesPerSample;
  20320. }
  20321. }
  20322. else
  20323. {
  20324. intData += destBytesPerSample * numSamples;
  20325. for (int i = numSamples; --i >= 0;)
  20326. {
  20327. intData -= destBytesPerSample;
  20328. *(uint32*)intData = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20329. }
  20330. }
  20331. }
  20332. void AudioDataConverters::convertFloatToFloat32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20333. {
  20334. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  20335. char* d = static_cast <char*> (dest);
  20336. for (int i = 0; i < numSamples; ++i)
  20337. {
  20338. *(float*) d = source[i];
  20339. #if JUCE_BIG_ENDIAN
  20340. *(uint32*) d = ByteOrder::swap (*(uint32*) d);
  20341. #endif
  20342. d += destBytesPerSample;
  20343. }
  20344. }
  20345. void AudioDataConverters::convertFloatToFloat32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20346. {
  20347. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  20348. char* d = static_cast <char*> (dest);
  20349. for (int i = 0; i < numSamples; ++i)
  20350. {
  20351. *(float*) d = source[i];
  20352. #if JUCE_LITTLE_ENDIAN
  20353. *(uint32*) d = ByteOrder::swap (*(uint32*) d);
  20354. #endif
  20355. d += destBytesPerSample;
  20356. }
  20357. }
  20358. void AudioDataConverters::convertInt16LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20359. {
  20360. const float scale = 1.0f / 0x7fff;
  20361. const char* intData = static_cast <const char*> (source);
  20362. if (source != (void*) dest || srcBytesPerSample >= 4)
  20363. {
  20364. for (int i = 0; i < numSamples; ++i)
  20365. {
  20366. dest[i] = scale * (short) ByteOrder::swapIfBigEndian (*(uint16*)intData);
  20367. intData += srcBytesPerSample;
  20368. }
  20369. }
  20370. else
  20371. {
  20372. intData += srcBytesPerSample * numSamples;
  20373. for (int i = numSamples; --i >= 0;)
  20374. {
  20375. intData -= srcBytesPerSample;
  20376. dest[i] = scale * (short) ByteOrder::swapIfBigEndian (*(uint16*)intData);
  20377. }
  20378. }
  20379. }
  20380. void AudioDataConverters::convertInt16BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20381. {
  20382. const float scale = 1.0f / 0x7fff;
  20383. const char* intData = static_cast <const char*> (source);
  20384. if (source != (void*) dest || srcBytesPerSample >= 4)
  20385. {
  20386. for (int i = 0; i < numSamples; ++i)
  20387. {
  20388. dest[i] = scale * (short) ByteOrder::swapIfLittleEndian (*(uint16*)intData);
  20389. intData += srcBytesPerSample;
  20390. }
  20391. }
  20392. else
  20393. {
  20394. intData += srcBytesPerSample * numSamples;
  20395. for (int i = numSamples; --i >= 0;)
  20396. {
  20397. intData -= srcBytesPerSample;
  20398. dest[i] = scale * (short) ByteOrder::swapIfLittleEndian (*(uint16*)intData);
  20399. }
  20400. }
  20401. }
  20402. void AudioDataConverters::convertInt24LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20403. {
  20404. const float scale = 1.0f / 0x7fffff;
  20405. const char* intData = static_cast <const char*> (source);
  20406. if (source != (void*) dest || srcBytesPerSample >= 4)
  20407. {
  20408. for (int i = 0; i < numSamples; ++i)
  20409. {
  20410. dest[i] = scale * (short) ByteOrder::littleEndian24Bit (intData);
  20411. intData += srcBytesPerSample;
  20412. }
  20413. }
  20414. else
  20415. {
  20416. intData += srcBytesPerSample * numSamples;
  20417. for (int i = numSamples; --i >= 0;)
  20418. {
  20419. intData -= srcBytesPerSample;
  20420. dest[i] = scale * (short) ByteOrder::littleEndian24Bit (intData);
  20421. }
  20422. }
  20423. }
  20424. void AudioDataConverters::convertInt24BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20425. {
  20426. const float scale = 1.0f / 0x7fffff;
  20427. const char* intData = static_cast <const char*> (source);
  20428. if (source != (void*) dest || srcBytesPerSample >= 4)
  20429. {
  20430. for (int i = 0; i < numSamples; ++i)
  20431. {
  20432. dest[i] = scale * (short) ByteOrder::bigEndian24Bit (intData);
  20433. intData += srcBytesPerSample;
  20434. }
  20435. }
  20436. else
  20437. {
  20438. intData += srcBytesPerSample * numSamples;
  20439. for (int i = numSamples; --i >= 0;)
  20440. {
  20441. intData -= srcBytesPerSample;
  20442. dest[i] = scale * (short) ByteOrder::bigEndian24Bit (intData);
  20443. }
  20444. }
  20445. }
  20446. void AudioDataConverters::convertInt32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20447. {
  20448. const float scale = 1.0f / 0x7fffffff;
  20449. const char* intData = static_cast <const char*> (source);
  20450. if (source != (void*) dest || srcBytesPerSample >= 4)
  20451. {
  20452. for (int i = 0; i < numSamples; ++i)
  20453. {
  20454. dest[i] = scale * (int) ByteOrder::swapIfBigEndian (*(uint32*) intData);
  20455. intData += srcBytesPerSample;
  20456. }
  20457. }
  20458. else
  20459. {
  20460. intData += srcBytesPerSample * numSamples;
  20461. for (int i = numSamples; --i >= 0;)
  20462. {
  20463. intData -= srcBytesPerSample;
  20464. dest[i] = scale * (int) ByteOrder::swapIfBigEndian (*(uint32*) intData);
  20465. }
  20466. }
  20467. }
  20468. void AudioDataConverters::convertInt32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20469. {
  20470. const float scale = 1.0f / 0x7fffffff;
  20471. const char* intData = static_cast <const char*> (source);
  20472. if (source != (void*) dest || srcBytesPerSample >= 4)
  20473. {
  20474. for (int i = 0; i < numSamples; ++i)
  20475. {
  20476. dest[i] = scale * (int) ByteOrder::swapIfLittleEndian (*(uint32*) intData);
  20477. intData += srcBytesPerSample;
  20478. }
  20479. }
  20480. else
  20481. {
  20482. intData += srcBytesPerSample * numSamples;
  20483. for (int i = numSamples; --i >= 0;)
  20484. {
  20485. intData -= srcBytesPerSample;
  20486. dest[i] = scale * (int) ByteOrder::swapIfLittleEndian (*(uint32*) intData);
  20487. }
  20488. }
  20489. }
  20490. void AudioDataConverters::convertFloat32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20491. {
  20492. const char* s = static_cast <const char*> (source);
  20493. for (int i = 0; i < numSamples; ++i)
  20494. {
  20495. dest[i] = *(float*)s;
  20496. #if JUCE_BIG_ENDIAN
  20497. uint32* const d = (uint32*) (dest + i);
  20498. *d = ByteOrder::swap (*d);
  20499. #endif
  20500. s += srcBytesPerSample;
  20501. }
  20502. }
  20503. void AudioDataConverters::convertFloat32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20504. {
  20505. const char* s = static_cast <const char*> (source);
  20506. for (int i = 0; i < numSamples; ++i)
  20507. {
  20508. dest[i] = *(float*)s;
  20509. #if JUCE_LITTLE_ENDIAN
  20510. uint32* const d = (uint32*) (dest + i);
  20511. *d = ByteOrder::swap (*d);
  20512. #endif
  20513. s += srcBytesPerSample;
  20514. }
  20515. }
  20516. void AudioDataConverters::convertFloatToFormat (const DataFormat destFormat,
  20517. const float* const source,
  20518. void* const dest,
  20519. const int numSamples)
  20520. {
  20521. switch (destFormat)
  20522. {
  20523. case int16LE:
  20524. convertFloatToInt16LE (source, dest, numSamples);
  20525. break;
  20526. case int16BE:
  20527. convertFloatToInt16BE (source, dest, numSamples);
  20528. break;
  20529. case int24LE:
  20530. convertFloatToInt24LE (source, dest, numSamples);
  20531. break;
  20532. case int24BE:
  20533. convertFloatToInt24BE (source, dest, numSamples);
  20534. break;
  20535. case int32LE:
  20536. convertFloatToInt32LE (source, dest, numSamples);
  20537. break;
  20538. case int32BE:
  20539. convertFloatToInt32BE (source, dest, numSamples);
  20540. break;
  20541. case float32LE:
  20542. convertFloatToFloat32LE (source, dest, numSamples);
  20543. break;
  20544. case float32BE:
  20545. convertFloatToFloat32BE (source, dest, numSamples);
  20546. break;
  20547. default:
  20548. jassertfalse;
  20549. break;
  20550. }
  20551. }
  20552. void AudioDataConverters::convertFormatToFloat (const DataFormat sourceFormat,
  20553. const void* const source,
  20554. float* const dest,
  20555. const int numSamples)
  20556. {
  20557. switch (sourceFormat)
  20558. {
  20559. case int16LE:
  20560. convertInt16LEToFloat (source, dest, numSamples);
  20561. break;
  20562. case int16BE:
  20563. convertInt16BEToFloat (source, dest, numSamples);
  20564. break;
  20565. case int24LE:
  20566. convertInt24LEToFloat (source, dest, numSamples);
  20567. break;
  20568. case int24BE:
  20569. convertInt24BEToFloat (source, dest, numSamples);
  20570. break;
  20571. case int32LE:
  20572. convertInt32LEToFloat (source, dest, numSamples);
  20573. break;
  20574. case int32BE:
  20575. convertInt32BEToFloat (source, dest, numSamples);
  20576. break;
  20577. case float32LE:
  20578. convertFloat32LEToFloat (source, dest, numSamples);
  20579. break;
  20580. case float32BE:
  20581. convertFloat32BEToFloat (source, dest, numSamples);
  20582. break;
  20583. default:
  20584. jassertfalse;
  20585. break;
  20586. }
  20587. }
  20588. void AudioDataConverters::interleaveSamples (const float** const source,
  20589. float* const dest,
  20590. const int numSamples,
  20591. const int numChannels)
  20592. {
  20593. for (int chan = 0; chan < numChannels; ++chan)
  20594. {
  20595. int i = chan;
  20596. const float* src = source [chan];
  20597. for (int j = 0; j < numSamples; ++j)
  20598. {
  20599. dest [i] = src [j];
  20600. i += numChannels;
  20601. }
  20602. }
  20603. }
  20604. void AudioDataConverters::deinterleaveSamples (const float* const source,
  20605. float** const dest,
  20606. const int numSamples,
  20607. const int numChannels)
  20608. {
  20609. for (int chan = 0; chan < numChannels; ++chan)
  20610. {
  20611. int i = chan;
  20612. float* dst = dest [chan];
  20613. for (int j = 0; j < numSamples; ++j)
  20614. {
  20615. dst [j] = source [i];
  20616. i += numChannels;
  20617. }
  20618. }
  20619. }
  20620. END_JUCE_NAMESPACE
  20621. /*** End of inlined file: juce_AudioDataConverters.cpp ***/
  20622. /*** Start of inlined file: juce_AudioSampleBuffer.cpp ***/
  20623. BEGIN_JUCE_NAMESPACE
  20624. AudioSampleBuffer::AudioSampleBuffer (const int numChannels_,
  20625. const int numSamples) throw()
  20626. : numChannels (numChannels_),
  20627. size (numSamples)
  20628. {
  20629. jassert (numSamples >= 0);
  20630. jassert (numChannels_ > 0);
  20631. allocateData();
  20632. }
  20633. AudioSampleBuffer::AudioSampleBuffer (const AudioSampleBuffer& other) throw()
  20634. : numChannels (other.numChannels),
  20635. size (other.size)
  20636. {
  20637. allocateData();
  20638. const size_t numBytes = size * sizeof (float);
  20639. for (int i = 0; i < numChannels; ++i)
  20640. memcpy (channels[i], other.channels[i], numBytes);
  20641. }
  20642. void AudioSampleBuffer::allocateData()
  20643. {
  20644. const size_t channelListSize = (numChannels + 1) * sizeof (float*);
  20645. allocatedBytes = (int) (numChannels * size * sizeof (float) + channelListSize + 32);
  20646. allocatedData.malloc (allocatedBytes);
  20647. channels = reinterpret_cast <float**> (allocatedData.getData());
  20648. float* chan = (float*) (allocatedData + channelListSize);
  20649. for (int i = 0; i < numChannels; ++i)
  20650. {
  20651. channels[i] = chan;
  20652. chan += size;
  20653. }
  20654. channels [numChannels] = 0;
  20655. }
  20656. AudioSampleBuffer::AudioSampleBuffer (float** dataToReferTo,
  20657. const int numChannels_,
  20658. const int numSamples) throw()
  20659. : numChannels (numChannels_),
  20660. size (numSamples),
  20661. allocatedBytes (0)
  20662. {
  20663. jassert (numChannels_ > 0);
  20664. allocateChannels (dataToReferTo);
  20665. }
  20666. void AudioSampleBuffer::setDataToReferTo (float** dataToReferTo,
  20667. const int newNumChannels,
  20668. const int newNumSamples) throw()
  20669. {
  20670. jassert (newNumChannels > 0);
  20671. allocatedBytes = 0;
  20672. allocatedData.free();
  20673. numChannels = newNumChannels;
  20674. size = newNumSamples;
  20675. allocateChannels (dataToReferTo);
  20676. }
  20677. void AudioSampleBuffer::allocateChannels (float** const dataToReferTo)
  20678. {
  20679. // (try to avoid doing a malloc here, as that'll blow up things like Pro-Tools)
  20680. if (numChannels < numElementsInArray (preallocatedChannelSpace))
  20681. {
  20682. channels = static_cast <float**> (preallocatedChannelSpace);
  20683. }
  20684. else
  20685. {
  20686. allocatedData.malloc (numChannels + 1, sizeof (float*));
  20687. channels = reinterpret_cast <float**> (allocatedData.getData());
  20688. }
  20689. for (int i = 0; i < numChannels; ++i)
  20690. {
  20691. // you have to pass in the same number of valid pointers as numChannels
  20692. jassert (dataToReferTo[i] != 0);
  20693. channels[i] = dataToReferTo[i];
  20694. }
  20695. channels [numChannels] = 0;
  20696. }
  20697. AudioSampleBuffer& AudioSampleBuffer::operator= (const AudioSampleBuffer& other) throw()
  20698. {
  20699. if (this != &other)
  20700. {
  20701. setSize (other.getNumChannels(), other.getNumSamples(), false, false, false);
  20702. const size_t numBytes = size * sizeof (float);
  20703. for (int i = 0; i < numChannels; ++i)
  20704. memcpy (channels[i], other.channels[i], numBytes);
  20705. }
  20706. return *this;
  20707. }
  20708. AudioSampleBuffer::~AudioSampleBuffer() throw()
  20709. {
  20710. }
  20711. void AudioSampleBuffer::setSize (const int newNumChannels,
  20712. const int newNumSamples,
  20713. const bool keepExistingContent,
  20714. const bool clearExtraSpace,
  20715. const bool avoidReallocating) throw()
  20716. {
  20717. jassert (newNumChannels > 0);
  20718. if (newNumSamples != size || newNumChannels != numChannels)
  20719. {
  20720. const size_t channelListSize = (newNumChannels + 1) * sizeof (float*);
  20721. const size_t newTotalBytes = (newNumChannels * newNumSamples * sizeof (float)) + channelListSize + 32;
  20722. if (keepExistingContent)
  20723. {
  20724. HeapBlock <char> newData;
  20725. newData.allocate (newTotalBytes, clearExtraSpace);
  20726. const int numChansToCopy = jmin (numChannels, newNumChannels);
  20727. const size_t numBytesToCopy = sizeof (float) * jmin (newNumSamples, size);
  20728. float** const newChannels = reinterpret_cast <float**> (newData.getData());
  20729. float* newChan = reinterpret_cast <float*> (newData + channelListSize);
  20730. for (int i = 0; i < numChansToCopy; ++i)
  20731. {
  20732. memcpy (newChan, channels[i], numBytesToCopy);
  20733. newChannels[i] = newChan;
  20734. newChan += newNumSamples;
  20735. }
  20736. allocatedData.swapWith (newData);
  20737. allocatedBytes = (int) newTotalBytes;
  20738. channels = newChannels;
  20739. }
  20740. else
  20741. {
  20742. if (avoidReallocating && allocatedBytes >= newTotalBytes)
  20743. {
  20744. if (clearExtraSpace)
  20745. zeromem (allocatedData, newTotalBytes);
  20746. }
  20747. else
  20748. {
  20749. allocatedBytes = newTotalBytes;
  20750. allocatedData.allocate (newTotalBytes, clearExtraSpace);
  20751. channels = reinterpret_cast <float**> (allocatedData.getData());
  20752. }
  20753. float* chan = reinterpret_cast <float*> (allocatedData + channelListSize);
  20754. for (int i = 0; i < newNumChannels; ++i)
  20755. {
  20756. channels[i] = chan;
  20757. chan += newNumSamples;
  20758. }
  20759. }
  20760. channels [newNumChannels] = 0;
  20761. size = newNumSamples;
  20762. numChannels = newNumChannels;
  20763. }
  20764. }
  20765. void AudioSampleBuffer::clear() throw()
  20766. {
  20767. for (int i = 0; i < numChannels; ++i)
  20768. zeromem (channels[i], size * sizeof (float));
  20769. }
  20770. void AudioSampleBuffer::clear (const int startSample,
  20771. const int numSamples) throw()
  20772. {
  20773. jassert (startSample >= 0 && startSample + numSamples <= size);
  20774. for (int i = 0; i < numChannels; ++i)
  20775. zeromem (channels [i] + startSample, numSamples * sizeof (float));
  20776. }
  20777. void AudioSampleBuffer::clear (const int channel,
  20778. const int startSample,
  20779. const int numSamples) throw()
  20780. {
  20781. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  20782. jassert (startSample >= 0 && startSample + numSamples <= size);
  20783. zeromem (channels [channel] + startSample, numSamples * sizeof (float));
  20784. }
  20785. void AudioSampleBuffer::applyGain (const int channel,
  20786. const int startSample,
  20787. int numSamples,
  20788. const float gain) throw()
  20789. {
  20790. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  20791. jassert (startSample >= 0 && startSample + numSamples <= size);
  20792. if (gain != 1.0f)
  20793. {
  20794. float* d = channels [channel] + startSample;
  20795. if (gain == 0.0f)
  20796. {
  20797. zeromem (d, sizeof (float) * numSamples);
  20798. }
  20799. else
  20800. {
  20801. while (--numSamples >= 0)
  20802. *d++ *= gain;
  20803. }
  20804. }
  20805. }
  20806. void AudioSampleBuffer::applyGainRamp (const int channel,
  20807. const int startSample,
  20808. int numSamples,
  20809. float startGain,
  20810. float endGain) throw()
  20811. {
  20812. if (startGain == endGain)
  20813. {
  20814. applyGain (channel, startSample, numSamples, startGain);
  20815. }
  20816. else
  20817. {
  20818. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  20819. jassert (startSample >= 0 && startSample + numSamples <= size);
  20820. const float increment = (endGain - startGain) / numSamples;
  20821. float* d = channels [channel] + startSample;
  20822. while (--numSamples >= 0)
  20823. {
  20824. *d++ *= startGain;
  20825. startGain += increment;
  20826. }
  20827. }
  20828. }
  20829. void AudioSampleBuffer::applyGain (const int startSample,
  20830. const int numSamples,
  20831. const float gain) throw()
  20832. {
  20833. for (int i = 0; i < numChannels; ++i)
  20834. applyGain (i, startSample, numSamples, gain);
  20835. }
  20836. void AudioSampleBuffer::addFrom (const int destChannel,
  20837. const int destStartSample,
  20838. const AudioSampleBuffer& source,
  20839. const int sourceChannel,
  20840. const int sourceStartSample,
  20841. int numSamples,
  20842. const float gain) throw()
  20843. {
  20844. jassert (&source != this || sourceChannel != destChannel);
  20845. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20846. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20847. jassert (((unsigned int) sourceChannel) < (unsigned int) source.numChannels);
  20848. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  20849. if (gain != 0.0f && numSamples > 0)
  20850. {
  20851. float* d = channels [destChannel] + destStartSample;
  20852. const float* s = source.channels [sourceChannel] + sourceStartSample;
  20853. if (gain != 1.0f)
  20854. {
  20855. while (--numSamples >= 0)
  20856. *d++ += gain * *s++;
  20857. }
  20858. else
  20859. {
  20860. while (--numSamples >= 0)
  20861. *d++ += *s++;
  20862. }
  20863. }
  20864. }
  20865. void AudioSampleBuffer::addFrom (const int destChannel,
  20866. const int destStartSample,
  20867. const float* source,
  20868. int numSamples,
  20869. const float gain) throw()
  20870. {
  20871. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20872. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20873. jassert (source != 0);
  20874. if (gain != 0.0f && numSamples > 0)
  20875. {
  20876. float* d = channels [destChannel] + destStartSample;
  20877. if (gain != 1.0f)
  20878. {
  20879. while (--numSamples >= 0)
  20880. *d++ += gain * *source++;
  20881. }
  20882. else
  20883. {
  20884. while (--numSamples >= 0)
  20885. *d++ += *source++;
  20886. }
  20887. }
  20888. }
  20889. void AudioSampleBuffer::addFromWithRamp (const int destChannel,
  20890. const int destStartSample,
  20891. const float* source,
  20892. int numSamples,
  20893. float startGain,
  20894. const float endGain) throw()
  20895. {
  20896. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20897. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20898. jassert (source != 0);
  20899. if (startGain == endGain)
  20900. {
  20901. addFrom (destChannel,
  20902. destStartSample,
  20903. source,
  20904. numSamples,
  20905. startGain);
  20906. }
  20907. else
  20908. {
  20909. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  20910. {
  20911. const float increment = (endGain - startGain) / numSamples;
  20912. float* d = channels [destChannel] + destStartSample;
  20913. while (--numSamples >= 0)
  20914. {
  20915. *d++ += startGain * *source++;
  20916. startGain += increment;
  20917. }
  20918. }
  20919. }
  20920. }
  20921. void AudioSampleBuffer::copyFrom (const int destChannel,
  20922. const int destStartSample,
  20923. const AudioSampleBuffer& source,
  20924. const int sourceChannel,
  20925. const int sourceStartSample,
  20926. int numSamples) throw()
  20927. {
  20928. jassert (&source != this || sourceChannel != destChannel);
  20929. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20930. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20931. jassert (((unsigned int) sourceChannel) < (unsigned int) source.numChannels);
  20932. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  20933. if (numSamples > 0)
  20934. {
  20935. memcpy (channels [destChannel] + destStartSample,
  20936. source.channels [sourceChannel] + sourceStartSample,
  20937. sizeof (float) * numSamples);
  20938. }
  20939. }
  20940. void AudioSampleBuffer::copyFrom (const int destChannel,
  20941. const int destStartSample,
  20942. const float* source,
  20943. int numSamples) throw()
  20944. {
  20945. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20946. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20947. jassert (source != 0);
  20948. if (numSamples > 0)
  20949. {
  20950. memcpy (channels [destChannel] + destStartSample,
  20951. source,
  20952. sizeof (float) * numSamples);
  20953. }
  20954. }
  20955. void AudioSampleBuffer::copyFrom (const int destChannel,
  20956. const int destStartSample,
  20957. const float* source,
  20958. int numSamples,
  20959. const float gain) throw()
  20960. {
  20961. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20962. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20963. jassert (source != 0);
  20964. if (numSamples > 0)
  20965. {
  20966. float* d = channels [destChannel] + destStartSample;
  20967. if (gain != 1.0f)
  20968. {
  20969. if (gain == 0)
  20970. {
  20971. zeromem (d, sizeof (float) * numSamples);
  20972. }
  20973. else
  20974. {
  20975. while (--numSamples >= 0)
  20976. *d++ = gain * *source++;
  20977. }
  20978. }
  20979. else
  20980. {
  20981. memcpy (d, source, sizeof (float) * numSamples);
  20982. }
  20983. }
  20984. }
  20985. void AudioSampleBuffer::copyFromWithRamp (const int destChannel,
  20986. const int destStartSample,
  20987. const float* source,
  20988. int numSamples,
  20989. float startGain,
  20990. float endGain) throw()
  20991. {
  20992. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20993. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20994. jassert (source != 0);
  20995. if (startGain == endGain)
  20996. {
  20997. copyFrom (destChannel,
  20998. destStartSample,
  20999. source,
  21000. numSamples,
  21001. startGain);
  21002. }
  21003. else
  21004. {
  21005. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  21006. {
  21007. const float increment = (endGain - startGain) / numSamples;
  21008. float* d = channels [destChannel] + destStartSample;
  21009. while (--numSamples >= 0)
  21010. {
  21011. *d++ = startGain * *source++;
  21012. startGain += increment;
  21013. }
  21014. }
  21015. }
  21016. }
  21017. void AudioSampleBuffer::findMinMax (const int channel,
  21018. const int startSample,
  21019. int numSamples,
  21020. float& minVal,
  21021. float& maxVal) const throw()
  21022. {
  21023. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21024. jassert (startSample >= 0 && startSample + numSamples <= size);
  21025. if (numSamples <= 0)
  21026. {
  21027. minVal = 0.0f;
  21028. maxVal = 0.0f;
  21029. }
  21030. else
  21031. {
  21032. const float* d = channels [channel] + startSample;
  21033. float mn = *d++;
  21034. float mx = mn;
  21035. while (--numSamples > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  21036. {
  21037. const float samp = *d++;
  21038. if (samp > mx)
  21039. mx = samp;
  21040. if (samp < mn)
  21041. mn = samp;
  21042. }
  21043. maxVal = mx;
  21044. minVal = mn;
  21045. }
  21046. }
  21047. float AudioSampleBuffer::getMagnitude (const int channel,
  21048. const int startSample,
  21049. const int numSamples) const throw()
  21050. {
  21051. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21052. jassert (startSample >= 0 && startSample + numSamples <= size);
  21053. float mn, mx;
  21054. findMinMax (channel, startSample, numSamples, mn, mx);
  21055. return jmax (mn, -mn, mx, -mx);
  21056. }
  21057. float AudioSampleBuffer::getMagnitude (const int startSample,
  21058. const int numSamples) const throw()
  21059. {
  21060. float mag = 0.0f;
  21061. for (int i = 0; i < numChannels; ++i)
  21062. mag = jmax (mag, getMagnitude (i, startSample, numSamples));
  21063. return mag;
  21064. }
  21065. float AudioSampleBuffer::getRMSLevel (const int channel,
  21066. const int startSample,
  21067. const int numSamples) const throw()
  21068. {
  21069. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21070. jassert (startSample >= 0 && startSample + numSamples <= size);
  21071. if (numSamples <= 0 || channel < 0 || channel >= numChannels)
  21072. return 0.0f;
  21073. const float* const data = channels [channel] + startSample;
  21074. double sum = 0.0;
  21075. for (int i = 0; i < numSamples; ++i)
  21076. {
  21077. const float sample = data [i];
  21078. sum += sample * sample;
  21079. }
  21080. return (float) std::sqrt (sum / numSamples);
  21081. }
  21082. void AudioSampleBuffer::readFromAudioReader (AudioFormatReader* reader,
  21083. const int startSample,
  21084. const int numSamples,
  21085. const int readerStartSample,
  21086. const bool useLeftChan,
  21087. const bool useRightChan) throw()
  21088. {
  21089. jassert (reader != 0);
  21090. jassert (startSample >= 0 && startSample + numSamples <= size);
  21091. if (numSamples > 0)
  21092. {
  21093. int* chans[3];
  21094. if (useLeftChan == useRightChan)
  21095. {
  21096. chans[0] = (int*) getSampleData (0, startSample);
  21097. chans[1] = (reader->numChannels > 1 && getNumChannels() > 1) ? (int*) getSampleData (1, startSample) : 0;
  21098. }
  21099. else if (useLeftChan || (reader->numChannels == 1))
  21100. {
  21101. chans[0] = (int*) getSampleData (0, startSample);
  21102. chans[1] = 0;
  21103. }
  21104. else if (useRightChan)
  21105. {
  21106. chans[0] = 0;
  21107. chans[1] = (int*) getSampleData (0, startSample);
  21108. }
  21109. chans[2] = 0;
  21110. reader->read (chans, 2, readerStartSample, numSamples, true);
  21111. if (! reader->usesFloatingPointData)
  21112. {
  21113. for (int j = 0; j < 2; ++j)
  21114. {
  21115. float* const d = reinterpret_cast <float*> (chans[j]);
  21116. if (d != 0)
  21117. {
  21118. const float multiplier = 1.0f / 0x7fffffff;
  21119. for (int i = 0; i < numSamples; ++i)
  21120. d[i] = *(int*)(d + i) * multiplier;
  21121. }
  21122. }
  21123. }
  21124. if (numChannels > 1 && (chans[0] == 0 || chans[1] == 0))
  21125. {
  21126. // if this is a stereo buffer and the source was mono, dupe the first channel..
  21127. memcpy (getSampleData (1, startSample),
  21128. getSampleData (0, startSample),
  21129. sizeof (float) * numSamples);
  21130. }
  21131. }
  21132. }
  21133. void AudioSampleBuffer::writeToAudioWriter (AudioFormatWriter* writer,
  21134. const int startSample,
  21135. const int numSamples) const throw()
  21136. {
  21137. jassert (startSample >= 0 && startSample + numSamples <= size);
  21138. if (numSamples > 0)
  21139. {
  21140. int* chans [3];
  21141. if (writer->isFloatingPoint())
  21142. {
  21143. chans[0] = (int*) getSampleData (0, startSample);
  21144. if (numChannels > 1)
  21145. chans[1] = (int*) getSampleData (1, startSample);
  21146. else
  21147. chans[1] = 0;
  21148. chans[2] = 0;
  21149. writer->write ((const int**) chans, numSamples);
  21150. }
  21151. else
  21152. {
  21153. HeapBlock <int> tempBuffer (numSamples * 2);
  21154. chans[0] = tempBuffer;
  21155. if (numChannels > 1)
  21156. chans[1] = chans[0] + numSamples;
  21157. else
  21158. chans[1] = 0;
  21159. chans[2] = 0;
  21160. for (int j = 0; j < 2; ++j)
  21161. {
  21162. int* const dest = chans[j];
  21163. if (dest != 0)
  21164. {
  21165. const float* const src = channels [j] + startSample;
  21166. for (int i = 0; i < numSamples; ++i)
  21167. {
  21168. const double samp = src[i];
  21169. if (samp <= -1.0)
  21170. dest[i] = std::numeric_limits<int>::min();
  21171. else if (samp >= 1.0)
  21172. dest[i] = std::numeric_limits<int>::max();
  21173. else
  21174. dest[i] = roundToInt (std::numeric_limits<int>::max() * samp);
  21175. }
  21176. }
  21177. }
  21178. writer->write ((const int**) chans, numSamples);
  21179. }
  21180. }
  21181. }
  21182. END_JUCE_NAMESPACE
  21183. /*** End of inlined file: juce_AudioSampleBuffer.cpp ***/
  21184. /*** Start of inlined file: juce_IIRFilter.cpp ***/
  21185. BEGIN_JUCE_NAMESPACE
  21186. IIRFilter::IIRFilter()
  21187. : active (false)
  21188. {
  21189. reset();
  21190. }
  21191. IIRFilter::IIRFilter (const IIRFilter& other)
  21192. : active (other.active)
  21193. {
  21194. const ScopedLock sl (other.processLock);
  21195. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  21196. reset();
  21197. }
  21198. IIRFilter::~IIRFilter()
  21199. {
  21200. }
  21201. void IIRFilter::reset() throw()
  21202. {
  21203. const ScopedLock sl (processLock);
  21204. x1 = 0;
  21205. x2 = 0;
  21206. y1 = 0;
  21207. y2 = 0;
  21208. }
  21209. float IIRFilter::processSingleSampleRaw (const float in) throw()
  21210. {
  21211. float out = coefficients[0] * in
  21212. + coefficients[1] * x1
  21213. + coefficients[2] * x2
  21214. - coefficients[4] * y1
  21215. - coefficients[5] * y2;
  21216. #if JUCE_INTEL
  21217. if (! (out < -1.0e-8 || out > 1.0e-8))
  21218. out = 0;
  21219. #endif
  21220. x2 = x1;
  21221. x1 = in;
  21222. y2 = y1;
  21223. y1 = out;
  21224. return out;
  21225. }
  21226. void IIRFilter::processSamples (float* const samples,
  21227. const int numSamples) throw()
  21228. {
  21229. const ScopedLock sl (processLock);
  21230. if (active)
  21231. {
  21232. for (int i = 0; i < numSamples; ++i)
  21233. {
  21234. const float in = samples[i];
  21235. float out = coefficients[0] * in
  21236. + coefficients[1] * x1
  21237. + coefficients[2] * x2
  21238. - coefficients[4] * y1
  21239. - coefficients[5] * y2;
  21240. #if JUCE_INTEL
  21241. if (! (out < -1.0e-8 || out > 1.0e-8))
  21242. out = 0;
  21243. #endif
  21244. x2 = x1;
  21245. x1 = in;
  21246. y2 = y1;
  21247. y1 = out;
  21248. samples[i] = out;
  21249. }
  21250. }
  21251. }
  21252. void IIRFilter::makeLowPass (const double sampleRate,
  21253. const double frequency) throw()
  21254. {
  21255. jassert (sampleRate > 0);
  21256. const double n = 1.0 / tan (double_Pi * frequency / sampleRate);
  21257. const double nSquared = n * n;
  21258. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  21259. setCoefficients (c1,
  21260. c1 * 2.0f,
  21261. c1,
  21262. 1.0,
  21263. c1 * 2.0 * (1.0 - nSquared),
  21264. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  21265. }
  21266. void IIRFilter::makeHighPass (const double sampleRate,
  21267. const double frequency) throw()
  21268. {
  21269. const double n = tan (double_Pi * frequency / sampleRate);
  21270. const double nSquared = n * n;
  21271. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  21272. setCoefficients (c1,
  21273. c1 * -2.0f,
  21274. c1,
  21275. 1.0,
  21276. c1 * 2.0 * (nSquared - 1.0),
  21277. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  21278. }
  21279. void IIRFilter::makeLowShelf (const double sampleRate,
  21280. const double cutOffFrequency,
  21281. const double Q,
  21282. const float gainFactor) throw()
  21283. {
  21284. jassert (sampleRate > 0);
  21285. jassert (Q > 0);
  21286. const double A = jmax (0.0f, gainFactor);
  21287. const double aminus1 = A - 1.0;
  21288. const double aplus1 = A + 1.0;
  21289. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  21290. const double coso = std::cos (omega);
  21291. const double beta = std::sin (omega) * std::sqrt (A) / Q;
  21292. const double aminus1TimesCoso = aminus1 * coso;
  21293. setCoefficients (A * (aplus1 - aminus1TimesCoso + beta),
  21294. A * 2.0 * (aminus1 - aplus1 * coso),
  21295. A * (aplus1 - aminus1TimesCoso - beta),
  21296. aplus1 + aminus1TimesCoso + beta,
  21297. -2.0 * (aminus1 + aplus1 * coso),
  21298. aplus1 + aminus1TimesCoso - beta);
  21299. }
  21300. void IIRFilter::makeHighShelf (const double sampleRate,
  21301. const double cutOffFrequency,
  21302. const double Q,
  21303. const float gainFactor) throw()
  21304. {
  21305. jassert (sampleRate > 0);
  21306. jassert (Q > 0);
  21307. const double A = jmax (0.0f, gainFactor);
  21308. const double aminus1 = A - 1.0;
  21309. const double aplus1 = A + 1.0;
  21310. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  21311. const double coso = std::cos (omega);
  21312. const double beta = std::sin (omega) * std::sqrt (A) / Q;
  21313. const double aminus1TimesCoso = aminus1 * coso;
  21314. setCoefficients (A * (aplus1 + aminus1TimesCoso + beta),
  21315. A * -2.0 * (aminus1 + aplus1 * coso),
  21316. A * (aplus1 + aminus1TimesCoso - beta),
  21317. aplus1 - aminus1TimesCoso + beta,
  21318. 2.0 * (aminus1 - aplus1 * coso),
  21319. aplus1 - aminus1TimesCoso - beta);
  21320. }
  21321. void IIRFilter::makeBandPass (const double sampleRate,
  21322. const double centreFrequency,
  21323. const double Q,
  21324. const float gainFactor) throw()
  21325. {
  21326. jassert (sampleRate > 0);
  21327. jassert (Q > 0);
  21328. const double A = jmax (0.0f, gainFactor);
  21329. const double omega = (double_Pi * 2.0 * jmax (centreFrequency, 2.0)) / sampleRate;
  21330. const double alpha = 0.5 * std::sin (omega) / Q;
  21331. const double c2 = -2.0 * std::cos (omega);
  21332. const double alphaTimesA = alpha * A;
  21333. const double alphaOverA = alpha / A;
  21334. setCoefficients (1.0 + alphaTimesA,
  21335. c2,
  21336. 1.0 - alphaTimesA,
  21337. 1.0 + alphaOverA,
  21338. c2,
  21339. 1.0 - alphaOverA);
  21340. }
  21341. void IIRFilter::makeInactive() throw()
  21342. {
  21343. const ScopedLock sl (processLock);
  21344. active = false;
  21345. }
  21346. void IIRFilter::copyCoefficientsFrom (const IIRFilter& other) throw()
  21347. {
  21348. const ScopedLock sl (processLock);
  21349. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  21350. active = other.active;
  21351. }
  21352. void IIRFilter::setCoefficients (double c1,
  21353. double c2,
  21354. double c3,
  21355. double c4,
  21356. double c5,
  21357. double c6) throw()
  21358. {
  21359. const double a = 1.0 / c4;
  21360. c1 *= a;
  21361. c2 *= a;
  21362. c3 *= a;
  21363. c5 *= a;
  21364. c6 *= a;
  21365. const ScopedLock sl (processLock);
  21366. coefficients[0] = (float) c1;
  21367. coefficients[1] = (float) c2;
  21368. coefficients[2] = (float) c3;
  21369. coefficients[3] = (float) c4;
  21370. coefficients[4] = (float) c5;
  21371. coefficients[5] = (float) c6;
  21372. active = true;
  21373. }
  21374. END_JUCE_NAMESPACE
  21375. /*** End of inlined file: juce_IIRFilter.cpp ***/
  21376. /*** Start of inlined file: juce_MidiBuffer.cpp ***/
  21377. BEGIN_JUCE_NAMESPACE
  21378. MidiBuffer::MidiBuffer() throw()
  21379. : bytesUsed (0)
  21380. {
  21381. }
  21382. MidiBuffer::MidiBuffer (const MidiMessage& message) throw()
  21383. : bytesUsed (0)
  21384. {
  21385. addEvent (message, 0);
  21386. }
  21387. MidiBuffer::MidiBuffer (const MidiBuffer& other) throw()
  21388. : data (other.data),
  21389. bytesUsed (other.bytesUsed)
  21390. {
  21391. }
  21392. MidiBuffer& MidiBuffer::operator= (const MidiBuffer& other) throw()
  21393. {
  21394. bytesUsed = other.bytesUsed;
  21395. data = other.data;
  21396. return *this;
  21397. }
  21398. void MidiBuffer::swapWith (MidiBuffer& other)
  21399. {
  21400. data.swapWith (other.data);
  21401. swapVariables <int> (bytesUsed, other.bytesUsed);
  21402. }
  21403. MidiBuffer::~MidiBuffer() throw()
  21404. {
  21405. }
  21406. inline uint8* MidiBuffer::getData() const throw()
  21407. {
  21408. return static_cast <uint8*> (data.getData());
  21409. }
  21410. inline int MidiBuffer::getEventTime (const void* const d) throw()
  21411. {
  21412. return *static_cast <const int*> (d);
  21413. }
  21414. inline uint16 MidiBuffer::getEventDataSize (const void* const d) throw()
  21415. {
  21416. return *reinterpret_cast <const uint16*> (static_cast <const char*> (d) + sizeof (int));
  21417. }
  21418. inline uint16 MidiBuffer::getEventTotalSize (const void* const d) throw()
  21419. {
  21420. return getEventDataSize (d) + sizeof (int) + sizeof (uint16);
  21421. }
  21422. void MidiBuffer::clear() throw()
  21423. {
  21424. bytesUsed = 0;
  21425. }
  21426. void MidiBuffer::clear (const int startSample,
  21427. const int numSamples) throw()
  21428. {
  21429. uint8* const start = findEventAfter (getData(), startSample - 1);
  21430. uint8* const end = findEventAfter (start, startSample + numSamples - 1);
  21431. if (end > start)
  21432. {
  21433. const int bytesToMove = bytesUsed - (int) (end - getData());
  21434. if (bytesToMove > 0)
  21435. memmove (start, end, bytesToMove);
  21436. bytesUsed -= (int) (end - start);
  21437. }
  21438. }
  21439. void MidiBuffer::addEvent (const MidiMessage& m,
  21440. const int sampleNumber) throw()
  21441. {
  21442. addEvent (m.getRawData(), m.getRawDataSize(), sampleNumber);
  21443. }
  21444. static int findActualEventLength (const uint8* const data,
  21445. const int maxBytes) throw()
  21446. {
  21447. unsigned int byte = (unsigned int) *data;
  21448. int size = 0;
  21449. if (byte == 0xf0 || byte == 0xf7)
  21450. {
  21451. const uint8* d = data + 1;
  21452. while (d < data + maxBytes)
  21453. if (*d++ == 0xf7)
  21454. break;
  21455. size = (int) (d - data);
  21456. }
  21457. else if (byte == 0xff)
  21458. {
  21459. int n;
  21460. const int bytesLeft = MidiMessage::readVariableLengthVal (data + 1, n);
  21461. size = jmin (maxBytes, n + 2 + bytesLeft);
  21462. }
  21463. else if (byte >= 0x80)
  21464. {
  21465. size = jmin (maxBytes, MidiMessage::getMessageLengthFromFirstByte ((uint8) byte));
  21466. }
  21467. return size;
  21468. }
  21469. void MidiBuffer::addEvent (const uint8* const newData,
  21470. const int maxBytes,
  21471. const int sampleNumber) throw()
  21472. {
  21473. const int numBytes = findActualEventLength (newData, maxBytes);
  21474. if (numBytes > 0)
  21475. {
  21476. int spaceNeeded = bytesUsed + numBytes + sizeof (int) + sizeof (uint16);
  21477. data.ensureSize ((spaceNeeded + spaceNeeded / 2 + 8) & ~7);
  21478. uint8* d = findEventAfter (getData(), sampleNumber);
  21479. const int bytesToMove = bytesUsed - (int) (d - getData());
  21480. if (bytesToMove > 0)
  21481. memmove (d + numBytes + sizeof (int) + sizeof (uint16), d, bytesToMove);
  21482. *reinterpret_cast <int*> (d) = sampleNumber;
  21483. d += sizeof (int);
  21484. *reinterpret_cast <uint16*> (d) = (uint16) numBytes;
  21485. d += sizeof (uint16);
  21486. memcpy (d, newData, numBytes);
  21487. bytesUsed += numBytes + sizeof (int) + sizeof (uint16);
  21488. }
  21489. }
  21490. void MidiBuffer::addEvents (const MidiBuffer& otherBuffer,
  21491. const int startSample,
  21492. const int numSamples,
  21493. const int sampleDeltaToAdd) throw()
  21494. {
  21495. Iterator i (otherBuffer);
  21496. i.setNextSamplePosition (startSample);
  21497. const uint8* eventData;
  21498. int eventSize, position;
  21499. while (i.getNextEvent (eventData, eventSize, position)
  21500. && (position < startSample + numSamples || numSamples < 0))
  21501. {
  21502. addEvent (eventData, eventSize, position + sampleDeltaToAdd);
  21503. }
  21504. }
  21505. void MidiBuffer::ensureSize (size_t minimumNumBytes)
  21506. {
  21507. data.ensureSize (minimumNumBytes);
  21508. }
  21509. bool MidiBuffer::isEmpty() const throw()
  21510. {
  21511. return bytesUsed == 0;
  21512. }
  21513. int MidiBuffer::getNumEvents() const throw()
  21514. {
  21515. int n = 0;
  21516. const uint8* d = getData();
  21517. const uint8* const end = d + bytesUsed;
  21518. while (d < end)
  21519. {
  21520. d += getEventTotalSize (d);
  21521. ++n;
  21522. }
  21523. return n;
  21524. }
  21525. int MidiBuffer::getFirstEventTime() const throw()
  21526. {
  21527. return bytesUsed > 0 ? getEventTime (data.getData()) : 0;
  21528. }
  21529. int MidiBuffer::getLastEventTime() const throw()
  21530. {
  21531. if (bytesUsed == 0)
  21532. return 0;
  21533. const uint8* d = getData();
  21534. const uint8* const endData = d + bytesUsed;
  21535. for (;;)
  21536. {
  21537. const uint8* const nextOne = d + getEventTotalSize (d);
  21538. if (nextOne >= endData)
  21539. return getEventTime (d);
  21540. d = nextOne;
  21541. }
  21542. }
  21543. uint8* MidiBuffer::findEventAfter (uint8* d, const int samplePosition) const throw()
  21544. {
  21545. const uint8* const endData = getData() + bytesUsed;
  21546. while (d < endData && getEventTime (d) <= samplePosition)
  21547. d += getEventTotalSize (d);
  21548. return d;
  21549. }
  21550. MidiBuffer::Iterator::Iterator (const MidiBuffer& buffer_) throw()
  21551. : buffer (buffer_),
  21552. data (buffer_.getData())
  21553. {
  21554. }
  21555. MidiBuffer::Iterator::~Iterator() throw()
  21556. {
  21557. }
  21558. void MidiBuffer::Iterator::setNextSamplePosition (const int samplePosition) throw()
  21559. {
  21560. data = buffer.getData();
  21561. const uint8* dataEnd = data + buffer.bytesUsed;
  21562. while (data < dataEnd && getEventTime (data) < samplePosition)
  21563. data += getEventTotalSize (data);
  21564. }
  21565. bool MidiBuffer::Iterator::getNextEvent (const uint8* &midiData, int& numBytes, int& samplePosition) throw()
  21566. {
  21567. if (data >= buffer.getData() + buffer.bytesUsed)
  21568. return false;
  21569. samplePosition = getEventTime (data);
  21570. numBytes = getEventDataSize (data);
  21571. data += sizeof (int) + sizeof (uint16);
  21572. midiData = data;
  21573. data += numBytes;
  21574. return true;
  21575. }
  21576. bool MidiBuffer::Iterator::getNextEvent (MidiMessage& result, int& samplePosition) throw()
  21577. {
  21578. if (data >= buffer.getData() + buffer.bytesUsed)
  21579. return false;
  21580. samplePosition = getEventTime (data);
  21581. const int numBytes = getEventDataSize (data);
  21582. data += sizeof (int) + sizeof (uint16);
  21583. result = MidiMessage (data, numBytes, samplePosition);
  21584. data += numBytes;
  21585. return true;
  21586. }
  21587. END_JUCE_NAMESPACE
  21588. /*** End of inlined file: juce_MidiBuffer.cpp ***/
  21589. /*** Start of inlined file: juce_MidiFile.cpp ***/
  21590. BEGIN_JUCE_NAMESPACE
  21591. namespace MidiFileHelpers
  21592. {
  21593. static void writeVariableLengthInt (OutputStream& out, unsigned int v)
  21594. {
  21595. unsigned int buffer = v & 0x7F;
  21596. while ((v >>= 7) != 0)
  21597. {
  21598. buffer <<= 8;
  21599. buffer |= ((v & 0x7F) | 0x80);
  21600. }
  21601. for (;;)
  21602. {
  21603. out.writeByte ((char) buffer);
  21604. if (buffer & 0x80)
  21605. buffer >>= 8;
  21606. else
  21607. break;
  21608. }
  21609. }
  21610. static bool parseMidiHeader (const uint8* &data, short& timeFormat, short& fileType, short& numberOfTracks) throw()
  21611. {
  21612. unsigned int ch = (int) ByteOrder::bigEndianInt (data);
  21613. data += 4;
  21614. if (ch != ByteOrder::bigEndianInt ("MThd"))
  21615. {
  21616. bool ok = false;
  21617. if (ch == ByteOrder::bigEndianInt ("RIFF"))
  21618. {
  21619. for (int i = 0; i < 8; ++i)
  21620. {
  21621. ch = ByteOrder::bigEndianInt (data);
  21622. data += 4;
  21623. if (ch == ByteOrder::bigEndianInt ("MThd"))
  21624. {
  21625. ok = true;
  21626. break;
  21627. }
  21628. }
  21629. }
  21630. if (! ok)
  21631. return false;
  21632. }
  21633. unsigned int bytesRemaining = ByteOrder::bigEndianInt (data);
  21634. data += 4;
  21635. fileType = (short) ByteOrder::bigEndianShort (data);
  21636. data += 2;
  21637. numberOfTracks = (short) ByteOrder::bigEndianShort (data);
  21638. data += 2;
  21639. timeFormat = (short) ByteOrder::bigEndianShort (data);
  21640. data += 2;
  21641. bytesRemaining -= 6;
  21642. data += bytesRemaining;
  21643. return true;
  21644. }
  21645. static double convertTicksToSeconds (const double time,
  21646. const MidiMessageSequence& tempoEvents,
  21647. const int timeFormat)
  21648. {
  21649. if (timeFormat > 0)
  21650. {
  21651. int numer = 4, denom = 4;
  21652. double tempoTime = 0.0, correctedTempoTime = 0.0;
  21653. const double tickLen = 1.0 / (timeFormat & 0x7fff);
  21654. double secsPerTick = 0.5 * tickLen;
  21655. const int numEvents = tempoEvents.getNumEvents();
  21656. for (int i = 0; i < numEvents; ++i)
  21657. {
  21658. const MidiMessage& m = tempoEvents.getEventPointer(i)->message;
  21659. if (time <= m.getTimeStamp())
  21660. break;
  21661. if (timeFormat > 0)
  21662. {
  21663. correctedTempoTime = correctedTempoTime
  21664. + (m.getTimeStamp() - tempoTime) * secsPerTick;
  21665. }
  21666. else
  21667. {
  21668. correctedTempoTime = tickLen * m.getTimeStamp() / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  21669. }
  21670. tempoTime = m.getTimeStamp();
  21671. if (m.isTempoMetaEvent())
  21672. secsPerTick = tickLen * m.getTempoSecondsPerQuarterNote();
  21673. else if (m.isTimeSignatureMetaEvent())
  21674. m.getTimeSignatureInfo (numer, denom);
  21675. while (i + 1 < numEvents)
  21676. {
  21677. const MidiMessage& m2 = tempoEvents.getEventPointer(i + 1)->message;
  21678. if (m2.getTimeStamp() == tempoTime)
  21679. {
  21680. ++i;
  21681. if (m2.isTempoMetaEvent())
  21682. secsPerTick = tickLen * m2.getTempoSecondsPerQuarterNote();
  21683. else if (m2.isTimeSignatureMetaEvent())
  21684. m2.getTimeSignatureInfo (numer, denom);
  21685. }
  21686. else
  21687. {
  21688. break;
  21689. }
  21690. }
  21691. }
  21692. return correctedTempoTime + (time - tempoTime) * secsPerTick;
  21693. }
  21694. else
  21695. {
  21696. return time / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  21697. }
  21698. }
  21699. }
  21700. MidiFile::MidiFile()
  21701. : timeFormat ((short) (unsigned short) 0xe728)
  21702. {
  21703. }
  21704. MidiFile::~MidiFile()
  21705. {
  21706. clear();
  21707. }
  21708. void MidiFile::clear()
  21709. {
  21710. tracks.clear();
  21711. }
  21712. int MidiFile::getNumTracks() const throw()
  21713. {
  21714. return tracks.size();
  21715. }
  21716. const MidiMessageSequence* MidiFile::getTrack (const int index) const throw()
  21717. {
  21718. return tracks [index];
  21719. }
  21720. void MidiFile::addTrack (const MidiMessageSequence& trackSequence)
  21721. {
  21722. tracks.add (new MidiMessageSequence (trackSequence));
  21723. }
  21724. short MidiFile::getTimeFormat() const throw()
  21725. {
  21726. return timeFormat;
  21727. }
  21728. void MidiFile::setTicksPerQuarterNote (const int ticks) throw()
  21729. {
  21730. timeFormat = (short) ticks;
  21731. }
  21732. void MidiFile::setSmpteTimeFormat (const int framesPerSecond,
  21733. const int subframeResolution) throw()
  21734. {
  21735. timeFormat = (short) (((-framesPerSecond) << 8) | subframeResolution);
  21736. }
  21737. void MidiFile::findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const
  21738. {
  21739. for (int i = tracks.size(); --i >= 0;)
  21740. {
  21741. const int numEvents = tracks.getUnchecked(i)->getNumEvents();
  21742. for (int j = 0; j < numEvents; ++j)
  21743. {
  21744. const MidiMessage& m = tracks.getUnchecked(i)->getEventPointer (j)->message;
  21745. if (m.isTempoMetaEvent())
  21746. tempoChangeEvents.addEvent (m);
  21747. }
  21748. }
  21749. }
  21750. void MidiFile::findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const
  21751. {
  21752. for (int i = tracks.size(); --i >= 0;)
  21753. {
  21754. const int numEvents = tracks.getUnchecked(i)->getNumEvents();
  21755. for (int j = 0; j < numEvents; ++j)
  21756. {
  21757. const MidiMessage& m = tracks.getUnchecked(i)->getEventPointer (j)->message;
  21758. if (m.isTimeSignatureMetaEvent())
  21759. timeSigEvents.addEvent (m);
  21760. }
  21761. }
  21762. }
  21763. double MidiFile::getLastTimestamp() const
  21764. {
  21765. double t = 0.0;
  21766. for (int i = tracks.size(); --i >= 0;)
  21767. t = jmax (t, tracks.getUnchecked(i)->getEndTime());
  21768. return t;
  21769. }
  21770. bool MidiFile::readFrom (InputStream& sourceStream)
  21771. {
  21772. clear();
  21773. MemoryBlock data;
  21774. const int maxSensibleMidiFileSize = 2 * 1024 * 1024;
  21775. // (put a sanity-check on the file size, as midi files are generally small)
  21776. if (sourceStream.readIntoMemoryBlock (data, maxSensibleMidiFileSize))
  21777. {
  21778. size_t size = data.getSize();
  21779. const uint8* d = static_cast <const uint8*> (data.getData());
  21780. short fileType, expectedTracks;
  21781. if (size > 16 && MidiFileHelpers::parseMidiHeader (d, timeFormat, fileType, expectedTracks))
  21782. {
  21783. size -= (int) (d - static_cast <const uint8*> (data.getData()));
  21784. int track = 0;
  21785. while (size > 0 && track < expectedTracks)
  21786. {
  21787. const int chunkType = (int) ByteOrder::bigEndianInt (d);
  21788. d += 4;
  21789. const int chunkSize = (int) ByteOrder::bigEndianInt (d);
  21790. d += 4;
  21791. if (chunkSize <= 0)
  21792. break;
  21793. if (size < 0)
  21794. return false;
  21795. if (chunkType == (int) ByteOrder::bigEndianInt ("MTrk"))
  21796. {
  21797. readNextTrack (d, chunkSize);
  21798. }
  21799. size -= chunkSize + 8;
  21800. d += chunkSize;
  21801. ++track;
  21802. }
  21803. return true;
  21804. }
  21805. }
  21806. return false;
  21807. }
  21808. // a comparator that puts all the note-offs before note-ons that have the same time
  21809. int MidiFile::compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  21810. const MidiMessageSequence::MidiEventHolder* const second)
  21811. {
  21812. const double diff = (first->message.getTimeStamp() - second->message.getTimeStamp());
  21813. if (diff == 0)
  21814. {
  21815. if (first->message.isNoteOff() && second->message.isNoteOn())
  21816. return -1;
  21817. else if (first->message.isNoteOn() && second->message.isNoteOff())
  21818. return 1;
  21819. else
  21820. return 0;
  21821. }
  21822. else
  21823. {
  21824. return (diff > 0) ? 1 : -1;
  21825. }
  21826. }
  21827. void MidiFile::readNextTrack (const uint8* data, int size)
  21828. {
  21829. double time = 0;
  21830. char lastStatusByte = 0;
  21831. MidiMessageSequence result;
  21832. while (size > 0)
  21833. {
  21834. int bytesUsed;
  21835. const int delay = MidiMessage::readVariableLengthVal (data, bytesUsed);
  21836. data += bytesUsed;
  21837. size -= bytesUsed;
  21838. time += delay;
  21839. int messSize = 0;
  21840. const MidiMessage mm (data, size, messSize, lastStatusByte, time);
  21841. if (messSize <= 0)
  21842. break;
  21843. size -= messSize;
  21844. data += messSize;
  21845. result.addEvent (mm);
  21846. const char firstByte = *(mm.getRawData());
  21847. if ((firstByte & 0xf0) != 0xf0)
  21848. lastStatusByte = firstByte;
  21849. }
  21850. // use a sort that puts all the note-offs before note-ons that have the same time
  21851. result.list.sort (*this, true);
  21852. result.updateMatchedPairs();
  21853. addTrack (result);
  21854. }
  21855. void MidiFile::convertTimestampTicksToSeconds()
  21856. {
  21857. MidiMessageSequence tempoEvents;
  21858. findAllTempoEvents (tempoEvents);
  21859. findAllTimeSigEvents (tempoEvents);
  21860. for (int i = 0; i < tracks.size(); ++i)
  21861. {
  21862. MidiMessageSequence& ms = *tracks.getUnchecked(i);
  21863. for (int j = ms.getNumEvents(); --j >= 0;)
  21864. {
  21865. MidiMessage& m = ms.getEventPointer(j)->message;
  21866. m.setTimeStamp (MidiFileHelpers::convertTicksToSeconds (m.getTimeStamp(),
  21867. tempoEvents,
  21868. timeFormat));
  21869. }
  21870. }
  21871. }
  21872. bool MidiFile::writeTo (OutputStream& out)
  21873. {
  21874. out.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MThd"));
  21875. out.writeIntBigEndian (6);
  21876. out.writeShortBigEndian (1); // type
  21877. out.writeShortBigEndian ((short) tracks.size());
  21878. out.writeShortBigEndian (timeFormat);
  21879. for (int i = 0; i < tracks.size(); ++i)
  21880. writeTrack (out, i);
  21881. out.flush();
  21882. return true;
  21883. }
  21884. void MidiFile::writeTrack (OutputStream& mainOut,
  21885. const int trackNum)
  21886. {
  21887. MemoryOutputStream out;
  21888. const MidiMessageSequence& ms = *tracks[trackNum];
  21889. int lastTick = 0;
  21890. char lastStatusByte = 0;
  21891. for (int i = 0; i < ms.getNumEvents(); ++i)
  21892. {
  21893. const MidiMessage& mm = ms.getEventPointer(i)->message;
  21894. const int tick = roundToInt (mm.getTimeStamp());
  21895. const int delta = jmax (0, tick - lastTick);
  21896. MidiFileHelpers::writeVariableLengthInt (out, delta);
  21897. lastTick = tick;
  21898. const char statusByte = *(mm.getRawData());
  21899. if ((statusByte == lastStatusByte)
  21900. && ((statusByte & 0xf0) != 0xf0)
  21901. && i > 0
  21902. && mm.getRawDataSize() > 1)
  21903. {
  21904. out.write (mm.getRawData() + 1, mm.getRawDataSize() - 1);
  21905. }
  21906. else
  21907. {
  21908. out.write (mm.getRawData(), mm.getRawDataSize());
  21909. }
  21910. lastStatusByte = statusByte;
  21911. }
  21912. out.writeByte (0);
  21913. const MidiMessage m (MidiMessage::endOfTrack());
  21914. out.write (m.getRawData(),
  21915. m.getRawDataSize());
  21916. mainOut.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MTrk"));
  21917. mainOut.writeIntBigEndian ((int) out.getDataSize());
  21918. mainOut.write (out.getData(), (int) out.getDataSize());
  21919. }
  21920. END_JUCE_NAMESPACE
  21921. /*** End of inlined file: juce_MidiFile.cpp ***/
  21922. /*** Start of inlined file: juce_MidiKeyboardState.cpp ***/
  21923. BEGIN_JUCE_NAMESPACE
  21924. MidiKeyboardState::MidiKeyboardState()
  21925. {
  21926. zerostruct (noteStates);
  21927. }
  21928. MidiKeyboardState::~MidiKeyboardState()
  21929. {
  21930. }
  21931. void MidiKeyboardState::reset()
  21932. {
  21933. const ScopedLock sl (lock);
  21934. zerostruct (noteStates);
  21935. eventsToAdd.clear();
  21936. }
  21937. bool MidiKeyboardState::isNoteOn (const int midiChannel, const int n) const throw()
  21938. {
  21939. jassert (midiChannel >= 0 && midiChannel <= 16);
  21940. return ((unsigned int) n) < 128
  21941. && (noteStates[n] & (1 << (midiChannel - 1))) != 0;
  21942. }
  21943. bool MidiKeyboardState::isNoteOnForChannels (const int midiChannelMask, const int n) const throw()
  21944. {
  21945. return ((unsigned int) n) < 128
  21946. && (noteStates[n] & midiChannelMask) != 0;
  21947. }
  21948. void MidiKeyboardState::noteOn (const int midiChannel, const int midiNoteNumber, const float velocity)
  21949. {
  21950. jassert (midiChannel >= 0 && midiChannel <= 16);
  21951. jassert (((unsigned int) midiNoteNumber) < 128);
  21952. const ScopedLock sl (lock);
  21953. if (((unsigned int) midiNoteNumber) < 128)
  21954. {
  21955. const int timeNow = (int) Time::getMillisecondCounter();
  21956. eventsToAdd.addEvent (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity), timeNow);
  21957. eventsToAdd.clear (0, timeNow - 500);
  21958. noteOnInternal (midiChannel, midiNoteNumber, velocity);
  21959. }
  21960. }
  21961. void MidiKeyboardState::noteOnInternal (const int midiChannel, const int midiNoteNumber, const float velocity)
  21962. {
  21963. if (((unsigned int) midiNoteNumber) < 128)
  21964. {
  21965. noteStates [midiNoteNumber] |= (1 << (midiChannel - 1));
  21966. for (int i = listeners.size(); --i >= 0;)
  21967. listeners.getUnchecked(i)->handleNoteOn (this, midiChannel, midiNoteNumber, velocity);
  21968. }
  21969. }
  21970. void MidiKeyboardState::noteOff (const int midiChannel, const int midiNoteNumber)
  21971. {
  21972. const ScopedLock sl (lock);
  21973. if (isNoteOn (midiChannel, midiNoteNumber))
  21974. {
  21975. const int timeNow = (int) Time::getMillisecondCounter();
  21976. eventsToAdd.addEvent (MidiMessage::noteOff (midiChannel, midiNoteNumber), timeNow);
  21977. eventsToAdd.clear (0, timeNow - 500);
  21978. noteOffInternal (midiChannel, midiNoteNumber);
  21979. }
  21980. }
  21981. void MidiKeyboardState::noteOffInternal (const int midiChannel, const int midiNoteNumber)
  21982. {
  21983. if (isNoteOn (midiChannel, midiNoteNumber))
  21984. {
  21985. noteStates [midiNoteNumber] &= ~(1 << (midiChannel - 1));
  21986. for (int i = listeners.size(); --i >= 0;)
  21987. listeners.getUnchecked(i)->handleNoteOff (this, midiChannel, midiNoteNumber);
  21988. }
  21989. }
  21990. void MidiKeyboardState::allNotesOff (const int midiChannel)
  21991. {
  21992. const ScopedLock sl (lock);
  21993. if (midiChannel <= 0)
  21994. {
  21995. for (int i = 1; i <= 16; ++i)
  21996. allNotesOff (i);
  21997. }
  21998. else
  21999. {
  22000. for (int i = 0; i < 128; ++i)
  22001. noteOff (midiChannel, i);
  22002. }
  22003. }
  22004. void MidiKeyboardState::processNextMidiEvent (const MidiMessage& message)
  22005. {
  22006. if (message.isNoteOn())
  22007. {
  22008. noteOnInternal (message.getChannel(), message.getNoteNumber(), message.getFloatVelocity());
  22009. }
  22010. else if (message.isNoteOff())
  22011. {
  22012. noteOffInternal (message.getChannel(), message.getNoteNumber());
  22013. }
  22014. else if (message.isAllNotesOff())
  22015. {
  22016. for (int i = 0; i < 128; ++i)
  22017. noteOffInternal (message.getChannel(), i);
  22018. }
  22019. }
  22020. void MidiKeyboardState::processNextMidiBuffer (MidiBuffer& buffer,
  22021. const int startSample,
  22022. const int numSamples,
  22023. const bool injectIndirectEvents)
  22024. {
  22025. MidiBuffer::Iterator i (buffer);
  22026. MidiMessage message (0xf4, 0.0);
  22027. int time;
  22028. const ScopedLock sl (lock);
  22029. while (i.getNextEvent (message, time))
  22030. processNextMidiEvent (message);
  22031. if (injectIndirectEvents)
  22032. {
  22033. MidiBuffer::Iterator i2 (eventsToAdd);
  22034. const int firstEventToAdd = eventsToAdd.getFirstEventTime();
  22035. const double scaleFactor = numSamples / (double) (eventsToAdd.getLastEventTime() + 1 - firstEventToAdd);
  22036. while (i2.getNextEvent (message, time))
  22037. {
  22038. const int pos = jlimit (0, numSamples - 1, roundToInt ((time - firstEventToAdd) * scaleFactor));
  22039. buffer.addEvent (message, startSample + pos);
  22040. }
  22041. }
  22042. eventsToAdd.clear();
  22043. }
  22044. void MidiKeyboardState::addListener (MidiKeyboardStateListener* const listener) throw()
  22045. {
  22046. const ScopedLock sl (lock);
  22047. listeners.addIfNotAlreadyThere (listener);
  22048. }
  22049. void MidiKeyboardState::removeListener (MidiKeyboardStateListener* const listener) throw()
  22050. {
  22051. const ScopedLock sl (lock);
  22052. listeners.removeValue (listener);
  22053. }
  22054. END_JUCE_NAMESPACE
  22055. /*** End of inlined file: juce_MidiKeyboardState.cpp ***/
  22056. /*** Start of inlined file: juce_MidiMessage.cpp ***/
  22057. BEGIN_JUCE_NAMESPACE
  22058. int MidiMessage::readVariableLengthVal (const uint8* data,
  22059. int& numBytesUsed) throw()
  22060. {
  22061. numBytesUsed = 0;
  22062. int v = 0;
  22063. int i;
  22064. do
  22065. {
  22066. i = (int) *data++;
  22067. if (++numBytesUsed > 6)
  22068. break;
  22069. v = (v << 7) + (i & 0x7f);
  22070. } while (i & 0x80);
  22071. return v;
  22072. }
  22073. int MidiMessage::getMessageLengthFromFirstByte (const uint8 firstByte) throw()
  22074. {
  22075. // this method only works for valid starting bytes of a short midi message
  22076. jassert (firstByte >= 0x80
  22077. && firstByte != 0xf0
  22078. && firstByte != 0xf7);
  22079. static const char messageLengths[] =
  22080. {
  22081. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22082. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22083. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22084. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22085. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  22086. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  22087. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22088. 1, 2, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
  22089. };
  22090. return messageLengths [firstByte & 0x7f];
  22091. }
  22092. MidiMessage::MidiMessage (const void* const d, const int dataSize, const double t)
  22093. : timeStamp (t),
  22094. size (dataSize)
  22095. {
  22096. jassert (dataSize > 0);
  22097. if (dataSize <= 4)
  22098. data = static_cast<uint8*> (preallocatedData.asBytes);
  22099. else
  22100. data = new uint8 [dataSize];
  22101. memcpy (data, d, dataSize);
  22102. // check that the length matches the data..
  22103. jassert (size > 3 || data[0] >= 0xf0 || getMessageLengthFromFirstByte (data[0]) == size);
  22104. }
  22105. MidiMessage::MidiMessage (const int byte1, const double t) throw()
  22106. : timeStamp (t),
  22107. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22108. size (1)
  22109. {
  22110. data[0] = (uint8) byte1;
  22111. // check that the length matches the data..
  22112. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 1);
  22113. }
  22114. MidiMessage::MidiMessage (const int byte1, const int byte2, const double t) throw()
  22115. : timeStamp (t),
  22116. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22117. size (2)
  22118. {
  22119. data[0] = (uint8) byte1;
  22120. data[1] = (uint8) byte2;
  22121. // check that the length matches the data..
  22122. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 2);
  22123. }
  22124. MidiMessage::MidiMessage (const int byte1, const int byte2, const int byte3, const double t) throw()
  22125. : timeStamp (t),
  22126. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22127. size (3)
  22128. {
  22129. data[0] = (uint8) byte1;
  22130. data[1] = (uint8) byte2;
  22131. data[2] = (uint8) byte3;
  22132. // check that the length matches the data..
  22133. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 3);
  22134. }
  22135. MidiMessage::MidiMessage (const MidiMessage& other)
  22136. : timeStamp (other.timeStamp),
  22137. size (other.size)
  22138. {
  22139. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  22140. {
  22141. data = new uint8 [size];
  22142. memcpy (data, other.data, size);
  22143. }
  22144. else
  22145. {
  22146. data = static_cast<uint8*> (preallocatedData.asBytes);
  22147. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  22148. }
  22149. }
  22150. MidiMessage::MidiMessage (const MidiMessage& other, const double newTimeStamp)
  22151. : timeStamp (newTimeStamp),
  22152. size (other.size)
  22153. {
  22154. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  22155. {
  22156. data = new uint8 [size];
  22157. memcpy (data, other.data, size);
  22158. }
  22159. else
  22160. {
  22161. data = static_cast<uint8*> (preallocatedData.asBytes);
  22162. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  22163. }
  22164. }
  22165. MidiMessage::MidiMessage (const void* src_, int sz, int& numBytesUsed, const uint8 lastStatusByte, double t)
  22166. : timeStamp (t),
  22167. data (static_cast<uint8*> (preallocatedData.asBytes))
  22168. {
  22169. const uint8* src = static_cast <const uint8*> (src_);
  22170. unsigned int byte = (unsigned int) *src;
  22171. if (byte < 0x80)
  22172. {
  22173. byte = (unsigned int) (uint8) lastStatusByte;
  22174. numBytesUsed = -1;
  22175. }
  22176. else
  22177. {
  22178. numBytesUsed = 0;
  22179. --sz;
  22180. ++src;
  22181. }
  22182. if (byte >= 0x80)
  22183. {
  22184. if (byte == 0xf0)
  22185. {
  22186. const uint8* d = src;
  22187. while (d < src + sz)
  22188. {
  22189. if (*d >= 0x80) // stop if we hit a status byte, and don't include it in this message
  22190. {
  22191. if (*d == 0xf7) // include an 0xf7 if we hit one
  22192. ++d;
  22193. break;
  22194. }
  22195. ++d;
  22196. }
  22197. size = 1 + (int) (d - src);
  22198. data = new uint8 [size];
  22199. *data = (uint8) byte;
  22200. memcpy (data + 1, src, size - 1);
  22201. }
  22202. else if (byte == 0xff)
  22203. {
  22204. int n;
  22205. const int bytesLeft = readVariableLengthVal (src + 1, n);
  22206. size = jmin (sz + 1, n + 2 + bytesLeft);
  22207. data = new uint8 [size];
  22208. *data = (uint8) byte;
  22209. memcpy (data + 1, src, size - 1);
  22210. }
  22211. else
  22212. {
  22213. preallocatedData.asInt32 = 0;
  22214. size = getMessageLengthFromFirstByte ((uint8) byte);
  22215. data[0] = (uint8) byte;
  22216. if (size > 1)
  22217. {
  22218. data[1] = src[0];
  22219. if (size > 2)
  22220. data[2] = src[1];
  22221. }
  22222. }
  22223. numBytesUsed += size;
  22224. }
  22225. else
  22226. {
  22227. preallocatedData.asInt32 = 0;
  22228. size = 0;
  22229. }
  22230. }
  22231. MidiMessage& MidiMessage::operator= (const MidiMessage& other)
  22232. {
  22233. if (this != &other)
  22234. {
  22235. timeStamp = other.timeStamp;
  22236. size = other.size;
  22237. if (data != static_cast <const uint8*> (preallocatedData.asBytes))
  22238. delete[] data;
  22239. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  22240. {
  22241. data = new uint8 [size];
  22242. memcpy (data, other.data, size);
  22243. }
  22244. else
  22245. {
  22246. data = static_cast<uint8*> (preallocatedData.asBytes);
  22247. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  22248. }
  22249. }
  22250. return *this;
  22251. }
  22252. MidiMessage::~MidiMessage()
  22253. {
  22254. if (data != static_cast <const uint8*> (preallocatedData.asBytes))
  22255. delete[] data;
  22256. }
  22257. int MidiMessage::getChannel() const throw()
  22258. {
  22259. if ((data[0] & 0xf0) != 0xf0)
  22260. return (data[0] & 0xf) + 1;
  22261. else
  22262. return 0;
  22263. }
  22264. bool MidiMessage::isForChannel (const int channel) const throw()
  22265. {
  22266. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  22267. return ((data[0] & 0xf) == channel - 1)
  22268. && ((data[0] & 0xf0) != 0xf0);
  22269. }
  22270. void MidiMessage::setChannel (const int channel) throw()
  22271. {
  22272. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  22273. if ((data[0] & 0xf0) != (uint8) 0xf0)
  22274. data[0] = (uint8) ((data[0] & (uint8)0xf0)
  22275. | (uint8)(channel - 1));
  22276. }
  22277. bool MidiMessage::isNoteOn (const bool returnTrueForVelocity0) const throw()
  22278. {
  22279. return ((data[0] & 0xf0) == 0x90)
  22280. && (returnTrueForVelocity0 || data[2] != 0);
  22281. }
  22282. bool MidiMessage::isNoteOff (const bool returnTrueForNoteOnVelocity0) const throw()
  22283. {
  22284. return ((data[0] & 0xf0) == 0x80)
  22285. || (returnTrueForNoteOnVelocity0 && (data[2] == 0) && ((data[0] & 0xf0) == 0x90));
  22286. }
  22287. bool MidiMessage::isNoteOnOrOff() const throw()
  22288. {
  22289. const int d = data[0] & 0xf0;
  22290. return (d == 0x90) || (d == 0x80);
  22291. }
  22292. int MidiMessage::getNoteNumber() const throw()
  22293. {
  22294. return data[1];
  22295. }
  22296. void MidiMessage::setNoteNumber (const int newNoteNumber) throw()
  22297. {
  22298. if (isNoteOnOrOff())
  22299. data[1] = (uint8) jlimit (0, 127, newNoteNumber);
  22300. }
  22301. uint8 MidiMessage::getVelocity() const throw()
  22302. {
  22303. if (isNoteOnOrOff())
  22304. return data[2];
  22305. else
  22306. return 0;
  22307. }
  22308. float MidiMessage::getFloatVelocity() const throw()
  22309. {
  22310. return getVelocity() * (1.0f / 127.0f);
  22311. }
  22312. void MidiMessage::setVelocity (const float newVelocity) throw()
  22313. {
  22314. if (isNoteOnOrOff())
  22315. data[2] = (uint8) jlimit (0, 0x7f, roundToInt (newVelocity * 127.0f));
  22316. }
  22317. void MidiMessage::multiplyVelocity (const float scaleFactor) throw()
  22318. {
  22319. if (isNoteOnOrOff())
  22320. data[2] = (uint8) jlimit (0, 0x7f, roundToInt (scaleFactor * data[2]));
  22321. }
  22322. bool MidiMessage::isAftertouch() const throw()
  22323. {
  22324. return (data[0] & 0xf0) == 0xa0;
  22325. }
  22326. int MidiMessage::getAfterTouchValue() const throw()
  22327. {
  22328. return data[2];
  22329. }
  22330. const MidiMessage MidiMessage::aftertouchChange (const int channel,
  22331. const int noteNum,
  22332. const int aftertouchValue) throw()
  22333. {
  22334. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  22335. jassert (((unsigned int) noteNum) <= 127);
  22336. jassert (((unsigned int) aftertouchValue) <= 127);
  22337. return MidiMessage (0xa0 | jlimit (0, 15, channel - 1),
  22338. noteNum & 0x7f,
  22339. aftertouchValue & 0x7f);
  22340. }
  22341. bool MidiMessage::isChannelPressure() const throw()
  22342. {
  22343. return (data[0] & 0xf0) == 0xd0;
  22344. }
  22345. int MidiMessage::getChannelPressureValue() const throw()
  22346. {
  22347. jassert (isChannelPressure());
  22348. return data[1];
  22349. }
  22350. const MidiMessage MidiMessage::channelPressureChange (const int channel,
  22351. const int pressure) throw()
  22352. {
  22353. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  22354. jassert (((unsigned int) pressure) <= 127);
  22355. return MidiMessage (0xd0 | jlimit (0, 15, channel - 1),
  22356. pressure & 0x7f);
  22357. }
  22358. bool MidiMessage::isProgramChange() const throw()
  22359. {
  22360. return (data[0] & 0xf0) == 0xc0;
  22361. }
  22362. int MidiMessage::getProgramChangeNumber() const throw()
  22363. {
  22364. return data[1];
  22365. }
  22366. const MidiMessage MidiMessage::programChange (const int channel,
  22367. const int programNumber) throw()
  22368. {
  22369. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  22370. return MidiMessage (0xc0 | jlimit (0, 15, channel - 1),
  22371. programNumber & 0x7f);
  22372. }
  22373. bool MidiMessage::isPitchWheel() const throw()
  22374. {
  22375. return (data[0] & 0xf0) == 0xe0;
  22376. }
  22377. int MidiMessage::getPitchWheelValue() const throw()
  22378. {
  22379. return data[1] | (data[2] << 7);
  22380. }
  22381. const MidiMessage MidiMessage::pitchWheel (const int channel,
  22382. const int position) throw()
  22383. {
  22384. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  22385. jassert (((unsigned int) position) <= 0x3fff);
  22386. return MidiMessage (0xe0 | jlimit (0, 15, channel - 1),
  22387. position & 127,
  22388. (position >> 7) & 127);
  22389. }
  22390. bool MidiMessage::isController() const throw()
  22391. {
  22392. return (data[0] & 0xf0) == 0xb0;
  22393. }
  22394. int MidiMessage::getControllerNumber() const throw()
  22395. {
  22396. jassert (isController());
  22397. return data[1];
  22398. }
  22399. int MidiMessage::getControllerValue() const throw()
  22400. {
  22401. jassert (isController());
  22402. return data[2];
  22403. }
  22404. const MidiMessage MidiMessage::controllerEvent (const int channel,
  22405. const int controllerType,
  22406. const int value) throw()
  22407. {
  22408. // the channel must be between 1 and 16 inclusive
  22409. jassert (channel > 0 && channel <= 16);
  22410. return MidiMessage (0xb0 | jlimit (0, 15, channel - 1),
  22411. controllerType & 127,
  22412. value & 127);
  22413. }
  22414. const MidiMessage MidiMessage::noteOn (const int channel,
  22415. const int noteNumber,
  22416. const float velocity) throw()
  22417. {
  22418. return noteOn (channel, noteNumber, (uint8)(velocity * 127.0f));
  22419. }
  22420. const MidiMessage MidiMessage::noteOn (const int channel,
  22421. const int noteNumber,
  22422. const uint8 velocity) throw()
  22423. {
  22424. jassert (channel > 0 && channel <= 16);
  22425. jassert (((unsigned int) noteNumber) <= 127);
  22426. return MidiMessage (0x90 | jlimit (0, 15, channel - 1),
  22427. noteNumber & 127,
  22428. jlimit (0, 127, roundToInt (velocity)));
  22429. }
  22430. const MidiMessage MidiMessage::noteOff (const int channel,
  22431. const int noteNumber) throw()
  22432. {
  22433. jassert (channel > 0 && channel <= 16);
  22434. jassert (((unsigned int) noteNumber) <= 127);
  22435. return MidiMessage (0x80 | jlimit (0, 15, channel - 1), noteNumber & 127, 0);
  22436. }
  22437. const MidiMessage MidiMessage::allNotesOff (const int channel) throw()
  22438. {
  22439. jassert (channel > 0 && channel <= 16);
  22440. return controllerEvent (channel, 123, 0);
  22441. }
  22442. bool MidiMessage::isAllNotesOff() const throw()
  22443. {
  22444. return (data[0] & 0xf0) == 0xb0
  22445. && data[1] == 123;
  22446. }
  22447. const MidiMessage MidiMessage::allSoundOff (const int channel) throw()
  22448. {
  22449. return controllerEvent (channel, 120, 0);
  22450. }
  22451. bool MidiMessage::isAllSoundOff() const throw()
  22452. {
  22453. return (data[0] & 0xf0) == 0xb0
  22454. && data[1] == 120;
  22455. }
  22456. const MidiMessage MidiMessage::allControllersOff (const int channel) throw()
  22457. {
  22458. return controllerEvent (channel, 121, 0);
  22459. }
  22460. const MidiMessage MidiMessage::masterVolume (const float volume)
  22461. {
  22462. const int vol = jlimit (0, 0x3fff, roundToInt (volume * 0x4000));
  22463. uint8 buf[8];
  22464. buf[0] = 0xf0;
  22465. buf[1] = 0x7f;
  22466. buf[2] = 0x7f;
  22467. buf[3] = 0x04;
  22468. buf[4] = 0x01;
  22469. buf[5] = (uint8) (vol & 0x7f);
  22470. buf[6] = (uint8) (vol >> 7);
  22471. buf[7] = 0xf7;
  22472. return MidiMessage (buf, 8);
  22473. }
  22474. bool MidiMessage::isSysEx() const throw()
  22475. {
  22476. return *data == 0xf0;
  22477. }
  22478. const MidiMessage MidiMessage::createSysExMessage (const uint8* sysexData, const int dataSize)
  22479. {
  22480. MemoryBlock mm (dataSize + 2);
  22481. uint8* const m = static_cast <uint8*> (mm.getData());
  22482. m[0] = 0xf0;
  22483. memcpy (m + 1, sysexData, dataSize);
  22484. m[dataSize + 1] = 0xf7;
  22485. return MidiMessage (m, dataSize + 2);
  22486. }
  22487. const uint8* MidiMessage::getSysExData() const throw()
  22488. {
  22489. return (isSysEx()) ? getRawData() + 1 : 0;
  22490. }
  22491. int MidiMessage::getSysExDataSize() const throw()
  22492. {
  22493. return (isSysEx()) ? size - 2 : 0;
  22494. }
  22495. bool MidiMessage::isMetaEvent() const throw()
  22496. {
  22497. return *data == 0xff;
  22498. }
  22499. bool MidiMessage::isActiveSense() const throw()
  22500. {
  22501. return *data == 0xfe;
  22502. }
  22503. int MidiMessage::getMetaEventType() const throw()
  22504. {
  22505. if (*data != 0xff)
  22506. return -1;
  22507. else
  22508. return data[1];
  22509. }
  22510. int MidiMessage::getMetaEventLength() const throw()
  22511. {
  22512. if (*data == 0xff)
  22513. {
  22514. int n;
  22515. return jmin (size - 2, readVariableLengthVal (data + 2, n));
  22516. }
  22517. return 0;
  22518. }
  22519. const uint8* MidiMessage::getMetaEventData() const throw()
  22520. {
  22521. int n;
  22522. const uint8* d = data + 2;
  22523. readVariableLengthVal (d, n);
  22524. return d + n;
  22525. }
  22526. bool MidiMessage::isTrackMetaEvent() const throw()
  22527. {
  22528. return getMetaEventType() == 0;
  22529. }
  22530. bool MidiMessage::isEndOfTrackMetaEvent() const throw()
  22531. {
  22532. return getMetaEventType() == 47;
  22533. }
  22534. bool MidiMessage::isTextMetaEvent() const throw()
  22535. {
  22536. const int t = getMetaEventType();
  22537. return t > 0 && t < 16;
  22538. }
  22539. const String MidiMessage::getTextFromTextMetaEvent() const
  22540. {
  22541. return String (reinterpret_cast <const char*> (getMetaEventData()), getMetaEventLength());
  22542. }
  22543. bool MidiMessage::isTrackNameEvent() const throw()
  22544. {
  22545. return (data[1] == 3)
  22546. && (*data == 0xff);
  22547. }
  22548. bool MidiMessage::isTempoMetaEvent() const throw()
  22549. {
  22550. return (data[1] == 81)
  22551. && (*data == 0xff);
  22552. }
  22553. bool MidiMessage::isMidiChannelMetaEvent() const throw()
  22554. {
  22555. return (data[1] == 0x20)
  22556. && (*data == 0xff)
  22557. && (data[2] == 1);
  22558. }
  22559. int MidiMessage::getMidiChannelMetaEventChannel() const throw()
  22560. {
  22561. return data[3] + 1;
  22562. }
  22563. double MidiMessage::getTempoSecondsPerQuarterNote() const throw()
  22564. {
  22565. if (! isTempoMetaEvent())
  22566. return 0.0;
  22567. const uint8* const d = getMetaEventData();
  22568. return (((unsigned int) d[0] << 16)
  22569. | ((unsigned int) d[1] << 8)
  22570. | d[2])
  22571. / 1000000.0;
  22572. }
  22573. double MidiMessage::getTempoMetaEventTickLength (const short timeFormat) const throw()
  22574. {
  22575. if (timeFormat > 0)
  22576. {
  22577. if (! isTempoMetaEvent())
  22578. return 0.5 / timeFormat;
  22579. return getTempoSecondsPerQuarterNote() / timeFormat;
  22580. }
  22581. else
  22582. {
  22583. const int frameCode = (-timeFormat) >> 8;
  22584. double framesPerSecond;
  22585. switch (frameCode)
  22586. {
  22587. case 24: framesPerSecond = 24.0; break;
  22588. case 25: framesPerSecond = 25.0; break;
  22589. case 29: framesPerSecond = 29.97; break;
  22590. case 30: framesPerSecond = 30.0; break;
  22591. default: framesPerSecond = 30.0; break;
  22592. }
  22593. return (1.0 / framesPerSecond) / (timeFormat & 0xff);
  22594. }
  22595. }
  22596. const MidiMessage MidiMessage::tempoMetaEvent (int microsecondsPerQuarterNote) throw()
  22597. {
  22598. uint8 d[8];
  22599. d[0] = 0xff;
  22600. d[1] = 81;
  22601. d[2] = 3;
  22602. d[3] = (uint8) (microsecondsPerQuarterNote >> 16);
  22603. d[4] = (uint8) ((microsecondsPerQuarterNote >> 8) & 0xff);
  22604. d[5] = (uint8) (microsecondsPerQuarterNote & 0xff);
  22605. return MidiMessage (d, 6, 0.0);
  22606. }
  22607. bool MidiMessage::isTimeSignatureMetaEvent() const throw()
  22608. {
  22609. return (data[1] == 0x58)
  22610. && (*data == (uint8) 0xff);
  22611. }
  22612. void MidiMessage::getTimeSignatureInfo (int& numerator, int& denominator) const throw()
  22613. {
  22614. if (isTimeSignatureMetaEvent())
  22615. {
  22616. const uint8* const d = getMetaEventData();
  22617. numerator = d[0];
  22618. denominator = 1 << d[1];
  22619. }
  22620. else
  22621. {
  22622. numerator = 4;
  22623. denominator = 4;
  22624. }
  22625. }
  22626. const MidiMessage MidiMessage::timeSignatureMetaEvent (const int numerator, const int denominator)
  22627. {
  22628. uint8 d[8];
  22629. d[0] = 0xff;
  22630. d[1] = 0x58;
  22631. d[2] = 0x04;
  22632. d[3] = (uint8) numerator;
  22633. int n = 1;
  22634. int powerOfTwo = 0;
  22635. while (n < denominator)
  22636. {
  22637. n <<= 1;
  22638. ++powerOfTwo;
  22639. }
  22640. d[4] = (uint8) powerOfTwo;
  22641. d[5] = 0x01;
  22642. d[6] = 96;
  22643. return MidiMessage (d, 7, 0.0);
  22644. }
  22645. const MidiMessage MidiMessage::midiChannelMetaEvent (const int channel) throw()
  22646. {
  22647. uint8 d[8];
  22648. d[0] = 0xff;
  22649. d[1] = 0x20;
  22650. d[2] = 0x01;
  22651. d[3] = (uint8) jlimit (0, 0xff, channel - 1);
  22652. return MidiMessage (d, 4, 0.0);
  22653. }
  22654. bool MidiMessage::isKeySignatureMetaEvent() const throw()
  22655. {
  22656. return getMetaEventType() == 89;
  22657. }
  22658. int MidiMessage::getKeySignatureNumberOfSharpsOrFlats() const throw()
  22659. {
  22660. return (int) *getMetaEventData();
  22661. }
  22662. const MidiMessage MidiMessage::endOfTrack() throw()
  22663. {
  22664. return MidiMessage (0xff, 0x2f, 0, 0.0);
  22665. }
  22666. bool MidiMessage::isSongPositionPointer() const throw()
  22667. {
  22668. return *data == 0xf2;
  22669. }
  22670. int MidiMessage::getSongPositionPointerMidiBeat() const throw()
  22671. {
  22672. return data[1] | (data[2] << 7);
  22673. }
  22674. const MidiMessage MidiMessage::songPositionPointer (const int positionInMidiBeats) throw()
  22675. {
  22676. return MidiMessage (0xf2,
  22677. positionInMidiBeats & 127,
  22678. (positionInMidiBeats >> 7) & 127);
  22679. }
  22680. bool MidiMessage::isMidiStart() const throw()
  22681. {
  22682. return *data == 0xfa;
  22683. }
  22684. const MidiMessage MidiMessage::midiStart() throw()
  22685. {
  22686. return MidiMessage (0xfa);
  22687. }
  22688. bool MidiMessage::isMidiContinue() const throw()
  22689. {
  22690. return *data == 0xfb;
  22691. }
  22692. const MidiMessage MidiMessage::midiContinue() throw()
  22693. {
  22694. return MidiMessage (0xfb);
  22695. }
  22696. bool MidiMessage::isMidiStop() const throw()
  22697. {
  22698. return *data == 0xfc;
  22699. }
  22700. const MidiMessage MidiMessage::midiStop() throw()
  22701. {
  22702. return MidiMessage (0xfc);
  22703. }
  22704. bool MidiMessage::isMidiClock() const throw()
  22705. {
  22706. return *data == 0xf8;
  22707. }
  22708. const MidiMessage MidiMessage::midiClock() throw()
  22709. {
  22710. return MidiMessage (0xf8);
  22711. }
  22712. bool MidiMessage::isQuarterFrame() const throw()
  22713. {
  22714. return *data == 0xf1;
  22715. }
  22716. int MidiMessage::getQuarterFrameSequenceNumber() const throw()
  22717. {
  22718. return ((int) data[1]) >> 4;
  22719. }
  22720. int MidiMessage::getQuarterFrameValue() const throw()
  22721. {
  22722. return ((int) data[1]) & 0x0f;
  22723. }
  22724. const MidiMessage MidiMessage::quarterFrame (const int sequenceNumber,
  22725. const int value) throw()
  22726. {
  22727. return MidiMessage (0xf1, (sequenceNumber << 4) | value);
  22728. }
  22729. bool MidiMessage::isFullFrame() const throw()
  22730. {
  22731. return data[0] == 0xf0
  22732. && data[1] == 0x7f
  22733. && size >= 10
  22734. && data[3] == 0x01
  22735. && data[4] == 0x01;
  22736. }
  22737. void MidiMessage::getFullFrameParameters (int& hours,
  22738. int& minutes,
  22739. int& seconds,
  22740. int& frames,
  22741. MidiMessage::SmpteTimecodeType& timecodeType) const throw()
  22742. {
  22743. jassert (isFullFrame());
  22744. timecodeType = (SmpteTimecodeType) (data[5] >> 5);
  22745. hours = data[5] & 0x1f;
  22746. minutes = data[6];
  22747. seconds = data[7];
  22748. frames = data[8];
  22749. }
  22750. const MidiMessage MidiMessage::fullFrame (const int hours,
  22751. const int minutes,
  22752. const int seconds,
  22753. const int frames,
  22754. MidiMessage::SmpteTimecodeType timecodeType)
  22755. {
  22756. uint8 d[10];
  22757. d[0] = 0xf0;
  22758. d[1] = 0x7f;
  22759. d[2] = 0x7f;
  22760. d[3] = 0x01;
  22761. d[4] = 0x01;
  22762. d[5] = (uint8) ((hours & 0x01f) | (timecodeType << 5));
  22763. d[6] = (uint8) minutes;
  22764. d[7] = (uint8) seconds;
  22765. d[8] = (uint8) frames;
  22766. d[9] = 0xf7;
  22767. return MidiMessage (d, 10, 0.0);
  22768. }
  22769. bool MidiMessage::isMidiMachineControlMessage() const throw()
  22770. {
  22771. return data[0] == 0xf0
  22772. && data[1] == 0x7f
  22773. && data[3] == 0x06
  22774. && size > 5;
  22775. }
  22776. MidiMessage::MidiMachineControlCommand MidiMessage::getMidiMachineControlCommand() const throw()
  22777. {
  22778. jassert (isMidiMachineControlMessage());
  22779. return (MidiMachineControlCommand) data[4];
  22780. }
  22781. const MidiMessage MidiMessage::midiMachineControlCommand (MidiMessage::MidiMachineControlCommand command)
  22782. {
  22783. uint8 d[6];
  22784. d[0] = 0xf0;
  22785. d[1] = 0x7f;
  22786. d[2] = 0x00;
  22787. d[3] = 0x06;
  22788. d[4] = (uint8) command;
  22789. d[5] = 0xf7;
  22790. return MidiMessage (d, 6, 0.0);
  22791. }
  22792. bool MidiMessage::isMidiMachineControlGoto (int& hours,
  22793. int& minutes,
  22794. int& seconds,
  22795. int& frames) const throw()
  22796. {
  22797. if (size >= 12
  22798. && data[0] == 0xf0
  22799. && data[1] == 0x7f
  22800. && data[3] == 0x06
  22801. && data[4] == 0x44
  22802. && data[5] == 0x06
  22803. && data[6] == 0x01)
  22804. {
  22805. hours = data[7] % 24; // (that some machines send out hours > 24)
  22806. minutes = data[8];
  22807. seconds = data[9];
  22808. frames = data[10];
  22809. return true;
  22810. }
  22811. return false;
  22812. }
  22813. const MidiMessage MidiMessage::midiMachineControlGoto (int hours,
  22814. int minutes,
  22815. int seconds,
  22816. int frames)
  22817. {
  22818. uint8 d[12];
  22819. d[0] = 0xf0;
  22820. d[1] = 0x7f;
  22821. d[2] = 0x00;
  22822. d[3] = 0x06;
  22823. d[4] = 0x44;
  22824. d[5] = 0x06;
  22825. d[6] = 0x01;
  22826. d[7] = (uint8) hours;
  22827. d[8] = (uint8) minutes;
  22828. d[9] = (uint8) seconds;
  22829. d[10] = (uint8) frames;
  22830. d[11] = 0xf7;
  22831. return MidiMessage (d, 12, 0.0);
  22832. }
  22833. const String MidiMessage::getMidiNoteName (int note,
  22834. bool useSharps,
  22835. bool includeOctaveNumber,
  22836. int octaveNumForMiddleC) throw()
  22837. {
  22838. static const char* const sharpNoteNames[] = { "C", "C#", "D", "D#", "E",
  22839. "F", "F#", "G", "G#", "A",
  22840. "A#", "B" };
  22841. static const char* const flatNoteNames[] = { "C", "Db", "D", "Eb", "E",
  22842. "F", "Gb", "G", "Ab", "A",
  22843. "Bb", "B" };
  22844. if (((unsigned int) note) < 128)
  22845. {
  22846. const String s ((useSharps) ? sharpNoteNames [note % 12]
  22847. : flatNoteNames [note % 12]);
  22848. if (includeOctaveNumber)
  22849. return s + String (note / 12 + (octaveNumForMiddleC - 5));
  22850. else
  22851. return s;
  22852. }
  22853. return String::empty;
  22854. }
  22855. const double MidiMessage::getMidiNoteInHertz (int noteNumber) throw()
  22856. {
  22857. noteNumber -= 12 * 6 + 9; // now 0 = A440
  22858. return 440.0 * pow (2.0, noteNumber / 12.0);
  22859. }
  22860. const String MidiMessage::getGMInstrumentName (int n) throw()
  22861. {
  22862. const char *names[] =
  22863. {
  22864. "Acoustic Grand Piano", "Bright Acoustic Piano", "Electric Grand Piano", "Honky-tonk Piano",
  22865. "Electric Piano 1", "Electric Piano 2", "Harpsichord", "Clavinet", "Celesta", "Glockenspiel",
  22866. "Music Box", "Vibraphone", "Marimba", "Xylophone", "Tubular Bells", "Dulcimer", "Drawbar Organ",
  22867. "Percussive Organ", "Rock Organ", "Church Organ", "Reed Organ", "Accordion", "Harmonica",
  22868. "Tango Accordion", "Acoustic Guitar (nylon)", "Acoustic Guitar (steel)", "Electric Guitar (jazz)",
  22869. "Electric Guitar (clean)", "Electric Guitar (mute)", "Overdriven Guitar", "Distortion Guitar",
  22870. "Guitar Harmonics", "Acoustic Bass", "Electric Bass (finger)", "Electric Bass (pick)",
  22871. "Fretless Bass", "Slap Bass 1", "Slap Bass 2", "Synth Bass 1", "Synth Bass 2", "Violin",
  22872. "Viola", "Cello", "Contrabass", "Tremolo Strings", "Pizzicato Strings", "Orchestral Harp",
  22873. "Timpani", "String Ensemble 1", "String Ensemble 2", "SynthStrings 1", "SynthStrings 2",
  22874. "Choir Aahs", "Voice Oohs", "Synth Voice", "Orchestra Hit", "Trumpet", "Trombone", "Tuba",
  22875. "Muted Trumpet", "French Horn", "Brass Section", "SynthBrass 1", "SynthBrass 2", "Soprano Sax",
  22876. "Alto Sax", "Tenor Sax", "Baritone Sax", "Oboe", "English Horn", "Bassoon", "Clarinet",
  22877. "Piccolo", "Flute", "Recorder", "Pan Flute", "Blown Bottle", "Shakuhachi", "Whistle",
  22878. "Ocarina", "Lead 1 (square)", "Lead 2 (sawtooth)", "Lead 3 (calliope)", "Lead 4 (chiff)",
  22879. "Lead 5 (charang)", "Lead 6 (voice)", "Lead 7 (fifths)", "Lead 8 (bass+lead)", "Pad 1 (new age)",
  22880. "Pad 2 (warm)", "Pad 3 (polysynth)", "Pad 4 (choir)", "Pad 5 (bowed)", "Pad 6 (metallic)",
  22881. "Pad 7 (halo)", "Pad 8 (sweep)", "FX 1 (rain)", "FX 2 (soundtrack)", "FX 3 (crystal)",
  22882. "FX 4 (atmosphere)", "FX 5 (brightness)", "FX 6 (goblins)", "FX 7 (echoes)", "FX 8 (sci-fi)",
  22883. "Sitar", "Banjo", "Shamisen", "Koto", "Kalimba", "Bag pipe", "Fiddle", "Shanai", "Tinkle Bell",
  22884. "Agogo", "Steel Drums", "Woodblock", "Taiko Drum", "Melodic Tom", "Synth Drum", "Reverse Cymbal",
  22885. "Guitar Fret Noise", "Breath Noise", "Seashore", "Bird Tweet", "Telephone Ring", "Helicopter",
  22886. "Applause", "Gunshot"
  22887. };
  22888. return (((unsigned int) n) < 128) ? names[n]
  22889. : (const char*)0;
  22890. }
  22891. const String MidiMessage::getGMInstrumentBankName (int n) throw()
  22892. {
  22893. const char* names[] =
  22894. {
  22895. "Piano", "Chromatic Percussion", "Organ", "Guitar",
  22896. "Bass", "Strings", "Ensemble", "Brass",
  22897. "Reed", "Pipe", "Synth Lead", "Synth Pad",
  22898. "Synth Effects", "Ethnic", "Percussive", "Sound Effects"
  22899. };
  22900. return (((unsigned int) n) <= 15) ? names[n]
  22901. : (const char*)0;
  22902. }
  22903. const String MidiMessage::getRhythmInstrumentName (int n) throw()
  22904. {
  22905. const char* names[] =
  22906. {
  22907. "Acoustic Bass Drum", "Bass Drum 1", "Side Stick", "Acoustic Snare",
  22908. "Hand Clap", "Electric Snare", "Low Floor Tom", "Closed Hi-Hat", "High Floor Tom",
  22909. "Pedal Hi-Hat", "Low Tom", "Open Hi-Hat", "Low-Mid Tom", "Hi-Mid Tom", "Crash Cymbal 1",
  22910. "High Tom", "Ride Cymbal 1", "Chinese Cymbal", "Ride Bell", "Tambourine", "Splash Cymbal",
  22911. "Cowbell", "Crash Cymbal 2", "Vibraslap", "Ride Cymbal 2", "Hi Bongo", "Low Bongo",
  22912. "Mute Hi Conga", "Open Hi Conga", "Low Conga", "High Timbale", "Low Timbale", "High Agogo",
  22913. "Low Agogo", "Cabasa", "Maracas", "Short Whistle", "Long Whistle", "Short Guiro",
  22914. "Long Guiro", "Claves", "Hi Wood Block", "Low Wood Block", "Mute Cuica", "Open Cuica",
  22915. "Mute Triangle", "Open Triangle"
  22916. };
  22917. return (n >= 35 && n <= 81) ? names [n - 35]
  22918. : (const char*)0;
  22919. }
  22920. const String MidiMessage::getControllerName (int n) throw()
  22921. {
  22922. const char* names[] =
  22923. {
  22924. "Bank Select", "Modulation Wheel (coarse)", "Breath controller (coarse)",
  22925. 0, "Foot Pedal (coarse)", "Portamento Time (coarse)",
  22926. "Data Entry (coarse)", "Volume (coarse)", "Balance (coarse)",
  22927. 0, "Pan position (coarse)", "Expression (coarse)", "Effect Control 1 (coarse)",
  22928. "Effect Control 2 (coarse)", 0, 0, "General Purpose Slider 1", "General Purpose Slider 2",
  22929. "General Purpose Slider 3", "General Purpose Slider 4", 0, 0, 0, 0, 0, 0, 0, 0,
  22930. 0, 0, 0, 0, "Bank Select (fine)", "Modulation Wheel (fine)", "Breath controller (fine)",
  22931. 0, "Foot Pedal (fine)", "Portamento Time (fine)", "Data Entry (fine)", "Volume (fine)",
  22932. "Balance (fine)", 0, "Pan position (fine)", "Expression (fine)", "Effect Control 1 (fine)",
  22933. "Effect Control 2 (fine)", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  22934. "Hold Pedal (on/off)", "Portamento (on/off)", "Sustenuto Pedal (on/off)", "Soft Pedal (on/off)",
  22935. "Legato Pedal (on/off)", "Hold 2 Pedal (on/off)", "Sound Variation", "Sound Timbre",
  22936. "Sound Release Time", "Sound Attack Time", "Sound Brightness", "Sound Control 6",
  22937. "Sound Control 7", "Sound Control 8", "Sound Control 9", "Sound Control 10",
  22938. "General Purpose Button 1 (on/off)", "General Purpose Button 2 (on/off)",
  22939. "General Purpose Button 3 (on/off)", "General Purpose Button 4 (on/off)",
  22940. 0, 0, 0, 0, 0, 0, 0, "Reverb Level", "Tremolo Level", "Chorus Level", "Celeste Level",
  22941. "Phaser Level", "Data Button increment", "Data Button decrement", "Non-registered Parameter (fine)",
  22942. "Non-registered Parameter (coarse)", "Registered Parameter (fine)", "Registered Parameter (coarse)",
  22943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "All Sound Off", "All Controllers Off",
  22944. "Local Keyboard (on/off)", "All Notes Off", "Omni Mode Off", "Omni Mode On", "Mono Operation",
  22945. "Poly Operation"
  22946. };
  22947. return (((unsigned int) n) < 128) ? names[n]
  22948. : (const char*)0;
  22949. }
  22950. END_JUCE_NAMESPACE
  22951. /*** End of inlined file: juce_MidiMessage.cpp ***/
  22952. /*** Start of inlined file: juce_MidiMessageCollector.cpp ***/
  22953. BEGIN_JUCE_NAMESPACE
  22954. MidiMessageCollector::MidiMessageCollector()
  22955. : lastCallbackTime (0),
  22956. sampleRate (44100.0001)
  22957. {
  22958. }
  22959. MidiMessageCollector::~MidiMessageCollector()
  22960. {
  22961. }
  22962. void MidiMessageCollector::reset (const double sampleRate_)
  22963. {
  22964. jassert (sampleRate_ > 0);
  22965. const ScopedLock sl (midiCallbackLock);
  22966. sampleRate = sampleRate_;
  22967. incomingMessages.clear();
  22968. lastCallbackTime = Time::getMillisecondCounterHiRes();
  22969. }
  22970. void MidiMessageCollector::addMessageToQueue (const MidiMessage& message)
  22971. {
  22972. // you need to call reset() to set the correct sample rate before using this object
  22973. jassert (sampleRate != 44100.0001);
  22974. // the messages that come in here need to be time-stamped correctly - see MidiInput
  22975. // for details of what the number should be.
  22976. jassert (message.getTimeStamp() != 0);
  22977. const ScopedLock sl (midiCallbackLock);
  22978. const int sampleNumber
  22979. = (int) ((message.getTimeStamp() - 0.001 * lastCallbackTime) * sampleRate);
  22980. incomingMessages.addEvent (message, sampleNumber);
  22981. // if the messages don't get used for over a second, we'd better
  22982. // get rid of any old ones to avoid the queue getting too big
  22983. if (sampleNumber > sampleRate)
  22984. incomingMessages.clear (0, sampleNumber - (int) sampleRate);
  22985. }
  22986. void MidiMessageCollector::removeNextBlockOfMessages (MidiBuffer& destBuffer,
  22987. const int numSamples)
  22988. {
  22989. // you need to call reset() to set the correct sample rate before using this object
  22990. jassert (sampleRate != 44100.0001);
  22991. const double timeNow = Time::getMillisecondCounterHiRes();
  22992. const double msElapsed = timeNow - lastCallbackTime;
  22993. const ScopedLock sl (midiCallbackLock);
  22994. lastCallbackTime = timeNow;
  22995. if (! incomingMessages.isEmpty())
  22996. {
  22997. int numSourceSamples = jmax (1, roundToInt (msElapsed * 0.001 * sampleRate));
  22998. int startSample = 0;
  22999. int scale = 1 << 16;
  23000. const uint8* midiData;
  23001. int numBytes, samplePosition;
  23002. MidiBuffer::Iterator iter (incomingMessages);
  23003. if (numSourceSamples > numSamples)
  23004. {
  23005. // if our list of events is longer than the buffer we're being
  23006. // asked for, scale them down to squeeze them all in..
  23007. const int maxBlockLengthToUse = numSamples << 5;
  23008. if (numSourceSamples > maxBlockLengthToUse)
  23009. {
  23010. startSample = numSourceSamples - maxBlockLengthToUse;
  23011. numSourceSamples = maxBlockLengthToUse;
  23012. iter.setNextSamplePosition (startSample);
  23013. }
  23014. scale = (numSamples << 10) / numSourceSamples;
  23015. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  23016. {
  23017. samplePosition = ((samplePosition - startSample) * scale) >> 10;
  23018. destBuffer.addEvent (midiData, numBytes,
  23019. jlimit (0, numSamples - 1, samplePosition));
  23020. }
  23021. }
  23022. else
  23023. {
  23024. // if our event list is shorter than the number we need, put them
  23025. // towards the end of the buffer
  23026. startSample = numSamples - numSourceSamples;
  23027. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  23028. {
  23029. destBuffer.addEvent (midiData, numBytes,
  23030. jlimit (0, numSamples - 1, samplePosition + startSample));
  23031. }
  23032. }
  23033. incomingMessages.clear();
  23034. }
  23035. }
  23036. void MidiMessageCollector::handleNoteOn (MidiKeyboardState*, int midiChannel, int midiNoteNumber, float velocity)
  23037. {
  23038. MidiMessage m (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity));
  23039. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  23040. addMessageToQueue (m);
  23041. }
  23042. void MidiMessageCollector::handleNoteOff (MidiKeyboardState*, int midiChannel, int midiNoteNumber)
  23043. {
  23044. MidiMessage m (MidiMessage::noteOff (midiChannel, midiNoteNumber));
  23045. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  23046. addMessageToQueue (m);
  23047. }
  23048. void MidiMessageCollector::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  23049. {
  23050. addMessageToQueue (message);
  23051. }
  23052. END_JUCE_NAMESPACE
  23053. /*** End of inlined file: juce_MidiMessageCollector.cpp ***/
  23054. /*** Start of inlined file: juce_MidiMessageSequence.cpp ***/
  23055. BEGIN_JUCE_NAMESPACE
  23056. MidiMessageSequence::MidiMessageSequence()
  23057. {
  23058. }
  23059. MidiMessageSequence::MidiMessageSequence (const MidiMessageSequence& other)
  23060. {
  23061. list.ensureStorageAllocated (other.list.size());
  23062. for (int i = 0; i < other.list.size(); ++i)
  23063. list.add (new MidiEventHolder (other.list.getUnchecked(i)->message));
  23064. }
  23065. MidiMessageSequence& MidiMessageSequence::operator= (const MidiMessageSequence& other)
  23066. {
  23067. MidiMessageSequence otherCopy (other);
  23068. swapWith (otherCopy);
  23069. return *this;
  23070. }
  23071. void MidiMessageSequence::swapWith (MidiMessageSequence& other) throw()
  23072. {
  23073. list.swapWithArray (other.list);
  23074. }
  23075. MidiMessageSequence::~MidiMessageSequence()
  23076. {
  23077. }
  23078. void MidiMessageSequence::clear()
  23079. {
  23080. list.clear();
  23081. }
  23082. int MidiMessageSequence::getNumEvents() const
  23083. {
  23084. return list.size();
  23085. }
  23086. MidiMessageSequence::MidiEventHolder* MidiMessageSequence::getEventPointer (const int index) const
  23087. {
  23088. return list [index];
  23089. }
  23090. double MidiMessageSequence::getTimeOfMatchingKeyUp (const int index) const
  23091. {
  23092. const MidiEventHolder* const meh = list [index];
  23093. if (meh != 0 && meh->noteOffObject != 0)
  23094. return meh->noteOffObject->message.getTimeStamp();
  23095. else
  23096. return 0.0;
  23097. }
  23098. int MidiMessageSequence::getIndexOfMatchingKeyUp (const int index) const
  23099. {
  23100. const MidiEventHolder* const meh = list [index];
  23101. return (meh != 0) ? list.indexOf (meh->noteOffObject) : -1;
  23102. }
  23103. int MidiMessageSequence::getIndexOf (MidiEventHolder* const event) const
  23104. {
  23105. return list.indexOf (event);
  23106. }
  23107. int MidiMessageSequence::getNextIndexAtTime (const double timeStamp) const
  23108. {
  23109. const int numEvents = list.size();
  23110. int i;
  23111. for (i = 0; i < numEvents; ++i)
  23112. if (list.getUnchecked(i)->message.getTimeStamp() >= timeStamp)
  23113. break;
  23114. return i;
  23115. }
  23116. double MidiMessageSequence::getStartTime() const
  23117. {
  23118. if (list.size() > 0)
  23119. return list.getUnchecked(0)->message.getTimeStamp();
  23120. else
  23121. return 0;
  23122. }
  23123. double MidiMessageSequence::getEndTime() const
  23124. {
  23125. if (list.size() > 0)
  23126. return list.getLast()->message.getTimeStamp();
  23127. else
  23128. return 0;
  23129. }
  23130. double MidiMessageSequence::getEventTime (const int index) const
  23131. {
  23132. if (((unsigned int) index) < (unsigned int) list.size())
  23133. return list.getUnchecked (index)->message.getTimeStamp();
  23134. return 0.0;
  23135. }
  23136. void MidiMessageSequence::addEvent (const MidiMessage& newMessage,
  23137. double timeAdjustment)
  23138. {
  23139. MidiEventHolder* const newOne = new MidiEventHolder (newMessage);
  23140. timeAdjustment += newMessage.getTimeStamp();
  23141. newOne->message.setTimeStamp (timeAdjustment);
  23142. int i;
  23143. for (i = list.size(); --i >= 0;)
  23144. if (list.getUnchecked(i)->message.getTimeStamp() <= timeAdjustment)
  23145. break;
  23146. list.insert (i + 1, newOne);
  23147. }
  23148. void MidiMessageSequence::deleteEvent (const int index,
  23149. const bool deleteMatchingNoteUp)
  23150. {
  23151. if (((unsigned int) index) < (unsigned int) list.size())
  23152. {
  23153. if (deleteMatchingNoteUp)
  23154. deleteEvent (getIndexOfMatchingKeyUp (index), false);
  23155. list.remove (index);
  23156. }
  23157. }
  23158. void MidiMessageSequence::addSequence (const MidiMessageSequence& other,
  23159. double timeAdjustment,
  23160. double firstAllowableTime,
  23161. double endOfAllowableDestTimes)
  23162. {
  23163. firstAllowableTime -= timeAdjustment;
  23164. endOfAllowableDestTimes -= timeAdjustment;
  23165. for (int i = 0; i < other.list.size(); ++i)
  23166. {
  23167. const MidiMessage& m = other.list.getUnchecked(i)->message;
  23168. const double t = m.getTimeStamp();
  23169. if (t >= firstAllowableTime && t < endOfAllowableDestTimes)
  23170. {
  23171. MidiEventHolder* const newOne = new MidiEventHolder (m);
  23172. newOne->message.setTimeStamp (timeAdjustment + t);
  23173. list.add (newOne);
  23174. }
  23175. }
  23176. sort();
  23177. }
  23178. int MidiMessageSequence::compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  23179. const MidiMessageSequence::MidiEventHolder* const second) throw()
  23180. {
  23181. const double diff = first->message.getTimeStamp()
  23182. - second->message.getTimeStamp();
  23183. return (diff > 0) - (diff < 0);
  23184. }
  23185. void MidiMessageSequence::sort()
  23186. {
  23187. list.sort (*this, true);
  23188. }
  23189. void MidiMessageSequence::updateMatchedPairs()
  23190. {
  23191. for (int i = 0; i < list.size(); ++i)
  23192. {
  23193. const MidiMessage& m1 = list.getUnchecked(i)->message;
  23194. if (m1.isNoteOn())
  23195. {
  23196. list.getUnchecked(i)->noteOffObject = 0;
  23197. const int note = m1.getNoteNumber();
  23198. const int chan = m1.getChannel();
  23199. const int len = list.size();
  23200. for (int j = i + 1; j < len; ++j)
  23201. {
  23202. const MidiMessage& m = list.getUnchecked(j)->message;
  23203. if (m.getNoteNumber() == note && m.getChannel() == chan)
  23204. {
  23205. if (m.isNoteOff())
  23206. {
  23207. list.getUnchecked(i)->noteOffObject = list[j];
  23208. break;
  23209. }
  23210. else if (m.isNoteOn())
  23211. {
  23212. list.insert (j, new MidiEventHolder (MidiMessage::noteOff (chan, note)));
  23213. list.getUnchecked(j)->message.setTimeStamp (m.getTimeStamp());
  23214. list.getUnchecked(i)->noteOffObject = list[j];
  23215. break;
  23216. }
  23217. }
  23218. }
  23219. }
  23220. }
  23221. }
  23222. void MidiMessageSequence::addTimeToMessages (const double delta)
  23223. {
  23224. for (int i = list.size(); --i >= 0;)
  23225. list.getUnchecked (i)->message.setTimeStamp (list.getUnchecked (i)->message.getTimeStamp()
  23226. + delta);
  23227. }
  23228. void MidiMessageSequence::extractMidiChannelMessages (const int channelNumberToExtract,
  23229. MidiMessageSequence& destSequence,
  23230. const bool alsoIncludeMetaEvents) const
  23231. {
  23232. for (int i = 0; i < list.size(); ++i)
  23233. {
  23234. const MidiMessage& mm = list.getUnchecked(i)->message;
  23235. if (mm.isForChannel (channelNumberToExtract)
  23236. || (alsoIncludeMetaEvents && mm.isMetaEvent()))
  23237. {
  23238. destSequence.addEvent (mm);
  23239. }
  23240. }
  23241. }
  23242. void MidiMessageSequence::extractSysExMessages (MidiMessageSequence& destSequence) const
  23243. {
  23244. for (int i = 0; i < list.size(); ++i)
  23245. {
  23246. const MidiMessage& mm = list.getUnchecked(i)->message;
  23247. if (mm.isSysEx())
  23248. destSequence.addEvent (mm);
  23249. }
  23250. }
  23251. void MidiMessageSequence::deleteMidiChannelMessages (const int channelNumberToRemove)
  23252. {
  23253. for (int i = list.size(); --i >= 0;)
  23254. if (list.getUnchecked(i)->message.isForChannel (channelNumberToRemove))
  23255. list.remove(i);
  23256. }
  23257. void MidiMessageSequence::deleteSysExMessages()
  23258. {
  23259. for (int i = list.size(); --i >= 0;)
  23260. if (list.getUnchecked(i)->message.isSysEx())
  23261. list.remove(i);
  23262. }
  23263. void MidiMessageSequence::createControllerUpdatesForTime (const int channelNumber,
  23264. const double time,
  23265. OwnedArray<MidiMessage>& dest)
  23266. {
  23267. bool doneProg = false;
  23268. bool donePitchWheel = false;
  23269. Array <int> doneControllers;
  23270. doneControllers.ensureStorageAllocated (32);
  23271. for (int i = list.size(); --i >= 0;)
  23272. {
  23273. const MidiMessage& mm = list.getUnchecked(i)->message;
  23274. if (mm.isForChannel (channelNumber)
  23275. && mm.getTimeStamp() <= time)
  23276. {
  23277. if (mm.isProgramChange())
  23278. {
  23279. if (! doneProg)
  23280. {
  23281. dest.add (new MidiMessage (mm, 0.0));
  23282. doneProg = true;
  23283. }
  23284. }
  23285. else if (mm.isController())
  23286. {
  23287. if (! doneControllers.contains (mm.getControllerNumber()))
  23288. {
  23289. dest.add (new MidiMessage (mm, 0.0));
  23290. doneControllers.add (mm.getControllerNumber());
  23291. }
  23292. }
  23293. else if (mm.isPitchWheel())
  23294. {
  23295. if (! donePitchWheel)
  23296. {
  23297. dest.add (new MidiMessage (mm, 0.0));
  23298. donePitchWheel = true;
  23299. }
  23300. }
  23301. }
  23302. }
  23303. }
  23304. MidiMessageSequence::MidiEventHolder::MidiEventHolder (const MidiMessage& message_)
  23305. : message (message_),
  23306. noteOffObject (0)
  23307. {
  23308. }
  23309. MidiMessageSequence::MidiEventHolder::~MidiEventHolder()
  23310. {
  23311. }
  23312. END_JUCE_NAMESPACE
  23313. /*** End of inlined file: juce_MidiMessageSequence.cpp ***/
  23314. /*** Start of inlined file: juce_AudioPluginFormat.cpp ***/
  23315. BEGIN_JUCE_NAMESPACE
  23316. AudioPluginFormat::AudioPluginFormat() throw()
  23317. {
  23318. }
  23319. AudioPluginFormat::~AudioPluginFormat()
  23320. {
  23321. }
  23322. END_JUCE_NAMESPACE
  23323. /*** End of inlined file: juce_AudioPluginFormat.cpp ***/
  23324. /*** Start of inlined file: juce_AudioPluginFormatManager.cpp ***/
  23325. BEGIN_JUCE_NAMESPACE
  23326. AudioPluginFormatManager::AudioPluginFormatManager() throw()
  23327. {
  23328. }
  23329. AudioPluginFormatManager::~AudioPluginFormatManager() throw()
  23330. {
  23331. clearSingletonInstance();
  23332. }
  23333. juce_ImplementSingleton_SingleThreaded (AudioPluginFormatManager);
  23334. void AudioPluginFormatManager::addDefaultFormats()
  23335. {
  23336. #if JUCE_DEBUG
  23337. // you should only call this method once!
  23338. for (int i = formats.size(); --i >= 0;)
  23339. {
  23340. #if JUCE_PLUGINHOST_VST && ! (JUCE_MAC && JUCE_64BIT)
  23341. jassert (dynamic_cast <VSTPluginFormat*> (formats[i]) == 0);
  23342. #endif
  23343. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  23344. jassert (dynamic_cast <AudioUnitPluginFormat*> (formats[i]) == 0);
  23345. #endif
  23346. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  23347. jassert (dynamic_cast <DirectXPluginFormat*> (formats[i]) == 0);
  23348. #endif
  23349. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  23350. jassert (dynamic_cast <LADSPAPluginFormat*> (formats[i]) == 0);
  23351. #endif
  23352. }
  23353. #endif
  23354. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  23355. formats.add (new AudioUnitPluginFormat());
  23356. #endif
  23357. #if JUCE_PLUGINHOST_VST && ! (JUCE_MAC && JUCE_64BIT)
  23358. formats.add (new VSTPluginFormat());
  23359. #endif
  23360. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  23361. formats.add (new DirectXPluginFormat());
  23362. #endif
  23363. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  23364. formats.add (new LADSPAPluginFormat());
  23365. #endif
  23366. }
  23367. int AudioPluginFormatManager::getNumFormats() throw()
  23368. {
  23369. return formats.size();
  23370. }
  23371. AudioPluginFormat* AudioPluginFormatManager::getFormat (const int index) throw()
  23372. {
  23373. return formats [index];
  23374. }
  23375. void AudioPluginFormatManager::addFormat (AudioPluginFormat* const format) throw()
  23376. {
  23377. formats.add (format);
  23378. }
  23379. AudioPluginInstance* AudioPluginFormatManager::createPluginInstance (const PluginDescription& description,
  23380. String& errorMessage) const
  23381. {
  23382. AudioPluginInstance* result = 0;
  23383. for (int i = 0; i < formats.size(); ++i)
  23384. {
  23385. result = formats.getUnchecked(i)->createInstanceFromDescription (description);
  23386. if (result != 0)
  23387. break;
  23388. }
  23389. if (result == 0)
  23390. {
  23391. if (! doesPluginStillExist (description))
  23392. errorMessage = TRANS ("This plug-in file no longer exists");
  23393. else
  23394. errorMessage = TRANS ("This plug-in failed to load correctly");
  23395. }
  23396. return result;
  23397. }
  23398. bool AudioPluginFormatManager::doesPluginStillExist (const PluginDescription& description) const
  23399. {
  23400. for (int i = 0; i < formats.size(); ++i)
  23401. if (formats.getUnchecked(i)->getName() == description.pluginFormatName)
  23402. return formats.getUnchecked(i)->doesPluginStillExist (description);
  23403. return false;
  23404. }
  23405. END_JUCE_NAMESPACE
  23406. /*** End of inlined file: juce_AudioPluginFormatManager.cpp ***/
  23407. /*** Start of inlined file: juce_AudioPluginInstance.cpp ***/
  23408. #define JUCE_PLUGIN_HOST 1
  23409. BEGIN_JUCE_NAMESPACE
  23410. AudioPluginInstance::AudioPluginInstance()
  23411. {
  23412. }
  23413. AudioPluginInstance::~AudioPluginInstance()
  23414. {
  23415. }
  23416. END_JUCE_NAMESPACE
  23417. /*** End of inlined file: juce_AudioPluginInstance.cpp ***/
  23418. /*** Start of inlined file: juce_KnownPluginList.cpp ***/
  23419. BEGIN_JUCE_NAMESPACE
  23420. KnownPluginList::KnownPluginList()
  23421. {
  23422. }
  23423. KnownPluginList::~KnownPluginList()
  23424. {
  23425. }
  23426. void KnownPluginList::clear()
  23427. {
  23428. if (types.size() > 0)
  23429. {
  23430. types.clear();
  23431. sendChangeMessage (this);
  23432. }
  23433. }
  23434. PluginDescription* KnownPluginList::getTypeForFile (const String& fileOrIdentifier) const throw()
  23435. {
  23436. for (int i = 0; i < types.size(); ++i)
  23437. if (types.getUnchecked(i)->fileOrIdentifier == fileOrIdentifier)
  23438. return types.getUnchecked(i);
  23439. return 0;
  23440. }
  23441. PluginDescription* KnownPluginList::getTypeForIdentifierString (const String& identifierString) const throw()
  23442. {
  23443. for (int i = 0; i < types.size(); ++i)
  23444. if (types.getUnchecked(i)->createIdentifierString() == identifierString)
  23445. return types.getUnchecked(i);
  23446. return 0;
  23447. }
  23448. bool KnownPluginList::addType (const PluginDescription& type)
  23449. {
  23450. for (int i = types.size(); --i >= 0;)
  23451. {
  23452. if (types.getUnchecked(i)->isDuplicateOf (type))
  23453. {
  23454. // strange - found a duplicate plugin with different info..
  23455. jassert (types.getUnchecked(i)->name == type.name);
  23456. jassert (types.getUnchecked(i)->isInstrument == type.isInstrument);
  23457. *types.getUnchecked(i) = type;
  23458. return false;
  23459. }
  23460. }
  23461. types.add (new PluginDescription (type));
  23462. sendChangeMessage (this);
  23463. return true;
  23464. }
  23465. void KnownPluginList::removeType (const int index) throw()
  23466. {
  23467. types.remove (index);
  23468. sendChangeMessage (this);
  23469. }
  23470. static Time getFileModTime (const String& fileOrIdentifier) throw()
  23471. {
  23472. if (fileOrIdentifier.startsWithChar ('/')
  23473. || fileOrIdentifier[1] == ':')
  23474. {
  23475. return File (fileOrIdentifier).getLastModificationTime();
  23476. }
  23477. return Time (0);
  23478. }
  23479. static bool timesAreDifferent (const Time& t1, const Time& t2) throw()
  23480. {
  23481. return t1 != t2 || t1 == Time (0);
  23482. }
  23483. bool KnownPluginList::isListingUpToDate (const String& fileOrIdentifier) const throw()
  23484. {
  23485. if (getTypeForFile (fileOrIdentifier) == 0)
  23486. return false;
  23487. for (int i = types.size(); --i >= 0;)
  23488. {
  23489. const PluginDescription* const d = types.getUnchecked(i);
  23490. if (d->fileOrIdentifier == fileOrIdentifier
  23491. && timesAreDifferent (d->lastFileModTime, getFileModTime (fileOrIdentifier)))
  23492. {
  23493. return false;
  23494. }
  23495. }
  23496. return true;
  23497. }
  23498. bool KnownPluginList::scanAndAddFile (const String& fileOrIdentifier,
  23499. const bool dontRescanIfAlreadyInList,
  23500. OwnedArray <PluginDescription>& typesFound,
  23501. AudioPluginFormat& format)
  23502. {
  23503. bool addedOne = false;
  23504. if (dontRescanIfAlreadyInList
  23505. && getTypeForFile (fileOrIdentifier) != 0)
  23506. {
  23507. bool needsRescanning = false;
  23508. for (int i = types.size(); --i >= 0;)
  23509. {
  23510. const PluginDescription* const d = types.getUnchecked(i);
  23511. if (d->fileOrIdentifier == fileOrIdentifier)
  23512. {
  23513. if (timesAreDifferent (d->lastFileModTime, getFileModTime (fileOrIdentifier)))
  23514. needsRescanning = true;
  23515. else
  23516. typesFound.add (new PluginDescription (*d));
  23517. }
  23518. }
  23519. if (! needsRescanning)
  23520. return false;
  23521. }
  23522. OwnedArray <PluginDescription> found;
  23523. format.findAllTypesForFile (found, fileOrIdentifier);
  23524. for (int i = 0; i < found.size(); ++i)
  23525. {
  23526. PluginDescription* const desc = found.getUnchecked(i);
  23527. jassert (desc != 0);
  23528. if (addType (*desc))
  23529. addedOne = true;
  23530. typesFound.add (new PluginDescription (*desc));
  23531. }
  23532. return addedOne;
  23533. }
  23534. void KnownPluginList::scanAndAddDragAndDroppedFiles (const StringArray& files,
  23535. OwnedArray <PluginDescription>& typesFound)
  23536. {
  23537. for (int i = 0; i < files.size(); ++i)
  23538. {
  23539. bool loaded = false;
  23540. for (int j = 0; j < AudioPluginFormatManager::getInstance()->getNumFormats(); ++j)
  23541. {
  23542. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (j);
  23543. if (scanAndAddFile (files[i], true, typesFound, *format))
  23544. loaded = true;
  23545. }
  23546. if (! loaded)
  23547. {
  23548. const File f (files[i]);
  23549. if (f.isDirectory())
  23550. {
  23551. StringArray s;
  23552. {
  23553. Array<File> subFiles;
  23554. f.findChildFiles (subFiles, File::findFilesAndDirectories, false);
  23555. for (int j = 0; j < subFiles.size(); ++j)
  23556. s.add (subFiles.getReference(j).getFullPathName());
  23557. }
  23558. scanAndAddDragAndDroppedFiles (s, typesFound);
  23559. }
  23560. }
  23561. }
  23562. }
  23563. class PluginSorter
  23564. {
  23565. public:
  23566. KnownPluginList::SortMethod method;
  23567. PluginSorter() throw() {}
  23568. int compareElements (const PluginDescription* const first,
  23569. const PluginDescription* const second) const throw()
  23570. {
  23571. int diff = 0;
  23572. if (method == KnownPluginList::sortByCategory)
  23573. diff = first->category.compareLexicographically (second->category);
  23574. else if (method == KnownPluginList::sortByManufacturer)
  23575. diff = first->manufacturerName.compareLexicographically (second->manufacturerName);
  23576. else if (method == KnownPluginList::sortByFileSystemLocation)
  23577. diff = first->fileOrIdentifier.replaceCharacter ('\\', '/')
  23578. .upToLastOccurrenceOf ("/", false, false)
  23579. .compare (second->fileOrIdentifier.replaceCharacter ('\\', '/')
  23580. .upToLastOccurrenceOf ("/", false, false));
  23581. if (diff == 0)
  23582. diff = first->name.compareLexicographically (second->name);
  23583. return diff;
  23584. }
  23585. };
  23586. void KnownPluginList::sort (const SortMethod method)
  23587. {
  23588. if (method != defaultOrder)
  23589. {
  23590. PluginSorter sorter;
  23591. sorter.method = method;
  23592. types.sort (sorter, true);
  23593. sendChangeMessage (this);
  23594. }
  23595. }
  23596. XmlElement* KnownPluginList::createXml() const
  23597. {
  23598. XmlElement* const e = new XmlElement ("KNOWNPLUGINS");
  23599. for (int i = 0; i < types.size(); ++i)
  23600. e->addChildElement (types.getUnchecked(i)->createXml());
  23601. return e;
  23602. }
  23603. void KnownPluginList::recreateFromXml (const XmlElement& xml)
  23604. {
  23605. clear();
  23606. if (xml.hasTagName ("KNOWNPLUGINS"))
  23607. {
  23608. forEachXmlChildElement (xml, e)
  23609. {
  23610. PluginDescription info;
  23611. if (info.loadFromXml (*e))
  23612. addType (info);
  23613. }
  23614. }
  23615. }
  23616. const int menuIdBase = 0x324503f4;
  23617. // This is used to turn a bunch of paths into a nested menu structure.
  23618. struct PluginFilesystemTree
  23619. {
  23620. private:
  23621. String folder;
  23622. OwnedArray <PluginFilesystemTree> subFolders;
  23623. Array <PluginDescription*> plugins;
  23624. void addPlugin (PluginDescription* const pd, const String& path)
  23625. {
  23626. if (path.isEmpty())
  23627. {
  23628. plugins.add (pd);
  23629. }
  23630. else
  23631. {
  23632. const String firstSubFolder (path.upToFirstOccurrenceOf ("/", false, false));
  23633. const String remainingPath (path.fromFirstOccurrenceOf ("/", false, false));
  23634. for (int i = subFolders.size(); --i >= 0;)
  23635. {
  23636. if (subFolders.getUnchecked(i)->folder.equalsIgnoreCase (firstSubFolder))
  23637. {
  23638. subFolders.getUnchecked(i)->addPlugin (pd, remainingPath);
  23639. return;
  23640. }
  23641. }
  23642. PluginFilesystemTree* const newFolder = new PluginFilesystemTree();
  23643. newFolder->folder = firstSubFolder;
  23644. subFolders.add (newFolder);
  23645. newFolder->addPlugin (pd, remainingPath);
  23646. }
  23647. }
  23648. // removes any deeply nested folders that don't contain any actual plugins
  23649. void optimise()
  23650. {
  23651. for (int i = subFolders.size(); --i >= 0;)
  23652. {
  23653. PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  23654. sub->optimise();
  23655. if (sub->plugins.size() == 0)
  23656. {
  23657. for (int j = 0; j < sub->subFolders.size(); ++j)
  23658. subFolders.add (sub->subFolders.getUnchecked(j));
  23659. sub->subFolders.clear (false);
  23660. subFolders.remove (i);
  23661. }
  23662. }
  23663. }
  23664. public:
  23665. void buildTree (const Array <PluginDescription*>& allPlugins)
  23666. {
  23667. for (int i = 0; i < allPlugins.size(); ++i)
  23668. {
  23669. String path (allPlugins.getUnchecked(i)
  23670. ->fileOrIdentifier.replaceCharacter ('\\', '/')
  23671. .upToLastOccurrenceOf ("/", false, false));
  23672. if (path.substring (1, 2) == ":")
  23673. path = path.substring (2);
  23674. addPlugin (allPlugins.getUnchecked(i), path);
  23675. }
  23676. optimise();
  23677. }
  23678. void addToMenu (PopupMenu& m, const OwnedArray <PluginDescription>& allPlugins) const
  23679. {
  23680. int i;
  23681. for (i = 0; i < subFolders.size(); ++i)
  23682. {
  23683. const PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  23684. PopupMenu subMenu;
  23685. sub->addToMenu (subMenu, allPlugins);
  23686. #if JUCE_MAC
  23687. // avoid the special AU formatting nonsense on Mac..
  23688. m.addSubMenu (sub->folder.fromFirstOccurrenceOf (":", false, false), subMenu);
  23689. #else
  23690. m.addSubMenu (sub->folder, subMenu);
  23691. #endif
  23692. }
  23693. for (i = 0; i < plugins.size(); ++i)
  23694. {
  23695. PluginDescription* const plugin = plugins.getUnchecked(i);
  23696. m.addItem (allPlugins.indexOf (plugin) + menuIdBase,
  23697. plugin->name, true, false);
  23698. }
  23699. }
  23700. };
  23701. void KnownPluginList::addToMenu (PopupMenu& menu, const SortMethod sortMethod) const
  23702. {
  23703. Array <PluginDescription*> sorted;
  23704. {
  23705. PluginSorter sorter;
  23706. sorter.method = sortMethod;
  23707. for (int i = 0; i < types.size(); ++i)
  23708. sorted.addSorted (sorter, types.getUnchecked(i));
  23709. }
  23710. if (sortMethod == sortByCategory
  23711. || sortMethod == sortByManufacturer)
  23712. {
  23713. String lastSubMenuName;
  23714. PopupMenu sub;
  23715. for (int i = 0; i < sorted.size(); ++i)
  23716. {
  23717. const PluginDescription* const pd = sorted.getUnchecked(i);
  23718. String thisSubMenuName (sortMethod == sortByCategory ? pd->category
  23719. : pd->manufacturerName);
  23720. if (! thisSubMenuName.containsNonWhitespaceChars())
  23721. thisSubMenuName = "Other";
  23722. if (thisSubMenuName != lastSubMenuName)
  23723. {
  23724. if (sub.getNumItems() > 0)
  23725. {
  23726. menu.addSubMenu (lastSubMenuName, sub);
  23727. sub.clear();
  23728. }
  23729. lastSubMenuName = thisSubMenuName;
  23730. }
  23731. sub.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  23732. }
  23733. if (sub.getNumItems() > 0)
  23734. menu.addSubMenu (lastSubMenuName, sub);
  23735. }
  23736. else if (sortMethod == sortByFileSystemLocation)
  23737. {
  23738. PluginFilesystemTree root;
  23739. root.buildTree (sorted);
  23740. root.addToMenu (menu, types);
  23741. }
  23742. else
  23743. {
  23744. for (int i = 0; i < sorted.size(); ++i)
  23745. {
  23746. const PluginDescription* const pd = sorted.getUnchecked(i);
  23747. menu.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  23748. }
  23749. }
  23750. }
  23751. int KnownPluginList::getIndexChosenByMenu (const int menuResultCode) const
  23752. {
  23753. const int i = menuResultCode - menuIdBase;
  23754. return (((unsigned int) i) < (unsigned int) types.size()) ? i : -1;
  23755. }
  23756. END_JUCE_NAMESPACE
  23757. /*** End of inlined file: juce_KnownPluginList.cpp ***/
  23758. /*** Start of inlined file: juce_PluginDescription.cpp ***/
  23759. BEGIN_JUCE_NAMESPACE
  23760. PluginDescription::PluginDescription() throw()
  23761. : uid (0),
  23762. isInstrument (false),
  23763. numInputChannels (0),
  23764. numOutputChannels (0)
  23765. {
  23766. }
  23767. PluginDescription::~PluginDescription() throw()
  23768. {
  23769. }
  23770. PluginDescription::PluginDescription (const PluginDescription& other) throw()
  23771. : name (other.name),
  23772. pluginFormatName (other.pluginFormatName),
  23773. category (other.category),
  23774. manufacturerName (other.manufacturerName),
  23775. version (other.version),
  23776. fileOrIdentifier (other.fileOrIdentifier),
  23777. lastFileModTime (other.lastFileModTime),
  23778. uid (other.uid),
  23779. isInstrument (other.isInstrument),
  23780. numInputChannels (other.numInputChannels),
  23781. numOutputChannels (other.numOutputChannels)
  23782. {
  23783. }
  23784. PluginDescription& PluginDescription::operator= (const PluginDescription& other) throw()
  23785. {
  23786. name = other.name;
  23787. pluginFormatName = other.pluginFormatName;
  23788. category = other.category;
  23789. manufacturerName = other.manufacturerName;
  23790. version = other.version;
  23791. fileOrIdentifier = other.fileOrIdentifier;
  23792. uid = other.uid;
  23793. isInstrument = other.isInstrument;
  23794. lastFileModTime = other.lastFileModTime;
  23795. numInputChannels = other.numInputChannels;
  23796. numOutputChannels = other.numOutputChannels;
  23797. return *this;
  23798. }
  23799. bool PluginDescription::isDuplicateOf (const PluginDescription& other) const
  23800. {
  23801. return fileOrIdentifier == other.fileOrIdentifier
  23802. && uid == other.uid;
  23803. }
  23804. const String PluginDescription::createIdentifierString() const throw()
  23805. {
  23806. return pluginFormatName
  23807. + "-" + name
  23808. + "-" + String::toHexString (fileOrIdentifier.hashCode())
  23809. + "-" + String::toHexString (uid);
  23810. }
  23811. XmlElement* PluginDescription::createXml() const
  23812. {
  23813. XmlElement* const e = new XmlElement ("PLUGIN");
  23814. e->setAttribute ("name", name);
  23815. e->setAttribute ("format", pluginFormatName);
  23816. e->setAttribute ("category", category);
  23817. e->setAttribute ("manufacturer", manufacturerName);
  23818. e->setAttribute ("version", version);
  23819. e->setAttribute ("file", fileOrIdentifier);
  23820. e->setAttribute ("uid", String::toHexString (uid));
  23821. e->setAttribute ("isInstrument", isInstrument);
  23822. e->setAttribute ("fileTime", String::toHexString (lastFileModTime.toMilliseconds()));
  23823. e->setAttribute ("numInputs", numInputChannels);
  23824. e->setAttribute ("numOutputs", numOutputChannels);
  23825. return e;
  23826. }
  23827. bool PluginDescription::loadFromXml (const XmlElement& xml)
  23828. {
  23829. if (xml.hasTagName ("PLUGIN"))
  23830. {
  23831. name = xml.getStringAttribute ("name");
  23832. pluginFormatName = xml.getStringAttribute ("format");
  23833. category = xml.getStringAttribute ("category");
  23834. manufacturerName = xml.getStringAttribute ("manufacturer");
  23835. version = xml.getStringAttribute ("version");
  23836. fileOrIdentifier = xml.getStringAttribute ("file");
  23837. uid = xml.getStringAttribute ("uid").getHexValue32();
  23838. isInstrument = xml.getBoolAttribute ("isInstrument", false);
  23839. lastFileModTime = Time (xml.getStringAttribute ("fileTime").getHexValue64());
  23840. numInputChannels = xml.getIntAttribute ("numInputs");
  23841. numOutputChannels = xml.getIntAttribute ("numOutputs");
  23842. return true;
  23843. }
  23844. return false;
  23845. }
  23846. END_JUCE_NAMESPACE
  23847. /*** End of inlined file: juce_PluginDescription.cpp ***/
  23848. /*** Start of inlined file: juce_PluginDirectoryScanner.cpp ***/
  23849. BEGIN_JUCE_NAMESPACE
  23850. PluginDirectoryScanner::PluginDirectoryScanner (KnownPluginList& listToAddTo,
  23851. AudioPluginFormat& formatToLookFor,
  23852. FileSearchPath directoriesToSearch,
  23853. const bool recursive,
  23854. const File& deadMansPedalFile_)
  23855. : list (listToAddTo),
  23856. format (formatToLookFor),
  23857. deadMansPedalFile (deadMansPedalFile_),
  23858. nextIndex (0),
  23859. progress (0)
  23860. {
  23861. directoriesToSearch.removeRedundantPaths();
  23862. filesOrIdentifiersToScan = format.searchPathsForPlugins (directoriesToSearch, recursive);
  23863. // If any plugins have crashed recently when being loaded, move them to the
  23864. // end of the list to give the others a chance to load correctly..
  23865. const StringArray crashedPlugins (getDeadMansPedalFile());
  23866. for (int i = 0; i < crashedPlugins.size(); ++i)
  23867. {
  23868. const String f = crashedPlugins[i];
  23869. for (int j = filesOrIdentifiersToScan.size(); --j >= 0;)
  23870. if (f == filesOrIdentifiersToScan[j])
  23871. filesOrIdentifiersToScan.move (j, -1);
  23872. }
  23873. }
  23874. PluginDirectoryScanner::~PluginDirectoryScanner()
  23875. {
  23876. }
  23877. const String PluginDirectoryScanner::getNextPluginFileThatWillBeScanned() const throw()
  23878. {
  23879. return format.getNameOfPluginFromIdentifier (filesOrIdentifiersToScan [nextIndex]);
  23880. }
  23881. bool PluginDirectoryScanner::scanNextFile (const bool dontRescanIfAlreadyInList)
  23882. {
  23883. String file (filesOrIdentifiersToScan [nextIndex]);
  23884. if (file.isNotEmpty())
  23885. {
  23886. if (! list.isListingUpToDate (file))
  23887. {
  23888. OwnedArray <PluginDescription> typesFound;
  23889. // Add this plugin to the end of the dead-man's pedal list in case it crashes...
  23890. StringArray crashedPlugins (getDeadMansPedalFile());
  23891. crashedPlugins.removeString (file);
  23892. crashedPlugins.add (file);
  23893. setDeadMansPedalFile (crashedPlugins);
  23894. list.scanAndAddFile (file,
  23895. dontRescanIfAlreadyInList,
  23896. typesFound,
  23897. format);
  23898. // Managed to load without crashing, so remove it from the dead-man's-pedal..
  23899. crashedPlugins.removeString (file);
  23900. setDeadMansPedalFile (crashedPlugins);
  23901. if (typesFound.size() == 0)
  23902. failedFiles.add (file);
  23903. }
  23904. ++nextIndex;
  23905. progress = nextIndex / (float) filesOrIdentifiersToScan.size();
  23906. }
  23907. return nextIndex < filesOrIdentifiersToScan.size();
  23908. }
  23909. const StringArray PluginDirectoryScanner::getDeadMansPedalFile() throw()
  23910. {
  23911. StringArray lines;
  23912. if (deadMansPedalFile != File::nonexistent)
  23913. {
  23914. lines.addLines (deadMansPedalFile.loadFileAsString());
  23915. lines.removeEmptyStrings();
  23916. }
  23917. return lines;
  23918. }
  23919. void PluginDirectoryScanner::setDeadMansPedalFile (const StringArray& newContents) throw()
  23920. {
  23921. if (deadMansPedalFile != File::nonexistent)
  23922. deadMansPedalFile.replaceWithText (newContents.joinIntoString ("\n"), true, true);
  23923. }
  23924. END_JUCE_NAMESPACE
  23925. /*** End of inlined file: juce_PluginDirectoryScanner.cpp ***/
  23926. /*** Start of inlined file: juce_PluginListComponent.cpp ***/
  23927. BEGIN_JUCE_NAMESPACE
  23928. PluginListComponent::PluginListComponent (KnownPluginList& listToEdit,
  23929. const File& deadMansPedalFile_,
  23930. PropertiesFile* const propertiesToUse_)
  23931. : list (listToEdit),
  23932. deadMansPedalFile (deadMansPedalFile_),
  23933. propertiesToUse (propertiesToUse_)
  23934. {
  23935. addAndMakeVisible (listBox = new ListBox (String::empty, this));
  23936. addAndMakeVisible (optionsButton = new TextButton ("Options..."));
  23937. optionsButton->addButtonListener (this);
  23938. optionsButton->setTriggeredOnMouseDown (true);
  23939. setSize (400, 600);
  23940. list.addChangeListener (this);
  23941. }
  23942. PluginListComponent::~PluginListComponent()
  23943. {
  23944. list.removeChangeListener (this);
  23945. deleteAllChildren();
  23946. }
  23947. void PluginListComponent::resized()
  23948. {
  23949. listBox->setBounds (0, 0, getWidth(), getHeight() - 30);
  23950. optionsButton->changeWidthToFitText (24);
  23951. optionsButton->setTopLeftPosition (8, getHeight() - 28);
  23952. }
  23953. void PluginListComponent::changeListenerCallback (void*)
  23954. {
  23955. listBox->updateContent();
  23956. listBox->repaint();
  23957. }
  23958. int PluginListComponent::getNumRows()
  23959. {
  23960. return list.getNumTypes();
  23961. }
  23962. void PluginListComponent::paintListBoxItem (int row,
  23963. Graphics& g,
  23964. int width, int height,
  23965. bool rowIsSelected)
  23966. {
  23967. if (rowIsSelected)
  23968. g.fillAll (findColour (TextEditor::highlightColourId));
  23969. const PluginDescription* const pd = list.getType (row);
  23970. if (pd != 0)
  23971. {
  23972. GlyphArrangement ga;
  23973. ga.addCurtailedLineOfText (Font (height * 0.7f, Font::bold), pd->name, 8.0f, height * 0.8f, width - 10.0f, true);
  23974. g.setColour (Colours::black);
  23975. ga.draw (g);
  23976. const Rectangle<float> bb (ga.getBoundingBox (0, -1, false));
  23977. String desc;
  23978. desc << pd->pluginFormatName
  23979. << (pd->isInstrument ? " instrument" : " effect")
  23980. << " - "
  23981. << pd->numInputChannels << (pd->numInputChannels == 1 ? " in" : " ins")
  23982. << " / "
  23983. << pd->numOutputChannels << (pd->numOutputChannels == 1 ? " out" : " outs");
  23984. if (pd->manufacturerName.isNotEmpty())
  23985. desc << " - " << pd->manufacturerName;
  23986. if (pd->version.isNotEmpty())
  23987. desc << " - " << pd->version;
  23988. if (pd->category.isNotEmpty())
  23989. desc << " - category: '" << pd->category << '\'';
  23990. g.setColour (Colours::grey);
  23991. ga.clear();
  23992. ga.addCurtailedLineOfText (Font (height * 0.6f), desc, bb.getRight() + 10.0f, height * 0.8f, width - bb.getRight() - 12.0f, true);
  23993. ga.draw (g);
  23994. }
  23995. }
  23996. void PluginListComponent::deleteKeyPressed (int lastRowSelected)
  23997. {
  23998. list.removeType (lastRowSelected);
  23999. }
  24000. void PluginListComponent::buttonClicked (Button* b)
  24001. {
  24002. if (optionsButton == b)
  24003. {
  24004. PopupMenu menu;
  24005. menu.addItem (1, TRANS("Clear list"));
  24006. menu.addItem (5, TRANS("Remove selected plugin from list"), listBox->getNumSelectedRows() > 0);
  24007. menu.addItem (6, TRANS("Show folder containing selected plugin"), listBox->getNumSelectedRows() > 0);
  24008. menu.addItem (7, TRANS("Remove any plugins whose files no longer exist"));
  24009. menu.addSeparator();
  24010. menu.addItem (2, TRANS("Sort alphabetically"));
  24011. menu.addItem (3, TRANS("Sort by category"));
  24012. menu.addItem (4, TRANS("Sort by manufacturer"));
  24013. menu.addSeparator();
  24014. for (int i = 0; i < AudioPluginFormatManager::getInstance()->getNumFormats(); ++i)
  24015. {
  24016. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (i);
  24017. if (format->getDefaultLocationsToSearch().getNumPaths() > 0)
  24018. menu.addItem (10 + i, "Scan for new or updated " + format->getName() + " plugins...");
  24019. }
  24020. const int r = menu.showAt (optionsButton);
  24021. if (r == 1)
  24022. {
  24023. list.clear();
  24024. }
  24025. else if (r == 2)
  24026. {
  24027. list.sort (KnownPluginList::sortAlphabetically);
  24028. }
  24029. else if (r == 3)
  24030. {
  24031. list.sort (KnownPluginList::sortByCategory);
  24032. }
  24033. else if (r == 4)
  24034. {
  24035. list.sort (KnownPluginList::sortByManufacturer);
  24036. }
  24037. else if (r == 5)
  24038. {
  24039. const SparseSet <int> selected (listBox->getSelectedRows());
  24040. for (int i = list.getNumTypes(); --i >= 0;)
  24041. if (selected.contains (i))
  24042. list.removeType (i);
  24043. }
  24044. else if (r == 6)
  24045. {
  24046. const PluginDescription* const desc = list.getType (listBox->getSelectedRow());
  24047. if (desc != 0)
  24048. {
  24049. if (File (desc->fileOrIdentifier).existsAsFile())
  24050. File (desc->fileOrIdentifier).getParentDirectory().startAsProcess();
  24051. }
  24052. }
  24053. else if (r == 7)
  24054. {
  24055. for (int i = list.getNumTypes(); --i >= 0;)
  24056. {
  24057. if (! AudioPluginFormatManager::getInstance()->doesPluginStillExist (*list.getType (i)))
  24058. {
  24059. list.removeType (i);
  24060. }
  24061. }
  24062. }
  24063. else if (r != 0)
  24064. {
  24065. typeToScan = r - 10;
  24066. startTimer (1);
  24067. }
  24068. }
  24069. }
  24070. void PluginListComponent::timerCallback()
  24071. {
  24072. stopTimer();
  24073. scanFor (AudioPluginFormatManager::getInstance()->getFormat (typeToScan));
  24074. }
  24075. bool PluginListComponent::isInterestedInFileDrag (const StringArray& /*files*/)
  24076. {
  24077. return true;
  24078. }
  24079. void PluginListComponent::filesDropped (const StringArray& files, int, int)
  24080. {
  24081. OwnedArray <PluginDescription> typesFound;
  24082. list.scanAndAddDragAndDroppedFiles (files, typesFound);
  24083. }
  24084. void PluginListComponent::scanFor (AudioPluginFormat* format)
  24085. {
  24086. if (format == 0)
  24087. return;
  24088. FileSearchPath path (format->getDefaultLocationsToSearch());
  24089. if (propertiesToUse != 0)
  24090. path = propertiesToUse->getValue ("lastPluginScanPath_" + format->getName(), path.toString());
  24091. {
  24092. AlertWindow aw (TRANS("Select folders to scan..."), String::empty, AlertWindow::NoIcon);
  24093. FileSearchPathListComponent pathList;
  24094. pathList.setSize (500, 300);
  24095. pathList.setPath (path);
  24096. aw.addCustomComponent (&pathList);
  24097. aw.addButton (TRANS("Scan"), 1, KeyPress::returnKey);
  24098. aw.addButton (TRANS("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  24099. if (aw.runModalLoop() == 0)
  24100. return;
  24101. path = pathList.getPath();
  24102. }
  24103. if (propertiesToUse != 0)
  24104. {
  24105. propertiesToUse->setValue ("lastPluginScanPath_" + format->getName(), path.toString());
  24106. propertiesToUse->saveIfNeeded();
  24107. }
  24108. double progress = 0.0;
  24109. AlertWindow aw (TRANS("Scanning for plugins..."),
  24110. TRANS("Searching for all possible plugin files..."), AlertWindow::NoIcon);
  24111. aw.addButton (TRANS("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  24112. aw.addProgressBarComponent (progress);
  24113. aw.enterModalState();
  24114. MessageManager::getInstance()->runDispatchLoopUntil (300);
  24115. PluginDirectoryScanner scanner (list, *format, path, true, deadMansPedalFile);
  24116. for (;;)
  24117. {
  24118. aw.setMessage (TRANS("Testing:\n\n")
  24119. + scanner.getNextPluginFileThatWillBeScanned());
  24120. MessageManager::getInstance()->runDispatchLoopUntil (20);
  24121. if (! scanner.scanNextFile (true))
  24122. break;
  24123. if (! aw.isCurrentlyModal())
  24124. break;
  24125. progress = scanner.getProgress();
  24126. }
  24127. if (scanner.getFailedFiles().size() > 0)
  24128. {
  24129. StringArray shortNames;
  24130. for (int i = 0; i < scanner.getFailedFiles().size(); ++i)
  24131. shortNames.add (File (scanner.getFailedFiles()[i]).getFileName());
  24132. AlertWindow::showMessageBox (AlertWindow::InfoIcon,
  24133. TRANS("Scan complete"),
  24134. TRANS("Note that the following files appeared to be plugin files, but failed to load correctly:\n\n")
  24135. + shortNames.joinIntoString (", "));
  24136. }
  24137. }
  24138. END_JUCE_NAMESPACE
  24139. /*** End of inlined file: juce_PluginListComponent.cpp ***/
  24140. /*** Start of inlined file: juce_AudioUnitPluginFormat.mm ***/
  24141. #if JUCE_PLUGINHOST_AU && ! (JUCE_LINUX || JUCE_WINDOWS)
  24142. #include <AudioUnit/AudioUnit.h>
  24143. #include <AudioUnit/AUCocoaUIView.h>
  24144. #include <CoreAudioKit/AUGenericView.h>
  24145. #if JUCE_SUPPORT_CARBON
  24146. #include <AudioToolbox/AudioUnitUtilities.h>
  24147. #include <AudioUnit/AudioUnitCarbonView.h>
  24148. #endif
  24149. BEGIN_JUCE_NAMESPACE
  24150. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  24151. #endif
  24152. #if JUCE_MAC
  24153. // Change this to disable logging of various activities
  24154. #ifndef AU_LOGGING
  24155. #define AU_LOGGING 1
  24156. #endif
  24157. #if AU_LOGGING
  24158. #define log(a) Logger::writeToLog(a);
  24159. #else
  24160. #define log(a)
  24161. #endif
  24162. static int insideCallback = 0;
  24163. static const String osTypeToString (OSType type)
  24164. {
  24165. char s[4];
  24166. s[0] = (char) (((uint32) type) >> 24);
  24167. s[1] = (char) (((uint32) type) >> 16);
  24168. s[2] = (char) (((uint32) type) >> 8);
  24169. s[3] = (char) ((uint32) type);
  24170. return String (s, 4);
  24171. }
  24172. static OSType stringToOSType (const String& s1)
  24173. {
  24174. const String s (s1 + " ");
  24175. return (((OSType) (unsigned char) s[0]) << 24)
  24176. | (((OSType) (unsigned char) s[1]) << 16)
  24177. | (((OSType) (unsigned char) s[2]) << 8)
  24178. | ((OSType) (unsigned char) s[3]);
  24179. }
  24180. static const char* auIdentifierPrefix = "AudioUnit:";
  24181. static const String createAUPluginIdentifier (const ComponentDescription& desc)
  24182. {
  24183. jassert (osTypeToString ('abcd') == "abcd"); // agh, must have got the endianness wrong..
  24184. jassert (stringToOSType ("abcd") == (OSType) 'abcd'); // ditto
  24185. String s (auIdentifierPrefix);
  24186. if (desc.componentType == kAudioUnitType_MusicDevice)
  24187. s << "Synths/";
  24188. else if (desc.componentType == kAudioUnitType_MusicEffect
  24189. || desc.componentType == kAudioUnitType_Effect)
  24190. s << "Effects/";
  24191. else if (desc.componentType == kAudioUnitType_Generator)
  24192. s << "Generators/";
  24193. else if (desc.componentType == kAudioUnitType_Panner)
  24194. s << "Panners/";
  24195. s << osTypeToString (desc.componentType) << ","
  24196. << osTypeToString (desc.componentSubType) << ","
  24197. << osTypeToString (desc.componentManufacturer);
  24198. return s;
  24199. }
  24200. static void getAUDetails (ComponentRecord* comp, String& name, String& manufacturer)
  24201. {
  24202. Handle componentNameHandle = NewHandle (sizeof (void*));
  24203. Handle componentInfoHandle = NewHandle (sizeof (void*));
  24204. if (componentNameHandle != 0 && componentInfoHandle != 0)
  24205. {
  24206. ComponentDescription desc;
  24207. if (GetComponentInfo (comp, &desc, componentNameHandle, componentInfoHandle, 0) == noErr)
  24208. {
  24209. ConstStr255Param nameString = (ConstStr255Param) (*componentNameHandle);
  24210. ConstStr255Param infoString = (ConstStr255Param) (*componentInfoHandle);
  24211. if (nameString != 0 && nameString[0] != 0)
  24212. {
  24213. const String all ((const char*) nameString + 1, nameString[0]);
  24214. DBG ("name: "+ all);
  24215. manufacturer = all.upToFirstOccurrenceOf (":", false, false).trim();
  24216. name = all.fromFirstOccurrenceOf (":", false, false).trim();
  24217. }
  24218. if (infoString != 0 && infoString[0] != 0)
  24219. {
  24220. DBG ("info: " + String ((const char*) infoString + 1, infoString[0]));
  24221. }
  24222. if (name.isEmpty())
  24223. name = "<Unknown>";
  24224. }
  24225. DisposeHandle (componentNameHandle);
  24226. DisposeHandle (componentInfoHandle);
  24227. }
  24228. }
  24229. static bool getComponentDescFromIdentifier (const String& fileOrIdentifier, ComponentDescription& desc,
  24230. String& name, String& version, String& manufacturer)
  24231. {
  24232. zerostruct (desc);
  24233. if (fileOrIdentifier.startsWithIgnoreCase (auIdentifierPrefix))
  24234. {
  24235. String s (fileOrIdentifier.substring (jmax (fileOrIdentifier.lastIndexOfChar (':'),
  24236. fileOrIdentifier.lastIndexOfChar ('/')) + 1));
  24237. StringArray tokens;
  24238. tokens.addTokens (s, ",", String::empty);
  24239. tokens.trim();
  24240. tokens.removeEmptyStrings();
  24241. if (tokens.size() == 3)
  24242. {
  24243. desc.componentType = stringToOSType (tokens[0]);
  24244. desc.componentSubType = stringToOSType (tokens[1]);
  24245. desc.componentManufacturer = stringToOSType (tokens[2]);
  24246. ComponentRecord* comp = FindNextComponent (0, &desc);
  24247. if (comp != 0)
  24248. {
  24249. getAUDetails (comp, name, manufacturer);
  24250. return true;
  24251. }
  24252. }
  24253. }
  24254. return false;
  24255. }
  24256. class AudioUnitPluginWindowCarbon;
  24257. class AudioUnitPluginWindowCocoa;
  24258. class AudioUnitPluginInstance : public AudioPluginInstance
  24259. {
  24260. public:
  24261. ~AudioUnitPluginInstance();
  24262. // AudioPluginInstance methods:
  24263. void fillInPluginDescription (PluginDescription& desc) const
  24264. {
  24265. desc.name = pluginName;
  24266. desc.fileOrIdentifier = createAUPluginIdentifier (componentDesc);
  24267. desc.uid = ((int) componentDesc.componentType)
  24268. ^ ((int) componentDesc.componentSubType)
  24269. ^ ((int) componentDesc.componentManufacturer);
  24270. desc.lastFileModTime = 0;
  24271. desc.pluginFormatName = "AudioUnit";
  24272. desc.category = getCategory();
  24273. desc.manufacturerName = manufacturer;
  24274. desc.version = version;
  24275. desc.numInputChannels = getNumInputChannels();
  24276. desc.numOutputChannels = getNumOutputChannels();
  24277. desc.isInstrument = (componentDesc.componentType == kAudioUnitType_MusicDevice);
  24278. }
  24279. const String getName() const { return pluginName; }
  24280. bool acceptsMidi() const { return wantsMidiMessages; }
  24281. bool producesMidi() const { return false; }
  24282. // AudioProcessor methods:
  24283. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  24284. void releaseResources();
  24285. void processBlock (AudioSampleBuffer& buffer,
  24286. MidiBuffer& midiMessages);
  24287. AudioProcessorEditor* createEditor();
  24288. const String getInputChannelName (const int index) const;
  24289. bool isInputChannelStereoPair (int index) const;
  24290. const String getOutputChannelName (const int index) const;
  24291. bool isOutputChannelStereoPair (int index) const;
  24292. int getNumParameters();
  24293. float getParameter (int index);
  24294. void setParameter (int index, float newValue);
  24295. const String getParameterName (int index);
  24296. const String getParameterText (int index);
  24297. bool isParameterAutomatable (int index) const;
  24298. int getNumPrograms();
  24299. int getCurrentProgram();
  24300. void setCurrentProgram (int index);
  24301. const String getProgramName (int index);
  24302. void changeProgramName (int index, const String& newName);
  24303. void getStateInformation (MemoryBlock& destData);
  24304. void getCurrentProgramStateInformation (MemoryBlock& destData);
  24305. void setStateInformation (const void* data, int sizeInBytes);
  24306. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  24307. juce_UseDebuggingNewOperator
  24308. private:
  24309. friend class AudioUnitPluginWindowCarbon;
  24310. friend class AudioUnitPluginWindowCocoa;
  24311. friend class AudioUnitPluginFormat;
  24312. ComponentDescription componentDesc;
  24313. String pluginName, manufacturer, version;
  24314. String fileOrIdentifier;
  24315. CriticalSection lock;
  24316. bool initialised, wantsMidiMessages, wasPlaying;
  24317. HeapBlock <AudioBufferList> outputBufferList;
  24318. AudioTimeStamp timeStamp;
  24319. AudioSampleBuffer* currentBuffer;
  24320. AudioUnit audioUnit;
  24321. Array <int> parameterIds;
  24322. bool getComponentDescFromFile (const String& fileOrIdentifier);
  24323. void initialise();
  24324. OSStatus renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  24325. const AudioTimeStamp* inTimeStamp,
  24326. UInt32 inBusNumber,
  24327. UInt32 inNumberFrames,
  24328. AudioBufferList* ioData) const;
  24329. static OSStatus renderGetInputCallback (void* inRefCon,
  24330. AudioUnitRenderActionFlags* ioActionFlags,
  24331. const AudioTimeStamp* inTimeStamp,
  24332. UInt32 inBusNumber,
  24333. UInt32 inNumberFrames,
  24334. AudioBufferList* ioData)
  24335. {
  24336. return ((AudioUnitPluginInstance*) inRefCon)
  24337. ->renderGetInput (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  24338. }
  24339. OSStatus getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const;
  24340. OSStatus getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat, Float32* outTimeSig_Numerator,
  24341. UInt32* outTimeSig_Denominator, Float64* outCurrentMeasureDownBeat) const;
  24342. OSStatus getTransportState (Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  24343. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  24344. Float64* outCycleStartBeat, Float64* outCycleEndBeat);
  24345. static OSStatus getBeatAndTempoCallback (void* inHostUserData, Float64* outCurrentBeat, Float64* outCurrentTempo)
  24346. {
  24347. return ((AudioUnitPluginInstance*) inHostUserData)->getBeatAndTempo (outCurrentBeat, outCurrentTempo);
  24348. }
  24349. static OSStatus getMusicalTimeLocationCallback (void* inHostUserData, UInt32* outDeltaSampleOffsetToNextBeat,
  24350. Float32* outTimeSig_Numerator, UInt32* outTimeSig_Denominator,
  24351. Float64* outCurrentMeasureDownBeat)
  24352. {
  24353. return ((AudioUnitPluginInstance*) inHostUserData)
  24354. ->getMusicalTimeLocation (outDeltaSampleOffsetToNextBeat, outTimeSig_Numerator,
  24355. outTimeSig_Denominator, outCurrentMeasureDownBeat);
  24356. }
  24357. static OSStatus getTransportStateCallback (void* inHostUserData, Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  24358. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  24359. Float64* outCycleStartBeat, Float64* outCycleEndBeat)
  24360. {
  24361. return ((AudioUnitPluginInstance*) inHostUserData)
  24362. ->getTransportState (outIsPlaying, outTransportStateChanged,
  24363. outCurrentSampleInTimeLine, outIsCycling,
  24364. outCycleStartBeat, outCycleEndBeat);
  24365. }
  24366. void getNumChannels (int& numIns, int& numOuts)
  24367. {
  24368. numIns = 0;
  24369. numOuts = 0;
  24370. AUChannelInfo supportedChannels [128];
  24371. UInt32 supportedChannelsSize = sizeof (supportedChannels);
  24372. if (AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SupportedNumChannels, kAudioUnitScope_Global,
  24373. 0, supportedChannels, &supportedChannelsSize) == noErr
  24374. && supportedChannelsSize > 0)
  24375. {
  24376. for (int i = 0; i < supportedChannelsSize / sizeof (AUChannelInfo); ++i)
  24377. {
  24378. numIns = jmax (numIns, (int) supportedChannels[i].inChannels);
  24379. numOuts = jmax (numOuts, (int) supportedChannels[i].outChannels);
  24380. }
  24381. }
  24382. else
  24383. {
  24384. // (this really means the plugin will take any number of ins/outs as long
  24385. // as they are the same)
  24386. numIns = numOuts = 2;
  24387. }
  24388. }
  24389. const String getCategory() const;
  24390. AudioUnitPluginInstance (const String& fileOrIdentifier);
  24391. };
  24392. AudioUnitPluginInstance::AudioUnitPluginInstance (const String& fileOrIdentifier)
  24393. : fileOrIdentifier (fileOrIdentifier),
  24394. initialised (false),
  24395. wantsMidiMessages (false),
  24396. audioUnit (0),
  24397. currentBuffer (0)
  24398. {
  24399. try
  24400. {
  24401. ++insideCallback;
  24402. log ("Opening AU: " + fileOrIdentifier);
  24403. if (getComponentDescFromFile (fileOrIdentifier))
  24404. {
  24405. ComponentRecord* const comp = FindNextComponent (0, &componentDesc);
  24406. if (comp != 0)
  24407. {
  24408. audioUnit = (AudioUnit) OpenComponent (comp);
  24409. wantsMidiMessages = componentDesc.componentType == kAudioUnitType_MusicDevice
  24410. || componentDesc.componentType == kAudioUnitType_MusicEffect;
  24411. }
  24412. }
  24413. --insideCallback;
  24414. }
  24415. catch (...)
  24416. {
  24417. --insideCallback;
  24418. }
  24419. }
  24420. AudioUnitPluginInstance::~AudioUnitPluginInstance()
  24421. {
  24422. const ScopedLock sl (lock);
  24423. jassert (insideCallback == 0);
  24424. if (audioUnit != 0)
  24425. {
  24426. AudioUnitUninitialize (audioUnit);
  24427. CloseComponent (audioUnit);
  24428. audioUnit = 0;
  24429. }
  24430. }
  24431. bool AudioUnitPluginInstance::getComponentDescFromFile (const String& fileOrIdentifier)
  24432. {
  24433. zerostruct (componentDesc);
  24434. if (getComponentDescFromIdentifier (fileOrIdentifier, componentDesc, pluginName, version, manufacturer))
  24435. return true;
  24436. const File file (fileOrIdentifier);
  24437. if (! file.hasFileExtension (".component"))
  24438. return false;
  24439. const char* const utf8 = fileOrIdentifier.toUTF8();
  24440. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  24441. strlen (utf8), file.isDirectory());
  24442. if (url != 0)
  24443. {
  24444. CFBundleRef bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  24445. CFRelease (url);
  24446. if (bundleRef != 0)
  24447. {
  24448. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  24449. if (name != 0 && CFGetTypeID (name) == CFStringGetTypeID())
  24450. pluginName = PlatformUtilities::cfStringToJuceString ((CFStringRef) name);
  24451. if (pluginName.isEmpty())
  24452. pluginName = file.getFileNameWithoutExtension();
  24453. CFTypeRef versionString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleVersion"));
  24454. if (versionString != 0 && CFGetTypeID (versionString) == CFStringGetTypeID())
  24455. version = PlatformUtilities::cfStringToJuceString ((CFStringRef) versionString);
  24456. CFTypeRef manuString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleGetInfoString"));
  24457. if (manuString != 0 && CFGetTypeID (manuString) == CFStringGetTypeID())
  24458. manufacturer = PlatformUtilities::cfStringToJuceString ((CFStringRef) manuString);
  24459. short resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  24460. UseResFile (resFileId);
  24461. for (int i = 1; i <= Count1Resources ('thng'); ++i)
  24462. {
  24463. Handle h = Get1IndResource ('thng', i);
  24464. if (h != 0)
  24465. {
  24466. HLock (h);
  24467. const uint32* const types = (const uint32*) *h;
  24468. if (types[0] == kAudioUnitType_MusicDevice
  24469. || types[0] == kAudioUnitType_MusicEffect
  24470. || types[0] == kAudioUnitType_Effect
  24471. || types[0] == kAudioUnitType_Generator
  24472. || types[0] == kAudioUnitType_Panner)
  24473. {
  24474. componentDesc.componentType = types[0];
  24475. componentDesc.componentSubType = types[1];
  24476. componentDesc.componentManufacturer = types[2];
  24477. break;
  24478. }
  24479. HUnlock (h);
  24480. ReleaseResource (h);
  24481. }
  24482. }
  24483. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  24484. CFRelease (bundleRef);
  24485. }
  24486. }
  24487. return componentDesc.componentType != 0 && componentDesc.componentSubType != 0;
  24488. }
  24489. void AudioUnitPluginInstance::initialise()
  24490. {
  24491. if (initialised || audioUnit == 0)
  24492. return;
  24493. log ("Initialising AU: " + pluginName);
  24494. parameterIds.clear();
  24495. {
  24496. UInt32 paramListSize = 0;
  24497. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  24498. 0, 0, &paramListSize);
  24499. if (paramListSize > 0)
  24500. {
  24501. parameterIds.insertMultiple (0, 0, paramListSize / sizeof (int));
  24502. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  24503. 0, &parameterIds.getReference(0), &paramListSize);
  24504. }
  24505. }
  24506. {
  24507. AURenderCallbackStruct info;
  24508. zerostruct (info);
  24509. info.inputProcRefCon = this;
  24510. info.inputProc = renderGetInputCallback;
  24511. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
  24512. 0, &info, sizeof (info));
  24513. }
  24514. {
  24515. HostCallbackInfo info;
  24516. zerostruct (info);
  24517. info.hostUserData = this;
  24518. info.beatAndTempoProc = getBeatAndTempoCallback;
  24519. info.musicalTimeLocationProc = getMusicalTimeLocationCallback;
  24520. info.transportStateProc = getTransportStateCallback;
  24521. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_HostCallbacks, kAudioUnitScope_Global,
  24522. 0, &info, sizeof (info));
  24523. }
  24524. int numIns, numOuts;
  24525. getNumChannels (numIns, numOuts);
  24526. setPlayConfigDetails (numIns, numOuts, 0, 0);
  24527. initialised = AudioUnitInitialize (audioUnit) == noErr;
  24528. setLatencySamples (0);
  24529. }
  24530. void AudioUnitPluginInstance::prepareToPlay (double sampleRate_,
  24531. int samplesPerBlockExpected)
  24532. {
  24533. if (audioUnit != 0)
  24534. {
  24535. Float64 sampleRateIn = 0, sampleRateOut = 0;
  24536. UInt32 sampleRateSize = sizeof (sampleRateIn);
  24537. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Input, 0, &sampleRateIn, &sampleRateSize);
  24538. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Output, 0, &sampleRateOut, &sampleRateSize);
  24539. if (sampleRateIn != sampleRate_ || sampleRateOut != sampleRate_)
  24540. {
  24541. if (initialised)
  24542. {
  24543. AudioUnitUninitialize (audioUnit);
  24544. initialised = false;
  24545. }
  24546. Float64 sr = sampleRate_;
  24547. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Input, 0, &sr, sizeof (Float64));
  24548. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Output, 0, &sr, sizeof (Float64));
  24549. }
  24550. }
  24551. initialise();
  24552. if (initialised)
  24553. {
  24554. int numIns, numOuts;
  24555. getNumChannels (numIns, numOuts);
  24556. setPlayConfigDetails (numIns, numOuts, sampleRate_, samplesPerBlockExpected);
  24557. Float64 latencySecs = 0.0;
  24558. UInt32 latencySize = sizeof (latencySecs);
  24559. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_Latency, kAudioUnitScope_Global,
  24560. 0, &latencySecs, &latencySize);
  24561. setLatencySamples (roundToInt (latencySecs * sampleRate_));
  24562. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  24563. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  24564. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  24565. AudioStreamBasicDescription stream;
  24566. zerostruct (stream);
  24567. stream.mSampleRate = sampleRate_;
  24568. stream.mFormatID = kAudioFormatLinearPCM;
  24569. stream.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kAudioFormatFlagIsNonInterleaved;
  24570. stream.mFramesPerPacket = 1;
  24571. stream.mBytesPerPacket = 4;
  24572. stream.mBytesPerFrame = 4;
  24573. stream.mBitsPerChannel = 32;
  24574. stream.mChannelsPerFrame = numIns;
  24575. OSStatus err = AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input,
  24576. 0, &stream, sizeof (stream));
  24577. stream.mChannelsPerFrame = numOuts;
  24578. err = AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output,
  24579. 0, &stream, sizeof (stream));
  24580. outputBufferList.calloc (sizeof (AudioBufferList) + sizeof (AudioBuffer) * (numOuts + 1), 1);
  24581. outputBufferList->mNumberBuffers = numOuts;
  24582. for (int i = numOuts; --i >= 0;)
  24583. outputBufferList->mBuffers[i].mNumberChannels = 1;
  24584. zerostruct (timeStamp);
  24585. timeStamp.mSampleTime = 0;
  24586. timeStamp.mHostTime = AudioGetCurrentHostTime();
  24587. timeStamp.mFlags = kAudioTimeStampSampleTimeValid | kAudioTimeStampHostTimeValid;
  24588. currentBuffer = 0;
  24589. wasPlaying = false;
  24590. }
  24591. }
  24592. void AudioUnitPluginInstance::releaseResources()
  24593. {
  24594. if (initialised)
  24595. {
  24596. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  24597. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  24598. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  24599. outputBufferList.free();
  24600. currentBuffer = 0;
  24601. }
  24602. }
  24603. OSStatus AudioUnitPluginInstance::renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  24604. const AudioTimeStamp* inTimeStamp,
  24605. UInt32 inBusNumber,
  24606. UInt32 inNumberFrames,
  24607. AudioBufferList* ioData) const
  24608. {
  24609. if (inBusNumber == 0
  24610. && currentBuffer != 0)
  24611. {
  24612. jassert (inNumberFrames == currentBuffer->getNumSamples()); // if this ever happens, might need to add extra handling
  24613. for (int i = 0; i < ioData->mNumberBuffers; ++i)
  24614. {
  24615. if (i < currentBuffer->getNumChannels())
  24616. {
  24617. memcpy (ioData->mBuffers[i].mData,
  24618. currentBuffer->getSampleData (i, 0),
  24619. sizeof (float) * inNumberFrames);
  24620. }
  24621. else
  24622. {
  24623. zeromem (ioData->mBuffers[i].mData, sizeof (float) * inNumberFrames);
  24624. }
  24625. }
  24626. }
  24627. return noErr;
  24628. }
  24629. void AudioUnitPluginInstance::processBlock (AudioSampleBuffer& buffer,
  24630. MidiBuffer& midiMessages)
  24631. {
  24632. const int numSamples = buffer.getNumSamples();
  24633. if (initialised)
  24634. {
  24635. AudioUnitRenderActionFlags flags = 0;
  24636. timeStamp.mHostTime = AudioGetCurrentHostTime();
  24637. for (int i = getNumOutputChannels(); --i >= 0;)
  24638. {
  24639. outputBufferList->mBuffers[i].mDataByteSize = sizeof (float) * numSamples;
  24640. outputBufferList->mBuffers[i].mData = buffer.getSampleData (i, 0);
  24641. }
  24642. currentBuffer = &buffer;
  24643. if (wantsMidiMessages)
  24644. {
  24645. const uint8* midiEventData;
  24646. int midiEventSize, midiEventPosition;
  24647. MidiBuffer::Iterator i (midiMessages);
  24648. while (i.getNextEvent (midiEventData, midiEventSize, midiEventPosition))
  24649. {
  24650. if (midiEventSize <= 3)
  24651. MusicDeviceMIDIEvent (audioUnit,
  24652. midiEventData[0], midiEventData[1], midiEventData[2],
  24653. midiEventPosition);
  24654. else
  24655. MusicDeviceSysEx (audioUnit, midiEventData, midiEventSize);
  24656. }
  24657. midiMessages.clear();
  24658. }
  24659. AudioUnitRender (audioUnit, &flags, &timeStamp,
  24660. 0, numSamples, outputBufferList);
  24661. timeStamp.mSampleTime += numSamples;
  24662. }
  24663. else
  24664. {
  24665. // Not initialised, so just bypass..
  24666. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  24667. buffer.clear (i, 0, buffer.getNumSamples());
  24668. }
  24669. }
  24670. OSStatus AudioUnitPluginInstance::getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const
  24671. {
  24672. AudioPlayHead* const ph = getPlayHead();
  24673. AudioPlayHead::CurrentPositionInfo result;
  24674. if (ph != 0 && ph->getCurrentPosition (result))
  24675. {
  24676. if (outCurrentBeat != 0)
  24677. *outCurrentBeat = result.ppqPosition;
  24678. if (outCurrentTempo != 0)
  24679. *outCurrentTempo = result.bpm;
  24680. }
  24681. else
  24682. {
  24683. if (outCurrentBeat != 0)
  24684. *outCurrentBeat = 0;
  24685. if (outCurrentTempo != 0)
  24686. *outCurrentTempo = 120.0;
  24687. }
  24688. return noErr;
  24689. }
  24690. OSStatus AudioUnitPluginInstance::getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat,
  24691. Float32* outTimeSig_Numerator,
  24692. UInt32* outTimeSig_Denominator,
  24693. Float64* outCurrentMeasureDownBeat) const
  24694. {
  24695. AudioPlayHead* const ph = getPlayHead();
  24696. AudioPlayHead::CurrentPositionInfo result;
  24697. if (ph != 0 && ph->getCurrentPosition (result))
  24698. {
  24699. if (outTimeSig_Numerator != 0)
  24700. *outTimeSig_Numerator = result.timeSigNumerator;
  24701. if (outTimeSig_Denominator != 0)
  24702. *outTimeSig_Denominator = result.timeSigDenominator;
  24703. if (outDeltaSampleOffsetToNextBeat != 0)
  24704. *outDeltaSampleOffsetToNextBeat = 0; //xxx
  24705. if (outCurrentMeasureDownBeat != 0)
  24706. *outCurrentMeasureDownBeat = result.ppqPositionOfLastBarStart; //xxx wrong
  24707. }
  24708. else
  24709. {
  24710. if (outDeltaSampleOffsetToNextBeat != 0)
  24711. *outDeltaSampleOffsetToNextBeat = 0;
  24712. if (outTimeSig_Numerator != 0)
  24713. *outTimeSig_Numerator = 4;
  24714. if (outTimeSig_Denominator != 0)
  24715. *outTimeSig_Denominator = 4;
  24716. if (outCurrentMeasureDownBeat != 0)
  24717. *outCurrentMeasureDownBeat = 0;
  24718. }
  24719. return noErr;
  24720. }
  24721. OSStatus AudioUnitPluginInstance::getTransportState (Boolean* outIsPlaying,
  24722. Boolean* outTransportStateChanged,
  24723. Float64* outCurrentSampleInTimeLine,
  24724. Boolean* outIsCycling,
  24725. Float64* outCycleStartBeat,
  24726. Float64* outCycleEndBeat)
  24727. {
  24728. AudioPlayHead* const ph = getPlayHead();
  24729. AudioPlayHead::CurrentPositionInfo result;
  24730. if (ph != 0 && ph->getCurrentPosition (result))
  24731. {
  24732. if (outIsPlaying != 0)
  24733. *outIsPlaying = result.isPlaying;
  24734. if (outTransportStateChanged != 0)
  24735. {
  24736. *outTransportStateChanged = result.isPlaying != wasPlaying;
  24737. wasPlaying = result.isPlaying;
  24738. }
  24739. if (outCurrentSampleInTimeLine != 0)
  24740. *outCurrentSampleInTimeLine = roundToInt (result.timeInSeconds * getSampleRate());
  24741. if (outIsCycling != 0)
  24742. *outIsCycling = false;
  24743. if (outCycleStartBeat != 0)
  24744. *outCycleStartBeat = 0;
  24745. if (outCycleEndBeat != 0)
  24746. *outCycleEndBeat = 0;
  24747. }
  24748. else
  24749. {
  24750. if (outIsPlaying != 0)
  24751. *outIsPlaying = false;
  24752. if (outTransportStateChanged != 0)
  24753. *outTransportStateChanged = false;
  24754. if (outCurrentSampleInTimeLine != 0)
  24755. *outCurrentSampleInTimeLine = 0;
  24756. if (outIsCycling != 0)
  24757. *outIsCycling = false;
  24758. if (outCycleStartBeat != 0)
  24759. *outCycleStartBeat = 0;
  24760. if (outCycleEndBeat != 0)
  24761. *outCycleEndBeat = 0;
  24762. }
  24763. return noErr;
  24764. }
  24765. class AudioUnitPluginWindowCocoa : public AudioProcessorEditor
  24766. {
  24767. public:
  24768. AudioUnitPluginWindowCocoa (AudioUnitPluginInstance& plugin_, const bool createGenericViewIfNeeded)
  24769. : AudioProcessorEditor (&plugin_),
  24770. plugin (plugin_),
  24771. wrapper (0)
  24772. {
  24773. addAndMakeVisible (wrapper = new NSViewComponent());
  24774. setOpaque (true);
  24775. setVisible (true);
  24776. setSize (100, 100);
  24777. createView (createGenericViewIfNeeded);
  24778. }
  24779. ~AudioUnitPluginWindowCocoa()
  24780. {
  24781. const bool wasValid = isValid();
  24782. wrapper->setView (0);
  24783. if (wasValid)
  24784. plugin.editorBeingDeleted (this);
  24785. delete wrapper;
  24786. }
  24787. bool isValid() const { return wrapper->getView() != 0; }
  24788. void paint (Graphics& g)
  24789. {
  24790. g.fillAll (Colours::white);
  24791. }
  24792. void resized()
  24793. {
  24794. wrapper->setSize (getWidth(), getHeight());
  24795. }
  24796. private:
  24797. AudioUnitPluginInstance& plugin;
  24798. NSViewComponent* wrapper;
  24799. bool createView (const bool createGenericViewIfNeeded)
  24800. {
  24801. NSView* pluginView = 0;
  24802. UInt32 dataSize = 0;
  24803. Boolean isWritable = false;
  24804. if (AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  24805. 0, &dataSize, &isWritable) == noErr
  24806. && dataSize != 0
  24807. && AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  24808. 0, &dataSize, &isWritable) == noErr)
  24809. {
  24810. HeapBlock <AudioUnitCocoaViewInfo> info;
  24811. info.calloc (dataSize, 1);
  24812. if (AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  24813. 0, info, &dataSize) == noErr)
  24814. {
  24815. NSString* viewClassName = (NSString*) (info->mCocoaAUViewClass[0]);
  24816. NSString* path = (NSString*) CFURLCopyPath (info->mCocoaAUViewBundleLocation);
  24817. NSBundle* viewBundle = [NSBundle bundleWithPath: [path autorelease]];
  24818. Class viewClass = [viewBundle classNamed: viewClassName];
  24819. if ([viewClass conformsToProtocol: @protocol (AUCocoaUIBase)]
  24820. && [viewClass instancesRespondToSelector: @selector (interfaceVersion)]
  24821. && [viewClass instancesRespondToSelector: @selector (uiViewForAudioUnit: withSize:)])
  24822. {
  24823. id factory = [[[viewClass alloc] init] autorelease];
  24824. pluginView = [factory uiViewForAudioUnit: plugin.audioUnit
  24825. withSize: NSMakeSize (getWidth(), getHeight())];
  24826. }
  24827. for (int i = (dataSize - sizeof (CFURLRef)) / sizeof (CFStringRef); --i >= 0;)
  24828. {
  24829. CFRelease (info->mCocoaAUViewClass[i]);
  24830. CFRelease (info->mCocoaAUViewBundleLocation);
  24831. }
  24832. }
  24833. }
  24834. if (createGenericViewIfNeeded && (pluginView == 0))
  24835. pluginView = [[AUGenericView alloc] initWithAudioUnit: plugin.audioUnit];
  24836. wrapper->setView (pluginView);
  24837. if (pluginView != 0)
  24838. setSize ([pluginView frame].size.width,
  24839. [pluginView frame].size.height);
  24840. return pluginView != 0;
  24841. }
  24842. };
  24843. #if JUCE_SUPPORT_CARBON
  24844. class AudioUnitPluginWindowCarbon : public AudioProcessorEditor
  24845. {
  24846. public:
  24847. AudioUnitPluginWindowCarbon (AudioUnitPluginInstance& plugin_)
  24848. : AudioProcessorEditor (&plugin_),
  24849. plugin (plugin_),
  24850. viewComponent (0)
  24851. {
  24852. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  24853. setOpaque (true);
  24854. setVisible (true);
  24855. setSize (400, 300);
  24856. ComponentDescription viewList [16];
  24857. UInt32 viewListSize = sizeof (viewList);
  24858. AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_GetUIComponentList, kAudioUnitScope_Global,
  24859. 0, &viewList, &viewListSize);
  24860. componentRecord = FindNextComponent (0, &viewList[0]);
  24861. }
  24862. ~AudioUnitPluginWindowCarbon()
  24863. {
  24864. innerWrapper = 0;
  24865. if (isValid())
  24866. plugin.editorBeingDeleted (this);
  24867. }
  24868. bool isValid() const throw() { return componentRecord != 0; }
  24869. void paint (Graphics& g)
  24870. {
  24871. g.fillAll (Colours::black);
  24872. }
  24873. void resized()
  24874. {
  24875. innerWrapper->setSize (getWidth(), getHeight());
  24876. }
  24877. bool keyStateChanged (bool)
  24878. {
  24879. return false;
  24880. }
  24881. bool keyPressed (const KeyPress&)
  24882. {
  24883. return false;
  24884. }
  24885. AudioUnit getAudioUnit() const { return plugin.audioUnit; }
  24886. AudioUnitCarbonView getViewComponent()
  24887. {
  24888. if (viewComponent == 0 && componentRecord != 0)
  24889. viewComponent = (AudioUnitCarbonView) OpenComponent (componentRecord);
  24890. return viewComponent;
  24891. }
  24892. void closeViewComponent()
  24893. {
  24894. if (viewComponent != 0)
  24895. {
  24896. CloseComponent (viewComponent);
  24897. viewComponent = 0;
  24898. }
  24899. }
  24900. juce_UseDebuggingNewOperator
  24901. private:
  24902. AudioUnitPluginInstance& plugin;
  24903. ComponentRecord* componentRecord;
  24904. AudioUnitCarbonView viewComponent;
  24905. class InnerWrapperComponent : public CarbonViewWrapperComponent
  24906. {
  24907. public:
  24908. InnerWrapperComponent (AudioUnitPluginWindowCarbon* const owner_)
  24909. : owner (owner_)
  24910. {
  24911. }
  24912. ~InnerWrapperComponent()
  24913. {
  24914. deleteWindow();
  24915. }
  24916. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  24917. {
  24918. log ("Opening AU GUI: " + owner->plugin.getName());
  24919. AudioUnitCarbonView viewComponent = owner->getViewComponent();
  24920. if (viewComponent == 0)
  24921. return 0;
  24922. Float32Point pos = { 0, 0 };
  24923. Float32Point size = { 250, 200 };
  24924. HIViewRef pluginView = 0;
  24925. AudioUnitCarbonViewCreate (viewComponent,
  24926. owner->getAudioUnit(),
  24927. windowRef,
  24928. rootView,
  24929. &pos,
  24930. &size,
  24931. (ControlRef*) &pluginView);
  24932. return pluginView;
  24933. }
  24934. void removeView (HIViewRef)
  24935. {
  24936. log ("Closing AU GUI: " + owner->plugin.getName());
  24937. owner->closeViewComponent();
  24938. }
  24939. private:
  24940. AudioUnitPluginWindowCarbon* const owner;
  24941. };
  24942. friend class InnerWrapperComponent;
  24943. ScopedPointer<InnerWrapperComponent> innerWrapper;
  24944. };
  24945. #endif
  24946. AudioProcessorEditor* AudioUnitPluginInstance::createEditor()
  24947. {
  24948. ScopedPointer<AudioProcessorEditor> w (new AudioUnitPluginWindowCocoa (*this, false));
  24949. if (! static_cast <AudioUnitPluginWindowCocoa*> (static_cast <AudioProcessorEditor*> (w))->isValid())
  24950. w = 0;
  24951. #if JUCE_SUPPORT_CARBON
  24952. if (w == 0)
  24953. {
  24954. w = new AudioUnitPluginWindowCarbon (*this);
  24955. if (! static_cast <AudioUnitPluginWindowCarbon*> (static_cast <AudioProcessorEditor*> (w))->isValid())
  24956. w = 0;
  24957. }
  24958. #endif
  24959. if (w == 0)
  24960. w = new AudioUnitPluginWindowCocoa (*this, true); // use AUGenericView as a fallback
  24961. return w.release();
  24962. }
  24963. const String AudioUnitPluginInstance::getCategory() const
  24964. {
  24965. const char* result = 0;
  24966. switch (componentDesc.componentType)
  24967. {
  24968. case kAudioUnitType_Effect:
  24969. case kAudioUnitType_MusicEffect:
  24970. result = "Effect";
  24971. break;
  24972. case kAudioUnitType_MusicDevice:
  24973. result = "Synth";
  24974. break;
  24975. case kAudioUnitType_Generator:
  24976. result = "Generator";
  24977. break;
  24978. case kAudioUnitType_Panner:
  24979. result = "Panner";
  24980. break;
  24981. default:
  24982. break;
  24983. }
  24984. return result;
  24985. }
  24986. int AudioUnitPluginInstance::getNumParameters()
  24987. {
  24988. return parameterIds.size();
  24989. }
  24990. float AudioUnitPluginInstance::getParameter (int index)
  24991. {
  24992. const ScopedLock sl (lock);
  24993. Float32 value = 0.0f;
  24994. if (audioUnit != 0 && ((unsigned int) index) < (unsigned int) parameterIds.size())
  24995. {
  24996. AudioUnitGetParameter (audioUnit,
  24997. (UInt32) parameterIds.getUnchecked (index),
  24998. kAudioUnitScope_Global, 0,
  24999. &value);
  25000. }
  25001. return value;
  25002. }
  25003. void AudioUnitPluginInstance::setParameter (int index, float newValue)
  25004. {
  25005. const ScopedLock sl (lock);
  25006. if (audioUnit != 0 && ((unsigned int) index) < (unsigned int) parameterIds.size())
  25007. {
  25008. AudioUnitSetParameter (audioUnit,
  25009. (UInt32) parameterIds.getUnchecked (index),
  25010. kAudioUnitScope_Global, 0,
  25011. newValue, 0);
  25012. }
  25013. }
  25014. const String AudioUnitPluginInstance::getParameterName (int index)
  25015. {
  25016. AudioUnitParameterInfo info;
  25017. zerostruct (info);
  25018. UInt32 sz = sizeof (info);
  25019. String name;
  25020. if (AudioUnitGetProperty (audioUnit,
  25021. kAudioUnitProperty_ParameterInfo,
  25022. kAudioUnitScope_Global,
  25023. parameterIds [index], &info, &sz) == noErr)
  25024. {
  25025. if ((info.flags & kAudioUnitParameterFlag_HasCFNameString) != 0)
  25026. name = PlatformUtilities::cfStringToJuceString (info.cfNameString);
  25027. else
  25028. name = String (info.name, sizeof (info.name));
  25029. }
  25030. return name;
  25031. }
  25032. const String AudioUnitPluginInstance::getParameterText (int index)
  25033. {
  25034. return String (getParameter (index));
  25035. }
  25036. bool AudioUnitPluginInstance::isParameterAutomatable (int index) const
  25037. {
  25038. AudioUnitParameterInfo info;
  25039. UInt32 sz = sizeof (info);
  25040. if (AudioUnitGetProperty (audioUnit,
  25041. kAudioUnitProperty_ParameterInfo,
  25042. kAudioUnitScope_Global,
  25043. parameterIds [index], &info, &sz) == noErr)
  25044. {
  25045. return (info.flags & kAudioUnitParameterFlag_NonRealTime) == 0;
  25046. }
  25047. return true;
  25048. }
  25049. int AudioUnitPluginInstance::getNumPrograms()
  25050. {
  25051. CFArrayRef presets;
  25052. UInt32 sz = sizeof (CFArrayRef);
  25053. int num = 0;
  25054. if (AudioUnitGetProperty (audioUnit,
  25055. kAudioUnitProperty_FactoryPresets,
  25056. kAudioUnitScope_Global,
  25057. 0, &presets, &sz) == noErr)
  25058. {
  25059. num = (int) CFArrayGetCount (presets);
  25060. CFRelease (presets);
  25061. }
  25062. return num;
  25063. }
  25064. int AudioUnitPluginInstance::getCurrentProgram()
  25065. {
  25066. AUPreset current;
  25067. current.presetNumber = 0;
  25068. UInt32 sz = sizeof (AUPreset);
  25069. AudioUnitGetProperty (audioUnit,
  25070. kAudioUnitProperty_FactoryPresets,
  25071. kAudioUnitScope_Global,
  25072. 0, &current, &sz);
  25073. return current.presetNumber;
  25074. }
  25075. void AudioUnitPluginInstance::setCurrentProgram (int newIndex)
  25076. {
  25077. AUPreset current;
  25078. current.presetNumber = newIndex;
  25079. current.presetName = 0;
  25080. AudioUnitSetProperty (audioUnit,
  25081. kAudioUnitProperty_FactoryPresets,
  25082. kAudioUnitScope_Global,
  25083. 0, &current, sizeof (AUPreset));
  25084. }
  25085. const String AudioUnitPluginInstance::getProgramName (int index)
  25086. {
  25087. String s;
  25088. CFArrayRef presets;
  25089. UInt32 sz = sizeof (CFArrayRef);
  25090. if (AudioUnitGetProperty (audioUnit,
  25091. kAudioUnitProperty_FactoryPresets,
  25092. kAudioUnitScope_Global,
  25093. 0, &presets, &sz) == noErr)
  25094. {
  25095. for (CFIndex i = 0; i < CFArrayGetCount (presets); ++i)
  25096. {
  25097. const AUPreset* p = (const AUPreset*) CFArrayGetValueAtIndex (presets, i);
  25098. if (p != 0 && p->presetNumber == index)
  25099. {
  25100. s = PlatformUtilities::cfStringToJuceString (p->presetName);
  25101. break;
  25102. }
  25103. }
  25104. CFRelease (presets);
  25105. }
  25106. return s;
  25107. }
  25108. void AudioUnitPluginInstance::changeProgramName (int index, const String& newName)
  25109. {
  25110. jassertfalse; // xxx not implemented!
  25111. }
  25112. const String AudioUnitPluginInstance::getInputChannelName (const int index) const
  25113. {
  25114. if (((unsigned int) index) < (unsigned int) getNumInputChannels())
  25115. return "Input " + String (index + 1);
  25116. return String::empty;
  25117. }
  25118. bool AudioUnitPluginInstance::isInputChannelStereoPair (int index) const
  25119. {
  25120. if (((unsigned int) index) >= (unsigned int) getNumInputChannels())
  25121. return false;
  25122. return true;
  25123. }
  25124. const String AudioUnitPluginInstance::getOutputChannelName (const int index) const
  25125. {
  25126. if (((unsigned int) index) < (unsigned int) getNumOutputChannels())
  25127. return "Output " + String (index + 1);
  25128. return String::empty;
  25129. }
  25130. bool AudioUnitPluginInstance::isOutputChannelStereoPair (int index) const
  25131. {
  25132. if (((unsigned int) index) >= (unsigned int) getNumOutputChannels())
  25133. return false;
  25134. return true;
  25135. }
  25136. void AudioUnitPluginInstance::getStateInformation (MemoryBlock& destData)
  25137. {
  25138. getCurrentProgramStateInformation (destData);
  25139. }
  25140. void AudioUnitPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  25141. {
  25142. CFPropertyListRef propertyList = 0;
  25143. UInt32 sz = sizeof (CFPropertyListRef);
  25144. if (AudioUnitGetProperty (audioUnit,
  25145. kAudioUnitProperty_ClassInfo,
  25146. kAudioUnitScope_Global,
  25147. 0, &propertyList, &sz) == noErr)
  25148. {
  25149. CFWriteStreamRef stream = CFWriteStreamCreateWithAllocatedBuffers (kCFAllocatorDefault, kCFAllocatorDefault);
  25150. CFWriteStreamOpen (stream);
  25151. CFIndex bytesWritten = CFPropertyListWriteToStream (propertyList, stream, kCFPropertyListBinaryFormat_v1_0, 0);
  25152. CFWriteStreamClose (stream);
  25153. CFDataRef data = (CFDataRef) CFWriteStreamCopyProperty (stream, kCFStreamPropertyDataWritten);
  25154. destData.setSize (bytesWritten);
  25155. destData.copyFrom (CFDataGetBytePtr (data), 0, destData.getSize());
  25156. CFRelease (data);
  25157. CFRelease (stream);
  25158. CFRelease (propertyList);
  25159. }
  25160. }
  25161. void AudioUnitPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  25162. {
  25163. setCurrentProgramStateInformation (data, sizeInBytes);
  25164. }
  25165. void AudioUnitPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  25166. {
  25167. CFReadStreamRef stream = CFReadStreamCreateWithBytesNoCopy (kCFAllocatorDefault,
  25168. (const UInt8*) data,
  25169. sizeInBytes,
  25170. kCFAllocatorNull);
  25171. CFReadStreamOpen (stream);
  25172. CFPropertyListFormat format = kCFPropertyListBinaryFormat_v1_0;
  25173. CFPropertyListRef propertyList = CFPropertyListCreateFromStream (kCFAllocatorDefault,
  25174. stream,
  25175. 0,
  25176. kCFPropertyListImmutable,
  25177. &format,
  25178. 0);
  25179. CFRelease (stream);
  25180. if (propertyList != 0)
  25181. AudioUnitSetProperty (audioUnit,
  25182. kAudioUnitProperty_ClassInfo,
  25183. kAudioUnitScope_Global,
  25184. 0, &propertyList, sizeof (propertyList));
  25185. }
  25186. AudioUnitPluginFormat::AudioUnitPluginFormat()
  25187. {
  25188. }
  25189. AudioUnitPluginFormat::~AudioUnitPluginFormat()
  25190. {
  25191. }
  25192. void AudioUnitPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  25193. const String& fileOrIdentifier)
  25194. {
  25195. if (! fileMightContainThisPluginType (fileOrIdentifier))
  25196. return;
  25197. PluginDescription desc;
  25198. desc.fileOrIdentifier = fileOrIdentifier;
  25199. desc.uid = 0;
  25200. try
  25201. {
  25202. ScopedPointer <AudioPluginInstance> createdInstance (createInstanceFromDescription (desc));
  25203. AudioUnitPluginInstance* const auInstance = dynamic_cast <AudioUnitPluginInstance*> ((AudioPluginInstance*) createdInstance);
  25204. if (auInstance != 0)
  25205. {
  25206. auInstance->fillInPluginDescription (desc);
  25207. results.add (new PluginDescription (desc));
  25208. }
  25209. }
  25210. catch (...)
  25211. {
  25212. // crashed while loading...
  25213. }
  25214. }
  25215. AudioPluginInstance* AudioUnitPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  25216. {
  25217. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  25218. {
  25219. ScopedPointer <AudioUnitPluginInstance> result (new AudioUnitPluginInstance (desc.fileOrIdentifier));
  25220. if (result->audioUnit != 0)
  25221. {
  25222. result->initialise();
  25223. return result.release();
  25224. }
  25225. }
  25226. return 0;
  25227. }
  25228. const StringArray AudioUnitPluginFormat::searchPathsForPlugins (const FileSearchPath& /*directoriesToSearch*/,
  25229. const bool /*recursive*/)
  25230. {
  25231. StringArray result;
  25232. ComponentRecord* comp = 0;
  25233. ComponentDescription desc;
  25234. zerostruct (desc);
  25235. for (;;)
  25236. {
  25237. zerostruct (desc);
  25238. comp = FindNextComponent (comp, &desc);
  25239. if (comp == 0)
  25240. break;
  25241. GetComponentInfo (comp, &desc, 0, 0, 0);
  25242. if (desc.componentType == kAudioUnitType_MusicDevice
  25243. || desc.componentType == kAudioUnitType_MusicEffect
  25244. || desc.componentType == kAudioUnitType_Effect
  25245. || desc.componentType == kAudioUnitType_Generator
  25246. || desc.componentType == kAudioUnitType_Panner)
  25247. {
  25248. const String s (createAUPluginIdentifier (desc));
  25249. DBG (s);
  25250. result.add (s);
  25251. }
  25252. }
  25253. return result;
  25254. }
  25255. bool AudioUnitPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  25256. {
  25257. ComponentDescription desc;
  25258. String name, version, manufacturer;
  25259. if (getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer))
  25260. return FindNextComponent (0, &desc) != 0;
  25261. const File f (fileOrIdentifier);
  25262. return f.hasFileExtension (".component")
  25263. && f.isDirectory();
  25264. }
  25265. const String AudioUnitPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  25266. {
  25267. ComponentDescription desc;
  25268. String name, version, manufacturer;
  25269. getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer);
  25270. if (name.isEmpty())
  25271. name = fileOrIdentifier;
  25272. return name;
  25273. }
  25274. bool AudioUnitPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  25275. {
  25276. if (desc.fileOrIdentifier.startsWithIgnoreCase (auIdentifierPrefix))
  25277. return fileMightContainThisPluginType (desc.fileOrIdentifier);
  25278. else
  25279. return File (desc.fileOrIdentifier).exists();
  25280. }
  25281. const FileSearchPath AudioUnitPluginFormat::getDefaultLocationsToSearch()
  25282. {
  25283. return FileSearchPath ("/(Default AudioUnit locations)");
  25284. }
  25285. #endif
  25286. END_JUCE_NAMESPACE
  25287. #undef log
  25288. #endif
  25289. /*** End of inlined file: juce_AudioUnitPluginFormat.mm ***/
  25290. /*** Start of inlined file: juce_VSTPluginFormat.mm ***/
  25291. // This file just wraps juce_VSTPluginFormat.cpp in an objective-C wrapper
  25292. #define JUCE_MAC_VST_INCLUDED 1
  25293. /*** Start of inlined file: juce_VSTPluginFormat.cpp ***/
  25294. #if JUCE_PLUGINHOST_VST && (JUCE_MAC_VST_INCLUDED || ! JUCE_MAC)
  25295. #if JUCE_WINDOWS
  25296. #undef _WIN32_WINNT
  25297. #define _WIN32_WINNT 0x500
  25298. #undef STRICT
  25299. #define STRICT
  25300. #include <windows.h>
  25301. #include <float.h>
  25302. #pragma warning (disable : 4312 4355)
  25303. #elif JUCE_LINUX
  25304. #include <float.h>
  25305. #include <sys/time.h>
  25306. #include <X11/Xlib.h>
  25307. #include <X11/Xutil.h>
  25308. #include <X11/Xatom.h>
  25309. #undef Font
  25310. #undef KeyPress
  25311. #undef Drawable
  25312. #undef Time
  25313. #else
  25314. #include <Cocoa/Cocoa.h>
  25315. #include <Carbon/Carbon.h>
  25316. #endif
  25317. #if ! (JUCE_MAC && JUCE_64BIT)
  25318. BEGIN_JUCE_NAMESPACE
  25319. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  25320. #endif
  25321. #undef PRAGMA_ALIGN_SUPPORTED
  25322. #define VST_FORCE_DEPRECATED 0
  25323. #if JUCE_MSVC
  25324. #pragma warning (push)
  25325. #pragma warning (disable: 4996)
  25326. #endif
  25327. /* Obviously you're going to need the Steinberg vstsdk2.4 folder in
  25328. your include path if you want to add VST support.
  25329. If you're not interested in VSTs, you can disable them by changing the
  25330. JUCE_PLUGINHOST_VST flag in juce_Config.h
  25331. */
  25332. #include "pluginterfaces/vst2.x/aeffectx.h"
  25333. #if JUCE_MSVC
  25334. #pragma warning (pop)
  25335. #endif
  25336. #if JUCE_LINUX
  25337. #define Font JUCE_NAMESPACE::Font
  25338. #define KeyPress JUCE_NAMESPACE::KeyPress
  25339. #define Drawable JUCE_NAMESPACE::Drawable
  25340. #define Time JUCE_NAMESPACE::Time
  25341. #endif
  25342. /*** Start of inlined file: juce_VSTMidiEventList.h ***/
  25343. #ifdef __aeffect__
  25344. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  25345. #define __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  25346. /** Holds a set of VSTMidiEvent objects and makes it easy to add
  25347. events to the list.
  25348. This is used by both the VST hosting code and the plugin wrapper.
  25349. */
  25350. class VSTMidiEventList
  25351. {
  25352. public:
  25353. VSTMidiEventList()
  25354. : numEventsUsed (0), numEventsAllocated (0)
  25355. {
  25356. }
  25357. ~VSTMidiEventList()
  25358. {
  25359. freeEvents();
  25360. }
  25361. void clear()
  25362. {
  25363. numEventsUsed = 0;
  25364. if (events != 0)
  25365. events->numEvents = 0;
  25366. }
  25367. void addEvent (const void* const midiData, const int numBytes, const int frameOffset)
  25368. {
  25369. ensureSize (numEventsUsed + 1);
  25370. VstMidiEvent* const e = (VstMidiEvent*) (events->events [numEventsUsed]);
  25371. events->numEvents = ++numEventsUsed;
  25372. if (numBytes <= 4)
  25373. {
  25374. if (e->type == kVstSysExType)
  25375. {
  25376. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  25377. e->type = kVstMidiType;
  25378. e->byteSize = sizeof (VstMidiEvent);
  25379. e->noteLength = 0;
  25380. e->noteOffset = 0;
  25381. e->detune = 0;
  25382. e->noteOffVelocity = 0;
  25383. }
  25384. e->deltaFrames = frameOffset;
  25385. memcpy (e->midiData, midiData, numBytes);
  25386. }
  25387. else
  25388. {
  25389. VstMidiSysexEvent* const se = (VstMidiSysexEvent*) e;
  25390. if (se->type == kVstSysExType)
  25391. se->sysexDump = (char*) juce_realloc (se->sysexDump, numBytes);
  25392. else
  25393. se->sysexDump = (char*) juce_malloc (numBytes);
  25394. memcpy (se->sysexDump, midiData, numBytes);
  25395. se->type = kVstSysExType;
  25396. se->byteSize = sizeof (VstMidiSysexEvent);
  25397. se->deltaFrames = frameOffset;
  25398. se->flags = 0;
  25399. se->dumpBytes = numBytes;
  25400. se->resvd1 = 0;
  25401. se->resvd2 = 0;
  25402. }
  25403. }
  25404. // Handy method to pull the events out of an event buffer supplied by the host
  25405. // or plugin.
  25406. static void addEventsToMidiBuffer (const VstEvents* events, MidiBuffer& dest)
  25407. {
  25408. for (int i = 0; i < events->numEvents; ++i)
  25409. {
  25410. const VstEvent* const e = events->events[i];
  25411. if (e != 0)
  25412. {
  25413. if (e->type == kVstMidiType)
  25414. {
  25415. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiEvent*) e)->midiData,
  25416. 4, e->deltaFrames);
  25417. }
  25418. else if (e->type == kVstSysExType)
  25419. {
  25420. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiSysexEvent*) e)->sysexDump,
  25421. (int) ((const VstMidiSysexEvent*) e)->dumpBytes,
  25422. e->deltaFrames);
  25423. }
  25424. }
  25425. }
  25426. }
  25427. void ensureSize (int numEventsNeeded)
  25428. {
  25429. if (numEventsNeeded > numEventsAllocated)
  25430. {
  25431. numEventsNeeded = (numEventsNeeded + 32) & ~31;
  25432. const int size = 20 + sizeof (VstEvent*) * numEventsNeeded;
  25433. if (events == 0)
  25434. events.calloc (size, 1);
  25435. else
  25436. events.realloc (size, 1);
  25437. for (int i = numEventsAllocated; i < numEventsNeeded; ++i)
  25438. {
  25439. VstMidiEvent* const e = (VstMidiEvent*) juce_calloc (jmax ((int) sizeof (VstMidiEvent),
  25440. (int) sizeof (VstMidiSysexEvent)));
  25441. e->type = kVstMidiType;
  25442. e->byteSize = sizeof (VstMidiEvent);
  25443. events->events[i] = (VstEvent*) e;
  25444. }
  25445. numEventsAllocated = numEventsNeeded;
  25446. }
  25447. }
  25448. void freeEvents()
  25449. {
  25450. if (events != 0)
  25451. {
  25452. for (int i = numEventsAllocated; --i >= 0;)
  25453. {
  25454. VstMidiEvent* const e = (VstMidiEvent*) (events->events[i]);
  25455. if (e->type == kVstSysExType)
  25456. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  25457. juce_free (e);
  25458. }
  25459. events.free();
  25460. numEventsUsed = 0;
  25461. numEventsAllocated = 0;
  25462. }
  25463. }
  25464. HeapBlock <VstEvents> events;
  25465. private:
  25466. int numEventsUsed, numEventsAllocated;
  25467. };
  25468. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  25469. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  25470. /*** End of inlined file: juce_VSTMidiEventList.h ***/
  25471. #if ! JUCE_WINDOWS
  25472. static void _fpreset() {}
  25473. static void _clearfp() {}
  25474. #endif
  25475. extern void juce_callAnyTimersSynchronously();
  25476. const int fxbVersionNum = 1;
  25477. struct fxProgram
  25478. {
  25479. long chunkMagic; // 'CcnK'
  25480. long byteSize; // of this chunk, excl. magic + byteSize
  25481. long fxMagic; // 'FxCk'
  25482. long version;
  25483. long fxID; // fx unique id
  25484. long fxVersion;
  25485. long numParams;
  25486. char prgName[28];
  25487. float params[1]; // variable no. of parameters
  25488. };
  25489. struct fxSet
  25490. {
  25491. long chunkMagic; // 'CcnK'
  25492. long byteSize; // of this chunk, excl. magic + byteSize
  25493. long fxMagic; // 'FxBk'
  25494. long version;
  25495. long fxID; // fx unique id
  25496. long fxVersion;
  25497. long numPrograms;
  25498. char future[128];
  25499. fxProgram programs[1]; // variable no. of programs
  25500. };
  25501. struct fxChunkSet
  25502. {
  25503. long chunkMagic; // 'CcnK'
  25504. long byteSize; // of this chunk, excl. magic + byteSize
  25505. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  25506. long version;
  25507. long fxID; // fx unique id
  25508. long fxVersion;
  25509. long numPrograms;
  25510. char future[128];
  25511. long chunkSize;
  25512. char chunk[8]; // variable
  25513. };
  25514. struct fxProgramSet
  25515. {
  25516. long chunkMagic; // 'CcnK'
  25517. long byteSize; // of this chunk, excl. magic + byteSize
  25518. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  25519. long version;
  25520. long fxID; // fx unique id
  25521. long fxVersion;
  25522. long numPrograms;
  25523. char name[28];
  25524. long chunkSize;
  25525. char chunk[8]; // variable
  25526. };
  25527. static long vst_swap (const long x) throw()
  25528. {
  25529. #ifdef JUCE_LITTLE_ENDIAN
  25530. return (long) ByteOrder::swap ((uint32) x);
  25531. #else
  25532. return x;
  25533. #endif
  25534. }
  25535. static float vst_swapFloat (const float x) throw()
  25536. {
  25537. #ifdef JUCE_LITTLE_ENDIAN
  25538. union { uint32 asInt; float asFloat; } n;
  25539. n.asFloat = x;
  25540. n.asInt = ByteOrder::swap (n.asInt);
  25541. return n.asFloat;
  25542. #else
  25543. return x;
  25544. #endif
  25545. }
  25546. typedef AEffect* (*MainCall) (audioMasterCallback);
  25547. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt);
  25548. static int shellUIDToCreate = 0;
  25549. static int insideVSTCallback = 0;
  25550. class VSTPluginWindow;
  25551. // Change this to disable logging of various VST activities
  25552. #ifndef VST_LOGGING
  25553. #define VST_LOGGING 1
  25554. #endif
  25555. #if VST_LOGGING
  25556. #define log(a) Logger::writeToLog(a);
  25557. #else
  25558. #define log(a)
  25559. #endif
  25560. #if JUCE_MAC && JUCE_PPC
  25561. static void* NewCFMFromMachO (void* const machofp) throw()
  25562. {
  25563. void* result = juce_malloc (8);
  25564. ((void**) result)[0] = machofp;
  25565. ((void**) result)[1] = result;
  25566. return result;
  25567. }
  25568. #endif
  25569. #if JUCE_LINUX
  25570. extern Display* display;
  25571. extern XContext windowHandleXContext;
  25572. typedef void (*EventProcPtr) (XEvent* ev);
  25573. static bool xErrorTriggered;
  25574. static int temporaryErrorHandler (Display*, XErrorEvent*)
  25575. {
  25576. xErrorTriggered = true;
  25577. return 0;
  25578. }
  25579. static int getPropertyFromXWindow (Window handle, Atom atom)
  25580. {
  25581. XErrorHandler oldErrorHandler = XSetErrorHandler (temporaryErrorHandler);
  25582. xErrorTriggered = false;
  25583. int userSize;
  25584. unsigned long bytes, userCount;
  25585. unsigned char* data;
  25586. Atom userType;
  25587. XGetWindowProperty (display, handle, atom, 0, 1, false, AnyPropertyType,
  25588. &userType, &userSize, &userCount, &bytes, &data);
  25589. XSetErrorHandler (oldErrorHandler);
  25590. return (userCount == 1 && ! xErrorTriggered) ? *(int*) data
  25591. : 0;
  25592. }
  25593. static Window getChildWindow (Window windowToCheck)
  25594. {
  25595. Window rootWindow, parentWindow;
  25596. Window* childWindows;
  25597. unsigned int numChildren;
  25598. XQueryTree (display,
  25599. windowToCheck,
  25600. &rootWindow,
  25601. &parentWindow,
  25602. &childWindows,
  25603. &numChildren);
  25604. if (numChildren > 0)
  25605. return childWindows [0];
  25606. return 0;
  25607. }
  25608. static void translateJuceToXButtonModifiers (const MouseEvent& e, XEvent& ev) throw()
  25609. {
  25610. if (e.mods.isLeftButtonDown())
  25611. {
  25612. ev.xbutton.button = Button1;
  25613. ev.xbutton.state |= Button1Mask;
  25614. }
  25615. else if (e.mods.isRightButtonDown())
  25616. {
  25617. ev.xbutton.button = Button3;
  25618. ev.xbutton.state |= Button3Mask;
  25619. }
  25620. else if (e.mods.isMiddleButtonDown())
  25621. {
  25622. ev.xbutton.button = Button2;
  25623. ev.xbutton.state |= Button2Mask;
  25624. }
  25625. }
  25626. static void translateJuceToXMotionModifiers (const MouseEvent& e, XEvent& ev) throw()
  25627. {
  25628. if (e.mods.isLeftButtonDown())
  25629. ev.xmotion.state |= Button1Mask;
  25630. else if (e.mods.isRightButtonDown())
  25631. ev.xmotion.state |= Button3Mask;
  25632. else if (e.mods.isMiddleButtonDown())
  25633. ev.xmotion.state |= Button2Mask;
  25634. }
  25635. static void translateJuceToXCrossingModifiers (const MouseEvent& e, XEvent& ev) throw()
  25636. {
  25637. if (e.mods.isLeftButtonDown())
  25638. ev.xcrossing.state |= Button1Mask;
  25639. else if (e.mods.isRightButtonDown())
  25640. ev.xcrossing.state |= Button3Mask;
  25641. else if (e.mods.isMiddleButtonDown())
  25642. ev.xcrossing.state |= Button2Mask;
  25643. }
  25644. static void translateJuceToXMouseWheelModifiers (const MouseEvent& e, const float increment, XEvent& ev) throw()
  25645. {
  25646. if (increment < 0)
  25647. {
  25648. ev.xbutton.button = Button5;
  25649. ev.xbutton.state |= Button5Mask;
  25650. }
  25651. else if (increment > 0)
  25652. {
  25653. ev.xbutton.button = Button4;
  25654. ev.xbutton.state |= Button4Mask;
  25655. }
  25656. }
  25657. #endif
  25658. class ModuleHandle : public ReferenceCountedObject
  25659. {
  25660. public:
  25661. File file;
  25662. MainCall moduleMain;
  25663. String pluginName;
  25664. static Array <ModuleHandle*>& getActiveModules()
  25665. {
  25666. static Array <ModuleHandle*> activeModules;
  25667. return activeModules;
  25668. }
  25669. static ModuleHandle* findOrCreateModule (const File& file)
  25670. {
  25671. for (int i = getActiveModules().size(); --i >= 0;)
  25672. {
  25673. ModuleHandle* const module = getActiveModules().getUnchecked(i);
  25674. if (module->file == file)
  25675. return module;
  25676. }
  25677. _fpreset(); // (doesn't do any harm)
  25678. ++insideVSTCallback;
  25679. shellUIDToCreate = 0;
  25680. log ("Attempting to load VST: " + file.getFullPathName());
  25681. ScopedPointer <ModuleHandle> m (new ModuleHandle (file));
  25682. if (! m->open())
  25683. m = 0;
  25684. --insideVSTCallback;
  25685. _fpreset(); // (doesn't do any harm)
  25686. return m.release();
  25687. }
  25688. ModuleHandle (const File& file_)
  25689. : file (file_),
  25690. moduleMain (0),
  25691. #if JUCE_WINDOWS || JUCE_LINUX
  25692. hModule (0)
  25693. #elif JUCE_MAC
  25694. fragId (0),
  25695. resHandle (0),
  25696. bundleRef (0),
  25697. resFileId (0)
  25698. #endif
  25699. {
  25700. getActiveModules().add (this);
  25701. #if JUCE_WINDOWS || JUCE_LINUX
  25702. fullParentDirectoryPathName = file_.getParentDirectory().getFullPathName();
  25703. #elif JUCE_MAC
  25704. FSRef ref;
  25705. PlatformUtilities::makeFSRefFromPath (&ref, file_.getParentDirectory().getFullPathName());
  25706. FSGetCatalogInfo (&ref, kFSCatInfoNone, 0, 0, &parentDirFSSpec, 0);
  25707. #endif
  25708. }
  25709. ~ModuleHandle()
  25710. {
  25711. getActiveModules().removeValue (this);
  25712. close();
  25713. }
  25714. juce_UseDebuggingNewOperator
  25715. #if JUCE_WINDOWS || JUCE_LINUX
  25716. void* hModule;
  25717. String fullParentDirectoryPathName;
  25718. bool open()
  25719. {
  25720. #if JUCE_WINDOWS
  25721. static bool timePeriodSet = false;
  25722. if (! timePeriodSet)
  25723. {
  25724. timePeriodSet = true;
  25725. timeBeginPeriod (2);
  25726. }
  25727. #endif
  25728. pluginName = file.getFileNameWithoutExtension();
  25729. hModule = PlatformUtilities::loadDynamicLibrary (file.getFullPathName());
  25730. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "VSTPluginMain");
  25731. if (moduleMain == 0)
  25732. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "main");
  25733. return moduleMain != 0;
  25734. }
  25735. void close()
  25736. {
  25737. _fpreset(); // (doesn't do any harm)
  25738. PlatformUtilities::freeDynamicLibrary (hModule);
  25739. }
  25740. void closeEffect (AEffect* eff)
  25741. {
  25742. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  25743. }
  25744. #else
  25745. CFragConnectionID fragId;
  25746. Handle resHandle;
  25747. CFBundleRef bundleRef;
  25748. FSSpec parentDirFSSpec;
  25749. short resFileId;
  25750. bool open()
  25751. {
  25752. bool ok = false;
  25753. const String filename (file.getFullPathName());
  25754. if (file.hasFileExtension (".vst"))
  25755. {
  25756. const char* const utf8 = filename.toUTF8();
  25757. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  25758. strlen (utf8), file.isDirectory());
  25759. if (url != 0)
  25760. {
  25761. bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  25762. CFRelease (url);
  25763. if (bundleRef != 0)
  25764. {
  25765. if (CFBundleLoadExecutable (bundleRef))
  25766. {
  25767. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("main_macho"));
  25768. if (moduleMain == 0)
  25769. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("VSTPluginMain"));
  25770. if (moduleMain != 0)
  25771. {
  25772. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  25773. if (name != 0)
  25774. {
  25775. if (CFGetTypeID (name) == CFStringGetTypeID())
  25776. {
  25777. char buffer[1024];
  25778. if (CFStringGetCString ((CFStringRef) name, buffer, sizeof (buffer), CFStringGetSystemEncoding()))
  25779. pluginName = buffer;
  25780. }
  25781. }
  25782. if (pluginName.isEmpty())
  25783. pluginName = file.getFileNameWithoutExtension();
  25784. resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  25785. ok = true;
  25786. }
  25787. }
  25788. if (! ok)
  25789. {
  25790. CFBundleUnloadExecutable (bundleRef);
  25791. CFRelease (bundleRef);
  25792. bundleRef = 0;
  25793. }
  25794. }
  25795. }
  25796. }
  25797. #if JUCE_PPC
  25798. else
  25799. {
  25800. FSRef fn;
  25801. if (FSPathMakeRef ((UInt8*) filename.toUTF8(), &fn, 0) == noErr)
  25802. {
  25803. resFileId = FSOpenResFile (&fn, fsRdPerm);
  25804. if (resFileId != -1)
  25805. {
  25806. const int numEffs = Count1Resources ('aEff');
  25807. for (int i = 0; i < numEffs; ++i)
  25808. {
  25809. resHandle = Get1IndResource ('aEff', i + 1);
  25810. if (resHandle != 0)
  25811. {
  25812. OSType type;
  25813. Str255 name;
  25814. SInt16 id;
  25815. GetResInfo (resHandle, &id, &type, name);
  25816. pluginName = String ((const char*) name + 1, name[0]);
  25817. DetachResource (resHandle);
  25818. HLock (resHandle);
  25819. Ptr ptr;
  25820. Str255 errorText;
  25821. OSErr err = GetMemFragment (*resHandle, GetHandleSize (resHandle),
  25822. name, kPrivateCFragCopy,
  25823. &fragId, &ptr, errorText);
  25824. if (err == noErr)
  25825. {
  25826. moduleMain = (MainCall) newMachOFromCFM (ptr);
  25827. ok = true;
  25828. }
  25829. else
  25830. {
  25831. HUnlock (resHandle);
  25832. }
  25833. break;
  25834. }
  25835. }
  25836. if (! ok)
  25837. CloseResFile (resFileId);
  25838. }
  25839. }
  25840. }
  25841. #endif
  25842. return ok;
  25843. }
  25844. void close()
  25845. {
  25846. #if JUCE_PPC
  25847. if (fragId != 0)
  25848. {
  25849. if (moduleMain != 0)
  25850. disposeMachOFromCFM ((void*) moduleMain);
  25851. CloseConnection (&fragId);
  25852. HUnlock (resHandle);
  25853. if (resFileId != 0)
  25854. CloseResFile (resFileId);
  25855. }
  25856. else
  25857. #endif
  25858. if (bundleRef != 0)
  25859. {
  25860. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  25861. if (CFGetRetainCount (bundleRef) == 1)
  25862. CFBundleUnloadExecutable (bundleRef);
  25863. if (CFGetRetainCount (bundleRef) > 0)
  25864. CFRelease (bundleRef);
  25865. }
  25866. }
  25867. void closeEffect (AEffect* eff)
  25868. {
  25869. #if JUCE_PPC
  25870. if (fragId != 0)
  25871. {
  25872. Array<void*> thingsToDelete;
  25873. thingsToDelete.add ((void*) eff->dispatcher);
  25874. thingsToDelete.add ((void*) eff->process);
  25875. thingsToDelete.add ((void*) eff->setParameter);
  25876. thingsToDelete.add ((void*) eff->getParameter);
  25877. thingsToDelete.add ((void*) eff->processReplacing);
  25878. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  25879. for (int i = thingsToDelete.size(); --i >= 0;)
  25880. disposeMachOFromCFM (thingsToDelete[i]);
  25881. }
  25882. else
  25883. #endif
  25884. {
  25885. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  25886. }
  25887. }
  25888. #if JUCE_PPC
  25889. static void* newMachOFromCFM (void* cfmfp)
  25890. {
  25891. if (cfmfp == 0)
  25892. return 0;
  25893. UInt32* const mfp = new UInt32[6];
  25894. mfp[0] = 0x3d800000 | ((UInt32) cfmfp >> 16);
  25895. mfp[1] = 0x618c0000 | ((UInt32) cfmfp & 0xffff);
  25896. mfp[2] = 0x800c0000;
  25897. mfp[3] = 0x804c0004;
  25898. mfp[4] = 0x7c0903a6;
  25899. mfp[5] = 0x4e800420;
  25900. MakeDataExecutable (mfp, sizeof (UInt32) * 6);
  25901. return mfp;
  25902. }
  25903. static void disposeMachOFromCFM (void* ptr)
  25904. {
  25905. delete[] static_cast <UInt32*> (ptr);
  25906. }
  25907. void coerceAEffectFunctionCalls (AEffect* eff)
  25908. {
  25909. if (fragId != 0)
  25910. {
  25911. eff->dispatcher = (AEffectDispatcherProc) newMachOFromCFM ((void*) eff->dispatcher);
  25912. eff->process = (AEffectProcessProc) newMachOFromCFM ((void*) eff->process);
  25913. eff->setParameter = (AEffectSetParameterProc) newMachOFromCFM ((void*) eff->setParameter);
  25914. eff->getParameter = (AEffectGetParameterProc) newMachOFromCFM ((void*) eff->getParameter);
  25915. eff->processReplacing = (AEffectProcessProc) newMachOFromCFM ((void*) eff->processReplacing);
  25916. }
  25917. }
  25918. #endif
  25919. #endif
  25920. };
  25921. /**
  25922. An instance of a plugin, created by a VSTPluginFormat.
  25923. */
  25924. class VSTPluginInstance : public AudioPluginInstance,
  25925. private Timer,
  25926. private AsyncUpdater
  25927. {
  25928. public:
  25929. ~VSTPluginInstance();
  25930. // AudioPluginInstance methods:
  25931. void fillInPluginDescription (PluginDescription& desc) const
  25932. {
  25933. desc.name = name;
  25934. desc.fileOrIdentifier = module->file.getFullPathName();
  25935. desc.uid = getUID();
  25936. desc.lastFileModTime = module->file.getLastModificationTime();
  25937. desc.pluginFormatName = "VST";
  25938. desc.category = getCategory();
  25939. {
  25940. char buffer [kVstMaxVendorStrLen + 8];
  25941. zerostruct (buffer);
  25942. dispatch (effGetVendorString, 0, 0, buffer, 0);
  25943. desc.manufacturerName = buffer;
  25944. }
  25945. desc.version = getVersion();
  25946. desc.numInputChannels = getNumInputChannels();
  25947. desc.numOutputChannels = getNumOutputChannels();
  25948. desc.isInstrument = (effect != 0 && (effect->flags & effFlagsIsSynth) != 0);
  25949. }
  25950. const String getName() const { return name; }
  25951. int getUID() const throw();
  25952. bool acceptsMidi() const { return wantsMidiMessages; }
  25953. bool producesMidi() const { return dispatch (effCanDo, 0, 0, (void*) "sendVstMidiEvent", 0) > 0; }
  25954. // AudioProcessor methods:
  25955. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  25956. void releaseResources();
  25957. void processBlock (AudioSampleBuffer& buffer,
  25958. MidiBuffer& midiMessages);
  25959. AudioProcessorEditor* createEditor();
  25960. const String getInputChannelName (const int index) const;
  25961. bool isInputChannelStereoPair (int index) const;
  25962. const String getOutputChannelName (const int index) const;
  25963. bool isOutputChannelStereoPair (int index) const;
  25964. int getNumParameters() { return effect != 0 ? effect->numParams : 0; }
  25965. float getParameter (int index);
  25966. void setParameter (int index, float newValue);
  25967. const String getParameterName (int index);
  25968. const String getParameterText (int index);
  25969. bool isParameterAutomatable (int index) const;
  25970. int getNumPrograms() { return effect != 0 ? effect->numPrograms : 0; }
  25971. int getCurrentProgram() { return dispatch (effGetProgram, 0, 0, 0, 0); }
  25972. void setCurrentProgram (int index);
  25973. const String getProgramName (int index);
  25974. void changeProgramName (int index, const String& newName);
  25975. void getStateInformation (MemoryBlock& destData);
  25976. void getCurrentProgramStateInformation (MemoryBlock& destData);
  25977. void setStateInformation (const void* data, int sizeInBytes);
  25978. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  25979. void timerCallback();
  25980. void handleAsyncUpdate();
  25981. VstIntPtr handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt);
  25982. juce_UseDebuggingNewOperator
  25983. private:
  25984. friend class VSTPluginWindow;
  25985. friend class VSTPluginFormat;
  25986. AEffect* effect;
  25987. String name;
  25988. CriticalSection lock;
  25989. bool wantsMidiMessages, initialised, isPowerOn;
  25990. mutable StringArray programNames;
  25991. AudioSampleBuffer tempBuffer;
  25992. CriticalSection midiInLock;
  25993. MidiBuffer incomingMidi;
  25994. VSTMidiEventList midiEventsToSend;
  25995. VstTimeInfo vstHostTime;
  25996. HeapBlock <float*> channels;
  25997. ReferenceCountedObjectPtr <ModuleHandle> module;
  25998. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const;
  25999. bool restoreProgramSettings (const fxProgram* const prog);
  26000. const String getCurrentProgramName();
  26001. void setParamsInProgramBlock (fxProgram* const prog) throw();
  26002. void updateStoredProgramNames();
  26003. void initialise();
  26004. void handleMidiFromPlugin (const VstEvents* const events);
  26005. void createTempParameterStore (MemoryBlock& dest);
  26006. void restoreFromTempParameterStore (const MemoryBlock& mb);
  26007. const String getParameterLabel (int index) const;
  26008. bool usesChunks() const throw() { return effect != 0 && (effect->flags & effFlagsProgramChunks) != 0; }
  26009. void getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const;
  26010. void setChunkData (const char* data, int size, bool isPreset);
  26011. bool loadFromFXBFile (const void* data, int numBytes);
  26012. bool saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB);
  26013. int getVersionNumber() const throw() { return effect != 0 ? effect->version : 0; }
  26014. const String getVersion() const throw();
  26015. const String getCategory() const throw();
  26016. bool hasEditor() const throw() { return effect != 0 && (effect->flags & effFlagsHasEditor) != 0; }
  26017. void setPower (const bool on);
  26018. VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module);
  26019. };
  26020. VSTPluginInstance::VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module_)
  26021. : effect (0),
  26022. wantsMidiMessages (false),
  26023. initialised (false),
  26024. isPowerOn (false),
  26025. tempBuffer (1, 1),
  26026. module (module_)
  26027. {
  26028. try
  26029. {
  26030. _fpreset();
  26031. ++insideVSTCallback;
  26032. name = module->pluginName;
  26033. log ("Creating VST instance: " + name);
  26034. #if JUCE_MAC
  26035. if (module->resFileId != 0)
  26036. UseResFile (module->resFileId);
  26037. #if JUCE_PPC
  26038. if (module->fragId != 0)
  26039. {
  26040. static void* audioMasterCoerced = 0;
  26041. if (audioMasterCoerced == 0)
  26042. audioMasterCoerced = NewCFMFromMachO ((void*) &audioMaster);
  26043. effect = module->moduleMain ((audioMasterCallback) audioMasterCoerced);
  26044. }
  26045. else
  26046. #endif
  26047. #endif
  26048. {
  26049. effect = module->moduleMain (&audioMaster);
  26050. }
  26051. --insideVSTCallback;
  26052. if (effect != 0 && effect->magic == kEffectMagic)
  26053. {
  26054. #if JUCE_PPC
  26055. module->coerceAEffectFunctionCalls (effect);
  26056. #endif
  26057. jassert (effect->resvd2 == 0);
  26058. jassert (effect->object != 0);
  26059. _fpreset(); // some dodgy plugs fuck around with this
  26060. }
  26061. else
  26062. {
  26063. effect = 0;
  26064. }
  26065. }
  26066. catch (...)
  26067. {
  26068. --insideVSTCallback;
  26069. }
  26070. }
  26071. VSTPluginInstance::~VSTPluginInstance()
  26072. {
  26073. {
  26074. const ScopedLock sl (lock);
  26075. jassert (insideVSTCallback == 0);
  26076. if (effect != 0 && effect->magic == kEffectMagic)
  26077. {
  26078. try
  26079. {
  26080. #if JUCE_MAC
  26081. if (module->resFileId != 0)
  26082. UseResFile (module->resFileId);
  26083. #endif
  26084. // Must delete any editors before deleting the plugin instance!
  26085. jassert (getActiveEditor() == 0);
  26086. _fpreset(); // some dodgy plugs fuck around with this
  26087. module->closeEffect (effect);
  26088. }
  26089. catch (...)
  26090. {}
  26091. }
  26092. module = 0;
  26093. effect = 0;
  26094. }
  26095. }
  26096. void VSTPluginInstance::initialise()
  26097. {
  26098. if (initialised || effect == 0)
  26099. return;
  26100. log ("Initialising VST: " + module->pluginName);
  26101. initialised = true;
  26102. dispatch (effIdentify, 0, 0, 0, 0);
  26103. // this code would ask the plugin for its name, but so few plugins
  26104. // actually bother implementing this correctly, that it's better to
  26105. // just ignore it and use the file name instead.
  26106. /* {
  26107. char buffer [256];
  26108. zerostruct (buffer);
  26109. dispatch (effGetEffectName, 0, 0, buffer, 0);
  26110. name = String (buffer).trim();
  26111. if (name.isEmpty())
  26112. name = module->pluginName;
  26113. }
  26114. */
  26115. if (getSampleRate() > 0)
  26116. dispatch (effSetSampleRate, 0, 0, 0, (float) getSampleRate());
  26117. if (getBlockSize() > 0)
  26118. dispatch (effSetBlockSize, 0, jmax (32, getBlockSize()), 0, 0);
  26119. dispatch (effOpen, 0, 0, 0, 0);
  26120. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  26121. getSampleRate(), getBlockSize());
  26122. if (getNumPrograms() > 1)
  26123. setCurrentProgram (0);
  26124. else
  26125. dispatch (effSetProgram, 0, 0, 0, 0);
  26126. int i;
  26127. for (i = effect->numInputs; --i >= 0;)
  26128. dispatch (effConnectInput, i, 1, 0, 0);
  26129. for (i = effect->numOutputs; --i >= 0;)
  26130. dispatch (effConnectOutput, i, 1, 0, 0);
  26131. updateStoredProgramNames();
  26132. wantsMidiMessages = dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0;
  26133. setLatencySamples (effect->initialDelay);
  26134. }
  26135. void VSTPluginInstance::prepareToPlay (double sampleRate_,
  26136. int samplesPerBlockExpected)
  26137. {
  26138. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  26139. sampleRate_, samplesPerBlockExpected);
  26140. setLatencySamples (effect->initialDelay);
  26141. channels.calloc (jmax (16, getNumOutputChannels(), getNumInputChannels()) + 2);
  26142. vstHostTime.tempo = 120.0;
  26143. vstHostTime.timeSigNumerator = 4;
  26144. vstHostTime.timeSigDenominator = 4;
  26145. vstHostTime.sampleRate = sampleRate_;
  26146. vstHostTime.samplePos = 0;
  26147. vstHostTime.flags = kVstNanosValid; /*| kVstTransportPlaying | kVstTempoValid | kVstTimeSigValid*/;
  26148. initialise();
  26149. if (initialised)
  26150. {
  26151. wantsMidiMessages = wantsMidiMessages
  26152. || (dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0);
  26153. if (wantsMidiMessages)
  26154. midiEventsToSend.ensureSize (256);
  26155. else
  26156. midiEventsToSend.freeEvents();
  26157. incomingMidi.clear();
  26158. dispatch (effSetSampleRate, 0, 0, 0, (float) sampleRate_);
  26159. dispatch (effSetBlockSize, 0, jmax (16, samplesPerBlockExpected), 0, 0);
  26160. tempBuffer.setSize (jmax (1, effect->numOutputs), samplesPerBlockExpected);
  26161. if (! isPowerOn)
  26162. setPower (true);
  26163. // dodgy hack to force some plugins to initialise the sample rate..
  26164. if ((! hasEditor()) && getNumParameters() > 0)
  26165. {
  26166. const float old = getParameter (0);
  26167. setParameter (0, (old < 0.5f) ? 1.0f : 0.0f);
  26168. setParameter (0, old);
  26169. }
  26170. dispatch (effStartProcess, 0, 0, 0, 0);
  26171. }
  26172. }
  26173. void VSTPluginInstance::releaseResources()
  26174. {
  26175. if (initialised)
  26176. {
  26177. dispatch (effStopProcess, 0, 0, 0, 0);
  26178. setPower (false);
  26179. }
  26180. tempBuffer.setSize (1, 1);
  26181. incomingMidi.clear();
  26182. midiEventsToSend.freeEvents();
  26183. channels.free();
  26184. }
  26185. void VSTPluginInstance::processBlock (AudioSampleBuffer& buffer,
  26186. MidiBuffer& midiMessages)
  26187. {
  26188. const int numSamples = buffer.getNumSamples();
  26189. if (initialised)
  26190. {
  26191. AudioPlayHead* playHead = getPlayHead();
  26192. if (playHead != 0)
  26193. {
  26194. AudioPlayHead::CurrentPositionInfo position;
  26195. playHead->getCurrentPosition (position);
  26196. vstHostTime.tempo = position.bpm;
  26197. vstHostTime.timeSigNumerator = position.timeSigNumerator;
  26198. vstHostTime.timeSigDenominator = position.timeSigDenominator;
  26199. vstHostTime.ppqPos = position.ppqPosition;
  26200. vstHostTime.barStartPos = position.ppqPositionOfLastBarStart;
  26201. vstHostTime.flags |= kVstTempoValid | kVstTimeSigValid | kVstPpqPosValid | kVstBarsValid;
  26202. if (position.isPlaying)
  26203. vstHostTime.flags |= kVstTransportPlaying;
  26204. else
  26205. vstHostTime.flags &= ~kVstTransportPlaying;
  26206. }
  26207. #if JUCE_WINDOWS
  26208. vstHostTime.nanoSeconds = timeGetTime() * 1000000.0;
  26209. #elif JUCE_LINUX
  26210. timeval micro;
  26211. gettimeofday (&micro, 0);
  26212. vstHostTime.nanoSeconds = micro.tv_usec * 1000.0;
  26213. #elif JUCE_MAC
  26214. UnsignedWide micro;
  26215. Microseconds (&micro);
  26216. vstHostTime.nanoSeconds = micro.lo * 1000.0;
  26217. #endif
  26218. if (wantsMidiMessages)
  26219. {
  26220. midiEventsToSend.clear();
  26221. midiEventsToSend.ensureSize (1);
  26222. MidiBuffer::Iterator iter (midiMessages);
  26223. const uint8* midiData;
  26224. int numBytesOfMidiData, samplePosition;
  26225. while (iter.getNextEvent (midiData, numBytesOfMidiData, samplePosition))
  26226. {
  26227. midiEventsToSend.addEvent (midiData, numBytesOfMidiData,
  26228. jlimit (0, numSamples - 1, samplePosition));
  26229. }
  26230. try
  26231. {
  26232. effect->dispatcher (effect, effProcessEvents, 0, 0, midiEventsToSend.events, 0);
  26233. }
  26234. catch (...)
  26235. {}
  26236. }
  26237. int i;
  26238. const int maxChans = jmax (effect->numInputs, effect->numOutputs);
  26239. for (i = 0; i < maxChans; ++i)
  26240. channels[i] = buffer.getSampleData (i);
  26241. channels [maxChans] = 0;
  26242. _clearfp();
  26243. if ((effect->flags & effFlagsCanReplacing) != 0)
  26244. {
  26245. try
  26246. {
  26247. effect->processReplacing (effect, channels, channels, numSamples);
  26248. }
  26249. catch (...)
  26250. {}
  26251. }
  26252. else
  26253. {
  26254. tempBuffer.setSize (effect->numOutputs, numSamples);
  26255. tempBuffer.clear();
  26256. float* outs [64];
  26257. for (i = effect->numOutputs; --i >= 0;)
  26258. outs[i] = tempBuffer.getSampleData (i);
  26259. outs [effect->numOutputs] = 0;
  26260. try
  26261. {
  26262. effect->process (effect, channels, outs, numSamples);
  26263. }
  26264. catch (...)
  26265. {}
  26266. for (i = effect->numOutputs; --i >= 0;)
  26267. buffer.copyFrom (i, 0, outs[i], numSamples);
  26268. }
  26269. }
  26270. else
  26271. {
  26272. // Not initialised, so just bypass..
  26273. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  26274. buffer.clear (i, 0, buffer.getNumSamples());
  26275. }
  26276. {
  26277. // copy any incoming midi..
  26278. const ScopedLock sl (midiInLock);
  26279. midiMessages.swapWith (incomingMidi);
  26280. incomingMidi.clear();
  26281. }
  26282. }
  26283. void VSTPluginInstance::handleMidiFromPlugin (const VstEvents* const events)
  26284. {
  26285. if (events != 0)
  26286. {
  26287. const ScopedLock sl (midiInLock);
  26288. VSTMidiEventList::addEventsToMidiBuffer (events, incomingMidi);
  26289. }
  26290. }
  26291. static Array <VSTPluginWindow*> activeVSTWindows;
  26292. class VSTPluginWindow : public AudioProcessorEditor,
  26293. #if ! JUCE_MAC
  26294. public ComponentMovementWatcher,
  26295. #endif
  26296. public Timer
  26297. {
  26298. public:
  26299. VSTPluginWindow (VSTPluginInstance& plugin_)
  26300. : AudioProcessorEditor (&plugin_),
  26301. #if ! JUCE_MAC
  26302. ComponentMovementWatcher (this),
  26303. #endif
  26304. plugin (plugin_),
  26305. isOpen (false),
  26306. wasShowing (false),
  26307. pluginRefusesToResize (false),
  26308. pluginWantsKeys (false),
  26309. alreadyInside (false),
  26310. recursiveResize (false)
  26311. {
  26312. #if JUCE_WINDOWS
  26313. sizeCheckCount = 0;
  26314. pluginHWND = 0;
  26315. #elif JUCE_LINUX
  26316. pluginWindow = None;
  26317. pluginProc = None;
  26318. #else
  26319. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  26320. #endif
  26321. activeVSTWindows.add (this);
  26322. setSize (1, 1);
  26323. setOpaque (true);
  26324. setVisible (true);
  26325. }
  26326. ~VSTPluginWindow()
  26327. {
  26328. #if JUCE_MAC
  26329. innerWrapper = 0;
  26330. #else
  26331. closePluginWindow();
  26332. #endif
  26333. activeVSTWindows.removeValue (this);
  26334. plugin.editorBeingDeleted (this);
  26335. }
  26336. #if ! JUCE_MAC
  26337. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  26338. {
  26339. if (recursiveResize)
  26340. return;
  26341. Component* const topComp = getTopLevelComponent();
  26342. if (topComp->getPeer() != 0)
  26343. {
  26344. const Point<int> pos (relativePositionToOtherComponent (topComp, Point<int>()));
  26345. recursiveResize = true;
  26346. #if JUCE_WINDOWS
  26347. if (pluginHWND != 0)
  26348. MoveWindow (pluginHWND, pos.getX(), pos.getY(), getWidth(), getHeight(), TRUE);
  26349. #elif JUCE_LINUX
  26350. if (pluginWindow != 0)
  26351. {
  26352. XResizeWindow (display, pluginWindow, getWidth(), getHeight());
  26353. XMoveWindow (display, pluginWindow, pos.getX(), pos.getY());
  26354. XMapRaised (display, pluginWindow);
  26355. }
  26356. #endif
  26357. recursiveResize = false;
  26358. }
  26359. }
  26360. void componentVisibilityChanged (Component&)
  26361. {
  26362. const bool isShowingNow = isShowing();
  26363. if (wasShowing != isShowingNow)
  26364. {
  26365. wasShowing = isShowingNow;
  26366. if (isShowingNow)
  26367. openPluginWindow();
  26368. else
  26369. closePluginWindow();
  26370. }
  26371. componentMovedOrResized (true, true);
  26372. }
  26373. void componentPeerChanged()
  26374. {
  26375. closePluginWindow();
  26376. openPluginWindow();
  26377. }
  26378. #endif
  26379. bool keyStateChanged (bool)
  26380. {
  26381. return pluginWantsKeys;
  26382. }
  26383. bool keyPressed (const KeyPress&)
  26384. {
  26385. return pluginWantsKeys;
  26386. }
  26387. #if JUCE_MAC
  26388. void paint (Graphics& g)
  26389. {
  26390. g.fillAll (Colours::black);
  26391. }
  26392. #else
  26393. void paint (Graphics& g)
  26394. {
  26395. if (isOpen)
  26396. {
  26397. ComponentPeer* const peer = getPeer();
  26398. if (peer != 0)
  26399. {
  26400. const Point<int> pos (getScreenPosition() - peer->getScreenPosition());
  26401. peer->addMaskedRegion (pos.getX(), pos.getY(), getWidth(), getHeight());
  26402. #if JUCE_LINUX
  26403. if (pluginWindow != 0)
  26404. {
  26405. const Rectangle<int> clip (g.getClipBounds());
  26406. XEvent ev;
  26407. zerostruct (ev);
  26408. ev.xexpose.type = Expose;
  26409. ev.xexpose.display = display;
  26410. ev.xexpose.window = pluginWindow;
  26411. ev.xexpose.x = clip.getX();
  26412. ev.xexpose.y = clip.getY();
  26413. ev.xexpose.width = clip.getWidth();
  26414. ev.xexpose.height = clip.getHeight();
  26415. sendEventToChild (&ev);
  26416. }
  26417. #endif
  26418. }
  26419. }
  26420. else
  26421. {
  26422. g.fillAll (Colours::black);
  26423. }
  26424. }
  26425. #endif
  26426. void timerCallback()
  26427. {
  26428. #if JUCE_WINDOWS
  26429. if (--sizeCheckCount <= 0)
  26430. {
  26431. sizeCheckCount = 10;
  26432. checkPluginWindowSize();
  26433. }
  26434. #endif
  26435. try
  26436. {
  26437. static bool reentrant = false;
  26438. if (! reentrant)
  26439. {
  26440. reentrant = true;
  26441. plugin.dispatch (effEditIdle, 0, 0, 0, 0);
  26442. reentrant = false;
  26443. }
  26444. }
  26445. catch (...)
  26446. {}
  26447. }
  26448. void mouseDown (const MouseEvent& e)
  26449. {
  26450. #if JUCE_LINUX
  26451. if (pluginWindow == 0)
  26452. return;
  26453. toFront (true);
  26454. XEvent ev;
  26455. zerostruct (ev);
  26456. ev.xbutton.display = display;
  26457. ev.xbutton.type = ButtonPress;
  26458. ev.xbutton.window = pluginWindow;
  26459. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  26460. ev.xbutton.time = CurrentTime;
  26461. ev.xbutton.x = e.x;
  26462. ev.xbutton.y = e.y;
  26463. ev.xbutton.x_root = e.getScreenX();
  26464. ev.xbutton.y_root = e.getScreenY();
  26465. translateJuceToXButtonModifiers (e, ev);
  26466. sendEventToChild (&ev);
  26467. #elif JUCE_WINDOWS
  26468. (void) e;
  26469. toFront (true);
  26470. #endif
  26471. }
  26472. void broughtToFront()
  26473. {
  26474. activeVSTWindows.removeValue (this);
  26475. activeVSTWindows.add (this);
  26476. #if JUCE_MAC
  26477. dispatch (effEditTop, 0, 0, 0, 0);
  26478. #endif
  26479. }
  26480. juce_UseDebuggingNewOperator
  26481. private:
  26482. VSTPluginInstance& plugin;
  26483. bool isOpen, wasShowing, recursiveResize;
  26484. bool pluginWantsKeys, pluginRefusesToResize, alreadyInside;
  26485. #if JUCE_WINDOWS
  26486. HWND pluginHWND;
  26487. void* originalWndProc;
  26488. int sizeCheckCount;
  26489. #elif JUCE_LINUX
  26490. Window pluginWindow;
  26491. EventProcPtr pluginProc;
  26492. #endif
  26493. #if JUCE_MAC
  26494. void openPluginWindow (WindowRef parentWindow)
  26495. {
  26496. if (isOpen || parentWindow == 0)
  26497. return;
  26498. isOpen = true;
  26499. ERect* rect = 0;
  26500. dispatch (effEditGetRect, 0, 0, &rect, 0);
  26501. dispatch (effEditOpen, 0, 0, parentWindow, 0);
  26502. // do this before and after like in the steinberg example
  26503. dispatch (effEditGetRect, 0, 0, &rect, 0);
  26504. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  26505. // Install keyboard hooks
  26506. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  26507. // double-check it's not too tiny
  26508. int w = 250, h = 150;
  26509. if (rect != 0)
  26510. {
  26511. w = rect->right - rect->left;
  26512. h = rect->bottom - rect->top;
  26513. if (w == 0 || h == 0)
  26514. {
  26515. w = 250;
  26516. h = 150;
  26517. }
  26518. }
  26519. w = jmax (w, 32);
  26520. h = jmax (h, 32);
  26521. setSize (w, h);
  26522. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  26523. repaint();
  26524. }
  26525. #else
  26526. void openPluginWindow()
  26527. {
  26528. if (isOpen || getWindowHandle() == 0)
  26529. return;
  26530. log ("Opening VST UI: " + plugin.name);
  26531. isOpen = true;
  26532. ERect* rect = 0;
  26533. dispatch (effEditGetRect, 0, 0, &rect, 0);
  26534. dispatch (effEditOpen, 0, 0, getWindowHandle(), 0);
  26535. // do this before and after like in the steinberg example
  26536. dispatch (effEditGetRect, 0, 0, &rect, 0);
  26537. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  26538. // Install keyboard hooks
  26539. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  26540. #if JUCE_WINDOWS
  26541. originalWndProc = 0;
  26542. pluginHWND = GetWindow ((HWND) getWindowHandle(), GW_CHILD);
  26543. if (pluginHWND == 0)
  26544. {
  26545. isOpen = false;
  26546. setSize (300, 150);
  26547. return;
  26548. }
  26549. #pragma warning (push)
  26550. #pragma warning (disable: 4244)
  26551. originalWndProc = (void*) GetWindowLongPtr (pluginHWND, GWL_WNDPROC);
  26552. if (! pluginWantsKeys)
  26553. SetWindowLongPtr (pluginHWND, GWLP_WNDPROC, (LONG_PTR) vstHookWndProc);
  26554. #pragma warning (pop)
  26555. int w, h;
  26556. RECT r;
  26557. GetWindowRect (pluginHWND, &r);
  26558. w = r.right - r.left;
  26559. h = r.bottom - r.top;
  26560. if (rect != 0)
  26561. {
  26562. const int rw = rect->right - rect->left;
  26563. const int rh = rect->bottom - rect->top;
  26564. if ((rw > 50 && rh > 50 && rw < 2000 && rh < 2000 && rw != w && rh != h)
  26565. || ((w == 0 && rw > 0) || (h == 0 && rh > 0)))
  26566. {
  26567. // very dodgy logic to decide which size is right.
  26568. if (abs (rw - w) > 350 || abs (rh - h) > 350)
  26569. {
  26570. SetWindowPos (pluginHWND, 0,
  26571. 0, 0, rw, rh,
  26572. SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  26573. GetWindowRect (pluginHWND, &r);
  26574. w = r.right - r.left;
  26575. h = r.bottom - r.top;
  26576. pluginRefusesToResize = (w != rw) || (h != rh);
  26577. w = rw;
  26578. h = rh;
  26579. }
  26580. }
  26581. }
  26582. #elif JUCE_LINUX
  26583. pluginWindow = getChildWindow ((Window) getWindowHandle());
  26584. if (pluginWindow != 0)
  26585. pluginProc = (EventProcPtr) getPropertyFromXWindow (pluginWindow,
  26586. XInternAtom (display, "_XEventProc", False));
  26587. int w = 250, h = 150;
  26588. if (rect != 0)
  26589. {
  26590. w = rect->right - rect->left;
  26591. h = rect->bottom - rect->top;
  26592. if (w == 0 || h == 0)
  26593. {
  26594. w = 250;
  26595. h = 150;
  26596. }
  26597. }
  26598. if (pluginWindow != 0)
  26599. XMapRaised (display, pluginWindow);
  26600. #endif
  26601. // double-check it's not too tiny
  26602. w = jmax (w, 32);
  26603. h = jmax (h, 32);
  26604. setSize (w, h);
  26605. #if JUCE_WINDOWS
  26606. checkPluginWindowSize();
  26607. #endif
  26608. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  26609. repaint();
  26610. }
  26611. #endif
  26612. #if ! JUCE_MAC
  26613. void closePluginWindow()
  26614. {
  26615. if (isOpen)
  26616. {
  26617. log ("Closing VST UI: " + plugin.getName());
  26618. isOpen = false;
  26619. dispatch (effEditClose, 0, 0, 0, 0);
  26620. #if JUCE_WINDOWS
  26621. #pragma warning (push)
  26622. #pragma warning (disable: 4244)
  26623. if (pluginHWND != 0 && IsWindow (pluginHWND))
  26624. SetWindowLongPtr (pluginHWND, GWLP_WNDPROC, (LONG_PTR) originalWndProc);
  26625. #pragma warning (pop)
  26626. stopTimer();
  26627. if (pluginHWND != 0 && IsWindow (pluginHWND))
  26628. DestroyWindow (pluginHWND);
  26629. pluginHWND = 0;
  26630. #elif JUCE_LINUX
  26631. stopTimer();
  26632. pluginWindow = 0;
  26633. pluginProc = 0;
  26634. #endif
  26635. }
  26636. }
  26637. #endif
  26638. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt)
  26639. {
  26640. return plugin.dispatch (opcode, index, value, ptr, opt);
  26641. }
  26642. #if JUCE_WINDOWS
  26643. void checkPluginWindowSize() throw()
  26644. {
  26645. RECT r;
  26646. GetWindowRect (pluginHWND, &r);
  26647. const int w = r.right - r.left;
  26648. const int h = r.bottom - r.top;
  26649. if (isShowing() && w > 0 && h > 0
  26650. && (w != getWidth() || h != getHeight())
  26651. && ! pluginRefusesToResize)
  26652. {
  26653. setSize (w, h);
  26654. sizeCheckCount = 0;
  26655. }
  26656. }
  26657. // hooks to get keyboard events from VST windows..
  26658. static LRESULT CALLBACK vstHookWndProc (HWND hW, UINT message, WPARAM wParam, LPARAM lParam)
  26659. {
  26660. for (int i = activeVSTWindows.size(); --i >= 0;)
  26661. {
  26662. const VSTPluginWindow* const w = (const VSTPluginWindow*) activeVSTWindows.getUnchecked (i);
  26663. if (w->pluginHWND == hW)
  26664. {
  26665. if (message == WM_CHAR
  26666. || message == WM_KEYDOWN
  26667. || message == WM_SYSKEYDOWN
  26668. || message == WM_KEYUP
  26669. || message == WM_SYSKEYUP
  26670. || message == WM_APPCOMMAND)
  26671. {
  26672. SendMessage ((HWND) w->getTopLevelComponent()->getWindowHandle(),
  26673. message, wParam, lParam);
  26674. }
  26675. return CallWindowProc ((WNDPROC) (w->originalWndProc),
  26676. (HWND) w->pluginHWND,
  26677. message,
  26678. wParam,
  26679. lParam);
  26680. }
  26681. }
  26682. return DefWindowProc (hW, message, wParam, lParam);
  26683. }
  26684. #endif
  26685. #if JUCE_LINUX
  26686. // overload mouse/keyboard events to forward them to the plugin's inner window..
  26687. void sendEventToChild (XEvent* event)
  26688. {
  26689. if (pluginProc != 0)
  26690. {
  26691. // if the plugin publishes an event procedure, pass the event directly..
  26692. pluginProc (event);
  26693. }
  26694. else if (pluginWindow != 0)
  26695. {
  26696. // if the plugin has a window, then send the event to the window so that
  26697. // its message thread will pick it up..
  26698. XSendEvent (display, pluginWindow, False, 0L, event);
  26699. XFlush (display);
  26700. }
  26701. }
  26702. void mouseEnter (const MouseEvent& e)
  26703. {
  26704. if (pluginWindow != 0)
  26705. {
  26706. XEvent ev;
  26707. zerostruct (ev);
  26708. ev.xcrossing.display = display;
  26709. ev.xcrossing.type = EnterNotify;
  26710. ev.xcrossing.window = pluginWindow;
  26711. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  26712. ev.xcrossing.time = CurrentTime;
  26713. ev.xcrossing.x = e.x;
  26714. ev.xcrossing.y = e.y;
  26715. ev.xcrossing.x_root = e.getScreenX();
  26716. ev.xcrossing.y_root = e.getScreenY();
  26717. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  26718. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  26719. translateJuceToXCrossingModifiers (e, ev);
  26720. sendEventToChild (&ev);
  26721. }
  26722. }
  26723. void mouseExit (const MouseEvent& e)
  26724. {
  26725. if (pluginWindow != 0)
  26726. {
  26727. XEvent ev;
  26728. zerostruct (ev);
  26729. ev.xcrossing.display = display;
  26730. ev.xcrossing.type = LeaveNotify;
  26731. ev.xcrossing.window = pluginWindow;
  26732. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  26733. ev.xcrossing.time = CurrentTime;
  26734. ev.xcrossing.x = e.x;
  26735. ev.xcrossing.y = e.y;
  26736. ev.xcrossing.x_root = e.getScreenX();
  26737. ev.xcrossing.y_root = e.getScreenY();
  26738. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  26739. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  26740. ev.xcrossing.focus = hasKeyboardFocus (true); // TODO - yes ?
  26741. translateJuceToXCrossingModifiers (e, ev);
  26742. sendEventToChild (&ev);
  26743. }
  26744. }
  26745. void mouseMove (const MouseEvent& e)
  26746. {
  26747. if (pluginWindow != 0)
  26748. {
  26749. XEvent ev;
  26750. zerostruct (ev);
  26751. ev.xmotion.display = display;
  26752. ev.xmotion.type = MotionNotify;
  26753. ev.xmotion.window = pluginWindow;
  26754. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  26755. ev.xmotion.time = CurrentTime;
  26756. ev.xmotion.is_hint = NotifyNormal;
  26757. ev.xmotion.x = e.x;
  26758. ev.xmotion.y = e.y;
  26759. ev.xmotion.x_root = e.getScreenX();
  26760. ev.xmotion.y_root = e.getScreenY();
  26761. sendEventToChild (&ev);
  26762. }
  26763. }
  26764. void mouseDrag (const MouseEvent& e)
  26765. {
  26766. if (pluginWindow != 0)
  26767. {
  26768. XEvent ev;
  26769. zerostruct (ev);
  26770. ev.xmotion.display = display;
  26771. ev.xmotion.type = MotionNotify;
  26772. ev.xmotion.window = pluginWindow;
  26773. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  26774. ev.xmotion.time = CurrentTime;
  26775. ev.xmotion.x = e.x ;
  26776. ev.xmotion.y = e.y;
  26777. ev.xmotion.x_root = e.getScreenX();
  26778. ev.xmotion.y_root = e.getScreenY();
  26779. ev.xmotion.is_hint = NotifyNormal;
  26780. translateJuceToXMotionModifiers (e, ev);
  26781. sendEventToChild (&ev);
  26782. }
  26783. }
  26784. void mouseUp (const MouseEvent& e)
  26785. {
  26786. if (pluginWindow != 0)
  26787. {
  26788. XEvent ev;
  26789. zerostruct (ev);
  26790. ev.xbutton.display = display;
  26791. ev.xbutton.type = ButtonRelease;
  26792. ev.xbutton.window = pluginWindow;
  26793. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  26794. ev.xbutton.time = CurrentTime;
  26795. ev.xbutton.x = e.x;
  26796. ev.xbutton.y = e.y;
  26797. ev.xbutton.x_root = e.getScreenX();
  26798. ev.xbutton.y_root = e.getScreenY();
  26799. translateJuceToXButtonModifiers (e, ev);
  26800. sendEventToChild (&ev);
  26801. }
  26802. }
  26803. void mouseWheelMove (const MouseEvent& e,
  26804. float incrementX,
  26805. float incrementY)
  26806. {
  26807. if (pluginWindow != 0)
  26808. {
  26809. XEvent ev;
  26810. zerostruct (ev);
  26811. ev.xbutton.display = display;
  26812. ev.xbutton.type = ButtonPress;
  26813. ev.xbutton.window = pluginWindow;
  26814. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  26815. ev.xbutton.time = CurrentTime;
  26816. ev.xbutton.x = e.x;
  26817. ev.xbutton.y = e.y;
  26818. ev.xbutton.x_root = e.getScreenX();
  26819. ev.xbutton.y_root = e.getScreenY();
  26820. translateJuceToXMouseWheelModifiers (e, incrementY, ev);
  26821. sendEventToChild (&ev);
  26822. // TODO - put a usleep here ?
  26823. ev.xbutton.type = ButtonRelease;
  26824. sendEventToChild (&ev);
  26825. }
  26826. }
  26827. #endif
  26828. #if JUCE_MAC
  26829. #if ! JUCE_SUPPORT_CARBON
  26830. #error "To build VSTs, you need to enable the JUCE_SUPPORT_CARBON flag in your config!"
  26831. #endif
  26832. class InnerWrapperComponent : public CarbonViewWrapperComponent
  26833. {
  26834. public:
  26835. InnerWrapperComponent (VSTPluginWindow* const owner_)
  26836. : owner (owner_),
  26837. alreadyInside (false)
  26838. {
  26839. }
  26840. ~InnerWrapperComponent()
  26841. {
  26842. deleteWindow();
  26843. }
  26844. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  26845. {
  26846. owner->openPluginWindow (windowRef);
  26847. return 0;
  26848. }
  26849. void removeView (HIViewRef)
  26850. {
  26851. owner->dispatch (effEditClose, 0, 0, 0, 0);
  26852. owner->dispatch (effEditSleep, 0, 0, 0, 0);
  26853. }
  26854. bool getEmbeddedViewSize (int& w, int& h)
  26855. {
  26856. ERect* rect = 0;
  26857. owner->dispatch (effEditGetRect, 0, 0, &rect, 0);
  26858. w = rect->right - rect->left;
  26859. h = rect->bottom - rect->top;
  26860. return true;
  26861. }
  26862. void mouseDown (int x, int y)
  26863. {
  26864. if (! alreadyInside)
  26865. {
  26866. alreadyInside = true;
  26867. getTopLevelComponent()->toFront (true);
  26868. owner->dispatch (effEditMouse, x, y, 0, 0);
  26869. alreadyInside = false;
  26870. }
  26871. else
  26872. {
  26873. PostEvent (::mouseDown, 0);
  26874. }
  26875. }
  26876. void paint()
  26877. {
  26878. ComponentPeer* const peer = getPeer();
  26879. if (peer != 0)
  26880. {
  26881. const Point<int> pos (getScreenPosition() - peer->getScreenPosition());
  26882. ERect r;
  26883. r.left = pos.getX();
  26884. r.right = r.left + getWidth();
  26885. r.top = pos.getY();
  26886. r.bottom = r.top + getHeight();
  26887. owner->dispatch (effEditDraw, 0, 0, &r, 0);
  26888. }
  26889. }
  26890. private:
  26891. VSTPluginWindow* const owner;
  26892. bool alreadyInside;
  26893. };
  26894. friend class InnerWrapperComponent;
  26895. ScopedPointer <InnerWrapperComponent> innerWrapper;
  26896. void resized()
  26897. {
  26898. innerWrapper->setSize (getWidth(), getHeight());
  26899. }
  26900. #endif
  26901. };
  26902. AudioProcessorEditor* VSTPluginInstance::createEditor()
  26903. {
  26904. if (hasEditor())
  26905. return new VSTPluginWindow (*this);
  26906. return 0;
  26907. }
  26908. void VSTPluginInstance::handleAsyncUpdate()
  26909. {
  26910. // indicates that something about the plugin has changed..
  26911. updateHostDisplay();
  26912. }
  26913. bool VSTPluginInstance::restoreProgramSettings (const fxProgram* const prog)
  26914. {
  26915. if (vst_swap (prog->chunkMagic) == 'CcnK' && vst_swap (prog->fxMagic) == 'FxCk')
  26916. {
  26917. changeProgramName (getCurrentProgram(), prog->prgName);
  26918. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  26919. setParameter (i, vst_swapFloat (prog->params[i]));
  26920. return true;
  26921. }
  26922. return false;
  26923. }
  26924. bool VSTPluginInstance::loadFromFXBFile (const void* const data,
  26925. const int dataSize)
  26926. {
  26927. if (dataSize < 28)
  26928. return false;
  26929. const fxSet* const set = (const fxSet*) data;
  26930. if ((vst_swap (set->chunkMagic) != 'CcnK' && vst_swap (set->chunkMagic) != 'KncC')
  26931. || vst_swap (set->version) > fxbVersionNum)
  26932. return false;
  26933. if (vst_swap (set->fxMagic) == 'FxBk')
  26934. {
  26935. // bank of programs
  26936. if (vst_swap (set->numPrograms) >= 0)
  26937. {
  26938. const int oldProg = getCurrentProgram();
  26939. const int numParams = vst_swap (((const fxProgram*) (set->programs))->numParams);
  26940. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  26941. for (int i = 0; i < vst_swap (set->numPrograms); ++i)
  26942. {
  26943. if (i != oldProg)
  26944. {
  26945. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + i * progLen);
  26946. if (((const char*) prog) - ((const char*) set) >= dataSize)
  26947. return false;
  26948. if (vst_swap (set->numPrograms) > 0)
  26949. setCurrentProgram (i);
  26950. if (! restoreProgramSettings (prog))
  26951. return false;
  26952. }
  26953. }
  26954. if (vst_swap (set->numPrograms) > 0)
  26955. setCurrentProgram (oldProg);
  26956. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + oldProg * progLen);
  26957. if (((const char*) prog) - ((const char*) set) >= dataSize)
  26958. return false;
  26959. if (! restoreProgramSettings (prog))
  26960. return false;
  26961. }
  26962. }
  26963. else if (vst_swap (set->fxMagic) == 'FxCk')
  26964. {
  26965. // single program
  26966. const fxProgram* const prog = (const fxProgram*) data;
  26967. if (vst_swap (prog->chunkMagic) != 'CcnK')
  26968. return false;
  26969. changeProgramName (getCurrentProgram(), prog->prgName);
  26970. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  26971. setParameter (i, vst_swapFloat (prog->params[i]));
  26972. }
  26973. else if (vst_swap (set->fxMagic) == 'FBCh' || vst_swap (set->fxMagic) == 'hCBF')
  26974. {
  26975. // non-preset chunk
  26976. const fxChunkSet* const cset = (const fxChunkSet*) data;
  26977. if (vst_swap (cset->chunkSize) + sizeof (fxChunkSet) - 8 > (unsigned int) dataSize)
  26978. return false;
  26979. setChunkData (cset->chunk, vst_swap (cset->chunkSize), false);
  26980. }
  26981. else if (vst_swap (set->fxMagic) == 'FPCh' || vst_swap (set->fxMagic) == 'hCPF')
  26982. {
  26983. // preset chunk
  26984. const fxProgramSet* const cset = (const fxProgramSet*) data;
  26985. if (vst_swap (cset->chunkSize) + sizeof (fxProgramSet) - 8 > (unsigned int) dataSize)
  26986. return false;
  26987. setChunkData (cset->chunk, vst_swap (cset->chunkSize), true);
  26988. changeProgramName (getCurrentProgram(), cset->name);
  26989. }
  26990. else
  26991. {
  26992. return false;
  26993. }
  26994. return true;
  26995. }
  26996. void VSTPluginInstance::setParamsInProgramBlock (fxProgram* const prog) throw()
  26997. {
  26998. const int numParams = getNumParameters();
  26999. prog->chunkMagic = vst_swap ('CcnK');
  27000. prog->byteSize = 0;
  27001. prog->fxMagic = vst_swap ('FxCk');
  27002. prog->version = vst_swap (fxbVersionNum);
  27003. prog->fxID = vst_swap (getUID());
  27004. prog->fxVersion = vst_swap (getVersionNumber());
  27005. prog->numParams = vst_swap (numParams);
  27006. getCurrentProgramName().copyToCString (prog->prgName, sizeof (prog->prgName) - 1);
  27007. for (int i = 0; i < numParams; ++i)
  27008. prog->params[i] = vst_swapFloat (getParameter (i));
  27009. }
  27010. bool VSTPluginInstance::saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB)
  27011. {
  27012. const int numPrograms = getNumPrograms();
  27013. const int numParams = getNumParameters();
  27014. if (usesChunks())
  27015. {
  27016. if (isFXB)
  27017. {
  27018. MemoryBlock chunk;
  27019. getChunkData (chunk, false, maxSizeMB);
  27020. const size_t totalLen = sizeof (fxChunkSet) + chunk.getSize() - 8;
  27021. dest.setSize (totalLen, true);
  27022. fxChunkSet* const set = (fxChunkSet*) dest.getData();
  27023. set->chunkMagic = vst_swap ('CcnK');
  27024. set->byteSize = 0;
  27025. set->fxMagic = vst_swap ('FBCh');
  27026. set->version = vst_swap (fxbVersionNum);
  27027. set->fxID = vst_swap (getUID());
  27028. set->fxVersion = vst_swap (getVersionNumber());
  27029. set->numPrograms = vst_swap (numPrograms);
  27030. set->chunkSize = vst_swap ((long) chunk.getSize());
  27031. chunk.copyTo (set->chunk, 0, chunk.getSize());
  27032. }
  27033. else
  27034. {
  27035. MemoryBlock chunk;
  27036. getChunkData (chunk, true, maxSizeMB);
  27037. const size_t totalLen = sizeof (fxProgramSet) + chunk.getSize() - 8;
  27038. dest.setSize (totalLen, true);
  27039. fxProgramSet* const set = (fxProgramSet*) dest.getData();
  27040. set->chunkMagic = vst_swap ('CcnK');
  27041. set->byteSize = 0;
  27042. set->fxMagic = vst_swap ('FPCh');
  27043. set->version = vst_swap (fxbVersionNum);
  27044. set->fxID = vst_swap (getUID());
  27045. set->fxVersion = vst_swap (getVersionNumber());
  27046. set->numPrograms = vst_swap (numPrograms);
  27047. set->chunkSize = vst_swap ((long) chunk.getSize());
  27048. getCurrentProgramName().copyToCString (set->name, sizeof (set->name) - 1);
  27049. chunk.copyTo (set->chunk, 0, chunk.getSize());
  27050. }
  27051. }
  27052. else
  27053. {
  27054. if (isFXB)
  27055. {
  27056. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  27057. const int len = (sizeof (fxSet) - sizeof (fxProgram)) + progLen * jmax (1, numPrograms);
  27058. dest.setSize (len, true);
  27059. fxSet* const set = (fxSet*) dest.getData();
  27060. set->chunkMagic = vst_swap ('CcnK');
  27061. set->byteSize = 0;
  27062. set->fxMagic = vst_swap ('FxBk');
  27063. set->version = vst_swap (fxbVersionNum);
  27064. set->fxID = vst_swap (getUID());
  27065. set->fxVersion = vst_swap (getVersionNumber());
  27066. set->numPrograms = vst_swap (numPrograms);
  27067. const int oldProgram = getCurrentProgram();
  27068. MemoryBlock oldSettings;
  27069. createTempParameterStore (oldSettings);
  27070. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + oldProgram * progLen));
  27071. for (int i = 0; i < numPrograms; ++i)
  27072. {
  27073. if (i != oldProgram)
  27074. {
  27075. setCurrentProgram (i);
  27076. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + i * progLen));
  27077. }
  27078. }
  27079. setCurrentProgram (oldProgram);
  27080. restoreFromTempParameterStore (oldSettings);
  27081. }
  27082. else
  27083. {
  27084. const int totalLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  27085. dest.setSize (totalLen, true);
  27086. setParamsInProgramBlock ((fxProgram*) dest.getData());
  27087. }
  27088. }
  27089. return true;
  27090. }
  27091. void VSTPluginInstance::getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const
  27092. {
  27093. if (usesChunks())
  27094. {
  27095. void* data = 0;
  27096. const int bytes = dispatch (effGetChunk, isPreset ? 1 : 0, 0, &data, 0.0f);
  27097. if (data != 0 && bytes <= maxSizeMB * 1024 * 1024)
  27098. {
  27099. mb.setSize (bytes);
  27100. mb.copyFrom (data, 0, bytes);
  27101. }
  27102. }
  27103. }
  27104. void VSTPluginInstance::setChunkData (const char* data, int size, bool isPreset)
  27105. {
  27106. if (size > 0 && usesChunks())
  27107. {
  27108. dispatch (effSetChunk, isPreset ? 1 : 0, size, (void*) data, 0.0f);
  27109. if (! isPreset)
  27110. updateStoredProgramNames();
  27111. }
  27112. }
  27113. void VSTPluginInstance::timerCallback()
  27114. {
  27115. if (dispatch (effIdle, 0, 0, 0, 0) == 0)
  27116. stopTimer();
  27117. }
  27118. int VSTPluginInstance::dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const
  27119. {
  27120. const ScopedLock sl (lock);
  27121. ++insideVSTCallback;
  27122. int result = 0;
  27123. try
  27124. {
  27125. if (effect != 0)
  27126. {
  27127. #if JUCE_MAC
  27128. if (module->resFileId != 0)
  27129. UseResFile (module->resFileId);
  27130. CGrafPtr oldPort;
  27131. if (getActiveEditor() != 0)
  27132. {
  27133. const Point<int> pos (getActiveEditor()->relativePositionToOtherComponent (getActiveEditor()->getTopLevelComponent(), Point<int>()));
  27134. GetPort (&oldPort);
  27135. SetPortWindowPort ((WindowRef) getActiveEditor()->getWindowHandle());
  27136. SetOrigin (-pos.getX(), -pos.getY());
  27137. }
  27138. #endif
  27139. result = effect->dispatcher (effect, opcode, index, value, ptr, opt);
  27140. #if JUCE_MAC
  27141. if (getActiveEditor() != 0)
  27142. SetPort (oldPort);
  27143. module->resFileId = CurResFile();
  27144. #endif
  27145. --insideVSTCallback;
  27146. return result;
  27147. }
  27148. }
  27149. catch (...)
  27150. {
  27151. }
  27152. --insideVSTCallback;
  27153. return result;
  27154. }
  27155. // handles non plugin-specific callbacks..
  27156. static const int defaultVSTSampleRateValue = 16384;
  27157. static const int defaultVSTBlockSizeValue = 512;
  27158. static VstIntPtr handleGeneralCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  27159. {
  27160. (void) index;
  27161. (void) value;
  27162. (void) opt;
  27163. switch (opcode)
  27164. {
  27165. case audioMasterCanDo:
  27166. {
  27167. static const char* canDos[] = { "supplyIdle",
  27168. "sendVstEvents",
  27169. "sendVstMidiEvent",
  27170. "sendVstTimeInfo",
  27171. "receiveVstEvents",
  27172. "receiveVstMidiEvent",
  27173. "supportShell",
  27174. "shellCategory" };
  27175. for (int i = 0; i < numElementsInArray (canDos); ++i)
  27176. if (strcmp (canDos[i], (const char*) ptr) == 0)
  27177. return 1;
  27178. return 0;
  27179. }
  27180. case audioMasterVersion:
  27181. return 0x2400;
  27182. case audioMasterCurrentId:
  27183. return shellUIDToCreate;
  27184. case audioMasterGetNumAutomatableParameters:
  27185. return 0;
  27186. case audioMasterGetAutomationState:
  27187. return 1;
  27188. case audioMasterGetVendorVersion:
  27189. return 0x0101;
  27190. case audioMasterGetVendorString:
  27191. case audioMasterGetProductString:
  27192. {
  27193. String hostName ("Juce VST Host");
  27194. if (JUCEApplication::getInstance() != 0)
  27195. hostName = JUCEApplication::getInstance()->getApplicationName();
  27196. hostName.copyToCString ((char*) ptr, jmin (kVstMaxVendorStrLen, kVstMaxProductStrLen) - 1);
  27197. }
  27198. break;
  27199. case audioMasterGetSampleRate:
  27200. return (VstIntPtr) defaultVSTSampleRateValue;
  27201. case audioMasterGetBlockSize:
  27202. return (VstIntPtr) defaultVSTBlockSizeValue;
  27203. case audioMasterSetOutputSampleRate:
  27204. return 0;
  27205. default:
  27206. DBG ("*** Unhandled VST Callback: " + String ((int) opcode));
  27207. break;
  27208. }
  27209. return 0;
  27210. }
  27211. // handles callbacks for a specific plugin
  27212. VstIntPtr VSTPluginInstance::handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  27213. {
  27214. switch (opcode)
  27215. {
  27216. case audioMasterAutomate:
  27217. sendParamChangeMessageToListeners (index, opt);
  27218. break;
  27219. case audioMasterProcessEvents:
  27220. handleMidiFromPlugin ((const VstEvents*) ptr);
  27221. break;
  27222. case audioMasterGetTime:
  27223. #if JUCE_MSVC
  27224. #pragma warning (push)
  27225. #pragma warning (disable: 4311)
  27226. #endif
  27227. return (VstIntPtr) &vstHostTime;
  27228. #if JUCE_MSVC
  27229. #pragma warning (pop)
  27230. #endif
  27231. break;
  27232. case audioMasterIdle:
  27233. if (insideVSTCallback == 0 && MessageManager::getInstance()->isThisTheMessageThread())
  27234. {
  27235. ++insideVSTCallback;
  27236. #if JUCE_MAC
  27237. if (getActiveEditor() != 0)
  27238. dispatch (effEditIdle, 0, 0, 0, 0);
  27239. #endif
  27240. juce_callAnyTimersSynchronously();
  27241. handleUpdateNowIfNeeded();
  27242. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  27243. ComponentPeer::getPeer (i)->performAnyPendingRepaintsNow();
  27244. --insideVSTCallback;
  27245. }
  27246. break;
  27247. case audioMasterUpdateDisplay:
  27248. triggerAsyncUpdate();
  27249. break;
  27250. case audioMasterTempoAt:
  27251. // returns (10000 * bpm)
  27252. break;
  27253. case audioMasterNeedIdle:
  27254. startTimer (50);
  27255. break;
  27256. case audioMasterSizeWindow:
  27257. if (getActiveEditor() != 0)
  27258. getActiveEditor()->setSize (index, value);
  27259. return 1;
  27260. case audioMasterGetSampleRate:
  27261. return (VstIntPtr) (getSampleRate() > 0 ? getSampleRate() : defaultVSTSampleRateValue);
  27262. case audioMasterGetBlockSize:
  27263. return (VstIntPtr) (getBlockSize() > 0 ? getBlockSize() : defaultVSTBlockSizeValue);
  27264. case audioMasterWantMidi:
  27265. wantsMidiMessages = true;
  27266. break;
  27267. case audioMasterGetDirectory:
  27268. #if JUCE_MAC
  27269. return (VstIntPtr) (void*) &module->parentDirFSSpec;
  27270. #else
  27271. return (VstIntPtr) (pointer_sized_uint) module->fullParentDirectoryPathName.toUTF8();
  27272. #endif
  27273. case audioMasterGetAutomationState:
  27274. // returns 0: not supported, 1: off, 2:read, 3:write, 4:read/write
  27275. break;
  27276. // none of these are handled (yet)..
  27277. case audioMasterBeginEdit:
  27278. case audioMasterEndEdit:
  27279. case audioMasterSetTime:
  27280. case audioMasterPinConnected:
  27281. case audioMasterGetParameterQuantization:
  27282. case audioMasterIOChanged:
  27283. case audioMasterGetInputLatency:
  27284. case audioMasterGetOutputLatency:
  27285. case audioMasterGetPreviousPlug:
  27286. case audioMasterGetNextPlug:
  27287. case audioMasterWillReplaceOrAccumulate:
  27288. case audioMasterGetCurrentProcessLevel:
  27289. case audioMasterOfflineStart:
  27290. case audioMasterOfflineRead:
  27291. case audioMasterOfflineWrite:
  27292. case audioMasterOfflineGetCurrentPass:
  27293. case audioMasterOfflineGetCurrentMetaPass:
  27294. case audioMasterVendorSpecific:
  27295. case audioMasterSetIcon:
  27296. case audioMasterGetLanguage:
  27297. case audioMasterOpenWindow:
  27298. case audioMasterCloseWindow:
  27299. break;
  27300. default:
  27301. return handleGeneralCallback (opcode, index, value, ptr, opt);
  27302. }
  27303. return 0;
  27304. }
  27305. // entry point for all callbacks from the plugin
  27306. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt)
  27307. {
  27308. try
  27309. {
  27310. if (effect != 0 && effect->resvd2 != 0)
  27311. {
  27312. return ((VSTPluginInstance*)(effect->resvd2))
  27313. ->handleCallback (opcode, index, value, ptr, opt);
  27314. }
  27315. return handleGeneralCallback (opcode, index, value, ptr, opt);
  27316. }
  27317. catch (...)
  27318. {
  27319. return 0;
  27320. }
  27321. }
  27322. const String VSTPluginInstance::getVersion() const throw()
  27323. {
  27324. unsigned int v = dispatch (effGetVendorVersion, 0, 0, 0, 0);
  27325. String s;
  27326. if (v == 0 || v == -1)
  27327. v = getVersionNumber();
  27328. if (v != 0)
  27329. {
  27330. int versionBits[4];
  27331. int n = 0;
  27332. while (v != 0)
  27333. {
  27334. versionBits [n++] = (v & 0xff);
  27335. v >>= 8;
  27336. }
  27337. s << 'V';
  27338. while (n > 0)
  27339. {
  27340. s << versionBits [--n];
  27341. if (n > 0)
  27342. s << '.';
  27343. }
  27344. }
  27345. return s;
  27346. }
  27347. int VSTPluginInstance::getUID() const throw()
  27348. {
  27349. int uid = effect != 0 ? effect->uniqueID : 0;
  27350. if (uid == 0)
  27351. uid = module->file.hashCode();
  27352. return uid;
  27353. }
  27354. const String VSTPluginInstance::getCategory() const throw()
  27355. {
  27356. const char* result = 0;
  27357. switch (dispatch (effGetPlugCategory, 0, 0, 0, 0))
  27358. {
  27359. case kPlugCategEffect:
  27360. result = "Effect";
  27361. break;
  27362. case kPlugCategSynth:
  27363. result = "Synth";
  27364. break;
  27365. case kPlugCategAnalysis:
  27366. result = "Anaylsis";
  27367. break;
  27368. case kPlugCategMastering:
  27369. result = "Mastering";
  27370. break;
  27371. case kPlugCategSpacializer:
  27372. result = "Spacial";
  27373. break;
  27374. case kPlugCategRoomFx:
  27375. result = "Reverb";
  27376. break;
  27377. case kPlugSurroundFx:
  27378. result = "Surround";
  27379. break;
  27380. case kPlugCategRestoration:
  27381. result = "Restoration";
  27382. break;
  27383. case kPlugCategGenerator:
  27384. result = "Tone generation";
  27385. break;
  27386. default:
  27387. break;
  27388. }
  27389. return result;
  27390. }
  27391. float VSTPluginInstance::getParameter (int index)
  27392. {
  27393. if (effect != 0 && ((unsigned int) index) < (unsigned int) effect->numParams)
  27394. {
  27395. try
  27396. {
  27397. const ScopedLock sl (lock);
  27398. return effect->getParameter (effect, index);
  27399. }
  27400. catch (...)
  27401. {
  27402. }
  27403. }
  27404. return 0.0f;
  27405. }
  27406. void VSTPluginInstance::setParameter (int index, float newValue)
  27407. {
  27408. if (effect != 0 && ((unsigned int) index) < (unsigned int) effect->numParams)
  27409. {
  27410. try
  27411. {
  27412. const ScopedLock sl (lock);
  27413. if (effect->getParameter (effect, index) != newValue)
  27414. effect->setParameter (effect, index, newValue);
  27415. }
  27416. catch (...)
  27417. {
  27418. }
  27419. }
  27420. }
  27421. const String VSTPluginInstance::getParameterName (int index)
  27422. {
  27423. if (effect != 0)
  27424. {
  27425. jassert (index >= 0 && index < effect->numParams);
  27426. char nm [256];
  27427. zerostruct (nm);
  27428. dispatch (effGetParamName, index, 0, nm, 0);
  27429. return String (nm).trim();
  27430. }
  27431. return String::empty;
  27432. }
  27433. const String VSTPluginInstance::getParameterLabel (int index) const
  27434. {
  27435. if (effect != 0)
  27436. {
  27437. jassert (index >= 0 && index < effect->numParams);
  27438. char nm [256];
  27439. zerostruct (nm);
  27440. dispatch (effGetParamLabel, index, 0, nm, 0);
  27441. return String (nm).trim();
  27442. }
  27443. return String::empty;
  27444. }
  27445. const String VSTPluginInstance::getParameterText (int index)
  27446. {
  27447. if (effect != 0)
  27448. {
  27449. jassert (index >= 0 && index < effect->numParams);
  27450. char nm [256];
  27451. zerostruct (nm);
  27452. dispatch (effGetParamDisplay, index, 0, nm, 0);
  27453. return String (nm).trim();
  27454. }
  27455. return String::empty;
  27456. }
  27457. bool VSTPluginInstance::isParameterAutomatable (int index) const
  27458. {
  27459. if (effect != 0)
  27460. {
  27461. jassert (index >= 0 && index < effect->numParams);
  27462. return dispatch (effCanBeAutomated, index, 0, 0, 0) != 0;
  27463. }
  27464. return false;
  27465. }
  27466. void VSTPluginInstance::createTempParameterStore (MemoryBlock& dest)
  27467. {
  27468. dest.setSize (64 + 4 * getNumParameters());
  27469. dest.fillWith (0);
  27470. getCurrentProgramName().copyToCString ((char*) dest.getData(), 63);
  27471. float* const p = (float*) (((char*) dest.getData()) + 64);
  27472. for (int i = 0; i < getNumParameters(); ++i)
  27473. p[i] = getParameter(i);
  27474. }
  27475. void VSTPluginInstance::restoreFromTempParameterStore (const MemoryBlock& m)
  27476. {
  27477. changeProgramName (getCurrentProgram(), (const char*) m.getData());
  27478. float* p = (float*) (((char*) m.getData()) + 64);
  27479. for (int i = 0; i < getNumParameters(); ++i)
  27480. setParameter (i, p[i]);
  27481. }
  27482. void VSTPluginInstance::setCurrentProgram (int newIndex)
  27483. {
  27484. if (getNumPrograms() > 0 && newIndex != getCurrentProgram())
  27485. dispatch (effSetProgram, 0, jlimit (0, getNumPrograms() - 1, newIndex), 0, 0);
  27486. }
  27487. const String VSTPluginInstance::getProgramName (int index)
  27488. {
  27489. if (index == getCurrentProgram())
  27490. {
  27491. return getCurrentProgramName();
  27492. }
  27493. else if (effect != 0)
  27494. {
  27495. char nm [256];
  27496. zerostruct (nm);
  27497. if (dispatch (effGetProgramNameIndexed,
  27498. jlimit (0, getNumPrograms(), index),
  27499. -1, nm, 0) != 0)
  27500. {
  27501. return String (nm).trim();
  27502. }
  27503. }
  27504. return programNames [index];
  27505. }
  27506. void VSTPluginInstance::changeProgramName (int index, const String& newName)
  27507. {
  27508. if (index == getCurrentProgram())
  27509. {
  27510. if (getNumPrograms() > 0 && newName != getCurrentProgramName())
  27511. dispatch (effSetProgramName, 0, 0, (void*) newName.substring (0, 24).toCString(), 0.0f);
  27512. }
  27513. else
  27514. {
  27515. jassertfalse; // xxx not implemented!
  27516. }
  27517. }
  27518. void VSTPluginInstance::updateStoredProgramNames()
  27519. {
  27520. if (effect != 0 && getNumPrograms() > 0)
  27521. {
  27522. char nm [256];
  27523. zerostruct (nm);
  27524. // only do this if the plugin can't use indexed names..
  27525. if (dispatch (effGetProgramNameIndexed, 0, -1, nm, 0) == 0)
  27526. {
  27527. const int oldProgram = getCurrentProgram();
  27528. MemoryBlock oldSettings;
  27529. createTempParameterStore (oldSettings);
  27530. for (int i = 0; i < getNumPrograms(); ++i)
  27531. {
  27532. setCurrentProgram (i);
  27533. getCurrentProgramName(); // (this updates the list)
  27534. }
  27535. setCurrentProgram (oldProgram);
  27536. restoreFromTempParameterStore (oldSettings);
  27537. }
  27538. }
  27539. }
  27540. const String VSTPluginInstance::getCurrentProgramName()
  27541. {
  27542. if (effect != 0)
  27543. {
  27544. char nm [256];
  27545. zerostruct (nm);
  27546. dispatch (effGetProgramName, 0, 0, nm, 0);
  27547. const int index = getCurrentProgram();
  27548. if (programNames[index].isEmpty())
  27549. {
  27550. while (programNames.size() < index)
  27551. programNames.add (String::empty);
  27552. programNames.set (index, String (nm).trim());
  27553. }
  27554. return String (nm).trim();
  27555. }
  27556. return String::empty;
  27557. }
  27558. const String VSTPluginInstance::getInputChannelName (const int index) const
  27559. {
  27560. if (index >= 0 && index < getNumInputChannels())
  27561. {
  27562. VstPinProperties pinProps;
  27563. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  27564. return String (pinProps.label, sizeof (pinProps.label));
  27565. }
  27566. return String::empty;
  27567. }
  27568. bool VSTPluginInstance::isInputChannelStereoPair (int index) const
  27569. {
  27570. if (index < 0 || index >= getNumInputChannels())
  27571. return false;
  27572. VstPinProperties pinProps;
  27573. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  27574. return (pinProps.flags & kVstPinIsStereo) != 0;
  27575. return true;
  27576. }
  27577. const String VSTPluginInstance::getOutputChannelName (const int index) const
  27578. {
  27579. if (index >= 0 && index < getNumOutputChannels())
  27580. {
  27581. VstPinProperties pinProps;
  27582. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  27583. return String (pinProps.label, sizeof (pinProps.label));
  27584. }
  27585. return String::empty;
  27586. }
  27587. bool VSTPluginInstance::isOutputChannelStereoPair (int index) const
  27588. {
  27589. if (index < 0 || index >= getNumOutputChannels())
  27590. return false;
  27591. VstPinProperties pinProps;
  27592. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  27593. return (pinProps.flags & kVstPinIsStereo) != 0;
  27594. return true;
  27595. }
  27596. void VSTPluginInstance::setPower (const bool on)
  27597. {
  27598. dispatch (effMainsChanged, 0, on ? 1 : 0, 0, 0);
  27599. isPowerOn = on;
  27600. }
  27601. const int defaultMaxSizeMB = 64;
  27602. void VSTPluginInstance::getStateInformation (MemoryBlock& destData)
  27603. {
  27604. saveToFXBFile (destData, true, defaultMaxSizeMB);
  27605. }
  27606. void VSTPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  27607. {
  27608. saveToFXBFile (destData, false, defaultMaxSizeMB);
  27609. }
  27610. void VSTPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  27611. {
  27612. loadFromFXBFile (data, sizeInBytes);
  27613. }
  27614. void VSTPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  27615. {
  27616. loadFromFXBFile (data, sizeInBytes);
  27617. }
  27618. VSTPluginFormat::VSTPluginFormat()
  27619. {
  27620. }
  27621. VSTPluginFormat::~VSTPluginFormat()
  27622. {
  27623. }
  27624. void VSTPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  27625. const String& fileOrIdentifier)
  27626. {
  27627. if (! fileMightContainThisPluginType (fileOrIdentifier))
  27628. return;
  27629. PluginDescription desc;
  27630. desc.fileOrIdentifier = fileOrIdentifier;
  27631. desc.uid = 0;
  27632. ScopedPointer <VSTPluginInstance> instance (dynamic_cast <VSTPluginInstance*> (createInstanceFromDescription (desc)));
  27633. if (instance == 0)
  27634. return;
  27635. try
  27636. {
  27637. #if JUCE_MAC
  27638. if (instance->module->resFileId != 0)
  27639. UseResFile (instance->module->resFileId);
  27640. #endif
  27641. instance->fillInPluginDescription (desc);
  27642. VstPlugCategory category = (VstPlugCategory) instance->dispatch (effGetPlugCategory, 0, 0, 0, 0);
  27643. if (category != kPlugCategShell)
  27644. {
  27645. // Normal plugin...
  27646. results.add (new PluginDescription (desc));
  27647. ++insideVSTCallback;
  27648. instance->dispatch (effOpen, 0, 0, 0, 0);
  27649. --insideVSTCallback;
  27650. }
  27651. else
  27652. {
  27653. // It's a shell plugin, so iterate all the subtypes...
  27654. char shellEffectName [64];
  27655. for (;;)
  27656. {
  27657. zerostruct (shellEffectName);
  27658. const int uid = instance->dispatch (effShellGetNextPlugin, 0, 0, shellEffectName, 0);
  27659. if (uid == 0)
  27660. {
  27661. break;
  27662. }
  27663. else
  27664. {
  27665. desc.uid = uid;
  27666. desc.name = shellEffectName;
  27667. bool alreadyThere = false;
  27668. for (int i = results.size(); --i >= 0;)
  27669. {
  27670. PluginDescription* const d = results.getUnchecked(i);
  27671. if (d->isDuplicateOf (desc))
  27672. {
  27673. alreadyThere = true;
  27674. break;
  27675. }
  27676. }
  27677. if (! alreadyThere)
  27678. results.add (new PluginDescription (desc));
  27679. }
  27680. }
  27681. }
  27682. }
  27683. catch (...)
  27684. {
  27685. // crashed while loading...
  27686. }
  27687. }
  27688. AudioPluginInstance* VSTPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  27689. {
  27690. ScopedPointer <VSTPluginInstance> result;
  27691. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  27692. {
  27693. File file (desc.fileOrIdentifier);
  27694. const File previousWorkingDirectory (File::getCurrentWorkingDirectory());
  27695. file.getParentDirectory().setAsCurrentWorkingDirectory();
  27696. const ReferenceCountedObjectPtr <ModuleHandle> module (ModuleHandle::findOrCreateModule (file));
  27697. if (module != 0)
  27698. {
  27699. shellUIDToCreate = desc.uid;
  27700. result = new VSTPluginInstance (module);
  27701. if (result->effect != 0)
  27702. {
  27703. result->effect->resvd2 = (VstIntPtr) (pointer_sized_int) (VSTPluginInstance*) result;
  27704. result->initialise();
  27705. }
  27706. else
  27707. {
  27708. result = 0;
  27709. }
  27710. }
  27711. previousWorkingDirectory.setAsCurrentWorkingDirectory();
  27712. }
  27713. return result.release();
  27714. }
  27715. bool VSTPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  27716. {
  27717. const File f (fileOrIdentifier);
  27718. #if JUCE_MAC
  27719. if (f.isDirectory() && f.hasFileExtension (".vst"))
  27720. return true;
  27721. #if JUCE_PPC
  27722. FSRef fileRef;
  27723. if (PlatformUtilities::makeFSRefFromPath (&fileRef, f.getFullPathName()))
  27724. {
  27725. const short resFileId = FSOpenResFile (&fileRef, fsRdPerm);
  27726. if (resFileId != -1)
  27727. {
  27728. const int numEffects = Count1Resources ('aEff');
  27729. CloseResFile (resFileId);
  27730. if (numEffects > 0)
  27731. return true;
  27732. }
  27733. }
  27734. #endif
  27735. return false;
  27736. #elif JUCE_WINDOWS
  27737. return f.existsAsFile()
  27738. && f.hasFileExtension (".dll");
  27739. #elif JUCE_LINUX
  27740. return f.existsAsFile()
  27741. && f.hasFileExtension (".so");
  27742. #endif
  27743. }
  27744. const String VSTPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  27745. {
  27746. return fileOrIdentifier;
  27747. }
  27748. bool VSTPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  27749. {
  27750. return File (desc.fileOrIdentifier).exists();
  27751. }
  27752. const StringArray VSTPluginFormat::searchPathsForPlugins (const FileSearchPath& directoriesToSearch, const bool recursive)
  27753. {
  27754. StringArray results;
  27755. for (int j = 0; j < directoriesToSearch.getNumPaths(); ++j)
  27756. recursiveFileSearch (results, directoriesToSearch [j], recursive);
  27757. return results;
  27758. }
  27759. void VSTPluginFormat::recursiveFileSearch (StringArray& results, const File& dir, const bool recursive)
  27760. {
  27761. // avoid allowing the dir iterator to be recursive, because we want to avoid letting it delve inside
  27762. // .component or .vst directories.
  27763. DirectoryIterator iter (dir, false, "*", File::findFilesAndDirectories);
  27764. while (iter.next())
  27765. {
  27766. const File f (iter.getFile());
  27767. bool isPlugin = false;
  27768. if (fileMightContainThisPluginType (f.getFullPathName()))
  27769. {
  27770. isPlugin = true;
  27771. results.add (f.getFullPathName());
  27772. }
  27773. if (recursive && (! isPlugin) && f.isDirectory())
  27774. recursiveFileSearch (results, f, true);
  27775. }
  27776. }
  27777. const FileSearchPath VSTPluginFormat::getDefaultLocationsToSearch()
  27778. {
  27779. #if JUCE_MAC
  27780. return FileSearchPath ("~/Library/Audio/Plug-Ins/VST;/Library/Audio/Plug-Ins/VST");
  27781. #elif JUCE_WINDOWS
  27782. const String programFiles (File::getSpecialLocation (File::globalApplicationsDirectory).getFullPathName());
  27783. return FileSearchPath (programFiles + "\\Steinberg\\VstPlugins");
  27784. #elif JUCE_LINUX
  27785. return FileSearchPath ("/usr/lib/vst");
  27786. #endif
  27787. }
  27788. END_JUCE_NAMESPACE
  27789. #endif
  27790. #undef log
  27791. #endif
  27792. /*** End of inlined file: juce_VSTPluginFormat.cpp ***/
  27793. /*** End of inlined file: juce_VSTPluginFormat.mm ***/
  27794. /*** Start of inlined file: juce_AudioProcessor.cpp ***/
  27795. BEGIN_JUCE_NAMESPACE
  27796. AudioProcessor::AudioProcessor()
  27797. : playHead (0),
  27798. activeEditor (0),
  27799. sampleRate (0),
  27800. blockSize (0),
  27801. numInputChannels (0),
  27802. numOutputChannels (0),
  27803. latencySamples (0),
  27804. suspended (false),
  27805. nonRealtime (false)
  27806. {
  27807. }
  27808. AudioProcessor::~AudioProcessor()
  27809. {
  27810. // ooh, nasty - the editor should have been deleted before the filter
  27811. // that it refers to is deleted..
  27812. jassert (activeEditor == 0);
  27813. #if JUCE_DEBUG
  27814. // This will fail if you've called beginParameterChangeGesture() for one
  27815. // or more parameters without having made a corresponding call to endParameterChangeGesture...
  27816. jassert (changingParams.countNumberOfSetBits() == 0);
  27817. #endif
  27818. }
  27819. void AudioProcessor::setPlayHead (AudioPlayHead* const newPlayHead) throw()
  27820. {
  27821. playHead = newPlayHead;
  27822. }
  27823. void AudioProcessor::addListener (AudioProcessorListener* const newListener) throw()
  27824. {
  27825. const ScopedLock sl (listenerLock);
  27826. listeners.addIfNotAlreadyThere (newListener);
  27827. }
  27828. void AudioProcessor::removeListener (AudioProcessorListener* const listenerToRemove) throw()
  27829. {
  27830. const ScopedLock sl (listenerLock);
  27831. listeners.removeValue (listenerToRemove);
  27832. }
  27833. void AudioProcessor::setPlayConfigDetails (const int numIns,
  27834. const int numOuts,
  27835. const double sampleRate_,
  27836. const int blockSize_) throw()
  27837. {
  27838. numInputChannels = numIns;
  27839. numOutputChannels = numOuts;
  27840. sampleRate = sampleRate_;
  27841. blockSize = blockSize_;
  27842. }
  27843. void AudioProcessor::setNonRealtime (const bool nonRealtime_) throw()
  27844. {
  27845. nonRealtime = nonRealtime_;
  27846. }
  27847. void AudioProcessor::setLatencySamples (const int newLatency)
  27848. {
  27849. if (latencySamples != newLatency)
  27850. {
  27851. latencySamples = newLatency;
  27852. updateHostDisplay();
  27853. }
  27854. }
  27855. void AudioProcessor::setParameterNotifyingHost (const int parameterIndex,
  27856. const float newValue)
  27857. {
  27858. setParameter (parameterIndex, newValue);
  27859. sendParamChangeMessageToListeners (parameterIndex, newValue);
  27860. }
  27861. void AudioProcessor::sendParamChangeMessageToListeners (const int parameterIndex, const float newValue)
  27862. {
  27863. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  27864. for (int i = listeners.size(); --i >= 0;)
  27865. {
  27866. AudioProcessorListener* l;
  27867. {
  27868. const ScopedLock sl (listenerLock);
  27869. l = listeners [i];
  27870. }
  27871. if (l != 0)
  27872. l->audioProcessorParameterChanged (this, parameterIndex, newValue);
  27873. }
  27874. }
  27875. void AudioProcessor::beginParameterChangeGesture (int parameterIndex)
  27876. {
  27877. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  27878. #if JUCE_DEBUG
  27879. // This means you've called beginParameterChangeGesture twice in succession without a matching
  27880. // call to endParameterChangeGesture. That might be fine in most hosts, but better to avoid doing it.
  27881. jassert (! changingParams [parameterIndex]);
  27882. changingParams.setBit (parameterIndex);
  27883. #endif
  27884. for (int i = listeners.size(); --i >= 0;)
  27885. {
  27886. AudioProcessorListener* l;
  27887. {
  27888. const ScopedLock sl (listenerLock);
  27889. l = listeners [i];
  27890. }
  27891. if (l != 0)
  27892. l->audioProcessorParameterChangeGestureBegin (this, parameterIndex);
  27893. }
  27894. }
  27895. void AudioProcessor::endParameterChangeGesture (int parameterIndex)
  27896. {
  27897. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  27898. #if JUCE_DEBUG
  27899. // This means you've called endParameterChangeGesture without having previously called
  27900. // endParameterChangeGesture. That might be fine in most hosts, but better to keep the
  27901. // calls matched correctly.
  27902. jassert (changingParams [parameterIndex]);
  27903. changingParams.clearBit (parameterIndex);
  27904. #endif
  27905. for (int i = listeners.size(); --i >= 0;)
  27906. {
  27907. AudioProcessorListener* l;
  27908. {
  27909. const ScopedLock sl (listenerLock);
  27910. l = listeners [i];
  27911. }
  27912. if (l != 0)
  27913. l->audioProcessorParameterChangeGestureEnd (this, parameterIndex);
  27914. }
  27915. }
  27916. void AudioProcessor::updateHostDisplay()
  27917. {
  27918. for (int i = listeners.size(); --i >= 0;)
  27919. {
  27920. AudioProcessorListener* l;
  27921. {
  27922. const ScopedLock sl (listenerLock);
  27923. l = listeners [i];
  27924. }
  27925. if (l != 0)
  27926. l->audioProcessorChanged (this);
  27927. }
  27928. }
  27929. bool AudioProcessor::isParameterAutomatable (int /*parameterIndex*/) const
  27930. {
  27931. return true;
  27932. }
  27933. bool AudioProcessor::isMetaParameter (int /*parameterIndex*/) const
  27934. {
  27935. return false;
  27936. }
  27937. void AudioProcessor::suspendProcessing (const bool shouldBeSuspended)
  27938. {
  27939. const ScopedLock sl (callbackLock);
  27940. suspended = shouldBeSuspended;
  27941. }
  27942. void AudioProcessor::reset()
  27943. {
  27944. }
  27945. void AudioProcessor::editorBeingDeleted (AudioProcessorEditor* const editor) throw()
  27946. {
  27947. const ScopedLock sl (callbackLock);
  27948. jassert (activeEditor == editor);
  27949. if (activeEditor == editor)
  27950. activeEditor = 0;
  27951. }
  27952. AudioProcessorEditor* AudioProcessor::createEditorIfNeeded()
  27953. {
  27954. if (activeEditor != 0)
  27955. return activeEditor;
  27956. AudioProcessorEditor* const ed = createEditor();
  27957. if (ed != 0)
  27958. {
  27959. // you must give your editor comp a size before returning it..
  27960. jassert (ed->getWidth() > 0 && ed->getHeight() > 0);
  27961. const ScopedLock sl (callbackLock);
  27962. activeEditor = ed;
  27963. }
  27964. return ed;
  27965. }
  27966. void AudioProcessor::getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData)
  27967. {
  27968. getStateInformation (destData);
  27969. }
  27970. void AudioProcessor::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  27971. {
  27972. setStateInformation (data, sizeInBytes);
  27973. }
  27974. // magic number to identify memory blocks that we've stored as XML
  27975. const uint32 magicXmlNumber = 0x21324356;
  27976. void AudioProcessor::copyXmlToBinary (const XmlElement& xml,
  27977. JUCE_NAMESPACE::MemoryBlock& destData)
  27978. {
  27979. const String xmlString (xml.createDocument (String::empty, true, false));
  27980. const int stringLength = xmlString.getNumBytesAsUTF8();
  27981. destData.setSize (stringLength + 10);
  27982. char* const d = (char*) destData.getData();
  27983. *(uint32*) d = ByteOrder::swapIfBigEndian ((const uint32) magicXmlNumber);
  27984. *(uint32*) (d + 4) = ByteOrder::swapIfBigEndian ((const uint32) stringLength);
  27985. xmlString.copyToUTF8 (d + 8, stringLength + 1);
  27986. }
  27987. XmlElement* AudioProcessor::getXmlFromBinary (const void* data,
  27988. const int sizeInBytes)
  27989. {
  27990. if (sizeInBytes > 8
  27991. && ByteOrder::littleEndianInt (data) == magicXmlNumber)
  27992. {
  27993. const int stringLength = (int) ByteOrder::littleEndianInt (((const char*) data) + 4);
  27994. if (stringLength > 0)
  27995. {
  27996. XmlDocument doc (String::fromUTF8 (((const char*) data) + 8,
  27997. jmin ((sizeInBytes - 8), stringLength)));
  27998. return doc.getDocumentElement();
  27999. }
  28000. }
  28001. return 0;
  28002. }
  28003. void AudioProcessorListener::audioProcessorParameterChangeGestureBegin (AudioProcessor*, int)
  28004. {
  28005. }
  28006. void AudioProcessorListener::audioProcessorParameterChangeGestureEnd (AudioProcessor*, int)
  28007. {
  28008. }
  28009. bool AudioPlayHead::CurrentPositionInfo::operator== (const CurrentPositionInfo& other) const throw()
  28010. {
  28011. return timeInSeconds == other.timeInSeconds
  28012. && ppqPosition == other.ppqPosition
  28013. && editOriginTime == other.editOriginTime
  28014. && ppqPositionOfLastBarStart == other.ppqPositionOfLastBarStart
  28015. && frameRate == other.frameRate
  28016. && isPlaying == other.isPlaying
  28017. && isRecording == other.isRecording
  28018. && bpm == other.bpm
  28019. && timeSigNumerator == other.timeSigNumerator
  28020. && timeSigDenominator == other.timeSigDenominator;
  28021. }
  28022. bool AudioPlayHead::CurrentPositionInfo::operator!= (const CurrentPositionInfo& other) const throw()
  28023. {
  28024. return ! operator== (other);
  28025. }
  28026. void AudioPlayHead::CurrentPositionInfo::resetToDefault()
  28027. {
  28028. zerostruct (*this);
  28029. timeSigNumerator = 4;
  28030. timeSigDenominator = 4;
  28031. bpm = 120;
  28032. }
  28033. END_JUCE_NAMESPACE
  28034. /*** End of inlined file: juce_AudioProcessor.cpp ***/
  28035. /*** Start of inlined file: juce_AudioProcessorEditor.cpp ***/
  28036. BEGIN_JUCE_NAMESPACE
  28037. AudioProcessorEditor::AudioProcessorEditor (AudioProcessor* const owner_)
  28038. : owner (owner_)
  28039. {
  28040. // the filter must be valid..
  28041. jassert (owner != 0);
  28042. }
  28043. AudioProcessorEditor::~AudioProcessorEditor()
  28044. {
  28045. // if this fails, then the wrapper hasn't called editorBeingDeleted() on the
  28046. // filter for some reason..
  28047. jassert (owner->getActiveEditor() != this);
  28048. }
  28049. END_JUCE_NAMESPACE
  28050. /*** End of inlined file: juce_AudioProcessorEditor.cpp ***/
  28051. /*** Start of inlined file: juce_AudioProcessorGraph.cpp ***/
  28052. BEGIN_JUCE_NAMESPACE
  28053. const int AudioProcessorGraph::midiChannelIndex = 0x1000;
  28054. AudioProcessorGraph::Node::Node (const uint32 id_, AudioProcessor* const processor_)
  28055. : id (id_),
  28056. processor (processor_),
  28057. isPrepared (false)
  28058. {
  28059. jassert (processor_ != 0);
  28060. }
  28061. AudioProcessorGraph::Node::~Node()
  28062. {
  28063. delete processor;
  28064. }
  28065. void AudioProcessorGraph::Node::prepare (const double sampleRate, const int blockSize,
  28066. AudioProcessorGraph* const graph)
  28067. {
  28068. if (! isPrepared)
  28069. {
  28070. isPrepared = true;
  28071. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  28072. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (processor);
  28073. if (ioProc != 0)
  28074. ioProc->setParentGraph (graph);
  28075. processor->setPlayConfigDetails (processor->getNumInputChannels(),
  28076. processor->getNumOutputChannels(),
  28077. sampleRate, blockSize);
  28078. processor->prepareToPlay (sampleRate, blockSize);
  28079. }
  28080. }
  28081. void AudioProcessorGraph::Node::unprepare()
  28082. {
  28083. if (isPrepared)
  28084. {
  28085. isPrepared = false;
  28086. processor->releaseResources();
  28087. }
  28088. }
  28089. AudioProcessorGraph::AudioProcessorGraph()
  28090. : lastNodeId (0),
  28091. renderingBuffers (1, 1),
  28092. currentAudioOutputBuffer (1, 1)
  28093. {
  28094. }
  28095. AudioProcessorGraph::~AudioProcessorGraph()
  28096. {
  28097. clearRenderingSequence();
  28098. clear();
  28099. }
  28100. const String AudioProcessorGraph::getName() const
  28101. {
  28102. return "Audio Graph";
  28103. }
  28104. void AudioProcessorGraph::clear()
  28105. {
  28106. nodes.clear();
  28107. connections.clear();
  28108. triggerAsyncUpdate();
  28109. }
  28110. AudioProcessorGraph::Node* AudioProcessorGraph::getNodeForId (const uint32 nodeId) const
  28111. {
  28112. for (int i = nodes.size(); --i >= 0;)
  28113. if (nodes.getUnchecked(i)->id == nodeId)
  28114. return nodes.getUnchecked(i);
  28115. return 0;
  28116. }
  28117. AudioProcessorGraph::Node* AudioProcessorGraph::addNode (AudioProcessor* const newProcessor,
  28118. uint32 nodeId)
  28119. {
  28120. if (newProcessor == 0)
  28121. {
  28122. jassertfalse;
  28123. return 0;
  28124. }
  28125. if (nodeId == 0)
  28126. {
  28127. nodeId = ++lastNodeId;
  28128. }
  28129. else
  28130. {
  28131. // you can't add a node with an id that already exists in the graph..
  28132. jassert (getNodeForId (nodeId) == 0);
  28133. removeNode (nodeId);
  28134. }
  28135. lastNodeId = nodeId;
  28136. Node* const n = new Node (nodeId, newProcessor);
  28137. nodes.add (n);
  28138. triggerAsyncUpdate();
  28139. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  28140. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (n->processor);
  28141. if (ioProc != 0)
  28142. ioProc->setParentGraph (this);
  28143. return n;
  28144. }
  28145. bool AudioProcessorGraph::removeNode (const uint32 nodeId)
  28146. {
  28147. disconnectNode (nodeId);
  28148. for (int i = nodes.size(); --i >= 0;)
  28149. {
  28150. if (nodes.getUnchecked(i)->id == nodeId)
  28151. {
  28152. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  28153. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (nodes.getUnchecked(i)->processor);
  28154. if (ioProc != 0)
  28155. ioProc->setParentGraph (0);
  28156. nodes.remove (i);
  28157. triggerAsyncUpdate();
  28158. return true;
  28159. }
  28160. }
  28161. return false;
  28162. }
  28163. const AudioProcessorGraph::Connection* AudioProcessorGraph::getConnectionBetween (const uint32 sourceNodeId,
  28164. const int sourceChannelIndex,
  28165. const uint32 destNodeId,
  28166. const int destChannelIndex) const
  28167. {
  28168. for (int i = connections.size(); --i >= 0;)
  28169. {
  28170. const Connection* const c = connections.getUnchecked(i);
  28171. if (c->sourceNodeId == sourceNodeId
  28172. && c->destNodeId == destNodeId
  28173. && c->sourceChannelIndex == sourceChannelIndex
  28174. && c->destChannelIndex == destChannelIndex)
  28175. {
  28176. return c;
  28177. }
  28178. }
  28179. return 0;
  28180. }
  28181. bool AudioProcessorGraph::isConnected (const uint32 possibleSourceNodeId,
  28182. const uint32 possibleDestNodeId) const
  28183. {
  28184. for (int i = connections.size(); --i >= 0;)
  28185. {
  28186. const Connection* const c = connections.getUnchecked(i);
  28187. if (c->sourceNodeId == possibleSourceNodeId
  28188. && c->destNodeId == possibleDestNodeId)
  28189. {
  28190. return true;
  28191. }
  28192. }
  28193. return false;
  28194. }
  28195. bool AudioProcessorGraph::canConnect (const uint32 sourceNodeId,
  28196. const int sourceChannelIndex,
  28197. const uint32 destNodeId,
  28198. const int destChannelIndex) const
  28199. {
  28200. if (sourceChannelIndex < 0
  28201. || destChannelIndex < 0
  28202. || sourceNodeId == destNodeId
  28203. || (destChannelIndex == midiChannelIndex) != (sourceChannelIndex == midiChannelIndex))
  28204. return false;
  28205. const Node* const source = getNodeForId (sourceNodeId);
  28206. if (source == 0
  28207. || (sourceChannelIndex != midiChannelIndex && sourceChannelIndex >= source->processor->getNumOutputChannels())
  28208. || (sourceChannelIndex == midiChannelIndex && ! source->processor->producesMidi()))
  28209. return false;
  28210. const Node* const dest = getNodeForId (destNodeId);
  28211. if (dest == 0
  28212. || (destChannelIndex != midiChannelIndex && destChannelIndex >= dest->processor->getNumInputChannels())
  28213. || (destChannelIndex == midiChannelIndex && ! dest->processor->acceptsMidi()))
  28214. return false;
  28215. return getConnectionBetween (sourceNodeId, sourceChannelIndex,
  28216. destNodeId, destChannelIndex) == 0;
  28217. }
  28218. bool AudioProcessorGraph::addConnection (const uint32 sourceNodeId,
  28219. const int sourceChannelIndex,
  28220. const uint32 destNodeId,
  28221. const int destChannelIndex)
  28222. {
  28223. if (! canConnect (sourceNodeId, sourceChannelIndex, destNodeId, destChannelIndex))
  28224. return false;
  28225. Connection* const c = new Connection();
  28226. c->sourceNodeId = sourceNodeId;
  28227. c->sourceChannelIndex = sourceChannelIndex;
  28228. c->destNodeId = destNodeId;
  28229. c->destChannelIndex = destChannelIndex;
  28230. connections.add (c);
  28231. triggerAsyncUpdate();
  28232. return true;
  28233. }
  28234. void AudioProcessorGraph::removeConnection (const int index)
  28235. {
  28236. connections.remove (index);
  28237. triggerAsyncUpdate();
  28238. }
  28239. bool AudioProcessorGraph::removeConnection (const uint32 sourceNodeId, const int sourceChannelIndex,
  28240. const uint32 destNodeId, const int destChannelIndex)
  28241. {
  28242. bool doneAnything = false;
  28243. for (int i = connections.size(); --i >= 0;)
  28244. {
  28245. const Connection* const c = connections.getUnchecked(i);
  28246. if (c->sourceNodeId == sourceNodeId
  28247. && c->destNodeId == destNodeId
  28248. && c->sourceChannelIndex == sourceChannelIndex
  28249. && c->destChannelIndex == destChannelIndex)
  28250. {
  28251. removeConnection (i);
  28252. doneAnything = true;
  28253. triggerAsyncUpdate();
  28254. }
  28255. }
  28256. return doneAnything;
  28257. }
  28258. bool AudioProcessorGraph::disconnectNode (const uint32 nodeId)
  28259. {
  28260. bool doneAnything = false;
  28261. for (int i = connections.size(); --i >= 0;)
  28262. {
  28263. const Connection* const c = connections.getUnchecked(i);
  28264. if (c->sourceNodeId == nodeId || c->destNodeId == nodeId)
  28265. {
  28266. removeConnection (i);
  28267. doneAnything = true;
  28268. triggerAsyncUpdate();
  28269. }
  28270. }
  28271. return doneAnything;
  28272. }
  28273. bool AudioProcessorGraph::removeIllegalConnections()
  28274. {
  28275. bool doneAnything = false;
  28276. for (int i = connections.size(); --i >= 0;)
  28277. {
  28278. const Connection* const c = connections.getUnchecked(i);
  28279. const Node* const source = getNodeForId (c->sourceNodeId);
  28280. const Node* const dest = getNodeForId (c->destNodeId);
  28281. if (source == 0 || dest == 0
  28282. || (c->sourceChannelIndex != midiChannelIndex
  28283. && (((unsigned int) c->sourceChannelIndex) >= (unsigned int) source->processor->getNumOutputChannels()))
  28284. || (c->sourceChannelIndex == midiChannelIndex
  28285. && ! source->processor->producesMidi())
  28286. || (c->destChannelIndex != midiChannelIndex
  28287. && (((unsigned int) c->destChannelIndex) >= (unsigned int) dest->processor->getNumInputChannels()))
  28288. || (c->destChannelIndex == midiChannelIndex
  28289. && ! dest->processor->acceptsMidi()))
  28290. {
  28291. removeConnection (i);
  28292. doneAnything = true;
  28293. triggerAsyncUpdate();
  28294. }
  28295. }
  28296. return doneAnything;
  28297. }
  28298. namespace GraphRenderingOps
  28299. {
  28300. class AudioGraphRenderingOp
  28301. {
  28302. public:
  28303. AudioGraphRenderingOp() {}
  28304. virtual ~AudioGraphRenderingOp() {}
  28305. virtual void perform (AudioSampleBuffer& sharedBufferChans,
  28306. const OwnedArray <MidiBuffer>& sharedMidiBuffers,
  28307. const int numSamples) = 0;
  28308. juce_UseDebuggingNewOperator
  28309. };
  28310. class ClearChannelOp : public AudioGraphRenderingOp
  28311. {
  28312. public:
  28313. ClearChannelOp (const int channelNum_)
  28314. : channelNum (channelNum_)
  28315. {}
  28316. ~ClearChannelOp() {}
  28317. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  28318. {
  28319. sharedBufferChans.clear (channelNum, 0, numSamples);
  28320. }
  28321. private:
  28322. const int channelNum;
  28323. ClearChannelOp (const ClearChannelOp&);
  28324. ClearChannelOp& operator= (const ClearChannelOp&);
  28325. };
  28326. class CopyChannelOp : public AudioGraphRenderingOp
  28327. {
  28328. public:
  28329. CopyChannelOp (const int srcChannelNum_, const int dstChannelNum_)
  28330. : srcChannelNum (srcChannelNum_),
  28331. dstChannelNum (dstChannelNum_)
  28332. {}
  28333. ~CopyChannelOp() {}
  28334. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  28335. {
  28336. sharedBufferChans.copyFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  28337. }
  28338. private:
  28339. const int srcChannelNum, dstChannelNum;
  28340. CopyChannelOp (const CopyChannelOp&);
  28341. CopyChannelOp& operator= (const CopyChannelOp&);
  28342. };
  28343. class AddChannelOp : public AudioGraphRenderingOp
  28344. {
  28345. public:
  28346. AddChannelOp (const int srcChannelNum_, const int dstChannelNum_)
  28347. : srcChannelNum (srcChannelNum_),
  28348. dstChannelNum (dstChannelNum_)
  28349. {}
  28350. ~AddChannelOp() {}
  28351. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  28352. {
  28353. sharedBufferChans.addFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  28354. }
  28355. private:
  28356. const int srcChannelNum, dstChannelNum;
  28357. AddChannelOp (const AddChannelOp&);
  28358. AddChannelOp& operator= (const AddChannelOp&);
  28359. };
  28360. class ClearMidiBufferOp : public AudioGraphRenderingOp
  28361. {
  28362. public:
  28363. ClearMidiBufferOp (const int bufferNum_)
  28364. : bufferNum (bufferNum_)
  28365. {}
  28366. ~ClearMidiBufferOp() {}
  28367. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int)
  28368. {
  28369. sharedMidiBuffers.getUnchecked (bufferNum)->clear();
  28370. }
  28371. private:
  28372. const int bufferNum;
  28373. ClearMidiBufferOp (const ClearMidiBufferOp&);
  28374. ClearMidiBufferOp& operator= (const ClearMidiBufferOp&);
  28375. };
  28376. class CopyMidiBufferOp : public AudioGraphRenderingOp
  28377. {
  28378. public:
  28379. CopyMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_)
  28380. : srcBufferNum (srcBufferNum_),
  28381. dstBufferNum (dstBufferNum_)
  28382. {}
  28383. ~CopyMidiBufferOp() {}
  28384. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int)
  28385. {
  28386. *sharedMidiBuffers.getUnchecked (dstBufferNum) = *sharedMidiBuffers.getUnchecked (srcBufferNum);
  28387. }
  28388. private:
  28389. const int srcBufferNum, dstBufferNum;
  28390. CopyMidiBufferOp (const CopyMidiBufferOp&);
  28391. CopyMidiBufferOp& operator= (const CopyMidiBufferOp&);
  28392. };
  28393. class AddMidiBufferOp : public AudioGraphRenderingOp
  28394. {
  28395. public:
  28396. AddMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_)
  28397. : srcBufferNum (srcBufferNum_),
  28398. dstBufferNum (dstBufferNum_)
  28399. {}
  28400. ~AddMidiBufferOp() {}
  28401. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples)
  28402. {
  28403. sharedMidiBuffers.getUnchecked (dstBufferNum)
  28404. ->addEvents (*sharedMidiBuffers.getUnchecked (srcBufferNum), 0, numSamples, 0);
  28405. }
  28406. private:
  28407. const int srcBufferNum, dstBufferNum;
  28408. AddMidiBufferOp (const AddMidiBufferOp&);
  28409. AddMidiBufferOp& operator= (const AddMidiBufferOp&);
  28410. };
  28411. class ProcessBufferOp : public AudioGraphRenderingOp
  28412. {
  28413. public:
  28414. ProcessBufferOp (const AudioProcessorGraph::Node::Ptr& node_,
  28415. const Array <int>& audioChannelsToUse_,
  28416. const int totalChans_,
  28417. const int midiBufferToUse_)
  28418. : node (node_),
  28419. processor (node_->processor),
  28420. audioChannelsToUse (audioChannelsToUse_),
  28421. totalChans (jmax (1, totalChans_)),
  28422. midiBufferToUse (midiBufferToUse_)
  28423. {
  28424. channels.calloc (totalChans);
  28425. while (audioChannelsToUse.size() < totalChans)
  28426. audioChannelsToUse.add (0);
  28427. }
  28428. ~ProcessBufferOp()
  28429. {
  28430. }
  28431. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples)
  28432. {
  28433. for (int i = totalChans; --i >= 0;)
  28434. channels[i] = sharedBufferChans.getSampleData (audioChannelsToUse.getUnchecked (i), 0);
  28435. AudioSampleBuffer buffer (channels, totalChans, numSamples);
  28436. processor->processBlock (buffer, *sharedMidiBuffers.getUnchecked (midiBufferToUse));
  28437. }
  28438. const AudioProcessorGraph::Node::Ptr node;
  28439. AudioProcessor* const processor;
  28440. private:
  28441. Array <int> audioChannelsToUse;
  28442. HeapBlock <float*> channels;
  28443. int totalChans;
  28444. int midiBufferToUse;
  28445. ProcessBufferOp (const ProcessBufferOp&);
  28446. ProcessBufferOp& operator= (const ProcessBufferOp&);
  28447. };
  28448. /** Used to calculate the correct sequence of rendering ops needed, based on
  28449. the best re-use of shared buffers at each stage.
  28450. */
  28451. class RenderingOpSequenceCalculator
  28452. {
  28453. public:
  28454. RenderingOpSequenceCalculator (AudioProcessorGraph& graph_,
  28455. const Array<void*>& orderedNodes_,
  28456. Array<void*>& renderingOps)
  28457. : graph (graph_),
  28458. orderedNodes (orderedNodes_)
  28459. {
  28460. nodeIds.add (-2); // first buffer is read-only zeros
  28461. channels.add (0);
  28462. midiNodeIds.add (-2);
  28463. for (int i = 0; i < orderedNodes.size(); ++i)
  28464. {
  28465. createRenderingOpsForNode ((AudioProcessorGraph::Node*) orderedNodes.getUnchecked(i),
  28466. renderingOps, i);
  28467. markAnyUnusedBuffersAsFree (i);
  28468. }
  28469. }
  28470. int getNumBuffersNeeded() const { return nodeIds.size(); }
  28471. int getNumMidiBuffersNeeded() const { return midiNodeIds.size(); }
  28472. juce_UseDebuggingNewOperator
  28473. private:
  28474. AudioProcessorGraph& graph;
  28475. const Array<void*>& orderedNodes;
  28476. Array <int> nodeIds, channels, midiNodeIds;
  28477. void createRenderingOpsForNode (AudioProcessorGraph::Node* const node,
  28478. Array<void*>& renderingOps,
  28479. const int ourRenderingIndex)
  28480. {
  28481. const int numIns = node->processor->getNumInputChannels();
  28482. const int numOuts = node->processor->getNumOutputChannels();
  28483. const int totalChans = jmax (numIns, numOuts);
  28484. Array <int> audioChannelsToUse;
  28485. int midiBufferToUse = -1;
  28486. for (int inputChan = 0; inputChan < numIns; ++inputChan)
  28487. {
  28488. // get a list of all the inputs to this node
  28489. Array <int> sourceNodes, sourceOutputChans;
  28490. for (int i = graph.getNumConnections(); --i >= 0;)
  28491. {
  28492. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  28493. if (c->destNodeId == node->id && c->destChannelIndex == inputChan)
  28494. {
  28495. sourceNodes.add (c->sourceNodeId);
  28496. sourceOutputChans.add (c->sourceChannelIndex);
  28497. }
  28498. }
  28499. int bufIndex = -1;
  28500. if (sourceNodes.size() == 0)
  28501. {
  28502. // unconnected input channel
  28503. if (inputChan >= numOuts)
  28504. {
  28505. bufIndex = getReadOnlyEmptyBuffer();
  28506. jassert (bufIndex >= 0);
  28507. }
  28508. else
  28509. {
  28510. bufIndex = getFreeBuffer (false);
  28511. renderingOps.add (new ClearChannelOp (bufIndex));
  28512. }
  28513. }
  28514. else if (sourceNodes.size() == 1)
  28515. {
  28516. // channel with a straightforward single input..
  28517. const int srcNode = sourceNodes.getUnchecked(0);
  28518. const int srcChan = sourceOutputChans.getUnchecked(0);
  28519. bufIndex = getBufferContaining (srcNode, srcChan);
  28520. if (bufIndex < 0)
  28521. {
  28522. // if not found, this is probably a feedback loop
  28523. bufIndex = getReadOnlyEmptyBuffer();
  28524. jassert (bufIndex >= 0);
  28525. }
  28526. if (inputChan < numOuts
  28527. && isBufferNeededLater (ourRenderingIndex,
  28528. inputChan,
  28529. srcNode, srcChan))
  28530. {
  28531. // can't mess up this channel because it's needed later by another node, so we
  28532. // need to use a copy of it..
  28533. const int newFreeBuffer = getFreeBuffer (false);
  28534. renderingOps.add (new CopyChannelOp (bufIndex, newFreeBuffer));
  28535. bufIndex = newFreeBuffer;
  28536. }
  28537. }
  28538. else
  28539. {
  28540. // channel with a mix of several inputs..
  28541. // try to find a re-usable channel from our inputs..
  28542. int reusableInputIndex = -1;
  28543. for (int i = 0; i < sourceNodes.size(); ++i)
  28544. {
  28545. const int sourceBufIndex = getBufferContaining (sourceNodes.getUnchecked(i),
  28546. sourceOutputChans.getUnchecked(i));
  28547. if (sourceBufIndex >= 0
  28548. && ! isBufferNeededLater (ourRenderingIndex,
  28549. inputChan,
  28550. sourceNodes.getUnchecked(i),
  28551. sourceOutputChans.getUnchecked(i)))
  28552. {
  28553. // we've found one of our input chans that can be re-used..
  28554. reusableInputIndex = i;
  28555. bufIndex = sourceBufIndex;
  28556. break;
  28557. }
  28558. }
  28559. if (reusableInputIndex < 0)
  28560. {
  28561. // can't re-use any of our input chans, so get a new one and copy everything into it..
  28562. bufIndex = getFreeBuffer (false);
  28563. jassert (bufIndex != 0);
  28564. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked (0),
  28565. sourceOutputChans.getUnchecked (0));
  28566. if (srcIndex < 0)
  28567. {
  28568. // if not found, this is probably a feedback loop
  28569. renderingOps.add (new ClearChannelOp (bufIndex));
  28570. }
  28571. else
  28572. {
  28573. renderingOps.add (new CopyChannelOp (srcIndex, bufIndex));
  28574. }
  28575. reusableInputIndex = 0;
  28576. }
  28577. for (int j = 0; j < sourceNodes.size(); ++j)
  28578. {
  28579. if (j != reusableInputIndex)
  28580. {
  28581. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked(j),
  28582. sourceOutputChans.getUnchecked(j));
  28583. if (srcIndex >= 0)
  28584. renderingOps.add (new AddChannelOp (srcIndex, bufIndex));
  28585. }
  28586. }
  28587. }
  28588. jassert (bufIndex >= 0);
  28589. audioChannelsToUse.add (bufIndex);
  28590. if (inputChan < numOuts)
  28591. markBufferAsContaining (bufIndex, node->id, inputChan);
  28592. }
  28593. for (int outputChan = numIns; outputChan < numOuts; ++outputChan)
  28594. {
  28595. const int bufIndex = getFreeBuffer (false);
  28596. jassert (bufIndex != 0);
  28597. audioChannelsToUse.add (bufIndex);
  28598. markBufferAsContaining (bufIndex, node->id, outputChan);
  28599. }
  28600. // Now the same thing for midi..
  28601. Array <int> midiSourceNodes;
  28602. for (int i = graph.getNumConnections(); --i >= 0;)
  28603. {
  28604. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  28605. if (c->destNodeId == node->id && c->destChannelIndex == AudioProcessorGraph::midiChannelIndex)
  28606. midiSourceNodes.add (c->sourceNodeId);
  28607. }
  28608. if (midiSourceNodes.size() == 0)
  28609. {
  28610. // No midi inputs..
  28611. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  28612. if (node->processor->acceptsMidi() || node->processor->producesMidi())
  28613. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  28614. }
  28615. else if (midiSourceNodes.size() == 1)
  28616. {
  28617. // One midi input..
  28618. midiBufferToUse = getBufferContaining (midiSourceNodes.getUnchecked(0),
  28619. AudioProcessorGraph::midiChannelIndex);
  28620. if (midiBufferToUse >= 0)
  28621. {
  28622. if (isBufferNeededLater (ourRenderingIndex,
  28623. AudioProcessorGraph::midiChannelIndex,
  28624. midiSourceNodes.getUnchecked(0),
  28625. AudioProcessorGraph::midiChannelIndex))
  28626. {
  28627. // can't mess up this channel because it's needed later by another node, so we
  28628. // need to use a copy of it..
  28629. const int newFreeBuffer = getFreeBuffer (true);
  28630. renderingOps.add (new CopyMidiBufferOp (midiBufferToUse, newFreeBuffer));
  28631. midiBufferToUse = newFreeBuffer;
  28632. }
  28633. }
  28634. else
  28635. {
  28636. // probably a feedback loop, so just use an empty one..
  28637. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  28638. }
  28639. }
  28640. else
  28641. {
  28642. // More than one midi input being mixed..
  28643. int reusableInputIndex = -1;
  28644. for (int i = 0; i < midiSourceNodes.size(); ++i)
  28645. {
  28646. const int sourceBufIndex = getBufferContaining (midiSourceNodes.getUnchecked(i),
  28647. AudioProcessorGraph::midiChannelIndex);
  28648. if (sourceBufIndex >= 0
  28649. && ! isBufferNeededLater (ourRenderingIndex,
  28650. AudioProcessorGraph::midiChannelIndex,
  28651. midiSourceNodes.getUnchecked(i),
  28652. AudioProcessorGraph::midiChannelIndex))
  28653. {
  28654. // we've found one of our input buffers that can be re-used..
  28655. reusableInputIndex = i;
  28656. midiBufferToUse = sourceBufIndex;
  28657. break;
  28658. }
  28659. }
  28660. if (reusableInputIndex < 0)
  28661. {
  28662. // can't re-use any of our input buffers, so get a new one and copy everything into it..
  28663. midiBufferToUse = getFreeBuffer (true);
  28664. jassert (midiBufferToUse >= 0);
  28665. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(0),
  28666. AudioProcessorGraph::midiChannelIndex);
  28667. if (srcIndex >= 0)
  28668. renderingOps.add (new CopyMidiBufferOp (srcIndex, midiBufferToUse));
  28669. else
  28670. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  28671. reusableInputIndex = 0;
  28672. }
  28673. for (int j = 0; j < midiSourceNodes.size(); ++j)
  28674. {
  28675. if (j != reusableInputIndex)
  28676. {
  28677. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(j),
  28678. AudioProcessorGraph::midiChannelIndex);
  28679. if (srcIndex >= 0)
  28680. renderingOps.add (new AddMidiBufferOp (srcIndex, midiBufferToUse));
  28681. }
  28682. }
  28683. }
  28684. if (node->processor->producesMidi())
  28685. markBufferAsContaining (midiBufferToUse, node->id,
  28686. AudioProcessorGraph::midiChannelIndex);
  28687. renderingOps.add (new ProcessBufferOp (node, audioChannelsToUse,
  28688. totalChans, midiBufferToUse));
  28689. }
  28690. int getFreeBuffer (const bool forMidi)
  28691. {
  28692. if (forMidi)
  28693. {
  28694. for (int i = 1; i < midiNodeIds.size(); ++i)
  28695. if (midiNodeIds.getUnchecked(i) < 0)
  28696. return i;
  28697. midiNodeIds.add (-1);
  28698. return midiNodeIds.size() - 1;
  28699. }
  28700. else
  28701. {
  28702. for (int i = 1; i < nodeIds.size(); ++i)
  28703. if (nodeIds.getUnchecked(i) < 0)
  28704. return i;
  28705. nodeIds.add (-1);
  28706. channels.add (0);
  28707. return nodeIds.size() - 1;
  28708. }
  28709. }
  28710. int getReadOnlyEmptyBuffer() const
  28711. {
  28712. return 0;
  28713. }
  28714. int getBufferContaining (const int nodeId, const int outputChannel) const
  28715. {
  28716. if (outputChannel == AudioProcessorGraph::midiChannelIndex)
  28717. {
  28718. for (int i = midiNodeIds.size(); --i >= 0;)
  28719. if (midiNodeIds.getUnchecked(i) == nodeId)
  28720. return i;
  28721. }
  28722. else
  28723. {
  28724. for (int i = nodeIds.size(); --i >= 0;)
  28725. if (nodeIds.getUnchecked(i) == nodeId
  28726. && channels.getUnchecked(i) == outputChannel)
  28727. return i;
  28728. }
  28729. return -1;
  28730. }
  28731. void markAnyUnusedBuffersAsFree (const int stepIndex)
  28732. {
  28733. int i;
  28734. for (i = 0; i < nodeIds.size(); ++i)
  28735. {
  28736. if (nodeIds.getUnchecked(i) >= 0
  28737. && ! isBufferNeededLater (stepIndex, -1,
  28738. nodeIds.getUnchecked(i),
  28739. channels.getUnchecked(i)))
  28740. {
  28741. nodeIds.set (i, -1);
  28742. }
  28743. }
  28744. for (i = 0; i < midiNodeIds.size(); ++i)
  28745. {
  28746. if (midiNodeIds.getUnchecked(i) >= 0
  28747. && ! isBufferNeededLater (stepIndex, -1,
  28748. midiNodeIds.getUnchecked(i),
  28749. AudioProcessorGraph::midiChannelIndex))
  28750. {
  28751. midiNodeIds.set (i, -1);
  28752. }
  28753. }
  28754. }
  28755. bool isBufferNeededLater (int stepIndexToSearchFrom,
  28756. int inputChannelOfIndexToIgnore,
  28757. const int nodeId,
  28758. const int outputChanIndex) const
  28759. {
  28760. while (stepIndexToSearchFrom < orderedNodes.size())
  28761. {
  28762. const AudioProcessorGraph::Node* const node = (const AudioProcessorGraph::Node*) orderedNodes.getUnchecked (stepIndexToSearchFrom);
  28763. if (outputChanIndex == AudioProcessorGraph::midiChannelIndex)
  28764. {
  28765. if (inputChannelOfIndexToIgnore != AudioProcessorGraph::midiChannelIndex
  28766. && graph.getConnectionBetween (nodeId, AudioProcessorGraph::midiChannelIndex,
  28767. node->id, AudioProcessorGraph::midiChannelIndex) != 0)
  28768. return true;
  28769. }
  28770. else
  28771. {
  28772. for (int i = 0; i < node->processor->getNumInputChannels(); ++i)
  28773. if (i != inputChannelOfIndexToIgnore
  28774. && graph.getConnectionBetween (nodeId, outputChanIndex,
  28775. node->id, i) != 0)
  28776. return true;
  28777. }
  28778. inputChannelOfIndexToIgnore = -1;
  28779. ++stepIndexToSearchFrom;
  28780. }
  28781. return false;
  28782. }
  28783. void markBufferAsContaining (int bufferNum, int nodeId, int outputIndex)
  28784. {
  28785. if (outputIndex == AudioProcessorGraph::midiChannelIndex)
  28786. {
  28787. jassert (bufferNum > 0 && bufferNum < midiNodeIds.size());
  28788. midiNodeIds.set (bufferNum, nodeId);
  28789. }
  28790. else
  28791. {
  28792. jassert (bufferNum >= 0 && bufferNum < nodeIds.size());
  28793. nodeIds.set (bufferNum, nodeId);
  28794. channels.set (bufferNum, outputIndex);
  28795. }
  28796. }
  28797. RenderingOpSequenceCalculator (const RenderingOpSequenceCalculator&);
  28798. RenderingOpSequenceCalculator& operator= (const RenderingOpSequenceCalculator&);
  28799. };
  28800. }
  28801. void AudioProcessorGraph::clearRenderingSequence()
  28802. {
  28803. const ScopedLock sl (renderLock);
  28804. for (int i = renderingOps.size(); --i >= 0;)
  28805. {
  28806. GraphRenderingOps::AudioGraphRenderingOp* const r
  28807. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  28808. renderingOps.remove (i);
  28809. delete r;
  28810. }
  28811. }
  28812. bool AudioProcessorGraph::isAnInputTo (const uint32 possibleInputId,
  28813. const uint32 possibleDestinationId,
  28814. const int recursionCheck) const
  28815. {
  28816. if (recursionCheck > 0)
  28817. {
  28818. for (int i = connections.size(); --i >= 0;)
  28819. {
  28820. const AudioProcessorGraph::Connection* const c = connections.getUnchecked (i);
  28821. if (c->destNodeId == possibleDestinationId
  28822. && (c->sourceNodeId == possibleInputId
  28823. || isAnInputTo (possibleInputId, c->sourceNodeId, recursionCheck - 1)))
  28824. return true;
  28825. }
  28826. }
  28827. return false;
  28828. }
  28829. void AudioProcessorGraph::buildRenderingSequence()
  28830. {
  28831. Array<void*> newRenderingOps;
  28832. int numRenderingBuffersNeeded = 2;
  28833. int numMidiBuffersNeeded = 1;
  28834. {
  28835. MessageManagerLock mml;
  28836. Array<void*> orderedNodes;
  28837. int i;
  28838. for (i = 0; i < nodes.size(); ++i)
  28839. {
  28840. Node* const node = nodes.getUnchecked(i);
  28841. node->prepare (getSampleRate(), getBlockSize(), this);
  28842. int j = 0;
  28843. for (; j < orderedNodes.size(); ++j)
  28844. if (isAnInputTo (node->id,
  28845. ((Node*) orderedNodes.getUnchecked (j))->id,
  28846. nodes.size() + 1))
  28847. break;
  28848. orderedNodes.insert (j, node);
  28849. }
  28850. GraphRenderingOps::RenderingOpSequenceCalculator calculator (*this, orderedNodes, newRenderingOps);
  28851. numRenderingBuffersNeeded = calculator.getNumBuffersNeeded();
  28852. numMidiBuffersNeeded = calculator.getNumMidiBuffersNeeded();
  28853. }
  28854. Array<void*> oldRenderingOps (renderingOps);
  28855. {
  28856. // swap over to the new rendering sequence..
  28857. const ScopedLock sl (renderLock);
  28858. renderingBuffers.setSize (numRenderingBuffersNeeded, getBlockSize());
  28859. renderingBuffers.clear();
  28860. for (int i = midiBuffers.size(); --i >= 0;)
  28861. midiBuffers.getUnchecked(i)->clear();
  28862. while (midiBuffers.size() < numMidiBuffersNeeded)
  28863. midiBuffers.add (new MidiBuffer());
  28864. renderingOps = newRenderingOps;
  28865. }
  28866. for (int i = oldRenderingOps.size(); --i >= 0;)
  28867. delete (GraphRenderingOps::AudioGraphRenderingOp*) oldRenderingOps.getUnchecked(i);
  28868. }
  28869. void AudioProcessorGraph::handleAsyncUpdate()
  28870. {
  28871. buildRenderingSequence();
  28872. }
  28873. void AudioProcessorGraph::prepareToPlay (double /*sampleRate*/, int estimatedSamplesPerBlock)
  28874. {
  28875. currentAudioInputBuffer = 0;
  28876. currentAudioOutputBuffer.setSize (jmax (1, getNumOutputChannels()), estimatedSamplesPerBlock);
  28877. currentMidiInputBuffer = 0;
  28878. currentMidiOutputBuffer.clear();
  28879. clearRenderingSequence();
  28880. buildRenderingSequence();
  28881. }
  28882. void AudioProcessorGraph::releaseResources()
  28883. {
  28884. for (int i = 0; i < nodes.size(); ++i)
  28885. nodes.getUnchecked(i)->unprepare();
  28886. renderingBuffers.setSize (1, 1);
  28887. midiBuffers.clear();
  28888. currentAudioInputBuffer = 0;
  28889. currentAudioOutputBuffer.setSize (1, 1);
  28890. currentMidiInputBuffer = 0;
  28891. currentMidiOutputBuffer.clear();
  28892. }
  28893. void AudioProcessorGraph::processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages)
  28894. {
  28895. const int numSamples = buffer.getNumSamples();
  28896. const ScopedLock sl (renderLock);
  28897. currentAudioInputBuffer = &buffer;
  28898. currentAudioOutputBuffer.setSize (jmax (1, buffer.getNumChannels()), numSamples);
  28899. currentAudioOutputBuffer.clear();
  28900. currentMidiInputBuffer = &midiMessages;
  28901. currentMidiOutputBuffer.clear();
  28902. int i;
  28903. for (i = 0; i < renderingOps.size(); ++i)
  28904. {
  28905. GraphRenderingOps::AudioGraphRenderingOp* const op
  28906. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  28907. op->perform (renderingBuffers, midiBuffers, numSamples);
  28908. }
  28909. for (i = 0; i < buffer.getNumChannels(); ++i)
  28910. buffer.copyFrom (i, 0, currentAudioOutputBuffer, i, 0, numSamples);
  28911. midiMessages.clear();
  28912. midiMessages.addEvents (currentMidiOutputBuffer, 0, buffer.getNumSamples(), 0);
  28913. }
  28914. const String AudioProcessorGraph::getInputChannelName (const int channelIndex) const
  28915. {
  28916. return "Input " + String (channelIndex + 1);
  28917. }
  28918. const String AudioProcessorGraph::getOutputChannelName (const int channelIndex) const
  28919. {
  28920. return "Output " + String (channelIndex + 1);
  28921. }
  28922. bool AudioProcessorGraph::isInputChannelStereoPair (int /*index*/) const
  28923. {
  28924. return true;
  28925. }
  28926. bool AudioProcessorGraph::isOutputChannelStereoPair (int /*index*/) const
  28927. {
  28928. return true;
  28929. }
  28930. bool AudioProcessorGraph::acceptsMidi() const
  28931. {
  28932. return true;
  28933. }
  28934. bool AudioProcessorGraph::producesMidi() const
  28935. {
  28936. return true;
  28937. }
  28938. void AudioProcessorGraph::getStateInformation (JUCE_NAMESPACE::MemoryBlock& /*destData*/)
  28939. {
  28940. }
  28941. void AudioProcessorGraph::setStateInformation (const void* /*data*/, int /*sizeInBytes*/)
  28942. {
  28943. }
  28944. AudioProcessorGraph::AudioGraphIOProcessor::AudioGraphIOProcessor (const IODeviceType type_)
  28945. : type (type_),
  28946. graph (0)
  28947. {
  28948. }
  28949. AudioProcessorGraph::AudioGraphIOProcessor::~AudioGraphIOProcessor()
  28950. {
  28951. }
  28952. const String AudioProcessorGraph::AudioGraphIOProcessor::getName() const
  28953. {
  28954. switch (type)
  28955. {
  28956. case audioOutputNode:
  28957. return "Audio Output";
  28958. case audioInputNode:
  28959. return "Audio Input";
  28960. case midiOutputNode:
  28961. return "Midi Output";
  28962. case midiInputNode:
  28963. return "Midi Input";
  28964. default:
  28965. break;
  28966. }
  28967. return String::empty;
  28968. }
  28969. void AudioProcessorGraph::AudioGraphIOProcessor::fillInPluginDescription (PluginDescription& d) const
  28970. {
  28971. d.name = getName();
  28972. d.uid = d.name.hashCode();
  28973. d.category = "I/O devices";
  28974. d.pluginFormatName = "Internal";
  28975. d.manufacturerName = "Raw Material Software";
  28976. d.version = "1.0";
  28977. d.isInstrument = false;
  28978. d.numInputChannels = getNumInputChannels();
  28979. if (type == audioOutputNode && graph != 0)
  28980. d.numInputChannels = graph->getNumInputChannels();
  28981. d.numOutputChannels = getNumOutputChannels();
  28982. if (type == audioInputNode && graph != 0)
  28983. d.numOutputChannels = graph->getNumOutputChannels();
  28984. }
  28985. void AudioProcessorGraph::AudioGraphIOProcessor::prepareToPlay (double, int)
  28986. {
  28987. jassert (graph != 0);
  28988. }
  28989. void AudioProcessorGraph::AudioGraphIOProcessor::releaseResources()
  28990. {
  28991. }
  28992. void AudioProcessorGraph::AudioGraphIOProcessor::processBlock (AudioSampleBuffer& buffer,
  28993. MidiBuffer& midiMessages)
  28994. {
  28995. jassert (graph != 0);
  28996. switch (type)
  28997. {
  28998. case audioOutputNode:
  28999. {
  29000. for (int i = jmin (graph->currentAudioOutputBuffer.getNumChannels(),
  29001. buffer.getNumChannels()); --i >= 0;)
  29002. {
  29003. graph->currentAudioOutputBuffer.addFrom (i, 0, buffer, i, 0, buffer.getNumSamples());
  29004. }
  29005. break;
  29006. }
  29007. case audioInputNode:
  29008. {
  29009. for (int i = jmin (graph->currentAudioInputBuffer->getNumChannels(),
  29010. buffer.getNumChannels()); --i >= 0;)
  29011. {
  29012. buffer.copyFrom (i, 0, *graph->currentAudioInputBuffer, i, 0, buffer.getNumSamples());
  29013. }
  29014. break;
  29015. }
  29016. case midiOutputNode:
  29017. graph->currentMidiOutputBuffer.addEvents (midiMessages, 0, buffer.getNumSamples(), 0);
  29018. break;
  29019. case midiInputNode:
  29020. midiMessages.addEvents (*graph->currentMidiInputBuffer, 0, buffer.getNumSamples(), 0);
  29021. break;
  29022. default:
  29023. break;
  29024. }
  29025. }
  29026. bool AudioProcessorGraph::AudioGraphIOProcessor::acceptsMidi() const
  29027. {
  29028. return type == midiOutputNode;
  29029. }
  29030. bool AudioProcessorGraph::AudioGraphIOProcessor::producesMidi() const
  29031. {
  29032. return type == midiInputNode;
  29033. }
  29034. const String AudioProcessorGraph::AudioGraphIOProcessor::getInputChannelName (const int channelIndex) const
  29035. {
  29036. switch (type)
  29037. {
  29038. case audioOutputNode:
  29039. return "Output " + String (channelIndex + 1);
  29040. case midiOutputNode:
  29041. return "Midi Output";
  29042. default:
  29043. break;
  29044. }
  29045. return String::empty;
  29046. }
  29047. const String AudioProcessorGraph::AudioGraphIOProcessor::getOutputChannelName (const int channelIndex) const
  29048. {
  29049. switch (type)
  29050. {
  29051. case audioInputNode:
  29052. return "Input " + String (channelIndex + 1);
  29053. case midiInputNode:
  29054. return "Midi Input";
  29055. default:
  29056. break;
  29057. }
  29058. return String::empty;
  29059. }
  29060. bool AudioProcessorGraph::AudioGraphIOProcessor::isInputChannelStereoPair (int /*index*/) const
  29061. {
  29062. return type == audioInputNode || type == audioOutputNode;
  29063. }
  29064. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutputChannelStereoPair (int index) const
  29065. {
  29066. return isInputChannelStereoPair (index);
  29067. }
  29068. bool AudioProcessorGraph::AudioGraphIOProcessor::isInput() const
  29069. {
  29070. return type == audioInputNode || type == midiInputNode;
  29071. }
  29072. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutput() const
  29073. {
  29074. return type == audioOutputNode || type == midiOutputNode;
  29075. }
  29076. AudioProcessorEditor* AudioProcessorGraph::AudioGraphIOProcessor::createEditor()
  29077. {
  29078. return 0;
  29079. }
  29080. int AudioProcessorGraph::AudioGraphIOProcessor::getNumParameters() { return 0; }
  29081. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterName (int) { return String::empty; }
  29082. float AudioProcessorGraph::AudioGraphIOProcessor::getParameter (int) { return 0.0f; }
  29083. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterText (int) { return String::empty; }
  29084. void AudioProcessorGraph::AudioGraphIOProcessor::setParameter (int, float) { }
  29085. int AudioProcessorGraph::AudioGraphIOProcessor::getNumPrograms() { return 0; }
  29086. int AudioProcessorGraph::AudioGraphIOProcessor::getCurrentProgram() { return 0; }
  29087. void AudioProcessorGraph::AudioGraphIOProcessor::setCurrentProgram (int) { }
  29088. const String AudioProcessorGraph::AudioGraphIOProcessor::getProgramName (int) { return String::empty; }
  29089. void AudioProcessorGraph::AudioGraphIOProcessor::changeProgramName (int, const String&) { }
  29090. void AudioProcessorGraph::AudioGraphIOProcessor::getStateInformation (JUCE_NAMESPACE::MemoryBlock&)
  29091. {
  29092. }
  29093. void AudioProcessorGraph::AudioGraphIOProcessor::setStateInformation (const void*, int)
  29094. {
  29095. }
  29096. void AudioProcessorGraph::AudioGraphIOProcessor::setParentGraph (AudioProcessorGraph* const newGraph)
  29097. {
  29098. graph = newGraph;
  29099. if (graph != 0)
  29100. {
  29101. setPlayConfigDetails (type == audioOutputNode ? graph->getNumOutputChannels() : 0,
  29102. type == audioInputNode ? graph->getNumInputChannels() : 0,
  29103. getSampleRate(),
  29104. getBlockSize());
  29105. updateHostDisplay();
  29106. }
  29107. }
  29108. END_JUCE_NAMESPACE
  29109. /*** End of inlined file: juce_AudioProcessorGraph.cpp ***/
  29110. /*** Start of inlined file: juce_AudioProcessorPlayer.cpp ***/
  29111. BEGIN_JUCE_NAMESPACE
  29112. AudioProcessorPlayer::AudioProcessorPlayer()
  29113. : processor (0),
  29114. sampleRate (0),
  29115. blockSize (0),
  29116. isPrepared (false),
  29117. numInputChans (0),
  29118. numOutputChans (0),
  29119. tempBuffer (1, 1)
  29120. {
  29121. }
  29122. AudioProcessorPlayer::~AudioProcessorPlayer()
  29123. {
  29124. setProcessor (0);
  29125. }
  29126. void AudioProcessorPlayer::setProcessor (AudioProcessor* const processorToPlay)
  29127. {
  29128. if (processor != processorToPlay)
  29129. {
  29130. if (processorToPlay != 0 && sampleRate > 0 && blockSize > 0)
  29131. {
  29132. processorToPlay->setPlayConfigDetails (numInputChans, numOutputChans,
  29133. sampleRate, blockSize);
  29134. processorToPlay->prepareToPlay (sampleRate, blockSize);
  29135. }
  29136. AudioProcessor* oldOne;
  29137. {
  29138. const ScopedLock sl (lock);
  29139. oldOne = isPrepared ? processor : 0;
  29140. processor = processorToPlay;
  29141. isPrepared = true;
  29142. }
  29143. if (oldOne != 0)
  29144. oldOne->releaseResources();
  29145. }
  29146. }
  29147. void AudioProcessorPlayer::audioDeviceIOCallback (const float** inputChannelData,
  29148. int numInputChannels,
  29149. float** outputChannelData,
  29150. int numOutputChannels,
  29151. int numSamples)
  29152. {
  29153. // these should have been prepared by audioDeviceAboutToStart()...
  29154. jassert (sampleRate > 0 && blockSize > 0);
  29155. incomingMidi.clear();
  29156. messageCollector.removeNextBlockOfMessages (incomingMidi, numSamples);
  29157. int i, totalNumChans = 0;
  29158. if (numInputChannels > numOutputChannels)
  29159. {
  29160. // if there aren't enough output channels for the number of
  29161. // inputs, we need to create some temporary extra ones (can't
  29162. // use the input data in case it gets written to)
  29163. tempBuffer.setSize (numInputChannels - numOutputChannels, numSamples,
  29164. false, false, true);
  29165. for (i = 0; i < numOutputChannels; ++i)
  29166. {
  29167. channels[totalNumChans] = outputChannelData[i];
  29168. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  29169. ++totalNumChans;
  29170. }
  29171. for (i = numOutputChannels; i < numInputChannels; ++i)
  29172. {
  29173. channels[totalNumChans] = tempBuffer.getSampleData (i - numOutputChannels, 0);
  29174. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  29175. ++totalNumChans;
  29176. }
  29177. }
  29178. else
  29179. {
  29180. for (i = 0; i < numInputChannels; ++i)
  29181. {
  29182. channels[totalNumChans] = outputChannelData[i];
  29183. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  29184. ++totalNumChans;
  29185. }
  29186. for (i = numInputChannels; i < numOutputChannels; ++i)
  29187. {
  29188. channels[totalNumChans] = outputChannelData[i];
  29189. zeromem (channels[totalNumChans], sizeof (float) * numSamples);
  29190. ++totalNumChans;
  29191. }
  29192. }
  29193. AudioSampleBuffer buffer (channels, totalNumChans, numSamples);
  29194. const ScopedLock sl (lock);
  29195. if (processor != 0)
  29196. {
  29197. const ScopedLock sl (processor->getCallbackLock());
  29198. if (! processor->isSuspended())
  29199. processor->processBlock (buffer, incomingMidi);
  29200. }
  29201. }
  29202. void AudioProcessorPlayer::audioDeviceAboutToStart (AudioIODevice* device)
  29203. {
  29204. const ScopedLock sl (lock);
  29205. sampleRate = device->getCurrentSampleRate();
  29206. blockSize = device->getCurrentBufferSizeSamples();
  29207. numInputChans = device->getActiveInputChannels().countNumberOfSetBits();
  29208. numOutputChans = device->getActiveOutputChannels().countNumberOfSetBits();
  29209. messageCollector.reset (sampleRate);
  29210. zeromem (channels, sizeof (channels));
  29211. if (processor != 0)
  29212. {
  29213. if (isPrepared)
  29214. processor->releaseResources();
  29215. AudioProcessor* const oldProcessor = processor;
  29216. setProcessor (0);
  29217. setProcessor (oldProcessor);
  29218. }
  29219. }
  29220. void AudioProcessorPlayer::audioDeviceStopped()
  29221. {
  29222. const ScopedLock sl (lock);
  29223. if (processor != 0 && isPrepared)
  29224. processor->releaseResources();
  29225. sampleRate = 0.0;
  29226. blockSize = 0;
  29227. isPrepared = false;
  29228. tempBuffer.setSize (1, 1);
  29229. }
  29230. void AudioProcessorPlayer::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  29231. {
  29232. messageCollector.addMessageToQueue (message);
  29233. }
  29234. END_JUCE_NAMESPACE
  29235. /*** End of inlined file: juce_AudioProcessorPlayer.cpp ***/
  29236. /*** Start of inlined file: juce_GenericAudioProcessorEditor.cpp ***/
  29237. BEGIN_JUCE_NAMESPACE
  29238. class ProcessorParameterPropertyComp : public PropertyComponent,
  29239. public AudioProcessorListener,
  29240. public AsyncUpdater
  29241. {
  29242. public:
  29243. ProcessorParameterPropertyComp (const String& name,
  29244. AudioProcessor* const owner_,
  29245. const int index_)
  29246. : PropertyComponent (name),
  29247. owner (owner_),
  29248. index (index_)
  29249. {
  29250. addAndMakeVisible (slider = new ParamSlider (owner_, index_));
  29251. owner_->addListener (this);
  29252. }
  29253. ~ProcessorParameterPropertyComp()
  29254. {
  29255. owner->removeListener (this);
  29256. deleteAllChildren();
  29257. }
  29258. void refresh()
  29259. {
  29260. slider->setValue (owner->getParameter (index), false);
  29261. }
  29262. void audioProcessorChanged (AudioProcessor*) {}
  29263. void audioProcessorParameterChanged (AudioProcessor*, int parameterIndex, float)
  29264. {
  29265. if (parameterIndex == index)
  29266. triggerAsyncUpdate();
  29267. }
  29268. void handleAsyncUpdate()
  29269. {
  29270. refresh();
  29271. }
  29272. juce_UseDebuggingNewOperator
  29273. private:
  29274. AudioProcessor* const owner;
  29275. const int index;
  29276. Slider* slider;
  29277. class ParamSlider : public Slider
  29278. {
  29279. public:
  29280. ParamSlider (AudioProcessor* const owner_, const int index_)
  29281. : Slider (String::empty),
  29282. owner (owner_),
  29283. index (index_)
  29284. {
  29285. setRange (0.0, 1.0, 0.0);
  29286. setSliderStyle (Slider::LinearBar);
  29287. setTextBoxIsEditable (false);
  29288. setScrollWheelEnabled (false);
  29289. }
  29290. ~ParamSlider()
  29291. {
  29292. }
  29293. void valueChanged()
  29294. {
  29295. const float newVal = (float) getValue();
  29296. if (owner->getParameter (index) != newVal)
  29297. owner->setParameter (index, newVal);
  29298. }
  29299. const String getTextFromValue (double /*value*/)
  29300. {
  29301. return owner->getParameterText (index);
  29302. }
  29303. juce_UseDebuggingNewOperator
  29304. private:
  29305. AudioProcessor* const owner;
  29306. const int index;
  29307. ParamSlider (const ParamSlider&);
  29308. ParamSlider& operator= (const ParamSlider&);
  29309. };
  29310. ProcessorParameterPropertyComp (const ProcessorParameterPropertyComp&);
  29311. ProcessorParameterPropertyComp& operator= (const ProcessorParameterPropertyComp&);
  29312. };
  29313. GenericAudioProcessorEditor::GenericAudioProcessorEditor (AudioProcessor* const owner_)
  29314. : AudioProcessorEditor (owner_)
  29315. {
  29316. setOpaque (true);
  29317. addAndMakeVisible (panel = new PropertyPanel());
  29318. Array <PropertyComponent*> params;
  29319. const int numParams = owner_->getNumParameters();
  29320. int totalHeight = 0;
  29321. for (int i = 0; i < numParams; ++i)
  29322. {
  29323. String name (owner_->getParameterName (i));
  29324. if (name.trim().isEmpty())
  29325. name = "Unnamed";
  29326. ProcessorParameterPropertyComp* const pc = new ProcessorParameterPropertyComp (name, owner_, i);
  29327. params.add (pc);
  29328. totalHeight += pc->getPreferredHeight();
  29329. }
  29330. panel->addProperties (params);
  29331. setSize (400, jlimit (25, 400, totalHeight));
  29332. }
  29333. GenericAudioProcessorEditor::~GenericAudioProcessorEditor()
  29334. {
  29335. deleteAllChildren();
  29336. }
  29337. void GenericAudioProcessorEditor::paint (Graphics& g)
  29338. {
  29339. g.fillAll (Colours::white);
  29340. }
  29341. void GenericAudioProcessorEditor::resized()
  29342. {
  29343. panel->setSize (getWidth(), getHeight());
  29344. }
  29345. END_JUCE_NAMESPACE
  29346. /*** End of inlined file: juce_GenericAudioProcessorEditor.cpp ***/
  29347. /*** Start of inlined file: juce_Sampler.cpp ***/
  29348. BEGIN_JUCE_NAMESPACE
  29349. SamplerSound::SamplerSound (const String& name_,
  29350. AudioFormatReader& source,
  29351. const BigInteger& midiNotes_,
  29352. const int midiNoteForNormalPitch,
  29353. const double attackTimeSecs,
  29354. const double releaseTimeSecs,
  29355. const double maxSampleLengthSeconds)
  29356. : name (name_),
  29357. midiNotes (midiNotes_),
  29358. midiRootNote (midiNoteForNormalPitch)
  29359. {
  29360. sourceSampleRate = source.sampleRate;
  29361. if (sourceSampleRate <= 0 || source.lengthInSamples <= 0)
  29362. {
  29363. length = 0;
  29364. attackSamples = 0;
  29365. releaseSamples = 0;
  29366. }
  29367. else
  29368. {
  29369. length = jmin ((int) source.lengthInSamples,
  29370. (int) (maxSampleLengthSeconds * sourceSampleRate));
  29371. data = new AudioSampleBuffer (jmin (2, (int) source.numChannels), length + 4);
  29372. data->readFromAudioReader (&source, 0, length + 4, 0, true, true);
  29373. attackSamples = roundToInt (attackTimeSecs * sourceSampleRate);
  29374. releaseSamples = roundToInt (releaseTimeSecs * sourceSampleRate);
  29375. }
  29376. }
  29377. SamplerSound::~SamplerSound()
  29378. {
  29379. }
  29380. bool SamplerSound::appliesToNote (const int midiNoteNumber)
  29381. {
  29382. return midiNotes [midiNoteNumber];
  29383. }
  29384. bool SamplerSound::appliesToChannel (const int /*midiChannel*/)
  29385. {
  29386. return true;
  29387. }
  29388. SamplerVoice::SamplerVoice()
  29389. : pitchRatio (0.0),
  29390. sourceSamplePosition (0.0),
  29391. lgain (0.0f),
  29392. rgain (0.0f),
  29393. isInAttack (false),
  29394. isInRelease (false)
  29395. {
  29396. }
  29397. SamplerVoice::~SamplerVoice()
  29398. {
  29399. }
  29400. bool SamplerVoice::canPlaySound (SynthesiserSound* sound)
  29401. {
  29402. return dynamic_cast <const SamplerSound*> (sound) != 0;
  29403. }
  29404. void SamplerVoice::startNote (const int midiNoteNumber,
  29405. const float velocity,
  29406. SynthesiserSound* s,
  29407. const int /*currentPitchWheelPosition*/)
  29408. {
  29409. const SamplerSound* const sound = dynamic_cast <const SamplerSound*> (s);
  29410. jassert (sound != 0); // this object can only play SamplerSounds!
  29411. if (sound != 0)
  29412. {
  29413. const double targetFreq = MidiMessage::getMidiNoteInHertz (midiNoteNumber);
  29414. const double naturalFreq = MidiMessage::getMidiNoteInHertz (sound->midiRootNote);
  29415. pitchRatio = (targetFreq * sound->sourceSampleRate) / (naturalFreq * getSampleRate());
  29416. sourceSamplePosition = 0.0;
  29417. lgain = velocity;
  29418. rgain = velocity;
  29419. isInAttack = (sound->attackSamples > 0);
  29420. isInRelease = false;
  29421. if (isInAttack)
  29422. {
  29423. attackReleaseLevel = 0.0f;
  29424. attackDelta = (float) (pitchRatio / sound->attackSamples);
  29425. }
  29426. else
  29427. {
  29428. attackReleaseLevel = 1.0f;
  29429. attackDelta = 0.0f;
  29430. }
  29431. if (sound->releaseSamples > 0)
  29432. {
  29433. releaseDelta = (float) (-pitchRatio / sound->releaseSamples);
  29434. }
  29435. else
  29436. {
  29437. releaseDelta = 0.0f;
  29438. }
  29439. }
  29440. }
  29441. void SamplerVoice::stopNote (const bool allowTailOff)
  29442. {
  29443. if (allowTailOff)
  29444. {
  29445. isInAttack = false;
  29446. isInRelease = true;
  29447. }
  29448. else
  29449. {
  29450. clearCurrentNote();
  29451. }
  29452. }
  29453. void SamplerVoice::pitchWheelMoved (const int /*newValue*/)
  29454. {
  29455. }
  29456. void SamplerVoice::controllerMoved (const int /*controllerNumber*/,
  29457. const int /*newValue*/)
  29458. {
  29459. }
  29460. void SamplerVoice::renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples)
  29461. {
  29462. const SamplerSound* const playingSound = static_cast <SamplerSound*> (getCurrentlyPlayingSound().getObject());
  29463. if (playingSound != 0)
  29464. {
  29465. const float* const inL = playingSound->data->getSampleData (0, 0);
  29466. const float* const inR = playingSound->data->getNumChannels() > 1
  29467. ? playingSound->data->getSampleData (1, 0) : 0;
  29468. float* outL = outputBuffer.getSampleData (0, startSample);
  29469. float* outR = outputBuffer.getNumChannels() > 1 ? outputBuffer.getSampleData (1, startSample) : 0;
  29470. while (--numSamples >= 0)
  29471. {
  29472. const int pos = (int) sourceSamplePosition;
  29473. const float alpha = (float) (sourceSamplePosition - pos);
  29474. const float invAlpha = 1.0f - alpha;
  29475. // just using a very simple linear interpolation here..
  29476. float l = (inL [pos] * invAlpha + inL [pos + 1] * alpha);
  29477. float r = (inR != 0) ? (inR [pos] * invAlpha + inR [pos + 1] * alpha)
  29478. : l;
  29479. l *= lgain;
  29480. r *= rgain;
  29481. if (isInAttack)
  29482. {
  29483. l *= attackReleaseLevel;
  29484. r *= attackReleaseLevel;
  29485. attackReleaseLevel += attackDelta;
  29486. if (attackReleaseLevel >= 1.0f)
  29487. {
  29488. attackReleaseLevel = 1.0f;
  29489. isInAttack = false;
  29490. }
  29491. }
  29492. else if (isInRelease)
  29493. {
  29494. l *= attackReleaseLevel;
  29495. r *= attackReleaseLevel;
  29496. attackReleaseLevel += releaseDelta;
  29497. if (attackReleaseLevel <= 0.0f)
  29498. {
  29499. stopNote (false);
  29500. break;
  29501. }
  29502. }
  29503. if (outR != 0)
  29504. {
  29505. *outL++ += l;
  29506. *outR++ += r;
  29507. }
  29508. else
  29509. {
  29510. *outL++ += (l + r) * 0.5f;
  29511. }
  29512. sourceSamplePosition += pitchRatio;
  29513. if (sourceSamplePosition > playingSound->length)
  29514. {
  29515. stopNote (false);
  29516. break;
  29517. }
  29518. }
  29519. }
  29520. }
  29521. END_JUCE_NAMESPACE
  29522. /*** End of inlined file: juce_Sampler.cpp ***/
  29523. /*** Start of inlined file: juce_Synthesiser.cpp ***/
  29524. BEGIN_JUCE_NAMESPACE
  29525. SynthesiserSound::SynthesiserSound()
  29526. {
  29527. }
  29528. SynthesiserSound::~SynthesiserSound()
  29529. {
  29530. }
  29531. SynthesiserVoice::SynthesiserVoice()
  29532. : currentSampleRate (44100.0),
  29533. currentlyPlayingNote (-1),
  29534. noteOnTime (0),
  29535. currentlyPlayingSound (0)
  29536. {
  29537. }
  29538. SynthesiserVoice::~SynthesiserVoice()
  29539. {
  29540. }
  29541. bool SynthesiserVoice::isPlayingChannel (const int midiChannel) const
  29542. {
  29543. return currentlyPlayingSound != 0
  29544. && currentlyPlayingSound->appliesToChannel (midiChannel);
  29545. }
  29546. void SynthesiserVoice::setCurrentPlaybackSampleRate (const double newRate)
  29547. {
  29548. currentSampleRate = newRate;
  29549. }
  29550. void SynthesiserVoice::clearCurrentNote()
  29551. {
  29552. currentlyPlayingNote = -1;
  29553. currentlyPlayingSound = 0;
  29554. }
  29555. Synthesiser::Synthesiser()
  29556. : sampleRate (0),
  29557. lastNoteOnCounter (0),
  29558. shouldStealNotes (true)
  29559. {
  29560. for (int i = 0; i < numElementsInArray (lastPitchWheelValues); ++i)
  29561. lastPitchWheelValues[i] = 0x2000;
  29562. }
  29563. Synthesiser::~Synthesiser()
  29564. {
  29565. }
  29566. SynthesiserVoice* Synthesiser::getVoice (const int index) const
  29567. {
  29568. const ScopedLock sl (lock);
  29569. return voices [index];
  29570. }
  29571. void Synthesiser::clearVoices()
  29572. {
  29573. const ScopedLock sl (lock);
  29574. voices.clear();
  29575. }
  29576. void Synthesiser::addVoice (SynthesiserVoice* const newVoice)
  29577. {
  29578. const ScopedLock sl (lock);
  29579. voices.add (newVoice);
  29580. }
  29581. void Synthesiser::removeVoice (const int index)
  29582. {
  29583. const ScopedLock sl (lock);
  29584. voices.remove (index);
  29585. }
  29586. void Synthesiser::clearSounds()
  29587. {
  29588. const ScopedLock sl (lock);
  29589. sounds.clear();
  29590. }
  29591. void Synthesiser::addSound (const SynthesiserSound::Ptr& newSound)
  29592. {
  29593. const ScopedLock sl (lock);
  29594. sounds.add (newSound);
  29595. }
  29596. void Synthesiser::removeSound (const int index)
  29597. {
  29598. const ScopedLock sl (lock);
  29599. sounds.remove (index);
  29600. }
  29601. void Synthesiser::setNoteStealingEnabled (const bool shouldStealNotes_)
  29602. {
  29603. shouldStealNotes = shouldStealNotes_;
  29604. }
  29605. void Synthesiser::setCurrentPlaybackSampleRate (const double newRate)
  29606. {
  29607. if (sampleRate != newRate)
  29608. {
  29609. const ScopedLock sl (lock);
  29610. allNotesOff (0, false);
  29611. sampleRate = newRate;
  29612. for (int i = voices.size(); --i >= 0;)
  29613. voices.getUnchecked (i)->setCurrentPlaybackSampleRate (newRate);
  29614. }
  29615. }
  29616. void Synthesiser::renderNextBlock (AudioSampleBuffer& outputBuffer,
  29617. const MidiBuffer& midiData,
  29618. int startSample,
  29619. int numSamples)
  29620. {
  29621. // must set the sample rate before using this!
  29622. jassert (sampleRate != 0);
  29623. const ScopedLock sl (lock);
  29624. MidiBuffer::Iterator midiIterator (midiData);
  29625. midiIterator.setNextSamplePosition (startSample);
  29626. MidiMessage m (0xf4, 0.0);
  29627. while (numSamples > 0)
  29628. {
  29629. int midiEventPos;
  29630. const bool useEvent = midiIterator.getNextEvent (m, midiEventPos)
  29631. && midiEventPos < startSample + numSamples;
  29632. const int numThisTime = useEvent ? midiEventPos - startSample
  29633. : numSamples;
  29634. if (numThisTime > 0)
  29635. {
  29636. for (int i = voices.size(); --i >= 0;)
  29637. voices.getUnchecked (i)->renderNextBlock (outputBuffer, startSample, numThisTime);
  29638. }
  29639. if (useEvent)
  29640. {
  29641. if (m.isNoteOn())
  29642. {
  29643. const int channel = m.getChannel();
  29644. noteOn (channel,
  29645. m.getNoteNumber(),
  29646. m.getFloatVelocity());
  29647. }
  29648. else if (m.isNoteOff())
  29649. {
  29650. noteOff (m.getChannel(),
  29651. m.getNoteNumber(),
  29652. true);
  29653. }
  29654. else if (m.isAllNotesOff() || m.isAllSoundOff())
  29655. {
  29656. allNotesOff (m.getChannel(), true);
  29657. }
  29658. else if (m.isPitchWheel())
  29659. {
  29660. const int channel = m.getChannel();
  29661. const int wheelPos = m.getPitchWheelValue();
  29662. lastPitchWheelValues [channel - 1] = wheelPos;
  29663. handlePitchWheel (channel, wheelPos);
  29664. }
  29665. else if (m.isController())
  29666. {
  29667. handleController (m.getChannel(),
  29668. m.getControllerNumber(),
  29669. m.getControllerValue());
  29670. }
  29671. }
  29672. startSample += numThisTime;
  29673. numSamples -= numThisTime;
  29674. }
  29675. }
  29676. void Synthesiser::noteOn (const int midiChannel,
  29677. const int midiNoteNumber,
  29678. const float velocity)
  29679. {
  29680. const ScopedLock sl (lock);
  29681. for (int i = sounds.size(); --i >= 0;)
  29682. {
  29683. SynthesiserSound* const sound = sounds.getUnchecked(i);
  29684. if (sound->appliesToNote (midiNoteNumber)
  29685. && sound->appliesToChannel (midiChannel))
  29686. {
  29687. startVoice (findFreeVoice (sound, shouldStealNotes),
  29688. sound, midiChannel, midiNoteNumber, velocity);
  29689. }
  29690. }
  29691. }
  29692. void Synthesiser::startVoice (SynthesiserVoice* const voice,
  29693. SynthesiserSound* const sound,
  29694. const int midiChannel,
  29695. const int midiNoteNumber,
  29696. const float velocity)
  29697. {
  29698. if (voice != 0 && sound != 0)
  29699. {
  29700. if (voice->currentlyPlayingSound != 0)
  29701. voice->stopNote (false);
  29702. voice->startNote (midiNoteNumber,
  29703. velocity,
  29704. sound,
  29705. lastPitchWheelValues [midiChannel - 1]);
  29706. voice->currentlyPlayingNote = midiNoteNumber;
  29707. voice->noteOnTime = ++lastNoteOnCounter;
  29708. voice->currentlyPlayingSound = sound;
  29709. }
  29710. }
  29711. void Synthesiser::noteOff (const int midiChannel,
  29712. const int midiNoteNumber,
  29713. const bool allowTailOff)
  29714. {
  29715. const ScopedLock sl (lock);
  29716. for (int i = voices.size(); --i >= 0;)
  29717. {
  29718. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29719. if (voice->getCurrentlyPlayingNote() == midiNoteNumber)
  29720. {
  29721. SynthesiserSound* const sound = voice->getCurrentlyPlayingSound();
  29722. if (sound != 0
  29723. && sound->appliesToNote (midiNoteNumber)
  29724. && sound->appliesToChannel (midiChannel))
  29725. {
  29726. voice->stopNote (allowTailOff);
  29727. // the subclass MUST call clearCurrentNote() if it's not tailing off! RTFM for stopNote()!
  29728. jassert (allowTailOff || (voice->getCurrentlyPlayingNote() < 0 && voice->getCurrentlyPlayingSound() == 0));
  29729. }
  29730. }
  29731. }
  29732. }
  29733. void Synthesiser::allNotesOff (const int midiChannel,
  29734. const bool allowTailOff)
  29735. {
  29736. const ScopedLock sl (lock);
  29737. for (int i = voices.size(); --i >= 0;)
  29738. {
  29739. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29740. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  29741. voice->stopNote (allowTailOff);
  29742. }
  29743. }
  29744. void Synthesiser::handlePitchWheel (const int midiChannel,
  29745. const int wheelValue)
  29746. {
  29747. const ScopedLock sl (lock);
  29748. for (int i = voices.size(); --i >= 0;)
  29749. {
  29750. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29751. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  29752. {
  29753. voice->pitchWheelMoved (wheelValue);
  29754. }
  29755. }
  29756. }
  29757. void Synthesiser::handleController (const int midiChannel,
  29758. const int controllerNumber,
  29759. const int controllerValue)
  29760. {
  29761. const ScopedLock sl (lock);
  29762. for (int i = voices.size(); --i >= 0;)
  29763. {
  29764. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29765. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  29766. voice->controllerMoved (controllerNumber, controllerValue);
  29767. }
  29768. }
  29769. SynthesiserVoice* Synthesiser::findFreeVoice (SynthesiserSound* soundToPlay,
  29770. const bool stealIfNoneAvailable) const
  29771. {
  29772. const ScopedLock sl (lock);
  29773. for (int i = voices.size(); --i >= 0;)
  29774. if (voices.getUnchecked (i)->getCurrentlyPlayingNote() < 0
  29775. && voices.getUnchecked (i)->canPlaySound (soundToPlay))
  29776. return voices.getUnchecked (i);
  29777. if (stealIfNoneAvailable)
  29778. {
  29779. // currently this just steals the one that's been playing the longest, but could be made a bit smarter..
  29780. SynthesiserVoice* oldest = 0;
  29781. for (int i = voices.size(); --i >= 0;)
  29782. {
  29783. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29784. if (voice->canPlaySound (soundToPlay)
  29785. && (oldest == 0 || oldest->noteOnTime > voice->noteOnTime))
  29786. oldest = voice;
  29787. }
  29788. jassert (oldest != 0);
  29789. return oldest;
  29790. }
  29791. return 0;
  29792. }
  29793. END_JUCE_NAMESPACE
  29794. /*** End of inlined file: juce_Synthesiser.cpp ***/
  29795. /*** Start of inlined file: juce_ActionBroadcaster.cpp ***/
  29796. BEGIN_JUCE_NAMESPACE
  29797. ActionBroadcaster::ActionBroadcaster() throw()
  29798. {
  29799. // are you trying to create this object before or after juce has been intialised??
  29800. jassert (MessageManager::instance != 0);
  29801. }
  29802. ActionBroadcaster::~ActionBroadcaster()
  29803. {
  29804. // all event-based objects must be deleted BEFORE juce is shut down!
  29805. jassert (MessageManager::instance != 0);
  29806. }
  29807. void ActionBroadcaster::addActionListener (ActionListener* const listener)
  29808. {
  29809. actionListenerList.addActionListener (listener);
  29810. }
  29811. void ActionBroadcaster::removeActionListener (ActionListener* const listener)
  29812. {
  29813. jassert (actionListenerList.isValidMessageListener());
  29814. if (actionListenerList.isValidMessageListener())
  29815. actionListenerList.removeActionListener (listener);
  29816. }
  29817. void ActionBroadcaster::removeAllActionListeners()
  29818. {
  29819. actionListenerList.removeAllActionListeners();
  29820. }
  29821. void ActionBroadcaster::sendActionMessage (const String& message) const
  29822. {
  29823. actionListenerList.sendActionMessage (message);
  29824. }
  29825. END_JUCE_NAMESPACE
  29826. /*** End of inlined file: juce_ActionBroadcaster.cpp ***/
  29827. /*** Start of inlined file: juce_ActionListenerList.cpp ***/
  29828. BEGIN_JUCE_NAMESPACE
  29829. // special message of our own with a string in it
  29830. class ActionMessage : public Message
  29831. {
  29832. public:
  29833. const String message;
  29834. ActionMessage (const String& messageText,
  29835. void* const listener_) throw()
  29836. : message (messageText)
  29837. {
  29838. pointerParameter = listener_;
  29839. }
  29840. ~ActionMessage() throw()
  29841. {
  29842. }
  29843. private:
  29844. ActionMessage (const ActionMessage&);
  29845. ActionMessage& operator= (const ActionMessage&);
  29846. };
  29847. ActionListenerList::ActionListenerList() throw()
  29848. {
  29849. }
  29850. ActionListenerList::~ActionListenerList() throw()
  29851. {
  29852. }
  29853. void ActionListenerList::addActionListener (ActionListener* const listener) throw()
  29854. {
  29855. const ScopedLock sl (actionListenerLock_);
  29856. jassert (listener != 0);
  29857. jassert (! actionListeners_.contains (listener)); // trying to add a listener to the list twice!
  29858. if (listener != 0)
  29859. actionListeners_.add (listener);
  29860. }
  29861. void ActionListenerList::removeActionListener (ActionListener* const listener) throw()
  29862. {
  29863. const ScopedLock sl (actionListenerLock_);
  29864. jassert (actionListeners_.contains (listener)); // trying to remove a listener that isn't on the list!
  29865. actionListeners_.removeValue (listener);
  29866. }
  29867. void ActionListenerList::removeAllActionListeners() throw()
  29868. {
  29869. const ScopedLock sl (actionListenerLock_);
  29870. actionListeners_.clear();
  29871. }
  29872. void ActionListenerList::sendActionMessage (const String& message) const
  29873. {
  29874. const ScopedLock sl (actionListenerLock_);
  29875. for (int i = actionListeners_.size(); --i >= 0;)
  29876. postMessage (new ActionMessage (message, static_cast <ActionListener*> (actionListeners_.getUnchecked(i))));
  29877. }
  29878. void ActionListenerList::handleMessage (const Message& message)
  29879. {
  29880. const ActionMessage& am = (const ActionMessage&) message;
  29881. if (actionListeners_.contains (am.pointerParameter))
  29882. static_cast <ActionListener*> (am.pointerParameter)->actionListenerCallback (am.message);
  29883. }
  29884. END_JUCE_NAMESPACE
  29885. /*** End of inlined file: juce_ActionListenerList.cpp ***/
  29886. /*** Start of inlined file: juce_AsyncUpdater.cpp ***/
  29887. BEGIN_JUCE_NAMESPACE
  29888. AsyncUpdater::AsyncUpdater() throw()
  29889. : asyncMessagePending (false)
  29890. {
  29891. internalAsyncHandler.owner = this;
  29892. }
  29893. AsyncUpdater::~AsyncUpdater()
  29894. {
  29895. }
  29896. void AsyncUpdater::triggerAsyncUpdate() throw()
  29897. {
  29898. if (! asyncMessagePending)
  29899. {
  29900. asyncMessagePending = true;
  29901. internalAsyncHandler.postMessage (new Message());
  29902. }
  29903. }
  29904. void AsyncUpdater::cancelPendingUpdate() throw()
  29905. {
  29906. asyncMessagePending = false;
  29907. }
  29908. void AsyncUpdater::handleUpdateNowIfNeeded()
  29909. {
  29910. if (asyncMessagePending)
  29911. {
  29912. asyncMessagePending = false;
  29913. handleAsyncUpdate();
  29914. }
  29915. }
  29916. void AsyncUpdater::AsyncUpdaterInternal::handleMessage (const Message&)
  29917. {
  29918. owner->handleUpdateNowIfNeeded();
  29919. }
  29920. END_JUCE_NAMESPACE
  29921. /*** End of inlined file: juce_AsyncUpdater.cpp ***/
  29922. /*** Start of inlined file: juce_ChangeBroadcaster.cpp ***/
  29923. BEGIN_JUCE_NAMESPACE
  29924. ChangeBroadcaster::ChangeBroadcaster() throw()
  29925. {
  29926. // are you trying to create this object before or after juce has been intialised??
  29927. jassert (MessageManager::instance != 0);
  29928. }
  29929. ChangeBroadcaster::~ChangeBroadcaster()
  29930. {
  29931. // all event-based objects must be deleted BEFORE juce is shut down!
  29932. jassert (MessageManager::instance != 0);
  29933. }
  29934. void ChangeBroadcaster::addChangeListener (ChangeListener* const listener) throw()
  29935. {
  29936. changeListenerList.addChangeListener (listener);
  29937. }
  29938. void ChangeBroadcaster::removeChangeListener (ChangeListener* const listener) throw()
  29939. {
  29940. jassert (changeListenerList.isValidMessageListener());
  29941. if (changeListenerList.isValidMessageListener())
  29942. changeListenerList.removeChangeListener (listener);
  29943. }
  29944. void ChangeBroadcaster::removeAllChangeListeners() throw()
  29945. {
  29946. changeListenerList.removeAllChangeListeners();
  29947. }
  29948. void ChangeBroadcaster::sendChangeMessage (void* objectThatHasChanged) throw()
  29949. {
  29950. changeListenerList.sendChangeMessage (objectThatHasChanged);
  29951. }
  29952. void ChangeBroadcaster::sendSynchronousChangeMessage (void* objectThatHasChanged)
  29953. {
  29954. changeListenerList.sendSynchronousChangeMessage (objectThatHasChanged);
  29955. }
  29956. void ChangeBroadcaster::dispatchPendingMessages()
  29957. {
  29958. changeListenerList.dispatchPendingMessages();
  29959. }
  29960. END_JUCE_NAMESPACE
  29961. /*** End of inlined file: juce_ChangeBroadcaster.cpp ***/
  29962. /*** Start of inlined file: juce_ChangeListenerList.cpp ***/
  29963. BEGIN_JUCE_NAMESPACE
  29964. ChangeListenerList::ChangeListenerList() throw()
  29965. : lastChangedObject (0),
  29966. messagePending (false)
  29967. {
  29968. }
  29969. ChangeListenerList::~ChangeListenerList() throw()
  29970. {
  29971. }
  29972. void ChangeListenerList::addChangeListener (ChangeListener* const listener) throw()
  29973. {
  29974. const ScopedLock sl (lock);
  29975. jassert (listener != 0);
  29976. if (listener != 0)
  29977. listeners.add (listener);
  29978. }
  29979. void ChangeListenerList::removeChangeListener (ChangeListener* const listener) throw()
  29980. {
  29981. const ScopedLock sl (lock);
  29982. listeners.removeValue (listener);
  29983. }
  29984. void ChangeListenerList::removeAllChangeListeners() throw()
  29985. {
  29986. const ScopedLock sl (lock);
  29987. listeners.clear();
  29988. }
  29989. void ChangeListenerList::sendChangeMessage (void* const objectThatHasChanged) throw()
  29990. {
  29991. const ScopedLock sl (lock);
  29992. if ((! messagePending) && (listeners.size() > 0))
  29993. {
  29994. lastChangedObject = objectThatHasChanged;
  29995. postMessage (new Message (0, 0, 0, objectThatHasChanged));
  29996. messagePending = true;
  29997. }
  29998. }
  29999. void ChangeListenerList::handleMessage (const Message& message)
  30000. {
  30001. sendSynchronousChangeMessage (message.pointerParameter);
  30002. }
  30003. void ChangeListenerList::sendSynchronousChangeMessage (void* const objectThatHasChanged)
  30004. {
  30005. const ScopedLock sl (lock);
  30006. messagePending = false;
  30007. for (int i = listeners.size(); --i >= 0;)
  30008. {
  30009. ChangeListener* const l = static_cast <ChangeListener*> (listeners.getUnchecked (i));
  30010. {
  30011. const ScopedUnlock tempUnlocker (lock);
  30012. l->changeListenerCallback (objectThatHasChanged);
  30013. }
  30014. i = jmin (i, listeners.size());
  30015. }
  30016. }
  30017. void ChangeListenerList::dispatchPendingMessages()
  30018. {
  30019. if (messagePending)
  30020. sendSynchronousChangeMessage (lastChangedObject);
  30021. }
  30022. END_JUCE_NAMESPACE
  30023. /*** End of inlined file: juce_ChangeListenerList.cpp ***/
  30024. /*** Start of inlined file: juce_InterprocessConnection.cpp ***/
  30025. BEGIN_JUCE_NAMESPACE
  30026. InterprocessConnection::InterprocessConnection (const bool callbacksOnMessageThread,
  30027. const uint32 magicMessageHeaderNumber)
  30028. : Thread ("Juce IPC connection"),
  30029. callbackConnectionState (false),
  30030. useMessageThread (callbacksOnMessageThread),
  30031. magicMessageHeader (magicMessageHeaderNumber),
  30032. pipeReceiveMessageTimeout (-1)
  30033. {
  30034. }
  30035. InterprocessConnection::~InterprocessConnection()
  30036. {
  30037. callbackConnectionState = false;
  30038. disconnect();
  30039. }
  30040. bool InterprocessConnection::connectToSocket (const String& hostName,
  30041. const int portNumber,
  30042. const int timeOutMillisecs)
  30043. {
  30044. disconnect();
  30045. const ScopedLock sl (pipeAndSocketLock);
  30046. socket = new StreamingSocket();
  30047. if (socket->connect (hostName, portNumber, timeOutMillisecs))
  30048. {
  30049. connectionMadeInt();
  30050. startThread();
  30051. return true;
  30052. }
  30053. else
  30054. {
  30055. socket = 0;
  30056. return false;
  30057. }
  30058. }
  30059. bool InterprocessConnection::connectToPipe (const String& pipeName,
  30060. const int pipeReceiveMessageTimeoutMs)
  30061. {
  30062. disconnect();
  30063. ScopedPointer <NamedPipe> newPipe (new NamedPipe());
  30064. if (newPipe->openExisting (pipeName))
  30065. {
  30066. const ScopedLock sl (pipeAndSocketLock);
  30067. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  30068. initialiseWithPipe (newPipe.release());
  30069. return true;
  30070. }
  30071. return false;
  30072. }
  30073. bool InterprocessConnection::createPipe (const String& pipeName,
  30074. const int pipeReceiveMessageTimeoutMs)
  30075. {
  30076. disconnect();
  30077. ScopedPointer <NamedPipe> newPipe (new NamedPipe());
  30078. if (newPipe->createNewPipe (pipeName))
  30079. {
  30080. const ScopedLock sl (pipeAndSocketLock);
  30081. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  30082. initialiseWithPipe (newPipe.release());
  30083. return true;
  30084. }
  30085. return false;
  30086. }
  30087. void InterprocessConnection::disconnect()
  30088. {
  30089. if (socket != 0)
  30090. socket->close();
  30091. if (pipe != 0)
  30092. {
  30093. pipe->cancelPendingReads();
  30094. pipe->close();
  30095. }
  30096. stopThread (4000);
  30097. {
  30098. const ScopedLock sl (pipeAndSocketLock);
  30099. socket = 0;
  30100. pipe = 0;
  30101. }
  30102. connectionLostInt();
  30103. }
  30104. bool InterprocessConnection::isConnected() const
  30105. {
  30106. const ScopedLock sl (pipeAndSocketLock);
  30107. return ((socket != 0 && socket->isConnected())
  30108. || (pipe != 0 && pipe->isOpen()))
  30109. && isThreadRunning();
  30110. }
  30111. const String InterprocessConnection::getConnectedHostName() const
  30112. {
  30113. if (pipe != 0)
  30114. {
  30115. return "localhost";
  30116. }
  30117. else if (socket != 0)
  30118. {
  30119. if (! socket->isLocal())
  30120. return socket->getHostName();
  30121. return "localhost";
  30122. }
  30123. return String::empty;
  30124. }
  30125. bool InterprocessConnection::sendMessage (const MemoryBlock& message)
  30126. {
  30127. uint32 messageHeader[2];
  30128. messageHeader [0] = ByteOrder::swapIfBigEndian (magicMessageHeader);
  30129. messageHeader [1] = ByteOrder::swapIfBigEndian ((uint32) message.getSize());
  30130. MemoryBlock messageData (sizeof (messageHeader) + message.getSize());
  30131. messageData.copyFrom (messageHeader, 0, sizeof (messageHeader));
  30132. messageData.copyFrom (message.getData(), sizeof (messageHeader), message.getSize());
  30133. size_t bytesWritten = 0;
  30134. const ScopedLock sl (pipeAndSocketLock);
  30135. if (socket != 0)
  30136. {
  30137. bytesWritten = socket->write (messageData.getData(), (int) messageData.getSize());
  30138. }
  30139. else if (pipe != 0)
  30140. {
  30141. bytesWritten = pipe->write (messageData.getData(), (int) messageData.getSize());
  30142. }
  30143. if (bytesWritten < 0)
  30144. {
  30145. // error..
  30146. return false;
  30147. }
  30148. return (bytesWritten == messageData.getSize());
  30149. }
  30150. void InterprocessConnection::initialiseWithSocket (StreamingSocket* const socket_)
  30151. {
  30152. jassert (socket == 0);
  30153. socket = socket_;
  30154. connectionMadeInt();
  30155. startThread();
  30156. }
  30157. void InterprocessConnection::initialiseWithPipe (NamedPipe* const pipe_)
  30158. {
  30159. jassert (pipe == 0);
  30160. pipe = pipe_;
  30161. connectionMadeInt();
  30162. startThread();
  30163. }
  30164. const int messageMagicNumber = 0xb734128b;
  30165. void InterprocessConnection::handleMessage (const Message& message)
  30166. {
  30167. if (message.intParameter1 == messageMagicNumber)
  30168. {
  30169. switch (message.intParameter2)
  30170. {
  30171. case 0:
  30172. {
  30173. ScopedPointer <MemoryBlock> data (static_cast <MemoryBlock*> (message.pointerParameter));
  30174. messageReceived (*data);
  30175. break;
  30176. }
  30177. case 1:
  30178. connectionMade();
  30179. break;
  30180. case 2:
  30181. connectionLost();
  30182. break;
  30183. }
  30184. }
  30185. }
  30186. void InterprocessConnection::connectionMadeInt()
  30187. {
  30188. if (! callbackConnectionState)
  30189. {
  30190. callbackConnectionState = true;
  30191. if (useMessageThread)
  30192. postMessage (new Message (messageMagicNumber, 1, 0, 0));
  30193. else
  30194. connectionMade();
  30195. }
  30196. }
  30197. void InterprocessConnection::connectionLostInt()
  30198. {
  30199. if (callbackConnectionState)
  30200. {
  30201. callbackConnectionState = false;
  30202. if (useMessageThread)
  30203. postMessage (new Message (messageMagicNumber, 2, 0, 0));
  30204. else
  30205. connectionLost();
  30206. }
  30207. }
  30208. void InterprocessConnection::deliverDataInt (const MemoryBlock& data)
  30209. {
  30210. jassert (callbackConnectionState);
  30211. if (useMessageThread)
  30212. postMessage (new Message (messageMagicNumber, 0, 0, new MemoryBlock (data)));
  30213. else
  30214. messageReceived (data);
  30215. }
  30216. bool InterprocessConnection::readNextMessageInt()
  30217. {
  30218. const int maximumMessageSize = 1024 * 1024 * 10; // sanity check
  30219. uint32 messageHeader[2];
  30220. const int bytes = (socket != 0) ? socket->read (messageHeader, sizeof (messageHeader), true)
  30221. : pipe->read (messageHeader, sizeof (messageHeader), pipeReceiveMessageTimeout);
  30222. if (bytes == sizeof (messageHeader)
  30223. && ByteOrder::swapIfBigEndian (messageHeader[0]) == magicMessageHeader)
  30224. {
  30225. int bytesInMessage = (int) ByteOrder::swapIfBigEndian (messageHeader[1]);
  30226. if (bytesInMessage > 0 && bytesInMessage < maximumMessageSize)
  30227. {
  30228. MemoryBlock messageData (bytesInMessage, true);
  30229. int bytesRead = 0;
  30230. while (bytesInMessage > 0)
  30231. {
  30232. if (threadShouldExit())
  30233. return false;
  30234. const int numThisTime = jmin (bytesInMessage, 65536);
  30235. const int bytesIn = (socket != 0) ? socket->read (static_cast <char*> (messageData.getData()) + bytesRead, numThisTime, true)
  30236. : pipe->read (static_cast <char*> (messageData.getData()) + bytesRead, numThisTime, pipeReceiveMessageTimeout);
  30237. if (bytesIn <= 0)
  30238. break;
  30239. bytesRead += bytesIn;
  30240. bytesInMessage -= bytesIn;
  30241. }
  30242. if (bytesRead >= 0)
  30243. deliverDataInt (messageData);
  30244. }
  30245. }
  30246. else if (bytes < 0)
  30247. {
  30248. {
  30249. const ScopedLock sl (pipeAndSocketLock);
  30250. socket = 0;
  30251. }
  30252. connectionLostInt();
  30253. return false;
  30254. }
  30255. return true;
  30256. }
  30257. void InterprocessConnection::run()
  30258. {
  30259. while (! threadShouldExit())
  30260. {
  30261. if (socket != 0)
  30262. {
  30263. const int ready = socket->waitUntilReady (true, 0);
  30264. if (ready < 0)
  30265. {
  30266. {
  30267. const ScopedLock sl (pipeAndSocketLock);
  30268. socket = 0;
  30269. }
  30270. connectionLostInt();
  30271. break;
  30272. }
  30273. else if (ready > 0)
  30274. {
  30275. if (! readNextMessageInt())
  30276. break;
  30277. }
  30278. else
  30279. {
  30280. Thread::sleep (2);
  30281. }
  30282. }
  30283. else if (pipe != 0)
  30284. {
  30285. if (! pipe->isOpen())
  30286. {
  30287. {
  30288. const ScopedLock sl (pipeAndSocketLock);
  30289. pipe = 0;
  30290. }
  30291. connectionLostInt();
  30292. break;
  30293. }
  30294. else
  30295. {
  30296. if (! readNextMessageInt())
  30297. break;
  30298. }
  30299. }
  30300. else
  30301. {
  30302. break;
  30303. }
  30304. }
  30305. }
  30306. END_JUCE_NAMESPACE
  30307. /*** End of inlined file: juce_InterprocessConnection.cpp ***/
  30308. /*** Start of inlined file: juce_InterprocessConnectionServer.cpp ***/
  30309. BEGIN_JUCE_NAMESPACE
  30310. InterprocessConnectionServer::InterprocessConnectionServer()
  30311. : Thread ("Juce IPC server")
  30312. {
  30313. }
  30314. InterprocessConnectionServer::~InterprocessConnectionServer()
  30315. {
  30316. stop();
  30317. }
  30318. bool InterprocessConnectionServer::beginWaitingForSocket (const int portNumber)
  30319. {
  30320. stop();
  30321. socket = new StreamingSocket();
  30322. if (socket->createListener (portNumber))
  30323. {
  30324. startThread();
  30325. return true;
  30326. }
  30327. socket = 0;
  30328. return false;
  30329. }
  30330. void InterprocessConnectionServer::stop()
  30331. {
  30332. signalThreadShouldExit();
  30333. if (socket != 0)
  30334. socket->close();
  30335. stopThread (4000);
  30336. socket = 0;
  30337. }
  30338. void InterprocessConnectionServer::run()
  30339. {
  30340. while ((! threadShouldExit()) && socket != 0)
  30341. {
  30342. ScopedPointer <StreamingSocket> clientSocket (socket->waitForNextConnection());
  30343. if (clientSocket != 0)
  30344. {
  30345. InterprocessConnection* newConnection = createConnectionObject();
  30346. if (newConnection != 0)
  30347. newConnection->initialiseWithSocket (clientSocket.release());
  30348. }
  30349. }
  30350. }
  30351. END_JUCE_NAMESPACE
  30352. /*** End of inlined file: juce_InterprocessConnectionServer.cpp ***/
  30353. /*** Start of inlined file: juce_Message.cpp ***/
  30354. BEGIN_JUCE_NAMESPACE
  30355. Message::Message() throw()
  30356. : intParameter1 (0),
  30357. intParameter2 (0),
  30358. intParameter3 (0),
  30359. pointerParameter (0)
  30360. {
  30361. }
  30362. Message::Message (const int intParameter1_,
  30363. const int intParameter2_,
  30364. const int intParameter3_,
  30365. void* const pointerParameter_) throw()
  30366. : intParameter1 (intParameter1_),
  30367. intParameter2 (intParameter2_),
  30368. intParameter3 (intParameter3_),
  30369. pointerParameter (pointerParameter_)
  30370. {
  30371. }
  30372. Message::~Message() throw()
  30373. {
  30374. }
  30375. END_JUCE_NAMESPACE
  30376. /*** End of inlined file: juce_Message.cpp ***/
  30377. /*** Start of inlined file: juce_MessageListener.cpp ***/
  30378. BEGIN_JUCE_NAMESPACE
  30379. MessageListener::MessageListener() throw()
  30380. {
  30381. // are you trying to create a messagelistener before or after juce has been intialised??
  30382. jassert (MessageManager::instance != 0);
  30383. if (MessageManager::instance != 0)
  30384. MessageManager::instance->messageListeners.add (this);
  30385. }
  30386. MessageListener::~MessageListener()
  30387. {
  30388. if (MessageManager::instance != 0)
  30389. MessageManager::instance->messageListeners.removeValue (this);
  30390. }
  30391. void MessageListener::postMessage (Message* const message) const throw()
  30392. {
  30393. message->messageRecipient = const_cast <MessageListener*> (this);
  30394. if (MessageManager::instance == 0)
  30395. MessageManager::getInstance();
  30396. MessageManager::instance->postMessageToQueue (message);
  30397. }
  30398. bool MessageListener::isValidMessageListener() const throw()
  30399. {
  30400. return (MessageManager::instance != 0)
  30401. && MessageManager::instance->messageListeners.contains (this);
  30402. }
  30403. END_JUCE_NAMESPACE
  30404. /*** End of inlined file: juce_MessageListener.cpp ***/
  30405. /*** Start of inlined file: juce_MessageManager.cpp ***/
  30406. BEGIN_JUCE_NAMESPACE
  30407. // platform-specific functions..
  30408. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages);
  30409. bool juce_postMessageToSystemQueue (void* message);
  30410. MessageManager* MessageManager::instance = 0;
  30411. static const int quitMessageId = 0xfffff321;
  30412. MessageManager::MessageManager() throw()
  30413. : quitMessagePosted (false),
  30414. quitMessageReceived (false),
  30415. threadWithLock (0)
  30416. {
  30417. messageThreadId = Thread::getCurrentThreadId();
  30418. }
  30419. MessageManager::~MessageManager() throw()
  30420. {
  30421. broadcastListeners = 0;
  30422. doPlatformSpecificShutdown();
  30423. jassert (instance == this);
  30424. instance = 0; // do this last in case this instance is still needed by doPlatformSpecificShutdown()
  30425. }
  30426. MessageManager* MessageManager::getInstance() throw()
  30427. {
  30428. if (instance == 0)
  30429. {
  30430. instance = new MessageManager();
  30431. doPlatformSpecificInitialisation();
  30432. }
  30433. return instance;
  30434. }
  30435. void MessageManager::postMessageToQueue (Message* const message)
  30436. {
  30437. if (quitMessagePosted || ! juce_postMessageToSystemQueue (message))
  30438. delete message;
  30439. }
  30440. CallbackMessage::CallbackMessage() throw() {}
  30441. CallbackMessage::~CallbackMessage() throw() {}
  30442. void CallbackMessage::post()
  30443. {
  30444. if (MessageManager::instance != 0)
  30445. MessageManager::instance->postCallbackMessage (this);
  30446. }
  30447. void MessageManager::postCallbackMessage (Message* const message)
  30448. {
  30449. message->messageRecipient = 0;
  30450. postMessageToQueue (message);
  30451. }
  30452. // not for public use..
  30453. void MessageManager::deliverMessage (void* const message)
  30454. {
  30455. const ScopedPointer <Message> m (static_cast <Message*> (message));
  30456. MessageListener* const recipient = m->messageRecipient;
  30457. JUCE_TRY
  30458. {
  30459. if (messageListeners.contains (recipient))
  30460. {
  30461. recipient->handleMessage (*m);
  30462. }
  30463. else if (recipient == 0)
  30464. {
  30465. if (m->intParameter1 == quitMessageId)
  30466. {
  30467. quitMessageReceived = true;
  30468. }
  30469. else
  30470. {
  30471. CallbackMessage* const cm = dynamic_cast <CallbackMessage*> (static_cast <Message*> (m));
  30472. if (cm != 0)
  30473. cm->messageCallback();
  30474. }
  30475. }
  30476. }
  30477. JUCE_CATCH_EXCEPTION
  30478. }
  30479. #if ! (JUCE_MAC || JUCE_IPHONE)
  30480. void MessageManager::runDispatchLoop()
  30481. {
  30482. jassert (isThisTheMessageThread()); // must only be called by the message thread
  30483. runDispatchLoopUntil (-1);
  30484. }
  30485. void MessageManager::stopDispatchLoop()
  30486. {
  30487. Message* const m = new Message (quitMessageId, 0, 0, 0);
  30488. m->messageRecipient = 0;
  30489. postMessageToQueue (m);
  30490. quitMessagePosted = true;
  30491. }
  30492. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  30493. {
  30494. jassert (isThisTheMessageThread()); // must only be called by the message thread
  30495. const int64 endTime = Time::currentTimeMillis() + millisecondsToRunFor;
  30496. while ((millisecondsToRunFor < 0 || endTime > Time::currentTimeMillis())
  30497. && ! quitMessageReceived)
  30498. {
  30499. JUCE_TRY
  30500. {
  30501. if (! juce_dispatchNextMessageOnSystemQueue (millisecondsToRunFor >= 0))
  30502. {
  30503. const int msToWait = (int) (endTime - Time::currentTimeMillis());
  30504. if (msToWait > 0)
  30505. Thread::sleep (jmin (5, msToWait));
  30506. }
  30507. }
  30508. JUCE_CATCH_EXCEPTION
  30509. }
  30510. return ! quitMessageReceived;
  30511. }
  30512. #endif
  30513. void MessageManager::deliverBroadcastMessage (const String& value)
  30514. {
  30515. if (broadcastListeners != 0)
  30516. broadcastListeners->sendActionMessage (value);
  30517. }
  30518. void MessageManager::registerBroadcastListener (ActionListener* const listener) throw()
  30519. {
  30520. if (broadcastListeners == 0)
  30521. broadcastListeners = new ActionListenerList();
  30522. broadcastListeners->addActionListener (listener);
  30523. }
  30524. void MessageManager::deregisterBroadcastListener (ActionListener* const listener) throw()
  30525. {
  30526. if (broadcastListeners != 0)
  30527. broadcastListeners->removeActionListener (listener);
  30528. }
  30529. bool MessageManager::isThisTheMessageThread() const throw()
  30530. {
  30531. return Thread::getCurrentThreadId() == messageThreadId;
  30532. }
  30533. void MessageManager::setCurrentThreadAsMessageThread()
  30534. {
  30535. if (messageThreadId != Thread::getCurrentThreadId())
  30536. {
  30537. messageThreadId = Thread::getCurrentThreadId();
  30538. // This is needed on windows to make sure the message window is created by this thread
  30539. doPlatformSpecificShutdown();
  30540. doPlatformSpecificInitialisation();
  30541. }
  30542. }
  30543. bool MessageManager::currentThreadHasLockedMessageManager() const throw()
  30544. {
  30545. const Thread::ThreadID thisThread = Thread::getCurrentThreadId();
  30546. return thisThread == messageThreadId || thisThread == threadWithLock;
  30547. }
  30548. /* The only safe way to lock the message thread while another thread does
  30549. some work is by posting a special message, whose purpose is to tie up the event
  30550. loop until the other thread has finished its business.
  30551. Any other approach can get horribly deadlocked if the OS uses its own hidden locks which
  30552. get locked before making an event callback, because if the same OS lock gets indirectly
  30553. accessed from another thread inside a MM lock, you're screwed. (this is exactly what happens
  30554. in Cocoa).
  30555. */
  30556. class MessageManagerLock::SharedEvents : public ReferenceCountedObject
  30557. {
  30558. public:
  30559. SharedEvents() {}
  30560. ~SharedEvents() {}
  30561. /* This class just holds a couple of events to communicate between the BlockingMessage
  30562. and the MessageManagerLock. Because both of these objects may be deleted at any time,
  30563. this shared data must be kept in a separate, ref-counted container. */
  30564. WaitableEvent lockedEvent, releaseEvent;
  30565. private:
  30566. SharedEvents (const SharedEvents&);
  30567. SharedEvents& operator= (const SharedEvents&);
  30568. };
  30569. class MessageManagerLock::BlockingMessage : public CallbackMessage
  30570. {
  30571. public:
  30572. BlockingMessage (MessageManagerLock::SharedEvents* const events_) : events (events_) {}
  30573. ~BlockingMessage() throw() {}
  30574. void messageCallback()
  30575. {
  30576. events->lockedEvent.signal();
  30577. events->releaseEvent.wait();
  30578. }
  30579. juce_UseDebuggingNewOperator
  30580. private:
  30581. ReferenceCountedObjectPtr <MessageManagerLock::SharedEvents> events;
  30582. BlockingMessage (const BlockingMessage&);
  30583. BlockingMessage& operator= (const BlockingMessage&);
  30584. };
  30585. MessageManagerLock::MessageManagerLock (Thread* const threadToCheck) throw()
  30586. : sharedEvents (0),
  30587. locked (false)
  30588. {
  30589. init (threadToCheck, 0);
  30590. }
  30591. MessageManagerLock::MessageManagerLock (ThreadPoolJob* const jobToCheckForExitSignal) throw()
  30592. : sharedEvents (0),
  30593. locked (false)
  30594. {
  30595. init (0, jobToCheckForExitSignal);
  30596. }
  30597. void MessageManagerLock::init (Thread* const threadToCheck, ThreadPoolJob* const job) throw()
  30598. {
  30599. if (MessageManager::instance != 0)
  30600. {
  30601. if (MessageManager::instance->currentThreadHasLockedMessageManager())
  30602. {
  30603. locked = true; // either we're on the message thread, or this is a re-entrant call.
  30604. }
  30605. else
  30606. {
  30607. if (threadToCheck == 0 && job == 0)
  30608. {
  30609. MessageManager::instance->lockingLock.enter();
  30610. }
  30611. else
  30612. {
  30613. while (! MessageManager::instance->lockingLock.tryEnter())
  30614. {
  30615. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  30616. || (job != 0 && job->shouldExit()))
  30617. return;
  30618. Thread::sleep (1);
  30619. }
  30620. }
  30621. sharedEvents = new SharedEvents();
  30622. sharedEvents->incReferenceCount();
  30623. (new BlockingMessage (sharedEvents))->post();
  30624. while (! sharedEvents->lockedEvent.wait (50))
  30625. {
  30626. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  30627. || (job != 0 && job->shouldExit()))
  30628. {
  30629. sharedEvents->releaseEvent.signal();
  30630. sharedEvents->decReferenceCount();
  30631. sharedEvents = 0;
  30632. MessageManager::instance->lockingLock.exit();
  30633. return;
  30634. }
  30635. }
  30636. jassert (MessageManager::instance->threadWithLock == 0);
  30637. MessageManager::instance->threadWithLock = Thread::getCurrentThreadId();
  30638. locked = true;
  30639. }
  30640. }
  30641. }
  30642. MessageManagerLock::~MessageManagerLock() throw()
  30643. {
  30644. if (sharedEvents != 0)
  30645. {
  30646. jassert (MessageManager::instance == 0 || MessageManager::instance->currentThreadHasLockedMessageManager());
  30647. sharedEvents->releaseEvent.signal();
  30648. sharedEvents->decReferenceCount();
  30649. if (MessageManager::instance != 0)
  30650. {
  30651. MessageManager::instance->threadWithLock = 0;
  30652. MessageManager::instance->lockingLock.exit();
  30653. }
  30654. }
  30655. }
  30656. END_JUCE_NAMESPACE
  30657. /*** End of inlined file: juce_MessageManager.cpp ***/
  30658. /*** Start of inlined file: juce_MultiTimer.cpp ***/
  30659. BEGIN_JUCE_NAMESPACE
  30660. class MultiTimer::MultiTimerCallback : public Timer
  30661. {
  30662. public:
  30663. MultiTimerCallback (const int timerId_, MultiTimer& owner_)
  30664. : timerId (timerId_),
  30665. owner (owner_)
  30666. {
  30667. }
  30668. ~MultiTimerCallback()
  30669. {
  30670. }
  30671. void timerCallback()
  30672. {
  30673. owner.timerCallback (timerId);
  30674. }
  30675. const int timerId;
  30676. private:
  30677. MultiTimer& owner;
  30678. };
  30679. MultiTimer::MultiTimer() throw()
  30680. {
  30681. }
  30682. MultiTimer::MultiTimer (const MultiTimer&) throw()
  30683. {
  30684. }
  30685. MultiTimer::~MultiTimer()
  30686. {
  30687. const ScopedLock sl (timerListLock);
  30688. timers.clear();
  30689. }
  30690. void MultiTimer::startTimer (const int timerId, const int intervalInMilliseconds) throw()
  30691. {
  30692. const ScopedLock sl (timerListLock);
  30693. for (int i = timers.size(); --i >= 0;)
  30694. {
  30695. MultiTimerCallback* const t = timers.getUnchecked(i);
  30696. if (t->timerId == timerId)
  30697. {
  30698. t->startTimer (intervalInMilliseconds);
  30699. return;
  30700. }
  30701. }
  30702. MultiTimerCallback* const newTimer = new MultiTimerCallback (timerId, *this);
  30703. timers.add (newTimer);
  30704. newTimer->startTimer (intervalInMilliseconds);
  30705. }
  30706. void MultiTimer::stopTimer (const int timerId) throw()
  30707. {
  30708. const ScopedLock sl (timerListLock);
  30709. for (int i = timers.size(); --i >= 0;)
  30710. {
  30711. MultiTimerCallback* const t = timers.getUnchecked(i);
  30712. if (t->timerId == timerId)
  30713. t->stopTimer();
  30714. }
  30715. }
  30716. bool MultiTimer::isTimerRunning (const int timerId) const throw()
  30717. {
  30718. const ScopedLock sl (timerListLock);
  30719. for (int i = timers.size(); --i >= 0;)
  30720. {
  30721. const MultiTimerCallback* const t = timers.getUnchecked(i);
  30722. if (t->timerId == timerId)
  30723. return t->isTimerRunning();
  30724. }
  30725. return false;
  30726. }
  30727. int MultiTimer::getTimerInterval (const int timerId) const throw()
  30728. {
  30729. const ScopedLock sl (timerListLock);
  30730. for (int i = timers.size(); --i >= 0;)
  30731. {
  30732. const MultiTimerCallback* const t = timers.getUnchecked(i);
  30733. if (t->timerId == timerId)
  30734. return t->getTimerInterval();
  30735. }
  30736. return 0;
  30737. }
  30738. END_JUCE_NAMESPACE
  30739. /*** End of inlined file: juce_MultiTimer.cpp ***/
  30740. /*** Start of inlined file: juce_Timer.cpp ***/
  30741. BEGIN_JUCE_NAMESPACE
  30742. class InternalTimerThread : private Thread,
  30743. private MessageListener,
  30744. private DeletedAtShutdown,
  30745. private AsyncUpdater
  30746. {
  30747. public:
  30748. InternalTimerThread()
  30749. : Thread ("Juce Timer"),
  30750. firstTimer (0),
  30751. callbackNeeded (0)
  30752. {
  30753. triggerAsyncUpdate();
  30754. }
  30755. ~InternalTimerThread() throw()
  30756. {
  30757. stopThread (4000);
  30758. jassert (instance == this || instance == 0);
  30759. if (instance == this)
  30760. instance = 0;
  30761. }
  30762. void run()
  30763. {
  30764. uint32 lastTime = Time::getMillisecondCounter();
  30765. while (! threadShouldExit())
  30766. {
  30767. const uint32 now = Time::getMillisecondCounter();
  30768. if (now <= lastTime)
  30769. {
  30770. wait (2);
  30771. continue;
  30772. }
  30773. const int elapsed = now - lastTime;
  30774. lastTime = now;
  30775. int timeUntilFirstTimer = 1000;
  30776. {
  30777. const ScopedLock sl (lock);
  30778. decrementAllCounters (elapsed);
  30779. if (firstTimer != 0)
  30780. timeUntilFirstTimer = firstTimer->countdownMs;
  30781. }
  30782. if (timeUntilFirstTimer <= 0)
  30783. {
  30784. /* If we managed to set the atomic boolean to true then send a message, this is needed
  30785. as a memory barrier so the message won't be sent before callbackNeeded is set to true,
  30786. but if it fails it means the message-thread changed the value from under us so at least
  30787. some processing is happenening and we can just loop around and try again
  30788. */
  30789. if (callbackNeeded.compareAndSetBool (1, 0))
  30790. {
  30791. postMessage (new Message());
  30792. /* Sometimes our message can get discarded by the OS (e.g. when running as an RTAS
  30793. when the app has a modal loop), so this is how long to wait before assuming the
  30794. message has been lost and trying again.
  30795. */
  30796. const uint32 messageDeliveryTimeout = now + 2000;
  30797. while (callbackNeeded.get() != 0)
  30798. {
  30799. wait (4);
  30800. if (threadShouldExit())
  30801. return;
  30802. if (Time::getMillisecondCounter() > messageDeliveryTimeout)
  30803. break;
  30804. }
  30805. }
  30806. }
  30807. else
  30808. {
  30809. // don't wait for too long because running this loop also helps keep the
  30810. // Time::getApproximateMillisecondTimer value stay up-to-date
  30811. wait (jlimit (1, 50, timeUntilFirstTimer));
  30812. }
  30813. }
  30814. }
  30815. void callTimers()
  30816. {
  30817. const ScopedLock sl (lock);
  30818. while (firstTimer != 0 && firstTimer->countdownMs <= 0)
  30819. {
  30820. Timer* const t = firstTimer;
  30821. t->countdownMs = t->periodMs;
  30822. removeTimer (t);
  30823. addTimer (t);
  30824. const ScopedUnlock ul (lock);
  30825. JUCE_TRY
  30826. {
  30827. t->timerCallback();
  30828. }
  30829. JUCE_CATCH_EXCEPTION
  30830. }
  30831. /* This is needed as a memory barrier to make sure all processing of current timers is done
  30832. before the boolean is set. This set should never fail since if it was false in the first place,
  30833. we wouldn't get a message (so it can't be changed from false to true from under us), and if we
  30834. get a message then the value is true and the other thread can only set it to true again and
  30835. we will get another callback to set it to false.
  30836. */
  30837. callbackNeeded.set (0);
  30838. }
  30839. void handleMessage (const Message&)
  30840. {
  30841. callTimers();
  30842. }
  30843. void callTimersSynchronously()
  30844. {
  30845. if (! isThreadRunning())
  30846. {
  30847. // (This is relied on by some plugins in cases where the MM has
  30848. // had to restart and the async callback never started)
  30849. cancelPendingUpdate();
  30850. triggerAsyncUpdate();
  30851. }
  30852. callTimers();
  30853. }
  30854. static void callAnyTimersSynchronously()
  30855. {
  30856. if (InternalTimerThread::instance != 0)
  30857. InternalTimerThread::instance->callTimersSynchronously();
  30858. }
  30859. static inline void add (Timer* const tim) throw()
  30860. {
  30861. if (instance == 0)
  30862. instance = new InternalTimerThread();
  30863. const ScopedLock sl (instance->lock);
  30864. instance->addTimer (tim);
  30865. }
  30866. static inline void remove (Timer* const tim) throw()
  30867. {
  30868. if (instance != 0)
  30869. {
  30870. const ScopedLock sl (instance->lock);
  30871. instance->removeTimer (tim);
  30872. }
  30873. }
  30874. static inline void resetCounter (Timer* const tim,
  30875. const int newCounter) throw()
  30876. {
  30877. if (instance != 0)
  30878. {
  30879. tim->countdownMs = newCounter;
  30880. tim->periodMs = newCounter;
  30881. if ((tim->next != 0 && tim->next->countdownMs < tim->countdownMs)
  30882. || (tim->previous != 0 && tim->previous->countdownMs > tim->countdownMs))
  30883. {
  30884. const ScopedLock sl (instance->lock);
  30885. instance->removeTimer (tim);
  30886. instance->addTimer (tim);
  30887. }
  30888. }
  30889. }
  30890. private:
  30891. friend class Timer;
  30892. static InternalTimerThread* instance;
  30893. static CriticalSection lock;
  30894. Timer* volatile firstTimer;
  30895. Atomic <int> callbackNeeded;
  30896. void addTimer (Timer* const t) throw()
  30897. {
  30898. #if JUCE_DEBUG
  30899. Timer* tt = firstTimer;
  30900. while (tt != 0)
  30901. {
  30902. // trying to add a timer that's already here - shouldn't get to this point,
  30903. // so if you get this assertion, let me know!
  30904. jassert (tt != t);
  30905. tt = tt->next;
  30906. }
  30907. jassert (t->previous == 0 && t->next == 0);
  30908. #endif
  30909. Timer* i = firstTimer;
  30910. if (i == 0 || i->countdownMs > t->countdownMs)
  30911. {
  30912. t->next = firstTimer;
  30913. firstTimer = t;
  30914. }
  30915. else
  30916. {
  30917. while (i->next != 0 && i->next->countdownMs <= t->countdownMs)
  30918. i = i->next;
  30919. jassert (i != 0);
  30920. t->next = i->next;
  30921. t->previous = i;
  30922. i->next = t;
  30923. }
  30924. if (t->next != 0)
  30925. t->next->previous = t;
  30926. jassert ((t->next == 0 || t->next->countdownMs >= t->countdownMs)
  30927. && (t->previous == 0 || t->previous->countdownMs <= t->countdownMs));
  30928. notify();
  30929. }
  30930. void removeTimer (Timer* const t) throw()
  30931. {
  30932. #if JUCE_DEBUG
  30933. Timer* tt = firstTimer;
  30934. bool found = false;
  30935. while (tt != 0)
  30936. {
  30937. if (tt == t)
  30938. {
  30939. found = true;
  30940. break;
  30941. }
  30942. tt = tt->next;
  30943. }
  30944. // trying to remove a timer that's not here - shouldn't get to this point,
  30945. // so if you get this assertion, let me know!
  30946. jassert (found);
  30947. #endif
  30948. if (t->previous != 0)
  30949. {
  30950. jassert (firstTimer != t);
  30951. t->previous->next = t->next;
  30952. }
  30953. else
  30954. {
  30955. jassert (firstTimer == t);
  30956. firstTimer = t->next;
  30957. }
  30958. if (t->next != 0)
  30959. t->next->previous = t->previous;
  30960. t->next = 0;
  30961. t->previous = 0;
  30962. }
  30963. void decrementAllCounters (const int numMillisecs) const
  30964. {
  30965. Timer* t = firstTimer;
  30966. while (t != 0)
  30967. {
  30968. t->countdownMs -= numMillisecs;
  30969. t = t->next;
  30970. }
  30971. }
  30972. void handleAsyncUpdate()
  30973. {
  30974. startThread (7);
  30975. }
  30976. InternalTimerThread (const InternalTimerThread&);
  30977. InternalTimerThread& operator= (const InternalTimerThread&);
  30978. };
  30979. InternalTimerThread* InternalTimerThread::instance = 0;
  30980. CriticalSection InternalTimerThread::lock;
  30981. void juce_callAnyTimersSynchronously()
  30982. {
  30983. InternalTimerThread::callAnyTimersSynchronously();
  30984. }
  30985. #if JUCE_DEBUG
  30986. static SortedSet <Timer*> activeTimers;
  30987. #endif
  30988. Timer::Timer() throw()
  30989. : countdownMs (0),
  30990. periodMs (0),
  30991. previous (0),
  30992. next (0)
  30993. {
  30994. #if JUCE_DEBUG
  30995. activeTimers.add (this);
  30996. #endif
  30997. }
  30998. Timer::Timer (const Timer&) throw()
  30999. : countdownMs (0),
  31000. periodMs (0),
  31001. previous (0),
  31002. next (0)
  31003. {
  31004. #if JUCE_DEBUG
  31005. activeTimers.add (this);
  31006. #endif
  31007. }
  31008. Timer::~Timer()
  31009. {
  31010. stopTimer();
  31011. #if JUCE_DEBUG
  31012. activeTimers.removeValue (this);
  31013. #endif
  31014. }
  31015. void Timer::startTimer (const int interval) throw()
  31016. {
  31017. const ScopedLock sl (InternalTimerThread::lock);
  31018. #if JUCE_DEBUG
  31019. // this isn't a valid object! Your timer might be a dangling pointer or something..
  31020. jassert (activeTimers.contains (this));
  31021. #endif
  31022. if (periodMs == 0)
  31023. {
  31024. countdownMs = interval;
  31025. periodMs = jmax (1, interval);
  31026. InternalTimerThread::add (this);
  31027. }
  31028. else
  31029. {
  31030. InternalTimerThread::resetCounter (this, interval);
  31031. }
  31032. }
  31033. void Timer::stopTimer() throw()
  31034. {
  31035. const ScopedLock sl (InternalTimerThread::lock);
  31036. #if JUCE_DEBUG
  31037. // this isn't a valid object! Your timer might be a dangling pointer or something..
  31038. jassert (activeTimers.contains (this));
  31039. #endif
  31040. if (periodMs > 0)
  31041. {
  31042. InternalTimerThread::remove (this);
  31043. periodMs = 0;
  31044. }
  31045. }
  31046. END_JUCE_NAMESPACE
  31047. /*** End of inlined file: juce_Timer.cpp ***/
  31048. #endif
  31049. #if JUCE_BUILD_GUI
  31050. /*** Start of inlined file: juce_Component.cpp ***/
  31051. BEGIN_JUCE_NAMESPACE
  31052. Component* Component::currentlyFocusedComponent = 0;
  31053. static Array <Component*> modalComponentStack, modalComponentReturnValueKeys;
  31054. static Array <int> modalReturnValues;
  31055. enum ComponentMessageNumbers
  31056. {
  31057. customCommandMessage = 0x7fff0001,
  31058. exitModalStateMessage = 0x7fff0002
  31059. };
  31060. #define checkMessageManagerIsLocked jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  31061. static uint32 nextComponentUID = 0;
  31062. Component::Component()
  31063. : parentComponent_ (0),
  31064. componentUID (++nextComponentUID),
  31065. numDeepMouseListeners (0),
  31066. lookAndFeel_ (0),
  31067. effect_ (0),
  31068. bufferedImage_ (0),
  31069. mouseListeners_ (0),
  31070. keyListeners_ (0),
  31071. componentFlags_ (0)
  31072. {
  31073. }
  31074. Component::Component (const String& name)
  31075. : componentName_ (name),
  31076. parentComponent_ (0),
  31077. componentUID (++nextComponentUID),
  31078. numDeepMouseListeners (0),
  31079. lookAndFeel_ (0),
  31080. effect_ (0),
  31081. bufferedImage_ (0),
  31082. mouseListeners_ (0),
  31083. keyListeners_ (0),
  31084. componentFlags_ (0)
  31085. {
  31086. }
  31087. Component::~Component()
  31088. {
  31089. componentListeners.call (&ComponentListener::componentBeingDeleted, *this);
  31090. if (parentComponent_ != 0)
  31091. {
  31092. parentComponent_->removeChildComponent (this);
  31093. }
  31094. else if ((currentlyFocusedComponent == this)
  31095. || isParentOf (currentlyFocusedComponent))
  31096. {
  31097. giveAwayFocus();
  31098. }
  31099. if (flags.hasHeavyweightPeerFlag)
  31100. removeFromDesktop();
  31101. modalComponentStack.removeValue (this);
  31102. for (int i = childComponentList_.size(); --i >= 0;)
  31103. childComponentList_.getUnchecked(i)->parentComponent_ = 0;
  31104. delete mouseListeners_;
  31105. delete keyListeners_;
  31106. }
  31107. void Component::setName (const String& name)
  31108. {
  31109. // if component methods are being called from threads other than the message
  31110. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31111. checkMessageManagerIsLocked
  31112. if (componentName_ != name)
  31113. {
  31114. componentName_ = name;
  31115. if (flags.hasHeavyweightPeerFlag)
  31116. {
  31117. ComponentPeer* const peer = getPeer();
  31118. jassert (peer != 0);
  31119. if (peer != 0)
  31120. peer->setTitle (name);
  31121. }
  31122. BailOutChecker checker (this);
  31123. componentListeners.callChecked (checker, &ComponentListener::componentNameChanged, *this);
  31124. }
  31125. }
  31126. void Component::setVisible (bool shouldBeVisible)
  31127. {
  31128. if (flags.visibleFlag != shouldBeVisible)
  31129. {
  31130. // if component methods are being called from threads other than the message
  31131. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31132. checkMessageManagerIsLocked
  31133. SafePointer<Component> safePointer (this);
  31134. flags.visibleFlag = shouldBeVisible;
  31135. internalRepaint (0, 0, getWidth(), getHeight());
  31136. sendFakeMouseMove();
  31137. if (! shouldBeVisible)
  31138. {
  31139. if (currentlyFocusedComponent == this
  31140. || isParentOf (currentlyFocusedComponent))
  31141. {
  31142. if (parentComponent_ != 0)
  31143. parentComponent_->grabKeyboardFocus();
  31144. else
  31145. giveAwayFocus();
  31146. }
  31147. }
  31148. if (safePointer != 0)
  31149. {
  31150. sendVisibilityChangeMessage();
  31151. if (safePointer != 0 && flags.hasHeavyweightPeerFlag)
  31152. {
  31153. ComponentPeer* const peer = getPeer();
  31154. jassert (peer != 0);
  31155. if (peer != 0)
  31156. {
  31157. peer->setVisible (shouldBeVisible);
  31158. internalHierarchyChanged();
  31159. }
  31160. }
  31161. }
  31162. }
  31163. }
  31164. void Component::visibilityChanged()
  31165. {
  31166. }
  31167. void Component::sendVisibilityChangeMessage()
  31168. {
  31169. BailOutChecker checker (this);
  31170. visibilityChanged();
  31171. if (! checker.shouldBailOut())
  31172. componentListeners.callChecked (checker, &ComponentListener::componentVisibilityChanged, *this);
  31173. }
  31174. bool Component::isShowing() const
  31175. {
  31176. if (flags.visibleFlag)
  31177. {
  31178. if (parentComponent_ != 0)
  31179. {
  31180. return parentComponent_->isShowing();
  31181. }
  31182. else
  31183. {
  31184. const ComponentPeer* const peer = getPeer();
  31185. return peer != 0 && ! peer->isMinimised();
  31186. }
  31187. }
  31188. return false;
  31189. }
  31190. class FadeOutProxyComponent : public Component,
  31191. public Timer
  31192. {
  31193. public:
  31194. FadeOutProxyComponent (Component* comp,
  31195. const int fadeLengthMs,
  31196. const int deltaXToMove,
  31197. const int deltaYToMove,
  31198. const float scaleFactorAtEnd)
  31199. : lastTime (0),
  31200. alpha (1.0f),
  31201. scale (1.0f)
  31202. {
  31203. image = comp->createComponentSnapshot (comp->getLocalBounds());
  31204. setBounds (comp->getBounds());
  31205. comp->getParentComponent()->addAndMakeVisible (this);
  31206. toBehind (comp);
  31207. alphaChangePerMs = -1.0f / (float)fadeLengthMs;
  31208. centreX = comp->getX() + comp->getWidth() * 0.5f;
  31209. xChangePerMs = deltaXToMove / (float)fadeLengthMs;
  31210. centreY = comp->getY() + comp->getHeight() * 0.5f;
  31211. yChangePerMs = deltaYToMove / (float)fadeLengthMs;
  31212. scaleChangePerMs = (scaleFactorAtEnd - 1.0f) / (float)fadeLengthMs;
  31213. setInterceptsMouseClicks (false, false);
  31214. // 30 fps is enough for a fade, but we need a higher rate if it's moving as well..
  31215. startTimer (1000 / ((deltaXToMove == 0 && deltaYToMove == 0) ? 30 : 50));
  31216. }
  31217. ~FadeOutProxyComponent()
  31218. {
  31219. }
  31220. void paint (Graphics& g)
  31221. {
  31222. g.setOpacity (alpha);
  31223. g.drawImage (image,
  31224. 0, 0, getWidth(), getHeight(),
  31225. 0, 0, image.getWidth(), image.getHeight());
  31226. }
  31227. void timerCallback()
  31228. {
  31229. const uint32 now = Time::getMillisecondCounter();
  31230. if (lastTime == 0)
  31231. lastTime = now;
  31232. const int msPassed = (now > lastTime) ? now - lastTime : 0;
  31233. lastTime = now;
  31234. alpha += alphaChangePerMs * msPassed;
  31235. if (alpha > 0)
  31236. {
  31237. if (xChangePerMs != 0.0f || yChangePerMs != 0.0f || scaleChangePerMs != 0.0f)
  31238. {
  31239. centreX += xChangePerMs * msPassed;
  31240. centreY += yChangePerMs * msPassed;
  31241. scale += scaleChangePerMs * msPassed;
  31242. const int w = roundToInt (image.getWidth() * scale);
  31243. const int h = roundToInt (image.getHeight() * scale);
  31244. setBounds (roundToInt (centreX) - w / 2,
  31245. roundToInt (centreY) - h / 2,
  31246. w, h);
  31247. }
  31248. repaint();
  31249. }
  31250. else
  31251. {
  31252. delete this;
  31253. }
  31254. }
  31255. juce_UseDebuggingNewOperator
  31256. private:
  31257. Image image;
  31258. uint32 lastTime;
  31259. float alpha, alphaChangePerMs;
  31260. float centreX, xChangePerMs;
  31261. float centreY, yChangePerMs;
  31262. float scale, scaleChangePerMs;
  31263. FadeOutProxyComponent (const FadeOutProxyComponent&);
  31264. FadeOutProxyComponent& operator= (const FadeOutProxyComponent&);
  31265. };
  31266. void Component::fadeOutComponent (const int millisecondsToFade,
  31267. const int deltaXToMove,
  31268. const int deltaYToMove,
  31269. const float scaleFactorAtEnd)
  31270. {
  31271. //xxx won't work for comps without parents
  31272. if (isShowing() && millisecondsToFade > 0)
  31273. new FadeOutProxyComponent (this, millisecondsToFade,
  31274. deltaXToMove, deltaYToMove, scaleFactorAtEnd);
  31275. setVisible (false);
  31276. }
  31277. bool Component::isValidComponent() const
  31278. {
  31279. return (this != 0) && isValidMessageListener();
  31280. }
  31281. void* Component::getWindowHandle() const
  31282. {
  31283. const ComponentPeer* const peer = getPeer();
  31284. if (peer != 0)
  31285. return peer->getNativeHandle();
  31286. return 0;
  31287. }
  31288. void Component::addToDesktop (int styleWanted, void* nativeWindowToAttachTo)
  31289. {
  31290. // if component methods are being called from threads other than the message
  31291. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31292. checkMessageManagerIsLocked
  31293. if (isOpaque())
  31294. styleWanted &= ~ComponentPeer::windowIsSemiTransparent;
  31295. else
  31296. styleWanted |= ComponentPeer::windowIsSemiTransparent;
  31297. int currentStyleFlags = 0;
  31298. // don't use getPeer(), so that we only get the peer that's specifically
  31299. // for this comp, and not for one of its parents.
  31300. ComponentPeer* peer = ComponentPeer::getPeerFor (this);
  31301. if (peer != 0)
  31302. currentStyleFlags = peer->getStyleFlags();
  31303. if (styleWanted != currentStyleFlags || ! flags.hasHeavyweightPeerFlag)
  31304. {
  31305. SafePointer<Component> safePointer (this);
  31306. #if JUCE_LINUX
  31307. // it's wise to give the component a non-zero size before
  31308. // putting it on the desktop, as X windows get confused by this, and
  31309. // a (1, 1) minimum size is enforced here.
  31310. setSize (jmax (1, getWidth()),
  31311. jmax (1, getHeight()));
  31312. #endif
  31313. const Point<int> topLeft (relativePositionToGlobal (Point<int> (0, 0)));
  31314. bool wasFullscreen = false;
  31315. bool wasMinimised = false;
  31316. ComponentBoundsConstrainer* currentConstainer = 0;
  31317. Rectangle<int> oldNonFullScreenBounds;
  31318. if (peer != 0)
  31319. {
  31320. wasFullscreen = peer->isFullScreen();
  31321. wasMinimised = peer->isMinimised();
  31322. currentConstainer = peer->getConstrainer();
  31323. oldNonFullScreenBounds = peer->getNonFullScreenBounds();
  31324. removeFromDesktop();
  31325. setTopLeftPosition (topLeft.getX(), topLeft.getY());
  31326. }
  31327. if (parentComponent_ != 0)
  31328. parentComponent_->removeChildComponent (this);
  31329. if (safePointer != 0)
  31330. {
  31331. flags.hasHeavyweightPeerFlag = true;
  31332. peer = createNewPeer (styleWanted, nativeWindowToAttachTo);
  31333. Desktop::getInstance().addDesktopComponent (this);
  31334. bounds_.setPosition (topLeft);
  31335. peer->setBounds (topLeft.getX(), topLeft.getY(), getWidth(), getHeight(), false);
  31336. peer->setVisible (isVisible());
  31337. if (wasFullscreen)
  31338. {
  31339. peer->setFullScreen (true);
  31340. peer->setNonFullScreenBounds (oldNonFullScreenBounds);
  31341. }
  31342. if (wasMinimised)
  31343. peer->setMinimised (true);
  31344. if (isAlwaysOnTop())
  31345. peer->setAlwaysOnTop (true);
  31346. peer->setConstrainer (currentConstainer);
  31347. repaint();
  31348. }
  31349. internalHierarchyChanged();
  31350. }
  31351. }
  31352. void Component::removeFromDesktop()
  31353. {
  31354. // if component methods are being called from threads other than the message
  31355. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31356. checkMessageManagerIsLocked
  31357. if (flags.hasHeavyweightPeerFlag)
  31358. {
  31359. ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  31360. flags.hasHeavyweightPeerFlag = false;
  31361. jassert (peer != 0);
  31362. delete peer;
  31363. Desktop::getInstance().removeDesktopComponent (this);
  31364. }
  31365. }
  31366. bool Component::isOnDesktop() const throw()
  31367. {
  31368. return flags.hasHeavyweightPeerFlag;
  31369. }
  31370. void Component::userTriedToCloseWindow()
  31371. {
  31372. /* This means that the user's trying to get rid of your window with the 'close window' system
  31373. menu option (on windows) or possibly the task manager - you should really handle this
  31374. and delete or hide your component in an appropriate way.
  31375. If you want to ignore the event and don't want to trigger this assertion, just override
  31376. this method and do nothing.
  31377. */
  31378. jassertfalse;
  31379. }
  31380. void Component::minimisationStateChanged (bool)
  31381. {
  31382. }
  31383. void Component::setOpaque (const bool shouldBeOpaque)
  31384. {
  31385. if (shouldBeOpaque != flags.opaqueFlag)
  31386. {
  31387. flags.opaqueFlag = shouldBeOpaque;
  31388. if (flags.hasHeavyweightPeerFlag)
  31389. {
  31390. const ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  31391. if (peer != 0)
  31392. {
  31393. // to make it recreate the heavyweight window
  31394. addToDesktop (peer->getStyleFlags());
  31395. }
  31396. }
  31397. repaint();
  31398. }
  31399. }
  31400. bool Component::isOpaque() const throw()
  31401. {
  31402. return flags.opaqueFlag;
  31403. }
  31404. void Component::setBufferedToImage (const bool shouldBeBuffered)
  31405. {
  31406. if (shouldBeBuffered != flags.bufferToImageFlag)
  31407. {
  31408. bufferedImage_ = Image();
  31409. flags.bufferToImageFlag = shouldBeBuffered;
  31410. }
  31411. }
  31412. void Component::toFront (const bool setAsForeground)
  31413. {
  31414. // if component methods are being called from threads other than the message
  31415. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31416. checkMessageManagerIsLocked
  31417. if (flags.hasHeavyweightPeerFlag)
  31418. {
  31419. ComponentPeer* const peer = getPeer();
  31420. if (peer != 0)
  31421. {
  31422. peer->toFront (setAsForeground);
  31423. if (setAsForeground && ! hasKeyboardFocus (true))
  31424. grabKeyboardFocus();
  31425. }
  31426. }
  31427. else if (parentComponent_ != 0)
  31428. {
  31429. Array<Component*>& childList = parentComponent_->childComponentList_;
  31430. if (childList.getLast() != this)
  31431. {
  31432. const int index = childList.indexOf (this);
  31433. if (index >= 0)
  31434. {
  31435. int insertIndex = -1;
  31436. if (! flags.alwaysOnTopFlag)
  31437. {
  31438. insertIndex = childList.size() - 1;
  31439. while (insertIndex > 0 && childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  31440. --insertIndex;
  31441. }
  31442. if (index != insertIndex)
  31443. {
  31444. childList.move (index, insertIndex);
  31445. sendFakeMouseMove();
  31446. repaintParent();
  31447. }
  31448. }
  31449. }
  31450. if (setAsForeground)
  31451. {
  31452. internalBroughtToFront();
  31453. grabKeyboardFocus();
  31454. }
  31455. }
  31456. }
  31457. void Component::toBehind (Component* const other)
  31458. {
  31459. if (other != 0 && other != this)
  31460. {
  31461. // the two components must belong to the same parent..
  31462. jassert (parentComponent_ == other->parentComponent_);
  31463. if (parentComponent_ != 0)
  31464. {
  31465. Array<Component*>& childList = parentComponent_->childComponentList_;
  31466. const int index = childList.indexOf (this);
  31467. if (index >= 0 && childList [index + 1] != other)
  31468. {
  31469. int otherIndex = childList.indexOf (other);
  31470. if (otherIndex >= 0)
  31471. {
  31472. if (index < otherIndex)
  31473. --otherIndex;
  31474. childList.move (index, otherIndex);
  31475. sendFakeMouseMove();
  31476. repaintParent();
  31477. }
  31478. }
  31479. }
  31480. else if (isOnDesktop())
  31481. {
  31482. jassert (other->isOnDesktop());
  31483. if (other->isOnDesktop())
  31484. {
  31485. ComponentPeer* const us = getPeer();
  31486. ComponentPeer* const them = other->getPeer();
  31487. jassert (us != 0 && them != 0);
  31488. if (us != 0 && them != 0)
  31489. us->toBehind (them);
  31490. }
  31491. }
  31492. }
  31493. }
  31494. void Component::toBack()
  31495. {
  31496. Array<Component*>& childList = parentComponent_->childComponentList_;
  31497. if (isOnDesktop())
  31498. {
  31499. jassertfalse; //xxx need to add this to native window
  31500. }
  31501. else if (parentComponent_ != 0 && childList.getFirst() != this)
  31502. {
  31503. const int index = childList.indexOf (this);
  31504. if (index > 0)
  31505. {
  31506. int insertIndex = 0;
  31507. if (flags.alwaysOnTopFlag)
  31508. {
  31509. while (insertIndex < childList.size()
  31510. && ! childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  31511. {
  31512. ++insertIndex;
  31513. }
  31514. }
  31515. if (index != insertIndex)
  31516. {
  31517. childList.move (index, insertIndex);
  31518. sendFakeMouseMove();
  31519. repaintParent();
  31520. }
  31521. }
  31522. }
  31523. }
  31524. void Component::setAlwaysOnTop (const bool shouldStayOnTop)
  31525. {
  31526. if (shouldStayOnTop != flags.alwaysOnTopFlag)
  31527. {
  31528. flags.alwaysOnTopFlag = shouldStayOnTop;
  31529. if (isOnDesktop())
  31530. {
  31531. ComponentPeer* const peer = getPeer();
  31532. jassert (peer != 0);
  31533. if (peer != 0)
  31534. {
  31535. if (! peer->setAlwaysOnTop (shouldStayOnTop))
  31536. {
  31537. // some kinds of peer can't change their always-on-top status, so
  31538. // for these, we'll need to create a new window
  31539. const int oldFlags = peer->getStyleFlags();
  31540. removeFromDesktop();
  31541. addToDesktop (oldFlags);
  31542. }
  31543. }
  31544. }
  31545. if (shouldStayOnTop)
  31546. toFront (false);
  31547. internalHierarchyChanged();
  31548. }
  31549. }
  31550. bool Component::isAlwaysOnTop() const throw()
  31551. {
  31552. return flags.alwaysOnTopFlag;
  31553. }
  31554. int Component::proportionOfWidth (const float proportion) const throw()
  31555. {
  31556. return roundToInt (proportion * bounds_.getWidth());
  31557. }
  31558. int Component::proportionOfHeight (const float proportion) const throw()
  31559. {
  31560. return roundToInt (proportion * bounds_.getHeight());
  31561. }
  31562. int Component::getParentWidth() const throw()
  31563. {
  31564. return (parentComponent_ != 0) ? parentComponent_->getWidth()
  31565. : getParentMonitorArea().getWidth();
  31566. }
  31567. int Component::getParentHeight() const throw()
  31568. {
  31569. return (parentComponent_ != 0) ? parentComponent_->getHeight()
  31570. : getParentMonitorArea().getHeight();
  31571. }
  31572. int Component::getScreenX() const
  31573. {
  31574. return getScreenPosition().getX();
  31575. }
  31576. int Component::getScreenY() const
  31577. {
  31578. return getScreenPosition().getY();
  31579. }
  31580. const Point<int> Component::getScreenPosition() const
  31581. {
  31582. return (parentComponent_ != 0) ? parentComponent_->getScreenPosition() + getPosition()
  31583. : (flags.hasHeavyweightPeerFlag ? getPeer()->getScreenPosition()
  31584. : getPosition());
  31585. }
  31586. const Rectangle<int> Component::getScreenBounds() const
  31587. {
  31588. return bounds_.withPosition (getScreenPosition());
  31589. }
  31590. const Point<int> Component::relativePositionToGlobal (const Point<int>& relativePosition) const
  31591. {
  31592. const Component* c = this;
  31593. Point<int> p (relativePosition);
  31594. do
  31595. {
  31596. if (c->flags.hasHeavyweightPeerFlag)
  31597. return c->getPeer()->relativePositionToGlobal (p);
  31598. p += c->getPosition();
  31599. c = c->parentComponent_;
  31600. }
  31601. while (c != 0);
  31602. return p;
  31603. }
  31604. const Point<int> Component::globalPositionToRelative (const Point<int>& screenPosition) const
  31605. {
  31606. if (flags.hasHeavyweightPeerFlag)
  31607. {
  31608. return getPeer()->globalPositionToRelative (screenPosition);
  31609. }
  31610. else
  31611. {
  31612. if (parentComponent_ != 0)
  31613. return parentComponent_->globalPositionToRelative (screenPosition) - getPosition();
  31614. return screenPosition - getPosition();
  31615. }
  31616. }
  31617. const Point<int> Component::relativePositionToOtherComponent (const Component* const targetComponent, const Point<int>& positionRelativeToThis) const
  31618. {
  31619. Point<int> p (positionRelativeToThis);
  31620. if (targetComponent != 0)
  31621. {
  31622. const Component* c = this;
  31623. do
  31624. {
  31625. if (c == targetComponent)
  31626. return p;
  31627. if (c->flags.hasHeavyweightPeerFlag)
  31628. {
  31629. p = c->getPeer()->relativePositionToGlobal (p);
  31630. break;
  31631. }
  31632. p += c->getPosition();
  31633. c = c->parentComponent_;
  31634. }
  31635. while (c != 0);
  31636. p = targetComponent->globalPositionToRelative (p);
  31637. }
  31638. return p;
  31639. }
  31640. void Component::setBounds (int x, int y, int w, int h)
  31641. {
  31642. // if component methods are being called from threads other than the message
  31643. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31644. checkMessageManagerIsLocked
  31645. if (w < 0) w = 0;
  31646. if (h < 0) h = 0;
  31647. const bool wasResized = (getWidth() != w || getHeight() != h);
  31648. const bool wasMoved = (getX() != x || getY() != y);
  31649. #if JUCE_DEBUG
  31650. // It's a very bad idea to try to resize a window during its paint() method!
  31651. jassert (! (flags.isInsidePaintCall && wasResized && isOnDesktop()));
  31652. #endif
  31653. if (wasMoved || wasResized)
  31654. {
  31655. if (flags.visibleFlag)
  31656. {
  31657. // send a fake mouse move to trigger enter/exit messages if needed..
  31658. sendFakeMouseMove();
  31659. if (! flags.hasHeavyweightPeerFlag)
  31660. repaintParent();
  31661. }
  31662. bounds_.setBounds (x, y, w, h);
  31663. if (wasResized)
  31664. repaint();
  31665. else if (! flags.hasHeavyweightPeerFlag)
  31666. repaintParent();
  31667. if (flags.hasHeavyweightPeerFlag)
  31668. {
  31669. ComponentPeer* const peer = getPeer();
  31670. if (peer != 0)
  31671. {
  31672. if (wasMoved && wasResized)
  31673. peer->setBounds (getX(), getY(), getWidth(), getHeight(), false);
  31674. else if (wasMoved)
  31675. peer->setPosition (getX(), getY());
  31676. else if (wasResized)
  31677. peer->setSize (getWidth(), getHeight());
  31678. }
  31679. }
  31680. sendMovedResizedMessages (wasMoved, wasResized);
  31681. }
  31682. }
  31683. void Component::sendMovedResizedMessages (const bool wasMoved, const bool wasResized)
  31684. {
  31685. JUCE_TRY
  31686. {
  31687. if (wasMoved)
  31688. moved();
  31689. if (wasResized)
  31690. {
  31691. resized();
  31692. for (int i = childComponentList_.size(); --i >= 0;)
  31693. {
  31694. childComponentList_.getUnchecked(i)->parentSizeChanged();
  31695. i = jmin (i, childComponentList_.size());
  31696. }
  31697. }
  31698. BailOutChecker checker (this);
  31699. if (parentComponent_ != 0)
  31700. parentComponent_->childBoundsChanged (this);
  31701. if (! checker.shouldBailOut())
  31702. componentListeners.callChecked (checker, &ComponentListener::componentMovedOrResized,
  31703. *this, wasMoved, wasResized);
  31704. }
  31705. JUCE_CATCH_EXCEPTION
  31706. }
  31707. void Component::setSize (const int w, const int h)
  31708. {
  31709. setBounds (getX(), getY(), w, h);
  31710. }
  31711. void Component::setTopLeftPosition (const int x, const int y)
  31712. {
  31713. setBounds (x, y, getWidth(), getHeight());
  31714. }
  31715. void Component::setTopRightPosition (const int x, const int y)
  31716. {
  31717. setTopLeftPosition (x - getWidth(), y);
  31718. }
  31719. void Component::setBounds (const Rectangle<int>& r)
  31720. {
  31721. setBounds (r.getX(),
  31722. r.getY(),
  31723. r.getWidth(),
  31724. r.getHeight());
  31725. }
  31726. void Component::setBoundsRelative (const float x, const float y,
  31727. const float w, const float h)
  31728. {
  31729. const int pw = getParentWidth();
  31730. const int ph = getParentHeight();
  31731. setBounds (roundToInt (x * pw),
  31732. roundToInt (y * ph),
  31733. roundToInt (w * pw),
  31734. roundToInt (h * ph));
  31735. }
  31736. void Component::setCentrePosition (const int x, const int y)
  31737. {
  31738. setTopLeftPosition (x - getWidth() / 2,
  31739. y - getHeight() / 2);
  31740. }
  31741. void Component::setCentreRelative (const float x, const float y)
  31742. {
  31743. setCentrePosition (roundToInt (getParentWidth() * x),
  31744. roundToInt (getParentHeight() * y));
  31745. }
  31746. void Component::centreWithSize (const int width, const int height)
  31747. {
  31748. setBounds ((getParentWidth() - width) / 2,
  31749. (getParentHeight() - height) / 2,
  31750. width,
  31751. height);
  31752. }
  31753. void Component::setBoundsInset (const BorderSize& borders)
  31754. {
  31755. setBounds (borders.getLeft(),
  31756. borders.getTop(),
  31757. getParentWidth() - (borders.getLeftAndRight()),
  31758. getParentHeight() - (borders.getTopAndBottom()));
  31759. }
  31760. void Component::setBoundsToFit (int x, int y, int width, int height,
  31761. const Justification& justification,
  31762. const bool onlyReduceInSize)
  31763. {
  31764. // it's no good calling this method unless both the component and
  31765. // target rectangle have a finite size.
  31766. jassert (getWidth() > 0 && getHeight() > 0 && width > 0 && height > 0);
  31767. if (getWidth() > 0 && getHeight() > 0
  31768. && width > 0 && height > 0)
  31769. {
  31770. int newW, newH;
  31771. if (onlyReduceInSize && getWidth() <= width && getHeight() <= height)
  31772. {
  31773. newW = getWidth();
  31774. newH = getHeight();
  31775. }
  31776. else
  31777. {
  31778. const double imageRatio = getHeight() / (double) getWidth();
  31779. const double targetRatio = height / (double) width;
  31780. if (imageRatio <= targetRatio)
  31781. {
  31782. newW = width;
  31783. newH = jmin (height, roundToInt (newW * imageRatio));
  31784. }
  31785. else
  31786. {
  31787. newH = height;
  31788. newW = jmin (width, roundToInt (newH / imageRatio));
  31789. }
  31790. }
  31791. if (newW > 0 && newH > 0)
  31792. {
  31793. int newX, newY;
  31794. justification.applyToRectangle (newX, newY, newW, newH,
  31795. x, y, width, height);
  31796. setBounds (newX, newY, newW, newH);
  31797. }
  31798. }
  31799. }
  31800. bool Component::hitTest (int x, int y)
  31801. {
  31802. if (! flags.ignoresMouseClicksFlag)
  31803. return true;
  31804. if (flags.allowChildMouseClicksFlag)
  31805. {
  31806. for (int i = getNumChildComponents(); --i >= 0;)
  31807. {
  31808. Component* const c = getChildComponent (i);
  31809. if (c->isVisible()
  31810. && c->bounds_.contains (x, y)
  31811. && c->hitTest (x - c->getX(),
  31812. y - c->getY()))
  31813. {
  31814. return true;
  31815. }
  31816. }
  31817. }
  31818. return false;
  31819. }
  31820. void Component::setInterceptsMouseClicks (const bool allowClicks,
  31821. const bool allowClicksOnChildComponents) throw()
  31822. {
  31823. flags.ignoresMouseClicksFlag = ! allowClicks;
  31824. flags.allowChildMouseClicksFlag = allowClicksOnChildComponents;
  31825. }
  31826. void Component::getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  31827. bool& allowsClicksOnChildComponents) const throw()
  31828. {
  31829. allowsClicksOnThisComponent = ! flags.ignoresMouseClicksFlag;
  31830. allowsClicksOnChildComponents = flags.allowChildMouseClicksFlag;
  31831. }
  31832. bool Component::contains (const int x, const int y)
  31833. {
  31834. if (((unsigned int) x) < (unsigned int) getWidth()
  31835. && ((unsigned int) y) < (unsigned int) getHeight()
  31836. && hitTest (x, y))
  31837. {
  31838. if (parentComponent_ != 0)
  31839. {
  31840. return parentComponent_->contains (x + getX(),
  31841. y + getY());
  31842. }
  31843. else if (flags.hasHeavyweightPeerFlag)
  31844. {
  31845. const ComponentPeer* const peer = getPeer();
  31846. if (peer != 0)
  31847. return peer->contains (Point<int> (x, y), true);
  31848. }
  31849. }
  31850. return false;
  31851. }
  31852. bool Component::reallyContains (int x, int y, const bool returnTrueIfWithinAChild)
  31853. {
  31854. if (! contains (x, y))
  31855. return false;
  31856. Component* p = this;
  31857. while (p->parentComponent_ != 0)
  31858. {
  31859. x += p->getX();
  31860. y += p->getY();
  31861. p = p->parentComponent_;
  31862. }
  31863. const Component* const c = p->getComponentAt (x, y);
  31864. return (c == this) || (returnTrueIfWithinAChild && isParentOf (c));
  31865. }
  31866. Component* Component::getComponentAt (const Point<int>& position)
  31867. {
  31868. return getComponentAt (position.getX(), position.getY());
  31869. }
  31870. Component* Component::getComponentAt (const int x, const int y)
  31871. {
  31872. if (flags.visibleFlag
  31873. && ((unsigned int) x) < (unsigned int) getWidth()
  31874. && ((unsigned int) y) < (unsigned int) getHeight()
  31875. && hitTest (x, y))
  31876. {
  31877. for (int i = childComponentList_.size(); --i >= 0;)
  31878. {
  31879. Component* const child = childComponentList_.getUnchecked(i);
  31880. Component* const c = child->getComponentAt (x - child->getX(),
  31881. y - child->getY());
  31882. if (c != 0)
  31883. return c;
  31884. }
  31885. return this;
  31886. }
  31887. return 0;
  31888. }
  31889. void Component::addChildComponent (Component* const child, int zOrder)
  31890. {
  31891. // if component methods are being called from threads other than the message
  31892. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31893. checkMessageManagerIsLocked
  31894. if (child != 0 && child->parentComponent_ != this)
  31895. {
  31896. if (child->parentComponent_ != 0)
  31897. child->parentComponent_->removeChildComponent (child);
  31898. else
  31899. child->removeFromDesktop();
  31900. child->parentComponent_ = this;
  31901. if (child->isVisible())
  31902. child->repaintParent();
  31903. if (! child->isAlwaysOnTop())
  31904. {
  31905. if (zOrder < 0 || zOrder > childComponentList_.size())
  31906. zOrder = childComponentList_.size();
  31907. while (zOrder > 0)
  31908. {
  31909. if (! childComponentList_.getUnchecked (zOrder - 1)->isAlwaysOnTop())
  31910. break;
  31911. --zOrder;
  31912. }
  31913. }
  31914. childComponentList_.insert (zOrder, child);
  31915. child->internalHierarchyChanged();
  31916. internalChildrenChanged();
  31917. }
  31918. }
  31919. void Component::addAndMakeVisible (Component* const child, int zOrder)
  31920. {
  31921. if (child != 0)
  31922. {
  31923. child->setVisible (true);
  31924. addChildComponent (child, zOrder);
  31925. }
  31926. }
  31927. void Component::removeChildComponent (Component* const child)
  31928. {
  31929. removeChildComponent (childComponentList_.indexOf (child));
  31930. }
  31931. Component* Component::removeChildComponent (const int index)
  31932. {
  31933. // if component methods are being called from threads other than the message
  31934. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31935. checkMessageManagerIsLocked
  31936. Component* const child = childComponentList_ [index];
  31937. if (child != 0)
  31938. {
  31939. sendFakeMouseMove();
  31940. child->repaintParent();
  31941. childComponentList_.remove (index);
  31942. child->parentComponent_ = 0;
  31943. JUCE_TRY
  31944. {
  31945. if ((currentlyFocusedComponent == child)
  31946. || child->isParentOf (currentlyFocusedComponent))
  31947. {
  31948. // get rid first to force the grabKeyboardFocus to change to us.
  31949. giveAwayFocus();
  31950. grabKeyboardFocus();
  31951. }
  31952. }
  31953. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  31954. catch (const std::exception& e)
  31955. {
  31956. currentlyFocusedComponent = 0;
  31957. Desktop::getInstance().triggerFocusCallback();
  31958. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  31959. }
  31960. catch (...)
  31961. {
  31962. currentlyFocusedComponent = 0;
  31963. Desktop::getInstance().triggerFocusCallback();
  31964. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  31965. }
  31966. #endif
  31967. child->internalHierarchyChanged();
  31968. internalChildrenChanged();
  31969. }
  31970. return child;
  31971. }
  31972. void Component::removeAllChildren()
  31973. {
  31974. while (childComponentList_.size() > 0)
  31975. removeChildComponent (childComponentList_.size() - 1);
  31976. }
  31977. void Component::deleteAllChildren()
  31978. {
  31979. while (childComponentList_.size() > 0)
  31980. delete (removeChildComponent (childComponentList_.size() - 1));
  31981. }
  31982. int Component::getNumChildComponents() const throw()
  31983. {
  31984. return childComponentList_.size();
  31985. }
  31986. Component* Component::getChildComponent (const int index) const throw()
  31987. {
  31988. return childComponentList_ [index];
  31989. }
  31990. int Component::getIndexOfChildComponent (const Component* const child) const throw()
  31991. {
  31992. return childComponentList_.indexOf (const_cast <Component*> (child));
  31993. }
  31994. Component* Component::getTopLevelComponent() const throw()
  31995. {
  31996. const Component* comp = this;
  31997. while (comp->parentComponent_ != 0)
  31998. comp = comp->parentComponent_;
  31999. return const_cast <Component*> (comp);
  32000. }
  32001. bool Component::isParentOf (const Component* possibleChild) const throw()
  32002. {
  32003. if (! possibleChild->isValidComponent())
  32004. {
  32005. jassert (possibleChild == 0);
  32006. return false;
  32007. }
  32008. while (possibleChild != 0)
  32009. {
  32010. possibleChild = possibleChild->parentComponent_;
  32011. if (possibleChild == this)
  32012. return true;
  32013. }
  32014. return false;
  32015. }
  32016. void Component::parentHierarchyChanged()
  32017. {
  32018. }
  32019. void Component::childrenChanged()
  32020. {
  32021. }
  32022. void Component::internalChildrenChanged()
  32023. {
  32024. if (componentListeners.isEmpty())
  32025. {
  32026. childrenChanged();
  32027. }
  32028. else
  32029. {
  32030. BailOutChecker checker (this);
  32031. childrenChanged();
  32032. if (! checker.shouldBailOut())
  32033. componentListeners.callChecked (checker, &ComponentListener::componentChildrenChanged, *this);
  32034. }
  32035. }
  32036. void Component::internalHierarchyChanged()
  32037. {
  32038. BailOutChecker checker (this);
  32039. parentHierarchyChanged();
  32040. if (checker.shouldBailOut())
  32041. return;
  32042. componentListeners.callChecked (checker, &ComponentListener::componentParentHierarchyChanged, *this);
  32043. if (checker.shouldBailOut())
  32044. return;
  32045. for (int i = childComponentList_.size(); --i >= 0;)
  32046. {
  32047. childComponentList_.getUnchecked (i)->internalHierarchyChanged();
  32048. if (checker.shouldBailOut())
  32049. {
  32050. // you really shouldn't delete the parent component during a callback telling you
  32051. // that it's changed..
  32052. jassertfalse;
  32053. return;
  32054. }
  32055. i = jmin (i, childComponentList_.size());
  32056. }
  32057. }
  32058. void* Component::runModalLoopCallback (void* userData)
  32059. {
  32060. return (void*) (pointer_sized_int) static_cast <Component*> (userData)->runModalLoop();
  32061. }
  32062. int Component::runModalLoop()
  32063. {
  32064. if (! MessageManager::getInstance()->isThisTheMessageThread())
  32065. {
  32066. // use a callback so this can be called from non-gui threads
  32067. return (int) (pointer_sized_int)
  32068. MessageManager::getInstance()
  32069. ->callFunctionOnMessageThread (&runModalLoopCallback, this);
  32070. }
  32071. SafePointer<Component> prevFocused (getCurrentlyFocusedComponent());
  32072. if (! isCurrentlyModal())
  32073. enterModalState();
  32074. JUCE_TRY
  32075. {
  32076. while (flags.currentlyModalFlag && flags.visibleFlag)
  32077. {
  32078. if (! MessageManager::getInstance()->runDispatchLoopUntil (20))
  32079. break;
  32080. // check whether this component was deleted during the last message
  32081. if (! isValidMessageListener())
  32082. break;
  32083. }
  32084. }
  32085. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  32086. catch (const std::exception& e)
  32087. {
  32088. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  32089. return 0;
  32090. }
  32091. catch (...)
  32092. {
  32093. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  32094. return 0;
  32095. }
  32096. #endif
  32097. const int modalIndex = modalComponentReturnValueKeys.indexOf (this);
  32098. int returnValue = 0;
  32099. if (modalIndex >= 0)
  32100. {
  32101. modalComponentReturnValueKeys.remove (modalIndex);
  32102. returnValue = modalReturnValues.remove (modalIndex);
  32103. }
  32104. modalComponentStack.removeValue (this);
  32105. if (prevFocused != 0)
  32106. prevFocused->grabKeyboardFocus();
  32107. return returnValue;
  32108. }
  32109. void Component::enterModalState (const bool takeKeyboardFocus_)
  32110. {
  32111. // if component methods are being called from threads other than the message
  32112. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32113. checkMessageManagerIsLocked
  32114. // Check for an attempt to make a component modal when it already is!
  32115. // This can cause nasty problems..
  32116. jassert (! flags.currentlyModalFlag);
  32117. if (! isCurrentlyModal())
  32118. {
  32119. modalComponentStack.add (this);
  32120. modalComponentReturnValueKeys.add (this);
  32121. modalReturnValues.add (0);
  32122. flags.currentlyModalFlag = true;
  32123. setVisible (true);
  32124. if (takeKeyboardFocus_)
  32125. grabKeyboardFocus();
  32126. }
  32127. }
  32128. void Component::exitModalState (const int returnValue)
  32129. {
  32130. if (isCurrentlyModal())
  32131. {
  32132. if (MessageManager::getInstance()->isThisTheMessageThread())
  32133. {
  32134. const int modalIndex = modalComponentReturnValueKeys.indexOf (this);
  32135. if (modalIndex >= 0)
  32136. {
  32137. modalReturnValues.set (modalIndex, returnValue);
  32138. }
  32139. else
  32140. {
  32141. modalComponentReturnValueKeys.add (this);
  32142. modalReturnValues.add (returnValue);
  32143. }
  32144. modalComponentStack.removeValue (this);
  32145. flags.currentlyModalFlag = false;
  32146. bringModalComponentToFront();
  32147. }
  32148. else
  32149. {
  32150. postMessage (new Message (exitModalStateMessage, returnValue, 0, 0));
  32151. }
  32152. }
  32153. }
  32154. bool Component::isCurrentlyModal() const throw()
  32155. {
  32156. return flags.currentlyModalFlag
  32157. && getCurrentlyModalComponent() == this;
  32158. }
  32159. bool Component::isCurrentlyBlockedByAnotherModalComponent() const
  32160. {
  32161. Component* const mc = getCurrentlyModalComponent();
  32162. return mc != 0
  32163. && mc != this
  32164. && (! mc->isParentOf (this))
  32165. && ! mc->canModalEventBeSentToComponent (this);
  32166. }
  32167. int JUCE_CALLTYPE Component::getNumCurrentlyModalComponents() throw()
  32168. {
  32169. return modalComponentStack.size();
  32170. }
  32171. Component* JUCE_CALLTYPE Component::getCurrentlyModalComponent (int index) throw()
  32172. {
  32173. Component* const c = static_cast <Component*> (modalComponentStack [modalComponentStack.size() - index - 1]);
  32174. return c->isValidComponent() ? c : 0;
  32175. }
  32176. void Component::bringModalComponentToFront()
  32177. {
  32178. ComponentPeer* lastOne = 0;
  32179. for (int i = 0; i < getNumCurrentlyModalComponents(); ++i)
  32180. {
  32181. Component* const c = getCurrentlyModalComponent (i);
  32182. if (c == 0)
  32183. break;
  32184. ComponentPeer* peer = c->getPeer();
  32185. if (peer != 0 && peer != lastOne)
  32186. {
  32187. if (lastOne == 0)
  32188. {
  32189. peer->toFront (true);
  32190. peer->grabFocus();
  32191. }
  32192. else
  32193. peer->toBehind (lastOne);
  32194. lastOne = peer;
  32195. }
  32196. }
  32197. }
  32198. void Component::setBroughtToFrontOnMouseClick (const bool shouldBeBroughtToFront) throw()
  32199. {
  32200. flags.bringToFrontOnClickFlag = shouldBeBroughtToFront;
  32201. }
  32202. bool Component::isBroughtToFrontOnMouseClick() const throw()
  32203. {
  32204. return flags.bringToFrontOnClickFlag;
  32205. }
  32206. void Component::setMouseCursor (const MouseCursor& cursor)
  32207. {
  32208. if (cursor_ != cursor)
  32209. {
  32210. cursor_ = cursor;
  32211. if (flags.visibleFlag)
  32212. updateMouseCursor();
  32213. }
  32214. }
  32215. const MouseCursor Component::getMouseCursor()
  32216. {
  32217. return cursor_;
  32218. }
  32219. void Component::updateMouseCursor() const
  32220. {
  32221. sendFakeMouseMove();
  32222. }
  32223. void Component::setRepaintsOnMouseActivity (const bool shouldRepaint) throw()
  32224. {
  32225. flags.repaintOnMouseActivityFlag = shouldRepaint;
  32226. }
  32227. void Component::repaintParent()
  32228. {
  32229. if (flags.visibleFlag)
  32230. internalRepaint (0, 0, getWidth(), getHeight());
  32231. }
  32232. void Component::repaint()
  32233. {
  32234. repaint (0, 0, getWidth(), getHeight());
  32235. }
  32236. void Component::repaint (const int x, const int y,
  32237. const int w, const int h)
  32238. {
  32239. bufferedImage_ = Image();
  32240. if (flags.visibleFlag)
  32241. internalRepaint (x, y, w, h);
  32242. }
  32243. void Component::repaint (const Rectangle<int>& area)
  32244. {
  32245. repaint (area.getX(), area.getY(), area.getWidth(), area.getHeight());
  32246. }
  32247. void Component::internalRepaint (int x, int y, int w, int h)
  32248. {
  32249. // if component methods are being called from threads other than the message
  32250. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32251. checkMessageManagerIsLocked
  32252. if (x < 0)
  32253. {
  32254. w += x;
  32255. x = 0;
  32256. }
  32257. if (x + w > getWidth())
  32258. w = getWidth() - x;
  32259. if (w > 0)
  32260. {
  32261. if (y < 0)
  32262. {
  32263. h += y;
  32264. y = 0;
  32265. }
  32266. if (y + h > getHeight())
  32267. h = getHeight() - y;
  32268. if (h > 0)
  32269. {
  32270. if (parentComponent_ != 0)
  32271. {
  32272. x += getX();
  32273. y += getY();
  32274. if (parentComponent_->flags.visibleFlag)
  32275. parentComponent_->internalRepaint (x, y, w, h);
  32276. }
  32277. else if (flags.hasHeavyweightPeerFlag)
  32278. {
  32279. ComponentPeer* const peer = getPeer();
  32280. if (peer != 0)
  32281. peer->repaint (Rectangle<int> (x, y, w, h));
  32282. }
  32283. }
  32284. }
  32285. }
  32286. void Component::renderComponent (Graphics& g)
  32287. {
  32288. const Rectangle<int> clipBounds (g.getClipBounds());
  32289. g.saveState();
  32290. clipObscuredRegions (g, clipBounds, 0, 0);
  32291. if (! g.isClipEmpty())
  32292. {
  32293. if (flags.bufferToImageFlag)
  32294. {
  32295. if (bufferedImage_.isNull())
  32296. {
  32297. bufferedImage_ = Image (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  32298. getWidth(), getHeight(), ! flags.opaqueFlag, Image::NativeImage);
  32299. Graphics imG (bufferedImage_);
  32300. paint (imG);
  32301. }
  32302. g.setColour (Colours::black);
  32303. g.drawImageAt (bufferedImage_, 0, 0);
  32304. }
  32305. else
  32306. {
  32307. paint (g);
  32308. }
  32309. }
  32310. g.restoreState();
  32311. for (int i = 0; i < childComponentList_.size(); ++i)
  32312. {
  32313. Component* const child = childComponentList_.getUnchecked (i);
  32314. if (child->isVisible() && clipBounds.intersects (child->getBounds()))
  32315. {
  32316. g.saveState();
  32317. if (g.reduceClipRegion (child->getX(), child->getY(),
  32318. child->getWidth(), child->getHeight()))
  32319. {
  32320. for (int j = i + 1; j < childComponentList_.size(); ++j)
  32321. {
  32322. const Component* const sibling = childComponentList_.getUnchecked (j);
  32323. if (sibling->flags.opaqueFlag && sibling->isVisible())
  32324. g.excludeClipRegion (sibling->getBounds());
  32325. }
  32326. if (! g.isClipEmpty())
  32327. {
  32328. g.setOrigin (child->getX(), child->getY());
  32329. child->paintEntireComponent (g);
  32330. }
  32331. }
  32332. g.restoreState();
  32333. }
  32334. }
  32335. g.saveState();
  32336. paintOverChildren (g);
  32337. g.restoreState();
  32338. }
  32339. void Component::paintEntireComponent (Graphics& g)
  32340. {
  32341. jassert (! g.isClipEmpty());
  32342. #if JUCE_DEBUG
  32343. flags.isInsidePaintCall = true;
  32344. #endif
  32345. if (effect_ != 0)
  32346. {
  32347. Image effectImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  32348. getWidth(), getHeight(),
  32349. ! flags.opaqueFlag, Image::NativeImage);
  32350. {
  32351. Graphics g2 (effectImage);
  32352. renderComponent (g2);
  32353. }
  32354. effect_->applyEffect (effectImage, g);
  32355. }
  32356. else
  32357. {
  32358. renderComponent (g);
  32359. }
  32360. #if JUCE_DEBUG
  32361. flags.isInsidePaintCall = false;
  32362. #endif
  32363. }
  32364. const Image Component::createComponentSnapshot (const Rectangle<int>& areaToGrab,
  32365. const bool clipImageToComponentBounds)
  32366. {
  32367. Rectangle<int> r (areaToGrab);
  32368. if (clipImageToComponentBounds)
  32369. r = r.getIntersection (getLocalBounds());
  32370. Image componentImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  32371. jmax (1, r.getWidth()),
  32372. jmax (1, r.getHeight()),
  32373. true);
  32374. Graphics imageContext (componentImage);
  32375. imageContext.setOrigin (-r.getX(), -r.getY());
  32376. paintEntireComponent (imageContext);
  32377. return componentImage;
  32378. }
  32379. void Component::setComponentEffect (ImageEffectFilter* const effect)
  32380. {
  32381. if (effect_ != effect)
  32382. {
  32383. effect_ = effect;
  32384. repaint();
  32385. }
  32386. }
  32387. LookAndFeel& Component::getLookAndFeel() const throw()
  32388. {
  32389. const Component* c = this;
  32390. do
  32391. {
  32392. if (c->lookAndFeel_ != 0)
  32393. return *(c->lookAndFeel_);
  32394. c = c->parentComponent_;
  32395. }
  32396. while (c != 0);
  32397. return LookAndFeel::getDefaultLookAndFeel();
  32398. }
  32399. void Component::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  32400. {
  32401. if (lookAndFeel_ != newLookAndFeel)
  32402. {
  32403. lookAndFeel_ = newLookAndFeel;
  32404. sendLookAndFeelChange();
  32405. }
  32406. }
  32407. void Component::lookAndFeelChanged()
  32408. {
  32409. }
  32410. void Component::sendLookAndFeelChange()
  32411. {
  32412. repaint();
  32413. lookAndFeelChanged();
  32414. // (it's not a great idea to do anything that would delete this component
  32415. // during the lookAndFeelChanged() callback)
  32416. jassert (isValidComponent());
  32417. SafePointer<Component> safePointer (this);
  32418. for (int i = childComponentList_.size(); --i >= 0;)
  32419. {
  32420. childComponentList_.getUnchecked (i)->sendLookAndFeelChange();
  32421. if (safePointer == 0)
  32422. return;
  32423. i = jmin (i, childComponentList_.size());
  32424. }
  32425. }
  32426. static const Identifier getColourPropertyId (const int colourId)
  32427. {
  32428. String s;
  32429. s.preallocateStorage (18);
  32430. s << "jcclr_" << String::toHexString (colourId);
  32431. return s;
  32432. }
  32433. const Colour Component::findColour (const int colourId, const bool inheritFromParent) const
  32434. {
  32435. var* v = properties.getItem (getColourPropertyId (colourId));
  32436. if (v != 0)
  32437. return Colour ((int) *v);
  32438. if (inheritFromParent && parentComponent_ != 0)
  32439. return parentComponent_->findColour (colourId, true);
  32440. return getLookAndFeel().findColour (colourId);
  32441. }
  32442. bool Component::isColourSpecified (const int colourId) const
  32443. {
  32444. return properties.contains (getColourPropertyId (colourId));
  32445. }
  32446. void Component::removeColour (const int colourId)
  32447. {
  32448. if (properties.remove (getColourPropertyId (colourId)))
  32449. colourChanged();
  32450. }
  32451. void Component::setColour (const int colourId, const Colour& colour)
  32452. {
  32453. if (properties.set (getColourPropertyId (colourId), (int) colour.getARGB()))
  32454. colourChanged();
  32455. }
  32456. void Component::copyAllExplicitColoursTo (Component& target) const
  32457. {
  32458. bool changed = false;
  32459. for (int i = properties.size(); --i >= 0;)
  32460. {
  32461. const Identifier name (properties.getName(i));
  32462. if (name.toString().startsWith ("jcclr_"))
  32463. if (target.properties.set (name, properties [name]))
  32464. changed = true;
  32465. }
  32466. if (changed)
  32467. target.colourChanged();
  32468. }
  32469. void Component::colourChanged()
  32470. {
  32471. }
  32472. const Rectangle<int> Component::getLocalBounds() const throw()
  32473. {
  32474. return Rectangle<int> (0, 0, getWidth(), getHeight());
  32475. }
  32476. const Rectangle<int> Component::getUnclippedArea() const
  32477. {
  32478. int x = 0, y = 0, w = getWidth(), h = getHeight();
  32479. Component* p = parentComponent_;
  32480. int px = getX();
  32481. int py = getY();
  32482. while (p != 0)
  32483. {
  32484. if (! Rectangle<int>::intersectRectangles (x, y, w, h, -px, -py, p->getWidth(), p->getHeight()))
  32485. return Rectangle<int>();
  32486. px += p->getX();
  32487. py += p->getY();
  32488. p = p->parentComponent_;
  32489. }
  32490. return Rectangle<int> (x, y, w, h);
  32491. }
  32492. void Component::clipObscuredRegions (Graphics& g, const Rectangle<int>& clipRect,
  32493. const int deltaX, const int deltaY) const
  32494. {
  32495. for (int i = childComponentList_.size(); --i >= 0;)
  32496. {
  32497. const Component* const c = childComponentList_.getUnchecked(i);
  32498. if (c->isVisible())
  32499. {
  32500. const Rectangle<int> newClip (clipRect.getIntersection (c->bounds_));
  32501. if (! newClip.isEmpty())
  32502. {
  32503. if (c->isOpaque())
  32504. {
  32505. g.excludeClipRegion (newClip.translated (deltaX, deltaY));
  32506. }
  32507. else
  32508. {
  32509. c->clipObscuredRegions (g, newClip.translated (-c->getX(), -c->getY()),
  32510. c->getX() + deltaX,
  32511. c->getY() + deltaY);
  32512. }
  32513. }
  32514. }
  32515. }
  32516. }
  32517. void Component::getVisibleArea (RectangleList& result, const bool includeSiblings) const
  32518. {
  32519. result.clear();
  32520. const Rectangle<int> unclipped (getUnclippedArea());
  32521. if (! unclipped.isEmpty())
  32522. {
  32523. result.add (unclipped);
  32524. if (includeSiblings)
  32525. {
  32526. const Component* const c = getTopLevelComponent();
  32527. c->subtractObscuredRegions (result, c->relativePositionToOtherComponent (this, Point<int>()),
  32528. c->getLocalBounds(), this);
  32529. }
  32530. subtractObscuredRegions (result, Point<int>(), unclipped, 0);
  32531. result.consolidate();
  32532. }
  32533. }
  32534. void Component::subtractObscuredRegions (RectangleList& result,
  32535. const Point<int>& delta,
  32536. const Rectangle<int>& clipRect,
  32537. const Component* const compToAvoid) const
  32538. {
  32539. for (int i = childComponentList_.size(); --i >= 0;)
  32540. {
  32541. const Component* const c = childComponentList_.getUnchecked(i);
  32542. if (c != compToAvoid && c->isVisible())
  32543. {
  32544. if (c->isOpaque())
  32545. {
  32546. Rectangle<int> childBounds (c->bounds_.getIntersection (clipRect));
  32547. childBounds.translate (delta.getX(), delta.getY());
  32548. result.subtract (childBounds);
  32549. }
  32550. else
  32551. {
  32552. Rectangle<int> newClip (clipRect.getIntersection (c->bounds_));
  32553. newClip.translate (-c->getX(), -c->getY());
  32554. c->subtractObscuredRegions (result, c->getPosition() + delta,
  32555. newClip, compToAvoid);
  32556. }
  32557. }
  32558. }
  32559. }
  32560. void Component::mouseEnter (const MouseEvent&)
  32561. {
  32562. // base class does nothing
  32563. }
  32564. void Component::mouseExit (const MouseEvent&)
  32565. {
  32566. // base class does nothing
  32567. }
  32568. void Component::mouseDown (const MouseEvent&)
  32569. {
  32570. // base class does nothing
  32571. }
  32572. void Component::mouseUp (const MouseEvent&)
  32573. {
  32574. // base class does nothing
  32575. }
  32576. void Component::mouseDrag (const MouseEvent&)
  32577. {
  32578. // base class does nothing
  32579. }
  32580. void Component::mouseMove (const MouseEvent&)
  32581. {
  32582. // base class does nothing
  32583. }
  32584. void Component::mouseDoubleClick (const MouseEvent&)
  32585. {
  32586. // base class does nothing
  32587. }
  32588. void Component::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  32589. {
  32590. // the base class just passes this event up to its parent..
  32591. if (parentComponent_ != 0)
  32592. parentComponent_->mouseWheelMove (e.getEventRelativeTo (parentComponent_),
  32593. wheelIncrementX, wheelIncrementY);
  32594. }
  32595. void Component::resized()
  32596. {
  32597. // base class does nothing
  32598. }
  32599. void Component::moved()
  32600. {
  32601. // base class does nothing
  32602. }
  32603. void Component::childBoundsChanged (Component*)
  32604. {
  32605. // base class does nothing
  32606. }
  32607. void Component::parentSizeChanged()
  32608. {
  32609. // base class does nothing
  32610. }
  32611. void Component::addComponentListener (ComponentListener* const newListener)
  32612. {
  32613. jassert (isValidComponent());
  32614. componentListeners.add (newListener);
  32615. }
  32616. void Component::removeComponentListener (ComponentListener* const listenerToRemove)
  32617. {
  32618. jassert (isValidComponent());
  32619. componentListeners.remove (listenerToRemove);
  32620. }
  32621. void Component::inputAttemptWhenModal()
  32622. {
  32623. bringModalComponentToFront();
  32624. getLookAndFeel().playAlertSound();
  32625. }
  32626. bool Component::canModalEventBeSentToComponent (const Component*)
  32627. {
  32628. return false;
  32629. }
  32630. void Component::internalModalInputAttempt()
  32631. {
  32632. Component* const current = getCurrentlyModalComponent();
  32633. if (current != 0)
  32634. current->inputAttemptWhenModal();
  32635. }
  32636. void Component::paint (Graphics&)
  32637. {
  32638. // all painting is done in the subclasses
  32639. jassert (! isOpaque()); // if your component's opaque, you've gotta paint it!
  32640. }
  32641. void Component::paintOverChildren (Graphics&)
  32642. {
  32643. // all painting is done in the subclasses
  32644. }
  32645. void Component::handleMessage (const Message& message)
  32646. {
  32647. if (message.intParameter1 == exitModalStateMessage)
  32648. {
  32649. exitModalState (message.intParameter2);
  32650. }
  32651. else if (message.intParameter1 == customCommandMessage)
  32652. {
  32653. handleCommandMessage (message.intParameter2);
  32654. }
  32655. }
  32656. void Component::postCommandMessage (const int commandId)
  32657. {
  32658. postMessage (new Message (customCommandMessage, commandId, 0, 0));
  32659. }
  32660. void Component::handleCommandMessage (int)
  32661. {
  32662. // used by subclasses
  32663. }
  32664. void Component::addMouseListener (MouseListener* const newListener,
  32665. const bool wantsEventsForAllNestedChildComponents)
  32666. {
  32667. // if component methods are being called from threads other than the message
  32668. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32669. checkMessageManagerIsLocked
  32670. if (mouseListeners_ == 0)
  32671. mouseListeners_ = new Array<MouseListener*>();
  32672. if (! mouseListeners_->contains (newListener))
  32673. {
  32674. if (wantsEventsForAllNestedChildComponents)
  32675. {
  32676. mouseListeners_->insert (0, newListener);
  32677. ++numDeepMouseListeners;
  32678. }
  32679. else
  32680. {
  32681. mouseListeners_->add (newListener);
  32682. }
  32683. }
  32684. }
  32685. void Component::removeMouseListener (MouseListener* const listenerToRemove)
  32686. {
  32687. // if component methods are being called from threads other than the message
  32688. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32689. checkMessageManagerIsLocked
  32690. if (mouseListeners_ != 0)
  32691. {
  32692. const int index = mouseListeners_->indexOf (listenerToRemove);
  32693. if (index >= 0)
  32694. {
  32695. if (index < numDeepMouseListeners)
  32696. --numDeepMouseListeners;
  32697. mouseListeners_->remove (index);
  32698. }
  32699. }
  32700. }
  32701. void Component::internalMouseEnter (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  32702. {
  32703. if (isCurrentlyBlockedByAnotherModalComponent())
  32704. {
  32705. // if something else is modal, always just show a normal mouse cursor
  32706. source.showMouseCursor (MouseCursor::NormalCursor);
  32707. return;
  32708. }
  32709. if (! flags.mouseInsideFlag)
  32710. {
  32711. flags.mouseInsideFlag = true;
  32712. flags.mouseOverFlag = true;
  32713. flags.draggingFlag = false;
  32714. BailOutChecker checker (this);
  32715. if (flags.repaintOnMouseActivityFlag)
  32716. repaint();
  32717. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  32718. this, this, time, relativePos,
  32719. time, 0, false);
  32720. mouseEnter (me);
  32721. if (checker.shouldBailOut())
  32722. return;
  32723. Desktop::getInstance().resetTimer();
  32724. Desktop::getInstance().mouseListeners.callChecked (checker, &MouseListener::mouseEnter, me);
  32725. if (checker.shouldBailOut())
  32726. return;
  32727. if (mouseListeners_ != 0)
  32728. {
  32729. for (int i = mouseListeners_->size(); --i >= 0;)
  32730. {
  32731. mouseListeners_->getUnchecked(i)->mouseEnter (me);
  32732. if (checker.shouldBailOut())
  32733. return;
  32734. i = jmin (i, mouseListeners_->size());
  32735. }
  32736. }
  32737. Component* p = parentComponent_;
  32738. while (p != 0)
  32739. {
  32740. if (p->numDeepMouseListeners > 0)
  32741. {
  32742. BailOutChecker checker2 (this, p);
  32743. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32744. {
  32745. p->mouseListeners_->getUnchecked(i)->mouseEnter (me);
  32746. if (checker2.shouldBailOut())
  32747. return;
  32748. i = jmin (i, p->numDeepMouseListeners);
  32749. }
  32750. }
  32751. p = p->parentComponent_;
  32752. }
  32753. }
  32754. }
  32755. void Component::internalMouseExit (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  32756. {
  32757. BailOutChecker checker (this);
  32758. if (flags.draggingFlag)
  32759. {
  32760. internalMouseUp (source, relativePos, time, source.getCurrentModifiers().getRawFlags());
  32761. if (checker.shouldBailOut())
  32762. return;
  32763. }
  32764. if (flags.mouseInsideFlag || flags.mouseOverFlag)
  32765. {
  32766. flags.mouseInsideFlag = false;
  32767. flags.mouseOverFlag = false;
  32768. flags.draggingFlag = false;
  32769. if (flags.repaintOnMouseActivityFlag)
  32770. repaint();
  32771. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  32772. this, this, time, relativePos,
  32773. time, 0, false);
  32774. mouseExit (me);
  32775. if (checker.shouldBailOut())
  32776. return;
  32777. Desktop::getInstance().resetTimer();
  32778. Desktop::getInstance().mouseListeners.callChecked (checker, &MouseListener::mouseExit, me);
  32779. if (checker.shouldBailOut())
  32780. return;
  32781. if (mouseListeners_ != 0)
  32782. {
  32783. for (int i = mouseListeners_->size(); --i >= 0;)
  32784. {
  32785. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseExit (me);
  32786. if (checker.shouldBailOut())
  32787. return;
  32788. i = jmin (i, mouseListeners_->size());
  32789. }
  32790. }
  32791. Component* p = parentComponent_;
  32792. while (p != 0)
  32793. {
  32794. if (p->numDeepMouseListeners > 0)
  32795. {
  32796. BailOutChecker checker2 (this, p);
  32797. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32798. {
  32799. p->mouseListeners_->getUnchecked (i)->mouseExit (me);
  32800. if (checker2.shouldBailOut())
  32801. return;
  32802. i = jmin (i, p->numDeepMouseListeners);
  32803. }
  32804. }
  32805. p = p->parentComponent_;
  32806. }
  32807. }
  32808. }
  32809. class InternalDragRepeater : public Timer
  32810. {
  32811. public:
  32812. InternalDragRepeater()
  32813. {}
  32814. ~InternalDragRepeater()
  32815. {
  32816. clearSingletonInstance();
  32817. }
  32818. juce_DeclareSingleton_SingleThreaded_Minimal (InternalDragRepeater)
  32819. void timerCallback()
  32820. {
  32821. Desktop& desktop = Desktop::getInstance();
  32822. int numMiceDown = 0;
  32823. for (int i = desktop.getNumMouseSources(); --i >= 0;)
  32824. {
  32825. MouseInputSource* const source = desktop.getMouseSource(i);
  32826. if (source->isDragging())
  32827. {
  32828. source->triggerFakeMove();
  32829. ++numMiceDown;
  32830. }
  32831. }
  32832. if (numMiceDown == 0)
  32833. deleteInstance();
  32834. }
  32835. juce_UseDebuggingNewOperator
  32836. private:
  32837. InternalDragRepeater (const InternalDragRepeater&);
  32838. InternalDragRepeater& operator= (const InternalDragRepeater&);
  32839. };
  32840. juce_ImplementSingleton_SingleThreaded (InternalDragRepeater)
  32841. void Component::beginDragAutoRepeat (const int interval)
  32842. {
  32843. if (interval > 0)
  32844. {
  32845. if (InternalDragRepeater::getInstance()->getTimerInterval() != interval)
  32846. InternalDragRepeater::getInstance()->startTimer (interval);
  32847. }
  32848. else
  32849. {
  32850. InternalDragRepeater::deleteInstance();
  32851. }
  32852. }
  32853. void Component::internalMouseDown (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  32854. {
  32855. Desktop& desktop = Desktop::getInstance();
  32856. BailOutChecker checker (this);
  32857. if (isCurrentlyBlockedByAnotherModalComponent())
  32858. {
  32859. internalModalInputAttempt();
  32860. if (checker.shouldBailOut())
  32861. return;
  32862. // If processing the input attempt has exited the modal loop, we'll allow the event
  32863. // to be delivered..
  32864. if (isCurrentlyBlockedByAnotherModalComponent())
  32865. {
  32866. // allow blocked mouse-events to go to global listeners..
  32867. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  32868. this, this, time, relativePos, time,
  32869. source.getNumberOfMultipleClicks(), false);
  32870. desktop.resetTimer();
  32871. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDown, me);
  32872. return;
  32873. }
  32874. }
  32875. {
  32876. Component* c = this;
  32877. while (c != 0)
  32878. {
  32879. if (c->isBroughtToFrontOnMouseClick())
  32880. {
  32881. c->toFront (true);
  32882. if (checker.shouldBailOut())
  32883. return;
  32884. }
  32885. c = c->parentComponent_;
  32886. }
  32887. }
  32888. if (! flags.dontFocusOnMouseClickFlag)
  32889. {
  32890. grabFocusInternal (focusChangedByMouseClick);
  32891. if (checker.shouldBailOut())
  32892. return;
  32893. }
  32894. flags.draggingFlag = true;
  32895. flags.mouseOverFlag = true;
  32896. if (flags.repaintOnMouseActivityFlag)
  32897. repaint();
  32898. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  32899. this, this, time, relativePos, time,
  32900. source.getNumberOfMultipleClicks(), false);
  32901. mouseDown (me);
  32902. if (checker.shouldBailOut())
  32903. return;
  32904. desktop.resetTimer();
  32905. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDown, me);
  32906. if (checker.shouldBailOut())
  32907. return;
  32908. if (mouseListeners_ != 0)
  32909. {
  32910. for (int i = mouseListeners_->size(); --i >= 0;)
  32911. {
  32912. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseDown (me);
  32913. if (checker.shouldBailOut())
  32914. return;
  32915. i = jmin (i, mouseListeners_->size());
  32916. }
  32917. }
  32918. Component* p = parentComponent_;
  32919. while (p != 0)
  32920. {
  32921. if (p->numDeepMouseListeners > 0)
  32922. {
  32923. BailOutChecker checker2 (this, p);
  32924. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32925. {
  32926. p->mouseListeners_->getUnchecked (i)->mouseDown (me);
  32927. if (checker2.shouldBailOut())
  32928. return;
  32929. i = jmin (i, p->numDeepMouseListeners);
  32930. }
  32931. }
  32932. p = p->parentComponent_;
  32933. }
  32934. }
  32935. void Component::internalMouseUp (MouseInputSource& source, const Point<int>& relativePos, const Time& time, const ModifierKeys& oldModifiers)
  32936. {
  32937. if (flags.draggingFlag)
  32938. {
  32939. Desktop& desktop = Desktop::getInstance();
  32940. flags.draggingFlag = false;
  32941. BailOutChecker checker (this);
  32942. if (flags.repaintOnMouseActivityFlag)
  32943. repaint();
  32944. const MouseEvent me (source, relativePos,
  32945. oldModifiers, this, this, time,
  32946. globalPositionToRelative (source.getLastMouseDownPosition()),
  32947. source.getLastMouseDownTime(),
  32948. source.getNumberOfMultipleClicks(),
  32949. source.hasMouseMovedSignificantlySincePressed());
  32950. mouseUp (me);
  32951. if (checker.shouldBailOut())
  32952. return;
  32953. desktop.resetTimer();
  32954. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseUp, me);
  32955. if (checker.shouldBailOut())
  32956. return;
  32957. if (mouseListeners_ != 0)
  32958. {
  32959. for (int i = mouseListeners_->size(); --i >= 0;)
  32960. {
  32961. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseUp (me);
  32962. if (checker.shouldBailOut())
  32963. return;
  32964. i = jmin (i, mouseListeners_->size());
  32965. }
  32966. }
  32967. {
  32968. Component* p = parentComponent_;
  32969. while (p != 0)
  32970. {
  32971. if (p->numDeepMouseListeners > 0)
  32972. {
  32973. BailOutChecker checker2 (this, p);
  32974. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32975. {
  32976. p->mouseListeners_->getUnchecked (i)->mouseUp (me);
  32977. if (checker2.shouldBailOut())
  32978. return;
  32979. i = jmin (i, p->numDeepMouseListeners);
  32980. }
  32981. }
  32982. p = p->parentComponent_;
  32983. }
  32984. }
  32985. // check for double-click
  32986. if (me.getNumberOfClicks() >= 2)
  32987. {
  32988. const int numListeners = (mouseListeners_ != 0) ? mouseListeners_->size() : 0;
  32989. mouseDoubleClick (me);
  32990. if (checker.shouldBailOut())
  32991. return;
  32992. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDoubleClick, me);
  32993. if (checker.shouldBailOut())
  32994. return;
  32995. for (int i = numListeners; --i >= 0;)
  32996. {
  32997. if (checker.shouldBailOut())
  32998. return;
  32999. MouseListener* const ml = (MouseListener*)((*mouseListeners_)[i]);
  33000. if (ml != 0)
  33001. ml->mouseDoubleClick (me);
  33002. }
  33003. if (checker.shouldBailOut())
  33004. return;
  33005. Component* p = parentComponent_;
  33006. while (p != 0)
  33007. {
  33008. if (p->numDeepMouseListeners > 0)
  33009. {
  33010. BailOutChecker checker2 (this, p);
  33011. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33012. {
  33013. p->mouseListeners_->getUnchecked (i)->mouseDoubleClick (me);
  33014. if (checker2.shouldBailOut())
  33015. return;
  33016. i = jmin (i, p->numDeepMouseListeners);
  33017. }
  33018. }
  33019. p = p->parentComponent_;
  33020. }
  33021. }
  33022. }
  33023. }
  33024. void Component::internalMouseDrag (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33025. {
  33026. if (flags.draggingFlag)
  33027. {
  33028. Desktop& desktop = Desktop::getInstance();
  33029. flags.mouseOverFlag = reallyContains (relativePos.getX(), relativePos.getY(), false);
  33030. BailOutChecker checker (this);
  33031. const MouseEvent me (source, relativePos,
  33032. source.getCurrentModifiers(), this, this, time,
  33033. globalPositionToRelative (source.getLastMouseDownPosition()),
  33034. source.getLastMouseDownTime(),
  33035. source.getNumberOfMultipleClicks(),
  33036. source.hasMouseMovedSignificantlySincePressed());
  33037. mouseDrag (me);
  33038. if (checker.shouldBailOut())
  33039. return;
  33040. desktop.resetTimer();
  33041. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDrag, me);
  33042. if (checker.shouldBailOut())
  33043. return;
  33044. if (mouseListeners_ != 0)
  33045. {
  33046. for (int i = mouseListeners_->size(); --i >= 0;)
  33047. {
  33048. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseDrag (me);
  33049. if (checker.shouldBailOut())
  33050. return;
  33051. i = jmin (i, mouseListeners_->size());
  33052. }
  33053. }
  33054. Component* p = parentComponent_;
  33055. while (p != 0)
  33056. {
  33057. if (p->numDeepMouseListeners > 0)
  33058. {
  33059. BailOutChecker checker2 (this, p);
  33060. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33061. {
  33062. p->mouseListeners_->getUnchecked (i)->mouseDrag (me);
  33063. if (checker2.shouldBailOut())
  33064. return;
  33065. i = jmin (i, p->numDeepMouseListeners);
  33066. }
  33067. }
  33068. p = p->parentComponent_;
  33069. }
  33070. }
  33071. }
  33072. void Component::internalMouseMove (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33073. {
  33074. Desktop& desktop = Desktop::getInstance();
  33075. BailOutChecker checker (this);
  33076. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33077. this, this, time, relativePos,
  33078. time, 0, false);
  33079. if (isCurrentlyBlockedByAnotherModalComponent())
  33080. {
  33081. // allow blocked mouse-events to go to global listeners..
  33082. desktop.sendMouseMove();
  33083. }
  33084. else
  33085. {
  33086. flags.mouseOverFlag = true;
  33087. mouseMove (me);
  33088. if (checker.shouldBailOut())
  33089. return;
  33090. desktop.resetTimer();
  33091. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseMove, me);
  33092. if (checker.shouldBailOut())
  33093. return;
  33094. if (mouseListeners_ != 0)
  33095. {
  33096. for (int i = mouseListeners_->size(); --i >= 0;)
  33097. {
  33098. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseMove (me);
  33099. if (checker.shouldBailOut())
  33100. return;
  33101. i = jmin (i, mouseListeners_->size());
  33102. }
  33103. }
  33104. Component* p = parentComponent_;
  33105. while (p != 0)
  33106. {
  33107. if (p->numDeepMouseListeners > 0)
  33108. {
  33109. BailOutChecker checker2 (this, p);
  33110. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33111. {
  33112. p->mouseListeners_->getUnchecked (i)->mouseMove (me);
  33113. if (checker2.shouldBailOut())
  33114. return;
  33115. i = jmin (i, p->numDeepMouseListeners);
  33116. }
  33117. }
  33118. p = p->parentComponent_;
  33119. }
  33120. }
  33121. }
  33122. void Component::internalMouseWheel (MouseInputSource& source, const Point<int>& relativePos,
  33123. const Time& time, const float amountX, const float amountY)
  33124. {
  33125. Desktop& desktop = Desktop::getInstance();
  33126. BailOutChecker checker (this);
  33127. const float wheelIncrementX = amountX * (1.0f / 256.0f);
  33128. const float wheelIncrementY = amountY * (1.0f / 256.0f);
  33129. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33130. this, this, time, relativePos, time, 0, false);
  33131. if (isCurrentlyBlockedByAnotherModalComponent())
  33132. {
  33133. // allow blocked mouse-events to go to global listeners..
  33134. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheelIncrementX, wheelIncrementY);
  33135. }
  33136. else
  33137. {
  33138. mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  33139. if (checker.shouldBailOut())
  33140. return;
  33141. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheelIncrementX, wheelIncrementY);
  33142. if (checker.shouldBailOut())
  33143. return;
  33144. if (mouseListeners_ != 0)
  33145. {
  33146. for (int i = mouseListeners_->size(); --i >= 0;)
  33147. {
  33148. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  33149. if (checker.shouldBailOut())
  33150. return;
  33151. i = jmin (i, mouseListeners_->size());
  33152. }
  33153. }
  33154. Component* p = parentComponent_;
  33155. while (p != 0)
  33156. {
  33157. if (p->numDeepMouseListeners > 0)
  33158. {
  33159. BailOutChecker checker2 (this, p);
  33160. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33161. {
  33162. p->mouseListeners_->getUnchecked (i)->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  33163. if (checker2.shouldBailOut())
  33164. return;
  33165. i = jmin (i, p->numDeepMouseListeners);
  33166. }
  33167. }
  33168. p = p->parentComponent_;
  33169. }
  33170. }
  33171. }
  33172. void Component::sendFakeMouseMove() const
  33173. {
  33174. Desktop::getInstance().getMainMouseSource().triggerFakeMove();
  33175. }
  33176. void Component::broughtToFront()
  33177. {
  33178. }
  33179. void Component::internalBroughtToFront()
  33180. {
  33181. if (! isValidComponent())
  33182. return;
  33183. if (flags.hasHeavyweightPeerFlag)
  33184. Desktop::getInstance().componentBroughtToFront (this);
  33185. BailOutChecker checker (this);
  33186. broughtToFront();
  33187. if (checker.shouldBailOut())
  33188. return;
  33189. componentListeners.callChecked (checker, &ComponentListener::componentBroughtToFront, *this);
  33190. if (checker.shouldBailOut())
  33191. return;
  33192. // When brought to the front and there's a modal component blocking this one,
  33193. // we need to bring the modal one to the front instead..
  33194. Component* const cm = getCurrentlyModalComponent();
  33195. if (cm != 0 && cm->getTopLevelComponent() != getTopLevelComponent())
  33196. bringModalComponentToFront();
  33197. }
  33198. void Component::focusGained (FocusChangeType)
  33199. {
  33200. // base class does nothing
  33201. }
  33202. void Component::internalFocusGain (const FocusChangeType cause)
  33203. {
  33204. SafePointer<Component> safePointer (this);
  33205. focusGained (cause);
  33206. if (safePointer != 0)
  33207. internalChildFocusChange (cause);
  33208. }
  33209. void Component::focusLost (FocusChangeType)
  33210. {
  33211. // base class does nothing
  33212. }
  33213. void Component::internalFocusLoss (const FocusChangeType cause)
  33214. {
  33215. SafePointer<Component> safePointer (this);
  33216. focusLost (focusChangedDirectly);
  33217. if (safePointer != 0)
  33218. internalChildFocusChange (cause);
  33219. }
  33220. void Component::focusOfChildComponentChanged (FocusChangeType /*cause*/)
  33221. {
  33222. // base class does nothing
  33223. }
  33224. void Component::internalChildFocusChange (FocusChangeType cause)
  33225. {
  33226. const bool childIsNowFocused = hasKeyboardFocus (true);
  33227. if (flags.childCompFocusedFlag != childIsNowFocused)
  33228. {
  33229. flags.childCompFocusedFlag = childIsNowFocused;
  33230. SafePointer<Component> safePointer (this);
  33231. focusOfChildComponentChanged (cause);
  33232. if (safePointer == 0)
  33233. return;
  33234. }
  33235. if (parentComponent_ != 0)
  33236. parentComponent_->internalChildFocusChange (cause);
  33237. }
  33238. bool Component::isEnabled() const throw()
  33239. {
  33240. return (! flags.isDisabledFlag)
  33241. && (parentComponent_ == 0 || parentComponent_->isEnabled());
  33242. }
  33243. void Component::setEnabled (const bool shouldBeEnabled)
  33244. {
  33245. if (flags.isDisabledFlag == shouldBeEnabled)
  33246. {
  33247. flags.isDisabledFlag = ! shouldBeEnabled;
  33248. // if any parent components are disabled, setting our flag won't make a difference,
  33249. // so no need to send a change message
  33250. if (parentComponent_ == 0 || parentComponent_->isEnabled())
  33251. sendEnablementChangeMessage();
  33252. }
  33253. }
  33254. void Component::sendEnablementChangeMessage()
  33255. {
  33256. SafePointer<Component> safePointer (this);
  33257. enablementChanged();
  33258. if (safePointer == 0)
  33259. return;
  33260. for (int i = getNumChildComponents(); --i >= 0;)
  33261. {
  33262. Component* const c = getChildComponent (i);
  33263. if (c != 0)
  33264. {
  33265. c->sendEnablementChangeMessage();
  33266. if (safePointer == 0)
  33267. return;
  33268. }
  33269. }
  33270. }
  33271. void Component::enablementChanged()
  33272. {
  33273. }
  33274. void Component::setWantsKeyboardFocus (const bool wantsFocus) throw()
  33275. {
  33276. flags.wantsFocusFlag = wantsFocus;
  33277. }
  33278. void Component::setMouseClickGrabsKeyboardFocus (const bool shouldGrabFocus)
  33279. {
  33280. flags.dontFocusOnMouseClickFlag = ! shouldGrabFocus;
  33281. }
  33282. bool Component::getMouseClickGrabsKeyboardFocus() const throw()
  33283. {
  33284. return ! flags.dontFocusOnMouseClickFlag;
  33285. }
  33286. bool Component::getWantsKeyboardFocus() const throw()
  33287. {
  33288. return flags.wantsFocusFlag && ! flags.isDisabledFlag;
  33289. }
  33290. void Component::setFocusContainer (const bool shouldBeFocusContainer) throw()
  33291. {
  33292. flags.isFocusContainerFlag = shouldBeFocusContainer;
  33293. }
  33294. bool Component::isFocusContainer() const throw()
  33295. {
  33296. return flags.isFocusContainerFlag;
  33297. }
  33298. static const Identifier juce_explicitFocusOrderId ("_jexfo");
  33299. int Component::getExplicitFocusOrder() const
  33300. {
  33301. return properties [juce_explicitFocusOrderId];
  33302. }
  33303. void Component::setExplicitFocusOrder (const int newFocusOrderIndex)
  33304. {
  33305. properties.set (juce_explicitFocusOrderId, newFocusOrderIndex);
  33306. }
  33307. KeyboardFocusTraverser* Component::createFocusTraverser()
  33308. {
  33309. if (flags.isFocusContainerFlag || parentComponent_ == 0)
  33310. return new KeyboardFocusTraverser();
  33311. return parentComponent_->createFocusTraverser();
  33312. }
  33313. void Component::takeKeyboardFocus (const FocusChangeType cause)
  33314. {
  33315. // give the focus to this component
  33316. if (currentlyFocusedComponent != this)
  33317. {
  33318. JUCE_TRY
  33319. {
  33320. // get the focus onto our desktop window
  33321. ComponentPeer* const peer = getPeer();
  33322. if (peer != 0)
  33323. {
  33324. SafePointer<Component> safePointer (this);
  33325. peer->grabFocus();
  33326. if (peer->isFocused() && currentlyFocusedComponent != this)
  33327. {
  33328. Component* const componentLosingFocus = currentlyFocusedComponent;
  33329. currentlyFocusedComponent = this;
  33330. Desktop::getInstance().triggerFocusCallback();
  33331. // call this after setting currentlyFocusedComponent so that the one that's
  33332. // losing it has a chance to see where focus is going
  33333. if (componentLosingFocus->isValidComponent())
  33334. componentLosingFocus->internalFocusLoss (cause);
  33335. if (currentlyFocusedComponent == this)
  33336. {
  33337. focusGained (cause);
  33338. if (safePointer != 0)
  33339. internalChildFocusChange (cause);
  33340. }
  33341. }
  33342. }
  33343. }
  33344. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  33345. catch (const std::exception& e)
  33346. {
  33347. currentlyFocusedComponent = 0;
  33348. Desktop::getInstance().triggerFocusCallback();
  33349. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  33350. }
  33351. catch (...)
  33352. {
  33353. currentlyFocusedComponent = 0;
  33354. Desktop::getInstance().triggerFocusCallback();
  33355. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  33356. }
  33357. #endif
  33358. }
  33359. }
  33360. void Component::grabFocusInternal (const FocusChangeType cause, const bool canTryParent)
  33361. {
  33362. if (isShowing())
  33363. {
  33364. if (flags.wantsFocusFlag && (isEnabled() || parentComponent_ == 0))
  33365. {
  33366. takeKeyboardFocus (cause);
  33367. }
  33368. else
  33369. {
  33370. if (isParentOf (currentlyFocusedComponent)
  33371. && currentlyFocusedComponent->isShowing())
  33372. {
  33373. // do nothing if the focused component is actually a child of ours..
  33374. }
  33375. else
  33376. {
  33377. // find the default child component..
  33378. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  33379. if (traverser != 0)
  33380. {
  33381. Component* const defaultComp = traverser->getDefaultComponent (this);
  33382. traverser = 0;
  33383. if (defaultComp != 0)
  33384. {
  33385. defaultComp->grabFocusInternal (cause, false);
  33386. return;
  33387. }
  33388. }
  33389. if (canTryParent && parentComponent_ != 0)
  33390. {
  33391. // if no children want it and we're allowed to try our parent comp,
  33392. // then pass up to parent, which will try our siblings.
  33393. parentComponent_->grabFocusInternal (cause, true);
  33394. }
  33395. }
  33396. }
  33397. }
  33398. }
  33399. void Component::grabKeyboardFocus()
  33400. {
  33401. // if component methods are being called from threads other than the message
  33402. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33403. checkMessageManagerIsLocked
  33404. grabFocusInternal (focusChangedDirectly);
  33405. }
  33406. void Component::moveKeyboardFocusToSibling (const bool moveToNext)
  33407. {
  33408. // if component methods are being called from threads other than the message
  33409. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33410. checkMessageManagerIsLocked
  33411. if (parentComponent_ != 0)
  33412. {
  33413. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  33414. if (traverser != 0)
  33415. {
  33416. Component* const nextComp = moveToNext ? traverser->getNextComponent (this)
  33417. : traverser->getPreviousComponent (this);
  33418. traverser = 0;
  33419. if (nextComp != 0)
  33420. {
  33421. if (nextComp->isCurrentlyBlockedByAnotherModalComponent())
  33422. {
  33423. SafePointer<Component> nextCompPointer (nextComp);
  33424. internalModalInputAttempt();
  33425. if (nextCompPointer == 0 || nextComp->isCurrentlyBlockedByAnotherModalComponent())
  33426. return;
  33427. }
  33428. nextComp->grabFocusInternal (focusChangedByTabKey);
  33429. return;
  33430. }
  33431. }
  33432. parentComponent_->moveKeyboardFocusToSibling (moveToNext);
  33433. }
  33434. }
  33435. bool Component::hasKeyboardFocus (const bool trueIfChildIsFocused) const
  33436. {
  33437. return (currentlyFocusedComponent == this)
  33438. || (trueIfChildIsFocused && isParentOf (currentlyFocusedComponent));
  33439. }
  33440. Component* JUCE_CALLTYPE Component::getCurrentlyFocusedComponent() throw()
  33441. {
  33442. return currentlyFocusedComponent;
  33443. }
  33444. void Component::giveAwayFocus()
  33445. {
  33446. // use a copy so we can clear the value before the call
  33447. Component* const componentLosingFocus = currentlyFocusedComponent;
  33448. currentlyFocusedComponent = 0;
  33449. Desktop::getInstance().triggerFocusCallback();
  33450. if (componentLosingFocus->isValidComponent())
  33451. componentLosingFocus->internalFocusLoss (focusChangedDirectly);
  33452. }
  33453. bool Component::isMouseOver() const throw()
  33454. {
  33455. return flags.mouseOverFlag;
  33456. }
  33457. bool Component::isMouseButtonDown() const throw()
  33458. {
  33459. return flags.draggingFlag;
  33460. }
  33461. bool Component::isMouseOverOrDragging() const throw()
  33462. {
  33463. return flags.mouseOverFlag || flags.draggingFlag;
  33464. }
  33465. bool JUCE_CALLTYPE Component::isMouseButtonDownAnywhere() throw()
  33466. {
  33467. return ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown();
  33468. }
  33469. const Point<int> Component::getMouseXYRelative() const
  33470. {
  33471. return globalPositionToRelative (Desktop::getMousePosition());
  33472. }
  33473. const Rectangle<int> Component::getParentMonitorArea() const
  33474. {
  33475. return Desktop::getInstance()
  33476. .getMonitorAreaContaining (relativePositionToGlobal (Point<int> (getWidth() / 2,
  33477. getHeight() / 2)));
  33478. }
  33479. void Component::addKeyListener (KeyListener* const newListener)
  33480. {
  33481. if (keyListeners_ == 0)
  33482. keyListeners_ = new Array <KeyListener*>();
  33483. keyListeners_->addIfNotAlreadyThere (newListener);
  33484. }
  33485. void Component::removeKeyListener (KeyListener* const listenerToRemove)
  33486. {
  33487. if (keyListeners_ != 0)
  33488. keyListeners_->removeValue (listenerToRemove);
  33489. }
  33490. bool Component::keyPressed (const KeyPress&)
  33491. {
  33492. return false;
  33493. }
  33494. bool Component::keyStateChanged (const bool /*isKeyDown*/)
  33495. {
  33496. return false;
  33497. }
  33498. void Component::modifierKeysChanged (const ModifierKeys& modifiers)
  33499. {
  33500. if (parentComponent_ != 0)
  33501. parentComponent_->modifierKeysChanged (modifiers);
  33502. }
  33503. void Component::internalModifierKeysChanged()
  33504. {
  33505. sendFakeMouseMove();
  33506. modifierKeysChanged (ModifierKeys::getCurrentModifiers());
  33507. }
  33508. ComponentPeer* Component::getPeer() const
  33509. {
  33510. if (flags.hasHeavyweightPeerFlag)
  33511. return ComponentPeer::getPeerFor (this);
  33512. else if (parentComponent_ != 0)
  33513. return parentComponent_->getPeer();
  33514. else
  33515. return 0;
  33516. }
  33517. Component::BailOutChecker::BailOutChecker (Component* const component1, Component* const component2_)
  33518. : safePointer1 (component1), safePointer2 (component2_), component2 (component2_)
  33519. {
  33520. jassert (component1 != 0);
  33521. }
  33522. bool Component::BailOutChecker::shouldBailOut() const throw()
  33523. {
  33524. return safePointer1 == 0 || safePointer2.getComponent() != component2;
  33525. }
  33526. END_JUCE_NAMESPACE
  33527. /*** End of inlined file: juce_Component.cpp ***/
  33528. /*** Start of inlined file: juce_ComponentListener.cpp ***/
  33529. BEGIN_JUCE_NAMESPACE
  33530. void ComponentListener::componentMovedOrResized (Component&, bool, bool) {}
  33531. void ComponentListener::componentBroughtToFront (Component&) {}
  33532. void ComponentListener::componentVisibilityChanged (Component&) {}
  33533. void ComponentListener::componentChildrenChanged (Component&) {}
  33534. void ComponentListener::componentParentHierarchyChanged (Component&) {}
  33535. void ComponentListener::componentNameChanged (Component&) {}
  33536. void ComponentListener::componentBeingDeleted (Component&) {}
  33537. END_JUCE_NAMESPACE
  33538. /*** End of inlined file: juce_ComponentListener.cpp ***/
  33539. /*** Start of inlined file: juce_Desktop.cpp ***/
  33540. BEGIN_JUCE_NAMESPACE
  33541. Desktop::Desktop()
  33542. : mouseClickCounter (0),
  33543. kioskModeComponent (0)
  33544. {
  33545. createMouseInputSources();
  33546. refreshMonitorSizes();
  33547. }
  33548. Desktop::~Desktop()
  33549. {
  33550. jassert (instance == this);
  33551. instance = 0;
  33552. // doh! If you don't delete all your windows before exiting, you're going to
  33553. // be leaking memory!
  33554. jassert (desktopComponents.size() == 0);
  33555. }
  33556. Desktop& JUCE_CALLTYPE Desktop::getInstance()
  33557. {
  33558. if (instance == 0)
  33559. instance = new Desktop();
  33560. return *instance;
  33561. }
  33562. Desktop* Desktop::instance = 0;
  33563. extern void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords,
  33564. const bool clipToWorkArea);
  33565. void Desktop::refreshMonitorSizes()
  33566. {
  33567. const Array <Rectangle<int> > oldClipped (monitorCoordsClipped);
  33568. const Array <Rectangle<int> > oldUnclipped (monitorCoordsUnclipped);
  33569. monitorCoordsClipped.clear();
  33570. monitorCoordsUnclipped.clear();
  33571. juce_updateMultiMonitorInfo (monitorCoordsClipped, true);
  33572. juce_updateMultiMonitorInfo (monitorCoordsUnclipped, false);
  33573. jassert (monitorCoordsClipped.size() == monitorCoordsUnclipped.size());
  33574. if (oldClipped != monitorCoordsClipped
  33575. || oldUnclipped != monitorCoordsUnclipped)
  33576. {
  33577. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  33578. {
  33579. ComponentPeer* const p = ComponentPeer::getPeer (i);
  33580. if (p != 0)
  33581. p->handleScreenSizeChange();
  33582. }
  33583. }
  33584. }
  33585. int Desktop::getNumDisplayMonitors() const throw()
  33586. {
  33587. return monitorCoordsClipped.size();
  33588. }
  33589. const Rectangle<int> Desktop::getDisplayMonitorCoordinates (const int index, const bool clippedToWorkArea) const throw()
  33590. {
  33591. return clippedToWorkArea ? monitorCoordsClipped [index]
  33592. : monitorCoordsUnclipped [index];
  33593. }
  33594. const RectangleList Desktop::getAllMonitorDisplayAreas (const bool clippedToWorkArea) const throw()
  33595. {
  33596. RectangleList rl;
  33597. for (int i = 0; i < getNumDisplayMonitors(); ++i)
  33598. rl.addWithoutMerging (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  33599. return rl;
  33600. }
  33601. const Rectangle<int> Desktop::getMainMonitorArea (const bool clippedToWorkArea) const throw()
  33602. {
  33603. return getDisplayMonitorCoordinates (0, clippedToWorkArea);
  33604. }
  33605. const Rectangle<int> Desktop::getMonitorAreaContaining (const Point<int>& position, const bool clippedToWorkArea) const
  33606. {
  33607. Rectangle<int> best (getMainMonitorArea (clippedToWorkArea));
  33608. double bestDistance = 1.0e10;
  33609. for (int i = getNumDisplayMonitors(); --i >= 0;)
  33610. {
  33611. const Rectangle<int> rect (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  33612. if (rect.contains (position))
  33613. return rect;
  33614. const double distance = rect.getCentre().getDistanceFrom (position);
  33615. if (distance < bestDistance)
  33616. {
  33617. bestDistance = distance;
  33618. best = rect;
  33619. }
  33620. }
  33621. return best;
  33622. }
  33623. int Desktop::getNumComponents() const throw()
  33624. {
  33625. return desktopComponents.size();
  33626. }
  33627. Component* Desktop::getComponent (const int index) const throw()
  33628. {
  33629. return desktopComponents [index];
  33630. }
  33631. Component* Desktop::findComponentAt (const Point<int>& screenPosition) const
  33632. {
  33633. for (int i = desktopComponents.size(); --i >= 0;)
  33634. {
  33635. Component* const c = desktopComponents.getUnchecked(i);
  33636. const Point<int> relative (c->globalPositionToRelative (screenPosition));
  33637. if (c->contains (relative.getX(), relative.getY()))
  33638. return c->getComponentAt (relative.getX(), relative.getY());
  33639. }
  33640. return 0;
  33641. }
  33642. void Desktop::addDesktopComponent (Component* const c)
  33643. {
  33644. jassert (c != 0);
  33645. jassert (! desktopComponents.contains (c));
  33646. desktopComponents.addIfNotAlreadyThere (c);
  33647. }
  33648. void Desktop::removeDesktopComponent (Component* const c)
  33649. {
  33650. desktopComponents.removeValue (c);
  33651. }
  33652. void Desktop::componentBroughtToFront (Component* const c)
  33653. {
  33654. const int index = desktopComponents.indexOf (c);
  33655. jassert (index >= 0);
  33656. if (index >= 0)
  33657. {
  33658. int newIndex = -1;
  33659. if (! c->isAlwaysOnTop())
  33660. {
  33661. newIndex = desktopComponents.size();
  33662. while (newIndex > 0 && desktopComponents.getUnchecked (newIndex - 1)->isAlwaysOnTop())
  33663. --newIndex;
  33664. --newIndex;
  33665. }
  33666. desktopComponents.move (index, newIndex);
  33667. }
  33668. }
  33669. const Point<int> Desktop::getLastMouseDownPosition() throw()
  33670. {
  33671. return getInstance().getMainMouseSource().getLastMouseDownPosition();
  33672. }
  33673. int Desktop::getMouseButtonClickCounter() throw()
  33674. {
  33675. return getInstance().mouseClickCounter;
  33676. }
  33677. void Desktop::incrementMouseClickCounter() throw()
  33678. {
  33679. ++mouseClickCounter;
  33680. }
  33681. int Desktop::getNumDraggingMouseSources() const throw()
  33682. {
  33683. int num = 0;
  33684. for (int i = mouseSources.size(); --i >= 0;)
  33685. if (mouseSources.getUnchecked(i)->isDragging())
  33686. ++num;
  33687. return num;
  33688. }
  33689. MouseInputSource* Desktop::getDraggingMouseSource (int index) const throw()
  33690. {
  33691. int num = 0;
  33692. for (int i = mouseSources.size(); --i >= 0;)
  33693. {
  33694. MouseInputSource* const mi = mouseSources.getUnchecked(i);
  33695. if (mi->isDragging())
  33696. {
  33697. if (index == num)
  33698. return mi;
  33699. ++num;
  33700. }
  33701. }
  33702. return 0;
  33703. }
  33704. void Desktop::addFocusChangeListener (FocusChangeListener* const listener)
  33705. {
  33706. focusListeners.add (listener);
  33707. }
  33708. void Desktop::removeFocusChangeListener (FocusChangeListener* const listener)
  33709. {
  33710. focusListeners.remove (listener);
  33711. }
  33712. void Desktop::triggerFocusCallback()
  33713. {
  33714. triggerAsyncUpdate();
  33715. }
  33716. void Desktop::handleAsyncUpdate()
  33717. {
  33718. Component* currentFocus = Component::getCurrentlyFocusedComponent();
  33719. focusListeners.call (&FocusChangeListener::globalFocusChanged, currentFocus);
  33720. }
  33721. void Desktop::addGlobalMouseListener (MouseListener* const listener)
  33722. {
  33723. mouseListeners.add (listener);
  33724. resetTimer();
  33725. }
  33726. void Desktop::removeGlobalMouseListener (MouseListener* const listener)
  33727. {
  33728. mouseListeners.remove (listener);
  33729. resetTimer();
  33730. }
  33731. void Desktop::timerCallback()
  33732. {
  33733. if (lastFakeMouseMove != getMousePosition())
  33734. sendMouseMove();
  33735. }
  33736. void Desktop::sendMouseMove()
  33737. {
  33738. if (! mouseListeners.isEmpty())
  33739. {
  33740. startTimer (20);
  33741. lastFakeMouseMove = getMousePosition();
  33742. Component* const target = findComponentAt (lastFakeMouseMove);
  33743. if (target != 0)
  33744. {
  33745. Component::BailOutChecker checker (target);
  33746. const Point<int> pos (target->globalPositionToRelative (lastFakeMouseMove));
  33747. const Time now (Time::getCurrentTime());
  33748. const MouseEvent me (getMainMouseSource(), pos, ModifierKeys::getCurrentModifiers(),
  33749. target, target, now, pos, now, 0, false);
  33750. if (me.mods.isAnyMouseButtonDown())
  33751. mouseListeners.callChecked (checker, &MouseListener::mouseDrag, me);
  33752. else
  33753. mouseListeners.callChecked (checker, &MouseListener::mouseMove, me);
  33754. }
  33755. }
  33756. }
  33757. void Desktop::resetTimer()
  33758. {
  33759. if (mouseListeners.size() == 0)
  33760. stopTimer();
  33761. else
  33762. startTimer (100);
  33763. lastFakeMouseMove = getMousePosition();
  33764. }
  33765. extern void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars);
  33766. void Desktop::setKioskModeComponent (Component* componentToUse, const bool allowMenusAndBars)
  33767. {
  33768. if (kioskModeComponent != componentToUse)
  33769. {
  33770. // agh! Don't delete a component without first stopping it being the kiosk comp
  33771. jassert (kioskModeComponent == 0 || kioskModeComponent->isValidComponent());
  33772. // agh! Don't remove a component from the desktop if it's the kiosk comp!
  33773. jassert (kioskModeComponent == 0 || kioskModeComponent->isOnDesktop());
  33774. if (kioskModeComponent->isValidComponent())
  33775. {
  33776. juce_setKioskComponent (kioskModeComponent, false, allowMenusAndBars);
  33777. kioskModeComponent->setBounds (kioskComponentOriginalBounds);
  33778. }
  33779. kioskModeComponent = componentToUse;
  33780. if (kioskModeComponent != 0)
  33781. {
  33782. jassert (kioskModeComponent->isValidComponent());
  33783. // Only components that are already on the desktop can be put into kiosk mode!
  33784. jassert (kioskModeComponent->isOnDesktop());
  33785. kioskComponentOriginalBounds = kioskModeComponent->getBounds();
  33786. juce_setKioskComponent (kioskModeComponent, true, allowMenusAndBars);
  33787. }
  33788. }
  33789. }
  33790. END_JUCE_NAMESPACE
  33791. /*** End of inlined file: juce_Desktop.cpp ***/
  33792. /*** Start of inlined file: juce_ArrowButton.cpp ***/
  33793. BEGIN_JUCE_NAMESPACE
  33794. ArrowButton::ArrowButton (const String& name,
  33795. float arrowDirectionInRadians,
  33796. const Colour& arrowColour)
  33797. : Button (name),
  33798. colour (arrowColour)
  33799. {
  33800. path.lineTo (0.0f, 1.0f);
  33801. path.lineTo (1.0f, 0.5f);
  33802. path.closeSubPath();
  33803. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * arrowDirectionInRadians,
  33804. 0.5f, 0.5f));
  33805. setComponentEffect (&shadow);
  33806. buttonStateChanged();
  33807. }
  33808. ArrowButton::~ArrowButton()
  33809. {
  33810. }
  33811. void ArrowButton::paintButton (Graphics& g,
  33812. bool /*isMouseOverButton*/,
  33813. bool /*isButtonDown*/)
  33814. {
  33815. g.setColour (colour);
  33816. g.fillPath (path, path.getTransformToScaleToFit ((float) offset,
  33817. (float) offset,
  33818. (float) (getWidth() - 3),
  33819. (float) (getHeight() - 3),
  33820. false));
  33821. }
  33822. void ArrowButton::buttonStateChanged()
  33823. {
  33824. offset = (isDown()) ? 1 : 0;
  33825. shadow.setShadowProperties ((isDown()) ? 1.2f : 3.0f,
  33826. 0.3f, -1, 0);
  33827. }
  33828. END_JUCE_NAMESPACE
  33829. /*** End of inlined file: juce_ArrowButton.cpp ***/
  33830. /*** Start of inlined file: juce_Button.cpp ***/
  33831. BEGIN_JUCE_NAMESPACE
  33832. class Button::RepeatTimer : public Timer
  33833. {
  33834. public:
  33835. RepeatTimer (Button& owner_) : owner (owner_) {}
  33836. void timerCallback() { owner.repeatTimerCallback(); }
  33837. juce_UseDebuggingNewOperator
  33838. private:
  33839. Button& owner;
  33840. RepeatTimer (const RepeatTimer&);
  33841. RepeatTimer& operator= (const RepeatTimer&);
  33842. };
  33843. Button::Button (const String& name)
  33844. : Component (name),
  33845. text (name),
  33846. buttonPressTime (0),
  33847. lastTimeCallbackTime (0),
  33848. commandManagerToUse (0),
  33849. autoRepeatDelay (-1),
  33850. autoRepeatSpeed (0),
  33851. autoRepeatMinimumDelay (-1),
  33852. radioGroupId (0),
  33853. commandID (0),
  33854. connectedEdgeFlags (0),
  33855. buttonState (buttonNormal),
  33856. lastToggleState (false),
  33857. clickTogglesState (false),
  33858. needsToRelease (false),
  33859. needsRepainting (false),
  33860. isKeyDown (false),
  33861. triggerOnMouseDown (false),
  33862. generateTooltip (false)
  33863. {
  33864. setWantsKeyboardFocus (true);
  33865. isOn.addListener (this);
  33866. }
  33867. Button::~Button()
  33868. {
  33869. isOn.removeListener (this);
  33870. if (commandManagerToUse != 0)
  33871. commandManagerToUse->removeListener (this);
  33872. repeatTimer = 0;
  33873. clearShortcuts();
  33874. }
  33875. void Button::setButtonText (const String& newText)
  33876. {
  33877. if (text != newText)
  33878. {
  33879. text = newText;
  33880. repaint();
  33881. }
  33882. }
  33883. void Button::setTooltip (const String& newTooltip)
  33884. {
  33885. SettableTooltipClient::setTooltip (newTooltip);
  33886. generateTooltip = false;
  33887. }
  33888. const String Button::getTooltip()
  33889. {
  33890. if (generateTooltip && commandManagerToUse != 0 && commandID != 0)
  33891. {
  33892. String tt (commandManagerToUse->getDescriptionOfCommand (commandID));
  33893. Array <KeyPress> keyPresses (commandManagerToUse->getKeyMappings()->getKeyPressesAssignedToCommand (commandID));
  33894. for (int i = 0; i < keyPresses.size(); ++i)
  33895. {
  33896. const String key (keyPresses.getReference(i).getTextDescription());
  33897. tt << " [";
  33898. if (key.length() == 1)
  33899. tt << TRANS("shortcut") << ": '" << key << "']";
  33900. else
  33901. tt << key << ']';
  33902. }
  33903. return tt;
  33904. }
  33905. return SettableTooltipClient::getTooltip();
  33906. }
  33907. void Button::setConnectedEdges (const int connectedEdgeFlags_)
  33908. {
  33909. if (connectedEdgeFlags != connectedEdgeFlags_)
  33910. {
  33911. connectedEdgeFlags = connectedEdgeFlags_;
  33912. repaint();
  33913. }
  33914. }
  33915. void Button::setToggleState (const bool shouldBeOn,
  33916. const bool sendChangeNotification)
  33917. {
  33918. if (shouldBeOn != lastToggleState)
  33919. {
  33920. if (isOn != shouldBeOn) // this test means that if the value is void rather than explicitly set to
  33921. isOn = shouldBeOn; // false, it won't be changed unless the required value is true.
  33922. lastToggleState = shouldBeOn;
  33923. repaint();
  33924. if (sendChangeNotification)
  33925. {
  33926. Component::SafePointer<Component> deletionWatcher (this);
  33927. sendClickMessage (ModifierKeys());
  33928. if (deletionWatcher == 0)
  33929. return;
  33930. }
  33931. if (lastToggleState)
  33932. turnOffOtherButtonsInGroup (sendChangeNotification);
  33933. }
  33934. }
  33935. void Button::setClickingTogglesState (const bool shouldToggle) throw()
  33936. {
  33937. clickTogglesState = shouldToggle;
  33938. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  33939. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  33940. // it is that this button represents, and the button will update its state to reflect this
  33941. // in the applicationCommandListChanged() method.
  33942. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  33943. }
  33944. bool Button::getClickingTogglesState() const throw()
  33945. {
  33946. return clickTogglesState;
  33947. }
  33948. void Button::valueChanged (Value& value)
  33949. {
  33950. if (value.refersToSameSourceAs (isOn))
  33951. setToggleState (isOn.getValue(), true);
  33952. }
  33953. void Button::setRadioGroupId (const int newGroupId)
  33954. {
  33955. if (radioGroupId != newGroupId)
  33956. {
  33957. radioGroupId = newGroupId;
  33958. if (lastToggleState)
  33959. turnOffOtherButtonsInGroup (true);
  33960. }
  33961. }
  33962. void Button::turnOffOtherButtonsInGroup (const bool sendChangeNotification)
  33963. {
  33964. Component* const p = getParentComponent();
  33965. if (p != 0 && radioGroupId != 0)
  33966. {
  33967. Component::SafePointer<Component> deletionWatcher (this);
  33968. for (int i = p->getNumChildComponents(); --i >= 0;)
  33969. {
  33970. Component* const c = p->getChildComponent (i);
  33971. if (c != this)
  33972. {
  33973. Button* const b = dynamic_cast <Button*> (c);
  33974. if (b != 0 && b->getRadioGroupId() == radioGroupId)
  33975. {
  33976. b->setToggleState (false, sendChangeNotification);
  33977. if (deletionWatcher == 0)
  33978. return;
  33979. }
  33980. }
  33981. }
  33982. }
  33983. }
  33984. void Button::enablementChanged()
  33985. {
  33986. updateState (0);
  33987. repaint();
  33988. }
  33989. Button::ButtonState Button::updateState (const MouseEvent* const e)
  33990. {
  33991. ButtonState state = buttonNormal;
  33992. if (isEnabled() && isVisible() && ! isCurrentlyBlockedByAnotherModalComponent())
  33993. {
  33994. Point<int> mousePos;
  33995. if (e == 0)
  33996. mousePos = getMouseXYRelative();
  33997. else
  33998. mousePos = e->getEventRelativeTo (this).getPosition();
  33999. const bool over = reallyContains (mousePos.getX(), mousePos.getY(), true);
  34000. const bool down = isMouseButtonDown();
  34001. if ((down && (over || (triggerOnMouseDown && buttonState == buttonDown))) || isKeyDown)
  34002. state = buttonDown;
  34003. else if (over)
  34004. state = buttonOver;
  34005. }
  34006. setState (state);
  34007. return state;
  34008. }
  34009. void Button::setState (const ButtonState newState)
  34010. {
  34011. if (buttonState != newState)
  34012. {
  34013. buttonState = newState;
  34014. repaint();
  34015. if (buttonState == buttonDown)
  34016. {
  34017. buttonPressTime = Time::getApproximateMillisecondCounter();
  34018. lastTimeCallbackTime = buttonPressTime;
  34019. }
  34020. sendStateMessage();
  34021. }
  34022. }
  34023. bool Button::isDown() const throw()
  34024. {
  34025. return buttonState == buttonDown;
  34026. }
  34027. bool Button::isOver() const throw()
  34028. {
  34029. return buttonState != buttonNormal;
  34030. }
  34031. void Button::buttonStateChanged()
  34032. {
  34033. }
  34034. uint32 Button::getMillisecondsSinceButtonDown() const throw()
  34035. {
  34036. const uint32 now = Time::getApproximateMillisecondCounter();
  34037. return now > buttonPressTime ? now - buttonPressTime : 0;
  34038. }
  34039. void Button::setTriggeredOnMouseDown (const bool isTriggeredOnMouseDown) throw()
  34040. {
  34041. triggerOnMouseDown = isTriggeredOnMouseDown;
  34042. }
  34043. void Button::clicked()
  34044. {
  34045. }
  34046. void Button::clicked (const ModifierKeys& /*modifiers*/)
  34047. {
  34048. clicked();
  34049. }
  34050. static const int clickMessageId = 0x2f3f4f99;
  34051. void Button::triggerClick()
  34052. {
  34053. postCommandMessage (clickMessageId);
  34054. }
  34055. void Button::internalClickCallback (const ModifierKeys& modifiers)
  34056. {
  34057. if (clickTogglesState)
  34058. setToggleState ((radioGroupId != 0) || ! lastToggleState, false);
  34059. sendClickMessage (modifiers);
  34060. }
  34061. void Button::flashButtonState()
  34062. {
  34063. if (isEnabled())
  34064. {
  34065. needsToRelease = true;
  34066. setState (buttonDown);
  34067. getRepeatTimer().startTimer (100);
  34068. }
  34069. }
  34070. void Button::handleCommandMessage (int commandId)
  34071. {
  34072. if (commandId == clickMessageId)
  34073. {
  34074. if (isEnabled())
  34075. {
  34076. flashButtonState();
  34077. internalClickCallback (ModifierKeys::getCurrentModifiers());
  34078. }
  34079. }
  34080. else
  34081. {
  34082. Component::handleCommandMessage (commandId);
  34083. }
  34084. }
  34085. void Button::addButtonListener (ButtonListener* const newListener)
  34086. {
  34087. buttonListeners.add (newListener);
  34088. }
  34089. void Button::removeButtonListener (ButtonListener* const listener)
  34090. {
  34091. buttonListeners.remove (listener);
  34092. }
  34093. void Button::sendClickMessage (const ModifierKeys& modifiers)
  34094. {
  34095. Component::BailOutChecker checker (this);
  34096. if (commandManagerToUse != 0 && commandID != 0)
  34097. {
  34098. ApplicationCommandTarget::InvocationInfo info (commandID);
  34099. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromButton;
  34100. info.originatingComponent = this;
  34101. commandManagerToUse->invoke (info, true);
  34102. }
  34103. clicked (modifiers);
  34104. if (! checker.shouldBailOut())
  34105. buttonListeners.callChecked (checker, &ButtonListener::buttonClicked, this);
  34106. }
  34107. void Button::sendStateMessage()
  34108. {
  34109. Component::BailOutChecker checker (this);
  34110. buttonStateChanged();
  34111. if (! checker.shouldBailOut())
  34112. buttonListeners.callChecked (checker, &ButtonListener::buttonStateChanged, this);
  34113. }
  34114. void Button::paint (Graphics& g)
  34115. {
  34116. if (needsToRelease && isEnabled())
  34117. {
  34118. needsToRelease = false;
  34119. needsRepainting = true;
  34120. }
  34121. paintButton (g, isOver(), isDown());
  34122. }
  34123. void Button::mouseEnter (const MouseEvent& e)
  34124. {
  34125. updateState (&e);
  34126. }
  34127. void Button::mouseExit (const MouseEvent& e)
  34128. {
  34129. updateState (&e);
  34130. }
  34131. void Button::mouseDown (const MouseEvent& e)
  34132. {
  34133. updateState (&e);
  34134. if (isDown())
  34135. {
  34136. if (autoRepeatDelay >= 0)
  34137. getRepeatTimer().startTimer (autoRepeatDelay);
  34138. if (triggerOnMouseDown)
  34139. internalClickCallback (e.mods);
  34140. }
  34141. }
  34142. void Button::mouseUp (const MouseEvent& e)
  34143. {
  34144. const bool wasDown = isDown();
  34145. updateState (&e);
  34146. if (wasDown && isOver() && ! triggerOnMouseDown)
  34147. internalClickCallback (e.mods);
  34148. }
  34149. void Button::mouseDrag (const MouseEvent& e)
  34150. {
  34151. const ButtonState oldState = buttonState;
  34152. updateState (&e);
  34153. if (autoRepeatDelay >= 0 && buttonState != oldState && isDown())
  34154. getRepeatTimer().startTimer (autoRepeatSpeed);
  34155. }
  34156. void Button::focusGained (FocusChangeType)
  34157. {
  34158. updateState (0);
  34159. repaint();
  34160. }
  34161. void Button::focusLost (FocusChangeType)
  34162. {
  34163. updateState (0);
  34164. repaint();
  34165. }
  34166. void Button::setVisible (bool shouldBeVisible)
  34167. {
  34168. if (shouldBeVisible != isVisible())
  34169. {
  34170. Component::setVisible (shouldBeVisible);
  34171. if (! shouldBeVisible)
  34172. needsToRelease = false;
  34173. updateState (0);
  34174. }
  34175. else
  34176. {
  34177. Component::setVisible (shouldBeVisible);
  34178. }
  34179. }
  34180. void Button::parentHierarchyChanged()
  34181. {
  34182. Component* const newKeySource = (shortcuts.size() == 0) ? 0 : getTopLevelComponent();
  34183. if (newKeySource != keySource.getComponent())
  34184. {
  34185. if (keySource != 0)
  34186. keySource->removeKeyListener (this);
  34187. keySource = newKeySource;
  34188. if (keySource != 0)
  34189. keySource->addKeyListener (this);
  34190. }
  34191. }
  34192. void Button::setCommandToTrigger (ApplicationCommandManager* const commandManagerToUse_,
  34193. const int commandID_,
  34194. const bool generateTooltip_)
  34195. {
  34196. commandID = commandID_;
  34197. generateTooltip = generateTooltip_;
  34198. if (commandManagerToUse != commandManagerToUse_)
  34199. {
  34200. if (commandManagerToUse != 0)
  34201. commandManagerToUse->removeListener (this);
  34202. commandManagerToUse = commandManagerToUse_;
  34203. if (commandManagerToUse != 0)
  34204. commandManagerToUse->addListener (this);
  34205. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  34206. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  34207. // it is that this button represents, and the button will update its state to reflect this
  34208. // in the applicationCommandListChanged() method.
  34209. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  34210. }
  34211. if (commandManagerToUse != 0)
  34212. applicationCommandListChanged();
  34213. else
  34214. setEnabled (true);
  34215. }
  34216. void Button::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  34217. {
  34218. if (info.commandID == commandID
  34219. && (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) == 0)
  34220. {
  34221. flashButtonState();
  34222. }
  34223. }
  34224. void Button::applicationCommandListChanged()
  34225. {
  34226. if (commandManagerToUse != 0)
  34227. {
  34228. ApplicationCommandInfo info (0);
  34229. ApplicationCommandTarget* const target = commandManagerToUse->getTargetForCommand (commandID, info);
  34230. setEnabled (target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0);
  34231. if (target != 0)
  34232. setToggleState ((info.flags & ApplicationCommandInfo::isTicked) != 0, false);
  34233. }
  34234. }
  34235. void Button::addShortcut (const KeyPress& key)
  34236. {
  34237. if (key.isValid())
  34238. {
  34239. jassert (! isRegisteredForShortcut (key)); // already registered!
  34240. shortcuts.add (key);
  34241. parentHierarchyChanged();
  34242. }
  34243. }
  34244. void Button::clearShortcuts()
  34245. {
  34246. shortcuts.clear();
  34247. parentHierarchyChanged();
  34248. }
  34249. bool Button::isShortcutPressed() const
  34250. {
  34251. if (! isCurrentlyBlockedByAnotherModalComponent())
  34252. {
  34253. for (int i = shortcuts.size(); --i >= 0;)
  34254. if (shortcuts.getReference(i).isCurrentlyDown())
  34255. return true;
  34256. }
  34257. return false;
  34258. }
  34259. bool Button::isRegisteredForShortcut (const KeyPress& key) const
  34260. {
  34261. for (int i = shortcuts.size(); --i >= 0;)
  34262. if (key == shortcuts.getReference(i))
  34263. return true;
  34264. return false;
  34265. }
  34266. bool Button::keyStateChanged (const bool, Component*)
  34267. {
  34268. if (! isEnabled())
  34269. return false;
  34270. const bool wasDown = isKeyDown;
  34271. isKeyDown = isShortcutPressed();
  34272. if (autoRepeatDelay >= 0 && (isKeyDown && ! wasDown))
  34273. getRepeatTimer().startTimer (autoRepeatDelay);
  34274. updateState (0);
  34275. if (isEnabled() && wasDown && ! isKeyDown)
  34276. {
  34277. internalClickCallback (ModifierKeys::getCurrentModifiers());
  34278. // (return immediately - this button may now have been deleted)
  34279. return true;
  34280. }
  34281. return wasDown || isKeyDown;
  34282. }
  34283. bool Button::keyPressed (const KeyPress&, Component*)
  34284. {
  34285. // returning true will avoid forwarding events for keys that we're using as shortcuts
  34286. return isShortcutPressed();
  34287. }
  34288. bool Button::keyPressed (const KeyPress& key)
  34289. {
  34290. if (isEnabled() && key.isKeyCode (KeyPress::returnKey))
  34291. {
  34292. triggerClick();
  34293. return true;
  34294. }
  34295. return false;
  34296. }
  34297. void Button::setRepeatSpeed (const int initialDelayMillisecs,
  34298. const int repeatMillisecs,
  34299. const int minimumDelayInMillisecs) throw()
  34300. {
  34301. autoRepeatDelay = initialDelayMillisecs;
  34302. autoRepeatSpeed = repeatMillisecs;
  34303. autoRepeatMinimumDelay = jmin (autoRepeatSpeed, minimumDelayInMillisecs);
  34304. }
  34305. void Button::repeatTimerCallback()
  34306. {
  34307. if (needsRepainting)
  34308. {
  34309. getRepeatTimer().stopTimer();
  34310. updateState (0);
  34311. needsRepainting = false;
  34312. }
  34313. else if (autoRepeatSpeed > 0 && (isKeyDown || (updateState (0) == buttonDown)))
  34314. {
  34315. int repeatSpeed = autoRepeatSpeed;
  34316. if (autoRepeatMinimumDelay >= 0)
  34317. {
  34318. double timeHeldDown = jmin (1.0, getMillisecondsSinceButtonDown() / 4000.0);
  34319. timeHeldDown *= timeHeldDown;
  34320. repeatSpeed = repeatSpeed + (int) (timeHeldDown * (autoRepeatMinimumDelay - repeatSpeed));
  34321. }
  34322. repeatSpeed = jmax (1, repeatSpeed);
  34323. getRepeatTimer().startTimer (repeatSpeed);
  34324. const uint32 now = Time::getApproximateMillisecondCounter();
  34325. const int numTimesToCallback = (now > lastTimeCallbackTime) ? jmax (1, (int) (now - lastTimeCallbackTime) / repeatSpeed) : 1;
  34326. lastTimeCallbackTime = now;
  34327. Component::SafePointer<Component> deletionWatcher (this);
  34328. for (int i = numTimesToCallback; --i >= 0;)
  34329. {
  34330. internalClickCallback (ModifierKeys::getCurrentModifiers());
  34331. if (deletionWatcher == 0 || ! isDown())
  34332. return;
  34333. }
  34334. }
  34335. else if (! needsToRelease)
  34336. {
  34337. getRepeatTimer().stopTimer();
  34338. }
  34339. }
  34340. Button::RepeatTimer& Button::getRepeatTimer()
  34341. {
  34342. if (repeatTimer == 0)
  34343. repeatTimer = new RepeatTimer (*this);
  34344. return *repeatTimer;
  34345. }
  34346. END_JUCE_NAMESPACE
  34347. /*** End of inlined file: juce_Button.cpp ***/
  34348. /*** Start of inlined file: juce_DrawableButton.cpp ***/
  34349. BEGIN_JUCE_NAMESPACE
  34350. DrawableButton::DrawableButton (const String& name,
  34351. const DrawableButton::ButtonStyle buttonStyle)
  34352. : Button (name),
  34353. style (buttonStyle),
  34354. edgeIndent (3)
  34355. {
  34356. if (buttonStyle == ImageOnButtonBackground)
  34357. {
  34358. backgroundOff = Colour (0xffbbbbff);
  34359. backgroundOn = Colour (0xff3333ff);
  34360. }
  34361. else
  34362. {
  34363. backgroundOff = Colours::transparentBlack;
  34364. backgroundOn = Colour (0xaabbbbff);
  34365. }
  34366. }
  34367. DrawableButton::~DrawableButton()
  34368. {
  34369. deleteImages();
  34370. }
  34371. void DrawableButton::deleteImages()
  34372. {
  34373. }
  34374. void DrawableButton::setImages (const Drawable* normal,
  34375. const Drawable* over,
  34376. const Drawable* down,
  34377. const Drawable* disabled,
  34378. const Drawable* normalOn,
  34379. const Drawable* overOn,
  34380. const Drawable* downOn,
  34381. const Drawable* disabledOn)
  34382. {
  34383. deleteImages();
  34384. jassert (normal != 0); // you really need to give it at least a normal image..
  34385. if (normal != 0)
  34386. normalImage = normal->createCopy();
  34387. if (over != 0)
  34388. overImage = over->createCopy();
  34389. if (down != 0)
  34390. downImage = down->createCopy();
  34391. if (disabled != 0)
  34392. disabledImage = disabled->createCopy();
  34393. if (normalOn != 0)
  34394. normalImageOn = normalOn->createCopy();
  34395. if (overOn != 0)
  34396. overImageOn = overOn->createCopy();
  34397. if (downOn != 0)
  34398. downImageOn = downOn->createCopy();
  34399. if (disabledOn != 0)
  34400. disabledImageOn = disabledOn->createCopy();
  34401. repaint();
  34402. }
  34403. void DrawableButton::setButtonStyle (const DrawableButton::ButtonStyle newStyle)
  34404. {
  34405. if (style != newStyle)
  34406. {
  34407. style = newStyle;
  34408. repaint();
  34409. }
  34410. }
  34411. void DrawableButton::setBackgroundColours (const Colour& toggledOffColour,
  34412. const Colour& toggledOnColour)
  34413. {
  34414. if (backgroundOff != toggledOffColour
  34415. || backgroundOn != toggledOnColour)
  34416. {
  34417. backgroundOff = toggledOffColour;
  34418. backgroundOn = toggledOnColour;
  34419. repaint();
  34420. }
  34421. }
  34422. const Colour& DrawableButton::getBackgroundColour() const throw()
  34423. {
  34424. return getToggleState() ? backgroundOn
  34425. : backgroundOff;
  34426. }
  34427. void DrawableButton::setEdgeIndent (const int numPixelsIndent)
  34428. {
  34429. edgeIndent = numPixelsIndent;
  34430. repaint();
  34431. }
  34432. void DrawableButton::paintButton (Graphics& g,
  34433. bool isMouseOverButton,
  34434. bool isButtonDown)
  34435. {
  34436. Rectangle<int> imageSpace;
  34437. if (style == ImageOnButtonBackground)
  34438. {
  34439. const int insetX = getWidth() / 4;
  34440. const int insetY = getHeight() / 4;
  34441. imageSpace.setBounds (insetX, insetY, getWidth() - insetX * 2, getHeight() - insetY * 2);
  34442. getLookAndFeel().drawButtonBackground (g, *this,
  34443. getBackgroundColour(),
  34444. isMouseOverButton,
  34445. isButtonDown);
  34446. }
  34447. else
  34448. {
  34449. g.fillAll (getBackgroundColour());
  34450. const int textH = (style == ImageAboveTextLabel)
  34451. ? jmin (16, proportionOfHeight (0.25f))
  34452. : 0;
  34453. const int indentX = jmin (edgeIndent, proportionOfWidth (0.3f));
  34454. const int indentY = jmin (edgeIndent, proportionOfHeight (0.3f));
  34455. imageSpace.setBounds (indentX, indentY,
  34456. getWidth() - indentX * 2,
  34457. getHeight() - indentY * 2 - textH);
  34458. if (textH > 0)
  34459. {
  34460. g.setFont ((float) textH);
  34461. g.setColour (Colours::black.withAlpha (isEnabled() ? 1.0f : 0.4f));
  34462. g.drawFittedText (getButtonText(),
  34463. 2, getHeight() - textH - 1,
  34464. getWidth() - 4, textH,
  34465. Justification::centred, 1);
  34466. }
  34467. }
  34468. g.setImageResamplingQuality (Graphics::mediumResamplingQuality);
  34469. g.setOpacity (1.0f);
  34470. const Drawable* imageToDraw = 0;
  34471. if (isEnabled())
  34472. {
  34473. imageToDraw = getCurrentImage();
  34474. }
  34475. else
  34476. {
  34477. imageToDraw = getToggleState() ? disabledImageOn
  34478. : disabledImage;
  34479. if (imageToDraw == 0)
  34480. {
  34481. g.setOpacity (0.4f);
  34482. imageToDraw = getNormalImage();
  34483. }
  34484. }
  34485. if (imageToDraw != 0)
  34486. {
  34487. if (style == ImageRaw)
  34488. {
  34489. imageToDraw->draw (g, 1.0f);
  34490. }
  34491. else
  34492. {
  34493. imageToDraw->drawWithin (g,
  34494. imageSpace.getX(),
  34495. imageSpace.getY(),
  34496. imageSpace.getWidth(),
  34497. imageSpace.getHeight(),
  34498. RectanglePlacement::centred,
  34499. 1.0f);
  34500. }
  34501. }
  34502. }
  34503. const Drawable* DrawableButton::getCurrentImage() const throw()
  34504. {
  34505. if (isDown())
  34506. return getDownImage();
  34507. if (isOver())
  34508. return getOverImage();
  34509. return getNormalImage();
  34510. }
  34511. const Drawable* DrawableButton::getNormalImage() const throw()
  34512. {
  34513. return (getToggleState() && normalImageOn != 0) ? normalImageOn
  34514. : normalImage;
  34515. }
  34516. const Drawable* DrawableButton::getOverImage() const throw()
  34517. {
  34518. const Drawable* d = normalImage;
  34519. if (getToggleState())
  34520. {
  34521. if (overImageOn != 0)
  34522. d = overImageOn;
  34523. else if (normalImageOn != 0)
  34524. d = normalImageOn;
  34525. else if (overImage != 0)
  34526. d = overImage;
  34527. }
  34528. else
  34529. {
  34530. if (overImage != 0)
  34531. d = overImage;
  34532. }
  34533. return d;
  34534. }
  34535. const Drawable* DrawableButton::getDownImage() const throw()
  34536. {
  34537. const Drawable* d = normalImage;
  34538. if (getToggleState())
  34539. {
  34540. if (downImageOn != 0)
  34541. d = downImageOn;
  34542. else if (overImageOn != 0)
  34543. d = overImageOn;
  34544. else if (normalImageOn != 0)
  34545. d = normalImageOn;
  34546. else if (downImage != 0)
  34547. d = downImage;
  34548. else
  34549. d = getOverImage();
  34550. }
  34551. else
  34552. {
  34553. if (downImage != 0)
  34554. d = downImage;
  34555. else
  34556. d = getOverImage();
  34557. }
  34558. return d;
  34559. }
  34560. END_JUCE_NAMESPACE
  34561. /*** End of inlined file: juce_DrawableButton.cpp ***/
  34562. /*** Start of inlined file: juce_HyperlinkButton.cpp ***/
  34563. BEGIN_JUCE_NAMESPACE
  34564. HyperlinkButton::HyperlinkButton (const String& linkText,
  34565. const URL& linkURL)
  34566. : Button (linkText),
  34567. url (linkURL),
  34568. font (14.0f, Font::underlined),
  34569. resizeFont (true),
  34570. justification (Justification::centred)
  34571. {
  34572. setMouseCursor (MouseCursor::PointingHandCursor);
  34573. setTooltip (linkURL.toString (false));
  34574. }
  34575. HyperlinkButton::~HyperlinkButton()
  34576. {
  34577. }
  34578. void HyperlinkButton::setFont (const Font& newFont,
  34579. const bool resizeToMatchComponentHeight,
  34580. const Justification& justificationType)
  34581. {
  34582. font = newFont;
  34583. resizeFont = resizeToMatchComponentHeight;
  34584. justification = justificationType;
  34585. repaint();
  34586. }
  34587. void HyperlinkButton::setURL (const URL& newURL) throw()
  34588. {
  34589. url = newURL;
  34590. setTooltip (newURL.toString (false));
  34591. }
  34592. const Font HyperlinkButton::getFontToUse() const
  34593. {
  34594. Font f (font);
  34595. if (resizeFont)
  34596. f.setHeight (getHeight() * 0.7f);
  34597. return f;
  34598. }
  34599. void HyperlinkButton::changeWidthToFitText()
  34600. {
  34601. setSize (getFontToUse().getStringWidth (getName()) + 6, getHeight());
  34602. }
  34603. void HyperlinkButton::colourChanged()
  34604. {
  34605. repaint();
  34606. }
  34607. void HyperlinkButton::clicked()
  34608. {
  34609. if (url.isWellFormed())
  34610. url.launchInDefaultBrowser();
  34611. }
  34612. void HyperlinkButton::paintButton (Graphics& g,
  34613. bool isMouseOverButton,
  34614. bool isButtonDown)
  34615. {
  34616. const Colour textColour (findColour (textColourId));
  34617. if (isEnabled())
  34618. g.setColour ((isMouseOverButton) ? textColour.darker ((isButtonDown) ? 1.3f : 0.4f)
  34619. : textColour);
  34620. else
  34621. g.setColour (textColour.withMultipliedAlpha (0.4f));
  34622. g.setFont (getFontToUse());
  34623. g.drawText (getButtonText(),
  34624. 2, 0, getWidth() - 2, getHeight(),
  34625. justification.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  34626. true);
  34627. }
  34628. END_JUCE_NAMESPACE
  34629. /*** End of inlined file: juce_HyperlinkButton.cpp ***/
  34630. /*** Start of inlined file: juce_ImageButton.cpp ***/
  34631. BEGIN_JUCE_NAMESPACE
  34632. ImageButton::ImageButton (const String& text_)
  34633. : Button (text_),
  34634. scaleImageToFit (true),
  34635. preserveProportions (true),
  34636. alphaThreshold (0),
  34637. imageX (0),
  34638. imageY (0),
  34639. imageW (0),
  34640. imageH (0),
  34641. normalImage (0),
  34642. overImage (0),
  34643. downImage (0)
  34644. {
  34645. }
  34646. ImageButton::~ImageButton()
  34647. {
  34648. }
  34649. void ImageButton::setImages (const bool resizeButtonNowToFitThisImage,
  34650. const bool rescaleImagesWhenButtonSizeChanges,
  34651. const bool preserveImageProportions,
  34652. const Image& normalImage_,
  34653. const float imageOpacityWhenNormal,
  34654. const Colour& overlayColourWhenNormal,
  34655. const Image& overImage_,
  34656. const float imageOpacityWhenOver,
  34657. const Colour& overlayColourWhenOver,
  34658. const Image& downImage_,
  34659. const float imageOpacityWhenDown,
  34660. const Colour& overlayColourWhenDown,
  34661. const float hitTestAlphaThreshold)
  34662. {
  34663. normalImage = normalImage_;
  34664. overImage = overImage_;
  34665. downImage = downImage_;
  34666. if (resizeButtonNowToFitThisImage && normalImage.isValid())
  34667. {
  34668. imageW = normalImage.getWidth();
  34669. imageH = normalImage.getHeight();
  34670. setSize (imageW, imageH);
  34671. }
  34672. scaleImageToFit = rescaleImagesWhenButtonSizeChanges;
  34673. preserveProportions = preserveImageProportions;
  34674. normalOpacity = imageOpacityWhenNormal;
  34675. normalOverlay = overlayColourWhenNormal;
  34676. overOpacity = imageOpacityWhenOver;
  34677. overOverlay = overlayColourWhenOver;
  34678. downOpacity = imageOpacityWhenDown;
  34679. downOverlay = overlayColourWhenDown;
  34680. alphaThreshold = (unsigned char) jlimit (0, 0xff, roundToInt (255.0f * hitTestAlphaThreshold));
  34681. repaint();
  34682. }
  34683. const Image ImageButton::getCurrentImage() const
  34684. {
  34685. if (isDown() || getToggleState())
  34686. return getDownImage();
  34687. if (isOver())
  34688. return getOverImage();
  34689. return getNormalImage();
  34690. }
  34691. const Image ImageButton::getNormalImage() const
  34692. {
  34693. return normalImage;
  34694. }
  34695. const Image ImageButton::getOverImage() const
  34696. {
  34697. return overImage.isValid() ? overImage
  34698. : normalImage;
  34699. }
  34700. const Image ImageButton::getDownImage() const
  34701. {
  34702. return downImage.isValid() ? downImage
  34703. : getOverImage();
  34704. }
  34705. void ImageButton::paintButton (Graphics& g,
  34706. bool isMouseOverButton,
  34707. bool isButtonDown)
  34708. {
  34709. if (! isEnabled())
  34710. {
  34711. isMouseOverButton = false;
  34712. isButtonDown = false;
  34713. }
  34714. Image im (getCurrentImage());
  34715. if (im.isValid())
  34716. {
  34717. const int iw = im.getWidth();
  34718. const int ih = im.getHeight();
  34719. imageW = getWidth();
  34720. imageH = getHeight();
  34721. imageX = (imageW - iw) >> 1;
  34722. imageY = (imageH - ih) >> 1;
  34723. if (scaleImageToFit)
  34724. {
  34725. if (preserveProportions)
  34726. {
  34727. int newW, newH;
  34728. const float imRatio = ih / (float)iw;
  34729. const float destRatio = imageH / (float)imageW;
  34730. if (imRatio > destRatio)
  34731. {
  34732. newW = roundToInt (imageH / imRatio);
  34733. newH = imageH;
  34734. }
  34735. else
  34736. {
  34737. newW = imageW;
  34738. newH = roundToInt (imageW * imRatio);
  34739. }
  34740. imageX = (imageW - newW) / 2;
  34741. imageY = (imageH - newH) / 2;
  34742. imageW = newW;
  34743. imageH = newH;
  34744. }
  34745. else
  34746. {
  34747. imageX = 0;
  34748. imageY = 0;
  34749. }
  34750. }
  34751. if (! scaleImageToFit)
  34752. {
  34753. imageW = iw;
  34754. imageH = ih;
  34755. }
  34756. getLookAndFeel().drawImageButton (g, &im, imageX, imageY, imageW, imageH,
  34757. isButtonDown ? downOverlay
  34758. : (isMouseOverButton ? overOverlay
  34759. : normalOverlay),
  34760. isButtonDown ? downOpacity
  34761. : (isMouseOverButton ? overOpacity
  34762. : normalOpacity),
  34763. *this);
  34764. }
  34765. }
  34766. bool ImageButton::hitTest (int x, int y)
  34767. {
  34768. if (alphaThreshold == 0)
  34769. return true;
  34770. Image im (getCurrentImage());
  34771. return im.isNull() || (imageW > 0 && imageH > 0
  34772. && alphaThreshold < im.getPixelAt (((x - imageX) * im.getWidth()) / imageW,
  34773. ((y - imageY) * im.getHeight()) / imageH).getAlpha());
  34774. }
  34775. END_JUCE_NAMESPACE
  34776. /*** End of inlined file: juce_ImageButton.cpp ***/
  34777. /*** Start of inlined file: juce_ShapeButton.cpp ***/
  34778. BEGIN_JUCE_NAMESPACE
  34779. ShapeButton::ShapeButton (const String& text_,
  34780. const Colour& normalColour_,
  34781. const Colour& overColour_,
  34782. const Colour& downColour_)
  34783. : Button (text_),
  34784. normalColour (normalColour_),
  34785. overColour (overColour_),
  34786. downColour (downColour_),
  34787. maintainShapeProportions (false),
  34788. outlineWidth (0.0f)
  34789. {
  34790. }
  34791. ShapeButton::~ShapeButton()
  34792. {
  34793. }
  34794. void ShapeButton::setColours (const Colour& newNormalColour,
  34795. const Colour& newOverColour,
  34796. const Colour& newDownColour)
  34797. {
  34798. normalColour = newNormalColour;
  34799. overColour = newOverColour;
  34800. downColour = newDownColour;
  34801. }
  34802. void ShapeButton::setOutline (const Colour& newOutlineColour,
  34803. const float newOutlineWidth)
  34804. {
  34805. outlineColour = newOutlineColour;
  34806. outlineWidth = newOutlineWidth;
  34807. }
  34808. void ShapeButton::setShape (const Path& newShape,
  34809. const bool resizeNowToFitThisShape,
  34810. const bool maintainShapeProportions_,
  34811. const bool hasShadow)
  34812. {
  34813. shape = newShape;
  34814. maintainShapeProportions = maintainShapeProportions_;
  34815. shadow.setShadowProperties (3.0f, 0.5f, 0, 0);
  34816. setComponentEffect ((hasShadow) ? &shadow : 0);
  34817. if (resizeNowToFitThisShape)
  34818. {
  34819. Rectangle<float> bounds (shape.getBounds());
  34820. if (hasShadow)
  34821. bounds.expand (4.0f, 4.0f);
  34822. shape.applyTransform (AffineTransform::translation (-bounds.getX(), -bounds.getY()));
  34823. setSize (1 + (int) (bounds.getWidth() + outlineWidth),
  34824. 1 + (int) (bounds.getHeight() + outlineWidth));
  34825. }
  34826. }
  34827. void ShapeButton::paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  34828. {
  34829. if (! isEnabled())
  34830. {
  34831. isMouseOverButton = false;
  34832. isButtonDown = false;
  34833. }
  34834. g.setColour ((isButtonDown) ? downColour
  34835. : (isMouseOverButton) ? overColour
  34836. : normalColour);
  34837. int w = getWidth();
  34838. int h = getHeight();
  34839. if (getComponentEffect() != 0)
  34840. {
  34841. w -= 4;
  34842. h -= 4;
  34843. }
  34844. const float offset = (outlineWidth * 0.5f) + (isButtonDown ? 1.5f : 0.0f);
  34845. const AffineTransform trans (shape.getTransformToScaleToFit (offset, offset,
  34846. w - offset - outlineWidth,
  34847. h - offset - outlineWidth,
  34848. maintainShapeProportions));
  34849. g.fillPath (shape, trans);
  34850. if (outlineWidth > 0.0f)
  34851. {
  34852. g.setColour (outlineColour);
  34853. g.strokePath (shape, PathStrokeType (outlineWidth), trans);
  34854. }
  34855. }
  34856. END_JUCE_NAMESPACE
  34857. /*** End of inlined file: juce_ShapeButton.cpp ***/
  34858. /*** Start of inlined file: juce_TextButton.cpp ***/
  34859. BEGIN_JUCE_NAMESPACE
  34860. TextButton::TextButton (const String& name,
  34861. const String& toolTip)
  34862. : Button (name)
  34863. {
  34864. setTooltip (toolTip);
  34865. }
  34866. TextButton::~TextButton()
  34867. {
  34868. }
  34869. void TextButton::paintButton (Graphics& g,
  34870. bool isMouseOverButton,
  34871. bool isButtonDown)
  34872. {
  34873. getLookAndFeel().drawButtonBackground (g, *this,
  34874. findColour (getToggleState() ? buttonOnColourId
  34875. : buttonColourId),
  34876. isMouseOverButton,
  34877. isButtonDown);
  34878. getLookAndFeel().drawButtonText (g, *this,
  34879. isMouseOverButton,
  34880. isButtonDown);
  34881. }
  34882. void TextButton::colourChanged()
  34883. {
  34884. repaint();
  34885. }
  34886. const Font TextButton::getFont()
  34887. {
  34888. return Font (jmin (15.0f, getHeight() * 0.6f));
  34889. }
  34890. void TextButton::changeWidthToFitText (const int newHeight)
  34891. {
  34892. if (newHeight >= 0)
  34893. setSize (jmax (1, getWidth()), newHeight);
  34894. setSize (getFont().getStringWidth (getButtonText()) + getHeight(),
  34895. getHeight());
  34896. }
  34897. END_JUCE_NAMESPACE
  34898. /*** End of inlined file: juce_TextButton.cpp ***/
  34899. /*** Start of inlined file: juce_ToggleButton.cpp ***/
  34900. BEGIN_JUCE_NAMESPACE
  34901. ToggleButton::ToggleButton (const String& buttonText)
  34902. : Button (buttonText)
  34903. {
  34904. setClickingTogglesState (true);
  34905. }
  34906. ToggleButton::~ToggleButton()
  34907. {
  34908. }
  34909. void ToggleButton::paintButton (Graphics& g,
  34910. bool isMouseOverButton,
  34911. bool isButtonDown)
  34912. {
  34913. getLookAndFeel().drawToggleButton (g, *this,
  34914. isMouseOverButton,
  34915. isButtonDown);
  34916. }
  34917. void ToggleButton::changeWidthToFitText()
  34918. {
  34919. getLookAndFeel().changeToggleButtonWidthToFitText (*this);
  34920. }
  34921. void ToggleButton::colourChanged()
  34922. {
  34923. repaint();
  34924. }
  34925. END_JUCE_NAMESPACE
  34926. /*** End of inlined file: juce_ToggleButton.cpp ***/
  34927. /*** Start of inlined file: juce_ToolbarButton.cpp ***/
  34928. BEGIN_JUCE_NAMESPACE
  34929. ToolbarButton::ToolbarButton (const int itemId_,
  34930. const String& buttonText,
  34931. Drawable* const normalImage_,
  34932. Drawable* const toggledOnImage_)
  34933. : ToolbarItemComponent (itemId_, buttonText, true),
  34934. normalImage (normalImage_),
  34935. toggledOnImage (toggledOnImage_)
  34936. {
  34937. jassert (normalImage_ != 0);
  34938. }
  34939. ToolbarButton::~ToolbarButton()
  34940. {
  34941. }
  34942. bool ToolbarButton::getToolbarItemSizes (int toolbarDepth,
  34943. bool /*isToolbarVertical*/,
  34944. int& preferredSize,
  34945. int& minSize, int& maxSize)
  34946. {
  34947. preferredSize = minSize = maxSize = toolbarDepth;
  34948. return true;
  34949. }
  34950. void ToolbarButton::paintButtonArea (Graphics& g,
  34951. int width, int height,
  34952. bool /*isMouseOver*/,
  34953. bool /*isMouseDown*/)
  34954. {
  34955. Drawable* d = normalImage;
  34956. if (getToggleState() && toggledOnImage != 0)
  34957. d = toggledOnImage;
  34958. if (! isEnabled())
  34959. {
  34960. Image im (Image::ARGB, width, height, true);
  34961. {
  34962. Graphics g2 (im);
  34963. d->drawWithin (g2, 0, 0, width, height, RectanglePlacement::centred, 1.0f);
  34964. }
  34965. im.desaturate();
  34966. g.drawImageAt (im, 0, 0);
  34967. }
  34968. else
  34969. {
  34970. d->drawWithin (g, 0, 0, width, height, RectanglePlacement::centred, 1.0f);
  34971. }
  34972. }
  34973. void ToolbarButton::contentAreaChanged (const Rectangle<int>&)
  34974. {
  34975. }
  34976. END_JUCE_NAMESPACE
  34977. /*** End of inlined file: juce_ToolbarButton.cpp ***/
  34978. /*** Start of inlined file: juce_CodeDocument.cpp ***/
  34979. BEGIN_JUCE_NAMESPACE
  34980. class CodeDocumentLine
  34981. {
  34982. public:
  34983. CodeDocumentLine (const juce_wchar* const line_,
  34984. const int lineLength_,
  34985. const int numNewLineChars,
  34986. const int lineStartInFile_)
  34987. : line (line_, lineLength_),
  34988. lineStartInFile (lineStartInFile_),
  34989. lineLength (lineLength_),
  34990. lineLengthWithoutNewLines (lineLength_ - numNewLineChars)
  34991. {
  34992. }
  34993. ~CodeDocumentLine()
  34994. {
  34995. }
  34996. static void createLines (Array <CodeDocumentLine*>& newLines, const String& text)
  34997. {
  34998. const juce_wchar* const t = text;
  34999. int pos = 0;
  35000. while (t [pos] != 0)
  35001. {
  35002. const int startOfLine = pos;
  35003. int numNewLineChars = 0;
  35004. while (t[pos] != 0)
  35005. {
  35006. if (t[pos] == '\r')
  35007. {
  35008. ++numNewLineChars;
  35009. ++pos;
  35010. if (t[pos] == '\n')
  35011. {
  35012. ++numNewLineChars;
  35013. ++pos;
  35014. }
  35015. break;
  35016. }
  35017. if (t[pos] == '\n')
  35018. {
  35019. ++numNewLineChars;
  35020. ++pos;
  35021. break;
  35022. }
  35023. ++pos;
  35024. }
  35025. newLines.add (new CodeDocumentLine (t + startOfLine, pos - startOfLine,
  35026. numNewLineChars, startOfLine));
  35027. }
  35028. jassert (pos == text.length());
  35029. }
  35030. bool endsWithLineBreak() const throw()
  35031. {
  35032. return lineLengthWithoutNewLines != lineLength;
  35033. }
  35034. void updateLength() throw()
  35035. {
  35036. lineLengthWithoutNewLines = lineLength = line.length();
  35037. while (lineLengthWithoutNewLines > 0
  35038. && (line [lineLengthWithoutNewLines - 1] == '\n'
  35039. || line [lineLengthWithoutNewLines - 1] == '\r'))
  35040. {
  35041. --lineLengthWithoutNewLines;
  35042. }
  35043. }
  35044. String line;
  35045. int lineStartInFile, lineLength, lineLengthWithoutNewLines;
  35046. };
  35047. CodeDocument::Iterator::Iterator (CodeDocument* const document_)
  35048. : document (document_),
  35049. currentLine (document_->lines[0]),
  35050. line (0),
  35051. position (0)
  35052. {
  35053. }
  35054. CodeDocument::Iterator::Iterator (const CodeDocument::Iterator& other)
  35055. : document (other.document),
  35056. currentLine (other.currentLine),
  35057. line (other.line),
  35058. position (other.position)
  35059. {
  35060. }
  35061. CodeDocument::Iterator& CodeDocument::Iterator::operator= (const CodeDocument::Iterator& other) throw()
  35062. {
  35063. document = other.document;
  35064. currentLine = other.currentLine;
  35065. line = other.line;
  35066. position = other.position;
  35067. return *this;
  35068. }
  35069. CodeDocument::Iterator::~Iterator() throw()
  35070. {
  35071. }
  35072. juce_wchar CodeDocument::Iterator::nextChar()
  35073. {
  35074. if (currentLine == 0)
  35075. return 0;
  35076. jassert (currentLine == document->lines.getUnchecked (line));
  35077. const juce_wchar result = currentLine->line [position - currentLine->lineStartInFile];
  35078. if (++position >= currentLine->lineStartInFile + currentLine->lineLength)
  35079. {
  35080. ++line;
  35081. currentLine = document->lines [line];
  35082. }
  35083. return result;
  35084. }
  35085. void CodeDocument::Iterator::skip()
  35086. {
  35087. if (currentLine != 0)
  35088. {
  35089. jassert (currentLine == document->lines.getUnchecked (line));
  35090. if (++position >= currentLine->lineStartInFile + currentLine->lineLength)
  35091. {
  35092. ++line;
  35093. currentLine = document->lines [line];
  35094. }
  35095. }
  35096. }
  35097. void CodeDocument::Iterator::skipToEndOfLine()
  35098. {
  35099. if (currentLine != 0)
  35100. {
  35101. jassert (currentLine == document->lines.getUnchecked (line));
  35102. ++line;
  35103. currentLine = document->lines [line];
  35104. if (currentLine != 0)
  35105. position = currentLine->lineStartInFile;
  35106. else
  35107. position = document->getNumCharacters();
  35108. }
  35109. }
  35110. juce_wchar CodeDocument::Iterator::peekNextChar() const
  35111. {
  35112. if (currentLine == 0)
  35113. return 0;
  35114. jassert (currentLine == document->lines.getUnchecked (line));
  35115. return const_cast <const String&> (currentLine->line) [position - currentLine->lineStartInFile];
  35116. }
  35117. void CodeDocument::Iterator::skipWhitespace()
  35118. {
  35119. while (CharacterFunctions::isWhitespace (peekNextChar()))
  35120. skip();
  35121. }
  35122. bool CodeDocument::Iterator::isEOF() const throw()
  35123. {
  35124. return currentLine == 0;
  35125. }
  35126. CodeDocument::Position::Position() throw()
  35127. : owner (0), characterPos (0), line (0),
  35128. indexInLine (0), positionMaintained (false)
  35129. {
  35130. }
  35131. CodeDocument::Position::Position (const CodeDocument* const ownerDocument,
  35132. const int line_, const int indexInLine_) throw()
  35133. : owner (const_cast <CodeDocument*> (ownerDocument)),
  35134. characterPos (0), line (line_),
  35135. indexInLine (indexInLine_), positionMaintained (false)
  35136. {
  35137. setLineAndIndex (line_, indexInLine_);
  35138. }
  35139. CodeDocument::Position::Position (const CodeDocument* const ownerDocument,
  35140. const int characterPos_) throw()
  35141. : owner (const_cast <CodeDocument*> (ownerDocument)),
  35142. positionMaintained (false)
  35143. {
  35144. setPosition (characterPos_);
  35145. }
  35146. CodeDocument::Position::Position (const Position& other) throw()
  35147. : owner (other.owner), characterPos (other.characterPos), line (other.line),
  35148. indexInLine (other.indexInLine), positionMaintained (false)
  35149. {
  35150. jassert (*this == other);
  35151. }
  35152. CodeDocument::Position::~Position() throw()
  35153. {
  35154. setPositionMaintained (false);
  35155. }
  35156. CodeDocument::Position& CodeDocument::Position::operator= (const Position& other) throw()
  35157. {
  35158. if (this != &other)
  35159. {
  35160. const bool wasPositionMaintained = positionMaintained;
  35161. if (owner != other.owner)
  35162. setPositionMaintained (false);
  35163. owner = other.owner;
  35164. line = other.line;
  35165. indexInLine = other.indexInLine;
  35166. characterPos = other.characterPos;
  35167. setPositionMaintained (wasPositionMaintained);
  35168. jassert (*this == other);
  35169. }
  35170. return *this;
  35171. }
  35172. bool CodeDocument::Position::operator== (const Position& other) const throw()
  35173. {
  35174. jassert ((characterPos == other.characterPos)
  35175. == (line == other.line && indexInLine == other.indexInLine));
  35176. return characterPos == other.characterPos
  35177. && line == other.line
  35178. && indexInLine == other.indexInLine
  35179. && owner == other.owner;
  35180. }
  35181. bool CodeDocument::Position::operator!= (const Position& other) const throw()
  35182. {
  35183. return ! operator== (other);
  35184. }
  35185. void CodeDocument::Position::setLineAndIndex (const int newLine, const int newIndexInLine) throw()
  35186. {
  35187. jassert (owner != 0);
  35188. if (owner->lines.size() == 0)
  35189. {
  35190. line = 0;
  35191. indexInLine = 0;
  35192. characterPos = 0;
  35193. }
  35194. else
  35195. {
  35196. if (newLine >= owner->lines.size())
  35197. {
  35198. line = owner->lines.size() - 1;
  35199. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  35200. jassert (l != 0);
  35201. indexInLine = l->lineLengthWithoutNewLines;
  35202. characterPos = l->lineStartInFile + indexInLine;
  35203. }
  35204. else
  35205. {
  35206. line = jmax (0, newLine);
  35207. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  35208. jassert (l != 0);
  35209. if (l->lineLengthWithoutNewLines > 0)
  35210. indexInLine = jlimit (0, l->lineLengthWithoutNewLines, newIndexInLine);
  35211. else
  35212. indexInLine = 0;
  35213. characterPos = l->lineStartInFile + indexInLine;
  35214. }
  35215. }
  35216. }
  35217. void CodeDocument::Position::setPosition (const int newPosition) throw()
  35218. {
  35219. jassert (owner != 0);
  35220. line = 0;
  35221. indexInLine = 0;
  35222. characterPos = 0;
  35223. if (newPosition > 0)
  35224. {
  35225. int lineStart = 0;
  35226. int lineEnd = owner->lines.size();
  35227. for (;;)
  35228. {
  35229. if (lineEnd - lineStart < 4)
  35230. {
  35231. for (int i = lineStart; i < lineEnd; ++i)
  35232. {
  35233. CodeDocumentLine* const l = owner->lines.getUnchecked (i);
  35234. int index = newPosition - l->lineStartInFile;
  35235. if (index >= 0 && (index < l->lineLength || i == lineEnd - 1))
  35236. {
  35237. line = i;
  35238. indexInLine = jmin (l->lineLengthWithoutNewLines, index);
  35239. characterPos = l->lineStartInFile + indexInLine;
  35240. }
  35241. }
  35242. break;
  35243. }
  35244. else
  35245. {
  35246. const int midIndex = (lineStart + lineEnd + 1) / 2;
  35247. CodeDocumentLine* const mid = owner->lines.getUnchecked (midIndex);
  35248. if (newPosition >= mid->lineStartInFile)
  35249. lineStart = midIndex;
  35250. else
  35251. lineEnd = midIndex;
  35252. }
  35253. }
  35254. }
  35255. }
  35256. void CodeDocument::Position::moveBy (int characterDelta) throw()
  35257. {
  35258. jassert (owner != 0);
  35259. if (characterDelta == 1)
  35260. {
  35261. setPosition (getPosition());
  35262. // If moving right, make sure we don't get stuck between the \r and \n characters..
  35263. if (line < owner->lines.size())
  35264. {
  35265. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  35266. if (indexInLine + characterDelta < l->lineLength
  35267. && indexInLine + characterDelta >= l->lineLengthWithoutNewLines + 1)
  35268. ++characterDelta;
  35269. }
  35270. }
  35271. setPosition (characterPos + characterDelta);
  35272. }
  35273. const CodeDocument::Position CodeDocument::Position::movedBy (const int characterDelta) const throw()
  35274. {
  35275. CodeDocument::Position p (*this);
  35276. p.moveBy (characterDelta);
  35277. return p;
  35278. }
  35279. const CodeDocument::Position CodeDocument::Position::movedByLines (const int deltaLines) const throw()
  35280. {
  35281. CodeDocument::Position p (*this);
  35282. p.setLineAndIndex (getLineNumber() + deltaLines, getIndexInLine());
  35283. return p;
  35284. }
  35285. const juce_wchar CodeDocument::Position::getCharacter() const throw()
  35286. {
  35287. const CodeDocumentLine* const l = owner->lines [line];
  35288. return l == 0 ? 0 : l->line [getIndexInLine()];
  35289. }
  35290. const String CodeDocument::Position::getLineText() const throw()
  35291. {
  35292. const CodeDocumentLine* const l = owner->lines [line];
  35293. return l == 0 ? String::empty : l->line;
  35294. }
  35295. void CodeDocument::Position::setPositionMaintained (const bool isMaintained) throw()
  35296. {
  35297. if (isMaintained != positionMaintained)
  35298. {
  35299. positionMaintained = isMaintained;
  35300. if (owner != 0)
  35301. {
  35302. if (isMaintained)
  35303. {
  35304. jassert (! owner->positionsToMaintain.contains (this));
  35305. owner->positionsToMaintain.add (this);
  35306. }
  35307. else
  35308. {
  35309. // If this happens, you may have deleted the document while there are Position objects that are still using it...
  35310. jassert (owner->positionsToMaintain.contains (this));
  35311. owner->positionsToMaintain.removeValue (this);
  35312. }
  35313. }
  35314. }
  35315. }
  35316. CodeDocument::CodeDocument()
  35317. : undoManager (std::numeric_limits<int>::max(), 10000),
  35318. currentActionIndex (0),
  35319. indexOfSavedState (-1),
  35320. maximumLineLength (-1),
  35321. newLineChars ("\r\n")
  35322. {
  35323. }
  35324. CodeDocument::~CodeDocument()
  35325. {
  35326. }
  35327. const String CodeDocument::getAllContent() const throw()
  35328. {
  35329. return getTextBetween (Position (this, 0),
  35330. Position (this, lines.size(), 0));
  35331. }
  35332. const String CodeDocument::getTextBetween (const Position& start, const Position& end) const throw()
  35333. {
  35334. if (end.getPosition() <= start.getPosition())
  35335. return String::empty;
  35336. const int startLine = start.getLineNumber();
  35337. const int endLine = end.getLineNumber();
  35338. if (startLine == endLine)
  35339. {
  35340. CodeDocumentLine* const line = lines [startLine];
  35341. return (line == 0) ? String::empty : line->line.substring (start.getIndexInLine(), end.getIndexInLine());
  35342. }
  35343. String result;
  35344. result.preallocateStorage (end.getPosition() - start.getPosition() + 4);
  35345. String::Concatenator concatenator (result);
  35346. const int maxLine = jmin (lines.size() - 1, endLine);
  35347. for (int i = jmax (0, startLine); i <= maxLine; ++i)
  35348. {
  35349. const CodeDocumentLine* line = lines.getUnchecked(i);
  35350. int len = line->lineLength;
  35351. if (i == startLine)
  35352. {
  35353. const int index = start.getIndexInLine();
  35354. concatenator.append (line->line.substring (index, len));
  35355. }
  35356. else if (i == endLine)
  35357. {
  35358. len = end.getIndexInLine();
  35359. concatenator.append (line->line.substring (0, len));
  35360. }
  35361. else
  35362. {
  35363. concatenator.append (line->line);
  35364. }
  35365. }
  35366. return result;
  35367. }
  35368. int CodeDocument::getNumCharacters() const throw()
  35369. {
  35370. const CodeDocumentLine* const lastLine = lines.getLast();
  35371. return (lastLine == 0) ? 0 : lastLine->lineStartInFile + lastLine->lineLength;
  35372. }
  35373. const String CodeDocument::getLine (const int lineIndex) const throw()
  35374. {
  35375. const CodeDocumentLine* const line = lines [lineIndex];
  35376. return (line == 0) ? String::empty : line->line;
  35377. }
  35378. int CodeDocument::getMaximumLineLength() throw()
  35379. {
  35380. if (maximumLineLength < 0)
  35381. {
  35382. maximumLineLength = 0;
  35383. for (int i = lines.size(); --i >= 0;)
  35384. maximumLineLength = jmax (maximumLineLength, lines.getUnchecked(i)->lineLength);
  35385. }
  35386. return maximumLineLength;
  35387. }
  35388. void CodeDocument::deleteSection (const Position& startPosition, const Position& endPosition)
  35389. {
  35390. remove (startPosition.getPosition(), endPosition.getPosition(), true);
  35391. }
  35392. void CodeDocument::insertText (const Position& position, const String& text)
  35393. {
  35394. insert (text, position.getPosition(), true);
  35395. }
  35396. void CodeDocument::replaceAllContent (const String& newContent)
  35397. {
  35398. remove (0, getNumCharacters(), true);
  35399. insert (newContent, 0, true);
  35400. }
  35401. bool CodeDocument::loadFromStream (InputStream& stream)
  35402. {
  35403. replaceAllContent (stream.readEntireStreamAsString());
  35404. setSavePoint();
  35405. clearUndoHistory();
  35406. return true;
  35407. }
  35408. bool CodeDocument::writeToStream (OutputStream& stream)
  35409. {
  35410. for (int i = 0; i < lines.size(); ++i)
  35411. {
  35412. String temp (lines.getUnchecked(i)->line); // use a copy to avoid bloating the memory footprint of the stored string.
  35413. const char* utf8 = temp.toUTF8();
  35414. if (! stream.write (utf8, (int) strlen (utf8)))
  35415. return false;
  35416. }
  35417. return true;
  35418. }
  35419. void CodeDocument::setNewLineCharacters (const String& newLine) throw()
  35420. {
  35421. jassert (newLine == "\r\n" || newLine == "\n" || newLine == "\r");
  35422. newLineChars = newLine;
  35423. }
  35424. void CodeDocument::newTransaction()
  35425. {
  35426. undoManager.beginNewTransaction (String::empty);
  35427. }
  35428. void CodeDocument::undo()
  35429. {
  35430. newTransaction();
  35431. undoManager.undo();
  35432. }
  35433. void CodeDocument::redo()
  35434. {
  35435. undoManager.redo();
  35436. }
  35437. void CodeDocument::clearUndoHistory()
  35438. {
  35439. undoManager.clearUndoHistory();
  35440. }
  35441. void CodeDocument::setSavePoint() throw()
  35442. {
  35443. indexOfSavedState = currentActionIndex;
  35444. }
  35445. bool CodeDocument::hasChangedSinceSavePoint() const throw()
  35446. {
  35447. return currentActionIndex != indexOfSavedState;
  35448. }
  35449. static int getCodeCharacterCategory (const juce_wchar character) throw()
  35450. {
  35451. return (CharacterFunctions::isLetterOrDigit (character) || character == '_')
  35452. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  35453. }
  35454. const CodeDocument::Position CodeDocument::findWordBreakAfter (const Position& position) const throw()
  35455. {
  35456. Position p (position);
  35457. const int maxDistance = 256;
  35458. int i = 0;
  35459. while (i < maxDistance
  35460. && CharacterFunctions::isWhitespace (p.getCharacter())
  35461. && (i == 0 || (p.getCharacter() != '\n'
  35462. && p.getCharacter() != '\r')))
  35463. {
  35464. ++i;
  35465. p.moveBy (1);
  35466. }
  35467. if (i == 0)
  35468. {
  35469. const int type = getCodeCharacterCategory (p.getCharacter());
  35470. while (i < maxDistance && type == getCodeCharacterCategory (p.getCharacter()))
  35471. {
  35472. ++i;
  35473. p.moveBy (1);
  35474. }
  35475. while (i < maxDistance
  35476. && CharacterFunctions::isWhitespace (p.getCharacter())
  35477. && (i == 0 || (p.getCharacter() != '\n'
  35478. && p.getCharacter() != '\r')))
  35479. {
  35480. ++i;
  35481. p.moveBy (1);
  35482. }
  35483. }
  35484. return p;
  35485. }
  35486. const CodeDocument::Position CodeDocument::findWordBreakBefore (const Position& position) const throw()
  35487. {
  35488. Position p (position);
  35489. const int maxDistance = 256;
  35490. int i = 0;
  35491. bool stoppedAtLineStart = false;
  35492. while (i < maxDistance)
  35493. {
  35494. const juce_wchar c = p.movedBy (-1).getCharacter();
  35495. if (c == '\r' || c == '\n')
  35496. {
  35497. stoppedAtLineStart = true;
  35498. if (i > 0)
  35499. break;
  35500. }
  35501. if (! CharacterFunctions::isWhitespace (c))
  35502. break;
  35503. p.moveBy (-1);
  35504. ++i;
  35505. }
  35506. if (i < maxDistance && ! stoppedAtLineStart)
  35507. {
  35508. const int type = getCodeCharacterCategory (p.movedBy (-1).getCharacter());
  35509. while (i < maxDistance && type == getCodeCharacterCategory (p.movedBy (-1).getCharacter()))
  35510. {
  35511. p.moveBy (-1);
  35512. ++i;
  35513. }
  35514. }
  35515. return p;
  35516. }
  35517. void CodeDocument::checkLastLineStatus()
  35518. {
  35519. while (lines.size() > 0
  35520. && lines.getLast()->lineLength == 0
  35521. && (lines.size() == 1 || ! lines.getUnchecked (lines.size() - 2)->endsWithLineBreak()))
  35522. {
  35523. // remove any empty lines at the end if the preceding line doesn't end in a newline.
  35524. lines.removeLast();
  35525. }
  35526. const CodeDocumentLine* const lastLine = lines.getLast();
  35527. if (lastLine != 0 && lastLine->endsWithLineBreak())
  35528. {
  35529. // check that there's an empty line at the end if the preceding one ends in a newline..
  35530. lines.add (new CodeDocumentLine (String::empty, 0, 0, lastLine->lineStartInFile + lastLine->lineLength));
  35531. }
  35532. }
  35533. void CodeDocument::addListener (CodeDocument::Listener* const listener) throw()
  35534. {
  35535. listeners.add (listener);
  35536. }
  35537. void CodeDocument::removeListener (CodeDocument::Listener* const listener) throw()
  35538. {
  35539. listeners.remove (listener);
  35540. }
  35541. void CodeDocument::sendListenerChangeMessage (const int startLine, const int endLine)
  35542. {
  35543. Position startPos (this, startLine, 0);
  35544. Position endPos (this, endLine, 0);
  35545. listeners.call (&Listener::codeDocumentChanged, startPos, endPos);
  35546. }
  35547. class CodeDocumentInsertAction : public UndoableAction
  35548. {
  35549. CodeDocument& owner;
  35550. const String text;
  35551. int insertPos;
  35552. CodeDocumentInsertAction (const CodeDocumentInsertAction&);
  35553. CodeDocumentInsertAction& operator= (const CodeDocumentInsertAction&);
  35554. public:
  35555. CodeDocumentInsertAction (CodeDocument& owner_, const String& text_, const int insertPos_) throw()
  35556. : owner (owner_),
  35557. text (text_),
  35558. insertPos (insertPos_)
  35559. {
  35560. }
  35561. ~CodeDocumentInsertAction() {}
  35562. bool perform()
  35563. {
  35564. owner.currentActionIndex++;
  35565. owner.insert (text, insertPos, false);
  35566. return true;
  35567. }
  35568. bool undo()
  35569. {
  35570. owner.currentActionIndex--;
  35571. owner.remove (insertPos, insertPos + text.length(), false);
  35572. return true;
  35573. }
  35574. int getSizeInUnits() { return text.length() + 32; }
  35575. };
  35576. void CodeDocument::insert (const String& text, const int insertPos, const bool undoable)
  35577. {
  35578. if (text.isEmpty())
  35579. return;
  35580. if (undoable)
  35581. {
  35582. undoManager.perform (new CodeDocumentInsertAction (*this, text, insertPos));
  35583. }
  35584. else
  35585. {
  35586. Position pos (this, insertPos);
  35587. const int firstAffectedLine = pos.getLineNumber();
  35588. int lastAffectedLine = firstAffectedLine + 1;
  35589. CodeDocumentLine* const firstLine = lines [firstAffectedLine];
  35590. String textInsideOriginalLine (text);
  35591. if (firstLine != 0)
  35592. {
  35593. const int index = pos.getIndexInLine();
  35594. textInsideOriginalLine = firstLine->line.substring (0, index)
  35595. + textInsideOriginalLine
  35596. + firstLine->line.substring (index);
  35597. }
  35598. maximumLineLength = -1;
  35599. Array <CodeDocumentLine*> newLines;
  35600. CodeDocumentLine::createLines (newLines, textInsideOriginalLine);
  35601. jassert (newLines.size() > 0);
  35602. CodeDocumentLine* const newFirstLine = newLines.getUnchecked (0);
  35603. newFirstLine->lineStartInFile = firstLine != 0 ? firstLine->lineStartInFile : 0;
  35604. lines.set (firstAffectedLine, newFirstLine);
  35605. if (newLines.size() > 1)
  35606. {
  35607. for (int i = 1; i < newLines.size(); ++i)
  35608. {
  35609. CodeDocumentLine* const l = newLines.getUnchecked (i);
  35610. lines.insert (firstAffectedLine + i, l);
  35611. }
  35612. lastAffectedLine = lines.size();
  35613. }
  35614. int i, lineStart = newFirstLine->lineStartInFile;
  35615. for (i = firstAffectedLine; i < lines.size(); ++i)
  35616. {
  35617. CodeDocumentLine* const l = lines.getUnchecked (i);
  35618. l->lineStartInFile = lineStart;
  35619. lineStart += l->lineLength;
  35620. }
  35621. checkLastLineStatus();
  35622. const int newTextLength = text.length();
  35623. for (i = 0; i < positionsToMaintain.size(); ++i)
  35624. {
  35625. CodeDocument::Position* const p = positionsToMaintain.getUnchecked(i);
  35626. if (p->getPosition() >= insertPos)
  35627. p->setPosition (p->getPosition() + newTextLength);
  35628. }
  35629. sendListenerChangeMessage (firstAffectedLine, lastAffectedLine);
  35630. }
  35631. }
  35632. class CodeDocumentDeleteAction : public UndoableAction
  35633. {
  35634. CodeDocument& owner;
  35635. int startPos, endPos;
  35636. String removedText;
  35637. CodeDocumentDeleteAction (const CodeDocumentDeleteAction&);
  35638. CodeDocumentDeleteAction& operator= (const CodeDocumentDeleteAction&);
  35639. public:
  35640. CodeDocumentDeleteAction (CodeDocument& owner_, const int startPos_, const int endPos_) throw()
  35641. : owner (owner_),
  35642. startPos (startPos_),
  35643. endPos (endPos_)
  35644. {
  35645. removedText = owner.getTextBetween (CodeDocument::Position (&owner, startPos),
  35646. CodeDocument::Position (&owner, endPos));
  35647. }
  35648. ~CodeDocumentDeleteAction() {}
  35649. bool perform()
  35650. {
  35651. owner.currentActionIndex++;
  35652. owner.remove (startPos, endPos, false);
  35653. return true;
  35654. }
  35655. bool undo()
  35656. {
  35657. owner.currentActionIndex--;
  35658. owner.insert (removedText, startPos, false);
  35659. return true;
  35660. }
  35661. int getSizeInUnits() { return removedText.length() + 32; }
  35662. };
  35663. void CodeDocument::remove (const int startPos, const int endPos, const bool undoable)
  35664. {
  35665. if (endPos <= startPos)
  35666. return;
  35667. if (undoable)
  35668. {
  35669. undoManager.perform (new CodeDocumentDeleteAction (*this, startPos, endPos));
  35670. }
  35671. else
  35672. {
  35673. Position startPosition (this, startPos);
  35674. Position endPosition (this, endPos);
  35675. maximumLineLength = -1;
  35676. const int firstAffectedLine = startPosition.getLineNumber();
  35677. const int endLine = endPosition.getLineNumber();
  35678. int lastAffectedLine = firstAffectedLine + 1;
  35679. CodeDocumentLine* const firstLine = lines.getUnchecked (firstAffectedLine);
  35680. if (firstAffectedLine == endLine)
  35681. {
  35682. firstLine->line = firstLine->line.substring (0, startPosition.getIndexInLine())
  35683. + firstLine->line.substring (endPosition.getIndexInLine());
  35684. firstLine->updateLength();
  35685. }
  35686. else
  35687. {
  35688. lastAffectedLine = lines.size();
  35689. CodeDocumentLine* const lastLine = lines.getUnchecked (endLine);
  35690. jassert (lastLine != 0);
  35691. firstLine->line = firstLine->line.substring (0, startPosition.getIndexInLine())
  35692. + lastLine->line.substring (endPosition.getIndexInLine());
  35693. firstLine->updateLength();
  35694. int numLinesToRemove = endLine - firstAffectedLine;
  35695. lines.removeRange (firstAffectedLine + 1, numLinesToRemove);
  35696. }
  35697. int i;
  35698. for (i = firstAffectedLine + 1; i < lines.size(); ++i)
  35699. {
  35700. CodeDocumentLine* const l = lines.getUnchecked (i);
  35701. const CodeDocumentLine* const previousLine = lines.getUnchecked (i - 1);
  35702. l->lineStartInFile = previousLine->lineStartInFile + previousLine->lineLength;
  35703. }
  35704. checkLastLineStatus();
  35705. const int totalChars = getNumCharacters();
  35706. for (i = 0; i < positionsToMaintain.size(); ++i)
  35707. {
  35708. CodeDocument::Position* p = positionsToMaintain.getUnchecked(i);
  35709. if (p->getPosition() > startPosition.getPosition())
  35710. p->setPosition (jmax (startPos, p->getPosition() + startPos - endPos));
  35711. if (p->getPosition() > totalChars)
  35712. p->setPosition (totalChars);
  35713. }
  35714. sendListenerChangeMessage (firstAffectedLine, lastAffectedLine);
  35715. }
  35716. }
  35717. END_JUCE_NAMESPACE
  35718. /*** End of inlined file: juce_CodeDocument.cpp ***/
  35719. /*** Start of inlined file: juce_CodeEditorComponent.cpp ***/
  35720. BEGIN_JUCE_NAMESPACE
  35721. class CodeEditorComponent::CaretComponent : public Component,
  35722. public Timer
  35723. {
  35724. public:
  35725. CaretComponent (CodeEditorComponent& owner_)
  35726. : owner (owner_)
  35727. {
  35728. setAlwaysOnTop (true);
  35729. setInterceptsMouseClicks (false, false);
  35730. }
  35731. ~CaretComponent()
  35732. {
  35733. }
  35734. void paint (Graphics& g)
  35735. {
  35736. g.fillAll (findColour (CodeEditorComponent::caretColourId));
  35737. }
  35738. void timerCallback()
  35739. {
  35740. setVisible (shouldBeShown() && ! isVisible());
  35741. }
  35742. void updatePosition()
  35743. {
  35744. startTimer (400);
  35745. setVisible (shouldBeShown());
  35746. setBounds (owner.getCharacterBounds (owner.getCaretPos()).withWidth (2));
  35747. }
  35748. private:
  35749. CodeEditorComponent& owner;
  35750. CaretComponent (const CaretComponent&);
  35751. CaretComponent& operator= (const CaretComponent&);
  35752. bool shouldBeShown() const { return owner.hasKeyboardFocus (true); }
  35753. };
  35754. class CodeEditorComponent::CodeEditorLine
  35755. {
  35756. public:
  35757. CodeEditorLine() throw()
  35758. : highlightColumnStart (0), highlightColumnEnd (0)
  35759. {
  35760. }
  35761. ~CodeEditorLine() throw()
  35762. {
  35763. }
  35764. bool update (CodeDocument& document, int lineNum,
  35765. CodeDocument::Iterator& source,
  35766. CodeTokeniser* analyser, const int spacesPerTab,
  35767. const CodeDocument::Position& selectionStart,
  35768. const CodeDocument::Position& selectionEnd)
  35769. {
  35770. Array <SyntaxToken> newTokens;
  35771. newTokens.ensureStorageAllocated (8);
  35772. if (analyser == 0)
  35773. {
  35774. newTokens.add (SyntaxToken (document.getLine (lineNum), -1));
  35775. }
  35776. else if (lineNum < document.getNumLines())
  35777. {
  35778. const CodeDocument::Position pos (&document, lineNum, 0);
  35779. createTokens (pos.getPosition(), pos.getLineText(),
  35780. source, analyser, newTokens);
  35781. }
  35782. replaceTabsWithSpaces (newTokens, spacesPerTab);
  35783. int newHighlightStart = 0;
  35784. int newHighlightEnd = 0;
  35785. if (selectionStart.getLineNumber() <= lineNum && selectionEnd.getLineNumber() >= lineNum)
  35786. {
  35787. const String line (document.getLine (lineNum));
  35788. CodeDocument::Position lineStart (&document, lineNum, 0), lineEnd (&document, lineNum + 1, 0);
  35789. newHighlightStart = indexToColumn (jmax (0, selectionStart.getPosition() - lineStart.getPosition()),
  35790. line, spacesPerTab);
  35791. newHighlightEnd = indexToColumn (jmin (lineEnd.getPosition() - lineStart.getPosition(), selectionEnd.getPosition() - lineStart.getPosition()),
  35792. line, spacesPerTab);
  35793. }
  35794. if (newHighlightStart != highlightColumnStart || newHighlightEnd != highlightColumnEnd)
  35795. {
  35796. highlightColumnStart = newHighlightStart;
  35797. highlightColumnEnd = newHighlightEnd;
  35798. }
  35799. else
  35800. {
  35801. if (tokens.size() == newTokens.size())
  35802. {
  35803. bool allTheSame = true;
  35804. for (int i = newTokens.size(); --i >= 0;)
  35805. {
  35806. if (tokens.getReference(i) != newTokens.getReference(i))
  35807. {
  35808. allTheSame = false;
  35809. break;
  35810. }
  35811. }
  35812. if (allTheSame)
  35813. return false;
  35814. }
  35815. }
  35816. tokens.swapWithArray (newTokens);
  35817. return true;
  35818. }
  35819. void draw (CodeEditorComponent& owner, Graphics& g, const Font& font,
  35820. float x, const int y, const int baselineOffset, const int lineHeight,
  35821. const Colour& highlightColour) const throw()
  35822. {
  35823. if (highlightColumnStart < highlightColumnEnd)
  35824. {
  35825. g.setColour (highlightColour);
  35826. g.fillRect (roundToInt (x + highlightColumnStart * owner.getCharWidth()), y,
  35827. roundToInt ((highlightColumnEnd - highlightColumnStart) * owner.getCharWidth()), lineHeight);
  35828. }
  35829. int lastType = std::numeric_limits<int>::min();
  35830. for (int i = 0; i < tokens.size(); ++i)
  35831. {
  35832. SyntaxToken& token = tokens.getReference(i);
  35833. if (lastType != token.tokenType)
  35834. {
  35835. lastType = token.tokenType;
  35836. g.setColour (owner.getColourForTokenType (lastType));
  35837. }
  35838. g.drawSingleLineText (token.text, roundToInt (x), y + baselineOffset);
  35839. if (i < tokens.size() - 1)
  35840. {
  35841. if (token.width < 0)
  35842. token.width = font.getStringWidthFloat (token.text);
  35843. x += token.width;
  35844. }
  35845. }
  35846. }
  35847. private:
  35848. struct SyntaxToken
  35849. {
  35850. String text;
  35851. int tokenType;
  35852. float width;
  35853. SyntaxToken (const String& text_, const int type) throw()
  35854. : text (text_), tokenType (type), width (-1.0f)
  35855. {
  35856. }
  35857. bool operator!= (const SyntaxToken& other) const throw()
  35858. {
  35859. return text != other.text || tokenType != other.tokenType;
  35860. }
  35861. };
  35862. Array <SyntaxToken> tokens;
  35863. int highlightColumnStart, highlightColumnEnd;
  35864. static void createTokens (int startPosition, const String& lineText,
  35865. CodeDocument::Iterator& source,
  35866. CodeTokeniser* analyser,
  35867. Array <SyntaxToken>& newTokens)
  35868. {
  35869. CodeDocument::Iterator lastIterator (source);
  35870. const int lineLength = lineText.length();
  35871. for (;;)
  35872. {
  35873. int tokenType = analyser->readNextToken (source);
  35874. int tokenStart = lastIterator.getPosition();
  35875. int tokenEnd = source.getPosition();
  35876. if (tokenEnd <= tokenStart)
  35877. break;
  35878. tokenEnd -= startPosition;
  35879. if (tokenEnd > 0)
  35880. {
  35881. tokenStart -= startPosition;
  35882. newTokens.add (SyntaxToken (lineText.substring (jmax (0, tokenStart), tokenEnd),
  35883. tokenType));
  35884. if (tokenEnd >= lineLength)
  35885. break;
  35886. }
  35887. lastIterator = source;
  35888. }
  35889. source = lastIterator;
  35890. }
  35891. static void replaceTabsWithSpaces (Array <SyntaxToken>& tokens, const int spacesPerTab) throw()
  35892. {
  35893. int x = 0;
  35894. for (int i = 0; i < tokens.size(); ++i)
  35895. {
  35896. SyntaxToken& t = tokens.getReference(i);
  35897. for (;;)
  35898. {
  35899. int tabPos = t.text.indexOfChar ('\t');
  35900. if (tabPos < 0)
  35901. break;
  35902. const int spacesNeeded = spacesPerTab - ((tabPos + x) % spacesPerTab);
  35903. t.text = t.text.replaceSection (tabPos, 1, String::repeatedString (" ", spacesNeeded));
  35904. }
  35905. x += t.text.length();
  35906. }
  35907. }
  35908. int indexToColumn (int index, const String& line, int spacesPerTab) const throw()
  35909. {
  35910. jassert (index <= line.length());
  35911. int col = 0;
  35912. for (int i = 0; i < index; ++i)
  35913. {
  35914. if (line[i] != '\t')
  35915. ++col;
  35916. else
  35917. col += spacesPerTab - (col % spacesPerTab);
  35918. }
  35919. return col;
  35920. }
  35921. };
  35922. CodeEditorComponent::CodeEditorComponent (CodeDocument& document_,
  35923. CodeTokeniser* const codeTokeniser_)
  35924. : document (document_),
  35925. firstLineOnScreen (0),
  35926. gutter (5),
  35927. spacesPerTab (4),
  35928. lineHeight (0),
  35929. linesOnScreen (0),
  35930. columnsOnScreen (0),
  35931. scrollbarThickness (16),
  35932. columnToTryToMaintain (-1),
  35933. useSpacesForTabs (false),
  35934. xOffset (0),
  35935. codeTokeniser (codeTokeniser_)
  35936. {
  35937. caretPos = CodeDocument::Position (&document_, 0, 0);
  35938. caretPos.setPositionMaintained (true);
  35939. selectionStart = CodeDocument::Position (&document_, 0, 0);
  35940. selectionStart.setPositionMaintained (true);
  35941. selectionEnd = CodeDocument::Position (&document_, 0, 0);
  35942. selectionEnd.setPositionMaintained (true);
  35943. setOpaque (true);
  35944. setMouseCursor (MouseCursor (MouseCursor::IBeamCursor));
  35945. setWantsKeyboardFocus (true);
  35946. addAndMakeVisible (verticalScrollBar = new ScrollBar (true));
  35947. verticalScrollBar->setSingleStepSize (1.0);
  35948. addAndMakeVisible (horizontalScrollBar = new ScrollBar (false));
  35949. horizontalScrollBar->setSingleStepSize (1.0);
  35950. addAndMakeVisible (caret = new CaretComponent (*this));
  35951. Font f (12.0f);
  35952. f.setTypefaceName (Font::getDefaultMonospacedFontName());
  35953. setFont (f);
  35954. resetToDefaultColours();
  35955. verticalScrollBar->addListener (this);
  35956. horizontalScrollBar->addListener (this);
  35957. document.addListener (this);
  35958. }
  35959. CodeEditorComponent::~CodeEditorComponent()
  35960. {
  35961. document.removeListener (this);
  35962. deleteAllChildren();
  35963. }
  35964. void CodeEditorComponent::loadContent (const String& newContent)
  35965. {
  35966. clearCachedIterators (0);
  35967. document.replaceAllContent (newContent);
  35968. document.clearUndoHistory();
  35969. document.setSavePoint();
  35970. caretPos.setPosition (0);
  35971. selectionStart.setPosition (0);
  35972. selectionEnd.setPosition (0);
  35973. scrollToLine (0);
  35974. }
  35975. bool CodeEditorComponent::isTextInputActive() const
  35976. {
  35977. return true;
  35978. }
  35979. void CodeEditorComponent::codeDocumentChanged (const CodeDocument::Position& affectedTextStart,
  35980. const CodeDocument::Position& affectedTextEnd)
  35981. {
  35982. clearCachedIterators (affectedTextStart.getLineNumber());
  35983. triggerAsyncUpdate();
  35984. caret->updatePosition();
  35985. columnToTryToMaintain = -1;
  35986. if (affectedTextEnd.getPosition() >= selectionStart.getPosition()
  35987. && affectedTextStart.getPosition() <= selectionEnd.getPosition())
  35988. deselectAll();
  35989. if (caretPos.getPosition() > affectedTextEnd.getPosition()
  35990. || caretPos.getPosition() < affectedTextStart.getPosition())
  35991. moveCaretTo (affectedTextStart, false);
  35992. updateScrollBars();
  35993. }
  35994. void CodeEditorComponent::resized()
  35995. {
  35996. linesOnScreen = (getHeight() - scrollbarThickness) / lineHeight;
  35997. columnsOnScreen = (int) ((getWidth() - scrollbarThickness) / charWidth);
  35998. lines.clear();
  35999. rebuildLineTokens();
  36000. caret->updatePosition();
  36001. verticalScrollBar->setBounds (getWidth() - scrollbarThickness, 0, scrollbarThickness, getHeight() - scrollbarThickness);
  36002. horizontalScrollBar->setBounds (gutter, getHeight() - scrollbarThickness, getWidth() - scrollbarThickness - gutter, scrollbarThickness);
  36003. updateScrollBars();
  36004. }
  36005. void CodeEditorComponent::paint (Graphics& g)
  36006. {
  36007. handleUpdateNowIfNeeded();
  36008. g.fillAll (findColour (CodeEditorComponent::backgroundColourId));
  36009. g.reduceClipRegion (gutter, 0, verticalScrollBar->getX() - gutter, horizontalScrollBar->getY());
  36010. g.setFont (font);
  36011. const int baselineOffset = (int) font.getAscent();
  36012. const Colour defaultColour (findColour (CodeEditorComponent::defaultTextColourId));
  36013. const Colour highlightColour (findColour (CodeEditorComponent::highlightColourId));
  36014. const Rectangle<int> clip (g.getClipBounds());
  36015. const int firstLineToDraw = jmax (0, clip.getY() / lineHeight);
  36016. const int lastLineToDraw = jmin (lines.size(), clip.getBottom() / lineHeight + 1);
  36017. for (int j = firstLineToDraw; j < lastLineToDraw; ++j)
  36018. {
  36019. lines.getUnchecked(j)->draw (*this, g, font,
  36020. (float) (gutter - xOffset * charWidth),
  36021. lineHeight * j, baselineOffset, lineHeight,
  36022. highlightColour);
  36023. }
  36024. }
  36025. void CodeEditorComponent::setScrollbarThickness (const int thickness) throw()
  36026. {
  36027. if (scrollbarThickness != thickness)
  36028. {
  36029. scrollbarThickness = thickness;
  36030. resized();
  36031. }
  36032. }
  36033. void CodeEditorComponent::handleAsyncUpdate()
  36034. {
  36035. rebuildLineTokens();
  36036. }
  36037. void CodeEditorComponent::rebuildLineTokens()
  36038. {
  36039. cancelPendingUpdate();
  36040. const int numNeeded = linesOnScreen + 1;
  36041. int minLineToRepaint = numNeeded;
  36042. int maxLineToRepaint = 0;
  36043. if (numNeeded != lines.size())
  36044. {
  36045. lines.clear();
  36046. for (int i = numNeeded; --i >= 0;)
  36047. lines.add (new CodeEditorLine());
  36048. minLineToRepaint = 0;
  36049. maxLineToRepaint = numNeeded;
  36050. }
  36051. jassert (numNeeded == lines.size());
  36052. CodeDocument::Iterator source (&document);
  36053. getIteratorForPosition (CodeDocument::Position (&document, firstLineOnScreen, 0).getPosition(), source);
  36054. for (int i = 0; i < numNeeded; ++i)
  36055. {
  36056. CodeEditorLine* const line = lines.getUnchecked(i);
  36057. if (line->update (document, firstLineOnScreen + i, source, codeTokeniser, spacesPerTab,
  36058. selectionStart, selectionEnd))
  36059. {
  36060. minLineToRepaint = jmin (minLineToRepaint, i);
  36061. maxLineToRepaint = jmax (maxLineToRepaint, i);
  36062. }
  36063. }
  36064. if (minLineToRepaint <= maxLineToRepaint)
  36065. {
  36066. repaint (gutter, lineHeight * minLineToRepaint - 1,
  36067. verticalScrollBar->getX() - gutter,
  36068. lineHeight * (1 + maxLineToRepaint - minLineToRepaint) + 2);
  36069. }
  36070. }
  36071. void CodeEditorComponent::moveCaretTo (const CodeDocument::Position& newPos, const bool highlighting)
  36072. {
  36073. caretPos = newPos;
  36074. columnToTryToMaintain = -1;
  36075. if (highlighting)
  36076. {
  36077. if (dragType == notDragging)
  36078. {
  36079. if (abs (caretPos.getPosition() - selectionStart.getPosition())
  36080. < abs (caretPos.getPosition() - selectionEnd.getPosition()))
  36081. dragType = draggingSelectionStart;
  36082. else
  36083. dragType = draggingSelectionEnd;
  36084. }
  36085. if (dragType == draggingSelectionStart)
  36086. {
  36087. selectionStart = caretPos;
  36088. if (selectionEnd.getPosition() < selectionStart.getPosition())
  36089. {
  36090. const CodeDocument::Position temp (selectionStart);
  36091. selectionStart = selectionEnd;
  36092. selectionEnd = temp;
  36093. dragType = draggingSelectionEnd;
  36094. }
  36095. }
  36096. else
  36097. {
  36098. selectionEnd = caretPos;
  36099. if (selectionEnd.getPosition() < selectionStart.getPosition())
  36100. {
  36101. const CodeDocument::Position temp (selectionStart);
  36102. selectionStart = selectionEnd;
  36103. selectionEnd = temp;
  36104. dragType = draggingSelectionStart;
  36105. }
  36106. }
  36107. triggerAsyncUpdate();
  36108. }
  36109. else
  36110. {
  36111. deselectAll();
  36112. }
  36113. caret->updatePosition();
  36114. scrollToKeepCaretOnScreen();
  36115. updateScrollBars();
  36116. }
  36117. void CodeEditorComponent::deselectAll()
  36118. {
  36119. if (selectionStart != selectionEnd)
  36120. triggerAsyncUpdate();
  36121. selectionStart = caretPos;
  36122. selectionEnd = caretPos;
  36123. }
  36124. void CodeEditorComponent::updateScrollBars()
  36125. {
  36126. verticalScrollBar->setRangeLimits (0, jmax (document.getNumLines(), firstLineOnScreen + linesOnScreen));
  36127. verticalScrollBar->setCurrentRange (firstLineOnScreen, linesOnScreen);
  36128. horizontalScrollBar->setRangeLimits (0, jmax ((double) document.getMaximumLineLength(), xOffset + columnsOnScreen));
  36129. horizontalScrollBar->setCurrentRange (xOffset, columnsOnScreen);
  36130. }
  36131. void CodeEditorComponent::scrollToLineInternal (int newFirstLineOnScreen)
  36132. {
  36133. newFirstLineOnScreen = jlimit (0, jmax (0, document.getNumLines() - 1),
  36134. newFirstLineOnScreen);
  36135. if (newFirstLineOnScreen != firstLineOnScreen)
  36136. {
  36137. firstLineOnScreen = newFirstLineOnScreen;
  36138. caret->updatePosition();
  36139. updateCachedIterators (firstLineOnScreen);
  36140. triggerAsyncUpdate();
  36141. }
  36142. }
  36143. void CodeEditorComponent::scrollToColumnInternal (double column)
  36144. {
  36145. const double newOffset = jlimit (0.0, document.getMaximumLineLength() + 3.0, column);
  36146. if (xOffset != newOffset)
  36147. {
  36148. xOffset = newOffset;
  36149. caret->updatePosition();
  36150. repaint();
  36151. }
  36152. }
  36153. void CodeEditorComponent::scrollToLine (int newFirstLineOnScreen)
  36154. {
  36155. scrollToLineInternal (newFirstLineOnScreen);
  36156. updateScrollBars();
  36157. }
  36158. void CodeEditorComponent::scrollToColumn (int newFirstColumnOnScreen)
  36159. {
  36160. scrollToColumnInternal (newFirstColumnOnScreen);
  36161. updateScrollBars();
  36162. }
  36163. void CodeEditorComponent::scrollBy (int deltaLines)
  36164. {
  36165. scrollToLine (firstLineOnScreen + deltaLines);
  36166. }
  36167. void CodeEditorComponent::scrollToKeepCaretOnScreen()
  36168. {
  36169. if (caretPos.getLineNumber() < firstLineOnScreen)
  36170. scrollBy (caretPos.getLineNumber() - firstLineOnScreen);
  36171. else if (caretPos.getLineNumber() >= firstLineOnScreen + linesOnScreen)
  36172. scrollBy (caretPos.getLineNumber() - (firstLineOnScreen + linesOnScreen - 1));
  36173. const int column = indexToColumn (caretPos.getLineNumber(), caretPos.getIndexInLine());
  36174. if (column >= xOffset + columnsOnScreen - 1)
  36175. scrollToColumn (column + 1 - columnsOnScreen);
  36176. else if (column < xOffset)
  36177. scrollToColumn (column);
  36178. }
  36179. const Rectangle<int> CodeEditorComponent::getCharacterBounds (const CodeDocument::Position& pos) const throw()
  36180. {
  36181. return Rectangle<int> (roundToInt ((gutter - xOffset * charWidth) + indexToColumn (pos.getLineNumber(), pos.getIndexInLine()) * charWidth),
  36182. (pos.getLineNumber() - firstLineOnScreen) * lineHeight,
  36183. roundToInt (charWidth),
  36184. lineHeight);
  36185. }
  36186. const CodeDocument::Position CodeEditorComponent::getPositionAt (int x, int y)
  36187. {
  36188. const int line = y / lineHeight + firstLineOnScreen;
  36189. const int column = roundToInt ((x - (gutter - xOffset * charWidth)) / charWidth);
  36190. const int index = columnToIndex (line, column);
  36191. return CodeDocument::Position (&document, line, index);
  36192. }
  36193. void CodeEditorComponent::insertTextAtCaret (const String& newText)
  36194. {
  36195. document.deleteSection (selectionStart, selectionEnd);
  36196. if (newText.isNotEmpty())
  36197. document.insertText (caretPos, newText);
  36198. scrollToKeepCaretOnScreen();
  36199. }
  36200. void CodeEditorComponent::insertTabAtCaret()
  36201. {
  36202. if (CharacterFunctions::isWhitespace (caretPos.getCharacter())
  36203. && caretPos.getLineNumber() == caretPos.movedBy (1).getLineNumber())
  36204. {
  36205. moveCaretTo (document.findWordBreakAfter (caretPos), false);
  36206. }
  36207. if (useSpacesForTabs)
  36208. {
  36209. const int caretCol = indexToColumn (caretPos.getLineNumber(), caretPos.getIndexInLine());
  36210. const int spacesNeeded = spacesPerTab - (caretCol % spacesPerTab);
  36211. insertTextAtCaret (String::repeatedString (" ", spacesNeeded));
  36212. }
  36213. else
  36214. {
  36215. insertTextAtCaret ("\t");
  36216. }
  36217. }
  36218. void CodeEditorComponent::cut()
  36219. {
  36220. insertTextAtCaret (String::empty);
  36221. }
  36222. void CodeEditorComponent::copy()
  36223. {
  36224. newTransaction();
  36225. const String selection (document.getTextBetween (selectionStart, selectionEnd));
  36226. if (selection.isNotEmpty())
  36227. SystemClipboard::copyTextToClipboard (selection);
  36228. }
  36229. void CodeEditorComponent::copyThenCut()
  36230. {
  36231. copy();
  36232. cut();
  36233. newTransaction();
  36234. }
  36235. void CodeEditorComponent::paste()
  36236. {
  36237. newTransaction();
  36238. const String clip (SystemClipboard::getTextFromClipboard());
  36239. if (clip.isNotEmpty())
  36240. insertTextAtCaret (clip);
  36241. newTransaction();
  36242. }
  36243. void CodeEditorComponent::cursorLeft (const bool moveInWholeWordSteps, const bool selecting)
  36244. {
  36245. newTransaction();
  36246. if (moveInWholeWordSteps)
  36247. moveCaretTo (document.findWordBreakBefore (caretPos), selecting);
  36248. else
  36249. moveCaretTo (caretPos.movedBy (-1), selecting);
  36250. }
  36251. void CodeEditorComponent::cursorRight (const bool moveInWholeWordSteps, const bool selecting)
  36252. {
  36253. newTransaction();
  36254. if (moveInWholeWordSteps)
  36255. moveCaretTo (document.findWordBreakAfter (caretPos), selecting);
  36256. else
  36257. moveCaretTo (caretPos.movedBy (1), selecting);
  36258. }
  36259. void CodeEditorComponent::moveLineDelta (const int delta, const bool selecting)
  36260. {
  36261. CodeDocument::Position pos (caretPos);
  36262. const int newLineNum = pos.getLineNumber() + delta;
  36263. if (columnToTryToMaintain < 0)
  36264. columnToTryToMaintain = indexToColumn (pos.getLineNumber(), pos.getIndexInLine());
  36265. pos.setLineAndIndex (newLineNum, columnToIndex (newLineNum, columnToTryToMaintain));
  36266. const int colToMaintain = columnToTryToMaintain;
  36267. moveCaretTo (pos, selecting);
  36268. columnToTryToMaintain = colToMaintain;
  36269. }
  36270. void CodeEditorComponent::cursorDown (const bool selecting)
  36271. {
  36272. newTransaction();
  36273. if (caretPos.getLineNumber() == document.getNumLines() - 1)
  36274. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), selecting);
  36275. else
  36276. moveLineDelta (1, selecting);
  36277. }
  36278. void CodeEditorComponent::cursorUp (const bool selecting)
  36279. {
  36280. newTransaction();
  36281. if (caretPos.getLineNumber() == 0)
  36282. moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting);
  36283. else
  36284. moveLineDelta (-1, selecting);
  36285. }
  36286. void CodeEditorComponent::pageDown (const bool selecting)
  36287. {
  36288. newTransaction();
  36289. scrollBy (jlimit (0, linesOnScreen, 1 + document.getNumLines() - firstLineOnScreen - linesOnScreen));
  36290. moveLineDelta (linesOnScreen, selecting);
  36291. }
  36292. void CodeEditorComponent::pageUp (const bool selecting)
  36293. {
  36294. newTransaction();
  36295. scrollBy (-linesOnScreen);
  36296. moveLineDelta (-linesOnScreen, selecting);
  36297. }
  36298. void CodeEditorComponent::scrollUp()
  36299. {
  36300. newTransaction();
  36301. scrollBy (1);
  36302. if (caretPos.getLineNumber() < firstLineOnScreen)
  36303. moveLineDelta (1, false);
  36304. }
  36305. void CodeEditorComponent::scrollDown()
  36306. {
  36307. newTransaction();
  36308. scrollBy (-1);
  36309. if (caretPos.getLineNumber() >= firstLineOnScreen + linesOnScreen)
  36310. moveLineDelta (-1, false);
  36311. }
  36312. void CodeEditorComponent::goToStartOfDocument (const bool selecting)
  36313. {
  36314. newTransaction();
  36315. moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting);
  36316. }
  36317. static int findFirstNonWhitespaceChar (const String& line) throw()
  36318. {
  36319. const int len = line.length();
  36320. for (int i = 0; i < len; ++i)
  36321. if (! CharacterFunctions::isWhitespace (line [i]))
  36322. return i;
  36323. return 0;
  36324. }
  36325. void CodeEditorComponent::goToStartOfLine (const bool selecting)
  36326. {
  36327. newTransaction();
  36328. int index = findFirstNonWhitespaceChar (caretPos.getLineText());
  36329. if (index >= caretPos.getIndexInLine() && caretPos.getIndexInLine() > 0)
  36330. index = 0;
  36331. moveCaretTo (CodeDocument::Position (&document, caretPos.getLineNumber(), index), selecting);
  36332. }
  36333. void CodeEditorComponent::goToEndOfDocument (const bool selecting)
  36334. {
  36335. newTransaction();
  36336. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), selecting);
  36337. }
  36338. void CodeEditorComponent::goToEndOfLine (const bool selecting)
  36339. {
  36340. newTransaction();
  36341. moveCaretTo (CodeDocument::Position (&document, caretPos.getLineNumber(), std::numeric_limits<int>::max()), selecting);
  36342. }
  36343. void CodeEditorComponent::backspace (const bool moveInWholeWordSteps)
  36344. {
  36345. if (moveInWholeWordSteps)
  36346. {
  36347. cut(); // in case something is already highlighted
  36348. moveCaretTo (document.findWordBreakBefore (caretPos), true);
  36349. }
  36350. else
  36351. {
  36352. if (selectionStart == selectionEnd)
  36353. selectionStart.moveBy (-1);
  36354. }
  36355. cut();
  36356. }
  36357. void CodeEditorComponent::deleteForward (const bool moveInWholeWordSteps)
  36358. {
  36359. if (moveInWholeWordSteps)
  36360. {
  36361. cut(); // in case something is already highlighted
  36362. moveCaretTo (document.findWordBreakAfter (caretPos), true);
  36363. }
  36364. else
  36365. {
  36366. if (selectionStart == selectionEnd)
  36367. selectionEnd.moveBy (1);
  36368. else
  36369. newTransaction();
  36370. }
  36371. cut();
  36372. }
  36373. void CodeEditorComponent::selectAll()
  36374. {
  36375. newTransaction();
  36376. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), false);
  36377. moveCaretTo (CodeDocument::Position (&document, 0, 0), true);
  36378. }
  36379. void CodeEditorComponent::undo()
  36380. {
  36381. document.undo();
  36382. scrollToKeepCaretOnScreen();
  36383. }
  36384. void CodeEditorComponent::redo()
  36385. {
  36386. document.redo();
  36387. scrollToKeepCaretOnScreen();
  36388. }
  36389. void CodeEditorComponent::newTransaction()
  36390. {
  36391. document.newTransaction();
  36392. startTimer (600);
  36393. }
  36394. void CodeEditorComponent::timerCallback()
  36395. {
  36396. newTransaction();
  36397. }
  36398. const Range<int> CodeEditorComponent::getHighlightedRegion() const
  36399. {
  36400. return Range<int> (selectionStart.getPosition(), selectionEnd.getPosition());
  36401. }
  36402. void CodeEditorComponent::setHighlightedRegion (const Range<int>& newRange)
  36403. {
  36404. moveCaretTo (CodeDocument::Position (&document, newRange.getStart()), false);
  36405. moveCaretTo (CodeDocument::Position (&document, newRange.getEnd()), true);
  36406. }
  36407. const String CodeEditorComponent::getTextInRange (const Range<int>& range) const
  36408. {
  36409. return document.getTextBetween (CodeDocument::Position (&document, range.getStart()),
  36410. CodeDocument::Position (&document, range.getEnd()));
  36411. }
  36412. bool CodeEditorComponent::keyPressed (const KeyPress& key)
  36413. {
  36414. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  36415. const bool shiftDown = key.getModifiers().isShiftDown();
  36416. if (key.isKeyCode (KeyPress::leftKey))
  36417. {
  36418. cursorLeft (moveInWholeWordSteps, shiftDown);
  36419. }
  36420. else if (key.isKeyCode (KeyPress::rightKey))
  36421. {
  36422. cursorRight (moveInWholeWordSteps, shiftDown);
  36423. }
  36424. else if (key.isKeyCode (KeyPress::upKey))
  36425. {
  36426. if (key.getModifiers().isCtrlDown() && ! shiftDown)
  36427. scrollDown();
  36428. #if JUCE_MAC
  36429. else if (key.getModifiers().isCommandDown())
  36430. goToStartOfDocument (shiftDown);
  36431. #endif
  36432. else
  36433. cursorUp (shiftDown);
  36434. }
  36435. else if (key.isKeyCode (KeyPress::downKey))
  36436. {
  36437. if (key.getModifiers().isCtrlDown() && ! shiftDown)
  36438. scrollUp();
  36439. #if JUCE_MAC
  36440. else if (key.getModifiers().isCommandDown())
  36441. goToEndOfDocument (shiftDown);
  36442. #endif
  36443. else
  36444. cursorDown (shiftDown);
  36445. }
  36446. else if (key.isKeyCode (KeyPress::pageDownKey))
  36447. {
  36448. pageDown (shiftDown);
  36449. }
  36450. else if (key.isKeyCode (KeyPress::pageUpKey))
  36451. {
  36452. pageUp (shiftDown);
  36453. }
  36454. else if (key.isKeyCode (KeyPress::homeKey))
  36455. {
  36456. if (moveInWholeWordSteps)
  36457. goToStartOfDocument (shiftDown);
  36458. else
  36459. goToStartOfLine (shiftDown);
  36460. }
  36461. else if (key.isKeyCode (KeyPress::endKey))
  36462. {
  36463. if (moveInWholeWordSteps)
  36464. goToEndOfDocument (shiftDown);
  36465. else
  36466. goToEndOfLine (shiftDown);
  36467. }
  36468. else if (key.isKeyCode (KeyPress::backspaceKey))
  36469. {
  36470. backspace (moveInWholeWordSteps);
  36471. }
  36472. else if (key.isKeyCode (KeyPress::deleteKey))
  36473. {
  36474. deleteForward (moveInWholeWordSteps);
  36475. }
  36476. else if (key == KeyPress ('c', ModifierKeys::commandModifier, 0))
  36477. {
  36478. copy();
  36479. }
  36480. else if (key == KeyPress ('x', ModifierKeys::commandModifier, 0))
  36481. {
  36482. copyThenCut();
  36483. }
  36484. else if (key == KeyPress ('v', ModifierKeys::commandModifier, 0))
  36485. {
  36486. paste();
  36487. }
  36488. else if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  36489. {
  36490. undo();
  36491. }
  36492. else if (key == KeyPress ('y', ModifierKeys::commandModifier, 0)
  36493. || key == KeyPress ('z', ModifierKeys::commandModifier | ModifierKeys::shiftModifier, 0))
  36494. {
  36495. redo();
  36496. }
  36497. else if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  36498. {
  36499. selectAll();
  36500. }
  36501. else if (key == KeyPress::tabKey || key.getTextCharacter() == '\t')
  36502. {
  36503. insertTabAtCaret();
  36504. }
  36505. else if (key == KeyPress::returnKey)
  36506. {
  36507. newTransaction();
  36508. insertTextAtCaret (document.getNewLineCharacters());
  36509. }
  36510. else if (key.isKeyCode (KeyPress::escapeKey))
  36511. {
  36512. newTransaction();
  36513. }
  36514. else if (key.getTextCharacter() >= ' ')
  36515. {
  36516. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  36517. }
  36518. else
  36519. {
  36520. return false;
  36521. }
  36522. return true;
  36523. }
  36524. void CodeEditorComponent::mouseDown (const MouseEvent& e)
  36525. {
  36526. newTransaction();
  36527. dragType = notDragging;
  36528. if (! e.mods.isPopupMenu())
  36529. {
  36530. beginDragAutoRepeat (100);
  36531. moveCaretTo (getPositionAt (e.x, e.y), e.mods.isShiftDown());
  36532. }
  36533. else
  36534. {
  36535. /*PopupMenu m;
  36536. addPopupMenuItems (m, &e);
  36537. const int result = m.show();
  36538. if (result != 0)
  36539. performPopupMenuAction (result);
  36540. */
  36541. }
  36542. }
  36543. void CodeEditorComponent::mouseDrag (const MouseEvent& e)
  36544. {
  36545. if (! e.mods.isPopupMenu())
  36546. moveCaretTo (getPositionAt (e.x, e.y), true);
  36547. }
  36548. void CodeEditorComponent::mouseUp (const MouseEvent&)
  36549. {
  36550. newTransaction();
  36551. beginDragAutoRepeat (0);
  36552. dragType = notDragging;
  36553. }
  36554. void CodeEditorComponent::mouseDoubleClick (const MouseEvent& e)
  36555. {
  36556. CodeDocument::Position tokenStart (getPositionAt (e.x, e.y));
  36557. CodeDocument::Position tokenEnd (tokenStart);
  36558. if (e.getNumberOfClicks() > 2)
  36559. {
  36560. tokenStart.setLineAndIndex (tokenStart.getLineNumber(), 0);
  36561. tokenEnd.setLineAndIndex (tokenStart.getLineNumber() + 1, 0);
  36562. }
  36563. else
  36564. {
  36565. while (CharacterFunctions::isLetterOrDigit (tokenEnd.getCharacter()))
  36566. tokenEnd.moveBy (1);
  36567. tokenStart = tokenEnd;
  36568. while (tokenStart.getIndexInLine() > 0
  36569. && CharacterFunctions::isLetterOrDigit (tokenStart.movedBy (-1).getCharacter()))
  36570. tokenStart.moveBy (-1);
  36571. }
  36572. moveCaretTo (tokenEnd, false);
  36573. moveCaretTo (tokenStart, true);
  36574. }
  36575. void CodeEditorComponent::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  36576. {
  36577. if ((verticalScrollBar->isVisible() && wheelIncrementY != 0)
  36578. || (horizontalScrollBar->isVisible() && wheelIncrementX != 0))
  36579. {
  36580. verticalScrollBar->mouseWheelMove (e, 0, wheelIncrementY);
  36581. horizontalScrollBar->mouseWheelMove (e, wheelIncrementX, 0);
  36582. }
  36583. else
  36584. {
  36585. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  36586. }
  36587. }
  36588. void CodeEditorComponent::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart)
  36589. {
  36590. if (scrollBarThatHasMoved == verticalScrollBar)
  36591. scrollToLineInternal ((int) newRangeStart);
  36592. else
  36593. scrollToColumnInternal (newRangeStart);
  36594. }
  36595. void CodeEditorComponent::focusGained (FocusChangeType)
  36596. {
  36597. caret->updatePosition();
  36598. }
  36599. void CodeEditorComponent::focusLost (FocusChangeType)
  36600. {
  36601. caret->updatePosition();
  36602. }
  36603. void CodeEditorComponent::setTabSize (const int numSpaces, const bool insertSpaces) throw()
  36604. {
  36605. useSpacesForTabs = insertSpaces;
  36606. if (spacesPerTab != numSpaces)
  36607. {
  36608. spacesPerTab = numSpaces;
  36609. triggerAsyncUpdate();
  36610. }
  36611. }
  36612. int CodeEditorComponent::indexToColumn (int lineNum, int index) const throw()
  36613. {
  36614. const String line (document.getLine (lineNum));
  36615. jassert (index <= line.length());
  36616. int col = 0;
  36617. for (int i = 0; i < index; ++i)
  36618. {
  36619. if (line[i] != '\t')
  36620. ++col;
  36621. else
  36622. col += getTabSize() - (col % getTabSize());
  36623. }
  36624. return col;
  36625. }
  36626. int CodeEditorComponent::columnToIndex (int lineNum, int column) const throw()
  36627. {
  36628. const String line (document.getLine (lineNum));
  36629. const int lineLength = line.length();
  36630. int i, col = 0;
  36631. for (i = 0; i < lineLength; ++i)
  36632. {
  36633. if (line[i] != '\t')
  36634. ++col;
  36635. else
  36636. col += getTabSize() - (col % getTabSize());
  36637. if (col > column)
  36638. break;
  36639. }
  36640. return i;
  36641. }
  36642. void CodeEditorComponent::setFont (const Font& newFont)
  36643. {
  36644. font = newFont;
  36645. charWidth = font.getStringWidthFloat ("0");
  36646. lineHeight = roundToInt (font.getHeight());
  36647. resized();
  36648. }
  36649. void CodeEditorComponent::resetToDefaultColours()
  36650. {
  36651. coloursForTokenCategories.clear();
  36652. if (codeTokeniser != 0)
  36653. {
  36654. for (int i = codeTokeniser->getTokenTypes().size(); --i >= 0;)
  36655. setColourForTokenType (i, codeTokeniser->getDefaultColour (i));
  36656. }
  36657. }
  36658. void CodeEditorComponent::setColourForTokenType (const int tokenType, const Colour& colour)
  36659. {
  36660. jassert (tokenType < 256);
  36661. while (coloursForTokenCategories.size() < tokenType)
  36662. coloursForTokenCategories.add (Colours::black);
  36663. coloursForTokenCategories.set (tokenType, colour);
  36664. repaint();
  36665. }
  36666. const Colour CodeEditorComponent::getColourForTokenType (const int tokenType) const throw()
  36667. {
  36668. if (((unsigned int) tokenType) >= (unsigned int) coloursForTokenCategories.size())
  36669. return findColour (CodeEditorComponent::defaultTextColourId);
  36670. return coloursForTokenCategories.getReference (tokenType);
  36671. }
  36672. void CodeEditorComponent::clearCachedIterators (const int firstLineToBeInvalid) throw()
  36673. {
  36674. int i;
  36675. for (i = cachedIterators.size(); --i >= 0;)
  36676. if (cachedIterators.getUnchecked (i)->getLine() < firstLineToBeInvalid)
  36677. break;
  36678. cachedIterators.removeRange (jmax (0, i - 1), cachedIterators.size());
  36679. }
  36680. void CodeEditorComponent::updateCachedIterators (int maxLineNum)
  36681. {
  36682. const int maxNumCachedPositions = 5000;
  36683. const int linesBetweenCachedSources = jmax (10, document.getNumLines() / maxNumCachedPositions);
  36684. if (cachedIterators.size() == 0)
  36685. cachedIterators.add (new CodeDocument::Iterator (&document));
  36686. if (codeTokeniser == 0)
  36687. return;
  36688. for (;;)
  36689. {
  36690. CodeDocument::Iterator* last = cachedIterators.getLast();
  36691. if (last->getLine() >= maxLineNum)
  36692. break;
  36693. CodeDocument::Iterator* t = new CodeDocument::Iterator (*last);
  36694. cachedIterators.add (t);
  36695. const int targetLine = last->getLine() + linesBetweenCachedSources;
  36696. for (;;)
  36697. {
  36698. codeTokeniser->readNextToken (*t);
  36699. if (t->getLine() >= targetLine)
  36700. break;
  36701. if (t->isEOF())
  36702. return;
  36703. }
  36704. }
  36705. }
  36706. void CodeEditorComponent::getIteratorForPosition (int position, CodeDocument::Iterator& source)
  36707. {
  36708. if (codeTokeniser == 0)
  36709. return;
  36710. for (int i = cachedIterators.size(); --i >= 0;)
  36711. {
  36712. CodeDocument::Iterator* t = cachedIterators.getUnchecked (i);
  36713. if (t->getPosition() <= position)
  36714. {
  36715. source = *t;
  36716. break;
  36717. }
  36718. }
  36719. while (source.getPosition() < position)
  36720. {
  36721. const CodeDocument::Iterator original (source);
  36722. codeTokeniser->readNextToken (source);
  36723. if (source.getPosition() > position || source.isEOF())
  36724. {
  36725. source = original;
  36726. break;
  36727. }
  36728. }
  36729. }
  36730. END_JUCE_NAMESPACE
  36731. /*** End of inlined file: juce_CodeEditorComponent.cpp ***/
  36732. /*** Start of inlined file: juce_CPlusPlusCodeTokeniser.cpp ***/
  36733. BEGIN_JUCE_NAMESPACE
  36734. CPlusPlusCodeTokeniser::CPlusPlusCodeTokeniser()
  36735. {
  36736. }
  36737. CPlusPlusCodeTokeniser::~CPlusPlusCodeTokeniser()
  36738. {
  36739. }
  36740. namespace CppTokeniser
  36741. {
  36742. static bool isIdentifierStart (const juce_wchar c) throw()
  36743. {
  36744. return CharacterFunctions::isLetter (c)
  36745. || c == '_' || c == '@';
  36746. }
  36747. static bool isIdentifierBody (const juce_wchar c) throw()
  36748. {
  36749. return CharacterFunctions::isLetterOrDigit (c)
  36750. || c == '_' || c == '@';
  36751. }
  36752. static bool isReservedKeyword (const juce_wchar* const token, const int tokenLength) throw()
  36753. {
  36754. static const juce_wchar* const keywords2Char[] =
  36755. { JUCE_T("if"), JUCE_T("do"), JUCE_T("or"), JUCE_T("id"), 0 };
  36756. static const juce_wchar* const keywords3Char[] =
  36757. { 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 };
  36758. static const juce_wchar* const keywords4Char[] =
  36759. { JUCE_T("bool"), JUCE_T("void"), JUCE_T("this"), JUCE_T("true"), JUCE_T("long"), JUCE_T("else"), JUCE_T("char"),
  36760. JUCE_T("enum"), JUCE_T("case"), JUCE_T("goto"), JUCE_T("auto"), 0 };
  36761. static const juce_wchar* const keywords5Char[] =
  36762. { JUCE_T("while"), JUCE_T("bitor"), JUCE_T("break"), JUCE_T("catch"), JUCE_T("class"), JUCE_T("compl"), JUCE_T("const"), JUCE_T("false"),
  36763. JUCE_T("float"), JUCE_T("short"), JUCE_T("throw"), JUCE_T("union"), JUCE_T("using"), JUCE_T("or_eq"), 0 };
  36764. static const juce_wchar* const keywords6Char[] =
  36765. { JUCE_T("return"), JUCE_T("struct"), JUCE_T("and_eq"), JUCE_T("bitand"), JUCE_T("delete"), JUCE_T("double"), JUCE_T("extern"),
  36766. JUCE_T("friend"), JUCE_T("inline"), JUCE_T("not_eq"), JUCE_T("public"), JUCE_T("sizeof"), JUCE_T("static"), JUCE_T("signed"),
  36767. JUCE_T("switch"), JUCE_T("typeid"), JUCE_T("wchar_t"), JUCE_T("xor_eq"), 0};
  36768. static const juce_wchar* const keywordsOther[] =
  36769. { JUCE_T("const_cast"), JUCE_T("continue"), JUCE_T("default"), JUCE_T("explicit"), JUCE_T("mutable"), JUCE_T("namespace"),
  36770. JUCE_T("operator"), JUCE_T("private"), JUCE_T("protected"), JUCE_T("register"), JUCE_T("reinterpret_cast"), JUCE_T("static_cast"),
  36771. JUCE_T("template"), JUCE_T("typedef"), JUCE_T("typename"), JUCE_T("unsigned"), JUCE_T("virtual"), JUCE_T("volatile"),
  36772. JUCE_T("@implementation"), JUCE_T("@interface"), JUCE_T("@end"), JUCE_T("@synthesize"), JUCE_T("@dynamic"), JUCE_T("@public"),
  36773. JUCE_T("@private"), JUCE_T("@property"), JUCE_T("@protected"), JUCE_T("@class"), 0 };
  36774. const juce_wchar* const* k;
  36775. switch (tokenLength)
  36776. {
  36777. case 2: k = keywords2Char; break;
  36778. case 3: k = keywords3Char; break;
  36779. case 4: k = keywords4Char; break;
  36780. case 5: k = keywords5Char; break;
  36781. case 6: k = keywords6Char; break;
  36782. default:
  36783. if (tokenLength < 2 || tokenLength > 16)
  36784. return false;
  36785. k = keywordsOther;
  36786. break;
  36787. }
  36788. int i = 0;
  36789. while (k[i] != 0)
  36790. {
  36791. if (k[i][0] == token[0] && CharacterFunctions::compare (k[i], token) == 0)
  36792. return true;
  36793. ++i;
  36794. }
  36795. return false;
  36796. }
  36797. static int parseIdentifier (CodeDocument::Iterator& source) throw()
  36798. {
  36799. int tokenLength = 0;
  36800. juce_wchar possibleIdentifier [19];
  36801. while (isIdentifierBody (source.peekNextChar()))
  36802. {
  36803. const juce_wchar c = source.nextChar();
  36804. if (tokenLength < numElementsInArray (possibleIdentifier) - 1)
  36805. possibleIdentifier [tokenLength] = c;
  36806. ++tokenLength;
  36807. }
  36808. if (tokenLength > 1 && tokenLength <= 16)
  36809. {
  36810. possibleIdentifier [tokenLength] = 0;
  36811. if (isReservedKeyword (possibleIdentifier, tokenLength))
  36812. return CPlusPlusCodeTokeniser::tokenType_builtInKeyword;
  36813. }
  36814. return CPlusPlusCodeTokeniser::tokenType_identifier;
  36815. }
  36816. static bool skipNumberSuffix (CodeDocument::Iterator& source)
  36817. {
  36818. const juce_wchar c = source.peekNextChar();
  36819. if (c == 'l' || c == 'L' || c == 'u' || c == 'U')
  36820. source.skip();
  36821. if (CharacterFunctions::isLetterOrDigit (source.peekNextChar()))
  36822. return false;
  36823. return true;
  36824. }
  36825. static bool isHexDigit (const juce_wchar c) throw()
  36826. {
  36827. return (c >= '0' && c <= '9')
  36828. || (c >= 'a' && c <= 'f')
  36829. || (c >= 'A' && c <= 'F');
  36830. }
  36831. static bool parseHexLiteral (CodeDocument::Iterator& source) throw()
  36832. {
  36833. if (source.nextChar() != '0')
  36834. return false;
  36835. juce_wchar c = source.nextChar();
  36836. if (c != 'x' && c != 'X')
  36837. return false;
  36838. int numDigits = 0;
  36839. while (isHexDigit (source.peekNextChar()))
  36840. {
  36841. ++numDigits;
  36842. source.skip();
  36843. }
  36844. if (numDigits == 0)
  36845. return false;
  36846. return skipNumberSuffix (source);
  36847. }
  36848. static bool isOctalDigit (const juce_wchar c) throw()
  36849. {
  36850. return c >= '0' && c <= '7';
  36851. }
  36852. static bool parseOctalLiteral (CodeDocument::Iterator& source) throw()
  36853. {
  36854. if (source.nextChar() != '0')
  36855. return false;
  36856. if (! isOctalDigit (source.nextChar()))
  36857. return false;
  36858. while (isOctalDigit (source.peekNextChar()))
  36859. source.skip();
  36860. return skipNumberSuffix (source);
  36861. }
  36862. static bool isDecimalDigit (const juce_wchar c) throw()
  36863. {
  36864. return c >= '0' && c <= '9';
  36865. }
  36866. static bool parseDecimalLiteral (CodeDocument::Iterator& source) throw()
  36867. {
  36868. int numChars = 0;
  36869. while (isDecimalDigit (source.peekNextChar()))
  36870. {
  36871. ++numChars;
  36872. source.skip();
  36873. }
  36874. if (numChars == 0)
  36875. return false;
  36876. return skipNumberSuffix (source);
  36877. }
  36878. static bool parseFloatLiteral (CodeDocument::Iterator& source) throw()
  36879. {
  36880. int numDigits = 0;
  36881. while (isDecimalDigit (source.peekNextChar()))
  36882. {
  36883. source.skip();
  36884. ++numDigits;
  36885. }
  36886. const bool hasPoint = (source.peekNextChar() == '.');
  36887. if (hasPoint)
  36888. {
  36889. source.skip();
  36890. while (isDecimalDigit (source.peekNextChar()))
  36891. {
  36892. source.skip();
  36893. ++numDigits;
  36894. }
  36895. }
  36896. if (numDigits == 0)
  36897. return false;
  36898. juce_wchar c = source.peekNextChar();
  36899. const bool hasExponent = (c == 'e' || c == 'E');
  36900. if (hasExponent)
  36901. {
  36902. source.skip();
  36903. c = source.peekNextChar();
  36904. if (c == '+' || c == '-')
  36905. source.skip();
  36906. int numExpDigits = 0;
  36907. while (isDecimalDigit (source.peekNextChar()))
  36908. {
  36909. source.skip();
  36910. ++numExpDigits;
  36911. }
  36912. if (numExpDigits == 0)
  36913. return false;
  36914. }
  36915. c = source.peekNextChar();
  36916. if (c == 'f' || c == 'F')
  36917. source.skip();
  36918. else if (! (hasExponent || hasPoint))
  36919. return false;
  36920. return true;
  36921. }
  36922. static int parseNumber (CodeDocument::Iterator& source)
  36923. {
  36924. const CodeDocument::Iterator original (source);
  36925. if (parseFloatLiteral (source))
  36926. return CPlusPlusCodeTokeniser::tokenType_floatLiteral;
  36927. source = original;
  36928. if (parseHexLiteral (source))
  36929. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  36930. source = original;
  36931. if (parseOctalLiteral (source))
  36932. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  36933. source = original;
  36934. if (parseDecimalLiteral (source))
  36935. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  36936. source = original;
  36937. source.skip();
  36938. return CPlusPlusCodeTokeniser::tokenType_error;
  36939. }
  36940. static void skipQuotedString (CodeDocument::Iterator& source) throw()
  36941. {
  36942. const juce_wchar quote = source.nextChar();
  36943. for (;;)
  36944. {
  36945. const juce_wchar c = source.nextChar();
  36946. if (c == quote || c == 0)
  36947. break;
  36948. if (c == '\\')
  36949. source.skip();
  36950. }
  36951. }
  36952. static void skipComment (CodeDocument::Iterator& source) throw()
  36953. {
  36954. bool lastWasStar = false;
  36955. for (;;)
  36956. {
  36957. const juce_wchar c = source.nextChar();
  36958. if (c == 0 || (c == '/' && lastWasStar))
  36959. break;
  36960. lastWasStar = (c == '*');
  36961. }
  36962. }
  36963. }
  36964. int CPlusPlusCodeTokeniser::readNextToken (CodeDocument::Iterator& source)
  36965. {
  36966. int result = tokenType_error;
  36967. source.skipWhitespace();
  36968. juce_wchar firstChar = source.peekNextChar();
  36969. switch (firstChar)
  36970. {
  36971. case 0:
  36972. source.skip();
  36973. break;
  36974. case '0':
  36975. case '1':
  36976. case '2':
  36977. case '3':
  36978. case '4':
  36979. case '5':
  36980. case '6':
  36981. case '7':
  36982. case '8':
  36983. case '9':
  36984. result = CppTokeniser::parseNumber (source);
  36985. break;
  36986. case '.':
  36987. result = CppTokeniser::parseNumber (source);
  36988. if (result == tokenType_error)
  36989. result = tokenType_punctuation;
  36990. break;
  36991. case ',':
  36992. case ';':
  36993. case ':':
  36994. source.skip();
  36995. result = tokenType_punctuation;
  36996. break;
  36997. case '(':
  36998. case ')':
  36999. case '{':
  37000. case '}':
  37001. case '[':
  37002. case ']':
  37003. source.skip();
  37004. result = tokenType_bracket;
  37005. break;
  37006. case '"':
  37007. case '\'':
  37008. CppTokeniser::skipQuotedString (source);
  37009. result = tokenType_stringLiteral;
  37010. break;
  37011. case '+':
  37012. result = tokenType_operator;
  37013. source.skip();
  37014. if (source.peekNextChar() == '+')
  37015. source.skip();
  37016. else if (source.peekNextChar() == '=')
  37017. source.skip();
  37018. break;
  37019. case '-':
  37020. source.skip();
  37021. result = CppTokeniser::parseNumber (source);
  37022. if (result == tokenType_error)
  37023. {
  37024. result = tokenType_operator;
  37025. if (source.peekNextChar() == '-')
  37026. source.skip();
  37027. else if (source.peekNextChar() == '=')
  37028. source.skip();
  37029. }
  37030. break;
  37031. case '*':
  37032. case '%':
  37033. case '=':
  37034. case '!':
  37035. result = tokenType_operator;
  37036. source.skip();
  37037. if (source.peekNextChar() == '=')
  37038. source.skip();
  37039. break;
  37040. case '/':
  37041. result = tokenType_operator;
  37042. source.skip();
  37043. if (source.peekNextChar() == '=')
  37044. {
  37045. source.skip();
  37046. }
  37047. else if (source.peekNextChar() == '/')
  37048. {
  37049. result = tokenType_comment;
  37050. source.skipToEndOfLine();
  37051. }
  37052. else if (source.peekNextChar() == '*')
  37053. {
  37054. source.skip();
  37055. result = tokenType_comment;
  37056. CppTokeniser::skipComment (source);
  37057. }
  37058. break;
  37059. case '?':
  37060. case '~':
  37061. source.skip();
  37062. result = tokenType_operator;
  37063. break;
  37064. case '<':
  37065. source.skip();
  37066. result = tokenType_operator;
  37067. if (source.peekNextChar() == '=')
  37068. {
  37069. source.skip();
  37070. }
  37071. else if (source.peekNextChar() == '<')
  37072. {
  37073. source.skip();
  37074. if (source.peekNextChar() == '=')
  37075. source.skip();
  37076. }
  37077. break;
  37078. case '>':
  37079. source.skip();
  37080. result = tokenType_operator;
  37081. if (source.peekNextChar() == '=')
  37082. {
  37083. source.skip();
  37084. }
  37085. else if (source.peekNextChar() == '<')
  37086. {
  37087. source.skip();
  37088. if (source.peekNextChar() == '=')
  37089. source.skip();
  37090. }
  37091. break;
  37092. case '|':
  37093. source.skip();
  37094. result = tokenType_operator;
  37095. if (source.peekNextChar() == '=')
  37096. {
  37097. source.skip();
  37098. }
  37099. else if (source.peekNextChar() == '|')
  37100. {
  37101. source.skip();
  37102. if (source.peekNextChar() == '=')
  37103. source.skip();
  37104. }
  37105. break;
  37106. case '&':
  37107. source.skip();
  37108. result = tokenType_operator;
  37109. if (source.peekNextChar() == '=')
  37110. {
  37111. source.skip();
  37112. }
  37113. else if (source.peekNextChar() == '&')
  37114. {
  37115. source.skip();
  37116. if (source.peekNextChar() == '=')
  37117. source.skip();
  37118. }
  37119. break;
  37120. case '^':
  37121. source.skip();
  37122. result = tokenType_operator;
  37123. if (source.peekNextChar() == '=')
  37124. {
  37125. source.skip();
  37126. }
  37127. else if (source.peekNextChar() == '^')
  37128. {
  37129. source.skip();
  37130. if (source.peekNextChar() == '=')
  37131. source.skip();
  37132. }
  37133. break;
  37134. case '#':
  37135. result = tokenType_preprocessor;
  37136. source.skipToEndOfLine();
  37137. break;
  37138. default:
  37139. if (CppTokeniser::isIdentifierStart (firstChar))
  37140. result = CppTokeniser::parseIdentifier (source);
  37141. else
  37142. source.skip();
  37143. break;
  37144. }
  37145. return result;
  37146. }
  37147. const StringArray CPlusPlusCodeTokeniser::getTokenTypes()
  37148. {
  37149. const char* const types[] =
  37150. {
  37151. "Error",
  37152. "Comment",
  37153. "C++ keyword",
  37154. "Identifier",
  37155. "Integer literal",
  37156. "Float literal",
  37157. "String literal",
  37158. "Operator",
  37159. "Bracket",
  37160. "Punctuation",
  37161. "Preprocessor line",
  37162. 0
  37163. };
  37164. return StringArray (types);
  37165. }
  37166. const Colour CPlusPlusCodeTokeniser::getDefaultColour (const int tokenType)
  37167. {
  37168. const uint32 colours[] =
  37169. {
  37170. 0xffcc0000, // error
  37171. 0xff00aa00, // comment
  37172. 0xff0000cc, // keyword
  37173. 0xff000000, // identifier
  37174. 0xff880000, // int literal
  37175. 0xff885500, // float literal
  37176. 0xff990099, // string literal
  37177. 0xff225500, // operator
  37178. 0xff000055, // bracket
  37179. 0xff004400, // punctuation
  37180. 0xff660000 // preprocessor
  37181. };
  37182. if (tokenType >= 0 && tokenType < numElementsInArray (colours))
  37183. return Colour (colours [tokenType]);
  37184. return Colours::black;
  37185. }
  37186. bool CPlusPlusCodeTokeniser::isReservedKeyword (const String& token) throw()
  37187. {
  37188. return CppTokeniser::isReservedKeyword (token, token.length());
  37189. }
  37190. END_JUCE_NAMESPACE
  37191. /*** End of inlined file: juce_CPlusPlusCodeTokeniser.cpp ***/
  37192. /*** Start of inlined file: juce_ComboBox.cpp ***/
  37193. BEGIN_JUCE_NAMESPACE
  37194. ComboBox::ComboBox (const String& name)
  37195. : Component (name),
  37196. lastCurrentId (0),
  37197. isButtonDown (false),
  37198. separatorPending (false),
  37199. menuActive (false),
  37200. label (0)
  37201. {
  37202. noChoicesMessage = TRANS("(no choices)");
  37203. setRepaintsOnMouseActivity (true);
  37204. lookAndFeelChanged();
  37205. currentId.addListener (this);
  37206. }
  37207. ComboBox::~ComboBox()
  37208. {
  37209. currentId.removeListener (this);
  37210. if (menuActive)
  37211. PopupMenu::dismissAllActiveMenus();
  37212. label = 0;
  37213. deleteAllChildren();
  37214. }
  37215. void ComboBox::setEditableText (const bool isEditable)
  37216. {
  37217. if (label->isEditableOnSingleClick() != isEditable || label->isEditableOnDoubleClick() != isEditable)
  37218. {
  37219. label->setEditable (isEditable, isEditable, false);
  37220. setWantsKeyboardFocus (! isEditable);
  37221. resized();
  37222. }
  37223. }
  37224. bool ComboBox::isTextEditable() const throw()
  37225. {
  37226. return label->isEditable();
  37227. }
  37228. void ComboBox::setJustificationType (const Justification& justification) throw()
  37229. {
  37230. label->setJustificationType (justification);
  37231. }
  37232. const Justification ComboBox::getJustificationType() const throw()
  37233. {
  37234. return label->getJustificationType();
  37235. }
  37236. void ComboBox::setTooltip (const String& newTooltip)
  37237. {
  37238. SettableTooltipClient::setTooltip (newTooltip);
  37239. label->setTooltip (newTooltip);
  37240. }
  37241. void ComboBox::addItem (const String& newItemText,
  37242. const int newItemId) throw()
  37243. {
  37244. // you can't add empty strings to the list..
  37245. jassert (newItemText.isNotEmpty());
  37246. // IDs must be non-zero, as zero is used to indicate a lack of selecion.
  37247. jassert (newItemId != 0);
  37248. // you shouldn't use duplicate item IDs!
  37249. jassert (getItemForId (newItemId) == 0);
  37250. if (newItemText.isNotEmpty() && newItemId != 0)
  37251. {
  37252. if (separatorPending)
  37253. {
  37254. separatorPending = false;
  37255. ItemInfo* const item = new ItemInfo();
  37256. item->itemId = 0;
  37257. item->isEnabled = false;
  37258. item->isHeading = false;
  37259. items.add (item);
  37260. }
  37261. ItemInfo* const item = new ItemInfo();
  37262. item->name = newItemText;
  37263. item->itemId = newItemId;
  37264. item->isEnabled = true;
  37265. item->isHeading = false;
  37266. items.add (item);
  37267. }
  37268. }
  37269. void ComboBox::addSeparator() throw()
  37270. {
  37271. separatorPending = (items.size() > 0);
  37272. }
  37273. void ComboBox::addSectionHeading (const String& headingName) throw()
  37274. {
  37275. // you can't add empty strings to the list..
  37276. jassert (headingName.isNotEmpty());
  37277. if (headingName.isNotEmpty())
  37278. {
  37279. if (separatorPending)
  37280. {
  37281. separatorPending = false;
  37282. ItemInfo* const item = new ItemInfo();
  37283. item->itemId = 0;
  37284. item->isEnabled = false;
  37285. item->isHeading = false;
  37286. items.add (item);
  37287. }
  37288. ItemInfo* const item = new ItemInfo();
  37289. item->name = headingName;
  37290. item->itemId = 0;
  37291. item->isEnabled = true;
  37292. item->isHeading = true;
  37293. items.add (item);
  37294. }
  37295. }
  37296. void ComboBox::setItemEnabled (const int itemId,
  37297. const bool shouldBeEnabled) throw()
  37298. {
  37299. ItemInfo* const item = getItemForId (itemId);
  37300. if (item != 0)
  37301. item->isEnabled = shouldBeEnabled;
  37302. }
  37303. void ComboBox::changeItemText (const int itemId,
  37304. const String& newText) throw()
  37305. {
  37306. ItemInfo* const item = getItemForId (itemId);
  37307. jassert (item != 0);
  37308. if (item != 0)
  37309. item->name = newText;
  37310. }
  37311. void ComboBox::clear (const bool dontSendChangeMessage)
  37312. {
  37313. items.clear();
  37314. separatorPending = false;
  37315. if (! label->isEditable())
  37316. setSelectedItemIndex (-1, dontSendChangeMessage);
  37317. }
  37318. bool ComboBox::ItemInfo::isSeparator() const throw()
  37319. {
  37320. return name.isEmpty();
  37321. }
  37322. bool ComboBox::ItemInfo::isRealItem() const throw()
  37323. {
  37324. return ! (isHeading || name.isEmpty());
  37325. }
  37326. ComboBox::ItemInfo* ComboBox::getItemForId (const int itemId) const throw()
  37327. {
  37328. if (itemId != 0)
  37329. {
  37330. for (int i = items.size(); --i >= 0;)
  37331. if (items.getUnchecked(i)->itemId == itemId)
  37332. return items.getUnchecked(i);
  37333. }
  37334. return 0;
  37335. }
  37336. ComboBox::ItemInfo* ComboBox::getItemForIndex (const int index) const throw()
  37337. {
  37338. int n = 0;
  37339. for (int i = 0; i < items.size(); ++i)
  37340. {
  37341. ItemInfo* const item = items.getUnchecked(i);
  37342. if (item->isRealItem())
  37343. if (n++ == index)
  37344. return item;
  37345. }
  37346. return 0;
  37347. }
  37348. int ComboBox::getNumItems() const throw()
  37349. {
  37350. int n = 0;
  37351. for (int i = items.size(); --i >= 0;)
  37352. if (items.getUnchecked(i)->isRealItem())
  37353. ++n;
  37354. return n;
  37355. }
  37356. const String ComboBox::getItemText (const int index) const throw()
  37357. {
  37358. const ItemInfo* const item = getItemForIndex (index);
  37359. if (item != 0)
  37360. return item->name;
  37361. return String::empty;
  37362. }
  37363. int ComboBox::getItemId (const int index) const throw()
  37364. {
  37365. const ItemInfo* const item = getItemForIndex (index);
  37366. return (item != 0) ? item->itemId : 0;
  37367. }
  37368. int ComboBox::indexOfItemId (const int itemId) const throw()
  37369. {
  37370. int n = 0;
  37371. for (int i = 0; i < items.size(); ++i)
  37372. {
  37373. const ItemInfo* const item = items.getUnchecked(i);
  37374. if (item->isRealItem())
  37375. {
  37376. if (item->itemId == itemId)
  37377. return n;
  37378. ++n;
  37379. }
  37380. }
  37381. return -1;
  37382. }
  37383. int ComboBox::getSelectedItemIndex() const throw()
  37384. {
  37385. int index = indexOfItemId (currentId.getValue());
  37386. if (getText() != getItemText (index))
  37387. index = -1;
  37388. return index;
  37389. }
  37390. void ComboBox::setSelectedItemIndex (const int index,
  37391. const bool dontSendChangeMessage) throw()
  37392. {
  37393. setSelectedId (getItemId (index), dontSendChangeMessage);
  37394. }
  37395. int ComboBox::getSelectedId() const throw()
  37396. {
  37397. const ItemInfo* const item = getItemForId (currentId.getValue());
  37398. return (item != 0 && getText() == item->name)
  37399. ? item->itemId
  37400. : 0;
  37401. }
  37402. void ComboBox::setSelectedId (const int newItemId,
  37403. const bool dontSendChangeMessage) throw()
  37404. {
  37405. const ItemInfo* const item = getItemForId (newItemId);
  37406. const String newItemText (item != 0 ? item->name : String::empty);
  37407. if (lastCurrentId != newItemId || label->getText() != newItemText)
  37408. {
  37409. if (! dontSendChangeMessage)
  37410. triggerAsyncUpdate();
  37411. label->setText (newItemText, false);
  37412. lastCurrentId = newItemId;
  37413. currentId = newItemId;
  37414. repaint(); // for the benefit of the 'none selected' text
  37415. }
  37416. }
  37417. void ComboBox::valueChanged (Value&)
  37418. {
  37419. if (lastCurrentId != (int) currentId.getValue())
  37420. setSelectedId (currentId.getValue(), false);
  37421. }
  37422. const String ComboBox::getText() const throw()
  37423. {
  37424. return label->getText();
  37425. }
  37426. void ComboBox::setText (const String& newText,
  37427. const bool dontSendChangeMessage) throw()
  37428. {
  37429. for (int i = items.size(); --i >= 0;)
  37430. {
  37431. const ItemInfo* const item = items.getUnchecked(i);
  37432. if (item->isRealItem()
  37433. && item->name == newText)
  37434. {
  37435. setSelectedId (item->itemId, dontSendChangeMessage);
  37436. return;
  37437. }
  37438. }
  37439. lastCurrentId = 0;
  37440. currentId = 0;
  37441. if (label->getText() != newText)
  37442. {
  37443. label->setText (newText, false);
  37444. if (! dontSendChangeMessage)
  37445. triggerAsyncUpdate();
  37446. }
  37447. repaint();
  37448. }
  37449. void ComboBox::showEditor()
  37450. {
  37451. jassert (isTextEditable()); // you probably shouldn't do this to a non-editable combo box?
  37452. label->showEditor();
  37453. }
  37454. void ComboBox::setTextWhenNothingSelected (const String& newMessage) throw()
  37455. {
  37456. if (textWhenNothingSelected != newMessage)
  37457. {
  37458. textWhenNothingSelected = newMessage;
  37459. repaint();
  37460. }
  37461. }
  37462. const String ComboBox::getTextWhenNothingSelected() const throw()
  37463. {
  37464. return textWhenNothingSelected;
  37465. }
  37466. void ComboBox::setTextWhenNoChoicesAvailable (const String& newMessage) throw()
  37467. {
  37468. noChoicesMessage = newMessage;
  37469. }
  37470. const String ComboBox::getTextWhenNoChoicesAvailable() const throw()
  37471. {
  37472. return noChoicesMessage;
  37473. }
  37474. void ComboBox::paint (Graphics& g)
  37475. {
  37476. getLookAndFeel().drawComboBox (g,
  37477. getWidth(),
  37478. getHeight(),
  37479. isButtonDown,
  37480. label->getRight(),
  37481. 0,
  37482. getWidth() - label->getRight(),
  37483. getHeight(),
  37484. *this);
  37485. if (textWhenNothingSelected.isNotEmpty()
  37486. && label->getText().isEmpty()
  37487. && ! label->isBeingEdited())
  37488. {
  37489. g.setColour (findColour (textColourId).withMultipliedAlpha (0.5f));
  37490. g.setFont (label->getFont());
  37491. g.drawFittedText (textWhenNothingSelected,
  37492. label->getX() + 2, label->getY() + 1,
  37493. label->getWidth() - 4, label->getHeight() - 2,
  37494. label->getJustificationType(),
  37495. jmax (1, (int) (label->getHeight() / label->getFont().getHeight())));
  37496. }
  37497. }
  37498. void ComboBox::resized()
  37499. {
  37500. if (getHeight() > 0 && getWidth() > 0)
  37501. getLookAndFeel().positionComboBoxText (*this, *label);
  37502. }
  37503. void ComboBox::enablementChanged()
  37504. {
  37505. repaint();
  37506. }
  37507. void ComboBox::lookAndFeelChanged()
  37508. {
  37509. repaint();
  37510. Label* const newLabel = getLookAndFeel().createComboBoxTextBox (*this);
  37511. if (label != 0)
  37512. {
  37513. newLabel->setEditable (label->isEditable());
  37514. newLabel->setJustificationType (label->getJustificationType());
  37515. newLabel->setTooltip (label->getTooltip());
  37516. newLabel->setText (label->getText(), false);
  37517. }
  37518. label = newLabel;
  37519. addAndMakeVisible (newLabel);
  37520. newLabel->addListener (this);
  37521. newLabel->addMouseListener (this, false);
  37522. newLabel->setColour (Label::backgroundColourId, Colours::transparentBlack);
  37523. newLabel->setColour (Label::textColourId, findColour (ComboBox::textColourId));
  37524. newLabel->setColour (TextEditor::textColourId, findColour (ComboBox::textColourId));
  37525. newLabel->setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  37526. newLabel->setColour (TextEditor::highlightColourId, findColour (TextEditor::highlightColourId));
  37527. newLabel->setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  37528. resized();
  37529. }
  37530. void ComboBox::colourChanged()
  37531. {
  37532. lookAndFeelChanged();
  37533. }
  37534. bool ComboBox::keyPressed (const KeyPress& key)
  37535. {
  37536. bool used = false;
  37537. if (key.isKeyCode (KeyPress::upKey)
  37538. || key.isKeyCode (KeyPress::leftKey))
  37539. {
  37540. setSelectedItemIndex (jmax (0, getSelectedItemIndex() - 1));
  37541. used = true;
  37542. }
  37543. else if (key.isKeyCode (KeyPress::downKey)
  37544. || key.isKeyCode (KeyPress::rightKey))
  37545. {
  37546. setSelectedItemIndex (jmin (getSelectedItemIndex() + 1, getNumItems() - 1));
  37547. used = true;
  37548. }
  37549. else if (key.isKeyCode (KeyPress::returnKey))
  37550. {
  37551. showPopup();
  37552. used = true;
  37553. }
  37554. return used;
  37555. }
  37556. bool ComboBox::keyStateChanged (const bool isKeyDown)
  37557. {
  37558. // only forward key events that aren't used by this component
  37559. return isKeyDown
  37560. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  37561. || KeyPress::isKeyCurrentlyDown (KeyPress::leftKey)
  37562. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  37563. || KeyPress::isKeyCurrentlyDown (KeyPress::rightKey));
  37564. }
  37565. void ComboBox::focusGained (FocusChangeType)
  37566. {
  37567. repaint();
  37568. }
  37569. void ComboBox::focusLost (FocusChangeType)
  37570. {
  37571. repaint();
  37572. }
  37573. void ComboBox::labelTextChanged (Label*)
  37574. {
  37575. triggerAsyncUpdate();
  37576. }
  37577. void ComboBox::showPopup()
  37578. {
  37579. if (! menuActive)
  37580. {
  37581. const int selectedId = getSelectedId();
  37582. Component::SafePointer<Component> deletionWatcher (this);
  37583. PopupMenu menu;
  37584. menu.setLookAndFeel (&getLookAndFeel());
  37585. for (int i = 0; i < items.size(); ++i)
  37586. {
  37587. const ItemInfo* const item = items.getUnchecked(i);
  37588. if (item->isSeparator())
  37589. menu.addSeparator();
  37590. else if (item->isHeading)
  37591. menu.addSectionHeader (item->name);
  37592. else
  37593. menu.addItem (item->itemId, item->name,
  37594. item->isEnabled, item->itemId == selectedId);
  37595. }
  37596. if (items.size() == 0)
  37597. menu.addItem (1, noChoicesMessage, false);
  37598. const int itemHeight = jlimit (12, 24, getHeight());
  37599. menuActive = true;
  37600. const int resultId = menu.showAt (this, selectedId,
  37601. getWidth(), 1, itemHeight);
  37602. if (deletionWatcher == 0)
  37603. return;
  37604. menuActive = false;
  37605. if (resultId != 0)
  37606. setSelectedId (resultId);
  37607. }
  37608. }
  37609. void ComboBox::mouseDown (const MouseEvent& e)
  37610. {
  37611. beginDragAutoRepeat (300);
  37612. isButtonDown = isEnabled();
  37613. if (isButtonDown
  37614. && (e.eventComponent == this || ! label->isEditable()))
  37615. {
  37616. showPopup();
  37617. }
  37618. }
  37619. void ComboBox::mouseDrag (const MouseEvent& e)
  37620. {
  37621. beginDragAutoRepeat (50);
  37622. if (isButtonDown && ! e.mouseWasClicked())
  37623. showPopup();
  37624. }
  37625. void ComboBox::mouseUp (const MouseEvent& e2)
  37626. {
  37627. if (isButtonDown)
  37628. {
  37629. isButtonDown = false;
  37630. repaint();
  37631. const MouseEvent e (e2.getEventRelativeTo (this));
  37632. if (reallyContains (e.x, e.y, true)
  37633. && (e2.eventComponent == this || ! label->isEditable()))
  37634. {
  37635. showPopup();
  37636. }
  37637. }
  37638. }
  37639. void ComboBox::addListener (ComboBoxListener* const listener) throw()
  37640. {
  37641. listeners.add (listener);
  37642. }
  37643. void ComboBox::removeListener (ComboBoxListener* const listener) throw()
  37644. {
  37645. listeners.remove (listener);
  37646. }
  37647. void ComboBox::handleAsyncUpdate()
  37648. {
  37649. Component::BailOutChecker checker (this);
  37650. listeners.callChecked (checker, &ComboBoxListener::comboBoxChanged, this);
  37651. }
  37652. END_JUCE_NAMESPACE
  37653. /*** End of inlined file: juce_ComboBox.cpp ***/
  37654. /*** Start of inlined file: juce_Label.cpp ***/
  37655. BEGIN_JUCE_NAMESPACE
  37656. Label::Label (const String& componentName,
  37657. const String& labelText)
  37658. : Component (componentName),
  37659. textValue (labelText),
  37660. lastTextValue (labelText),
  37661. font (15.0f),
  37662. justification (Justification::centredLeft),
  37663. ownerComponent (0),
  37664. horizontalBorderSize (5),
  37665. verticalBorderSize (1),
  37666. minimumHorizontalScale (0.7f),
  37667. editSingleClick (false),
  37668. editDoubleClick (false),
  37669. lossOfFocusDiscardsChanges (false)
  37670. {
  37671. setColour (TextEditor::textColourId, Colours::black);
  37672. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  37673. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  37674. textValue.addListener (this);
  37675. }
  37676. Label::~Label()
  37677. {
  37678. textValue.removeListener (this);
  37679. if (ownerComponent != 0)
  37680. ownerComponent->removeComponentListener (this);
  37681. editor = 0;
  37682. }
  37683. void Label::setText (const String& newText,
  37684. const bool broadcastChangeMessage)
  37685. {
  37686. hideEditor (true);
  37687. if (lastTextValue != newText)
  37688. {
  37689. lastTextValue = newText;
  37690. textValue = newText;
  37691. repaint();
  37692. textWasChanged();
  37693. if (ownerComponent != 0)
  37694. componentMovedOrResized (*ownerComponent, true, true);
  37695. if (broadcastChangeMessage)
  37696. callChangeListeners();
  37697. }
  37698. }
  37699. const String Label::getText (const bool returnActiveEditorContents) const throw()
  37700. {
  37701. return (returnActiveEditorContents && isBeingEdited())
  37702. ? editor->getText()
  37703. : textValue.toString();
  37704. }
  37705. void Label::valueChanged (Value&)
  37706. {
  37707. if (lastTextValue != textValue.toString())
  37708. setText (textValue.toString(), true);
  37709. }
  37710. void Label::setFont (const Font& newFont) throw()
  37711. {
  37712. if (font != newFont)
  37713. {
  37714. font = newFont;
  37715. repaint();
  37716. }
  37717. }
  37718. const Font& Label::getFont() const throw()
  37719. {
  37720. return font;
  37721. }
  37722. void Label::setEditable (const bool editOnSingleClick,
  37723. const bool editOnDoubleClick,
  37724. const bool lossOfFocusDiscardsChanges_) throw()
  37725. {
  37726. editSingleClick = editOnSingleClick;
  37727. editDoubleClick = editOnDoubleClick;
  37728. lossOfFocusDiscardsChanges = lossOfFocusDiscardsChanges_;
  37729. setWantsKeyboardFocus (editOnSingleClick || editOnDoubleClick);
  37730. setFocusContainer (editOnSingleClick || editOnDoubleClick);
  37731. }
  37732. void Label::setJustificationType (const Justification& newJustification) throw()
  37733. {
  37734. if (justification != newJustification)
  37735. {
  37736. justification = newJustification;
  37737. repaint();
  37738. }
  37739. }
  37740. void Label::setBorderSize (int h, int v)
  37741. {
  37742. if (horizontalBorderSize != h || verticalBorderSize != v)
  37743. {
  37744. horizontalBorderSize = h;
  37745. verticalBorderSize = v;
  37746. repaint();
  37747. }
  37748. }
  37749. Component* Label::getAttachedComponent() const
  37750. {
  37751. return static_cast<Component*> (ownerComponent);
  37752. }
  37753. void Label::attachToComponent (Component* owner,
  37754. const bool onLeft)
  37755. {
  37756. if (ownerComponent != 0)
  37757. ownerComponent->removeComponentListener (this);
  37758. ownerComponent = owner;
  37759. leftOfOwnerComp = onLeft;
  37760. if (ownerComponent != 0)
  37761. {
  37762. setVisible (owner->isVisible());
  37763. ownerComponent->addComponentListener (this);
  37764. componentParentHierarchyChanged (*ownerComponent);
  37765. componentMovedOrResized (*ownerComponent, true, true);
  37766. }
  37767. }
  37768. void Label::componentMovedOrResized (Component& component, bool /*wasMoved*/, bool /*wasResized*/)
  37769. {
  37770. if (leftOfOwnerComp)
  37771. {
  37772. setSize (jmin (getFont().getStringWidth (textValue.toString()) + 8, component.getX()),
  37773. component.getHeight());
  37774. setTopRightPosition (component.getX(), component.getY());
  37775. }
  37776. else
  37777. {
  37778. setSize (component.getWidth(),
  37779. 8 + roundToInt (getFont().getHeight()));
  37780. setTopLeftPosition (component.getX(), component.getY() - getHeight());
  37781. }
  37782. }
  37783. void Label::componentParentHierarchyChanged (Component& component)
  37784. {
  37785. if (component.getParentComponent() != 0)
  37786. component.getParentComponent()->addChildComponent (this);
  37787. }
  37788. void Label::componentVisibilityChanged (Component& component)
  37789. {
  37790. setVisible (component.isVisible());
  37791. }
  37792. void Label::textWasEdited()
  37793. {
  37794. }
  37795. void Label::textWasChanged()
  37796. {
  37797. }
  37798. void Label::showEditor()
  37799. {
  37800. if (editor == 0)
  37801. {
  37802. addAndMakeVisible (editor = createEditorComponent());
  37803. editor->setText (getText(), false);
  37804. editor->addListener (this);
  37805. editor->grabKeyboardFocus();
  37806. editor->setHighlightedRegion (Range<int> (0, textValue.toString().length()));
  37807. editor->addListener (this);
  37808. resized();
  37809. repaint();
  37810. editorShown (editor);
  37811. enterModalState (false);
  37812. editor->grabKeyboardFocus();
  37813. }
  37814. }
  37815. void Label::editorShown (TextEditor* /*editorComponent*/)
  37816. {
  37817. }
  37818. void Label::editorAboutToBeHidden (TextEditor* /*editorComponent*/)
  37819. {
  37820. }
  37821. bool Label::updateFromTextEditorContents()
  37822. {
  37823. jassert (editor != 0);
  37824. const String newText (editor->getText());
  37825. if (textValue.toString() != newText)
  37826. {
  37827. lastTextValue = newText;
  37828. textValue = newText;
  37829. repaint();
  37830. textWasChanged();
  37831. if (ownerComponent != 0)
  37832. componentMovedOrResized (*ownerComponent, true, true);
  37833. return true;
  37834. }
  37835. return false;
  37836. }
  37837. void Label::hideEditor (const bool discardCurrentEditorContents)
  37838. {
  37839. if (editor != 0)
  37840. {
  37841. Component::SafePointer<Component> deletionChecker (this);
  37842. editorAboutToBeHidden (editor);
  37843. const bool changed = (! discardCurrentEditorContents)
  37844. && updateFromTextEditorContents();
  37845. editor = 0;
  37846. repaint();
  37847. if (changed)
  37848. textWasEdited();
  37849. if (deletionChecker != 0)
  37850. exitModalState (0);
  37851. if (changed && deletionChecker != 0)
  37852. callChangeListeners();
  37853. }
  37854. }
  37855. void Label::inputAttemptWhenModal()
  37856. {
  37857. if (editor != 0)
  37858. {
  37859. if (lossOfFocusDiscardsChanges)
  37860. textEditorEscapeKeyPressed (*editor);
  37861. else
  37862. textEditorReturnKeyPressed (*editor);
  37863. }
  37864. }
  37865. bool Label::isBeingEdited() const throw()
  37866. {
  37867. return editor != 0;
  37868. }
  37869. TextEditor* Label::createEditorComponent()
  37870. {
  37871. TextEditor* const ed = new TextEditor (getName());
  37872. ed->setFont (font);
  37873. // copy these colours from our own settings..
  37874. const int cols[] = { TextEditor::backgroundColourId,
  37875. TextEditor::textColourId,
  37876. TextEditor::highlightColourId,
  37877. TextEditor::highlightedTextColourId,
  37878. TextEditor::caretColourId,
  37879. TextEditor::outlineColourId,
  37880. TextEditor::focusedOutlineColourId,
  37881. TextEditor::shadowColourId };
  37882. for (int i = 0; i < numElementsInArray (cols); ++i)
  37883. ed->setColour (cols[i], findColour (cols[i]));
  37884. return ed;
  37885. }
  37886. void Label::paint (Graphics& g)
  37887. {
  37888. getLookAndFeel().drawLabel (g, *this);
  37889. }
  37890. void Label::mouseUp (const MouseEvent& e)
  37891. {
  37892. if (editSingleClick
  37893. && e.mouseWasClicked()
  37894. && contains (e.x, e.y)
  37895. && ! e.mods.isPopupMenu())
  37896. {
  37897. showEditor();
  37898. }
  37899. }
  37900. void Label::mouseDoubleClick (const MouseEvent& e)
  37901. {
  37902. if (editDoubleClick && ! e.mods.isPopupMenu())
  37903. showEditor();
  37904. }
  37905. void Label::resized()
  37906. {
  37907. if (editor != 0)
  37908. editor->setBoundsInset (BorderSize (0));
  37909. }
  37910. void Label::focusGained (FocusChangeType cause)
  37911. {
  37912. if (editSingleClick && cause == focusChangedByTabKey)
  37913. showEditor();
  37914. }
  37915. void Label::enablementChanged()
  37916. {
  37917. repaint();
  37918. }
  37919. void Label::colourChanged()
  37920. {
  37921. repaint();
  37922. }
  37923. void Label::setMinimumHorizontalScale (const float newScale)
  37924. {
  37925. if (minimumHorizontalScale != newScale)
  37926. {
  37927. minimumHorizontalScale = newScale;
  37928. repaint();
  37929. }
  37930. }
  37931. // We'll use a custom focus traverser here to make sure focus goes from the
  37932. // text editor to another component rather than back to the label itself.
  37933. class LabelKeyboardFocusTraverser : public KeyboardFocusTraverser
  37934. {
  37935. public:
  37936. LabelKeyboardFocusTraverser() {}
  37937. Component* getNextComponent (Component* current)
  37938. {
  37939. return KeyboardFocusTraverser::getNextComponent (dynamic_cast <TextEditor*> (current) != 0
  37940. ? current->getParentComponent() : current);
  37941. }
  37942. Component* getPreviousComponent (Component* current)
  37943. {
  37944. return KeyboardFocusTraverser::getPreviousComponent (dynamic_cast <TextEditor*> (current) != 0
  37945. ? current->getParentComponent() : current);
  37946. }
  37947. };
  37948. KeyboardFocusTraverser* Label::createFocusTraverser()
  37949. {
  37950. return new LabelKeyboardFocusTraverser();
  37951. }
  37952. void Label::addListener (LabelListener* const listener) throw()
  37953. {
  37954. listeners.add (listener);
  37955. }
  37956. void Label::removeListener (LabelListener* const listener) throw()
  37957. {
  37958. listeners.remove (listener);
  37959. }
  37960. void Label::callChangeListeners()
  37961. {
  37962. Component::BailOutChecker checker (this);
  37963. listeners.callChecked (checker, &LabelListener::labelTextChanged, this);
  37964. }
  37965. void Label::textEditorTextChanged (TextEditor& ed)
  37966. {
  37967. if (editor != 0)
  37968. {
  37969. jassert (&ed == editor);
  37970. if (! (hasKeyboardFocus (true) || isCurrentlyBlockedByAnotherModalComponent()))
  37971. {
  37972. if (lossOfFocusDiscardsChanges)
  37973. textEditorEscapeKeyPressed (ed);
  37974. else
  37975. textEditorReturnKeyPressed (ed);
  37976. }
  37977. }
  37978. }
  37979. void Label::textEditorReturnKeyPressed (TextEditor& ed)
  37980. {
  37981. if (editor != 0)
  37982. {
  37983. jassert (&ed == editor);
  37984. (void) ed;
  37985. const bool changed = updateFromTextEditorContents();
  37986. hideEditor (true);
  37987. if (changed)
  37988. {
  37989. Component::SafePointer<Component> deletionChecker (this);
  37990. textWasEdited();
  37991. if (deletionChecker != 0)
  37992. callChangeListeners();
  37993. }
  37994. }
  37995. }
  37996. void Label::textEditorEscapeKeyPressed (TextEditor& ed)
  37997. {
  37998. if (editor != 0)
  37999. {
  38000. jassert (&ed == editor);
  38001. (void) ed;
  38002. editor->setText (textValue.toString(), false);
  38003. hideEditor (true);
  38004. }
  38005. }
  38006. void Label::textEditorFocusLost (TextEditor& ed)
  38007. {
  38008. textEditorTextChanged (ed);
  38009. }
  38010. END_JUCE_NAMESPACE
  38011. /*** End of inlined file: juce_Label.cpp ***/
  38012. /*** Start of inlined file: juce_ListBox.cpp ***/
  38013. BEGIN_JUCE_NAMESPACE
  38014. class ListBoxRowComponent : public Component,
  38015. public TooltipClient
  38016. {
  38017. public:
  38018. ListBoxRowComponent (ListBox& owner_)
  38019. : owner (owner_),
  38020. row (-1),
  38021. selected (false),
  38022. isDragging (false)
  38023. {
  38024. }
  38025. ~ListBoxRowComponent()
  38026. {
  38027. deleteAllChildren();
  38028. }
  38029. void paint (Graphics& g)
  38030. {
  38031. if (owner.getModel() != 0)
  38032. owner.getModel()->paintListBoxItem (row, g, getWidth(), getHeight(), selected);
  38033. }
  38034. void update (const int row_, const bool selected_)
  38035. {
  38036. if (row != row_ || selected != selected_)
  38037. {
  38038. repaint();
  38039. row = row_;
  38040. selected = selected_;
  38041. }
  38042. if (owner.getModel() != 0)
  38043. {
  38044. Component* const customComp = owner.getModel()->refreshComponentForRow (row_, selected_, getChildComponent (0));
  38045. if (customComp != 0)
  38046. {
  38047. addAndMakeVisible (customComp);
  38048. customComp->setBounds (0, 0, getWidth(), getHeight());
  38049. for (int i = getNumChildComponents(); --i >= 0;)
  38050. if (getChildComponent (i) != customComp)
  38051. delete getChildComponent (i);
  38052. }
  38053. else
  38054. {
  38055. deleteAllChildren();
  38056. }
  38057. }
  38058. }
  38059. void mouseDown (const MouseEvent& e)
  38060. {
  38061. isDragging = false;
  38062. selectRowOnMouseUp = false;
  38063. if (isEnabled())
  38064. {
  38065. if (! selected)
  38066. {
  38067. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  38068. if (owner.getModel() != 0)
  38069. owner.getModel()->listBoxItemClicked (row, e);
  38070. }
  38071. else
  38072. {
  38073. selectRowOnMouseUp = true;
  38074. }
  38075. }
  38076. }
  38077. void mouseUp (const MouseEvent& e)
  38078. {
  38079. if (isEnabled() && selectRowOnMouseUp && ! isDragging)
  38080. {
  38081. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  38082. if (owner.getModel() != 0)
  38083. owner.getModel()->listBoxItemClicked (row, e);
  38084. }
  38085. }
  38086. void mouseDoubleClick (const MouseEvent& e)
  38087. {
  38088. if (owner.getModel() != 0 && isEnabled())
  38089. owner.getModel()->listBoxItemDoubleClicked (row, e);
  38090. }
  38091. void mouseDrag (const MouseEvent& e)
  38092. {
  38093. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  38094. {
  38095. const SparseSet<int> selectedRows (owner.getSelectedRows());
  38096. if (selectedRows.size() > 0)
  38097. {
  38098. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  38099. if (dragDescription.isNotEmpty())
  38100. {
  38101. isDragging = true;
  38102. owner.startDragAndDrop (e, dragDescription);
  38103. }
  38104. }
  38105. }
  38106. }
  38107. void resized()
  38108. {
  38109. if (getNumChildComponents() > 0)
  38110. getChildComponent(0)->setBounds (0, 0, getWidth(), getHeight());
  38111. }
  38112. const String getTooltip()
  38113. {
  38114. if (owner.getModel() != 0)
  38115. return owner.getModel()->getTooltipForRow (row);
  38116. return String::empty;
  38117. }
  38118. juce_UseDebuggingNewOperator
  38119. bool neededFlag;
  38120. private:
  38121. ListBox& owner;
  38122. int row;
  38123. bool selected, isDragging, selectRowOnMouseUp;
  38124. ListBoxRowComponent (const ListBoxRowComponent&);
  38125. ListBoxRowComponent& operator= (const ListBoxRowComponent&);
  38126. };
  38127. class ListViewport : public Viewport
  38128. {
  38129. public:
  38130. int firstIndex, firstWholeIndex, lastWholeIndex;
  38131. bool hasUpdated;
  38132. ListViewport (ListBox& owner_)
  38133. : owner (owner_)
  38134. {
  38135. setWantsKeyboardFocus (false);
  38136. setViewedComponent (new Component());
  38137. getViewedComponent()->addMouseListener (this, false);
  38138. getViewedComponent()->setWantsKeyboardFocus (false);
  38139. }
  38140. ~ListViewport()
  38141. {
  38142. getViewedComponent()->removeMouseListener (this);
  38143. getViewedComponent()->deleteAllChildren();
  38144. }
  38145. ListBoxRowComponent* getComponentForRow (const int row) const throw()
  38146. {
  38147. return static_cast <ListBoxRowComponent*>
  38148. (getViewedComponent()->getChildComponent (row % jmax (1, getViewedComponent()->getNumChildComponents())));
  38149. }
  38150. int getRowNumberOfComponent (Component* const rowComponent) const throw()
  38151. {
  38152. const int index = getIndexOfChildComponent (rowComponent);
  38153. const int num = getViewedComponent()->getNumChildComponents();
  38154. for (int i = num; --i >= 0;)
  38155. if (((firstIndex + i) % jmax (1, num)) == index)
  38156. return firstIndex + i;
  38157. return -1;
  38158. }
  38159. Component* getComponentForRowIfOnscreen (const int row) const throw()
  38160. {
  38161. return (row >= firstIndex && row < firstIndex + getViewedComponent()->getNumChildComponents())
  38162. ? getComponentForRow (row) : 0;
  38163. }
  38164. void visibleAreaChanged (int, int, int, int)
  38165. {
  38166. updateVisibleArea (true);
  38167. if (owner.getModel() != 0)
  38168. owner.getModel()->listWasScrolled();
  38169. }
  38170. void updateVisibleArea (const bool makeSureItUpdatesContent)
  38171. {
  38172. hasUpdated = false;
  38173. const int newX = getViewedComponent()->getX();
  38174. int newY = getViewedComponent()->getY();
  38175. const int newW = jmax (owner.minimumRowWidth, getMaximumVisibleWidth());
  38176. const int newH = owner.totalItems * owner.getRowHeight();
  38177. if (newY + newH < getMaximumVisibleHeight() && newH > getMaximumVisibleHeight())
  38178. newY = getMaximumVisibleHeight() - newH;
  38179. getViewedComponent()->setBounds (newX, newY, newW, newH);
  38180. if (makeSureItUpdatesContent && ! hasUpdated)
  38181. updateContents();
  38182. }
  38183. void updateContents()
  38184. {
  38185. hasUpdated = true;
  38186. const int rowHeight = owner.getRowHeight();
  38187. if (rowHeight > 0)
  38188. {
  38189. const int y = getViewPositionY();
  38190. const int w = getViewedComponent()->getWidth();
  38191. const int numNeeded = 2 + getMaximumVisibleHeight() / rowHeight;
  38192. while (numNeeded > getViewedComponent()->getNumChildComponents())
  38193. getViewedComponent()->addAndMakeVisible (new ListBoxRowComponent (owner));
  38194. jassert (numNeeded >= 0);
  38195. while (numNeeded < getViewedComponent()->getNumChildComponents())
  38196. {
  38197. Component* const rowToRemove
  38198. = getViewedComponent()->getChildComponent (getViewedComponent()->getNumChildComponents() - 1);
  38199. delete rowToRemove;
  38200. }
  38201. firstIndex = y / rowHeight;
  38202. firstWholeIndex = (y + rowHeight - 1) / rowHeight;
  38203. lastWholeIndex = (y + getMaximumVisibleHeight() - 1) / rowHeight;
  38204. for (int i = 0; i < numNeeded; ++i)
  38205. {
  38206. const int row = i + firstIndex;
  38207. ListBoxRowComponent* const rowComp = getComponentForRow (row);
  38208. if (rowComp != 0)
  38209. {
  38210. rowComp->setBounds (0, row * rowHeight, w, rowHeight);
  38211. rowComp->update (row, owner.isRowSelected (row));
  38212. }
  38213. }
  38214. }
  38215. if (owner.headerComponent != 0)
  38216. owner.headerComponent->setBounds (owner.outlineThickness + getViewedComponent()->getX(),
  38217. owner.outlineThickness,
  38218. jmax (owner.getWidth() - owner.outlineThickness * 2,
  38219. getViewedComponent()->getWidth()),
  38220. owner.headerComponent->getHeight());
  38221. }
  38222. void paint (Graphics& g)
  38223. {
  38224. if (isOpaque())
  38225. g.fillAll (owner.findColour (ListBox::backgroundColourId));
  38226. }
  38227. bool keyPressed (const KeyPress& key)
  38228. {
  38229. if (key.isKeyCode (KeyPress::upKey)
  38230. || key.isKeyCode (KeyPress::downKey)
  38231. || key.isKeyCode (KeyPress::pageUpKey)
  38232. || key.isKeyCode (KeyPress::pageDownKey)
  38233. || key.isKeyCode (KeyPress::homeKey)
  38234. || key.isKeyCode (KeyPress::endKey))
  38235. {
  38236. // we want to avoid these keypresses going to the viewport, and instead allow
  38237. // them to pass up to our listbox..
  38238. return false;
  38239. }
  38240. return Viewport::keyPressed (key);
  38241. }
  38242. juce_UseDebuggingNewOperator
  38243. private:
  38244. ListBox& owner;
  38245. ListViewport (const ListViewport&);
  38246. ListViewport& operator= (const ListViewport&);
  38247. };
  38248. ListBox::ListBox (const String& name, ListBoxModel* const model_)
  38249. : Component (name),
  38250. model (model_),
  38251. headerComponent (0),
  38252. totalItems (0),
  38253. rowHeight (22),
  38254. minimumRowWidth (0),
  38255. outlineThickness (0),
  38256. lastRowSelected (-1),
  38257. mouseMoveSelects (false),
  38258. multipleSelection (false),
  38259. hasDoneInitialUpdate (false)
  38260. {
  38261. addAndMakeVisible (viewport = new ListViewport (*this));
  38262. setWantsKeyboardFocus (true);
  38263. colourChanged();
  38264. }
  38265. ListBox::~ListBox()
  38266. {
  38267. deleteAllChildren();
  38268. }
  38269. void ListBox::setModel (ListBoxModel* const newModel)
  38270. {
  38271. if (model != newModel)
  38272. {
  38273. model = newModel;
  38274. updateContent();
  38275. }
  38276. }
  38277. void ListBox::setMultipleSelectionEnabled (bool b)
  38278. {
  38279. multipleSelection = b;
  38280. }
  38281. void ListBox::setMouseMoveSelectsRows (bool b)
  38282. {
  38283. mouseMoveSelects = b;
  38284. if (b)
  38285. addMouseListener (this, true);
  38286. }
  38287. void ListBox::paint (Graphics& g)
  38288. {
  38289. if (! hasDoneInitialUpdate)
  38290. updateContent();
  38291. g.fillAll (findColour (backgroundColourId));
  38292. }
  38293. void ListBox::paintOverChildren (Graphics& g)
  38294. {
  38295. if (outlineThickness > 0)
  38296. {
  38297. g.setColour (findColour (outlineColourId));
  38298. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  38299. }
  38300. }
  38301. void ListBox::resized()
  38302. {
  38303. viewport->setBoundsInset (BorderSize (outlineThickness + ((headerComponent != 0) ? headerComponent->getHeight() : 0),
  38304. outlineThickness,
  38305. outlineThickness,
  38306. outlineThickness));
  38307. viewport->setSingleStepSizes (20, getRowHeight());
  38308. viewport->updateVisibleArea (false);
  38309. }
  38310. void ListBox::visibilityChanged()
  38311. {
  38312. viewport->updateVisibleArea (true);
  38313. }
  38314. Viewport* ListBox::getViewport() const throw()
  38315. {
  38316. return viewport;
  38317. }
  38318. void ListBox::updateContent()
  38319. {
  38320. hasDoneInitialUpdate = true;
  38321. totalItems = (model != 0) ? model->getNumRows() : 0;
  38322. bool selectionChanged = false;
  38323. if (selected [selected.size() - 1] >= totalItems)
  38324. {
  38325. selected.removeRange (Range <int> (totalItems, std::numeric_limits<int>::max()));
  38326. lastRowSelected = getSelectedRow (0);
  38327. selectionChanged = true;
  38328. }
  38329. viewport->updateVisibleArea (isVisible());
  38330. viewport->resized();
  38331. if (selectionChanged && model != 0)
  38332. model->selectedRowsChanged (lastRowSelected);
  38333. }
  38334. void ListBox::selectRow (const int row,
  38335. bool dontScroll,
  38336. bool deselectOthersFirst)
  38337. {
  38338. selectRowInternal (row, dontScroll, deselectOthersFirst, false);
  38339. }
  38340. void ListBox::selectRowInternal (const int row,
  38341. bool dontScroll,
  38342. bool deselectOthersFirst,
  38343. bool isMouseClick)
  38344. {
  38345. if (! multipleSelection)
  38346. deselectOthersFirst = true;
  38347. if ((! isRowSelected (row))
  38348. || (deselectOthersFirst && getNumSelectedRows() > 1))
  38349. {
  38350. if (((unsigned int) row) < (unsigned int) totalItems)
  38351. {
  38352. if (deselectOthersFirst)
  38353. selected.clear();
  38354. selected.addRange (Range<int> (row, row + 1));
  38355. if (getHeight() == 0 || getWidth() == 0)
  38356. dontScroll = true;
  38357. viewport->hasUpdated = false;
  38358. if (row < viewport->firstWholeIndex && ! dontScroll)
  38359. {
  38360. viewport->setViewPosition (viewport->getViewPositionX(),
  38361. row * getRowHeight());
  38362. }
  38363. else if (row >= viewport->lastWholeIndex && ! dontScroll)
  38364. {
  38365. const int rowsOnScreen = viewport->lastWholeIndex - viewport->firstWholeIndex;
  38366. if (row >= lastRowSelected + rowsOnScreen
  38367. && rowsOnScreen < totalItems - 1
  38368. && ! isMouseClick)
  38369. {
  38370. viewport->setViewPosition (viewport->getViewPositionX(),
  38371. jlimit (0, jmax (0, totalItems - rowsOnScreen), row)
  38372. * getRowHeight());
  38373. }
  38374. else
  38375. {
  38376. viewport->setViewPosition (viewport->getViewPositionX(),
  38377. jmax (0, (row + 1) * getRowHeight() - viewport->getMaximumVisibleHeight()));
  38378. }
  38379. }
  38380. if (! viewport->hasUpdated)
  38381. viewport->updateContents();
  38382. lastRowSelected = row;
  38383. model->selectedRowsChanged (row);
  38384. }
  38385. else
  38386. {
  38387. if (deselectOthersFirst)
  38388. deselectAllRows();
  38389. }
  38390. }
  38391. }
  38392. void ListBox::deselectRow (const int row)
  38393. {
  38394. if (selected.contains (row))
  38395. {
  38396. selected.removeRange (Range <int> (row, row + 1));
  38397. if (row == lastRowSelected)
  38398. lastRowSelected = getSelectedRow (0);
  38399. viewport->updateContents();
  38400. model->selectedRowsChanged (lastRowSelected);
  38401. }
  38402. }
  38403. void ListBox::setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  38404. const bool sendNotificationEventToModel)
  38405. {
  38406. selected = setOfRowsToBeSelected;
  38407. selected.removeRange (Range <int> (totalItems, std::numeric_limits<int>::max()));
  38408. if (! isRowSelected (lastRowSelected))
  38409. lastRowSelected = getSelectedRow (0);
  38410. viewport->updateContents();
  38411. if ((model != 0) && sendNotificationEventToModel)
  38412. model->selectedRowsChanged (lastRowSelected);
  38413. }
  38414. const SparseSet<int> ListBox::getSelectedRows() const
  38415. {
  38416. return selected;
  38417. }
  38418. void ListBox::selectRangeOfRows (int firstRow, int lastRow)
  38419. {
  38420. if (multipleSelection && (firstRow != lastRow))
  38421. {
  38422. const int numRows = totalItems - 1;
  38423. firstRow = jlimit (0, jmax (0, numRows), firstRow);
  38424. lastRow = jlimit (0, jmax (0, numRows), lastRow);
  38425. selected.addRange (Range <int> (jmin (firstRow, lastRow),
  38426. jmax (firstRow, lastRow) + 1));
  38427. selected.removeRange (Range <int> (lastRow, lastRow + 1));
  38428. }
  38429. selectRowInternal (lastRow, false, false, true);
  38430. }
  38431. void ListBox::flipRowSelection (const int row)
  38432. {
  38433. if (isRowSelected (row))
  38434. deselectRow (row);
  38435. else
  38436. selectRowInternal (row, false, false, true);
  38437. }
  38438. void ListBox::deselectAllRows()
  38439. {
  38440. if (! selected.isEmpty())
  38441. {
  38442. selected.clear();
  38443. lastRowSelected = -1;
  38444. viewport->updateContents();
  38445. if (model != 0)
  38446. model->selectedRowsChanged (lastRowSelected);
  38447. }
  38448. }
  38449. void ListBox::selectRowsBasedOnModifierKeys (const int row,
  38450. const ModifierKeys& mods)
  38451. {
  38452. if (multipleSelection && mods.isCommandDown())
  38453. {
  38454. flipRowSelection (row);
  38455. }
  38456. else if (multipleSelection && mods.isShiftDown() && lastRowSelected >= 0)
  38457. {
  38458. selectRangeOfRows (lastRowSelected, row);
  38459. }
  38460. else if ((! mods.isPopupMenu()) || ! isRowSelected (row))
  38461. {
  38462. selectRowInternal (row, false, true, true);
  38463. }
  38464. }
  38465. int ListBox::getNumSelectedRows() const
  38466. {
  38467. return selected.size();
  38468. }
  38469. int ListBox::getSelectedRow (const int index) const
  38470. {
  38471. return (((unsigned int) index) < (unsigned int) selected.size())
  38472. ? selected [index] : -1;
  38473. }
  38474. bool ListBox::isRowSelected (const int row) const
  38475. {
  38476. return selected.contains (row);
  38477. }
  38478. int ListBox::getLastRowSelected() const
  38479. {
  38480. return (isRowSelected (lastRowSelected)) ? lastRowSelected : -1;
  38481. }
  38482. int ListBox::getRowContainingPosition (const int x, const int y) const throw()
  38483. {
  38484. if (((unsigned int) x) < (unsigned int) getWidth())
  38485. {
  38486. const int row = (viewport->getViewPositionY() + y - viewport->getY()) / rowHeight;
  38487. if (((unsigned int) row) < (unsigned int) totalItems)
  38488. return row;
  38489. }
  38490. return -1;
  38491. }
  38492. int ListBox::getInsertionIndexForPosition (const int x, const int y) const throw()
  38493. {
  38494. if (((unsigned int) x) < (unsigned int) getWidth())
  38495. {
  38496. const int row = (viewport->getViewPositionY() + y + rowHeight / 2 - viewport->getY()) / rowHeight;
  38497. return jlimit (0, totalItems, row);
  38498. }
  38499. return -1;
  38500. }
  38501. Component* ListBox::getComponentForRowNumber (const int row) const throw()
  38502. {
  38503. Component* const listRowComp = viewport->getComponentForRowIfOnscreen (row);
  38504. return listRowComp != 0 ? listRowComp->getChildComponent (0) : 0;
  38505. }
  38506. int ListBox::getRowNumberOfComponent (Component* const rowComponent) const throw()
  38507. {
  38508. return viewport->getRowNumberOfComponent (rowComponent);
  38509. }
  38510. const Rectangle<int> ListBox::getRowPosition (const int rowNumber,
  38511. const bool relativeToComponentTopLeft) const throw()
  38512. {
  38513. int y = viewport->getY() + rowHeight * rowNumber;
  38514. if (relativeToComponentTopLeft)
  38515. y -= viewport->getViewPositionY();
  38516. return Rectangle<int> (viewport->getX(), y,
  38517. viewport->getViewedComponent()->getWidth(), rowHeight);
  38518. }
  38519. void ListBox::setVerticalPosition (const double proportion)
  38520. {
  38521. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  38522. viewport->setViewPosition (viewport->getViewPositionX(),
  38523. jmax (0, roundToInt (proportion * offscreen)));
  38524. }
  38525. double ListBox::getVerticalPosition() const
  38526. {
  38527. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  38528. return (offscreen > 0) ? viewport->getViewPositionY() / (double) offscreen
  38529. : 0;
  38530. }
  38531. int ListBox::getVisibleRowWidth() const throw()
  38532. {
  38533. return viewport->getViewWidth();
  38534. }
  38535. void ListBox::scrollToEnsureRowIsOnscreen (const int row)
  38536. {
  38537. if (row < viewport->firstWholeIndex)
  38538. {
  38539. viewport->setViewPosition (viewport->getViewPositionX(),
  38540. row * getRowHeight());
  38541. }
  38542. else if (row >= viewport->lastWholeIndex)
  38543. {
  38544. viewport->setViewPosition (viewport->getViewPositionX(),
  38545. jmax (0, (row + 1) * getRowHeight() - viewport->getMaximumVisibleHeight()));
  38546. }
  38547. }
  38548. bool ListBox::keyPressed (const KeyPress& key)
  38549. {
  38550. const int numVisibleRows = viewport->getHeight() / getRowHeight();
  38551. const bool multiple = multipleSelection
  38552. && (lastRowSelected >= 0)
  38553. && (key.getModifiers().isShiftDown()
  38554. || key.getModifiers().isCtrlDown()
  38555. || key.getModifiers().isCommandDown());
  38556. if (key.isKeyCode (KeyPress::upKey))
  38557. {
  38558. if (multiple)
  38559. selectRangeOfRows (lastRowSelected, lastRowSelected - 1);
  38560. else
  38561. selectRow (jmax (0, lastRowSelected - 1));
  38562. }
  38563. else if (key.isKeyCode (KeyPress::returnKey)
  38564. && isRowSelected (lastRowSelected))
  38565. {
  38566. if (model != 0)
  38567. model->returnKeyPressed (lastRowSelected);
  38568. }
  38569. else if (key.isKeyCode (KeyPress::pageUpKey))
  38570. {
  38571. if (multiple)
  38572. selectRangeOfRows (lastRowSelected, lastRowSelected - numVisibleRows);
  38573. else
  38574. selectRow (jmax (0, jmax (0, lastRowSelected) - numVisibleRows));
  38575. }
  38576. else if (key.isKeyCode (KeyPress::pageDownKey))
  38577. {
  38578. if (multiple)
  38579. selectRangeOfRows (lastRowSelected, lastRowSelected + numVisibleRows);
  38580. else
  38581. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + numVisibleRows));
  38582. }
  38583. else if (key.isKeyCode (KeyPress::homeKey))
  38584. {
  38585. if (multiple && key.getModifiers().isShiftDown())
  38586. selectRangeOfRows (lastRowSelected, 0);
  38587. else
  38588. selectRow (0);
  38589. }
  38590. else if (key.isKeyCode (KeyPress::endKey))
  38591. {
  38592. if (multiple && key.getModifiers().isShiftDown())
  38593. selectRangeOfRows (lastRowSelected, totalItems - 1);
  38594. else
  38595. selectRow (totalItems - 1);
  38596. }
  38597. else if (key.isKeyCode (KeyPress::downKey))
  38598. {
  38599. if (multiple)
  38600. selectRangeOfRows (lastRowSelected, lastRowSelected + 1);
  38601. else
  38602. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + 1));
  38603. }
  38604. else if ((key.isKeyCode (KeyPress::deleteKey) || key.isKeyCode (KeyPress::backspaceKey))
  38605. && isRowSelected (lastRowSelected))
  38606. {
  38607. if (model != 0)
  38608. model->deleteKeyPressed (lastRowSelected);
  38609. }
  38610. else if (multiple && key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  38611. {
  38612. selectRangeOfRows (0, std::numeric_limits<int>::max());
  38613. }
  38614. else
  38615. {
  38616. return false;
  38617. }
  38618. return true;
  38619. }
  38620. bool ListBox::keyStateChanged (const bool isKeyDown)
  38621. {
  38622. return isKeyDown
  38623. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  38624. || KeyPress::isKeyCurrentlyDown (KeyPress::pageUpKey)
  38625. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  38626. || KeyPress::isKeyCurrentlyDown (KeyPress::pageDownKey)
  38627. || KeyPress::isKeyCurrentlyDown (KeyPress::homeKey)
  38628. || KeyPress::isKeyCurrentlyDown (KeyPress::endKey)
  38629. || KeyPress::isKeyCurrentlyDown (KeyPress::returnKey));
  38630. }
  38631. void ListBox::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  38632. {
  38633. getHorizontalScrollBar()->mouseWheelMove (e, wheelIncrementX, 0);
  38634. getVerticalScrollBar()->mouseWheelMove (e, 0, wheelIncrementY);
  38635. }
  38636. void ListBox::mouseMove (const MouseEvent& e)
  38637. {
  38638. if (mouseMoveSelects)
  38639. {
  38640. const MouseEvent e2 (e.getEventRelativeTo (this));
  38641. selectRow (getRowContainingPosition (e2.x, e2.y), true);
  38642. }
  38643. }
  38644. void ListBox::mouseExit (const MouseEvent& e)
  38645. {
  38646. mouseMove (e);
  38647. }
  38648. void ListBox::mouseUp (const MouseEvent& e)
  38649. {
  38650. if (e.mouseWasClicked() && model != 0)
  38651. model->backgroundClicked();
  38652. }
  38653. void ListBox::setRowHeight (const int newHeight)
  38654. {
  38655. rowHeight = jmax (1, newHeight);
  38656. viewport->setSingleStepSizes (20, rowHeight);
  38657. updateContent();
  38658. }
  38659. int ListBox::getNumRowsOnScreen() const throw()
  38660. {
  38661. return viewport->getMaximumVisibleHeight() / rowHeight;
  38662. }
  38663. void ListBox::setMinimumContentWidth (const int newMinimumWidth)
  38664. {
  38665. minimumRowWidth = newMinimumWidth;
  38666. updateContent();
  38667. }
  38668. int ListBox::getVisibleContentWidth() const throw()
  38669. {
  38670. return viewport->getMaximumVisibleWidth();
  38671. }
  38672. ScrollBar* ListBox::getVerticalScrollBar() const throw()
  38673. {
  38674. return viewport->getVerticalScrollBar();
  38675. }
  38676. ScrollBar* ListBox::getHorizontalScrollBar() const throw()
  38677. {
  38678. return viewport->getHorizontalScrollBar();
  38679. }
  38680. void ListBox::colourChanged()
  38681. {
  38682. setOpaque (findColour (backgroundColourId).isOpaque());
  38683. viewport->setOpaque (isOpaque());
  38684. repaint();
  38685. }
  38686. void ListBox::setOutlineThickness (const int outlineThickness_)
  38687. {
  38688. outlineThickness = outlineThickness_;
  38689. resized();
  38690. }
  38691. void ListBox::setHeaderComponent (Component* const newHeaderComponent)
  38692. {
  38693. if (headerComponent != newHeaderComponent)
  38694. {
  38695. delete headerComponent;
  38696. headerComponent = newHeaderComponent;
  38697. addAndMakeVisible (newHeaderComponent);
  38698. ListBox::resized();
  38699. }
  38700. }
  38701. void ListBox::repaintRow (const int rowNumber) throw()
  38702. {
  38703. repaint (getRowPosition (rowNumber, true));
  38704. }
  38705. const Image ListBox::createSnapshotOfSelectedRows (int& imageX, int& imageY)
  38706. {
  38707. Rectangle<int> imageArea;
  38708. const int firstRow = getRowContainingPosition (0, 0);
  38709. int i;
  38710. for (i = getNumRowsOnScreen() + 2; --i >= 0;)
  38711. {
  38712. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  38713. if (rowComp != 0 && isRowSelected (firstRow + i))
  38714. {
  38715. const Point<int> pos (rowComp->relativePositionToOtherComponent (this, Point<int>()));
  38716. const Rectangle<int> rowRect (pos.getX(), pos.getY(), rowComp->getWidth(), rowComp->getHeight());
  38717. imageArea = imageArea.getUnion (rowRect);
  38718. }
  38719. }
  38720. imageArea = imageArea.getIntersection (getLocalBounds());
  38721. imageX = imageArea.getX();
  38722. imageY = imageArea.getY();
  38723. Image snapshot (Image::ARGB, imageArea.getWidth(), imageArea.getHeight(), true, Image::NativeImage);
  38724. for (i = getNumRowsOnScreen() + 2; --i >= 0;)
  38725. {
  38726. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  38727. if (rowComp != 0 && isRowSelected (firstRow + i))
  38728. {
  38729. const Point<int> pos (rowComp->relativePositionToOtherComponent (this, Point<int>()));
  38730. Graphics g (snapshot);
  38731. g.setOrigin (pos.getX() - imageX, pos.getY() - imageY);
  38732. if (g.reduceClipRegion (0, 0, rowComp->getWidth(), rowComp->getHeight()))
  38733. rowComp->paintEntireComponent (g);
  38734. }
  38735. }
  38736. return snapshot;
  38737. }
  38738. void ListBox::startDragAndDrop (const MouseEvent& e, const String& dragDescription)
  38739. {
  38740. DragAndDropContainer* const dragContainer
  38741. = DragAndDropContainer::findParentDragContainerFor (this);
  38742. if (dragContainer != 0)
  38743. {
  38744. int x, y;
  38745. Image dragImage (createSnapshotOfSelectedRows (x, y));
  38746. dragImage.multiplyAllAlphas (0.6f);
  38747. MouseEvent e2 (e.getEventRelativeTo (this));
  38748. const Point<int> p (x - e2.x, y - e2.y);
  38749. dragContainer->startDragging (dragDescription, this, dragImage, true, &p);
  38750. }
  38751. else
  38752. {
  38753. // to be able to do a drag-and-drop operation, the listbox needs to
  38754. // be inside a component which is also a DragAndDropContainer.
  38755. jassertfalse;
  38756. }
  38757. }
  38758. Component* ListBoxModel::refreshComponentForRow (int, bool, Component* existingComponentToUpdate)
  38759. {
  38760. (void) existingComponentToUpdate;
  38761. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  38762. return 0;
  38763. }
  38764. void ListBoxModel::listBoxItemClicked (int, const MouseEvent&)
  38765. {
  38766. }
  38767. void ListBoxModel::listBoxItemDoubleClicked (int, const MouseEvent&)
  38768. {
  38769. }
  38770. void ListBoxModel::backgroundClicked()
  38771. {
  38772. }
  38773. void ListBoxModel::selectedRowsChanged (int)
  38774. {
  38775. }
  38776. void ListBoxModel::deleteKeyPressed (int)
  38777. {
  38778. }
  38779. void ListBoxModel::returnKeyPressed (int)
  38780. {
  38781. }
  38782. void ListBoxModel::listWasScrolled()
  38783. {
  38784. }
  38785. const String ListBoxModel::getDragSourceDescription (const SparseSet<int>&)
  38786. {
  38787. return String::empty;
  38788. }
  38789. const String ListBoxModel::getTooltipForRow (int)
  38790. {
  38791. return String::empty;
  38792. }
  38793. END_JUCE_NAMESPACE
  38794. /*** End of inlined file: juce_ListBox.cpp ***/
  38795. /*** Start of inlined file: juce_ProgressBar.cpp ***/
  38796. BEGIN_JUCE_NAMESPACE
  38797. ProgressBar::ProgressBar (double& progress_)
  38798. : progress (progress_),
  38799. displayPercentage (true),
  38800. lastCallbackTime (0)
  38801. {
  38802. currentValue = jlimit (0.0, 1.0, progress);
  38803. }
  38804. ProgressBar::~ProgressBar()
  38805. {
  38806. }
  38807. void ProgressBar::setPercentageDisplay (const bool shouldDisplayPercentage)
  38808. {
  38809. displayPercentage = shouldDisplayPercentage;
  38810. repaint();
  38811. }
  38812. void ProgressBar::setTextToDisplay (const String& text)
  38813. {
  38814. displayPercentage = false;
  38815. displayedMessage = text;
  38816. }
  38817. void ProgressBar::lookAndFeelChanged()
  38818. {
  38819. setOpaque (findColour (backgroundColourId).isOpaque());
  38820. }
  38821. void ProgressBar::colourChanged()
  38822. {
  38823. lookAndFeelChanged();
  38824. }
  38825. void ProgressBar::paint (Graphics& g)
  38826. {
  38827. String text;
  38828. if (displayPercentage)
  38829. {
  38830. if (currentValue >= 0 && currentValue <= 1.0)
  38831. text << roundToInt (currentValue * 100.0) << '%';
  38832. }
  38833. else
  38834. {
  38835. text = displayedMessage;
  38836. }
  38837. getLookAndFeel().drawProgressBar (g, *this,
  38838. getWidth(), getHeight(),
  38839. currentValue, text);
  38840. }
  38841. void ProgressBar::visibilityChanged()
  38842. {
  38843. if (isVisible())
  38844. startTimer (30);
  38845. else
  38846. stopTimer();
  38847. }
  38848. void ProgressBar::timerCallback()
  38849. {
  38850. double newProgress = progress;
  38851. const uint32 now = Time::getMillisecondCounter();
  38852. const int timeSinceLastCallback = (int) (now - lastCallbackTime);
  38853. lastCallbackTime = now;
  38854. if (currentValue != newProgress
  38855. || newProgress < 0 || newProgress >= 1.0
  38856. || currentMessage != displayedMessage)
  38857. {
  38858. if (currentValue < newProgress
  38859. && newProgress >= 0 && newProgress < 1.0
  38860. && currentValue >= 0 && currentValue < 1.0)
  38861. {
  38862. newProgress = jmin (currentValue + 0.0008 * timeSinceLastCallback,
  38863. newProgress);
  38864. }
  38865. currentValue = newProgress;
  38866. currentMessage = displayedMessage;
  38867. repaint();
  38868. }
  38869. }
  38870. END_JUCE_NAMESPACE
  38871. /*** End of inlined file: juce_ProgressBar.cpp ***/
  38872. /*** Start of inlined file: juce_Slider.cpp ***/
  38873. BEGIN_JUCE_NAMESPACE
  38874. class SliderPopupDisplayComponent : public BubbleComponent
  38875. {
  38876. public:
  38877. SliderPopupDisplayComponent (Slider* const owner_)
  38878. : owner (owner_),
  38879. font (15.0f, Font::bold)
  38880. {
  38881. setAlwaysOnTop (true);
  38882. }
  38883. ~SliderPopupDisplayComponent()
  38884. {
  38885. }
  38886. void paintContent (Graphics& g, int w, int h)
  38887. {
  38888. g.setFont (font);
  38889. g.setColour (Colours::black);
  38890. g.drawFittedText (text, 0, 0, w, h, Justification::centred, 1);
  38891. }
  38892. void getContentSize (int& w, int& h)
  38893. {
  38894. w = font.getStringWidth (text) + 18;
  38895. h = (int) (font.getHeight() * 1.6f);
  38896. }
  38897. void updatePosition (const String& newText)
  38898. {
  38899. if (text != newText)
  38900. {
  38901. text = newText;
  38902. repaint();
  38903. }
  38904. BubbleComponent::setPosition (owner);
  38905. }
  38906. juce_UseDebuggingNewOperator
  38907. private:
  38908. Slider* owner;
  38909. Font font;
  38910. String text;
  38911. SliderPopupDisplayComponent (const SliderPopupDisplayComponent&);
  38912. SliderPopupDisplayComponent& operator= (const SliderPopupDisplayComponent&);
  38913. };
  38914. Slider::Slider (const String& name)
  38915. : Component (name),
  38916. lastCurrentValue (0),
  38917. lastValueMin (0),
  38918. lastValueMax (0),
  38919. minimum (0),
  38920. maximum (10),
  38921. interval (0),
  38922. skewFactor (1.0),
  38923. velocityModeSensitivity (1.0),
  38924. velocityModeOffset (0.0),
  38925. velocityModeThreshold (1),
  38926. rotaryStart (float_Pi * 1.2f),
  38927. rotaryEnd (float_Pi * 2.8f),
  38928. numDecimalPlaces (7),
  38929. sliderRegionStart (0),
  38930. sliderRegionSize (1),
  38931. sliderBeingDragged (-1),
  38932. pixelsForFullDragExtent (250),
  38933. style (LinearHorizontal),
  38934. textBoxPos (TextBoxLeft),
  38935. textBoxWidth (80),
  38936. textBoxHeight (20),
  38937. incDecButtonMode (incDecButtonsNotDraggable),
  38938. editableText (true),
  38939. doubleClickToValue (false),
  38940. isVelocityBased (false),
  38941. userKeyOverridesVelocity (true),
  38942. rotaryStop (true),
  38943. incDecButtonsSideBySide (false),
  38944. sendChangeOnlyOnRelease (false),
  38945. popupDisplayEnabled (false),
  38946. menuEnabled (false),
  38947. menuShown (false),
  38948. scrollWheelEnabled (true),
  38949. snapsToMousePos (true),
  38950. valueBox (0),
  38951. incButton (0),
  38952. decButton (0),
  38953. popupDisplay (0),
  38954. parentForPopupDisplay (0)
  38955. {
  38956. setWantsKeyboardFocus (false);
  38957. setRepaintsOnMouseActivity (true);
  38958. lookAndFeelChanged();
  38959. updateText();
  38960. currentValue.addListener (this);
  38961. valueMin.addListener (this);
  38962. valueMax.addListener (this);
  38963. }
  38964. Slider::~Slider()
  38965. {
  38966. currentValue.removeListener (this);
  38967. valueMin.removeListener (this);
  38968. valueMax.removeListener (this);
  38969. popupDisplay = 0;
  38970. deleteAllChildren();
  38971. }
  38972. void Slider::handleAsyncUpdate()
  38973. {
  38974. cancelPendingUpdate();
  38975. Component::BailOutChecker checker (this);
  38976. listeners.callChecked (checker, &SliderListener::sliderValueChanged, this);
  38977. }
  38978. void Slider::sendDragStart()
  38979. {
  38980. startedDragging();
  38981. Component::BailOutChecker checker (this);
  38982. listeners.callChecked (checker, &SliderListener::sliderDragStarted, this);
  38983. }
  38984. void Slider::sendDragEnd()
  38985. {
  38986. stoppedDragging();
  38987. sliderBeingDragged = -1;
  38988. Component::BailOutChecker checker (this);
  38989. listeners.callChecked (checker, &SliderListener::sliderDragEnded, this);
  38990. }
  38991. void Slider::addListener (SliderListener* const listener)
  38992. {
  38993. listeners.add (listener);
  38994. }
  38995. void Slider::removeListener (SliderListener* const listener)
  38996. {
  38997. listeners.remove (listener);
  38998. }
  38999. void Slider::setSliderStyle (const SliderStyle newStyle)
  39000. {
  39001. if (style != newStyle)
  39002. {
  39003. style = newStyle;
  39004. repaint();
  39005. lookAndFeelChanged();
  39006. }
  39007. }
  39008. void Slider::setRotaryParameters (const float startAngleRadians,
  39009. const float endAngleRadians,
  39010. const bool stopAtEnd)
  39011. {
  39012. // make sure the values are sensible..
  39013. jassert (rotaryStart >= 0 && rotaryEnd >= 0);
  39014. jassert (rotaryStart < float_Pi * 4.0f && rotaryEnd < float_Pi * 4.0f);
  39015. jassert (rotaryStart < rotaryEnd);
  39016. rotaryStart = startAngleRadians;
  39017. rotaryEnd = endAngleRadians;
  39018. rotaryStop = stopAtEnd;
  39019. }
  39020. void Slider::setVelocityBasedMode (const bool velBased)
  39021. {
  39022. isVelocityBased = velBased;
  39023. }
  39024. void Slider::setVelocityModeParameters (const double sensitivity,
  39025. const int threshold,
  39026. const double offset,
  39027. const bool userCanPressKeyToSwapMode)
  39028. {
  39029. jassert (threshold >= 0);
  39030. jassert (sensitivity > 0);
  39031. jassert (offset >= 0);
  39032. velocityModeSensitivity = sensitivity;
  39033. velocityModeOffset = offset;
  39034. velocityModeThreshold = threshold;
  39035. userKeyOverridesVelocity = userCanPressKeyToSwapMode;
  39036. }
  39037. void Slider::setSkewFactor (const double factor)
  39038. {
  39039. skewFactor = factor;
  39040. }
  39041. void Slider::setSkewFactorFromMidPoint (const double sliderValueToShowAtMidPoint)
  39042. {
  39043. if (maximum > minimum)
  39044. skewFactor = log (0.5) / log ((sliderValueToShowAtMidPoint - minimum)
  39045. / (maximum - minimum));
  39046. }
  39047. void Slider::setMouseDragSensitivity (const int distanceForFullScaleDrag)
  39048. {
  39049. jassert (distanceForFullScaleDrag > 0);
  39050. pixelsForFullDragExtent = distanceForFullScaleDrag;
  39051. }
  39052. void Slider::setIncDecButtonsMode (const IncDecButtonMode mode)
  39053. {
  39054. if (incDecButtonMode != mode)
  39055. {
  39056. incDecButtonMode = mode;
  39057. lookAndFeelChanged();
  39058. }
  39059. }
  39060. void Slider::setTextBoxStyle (const TextEntryBoxPosition newPosition,
  39061. const bool isReadOnly,
  39062. const int textEntryBoxWidth,
  39063. const int textEntryBoxHeight)
  39064. {
  39065. if (textBoxPos != newPosition
  39066. || editableText != (! isReadOnly)
  39067. || textBoxWidth != textEntryBoxWidth
  39068. || textBoxHeight != textEntryBoxHeight)
  39069. {
  39070. textBoxPos = newPosition;
  39071. editableText = ! isReadOnly;
  39072. textBoxWidth = textEntryBoxWidth;
  39073. textBoxHeight = textEntryBoxHeight;
  39074. repaint();
  39075. lookAndFeelChanged();
  39076. }
  39077. }
  39078. void Slider::setTextBoxIsEditable (const bool shouldBeEditable)
  39079. {
  39080. editableText = shouldBeEditable;
  39081. if (valueBox != 0)
  39082. valueBox->setEditable (shouldBeEditable && isEnabled());
  39083. }
  39084. void Slider::showTextBox()
  39085. {
  39086. jassert (editableText); // this should probably be avoided in read-only sliders.
  39087. if (valueBox != 0)
  39088. valueBox->showEditor();
  39089. }
  39090. void Slider::hideTextBox (const bool discardCurrentEditorContents)
  39091. {
  39092. if (valueBox != 0)
  39093. {
  39094. valueBox->hideEditor (discardCurrentEditorContents);
  39095. if (discardCurrentEditorContents)
  39096. updateText();
  39097. }
  39098. }
  39099. void Slider::setChangeNotificationOnlyOnRelease (const bool onlyNotifyOnRelease)
  39100. {
  39101. sendChangeOnlyOnRelease = onlyNotifyOnRelease;
  39102. }
  39103. void Slider::setSliderSnapsToMousePosition (const bool shouldSnapToMouse)
  39104. {
  39105. snapsToMousePos = shouldSnapToMouse;
  39106. }
  39107. void Slider::setPopupDisplayEnabled (const bool enabled,
  39108. Component* const parentComponentToUse)
  39109. {
  39110. popupDisplayEnabled = enabled;
  39111. parentForPopupDisplay = parentComponentToUse;
  39112. }
  39113. void Slider::colourChanged()
  39114. {
  39115. lookAndFeelChanged();
  39116. }
  39117. void Slider::lookAndFeelChanged()
  39118. {
  39119. const String previousTextBoxContent (valueBox != 0 ? valueBox->getText()
  39120. : getTextFromValue (currentValue.getValue()));
  39121. deleteAllChildren();
  39122. valueBox = 0;
  39123. LookAndFeel& lf = getLookAndFeel();
  39124. if (textBoxPos != NoTextBox)
  39125. {
  39126. addAndMakeVisible (valueBox = getLookAndFeel().createSliderTextBox (*this));
  39127. valueBox->setWantsKeyboardFocus (false);
  39128. valueBox->setText (previousTextBoxContent, false);
  39129. valueBox->setEditable (editableText && isEnabled());
  39130. valueBox->addListener (this);
  39131. if (style == LinearBar)
  39132. valueBox->addMouseListener (this, false);
  39133. valueBox->setTooltip (getTooltip());
  39134. }
  39135. if (style == IncDecButtons)
  39136. {
  39137. addAndMakeVisible (incButton = lf.createSliderButton (true));
  39138. incButton->addButtonListener (this);
  39139. addAndMakeVisible (decButton = lf.createSliderButton (false));
  39140. decButton->addButtonListener (this);
  39141. if (incDecButtonMode != incDecButtonsNotDraggable)
  39142. {
  39143. incButton->addMouseListener (this, false);
  39144. decButton->addMouseListener (this, false);
  39145. }
  39146. else
  39147. {
  39148. incButton->setRepeatSpeed (300, 100, 20);
  39149. incButton->addMouseListener (decButton, false);
  39150. decButton->setRepeatSpeed (300, 100, 20);
  39151. decButton->addMouseListener (incButton, false);
  39152. }
  39153. incButton->setTooltip (getTooltip());
  39154. decButton->setTooltip (getTooltip());
  39155. }
  39156. setComponentEffect (lf.getSliderEffect());
  39157. resized();
  39158. repaint();
  39159. }
  39160. void Slider::setRange (const double newMin,
  39161. const double newMax,
  39162. const double newInt)
  39163. {
  39164. if (minimum != newMin
  39165. || maximum != newMax
  39166. || interval != newInt)
  39167. {
  39168. minimum = newMin;
  39169. maximum = newMax;
  39170. interval = newInt;
  39171. // figure out the number of DPs needed to display all values at this
  39172. // interval setting.
  39173. numDecimalPlaces = 7;
  39174. if (newInt != 0)
  39175. {
  39176. int v = abs ((int) (newInt * 10000000));
  39177. while ((v % 10) == 0)
  39178. {
  39179. --numDecimalPlaces;
  39180. v /= 10;
  39181. }
  39182. }
  39183. // keep the current values inside the new range..
  39184. if (style != TwoValueHorizontal && style != TwoValueVertical)
  39185. {
  39186. setValue (getValue(), false, false);
  39187. }
  39188. else
  39189. {
  39190. setMinValue (getMinValue(), false, false);
  39191. setMaxValue (getMaxValue(), false, false);
  39192. }
  39193. updateText();
  39194. }
  39195. }
  39196. void Slider::triggerChangeMessage (const bool synchronous)
  39197. {
  39198. if (synchronous)
  39199. handleAsyncUpdate();
  39200. else
  39201. triggerAsyncUpdate();
  39202. valueChanged();
  39203. }
  39204. void Slider::valueChanged (Value& value)
  39205. {
  39206. if (value.refersToSameSourceAs (currentValue))
  39207. {
  39208. if (style != TwoValueHorizontal && style != TwoValueVertical)
  39209. setValue (currentValue.getValue(), false, false);
  39210. }
  39211. else if (value.refersToSameSourceAs (valueMin))
  39212. setMinValue (valueMin.getValue(), false, false, true);
  39213. else if (value.refersToSameSourceAs (valueMax))
  39214. setMaxValue (valueMax.getValue(), false, false, true);
  39215. }
  39216. double Slider::getValue() const
  39217. {
  39218. // for a two-value style slider, you should use the getMinValue() and getMaxValue()
  39219. // methods to get the two values.
  39220. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  39221. return currentValue.getValue();
  39222. }
  39223. void Slider::setValue (double newValue,
  39224. const bool sendUpdateMessage,
  39225. const bool sendMessageSynchronously)
  39226. {
  39227. // for a two-value style slider, you should use the setMinValue() and setMaxValue()
  39228. // methods to set the two values.
  39229. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  39230. newValue = constrainedValue (newValue);
  39231. if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  39232. {
  39233. jassert ((double) valueMin.getValue() <= (double) valueMax.getValue());
  39234. newValue = jlimit ((double) valueMin.getValue(),
  39235. (double) valueMax.getValue(),
  39236. newValue);
  39237. }
  39238. if (newValue != lastCurrentValue)
  39239. {
  39240. if (valueBox != 0)
  39241. valueBox->hideEditor (true);
  39242. lastCurrentValue = newValue;
  39243. currentValue = newValue;
  39244. updateText();
  39245. repaint();
  39246. if (popupDisplay != 0)
  39247. {
  39248. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  39249. ->updatePosition (getTextFromValue (newValue));
  39250. popupDisplay->repaint();
  39251. }
  39252. if (sendUpdateMessage)
  39253. triggerChangeMessage (sendMessageSynchronously);
  39254. }
  39255. }
  39256. double Slider::getMinValue() const
  39257. {
  39258. // The minimum value only applies to sliders that are in two- or three-value mode.
  39259. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  39260. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  39261. return valueMin.getValue();
  39262. }
  39263. double Slider::getMaxValue() const
  39264. {
  39265. // The maximum value only applies to sliders that are in two- or three-value mode.
  39266. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  39267. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  39268. return valueMax.getValue();
  39269. }
  39270. void Slider::setMinValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  39271. {
  39272. // The minimum value only applies to sliders that are in two- or three-value mode.
  39273. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  39274. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  39275. newValue = constrainedValue (newValue);
  39276. if (style == TwoValueHorizontal || style == TwoValueVertical)
  39277. {
  39278. if (allowNudgingOfOtherValues && newValue > (double) valueMax.getValue())
  39279. setMaxValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  39280. newValue = jmin ((double) valueMax.getValue(), newValue);
  39281. }
  39282. else
  39283. {
  39284. if (allowNudgingOfOtherValues && newValue > lastCurrentValue)
  39285. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  39286. newValue = jmin (lastCurrentValue, newValue);
  39287. }
  39288. if (lastValueMin != newValue)
  39289. {
  39290. lastValueMin = newValue;
  39291. valueMin = newValue;
  39292. repaint();
  39293. if (popupDisplay != 0)
  39294. {
  39295. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  39296. ->updatePosition (getTextFromValue (newValue));
  39297. popupDisplay->repaint();
  39298. }
  39299. if (sendUpdateMessage)
  39300. triggerChangeMessage (sendMessageSynchronously);
  39301. }
  39302. }
  39303. void Slider::setMaxValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  39304. {
  39305. // The maximum value only applies to sliders that are in two- or three-value mode.
  39306. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  39307. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  39308. newValue = constrainedValue (newValue);
  39309. if (style == TwoValueHorizontal || style == TwoValueVertical)
  39310. {
  39311. if (allowNudgingOfOtherValues && newValue < (double) valueMin.getValue())
  39312. setMinValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  39313. newValue = jmax ((double) valueMin.getValue(), newValue);
  39314. }
  39315. else
  39316. {
  39317. if (allowNudgingOfOtherValues && newValue < lastCurrentValue)
  39318. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  39319. newValue = jmax (lastCurrentValue, newValue);
  39320. }
  39321. if (lastValueMax != newValue)
  39322. {
  39323. lastValueMax = newValue;
  39324. valueMax = newValue;
  39325. repaint();
  39326. if (popupDisplay != 0)
  39327. {
  39328. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  39329. ->updatePosition (getTextFromValue (valueMax.getValue()));
  39330. popupDisplay->repaint();
  39331. }
  39332. if (sendUpdateMessage)
  39333. triggerChangeMessage (sendMessageSynchronously);
  39334. }
  39335. }
  39336. void Slider::setDoubleClickReturnValue (const bool isDoubleClickEnabled,
  39337. const double valueToSetOnDoubleClick)
  39338. {
  39339. doubleClickToValue = isDoubleClickEnabled;
  39340. doubleClickReturnValue = valueToSetOnDoubleClick;
  39341. }
  39342. double Slider::getDoubleClickReturnValue (bool& isEnabled_) const
  39343. {
  39344. isEnabled_ = doubleClickToValue;
  39345. return doubleClickReturnValue;
  39346. }
  39347. void Slider::updateText()
  39348. {
  39349. if (valueBox != 0)
  39350. valueBox->setText (getTextFromValue (currentValue.getValue()), false);
  39351. }
  39352. void Slider::setTextValueSuffix (const String& suffix)
  39353. {
  39354. if (textSuffix != suffix)
  39355. {
  39356. textSuffix = suffix;
  39357. updateText();
  39358. }
  39359. }
  39360. const String Slider::getTextValueSuffix() const
  39361. {
  39362. return textSuffix;
  39363. }
  39364. const String Slider::getTextFromValue (double v)
  39365. {
  39366. if (getNumDecimalPlacesToDisplay() > 0)
  39367. return String (v, getNumDecimalPlacesToDisplay()) + getTextValueSuffix();
  39368. else
  39369. return String (roundToInt (v)) + getTextValueSuffix();
  39370. }
  39371. double Slider::getValueFromText (const String& text)
  39372. {
  39373. String t (text.trimStart());
  39374. if (t.endsWith (textSuffix))
  39375. t = t.substring (0, t.length() - textSuffix.length());
  39376. while (t.startsWithChar ('+'))
  39377. t = t.substring (1).trimStart();
  39378. return t.initialSectionContainingOnly ("0123456789.,-")
  39379. .getDoubleValue();
  39380. }
  39381. double Slider::proportionOfLengthToValue (double proportion)
  39382. {
  39383. if (skewFactor != 1.0 && proportion > 0.0)
  39384. proportion = exp (log (proportion) / skewFactor);
  39385. return minimum + (maximum - minimum) * proportion;
  39386. }
  39387. double Slider::valueToProportionOfLength (double value)
  39388. {
  39389. const double n = (value - minimum) / (maximum - minimum);
  39390. return skewFactor == 1.0 ? n : pow (n, skewFactor);
  39391. }
  39392. double Slider::snapValue (double attemptedValue, const bool)
  39393. {
  39394. return attemptedValue;
  39395. }
  39396. void Slider::startedDragging()
  39397. {
  39398. }
  39399. void Slider::stoppedDragging()
  39400. {
  39401. }
  39402. void Slider::valueChanged()
  39403. {
  39404. }
  39405. void Slider::enablementChanged()
  39406. {
  39407. repaint();
  39408. }
  39409. void Slider::setPopupMenuEnabled (const bool menuEnabled_)
  39410. {
  39411. menuEnabled = menuEnabled_;
  39412. }
  39413. void Slider::setScrollWheelEnabled (const bool enabled)
  39414. {
  39415. scrollWheelEnabled = enabled;
  39416. }
  39417. void Slider::labelTextChanged (Label* label)
  39418. {
  39419. const double newValue = snapValue (getValueFromText (label->getText()), false);
  39420. if (newValue != (double) currentValue.getValue())
  39421. {
  39422. sendDragStart();
  39423. setValue (newValue, true, true);
  39424. sendDragEnd();
  39425. }
  39426. updateText(); // force a clean-up of the text, needed in case setValue() hasn't done this.
  39427. }
  39428. void Slider::buttonClicked (Button* button)
  39429. {
  39430. if (style == IncDecButtons)
  39431. {
  39432. sendDragStart();
  39433. if (button == incButton)
  39434. setValue (snapValue (getValue() + interval, false), true, true);
  39435. else if (button == decButton)
  39436. setValue (snapValue (getValue() - interval, false), true, true);
  39437. sendDragEnd();
  39438. }
  39439. }
  39440. double Slider::constrainedValue (double value) const
  39441. {
  39442. if (interval > 0)
  39443. value = minimum + interval * std::floor ((value - minimum) / interval + 0.5);
  39444. if (value <= minimum || maximum <= minimum)
  39445. value = minimum;
  39446. else if (value >= maximum)
  39447. value = maximum;
  39448. return value;
  39449. }
  39450. float Slider::getLinearSliderPos (const double value)
  39451. {
  39452. double sliderPosProportional;
  39453. if (maximum > minimum)
  39454. {
  39455. if (value < minimum)
  39456. {
  39457. sliderPosProportional = 0.0;
  39458. }
  39459. else if (value > maximum)
  39460. {
  39461. sliderPosProportional = 1.0;
  39462. }
  39463. else
  39464. {
  39465. sliderPosProportional = valueToProportionOfLength (value);
  39466. jassert (sliderPosProportional >= 0 && sliderPosProportional <= 1.0);
  39467. }
  39468. }
  39469. else
  39470. {
  39471. sliderPosProportional = 0.5;
  39472. }
  39473. if (isVertical() || style == IncDecButtons)
  39474. sliderPosProportional = 1.0 - sliderPosProportional;
  39475. return (float) (sliderRegionStart + sliderPosProportional * sliderRegionSize);
  39476. }
  39477. bool Slider::isHorizontal() const
  39478. {
  39479. return style == LinearHorizontal
  39480. || style == LinearBar
  39481. || style == TwoValueHorizontal
  39482. || style == ThreeValueHorizontal;
  39483. }
  39484. bool Slider::isVertical() const
  39485. {
  39486. return style == LinearVertical
  39487. || style == TwoValueVertical
  39488. || style == ThreeValueVertical;
  39489. }
  39490. bool Slider::incDecDragDirectionIsHorizontal() const
  39491. {
  39492. return incDecButtonMode == incDecButtonsDraggable_Horizontal
  39493. || (incDecButtonMode == incDecButtonsDraggable_AutoDirection && incDecButtonsSideBySide);
  39494. }
  39495. float Slider::getPositionOfValue (const double value)
  39496. {
  39497. if (isHorizontal() || isVertical())
  39498. {
  39499. return getLinearSliderPos (value);
  39500. }
  39501. else
  39502. {
  39503. jassertfalse; // not a valid call on a slider that doesn't work linearly!
  39504. return 0.0f;
  39505. }
  39506. }
  39507. void Slider::paint (Graphics& g)
  39508. {
  39509. if (style != IncDecButtons)
  39510. {
  39511. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  39512. {
  39513. const float sliderPos = (float) valueToProportionOfLength (lastCurrentValue);
  39514. jassert (sliderPos >= 0 && sliderPos <= 1.0f);
  39515. getLookAndFeel().drawRotarySlider (g,
  39516. sliderRect.getX(),
  39517. sliderRect.getY(),
  39518. sliderRect.getWidth(),
  39519. sliderRect.getHeight(),
  39520. sliderPos,
  39521. rotaryStart, rotaryEnd,
  39522. *this);
  39523. }
  39524. else
  39525. {
  39526. getLookAndFeel().drawLinearSlider (g,
  39527. sliderRect.getX(),
  39528. sliderRect.getY(),
  39529. sliderRect.getWidth(),
  39530. sliderRect.getHeight(),
  39531. getLinearSliderPos (lastCurrentValue),
  39532. getLinearSliderPos (lastValueMin),
  39533. getLinearSliderPos (lastValueMax),
  39534. style,
  39535. *this);
  39536. }
  39537. if (style == LinearBar && valueBox == 0)
  39538. {
  39539. g.setColour (findColour (Slider::textBoxOutlineColourId));
  39540. g.drawRect (0, 0, getWidth(), getHeight(), 1);
  39541. }
  39542. }
  39543. }
  39544. void Slider::resized()
  39545. {
  39546. int minXSpace = 0;
  39547. int minYSpace = 0;
  39548. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  39549. minXSpace = 30;
  39550. else
  39551. minYSpace = 15;
  39552. const int tbw = jmax (0, jmin (textBoxWidth, getWidth() - minXSpace));
  39553. const int tbh = jmax (0, jmin (textBoxHeight, getHeight() - minYSpace));
  39554. if (style == LinearBar)
  39555. {
  39556. if (valueBox != 0)
  39557. valueBox->setBounds (0, 0, getWidth(), getHeight());
  39558. }
  39559. else
  39560. {
  39561. if (textBoxPos == NoTextBox)
  39562. {
  39563. sliderRect.setBounds (0, 0, getWidth(), getHeight());
  39564. }
  39565. else if (textBoxPos == TextBoxLeft)
  39566. {
  39567. valueBox->setBounds (0, (getHeight() - tbh) / 2, tbw, tbh);
  39568. sliderRect.setBounds (tbw, 0, getWidth() - tbw, getHeight());
  39569. }
  39570. else if (textBoxPos == TextBoxRight)
  39571. {
  39572. valueBox->setBounds (getWidth() - tbw, (getHeight() - tbh) / 2, tbw, tbh);
  39573. sliderRect.setBounds (0, 0, getWidth() - tbw, getHeight());
  39574. }
  39575. else if (textBoxPos == TextBoxAbove)
  39576. {
  39577. valueBox->setBounds ((getWidth() - tbw) / 2, 0, tbw, tbh);
  39578. sliderRect.setBounds (0, tbh, getWidth(), getHeight() - tbh);
  39579. }
  39580. else if (textBoxPos == TextBoxBelow)
  39581. {
  39582. valueBox->setBounds ((getWidth() - tbw) / 2, getHeight() - tbh, tbw, tbh);
  39583. sliderRect.setBounds (0, 0, getWidth(), getHeight() - tbh);
  39584. }
  39585. }
  39586. const int indent = getLookAndFeel().getSliderThumbRadius (*this);
  39587. if (style == LinearBar)
  39588. {
  39589. const int barIndent = 1;
  39590. sliderRegionStart = barIndent;
  39591. sliderRegionSize = getWidth() - barIndent * 2;
  39592. sliderRect.setBounds (sliderRegionStart, barIndent,
  39593. sliderRegionSize, getHeight() - barIndent * 2);
  39594. }
  39595. else if (isHorizontal())
  39596. {
  39597. sliderRegionStart = sliderRect.getX() + indent;
  39598. sliderRegionSize = jmax (1, sliderRect.getWidth() - indent * 2);
  39599. sliderRect.setBounds (sliderRegionStart, sliderRect.getY(),
  39600. sliderRegionSize, sliderRect.getHeight());
  39601. }
  39602. else if (isVertical())
  39603. {
  39604. sliderRegionStart = sliderRect.getY() + indent;
  39605. sliderRegionSize = jmax (1, sliderRect.getHeight() - indent * 2);
  39606. sliderRect.setBounds (sliderRect.getX(), sliderRegionStart,
  39607. sliderRect.getWidth(), sliderRegionSize);
  39608. }
  39609. else
  39610. {
  39611. sliderRegionStart = 0;
  39612. sliderRegionSize = 100;
  39613. }
  39614. if (style == IncDecButtons)
  39615. {
  39616. Rectangle<int> buttonRect (sliderRect);
  39617. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  39618. buttonRect.expand (-2, 0);
  39619. else
  39620. buttonRect.expand (0, -2);
  39621. incDecButtonsSideBySide = buttonRect.getWidth() > buttonRect.getHeight();
  39622. if (incDecButtonsSideBySide)
  39623. {
  39624. decButton->setBounds (buttonRect.getX(),
  39625. buttonRect.getY(),
  39626. buttonRect.getWidth() / 2,
  39627. buttonRect.getHeight());
  39628. decButton->setConnectedEdges (Button::ConnectedOnRight);
  39629. incButton->setBounds (buttonRect.getCentreX(),
  39630. buttonRect.getY(),
  39631. buttonRect.getWidth() / 2,
  39632. buttonRect.getHeight());
  39633. incButton->setConnectedEdges (Button::ConnectedOnLeft);
  39634. }
  39635. else
  39636. {
  39637. incButton->setBounds (buttonRect.getX(),
  39638. buttonRect.getY(),
  39639. buttonRect.getWidth(),
  39640. buttonRect.getHeight() / 2);
  39641. incButton->setConnectedEdges (Button::ConnectedOnBottom);
  39642. decButton->setBounds (buttonRect.getX(),
  39643. buttonRect.getCentreY(),
  39644. buttonRect.getWidth(),
  39645. buttonRect.getHeight() / 2);
  39646. decButton->setConnectedEdges (Button::ConnectedOnTop);
  39647. }
  39648. }
  39649. }
  39650. void Slider::focusOfChildComponentChanged (FocusChangeType)
  39651. {
  39652. repaint();
  39653. }
  39654. void Slider::mouseDown (const MouseEvent& e)
  39655. {
  39656. mouseWasHidden = false;
  39657. incDecDragged = false;
  39658. mouseXWhenLastDragged = e.x;
  39659. mouseYWhenLastDragged = e.y;
  39660. mouseDragStartX = e.getMouseDownX();
  39661. mouseDragStartY = e.getMouseDownY();
  39662. if (isEnabled())
  39663. {
  39664. if (e.mods.isPopupMenu() && menuEnabled)
  39665. {
  39666. menuShown = true;
  39667. PopupMenu m;
  39668. m.setLookAndFeel (&getLookAndFeel());
  39669. m.addItem (1, TRANS ("velocity-sensitive mode"), true, isVelocityBased);
  39670. m.addSeparator();
  39671. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  39672. {
  39673. PopupMenu rotaryMenu;
  39674. rotaryMenu.addItem (2, TRANS ("use circular dragging"), true, style == Rotary);
  39675. rotaryMenu.addItem (3, TRANS ("use left-right dragging"), true, style == RotaryHorizontalDrag);
  39676. rotaryMenu.addItem (4, TRANS ("use up-down dragging"), true, style == RotaryVerticalDrag);
  39677. m.addSubMenu (TRANS ("rotary mode"), rotaryMenu);
  39678. }
  39679. const int r = m.show();
  39680. if (r == 1)
  39681. {
  39682. setVelocityBasedMode (! isVelocityBased);
  39683. }
  39684. else if (r == 2)
  39685. {
  39686. setSliderStyle (Rotary);
  39687. }
  39688. else if (r == 3)
  39689. {
  39690. setSliderStyle (RotaryHorizontalDrag);
  39691. }
  39692. else if (r == 4)
  39693. {
  39694. setSliderStyle (RotaryVerticalDrag);
  39695. }
  39696. }
  39697. else if (maximum > minimum)
  39698. {
  39699. menuShown = false;
  39700. if (valueBox != 0)
  39701. valueBox->hideEditor (true);
  39702. sliderBeingDragged = 0;
  39703. if (style == TwoValueHorizontal
  39704. || style == TwoValueVertical
  39705. || style == ThreeValueHorizontal
  39706. || style == ThreeValueVertical)
  39707. {
  39708. const float mousePos = (float) (isVertical() ? e.y : e.x);
  39709. const float normalPosDistance = std::abs (getLinearSliderPos (currentValue.getValue()) - mousePos);
  39710. const float minPosDistance = std::abs (getLinearSliderPos (valueMin.getValue()) - 0.1f - mousePos);
  39711. const float maxPosDistance = std::abs (getLinearSliderPos (valueMax.getValue()) + 0.1f - mousePos);
  39712. if (style == TwoValueHorizontal || style == TwoValueVertical)
  39713. {
  39714. if (maxPosDistance <= minPosDistance)
  39715. sliderBeingDragged = 2;
  39716. else
  39717. sliderBeingDragged = 1;
  39718. }
  39719. else if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  39720. {
  39721. if (normalPosDistance >= minPosDistance && maxPosDistance >= minPosDistance)
  39722. sliderBeingDragged = 1;
  39723. else if (normalPosDistance >= maxPosDistance)
  39724. sliderBeingDragged = 2;
  39725. }
  39726. }
  39727. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  39728. lastAngle = rotaryStart + (rotaryEnd - rotaryStart)
  39729. * valueToProportionOfLength (currentValue.getValue());
  39730. valueWhenLastDragged = ((sliderBeingDragged == 2) ? valueMax
  39731. : ((sliderBeingDragged == 1) ? valueMin
  39732. : currentValue)).getValue();
  39733. valueOnMouseDown = valueWhenLastDragged;
  39734. if (popupDisplayEnabled)
  39735. {
  39736. SliderPopupDisplayComponent* const popup = new SliderPopupDisplayComponent (this);
  39737. popupDisplay = popup;
  39738. if (parentForPopupDisplay != 0)
  39739. {
  39740. parentForPopupDisplay->addChildComponent (popup);
  39741. }
  39742. else
  39743. {
  39744. popup->addToDesktop (0);
  39745. }
  39746. popup->setVisible (true);
  39747. }
  39748. sendDragStart();
  39749. mouseDrag (e);
  39750. }
  39751. }
  39752. }
  39753. void Slider::mouseUp (const MouseEvent&)
  39754. {
  39755. if (isEnabled()
  39756. && (! menuShown)
  39757. && (maximum > minimum)
  39758. && (style != IncDecButtons || incDecDragged))
  39759. {
  39760. restoreMouseIfHidden();
  39761. if (sendChangeOnlyOnRelease && valueOnMouseDown != (double) currentValue.getValue())
  39762. triggerChangeMessage (false);
  39763. sendDragEnd();
  39764. popupDisplay = 0;
  39765. if (style == IncDecButtons)
  39766. {
  39767. incButton->setState (Button::buttonNormal);
  39768. decButton->setState (Button::buttonNormal);
  39769. }
  39770. }
  39771. }
  39772. void Slider::restoreMouseIfHidden()
  39773. {
  39774. if (mouseWasHidden)
  39775. {
  39776. mouseWasHidden = false;
  39777. for (int i = Desktop::getInstance().getNumMouseSources(); --i >= 0;)
  39778. Desktop::getInstance().getMouseSource(i)->enableUnboundedMouseMovement (false);
  39779. const double pos = (sliderBeingDragged == 2) ? getMaxValue()
  39780. : ((sliderBeingDragged == 1) ? getMinValue()
  39781. : (double) currentValue.getValue());
  39782. Point<int> mousePos;
  39783. if (style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  39784. {
  39785. mousePos = Desktop::getLastMouseDownPosition();
  39786. if (style == RotaryHorizontalDrag)
  39787. {
  39788. const double posDiff = valueToProportionOfLength (pos) - valueToProportionOfLength (valueOnMouseDown);
  39789. mousePos += Point<int> (roundToInt (pixelsForFullDragExtent * posDiff), 0);
  39790. }
  39791. else
  39792. {
  39793. const double posDiff = valueToProportionOfLength (valueOnMouseDown) - valueToProportionOfLength (pos);
  39794. mousePos += Point<int> (0, roundToInt (pixelsForFullDragExtent * posDiff));
  39795. }
  39796. }
  39797. else
  39798. {
  39799. const int pixelPos = (int) getLinearSliderPos (pos);
  39800. mousePos = relativePositionToGlobal (Point<int> (isHorizontal() ? pixelPos : (getWidth() / 2),
  39801. isVertical() ? pixelPos : (getHeight() / 2)));
  39802. }
  39803. Desktop::setMousePosition (mousePos);
  39804. }
  39805. }
  39806. void Slider::modifierKeysChanged (const ModifierKeys& modifiers)
  39807. {
  39808. if (isEnabled()
  39809. && style != IncDecButtons
  39810. && style != Rotary
  39811. && isVelocityBased == modifiers.isAnyModifierKeyDown())
  39812. {
  39813. restoreMouseIfHidden();
  39814. }
  39815. }
  39816. static double smallestAngleBetween (double a1, double a2)
  39817. {
  39818. return jmin (std::abs (a1 - a2),
  39819. std::abs (a1 + double_Pi * 2.0 - a2),
  39820. std::abs (a2 + double_Pi * 2.0 - a1));
  39821. }
  39822. void Slider::mouseDrag (const MouseEvent& e)
  39823. {
  39824. if (isEnabled()
  39825. && (! menuShown)
  39826. && (maximum > minimum))
  39827. {
  39828. if (style == Rotary)
  39829. {
  39830. int dx = e.x - sliderRect.getCentreX();
  39831. int dy = e.y - sliderRect.getCentreY();
  39832. if (dx * dx + dy * dy > 25)
  39833. {
  39834. double angle = std::atan2 ((double) dx, (double) -dy);
  39835. while (angle < 0.0)
  39836. angle += double_Pi * 2.0;
  39837. if (rotaryStop && ! e.mouseWasClicked())
  39838. {
  39839. if (std::abs (angle - lastAngle) > double_Pi)
  39840. {
  39841. if (angle >= lastAngle)
  39842. angle -= double_Pi * 2.0;
  39843. else
  39844. angle += double_Pi * 2.0;
  39845. }
  39846. if (angle >= lastAngle)
  39847. angle = jmin (angle, (double) jmax (rotaryStart, rotaryEnd));
  39848. else
  39849. angle = jmax (angle, (double) jmin (rotaryStart, rotaryEnd));
  39850. }
  39851. else
  39852. {
  39853. while (angle < rotaryStart)
  39854. angle += double_Pi * 2.0;
  39855. if (angle > rotaryEnd)
  39856. {
  39857. if (smallestAngleBetween (angle, rotaryStart) <= smallestAngleBetween (angle, rotaryEnd))
  39858. angle = rotaryStart;
  39859. else
  39860. angle = rotaryEnd;
  39861. }
  39862. }
  39863. const double proportion = (angle - rotaryStart) / (rotaryEnd - rotaryStart);
  39864. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, proportion));
  39865. lastAngle = angle;
  39866. }
  39867. }
  39868. else
  39869. {
  39870. if (style == LinearBar && e.mouseWasClicked()
  39871. && valueBox != 0 && valueBox->isEditable())
  39872. return;
  39873. if (style == IncDecButtons && ! incDecDragged)
  39874. {
  39875. if (e.getDistanceFromDragStart() < 10 || e.mouseWasClicked())
  39876. return;
  39877. incDecDragged = true;
  39878. mouseDragStartX = e.x;
  39879. mouseDragStartY = e.y;
  39880. }
  39881. if ((isVelocityBased == (userKeyOverridesVelocity ? e.mods.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::commandModifier | ModifierKeys::altModifier)
  39882. : false))
  39883. || ((maximum - minimum) / sliderRegionSize < interval))
  39884. {
  39885. const int mousePos = (isHorizontal() || style == RotaryHorizontalDrag) ? e.x : e.y;
  39886. double scaledMousePos = (mousePos - sliderRegionStart) / (double) sliderRegionSize;
  39887. if (style == RotaryHorizontalDrag
  39888. || style == RotaryVerticalDrag
  39889. || style == IncDecButtons
  39890. || ((style == LinearHorizontal || style == LinearVertical || style == LinearBar)
  39891. && ! snapsToMousePos))
  39892. {
  39893. const int mouseDiff = (style == RotaryHorizontalDrag
  39894. || style == LinearHorizontal
  39895. || style == LinearBar
  39896. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  39897. ? e.x - mouseDragStartX
  39898. : mouseDragStartY - e.y;
  39899. double newPos = valueToProportionOfLength (valueOnMouseDown)
  39900. + mouseDiff * (1.0 / pixelsForFullDragExtent);
  39901. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, newPos));
  39902. if (style == IncDecButtons)
  39903. {
  39904. incButton->setState (mouseDiff < 0 ? Button::buttonNormal : Button::buttonDown);
  39905. decButton->setState (mouseDiff > 0 ? Button::buttonNormal : Button::buttonDown);
  39906. }
  39907. }
  39908. else
  39909. {
  39910. if (isVertical())
  39911. scaledMousePos = 1.0 - scaledMousePos;
  39912. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, scaledMousePos));
  39913. }
  39914. }
  39915. else
  39916. {
  39917. const int mouseDiff = (isHorizontal() || style == RotaryHorizontalDrag
  39918. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  39919. ? e.x - mouseXWhenLastDragged
  39920. : e.y - mouseYWhenLastDragged;
  39921. const double maxSpeed = jmax (200, sliderRegionSize);
  39922. double speed = jlimit (0.0, maxSpeed, (double) abs (mouseDiff));
  39923. if (speed != 0)
  39924. {
  39925. speed = 0.2 * velocityModeSensitivity
  39926. * (1.0 + std::sin (double_Pi * (1.5 + jmin (0.5, velocityModeOffset
  39927. + jmax (0.0, (double) (speed - velocityModeThreshold))
  39928. / maxSpeed))));
  39929. if (mouseDiff < 0)
  39930. speed = -speed;
  39931. if (isVertical() || style == RotaryVerticalDrag
  39932. || (style == IncDecButtons && ! incDecDragDirectionIsHorizontal()))
  39933. speed = -speed;
  39934. const double currentPos = valueToProportionOfLength (valueWhenLastDragged);
  39935. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + speed));
  39936. e.source.enableUnboundedMouseMovement (true, false);
  39937. mouseWasHidden = true;
  39938. }
  39939. }
  39940. }
  39941. valueWhenLastDragged = jlimit (minimum, maximum, valueWhenLastDragged);
  39942. if (sliderBeingDragged == 0)
  39943. {
  39944. setValue (snapValue (valueWhenLastDragged, true),
  39945. ! sendChangeOnlyOnRelease, true);
  39946. }
  39947. else if (sliderBeingDragged == 1)
  39948. {
  39949. setMinValue (snapValue (valueWhenLastDragged, true),
  39950. ! sendChangeOnlyOnRelease, false, true);
  39951. if (e.mods.isShiftDown())
  39952. setMaxValue (getMinValue() + minMaxDiff, false, false, true);
  39953. else
  39954. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  39955. }
  39956. else
  39957. {
  39958. jassert (sliderBeingDragged == 2);
  39959. setMaxValue (snapValue (valueWhenLastDragged, true),
  39960. ! sendChangeOnlyOnRelease, false, true);
  39961. if (e.mods.isShiftDown())
  39962. setMinValue (getMaxValue() - minMaxDiff, false, false, true);
  39963. else
  39964. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  39965. }
  39966. mouseXWhenLastDragged = e.x;
  39967. mouseYWhenLastDragged = e.y;
  39968. }
  39969. }
  39970. void Slider::mouseDoubleClick (const MouseEvent&)
  39971. {
  39972. if (doubleClickToValue
  39973. && isEnabled()
  39974. && style != IncDecButtons
  39975. && minimum <= doubleClickReturnValue
  39976. && maximum >= doubleClickReturnValue)
  39977. {
  39978. sendDragStart();
  39979. setValue (doubleClickReturnValue, true, true);
  39980. sendDragEnd();
  39981. }
  39982. }
  39983. void Slider::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  39984. {
  39985. if (scrollWheelEnabled && isEnabled()
  39986. && style != TwoValueHorizontal
  39987. && style != TwoValueVertical)
  39988. {
  39989. if (maximum > minimum && ! e.mods.isAnyMouseButtonDown())
  39990. {
  39991. if (valueBox != 0)
  39992. valueBox->hideEditor (false);
  39993. const double value = (double) currentValue.getValue();
  39994. const double proportionDelta = (wheelIncrementX != 0 ? -wheelIncrementX : wheelIncrementY) * 0.15f;
  39995. const double currentPos = valueToProportionOfLength (value);
  39996. const double newValue = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + proportionDelta));
  39997. double delta = (newValue != value)
  39998. ? jmax (std::abs (newValue - value), interval) : 0;
  39999. if (value > newValue)
  40000. delta = -delta;
  40001. sendDragStart();
  40002. setValue (snapValue (value + delta, false), true, true);
  40003. sendDragEnd();
  40004. }
  40005. }
  40006. else
  40007. {
  40008. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  40009. }
  40010. }
  40011. void SliderListener::sliderDragStarted (Slider*)
  40012. {
  40013. }
  40014. void SliderListener::sliderDragEnded (Slider*)
  40015. {
  40016. }
  40017. END_JUCE_NAMESPACE
  40018. /*** End of inlined file: juce_Slider.cpp ***/
  40019. /*** Start of inlined file: juce_TableHeaderComponent.cpp ***/
  40020. BEGIN_JUCE_NAMESPACE
  40021. class DragOverlayComp : public Component
  40022. {
  40023. public:
  40024. DragOverlayComp (const Image& image_)
  40025. : image (image_)
  40026. {
  40027. image.duplicateIfShared();
  40028. image.multiplyAllAlphas (0.8f);
  40029. setAlwaysOnTop (true);
  40030. }
  40031. ~DragOverlayComp()
  40032. {
  40033. }
  40034. void paint (Graphics& g)
  40035. {
  40036. g.drawImageAt (image, 0, 0);
  40037. }
  40038. private:
  40039. Image image;
  40040. DragOverlayComp (const DragOverlayComp&);
  40041. DragOverlayComp& operator= (const DragOverlayComp&);
  40042. };
  40043. TableHeaderComponent::TableHeaderComponent()
  40044. : columnsChanged (false),
  40045. columnsResized (false),
  40046. sortChanged (false),
  40047. menuActive (true),
  40048. stretchToFit (false),
  40049. columnIdBeingResized (0),
  40050. columnIdBeingDragged (0),
  40051. columnIdUnderMouse (0),
  40052. lastDeliberateWidth (0)
  40053. {
  40054. }
  40055. TableHeaderComponent::~TableHeaderComponent()
  40056. {
  40057. dragOverlayComp = 0;
  40058. }
  40059. void TableHeaderComponent::setPopupMenuActive (const bool hasMenu)
  40060. {
  40061. menuActive = hasMenu;
  40062. }
  40063. bool TableHeaderComponent::isPopupMenuActive() const { return menuActive; }
  40064. int TableHeaderComponent::getNumColumns (const bool onlyCountVisibleColumns) const
  40065. {
  40066. if (onlyCountVisibleColumns)
  40067. {
  40068. int num = 0;
  40069. for (int i = columns.size(); --i >= 0;)
  40070. if (columns.getUnchecked(i)->isVisible())
  40071. ++num;
  40072. return num;
  40073. }
  40074. else
  40075. {
  40076. return columns.size();
  40077. }
  40078. }
  40079. const String TableHeaderComponent::getColumnName (const int columnId) const
  40080. {
  40081. const ColumnInfo* const ci = getInfoForId (columnId);
  40082. return ci != 0 ? ci->name : String::empty;
  40083. }
  40084. void TableHeaderComponent::setColumnName (const int columnId, const String& newName)
  40085. {
  40086. ColumnInfo* const ci = getInfoForId (columnId);
  40087. if (ci != 0 && ci->name != newName)
  40088. {
  40089. ci->name = newName;
  40090. sendColumnsChanged();
  40091. }
  40092. }
  40093. void TableHeaderComponent::addColumn (const String& columnName,
  40094. const int columnId,
  40095. const int width,
  40096. const int minimumWidth,
  40097. const int maximumWidth,
  40098. const int propertyFlags,
  40099. const int insertIndex)
  40100. {
  40101. // can't have a duplicate or null ID!
  40102. jassert (columnId != 0 && getIndexOfColumnId (columnId, false) < 0);
  40103. jassert (width > 0);
  40104. ColumnInfo* const ci = new ColumnInfo();
  40105. ci->name = columnName;
  40106. ci->id = columnId;
  40107. ci->width = width;
  40108. ci->lastDeliberateWidth = width;
  40109. ci->minimumWidth = minimumWidth;
  40110. ci->maximumWidth = maximumWidth;
  40111. if (ci->maximumWidth < 0)
  40112. ci->maximumWidth = std::numeric_limits<int>::max();
  40113. jassert (ci->maximumWidth >= ci->minimumWidth);
  40114. ci->propertyFlags = propertyFlags;
  40115. columns.insert (insertIndex, ci);
  40116. sendColumnsChanged();
  40117. }
  40118. void TableHeaderComponent::removeColumn (const int columnIdToRemove)
  40119. {
  40120. const int index = getIndexOfColumnId (columnIdToRemove, false);
  40121. if (index >= 0)
  40122. {
  40123. columns.remove (index);
  40124. sortChanged = true;
  40125. sendColumnsChanged();
  40126. }
  40127. }
  40128. void TableHeaderComponent::removeAllColumns()
  40129. {
  40130. if (columns.size() > 0)
  40131. {
  40132. columns.clear();
  40133. sendColumnsChanged();
  40134. }
  40135. }
  40136. void TableHeaderComponent::moveColumn (const int columnId, int newIndex)
  40137. {
  40138. const int currentIndex = getIndexOfColumnId (columnId, false);
  40139. newIndex = visibleIndexToTotalIndex (newIndex);
  40140. if (columns [currentIndex] != 0 && currentIndex != newIndex)
  40141. {
  40142. columns.move (currentIndex, newIndex);
  40143. sendColumnsChanged();
  40144. }
  40145. }
  40146. int TableHeaderComponent::getColumnWidth (const int columnId) const
  40147. {
  40148. const ColumnInfo* const ci = getInfoForId (columnId);
  40149. return ci != 0 ? ci->width : 0;
  40150. }
  40151. void TableHeaderComponent::setColumnWidth (const int columnId, const int newWidth)
  40152. {
  40153. ColumnInfo* const ci = getInfoForId (columnId);
  40154. if (ci != 0 && ci->width != newWidth)
  40155. {
  40156. const int numColumns = getNumColumns (true);
  40157. ci->lastDeliberateWidth = ci->width
  40158. = jlimit (ci->minimumWidth, ci->maximumWidth, newWidth);
  40159. if (stretchToFit)
  40160. {
  40161. const int index = getIndexOfColumnId (columnId, true) + 1;
  40162. if (((unsigned int) index) < (unsigned int) numColumns)
  40163. {
  40164. const int x = getColumnPosition (index).getX();
  40165. if (lastDeliberateWidth == 0)
  40166. lastDeliberateWidth = getTotalWidth();
  40167. resizeColumnsToFit (visibleIndexToTotalIndex (index), lastDeliberateWidth - x);
  40168. }
  40169. }
  40170. repaint();
  40171. columnsResized = true;
  40172. triggerAsyncUpdate();
  40173. }
  40174. }
  40175. int TableHeaderComponent::getIndexOfColumnId (const int columnId, const bool onlyCountVisibleColumns) const
  40176. {
  40177. int n = 0;
  40178. for (int i = 0; i < columns.size(); ++i)
  40179. {
  40180. if ((! onlyCountVisibleColumns) || columns.getUnchecked(i)->isVisible())
  40181. {
  40182. if (columns.getUnchecked(i)->id == columnId)
  40183. return n;
  40184. ++n;
  40185. }
  40186. }
  40187. return -1;
  40188. }
  40189. int TableHeaderComponent::getColumnIdOfIndex (int index, const bool onlyCountVisibleColumns) const
  40190. {
  40191. if (onlyCountVisibleColumns)
  40192. index = visibleIndexToTotalIndex (index);
  40193. const ColumnInfo* const ci = columns [index];
  40194. return (ci != 0) ? ci->id : 0;
  40195. }
  40196. const Rectangle<int> TableHeaderComponent::getColumnPosition (const int index) const
  40197. {
  40198. int x = 0, width = 0, n = 0;
  40199. for (int i = 0; i < columns.size(); ++i)
  40200. {
  40201. x += width;
  40202. if (columns.getUnchecked(i)->isVisible())
  40203. {
  40204. width = columns.getUnchecked(i)->width;
  40205. if (n++ == index)
  40206. break;
  40207. }
  40208. else
  40209. {
  40210. width = 0;
  40211. }
  40212. }
  40213. return Rectangle<int> (x, 0, width, getHeight());
  40214. }
  40215. int TableHeaderComponent::getColumnIdAtX (const int xToFind) const
  40216. {
  40217. if (xToFind >= 0)
  40218. {
  40219. int x = 0;
  40220. for (int i = 0; i < columns.size(); ++i)
  40221. {
  40222. const ColumnInfo* const ci = columns.getUnchecked(i);
  40223. if (ci->isVisible())
  40224. {
  40225. x += ci->width;
  40226. if (xToFind < x)
  40227. return ci->id;
  40228. }
  40229. }
  40230. }
  40231. return 0;
  40232. }
  40233. int TableHeaderComponent::getTotalWidth() const
  40234. {
  40235. int w = 0;
  40236. for (int i = columns.size(); --i >= 0;)
  40237. if (columns.getUnchecked(i)->isVisible())
  40238. w += columns.getUnchecked(i)->width;
  40239. return w;
  40240. }
  40241. void TableHeaderComponent::setStretchToFitActive (const bool shouldStretchToFit)
  40242. {
  40243. stretchToFit = shouldStretchToFit;
  40244. lastDeliberateWidth = getTotalWidth();
  40245. resized();
  40246. }
  40247. bool TableHeaderComponent::isStretchToFitActive() const
  40248. {
  40249. return stretchToFit;
  40250. }
  40251. void TableHeaderComponent::resizeAllColumnsToFit (int targetTotalWidth)
  40252. {
  40253. if (stretchToFit && getWidth() > 0
  40254. && columnIdBeingResized == 0 && columnIdBeingDragged == 0)
  40255. {
  40256. lastDeliberateWidth = targetTotalWidth;
  40257. resizeColumnsToFit (0, targetTotalWidth);
  40258. }
  40259. }
  40260. void TableHeaderComponent::resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth)
  40261. {
  40262. targetTotalWidth = jmax (targetTotalWidth, 0);
  40263. StretchableObjectResizer sor;
  40264. int i;
  40265. for (i = firstColumnIndex; i < columns.size(); ++i)
  40266. {
  40267. ColumnInfo* const ci = columns.getUnchecked(i);
  40268. if (ci->isVisible())
  40269. sor.addItem (ci->lastDeliberateWidth, ci->minimumWidth, ci->maximumWidth);
  40270. }
  40271. sor.resizeToFit (targetTotalWidth);
  40272. int visIndex = 0;
  40273. for (i = firstColumnIndex; i < columns.size(); ++i)
  40274. {
  40275. ColumnInfo* const ci = columns.getUnchecked(i);
  40276. if (ci->isVisible())
  40277. {
  40278. const int newWidth = jlimit (ci->minimumWidth, ci->maximumWidth,
  40279. (int) std::floor (sor.getItemSize (visIndex++)));
  40280. if (newWidth != ci->width)
  40281. {
  40282. ci->width = newWidth;
  40283. repaint();
  40284. columnsResized = true;
  40285. triggerAsyncUpdate();
  40286. }
  40287. }
  40288. }
  40289. }
  40290. void TableHeaderComponent::setColumnVisible (const int columnId, const bool shouldBeVisible)
  40291. {
  40292. ColumnInfo* const ci = getInfoForId (columnId);
  40293. if (ci != 0 && shouldBeVisible != ci->isVisible())
  40294. {
  40295. if (shouldBeVisible)
  40296. ci->propertyFlags |= visible;
  40297. else
  40298. ci->propertyFlags &= ~visible;
  40299. sendColumnsChanged();
  40300. resized();
  40301. }
  40302. }
  40303. bool TableHeaderComponent::isColumnVisible (const int columnId) const
  40304. {
  40305. const ColumnInfo* const ci = getInfoForId (columnId);
  40306. return ci != 0 && ci->isVisible();
  40307. }
  40308. void TableHeaderComponent::setSortColumnId (const int columnId, const bool sortForwards)
  40309. {
  40310. if (getSortColumnId() != columnId || isSortedForwards() != sortForwards)
  40311. {
  40312. for (int i = columns.size(); --i >= 0;)
  40313. columns.getUnchecked(i)->propertyFlags &= ~(sortedForwards | sortedBackwards);
  40314. ColumnInfo* const ci = getInfoForId (columnId);
  40315. if (ci != 0)
  40316. ci->propertyFlags |= (sortForwards ? sortedForwards : sortedBackwards);
  40317. reSortTable();
  40318. }
  40319. }
  40320. int TableHeaderComponent::getSortColumnId() const
  40321. {
  40322. for (int i = columns.size(); --i >= 0;)
  40323. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  40324. return columns.getUnchecked(i)->id;
  40325. return 0;
  40326. }
  40327. bool TableHeaderComponent::isSortedForwards() const
  40328. {
  40329. for (int i = columns.size(); --i >= 0;)
  40330. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  40331. return (columns.getUnchecked(i)->propertyFlags & sortedForwards) != 0;
  40332. return true;
  40333. }
  40334. void TableHeaderComponent::reSortTable()
  40335. {
  40336. sortChanged = true;
  40337. repaint();
  40338. triggerAsyncUpdate();
  40339. }
  40340. const String TableHeaderComponent::toString() const
  40341. {
  40342. String s;
  40343. XmlElement doc ("TABLELAYOUT");
  40344. doc.setAttribute ("sortedCol", getSortColumnId());
  40345. doc.setAttribute ("sortForwards", isSortedForwards());
  40346. for (int i = 0; i < columns.size(); ++i)
  40347. {
  40348. const ColumnInfo* const ci = columns.getUnchecked (i);
  40349. XmlElement* const e = doc.createNewChildElement ("COLUMN");
  40350. e->setAttribute ("id", ci->id);
  40351. e->setAttribute ("visible", ci->isVisible());
  40352. e->setAttribute ("width", ci->width);
  40353. }
  40354. return doc.createDocument (String::empty, true, false);
  40355. }
  40356. void TableHeaderComponent::restoreFromString (const String& storedVersion)
  40357. {
  40358. XmlDocument doc (storedVersion);
  40359. ScopedPointer <XmlElement> storedXml (doc.getDocumentElement());
  40360. int index = 0;
  40361. if (storedXml != 0 && storedXml->hasTagName ("TABLELAYOUT"))
  40362. {
  40363. forEachXmlChildElement (*storedXml, col)
  40364. {
  40365. const int tabId = col->getIntAttribute ("id");
  40366. ColumnInfo* const ci = getInfoForId (tabId);
  40367. if (ci != 0)
  40368. {
  40369. columns.move (columns.indexOf (ci), index);
  40370. ci->width = col->getIntAttribute ("width");
  40371. setColumnVisible (tabId, col->getBoolAttribute ("visible"));
  40372. }
  40373. ++index;
  40374. }
  40375. columnsResized = true;
  40376. sendColumnsChanged();
  40377. setSortColumnId (storedXml->getIntAttribute ("sortedCol"),
  40378. storedXml->getBoolAttribute ("sortForwards", true));
  40379. }
  40380. }
  40381. void TableHeaderComponent::addListener (TableHeaderListener* const newListener)
  40382. {
  40383. listeners.addIfNotAlreadyThere (newListener);
  40384. }
  40385. void TableHeaderComponent::removeListener (TableHeaderListener* const listenerToRemove)
  40386. {
  40387. listeners.removeValue (listenerToRemove);
  40388. }
  40389. void TableHeaderComponent::columnClicked (int columnId, const ModifierKeys& mods)
  40390. {
  40391. const ColumnInfo* const ci = getInfoForId (columnId);
  40392. if (ci != 0 && (ci->propertyFlags & sortable) != 0 && ! mods.isPopupMenu())
  40393. setSortColumnId (columnId, (ci->propertyFlags & sortedForwards) == 0);
  40394. }
  40395. void TableHeaderComponent::addMenuItems (PopupMenu& menu, const int /*columnIdClicked*/)
  40396. {
  40397. for (int i = 0; i < columns.size(); ++i)
  40398. {
  40399. const ColumnInfo* const ci = columns.getUnchecked(i);
  40400. if ((ci->propertyFlags & appearsOnColumnMenu) != 0)
  40401. menu.addItem (ci->id, ci->name,
  40402. (ci->propertyFlags & (sortedForwards | sortedBackwards)) == 0,
  40403. isColumnVisible (ci->id));
  40404. }
  40405. }
  40406. void TableHeaderComponent::reactToMenuItem (const int menuReturnId, const int /*columnIdClicked*/)
  40407. {
  40408. if (getIndexOfColumnId (menuReturnId, false) >= 0)
  40409. setColumnVisible (menuReturnId, ! isColumnVisible (menuReturnId));
  40410. }
  40411. void TableHeaderComponent::paint (Graphics& g)
  40412. {
  40413. LookAndFeel& lf = getLookAndFeel();
  40414. lf.drawTableHeaderBackground (g, *this);
  40415. const Rectangle<int> clip (g.getClipBounds());
  40416. int x = 0;
  40417. for (int i = 0; i < columns.size(); ++i)
  40418. {
  40419. const ColumnInfo* const ci = columns.getUnchecked(i);
  40420. if (ci->isVisible())
  40421. {
  40422. if (x + ci->width > clip.getX()
  40423. && (ci->id != columnIdBeingDragged
  40424. || dragOverlayComp == 0
  40425. || ! dragOverlayComp->isVisible()))
  40426. {
  40427. g.saveState();
  40428. g.setOrigin (x, 0);
  40429. g.reduceClipRegion (0, 0, ci->width, getHeight());
  40430. lf.drawTableHeaderColumn (g, ci->name, ci->id, ci->width, getHeight(),
  40431. ci->id == columnIdUnderMouse,
  40432. ci->id == columnIdUnderMouse && isMouseButtonDown(),
  40433. ci->propertyFlags);
  40434. g.restoreState();
  40435. }
  40436. x += ci->width;
  40437. if (x >= clip.getRight())
  40438. break;
  40439. }
  40440. }
  40441. }
  40442. void TableHeaderComponent::resized()
  40443. {
  40444. }
  40445. void TableHeaderComponent::mouseMove (const MouseEvent& e)
  40446. {
  40447. updateColumnUnderMouse (e.x, e.y);
  40448. }
  40449. void TableHeaderComponent::mouseEnter (const MouseEvent& e)
  40450. {
  40451. updateColumnUnderMouse (e.x, e.y);
  40452. }
  40453. void TableHeaderComponent::mouseExit (const MouseEvent& e)
  40454. {
  40455. updateColumnUnderMouse (e.x, e.y);
  40456. }
  40457. void TableHeaderComponent::mouseDown (const MouseEvent& e)
  40458. {
  40459. repaint();
  40460. columnIdBeingResized = 0;
  40461. columnIdBeingDragged = 0;
  40462. if (columnIdUnderMouse != 0)
  40463. {
  40464. draggingColumnOffset = e.x - getColumnPosition (getIndexOfColumnId (columnIdUnderMouse, true)).getX();
  40465. if (e.mods.isPopupMenu())
  40466. columnClicked (columnIdUnderMouse, e.mods);
  40467. }
  40468. if (menuActive && e.mods.isPopupMenu())
  40469. showColumnChooserMenu (columnIdUnderMouse);
  40470. }
  40471. void TableHeaderComponent::mouseDrag (const MouseEvent& e)
  40472. {
  40473. if (columnIdBeingResized == 0
  40474. && columnIdBeingDragged == 0
  40475. && ! (e.mouseWasClicked() || e.mods.isPopupMenu()))
  40476. {
  40477. dragOverlayComp = 0;
  40478. columnIdBeingResized = getResizeDraggerAt (e.getMouseDownX());
  40479. if (columnIdBeingResized != 0)
  40480. {
  40481. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  40482. initialColumnWidth = ci->width;
  40483. }
  40484. else
  40485. {
  40486. beginDrag (e);
  40487. }
  40488. }
  40489. if (columnIdBeingResized != 0)
  40490. {
  40491. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  40492. if (ci != 0)
  40493. {
  40494. int w = jlimit (ci->minimumWidth, ci->maximumWidth,
  40495. initialColumnWidth + e.getDistanceFromDragStartX());
  40496. if (stretchToFit)
  40497. {
  40498. // prevent us dragging a column too far right if we're in stretch-to-fit mode
  40499. int minWidthOnRight = 0;
  40500. for (int i = getIndexOfColumnId (columnIdBeingResized, false) + 1; i < columns.size(); ++i)
  40501. if (columns.getUnchecked (i)->isVisible())
  40502. minWidthOnRight += columns.getUnchecked (i)->minimumWidth;
  40503. const Rectangle<int> currentPos (getColumnPosition (getIndexOfColumnId (columnIdBeingResized, true)));
  40504. w = jmax (ci->minimumWidth, jmin (w, getWidth() - minWidthOnRight - currentPos.getX()));
  40505. }
  40506. setColumnWidth (columnIdBeingResized, w);
  40507. }
  40508. }
  40509. else if (columnIdBeingDragged != 0)
  40510. {
  40511. if (e.y >= -50 && e.y < getHeight() + 50)
  40512. {
  40513. if (dragOverlayComp != 0)
  40514. {
  40515. dragOverlayComp->setVisible (true);
  40516. dragOverlayComp->setBounds (jlimit (0,
  40517. jmax (0, getTotalWidth() - dragOverlayComp->getWidth()),
  40518. e.x - draggingColumnOffset),
  40519. 0,
  40520. dragOverlayComp->getWidth(),
  40521. getHeight());
  40522. for (int i = columns.size(); --i >= 0;)
  40523. {
  40524. const int currentIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  40525. int newIndex = currentIndex;
  40526. if (newIndex > 0)
  40527. {
  40528. // if the previous column isn't draggable, we can't move our column
  40529. // past it, because that'd change the undraggable column's position..
  40530. const ColumnInfo* const previous = columns.getUnchecked (newIndex - 1);
  40531. if ((previous->propertyFlags & draggable) != 0)
  40532. {
  40533. const int leftOfPrevious = getColumnPosition (newIndex - 1).getX();
  40534. const int rightOfCurrent = getColumnPosition (newIndex).getRight();
  40535. if (abs (dragOverlayComp->getX() - leftOfPrevious)
  40536. < abs (dragOverlayComp->getRight() - rightOfCurrent))
  40537. {
  40538. --newIndex;
  40539. }
  40540. }
  40541. }
  40542. if (newIndex < columns.size() - 1)
  40543. {
  40544. // if the next column isn't draggable, we can't move our column
  40545. // past it, because that'd change the undraggable column's position..
  40546. const ColumnInfo* const nextCol = columns.getUnchecked (newIndex + 1);
  40547. if ((nextCol->propertyFlags & draggable) != 0)
  40548. {
  40549. const int leftOfCurrent = getColumnPosition (newIndex).getX();
  40550. const int rightOfNext = getColumnPosition (newIndex + 1).getRight();
  40551. if (abs (dragOverlayComp->getX() - leftOfCurrent)
  40552. > abs (dragOverlayComp->getRight() - rightOfNext))
  40553. {
  40554. ++newIndex;
  40555. }
  40556. }
  40557. }
  40558. if (newIndex != currentIndex)
  40559. moveColumn (columnIdBeingDragged, newIndex);
  40560. else
  40561. break;
  40562. }
  40563. }
  40564. }
  40565. else
  40566. {
  40567. endDrag (draggingColumnOriginalIndex);
  40568. }
  40569. }
  40570. }
  40571. void TableHeaderComponent::beginDrag (const MouseEvent& e)
  40572. {
  40573. if (columnIdBeingDragged == 0)
  40574. {
  40575. columnIdBeingDragged = getColumnIdAtX (e.getMouseDownX());
  40576. const ColumnInfo* const ci = getInfoForId (columnIdBeingDragged);
  40577. if (ci == 0 || (ci->propertyFlags & draggable) == 0)
  40578. {
  40579. columnIdBeingDragged = 0;
  40580. }
  40581. else
  40582. {
  40583. draggingColumnOriginalIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  40584. const Rectangle<int> columnRect (getColumnPosition (draggingColumnOriginalIndex));
  40585. const int temp = columnIdBeingDragged;
  40586. columnIdBeingDragged = 0;
  40587. addAndMakeVisible (dragOverlayComp = new DragOverlayComp (createComponentSnapshot (columnRect, false)));
  40588. columnIdBeingDragged = temp;
  40589. dragOverlayComp->setBounds (columnRect);
  40590. for (int i = listeners.size(); --i >= 0;)
  40591. {
  40592. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, columnIdBeingDragged);
  40593. i = jmin (i, listeners.size() - 1);
  40594. }
  40595. }
  40596. }
  40597. }
  40598. void TableHeaderComponent::endDrag (const int finalIndex)
  40599. {
  40600. if (columnIdBeingDragged != 0)
  40601. {
  40602. moveColumn (columnIdBeingDragged, finalIndex);
  40603. columnIdBeingDragged = 0;
  40604. repaint();
  40605. for (int i = listeners.size(); --i >= 0;)
  40606. {
  40607. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, 0);
  40608. i = jmin (i, listeners.size() - 1);
  40609. }
  40610. }
  40611. }
  40612. void TableHeaderComponent::mouseUp (const MouseEvent& e)
  40613. {
  40614. mouseDrag (e);
  40615. for (int i = columns.size(); --i >= 0;)
  40616. if (columns.getUnchecked (i)->isVisible())
  40617. columns.getUnchecked (i)->lastDeliberateWidth = columns.getUnchecked (i)->width;
  40618. columnIdBeingResized = 0;
  40619. repaint();
  40620. endDrag (getIndexOfColumnId (columnIdBeingDragged, true));
  40621. updateColumnUnderMouse (e.x, e.y);
  40622. if (columnIdUnderMouse != 0 && e.mouseWasClicked() && ! e.mods.isPopupMenu())
  40623. columnClicked (columnIdUnderMouse, e.mods);
  40624. dragOverlayComp = 0;
  40625. }
  40626. const MouseCursor TableHeaderComponent::getMouseCursor()
  40627. {
  40628. if (columnIdBeingResized != 0 || (getResizeDraggerAt (getMouseXYRelative().getX()) != 0 && ! isMouseButtonDown()))
  40629. return MouseCursor (MouseCursor::LeftRightResizeCursor);
  40630. return Component::getMouseCursor();
  40631. }
  40632. bool TableHeaderComponent::ColumnInfo::isVisible() const
  40633. {
  40634. return (propertyFlags & TableHeaderComponent::visible) != 0;
  40635. }
  40636. TableHeaderComponent::ColumnInfo* TableHeaderComponent::getInfoForId (const int id) const
  40637. {
  40638. for (int i = columns.size(); --i >= 0;)
  40639. if (columns.getUnchecked(i)->id == id)
  40640. return columns.getUnchecked(i);
  40641. return 0;
  40642. }
  40643. int TableHeaderComponent::visibleIndexToTotalIndex (const int visibleIndex) const
  40644. {
  40645. int n = 0;
  40646. for (int i = 0; i < columns.size(); ++i)
  40647. {
  40648. if (columns.getUnchecked(i)->isVisible())
  40649. {
  40650. if (n == visibleIndex)
  40651. return i;
  40652. ++n;
  40653. }
  40654. }
  40655. return -1;
  40656. }
  40657. void TableHeaderComponent::sendColumnsChanged()
  40658. {
  40659. if (stretchToFit && lastDeliberateWidth > 0)
  40660. resizeAllColumnsToFit (lastDeliberateWidth);
  40661. repaint();
  40662. columnsChanged = true;
  40663. triggerAsyncUpdate();
  40664. }
  40665. void TableHeaderComponent::handleAsyncUpdate()
  40666. {
  40667. const bool changed = columnsChanged || sortChanged;
  40668. const bool sized = columnsResized || changed;
  40669. const bool sorted = sortChanged;
  40670. columnsChanged = false;
  40671. columnsResized = false;
  40672. sortChanged = false;
  40673. if (sorted)
  40674. {
  40675. for (int i = listeners.size(); --i >= 0;)
  40676. {
  40677. listeners.getUnchecked(i)->tableSortOrderChanged (this);
  40678. i = jmin (i, listeners.size() - 1);
  40679. }
  40680. }
  40681. if (changed)
  40682. {
  40683. for (int i = listeners.size(); --i >= 0;)
  40684. {
  40685. listeners.getUnchecked(i)->tableColumnsChanged (this);
  40686. i = jmin (i, listeners.size() - 1);
  40687. }
  40688. }
  40689. if (sized)
  40690. {
  40691. for (int i = listeners.size(); --i >= 0;)
  40692. {
  40693. listeners.getUnchecked(i)->tableColumnsResized (this);
  40694. i = jmin (i, listeners.size() - 1);
  40695. }
  40696. }
  40697. }
  40698. int TableHeaderComponent::getResizeDraggerAt (const int mouseX) const
  40699. {
  40700. if (((unsigned int) mouseX) < (unsigned int) getWidth())
  40701. {
  40702. const int draggableDistance = 3;
  40703. int x = 0;
  40704. for (int i = 0; i < columns.size(); ++i)
  40705. {
  40706. const ColumnInfo* const ci = columns.getUnchecked(i);
  40707. if (ci->isVisible())
  40708. {
  40709. if (abs (mouseX - (x + ci->width)) <= draggableDistance
  40710. && (ci->propertyFlags & resizable) != 0)
  40711. return ci->id;
  40712. x += ci->width;
  40713. }
  40714. }
  40715. }
  40716. return 0;
  40717. }
  40718. void TableHeaderComponent::updateColumnUnderMouse (int x, int y)
  40719. {
  40720. const int newCol = (reallyContains (x, y, true) && getResizeDraggerAt (x) == 0)
  40721. ? getColumnIdAtX (x) : 0;
  40722. if (newCol != columnIdUnderMouse)
  40723. {
  40724. columnIdUnderMouse = newCol;
  40725. repaint();
  40726. }
  40727. }
  40728. void TableHeaderComponent::showColumnChooserMenu (const int columnIdClicked)
  40729. {
  40730. PopupMenu m;
  40731. addMenuItems (m, columnIdClicked);
  40732. if (m.getNumItems() > 0)
  40733. {
  40734. m.setLookAndFeel (&getLookAndFeel());
  40735. const int result = m.show();
  40736. if (result != 0)
  40737. reactToMenuItem (result, columnIdClicked);
  40738. }
  40739. }
  40740. void TableHeaderListener::tableColumnDraggingChanged (TableHeaderComponent*, int)
  40741. {
  40742. }
  40743. END_JUCE_NAMESPACE
  40744. /*** End of inlined file: juce_TableHeaderComponent.cpp ***/
  40745. /*** Start of inlined file: juce_TableListBox.cpp ***/
  40746. BEGIN_JUCE_NAMESPACE
  40747. static const char* const tableColumnPropertyTag = "_tableColumnID";
  40748. class TableListRowComp : public Component,
  40749. public TooltipClient
  40750. {
  40751. public:
  40752. TableListRowComp (TableListBox& owner_)
  40753. : owner (owner_),
  40754. row (-1),
  40755. isSelected (false)
  40756. {
  40757. }
  40758. ~TableListRowComp()
  40759. {
  40760. deleteAllChildren();
  40761. }
  40762. void paint (Graphics& g)
  40763. {
  40764. TableListBoxModel* const model = owner.getModel();
  40765. if (model != 0)
  40766. {
  40767. const TableHeaderComponent* const header = owner.getHeader();
  40768. model->paintRowBackground (g, row, getWidth(), getHeight(), isSelected);
  40769. const int numColumns = header->getNumColumns (true);
  40770. for (int i = 0; i < numColumns; ++i)
  40771. {
  40772. if (! columnsWithComponents [i])
  40773. {
  40774. const int columnId = header->getColumnIdOfIndex (i, true);
  40775. Rectangle<int> columnRect (header->getColumnPosition (i));
  40776. columnRect.setSize (columnRect.getWidth(), getHeight());
  40777. g.saveState();
  40778. g.reduceClipRegion (columnRect);
  40779. g.setOrigin (columnRect.getX(), 0);
  40780. model->paintCell (g, row, columnId, columnRect.getWidth(), columnRect.getHeight(), isSelected);
  40781. g.restoreState();
  40782. }
  40783. }
  40784. }
  40785. }
  40786. void update (const int newRow, const bool isNowSelected)
  40787. {
  40788. if (newRow != row || isNowSelected != isSelected)
  40789. {
  40790. row = newRow;
  40791. isSelected = isNowSelected;
  40792. repaint();
  40793. }
  40794. if (row < owner.getNumRows())
  40795. {
  40796. jassert (row >= 0);
  40797. const Identifier tagPropertyName ("_tableLastUseNum");
  40798. const int newTag = Random::getSystemRandom().nextInt();
  40799. const TableHeaderComponent* const header = owner.getHeader();
  40800. const int numColumns = header->getNumColumns (true);
  40801. int i;
  40802. columnsWithComponents.clear();
  40803. if (owner.getModel() != 0)
  40804. {
  40805. for (i = 0; i < numColumns; ++i)
  40806. {
  40807. const int columnId = header->getColumnIdOfIndex (i, true);
  40808. Component* const newComp
  40809. = owner.getModel()->refreshComponentForCell (row, columnId, isSelected,
  40810. findChildComponentForColumn (columnId));
  40811. if (newComp != 0)
  40812. {
  40813. addAndMakeVisible (newComp);
  40814. newComp->getProperties().set (tagPropertyName, newTag);
  40815. newComp->getProperties().set (tableColumnPropertyTag, columnId);
  40816. const Rectangle<int> columnRect (header->getColumnPosition (i));
  40817. newComp->setBounds (columnRect.getX(), 0, columnRect.getWidth(), getHeight());
  40818. columnsWithComponents.setBit (i);
  40819. }
  40820. }
  40821. }
  40822. for (i = getNumChildComponents(); --i >= 0;)
  40823. {
  40824. Component* const c = getChildComponent (i);
  40825. if ((int) c->getProperties() [tagPropertyName] != newTag)
  40826. delete c;
  40827. }
  40828. }
  40829. else
  40830. {
  40831. columnsWithComponents.clear();
  40832. deleteAllChildren();
  40833. }
  40834. }
  40835. void resized()
  40836. {
  40837. for (int i = getNumChildComponents(); --i >= 0;)
  40838. {
  40839. Component* const c = getChildComponent (i);
  40840. const int columnId = c->getProperties() [tableColumnPropertyTag];
  40841. if (columnId != 0)
  40842. {
  40843. const Rectangle<int> columnRect (owner.getHeader()->getColumnPosition (owner.getHeader()->getIndexOfColumnId (columnId, true)));
  40844. c->setBounds (columnRect.getX(), 0, columnRect.getWidth(), getHeight());
  40845. }
  40846. }
  40847. }
  40848. void mouseDown (const MouseEvent& e)
  40849. {
  40850. isDragging = false;
  40851. selectRowOnMouseUp = false;
  40852. if (isEnabled())
  40853. {
  40854. if (! isSelected)
  40855. {
  40856. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  40857. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  40858. if (columnId != 0 && owner.getModel() != 0)
  40859. owner.getModel()->cellClicked (row, columnId, e);
  40860. }
  40861. else
  40862. {
  40863. selectRowOnMouseUp = true;
  40864. }
  40865. }
  40866. }
  40867. void mouseDrag (const MouseEvent& e)
  40868. {
  40869. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  40870. {
  40871. const SparseSet<int> selectedRows (owner.getSelectedRows());
  40872. if (selectedRows.size() > 0)
  40873. {
  40874. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  40875. if (dragDescription.isNotEmpty())
  40876. {
  40877. isDragging = true;
  40878. owner.startDragAndDrop (e, dragDescription);
  40879. }
  40880. }
  40881. }
  40882. }
  40883. void mouseUp (const MouseEvent& e)
  40884. {
  40885. if (selectRowOnMouseUp && e.mouseWasClicked() && isEnabled())
  40886. {
  40887. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  40888. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  40889. if (columnId != 0 && owner.getModel() != 0)
  40890. owner.getModel()->cellClicked (row, columnId, e);
  40891. }
  40892. }
  40893. void mouseDoubleClick (const MouseEvent& e)
  40894. {
  40895. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  40896. if (columnId != 0 && owner.getModel() != 0)
  40897. owner.getModel()->cellDoubleClicked (row, columnId, e);
  40898. }
  40899. const String getTooltip()
  40900. {
  40901. const int columnId = owner.getHeader()->getColumnIdAtX (getMouseXYRelative().getX());
  40902. if (columnId != 0 && owner.getModel() != 0)
  40903. return owner.getModel()->getCellTooltip (row, columnId);
  40904. return String::empty;
  40905. }
  40906. juce_UseDebuggingNewOperator
  40907. private:
  40908. TableListBox& owner;
  40909. int row;
  40910. bool isSelected, isDragging, selectRowOnMouseUp;
  40911. BigInteger columnsWithComponents;
  40912. Component* findChildComponentForColumn (const int columnId) const
  40913. {
  40914. for (int i = getNumChildComponents(); --i >= 0;)
  40915. {
  40916. Component* const c = getChildComponent (i);
  40917. if ((int) c->getProperties() [tableColumnPropertyTag] == columnId)
  40918. return c;
  40919. }
  40920. return 0;
  40921. }
  40922. TableListRowComp (const TableListRowComp&);
  40923. TableListRowComp& operator= (const TableListRowComp&);
  40924. };
  40925. class TableListBoxHeader : public TableHeaderComponent
  40926. {
  40927. public:
  40928. TableListBoxHeader (TableListBox& owner_)
  40929. : owner (owner_)
  40930. {
  40931. }
  40932. ~TableListBoxHeader()
  40933. {
  40934. }
  40935. void addMenuItems (PopupMenu& menu, int columnIdClicked)
  40936. {
  40937. if (owner.isAutoSizeMenuOptionShown())
  40938. {
  40939. menu.addItem (0xf836743, TRANS("Auto-size this column"), columnIdClicked != 0);
  40940. menu.addItem (0xf836744, TRANS("Auto-size all columns"), owner.getHeader()->getNumColumns (true) > 0);
  40941. menu.addSeparator();
  40942. }
  40943. TableHeaderComponent::addMenuItems (menu, columnIdClicked);
  40944. }
  40945. void reactToMenuItem (int menuReturnId, int columnIdClicked)
  40946. {
  40947. if (menuReturnId == 0xf836743)
  40948. {
  40949. owner.autoSizeColumn (columnIdClicked);
  40950. }
  40951. else if (menuReturnId == 0xf836744)
  40952. {
  40953. owner.autoSizeAllColumns();
  40954. }
  40955. else
  40956. {
  40957. TableHeaderComponent::reactToMenuItem (menuReturnId, columnIdClicked);
  40958. }
  40959. }
  40960. juce_UseDebuggingNewOperator
  40961. private:
  40962. TableListBox& owner;
  40963. TableListBoxHeader (const TableListBoxHeader&);
  40964. TableListBoxHeader& operator= (const TableListBoxHeader&);
  40965. };
  40966. TableListBox::TableListBox (const String& name, TableListBoxModel* const model_)
  40967. : ListBox (name, 0),
  40968. model (model_),
  40969. autoSizeOptionsShown (true)
  40970. {
  40971. ListBox::model = this;
  40972. header = new TableListBoxHeader (*this);
  40973. header->setSize (100, 28);
  40974. header->addListener (this);
  40975. setHeaderComponent (header);
  40976. }
  40977. TableListBox::~TableListBox()
  40978. {
  40979. deleteAllChildren();
  40980. }
  40981. void TableListBox::setModel (TableListBoxModel* const newModel)
  40982. {
  40983. if (model != newModel)
  40984. {
  40985. model = newModel;
  40986. updateContent();
  40987. }
  40988. }
  40989. int TableListBox::getHeaderHeight() const
  40990. {
  40991. return header->getHeight();
  40992. }
  40993. void TableListBox::setHeaderHeight (const int newHeight)
  40994. {
  40995. header->setSize (header->getWidth(), newHeight);
  40996. resized();
  40997. }
  40998. void TableListBox::autoSizeColumn (const int columnId)
  40999. {
  41000. const int width = model != 0 ? model->getColumnAutoSizeWidth (columnId) : 0;
  41001. if (width > 0)
  41002. header->setColumnWidth (columnId, width);
  41003. }
  41004. void TableListBox::autoSizeAllColumns()
  41005. {
  41006. for (int i = 0; i < header->getNumColumns (true); ++i)
  41007. autoSizeColumn (header->getColumnIdOfIndex (i, true));
  41008. }
  41009. void TableListBox::setAutoSizeMenuOptionShown (const bool shouldBeShown)
  41010. {
  41011. autoSizeOptionsShown = shouldBeShown;
  41012. }
  41013. bool TableListBox::isAutoSizeMenuOptionShown() const
  41014. {
  41015. return autoSizeOptionsShown;
  41016. }
  41017. const Rectangle<int> TableListBox::getCellPosition (const int columnId,
  41018. const int rowNumber,
  41019. const bool relativeToComponentTopLeft) const
  41020. {
  41021. Rectangle<int> headerCell (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  41022. if (relativeToComponentTopLeft)
  41023. headerCell.translate (header->getX(), 0);
  41024. const Rectangle<int> row (getRowPosition (rowNumber, relativeToComponentTopLeft));
  41025. return Rectangle<int> (headerCell.getX(), row.getY(),
  41026. headerCell.getWidth(), row.getHeight());
  41027. }
  41028. void TableListBox::scrollToEnsureColumnIsOnscreen (const int columnId)
  41029. {
  41030. ScrollBar* const scrollbar = getHorizontalScrollBar();
  41031. if (scrollbar != 0)
  41032. {
  41033. const Rectangle<int> pos (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  41034. double x = scrollbar->getCurrentRangeStart();
  41035. const double w = scrollbar->getCurrentRangeSize();
  41036. if (pos.getX() < x)
  41037. x = pos.getX();
  41038. else if (pos.getRight() > x + w)
  41039. x += jmax (0.0, pos.getRight() - (x + w));
  41040. scrollbar->setCurrentRangeStart (x);
  41041. }
  41042. }
  41043. int TableListBox::getNumRows()
  41044. {
  41045. return model != 0 ? model->getNumRows() : 0;
  41046. }
  41047. void TableListBox::paintListBoxItem (int, Graphics&, int, int, bool)
  41048. {
  41049. }
  41050. Component* TableListBox::refreshComponentForRow (int rowNumber, bool isRowSelected_, Component* existingComponentToUpdate)
  41051. {
  41052. if (existingComponentToUpdate == 0)
  41053. existingComponentToUpdate = new TableListRowComp (*this);
  41054. static_cast <TableListRowComp*> (existingComponentToUpdate)->update (rowNumber, isRowSelected_);
  41055. return existingComponentToUpdate;
  41056. }
  41057. void TableListBox::selectedRowsChanged (int row)
  41058. {
  41059. if (model != 0)
  41060. model->selectedRowsChanged (row);
  41061. }
  41062. void TableListBox::deleteKeyPressed (int row)
  41063. {
  41064. if (model != 0)
  41065. model->deleteKeyPressed (row);
  41066. }
  41067. void TableListBox::returnKeyPressed (int row)
  41068. {
  41069. if (model != 0)
  41070. model->returnKeyPressed (row);
  41071. }
  41072. void TableListBox::backgroundClicked()
  41073. {
  41074. if (model != 0)
  41075. model->backgroundClicked();
  41076. }
  41077. void TableListBox::listWasScrolled()
  41078. {
  41079. if (model != 0)
  41080. model->listWasScrolled();
  41081. }
  41082. void TableListBox::tableColumnsChanged (TableHeaderComponent*)
  41083. {
  41084. setMinimumContentWidth (header->getTotalWidth());
  41085. repaint();
  41086. updateColumnComponents();
  41087. }
  41088. void TableListBox::tableColumnsResized (TableHeaderComponent*)
  41089. {
  41090. setMinimumContentWidth (header->getTotalWidth());
  41091. repaint();
  41092. updateColumnComponents();
  41093. }
  41094. void TableListBox::tableSortOrderChanged (TableHeaderComponent*)
  41095. {
  41096. if (model != 0)
  41097. model->sortOrderChanged (header->getSortColumnId(),
  41098. header->isSortedForwards());
  41099. }
  41100. void TableListBox::tableColumnDraggingChanged (TableHeaderComponent*, int columnIdNowBeingDragged_)
  41101. {
  41102. columnIdNowBeingDragged = columnIdNowBeingDragged_;
  41103. repaint();
  41104. }
  41105. void TableListBox::resized()
  41106. {
  41107. ListBox::resized();
  41108. header->resizeAllColumnsToFit (getVisibleContentWidth());
  41109. setMinimumContentWidth (header->getTotalWidth());
  41110. }
  41111. void TableListBox::updateColumnComponents() const
  41112. {
  41113. const int firstRow = getRowContainingPosition (0, 0);
  41114. for (int i = firstRow + getNumRowsOnScreen() + 2; --i >= firstRow;)
  41115. {
  41116. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (i));
  41117. if (rowComp != 0)
  41118. rowComp->resized();
  41119. }
  41120. }
  41121. void TableListBoxModel::cellClicked (int, int, const MouseEvent&)
  41122. {
  41123. }
  41124. void TableListBoxModel::cellDoubleClicked (int, int, const MouseEvent&)
  41125. {
  41126. }
  41127. void TableListBoxModel::backgroundClicked()
  41128. {
  41129. }
  41130. void TableListBoxModel::sortOrderChanged (int, const bool)
  41131. {
  41132. }
  41133. int TableListBoxModel::getColumnAutoSizeWidth (int)
  41134. {
  41135. return 0;
  41136. }
  41137. void TableListBoxModel::selectedRowsChanged (int)
  41138. {
  41139. }
  41140. void TableListBoxModel::deleteKeyPressed (int)
  41141. {
  41142. }
  41143. void TableListBoxModel::returnKeyPressed (int)
  41144. {
  41145. }
  41146. void TableListBoxModel::listWasScrolled()
  41147. {
  41148. }
  41149. const String TableListBoxModel::getCellTooltip (int /*rowNumber*/, int /*columnId*/)
  41150. {
  41151. return String::empty;
  41152. }
  41153. const String TableListBoxModel::getDragSourceDescription (const SparseSet<int>&)
  41154. {
  41155. return String::empty;
  41156. }
  41157. Component* TableListBoxModel::refreshComponentForCell (int, int, bool, Component* existingComponentToUpdate)
  41158. {
  41159. (void) existingComponentToUpdate;
  41160. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  41161. return 0;
  41162. }
  41163. END_JUCE_NAMESPACE
  41164. /*** End of inlined file: juce_TableListBox.cpp ***/
  41165. /*** Start of inlined file: juce_TextEditor.cpp ***/
  41166. BEGIN_JUCE_NAMESPACE
  41167. // a word or space that can't be broken down any further
  41168. struct TextAtom
  41169. {
  41170. String atomText;
  41171. float width;
  41172. uint16 numChars;
  41173. bool isWhitespace() const { return CharacterFunctions::isWhitespace (atomText[0]); }
  41174. bool isNewLine() const { return atomText[0] == '\r' || atomText[0] == '\n'; }
  41175. const String getText (const juce_wchar passwordCharacter) const
  41176. {
  41177. if (passwordCharacter == 0)
  41178. return atomText;
  41179. else
  41180. return String::repeatedString (String::charToString (passwordCharacter),
  41181. atomText.length());
  41182. }
  41183. const String getTrimmedText (const juce_wchar passwordCharacter) const
  41184. {
  41185. if (passwordCharacter == 0)
  41186. return atomText.substring (0, numChars);
  41187. else if (isNewLine())
  41188. return String::empty;
  41189. else
  41190. return String::repeatedString (String::charToString (passwordCharacter), numChars);
  41191. }
  41192. };
  41193. // a run of text with a single font and colour
  41194. class TextEditor::UniformTextSection
  41195. {
  41196. public:
  41197. UniformTextSection (const String& text,
  41198. const Font& font_,
  41199. const Colour& colour_,
  41200. const juce_wchar passwordCharacter)
  41201. : font (font_),
  41202. colour (colour_)
  41203. {
  41204. initialiseAtoms (text, passwordCharacter);
  41205. }
  41206. UniformTextSection (const UniformTextSection& other)
  41207. : font (other.font),
  41208. colour (other.colour)
  41209. {
  41210. atoms.ensureStorageAllocated (other.atoms.size());
  41211. for (int i = 0; i < other.atoms.size(); ++i)
  41212. atoms.add (new TextAtom (*other.atoms.getUnchecked(i)));
  41213. }
  41214. ~UniformTextSection()
  41215. {
  41216. // (no need to delete the atoms, as they're explicitly deleted by the caller)
  41217. }
  41218. void clear()
  41219. {
  41220. for (int i = atoms.size(); --i >= 0;)
  41221. delete getAtom(i);
  41222. atoms.clear();
  41223. }
  41224. int getNumAtoms() const
  41225. {
  41226. return atoms.size();
  41227. }
  41228. TextAtom* getAtom (const int index) const throw()
  41229. {
  41230. return atoms.getUnchecked (index);
  41231. }
  41232. void append (const UniformTextSection& other, const juce_wchar passwordCharacter)
  41233. {
  41234. if (other.atoms.size() > 0)
  41235. {
  41236. TextAtom* const lastAtom = atoms.getLast();
  41237. int i = 0;
  41238. if (lastAtom != 0)
  41239. {
  41240. if (! CharacterFunctions::isWhitespace (lastAtom->atomText.getLastCharacter()))
  41241. {
  41242. TextAtom* const first = other.getAtom(0);
  41243. if (! CharacterFunctions::isWhitespace (first->atomText[0]))
  41244. {
  41245. lastAtom->atomText += first->atomText;
  41246. lastAtom->numChars = (uint16) (lastAtom->numChars + first->numChars);
  41247. lastAtom->width = font.getStringWidthFloat (lastAtom->getText (passwordCharacter));
  41248. delete first;
  41249. ++i;
  41250. }
  41251. }
  41252. }
  41253. atoms.ensureStorageAllocated (atoms.size() + other.atoms.size() - i);
  41254. while (i < other.atoms.size())
  41255. {
  41256. atoms.add (other.getAtom(i));
  41257. ++i;
  41258. }
  41259. }
  41260. }
  41261. UniformTextSection* split (const int indexToBreakAt,
  41262. const juce_wchar passwordCharacter)
  41263. {
  41264. UniformTextSection* const section2 = new UniformTextSection (String::empty,
  41265. font, colour,
  41266. passwordCharacter);
  41267. int index = 0;
  41268. for (int i = 0; i < atoms.size(); ++i)
  41269. {
  41270. TextAtom* const atom = getAtom(i);
  41271. const int nextIndex = index + atom->numChars;
  41272. if (index == indexToBreakAt)
  41273. {
  41274. int j;
  41275. for (j = i; j < atoms.size(); ++j)
  41276. section2->atoms.add (getAtom (j));
  41277. for (j = atoms.size(); --j >= i;)
  41278. atoms.remove (j);
  41279. break;
  41280. }
  41281. else if (indexToBreakAt >= index && indexToBreakAt < nextIndex)
  41282. {
  41283. TextAtom* const secondAtom = new TextAtom();
  41284. secondAtom->atomText = atom->atomText.substring (indexToBreakAt - index);
  41285. secondAtom->width = font.getStringWidthFloat (secondAtom->getText (passwordCharacter));
  41286. secondAtom->numChars = (uint16) secondAtom->atomText.length();
  41287. section2->atoms.add (secondAtom);
  41288. atom->atomText = atom->atomText.substring (0, indexToBreakAt - index);
  41289. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  41290. atom->numChars = (uint16) (indexToBreakAt - index);
  41291. int j;
  41292. for (j = i + 1; j < atoms.size(); ++j)
  41293. section2->atoms.add (getAtom (j));
  41294. for (j = atoms.size(); --j > i;)
  41295. atoms.remove (j);
  41296. break;
  41297. }
  41298. index = nextIndex;
  41299. }
  41300. return section2;
  41301. }
  41302. void appendAllText (String::Concatenator& concatenator) const
  41303. {
  41304. for (int i = 0; i < atoms.size(); ++i)
  41305. concatenator.append (getAtom(i)->atomText);
  41306. }
  41307. void appendSubstring (String::Concatenator& concatenator,
  41308. const Range<int>& range) const
  41309. {
  41310. int index = 0;
  41311. for (int i = 0; i < atoms.size(); ++i)
  41312. {
  41313. const TextAtom* const atom = getAtom (i);
  41314. const int nextIndex = index + atom->numChars;
  41315. if (range.getStart() < nextIndex)
  41316. {
  41317. if (range.getEnd() <= index)
  41318. break;
  41319. const Range<int> r ((range - index).getIntersectionWith (Range<int> (0, (int) atom->numChars)));
  41320. if (! r.isEmpty())
  41321. concatenator.append (atom->atomText.substring (r.getStart(), r.getEnd()));
  41322. }
  41323. index = nextIndex;
  41324. }
  41325. }
  41326. int getTotalLength() const
  41327. {
  41328. int total = 0;
  41329. for (int i = atoms.size(); --i >= 0;)
  41330. total += getAtom(i)->numChars;
  41331. return total;
  41332. }
  41333. void setFont (const Font& newFont,
  41334. const juce_wchar passwordCharacter)
  41335. {
  41336. if (font != newFont)
  41337. {
  41338. font = newFont;
  41339. for (int i = atoms.size(); --i >= 0;)
  41340. {
  41341. TextAtom* const atom = atoms.getUnchecked(i);
  41342. atom->width = newFont.getStringWidthFloat (atom->getText (passwordCharacter));
  41343. }
  41344. }
  41345. }
  41346. juce_UseDebuggingNewOperator
  41347. Font font;
  41348. Colour colour;
  41349. private:
  41350. Array <TextAtom*> atoms;
  41351. void initialiseAtoms (const String& textToParse,
  41352. const juce_wchar passwordCharacter)
  41353. {
  41354. int i = 0;
  41355. const int len = textToParse.length();
  41356. const juce_wchar* const text = textToParse;
  41357. while (i < len)
  41358. {
  41359. int start = i;
  41360. // create a whitespace atom unless it starts with non-ws
  41361. if (CharacterFunctions::isWhitespace (text[i])
  41362. && text[i] != '\r'
  41363. && text[i] != '\n')
  41364. {
  41365. while (i < len
  41366. && CharacterFunctions::isWhitespace (text[i])
  41367. && text[i] != '\r'
  41368. && text[i] != '\n')
  41369. {
  41370. ++i;
  41371. }
  41372. }
  41373. else
  41374. {
  41375. if (text[i] == '\r')
  41376. {
  41377. ++i;
  41378. if ((i < len) && (text[i] == '\n'))
  41379. {
  41380. ++start;
  41381. ++i;
  41382. }
  41383. }
  41384. else if (text[i] == '\n')
  41385. {
  41386. ++i;
  41387. }
  41388. else
  41389. {
  41390. while ((i < len) && ! CharacterFunctions::isWhitespace (text[i]))
  41391. ++i;
  41392. }
  41393. }
  41394. TextAtom* const atom = new TextAtom();
  41395. atom->atomText = String (text + start, i - start);
  41396. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  41397. atom->numChars = (uint16) (i - start);
  41398. atoms.add (atom);
  41399. }
  41400. }
  41401. UniformTextSection& operator= (const UniformTextSection& other);
  41402. };
  41403. class TextEditor::Iterator
  41404. {
  41405. public:
  41406. Iterator (const Array <UniformTextSection*>& sections_,
  41407. const float wordWrapWidth_,
  41408. const juce_wchar passwordCharacter_)
  41409. : indexInText (0),
  41410. lineY (0),
  41411. lineHeight (0),
  41412. maxDescent (0),
  41413. atomX (0),
  41414. atomRight (0),
  41415. atom (0),
  41416. currentSection (0),
  41417. sections (sections_),
  41418. sectionIndex (0),
  41419. atomIndex (0),
  41420. wordWrapWidth (wordWrapWidth_),
  41421. passwordCharacter (passwordCharacter_)
  41422. {
  41423. jassert (wordWrapWidth_ > 0);
  41424. if (sections.size() > 0)
  41425. {
  41426. currentSection = sections.getUnchecked (sectionIndex);
  41427. if (currentSection != 0)
  41428. beginNewLine();
  41429. }
  41430. }
  41431. Iterator (const Iterator& other)
  41432. : indexInText (other.indexInText),
  41433. lineY (other.lineY),
  41434. lineHeight (other.lineHeight),
  41435. maxDescent (other.maxDescent),
  41436. atomX (other.atomX),
  41437. atomRight (other.atomRight),
  41438. atom (other.atom),
  41439. currentSection (other.currentSection),
  41440. sections (other.sections),
  41441. sectionIndex (other.sectionIndex),
  41442. atomIndex (other.atomIndex),
  41443. wordWrapWidth (other.wordWrapWidth),
  41444. passwordCharacter (other.passwordCharacter),
  41445. tempAtom (other.tempAtom)
  41446. {
  41447. }
  41448. ~Iterator()
  41449. {
  41450. }
  41451. bool next()
  41452. {
  41453. if (atom == &tempAtom)
  41454. {
  41455. const int numRemaining = tempAtom.atomText.length() - tempAtom.numChars;
  41456. if (numRemaining > 0)
  41457. {
  41458. tempAtom.atomText = tempAtom.atomText.substring (tempAtom.numChars);
  41459. atomX = 0;
  41460. if (tempAtom.numChars > 0)
  41461. lineY += lineHeight;
  41462. indexInText += tempAtom.numChars;
  41463. GlyphArrangement g;
  41464. g.addLineOfText (currentSection->font, atom->getText (passwordCharacter), 0.0f, 0.0f);
  41465. int split;
  41466. for (split = 0; split < g.getNumGlyphs(); ++split)
  41467. if (shouldWrap (g.getGlyph (split).getRight()))
  41468. break;
  41469. if (split > 0 && split <= numRemaining)
  41470. {
  41471. tempAtom.numChars = (uint16) split;
  41472. tempAtom.width = g.getGlyph (split - 1).getRight();
  41473. atomRight = atomX + tempAtom.width;
  41474. return true;
  41475. }
  41476. }
  41477. }
  41478. bool forceNewLine = false;
  41479. if (sectionIndex >= sections.size())
  41480. {
  41481. moveToEndOfLastAtom();
  41482. return false;
  41483. }
  41484. else if (atomIndex >= currentSection->getNumAtoms() - 1)
  41485. {
  41486. if (atomIndex >= currentSection->getNumAtoms())
  41487. {
  41488. if (++sectionIndex >= sections.size())
  41489. {
  41490. moveToEndOfLastAtom();
  41491. return false;
  41492. }
  41493. atomIndex = 0;
  41494. currentSection = sections.getUnchecked (sectionIndex);
  41495. }
  41496. else
  41497. {
  41498. const TextAtom* const lastAtom = currentSection->getAtom (atomIndex);
  41499. if (! lastAtom->isWhitespace())
  41500. {
  41501. // handle the case where the last atom in a section is actually part of the same
  41502. // word as the first atom of the next section...
  41503. float right = atomRight + lastAtom->width;
  41504. float lineHeight2 = lineHeight;
  41505. float maxDescent2 = maxDescent;
  41506. for (int section = sectionIndex + 1; section < sections.size(); ++section)
  41507. {
  41508. const UniformTextSection* const s = sections.getUnchecked (section);
  41509. if (s->getNumAtoms() == 0)
  41510. break;
  41511. const TextAtom* const nextAtom = s->getAtom (0);
  41512. if (nextAtom->isWhitespace())
  41513. break;
  41514. right += nextAtom->width;
  41515. lineHeight2 = jmax (lineHeight2, s->font.getHeight());
  41516. maxDescent2 = jmax (maxDescent2, s->font.getDescent());
  41517. if (shouldWrap (right))
  41518. {
  41519. lineHeight = lineHeight2;
  41520. maxDescent = maxDescent2;
  41521. forceNewLine = true;
  41522. break;
  41523. }
  41524. if (s->getNumAtoms() > 1)
  41525. break;
  41526. }
  41527. }
  41528. }
  41529. }
  41530. if (atom != 0)
  41531. {
  41532. atomX = atomRight;
  41533. indexInText += atom->numChars;
  41534. if (atom->isNewLine())
  41535. beginNewLine();
  41536. }
  41537. atom = currentSection->getAtom (atomIndex);
  41538. atomRight = atomX + atom->width;
  41539. ++atomIndex;
  41540. if (shouldWrap (atomRight) || forceNewLine)
  41541. {
  41542. if (atom->isWhitespace())
  41543. {
  41544. // leave whitespace at the end of a line, but truncate it to avoid scrolling
  41545. atomRight = jmin (atomRight, wordWrapWidth);
  41546. }
  41547. else
  41548. {
  41549. atomRight = atom->width;
  41550. if (shouldWrap (atomRight)) // atom too big to fit on a line, so break it up..
  41551. {
  41552. tempAtom = *atom;
  41553. tempAtom.width = 0;
  41554. tempAtom.numChars = 0;
  41555. atom = &tempAtom;
  41556. if (atomX > 0)
  41557. beginNewLine();
  41558. return next();
  41559. }
  41560. beginNewLine();
  41561. return true;
  41562. }
  41563. }
  41564. return true;
  41565. }
  41566. void beginNewLine()
  41567. {
  41568. atomX = 0;
  41569. lineY += lineHeight;
  41570. int tempSectionIndex = sectionIndex;
  41571. int tempAtomIndex = atomIndex;
  41572. const UniformTextSection* section = sections.getUnchecked (tempSectionIndex);
  41573. lineHeight = section->font.getHeight();
  41574. maxDescent = section->font.getDescent();
  41575. float x = (atom != 0) ? atom->width : 0;
  41576. while (! shouldWrap (x))
  41577. {
  41578. if (tempSectionIndex >= sections.size())
  41579. break;
  41580. bool checkSize = false;
  41581. if (tempAtomIndex >= section->getNumAtoms())
  41582. {
  41583. if (++tempSectionIndex >= sections.size())
  41584. break;
  41585. tempAtomIndex = 0;
  41586. section = sections.getUnchecked (tempSectionIndex);
  41587. checkSize = true;
  41588. }
  41589. const TextAtom* const nextAtom = section->getAtom (tempAtomIndex);
  41590. if (nextAtom == 0)
  41591. break;
  41592. x += nextAtom->width;
  41593. if (shouldWrap (x) || nextAtom->isNewLine())
  41594. break;
  41595. if (checkSize)
  41596. {
  41597. lineHeight = jmax (lineHeight, section->font.getHeight());
  41598. maxDescent = jmax (maxDescent, section->font.getDescent());
  41599. }
  41600. ++tempAtomIndex;
  41601. }
  41602. }
  41603. void draw (Graphics& g, const UniformTextSection*& lastSection) const
  41604. {
  41605. if (passwordCharacter != 0 || ! atom->isWhitespace())
  41606. {
  41607. if (lastSection != currentSection)
  41608. {
  41609. lastSection = currentSection;
  41610. g.setColour (currentSection->colour);
  41611. g.setFont (currentSection->font);
  41612. }
  41613. jassert (atom->getTrimmedText (passwordCharacter).isNotEmpty());
  41614. GlyphArrangement ga;
  41615. ga.addLineOfText (currentSection->font,
  41616. atom->getTrimmedText (passwordCharacter),
  41617. atomX,
  41618. (float) roundToInt (lineY + lineHeight - maxDescent));
  41619. ga.draw (g);
  41620. }
  41621. }
  41622. void drawSelection (Graphics& g,
  41623. const Range<int>& selection) const
  41624. {
  41625. const int startX = roundToInt (indexToX (selection.getStart()));
  41626. const int endX = roundToInt (indexToX (selection.getEnd()));
  41627. const int y = roundToInt (lineY);
  41628. const int nextY = roundToInt (lineY + lineHeight);
  41629. g.fillRect (startX, y, endX - startX, nextY - y);
  41630. }
  41631. void drawSelectedText (Graphics& g,
  41632. const Range<int>& selection,
  41633. const Colour& selectedTextColour) const
  41634. {
  41635. if (passwordCharacter != 0 || ! atom->isWhitespace())
  41636. {
  41637. GlyphArrangement ga;
  41638. ga.addLineOfText (currentSection->font,
  41639. atom->getTrimmedText (passwordCharacter),
  41640. atomX,
  41641. (float) roundToInt (lineY + lineHeight - maxDescent));
  41642. if (selection.getEnd() < indexInText + atom->numChars)
  41643. {
  41644. GlyphArrangement ga2 (ga);
  41645. ga2.removeRangeOfGlyphs (0, selection.getEnd() - indexInText);
  41646. ga.removeRangeOfGlyphs (selection.getEnd() - indexInText, -1);
  41647. g.setColour (currentSection->colour);
  41648. ga2.draw (g);
  41649. }
  41650. if (selection.getStart() > indexInText)
  41651. {
  41652. GlyphArrangement ga2 (ga);
  41653. ga2.removeRangeOfGlyphs (selection.getStart() - indexInText, -1);
  41654. ga.removeRangeOfGlyphs (0, selection.getStart() - indexInText);
  41655. g.setColour (currentSection->colour);
  41656. ga2.draw (g);
  41657. }
  41658. g.setColour (selectedTextColour);
  41659. ga.draw (g);
  41660. }
  41661. }
  41662. float indexToX (const int indexToFind) const
  41663. {
  41664. if (indexToFind <= indexInText)
  41665. return atomX;
  41666. if (indexToFind >= indexInText + atom->numChars)
  41667. return atomRight;
  41668. GlyphArrangement g;
  41669. g.addLineOfText (currentSection->font,
  41670. atom->getText (passwordCharacter),
  41671. atomX, 0.0f);
  41672. if (indexToFind - indexInText >= g.getNumGlyphs())
  41673. return atomRight;
  41674. return jmin (atomRight, g.getGlyph (indexToFind - indexInText).getLeft());
  41675. }
  41676. int xToIndex (const float xToFind) const
  41677. {
  41678. if (xToFind <= atomX || atom->isNewLine())
  41679. return indexInText;
  41680. if (xToFind >= atomRight)
  41681. return indexInText + atom->numChars;
  41682. GlyphArrangement g;
  41683. g.addLineOfText (currentSection->font,
  41684. atom->getText (passwordCharacter),
  41685. atomX, 0.0f);
  41686. int j;
  41687. for (j = 0; j < g.getNumGlyphs(); ++j)
  41688. if ((g.getGlyph(j).getLeft() + g.getGlyph(j).getRight()) / 2 > xToFind)
  41689. break;
  41690. return indexInText + j;
  41691. }
  41692. bool getCharPosition (const int index, float& cx, float& cy, float& lineHeight_)
  41693. {
  41694. while (next())
  41695. {
  41696. if (indexInText + atom->numChars > index)
  41697. {
  41698. cx = indexToX (index);
  41699. cy = lineY;
  41700. lineHeight_ = lineHeight;
  41701. return true;
  41702. }
  41703. }
  41704. cx = atomX;
  41705. cy = lineY;
  41706. lineHeight_ = lineHeight;
  41707. return false;
  41708. }
  41709. juce_UseDebuggingNewOperator
  41710. int indexInText;
  41711. float lineY, lineHeight, maxDescent;
  41712. float atomX, atomRight;
  41713. const TextAtom* atom;
  41714. const UniformTextSection* currentSection;
  41715. private:
  41716. const Array <UniformTextSection*>& sections;
  41717. int sectionIndex, atomIndex;
  41718. const float wordWrapWidth;
  41719. const juce_wchar passwordCharacter;
  41720. TextAtom tempAtom;
  41721. Iterator& operator= (const Iterator&);
  41722. void moveToEndOfLastAtom()
  41723. {
  41724. if (atom != 0)
  41725. {
  41726. atomX = atomRight;
  41727. if (atom->isNewLine())
  41728. {
  41729. atomX = 0.0f;
  41730. lineY += lineHeight;
  41731. }
  41732. }
  41733. }
  41734. bool shouldWrap (const float x) const
  41735. {
  41736. return (x - 0.0001f) >= wordWrapWidth;
  41737. }
  41738. };
  41739. class TextEditor::InsertAction : public UndoableAction
  41740. {
  41741. TextEditor& owner;
  41742. const String text;
  41743. const int insertIndex, oldCaretPos, newCaretPos;
  41744. const Font font;
  41745. const Colour colour;
  41746. InsertAction (const InsertAction&);
  41747. InsertAction& operator= (const InsertAction&);
  41748. public:
  41749. InsertAction (TextEditor& owner_,
  41750. const String& text_,
  41751. const int insertIndex_,
  41752. const Font& font_,
  41753. const Colour& colour_,
  41754. const int oldCaretPos_,
  41755. const int newCaretPos_)
  41756. : owner (owner_),
  41757. text (text_),
  41758. insertIndex (insertIndex_),
  41759. oldCaretPos (oldCaretPos_),
  41760. newCaretPos (newCaretPos_),
  41761. font (font_),
  41762. colour (colour_)
  41763. {
  41764. }
  41765. ~InsertAction()
  41766. {
  41767. }
  41768. bool perform()
  41769. {
  41770. owner.insert (text, insertIndex, font, colour, 0, newCaretPos);
  41771. return true;
  41772. }
  41773. bool undo()
  41774. {
  41775. owner.remove (Range<int> (insertIndex, insertIndex + text.length()), 0, oldCaretPos);
  41776. return true;
  41777. }
  41778. int getSizeInUnits()
  41779. {
  41780. return text.length() + 16;
  41781. }
  41782. };
  41783. class TextEditor::RemoveAction : public UndoableAction
  41784. {
  41785. TextEditor& owner;
  41786. const Range<int> range;
  41787. const int oldCaretPos, newCaretPos;
  41788. Array <UniformTextSection*> removedSections;
  41789. RemoveAction (const RemoveAction&);
  41790. RemoveAction& operator= (const RemoveAction&);
  41791. public:
  41792. RemoveAction (TextEditor& owner_,
  41793. const Range<int> range_,
  41794. const int oldCaretPos_,
  41795. const int newCaretPos_,
  41796. const Array <UniformTextSection*>& removedSections_)
  41797. : owner (owner_),
  41798. range (range_),
  41799. oldCaretPos (oldCaretPos_),
  41800. newCaretPos (newCaretPos_),
  41801. removedSections (removedSections_)
  41802. {
  41803. }
  41804. ~RemoveAction()
  41805. {
  41806. for (int i = removedSections.size(); --i >= 0;)
  41807. {
  41808. UniformTextSection* const section = removedSections.getUnchecked (i);
  41809. section->clear();
  41810. delete section;
  41811. }
  41812. }
  41813. bool perform()
  41814. {
  41815. owner.remove (range, 0, newCaretPos);
  41816. return true;
  41817. }
  41818. bool undo()
  41819. {
  41820. owner.reinsert (range.getStart(), removedSections);
  41821. owner.moveCursorTo (oldCaretPos, false);
  41822. return true;
  41823. }
  41824. int getSizeInUnits()
  41825. {
  41826. int n = 0;
  41827. for (int i = removedSections.size(); --i >= 0;)
  41828. n += removedSections.getUnchecked (i)->getTotalLength();
  41829. return n + 16;
  41830. }
  41831. };
  41832. class TextEditor::TextHolderComponent : public Component,
  41833. public Timer,
  41834. public Value::Listener
  41835. {
  41836. public:
  41837. TextHolderComponent (TextEditor& owner_)
  41838. : owner (owner_)
  41839. {
  41840. setWantsKeyboardFocus (false);
  41841. setInterceptsMouseClicks (false, true);
  41842. owner.getTextValue().addListener (this);
  41843. }
  41844. ~TextHolderComponent()
  41845. {
  41846. owner.getTextValue().removeListener (this);
  41847. }
  41848. void paint (Graphics& g)
  41849. {
  41850. owner.drawContent (g);
  41851. }
  41852. void timerCallback()
  41853. {
  41854. owner.timerCallbackInt();
  41855. }
  41856. const MouseCursor getMouseCursor()
  41857. {
  41858. return owner.getMouseCursor();
  41859. }
  41860. void valueChanged (Value&)
  41861. {
  41862. owner.textWasChangedByValue();
  41863. }
  41864. private:
  41865. TextEditor& owner;
  41866. TextHolderComponent (const TextHolderComponent&);
  41867. TextHolderComponent& operator= (const TextHolderComponent&);
  41868. };
  41869. class TextEditorViewport : public Viewport
  41870. {
  41871. public:
  41872. TextEditorViewport (TextEditor* const owner_)
  41873. : owner (owner_), lastWordWrapWidth (0), rentrant (false)
  41874. {
  41875. }
  41876. ~TextEditorViewport()
  41877. {
  41878. }
  41879. void visibleAreaChanged (int, int, int, int)
  41880. {
  41881. if (! rentrant) // it's rare, but possible to get into a feedback loop as the viewport's scrollbars
  41882. // appear and disappear, causing the wrap width to change.
  41883. {
  41884. const float wordWrapWidth = owner->getWordWrapWidth();
  41885. if (wordWrapWidth != lastWordWrapWidth)
  41886. {
  41887. lastWordWrapWidth = wordWrapWidth;
  41888. rentrant = true;
  41889. owner->updateTextHolderSize();
  41890. rentrant = false;
  41891. }
  41892. }
  41893. }
  41894. private:
  41895. TextEditor* const owner;
  41896. float lastWordWrapWidth;
  41897. bool rentrant;
  41898. TextEditorViewport (const TextEditorViewport&);
  41899. TextEditorViewport& operator= (const TextEditorViewport&);
  41900. };
  41901. namespace TextEditorDefs
  41902. {
  41903. const int flashSpeedIntervalMs = 380;
  41904. const int textChangeMessageId = 0x10003001;
  41905. const int returnKeyMessageId = 0x10003002;
  41906. const int escapeKeyMessageId = 0x10003003;
  41907. const int focusLossMessageId = 0x10003004;
  41908. const int maxActionsPerTransaction = 100;
  41909. }
  41910. TextEditor::TextEditor (const String& name,
  41911. const juce_wchar passwordCharacter_)
  41912. : Component (name),
  41913. borderSize (1, 1, 1, 3),
  41914. readOnly (false),
  41915. multiline (false),
  41916. wordWrap (false),
  41917. returnKeyStartsNewLine (false),
  41918. caretVisible (true),
  41919. popupMenuEnabled (true),
  41920. selectAllTextWhenFocused (false),
  41921. scrollbarVisible (true),
  41922. wasFocused (false),
  41923. caretFlashState (true),
  41924. keepCursorOnScreen (true),
  41925. tabKeyUsed (false),
  41926. menuActive (false),
  41927. valueTextNeedsUpdating (false),
  41928. cursorX (0),
  41929. cursorY (0),
  41930. cursorHeight (0),
  41931. maxTextLength (0),
  41932. leftIndent (4),
  41933. topIndent (4),
  41934. lastTransactionTime (0),
  41935. currentFont (14.0f),
  41936. totalNumChars (0),
  41937. caretPosition (0),
  41938. passwordCharacter (passwordCharacter_),
  41939. dragType (notDragging)
  41940. {
  41941. setOpaque (true);
  41942. addAndMakeVisible (viewport = new TextEditorViewport (this));
  41943. viewport->setViewedComponent (textHolder = new TextHolderComponent (*this));
  41944. viewport->setWantsKeyboardFocus (false);
  41945. viewport->setScrollBarsShown (false, false);
  41946. setMouseCursor (MouseCursor::IBeamCursor);
  41947. setWantsKeyboardFocus (true);
  41948. }
  41949. TextEditor::~TextEditor()
  41950. {
  41951. textValue.referTo (Value());
  41952. clearInternal (0);
  41953. viewport = 0;
  41954. textHolder = 0;
  41955. }
  41956. void TextEditor::newTransaction()
  41957. {
  41958. lastTransactionTime = Time::getApproximateMillisecondCounter();
  41959. undoManager.beginNewTransaction();
  41960. }
  41961. void TextEditor::doUndoRedo (const bool isRedo)
  41962. {
  41963. if (! isReadOnly())
  41964. {
  41965. if (isRedo ? undoManager.redo()
  41966. : undoManager.undo())
  41967. {
  41968. scrollToMakeSureCursorIsVisible();
  41969. repaint();
  41970. textChanged();
  41971. }
  41972. }
  41973. }
  41974. void TextEditor::setMultiLine (const bool shouldBeMultiLine,
  41975. const bool shouldWordWrap)
  41976. {
  41977. if (multiline != shouldBeMultiLine
  41978. || wordWrap != (shouldWordWrap && shouldBeMultiLine))
  41979. {
  41980. multiline = shouldBeMultiLine;
  41981. wordWrap = shouldWordWrap && shouldBeMultiLine;
  41982. viewport->setScrollBarsShown (scrollbarVisible && multiline,
  41983. scrollbarVisible && multiline);
  41984. viewport->setViewPosition (0, 0);
  41985. resized();
  41986. scrollToMakeSureCursorIsVisible();
  41987. }
  41988. }
  41989. bool TextEditor::isMultiLine() const
  41990. {
  41991. return multiline;
  41992. }
  41993. void TextEditor::setScrollbarsShown (bool shown)
  41994. {
  41995. if (scrollbarVisible != shown)
  41996. {
  41997. scrollbarVisible = shown;
  41998. shown = shown && isMultiLine();
  41999. viewport->setScrollBarsShown (shown, shown);
  42000. }
  42001. }
  42002. void TextEditor::setReadOnly (const bool shouldBeReadOnly)
  42003. {
  42004. if (readOnly != shouldBeReadOnly)
  42005. {
  42006. readOnly = shouldBeReadOnly;
  42007. enablementChanged();
  42008. }
  42009. }
  42010. bool TextEditor::isReadOnly() const
  42011. {
  42012. return readOnly || ! isEnabled();
  42013. }
  42014. bool TextEditor::isTextInputActive() const
  42015. {
  42016. return ! isReadOnly();
  42017. }
  42018. void TextEditor::setReturnKeyStartsNewLine (const bool shouldStartNewLine)
  42019. {
  42020. returnKeyStartsNewLine = shouldStartNewLine;
  42021. }
  42022. void TextEditor::setTabKeyUsedAsCharacter (const bool shouldTabKeyBeUsed)
  42023. {
  42024. tabKeyUsed = shouldTabKeyBeUsed;
  42025. }
  42026. void TextEditor::setPopupMenuEnabled (const bool b)
  42027. {
  42028. popupMenuEnabled = b;
  42029. }
  42030. void TextEditor::setSelectAllWhenFocused (const bool b)
  42031. {
  42032. selectAllTextWhenFocused = b;
  42033. }
  42034. const Font TextEditor::getFont() const
  42035. {
  42036. return currentFont;
  42037. }
  42038. void TextEditor::setFont (const Font& newFont)
  42039. {
  42040. currentFont = newFont;
  42041. scrollToMakeSureCursorIsVisible();
  42042. }
  42043. void TextEditor::applyFontToAllText (const Font& newFont)
  42044. {
  42045. currentFont = newFont;
  42046. const Colour overallColour (findColour (textColourId));
  42047. for (int i = sections.size(); --i >= 0;)
  42048. {
  42049. UniformTextSection* const uts = sections.getUnchecked (i);
  42050. uts->setFont (newFont, passwordCharacter);
  42051. uts->colour = overallColour;
  42052. }
  42053. coalesceSimilarSections();
  42054. updateTextHolderSize();
  42055. scrollToMakeSureCursorIsVisible();
  42056. repaint();
  42057. }
  42058. void TextEditor::colourChanged()
  42059. {
  42060. setOpaque (findColour (backgroundColourId).isOpaque());
  42061. repaint();
  42062. }
  42063. void TextEditor::setCaretVisible (const bool shouldCaretBeVisible)
  42064. {
  42065. caretVisible = shouldCaretBeVisible;
  42066. if (shouldCaretBeVisible)
  42067. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  42068. setMouseCursor (shouldCaretBeVisible ? MouseCursor::IBeamCursor
  42069. : MouseCursor::NormalCursor);
  42070. }
  42071. void TextEditor::setInputRestrictions (const int maxLen,
  42072. const String& chars)
  42073. {
  42074. maxTextLength = jmax (0, maxLen);
  42075. allowedCharacters = chars;
  42076. }
  42077. void TextEditor::setTextToShowWhenEmpty (const String& text, const Colour& colourToUse)
  42078. {
  42079. textToShowWhenEmpty = text;
  42080. colourForTextWhenEmpty = colourToUse;
  42081. }
  42082. void TextEditor::setPasswordCharacter (const juce_wchar newPasswordCharacter)
  42083. {
  42084. if (passwordCharacter != newPasswordCharacter)
  42085. {
  42086. passwordCharacter = newPasswordCharacter;
  42087. resized();
  42088. repaint();
  42089. }
  42090. }
  42091. void TextEditor::setScrollBarThickness (const int newThicknessPixels)
  42092. {
  42093. viewport->setScrollBarThickness (newThicknessPixels);
  42094. }
  42095. void TextEditor::setScrollBarButtonVisibility (const bool buttonsVisible)
  42096. {
  42097. viewport->setScrollBarButtonVisibility (buttonsVisible);
  42098. }
  42099. void TextEditor::clear()
  42100. {
  42101. clearInternal (0);
  42102. updateTextHolderSize();
  42103. undoManager.clearUndoHistory();
  42104. }
  42105. void TextEditor::setText (const String& newText,
  42106. const bool sendTextChangeMessage)
  42107. {
  42108. const int newLength = newText.length();
  42109. if (newLength != getTotalNumChars() || getText() != newText)
  42110. {
  42111. const int oldCursorPos = caretPosition;
  42112. const bool cursorWasAtEnd = oldCursorPos >= getTotalNumChars();
  42113. clearInternal (0);
  42114. insert (newText, 0, currentFont, findColour (textColourId), 0, caretPosition);
  42115. // if you're adding text with line-feeds to a single-line text editor, it
  42116. // ain't gonna look right!
  42117. jassert (multiline || ! newText.containsAnyOf ("\r\n"));
  42118. if (cursorWasAtEnd && ! isMultiLine())
  42119. moveCursorTo (getTotalNumChars(), false);
  42120. else
  42121. moveCursorTo (oldCursorPos, false);
  42122. if (sendTextChangeMessage)
  42123. textChanged();
  42124. updateTextHolderSize();
  42125. scrollToMakeSureCursorIsVisible();
  42126. undoManager.clearUndoHistory();
  42127. repaint();
  42128. }
  42129. }
  42130. Value& TextEditor::getTextValue()
  42131. {
  42132. if (valueTextNeedsUpdating)
  42133. {
  42134. valueTextNeedsUpdating = false;
  42135. textValue = getText();
  42136. }
  42137. return textValue;
  42138. }
  42139. void TextEditor::textWasChangedByValue()
  42140. {
  42141. if (textValue.getValueSource().getReferenceCount() > 1)
  42142. setText (textValue.getValue());
  42143. }
  42144. void TextEditor::textChanged()
  42145. {
  42146. updateTextHolderSize();
  42147. postCommandMessage (TextEditorDefs::textChangeMessageId);
  42148. if (textValue.getValueSource().getReferenceCount() > 1)
  42149. {
  42150. valueTextNeedsUpdating = false;
  42151. textValue = getText();
  42152. }
  42153. }
  42154. void TextEditor::returnPressed()
  42155. {
  42156. postCommandMessage (TextEditorDefs::returnKeyMessageId);
  42157. }
  42158. void TextEditor::escapePressed()
  42159. {
  42160. postCommandMessage (TextEditorDefs::escapeKeyMessageId);
  42161. }
  42162. void TextEditor::addListener (TextEditorListener* const newListener)
  42163. {
  42164. listeners.add (newListener);
  42165. }
  42166. void TextEditor::removeListener (TextEditorListener* const listenerToRemove)
  42167. {
  42168. listeners.remove (listenerToRemove);
  42169. }
  42170. void TextEditor::timerCallbackInt()
  42171. {
  42172. const bool newState = (! caretFlashState) && ! isCurrentlyBlockedByAnotherModalComponent();
  42173. if (caretFlashState != newState)
  42174. {
  42175. caretFlashState = newState;
  42176. if (caretFlashState)
  42177. wasFocused = true;
  42178. if (caretVisible
  42179. && hasKeyboardFocus (false)
  42180. && ! isReadOnly())
  42181. {
  42182. repaintCaret();
  42183. }
  42184. }
  42185. const unsigned int now = Time::getApproximateMillisecondCounter();
  42186. if (now > lastTransactionTime + 200)
  42187. newTransaction();
  42188. }
  42189. void TextEditor::repaintCaret()
  42190. {
  42191. if (! findColour (caretColourId).isTransparent())
  42192. repaint (borderSize.getLeft() + textHolder->getX() + leftIndent + roundToInt (cursorX) - 1,
  42193. borderSize.getTop() + textHolder->getY() + topIndent + roundToInt (cursorY) - 1,
  42194. 4,
  42195. roundToInt (cursorHeight) + 2);
  42196. }
  42197. void TextEditor::repaintText (const Range<int>& range)
  42198. {
  42199. if (! range.isEmpty())
  42200. {
  42201. float x = 0, y = 0, lh = currentFont.getHeight();
  42202. const float wordWrapWidth = getWordWrapWidth();
  42203. if (wordWrapWidth > 0)
  42204. {
  42205. Iterator i (sections, wordWrapWidth, passwordCharacter);
  42206. i.getCharPosition (range.getStart(), x, y, lh);
  42207. const int y1 = (int) y;
  42208. int y2;
  42209. if (range.getEnd() >= getTotalNumChars())
  42210. {
  42211. y2 = textHolder->getHeight();
  42212. }
  42213. else
  42214. {
  42215. i.getCharPosition (range.getEnd(), x, y, lh);
  42216. y2 = (int) (y + lh * 2.0f);
  42217. }
  42218. textHolder->repaint (0, y1, textHolder->getWidth(), y2 - y1);
  42219. }
  42220. }
  42221. }
  42222. void TextEditor::moveCaret (int newCaretPos)
  42223. {
  42224. if (newCaretPos < 0)
  42225. newCaretPos = 0;
  42226. else if (newCaretPos > getTotalNumChars())
  42227. newCaretPos = getTotalNumChars();
  42228. if (newCaretPos != getCaretPosition())
  42229. {
  42230. repaintCaret();
  42231. caretFlashState = true;
  42232. caretPosition = newCaretPos;
  42233. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  42234. scrollToMakeSureCursorIsVisible();
  42235. repaintCaret();
  42236. }
  42237. }
  42238. void TextEditor::setCaretPosition (const int newIndex)
  42239. {
  42240. moveCursorTo (newIndex, false);
  42241. }
  42242. int TextEditor::getCaretPosition() const
  42243. {
  42244. return caretPosition;
  42245. }
  42246. void TextEditor::scrollEditorToPositionCaret (const int desiredCaretX,
  42247. const int desiredCaretY)
  42248. {
  42249. updateCaretPosition();
  42250. int vx = roundToInt (cursorX) - desiredCaretX;
  42251. int vy = roundToInt (cursorY) - desiredCaretY;
  42252. if (desiredCaretX < jmax (1, proportionOfWidth (0.05f)))
  42253. {
  42254. vx += desiredCaretX - proportionOfWidth (0.2f);
  42255. }
  42256. else if (desiredCaretX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  42257. {
  42258. vx += desiredCaretX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  42259. }
  42260. vx = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), vx);
  42261. if (! isMultiLine())
  42262. {
  42263. vy = viewport->getViewPositionY();
  42264. }
  42265. else
  42266. {
  42267. vy = jlimit (0, jmax (0, textHolder->getHeight() - viewport->getMaximumVisibleHeight()), vy);
  42268. const int curH = roundToInt (cursorHeight);
  42269. if (desiredCaretY < 0)
  42270. {
  42271. vy = jmax (0, desiredCaretY + vy);
  42272. }
  42273. else if (desiredCaretY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  42274. {
  42275. vy += desiredCaretY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  42276. }
  42277. }
  42278. viewport->setViewPosition (vx, vy);
  42279. }
  42280. const Rectangle<int> TextEditor::getCaretRectangle()
  42281. {
  42282. updateCaretPosition();
  42283. return Rectangle<int> (roundToInt (cursorX) - viewport->getX(),
  42284. roundToInt (cursorY) - viewport->getY(),
  42285. 1, roundToInt (cursorHeight));
  42286. }
  42287. float TextEditor::getWordWrapWidth() const
  42288. {
  42289. return (wordWrap) ? (float) (viewport->getMaximumVisibleWidth() - leftIndent - leftIndent / 2)
  42290. : 1.0e10f;
  42291. }
  42292. void TextEditor::updateTextHolderSize()
  42293. {
  42294. const float wordWrapWidth = getWordWrapWidth();
  42295. if (wordWrapWidth > 0)
  42296. {
  42297. float maxWidth = 0.0f;
  42298. Iterator i (sections, wordWrapWidth, passwordCharacter);
  42299. while (i.next())
  42300. maxWidth = jmax (maxWidth, i.atomRight);
  42301. const int w = leftIndent + roundToInt (maxWidth);
  42302. const int h = topIndent + roundToInt (jmax (i.lineY + i.lineHeight,
  42303. currentFont.getHeight()));
  42304. textHolder->setSize (w + 1, h + 1);
  42305. }
  42306. }
  42307. int TextEditor::getTextWidth() const
  42308. {
  42309. return textHolder->getWidth();
  42310. }
  42311. int TextEditor::getTextHeight() const
  42312. {
  42313. return textHolder->getHeight();
  42314. }
  42315. void TextEditor::setIndents (const int newLeftIndent,
  42316. const int newTopIndent)
  42317. {
  42318. leftIndent = newLeftIndent;
  42319. topIndent = newTopIndent;
  42320. }
  42321. void TextEditor::setBorder (const BorderSize& border)
  42322. {
  42323. borderSize = border;
  42324. resized();
  42325. }
  42326. const BorderSize TextEditor::getBorder() const
  42327. {
  42328. return borderSize;
  42329. }
  42330. void TextEditor::setScrollToShowCursor (const bool shouldScrollToShowCursor)
  42331. {
  42332. keepCursorOnScreen = shouldScrollToShowCursor;
  42333. }
  42334. void TextEditor::updateCaretPosition()
  42335. {
  42336. cursorHeight = currentFont.getHeight(); // (in case the text is empty and the call below doesn't set this value)
  42337. getCharPosition (caretPosition, cursorX, cursorY, cursorHeight);
  42338. }
  42339. void TextEditor::scrollToMakeSureCursorIsVisible()
  42340. {
  42341. updateCaretPosition();
  42342. if (keepCursorOnScreen)
  42343. {
  42344. int x = viewport->getViewPositionX();
  42345. int y = viewport->getViewPositionY();
  42346. const int relativeCursorX = roundToInt (cursorX) - x;
  42347. const int relativeCursorY = roundToInt (cursorY) - y;
  42348. if (relativeCursorX < jmax (1, proportionOfWidth (0.05f)))
  42349. {
  42350. x += relativeCursorX - proportionOfWidth (0.2f);
  42351. }
  42352. else if (relativeCursorX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  42353. {
  42354. x += relativeCursorX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  42355. }
  42356. x = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), x);
  42357. if (! isMultiLine())
  42358. {
  42359. y = (getHeight() - textHolder->getHeight() - topIndent) / -2;
  42360. }
  42361. else
  42362. {
  42363. const int curH = roundToInt (cursorHeight);
  42364. if (relativeCursorY < 0)
  42365. {
  42366. y = jmax (0, relativeCursorY + y);
  42367. }
  42368. else if (relativeCursorY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  42369. {
  42370. y += relativeCursorY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  42371. }
  42372. }
  42373. viewport->setViewPosition (x, y);
  42374. }
  42375. }
  42376. void TextEditor::moveCursorTo (const int newPosition,
  42377. const bool isSelecting)
  42378. {
  42379. if (isSelecting)
  42380. {
  42381. moveCaret (newPosition);
  42382. const Range<int> oldSelection (selection);
  42383. if (dragType == notDragging)
  42384. {
  42385. if (abs (getCaretPosition() - selection.getStart()) < abs (getCaretPosition() - selection.getEnd()))
  42386. dragType = draggingSelectionStart;
  42387. else
  42388. dragType = draggingSelectionEnd;
  42389. }
  42390. if (dragType == draggingSelectionStart)
  42391. {
  42392. if (getCaretPosition() >= selection.getEnd())
  42393. dragType = draggingSelectionEnd;
  42394. selection = Range<int>::between (getCaretPosition(), selection.getEnd());
  42395. }
  42396. else
  42397. {
  42398. if (getCaretPosition() < selection.getStart())
  42399. dragType = draggingSelectionStart;
  42400. selection = Range<int>::between (getCaretPosition(), selection.getStart());
  42401. }
  42402. repaintText (selection.getUnionWith (oldSelection));
  42403. }
  42404. else
  42405. {
  42406. dragType = notDragging;
  42407. repaintText (selection);
  42408. moveCaret (newPosition);
  42409. selection = Range<int>::emptyRange (getCaretPosition());
  42410. }
  42411. }
  42412. int TextEditor::getTextIndexAt (const int x,
  42413. const int y)
  42414. {
  42415. return indexAtPosition ((float) (x + viewport->getViewPositionX() - leftIndent),
  42416. (float) (y + viewport->getViewPositionY() - topIndent));
  42417. }
  42418. void TextEditor::insertTextAtCaret (const String& newText_)
  42419. {
  42420. String newText (newText_);
  42421. if (allowedCharacters.isNotEmpty())
  42422. newText = newText.retainCharacters (allowedCharacters);
  42423. if ((! returnKeyStartsNewLine) && newText == "\n")
  42424. {
  42425. returnPressed();
  42426. return;
  42427. }
  42428. if (! isMultiLine())
  42429. newText = newText.replaceCharacters ("\r\n", " ");
  42430. else
  42431. newText = newText.replace ("\r\n", "\n");
  42432. const int newCaretPos = selection.getStart() + newText.length();
  42433. const int insertIndex = selection.getStart();
  42434. remove (selection, getUndoManager(),
  42435. newText.isNotEmpty() ? newCaretPos - 1 : newCaretPos);
  42436. if (maxTextLength > 0)
  42437. newText = newText.substring (0, maxTextLength - getTotalNumChars());
  42438. if (newText.isNotEmpty())
  42439. insert (newText,
  42440. insertIndex,
  42441. currentFont,
  42442. findColour (textColourId),
  42443. getUndoManager(),
  42444. newCaretPos);
  42445. textChanged();
  42446. }
  42447. void TextEditor::setHighlightedRegion (const Range<int>& newSelection)
  42448. {
  42449. moveCursorTo (newSelection.getStart(), false);
  42450. moveCursorTo (newSelection.getEnd(), true);
  42451. }
  42452. void TextEditor::copy()
  42453. {
  42454. if (passwordCharacter == 0)
  42455. {
  42456. const String selectedText (getHighlightedText());
  42457. if (selectedText.isNotEmpty())
  42458. SystemClipboard::copyTextToClipboard (selectedText);
  42459. }
  42460. }
  42461. void TextEditor::paste()
  42462. {
  42463. if (! isReadOnly())
  42464. {
  42465. const String clip (SystemClipboard::getTextFromClipboard());
  42466. if (clip.isNotEmpty())
  42467. insertTextAtCaret (clip);
  42468. }
  42469. }
  42470. void TextEditor::cut()
  42471. {
  42472. if (! isReadOnly())
  42473. {
  42474. moveCaret (selection.getEnd());
  42475. insertTextAtCaret (String::empty);
  42476. }
  42477. }
  42478. void TextEditor::drawContent (Graphics& g)
  42479. {
  42480. const float wordWrapWidth = getWordWrapWidth();
  42481. if (wordWrapWidth > 0)
  42482. {
  42483. g.setOrigin (leftIndent, topIndent);
  42484. const Rectangle<int> clip (g.getClipBounds());
  42485. Colour selectedTextColour;
  42486. Iterator i (sections, wordWrapWidth, passwordCharacter);
  42487. while (i.lineY + 200.0 < clip.getY() && i.next())
  42488. {}
  42489. if (! selection.isEmpty())
  42490. {
  42491. g.setColour (findColour (highlightColourId)
  42492. .withMultipliedAlpha (hasKeyboardFocus (true) ? 1.0f : 0.5f));
  42493. selectedTextColour = findColour (highlightedTextColourId);
  42494. Iterator i2 (i);
  42495. while (i2.next() && i2.lineY < clip.getBottom())
  42496. {
  42497. if (i2.lineY + i2.lineHeight >= clip.getY()
  42498. && selection.intersects (Range<int> (i2.indexInText, i2.indexInText + i2.atom->numChars)))
  42499. {
  42500. i2.drawSelection (g, selection);
  42501. }
  42502. }
  42503. }
  42504. const UniformTextSection* lastSection = 0;
  42505. while (i.next() && i.lineY < clip.getBottom())
  42506. {
  42507. if (i.lineY + i.lineHeight >= clip.getY())
  42508. {
  42509. if (selection.intersects (Range<int> (i.indexInText, i.indexInText + i.atom->numChars)))
  42510. {
  42511. i.drawSelectedText (g, selection, selectedTextColour);
  42512. lastSection = 0;
  42513. }
  42514. else
  42515. {
  42516. i.draw (g, lastSection);
  42517. }
  42518. }
  42519. }
  42520. }
  42521. }
  42522. void TextEditor::paint (Graphics& g)
  42523. {
  42524. getLookAndFeel().fillTextEditorBackground (g, getWidth(), getHeight(), *this);
  42525. }
  42526. void TextEditor::paintOverChildren (Graphics& g)
  42527. {
  42528. if (caretFlashState
  42529. && hasKeyboardFocus (false)
  42530. && caretVisible
  42531. && ! isReadOnly())
  42532. {
  42533. g.setColour (findColour (caretColourId));
  42534. g.fillRect (borderSize.getLeft() + textHolder->getX() + leftIndent + cursorX,
  42535. borderSize.getTop() + textHolder->getY() + topIndent + cursorY,
  42536. 2.0f, cursorHeight);
  42537. }
  42538. if (textToShowWhenEmpty.isNotEmpty()
  42539. && (! hasKeyboardFocus (false))
  42540. && getTotalNumChars() == 0)
  42541. {
  42542. g.setColour (colourForTextWhenEmpty);
  42543. g.setFont (getFont());
  42544. if (isMultiLine())
  42545. {
  42546. g.drawText (textToShowWhenEmpty,
  42547. 0, 0, getWidth(), getHeight(),
  42548. Justification::centred, true);
  42549. }
  42550. else
  42551. {
  42552. g.drawText (textToShowWhenEmpty,
  42553. leftIndent, topIndent,
  42554. viewport->getWidth() - leftIndent,
  42555. viewport->getHeight() - topIndent,
  42556. Justification::centredLeft, true);
  42557. }
  42558. }
  42559. getLookAndFeel().drawTextEditorOutline (g, getWidth(), getHeight(), *this);
  42560. }
  42561. void TextEditor::mouseDown (const MouseEvent& e)
  42562. {
  42563. beginDragAutoRepeat (100);
  42564. newTransaction();
  42565. if (wasFocused || ! selectAllTextWhenFocused)
  42566. {
  42567. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  42568. {
  42569. moveCursorTo (getTextIndexAt (e.x, e.y),
  42570. e.mods.isShiftDown());
  42571. }
  42572. else
  42573. {
  42574. PopupMenu m;
  42575. m.setLookAndFeel (&getLookAndFeel());
  42576. addPopupMenuItems (m, &e);
  42577. menuActive = true;
  42578. const int result = m.show();
  42579. menuActive = false;
  42580. if (result != 0)
  42581. performPopupMenuAction (result);
  42582. }
  42583. }
  42584. }
  42585. void TextEditor::mouseDrag (const MouseEvent& e)
  42586. {
  42587. if (wasFocused || ! selectAllTextWhenFocused)
  42588. {
  42589. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  42590. {
  42591. moveCursorTo (getTextIndexAt (e.x, e.y), true);
  42592. }
  42593. }
  42594. }
  42595. void TextEditor::mouseUp (const MouseEvent& e)
  42596. {
  42597. newTransaction();
  42598. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  42599. if (wasFocused || ! selectAllTextWhenFocused)
  42600. {
  42601. if (e.mouseWasClicked() && ! (popupMenuEnabled && e.mods.isPopupMenu()))
  42602. {
  42603. moveCaret (getTextIndexAt (e.x, e.y));
  42604. }
  42605. }
  42606. wasFocused = true;
  42607. }
  42608. void TextEditor::mouseDoubleClick (const MouseEvent& e)
  42609. {
  42610. int tokenEnd = getTextIndexAt (e.x, e.y);
  42611. int tokenStart = tokenEnd;
  42612. if (e.getNumberOfClicks() > 3)
  42613. {
  42614. tokenStart = 0;
  42615. tokenEnd = getTotalNumChars();
  42616. }
  42617. else
  42618. {
  42619. const String t (getText());
  42620. const int totalLength = getTotalNumChars();
  42621. while (tokenEnd < totalLength)
  42622. {
  42623. // (note the slight bodge here - it's because iswalnum only checks for alphabetic chars in the current locale)
  42624. if (CharacterFunctions::isLetterOrDigit (t [tokenEnd]) || t [tokenEnd] > 128)
  42625. ++tokenEnd;
  42626. else
  42627. break;
  42628. }
  42629. tokenStart = tokenEnd;
  42630. while (tokenStart > 0)
  42631. {
  42632. // (note the slight bodge here - it's because iswalnum only checks for alphabetic chars in the current locale)
  42633. if (CharacterFunctions::isLetterOrDigit (t [tokenStart - 1]) || t [tokenStart - 1] > 128)
  42634. --tokenStart;
  42635. else
  42636. break;
  42637. }
  42638. if (e.getNumberOfClicks() > 2)
  42639. {
  42640. while (tokenEnd < totalLength)
  42641. {
  42642. if (t [tokenEnd] != '\r' && t [tokenEnd] != '\n')
  42643. ++tokenEnd;
  42644. else
  42645. break;
  42646. }
  42647. while (tokenStart > 0)
  42648. {
  42649. if (t [tokenStart - 1] != '\r' && t [tokenStart - 1] != '\n')
  42650. --tokenStart;
  42651. else
  42652. break;
  42653. }
  42654. }
  42655. }
  42656. moveCursorTo (tokenEnd, false);
  42657. moveCursorTo (tokenStart, true);
  42658. }
  42659. void TextEditor::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  42660. {
  42661. if (! viewport->useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  42662. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  42663. }
  42664. bool TextEditor::keyPressed (const KeyPress& key)
  42665. {
  42666. if (isReadOnly() && key != KeyPress ('c', ModifierKeys::commandModifier, 0))
  42667. return false;
  42668. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  42669. if (key.isKeyCode (KeyPress::leftKey)
  42670. || key.isKeyCode (KeyPress::upKey))
  42671. {
  42672. newTransaction();
  42673. int newPos;
  42674. if (isMultiLine() && key.isKeyCode (KeyPress::upKey))
  42675. newPos = indexAtPosition (cursorX, cursorY - 1);
  42676. else if (moveInWholeWordSteps)
  42677. newPos = findWordBreakBefore (getCaretPosition());
  42678. else
  42679. newPos = getCaretPosition() - 1;
  42680. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  42681. }
  42682. else if (key.isKeyCode (KeyPress::rightKey)
  42683. || key.isKeyCode (KeyPress::downKey))
  42684. {
  42685. newTransaction();
  42686. int newPos;
  42687. if (isMultiLine() && key.isKeyCode (KeyPress::downKey))
  42688. newPos = indexAtPosition (cursorX, cursorY + cursorHeight + 1);
  42689. else if (moveInWholeWordSteps)
  42690. newPos = findWordBreakAfter (getCaretPosition());
  42691. else
  42692. newPos = getCaretPosition() + 1;
  42693. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  42694. }
  42695. else if (key.isKeyCode (KeyPress::pageDownKey) && isMultiLine())
  42696. {
  42697. newTransaction();
  42698. moveCursorTo (indexAtPosition (cursorX, cursorY + cursorHeight + viewport->getViewHeight()),
  42699. key.getModifiers().isShiftDown());
  42700. }
  42701. else if (key.isKeyCode (KeyPress::pageUpKey) && isMultiLine())
  42702. {
  42703. newTransaction();
  42704. moveCursorTo (indexAtPosition (cursorX, cursorY - viewport->getViewHeight()),
  42705. key.getModifiers().isShiftDown());
  42706. }
  42707. else if (key.isKeyCode (KeyPress::homeKey))
  42708. {
  42709. newTransaction();
  42710. if (isMultiLine() && ! moveInWholeWordSteps)
  42711. moveCursorTo (indexAtPosition (0.0f, cursorY),
  42712. key.getModifiers().isShiftDown());
  42713. else
  42714. moveCursorTo (0, key.getModifiers().isShiftDown());
  42715. }
  42716. else if (key.isKeyCode (KeyPress::endKey))
  42717. {
  42718. newTransaction();
  42719. if (isMultiLine() && ! moveInWholeWordSteps)
  42720. moveCursorTo (indexAtPosition ((float) textHolder->getWidth(), cursorY),
  42721. key.getModifiers().isShiftDown());
  42722. else
  42723. moveCursorTo (getTotalNumChars(), key.getModifiers().isShiftDown());
  42724. }
  42725. else if (key.isKeyCode (KeyPress::backspaceKey))
  42726. {
  42727. if (moveInWholeWordSteps)
  42728. {
  42729. moveCursorTo (findWordBreakBefore (getCaretPosition()), true);
  42730. }
  42731. else
  42732. {
  42733. if (selection.isEmpty() && selection.getStart() > 0)
  42734. selection.setStart (selection.getEnd() - 1);
  42735. }
  42736. cut();
  42737. }
  42738. else if (key.isKeyCode (KeyPress::deleteKey))
  42739. {
  42740. if (key.getModifiers().isShiftDown())
  42741. copy();
  42742. if (selection.isEmpty() && selection.getStart() < getTotalNumChars())
  42743. selection.setEnd (selection.getStart() + 1);
  42744. cut();
  42745. }
  42746. else if (key == KeyPress ('c', ModifierKeys::commandModifier, 0)
  42747. || key == KeyPress (KeyPress::insertKey, ModifierKeys::ctrlModifier, 0))
  42748. {
  42749. newTransaction();
  42750. copy();
  42751. }
  42752. else if (key == KeyPress ('x', ModifierKeys::commandModifier, 0))
  42753. {
  42754. newTransaction();
  42755. copy();
  42756. cut();
  42757. }
  42758. else if (key == KeyPress ('v', ModifierKeys::commandModifier, 0)
  42759. || key == KeyPress (KeyPress::insertKey, ModifierKeys::shiftModifier, 0))
  42760. {
  42761. newTransaction();
  42762. paste();
  42763. }
  42764. else if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  42765. {
  42766. newTransaction();
  42767. doUndoRedo (false);
  42768. }
  42769. else if (key == KeyPress ('y', ModifierKeys::commandModifier, 0))
  42770. {
  42771. newTransaction();
  42772. doUndoRedo (true);
  42773. }
  42774. else if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  42775. {
  42776. newTransaction();
  42777. moveCursorTo (getTotalNumChars(), false);
  42778. moveCursorTo (0, true);
  42779. }
  42780. else if (key == KeyPress::returnKey)
  42781. {
  42782. newTransaction();
  42783. insertTextAtCaret ("\n");
  42784. }
  42785. else if (key.isKeyCode (KeyPress::escapeKey))
  42786. {
  42787. newTransaction();
  42788. moveCursorTo (getCaretPosition(), false);
  42789. escapePressed();
  42790. }
  42791. else if (key.getTextCharacter() >= ' '
  42792. || (tabKeyUsed && (key.getTextCharacter() == '\t')))
  42793. {
  42794. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  42795. lastTransactionTime = Time::getApproximateMillisecondCounter();
  42796. }
  42797. else
  42798. {
  42799. return false;
  42800. }
  42801. return true;
  42802. }
  42803. bool TextEditor::keyStateChanged (const bool isKeyDown)
  42804. {
  42805. if (! isKeyDown)
  42806. return false;
  42807. #if JUCE_WINDOWS
  42808. if (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0).isCurrentlyDown())
  42809. return false; // We need to explicitly allow alt-F4 to pass through on Windows
  42810. #endif
  42811. // (overridden to avoid forwarding key events to the parent)
  42812. return ! ModifierKeys::getCurrentModifiers().isCommandDown();
  42813. }
  42814. const int baseMenuItemID = 0x7fff0000;
  42815. void TextEditor::addPopupMenuItems (PopupMenu& m, const MouseEvent*)
  42816. {
  42817. const bool writable = ! isReadOnly();
  42818. if (passwordCharacter == 0)
  42819. {
  42820. m.addItem (baseMenuItemID + 1, TRANS("cut"), writable);
  42821. m.addItem (baseMenuItemID + 2, TRANS("copy"), ! selection.isEmpty());
  42822. m.addItem (baseMenuItemID + 3, TRANS("paste"), writable);
  42823. }
  42824. m.addItem (baseMenuItemID + 4, TRANS("delete"), writable);
  42825. m.addSeparator();
  42826. m.addItem (baseMenuItemID + 5, TRANS("select all"));
  42827. m.addSeparator();
  42828. if (getUndoManager() != 0)
  42829. {
  42830. m.addItem (baseMenuItemID + 6, TRANS("undo"), undoManager.canUndo());
  42831. m.addItem (baseMenuItemID + 7, TRANS("redo"), undoManager.canRedo());
  42832. }
  42833. }
  42834. void TextEditor::performPopupMenuAction (const int menuItemID)
  42835. {
  42836. switch (menuItemID)
  42837. {
  42838. case baseMenuItemID + 1:
  42839. copy();
  42840. cut();
  42841. break;
  42842. case baseMenuItemID + 2:
  42843. copy();
  42844. break;
  42845. case baseMenuItemID + 3:
  42846. paste();
  42847. break;
  42848. case baseMenuItemID + 4:
  42849. cut();
  42850. break;
  42851. case baseMenuItemID + 5:
  42852. moveCursorTo (getTotalNumChars(), false);
  42853. moveCursorTo (0, true);
  42854. break;
  42855. case baseMenuItemID + 6:
  42856. doUndoRedo (false);
  42857. break;
  42858. case baseMenuItemID + 7:
  42859. doUndoRedo (true);
  42860. break;
  42861. default:
  42862. break;
  42863. }
  42864. }
  42865. void TextEditor::focusGained (FocusChangeType)
  42866. {
  42867. newTransaction();
  42868. caretFlashState = true;
  42869. if (selectAllTextWhenFocused)
  42870. {
  42871. moveCursorTo (0, false);
  42872. moveCursorTo (getTotalNumChars(), true);
  42873. }
  42874. repaint();
  42875. if (caretVisible)
  42876. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  42877. ComponentPeer* const peer = getPeer();
  42878. if (peer != 0 && ! isReadOnly())
  42879. peer->textInputRequired (getScreenPosition() - peer->getScreenPosition());
  42880. }
  42881. void TextEditor::focusLost (FocusChangeType)
  42882. {
  42883. newTransaction();
  42884. wasFocused = false;
  42885. textHolder->stopTimer();
  42886. caretFlashState = false;
  42887. postCommandMessage (TextEditorDefs::focusLossMessageId);
  42888. repaint();
  42889. }
  42890. void TextEditor::resized()
  42891. {
  42892. viewport->setBoundsInset (borderSize);
  42893. viewport->setSingleStepSizes (16, roundToInt (currentFont.getHeight()));
  42894. updateTextHolderSize();
  42895. if (! isMultiLine())
  42896. {
  42897. scrollToMakeSureCursorIsVisible();
  42898. }
  42899. else
  42900. {
  42901. updateCaretPosition();
  42902. }
  42903. }
  42904. void TextEditor::handleCommandMessage (const int commandId)
  42905. {
  42906. Component::BailOutChecker checker (this);
  42907. switch (commandId)
  42908. {
  42909. case TextEditorDefs::textChangeMessageId:
  42910. listeners.callChecked (checker, &TextEditorListener::textEditorTextChanged, (TextEditor&) *this);
  42911. break;
  42912. case TextEditorDefs::returnKeyMessageId:
  42913. listeners.callChecked (checker, &TextEditorListener::textEditorReturnKeyPressed, (TextEditor&) *this);
  42914. break;
  42915. case TextEditorDefs::escapeKeyMessageId:
  42916. listeners.callChecked (checker, &TextEditorListener::textEditorEscapeKeyPressed, (TextEditor&) *this);
  42917. break;
  42918. case TextEditorDefs::focusLossMessageId:
  42919. listeners.callChecked (checker, &TextEditorListener::textEditorFocusLost, (TextEditor&) *this);
  42920. break;
  42921. default:
  42922. jassertfalse;
  42923. break;
  42924. }
  42925. }
  42926. void TextEditor::enablementChanged()
  42927. {
  42928. setMouseCursor (isReadOnly() ? MouseCursor::NormalCursor
  42929. : MouseCursor::IBeamCursor);
  42930. repaint();
  42931. }
  42932. UndoManager* TextEditor::getUndoManager() throw()
  42933. {
  42934. return isReadOnly() ? &undoManager : 0;
  42935. }
  42936. void TextEditor::clearInternal (UndoManager* const um)
  42937. {
  42938. remove (Range<int> (0, getTotalNumChars()), um, caretPosition);
  42939. }
  42940. void TextEditor::insert (const String& text,
  42941. const int insertIndex,
  42942. const Font& font,
  42943. const Colour& colour,
  42944. UndoManager* const um,
  42945. const int caretPositionToMoveTo)
  42946. {
  42947. if (text.isNotEmpty())
  42948. {
  42949. if (um != 0)
  42950. {
  42951. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  42952. newTransaction();
  42953. um->perform (new InsertAction (*this, text, insertIndex, font, colour,
  42954. caretPosition, caretPositionToMoveTo));
  42955. }
  42956. else
  42957. {
  42958. repaintText (Range<int> (insertIndex, getTotalNumChars())); // must do this before and after changing the data, in case
  42959. // a line gets moved due to word wrap
  42960. int index = 0;
  42961. int nextIndex = 0;
  42962. for (int i = 0; i < sections.size(); ++i)
  42963. {
  42964. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  42965. if (insertIndex == index)
  42966. {
  42967. sections.insert (i, new UniformTextSection (text,
  42968. font, colour,
  42969. passwordCharacter));
  42970. break;
  42971. }
  42972. else if (insertIndex > index && insertIndex < nextIndex)
  42973. {
  42974. splitSection (i, insertIndex - index);
  42975. sections.insert (i + 1, new UniformTextSection (text,
  42976. font, colour,
  42977. passwordCharacter));
  42978. break;
  42979. }
  42980. index = nextIndex;
  42981. }
  42982. if (nextIndex == insertIndex)
  42983. sections.add (new UniformTextSection (text,
  42984. font, colour,
  42985. passwordCharacter));
  42986. coalesceSimilarSections();
  42987. totalNumChars = -1;
  42988. valueTextNeedsUpdating = true;
  42989. moveCursorTo (caretPositionToMoveTo, false);
  42990. repaintText (Range<int> (insertIndex, getTotalNumChars()));
  42991. }
  42992. }
  42993. }
  42994. void TextEditor::reinsert (const int insertIndex,
  42995. const Array <UniformTextSection*>& sectionsToInsert)
  42996. {
  42997. int index = 0;
  42998. int nextIndex = 0;
  42999. for (int i = 0; i < sections.size(); ++i)
  43000. {
  43001. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  43002. if (insertIndex == index)
  43003. {
  43004. for (int j = sectionsToInsert.size(); --j >= 0;)
  43005. sections.insert (i, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  43006. break;
  43007. }
  43008. else if (insertIndex > index && insertIndex < nextIndex)
  43009. {
  43010. splitSection (i, insertIndex - index);
  43011. for (int j = sectionsToInsert.size(); --j >= 0;)
  43012. sections.insert (i + 1, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  43013. break;
  43014. }
  43015. index = nextIndex;
  43016. }
  43017. if (nextIndex == insertIndex)
  43018. {
  43019. for (int j = 0; j < sectionsToInsert.size(); ++j)
  43020. sections.add (new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  43021. }
  43022. coalesceSimilarSections();
  43023. totalNumChars = -1;
  43024. valueTextNeedsUpdating = true;
  43025. }
  43026. void TextEditor::remove (const Range<int>& range,
  43027. UndoManager* const um,
  43028. const int caretPositionToMoveTo)
  43029. {
  43030. if (! range.isEmpty())
  43031. {
  43032. int index = 0;
  43033. for (int i = 0; i < sections.size(); ++i)
  43034. {
  43035. const int nextIndex = index + sections.getUnchecked(i)->getTotalLength();
  43036. if (range.getStart() > index && range.getStart() < nextIndex)
  43037. {
  43038. splitSection (i, range.getStart() - index);
  43039. --i;
  43040. }
  43041. else if (range.getEnd() > index && range.getEnd() < nextIndex)
  43042. {
  43043. splitSection (i, range.getEnd() - index);
  43044. --i;
  43045. }
  43046. else
  43047. {
  43048. index = nextIndex;
  43049. if (index > range.getEnd())
  43050. break;
  43051. }
  43052. }
  43053. index = 0;
  43054. if (um != 0)
  43055. {
  43056. Array <UniformTextSection*> removedSections;
  43057. for (int i = 0; i < sections.size(); ++i)
  43058. {
  43059. if (range.getEnd() <= range.getStart())
  43060. break;
  43061. UniformTextSection* const section = sections.getUnchecked (i);
  43062. const int nextIndex = index + section->getTotalLength();
  43063. if (range.getStart() <= index && range.getEnd() >= nextIndex)
  43064. removedSections.add (new UniformTextSection (*section));
  43065. index = nextIndex;
  43066. }
  43067. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  43068. newTransaction();
  43069. um->perform (new RemoveAction (*this, range, caretPosition,
  43070. caretPositionToMoveTo, removedSections));
  43071. }
  43072. else
  43073. {
  43074. Range<int> remainingRange (range);
  43075. for (int i = 0; i < sections.size(); ++i)
  43076. {
  43077. UniformTextSection* const section = sections.getUnchecked (i);
  43078. const int nextIndex = index + section->getTotalLength();
  43079. if (remainingRange.getStart() <= index && remainingRange.getEnd() >= nextIndex)
  43080. {
  43081. sections.remove(i);
  43082. section->clear();
  43083. delete section;
  43084. remainingRange.setEnd (remainingRange.getEnd() - (nextIndex - index));
  43085. if (remainingRange.isEmpty())
  43086. break;
  43087. --i;
  43088. }
  43089. else
  43090. {
  43091. index = nextIndex;
  43092. }
  43093. }
  43094. coalesceSimilarSections();
  43095. totalNumChars = -1;
  43096. valueTextNeedsUpdating = true;
  43097. moveCursorTo (caretPositionToMoveTo, false);
  43098. repaintText (Range<int> (range.getStart(), getTotalNumChars()));
  43099. }
  43100. }
  43101. }
  43102. const String TextEditor::getText() const
  43103. {
  43104. String t;
  43105. t.preallocateStorage (getTotalNumChars());
  43106. String::Concatenator concatenator (t);
  43107. for (int i = 0; i < sections.size(); ++i)
  43108. sections.getUnchecked (i)->appendAllText (concatenator);
  43109. return t;
  43110. }
  43111. const String TextEditor::getTextInRange (const Range<int>& range) const
  43112. {
  43113. String t;
  43114. if (! range.isEmpty())
  43115. {
  43116. t.preallocateStorage (jmin (getTotalNumChars(), range.getLength()));
  43117. String::Concatenator concatenator (t);
  43118. int index = 0;
  43119. for (int i = 0; i < sections.size(); ++i)
  43120. {
  43121. const UniformTextSection* const s = sections.getUnchecked (i);
  43122. const int nextIndex = index + s->getTotalLength();
  43123. if (range.getStart() < nextIndex)
  43124. {
  43125. if (range.getEnd() <= index)
  43126. break;
  43127. s->appendSubstring (concatenator, range - index);
  43128. }
  43129. index = nextIndex;
  43130. }
  43131. }
  43132. return t;
  43133. }
  43134. const String TextEditor::getHighlightedText() const
  43135. {
  43136. return getTextInRange (selection);
  43137. }
  43138. int TextEditor::getTotalNumChars() const
  43139. {
  43140. if (totalNumChars < 0)
  43141. {
  43142. totalNumChars = 0;
  43143. for (int i = sections.size(); --i >= 0;)
  43144. totalNumChars += sections.getUnchecked (i)->getTotalLength();
  43145. }
  43146. return totalNumChars;
  43147. }
  43148. bool TextEditor::isEmpty() const
  43149. {
  43150. return getTotalNumChars() == 0;
  43151. }
  43152. void TextEditor::getCharPosition (const int index, float& cx, float& cy, float& lineHeight) const
  43153. {
  43154. const float wordWrapWidth = getWordWrapWidth();
  43155. if (wordWrapWidth > 0 && sections.size() > 0)
  43156. {
  43157. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43158. i.getCharPosition (index, cx, cy, lineHeight);
  43159. }
  43160. else
  43161. {
  43162. cx = cy = 0;
  43163. lineHeight = currentFont.getHeight();
  43164. }
  43165. }
  43166. int TextEditor::indexAtPosition (const float x, const float y)
  43167. {
  43168. const float wordWrapWidth = getWordWrapWidth();
  43169. if (wordWrapWidth > 0)
  43170. {
  43171. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43172. while (i.next())
  43173. {
  43174. if (i.lineY + i.lineHeight > y)
  43175. {
  43176. if (i.lineY > y)
  43177. return jmax (0, i.indexInText - 1);
  43178. if (i.atomX >= x)
  43179. return i.indexInText;
  43180. if (x < i.atomRight)
  43181. return i.xToIndex (x);
  43182. }
  43183. }
  43184. }
  43185. return getTotalNumChars();
  43186. }
  43187. static int getCharacterCategory (const juce_wchar character)
  43188. {
  43189. return CharacterFunctions::isLetterOrDigit (character)
  43190. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  43191. }
  43192. int TextEditor::findWordBreakAfter (const int position) const
  43193. {
  43194. const String t (getTextInRange (Range<int> (position, position + 512)));
  43195. const int totalLength = t.length();
  43196. int i = 0;
  43197. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  43198. ++i;
  43199. const int type = getCharacterCategory (t[i]);
  43200. while (i < totalLength && type == getCharacterCategory (t[i]))
  43201. ++i;
  43202. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  43203. ++i;
  43204. return position + i;
  43205. }
  43206. int TextEditor::findWordBreakBefore (const int position) const
  43207. {
  43208. if (position <= 0)
  43209. return 0;
  43210. const int startOfBuffer = jmax (0, position - 512);
  43211. const String t (getTextInRange (Range<int> (startOfBuffer, position)));
  43212. int i = position - startOfBuffer;
  43213. while (i > 0 && CharacterFunctions::isWhitespace (t [i - 1]))
  43214. --i;
  43215. if (i > 0)
  43216. {
  43217. const int type = getCharacterCategory (t [i - 1]);
  43218. while (i > 0 && type == getCharacterCategory (t [i - 1]))
  43219. --i;
  43220. }
  43221. jassert (startOfBuffer + i >= 0);
  43222. return startOfBuffer + i;
  43223. }
  43224. void TextEditor::splitSection (const int sectionIndex,
  43225. const int charToSplitAt)
  43226. {
  43227. jassert (sections[sectionIndex] != 0);
  43228. sections.insert (sectionIndex + 1,
  43229. sections.getUnchecked (sectionIndex)->split (charToSplitAt, passwordCharacter));
  43230. }
  43231. void TextEditor::coalesceSimilarSections()
  43232. {
  43233. for (int i = 0; i < sections.size() - 1; ++i)
  43234. {
  43235. UniformTextSection* const s1 = sections.getUnchecked (i);
  43236. UniformTextSection* const s2 = sections.getUnchecked (i + 1);
  43237. if (s1->font == s2->font
  43238. && s1->colour == s2->colour)
  43239. {
  43240. s1->append (*s2, passwordCharacter);
  43241. sections.remove (i + 1);
  43242. delete s2;
  43243. --i;
  43244. }
  43245. }
  43246. }
  43247. END_JUCE_NAMESPACE
  43248. /*** End of inlined file: juce_TextEditor.cpp ***/
  43249. /*** Start of inlined file: juce_Toolbar.cpp ***/
  43250. BEGIN_JUCE_NAMESPACE
  43251. const char* const Toolbar::toolbarDragDescriptor = "_toolbarItem_";
  43252. class ToolbarSpacerComp : public ToolbarItemComponent
  43253. {
  43254. public:
  43255. ToolbarSpacerComp (const int itemId_, const float fixedSize_, const bool drawBar_)
  43256. : ToolbarItemComponent (itemId_, String::empty, false),
  43257. fixedSize (fixedSize_),
  43258. drawBar (drawBar_)
  43259. {
  43260. }
  43261. ~ToolbarSpacerComp()
  43262. {
  43263. }
  43264. bool getToolbarItemSizes (int toolbarThickness, bool /*isToolbarVertical*/,
  43265. int& preferredSize, int& minSize, int& maxSize)
  43266. {
  43267. if (fixedSize <= 0)
  43268. {
  43269. preferredSize = toolbarThickness * 2;
  43270. minSize = 4;
  43271. maxSize = 32768;
  43272. }
  43273. else
  43274. {
  43275. maxSize = roundToInt (toolbarThickness * fixedSize);
  43276. minSize = drawBar ? maxSize : jmin (4, maxSize);
  43277. preferredSize = maxSize;
  43278. if (getEditingMode() == editableOnPalette)
  43279. preferredSize = maxSize = toolbarThickness / (drawBar ? 3 : 2);
  43280. }
  43281. return true;
  43282. }
  43283. void paintButtonArea (Graphics&, int, int, bool, bool)
  43284. {
  43285. }
  43286. void contentAreaChanged (const Rectangle<int>&)
  43287. {
  43288. }
  43289. int getResizeOrder() const throw()
  43290. {
  43291. return fixedSize <= 0 ? 0 : 1;
  43292. }
  43293. void paint (Graphics& g)
  43294. {
  43295. const int w = getWidth();
  43296. const int h = getHeight();
  43297. if (drawBar)
  43298. {
  43299. g.setColour (findColour (Toolbar::separatorColourId, true));
  43300. const float thickness = 0.2f;
  43301. if (isToolbarVertical())
  43302. g.fillRect (w * 0.1f, h * (0.5f - thickness * 0.5f), w * 0.8f, h * thickness);
  43303. else
  43304. g.fillRect (w * (0.5f - thickness * 0.5f), h * 0.1f, w * thickness, h * 0.8f);
  43305. }
  43306. if (getEditingMode() != normalMode && ! drawBar)
  43307. {
  43308. g.setColour (findColour (Toolbar::separatorColourId, true));
  43309. const int indentX = jmin (2, (w - 3) / 2);
  43310. const int indentY = jmin (2, (h - 3) / 2);
  43311. g.drawRect (indentX, indentY, w - indentX * 2, h - indentY * 2, 1);
  43312. if (fixedSize <= 0)
  43313. {
  43314. float x1, y1, x2, y2, x3, y3, x4, y4, hw, hl;
  43315. if (isToolbarVertical())
  43316. {
  43317. x1 = w * 0.5f;
  43318. y1 = h * 0.4f;
  43319. x2 = x1;
  43320. y2 = indentX * 2.0f;
  43321. x3 = x1;
  43322. y3 = h * 0.6f;
  43323. x4 = x1;
  43324. y4 = h - y2;
  43325. hw = w * 0.15f;
  43326. hl = w * 0.2f;
  43327. }
  43328. else
  43329. {
  43330. x1 = w * 0.4f;
  43331. y1 = h * 0.5f;
  43332. x2 = indentX * 2.0f;
  43333. y2 = y1;
  43334. x3 = w * 0.6f;
  43335. y3 = y1;
  43336. x4 = w - x2;
  43337. y4 = y1;
  43338. hw = h * 0.15f;
  43339. hl = h * 0.2f;
  43340. }
  43341. Path p;
  43342. p.addArrow (Line<float> (x1, y1, x2, y2), 1.5f, hw, hl);
  43343. p.addArrow (Line<float> (x3, y3, x4, y4), 1.5f, hw, hl);
  43344. g.fillPath (p);
  43345. }
  43346. }
  43347. }
  43348. juce_UseDebuggingNewOperator
  43349. private:
  43350. const float fixedSize;
  43351. const bool drawBar;
  43352. ToolbarSpacerComp (const ToolbarSpacerComp&);
  43353. ToolbarSpacerComp& operator= (const ToolbarSpacerComp&);
  43354. };
  43355. class MissingItemsComponent : public PopupMenuCustomComponent
  43356. {
  43357. public:
  43358. MissingItemsComponent (Toolbar& owner_, const int height_)
  43359. : PopupMenuCustomComponent (true),
  43360. owner (owner_),
  43361. height (height_)
  43362. {
  43363. for (int i = owner_.items.size(); --i >= 0;)
  43364. {
  43365. ToolbarItemComponent* const tc = owner_.items.getUnchecked(i);
  43366. if (dynamic_cast <ToolbarSpacerComp*> (tc) == 0 && ! tc->isVisible())
  43367. {
  43368. oldIndexes.insert (0, i);
  43369. addAndMakeVisible (tc, 0);
  43370. }
  43371. }
  43372. layout (400);
  43373. }
  43374. ~MissingItemsComponent()
  43375. {
  43376. // deleting the toolbar while its menu it open??
  43377. jassert (owner.isValidComponent());
  43378. for (int i = 0; i < getNumChildComponents(); ++i)
  43379. {
  43380. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  43381. if (tc != 0)
  43382. {
  43383. tc->setVisible (false);
  43384. const int index = oldIndexes.remove (i);
  43385. owner.addChildComponent (tc, index);
  43386. --i;
  43387. }
  43388. }
  43389. owner.resized();
  43390. }
  43391. void layout (const int preferredWidth)
  43392. {
  43393. const int indent = 8;
  43394. int x = indent;
  43395. int y = indent;
  43396. int maxX = 0;
  43397. for (int i = 0; i < getNumChildComponents(); ++i)
  43398. {
  43399. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  43400. if (tc != 0)
  43401. {
  43402. int preferredSize = 1, minSize = 1, maxSize = 1;
  43403. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  43404. {
  43405. if (x + preferredSize > preferredWidth && x > indent)
  43406. {
  43407. x = indent;
  43408. y += height;
  43409. }
  43410. tc->setBounds (x, y, preferredSize, height);
  43411. x += preferredSize;
  43412. maxX = jmax (maxX, x);
  43413. }
  43414. }
  43415. }
  43416. setSize (maxX + 8, y + height + 8);
  43417. }
  43418. void getIdealSize (int& idealWidth, int& idealHeight)
  43419. {
  43420. idealWidth = getWidth();
  43421. idealHeight = getHeight();
  43422. }
  43423. juce_UseDebuggingNewOperator
  43424. private:
  43425. Toolbar& owner;
  43426. const int height;
  43427. Array <int> oldIndexes;
  43428. MissingItemsComponent (const MissingItemsComponent&);
  43429. MissingItemsComponent& operator= (const MissingItemsComponent&);
  43430. };
  43431. Toolbar::Toolbar()
  43432. : vertical (false),
  43433. isEditingActive (false),
  43434. toolbarStyle (Toolbar::iconsOnly)
  43435. {
  43436. addChildComponent (missingItemsButton = getLookAndFeel().createToolbarMissingItemsButton (*this));
  43437. missingItemsButton->setAlwaysOnTop (true);
  43438. missingItemsButton->addButtonListener (this);
  43439. }
  43440. Toolbar::~Toolbar()
  43441. {
  43442. animator.cancelAllAnimations (true);
  43443. deleteAllChildren();
  43444. }
  43445. void Toolbar::setVertical (const bool shouldBeVertical)
  43446. {
  43447. if (vertical != shouldBeVertical)
  43448. {
  43449. vertical = shouldBeVertical;
  43450. resized();
  43451. }
  43452. }
  43453. void Toolbar::clear()
  43454. {
  43455. for (int i = items.size(); --i >= 0;)
  43456. {
  43457. ToolbarItemComponent* const tc = items.getUnchecked(i);
  43458. items.remove (i);
  43459. delete tc;
  43460. }
  43461. resized();
  43462. }
  43463. ToolbarItemComponent* Toolbar::createItem (ToolbarItemFactory& factory, const int itemId)
  43464. {
  43465. if (itemId == ToolbarItemFactory::separatorBarId)
  43466. return new ToolbarSpacerComp (itemId, 0.1f, true);
  43467. else if (itemId == ToolbarItemFactory::spacerId)
  43468. return new ToolbarSpacerComp (itemId, 0.5f, false);
  43469. else if (itemId == ToolbarItemFactory::flexibleSpacerId)
  43470. return new ToolbarSpacerComp (itemId, 0, false);
  43471. return factory.createItem (itemId);
  43472. }
  43473. void Toolbar::addItemInternal (ToolbarItemFactory& factory,
  43474. const int itemId,
  43475. const int insertIndex)
  43476. {
  43477. // An ID can't be zero - this might indicate a mistake somewhere?
  43478. jassert (itemId != 0);
  43479. ToolbarItemComponent* const tc = createItem (factory, itemId);
  43480. if (tc != 0)
  43481. {
  43482. #if JUCE_DEBUG
  43483. Array <int> allowedIds;
  43484. factory.getAllToolbarItemIds (allowedIds);
  43485. // If your factory can create an item for a given ID, it must also return
  43486. // that ID from its getAllToolbarItemIds() method!
  43487. jassert (allowedIds.contains (itemId));
  43488. #endif
  43489. items.insert (insertIndex, tc);
  43490. addAndMakeVisible (tc, insertIndex);
  43491. }
  43492. }
  43493. void Toolbar::addItem (ToolbarItemFactory& factory,
  43494. const int itemId,
  43495. const int insertIndex)
  43496. {
  43497. addItemInternal (factory, itemId, insertIndex);
  43498. resized();
  43499. }
  43500. void Toolbar::addDefaultItems (ToolbarItemFactory& factoryToUse)
  43501. {
  43502. Array <int> ids;
  43503. factoryToUse.getDefaultItemSet (ids);
  43504. clear();
  43505. for (int i = 0; i < ids.size(); ++i)
  43506. addItemInternal (factoryToUse, ids.getUnchecked (i), -1);
  43507. resized();
  43508. }
  43509. void Toolbar::removeToolbarItem (const int itemIndex)
  43510. {
  43511. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  43512. if (tc != 0)
  43513. {
  43514. items.removeValue (tc);
  43515. delete tc;
  43516. resized();
  43517. }
  43518. }
  43519. int Toolbar::getNumItems() const throw()
  43520. {
  43521. return items.size();
  43522. }
  43523. int Toolbar::getItemId (const int itemIndex) const throw()
  43524. {
  43525. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  43526. return tc != 0 ? tc->getItemId() : 0;
  43527. }
  43528. ToolbarItemComponent* Toolbar::getItemComponent (const int itemIndex) const throw()
  43529. {
  43530. return items [itemIndex];
  43531. }
  43532. ToolbarItemComponent* Toolbar::getNextActiveComponent (int index, const int delta) const
  43533. {
  43534. for (;;)
  43535. {
  43536. index += delta;
  43537. ToolbarItemComponent* const tc = getItemComponent (index);
  43538. if (tc == 0)
  43539. break;
  43540. if (tc->isActive)
  43541. return tc;
  43542. }
  43543. return 0;
  43544. }
  43545. void Toolbar::setStyle (const ToolbarItemStyle& newStyle)
  43546. {
  43547. if (toolbarStyle != newStyle)
  43548. {
  43549. toolbarStyle = newStyle;
  43550. updateAllItemPositions (false);
  43551. }
  43552. }
  43553. const String Toolbar::toString() const
  43554. {
  43555. String s ("TB:");
  43556. for (int i = 0; i < getNumItems(); ++i)
  43557. s << getItemId(i) << ' ';
  43558. return s.trimEnd();
  43559. }
  43560. bool Toolbar::restoreFromString (ToolbarItemFactory& factoryToUse,
  43561. const String& savedVersion)
  43562. {
  43563. if (! savedVersion.startsWith ("TB:"))
  43564. return false;
  43565. StringArray tokens;
  43566. tokens.addTokens (savedVersion.substring (3), false);
  43567. clear();
  43568. for (int i = 0; i < tokens.size(); ++i)
  43569. addItemInternal (factoryToUse, tokens[i].getIntValue(), -1);
  43570. resized();
  43571. return true;
  43572. }
  43573. void Toolbar::paint (Graphics& g)
  43574. {
  43575. getLookAndFeel().paintToolbarBackground (g, getWidth(), getHeight(), *this);
  43576. }
  43577. int Toolbar::getThickness() const throw()
  43578. {
  43579. return vertical ? getWidth() : getHeight();
  43580. }
  43581. int Toolbar::getLength() const throw()
  43582. {
  43583. return vertical ? getHeight() : getWidth();
  43584. }
  43585. void Toolbar::setEditingActive (const bool active)
  43586. {
  43587. if (isEditingActive != active)
  43588. {
  43589. isEditingActive = active;
  43590. updateAllItemPositions (false);
  43591. }
  43592. }
  43593. void Toolbar::resized()
  43594. {
  43595. updateAllItemPositions (false);
  43596. }
  43597. void Toolbar::updateAllItemPositions (const bool animate)
  43598. {
  43599. if (getWidth() > 0 && getHeight() > 0)
  43600. {
  43601. StretchableObjectResizer resizer;
  43602. int i;
  43603. for (i = 0; i < items.size(); ++i)
  43604. {
  43605. ToolbarItemComponent* const tc = items.getUnchecked(i);
  43606. tc->setEditingMode (isEditingActive ? ToolbarItemComponent::editableOnToolbar
  43607. : ToolbarItemComponent::normalMode);
  43608. tc->setStyle (toolbarStyle);
  43609. ToolbarSpacerComp* const spacer = dynamic_cast <ToolbarSpacerComp*> (tc);
  43610. int preferredSize = 1, minSize = 1, maxSize = 1;
  43611. if (tc->getToolbarItemSizes (getThickness(), isVertical(),
  43612. preferredSize, minSize, maxSize))
  43613. {
  43614. tc->isActive = true;
  43615. resizer.addItem (preferredSize, minSize, maxSize,
  43616. spacer != 0 ? spacer->getResizeOrder() : 2);
  43617. }
  43618. else
  43619. {
  43620. tc->isActive = false;
  43621. tc->setVisible (false);
  43622. }
  43623. }
  43624. resizer.resizeToFit (getLength());
  43625. int totalLength = 0;
  43626. for (i = 0; i < resizer.getNumItems(); ++i)
  43627. totalLength += (int) resizer.getItemSize (i);
  43628. const bool itemsOffTheEnd = totalLength > getLength();
  43629. const int extrasButtonSize = getThickness() / 2;
  43630. missingItemsButton->setSize (extrasButtonSize, extrasButtonSize);
  43631. missingItemsButton->setVisible (itemsOffTheEnd);
  43632. missingItemsButton->setEnabled (! isEditingActive);
  43633. if (vertical)
  43634. missingItemsButton->setCentrePosition (getWidth() / 2,
  43635. getHeight() - 4 - extrasButtonSize / 2);
  43636. else
  43637. missingItemsButton->setCentrePosition (getWidth() - 4 - extrasButtonSize / 2,
  43638. getHeight() / 2);
  43639. const int maxLength = itemsOffTheEnd ? (vertical ? missingItemsButton->getY()
  43640. : missingItemsButton->getX()) - 4
  43641. : getLength();
  43642. int pos = 0, activeIndex = 0;
  43643. for (i = 0; i < items.size(); ++i)
  43644. {
  43645. ToolbarItemComponent* const tc = items.getUnchecked(i);
  43646. if (tc->isActive)
  43647. {
  43648. const int size = (int) resizer.getItemSize (activeIndex++);
  43649. Rectangle<int> newBounds;
  43650. if (vertical)
  43651. newBounds.setBounds (0, pos, getWidth(), size);
  43652. else
  43653. newBounds.setBounds (pos, 0, size, getHeight());
  43654. if (animate)
  43655. {
  43656. animator.animateComponent (tc, newBounds, 200, 3.0, 0.0);
  43657. }
  43658. else
  43659. {
  43660. animator.cancelAnimation (tc, false);
  43661. tc->setBounds (newBounds);
  43662. }
  43663. pos += size;
  43664. tc->setVisible (pos <= maxLength
  43665. && ((! tc->isBeingDragged)
  43666. || tc->getEditingMode() == ToolbarItemComponent::editableOnPalette));
  43667. }
  43668. }
  43669. }
  43670. }
  43671. void Toolbar::buttonClicked (Button*)
  43672. {
  43673. jassert (missingItemsButton->isShowing());
  43674. if (missingItemsButton->isShowing())
  43675. {
  43676. PopupMenu m;
  43677. m.addCustomItem (1, new MissingItemsComponent (*this, getThickness()));
  43678. m.showAt (missingItemsButton);
  43679. }
  43680. }
  43681. bool Toolbar::isInterestedInDragSource (const String& sourceDescription,
  43682. Component* /*sourceComponent*/)
  43683. {
  43684. return sourceDescription == toolbarDragDescriptor && isEditingActive;
  43685. }
  43686. void Toolbar::itemDragMove (const String&, Component* sourceComponent, int x, int y)
  43687. {
  43688. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  43689. if (tc != 0)
  43690. {
  43691. if (getNumItems() == 0)
  43692. {
  43693. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  43694. {
  43695. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  43696. if (palette != 0)
  43697. palette->replaceComponent (tc);
  43698. }
  43699. else
  43700. {
  43701. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  43702. }
  43703. items.add (tc);
  43704. addChildComponent (tc);
  43705. updateAllItemPositions (false);
  43706. }
  43707. else
  43708. {
  43709. for (int i = getNumItems(); --i >= 0;)
  43710. {
  43711. int currentIndex = getIndexOfChildComponent (tc);
  43712. if (currentIndex < 0)
  43713. {
  43714. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  43715. {
  43716. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  43717. if (palette != 0)
  43718. palette->replaceComponent (tc);
  43719. }
  43720. else
  43721. {
  43722. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  43723. }
  43724. items.add (tc);
  43725. addChildComponent (tc);
  43726. currentIndex = getIndexOfChildComponent (tc);
  43727. updateAllItemPositions (true);
  43728. }
  43729. int newIndex = currentIndex;
  43730. const int dragObjectLeft = vertical ? (y - tc->dragOffsetY) : (x - tc->dragOffsetX);
  43731. const int dragObjectRight = dragObjectLeft + (vertical ? tc->getHeight() : tc->getWidth());
  43732. const Rectangle<int> current (animator.getComponentDestination (getChildComponent (newIndex)));
  43733. ToolbarItemComponent* const prev = getNextActiveComponent (newIndex, -1);
  43734. if (prev != 0)
  43735. {
  43736. const Rectangle<int> previousPos (animator.getComponentDestination (prev));
  43737. if (abs (dragObjectLeft - (vertical ? previousPos.getY() : previousPos.getX())
  43738. < abs (dragObjectRight - (vertical ? current.getBottom() : current.getRight()))))
  43739. {
  43740. newIndex = getIndexOfChildComponent (prev);
  43741. }
  43742. }
  43743. ToolbarItemComponent* const next = getNextActiveComponent (newIndex, 1);
  43744. if (next != 0)
  43745. {
  43746. const Rectangle<int> nextPos (animator.getComponentDestination (next));
  43747. if (abs (dragObjectLeft - (vertical ? current.getY() : current.getX())
  43748. > abs (dragObjectRight - (vertical ? nextPos.getBottom() : nextPos.getRight()))))
  43749. {
  43750. newIndex = getIndexOfChildComponent (next) + 1;
  43751. }
  43752. }
  43753. if (newIndex != currentIndex)
  43754. {
  43755. items.removeValue (tc);
  43756. removeChildComponent (tc);
  43757. addChildComponent (tc, newIndex);
  43758. items.insert (newIndex, tc);
  43759. updateAllItemPositions (true);
  43760. }
  43761. else
  43762. {
  43763. break;
  43764. }
  43765. }
  43766. }
  43767. }
  43768. }
  43769. void Toolbar::itemDragExit (const String&, Component* sourceComponent)
  43770. {
  43771. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  43772. if (tc != 0)
  43773. {
  43774. if (isParentOf (tc))
  43775. {
  43776. items.removeValue (tc);
  43777. removeChildComponent (tc);
  43778. updateAllItemPositions (true);
  43779. }
  43780. }
  43781. }
  43782. void Toolbar::itemDropped (const String&, Component*, int, int)
  43783. {
  43784. }
  43785. void Toolbar::mouseDown (const MouseEvent& e)
  43786. {
  43787. if (e.mods.isPopupMenu())
  43788. {
  43789. }
  43790. }
  43791. class ToolbarCustomisationDialog : public DialogWindow
  43792. {
  43793. public:
  43794. ToolbarCustomisationDialog (ToolbarItemFactory& factory,
  43795. Toolbar* const toolbar_,
  43796. const int optionFlags)
  43797. : DialogWindow (TRANS("Add/remove items from toolbar"), Colours::white, true, true),
  43798. toolbar (toolbar_)
  43799. {
  43800. setContentComponent (new CustomiserPanel (factory, toolbar, optionFlags), true, true);
  43801. setResizable (true, true);
  43802. setResizeLimits (400, 300, 1500, 1000);
  43803. positionNearBar();
  43804. }
  43805. ~ToolbarCustomisationDialog()
  43806. {
  43807. setContentComponent (0, true);
  43808. }
  43809. void closeButtonPressed()
  43810. {
  43811. setVisible (false);
  43812. }
  43813. bool canModalEventBeSentToComponent (const Component* comp)
  43814. {
  43815. return toolbar->isParentOf (comp);
  43816. }
  43817. void positionNearBar()
  43818. {
  43819. const Rectangle<int> screenSize (toolbar->getParentMonitorArea());
  43820. const int tbx = toolbar->getScreenX();
  43821. const int tby = toolbar->getScreenY();
  43822. const int gap = 8;
  43823. int x, y;
  43824. if (toolbar->isVertical())
  43825. {
  43826. y = tby;
  43827. if (tbx > screenSize.getCentreX())
  43828. x = tbx - getWidth() - gap;
  43829. else
  43830. x = tbx + toolbar->getWidth() + gap;
  43831. }
  43832. else
  43833. {
  43834. x = tbx + (toolbar->getWidth() - getWidth()) / 2;
  43835. if (tby > screenSize.getCentreY())
  43836. y = tby - getHeight() - gap;
  43837. else
  43838. y = tby + toolbar->getHeight() + gap;
  43839. }
  43840. setTopLeftPosition (x, y);
  43841. }
  43842. private:
  43843. Toolbar* const toolbar;
  43844. class CustomiserPanel : public Component,
  43845. private ComboBoxListener,
  43846. private ButtonListener
  43847. {
  43848. public:
  43849. CustomiserPanel (ToolbarItemFactory& factory_,
  43850. Toolbar* const toolbar_,
  43851. const int optionFlags)
  43852. : factory (factory_),
  43853. toolbar (toolbar_),
  43854. styleBox (0),
  43855. defaultButton (0)
  43856. {
  43857. addAndMakeVisible (palette = new ToolbarItemPalette (factory, toolbar));
  43858. if ((optionFlags & (Toolbar::allowIconsOnlyChoice
  43859. | Toolbar::allowIconsWithTextChoice
  43860. | Toolbar::allowTextOnlyChoice)) != 0)
  43861. {
  43862. addAndMakeVisible (styleBox = new ComboBox (String::empty));
  43863. styleBox->setEditableText (false);
  43864. if ((optionFlags & Toolbar::allowIconsOnlyChoice) != 0)
  43865. styleBox->addItem (TRANS("Show icons only"), 1);
  43866. if ((optionFlags & Toolbar::allowIconsWithTextChoice) != 0)
  43867. styleBox->addItem (TRANS("Show icons and descriptions"), 2);
  43868. if ((optionFlags & Toolbar::allowTextOnlyChoice) != 0)
  43869. styleBox->addItem (TRANS("Show descriptions only"), 3);
  43870. if (toolbar_->getStyle() == Toolbar::iconsOnly)
  43871. styleBox->setSelectedId (1);
  43872. else if (toolbar_->getStyle() == Toolbar::iconsWithText)
  43873. styleBox->setSelectedId (2);
  43874. else if (toolbar_->getStyle() == Toolbar::textOnly)
  43875. styleBox->setSelectedId (3);
  43876. styleBox->addListener (this);
  43877. }
  43878. if ((optionFlags & Toolbar::showResetToDefaultsButton) != 0)
  43879. {
  43880. addAndMakeVisible (defaultButton = new TextButton (TRANS ("Restore to default set of items")));
  43881. defaultButton->addButtonListener (this);
  43882. }
  43883. addAndMakeVisible (instructions = new Label (String::empty,
  43884. 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.")));
  43885. instructions->setFont (Font (13.0f));
  43886. setSize (500, 300);
  43887. }
  43888. ~CustomiserPanel()
  43889. {
  43890. deleteAllChildren();
  43891. }
  43892. void comboBoxChanged (ComboBox*)
  43893. {
  43894. if (styleBox->getSelectedId() == 1)
  43895. toolbar->setStyle (Toolbar::iconsOnly);
  43896. else if (styleBox->getSelectedId() == 2)
  43897. toolbar->setStyle (Toolbar::iconsWithText);
  43898. else if (styleBox->getSelectedId() == 3)
  43899. toolbar->setStyle (Toolbar::textOnly);
  43900. palette->resized(); // to make it update the styles
  43901. }
  43902. void buttonClicked (Button*)
  43903. {
  43904. toolbar->addDefaultItems (factory);
  43905. }
  43906. void paint (Graphics& g)
  43907. {
  43908. Colour background;
  43909. DialogWindow* const dw = findParentComponentOfClass ((DialogWindow*) 0);
  43910. if (dw != 0)
  43911. background = dw->getBackgroundColour();
  43912. g.setColour (background.contrasting().withAlpha (0.3f));
  43913. g.fillRect (palette->getX(), palette->getBottom() - 1, palette->getWidth(), 1);
  43914. }
  43915. void resized()
  43916. {
  43917. palette->setBounds (0, 0, getWidth(), getHeight() - 120);
  43918. if (styleBox != 0)
  43919. styleBox->setBounds (10, getHeight() - 110, 200, 22);
  43920. if (defaultButton != 0)
  43921. {
  43922. defaultButton->changeWidthToFitText (22);
  43923. defaultButton->setTopLeftPosition (240, getHeight() - 110);
  43924. }
  43925. instructions->setBounds (10, getHeight() - 80, getWidth() - 20, 80);
  43926. }
  43927. private:
  43928. ToolbarItemFactory& factory;
  43929. Toolbar* const toolbar;
  43930. Label* instructions;
  43931. ToolbarItemPalette* palette;
  43932. ComboBox* styleBox;
  43933. TextButton* defaultButton;
  43934. };
  43935. };
  43936. void Toolbar::showCustomisationDialog (ToolbarItemFactory& factory, const int optionFlags)
  43937. {
  43938. setEditingActive (true);
  43939. ToolbarCustomisationDialog dw (factory, this, optionFlags);
  43940. dw.runModalLoop();
  43941. jassert (isValidComponent()); // ? deleting the toolbar while it's being edited?
  43942. setEditingActive (false);
  43943. }
  43944. END_JUCE_NAMESPACE
  43945. /*** End of inlined file: juce_Toolbar.cpp ***/
  43946. /*** Start of inlined file: juce_ToolbarItemComponent.cpp ***/
  43947. BEGIN_JUCE_NAMESPACE
  43948. ToolbarItemFactory::ToolbarItemFactory()
  43949. {
  43950. }
  43951. ToolbarItemFactory::~ToolbarItemFactory()
  43952. {
  43953. }
  43954. class ItemDragAndDropOverlayComponent : public Component
  43955. {
  43956. public:
  43957. ItemDragAndDropOverlayComponent()
  43958. : isDragging (false)
  43959. {
  43960. setAlwaysOnTop (true);
  43961. setRepaintsOnMouseActivity (true);
  43962. setMouseCursor (MouseCursor::DraggingHandCursor);
  43963. }
  43964. ~ItemDragAndDropOverlayComponent()
  43965. {
  43966. }
  43967. void paint (Graphics& g)
  43968. {
  43969. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  43970. if (isMouseOverOrDragging()
  43971. && tc != 0
  43972. && tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  43973. {
  43974. g.setColour (findColour (Toolbar::editingModeOutlineColourId, true));
  43975. g.drawRect (0, 0, getWidth(), getHeight(),
  43976. jmin (2, (getWidth() - 1) / 2, (getHeight() - 1) / 2));
  43977. }
  43978. }
  43979. void mouseDown (const MouseEvent& e)
  43980. {
  43981. isDragging = false;
  43982. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  43983. if (tc != 0)
  43984. {
  43985. tc->dragOffsetX = e.x;
  43986. tc->dragOffsetY = e.y;
  43987. }
  43988. }
  43989. void mouseDrag (const MouseEvent& e)
  43990. {
  43991. if (! (isDragging || e.mouseWasClicked()))
  43992. {
  43993. isDragging = true;
  43994. DragAndDropContainer* const dnd = DragAndDropContainer::findParentDragContainerFor (this);
  43995. if (dnd != 0)
  43996. {
  43997. dnd->startDragging (Toolbar::toolbarDragDescriptor, getParentComponent(), Image(), true);
  43998. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  43999. if (tc != 0)
  44000. {
  44001. tc->isBeingDragged = true;
  44002. if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  44003. tc->setVisible (false);
  44004. }
  44005. }
  44006. }
  44007. }
  44008. void mouseUp (const MouseEvent&)
  44009. {
  44010. isDragging = false;
  44011. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44012. if (tc != 0)
  44013. {
  44014. tc->isBeingDragged = false;
  44015. Toolbar* const tb = tc->getToolbar();
  44016. if (tb != 0)
  44017. tb->updateAllItemPositions (true);
  44018. else if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  44019. delete tc;
  44020. }
  44021. }
  44022. void parentSizeChanged()
  44023. {
  44024. setBounds (0, 0, getParentWidth(), getParentHeight());
  44025. }
  44026. juce_UseDebuggingNewOperator
  44027. private:
  44028. bool isDragging;
  44029. ItemDragAndDropOverlayComponent (const ItemDragAndDropOverlayComponent&);
  44030. ItemDragAndDropOverlayComponent& operator= (const ItemDragAndDropOverlayComponent&);
  44031. };
  44032. ToolbarItemComponent::ToolbarItemComponent (const int itemId_,
  44033. const String& labelText,
  44034. const bool isBeingUsedAsAButton_)
  44035. : Button (labelText),
  44036. itemId (itemId_),
  44037. mode (normalMode),
  44038. toolbarStyle (Toolbar::iconsOnly),
  44039. dragOffsetX (0),
  44040. dragOffsetY (0),
  44041. isActive (true),
  44042. isBeingDragged (false),
  44043. isBeingUsedAsAButton (isBeingUsedAsAButton_)
  44044. {
  44045. // Your item ID can't be 0!
  44046. jassert (itemId_ != 0);
  44047. }
  44048. ToolbarItemComponent::~ToolbarItemComponent()
  44049. {
  44050. jassert (overlayComp == 0 || overlayComp->isValidComponent());
  44051. overlayComp = 0;
  44052. }
  44053. Toolbar* ToolbarItemComponent::getToolbar() const
  44054. {
  44055. return dynamic_cast <Toolbar*> (getParentComponent());
  44056. }
  44057. bool ToolbarItemComponent::isToolbarVertical() const
  44058. {
  44059. const Toolbar* const t = getToolbar();
  44060. return t != 0 && t->isVertical();
  44061. }
  44062. void ToolbarItemComponent::setStyle (const Toolbar::ToolbarItemStyle& newStyle)
  44063. {
  44064. if (toolbarStyle != newStyle)
  44065. {
  44066. toolbarStyle = newStyle;
  44067. repaint();
  44068. resized();
  44069. }
  44070. }
  44071. void ToolbarItemComponent::paintButton (Graphics& g, const bool over, const bool down)
  44072. {
  44073. if (isBeingUsedAsAButton)
  44074. getLookAndFeel().paintToolbarButtonBackground (g, getWidth(), getHeight(),
  44075. over, down, *this);
  44076. if (toolbarStyle != Toolbar::iconsOnly)
  44077. {
  44078. const int indent = contentArea.getX();
  44079. int y = indent;
  44080. int h = getHeight() - indent * 2;
  44081. if (toolbarStyle == Toolbar::iconsWithText)
  44082. {
  44083. y = contentArea.getBottom() + indent / 2;
  44084. h -= contentArea.getHeight();
  44085. }
  44086. getLookAndFeel().paintToolbarButtonLabel (g, indent, y, getWidth() - indent * 2, h,
  44087. getButtonText(), *this);
  44088. }
  44089. if (! contentArea.isEmpty())
  44090. {
  44091. g.saveState();
  44092. g.setOrigin (contentArea.getX(), contentArea.getY());
  44093. g.reduceClipRegion (0, 0, contentArea.getWidth(), contentArea.getHeight());
  44094. paintButtonArea (g, contentArea.getWidth(), contentArea.getHeight(), over, down);
  44095. g.restoreState();
  44096. }
  44097. }
  44098. void ToolbarItemComponent::resized()
  44099. {
  44100. if (toolbarStyle != Toolbar::textOnly)
  44101. {
  44102. const int indent = jmin (proportionOfWidth (0.08f),
  44103. proportionOfHeight (0.08f));
  44104. contentArea = Rectangle<int> (indent, indent,
  44105. getWidth() - indent * 2,
  44106. toolbarStyle == Toolbar::iconsWithText ? proportionOfHeight (0.55f)
  44107. : (getHeight() - indent * 2));
  44108. }
  44109. else
  44110. {
  44111. contentArea = Rectangle<int>();
  44112. }
  44113. contentAreaChanged (contentArea);
  44114. }
  44115. void ToolbarItemComponent::setEditingMode (const ToolbarEditingMode newMode)
  44116. {
  44117. if (mode != newMode)
  44118. {
  44119. mode = newMode;
  44120. repaint();
  44121. if (mode == normalMode)
  44122. {
  44123. jassert (overlayComp == 0 || overlayComp->isValidComponent());
  44124. overlayComp = 0;
  44125. }
  44126. else if (overlayComp == 0)
  44127. {
  44128. addAndMakeVisible (overlayComp = new ItemDragAndDropOverlayComponent());
  44129. overlayComp->parentSizeChanged();
  44130. }
  44131. resized();
  44132. }
  44133. }
  44134. END_JUCE_NAMESPACE
  44135. /*** End of inlined file: juce_ToolbarItemComponent.cpp ***/
  44136. /*** Start of inlined file: juce_ToolbarItemPalette.cpp ***/
  44137. BEGIN_JUCE_NAMESPACE
  44138. ToolbarItemPalette::ToolbarItemPalette (ToolbarItemFactory& factory_,
  44139. Toolbar* const toolbar_)
  44140. : factory (factory_),
  44141. toolbar (toolbar_)
  44142. {
  44143. Component* const itemHolder = new Component();
  44144. Array <int> allIds;
  44145. factory_.getAllToolbarItemIds (allIds);
  44146. for (int i = 0; i < allIds.size(); ++i)
  44147. {
  44148. ToolbarItemComponent* const tc = Toolbar::createItem (factory_, allIds.getUnchecked (i));
  44149. jassert (tc != 0);
  44150. if (tc != 0)
  44151. {
  44152. itemHolder->addAndMakeVisible (tc);
  44153. tc->setEditingMode (ToolbarItemComponent::editableOnPalette);
  44154. }
  44155. }
  44156. viewport = new Viewport();
  44157. viewport->setViewedComponent (itemHolder);
  44158. addAndMakeVisible (viewport);
  44159. }
  44160. ToolbarItemPalette::~ToolbarItemPalette()
  44161. {
  44162. viewport->getViewedComponent()->deleteAllChildren();
  44163. deleteAllChildren();
  44164. }
  44165. void ToolbarItemPalette::resized()
  44166. {
  44167. viewport->setBoundsInset (BorderSize (1));
  44168. Component* const itemHolder = viewport->getViewedComponent();
  44169. const int indent = 8;
  44170. const int preferredWidth = viewport->getWidth() - viewport->getScrollBarThickness() - indent;
  44171. const int height = toolbar->getThickness();
  44172. int x = indent;
  44173. int y = indent;
  44174. int maxX = 0;
  44175. for (int i = 0; i < itemHolder->getNumChildComponents(); ++i)
  44176. {
  44177. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (itemHolder->getChildComponent (i));
  44178. if (tc != 0)
  44179. {
  44180. tc->setStyle (toolbar->getStyle());
  44181. int preferredSize = 1, minSize = 1, maxSize = 1;
  44182. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  44183. {
  44184. if (x + preferredSize > preferredWidth && x > indent)
  44185. {
  44186. x = indent;
  44187. y += height;
  44188. }
  44189. tc->setBounds (x, y, preferredSize, height);
  44190. x += preferredSize + 8;
  44191. maxX = jmax (maxX, x);
  44192. }
  44193. }
  44194. }
  44195. itemHolder->setSize (maxX, y + height + 8);
  44196. }
  44197. void ToolbarItemPalette::replaceComponent (ToolbarItemComponent* const comp)
  44198. {
  44199. ToolbarItemComponent* const tc = Toolbar::createItem (factory, comp->getItemId());
  44200. jassert (tc != 0);
  44201. if (tc != 0)
  44202. {
  44203. tc->setBounds (comp->getBounds());
  44204. tc->setStyle (toolbar->getStyle());
  44205. tc->setEditingMode (comp->getEditingMode());
  44206. viewport->getViewedComponent()->addAndMakeVisible (tc, getIndexOfChildComponent (comp));
  44207. }
  44208. }
  44209. END_JUCE_NAMESPACE
  44210. /*** End of inlined file: juce_ToolbarItemPalette.cpp ***/
  44211. /*** Start of inlined file: juce_TreeView.cpp ***/
  44212. BEGIN_JUCE_NAMESPACE
  44213. class TreeViewContentComponent : public Component,
  44214. public TooltipClient
  44215. {
  44216. public:
  44217. TreeViewContentComponent (TreeView& owner_)
  44218. : owner (owner_),
  44219. buttonUnderMouse (0),
  44220. isDragging (false)
  44221. {
  44222. }
  44223. ~TreeViewContentComponent()
  44224. {
  44225. deleteAllChildren();
  44226. }
  44227. void mouseDown (const MouseEvent& e)
  44228. {
  44229. updateButtonUnderMouse (e);
  44230. isDragging = false;
  44231. needSelectionOnMouseUp = false;
  44232. Rectangle<int> pos;
  44233. TreeViewItem* const item = findItemAt (e.y, pos);
  44234. if (item == 0)
  44235. return;
  44236. // (if the open/close buttons are hidden, we'll treat clicks to the left of the item
  44237. // as selection clicks)
  44238. if (e.x < pos.getX() && owner.openCloseButtonsVisible)
  44239. {
  44240. if (e.x >= pos.getX() - owner.getIndentSize())
  44241. item->setOpen (! item->isOpen());
  44242. // (clicks to the left of an open/close button are ignored)
  44243. }
  44244. else
  44245. {
  44246. // mouse-down inside the body of the item..
  44247. if (! owner.isMultiSelectEnabled())
  44248. item->setSelected (true, true);
  44249. else if (item->isSelected())
  44250. needSelectionOnMouseUp = ! e.mods.isPopupMenu();
  44251. else
  44252. selectBasedOnModifiers (item, e.mods);
  44253. if (e.x >= pos.getX())
  44254. item->itemClicked (e.withNewPosition (e.getPosition() - pos.getPosition()));
  44255. }
  44256. }
  44257. void mouseUp (const MouseEvent& e)
  44258. {
  44259. updateButtonUnderMouse (e);
  44260. if (needSelectionOnMouseUp && e.mouseWasClicked())
  44261. {
  44262. Rectangle<int> pos;
  44263. TreeViewItem* const item = findItemAt (e.y, pos);
  44264. if (item != 0)
  44265. selectBasedOnModifiers (item, e.mods);
  44266. }
  44267. }
  44268. void mouseDoubleClick (const MouseEvent& e)
  44269. {
  44270. if (e.getNumberOfClicks() != 3) // ignore triple clicks
  44271. {
  44272. Rectangle<int> pos;
  44273. TreeViewItem* const item = findItemAt (e.y, pos);
  44274. if (item != 0 && (e.x >= pos.getX() || ! owner.openCloseButtonsVisible))
  44275. item->itemDoubleClicked (e.withNewPosition (e.getPosition() - pos.getPosition()));
  44276. }
  44277. }
  44278. void mouseDrag (const MouseEvent& e)
  44279. {
  44280. if (isEnabled()
  44281. && ! (isDragging || e.mouseWasClicked()
  44282. || e.getDistanceFromDragStart() < 5
  44283. || e.mods.isPopupMenu()))
  44284. {
  44285. isDragging = true;
  44286. Rectangle<int> pos;
  44287. TreeViewItem* const item = findItemAt (e.getMouseDownY(), pos);
  44288. if (item != 0 && e.getMouseDownX() >= pos.getX())
  44289. {
  44290. const String dragDescription (item->getDragSourceDescription());
  44291. if (dragDescription.isNotEmpty())
  44292. {
  44293. DragAndDropContainer* const dragContainer
  44294. = DragAndDropContainer::findParentDragContainerFor (this);
  44295. if (dragContainer != 0)
  44296. {
  44297. pos.setSize (pos.getWidth(), item->itemHeight);
  44298. Image dragImage (Component::createComponentSnapshot (pos, true));
  44299. dragImage.multiplyAllAlphas (0.6f);
  44300. Point<int> imageOffset (pos.getPosition() - e.getPosition());
  44301. dragContainer->startDragging (dragDescription, &owner, dragImage, true, &imageOffset);
  44302. }
  44303. else
  44304. {
  44305. // to be able to do a drag-and-drop operation, the treeview needs to
  44306. // be inside a component which is also a DragAndDropContainer.
  44307. jassertfalse;
  44308. }
  44309. }
  44310. }
  44311. }
  44312. }
  44313. void mouseMove (const MouseEvent& e)
  44314. {
  44315. updateButtonUnderMouse (e);
  44316. }
  44317. void mouseExit (const MouseEvent& e)
  44318. {
  44319. updateButtonUnderMouse (e);
  44320. }
  44321. void paint (Graphics& g)
  44322. {
  44323. if (owner.rootItem != 0)
  44324. {
  44325. owner.handleAsyncUpdate();
  44326. if (! owner.rootItemVisible)
  44327. g.setOrigin (0, -owner.rootItem->itemHeight);
  44328. owner.rootItem->paintRecursively (g, getWidth());
  44329. }
  44330. }
  44331. TreeViewItem* findItemAt (int y, Rectangle<int>& itemPosition) const
  44332. {
  44333. if (owner.rootItem != 0)
  44334. {
  44335. owner.handleAsyncUpdate();
  44336. if (! owner.rootItemVisible)
  44337. y += owner.rootItem->itemHeight;
  44338. TreeViewItem* const ti = owner.rootItem->findItemRecursively (y);
  44339. if (ti != 0)
  44340. itemPosition = ti->getItemPosition (false);
  44341. return ti;
  44342. }
  44343. return 0;
  44344. }
  44345. void updateComponents()
  44346. {
  44347. const int visibleTop = -getY();
  44348. const int visibleBottom = visibleTop + getParentHeight();
  44349. BigInteger itemsToKeep;
  44350. {
  44351. TreeViewItem* item = owner.rootItem;
  44352. int y = (item != 0 && ! owner.rootItemVisible) ? -item->itemHeight : 0;
  44353. while (item != 0 && y < visibleBottom)
  44354. {
  44355. y += item->itemHeight;
  44356. if (y >= visibleTop)
  44357. {
  44358. const int index = rowComponentIds.indexOf (item->uid);
  44359. if (index < 0)
  44360. {
  44361. Component* const comp = item->createItemComponent();
  44362. if (comp != 0)
  44363. {
  44364. addAndMakeVisible (comp);
  44365. itemsToKeep.setBit (rowComponentItems.size());
  44366. rowComponentItems.add (item);
  44367. rowComponentIds.add (item->uid);
  44368. rowComponents.add (comp);
  44369. }
  44370. }
  44371. else
  44372. {
  44373. itemsToKeep.setBit (index);
  44374. }
  44375. }
  44376. item = item->getNextVisibleItem (true);
  44377. }
  44378. }
  44379. for (int i = rowComponentItems.size(); --i >= 0;)
  44380. {
  44381. Component* const comp = rowComponents.getUnchecked(i);
  44382. bool keep = false;
  44383. if (isParentOf (comp))
  44384. {
  44385. if (itemsToKeep[i])
  44386. {
  44387. const TreeViewItem* const item = rowComponentItems.getUnchecked(i);
  44388. Rectangle<int> pos (item->getItemPosition (false));
  44389. pos.setSize (pos.getWidth(), item->itemHeight);
  44390. if (pos.getBottom() >= visibleTop && pos.getY() < visibleBottom)
  44391. {
  44392. keep = true;
  44393. comp->setBounds (pos);
  44394. }
  44395. }
  44396. if ((! keep) && isMouseDraggingInChildCompOf (comp))
  44397. {
  44398. keep = true;
  44399. comp->setSize (0, 0);
  44400. }
  44401. }
  44402. if (! keep)
  44403. {
  44404. delete comp;
  44405. rowComponents.remove (i);
  44406. rowComponentIds.remove (i);
  44407. rowComponentItems.remove (i);
  44408. }
  44409. }
  44410. }
  44411. void updateButtonUnderMouse (const MouseEvent& e)
  44412. {
  44413. TreeViewItem* newItem = 0;
  44414. if (owner.openCloseButtonsVisible)
  44415. {
  44416. Rectangle<int> pos;
  44417. TreeViewItem* item = findItemAt (e.y, pos);
  44418. if (item != 0 && e.x < pos.getX() && e.x >= pos.getX() - owner.getIndentSize())
  44419. {
  44420. newItem = item;
  44421. if (! newItem->mightContainSubItems())
  44422. newItem = 0;
  44423. }
  44424. }
  44425. if (buttonUnderMouse != newItem)
  44426. {
  44427. if (buttonUnderMouse != 0 && containsItem (buttonUnderMouse))
  44428. {
  44429. const Rectangle<int> r (buttonUnderMouse->getItemPosition (false));
  44430. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  44431. }
  44432. buttonUnderMouse = newItem;
  44433. if (buttonUnderMouse != 0)
  44434. {
  44435. const Rectangle<int> r (buttonUnderMouse->getItemPosition (false));
  44436. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  44437. }
  44438. }
  44439. }
  44440. bool isMouseOverButton (TreeViewItem* const item) const throw()
  44441. {
  44442. return item == buttonUnderMouse;
  44443. }
  44444. void resized()
  44445. {
  44446. owner.itemsChanged();
  44447. }
  44448. const String getTooltip()
  44449. {
  44450. Rectangle<int> pos;
  44451. TreeViewItem* const item = findItemAt (getMouseXYRelative().getY(), pos);
  44452. if (item != 0)
  44453. return item->getTooltip();
  44454. return owner.getTooltip();
  44455. }
  44456. juce_UseDebuggingNewOperator
  44457. private:
  44458. TreeView& owner;
  44459. Array <TreeViewItem*> rowComponentItems;
  44460. Array <int> rowComponentIds;
  44461. Array <Component*> rowComponents;
  44462. TreeViewItem* buttonUnderMouse;
  44463. bool isDragging, needSelectionOnMouseUp;
  44464. void selectBasedOnModifiers (TreeViewItem* const item, const ModifierKeys& modifiers)
  44465. {
  44466. TreeViewItem* firstSelected = 0;
  44467. if (modifiers.isShiftDown() && ((firstSelected = owner.getSelectedItem (0)) != 0))
  44468. {
  44469. TreeViewItem* const lastSelected = owner.getSelectedItem (owner.getNumSelectedItems() - 1);
  44470. jassert (lastSelected != 0);
  44471. int rowStart = firstSelected->getRowNumberInTree();
  44472. int rowEnd = lastSelected->getRowNumberInTree();
  44473. if (rowStart > rowEnd)
  44474. swapVariables (rowStart, rowEnd);
  44475. int ourRow = item->getRowNumberInTree();
  44476. int otherEnd = ourRow < rowEnd ? rowStart : rowEnd;
  44477. if (ourRow > otherEnd)
  44478. swapVariables (ourRow, otherEnd);
  44479. for (int i = ourRow; i <= otherEnd; ++i)
  44480. owner.getItemOnRow (i)->setSelected (true, false);
  44481. }
  44482. else
  44483. {
  44484. const bool cmd = modifiers.isCommandDown();
  44485. item->setSelected ((! cmd) || ! item->isSelected(), ! cmd);
  44486. }
  44487. }
  44488. bool containsItem (TreeViewItem* const item) const
  44489. {
  44490. for (int i = rowComponentItems.size(); --i >= 0;)
  44491. if (rowComponentItems.getUnchecked(i) == item)
  44492. return true;
  44493. return false;
  44494. }
  44495. static bool isMouseDraggingInChildCompOf (Component* const comp)
  44496. {
  44497. for (int i = Desktop::getInstance().getNumMouseSources(); --i >= 0;)
  44498. {
  44499. MouseInputSource* const source = Desktop::getInstance().getMouseSource(i);
  44500. if (source->isDragging())
  44501. {
  44502. Component* const underMouse = source->getComponentUnderMouse();
  44503. if (underMouse != 0 && (comp == underMouse || comp->isParentOf (underMouse)))
  44504. return true;
  44505. }
  44506. }
  44507. return false;
  44508. }
  44509. TreeViewContentComponent (const TreeViewContentComponent&);
  44510. TreeViewContentComponent& operator= (const TreeViewContentComponent&);
  44511. };
  44512. class TreeView::TreeViewport : public Viewport
  44513. {
  44514. public:
  44515. TreeViewport() throw() : lastX (-1) {}
  44516. ~TreeViewport() throw() {}
  44517. void updateComponents (const bool triggerResize = false)
  44518. {
  44519. TreeViewContentComponent* const tvc = static_cast <TreeViewContentComponent*> (getViewedComponent());
  44520. if (tvc != 0)
  44521. {
  44522. if (triggerResize)
  44523. tvc->resized();
  44524. else
  44525. tvc->updateComponents();
  44526. }
  44527. repaint();
  44528. }
  44529. void visibleAreaChanged (int x, int, int, int)
  44530. {
  44531. const bool hasScrolledSideways = (x != lastX);
  44532. lastX = x;
  44533. updateComponents (hasScrolledSideways);
  44534. }
  44535. juce_UseDebuggingNewOperator
  44536. private:
  44537. int lastX;
  44538. TreeViewport (const TreeViewport&);
  44539. TreeViewport& operator= (const TreeViewport&);
  44540. };
  44541. TreeView::TreeView (const String& componentName)
  44542. : Component (componentName),
  44543. rootItem (0),
  44544. indentSize (24),
  44545. defaultOpenness (false),
  44546. needsRecalculating (true),
  44547. rootItemVisible (true),
  44548. multiSelectEnabled (false),
  44549. openCloseButtonsVisible (true)
  44550. {
  44551. addAndMakeVisible (viewport = new TreeViewport());
  44552. viewport->setViewedComponent (new TreeViewContentComponent (*this));
  44553. viewport->setWantsKeyboardFocus (false);
  44554. setWantsKeyboardFocus (true);
  44555. }
  44556. TreeView::~TreeView()
  44557. {
  44558. if (rootItem != 0)
  44559. rootItem->setOwnerView (0);
  44560. }
  44561. void TreeView::setRootItem (TreeViewItem* const newRootItem)
  44562. {
  44563. if (rootItem != newRootItem)
  44564. {
  44565. if (newRootItem != 0)
  44566. {
  44567. jassert (newRootItem->ownerView == 0); // can't use a tree item in more than one tree at once..
  44568. if (newRootItem->ownerView != 0)
  44569. newRootItem->ownerView->setRootItem (0);
  44570. }
  44571. if (rootItem != 0)
  44572. rootItem->setOwnerView (0);
  44573. rootItem = newRootItem;
  44574. if (newRootItem != 0)
  44575. newRootItem->setOwnerView (this);
  44576. needsRecalculating = true;
  44577. handleAsyncUpdate();
  44578. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  44579. {
  44580. rootItem->setOpen (false); // force a re-open
  44581. rootItem->setOpen (true);
  44582. }
  44583. }
  44584. }
  44585. void TreeView::deleteRootItem()
  44586. {
  44587. const ScopedPointer <TreeViewItem> deleter (rootItem);
  44588. setRootItem (0);
  44589. }
  44590. void TreeView::setRootItemVisible (const bool shouldBeVisible)
  44591. {
  44592. rootItemVisible = shouldBeVisible;
  44593. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  44594. {
  44595. rootItem->setOpen (false); // force a re-open
  44596. rootItem->setOpen (true);
  44597. }
  44598. itemsChanged();
  44599. }
  44600. void TreeView::colourChanged()
  44601. {
  44602. setOpaque (findColour (backgroundColourId).isOpaque());
  44603. repaint();
  44604. }
  44605. void TreeView::setIndentSize (const int newIndentSize)
  44606. {
  44607. if (indentSize != newIndentSize)
  44608. {
  44609. indentSize = newIndentSize;
  44610. resized();
  44611. }
  44612. }
  44613. void TreeView::setDefaultOpenness (const bool isOpenByDefault)
  44614. {
  44615. if (defaultOpenness != isOpenByDefault)
  44616. {
  44617. defaultOpenness = isOpenByDefault;
  44618. itemsChanged();
  44619. }
  44620. }
  44621. void TreeView::setMultiSelectEnabled (const bool canMultiSelect)
  44622. {
  44623. multiSelectEnabled = canMultiSelect;
  44624. }
  44625. void TreeView::setOpenCloseButtonsVisible (const bool shouldBeVisible)
  44626. {
  44627. if (openCloseButtonsVisible != shouldBeVisible)
  44628. {
  44629. openCloseButtonsVisible = shouldBeVisible;
  44630. itemsChanged();
  44631. }
  44632. }
  44633. Viewport* TreeView::getViewport() const throw()
  44634. {
  44635. return viewport;
  44636. }
  44637. void TreeView::clearSelectedItems()
  44638. {
  44639. if (rootItem != 0)
  44640. rootItem->deselectAllRecursively();
  44641. }
  44642. int TreeView::getNumSelectedItems() const throw()
  44643. {
  44644. return (rootItem != 0) ? rootItem->countSelectedItemsRecursively() : 0;
  44645. }
  44646. TreeViewItem* TreeView::getSelectedItem (const int index) const throw()
  44647. {
  44648. return (rootItem != 0) ? rootItem->getSelectedItemWithIndex (index) : 0;
  44649. }
  44650. int TreeView::getNumRowsInTree() const
  44651. {
  44652. if (rootItem != 0)
  44653. return rootItem->getNumRows() - (rootItemVisible ? 0 : 1);
  44654. return 0;
  44655. }
  44656. TreeViewItem* TreeView::getItemOnRow (int index) const
  44657. {
  44658. if (! rootItemVisible)
  44659. ++index;
  44660. if (rootItem != 0 && index >= 0)
  44661. return rootItem->getItemOnRow (index);
  44662. return 0;
  44663. }
  44664. TreeViewItem* TreeView::getItemAt (int y) const throw()
  44665. {
  44666. TreeViewContentComponent* const tc = static_cast <TreeViewContentComponent*> (viewport->getViewedComponent());
  44667. Rectangle<int> pos;
  44668. return tc->findItemAt (relativePositionToOtherComponent (tc, Point<int> (0, y)).getY(), pos);
  44669. }
  44670. TreeViewItem* TreeView::findItemFromIdentifierString (const String& identifierString) const
  44671. {
  44672. if (rootItem == 0)
  44673. return 0;
  44674. return rootItem->findItemFromIdentifierString (identifierString);
  44675. }
  44676. XmlElement* TreeView::getOpennessState (const bool alsoIncludeScrollPosition) const
  44677. {
  44678. XmlElement* e = 0;
  44679. if (rootItem != 0)
  44680. {
  44681. e = rootItem->getOpennessState();
  44682. if (e != 0 && alsoIncludeScrollPosition)
  44683. e->setAttribute ("scrollPos", viewport->getViewPositionY());
  44684. }
  44685. return e;
  44686. }
  44687. void TreeView::restoreOpennessState (const XmlElement& newState)
  44688. {
  44689. if (rootItem != 0)
  44690. {
  44691. rootItem->restoreOpennessState (newState);
  44692. if (newState.hasAttribute ("scrollPos"))
  44693. viewport->setViewPosition (viewport->getViewPositionX(),
  44694. newState.getIntAttribute ("scrollPos"));
  44695. }
  44696. }
  44697. void TreeView::paint (Graphics& g)
  44698. {
  44699. g.fillAll (findColour (backgroundColourId));
  44700. }
  44701. void TreeView::resized()
  44702. {
  44703. viewport->setBounds (0, 0, getWidth(), getHeight());
  44704. itemsChanged();
  44705. handleAsyncUpdate();
  44706. }
  44707. void TreeView::enablementChanged()
  44708. {
  44709. repaint();
  44710. }
  44711. void TreeView::moveSelectedRow (int delta)
  44712. {
  44713. if (delta == 0)
  44714. return;
  44715. int rowSelected = 0;
  44716. TreeViewItem* const firstSelected = getSelectedItem (0);
  44717. if (firstSelected != 0)
  44718. rowSelected = firstSelected->getRowNumberInTree();
  44719. rowSelected = jlimit (0, getNumRowsInTree() - 1, rowSelected + delta);
  44720. for (;;)
  44721. {
  44722. TreeViewItem* item = getItemOnRow (rowSelected);
  44723. if (item != 0)
  44724. {
  44725. if (! item->canBeSelected())
  44726. {
  44727. // if the row we want to highlight doesn't allow it, try skipping
  44728. // to the next item..
  44729. const int nextRowToTry = jlimit (0, getNumRowsInTree() - 1,
  44730. rowSelected + (delta < 0 ? -1 : 1));
  44731. if (rowSelected != nextRowToTry)
  44732. {
  44733. rowSelected = nextRowToTry;
  44734. continue;
  44735. }
  44736. else
  44737. {
  44738. break;
  44739. }
  44740. }
  44741. item->setSelected (true, true);
  44742. scrollToKeepItemVisible (item);
  44743. }
  44744. break;
  44745. }
  44746. }
  44747. void TreeView::scrollToKeepItemVisible (TreeViewItem* item)
  44748. {
  44749. if (item != 0 && item->ownerView == this)
  44750. {
  44751. handleAsyncUpdate();
  44752. item = item->getDeepestOpenParentItem();
  44753. int y = item->y;
  44754. int viewTop = viewport->getViewPositionY();
  44755. if (y < viewTop)
  44756. {
  44757. viewport->setViewPosition (viewport->getViewPositionX(), y);
  44758. }
  44759. else if (y + item->itemHeight > viewTop + viewport->getViewHeight())
  44760. {
  44761. viewport->setViewPosition (viewport->getViewPositionX(),
  44762. (y + item->itemHeight) - viewport->getViewHeight());
  44763. }
  44764. }
  44765. }
  44766. bool TreeView::keyPressed (const KeyPress& key)
  44767. {
  44768. if (key.isKeyCode (KeyPress::upKey))
  44769. {
  44770. moveSelectedRow (-1);
  44771. }
  44772. else if (key.isKeyCode (KeyPress::downKey))
  44773. {
  44774. moveSelectedRow (1);
  44775. }
  44776. else if (key.isKeyCode (KeyPress::pageDownKey) || key.isKeyCode (KeyPress::pageUpKey))
  44777. {
  44778. if (rootItem != 0)
  44779. {
  44780. int rowsOnScreen = getHeight() / jmax (1, rootItem->itemHeight);
  44781. if (key.isKeyCode (KeyPress::pageUpKey))
  44782. rowsOnScreen = -rowsOnScreen;
  44783. moveSelectedRow (rowsOnScreen);
  44784. }
  44785. }
  44786. else if (key.isKeyCode (KeyPress::homeKey))
  44787. {
  44788. moveSelectedRow (-0x3fffffff);
  44789. }
  44790. else if (key.isKeyCode (KeyPress::endKey))
  44791. {
  44792. moveSelectedRow (0x3fffffff);
  44793. }
  44794. else if (key.isKeyCode (KeyPress::returnKey))
  44795. {
  44796. TreeViewItem* const firstSelected = getSelectedItem (0);
  44797. if (firstSelected != 0)
  44798. firstSelected->setOpen (! firstSelected->isOpen());
  44799. }
  44800. else if (key.isKeyCode (KeyPress::leftKey))
  44801. {
  44802. TreeViewItem* const firstSelected = getSelectedItem (0);
  44803. if (firstSelected != 0)
  44804. {
  44805. if (firstSelected->isOpen())
  44806. {
  44807. firstSelected->setOpen (false);
  44808. }
  44809. else
  44810. {
  44811. TreeViewItem* parent = firstSelected->parentItem;
  44812. if ((! rootItemVisible) && parent == rootItem)
  44813. parent = 0;
  44814. if (parent != 0)
  44815. {
  44816. parent->setSelected (true, true);
  44817. scrollToKeepItemVisible (parent);
  44818. }
  44819. }
  44820. }
  44821. }
  44822. else if (key.isKeyCode (KeyPress::rightKey))
  44823. {
  44824. TreeViewItem* const firstSelected = getSelectedItem (0);
  44825. if (firstSelected != 0)
  44826. {
  44827. if (firstSelected->isOpen() || ! firstSelected->mightContainSubItems())
  44828. moveSelectedRow (1);
  44829. else
  44830. firstSelected->setOpen (true);
  44831. }
  44832. }
  44833. else
  44834. {
  44835. return false;
  44836. }
  44837. return true;
  44838. }
  44839. void TreeView::itemsChanged() throw()
  44840. {
  44841. needsRecalculating = true;
  44842. repaint();
  44843. triggerAsyncUpdate();
  44844. }
  44845. void TreeView::handleAsyncUpdate()
  44846. {
  44847. if (needsRecalculating)
  44848. {
  44849. needsRecalculating = false;
  44850. const ScopedLock sl (nodeAlterationLock);
  44851. if (rootItem != 0)
  44852. rootItem->updatePositions (rootItemVisible ? 0 : -rootItem->itemHeight);
  44853. viewport->updateComponents();
  44854. if (rootItem != 0)
  44855. {
  44856. viewport->getViewedComponent()
  44857. ->setSize (jmax (viewport->getMaximumVisibleWidth(), rootItem->totalWidth),
  44858. rootItem->totalHeight - (rootItemVisible ? 0 : rootItem->itemHeight));
  44859. }
  44860. else
  44861. {
  44862. viewport->getViewedComponent()->setSize (0, 0);
  44863. }
  44864. }
  44865. }
  44866. class TreeView::InsertPointHighlight : public Component
  44867. {
  44868. public:
  44869. InsertPointHighlight()
  44870. : lastItem (0)
  44871. {
  44872. setSize (100, 12);
  44873. setAlwaysOnTop (true);
  44874. setInterceptsMouseClicks (false, false);
  44875. }
  44876. ~InsertPointHighlight() {}
  44877. void setTargetPosition (TreeViewItem* const item, int insertIndex, const int x, const int y, const int width) throw()
  44878. {
  44879. lastItem = item;
  44880. lastIndex = insertIndex;
  44881. const int offset = getHeight() / 2;
  44882. setBounds (x - offset, y - offset, width - (x - offset), getHeight());
  44883. }
  44884. void paint (Graphics& g)
  44885. {
  44886. Path p;
  44887. const float h = (float) getHeight();
  44888. p.addEllipse (2.0f, 2.0f, h - 4.0f, h - 4.0f);
  44889. p.startNewSubPath (h - 2.0f, h / 2.0f);
  44890. p.lineTo ((float) getWidth(), h / 2.0f);
  44891. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  44892. g.strokePath (p, PathStrokeType (2.0f));
  44893. }
  44894. TreeViewItem* lastItem;
  44895. int lastIndex;
  44896. private:
  44897. InsertPointHighlight (const InsertPointHighlight&);
  44898. InsertPointHighlight& operator= (const InsertPointHighlight&);
  44899. };
  44900. class TreeView::TargetGroupHighlight : public Component
  44901. {
  44902. public:
  44903. TargetGroupHighlight()
  44904. {
  44905. setAlwaysOnTop (true);
  44906. setInterceptsMouseClicks (false, false);
  44907. }
  44908. ~TargetGroupHighlight() {}
  44909. void setTargetPosition (TreeViewItem* const item) throw()
  44910. {
  44911. Rectangle<int> r (item->getItemPosition (true));
  44912. r.setHeight (item->getItemHeight());
  44913. setBounds (r);
  44914. }
  44915. void paint (Graphics& g)
  44916. {
  44917. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  44918. g.drawRoundedRectangle (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 3.0f, 2.0f);
  44919. }
  44920. private:
  44921. TargetGroupHighlight (const TargetGroupHighlight&);
  44922. TargetGroupHighlight& operator= (const TargetGroupHighlight&);
  44923. };
  44924. void TreeView::showDragHighlight (TreeViewItem* item, int insertIndex, int x, int y) throw()
  44925. {
  44926. beginDragAutoRepeat (1000 / 30);
  44927. if (dragInsertPointHighlight == 0)
  44928. {
  44929. addAndMakeVisible (dragInsertPointHighlight = new InsertPointHighlight());
  44930. addAndMakeVisible (dragTargetGroupHighlight = new TargetGroupHighlight());
  44931. }
  44932. dragInsertPointHighlight->setTargetPosition (item, insertIndex, x, y, viewport->getViewWidth());
  44933. dragTargetGroupHighlight->setTargetPosition (item);
  44934. }
  44935. void TreeView::hideDragHighlight() throw()
  44936. {
  44937. dragInsertPointHighlight = 0;
  44938. dragTargetGroupHighlight = 0;
  44939. }
  44940. TreeViewItem* TreeView::getInsertPosition (int& x, int& y, int& insertIndex,
  44941. const StringArray& files, const String& sourceDescription,
  44942. Component* sourceComponent) const throw()
  44943. {
  44944. insertIndex = 0;
  44945. TreeViewItem* item = getItemAt (y);
  44946. if (item == 0)
  44947. return 0;
  44948. Rectangle<int> itemPos (item->getItemPosition (true));
  44949. insertIndex = item->getIndexInParent();
  44950. const int oldY = y;
  44951. y = itemPos.getY();
  44952. if (item->getNumSubItems() == 0 || ! item->isOpen())
  44953. {
  44954. if (files.size() > 0 ? item->isInterestedInFileDrag (files)
  44955. : item->isInterestedInDragSource (sourceDescription, sourceComponent))
  44956. {
  44957. // Check if we're trying to drag into an empty group item..
  44958. if (oldY > itemPos.getY() + itemPos.getHeight() / 4
  44959. && oldY < itemPos.getBottom() - itemPos.getHeight() / 4)
  44960. {
  44961. insertIndex = 0;
  44962. x = itemPos.getX() + getIndentSize();
  44963. y = itemPos.getBottom();
  44964. return item;
  44965. }
  44966. }
  44967. }
  44968. if (oldY > itemPos.getCentreY())
  44969. {
  44970. y += item->getItemHeight();
  44971. while (item->isLastOfSiblings() && item->parentItem != 0
  44972. && item->parentItem->parentItem != 0)
  44973. {
  44974. if (x > itemPos.getX())
  44975. break;
  44976. item = item->parentItem;
  44977. itemPos = item->getItemPosition (true);
  44978. insertIndex = item->getIndexInParent();
  44979. }
  44980. ++insertIndex;
  44981. }
  44982. x = itemPos.getX();
  44983. return item->parentItem;
  44984. }
  44985. void TreeView::handleDrag (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y)
  44986. {
  44987. const bool scrolled = viewport->autoScroll (x, y, 20, 10);
  44988. int insertIndex;
  44989. TreeViewItem* const item = getInsertPosition (x, y, insertIndex, files, sourceDescription, sourceComponent);
  44990. if (item != 0)
  44991. {
  44992. if (scrolled || dragInsertPointHighlight == 0
  44993. || dragInsertPointHighlight->lastItem != item
  44994. || dragInsertPointHighlight->lastIndex != insertIndex)
  44995. {
  44996. if (files.size() > 0 ? item->isInterestedInFileDrag (files)
  44997. : item->isInterestedInDragSource (sourceDescription, sourceComponent))
  44998. showDragHighlight (item, insertIndex, x, y);
  44999. else
  45000. hideDragHighlight();
  45001. }
  45002. }
  45003. else
  45004. {
  45005. hideDragHighlight();
  45006. }
  45007. }
  45008. void TreeView::handleDrop (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y)
  45009. {
  45010. hideDragHighlight();
  45011. int insertIndex;
  45012. TreeViewItem* const item = getInsertPosition (x, y, insertIndex, files, sourceDescription, sourceComponent);
  45013. if (item != 0)
  45014. {
  45015. if (files.size() > 0)
  45016. {
  45017. if (item->isInterestedInFileDrag (files))
  45018. item->filesDropped (files, insertIndex);
  45019. }
  45020. else
  45021. {
  45022. if (item->isInterestedInDragSource (sourceDescription, sourceComponent))
  45023. item->itemDropped (sourceDescription, sourceComponent, insertIndex);
  45024. }
  45025. }
  45026. }
  45027. bool TreeView::isInterestedInFileDrag (const StringArray&)
  45028. {
  45029. return true;
  45030. }
  45031. void TreeView::fileDragEnter (const StringArray& files, int x, int y)
  45032. {
  45033. fileDragMove (files, x, y);
  45034. }
  45035. void TreeView::fileDragMove (const StringArray& files, int x, int y)
  45036. {
  45037. handleDrag (files, String::empty, 0, x, y);
  45038. }
  45039. void TreeView::fileDragExit (const StringArray&)
  45040. {
  45041. hideDragHighlight();
  45042. }
  45043. void TreeView::filesDropped (const StringArray& files, int x, int y)
  45044. {
  45045. handleDrop (files, String::empty, 0, x, y);
  45046. }
  45047. bool TreeView::isInterestedInDragSource (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  45048. {
  45049. return true;
  45050. }
  45051. void TreeView::itemDragEnter (const String& sourceDescription, Component* sourceComponent, int x, int y)
  45052. {
  45053. itemDragMove (sourceDescription, sourceComponent, x, y);
  45054. }
  45055. void TreeView::itemDragMove (const String& sourceDescription, Component* sourceComponent, int x, int y)
  45056. {
  45057. handleDrag (StringArray(), sourceDescription, sourceComponent, x, y);
  45058. }
  45059. void TreeView::itemDragExit (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  45060. {
  45061. hideDragHighlight();
  45062. }
  45063. void TreeView::itemDropped (const String& sourceDescription, Component* sourceComponent, int x, int y)
  45064. {
  45065. handleDrop (StringArray(), sourceDescription, sourceComponent, x, y);
  45066. }
  45067. enum TreeViewOpenness
  45068. {
  45069. opennessDefault = 0,
  45070. opennessClosed = 1,
  45071. opennessOpen = 2
  45072. };
  45073. TreeViewItem::TreeViewItem()
  45074. : ownerView (0),
  45075. parentItem (0),
  45076. y (0),
  45077. itemHeight (0),
  45078. totalHeight (0),
  45079. selected (false),
  45080. redrawNeeded (true),
  45081. drawLinesInside (true),
  45082. drawsInLeftMargin (false),
  45083. openness (opennessDefault)
  45084. {
  45085. static int nextUID = 0;
  45086. uid = nextUID++;
  45087. }
  45088. TreeViewItem::~TreeViewItem()
  45089. {
  45090. }
  45091. const String TreeViewItem::getUniqueName() const
  45092. {
  45093. return String::empty;
  45094. }
  45095. void TreeViewItem::itemOpennessChanged (bool)
  45096. {
  45097. }
  45098. int TreeViewItem::getNumSubItems() const throw()
  45099. {
  45100. return subItems.size();
  45101. }
  45102. TreeViewItem* TreeViewItem::getSubItem (const int index) const throw()
  45103. {
  45104. return subItems [index];
  45105. }
  45106. void TreeViewItem::clearSubItems()
  45107. {
  45108. if (subItems.size() > 0)
  45109. {
  45110. if (ownerView != 0)
  45111. {
  45112. const ScopedLock sl (ownerView->nodeAlterationLock);
  45113. subItems.clear();
  45114. treeHasChanged();
  45115. }
  45116. else
  45117. {
  45118. subItems.clear();
  45119. }
  45120. }
  45121. }
  45122. void TreeViewItem::addSubItem (TreeViewItem* const newItem, const int insertPosition)
  45123. {
  45124. if (newItem != 0)
  45125. {
  45126. newItem->parentItem = this;
  45127. newItem->setOwnerView (ownerView);
  45128. newItem->y = 0;
  45129. newItem->itemHeight = newItem->getItemHeight();
  45130. newItem->totalHeight = 0;
  45131. newItem->itemWidth = newItem->getItemWidth();
  45132. newItem->totalWidth = 0;
  45133. if (ownerView != 0)
  45134. {
  45135. const ScopedLock sl (ownerView->nodeAlterationLock);
  45136. subItems.insert (insertPosition, newItem);
  45137. treeHasChanged();
  45138. if (newItem->isOpen())
  45139. newItem->itemOpennessChanged (true);
  45140. }
  45141. else
  45142. {
  45143. subItems.insert (insertPosition, newItem);
  45144. if (newItem->isOpen())
  45145. newItem->itemOpennessChanged (true);
  45146. }
  45147. }
  45148. }
  45149. void TreeViewItem::removeSubItem (const int index, const bool deleteItem)
  45150. {
  45151. if (ownerView != 0)
  45152. {
  45153. const ScopedLock sl (ownerView->nodeAlterationLock);
  45154. if (((unsigned int) index) < (unsigned int) subItems.size())
  45155. {
  45156. subItems.remove (index, deleteItem);
  45157. treeHasChanged();
  45158. }
  45159. }
  45160. else
  45161. {
  45162. subItems.remove (index, deleteItem);
  45163. }
  45164. }
  45165. bool TreeViewItem::isOpen() const throw()
  45166. {
  45167. if (openness == opennessDefault)
  45168. return ownerView != 0 && ownerView->defaultOpenness;
  45169. else
  45170. return openness == opennessOpen;
  45171. }
  45172. void TreeViewItem::setOpen (const bool shouldBeOpen)
  45173. {
  45174. if (isOpen() != shouldBeOpen)
  45175. {
  45176. openness = shouldBeOpen ? opennessOpen
  45177. : opennessClosed;
  45178. treeHasChanged();
  45179. itemOpennessChanged (isOpen());
  45180. }
  45181. }
  45182. bool TreeViewItem::isSelected() const throw()
  45183. {
  45184. return selected;
  45185. }
  45186. void TreeViewItem::deselectAllRecursively()
  45187. {
  45188. setSelected (false, false);
  45189. for (int i = 0; i < subItems.size(); ++i)
  45190. subItems.getUnchecked(i)->deselectAllRecursively();
  45191. }
  45192. void TreeViewItem::setSelected (const bool shouldBeSelected,
  45193. const bool deselectOtherItemsFirst)
  45194. {
  45195. if (shouldBeSelected && ! canBeSelected())
  45196. return;
  45197. if (deselectOtherItemsFirst)
  45198. getTopLevelItem()->deselectAllRecursively();
  45199. if (shouldBeSelected != selected)
  45200. {
  45201. selected = shouldBeSelected;
  45202. if (ownerView != 0)
  45203. ownerView->repaint();
  45204. itemSelectionChanged (shouldBeSelected);
  45205. }
  45206. }
  45207. void TreeViewItem::paintItem (Graphics&, int, int)
  45208. {
  45209. }
  45210. void TreeViewItem::paintOpenCloseButton (Graphics& g, int width, int height, bool isMouseOver)
  45211. {
  45212. ownerView->getLookAndFeel()
  45213. .drawTreeviewPlusMinusBox (g, 0, 0, width, height, ! isOpen(), isMouseOver);
  45214. }
  45215. void TreeViewItem::itemClicked (const MouseEvent&)
  45216. {
  45217. }
  45218. void TreeViewItem::itemDoubleClicked (const MouseEvent&)
  45219. {
  45220. if (mightContainSubItems())
  45221. setOpen (! isOpen());
  45222. }
  45223. void TreeViewItem::itemSelectionChanged (bool)
  45224. {
  45225. }
  45226. const String TreeViewItem::getTooltip()
  45227. {
  45228. return String::empty;
  45229. }
  45230. const String TreeViewItem::getDragSourceDescription()
  45231. {
  45232. return String::empty;
  45233. }
  45234. bool TreeViewItem::isInterestedInFileDrag (const StringArray&)
  45235. {
  45236. return false;
  45237. }
  45238. void TreeViewItem::filesDropped (const StringArray& /*files*/, int /*insertIndex*/)
  45239. {
  45240. }
  45241. bool TreeViewItem::isInterestedInDragSource (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  45242. {
  45243. return false;
  45244. }
  45245. void TreeViewItem::itemDropped (const String& /*sourceDescription*/, Component* /*sourceComponent*/, int /*insertIndex*/)
  45246. {
  45247. }
  45248. const Rectangle<int> TreeViewItem::getItemPosition (const bool relativeToTreeViewTopLeft) const throw()
  45249. {
  45250. const int indentX = getIndentX();
  45251. int width = itemWidth;
  45252. if (ownerView != 0 && width < 0)
  45253. width = ownerView->viewport->getViewWidth() - indentX;
  45254. Rectangle<int> r (indentX, y, jmax (0, width), totalHeight);
  45255. if (relativeToTreeViewTopLeft)
  45256. r -= ownerView->viewport->getViewPosition();
  45257. return r;
  45258. }
  45259. void TreeViewItem::treeHasChanged() const throw()
  45260. {
  45261. if (ownerView != 0)
  45262. ownerView->itemsChanged();
  45263. }
  45264. void TreeViewItem::repaintItem() const
  45265. {
  45266. if (ownerView != 0 && areAllParentsOpen())
  45267. {
  45268. Rectangle<int> r (getItemPosition (true));
  45269. r.setLeft (0);
  45270. ownerView->viewport->repaint (r);
  45271. }
  45272. }
  45273. bool TreeViewItem::areAllParentsOpen() const throw()
  45274. {
  45275. return parentItem == 0
  45276. || (parentItem->isOpen() && parentItem->areAllParentsOpen());
  45277. }
  45278. void TreeViewItem::updatePositions (int newY)
  45279. {
  45280. y = newY;
  45281. itemHeight = getItemHeight();
  45282. totalHeight = itemHeight;
  45283. itemWidth = getItemWidth();
  45284. totalWidth = jmax (itemWidth, 0) + getIndentX();
  45285. if (isOpen())
  45286. {
  45287. newY += totalHeight;
  45288. for (int i = 0; i < subItems.size(); ++i)
  45289. {
  45290. TreeViewItem* const ti = subItems.getUnchecked(i);
  45291. ti->updatePositions (newY);
  45292. newY += ti->totalHeight;
  45293. totalHeight += ti->totalHeight;
  45294. totalWidth = jmax (totalWidth, ti->totalWidth);
  45295. }
  45296. }
  45297. }
  45298. TreeViewItem* TreeViewItem::getDeepestOpenParentItem() throw()
  45299. {
  45300. TreeViewItem* result = this;
  45301. TreeViewItem* item = this;
  45302. while (item->parentItem != 0)
  45303. {
  45304. item = item->parentItem;
  45305. if (! item->isOpen())
  45306. result = item;
  45307. }
  45308. return result;
  45309. }
  45310. void TreeViewItem::setOwnerView (TreeView* const newOwner) throw()
  45311. {
  45312. ownerView = newOwner;
  45313. for (int i = subItems.size(); --i >= 0;)
  45314. subItems.getUnchecked(i)->setOwnerView (newOwner);
  45315. }
  45316. int TreeViewItem::getIndentX() const throw()
  45317. {
  45318. const int indentWidth = ownerView->getIndentSize();
  45319. int x = ownerView->rootItemVisible ? indentWidth : 0;
  45320. if (! ownerView->openCloseButtonsVisible)
  45321. x -= indentWidth;
  45322. TreeViewItem* p = parentItem;
  45323. while (p != 0)
  45324. {
  45325. x += indentWidth;
  45326. p = p->parentItem;
  45327. }
  45328. return x;
  45329. }
  45330. void TreeViewItem::setDrawsInLeftMargin (bool canDrawInLeftMargin) throw()
  45331. {
  45332. drawsInLeftMargin = canDrawInLeftMargin;
  45333. }
  45334. void TreeViewItem::paintRecursively (Graphics& g, int width)
  45335. {
  45336. jassert (ownerView != 0);
  45337. if (ownerView == 0)
  45338. return;
  45339. const int indent = getIndentX();
  45340. const int itemW = itemWidth < 0 ? width - indent : itemWidth;
  45341. g.setColour (ownerView->findColour (TreeView::linesColourId));
  45342. const float halfH = itemHeight * 0.5f;
  45343. int depth = 0;
  45344. TreeViewItem* p = parentItem;
  45345. while (p != 0)
  45346. {
  45347. ++depth;
  45348. p = p->parentItem;
  45349. }
  45350. if (! ownerView->rootItemVisible)
  45351. --depth;
  45352. const int indentWidth = ownerView->getIndentSize();
  45353. if (depth >= 0 && ownerView->openCloseButtonsVisible)
  45354. {
  45355. float x = (depth + 0.5f) * indentWidth;
  45356. if (depth >= 0)
  45357. {
  45358. if (parentItem != 0 && parentItem->drawLinesInside)
  45359. g.drawLine (x, 0, x, isLastOfSiblings() ? halfH : (float) itemHeight);
  45360. if ((parentItem != 0 && parentItem->drawLinesInside)
  45361. || (parentItem == 0 && drawLinesInside))
  45362. g.drawLine (x, halfH, x + indentWidth / 2, halfH);
  45363. }
  45364. p = parentItem;
  45365. int d = depth;
  45366. while (p != 0 && --d >= 0)
  45367. {
  45368. x -= (float) indentWidth;
  45369. if ((p->parentItem == 0 || p->parentItem->drawLinesInside)
  45370. && ! p->isLastOfSiblings())
  45371. {
  45372. g.drawLine (x, 0, x, (float) itemHeight);
  45373. }
  45374. p = p->parentItem;
  45375. }
  45376. if (mightContainSubItems())
  45377. {
  45378. g.saveState();
  45379. g.setOrigin (depth * indentWidth, 0);
  45380. g.reduceClipRegion (0, 0, indentWidth, itemHeight);
  45381. paintOpenCloseButton (g, indentWidth, itemHeight,
  45382. static_cast <TreeViewContentComponent*> (ownerView->viewport->getViewedComponent())
  45383. ->isMouseOverButton (this));
  45384. g.restoreState();
  45385. }
  45386. }
  45387. {
  45388. g.saveState();
  45389. g.setOrigin (indent, 0);
  45390. if (g.reduceClipRegion (drawsInLeftMargin ? -indent : 0, 0,
  45391. drawsInLeftMargin ? itemW + indent : itemW, itemHeight))
  45392. paintItem (g, itemW, itemHeight);
  45393. g.restoreState();
  45394. }
  45395. if (isOpen())
  45396. {
  45397. const Rectangle<int> clip (g.getClipBounds());
  45398. for (int i = 0; i < subItems.size(); ++i)
  45399. {
  45400. TreeViewItem* const ti = subItems.getUnchecked(i);
  45401. const int relY = ti->y - y;
  45402. if (relY >= clip.getBottom())
  45403. break;
  45404. if (relY + ti->totalHeight >= clip.getY())
  45405. {
  45406. g.saveState();
  45407. g.setOrigin (0, relY);
  45408. if (g.reduceClipRegion (0, 0, width, ti->totalHeight))
  45409. ti->paintRecursively (g, width);
  45410. g.restoreState();
  45411. }
  45412. }
  45413. }
  45414. }
  45415. bool TreeViewItem::isLastOfSiblings() const throw()
  45416. {
  45417. return parentItem == 0
  45418. || parentItem->subItems.getLast() == this;
  45419. }
  45420. int TreeViewItem::getIndexInParent() const throw()
  45421. {
  45422. if (parentItem == 0)
  45423. return 0;
  45424. return parentItem->subItems.indexOf (this);
  45425. }
  45426. TreeViewItem* TreeViewItem::getTopLevelItem() throw()
  45427. {
  45428. return (parentItem == 0) ? this
  45429. : parentItem->getTopLevelItem();
  45430. }
  45431. int TreeViewItem::getNumRows() const throw()
  45432. {
  45433. int num = 1;
  45434. if (isOpen())
  45435. {
  45436. for (int i = subItems.size(); --i >= 0;)
  45437. num += subItems.getUnchecked(i)->getNumRows();
  45438. }
  45439. return num;
  45440. }
  45441. TreeViewItem* TreeViewItem::getItemOnRow (int index) throw()
  45442. {
  45443. if (index == 0)
  45444. return this;
  45445. if (index > 0 && isOpen())
  45446. {
  45447. --index;
  45448. for (int i = 0; i < subItems.size(); ++i)
  45449. {
  45450. TreeViewItem* const item = subItems.getUnchecked(i);
  45451. if (index == 0)
  45452. return item;
  45453. const int numRows = item->getNumRows();
  45454. if (numRows > index)
  45455. return item->getItemOnRow (index);
  45456. index -= numRows;
  45457. }
  45458. }
  45459. return 0;
  45460. }
  45461. TreeViewItem* TreeViewItem::findItemRecursively (int targetY) throw()
  45462. {
  45463. if (((unsigned int) targetY) < (unsigned int) totalHeight)
  45464. {
  45465. const int h = itemHeight;
  45466. if (targetY < h)
  45467. return this;
  45468. if (isOpen())
  45469. {
  45470. targetY -= h;
  45471. for (int i = 0; i < subItems.size(); ++i)
  45472. {
  45473. TreeViewItem* const ti = subItems.getUnchecked(i);
  45474. if (targetY < ti->totalHeight)
  45475. return ti->findItemRecursively (targetY);
  45476. targetY -= ti->totalHeight;
  45477. }
  45478. }
  45479. }
  45480. return 0;
  45481. }
  45482. int TreeViewItem::countSelectedItemsRecursively() const throw()
  45483. {
  45484. int total = 0;
  45485. if (isSelected())
  45486. ++total;
  45487. for (int i = subItems.size(); --i >= 0;)
  45488. total += subItems.getUnchecked(i)->countSelectedItemsRecursively();
  45489. return total;
  45490. }
  45491. TreeViewItem* TreeViewItem::getSelectedItemWithIndex (int index) throw()
  45492. {
  45493. if (isSelected())
  45494. {
  45495. if (index == 0)
  45496. return this;
  45497. --index;
  45498. }
  45499. if (index >= 0)
  45500. {
  45501. for (int i = 0; i < subItems.size(); ++i)
  45502. {
  45503. TreeViewItem* const item = subItems.getUnchecked(i);
  45504. TreeViewItem* const found = item->getSelectedItemWithIndex (index);
  45505. if (found != 0)
  45506. return found;
  45507. index -= item->countSelectedItemsRecursively();
  45508. }
  45509. }
  45510. return 0;
  45511. }
  45512. int TreeViewItem::getRowNumberInTree() const throw()
  45513. {
  45514. if (parentItem != 0 && ownerView != 0)
  45515. {
  45516. int n = 1 + parentItem->getRowNumberInTree();
  45517. int ourIndex = parentItem->subItems.indexOf (this);
  45518. jassert (ourIndex >= 0);
  45519. while (--ourIndex >= 0)
  45520. n += parentItem->subItems [ourIndex]->getNumRows();
  45521. if (parentItem->parentItem == 0
  45522. && ! ownerView->rootItemVisible)
  45523. --n;
  45524. return n;
  45525. }
  45526. else
  45527. {
  45528. return 0;
  45529. }
  45530. }
  45531. void TreeViewItem::setLinesDrawnForSubItems (const bool drawLines) throw()
  45532. {
  45533. drawLinesInside = drawLines;
  45534. }
  45535. TreeViewItem* TreeViewItem::getNextVisibleItem (const bool recurse) const throw()
  45536. {
  45537. if (recurse && isOpen() && subItems.size() > 0)
  45538. return subItems [0];
  45539. if (parentItem != 0)
  45540. {
  45541. const int nextIndex = parentItem->subItems.indexOf (this) + 1;
  45542. if (nextIndex >= parentItem->subItems.size())
  45543. return parentItem->getNextVisibleItem (false);
  45544. return parentItem->subItems [nextIndex];
  45545. }
  45546. return 0;
  45547. }
  45548. const String TreeViewItem::getItemIdentifierString() const
  45549. {
  45550. String s;
  45551. if (parentItem != 0)
  45552. s = parentItem->getItemIdentifierString();
  45553. return s + "/" + getUniqueName().replaceCharacter ('/', '\\');
  45554. }
  45555. TreeViewItem* TreeViewItem::findItemFromIdentifierString (const String& identifierString)
  45556. {
  45557. const String thisId (getUniqueName());
  45558. if (thisId == identifierString)
  45559. return this;
  45560. if (identifierString.startsWith (thisId + "/"))
  45561. {
  45562. const String remainingPath (identifierString.substring (thisId.length() + 1));
  45563. bool wasOpen = isOpen();
  45564. setOpen (true);
  45565. for (int i = subItems.size(); --i >= 0;)
  45566. {
  45567. TreeViewItem* item = subItems.getUnchecked(i)->findItemFromIdentifierString (remainingPath);
  45568. if (item != 0)
  45569. return item;
  45570. }
  45571. setOpen (wasOpen);
  45572. }
  45573. return 0;
  45574. }
  45575. void TreeViewItem::restoreOpennessState (const XmlElement& e) throw()
  45576. {
  45577. if (e.hasTagName ("CLOSED"))
  45578. {
  45579. setOpen (false);
  45580. }
  45581. else if (e.hasTagName ("OPEN"))
  45582. {
  45583. setOpen (true);
  45584. forEachXmlChildElement (e, n)
  45585. {
  45586. const String id (n->getStringAttribute ("id"));
  45587. for (int i = 0; i < subItems.size(); ++i)
  45588. {
  45589. TreeViewItem* const ti = subItems.getUnchecked(i);
  45590. if (ti->getUniqueName() == id)
  45591. {
  45592. ti->restoreOpennessState (*n);
  45593. break;
  45594. }
  45595. }
  45596. }
  45597. }
  45598. }
  45599. XmlElement* TreeViewItem::getOpennessState() const throw()
  45600. {
  45601. const String name (getUniqueName());
  45602. if (name.isNotEmpty())
  45603. {
  45604. XmlElement* e;
  45605. if (isOpen())
  45606. {
  45607. e = new XmlElement ("OPEN");
  45608. for (int i = 0; i < subItems.size(); ++i)
  45609. e->addChildElement (subItems.getUnchecked(i)->getOpennessState());
  45610. }
  45611. else
  45612. {
  45613. e = new XmlElement ("CLOSED");
  45614. }
  45615. e->setAttribute ("id", name);
  45616. return e;
  45617. }
  45618. else
  45619. {
  45620. // trying to save the openness for an element that has no name - this won't
  45621. // work because it needs the names to identify what to open.
  45622. jassertfalse;
  45623. }
  45624. return 0;
  45625. }
  45626. END_JUCE_NAMESPACE
  45627. /*** End of inlined file: juce_TreeView.cpp ***/
  45628. /*** Start of inlined file: juce_DirectoryContentsDisplayComponent.cpp ***/
  45629. BEGIN_JUCE_NAMESPACE
  45630. DirectoryContentsDisplayComponent::DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow)
  45631. : fileList (listToShow)
  45632. {
  45633. }
  45634. DirectoryContentsDisplayComponent::~DirectoryContentsDisplayComponent()
  45635. {
  45636. }
  45637. FileBrowserListener::~FileBrowserListener()
  45638. {
  45639. }
  45640. void DirectoryContentsDisplayComponent::addListener (FileBrowserListener* const listener)
  45641. {
  45642. listeners.add (listener);
  45643. }
  45644. void DirectoryContentsDisplayComponent::removeListener (FileBrowserListener* const listener)
  45645. {
  45646. listeners.remove (listener);
  45647. }
  45648. void DirectoryContentsDisplayComponent::sendSelectionChangeMessage()
  45649. {
  45650. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  45651. listeners.callChecked (checker, &FileBrowserListener::selectionChanged);
  45652. }
  45653. void DirectoryContentsDisplayComponent::sendMouseClickMessage (const File& file, const MouseEvent& e)
  45654. {
  45655. if (fileList.getDirectory().exists())
  45656. {
  45657. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  45658. listeners.callChecked (checker, &FileBrowserListener::fileClicked, file, e);
  45659. }
  45660. }
  45661. void DirectoryContentsDisplayComponent::sendDoubleClickMessage (const File& file)
  45662. {
  45663. if (fileList.getDirectory().exists())
  45664. {
  45665. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  45666. listeners.callChecked (checker, &FileBrowserListener::fileDoubleClicked, file);
  45667. }
  45668. }
  45669. END_JUCE_NAMESPACE
  45670. /*** End of inlined file: juce_DirectoryContentsDisplayComponent.cpp ***/
  45671. /*** Start of inlined file: juce_DirectoryContentsList.cpp ***/
  45672. BEGIN_JUCE_NAMESPACE
  45673. DirectoryContentsList::DirectoryContentsList (const FileFilter* const fileFilter_,
  45674. TimeSliceThread& thread_)
  45675. : fileFilter (fileFilter_),
  45676. thread (thread_),
  45677. fileTypeFlags (File::ignoreHiddenFiles | File::findFiles),
  45678. fileFindHandle (0),
  45679. shouldStop (true)
  45680. {
  45681. }
  45682. DirectoryContentsList::~DirectoryContentsList()
  45683. {
  45684. clear();
  45685. }
  45686. void DirectoryContentsList::setIgnoresHiddenFiles (const bool shouldIgnoreHiddenFiles)
  45687. {
  45688. setTypeFlags (shouldIgnoreHiddenFiles ? (fileTypeFlags | File::ignoreHiddenFiles)
  45689. : (fileTypeFlags & ~File::ignoreHiddenFiles));
  45690. }
  45691. bool DirectoryContentsList::ignoresHiddenFiles() const
  45692. {
  45693. return (fileTypeFlags & File::ignoreHiddenFiles) != 0;
  45694. }
  45695. const File& DirectoryContentsList::getDirectory() const
  45696. {
  45697. return root;
  45698. }
  45699. void DirectoryContentsList::setDirectory (const File& directory,
  45700. const bool includeDirectories,
  45701. const bool includeFiles)
  45702. {
  45703. jassert (includeDirectories || includeFiles); // you have to speciify at least one of these!
  45704. if (directory != root)
  45705. {
  45706. clear();
  45707. root = directory;
  45708. // (this forces a refresh when setTypeFlags() is called, rather than triggering two refreshes)
  45709. fileTypeFlags &= ~(File::findDirectories | File::findFiles);
  45710. }
  45711. int newFlags = fileTypeFlags;
  45712. if (includeDirectories) newFlags |= File::findDirectories; else newFlags &= ~File::findDirectories;
  45713. if (includeFiles) newFlags |= File::findFiles; else newFlags &= ~File::findFiles;
  45714. setTypeFlags (newFlags);
  45715. }
  45716. void DirectoryContentsList::setTypeFlags (const int newFlags)
  45717. {
  45718. if (fileTypeFlags != newFlags)
  45719. {
  45720. fileTypeFlags = newFlags;
  45721. refresh();
  45722. }
  45723. }
  45724. void DirectoryContentsList::clear()
  45725. {
  45726. shouldStop = true;
  45727. thread.removeTimeSliceClient (this);
  45728. fileFindHandle = 0;
  45729. if (files.size() > 0)
  45730. {
  45731. files.clear();
  45732. changed();
  45733. }
  45734. }
  45735. void DirectoryContentsList::refresh()
  45736. {
  45737. clear();
  45738. if (root.isDirectory())
  45739. {
  45740. fileFindHandle = new DirectoryIterator (root, false, "*", fileTypeFlags);
  45741. shouldStop = false;
  45742. thread.addTimeSliceClient (this);
  45743. }
  45744. }
  45745. int DirectoryContentsList::getNumFiles() const
  45746. {
  45747. return files.size();
  45748. }
  45749. bool DirectoryContentsList::getFileInfo (const int index,
  45750. FileInfo& result) const
  45751. {
  45752. const ScopedLock sl (fileListLock);
  45753. const FileInfo* const info = files [index];
  45754. if (info != 0)
  45755. {
  45756. result = *info;
  45757. return true;
  45758. }
  45759. return false;
  45760. }
  45761. const File DirectoryContentsList::getFile (const int index) const
  45762. {
  45763. const ScopedLock sl (fileListLock);
  45764. const FileInfo* const info = files [index];
  45765. if (info != 0)
  45766. return root.getChildFile (info->filename);
  45767. return File::nonexistent;
  45768. }
  45769. bool DirectoryContentsList::isStillLoading() const
  45770. {
  45771. return fileFindHandle != 0;
  45772. }
  45773. void DirectoryContentsList::changed()
  45774. {
  45775. sendChangeMessage (this);
  45776. }
  45777. bool DirectoryContentsList::useTimeSlice()
  45778. {
  45779. const uint32 startTime = Time::getApproximateMillisecondCounter();
  45780. bool hasChanged = false;
  45781. for (int i = 100; --i >= 0;)
  45782. {
  45783. if (! checkNextFile (hasChanged))
  45784. {
  45785. if (hasChanged)
  45786. changed();
  45787. return false;
  45788. }
  45789. if (shouldStop || (Time::getApproximateMillisecondCounter() > startTime + 150))
  45790. break;
  45791. }
  45792. if (hasChanged)
  45793. changed();
  45794. return true;
  45795. }
  45796. bool DirectoryContentsList::checkNextFile (bool& hasChanged)
  45797. {
  45798. if (fileFindHandle != 0)
  45799. {
  45800. bool fileFoundIsDir, isHidden, isReadOnly;
  45801. int64 fileSize;
  45802. Time modTime, creationTime;
  45803. if (fileFindHandle->next (&fileFoundIsDir, &isHidden, &fileSize,
  45804. &modTime, &creationTime, &isReadOnly))
  45805. {
  45806. if (addFile (fileFindHandle->getFile(), fileFoundIsDir,
  45807. fileSize, modTime, creationTime, isReadOnly))
  45808. {
  45809. hasChanged = true;
  45810. }
  45811. return true;
  45812. }
  45813. else
  45814. {
  45815. fileFindHandle = 0;
  45816. }
  45817. }
  45818. return false;
  45819. }
  45820. int DirectoryContentsList::compareElements (const DirectoryContentsList::FileInfo* const first,
  45821. const DirectoryContentsList::FileInfo* const second)
  45822. {
  45823. #if JUCE_WINDOWS
  45824. if (first->isDirectory != second->isDirectory)
  45825. return first->isDirectory ? -1 : 1;
  45826. #endif
  45827. return first->filename.compareIgnoreCase (second->filename);
  45828. }
  45829. bool DirectoryContentsList::addFile (const File& file,
  45830. const bool isDir,
  45831. const int64 fileSize,
  45832. const Time& modTime,
  45833. const Time& creationTime,
  45834. const bool isReadOnly)
  45835. {
  45836. if (fileFilter == 0
  45837. || ((! isDir) && fileFilter->isFileSuitable (file))
  45838. || (isDir && fileFilter->isDirectorySuitable (file)))
  45839. {
  45840. ScopedPointer <FileInfo> info (new FileInfo());
  45841. info->filename = file.getFileName();
  45842. info->fileSize = fileSize;
  45843. info->modificationTime = modTime;
  45844. info->creationTime = creationTime;
  45845. info->isDirectory = isDir;
  45846. info->isReadOnly = isReadOnly;
  45847. const ScopedLock sl (fileListLock);
  45848. for (int i = files.size(); --i >= 0;)
  45849. if (files.getUnchecked(i)->filename == info->filename)
  45850. return false;
  45851. files.addSorted (*this, info.release());
  45852. return true;
  45853. }
  45854. return false;
  45855. }
  45856. END_JUCE_NAMESPACE
  45857. /*** End of inlined file: juce_DirectoryContentsList.cpp ***/
  45858. /*** Start of inlined file: juce_FileBrowserComponent.cpp ***/
  45859. BEGIN_JUCE_NAMESPACE
  45860. FileBrowserComponent::FileBrowserComponent (int flags_,
  45861. const File& initialFileOrDirectory,
  45862. const FileFilter* fileFilter_,
  45863. FilePreviewComponent* previewComp_)
  45864. : FileFilter (String::empty),
  45865. fileFilter (fileFilter_),
  45866. flags (flags_),
  45867. previewComp (previewComp_),
  45868. thread ("Juce FileBrowser")
  45869. {
  45870. // You need to specify one or other of the open/save flags..
  45871. jassert ((flags & (saveMode | openMode)) != 0);
  45872. jassert ((flags & (saveMode | openMode)) != (saveMode | openMode));
  45873. // You need to specify at least one of these flags..
  45874. jassert ((flags & (canSelectFiles | canSelectDirectories)) != 0);
  45875. String filename;
  45876. if (initialFileOrDirectory == File::nonexistent)
  45877. {
  45878. currentRoot = File::getCurrentWorkingDirectory();
  45879. }
  45880. else if (initialFileOrDirectory.isDirectory())
  45881. {
  45882. currentRoot = initialFileOrDirectory;
  45883. }
  45884. else
  45885. {
  45886. chosenFiles.add (initialFileOrDirectory);
  45887. currentRoot = initialFileOrDirectory.getParentDirectory();
  45888. filename = initialFileOrDirectory.getFileName();
  45889. }
  45890. fileList = new DirectoryContentsList (this, thread);
  45891. if ((flags & useTreeView) != 0)
  45892. {
  45893. FileTreeComponent* const tree = new FileTreeComponent (*fileList);
  45894. if ((flags & canSelectMultipleItems) != 0)
  45895. tree->setMultiSelectEnabled (true);
  45896. addAndMakeVisible (tree);
  45897. fileListComponent = tree;
  45898. }
  45899. else
  45900. {
  45901. FileListComponent* const list = new FileListComponent (*fileList);
  45902. list->setOutlineThickness (1);
  45903. if ((flags & canSelectMultipleItems) != 0)
  45904. list->setMultipleSelectionEnabled (true);
  45905. addAndMakeVisible (list);
  45906. fileListComponent = list;
  45907. }
  45908. fileListComponent->addListener (this);
  45909. addAndMakeVisible (currentPathBox = new ComboBox ("path"));
  45910. currentPathBox->setEditableText (true);
  45911. StringArray rootNames, rootPaths;
  45912. const BigInteger separators (getRoots (rootNames, rootPaths));
  45913. for (int i = 0; i < rootNames.size(); ++i)
  45914. {
  45915. if (separators [i])
  45916. currentPathBox->addSeparator();
  45917. currentPathBox->addItem (rootNames[i], i + 1);
  45918. }
  45919. currentPathBox->addSeparator();
  45920. currentPathBox->addListener (this);
  45921. addAndMakeVisible (filenameBox = new TextEditor());
  45922. filenameBox->setMultiLine (false);
  45923. filenameBox->setSelectAllWhenFocused (true);
  45924. filenameBox->setText (filename, false);
  45925. filenameBox->addListener (this);
  45926. filenameBox->setReadOnly ((flags & (filenameBoxIsReadOnly | canSelectMultipleItems)) != 0);
  45927. Label* label = new Label ("f", TRANS("file:"));
  45928. addAndMakeVisible (label);
  45929. label->attachToComponent (filenameBox, true);
  45930. addAndMakeVisible (goUpButton = getLookAndFeel().createFileBrowserGoUpButton());
  45931. goUpButton->addButtonListener (this);
  45932. goUpButton->setTooltip (TRANS ("go up to parent directory"));
  45933. if (previewComp != 0)
  45934. addAndMakeVisible (previewComp);
  45935. setRoot (currentRoot);
  45936. thread.startThread (4);
  45937. }
  45938. FileBrowserComponent::~FileBrowserComponent()
  45939. {
  45940. if (previewComp != 0)
  45941. removeChildComponent (previewComp);
  45942. deleteAllChildren();
  45943. fileList = 0;
  45944. thread.stopThread (10000);
  45945. }
  45946. void FileBrowserComponent::addListener (FileBrowserListener* const newListener)
  45947. {
  45948. listeners.add (newListener);
  45949. }
  45950. void FileBrowserComponent::removeListener (FileBrowserListener* const listener)
  45951. {
  45952. listeners.remove (listener);
  45953. }
  45954. bool FileBrowserComponent::isSaveMode() const throw()
  45955. {
  45956. return (flags & saveMode) != 0;
  45957. }
  45958. int FileBrowserComponent::getNumSelectedFiles() const throw()
  45959. {
  45960. if (chosenFiles.size() == 0 && currentFileIsValid())
  45961. return 1;
  45962. return chosenFiles.size();
  45963. }
  45964. const File FileBrowserComponent::getSelectedFile (int index) const throw()
  45965. {
  45966. if ((flags & canSelectDirectories) != 0 && filenameBox->getText().isEmpty())
  45967. return currentRoot;
  45968. if (! filenameBox->isReadOnly())
  45969. return currentRoot.getChildFile (filenameBox->getText());
  45970. return chosenFiles[index];
  45971. }
  45972. bool FileBrowserComponent::currentFileIsValid() const
  45973. {
  45974. if (isSaveMode())
  45975. return ! getSelectedFile (0).isDirectory();
  45976. else
  45977. return getSelectedFile (0).exists();
  45978. }
  45979. const File FileBrowserComponent::getHighlightedFile() const throw()
  45980. {
  45981. return fileListComponent->getSelectedFile (0);
  45982. }
  45983. void FileBrowserComponent::deselectAllFiles()
  45984. {
  45985. fileListComponent->deselectAllFiles();
  45986. }
  45987. bool FileBrowserComponent::isFileSuitable (const File& file) const
  45988. {
  45989. return (flags & canSelectFiles) != 0 ? (fileFilter == 0 || fileFilter->isFileSuitable (file))
  45990. : false;
  45991. }
  45992. bool FileBrowserComponent::isDirectorySuitable (const File&) const
  45993. {
  45994. return true;
  45995. }
  45996. bool FileBrowserComponent::isFileOrDirSuitable (const File& f) const
  45997. {
  45998. if (f.isDirectory())
  45999. return (flags & canSelectDirectories) != 0 && (fileFilter == 0 || fileFilter->isDirectorySuitable (f));
  46000. return (flags & canSelectFiles) != 0 && f.exists()
  46001. && (fileFilter == 0 || fileFilter->isFileSuitable (f));
  46002. }
  46003. const File FileBrowserComponent::getRoot() const
  46004. {
  46005. return currentRoot;
  46006. }
  46007. void FileBrowserComponent::setRoot (const File& newRootDirectory)
  46008. {
  46009. if (currentRoot != newRootDirectory)
  46010. {
  46011. fileListComponent->scrollToTop();
  46012. String path (newRootDirectory.getFullPathName());
  46013. if (path.isEmpty())
  46014. path = File::separatorString;
  46015. StringArray rootNames, rootPaths;
  46016. getRoots (rootNames, rootPaths);
  46017. if (! rootPaths.contains (path, true))
  46018. {
  46019. bool alreadyListed = false;
  46020. for (int i = currentPathBox->getNumItems(); --i >= 0;)
  46021. {
  46022. if (currentPathBox->getItemText (i).equalsIgnoreCase (path))
  46023. {
  46024. alreadyListed = true;
  46025. break;
  46026. }
  46027. }
  46028. if (! alreadyListed)
  46029. currentPathBox->addItem (path, currentPathBox->getNumItems() + 2);
  46030. }
  46031. }
  46032. currentRoot = newRootDirectory;
  46033. fileList->setDirectory (currentRoot, true, true);
  46034. String currentRootName (currentRoot.getFullPathName());
  46035. if (currentRootName.isEmpty())
  46036. currentRootName = File::separatorString;
  46037. currentPathBox->setText (currentRootName, true);
  46038. goUpButton->setEnabled (currentRoot.getParentDirectory().isDirectory()
  46039. && currentRoot.getParentDirectory() != currentRoot);
  46040. }
  46041. void FileBrowserComponent::goUp()
  46042. {
  46043. setRoot (getRoot().getParentDirectory());
  46044. }
  46045. void FileBrowserComponent::refresh()
  46046. {
  46047. fileList->refresh();
  46048. }
  46049. const String FileBrowserComponent::getActionVerb() const
  46050. {
  46051. return isSaveMode() ? TRANS("Save") : TRANS("Open");
  46052. }
  46053. FilePreviewComponent* FileBrowserComponent::getPreviewComponent() const throw()
  46054. {
  46055. return previewComp;
  46056. }
  46057. void FileBrowserComponent::resized()
  46058. {
  46059. getLookAndFeel()
  46060. .layoutFileBrowserComponent (*this, fileListComponent,
  46061. previewComp, currentPathBox,
  46062. filenameBox, goUpButton);
  46063. }
  46064. void FileBrowserComponent::sendListenerChangeMessage()
  46065. {
  46066. Component::BailOutChecker checker (this);
  46067. if (previewComp != 0)
  46068. previewComp->selectedFileChanged (getSelectedFile (0));
  46069. // You shouldn't delete the browser when the file gets changed!
  46070. jassert (! checker.shouldBailOut());
  46071. listeners.callChecked (checker, &FileBrowserListener::selectionChanged);
  46072. }
  46073. void FileBrowserComponent::selectionChanged()
  46074. {
  46075. StringArray newFilenames;
  46076. bool resetChosenFiles = true;
  46077. for (int i = 0; i < fileListComponent->getNumSelectedFiles(); ++i)
  46078. {
  46079. const File f (fileListComponent->getSelectedFile (i));
  46080. if (isFileOrDirSuitable (f))
  46081. {
  46082. if (resetChosenFiles)
  46083. {
  46084. chosenFiles.clear();
  46085. resetChosenFiles = false;
  46086. }
  46087. chosenFiles.add (f);
  46088. newFilenames.add (f.getRelativePathFrom (getRoot()));
  46089. }
  46090. }
  46091. if (newFilenames.size() > 0)
  46092. filenameBox->setText (newFilenames.joinIntoString (", "), false);
  46093. sendListenerChangeMessage();
  46094. }
  46095. void FileBrowserComponent::fileClicked (const File& f, const MouseEvent& e)
  46096. {
  46097. Component::BailOutChecker checker (this);
  46098. listeners.callChecked (checker, &FileBrowserListener::fileClicked, f, e);
  46099. }
  46100. void FileBrowserComponent::fileDoubleClicked (const File& f)
  46101. {
  46102. if (f.isDirectory())
  46103. {
  46104. setRoot (f);
  46105. if ((flags & canSelectDirectories) != 0)
  46106. filenameBox->setText (String::empty);
  46107. }
  46108. else
  46109. {
  46110. Component::BailOutChecker checker (this);
  46111. listeners.callChecked (checker, &FileBrowserListener::fileDoubleClicked, f);
  46112. }
  46113. }
  46114. bool FileBrowserComponent::keyPressed (const KeyPress& key)
  46115. {
  46116. (void) key;
  46117. #if JUCE_LINUX || JUCE_WINDOWS
  46118. if (key.getModifiers().isCommandDown()
  46119. && (key.getKeyCode() == 'H' || key.getKeyCode() == 'h'))
  46120. {
  46121. fileList->setIgnoresHiddenFiles (! fileList->ignoresHiddenFiles());
  46122. fileList->refresh();
  46123. return true;
  46124. }
  46125. #endif
  46126. return false;
  46127. }
  46128. void FileBrowserComponent::textEditorTextChanged (TextEditor&)
  46129. {
  46130. sendListenerChangeMessage();
  46131. }
  46132. void FileBrowserComponent::textEditorReturnKeyPressed (TextEditor&)
  46133. {
  46134. if (filenameBox->getText().containsChar (File::separator))
  46135. {
  46136. const File f (currentRoot.getChildFile (filenameBox->getText()));
  46137. if (f.isDirectory())
  46138. {
  46139. setRoot (f);
  46140. chosenFiles.clear();
  46141. filenameBox->setText (String::empty);
  46142. }
  46143. else
  46144. {
  46145. setRoot (f.getParentDirectory());
  46146. chosenFiles.clear();
  46147. chosenFiles.add (f);
  46148. filenameBox->setText (f.getFileName());
  46149. }
  46150. }
  46151. else
  46152. {
  46153. fileDoubleClicked (getSelectedFile (0));
  46154. }
  46155. }
  46156. void FileBrowserComponent::textEditorEscapeKeyPressed (TextEditor&)
  46157. {
  46158. }
  46159. void FileBrowserComponent::textEditorFocusLost (TextEditor&)
  46160. {
  46161. if (! isSaveMode())
  46162. selectionChanged();
  46163. }
  46164. void FileBrowserComponent::buttonClicked (Button*)
  46165. {
  46166. goUp();
  46167. }
  46168. void FileBrowserComponent::comboBoxChanged (ComboBox*)
  46169. {
  46170. const String newText (currentPathBox->getText().trim().unquoted());
  46171. if (newText.isNotEmpty())
  46172. {
  46173. const int index = currentPathBox->getSelectedId() - 1;
  46174. StringArray rootNames, rootPaths;
  46175. getRoots (rootNames, rootPaths);
  46176. if (rootPaths [index].isNotEmpty())
  46177. {
  46178. setRoot (File (rootPaths [index]));
  46179. }
  46180. else
  46181. {
  46182. File f (newText);
  46183. for (;;)
  46184. {
  46185. if (f.isDirectory())
  46186. {
  46187. setRoot (f);
  46188. break;
  46189. }
  46190. if (f.getParentDirectory() == f)
  46191. break;
  46192. f = f.getParentDirectory();
  46193. }
  46194. }
  46195. }
  46196. }
  46197. const BigInteger FileBrowserComponent::getRoots (StringArray& rootNames, StringArray& rootPaths)
  46198. {
  46199. BigInteger separators;
  46200. #if JUCE_WINDOWS
  46201. Array<File> roots;
  46202. File::findFileSystemRoots (roots);
  46203. rootPaths.clear();
  46204. for (int i = 0; i < roots.size(); ++i)
  46205. {
  46206. const File& drive = roots.getReference(i);
  46207. String name (drive.getFullPathName());
  46208. rootPaths.add (name);
  46209. if (drive.isOnHardDisk())
  46210. {
  46211. String volume (drive.getVolumeLabel());
  46212. if (volume.isEmpty())
  46213. volume = TRANS("Hard Drive");
  46214. name << " [" << drive.getVolumeLabel() << ']';
  46215. }
  46216. else if (drive.isOnCDRomDrive())
  46217. {
  46218. name << TRANS(" [CD/DVD drive]");
  46219. }
  46220. rootNames.add (name);
  46221. }
  46222. separators.setBit (rootPaths.size());
  46223. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  46224. rootNames.add ("Documents");
  46225. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  46226. rootNames.add ("Desktop");
  46227. #endif
  46228. #if JUCE_MAC
  46229. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  46230. rootNames.add ("Home folder");
  46231. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  46232. rootNames.add ("Documents");
  46233. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  46234. rootNames.add ("Desktop");
  46235. separators.setBit (rootPaths.size());
  46236. Array <File> volumes;
  46237. File vol ("/Volumes");
  46238. vol.findChildFiles (volumes, File::findDirectories, false);
  46239. for (int i = 0; i < volumes.size(); ++i)
  46240. {
  46241. const File& volume = volumes.getReference(i);
  46242. if (volume.isDirectory() && ! volume.getFileName().startsWithChar ('.'))
  46243. {
  46244. rootPaths.add (volume.getFullPathName());
  46245. rootNames.add (volume.getFileName());
  46246. }
  46247. }
  46248. #endif
  46249. #if JUCE_LINUX
  46250. rootPaths.add ("/");
  46251. rootNames.add ("/");
  46252. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  46253. rootNames.add ("Home folder");
  46254. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  46255. rootNames.add ("Desktop");
  46256. #endif
  46257. return separators;
  46258. }
  46259. END_JUCE_NAMESPACE
  46260. /*** End of inlined file: juce_FileBrowserComponent.cpp ***/
  46261. /*** Start of inlined file: juce_FileChooser.cpp ***/
  46262. BEGIN_JUCE_NAMESPACE
  46263. FileChooser::FileChooser (const String& chooserBoxTitle,
  46264. const File& currentFileOrDirectory,
  46265. const String& fileFilters,
  46266. const bool useNativeDialogBox_)
  46267. : title (chooserBoxTitle),
  46268. filters (fileFilters),
  46269. startingFile (currentFileOrDirectory),
  46270. useNativeDialogBox (useNativeDialogBox_)
  46271. {
  46272. #if JUCE_LINUX
  46273. useNativeDialogBox = false;
  46274. #endif
  46275. if (! fileFilters.containsNonWhitespaceChars())
  46276. filters = "*";
  46277. }
  46278. FileChooser::~FileChooser()
  46279. {
  46280. }
  46281. bool FileChooser::browseForFileToOpen (FilePreviewComponent* previewComponent)
  46282. {
  46283. return showDialog (false, true, false, false, false, previewComponent);
  46284. }
  46285. bool FileChooser::browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent)
  46286. {
  46287. return showDialog (false, true, false, false, true, previewComponent);
  46288. }
  46289. bool FileChooser::browseForMultipleFilesOrDirectories (FilePreviewComponent* previewComponent)
  46290. {
  46291. return showDialog (true, true, false, false, true, previewComponent);
  46292. }
  46293. bool FileChooser::browseForFileToSave (const bool warnAboutOverwritingExistingFiles)
  46294. {
  46295. return showDialog (false, true, true, warnAboutOverwritingExistingFiles, false, 0);
  46296. }
  46297. bool FileChooser::browseForDirectory()
  46298. {
  46299. return showDialog (true, false, false, false, false, 0);
  46300. }
  46301. const File FileChooser::getResult() const
  46302. {
  46303. // if you've used a multiple-file select, you should use the getResults() method
  46304. // to retrieve all the files that were chosen.
  46305. jassert (results.size() <= 1);
  46306. return results.getFirst();
  46307. }
  46308. const Array<File>& FileChooser::getResults() const
  46309. {
  46310. return results;
  46311. }
  46312. bool FileChooser::showDialog (const bool selectsDirectories,
  46313. const bool selectsFiles,
  46314. const bool isSave,
  46315. const bool warnAboutOverwritingExistingFiles,
  46316. const bool selectMultipleFiles,
  46317. FilePreviewComponent* const previewComponent)
  46318. {
  46319. Component::SafePointer<Component> previouslyFocused (Component::getCurrentlyFocusedComponent());
  46320. results.clear();
  46321. // the preview component needs to be the right size before you pass it in here..
  46322. jassert (previewComponent == 0 || (previewComponent->getWidth() > 10
  46323. && previewComponent->getHeight() > 10));
  46324. #if JUCE_WINDOWS
  46325. if (useNativeDialogBox && ! (selectsFiles && selectsDirectories))
  46326. #elif JUCE_MAC
  46327. if (useNativeDialogBox && (previewComponent == 0))
  46328. #else
  46329. if (false)
  46330. #endif
  46331. {
  46332. showPlatformDialog (results, title, startingFile, filters,
  46333. selectsDirectories, selectsFiles, isSave,
  46334. warnAboutOverwritingExistingFiles,
  46335. selectMultipleFiles,
  46336. previewComponent);
  46337. }
  46338. else
  46339. {
  46340. WildcardFileFilter wildcard (selectsFiles ? filters : String::empty,
  46341. selectsDirectories ? "*" : String::empty,
  46342. String::empty);
  46343. int flags = isSave ? FileBrowserComponent::saveMode
  46344. : FileBrowserComponent::openMode;
  46345. if (selectsFiles)
  46346. flags |= FileBrowserComponent::canSelectFiles;
  46347. if (selectsDirectories)
  46348. {
  46349. flags |= FileBrowserComponent::canSelectDirectories;
  46350. if (! isSave)
  46351. flags |= FileBrowserComponent::filenameBoxIsReadOnly;
  46352. }
  46353. if (selectMultipleFiles)
  46354. flags |= FileBrowserComponent::canSelectMultipleItems;
  46355. FileBrowserComponent browserComponent (flags, startingFile, &wildcard, previewComponent);
  46356. FileChooserDialogBox box (title, String::empty,
  46357. browserComponent,
  46358. warnAboutOverwritingExistingFiles,
  46359. browserComponent.findColour (AlertWindow::backgroundColourId));
  46360. if (box.show())
  46361. {
  46362. for (int i = 0; i < browserComponent.getNumSelectedFiles(); ++i)
  46363. results.add (browserComponent.getSelectedFile (i));
  46364. }
  46365. }
  46366. if (previouslyFocused != 0)
  46367. previouslyFocused->grabKeyboardFocus();
  46368. return results.size() > 0;
  46369. }
  46370. FilePreviewComponent::FilePreviewComponent()
  46371. {
  46372. }
  46373. FilePreviewComponent::~FilePreviewComponent()
  46374. {
  46375. }
  46376. END_JUCE_NAMESPACE
  46377. /*** End of inlined file: juce_FileChooser.cpp ***/
  46378. /*** Start of inlined file: juce_FileChooserDialogBox.cpp ***/
  46379. BEGIN_JUCE_NAMESPACE
  46380. FileChooserDialogBox::FileChooserDialogBox (const String& name,
  46381. const String& instructions,
  46382. FileBrowserComponent& chooserComponent,
  46383. const bool warnAboutOverwritingExistingFiles_,
  46384. const Colour& backgroundColour)
  46385. : ResizableWindow (name, backgroundColour, true),
  46386. warnAboutOverwritingExistingFiles (warnAboutOverwritingExistingFiles_)
  46387. {
  46388. content = new ContentComponent();
  46389. content->setName (name);
  46390. content->instructions = instructions;
  46391. content->chooserComponent = &chooserComponent;
  46392. content->addAndMakeVisible (&chooserComponent);
  46393. content->okButton = new TextButton (chooserComponent.getActionVerb());
  46394. content->addAndMakeVisible (content->okButton);
  46395. content->okButton->addButtonListener (this);
  46396. content->okButton->setEnabled (chooserComponent.currentFileIsValid());
  46397. content->okButton->addShortcut (KeyPress (KeyPress::returnKey, 0, 0));
  46398. content->cancelButton = new TextButton (TRANS("Cancel"));
  46399. content->addAndMakeVisible (content->cancelButton);
  46400. content->cancelButton->addButtonListener (this);
  46401. content->cancelButton->addShortcut (KeyPress (KeyPress::escapeKey, 0, 0));
  46402. setContentComponent (content);
  46403. setResizable (true, true);
  46404. setResizeLimits (300, 300, 1200, 1000);
  46405. content->chooserComponent->addListener (this);
  46406. }
  46407. FileChooserDialogBox::~FileChooserDialogBox()
  46408. {
  46409. content->chooserComponent->removeListener (this);
  46410. }
  46411. bool FileChooserDialogBox::show (int w, int h)
  46412. {
  46413. if (w <= 0)
  46414. {
  46415. Component* const previewComp = content->chooserComponent->getPreviewComponent();
  46416. if (previewComp != 0)
  46417. w = 400 + previewComp->getWidth();
  46418. else
  46419. w = 600;
  46420. }
  46421. if (h <= 0)
  46422. h = 500;
  46423. centreWithSize (w, h);
  46424. const bool ok = (runModalLoop() != 0);
  46425. setVisible (false);
  46426. return ok;
  46427. }
  46428. void FileChooserDialogBox::buttonClicked (Button* button)
  46429. {
  46430. if (button == content->okButton)
  46431. {
  46432. if (warnAboutOverwritingExistingFiles
  46433. && content->chooserComponent->isSaveMode()
  46434. && content->chooserComponent->getSelectedFile(0).exists())
  46435. {
  46436. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  46437. TRANS("File already exists"),
  46438. TRANS("There's already a file called:")
  46439. + "\n\n" + content->chooserComponent->getSelectedFile(0).getFullPathName()
  46440. + "\n\n" + TRANS("Are you sure you want to overwrite it?"),
  46441. TRANS("overwrite"),
  46442. TRANS("cancel")))
  46443. {
  46444. return;
  46445. }
  46446. }
  46447. exitModalState (1);
  46448. }
  46449. else if (button == content->cancelButton)
  46450. closeButtonPressed();
  46451. }
  46452. void FileChooserDialogBox::closeButtonPressed()
  46453. {
  46454. setVisible (false);
  46455. }
  46456. void FileChooserDialogBox::selectionChanged()
  46457. {
  46458. content->okButton->setEnabled (content->chooserComponent->currentFileIsValid());
  46459. }
  46460. void FileChooserDialogBox::fileClicked (const File&, const MouseEvent&)
  46461. {
  46462. }
  46463. void FileChooserDialogBox::fileDoubleClicked (const File&)
  46464. {
  46465. selectionChanged();
  46466. content->okButton->triggerClick();
  46467. }
  46468. FileChooserDialogBox::ContentComponent::ContentComponent()
  46469. {
  46470. setInterceptsMouseClicks (false, true);
  46471. }
  46472. FileChooserDialogBox::ContentComponent::~ContentComponent()
  46473. {
  46474. delete okButton;
  46475. delete cancelButton;
  46476. }
  46477. void FileChooserDialogBox::ContentComponent::paint (Graphics& g)
  46478. {
  46479. g.setColour (getLookAndFeel().findColour (FileChooserDialogBox::titleTextColourId));
  46480. text.draw (g);
  46481. }
  46482. void FileChooserDialogBox::ContentComponent::resized()
  46483. {
  46484. getLookAndFeel().createFileChooserHeaderText (getName(), instructions, text, getWidth());
  46485. const Rectangle<float> bb (text.getBoundingBox (0, text.getNumGlyphs(), false));
  46486. const int y = roundToInt (bb.getBottom()) + 10;
  46487. const int buttonHeight = 26;
  46488. const int buttonY = getHeight() - buttonHeight - 8;
  46489. chooserComponent->setBounds (0, y, getWidth(), buttonY - y - 20);
  46490. okButton->setBounds (proportionOfWidth (0.25f), buttonY,
  46491. proportionOfWidth (0.2f), buttonHeight);
  46492. cancelButton->setBounds (proportionOfWidth (0.55f), buttonY,
  46493. proportionOfWidth (0.2f), buttonHeight);
  46494. }
  46495. END_JUCE_NAMESPACE
  46496. /*** End of inlined file: juce_FileChooserDialogBox.cpp ***/
  46497. /*** Start of inlined file: juce_FileFilter.cpp ***/
  46498. BEGIN_JUCE_NAMESPACE
  46499. FileFilter::FileFilter (const String& filterDescription)
  46500. : description (filterDescription)
  46501. {
  46502. }
  46503. FileFilter::~FileFilter()
  46504. {
  46505. }
  46506. const String& FileFilter::getDescription() const throw()
  46507. {
  46508. return description;
  46509. }
  46510. END_JUCE_NAMESPACE
  46511. /*** End of inlined file: juce_FileFilter.cpp ***/
  46512. /*** Start of inlined file: juce_FileListComponent.cpp ***/
  46513. BEGIN_JUCE_NAMESPACE
  46514. const Image juce_createIconForFile (const File& file);
  46515. FileListComponent::FileListComponent (DirectoryContentsList& listToShow)
  46516. : ListBox (String::empty, 0),
  46517. DirectoryContentsDisplayComponent (listToShow)
  46518. {
  46519. setModel (this);
  46520. fileList.addChangeListener (this);
  46521. }
  46522. FileListComponent::~FileListComponent()
  46523. {
  46524. fileList.removeChangeListener (this);
  46525. deleteAllChildren();
  46526. }
  46527. int FileListComponent::getNumSelectedFiles() const
  46528. {
  46529. return getNumSelectedRows();
  46530. }
  46531. const File FileListComponent::getSelectedFile (int index) const
  46532. {
  46533. return fileList.getFile (getSelectedRow (index));
  46534. }
  46535. void FileListComponent::deselectAllFiles()
  46536. {
  46537. deselectAllRows();
  46538. }
  46539. void FileListComponent::scrollToTop()
  46540. {
  46541. getVerticalScrollBar()->setCurrentRangeStart (0);
  46542. }
  46543. void FileListComponent::changeListenerCallback (void*)
  46544. {
  46545. updateContent();
  46546. if (lastDirectory != fileList.getDirectory())
  46547. {
  46548. lastDirectory = fileList.getDirectory();
  46549. deselectAllRows();
  46550. }
  46551. }
  46552. class FileListItemComponent : public Component,
  46553. public TimeSliceClient,
  46554. public AsyncUpdater
  46555. {
  46556. public:
  46557. FileListItemComponent (FileListComponent& owner_, TimeSliceThread& thread_)
  46558. : owner (owner_), thread (thread_),
  46559. highlighted (false), index (0), icon (0)
  46560. {
  46561. }
  46562. ~FileListItemComponent()
  46563. {
  46564. thread.removeTimeSliceClient (this);
  46565. clearIcon();
  46566. }
  46567. void paint (Graphics& g)
  46568. {
  46569. getLookAndFeel().drawFileBrowserRow (g, getWidth(), getHeight(),
  46570. file.getFileName(),
  46571. &icon,
  46572. fileSize, modTime,
  46573. isDirectory, highlighted,
  46574. index);
  46575. }
  46576. void mouseDown (const MouseEvent& e)
  46577. {
  46578. owner.selectRowsBasedOnModifierKeys (index, e.mods);
  46579. owner.sendMouseClickMessage (file, e);
  46580. }
  46581. void mouseDoubleClick (const MouseEvent&)
  46582. {
  46583. owner.sendDoubleClickMessage (file);
  46584. }
  46585. void update (const File& root,
  46586. const DirectoryContentsList::FileInfo* const fileInfo,
  46587. const int index_,
  46588. const bool highlighted_)
  46589. {
  46590. thread.removeTimeSliceClient (this);
  46591. if (highlighted_ != highlighted
  46592. || index_ != index)
  46593. {
  46594. index = index_;
  46595. highlighted = highlighted_;
  46596. repaint();
  46597. }
  46598. File newFile;
  46599. String newFileSize;
  46600. String newModTime;
  46601. if (fileInfo != 0)
  46602. {
  46603. newFile = root.getChildFile (fileInfo->filename);
  46604. newFileSize = File::descriptionOfSizeInBytes (fileInfo->fileSize);
  46605. newModTime = fileInfo->modificationTime.formatted ("%d %b '%y %H:%M");
  46606. }
  46607. if (newFile != file
  46608. || fileSize != newFileSize
  46609. || modTime != newModTime)
  46610. {
  46611. file = newFile;
  46612. fileSize = newFileSize;
  46613. modTime = newModTime;
  46614. isDirectory = fileInfo != 0 && fileInfo->isDirectory;
  46615. repaint();
  46616. clearIcon();
  46617. }
  46618. if (file != File::nonexistent && icon.isNull() && ! isDirectory)
  46619. {
  46620. updateIcon (true);
  46621. if (! icon.isValid())
  46622. thread.addTimeSliceClient (this);
  46623. }
  46624. }
  46625. bool useTimeSlice()
  46626. {
  46627. updateIcon (false);
  46628. return false;
  46629. }
  46630. void handleAsyncUpdate()
  46631. {
  46632. repaint();
  46633. }
  46634. juce_UseDebuggingNewOperator
  46635. private:
  46636. FileListComponent& owner;
  46637. TimeSliceThread& thread;
  46638. bool highlighted;
  46639. int index;
  46640. File file;
  46641. String fileSize;
  46642. String modTime;
  46643. Image icon;
  46644. bool isDirectory;
  46645. void clearIcon()
  46646. {
  46647. icon = Image();
  46648. }
  46649. void updateIcon (const bool onlyUpdateIfCached)
  46650. {
  46651. if (icon.isNull())
  46652. {
  46653. const int hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
  46654. Image im (ImageCache::getFromHashCode (hashCode));
  46655. if (im.isNull() && ! onlyUpdateIfCached)
  46656. {
  46657. im = juce_createIconForFile (file);
  46658. if (im.isValid())
  46659. ImageCache::addImageToCache (im, hashCode);
  46660. }
  46661. if (im.isValid())
  46662. {
  46663. icon = im;
  46664. triggerAsyncUpdate();
  46665. }
  46666. }
  46667. }
  46668. };
  46669. int FileListComponent::getNumRows()
  46670. {
  46671. return fileList.getNumFiles();
  46672. }
  46673. void FileListComponent::paintListBoxItem (int, Graphics&, int, int, bool)
  46674. {
  46675. }
  46676. Component* FileListComponent::refreshComponentForRow (int row, bool isSelected, Component* existingComponentToUpdate)
  46677. {
  46678. FileListItemComponent* comp = dynamic_cast <FileListItemComponent*> (existingComponentToUpdate);
  46679. if (comp == 0)
  46680. {
  46681. delete existingComponentToUpdate;
  46682. comp = new FileListItemComponent (*this, fileList.getTimeSliceThread());
  46683. }
  46684. DirectoryContentsList::FileInfo fileInfo;
  46685. if (fileList.getFileInfo (row, fileInfo))
  46686. comp->update (fileList.getDirectory(), &fileInfo, row, isSelected);
  46687. else
  46688. comp->update (fileList.getDirectory(), 0, row, isSelected);
  46689. return comp;
  46690. }
  46691. void FileListComponent::selectedRowsChanged (int /*lastRowSelected*/)
  46692. {
  46693. sendSelectionChangeMessage();
  46694. }
  46695. void FileListComponent::deleteKeyPressed (int /*currentSelectedRow*/)
  46696. {
  46697. }
  46698. void FileListComponent::returnKeyPressed (int currentSelectedRow)
  46699. {
  46700. sendDoubleClickMessage (fileList.getFile (currentSelectedRow));
  46701. }
  46702. END_JUCE_NAMESPACE
  46703. /*** End of inlined file: juce_FileListComponent.cpp ***/
  46704. /*** Start of inlined file: juce_FilenameComponent.cpp ***/
  46705. BEGIN_JUCE_NAMESPACE
  46706. FilenameComponent::FilenameComponent (const String& name,
  46707. const File& currentFile,
  46708. const bool canEditFilename,
  46709. const bool isDirectory,
  46710. const bool isForSaving,
  46711. const String& fileBrowserWildcard,
  46712. const String& enforcedSuffix_,
  46713. const String& textWhenNothingSelected)
  46714. : Component (name),
  46715. maxRecentFiles (30),
  46716. isDir (isDirectory),
  46717. isSaving (isForSaving),
  46718. isFileDragOver (false),
  46719. wildcard (fileBrowserWildcard),
  46720. enforcedSuffix (enforcedSuffix_)
  46721. {
  46722. addAndMakeVisible (&filenameBox);
  46723. filenameBox.setEditableText (canEditFilename);
  46724. filenameBox.addListener (this);
  46725. filenameBox.setTextWhenNothingSelected (textWhenNothingSelected);
  46726. filenameBox.setTextWhenNoChoicesAvailable (TRANS("(no recently seleced files)"));
  46727. setBrowseButtonText ("...");
  46728. setCurrentFile (currentFile, true);
  46729. }
  46730. FilenameComponent::~FilenameComponent()
  46731. {
  46732. }
  46733. void FilenameComponent::paintOverChildren (Graphics& g)
  46734. {
  46735. if (isFileDragOver)
  46736. {
  46737. g.setColour (Colours::red.withAlpha (0.2f));
  46738. g.drawRect (0, 0, getWidth(), getHeight(), 3);
  46739. }
  46740. }
  46741. void FilenameComponent::resized()
  46742. {
  46743. getLookAndFeel().layoutFilenameComponent (*this, &filenameBox, browseButton);
  46744. }
  46745. void FilenameComponent::setBrowseButtonText (const String& newBrowseButtonText)
  46746. {
  46747. browseButtonText = newBrowseButtonText;
  46748. lookAndFeelChanged();
  46749. }
  46750. void FilenameComponent::lookAndFeelChanged()
  46751. {
  46752. browseButton = 0;
  46753. addAndMakeVisible (browseButton = getLookAndFeel().createFilenameComponentBrowseButton (browseButtonText));
  46754. browseButton->setConnectedEdges (Button::ConnectedOnLeft);
  46755. resized();
  46756. browseButton->addButtonListener (this);
  46757. }
  46758. void FilenameComponent::setTooltip (const String& newTooltip)
  46759. {
  46760. SettableTooltipClient::setTooltip (newTooltip);
  46761. filenameBox.setTooltip (newTooltip);
  46762. }
  46763. void FilenameComponent::setDefaultBrowseTarget (const File& newDefaultDirectory)
  46764. {
  46765. defaultBrowseFile = newDefaultDirectory;
  46766. }
  46767. void FilenameComponent::buttonClicked (Button*)
  46768. {
  46769. FileChooser fc (TRANS("Choose a new file"),
  46770. getCurrentFile() == File::nonexistent ? defaultBrowseFile
  46771. : getCurrentFile(),
  46772. wildcard);
  46773. if (isDir ? fc.browseForDirectory()
  46774. : (isSaving ? fc.browseForFileToSave (false)
  46775. : fc.browseForFileToOpen()))
  46776. {
  46777. setCurrentFile (fc.getResult(), true);
  46778. }
  46779. }
  46780. void FilenameComponent::comboBoxChanged (ComboBox*)
  46781. {
  46782. setCurrentFile (getCurrentFile(), true);
  46783. }
  46784. bool FilenameComponent::isInterestedInFileDrag (const StringArray&)
  46785. {
  46786. return true;
  46787. }
  46788. void FilenameComponent::filesDropped (const StringArray& filenames, int, int)
  46789. {
  46790. isFileDragOver = false;
  46791. repaint();
  46792. const File f (filenames[0]);
  46793. if (f.exists() && (f.isDirectory() == isDir))
  46794. setCurrentFile (f, true);
  46795. }
  46796. void FilenameComponent::fileDragEnter (const StringArray&, int, int)
  46797. {
  46798. isFileDragOver = true;
  46799. repaint();
  46800. }
  46801. void FilenameComponent::fileDragExit (const StringArray&)
  46802. {
  46803. isFileDragOver = false;
  46804. repaint();
  46805. }
  46806. const File FilenameComponent::getCurrentFile() const
  46807. {
  46808. File f (filenameBox.getText());
  46809. if (enforcedSuffix.isNotEmpty())
  46810. f = f.withFileExtension (enforcedSuffix);
  46811. return f;
  46812. }
  46813. void FilenameComponent::setCurrentFile (File newFile,
  46814. const bool addToRecentlyUsedList,
  46815. const bool sendChangeNotification)
  46816. {
  46817. if (enforcedSuffix.isNotEmpty())
  46818. newFile = newFile.withFileExtension (enforcedSuffix);
  46819. if (newFile.getFullPathName() != lastFilename)
  46820. {
  46821. lastFilename = newFile.getFullPathName();
  46822. if (addToRecentlyUsedList)
  46823. addRecentlyUsedFile (newFile);
  46824. filenameBox.setText (lastFilename, true);
  46825. if (sendChangeNotification)
  46826. triggerAsyncUpdate();
  46827. }
  46828. }
  46829. void FilenameComponent::setFilenameIsEditable (const bool shouldBeEditable)
  46830. {
  46831. filenameBox.setEditableText (shouldBeEditable);
  46832. }
  46833. const StringArray FilenameComponent::getRecentlyUsedFilenames() const
  46834. {
  46835. StringArray names;
  46836. for (int i = 0; i < filenameBox.getNumItems(); ++i)
  46837. names.add (filenameBox.getItemText (i));
  46838. return names;
  46839. }
  46840. void FilenameComponent::setRecentlyUsedFilenames (const StringArray& filenames)
  46841. {
  46842. if (filenames != getRecentlyUsedFilenames())
  46843. {
  46844. filenameBox.clear();
  46845. for (int i = 0; i < jmin (filenames.size(), maxRecentFiles); ++i)
  46846. filenameBox.addItem (filenames[i], i + 1);
  46847. }
  46848. }
  46849. void FilenameComponent::setMaxNumberOfRecentFiles (const int newMaximum)
  46850. {
  46851. maxRecentFiles = jmax (1, newMaximum);
  46852. setRecentlyUsedFilenames (getRecentlyUsedFilenames());
  46853. }
  46854. void FilenameComponent::addRecentlyUsedFile (const File& file)
  46855. {
  46856. StringArray files (getRecentlyUsedFilenames());
  46857. if (file.getFullPathName().isNotEmpty())
  46858. {
  46859. files.removeString (file.getFullPathName(), true);
  46860. files.insert (0, file.getFullPathName());
  46861. setRecentlyUsedFilenames (files);
  46862. }
  46863. }
  46864. void FilenameComponent::addListener (FilenameComponentListener* const listener)
  46865. {
  46866. listeners.add (listener);
  46867. }
  46868. void FilenameComponent::removeListener (FilenameComponentListener* const listener)
  46869. {
  46870. listeners.remove (listener);
  46871. }
  46872. void FilenameComponent::handleAsyncUpdate()
  46873. {
  46874. Component::BailOutChecker checker (this);
  46875. listeners.callChecked (checker, &FilenameComponentListener::filenameComponentChanged, this);
  46876. }
  46877. END_JUCE_NAMESPACE
  46878. /*** End of inlined file: juce_FilenameComponent.cpp ***/
  46879. /*** Start of inlined file: juce_FileSearchPathListComponent.cpp ***/
  46880. BEGIN_JUCE_NAMESPACE
  46881. FileSearchPathListComponent::FileSearchPathListComponent()
  46882. {
  46883. addAndMakeVisible (listBox = new ListBox (String::empty, this));
  46884. listBox->setColour (ListBox::backgroundColourId, Colours::black.withAlpha (0.02f));
  46885. listBox->setColour (ListBox::outlineColourId, Colours::black.withAlpha (0.1f));
  46886. listBox->setOutlineThickness (1);
  46887. addAndMakeVisible (addButton = new TextButton ("+"));
  46888. addButton->addButtonListener (this);
  46889. addButton->setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  46890. addAndMakeVisible (removeButton = new TextButton ("-"));
  46891. removeButton->addButtonListener (this);
  46892. removeButton->setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  46893. addAndMakeVisible (changeButton = new TextButton (TRANS("change...")));
  46894. changeButton->addButtonListener (this);
  46895. addAndMakeVisible (upButton = new DrawableButton (String::empty, DrawableButton::ImageOnButtonBackground));
  46896. upButton->addButtonListener (this);
  46897. {
  46898. Path arrowPath;
  46899. arrowPath.addArrow (Line<float> (50.0f, 100.0f, 50.0f, 0.0f), 40.0f, 100.0f, 50.0f);
  46900. DrawablePath arrowImage;
  46901. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  46902. arrowImage.setPath (arrowPath);
  46903. upButton->setImages (&arrowImage);
  46904. }
  46905. addAndMakeVisible (downButton = new DrawableButton (String::empty, DrawableButton::ImageOnButtonBackground));
  46906. downButton->addButtonListener (this);
  46907. {
  46908. Path arrowPath;
  46909. arrowPath.addArrow (Line<float> (50.0f, 0.0f, 50.0f, 100.0f), 40.0f, 100.0f, 50.0f);
  46910. DrawablePath arrowImage;
  46911. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  46912. arrowImage.setPath (arrowPath);
  46913. downButton->setImages (&arrowImage);
  46914. }
  46915. updateButtons();
  46916. }
  46917. FileSearchPathListComponent::~FileSearchPathListComponent()
  46918. {
  46919. deleteAllChildren();
  46920. }
  46921. void FileSearchPathListComponent::updateButtons()
  46922. {
  46923. const bool anythingSelected = listBox->getNumSelectedRows() > 0;
  46924. removeButton->setEnabled (anythingSelected);
  46925. changeButton->setEnabled (anythingSelected);
  46926. upButton->setEnabled (anythingSelected);
  46927. downButton->setEnabled (anythingSelected);
  46928. }
  46929. void FileSearchPathListComponent::changed()
  46930. {
  46931. listBox->updateContent();
  46932. listBox->repaint();
  46933. updateButtons();
  46934. }
  46935. void FileSearchPathListComponent::setPath (const FileSearchPath& newPath)
  46936. {
  46937. if (newPath.toString() != path.toString())
  46938. {
  46939. path = newPath;
  46940. changed();
  46941. }
  46942. }
  46943. void FileSearchPathListComponent::setDefaultBrowseTarget (const File& newDefaultDirectory)
  46944. {
  46945. defaultBrowseTarget = newDefaultDirectory;
  46946. }
  46947. int FileSearchPathListComponent::getNumRows()
  46948. {
  46949. return path.getNumPaths();
  46950. }
  46951. void FileSearchPathListComponent::paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected)
  46952. {
  46953. if (rowIsSelected)
  46954. g.fillAll (findColour (TextEditor::highlightColourId));
  46955. g.setColour (findColour (ListBox::textColourId));
  46956. Font f (height * 0.7f);
  46957. f.setHorizontalScale (0.9f);
  46958. g.setFont (f);
  46959. g.drawText (path [rowNumber].getFullPathName(),
  46960. 4, 0, width - 6, height,
  46961. Justification::centredLeft, true);
  46962. }
  46963. void FileSearchPathListComponent::deleteKeyPressed (int row)
  46964. {
  46965. if (((unsigned int) row) < (unsigned int) path.getNumPaths())
  46966. {
  46967. path.remove (row);
  46968. changed();
  46969. }
  46970. }
  46971. void FileSearchPathListComponent::returnKeyPressed (int row)
  46972. {
  46973. FileChooser chooser (TRANS("Change folder..."), path [row], "*");
  46974. if (chooser.browseForDirectory())
  46975. {
  46976. path.remove (row);
  46977. path.add (chooser.getResult(), row);
  46978. changed();
  46979. }
  46980. }
  46981. void FileSearchPathListComponent::listBoxItemDoubleClicked (int row, const MouseEvent&)
  46982. {
  46983. returnKeyPressed (row);
  46984. }
  46985. void FileSearchPathListComponent::selectedRowsChanged (int)
  46986. {
  46987. updateButtons();
  46988. }
  46989. void FileSearchPathListComponent::paint (Graphics& g)
  46990. {
  46991. g.fillAll (findColour (backgroundColourId));
  46992. }
  46993. void FileSearchPathListComponent::resized()
  46994. {
  46995. const int buttonH = 22;
  46996. const int buttonY = getHeight() - buttonH - 4;
  46997. listBox->setBounds (2, 2, getWidth() - 4, buttonY - 5);
  46998. addButton->setBounds (2, buttonY, buttonH, buttonH);
  46999. removeButton->setBounds (addButton->getRight(), buttonY, buttonH, buttonH);
  47000. changeButton->changeWidthToFitText (buttonH);
  47001. downButton->setSize (buttonH * 2, buttonH);
  47002. upButton->setSize (buttonH * 2, buttonH);
  47003. downButton->setTopRightPosition (getWidth() - 2, buttonY);
  47004. upButton->setTopRightPosition (downButton->getX() - 4, buttonY);
  47005. changeButton->setTopRightPosition (upButton->getX() - 8, buttonY);
  47006. }
  47007. bool FileSearchPathListComponent::isInterestedInFileDrag (const StringArray&)
  47008. {
  47009. return true;
  47010. }
  47011. void FileSearchPathListComponent::filesDropped (const StringArray& filenames, int, int mouseY)
  47012. {
  47013. for (int i = filenames.size(); --i >= 0;)
  47014. {
  47015. const File f (filenames[i]);
  47016. if (f.isDirectory())
  47017. {
  47018. const int row = listBox->getRowContainingPosition (0, mouseY - listBox->getY());
  47019. path.add (f, row);
  47020. changed();
  47021. }
  47022. }
  47023. }
  47024. void FileSearchPathListComponent::buttonClicked (Button* button)
  47025. {
  47026. const int currentRow = listBox->getSelectedRow();
  47027. if (button == removeButton)
  47028. {
  47029. deleteKeyPressed (currentRow);
  47030. }
  47031. else if (button == addButton)
  47032. {
  47033. File start (defaultBrowseTarget);
  47034. if (start == File::nonexistent)
  47035. start = path [0];
  47036. if (start == File::nonexistent)
  47037. start = File::getCurrentWorkingDirectory();
  47038. FileChooser chooser (TRANS("Add a folder..."), start, "*");
  47039. if (chooser.browseForDirectory())
  47040. {
  47041. path.add (chooser.getResult(), currentRow);
  47042. }
  47043. }
  47044. else if (button == changeButton)
  47045. {
  47046. returnKeyPressed (currentRow);
  47047. }
  47048. else if (button == upButton)
  47049. {
  47050. if (currentRow > 0 && currentRow < path.getNumPaths())
  47051. {
  47052. const File f (path[currentRow]);
  47053. path.remove (currentRow);
  47054. path.add (f, currentRow - 1);
  47055. listBox->selectRow (currentRow - 1);
  47056. }
  47057. }
  47058. else if (button == downButton)
  47059. {
  47060. if (currentRow >= 0 && currentRow < path.getNumPaths() - 1)
  47061. {
  47062. const File f (path[currentRow]);
  47063. path.remove (currentRow);
  47064. path.add (f, currentRow + 1);
  47065. listBox->selectRow (currentRow + 1);
  47066. }
  47067. }
  47068. changed();
  47069. }
  47070. END_JUCE_NAMESPACE
  47071. /*** End of inlined file: juce_FileSearchPathListComponent.cpp ***/
  47072. /*** Start of inlined file: juce_FileTreeComponent.cpp ***/
  47073. BEGIN_JUCE_NAMESPACE
  47074. const Image juce_createIconForFile (const File& file);
  47075. class FileListTreeItem : public TreeViewItem,
  47076. public TimeSliceClient,
  47077. public AsyncUpdater,
  47078. public ChangeListener
  47079. {
  47080. public:
  47081. FileListTreeItem (FileTreeComponent& owner_,
  47082. DirectoryContentsList* const parentContentsList_,
  47083. const int indexInContentsList_,
  47084. const File& file_,
  47085. TimeSliceThread& thread_)
  47086. : file (file_),
  47087. owner (owner_),
  47088. parentContentsList (parentContentsList_),
  47089. indexInContentsList (indexInContentsList_),
  47090. subContentsList (0),
  47091. canDeleteSubContentsList (false),
  47092. thread (thread_),
  47093. icon (0)
  47094. {
  47095. DirectoryContentsList::FileInfo fileInfo;
  47096. if (parentContentsList_ != 0
  47097. && parentContentsList_->getFileInfo (indexInContentsList_, fileInfo))
  47098. {
  47099. fileSize = File::descriptionOfSizeInBytes (fileInfo.fileSize);
  47100. modTime = fileInfo.modificationTime.formatted ("%d %b '%y %H:%M");
  47101. isDirectory = fileInfo.isDirectory;
  47102. }
  47103. else
  47104. {
  47105. isDirectory = true;
  47106. }
  47107. }
  47108. ~FileListTreeItem()
  47109. {
  47110. thread.removeTimeSliceClient (this);
  47111. clearSubItems();
  47112. if (canDeleteSubContentsList)
  47113. delete subContentsList;
  47114. }
  47115. bool mightContainSubItems() { return isDirectory; }
  47116. const String getUniqueName() const { return file.getFullPathName(); }
  47117. int getItemHeight() const { return 22; }
  47118. const String getDragSourceDescription() { return owner.getDragAndDropDescription(); }
  47119. void itemOpennessChanged (bool isNowOpen)
  47120. {
  47121. if (isNowOpen)
  47122. {
  47123. clearSubItems();
  47124. isDirectory = file.isDirectory();
  47125. if (isDirectory)
  47126. {
  47127. if (subContentsList == 0)
  47128. {
  47129. jassert (parentContentsList != 0);
  47130. DirectoryContentsList* const l = new DirectoryContentsList (parentContentsList->getFilter(), thread);
  47131. l->setDirectory (file, true, true);
  47132. setSubContentsList (l);
  47133. canDeleteSubContentsList = true;
  47134. }
  47135. changeListenerCallback (0);
  47136. }
  47137. }
  47138. }
  47139. void setSubContentsList (DirectoryContentsList* newList)
  47140. {
  47141. jassert (subContentsList == 0);
  47142. subContentsList = newList;
  47143. newList->addChangeListener (this);
  47144. }
  47145. void changeListenerCallback (void*)
  47146. {
  47147. clearSubItems();
  47148. if (isOpen() && subContentsList != 0)
  47149. {
  47150. for (int i = 0; i < subContentsList->getNumFiles(); ++i)
  47151. {
  47152. FileListTreeItem* const item
  47153. = new FileListTreeItem (owner, subContentsList, i, subContentsList->getFile(i), thread);
  47154. addSubItem (item);
  47155. }
  47156. }
  47157. }
  47158. void paintItem (Graphics& g, int width, int height)
  47159. {
  47160. if (file != File::nonexistent)
  47161. {
  47162. updateIcon (true);
  47163. if (icon.isNull())
  47164. thread.addTimeSliceClient (this);
  47165. }
  47166. owner.getLookAndFeel()
  47167. .drawFileBrowserRow (g, width, height,
  47168. file.getFileName(),
  47169. &icon, fileSize, modTime,
  47170. isDirectory, isSelected(),
  47171. indexInContentsList);
  47172. }
  47173. void itemClicked (const MouseEvent& e)
  47174. {
  47175. owner.sendMouseClickMessage (file, e);
  47176. }
  47177. void itemDoubleClicked (const MouseEvent& e)
  47178. {
  47179. TreeViewItem::itemDoubleClicked (e);
  47180. owner.sendDoubleClickMessage (file);
  47181. }
  47182. void itemSelectionChanged (bool)
  47183. {
  47184. owner.sendSelectionChangeMessage();
  47185. }
  47186. bool useTimeSlice()
  47187. {
  47188. updateIcon (false);
  47189. thread.removeTimeSliceClient (this);
  47190. return false;
  47191. }
  47192. void handleAsyncUpdate()
  47193. {
  47194. owner.repaint();
  47195. }
  47196. const File file;
  47197. juce_UseDebuggingNewOperator
  47198. private:
  47199. FileTreeComponent& owner;
  47200. DirectoryContentsList* parentContentsList;
  47201. int indexInContentsList;
  47202. DirectoryContentsList* subContentsList;
  47203. bool isDirectory, canDeleteSubContentsList;
  47204. TimeSliceThread& thread;
  47205. Image icon;
  47206. String fileSize;
  47207. String modTime;
  47208. void updateIcon (const bool onlyUpdateIfCached)
  47209. {
  47210. if (icon.isNull())
  47211. {
  47212. const int hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
  47213. Image im (ImageCache::getFromHashCode (hashCode));
  47214. if (im.isNull() && ! onlyUpdateIfCached)
  47215. {
  47216. im = juce_createIconForFile (file);
  47217. if (im.isValid())
  47218. ImageCache::addImageToCache (im, hashCode);
  47219. }
  47220. if (im.isValid())
  47221. {
  47222. icon = im;
  47223. triggerAsyncUpdate();
  47224. }
  47225. }
  47226. }
  47227. };
  47228. FileTreeComponent::FileTreeComponent (DirectoryContentsList& listToShow)
  47229. : DirectoryContentsDisplayComponent (listToShow)
  47230. {
  47231. FileListTreeItem* const root
  47232. = new FileListTreeItem (*this, 0, 0, listToShow.getDirectory(),
  47233. listToShow.getTimeSliceThread());
  47234. root->setSubContentsList (&listToShow);
  47235. setRootItemVisible (false);
  47236. setRootItem (root);
  47237. }
  47238. FileTreeComponent::~FileTreeComponent()
  47239. {
  47240. deleteRootItem();
  47241. }
  47242. const File FileTreeComponent::getSelectedFile (const int index) const
  47243. {
  47244. const FileListTreeItem* const item = dynamic_cast <const FileListTreeItem*> (getSelectedItem (index));
  47245. return item != 0 ? item->file
  47246. : File::nonexistent;
  47247. }
  47248. void FileTreeComponent::deselectAllFiles()
  47249. {
  47250. clearSelectedItems();
  47251. }
  47252. void FileTreeComponent::scrollToTop()
  47253. {
  47254. getViewport()->getVerticalScrollBar()->setCurrentRangeStart (0);
  47255. }
  47256. void FileTreeComponent::setDragAndDropDescription (const String& description)
  47257. {
  47258. dragAndDropDescription = description;
  47259. }
  47260. END_JUCE_NAMESPACE
  47261. /*** End of inlined file: juce_FileTreeComponent.cpp ***/
  47262. /*** Start of inlined file: juce_ImagePreviewComponent.cpp ***/
  47263. BEGIN_JUCE_NAMESPACE
  47264. ImagePreviewComponent::ImagePreviewComponent()
  47265. {
  47266. }
  47267. ImagePreviewComponent::~ImagePreviewComponent()
  47268. {
  47269. }
  47270. void ImagePreviewComponent::getThumbSize (int& w, int& h) const
  47271. {
  47272. const int availableW = proportionOfWidth (0.97f);
  47273. const int availableH = getHeight() - 13 * 4;
  47274. const double scale = jmin (1.0,
  47275. availableW / (double) w,
  47276. availableH / (double) h);
  47277. w = roundToInt (scale * w);
  47278. h = roundToInt (scale * h);
  47279. }
  47280. void ImagePreviewComponent::selectedFileChanged (const File& file)
  47281. {
  47282. if (fileToLoad != file)
  47283. {
  47284. fileToLoad = file;
  47285. startTimer (100);
  47286. }
  47287. }
  47288. void ImagePreviewComponent::timerCallback()
  47289. {
  47290. stopTimer();
  47291. currentThumbnail = Image();
  47292. currentDetails = String::empty;
  47293. repaint();
  47294. ScopedPointer <FileInputStream> in (fileToLoad.createInputStream());
  47295. if (in != 0)
  47296. {
  47297. ImageFileFormat* const format = ImageFileFormat::findImageFormatForStream (*in);
  47298. if (format != 0)
  47299. {
  47300. currentThumbnail = format->decodeImage (*in);
  47301. if (currentThumbnail.isValid())
  47302. {
  47303. int w = currentThumbnail.getWidth();
  47304. int h = currentThumbnail.getHeight();
  47305. currentDetails
  47306. << fileToLoad.getFileName() << "\n"
  47307. << format->getFormatName() << "\n"
  47308. << w << " x " << h << " pixels\n"
  47309. << File::descriptionOfSizeInBytes (fileToLoad.getSize());
  47310. getThumbSize (w, h);
  47311. currentThumbnail = currentThumbnail.rescaled (w, h);
  47312. }
  47313. }
  47314. }
  47315. }
  47316. void ImagePreviewComponent::paint (Graphics& g)
  47317. {
  47318. if (currentThumbnail.isValid())
  47319. {
  47320. g.setFont (13.0f);
  47321. int w = currentThumbnail.getWidth();
  47322. int h = currentThumbnail.getHeight();
  47323. getThumbSize (w, h);
  47324. const int numLines = 4;
  47325. const int totalH = 13 * numLines + h + 4;
  47326. const int y = (getHeight() - totalH) / 2;
  47327. g.drawImageWithin (currentThumbnail,
  47328. (getWidth() - w) / 2, y, w, h,
  47329. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  47330. false);
  47331. g.drawFittedText (currentDetails,
  47332. 0, y + h + 4, getWidth(), 100,
  47333. Justification::centredTop, numLines);
  47334. }
  47335. }
  47336. END_JUCE_NAMESPACE
  47337. /*** End of inlined file: juce_ImagePreviewComponent.cpp ***/
  47338. /*** Start of inlined file: juce_WildcardFileFilter.cpp ***/
  47339. BEGIN_JUCE_NAMESPACE
  47340. WildcardFileFilter::WildcardFileFilter (const String& fileWildcardPatterns,
  47341. const String& directoryWildcardPatterns,
  47342. const String& description_)
  47343. : FileFilter (description_.isEmpty() ? fileWildcardPatterns
  47344. : (description_ + " (" + fileWildcardPatterns + ")"))
  47345. {
  47346. parse (fileWildcardPatterns, fileWildcards);
  47347. parse (directoryWildcardPatterns, directoryWildcards);
  47348. }
  47349. WildcardFileFilter::~WildcardFileFilter()
  47350. {
  47351. }
  47352. bool WildcardFileFilter::isFileSuitable (const File& file) const
  47353. {
  47354. return match (file, fileWildcards);
  47355. }
  47356. bool WildcardFileFilter::isDirectorySuitable (const File& file) const
  47357. {
  47358. return match (file, directoryWildcards);
  47359. }
  47360. void WildcardFileFilter::parse (const String& pattern, StringArray& result)
  47361. {
  47362. result.addTokens (pattern.toLowerCase(), ";,", "\"'");
  47363. result.trim();
  47364. result.removeEmptyStrings();
  47365. // special case for *.*, because people use it to mean "any file", but it
  47366. // would actually ignore files with no extension.
  47367. for (int i = result.size(); --i >= 0;)
  47368. if (result[i] == "*.*")
  47369. result.set (i, "*");
  47370. }
  47371. bool WildcardFileFilter::match (const File& file, const StringArray& wildcards)
  47372. {
  47373. const String filename (file.getFileName());
  47374. for (int i = wildcards.size(); --i >= 0;)
  47375. if (filename.matchesWildcard (wildcards[i], true))
  47376. return true;
  47377. return false;
  47378. }
  47379. END_JUCE_NAMESPACE
  47380. /*** End of inlined file: juce_WildcardFileFilter.cpp ***/
  47381. /*** Start of inlined file: juce_KeyboardFocusTraverser.cpp ***/
  47382. BEGIN_JUCE_NAMESPACE
  47383. KeyboardFocusTraverser::KeyboardFocusTraverser()
  47384. {
  47385. }
  47386. KeyboardFocusTraverser::~KeyboardFocusTraverser()
  47387. {
  47388. }
  47389. namespace KeyboardFocusHelpers
  47390. {
  47391. // This will sort a set of components, so that they are ordered in terms of
  47392. // left-to-right and then top-to-bottom.
  47393. class ScreenPositionComparator
  47394. {
  47395. public:
  47396. ScreenPositionComparator() {}
  47397. static int compareElements (const Component* const first, const Component* const second)
  47398. {
  47399. int explicitOrder1 = first->getExplicitFocusOrder();
  47400. if (explicitOrder1 <= 0)
  47401. explicitOrder1 = std::numeric_limits<int>::max() / 2;
  47402. int explicitOrder2 = second->getExplicitFocusOrder();
  47403. if (explicitOrder2 <= 0)
  47404. explicitOrder2 = std::numeric_limits<int>::max() / 2;
  47405. if (explicitOrder1 != explicitOrder2)
  47406. return explicitOrder1 - explicitOrder2;
  47407. const int diff = first->getY() - second->getY();
  47408. return (diff == 0) ? first->getX() - second->getX()
  47409. : diff;
  47410. }
  47411. };
  47412. static void findAllFocusableComponents (Component* const parent, Array <Component*>& comps)
  47413. {
  47414. if (parent->getNumChildComponents() > 0)
  47415. {
  47416. Array <Component*> localComps;
  47417. ScreenPositionComparator comparator;
  47418. int i;
  47419. for (i = parent->getNumChildComponents(); --i >= 0;)
  47420. {
  47421. Component* const c = parent->getChildComponent (i);
  47422. if (c->isVisible() && c->isEnabled())
  47423. localComps.addSorted (comparator, c);
  47424. }
  47425. for (i = 0; i < localComps.size(); ++i)
  47426. {
  47427. Component* const c = localComps.getUnchecked (i);
  47428. if (c->getWantsKeyboardFocus())
  47429. comps.add (c);
  47430. if (! c->isFocusContainer())
  47431. findAllFocusableComponents (c, comps);
  47432. }
  47433. }
  47434. }
  47435. }
  47436. static Component* getIncrementedComponent (Component* const current, const int delta)
  47437. {
  47438. Component* focusContainer = current->getParentComponent();
  47439. if (focusContainer != 0)
  47440. {
  47441. while (focusContainer->getParentComponent() != 0 && ! focusContainer->isFocusContainer())
  47442. focusContainer = focusContainer->getParentComponent();
  47443. if (focusContainer != 0)
  47444. {
  47445. Array <Component*> comps;
  47446. KeyboardFocusHelpers::findAllFocusableComponents (focusContainer, comps);
  47447. if (comps.size() > 0)
  47448. {
  47449. const int index = comps.indexOf (current);
  47450. return comps [(index + comps.size() + delta) % comps.size()];
  47451. }
  47452. }
  47453. }
  47454. return 0;
  47455. }
  47456. Component* KeyboardFocusTraverser::getNextComponent (Component* current)
  47457. {
  47458. return getIncrementedComponent (current, 1);
  47459. }
  47460. Component* KeyboardFocusTraverser::getPreviousComponent (Component* current)
  47461. {
  47462. return getIncrementedComponent (current, -1);
  47463. }
  47464. Component* KeyboardFocusTraverser::getDefaultComponent (Component* parentComponent)
  47465. {
  47466. Array <Component*> comps;
  47467. if (parentComponent != 0)
  47468. KeyboardFocusHelpers::findAllFocusableComponents (parentComponent, comps);
  47469. return comps.getFirst();
  47470. }
  47471. END_JUCE_NAMESPACE
  47472. /*** End of inlined file: juce_KeyboardFocusTraverser.cpp ***/
  47473. /*** Start of inlined file: juce_KeyListener.cpp ***/
  47474. BEGIN_JUCE_NAMESPACE
  47475. bool KeyListener::keyStateChanged (const bool, Component*)
  47476. {
  47477. return false;
  47478. }
  47479. END_JUCE_NAMESPACE
  47480. /*** End of inlined file: juce_KeyListener.cpp ***/
  47481. /*** Start of inlined file: juce_KeyMappingEditorComponent.cpp ***/
  47482. BEGIN_JUCE_NAMESPACE
  47483. // N.B. these two includes are put here deliberately to avoid problems with
  47484. // old GCCs failing on long include paths
  47485. const int maxKeys = 3;
  47486. class KeyMappingChangeButton : public Button
  47487. {
  47488. public:
  47489. KeyMappingChangeButton (KeyMappingEditorComponent* const owner_,
  47490. const CommandID commandID_,
  47491. const String& keyName,
  47492. const int keyNum_)
  47493. : Button (keyName),
  47494. owner (owner_),
  47495. commandID (commandID_),
  47496. keyNum (keyNum_)
  47497. {
  47498. setWantsKeyboardFocus (false);
  47499. setTriggeredOnMouseDown (keyNum >= 0);
  47500. if (keyNum_ < 0)
  47501. setTooltip (TRANS("adds a new key-mapping"));
  47502. else
  47503. setTooltip (TRANS("click to change this key-mapping"));
  47504. }
  47505. ~KeyMappingChangeButton()
  47506. {
  47507. }
  47508. void paintButton (Graphics& g, bool /*isOver*/, bool /*isDown*/)
  47509. {
  47510. getLookAndFeel().drawKeymapChangeButton (g, getWidth(), getHeight(), *this,
  47511. keyNum >= 0 ? getName() : String::empty);
  47512. }
  47513. void clicked()
  47514. {
  47515. if (keyNum >= 0)
  47516. {
  47517. // existing key clicked..
  47518. PopupMenu m;
  47519. m.addItem (1, TRANS("change this key-mapping"));
  47520. m.addSeparator();
  47521. m.addItem (2, TRANS("remove this key-mapping"));
  47522. const int res = m.show();
  47523. if (res == 1)
  47524. {
  47525. owner->assignNewKey (commandID, keyNum);
  47526. }
  47527. else if (res == 2)
  47528. {
  47529. owner->getMappings()->removeKeyPress (commandID, keyNum);
  47530. }
  47531. }
  47532. else
  47533. {
  47534. // + button pressed..
  47535. owner->assignNewKey (commandID, -1);
  47536. }
  47537. }
  47538. void fitToContent (const int h) throw()
  47539. {
  47540. if (keyNum < 0)
  47541. {
  47542. setSize (h, h);
  47543. }
  47544. else
  47545. {
  47546. Font f (h * 0.6f);
  47547. setSize (jlimit (h * 4, h * 8, 6 + f.getStringWidth (getName())), h);
  47548. }
  47549. }
  47550. juce_UseDebuggingNewOperator
  47551. private:
  47552. KeyMappingEditorComponent* const owner;
  47553. const CommandID commandID;
  47554. const int keyNum;
  47555. KeyMappingChangeButton (const KeyMappingChangeButton&);
  47556. KeyMappingChangeButton& operator= (const KeyMappingChangeButton&);
  47557. };
  47558. class KeyMappingItemComponent : public Component
  47559. {
  47560. public:
  47561. KeyMappingItemComponent (KeyMappingEditorComponent* const owner_,
  47562. const CommandID commandID_)
  47563. : owner (owner_),
  47564. commandID (commandID_)
  47565. {
  47566. setInterceptsMouseClicks (false, true);
  47567. const bool isReadOnly = owner_->isCommandReadOnly (commandID);
  47568. const Array <KeyPress> keyPresses (owner_->getMappings()->getKeyPressesAssignedToCommand (commandID));
  47569. for (int i = 0; i < jmin (maxKeys, keyPresses.size()); ++i)
  47570. {
  47571. KeyMappingChangeButton* const kb
  47572. = new KeyMappingChangeButton (owner_, commandID,
  47573. owner_->getDescriptionForKeyPress (keyPresses.getReference (i)), i);
  47574. kb->setEnabled (! isReadOnly);
  47575. addAndMakeVisible (kb);
  47576. }
  47577. KeyMappingChangeButton* const kb
  47578. = new KeyMappingChangeButton (owner_, commandID, String::empty, -1);
  47579. addChildComponent (kb);
  47580. kb->setVisible (keyPresses.size() < maxKeys && ! isReadOnly);
  47581. }
  47582. ~KeyMappingItemComponent()
  47583. {
  47584. deleteAllChildren();
  47585. }
  47586. void paint (Graphics& g)
  47587. {
  47588. g.setFont (getHeight() * 0.7f);
  47589. g.setColour (findColour (KeyMappingEditorComponent::textColourId));
  47590. g.drawFittedText (owner->getMappings()->getCommandManager()->getNameOfCommand (commandID),
  47591. 4, 0, jmax (40, getChildComponent (0)->getX() - 5), getHeight(),
  47592. Justification::centredLeft, true);
  47593. }
  47594. void resized()
  47595. {
  47596. int x = getWidth() - 4;
  47597. for (int i = getNumChildComponents(); --i >= 0;)
  47598. {
  47599. KeyMappingChangeButton* const kb = dynamic_cast <KeyMappingChangeButton*> (getChildComponent (i));
  47600. kb->fitToContent (getHeight() - 2);
  47601. kb->setTopRightPosition (x, 1);
  47602. x -= kb->getWidth() + 5;
  47603. }
  47604. }
  47605. juce_UseDebuggingNewOperator
  47606. private:
  47607. KeyMappingEditorComponent* const owner;
  47608. const CommandID commandID;
  47609. KeyMappingItemComponent (const KeyMappingItemComponent&);
  47610. KeyMappingItemComponent& operator= (const KeyMappingItemComponent&);
  47611. };
  47612. class KeyMappingTreeViewItem : public TreeViewItem
  47613. {
  47614. public:
  47615. KeyMappingTreeViewItem (KeyMappingEditorComponent* const owner_,
  47616. const CommandID commandID_)
  47617. : owner (owner_),
  47618. commandID (commandID_)
  47619. {
  47620. }
  47621. ~KeyMappingTreeViewItem()
  47622. {
  47623. }
  47624. const String getUniqueName() const { return String ((int) commandID) + "_id"; }
  47625. bool mightContainSubItems() { return false; }
  47626. int getItemHeight() const { return 20; }
  47627. Component* createItemComponent()
  47628. {
  47629. return new KeyMappingItemComponent (owner, commandID);
  47630. }
  47631. juce_UseDebuggingNewOperator
  47632. private:
  47633. KeyMappingEditorComponent* const owner;
  47634. const CommandID commandID;
  47635. KeyMappingTreeViewItem (const KeyMappingTreeViewItem&);
  47636. KeyMappingTreeViewItem& operator= (const KeyMappingTreeViewItem&);
  47637. };
  47638. class KeyCategoryTreeViewItem : public TreeViewItem
  47639. {
  47640. public:
  47641. KeyCategoryTreeViewItem (KeyMappingEditorComponent* const owner_,
  47642. const String& name)
  47643. : owner (owner_),
  47644. categoryName (name)
  47645. {
  47646. }
  47647. ~KeyCategoryTreeViewItem()
  47648. {
  47649. }
  47650. const String getUniqueName() const { return categoryName + "_cat"; }
  47651. bool mightContainSubItems() { return true; }
  47652. int getItemHeight() const { return 28; }
  47653. void paintItem (Graphics& g, int width, int height)
  47654. {
  47655. g.setFont (height * 0.6f, Font::bold);
  47656. g.setColour (owner->findColour (KeyMappingEditorComponent::textColourId));
  47657. g.drawText (categoryName,
  47658. 2, 0, width - 2, height,
  47659. Justification::centredLeft, true);
  47660. }
  47661. void itemOpennessChanged (bool isNowOpen)
  47662. {
  47663. if (isNowOpen)
  47664. {
  47665. if (getNumSubItems() == 0)
  47666. {
  47667. Array <CommandID> commands (owner->getMappings()->getCommandManager()->getCommandsInCategory (categoryName));
  47668. for (int i = 0; i < commands.size(); ++i)
  47669. {
  47670. if (owner->shouldCommandBeIncluded (commands[i]))
  47671. addSubItem (new KeyMappingTreeViewItem (owner, commands[i]));
  47672. }
  47673. }
  47674. }
  47675. else
  47676. {
  47677. clearSubItems();
  47678. }
  47679. }
  47680. juce_UseDebuggingNewOperator
  47681. private:
  47682. KeyMappingEditorComponent* owner;
  47683. String categoryName;
  47684. KeyCategoryTreeViewItem (const KeyCategoryTreeViewItem&);
  47685. KeyCategoryTreeViewItem& operator= (const KeyCategoryTreeViewItem&);
  47686. };
  47687. KeyMappingEditorComponent::KeyMappingEditorComponent (KeyPressMappingSet* const mappingManager,
  47688. const bool showResetToDefaultButton)
  47689. : mappings (mappingManager)
  47690. {
  47691. jassert (mappingManager != 0); // can't be null!
  47692. mappingManager->addChangeListener (this);
  47693. setLinesDrawnForSubItems (false);
  47694. resetButton = 0;
  47695. if (showResetToDefaultButton)
  47696. {
  47697. addAndMakeVisible (resetButton = new TextButton (TRANS("reset to defaults")));
  47698. resetButton->addButtonListener (this);
  47699. }
  47700. addAndMakeVisible (tree = new TreeView());
  47701. tree->setColour (TreeView::backgroundColourId, findColour (backgroundColourId));
  47702. tree->setRootItemVisible (false);
  47703. tree->setDefaultOpenness (true);
  47704. tree->setRootItem (this);
  47705. }
  47706. KeyMappingEditorComponent::~KeyMappingEditorComponent()
  47707. {
  47708. mappings->removeChangeListener (this);
  47709. deleteAllChildren();
  47710. }
  47711. bool KeyMappingEditorComponent::mightContainSubItems()
  47712. {
  47713. return true;
  47714. }
  47715. const String KeyMappingEditorComponent::getUniqueName() const
  47716. {
  47717. return "keys";
  47718. }
  47719. void KeyMappingEditorComponent::setColours (const Colour& mainBackground,
  47720. const Colour& textColour)
  47721. {
  47722. setColour (backgroundColourId, mainBackground);
  47723. setColour (textColourId, textColour);
  47724. tree->setColour (TreeView::backgroundColourId, mainBackground);
  47725. }
  47726. void KeyMappingEditorComponent::parentHierarchyChanged()
  47727. {
  47728. changeListenerCallback (0);
  47729. }
  47730. void KeyMappingEditorComponent::resized()
  47731. {
  47732. int h = getHeight();
  47733. if (resetButton != 0)
  47734. {
  47735. const int buttonHeight = 20;
  47736. h -= buttonHeight + 8;
  47737. int x = getWidth() - 8;
  47738. resetButton->changeWidthToFitText (buttonHeight);
  47739. resetButton->setTopRightPosition (x, h + 6);
  47740. }
  47741. tree->setBounds (0, 0, getWidth(), h);
  47742. }
  47743. void KeyMappingEditorComponent::buttonClicked (Button* button)
  47744. {
  47745. if (button == resetButton)
  47746. {
  47747. if (AlertWindow::showOkCancelBox (AlertWindow::QuestionIcon,
  47748. TRANS("Reset to defaults"),
  47749. TRANS("Are you sure you want to reset all the key-mappings to their default state?"),
  47750. TRANS("Reset")))
  47751. {
  47752. mappings->resetToDefaultMappings();
  47753. }
  47754. }
  47755. }
  47756. void KeyMappingEditorComponent::changeListenerCallback (void*)
  47757. {
  47758. ScopedPointer <XmlElement> oldOpenness (tree->getOpennessState (true));
  47759. clearSubItems();
  47760. const StringArray categories (mappings->getCommandManager()->getCommandCategories());
  47761. for (int i = 0; i < categories.size(); ++i)
  47762. {
  47763. const Array <CommandID> commands (mappings->getCommandManager()->getCommandsInCategory (categories[i]));
  47764. int count = 0;
  47765. for (int j = 0; j < commands.size(); ++j)
  47766. if (shouldCommandBeIncluded (commands[j]))
  47767. ++count;
  47768. if (count > 0)
  47769. addSubItem (new KeyCategoryTreeViewItem (this, categories[i]));
  47770. }
  47771. if (oldOpenness != 0)
  47772. tree->restoreOpennessState (*oldOpenness);
  47773. }
  47774. class KeyEntryWindow : public AlertWindow
  47775. {
  47776. public:
  47777. KeyEntryWindow (KeyMappingEditorComponent* const owner_)
  47778. : AlertWindow (TRANS("New key-mapping"),
  47779. TRANS("Please press a key combination now..."),
  47780. AlertWindow::NoIcon),
  47781. owner (owner_)
  47782. {
  47783. addButton (TRANS("ok"), 1);
  47784. addButton (TRANS("cancel"), 0);
  47785. // (avoid return + escape keys getting processed by the buttons..)
  47786. for (int i = getNumChildComponents(); --i >= 0;)
  47787. getChildComponent (i)->setWantsKeyboardFocus (false);
  47788. setWantsKeyboardFocus (true);
  47789. grabKeyboardFocus();
  47790. }
  47791. ~KeyEntryWindow()
  47792. {
  47793. }
  47794. bool keyPressed (const KeyPress& key)
  47795. {
  47796. lastPress = key;
  47797. String message (TRANS("Key: ") + owner->getDescriptionForKeyPress (key));
  47798. const CommandID previousCommand = owner->getMappings()->findCommandForKeyPress (key);
  47799. if (previousCommand != 0)
  47800. {
  47801. message << "\n\n"
  47802. << TRANS("(Currently assigned to \"")
  47803. << owner->getMappings()->getCommandManager()->getNameOfCommand (previousCommand)
  47804. << "\")";
  47805. }
  47806. setMessage (message);
  47807. return true;
  47808. }
  47809. bool keyStateChanged (bool)
  47810. {
  47811. return true;
  47812. }
  47813. KeyPress lastPress;
  47814. juce_UseDebuggingNewOperator
  47815. private:
  47816. KeyMappingEditorComponent* owner;
  47817. KeyEntryWindow (const KeyEntryWindow&);
  47818. KeyEntryWindow& operator= (const KeyEntryWindow&);
  47819. };
  47820. void KeyMappingEditorComponent::assignNewKey (const CommandID commandID, const int index)
  47821. {
  47822. KeyEntryWindow entryWindow (this);
  47823. if (entryWindow.runModalLoop() != 0)
  47824. {
  47825. entryWindow.setVisible (false);
  47826. if (entryWindow.lastPress.isValid())
  47827. {
  47828. const CommandID previousCommand = mappings->findCommandForKeyPress (entryWindow.lastPress);
  47829. if (previousCommand != 0)
  47830. {
  47831. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  47832. TRANS("Change key-mapping"),
  47833. TRANS("This key is already assigned to the command \"")
  47834. + mappings->getCommandManager()->getNameOfCommand (previousCommand)
  47835. + TRANS("\"\n\nDo you want to re-assign it to this new command instead?"),
  47836. TRANS("re-assign"),
  47837. TRANS("cancel")))
  47838. {
  47839. return;
  47840. }
  47841. }
  47842. mappings->removeKeyPress (entryWindow.lastPress);
  47843. if (index >= 0)
  47844. mappings->removeKeyPress (commandID, index);
  47845. mappings->addKeyPress (commandID, entryWindow.lastPress, index);
  47846. }
  47847. }
  47848. }
  47849. bool KeyMappingEditorComponent::shouldCommandBeIncluded (const CommandID commandID)
  47850. {
  47851. const ApplicationCommandInfo* const ci = mappings->getCommandManager()->getCommandForID (commandID);
  47852. return (ci != 0) && ((ci->flags & ApplicationCommandInfo::hiddenFromKeyEditor) == 0);
  47853. }
  47854. bool KeyMappingEditorComponent::isCommandReadOnly (const CommandID commandID)
  47855. {
  47856. const ApplicationCommandInfo* const ci = mappings->getCommandManager()->getCommandForID (commandID);
  47857. return (ci != 0) && ((ci->flags & ApplicationCommandInfo::readOnlyInKeyEditor) != 0);
  47858. }
  47859. const String KeyMappingEditorComponent::getDescriptionForKeyPress (const KeyPress& key)
  47860. {
  47861. return key.getTextDescription();
  47862. }
  47863. END_JUCE_NAMESPACE
  47864. /*** End of inlined file: juce_KeyMappingEditorComponent.cpp ***/
  47865. /*** Start of inlined file: juce_KeyPress.cpp ***/
  47866. BEGIN_JUCE_NAMESPACE
  47867. KeyPress::KeyPress() throw()
  47868. : keyCode (0),
  47869. mods (0),
  47870. textCharacter (0)
  47871. {
  47872. }
  47873. KeyPress::KeyPress (const int keyCode_,
  47874. const ModifierKeys& mods_,
  47875. const juce_wchar textCharacter_) throw()
  47876. : keyCode (keyCode_),
  47877. mods (mods_),
  47878. textCharacter (textCharacter_)
  47879. {
  47880. }
  47881. KeyPress::KeyPress (const int keyCode_) throw()
  47882. : keyCode (keyCode_),
  47883. textCharacter (0)
  47884. {
  47885. }
  47886. KeyPress::KeyPress (const KeyPress& other) throw()
  47887. : keyCode (other.keyCode),
  47888. mods (other.mods),
  47889. textCharacter (other.textCharacter)
  47890. {
  47891. }
  47892. KeyPress& KeyPress::operator= (const KeyPress& other) throw()
  47893. {
  47894. keyCode = other.keyCode;
  47895. mods = other.mods;
  47896. textCharacter = other.textCharacter;
  47897. return *this;
  47898. }
  47899. bool KeyPress::operator== (const KeyPress& other) const throw()
  47900. {
  47901. return mods.getRawFlags() == other.mods.getRawFlags()
  47902. && (textCharacter == other.textCharacter
  47903. || textCharacter == 0
  47904. || other.textCharacter == 0)
  47905. && (keyCode == other.keyCode
  47906. || (keyCode < 256
  47907. && other.keyCode < 256
  47908. && CharacterFunctions::toLowerCase ((juce_wchar) keyCode)
  47909. == CharacterFunctions::toLowerCase ((juce_wchar) other.keyCode)));
  47910. }
  47911. bool KeyPress::operator!= (const KeyPress& other) const throw()
  47912. {
  47913. return ! operator== (other);
  47914. }
  47915. bool KeyPress::isCurrentlyDown() const
  47916. {
  47917. return isKeyCurrentlyDown (keyCode)
  47918. && (ModifierKeys::getCurrentModifiers().getRawFlags() & ModifierKeys::allKeyboardModifiers)
  47919. == (mods.getRawFlags() & ModifierKeys::allKeyboardModifiers);
  47920. }
  47921. namespace KeyPressHelpers
  47922. {
  47923. struct KeyNameAndCode
  47924. {
  47925. const char* name;
  47926. int code;
  47927. };
  47928. static const KeyNameAndCode translations[] =
  47929. {
  47930. { "spacebar", KeyPress::spaceKey },
  47931. { "return", KeyPress::returnKey },
  47932. { "escape", KeyPress::escapeKey },
  47933. { "backspace", KeyPress::backspaceKey },
  47934. { "cursor left", KeyPress::leftKey },
  47935. { "cursor right", KeyPress::rightKey },
  47936. { "cursor up", KeyPress::upKey },
  47937. { "cursor down", KeyPress::downKey },
  47938. { "page up", KeyPress::pageUpKey },
  47939. { "page down", KeyPress::pageDownKey },
  47940. { "home", KeyPress::homeKey },
  47941. { "end", KeyPress::endKey },
  47942. { "delete", KeyPress::deleteKey },
  47943. { "insert", KeyPress::insertKey },
  47944. { "tab", KeyPress::tabKey },
  47945. { "play", KeyPress::playKey },
  47946. { "stop", KeyPress::stopKey },
  47947. { "fast forward", KeyPress::fastForwardKey },
  47948. { "rewind", KeyPress::rewindKey }
  47949. };
  47950. static const String numberPadPrefix() { return "numpad "; }
  47951. }
  47952. const KeyPress KeyPress::createFromDescription (const String& desc)
  47953. {
  47954. int modifiers = 0;
  47955. if (desc.containsWholeWordIgnoreCase ("ctrl")
  47956. || desc.containsWholeWordIgnoreCase ("control")
  47957. || desc.containsWholeWordIgnoreCase ("ctl"))
  47958. modifiers |= ModifierKeys::ctrlModifier;
  47959. if (desc.containsWholeWordIgnoreCase ("shift")
  47960. || desc.containsWholeWordIgnoreCase ("shft"))
  47961. modifiers |= ModifierKeys::shiftModifier;
  47962. if (desc.containsWholeWordIgnoreCase ("alt")
  47963. || desc.containsWholeWordIgnoreCase ("option"))
  47964. modifiers |= ModifierKeys::altModifier;
  47965. if (desc.containsWholeWordIgnoreCase ("command")
  47966. || desc.containsWholeWordIgnoreCase ("cmd"))
  47967. modifiers |= ModifierKeys::commandModifier;
  47968. int key = 0;
  47969. for (int i = 0; i < numElementsInArray (KeyPressHelpers::translations); ++i)
  47970. {
  47971. if (desc.containsWholeWordIgnoreCase (String (KeyPressHelpers::translations[i].name)))
  47972. {
  47973. key = KeyPressHelpers::translations[i].code;
  47974. break;
  47975. }
  47976. }
  47977. if (key == 0)
  47978. {
  47979. // see if it's a numpad key..
  47980. if (desc.containsIgnoreCase (KeyPressHelpers::numberPadPrefix()))
  47981. {
  47982. const juce_wchar lastChar = desc.trimEnd().getLastCharacter();
  47983. if (lastChar >= '0' && lastChar <= '9')
  47984. key = numberPad0 + lastChar - '0';
  47985. else if (lastChar == '+')
  47986. key = numberPadAdd;
  47987. else if (lastChar == '-')
  47988. key = numberPadSubtract;
  47989. else if (lastChar == '*')
  47990. key = numberPadMultiply;
  47991. else if (lastChar == '/')
  47992. key = numberPadDivide;
  47993. else if (lastChar == '.')
  47994. key = numberPadDecimalPoint;
  47995. else if (lastChar == '=')
  47996. key = numberPadEquals;
  47997. else if (desc.endsWith ("separator"))
  47998. key = numberPadSeparator;
  47999. else if (desc.endsWith ("delete"))
  48000. key = numberPadDelete;
  48001. }
  48002. if (key == 0)
  48003. {
  48004. // see if it's a function key..
  48005. for (int i = 1; i <= 12; ++i)
  48006. if (desc.containsWholeWordIgnoreCase ("f" + String (i)))
  48007. key = F1Key + i - 1;
  48008. if (key == 0)
  48009. {
  48010. // give up and use the hex code..
  48011. const int hexCode = desc.fromFirstOccurrenceOf ("#", false, false)
  48012. .toLowerCase()
  48013. .retainCharacters ("0123456789abcdef")
  48014. .getHexValue32();
  48015. if (hexCode > 0)
  48016. key = hexCode;
  48017. else
  48018. key = CharacterFunctions::toUpperCase (desc.getLastCharacter());
  48019. }
  48020. }
  48021. }
  48022. return KeyPress (key, ModifierKeys (modifiers), 0);
  48023. }
  48024. const String KeyPress::getTextDescription() const
  48025. {
  48026. String desc;
  48027. if (keyCode > 0)
  48028. {
  48029. // some keyboard layouts use a shift-key to get the slash, but in those cases, we
  48030. // want to store it as being a slash, not shift+whatever.
  48031. if (textCharacter == '/')
  48032. return "/";
  48033. if (mods.isCtrlDown())
  48034. desc << "ctrl + ";
  48035. if (mods.isShiftDown())
  48036. desc << "shift + ";
  48037. #if JUCE_MAC
  48038. // only do this on the mac, because on Windows ctrl and command are the same,
  48039. // and this would get confusing
  48040. if (mods.isCommandDown())
  48041. desc << "command + ";
  48042. if (mods.isAltDown())
  48043. desc << "option + ";
  48044. #else
  48045. if (mods.isAltDown())
  48046. desc << "alt + ";
  48047. #endif
  48048. for (int i = 0; i < numElementsInArray (KeyPressHelpers::translations); ++i)
  48049. if (keyCode == KeyPressHelpers::translations[i].code)
  48050. return desc + KeyPressHelpers::translations[i].name;
  48051. if (keyCode >= F1Key && keyCode <= F16Key)
  48052. desc << 'F' << (1 + keyCode - F1Key);
  48053. else if (keyCode >= numberPad0 && keyCode <= numberPad9)
  48054. desc << KeyPressHelpers::numberPadPrefix() << (keyCode - numberPad0);
  48055. else if (keyCode >= 33 && keyCode < 176)
  48056. desc += CharacterFunctions::toUpperCase ((juce_wchar) keyCode);
  48057. else if (keyCode == numberPadAdd)
  48058. desc << KeyPressHelpers::numberPadPrefix() << '+';
  48059. else if (keyCode == numberPadSubtract)
  48060. desc << KeyPressHelpers::numberPadPrefix() << '-';
  48061. else if (keyCode == numberPadMultiply)
  48062. desc << KeyPressHelpers::numberPadPrefix() << '*';
  48063. else if (keyCode == numberPadDivide)
  48064. desc << KeyPressHelpers::numberPadPrefix() << '/';
  48065. else if (keyCode == numberPadSeparator)
  48066. desc << KeyPressHelpers::numberPadPrefix() << "separator";
  48067. else if (keyCode == numberPadDecimalPoint)
  48068. desc << KeyPressHelpers::numberPadPrefix() << '.';
  48069. else if (keyCode == numberPadDelete)
  48070. desc << KeyPressHelpers::numberPadPrefix() << "delete";
  48071. else
  48072. desc << '#' << String::toHexString (keyCode);
  48073. }
  48074. return desc;
  48075. }
  48076. END_JUCE_NAMESPACE
  48077. /*** End of inlined file: juce_KeyPress.cpp ***/
  48078. /*** Start of inlined file: juce_KeyPressMappingSet.cpp ***/
  48079. BEGIN_JUCE_NAMESPACE
  48080. KeyPressMappingSet::KeyPressMappingSet (ApplicationCommandManager* const commandManager_)
  48081. : commandManager (commandManager_)
  48082. {
  48083. // A manager is needed to get the descriptions of commands, and will be called when
  48084. // a command is invoked. So you can't leave this null..
  48085. jassert (commandManager_ != 0);
  48086. Desktop::getInstance().addFocusChangeListener (this);
  48087. }
  48088. KeyPressMappingSet::KeyPressMappingSet (const KeyPressMappingSet& other)
  48089. : commandManager (other.commandManager)
  48090. {
  48091. Desktop::getInstance().addFocusChangeListener (this);
  48092. }
  48093. KeyPressMappingSet::~KeyPressMappingSet()
  48094. {
  48095. Desktop::getInstance().removeFocusChangeListener (this);
  48096. }
  48097. const Array <KeyPress> KeyPressMappingSet::getKeyPressesAssignedToCommand (const CommandID commandID) const
  48098. {
  48099. for (int i = 0; i < mappings.size(); ++i)
  48100. if (mappings.getUnchecked(i)->commandID == commandID)
  48101. return mappings.getUnchecked (i)->keypresses;
  48102. return Array <KeyPress> ();
  48103. }
  48104. void KeyPressMappingSet::addKeyPress (const CommandID commandID,
  48105. const KeyPress& newKeyPress,
  48106. int insertIndex)
  48107. {
  48108. // If you specify an upper-case letter but no shift key, how is the user supposed to press it!?
  48109. // Stick to lower-case letters when defining a keypress, to avoid ambiguity.
  48110. jassert (! (CharacterFunctions::isUpperCase (newKeyPress.getTextCharacter())
  48111. && ! newKeyPress.getModifiers().isShiftDown()));
  48112. if (findCommandForKeyPress (newKeyPress) != commandID)
  48113. {
  48114. removeKeyPress (newKeyPress);
  48115. if (newKeyPress.isValid())
  48116. {
  48117. for (int i = mappings.size(); --i >= 0;)
  48118. {
  48119. if (mappings.getUnchecked(i)->commandID == commandID)
  48120. {
  48121. mappings.getUnchecked(i)->keypresses.insert (insertIndex, newKeyPress);
  48122. sendChangeMessage (this);
  48123. return;
  48124. }
  48125. }
  48126. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  48127. if (ci != 0)
  48128. {
  48129. CommandMapping* const cm = new CommandMapping();
  48130. cm->commandID = commandID;
  48131. cm->keypresses.add (newKeyPress);
  48132. cm->wantsKeyUpDownCallbacks = (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) != 0;
  48133. mappings.add (cm);
  48134. sendChangeMessage (this);
  48135. }
  48136. }
  48137. }
  48138. }
  48139. void KeyPressMappingSet::resetToDefaultMappings()
  48140. {
  48141. mappings.clear();
  48142. for (int i = 0; i < commandManager->getNumCommands(); ++i)
  48143. {
  48144. const ApplicationCommandInfo* const ci = commandManager->getCommandForIndex (i);
  48145. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  48146. {
  48147. addKeyPress (ci->commandID,
  48148. ci->defaultKeypresses.getReference (j));
  48149. }
  48150. }
  48151. sendChangeMessage (this);
  48152. }
  48153. void KeyPressMappingSet::resetToDefaultMapping (const CommandID commandID)
  48154. {
  48155. clearAllKeyPresses (commandID);
  48156. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  48157. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  48158. {
  48159. addKeyPress (ci->commandID,
  48160. ci->defaultKeypresses.getReference (j));
  48161. }
  48162. }
  48163. void KeyPressMappingSet::clearAllKeyPresses()
  48164. {
  48165. if (mappings.size() > 0)
  48166. {
  48167. sendChangeMessage (this);
  48168. mappings.clear();
  48169. }
  48170. }
  48171. void KeyPressMappingSet::clearAllKeyPresses (const CommandID commandID)
  48172. {
  48173. for (int i = mappings.size(); --i >= 0;)
  48174. {
  48175. if (mappings.getUnchecked(i)->commandID == commandID)
  48176. {
  48177. mappings.remove (i);
  48178. sendChangeMessage (this);
  48179. }
  48180. }
  48181. }
  48182. void KeyPressMappingSet::removeKeyPress (const KeyPress& keypress)
  48183. {
  48184. if (keypress.isValid())
  48185. {
  48186. for (int i = mappings.size(); --i >= 0;)
  48187. {
  48188. CommandMapping* const cm = mappings.getUnchecked(i);
  48189. for (int j = cm->keypresses.size(); --j >= 0;)
  48190. {
  48191. if (keypress == cm->keypresses [j])
  48192. {
  48193. cm->keypresses.remove (j);
  48194. sendChangeMessage (this);
  48195. }
  48196. }
  48197. }
  48198. }
  48199. }
  48200. void KeyPressMappingSet::removeKeyPress (const CommandID commandID, const int keyPressIndex)
  48201. {
  48202. for (int i = mappings.size(); --i >= 0;)
  48203. {
  48204. if (mappings.getUnchecked(i)->commandID == commandID)
  48205. {
  48206. mappings.getUnchecked(i)->keypresses.remove (keyPressIndex);
  48207. sendChangeMessage (this);
  48208. break;
  48209. }
  48210. }
  48211. }
  48212. CommandID KeyPressMappingSet::findCommandForKeyPress (const KeyPress& keyPress) const throw()
  48213. {
  48214. for (int i = 0; i < mappings.size(); ++i)
  48215. if (mappings.getUnchecked(i)->keypresses.contains (keyPress))
  48216. return mappings.getUnchecked(i)->commandID;
  48217. return 0;
  48218. }
  48219. bool KeyPressMappingSet::containsMapping (const CommandID commandID, const KeyPress& keyPress) const throw()
  48220. {
  48221. for (int i = mappings.size(); --i >= 0;)
  48222. if (mappings.getUnchecked(i)->commandID == commandID)
  48223. return mappings.getUnchecked(i)->keypresses.contains (keyPress);
  48224. return false;
  48225. }
  48226. void KeyPressMappingSet::invokeCommand (const CommandID commandID,
  48227. const KeyPress& key,
  48228. const bool isKeyDown,
  48229. const int millisecsSinceKeyPressed,
  48230. Component* const originatingComponent) const
  48231. {
  48232. ApplicationCommandTarget::InvocationInfo info (commandID);
  48233. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromKeyPress;
  48234. info.isKeyDown = isKeyDown;
  48235. info.keyPress = key;
  48236. info.millisecsSinceKeyPressed = millisecsSinceKeyPressed;
  48237. info.originatingComponent = originatingComponent;
  48238. commandManager->invoke (info, false);
  48239. }
  48240. bool KeyPressMappingSet::restoreFromXml (const XmlElement& xmlVersion)
  48241. {
  48242. if (xmlVersion.hasTagName ("KEYMAPPINGS"))
  48243. {
  48244. if (xmlVersion.getBoolAttribute ("basedOnDefaults", true))
  48245. {
  48246. // if the XML was created as a set of differences from the default mappings,
  48247. // (i.e. by calling createXml (true)), then we need to first restore the defaults.
  48248. resetToDefaultMappings();
  48249. }
  48250. else
  48251. {
  48252. // if the XML was created calling createXml (false), then we need to clear all
  48253. // the keys and treat the xml as describing the entire set of mappings.
  48254. clearAllKeyPresses();
  48255. }
  48256. forEachXmlChildElement (xmlVersion, map)
  48257. {
  48258. const CommandID commandId = map->getStringAttribute ("commandId").getHexValue32();
  48259. if (commandId != 0)
  48260. {
  48261. const KeyPress key (KeyPress::createFromDescription (map->getStringAttribute ("key")));
  48262. if (map->hasTagName ("MAPPING"))
  48263. {
  48264. addKeyPress (commandId, key);
  48265. }
  48266. else if (map->hasTagName ("UNMAPPING"))
  48267. {
  48268. if (containsMapping (commandId, key))
  48269. removeKeyPress (key);
  48270. }
  48271. }
  48272. }
  48273. return true;
  48274. }
  48275. return false;
  48276. }
  48277. XmlElement* KeyPressMappingSet::createXml (const bool saveDifferencesFromDefaultSet) const
  48278. {
  48279. ScopedPointer <KeyPressMappingSet> defaultSet;
  48280. if (saveDifferencesFromDefaultSet)
  48281. {
  48282. defaultSet = new KeyPressMappingSet (commandManager);
  48283. defaultSet->resetToDefaultMappings();
  48284. }
  48285. XmlElement* const doc = new XmlElement ("KEYMAPPINGS");
  48286. doc->setAttribute ("basedOnDefaults", saveDifferencesFromDefaultSet);
  48287. int i;
  48288. for (i = 0; i < mappings.size(); ++i)
  48289. {
  48290. const CommandMapping* const cm = mappings.getUnchecked(i);
  48291. for (int j = 0; j < cm->keypresses.size(); ++j)
  48292. {
  48293. if (defaultSet == 0
  48294. || ! defaultSet->containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  48295. {
  48296. XmlElement* const map = doc->createNewChildElement ("MAPPING");
  48297. map->setAttribute ("commandId", String::toHexString ((int) cm->commandID));
  48298. map->setAttribute ("description", commandManager->getDescriptionOfCommand (cm->commandID));
  48299. map->setAttribute ("key", cm->keypresses.getReference (j).getTextDescription());
  48300. }
  48301. }
  48302. }
  48303. if (defaultSet != 0)
  48304. {
  48305. for (i = 0; i < defaultSet->mappings.size(); ++i)
  48306. {
  48307. const CommandMapping* const cm = defaultSet->mappings.getUnchecked(i);
  48308. for (int j = 0; j < cm->keypresses.size(); ++j)
  48309. {
  48310. if (! containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  48311. {
  48312. XmlElement* const map = doc->createNewChildElement ("UNMAPPING");
  48313. map->setAttribute ("commandId", String::toHexString ((int) cm->commandID));
  48314. map->setAttribute ("description", commandManager->getDescriptionOfCommand (cm->commandID));
  48315. map->setAttribute ("key", cm->keypresses.getReference (j).getTextDescription());
  48316. }
  48317. }
  48318. }
  48319. }
  48320. return doc;
  48321. }
  48322. bool KeyPressMappingSet::keyPressed (const KeyPress& key,
  48323. Component* originatingComponent)
  48324. {
  48325. bool used = false;
  48326. const CommandID commandID = findCommandForKeyPress (key);
  48327. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  48328. if (ci != 0
  48329. && (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) == 0)
  48330. {
  48331. ApplicationCommandInfo info (0);
  48332. if (commandManager->getTargetForCommand (commandID, info) != 0
  48333. && (info.flags & ApplicationCommandInfo::isDisabled) == 0)
  48334. {
  48335. invokeCommand (commandID, key, true, 0, originatingComponent);
  48336. used = true;
  48337. }
  48338. else
  48339. {
  48340. if (originatingComponent != 0)
  48341. originatingComponent->getLookAndFeel().playAlertSound();
  48342. }
  48343. }
  48344. return used;
  48345. }
  48346. bool KeyPressMappingSet::keyStateChanged (const bool /*isKeyDown*/, Component* originatingComponent)
  48347. {
  48348. bool used = false;
  48349. const uint32 now = Time::getMillisecondCounter();
  48350. for (int i = mappings.size(); --i >= 0;)
  48351. {
  48352. CommandMapping* const cm = mappings.getUnchecked(i);
  48353. if (cm->wantsKeyUpDownCallbacks)
  48354. {
  48355. for (int j = cm->keypresses.size(); --j >= 0;)
  48356. {
  48357. const KeyPress key (cm->keypresses.getReference (j));
  48358. const bool isDown = key.isCurrentlyDown();
  48359. int keyPressEntryIndex = 0;
  48360. bool wasDown = false;
  48361. for (int k = keysDown.size(); --k >= 0;)
  48362. {
  48363. if (key == keysDown.getUnchecked(k)->key)
  48364. {
  48365. keyPressEntryIndex = k;
  48366. wasDown = true;
  48367. used = true;
  48368. break;
  48369. }
  48370. }
  48371. if (isDown != wasDown)
  48372. {
  48373. int millisecs = 0;
  48374. if (isDown)
  48375. {
  48376. KeyPressTime* const k = new KeyPressTime();
  48377. k->key = key;
  48378. k->timeWhenPressed = now;
  48379. keysDown.add (k);
  48380. }
  48381. else
  48382. {
  48383. const uint32 pressTime = keysDown.getUnchecked (keyPressEntryIndex)->timeWhenPressed;
  48384. if (now > pressTime)
  48385. millisecs = now - pressTime;
  48386. keysDown.remove (keyPressEntryIndex);
  48387. }
  48388. invokeCommand (cm->commandID, key, isDown, millisecs, originatingComponent);
  48389. used = true;
  48390. }
  48391. }
  48392. }
  48393. }
  48394. return used;
  48395. }
  48396. void KeyPressMappingSet::globalFocusChanged (Component* focusedComponent)
  48397. {
  48398. if (focusedComponent != 0)
  48399. focusedComponent->keyStateChanged (false);
  48400. }
  48401. END_JUCE_NAMESPACE
  48402. /*** End of inlined file: juce_KeyPressMappingSet.cpp ***/
  48403. /*** Start of inlined file: juce_ModifierKeys.cpp ***/
  48404. BEGIN_JUCE_NAMESPACE
  48405. ModifierKeys::ModifierKeys (const int flags_) throw()
  48406. : flags (flags_)
  48407. {
  48408. }
  48409. ModifierKeys::ModifierKeys (const ModifierKeys& other) throw()
  48410. : flags (other.flags)
  48411. {
  48412. }
  48413. ModifierKeys& ModifierKeys::operator= (const ModifierKeys& other) throw()
  48414. {
  48415. flags = other.flags;
  48416. return *this;
  48417. }
  48418. ModifierKeys ModifierKeys::currentModifiers;
  48419. const ModifierKeys ModifierKeys::getCurrentModifiers() throw()
  48420. {
  48421. return currentModifiers;
  48422. }
  48423. int ModifierKeys::getNumMouseButtonsDown() const throw()
  48424. {
  48425. int num = 0;
  48426. if (isLeftButtonDown()) ++num;
  48427. if (isRightButtonDown()) ++num;
  48428. if (isMiddleButtonDown()) ++num;
  48429. return num;
  48430. }
  48431. END_JUCE_NAMESPACE
  48432. /*** End of inlined file: juce_ModifierKeys.cpp ***/
  48433. /*** Start of inlined file: juce_ComponentAnimator.cpp ***/
  48434. BEGIN_JUCE_NAMESPACE
  48435. class ComponentAnimator::AnimationTask
  48436. {
  48437. public:
  48438. AnimationTask (Component* const comp)
  48439. : component (comp)
  48440. {
  48441. }
  48442. Component::SafePointer<Component> component;
  48443. Rectangle<int> destination;
  48444. int msElapsed, msTotal;
  48445. double startSpeed, midSpeed, endSpeed, lastProgress;
  48446. double left, top, right, bottom;
  48447. bool useTimeslice (const int elapsed)
  48448. {
  48449. if (component == 0)
  48450. return false;
  48451. msElapsed += elapsed;
  48452. double newProgress = msElapsed / (double) msTotal;
  48453. if (newProgress >= 0 && newProgress < 1.0)
  48454. {
  48455. newProgress = timeToDistance (newProgress);
  48456. const double delta = (newProgress - lastProgress) / (1.0 - lastProgress);
  48457. jassert (newProgress >= lastProgress);
  48458. lastProgress = newProgress;
  48459. left += (destination.getX() - left) * delta;
  48460. top += (destination.getY() - top) * delta;
  48461. right += (destination.getRight() - right) * delta;
  48462. bottom += (destination.getBottom() - bottom) * delta;
  48463. if (delta < 1.0)
  48464. {
  48465. const Rectangle<int> newBounds (roundToInt (left),
  48466. roundToInt (top),
  48467. roundToInt (right - left),
  48468. roundToInt (bottom - top));
  48469. if (newBounds != destination)
  48470. {
  48471. component->setBounds (newBounds);
  48472. return true;
  48473. }
  48474. }
  48475. }
  48476. component->setBounds (destination);
  48477. return false;
  48478. }
  48479. void moveToFinalDestination()
  48480. {
  48481. if (component != 0)
  48482. component->setBounds (destination);
  48483. }
  48484. private:
  48485. inline double timeToDistance (const double time) const
  48486. {
  48487. return (time < 0.5) ? time * (startSpeed + time * (midSpeed - startSpeed))
  48488. : 0.5 * (startSpeed + 0.5 * (midSpeed - startSpeed))
  48489. + (time - 0.5) * (midSpeed + (time - 0.5) * (endSpeed - midSpeed));
  48490. }
  48491. };
  48492. ComponentAnimator::ComponentAnimator()
  48493. : lastTime (0)
  48494. {
  48495. }
  48496. ComponentAnimator::~ComponentAnimator()
  48497. {
  48498. cancelAllAnimations (false);
  48499. jassert (tasks.size() == 0);
  48500. }
  48501. ComponentAnimator::AnimationTask* ComponentAnimator::findTaskFor (Component* const component) const
  48502. {
  48503. for (int i = tasks.size(); --i >= 0;)
  48504. if (component == tasks.getUnchecked(i)->component.getComponent())
  48505. return tasks.getUnchecked(i);
  48506. return 0;
  48507. }
  48508. void ComponentAnimator::animateComponent (Component* const component,
  48509. const Rectangle<int>& finalPosition,
  48510. const int millisecondsToSpendMoving,
  48511. const double startSpeed,
  48512. const double endSpeed)
  48513. {
  48514. if (component != 0)
  48515. {
  48516. AnimationTask* at = findTaskFor (component);
  48517. if (at == 0)
  48518. {
  48519. at = new AnimationTask (component);
  48520. tasks.add (at);
  48521. sendChangeMessage (this);
  48522. }
  48523. at->msElapsed = 0;
  48524. at->lastProgress = 0;
  48525. at->msTotal = jmax (1, millisecondsToSpendMoving);
  48526. at->destination = finalPosition;
  48527. // the speeds must be 0 or greater!
  48528. jassert (startSpeed >= 0 && endSpeed >= 0)
  48529. const double invTotalDistance = 4.0 / (startSpeed + endSpeed + 2.0);
  48530. at->startSpeed = jmax (0.0, startSpeed * invTotalDistance);
  48531. at->midSpeed = invTotalDistance;
  48532. at->endSpeed = jmax (0.0, endSpeed * invTotalDistance);
  48533. at->left = component->getX();
  48534. at->top = component->getY();
  48535. at->right = component->getRight();
  48536. at->bottom = component->getBottom();
  48537. if (! isTimerRunning())
  48538. {
  48539. lastTime = Time::getMillisecondCounter();
  48540. startTimer (1000 / 50);
  48541. }
  48542. }
  48543. }
  48544. void ComponentAnimator::cancelAllAnimations (const bool moveComponentsToTheirFinalPositions)
  48545. {
  48546. for (int i = tasks.size(); --i >= 0;)
  48547. {
  48548. AnimationTask* const at = tasks.getUnchecked(i);
  48549. if (moveComponentsToTheirFinalPositions)
  48550. at->moveToFinalDestination();
  48551. delete at;
  48552. tasks.remove (i);
  48553. sendChangeMessage (this);
  48554. }
  48555. }
  48556. void ComponentAnimator::cancelAnimation (Component* const component,
  48557. const bool moveComponentToItsFinalPosition)
  48558. {
  48559. AnimationTask* const at = findTaskFor (component);
  48560. if (at != 0)
  48561. {
  48562. if (moveComponentToItsFinalPosition)
  48563. at->moveToFinalDestination();
  48564. tasks.removeValue (at);
  48565. delete at;
  48566. sendChangeMessage (this);
  48567. }
  48568. }
  48569. const Rectangle<int> ComponentAnimator::getComponentDestination (Component* const component)
  48570. {
  48571. AnimationTask* const at = findTaskFor (component);
  48572. if (at != 0)
  48573. return at->destination;
  48574. else if (component != 0)
  48575. return component->getBounds();
  48576. return Rectangle<int>();
  48577. }
  48578. bool ComponentAnimator::isAnimating (Component* component) const
  48579. {
  48580. return findTaskFor (component) != 0;
  48581. }
  48582. void ComponentAnimator::timerCallback()
  48583. {
  48584. const uint32 timeNow = Time::getMillisecondCounter();
  48585. if (lastTime == 0 || lastTime == timeNow)
  48586. lastTime = timeNow;
  48587. const int elapsed = timeNow - lastTime;
  48588. for (int i = tasks.size(); --i >= 0;)
  48589. {
  48590. AnimationTask* const at = tasks.getUnchecked(i);
  48591. if (! at->useTimeslice (elapsed))
  48592. {
  48593. tasks.remove (i);
  48594. delete at;
  48595. sendChangeMessage (this);
  48596. }
  48597. }
  48598. lastTime = timeNow;
  48599. if (tasks.size() == 0)
  48600. stopTimer();
  48601. }
  48602. END_JUCE_NAMESPACE
  48603. /*** End of inlined file: juce_ComponentAnimator.cpp ***/
  48604. /*** Start of inlined file: juce_ComponentBoundsConstrainer.cpp ***/
  48605. BEGIN_JUCE_NAMESPACE
  48606. ComponentBoundsConstrainer::ComponentBoundsConstrainer() throw()
  48607. : minW (0),
  48608. maxW (0x3fffffff),
  48609. minH (0),
  48610. maxH (0x3fffffff),
  48611. minOffTop (0),
  48612. minOffLeft (0),
  48613. minOffBottom (0),
  48614. minOffRight (0),
  48615. aspectRatio (0.0)
  48616. {
  48617. }
  48618. ComponentBoundsConstrainer::~ComponentBoundsConstrainer()
  48619. {
  48620. }
  48621. void ComponentBoundsConstrainer::setMinimumWidth (const int minimumWidth) throw()
  48622. {
  48623. minW = minimumWidth;
  48624. }
  48625. void ComponentBoundsConstrainer::setMaximumWidth (const int maximumWidth) throw()
  48626. {
  48627. maxW = maximumWidth;
  48628. }
  48629. void ComponentBoundsConstrainer::setMinimumHeight (const int minimumHeight) throw()
  48630. {
  48631. minH = minimumHeight;
  48632. }
  48633. void ComponentBoundsConstrainer::setMaximumHeight (const int maximumHeight) throw()
  48634. {
  48635. maxH = maximumHeight;
  48636. }
  48637. void ComponentBoundsConstrainer::setMinimumSize (const int minimumWidth, const int minimumHeight) throw()
  48638. {
  48639. jassert (maxW >= minimumWidth);
  48640. jassert (maxH >= minimumHeight);
  48641. jassert (minimumWidth > 0 && minimumHeight > 0);
  48642. minW = minimumWidth;
  48643. minH = minimumHeight;
  48644. if (minW > maxW)
  48645. maxW = minW;
  48646. if (minH > maxH)
  48647. maxH = minH;
  48648. }
  48649. void ComponentBoundsConstrainer::setMaximumSize (const int maximumWidth, const int maximumHeight) throw()
  48650. {
  48651. jassert (maximumWidth >= minW);
  48652. jassert (maximumHeight >= minH);
  48653. jassert (maximumWidth > 0 && maximumHeight > 0);
  48654. maxW = jmax (minW, maximumWidth);
  48655. maxH = jmax (minH, maximumHeight);
  48656. }
  48657. void ComponentBoundsConstrainer::setSizeLimits (const int minimumWidth,
  48658. const int minimumHeight,
  48659. const int maximumWidth,
  48660. const int maximumHeight) throw()
  48661. {
  48662. jassert (maximumWidth >= minimumWidth);
  48663. jassert (maximumHeight >= minimumHeight);
  48664. jassert (maximumWidth > 0 && maximumHeight > 0);
  48665. jassert (minimumWidth > 0 && minimumHeight > 0);
  48666. minW = jmax (0, minimumWidth);
  48667. minH = jmax (0, minimumHeight);
  48668. maxW = jmax (minW, maximumWidth);
  48669. maxH = jmax (minH, maximumHeight);
  48670. }
  48671. void ComponentBoundsConstrainer::setMinimumOnscreenAmounts (const int minimumWhenOffTheTop,
  48672. const int minimumWhenOffTheLeft,
  48673. const int minimumWhenOffTheBottom,
  48674. const int minimumWhenOffTheRight) throw()
  48675. {
  48676. minOffTop = minimumWhenOffTheTop;
  48677. minOffLeft = minimumWhenOffTheLeft;
  48678. minOffBottom = minimumWhenOffTheBottom;
  48679. minOffRight = minimumWhenOffTheRight;
  48680. }
  48681. void ComponentBoundsConstrainer::setFixedAspectRatio (const double widthOverHeight) throw()
  48682. {
  48683. aspectRatio = jmax (0.0, widthOverHeight);
  48684. }
  48685. double ComponentBoundsConstrainer::getFixedAspectRatio() const throw()
  48686. {
  48687. return aspectRatio;
  48688. }
  48689. void ComponentBoundsConstrainer::setBoundsForComponent (Component* const component,
  48690. const Rectangle<int>& targetBounds,
  48691. const bool isStretchingTop,
  48692. const bool isStretchingLeft,
  48693. const bool isStretchingBottom,
  48694. const bool isStretchingRight)
  48695. {
  48696. jassert (component != 0);
  48697. Rectangle<int> limits, bounds (targetBounds);
  48698. BorderSize border;
  48699. Component* const parent = component->getParentComponent();
  48700. if (parent == 0)
  48701. {
  48702. ComponentPeer* peer = component->getPeer();
  48703. if (peer != 0)
  48704. border = peer->getFrameSize();
  48705. limits = Desktop::getInstance().getMonitorAreaContaining (bounds.getCentre());
  48706. }
  48707. else
  48708. {
  48709. limits.setSize (parent->getWidth(), parent->getHeight());
  48710. }
  48711. border.addTo (bounds);
  48712. checkBounds (bounds,
  48713. border.addedTo (component->getBounds()), limits,
  48714. isStretchingTop, isStretchingLeft,
  48715. isStretchingBottom, isStretchingRight);
  48716. border.subtractFrom (bounds);
  48717. applyBoundsToComponent (component, bounds);
  48718. }
  48719. void ComponentBoundsConstrainer::checkComponentBounds (Component* component)
  48720. {
  48721. setBoundsForComponent (component, component->getBounds(),
  48722. false, false, false, false);
  48723. }
  48724. void ComponentBoundsConstrainer::applyBoundsToComponent (Component* component,
  48725. const Rectangle<int>& bounds)
  48726. {
  48727. component->setBounds (bounds);
  48728. }
  48729. void ComponentBoundsConstrainer::resizeStart()
  48730. {
  48731. }
  48732. void ComponentBoundsConstrainer::resizeEnd()
  48733. {
  48734. }
  48735. void ComponentBoundsConstrainer::checkBounds (Rectangle<int>& bounds,
  48736. const Rectangle<int>& old,
  48737. const Rectangle<int>& limits,
  48738. const bool isStretchingTop,
  48739. const bool isStretchingLeft,
  48740. const bool isStretchingBottom,
  48741. const bool isStretchingRight)
  48742. {
  48743. int x = bounds.getX();
  48744. int y = bounds.getY();
  48745. int w = bounds.getWidth();
  48746. int h = bounds.getHeight();
  48747. // constrain the size if it's being stretched..
  48748. if (isStretchingLeft)
  48749. {
  48750. x = jlimit (old.getRight() - maxW, old.getRight() - minW, x);
  48751. w = old.getRight() - x;
  48752. }
  48753. if (isStretchingRight)
  48754. {
  48755. w = jlimit (minW, maxW, w);
  48756. }
  48757. if (isStretchingTop)
  48758. {
  48759. y = jlimit (old.getBottom() - maxH, old.getBottom() - minH, y);
  48760. h = old.getBottom() - y;
  48761. }
  48762. if (isStretchingBottom)
  48763. {
  48764. h = jlimit (minH, maxH, h);
  48765. }
  48766. // constrain the aspect ratio if one has been specified..
  48767. if (aspectRatio > 0.0 && w > 0 && h > 0)
  48768. {
  48769. bool adjustWidth;
  48770. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  48771. {
  48772. adjustWidth = true;
  48773. }
  48774. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  48775. {
  48776. adjustWidth = false;
  48777. }
  48778. else
  48779. {
  48780. const double oldRatio = (old.getHeight() > 0) ? std::abs (old.getWidth() / (double) old.getHeight()) : 0.0;
  48781. const double newRatio = std::abs (w / (double) h);
  48782. adjustWidth = (oldRatio > newRatio);
  48783. }
  48784. if (adjustWidth)
  48785. {
  48786. w = roundToInt (h * aspectRatio);
  48787. if (w > maxW || w < minW)
  48788. {
  48789. w = jlimit (minW, maxW, w);
  48790. h = roundToInt (w / aspectRatio);
  48791. }
  48792. }
  48793. else
  48794. {
  48795. h = roundToInt (w / aspectRatio);
  48796. if (h > maxH || h < minH)
  48797. {
  48798. h = jlimit (minH, maxH, h);
  48799. w = roundToInt (h * aspectRatio);
  48800. }
  48801. }
  48802. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  48803. {
  48804. x = old.getX() + (old.getWidth() - w) / 2;
  48805. }
  48806. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  48807. {
  48808. y = old.getY() + (old.getHeight() - h) / 2;
  48809. }
  48810. else
  48811. {
  48812. if (isStretchingLeft)
  48813. x = old.getRight() - w;
  48814. if (isStretchingTop)
  48815. y = old.getBottom() - h;
  48816. }
  48817. }
  48818. // ...and constrain the position if limits have been set for that.
  48819. if (minOffTop > 0 || minOffLeft > 0 || minOffBottom > 0 || minOffRight > 0)
  48820. {
  48821. if (minOffTop > 0)
  48822. {
  48823. const int limit = limits.getY() + jmin (minOffTop - h, 0);
  48824. if (y < limit)
  48825. {
  48826. if (isStretchingTop)
  48827. h -= (limit - y);
  48828. y = limit;
  48829. }
  48830. }
  48831. if (minOffLeft > 0)
  48832. {
  48833. const int limit = limits.getX() + jmin (minOffLeft - w, 0);
  48834. if (x < limit)
  48835. {
  48836. if (isStretchingLeft)
  48837. w -= (limit - x);
  48838. x = limit;
  48839. }
  48840. }
  48841. if (minOffBottom > 0)
  48842. {
  48843. const int limit = limits.getBottom() - jmin (minOffBottom, h);
  48844. if (y > limit)
  48845. {
  48846. if (isStretchingBottom)
  48847. h += (limit - y);
  48848. else
  48849. y = limit;
  48850. }
  48851. }
  48852. if (minOffRight > 0)
  48853. {
  48854. const int limit = limits.getRight() - jmin (minOffRight, w);
  48855. if (x > limit)
  48856. {
  48857. if (isStretchingRight)
  48858. w += (limit - x);
  48859. else
  48860. x = limit;
  48861. }
  48862. }
  48863. }
  48864. jassert (w >= 0 && h >= 0);
  48865. bounds = Rectangle<int> (x, y, w, h);
  48866. }
  48867. END_JUCE_NAMESPACE
  48868. /*** End of inlined file: juce_ComponentBoundsConstrainer.cpp ***/
  48869. /*** Start of inlined file: juce_ComponentMovementWatcher.cpp ***/
  48870. BEGIN_JUCE_NAMESPACE
  48871. ComponentMovementWatcher::ComponentMovementWatcher (Component* const component_)
  48872. : component (component_),
  48873. lastPeer (0),
  48874. reentrant (false)
  48875. {
  48876. jassert (component != 0); // can't use this with a null pointer..
  48877. component->addComponentListener (this);
  48878. registerWithParentComps();
  48879. }
  48880. ComponentMovementWatcher::~ComponentMovementWatcher()
  48881. {
  48882. component->removeComponentListener (this);
  48883. unregister();
  48884. }
  48885. void ComponentMovementWatcher::componentParentHierarchyChanged (Component&)
  48886. {
  48887. // agh! don't delete the target component without deleting this object first!
  48888. jassert (component != 0);
  48889. if (! reentrant)
  48890. {
  48891. reentrant = true;
  48892. ComponentPeer* const peer = component->getPeer();
  48893. if (peer != lastPeer)
  48894. {
  48895. componentPeerChanged();
  48896. if (component == 0)
  48897. return;
  48898. lastPeer = peer;
  48899. }
  48900. unregister();
  48901. registerWithParentComps();
  48902. reentrant = false;
  48903. componentMovedOrResized (*component, true, true);
  48904. }
  48905. }
  48906. void ComponentMovementWatcher::componentMovedOrResized (Component&, bool wasMoved, bool wasResized)
  48907. {
  48908. // agh! don't delete the target component without deleting this object first!
  48909. jassert (component != 0);
  48910. if (wasMoved)
  48911. {
  48912. const Point<int> pos (component->relativePositionToOtherComponent (component->getTopLevelComponent(), Point<int>()));
  48913. wasMoved = lastBounds.getPosition() != pos;
  48914. lastBounds.setPosition (pos);
  48915. }
  48916. wasResized = (lastBounds.getWidth() != component->getWidth() || lastBounds.getHeight() != component->getHeight());
  48917. lastBounds.setSize (component->getWidth(), component->getHeight());
  48918. if (wasMoved || wasResized)
  48919. componentMovedOrResized (wasMoved, wasResized);
  48920. }
  48921. void ComponentMovementWatcher::registerWithParentComps() throw()
  48922. {
  48923. Component* p = component->getParentComponent();
  48924. while (p != 0)
  48925. {
  48926. p->addComponentListener (this);
  48927. registeredParentComps.add (p);
  48928. p = p->getParentComponent();
  48929. }
  48930. }
  48931. void ComponentMovementWatcher::unregister() throw()
  48932. {
  48933. for (int i = registeredParentComps.size(); --i >= 0;)
  48934. registeredParentComps.getUnchecked(i)->removeComponentListener (this);
  48935. registeredParentComps.clear();
  48936. }
  48937. END_JUCE_NAMESPACE
  48938. /*** End of inlined file: juce_ComponentMovementWatcher.cpp ***/
  48939. /*** Start of inlined file: juce_GroupComponent.cpp ***/
  48940. BEGIN_JUCE_NAMESPACE
  48941. GroupComponent::GroupComponent (const String& componentName,
  48942. const String& labelText)
  48943. : Component (componentName),
  48944. text (labelText),
  48945. justification (Justification::left)
  48946. {
  48947. setInterceptsMouseClicks (false, true);
  48948. }
  48949. GroupComponent::~GroupComponent()
  48950. {
  48951. }
  48952. void GroupComponent::setText (const String& newText)
  48953. {
  48954. if (text != newText)
  48955. {
  48956. text = newText;
  48957. repaint();
  48958. }
  48959. }
  48960. const String GroupComponent::getText() const
  48961. {
  48962. return text;
  48963. }
  48964. void GroupComponent::setTextLabelPosition (const Justification& newJustification)
  48965. {
  48966. if (justification != newJustification)
  48967. {
  48968. justification = newJustification;
  48969. repaint();
  48970. }
  48971. }
  48972. void GroupComponent::paint (Graphics& g)
  48973. {
  48974. getLookAndFeel()
  48975. .drawGroupComponentOutline (g, getWidth(), getHeight(),
  48976. text, justification,
  48977. *this);
  48978. }
  48979. void GroupComponent::enablementChanged()
  48980. {
  48981. repaint();
  48982. }
  48983. void GroupComponent::colourChanged()
  48984. {
  48985. repaint();
  48986. }
  48987. END_JUCE_NAMESPACE
  48988. /*** End of inlined file: juce_GroupComponent.cpp ***/
  48989. /*** Start of inlined file: juce_MultiDocumentPanel.cpp ***/
  48990. BEGIN_JUCE_NAMESPACE
  48991. MultiDocumentPanelWindow::MultiDocumentPanelWindow (const Colour& backgroundColour)
  48992. : DocumentWindow (String::empty, backgroundColour,
  48993. DocumentWindow::maximiseButton | DocumentWindow::closeButton, false)
  48994. {
  48995. }
  48996. MultiDocumentPanelWindow::~MultiDocumentPanelWindow()
  48997. {
  48998. }
  48999. void MultiDocumentPanelWindow::maximiseButtonPressed()
  49000. {
  49001. MultiDocumentPanel* const owner = getOwner();
  49002. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  49003. if (owner != 0)
  49004. owner->setLayoutMode (MultiDocumentPanel::MaximisedWindowsWithTabs);
  49005. }
  49006. void MultiDocumentPanelWindow::closeButtonPressed()
  49007. {
  49008. MultiDocumentPanel* const owner = getOwner();
  49009. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  49010. if (owner != 0)
  49011. owner->closeDocument (getContentComponent(), true);
  49012. }
  49013. void MultiDocumentPanelWindow::activeWindowStatusChanged()
  49014. {
  49015. DocumentWindow::activeWindowStatusChanged();
  49016. updateOrder();
  49017. }
  49018. void MultiDocumentPanelWindow::broughtToFront()
  49019. {
  49020. DocumentWindow::broughtToFront();
  49021. updateOrder();
  49022. }
  49023. void MultiDocumentPanelWindow::updateOrder()
  49024. {
  49025. MultiDocumentPanel* const owner = getOwner();
  49026. if (owner != 0)
  49027. owner->updateOrder();
  49028. }
  49029. MultiDocumentPanel* MultiDocumentPanelWindow::getOwner() const throw()
  49030. {
  49031. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  49032. return findParentComponentOfClass ((MultiDocumentPanel*) 0);
  49033. }
  49034. class MDITabbedComponentInternal : public TabbedComponent
  49035. {
  49036. public:
  49037. MDITabbedComponentInternal()
  49038. : TabbedComponent (TabbedButtonBar::TabsAtTop)
  49039. {
  49040. }
  49041. ~MDITabbedComponentInternal()
  49042. {
  49043. }
  49044. void currentTabChanged (int, const String&)
  49045. {
  49046. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  49047. MultiDocumentPanel* const owner = findParentComponentOfClass ((MultiDocumentPanel*) 0);
  49048. if (owner != 0)
  49049. owner->updateOrder();
  49050. }
  49051. };
  49052. MultiDocumentPanel::MultiDocumentPanel()
  49053. : mode (MaximisedWindowsWithTabs),
  49054. tabComponent (0),
  49055. backgroundColour (Colours::lightblue),
  49056. maximumNumDocuments (0),
  49057. numDocsBeforeTabsUsed (0)
  49058. {
  49059. setOpaque (true);
  49060. }
  49061. MultiDocumentPanel::~MultiDocumentPanel()
  49062. {
  49063. closeAllDocuments (false);
  49064. }
  49065. static bool shouldDeleteComp (Component* const c)
  49066. {
  49067. return c->getProperties() ["mdiDocumentDelete_"];
  49068. }
  49069. bool MultiDocumentPanel::closeAllDocuments (const bool checkItsOkToCloseFirst)
  49070. {
  49071. while (components.size() > 0)
  49072. if (! closeDocument (components.getLast(), checkItsOkToCloseFirst))
  49073. return false;
  49074. return true;
  49075. }
  49076. MultiDocumentPanelWindow* MultiDocumentPanel::createNewDocumentWindow()
  49077. {
  49078. return new MultiDocumentPanelWindow (backgroundColour);
  49079. }
  49080. void MultiDocumentPanel::addWindow (Component* component)
  49081. {
  49082. MultiDocumentPanelWindow* const dw = createNewDocumentWindow();
  49083. dw->setResizable (true, false);
  49084. dw->setContentComponent (component, false, true);
  49085. dw->setName (component->getName());
  49086. const var bkg (component->getProperties() ["mdiDocumentBkg_"]);
  49087. dw->setBackgroundColour (bkg.isVoid() ? backgroundColour : Colour ((int) bkg));
  49088. int x = 4;
  49089. Component* const topComp = getChildComponent (getNumChildComponents() - 1);
  49090. if (topComp != 0 && topComp->getX() == x && topComp->getY() == x)
  49091. x += 16;
  49092. dw->setTopLeftPosition (x, x);
  49093. const var pos (component->getProperties() ["mdiDocumentPos_"]);
  49094. if (pos.toString().isNotEmpty())
  49095. dw->restoreWindowStateFromString (pos.toString());
  49096. addAndMakeVisible (dw);
  49097. dw->toFront (true);
  49098. }
  49099. bool MultiDocumentPanel::addDocument (Component* const component,
  49100. const Colour& docColour,
  49101. const bool deleteWhenRemoved)
  49102. {
  49103. // If you try passing a full DocumentWindow or ResizableWindow in here, you'll end up
  49104. // with a frame-within-a-frame! Just pass in the bare content component.
  49105. jassert (dynamic_cast <ResizableWindow*> (component) == 0);
  49106. if (component == 0 || (maximumNumDocuments > 0 && components.size() >= maximumNumDocuments))
  49107. return false;
  49108. components.add (component);
  49109. component->getProperties().set ("mdiDocumentDelete_", deleteWhenRemoved);
  49110. component->getProperties().set ("mdiDocumentBkg_", (int) docColour.getARGB());
  49111. component->addComponentListener (this);
  49112. if (mode == FloatingWindows)
  49113. {
  49114. if (isFullscreenWhenOneDocument())
  49115. {
  49116. if (components.size() == 1)
  49117. {
  49118. addAndMakeVisible (component);
  49119. }
  49120. else
  49121. {
  49122. if (components.size() == 2)
  49123. addWindow (components.getFirst());
  49124. addWindow (component);
  49125. }
  49126. }
  49127. else
  49128. {
  49129. addWindow (component);
  49130. }
  49131. }
  49132. else
  49133. {
  49134. if (tabComponent == 0 && components.size() > numDocsBeforeTabsUsed)
  49135. {
  49136. addAndMakeVisible (tabComponent = new MDITabbedComponentInternal());
  49137. Array <Component*> temp (components);
  49138. for (int i = 0; i < temp.size(); ++i)
  49139. tabComponent->addTab (temp[i]->getName(), docColour, temp[i], false);
  49140. resized();
  49141. }
  49142. else
  49143. {
  49144. if (tabComponent != 0)
  49145. tabComponent->addTab (component->getName(), docColour, component, false);
  49146. else
  49147. addAndMakeVisible (component);
  49148. }
  49149. setActiveDocument (component);
  49150. }
  49151. resized();
  49152. activeDocumentChanged();
  49153. return true;
  49154. }
  49155. bool MultiDocumentPanel::closeDocument (Component* component,
  49156. const bool checkItsOkToCloseFirst)
  49157. {
  49158. if (components.contains (component))
  49159. {
  49160. if (checkItsOkToCloseFirst && ! tryToCloseDocument (component))
  49161. return false;
  49162. component->removeComponentListener (this);
  49163. const bool shouldDelete = shouldDeleteComp (component);
  49164. component->getProperties().remove ("mdiDocumentDelete_");
  49165. component->getProperties().remove ("mdiDocumentBkg_");
  49166. if (mode == FloatingWindows)
  49167. {
  49168. for (int i = getNumChildComponents(); --i >= 0;)
  49169. {
  49170. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49171. if (dw != 0 && dw->getContentComponent() == component)
  49172. {
  49173. dw->setContentComponent (0, false);
  49174. delete dw;
  49175. break;
  49176. }
  49177. }
  49178. if (shouldDelete)
  49179. delete component;
  49180. components.removeValue (component);
  49181. if (isFullscreenWhenOneDocument() && components.size() == 1)
  49182. {
  49183. for (int i = getNumChildComponents(); --i >= 0;)
  49184. {
  49185. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49186. if (dw != 0)
  49187. {
  49188. dw->setContentComponent (0, false);
  49189. delete dw;
  49190. }
  49191. }
  49192. addAndMakeVisible (components.getFirst());
  49193. }
  49194. }
  49195. else
  49196. {
  49197. jassert (components.indexOf (component) >= 0);
  49198. if (tabComponent != 0)
  49199. {
  49200. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  49201. if (tabComponent->getTabContentComponent (i) == component)
  49202. tabComponent->removeTab (i);
  49203. }
  49204. else
  49205. {
  49206. removeChildComponent (component);
  49207. }
  49208. if (shouldDelete)
  49209. delete component;
  49210. if (tabComponent != 0 && tabComponent->getNumTabs() <= numDocsBeforeTabsUsed)
  49211. deleteAndZero (tabComponent);
  49212. components.removeValue (component);
  49213. if (components.size() > 0 && tabComponent == 0)
  49214. addAndMakeVisible (components.getFirst());
  49215. }
  49216. resized();
  49217. activeDocumentChanged();
  49218. }
  49219. else
  49220. {
  49221. jassertfalse;
  49222. }
  49223. return true;
  49224. }
  49225. int MultiDocumentPanel::getNumDocuments() const throw()
  49226. {
  49227. return components.size();
  49228. }
  49229. Component* MultiDocumentPanel::getDocument (const int index) const throw()
  49230. {
  49231. return components [index];
  49232. }
  49233. Component* MultiDocumentPanel::getActiveDocument() const throw()
  49234. {
  49235. if (mode == FloatingWindows)
  49236. {
  49237. for (int i = getNumChildComponents(); --i >= 0;)
  49238. {
  49239. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49240. if (dw != 0 && dw->isActiveWindow())
  49241. return dw->getContentComponent();
  49242. }
  49243. }
  49244. return components.getLast();
  49245. }
  49246. void MultiDocumentPanel::setActiveDocument (Component* component)
  49247. {
  49248. if (mode == FloatingWindows)
  49249. {
  49250. component = getContainerComp (component);
  49251. if (component != 0)
  49252. component->toFront (true);
  49253. }
  49254. else if (tabComponent != 0)
  49255. {
  49256. jassert (components.indexOf (component) >= 0);
  49257. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  49258. {
  49259. if (tabComponent->getTabContentComponent (i) == component)
  49260. {
  49261. tabComponent->setCurrentTabIndex (i);
  49262. break;
  49263. }
  49264. }
  49265. }
  49266. else
  49267. {
  49268. component->grabKeyboardFocus();
  49269. }
  49270. }
  49271. void MultiDocumentPanel::activeDocumentChanged()
  49272. {
  49273. }
  49274. void MultiDocumentPanel::setMaximumNumDocuments (const int newNumber)
  49275. {
  49276. maximumNumDocuments = newNumber;
  49277. }
  49278. void MultiDocumentPanel::useFullscreenWhenOneDocument (const bool shouldUseTabs)
  49279. {
  49280. numDocsBeforeTabsUsed = shouldUseTabs ? 1 : 0;
  49281. }
  49282. bool MultiDocumentPanel::isFullscreenWhenOneDocument() const throw()
  49283. {
  49284. return numDocsBeforeTabsUsed != 0;
  49285. }
  49286. void MultiDocumentPanel::setLayoutMode (const LayoutMode newLayoutMode)
  49287. {
  49288. if (mode != newLayoutMode)
  49289. {
  49290. mode = newLayoutMode;
  49291. if (mode == FloatingWindows)
  49292. {
  49293. deleteAndZero (tabComponent);
  49294. }
  49295. else
  49296. {
  49297. for (int i = getNumChildComponents(); --i >= 0;)
  49298. {
  49299. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49300. if (dw != 0)
  49301. {
  49302. dw->getContentComponent()->getProperties().set ("mdiDocumentPos_", dw->getWindowStateAsString());
  49303. dw->setContentComponent (0, false);
  49304. delete dw;
  49305. }
  49306. }
  49307. }
  49308. resized();
  49309. const Array <Component*> tempComps (components);
  49310. components.clear();
  49311. for (int i = 0; i < tempComps.size(); ++i)
  49312. {
  49313. Component* const c = tempComps.getUnchecked(i);
  49314. addDocument (c,
  49315. Colour ((int) c->getProperties().getWithDefault ("mdiDocumentBkg_", (int) Colours::white.getARGB())),
  49316. shouldDeleteComp (c));
  49317. }
  49318. }
  49319. }
  49320. void MultiDocumentPanel::setBackgroundColour (const Colour& newBackgroundColour)
  49321. {
  49322. if (backgroundColour != newBackgroundColour)
  49323. {
  49324. backgroundColour = newBackgroundColour;
  49325. setOpaque (newBackgroundColour.isOpaque());
  49326. repaint();
  49327. }
  49328. }
  49329. void MultiDocumentPanel::paint (Graphics& g)
  49330. {
  49331. g.fillAll (backgroundColour);
  49332. }
  49333. void MultiDocumentPanel::resized()
  49334. {
  49335. if (mode == MaximisedWindowsWithTabs || components.size() == numDocsBeforeTabsUsed)
  49336. {
  49337. for (int i = getNumChildComponents(); --i >= 0;)
  49338. getChildComponent (i)->setBounds (0, 0, getWidth(), getHeight());
  49339. }
  49340. setWantsKeyboardFocus (components.size() == 0);
  49341. }
  49342. Component* MultiDocumentPanel::getContainerComp (Component* c) const
  49343. {
  49344. if (mode == FloatingWindows)
  49345. {
  49346. for (int i = 0; i < getNumChildComponents(); ++i)
  49347. {
  49348. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49349. if (dw != 0 && dw->getContentComponent() == c)
  49350. {
  49351. c = dw;
  49352. break;
  49353. }
  49354. }
  49355. }
  49356. return c;
  49357. }
  49358. void MultiDocumentPanel::componentNameChanged (Component&)
  49359. {
  49360. if (mode == FloatingWindows)
  49361. {
  49362. for (int i = 0; i < getNumChildComponents(); ++i)
  49363. {
  49364. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49365. if (dw != 0)
  49366. dw->setName (dw->getContentComponent()->getName());
  49367. }
  49368. }
  49369. else if (tabComponent != 0)
  49370. {
  49371. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  49372. tabComponent->setTabName (i, tabComponent->getTabContentComponent (i)->getName());
  49373. }
  49374. }
  49375. void MultiDocumentPanel::updateOrder()
  49376. {
  49377. const Array <Component*> oldList (components);
  49378. if (mode == FloatingWindows)
  49379. {
  49380. components.clear();
  49381. for (int i = 0; i < getNumChildComponents(); ++i)
  49382. {
  49383. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49384. if (dw != 0)
  49385. components.add (dw->getContentComponent());
  49386. }
  49387. }
  49388. else
  49389. {
  49390. if (tabComponent != 0)
  49391. {
  49392. Component* const current = tabComponent->getCurrentContentComponent();
  49393. if (current != 0)
  49394. {
  49395. components.removeValue (current);
  49396. components.add (current);
  49397. }
  49398. }
  49399. }
  49400. if (components != oldList)
  49401. activeDocumentChanged();
  49402. }
  49403. END_JUCE_NAMESPACE
  49404. /*** End of inlined file: juce_MultiDocumentPanel.cpp ***/
  49405. /*** Start of inlined file: juce_ResizableBorderComponent.cpp ***/
  49406. BEGIN_JUCE_NAMESPACE
  49407. ResizableBorderComponent::Zone::Zone (int zoneFlags) throw()
  49408. : zone (zoneFlags)
  49409. {
  49410. }
  49411. ResizableBorderComponent::Zone::Zone (const ResizableBorderComponent::Zone& other) throw() : zone (other.zone) {}
  49412. ResizableBorderComponent::Zone& ResizableBorderComponent::Zone::operator= (const ResizableBorderComponent::Zone& other) throw() { zone = other.zone; return *this; }
  49413. bool ResizableBorderComponent::Zone::operator== (const ResizableBorderComponent::Zone& other) const throw() { return zone == other.zone; }
  49414. bool ResizableBorderComponent::Zone::operator!= (const ResizableBorderComponent::Zone& other) const throw() { return zone != other.zone; }
  49415. const ResizableBorderComponent::Zone ResizableBorderComponent::Zone::fromPositionOnBorder (const Rectangle<int>& totalSize,
  49416. const BorderSize& border,
  49417. const Point<int>& position)
  49418. {
  49419. int z = 0;
  49420. if (totalSize.contains (position)
  49421. && ! border.subtractedFrom (totalSize).contains (position))
  49422. {
  49423. const int minW = jmax (totalSize.getWidth() / 10, jmin (10, totalSize.getWidth() / 3));
  49424. if (position.getX() < jmax (border.getLeft(), minW))
  49425. z |= left;
  49426. else if (position.getX() >= totalSize.getWidth() - jmax (border.getRight(), minW))
  49427. z |= right;
  49428. const int minH = jmax (totalSize.getHeight() / 10, jmin (10, totalSize.getHeight() / 3));
  49429. if (position.getY() < jmax (border.getTop(), minH))
  49430. z |= top;
  49431. else if (position.getY() >= totalSize.getHeight() - jmax (border.getBottom(), minH))
  49432. z |= bottom;
  49433. }
  49434. return Zone (z);
  49435. }
  49436. const MouseCursor ResizableBorderComponent::Zone::getMouseCursor() const throw()
  49437. {
  49438. MouseCursor::StandardCursorType mc = MouseCursor::NormalCursor;
  49439. switch (zone)
  49440. {
  49441. case (left | top): mc = MouseCursor::TopLeftCornerResizeCursor; break;
  49442. case top: mc = MouseCursor::TopEdgeResizeCursor; break;
  49443. case (right | top): mc = MouseCursor::TopRightCornerResizeCursor; break;
  49444. case left: mc = MouseCursor::LeftEdgeResizeCursor; break;
  49445. case right: mc = MouseCursor::RightEdgeResizeCursor; break;
  49446. case (left | bottom): mc = MouseCursor::BottomLeftCornerResizeCursor; break;
  49447. case bottom: mc = MouseCursor::BottomEdgeResizeCursor; break;
  49448. case (right | bottom): mc = MouseCursor::BottomRightCornerResizeCursor; break;
  49449. default: break;
  49450. }
  49451. return mc;
  49452. }
  49453. const Rectangle<int> ResizableBorderComponent::Zone::resizeRectangleBy (Rectangle<int> b, const Point<int>& offset) const throw()
  49454. {
  49455. if (isDraggingWholeObject())
  49456. return b + offset;
  49457. if (isDraggingLeftEdge())
  49458. b.setLeft (b.getX() + offset.getX());
  49459. if (isDraggingRightEdge())
  49460. b.setWidth (jmax (0, b.getWidth() + offset.getX()));
  49461. if (isDraggingTopEdge())
  49462. b.setTop (b.getY() + offset.getY());
  49463. if (isDraggingBottomEdge())
  49464. b.setHeight (jmax (0, b.getHeight() + offset.getY()));
  49465. return b;
  49466. }
  49467. const Rectangle<float> ResizableBorderComponent::Zone::resizeRectangleBy (Rectangle<float> b, const Point<float>& offset) const throw()
  49468. {
  49469. if (isDraggingWholeObject())
  49470. return b + offset;
  49471. if (isDraggingLeftEdge())
  49472. b.setLeft (b.getX() + offset.getX());
  49473. if (isDraggingRightEdge())
  49474. b.setWidth (jmax (0.0f, b.getWidth() + offset.getX()));
  49475. if (isDraggingTopEdge())
  49476. b.setTop (b.getY() + offset.getY());
  49477. if (isDraggingBottomEdge())
  49478. b.setHeight (jmax (0.0f, b.getHeight() + offset.getY()));
  49479. return b;
  49480. }
  49481. ResizableBorderComponent::ResizableBorderComponent (Component* const componentToResize,
  49482. ComponentBoundsConstrainer* const constrainer_)
  49483. : component (componentToResize),
  49484. constrainer (constrainer_),
  49485. borderSize (5),
  49486. mouseZone (0)
  49487. {
  49488. }
  49489. ResizableBorderComponent::~ResizableBorderComponent()
  49490. {
  49491. }
  49492. void ResizableBorderComponent::paint (Graphics& g)
  49493. {
  49494. getLookAndFeel().drawResizableFrame (g, getWidth(), getHeight(), borderSize);
  49495. }
  49496. void ResizableBorderComponent::mouseEnter (const MouseEvent& e)
  49497. {
  49498. updateMouseZone (e);
  49499. }
  49500. void ResizableBorderComponent::mouseMove (const MouseEvent& e)
  49501. {
  49502. updateMouseZone (e);
  49503. }
  49504. void ResizableBorderComponent::mouseDown (const MouseEvent& e)
  49505. {
  49506. if (component == 0)
  49507. {
  49508. jassertfalse; // You've deleted the component that this resizer was supposed to be using!
  49509. return;
  49510. }
  49511. updateMouseZone (e);
  49512. originalBounds = component->getBounds();
  49513. if (constrainer != 0)
  49514. constrainer->resizeStart();
  49515. }
  49516. void ResizableBorderComponent::mouseDrag (const MouseEvent& e)
  49517. {
  49518. if (component == 0)
  49519. {
  49520. jassertfalse; // You've deleted the component that this resizer was supposed to be using!
  49521. return;
  49522. }
  49523. const Rectangle<int> bounds (mouseZone.resizeRectangleBy (originalBounds, e.getOffsetFromDragStart()));
  49524. if (constrainer != 0)
  49525. constrainer->setBoundsForComponent (component, bounds,
  49526. mouseZone.isDraggingTopEdge(),
  49527. mouseZone.isDraggingLeftEdge(),
  49528. mouseZone.isDraggingBottomEdge(),
  49529. mouseZone.isDraggingRightEdge());
  49530. else
  49531. component->setBounds (bounds);
  49532. }
  49533. void ResizableBorderComponent::mouseUp (const MouseEvent&)
  49534. {
  49535. if (constrainer != 0)
  49536. constrainer->resizeEnd();
  49537. }
  49538. bool ResizableBorderComponent::hitTest (int x, int y)
  49539. {
  49540. return x < borderSize.getLeft()
  49541. || x >= getWidth() - borderSize.getRight()
  49542. || y < borderSize.getTop()
  49543. || y >= getHeight() - borderSize.getBottom();
  49544. }
  49545. void ResizableBorderComponent::setBorderThickness (const BorderSize& newBorderSize)
  49546. {
  49547. if (borderSize != newBorderSize)
  49548. {
  49549. borderSize = newBorderSize;
  49550. repaint();
  49551. }
  49552. }
  49553. const BorderSize ResizableBorderComponent::getBorderThickness() const
  49554. {
  49555. return borderSize;
  49556. }
  49557. void ResizableBorderComponent::updateMouseZone (const MouseEvent& e)
  49558. {
  49559. Zone newZone (Zone::fromPositionOnBorder (getLocalBounds(), borderSize, e.getPosition()));
  49560. if (mouseZone != newZone)
  49561. {
  49562. mouseZone = newZone;
  49563. setMouseCursor (newZone.getMouseCursor());
  49564. }
  49565. }
  49566. END_JUCE_NAMESPACE
  49567. /*** End of inlined file: juce_ResizableBorderComponent.cpp ***/
  49568. /*** Start of inlined file: juce_ResizableCornerComponent.cpp ***/
  49569. BEGIN_JUCE_NAMESPACE
  49570. ResizableCornerComponent::ResizableCornerComponent (Component* const componentToResize,
  49571. ComponentBoundsConstrainer* const constrainer_)
  49572. : component (componentToResize),
  49573. constrainer (constrainer_)
  49574. {
  49575. setRepaintsOnMouseActivity (true);
  49576. setMouseCursor (MouseCursor::BottomRightCornerResizeCursor);
  49577. }
  49578. ResizableCornerComponent::~ResizableCornerComponent()
  49579. {
  49580. }
  49581. void ResizableCornerComponent::paint (Graphics& g)
  49582. {
  49583. getLookAndFeel()
  49584. .drawCornerResizer (g, getWidth(), getHeight(),
  49585. isMouseOverOrDragging(),
  49586. isMouseButtonDown());
  49587. }
  49588. void ResizableCornerComponent::mouseDown (const MouseEvent&)
  49589. {
  49590. if (component == 0)
  49591. {
  49592. jassertfalse; // You've deleted the component that this resizer is supposed to be controlling!
  49593. return;
  49594. }
  49595. originalBounds = component->getBounds();
  49596. if (constrainer != 0)
  49597. constrainer->resizeStart();
  49598. }
  49599. void ResizableCornerComponent::mouseDrag (const MouseEvent& e)
  49600. {
  49601. if (component == 0)
  49602. {
  49603. jassertfalse; // You've deleted the component that this resizer is supposed to be controlling!
  49604. return;
  49605. }
  49606. Rectangle<int> r (originalBounds.withSize (originalBounds.getWidth() + e.getDistanceFromDragStartX(),
  49607. originalBounds.getHeight() + e.getDistanceFromDragStartY()));
  49608. if (constrainer != 0)
  49609. constrainer->setBoundsForComponent (component, r, false, false, true, true);
  49610. else
  49611. component->setBounds (r);
  49612. }
  49613. void ResizableCornerComponent::mouseUp (const MouseEvent&)
  49614. {
  49615. if (constrainer != 0)
  49616. constrainer->resizeStart();
  49617. }
  49618. bool ResizableCornerComponent::hitTest (int x, int y)
  49619. {
  49620. if (getWidth() <= 0)
  49621. return false;
  49622. const int yAtX = getHeight() - (getHeight() * x / getWidth());
  49623. return y >= yAtX - getHeight() / 4;
  49624. }
  49625. END_JUCE_NAMESPACE
  49626. /*** End of inlined file: juce_ResizableCornerComponent.cpp ***/
  49627. /*** Start of inlined file: juce_ScrollBar.cpp ***/
  49628. BEGIN_JUCE_NAMESPACE
  49629. class ScrollBar::ScrollbarButton : public Button
  49630. {
  49631. public:
  49632. int direction;
  49633. ScrollbarButton (const int direction_, ScrollBar& owner_)
  49634. : Button (String::empty),
  49635. direction (direction_),
  49636. owner (owner_)
  49637. {
  49638. setWantsKeyboardFocus (false);
  49639. }
  49640. ~ScrollbarButton()
  49641. {
  49642. }
  49643. void paintButton (Graphics& g, bool over, bool down)
  49644. {
  49645. getLookAndFeel()
  49646. .drawScrollbarButton (g, owner,
  49647. getWidth(), getHeight(),
  49648. direction,
  49649. owner.isVertical(),
  49650. over, down);
  49651. }
  49652. void clicked()
  49653. {
  49654. owner.moveScrollbarInSteps ((direction == 1 || direction == 2) ? 1 : -1);
  49655. }
  49656. juce_UseDebuggingNewOperator
  49657. private:
  49658. ScrollBar& owner;
  49659. ScrollbarButton (const ScrollbarButton&);
  49660. ScrollbarButton& operator= (const ScrollbarButton&);
  49661. };
  49662. ScrollBar::ScrollBar (const bool vertical_,
  49663. const bool buttonsAreVisible)
  49664. : totalRange (0.0, 1.0),
  49665. visibleRange (0.0, 0.1),
  49666. singleStepSize (0.1),
  49667. thumbAreaStart (0),
  49668. thumbAreaSize (0),
  49669. thumbStart (0),
  49670. thumbSize (0),
  49671. initialDelayInMillisecs (100),
  49672. repeatDelayInMillisecs (50),
  49673. minimumDelayInMillisecs (10),
  49674. vertical (vertical_),
  49675. isDraggingThumb (false),
  49676. autohides (true)
  49677. {
  49678. setButtonVisibility (buttonsAreVisible);
  49679. setRepaintsOnMouseActivity (true);
  49680. setFocusContainer (true);
  49681. }
  49682. ScrollBar::~ScrollBar()
  49683. {
  49684. upButton = 0;
  49685. downButton = 0;
  49686. }
  49687. void ScrollBar::setRangeLimits (const Range<double>& newRangeLimit)
  49688. {
  49689. if (totalRange != newRangeLimit)
  49690. {
  49691. totalRange = newRangeLimit;
  49692. setCurrentRange (visibleRange);
  49693. updateThumbPosition();
  49694. }
  49695. }
  49696. void ScrollBar::setRangeLimits (const double newMinimum, const double newMaximum)
  49697. {
  49698. jassert (newMaximum >= newMinimum); // these can't be the wrong way round!
  49699. setRangeLimits (Range<double> (newMinimum, newMaximum));
  49700. }
  49701. void ScrollBar::setCurrentRange (const Range<double>& newRange)
  49702. {
  49703. const Range<double> constrainedRange (totalRange.constrainRange (newRange));
  49704. if (visibleRange != constrainedRange)
  49705. {
  49706. visibleRange = constrainedRange;
  49707. updateThumbPosition();
  49708. triggerAsyncUpdate();
  49709. }
  49710. }
  49711. void ScrollBar::setCurrentRange (const double newStart, const double newSize)
  49712. {
  49713. setCurrentRange (Range<double> (newStart, newStart + newSize));
  49714. }
  49715. void ScrollBar::setCurrentRangeStart (const double newStart)
  49716. {
  49717. setCurrentRange (visibleRange.movedToStartAt (newStart));
  49718. }
  49719. void ScrollBar::setSingleStepSize (const double newSingleStepSize)
  49720. {
  49721. singleStepSize = newSingleStepSize;
  49722. }
  49723. void ScrollBar::moveScrollbarInSteps (const int howManySteps)
  49724. {
  49725. setCurrentRange (visibleRange + howManySteps * singleStepSize);
  49726. }
  49727. void ScrollBar::moveScrollbarInPages (const int howManyPages)
  49728. {
  49729. setCurrentRange (visibleRange + howManyPages * visibleRange.getLength());
  49730. }
  49731. void ScrollBar::scrollToTop()
  49732. {
  49733. setCurrentRange (visibleRange.movedToStartAt (getMinimumRangeLimit()));
  49734. }
  49735. void ScrollBar::scrollToBottom()
  49736. {
  49737. setCurrentRange (visibleRange.movedToEndAt (getMaximumRangeLimit()));
  49738. }
  49739. void ScrollBar::setButtonRepeatSpeed (const int initialDelayInMillisecs_,
  49740. const int repeatDelayInMillisecs_,
  49741. const int minimumDelayInMillisecs_)
  49742. {
  49743. initialDelayInMillisecs = initialDelayInMillisecs_;
  49744. repeatDelayInMillisecs = repeatDelayInMillisecs_;
  49745. minimumDelayInMillisecs = minimumDelayInMillisecs_;
  49746. if (upButton != 0)
  49747. {
  49748. upButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  49749. downButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  49750. }
  49751. }
  49752. void ScrollBar::addListener (ScrollBarListener* const listener)
  49753. {
  49754. listeners.add (listener);
  49755. }
  49756. void ScrollBar::removeListener (ScrollBarListener* const listener)
  49757. {
  49758. listeners.remove (listener);
  49759. }
  49760. void ScrollBar::handleAsyncUpdate()
  49761. {
  49762. double start = visibleRange.getStart(); // (need to use a temp variable for VC7 compatibility)
  49763. listeners.call (&ScrollBarListener::scrollBarMoved, this, start);
  49764. }
  49765. void ScrollBar::updateThumbPosition()
  49766. {
  49767. int newThumbSize = roundToInt (totalRange.getLength() > 0 ? (visibleRange.getLength() * thumbAreaSize) / totalRange.getLength()
  49768. : thumbAreaSize);
  49769. if (newThumbSize < getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  49770. newThumbSize = jmin (getLookAndFeel().getMinimumScrollbarThumbSize (*this), thumbAreaSize - 1);
  49771. if (newThumbSize > thumbAreaSize)
  49772. newThumbSize = thumbAreaSize;
  49773. int newThumbStart = thumbAreaStart;
  49774. if (totalRange.getLength() > visibleRange.getLength())
  49775. newThumbStart += roundToInt (((visibleRange.getStart() - totalRange.getStart()) * (thumbAreaSize - newThumbSize))
  49776. / (totalRange.getLength() - visibleRange.getLength()));
  49777. setVisible ((! autohides) || (totalRange.getLength() > visibleRange.getLength() && visibleRange.getLength() > 0.0));
  49778. if (thumbStart != newThumbStart || thumbSize != newThumbSize)
  49779. {
  49780. const int repaintStart = jmin (thumbStart, newThumbStart) - 4;
  49781. const int repaintSize = jmax (thumbStart + thumbSize, newThumbStart + newThumbSize) + 8 - repaintStart;
  49782. if (vertical)
  49783. repaint (0, repaintStart, getWidth(), repaintSize);
  49784. else
  49785. repaint (repaintStart, 0, repaintSize, getHeight());
  49786. thumbStart = newThumbStart;
  49787. thumbSize = newThumbSize;
  49788. }
  49789. }
  49790. void ScrollBar::setOrientation (const bool shouldBeVertical)
  49791. {
  49792. if (vertical != shouldBeVertical)
  49793. {
  49794. vertical = shouldBeVertical;
  49795. if (upButton != 0)
  49796. {
  49797. upButton->direction = vertical ? 0 : 3;
  49798. downButton->direction = vertical ? 2 : 1;
  49799. }
  49800. updateThumbPosition();
  49801. }
  49802. }
  49803. void ScrollBar::setButtonVisibility (const bool buttonsAreVisible)
  49804. {
  49805. upButton = 0;
  49806. downButton = 0;
  49807. if (buttonsAreVisible)
  49808. {
  49809. addAndMakeVisible (upButton = new ScrollbarButton (vertical ? 0 : 3, *this));
  49810. addAndMakeVisible (downButton = new ScrollbarButton (vertical ? 2 : 1, *this));
  49811. setButtonRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  49812. }
  49813. updateThumbPosition();
  49814. }
  49815. void ScrollBar::setAutoHide (const bool shouldHideWhenFullRange)
  49816. {
  49817. autohides = shouldHideWhenFullRange;
  49818. updateThumbPosition();
  49819. }
  49820. bool ScrollBar::autoHides() const throw()
  49821. {
  49822. return autohides;
  49823. }
  49824. void ScrollBar::paint (Graphics& g)
  49825. {
  49826. if (thumbAreaSize > 0)
  49827. {
  49828. LookAndFeel& lf = getLookAndFeel();
  49829. const int thumb = (thumbAreaSize > lf.getMinimumScrollbarThumbSize (*this))
  49830. ? thumbSize : 0;
  49831. if (vertical)
  49832. {
  49833. lf.drawScrollbar (g, *this,
  49834. 0, thumbAreaStart,
  49835. getWidth(), thumbAreaSize,
  49836. vertical,
  49837. thumbStart, thumb,
  49838. isMouseOver(), isMouseButtonDown());
  49839. }
  49840. else
  49841. {
  49842. lf.drawScrollbar (g, *this,
  49843. thumbAreaStart, 0,
  49844. thumbAreaSize, getHeight(),
  49845. vertical,
  49846. thumbStart, thumb,
  49847. isMouseOver(), isMouseButtonDown());
  49848. }
  49849. }
  49850. }
  49851. void ScrollBar::lookAndFeelChanged()
  49852. {
  49853. setComponentEffect (getLookAndFeel().getScrollbarEffect());
  49854. }
  49855. void ScrollBar::resized()
  49856. {
  49857. const int length = ((vertical) ? getHeight() : getWidth());
  49858. const int buttonSize = (upButton != 0) ? jmin (getLookAndFeel().getScrollbarButtonSize (*this), (length >> 1))
  49859. : 0;
  49860. if (length < 32 + getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  49861. {
  49862. thumbAreaStart = length >> 1;
  49863. thumbAreaSize = 0;
  49864. }
  49865. else
  49866. {
  49867. thumbAreaStart = buttonSize;
  49868. thumbAreaSize = length - (buttonSize << 1);
  49869. }
  49870. if (upButton != 0)
  49871. {
  49872. if (vertical)
  49873. {
  49874. upButton->setBounds (0, 0, getWidth(), buttonSize);
  49875. downButton->setBounds (0, thumbAreaStart + thumbAreaSize, getWidth(), buttonSize);
  49876. }
  49877. else
  49878. {
  49879. upButton->setBounds (0, 0, buttonSize, getHeight());
  49880. downButton->setBounds (thumbAreaStart + thumbAreaSize, 0, buttonSize, getHeight());
  49881. }
  49882. }
  49883. updateThumbPosition();
  49884. }
  49885. void ScrollBar::mouseDown (const MouseEvent& e)
  49886. {
  49887. isDraggingThumb = false;
  49888. lastMousePos = vertical ? e.y : e.x;
  49889. dragStartMousePos = lastMousePos;
  49890. dragStartRange = visibleRange.getStart();
  49891. if (dragStartMousePos < thumbStart)
  49892. {
  49893. moveScrollbarInPages (-1);
  49894. startTimer (400);
  49895. }
  49896. else if (dragStartMousePos >= thumbStart + thumbSize)
  49897. {
  49898. moveScrollbarInPages (1);
  49899. startTimer (400);
  49900. }
  49901. else
  49902. {
  49903. isDraggingThumb = (thumbAreaSize > getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  49904. && (thumbAreaSize > thumbSize);
  49905. }
  49906. }
  49907. void ScrollBar::mouseDrag (const MouseEvent& e)
  49908. {
  49909. if (isDraggingThumb)
  49910. {
  49911. const int deltaPixels = ((vertical) ? e.y : e.x) - dragStartMousePos;
  49912. setCurrentRangeStart (dragStartRange
  49913. + deltaPixels * (totalRange.getLength() - visibleRange.getLength())
  49914. / (thumbAreaSize - thumbSize));
  49915. }
  49916. else
  49917. {
  49918. lastMousePos = (vertical) ? e.y : e.x;
  49919. }
  49920. }
  49921. void ScrollBar::mouseUp (const MouseEvent&)
  49922. {
  49923. isDraggingThumb = false;
  49924. stopTimer();
  49925. repaint();
  49926. }
  49927. void ScrollBar::mouseWheelMove (const MouseEvent&,
  49928. float wheelIncrementX,
  49929. float wheelIncrementY)
  49930. {
  49931. float increment = vertical ? wheelIncrementY : wheelIncrementX;
  49932. if (increment < 0)
  49933. increment = jmin (increment * 10.0f, -1.0f);
  49934. else if (increment > 0)
  49935. increment = jmax (increment * 10.0f, 1.0f);
  49936. setCurrentRange (visibleRange - singleStepSize * increment);
  49937. }
  49938. void ScrollBar::timerCallback()
  49939. {
  49940. if (isMouseButtonDown())
  49941. {
  49942. startTimer (40);
  49943. if (lastMousePos < thumbStart)
  49944. setCurrentRange (visibleRange - visibleRange.getLength());
  49945. else if (lastMousePos > thumbStart + thumbSize)
  49946. setCurrentRangeStart (visibleRange.getEnd());
  49947. }
  49948. else
  49949. {
  49950. stopTimer();
  49951. }
  49952. }
  49953. bool ScrollBar::keyPressed (const KeyPress& key)
  49954. {
  49955. if (! isVisible())
  49956. return false;
  49957. if (key.isKeyCode (KeyPress::upKey) || key.isKeyCode (KeyPress::leftKey))
  49958. moveScrollbarInSteps (-1);
  49959. else if (key.isKeyCode (KeyPress::downKey) || key.isKeyCode (KeyPress::rightKey))
  49960. moveScrollbarInSteps (1);
  49961. else if (key.isKeyCode (KeyPress::pageUpKey))
  49962. moveScrollbarInPages (-1);
  49963. else if (key.isKeyCode (KeyPress::pageDownKey))
  49964. moveScrollbarInPages (1);
  49965. else if (key.isKeyCode (KeyPress::homeKey))
  49966. scrollToTop();
  49967. else if (key.isKeyCode (KeyPress::endKey))
  49968. scrollToBottom();
  49969. else
  49970. return false;
  49971. return true;
  49972. }
  49973. END_JUCE_NAMESPACE
  49974. /*** End of inlined file: juce_ScrollBar.cpp ***/
  49975. /*** Start of inlined file: juce_StretchableLayoutManager.cpp ***/
  49976. BEGIN_JUCE_NAMESPACE
  49977. StretchableLayoutManager::StretchableLayoutManager()
  49978. : totalSize (0)
  49979. {
  49980. }
  49981. StretchableLayoutManager::~StretchableLayoutManager()
  49982. {
  49983. }
  49984. void StretchableLayoutManager::clearAllItems()
  49985. {
  49986. items.clear();
  49987. totalSize = 0;
  49988. }
  49989. void StretchableLayoutManager::setItemLayout (const int itemIndex,
  49990. const double minimumSize,
  49991. const double maximumSize,
  49992. const double preferredSize)
  49993. {
  49994. ItemLayoutProperties* layout = getInfoFor (itemIndex);
  49995. if (layout == 0)
  49996. {
  49997. layout = new ItemLayoutProperties();
  49998. layout->itemIndex = itemIndex;
  49999. int i;
  50000. for (i = 0; i < items.size(); ++i)
  50001. if (items.getUnchecked (i)->itemIndex > itemIndex)
  50002. break;
  50003. items.insert (i, layout);
  50004. }
  50005. layout->minSize = minimumSize;
  50006. layout->maxSize = maximumSize;
  50007. layout->preferredSize = preferredSize;
  50008. layout->currentSize = 0;
  50009. }
  50010. bool StretchableLayoutManager::getItemLayout (const int itemIndex,
  50011. double& minimumSize,
  50012. double& maximumSize,
  50013. double& preferredSize) const
  50014. {
  50015. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  50016. if (layout != 0)
  50017. {
  50018. minimumSize = layout->minSize;
  50019. maximumSize = layout->maxSize;
  50020. preferredSize = layout->preferredSize;
  50021. return true;
  50022. }
  50023. return false;
  50024. }
  50025. void StretchableLayoutManager::setTotalSize (const int newTotalSize)
  50026. {
  50027. totalSize = newTotalSize;
  50028. fitComponentsIntoSpace (0, items.size(), totalSize, 0);
  50029. }
  50030. int StretchableLayoutManager::getItemCurrentPosition (const int itemIndex) const
  50031. {
  50032. int pos = 0;
  50033. for (int i = 0; i < itemIndex; ++i)
  50034. {
  50035. const ItemLayoutProperties* const layout = getInfoFor (i);
  50036. if (layout != 0)
  50037. pos += layout->currentSize;
  50038. }
  50039. return pos;
  50040. }
  50041. int StretchableLayoutManager::getItemCurrentAbsoluteSize (const int itemIndex) const
  50042. {
  50043. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  50044. if (layout != 0)
  50045. return layout->currentSize;
  50046. return 0;
  50047. }
  50048. double StretchableLayoutManager::getItemCurrentRelativeSize (const int itemIndex) const
  50049. {
  50050. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  50051. if (layout != 0)
  50052. return -layout->currentSize / (double) totalSize;
  50053. return 0;
  50054. }
  50055. void StretchableLayoutManager::setItemPosition (const int itemIndex,
  50056. int newPosition)
  50057. {
  50058. for (int i = items.size(); --i >= 0;)
  50059. {
  50060. const ItemLayoutProperties* const layout = items.getUnchecked(i);
  50061. if (layout->itemIndex == itemIndex)
  50062. {
  50063. int realTotalSize = jmax (totalSize, getMinimumSizeOfItems (0, items.size()));
  50064. const int minSizeAfterThisComp = getMinimumSizeOfItems (i, items.size());
  50065. const int maxSizeAfterThisComp = getMaximumSizeOfItems (i + 1, items.size());
  50066. newPosition = jmax (newPosition, totalSize - maxSizeAfterThisComp - layout->currentSize);
  50067. newPosition = jmin (newPosition, realTotalSize - minSizeAfterThisComp);
  50068. int endPos = fitComponentsIntoSpace (0, i, newPosition, 0);
  50069. endPos += layout->currentSize;
  50070. fitComponentsIntoSpace (i + 1, items.size(), totalSize - endPos, endPos);
  50071. updatePrefSizesToMatchCurrentPositions();
  50072. break;
  50073. }
  50074. }
  50075. }
  50076. void StretchableLayoutManager::layOutComponents (Component** const components,
  50077. int numComponents,
  50078. int x, int y, int w, int h,
  50079. const bool vertically,
  50080. const bool resizeOtherDimension)
  50081. {
  50082. setTotalSize (vertically ? h : w);
  50083. int pos = vertically ? y : x;
  50084. for (int i = 0; i < numComponents; ++i)
  50085. {
  50086. const ItemLayoutProperties* const layout = getInfoFor (i);
  50087. if (layout != 0)
  50088. {
  50089. Component* const c = components[i];
  50090. if (c != 0)
  50091. {
  50092. if (i == numComponents - 1)
  50093. {
  50094. // if it's the last item, crop it to exactly fit the available space..
  50095. if (resizeOtherDimension)
  50096. {
  50097. if (vertically)
  50098. c->setBounds (x, pos, w, jmax (layout->currentSize, h - pos));
  50099. else
  50100. c->setBounds (pos, y, jmax (layout->currentSize, w - pos), h);
  50101. }
  50102. else
  50103. {
  50104. if (vertically)
  50105. c->setBounds (c->getX(), pos, c->getWidth(), jmax (layout->currentSize, h - pos));
  50106. else
  50107. c->setBounds (pos, c->getY(), jmax (layout->currentSize, w - pos), c->getHeight());
  50108. }
  50109. }
  50110. else
  50111. {
  50112. if (resizeOtherDimension)
  50113. {
  50114. if (vertically)
  50115. c->setBounds (x, pos, w, layout->currentSize);
  50116. else
  50117. c->setBounds (pos, y, layout->currentSize, h);
  50118. }
  50119. else
  50120. {
  50121. if (vertically)
  50122. c->setBounds (c->getX(), pos, c->getWidth(), layout->currentSize);
  50123. else
  50124. c->setBounds (pos, c->getY(), layout->currentSize, c->getHeight());
  50125. }
  50126. }
  50127. }
  50128. pos += layout->currentSize;
  50129. }
  50130. }
  50131. }
  50132. StretchableLayoutManager::ItemLayoutProperties* StretchableLayoutManager::getInfoFor (const int itemIndex) const
  50133. {
  50134. for (int i = items.size(); --i >= 0;)
  50135. if (items.getUnchecked(i)->itemIndex == itemIndex)
  50136. return items.getUnchecked(i);
  50137. return 0;
  50138. }
  50139. int StretchableLayoutManager::fitComponentsIntoSpace (const int startIndex,
  50140. const int endIndex,
  50141. const int availableSpace,
  50142. int startPos)
  50143. {
  50144. // calculate the total sizes
  50145. int i;
  50146. double totalIdealSize = 0.0;
  50147. int totalMinimums = 0;
  50148. for (i = startIndex; i < endIndex; ++i)
  50149. {
  50150. ItemLayoutProperties* const layout = items.getUnchecked (i);
  50151. layout->currentSize = sizeToRealSize (layout->minSize, totalSize);
  50152. totalMinimums += layout->currentSize;
  50153. totalIdealSize += sizeToRealSize (layout->preferredSize, availableSpace);
  50154. }
  50155. if (totalIdealSize <= 0)
  50156. totalIdealSize = 1.0;
  50157. // now calc the best sizes..
  50158. int extraSpace = availableSpace - totalMinimums;
  50159. while (extraSpace > 0)
  50160. {
  50161. int numWantingMoreSpace = 0;
  50162. int numHavingTakenExtraSpace = 0;
  50163. // first figure out how many comps want a slice of the extra space..
  50164. for (i = startIndex; i < endIndex; ++i)
  50165. {
  50166. ItemLayoutProperties* const layout = items.getUnchecked (i);
  50167. double sizeWanted = sizeToRealSize (layout->preferredSize, availableSpace);
  50168. const int bestSize = jlimit (layout->currentSize,
  50169. jmax (layout->currentSize,
  50170. sizeToRealSize (layout->maxSize, totalSize)),
  50171. roundToInt (sizeWanted * availableSpace / totalIdealSize));
  50172. if (bestSize > layout->currentSize)
  50173. ++numWantingMoreSpace;
  50174. }
  50175. // ..share out the extra space..
  50176. for (i = startIndex; i < endIndex; ++i)
  50177. {
  50178. ItemLayoutProperties* const layout = items.getUnchecked (i);
  50179. double sizeWanted = sizeToRealSize (layout->preferredSize, availableSpace);
  50180. int bestSize = jlimit (layout->currentSize,
  50181. jmax (layout->currentSize, sizeToRealSize (layout->maxSize, totalSize)),
  50182. roundToInt (sizeWanted * availableSpace / totalIdealSize));
  50183. const int extraWanted = bestSize - layout->currentSize;
  50184. if (extraWanted > 0)
  50185. {
  50186. const int extraAllowed = jmin (extraWanted,
  50187. extraSpace / jmax (1, numWantingMoreSpace));
  50188. if (extraAllowed > 0)
  50189. {
  50190. ++numHavingTakenExtraSpace;
  50191. --numWantingMoreSpace;
  50192. layout->currentSize += extraAllowed;
  50193. extraSpace -= extraAllowed;
  50194. }
  50195. }
  50196. }
  50197. if (numHavingTakenExtraSpace <= 0)
  50198. break;
  50199. }
  50200. // ..and calculate the end position
  50201. for (i = startIndex; i < endIndex; ++i)
  50202. {
  50203. ItemLayoutProperties* const layout = items.getUnchecked(i);
  50204. startPos += layout->currentSize;
  50205. }
  50206. return startPos;
  50207. }
  50208. int StretchableLayoutManager::getMinimumSizeOfItems (const int startIndex,
  50209. const int endIndex) const
  50210. {
  50211. int totalMinimums = 0;
  50212. for (int i = startIndex; i < endIndex; ++i)
  50213. totalMinimums += sizeToRealSize (items.getUnchecked (i)->minSize, totalSize);
  50214. return totalMinimums;
  50215. }
  50216. int StretchableLayoutManager::getMaximumSizeOfItems (const int startIndex, const int endIndex) const
  50217. {
  50218. int totalMaximums = 0;
  50219. for (int i = startIndex; i < endIndex; ++i)
  50220. totalMaximums += sizeToRealSize (items.getUnchecked (i)->maxSize, totalSize);
  50221. return totalMaximums;
  50222. }
  50223. void StretchableLayoutManager::updatePrefSizesToMatchCurrentPositions()
  50224. {
  50225. for (int i = 0; i < items.size(); ++i)
  50226. {
  50227. ItemLayoutProperties* const layout = items.getUnchecked (i);
  50228. layout->preferredSize
  50229. = (layout->preferredSize < 0) ? getItemCurrentRelativeSize (i)
  50230. : getItemCurrentAbsoluteSize (i);
  50231. }
  50232. }
  50233. int StretchableLayoutManager::sizeToRealSize (double size, int totalSpace)
  50234. {
  50235. if (size < 0)
  50236. size *= -totalSpace;
  50237. return roundToInt (size);
  50238. }
  50239. END_JUCE_NAMESPACE
  50240. /*** End of inlined file: juce_StretchableLayoutManager.cpp ***/
  50241. /*** Start of inlined file: juce_StretchableLayoutResizerBar.cpp ***/
  50242. BEGIN_JUCE_NAMESPACE
  50243. StretchableLayoutResizerBar::StretchableLayoutResizerBar (StretchableLayoutManager* layout_,
  50244. const int itemIndex_,
  50245. const bool isVertical_)
  50246. : layout (layout_),
  50247. itemIndex (itemIndex_),
  50248. isVertical (isVertical_)
  50249. {
  50250. setRepaintsOnMouseActivity (true);
  50251. setMouseCursor (MouseCursor (isVertical_ ? MouseCursor::LeftRightResizeCursor
  50252. : MouseCursor::UpDownResizeCursor));
  50253. }
  50254. StretchableLayoutResizerBar::~StretchableLayoutResizerBar()
  50255. {
  50256. }
  50257. void StretchableLayoutResizerBar::paint (Graphics& g)
  50258. {
  50259. getLookAndFeel().drawStretchableLayoutResizerBar (g,
  50260. getWidth(), getHeight(),
  50261. isVertical,
  50262. isMouseOver(),
  50263. isMouseButtonDown());
  50264. }
  50265. void StretchableLayoutResizerBar::mouseDown (const MouseEvent&)
  50266. {
  50267. mouseDownPos = layout->getItemCurrentPosition (itemIndex);
  50268. }
  50269. void StretchableLayoutResizerBar::mouseDrag (const MouseEvent& e)
  50270. {
  50271. const int desiredPos = mouseDownPos + (isVertical ? e.getDistanceFromDragStartX()
  50272. : e.getDistanceFromDragStartY());
  50273. layout->setItemPosition (itemIndex, desiredPos);
  50274. hasBeenMoved();
  50275. }
  50276. void StretchableLayoutResizerBar::hasBeenMoved()
  50277. {
  50278. if (getParentComponent() != 0)
  50279. getParentComponent()->resized();
  50280. }
  50281. END_JUCE_NAMESPACE
  50282. /*** End of inlined file: juce_StretchableLayoutResizerBar.cpp ***/
  50283. /*** Start of inlined file: juce_StretchableObjectResizer.cpp ***/
  50284. BEGIN_JUCE_NAMESPACE
  50285. StretchableObjectResizer::StretchableObjectResizer()
  50286. {
  50287. }
  50288. StretchableObjectResizer::~StretchableObjectResizer()
  50289. {
  50290. }
  50291. void StretchableObjectResizer::addItem (const double size,
  50292. const double minSize, const double maxSize,
  50293. const int order)
  50294. {
  50295. // the order must be >= 0 but less than the maximum integer value.
  50296. jassert (order >= 0 && order < std::numeric_limits<int>::max());
  50297. Item* const item = new Item();
  50298. item->size = size;
  50299. item->minSize = minSize;
  50300. item->maxSize = maxSize;
  50301. item->order = order;
  50302. items.add (item);
  50303. }
  50304. double StretchableObjectResizer::getItemSize (const int index) const throw()
  50305. {
  50306. const Item* const it = items [index];
  50307. return it != 0 ? it->size : 0;
  50308. }
  50309. void StretchableObjectResizer::resizeToFit (const double targetSize)
  50310. {
  50311. int order = 0;
  50312. for (;;)
  50313. {
  50314. double currentSize = 0;
  50315. double minSize = 0;
  50316. double maxSize = 0;
  50317. int nextHighestOrder = std::numeric_limits<int>::max();
  50318. for (int i = 0; i < items.size(); ++i)
  50319. {
  50320. const Item* const it = items.getUnchecked(i);
  50321. currentSize += it->size;
  50322. if (it->order <= order)
  50323. {
  50324. minSize += it->minSize;
  50325. maxSize += it->maxSize;
  50326. }
  50327. else
  50328. {
  50329. minSize += it->size;
  50330. maxSize += it->size;
  50331. nextHighestOrder = jmin (nextHighestOrder, it->order);
  50332. }
  50333. }
  50334. const double thisIterationTarget = jlimit (minSize, maxSize, targetSize);
  50335. if (thisIterationTarget >= currentSize)
  50336. {
  50337. const double availableExtraSpace = maxSize - currentSize;
  50338. const double targetAmountOfExtraSpace = thisIterationTarget - currentSize;
  50339. const double scale = targetAmountOfExtraSpace / availableExtraSpace;
  50340. for (int i = 0; i < items.size(); ++i)
  50341. {
  50342. Item* const it = items.getUnchecked(i);
  50343. if (it->order <= order)
  50344. it->size = jmin (it->maxSize, it->size + (it->maxSize - it->size) * scale);
  50345. }
  50346. }
  50347. else
  50348. {
  50349. const double amountOfSlack = currentSize - minSize;
  50350. const double targetAmountOfSlack = thisIterationTarget - minSize;
  50351. const double scale = targetAmountOfSlack / amountOfSlack;
  50352. for (int i = 0; i < items.size(); ++i)
  50353. {
  50354. Item* const it = items.getUnchecked(i);
  50355. if (it->order <= order)
  50356. it->size = jmax (it->minSize, it->minSize + (it->size - it->minSize) * scale);
  50357. }
  50358. }
  50359. if (nextHighestOrder < std::numeric_limits<int>::max())
  50360. order = nextHighestOrder;
  50361. else
  50362. break;
  50363. }
  50364. }
  50365. END_JUCE_NAMESPACE
  50366. /*** End of inlined file: juce_StretchableObjectResizer.cpp ***/
  50367. /*** Start of inlined file: juce_TabbedButtonBar.cpp ***/
  50368. BEGIN_JUCE_NAMESPACE
  50369. TabBarButton::TabBarButton (const String& name,
  50370. TabbedButtonBar* const owner_,
  50371. const int index)
  50372. : Button (name),
  50373. owner (owner_),
  50374. tabIndex (index),
  50375. overlapPixels (0)
  50376. {
  50377. shadow.setShadowProperties (2.2f, 0.7f, 0, 0);
  50378. setComponentEffect (&shadow);
  50379. setWantsKeyboardFocus (false);
  50380. }
  50381. TabBarButton::~TabBarButton()
  50382. {
  50383. }
  50384. void TabBarButton::paintButton (Graphics& g,
  50385. bool isMouseOverButton,
  50386. bool isButtonDown)
  50387. {
  50388. int x, y, w, h;
  50389. getActiveArea (x, y, w, h);
  50390. g.setOrigin (x, y);
  50391. getLookAndFeel()
  50392. .drawTabButton (g, w, h,
  50393. owner->getTabBackgroundColour (tabIndex),
  50394. tabIndex, getButtonText(), *this,
  50395. owner->getOrientation(),
  50396. isMouseOverButton, isButtonDown,
  50397. getToggleState());
  50398. }
  50399. void TabBarButton::clicked (const ModifierKeys& mods)
  50400. {
  50401. if (mods.isPopupMenu())
  50402. owner->popupMenuClickOnTab (tabIndex, getButtonText());
  50403. else
  50404. owner->setCurrentTabIndex (tabIndex);
  50405. }
  50406. bool TabBarButton::hitTest (int mx, int my)
  50407. {
  50408. int x, y, w, h;
  50409. getActiveArea (x, y, w, h);
  50410. if (owner->getOrientation() == TabbedButtonBar::TabsAtLeft
  50411. || owner->getOrientation() == TabbedButtonBar::TabsAtRight)
  50412. {
  50413. if (((unsigned int) mx) < (unsigned int) getWidth()
  50414. && my >= y + overlapPixels
  50415. && my < y + h - overlapPixels)
  50416. return true;
  50417. }
  50418. else
  50419. {
  50420. if (mx >= x + overlapPixels && mx < x + w - overlapPixels
  50421. && ((unsigned int) my) < (unsigned int) getHeight())
  50422. return true;
  50423. }
  50424. Path p;
  50425. getLookAndFeel()
  50426. .createTabButtonShape (p, w, h, tabIndex, getButtonText(), *this,
  50427. owner->getOrientation(),
  50428. false, false, getToggleState());
  50429. return p.contains ((float) (mx - x),
  50430. (float) (my - y));
  50431. }
  50432. int TabBarButton::getBestTabLength (const int depth)
  50433. {
  50434. return jlimit (depth * 2,
  50435. depth * 7,
  50436. getLookAndFeel().getTabButtonBestWidth (tabIndex, getButtonText(), depth, *this));
  50437. }
  50438. void TabBarButton::getActiveArea (int& x, int& y, int& w, int& h)
  50439. {
  50440. x = 0;
  50441. y = 0;
  50442. int r = getWidth();
  50443. int b = getHeight();
  50444. const int spaceAroundImage = getLookAndFeel().getTabButtonSpaceAroundImage();
  50445. if (owner->getOrientation() != TabbedButtonBar::TabsAtLeft)
  50446. r -= spaceAroundImage;
  50447. if (owner->getOrientation() != TabbedButtonBar::TabsAtRight)
  50448. x += spaceAroundImage;
  50449. if (owner->getOrientation() != TabbedButtonBar::TabsAtBottom)
  50450. y += spaceAroundImage;
  50451. if (owner->getOrientation() != TabbedButtonBar::TabsAtTop)
  50452. b -= spaceAroundImage;
  50453. w = r - x;
  50454. h = b - y;
  50455. }
  50456. class TabAreaBehindFrontButtonComponent : public Component
  50457. {
  50458. public:
  50459. TabAreaBehindFrontButtonComponent (TabbedButtonBar* const owner_)
  50460. : owner (owner_)
  50461. {
  50462. setInterceptsMouseClicks (false, false);
  50463. }
  50464. ~TabAreaBehindFrontButtonComponent()
  50465. {
  50466. }
  50467. void paint (Graphics& g)
  50468. {
  50469. getLookAndFeel()
  50470. .drawTabAreaBehindFrontButton (g, getWidth(), getHeight(),
  50471. *owner, owner->getOrientation());
  50472. }
  50473. void enablementChanged()
  50474. {
  50475. repaint();
  50476. }
  50477. private:
  50478. TabbedButtonBar* const owner;
  50479. TabAreaBehindFrontButtonComponent (const TabAreaBehindFrontButtonComponent&);
  50480. TabAreaBehindFrontButtonComponent& operator= (const TabAreaBehindFrontButtonComponent&);
  50481. };
  50482. TabbedButtonBar::TabbedButtonBar (const Orientation orientation_)
  50483. : orientation (orientation_),
  50484. currentTabIndex (-1)
  50485. {
  50486. setInterceptsMouseClicks (false, true);
  50487. addAndMakeVisible (behindFrontTab = new TabAreaBehindFrontButtonComponent (this));
  50488. setFocusContainer (true);
  50489. }
  50490. TabbedButtonBar::~TabbedButtonBar()
  50491. {
  50492. extraTabsButton = 0;
  50493. deleteAllChildren();
  50494. }
  50495. void TabbedButtonBar::setOrientation (const Orientation newOrientation)
  50496. {
  50497. orientation = newOrientation;
  50498. for (int i = getNumChildComponents(); --i >= 0;)
  50499. getChildComponent (i)->resized();
  50500. resized();
  50501. }
  50502. TabBarButton* TabbedButtonBar::createTabButton (const String& name, const int index)
  50503. {
  50504. return new TabBarButton (name, this, index);
  50505. }
  50506. void TabbedButtonBar::clearTabs()
  50507. {
  50508. tabs.clear();
  50509. tabColours.clear();
  50510. currentTabIndex = -1;
  50511. extraTabsButton = 0;
  50512. removeChildComponent (behindFrontTab);
  50513. deleteAllChildren();
  50514. addChildComponent (behindFrontTab);
  50515. setCurrentTabIndex (-1);
  50516. }
  50517. void TabbedButtonBar::addTab (const String& tabName,
  50518. const Colour& tabBackgroundColour,
  50519. int insertIndex)
  50520. {
  50521. jassert (tabName.isNotEmpty()); // you have to give them all a name..
  50522. if (tabName.isNotEmpty())
  50523. {
  50524. if (((unsigned int) insertIndex) > (unsigned int) tabs.size())
  50525. insertIndex = tabs.size();
  50526. for (int i = tabs.size(); --i >= insertIndex;)
  50527. {
  50528. TabBarButton* const tb = getTabButton (i);
  50529. if (tb != 0)
  50530. tb->tabIndex++;
  50531. }
  50532. tabs.insert (insertIndex, tabName);
  50533. tabColours.insert (insertIndex, tabBackgroundColour);
  50534. TabBarButton* const tb = createTabButton (tabName, insertIndex);
  50535. jassert (tb != 0); // your createTabButton() mustn't return zero!
  50536. addAndMakeVisible (tb, insertIndex);
  50537. resized();
  50538. if (currentTabIndex < 0)
  50539. setCurrentTabIndex (0);
  50540. }
  50541. }
  50542. void TabbedButtonBar::setTabName (const int tabIndex,
  50543. const String& newName)
  50544. {
  50545. if (((unsigned int) tabIndex) < (unsigned int) tabs.size()
  50546. && tabs[tabIndex] != newName)
  50547. {
  50548. tabs.set (tabIndex, newName);
  50549. TabBarButton* const tb = getTabButton (tabIndex);
  50550. if (tb != 0)
  50551. tb->setButtonText (newName);
  50552. resized();
  50553. }
  50554. }
  50555. void TabbedButtonBar::removeTab (const int tabIndex)
  50556. {
  50557. if (((unsigned int) tabIndex) < (unsigned int) tabs.size())
  50558. {
  50559. const int oldTabIndex = currentTabIndex;
  50560. if (currentTabIndex == tabIndex)
  50561. currentTabIndex = -1;
  50562. tabs.remove (tabIndex);
  50563. tabColours.remove (tabIndex);
  50564. delete getTabButton (tabIndex);
  50565. for (int i = tabIndex + 1; i <= tabs.size(); ++i)
  50566. {
  50567. TabBarButton* const tb = getTabButton (i);
  50568. if (tb != 0)
  50569. tb->tabIndex--;
  50570. }
  50571. resized();
  50572. setCurrentTabIndex (jlimit (0, jmax (0, tabs.size() - 1), oldTabIndex));
  50573. }
  50574. }
  50575. void TabbedButtonBar::moveTab (const int currentIndex,
  50576. const int newIndex)
  50577. {
  50578. tabs.move (currentIndex, newIndex);
  50579. tabColours.move (currentIndex, newIndex);
  50580. resized();
  50581. }
  50582. int TabbedButtonBar::getNumTabs() const
  50583. {
  50584. return tabs.size();
  50585. }
  50586. const StringArray TabbedButtonBar::getTabNames() const
  50587. {
  50588. return tabs;
  50589. }
  50590. void TabbedButtonBar::setCurrentTabIndex (int newIndex, const bool sendChangeMessage_)
  50591. {
  50592. if (currentTabIndex != newIndex)
  50593. {
  50594. if (((unsigned int) newIndex) >= (unsigned int) tabs.size())
  50595. newIndex = -1;
  50596. currentTabIndex = newIndex;
  50597. for (int i = 0; i < getNumChildComponents(); ++i)
  50598. {
  50599. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  50600. if (tb != 0)
  50601. tb->setToggleState (tb->tabIndex == newIndex, false);
  50602. }
  50603. resized();
  50604. if (sendChangeMessage_)
  50605. sendChangeMessage (this);
  50606. currentTabChanged (newIndex, newIndex >= 0 ? tabs [newIndex] : String::empty);
  50607. }
  50608. }
  50609. TabBarButton* TabbedButtonBar::getTabButton (const int index) const
  50610. {
  50611. for (int i = getNumChildComponents(); --i >= 0;)
  50612. {
  50613. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  50614. if (tb != 0 && tb->tabIndex == index)
  50615. return tb;
  50616. }
  50617. return 0;
  50618. }
  50619. void TabbedButtonBar::lookAndFeelChanged()
  50620. {
  50621. extraTabsButton = 0;
  50622. resized();
  50623. }
  50624. void TabbedButtonBar::resized()
  50625. {
  50626. const double minimumScale = 0.7;
  50627. int depth = getWidth();
  50628. int length = getHeight();
  50629. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  50630. swapVariables (depth, length);
  50631. const int overlap = getLookAndFeel().getTabButtonOverlap (depth)
  50632. + getLookAndFeel().getTabButtonSpaceAroundImage() * 2;
  50633. int i, totalLength = overlap;
  50634. int numVisibleButtons = tabs.size();
  50635. for (i = 0; i < getNumChildComponents(); ++i)
  50636. {
  50637. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  50638. if (tb != 0)
  50639. {
  50640. totalLength += tb->getBestTabLength (depth) - overlap;
  50641. tb->overlapPixels = overlap / 2;
  50642. }
  50643. }
  50644. double scale = 1.0;
  50645. if (totalLength > length)
  50646. scale = jmax (minimumScale, length / (double) totalLength);
  50647. const bool isTooBig = totalLength * scale > length;
  50648. int tabsButtonPos = 0;
  50649. if (isTooBig)
  50650. {
  50651. if (extraTabsButton == 0)
  50652. {
  50653. addAndMakeVisible (extraTabsButton = getLookAndFeel().createTabBarExtrasButton());
  50654. extraTabsButton->addButtonListener (this);
  50655. extraTabsButton->setAlwaysOnTop (true);
  50656. extraTabsButton->setTriggeredOnMouseDown (true);
  50657. }
  50658. const int buttonSize = jmin (proportionOfWidth (0.7f), proportionOfHeight (0.7f));
  50659. extraTabsButton->setSize (buttonSize, buttonSize);
  50660. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  50661. {
  50662. tabsButtonPos = getWidth() - buttonSize / 2 - 1;
  50663. extraTabsButton->setCentrePosition (tabsButtonPos, getHeight() / 2);
  50664. }
  50665. else
  50666. {
  50667. tabsButtonPos = getHeight() - buttonSize / 2 - 1;
  50668. extraTabsButton->setCentrePosition (getWidth() / 2, tabsButtonPos);
  50669. }
  50670. totalLength = 0;
  50671. for (i = 0; i < tabs.size(); ++i)
  50672. {
  50673. TabBarButton* const tb = getTabButton (i);
  50674. if (tb != 0)
  50675. {
  50676. const int newLength = totalLength + tb->getBestTabLength (depth);
  50677. if (i > 0 && newLength * minimumScale > tabsButtonPos)
  50678. {
  50679. totalLength += overlap;
  50680. break;
  50681. }
  50682. numVisibleButtons = i + 1;
  50683. totalLength = newLength - overlap;
  50684. }
  50685. }
  50686. scale = jmax (minimumScale, tabsButtonPos / (double) totalLength);
  50687. }
  50688. else
  50689. {
  50690. extraTabsButton = 0;
  50691. }
  50692. int pos = 0;
  50693. TabBarButton* frontTab = 0;
  50694. for (i = 0; i < tabs.size(); ++i)
  50695. {
  50696. TabBarButton* const tb = getTabButton (i);
  50697. if (tb != 0)
  50698. {
  50699. const int bestLength = roundToInt (scale * tb->getBestTabLength (depth));
  50700. if (i < numVisibleButtons)
  50701. {
  50702. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  50703. tb->setBounds (pos, 0, bestLength, getHeight());
  50704. else
  50705. tb->setBounds (0, pos, getWidth(), bestLength);
  50706. tb->toBack();
  50707. if (tb->tabIndex == currentTabIndex)
  50708. frontTab = tb;
  50709. tb->setVisible (true);
  50710. }
  50711. else
  50712. {
  50713. tb->setVisible (false);
  50714. }
  50715. pos += bestLength - overlap;
  50716. }
  50717. }
  50718. behindFrontTab->setBounds (0, 0, getWidth(), getHeight());
  50719. if (frontTab != 0)
  50720. {
  50721. frontTab->toFront (false);
  50722. behindFrontTab->toBehind (frontTab);
  50723. }
  50724. }
  50725. const Colour TabbedButtonBar::getTabBackgroundColour (const int tabIndex)
  50726. {
  50727. return tabColours [tabIndex];
  50728. }
  50729. void TabbedButtonBar::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  50730. {
  50731. if (((unsigned int) tabIndex) < (unsigned int) tabColours.size()
  50732. && tabColours [tabIndex] != newColour)
  50733. {
  50734. tabColours.set (tabIndex, newColour);
  50735. repaint();
  50736. }
  50737. }
  50738. void TabbedButtonBar::buttonClicked (Button* button)
  50739. {
  50740. if (button == extraTabsButton)
  50741. {
  50742. PopupMenu m;
  50743. for (int i = 0; i < tabs.size(); ++i)
  50744. {
  50745. TabBarButton* const tb = getTabButton (i);
  50746. if (tb != 0 && ! tb->isVisible())
  50747. m.addItem (tb->tabIndex + 1, tabs[i], true, i == currentTabIndex);
  50748. }
  50749. const int res = m.showAt (extraTabsButton);
  50750. if (res != 0)
  50751. setCurrentTabIndex (res - 1);
  50752. }
  50753. }
  50754. void TabbedButtonBar::currentTabChanged (const int, const String&)
  50755. {
  50756. }
  50757. void TabbedButtonBar::popupMenuClickOnTab (const int, const String&)
  50758. {
  50759. }
  50760. END_JUCE_NAMESPACE
  50761. /*** End of inlined file: juce_TabbedButtonBar.cpp ***/
  50762. /*** Start of inlined file: juce_TabbedComponent.cpp ***/
  50763. BEGIN_JUCE_NAMESPACE
  50764. class TabCompButtonBar : public TabbedButtonBar
  50765. {
  50766. public:
  50767. TabCompButtonBar (TabbedComponent* const owner_,
  50768. const TabbedButtonBar::Orientation orientation_)
  50769. : TabbedButtonBar (orientation_),
  50770. owner (owner_)
  50771. {
  50772. }
  50773. ~TabCompButtonBar()
  50774. {
  50775. }
  50776. void currentTabChanged (int newCurrentTabIndex, const String& newTabName)
  50777. {
  50778. owner->changeCallback (newCurrentTabIndex, newTabName);
  50779. }
  50780. void popupMenuClickOnTab (int tabIndex, const String& tabName)
  50781. {
  50782. owner->popupMenuClickOnTab (tabIndex, tabName);
  50783. }
  50784. const Colour getTabBackgroundColour (const int tabIndex)
  50785. {
  50786. return owner->tabs->getTabBackgroundColour (tabIndex);
  50787. }
  50788. TabBarButton* createTabButton (const String& tabName, int tabIndex)
  50789. {
  50790. return owner->createTabButton (tabName, tabIndex);
  50791. }
  50792. juce_UseDebuggingNewOperator
  50793. private:
  50794. TabbedComponent* const owner;
  50795. TabCompButtonBar (const TabCompButtonBar&);
  50796. TabCompButtonBar& operator= (const TabCompButtonBar&);
  50797. };
  50798. TabbedComponent::TabbedComponent (const TabbedButtonBar::Orientation orientation)
  50799. : panelComponent (0),
  50800. tabDepth (30),
  50801. outlineThickness (1),
  50802. edgeIndent (0)
  50803. {
  50804. addAndMakeVisible (tabs = new TabCompButtonBar (this, orientation));
  50805. }
  50806. TabbedComponent::~TabbedComponent()
  50807. {
  50808. clearTabs();
  50809. delete tabs;
  50810. }
  50811. void TabbedComponent::setOrientation (const TabbedButtonBar::Orientation orientation)
  50812. {
  50813. tabs->setOrientation (orientation);
  50814. resized();
  50815. }
  50816. TabbedButtonBar::Orientation TabbedComponent::getOrientation() const throw()
  50817. {
  50818. return tabs->getOrientation();
  50819. }
  50820. void TabbedComponent::setTabBarDepth (const int newDepth)
  50821. {
  50822. if (tabDepth != newDepth)
  50823. {
  50824. tabDepth = newDepth;
  50825. resized();
  50826. }
  50827. }
  50828. TabBarButton* TabbedComponent::createTabButton (const String& tabName, const int tabIndex)
  50829. {
  50830. return new TabBarButton (tabName, tabs, tabIndex);
  50831. }
  50832. const Identifier TabbedComponent::deleteComponentId ("deleteByTabComp_");
  50833. void TabbedComponent::clearTabs()
  50834. {
  50835. if (panelComponent != 0)
  50836. {
  50837. panelComponent->setVisible (false);
  50838. removeChildComponent (panelComponent);
  50839. panelComponent = 0;
  50840. }
  50841. tabs->clearTabs();
  50842. for (int i = contentComponents.size(); --i >= 0;)
  50843. {
  50844. Component* const c = contentComponents.getUnchecked(i);
  50845. // be careful not to delete these components until they've been removed from the tab component
  50846. jassert (c == 0 || c->isValidComponent());
  50847. if (c != 0 && (bool) c->getProperties() [deleteComponentId])
  50848. delete c;
  50849. }
  50850. contentComponents.clear();
  50851. }
  50852. void TabbedComponent::addTab (const String& tabName,
  50853. const Colour& tabBackgroundColour,
  50854. Component* const contentComponent,
  50855. const bool deleteComponentWhenNotNeeded,
  50856. const int insertIndex)
  50857. {
  50858. contentComponents.insert (insertIndex, contentComponent);
  50859. if (contentComponent != 0)
  50860. contentComponent->getProperties().set (deleteComponentId, deleteComponentWhenNotNeeded);
  50861. tabs->addTab (tabName, tabBackgroundColour, insertIndex);
  50862. }
  50863. void TabbedComponent::setTabName (const int tabIndex, const String& newName)
  50864. {
  50865. tabs->setTabName (tabIndex, newName);
  50866. }
  50867. void TabbedComponent::removeTab (const int tabIndex)
  50868. {
  50869. Component* const c = contentComponents [tabIndex];
  50870. if (c != 0 && (bool) c->getProperties() [deleteComponentId])
  50871. {
  50872. if (c == panelComponent)
  50873. panelComponent = 0;
  50874. delete c;
  50875. }
  50876. contentComponents.remove (tabIndex);
  50877. tabs->removeTab (tabIndex);
  50878. }
  50879. int TabbedComponent::getNumTabs() const
  50880. {
  50881. return tabs->getNumTabs();
  50882. }
  50883. const StringArray TabbedComponent::getTabNames() const
  50884. {
  50885. return tabs->getTabNames();
  50886. }
  50887. Component* TabbedComponent::getTabContentComponent (const int tabIndex) const throw()
  50888. {
  50889. return contentComponents [tabIndex];
  50890. }
  50891. const Colour TabbedComponent::getTabBackgroundColour (const int tabIndex) const throw()
  50892. {
  50893. return tabs->getTabBackgroundColour (tabIndex);
  50894. }
  50895. void TabbedComponent::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  50896. {
  50897. tabs->setTabBackgroundColour (tabIndex, newColour);
  50898. if (getCurrentTabIndex() == tabIndex)
  50899. repaint();
  50900. }
  50901. void TabbedComponent::setCurrentTabIndex (const int newTabIndex, const bool sendChangeMessage)
  50902. {
  50903. tabs->setCurrentTabIndex (newTabIndex, sendChangeMessage);
  50904. }
  50905. int TabbedComponent::getCurrentTabIndex() const
  50906. {
  50907. return tabs->getCurrentTabIndex();
  50908. }
  50909. const String& TabbedComponent::getCurrentTabName() const
  50910. {
  50911. return tabs->getCurrentTabName();
  50912. }
  50913. void TabbedComponent::setOutline (int thickness)
  50914. {
  50915. outlineThickness = thickness;
  50916. repaint();
  50917. }
  50918. void TabbedComponent::setIndent (const int indentThickness)
  50919. {
  50920. edgeIndent = indentThickness;
  50921. }
  50922. void TabbedComponent::paint (Graphics& g)
  50923. {
  50924. g.fillAll (findColour (backgroundColourId));
  50925. const TabbedButtonBar::Orientation o = getOrientation();
  50926. int x = 0;
  50927. int y = 0;
  50928. int r = getWidth();
  50929. int b = getHeight();
  50930. if (o == TabbedButtonBar::TabsAtTop)
  50931. y += tabDepth;
  50932. else if (o == TabbedButtonBar::TabsAtBottom)
  50933. b -= tabDepth;
  50934. else if (o == TabbedButtonBar::TabsAtLeft)
  50935. x += tabDepth;
  50936. else if (o == TabbedButtonBar::TabsAtRight)
  50937. r -= tabDepth;
  50938. g.reduceClipRegion (x, y, r - x, b - y);
  50939. g.fillAll (tabs->getTabBackgroundColour (getCurrentTabIndex()));
  50940. if (outlineThickness > 0)
  50941. {
  50942. if (o == TabbedButtonBar::TabsAtTop)
  50943. --y;
  50944. else if (o == TabbedButtonBar::TabsAtBottom)
  50945. ++b;
  50946. else if (o == TabbedButtonBar::TabsAtLeft)
  50947. --x;
  50948. else if (o == TabbedButtonBar::TabsAtRight)
  50949. ++r;
  50950. g.setColour (findColour (outlineColourId));
  50951. g.drawRect (x, y, r - x, b - y, outlineThickness);
  50952. }
  50953. }
  50954. void TabbedComponent::resized()
  50955. {
  50956. const TabbedButtonBar::Orientation o = getOrientation();
  50957. const int indent = edgeIndent + outlineThickness;
  50958. BorderSize indents (indent);
  50959. if (o == TabbedButtonBar::TabsAtTop)
  50960. {
  50961. tabs->setBounds (0, 0, getWidth(), tabDepth);
  50962. indents.setTop (tabDepth + edgeIndent);
  50963. }
  50964. else if (o == TabbedButtonBar::TabsAtBottom)
  50965. {
  50966. tabs->setBounds (0, getHeight() - tabDepth, getWidth(), tabDepth);
  50967. indents.setBottom (tabDepth + edgeIndent);
  50968. }
  50969. else if (o == TabbedButtonBar::TabsAtLeft)
  50970. {
  50971. tabs->setBounds (0, 0, tabDepth, getHeight());
  50972. indents.setLeft (tabDepth + edgeIndent);
  50973. }
  50974. else if (o == TabbedButtonBar::TabsAtRight)
  50975. {
  50976. tabs->setBounds (getWidth() - tabDepth, 0, tabDepth, getHeight());
  50977. indents.setRight (tabDepth + edgeIndent);
  50978. }
  50979. const Rectangle<int> bounds (indents.subtractedFrom (getLocalBounds()));
  50980. for (int i = contentComponents.size(); --i >= 0;)
  50981. if (contentComponents.getUnchecked (i) != 0)
  50982. contentComponents.getUnchecked (i)->setBounds (bounds);
  50983. }
  50984. void TabbedComponent::lookAndFeelChanged()
  50985. {
  50986. for (int i = contentComponents.size(); --i >= 0;)
  50987. if (contentComponents.getUnchecked (i) != 0)
  50988. contentComponents.getUnchecked (i)->lookAndFeelChanged();
  50989. }
  50990. void TabbedComponent::changeCallback (const int newCurrentTabIndex,
  50991. const String& newTabName)
  50992. {
  50993. if (panelComponent != 0)
  50994. {
  50995. panelComponent->setVisible (false);
  50996. removeChildComponent (panelComponent);
  50997. panelComponent = 0;
  50998. }
  50999. if (getCurrentTabIndex() >= 0)
  51000. {
  51001. panelComponent = contentComponents [getCurrentTabIndex()];
  51002. if (panelComponent != 0)
  51003. {
  51004. // do these ops as two stages instead of addAndMakeVisible() so that the
  51005. // component has always got a parent when it gets the visibilityChanged() callback
  51006. addChildComponent (panelComponent);
  51007. panelComponent->setVisible (true);
  51008. panelComponent->toFront (true);
  51009. }
  51010. repaint();
  51011. }
  51012. resized();
  51013. currentTabChanged (newCurrentTabIndex, newTabName);
  51014. }
  51015. void TabbedComponent::currentTabChanged (const int, const String&)
  51016. {
  51017. }
  51018. void TabbedComponent::popupMenuClickOnTab (const int, const String&)
  51019. {
  51020. }
  51021. END_JUCE_NAMESPACE
  51022. /*** End of inlined file: juce_TabbedComponent.cpp ***/
  51023. /*** Start of inlined file: juce_Viewport.cpp ***/
  51024. BEGIN_JUCE_NAMESPACE
  51025. Viewport::Viewport (const String& componentName)
  51026. : Component (componentName),
  51027. scrollBarThickness (0),
  51028. singleStepX (16),
  51029. singleStepY (16),
  51030. showHScrollbar (true),
  51031. showVScrollbar (true),
  51032. verticalScrollBar (true),
  51033. horizontalScrollBar (false)
  51034. {
  51035. // content holder is used to clip the contents so they don't overlap the scrollbars
  51036. addAndMakeVisible (&contentHolder);
  51037. contentHolder.setInterceptsMouseClicks (false, true);
  51038. addChildComponent (&verticalScrollBar);
  51039. addChildComponent (&horizontalScrollBar);
  51040. verticalScrollBar.addListener (this);
  51041. horizontalScrollBar.addListener (this);
  51042. setInterceptsMouseClicks (false, true);
  51043. setWantsKeyboardFocus (true);
  51044. }
  51045. Viewport::~Viewport()
  51046. {
  51047. contentHolder.deleteAllChildren();
  51048. }
  51049. void Viewport::visibleAreaChanged (int, int, int, int)
  51050. {
  51051. }
  51052. void Viewport::setViewedComponent (Component* const newViewedComponent)
  51053. {
  51054. if (contentComp.getComponent() != newViewedComponent)
  51055. {
  51056. {
  51057. ScopedPointer<Component> oldCompDeleter (contentComp);
  51058. contentComp = 0;
  51059. }
  51060. contentComp = newViewedComponent;
  51061. if (contentComp != 0)
  51062. {
  51063. contentComp->setTopLeftPosition (0, 0);
  51064. contentHolder.addAndMakeVisible (contentComp);
  51065. contentComp->addComponentListener (this);
  51066. }
  51067. updateVisibleArea();
  51068. }
  51069. }
  51070. int Viewport::getMaximumVisibleWidth() const
  51071. {
  51072. return contentHolder.getWidth();
  51073. }
  51074. int Viewport::getMaximumVisibleHeight() const
  51075. {
  51076. return contentHolder.getHeight();
  51077. }
  51078. void Viewport::setViewPosition (const int xPixelsOffset, const int yPixelsOffset)
  51079. {
  51080. if (contentComp != 0)
  51081. contentComp->setTopLeftPosition (-xPixelsOffset, -yPixelsOffset);
  51082. }
  51083. void Viewport::setViewPositionProportionately (const double x, const double y)
  51084. {
  51085. if (contentComp != 0)
  51086. setViewPosition (jmax (0, roundToInt (x * (contentComp->getWidth() - getWidth()))),
  51087. jmax (0, roundToInt (y * (contentComp->getHeight() - getHeight()))));
  51088. }
  51089. bool Viewport::autoScroll (const int mouseX, const int mouseY, const int activeBorderThickness, const int maximumSpeed)
  51090. {
  51091. if (contentComp != 0)
  51092. {
  51093. int dx = 0, dy = 0;
  51094. if (horizontalScrollBar.isVisible() || contentComp->getX() < 0 || contentComp->getRight() > getWidth())
  51095. {
  51096. if (mouseX < activeBorderThickness)
  51097. dx = activeBorderThickness - mouseX;
  51098. else if (mouseX >= contentHolder.getWidth() - activeBorderThickness)
  51099. dx = (contentHolder.getWidth() - activeBorderThickness) - mouseX;
  51100. if (dx < 0)
  51101. dx = jmax (dx, -maximumSpeed, contentHolder.getWidth() - contentComp->getRight());
  51102. else
  51103. dx = jmin (dx, maximumSpeed, -contentComp->getX());
  51104. }
  51105. if (verticalScrollBar.isVisible() || contentComp->getY() < 0 || contentComp->getBottom() > getHeight())
  51106. {
  51107. if (mouseY < activeBorderThickness)
  51108. dy = activeBorderThickness - mouseY;
  51109. else if (mouseY >= contentHolder.getHeight() - activeBorderThickness)
  51110. dy = (contentHolder.getHeight() - activeBorderThickness) - mouseY;
  51111. if (dy < 0)
  51112. dy = jmax (dy, -maximumSpeed, contentHolder.getHeight() - contentComp->getBottom());
  51113. else
  51114. dy = jmin (dy, maximumSpeed, -contentComp->getY());
  51115. }
  51116. if (dx != 0 || dy != 0)
  51117. {
  51118. contentComp->setTopLeftPosition (contentComp->getX() + dx,
  51119. contentComp->getY() + dy);
  51120. return true;
  51121. }
  51122. }
  51123. return false;
  51124. }
  51125. void Viewport::componentMovedOrResized (Component&, bool, bool)
  51126. {
  51127. updateVisibleArea();
  51128. }
  51129. void Viewport::resized()
  51130. {
  51131. updateVisibleArea();
  51132. }
  51133. void Viewport::updateVisibleArea()
  51134. {
  51135. const int scrollbarWidth = getScrollBarThickness();
  51136. const bool canShowAnyBars = getWidth() > scrollbarWidth && getHeight() > scrollbarWidth;
  51137. const bool canShowHBar = showHScrollbar && canShowAnyBars;
  51138. const bool canShowVBar = showVScrollbar && canShowAnyBars;
  51139. bool hBarVisible = canShowHBar && ! horizontalScrollBar.autoHides();
  51140. bool vBarVisible = canShowVBar && ! verticalScrollBar.autoHides();
  51141. Rectangle<int> contentArea (getLocalBounds());
  51142. if (contentComp != 0 && ! contentArea.contains (contentComp->getBounds()))
  51143. {
  51144. hBarVisible = canShowHBar && (hBarVisible || contentComp->getX() < 0 || contentComp->getRight() > contentArea.getWidth());
  51145. vBarVisible = canShowVBar && (vBarVisible || contentComp->getY() < 0 || contentComp->getBottom() > contentArea.getHeight());
  51146. if (vBarVisible)
  51147. contentArea.setWidth (getWidth() - scrollbarWidth);
  51148. if (hBarVisible)
  51149. contentArea.setHeight (getHeight() - scrollbarWidth);
  51150. if (! contentArea.contains (contentComp->getBounds()))
  51151. {
  51152. hBarVisible = canShowHBar && (hBarVisible || contentComp->getRight() > contentArea.getWidth());
  51153. vBarVisible = canShowVBar && (vBarVisible || contentComp->getBottom() > contentArea.getHeight());
  51154. }
  51155. }
  51156. if (vBarVisible)
  51157. contentArea.setWidth (getWidth() - scrollbarWidth);
  51158. if (hBarVisible)
  51159. contentArea.setHeight (getHeight() - scrollbarWidth);
  51160. contentHolder.setBounds (contentArea);
  51161. Rectangle<int> contentBounds;
  51162. if (contentComp != 0)
  51163. contentBounds = contentComp->getBounds();
  51164. const Point<int> visibleOrigin (-contentBounds.getPosition());
  51165. if (hBarVisible)
  51166. {
  51167. horizontalScrollBar.setBounds (0, contentArea.getHeight(), contentArea.getWidth(), scrollbarWidth);
  51168. horizontalScrollBar.setRangeLimits (0.0, contentBounds.getWidth());
  51169. horizontalScrollBar.setCurrentRange (visibleOrigin.getX(), contentArea.getWidth());
  51170. horizontalScrollBar.setSingleStepSize (singleStepX);
  51171. }
  51172. if (vBarVisible)
  51173. {
  51174. verticalScrollBar.setBounds (contentArea.getWidth(), 0, scrollbarWidth, contentArea.getHeight());
  51175. verticalScrollBar.setRangeLimits (0.0, contentBounds.getHeight());
  51176. verticalScrollBar.setCurrentRange (visibleOrigin.getY(), contentArea.getHeight());
  51177. verticalScrollBar.setSingleStepSize (singleStepY);
  51178. }
  51179. // Force the visibility *after* setting the ranges to avoid flicker caused by edge conditions in the numbers.
  51180. horizontalScrollBar.setVisible (hBarVisible);
  51181. verticalScrollBar.setVisible (vBarVisible);
  51182. const Rectangle<int> visibleArea (visibleOrigin.getX(), visibleOrigin.getY(),
  51183. jmin (contentBounds.getWidth() - visibleOrigin.getX(), contentArea.getWidth()),
  51184. jmin (contentBounds.getHeight() - visibleOrigin.getY(), contentArea.getHeight()));
  51185. if (lastVisibleArea != visibleArea)
  51186. {
  51187. lastVisibleArea = visibleArea;
  51188. visibleAreaChanged (visibleArea.getX(), visibleArea.getY(), visibleArea.getWidth(), visibleArea.getHeight());
  51189. }
  51190. horizontalScrollBar.handleUpdateNowIfNeeded();
  51191. verticalScrollBar.handleUpdateNowIfNeeded();
  51192. }
  51193. void Viewport::setSingleStepSizes (const int stepX, const int stepY)
  51194. {
  51195. if (singleStepX != stepX || singleStepY != stepY)
  51196. {
  51197. singleStepX = stepX;
  51198. singleStepY = stepY;
  51199. updateVisibleArea();
  51200. }
  51201. }
  51202. void Viewport::setScrollBarsShown (const bool showVerticalScrollbarIfNeeded,
  51203. const bool showHorizontalScrollbarIfNeeded)
  51204. {
  51205. if (showVScrollbar != showVerticalScrollbarIfNeeded
  51206. || showHScrollbar != showHorizontalScrollbarIfNeeded)
  51207. {
  51208. showVScrollbar = showVerticalScrollbarIfNeeded;
  51209. showHScrollbar = showHorizontalScrollbarIfNeeded;
  51210. updateVisibleArea();
  51211. }
  51212. }
  51213. void Viewport::setScrollBarThickness (const int thickness)
  51214. {
  51215. if (scrollBarThickness != thickness)
  51216. {
  51217. scrollBarThickness = thickness;
  51218. updateVisibleArea();
  51219. }
  51220. }
  51221. int Viewport::getScrollBarThickness() const
  51222. {
  51223. return scrollBarThickness > 0 ? scrollBarThickness
  51224. : getLookAndFeel().getDefaultScrollbarWidth();
  51225. }
  51226. void Viewport::setScrollBarButtonVisibility (const bool buttonsVisible)
  51227. {
  51228. verticalScrollBar.setButtonVisibility (buttonsVisible);
  51229. horizontalScrollBar.setButtonVisibility (buttonsVisible);
  51230. }
  51231. void Viewport::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart)
  51232. {
  51233. const int newRangeStartInt = roundToInt (newRangeStart);
  51234. if (scrollBarThatHasMoved == &horizontalScrollBar)
  51235. {
  51236. setViewPosition (newRangeStartInt, getViewPositionY());
  51237. }
  51238. else if (scrollBarThatHasMoved == &verticalScrollBar)
  51239. {
  51240. setViewPosition (getViewPositionX(), newRangeStartInt);
  51241. }
  51242. }
  51243. void Viewport::mouseWheelMove (const MouseEvent& e, const float wheelIncrementX, const float wheelIncrementY)
  51244. {
  51245. if (! useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  51246. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  51247. }
  51248. bool Viewport::useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  51249. {
  51250. if (! (e.mods.isAltDown() || e.mods.isCtrlDown()))
  51251. {
  51252. const bool hasVertBar = verticalScrollBar.isVisible();
  51253. const bool hasHorzBar = horizontalScrollBar.isVisible();
  51254. if (hasHorzBar && (wheelIncrementX != 0 || e.mods.isShiftDown() || ! hasVertBar))
  51255. {
  51256. if (wheelIncrementX == 0 && ! hasVertBar)
  51257. wheelIncrementX = wheelIncrementY;
  51258. horizontalScrollBar.mouseWheelMove (e.getEventRelativeTo (&horizontalScrollBar),
  51259. wheelIncrementX, wheelIncrementY);
  51260. return true;
  51261. }
  51262. else if (hasVertBar && wheelIncrementY != 0)
  51263. {
  51264. verticalScrollBar.mouseWheelMove (e.getEventRelativeTo (&verticalScrollBar),
  51265. wheelIncrementX, wheelIncrementY);
  51266. return true;
  51267. }
  51268. }
  51269. return false;
  51270. }
  51271. bool Viewport::keyPressed (const KeyPress& key)
  51272. {
  51273. const bool isUpDownKey = key.isKeyCode (KeyPress::upKey)
  51274. || key.isKeyCode (KeyPress::downKey)
  51275. || key.isKeyCode (KeyPress::pageUpKey)
  51276. || key.isKeyCode (KeyPress::pageDownKey)
  51277. || key.isKeyCode (KeyPress::homeKey)
  51278. || key.isKeyCode (KeyPress::endKey);
  51279. if (verticalScrollBar.isVisible() && isUpDownKey)
  51280. return verticalScrollBar.keyPressed (key);
  51281. const bool isLeftRightKey = key.isKeyCode (KeyPress::leftKey)
  51282. || key.isKeyCode (KeyPress::rightKey);
  51283. if (horizontalScrollBar.isVisible() && (isUpDownKey || isLeftRightKey))
  51284. return horizontalScrollBar.keyPressed (key);
  51285. return false;
  51286. }
  51287. END_JUCE_NAMESPACE
  51288. /*** End of inlined file: juce_Viewport.cpp ***/
  51289. /*** Start of inlined file: juce_LookAndFeel.cpp ***/
  51290. BEGIN_JUCE_NAMESPACE
  51291. static const Colour createBaseColour (const Colour& buttonColour,
  51292. const bool hasKeyboardFocus,
  51293. const bool isMouseOverButton,
  51294. const bool isButtonDown) throw()
  51295. {
  51296. const float sat = hasKeyboardFocus ? 1.3f : 0.9f;
  51297. const Colour baseColour (buttonColour.withMultipliedSaturation (sat));
  51298. if (isButtonDown)
  51299. return baseColour.contrasting (0.2f);
  51300. else if (isMouseOverButton)
  51301. return baseColour.contrasting (0.1f);
  51302. return baseColour;
  51303. }
  51304. LookAndFeel::LookAndFeel()
  51305. {
  51306. /* if this fails it means you're trying to create a LookAndFeel object before
  51307. the static Colours have been initialised. That ain't gonna work. It probably
  51308. means that you're using a static LookAndFeel object and that your compiler has
  51309. decided to intialise it before the Colours class.
  51310. */
  51311. jassert (Colours::white == Colour (0xffffffff));
  51312. // set up the standard set of colours..
  51313. const int textButtonColour = 0xffbbbbff;
  51314. const int textHighlightColour = 0x401111ee;
  51315. const int standardOutlineColour = 0xb2808080;
  51316. static const int standardColours[] =
  51317. {
  51318. TextButton::buttonColourId, textButtonColour,
  51319. TextButton::buttonOnColourId, 0xff4444ff,
  51320. TextButton::textColourOnId, 0xff000000,
  51321. TextButton::textColourOffId, 0xff000000,
  51322. ComboBox::buttonColourId, 0xffbbbbff,
  51323. ComboBox::outlineColourId, standardOutlineColour,
  51324. ToggleButton::textColourId, 0xff000000,
  51325. TextEditor::backgroundColourId, 0xffffffff,
  51326. TextEditor::textColourId, 0xff000000,
  51327. TextEditor::highlightColourId, textHighlightColour,
  51328. TextEditor::highlightedTextColourId, 0xff000000,
  51329. TextEditor::caretColourId, 0xff000000,
  51330. TextEditor::outlineColourId, 0x00000000,
  51331. TextEditor::focusedOutlineColourId, textButtonColour,
  51332. TextEditor::shadowColourId, 0x38000000,
  51333. Label::backgroundColourId, 0x00000000,
  51334. Label::textColourId, 0xff000000,
  51335. Label::outlineColourId, 0x00000000,
  51336. ScrollBar::backgroundColourId, 0x00000000,
  51337. ScrollBar::thumbColourId, 0xffffffff,
  51338. ScrollBar::trackColourId, 0xffffffff,
  51339. TreeView::linesColourId, 0x4c000000,
  51340. TreeView::backgroundColourId, 0x00000000,
  51341. TreeView::dragAndDropIndicatorColourId, 0x80ff0000,
  51342. PopupMenu::backgroundColourId, 0xffffffff,
  51343. PopupMenu::textColourId, 0xff000000,
  51344. PopupMenu::headerTextColourId, 0xff000000,
  51345. PopupMenu::highlightedTextColourId, 0xffffffff,
  51346. PopupMenu::highlightedBackgroundColourId, 0x991111aa,
  51347. ComboBox::textColourId, 0xff000000,
  51348. ComboBox::backgroundColourId, 0xffffffff,
  51349. ComboBox::arrowColourId, 0x99000000,
  51350. ListBox::backgroundColourId, 0xffffffff,
  51351. ListBox::outlineColourId, standardOutlineColour,
  51352. ListBox::textColourId, 0xff000000,
  51353. Slider::backgroundColourId, 0x00000000,
  51354. Slider::thumbColourId, textButtonColour,
  51355. Slider::trackColourId, 0x7fffffff,
  51356. Slider::rotarySliderFillColourId, 0x7f0000ff,
  51357. Slider::rotarySliderOutlineColourId, 0x66000000,
  51358. Slider::textBoxTextColourId, 0xff000000,
  51359. Slider::textBoxBackgroundColourId, 0xffffffff,
  51360. Slider::textBoxHighlightColourId, textHighlightColour,
  51361. Slider::textBoxOutlineColourId, standardOutlineColour,
  51362. ResizableWindow::backgroundColourId, 0xff777777,
  51363. //DocumentWindow::textColourId, 0xff000000, // (this is deliberately not set)
  51364. AlertWindow::backgroundColourId, 0xffededed,
  51365. AlertWindow::textColourId, 0xff000000,
  51366. AlertWindow::outlineColourId, 0xff666666,
  51367. ProgressBar::backgroundColourId, 0xffeeeeee,
  51368. ProgressBar::foregroundColourId, 0xffaaaaee,
  51369. TooltipWindow::backgroundColourId, 0xffeeeebb,
  51370. TooltipWindow::textColourId, 0xff000000,
  51371. TooltipWindow::outlineColourId, 0x4c000000,
  51372. TabbedComponent::backgroundColourId, 0x00000000,
  51373. TabbedComponent::outlineColourId, 0xff777777,
  51374. TabbedButtonBar::tabOutlineColourId, 0x80000000,
  51375. TabbedButtonBar::frontOutlineColourId, 0x90000000,
  51376. Toolbar::backgroundColourId, 0xfff6f8f9,
  51377. Toolbar::separatorColourId, 0x4c000000,
  51378. Toolbar::buttonMouseOverBackgroundColourId, 0x4c0000ff,
  51379. Toolbar::buttonMouseDownBackgroundColourId, 0x800000ff,
  51380. Toolbar::labelTextColourId, 0xff000000,
  51381. Toolbar::editingModeOutlineColourId, 0xffff0000,
  51382. HyperlinkButton::textColourId, 0xcc1111ee,
  51383. GroupComponent::outlineColourId, 0x66000000,
  51384. GroupComponent::textColourId, 0xff000000,
  51385. DirectoryContentsDisplayComponent::highlightColourId, textHighlightColour,
  51386. DirectoryContentsDisplayComponent::textColourId, 0xff000000,
  51387. 0x1000440, /*LassoComponent::lassoFillColourId*/ 0x66dddddd,
  51388. 0x1000441, /*LassoComponent::lassoOutlineColourId*/ 0x99111111,
  51389. MidiKeyboardComponent::whiteNoteColourId, 0xffffffff,
  51390. MidiKeyboardComponent::blackNoteColourId, 0xff000000,
  51391. MidiKeyboardComponent::keySeparatorLineColourId, 0x66000000,
  51392. MidiKeyboardComponent::mouseOverKeyOverlayColourId, 0x80ffff00,
  51393. MidiKeyboardComponent::keyDownOverlayColourId, 0xffb6b600,
  51394. MidiKeyboardComponent::textLabelColourId, 0xff000000,
  51395. MidiKeyboardComponent::upDownButtonBackgroundColourId, 0xffd3d3d3,
  51396. MidiKeyboardComponent::upDownButtonArrowColourId, 0xff000000,
  51397. CodeEditorComponent::backgroundColourId, 0xffffffff,
  51398. CodeEditorComponent::caretColourId, 0xff000000,
  51399. CodeEditorComponent::highlightColourId, textHighlightColour,
  51400. CodeEditorComponent::defaultTextColourId, 0xff000000,
  51401. ColourSelector::backgroundColourId, 0xffe5e5e5,
  51402. ColourSelector::labelTextColourId, 0xff000000,
  51403. KeyMappingEditorComponent::backgroundColourId, 0x00000000,
  51404. KeyMappingEditorComponent::textColourId, 0xff000000,
  51405. FileSearchPathListComponent::backgroundColourId, 0xffffffff,
  51406. FileChooserDialogBox::titleTextColourId, 0xff000000,
  51407. };
  51408. for (int i = 0; i < numElementsInArray (standardColours); i += 2)
  51409. setColour (standardColours [i], Colour (standardColours [i + 1]));
  51410. static String defaultSansName, defaultSerifName, defaultFixedName;
  51411. if (defaultSansName.isEmpty())
  51412. Font::getPlatformDefaultFontNames (defaultSansName, defaultSerifName, defaultFixedName);
  51413. defaultSans = defaultSansName;
  51414. defaultSerif = defaultSerifName;
  51415. defaultFixed = defaultFixedName;
  51416. }
  51417. LookAndFeel::~LookAndFeel()
  51418. {
  51419. }
  51420. const Colour LookAndFeel::findColour (const int colourId) const throw()
  51421. {
  51422. const int index = colourIds.indexOf (colourId);
  51423. if (index >= 0)
  51424. return colours [index];
  51425. jassertfalse;
  51426. return Colours::black;
  51427. }
  51428. void LookAndFeel::setColour (const int colourId, const Colour& colour) throw()
  51429. {
  51430. const int index = colourIds.indexOf (colourId);
  51431. if (index >= 0)
  51432. {
  51433. colours.set (index, colour);
  51434. }
  51435. else
  51436. {
  51437. colourIds.add (colourId);
  51438. colours.add (colour);
  51439. }
  51440. }
  51441. bool LookAndFeel::isColourSpecified (const int colourId) const throw()
  51442. {
  51443. return colourIds.contains (colourId);
  51444. }
  51445. static LookAndFeel* defaultLF = 0;
  51446. static LookAndFeel* currentDefaultLF = 0;
  51447. LookAndFeel& LookAndFeel::getDefaultLookAndFeel() throw()
  51448. {
  51449. // if this happens, your app hasn't initialised itself properly.. if you're
  51450. // trying to hack your own main() function, have a look at
  51451. // JUCEApplication::initialiseForGUI()
  51452. jassert (currentDefaultLF != 0);
  51453. return *currentDefaultLF;
  51454. }
  51455. void LookAndFeel::setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) throw()
  51456. {
  51457. if (newDefaultLookAndFeel == 0)
  51458. {
  51459. if (defaultLF == 0)
  51460. defaultLF = new LookAndFeel();
  51461. newDefaultLookAndFeel = defaultLF;
  51462. }
  51463. currentDefaultLF = newDefaultLookAndFeel;
  51464. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  51465. {
  51466. Component* const c = Desktop::getInstance().getComponent (i);
  51467. if (c != 0)
  51468. c->sendLookAndFeelChange();
  51469. }
  51470. }
  51471. void LookAndFeel::clearDefaultLookAndFeel() throw()
  51472. {
  51473. if (currentDefaultLF == defaultLF)
  51474. currentDefaultLF = 0;
  51475. deleteAndZero (defaultLF);
  51476. }
  51477. const Typeface::Ptr LookAndFeel::getTypefaceForFont (const Font& font)
  51478. {
  51479. String faceName (font.getTypefaceName());
  51480. if (faceName == Font::getDefaultSansSerifFontName())
  51481. faceName = defaultSans;
  51482. else if (faceName == Font::getDefaultSerifFontName())
  51483. faceName = defaultSerif;
  51484. else if (faceName == Font::getDefaultMonospacedFontName())
  51485. faceName = defaultFixed;
  51486. Font f (font);
  51487. f.setTypefaceName (faceName);
  51488. return Typeface::createSystemTypefaceFor (f);
  51489. }
  51490. void LookAndFeel::setDefaultSansSerifTypefaceName (const String& newName)
  51491. {
  51492. defaultSans = newName;
  51493. }
  51494. const MouseCursor LookAndFeel::getMouseCursorFor (Component& component)
  51495. {
  51496. return component.getMouseCursor();
  51497. }
  51498. void LookAndFeel::drawButtonBackground (Graphics& g,
  51499. Button& button,
  51500. const Colour& backgroundColour,
  51501. bool isMouseOverButton,
  51502. bool isButtonDown)
  51503. {
  51504. const int width = button.getWidth();
  51505. const int height = button.getHeight();
  51506. const float outlineThickness = button.isEnabled() ? ((isButtonDown || isMouseOverButton) ? 1.2f : 0.7f) : 0.4f;
  51507. const float halfThickness = outlineThickness * 0.5f;
  51508. const float indentL = button.isConnectedOnLeft() ? 0.1f : halfThickness;
  51509. const float indentR = button.isConnectedOnRight() ? 0.1f : halfThickness;
  51510. const float indentT = button.isConnectedOnTop() ? 0.1f : halfThickness;
  51511. const float indentB = button.isConnectedOnBottom() ? 0.1f : halfThickness;
  51512. const Colour baseColour (createBaseColour (backgroundColour,
  51513. button.hasKeyboardFocus (true),
  51514. isMouseOverButton, isButtonDown)
  51515. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  51516. drawGlassLozenge (g,
  51517. indentL,
  51518. indentT,
  51519. width - indentL - indentR,
  51520. height - indentT - indentB,
  51521. baseColour, outlineThickness, -1.0f,
  51522. button.isConnectedOnLeft(),
  51523. button.isConnectedOnRight(),
  51524. button.isConnectedOnTop(),
  51525. button.isConnectedOnBottom());
  51526. }
  51527. const Font LookAndFeel::getFontForTextButton (TextButton& button)
  51528. {
  51529. return button.getFont();
  51530. }
  51531. void LookAndFeel::drawButtonText (Graphics& g, TextButton& button,
  51532. bool /*isMouseOverButton*/, bool /*isButtonDown*/)
  51533. {
  51534. Font font (getFontForTextButton (button));
  51535. g.setFont (font);
  51536. g.setColour (button.findColour (button.getToggleState() ? TextButton::textColourOnId
  51537. : TextButton::textColourOffId)
  51538. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  51539. const int yIndent = jmin (4, button.proportionOfHeight (0.3f));
  51540. const int cornerSize = jmin (button.getHeight(), button.getWidth()) / 2;
  51541. const int fontHeight = roundToInt (font.getHeight() * 0.6f);
  51542. const int leftIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnLeft() ? 4 : 2));
  51543. const int rightIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnRight() ? 4 : 2));
  51544. g.drawFittedText (button.getButtonText(),
  51545. leftIndent,
  51546. yIndent,
  51547. button.getWidth() - leftIndent - rightIndent,
  51548. button.getHeight() - yIndent * 2,
  51549. Justification::centred, 2);
  51550. }
  51551. void LookAndFeel::drawTickBox (Graphics& g,
  51552. Component& component,
  51553. float x, float y, float w, float h,
  51554. const bool ticked,
  51555. const bool isEnabled,
  51556. const bool isMouseOverButton,
  51557. const bool isButtonDown)
  51558. {
  51559. const float boxSize = w * 0.7f;
  51560. drawGlassSphere (g, x, y + (h - boxSize) * 0.5f, boxSize,
  51561. createBaseColour (component.findColour (TextButton::buttonColourId)
  51562. .withMultipliedAlpha (isEnabled ? 1.0f : 0.5f),
  51563. true,
  51564. isMouseOverButton,
  51565. isButtonDown),
  51566. isEnabled ? ((isButtonDown || isMouseOverButton) ? 1.1f : 0.5f) : 0.3f);
  51567. if (ticked)
  51568. {
  51569. Path tick;
  51570. tick.startNewSubPath (1.5f, 3.0f);
  51571. tick.lineTo (3.0f, 6.0f);
  51572. tick.lineTo (6.0f, 0.0f);
  51573. g.setColour (isEnabled ? Colours::black : Colours::grey);
  51574. const AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f)
  51575. .translated (x, y));
  51576. g.strokePath (tick, PathStrokeType (2.5f), trans);
  51577. }
  51578. }
  51579. void LookAndFeel::drawToggleButton (Graphics& g,
  51580. ToggleButton& button,
  51581. bool isMouseOverButton,
  51582. bool isButtonDown)
  51583. {
  51584. if (button.hasKeyboardFocus (true))
  51585. {
  51586. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  51587. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  51588. }
  51589. float fontSize = jmin (15.0f, button.getHeight() * 0.75f);
  51590. const float tickWidth = fontSize * 1.1f;
  51591. drawTickBox (g, button, 4.0f, (button.getHeight() - tickWidth) * 0.5f,
  51592. tickWidth, tickWidth,
  51593. button.getToggleState(),
  51594. button.isEnabled(),
  51595. isMouseOverButton,
  51596. isButtonDown);
  51597. g.setColour (button.findColour (ToggleButton::textColourId));
  51598. g.setFont (fontSize);
  51599. if (! button.isEnabled())
  51600. g.setOpacity (0.5f);
  51601. const int textX = (int) tickWidth + 5;
  51602. g.drawFittedText (button.getButtonText(),
  51603. textX, 0,
  51604. button.getWidth() - textX - 2, button.getHeight(),
  51605. Justification::centredLeft, 10);
  51606. }
  51607. void LookAndFeel::changeToggleButtonWidthToFitText (ToggleButton& button)
  51608. {
  51609. Font font (jmin (15.0f, button.getHeight() * 0.6f));
  51610. const int tickWidth = jmin (24, button.getHeight());
  51611. button.setSize (font.getStringWidth (button.getButtonText()) + tickWidth + 8,
  51612. button.getHeight());
  51613. }
  51614. AlertWindow* LookAndFeel::createAlertWindow (const String& title,
  51615. const String& message,
  51616. const String& button1,
  51617. const String& button2,
  51618. const String& button3,
  51619. AlertWindow::AlertIconType iconType,
  51620. int numButtons,
  51621. Component* associatedComponent)
  51622. {
  51623. AlertWindow* aw = new AlertWindow (title, message, iconType, associatedComponent);
  51624. if (numButtons == 1)
  51625. {
  51626. aw->addButton (button1, 0,
  51627. KeyPress (KeyPress::escapeKey, 0, 0),
  51628. KeyPress (KeyPress::returnKey, 0, 0));
  51629. }
  51630. else
  51631. {
  51632. const KeyPress button1ShortCut (CharacterFunctions::toLowerCase (button1[0]), 0, 0);
  51633. KeyPress button2ShortCut (CharacterFunctions::toLowerCase (button2[0]), 0, 0);
  51634. if (button1ShortCut == button2ShortCut)
  51635. button2ShortCut = KeyPress();
  51636. if (numButtons == 2)
  51637. {
  51638. aw->addButton (button1, 1, KeyPress (KeyPress::returnKey, 0, 0), button1ShortCut);
  51639. aw->addButton (button2, 0, KeyPress (KeyPress::escapeKey, 0, 0), button2ShortCut);
  51640. }
  51641. else if (numButtons == 3)
  51642. {
  51643. aw->addButton (button1, 1, button1ShortCut);
  51644. aw->addButton (button2, 2, button2ShortCut);
  51645. aw->addButton (button3, 0, KeyPress (KeyPress::escapeKey, 0, 0));
  51646. }
  51647. }
  51648. return aw;
  51649. }
  51650. void LookAndFeel::drawAlertBox (Graphics& g,
  51651. AlertWindow& alert,
  51652. const Rectangle<int>& textArea,
  51653. TextLayout& textLayout)
  51654. {
  51655. g.fillAll (alert.findColour (AlertWindow::backgroundColourId));
  51656. int iconSpaceUsed = 0;
  51657. Justification alignment (Justification::horizontallyCentred);
  51658. const int iconWidth = 80;
  51659. int iconSize = jmin (iconWidth + 50, alert.getHeight() + 20);
  51660. if (alert.containsAnyExtraComponents() || alert.getNumButtons() > 2)
  51661. iconSize = jmin (iconSize, textArea.getHeight() + 50);
  51662. const Rectangle<int> iconRect (iconSize / -10, iconSize / -10,
  51663. iconSize, iconSize);
  51664. if (alert.getAlertType() != AlertWindow::NoIcon)
  51665. {
  51666. Path icon;
  51667. uint32 colour;
  51668. char character;
  51669. if (alert.getAlertType() == AlertWindow::WarningIcon)
  51670. {
  51671. colour = 0x55ff5555;
  51672. character = '!';
  51673. icon.addTriangle (iconRect.getX() + iconRect.getWidth() * 0.5f, (float) iconRect.getY(),
  51674. (float) iconRect.getRight(), (float) iconRect.getBottom(),
  51675. (float) iconRect.getX(), (float) iconRect.getBottom());
  51676. icon = icon.createPathWithRoundedCorners (5.0f);
  51677. }
  51678. else
  51679. {
  51680. colour = alert.getAlertType() == AlertWindow::InfoIcon ? 0x605555ff : 0x40b69900;
  51681. character = alert.getAlertType() == AlertWindow::InfoIcon ? 'i' : '?';
  51682. icon.addEllipse ((float) iconRect.getX(), (float) iconRect.getY(),
  51683. (float) iconRect.getWidth(), (float) iconRect.getHeight());
  51684. }
  51685. GlyphArrangement ga;
  51686. ga.addFittedText (Font (iconRect.getHeight() * 0.9f, Font::bold),
  51687. String::charToString (character),
  51688. (float) iconRect.getX(), (float) iconRect.getY(),
  51689. (float) iconRect.getWidth(), (float) iconRect.getHeight(),
  51690. Justification::centred, false);
  51691. ga.createPath (icon);
  51692. icon.setUsingNonZeroWinding (false);
  51693. g.setColour (Colour (colour));
  51694. g.fillPath (icon);
  51695. iconSpaceUsed = iconWidth;
  51696. alignment = Justification::left;
  51697. }
  51698. g.setColour (alert.findColour (AlertWindow::textColourId));
  51699. textLayout.drawWithin (g,
  51700. textArea.getX() + iconSpaceUsed, textArea.getY(),
  51701. textArea.getWidth() - iconSpaceUsed, textArea.getHeight(),
  51702. alignment.getFlags() | Justification::top);
  51703. g.setColour (alert.findColour (AlertWindow::outlineColourId));
  51704. g.drawRect (0, 0, alert.getWidth(), alert.getHeight());
  51705. }
  51706. int LookAndFeel::getAlertBoxWindowFlags()
  51707. {
  51708. return ComponentPeer::windowAppearsOnTaskbar
  51709. | ComponentPeer::windowHasDropShadow;
  51710. }
  51711. int LookAndFeel::getAlertWindowButtonHeight()
  51712. {
  51713. return 28;
  51714. }
  51715. const Font LookAndFeel::getAlertWindowFont()
  51716. {
  51717. return Font (12.0f);
  51718. }
  51719. void LookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  51720. int width, int height,
  51721. double progress, const String& textToShow)
  51722. {
  51723. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  51724. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  51725. g.fillAll (background);
  51726. if (progress >= 0.0f && progress < 1.0f)
  51727. {
  51728. drawGlassLozenge (g, 1.0f, 1.0f,
  51729. (float) jlimit (0.0, width - 2.0, progress * (width - 2.0)),
  51730. (float) (height - 2),
  51731. foreground,
  51732. 0.5f, 0.0f,
  51733. true, true, true, true);
  51734. }
  51735. else
  51736. {
  51737. // spinning bar..
  51738. g.setColour (foreground);
  51739. const int stripeWidth = height * 2;
  51740. const int position = (Time::getMillisecondCounter() / 15) % stripeWidth;
  51741. Path p;
  51742. for (float x = (float) (- position); x < width + stripeWidth; x += stripeWidth)
  51743. p.addQuadrilateral (x, 0.0f,
  51744. x + stripeWidth * 0.5f, 0.0f,
  51745. x, (float) height,
  51746. x - stripeWidth * 0.5f, (float) height);
  51747. Image im (Image::ARGB, width, height, true);
  51748. {
  51749. Graphics g2 (im);
  51750. drawGlassLozenge (g2, 1.0f, 1.0f,
  51751. (float) (width - 2),
  51752. (float) (height - 2),
  51753. foreground,
  51754. 0.5f, 0.0f,
  51755. true, true, true, true);
  51756. }
  51757. g.setTiledImageFill (im, 0, 0, 0.85f);
  51758. g.fillPath (p);
  51759. }
  51760. if (textToShow.isNotEmpty())
  51761. {
  51762. g.setColour (Colour::contrasting (background, foreground));
  51763. g.setFont (height * 0.6f);
  51764. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  51765. }
  51766. }
  51767. void LookAndFeel::drawSpinningWaitAnimation (Graphics& g, const Colour& colour, int x, int y, int w, int h)
  51768. {
  51769. const float radius = jmin (w, h) * 0.4f;
  51770. const float thickness = radius * 0.15f;
  51771. Path p;
  51772. p.addRoundedRectangle (radius * 0.4f, thickness * -0.5f,
  51773. radius * 0.6f, thickness,
  51774. thickness * 0.5f);
  51775. const float cx = x + w * 0.5f;
  51776. const float cy = y + h * 0.5f;
  51777. const uint32 animationIndex = (Time::getMillisecondCounter() / (1000 / 10)) % 12;
  51778. for (int i = 0; i < 12; ++i)
  51779. {
  51780. const int n = (i + 12 - animationIndex) % 12;
  51781. g.setColour (colour.withMultipliedAlpha ((n + 1) / 12.0f));
  51782. g.fillPath (p, AffineTransform::rotation (i * (float_Pi / 6.0f))
  51783. .translated (cx, cy));
  51784. }
  51785. }
  51786. void LookAndFeel::drawScrollbarButton (Graphics& g,
  51787. ScrollBar& scrollbar,
  51788. int width, int height,
  51789. int buttonDirection,
  51790. bool /*isScrollbarVertical*/,
  51791. bool /*isMouseOverButton*/,
  51792. bool isButtonDown)
  51793. {
  51794. Path p;
  51795. if (buttonDirection == 0)
  51796. p.addTriangle (width * 0.5f, height * 0.2f,
  51797. width * 0.1f, height * 0.7f,
  51798. width * 0.9f, height * 0.7f);
  51799. else if (buttonDirection == 1)
  51800. p.addTriangle (width * 0.8f, height * 0.5f,
  51801. width * 0.3f, height * 0.1f,
  51802. width * 0.3f, height * 0.9f);
  51803. else if (buttonDirection == 2)
  51804. p.addTriangle (width * 0.5f, height * 0.8f,
  51805. width * 0.1f, height * 0.3f,
  51806. width * 0.9f, height * 0.3f);
  51807. else if (buttonDirection == 3)
  51808. p.addTriangle (width * 0.2f, height * 0.5f,
  51809. width * 0.7f, height * 0.1f,
  51810. width * 0.7f, height * 0.9f);
  51811. if (isButtonDown)
  51812. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId).contrasting (0.2f));
  51813. else
  51814. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId));
  51815. g.fillPath (p);
  51816. g.setColour (Colour (0x80000000));
  51817. g.strokePath (p, PathStrokeType (0.5f));
  51818. }
  51819. void LookAndFeel::drawScrollbar (Graphics& g,
  51820. ScrollBar& scrollbar,
  51821. int x, int y,
  51822. int width, int height,
  51823. bool isScrollbarVertical,
  51824. int thumbStartPosition,
  51825. int thumbSize,
  51826. bool /*isMouseOver*/,
  51827. bool /*isMouseDown*/)
  51828. {
  51829. g.fillAll (scrollbar.findColour (ScrollBar::backgroundColourId));
  51830. Path slotPath, thumbPath;
  51831. const float slotIndent = jmin (width, height) > 15 ? 1.0f : 0.0f;
  51832. const float slotIndentx2 = slotIndent * 2.0f;
  51833. const float thumbIndent = slotIndent + 1.0f;
  51834. const float thumbIndentx2 = thumbIndent * 2.0f;
  51835. float gx1 = 0.0f, gy1 = 0.0f, gx2 = 0.0f, gy2 = 0.0f;
  51836. if (isScrollbarVertical)
  51837. {
  51838. slotPath.addRoundedRectangle (x + slotIndent,
  51839. y + slotIndent,
  51840. width - slotIndentx2,
  51841. height - slotIndentx2,
  51842. (width - slotIndentx2) * 0.5f);
  51843. if (thumbSize > 0)
  51844. thumbPath.addRoundedRectangle (x + thumbIndent,
  51845. thumbStartPosition + thumbIndent,
  51846. width - thumbIndentx2,
  51847. thumbSize - thumbIndentx2,
  51848. (width - thumbIndentx2) * 0.5f);
  51849. gx1 = (float) x;
  51850. gx2 = x + width * 0.7f;
  51851. }
  51852. else
  51853. {
  51854. slotPath.addRoundedRectangle (x + slotIndent,
  51855. y + slotIndent,
  51856. width - slotIndentx2,
  51857. height - slotIndentx2,
  51858. (height - slotIndentx2) * 0.5f);
  51859. if (thumbSize > 0)
  51860. thumbPath.addRoundedRectangle (thumbStartPosition + thumbIndent,
  51861. y + thumbIndent,
  51862. thumbSize - thumbIndentx2,
  51863. height - thumbIndentx2,
  51864. (height - thumbIndentx2) * 0.5f);
  51865. gy1 = (float) y;
  51866. gy2 = y + height * 0.7f;
  51867. }
  51868. const Colour thumbColour (scrollbar.findColour (ScrollBar::thumbColourId));
  51869. g.setGradientFill (ColourGradient (thumbColour.overlaidWith (Colour (0x44000000)), gx1, gy1,
  51870. thumbColour.overlaidWith (Colour (0x19000000)), gx2, gy2, false));
  51871. g.fillPath (slotPath);
  51872. if (isScrollbarVertical)
  51873. {
  51874. gx1 = x + width * 0.6f;
  51875. gx2 = (float) x + width;
  51876. }
  51877. else
  51878. {
  51879. gy1 = y + height * 0.6f;
  51880. gy2 = (float) y + height;
  51881. }
  51882. g.setGradientFill (ColourGradient (Colours::transparentBlack,gx1, gy1,
  51883. Colour (0x19000000), gx2, gy2, false));
  51884. g.fillPath (slotPath);
  51885. g.setColour (thumbColour);
  51886. g.fillPath (thumbPath);
  51887. g.setGradientFill (ColourGradient (Colour (0x10000000), gx1, gy1,
  51888. Colours::transparentBlack, gx2, gy2, false));
  51889. g.saveState();
  51890. if (isScrollbarVertical)
  51891. g.reduceClipRegion (x + width / 2, y, width, height);
  51892. else
  51893. g.reduceClipRegion (x, y + height / 2, width, height);
  51894. g.fillPath (thumbPath);
  51895. g.restoreState();
  51896. g.setColour (Colour (0x4c000000));
  51897. g.strokePath (thumbPath, PathStrokeType (0.4f));
  51898. }
  51899. ImageEffectFilter* LookAndFeel::getScrollbarEffect()
  51900. {
  51901. return 0;
  51902. }
  51903. int LookAndFeel::getMinimumScrollbarThumbSize (ScrollBar& scrollbar)
  51904. {
  51905. return jmin (scrollbar.getWidth(), scrollbar.getHeight()) * 2;
  51906. }
  51907. int LookAndFeel::getDefaultScrollbarWidth()
  51908. {
  51909. return 18;
  51910. }
  51911. int LookAndFeel::getScrollbarButtonSize (ScrollBar& scrollbar)
  51912. {
  51913. return 2 + (scrollbar.isVertical() ? scrollbar.getWidth()
  51914. : scrollbar.getHeight());
  51915. }
  51916. const Path LookAndFeel::getTickShape (const float height)
  51917. {
  51918. static const unsigned char tickShapeData[] =
  51919. {
  51920. 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,
  51921. 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,
  51922. 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,
  51923. 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,
  51924. 96,140,68,0,128,188,67,0,224,168,68,0,0,119,67,99,101
  51925. };
  51926. Path p;
  51927. p.loadPathFromData (tickShapeData, sizeof (tickShapeData));
  51928. p.scaleToFit (0, 0, height * 2.0f, height, true);
  51929. return p;
  51930. }
  51931. const Path LookAndFeel::getCrossShape (const float height)
  51932. {
  51933. static const unsigned char crossShapeData[] =
  51934. {
  51935. 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,
  51936. 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,
  51937. 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,
  51938. 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,
  51939. 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,
  51940. 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,
  51941. 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
  51942. };
  51943. Path p;
  51944. p.loadPathFromData (crossShapeData, sizeof (crossShapeData));
  51945. p.scaleToFit (0, 0, height * 2.0f, height, true);
  51946. return p;
  51947. }
  51948. void LookAndFeel::drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus, bool /*isMouseOver*/)
  51949. {
  51950. const int boxSize = ((jmin (16, w, h) << 1) / 3) | 1;
  51951. x += (w - boxSize) >> 1;
  51952. y += (h - boxSize) >> 1;
  51953. w = boxSize;
  51954. h = boxSize;
  51955. g.setColour (Colour (0xe5ffffff));
  51956. g.fillRect (x, y, w, h);
  51957. g.setColour (Colour (0x80000000));
  51958. g.drawRect (x, y, w, h);
  51959. const float size = boxSize / 2 + 1.0f;
  51960. const float centre = (float) (boxSize / 2);
  51961. g.fillRect (x + (w - size) * 0.5f, y + centre, size, 1.0f);
  51962. if (isPlus)
  51963. g.fillRect (x + centre, y + (h - size) * 0.5f, 1.0f, size);
  51964. }
  51965. void LookAndFeel::drawBubble (Graphics& g,
  51966. float tipX, float tipY,
  51967. float boxX, float boxY,
  51968. float boxW, float boxH)
  51969. {
  51970. int side = 0;
  51971. if (tipX < boxX)
  51972. side = 1;
  51973. else if (tipX > boxX + boxW)
  51974. side = 3;
  51975. else if (tipY > boxY + boxH)
  51976. side = 2;
  51977. const float indent = 2.0f;
  51978. Path p;
  51979. p.addBubble (boxX + indent,
  51980. boxY + indent,
  51981. boxW - indent * 2.0f,
  51982. boxH - indent * 2.0f,
  51983. 5.0f,
  51984. tipX, tipY,
  51985. side,
  51986. 0.5f,
  51987. jmin (15.0f, boxW * 0.3f, boxH * 0.3f));
  51988. //xxx need to take comp as param for colour
  51989. g.setColour (findColour (TooltipWindow::backgroundColourId).withAlpha (0.9f));
  51990. g.fillPath (p);
  51991. //xxx as above
  51992. g.setColour (findColour (TooltipWindow::textColourId).withAlpha (0.4f));
  51993. g.strokePath (p, PathStrokeType (1.33f));
  51994. }
  51995. const Font LookAndFeel::getPopupMenuFont()
  51996. {
  51997. return Font (17.0f);
  51998. }
  51999. void LookAndFeel::getIdealPopupMenuItemSize (const String& text,
  52000. const bool isSeparator,
  52001. int standardMenuItemHeight,
  52002. int& idealWidth,
  52003. int& idealHeight)
  52004. {
  52005. if (isSeparator)
  52006. {
  52007. idealWidth = 50;
  52008. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight / 2 : 10;
  52009. }
  52010. else
  52011. {
  52012. Font font (getPopupMenuFont());
  52013. if (standardMenuItemHeight > 0 && font.getHeight() > standardMenuItemHeight / 1.3f)
  52014. font.setHeight (standardMenuItemHeight / 1.3f);
  52015. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight : roundToInt (font.getHeight() * 1.3f);
  52016. idealWidth = font.getStringWidth (text) + idealHeight * 2;
  52017. }
  52018. }
  52019. void LookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  52020. {
  52021. const Colour background (findColour (PopupMenu::backgroundColourId));
  52022. g.fillAll (background);
  52023. g.setColour (background.overlaidWith (Colour (0x2badd8e6)));
  52024. for (int i = 0; i < height; i += 3)
  52025. g.fillRect (0, i, width, 1);
  52026. #if ! JUCE_MAC
  52027. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.6f));
  52028. g.drawRect (0, 0, width, height);
  52029. #endif
  52030. }
  52031. void LookAndFeel::drawPopupMenuUpDownArrow (Graphics& g,
  52032. int width, int height,
  52033. bool isScrollUpArrow)
  52034. {
  52035. const Colour background (findColour (PopupMenu::backgroundColourId));
  52036. g.setGradientFill (ColourGradient (background, 0.0f, height * 0.5f,
  52037. background.withAlpha (0.0f),
  52038. 0.0f, isScrollUpArrow ? ((float) height) : 0.0f,
  52039. false));
  52040. g.fillRect (1, 1, width - 2, height - 2);
  52041. const float hw = width * 0.5f;
  52042. const float arrowW = height * 0.3f;
  52043. const float y1 = height * (isScrollUpArrow ? 0.6f : 0.3f);
  52044. const float y2 = height * (isScrollUpArrow ? 0.3f : 0.6f);
  52045. Path p;
  52046. p.addTriangle (hw - arrowW, y1,
  52047. hw + arrowW, y1,
  52048. hw, y2);
  52049. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.5f));
  52050. g.fillPath (p);
  52051. }
  52052. void LookAndFeel::drawPopupMenuItem (Graphics& g,
  52053. int width, int height,
  52054. const bool isSeparator,
  52055. const bool isActive,
  52056. const bool isHighlighted,
  52057. const bool isTicked,
  52058. const bool hasSubMenu,
  52059. const String& text,
  52060. const String& shortcutKeyText,
  52061. Image* image,
  52062. const Colour* const textColourToUse)
  52063. {
  52064. const float halfH = height * 0.5f;
  52065. if (isSeparator)
  52066. {
  52067. const float separatorIndent = 5.5f;
  52068. g.setColour (Colour (0x33000000));
  52069. g.drawLine (separatorIndent, halfH, width - separatorIndent, halfH);
  52070. g.setColour (Colour (0x66ffffff));
  52071. g.drawLine (separatorIndent, halfH + 1.0f, width - separatorIndent, halfH + 1.0f);
  52072. }
  52073. else
  52074. {
  52075. Colour textColour (findColour (PopupMenu::textColourId));
  52076. if (textColourToUse != 0)
  52077. textColour = *textColourToUse;
  52078. if (isHighlighted)
  52079. {
  52080. g.setColour (findColour (PopupMenu::highlightedBackgroundColourId));
  52081. g.fillRect (1, 1, width - 2, height - 2);
  52082. g.setColour (findColour (PopupMenu::highlightedTextColourId));
  52083. }
  52084. else
  52085. {
  52086. g.setColour (textColour);
  52087. }
  52088. if (! isActive)
  52089. g.setOpacity (0.3f);
  52090. Font font (getPopupMenuFont());
  52091. if (font.getHeight() > height / 1.3f)
  52092. font.setHeight (height / 1.3f);
  52093. g.setFont (font);
  52094. const int leftBorder = (height * 5) / 4;
  52095. const int rightBorder = 4;
  52096. if (image != 0)
  52097. {
  52098. g.drawImageWithin (*image,
  52099. 2, 1, leftBorder - 4, height - 2,
  52100. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize, false);
  52101. }
  52102. else if (isTicked)
  52103. {
  52104. const Path tick (getTickShape (1.0f));
  52105. const float th = font.getAscent();
  52106. const float ty = halfH - th * 0.5f;
  52107. g.fillPath (tick, tick.getTransformToScaleToFit (2.0f, ty, (float) (leftBorder - 4),
  52108. th, true));
  52109. }
  52110. g.drawFittedText (text,
  52111. leftBorder, 0,
  52112. width - (leftBorder + rightBorder), height,
  52113. Justification::centredLeft, 1);
  52114. if (shortcutKeyText.isNotEmpty())
  52115. {
  52116. Font f2 (font);
  52117. f2.setHeight (f2.getHeight() * 0.75f);
  52118. f2.setHorizontalScale (0.95f);
  52119. g.setFont (f2);
  52120. g.drawText (shortcutKeyText,
  52121. leftBorder,
  52122. 0,
  52123. width - (leftBorder + rightBorder + 4),
  52124. height,
  52125. Justification::centredRight,
  52126. true);
  52127. }
  52128. if (hasSubMenu)
  52129. {
  52130. const float arrowH = 0.6f * getPopupMenuFont().getAscent();
  52131. const float x = width - height * 0.6f;
  52132. Path p;
  52133. p.addTriangle (x, halfH - arrowH * 0.5f,
  52134. x, halfH + arrowH * 0.5f,
  52135. x + arrowH * 0.6f, halfH);
  52136. g.fillPath (p);
  52137. }
  52138. }
  52139. }
  52140. int LookAndFeel::getMenuWindowFlags()
  52141. {
  52142. return ComponentPeer::windowHasDropShadow;
  52143. }
  52144. void LookAndFeel::drawMenuBarBackground (Graphics& g, int width, int height,
  52145. bool, MenuBarComponent& menuBar)
  52146. {
  52147. const Colour baseColour (createBaseColour (menuBar.findColour (PopupMenu::backgroundColourId), false, false, false));
  52148. if (menuBar.isEnabled())
  52149. {
  52150. drawShinyButtonShape (g,
  52151. -4.0f, 0.0f,
  52152. width + 8.0f, (float) height,
  52153. 0.0f,
  52154. baseColour,
  52155. 0.4f,
  52156. true, true, true, true);
  52157. }
  52158. else
  52159. {
  52160. g.fillAll (baseColour);
  52161. }
  52162. }
  52163. const Font LookAndFeel::getMenuBarFont (MenuBarComponent& menuBar, int /*itemIndex*/, const String& /*itemText*/)
  52164. {
  52165. return Font (menuBar.getHeight() * 0.7f);
  52166. }
  52167. int LookAndFeel::getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText)
  52168. {
  52169. return getMenuBarFont (menuBar, itemIndex, itemText)
  52170. .getStringWidth (itemText) + menuBar.getHeight();
  52171. }
  52172. void LookAndFeel::drawMenuBarItem (Graphics& g,
  52173. int width, int height,
  52174. int itemIndex,
  52175. const String& itemText,
  52176. bool isMouseOverItem,
  52177. bool isMenuOpen,
  52178. bool /*isMouseOverBar*/,
  52179. MenuBarComponent& menuBar)
  52180. {
  52181. if (! menuBar.isEnabled())
  52182. {
  52183. g.setColour (menuBar.findColour (PopupMenu::textColourId)
  52184. .withMultipliedAlpha (0.5f));
  52185. }
  52186. else if (isMenuOpen || isMouseOverItem)
  52187. {
  52188. g.fillAll (menuBar.findColour (PopupMenu::highlightedBackgroundColourId));
  52189. g.setColour (menuBar.findColour (PopupMenu::highlightedTextColourId));
  52190. }
  52191. else
  52192. {
  52193. g.setColour (menuBar.findColour (PopupMenu::textColourId));
  52194. }
  52195. g.setFont (getMenuBarFont (menuBar, itemIndex, itemText));
  52196. g.drawFittedText (itemText, 0, 0, width, height, Justification::centred, 1);
  52197. }
  52198. void LookAndFeel::fillTextEditorBackground (Graphics& g, int /*width*/, int /*height*/,
  52199. TextEditor& textEditor)
  52200. {
  52201. g.fillAll (textEditor.findColour (TextEditor::backgroundColourId));
  52202. }
  52203. void LookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  52204. {
  52205. if (textEditor.isEnabled())
  52206. {
  52207. if (textEditor.hasKeyboardFocus (true) && ! textEditor.isReadOnly())
  52208. {
  52209. const int border = 2;
  52210. g.setColour (textEditor.findColour (TextEditor::focusedOutlineColourId));
  52211. g.drawRect (0, 0, width, height, border);
  52212. g.setOpacity (1.0f);
  52213. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId).withMultipliedAlpha (0.75f));
  52214. g.drawBevel (0, 0, width, height + 2, border + 2, shadowColour, shadowColour);
  52215. }
  52216. else
  52217. {
  52218. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  52219. g.drawRect (0, 0, width, height);
  52220. g.setOpacity (1.0f);
  52221. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId));
  52222. g.drawBevel (0, 0, width, height + 2, 3, shadowColour, shadowColour);
  52223. }
  52224. }
  52225. }
  52226. void LookAndFeel::drawComboBox (Graphics& g, int width, int height,
  52227. const bool isButtonDown,
  52228. int buttonX, int buttonY,
  52229. int buttonW, int buttonH,
  52230. ComboBox& box)
  52231. {
  52232. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  52233. if (box.isEnabled() && box.hasKeyboardFocus (false))
  52234. {
  52235. g.setColour (box.findColour (TextButton::buttonColourId));
  52236. g.drawRect (0, 0, width, height, 2);
  52237. }
  52238. else
  52239. {
  52240. g.setColour (box.findColour (ComboBox::outlineColourId));
  52241. g.drawRect (0, 0, width, height);
  52242. }
  52243. const float outlineThickness = box.isEnabled() ? (isButtonDown ? 1.2f : 0.5f) : 0.3f;
  52244. const Colour baseColour (createBaseColour (box.findColour (ComboBox::buttonColourId),
  52245. box.hasKeyboardFocus (true),
  52246. false, isButtonDown)
  52247. .withMultipliedAlpha (box.isEnabled() ? 1.0f : 0.5f));
  52248. drawGlassLozenge (g,
  52249. buttonX + outlineThickness, buttonY + outlineThickness,
  52250. buttonW - outlineThickness * 2.0f, buttonH - outlineThickness * 2.0f,
  52251. baseColour, outlineThickness, -1.0f,
  52252. true, true, true, true);
  52253. if (box.isEnabled())
  52254. {
  52255. const float arrowX = 0.3f;
  52256. const float arrowH = 0.2f;
  52257. Path p;
  52258. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  52259. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  52260. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  52261. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  52262. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  52263. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  52264. g.setColour (box.findColour (ComboBox::arrowColourId));
  52265. g.fillPath (p);
  52266. }
  52267. }
  52268. const Font LookAndFeel::getComboBoxFont (ComboBox& box)
  52269. {
  52270. return Font (jmin (15.0f, box.getHeight() * 0.85f));
  52271. }
  52272. Label* LookAndFeel::createComboBoxTextBox (ComboBox&)
  52273. {
  52274. return new Label (String::empty, String::empty);
  52275. }
  52276. void LookAndFeel::positionComboBoxText (ComboBox& box, Label& label)
  52277. {
  52278. label.setBounds (1, 1,
  52279. box.getWidth() + 3 - box.getHeight(),
  52280. box.getHeight() - 2);
  52281. label.setFont (getComboBoxFont (box));
  52282. }
  52283. void LookAndFeel::drawLabel (Graphics& g, Label& label)
  52284. {
  52285. g.fillAll (label.findColour (Label::backgroundColourId));
  52286. if (! label.isBeingEdited())
  52287. {
  52288. const float alpha = label.isEnabled() ? 1.0f : 0.5f;
  52289. g.setColour (label.findColour (Label::textColourId).withMultipliedAlpha (alpha));
  52290. g.setFont (label.getFont());
  52291. g.drawFittedText (label.getText(),
  52292. label.getHorizontalBorderSize(),
  52293. label.getVerticalBorderSize(),
  52294. label.getWidth() - 2 * label.getHorizontalBorderSize(),
  52295. label.getHeight() - 2 * label.getVerticalBorderSize(),
  52296. label.getJustificationType(),
  52297. jmax (1, (int) (label.getHeight() / label.getFont().getHeight())),
  52298. label.getMinimumHorizontalScale());
  52299. g.setColour (label.findColour (Label::outlineColourId).withMultipliedAlpha (alpha));
  52300. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  52301. }
  52302. else if (label.isEnabled())
  52303. {
  52304. g.setColour (label.findColour (Label::outlineColourId));
  52305. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  52306. }
  52307. }
  52308. void LookAndFeel::drawLinearSliderBackground (Graphics& g,
  52309. int x, int y,
  52310. int width, int height,
  52311. float /*sliderPos*/,
  52312. float /*minSliderPos*/,
  52313. float /*maxSliderPos*/,
  52314. const Slider::SliderStyle /*style*/,
  52315. Slider& slider)
  52316. {
  52317. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  52318. const Colour trackColour (slider.findColour (Slider::trackColourId));
  52319. const Colour gradCol1 (trackColour.overlaidWith (Colours::black.withAlpha (slider.isEnabled() ? 0.25f : 0.13f)));
  52320. const Colour gradCol2 (trackColour.overlaidWith (Colour (0x14000000)));
  52321. Path indent;
  52322. if (slider.isHorizontal())
  52323. {
  52324. const float iy = y + height * 0.5f - sliderRadius * 0.5f;
  52325. const float ih = sliderRadius;
  52326. g.setGradientFill (ColourGradient (gradCol1, 0.0f, iy,
  52327. gradCol2, 0.0f, iy + ih, false));
  52328. indent.addRoundedRectangle (x - sliderRadius * 0.5f, iy,
  52329. width + sliderRadius, ih,
  52330. 5.0f);
  52331. g.fillPath (indent);
  52332. }
  52333. else
  52334. {
  52335. const float ix = x + width * 0.5f - sliderRadius * 0.5f;
  52336. const float iw = sliderRadius;
  52337. g.setGradientFill (ColourGradient (gradCol1, ix, 0.0f,
  52338. gradCol2, ix + iw, 0.0f, false));
  52339. indent.addRoundedRectangle (ix, y - sliderRadius * 0.5f,
  52340. iw, height + sliderRadius,
  52341. 5.0f);
  52342. g.fillPath (indent);
  52343. }
  52344. g.setColour (Colour (0x4c000000));
  52345. g.strokePath (indent, PathStrokeType (0.5f));
  52346. }
  52347. void LookAndFeel::drawLinearSliderThumb (Graphics& g,
  52348. int x, int y,
  52349. int width, int height,
  52350. float sliderPos,
  52351. float minSliderPos,
  52352. float maxSliderPos,
  52353. const Slider::SliderStyle style,
  52354. Slider& slider)
  52355. {
  52356. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  52357. Colour knobColour (createBaseColour (slider.findColour (Slider::thumbColourId),
  52358. slider.hasKeyboardFocus (false) && slider.isEnabled(),
  52359. slider.isMouseOverOrDragging() && slider.isEnabled(),
  52360. slider.isMouseButtonDown() && slider.isEnabled()));
  52361. const float outlineThickness = slider.isEnabled() ? 0.8f : 0.3f;
  52362. if (style == Slider::LinearHorizontal || style == Slider::LinearVertical)
  52363. {
  52364. float kx, ky;
  52365. if (style == Slider::LinearVertical)
  52366. {
  52367. kx = x + width * 0.5f;
  52368. ky = sliderPos;
  52369. }
  52370. else
  52371. {
  52372. kx = sliderPos;
  52373. ky = y + height * 0.5f;
  52374. }
  52375. drawGlassSphere (g,
  52376. kx - sliderRadius,
  52377. ky - sliderRadius,
  52378. sliderRadius * 2.0f,
  52379. knobColour, outlineThickness);
  52380. }
  52381. else
  52382. {
  52383. if (style == Slider::ThreeValueVertical)
  52384. {
  52385. drawGlassSphere (g, x + width * 0.5f - sliderRadius,
  52386. sliderPos - sliderRadius,
  52387. sliderRadius * 2.0f,
  52388. knobColour, outlineThickness);
  52389. }
  52390. else if (style == Slider::ThreeValueHorizontal)
  52391. {
  52392. drawGlassSphere (g,sliderPos - sliderRadius,
  52393. y + height * 0.5f - sliderRadius,
  52394. sliderRadius * 2.0f,
  52395. knobColour, outlineThickness);
  52396. }
  52397. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  52398. {
  52399. const float sr = jmin (sliderRadius, width * 0.4f);
  52400. drawGlassPointer (g, jmax (0.0f, x + width * 0.5f - sliderRadius * 2.0f),
  52401. minSliderPos - sliderRadius,
  52402. sliderRadius * 2.0f, knobColour, outlineThickness, 1);
  52403. drawGlassPointer (g, jmin (x + width - sliderRadius * 2.0f, x + width * 0.5f), maxSliderPos - sr,
  52404. sliderRadius * 2.0f, knobColour, outlineThickness, 3);
  52405. }
  52406. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  52407. {
  52408. const float sr = jmin (sliderRadius, height * 0.4f);
  52409. drawGlassPointer (g, minSliderPos - sr,
  52410. jmax (0.0f, y + height * 0.5f - sliderRadius * 2.0f),
  52411. sliderRadius * 2.0f, knobColour, outlineThickness, 2);
  52412. drawGlassPointer (g, maxSliderPos - sliderRadius,
  52413. jmin (y + height - sliderRadius * 2.0f, y + height * 0.5f),
  52414. sliderRadius * 2.0f, knobColour, outlineThickness, 4);
  52415. }
  52416. }
  52417. }
  52418. void LookAndFeel::drawLinearSlider (Graphics& g,
  52419. int x, int y,
  52420. int width, int height,
  52421. float sliderPos,
  52422. float minSliderPos,
  52423. float maxSliderPos,
  52424. const Slider::SliderStyle style,
  52425. Slider& slider)
  52426. {
  52427. g.fillAll (slider.findColour (Slider::backgroundColourId));
  52428. if (style == Slider::LinearBar)
  52429. {
  52430. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  52431. Colour baseColour (createBaseColour (slider.findColour (Slider::thumbColourId)
  52432. .withMultipliedSaturation (slider.isEnabled() ? 1.0f : 0.5f),
  52433. false,
  52434. isMouseOver,
  52435. isMouseOver || slider.isMouseButtonDown()));
  52436. drawShinyButtonShape (g,
  52437. (float) x, (float) y, sliderPos - (float) x, (float) height, 0.0f,
  52438. baseColour,
  52439. slider.isEnabled() ? 0.9f : 0.3f,
  52440. true, true, true, true);
  52441. }
  52442. else
  52443. {
  52444. drawLinearSliderBackground (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  52445. drawLinearSliderThumb (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  52446. }
  52447. }
  52448. int LookAndFeel::getSliderThumbRadius (Slider& slider)
  52449. {
  52450. return jmin (7,
  52451. slider.getHeight() / 2,
  52452. slider.getWidth() / 2) + 2;
  52453. }
  52454. void LookAndFeel::drawRotarySlider (Graphics& g,
  52455. int x, int y,
  52456. int width, int height,
  52457. float sliderPos,
  52458. const float rotaryStartAngle,
  52459. const float rotaryEndAngle,
  52460. Slider& slider)
  52461. {
  52462. const float radius = jmin (width / 2, height / 2) - 2.0f;
  52463. const float centreX = x + width * 0.5f;
  52464. const float centreY = y + height * 0.5f;
  52465. const float rx = centreX - radius;
  52466. const float ry = centreY - radius;
  52467. const float rw = radius * 2.0f;
  52468. const float angle = rotaryStartAngle + sliderPos * (rotaryEndAngle - rotaryStartAngle);
  52469. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  52470. if (radius > 12.0f)
  52471. {
  52472. if (slider.isEnabled())
  52473. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  52474. else
  52475. g.setColour (Colour (0x80808080));
  52476. const float thickness = 0.7f;
  52477. {
  52478. Path filledArc;
  52479. filledArc.addPieSegment (rx, ry, rw, rw,
  52480. rotaryStartAngle,
  52481. angle,
  52482. thickness);
  52483. g.fillPath (filledArc);
  52484. }
  52485. if (thickness > 0)
  52486. {
  52487. const float innerRadius = radius * 0.2f;
  52488. Path p;
  52489. p.addTriangle (-innerRadius, 0.0f,
  52490. 0.0f, -radius * thickness * 1.1f,
  52491. innerRadius, 0.0f);
  52492. p.addEllipse (-innerRadius, -innerRadius, innerRadius * 2.0f, innerRadius * 2.0f);
  52493. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  52494. }
  52495. if (slider.isEnabled())
  52496. g.setColour (slider.findColour (Slider::rotarySliderOutlineColourId));
  52497. else
  52498. g.setColour (Colour (0x80808080));
  52499. Path outlineArc;
  52500. outlineArc.addPieSegment (rx, ry, rw, rw, rotaryStartAngle, rotaryEndAngle, thickness);
  52501. outlineArc.closeSubPath();
  52502. g.strokePath (outlineArc, PathStrokeType (slider.isEnabled() ? (isMouseOver ? 2.0f : 1.2f) : 0.3f));
  52503. }
  52504. else
  52505. {
  52506. if (slider.isEnabled())
  52507. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  52508. else
  52509. g.setColour (Colour (0x80808080));
  52510. Path p;
  52511. p.addEllipse (-0.4f * rw, -0.4f * rw, rw * 0.8f, rw * 0.8f);
  52512. PathStrokeType (rw * 0.1f).createStrokedPath (p, p);
  52513. p.addLineSegment (Line<float> (0.0f, 0.0f, 0.0f, -radius), rw * 0.2f);
  52514. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  52515. }
  52516. }
  52517. Button* LookAndFeel::createSliderButton (const bool isIncrement)
  52518. {
  52519. return new TextButton (isIncrement ? "+" : "-", String::empty);
  52520. }
  52521. class SliderLabelComp : public Label
  52522. {
  52523. public:
  52524. SliderLabelComp() : Label (String::empty, String::empty) {}
  52525. ~SliderLabelComp() {}
  52526. void mouseWheelMove (const MouseEvent&, float, float) {}
  52527. };
  52528. Label* LookAndFeel::createSliderTextBox (Slider& slider)
  52529. {
  52530. Label* const l = new SliderLabelComp();
  52531. l->setJustificationType (Justification::centred);
  52532. l->setColour (Label::textColourId, slider.findColour (Slider::textBoxTextColourId));
  52533. l->setColour (Label::backgroundColourId,
  52534. (slider.getSliderStyle() == Slider::LinearBar) ? Colours::transparentBlack
  52535. : slider.findColour (Slider::textBoxBackgroundColourId));
  52536. l->setColour (Label::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  52537. l->setColour (TextEditor::textColourId, slider.findColour (Slider::textBoxTextColourId));
  52538. l->setColour (TextEditor::backgroundColourId,
  52539. slider.findColour (Slider::textBoxBackgroundColourId)
  52540. .withAlpha (slider.getSliderStyle() == Slider::LinearBar ? 0.7f : 1.0f));
  52541. l->setColour (TextEditor::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  52542. return l;
  52543. }
  52544. ImageEffectFilter* LookAndFeel::getSliderEffect()
  52545. {
  52546. return 0;
  52547. }
  52548. static const TextLayout layoutTooltipText (const String& text) throw()
  52549. {
  52550. const float tooltipFontSize = 12.0f;
  52551. const int maxToolTipWidth = 400;
  52552. const Font f (tooltipFontSize, Font::bold);
  52553. TextLayout tl (text, f);
  52554. tl.layout (maxToolTipWidth, Justification::left, true);
  52555. return tl;
  52556. }
  52557. void LookAndFeel::getTooltipSize (const String& tipText, int& width, int& height)
  52558. {
  52559. const TextLayout tl (layoutTooltipText (tipText));
  52560. width = tl.getWidth() + 14;
  52561. height = tl.getHeight() + 6;
  52562. }
  52563. void LookAndFeel::drawTooltip (Graphics& g, const String& text, int width, int height)
  52564. {
  52565. g.fillAll (findColour (TooltipWindow::backgroundColourId));
  52566. const Colour textCol (findColour (TooltipWindow::textColourId));
  52567. #if ! JUCE_MAC // The mac windows already have a non-optional 1 pix outline, so don't double it here..
  52568. g.setColour (findColour (TooltipWindow::outlineColourId));
  52569. g.drawRect (0, 0, width, height, 1);
  52570. #endif
  52571. const TextLayout tl (layoutTooltipText (text));
  52572. g.setColour (findColour (TooltipWindow::textColourId));
  52573. tl.drawWithin (g, 0, 0, width, height, Justification::centred);
  52574. }
  52575. Button* LookAndFeel::createFilenameComponentBrowseButton (const String& text)
  52576. {
  52577. return new TextButton (text, TRANS("click to browse for a different file"));
  52578. }
  52579. void LookAndFeel::layoutFilenameComponent (FilenameComponent& filenameComp,
  52580. ComboBox* filenameBox,
  52581. Button* browseButton)
  52582. {
  52583. browseButton->setSize (80, filenameComp.getHeight());
  52584. TextButton* const tb = dynamic_cast <TextButton*> (browseButton);
  52585. if (tb != 0)
  52586. tb->changeWidthToFitText();
  52587. browseButton->setTopRightPosition (filenameComp.getWidth(), 0);
  52588. filenameBox->setBounds (0, 0, browseButton->getX(), filenameComp.getHeight());
  52589. }
  52590. void LookAndFeel::drawImageButton (Graphics& g, Image* image,
  52591. int imageX, int imageY, int imageW, int imageH,
  52592. const Colour& overlayColour,
  52593. float imageOpacity,
  52594. ImageButton& button)
  52595. {
  52596. if (! button.isEnabled())
  52597. imageOpacity *= 0.3f;
  52598. if (! overlayColour.isOpaque())
  52599. {
  52600. g.setOpacity (imageOpacity);
  52601. g.drawImage (*image, imageX, imageY, imageW, imageH,
  52602. 0, 0, image->getWidth(), image->getHeight(), false);
  52603. }
  52604. if (! overlayColour.isTransparent())
  52605. {
  52606. g.setColour (overlayColour);
  52607. g.drawImage (*image, imageX, imageY, imageW, imageH,
  52608. 0, 0, image->getWidth(), image->getHeight(), true);
  52609. }
  52610. }
  52611. void LookAndFeel::drawCornerResizer (Graphics& g,
  52612. int w, int h,
  52613. bool /*isMouseOver*/,
  52614. bool /*isMouseDragging*/)
  52615. {
  52616. const float lineThickness = jmin (w, h) * 0.075f;
  52617. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  52618. {
  52619. g.setColour (Colours::lightgrey);
  52620. g.drawLine (w * i,
  52621. h + 1.0f,
  52622. w + 1.0f,
  52623. h * i,
  52624. lineThickness);
  52625. g.setColour (Colours::darkgrey);
  52626. g.drawLine (w * i + lineThickness,
  52627. h + 1.0f,
  52628. w + 1.0f,
  52629. h * i + lineThickness,
  52630. lineThickness);
  52631. }
  52632. }
  52633. void LookAndFeel::drawResizableFrame (Graphics&, int /*w*/, int /*h*/,
  52634. const BorderSize& /*borders*/)
  52635. {
  52636. }
  52637. void LookAndFeel::fillResizableWindowBackground (Graphics& g, int /*w*/, int /*h*/,
  52638. const BorderSize& /*border*/, ResizableWindow& window)
  52639. {
  52640. g.fillAll (window.getBackgroundColour());
  52641. }
  52642. void LookAndFeel::drawResizableWindowBorder (Graphics& g, int w, int h,
  52643. const BorderSize& border, ResizableWindow&)
  52644. {
  52645. g.setColour (Colour (0x80000000));
  52646. g.drawRect (0, 0, w, h);
  52647. g.setColour (Colour (0x19000000));
  52648. g.drawRect (border.getLeft() - 1,
  52649. border.getTop() - 1,
  52650. w + 2 - border.getLeftAndRight(),
  52651. h + 2 - border.getTopAndBottom());
  52652. }
  52653. void LookAndFeel::drawDocumentWindowTitleBar (DocumentWindow& window,
  52654. Graphics& g, int w, int h,
  52655. int titleSpaceX, int titleSpaceW,
  52656. const Image* icon,
  52657. bool drawTitleTextOnLeft)
  52658. {
  52659. const bool isActive = window.isActiveWindow();
  52660. g.setGradientFill (ColourGradient (window.getBackgroundColour(),
  52661. 0.0f, 0.0f,
  52662. window.getBackgroundColour().contrasting (isActive ? 0.15f : 0.05f),
  52663. 0.0f, (float) h, false));
  52664. g.fillAll();
  52665. Font font (h * 0.65f, Font::bold);
  52666. g.setFont (font);
  52667. int textW = font.getStringWidth (window.getName());
  52668. int iconW = 0;
  52669. int iconH = 0;
  52670. if (icon != 0)
  52671. {
  52672. iconH = (int) font.getHeight();
  52673. iconW = icon->getWidth() * iconH / icon->getHeight() + 4;
  52674. }
  52675. textW = jmin (titleSpaceW, textW + iconW);
  52676. int textX = drawTitleTextOnLeft ? titleSpaceX
  52677. : jmax (titleSpaceX, (w - textW) / 2);
  52678. if (textX + textW > titleSpaceX + titleSpaceW)
  52679. textX = titleSpaceX + titleSpaceW - textW;
  52680. if (icon != 0)
  52681. {
  52682. g.setOpacity (isActive ? 1.0f : 0.6f);
  52683. g.drawImageWithin (*icon, textX, (h - iconH) / 2, iconW, iconH,
  52684. RectanglePlacement::centred, false);
  52685. textX += iconW;
  52686. textW -= iconW;
  52687. }
  52688. if (window.isColourSpecified (DocumentWindow::textColourId) || isColourSpecified (DocumentWindow::textColourId))
  52689. g.setColour (findColour (DocumentWindow::textColourId));
  52690. else
  52691. g.setColour (window.getBackgroundColour().contrasting (isActive ? 0.7f : 0.4f));
  52692. g.drawText (window.getName(), textX, 0, textW, h, Justification::centredLeft, true);
  52693. }
  52694. class GlassWindowButton : public Button
  52695. {
  52696. public:
  52697. GlassWindowButton (const String& name, const Colour& col,
  52698. const Path& normalShape_,
  52699. const Path& toggledShape_) throw()
  52700. : Button (name),
  52701. colour (col),
  52702. normalShape (normalShape_),
  52703. toggledShape (toggledShape_)
  52704. {
  52705. }
  52706. ~GlassWindowButton()
  52707. {
  52708. }
  52709. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  52710. {
  52711. float alpha = isMouseOverButton ? (isButtonDown ? 1.0f : 0.8f) : 0.55f;
  52712. if (! isEnabled())
  52713. alpha *= 0.5f;
  52714. float x = 0, y = 0, diam;
  52715. if (getWidth() < getHeight())
  52716. {
  52717. diam = (float) getWidth();
  52718. y = (getHeight() - getWidth()) * 0.5f;
  52719. }
  52720. else
  52721. {
  52722. diam = (float) getHeight();
  52723. y = (getWidth() - getHeight()) * 0.5f;
  52724. }
  52725. x += diam * 0.05f;
  52726. y += diam * 0.05f;
  52727. diam *= 0.9f;
  52728. g.setGradientFill (ColourGradient (Colour::greyLevel (0.9f).withAlpha (alpha), 0, y + diam,
  52729. Colour::greyLevel (0.6f).withAlpha (alpha), 0, y, false));
  52730. g.fillEllipse (x, y, diam, diam);
  52731. x += 2.0f;
  52732. y += 2.0f;
  52733. diam -= 4.0f;
  52734. LookAndFeel::drawGlassSphere (g, x, y, diam, colour.withAlpha (alpha), 1.0f);
  52735. Path& p = getToggleState() ? toggledShape : normalShape;
  52736. const AffineTransform t (p.getTransformToScaleToFit (x + diam * 0.3f, y + diam * 0.3f,
  52737. diam * 0.4f, diam * 0.4f, true));
  52738. g.setColour (Colours::black.withAlpha (alpha * 0.6f));
  52739. g.fillPath (p, t);
  52740. }
  52741. juce_UseDebuggingNewOperator
  52742. private:
  52743. Colour colour;
  52744. Path normalShape, toggledShape;
  52745. GlassWindowButton (const GlassWindowButton&);
  52746. GlassWindowButton& operator= (const GlassWindowButton&);
  52747. };
  52748. Button* LookAndFeel::createDocumentWindowButton (int buttonType)
  52749. {
  52750. Path shape;
  52751. const float crossThickness = 0.25f;
  52752. if (buttonType == DocumentWindow::closeButton)
  52753. {
  52754. shape.addLineSegment (Line<float> (0.0f, 0.0f, 1.0f, 1.0f), crossThickness * 1.4f);
  52755. shape.addLineSegment (Line<float> (1.0f, 0.0f, 0.0f, 1.0f), crossThickness * 1.4f);
  52756. return new GlassWindowButton ("close", Colour (0xffdd1100), shape, shape);
  52757. }
  52758. else if (buttonType == DocumentWindow::minimiseButton)
  52759. {
  52760. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), crossThickness);
  52761. return new GlassWindowButton ("minimise", Colour (0xffaa8811), shape, shape);
  52762. }
  52763. else if (buttonType == DocumentWindow::maximiseButton)
  52764. {
  52765. shape.addLineSegment (Line<float> (0.5f, 0.0f, 0.5f, 1.0f), crossThickness);
  52766. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), crossThickness);
  52767. Path fullscreenShape;
  52768. fullscreenShape.startNewSubPath (45.0f, 100.0f);
  52769. fullscreenShape.lineTo (0.0f, 100.0f);
  52770. fullscreenShape.lineTo (0.0f, 0.0f);
  52771. fullscreenShape.lineTo (100.0f, 0.0f);
  52772. fullscreenShape.lineTo (100.0f, 45.0f);
  52773. fullscreenShape.addRectangle (45.0f, 45.0f, 100.0f, 100.0f);
  52774. PathStrokeType (30.0f).createStrokedPath (fullscreenShape, fullscreenShape);
  52775. return new GlassWindowButton ("maximise", Colour (0xff119911), shape, fullscreenShape);
  52776. }
  52777. jassertfalse;
  52778. return 0;
  52779. }
  52780. void LookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  52781. int titleBarX,
  52782. int titleBarY,
  52783. int titleBarW,
  52784. int titleBarH,
  52785. Button* minimiseButton,
  52786. Button* maximiseButton,
  52787. Button* closeButton,
  52788. bool positionTitleBarButtonsOnLeft)
  52789. {
  52790. const int buttonW = titleBarH - titleBarH / 8;
  52791. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  52792. : titleBarX + titleBarW - buttonW - buttonW / 4;
  52793. if (closeButton != 0)
  52794. {
  52795. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  52796. x += positionTitleBarButtonsOnLeft ? buttonW : -(buttonW + buttonW / 4);
  52797. }
  52798. if (positionTitleBarButtonsOnLeft)
  52799. swapVariables (minimiseButton, maximiseButton);
  52800. if (maximiseButton != 0)
  52801. {
  52802. maximiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  52803. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  52804. }
  52805. if (minimiseButton != 0)
  52806. minimiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  52807. }
  52808. int LookAndFeel::getDefaultMenuBarHeight()
  52809. {
  52810. return 24;
  52811. }
  52812. DropShadower* LookAndFeel::createDropShadowerForComponent (Component*)
  52813. {
  52814. return new DropShadower (0.4f, 1, 5, 10);
  52815. }
  52816. void LookAndFeel::drawStretchableLayoutResizerBar (Graphics& g,
  52817. int w, int h,
  52818. bool /*isVerticalBar*/,
  52819. bool isMouseOver,
  52820. bool isMouseDragging)
  52821. {
  52822. float alpha = 0.5f;
  52823. if (isMouseOver || isMouseDragging)
  52824. {
  52825. g.fillAll (Colour (0x190000ff));
  52826. alpha = 1.0f;
  52827. }
  52828. const float cx = w * 0.5f;
  52829. const float cy = h * 0.5f;
  52830. const float cr = jmin (w, h) * 0.4f;
  52831. g.setGradientFill (ColourGradient (Colours::white.withAlpha (alpha), cx + cr * 0.1f, cy + cr,
  52832. Colours::black.withAlpha (alpha), cx, cy - cr * 4.0f,
  52833. true));
  52834. g.fillEllipse (cx - cr, cy - cr, cr * 2.0f, cr * 2.0f);
  52835. }
  52836. void LookAndFeel::drawGroupComponentOutline (Graphics& g, int width, int height,
  52837. const String& text,
  52838. const Justification& position,
  52839. GroupComponent& group)
  52840. {
  52841. const float textH = 15.0f;
  52842. const float indent = 3.0f;
  52843. const float textEdgeGap = 4.0f;
  52844. float cs = 5.0f;
  52845. Font f (textH);
  52846. Path p;
  52847. float x = indent;
  52848. float y = f.getAscent() - 3.0f;
  52849. float w = jmax (0.0f, width - x * 2.0f);
  52850. float h = jmax (0.0f, height - y - indent);
  52851. cs = jmin (cs, w * 0.5f, h * 0.5f);
  52852. const float cs2 = 2.0f * cs;
  52853. float textW = text.isEmpty() ? 0 : jlimit (0.0f, jmax (0.0f, w - cs2 - textEdgeGap * 2), f.getStringWidth (text) + textEdgeGap * 2.0f);
  52854. float textX = cs + textEdgeGap;
  52855. if (position.testFlags (Justification::horizontallyCentred))
  52856. textX = cs + (w - cs2 - textW) * 0.5f;
  52857. else if (position.testFlags (Justification::right))
  52858. textX = w - cs - textW - textEdgeGap;
  52859. p.startNewSubPath (x + textX + textW, y);
  52860. p.lineTo (x + w - cs, y);
  52861. p.addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  52862. p.lineTo (x + w, y + h - cs);
  52863. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  52864. p.lineTo (x + cs, y + h);
  52865. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  52866. p.lineTo (x, y + cs);
  52867. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  52868. p.lineTo (x + textX, y);
  52869. const float alpha = group.isEnabled() ? 1.0f : 0.5f;
  52870. g.setColour (group.findColour (GroupComponent::outlineColourId)
  52871. .withMultipliedAlpha (alpha));
  52872. g.strokePath (p, PathStrokeType (2.0f));
  52873. g.setColour (group.findColour (GroupComponent::textColourId)
  52874. .withMultipliedAlpha (alpha));
  52875. g.setFont (f);
  52876. g.drawText (text,
  52877. roundToInt (x + textX), 0,
  52878. roundToInt (textW),
  52879. roundToInt (textH),
  52880. Justification::centred, true);
  52881. }
  52882. int LookAndFeel::getTabButtonOverlap (int tabDepth)
  52883. {
  52884. return 1 + tabDepth / 3;
  52885. }
  52886. int LookAndFeel::getTabButtonSpaceAroundImage()
  52887. {
  52888. return 4;
  52889. }
  52890. void LookAndFeel::createTabButtonShape (Path& p,
  52891. int width, int height,
  52892. int /*tabIndex*/,
  52893. const String& /*text*/,
  52894. Button& /*button*/,
  52895. TabbedButtonBar::Orientation orientation,
  52896. const bool /*isMouseOver*/,
  52897. const bool /*isMouseDown*/,
  52898. const bool /*isFrontTab*/)
  52899. {
  52900. const float w = (float) width;
  52901. const float h = (float) height;
  52902. float length = w;
  52903. float depth = h;
  52904. if (orientation == TabbedButtonBar::TabsAtLeft
  52905. || orientation == TabbedButtonBar::TabsAtRight)
  52906. {
  52907. swapVariables (length, depth);
  52908. }
  52909. const float indent = (float) getTabButtonOverlap ((int) depth);
  52910. const float overhang = 4.0f;
  52911. if (orientation == TabbedButtonBar::TabsAtLeft)
  52912. {
  52913. p.startNewSubPath (w, 0.0f);
  52914. p.lineTo (0.0f, indent);
  52915. p.lineTo (0.0f, h - indent);
  52916. p.lineTo (w, h);
  52917. p.lineTo (w + overhang, h + overhang);
  52918. p.lineTo (w + overhang, -overhang);
  52919. }
  52920. else if (orientation == TabbedButtonBar::TabsAtRight)
  52921. {
  52922. p.startNewSubPath (0.0f, 0.0f);
  52923. p.lineTo (w, indent);
  52924. p.lineTo (w, h - indent);
  52925. p.lineTo (0.0f, h);
  52926. p.lineTo (-overhang, h + overhang);
  52927. p.lineTo (-overhang, -overhang);
  52928. }
  52929. else if (orientation == TabbedButtonBar::TabsAtBottom)
  52930. {
  52931. p.startNewSubPath (0.0f, 0.0f);
  52932. p.lineTo (indent, h);
  52933. p.lineTo (w - indent, h);
  52934. p.lineTo (w, 0.0f);
  52935. p.lineTo (w + overhang, -overhang);
  52936. p.lineTo (-overhang, -overhang);
  52937. }
  52938. else
  52939. {
  52940. p.startNewSubPath (0.0f, h);
  52941. p.lineTo (indent, 0.0f);
  52942. p.lineTo (w - indent, 0.0f);
  52943. p.lineTo (w, h);
  52944. p.lineTo (w + overhang, h + overhang);
  52945. p.lineTo (-overhang, h + overhang);
  52946. }
  52947. p.closeSubPath();
  52948. p = p.createPathWithRoundedCorners (3.0f);
  52949. }
  52950. void LookAndFeel::fillTabButtonShape (Graphics& g,
  52951. const Path& path,
  52952. const Colour& preferredColour,
  52953. int /*tabIndex*/,
  52954. const String& /*text*/,
  52955. Button& button,
  52956. TabbedButtonBar::Orientation /*orientation*/,
  52957. const bool /*isMouseOver*/,
  52958. const bool /*isMouseDown*/,
  52959. const bool isFrontTab)
  52960. {
  52961. g.setColour (isFrontTab ? preferredColour
  52962. : preferredColour.withMultipliedAlpha (0.9f));
  52963. g.fillPath (path);
  52964. g.setColour (button.findColour (isFrontTab ? TabbedButtonBar::frontOutlineColourId
  52965. : TabbedButtonBar::tabOutlineColourId, false)
  52966. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  52967. g.strokePath (path, PathStrokeType (isFrontTab ? 1.0f : 0.5f));
  52968. }
  52969. void LookAndFeel::drawTabButtonText (Graphics& g,
  52970. int x, int y, int w, int h,
  52971. const Colour& preferredBackgroundColour,
  52972. int /*tabIndex*/,
  52973. const String& text,
  52974. Button& button,
  52975. TabbedButtonBar::Orientation orientation,
  52976. const bool isMouseOver,
  52977. const bool isMouseDown,
  52978. const bool isFrontTab)
  52979. {
  52980. int length = w;
  52981. int depth = h;
  52982. if (orientation == TabbedButtonBar::TabsAtLeft
  52983. || orientation == TabbedButtonBar::TabsAtRight)
  52984. {
  52985. swapVariables (length, depth);
  52986. }
  52987. Font font (depth * 0.6f);
  52988. font.setUnderline (button.hasKeyboardFocus (false));
  52989. GlyphArrangement textLayout;
  52990. textLayout.addFittedText (font, text.trim(),
  52991. 0.0f, 0.0f, (float) length, (float) depth,
  52992. Justification::centred,
  52993. jmax (1, depth / 12));
  52994. AffineTransform transform;
  52995. if (orientation == TabbedButtonBar::TabsAtLeft)
  52996. {
  52997. transform = transform.rotated (float_Pi * -0.5f)
  52998. .translated ((float) x, (float) (y + h));
  52999. }
  53000. else if (orientation == TabbedButtonBar::TabsAtRight)
  53001. {
  53002. transform = transform.rotated (float_Pi * 0.5f)
  53003. .translated ((float) (x + w), (float) y);
  53004. }
  53005. else
  53006. {
  53007. transform = transform.translated ((float) x, (float) y);
  53008. }
  53009. if (isFrontTab && (button.isColourSpecified (TabbedButtonBar::frontTextColourId) || isColourSpecified (TabbedButtonBar::frontTextColourId)))
  53010. g.setColour (findColour (TabbedButtonBar::frontTextColourId));
  53011. else if (button.isColourSpecified (TabbedButtonBar::tabTextColourId) || isColourSpecified (TabbedButtonBar::tabTextColourId))
  53012. g.setColour (findColour (TabbedButtonBar::tabTextColourId));
  53013. else
  53014. g.setColour (preferredBackgroundColour.contrasting());
  53015. if (! (isMouseOver || isMouseDown))
  53016. g.setOpacity (0.8f);
  53017. if (! button.isEnabled())
  53018. g.setOpacity (0.3f);
  53019. textLayout.draw (g, transform);
  53020. }
  53021. int LookAndFeel::getTabButtonBestWidth (int /*tabIndex*/,
  53022. const String& text,
  53023. int tabDepth,
  53024. Button&)
  53025. {
  53026. Font f (tabDepth * 0.6f);
  53027. return f.getStringWidth (text.trim()) + getTabButtonOverlap (tabDepth) * 2;
  53028. }
  53029. void LookAndFeel::drawTabButton (Graphics& g,
  53030. int w, int h,
  53031. const Colour& preferredColour,
  53032. int tabIndex,
  53033. const String& text,
  53034. Button& button,
  53035. TabbedButtonBar::Orientation orientation,
  53036. const bool isMouseOver,
  53037. const bool isMouseDown,
  53038. const bool isFrontTab)
  53039. {
  53040. int length = w;
  53041. int depth = h;
  53042. if (orientation == TabbedButtonBar::TabsAtLeft
  53043. || orientation == TabbedButtonBar::TabsAtRight)
  53044. {
  53045. swapVariables (length, depth);
  53046. }
  53047. Path tabShape;
  53048. createTabButtonShape (tabShape, w, h,
  53049. tabIndex, text, button, orientation,
  53050. isMouseOver, isMouseDown, isFrontTab);
  53051. fillTabButtonShape (g, tabShape, preferredColour,
  53052. tabIndex, text, button, orientation,
  53053. isMouseOver, isMouseDown, isFrontTab);
  53054. const int indent = getTabButtonOverlap (depth);
  53055. int x = 0, y = 0;
  53056. if (orientation == TabbedButtonBar::TabsAtLeft
  53057. || orientation == TabbedButtonBar::TabsAtRight)
  53058. {
  53059. y += indent;
  53060. h -= indent * 2;
  53061. }
  53062. else
  53063. {
  53064. x += indent;
  53065. w -= indent * 2;
  53066. }
  53067. drawTabButtonText (g, x, y, w, h, preferredColour,
  53068. tabIndex, text, button, orientation,
  53069. isMouseOver, isMouseDown, isFrontTab);
  53070. }
  53071. void LookAndFeel::drawTabAreaBehindFrontButton (Graphics& g,
  53072. int w, int h,
  53073. TabbedButtonBar& tabBar,
  53074. TabbedButtonBar::Orientation orientation)
  53075. {
  53076. const float shadowSize = 0.2f;
  53077. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  53078. Rectangle<int> shadowRect;
  53079. if (orientation == TabbedButtonBar::TabsAtLeft)
  53080. {
  53081. x1 = (float) w;
  53082. x2 = w * (1.0f - shadowSize);
  53083. shadowRect.setBounds ((int) x2, 0, w - (int) x2, h);
  53084. }
  53085. else if (orientation == TabbedButtonBar::TabsAtRight)
  53086. {
  53087. x2 = w * shadowSize;
  53088. shadowRect.setBounds (0, 0, (int) x2, h);
  53089. }
  53090. else if (orientation == TabbedButtonBar::TabsAtBottom)
  53091. {
  53092. y2 = h * shadowSize;
  53093. shadowRect.setBounds (0, 0, w, (int) y2);
  53094. }
  53095. else
  53096. {
  53097. y1 = (float) h;
  53098. y2 = h * (1.0f - shadowSize);
  53099. shadowRect.setBounds (0, (int) y2, w, h - (int) y2);
  53100. }
  53101. g.setGradientFill (ColourGradient (Colours::black.withAlpha (tabBar.isEnabled() ? 0.3f : 0.15f), x1, y1,
  53102. Colours::transparentBlack, x2, y2, false));
  53103. shadowRect.expand (2, 2);
  53104. g.fillRect (shadowRect);
  53105. g.setColour (Colour (0x80000000));
  53106. if (orientation == TabbedButtonBar::TabsAtLeft)
  53107. {
  53108. g.fillRect (w - 1, 0, 1, h);
  53109. }
  53110. else if (orientation == TabbedButtonBar::TabsAtRight)
  53111. {
  53112. g.fillRect (0, 0, 1, h);
  53113. }
  53114. else if (orientation == TabbedButtonBar::TabsAtBottom)
  53115. {
  53116. g.fillRect (0, 0, w, 1);
  53117. }
  53118. else
  53119. {
  53120. g.fillRect (0, h - 1, w, 1);
  53121. }
  53122. }
  53123. Button* LookAndFeel::createTabBarExtrasButton()
  53124. {
  53125. const float thickness = 7.0f;
  53126. const float indent = 22.0f;
  53127. Path p;
  53128. p.addEllipse (-10.0f, -10.0f, 120.0f, 120.0f);
  53129. DrawablePath ellipse;
  53130. ellipse.setPath (p);
  53131. ellipse.setFill (Colour (0x99ffffff));
  53132. p.clear();
  53133. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  53134. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  53135. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  53136. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  53137. p.setUsingNonZeroWinding (false);
  53138. DrawablePath dp;
  53139. dp.setPath (p);
  53140. dp.setFill (Colour (0x59000000));
  53141. DrawableComposite normalImage;
  53142. normalImage.insertDrawable (ellipse);
  53143. normalImage.insertDrawable (dp);
  53144. dp.setFill (Colour (0xcc000000));
  53145. DrawableComposite overImage;
  53146. overImage.insertDrawable (ellipse);
  53147. overImage.insertDrawable (dp);
  53148. DrawableButton* db = new DrawableButton ("tabs", DrawableButton::ImageFitted);
  53149. db->setImages (&normalImage, &overImage, 0);
  53150. return db;
  53151. }
  53152. void LookAndFeel::drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header)
  53153. {
  53154. g.fillAll (Colours::white);
  53155. const int w = header.getWidth();
  53156. const int h = header.getHeight();
  53157. g.setGradientFill (ColourGradient (Colour (0xffe8ebf9), 0.0f, h * 0.5f,
  53158. Colour (0xfff6f8f9), 0.0f, h - 1.0f,
  53159. false));
  53160. g.fillRect (0, h / 2, w, h);
  53161. g.setColour (Colour (0x33000000));
  53162. g.fillRect (0, h - 1, w, 1);
  53163. for (int i = header.getNumColumns (true); --i >= 0;)
  53164. g.fillRect (header.getColumnPosition (i).getRight() - 1, 0, 1, h - 1);
  53165. }
  53166. void LookAndFeel::drawTableHeaderColumn (Graphics& g, const String& columnName, int /*columnId*/,
  53167. int width, int height,
  53168. bool isMouseOver, bool isMouseDown,
  53169. int columnFlags)
  53170. {
  53171. if (isMouseDown)
  53172. g.fillAll (Colour (0x8899aadd));
  53173. else if (isMouseOver)
  53174. g.fillAll (Colour (0x5599aadd));
  53175. int rightOfText = width - 4;
  53176. if ((columnFlags & (TableHeaderComponent::sortedForwards | TableHeaderComponent::sortedBackwards)) != 0)
  53177. {
  53178. const float top = height * ((columnFlags & TableHeaderComponent::sortedForwards) != 0 ? 0.35f : (1.0f - 0.35f));
  53179. const float bottom = height - top;
  53180. const float w = height * 0.5f;
  53181. const float x = rightOfText - (w * 1.25f);
  53182. rightOfText = (int) x;
  53183. Path sortArrow;
  53184. sortArrow.addTriangle (x, bottom, x + w * 0.5f, top, x + w, bottom);
  53185. g.setColour (Colour (0x99000000));
  53186. g.fillPath (sortArrow);
  53187. }
  53188. g.setColour (Colours::black);
  53189. g.setFont (height * 0.5f, Font::bold);
  53190. const int textX = 4;
  53191. g.drawFittedText (columnName, textX, 0, rightOfText - textX, height, Justification::centredLeft, 1);
  53192. }
  53193. void LookAndFeel::paintToolbarBackground (Graphics& g, int w, int h, Toolbar& toolbar)
  53194. {
  53195. const Colour background (toolbar.findColour (Toolbar::backgroundColourId));
  53196. g.setGradientFill (ColourGradient (background, 0.0f, 0.0f,
  53197. background.darker (0.1f),
  53198. toolbar.isVertical() ? w - 1.0f : 0.0f,
  53199. toolbar.isVertical() ? 0.0f : h - 1.0f,
  53200. false));
  53201. g.fillAll();
  53202. }
  53203. Button* LookAndFeel::createToolbarMissingItemsButton (Toolbar& /*toolbar*/)
  53204. {
  53205. return createTabBarExtrasButton();
  53206. }
  53207. void LookAndFeel::paintToolbarButtonBackground (Graphics& g, int /*width*/, int /*height*/,
  53208. bool isMouseOver, bool isMouseDown,
  53209. ToolbarItemComponent& component)
  53210. {
  53211. if (isMouseDown)
  53212. g.fillAll (component.findColour (Toolbar::buttonMouseDownBackgroundColourId, true));
  53213. else if (isMouseOver)
  53214. g.fillAll (component.findColour (Toolbar::buttonMouseOverBackgroundColourId, true));
  53215. }
  53216. void LookAndFeel::paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  53217. const String& text, ToolbarItemComponent& component)
  53218. {
  53219. g.setColour (component.findColour (Toolbar::labelTextColourId, true)
  53220. .withAlpha (component.isEnabled() ? 1.0f : 0.25f));
  53221. const float fontHeight = jmin (14.0f, height * 0.85f);
  53222. g.setFont (fontHeight);
  53223. g.drawFittedText (text,
  53224. x, y, width, height,
  53225. Justification::centred,
  53226. jmax (1, height / (int) fontHeight));
  53227. }
  53228. void LookAndFeel::drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  53229. bool isOpen, int width, int height)
  53230. {
  53231. const int buttonSize = (height * 3) / 4;
  53232. const int buttonIndent = (height - buttonSize) / 2;
  53233. drawTreeviewPlusMinusBox (g, buttonIndent, buttonIndent, buttonSize, buttonSize, ! isOpen, false);
  53234. const int textX = buttonIndent * 2 + buttonSize + 2;
  53235. g.setColour (Colours::black);
  53236. g.setFont (height * 0.7f, Font::bold);
  53237. g.drawText (name, textX, 0, width - textX - 4, height, Justification::centredLeft, true);
  53238. }
  53239. void LookAndFeel::drawPropertyComponentBackground (Graphics& g, int width, int height,
  53240. PropertyComponent&)
  53241. {
  53242. g.setColour (Colour (0x66ffffff));
  53243. g.fillRect (0, 0, width, height - 1);
  53244. }
  53245. void LookAndFeel::drawPropertyComponentLabel (Graphics& g, int, int height,
  53246. PropertyComponent& component)
  53247. {
  53248. g.setColour (Colours::black);
  53249. if (! component.isEnabled())
  53250. g.setOpacity (0.6f);
  53251. g.setFont (jmin (height, 24) * 0.65f);
  53252. const Rectangle<int> r (getPropertyComponentContentPosition (component));
  53253. g.drawFittedText (component.getName(),
  53254. 3, r.getY(), r.getX() - 5, r.getHeight(),
  53255. Justification::centredLeft, 2);
  53256. }
  53257. const Rectangle<int> LookAndFeel::getPropertyComponentContentPosition (PropertyComponent& component)
  53258. {
  53259. return Rectangle<int> (component.getWidth() / 3, 1,
  53260. component.getWidth() - component.getWidth() / 3 - 1, component.getHeight() - 3);
  53261. }
  53262. void LookAndFeel::drawCallOutBoxBackground (CallOutBox& box, Graphics& g, const Path& path)
  53263. {
  53264. Image content (Image::ARGB, box.getWidth(), box.getHeight(), true);
  53265. {
  53266. Graphics g2 (content);
  53267. g2.setColour (Colour::greyLevel (0.23f).withAlpha (0.9f));
  53268. g2.fillPath (path);
  53269. g2.setColour (Colours::white.withAlpha (0.8f));
  53270. g2.strokePath (path, PathStrokeType (2.0f));
  53271. }
  53272. DropShadowEffect shadow;
  53273. shadow.setShadowProperties (5.0f, 0.4f, 0, 2);
  53274. shadow.applyEffect (content, g);
  53275. }
  53276. void LookAndFeel::createFileChooserHeaderText (const String& title,
  53277. const String& instructions,
  53278. GlyphArrangement& text,
  53279. int width)
  53280. {
  53281. text.clear();
  53282. text.addJustifiedText (Font (17.0f, Font::bold), title,
  53283. 8.0f, 22.0f, width - 16.0f,
  53284. Justification::centred);
  53285. text.addJustifiedText (Font (14.0f), instructions,
  53286. 8.0f, 24.0f + 16.0f, width - 16.0f,
  53287. Justification::centred);
  53288. }
  53289. void LookAndFeel::drawFileBrowserRow (Graphics& g, int width, int height,
  53290. const String& filename, Image* icon,
  53291. const String& fileSizeDescription,
  53292. const String& fileTimeDescription,
  53293. const bool isDirectory,
  53294. const bool isItemSelected,
  53295. const int /*itemIndex*/)
  53296. {
  53297. if (isItemSelected)
  53298. g.fillAll (findColour (DirectoryContentsDisplayComponent::highlightColourId));
  53299. g.setColour (findColour (DirectoryContentsDisplayComponent::textColourId));
  53300. g.setFont (height * 0.7f);
  53301. Image im;
  53302. if (icon != 0)
  53303. im = *icon;
  53304. if (im.isNull())
  53305. im = isDirectory ? getDefaultFolderImage()
  53306. : getDefaultDocumentFileImage();
  53307. const int x = 32;
  53308. if (im.isValid())
  53309. {
  53310. g.drawImageWithin (im, 2, 2, x - 4, height - 4,
  53311. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  53312. false);
  53313. }
  53314. if (width > 450 && ! isDirectory)
  53315. {
  53316. const int sizeX = roundToInt (width * 0.7f);
  53317. const int dateX = roundToInt (width * 0.8f);
  53318. g.drawFittedText (filename,
  53319. x, 0, sizeX - x, height,
  53320. Justification::centredLeft, 1);
  53321. g.setFont (height * 0.5f);
  53322. g.setColour (Colours::darkgrey);
  53323. if (! isDirectory)
  53324. {
  53325. g.drawFittedText (fileSizeDescription,
  53326. sizeX, 0, dateX - sizeX - 8, height,
  53327. Justification::centredRight, 1);
  53328. g.drawFittedText (fileTimeDescription,
  53329. dateX, 0, width - 8 - dateX, height,
  53330. Justification::centredRight, 1);
  53331. }
  53332. }
  53333. else
  53334. {
  53335. g.drawFittedText (filename,
  53336. x, 0, width - x, height,
  53337. Justification::centredLeft, 1);
  53338. }
  53339. }
  53340. Button* LookAndFeel::createFileBrowserGoUpButton()
  53341. {
  53342. DrawableButton* goUpButton = new DrawableButton ("up", DrawableButton::ImageOnButtonBackground);
  53343. Path arrowPath;
  53344. arrowPath.addArrow (Line<float> (50.0f, 100.0f, 50.0f, 0.0f), 40.0f, 100.0f, 50.0f);
  53345. DrawablePath arrowImage;
  53346. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  53347. arrowImage.setPath (arrowPath);
  53348. goUpButton->setImages (&arrowImage);
  53349. return goUpButton;
  53350. }
  53351. void LookAndFeel::layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  53352. DirectoryContentsDisplayComponent* fileListComponent,
  53353. FilePreviewComponent* previewComp,
  53354. ComboBox* currentPathBox,
  53355. TextEditor* filenameBox,
  53356. Button* goUpButton)
  53357. {
  53358. const int x = 8;
  53359. int w = browserComp.getWidth() - x - x;
  53360. if (previewComp != 0)
  53361. {
  53362. const int previewWidth = w / 3;
  53363. previewComp->setBounds (x + w - previewWidth, 0, previewWidth, browserComp.getHeight());
  53364. w -= previewWidth + 4;
  53365. }
  53366. int y = 4;
  53367. const int controlsHeight = 22;
  53368. const int bottomSectionHeight = controlsHeight + 8;
  53369. const int upButtonWidth = 50;
  53370. currentPathBox->setBounds (x, y, w - upButtonWidth - 6, controlsHeight);
  53371. goUpButton->setBounds (x + w - upButtonWidth, y, upButtonWidth, controlsHeight);
  53372. y += controlsHeight + 4;
  53373. Component* const listAsComp = dynamic_cast <Component*> (fileListComponent);
  53374. listAsComp->setBounds (x, y, w, browserComp.getHeight() - y - bottomSectionHeight);
  53375. y = listAsComp->getBottom() + 4;
  53376. filenameBox->setBounds (x + 50, y, w - 50, controlsHeight);
  53377. }
  53378. const Image LookAndFeel::getDefaultFolderImage()
  53379. {
  53380. 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,
  53381. 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,
  53382. 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,
  53383. 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,
  53384. 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,
  53385. 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,
  53386. 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,
  53387. 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,
  53388. 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,
  53389. 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,
  53390. 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,
  53391. 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,
  53392. 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,
  53393. 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,
  53394. 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,
  53395. 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,
  53396. 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,
  53397. 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,
  53398. 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,
  53399. 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,
  53400. 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,
  53401. 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,
  53402. 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,
  53403. 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,
  53404. 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,
  53405. 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,
  53406. 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,
  53407. 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,
  53408. 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,
  53409. 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,
  53410. 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,
  53411. 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,
  53412. 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,
  53413. 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,
  53414. 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,
  53415. 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,
  53416. 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,
  53417. 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,
  53418. 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,
  53419. 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,
  53420. 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,
  53421. 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,
  53422. 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,
  53423. 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};
  53424. return ImageCache::getFromMemory (foldericon_png, sizeof (foldericon_png));
  53425. }
  53426. const Image LookAndFeel::getDefaultDocumentFileImage()
  53427. {
  53428. 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,
  53429. 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,
  53430. 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,
  53431. 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,
  53432. 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,
  53433. 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,
  53434. 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,
  53435. 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,
  53436. 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,
  53437. 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,
  53438. 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,
  53439. 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,
  53440. 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,
  53441. 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,
  53442. 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,
  53443. 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,
  53444. 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,
  53445. 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,
  53446. 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,
  53447. 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,
  53448. 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,
  53449. 174,66,96,130,0,0};
  53450. return ImageCache::getFromMemory (fileicon_png, sizeof (fileicon_png));
  53451. }
  53452. void LookAndFeel::playAlertSound()
  53453. {
  53454. PlatformUtilities::beep();
  53455. }
  53456. void LookAndFeel::drawLevelMeter (Graphics& g, int width, int height, float level)
  53457. {
  53458. g.setColour (Colours::white.withAlpha (0.7f));
  53459. g.fillRoundedRectangle (0.0f, 0.0f, (float) width, (float) height, 3.0f);
  53460. g.setColour (Colours::black.withAlpha (0.2f));
  53461. g.drawRoundedRectangle (1.0f, 1.0f, width - 2.0f, height - 2.0f, 3.0f, 1.0f);
  53462. const int totalBlocks = 7;
  53463. const int numBlocks = roundToInt (totalBlocks * level);
  53464. const float w = (width - 6.0f) / (float) totalBlocks;
  53465. for (int i = 0; i < totalBlocks; ++i)
  53466. {
  53467. if (i >= numBlocks)
  53468. g.setColour (Colours::lightblue.withAlpha (0.6f));
  53469. else
  53470. g.setColour (i < totalBlocks - 1 ? Colours::blue.withAlpha (0.5f)
  53471. : Colours::red);
  53472. g.fillRoundedRectangle (3.0f + i * w + w * 0.1f, 3.0f, w * 0.8f, height - 6.0f, w * 0.4f);
  53473. }
  53474. }
  53475. void LookAndFeel::drawKeymapChangeButton (Graphics& g, int width, int height, Button& button, const String& keyDescription)
  53476. {
  53477. const Colour textColour (button.findColour (KeyMappingEditorComponent::textColourId, true));
  53478. if (keyDescription.isNotEmpty())
  53479. {
  53480. if (button.isEnabled())
  53481. {
  53482. const float alpha = button.isDown() ? 0.3f : (button.isOver() ? 0.15f : 0.08f);
  53483. g.fillAll (textColour.withAlpha (alpha));
  53484. g.setOpacity (0.3f);
  53485. g.drawBevel (0, 0, width, height, 2);
  53486. }
  53487. g.setColour (textColour);
  53488. g.setFont (height * 0.6f);
  53489. g.drawFittedText (keyDescription,
  53490. 3, 0, width - 6, height,
  53491. Justification::centred, 1);
  53492. }
  53493. else
  53494. {
  53495. const float thickness = 7.0f;
  53496. const float indent = 22.0f;
  53497. Path p;
  53498. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  53499. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  53500. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  53501. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  53502. p.setUsingNonZeroWinding (false);
  53503. g.setColour (textColour.withAlpha (button.isDown() ? 0.7f : (button.isOver() ? 0.5f : 0.3f)));
  53504. g.fillPath (p, p.getTransformToScaleToFit (2.0f, 2.0f, width - 4.0f, height - 4.0f, true));
  53505. }
  53506. if (button.hasKeyboardFocus (false))
  53507. {
  53508. g.setColour (textColour.withAlpha (0.4f));
  53509. g.drawRect (0, 0, width, height);
  53510. }
  53511. }
  53512. static void createRoundedPath (Path& p,
  53513. const float x, const float y,
  53514. const float w, const float h,
  53515. const float cs,
  53516. const bool curveTopLeft, const bool curveTopRight,
  53517. const bool curveBottomLeft, const bool curveBottomRight) throw()
  53518. {
  53519. const float cs2 = 2.0f * cs;
  53520. if (curveTopLeft)
  53521. {
  53522. p.startNewSubPath (x, y + cs);
  53523. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  53524. }
  53525. else
  53526. {
  53527. p.startNewSubPath (x, y);
  53528. }
  53529. if (curveTopRight)
  53530. {
  53531. p.lineTo (x + w - cs, y);
  53532. p.addArc (x + w - cs2, y, cs2, cs2, 0.0f, float_Pi * 0.5f);
  53533. }
  53534. else
  53535. {
  53536. p.lineTo (x + w, y);
  53537. }
  53538. if (curveBottomRight)
  53539. {
  53540. p.lineTo (x + w, y + h - cs);
  53541. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  53542. }
  53543. else
  53544. {
  53545. p.lineTo (x + w, y + h);
  53546. }
  53547. if (curveBottomLeft)
  53548. {
  53549. p.lineTo (x + cs, y + h);
  53550. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  53551. }
  53552. else
  53553. {
  53554. p.lineTo (x, y + h);
  53555. }
  53556. p.closeSubPath();
  53557. }
  53558. void LookAndFeel::drawShinyButtonShape (Graphics& g,
  53559. float x, float y, float w, float h,
  53560. float maxCornerSize,
  53561. const Colour& baseColour,
  53562. const float strokeWidth,
  53563. const bool flatOnLeft,
  53564. const bool flatOnRight,
  53565. const bool flatOnTop,
  53566. const bool flatOnBottom) throw()
  53567. {
  53568. if (w <= strokeWidth * 1.1f || h <= strokeWidth * 1.1f)
  53569. return;
  53570. const float cs = jmin (maxCornerSize, w * 0.5f, h * 0.5f);
  53571. Path outline;
  53572. createRoundedPath (outline, x, y, w, h, cs,
  53573. ! (flatOnLeft || flatOnTop),
  53574. ! (flatOnRight || flatOnTop),
  53575. ! (flatOnLeft || flatOnBottom),
  53576. ! (flatOnRight || flatOnBottom));
  53577. ColourGradient cg (baseColour, 0.0f, y,
  53578. baseColour.overlaidWith (Colour (0x070000ff)), 0.0f, y + h,
  53579. false);
  53580. cg.addColour (0.5, baseColour.overlaidWith (Colour (0x33ffffff)));
  53581. cg.addColour (0.51, baseColour.overlaidWith (Colour (0x110000ff)));
  53582. g.setGradientFill (cg);
  53583. g.fillPath (outline);
  53584. g.setColour (Colour (0x80000000));
  53585. g.strokePath (outline, PathStrokeType (strokeWidth));
  53586. }
  53587. void LookAndFeel::drawGlassSphere (Graphics& g,
  53588. const float x, const float y,
  53589. const float diameter,
  53590. const Colour& colour,
  53591. const float outlineThickness) throw()
  53592. {
  53593. if (diameter <= outlineThickness)
  53594. return;
  53595. Path p;
  53596. p.addEllipse (x, y, diameter, diameter);
  53597. {
  53598. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  53599. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  53600. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  53601. g.setGradientFill (cg);
  53602. g.fillPath (p);
  53603. }
  53604. g.setGradientFill (ColourGradient (Colours::white, 0, y + diameter * 0.06f,
  53605. Colours::transparentWhite, 0, y + diameter * 0.3f, false));
  53606. g.fillEllipse (x + diameter * 0.2f, y + diameter * 0.05f, diameter * 0.6f, diameter * 0.4f);
  53607. ColourGradient cg (Colours::transparentBlack,
  53608. x + diameter * 0.5f, y + diameter * 0.5f,
  53609. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  53610. x, y + diameter * 0.5f, true);
  53611. cg.addColour (0.7, Colours::transparentBlack);
  53612. cg.addColour (0.8, Colours::black.withAlpha (0.1f * outlineThickness));
  53613. g.setGradientFill (cg);
  53614. g.fillPath (p);
  53615. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  53616. g.drawEllipse (x, y, diameter, diameter, outlineThickness);
  53617. }
  53618. void LookAndFeel::drawGlassPointer (Graphics& g,
  53619. const float x, const float y,
  53620. const float diameter,
  53621. const Colour& colour, const float outlineThickness,
  53622. const int direction) throw()
  53623. {
  53624. if (diameter <= outlineThickness)
  53625. return;
  53626. Path p;
  53627. p.startNewSubPath (x + diameter * 0.5f, y);
  53628. p.lineTo (x + diameter, y + diameter * 0.6f);
  53629. p.lineTo (x + diameter, y + diameter);
  53630. p.lineTo (x, y + diameter);
  53631. p.lineTo (x, y + diameter * 0.6f);
  53632. p.closeSubPath();
  53633. p.applyTransform (AffineTransform::rotation (direction * (float_Pi * 0.5f), x + diameter * 0.5f, y + diameter * 0.5f));
  53634. {
  53635. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  53636. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  53637. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  53638. g.setGradientFill (cg);
  53639. g.fillPath (p);
  53640. }
  53641. ColourGradient cg (Colours::transparentBlack,
  53642. x + diameter * 0.5f, y + diameter * 0.5f,
  53643. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  53644. x - diameter * 0.2f, y + diameter * 0.5f, true);
  53645. cg.addColour (0.5, Colours::transparentBlack);
  53646. cg.addColour (0.7, Colours::black.withAlpha (0.07f * outlineThickness));
  53647. g.setGradientFill (cg);
  53648. g.fillPath (p);
  53649. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  53650. g.strokePath (p, PathStrokeType (outlineThickness));
  53651. }
  53652. void LookAndFeel::drawGlassLozenge (Graphics& g,
  53653. const float x, const float y,
  53654. const float width, const float height,
  53655. const Colour& colour,
  53656. const float outlineThickness,
  53657. const float cornerSize,
  53658. const bool flatOnLeft,
  53659. const bool flatOnRight,
  53660. const bool flatOnTop,
  53661. const bool flatOnBottom) throw()
  53662. {
  53663. if (width <= outlineThickness || height <= outlineThickness)
  53664. return;
  53665. const int intX = (int) x;
  53666. const int intY = (int) y;
  53667. const int intW = (int) width;
  53668. const int intH = (int) height;
  53669. const float cs = cornerSize < 0 ? jmin (width * 0.5f, height * 0.5f) : cornerSize;
  53670. const float edgeBlurRadius = height * 0.75f + (height - cs * 2.0f);
  53671. const int intEdge = (int) edgeBlurRadius;
  53672. Path outline;
  53673. createRoundedPath (outline, x, y, width, height, cs,
  53674. ! (flatOnLeft || flatOnTop),
  53675. ! (flatOnRight || flatOnTop),
  53676. ! (flatOnLeft || flatOnBottom),
  53677. ! (flatOnRight || flatOnBottom));
  53678. {
  53679. ColourGradient cg (colour.darker (0.2f), 0, y,
  53680. colour.darker (0.2f), 0, y + height, false);
  53681. cg.addColour (0.03, colour.withMultipliedAlpha (0.3f));
  53682. cg.addColour (0.4, colour);
  53683. cg.addColour (0.97, colour.withMultipliedAlpha (0.3f));
  53684. g.setGradientFill (cg);
  53685. g.fillPath (outline);
  53686. }
  53687. ColourGradient cg (Colours::transparentBlack, x + edgeBlurRadius, y + height * 0.5f,
  53688. colour.darker (0.2f), x, y + height * 0.5f, true);
  53689. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.5f) / edgeBlurRadius), Colours::transparentBlack);
  53690. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.25f) / edgeBlurRadius), colour.darker (0.2f).withMultipliedAlpha (0.3f));
  53691. if (! (flatOnLeft || flatOnTop || flatOnBottom))
  53692. {
  53693. g.saveState();
  53694. g.setGradientFill (cg);
  53695. g.reduceClipRegion (intX, intY, intEdge, intH);
  53696. g.fillPath (outline);
  53697. g.restoreState();
  53698. }
  53699. if (! (flatOnRight || flatOnTop || flatOnBottom))
  53700. {
  53701. cg.point1.setX (x + width - edgeBlurRadius);
  53702. cg.point2.setX (x + width);
  53703. g.saveState();
  53704. g.setGradientFill (cg);
  53705. g.reduceClipRegion (intX + intW - intEdge, intY, 2 + intEdge, intH);
  53706. g.fillPath (outline);
  53707. g.restoreState();
  53708. }
  53709. {
  53710. const float leftIndent = flatOnLeft ? 0.0f : cs * 0.4f;
  53711. const float rightIndent = flatOnRight ? 0.0f : cs * 0.4f;
  53712. Path highlight;
  53713. createRoundedPath (highlight,
  53714. x + leftIndent,
  53715. y + cs * 0.1f,
  53716. width - (leftIndent + rightIndent),
  53717. height * 0.4f, cs * 0.4f,
  53718. ! (flatOnLeft || flatOnTop),
  53719. ! (flatOnRight || flatOnTop),
  53720. ! (flatOnLeft || flatOnBottom),
  53721. ! (flatOnRight || flatOnBottom));
  53722. g.setGradientFill (ColourGradient (colour.brighter (10.0f), 0, y + height * 0.06f,
  53723. Colours::transparentWhite, 0, y + height * 0.4f, false));
  53724. g.fillPath (highlight);
  53725. }
  53726. g.setColour (colour.darker().withMultipliedAlpha (1.5f));
  53727. g.strokePath (outline, PathStrokeType (outlineThickness));
  53728. }
  53729. END_JUCE_NAMESPACE
  53730. /*** End of inlined file: juce_LookAndFeel.cpp ***/
  53731. /*** Start of inlined file: juce_OldSchoolLookAndFeel.cpp ***/
  53732. BEGIN_JUCE_NAMESPACE
  53733. OldSchoolLookAndFeel::OldSchoolLookAndFeel()
  53734. {
  53735. setColour (TextButton::buttonColourId, Colour (0xffbbbbff));
  53736. setColour (ListBox::outlineColourId, findColour (ComboBox::outlineColourId));
  53737. setColour (ScrollBar::thumbColourId, Colour (0xffbbbbdd));
  53738. setColour (ScrollBar::backgroundColourId, Colours::transparentBlack);
  53739. setColour (Slider::thumbColourId, Colours::white);
  53740. setColour (Slider::trackColourId, Colour (0x7f000000));
  53741. setColour (Slider::textBoxOutlineColourId, Colours::grey);
  53742. setColour (ProgressBar::backgroundColourId, Colours::white.withAlpha (0.6f));
  53743. setColour (ProgressBar::foregroundColourId, Colours::green.withAlpha (0.7f));
  53744. setColour (PopupMenu::backgroundColourId, Colour (0xffeef5f8));
  53745. setColour (PopupMenu::highlightedBackgroundColourId, Colour (0xbfa4c2ce));
  53746. setColour (PopupMenu::highlightedTextColourId, Colours::black);
  53747. setColour (TextEditor::focusedOutlineColourId, findColour (TextButton::buttonColourId));
  53748. scrollbarShadow.setShadowProperties (2.2f, 0.5f, 0, 0);
  53749. }
  53750. OldSchoolLookAndFeel::~OldSchoolLookAndFeel()
  53751. {
  53752. }
  53753. void OldSchoolLookAndFeel::drawButtonBackground (Graphics& g,
  53754. Button& button,
  53755. const Colour& backgroundColour,
  53756. bool isMouseOverButton,
  53757. bool isButtonDown)
  53758. {
  53759. const int width = button.getWidth();
  53760. const int height = button.getHeight();
  53761. const float indent = 2.0f;
  53762. const int cornerSize = jmin (roundToInt (width * 0.4f),
  53763. roundToInt (height * 0.4f));
  53764. Path p;
  53765. p.addRoundedRectangle (indent, indent,
  53766. width - indent * 2.0f,
  53767. height - indent * 2.0f,
  53768. (float) cornerSize);
  53769. Colour bc (backgroundColour.withMultipliedSaturation (0.3f));
  53770. if (isMouseOverButton)
  53771. {
  53772. if (isButtonDown)
  53773. bc = bc.brighter();
  53774. else if (bc.getBrightness() > 0.5f)
  53775. bc = bc.darker (0.1f);
  53776. else
  53777. bc = bc.brighter (0.1f);
  53778. }
  53779. g.setColour (bc);
  53780. g.fillPath (p);
  53781. g.setColour (bc.contrasting().withAlpha ((isMouseOverButton) ? 0.6f : 0.4f));
  53782. g.strokePath (p, PathStrokeType ((isMouseOverButton) ? 2.0f : 1.4f));
  53783. }
  53784. void OldSchoolLookAndFeel::drawTickBox (Graphics& g,
  53785. Component& /*component*/,
  53786. float x, float y, float w, float h,
  53787. const bool ticked,
  53788. const bool isEnabled,
  53789. const bool /*isMouseOverButton*/,
  53790. const bool isButtonDown)
  53791. {
  53792. Path box;
  53793. box.addRoundedRectangle (0.0f, 2.0f, 6.0f, 6.0f, 1.0f);
  53794. g.setColour (isEnabled ? Colours::blue.withAlpha (isButtonDown ? 0.3f : 0.1f)
  53795. : Colours::lightgrey.withAlpha (0.1f));
  53796. AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f).translated (x, y));
  53797. g.fillPath (box, trans);
  53798. g.setColour (Colours::black.withAlpha (0.6f));
  53799. g.strokePath (box, PathStrokeType (0.9f), trans);
  53800. if (ticked)
  53801. {
  53802. Path tick;
  53803. tick.startNewSubPath (1.5f, 3.0f);
  53804. tick.lineTo (3.0f, 6.0f);
  53805. tick.lineTo (6.0f, 0.0f);
  53806. g.setColour (isEnabled ? Colours::black : Colours::grey);
  53807. g.strokePath (tick, PathStrokeType (2.5f), trans);
  53808. }
  53809. }
  53810. void OldSchoolLookAndFeel::drawToggleButton (Graphics& g,
  53811. ToggleButton& button,
  53812. bool isMouseOverButton,
  53813. bool isButtonDown)
  53814. {
  53815. if (button.hasKeyboardFocus (true))
  53816. {
  53817. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  53818. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  53819. }
  53820. const int tickWidth = jmin (20, button.getHeight() - 4);
  53821. drawTickBox (g, button, 4.0f, (button.getHeight() - tickWidth) * 0.5f,
  53822. (float) tickWidth, (float) tickWidth,
  53823. button.getToggleState(),
  53824. button.isEnabled(),
  53825. isMouseOverButton,
  53826. isButtonDown);
  53827. g.setColour (button.findColour (ToggleButton::textColourId));
  53828. g.setFont (jmin (15.0f, button.getHeight() * 0.6f));
  53829. if (! button.isEnabled())
  53830. g.setOpacity (0.5f);
  53831. const int textX = tickWidth + 5;
  53832. g.drawFittedText (button.getButtonText(),
  53833. textX, 4,
  53834. button.getWidth() - textX - 2, button.getHeight() - 8,
  53835. Justification::centredLeft, 10);
  53836. }
  53837. void OldSchoolLookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  53838. int width, int height,
  53839. double progress, const String& textToShow)
  53840. {
  53841. if (progress < 0 || progress >= 1.0)
  53842. {
  53843. LookAndFeel::drawProgressBar (g, progressBar, width, height, progress, textToShow);
  53844. }
  53845. else
  53846. {
  53847. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  53848. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  53849. g.fillAll (background);
  53850. g.setColour (foreground);
  53851. g.fillRect (1, 1,
  53852. jlimit (0, width - 2, roundToInt (progress * (width - 2))),
  53853. height - 2);
  53854. if (textToShow.isNotEmpty())
  53855. {
  53856. g.setColour (Colour::contrasting (background, foreground));
  53857. g.setFont (height * 0.6f);
  53858. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  53859. }
  53860. }
  53861. }
  53862. void OldSchoolLookAndFeel::drawScrollbarButton (Graphics& g,
  53863. ScrollBar& bar,
  53864. int width, int height,
  53865. int buttonDirection,
  53866. bool isScrollbarVertical,
  53867. bool isMouseOverButton,
  53868. bool isButtonDown)
  53869. {
  53870. if (isScrollbarVertical)
  53871. width -= 2;
  53872. else
  53873. height -= 2;
  53874. Path p;
  53875. if (buttonDirection == 0)
  53876. p.addTriangle (width * 0.5f, height * 0.2f,
  53877. width * 0.1f, height * 0.7f,
  53878. width * 0.9f, height * 0.7f);
  53879. else if (buttonDirection == 1)
  53880. p.addTriangle (width * 0.8f, height * 0.5f,
  53881. width * 0.3f, height * 0.1f,
  53882. width * 0.3f, height * 0.9f);
  53883. else if (buttonDirection == 2)
  53884. p.addTriangle (width * 0.5f, height * 0.8f,
  53885. width * 0.1f, height * 0.3f,
  53886. width * 0.9f, height * 0.3f);
  53887. else if (buttonDirection == 3)
  53888. p.addTriangle (width * 0.2f, height * 0.5f,
  53889. width * 0.7f, height * 0.1f,
  53890. width * 0.7f, height * 0.9f);
  53891. if (isButtonDown)
  53892. g.setColour (Colours::white);
  53893. else if (isMouseOverButton)
  53894. g.setColour (Colours::white.withAlpha (0.7f));
  53895. else
  53896. g.setColour (bar.findColour (ScrollBar::thumbColourId).withAlpha (0.5f));
  53897. g.fillPath (p);
  53898. g.setColour (Colours::black.withAlpha (0.5f));
  53899. g.strokePath (p, PathStrokeType (0.5f));
  53900. }
  53901. void OldSchoolLookAndFeel::drawScrollbar (Graphics& g,
  53902. ScrollBar& bar,
  53903. int x, int y,
  53904. int width, int height,
  53905. bool isScrollbarVertical,
  53906. int thumbStartPosition,
  53907. int thumbSize,
  53908. bool isMouseOver,
  53909. bool isMouseDown)
  53910. {
  53911. g.fillAll (bar.findColour (ScrollBar::backgroundColourId));
  53912. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  53913. .withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.15f));
  53914. if (thumbSize > 0.0f)
  53915. {
  53916. Rectangle<int> thumb;
  53917. if (isScrollbarVertical)
  53918. {
  53919. width -= 2;
  53920. g.fillRect (x + roundToInt (width * 0.35f), y,
  53921. roundToInt (width * 0.3f), height);
  53922. thumb.setBounds (x + 1, thumbStartPosition,
  53923. width - 2, thumbSize);
  53924. }
  53925. else
  53926. {
  53927. height -= 2;
  53928. g.fillRect (x, y + roundToInt (height * 0.35f),
  53929. width, roundToInt (height * 0.3f));
  53930. thumb.setBounds (thumbStartPosition, y + 1,
  53931. thumbSize, height - 2);
  53932. }
  53933. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  53934. .withAlpha ((isMouseOver || isMouseDown) ? 0.95f : 0.7f));
  53935. g.fillRect (thumb);
  53936. g.setColour (Colours::black.withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.25f));
  53937. g.drawRect (thumb.getX(), thumb.getY(), thumb.getWidth(), thumb.getHeight());
  53938. if (thumbSize > 16)
  53939. {
  53940. for (int i = 3; --i >= 0;)
  53941. {
  53942. const float linePos = thumbStartPosition + thumbSize / 2 + (i - 1) * 4.0f;
  53943. g.setColour (Colours::black.withAlpha (0.15f));
  53944. if (isScrollbarVertical)
  53945. {
  53946. g.drawLine (x + width * 0.2f, linePos, width * 0.8f, linePos);
  53947. g.setColour (Colours::white.withAlpha (0.15f));
  53948. g.drawLine (width * 0.2f, linePos - 1, width * 0.8f, linePos - 1);
  53949. }
  53950. else
  53951. {
  53952. g.drawLine (linePos, height * 0.2f, linePos, height * 0.8f);
  53953. g.setColour (Colours::white.withAlpha (0.15f));
  53954. g.drawLine (linePos - 1, height * 0.2f, linePos - 1, height * 0.8f);
  53955. }
  53956. }
  53957. }
  53958. }
  53959. }
  53960. ImageEffectFilter* OldSchoolLookAndFeel::getScrollbarEffect()
  53961. {
  53962. return &scrollbarShadow;
  53963. }
  53964. void OldSchoolLookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  53965. {
  53966. g.fillAll (findColour (PopupMenu::backgroundColourId));
  53967. g.setColour (Colours::black.withAlpha (0.6f));
  53968. g.drawRect (0, 0, width, height);
  53969. }
  53970. void OldSchoolLookAndFeel::drawMenuBarBackground (Graphics& g, int /*width*/, int /*height*/,
  53971. bool, MenuBarComponent& menuBar)
  53972. {
  53973. g.fillAll (menuBar.findColour (PopupMenu::backgroundColourId));
  53974. }
  53975. void OldSchoolLookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  53976. {
  53977. if (textEditor.isEnabled())
  53978. {
  53979. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  53980. g.drawRect (0, 0, width, height);
  53981. }
  53982. }
  53983. void OldSchoolLookAndFeel::drawComboBox (Graphics& g, int width, int height,
  53984. const bool isButtonDown,
  53985. int buttonX, int buttonY,
  53986. int buttonW, int buttonH,
  53987. ComboBox& box)
  53988. {
  53989. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  53990. g.setColour (box.findColour ((isButtonDown) ? ComboBox::buttonColourId
  53991. : ComboBox::backgroundColourId));
  53992. g.fillRect (buttonX, buttonY, buttonW, buttonH);
  53993. g.setColour (box.findColour (ComboBox::outlineColourId));
  53994. g.drawRect (0, 0, width, height);
  53995. const float arrowX = 0.2f;
  53996. const float arrowH = 0.3f;
  53997. if (box.isEnabled())
  53998. {
  53999. Path p;
  54000. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  54001. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  54002. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  54003. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  54004. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  54005. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  54006. g.setColour (box.findColour ((isButtonDown) ? ComboBox::backgroundColourId
  54007. : ComboBox::buttonColourId));
  54008. g.fillPath (p);
  54009. }
  54010. }
  54011. const Font OldSchoolLookAndFeel::getComboBoxFont (ComboBox& box)
  54012. {
  54013. Font f (jmin (15.0f, box.getHeight() * 0.85f));
  54014. f.setHorizontalScale (0.9f);
  54015. return f;
  54016. }
  54017. static void drawTriangle (Graphics& g, float x1, float y1, float x2, float y2, float x3, float y3, const Colour& fill, const Colour& outline) throw()
  54018. {
  54019. Path p;
  54020. p.addTriangle (x1, y1, x2, y2, x3, y3);
  54021. g.setColour (fill);
  54022. g.fillPath (p);
  54023. g.setColour (outline);
  54024. g.strokePath (p, PathStrokeType (0.3f));
  54025. }
  54026. void OldSchoolLookAndFeel::drawLinearSlider (Graphics& g,
  54027. int x, int y,
  54028. int w, int h,
  54029. float sliderPos,
  54030. float minSliderPos,
  54031. float maxSliderPos,
  54032. const Slider::SliderStyle style,
  54033. Slider& slider)
  54034. {
  54035. g.fillAll (slider.findColour (Slider::backgroundColourId));
  54036. if (style == Slider::LinearBar)
  54037. {
  54038. g.setColour (slider.findColour (Slider::thumbColourId));
  54039. g.fillRect (x, y, (int) sliderPos - x, h);
  54040. g.setColour (slider.findColour (Slider::textBoxTextColourId).withMultipliedAlpha (0.5f));
  54041. g.drawRect (x, y, (int) sliderPos - x, h);
  54042. }
  54043. else
  54044. {
  54045. g.setColour (slider.findColour (Slider::trackColourId)
  54046. .withMultipliedAlpha (slider.isEnabled() ? 1.0f : 0.3f));
  54047. if (slider.isHorizontal())
  54048. {
  54049. g.fillRect (x, y + roundToInt (h * 0.6f),
  54050. w, roundToInt (h * 0.2f));
  54051. }
  54052. else
  54053. {
  54054. g.fillRect (x + roundToInt (w * 0.5f - jmin (3.0f, w * 0.1f)), y,
  54055. jmin (4, roundToInt (w * 0.2f)), h);
  54056. }
  54057. float alpha = 0.35f;
  54058. if (slider.isEnabled())
  54059. alpha = slider.isMouseOverOrDragging() ? 1.0f : 0.7f;
  54060. const Colour fill (slider.findColour (Slider::thumbColourId).withAlpha (alpha));
  54061. const Colour outline (Colours::black.withAlpha (slider.isEnabled() ? 0.7f : 0.35f));
  54062. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  54063. {
  54064. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), minSliderPos,
  54065. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos - 7.0f,
  54066. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos,
  54067. fill, outline);
  54068. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), maxSliderPos,
  54069. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos,
  54070. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos + 7.0f,
  54071. fill, outline);
  54072. }
  54073. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  54074. {
  54075. drawTriangle (g, minSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  54076. minSliderPos - 7.0f, y + h * 0.9f ,
  54077. minSliderPos, y + h * 0.9f,
  54078. fill, outline);
  54079. drawTriangle (g, maxSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  54080. maxSliderPos, y + h * 0.9f,
  54081. maxSliderPos + 7.0f, y + h * 0.9f,
  54082. fill, outline);
  54083. }
  54084. if (style == Slider::LinearHorizontal || style == Slider::ThreeValueHorizontal)
  54085. {
  54086. drawTriangle (g, sliderPos, y + h * 0.9f,
  54087. sliderPos - 7.0f, y + h * 0.2f,
  54088. sliderPos + 7.0f, y + h * 0.2f,
  54089. fill, outline);
  54090. }
  54091. else if (style == Slider::LinearVertical || style == Slider::ThreeValueVertical)
  54092. {
  54093. drawTriangle (g, x + w * 0.5f - jmin (4.0f, w * 0.3f), sliderPos,
  54094. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos - 7.0f,
  54095. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos + 7.0f,
  54096. fill, outline);
  54097. }
  54098. }
  54099. }
  54100. Button* OldSchoolLookAndFeel::createSliderButton (const bool isIncrement)
  54101. {
  54102. if (isIncrement)
  54103. return new ArrowButton ("u", 0.75f, Colours::white.withAlpha (0.8f));
  54104. else
  54105. return new ArrowButton ("d", 0.25f, Colours::white.withAlpha (0.8f));
  54106. }
  54107. ImageEffectFilter* OldSchoolLookAndFeel::getSliderEffect()
  54108. {
  54109. return &scrollbarShadow;
  54110. }
  54111. int OldSchoolLookAndFeel::getSliderThumbRadius (Slider&)
  54112. {
  54113. return 8;
  54114. }
  54115. void OldSchoolLookAndFeel::drawCornerResizer (Graphics& g,
  54116. int w, int h,
  54117. bool isMouseOver,
  54118. bool isMouseDragging)
  54119. {
  54120. g.setColour ((isMouseOver || isMouseDragging) ? Colours::lightgrey
  54121. : Colours::darkgrey);
  54122. const float lineThickness = jmin (w, h) * 0.1f;
  54123. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  54124. {
  54125. g.drawLine (w * i,
  54126. h + 1.0f,
  54127. w + 1.0f,
  54128. h * i,
  54129. lineThickness);
  54130. }
  54131. }
  54132. Button* OldSchoolLookAndFeel::createDocumentWindowButton (int buttonType)
  54133. {
  54134. Path shape;
  54135. if (buttonType == DocumentWindow::closeButton)
  54136. {
  54137. shape.addLineSegment (Line<float> (0.0f, 0.0f, 1.0f, 1.0f), 0.35f);
  54138. shape.addLineSegment (Line<float> (1.0f, 0.0f, 0.0f, 1.0f), 0.35f);
  54139. ShapeButton* const b = new ShapeButton ("close",
  54140. Colour (0x7fff3333),
  54141. Colour (0xd7ff3333),
  54142. Colour (0xf7ff3333));
  54143. b->setShape (shape, true, true, true);
  54144. return b;
  54145. }
  54146. else if (buttonType == DocumentWindow::minimiseButton)
  54147. {
  54148. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), 0.25f);
  54149. DrawableButton* b = new DrawableButton ("minimise", DrawableButton::ImageFitted);
  54150. DrawablePath dp;
  54151. dp.setPath (shape);
  54152. dp.setFill (Colours::black.withAlpha (0.3f));
  54153. b->setImages (&dp);
  54154. return b;
  54155. }
  54156. else if (buttonType == DocumentWindow::maximiseButton)
  54157. {
  54158. shape.addLineSegment (Line<float> (0.5f, 0.0f, 0.5f, 1.0f), 0.25f);
  54159. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), 0.25f);
  54160. DrawableButton* b = new DrawableButton ("maximise", DrawableButton::ImageFitted);
  54161. DrawablePath dp;
  54162. dp.setPath (shape);
  54163. dp.setFill (Colours::black.withAlpha (0.3f));
  54164. b->setImages (&dp);
  54165. return b;
  54166. }
  54167. jassertfalse;
  54168. return 0;
  54169. }
  54170. void OldSchoolLookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  54171. int titleBarX,
  54172. int titleBarY,
  54173. int titleBarW,
  54174. int titleBarH,
  54175. Button* minimiseButton,
  54176. Button* maximiseButton,
  54177. Button* closeButton,
  54178. bool positionTitleBarButtonsOnLeft)
  54179. {
  54180. titleBarY += titleBarH / 8;
  54181. titleBarH -= titleBarH / 4;
  54182. const int buttonW = titleBarH;
  54183. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  54184. : titleBarX + titleBarW - buttonW - 4;
  54185. if (closeButton != 0)
  54186. {
  54187. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  54188. x += positionTitleBarButtonsOnLeft ? buttonW + buttonW / 5
  54189. : -(buttonW + buttonW / 5);
  54190. }
  54191. if (positionTitleBarButtonsOnLeft)
  54192. swapVariables (minimiseButton, maximiseButton);
  54193. if (maximiseButton != 0)
  54194. {
  54195. maximiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  54196. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  54197. }
  54198. if (minimiseButton != 0)
  54199. minimiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  54200. }
  54201. END_JUCE_NAMESPACE
  54202. /*** End of inlined file: juce_OldSchoolLookAndFeel.cpp ***/
  54203. /*** Start of inlined file: juce_MenuBarComponent.cpp ***/
  54204. BEGIN_JUCE_NAMESPACE
  54205. class DummyMenuComponent : public Component
  54206. {
  54207. DummyMenuComponent (const DummyMenuComponent&);
  54208. DummyMenuComponent& operator= (const DummyMenuComponent&);
  54209. public:
  54210. DummyMenuComponent() {}
  54211. ~DummyMenuComponent() {}
  54212. void inputAttemptWhenModal()
  54213. {
  54214. exitModalState (0);
  54215. }
  54216. };
  54217. MenuBarComponent::MenuBarComponent (MenuBarModel* model_)
  54218. : model (0),
  54219. itemUnderMouse (-1),
  54220. currentPopupIndex (-1),
  54221. indexToShowAgain (-1),
  54222. lastMouseX (0),
  54223. lastMouseY (0),
  54224. inModalState (false)
  54225. {
  54226. setRepaintsOnMouseActivity (true);
  54227. setWantsKeyboardFocus (false);
  54228. setMouseClickGrabsKeyboardFocus (false);
  54229. setModel (model_);
  54230. }
  54231. MenuBarComponent::~MenuBarComponent()
  54232. {
  54233. setModel (0);
  54234. Desktop::getInstance().removeGlobalMouseListener (this);
  54235. currentPopup = 0;
  54236. }
  54237. void MenuBarComponent::setModel (MenuBarModel* const newModel)
  54238. {
  54239. if (model != newModel)
  54240. {
  54241. if (model != 0)
  54242. model->removeListener (this);
  54243. model = newModel;
  54244. if (model != 0)
  54245. model->addListener (this);
  54246. repaint();
  54247. menuBarItemsChanged (0);
  54248. }
  54249. }
  54250. void MenuBarComponent::paint (Graphics& g)
  54251. {
  54252. const bool isMouseOverBar = currentPopupIndex >= 0 || itemUnderMouse >= 0 || isMouseOver();
  54253. getLookAndFeel().drawMenuBarBackground (g,
  54254. getWidth(),
  54255. getHeight(),
  54256. isMouseOverBar,
  54257. *this);
  54258. if (model != 0)
  54259. {
  54260. for (int i = 0; i < menuNames.size(); ++i)
  54261. {
  54262. g.saveState();
  54263. g.setOrigin (xPositions [i], 0);
  54264. g.reduceClipRegion (0, 0, xPositions[i + 1] - xPositions[i], getHeight());
  54265. getLookAndFeel().drawMenuBarItem (g,
  54266. xPositions[i + 1] - xPositions[i],
  54267. getHeight(),
  54268. i,
  54269. menuNames[i],
  54270. i == itemUnderMouse,
  54271. i == currentPopupIndex,
  54272. isMouseOverBar,
  54273. *this);
  54274. g.restoreState();
  54275. }
  54276. }
  54277. }
  54278. void MenuBarComponent::resized()
  54279. {
  54280. xPositions.clear();
  54281. int x = 2;
  54282. xPositions.add (x);
  54283. for (int i = 0; i < menuNames.size(); ++i)
  54284. {
  54285. x += getLookAndFeel().getMenuBarItemWidth (*this, i, menuNames[i]);
  54286. xPositions.add (x);
  54287. }
  54288. }
  54289. int MenuBarComponent::getItemAt (const int x, const int y)
  54290. {
  54291. for (int i = 0; i < xPositions.size(); ++i)
  54292. if (x >= xPositions[i] && x < xPositions[i + 1])
  54293. return reallyContains (x, y, true) ? i : -1;
  54294. return -1;
  54295. }
  54296. void MenuBarComponent::repaintMenuItem (int index)
  54297. {
  54298. if (((unsigned int) index) < (unsigned int) xPositions.size())
  54299. {
  54300. const int x1 = xPositions [index];
  54301. const int x2 = xPositions [index + 1];
  54302. repaint (x1 - 2, 0, x2 - x1 + 4, getHeight());
  54303. }
  54304. }
  54305. void MenuBarComponent::updateItemUnderMouse (int x, int y)
  54306. {
  54307. const int newItem = getItemAt (x, y);
  54308. if (itemUnderMouse != newItem)
  54309. {
  54310. repaintMenuItem (itemUnderMouse);
  54311. itemUnderMouse = newItem;
  54312. repaintMenuItem (itemUnderMouse);
  54313. }
  54314. }
  54315. void MenuBarComponent::hideCurrentMenu()
  54316. {
  54317. currentPopup = 0;
  54318. repaint();
  54319. }
  54320. void MenuBarComponent::showMenu (int index)
  54321. {
  54322. if (index != currentPopupIndex)
  54323. {
  54324. if (inModalState)
  54325. {
  54326. hideCurrentMenu();
  54327. indexToShowAgain = index;
  54328. return;
  54329. }
  54330. indexToShowAgain = -1;
  54331. currentPopupIndex = -1;
  54332. itemUnderMouse = index;
  54333. currentPopup = 0;
  54334. menuBarItemsChanged (0);
  54335. Component::SafePointer<Component> prevFocused (getCurrentlyFocusedComponent());
  54336. Component::SafePointer<Component> deletionChecker (this);
  54337. enterModalState (false);
  54338. inModalState = true;
  54339. int result = 0;
  54340. ApplicationCommandManager* managerOfChosenCommand = 0;
  54341. Desktop::getInstance().addGlobalMouseListener (this);
  54342. for (;;)
  54343. {
  54344. const int x = getScreenX() + xPositions [itemUnderMouse];
  54345. const int w = xPositions [itemUnderMouse + 1] - xPositions [itemUnderMouse];
  54346. currentPopupIndex = itemUnderMouse;
  54347. indexToShowAgain = -1;
  54348. repaint();
  54349. if (((unsigned int) itemUnderMouse) < (unsigned int) menuNames.size())
  54350. {
  54351. PopupMenu m (model->getMenuForIndex (itemUnderMouse,
  54352. menuNames [itemUnderMouse]));
  54353. if (m.lookAndFeel == 0)
  54354. m.setLookAndFeel (&getLookAndFeel());
  54355. currentPopup = m.createMenuComponent (x, getScreenY(),
  54356. w, getHeight(),
  54357. 0, w, 0, 0,
  54358. true, this,
  54359. &managerOfChosenCommand,
  54360. this);
  54361. }
  54362. if (currentPopup == 0)
  54363. {
  54364. currentPopup = new DummyMenuComponent();
  54365. addAndMakeVisible (currentPopup);
  54366. }
  54367. currentPopup->enterModalState (false);
  54368. currentPopup->toFront (false); // need to do this after making it modal, or it could
  54369. // be stuck behind other comps that are already modal..
  54370. result = currentPopup->runModalLoop();
  54371. if (deletionChecker == 0)
  54372. return;
  54373. const int lastPopupIndex = currentPopupIndex;
  54374. currentPopup = 0;
  54375. currentPopupIndex = -1;
  54376. if (result != 0)
  54377. {
  54378. topLevelIndexClicked = lastPopupIndex;
  54379. break;
  54380. }
  54381. else if (indexToShowAgain >= 0)
  54382. {
  54383. menuBarItemsChanged (0);
  54384. repaint();
  54385. itemUnderMouse = indexToShowAgain;
  54386. if (((unsigned int) itemUnderMouse) >= (unsigned int) menuNames.size())
  54387. break;
  54388. }
  54389. else
  54390. {
  54391. break;
  54392. }
  54393. }
  54394. Desktop::getInstance().removeGlobalMouseListener (this);
  54395. inModalState = false;
  54396. exitModalState (0);
  54397. if (prevFocused != 0)
  54398. prevFocused->grabKeyboardFocus();
  54399. const Point<int> mousePos (getMouseXYRelative());
  54400. updateItemUnderMouse (mousePos.getX(), mousePos.getY());
  54401. repaint();
  54402. if (result != 0)
  54403. {
  54404. if (managerOfChosenCommand != 0)
  54405. {
  54406. ApplicationCommandTarget::InvocationInfo info (result);
  54407. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  54408. managerOfChosenCommand->invoke (info, true);
  54409. }
  54410. postCommandMessage (result);
  54411. }
  54412. }
  54413. }
  54414. void MenuBarComponent::handleCommandMessage (int commandId)
  54415. {
  54416. if (model != 0)
  54417. model->menuItemSelected (commandId, topLevelIndexClicked);
  54418. }
  54419. void MenuBarComponent::mouseEnter (const MouseEvent& e)
  54420. {
  54421. if (e.eventComponent == this)
  54422. updateItemUnderMouse (e.x, e.y);
  54423. }
  54424. void MenuBarComponent::mouseExit (const MouseEvent& e)
  54425. {
  54426. if (e.eventComponent == this)
  54427. updateItemUnderMouse (e.x, e.y);
  54428. }
  54429. void MenuBarComponent::mouseDown (const MouseEvent& e)
  54430. {
  54431. if (currentPopupIndex < 0)
  54432. {
  54433. const MouseEvent e2 (e.getEventRelativeTo (this));
  54434. updateItemUnderMouse (e2.x, e2.y);
  54435. currentPopupIndex = -2;
  54436. showMenu (itemUnderMouse);
  54437. }
  54438. }
  54439. void MenuBarComponent::mouseDrag (const MouseEvent& e)
  54440. {
  54441. const MouseEvent e2 (e.getEventRelativeTo (this));
  54442. const int item = getItemAt (e2.x, e2.y);
  54443. if (item >= 0)
  54444. showMenu (item);
  54445. }
  54446. void MenuBarComponent::mouseUp (const MouseEvent& e)
  54447. {
  54448. const MouseEvent e2 (e.getEventRelativeTo (this));
  54449. updateItemUnderMouse (e2.x, e2.y);
  54450. if (itemUnderMouse < 0 && dynamic_cast <DummyMenuComponent*> (static_cast <Component*> (currentPopup)) != 0)
  54451. hideCurrentMenu();
  54452. }
  54453. void MenuBarComponent::mouseMove (const MouseEvent& e)
  54454. {
  54455. const MouseEvent e2 (e.getEventRelativeTo (this));
  54456. if (lastMouseX != e2.x || lastMouseY != e2.y)
  54457. {
  54458. if (currentPopupIndex >= 0)
  54459. {
  54460. const int item = getItemAt (e2.x, e2.y);
  54461. if (item >= 0)
  54462. showMenu (item);
  54463. }
  54464. else
  54465. {
  54466. updateItemUnderMouse (e2.x, e2.y);
  54467. }
  54468. lastMouseX = e2.x;
  54469. lastMouseY = e2.y;
  54470. }
  54471. }
  54472. bool MenuBarComponent::keyPressed (const KeyPress& key)
  54473. {
  54474. bool used = false;
  54475. const int numMenus = menuNames.size();
  54476. const int currentIndex = jlimit (0, menuNames.size() - 1, currentPopupIndex);
  54477. if (key.isKeyCode (KeyPress::leftKey))
  54478. {
  54479. showMenu ((currentIndex + numMenus - 1) % numMenus);
  54480. used = true;
  54481. }
  54482. else if (key.isKeyCode (KeyPress::rightKey))
  54483. {
  54484. showMenu ((currentIndex + 1) % numMenus);
  54485. used = true;
  54486. }
  54487. return used;
  54488. }
  54489. void MenuBarComponent::inputAttemptWhenModal()
  54490. {
  54491. hideCurrentMenu();
  54492. }
  54493. void MenuBarComponent::menuBarItemsChanged (MenuBarModel* /*menuBarModel*/)
  54494. {
  54495. StringArray newNames;
  54496. if (model != 0)
  54497. newNames = model->getMenuBarNames();
  54498. if (newNames != menuNames)
  54499. {
  54500. menuNames = newNames;
  54501. repaint();
  54502. resized();
  54503. }
  54504. }
  54505. void MenuBarComponent::menuCommandInvoked (MenuBarModel* /*menuBarModel*/,
  54506. const ApplicationCommandTarget::InvocationInfo& info)
  54507. {
  54508. if (model == 0
  54509. || (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) != 0)
  54510. return;
  54511. for (int i = 0; i < menuNames.size(); ++i)
  54512. {
  54513. const PopupMenu menu (model->getMenuForIndex (i, menuNames [i]));
  54514. if (menu.containsCommandItem (info.commandID))
  54515. {
  54516. itemUnderMouse = i;
  54517. repaintMenuItem (i);
  54518. startTimer (200);
  54519. break;
  54520. }
  54521. }
  54522. }
  54523. void MenuBarComponent::timerCallback()
  54524. {
  54525. stopTimer();
  54526. const Point<int> mousePos (getMouseXYRelative());
  54527. updateItemUnderMouse (mousePos.getX(), mousePos.getY());
  54528. }
  54529. END_JUCE_NAMESPACE
  54530. /*** End of inlined file: juce_MenuBarComponent.cpp ***/
  54531. /*** Start of inlined file: juce_MenuBarModel.cpp ***/
  54532. BEGIN_JUCE_NAMESPACE
  54533. MenuBarModel::MenuBarModel() throw()
  54534. : manager (0)
  54535. {
  54536. }
  54537. MenuBarModel::~MenuBarModel()
  54538. {
  54539. setApplicationCommandManagerToWatch (0);
  54540. }
  54541. void MenuBarModel::menuItemsChanged()
  54542. {
  54543. triggerAsyncUpdate();
  54544. }
  54545. void MenuBarModel::setApplicationCommandManagerToWatch (ApplicationCommandManager* const newManager) throw()
  54546. {
  54547. if (manager != newManager)
  54548. {
  54549. if (manager != 0)
  54550. manager->removeListener (this);
  54551. manager = newManager;
  54552. if (manager != 0)
  54553. manager->addListener (this);
  54554. }
  54555. }
  54556. void MenuBarModel::addListener (MenuBarModelListener* const newListener) throw()
  54557. {
  54558. listeners.add (newListener);
  54559. }
  54560. void MenuBarModel::removeListener (MenuBarModelListener* const listenerToRemove) throw()
  54561. {
  54562. // Trying to remove a listener that isn't on the list!
  54563. // If this assertion happens because this object is a dangling pointer, make sure you've not
  54564. // deleted this menu model while it's still being used by something (e.g. by a MenuBarComponent)
  54565. jassert (listeners.contains (listenerToRemove));
  54566. listeners.remove (listenerToRemove);
  54567. }
  54568. void MenuBarModel::handleAsyncUpdate()
  54569. {
  54570. listeners.call (&MenuBarModelListener::menuBarItemsChanged, this);
  54571. }
  54572. void MenuBarModel::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  54573. {
  54574. listeners.call (&MenuBarModelListener::menuCommandInvoked, this, info);
  54575. }
  54576. void MenuBarModel::applicationCommandListChanged()
  54577. {
  54578. menuItemsChanged();
  54579. }
  54580. END_JUCE_NAMESPACE
  54581. /*** End of inlined file: juce_MenuBarModel.cpp ***/
  54582. /*** Start of inlined file: juce_PopupMenu.cpp ***/
  54583. BEGIN_JUCE_NAMESPACE
  54584. class PopupMenu::Item
  54585. {
  54586. public:
  54587. Item()
  54588. : itemId (0), active (true), isSeparator (true), isTicked (false),
  54589. usesColour (false), customComp (0), commandManager (0)
  54590. {
  54591. }
  54592. Item (const int itemId_,
  54593. const String& text_,
  54594. const bool active_,
  54595. const bool isTicked_,
  54596. const Image& im,
  54597. const Colour& textColour_,
  54598. const bool usesColour_,
  54599. PopupMenuCustomComponent* const customComp_,
  54600. const PopupMenu* const subMenu_,
  54601. ApplicationCommandManager* const commandManager_)
  54602. : itemId (itemId_), text (text_), textColour (textColour_),
  54603. active (active_), isSeparator (false), isTicked (isTicked_),
  54604. usesColour (usesColour_), image (im), customComp (customComp_),
  54605. commandManager (commandManager_)
  54606. {
  54607. if (subMenu_ != 0)
  54608. subMenu = new PopupMenu (*subMenu_);
  54609. if (commandManager_ != 0 && itemId_ != 0)
  54610. {
  54611. String shortcutKey;
  54612. Array <KeyPress> keyPresses (commandManager_->getKeyMappings()
  54613. ->getKeyPressesAssignedToCommand (itemId_));
  54614. for (int i = 0; i < keyPresses.size(); ++i)
  54615. {
  54616. const String key (keyPresses.getReference(i).getTextDescription());
  54617. if (shortcutKey.isNotEmpty())
  54618. shortcutKey << ", ";
  54619. if (key.length() == 1)
  54620. shortcutKey << "shortcut: '" << key << '\'';
  54621. else
  54622. shortcutKey << key;
  54623. }
  54624. shortcutKey = shortcutKey.trim();
  54625. if (shortcutKey.isNotEmpty())
  54626. text << "<end>" << shortcutKey;
  54627. }
  54628. }
  54629. Item (const Item& other)
  54630. : itemId (other.itemId),
  54631. text (other.text),
  54632. textColour (other.textColour),
  54633. active (other.active),
  54634. isSeparator (other.isSeparator),
  54635. isTicked (other.isTicked),
  54636. usesColour (other.usesColour),
  54637. image (other.image),
  54638. customComp (other.customComp),
  54639. commandManager (other.commandManager)
  54640. {
  54641. if (other.subMenu != 0)
  54642. subMenu = new PopupMenu (*(other.subMenu));
  54643. }
  54644. ~Item()
  54645. {
  54646. customComp = 0;
  54647. }
  54648. bool canBeTriggered() const throw()
  54649. {
  54650. return active && ! (isSeparator || (subMenu != 0));
  54651. }
  54652. bool hasActiveSubMenu() const throw()
  54653. {
  54654. return active && (subMenu != 0);
  54655. }
  54656. const int itemId;
  54657. String text;
  54658. const Colour textColour;
  54659. const bool active, isSeparator, isTicked, usesColour;
  54660. Image image;
  54661. ReferenceCountedObjectPtr <PopupMenuCustomComponent> customComp;
  54662. ScopedPointer <PopupMenu> subMenu;
  54663. ApplicationCommandManager* const commandManager;
  54664. juce_UseDebuggingNewOperator
  54665. private:
  54666. Item& operator= (const Item&);
  54667. };
  54668. class PopupMenu::ItemComponent : public Component
  54669. {
  54670. public:
  54671. ItemComponent (const PopupMenu::Item& itemInfo_)
  54672. : itemInfo (itemInfo_),
  54673. isHighlighted (false)
  54674. {
  54675. if (itemInfo.customComp != 0)
  54676. addAndMakeVisible (itemInfo.customComp);
  54677. }
  54678. ~ItemComponent()
  54679. {
  54680. if (itemInfo.customComp != 0)
  54681. removeChildComponent (itemInfo.customComp);
  54682. }
  54683. void getIdealSize (int& idealWidth,
  54684. int& idealHeight,
  54685. const int standardItemHeight)
  54686. {
  54687. if (itemInfo.customComp != 0)
  54688. {
  54689. itemInfo.customComp->getIdealSize (idealWidth, idealHeight);
  54690. }
  54691. else
  54692. {
  54693. getLookAndFeel().getIdealPopupMenuItemSize (itemInfo.text,
  54694. itemInfo.isSeparator,
  54695. standardItemHeight,
  54696. idealWidth,
  54697. idealHeight);
  54698. }
  54699. }
  54700. void paint (Graphics& g)
  54701. {
  54702. if (itemInfo.customComp == 0)
  54703. {
  54704. String mainText (itemInfo.text);
  54705. String endText;
  54706. const int endIndex = mainText.indexOf ("<end>");
  54707. if (endIndex >= 0)
  54708. {
  54709. endText = mainText.substring (endIndex + 5).trim();
  54710. mainText = mainText.substring (0, endIndex);
  54711. }
  54712. getLookAndFeel()
  54713. .drawPopupMenuItem (g, getWidth(), getHeight(),
  54714. itemInfo.isSeparator,
  54715. itemInfo.active,
  54716. isHighlighted,
  54717. itemInfo.isTicked,
  54718. itemInfo.subMenu != 0,
  54719. mainText, endText,
  54720. itemInfo.image.isValid() ? &itemInfo.image : 0,
  54721. itemInfo.usesColour ? &(itemInfo.textColour) : 0);
  54722. }
  54723. }
  54724. void resized()
  54725. {
  54726. if (getNumChildComponents() > 0)
  54727. getChildComponent(0)->setBounds (2, 0, getWidth() - 4, getHeight());
  54728. }
  54729. void setHighlighted (bool shouldBeHighlighted)
  54730. {
  54731. shouldBeHighlighted = shouldBeHighlighted && itemInfo.active;
  54732. if (isHighlighted != shouldBeHighlighted)
  54733. {
  54734. isHighlighted = shouldBeHighlighted;
  54735. if (itemInfo.customComp != 0)
  54736. {
  54737. itemInfo.customComp->isHighlighted = shouldBeHighlighted;
  54738. itemInfo.customComp->repaint();
  54739. }
  54740. repaint();
  54741. }
  54742. }
  54743. PopupMenu::Item itemInfo;
  54744. juce_UseDebuggingNewOperator
  54745. private:
  54746. bool isHighlighted;
  54747. ItemComponent (const ItemComponent&);
  54748. ItemComponent& operator= (const ItemComponent&);
  54749. };
  54750. namespace PopupMenuSettings
  54751. {
  54752. static const int scrollZone = 24;
  54753. static const int borderSize = 2;
  54754. static const int timerInterval = 50;
  54755. static const int dismissCommandId = 0x6287345f;
  54756. }
  54757. class PopupMenu::Window : public Component,
  54758. private Timer
  54759. {
  54760. public:
  54761. Window()
  54762. : Component ("menu"),
  54763. owner (0),
  54764. currentChild (0),
  54765. activeSubMenu (0),
  54766. menuBarComponent (0),
  54767. managerOfChosenCommand (0),
  54768. minimumWidth (0),
  54769. maximumNumColumns (7),
  54770. standardItemHeight (0),
  54771. isOver (false),
  54772. hasBeenOver (false),
  54773. isDown (false),
  54774. needsToScroll (false),
  54775. hideOnExit (false),
  54776. disableMouseMoves (false),
  54777. hasAnyJuceCompHadFocus (false),
  54778. numColumns (0),
  54779. contentHeight (0),
  54780. childYOffset (0),
  54781. timeEnteredCurrentChildComp (0),
  54782. scrollAcceleration (1.0)
  54783. {
  54784. menuCreationTime = lastFocused = lastScroll = Time::getMillisecondCounter();
  54785. setWantsKeyboardFocus (true);
  54786. setMouseClickGrabsKeyboardFocus (false);
  54787. setOpaque (true);
  54788. setAlwaysOnTop (true);
  54789. Desktop::getInstance().addGlobalMouseListener (this);
  54790. getActiveWindows().add (this);
  54791. }
  54792. ~Window()
  54793. {
  54794. getActiveWindows().removeValue (this);
  54795. Desktop::getInstance().removeGlobalMouseListener (this);
  54796. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  54797. activeSubMenu = 0;
  54798. deleteAllChildren();
  54799. }
  54800. static Window* create (const PopupMenu& menu,
  54801. const bool dismissOnMouseUp,
  54802. Window* const owner_,
  54803. const int minX, const int maxX,
  54804. const int minY, const int maxY,
  54805. const int minimumWidth,
  54806. const int maximumNumColumns,
  54807. const int standardItemHeight,
  54808. const bool alignToRectangle,
  54809. const int itemIdThatMustBeVisible,
  54810. Component* const menuBarComponent,
  54811. ApplicationCommandManager** managerOfChosenCommand,
  54812. Component* const componentAttachedTo)
  54813. {
  54814. if (menu.items.size() > 0)
  54815. {
  54816. int totalItems = 0;
  54817. ScopedPointer <Window> mw (new Window());
  54818. mw->setLookAndFeel (menu.lookAndFeel);
  54819. mw->setWantsKeyboardFocus (false);
  54820. mw->minimumWidth = minimumWidth;
  54821. mw->maximumNumColumns = maximumNumColumns;
  54822. mw->standardItemHeight = standardItemHeight;
  54823. mw->dismissOnMouseUp = dismissOnMouseUp;
  54824. for (int i = 0; i < menu.items.size(); ++i)
  54825. {
  54826. PopupMenu::Item* const item = menu.items.getUnchecked(i);
  54827. mw->addItem (*item);
  54828. ++totalItems;
  54829. }
  54830. if (totalItems > 0)
  54831. {
  54832. mw->owner = owner_;
  54833. mw->menuBarComponent = menuBarComponent;
  54834. mw->managerOfChosenCommand = managerOfChosenCommand;
  54835. mw->componentAttachedTo = componentAttachedTo;
  54836. mw->componentAttachedToOriginal = componentAttachedTo;
  54837. mw->calculateWindowPos (minX, maxX, minY, maxY, alignToRectangle);
  54838. mw->setTopLeftPosition (mw->windowPos.getX(),
  54839. mw->windowPos.getY());
  54840. mw->updateYPositions();
  54841. if (itemIdThatMustBeVisible != 0)
  54842. {
  54843. const int y = minY - mw->windowPos.getY();
  54844. mw->ensureItemIsVisible (itemIdThatMustBeVisible,
  54845. (((unsigned int) y) < (unsigned int) mw->windowPos.getHeight()) ? y : -1);
  54846. }
  54847. mw->resizeToBestWindowPos();
  54848. mw->addToDesktop (ComponentPeer::windowIsTemporary
  54849. | mw->getLookAndFeel().getMenuWindowFlags());
  54850. return mw.release();
  54851. }
  54852. }
  54853. return 0;
  54854. }
  54855. void paint (Graphics& g)
  54856. {
  54857. getLookAndFeel().drawPopupMenuBackground (g, getWidth(), getHeight());
  54858. }
  54859. void paintOverChildren (Graphics& g)
  54860. {
  54861. if (isScrolling())
  54862. {
  54863. LookAndFeel& lf = getLookAndFeel();
  54864. if (isScrollZoneActive (false))
  54865. lf.drawPopupMenuUpDownArrow (g, getWidth(), PopupMenuSettings::scrollZone, true);
  54866. if (isScrollZoneActive (true))
  54867. {
  54868. g.setOrigin (0, getHeight() - PopupMenuSettings::scrollZone);
  54869. lf.drawPopupMenuUpDownArrow (g, getWidth(), PopupMenuSettings::scrollZone, false);
  54870. }
  54871. }
  54872. }
  54873. bool isScrollZoneActive (bool bottomOne) const
  54874. {
  54875. return isScrolling()
  54876. && (bottomOne
  54877. ? childYOffset < contentHeight - windowPos.getHeight()
  54878. : childYOffset > 0);
  54879. }
  54880. void addItem (const PopupMenu::Item& item)
  54881. {
  54882. PopupMenu::ItemComponent* const mic = new PopupMenu::ItemComponent (item);
  54883. addAndMakeVisible (mic);
  54884. int itemW = 80;
  54885. int itemH = 16;
  54886. mic->getIdealSize (itemW, itemH, standardItemHeight);
  54887. mic->setSize (itemW, jlimit (2, 600, itemH));
  54888. mic->addMouseListener (this, false);
  54889. }
  54890. // hide this and all sub-comps
  54891. void hide (const PopupMenu::Item* const item)
  54892. {
  54893. if (isVisible())
  54894. {
  54895. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  54896. activeSubMenu = 0;
  54897. currentChild = 0;
  54898. exitModalState (item != 0 ? item->itemId : 0);
  54899. setVisible (false);
  54900. if (item != 0
  54901. && item->commandManager != 0
  54902. && item->itemId != 0)
  54903. {
  54904. *managerOfChosenCommand = item->commandManager;
  54905. }
  54906. }
  54907. }
  54908. void dismissMenu (const PopupMenu::Item* const item)
  54909. {
  54910. if (owner != 0)
  54911. {
  54912. owner->dismissMenu (item);
  54913. }
  54914. else
  54915. {
  54916. if (item != 0)
  54917. {
  54918. // need a copy of this on the stack as the one passed in will get deleted during this call
  54919. const PopupMenu::Item mi (*item);
  54920. hide (&mi);
  54921. }
  54922. else
  54923. {
  54924. hide (0);
  54925. }
  54926. }
  54927. }
  54928. void mouseMove (const MouseEvent&)
  54929. {
  54930. timerCallback();
  54931. }
  54932. void mouseDown (const MouseEvent&)
  54933. {
  54934. timerCallback();
  54935. }
  54936. void mouseDrag (const MouseEvent&)
  54937. {
  54938. timerCallback();
  54939. }
  54940. void mouseUp (const MouseEvent&)
  54941. {
  54942. timerCallback();
  54943. }
  54944. void mouseWheelMove (const MouseEvent&, float /*amountX*/, float amountY)
  54945. {
  54946. alterChildYPos (roundToInt (-10.0f * amountY * PopupMenuSettings::scrollZone));
  54947. lastMouse = Point<int> (-1, -1);
  54948. }
  54949. bool keyPressed (const KeyPress& key)
  54950. {
  54951. if (key.isKeyCode (KeyPress::downKey))
  54952. {
  54953. selectNextItem (1);
  54954. }
  54955. else if (key.isKeyCode (KeyPress::upKey))
  54956. {
  54957. selectNextItem (-1);
  54958. }
  54959. else if (key.isKeyCode (KeyPress::leftKey))
  54960. {
  54961. if (owner != 0)
  54962. {
  54963. Component::SafePointer<Window> parentWindow (owner);
  54964. PopupMenu::ItemComponent* currentChildOfParent = parentWindow->currentChild;
  54965. hide (0);
  54966. if (parentWindow != 0)
  54967. parentWindow->setCurrentlyHighlightedChild (currentChildOfParent);
  54968. disableTimerUntilMouseMoves();
  54969. }
  54970. else if (menuBarComponent != 0)
  54971. {
  54972. menuBarComponent->keyPressed (key);
  54973. }
  54974. }
  54975. else if (key.isKeyCode (KeyPress::rightKey))
  54976. {
  54977. disableTimerUntilMouseMoves();
  54978. if (showSubMenuFor (currentChild))
  54979. {
  54980. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  54981. if (activeSubMenu != 0 && activeSubMenu->isVisible())
  54982. activeSubMenu->selectNextItem (1);
  54983. }
  54984. else if (menuBarComponent != 0)
  54985. {
  54986. menuBarComponent->keyPressed (key);
  54987. }
  54988. }
  54989. else if (key.isKeyCode (KeyPress::returnKey))
  54990. {
  54991. triggerCurrentlyHighlightedItem();
  54992. }
  54993. else if (key.isKeyCode (KeyPress::escapeKey))
  54994. {
  54995. dismissMenu (0);
  54996. }
  54997. else
  54998. {
  54999. return false;
  55000. }
  55001. return true;
  55002. }
  55003. void inputAttemptWhenModal()
  55004. {
  55005. Component::SafePointer<Component> deletionChecker (this);
  55006. timerCallback();
  55007. if (deletionChecker != 0 && ! isOverAnyMenu())
  55008. {
  55009. if (componentAttachedTo != 0)
  55010. {
  55011. // we want to dismiss the menu, but if we do it synchronously, then
  55012. // the mouse-click will be allowed to pass through. That's good, except
  55013. // when the user clicks on the button that orginally popped the menu up,
  55014. // as they'll expect the menu to go away, and in fact it'll just
  55015. // come back. So only dismiss synchronously if they're not on the original
  55016. // comp that we're attached to.
  55017. const Point<int> mousePos (componentAttachedTo->getMouseXYRelative());
  55018. if (componentAttachedTo->reallyContains (mousePos.getX(), mousePos.getY(), true))
  55019. {
  55020. postCommandMessage (PopupMenuSettings::dismissCommandId); // dismiss asynchrounously
  55021. return;
  55022. }
  55023. }
  55024. dismissMenu (0);
  55025. }
  55026. }
  55027. void handleCommandMessage (int commandId)
  55028. {
  55029. Component::handleCommandMessage (commandId);
  55030. if (commandId == PopupMenuSettings::dismissCommandId)
  55031. dismissMenu (0);
  55032. }
  55033. void timerCallback()
  55034. {
  55035. if (! isVisible())
  55036. return;
  55037. if (componentAttachedTo != componentAttachedToOriginal)
  55038. {
  55039. dismissMenu (0);
  55040. return;
  55041. }
  55042. Window* currentlyModalWindow = dynamic_cast <Window*> (Component::getCurrentlyModalComponent());
  55043. if (currentlyModalWindow != 0 && ! treeContains (currentlyModalWindow))
  55044. return;
  55045. startTimer (PopupMenuSettings::timerInterval); // do this in case it was called from a mouse
  55046. // move rather than a real timer callback
  55047. const Point<int> globalMousePos (Desktop::getMousePosition());
  55048. const Point<int> localMousePos (globalPositionToRelative (globalMousePos));
  55049. const uint32 now = Time::getMillisecondCounter();
  55050. if (now > timeEnteredCurrentChildComp + 100
  55051. && reallyContains (localMousePos.getX(), localMousePos.getY(), true)
  55052. && currentChild->isValidComponent()
  55053. && (! disableMouseMoves)
  55054. && ! (activeSubMenu != 0 && activeSubMenu->isVisible()))
  55055. {
  55056. showSubMenuFor (currentChild);
  55057. }
  55058. if (globalMousePos != lastMouse || now > lastMouseMoveTime + 350)
  55059. {
  55060. highlightItemUnderMouse (globalMousePos, localMousePos);
  55061. }
  55062. bool overScrollArea = false;
  55063. if (isScrolling()
  55064. && (isOver || (isDown && ((unsigned int) localMousePos.getX()) < (unsigned int) getWidth()))
  55065. && ((isScrollZoneActive (false) && localMousePos.getY() < PopupMenuSettings::scrollZone)
  55066. || (isScrollZoneActive (true) && localMousePos.getY() > getHeight() - PopupMenuSettings::scrollZone)))
  55067. {
  55068. if (now > lastScroll + 20)
  55069. {
  55070. scrollAcceleration = jmin (4.0, scrollAcceleration * 1.04);
  55071. int amount = 0;
  55072. for (int i = 0; i < getNumChildComponents() && amount == 0; ++i)
  55073. amount = ((int) scrollAcceleration) * getChildComponent (i)->getHeight();
  55074. alterChildYPos (localMousePos.getY() < PopupMenuSettings::scrollZone ? -amount : amount);
  55075. lastScroll = now;
  55076. }
  55077. overScrollArea = true;
  55078. lastMouse = Point<int> (-1, -1); // trigger a mouse-move
  55079. }
  55080. else
  55081. {
  55082. scrollAcceleration = 1.0;
  55083. }
  55084. const bool wasDown = isDown;
  55085. bool isOverAny = isOverAnyMenu();
  55086. if (hideOnExit && hasBeenOver && (! isOverAny) && activeSubMenu != 0)
  55087. {
  55088. activeSubMenu->updateMouseOverStatus (globalMousePos);
  55089. isOverAny = isOverAnyMenu();
  55090. }
  55091. if (hideOnExit && hasBeenOver && ! isOverAny)
  55092. {
  55093. hide (0);
  55094. }
  55095. else
  55096. {
  55097. isDown = hasBeenOver
  55098. && (ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown()
  55099. || ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown());
  55100. bool anyFocused = Process::isForegroundProcess();
  55101. if (anyFocused && Component::getCurrentlyFocusedComponent() == 0)
  55102. {
  55103. // because no component at all may have focus, our test here will
  55104. // only be triggered when something has focus and then loses it.
  55105. anyFocused = ! hasAnyJuceCompHadFocus;
  55106. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  55107. {
  55108. if (ComponentPeer::getPeer (i)->isFocused())
  55109. {
  55110. anyFocused = true;
  55111. hasAnyJuceCompHadFocus = true;
  55112. break;
  55113. }
  55114. }
  55115. }
  55116. if (! anyFocused)
  55117. {
  55118. if (now > lastFocused + 10)
  55119. {
  55120. wasHiddenBecauseOfAppChange() = true;
  55121. dismissMenu (0);
  55122. return; // may have been deleted by the previous call..
  55123. }
  55124. }
  55125. else if (wasDown && now > menuCreationTime + 250
  55126. && ! (isDown || overScrollArea))
  55127. {
  55128. isOver = reallyContains (localMousePos.getX(), localMousePos.getY(), true);
  55129. if (isOver)
  55130. {
  55131. triggerCurrentlyHighlightedItem();
  55132. }
  55133. else if ((hasBeenOver || ! dismissOnMouseUp) && ! isOverAny)
  55134. {
  55135. dismissMenu (0);
  55136. }
  55137. return; // may have been deleted by the previous calls..
  55138. }
  55139. else
  55140. {
  55141. lastFocused = now;
  55142. }
  55143. }
  55144. }
  55145. static Array<Window*>& getActiveWindows()
  55146. {
  55147. static Array<Window*> activeMenuWindows;
  55148. return activeMenuWindows;
  55149. }
  55150. static bool& wasHiddenBecauseOfAppChange() throw()
  55151. {
  55152. static bool b = false;
  55153. return b;
  55154. }
  55155. juce_UseDebuggingNewOperator
  55156. private:
  55157. Window* owner;
  55158. PopupMenu::ItemComponent* currentChild;
  55159. ScopedPointer <Window> activeSubMenu;
  55160. Component* menuBarComponent;
  55161. ApplicationCommandManager** managerOfChosenCommand;
  55162. Component::SafePointer<Component> componentAttachedTo;
  55163. Component* componentAttachedToOriginal;
  55164. Rectangle<int> windowPos;
  55165. Point<int> lastMouse;
  55166. int minimumWidth, maximumNumColumns, standardItemHeight;
  55167. bool isOver, hasBeenOver, isDown, needsToScroll;
  55168. bool dismissOnMouseUp, hideOnExit, disableMouseMoves, hasAnyJuceCompHadFocus;
  55169. int numColumns, contentHeight, childYOffset;
  55170. Array <int> columnWidths;
  55171. uint32 menuCreationTime, lastFocused, lastScroll, lastMouseMoveTime, timeEnteredCurrentChildComp;
  55172. double scrollAcceleration;
  55173. bool overlaps (const Rectangle<int>& r) const
  55174. {
  55175. return r.intersects (getBounds())
  55176. || (owner != 0 && owner->overlaps (r));
  55177. }
  55178. bool isOverAnyMenu() const
  55179. {
  55180. return (owner != 0) ? owner->isOverAnyMenu()
  55181. : isOverChildren();
  55182. }
  55183. bool isOverChildren() const
  55184. {
  55185. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  55186. return isVisible()
  55187. && (isOver || (activeSubMenu != 0 && activeSubMenu->isOverChildren()));
  55188. }
  55189. void updateMouseOverStatus (const Point<int>& globalMousePos)
  55190. {
  55191. const Point<int> relPos (globalPositionToRelative (globalMousePos));
  55192. isOver = reallyContains (relPos.getX(), relPos.getY(), true);
  55193. if (activeSubMenu != 0)
  55194. activeSubMenu->updateMouseOverStatus (globalMousePos);
  55195. }
  55196. bool treeContains (const Window* const window) const throw()
  55197. {
  55198. const Window* mw = this;
  55199. while (mw->owner != 0)
  55200. mw = mw->owner;
  55201. while (mw != 0)
  55202. {
  55203. if (mw == window)
  55204. return true;
  55205. mw = mw->activeSubMenu;
  55206. }
  55207. return false;
  55208. }
  55209. void calculateWindowPos (const int minX, const int maxX,
  55210. const int minY, const int maxY,
  55211. const bool alignToRectangle)
  55212. {
  55213. const Rectangle<int> mon (Desktop::getInstance()
  55214. .getMonitorAreaContaining (Point<int> ((minX + maxX) / 2,
  55215. (minY + maxY) / 2),
  55216. #if JUCE_MAC
  55217. true));
  55218. #else
  55219. false)); // on windows, don't stop the menu overlapping the taskbar
  55220. #endif
  55221. int x, y, widthToUse, heightToUse;
  55222. layoutMenuItems (mon.getWidth() - 24, widthToUse, heightToUse);
  55223. if (alignToRectangle)
  55224. {
  55225. x = minX;
  55226. const int spaceUnder = mon.getHeight() - (maxY - mon.getY());
  55227. const int spaceOver = minY - mon.getY();
  55228. if (heightToUse < spaceUnder - 30 || spaceUnder >= spaceOver)
  55229. y = maxY;
  55230. else
  55231. y = minY - heightToUse;
  55232. }
  55233. else
  55234. {
  55235. bool tendTowardsRight = (minX + maxX) / 2 < mon.getCentreX();
  55236. if (owner != 0)
  55237. {
  55238. if (owner->owner != 0)
  55239. {
  55240. const bool ownerGoingRight = (owner->getX() + owner->getWidth() / 2
  55241. > owner->owner->getX() + owner->owner->getWidth() / 2);
  55242. if (ownerGoingRight && maxX + widthToUse < mon.getRight() - 4)
  55243. tendTowardsRight = true;
  55244. else if ((! ownerGoingRight) && minX > widthToUse + 4)
  55245. tendTowardsRight = false;
  55246. }
  55247. else if (maxX + widthToUse < mon.getRight() - 32)
  55248. {
  55249. tendTowardsRight = true;
  55250. }
  55251. }
  55252. const int biggestSpace = jmax (mon.getRight() - maxX,
  55253. minX - mon.getX()) - 32;
  55254. if (biggestSpace < widthToUse)
  55255. {
  55256. layoutMenuItems (biggestSpace + (maxX - minX) / 3, widthToUse, heightToUse);
  55257. if (numColumns > 1)
  55258. layoutMenuItems (biggestSpace - 4, widthToUse, heightToUse);
  55259. tendTowardsRight = (mon.getRight() - maxX) >= (minX - mon.getX());
  55260. }
  55261. if (tendTowardsRight)
  55262. x = jmin (mon.getRight() - widthToUse - 4, maxX);
  55263. else
  55264. x = jmax (mon.getX() + 4, minX - widthToUse);
  55265. y = minY;
  55266. if ((minY + maxY) / 2 > mon.getCentreY())
  55267. y = jmax (mon.getY(), maxY - heightToUse);
  55268. }
  55269. x = jmax (mon.getX() + 1, jmin (mon.getRight() - (widthToUse + 6), x));
  55270. y = jmax (mon.getY() + 1, jmin (mon.getBottom() - (heightToUse + 6), y));
  55271. windowPos.setBounds (x, y, widthToUse, heightToUse);
  55272. // sets this flag if it's big enough to obscure any of its parent menus
  55273. hideOnExit = (owner != 0)
  55274. && owner->windowPos.intersects (windowPos.expanded (-4, -4));
  55275. }
  55276. void layoutMenuItems (const int maxMenuW, int& width, int& height)
  55277. {
  55278. numColumns = 0;
  55279. contentHeight = 0;
  55280. const int maxMenuH = getParentHeight() - 24;
  55281. int totalW;
  55282. do
  55283. {
  55284. ++numColumns;
  55285. totalW = workOutBestSize (maxMenuW);
  55286. if (totalW > maxMenuW)
  55287. {
  55288. numColumns = jmax (1, numColumns - 1);
  55289. totalW = workOutBestSize (maxMenuW); // to update col widths
  55290. break;
  55291. }
  55292. else if (totalW > maxMenuW / 2 || contentHeight < maxMenuH)
  55293. {
  55294. break;
  55295. }
  55296. } while (numColumns < maximumNumColumns);
  55297. const int actualH = jmin (contentHeight, maxMenuH);
  55298. needsToScroll = contentHeight > actualH;
  55299. width = updateYPositions();
  55300. height = actualH + PopupMenuSettings::borderSize * 2;
  55301. }
  55302. int workOutBestSize (const int maxMenuW)
  55303. {
  55304. int totalW = 0;
  55305. contentHeight = 0;
  55306. int childNum = 0;
  55307. for (int col = 0; col < numColumns; ++col)
  55308. {
  55309. int i, colW = 50, colH = 0;
  55310. const int numChildren = jmin (getNumChildComponents() - childNum,
  55311. (getNumChildComponents() + numColumns - 1) / numColumns);
  55312. for (i = numChildren; --i >= 0;)
  55313. {
  55314. colW = jmax (colW, getChildComponent (childNum + i)->getWidth());
  55315. colH += getChildComponent (childNum + i)->getHeight();
  55316. }
  55317. colW = jmin (maxMenuW / jmax (1, numColumns - 2), colW + PopupMenuSettings::borderSize * 2);
  55318. columnWidths.set (col, colW);
  55319. totalW += colW;
  55320. contentHeight = jmax (contentHeight, colH);
  55321. childNum += numChildren;
  55322. }
  55323. if (totalW < minimumWidth)
  55324. {
  55325. totalW = minimumWidth;
  55326. for (int col = 0; col < numColumns; ++col)
  55327. columnWidths.set (0, totalW / numColumns);
  55328. }
  55329. return totalW;
  55330. }
  55331. void ensureItemIsVisible (const int itemId, int wantedY)
  55332. {
  55333. jassert (itemId != 0)
  55334. for (int i = getNumChildComponents(); --i >= 0;)
  55335. {
  55336. PopupMenu::ItemComponent* const m = static_cast <PopupMenu::ItemComponent*> (getChildComponent (i));
  55337. if (m != 0
  55338. && m->itemInfo.itemId == itemId
  55339. && windowPos.getHeight() > PopupMenuSettings::scrollZone * 4)
  55340. {
  55341. const int currentY = m->getY();
  55342. if (wantedY > 0 || currentY < 0 || m->getBottom() > windowPos.getHeight())
  55343. {
  55344. if (wantedY < 0)
  55345. wantedY = jlimit (PopupMenuSettings::scrollZone,
  55346. jmax (PopupMenuSettings::scrollZone,
  55347. windowPos.getHeight() - (PopupMenuSettings::scrollZone + m->getHeight())),
  55348. currentY);
  55349. const Rectangle<int> mon (Desktop::getInstance().getMonitorAreaContaining (windowPos.getPosition(), true));
  55350. int deltaY = wantedY - currentY;
  55351. windowPos.setSize (jmin (windowPos.getWidth(), mon.getWidth()),
  55352. jmin (windowPos.getHeight(), mon.getHeight()));
  55353. const int newY = jlimit (mon.getY(),
  55354. mon.getBottom() - windowPos.getHeight(),
  55355. windowPos.getY() + deltaY);
  55356. deltaY -= newY - windowPos.getY();
  55357. childYOffset -= deltaY;
  55358. windowPos.setPosition (windowPos.getX(), newY);
  55359. updateYPositions();
  55360. }
  55361. break;
  55362. }
  55363. }
  55364. }
  55365. void resizeToBestWindowPos()
  55366. {
  55367. Rectangle<int> r (windowPos);
  55368. if (childYOffset < 0)
  55369. {
  55370. r.setBounds (r.getX(), r.getY() - childYOffset,
  55371. r.getWidth(), r.getHeight() + childYOffset);
  55372. }
  55373. else if (childYOffset > 0)
  55374. {
  55375. const int spaceAtBottom = r.getHeight() - (contentHeight - childYOffset);
  55376. if (spaceAtBottom > 0)
  55377. r.setSize (r.getWidth(), r.getHeight() - spaceAtBottom);
  55378. }
  55379. setBounds (r);
  55380. updateYPositions();
  55381. }
  55382. void alterChildYPos (const int delta)
  55383. {
  55384. if (isScrolling())
  55385. {
  55386. childYOffset += delta;
  55387. if (delta < 0)
  55388. {
  55389. childYOffset = jmax (childYOffset, 0);
  55390. }
  55391. else if (delta > 0)
  55392. {
  55393. childYOffset = jmin (childYOffset,
  55394. contentHeight - windowPos.getHeight() + PopupMenuSettings::borderSize);
  55395. }
  55396. updateYPositions();
  55397. }
  55398. else
  55399. {
  55400. childYOffset = 0;
  55401. }
  55402. resizeToBestWindowPos();
  55403. repaint();
  55404. }
  55405. int updateYPositions()
  55406. {
  55407. int x = 0;
  55408. int childNum = 0;
  55409. for (int col = 0; col < numColumns; ++col)
  55410. {
  55411. const int numChildren = jmin (getNumChildComponents() - childNum,
  55412. (getNumChildComponents() + numColumns - 1) / numColumns);
  55413. const int colW = columnWidths [col];
  55414. int y = PopupMenuSettings::borderSize - (childYOffset + (getY() - windowPos.getY()));
  55415. for (int i = 0; i < numChildren; ++i)
  55416. {
  55417. Component* const c = getChildComponent (childNum + i);
  55418. c->setBounds (x, y, colW, c->getHeight());
  55419. y += c->getHeight();
  55420. }
  55421. x += colW;
  55422. childNum += numChildren;
  55423. }
  55424. return x;
  55425. }
  55426. bool isScrolling() const throw()
  55427. {
  55428. return childYOffset != 0 || needsToScroll;
  55429. }
  55430. void setCurrentlyHighlightedChild (PopupMenu::ItemComponent* const child)
  55431. {
  55432. if (currentChild->isValidComponent())
  55433. currentChild->setHighlighted (false);
  55434. currentChild = child;
  55435. if (currentChild != 0)
  55436. {
  55437. currentChild->setHighlighted (true);
  55438. timeEnteredCurrentChildComp = Time::getApproximateMillisecondCounter();
  55439. }
  55440. }
  55441. bool showSubMenuFor (PopupMenu::ItemComponent* const childComp)
  55442. {
  55443. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  55444. activeSubMenu = 0;
  55445. if (childComp->isValidComponent() && childComp->itemInfo.hasActiveSubMenu())
  55446. {
  55447. const Point<int> topLeft (childComp->relativePositionToGlobal (Point<int>()));
  55448. const Point<int> bottomRight (childComp->relativePositionToGlobal (Point<int> (childComp->getWidth(), childComp->getHeight())));
  55449. activeSubMenu = Window::create (*(childComp->itemInfo.subMenu),
  55450. dismissOnMouseUp,
  55451. this,
  55452. topLeft.getX(), bottomRight.getX(), topLeft.getY(), bottomRight.getY(),
  55453. 0, maximumNumColumns,
  55454. standardItemHeight,
  55455. false, 0, menuBarComponent,
  55456. managerOfChosenCommand,
  55457. componentAttachedTo);
  55458. if (activeSubMenu != 0)
  55459. {
  55460. activeSubMenu->setVisible (true);
  55461. activeSubMenu->enterModalState (false);
  55462. activeSubMenu->toFront (false);
  55463. return true;
  55464. }
  55465. }
  55466. return false;
  55467. }
  55468. void highlightItemUnderMouse (const Point<int>& globalMousePos, const Point<int>& localMousePos)
  55469. {
  55470. isOver = reallyContains (localMousePos.getX(), localMousePos.getY(), true);
  55471. if (isOver)
  55472. hasBeenOver = true;
  55473. if (lastMouse.getDistanceFrom (globalMousePos) > 2)
  55474. {
  55475. lastMouseMoveTime = Time::getApproximateMillisecondCounter();
  55476. if (disableMouseMoves && isOver)
  55477. disableMouseMoves = false;
  55478. }
  55479. if (disableMouseMoves || (activeSubMenu != 0 && activeSubMenu->isOverChildren()))
  55480. return;
  55481. bool isMovingTowardsMenu = false;
  55482. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent())
  55483. if (isOver && (activeSubMenu != 0) && globalMousePos != lastMouse)
  55484. {
  55485. // try to intelligently guess whether the user is moving the mouse towards a currently-open
  55486. // submenu. To do this, look at whether the mouse stays inside a triangular region that
  55487. // extends from the last mouse pos to the submenu's rectangle..
  55488. float subX = (float) activeSubMenu->getScreenX();
  55489. if (activeSubMenu->getX() > getX())
  55490. {
  55491. lastMouse -= Point<int> (2, 0); // to enlarge the triangle a bit, in case the mouse only moves a couple of pixels
  55492. }
  55493. else
  55494. {
  55495. lastMouse += Point<int> (2, 0);
  55496. subX += activeSubMenu->getWidth();
  55497. }
  55498. Path areaTowardsSubMenu;
  55499. areaTowardsSubMenu.addTriangle ((float) lastMouse.getX(),
  55500. (float) lastMouse.getY(),
  55501. subX,
  55502. (float) activeSubMenu->getScreenY(),
  55503. subX,
  55504. (float) (activeSubMenu->getScreenY() + activeSubMenu->getHeight()));
  55505. isMovingTowardsMenu = areaTowardsSubMenu.contains ((float) globalMousePos.getX(), (float) globalMousePos.getY());
  55506. }
  55507. lastMouse = globalMousePos;
  55508. if (! isMovingTowardsMenu)
  55509. {
  55510. Component* c = getComponentAt (localMousePos.getX(), localMousePos.getY());
  55511. if (c == this)
  55512. c = 0;
  55513. PopupMenu::ItemComponent* mic = dynamic_cast <PopupMenu::ItemComponent*> (c);
  55514. if (mic == 0 && c != 0)
  55515. mic = c->findParentComponentOfClass ((PopupMenu::ItemComponent*) 0);
  55516. if (mic != currentChild
  55517. && (isOver || (activeSubMenu == 0) || ! activeSubMenu->isVisible()))
  55518. {
  55519. if (isOver && (c != 0) && (activeSubMenu != 0))
  55520. {
  55521. activeSubMenu->hide (0);
  55522. }
  55523. if (! isOver)
  55524. mic = 0;
  55525. setCurrentlyHighlightedChild (mic);
  55526. }
  55527. }
  55528. }
  55529. void triggerCurrentlyHighlightedItem()
  55530. {
  55531. if (currentChild->isValidComponent()
  55532. && currentChild->itemInfo.canBeTriggered()
  55533. && (currentChild->itemInfo.customComp == 0
  55534. || currentChild->itemInfo.customComp->isTriggeredAutomatically))
  55535. {
  55536. dismissMenu (&currentChild->itemInfo);
  55537. }
  55538. }
  55539. void selectNextItem (const int delta)
  55540. {
  55541. disableTimerUntilMouseMoves();
  55542. PopupMenu::ItemComponent* mic = 0;
  55543. bool wasLastOne = (currentChild == 0);
  55544. const int numItems = getNumChildComponents();
  55545. for (int i = 0; i < numItems + 1; ++i)
  55546. {
  55547. int index = (delta > 0) ? i : (numItems - 1 - i);
  55548. index = (index + numItems) % numItems;
  55549. mic = dynamic_cast <PopupMenu::ItemComponent*> (getChildComponent (index));
  55550. if (mic != 0 && (mic->itemInfo.canBeTriggered() || mic->itemInfo.hasActiveSubMenu())
  55551. && wasLastOne)
  55552. break;
  55553. if (mic == currentChild)
  55554. wasLastOne = true;
  55555. }
  55556. setCurrentlyHighlightedChild (mic);
  55557. }
  55558. void disableTimerUntilMouseMoves()
  55559. {
  55560. disableMouseMoves = true;
  55561. if (owner != 0)
  55562. owner->disableTimerUntilMouseMoves();
  55563. }
  55564. Window (const Window&);
  55565. Window& operator= (const Window&);
  55566. };
  55567. PopupMenu::PopupMenu()
  55568. : lookAndFeel (0),
  55569. separatorPending (false)
  55570. {
  55571. }
  55572. PopupMenu::PopupMenu (const PopupMenu& other)
  55573. : lookAndFeel (other.lookAndFeel),
  55574. separatorPending (false)
  55575. {
  55576. items.addCopiesOf (other.items);
  55577. }
  55578. PopupMenu& PopupMenu::operator= (const PopupMenu& other)
  55579. {
  55580. if (this != &other)
  55581. {
  55582. lookAndFeel = other.lookAndFeel;
  55583. clear();
  55584. items.addCopiesOf (other.items);
  55585. }
  55586. return *this;
  55587. }
  55588. PopupMenu::~PopupMenu()
  55589. {
  55590. clear();
  55591. }
  55592. void PopupMenu::clear()
  55593. {
  55594. items.clear();
  55595. separatorPending = false;
  55596. }
  55597. void PopupMenu::addSeparatorIfPending()
  55598. {
  55599. if (separatorPending)
  55600. {
  55601. separatorPending = false;
  55602. if (items.size() > 0)
  55603. items.add (new Item());
  55604. }
  55605. }
  55606. void PopupMenu::addItem (const int itemResultId,
  55607. const String& itemText,
  55608. const bool isActive,
  55609. const bool isTicked,
  55610. const Image& iconToUse)
  55611. {
  55612. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  55613. // didn't pick anything, so you shouldn't use it as the id
  55614. // for an item..
  55615. addSeparatorIfPending();
  55616. items.add (new Item (itemResultId, itemText, isActive, isTicked, iconToUse,
  55617. Colours::black, false, 0, 0, 0));
  55618. }
  55619. void PopupMenu::addCommandItem (ApplicationCommandManager* commandManager,
  55620. const int commandID,
  55621. const String& displayName)
  55622. {
  55623. jassert (commandManager != 0 && commandID != 0);
  55624. const ApplicationCommandInfo* const registeredInfo = commandManager->getCommandForID (commandID);
  55625. if (registeredInfo != 0)
  55626. {
  55627. ApplicationCommandInfo info (*registeredInfo);
  55628. ApplicationCommandTarget* const target = commandManager->getTargetForCommand (commandID, info);
  55629. addSeparatorIfPending();
  55630. items.add (new Item (commandID,
  55631. displayName.isNotEmpty() ? displayName
  55632. : info.shortName,
  55633. target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0,
  55634. (info.flags & ApplicationCommandInfo::isTicked) != 0,
  55635. Image(),
  55636. Colours::black,
  55637. false,
  55638. 0, 0,
  55639. commandManager));
  55640. }
  55641. }
  55642. void PopupMenu::addColouredItem (const int itemResultId,
  55643. const String& itemText,
  55644. const Colour& itemTextColour,
  55645. const bool isActive,
  55646. const bool isTicked,
  55647. const Image& iconToUse)
  55648. {
  55649. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  55650. // didn't pick anything, so you shouldn't use it as the id
  55651. // for an item..
  55652. addSeparatorIfPending();
  55653. items.add (new Item (itemResultId, itemText, isActive, isTicked, iconToUse,
  55654. itemTextColour, true, 0, 0, 0));
  55655. }
  55656. void PopupMenu::addCustomItem (const int itemResultId,
  55657. PopupMenuCustomComponent* const customComponent)
  55658. {
  55659. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  55660. // didn't pick anything, so you shouldn't use it as the id
  55661. // for an item..
  55662. addSeparatorIfPending();
  55663. items.add (new Item (itemResultId, String::empty, true, false, Image(),
  55664. Colours::black, false, customComponent, 0, 0));
  55665. }
  55666. class NormalComponentWrapper : public PopupMenuCustomComponent
  55667. {
  55668. public:
  55669. NormalComponentWrapper (Component* const comp,
  55670. const int w, const int h,
  55671. const bool triggerMenuItemAutomaticallyWhenClicked)
  55672. : PopupMenuCustomComponent (triggerMenuItemAutomaticallyWhenClicked),
  55673. width (w),
  55674. height (h)
  55675. {
  55676. addAndMakeVisible (comp);
  55677. }
  55678. ~NormalComponentWrapper() {}
  55679. void getIdealSize (int& idealWidth, int& idealHeight)
  55680. {
  55681. idealWidth = width;
  55682. idealHeight = height;
  55683. }
  55684. void resized()
  55685. {
  55686. if (getChildComponent(0) != 0)
  55687. getChildComponent(0)->setBounds (0, 0, getWidth(), getHeight());
  55688. }
  55689. juce_UseDebuggingNewOperator
  55690. private:
  55691. const int width, height;
  55692. NormalComponentWrapper (const NormalComponentWrapper&);
  55693. NormalComponentWrapper& operator= (const NormalComponentWrapper&);
  55694. };
  55695. void PopupMenu::addCustomItem (const int itemResultId,
  55696. Component* customComponent,
  55697. int idealWidth, int idealHeight,
  55698. const bool triggerMenuItemAutomaticallyWhenClicked)
  55699. {
  55700. addCustomItem (itemResultId,
  55701. new NormalComponentWrapper (customComponent,
  55702. idealWidth, idealHeight,
  55703. triggerMenuItemAutomaticallyWhenClicked));
  55704. }
  55705. void PopupMenu::addSubMenu (const String& subMenuName,
  55706. const PopupMenu& subMenu,
  55707. const bool isActive,
  55708. const Image& iconToUse,
  55709. const bool isTicked)
  55710. {
  55711. addSeparatorIfPending();
  55712. items.add (new Item (0, subMenuName, isActive && (subMenu.getNumItems() > 0), isTicked,
  55713. iconToUse, Colours::black, false, 0, &subMenu, 0));
  55714. }
  55715. void PopupMenu::addSeparator()
  55716. {
  55717. separatorPending = true;
  55718. }
  55719. class HeaderItemComponent : public PopupMenuCustomComponent
  55720. {
  55721. public:
  55722. HeaderItemComponent (const String& name)
  55723. : PopupMenuCustomComponent (false)
  55724. {
  55725. setName (name);
  55726. }
  55727. ~HeaderItemComponent()
  55728. {
  55729. }
  55730. void paint (Graphics& g)
  55731. {
  55732. Font f (getLookAndFeel().getPopupMenuFont());
  55733. f.setBold (true);
  55734. g.setFont (f);
  55735. g.setColour (findColour (PopupMenu::headerTextColourId));
  55736. g.drawFittedText (getName(),
  55737. 12, 0, getWidth() - 16, proportionOfHeight (0.8f),
  55738. Justification::bottomLeft, 1);
  55739. }
  55740. void getIdealSize (int& idealWidth,
  55741. int& idealHeight)
  55742. {
  55743. getLookAndFeel().getIdealPopupMenuItemSize (getName(), false, -1, idealWidth, idealHeight);
  55744. idealHeight += idealHeight / 2;
  55745. idealWidth += idealWidth / 4;
  55746. }
  55747. juce_UseDebuggingNewOperator
  55748. };
  55749. void PopupMenu::addSectionHeader (const String& title)
  55750. {
  55751. addCustomItem (0X4734a34f, new HeaderItemComponent (title));
  55752. }
  55753. Component* PopupMenu::createMenuComponent (const int x, const int y, const int w, const int h,
  55754. const int itemIdThatMustBeVisible,
  55755. const int minimumWidth,
  55756. const int maximumNumColumns,
  55757. const int standardItemHeight,
  55758. const bool alignToRectangle,
  55759. Component* menuBarComponent,
  55760. ApplicationCommandManager** managerOfChosenCommand,
  55761. Component* const componentAttachedTo)
  55762. {
  55763. Window* const pw
  55764. = Window::create (*this,
  55765. ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown(),
  55766. 0,
  55767. x, x + w,
  55768. y, y + h,
  55769. minimumWidth,
  55770. maximumNumColumns,
  55771. standardItemHeight,
  55772. alignToRectangle,
  55773. itemIdThatMustBeVisible,
  55774. menuBarComponent,
  55775. managerOfChosenCommand,
  55776. componentAttachedTo);
  55777. if (pw != 0)
  55778. pw->setVisible (true);
  55779. return pw;
  55780. }
  55781. int PopupMenu::showMenu (const int x, const int y, const int w, const int h,
  55782. const int itemIdThatMustBeVisible,
  55783. const int minimumWidth,
  55784. const int maximumNumColumns,
  55785. const int standardItemHeight,
  55786. const bool alignToRectangle,
  55787. Component* const componentAttachedTo)
  55788. {
  55789. Component::SafePointer<Component> prevFocused (Component::getCurrentlyFocusedComponent());
  55790. Component::SafePointer<Component> prevTopLevel ((prevFocused != 0) ? prevFocused->getTopLevelComponent() : 0);
  55791. Window::wasHiddenBecauseOfAppChange() = false;
  55792. int result = 0;
  55793. ApplicationCommandManager* managerOfChosenCommand = 0;
  55794. ScopedPointer <Component> popupComp (createMenuComponent (x, y, w, h,
  55795. itemIdThatMustBeVisible,
  55796. minimumWidth,
  55797. maximumNumColumns > 0 ? maximumNumColumns : 7,
  55798. standardItemHeight,
  55799. alignToRectangle, 0,
  55800. &managerOfChosenCommand,
  55801. componentAttachedTo));
  55802. if (popupComp != 0)
  55803. {
  55804. popupComp->enterModalState (false);
  55805. popupComp->toFront (false); // need to do this after making it modal, or it could
  55806. // be stuck behind other comps that are already modal..
  55807. result = popupComp->runModalLoop();
  55808. popupComp = 0;
  55809. if (! Window::wasHiddenBecauseOfAppChange())
  55810. {
  55811. if (prevTopLevel != 0)
  55812. prevTopLevel->toFront (true);
  55813. if (prevFocused != 0)
  55814. prevFocused->grabKeyboardFocus();
  55815. }
  55816. }
  55817. if (managerOfChosenCommand != 0 && result != 0)
  55818. {
  55819. ApplicationCommandTarget::InvocationInfo info (result);
  55820. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  55821. managerOfChosenCommand->invoke (info, true);
  55822. }
  55823. return result;
  55824. }
  55825. int PopupMenu::show (const int itemIdThatMustBeVisible,
  55826. const int minimumWidth,
  55827. const int maximumNumColumns,
  55828. const int standardItemHeight)
  55829. {
  55830. const Point<int> mousePos (Desktop::getMousePosition());
  55831. return showAt (mousePos.getX(), mousePos.getY(),
  55832. itemIdThatMustBeVisible,
  55833. minimumWidth,
  55834. maximumNumColumns,
  55835. standardItemHeight);
  55836. }
  55837. int PopupMenu::showAt (const int screenX,
  55838. const int screenY,
  55839. const int itemIdThatMustBeVisible,
  55840. const int minimumWidth,
  55841. const int maximumNumColumns,
  55842. const int standardItemHeight)
  55843. {
  55844. return showMenu (screenX, screenY, 1, 1,
  55845. itemIdThatMustBeVisible,
  55846. minimumWidth, maximumNumColumns,
  55847. standardItemHeight,
  55848. false, 0);
  55849. }
  55850. int PopupMenu::showAt (Component* componentToAttachTo,
  55851. const int itemIdThatMustBeVisible,
  55852. const int minimumWidth,
  55853. const int maximumNumColumns,
  55854. const int standardItemHeight)
  55855. {
  55856. if (componentToAttachTo != 0)
  55857. {
  55858. return showMenu (componentToAttachTo->getScreenX(),
  55859. componentToAttachTo->getScreenY(),
  55860. componentToAttachTo->getWidth(),
  55861. componentToAttachTo->getHeight(),
  55862. itemIdThatMustBeVisible,
  55863. minimumWidth,
  55864. maximumNumColumns,
  55865. standardItemHeight,
  55866. true, componentToAttachTo);
  55867. }
  55868. else
  55869. {
  55870. return show (itemIdThatMustBeVisible,
  55871. minimumWidth,
  55872. maximumNumColumns,
  55873. standardItemHeight);
  55874. }
  55875. }
  55876. void JUCE_CALLTYPE PopupMenu::dismissAllActiveMenus()
  55877. {
  55878. for (int i = Window::getActiveWindows().size(); --i >= 0;)
  55879. {
  55880. Window* const pmw = Window::getActiveWindows()[i];
  55881. if (pmw != 0)
  55882. pmw->dismissMenu (0);
  55883. }
  55884. }
  55885. int PopupMenu::getNumItems() const throw()
  55886. {
  55887. int num = 0;
  55888. for (int i = items.size(); --i >= 0;)
  55889. if (! (items.getUnchecked(i))->isSeparator)
  55890. ++num;
  55891. return num;
  55892. }
  55893. bool PopupMenu::containsCommandItem (const int commandID) const
  55894. {
  55895. for (int i = items.size(); --i >= 0;)
  55896. {
  55897. const Item* mi = items.getUnchecked (i);
  55898. if ((mi->itemId == commandID && mi->commandManager != 0)
  55899. || (mi->subMenu != 0 && mi->subMenu->containsCommandItem (commandID)))
  55900. {
  55901. return true;
  55902. }
  55903. }
  55904. return false;
  55905. }
  55906. bool PopupMenu::containsAnyActiveItems() const throw()
  55907. {
  55908. for (int i = items.size(); --i >= 0;)
  55909. {
  55910. const Item* const mi = items.getUnchecked (i);
  55911. if (mi->subMenu != 0)
  55912. {
  55913. if (mi->subMenu->containsAnyActiveItems())
  55914. return true;
  55915. }
  55916. else if (mi->active)
  55917. {
  55918. return true;
  55919. }
  55920. }
  55921. return false;
  55922. }
  55923. void PopupMenu::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  55924. {
  55925. lookAndFeel = newLookAndFeel;
  55926. }
  55927. PopupMenuCustomComponent::PopupMenuCustomComponent (const bool isTriggeredAutomatically_)
  55928. : isHighlighted (false),
  55929. isTriggeredAutomatically (isTriggeredAutomatically_)
  55930. {
  55931. }
  55932. PopupMenuCustomComponent::~PopupMenuCustomComponent()
  55933. {
  55934. }
  55935. void PopupMenuCustomComponent::triggerMenuItem()
  55936. {
  55937. PopupMenu::ItemComponent* const mic = dynamic_cast <PopupMenu::ItemComponent*> (getParentComponent());
  55938. if (mic != 0)
  55939. {
  55940. PopupMenu::Window* const pmw = dynamic_cast <PopupMenu::Window*> (mic->getParentComponent());
  55941. if (pmw != 0)
  55942. {
  55943. pmw->dismissMenu (&mic->itemInfo);
  55944. }
  55945. else
  55946. {
  55947. // something must have gone wrong with the component hierarchy if this happens..
  55948. jassertfalse;
  55949. }
  55950. }
  55951. else
  55952. {
  55953. // why isn't this component inside a menu? Not much point triggering the item if
  55954. // there's no menu.
  55955. jassertfalse;
  55956. }
  55957. }
  55958. PopupMenu::MenuItemIterator::MenuItemIterator (const PopupMenu& menu_)
  55959. : subMenu (0),
  55960. itemId (0),
  55961. isSeparator (false),
  55962. isTicked (false),
  55963. isEnabled (false),
  55964. isCustomComponent (false),
  55965. isSectionHeader (false),
  55966. customColour (0),
  55967. customImage (0),
  55968. menu (menu_),
  55969. index (0)
  55970. {
  55971. }
  55972. PopupMenu::MenuItemIterator::~MenuItemIterator()
  55973. {
  55974. }
  55975. bool PopupMenu::MenuItemIterator::next()
  55976. {
  55977. if (index >= menu.items.size())
  55978. return false;
  55979. const Item* const item = menu.items.getUnchecked (index);
  55980. ++index;
  55981. itemName = item->customComp != 0 ? item->customComp->getName() : item->text;
  55982. subMenu = item->subMenu;
  55983. itemId = item->itemId;
  55984. isSeparator = item->isSeparator;
  55985. isTicked = item->isTicked;
  55986. isEnabled = item->active;
  55987. isSectionHeader = dynamic_cast <HeaderItemComponent*> ((PopupMenuCustomComponent*) item->customComp) != 0;
  55988. isCustomComponent = (! isSectionHeader) && item->customComp != 0;
  55989. customColour = item->usesColour ? &(item->textColour) : 0;
  55990. customImage = item->image;
  55991. commandManager = item->commandManager;
  55992. return true;
  55993. }
  55994. END_JUCE_NAMESPACE
  55995. /*** End of inlined file: juce_PopupMenu.cpp ***/
  55996. /*** Start of inlined file: juce_ComponentDragger.cpp ***/
  55997. BEGIN_JUCE_NAMESPACE
  55998. ComponentDragger::ComponentDragger()
  55999. : constrainer (0)
  56000. {
  56001. }
  56002. ComponentDragger::~ComponentDragger()
  56003. {
  56004. }
  56005. void ComponentDragger::startDraggingComponent (Component* const componentToDrag,
  56006. ComponentBoundsConstrainer* const constrainer_)
  56007. {
  56008. jassert (componentToDrag->isValidComponent());
  56009. if (componentToDrag != 0)
  56010. {
  56011. constrainer = constrainer_;
  56012. originalPos = componentToDrag->relativePositionToGlobal (Point<int>());
  56013. }
  56014. }
  56015. void ComponentDragger::dragComponent (Component* const componentToDrag, const MouseEvent& e)
  56016. {
  56017. jassert (componentToDrag->isValidComponent());
  56018. jassert (e.mods.isAnyMouseButtonDown()); // (the event has to be a drag event..)
  56019. if (componentToDrag != 0)
  56020. {
  56021. Rectangle<int> bounds (componentToDrag->getBounds().withPosition (originalPos));
  56022. const Component* const parentComp = componentToDrag->getParentComponent();
  56023. if (parentComp != 0)
  56024. bounds.setPosition (parentComp->globalPositionToRelative (originalPos));
  56025. bounds.setPosition (bounds.getPosition() + e.getOffsetFromDragStart());
  56026. if (constrainer != 0)
  56027. constrainer->setBoundsForComponent (componentToDrag, bounds, false, false, false, false);
  56028. else
  56029. componentToDrag->setBounds (bounds);
  56030. }
  56031. }
  56032. END_JUCE_NAMESPACE
  56033. /*** End of inlined file: juce_ComponentDragger.cpp ***/
  56034. /*** Start of inlined file: juce_DragAndDropContainer.cpp ***/
  56035. BEGIN_JUCE_NAMESPACE
  56036. bool juce_performDragDropFiles (const StringArray& files, const bool copyFiles, bool& shouldStop);
  56037. bool juce_performDragDropText (const String& text, bool& shouldStop);
  56038. class DragImageComponent : public Component,
  56039. public Timer
  56040. {
  56041. public:
  56042. DragImageComponent (const Image& im,
  56043. const String& desc,
  56044. Component* const sourceComponent,
  56045. Component* const mouseDragSource_,
  56046. DragAndDropContainer* const o,
  56047. const Point<int>& imageOffset_)
  56048. : image (im),
  56049. source (sourceComponent),
  56050. mouseDragSource (mouseDragSource_),
  56051. owner (o),
  56052. dragDesc (desc),
  56053. imageOffset (imageOffset_),
  56054. hasCheckedForExternalDrag (false),
  56055. drawImage (true)
  56056. {
  56057. setSize (im.getWidth(), im.getHeight());
  56058. if (mouseDragSource == 0)
  56059. mouseDragSource = source;
  56060. mouseDragSource->addMouseListener (this, false);
  56061. startTimer (200);
  56062. setInterceptsMouseClicks (false, false);
  56063. setAlwaysOnTop (true);
  56064. }
  56065. ~DragImageComponent()
  56066. {
  56067. if (owner->dragImageComponent == this)
  56068. owner->dragImageComponent.release();
  56069. if (mouseDragSource != 0)
  56070. {
  56071. mouseDragSource->removeMouseListener (this);
  56072. if (getCurrentlyOver() != 0 && getCurrentlyOver()->isInterestedInDragSource (dragDesc, source))
  56073. getCurrentlyOver()->itemDragExit (dragDesc, source);
  56074. }
  56075. }
  56076. void paint (Graphics& g)
  56077. {
  56078. if (isOpaque())
  56079. g.fillAll (Colours::white);
  56080. if (drawImage)
  56081. {
  56082. g.setOpacity (1.0f);
  56083. g.drawImageAt (image, 0, 0);
  56084. }
  56085. }
  56086. DragAndDropTarget* findTarget (const Point<int>& screenPos, Point<int>& relativePos)
  56087. {
  56088. Component* hit = getParentComponent();
  56089. if (hit == 0)
  56090. {
  56091. hit = Desktop::getInstance().findComponentAt (screenPos);
  56092. }
  56093. else
  56094. {
  56095. const Point<int> relPos (hit->globalPositionToRelative (screenPos));
  56096. hit = hit->getComponentAt (relPos.getX(), relPos.getY());
  56097. }
  56098. // (note: use a local copy of the dragDesc member in case the callback runs
  56099. // a modal loop and deletes this object before the method completes)
  56100. const String dragDescLocal (dragDesc);
  56101. while (hit != 0)
  56102. {
  56103. DragAndDropTarget* const ddt = dynamic_cast <DragAndDropTarget*> (hit);
  56104. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  56105. {
  56106. relativePos = hit->globalPositionToRelative (screenPos);
  56107. return ddt;
  56108. }
  56109. hit = hit->getParentComponent();
  56110. }
  56111. return 0;
  56112. }
  56113. void mouseUp (const MouseEvent& e)
  56114. {
  56115. if (e.originalComponent != this)
  56116. {
  56117. if (mouseDragSource != 0)
  56118. mouseDragSource->removeMouseListener (this);
  56119. bool dropAccepted = false;
  56120. DragAndDropTarget* ddt = 0;
  56121. Point<int> relPos;
  56122. if (isVisible())
  56123. {
  56124. setVisible (false);
  56125. ddt = findTarget (e.getScreenPosition(), relPos);
  56126. // fade this component and remove it - it'll be deleted later by the timer callback
  56127. dropAccepted = ddt != 0;
  56128. setVisible (true);
  56129. if (dropAccepted || source == 0)
  56130. {
  56131. fadeOutComponent (120);
  56132. }
  56133. else
  56134. {
  56135. const Point<int> target (source->relativePositionToGlobal (Point<int> (source->getWidth() / 2,
  56136. source->getHeight() / 2)));
  56137. const Point<int> ourCentre (relativePositionToGlobal (Point<int> (getWidth() / 2,
  56138. getHeight() / 2)));
  56139. fadeOutComponent (120,
  56140. target.getX() - ourCentre.getX(),
  56141. target.getY() - ourCentre.getY());
  56142. }
  56143. }
  56144. if (getParentComponent() != 0)
  56145. getParentComponent()->removeChildComponent (this);
  56146. if (dropAccepted && ddt != 0)
  56147. {
  56148. // (note: use a local copy of the dragDesc member in case the callback runs
  56149. // a modal loop and deletes this object before the method completes)
  56150. const String dragDescLocal (dragDesc);
  56151. currentlyOverComp = 0;
  56152. ddt->itemDropped (dragDescLocal, source, relPos.getX(), relPos.getY());
  56153. }
  56154. // careful - this object could now be deleted..
  56155. }
  56156. }
  56157. void updateLocation (const bool canDoExternalDrag, const Point<int>& screenPos)
  56158. {
  56159. // (note: use a local copy of the dragDesc member in case the callback runs
  56160. // a modal loop and deletes this object before it returns)
  56161. const String dragDescLocal (dragDesc);
  56162. Point<int> newPos (screenPos + imageOffset);
  56163. if (getParentComponent() != 0)
  56164. newPos = getParentComponent()->globalPositionToRelative (newPos);
  56165. //if (newX != getX() || newY != getY())
  56166. {
  56167. setTopLeftPosition (newPos.getX(), newPos.getY());
  56168. Point<int> relPos;
  56169. DragAndDropTarget* const ddt = findTarget (screenPos, relPos);
  56170. Component* ddtComp = dynamic_cast <Component*> (ddt);
  56171. drawImage = (ddt == 0) || ddt->shouldDrawDragImageWhenOver();
  56172. if (ddtComp != currentlyOverComp)
  56173. {
  56174. if (currentlyOverComp != 0 && source != 0
  56175. && getCurrentlyOver()->isInterestedInDragSource (dragDescLocal, source))
  56176. {
  56177. getCurrentlyOver()->itemDragExit (dragDescLocal, source);
  56178. }
  56179. currentlyOverComp = ddtComp;
  56180. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  56181. ddt->itemDragEnter (dragDescLocal, source, relPos.getX(), relPos.getY());
  56182. }
  56183. DragAndDropTarget* target = getCurrentlyOver();
  56184. if (target != 0 && target->isInterestedInDragSource (dragDescLocal, source))
  56185. target->itemDragMove (dragDescLocal, source, relPos.getX(), relPos.getY());
  56186. if (getCurrentlyOver() == 0 && canDoExternalDrag && ! hasCheckedForExternalDrag)
  56187. {
  56188. if (Desktop::getInstance().findComponentAt (screenPos) == 0)
  56189. {
  56190. hasCheckedForExternalDrag = true;
  56191. StringArray files;
  56192. bool canMoveFiles = false;
  56193. if (owner->shouldDropFilesWhenDraggedExternally (dragDescLocal, source, files, canMoveFiles)
  56194. && files.size() > 0)
  56195. {
  56196. Component::SafePointer<Component> cdw (this);
  56197. setVisible (false);
  56198. if (ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown())
  56199. DragAndDropContainer::performExternalDragDropOfFiles (files, canMoveFiles);
  56200. if (cdw != 0)
  56201. delete this;
  56202. return;
  56203. }
  56204. }
  56205. }
  56206. }
  56207. }
  56208. void mouseDrag (const MouseEvent& e)
  56209. {
  56210. if (e.originalComponent != this)
  56211. updateLocation (true, e.getScreenPosition());
  56212. }
  56213. void timerCallback()
  56214. {
  56215. if (source == 0)
  56216. {
  56217. delete this;
  56218. }
  56219. else if (! isMouseButtonDownAnywhere())
  56220. {
  56221. if (mouseDragSource != 0)
  56222. mouseDragSource->removeMouseListener (this);
  56223. delete this;
  56224. }
  56225. }
  56226. private:
  56227. Image image;
  56228. Component::SafePointer<Component> source;
  56229. Component::SafePointer<Component> mouseDragSource;
  56230. DragAndDropContainer* const owner;
  56231. Component::SafePointer<Component> currentlyOverComp;
  56232. DragAndDropTarget* getCurrentlyOver()
  56233. {
  56234. return dynamic_cast <DragAndDropTarget*> (static_cast <Component*> (currentlyOverComp));
  56235. }
  56236. String dragDesc;
  56237. const Point<int> imageOffset;
  56238. bool hasCheckedForExternalDrag, drawImage;
  56239. DragImageComponent (const DragImageComponent&);
  56240. DragImageComponent& operator= (const DragImageComponent&);
  56241. };
  56242. DragAndDropContainer::DragAndDropContainer()
  56243. {
  56244. }
  56245. DragAndDropContainer::~DragAndDropContainer()
  56246. {
  56247. dragImageComponent = 0;
  56248. }
  56249. void DragAndDropContainer::startDragging (const String& sourceDescription,
  56250. Component* sourceComponent,
  56251. const Image& dragImage_,
  56252. const bool allowDraggingToExternalWindows,
  56253. const Point<int>* imageOffsetFromMouse)
  56254. {
  56255. Image dragImage (dragImage_);
  56256. if (dragImageComponent == 0)
  56257. {
  56258. Component* const thisComp = dynamic_cast <Component*> (this);
  56259. if (thisComp == 0)
  56260. {
  56261. jassertfalse; // Your DragAndDropContainer needs to be a Component!
  56262. return;
  56263. }
  56264. MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource (0);
  56265. if (draggingSource == 0 || ! draggingSource->isDragging())
  56266. {
  56267. jassertfalse; // You must call startDragging() from within a mouseDown or mouseDrag callback!
  56268. return;
  56269. }
  56270. const Point<int> lastMouseDown (Desktop::getLastMouseDownPosition());
  56271. Point<int> imageOffset;
  56272. if (dragImage.isNull())
  56273. {
  56274. dragImage = sourceComponent->createComponentSnapshot (sourceComponent->getLocalBounds())
  56275. .convertedToFormat (Image::ARGB);
  56276. dragImage.multiplyAllAlphas (0.6f);
  56277. const int lo = 150;
  56278. const int hi = 400;
  56279. Point<int> relPos (sourceComponent->globalPositionToRelative (lastMouseDown));
  56280. Point<int> clipped (dragImage.getBounds().getConstrainedPoint (relPos));
  56281. for (int y = dragImage.getHeight(); --y >= 0;)
  56282. {
  56283. const double dy = (y - clipped.getY()) * (y - clipped.getY());
  56284. for (int x = dragImage.getWidth(); --x >= 0;)
  56285. {
  56286. const int dx = x - clipped.getX();
  56287. const int distance = roundToInt (std::sqrt (dx * dx + dy));
  56288. if (distance > lo)
  56289. {
  56290. const float alpha = (distance > hi) ? 0
  56291. : (hi - distance) / (float) (hi - lo)
  56292. + Random::getSystemRandom().nextFloat() * 0.008f;
  56293. dragImage.multiplyAlphaAt (x, y, alpha);
  56294. }
  56295. }
  56296. }
  56297. imageOffset = -clipped;
  56298. }
  56299. else
  56300. {
  56301. if (imageOffsetFromMouse == 0)
  56302. imageOffset = -dragImage.getBounds().getCentre();
  56303. else
  56304. imageOffset = -(dragImage.getBounds().getConstrainedPoint (-*imageOffsetFromMouse));
  56305. }
  56306. dragImageComponent = new DragImageComponent (dragImage, sourceDescription, sourceComponent,
  56307. draggingSource->getComponentUnderMouse(), this, imageOffset);
  56308. currentDragDesc = sourceDescription;
  56309. if (allowDraggingToExternalWindows)
  56310. {
  56311. if (! Desktop::canUseSemiTransparentWindows())
  56312. dragImageComponent->setOpaque (true);
  56313. dragImageComponent->addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  56314. | ComponentPeer::windowIsTemporary
  56315. | ComponentPeer::windowIgnoresKeyPresses);
  56316. }
  56317. else
  56318. thisComp->addChildComponent (dragImageComponent);
  56319. static_cast <DragImageComponent*> (static_cast <Component*> (dragImageComponent))->updateLocation (false, lastMouseDown);
  56320. dragImageComponent->setVisible (true);
  56321. }
  56322. }
  56323. bool DragAndDropContainer::isDragAndDropActive() const
  56324. {
  56325. return dragImageComponent != 0;
  56326. }
  56327. const String DragAndDropContainer::getCurrentDragDescription() const
  56328. {
  56329. return (dragImageComponent != 0) ? currentDragDesc
  56330. : String::empty;
  56331. }
  56332. DragAndDropContainer* DragAndDropContainer::findParentDragContainerFor (Component* c)
  56333. {
  56334. return c == 0 ? 0 : c->findParentComponentOfClass ((DragAndDropContainer*) 0);
  56335. }
  56336. bool DragAndDropContainer::shouldDropFilesWhenDraggedExternally (const String&, Component*, StringArray&, bool&)
  56337. {
  56338. return false;
  56339. }
  56340. void DragAndDropTarget::itemDragEnter (const String&, Component*, int, int)
  56341. {
  56342. }
  56343. void DragAndDropTarget::itemDragMove (const String&, Component*, int, int)
  56344. {
  56345. }
  56346. void DragAndDropTarget::itemDragExit (const String&, Component*)
  56347. {
  56348. }
  56349. bool DragAndDropTarget::shouldDrawDragImageWhenOver()
  56350. {
  56351. return true;
  56352. }
  56353. void FileDragAndDropTarget::fileDragEnter (const StringArray&, int, int)
  56354. {
  56355. }
  56356. void FileDragAndDropTarget::fileDragMove (const StringArray&, int, int)
  56357. {
  56358. }
  56359. void FileDragAndDropTarget::fileDragExit (const StringArray&)
  56360. {
  56361. }
  56362. END_JUCE_NAMESPACE
  56363. /*** End of inlined file: juce_DragAndDropContainer.cpp ***/
  56364. /*** Start of inlined file: juce_MouseCursor.cpp ***/
  56365. BEGIN_JUCE_NAMESPACE
  56366. class MouseCursor::SharedCursorHandle
  56367. {
  56368. public:
  56369. explicit SharedCursorHandle (const MouseCursor::StandardCursorType type)
  56370. : handle (createStandardMouseCursor (type)),
  56371. refCount (1),
  56372. standardType (type),
  56373. isStandard (true)
  56374. {
  56375. }
  56376. SharedCursorHandle (const Image& image, const int hotSpotX, const int hotSpotY)
  56377. : handle (createMouseCursorFromImage (image, hotSpotX, hotSpotY)),
  56378. refCount (1),
  56379. standardType (MouseCursor::NormalCursor),
  56380. isStandard (false)
  56381. {
  56382. }
  56383. static SharedCursorHandle* createStandard (const MouseCursor::StandardCursorType type)
  56384. {
  56385. const ScopedLock sl (getLock());
  56386. for (int i = getCursors().size(); --i >= 0;)
  56387. {
  56388. SharedCursorHandle* const sc = getCursors().getUnchecked(i);
  56389. if (sc->standardType == type)
  56390. return sc->retain();
  56391. }
  56392. SharedCursorHandle* const sc = new SharedCursorHandle (type);
  56393. getCursors().add (sc);
  56394. return sc;
  56395. }
  56396. SharedCursorHandle* retain() throw()
  56397. {
  56398. ++refCount;
  56399. return this;
  56400. }
  56401. void release()
  56402. {
  56403. if (--refCount == 0)
  56404. {
  56405. if (isStandard)
  56406. {
  56407. const ScopedLock sl (getLock());
  56408. getCursors().removeValue (this);
  56409. }
  56410. delete this;
  56411. }
  56412. }
  56413. void* getHandle() const throw() { return handle; }
  56414. juce_UseDebuggingNewOperator
  56415. private:
  56416. void* const handle;
  56417. Atomic <int> refCount;
  56418. const MouseCursor::StandardCursorType standardType;
  56419. const bool isStandard;
  56420. static CriticalSection& getLock()
  56421. {
  56422. static CriticalSection lock;
  56423. return lock;
  56424. }
  56425. static Array <SharedCursorHandle*>& getCursors()
  56426. {
  56427. static Array <SharedCursorHandle*> cursors;
  56428. return cursors;
  56429. }
  56430. ~SharedCursorHandle()
  56431. {
  56432. deleteMouseCursor (handle, isStandard);
  56433. }
  56434. SharedCursorHandle& operator= (const SharedCursorHandle&);
  56435. };
  56436. MouseCursor::MouseCursor()
  56437. : cursorHandle (SharedCursorHandle::createStandard (NormalCursor))
  56438. {
  56439. jassert (cursorHandle != 0);
  56440. }
  56441. MouseCursor::MouseCursor (const StandardCursorType type)
  56442. : cursorHandle (SharedCursorHandle::createStandard (type))
  56443. {
  56444. jassert (cursorHandle != 0);
  56445. }
  56446. MouseCursor::MouseCursor (const Image& image, const int hotSpotX, const int hotSpotY)
  56447. : cursorHandle (new SharedCursorHandle (image, hotSpotX, hotSpotY))
  56448. {
  56449. }
  56450. MouseCursor::MouseCursor (const MouseCursor& other)
  56451. : cursorHandle (other.cursorHandle->retain())
  56452. {
  56453. }
  56454. MouseCursor::~MouseCursor()
  56455. {
  56456. cursorHandle->release();
  56457. }
  56458. MouseCursor& MouseCursor::operator= (const MouseCursor& other)
  56459. {
  56460. other.cursorHandle->retain();
  56461. cursorHandle->release();
  56462. cursorHandle = other.cursorHandle;
  56463. return *this;
  56464. }
  56465. bool MouseCursor::operator== (const MouseCursor& other) const throw()
  56466. {
  56467. return getHandle() == other.getHandle();
  56468. }
  56469. bool MouseCursor::operator!= (const MouseCursor& other) const throw()
  56470. {
  56471. return getHandle() != other.getHandle();
  56472. }
  56473. void* MouseCursor::getHandle() const throw()
  56474. {
  56475. return cursorHandle->getHandle();
  56476. }
  56477. void MouseCursor::showWaitCursor()
  56478. {
  56479. Desktop::getInstance().getMainMouseSource().showMouseCursor (MouseCursor::WaitCursor);
  56480. }
  56481. void MouseCursor::hideWaitCursor()
  56482. {
  56483. Desktop::getInstance().getMainMouseSource().revealCursor();
  56484. }
  56485. END_JUCE_NAMESPACE
  56486. /*** End of inlined file: juce_MouseCursor.cpp ***/
  56487. /*** Start of inlined file: juce_MouseEvent.cpp ***/
  56488. BEGIN_JUCE_NAMESPACE
  56489. MouseEvent::MouseEvent (MouseInputSource& source_,
  56490. const Point<int>& position,
  56491. const ModifierKeys& mods_,
  56492. Component* const eventComponent_,
  56493. Component* const originator,
  56494. const Time& eventTime_,
  56495. const Point<int> mouseDownPos_,
  56496. const Time& mouseDownTime_,
  56497. const int numberOfClicks_,
  56498. const bool mouseWasDragged) throw()
  56499. : x (position.getX()),
  56500. y (position.getY()),
  56501. mods (mods_),
  56502. eventComponent (eventComponent_),
  56503. originalComponent (originator),
  56504. eventTime (eventTime_),
  56505. source (source_),
  56506. mouseDownPos (mouseDownPos_),
  56507. mouseDownTime (mouseDownTime_),
  56508. numberOfClicks (numberOfClicks_),
  56509. wasMovedSinceMouseDown (mouseWasDragged)
  56510. {
  56511. }
  56512. MouseEvent::~MouseEvent() throw()
  56513. {
  56514. }
  56515. const MouseEvent MouseEvent::getEventRelativeTo (Component* const otherComponent) const throw()
  56516. {
  56517. if (otherComponent == 0)
  56518. {
  56519. jassertfalse;
  56520. return *this;
  56521. }
  56522. return MouseEvent (source, eventComponent->relativePositionToOtherComponent (otherComponent, getPosition()),
  56523. mods, otherComponent, originalComponent, eventTime,
  56524. eventComponent->relativePositionToOtherComponent (otherComponent, mouseDownPos),
  56525. mouseDownTime, numberOfClicks, wasMovedSinceMouseDown);
  56526. }
  56527. const MouseEvent MouseEvent::withNewPosition (const Point<int>& newPosition) const throw()
  56528. {
  56529. return MouseEvent (source, newPosition, mods, eventComponent, originalComponent,
  56530. eventTime, mouseDownPos, mouseDownTime,
  56531. numberOfClicks, wasMovedSinceMouseDown);
  56532. }
  56533. bool MouseEvent::mouseWasClicked() const throw()
  56534. {
  56535. return ! wasMovedSinceMouseDown;
  56536. }
  56537. int MouseEvent::getMouseDownX() const throw()
  56538. {
  56539. return mouseDownPos.getX();
  56540. }
  56541. int MouseEvent::getMouseDownY() const throw()
  56542. {
  56543. return mouseDownPos.getY();
  56544. }
  56545. const Point<int> MouseEvent::getMouseDownPosition() const throw()
  56546. {
  56547. return mouseDownPos;
  56548. }
  56549. int MouseEvent::getDistanceFromDragStartX() const throw()
  56550. {
  56551. return x - mouseDownPos.getX();
  56552. }
  56553. int MouseEvent::getDistanceFromDragStartY() const throw()
  56554. {
  56555. return y - mouseDownPos.getY();
  56556. }
  56557. int MouseEvent::getDistanceFromDragStart() const throw()
  56558. {
  56559. return mouseDownPos.getDistanceFrom (getPosition());
  56560. }
  56561. const Point<int> MouseEvent::getOffsetFromDragStart() const throw()
  56562. {
  56563. return getPosition() - mouseDownPos;
  56564. }
  56565. int MouseEvent::getLengthOfMousePress() const throw()
  56566. {
  56567. if (mouseDownTime.toMilliseconds() > 0)
  56568. return jmax (0, (int) (eventTime - mouseDownTime).inMilliseconds());
  56569. return 0;
  56570. }
  56571. const Point<int> MouseEvent::getPosition() const throw()
  56572. {
  56573. return Point<int> (x, y);
  56574. }
  56575. int MouseEvent::getScreenX() const
  56576. {
  56577. return getScreenPosition().getX();
  56578. }
  56579. int MouseEvent::getScreenY() const
  56580. {
  56581. return getScreenPosition().getY();
  56582. }
  56583. const Point<int> MouseEvent::getScreenPosition() const
  56584. {
  56585. return eventComponent->relativePositionToGlobal (Point<int> (x, y));
  56586. }
  56587. int MouseEvent::getMouseDownScreenX() const
  56588. {
  56589. return getMouseDownScreenPosition().getX();
  56590. }
  56591. int MouseEvent::getMouseDownScreenY() const
  56592. {
  56593. return getMouseDownScreenPosition().getY();
  56594. }
  56595. const Point<int> MouseEvent::getMouseDownScreenPosition() const
  56596. {
  56597. return eventComponent->relativePositionToGlobal (mouseDownPos);
  56598. }
  56599. static int doubleClickTimeOutMs = 400;
  56600. void MouseEvent::setDoubleClickTimeout (const int newTime) throw()
  56601. {
  56602. doubleClickTimeOutMs = newTime;
  56603. }
  56604. int MouseEvent::getDoubleClickTimeout() throw()
  56605. {
  56606. return doubleClickTimeOutMs;
  56607. }
  56608. END_JUCE_NAMESPACE
  56609. /*** End of inlined file: juce_MouseEvent.cpp ***/
  56610. /*** Start of inlined file: juce_MouseInputSource.cpp ***/
  56611. BEGIN_JUCE_NAMESPACE
  56612. class MouseInputSourceInternal : public AsyncUpdater
  56613. {
  56614. public:
  56615. MouseInputSourceInternal (MouseInputSource& source_, const int index_, const bool isMouseDevice_)
  56616. : index (index_), isMouseDevice (isMouseDevice_), source (source_), lastPeer (0), lastTime (0),
  56617. isUnboundedMouseModeOn (false), isCursorVisibleUntilOffscreen (false), currentCursorHandle (0),
  56618. mouseEventCounter (0)
  56619. {
  56620. zerostruct (mouseDowns);
  56621. }
  56622. ~MouseInputSourceInternal()
  56623. {
  56624. }
  56625. bool isDragging() const throw()
  56626. {
  56627. return buttonState.isAnyMouseButtonDown();
  56628. }
  56629. Component* getComponentUnderMouse() const
  56630. {
  56631. return static_cast <Component*> (componentUnderMouse);
  56632. }
  56633. const ModifierKeys getCurrentModifiers() const
  56634. {
  56635. return ModifierKeys::getCurrentModifiers().withoutMouseButtons().withFlags (buttonState.getRawFlags());
  56636. }
  56637. ComponentPeer* getPeer()
  56638. {
  56639. if (! ComponentPeer::isValidPeer (lastPeer))
  56640. lastPeer = 0;
  56641. return lastPeer;
  56642. }
  56643. Component* findComponentAt (const Point<int>& screenPos)
  56644. {
  56645. ComponentPeer* const peer = getPeer();
  56646. if (peer != 0)
  56647. {
  56648. Component* const comp = peer->getComponent();
  56649. const Point<int> relativePos (comp->globalPositionToRelative (screenPos));
  56650. // (the contains() call is needed to test for overlapping desktop windows)
  56651. if (comp->contains (relativePos.getX(), relativePos.getY()))
  56652. return comp->getComponentAt (relativePos);
  56653. }
  56654. return 0;
  56655. }
  56656. const Point<int> getScreenPosition() const throw()
  56657. {
  56658. return lastScreenPos + unboundedMouseOffset;
  56659. }
  56660. void sendMouseEnter (Component* const comp, const Point<int>& screenPos, const int64 time)
  56661. {
  56662. //DBG ("Mouse " + String (source.getIndex()) + " enter: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56663. comp->internalMouseEnter (source, comp->globalPositionToRelative (screenPos), time);
  56664. }
  56665. void sendMouseExit (Component* const comp, const Point<int>& screenPos, const int64 time)
  56666. {
  56667. //DBG ("Mouse " + String (source.getIndex()) + " exit: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56668. comp->internalMouseExit (source, comp->globalPositionToRelative (screenPos), time);
  56669. }
  56670. void sendMouseMove (Component* const comp, const Point<int>& screenPos, const int64 time)
  56671. {
  56672. //DBG ("Mouse " + String (source.getIndex()) + " move: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56673. comp->internalMouseMove (source, comp->globalPositionToRelative (screenPos), time);
  56674. }
  56675. void sendMouseDown (Component* const comp, const Point<int>& screenPos, const int64 time)
  56676. {
  56677. //DBG ("Mouse " + String (source.getIndex()) + " down: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56678. comp->internalMouseDown (source, comp->globalPositionToRelative (screenPos), time);
  56679. }
  56680. void sendMouseDrag (Component* const comp, const Point<int>& screenPos, const int64 time)
  56681. {
  56682. //DBG ("Mouse " + String (source.getIndex()) + " drag: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56683. comp->internalMouseDrag (source, comp->globalPositionToRelative (screenPos), time);
  56684. }
  56685. void sendMouseUp (Component* const comp, const Point<int>& screenPos, const int64 time)
  56686. {
  56687. //DBG ("Mouse " + String (source.getIndex()) + " up: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56688. comp->internalMouseUp (source, comp->globalPositionToRelative (screenPos), time, getCurrentModifiers());
  56689. }
  56690. void sendMouseWheel (Component* const comp, const Point<int>& screenPos, const int64 time, float x, float y)
  56691. {
  56692. //DBG ("Mouse " + String (source.getIndex()) + " wheel: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56693. comp->internalMouseWheel (source, comp->globalPositionToRelative (screenPos), time, x, y);
  56694. }
  56695. // (returns true if the button change caused a modal event loop)
  56696. bool setButtons (const Point<int>& screenPos, const int64 time, const ModifierKeys& newButtonState)
  56697. {
  56698. if (buttonState == newButtonState)
  56699. return false;
  56700. setScreenPos (screenPos, time, false);
  56701. // (ignore secondary clicks when there's already a button down)
  56702. if (buttonState.isAnyMouseButtonDown() == newButtonState.isAnyMouseButtonDown())
  56703. {
  56704. buttonState = newButtonState;
  56705. return false;
  56706. }
  56707. const int lastCounter = mouseEventCounter;
  56708. if (buttonState.isAnyMouseButtonDown())
  56709. {
  56710. Component* const current = getComponentUnderMouse();
  56711. if (current != 0)
  56712. sendMouseUp (current, screenPos + unboundedMouseOffset, time);
  56713. enableUnboundedMouseMovement (false, false);
  56714. }
  56715. buttonState = newButtonState;
  56716. if (buttonState.isAnyMouseButtonDown())
  56717. {
  56718. Desktop::getInstance().incrementMouseClickCounter();
  56719. Component* const current = getComponentUnderMouse();
  56720. if (current != 0)
  56721. {
  56722. registerMouseDown (screenPos, time, current);
  56723. sendMouseDown (current, screenPos, time);
  56724. }
  56725. }
  56726. return lastCounter != mouseEventCounter;
  56727. }
  56728. void setComponentUnderMouse (Component* const newComponent, const Point<int>& screenPos, const int64 time)
  56729. {
  56730. Component* current = getComponentUnderMouse();
  56731. if (newComponent != current)
  56732. {
  56733. Component::SafePointer<Component> safeNewComp (newComponent);
  56734. const ModifierKeys originalButtonState (buttonState);
  56735. if (current != 0)
  56736. {
  56737. setButtons (screenPos, time, ModifierKeys());
  56738. sendMouseExit (current, screenPos, time);
  56739. buttonState = originalButtonState;
  56740. }
  56741. componentUnderMouse = safeNewComp;
  56742. current = getComponentUnderMouse();
  56743. if (current != 0)
  56744. sendMouseEnter (current, screenPos, time);
  56745. revealCursor (false);
  56746. setButtons (screenPos, time, originalButtonState);
  56747. }
  56748. }
  56749. void setPeer (ComponentPeer* const newPeer, const Point<int>& screenPos, const int64 time)
  56750. {
  56751. ModifierKeys::updateCurrentModifiers();
  56752. if (newPeer != lastPeer)
  56753. {
  56754. setComponentUnderMouse (0, screenPos, time);
  56755. lastPeer = newPeer;
  56756. setComponentUnderMouse (findComponentAt (screenPos), screenPos, time);
  56757. }
  56758. }
  56759. void setScreenPos (const Point<int>& newScreenPos, const int64 time, const bool forceUpdate)
  56760. {
  56761. if (! isDragging())
  56762. setComponentUnderMouse (findComponentAt (newScreenPos), newScreenPos, time);
  56763. if (newScreenPos != lastScreenPos || forceUpdate)
  56764. {
  56765. cancelPendingUpdate();
  56766. lastScreenPos = newScreenPos;
  56767. Component* const current = getComponentUnderMouse();
  56768. if (current != 0)
  56769. {
  56770. if (isDragging())
  56771. {
  56772. registerMouseDrag (newScreenPos);
  56773. sendMouseDrag (current, newScreenPos + unboundedMouseOffset, time);
  56774. if (isUnboundedMouseModeOn)
  56775. handleUnboundedDrag (current);
  56776. }
  56777. else
  56778. {
  56779. sendMouseMove (current, newScreenPos, time);
  56780. }
  56781. }
  56782. revealCursor (false);
  56783. }
  56784. }
  56785. void handleEvent (ComponentPeer* const newPeer, const Point<int>& positionWithinPeer, const int64 time, const ModifierKeys& newMods)
  56786. {
  56787. jassert (newPeer != 0);
  56788. lastTime = time;
  56789. ++mouseEventCounter;
  56790. const Point<int> screenPos (newPeer->relativePositionToGlobal (positionWithinPeer));
  56791. if (isDragging() && newMods.isAnyMouseButtonDown())
  56792. {
  56793. setScreenPos (screenPos, time, false);
  56794. }
  56795. else
  56796. {
  56797. setPeer (newPeer, screenPos, time);
  56798. ComponentPeer* peer = getPeer();
  56799. if (peer != 0)
  56800. {
  56801. if (setButtons (screenPos, time, newMods))
  56802. return; // some modal events have been dispatched, so the current event is now out-of-date
  56803. peer = getPeer();
  56804. if (peer != 0)
  56805. setScreenPos (screenPos, time, false);
  56806. }
  56807. }
  56808. }
  56809. void handleWheel (ComponentPeer* const peer, const Point<int>& positionWithinPeer, int64 time, float x, float y)
  56810. {
  56811. jassert (peer != 0);
  56812. lastTime = time;
  56813. ++mouseEventCounter;
  56814. const Point<int> screenPos (peer->relativePositionToGlobal (positionWithinPeer));
  56815. setPeer (peer, screenPos, time);
  56816. setScreenPos (screenPos, time, false);
  56817. triggerFakeMove();
  56818. if (! isDragging())
  56819. {
  56820. Component* current = getComponentUnderMouse();
  56821. if (current != 0)
  56822. sendMouseWheel (current, screenPos, time, x, y);
  56823. }
  56824. }
  56825. const Time getLastMouseDownTime() const throw()
  56826. {
  56827. return Time (mouseDowns[0].time);
  56828. }
  56829. const Point<int> getLastMouseDownPosition() const throw()
  56830. {
  56831. return mouseDowns[0].position;
  56832. }
  56833. int getNumberOfMultipleClicks() const throw()
  56834. {
  56835. int numClicks = 0;
  56836. if (mouseDowns[0].time != 0)
  56837. {
  56838. if (! mouseMovedSignificantlySincePressed)
  56839. ++numClicks;
  56840. for (int i = 1; i < numElementsInArray (mouseDowns); ++i)
  56841. {
  56842. if (mouseDowns[0].time - mouseDowns[i].time < (int) (MouseEvent::getDoubleClickTimeout() * (1.0 + 0.25 * (i - 1)))
  56843. && abs (mouseDowns[0].position.getX() - mouseDowns[i].position.getX()) < 8
  56844. && abs (mouseDowns[0].position.getY() - mouseDowns[i].position.getY()) < 8)
  56845. {
  56846. ++numClicks;
  56847. }
  56848. else
  56849. {
  56850. break;
  56851. }
  56852. }
  56853. }
  56854. return numClicks;
  56855. }
  56856. bool hasMouseMovedSignificantlySincePressed() const throw()
  56857. {
  56858. return mouseMovedSignificantlySincePressed
  56859. || lastTime > mouseDowns[0].time + 300;
  56860. }
  56861. void triggerFakeMove()
  56862. {
  56863. triggerAsyncUpdate();
  56864. }
  56865. void handleAsyncUpdate()
  56866. {
  56867. if (! isDragging())
  56868. setScreenPos (Desktop::getMousePosition(), jmax (lastTime, Time::currentTimeMillis()), true);
  56869. }
  56870. void enableUnboundedMouseMovement (bool enable, bool keepCursorVisibleUntilOffscreen)
  56871. {
  56872. enable = enable && isDragging();
  56873. isCursorVisibleUntilOffscreen = keepCursorVisibleUntilOffscreen;
  56874. if (enable != isUnboundedMouseModeOn)
  56875. {
  56876. if ((! enable) && ((! isCursorVisibleUntilOffscreen) || ! unboundedMouseOffset.isOrigin()))
  56877. {
  56878. // when released, return the mouse to within the component's bounds
  56879. Component* current = getComponentUnderMouse();
  56880. if (current != 0)
  56881. Desktop::setMousePosition (current->getScreenBounds()
  56882. .getConstrainedPoint (current->getMouseXYRelative()));
  56883. }
  56884. isUnboundedMouseModeOn = enable;
  56885. unboundedMouseOffset = Point<int>();
  56886. revealCursor (true);
  56887. }
  56888. }
  56889. void handleUnboundedDrag (Component* current)
  56890. {
  56891. const Rectangle<int> screenArea (current->getParentMonitorArea().expanded (-2, -2));
  56892. if (! screenArea.contains (lastScreenPos))
  56893. {
  56894. const Point<int> componentCentre (current->getScreenBounds().getCentre());
  56895. unboundedMouseOffset += (lastScreenPos - componentCentre);
  56896. Desktop::setMousePosition (componentCentre);
  56897. }
  56898. else if (isCursorVisibleUntilOffscreen
  56899. && (! unboundedMouseOffset.isOrigin())
  56900. && screenArea.contains (lastScreenPos + unboundedMouseOffset))
  56901. {
  56902. Desktop::setMousePosition (lastScreenPos + unboundedMouseOffset);
  56903. unboundedMouseOffset = Point<int>();
  56904. }
  56905. }
  56906. void showMouseCursor (MouseCursor cursor, bool forcedUpdate)
  56907. {
  56908. if (isUnboundedMouseModeOn && ((! unboundedMouseOffset.isOrigin()) || ! isCursorVisibleUntilOffscreen))
  56909. {
  56910. cursor = MouseCursor::NoCursor;
  56911. forcedUpdate = true;
  56912. }
  56913. if (forcedUpdate || cursor.getHandle() != currentCursorHandle)
  56914. {
  56915. currentCursorHandle = cursor.getHandle();
  56916. cursor.showInWindow (getPeer());
  56917. }
  56918. }
  56919. void hideCursor()
  56920. {
  56921. showMouseCursor (MouseCursor::NoCursor, true);
  56922. }
  56923. void revealCursor (bool forcedUpdate)
  56924. {
  56925. MouseCursor mc (MouseCursor::NormalCursor);
  56926. Component* current = getComponentUnderMouse();
  56927. if (current != 0)
  56928. mc = current->getLookAndFeel().getMouseCursorFor (*current);
  56929. showMouseCursor (mc, forcedUpdate);
  56930. }
  56931. int index;
  56932. bool isMouseDevice;
  56933. Point<int> lastScreenPos;
  56934. ModifierKeys buttonState;
  56935. private:
  56936. MouseInputSource& source;
  56937. Component::SafePointer<Component> componentUnderMouse;
  56938. ComponentPeer* lastPeer;
  56939. Point<int> unboundedMouseOffset;
  56940. bool isUnboundedMouseModeOn, isCursorVisibleUntilOffscreen;
  56941. void* currentCursorHandle;
  56942. int mouseEventCounter;
  56943. struct RecentMouseDown
  56944. {
  56945. Point<int> position;
  56946. int64 time;
  56947. Component* component;
  56948. };
  56949. RecentMouseDown mouseDowns[4];
  56950. bool mouseMovedSignificantlySincePressed;
  56951. int64 lastTime;
  56952. void registerMouseDown (const Point<int>& screenPos, const int64 time, Component* const component) throw()
  56953. {
  56954. for (int i = numElementsInArray (mouseDowns); --i > 0;)
  56955. mouseDowns[i] = mouseDowns[i - 1];
  56956. mouseDowns[0].position = screenPos;
  56957. mouseDowns[0].time = time;
  56958. mouseDowns[0].component = component;
  56959. mouseMovedSignificantlySincePressed = false;
  56960. }
  56961. void registerMouseDrag (const Point<int>& screenPos) throw()
  56962. {
  56963. mouseMovedSignificantlySincePressed = mouseMovedSignificantlySincePressed
  56964. || mouseDowns[0].position.getDistanceFrom (screenPos) >= 4;
  56965. }
  56966. MouseInputSourceInternal (const MouseInputSourceInternal&);
  56967. MouseInputSourceInternal& operator= (const MouseInputSourceInternal&);
  56968. };
  56969. MouseInputSource::MouseInputSource (const int index, const bool isMouseDevice)
  56970. {
  56971. pimpl = new MouseInputSourceInternal (*this, index, isMouseDevice);
  56972. }
  56973. MouseInputSource::~MouseInputSource()
  56974. {
  56975. }
  56976. bool MouseInputSource::isMouse() const { return pimpl->isMouseDevice; }
  56977. bool MouseInputSource::isTouch() const { return ! isMouse(); }
  56978. bool MouseInputSource::canHover() const { return isMouse(); }
  56979. bool MouseInputSource::hasMouseWheel() const { return isMouse(); }
  56980. int MouseInputSource::getIndex() const { return pimpl->index; }
  56981. bool MouseInputSource::isDragging() const { return pimpl->isDragging(); }
  56982. const Point<int> MouseInputSource::getScreenPosition() const { return pimpl->getScreenPosition(); }
  56983. const ModifierKeys MouseInputSource::getCurrentModifiers() const { return pimpl->getCurrentModifiers(); }
  56984. Component* MouseInputSource::getComponentUnderMouse() const { return pimpl->getComponentUnderMouse(); }
  56985. void MouseInputSource::triggerFakeMove() const { pimpl->triggerFakeMove(); }
  56986. int MouseInputSource::getNumberOfMultipleClicks() const throw() { return pimpl->getNumberOfMultipleClicks(); }
  56987. const Time MouseInputSource::getLastMouseDownTime() const throw() { return pimpl->getLastMouseDownTime(); }
  56988. const Point<int> MouseInputSource::getLastMouseDownPosition() const throw() { return pimpl->getLastMouseDownPosition(); }
  56989. bool MouseInputSource::hasMouseMovedSignificantlySincePressed() const throw() { return pimpl->hasMouseMovedSignificantlySincePressed(); }
  56990. bool MouseInputSource::canDoUnboundedMovement() const throw() { return isMouse(); }
  56991. void MouseInputSource::enableUnboundedMouseMovement (bool isEnabled, bool keepCursorVisibleUntilOffscreen) { pimpl->enableUnboundedMouseMovement (isEnabled, keepCursorVisibleUntilOffscreen); }
  56992. bool MouseInputSource::hasMouseCursor() const throw() { return isMouse(); }
  56993. void MouseInputSource::showMouseCursor (const MouseCursor& cursor) { pimpl->showMouseCursor (cursor, false); }
  56994. void MouseInputSource::hideCursor() { pimpl->hideCursor(); }
  56995. void MouseInputSource::revealCursor() { pimpl->revealCursor (false); }
  56996. void MouseInputSource::forceMouseCursorUpdate() { pimpl->revealCursor (true); }
  56997. void MouseInputSource::handleEvent (ComponentPeer* peer, const Point<int>& positionWithinPeer, const int64 time, const ModifierKeys& mods)
  56998. {
  56999. pimpl->handleEvent (peer, positionWithinPeer, time, mods.withOnlyMouseButtons());
  57000. }
  57001. void MouseInputSource::handleWheel (ComponentPeer* const peer, const Point<int>& positionWithinPeer, const int64 time, const float x, const float y)
  57002. {
  57003. pimpl->handleWheel (peer, positionWithinPeer, time, x, y);
  57004. }
  57005. END_JUCE_NAMESPACE
  57006. /*** End of inlined file: juce_MouseInputSource.cpp ***/
  57007. /*** Start of inlined file: juce_MouseHoverDetector.cpp ***/
  57008. BEGIN_JUCE_NAMESPACE
  57009. MouseHoverDetector::MouseHoverDetector (const int hoverTimeMillisecs_)
  57010. : source (0),
  57011. hoverTimeMillisecs (hoverTimeMillisecs_),
  57012. hasJustHovered (false)
  57013. {
  57014. internalTimer.owner = this;
  57015. }
  57016. MouseHoverDetector::~MouseHoverDetector()
  57017. {
  57018. setHoverComponent (0);
  57019. }
  57020. void MouseHoverDetector::setHoverTimeMillisecs (const int newTimeInMillisecs)
  57021. {
  57022. hoverTimeMillisecs = newTimeInMillisecs;
  57023. }
  57024. void MouseHoverDetector::setHoverComponent (Component* const newSourceComponent)
  57025. {
  57026. if (source != newSourceComponent)
  57027. {
  57028. internalTimer.stopTimer();
  57029. hasJustHovered = false;
  57030. if (source != 0)
  57031. {
  57032. // ! you need to delete the hover detector before deleting its component
  57033. jassert (source->isValidComponent());
  57034. source->removeMouseListener (&internalTimer);
  57035. }
  57036. source = newSourceComponent;
  57037. if (newSourceComponent != 0)
  57038. newSourceComponent->addMouseListener (&internalTimer, false);
  57039. }
  57040. }
  57041. void MouseHoverDetector::hoverTimerCallback()
  57042. {
  57043. internalTimer.stopTimer();
  57044. if (source != 0)
  57045. {
  57046. const Point<int> pos (source->getMouseXYRelative());
  57047. if (source->reallyContains (pos.getX(), pos.getY(), false))
  57048. {
  57049. hasJustHovered = true;
  57050. mouseHovered (pos.getX(), pos.getY());
  57051. }
  57052. }
  57053. }
  57054. void MouseHoverDetector::checkJustHoveredCallback()
  57055. {
  57056. if (hasJustHovered)
  57057. {
  57058. hasJustHovered = false;
  57059. mouseMovedAfterHover();
  57060. }
  57061. }
  57062. void MouseHoverDetector::HoverDetectorInternal::timerCallback()
  57063. {
  57064. owner->hoverTimerCallback();
  57065. }
  57066. void MouseHoverDetector::HoverDetectorInternal::mouseEnter (const MouseEvent&)
  57067. {
  57068. stopTimer();
  57069. owner->checkJustHoveredCallback();
  57070. }
  57071. void MouseHoverDetector::HoverDetectorInternal::mouseExit (const MouseEvent&)
  57072. {
  57073. stopTimer();
  57074. owner->checkJustHoveredCallback();
  57075. }
  57076. void MouseHoverDetector::HoverDetectorInternal::mouseDown (const MouseEvent&)
  57077. {
  57078. stopTimer();
  57079. owner->checkJustHoveredCallback();
  57080. }
  57081. void MouseHoverDetector::HoverDetectorInternal::mouseUp (const MouseEvent&)
  57082. {
  57083. stopTimer();
  57084. owner->checkJustHoveredCallback();
  57085. }
  57086. void MouseHoverDetector::HoverDetectorInternal::mouseMove (const MouseEvent& e)
  57087. {
  57088. if (lastX != e.x || lastY != e.y) // to avoid fake mouse-moves setting it off
  57089. {
  57090. lastX = e.x;
  57091. lastY = e.y;
  57092. if (owner->source != 0)
  57093. startTimer (owner->hoverTimeMillisecs);
  57094. owner->checkJustHoveredCallback();
  57095. }
  57096. }
  57097. void MouseHoverDetector::HoverDetectorInternal::mouseWheelMove (const MouseEvent&, float, float)
  57098. {
  57099. stopTimer();
  57100. owner->checkJustHoveredCallback();
  57101. }
  57102. END_JUCE_NAMESPACE
  57103. /*** End of inlined file: juce_MouseHoverDetector.cpp ***/
  57104. /*** Start of inlined file: juce_MouseListener.cpp ***/
  57105. BEGIN_JUCE_NAMESPACE
  57106. void MouseListener::mouseEnter (const MouseEvent&)
  57107. {
  57108. }
  57109. void MouseListener::mouseExit (const MouseEvent&)
  57110. {
  57111. }
  57112. void MouseListener::mouseDown (const MouseEvent&)
  57113. {
  57114. }
  57115. void MouseListener::mouseUp (const MouseEvent&)
  57116. {
  57117. }
  57118. void MouseListener::mouseDrag (const MouseEvent&)
  57119. {
  57120. }
  57121. void MouseListener::mouseMove (const MouseEvent&)
  57122. {
  57123. }
  57124. void MouseListener::mouseDoubleClick (const MouseEvent&)
  57125. {
  57126. }
  57127. void MouseListener::mouseWheelMove (const MouseEvent&, float, float)
  57128. {
  57129. }
  57130. END_JUCE_NAMESPACE
  57131. /*** End of inlined file: juce_MouseListener.cpp ***/
  57132. /*** Start of inlined file: juce_BooleanPropertyComponent.cpp ***/
  57133. BEGIN_JUCE_NAMESPACE
  57134. BooleanPropertyComponent::BooleanPropertyComponent (const String& name,
  57135. const String& buttonTextWhenTrue,
  57136. const String& buttonTextWhenFalse)
  57137. : PropertyComponent (name),
  57138. onText (buttonTextWhenTrue),
  57139. offText (buttonTextWhenFalse)
  57140. {
  57141. addAndMakeVisible (&button);
  57142. button.setClickingTogglesState (false);
  57143. button.addButtonListener (this);
  57144. }
  57145. BooleanPropertyComponent::BooleanPropertyComponent (const Value& valueToControl,
  57146. const String& name,
  57147. const String& buttonText)
  57148. : PropertyComponent (name),
  57149. onText (buttonText),
  57150. offText (buttonText)
  57151. {
  57152. addAndMakeVisible (&button);
  57153. button.setClickingTogglesState (false);
  57154. button.setButtonText (buttonText);
  57155. button.getToggleStateValue().referTo (valueToControl);
  57156. button.setClickingTogglesState (true);
  57157. }
  57158. BooleanPropertyComponent::~BooleanPropertyComponent()
  57159. {
  57160. }
  57161. void BooleanPropertyComponent::setState (const bool newState)
  57162. {
  57163. button.setToggleState (newState, true);
  57164. }
  57165. bool BooleanPropertyComponent::getState() const
  57166. {
  57167. return button.getToggleState();
  57168. }
  57169. void BooleanPropertyComponent::paint (Graphics& g)
  57170. {
  57171. PropertyComponent::paint (g);
  57172. g.setColour (Colours::white);
  57173. g.fillRect (button.getBounds());
  57174. g.setColour (findColour (ComboBox::outlineColourId));
  57175. g.drawRect (button.getBounds());
  57176. }
  57177. void BooleanPropertyComponent::refresh()
  57178. {
  57179. button.setToggleState (getState(), false);
  57180. button.setButtonText (button.getToggleState() ? onText : offText);
  57181. }
  57182. void BooleanPropertyComponent::buttonClicked (Button*)
  57183. {
  57184. setState (! getState());
  57185. }
  57186. END_JUCE_NAMESPACE
  57187. /*** End of inlined file: juce_BooleanPropertyComponent.cpp ***/
  57188. /*** Start of inlined file: juce_ButtonPropertyComponent.cpp ***/
  57189. BEGIN_JUCE_NAMESPACE
  57190. ButtonPropertyComponent::ButtonPropertyComponent (const String& name,
  57191. const bool triggerOnMouseDown)
  57192. : PropertyComponent (name)
  57193. {
  57194. addAndMakeVisible (&button);
  57195. button.setTriggeredOnMouseDown (triggerOnMouseDown);
  57196. button.addButtonListener (this);
  57197. }
  57198. ButtonPropertyComponent::~ButtonPropertyComponent()
  57199. {
  57200. }
  57201. void ButtonPropertyComponent::refresh()
  57202. {
  57203. button.setButtonText (getButtonText());
  57204. }
  57205. void ButtonPropertyComponent::buttonClicked (Button*)
  57206. {
  57207. buttonClicked();
  57208. }
  57209. END_JUCE_NAMESPACE
  57210. /*** End of inlined file: juce_ButtonPropertyComponent.cpp ***/
  57211. /*** Start of inlined file: juce_ChoicePropertyComponent.cpp ***/
  57212. BEGIN_JUCE_NAMESPACE
  57213. class ChoicePropertyComponent::RemapperValueSource : public Value::ValueSource,
  57214. public Value::Listener
  57215. {
  57216. public:
  57217. RemapperValueSource (const Value& sourceValue_, const Array<var>& mappings_)
  57218. : sourceValue (sourceValue_),
  57219. mappings (mappings_)
  57220. {
  57221. sourceValue.addListener (this);
  57222. }
  57223. ~RemapperValueSource() {}
  57224. const var getValue() const
  57225. {
  57226. return mappings.indexOf (sourceValue.getValue()) + 1;
  57227. }
  57228. void setValue (const var& newValue)
  57229. {
  57230. const var remappedVal (mappings [(int) newValue - 1]);
  57231. if (remappedVal != sourceValue)
  57232. sourceValue = remappedVal;
  57233. }
  57234. void valueChanged (Value&)
  57235. {
  57236. sendChangeMessage (true);
  57237. }
  57238. juce_UseDebuggingNewOperator
  57239. protected:
  57240. Value sourceValue;
  57241. Array<var> mappings;
  57242. RemapperValueSource (const RemapperValueSource&);
  57243. const RemapperValueSource& operator= (const RemapperValueSource&);
  57244. };
  57245. ChoicePropertyComponent::ChoicePropertyComponent (const String& name)
  57246. : PropertyComponent (name),
  57247. isCustomClass (true)
  57248. {
  57249. }
  57250. ChoicePropertyComponent::ChoicePropertyComponent (const Value& valueToControl,
  57251. const String& name,
  57252. const StringArray& choices_,
  57253. const Array <var>& correspondingValues)
  57254. : PropertyComponent (name),
  57255. choices (choices_),
  57256. isCustomClass (false)
  57257. {
  57258. // The array of corresponding values must contain one value for each of the items in
  57259. // the choices array!
  57260. jassert (correspondingValues.size() == choices.size());
  57261. createComboBox();
  57262. comboBox.getSelectedIdAsValue().referTo (Value (new RemapperValueSource (valueToControl, correspondingValues)));
  57263. }
  57264. ChoicePropertyComponent::~ChoicePropertyComponent()
  57265. {
  57266. }
  57267. void ChoicePropertyComponent::createComboBox()
  57268. {
  57269. addAndMakeVisible (&comboBox);
  57270. for (int i = 0; i < choices.size(); ++i)
  57271. {
  57272. if (choices[i].isNotEmpty())
  57273. comboBox.addItem (choices[i], i + 1);
  57274. else
  57275. comboBox.addSeparator();
  57276. }
  57277. comboBox.setEditableText (false);
  57278. }
  57279. void ChoicePropertyComponent::setIndex (const int /*newIndex*/)
  57280. {
  57281. jassertfalse; // you need to override this method in your subclass!
  57282. }
  57283. int ChoicePropertyComponent::getIndex() const
  57284. {
  57285. jassertfalse; // you need to override this method in your subclass!
  57286. return -1;
  57287. }
  57288. const StringArray& ChoicePropertyComponent::getChoices() const
  57289. {
  57290. return choices;
  57291. }
  57292. void ChoicePropertyComponent::refresh()
  57293. {
  57294. if (isCustomClass)
  57295. {
  57296. if (! comboBox.isVisible())
  57297. {
  57298. createComboBox();
  57299. comboBox.addListener (this);
  57300. }
  57301. comboBox.setSelectedId (getIndex() + 1, true);
  57302. }
  57303. }
  57304. void ChoicePropertyComponent::comboBoxChanged (ComboBox*)
  57305. {
  57306. if (isCustomClass)
  57307. {
  57308. const int newIndex = comboBox.getSelectedId() - 1;
  57309. if (newIndex != getIndex())
  57310. setIndex (newIndex);
  57311. }
  57312. }
  57313. END_JUCE_NAMESPACE
  57314. /*** End of inlined file: juce_ChoicePropertyComponent.cpp ***/
  57315. /*** Start of inlined file: juce_PropertyComponent.cpp ***/
  57316. BEGIN_JUCE_NAMESPACE
  57317. PropertyComponent::PropertyComponent (const String& name,
  57318. const int preferredHeight_)
  57319. : Component (name),
  57320. preferredHeight (preferredHeight_)
  57321. {
  57322. jassert (name.isNotEmpty());
  57323. }
  57324. PropertyComponent::~PropertyComponent()
  57325. {
  57326. }
  57327. void PropertyComponent::paint (Graphics& g)
  57328. {
  57329. getLookAndFeel().drawPropertyComponentBackground (g, getWidth(), getHeight(), *this);
  57330. getLookAndFeel().drawPropertyComponentLabel (g, getWidth(), getHeight(), *this);
  57331. }
  57332. void PropertyComponent::resized()
  57333. {
  57334. if (getNumChildComponents() > 0)
  57335. getChildComponent (0)->setBounds (getLookAndFeel().getPropertyComponentContentPosition (*this));
  57336. }
  57337. void PropertyComponent::enablementChanged()
  57338. {
  57339. repaint();
  57340. }
  57341. END_JUCE_NAMESPACE
  57342. /*** End of inlined file: juce_PropertyComponent.cpp ***/
  57343. /*** Start of inlined file: juce_PropertyPanel.cpp ***/
  57344. BEGIN_JUCE_NAMESPACE
  57345. class PropertyPanel::PropertyHolderComponent : public Component
  57346. {
  57347. public:
  57348. PropertyHolderComponent()
  57349. {
  57350. }
  57351. ~PropertyHolderComponent()
  57352. {
  57353. deleteAllChildren();
  57354. }
  57355. void paint (Graphics&)
  57356. {
  57357. }
  57358. void updateLayout (int width);
  57359. void refreshAll() const;
  57360. private:
  57361. PropertyHolderComponent (const PropertyHolderComponent&);
  57362. PropertyHolderComponent& operator= (const PropertyHolderComponent&);
  57363. };
  57364. class PropertySectionComponent : public Component
  57365. {
  57366. public:
  57367. PropertySectionComponent (const String& sectionTitle,
  57368. const Array <PropertyComponent*>& newProperties,
  57369. const bool open)
  57370. : Component (sectionTitle),
  57371. titleHeight (sectionTitle.isNotEmpty() ? 22 : 0),
  57372. isOpen_ (open)
  57373. {
  57374. for (int i = newProperties.size(); --i >= 0;)
  57375. {
  57376. addAndMakeVisible (newProperties.getUnchecked(i));
  57377. newProperties.getUnchecked(i)->refresh();
  57378. }
  57379. }
  57380. ~PropertySectionComponent()
  57381. {
  57382. deleteAllChildren();
  57383. }
  57384. void paint (Graphics& g)
  57385. {
  57386. if (titleHeight > 0)
  57387. getLookAndFeel().drawPropertyPanelSectionHeader (g, getName(), isOpen(), getWidth(), titleHeight);
  57388. }
  57389. void resized()
  57390. {
  57391. int y = titleHeight;
  57392. for (int i = getNumChildComponents(); --i >= 0;)
  57393. {
  57394. PropertyComponent* const pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  57395. if (pec != 0)
  57396. {
  57397. const int prefH = pec->getPreferredHeight();
  57398. pec->setBounds (1, y, getWidth() - 2, prefH);
  57399. y += prefH;
  57400. }
  57401. }
  57402. }
  57403. int getPreferredHeight() const
  57404. {
  57405. int y = titleHeight;
  57406. if (isOpen())
  57407. {
  57408. for (int i = 0; i < getNumChildComponents(); ++i)
  57409. {
  57410. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  57411. if (pec != 0)
  57412. y += pec->getPreferredHeight();
  57413. }
  57414. }
  57415. return y;
  57416. }
  57417. void setOpen (const bool open)
  57418. {
  57419. if (isOpen_ != open)
  57420. {
  57421. isOpen_ = open;
  57422. for (int i = 0; i < getNumChildComponents(); ++i)
  57423. {
  57424. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  57425. if (pec != 0)
  57426. pec->setVisible (open);
  57427. }
  57428. // (unable to use the syntax findParentComponentOfClass <DragAndDropContainer> () because of a VC6 compiler bug)
  57429. PropertyPanel* const pp = findParentComponentOfClass ((PropertyPanel*) 0);
  57430. if (pp != 0)
  57431. pp->resized();
  57432. }
  57433. }
  57434. bool isOpen() const
  57435. {
  57436. return isOpen_;
  57437. }
  57438. void refreshAll() const
  57439. {
  57440. for (int i = 0; i < getNumChildComponents(); ++i)
  57441. {
  57442. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  57443. if (pec != 0)
  57444. pec->refresh();
  57445. }
  57446. }
  57447. void mouseDown (const MouseEvent&)
  57448. {
  57449. }
  57450. void mouseUp (const MouseEvent& e)
  57451. {
  57452. if (e.getMouseDownX() < titleHeight
  57453. && e.x < titleHeight
  57454. && e.y < titleHeight
  57455. && e.getNumberOfClicks() != 2)
  57456. {
  57457. setOpen (! isOpen());
  57458. }
  57459. }
  57460. void mouseDoubleClick (const MouseEvent& e)
  57461. {
  57462. if (e.y < titleHeight)
  57463. setOpen (! isOpen());
  57464. }
  57465. private:
  57466. int titleHeight;
  57467. bool isOpen_;
  57468. PropertySectionComponent (const PropertySectionComponent&);
  57469. PropertySectionComponent& operator= (const PropertySectionComponent&);
  57470. };
  57471. void PropertyPanel::PropertyHolderComponent::updateLayout (const int width)
  57472. {
  57473. int y = 0;
  57474. for (int i = getNumChildComponents(); --i >= 0;)
  57475. {
  57476. PropertySectionComponent* const section
  57477. = dynamic_cast <PropertySectionComponent*> (getChildComponent (i));
  57478. if (section != 0)
  57479. {
  57480. const int prefH = section->getPreferredHeight();
  57481. section->setBounds (0, y, width, prefH);
  57482. y += prefH;
  57483. }
  57484. }
  57485. setSize (width, y);
  57486. repaint();
  57487. }
  57488. void PropertyPanel::PropertyHolderComponent::refreshAll() const
  57489. {
  57490. for (int i = getNumChildComponents(); --i >= 0;)
  57491. {
  57492. PropertySectionComponent* const section
  57493. = dynamic_cast <PropertySectionComponent*> (getChildComponent (i));
  57494. if (section != 0)
  57495. section->refreshAll();
  57496. }
  57497. }
  57498. PropertyPanel::PropertyPanel()
  57499. {
  57500. messageWhenEmpty = TRANS("(nothing selected)");
  57501. addAndMakeVisible (&viewport);
  57502. viewport.setViewedComponent (propertyHolderComponent = new PropertyHolderComponent());
  57503. viewport.setFocusContainer (true);
  57504. }
  57505. PropertyPanel::~PropertyPanel()
  57506. {
  57507. clear();
  57508. }
  57509. void PropertyPanel::paint (Graphics& g)
  57510. {
  57511. if (propertyHolderComponent->getNumChildComponents() == 0)
  57512. {
  57513. g.setColour (Colours::black.withAlpha (0.5f));
  57514. g.setFont (14.0f);
  57515. g.drawText (messageWhenEmpty, 0, 0, getWidth(), 30,
  57516. Justification::centred, true);
  57517. }
  57518. }
  57519. void PropertyPanel::resized()
  57520. {
  57521. viewport.setBounds (0, 0, getWidth(), getHeight());
  57522. updatePropHolderLayout();
  57523. }
  57524. void PropertyPanel::clear()
  57525. {
  57526. if (propertyHolderComponent->getNumChildComponents() > 0)
  57527. {
  57528. propertyHolderComponent->deleteAllChildren();
  57529. repaint();
  57530. }
  57531. }
  57532. void PropertyPanel::addProperties (const Array <PropertyComponent*>& newProperties)
  57533. {
  57534. if (propertyHolderComponent->getNumChildComponents() == 0)
  57535. repaint();
  57536. propertyHolderComponent->addAndMakeVisible (new PropertySectionComponent (String::empty,
  57537. newProperties,
  57538. true), 0);
  57539. updatePropHolderLayout();
  57540. }
  57541. void PropertyPanel::addSection (const String& sectionTitle,
  57542. const Array <PropertyComponent*>& newProperties,
  57543. const bool shouldBeOpen)
  57544. {
  57545. jassert (sectionTitle.isNotEmpty());
  57546. if (propertyHolderComponent->getNumChildComponents() == 0)
  57547. repaint();
  57548. propertyHolderComponent->addAndMakeVisible (new PropertySectionComponent (sectionTitle,
  57549. newProperties,
  57550. shouldBeOpen), 0);
  57551. updatePropHolderLayout();
  57552. }
  57553. void PropertyPanel::updatePropHolderLayout() const
  57554. {
  57555. const int maxWidth = viewport.getMaximumVisibleWidth();
  57556. propertyHolderComponent->updateLayout (maxWidth);
  57557. const int newMaxWidth = viewport.getMaximumVisibleWidth();
  57558. if (maxWidth != newMaxWidth)
  57559. {
  57560. // need to do this twice because of scrollbars changing the size, etc.
  57561. propertyHolderComponent->updateLayout (newMaxWidth);
  57562. }
  57563. }
  57564. void PropertyPanel::refreshAll() const
  57565. {
  57566. propertyHolderComponent->refreshAll();
  57567. }
  57568. const StringArray PropertyPanel::getSectionNames() const
  57569. {
  57570. StringArray s;
  57571. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  57572. {
  57573. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  57574. if (section != 0 && section->getName().isNotEmpty())
  57575. s.add (section->getName());
  57576. }
  57577. return s;
  57578. }
  57579. bool PropertyPanel::isSectionOpen (const int sectionIndex) const
  57580. {
  57581. int index = 0;
  57582. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  57583. {
  57584. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  57585. if (section != 0 && section->getName().isNotEmpty())
  57586. {
  57587. if (index == sectionIndex)
  57588. return section->isOpen();
  57589. ++index;
  57590. }
  57591. }
  57592. return false;
  57593. }
  57594. void PropertyPanel::setSectionOpen (const int sectionIndex, const bool shouldBeOpen)
  57595. {
  57596. int index = 0;
  57597. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  57598. {
  57599. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  57600. if (section != 0 && section->getName().isNotEmpty())
  57601. {
  57602. if (index == sectionIndex)
  57603. {
  57604. section->setOpen (shouldBeOpen);
  57605. break;
  57606. }
  57607. ++index;
  57608. }
  57609. }
  57610. }
  57611. void PropertyPanel::setSectionEnabled (const int sectionIndex, const bool shouldBeEnabled)
  57612. {
  57613. int index = 0;
  57614. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  57615. {
  57616. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  57617. if (section != 0 && section->getName().isNotEmpty())
  57618. {
  57619. if (index == sectionIndex)
  57620. {
  57621. section->setEnabled (shouldBeEnabled);
  57622. break;
  57623. }
  57624. ++index;
  57625. }
  57626. }
  57627. }
  57628. XmlElement* PropertyPanel::getOpennessState() const
  57629. {
  57630. XmlElement* const xml = new XmlElement ("PROPERTYPANELSTATE");
  57631. xml->setAttribute ("scrollPos", viewport.getViewPositionY());
  57632. const StringArray sections (getSectionNames());
  57633. for (int i = 0; i < sections.size(); ++i)
  57634. {
  57635. if (sections[i].isNotEmpty())
  57636. {
  57637. XmlElement* const e = xml->createNewChildElement ("SECTION");
  57638. e->setAttribute ("name", sections[i]);
  57639. e->setAttribute ("open", isSectionOpen (i) ? 1 : 0);
  57640. }
  57641. }
  57642. return xml;
  57643. }
  57644. void PropertyPanel::restoreOpennessState (const XmlElement& xml)
  57645. {
  57646. if (xml.hasTagName ("PROPERTYPANELSTATE"))
  57647. {
  57648. const StringArray sections (getSectionNames());
  57649. forEachXmlChildElementWithTagName (xml, e, "SECTION")
  57650. {
  57651. setSectionOpen (sections.indexOf (e->getStringAttribute ("name")),
  57652. e->getBoolAttribute ("open"));
  57653. }
  57654. viewport.setViewPosition (viewport.getViewPositionX(),
  57655. xml.getIntAttribute ("scrollPos", viewport.getViewPositionY()));
  57656. }
  57657. }
  57658. void PropertyPanel::setMessageWhenEmpty (const String& newMessage)
  57659. {
  57660. if (messageWhenEmpty != newMessage)
  57661. {
  57662. messageWhenEmpty = newMessage;
  57663. repaint();
  57664. }
  57665. }
  57666. const String& PropertyPanel::getMessageWhenEmpty() const
  57667. {
  57668. return messageWhenEmpty;
  57669. }
  57670. END_JUCE_NAMESPACE
  57671. /*** End of inlined file: juce_PropertyPanel.cpp ***/
  57672. /*** Start of inlined file: juce_SliderPropertyComponent.cpp ***/
  57673. BEGIN_JUCE_NAMESPACE
  57674. SliderPropertyComponent::SliderPropertyComponent (const String& name,
  57675. const double rangeMin,
  57676. const double rangeMax,
  57677. const double interval,
  57678. const double skewFactor)
  57679. : PropertyComponent (name)
  57680. {
  57681. addAndMakeVisible (&slider);
  57682. slider.setRange (rangeMin, rangeMax, interval);
  57683. slider.setSkewFactor (skewFactor);
  57684. slider.setSliderStyle (Slider::LinearBar);
  57685. slider.addListener (this);
  57686. }
  57687. SliderPropertyComponent::SliderPropertyComponent (const Value& valueToControl,
  57688. const String& name,
  57689. const double rangeMin,
  57690. const double rangeMax,
  57691. const double interval,
  57692. const double skewFactor)
  57693. : PropertyComponent (name)
  57694. {
  57695. addAndMakeVisible (&slider);
  57696. slider.setRange (rangeMin, rangeMax, interval);
  57697. slider.setSkewFactor (skewFactor);
  57698. slider.setSliderStyle (Slider::LinearBar);
  57699. slider.getValueObject().referTo (valueToControl);
  57700. }
  57701. SliderPropertyComponent::~SliderPropertyComponent()
  57702. {
  57703. }
  57704. void SliderPropertyComponent::setValue (const double /*newValue*/)
  57705. {
  57706. }
  57707. double SliderPropertyComponent::getValue() const
  57708. {
  57709. return slider.getValue();
  57710. }
  57711. void SliderPropertyComponent::refresh()
  57712. {
  57713. slider.setValue (getValue(), false);
  57714. }
  57715. void SliderPropertyComponent::sliderValueChanged (Slider*)
  57716. {
  57717. if (getValue() != slider.getValue())
  57718. setValue (slider.getValue());
  57719. }
  57720. END_JUCE_NAMESPACE
  57721. /*** End of inlined file: juce_SliderPropertyComponent.cpp ***/
  57722. /*** Start of inlined file: juce_TextPropertyComponent.cpp ***/
  57723. BEGIN_JUCE_NAMESPACE
  57724. class TextPropLabel : public Label
  57725. {
  57726. TextPropertyComponent& owner;
  57727. int maxChars;
  57728. bool isMultiline;
  57729. public:
  57730. TextPropLabel (TextPropertyComponent& owner_,
  57731. const int maxChars_, const bool isMultiline_)
  57732. : Label (String::empty, String::empty),
  57733. owner (owner_),
  57734. maxChars (maxChars_),
  57735. isMultiline (isMultiline_)
  57736. {
  57737. setEditable (true, true, false);
  57738. setColour (backgroundColourId, Colours::white);
  57739. setColour (outlineColourId, findColour (ComboBox::outlineColourId));
  57740. }
  57741. ~TextPropLabel()
  57742. {
  57743. }
  57744. TextEditor* createEditorComponent()
  57745. {
  57746. TextEditor* const textEditor = Label::createEditorComponent();
  57747. textEditor->setInputRestrictions (maxChars);
  57748. if (isMultiline)
  57749. {
  57750. textEditor->setMultiLine (true, true);
  57751. textEditor->setReturnKeyStartsNewLine (true);
  57752. }
  57753. return textEditor;
  57754. }
  57755. void textWasEdited()
  57756. {
  57757. owner.textWasEdited();
  57758. }
  57759. };
  57760. TextPropertyComponent::TextPropertyComponent (const String& name,
  57761. const int maxNumChars,
  57762. const bool isMultiLine)
  57763. : PropertyComponent (name)
  57764. {
  57765. createEditor (maxNumChars, isMultiLine);
  57766. }
  57767. TextPropertyComponent::TextPropertyComponent (const Value& valueToControl,
  57768. const String& name,
  57769. const int maxNumChars,
  57770. const bool isMultiLine)
  57771. : PropertyComponent (name)
  57772. {
  57773. createEditor (maxNumChars, isMultiLine);
  57774. textEditor->getTextValue().referTo (valueToControl);
  57775. }
  57776. TextPropertyComponent::~TextPropertyComponent()
  57777. {
  57778. deleteAllChildren();
  57779. }
  57780. void TextPropertyComponent::setText (const String& newText)
  57781. {
  57782. textEditor->setText (newText, true);
  57783. }
  57784. const String TextPropertyComponent::getText() const
  57785. {
  57786. return textEditor->getText();
  57787. }
  57788. void TextPropertyComponent::createEditor (const int maxNumChars, const bool isMultiLine)
  57789. {
  57790. addAndMakeVisible (textEditor = new TextPropLabel (*this, maxNumChars, isMultiLine));
  57791. if (isMultiLine)
  57792. {
  57793. textEditor->setJustificationType (Justification::topLeft);
  57794. preferredHeight = 120;
  57795. }
  57796. }
  57797. void TextPropertyComponent::refresh()
  57798. {
  57799. textEditor->setText (getText(), false);
  57800. }
  57801. void TextPropertyComponent::textWasEdited()
  57802. {
  57803. const String newText (textEditor->getText());
  57804. if (getText() != newText)
  57805. setText (newText);
  57806. }
  57807. END_JUCE_NAMESPACE
  57808. /*** End of inlined file: juce_TextPropertyComponent.cpp ***/
  57809. /*** Start of inlined file: juce_AudioDeviceSelectorComponent.cpp ***/
  57810. BEGIN_JUCE_NAMESPACE
  57811. class SimpleDeviceManagerInputLevelMeter : public Component,
  57812. public Timer
  57813. {
  57814. public:
  57815. SimpleDeviceManagerInputLevelMeter (AudioDeviceManager* const manager_)
  57816. : manager (manager_),
  57817. level (0)
  57818. {
  57819. startTimer (50);
  57820. manager->enableInputLevelMeasurement (true);
  57821. }
  57822. ~SimpleDeviceManagerInputLevelMeter()
  57823. {
  57824. manager->enableInputLevelMeasurement (false);
  57825. }
  57826. void timerCallback()
  57827. {
  57828. const float newLevel = (float) manager->getCurrentInputLevel();
  57829. if (std::abs (level - newLevel) > 0.005f)
  57830. {
  57831. level = newLevel;
  57832. repaint();
  57833. }
  57834. }
  57835. void paint (Graphics& g)
  57836. {
  57837. getLookAndFeel().drawLevelMeter (g, getWidth(), getHeight(),
  57838. (float) exp (log (level) / 3.0)); // (add a bit of a skew to make the level more obvious)
  57839. }
  57840. private:
  57841. AudioDeviceManager* const manager;
  57842. float level;
  57843. SimpleDeviceManagerInputLevelMeter (const SimpleDeviceManagerInputLevelMeter&);
  57844. SimpleDeviceManagerInputLevelMeter& operator= (const SimpleDeviceManagerInputLevelMeter&);
  57845. };
  57846. class AudioDeviceSelectorComponent::MidiInputSelectorComponentListBox : public ListBox,
  57847. public ListBoxModel
  57848. {
  57849. public:
  57850. MidiInputSelectorComponentListBox (AudioDeviceManager& deviceManager_,
  57851. const String& noItemsMessage_,
  57852. const int minNumber_,
  57853. const int maxNumber_)
  57854. : ListBox (String::empty, 0),
  57855. deviceManager (deviceManager_),
  57856. noItemsMessage (noItemsMessage_),
  57857. minNumber (minNumber_),
  57858. maxNumber (maxNumber_)
  57859. {
  57860. items = MidiInput::getDevices();
  57861. setModel (this);
  57862. setOutlineThickness (1);
  57863. }
  57864. ~MidiInputSelectorComponentListBox()
  57865. {
  57866. }
  57867. int getNumRows()
  57868. {
  57869. return items.size();
  57870. }
  57871. void paintListBoxItem (int row,
  57872. Graphics& g,
  57873. int width, int height,
  57874. bool rowIsSelected)
  57875. {
  57876. if (((unsigned int) row) < (unsigned int) items.size())
  57877. {
  57878. if (rowIsSelected)
  57879. g.fillAll (findColour (TextEditor::highlightColourId)
  57880. .withMultipliedAlpha (0.3f));
  57881. const String item (items [row]);
  57882. bool enabled = deviceManager.isMidiInputEnabled (item);
  57883. const int x = getTickX();
  57884. const float tickW = height * 0.75f;
  57885. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  57886. enabled, true, true, false);
  57887. g.setFont (height * 0.6f);
  57888. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  57889. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  57890. }
  57891. }
  57892. void listBoxItemClicked (int row, const MouseEvent& e)
  57893. {
  57894. selectRow (row);
  57895. if (e.x < getTickX())
  57896. flipEnablement (row);
  57897. }
  57898. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  57899. {
  57900. flipEnablement (row);
  57901. }
  57902. void returnKeyPressed (int row)
  57903. {
  57904. flipEnablement (row);
  57905. }
  57906. void paint (Graphics& g)
  57907. {
  57908. ListBox::paint (g);
  57909. if (items.size() == 0)
  57910. {
  57911. g.setColour (Colours::grey);
  57912. g.setFont (13.0f);
  57913. g.drawText (noItemsMessage,
  57914. 0, 0, getWidth(), getHeight() / 2,
  57915. Justification::centred, true);
  57916. }
  57917. }
  57918. int getBestHeight (const int preferredHeight)
  57919. {
  57920. const int extra = getOutlineThickness() * 2;
  57921. return jmax (getRowHeight() * 2 + extra,
  57922. jmin (getRowHeight() * getNumRows() + extra,
  57923. preferredHeight));
  57924. }
  57925. juce_UseDebuggingNewOperator
  57926. private:
  57927. AudioDeviceManager& deviceManager;
  57928. const String noItemsMessage;
  57929. StringArray items;
  57930. int minNumber, maxNumber;
  57931. void flipEnablement (const int row)
  57932. {
  57933. if (((unsigned int) row) < (unsigned int) items.size())
  57934. {
  57935. const String item (items [row]);
  57936. deviceManager.setMidiInputEnabled (item, ! deviceManager.isMidiInputEnabled (item));
  57937. }
  57938. }
  57939. int getTickX() const
  57940. {
  57941. return getRowHeight() + 5;
  57942. }
  57943. MidiInputSelectorComponentListBox (const MidiInputSelectorComponentListBox&);
  57944. MidiInputSelectorComponentListBox& operator= (const MidiInputSelectorComponentListBox&);
  57945. };
  57946. class AudioDeviceSettingsPanel : public Component,
  57947. public ComboBoxListener,
  57948. public ChangeListener,
  57949. public ButtonListener
  57950. {
  57951. public:
  57952. AudioDeviceSettingsPanel (AudioIODeviceType* type_,
  57953. AudioIODeviceType::DeviceSetupDetails& setup_,
  57954. const bool hideAdvancedOptionsWithButton)
  57955. : type (type_),
  57956. setup (setup_)
  57957. {
  57958. if (hideAdvancedOptionsWithButton)
  57959. {
  57960. addAndMakeVisible (showAdvancedSettingsButton = new TextButton (TRANS("Show advanced settings...")));
  57961. showAdvancedSettingsButton->addButtonListener (this);
  57962. }
  57963. type->scanForDevices();
  57964. setup.manager->addChangeListener (this);
  57965. changeListenerCallback (0);
  57966. }
  57967. ~AudioDeviceSettingsPanel()
  57968. {
  57969. setup.manager->removeChangeListener (this);
  57970. }
  57971. void resized()
  57972. {
  57973. const int lx = proportionOfWidth (0.35f);
  57974. const int w = proportionOfWidth (0.4f);
  57975. const int h = 24;
  57976. const int space = 6;
  57977. const int dh = h + space;
  57978. int y = 0;
  57979. if (outputDeviceDropDown != 0)
  57980. {
  57981. outputDeviceDropDown->setBounds (lx, y, w, h);
  57982. if (testButton != 0)
  57983. testButton->setBounds (proportionOfWidth (0.77f),
  57984. outputDeviceDropDown->getY(),
  57985. proportionOfWidth (0.18f),
  57986. h);
  57987. y += dh;
  57988. }
  57989. if (inputDeviceDropDown != 0)
  57990. {
  57991. inputDeviceDropDown->setBounds (lx, y, w, h);
  57992. inputLevelMeter->setBounds (proportionOfWidth (0.77f),
  57993. inputDeviceDropDown->getY(),
  57994. proportionOfWidth (0.18f),
  57995. h);
  57996. y += dh;
  57997. }
  57998. const int maxBoxHeight = 100;//(getHeight() - y - dh * 2) / numBoxes;
  57999. if (outputChanList != 0)
  58000. {
  58001. const int bh = outputChanList->getBestHeight (maxBoxHeight);
  58002. outputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  58003. y += bh + space;
  58004. }
  58005. if (inputChanList != 0)
  58006. {
  58007. const int bh = inputChanList->getBestHeight (maxBoxHeight);
  58008. inputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  58009. y += bh + space;
  58010. }
  58011. y += space * 2;
  58012. if (showAdvancedSettingsButton != 0)
  58013. {
  58014. showAdvancedSettingsButton->changeWidthToFitText (h);
  58015. showAdvancedSettingsButton->setTopLeftPosition (lx, y);
  58016. }
  58017. if (sampleRateDropDown != 0)
  58018. {
  58019. sampleRateDropDown->setVisible (showAdvancedSettingsButton == 0
  58020. || ! showAdvancedSettingsButton->isVisible());
  58021. sampleRateDropDown->setBounds (lx, y, w, h);
  58022. y += dh;
  58023. }
  58024. if (bufferSizeDropDown != 0)
  58025. {
  58026. bufferSizeDropDown->setVisible (showAdvancedSettingsButton == 0
  58027. || ! showAdvancedSettingsButton->isVisible());
  58028. bufferSizeDropDown->setBounds (lx, y, w, h);
  58029. y += dh;
  58030. }
  58031. if (showUIButton != 0)
  58032. {
  58033. showUIButton->setVisible (showAdvancedSettingsButton == 0
  58034. || ! showAdvancedSettingsButton->isVisible());
  58035. showUIButton->changeWidthToFitText (h);
  58036. showUIButton->setTopLeftPosition (lx, y);
  58037. }
  58038. }
  58039. void comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  58040. {
  58041. if (comboBoxThatHasChanged == 0)
  58042. return;
  58043. AudioDeviceManager::AudioDeviceSetup config;
  58044. setup.manager->getAudioDeviceSetup (config);
  58045. String error;
  58046. if (comboBoxThatHasChanged == outputDeviceDropDown
  58047. || comboBoxThatHasChanged == inputDeviceDropDown)
  58048. {
  58049. if (outputDeviceDropDown != 0)
  58050. config.outputDeviceName = outputDeviceDropDown->getSelectedId() < 0 ? String::empty
  58051. : outputDeviceDropDown->getText();
  58052. if (inputDeviceDropDown != 0)
  58053. config.inputDeviceName = inputDeviceDropDown->getSelectedId() < 0 ? String::empty
  58054. : inputDeviceDropDown->getText();
  58055. if (! type->hasSeparateInputsAndOutputs())
  58056. config.inputDeviceName = config.outputDeviceName;
  58057. if (comboBoxThatHasChanged == inputDeviceDropDown)
  58058. config.useDefaultInputChannels = true;
  58059. else
  58060. config.useDefaultOutputChannels = true;
  58061. error = setup.manager->setAudioDeviceSetup (config, true);
  58062. showCorrectDeviceName (inputDeviceDropDown, true);
  58063. showCorrectDeviceName (outputDeviceDropDown, false);
  58064. updateControlPanelButton();
  58065. resized();
  58066. }
  58067. else if (comboBoxThatHasChanged == sampleRateDropDown)
  58068. {
  58069. if (sampleRateDropDown->getSelectedId() > 0)
  58070. {
  58071. config.sampleRate = sampleRateDropDown->getSelectedId();
  58072. error = setup.manager->setAudioDeviceSetup (config, true);
  58073. }
  58074. }
  58075. else if (comboBoxThatHasChanged == bufferSizeDropDown)
  58076. {
  58077. if (bufferSizeDropDown->getSelectedId() > 0)
  58078. {
  58079. config.bufferSize = bufferSizeDropDown->getSelectedId();
  58080. error = setup.manager->setAudioDeviceSetup (config, true);
  58081. }
  58082. }
  58083. if (error.isNotEmpty())
  58084. {
  58085. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  58086. "Error when trying to open audio device!",
  58087. error);
  58088. }
  58089. }
  58090. void buttonClicked (Button* button)
  58091. {
  58092. if (button == showAdvancedSettingsButton)
  58093. {
  58094. showAdvancedSettingsButton->setVisible (false);
  58095. resized();
  58096. }
  58097. else if (button == showUIButton)
  58098. {
  58099. AudioIODevice* const device = setup.manager->getCurrentAudioDevice();
  58100. if (device != 0 && device->showControlPanel())
  58101. {
  58102. setup.manager->closeAudioDevice();
  58103. setup.manager->restartLastAudioDevice();
  58104. getTopLevelComponent()->toFront (true);
  58105. }
  58106. }
  58107. else if (button == testButton && testButton != 0)
  58108. {
  58109. setup.manager->playTestSound();
  58110. }
  58111. }
  58112. void updateControlPanelButton()
  58113. {
  58114. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  58115. showUIButton = 0;
  58116. if (currentDevice != 0 && currentDevice->hasControlPanel())
  58117. {
  58118. addAndMakeVisible (showUIButton = new TextButton (TRANS ("show this device's control panel"),
  58119. TRANS ("opens the device's own control panel")));
  58120. showUIButton->addButtonListener (this);
  58121. }
  58122. resized();
  58123. }
  58124. void changeListenerCallback (void*)
  58125. {
  58126. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  58127. if (setup.maxNumOutputChannels > 0 || ! type->hasSeparateInputsAndOutputs())
  58128. {
  58129. if (outputDeviceDropDown == 0)
  58130. {
  58131. outputDeviceDropDown = new ComboBox (String::empty);
  58132. outputDeviceDropDown->addListener (this);
  58133. addAndMakeVisible (outputDeviceDropDown);
  58134. outputDeviceLabel = new Label (String::empty,
  58135. type->hasSeparateInputsAndOutputs() ? TRANS ("output:")
  58136. : TRANS ("device:"));
  58137. outputDeviceLabel->attachToComponent (outputDeviceDropDown, true);
  58138. if (setup.maxNumOutputChannels > 0)
  58139. {
  58140. addAndMakeVisible (testButton = new TextButton (TRANS ("Test")));
  58141. testButton->addButtonListener (this);
  58142. }
  58143. }
  58144. addNamesToDeviceBox (*outputDeviceDropDown, false);
  58145. }
  58146. if (setup.maxNumInputChannels > 0 && type->hasSeparateInputsAndOutputs())
  58147. {
  58148. if (inputDeviceDropDown == 0)
  58149. {
  58150. inputDeviceDropDown = new ComboBox (String::empty);
  58151. inputDeviceDropDown->addListener (this);
  58152. addAndMakeVisible (inputDeviceDropDown);
  58153. inputDeviceLabel = new Label (String::empty, TRANS ("input:"));
  58154. inputDeviceLabel->attachToComponent (inputDeviceDropDown, true);
  58155. addAndMakeVisible (inputLevelMeter
  58156. = new SimpleDeviceManagerInputLevelMeter (setup.manager));
  58157. }
  58158. addNamesToDeviceBox (*inputDeviceDropDown, true);
  58159. }
  58160. updateControlPanelButton();
  58161. showCorrectDeviceName (inputDeviceDropDown, true);
  58162. showCorrectDeviceName (outputDeviceDropDown, false);
  58163. if (currentDevice != 0)
  58164. {
  58165. if (setup.maxNumOutputChannels > 0
  58166. && setup.minNumOutputChannels < setup.manager->getCurrentAudioDevice()->getOutputChannelNames().size())
  58167. {
  58168. if (outputChanList == 0)
  58169. {
  58170. addAndMakeVisible (outputChanList
  58171. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioOutputType,
  58172. TRANS ("(no audio output channels found)")));
  58173. outputChanLabel = new Label (String::empty, TRANS ("active output channels:"));
  58174. outputChanLabel->attachToComponent (outputChanList, true);
  58175. }
  58176. outputChanList->refresh();
  58177. }
  58178. else
  58179. {
  58180. outputChanLabel = 0;
  58181. outputChanList = 0;
  58182. }
  58183. if (setup.maxNumInputChannels > 0
  58184. && setup.minNumInputChannels < setup.manager->getCurrentAudioDevice()->getInputChannelNames().size())
  58185. {
  58186. if (inputChanList == 0)
  58187. {
  58188. addAndMakeVisible (inputChanList
  58189. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioInputType,
  58190. TRANS ("(no audio input channels found)")));
  58191. inputChanLabel = new Label (String::empty, TRANS ("active input channels:"));
  58192. inputChanLabel->attachToComponent (inputChanList, true);
  58193. }
  58194. inputChanList->refresh();
  58195. }
  58196. else
  58197. {
  58198. inputChanLabel = 0;
  58199. inputChanList = 0;
  58200. }
  58201. // sample rate..
  58202. {
  58203. if (sampleRateDropDown == 0)
  58204. {
  58205. addAndMakeVisible (sampleRateDropDown = new ComboBox (String::empty));
  58206. sampleRateDropDown->addListener (this);
  58207. sampleRateLabel = new Label (String::empty, TRANS ("sample rate:"));
  58208. sampleRateLabel->attachToComponent (sampleRateDropDown, true);
  58209. }
  58210. else
  58211. {
  58212. sampleRateDropDown->clear();
  58213. sampleRateDropDown->removeListener (this);
  58214. }
  58215. const int numRates = currentDevice->getNumSampleRates();
  58216. for (int i = 0; i < numRates; ++i)
  58217. {
  58218. const int rate = roundToInt (currentDevice->getSampleRate (i));
  58219. sampleRateDropDown->addItem (String (rate) + " Hz", rate);
  58220. }
  58221. sampleRateDropDown->setSelectedId (roundToInt (currentDevice->getCurrentSampleRate()), true);
  58222. sampleRateDropDown->addListener (this);
  58223. }
  58224. // buffer size
  58225. {
  58226. if (bufferSizeDropDown == 0)
  58227. {
  58228. addAndMakeVisible (bufferSizeDropDown = new ComboBox (String::empty));
  58229. bufferSizeDropDown->addListener (this);
  58230. bufferSizeLabel = new Label (String::empty, TRANS ("audio buffer size:"));
  58231. bufferSizeLabel->attachToComponent (bufferSizeDropDown, true);
  58232. }
  58233. else
  58234. {
  58235. bufferSizeDropDown->clear();
  58236. }
  58237. const int numBufferSizes = currentDevice->getNumBufferSizesAvailable();
  58238. double currentRate = currentDevice->getCurrentSampleRate();
  58239. if (currentRate == 0)
  58240. currentRate = 48000.0;
  58241. for (int i = 0; i < numBufferSizes; ++i)
  58242. {
  58243. const int bs = currentDevice->getBufferSizeSamples (i);
  58244. bufferSizeDropDown->addItem (String (bs)
  58245. + " samples ("
  58246. + String (bs * 1000.0 / currentRate, 1)
  58247. + " ms)",
  58248. bs);
  58249. }
  58250. bufferSizeDropDown->setSelectedId (currentDevice->getCurrentBufferSizeSamples(), true);
  58251. }
  58252. }
  58253. else
  58254. {
  58255. jassert (setup.manager->getCurrentAudioDevice() == 0); // not the correct device type!
  58256. sampleRateLabel = 0;
  58257. bufferSizeLabel = 0;
  58258. sampleRateDropDown = 0;
  58259. bufferSizeDropDown = 0;
  58260. if (outputDeviceDropDown != 0)
  58261. outputDeviceDropDown->setSelectedId (-1, true);
  58262. if (inputDeviceDropDown != 0)
  58263. inputDeviceDropDown->setSelectedId (-1, true);
  58264. }
  58265. resized();
  58266. setSize (getWidth(), getLowestY() + 4);
  58267. }
  58268. private:
  58269. AudioIODeviceType* const type;
  58270. const AudioIODeviceType::DeviceSetupDetails setup;
  58271. ScopedPointer<ComboBox> outputDeviceDropDown, inputDeviceDropDown, sampleRateDropDown, bufferSizeDropDown;
  58272. ScopedPointer<Label> outputDeviceLabel, inputDeviceLabel, sampleRateLabel, bufferSizeLabel, inputChanLabel, outputChanLabel;
  58273. ScopedPointer<TextButton> testButton;
  58274. ScopedPointer<Component> inputLevelMeter;
  58275. ScopedPointer<TextButton> showUIButton, showAdvancedSettingsButton;
  58276. void showCorrectDeviceName (ComboBox* const box, const bool isInput)
  58277. {
  58278. if (box != 0)
  58279. {
  58280. AudioIODevice* const currentDevice = dynamic_cast <AudioIODevice*> (setup.manager->getCurrentAudioDevice());
  58281. const int index = type->getIndexOfDevice (currentDevice, isInput);
  58282. box->setSelectedId (index + 1, true);
  58283. if (testButton != 0 && ! isInput)
  58284. testButton->setEnabled (index >= 0);
  58285. }
  58286. }
  58287. void addNamesToDeviceBox (ComboBox& combo, bool isInputs)
  58288. {
  58289. const StringArray devs (type->getDeviceNames (isInputs));
  58290. combo.clear (true);
  58291. for (int i = 0; i < devs.size(); ++i)
  58292. combo.addItem (devs[i], i + 1);
  58293. combo.addItem (TRANS("<< none >>"), -1);
  58294. combo.setSelectedId (-1, true);
  58295. }
  58296. int getLowestY() const
  58297. {
  58298. int y = 0;
  58299. for (int i = getNumChildComponents(); --i >= 0;)
  58300. y = jmax (y, getChildComponent (i)->getBottom());
  58301. return y;
  58302. }
  58303. public:
  58304. class ChannelSelectorListBox : public ListBox,
  58305. public ListBoxModel
  58306. {
  58307. public:
  58308. enum BoxType
  58309. {
  58310. audioInputType,
  58311. audioOutputType
  58312. };
  58313. ChannelSelectorListBox (const AudioIODeviceType::DeviceSetupDetails& setup_,
  58314. const BoxType type_,
  58315. const String& noItemsMessage_)
  58316. : ListBox (String::empty, 0),
  58317. setup (setup_),
  58318. type (type_),
  58319. noItemsMessage (noItemsMessage_)
  58320. {
  58321. refresh();
  58322. setModel (this);
  58323. setOutlineThickness (1);
  58324. }
  58325. ~ChannelSelectorListBox()
  58326. {
  58327. }
  58328. void refresh()
  58329. {
  58330. items.clear();
  58331. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  58332. if (currentDevice != 0)
  58333. {
  58334. if (type == audioInputType)
  58335. items = currentDevice->getInputChannelNames();
  58336. else if (type == audioOutputType)
  58337. items = currentDevice->getOutputChannelNames();
  58338. if (setup.useStereoPairs)
  58339. {
  58340. StringArray pairs;
  58341. for (int i = 0; i < items.size(); i += 2)
  58342. {
  58343. const String name (items[i]);
  58344. const String name2 (items[i + 1]);
  58345. String commonBit;
  58346. for (int j = 0; j < name.length(); ++j)
  58347. if (name.substring (0, j).equalsIgnoreCase (name2.substring (0, j)))
  58348. commonBit = name.substring (0, j);
  58349. // Make sure we only split the name at a space, because otherwise, things
  58350. // like "input 11" + "input 12" would become "input 11 + 2"
  58351. while (commonBit.isNotEmpty() && ! CharacterFunctions::isWhitespace (commonBit.getLastCharacter()))
  58352. commonBit = commonBit.dropLastCharacters (1);
  58353. pairs.add (name.trim() + " + " + name2.substring (commonBit.length()).trim());
  58354. }
  58355. items = pairs;
  58356. }
  58357. }
  58358. updateContent();
  58359. repaint();
  58360. }
  58361. int getNumRows()
  58362. {
  58363. return items.size();
  58364. }
  58365. void paintListBoxItem (int row,
  58366. Graphics& g,
  58367. int width, int height,
  58368. bool rowIsSelected)
  58369. {
  58370. if (((unsigned int) row) < (unsigned int) items.size())
  58371. {
  58372. if (rowIsSelected)
  58373. g.fillAll (findColour (TextEditor::highlightColourId)
  58374. .withMultipliedAlpha (0.3f));
  58375. const String item (items [row]);
  58376. bool enabled = false;
  58377. AudioDeviceManager::AudioDeviceSetup config;
  58378. setup.manager->getAudioDeviceSetup (config);
  58379. if (setup.useStereoPairs)
  58380. {
  58381. if (type == audioInputType)
  58382. enabled = config.inputChannels [row * 2] || config.inputChannels [row * 2 + 1];
  58383. else if (type == audioOutputType)
  58384. enabled = config.outputChannels [row * 2] || config.outputChannels [row * 2 + 1];
  58385. }
  58386. else
  58387. {
  58388. if (type == audioInputType)
  58389. enabled = config.inputChannels [row];
  58390. else if (type == audioOutputType)
  58391. enabled = config.outputChannels [row];
  58392. }
  58393. const int x = getTickX();
  58394. const float tickW = height * 0.75f;
  58395. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  58396. enabled, true, true, false);
  58397. g.setFont (height * 0.6f);
  58398. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  58399. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  58400. }
  58401. }
  58402. void listBoxItemClicked (int row, const MouseEvent& e)
  58403. {
  58404. selectRow (row);
  58405. if (e.x < getTickX())
  58406. flipEnablement (row);
  58407. }
  58408. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  58409. {
  58410. flipEnablement (row);
  58411. }
  58412. void returnKeyPressed (int row)
  58413. {
  58414. flipEnablement (row);
  58415. }
  58416. void paint (Graphics& g)
  58417. {
  58418. ListBox::paint (g);
  58419. if (items.size() == 0)
  58420. {
  58421. g.setColour (Colours::grey);
  58422. g.setFont (13.0f);
  58423. g.drawText (noItemsMessage,
  58424. 0, 0, getWidth(), getHeight() / 2,
  58425. Justification::centred, true);
  58426. }
  58427. }
  58428. int getBestHeight (int maxHeight)
  58429. {
  58430. return getRowHeight() * jlimit (2, jmax (2, maxHeight / getRowHeight()),
  58431. getNumRows())
  58432. + getOutlineThickness() * 2;
  58433. }
  58434. juce_UseDebuggingNewOperator
  58435. private:
  58436. const AudioIODeviceType::DeviceSetupDetails setup;
  58437. const BoxType type;
  58438. const String noItemsMessage;
  58439. StringArray items;
  58440. void flipEnablement (const int row)
  58441. {
  58442. jassert (type == audioInputType || type == audioOutputType);
  58443. if (((unsigned int) row) < (unsigned int) items.size())
  58444. {
  58445. AudioDeviceManager::AudioDeviceSetup config;
  58446. setup.manager->getAudioDeviceSetup (config);
  58447. if (setup.useStereoPairs)
  58448. {
  58449. BigInteger bits;
  58450. BigInteger& original = (type == audioInputType ? config.inputChannels
  58451. : config.outputChannels);
  58452. int i;
  58453. for (i = 0; i < 256; i += 2)
  58454. bits.setBit (i / 2, original [i] || original [i + 1]);
  58455. if (type == audioInputType)
  58456. {
  58457. config.useDefaultInputChannels = false;
  58458. flipBit (bits, row, setup.minNumInputChannels / 2, setup.maxNumInputChannels / 2);
  58459. }
  58460. else
  58461. {
  58462. config.useDefaultOutputChannels = false;
  58463. flipBit (bits, row, setup.minNumOutputChannels / 2, setup.maxNumOutputChannels / 2);
  58464. }
  58465. for (i = 0; i < 256; ++i)
  58466. original.setBit (i, bits [i / 2]);
  58467. }
  58468. else
  58469. {
  58470. if (type == audioInputType)
  58471. {
  58472. config.useDefaultInputChannels = false;
  58473. flipBit (config.inputChannels, row, setup.minNumInputChannels, setup.maxNumInputChannels);
  58474. }
  58475. else
  58476. {
  58477. config.useDefaultOutputChannels = false;
  58478. flipBit (config.outputChannels, row, setup.minNumOutputChannels, setup.maxNumOutputChannels);
  58479. }
  58480. }
  58481. String error (setup.manager->setAudioDeviceSetup (config, true));
  58482. if (! error.isEmpty())
  58483. {
  58484. //xxx
  58485. }
  58486. }
  58487. }
  58488. static void flipBit (BigInteger& chans, int index, int minNumber, int maxNumber)
  58489. {
  58490. const int numActive = chans.countNumberOfSetBits();
  58491. if (chans [index])
  58492. {
  58493. if (numActive > minNumber)
  58494. chans.setBit (index, false);
  58495. }
  58496. else
  58497. {
  58498. if (numActive >= maxNumber)
  58499. {
  58500. const int firstActiveChan = chans.findNextSetBit();
  58501. chans.setBit (index > firstActiveChan
  58502. ? firstActiveChan : chans.getHighestBit(),
  58503. false);
  58504. }
  58505. chans.setBit (index, true);
  58506. }
  58507. }
  58508. int getTickX() const
  58509. {
  58510. return getRowHeight() + 5;
  58511. }
  58512. ChannelSelectorListBox (const ChannelSelectorListBox&);
  58513. ChannelSelectorListBox& operator= (const ChannelSelectorListBox&);
  58514. };
  58515. private:
  58516. ScopedPointer<ChannelSelectorListBox> inputChanList, outputChanList;
  58517. AudioDeviceSettingsPanel (const AudioDeviceSettingsPanel&);
  58518. AudioDeviceSettingsPanel& operator= (const AudioDeviceSettingsPanel&);
  58519. };
  58520. AudioDeviceSelectorComponent::AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager_,
  58521. const int minInputChannels_,
  58522. const int maxInputChannels_,
  58523. const int minOutputChannels_,
  58524. const int maxOutputChannels_,
  58525. const bool showMidiInputOptions,
  58526. const bool showMidiOutputSelector,
  58527. const bool showChannelsAsStereoPairs_,
  58528. const bool hideAdvancedOptionsWithButton_)
  58529. : deviceManager (deviceManager_),
  58530. deviceTypeDropDown (0),
  58531. deviceTypeDropDownLabel (0),
  58532. minOutputChannels (minOutputChannels_),
  58533. maxOutputChannels (maxOutputChannels_),
  58534. minInputChannels (minInputChannels_),
  58535. maxInputChannels (maxInputChannels_),
  58536. showChannelsAsStereoPairs (showChannelsAsStereoPairs_),
  58537. hideAdvancedOptionsWithButton (hideAdvancedOptionsWithButton_)
  58538. {
  58539. jassert (minOutputChannels >= 0 && minOutputChannels <= maxOutputChannels);
  58540. jassert (minInputChannels >= 0 && minInputChannels <= maxInputChannels);
  58541. if (deviceManager_.getAvailableDeviceTypes().size() > 1)
  58542. {
  58543. deviceTypeDropDown = new ComboBox (String::empty);
  58544. for (int i = 0; i < deviceManager_.getAvailableDeviceTypes().size(); ++i)
  58545. {
  58546. deviceTypeDropDown
  58547. ->addItem (deviceManager_.getAvailableDeviceTypes().getUnchecked(i)->getTypeName(),
  58548. i + 1);
  58549. }
  58550. addAndMakeVisible (deviceTypeDropDown);
  58551. deviceTypeDropDown->addListener (this);
  58552. deviceTypeDropDownLabel = new Label (String::empty, TRANS ("audio device type:"));
  58553. deviceTypeDropDownLabel->setJustificationType (Justification::centredRight);
  58554. deviceTypeDropDownLabel->attachToComponent (deviceTypeDropDown, true);
  58555. }
  58556. if (showMidiInputOptions)
  58557. {
  58558. addAndMakeVisible (midiInputsList
  58559. = new MidiInputSelectorComponentListBox (deviceManager,
  58560. TRANS("(no midi inputs available)"),
  58561. 0, 0));
  58562. midiInputsLabel = new Label (String::empty, TRANS ("active midi inputs:"));
  58563. midiInputsLabel->setJustificationType (Justification::topRight);
  58564. midiInputsLabel->attachToComponent (midiInputsList, true);
  58565. }
  58566. else
  58567. {
  58568. midiInputsList = 0;
  58569. midiInputsLabel = 0;
  58570. }
  58571. if (showMidiOutputSelector)
  58572. {
  58573. addAndMakeVisible (midiOutputSelector = new ComboBox (String::empty));
  58574. midiOutputSelector->addListener (this);
  58575. midiOutputLabel = new Label ("lm", TRANS("Midi Output:"));
  58576. midiOutputLabel->attachToComponent (midiOutputSelector, true);
  58577. }
  58578. else
  58579. {
  58580. midiOutputSelector = 0;
  58581. midiOutputLabel = 0;
  58582. }
  58583. deviceManager_.addChangeListener (this);
  58584. changeListenerCallback (0);
  58585. }
  58586. AudioDeviceSelectorComponent::~AudioDeviceSelectorComponent()
  58587. {
  58588. deviceManager.removeChangeListener (this);
  58589. }
  58590. void AudioDeviceSelectorComponent::resized()
  58591. {
  58592. const int lx = proportionOfWidth (0.35f);
  58593. const int w = proportionOfWidth (0.4f);
  58594. const int h = 24;
  58595. const int space = 6;
  58596. const int dh = h + space;
  58597. int y = 15;
  58598. if (deviceTypeDropDown != 0)
  58599. {
  58600. deviceTypeDropDown->setBounds (lx, y, proportionOfWidth (0.3f), h);
  58601. y += dh + space * 2;
  58602. }
  58603. if (audioDeviceSettingsComp != 0)
  58604. {
  58605. audioDeviceSettingsComp->setBounds (0, y, getWidth(), audioDeviceSettingsComp->getHeight());
  58606. y += audioDeviceSettingsComp->getHeight() + space;
  58607. }
  58608. if (midiInputsList != 0)
  58609. {
  58610. const int bh = midiInputsList->getBestHeight (jmin (h * 8, getHeight() - y - space - h));
  58611. midiInputsList->setBounds (lx, y, w, bh);
  58612. y += bh + space;
  58613. }
  58614. if (midiOutputSelector != 0)
  58615. midiOutputSelector->setBounds (lx, y, w, h);
  58616. }
  58617. void AudioDeviceSelectorComponent::childBoundsChanged (Component* child)
  58618. {
  58619. if (child == audioDeviceSettingsComp)
  58620. resized();
  58621. }
  58622. void AudioDeviceSelectorComponent::buttonClicked (Button*)
  58623. {
  58624. AudioIODevice* const device = deviceManager.getCurrentAudioDevice();
  58625. if (device != 0 && device->hasControlPanel())
  58626. {
  58627. if (device->showControlPanel())
  58628. deviceManager.restartLastAudioDevice();
  58629. getTopLevelComponent()->toFront (true);
  58630. }
  58631. }
  58632. void AudioDeviceSelectorComponent::comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  58633. {
  58634. if (comboBoxThatHasChanged == deviceTypeDropDown)
  58635. {
  58636. AudioIODeviceType* const type = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown->getSelectedId() - 1];
  58637. if (type != 0)
  58638. {
  58639. audioDeviceSettingsComp = 0;
  58640. deviceManager.setCurrentAudioDeviceType (type->getTypeName(), true);
  58641. changeListenerCallback (0); // needed in case the type hasn't actally changed
  58642. }
  58643. }
  58644. else if (comboBoxThatHasChanged == midiOutputSelector)
  58645. {
  58646. deviceManager.setDefaultMidiOutput (midiOutputSelector->getText());
  58647. }
  58648. }
  58649. void AudioDeviceSelectorComponent::changeListenerCallback (void*)
  58650. {
  58651. if (deviceTypeDropDown != 0)
  58652. {
  58653. deviceTypeDropDown->setText (deviceManager.getCurrentAudioDeviceType(), false);
  58654. }
  58655. if (audioDeviceSettingsComp == 0
  58656. || audioDeviceSettingsCompType != deviceManager.getCurrentAudioDeviceType())
  58657. {
  58658. audioDeviceSettingsCompType = deviceManager.getCurrentAudioDeviceType();
  58659. audioDeviceSettingsComp = 0;
  58660. AudioIODeviceType* const type
  58661. = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown == 0
  58662. ? 0 : deviceTypeDropDown->getSelectedId() - 1];
  58663. if (type != 0)
  58664. {
  58665. AudioIODeviceType::DeviceSetupDetails details;
  58666. details.manager = &deviceManager;
  58667. details.minNumInputChannels = minInputChannels;
  58668. details.maxNumInputChannels = maxInputChannels;
  58669. details.minNumOutputChannels = minOutputChannels;
  58670. details.maxNumOutputChannels = maxOutputChannels;
  58671. details.useStereoPairs = showChannelsAsStereoPairs;
  58672. audioDeviceSettingsComp = new AudioDeviceSettingsPanel (type, details, hideAdvancedOptionsWithButton);
  58673. if (audioDeviceSettingsComp != 0)
  58674. {
  58675. addAndMakeVisible (audioDeviceSettingsComp);
  58676. audioDeviceSettingsComp->resized();
  58677. }
  58678. }
  58679. }
  58680. if (midiInputsList != 0)
  58681. {
  58682. midiInputsList->updateContent();
  58683. midiInputsList->repaint();
  58684. }
  58685. if (midiOutputSelector != 0)
  58686. {
  58687. midiOutputSelector->clear();
  58688. const StringArray midiOuts (MidiOutput::getDevices());
  58689. midiOutputSelector->addItem (TRANS("<< none >>"), -1);
  58690. midiOutputSelector->addSeparator();
  58691. for (int i = 0; i < midiOuts.size(); ++i)
  58692. midiOutputSelector->addItem (midiOuts[i], i + 1);
  58693. int current = -1;
  58694. if (deviceManager.getDefaultMidiOutput() != 0)
  58695. current = 1 + midiOuts.indexOf (deviceManager.getDefaultMidiOutputName());
  58696. midiOutputSelector->setSelectedId (current, true);
  58697. }
  58698. resized();
  58699. }
  58700. END_JUCE_NAMESPACE
  58701. /*** End of inlined file: juce_AudioDeviceSelectorComponent.cpp ***/
  58702. /*** Start of inlined file: juce_BubbleComponent.cpp ***/
  58703. BEGIN_JUCE_NAMESPACE
  58704. BubbleComponent::BubbleComponent()
  58705. : side (0),
  58706. allowablePlacements (above | below | left | right),
  58707. arrowTipX (0.0f),
  58708. arrowTipY (0.0f)
  58709. {
  58710. setInterceptsMouseClicks (false, false);
  58711. shadow.setShadowProperties (5.0f, 0.35f, 0, 0);
  58712. setComponentEffect (&shadow);
  58713. }
  58714. BubbleComponent::~BubbleComponent()
  58715. {
  58716. }
  58717. void BubbleComponent::paint (Graphics& g)
  58718. {
  58719. int x = content.getX();
  58720. int y = content.getY();
  58721. int w = content.getWidth();
  58722. int h = content.getHeight();
  58723. int cw, ch;
  58724. getContentSize (cw, ch);
  58725. if (side == 3)
  58726. x += w - cw;
  58727. else if (side != 1)
  58728. x += (w - cw) / 2;
  58729. w = cw;
  58730. if (side == 2)
  58731. y += h - ch;
  58732. else if (side != 0)
  58733. y += (h - ch) / 2;
  58734. h = ch;
  58735. getLookAndFeel().drawBubble (g, arrowTipX, arrowTipY,
  58736. (float) x, (float) y,
  58737. (float) w, (float) h);
  58738. const int cx = x + (w - cw) / 2;
  58739. const int cy = y + (h - ch) / 2;
  58740. const int indent = 3;
  58741. g.setOrigin (cx + indent, cy + indent);
  58742. g.reduceClipRegion (0, 0, cw - indent * 2, ch - indent * 2);
  58743. paintContent (g, cw - indent * 2, ch - indent * 2);
  58744. }
  58745. void BubbleComponent::setAllowedPlacement (const int newPlacement)
  58746. {
  58747. allowablePlacements = newPlacement;
  58748. }
  58749. void BubbleComponent::setPosition (Component* componentToPointTo)
  58750. {
  58751. jassert (componentToPointTo->isValidComponent());
  58752. Point<int> pos;
  58753. if (getParentComponent() != 0)
  58754. pos = componentToPointTo->relativePositionToOtherComponent (getParentComponent(), pos);
  58755. else
  58756. pos = componentToPointTo->relativePositionToGlobal (pos);
  58757. setPosition (Rectangle<int> (pos.getX(), pos.getY(), componentToPointTo->getWidth(), componentToPointTo->getHeight()));
  58758. }
  58759. void BubbleComponent::setPosition (const int arrowTipX_,
  58760. const int arrowTipY_)
  58761. {
  58762. setPosition (Rectangle<int> (arrowTipX_, arrowTipY_, 1, 1));
  58763. }
  58764. void BubbleComponent::setPosition (const Rectangle<int>& rectangleToPointTo)
  58765. {
  58766. Rectangle<int> availableSpace;
  58767. if (getParentComponent() != 0)
  58768. {
  58769. availableSpace.setSize (getParentComponent()->getWidth(),
  58770. getParentComponent()->getHeight());
  58771. }
  58772. else
  58773. {
  58774. availableSpace = getParentMonitorArea();
  58775. }
  58776. int x = 0;
  58777. int y = 0;
  58778. int w = 150;
  58779. int h = 30;
  58780. getContentSize (w, h);
  58781. w += 30;
  58782. h += 30;
  58783. const float edgeIndent = 2.0f;
  58784. const int arrowLength = jmin (10, h / 3, w / 3);
  58785. int spaceAbove = ((allowablePlacements & above) != 0) ? jmax (0, rectangleToPointTo.getY() - availableSpace.getY()) : -1;
  58786. int spaceBelow = ((allowablePlacements & below) != 0) ? jmax (0, availableSpace.getBottom() - rectangleToPointTo.getBottom()) : -1;
  58787. int spaceLeft = ((allowablePlacements & left) != 0) ? jmax (0, rectangleToPointTo.getX() - availableSpace.getX()) : -1;
  58788. int spaceRight = ((allowablePlacements & right) != 0) ? jmax (0, availableSpace.getRight() - rectangleToPointTo.getRight()) : -1;
  58789. // look at whether the component is elongated, and if so, try to position next to its longer dimension.
  58790. if (rectangleToPointTo.getWidth() > rectangleToPointTo.getHeight() * 2
  58791. && (spaceAbove > h + 20 || spaceBelow > h + 20))
  58792. {
  58793. spaceLeft = spaceRight = 0;
  58794. }
  58795. else if (rectangleToPointTo.getWidth() < rectangleToPointTo.getHeight() / 2
  58796. && (spaceLeft > w + 20 || spaceRight > w + 20))
  58797. {
  58798. spaceAbove = spaceBelow = 0;
  58799. }
  58800. if (jmax (spaceAbove, spaceBelow) >= jmax (spaceLeft, spaceRight))
  58801. {
  58802. x = rectangleToPointTo.getX() + (rectangleToPointTo.getWidth() - w) / 2;
  58803. arrowTipX = w * 0.5f;
  58804. content.setSize (w, h - arrowLength);
  58805. if (spaceAbove >= spaceBelow)
  58806. {
  58807. // above
  58808. y = rectangleToPointTo.getY() - h;
  58809. content.setPosition (0, 0);
  58810. arrowTipY = h - edgeIndent;
  58811. side = 2;
  58812. }
  58813. else
  58814. {
  58815. // below
  58816. y = rectangleToPointTo.getBottom();
  58817. content.setPosition (0, arrowLength);
  58818. arrowTipY = edgeIndent;
  58819. side = 0;
  58820. }
  58821. }
  58822. else
  58823. {
  58824. y = rectangleToPointTo.getY() + (rectangleToPointTo.getHeight() - h) / 2;
  58825. arrowTipY = h * 0.5f;
  58826. content.setSize (w - arrowLength, h);
  58827. if (spaceLeft > spaceRight)
  58828. {
  58829. // on the left
  58830. x = rectangleToPointTo.getX() - w;
  58831. content.setPosition (0, 0);
  58832. arrowTipX = w - edgeIndent;
  58833. side = 3;
  58834. }
  58835. else
  58836. {
  58837. // on the right
  58838. x = rectangleToPointTo.getRight();
  58839. content.setPosition (arrowLength, 0);
  58840. arrowTipX = edgeIndent;
  58841. side = 1;
  58842. }
  58843. }
  58844. setBounds (x, y, w, h);
  58845. }
  58846. END_JUCE_NAMESPACE
  58847. /*** End of inlined file: juce_BubbleComponent.cpp ***/
  58848. /*** Start of inlined file: juce_BubbleMessageComponent.cpp ***/
  58849. BEGIN_JUCE_NAMESPACE
  58850. BubbleMessageComponent::BubbleMessageComponent (int fadeOutLengthMs)
  58851. : fadeOutLength (fadeOutLengthMs),
  58852. deleteAfterUse (false)
  58853. {
  58854. }
  58855. BubbleMessageComponent::~BubbleMessageComponent()
  58856. {
  58857. fadeOutComponent (fadeOutLength);
  58858. }
  58859. void BubbleMessageComponent::showAt (int x, int y,
  58860. const String& text,
  58861. const int numMillisecondsBeforeRemoving,
  58862. const bool removeWhenMouseClicked,
  58863. const bool deleteSelfAfterUse)
  58864. {
  58865. textLayout.clear();
  58866. textLayout.setText (text, Font (14.0f));
  58867. textLayout.layout (256, Justification::centredLeft, true);
  58868. setPosition (x, y);
  58869. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  58870. }
  58871. void BubbleMessageComponent::showAt (Component* const component,
  58872. const String& text,
  58873. const int numMillisecondsBeforeRemoving,
  58874. const bool removeWhenMouseClicked,
  58875. const bool deleteSelfAfterUse)
  58876. {
  58877. textLayout.clear();
  58878. textLayout.setText (text, Font (14.0f));
  58879. textLayout.layout (256, Justification::centredLeft, true);
  58880. setPosition (component);
  58881. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  58882. }
  58883. void BubbleMessageComponent::init (const int numMillisecondsBeforeRemoving,
  58884. const bool removeWhenMouseClicked,
  58885. const bool deleteSelfAfterUse)
  58886. {
  58887. setVisible (true);
  58888. deleteAfterUse = deleteSelfAfterUse;
  58889. if (numMillisecondsBeforeRemoving > 0)
  58890. expiryTime = Time::getMillisecondCounter() + numMillisecondsBeforeRemoving;
  58891. else
  58892. expiryTime = 0;
  58893. startTimer (77);
  58894. mouseClickCounter = Desktop::getInstance().getMouseButtonClickCounter();
  58895. if (! (removeWhenMouseClicked && isShowing()))
  58896. mouseClickCounter += 0xfffff;
  58897. repaint();
  58898. }
  58899. void BubbleMessageComponent::getContentSize (int& w, int& h)
  58900. {
  58901. w = textLayout.getWidth() + 16;
  58902. h = textLayout.getHeight() + 16;
  58903. }
  58904. void BubbleMessageComponent::paintContent (Graphics& g, int w, int h)
  58905. {
  58906. g.setColour (findColour (TooltipWindow::textColourId));
  58907. textLayout.drawWithin (g, 0, 0, w, h, Justification::centred);
  58908. }
  58909. void BubbleMessageComponent::timerCallback()
  58910. {
  58911. if (Desktop::getInstance().getMouseButtonClickCounter() > mouseClickCounter)
  58912. {
  58913. stopTimer();
  58914. setVisible (false);
  58915. if (deleteAfterUse)
  58916. delete this;
  58917. }
  58918. else if (expiryTime != 0 && Time::getMillisecondCounter() > expiryTime)
  58919. {
  58920. stopTimer();
  58921. fadeOutComponent (fadeOutLength);
  58922. if (deleteAfterUse)
  58923. delete this;
  58924. }
  58925. }
  58926. END_JUCE_NAMESPACE
  58927. /*** End of inlined file: juce_BubbleMessageComponent.cpp ***/
  58928. /*** Start of inlined file: juce_ColourSelector.cpp ***/
  58929. BEGIN_JUCE_NAMESPACE
  58930. static const int swatchesPerRow = 8;
  58931. static const int swatchHeight = 22;
  58932. class ColourComponentSlider : public Slider
  58933. {
  58934. public:
  58935. ColourComponentSlider (const String& name)
  58936. : Slider (name)
  58937. {
  58938. setRange (0.0, 255.0, 1.0);
  58939. }
  58940. ~ColourComponentSlider()
  58941. {
  58942. }
  58943. const String getTextFromValue (double value)
  58944. {
  58945. return String::toHexString ((int) value).toUpperCase().paddedLeft ('0', 2);
  58946. }
  58947. double getValueFromText (const String& text)
  58948. {
  58949. return (double) text.getHexValue32();
  58950. }
  58951. private:
  58952. ColourComponentSlider (const ColourComponentSlider&);
  58953. ColourComponentSlider& operator= (const ColourComponentSlider&);
  58954. };
  58955. class ColourSpaceMarker : public Component
  58956. {
  58957. public:
  58958. ColourSpaceMarker()
  58959. {
  58960. setInterceptsMouseClicks (false, false);
  58961. }
  58962. ~ColourSpaceMarker()
  58963. {
  58964. }
  58965. void paint (Graphics& g)
  58966. {
  58967. g.setColour (Colour::greyLevel (0.1f));
  58968. g.drawEllipse (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 1.0f);
  58969. g.setColour (Colour::greyLevel (0.9f));
  58970. g.drawEllipse (2.0f, 2.0f, getWidth() - 4.0f, getHeight() - 4.0f, 1.0f);
  58971. }
  58972. private:
  58973. ColourSpaceMarker (const ColourSpaceMarker&);
  58974. ColourSpaceMarker& operator= (const ColourSpaceMarker&);
  58975. };
  58976. class ColourSelector::ColourSpaceView : public Component
  58977. {
  58978. public:
  58979. ColourSpaceView (ColourSelector* owner_,
  58980. float& h_, float& s_, float& v_,
  58981. const int edgeSize)
  58982. : owner (owner_),
  58983. h (h_), s (s_), v (v_),
  58984. lastHue (0.0f),
  58985. edge (edgeSize)
  58986. {
  58987. addAndMakeVisible (marker = new ColourSpaceMarker());
  58988. setMouseCursor (MouseCursor::CrosshairCursor);
  58989. }
  58990. ~ColourSpaceView()
  58991. {
  58992. deleteAllChildren();
  58993. }
  58994. void paint (Graphics& g)
  58995. {
  58996. if (colours.isNull())
  58997. {
  58998. const int width = getWidth() / 2;
  58999. const int height = getHeight() / 2;
  59000. colours = Image (Image::RGB, width, height, false);
  59001. Image::BitmapData pixels (colours, 0, 0, width, height, true);
  59002. for (int y = 0; y < height; ++y)
  59003. {
  59004. const float val = 1.0f - y / (float) height;
  59005. for (int x = 0; x < width; ++x)
  59006. {
  59007. const float sat = x / (float) width;
  59008. pixels.setPixelColour (x, y, Colour (h, sat, val, 1.0f));
  59009. }
  59010. }
  59011. }
  59012. g.setOpacity (1.0f);
  59013. g.drawImage (colours, edge, edge, getWidth() - edge * 2, getHeight() - edge * 2,
  59014. 0, 0, colours.getWidth(), colours.getHeight());
  59015. }
  59016. void mouseDown (const MouseEvent& e)
  59017. {
  59018. mouseDrag (e);
  59019. }
  59020. void mouseDrag (const MouseEvent& e)
  59021. {
  59022. const float sat = (e.x - edge) / (float) (getWidth() - edge * 2);
  59023. const float val = 1.0f - (e.y - edge) / (float) (getHeight() - edge * 2);
  59024. owner->setSV (sat, val);
  59025. }
  59026. void updateIfNeeded()
  59027. {
  59028. if (lastHue != h)
  59029. {
  59030. lastHue = h;
  59031. colours = Image();
  59032. repaint();
  59033. }
  59034. updateMarker();
  59035. }
  59036. void resized()
  59037. {
  59038. colours = Image();
  59039. updateMarker();
  59040. }
  59041. private:
  59042. ColourSelector* const owner;
  59043. float& h;
  59044. float& s;
  59045. float& v;
  59046. float lastHue;
  59047. ColourSpaceMarker* marker;
  59048. const int edge;
  59049. Image colours;
  59050. void updateMarker() const
  59051. {
  59052. marker->setBounds (roundToInt ((getWidth() - edge * 2) * s),
  59053. roundToInt ((getHeight() - edge * 2) * (1.0f - v)),
  59054. edge * 2, edge * 2);
  59055. }
  59056. ColourSpaceView (const ColourSpaceView&);
  59057. ColourSpaceView& operator= (const ColourSpaceView&);
  59058. };
  59059. class HueSelectorMarker : public Component
  59060. {
  59061. public:
  59062. HueSelectorMarker()
  59063. {
  59064. setInterceptsMouseClicks (false, false);
  59065. }
  59066. ~HueSelectorMarker()
  59067. {
  59068. }
  59069. void paint (Graphics& g)
  59070. {
  59071. Path p;
  59072. p.addTriangle (1.0f, 1.0f,
  59073. getWidth() * 0.3f, getHeight() * 0.5f,
  59074. 1.0f, getHeight() - 1.0f);
  59075. p.addTriangle (getWidth() - 1.0f, 1.0f,
  59076. getWidth() * 0.7f, getHeight() * 0.5f,
  59077. getWidth() - 1.0f, getHeight() - 1.0f);
  59078. g.setColour (Colours::white.withAlpha (0.75f));
  59079. g.fillPath (p);
  59080. g.setColour (Colours::black.withAlpha (0.75f));
  59081. g.strokePath (p, PathStrokeType (1.2f));
  59082. }
  59083. private:
  59084. HueSelectorMarker (const HueSelectorMarker&);
  59085. HueSelectorMarker& operator= (const HueSelectorMarker&);
  59086. };
  59087. class ColourSelector::HueSelectorComp : public Component
  59088. {
  59089. public:
  59090. HueSelectorComp (ColourSelector* owner_,
  59091. float& h_, float& s_, float& v_,
  59092. const int edgeSize)
  59093. : owner (owner_),
  59094. h (h_), s (s_), v (v_),
  59095. lastHue (0.0f),
  59096. edge (edgeSize)
  59097. {
  59098. addAndMakeVisible (marker = new HueSelectorMarker());
  59099. }
  59100. ~HueSelectorComp()
  59101. {
  59102. deleteAllChildren();
  59103. }
  59104. void paint (Graphics& g)
  59105. {
  59106. const float yScale = 1.0f / (getHeight() - edge * 2);
  59107. const Rectangle<int> clip (g.getClipBounds());
  59108. for (int y = jmin (clip.getBottom(), getHeight() - edge); --y >= jmax (edge, clip.getY());)
  59109. {
  59110. g.setColour (Colour ((y - edge) * yScale, 1.0f, 1.0f, 1.0f));
  59111. g.fillRect (edge, y, getWidth() - edge * 2, 1);
  59112. }
  59113. }
  59114. void resized()
  59115. {
  59116. marker->setBounds (0, roundToInt ((getHeight() - edge * 2) * h),
  59117. getWidth(), edge * 2);
  59118. }
  59119. void mouseDown (const MouseEvent& e)
  59120. {
  59121. mouseDrag (e);
  59122. }
  59123. void mouseDrag (const MouseEvent& e)
  59124. {
  59125. const float hue = (e.y - edge) / (float) (getHeight() - edge * 2);
  59126. owner->setHue (hue);
  59127. }
  59128. void updateIfNeeded()
  59129. {
  59130. resized();
  59131. }
  59132. private:
  59133. ColourSelector* const owner;
  59134. float& h;
  59135. float& s;
  59136. float& v;
  59137. float lastHue;
  59138. HueSelectorMarker* marker;
  59139. const int edge;
  59140. HueSelectorComp (const HueSelectorComp&);
  59141. HueSelectorComp& operator= (const HueSelectorComp&);
  59142. };
  59143. class ColourSelector::SwatchComponent : public Component
  59144. {
  59145. public:
  59146. SwatchComponent (ColourSelector* owner_, int index_)
  59147. : owner (owner_),
  59148. index (index_)
  59149. {
  59150. }
  59151. ~SwatchComponent()
  59152. {
  59153. }
  59154. void paint (Graphics& g)
  59155. {
  59156. const Colour colour (owner->getSwatchColour (index));
  59157. g.fillCheckerBoard (0, 0, getWidth(), getHeight(),
  59158. 6, 6,
  59159. Colour (0xffdddddd).overlaidWith (colour),
  59160. Colour (0xffffffff).overlaidWith (colour));
  59161. }
  59162. void mouseDown (const MouseEvent&)
  59163. {
  59164. PopupMenu m;
  59165. m.addItem (1, TRANS("Use this swatch as the current colour"));
  59166. m.addSeparator();
  59167. m.addItem (2, TRANS("Set this swatch to the current colour"));
  59168. const int r = m.showAt (this);
  59169. if (r == 1)
  59170. {
  59171. owner->setCurrentColour (owner->getSwatchColour (index));
  59172. }
  59173. else if (r == 2)
  59174. {
  59175. if (owner->getSwatchColour (index) != owner->getCurrentColour())
  59176. {
  59177. owner->setSwatchColour (index, owner->getCurrentColour());
  59178. repaint();
  59179. }
  59180. }
  59181. }
  59182. private:
  59183. ColourSelector* const owner;
  59184. const int index;
  59185. SwatchComponent (const SwatchComponent&);
  59186. SwatchComponent& operator= (const SwatchComponent&);
  59187. };
  59188. ColourSelector::ColourSelector (const int flags_,
  59189. const int edgeGap_,
  59190. const int gapAroundColourSpaceComponent)
  59191. : colour (Colours::white),
  59192. flags (flags_),
  59193. topSpace (0),
  59194. edgeGap (edgeGap_)
  59195. {
  59196. // not much point having a selector with no components in it!
  59197. jassert ((flags_ & (showColourAtTop | showSliders | showColourspace)) != 0);
  59198. updateHSV();
  59199. if ((flags & showSliders) != 0)
  59200. {
  59201. addAndMakeVisible (sliders[0] = new ColourComponentSlider (TRANS ("red")));
  59202. addAndMakeVisible (sliders[1] = new ColourComponentSlider (TRANS ("green")));
  59203. addAndMakeVisible (sliders[2] = new ColourComponentSlider (TRANS ("blue")));
  59204. addChildComponent (sliders[3] = new ColourComponentSlider (TRANS ("alpha")));
  59205. sliders[3]->setVisible ((flags & showAlphaChannel) != 0);
  59206. for (int i = 4; --i >= 0;)
  59207. sliders[i]->addListener (this);
  59208. }
  59209. else
  59210. {
  59211. zeromem (sliders, sizeof (sliders));
  59212. }
  59213. if ((flags & showColourspace) != 0)
  59214. {
  59215. addAndMakeVisible (colourSpace = new ColourSpaceView (this, h, s, v, gapAroundColourSpaceComponent));
  59216. addAndMakeVisible (hueSelector = new HueSelectorComp (this, h, s, v, gapAroundColourSpaceComponent));
  59217. }
  59218. else
  59219. {
  59220. colourSpace = 0;
  59221. hueSelector = 0;
  59222. }
  59223. update();
  59224. }
  59225. ColourSelector::~ColourSelector()
  59226. {
  59227. dispatchPendingMessages();
  59228. swatchComponents.clear();
  59229. deleteAllChildren();
  59230. }
  59231. const Colour ColourSelector::getCurrentColour() const
  59232. {
  59233. return ((flags & showAlphaChannel) != 0) ? colour
  59234. : colour.withAlpha ((uint8) 0xff);
  59235. }
  59236. void ColourSelector::setCurrentColour (const Colour& c)
  59237. {
  59238. if (c != colour)
  59239. {
  59240. colour = ((flags & showAlphaChannel) != 0) ? c : c.withAlpha ((uint8) 0xff);
  59241. updateHSV();
  59242. update();
  59243. }
  59244. }
  59245. void ColourSelector::setHue (float newH)
  59246. {
  59247. newH = jlimit (0.0f, 1.0f, newH);
  59248. if (h != newH)
  59249. {
  59250. h = newH;
  59251. colour = Colour (h, s, v, colour.getFloatAlpha());
  59252. update();
  59253. }
  59254. }
  59255. void ColourSelector::setSV (float newS, float newV)
  59256. {
  59257. newS = jlimit (0.0f, 1.0f, newS);
  59258. newV = jlimit (0.0f, 1.0f, newV);
  59259. if (s != newS || v != newV)
  59260. {
  59261. s = newS;
  59262. v = newV;
  59263. colour = Colour (h, s, v, colour.getFloatAlpha());
  59264. update();
  59265. }
  59266. }
  59267. void ColourSelector::updateHSV()
  59268. {
  59269. colour.getHSB (h, s, v);
  59270. }
  59271. void ColourSelector::update()
  59272. {
  59273. if (sliders[0] != 0)
  59274. {
  59275. sliders[0]->setValue ((int) colour.getRed());
  59276. sliders[1]->setValue ((int) colour.getGreen());
  59277. sliders[2]->setValue ((int) colour.getBlue());
  59278. sliders[3]->setValue ((int) colour.getAlpha());
  59279. }
  59280. if (colourSpace != 0)
  59281. {
  59282. colourSpace->updateIfNeeded();
  59283. hueSelector->updateIfNeeded();
  59284. }
  59285. if ((flags & showColourAtTop) != 0)
  59286. repaint (0, edgeGap, getWidth(), topSpace - edgeGap);
  59287. sendChangeMessage (this);
  59288. }
  59289. void ColourSelector::paint (Graphics& g)
  59290. {
  59291. g.fillAll (findColour (backgroundColourId));
  59292. if ((flags & showColourAtTop) != 0)
  59293. {
  59294. const Colour currentColour (getCurrentColour());
  59295. g.fillCheckerBoard (edgeGap, edgeGap, getWidth() - edgeGap - edgeGap, topSpace - edgeGap - edgeGap,
  59296. 10, 10,
  59297. Colour (0xffdddddd).overlaidWith (currentColour),
  59298. Colour (0xffffffff).overlaidWith (currentColour));
  59299. g.setColour (Colours::white.overlaidWith (currentColour).contrasting());
  59300. g.setFont (14.0f, true);
  59301. g.drawText (currentColour.toDisplayString ((flags & showAlphaChannel) != 0),
  59302. 0, edgeGap, getWidth(), topSpace - edgeGap * 2,
  59303. Justification::centred, false);
  59304. }
  59305. if ((flags & showSliders) != 0)
  59306. {
  59307. g.setColour (findColour (labelTextColourId));
  59308. g.setFont (11.0f);
  59309. for (int i = 4; --i >= 0;)
  59310. {
  59311. if (sliders[i]->isVisible())
  59312. g.drawText (sliders[i]->getName() + ":",
  59313. 0, sliders[i]->getY(),
  59314. sliders[i]->getX() - 8, sliders[i]->getHeight(),
  59315. Justification::centredRight, false);
  59316. }
  59317. }
  59318. }
  59319. void ColourSelector::resized()
  59320. {
  59321. const int numSliders = ((flags & showAlphaChannel) != 0) ? 4 : 3;
  59322. const int numSwatches = getNumSwatches();
  59323. const int swatchSpace = numSwatches > 0 ? edgeGap + swatchHeight * ((numSwatches + 7) / swatchesPerRow) : 0;
  59324. const int sliderSpace = ((flags & showSliders) != 0) ? jmin (22 * numSliders + edgeGap, proportionOfHeight (0.3f)) : 0;
  59325. topSpace = ((flags & showColourAtTop) != 0) ? jmin (30 + edgeGap * 2, proportionOfHeight (0.2f)) : edgeGap;
  59326. int y = topSpace;
  59327. if ((flags & showColourspace) != 0)
  59328. {
  59329. const int hueWidth = jmin (50, proportionOfWidth (0.15f));
  59330. colourSpace->setBounds (edgeGap, y,
  59331. getWidth() - hueWidth - edgeGap - 4,
  59332. getHeight() - topSpace - sliderSpace - swatchSpace - edgeGap);
  59333. hueSelector->setBounds (colourSpace->getRight() + 4, y,
  59334. getWidth() - edgeGap - (colourSpace->getRight() + 4),
  59335. colourSpace->getHeight());
  59336. y = getHeight() - sliderSpace - swatchSpace - edgeGap;
  59337. }
  59338. if ((flags & showSliders) != 0)
  59339. {
  59340. const int sliderHeight = jmax (4, sliderSpace / numSliders);
  59341. for (int i = 0; i < numSliders; ++i)
  59342. {
  59343. sliders[i]->setBounds (proportionOfWidth (0.2f), y,
  59344. proportionOfWidth (0.72f), sliderHeight - 2);
  59345. y += sliderHeight;
  59346. }
  59347. }
  59348. if (numSwatches > 0)
  59349. {
  59350. const int startX = 8;
  59351. const int xGap = 4;
  59352. const int yGap = 4;
  59353. const int swatchWidth = (getWidth() - startX * 2) / swatchesPerRow;
  59354. y += edgeGap;
  59355. if (swatchComponents.size() != numSwatches)
  59356. {
  59357. swatchComponents.clear();
  59358. for (int i = 0; i < numSwatches; ++i)
  59359. {
  59360. SwatchComponent* const sc = new SwatchComponent (this, i);
  59361. swatchComponents.add (sc);
  59362. addAndMakeVisible (sc);
  59363. }
  59364. }
  59365. int x = startX;
  59366. for (int i = 0; i < swatchComponents.size(); ++i)
  59367. {
  59368. SwatchComponent* const sc = swatchComponents.getUnchecked(i);
  59369. sc->setBounds (x + xGap / 2,
  59370. y + yGap / 2,
  59371. swatchWidth - xGap,
  59372. swatchHeight - yGap);
  59373. if (((i + 1) % swatchesPerRow) == 0)
  59374. {
  59375. x = startX;
  59376. y += swatchHeight;
  59377. }
  59378. else
  59379. {
  59380. x += swatchWidth;
  59381. }
  59382. }
  59383. }
  59384. }
  59385. void ColourSelector::sliderValueChanged (Slider*)
  59386. {
  59387. if (sliders[0] != 0)
  59388. setCurrentColour (Colour ((uint8) sliders[0]->getValue(),
  59389. (uint8) sliders[1]->getValue(),
  59390. (uint8) sliders[2]->getValue(),
  59391. (uint8) sliders[3]->getValue()));
  59392. }
  59393. int ColourSelector::getNumSwatches() const
  59394. {
  59395. return 0;
  59396. }
  59397. const Colour ColourSelector::getSwatchColour (const int) const
  59398. {
  59399. jassertfalse; // if you've overridden getNumSwatches(), you also need to implement this method
  59400. return Colours::black;
  59401. }
  59402. void ColourSelector::setSwatchColour (const int, const Colour&) const
  59403. {
  59404. jassertfalse; // if you've overridden getNumSwatches(), you also need to implement this method
  59405. }
  59406. END_JUCE_NAMESPACE
  59407. /*** End of inlined file: juce_ColourSelector.cpp ***/
  59408. /*** Start of inlined file: juce_DropShadower.cpp ***/
  59409. BEGIN_JUCE_NAMESPACE
  59410. class ShadowWindow : public Component
  59411. {
  59412. Component* owner;
  59413. Image shadowImageSections [12];
  59414. const int type; // 0 = left, 1 = right, 2 = top, 3 = bottom. left + right are full-height
  59415. public:
  59416. ShadowWindow (Component* const owner_,
  59417. const int type_,
  59418. const Image shadowImageSections_ [12])
  59419. : owner (owner_),
  59420. type (type_)
  59421. {
  59422. for (int i = 0; i < numElementsInArray (shadowImageSections); ++i)
  59423. shadowImageSections [i] = shadowImageSections_ [i];
  59424. setInterceptsMouseClicks (false, false);
  59425. if (owner_->isOnDesktop())
  59426. {
  59427. setSize (1, 1); // to keep the OS happy by not having zero-size windows
  59428. addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  59429. | ComponentPeer::windowIsTemporary
  59430. | ComponentPeer::windowIgnoresKeyPresses);
  59431. }
  59432. else if (owner_->getParentComponent() != 0)
  59433. {
  59434. owner_->getParentComponent()->addChildComponent (this);
  59435. }
  59436. }
  59437. ~ShadowWindow()
  59438. {
  59439. }
  59440. void paint (Graphics& g)
  59441. {
  59442. const Image& topLeft = shadowImageSections [type * 3];
  59443. const Image& bottomRight = shadowImageSections [type * 3 + 1];
  59444. const Image& filler = shadowImageSections [type * 3 + 2];
  59445. g.setOpacity (1.0f);
  59446. if (type < 2)
  59447. {
  59448. int imH = jmin (topLeft.getHeight(), getHeight() / 2);
  59449. g.drawImage (topLeft,
  59450. 0, 0, topLeft.getWidth(), imH,
  59451. 0, 0, topLeft.getWidth(), imH);
  59452. imH = jmin (bottomRight.getHeight(), getHeight() - getHeight() / 2);
  59453. g.drawImage (bottomRight,
  59454. 0, getHeight() - imH, bottomRight.getWidth(), imH,
  59455. 0, bottomRight.getHeight() - imH, bottomRight.getWidth(), imH);
  59456. g.setTiledImageFill (filler, 0, 0, 1.0f);
  59457. g.fillRect (0, topLeft.getHeight(), getWidth(), getHeight() - (topLeft.getHeight() + bottomRight.getHeight()));
  59458. }
  59459. else
  59460. {
  59461. int imW = jmin (topLeft.getWidth(), getWidth() / 2);
  59462. g.drawImage (topLeft,
  59463. 0, 0, imW, topLeft.getHeight(),
  59464. 0, 0, imW, topLeft.getHeight());
  59465. imW = jmin (bottomRight.getWidth(), getWidth() - getWidth() / 2);
  59466. g.drawImage (bottomRight,
  59467. getWidth() - imW, 0, imW, bottomRight.getHeight(),
  59468. bottomRight.getWidth() - imW, 0, imW, bottomRight.getHeight());
  59469. g.setTiledImageFill (filler, 0, 0, 1.0f);
  59470. g.fillRect (topLeft.getWidth(), 0, getWidth() - (topLeft.getWidth() + bottomRight.getWidth()), getHeight());
  59471. }
  59472. }
  59473. void resized()
  59474. {
  59475. repaint(); // (needed for correct repainting)
  59476. }
  59477. private:
  59478. ShadowWindow (const ShadowWindow&);
  59479. ShadowWindow& operator= (const ShadowWindow&);
  59480. };
  59481. DropShadower::DropShadower (const float alpha_,
  59482. const int xOffset_,
  59483. const int yOffset_,
  59484. const float blurRadius_)
  59485. : owner (0),
  59486. numShadows (0),
  59487. shadowEdge (jmax (xOffset_, yOffset_) + (int) blurRadius_),
  59488. xOffset (xOffset_),
  59489. yOffset (yOffset_),
  59490. alpha (alpha_),
  59491. blurRadius (blurRadius_),
  59492. inDestructor (false),
  59493. reentrant (false)
  59494. {
  59495. }
  59496. DropShadower::~DropShadower()
  59497. {
  59498. if (owner != 0)
  59499. owner->removeComponentListener (this);
  59500. inDestructor = true;
  59501. deleteShadowWindows();
  59502. }
  59503. void DropShadower::deleteShadowWindows()
  59504. {
  59505. if (numShadows > 0)
  59506. {
  59507. int i;
  59508. for (i = numShadows; --i >= 0;)
  59509. delete shadowWindows[i];
  59510. numShadows = 0;
  59511. }
  59512. }
  59513. void DropShadower::setOwner (Component* componentToFollow)
  59514. {
  59515. if (componentToFollow != owner)
  59516. {
  59517. if (owner != 0)
  59518. owner->removeComponentListener (this);
  59519. // (the component can't be null)
  59520. jassert (componentToFollow != 0);
  59521. owner = componentToFollow;
  59522. jassert (owner != 0);
  59523. jassert (owner->isOpaque()); // doesn't work properly for semi-transparent comps!
  59524. owner->addComponentListener (this);
  59525. updateShadows();
  59526. }
  59527. }
  59528. void DropShadower::componentMovedOrResized (Component&, bool /*wasMoved*/, bool /*wasResized*/)
  59529. {
  59530. updateShadows();
  59531. }
  59532. void DropShadower::componentBroughtToFront (Component&)
  59533. {
  59534. bringShadowWindowsToFront();
  59535. }
  59536. void DropShadower::componentChildrenChanged (Component&)
  59537. {
  59538. }
  59539. void DropShadower::componentParentHierarchyChanged (Component&)
  59540. {
  59541. deleteShadowWindows();
  59542. updateShadows();
  59543. }
  59544. void DropShadower::componentVisibilityChanged (Component&)
  59545. {
  59546. updateShadows();
  59547. }
  59548. void DropShadower::updateShadows()
  59549. {
  59550. if (reentrant || inDestructor || (owner == 0))
  59551. return;
  59552. reentrant = true;
  59553. ComponentPeer* const nw = owner->getPeer();
  59554. const bool isOwnerVisible = owner->isVisible()
  59555. && (nw == 0 || ! nw->isMinimised());
  59556. const bool createShadowWindows = numShadows == 0
  59557. && owner->getWidth() > 0
  59558. && owner->getHeight() > 0
  59559. && isOwnerVisible
  59560. && (Desktop::canUseSemiTransparentWindows()
  59561. || owner->getParentComponent() != 0);
  59562. if (createShadowWindows)
  59563. {
  59564. // keep a cached version of the image to save doing the gaussian too often
  59565. String imageId;
  59566. imageId << shadowEdge << ',' << xOffset << ',' << yOffset << ',' << alpha;
  59567. const int hash = imageId.hashCode();
  59568. Image bigIm (ImageCache::getFromHashCode (hash));
  59569. if (bigIm.isNull())
  59570. {
  59571. bigIm = Image (Image::ARGB, shadowEdge * 5, shadowEdge * 5, true, Image::NativeImage);
  59572. Graphics bigG (bigIm);
  59573. bigG.setColour (Colours::black.withAlpha (alpha));
  59574. bigG.fillRect (shadowEdge + xOffset,
  59575. shadowEdge + yOffset,
  59576. bigIm.getWidth() - (shadowEdge * 2),
  59577. bigIm.getHeight() - (shadowEdge * 2));
  59578. ImageConvolutionKernel blurKernel (roundToInt (blurRadius * 2.0f));
  59579. blurKernel.createGaussianBlur (blurRadius);
  59580. blurKernel.applyToImage (bigIm, bigIm,
  59581. Rectangle<int> (xOffset, yOffset,
  59582. bigIm.getWidth(), bigIm.getHeight()));
  59583. ImageCache::addImageToCache (bigIm, hash);
  59584. }
  59585. const int iw = bigIm.getWidth();
  59586. const int ih = bigIm.getHeight();
  59587. const int shadowEdge2 = shadowEdge * 2;
  59588. setShadowImage (bigIm, 0, shadowEdge, shadowEdge2, 0, 0);
  59589. setShadowImage (bigIm, 1, shadowEdge, shadowEdge2, 0, ih - shadowEdge2);
  59590. setShadowImage (bigIm, 2, shadowEdge, shadowEdge, 0, shadowEdge2);
  59591. setShadowImage (bigIm, 3, shadowEdge, shadowEdge2, iw - shadowEdge, 0);
  59592. setShadowImage (bigIm, 4, shadowEdge, shadowEdge2, iw - shadowEdge, ih - shadowEdge2);
  59593. setShadowImage (bigIm, 5, shadowEdge, shadowEdge, iw - shadowEdge, shadowEdge2);
  59594. setShadowImage (bigIm, 6, shadowEdge, shadowEdge, shadowEdge, 0);
  59595. setShadowImage (bigIm, 7, shadowEdge, shadowEdge, iw - shadowEdge2, 0);
  59596. setShadowImage (bigIm, 8, shadowEdge, shadowEdge, shadowEdge2, 0);
  59597. setShadowImage (bigIm, 9, shadowEdge, shadowEdge, shadowEdge, ih - shadowEdge);
  59598. setShadowImage (bigIm, 10, shadowEdge, shadowEdge, iw - shadowEdge2, ih - shadowEdge);
  59599. setShadowImage (bigIm, 11, shadowEdge, shadowEdge, shadowEdge2, ih - shadowEdge);
  59600. for (int i = 0; i < 4; ++i)
  59601. {
  59602. shadowWindows[numShadows] = new ShadowWindow (owner, i, shadowImageSections);
  59603. ++numShadows;
  59604. }
  59605. }
  59606. if (numShadows > 0)
  59607. {
  59608. for (int i = numShadows; --i >= 0;)
  59609. {
  59610. shadowWindows[i]->setAlwaysOnTop (owner->isAlwaysOnTop());
  59611. shadowWindows[i]->setVisible (isOwnerVisible);
  59612. }
  59613. const int x = owner->getX();
  59614. const int y = owner->getY() - shadowEdge;
  59615. const int w = owner->getWidth();
  59616. const int h = owner->getHeight() + shadowEdge + shadowEdge;
  59617. shadowWindows[0]->setBounds (x - shadowEdge,
  59618. y,
  59619. shadowEdge,
  59620. h);
  59621. shadowWindows[1]->setBounds (x + w,
  59622. y,
  59623. shadowEdge,
  59624. h);
  59625. shadowWindows[2]->setBounds (x,
  59626. y,
  59627. w,
  59628. shadowEdge);
  59629. shadowWindows[3]->setBounds (x,
  59630. owner->getBottom(),
  59631. w,
  59632. shadowEdge);
  59633. }
  59634. reentrant = false;
  59635. if (createShadowWindows)
  59636. bringShadowWindowsToFront();
  59637. }
  59638. void DropShadower::setShadowImage (const Image& src, const int num, const int w, const int h,
  59639. const int sx, const int sy)
  59640. {
  59641. shadowImageSections[num] = Image (Image::ARGB, w, h, true, Image::NativeImage);
  59642. Graphics g (shadowImageSections[num]);
  59643. g.drawImage (src, 0, 0, w, h, sx, sy, w, h);
  59644. }
  59645. void DropShadower::bringShadowWindowsToFront()
  59646. {
  59647. if (! (inDestructor || reentrant))
  59648. {
  59649. updateShadows();
  59650. reentrant = true;
  59651. for (int i = numShadows; --i >= 0;)
  59652. shadowWindows[i]->toBehind (owner);
  59653. reentrant = false;
  59654. }
  59655. }
  59656. END_JUCE_NAMESPACE
  59657. /*** End of inlined file: juce_DropShadower.cpp ***/
  59658. /*** Start of inlined file: juce_MagnifierComponent.cpp ***/
  59659. BEGIN_JUCE_NAMESPACE
  59660. class MagnifyingPeer : public ComponentPeer
  59661. {
  59662. public:
  59663. MagnifyingPeer (Component* const component_,
  59664. MagnifierComponent* const magnifierComp_)
  59665. : ComponentPeer (component_, 0),
  59666. magnifierComp (magnifierComp_)
  59667. {
  59668. }
  59669. ~MagnifyingPeer()
  59670. {
  59671. }
  59672. void* getNativeHandle() const { return 0; }
  59673. void setVisible (bool) {}
  59674. void setTitle (const String&) {}
  59675. void setPosition (int, int) {}
  59676. void setSize (int, int) {}
  59677. void setBounds (int, int, int, int, bool) {}
  59678. void setMinimised (bool) {}
  59679. bool isMinimised() const { return false; }
  59680. void setFullScreen (bool) {}
  59681. bool isFullScreen() const { return false; }
  59682. const BorderSize getFrameSize() const { return BorderSize (0); }
  59683. bool setAlwaysOnTop (bool) { return true; }
  59684. void toFront (bool) {}
  59685. void toBehind (ComponentPeer*) {}
  59686. void setIcon (const Image&) {}
  59687. bool isFocused() const
  59688. {
  59689. return magnifierComp->hasKeyboardFocus (true);
  59690. }
  59691. void grabFocus()
  59692. {
  59693. ComponentPeer* peer = magnifierComp->getPeer();
  59694. if (peer != 0)
  59695. peer->grabFocus();
  59696. }
  59697. void textInputRequired (const Point<int>& position)
  59698. {
  59699. ComponentPeer* peer = magnifierComp->getPeer();
  59700. if (peer != 0)
  59701. peer->textInputRequired (position);
  59702. }
  59703. const Rectangle<int> getBounds() const
  59704. {
  59705. return Rectangle<int> (magnifierComp->getScreenX(), magnifierComp->getScreenY(),
  59706. component->getWidth(), component->getHeight());
  59707. }
  59708. const Point<int> getScreenPosition() const
  59709. {
  59710. return magnifierComp->getScreenPosition();
  59711. }
  59712. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition)
  59713. {
  59714. const double zoom = magnifierComp->getScaleFactor();
  59715. return magnifierComp->relativePositionToGlobal (Point<int> (roundToInt (relativePosition.getX() * zoom),
  59716. roundToInt (relativePosition.getY() * zoom)));
  59717. }
  59718. const Point<int> globalPositionToRelative (const Point<int>& screenPosition)
  59719. {
  59720. const Point<int> p (magnifierComp->globalPositionToRelative (screenPosition));
  59721. const double zoom = magnifierComp->getScaleFactor();
  59722. return Point<int> (roundToInt (p.getX() / zoom),
  59723. roundToInt (p.getY() / zoom));
  59724. }
  59725. bool contains (const Point<int>& position, bool) const
  59726. {
  59727. return ((unsigned int) position.getX()) < (unsigned int) magnifierComp->getWidth()
  59728. && ((unsigned int) position.getY()) < (unsigned int) magnifierComp->getHeight();
  59729. }
  59730. void repaint (const Rectangle<int>& area)
  59731. {
  59732. const double zoom = magnifierComp->getScaleFactor();
  59733. magnifierComp->repaint ((int) (area.getX() * zoom),
  59734. (int) (area.getY() * zoom),
  59735. roundToInt (area.getWidth() * zoom) + 1,
  59736. roundToInt (area.getHeight() * zoom) + 1);
  59737. }
  59738. void performAnyPendingRepaintsNow()
  59739. {
  59740. }
  59741. juce_UseDebuggingNewOperator
  59742. private:
  59743. MagnifierComponent* const magnifierComp;
  59744. MagnifyingPeer (const MagnifyingPeer&);
  59745. MagnifyingPeer& operator= (const MagnifyingPeer&);
  59746. };
  59747. class PeerHolderComp : public Component
  59748. {
  59749. public:
  59750. PeerHolderComp (MagnifierComponent* const magnifierComp_)
  59751. : magnifierComp (magnifierComp_)
  59752. {
  59753. setVisible (true);
  59754. }
  59755. ~PeerHolderComp()
  59756. {
  59757. }
  59758. ComponentPeer* createNewPeer (int, void*)
  59759. {
  59760. return new MagnifyingPeer (this, magnifierComp);
  59761. }
  59762. void childBoundsChanged (Component* c)
  59763. {
  59764. if (c != 0)
  59765. {
  59766. setSize (c->getWidth(), c->getHeight());
  59767. magnifierComp->childBoundsChanged (this);
  59768. }
  59769. }
  59770. void mouseWheelMove (const MouseEvent& e, float ix, float iy)
  59771. {
  59772. // unhandled mouse wheel moves can be referred upwards to the parent comp..
  59773. Component* const p = magnifierComp->getParentComponent();
  59774. if (p != 0)
  59775. p->mouseWheelMove (e.getEventRelativeTo (p), ix, iy);
  59776. }
  59777. private:
  59778. MagnifierComponent* const magnifierComp;
  59779. PeerHolderComp (const PeerHolderComp&);
  59780. PeerHolderComp& operator= (const PeerHolderComp&);
  59781. };
  59782. MagnifierComponent::MagnifierComponent (Component* const content_,
  59783. const bool deleteContentCompWhenNoLongerNeeded)
  59784. : content (content_),
  59785. scaleFactor (0.0),
  59786. peer (0),
  59787. deleteContent (deleteContentCompWhenNoLongerNeeded),
  59788. quality (Graphics::lowResamplingQuality),
  59789. mouseSource (0, true)
  59790. {
  59791. holderComp = new PeerHolderComp (this);
  59792. setScaleFactor (1.0);
  59793. }
  59794. MagnifierComponent::~MagnifierComponent()
  59795. {
  59796. delete holderComp;
  59797. if (deleteContent)
  59798. delete content;
  59799. }
  59800. void MagnifierComponent::setScaleFactor (double newScaleFactor)
  59801. {
  59802. jassert (newScaleFactor > 0.0); // hmm - unlikely to work well with a negative scale factor
  59803. newScaleFactor = jlimit (1.0 / 8.0, 1000.0, newScaleFactor);
  59804. if (scaleFactor != newScaleFactor)
  59805. {
  59806. scaleFactor = newScaleFactor;
  59807. if (scaleFactor == 1.0)
  59808. {
  59809. holderComp->removeFromDesktop();
  59810. peer = 0;
  59811. addChildComponent (content);
  59812. childBoundsChanged (content);
  59813. }
  59814. else
  59815. {
  59816. holderComp->addAndMakeVisible (content);
  59817. holderComp->childBoundsChanged (content);
  59818. childBoundsChanged (holderComp);
  59819. holderComp->addToDesktop (0);
  59820. peer = holderComp->getPeer();
  59821. }
  59822. repaint();
  59823. }
  59824. }
  59825. void MagnifierComponent::setResamplingQuality (Graphics::ResamplingQuality newQuality)
  59826. {
  59827. quality = newQuality;
  59828. }
  59829. void MagnifierComponent::paint (Graphics& g)
  59830. {
  59831. const int w = holderComp->getWidth();
  59832. const int h = holderComp->getHeight();
  59833. if (w == 0 || h == 0)
  59834. return;
  59835. const Rectangle<int> r (g.getClipBounds());
  59836. const int srcX = (int) (r.getX() / scaleFactor);
  59837. const int srcY = (int) (r.getY() / scaleFactor);
  59838. int srcW = roundToInt (r.getRight() / scaleFactor) - srcX;
  59839. int srcH = roundToInt (r.getBottom() / scaleFactor) - srcY;
  59840. if (scaleFactor >= 1.0)
  59841. {
  59842. ++srcW;
  59843. ++srcH;
  59844. }
  59845. Image temp (Image::ARGB, jmax (w, srcX + srcW), jmax (h, srcY + srcH), false);
  59846. temp.clear (Rectangle<int> (srcX, srcY, srcW, srcH));
  59847. {
  59848. Graphics g2 (temp);
  59849. g2.reduceClipRegion (srcX, srcY, srcW, srcH);
  59850. holderComp->paintEntireComponent (g2);
  59851. }
  59852. g.setImageResamplingQuality (quality);
  59853. g.drawImageTransformed (temp, temp.getBounds(),
  59854. AffineTransform::scale ((float) scaleFactor, (float) scaleFactor),
  59855. false);
  59856. }
  59857. void MagnifierComponent::childBoundsChanged (Component* c)
  59858. {
  59859. if (c != 0)
  59860. setSize (roundToInt (c->getWidth() * scaleFactor),
  59861. roundToInt (c->getHeight() * scaleFactor));
  59862. }
  59863. void MagnifierComponent::passOnMouseEventToPeer (const MouseEvent& e)
  59864. {
  59865. if (peer != 0)
  59866. mouseSource.handleEvent (peer, Point<int> (scaleInt (e.x), scaleInt (e.y)),
  59867. e.eventTime.toMilliseconds(), ModifierKeys::getCurrentModifiers());
  59868. }
  59869. void MagnifierComponent::mouseDown (const MouseEvent& e)
  59870. {
  59871. passOnMouseEventToPeer (e);
  59872. }
  59873. void MagnifierComponent::mouseUp (const MouseEvent& e)
  59874. {
  59875. passOnMouseEventToPeer (e);
  59876. }
  59877. void MagnifierComponent::mouseDrag (const MouseEvent& e)
  59878. {
  59879. passOnMouseEventToPeer (e);
  59880. }
  59881. void MagnifierComponent::mouseMove (const MouseEvent& e)
  59882. {
  59883. passOnMouseEventToPeer (e);
  59884. }
  59885. void MagnifierComponent::mouseEnter (const MouseEvent& e)
  59886. {
  59887. passOnMouseEventToPeer (e);
  59888. }
  59889. void MagnifierComponent::mouseExit (const MouseEvent& e)
  59890. {
  59891. passOnMouseEventToPeer (e);
  59892. }
  59893. void MagnifierComponent::mouseWheelMove (const MouseEvent& e, float ix, float iy)
  59894. {
  59895. if (peer != 0)
  59896. peer->handleMouseWheel (e.source.getIndex(),
  59897. Point<int> (scaleInt (e.x), scaleInt (e.y)), e.eventTime.toMilliseconds(),
  59898. ix * 256.0f, iy * 256.0f);
  59899. else
  59900. Component::mouseWheelMove (e, ix, iy);
  59901. }
  59902. int MagnifierComponent::scaleInt (const int n) const
  59903. {
  59904. return roundToInt (n / scaleFactor);
  59905. }
  59906. END_JUCE_NAMESPACE
  59907. /*** End of inlined file: juce_MagnifierComponent.cpp ***/
  59908. /*** Start of inlined file: juce_MidiKeyboardComponent.cpp ***/
  59909. BEGIN_JUCE_NAMESPACE
  59910. class MidiKeyboardUpDownButton : public Button
  59911. {
  59912. public:
  59913. MidiKeyboardUpDownButton (MidiKeyboardComponent* const owner_,
  59914. const int delta_)
  59915. : Button (String::empty),
  59916. owner (owner_),
  59917. delta (delta_)
  59918. {
  59919. setOpaque (true);
  59920. }
  59921. ~MidiKeyboardUpDownButton()
  59922. {
  59923. }
  59924. void clicked()
  59925. {
  59926. int note = owner->getLowestVisibleKey();
  59927. if (delta < 0)
  59928. note = (note - 1) / 12;
  59929. else
  59930. note = note / 12 + 1;
  59931. owner->setLowestVisibleKey (note * 12);
  59932. }
  59933. void paintButton (Graphics& g,
  59934. bool isMouseOverButton,
  59935. bool isButtonDown)
  59936. {
  59937. owner->drawUpDownButton (g, getWidth(), getHeight(),
  59938. isMouseOverButton, isButtonDown,
  59939. delta > 0);
  59940. }
  59941. private:
  59942. MidiKeyboardComponent* const owner;
  59943. const int delta;
  59944. MidiKeyboardUpDownButton (const MidiKeyboardUpDownButton&);
  59945. MidiKeyboardUpDownButton& operator= (const MidiKeyboardUpDownButton&);
  59946. };
  59947. MidiKeyboardComponent::MidiKeyboardComponent (MidiKeyboardState& state_,
  59948. const Orientation orientation_)
  59949. : state (state_),
  59950. xOffset (0),
  59951. blackNoteLength (1),
  59952. keyWidth (16.0f),
  59953. orientation (orientation_),
  59954. midiChannel (1),
  59955. midiInChannelMask (0xffff),
  59956. velocity (1.0f),
  59957. noteUnderMouse (-1),
  59958. mouseDownNote (-1),
  59959. rangeStart (0),
  59960. rangeEnd (127),
  59961. firstKey (12 * 4),
  59962. canScroll (true),
  59963. mouseDragging (false),
  59964. useMousePositionForVelocity (true),
  59965. keyMappingOctave (6),
  59966. octaveNumForMiddleC (3)
  59967. {
  59968. addChildComponent (scrollDown = new MidiKeyboardUpDownButton (this, -1));
  59969. addChildComponent (scrollUp = new MidiKeyboardUpDownButton (this, 1));
  59970. // initialise with a default set of querty key-mappings..
  59971. const char* const keymap = "awsedftgyhujkolp;";
  59972. for (int i = String (keymap).length(); --i >= 0;)
  59973. setKeyPressForNote (KeyPress (keymap[i], 0, 0), i);
  59974. setOpaque (true);
  59975. setWantsKeyboardFocus (true);
  59976. state.addListener (this);
  59977. }
  59978. MidiKeyboardComponent::~MidiKeyboardComponent()
  59979. {
  59980. state.removeListener (this);
  59981. jassert (mouseDownNote < 0 && keysPressed.countNumberOfSetBits() == 0); // leaving stuck notes!
  59982. deleteAllChildren();
  59983. }
  59984. void MidiKeyboardComponent::setKeyWidth (const float widthInPixels)
  59985. {
  59986. keyWidth = widthInPixels;
  59987. resized();
  59988. }
  59989. void MidiKeyboardComponent::setOrientation (const Orientation newOrientation)
  59990. {
  59991. if (orientation != newOrientation)
  59992. {
  59993. orientation = newOrientation;
  59994. resized();
  59995. }
  59996. }
  59997. void MidiKeyboardComponent::setAvailableRange (const int lowestNote,
  59998. const int highestNote)
  59999. {
  60000. jassert (lowestNote >= 0 && lowestNote <= 127);
  60001. jassert (highestNote >= 0 && highestNote <= 127);
  60002. jassert (lowestNote <= highestNote);
  60003. if (rangeStart != lowestNote || rangeEnd != highestNote)
  60004. {
  60005. rangeStart = jlimit (0, 127, lowestNote);
  60006. rangeEnd = jlimit (0, 127, highestNote);
  60007. firstKey = jlimit (rangeStart, rangeEnd, firstKey);
  60008. resized();
  60009. }
  60010. }
  60011. void MidiKeyboardComponent::setLowestVisibleKey (int noteNumber)
  60012. {
  60013. noteNumber = jlimit (rangeStart, rangeEnd, noteNumber);
  60014. if (noteNumber != firstKey)
  60015. {
  60016. firstKey = noteNumber;
  60017. sendChangeMessage (this);
  60018. resized();
  60019. }
  60020. }
  60021. void MidiKeyboardComponent::setScrollButtonsVisible (const bool canScroll_)
  60022. {
  60023. if (canScroll != canScroll_)
  60024. {
  60025. canScroll = canScroll_;
  60026. resized();
  60027. }
  60028. }
  60029. void MidiKeyboardComponent::colourChanged()
  60030. {
  60031. repaint();
  60032. }
  60033. void MidiKeyboardComponent::setMidiChannel (const int midiChannelNumber)
  60034. {
  60035. jassert (midiChannelNumber > 0 && midiChannelNumber <= 16);
  60036. if (midiChannel != midiChannelNumber)
  60037. {
  60038. resetAnyKeysInUse();
  60039. midiChannel = jlimit (1, 16, midiChannelNumber);
  60040. }
  60041. }
  60042. void MidiKeyboardComponent::setMidiChannelsToDisplay (const int midiChannelMask)
  60043. {
  60044. midiInChannelMask = midiChannelMask;
  60045. triggerAsyncUpdate();
  60046. }
  60047. void MidiKeyboardComponent::setVelocity (const float velocity_, const bool useMousePositionForVelocity_)
  60048. {
  60049. velocity = jlimit (0.0f, 1.0f, velocity_);
  60050. useMousePositionForVelocity = useMousePositionForVelocity_;
  60051. }
  60052. void MidiKeyboardComponent::getKeyPosition (int midiNoteNumber, const float keyWidth_, int& x, int& w) const
  60053. {
  60054. jassert (midiNoteNumber >= 0 && midiNoteNumber < 128);
  60055. static const float blackNoteWidth = 0.7f;
  60056. static const float notePos[] = { 0.0f, 1 - blackNoteWidth * 0.6f,
  60057. 1.0f, 2 - blackNoteWidth * 0.4f,
  60058. 2.0f, 3.0f, 4 - blackNoteWidth * 0.7f,
  60059. 4.0f, 5 - blackNoteWidth * 0.5f,
  60060. 5.0f, 6 - blackNoteWidth * 0.3f,
  60061. 6.0f };
  60062. static const float widths[] = { 1.0f, blackNoteWidth,
  60063. 1.0f, blackNoteWidth,
  60064. 1.0f, 1.0f, blackNoteWidth,
  60065. 1.0f, blackNoteWidth,
  60066. 1.0f, blackNoteWidth,
  60067. 1.0f };
  60068. const int octave = midiNoteNumber / 12;
  60069. const int note = midiNoteNumber % 12;
  60070. x = roundToInt (octave * 7.0f * keyWidth_ + notePos [note] * keyWidth_);
  60071. w = roundToInt (widths [note] * keyWidth_);
  60072. }
  60073. void MidiKeyboardComponent::getKeyPos (int midiNoteNumber, int& x, int& w) const
  60074. {
  60075. getKeyPosition (midiNoteNumber, keyWidth, x, w);
  60076. int rx, rw;
  60077. getKeyPosition (rangeStart, keyWidth, rx, rw);
  60078. x -= xOffset + rx;
  60079. }
  60080. int MidiKeyboardComponent::getKeyStartPosition (const int midiNoteNumber) const
  60081. {
  60082. int x, y;
  60083. getKeyPos (midiNoteNumber, x, y);
  60084. return x;
  60085. }
  60086. static const uint8 whiteNotes[] = { 0, 2, 4, 5, 7, 9, 11 };
  60087. static const uint8 blackNotes[] = { 1, 3, 6, 8, 10 };
  60088. int MidiKeyboardComponent::xyToNote (const Point<int>& pos, float& mousePositionVelocity)
  60089. {
  60090. if (! reallyContains (pos.getX(), pos.getY(), false))
  60091. return -1;
  60092. Point<int> p (pos);
  60093. if (orientation != horizontalKeyboard)
  60094. {
  60095. p = Point<int> (p.getY(), p.getX());
  60096. if (orientation == verticalKeyboardFacingLeft)
  60097. p = Point<int> (p.getX(), getWidth() - p.getY());
  60098. else
  60099. p = Point<int> (getHeight() - p.getX(), p.getY());
  60100. }
  60101. return remappedXYToNote (p + Point<int> (xOffset, 0), mousePositionVelocity);
  60102. }
  60103. int MidiKeyboardComponent::remappedXYToNote (const Point<int>& pos, float& mousePositionVelocity) const
  60104. {
  60105. if (pos.getY() < blackNoteLength)
  60106. {
  60107. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  60108. {
  60109. for (int i = 0; i < 5; ++i)
  60110. {
  60111. const int note = octaveStart + blackNotes [i];
  60112. if (note >= rangeStart && note <= rangeEnd)
  60113. {
  60114. int kx, kw;
  60115. getKeyPos (note, kx, kw);
  60116. kx += xOffset;
  60117. if (pos.getX() >= kx && pos.getX() < kx + kw)
  60118. {
  60119. mousePositionVelocity = pos.getY() / (float) blackNoteLength;
  60120. return note;
  60121. }
  60122. }
  60123. }
  60124. }
  60125. }
  60126. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  60127. {
  60128. for (int i = 0; i < 7; ++i)
  60129. {
  60130. const int note = octaveStart + whiteNotes [i];
  60131. if (note >= rangeStart && note <= rangeEnd)
  60132. {
  60133. int kx, kw;
  60134. getKeyPos (note, kx, kw);
  60135. kx += xOffset;
  60136. if (pos.getX() >= kx && pos.getX() < kx + kw)
  60137. {
  60138. const int whiteNoteLength = (orientation == horizontalKeyboard) ? getHeight() : getWidth();
  60139. mousePositionVelocity = pos.getY() / (float) whiteNoteLength;
  60140. return note;
  60141. }
  60142. }
  60143. }
  60144. }
  60145. mousePositionVelocity = 0;
  60146. return -1;
  60147. }
  60148. void MidiKeyboardComponent::repaintNote (const int noteNum)
  60149. {
  60150. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60151. {
  60152. int x, w;
  60153. getKeyPos (noteNum, x, w);
  60154. if (orientation == horizontalKeyboard)
  60155. repaint (x, 0, w, getHeight());
  60156. else if (orientation == verticalKeyboardFacingLeft)
  60157. repaint (0, x, getWidth(), w);
  60158. else if (orientation == verticalKeyboardFacingRight)
  60159. repaint (0, getHeight() - x - w, getWidth(), w);
  60160. }
  60161. }
  60162. void MidiKeyboardComponent::paint (Graphics& g)
  60163. {
  60164. g.fillAll (Colours::white.overlaidWith (findColour (whiteNoteColourId)));
  60165. const Colour lineColour (findColour (keySeparatorLineColourId));
  60166. const Colour textColour (findColour (textLabelColourId));
  60167. int x, w, octave;
  60168. for (octave = 0; octave < 128; octave += 12)
  60169. {
  60170. for (int white = 0; white < 7; ++white)
  60171. {
  60172. const int noteNum = octave + whiteNotes [white];
  60173. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60174. {
  60175. getKeyPos (noteNum, x, w);
  60176. if (orientation == horizontalKeyboard)
  60177. drawWhiteNote (noteNum, g, x, 0, w, getHeight(),
  60178. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60179. noteUnderMouse == noteNum,
  60180. lineColour, textColour);
  60181. else if (orientation == verticalKeyboardFacingLeft)
  60182. drawWhiteNote (noteNum, g, 0, x, getWidth(), w,
  60183. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60184. noteUnderMouse == noteNum,
  60185. lineColour, textColour);
  60186. else if (orientation == verticalKeyboardFacingRight)
  60187. drawWhiteNote (noteNum, g, 0, getHeight() - x - w, getWidth(), w,
  60188. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60189. noteUnderMouse == noteNum,
  60190. lineColour, textColour);
  60191. }
  60192. }
  60193. }
  60194. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  60195. if (orientation == verticalKeyboardFacingLeft)
  60196. {
  60197. x1 = getWidth() - 1.0f;
  60198. x2 = getWidth() - 5.0f;
  60199. }
  60200. else if (orientation == verticalKeyboardFacingRight)
  60201. x2 = 5.0f;
  60202. else
  60203. y2 = 5.0f;
  60204. g.setGradientFill (ColourGradient (Colours::black.withAlpha (0.3f), x1, y1,
  60205. Colours::transparentBlack, x2, y2, false));
  60206. getKeyPos (rangeEnd, x, w);
  60207. x += w;
  60208. if (orientation == verticalKeyboardFacingLeft)
  60209. g.fillRect (getWidth() - 5, 0, 5, x);
  60210. else if (orientation == verticalKeyboardFacingRight)
  60211. g.fillRect (0, 0, 5, x);
  60212. else
  60213. g.fillRect (0, 0, x, 5);
  60214. g.setColour (lineColour);
  60215. if (orientation == verticalKeyboardFacingLeft)
  60216. g.fillRect (0, 0, 1, x);
  60217. else if (orientation == verticalKeyboardFacingRight)
  60218. g.fillRect (getWidth() - 1, 0, 1, x);
  60219. else
  60220. g.fillRect (0, getHeight() - 1, x, 1);
  60221. const Colour blackNoteColour (findColour (blackNoteColourId));
  60222. for (octave = 0; octave < 128; octave += 12)
  60223. {
  60224. for (int black = 0; black < 5; ++black)
  60225. {
  60226. const int noteNum = octave + blackNotes [black];
  60227. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60228. {
  60229. getKeyPos (noteNum, x, w);
  60230. if (orientation == horizontalKeyboard)
  60231. drawBlackNote (noteNum, g, x, 0, w, blackNoteLength,
  60232. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60233. noteUnderMouse == noteNum,
  60234. blackNoteColour);
  60235. else if (orientation == verticalKeyboardFacingLeft)
  60236. drawBlackNote (noteNum, g, getWidth() - blackNoteLength, x, blackNoteLength, w,
  60237. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60238. noteUnderMouse == noteNum,
  60239. blackNoteColour);
  60240. else if (orientation == verticalKeyboardFacingRight)
  60241. drawBlackNote (noteNum, g, 0, getHeight() - x - w, blackNoteLength, w,
  60242. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60243. noteUnderMouse == noteNum,
  60244. blackNoteColour);
  60245. }
  60246. }
  60247. }
  60248. }
  60249. void MidiKeyboardComponent::drawWhiteNote (int midiNoteNumber,
  60250. Graphics& g, int x, int y, int w, int h,
  60251. bool isDown, bool isOver,
  60252. const Colour& lineColour,
  60253. const Colour& textColour)
  60254. {
  60255. Colour c (Colours::transparentWhite);
  60256. if (isDown)
  60257. c = findColour (keyDownOverlayColourId);
  60258. if (isOver)
  60259. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  60260. g.setColour (c);
  60261. g.fillRect (x, y, w, h);
  60262. const String text (getWhiteNoteText (midiNoteNumber));
  60263. if (! text.isEmpty())
  60264. {
  60265. g.setColour (textColour);
  60266. Font f (jmin (12.0f, keyWidth * 0.9f));
  60267. f.setHorizontalScale (0.8f);
  60268. g.setFont (f);
  60269. Justification justification (Justification::centredBottom);
  60270. if (orientation == verticalKeyboardFacingLeft)
  60271. justification = Justification::centredLeft;
  60272. else if (orientation == verticalKeyboardFacingRight)
  60273. justification = Justification::centredRight;
  60274. g.drawFittedText (text, x + 2, y + 2, w - 4, h - 4, justification, 1);
  60275. }
  60276. g.setColour (lineColour);
  60277. if (orientation == horizontalKeyboard)
  60278. g.fillRect (x, y, 1, h);
  60279. else if (orientation == verticalKeyboardFacingLeft)
  60280. g.fillRect (x, y, w, 1);
  60281. else if (orientation == verticalKeyboardFacingRight)
  60282. g.fillRect (x, y + h - 1, w, 1);
  60283. if (midiNoteNumber == rangeEnd)
  60284. {
  60285. if (orientation == horizontalKeyboard)
  60286. g.fillRect (x + w, y, 1, h);
  60287. else if (orientation == verticalKeyboardFacingLeft)
  60288. g.fillRect (x, y + h, w, 1);
  60289. else if (orientation == verticalKeyboardFacingRight)
  60290. g.fillRect (x, y - 1, w, 1);
  60291. }
  60292. }
  60293. void MidiKeyboardComponent::drawBlackNote (int /*midiNoteNumber*/,
  60294. Graphics& g, int x, int y, int w, int h,
  60295. bool isDown, bool isOver,
  60296. const Colour& noteFillColour)
  60297. {
  60298. Colour c (noteFillColour);
  60299. if (isDown)
  60300. c = c.overlaidWith (findColour (keyDownOverlayColourId));
  60301. if (isOver)
  60302. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  60303. g.setColour (c);
  60304. g.fillRect (x, y, w, h);
  60305. if (isDown)
  60306. {
  60307. g.setColour (noteFillColour);
  60308. g.drawRect (x, y, w, h);
  60309. }
  60310. else
  60311. {
  60312. const int xIndent = jmax (1, jmin (w, h) / 8);
  60313. g.setColour (c.brighter());
  60314. if (orientation == horizontalKeyboard)
  60315. g.fillRect (x + xIndent, y, w - xIndent * 2, 7 * h / 8);
  60316. else if (orientation == verticalKeyboardFacingLeft)
  60317. g.fillRect (x + w / 8, y + xIndent, w - w / 8, h - xIndent * 2);
  60318. else if (orientation == verticalKeyboardFacingRight)
  60319. g.fillRect (x, y + xIndent, 7 * w / 8, h - xIndent * 2);
  60320. }
  60321. }
  60322. void MidiKeyboardComponent::setOctaveForMiddleC (const int octaveNumForMiddleC_)
  60323. {
  60324. octaveNumForMiddleC = octaveNumForMiddleC_;
  60325. repaint();
  60326. }
  60327. const String MidiKeyboardComponent::getWhiteNoteText (const int midiNoteNumber)
  60328. {
  60329. if (keyWidth > 14.0f && midiNoteNumber % 12 == 0)
  60330. return MidiMessage::getMidiNoteName (midiNoteNumber, true, true, octaveNumForMiddleC);
  60331. return String::empty;
  60332. }
  60333. void MidiKeyboardComponent::drawUpDownButton (Graphics& g, int w, int h,
  60334. const bool isMouseOver_,
  60335. const bool isButtonDown,
  60336. const bool movesOctavesUp)
  60337. {
  60338. g.fillAll (findColour (upDownButtonBackgroundColourId));
  60339. float angle;
  60340. if (orientation == MidiKeyboardComponent::horizontalKeyboard)
  60341. angle = movesOctavesUp ? 0.0f : 0.5f;
  60342. else if (orientation == MidiKeyboardComponent::verticalKeyboardFacingLeft)
  60343. angle = movesOctavesUp ? 0.25f : 0.75f;
  60344. else
  60345. angle = movesOctavesUp ? 0.75f : 0.25f;
  60346. Path path;
  60347. path.lineTo (0.0f, 1.0f);
  60348. path.lineTo (1.0f, 0.5f);
  60349. path.closeSubPath();
  60350. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * angle, 0.5f, 0.5f));
  60351. g.setColour (findColour (upDownButtonArrowColourId)
  60352. .withAlpha (isButtonDown ? 1.0f : (isMouseOver_ ? 0.6f : 0.4f)));
  60353. g.fillPath (path, path.getTransformToScaleToFit (1.0f, 1.0f,
  60354. w - 2.0f,
  60355. h - 2.0f,
  60356. true));
  60357. }
  60358. void MidiKeyboardComponent::resized()
  60359. {
  60360. int w = getWidth();
  60361. int h = getHeight();
  60362. if (w > 0 && h > 0)
  60363. {
  60364. if (orientation != horizontalKeyboard)
  60365. swapVariables (w, h);
  60366. blackNoteLength = roundToInt (h * 0.7f);
  60367. int kx2, kw2;
  60368. getKeyPos (rangeEnd, kx2, kw2);
  60369. kx2 += kw2;
  60370. if (firstKey != rangeStart)
  60371. {
  60372. int kx1, kw1;
  60373. getKeyPos (rangeStart, kx1, kw1);
  60374. if (kx2 - kx1 <= w)
  60375. {
  60376. firstKey = rangeStart;
  60377. sendChangeMessage (this);
  60378. repaint();
  60379. }
  60380. }
  60381. const bool showScrollButtons = canScroll && (firstKey > rangeStart || kx2 > w + xOffset * 2);
  60382. scrollDown->setVisible (showScrollButtons);
  60383. scrollUp->setVisible (showScrollButtons);
  60384. xOffset = 0;
  60385. if (showScrollButtons)
  60386. {
  60387. const int scrollButtonW = jmin (12, w / 2);
  60388. if (orientation == horizontalKeyboard)
  60389. {
  60390. scrollDown->setBounds (0, 0, scrollButtonW, getHeight());
  60391. scrollUp->setBounds (getWidth() - scrollButtonW, 0, scrollButtonW, getHeight());
  60392. }
  60393. else if (orientation == verticalKeyboardFacingLeft)
  60394. {
  60395. scrollDown->setBounds (0, 0, getWidth(), scrollButtonW);
  60396. scrollUp->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  60397. }
  60398. else if (orientation == verticalKeyboardFacingRight)
  60399. {
  60400. scrollDown->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  60401. scrollUp->setBounds (0, 0, getWidth(), scrollButtonW);
  60402. }
  60403. int endOfLastKey, kw;
  60404. getKeyPos (rangeEnd, endOfLastKey, kw);
  60405. endOfLastKey += kw;
  60406. float mousePositionVelocity;
  60407. const int spaceAvailable = w - scrollButtonW * 2;
  60408. const int lastStartKey = remappedXYToNote (Point<int> (endOfLastKey - spaceAvailable, 0), mousePositionVelocity) + 1;
  60409. if (lastStartKey >= 0 && firstKey > lastStartKey)
  60410. {
  60411. firstKey = jlimit (rangeStart, rangeEnd, lastStartKey);
  60412. sendChangeMessage (this);
  60413. }
  60414. int newOffset = 0;
  60415. getKeyPos (firstKey, newOffset, kw);
  60416. xOffset = newOffset - scrollButtonW;
  60417. }
  60418. else
  60419. {
  60420. firstKey = rangeStart;
  60421. }
  60422. timerCallback();
  60423. repaint();
  60424. }
  60425. }
  60426. void MidiKeyboardComponent::handleNoteOn (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/, float /*velocity*/)
  60427. {
  60428. triggerAsyncUpdate();
  60429. }
  60430. void MidiKeyboardComponent::handleNoteOff (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/)
  60431. {
  60432. triggerAsyncUpdate();
  60433. }
  60434. void MidiKeyboardComponent::handleAsyncUpdate()
  60435. {
  60436. for (int i = rangeStart; i <= rangeEnd; ++i)
  60437. {
  60438. if (keysCurrentlyDrawnDown[i] != state.isNoteOnForChannels (midiInChannelMask, i))
  60439. {
  60440. keysCurrentlyDrawnDown.setBit (i, state.isNoteOnForChannels (midiInChannelMask, i));
  60441. repaintNote (i);
  60442. }
  60443. }
  60444. }
  60445. void MidiKeyboardComponent::resetAnyKeysInUse()
  60446. {
  60447. if (keysPressed.countNumberOfSetBits() > 0 || mouseDownNote > 0)
  60448. {
  60449. state.allNotesOff (midiChannel);
  60450. keysPressed.clear();
  60451. mouseDownNote = -1;
  60452. }
  60453. }
  60454. void MidiKeyboardComponent::updateNoteUnderMouse (const Point<int>& pos)
  60455. {
  60456. float mousePositionVelocity = 0.0f;
  60457. const int newNote = (mouseDragging || isMouseOver())
  60458. ? xyToNote (pos, mousePositionVelocity) : -1;
  60459. if (noteUnderMouse != newNote)
  60460. {
  60461. if (mouseDownNote >= 0)
  60462. {
  60463. state.noteOff (midiChannel, mouseDownNote);
  60464. mouseDownNote = -1;
  60465. }
  60466. if (mouseDragging && newNote >= 0)
  60467. {
  60468. if (! useMousePositionForVelocity)
  60469. mousePositionVelocity = 1.0f;
  60470. state.noteOn (midiChannel, newNote, mousePositionVelocity * velocity);
  60471. mouseDownNote = newNote;
  60472. }
  60473. repaintNote (noteUnderMouse);
  60474. noteUnderMouse = newNote;
  60475. repaintNote (noteUnderMouse);
  60476. }
  60477. else if (mouseDownNote >= 0 && ! mouseDragging)
  60478. {
  60479. state.noteOff (midiChannel, mouseDownNote);
  60480. mouseDownNote = -1;
  60481. }
  60482. }
  60483. void MidiKeyboardComponent::mouseMove (const MouseEvent& e)
  60484. {
  60485. updateNoteUnderMouse (e.getPosition());
  60486. stopTimer();
  60487. }
  60488. void MidiKeyboardComponent::mouseDrag (const MouseEvent& e)
  60489. {
  60490. float mousePositionVelocity;
  60491. const int newNote = xyToNote (e.getPosition(), mousePositionVelocity);
  60492. if (newNote >= 0)
  60493. mouseDraggedToKey (newNote, e);
  60494. updateNoteUnderMouse (e.getPosition());
  60495. }
  60496. bool MidiKeyboardComponent::mouseDownOnKey (int /*midiNoteNumber*/, const MouseEvent&)
  60497. {
  60498. return true;
  60499. }
  60500. void MidiKeyboardComponent::mouseDraggedToKey (int /*midiNoteNumber*/, const MouseEvent&)
  60501. {
  60502. }
  60503. void MidiKeyboardComponent::mouseDown (const MouseEvent& e)
  60504. {
  60505. float mousePositionVelocity;
  60506. const int newNote = xyToNote (e.getPosition(), mousePositionVelocity);
  60507. mouseDragging = false;
  60508. if (newNote >= 0 && mouseDownOnKey (newNote, e))
  60509. {
  60510. repaintNote (noteUnderMouse);
  60511. noteUnderMouse = -1;
  60512. mouseDragging = true;
  60513. updateNoteUnderMouse (e.getPosition());
  60514. startTimer (500);
  60515. }
  60516. }
  60517. void MidiKeyboardComponent::mouseUp (const MouseEvent& e)
  60518. {
  60519. mouseDragging = false;
  60520. updateNoteUnderMouse (e.getPosition());
  60521. stopTimer();
  60522. }
  60523. void MidiKeyboardComponent::mouseEnter (const MouseEvent& e)
  60524. {
  60525. updateNoteUnderMouse (e.getPosition());
  60526. }
  60527. void MidiKeyboardComponent::mouseExit (const MouseEvent& e)
  60528. {
  60529. updateNoteUnderMouse (e.getPosition());
  60530. }
  60531. void MidiKeyboardComponent::mouseWheelMove (const MouseEvent&, float ix, float iy)
  60532. {
  60533. setLowestVisibleKey (getLowestVisibleKey() + roundToInt ((ix != 0 ? ix : iy) * 5.0f));
  60534. }
  60535. void MidiKeyboardComponent::timerCallback()
  60536. {
  60537. updateNoteUnderMouse (getMouseXYRelative());
  60538. }
  60539. void MidiKeyboardComponent::clearKeyMappings()
  60540. {
  60541. resetAnyKeysInUse();
  60542. keyPressNotes.clear();
  60543. keyPresses.clear();
  60544. }
  60545. void MidiKeyboardComponent::setKeyPressForNote (const KeyPress& key,
  60546. const int midiNoteOffsetFromC)
  60547. {
  60548. removeKeyPressForNote (midiNoteOffsetFromC);
  60549. keyPressNotes.add (midiNoteOffsetFromC);
  60550. keyPresses.add (key);
  60551. }
  60552. void MidiKeyboardComponent::removeKeyPressForNote (const int midiNoteOffsetFromC)
  60553. {
  60554. for (int i = keyPressNotes.size(); --i >= 0;)
  60555. {
  60556. if (keyPressNotes.getUnchecked (i) == midiNoteOffsetFromC)
  60557. {
  60558. keyPressNotes.remove (i);
  60559. keyPresses.remove (i);
  60560. }
  60561. }
  60562. }
  60563. void MidiKeyboardComponent::setKeyPressBaseOctave (const int newOctaveNumber)
  60564. {
  60565. jassert (newOctaveNumber >= 0 && newOctaveNumber <= 10);
  60566. keyMappingOctave = newOctaveNumber;
  60567. }
  60568. bool MidiKeyboardComponent::keyStateChanged (const bool /*isKeyDown*/)
  60569. {
  60570. bool keyPressUsed = false;
  60571. for (int i = keyPresses.size(); --i >= 0;)
  60572. {
  60573. const int note = 12 * keyMappingOctave + keyPressNotes.getUnchecked (i);
  60574. if (keyPresses.getReference(i).isCurrentlyDown())
  60575. {
  60576. if (! keysPressed [note])
  60577. {
  60578. keysPressed.setBit (note);
  60579. state.noteOn (midiChannel, note, velocity);
  60580. keyPressUsed = true;
  60581. }
  60582. }
  60583. else
  60584. {
  60585. if (keysPressed [note])
  60586. {
  60587. keysPressed.clearBit (note);
  60588. state.noteOff (midiChannel, note);
  60589. keyPressUsed = true;
  60590. }
  60591. }
  60592. }
  60593. return keyPressUsed;
  60594. }
  60595. void MidiKeyboardComponent::focusLost (FocusChangeType)
  60596. {
  60597. resetAnyKeysInUse();
  60598. }
  60599. END_JUCE_NAMESPACE
  60600. /*** End of inlined file: juce_MidiKeyboardComponent.cpp ***/
  60601. /*** Start of inlined file: juce_OpenGLComponent.cpp ***/
  60602. #if JUCE_OPENGL
  60603. BEGIN_JUCE_NAMESPACE
  60604. extern void juce_glViewport (const int w, const int h);
  60605. OpenGLPixelFormat::OpenGLPixelFormat (const int bitsPerRGBComponent,
  60606. const int alphaBits_,
  60607. const int depthBufferBits_,
  60608. const int stencilBufferBits_)
  60609. : redBits (bitsPerRGBComponent),
  60610. greenBits (bitsPerRGBComponent),
  60611. blueBits (bitsPerRGBComponent),
  60612. alphaBits (alphaBits_),
  60613. depthBufferBits (depthBufferBits_),
  60614. stencilBufferBits (stencilBufferBits_),
  60615. accumulationBufferRedBits (0),
  60616. accumulationBufferGreenBits (0),
  60617. accumulationBufferBlueBits (0),
  60618. accumulationBufferAlphaBits (0),
  60619. fullSceneAntiAliasingNumSamples (0)
  60620. {
  60621. }
  60622. OpenGLPixelFormat::OpenGLPixelFormat (const OpenGLPixelFormat& other)
  60623. : redBits (other.redBits),
  60624. greenBits (other.greenBits),
  60625. blueBits (other.blueBits),
  60626. alphaBits (other.alphaBits),
  60627. depthBufferBits (other.depthBufferBits),
  60628. stencilBufferBits (other.stencilBufferBits),
  60629. accumulationBufferRedBits (other.accumulationBufferRedBits),
  60630. accumulationBufferGreenBits (other.accumulationBufferGreenBits),
  60631. accumulationBufferBlueBits (other.accumulationBufferBlueBits),
  60632. accumulationBufferAlphaBits (other.accumulationBufferAlphaBits),
  60633. fullSceneAntiAliasingNumSamples (other.fullSceneAntiAliasingNumSamples)
  60634. {
  60635. }
  60636. OpenGLPixelFormat& OpenGLPixelFormat::operator= (const OpenGLPixelFormat& other)
  60637. {
  60638. redBits = other.redBits;
  60639. greenBits = other.greenBits;
  60640. blueBits = other.blueBits;
  60641. alphaBits = other.alphaBits;
  60642. depthBufferBits = other.depthBufferBits;
  60643. stencilBufferBits = other.stencilBufferBits;
  60644. accumulationBufferRedBits = other.accumulationBufferRedBits;
  60645. accumulationBufferGreenBits = other.accumulationBufferGreenBits;
  60646. accumulationBufferBlueBits = other.accumulationBufferBlueBits;
  60647. accumulationBufferAlphaBits = other.accumulationBufferAlphaBits;
  60648. fullSceneAntiAliasingNumSamples = other.fullSceneAntiAliasingNumSamples;
  60649. return *this;
  60650. }
  60651. bool OpenGLPixelFormat::operator== (const OpenGLPixelFormat& other) const
  60652. {
  60653. return redBits == other.redBits
  60654. && greenBits == other.greenBits
  60655. && blueBits == other.blueBits
  60656. && alphaBits == other.alphaBits
  60657. && depthBufferBits == other.depthBufferBits
  60658. && stencilBufferBits == other.stencilBufferBits
  60659. && accumulationBufferRedBits == other.accumulationBufferRedBits
  60660. && accumulationBufferGreenBits == other.accumulationBufferGreenBits
  60661. && accumulationBufferBlueBits == other.accumulationBufferBlueBits
  60662. && accumulationBufferAlphaBits == other.accumulationBufferAlphaBits
  60663. && fullSceneAntiAliasingNumSamples == other.fullSceneAntiAliasingNumSamples;
  60664. }
  60665. static Array<OpenGLContext*> knownContexts;
  60666. OpenGLContext::OpenGLContext() throw()
  60667. {
  60668. knownContexts.add (this);
  60669. }
  60670. OpenGLContext::~OpenGLContext()
  60671. {
  60672. knownContexts.removeValue (this);
  60673. }
  60674. OpenGLContext* OpenGLContext::getCurrentContext()
  60675. {
  60676. for (int i = knownContexts.size(); --i >= 0;)
  60677. {
  60678. OpenGLContext* const oglc = knownContexts.getUnchecked(i);
  60679. if (oglc->isActive())
  60680. return oglc;
  60681. }
  60682. return 0;
  60683. }
  60684. class OpenGLComponent::OpenGLComponentWatcher : public ComponentMovementWatcher
  60685. {
  60686. public:
  60687. OpenGLComponentWatcher (OpenGLComponent* const owner_)
  60688. : ComponentMovementWatcher (owner_),
  60689. owner (owner_),
  60690. wasShowing (false)
  60691. {
  60692. }
  60693. ~OpenGLComponentWatcher() {}
  60694. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  60695. {
  60696. owner->updateContextPosition();
  60697. }
  60698. void componentPeerChanged()
  60699. {
  60700. const ScopedLock sl (owner->getContextLock());
  60701. owner->deleteContext();
  60702. }
  60703. void componentVisibilityChanged (Component&)
  60704. {
  60705. const bool isShowingNow = owner->isShowing();
  60706. if (wasShowing != isShowingNow)
  60707. {
  60708. wasShowing = isShowingNow;
  60709. owner->updateContextPosition();
  60710. }
  60711. }
  60712. juce_UseDebuggingNewOperator
  60713. private:
  60714. OpenGLComponent* const owner;
  60715. bool wasShowing;
  60716. };
  60717. OpenGLComponent::OpenGLComponent (const OpenGLType type_)
  60718. : type (type_),
  60719. contextToShareListsWith (0),
  60720. needToUpdateViewport (true)
  60721. {
  60722. setOpaque (true);
  60723. componentWatcher = new OpenGLComponentWatcher (this);
  60724. }
  60725. OpenGLComponent::~OpenGLComponent()
  60726. {
  60727. deleteContext();
  60728. componentWatcher = 0;
  60729. }
  60730. void OpenGLComponent::deleteContext()
  60731. {
  60732. const ScopedLock sl (contextLock);
  60733. context = 0;
  60734. }
  60735. void OpenGLComponent::updateContextPosition()
  60736. {
  60737. needToUpdateViewport = true;
  60738. if (getWidth() > 0 && getHeight() > 0)
  60739. {
  60740. Component* const topComp = getTopLevelComponent();
  60741. if (topComp->getPeer() != 0)
  60742. {
  60743. const ScopedLock sl (contextLock);
  60744. if (context != 0)
  60745. context->updateWindowPosition (getScreenX() - topComp->getScreenX(),
  60746. getScreenY() - topComp->getScreenY(),
  60747. getWidth(),
  60748. getHeight(),
  60749. topComp->getHeight());
  60750. }
  60751. }
  60752. }
  60753. const OpenGLPixelFormat OpenGLComponent::getPixelFormat() const
  60754. {
  60755. OpenGLPixelFormat pf;
  60756. const ScopedLock sl (contextLock);
  60757. if (context != 0)
  60758. pf = context->getPixelFormat();
  60759. return pf;
  60760. }
  60761. void OpenGLComponent::setPixelFormat (const OpenGLPixelFormat& formatToUse)
  60762. {
  60763. if (! (preferredPixelFormat == formatToUse))
  60764. {
  60765. const ScopedLock sl (contextLock);
  60766. deleteContext();
  60767. preferredPixelFormat = formatToUse;
  60768. }
  60769. }
  60770. void OpenGLComponent::shareWith (OpenGLContext* c)
  60771. {
  60772. if (contextToShareListsWith != c)
  60773. {
  60774. const ScopedLock sl (contextLock);
  60775. deleteContext();
  60776. contextToShareListsWith = c;
  60777. }
  60778. }
  60779. bool OpenGLComponent::makeCurrentContextActive()
  60780. {
  60781. if (context == 0)
  60782. {
  60783. const ScopedLock sl (contextLock);
  60784. if (isShowing() && getTopLevelComponent()->getPeer() != 0)
  60785. {
  60786. context = createContext();
  60787. if (context != 0)
  60788. {
  60789. updateContextPosition();
  60790. if (context->makeActive())
  60791. newOpenGLContextCreated();
  60792. }
  60793. }
  60794. }
  60795. return context != 0 && context->makeActive();
  60796. }
  60797. void OpenGLComponent::makeCurrentContextInactive()
  60798. {
  60799. if (context != 0)
  60800. context->makeInactive();
  60801. }
  60802. bool OpenGLComponent::isActiveContext() const throw()
  60803. {
  60804. return context != 0 && context->isActive();
  60805. }
  60806. void OpenGLComponent::swapBuffers()
  60807. {
  60808. if (context != 0)
  60809. context->swapBuffers();
  60810. }
  60811. void OpenGLComponent::paint (Graphics&)
  60812. {
  60813. if (renderAndSwapBuffers())
  60814. {
  60815. ComponentPeer* const peer = getPeer();
  60816. if (peer != 0)
  60817. {
  60818. const Point<int> topLeft (getScreenPosition() - peer->getScreenPosition());
  60819. peer->addMaskedRegion (topLeft.getX(), topLeft.getY(), getWidth(), getHeight());
  60820. }
  60821. }
  60822. }
  60823. bool OpenGLComponent::renderAndSwapBuffers()
  60824. {
  60825. const ScopedLock sl (contextLock);
  60826. if (! makeCurrentContextActive())
  60827. return false;
  60828. if (needToUpdateViewport)
  60829. {
  60830. needToUpdateViewport = false;
  60831. juce_glViewport (getWidth(), getHeight());
  60832. }
  60833. renderOpenGL();
  60834. swapBuffers();
  60835. return true;
  60836. }
  60837. void OpenGLComponent::internalRepaint (int x, int y, int w, int h)
  60838. {
  60839. Component::internalRepaint (x, y, w, h);
  60840. if (context != 0)
  60841. context->repaint();
  60842. }
  60843. END_JUCE_NAMESPACE
  60844. #endif
  60845. /*** End of inlined file: juce_OpenGLComponent.cpp ***/
  60846. /*** Start of inlined file: juce_PreferencesPanel.cpp ***/
  60847. BEGIN_JUCE_NAMESPACE
  60848. PreferencesPanel::PreferencesPanel()
  60849. : buttonSize (70)
  60850. {
  60851. }
  60852. PreferencesPanel::~PreferencesPanel()
  60853. {
  60854. currentPage = 0;
  60855. deleteAllChildren();
  60856. }
  60857. void PreferencesPanel::addSettingsPage (const String& title,
  60858. const Drawable* icon,
  60859. const Drawable* overIcon,
  60860. const Drawable* downIcon)
  60861. {
  60862. DrawableButton* button = new DrawableButton (title, DrawableButton::ImageAboveTextLabel);
  60863. button->setImages (icon, overIcon, downIcon);
  60864. button->setRadioGroupId (1);
  60865. button->addButtonListener (this);
  60866. button->setClickingTogglesState (true);
  60867. button->setWantsKeyboardFocus (false);
  60868. addAndMakeVisible (button);
  60869. resized();
  60870. if (currentPage == 0)
  60871. setCurrentPage (title);
  60872. }
  60873. void PreferencesPanel::addSettingsPage (const String& title,
  60874. const void* imageData,
  60875. const int imageDataSize)
  60876. {
  60877. DrawableImage icon, iconOver, iconDown;
  60878. icon.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  60879. iconOver.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  60880. iconOver.setOverlayColour (Colours::black.withAlpha (0.12f));
  60881. iconDown.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  60882. iconDown.setOverlayColour (Colours::black.withAlpha (0.25f));
  60883. addSettingsPage (title, &icon, &iconOver, &iconDown);
  60884. }
  60885. class PrefsDialogWindow : public DialogWindow
  60886. {
  60887. public:
  60888. PrefsDialogWindow (const String& dialogtitle,
  60889. const Colour& backgroundColour)
  60890. : DialogWindow (dialogtitle, backgroundColour, true)
  60891. {
  60892. }
  60893. ~PrefsDialogWindow()
  60894. {
  60895. }
  60896. void closeButtonPressed()
  60897. {
  60898. exitModalState (0);
  60899. }
  60900. private:
  60901. PrefsDialogWindow (const PrefsDialogWindow&);
  60902. PrefsDialogWindow& operator= (const PrefsDialogWindow&);
  60903. };
  60904. void PreferencesPanel::showInDialogBox (const String& dialogtitle,
  60905. int dialogWidth,
  60906. int dialogHeight,
  60907. const Colour& backgroundColour)
  60908. {
  60909. setSize (dialogWidth, dialogHeight);
  60910. PrefsDialogWindow dw (dialogtitle, backgroundColour);
  60911. dw.setContentComponent (this, true, true);
  60912. dw.centreAroundComponent (0, dw.getWidth(), dw.getHeight());
  60913. dw.runModalLoop();
  60914. dw.setContentComponent (0, false, false);
  60915. }
  60916. void PreferencesPanel::resized()
  60917. {
  60918. int x = 0;
  60919. for (int i = 0; i < getNumChildComponents(); ++i)
  60920. {
  60921. Component* c = getChildComponent (i);
  60922. if (dynamic_cast <DrawableButton*> (c) == 0)
  60923. {
  60924. c->setBounds (0, buttonSize + 5, getWidth(), getHeight() - buttonSize - 5);
  60925. }
  60926. else
  60927. {
  60928. c->setBounds (x, 0, buttonSize, buttonSize);
  60929. x += buttonSize;
  60930. }
  60931. }
  60932. }
  60933. void PreferencesPanel::paint (Graphics& g)
  60934. {
  60935. g.setColour (Colours::grey);
  60936. g.fillRect (0, buttonSize + 2, getWidth(), 1);
  60937. }
  60938. void PreferencesPanel::setCurrentPage (const String& pageName)
  60939. {
  60940. if (currentPageName != pageName)
  60941. {
  60942. currentPageName = pageName;
  60943. currentPage = 0;
  60944. currentPage = createComponentForPage (pageName);
  60945. if (currentPage != 0)
  60946. {
  60947. addAndMakeVisible (currentPage);
  60948. currentPage->toBack();
  60949. resized();
  60950. }
  60951. for (int i = 0; i < getNumChildComponents(); ++i)
  60952. {
  60953. DrawableButton* db = dynamic_cast <DrawableButton*> (getChildComponent (i));
  60954. if (db != 0 && db->getName() == pageName)
  60955. {
  60956. db->setToggleState (true, false);
  60957. break;
  60958. }
  60959. }
  60960. }
  60961. }
  60962. void PreferencesPanel::buttonClicked (Button*)
  60963. {
  60964. for (int i = 0; i < getNumChildComponents(); ++i)
  60965. {
  60966. DrawableButton* db = dynamic_cast <DrawableButton*> (getChildComponent (i));
  60967. if (db != 0 && db->getToggleState())
  60968. {
  60969. setCurrentPage (db->getName());
  60970. break;
  60971. }
  60972. }
  60973. }
  60974. END_JUCE_NAMESPACE
  60975. /*** End of inlined file: juce_PreferencesPanel.cpp ***/
  60976. /*** Start of inlined file: juce_SystemTrayIconComponent.cpp ***/
  60977. #if JUCE_WINDOWS || JUCE_LINUX
  60978. BEGIN_JUCE_NAMESPACE
  60979. SystemTrayIconComponent::SystemTrayIconComponent()
  60980. {
  60981. addToDesktop (0);
  60982. }
  60983. SystemTrayIconComponent::~SystemTrayIconComponent()
  60984. {
  60985. }
  60986. END_JUCE_NAMESPACE
  60987. #endif
  60988. /*** End of inlined file: juce_SystemTrayIconComponent.cpp ***/
  60989. /*** Start of inlined file: juce_AlertWindow.cpp ***/
  60990. BEGIN_JUCE_NAMESPACE
  60991. class AlertWindowTextEditor : public TextEditor
  60992. {
  60993. public:
  60994. AlertWindowTextEditor (const String& name, const bool isPasswordBox)
  60995. : TextEditor (name, isPasswordBox ? getDefaultPasswordChar() : 0)
  60996. {
  60997. setSelectAllWhenFocused (true);
  60998. }
  60999. ~AlertWindowTextEditor()
  61000. {
  61001. }
  61002. void returnPressed()
  61003. {
  61004. // pass these up the component hierarchy to be trigger the buttons
  61005. getParentComponent()->keyPressed (KeyPress (KeyPress::returnKey, 0, '\n'));
  61006. }
  61007. void escapePressed()
  61008. {
  61009. // pass these up the component hierarchy to be trigger the buttons
  61010. getParentComponent()->keyPressed (KeyPress (KeyPress::escapeKey, 0, 0));
  61011. }
  61012. private:
  61013. AlertWindowTextEditor (const AlertWindowTextEditor&);
  61014. AlertWindowTextEditor& operator= (const AlertWindowTextEditor&);
  61015. static juce_wchar getDefaultPasswordChar() throw()
  61016. {
  61017. #if JUCE_LINUX
  61018. return 0x2022;
  61019. #else
  61020. return 0x25cf;
  61021. #endif
  61022. }
  61023. };
  61024. AlertWindow::AlertWindow (const String& title,
  61025. const String& message,
  61026. AlertIconType iconType,
  61027. Component* associatedComponent_)
  61028. : TopLevelWindow (title, true),
  61029. alertIconType (iconType),
  61030. associatedComponent (associatedComponent_)
  61031. {
  61032. if (message.isEmpty())
  61033. text = " "; // to force an update if the message is empty
  61034. setMessage (message);
  61035. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  61036. {
  61037. Component* const c = Desktop::getInstance().getComponent (i);
  61038. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  61039. {
  61040. setAlwaysOnTop (true);
  61041. break;
  61042. }
  61043. }
  61044. if (JUCEApplication::getInstance() == 0)
  61045. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  61046. lookAndFeelChanged();
  61047. constrainer.setMinimumOnscreenAmounts (0x10000, 0x10000, 0x10000, 0x10000);
  61048. }
  61049. AlertWindow::~AlertWindow()
  61050. {
  61051. for (int i = customComps.size(); --i >= 0;)
  61052. removeChildComponent ((Component*) customComps[i]);
  61053. deleteAllChildren();
  61054. }
  61055. void AlertWindow::userTriedToCloseWindow()
  61056. {
  61057. exitModalState (0);
  61058. }
  61059. void AlertWindow::setMessage (const String& message)
  61060. {
  61061. const String newMessage (message.substring (0, 2048));
  61062. if (text != newMessage)
  61063. {
  61064. text = newMessage;
  61065. font.setHeight (15.0f);
  61066. Font titleFont (font.getHeight() * 1.1f, Font::bold);
  61067. textLayout.setText (getName() + "\n\n", titleFont);
  61068. textLayout.appendText (text, font);
  61069. updateLayout (true);
  61070. repaint();
  61071. }
  61072. }
  61073. void AlertWindow::buttonClicked (Button* button)
  61074. {
  61075. for (int i = 0; i < buttons.size(); i++)
  61076. {
  61077. TextButton* const c = (TextButton*) buttons[i];
  61078. if (button->getName() == c->getName())
  61079. {
  61080. if (c->getParentComponent() != 0)
  61081. c->getParentComponent()->exitModalState (c->getCommandID());
  61082. break;
  61083. }
  61084. }
  61085. }
  61086. void AlertWindow::addButton (const String& name,
  61087. const int returnValue,
  61088. const KeyPress& shortcutKey1,
  61089. const KeyPress& shortcutKey2)
  61090. {
  61091. TextButton* const b = new TextButton (name, String::empty);
  61092. b->setWantsKeyboardFocus (true);
  61093. b->setMouseClickGrabsKeyboardFocus (false);
  61094. b->setCommandToTrigger (0, returnValue, false);
  61095. b->addShortcut (shortcutKey1);
  61096. b->addShortcut (shortcutKey2);
  61097. b->addButtonListener (this);
  61098. b->changeWidthToFitText (getLookAndFeel().getAlertWindowButtonHeight());
  61099. addAndMakeVisible (b, 0);
  61100. buttons.add (b);
  61101. updateLayout (false);
  61102. }
  61103. int AlertWindow::getNumButtons() const
  61104. {
  61105. return buttons.size();
  61106. }
  61107. void AlertWindow::triggerButtonClick (const String& buttonName)
  61108. {
  61109. for (int i = buttons.size(); --i >= 0;)
  61110. {
  61111. TextButton* const b = (TextButton*) buttons[i];
  61112. if (buttonName == b->getName())
  61113. {
  61114. b->triggerClick();
  61115. break;
  61116. }
  61117. }
  61118. }
  61119. void AlertWindow::addTextEditor (const String& name,
  61120. const String& initialContents,
  61121. const String& onScreenLabel,
  61122. const bool isPasswordBox)
  61123. {
  61124. AlertWindowTextEditor* const tc = new AlertWindowTextEditor (name, isPasswordBox);
  61125. tc->setColour (TextEditor::outlineColourId, findColour (ComboBox::outlineColourId));
  61126. tc->setFont (font);
  61127. tc->setText (initialContents);
  61128. tc->setCaretPosition (initialContents.length());
  61129. addAndMakeVisible (tc);
  61130. textBoxes.add (tc);
  61131. allComps.add (tc);
  61132. textboxNames.add (onScreenLabel);
  61133. updateLayout (false);
  61134. }
  61135. const String AlertWindow::getTextEditorContents (const String& nameOfTextEditor) const
  61136. {
  61137. for (int i = textBoxes.size(); --i >= 0;)
  61138. if (((TextEditor*)textBoxes[i])->getName() == nameOfTextEditor)
  61139. return ((TextEditor*)textBoxes[i])->getText();
  61140. return String::empty;
  61141. }
  61142. void AlertWindow::addComboBox (const String& name,
  61143. const StringArray& items,
  61144. const String& onScreenLabel)
  61145. {
  61146. ComboBox* const cb = new ComboBox (name);
  61147. for (int i = 0; i < items.size(); ++i)
  61148. cb->addItem (items[i], i + 1);
  61149. addAndMakeVisible (cb);
  61150. cb->setSelectedItemIndex (0);
  61151. comboBoxes.add (cb);
  61152. allComps.add (cb);
  61153. comboBoxNames.add (onScreenLabel);
  61154. updateLayout (false);
  61155. }
  61156. ComboBox* AlertWindow::getComboBoxComponent (const String& nameOfList) const
  61157. {
  61158. for (int i = comboBoxes.size(); --i >= 0;)
  61159. if (((ComboBox*) comboBoxes[i])->getName() == nameOfList)
  61160. return (ComboBox*) comboBoxes[i];
  61161. return 0;
  61162. }
  61163. class AlertTextComp : public TextEditor
  61164. {
  61165. public:
  61166. AlertTextComp (const String& message,
  61167. const Font& font)
  61168. {
  61169. setReadOnly (true);
  61170. setMultiLine (true, true);
  61171. setCaretVisible (false);
  61172. setScrollbarsShown (true);
  61173. lookAndFeelChanged();
  61174. setWantsKeyboardFocus (false);
  61175. setFont (font);
  61176. setText (message, false);
  61177. bestWidth = 2 * (int) std::sqrt (font.getHeight() * font.getStringWidth (message));
  61178. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  61179. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  61180. setColour (TextEditor::shadowColourId, Colours::transparentBlack);
  61181. }
  61182. ~AlertTextComp()
  61183. {
  61184. }
  61185. int getPreferredWidth() const throw() { return bestWidth; }
  61186. void updateLayout (const int width)
  61187. {
  61188. TextLayout text;
  61189. text.appendText (getText(), getFont());
  61190. text.layout (width - 8, Justification::topLeft, true);
  61191. setSize (width, jmin (width, text.getHeight() + (int) getFont().getHeight()));
  61192. }
  61193. private:
  61194. int bestWidth;
  61195. AlertTextComp (const AlertTextComp&);
  61196. AlertTextComp& operator= (const AlertTextComp&);
  61197. };
  61198. void AlertWindow::addTextBlock (const String& textBlock)
  61199. {
  61200. AlertTextComp* const c = new AlertTextComp (textBlock, font);
  61201. textBlocks.add (c);
  61202. allComps.add (c);
  61203. addAndMakeVisible (c);
  61204. updateLayout (false);
  61205. }
  61206. void AlertWindow::addProgressBarComponent (double& progressValue)
  61207. {
  61208. ProgressBar* const pb = new ProgressBar (progressValue);
  61209. progressBars.add (pb);
  61210. allComps.add (pb);
  61211. addAndMakeVisible (pb);
  61212. updateLayout (false);
  61213. }
  61214. void AlertWindow::addCustomComponent (Component* const component)
  61215. {
  61216. customComps.add (component);
  61217. allComps.add (component);
  61218. addAndMakeVisible (component);
  61219. updateLayout (false);
  61220. }
  61221. int AlertWindow::getNumCustomComponents() const
  61222. {
  61223. return customComps.size();
  61224. }
  61225. Component* AlertWindow::getCustomComponent (const int index) const
  61226. {
  61227. return (Component*) customComps [index];
  61228. }
  61229. Component* AlertWindow::removeCustomComponent (const int index)
  61230. {
  61231. Component* const c = getCustomComponent (index);
  61232. if (c != 0)
  61233. {
  61234. customComps.removeValue (c);
  61235. allComps.removeValue (c);
  61236. removeChildComponent (c);
  61237. updateLayout (false);
  61238. }
  61239. return c;
  61240. }
  61241. void AlertWindow::paint (Graphics& g)
  61242. {
  61243. getLookAndFeel().drawAlertBox (g, *this, textArea, textLayout);
  61244. g.setColour (findColour (textColourId));
  61245. g.setFont (getLookAndFeel().getAlertWindowFont());
  61246. int i;
  61247. for (i = textBoxes.size(); --i >= 0;)
  61248. {
  61249. const TextEditor* const te = (TextEditor*) textBoxes[i];
  61250. g.drawFittedText (textboxNames[i],
  61251. te->getX(), te->getY() - 14,
  61252. te->getWidth(), 14,
  61253. Justification::centredLeft, 1);
  61254. }
  61255. for (i = comboBoxNames.size(); --i >= 0;)
  61256. {
  61257. const ComboBox* const cb = (ComboBox*) comboBoxes[i];
  61258. g.drawFittedText (comboBoxNames[i],
  61259. cb->getX(), cb->getY() - 14,
  61260. cb->getWidth(), 14,
  61261. Justification::centredLeft, 1);
  61262. }
  61263. for (i = customComps.size(); --i >= 0;)
  61264. {
  61265. const Component* const c = (Component*) customComps[i];
  61266. g.drawFittedText (c->getName(),
  61267. c->getX(), c->getY() - 14,
  61268. c->getWidth(), 14,
  61269. Justification::centredLeft, 1);
  61270. }
  61271. }
  61272. void AlertWindow::updateLayout (const bool onlyIncreaseSize)
  61273. {
  61274. const int titleH = 24;
  61275. const int iconWidth = 80;
  61276. const int wid = jmax (font.getStringWidth (text),
  61277. font.getStringWidth (getName()));
  61278. const int sw = (int) std::sqrt (font.getHeight() * wid);
  61279. int w = jmin (300 + sw * 2, (int) (getParentWidth() * 0.7f));
  61280. const int edgeGap = 10;
  61281. const int labelHeight = 18;
  61282. int iconSpace;
  61283. if (alertIconType == NoIcon)
  61284. {
  61285. textLayout.layout (w, Justification::horizontallyCentred, true);
  61286. iconSpace = 0;
  61287. }
  61288. else
  61289. {
  61290. textLayout.layout (w, Justification::left, true);
  61291. iconSpace = iconWidth;
  61292. }
  61293. w = jmax (350, textLayout.getWidth() + iconSpace + edgeGap * 4);
  61294. w = jmin (w, (int) (getParentWidth() * 0.7f));
  61295. const int textLayoutH = textLayout.getHeight();
  61296. const int textBottom = 16 + titleH + textLayoutH;
  61297. int h = textBottom;
  61298. int buttonW = 40;
  61299. int i;
  61300. for (i = 0; i < buttons.size(); ++i)
  61301. buttonW += 16 + ((const TextButton*) buttons[i])->getWidth();
  61302. w = jmax (buttonW, w);
  61303. h += (textBoxes.size() + comboBoxes.size() + progressBars.size()) * 50;
  61304. if (buttons.size() > 0)
  61305. h += 20 + ((TextButton*) buttons[0])->getHeight();
  61306. for (i = customComps.size(); --i >= 0;)
  61307. {
  61308. Component* c = (Component*) customComps[i];
  61309. w = jmax (w, (c->getWidth() * 100) / 80);
  61310. h += 10 + c->getHeight();
  61311. if (c->getName().isNotEmpty())
  61312. h += labelHeight;
  61313. }
  61314. for (i = textBlocks.size(); --i >= 0;)
  61315. {
  61316. const AlertTextComp* const ac = (AlertTextComp*) textBlocks[i];
  61317. w = jmax (w, ac->getPreferredWidth());
  61318. }
  61319. w = jmin (w, (int) (getParentWidth() * 0.7f));
  61320. for (i = textBlocks.size(); --i >= 0;)
  61321. {
  61322. AlertTextComp* const ac = (AlertTextComp*) textBlocks[i];
  61323. ac->updateLayout ((int) (w * 0.8f));
  61324. h += ac->getHeight() + 10;
  61325. }
  61326. h = jmin (getParentHeight() - 50, h);
  61327. if (onlyIncreaseSize)
  61328. {
  61329. w = jmax (w, getWidth());
  61330. h = jmax (h, getHeight());
  61331. }
  61332. if (! isVisible())
  61333. {
  61334. centreAroundComponent (associatedComponent, w, h);
  61335. }
  61336. else
  61337. {
  61338. const int cx = getX() + getWidth() / 2;
  61339. const int cy = getY() + getHeight() / 2;
  61340. setBounds (cx - w / 2,
  61341. cy - h / 2,
  61342. w, h);
  61343. }
  61344. textArea.setBounds (edgeGap, edgeGap, w - (edgeGap * 2), h - edgeGap);
  61345. const int spacer = 16;
  61346. int totalWidth = -spacer;
  61347. for (i = buttons.size(); --i >= 0;)
  61348. totalWidth += ((TextButton*) buttons[i])->getWidth() + spacer;
  61349. int x = (w - totalWidth) / 2;
  61350. int y = (int) (getHeight() * 0.95f);
  61351. for (i = 0; i < buttons.size(); ++i)
  61352. {
  61353. TextButton* const c = (TextButton*) buttons[i];
  61354. int ny = proportionOfHeight (0.95f) - c->getHeight();
  61355. c->setTopLeftPosition (x, ny);
  61356. if (ny < y)
  61357. y = ny;
  61358. x += c->getWidth() + spacer;
  61359. c->toFront (false);
  61360. }
  61361. y = textBottom;
  61362. for (i = 0; i < allComps.size(); ++i)
  61363. {
  61364. Component* const c = (Component*) allComps[i];
  61365. h = 22;
  61366. const int comboIndex = comboBoxes.indexOf (c);
  61367. if (comboIndex >= 0 && comboBoxNames [comboIndex].isNotEmpty())
  61368. y += labelHeight;
  61369. const int tbIndex = textBoxes.indexOf (c);
  61370. if (tbIndex >= 0 && textboxNames[tbIndex].isNotEmpty())
  61371. y += labelHeight;
  61372. if (customComps.contains (c))
  61373. {
  61374. if (c->getName().isNotEmpty())
  61375. y += labelHeight;
  61376. c->setTopLeftPosition (proportionOfWidth (0.1f), y);
  61377. h = c->getHeight();
  61378. }
  61379. else if (textBlocks.contains (c))
  61380. {
  61381. c->setTopLeftPosition ((getWidth() - c->getWidth()) / 2, y);
  61382. h = c->getHeight();
  61383. }
  61384. else
  61385. {
  61386. c->setBounds (proportionOfWidth (0.1f), y, proportionOfWidth (0.8f), h);
  61387. }
  61388. y += h + 10;
  61389. }
  61390. setWantsKeyboardFocus (getNumChildComponents() == 0);
  61391. }
  61392. bool AlertWindow::containsAnyExtraComponents() const
  61393. {
  61394. return textBoxes.size()
  61395. + comboBoxes.size()
  61396. + progressBars.size()
  61397. + customComps.size() > 0;
  61398. }
  61399. void AlertWindow::mouseDown (const MouseEvent&)
  61400. {
  61401. dragger.startDraggingComponent (this, &constrainer);
  61402. }
  61403. void AlertWindow::mouseDrag (const MouseEvent& e)
  61404. {
  61405. dragger.dragComponent (this, e);
  61406. }
  61407. bool AlertWindow::keyPressed (const KeyPress& key)
  61408. {
  61409. for (int i = buttons.size(); --i >= 0;)
  61410. {
  61411. TextButton* const b = (TextButton*) buttons[i];
  61412. if (b->isRegisteredForShortcut (key))
  61413. {
  61414. b->triggerClick();
  61415. return true;
  61416. }
  61417. }
  61418. if (key.isKeyCode (KeyPress::escapeKey) && buttons.size() == 0)
  61419. {
  61420. exitModalState (0);
  61421. return true;
  61422. }
  61423. else if (key.isKeyCode (KeyPress::returnKey) && buttons.size() == 1)
  61424. {
  61425. ((TextButton*) buttons.getFirst())->triggerClick();
  61426. return true;
  61427. }
  61428. return false;
  61429. }
  61430. void AlertWindow::lookAndFeelChanged()
  61431. {
  61432. const int newFlags = getLookAndFeel().getAlertBoxWindowFlags();
  61433. setUsingNativeTitleBar ((newFlags & ComponentPeer::windowHasTitleBar) != 0);
  61434. setDropShadowEnabled (isOpaque() && (newFlags & ComponentPeer::windowHasDropShadow) != 0);
  61435. }
  61436. int AlertWindow::getDesktopWindowStyleFlags() const
  61437. {
  61438. return getLookAndFeel().getAlertBoxWindowFlags();
  61439. }
  61440. struct AlertWindowInfo
  61441. {
  61442. String title, message, button1, button2, button3;
  61443. AlertWindow::AlertIconType iconType;
  61444. int numButtons;
  61445. Component::SafePointer<Component> associatedComponent;
  61446. int run() const
  61447. {
  61448. return (int) (pointer_sized_int)
  61449. MessageManager::getInstance()->callFunctionOnMessageThread (showCallback, (void*) this);
  61450. }
  61451. private:
  61452. int show() const
  61453. {
  61454. LookAndFeel& lf = associatedComponent != 0 ? associatedComponent->getLookAndFeel()
  61455. : LookAndFeel::getDefaultLookAndFeel();
  61456. ScopedPointer <Component> alertBox (lf.createAlertWindow (title, message, button1, button2, button3,
  61457. iconType, numButtons, associatedComponent));
  61458. jassert (alertBox != 0); // you have to return one of these!
  61459. return alertBox->runModalLoop();
  61460. }
  61461. static void* showCallback (void* userData)
  61462. {
  61463. return (void*) (pointer_sized_int) ((const AlertWindowInfo*) userData)->show();
  61464. }
  61465. };
  61466. void AlertWindow::showMessageBox (AlertIconType iconType,
  61467. const String& title,
  61468. const String& message,
  61469. const String& buttonText,
  61470. Component* associatedComponent)
  61471. {
  61472. AlertWindowInfo info;
  61473. info.title = title;
  61474. info.message = message;
  61475. info.button1 = buttonText.isEmpty() ? TRANS("ok") : buttonText;
  61476. info.iconType = iconType;
  61477. info.numButtons = 1;
  61478. info.associatedComponent = associatedComponent;
  61479. info.run();
  61480. }
  61481. bool AlertWindow::showOkCancelBox (AlertIconType iconType,
  61482. const String& title,
  61483. const String& message,
  61484. const String& button1Text,
  61485. const String& button2Text,
  61486. Component* associatedComponent)
  61487. {
  61488. AlertWindowInfo info;
  61489. info.title = title;
  61490. info.message = message;
  61491. info.button1 = button1Text.isEmpty() ? TRANS("ok") : button1Text;
  61492. info.button2 = button2Text.isEmpty() ? TRANS("cancel") : button2Text;
  61493. info.iconType = iconType;
  61494. info.numButtons = 2;
  61495. info.associatedComponent = associatedComponent;
  61496. return info.run() != 0;
  61497. }
  61498. int AlertWindow::showYesNoCancelBox (AlertIconType iconType,
  61499. const String& title,
  61500. const String& message,
  61501. const String& button1Text,
  61502. const String& button2Text,
  61503. const String& button3Text,
  61504. Component* associatedComponent)
  61505. {
  61506. AlertWindowInfo info;
  61507. info.title = title;
  61508. info.message = message;
  61509. info.button1 = button1Text.isEmpty() ? TRANS("yes") : button1Text;
  61510. info.button2 = button2Text.isEmpty() ? TRANS("no") : button2Text;
  61511. info.button3 = button3Text.isEmpty() ? TRANS("cancel") : button3Text;
  61512. info.iconType = iconType;
  61513. info.numButtons = 3;
  61514. info.associatedComponent = associatedComponent;
  61515. return info.run();
  61516. }
  61517. END_JUCE_NAMESPACE
  61518. /*** End of inlined file: juce_AlertWindow.cpp ***/
  61519. /*** Start of inlined file: juce_CallOutBox.cpp ***/
  61520. BEGIN_JUCE_NAMESPACE
  61521. CallOutBox::CallOutBox (Component& contentComponent,
  61522. Component& componentToPointTo,
  61523. Component* const parentComponent)
  61524. : borderSpace (20), arrowSize (16.0f), content (contentComponent)
  61525. {
  61526. addAndMakeVisible (&content);
  61527. if (parentComponent != 0)
  61528. {
  61529. updatePosition (parentComponent->getLocalBounds(),
  61530. componentToPointTo.getLocalBounds()
  61531. + componentToPointTo.relativePositionToOtherComponent (parentComponent, Point<int>()));
  61532. parentComponent->addAndMakeVisible (this);
  61533. }
  61534. else
  61535. {
  61536. updatePosition (componentToPointTo.getScreenBounds(),
  61537. componentToPointTo.getParentMonitorArea());
  61538. addToDesktop (ComponentPeer::windowIsTemporary);
  61539. }
  61540. }
  61541. CallOutBox::~CallOutBox()
  61542. {
  61543. }
  61544. void CallOutBox::setArrowSize (const float newSize)
  61545. {
  61546. arrowSize = newSize;
  61547. borderSpace = jmax (20, (int) arrowSize);
  61548. refreshPath();
  61549. }
  61550. void CallOutBox::paint (Graphics& g)
  61551. {
  61552. if (background.isNull())
  61553. {
  61554. background = Image (Image::ARGB, getWidth(), getHeight(), true);
  61555. Graphics g (background);
  61556. getLookAndFeel().drawCallOutBoxBackground (*this, g, outline);
  61557. }
  61558. g.setColour (Colours::black);
  61559. g.drawImageAt (background, 0, 0);
  61560. }
  61561. void CallOutBox::resized()
  61562. {
  61563. content.setTopLeftPosition (borderSpace, borderSpace);
  61564. refreshPath();
  61565. }
  61566. void CallOutBox::moved()
  61567. {
  61568. refreshPath();
  61569. }
  61570. void CallOutBox::childBoundsChanged (Component*)
  61571. {
  61572. updatePosition (targetArea, availableArea);
  61573. }
  61574. bool CallOutBox::hitTest (int x, int y)
  61575. {
  61576. return outline.contains ((float) x, (float) y);
  61577. }
  61578. void CallOutBox::inputAttemptWhenModal()
  61579. {
  61580. exitModalState (0);
  61581. setVisible (false);
  61582. }
  61583. bool CallOutBox::keyPressed (const KeyPress& key)
  61584. {
  61585. if (key.isKeyCode (KeyPress::escapeKey))
  61586. {
  61587. inputAttemptWhenModal();
  61588. return true;
  61589. }
  61590. return false;
  61591. }
  61592. void CallOutBox::updatePosition (const Rectangle<int>& newAreaToPointTo, const Rectangle<int>& newAreaToFitIn)
  61593. {
  61594. targetArea = newAreaToPointTo;
  61595. availableArea = newAreaToFitIn;
  61596. Rectangle<int> bounds (0, 0,
  61597. content.getWidth() + borderSpace * 2,
  61598. content.getHeight() + borderSpace * 2);
  61599. const int hw = bounds.getWidth() / 2;
  61600. const int hh = bounds.getHeight() / 2;
  61601. const float hwReduced = (float) (hw - borderSpace * 3);
  61602. const float hhReduced = (float) (hh - borderSpace * 3);
  61603. const float arrowIndent = borderSpace - arrowSize;
  61604. Point<float> targets[4] = { Point<float> ((float) targetArea.getCentreX(), (float) targetArea.getBottom()),
  61605. Point<float> ((float) targetArea.getRight(), (float) targetArea.getCentreY()),
  61606. Point<float> ((float) targetArea.getX(), (float) targetArea.getCentreY()),
  61607. Point<float> ((float) targetArea.getCentreX(), (float) targetArea.getY()) };
  61608. Line<float> lines[4] = { Line<float> (targets[0].translated (-hwReduced, hh - arrowIndent), targets[0].translated (hwReduced, hh - arrowIndent)),
  61609. Line<float> (targets[1].translated (hw - arrowIndent, -hhReduced), targets[1].translated (hw - arrowIndent, hhReduced)),
  61610. Line<float> (targets[2].translated (-(hw - arrowIndent), -hhReduced), targets[2].translated (-(hw - arrowIndent), hhReduced)),
  61611. Line<float> (targets[3].translated (-hwReduced, -(hh - arrowIndent)), targets[3].translated (hwReduced, -(hh - arrowIndent))) };
  61612. const Rectangle<float> centrePointArea (newAreaToFitIn.reduced (hw, hh).toFloat());
  61613. float nearest = 1.0e9f;
  61614. for (int i = 0; i < 4; ++i)
  61615. {
  61616. Line<float> constrainedLine (centrePointArea.getConstrainedPoint (lines[i].getStart()),
  61617. centrePointArea.getConstrainedPoint (lines[i].getEnd()));
  61618. const Point<float> centre (constrainedLine.findNearestPointTo (centrePointArea.getCentre()));
  61619. float distanceFromCentre = centre.getDistanceFrom (centrePointArea.getCentre());
  61620. if (! (centrePointArea.contains (lines[i].getStart()) || centrePointArea.contains (lines[i].getEnd())))
  61621. distanceFromCentre *= 2.0f;
  61622. if (distanceFromCentre < nearest)
  61623. {
  61624. nearest = distanceFromCentre;
  61625. targetPoint = targets[i];
  61626. bounds.setPosition ((int) (centre.getX() - hw),
  61627. (int) (centre.getY() - hh));
  61628. }
  61629. }
  61630. setBounds (bounds);
  61631. }
  61632. void CallOutBox::refreshPath()
  61633. {
  61634. repaint();
  61635. background = Image();
  61636. outline.clear();
  61637. const float gap = 4.5f;
  61638. const float cornerSize = 9.0f;
  61639. const float cornerSize2 = 2.0f * cornerSize;
  61640. const float arrowBaseWidth = arrowSize * 0.7f;
  61641. const float left = content.getX() - gap, top = content.getY() - gap, right = content.getRight() + gap, bottom = content.getBottom() + gap;
  61642. const float targetX = targetPoint.getX() - getX(), targetY = targetPoint.getY() - getY();
  61643. outline.startNewSubPath (left + cornerSize, top);
  61644. if (targetY <= top)
  61645. {
  61646. outline.lineTo (targetX - arrowBaseWidth, top);
  61647. outline.lineTo (targetX, targetY);
  61648. outline.lineTo (targetX + arrowBaseWidth, top);
  61649. }
  61650. outline.lineTo (right - cornerSize, top);
  61651. outline.addArc (right - cornerSize2, top, cornerSize2, cornerSize2, 0, float_Pi * 0.5f);
  61652. if (targetX >= right)
  61653. {
  61654. outline.lineTo (right, targetY - arrowBaseWidth);
  61655. outline.lineTo (targetX, targetY);
  61656. outline.lineTo (right, targetY + arrowBaseWidth);
  61657. }
  61658. outline.lineTo (right, bottom - cornerSize);
  61659. outline.addArc (right - cornerSize2, bottom - cornerSize2, cornerSize2, cornerSize2, float_Pi * 0.5f, float_Pi);
  61660. if (targetY >= bottom)
  61661. {
  61662. outline.lineTo (targetX + arrowBaseWidth, bottom);
  61663. outline.lineTo (targetX, targetY);
  61664. outline.lineTo (targetX - arrowBaseWidth, bottom);
  61665. }
  61666. outline.lineTo (left + cornerSize, bottom);
  61667. outline.addArc (left, bottom - cornerSize2, cornerSize2, cornerSize2, float_Pi, float_Pi * 1.5f);
  61668. if (targetX <= left)
  61669. {
  61670. outline.lineTo (left, targetY + arrowBaseWidth);
  61671. outline.lineTo (targetX, targetY);
  61672. outline.lineTo (left, targetY - arrowBaseWidth);
  61673. }
  61674. outline.lineTo (left, top + cornerSize);
  61675. outline.addArc (left, top, cornerSize2, cornerSize2, float_Pi * 1.5f, float_Pi * 2.0f - 0.05f);
  61676. outline.closeSubPath();
  61677. }
  61678. END_JUCE_NAMESPACE
  61679. /*** End of inlined file: juce_CallOutBox.cpp ***/
  61680. /*** Start of inlined file: juce_ComponentPeer.cpp ***/
  61681. BEGIN_JUCE_NAMESPACE
  61682. //#define JUCE_ENABLE_REPAINT_DEBUGGING 1
  61683. static Array <ComponentPeer*> heavyweightPeers;
  61684. ComponentPeer::ComponentPeer (Component* const component_, const int styleFlags_)
  61685. : component (component_),
  61686. styleFlags (styleFlags_),
  61687. lastPaintTime (0),
  61688. constrainer (0),
  61689. lastDragAndDropCompUnderMouse (0),
  61690. fakeMouseMessageSent (false),
  61691. isWindowMinimised (false)
  61692. {
  61693. heavyweightPeers.add (this);
  61694. }
  61695. ComponentPeer::~ComponentPeer()
  61696. {
  61697. heavyweightPeers.removeValue (this);
  61698. Desktop::getInstance().triggerFocusCallback();
  61699. }
  61700. int ComponentPeer::getNumPeers() throw()
  61701. {
  61702. return heavyweightPeers.size();
  61703. }
  61704. ComponentPeer* ComponentPeer::getPeer (const int index) throw()
  61705. {
  61706. return heavyweightPeers [index];
  61707. }
  61708. ComponentPeer* ComponentPeer::getPeerFor (const Component* const component) throw()
  61709. {
  61710. for (int i = heavyweightPeers.size(); --i >= 0;)
  61711. {
  61712. ComponentPeer* const peer = heavyweightPeers.getUnchecked(i);
  61713. if (peer->getComponent() == component)
  61714. return peer;
  61715. }
  61716. return 0;
  61717. }
  61718. bool ComponentPeer::isValidPeer (const ComponentPeer* const peer) throw()
  61719. {
  61720. return heavyweightPeers.contains (const_cast <ComponentPeer*> (peer));
  61721. }
  61722. void ComponentPeer::updateCurrentModifiers() throw()
  61723. {
  61724. ModifierKeys::updateCurrentModifiers();
  61725. }
  61726. void ComponentPeer::handleMouseEvent (const int touchIndex, const Point<int>& positionWithinPeer, const ModifierKeys& newMods, const int64 time)
  61727. {
  61728. MouseInputSource* const mouse = Desktop::getInstance().getMouseSource (touchIndex);
  61729. jassert (mouse != 0); // not enough sources!
  61730. mouse->handleEvent (this, positionWithinPeer, time, newMods);
  61731. }
  61732. void ComponentPeer::handleMouseWheel (const int touchIndex, const Point<int>& positionWithinPeer, const int64 time, const float x, const float y)
  61733. {
  61734. MouseInputSource* const mouse = Desktop::getInstance().getMouseSource (touchIndex);
  61735. jassert (mouse != 0); // not enough sources!
  61736. mouse->handleWheel (this, positionWithinPeer, time, x, y);
  61737. }
  61738. void ComponentPeer::handlePaint (LowLevelGraphicsContext& contextToPaintTo)
  61739. {
  61740. Graphics g (&contextToPaintTo);
  61741. #if JUCE_ENABLE_REPAINT_DEBUGGING
  61742. g.saveState();
  61743. #endif
  61744. JUCE_TRY
  61745. {
  61746. component->paintEntireComponent (g);
  61747. }
  61748. JUCE_CATCH_EXCEPTION
  61749. #if JUCE_ENABLE_REPAINT_DEBUGGING
  61750. // enabling this code will fill all areas that get repainted with a colour overlay, to show
  61751. // clearly when things are being repainted.
  61752. {
  61753. g.restoreState();
  61754. g.fillAll (Colour ((uint8) Random::getSystemRandom().nextInt (255),
  61755. (uint8) Random::getSystemRandom().nextInt (255),
  61756. (uint8) Random::getSystemRandom().nextInt (255),
  61757. (uint8) 0x50));
  61758. }
  61759. #endif
  61760. }
  61761. bool ComponentPeer::handleKeyPress (const int keyCode,
  61762. const juce_wchar textCharacter)
  61763. {
  61764. updateCurrentModifiers();
  61765. Component* target = Component::getCurrentlyFocusedComponent() != 0
  61766. ? Component::getCurrentlyFocusedComponent()
  61767. : component;
  61768. if (target->isCurrentlyBlockedByAnotherModalComponent())
  61769. {
  61770. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  61771. if (currentModalComp != 0)
  61772. target = currentModalComp;
  61773. }
  61774. const KeyPress keyInfo (keyCode,
  61775. ModifierKeys::getCurrentModifiers().getRawFlags()
  61776. & ModifierKeys::allKeyboardModifiers,
  61777. textCharacter);
  61778. bool keyWasUsed = false;
  61779. while (target != 0)
  61780. {
  61781. const Component::SafePointer<Component> deletionChecker (target);
  61782. if (target->keyListeners_ != 0)
  61783. {
  61784. for (int i = target->keyListeners_->size(); --i >= 0;)
  61785. {
  61786. keyWasUsed = target->keyListeners_->getUnchecked(i)->keyPressed (keyInfo, target);
  61787. if (keyWasUsed || deletionChecker == 0)
  61788. return keyWasUsed;
  61789. i = jmin (i, target->keyListeners_->size());
  61790. }
  61791. }
  61792. keyWasUsed = target->keyPressed (keyInfo);
  61793. if (keyWasUsed || deletionChecker == 0)
  61794. break;
  61795. if (keyInfo.isKeyCode (KeyPress::tabKey) && Component::getCurrentlyFocusedComponent() != 0)
  61796. {
  61797. Component* const currentlyFocused = Component::getCurrentlyFocusedComponent();
  61798. currentlyFocused->moveKeyboardFocusToSibling (! keyInfo.getModifiers().isShiftDown());
  61799. keyWasUsed = (currentlyFocused != Component::getCurrentlyFocusedComponent());
  61800. break;
  61801. }
  61802. target = target->parentComponent_;
  61803. }
  61804. return keyWasUsed;
  61805. }
  61806. bool ComponentPeer::handleKeyUpOrDown (const bool isKeyDown)
  61807. {
  61808. updateCurrentModifiers();
  61809. Component* target = Component::getCurrentlyFocusedComponent() != 0
  61810. ? Component::getCurrentlyFocusedComponent()
  61811. : component;
  61812. if (target->isCurrentlyBlockedByAnotherModalComponent())
  61813. {
  61814. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  61815. if (currentModalComp != 0)
  61816. target = currentModalComp;
  61817. }
  61818. bool keyWasUsed = false;
  61819. while (target != 0)
  61820. {
  61821. const Component::SafePointer<Component> deletionChecker (target);
  61822. keyWasUsed = target->keyStateChanged (isKeyDown);
  61823. if (keyWasUsed || deletionChecker == 0)
  61824. break;
  61825. if (target->keyListeners_ != 0)
  61826. {
  61827. for (int i = target->keyListeners_->size(); --i >= 0;)
  61828. {
  61829. keyWasUsed = target->keyListeners_->getUnchecked(i)->keyStateChanged (isKeyDown, target);
  61830. if (keyWasUsed || deletionChecker == 0)
  61831. return keyWasUsed;
  61832. i = jmin (i, target->keyListeners_->size());
  61833. }
  61834. }
  61835. target = target->parentComponent_;
  61836. }
  61837. return keyWasUsed;
  61838. }
  61839. void ComponentPeer::handleModifierKeysChange()
  61840. {
  61841. updateCurrentModifiers();
  61842. Component* target = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  61843. if (target == 0)
  61844. target = Component::getCurrentlyFocusedComponent();
  61845. if (target == 0)
  61846. target = component;
  61847. if (target != 0)
  61848. target->internalModifierKeysChanged();
  61849. }
  61850. TextInputTarget* ComponentPeer::findCurrentTextInputTarget()
  61851. {
  61852. Component* const c = Component::getCurrentlyFocusedComponent();
  61853. if (component->isParentOf (c))
  61854. {
  61855. TextInputTarget* const ti = dynamic_cast <TextInputTarget*> (c);
  61856. if (ti != 0 && ti->isTextInputActive())
  61857. return ti;
  61858. }
  61859. return 0;
  61860. }
  61861. void ComponentPeer::handleBroughtToFront()
  61862. {
  61863. updateCurrentModifiers();
  61864. if (component != 0)
  61865. component->internalBroughtToFront();
  61866. }
  61867. void ComponentPeer::setConstrainer (ComponentBoundsConstrainer* const newConstrainer) throw()
  61868. {
  61869. constrainer = newConstrainer;
  61870. }
  61871. void ComponentPeer::handleMovedOrResized()
  61872. {
  61873. jassert (component->isValidComponent());
  61874. updateCurrentModifiers();
  61875. const bool nowMinimised = isMinimised();
  61876. if (component->flags.hasHeavyweightPeerFlag && ! nowMinimised)
  61877. {
  61878. const Component::SafePointer<Component> deletionChecker (component);
  61879. const Rectangle<int> newBounds (getBounds());
  61880. const bool wasMoved = (component->getPosition() != newBounds.getPosition());
  61881. const bool wasResized = (component->getWidth() != newBounds.getWidth() || component->getHeight() != newBounds.getHeight());
  61882. if (wasMoved || wasResized)
  61883. {
  61884. component->bounds_ = newBounds;
  61885. if (wasResized)
  61886. component->repaint();
  61887. component->sendMovedResizedMessages (wasMoved, wasResized);
  61888. if (deletionChecker == 0)
  61889. return;
  61890. }
  61891. }
  61892. if (isWindowMinimised != nowMinimised)
  61893. {
  61894. isWindowMinimised = nowMinimised;
  61895. component->minimisationStateChanged (nowMinimised);
  61896. component->sendVisibilityChangeMessage();
  61897. }
  61898. if (! isFullScreen())
  61899. lastNonFullscreenBounds = component->getBounds();
  61900. }
  61901. void ComponentPeer::handleFocusGain()
  61902. {
  61903. updateCurrentModifiers();
  61904. if (component->isParentOf (lastFocusedComponent))
  61905. {
  61906. Component::currentlyFocusedComponent = lastFocusedComponent;
  61907. Desktop::getInstance().triggerFocusCallback();
  61908. lastFocusedComponent->internalFocusGain (Component::focusChangedDirectly);
  61909. }
  61910. else
  61911. {
  61912. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  61913. component->grabKeyboardFocus();
  61914. else
  61915. Component::bringModalComponentToFront();
  61916. }
  61917. }
  61918. void ComponentPeer::handleFocusLoss()
  61919. {
  61920. updateCurrentModifiers();
  61921. if (component->hasKeyboardFocus (true))
  61922. {
  61923. lastFocusedComponent = Component::currentlyFocusedComponent;
  61924. if (lastFocusedComponent != 0)
  61925. {
  61926. Component::currentlyFocusedComponent = 0;
  61927. Desktop::getInstance().triggerFocusCallback();
  61928. lastFocusedComponent->internalFocusLoss (Component::focusChangedByMouseClick);
  61929. }
  61930. }
  61931. }
  61932. Component* ComponentPeer::getLastFocusedSubcomponent() const throw()
  61933. {
  61934. return (component->isParentOf (lastFocusedComponent) && lastFocusedComponent->isShowing())
  61935. ? static_cast <Component*> (lastFocusedComponent)
  61936. : component;
  61937. }
  61938. void ComponentPeer::handleScreenSizeChange()
  61939. {
  61940. updateCurrentModifiers();
  61941. component->parentSizeChanged();
  61942. handleMovedOrResized();
  61943. }
  61944. void ComponentPeer::setNonFullScreenBounds (const Rectangle<int>& newBounds) throw()
  61945. {
  61946. lastNonFullscreenBounds = newBounds;
  61947. }
  61948. const Rectangle<int>& ComponentPeer::getNonFullScreenBounds() const throw()
  61949. {
  61950. return lastNonFullscreenBounds;
  61951. }
  61952. static FileDragAndDropTarget* findDragAndDropTarget (Component* c,
  61953. const StringArray& files,
  61954. FileDragAndDropTarget* const lastOne)
  61955. {
  61956. while (c != 0)
  61957. {
  61958. FileDragAndDropTarget* const t = dynamic_cast <FileDragAndDropTarget*> (c);
  61959. if (t != 0 && (t == lastOne || t->isInterestedInFileDrag (files)))
  61960. return t;
  61961. c = c->getParentComponent();
  61962. }
  61963. return 0;
  61964. }
  61965. void ComponentPeer::handleFileDragMove (const StringArray& files, const Point<int>& position)
  61966. {
  61967. updateCurrentModifiers();
  61968. FileDragAndDropTarget* lastTarget
  61969. = dynamic_cast<FileDragAndDropTarget*> (static_cast<Component*> (dragAndDropTargetComponent));
  61970. FileDragAndDropTarget* newTarget = 0;
  61971. Component* const compUnderMouse = component->getComponentAt (position);
  61972. if (compUnderMouse != lastDragAndDropCompUnderMouse)
  61973. {
  61974. lastDragAndDropCompUnderMouse = compUnderMouse;
  61975. newTarget = findDragAndDropTarget (compUnderMouse, files, lastTarget);
  61976. if (newTarget != lastTarget)
  61977. {
  61978. if (lastTarget != 0)
  61979. lastTarget->fileDragExit (files);
  61980. dragAndDropTargetComponent = 0;
  61981. if (newTarget != 0)
  61982. {
  61983. dragAndDropTargetComponent = dynamic_cast <Component*> (newTarget);
  61984. const Point<int> pos (component->relativePositionToOtherComponent (dragAndDropTargetComponent, position));
  61985. newTarget->fileDragEnter (files, pos.getX(), pos.getY());
  61986. }
  61987. }
  61988. }
  61989. else
  61990. {
  61991. newTarget = lastTarget;
  61992. }
  61993. if (newTarget != 0)
  61994. {
  61995. Component* const targetComp = dynamic_cast <Component*> (newTarget);
  61996. const Point<int> pos (component->relativePositionToOtherComponent (targetComp, position));
  61997. newTarget->fileDragMove (files, pos.getX(), pos.getY());
  61998. }
  61999. }
  62000. void ComponentPeer::handleFileDragExit (const StringArray& files)
  62001. {
  62002. handleFileDragMove (files, Point<int> (-1, -1));
  62003. jassert (dragAndDropTargetComponent == 0);
  62004. lastDragAndDropCompUnderMouse = 0;
  62005. }
  62006. void ComponentPeer::handleFileDragDrop (const StringArray& files, const Point<int>& position)
  62007. {
  62008. handleFileDragMove (files, position);
  62009. if (dragAndDropTargetComponent != 0)
  62010. {
  62011. FileDragAndDropTarget* const target
  62012. = dynamic_cast<FileDragAndDropTarget*> (static_cast<Component*> (dragAndDropTargetComponent));
  62013. dragAndDropTargetComponent = 0;
  62014. lastDragAndDropCompUnderMouse = 0;
  62015. if (target != 0)
  62016. {
  62017. Component* const targetComp = dynamic_cast <Component*> (target);
  62018. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  62019. {
  62020. targetComp->internalModalInputAttempt();
  62021. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  62022. return;
  62023. }
  62024. const Point<int> pos (component->relativePositionToOtherComponent (targetComp, position));
  62025. target->filesDropped (files, pos.getX(), pos.getY());
  62026. }
  62027. }
  62028. }
  62029. void ComponentPeer::handleUserClosingWindow()
  62030. {
  62031. updateCurrentModifiers();
  62032. component->userTriedToCloseWindow();
  62033. }
  62034. void ComponentPeer::bringModalComponentToFront()
  62035. {
  62036. Component::bringModalComponentToFront();
  62037. }
  62038. void ComponentPeer::clearMaskedRegion()
  62039. {
  62040. maskedRegion.clear();
  62041. }
  62042. void ComponentPeer::addMaskedRegion (int x, int y, int w, int h)
  62043. {
  62044. maskedRegion.add (x, y, w, h);
  62045. }
  62046. const StringArray ComponentPeer::getAvailableRenderingEngines() throw()
  62047. {
  62048. StringArray s;
  62049. s.add ("Software Renderer");
  62050. return s;
  62051. }
  62052. int ComponentPeer::getCurrentRenderingEngine() throw()
  62053. {
  62054. return 0;
  62055. }
  62056. void ComponentPeer::setCurrentRenderingEngine (int /*index*/) throw()
  62057. {
  62058. }
  62059. END_JUCE_NAMESPACE
  62060. /*** End of inlined file: juce_ComponentPeer.cpp ***/
  62061. /*** Start of inlined file: juce_DialogWindow.cpp ***/
  62062. BEGIN_JUCE_NAMESPACE
  62063. DialogWindow::DialogWindow (const String& name,
  62064. const Colour& backgroundColour_,
  62065. const bool escapeKeyTriggersCloseButton_,
  62066. const bool addToDesktop_)
  62067. : DocumentWindow (name, backgroundColour_, DocumentWindow::closeButton, addToDesktop_),
  62068. escapeKeyTriggersCloseButton (escapeKeyTriggersCloseButton_)
  62069. {
  62070. }
  62071. DialogWindow::~DialogWindow()
  62072. {
  62073. }
  62074. void DialogWindow::resized()
  62075. {
  62076. DocumentWindow::resized();
  62077. const KeyPress esc (KeyPress::escapeKey, 0, 0);
  62078. if (escapeKeyTriggersCloseButton
  62079. && getCloseButton() != 0
  62080. && ! getCloseButton()->isRegisteredForShortcut (esc))
  62081. {
  62082. getCloseButton()->addShortcut (esc);
  62083. }
  62084. }
  62085. class TempDialogWindow : public DialogWindow
  62086. {
  62087. public:
  62088. TempDialogWindow (const String& title, const Colour& colour, const bool escapeCloses)
  62089. : DialogWindow (title, colour, escapeCloses, true)
  62090. {
  62091. if (JUCEApplication::getInstance() == 0)
  62092. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  62093. }
  62094. ~TempDialogWindow()
  62095. {
  62096. }
  62097. void closeButtonPressed()
  62098. {
  62099. setVisible (false);
  62100. }
  62101. private:
  62102. TempDialogWindow (const TempDialogWindow&);
  62103. TempDialogWindow& operator= (const TempDialogWindow&);
  62104. };
  62105. int DialogWindow::showModalDialog (const String& dialogTitle,
  62106. Component* contentComponent,
  62107. Component* componentToCentreAround,
  62108. const Colour& colour,
  62109. const bool escapeKeyTriggersCloseButton,
  62110. const bool shouldBeResizable,
  62111. const bool useBottomRightCornerResizer)
  62112. {
  62113. TempDialogWindow dw (dialogTitle, colour, escapeKeyTriggersCloseButton);
  62114. dw.setContentComponent (contentComponent, true, true);
  62115. dw.centreAroundComponent (componentToCentreAround, dw.getWidth(), dw.getHeight());
  62116. dw.setResizable (shouldBeResizable, useBottomRightCornerResizer);
  62117. const int result = dw.runModalLoop();
  62118. dw.setContentComponent (0, false);
  62119. return result;
  62120. }
  62121. END_JUCE_NAMESPACE
  62122. /*** End of inlined file: juce_DialogWindow.cpp ***/
  62123. /*** Start of inlined file: juce_DocumentWindow.cpp ***/
  62124. BEGIN_JUCE_NAMESPACE
  62125. class DocumentWindow::ButtonListenerProxy : public ButtonListener
  62126. {
  62127. public:
  62128. ButtonListenerProxy (DocumentWindow& owner_)
  62129. : owner (owner_)
  62130. {
  62131. }
  62132. void buttonClicked (Button* button)
  62133. {
  62134. if (button == owner.getMinimiseButton())
  62135. owner.minimiseButtonPressed();
  62136. else if (button == owner.getMaximiseButton())
  62137. owner.maximiseButtonPressed();
  62138. else if (button == owner.getCloseButton())
  62139. owner.closeButtonPressed();
  62140. }
  62141. juce_UseDebuggingNewOperator
  62142. private:
  62143. DocumentWindow& owner;
  62144. ButtonListenerProxy (const ButtonListenerProxy&);
  62145. ButtonListenerProxy& operator= (const ButtonListenerProxy&);
  62146. };
  62147. DocumentWindow::DocumentWindow (const String& title,
  62148. const Colour& backgroundColour,
  62149. const int requiredButtons_,
  62150. const bool addToDesktop_)
  62151. : ResizableWindow (title, backgroundColour, addToDesktop_),
  62152. titleBarHeight (26),
  62153. menuBarHeight (24),
  62154. requiredButtons (requiredButtons_),
  62155. #if JUCE_MAC
  62156. positionTitleBarButtonsOnLeft (true),
  62157. #else
  62158. positionTitleBarButtonsOnLeft (false),
  62159. #endif
  62160. drawTitleTextCentred (true),
  62161. menuBarModel (0)
  62162. {
  62163. setResizeLimits (128, 128, 32768, 32768);
  62164. lookAndFeelChanged();
  62165. }
  62166. DocumentWindow::~DocumentWindow()
  62167. {
  62168. for (int i = numElementsInArray (titleBarButtons); --i >= 0;)
  62169. titleBarButtons[i] = 0;
  62170. menuBar = 0;
  62171. }
  62172. void DocumentWindow::repaintTitleBar()
  62173. {
  62174. repaint (getTitleBarArea());
  62175. }
  62176. void DocumentWindow::setName (const String& newName)
  62177. {
  62178. if (newName != getName())
  62179. {
  62180. Component::setName (newName);
  62181. repaintTitleBar();
  62182. }
  62183. }
  62184. void DocumentWindow::setIcon (const Image& imageToUse)
  62185. {
  62186. titleBarIcon = imageToUse;
  62187. repaintTitleBar();
  62188. }
  62189. void DocumentWindow::setTitleBarHeight (const int newHeight)
  62190. {
  62191. titleBarHeight = newHeight;
  62192. resized();
  62193. repaintTitleBar();
  62194. }
  62195. void DocumentWindow::setTitleBarButtonsRequired (const int requiredButtons_,
  62196. const bool positionTitleBarButtonsOnLeft_)
  62197. {
  62198. requiredButtons = requiredButtons_;
  62199. positionTitleBarButtonsOnLeft = positionTitleBarButtonsOnLeft_;
  62200. lookAndFeelChanged();
  62201. }
  62202. void DocumentWindow::setTitleBarTextCentred (const bool textShouldBeCentred)
  62203. {
  62204. drawTitleTextCentred = textShouldBeCentred;
  62205. repaintTitleBar();
  62206. }
  62207. void DocumentWindow::setMenuBar (MenuBarModel* menuBarModel_,
  62208. const int menuBarHeight_)
  62209. {
  62210. if (menuBarModel != menuBarModel_)
  62211. {
  62212. menuBar = 0;
  62213. menuBarModel = menuBarModel_;
  62214. menuBarHeight = (menuBarHeight_ > 0) ? menuBarHeight_
  62215. : getLookAndFeel().getDefaultMenuBarHeight();
  62216. if (menuBarModel != 0)
  62217. {
  62218. // (call the Component method directly to avoid the assertion in ResizableWindow)
  62219. Component::addAndMakeVisible (menuBar = new MenuBarComponent (menuBarModel));
  62220. menuBar->setEnabled (isActiveWindow());
  62221. }
  62222. resized();
  62223. }
  62224. }
  62225. void DocumentWindow::closeButtonPressed()
  62226. {
  62227. /* If you've got a close button, you have to override this method to get
  62228. rid of your window!
  62229. If the window is just a pop-up, you should override this method and make
  62230. it delete the window in whatever way is appropriate for your app. E.g. you
  62231. might just want to call "delete this".
  62232. If your app is centred around this window such that the whole app should quit when
  62233. the window is closed, then you will probably want to use this method as an opportunity
  62234. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  62235. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  62236. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  62237. or closing it via the taskbar icon on Windows).
  62238. */
  62239. jassertfalse;
  62240. }
  62241. void DocumentWindow::minimiseButtonPressed()
  62242. {
  62243. setMinimised (true);
  62244. }
  62245. void DocumentWindow::maximiseButtonPressed()
  62246. {
  62247. setFullScreen (! isFullScreen());
  62248. }
  62249. void DocumentWindow::paint (Graphics& g)
  62250. {
  62251. ResizableWindow::paint (g);
  62252. if (resizableBorder == 0)
  62253. {
  62254. g.setColour (getBackgroundColour().overlaidWith (Colour (0x80000000)));
  62255. const BorderSize border (getBorderThickness());
  62256. g.fillRect (0, 0, getWidth(), border.getTop());
  62257. g.fillRect (0, border.getTop(), border.getLeft(), getHeight() - border.getTopAndBottom());
  62258. g.fillRect (getWidth() - border.getRight(), border.getTop(), border.getRight(), getHeight() - border.getTopAndBottom());
  62259. g.fillRect (0, getHeight() - border.getBottom(), getWidth(), border.getBottom());
  62260. }
  62261. const Rectangle<int> titleBarArea (getTitleBarArea());
  62262. g.setOrigin (titleBarArea.getX(), titleBarArea.getY());
  62263. g.reduceClipRegion (0, 0, titleBarArea.getWidth(), titleBarArea.getHeight());
  62264. int titleSpaceX1 = 6;
  62265. int titleSpaceX2 = titleBarArea.getWidth() - 6;
  62266. for (int i = 0; i < 3; ++i)
  62267. {
  62268. if (titleBarButtons[i] != 0)
  62269. {
  62270. if (positionTitleBarButtonsOnLeft)
  62271. titleSpaceX1 = jmax (titleSpaceX1, titleBarButtons[i]->getRight() + (getWidth() - titleBarButtons[i]->getRight()) / 8);
  62272. else
  62273. titleSpaceX2 = jmin (titleSpaceX2, titleBarButtons[i]->getX() - (titleBarButtons[i]->getX() / 8));
  62274. }
  62275. }
  62276. getLookAndFeel().drawDocumentWindowTitleBar (*this, g,
  62277. titleBarArea.getWidth(),
  62278. titleBarArea.getHeight(),
  62279. titleSpaceX1,
  62280. jmax (1, titleSpaceX2 - titleSpaceX1),
  62281. titleBarIcon.isValid() ? &titleBarIcon : 0,
  62282. ! drawTitleTextCentred);
  62283. }
  62284. void DocumentWindow::resized()
  62285. {
  62286. ResizableWindow::resized();
  62287. if (titleBarButtons[1] != 0)
  62288. titleBarButtons[1]->setToggleState (isFullScreen(), false);
  62289. const Rectangle<int> titleBarArea (getTitleBarArea());
  62290. getLookAndFeel()
  62291. .positionDocumentWindowButtons (*this,
  62292. titleBarArea.getX(), titleBarArea.getY(),
  62293. titleBarArea.getWidth(), titleBarArea.getHeight(),
  62294. titleBarButtons[0],
  62295. titleBarButtons[1],
  62296. titleBarButtons[2],
  62297. positionTitleBarButtonsOnLeft);
  62298. if (menuBar != 0)
  62299. menuBar->setBounds (titleBarArea.getX(), titleBarArea.getBottom(),
  62300. titleBarArea.getWidth(), menuBarHeight);
  62301. }
  62302. const BorderSize DocumentWindow::getBorderThickness()
  62303. {
  62304. return BorderSize ((isFullScreen() || isUsingNativeTitleBar())
  62305. ? 0 : (resizableBorder != 0 ? 4 : 1));
  62306. }
  62307. const BorderSize DocumentWindow::getContentComponentBorder()
  62308. {
  62309. BorderSize border (getBorderThickness());
  62310. border.setTop (border.getTop()
  62311. + (isUsingNativeTitleBar() ? 0 : titleBarHeight)
  62312. + (menuBar != 0 ? menuBarHeight : 0));
  62313. return border;
  62314. }
  62315. int DocumentWindow::getTitleBarHeight() const
  62316. {
  62317. return isUsingNativeTitleBar() ? 0 : jmin (titleBarHeight, getHeight() - 4);
  62318. }
  62319. const Rectangle<int> DocumentWindow::getTitleBarArea()
  62320. {
  62321. const BorderSize border (getBorderThickness());
  62322. return Rectangle<int> (border.getLeft(), border.getTop(),
  62323. getWidth() - border.getLeftAndRight(),
  62324. getTitleBarHeight());
  62325. }
  62326. Button* DocumentWindow::getCloseButton() const throw()
  62327. {
  62328. return titleBarButtons[2];
  62329. }
  62330. Button* DocumentWindow::getMinimiseButton() const throw()
  62331. {
  62332. return titleBarButtons[0];
  62333. }
  62334. Button* DocumentWindow::getMaximiseButton() const throw()
  62335. {
  62336. return titleBarButtons[1];
  62337. }
  62338. int DocumentWindow::getDesktopWindowStyleFlags() const
  62339. {
  62340. int styleFlags = ResizableWindow::getDesktopWindowStyleFlags();
  62341. if ((requiredButtons & minimiseButton) != 0)
  62342. styleFlags |= ComponentPeer::windowHasMinimiseButton;
  62343. if ((requiredButtons & maximiseButton) != 0)
  62344. styleFlags |= ComponentPeer::windowHasMaximiseButton;
  62345. if ((requiredButtons & closeButton) != 0)
  62346. styleFlags |= ComponentPeer::windowHasCloseButton;
  62347. return styleFlags;
  62348. }
  62349. void DocumentWindow::lookAndFeelChanged()
  62350. {
  62351. int i;
  62352. for (i = numElementsInArray (titleBarButtons); --i >= 0;)
  62353. titleBarButtons[i] = 0;
  62354. if (! isUsingNativeTitleBar())
  62355. {
  62356. titleBarButtons[0] = ((requiredButtons & minimiseButton) != 0)
  62357. ? getLookAndFeel().createDocumentWindowButton (minimiseButton) : 0;
  62358. titleBarButtons[1] = ((requiredButtons & maximiseButton) != 0)
  62359. ? getLookAndFeel().createDocumentWindowButton (maximiseButton) : 0;
  62360. titleBarButtons[2] = ((requiredButtons & closeButton) != 0)
  62361. ? getLookAndFeel().createDocumentWindowButton (closeButton) : 0;
  62362. for (i = 0; i < 3; ++i)
  62363. {
  62364. if (titleBarButtons[i] != 0)
  62365. {
  62366. if (buttonListener == 0)
  62367. buttonListener = new ButtonListenerProxy (*this);
  62368. titleBarButtons[i]->addButtonListener (buttonListener);
  62369. titleBarButtons[i]->setWantsKeyboardFocus (false);
  62370. // (call the Component method directly to avoid the assertion in ResizableWindow)
  62371. Component::addAndMakeVisible (titleBarButtons[i]);
  62372. }
  62373. }
  62374. if (getCloseButton() != 0)
  62375. {
  62376. #if JUCE_MAC
  62377. getCloseButton()->addShortcut (KeyPress ('w', ModifierKeys::commandModifier, 0));
  62378. #else
  62379. getCloseButton()->addShortcut (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0));
  62380. #endif
  62381. }
  62382. }
  62383. activeWindowStatusChanged();
  62384. ResizableWindow::lookAndFeelChanged();
  62385. }
  62386. void DocumentWindow::parentHierarchyChanged()
  62387. {
  62388. lookAndFeelChanged();
  62389. }
  62390. void DocumentWindow::activeWindowStatusChanged()
  62391. {
  62392. ResizableWindow::activeWindowStatusChanged();
  62393. for (int i = numElementsInArray (titleBarButtons); --i >= 0;)
  62394. if (titleBarButtons[i] != 0)
  62395. titleBarButtons[i]->setEnabled (isActiveWindow());
  62396. if (menuBar != 0)
  62397. menuBar->setEnabled (isActiveWindow());
  62398. }
  62399. void DocumentWindow::mouseDoubleClick (const MouseEvent& e)
  62400. {
  62401. if (getTitleBarArea().contains (e.x, e.y)
  62402. && getMaximiseButton() != 0)
  62403. {
  62404. getMaximiseButton()->triggerClick();
  62405. }
  62406. }
  62407. void DocumentWindow::userTriedToCloseWindow()
  62408. {
  62409. closeButtonPressed();
  62410. }
  62411. END_JUCE_NAMESPACE
  62412. /*** End of inlined file: juce_DocumentWindow.cpp ***/
  62413. /*** Start of inlined file: juce_ResizableWindow.cpp ***/
  62414. BEGIN_JUCE_NAMESPACE
  62415. ResizableWindow::ResizableWindow (const String& name,
  62416. const bool addToDesktop_)
  62417. : TopLevelWindow (name, addToDesktop_),
  62418. resizeToFitContent (false),
  62419. fullscreen (false),
  62420. lastNonFullScreenPos (50, 50, 256, 256),
  62421. constrainer (0)
  62422. #if JUCE_DEBUG
  62423. , hasBeenResized (false)
  62424. #endif
  62425. {
  62426. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  62427. lastNonFullScreenPos.setBounds (50, 50, 256, 256);
  62428. if (addToDesktop_)
  62429. Component::addToDesktop (getDesktopWindowStyleFlags());
  62430. }
  62431. ResizableWindow::ResizableWindow (const String& name,
  62432. const Colour& backgroundColour_,
  62433. const bool addToDesktop_)
  62434. : TopLevelWindow (name, addToDesktop_),
  62435. resizeToFitContent (false),
  62436. fullscreen (false),
  62437. lastNonFullScreenPos (50, 50, 256, 256),
  62438. constrainer (0)
  62439. #if JUCE_DEBUG
  62440. , hasBeenResized (false)
  62441. #endif
  62442. {
  62443. setBackgroundColour (backgroundColour_);
  62444. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  62445. if (addToDesktop_)
  62446. Component::addToDesktop (getDesktopWindowStyleFlags());
  62447. }
  62448. ResizableWindow::~ResizableWindow()
  62449. {
  62450. resizableCorner = 0;
  62451. resizableBorder = 0;
  62452. contentComponent = 0;
  62453. // have you been adding your own components directly to this window..? tut tut tut.
  62454. // Read the instructions for using a ResizableWindow!
  62455. jassert (getNumChildComponents() == 0);
  62456. }
  62457. int ResizableWindow::getDesktopWindowStyleFlags() const
  62458. {
  62459. int styleFlags = TopLevelWindow::getDesktopWindowStyleFlags();
  62460. if (isResizable() && (styleFlags & ComponentPeer::windowHasTitleBar) != 0)
  62461. styleFlags |= ComponentPeer::windowIsResizable;
  62462. return styleFlags;
  62463. }
  62464. void ResizableWindow::setContentComponent (Component* const newContentComponent,
  62465. const bool deleteOldOne,
  62466. const bool resizeToFit)
  62467. {
  62468. resizeToFitContent = resizeToFit;
  62469. if (newContentComponent != static_cast <Component*> (contentComponent))
  62470. {
  62471. if (! deleteOldOne)
  62472. removeChildComponent (contentComponent.release());
  62473. contentComponent = newContentComponent;
  62474. Component::addAndMakeVisible (contentComponent);
  62475. }
  62476. if (resizeToFit)
  62477. childBoundsChanged (contentComponent);
  62478. resized(); // must always be called to position the new content comp
  62479. }
  62480. void ResizableWindow::setContentComponentSize (int width, int height)
  62481. {
  62482. jassert (width > 0 && height > 0); // not a great idea to give it a zero size..
  62483. const BorderSize border (getContentComponentBorder());
  62484. setSize (width + border.getLeftAndRight(),
  62485. height + border.getTopAndBottom());
  62486. }
  62487. const BorderSize ResizableWindow::getBorderThickness()
  62488. {
  62489. return BorderSize (isUsingNativeTitleBar() ? 0 : ((resizableBorder != 0 && ! isFullScreen()) ? 5 : 3));
  62490. }
  62491. const BorderSize ResizableWindow::getContentComponentBorder()
  62492. {
  62493. return getBorderThickness();
  62494. }
  62495. void ResizableWindow::moved()
  62496. {
  62497. updateLastPos();
  62498. }
  62499. void ResizableWindow::visibilityChanged()
  62500. {
  62501. TopLevelWindow::visibilityChanged();
  62502. updateLastPos();
  62503. }
  62504. void ResizableWindow::resized()
  62505. {
  62506. if (resizableBorder != 0)
  62507. {
  62508. resizableBorder->setVisible (! isFullScreen());
  62509. resizableBorder->setBorderThickness (getBorderThickness());
  62510. resizableBorder->setSize (getWidth(), getHeight());
  62511. resizableBorder->toBack();
  62512. }
  62513. if (resizableCorner != 0)
  62514. {
  62515. resizableCorner->setVisible (! isFullScreen());
  62516. const int resizerSize = 18;
  62517. resizableCorner->setBounds (getWidth() - resizerSize,
  62518. getHeight() - resizerSize,
  62519. resizerSize, resizerSize);
  62520. }
  62521. if (contentComponent != 0)
  62522. contentComponent->setBoundsInset (getContentComponentBorder());
  62523. updateLastPos();
  62524. #if JUCE_DEBUG
  62525. hasBeenResized = true;
  62526. #endif
  62527. }
  62528. void ResizableWindow::childBoundsChanged (Component* child)
  62529. {
  62530. if ((child == contentComponent) && (child != 0) && resizeToFitContent)
  62531. {
  62532. // not going to look very good if this component has a zero size..
  62533. jassert (child->getWidth() > 0);
  62534. jassert (child->getHeight() > 0);
  62535. const BorderSize borders (getContentComponentBorder());
  62536. setSize (child->getWidth() + borders.getLeftAndRight(),
  62537. child->getHeight() + borders.getTopAndBottom());
  62538. }
  62539. }
  62540. void ResizableWindow::activeWindowStatusChanged()
  62541. {
  62542. const BorderSize borders (getContentComponentBorder());
  62543. repaint (0, 0, getWidth(), borders.getTop());
  62544. repaint (0, borders.getTop(), borders.getLeft(), getHeight() - borders.getBottom() - borders.getTop());
  62545. repaint (0, getHeight() - borders.getBottom(), getWidth(), borders.getBottom());
  62546. repaint (getWidth() - borders.getRight(), borders.getTop(), borders.getRight(), getHeight() - borders.getBottom() - borders.getTop());
  62547. }
  62548. void ResizableWindow::setResizable (const bool shouldBeResizable,
  62549. const bool useBottomRightCornerResizer)
  62550. {
  62551. if (shouldBeResizable)
  62552. {
  62553. if (useBottomRightCornerResizer)
  62554. {
  62555. resizableBorder = 0;
  62556. if (resizableCorner == 0)
  62557. {
  62558. Component::addChildComponent (resizableCorner = new ResizableCornerComponent (this, constrainer));
  62559. resizableCorner->setAlwaysOnTop (true);
  62560. }
  62561. }
  62562. else
  62563. {
  62564. resizableCorner = 0;
  62565. if (resizableBorder == 0)
  62566. Component::addChildComponent (resizableBorder = new ResizableBorderComponent (this, constrainer));
  62567. }
  62568. }
  62569. else
  62570. {
  62571. resizableCorner = 0;
  62572. resizableBorder = 0;
  62573. }
  62574. if (isUsingNativeTitleBar())
  62575. recreateDesktopWindow();
  62576. childBoundsChanged (contentComponent);
  62577. resized();
  62578. }
  62579. bool ResizableWindow::isResizable() const throw()
  62580. {
  62581. return resizableCorner != 0
  62582. || resizableBorder != 0;
  62583. }
  62584. void ResizableWindow::setResizeLimits (const int newMinimumWidth,
  62585. const int newMinimumHeight,
  62586. const int newMaximumWidth,
  62587. const int newMaximumHeight) throw()
  62588. {
  62589. // if you've set up a custom constrainer then these settings won't have any effect..
  62590. jassert (constrainer == &defaultConstrainer || constrainer == 0);
  62591. if (constrainer == 0)
  62592. setConstrainer (&defaultConstrainer);
  62593. defaultConstrainer.setSizeLimits (newMinimumWidth, newMinimumHeight,
  62594. newMaximumWidth, newMaximumHeight);
  62595. setBoundsConstrained (getBounds());
  62596. }
  62597. void ResizableWindow::setConstrainer (ComponentBoundsConstrainer* newConstrainer)
  62598. {
  62599. if (constrainer != newConstrainer)
  62600. {
  62601. constrainer = newConstrainer;
  62602. const bool useBottomRightCornerResizer = resizableCorner != 0;
  62603. const bool shouldBeResizable = useBottomRightCornerResizer || resizableBorder != 0;
  62604. resizableCorner = 0;
  62605. resizableBorder = 0;
  62606. setResizable (shouldBeResizable, useBottomRightCornerResizer);
  62607. ComponentPeer* const peer = getPeer();
  62608. if (peer != 0)
  62609. peer->setConstrainer (newConstrainer);
  62610. }
  62611. }
  62612. void ResizableWindow::setBoundsConstrained (const Rectangle<int>& bounds)
  62613. {
  62614. if (constrainer != 0)
  62615. constrainer->setBoundsForComponent (this, bounds, false, false, false, false);
  62616. else
  62617. setBounds (bounds);
  62618. }
  62619. void ResizableWindow::paint (Graphics& g)
  62620. {
  62621. getLookAndFeel().fillResizableWindowBackground (g, getWidth(), getHeight(),
  62622. getBorderThickness(), *this);
  62623. if (! isFullScreen())
  62624. {
  62625. getLookAndFeel().drawResizableWindowBorder (g, getWidth(), getHeight(),
  62626. getBorderThickness(), *this);
  62627. }
  62628. #if JUCE_DEBUG
  62629. /* If this fails, then you've probably written a subclass with a resized()
  62630. callback but forgotten to make it call its parent class's resized() method.
  62631. It's important when you override methods like resized(), moved(),
  62632. etc., that you make sure the base class methods also get called.
  62633. Of course you shouldn't really be overriding ResizableWindow::resized() anyway,
  62634. because your content should all be inside the content component - and it's the
  62635. content component's resized() method that you should be using to do your
  62636. layout.
  62637. */
  62638. jassert (hasBeenResized || (getWidth() == 0 && getHeight() == 0));
  62639. #endif
  62640. }
  62641. void ResizableWindow::lookAndFeelChanged()
  62642. {
  62643. resized();
  62644. if (isOnDesktop())
  62645. {
  62646. Component::addToDesktop (getDesktopWindowStyleFlags());
  62647. ComponentPeer* const peer = getPeer();
  62648. if (peer != 0)
  62649. peer->setConstrainer (constrainer);
  62650. }
  62651. }
  62652. const Colour ResizableWindow::getBackgroundColour() const throw()
  62653. {
  62654. return findColour (backgroundColourId, false);
  62655. }
  62656. void ResizableWindow::setBackgroundColour (const Colour& newColour)
  62657. {
  62658. Colour backgroundColour (newColour);
  62659. if (! Desktop::canUseSemiTransparentWindows())
  62660. backgroundColour = newColour.withAlpha (1.0f);
  62661. setColour (backgroundColourId, backgroundColour);
  62662. setOpaque (backgroundColour.isOpaque());
  62663. repaint();
  62664. }
  62665. bool ResizableWindow::isFullScreen() const
  62666. {
  62667. if (isOnDesktop())
  62668. {
  62669. ComponentPeer* const peer = getPeer();
  62670. return peer != 0 && peer->isFullScreen();
  62671. }
  62672. return fullscreen;
  62673. }
  62674. void ResizableWindow::setFullScreen (const bool shouldBeFullScreen)
  62675. {
  62676. if (shouldBeFullScreen != isFullScreen())
  62677. {
  62678. updateLastPos();
  62679. fullscreen = shouldBeFullScreen;
  62680. if (isOnDesktop())
  62681. {
  62682. ComponentPeer* const peer = getPeer();
  62683. if (peer != 0)
  62684. {
  62685. // keep a copy of this intact in case the real one gets messed-up while we're un-maximising
  62686. const Rectangle<int> lastPos (lastNonFullScreenPos);
  62687. peer->setFullScreen (shouldBeFullScreen);
  62688. if (! shouldBeFullScreen)
  62689. setBounds (lastPos);
  62690. }
  62691. else
  62692. {
  62693. jassertfalse;
  62694. }
  62695. }
  62696. else
  62697. {
  62698. if (shouldBeFullScreen)
  62699. setBounds (0, 0, getParentWidth(), getParentHeight());
  62700. else
  62701. setBounds (lastNonFullScreenPos);
  62702. }
  62703. resized();
  62704. }
  62705. }
  62706. bool ResizableWindow::isMinimised() const
  62707. {
  62708. ComponentPeer* const peer = getPeer();
  62709. return (peer != 0) && peer->isMinimised();
  62710. }
  62711. void ResizableWindow::setMinimised (const bool shouldMinimise)
  62712. {
  62713. if (shouldMinimise != isMinimised())
  62714. {
  62715. ComponentPeer* const peer = getPeer();
  62716. if (peer != 0)
  62717. {
  62718. updateLastPos();
  62719. peer->setMinimised (shouldMinimise);
  62720. }
  62721. else
  62722. {
  62723. jassertfalse;
  62724. }
  62725. }
  62726. }
  62727. void ResizableWindow::updateLastPos()
  62728. {
  62729. if (isShowing() && ! (isFullScreen() || isMinimised()))
  62730. {
  62731. lastNonFullScreenPos = getBounds();
  62732. }
  62733. }
  62734. void ResizableWindow::parentSizeChanged()
  62735. {
  62736. if (isFullScreen() && getParentComponent() != 0)
  62737. {
  62738. setBounds (0, 0, getParentWidth(), getParentHeight());
  62739. }
  62740. }
  62741. const String ResizableWindow::getWindowStateAsString()
  62742. {
  62743. updateLastPos();
  62744. return (isFullScreen() ? "fs " : "") + lastNonFullScreenPos.toString();
  62745. }
  62746. bool ResizableWindow::restoreWindowStateFromString (const String& s)
  62747. {
  62748. StringArray tokens;
  62749. tokens.addTokens (s, false);
  62750. tokens.removeEmptyStrings();
  62751. tokens.trim();
  62752. const bool fs = tokens[0].startsWithIgnoreCase ("fs");
  62753. const int firstCoord = fs ? 1 : 0;
  62754. if (tokens.size() != firstCoord + 4)
  62755. return false;
  62756. Rectangle<int> newPos (tokens[firstCoord].getIntValue(),
  62757. tokens[firstCoord + 1].getIntValue(),
  62758. tokens[firstCoord + 2].getIntValue(),
  62759. tokens[firstCoord + 3].getIntValue());
  62760. if (newPos.isEmpty())
  62761. return false;
  62762. const Rectangle<int> screen (Desktop::getInstance().getMonitorAreaContaining (newPos.getCentre()));
  62763. ComponentPeer* const peer = isOnDesktop() ? getPeer() : 0;
  62764. if (peer != 0)
  62765. peer->getFrameSize().addTo (newPos);
  62766. if (! screen.contains (newPos))
  62767. {
  62768. newPos.setSize (jmin (newPos.getWidth(), screen.getWidth()),
  62769. jmin (newPos.getHeight(), screen.getHeight()));
  62770. newPos.setPosition (jlimit (screen.getX(), screen.getRight() - newPos.getWidth(), newPos.getX()),
  62771. jlimit (screen.getY(), screen.getBottom() - newPos.getHeight(), newPos.getY()));
  62772. }
  62773. if (peer != 0)
  62774. {
  62775. peer->getFrameSize().subtractFrom (newPos);
  62776. peer->setNonFullScreenBounds (newPos);
  62777. }
  62778. lastNonFullScreenPos = newPos;
  62779. setFullScreen (fs);
  62780. if (! fs)
  62781. setBoundsConstrained (newPos);
  62782. return true;
  62783. }
  62784. void ResizableWindow::mouseDown (const MouseEvent&)
  62785. {
  62786. if (! isFullScreen())
  62787. dragger.startDraggingComponent (this, constrainer);
  62788. }
  62789. void ResizableWindow::mouseDrag (const MouseEvent& e)
  62790. {
  62791. if (! isFullScreen())
  62792. dragger.dragComponent (this, e);
  62793. }
  62794. #if JUCE_DEBUG
  62795. void ResizableWindow::addChildComponent (Component* const child, int zOrder)
  62796. {
  62797. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  62798. manages its child components automatically, and if you add your own it'll cause
  62799. trouble. Instead, use setContentComponent() to give it a component which
  62800. will be automatically resized and kept in the right place - then you can add
  62801. subcomponents to the content comp. See the notes for the ResizableWindow class
  62802. for more info.
  62803. If you really know what you're doing and want to avoid this assertion, just call
  62804. Component::addChildComponent directly.
  62805. */
  62806. jassertfalse;
  62807. Component::addChildComponent (child, zOrder);
  62808. }
  62809. void ResizableWindow::addAndMakeVisible (Component* const child, int zOrder)
  62810. {
  62811. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  62812. manages its child components automatically, and if you add your own it'll cause
  62813. trouble. Instead, use setContentComponent() to give it a component which
  62814. will be automatically resized and kept in the right place - then you can add
  62815. subcomponents to the content comp. See the notes for the ResizableWindow class
  62816. for more info.
  62817. If you really know what you're doing and want to avoid this assertion, just call
  62818. Component::addAndMakeVisible directly.
  62819. */
  62820. jassertfalse;
  62821. Component::addAndMakeVisible (child, zOrder);
  62822. }
  62823. #endif
  62824. END_JUCE_NAMESPACE
  62825. /*** End of inlined file: juce_ResizableWindow.cpp ***/
  62826. /*** Start of inlined file: juce_SplashScreen.cpp ***/
  62827. BEGIN_JUCE_NAMESPACE
  62828. SplashScreen::SplashScreen()
  62829. {
  62830. setOpaque (true);
  62831. }
  62832. SplashScreen::~SplashScreen()
  62833. {
  62834. }
  62835. void SplashScreen::show (const String& title,
  62836. const Image& backgroundImage_,
  62837. const int minimumTimeToDisplayFor,
  62838. const bool useDropShadow,
  62839. const bool removeOnMouseClick)
  62840. {
  62841. backgroundImage = backgroundImage_;
  62842. jassert (backgroundImage_.isValid());
  62843. if (backgroundImage_.isValid())
  62844. {
  62845. setOpaque (! backgroundImage_.hasAlphaChannel());
  62846. show (title,
  62847. backgroundImage_.getWidth(),
  62848. backgroundImage_.getHeight(),
  62849. minimumTimeToDisplayFor,
  62850. useDropShadow,
  62851. removeOnMouseClick);
  62852. }
  62853. }
  62854. void SplashScreen::show (const String& title,
  62855. const int width,
  62856. const int height,
  62857. const int minimumTimeToDisplayFor,
  62858. const bool useDropShadow,
  62859. const bool removeOnMouseClick)
  62860. {
  62861. setName (title);
  62862. setAlwaysOnTop (true);
  62863. setVisible (true);
  62864. centreWithSize (width, height);
  62865. addToDesktop (useDropShadow ? ComponentPeer::windowHasDropShadow : 0);
  62866. toFront (false);
  62867. MessageManager::getInstance()->runDispatchLoopUntil (300);
  62868. repaint();
  62869. originalClickCounter = removeOnMouseClick
  62870. ? Desktop::getMouseButtonClickCounter()
  62871. : std::numeric_limits<int>::max();
  62872. earliestTimeToDelete = Time::getCurrentTime() + RelativeTime::milliseconds (minimumTimeToDisplayFor);
  62873. startTimer (50);
  62874. }
  62875. void SplashScreen::paint (Graphics& g)
  62876. {
  62877. g.setOpacity (1.0f);
  62878. g.drawImage (backgroundImage,
  62879. 0, 0, getWidth(), getHeight(),
  62880. 0, 0, backgroundImage.getWidth(), backgroundImage.getHeight());
  62881. }
  62882. void SplashScreen::timerCallback()
  62883. {
  62884. if (Time::getCurrentTime() > earliestTimeToDelete
  62885. || Desktop::getMouseButtonClickCounter() > originalClickCounter)
  62886. {
  62887. delete this;
  62888. }
  62889. }
  62890. END_JUCE_NAMESPACE
  62891. /*** End of inlined file: juce_SplashScreen.cpp ***/
  62892. /*** Start of inlined file: juce_ThreadWithProgressWindow.cpp ***/
  62893. BEGIN_JUCE_NAMESPACE
  62894. ThreadWithProgressWindow::ThreadWithProgressWindow (const String& title,
  62895. const bool hasProgressBar,
  62896. const bool hasCancelButton,
  62897. const int timeOutMsWhenCancelling_,
  62898. const String& cancelButtonText)
  62899. : Thread ("Juce Progress Window"),
  62900. progress (0.0),
  62901. timeOutMsWhenCancelling (timeOutMsWhenCancelling_)
  62902. {
  62903. alertWindow = LookAndFeel::getDefaultLookAndFeel()
  62904. .createAlertWindow (title, String::empty, cancelButtonText,
  62905. String::empty, String::empty,
  62906. AlertWindow::NoIcon, hasCancelButton ? 1 : 0, 0);
  62907. if (hasProgressBar)
  62908. alertWindow->addProgressBarComponent (progress);
  62909. }
  62910. ThreadWithProgressWindow::~ThreadWithProgressWindow()
  62911. {
  62912. stopThread (timeOutMsWhenCancelling);
  62913. }
  62914. bool ThreadWithProgressWindow::runThread (const int priority)
  62915. {
  62916. startThread (priority);
  62917. startTimer (100);
  62918. {
  62919. const ScopedLock sl (messageLock);
  62920. alertWindow->setMessage (message);
  62921. }
  62922. const bool finishedNaturally = alertWindow->runModalLoop() != 0;
  62923. stopThread (timeOutMsWhenCancelling);
  62924. alertWindow->setVisible (false);
  62925. return finishedNaturally;
  62926. }
  62927. void ThreadWithProgressWindow::setProgress (const double newProgress)
  62928. {
  62929. progress = newProgress;
  62930. }
  62931. void ThreadWithProgressWindow::setStatusMessage (const String& newStatusMessage)
  62932. {
  62933. const ScopedLock sl (messageLock);
  62934. message = newStatusMessage;
  62935. }
  62936. void ThreadWithProgressWindow::timerCallback()
  62937. {
  62938. if (! isThreadRunning())
  62939. {
  62940. // thread has finished normally..
  62941. alertWindow->exitModalState (1);
  62942. alertWindow->setVisible (false);
  62943. }
  62944. else
  62945. {
  62946. const ScopedLock sl (messageLock);
  62947. alertWindow->setMessage (message);
  62948. }
  62949. }
  62950. END_JUCE_NAMESPACE
  62951. /*** End of inlined file: juce_ThreadWithProgressWindow.cpp ***/
  62952. /*** Start of inlined file: juce_TooltipWindow.cpp ***/
  62953. BEGIN_JUCE_NAMESPACE
  62954. TooltipWindow::TooltipWindow (Component* const parentComponent,
  62955. const int millisecondsBeforeTipAppears_)
  62956. : Component ("tooltip"),
  62957. millisecondsBeforeTipAppears (millisecondsBeforeTipAppears_),
  62958. mouseClicks (0),
  62959. lastHideTime (0),
  62960. lastComponentUnderMouse (0),
  62961. changedCompsSinceShown (true)
  62962. {
  62963. if (Desktop::getInstance().getMainMouseSource().canHover())
  62964. startTimer (123);
  62965. setAlwaysOnTop (true);
  62966. setOpaque (true);
  62967. if (parentComponent != 0)
  62968. parentComponent->addChildComponent (this);
  62969. }
  62970. TooltipWindow::~TooltipWindow()
  62971. {
  62972. hide();
  62973. }
  62974. void TooltipWindow::setMillisecondsBeforeTipAppears (const int newTimeMs) throw()
  62975. {
  62976. millisecondsBeforeTipAppears = newTimeMs;
  62977. }
  62978. void TooltipWindow::paint (Graphics& g)
  62979. {
  62980. getLookAndFeel().drawTooltip (g, tipShowing, getWidth(), getHeight());
  62981. }
  62982. void TooltipWindow::mouseEnter (const MouseEvent&)
  62983. {
  62984. hide();
  62985. }
  62986. void TooltipWindow::showFor (const String& tip)
  62987. {
  62988. jassert (tip.isNotEmpty());
  62989. tipShowing = tip;
  62990. Point<int> mousePos (Desktop::getMousePosition());
  62991. if (getParentComponent() != 0)
  62992. mousePos = getParentComponent()->globalPositionToRelative (mousePos);
  62993. int x, y, w, h;
  62994. getLookAndFeel().getTooltipSize (tip, w, h);
  62995. if (mousePos.getX() > getParentWidth() / 2)
  62996. x = mousePos.getX() - (w + 12);
  62997. else
  62998. x = mousePos.getX() + 24;
  62999. if (mousePos.getY() > getParentHeight() / 2)
  63000. y = mousePos.getY() - (h + 6);
  63001. else
  63002. y = mousePos.getY() + 6;
  63003. setBounds (x, y, w, h);
  63004. setVisible (true);
  63005. if (getParentComponent() == 0)
  63006. {
  63007. addToDesktop (ComponentPeer::windowHasDropShadow
  63008. | ComponentPeer::windowIsTemporary
  63009. | ComponentPeer::windowIgnoresKeyPresses);
  63010. }
  63011. toFront (false);
  63012. }
  63013. const String TooltipWindow::getTipFor (Component* const c)
  63014. {
  63015. if (c != 0
  63016. && Process::isForegroundProcess()
  63017. && ! Component::isMouseButtonDownAnywhere())
  63018. {
  63019. TooltipClient* const ttc = dynamic_cast <TooltipClient*> (c);
  63020. if (ttc != 0 && ! c->isCurrentlyBlockedByAnotherModalComponent())
  63021. return ttc->getTooltip();
  63022. }
  63023. return String::empty;
  63024. }
  63025. void TooltipWindow::hide()
  63026. {
  63027. tipShowing = String::empty;
  63028. removeFromDesktop();
  63029. setVisible (false);
  63030. }
  63031. void TooltipWindow::timerCallback()
  63032. {
  63033. const unsigned int now = Time::getApproximateMillisecondCounter();
  63034. Component* const newComp = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  63035. const String newTip (getTipFor (newComp));
  63036. const bool tipChanged = (newTip != lastTipUnderMouse || newComp != lastComponentUnderMouse);
  63037. lastComponentUnderMouse = newComp;
  63038. lastTipUnderMouse = newTip;
  63039. const int clickCount = Desktop::getInstance().getMouseButtonClickCounter();
  63040. const bool mouseWasClicked = clickCount > mouseClicks;
  63041. mouseClicks = clickCount;
  63042. const Point<int> mousePos (Desktop::getMousePosition());
  63043. const bool mouseMovedQuickly = mousePos.getDistanceFrom (lastMousePos) > 12;
  63044. lastMousePos = mousePos;
  63045. if (tipChanged || mouseWasClicked || mouseMovedQuickly)
  63046. lastCompChangeTime = now;
  63047. if (isVisible() || now < lastHideTime + 500)
  63048. {
  63049. // if a tip is currently visible (or has just disappeared), update to a new one
  63050. // immediately if needed..
  63051. if (newComp == 0 || mouseWasClicked || newTip.isEmpty())
  63052. {
  63053. if (isVisible())
  63054. {
  63055. lastHideTime = now;
  63056. hide();
  63057. }
  63058. }
  63059. else if (tipChanged)
  63060. {
  63061. showFor (newTip);
  63062. }
  63063. }
  63064. else
  63065. {
  63066. // if there isn't currently a tip, but one is needed, only let it
  63067. // appear after a timeout..
  63068. if (newTip.isNotEmpty()
  63069. && newTip != tipShowing
  63070. && now > lastCompChangeTime + millisecondsBeforeTipAppears)
  63071. {
  63072. showFor (newTip);
  63073. }
  63074. }
  63075. }
  63076. END_JUCE_NAMESPACE
  63077. /*** End of inlined file: juce_TooltipWindow.cpp ***/
  63078. /*** Start of inlined file: juce_TopLevelWindow.cpp ***/
  63079. BEGIN_JUCE_NAMESPACE
  63080. /** Keeps track of the active top level window.
  63081. */
  63082. class TopLevelWindowManager : public Timer,
  63083. public DeletedAtShutdown
  63084. {
  63085. public:
  63086. TopLevelWindowManager()
  63087. : currentActive (0)
  63088. {
  63089. }
  63090. ~TopLevelWindowManager()
  63091. {
  63092. clearSingletonInstance();
  63093. }
  63094. juce_DeclareSingleton_SingleThreaded_Minimal (TopLevelWindowManager)
  63095. void timerCallback()
  63096. {
  63097. startTimer (jmin (1731, getTimerInterval() * 2));
  63098. TopLevelWindow* active = 0;
  63099. if (Process::isForegroundProcess())
  63100. {
  63101. active = currentActive;
  63102. Component* const c = Component::getCurrentlyFocusedComponent();
  63103. TopLevelWindow* tlw = dynamic_cast <TopLevelWindow*> (c);
  63104. if (tlw == 0 && c != 0)
  63105. // (unable to use the syntax findParentComponentOfClass <TopLevelWindow> () because of a VC6 compiler bug)
  63106. tlw = c->findParentComponentOfClass ((TopLevelWindow*) 0);
  63107. if (tlw != 0)
  63108. active = tlw;
  63109. }
  63110. if (active != currentActive)
  63111. {
  63112. currentActive = active;
  63113. for (int i = windows.size(); --i >= 0;)
  63114. {
  63115. TopLevelWindow* const tlw = windows.getUnchecked (i);
  63116. tlw->setWindowActive (isWindowActive (tlw));
  63117. i = jmin (i, windows.size() - 1);
  63118. }
  63119. Desktop::getInstance().triggerFocusCallback();
  63120. }
  63121. }
  63122. bool addWindow (TopLevelWindow* const w)
  63123. {
  63124. windows.add (w);
  63125. startTimer (10);
  63126. return isWindowActive (w);
  63127. }
  63128. void removeWindow (TopLevelWindow* const w)
  63129. {
  63130. startTimer (10);
  63131. if (currentActive == w)
  63132. currentActive = 0;
  63133. windows.removeValue (w);
  63134. if (windows.size() == 0)
  63135. deleteInstance();
  63136. }
  63137. Array <TopLevelWindow*> windows;
  63138. private:
  63139. TopLevelWindow* currentActive;
  63140. bool isWindowActive (TopLevelWindow* const tlw) const
  63141. {
  63142. return (tlw == currentActive
  63143. || tlw->isParentOf (currentActive)
  63144. || tlw->hasKeyboardFocus (true))
  63145. && tlw->isShowing();
  63146. }
  63147. TopLevelWindowManager (const TopLevelWindowManager&);
  63148. TopLevelWindowManager& operator= (const TopLevelWindowManager&);
  63149. };
  63150. juce_ImplementSingleton_SingleThreaded (TopLevelWindowManager)
  63151. void juce_CheckCurrentlyFocusedTopLevelWindow()
  63152. {
  63153. if (TopLevelWindowManager::getInstanceWithoutCreating() != 0)
  63154. TopLevelWindowManager::getInstanceWithoutCreating()->startTimer (20);
  63155. }
  63156. TopLevelWindow::TopLevelWindow (const String& name,
  63157. const bool addToDesktop_)
  63158. : Component (name),
  63159. useDropShadow (true),
  63160. useNativeTitleBar (false),
  63161. windowIsActive_ (false)
  63162. {
  63163. setOpaque (true);
  63164. if (addToDesktop_)
  63165. Component::addToDesktop (getDesktopWindowStyleFlags());
  63166. else
  63167. setDropShadowEnabled (true);
  63168. setWantsKeyboardFocus (true);
  63169. setBroughtToFrontOnMouseClick (true);
  63170. windowIsActive_ = TopLevelWindowManager::getInstance()->addWindow (this);
  63171. }
  63172. TopLevelWindow::~TopLevelWindow()
  63173. {
  63174. shadower = 0;
  63175. TopLevelWindowManager::getInstance()->removeWindow (this);
  63176. }
  63177. void TopLevelWindow::focusOfChildComponentChanged (FocusChangeType)
  63178. {
  63179. if (hasKeyboardFocus (true))
  63180. TopLevelWindowManager::getInstance()->timerCallback();
  63181. else
  63182. TopLevelWindowManager::getInstance()->startTimer (10);
  63183. }
  63184. void TopLevelWindow::setWindowActive (const bool isNowActive)
  63185. {
  63186. if (windowIsActive_ != isNowActive)
  63187. {
  63188. windowIsActive_ = isNowActive;
  63189. activeWindowStatusChanged();
  63190. }
  63191. }
  63192. void TopLevelWindow::activeWindowStatusChanged()
  63193. {
  63194. }
  63195. void TopLevelWindow::parentHierarchyChanged()
  63196. {
  63197. setDropShadowEnabled (useDropShadow);
  63198. }
  63199. void TopLevelWindow::visibilityChanged()
  63200. {
  63201. if (isShowing())
  63202. toFront (true);
  63203. }
  63204. int TopLevelWindow::getDesktopWindowStyleFlags() const
  63205. {
  63206. int styleFlags = ComponentPeer::windowAppearsOnTaskbar;
  63207. if (useDropShadow)
  63208. styleFlags |= ComponentPeer::windowHasDropShadow;
  63209. if (useNativeTitleBar)
  63210. styleFlags |= ComponentPeer::windowHasTitleBar;
  63211. return styleFlags;
  63212. }
  63213. void TopLevelWindow::setDropShadowEnabled (const bool useShadow)
  63214. {
  63215. useDropShadow = useShadow;
  63216. if (isOnDesktop())
  63217. {
  63218. shadower = 0;
  63219. Component::addToDesktop (getDesktopWindowStyleFlags());
  63220. }
  63221. else
  63222. {
  63223. if (useShadow && isOpaque())
  63224. {
  63225. if (shadower == 0)
  63226. {
  63227. shadower = getLookAndFeel().createDropShadowerForComponent (this);
  63228. if (shadower != 0)
  63229. shadower->setOwner (this);
  63230. }
  63231. }
  63232. else
  63233. {
  63234. shadower = 0;
  63235. }
  63236. }
  63237. }
  63238. void TopLevelWindow::setUsingNativeTitleBar (const bool useNativeTitleBar_)
  63239. {
  63240. if (useNativeTitleBar != useNativeTitleBar_)
  63241. {
  63242. useNativeTitleBar = useNativeTitleBar_;
  63243. recreateDesktopWindow();
  63244. sendLookAndFeelChange();
  63245. }
  63246. }
  63247. void TopLevelWindow::recreateDesktopWindow()
  63248. {
  63249. if (isOnDesktop())
  63250. {
  63251. Component::addToDesktop (getDesktopWindowStyleFlags());
  63252. toFront (true);
  63253. }
  63254. }
  63255. void TopLevelWindow::addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo)
  63256. {
  63257. /* It's not recommended to change the desktop window flags directly for a TopLevelWindow,
  63258. because this class needs to make sure its layout corresponds with settings like whether
  63259. it's got a native title bar or not.
  63260. If you need custom flags for your window, you can override the getDesktopWindowStyleFlags()
  63261. method. If you do this, it's best to call the base class's getDesktopWindowStyleFlags()
  63262. method, then add or remove whatever flags are necessary from this value before returning it.
  63263. */
  63264. jassert ((windowStyleFlags & ~ComponentPeer::windowIsSemiTransparent)
  63265. == (getDesktopWindowStyleFlags() & ~ComponentPeer::windowIsSemiTransparent));
  63266. Component::addToDesktop (windowStyleFlags, nativeWindowToAttachTo);
  63267. if (windowStyleFlags != getDesktopWindowStyleFlags())
  63268. sendLookAndFeelChange();
  63269. }
  63270. void TopLevelWindow::centreAroundComponent (Component* c, const int width, const int height)
  63271. {
  63272. if (c == 0)
  63273. c = TopLevelWindow::getActiveTopLevelWindow();
  63274. if (c == 0)
  63275. {
  63276. centreWithSize (width, height);
  63277. }
  63278. else
  63279. {
  63280. Point<int> p (c->relativePositionToGlobal (Point<int> ((c->getWidth() - width) / 2,
  63281. (c->getHeight() - height) / 2)));
  63282. Rectangle<int> parentArea (c->getParentMonitorArea());
  63283. if (getParentComponent() != 0)
  63284. {
  63285. p = getParentComponent()->globalPositionToRelative (p);
  63286. parentArea.setBounds (0, 0, getParentWidth(), getParentHeight());
  63287. }
  63288. parentArea.reduce (12, 12);
  63289. setBounds (jlimit (parentArea.getX(), jmax (parentArea.getX(), parentArea.getRight() - width), p.getX()),
  63290. jlimit (parentArea.getY(), jmax (parentArea.getY(), parentArea.getBottom() - height), p.getY()),
  63291. width, height);
  63292. }
  63293. }
  63294. int TopLevelWindow::getNumTopLevelWindows() throw()
  63295. {
  63296. return TopLevelWindowManager::getInstance()->windows.size();
  63297. }
  63298. TopLevelWindow* TopLevelWindow::getTopLevelWindow (const int index) throw()
  63299. {
  63300. return static_cast <TopLevelWindow*> (TopLevelWindowManager::getInstance()->windows [index]);
  63301. }
  63302. TopLevelWindow* TopLevelWindow::getActiveTopLevelWindow() throw()
  63303. {
  63304. TopLevelWindow* best = 0;
  63305. int bestNumTWLParents = -1;
  63306. for (int i = TopLevelWindow::getNumTopLevelWindows(); --i >= 0;)
  63307. {
  63308. TopLevelWindow* const tlw = TopLevelWindow::getTopLevelWindow (i);
  63309. if (tlw->isActiveWindow())
  63310. {
  63311. int numTWLParents = 0;
  63312. const Component* c = tlw->getParentComponent();
  63313. while (c != 0)
  63314. {
  63315. if (dynamic_cast <const TopLevelWindow*> (c) != 0)
  63316. ++numTWLParents;
  63317. c = c->getParentComponent();
  63318. }
  63319. if (bestNumTWLParents < numTWLParents)
  63320. {
  63321. best = tlw;
  63322. bestNumTWLParents = numTWLParents;
  63323. }
  63324. }
  63325. }
  63326. return best;
  63327. }
  63328. END_JUCE_NAMESPACE
  63329. /*** End of inlined file: juce_TopLevelWindow.cpp ***/
  63330. #endif
  63331. #if JUCE_BUILD_MISC // (put these in misc to balance the file sizes and avoid problems in iphone build)
  63332. /*** Start of inlined file: juce_Colour.cpp ***/
  63333. BEGIN_JUCE_NAMESPACE
  63334. namespace ColourHelpers
  63335. {
  63336. static uint8 floatAlphaToInt (const float alpha) throw()
  63337. {
  63338. return (uint8) jlimit (0, 0xff, roundToInt (alpha * 255.0f));
  63339. }
  63340. static void convertHSBtoRGB (float h, float s, float v,
  63341. uint8& r, uint8& g, uint8& b) throw()
  63342. {
  63343. v = jlimit (0.0f, 1.0f, v);
  63344. v *= 255.0f;
  63345. const uint8 intV = (uint8) roundToInt (v);
  63346. if (s <= 0)
  63347. {
  63348. r = intV;
  63349. g = intV;
  63350. b = intV;
  63351. }
  63352. else
  63353. {
  63354. s = jmin (1.0f, s);
  63355. h = jlimit (0.0f, 1.0f, h);
  63356. h = (h - std::floor (h)) * 6.0f + 0.00001f; // need a small adjustment to compensate for rounding errors
  63357. const float f = h - std::floor (h);
  63358. const uint8 x = (uint8) roundToInt (v * (1.0f - s));
  63359. const float y = v * (1.0f - s * f);
  63360. const float z = v * (1.0f - (s * (1.0f - f)));
  63361. if (h < 1.0f)
  63362. {
  63363. r = intV;
  63364. g = (uint8) roundToInt (z);
  63365. b = x;
  63366. }
  63367. else if (h < 2.0f)
  63368. {
  63369. r = (uint8) roundToInt (y);
  63370. g = intV;
  63371. b = x;
  63372. }
  63373. else if (h < 3.0f)
  63374. {
  63375. r = x;
  63376. g = intV;
  63377. b = (uint8) roundToInt (z);
  63378. }
  63379. else if (h < 4.0f)
  63380. {
  63381. r = x;
  63382. g = (uint8) roundToInt (y);
  63383. b = intV;
  63384. }
  63385. else if (h < 5.0f)
  63386. {
  63387. r = (uint8) roundToInt (z);
  63388. g = x;
  63389. b = intV;
  63390. }
  63391. else if (h < 6.0f)
  63392. {
  63393. r = intV;
  63394. g = x;
  63395. b = (uint8) roundToInt (y);
  63396. }
  63397. else
  63398. {
  63399. r = 0;
  63400. g = 0;
  63401. b = 0;
  63402. }
  63403. }
  63404. }
  63405. }
  63406. Colour::Colour() throw()
  63407. : argb (0)
  63408. {
  63409. }
  63410. Colour::Colour (const Colour& other) throw()
  63411. : argb (other.argb)
  63412. {
  63413. }
  63414. Colour& Colour::operator= (const Colour& other) throw()
  63415. {
  63416. argb = other.argb;
  63417. return *this;
  63418. }
  63419. bool Colour::operator== (const Colour& other) const throw()
  63420. {
  63421. return argb.getARGB() == other.argb.getARGB();
  63422. }
  63423. bool Colour::operator!= (const Colour& other) const throw()
  63424. {
  63425. return argb.getARGB() != other.argb.getARGB();
  63426. }
  63427. Colour::Colour (const uint32 argb_) throw()
  63428. : argb (argb_)
  63429. {
  63430. }
  63431. Colour::Colour (const uint8 red,
  63432. const uint8 green,
  63433. const uint8 blue) throw()
  63434. {
  63435. argb.setARGB (0xff, red, green, blue);
  63436. }
  63437. const Colour Colour::fromRGB (const uint8 red,
  63438. const uint8 green,
  63439. const uint8 blue) throw()
  63440. {
  63441. return Colour (red, green, blue);
  63442. }
  63443. Colour::Colour (const uint8 red,
  63444. const uint8 green,
  63445. const uint8 blue,
  63446. const uint8 alpha) throw()
  63447. {
  63448. argb.setARGB (alpha, red, green, blue);
  63449. }
  63450. const Colour Colour::fromRGBA (const uint8 red,
  63451. const uint8 green,
  63452. const uint8 blue,
  63453. const uint8 alpha) throw()
  63454. {
  63455. return Colour (red, green, blue, alpha);
  63456. }
  63457. Colour::Colour (const uint8 red,
  63458. const uint8 green,
  63459. const uint8 blue,
  63460. const float alpha) throw()
  63461. {
  63462. argb.setARGB (ColourHelpers::floatAlphaToInt (alpha), red, green, blue);
  63463. }
  63464. const Colour Colour::fromRGBAFloat (const uint8 red,
  63465. const uint8 green,
  63466. const uint8 blue,
  63467. const float alpha) throw()
  63468. {
  63469. return Colour (red, green, blue, alpha);
  63470. }
  63471. Colour::Colour (const float hue,
  63472. const float saturation,
  63473. const float brightness,
  63474. const float alpha) throw()
  63475. {
  63476. uint8 r = getRed(), g = getGreen(), b = getBlue();
  63477. ColourHelpers::convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  63478. argb.setARGB (ColourHelpers::floatAlphaToInt (alpha), r, g, b);
  63479. }
  63480. const Colour Colour::fromHSV (const float hue,
  63481. const float saturation,
  63482. const float brightness,
  63483. const float alpha) throw()
  63484. {
  63485. return Colour (hue, saturation, brightness, alpha);
  63486. }
  63487. Colour::Colour (const float hue,
  63488. const float saturation,
  63489. const float brightness,
  63490. const uint8 alpha) throw()
  63491. {
  63492. uint8 r = getRed(), g = getGreen(), b = getBlue();
  63493. ColourHelpers::convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  63494. argb.setARGB (alpha, r, g, b);
  63495. }
  63496. Colour::~Colour() throw()
  63497. {
  63498. }
  63499. const PixelARGB Colour::getPixelARGB() const throw()
  63500. {
  63501. PixelARGB p (argb);
  63502. p.premultiply();
  63503. return p;
  63504. }
  63505. uint32 Colour::getARGB() const throw()
  63506. {
  63507. return argb.getARGB();
  63508. }
  63509. bool Colour::isTransparent() const throw()
  63510. {
  63511. return getAlpha() == 0;
  63512. }
  63513. bool Colour::isOpaque() const throw()
  63514. {
  63515. return getAlpha() == 0xff;
  63516. }
  63517. const Colour Colour::withAlpha (const uint8 newAlpha) const throw()
  63518. {
  63519. PixelARGB newCol (argb);
  63520. newCol.setAlpha (newAlpha);
  63521. return Colour (newCol.getARGB());
  63522. }
  63523. const Colour Colour::withAlpha (const float newAlpha) const throw()
  63524. {
  63525. jassert (newAlpha >= 0 && newAlpha <= 1.0f);
  63526. PixelARGB newCol (argb);
  63527. newCol.setAlpha (ColourHelpers::floatAlphaToInt (newAlpha));
  63528. return Colour (newCol.getARGB());
  63529. }
  63530. const Colour Colour::withMultipliedAlpha (const float alphaMultiplier) const throw()
  63531. {
  63532. jassert (alphaMultiplier >= 0);
  63533. PixelARGB newCol (argb);
  63534. newCol.setAlpha ((uint8) jmin (0xff, roundToInt (alphaMultiplier * newCol.getAlpha())));
  63535. return Colour (newCol.getARGB());
  63536. }
  63537. const Colour Colour::overlaidWith (const Colour& src) const throw()
  63538. {
  63539. const int destAlpha = getAlpha();
  63540. if (destAlpha > 0)
  63541. {
  63542. const int invA = 0xff - (int) src.getAlpha();
  63543. const int resA = 0xff - (((0xff - destAlpha) * invA) >> 8);
  63544. if (resA > 0)
  63545. {
  63546. const int da = (invA * destAlpha) / resA;
  63547. return Colour ((uint8) (src.getRed() + ((((int) getRed() - src.getRed()) * da) >> 8)),
  63548. (uint8) (src.getGreen() + ((((int) getGreen() - src.getGreen()) * da) >> 8)),
  63549. (uint8) (src.getBlue() + ((((int) getBlue() - src.getBlue()) * da) >> 8)),
  63550. (uint8) resA);
  63551. }
  63552. return *this;
  63553. }
  63554. else
  63555. {
  63556. return src;
  63557. }
  63558. }
  63559. const Colour Colour::interpolatedWith (const Colour& other, float proportionOfOther) const throw()
  63560. {
  63561. if (proportionOfOther <= 0)
  63562. return *this;
  63563. if (proportionOfOther >= 1.0f)
  63564. return other;
  63565. PixelARGB c1 (getPixelARGB());
  63566. const PixelARGB c2 (other.getPixelARGB());
  63567. c1.tween (c2, roundToInt (proportionOfOther * 255.0f));
  63568. c1.unpremultiply();
  63569. return Colour (c1.getARGB());
  63570. }
  63571. float Colour::getFloatRed() const throw()
  63572. {
  63573. return getRed() / 255.0f;
  63574. }
  63575. float Colour::getFloatGreen() const throw()
  63576. {
  63577. return getGreen() / 255.0f;
  63578. }
  63579. float Colour::getFloatBlue() const throw()
  63580. {
  63581. return getBlue() / 255.0f;
  63582. }
  63583. float Colour::getFloatAlpha() const throw()
  63584. {
  63585. return getAlpha() / 255.0f;
  63586. }
  63587. void Colour::getHSB (float& h, float& s, float& v) const throw()
  63588. {
  63589. const int r = getRed();
  63590. const int g = getGreen();
  63591. const int b = getBlue();
  63592. const int hi = jmax (r, g, b);
  63593. const int lo = jmin (r, g, b);
  63594. if (hi != 0)
  63595. {
  63596. s = (hi - lo) / (float) hi;
  63597. if (s != 0)
  63598. {
  63599. const float invDiff = 1.0f / (hi - lo);
  63600. const float red = (hi - r) * invDiff;
  63601. const float green = (hi - g) * invDiff;
  63602. const float blue = (hi - b) * invDiff;
  63603. if (r == hi)
  63604. h = blue - green;
  63605. else if (g == hi)
  63606. h = 2.0f + red - blue;
  63607. else
  63608. h = 4.0f + green - red;
  63609. h *= 1.0f / 6.0f;
  63610. if (h < 0)
  63611. ++h;
  63612. }
  63613. else
  63614. {
  63615. h = 0;
  63616. }
  63617. }
  63618. else
  63619. {
  63620. s = 0;
  63621. h = 0;
  63622. }
  63623. v = hi / 255.0f;
  63624. }
  63625. float Colour::getHue() const throw()
  63626. {
  63627. float h, s, b;
  63628. getHSB (h, s, b);
  63629. return h;
  63630. }
  63631. const Colour Colour::withHue (const float hue) const throw()
  63632. {
  63633. float h, s, b;
  63634. getHSB (h, s, b);
  63635. return Colour (hue, s, b, getAlpha());
  63636. }
  63637. const Colour Colour::withRotatedHue (const float amountToRotate) const throw()
  63638. {
  63639. float h, s, b;
  63640. getHSB (h, s, b);
  63641. h += amountToRotate;
  63642. h -= std::floor (h);
  63643. return Colour (h, s, b, getAlpha());
  63644. }
  63645. float Colour::getSaturation() const throw()
  63646. {
  63647. float h, s, b;
  63648. getHSB (h, s, b);
  63649. return s;
  63650. }
  63651. const Colour Colour::withSaturation (const float saturation) const throw()
  63652. {
  63653. float h, s, b;
  63654. getHSB (h, s, b);
  63655. return Colour (h, saturation, b, getAlpha());
  63656. }
  63657. const Colour Colour::withMultipliedSaturation (const float amount) const throw()
  63658. {
  63659. float h, s, b;
  63660. getHSB (h, s, b);
  63661. return Colour (h, jmin (1.0f, s * amount), b, getAlpha());
  63662. }
  63663. float Colour::getBrightness() const throw()
  63664. {
  63665. float h, s, b;
  63666. getHSB (h, s, b);
  63667. return b;
  63668. }
  63669. const Colour Colour::withBrightness (const float brightness) const throw()
  63670. {
  63671. float h, s, b;
  63672. getHSB (h, s, b);
  63673. return Colour (h, s, brightness, getAlpha());
  63674. }
  63675. const Colour Colour::withMultipliedBrightness (const float amount) const throw()
  63676. {
  63677. float h, s, b;
  63678. getHSB (h, s, b);
  63679. b *= amount;
  63680. if (b > 1.0f)
  63681. b = 1.0f;
  63682. return Colour (h, s, b, getAlpha());
  63683. }
  63684. const Colour Colour::brighter (float amount) const throw()
  63685. {
  63686. amount = 1.0f / (1.0f + amount);
  63687. return Colour ((uint8) (255 - (amount * (255 - getRed()))),
  63688. (uint8) (255 - (amount * (255 - getGreen()))),
  63689. (uint8) (255 - (amount * (255 - getBlue()))),
  63690. getAlpha());
  63691. }
  63692. const Colour Colour::darker (float amount) const throw()
  63693. {
  63694. amount = 1.0f / (1.0f + amount);
  63695. return Colour ((uint8) (amount * getRed()),
  63696. (uint8) (amount * getGreen()),
  63697. (uint8) (amount * getBlue()),
  63698. getAlpha());
  63699. }
  63700. const Colour Colour::greyLevel (const float brightness) throw()
  63701. {
  63702. const uint8 level
  63703. = (uint8) jlimit (0x00, 0xff, roundToInt (brightness * 255.0f));
  63704. return Colour (level, level, level);
  63705. }
  63706. const Colour Colour::contrasting (const float amount) const throw()
  63707. {
  63708. return overlaidWith ((((int) getRed() + (int) getGreen() + (int) getBlue() >= 3 * 128)
  63709. ? Colours::black
  63710. : Colours::white).withAlpha (amount));
  63711. }
  63712. const Colour Colour::contrasting (const Colour& colour1,
  63713. const Colour& colour2) throw()
  63714. {
  63715. const float b1 = colour1.getBrightness();
  63716. const float b2 = colour2.getBrightness();
  63717. float best = 0.0f;
  63718. float bestDist = 0.0f;
  63719. for (float i = 0.0f; i < 1.0f; i += 0.02f)
  63720. {
  63721. const float d1 = std::abs (i - b1);
  63722. const float d2 = std::abs (i - b2);
  63723. const float dist = jmin (d1, d2, 1.0f - d1, 1.0f - d2);
  63724. if (dist > bestDist)
  63725. {
  63726. best = i;
  63727. bestDist = dist;
  63728. }
  63729. }
  63730. return colour1.overlaidWith (colour2.withMultipliedAlpha (0.5f))
  63731. .withBrightness (best);
  63732. }
  63733. const String Colour::toString() const
  63734. {
  63735. return String::toHexString ((int) argb.getARGB());
  63736. }
  63737. const Colour Colour::fromString (const String& encodedColourString)
  63738. {
  63739. return Colour ((uint32) encodedColourString.getHexValue32());
  63740. }
  63741. const String Colour::toDisplayString (const bool includeAlphaValue) const
  63742. {
  63743. return String::toHexString ((int) (argb.getARGB() & (includeAlphaValue ? 0xffffffff : 0xffffff)))
  63744. .paddedLeft ('0', includeAlphaValue ? 8 : 6)
  63745. .toUpperCase();
  63746. }
  63747. END_JUCE_NAMESPACE
  63748. /*** End of inlined file: juce_Colour.cpp ***/
  63749. /*** Start of inlined file: juce_ColourGradient.cpp ***/
  63750. BEGIN_JUCE_NAMESPACE
  63751. ColourGradient::ColourGradient() throw()
  63752. {
  63753. #if JUCE_DEBUG
  63754. point1.setX (987654.0f);
  63755. #endif
  63756. }
  63757. ColourGradient::ColourGradient (const Colour& colour1, const float x1_, const float y1_,
  63758. const Colour& colour2, const float x2_, const float y2_,
  63759. const bool isRadial_)
  63760. : point1 (x1_, y1_),
  63761. point2 (x2_, y2_),
  63762. isRadial (isRadial_)
  63763. {
  63764. colours.add (ColourPoint (0.0, colour1));
  63765. colours.add (ColourPoint (1.0, colour2));
  63766. }
  63767. ColourGradient::~ColourGradient()
  63768. {
  63769. }
  63770. bool ColourGradient::operator== (const ColourGradient& other) const throw()
  63771. {
  63772. return point1 == other.point1 && point2 == other.point2
  63773. && isRadial == other.isRadial
  63774. && colours == other.colours;
  63775. }
  63776. bool ColourGradient::operator!= (const ColourGradient& other) const throw()
  63777. {
  63778. return ! operator== (other);
  63779. }
  63780. void ColourGradient::clearColours()
  63781. {
  63782. colours.clear();
  63783. }
  63784. int ColourGradient::addColour (const double proportionAlongGradient, const Colour& colour)
  63785. {
  63786. // must be within the two end-points
  63787. jassert (proportionAlongGradient >= 0 && proportionAlongGradient <= 1.0);
  63788. const double pos = jlimit (0.0, 1.0, proportionAlongGradient);
  63789. int i;
  63790. for (i = 0; i < colours.size(); ++i)
  63791. if (colours.getReference(i).position > pos)
  63792. break;
  63793. colours.insert (i, ColourPoint (pos, colour));
  63794. return i;
  63795. }
  63796. void ColourGradient::removeColour (int index)
  63797. {
  63798. jassert (index > 0 && index < colours.size() - 1);
  63799. colours.remove (index);
  63800. }
  63801. void ColourGradient::multiplyOpacity (const float multiplier) throw()
  63802. {
  63803. for (int i = 0; i < colours.size(); ++i)
  63804. {
  63805. Colour& c = colours.getReference(i).colour;
  63806. c = c.withMultipliedAlpha (multiplier);
  63807. }
  63808. }
  63809. int ColourGradient::getNumColours() const throw()
  63810. {
  63811. return colours.size();
  63812. }
  63813. double ColourGradient::getColourPosition (const int index) const throw()
  63814. {
  63815. if (((unsigned int) index) < (unsigned int) colours.size())
  63816. return colours.getReference (index).position;
  63817. return 0;
  63818. }
  63819. const Colour ColourGradient::getColour (const int index) const throw()
  63820. {
  63821. if (((unsigned int) index) < (unsigned int) colours.size())
  63822. return colours.getReference (index).colour;
  63823. return Colour();
  63824. }
  63825. void ColourGradient::setColour (int index, const Colour& newColour) throw()
  63826. {
  63827. if (((unsigned int) index) < (unsigned int) colours.size())
  63828. colours.getReference (index).colour = newColour;
  63829. }
  63830. const Colour ColourGradient::getColourAtPosition (const double position) const throw()
  63831. {
  63832. jassert (colours.getReference(0).position == 0); // the first colour specified has to go at position 0
  63833. if (position <= 0 || colours.size() <= 1)
  63834. return colours.getReference(0).colour;
  63835. int i = colours.size() - 1;
  63836. while (position < colours.getReference(i).position)
  63837. --i;
  63838. const ColourPoint& p1 = colours.getReference (i);
  63839. if (i >= colours.size() - 1)
  63840. return p1.colour;
  63841. const ColourPoint& p2 = colours.getReference (i + 1);
  63842. return p1.colour.interpolatedWith (p2.colour, (float) ((position - p1.position) / (p2.position - p1.position)));
  63843. }
  63844. int ColourGradient::createLookupTable (const AffineTransform& transform, HeapBlock <PixelARGB>& lookupTable) const
  63845. {
  63846. #if JUCE_DEBUG
  63847. // trying to use the object without setting its co-ordinates? Have a careful read of
  63848. // the comments for the constructors.
  63849. jassert (point1.getX() != 987654.0f);
  63850. #endif
  63851. const int numEntries = jlimit (1, jmax (1, (colours.size() - 1) << 8),
  63852. 3 * (int) point1.transformedBy (transform)
  63853. .getDistanceFrom (point2.transformedBy (transform)));
  63854. lookupTable.malloc (numEntries);
  63855. if (colours.size() >= 2)
  63856. {
  63857. jassert (colours.getReference(0).position == 0); // the first colour specified has to go at position 0
  63858. PixelARGB pix1 (colours.getReference (0).colour.getPixelARGB());
  63859. int index = 0;
  63860. for (int j = 1; j < colours.size(); ++j)
  63861. {
  63862. const ColourPoint& p = colours.getReference (j);
  63863. const int numToDo = roundToInt (p.position * (numEntries - 1)) - index;
  63864. const PixelARGB pix2 (p.colour.getPixelARGB());
  63865. for (int i = 0; i < numToDo; ++i)
  63866. {
  63867. jassert (index >= 0 && index < numEntries);
  63868. lookupTable[index] = pix1;
  63869. lookupTable[index].tween (pix2, (i << 8) / numToDo);
  63870. ++index;
  63871. }
  63872. pix1 = pix2;
  63873. }
  63874. while (index < numEntries)
  63875. lookupTable [index++] = pix1;
  63876. }
  63877. else
  63878. {
  63879. jassertfalse; // no colours specified!
  63880. }
  63881. return numEntries;
  63882. }
  63883. bool ColourGradient::isOpaque() const throw()
  63884. {
  63885. for (int i = 0; i < colours.size(); ++i)
  63886. if (! colours.getReference(i).colour.isOpaque())
  63887. return false;
  63888. return true;
  63889. }
  63890. bool ColourGradient::isInvisible() const throw()
  63891. {
  63892. for (int i = 0; i < colours.size(); ++i)
  63893. if (! colours.getReference(i).colour.isTransparent())
  63894. return false;
  63895. return true;
  63896. }
  63897. END_JUCE_NAMESPACE
  63898. /*** End of inlined file: juce_ColourGradient.cpp ***/
  63899. /*** Start of inlined file: juce_Colours.cpp ***/
  63900. BEGIN_JUCE_NAMESPACE
  63901. const Colour Colours::transparentBlack (0);
  63902. const Colour Colours::transparentWhite (0x00ffffff);
  63903. const Colour Colours::aliceblue (0xfff0f8ff);
  63904. const Colour Colours::antiquewhite (0xfffaebd7);
  63905. const Colour Colours::aqua (0xff00ffff);
  63906. const Colour Colours::aquamarine (0xff7fffd4);
  63907. const Colour Colours::azure (0xfff0ffff);
  63908. const Colour Colours::beige (0xfff5f5dc);
  63909. const Colour Colours::bisque (0xffffe4c4);
  63910. const Colour Colours::black (0xff000000);
  63911. const Colour Colours::blanchedalmond (0xffffebcd);
  63912. const Colour Colours::blue (0xff0000ff);
  63913. const Colour Colours::blueviolet (0xff8a2be2);
  63914. const Colour Colours::brown (0xffa52a2a);
  63915. const Colour Colours::burlywood (0xffdeb887);
  63916. const Colour Colours::cadetblue (0xff5f9ea0);
  63917. const Colour Colours::chartreuse (0xff7fff00);
  63918. const Colour Colours::chocolate (0xffd2691e);
  63919. const Colour Colours::coral (0xffff7f50);
  63920. const Colour Colours::cornflowerblue (0xff6495ed);
  63921. const Colour Colours::cornsilk (0xfffff8dc);
  63922. const Colour Colours::crimson (0xffdc143c);
  63923. const Colour Colours::cyan (0xff00ffff);
  63924. const Colour Colours::darkblue (0xff00008b);
  63925. const Colour Colours::darkcyan (0xff008b8b);
  63926. const Colour Colours::darkgoldenrod (0xffb8860b);
  63927. const Colour Colours::darkgrey (0xff555555);
  63928. const Colour Colours::darkgreen (0xff006400);
  63929. const Colour Colours::darkkhaki (0xffbdb76b);
  63930. const Colour Colours::darkmagenta (0xff8b008b);
  63931. const Colour Colours::darkolivegreen (0xff556b2f);
  63932. const Colour Colours::darkorange (0xffff8c00);
  63933. const Colour Colours::darkorchid (0xff9932cc);
  63934. const Colour Colours::darkred (0xff8b0000);
  63935. const Colour Colours::darksalmon (0xffe9967a);
  63936. const Colour Colours::darkseagreen (0xff8fbc8f);
  63937. const Colour Colours::darkslateblue (0xff483d8b);
  63938. const Colour Colours::darkslategrey (0xff2f4f4f);
  63939. const Colour Colours::darkturquoise (0xff00ced1);
  63940. const Colour Colours::darkviolet (0xff9400d3);
  63941. const Colour Colours::deeppink (0xffff1493);
  63942. const Colour Colours::deepskyblue (0xff00bfff);
  63943. const Colour Colours::dimgrey (0xff696969);
  63944. const Colour Colours::dodgerblue (0xff1e90ff);
  63945. const Colour Colours::firebrick (0xffb22222);
  63946. const Colour Colours::floralwhite (0xfffffaf0);
  63947. const Colour Colours::forestgreen (0xff228b22);
  63948. const Colour Colours::fuchsia (0xffff00ff);
  63949. const Colour Colours::gainsboro (0xffdcdcdc);
  63950. const Colour Colours::gold (0xffffd700);
  63951. const Colour Colours::goldenrod (0xffdaa520);
  63952. const Colour Colours::grey (0xff808080);
  63953. const Colour Colours::green (0xff008000);
  63954. const Colour Colours::greenyellow (0xffadff2f);
  63955. const Colour Colours::honeydew (0xfff0fff0);
  63956. const Colour Colours::hotpink (0xffff69b4);
  63957. const Colour Colours::indianred (0xffcd5c5c);
  63958. const Colour Colours::indigo (0xff4b0082);
  63959. const Colour Colours::ivory (0xfffffff0);
  63960. const Colour Colours::khaki (0xfff0e68c);
  63961. const Colour Colours::lavender (0xffe6e6fa);
  63962. const Colour Colours::lavenderblush (0xfffff0f5);
  63963. const Colour Colours::lemonchiffon (0xfffffacd);
  63964. const Colour Colours::lightblue (0xffadd8e6);
  63965. const Colour Colours::lightcoral (0xfff08080);
  63966. const Colour Colours::lightcyan (0xffe0ffff);
  63967. const Colour Colours::lightgoldenrodyellow (0xfffafad2);
  63968. const Colour Colours::lightgreen (0xff90ee90);
  63969. const Colour Colours::lightgrey (0xffd3d3d3);
  63970. const Colour Colours::lightpink (0xffffb6c1);
  63971. const Colour Colours::lightsalmon (0xffffa07a);
  63972. const Colour Colours::lightseagreen (0xff20b2aa);
  63973. const Colour Colours::lightskyblue (0xff87cefa);
  63974. const Colour Colours::lightslategrey (0xff778899);
  63975. const Colour Colours::lightsteelblue (0xffb0c4de);
  63976. const Colour Colours::lightyellow (0xffffffe0);
  63977. const Colour Colours::lime (0xff00ff00);
  63978. const Colour Colours::limegreen (0xff32cd32);
  63979. const Colour Colours::linen (0xfffaf0e6);
  63980. const Colour Colours::magenta (0xffff00ff);
  63981. const Colour Colours::maroon (0xff800000);
  63982. const Colour Colours::mediumaquamarine (0xff66cdaa);
  63983. const Colour Colours::mediumblue (0xff0000cd);
  63984. const Colour Colours::mediumorchid (0xffba55d3);
  63985. const Colour Colours::mediumpurple (0xff9370db);
  63986. const Colour Colours::mediumseagreen (0xff3cb371);
  63987. const Colour Colours::mediumslateblue (0xff7b68ee);
  63988. const Colour Colours::mediumspringgreen (0xff00fa9a);
  63989. const Colour Colours::mediumturquoise (0xff48d1cc);
  63990. const Colour Colours::mediumvioletred (0xffc71585);
  63991. const Colour Colours::midnightblue (0xff191970);
  63992. const Colour Colours::mintcream (0xfff5fffa);
  63993. const Colour Colours::mistyrose (0xffffe4e1);
  63994. const Colour Colours::navajowhite (0xffffdead);
  63995. const Colour Colours::navy (0xff000080);
  63996. const Colour Colours::oldlace (0xfffdf5e6);
  63997. const Colour Colours::olive (0xff808000);
  63998. const Colour Colours::olivedrab (0xff6b8e23);
  63999. const Colour Colours::orange (0xffffa500);
  64000. const Colour Colours::orangered (0xffff4500);
  64001. const Colour Colours::orchid (0xffda70d6);
  64002. const Colour Colours::palegoldenrod (0xffeee8aa);
  64003. const Colour Colours::palegreen (0xff98fb98);
  64004. const Colour Colours::paleturquoise (0xffafeeee);
  64005. const Colour Colours::palevioletred (0xffdb7093);
  64006. const Colour Colours::papayawhip (0xffffefd5);
  64007. const Colour Colours::peachpuff (0xffffdab9);
  64008. const Colour Colours::peru (0xffcd853f);
  64009. const Colour Colours::pink (0xffffc0cb);
  64010. const Colour Colours::plum (0xffdda0dd);
  64011. const Colour Colours::powderblue (0xffb0e0e6);
  64012. const Colour Colours::purple (0xff800080);
  64013. const Colour Colours::red (0xffff0000);
  64014. const Colour Colours::rosybrown (0xffbc8f8f);
  64015. const Colour Colours::royalblue (0xff4169e1);
  64016. const Colour Colours::saddlebrown (0xff8b4513);
  64017. const Colour Colours::salmon (0xfffa8072);
  64018. const Colour Colours::sandybrown (0xfff4a460);
  64019. const Colour Colours::seagreen (0xff2e8b57);
  64020. const Colour Colours::seashell (0xfffff5ee);
  64021. const Colour Colours::sienna (0xffa0522d);
  64022. const Colour Colours::silver (0xffc0c0c0);
  64023. const Colour Colours::skyblue (0xff87ceeb);
  64024. const Colour Colours::slateblue (0xff6a5acd);
  64025. const Colour Colours::slategrey (0xff708090);
  64026. const Colour Colours::snow (0xfffffafa);
  64027. const Colour Colours::springgreen (0xff00ff7f);
  64028. const Colour Colours::steelblue (0xff4682b4);
  64029. const Colour Colours::tan (0xffd2b48c);
  64030. const Colour Colours::teal (0xff008080);
  64031. const Colour Colours::thistle (0xffd8bfd8);
  64032. const Colour Colours::tomato (0xffff6347);
  64033. const Colour Colours::turquoise (0xff40e0d0);
  64034. const Colour Colours::violet (0xffee82ee);
  64035. const Colour Colours::wheat (0xfff5deb3);
  64036. const Colour Colours::white (0xffffffff);
  64037. const Colour Colours::whitesmoke (0xfff5f5f5);
  64038. const Colour Colours::yellow (0xffffff00);
  64039. const Colour Colours::yellowgreen (0xff9acd32);
  64040. const Colour Colours::findColourForName (const String& colourName,
  64041. const Colour& defaultColour)
  64042. {
  64043. static const int presets[] =
  64044. {
  64045. // (first value is the string's hashcode, second is ARGB)
  64046. 0x05978fff, 0xff000000, /* black */
  64047. 0x06bdcc29, 0xffffffff, /* white */
  64048. 0x002e305a, 0xff0000ff, /* blue */
  64049. 0x00308adf, 0xff808080, /* grey */
  64050. 0x05e0cf03, 0xff008000, /* green */
  64051. 0x0001b891, 0xffff0000, /* red */
  64052. 0xd43c6474, 0xffffff00, /* yellow */
  64053. 0x620886da, 0xfff0f8ff, /* aliceblue */
  64054. 0x20a2676a, 0xfffaebd7, /* antiquewhite */
  64055. 0x002dcebc, 0xff00ffff, /* aqua */
  64056. 0x46bb5f7e, 0xff7fffd4, /* aquamarine */
  64057. 0x0590228f, 0xfff0ffff, /* azure */
  64058. 0x05947fe4, 0xfff5f5dc, /* beige */
  64059. 0xad388e35, 0xffffe4c4, /* bisque */
  64060. 0x00674f7e, 0xffffebcd, /* blanchedalmond */
  64061. 0x39129959, 0xff8a2be2, /* blueviolet */
  64062. 0x059a8136, 0xffa52a2a, /* brown */
  64063. 0x89cea8f9, 0xffdeb887, /* burlywood */
  64064. 0x0fa260cf, 0xff5f9ea0, /* cadetblue */
  64065. 0x6b748956, 0xff7fff00, /* chartreuse */
  64066. 0x2903623c, 0xffd2691e, /* chocolate */
  64067. 0x05a74431, 0xffff7f50, /* coral */
  64068. 0x618d42dd, 0xff6495ed, /* cornflowerblue */
  64069. 0xe4b479fd, 0xfffff8dc, /* cornsilk */
  64070. 0x3d8c4edf, 0xffdc143c, /* crimson */
  64071. 0x002ed323, 0xff00ffff, /* cyan */
  64072. 0x67cc74d0, 0xff00008b, /* darkblue */
  64073. 0x67cd1799, 0xff008b8b, /* darkcyan */
  64074. 0x31bbd168, 0xffb8860b, /* darkgoldenrod */
  64075. 0x67cecf55, 0xff555555, /* darkgrey */
  64076. 0x920b194d, 0xff006400, /* darkgreen */
  64077. 0x923edd4c, 0xffbdb76b, /* darkkhaki */
  64078. 0x5c293873, 0xff8b008b, /* darkmagenta */
  64079. 0x6b6671fe, 0xff556b2f, /* darkolivegreen */
  64080. 0xbcfd2524, 0xffff8c00, /* darkorange */
  64081. 0xbcfdf799, 0xff9932cc, /* darkorchid */
  64082. 0x55ee0d5b, 0xff8b0000, /* darkred */
  64083. 0xc2e5f564, 0xffe9967a, /* darksalmon */
  64084. 0x61be858a, 0xff8fbc8f, /* darkseagreen */
  64085. 0xc2b0f2bd, 0xff483d8b, /* darkslateblue */
  64086. 0xc2b34d42, 0xff2f4f4f, /* darkslategrey */
  64087. 0x7cf2b06b, 0xff00ced1, /* darkturquoise */
  64088. 0xc8769375, 0xff9400d3, /* darkviolet */
  64089. 0x25832862, 0xffff1493, /* deeppink */
  64090. 0xfcad568f, 0xff00bfff, /* deepskyblue */
  64091. 0x634c8b67, 0xff696969, /* dimgrey */
  64092. 0x45c1ce55, 0xff1e90ff, /* dodgerblue */
  64093. 0xef19e3cb, 0xffb22222, /* firebrick */
  64094. 0xb852b195, 0xfffffaf0, /* floralwhite */
  64095. 0xd086fd06, 0xff228b22, /* forestgreen */
  64096. 0xe106b6d7, 0xffff00ff, /* fuchsia */
  64097. 0x7880d61e, 0xffdcdcdc, /* gainsboro */
  64098. 0x00308060, 0xffffd700, /* gold */
  64099. 0xb3b3bc1e, 0xffdaa520, /* goldenrod */
  64100. 0xbab8a537, 0xffadff2f, /* greenyellow */
  64101. 0xe4cacafb, 0xfff0fff0, /* honeydew */
  64102. 0x41892743, 0xffff69b4, /* hotpink */
  64103. 0xd5796f1a, 0xffcd5c5c, /* indianred */
  64104. 0xb969fed2, 0xff4b0082, /* indigo */
  64105. 0x05fef6a9, 0xfffffff0, /* ivory */
  64106. 0x06149302, 0xfff0e68c, /* khaki */
  64107. 0xad5a05c7, 0xffe6e6fa, /* lavender */
  64108. 0x7c4d5b99, 0xfffff0f5, /* lavenderblush */
  64109. 0x195756f0, 0xfffffacd, /* lemonchiffon */
  64110. 0x28e4ea70, 0xffadd8e6, /* lightblue */
  64111. 0xf3c7ccdb, 0xfff08080, /* lightcoral */
  64112. 0x28e58d39, 0xffe0ffff, /* lightcyan */
  64113. 0x21234e3c, 0xfffafad2, /* lightgoldenrodyellow */
  64114. 0xf40157ad, 0xff90ee90, /* lightgreen */
  64115. 0x28e744f5, 0xffd3d3d3, /* lightgrey */
  64116. 0x28eb3b8c, 0xffffb6c1, /* lightpink */
  64117. 0x9fb78304, 0xffffa07a, /* lightsalmon */
  64118. 0x50632b2a, 0xff20b2aa, /* lightseagreen */
  64119. 0x68fb7b25, 0xff87cefa, /* lightskyblue */
  64120. 0xa8a35ba2, 0xff778899, /* lightslategrey */
  64121. 0xa20d484f, 0xffb0c4de, /* lightsteelblue */
  64122. 0xaa2cf10a, 0xffffffe0, /* lightyellow */
  64123. 0x0032afd5, 0xff00ff00, /* lime */
  64124. 0x607bbc4e, 0xff32cd32, /* limegreen */
  64125. 0x06234efa, 0xfffaf0e6, /* linen */
  64126. 0x316858a9, 0xffff00ff, /* magenta */
  64127. 0xbf8ca470, 0xff800000, /* maroon */
  64128. 0xbd58e0b3, 0xff66cdaa, /* mediumaquamarine */
  64129. 0x967dfd4f, 0xff0000cd, /* mediumblue */
  64130. 0x056f5c58, 0xffba55d3, /* mediumorchid */
  64131. 0x07556b71, 0xff9370db, /* mediumpurple */
  64132. 0x5369b689, 0xff3cb371, /* mediumseagreen */
  64133. 0x066be19e, 0xff7b68ee, /* mediumslateblue */
  64134. 0x3256b281, 0xff00fa9a, /* mediumspringgreen */
  64135. 0xc0ad9f4c, 0xff48d1cc, /* mediumturquoise */
  64136. 0x628e63dd, 0xffc71585, /* mediumvioletred */
  64137. 0x168eb32a, 0xff191970, /* midnightblue */
  64138. 0x4306b960, 0xfff5fffa, /* mintcream */
  64139. 0x4cbc0e6b, 0xffffe4e1, /* mistyrose */
  64140. 0xe97218a6, 0xffffdead, /* navajowhite */
  64141. 0x00337bb6, 0xff000080, /* navy */
  64142. 0xadd2d33e, 0xfffdf5e6, /* oldlace */
  64143. 0x064ee1db, 0xff808000, /* olive */
  64144. 0x9e33a98a, 0xff6b8e23, /* olivedrab */
  64145. 0xc3de262e, 0xffffa500, /* orange */
  64146. 0x58bebba3, 0xffff4500, /* orangered */
  64147. 0xc3def8a3, 0xffda70d6, /* orchid */
  64148. 0x28cb4834, 0xffeee8aa, /* palegoldenrod */
  64149. 0x3d9dd619, 0xff98fb98, /* palegreen */
  64150. 0x74022737, 0xffafeeee, /* paleturquoise */
  64151. 0x15e2ebc8, 0xffdb7093, /* palevioletred */
  64152. 0x5fd898e2, 0xffffefd5, /* papayawhip */
  64153. 0x93e1b776, 0xffffdab9, /* peachpuff */
  64154. 0x003472f8, 0xffcd853f, /* peru */
  64155. 0x00348176, 0xffffc0cb, /* pink */
  64156. 0x00348d94, 0xffdda0dd, /* plum */
  64157. 0xd036be93, 0xffb0e0e6, /* powderblue */
  64158. 0xc5c507bc, 0xff800080, /* purple */
  64159. 0xa89d65b3, 0xffbc8f8f, /* rosybrown */
  64160. 0xbd9413e1, 0xff4169e1, /* royalblue */
  64161. 0xf456044f, 0xff8b4513, /* saddlebrown */
  64162. 0xc9c6f66e, 0xfffa8072, /* salmon */
  64163. 0x0bb131e1, 0xfff4a460, /* sandybrown */
  64164. 0x34636c14, 0xff2e8b57, /* seagreen */
  64165. 0x3507fb41, 0xfffff5ee, /* seashell */
  64166. 0xca348772, 0xffa0522d, /* sienna */
  64167. 0xca37d30d, 0xffc0c0c0, /* silver */
  64168. 0x80da74fb, 0xff87ceeb, /* skyblue */
  64169. 0x44a8dd73, 0xff6a5acd, /* slateblue */
  64170. 0x44ab37f8, 0xff708090, /* slategrey */
  64171. 0x0035f183, 0xfffffafa, /* snow */
  64172. 0xd5440d16, 0xff00ff7f, /* springgreen */
  64173. 0x3e1524a5, 0xff4682b4, /* steelblue */
  64174. 0x0001bfa1, 0xffd2b48c, /* tan */
  64175. 0x0036425c, 0xff008080, /* teal */
  64176. 0xafc8858f, 0xffd8bfd8, /* thistle */
  64177. 0xcc41600a, 0xffff6347, /* tomato */
  64178. 0xfeea9b21, 0xff40e0d0, /* turquoise */
  64179. 0xcf57947f, 0xffee82ee, /* violet */
  64180. 0x06bdbae7, 0xfff5deb3, /* wheat */
  64181. 0x10802ee6, 0xfff5f5f5, /* whitesmoke */
  64182. 0xe1b5130f, 0xff9acd32 /* yellowgreen */
  64183. };
  64184. const int hash = colourName.trim().toLowerCase().hashCode();
  64185. for (int i = 0; i < numElementsInArray (presets); i += 2)
  64186. if (presets [i] == hash)
  64187. return Colour (presets [i + 1]);
  64188. return defaultColour;
  64189. }
  64190. END_JUCE_NAMESPACE
  64191. /*** End of inlined file: juce_Colours.cpp ***/
  64192. /*** Start of inlined file: juce_EdgeTable.cpp ***/
  64193. BEGIN_JUCE_NAMESPACE
  64194. const int juce_edgeTableDefaultEdgesPerLine = 32;
  64195. EdgeTable::EdgeTable (const Rectangle<int>& bounds_,
  64196. const Path& path, const AffineTransform& transform)
  64197. : bounds (bounds_),
  64198. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  64199. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  64200. needToCheckEmptinesss (true)
  64201. {
  64202. table.malloc ((bounds.getHeight() + 1) * lineStrideElements);
  64203. int* t = table;
  64204. for (int i = bounds.getHeight(); --i >= 0;)
  64205. {
  64206. *t = 0;
  64207. t += lineStrideElements;
  64208. }
  64209. const int topLimit = bounds.getY() << 8;
  64210. const int heightLimit = bounds.getHeight() << 8;
  64211. const int leftLimit = bounds.getX() << 8;
  64212. const int rightLimit = bounds.getRight() << 8;
  64213. PathFlatteningIterator iter (path, transform);
  64214. while (iter.next())
  64215. {
  64216. int y1 = roundToInt (iter.y1 * 256.0f);
  64217. int y2 = roundToInt (iter.y2 * 256.0f);
  64218. if (y1 != y2)
  64219. {
  64220. y1 -= topLimit;
  64221. y2 -= topLimit;
  64222. const int startY = y1;
  64223. int direction = -1;
  64224. if (y1 > y2)
  64225. {
  64226. swapVariables (y1, y2);
  64227. direction = 1;
  64228. }
  64229. if (y1 < 0)
  64230. y1 = 0;
  64231. if (y2 > heightLimit)
  64232. y2 = heightLimit;
  64233. if (y1 < y2)
  64234. {
  64235. const double startX = 256.0f * iter.x1;
  64236. const double multiplier = (iter.x2 - iter.x1) / (iter.y2 - iter.y1);
  64237. const int stepSize = jlimit (1, 256, 256 / (1 + (int) std::abs (multiplier)));
  64238. do
  64239. {
  64240. const int step = jmin (stepSize, y2 - y1, 256 - (y1 & 255));
  64241. int x = roundToInt (startX + multiplier * ((y1 + (step >> 1)) - startY));
  64242. if (x < leftLimit)
  64243. x = leftLimit;
  64244. else if (x >= rightLimit)
  64245. x = rightLimit - 1;
  64246. addEdgePoint (x, y1 >> 8, direction * step);
  64247. y1 += step;
  64248. }
  64249. while (y1 < y2);
  64250. }
  64251. }
  64252. }
  64253. sanitiseLevels (path.isUsingNonZeroWinding());
  64254. }
  64255. EdgeTable::EdgeTable (const Rectangle<int>& rectangleToAdd)
  64256. : bounds (rectangleToAdd),
  64257. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  64258. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  64259. needToCheckEmptinesss (true)
  64260. {
  64261. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  64262. table[0] = 0;
  64263. const int x1 = rectangleToAdd.getX() << 8;
  64264. const int x2 = rectangleToAdd.getRight() << 8;
  64265. int* t = table;
  64266. for (int i = rectangleToAdd.getHeight(); --i >= 0;)
  64267. {
  64268. t[0] = 2;
  64269. t[1] = x1;
  64270. t[2] = 255;
  64271. t[3] = x2;
  64272. t[4] = 0;
  64273. t += lineStrideElements;
  64274. }
  64275. }
  64276. EdgeTable::EdgeTable (const RectangleList& rectanglesToAdd)
  64277. : bounds (rectanglesToAdd.getBounds()),
  64278. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  64279. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  64280. needToCheckEmptinesss (true)
  64281. {
  64282. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  64283. int* t = table;
  64284. for (int i = bounds.getHeight(); --i >= 0;)
  64285. {
  64286. *t = 0;
  64287. t += lineStrideElements;
  64288. }
  64289. for (RectangleList::Iterator iter (rectanglesToAdd); iter.next();)
  64290. {
  64291. const Rectangle<int>* const r = iter.getRectangle();
  64292. const int x1 = r->getX() << 8;
  64293. const int x2 = r->getRight() << 8;
  64294. int y = r->getY() - bounds.getY();
  64295. for (int j = r->getHeight(); --j >= 0;)
  64296. {
  64297. addEdgePoint (x1, y, 255);
  64298. addEdgePoint (x2, y, -255);
  64299. ++y;
  64300. }
  64301. }
  64302. sanitiseLevels (true);
  64303. }
  64304. EdgeTable::EdgeTable (const Rectangle<float>& rectangleToAdd)
  64305. : bounds (Rectangle<int> ((int) std::floor (rectangleToAdd.getX()),
  64306. roundToInt (rectangleToAdd.getY() * 256.0f) >> 8,
  64307. 2 + (int) rectangleToAdd.getWidth(),
  64308. 2 + (int) rectangleToAdd.getHeight())),
  64309. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  64310. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  64311. needToCheckEmptinesss (true)
  64312. {
  64313. jassert (! rectangleToAdd.isEmpty());
  64314. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  64315. table[0] = 0;
  64316. const int x1 = roundToInt (rectangleToAdd.getX() * 256.0f);
  64317. const int x2 = roundToInt (rectangleToAdd.getRight() * 256.0f);
  64318. int y1 = roundToInt (rectangleToAdd.getY() * 256.0f) - (bounds.getY() << 8);
  64319. jassert (y1 < 256);
  64320. int y2 = roundToInt (rectangleToAdd.getBottom() * 256.0f) - (bounds.getY() << 8);
  64321. if (x2 <= x1 || y2 <= y1)
  64322. {
  64323. bounds.setHeight (0);
  64324. return;
  64325. }
  64326. int lineY = 0;
  64327. int* t = table;
  64328. if ((y1 >> 8) == (y2 >> 8))
  64329. {
  64330. t[0] = 2;
  64331. t[1] = x1;
  64332. t[2] = y2 - y1;
  64333. t[3] = x2;
  64334. t[4] = 0;
  64335. ++lineY;
  64336. t += lineStrideElements;
  64337. }
  64338. else
  64339. {
  64340. t[0] = 2;
  64341. t[1] = x1;
  64342. t[2] = 255 - (y1 & 255);
  64343. t[3] = x2;
  64344. t[4] = 0;
  64345. ++lineY;
  64346. t += lineStrideElements;
  64347. while (lineY < (y2 >> 8))
  64348. {
  64349. t[0] = 2;
  64350. t[1] = x1;
  64351. t[2] = 255;
  64352. t[3] = x2;
  64353. t[4] = 0;
  64354. ++lineY;
  64355. t += lineStrideElements;
  64356. }
  64357. jassert (lineY < bounds.getHeight());
  64358. t[0] = 2;
  64359. t[1] = x1;
  64360. t[2] = y2 & 255;
  64361. t[3] = x2;
  64362. t[4] = 0;
  64363. ++lineY;
  64364. t += lineStrideElements;
  64365. }
  64366. while (lineY < bounds.getHeight())
  64367. {
  64368. t[0] = 0;
  64369. t += lineStrideElements;
  64370. ++lineY;
  64371. }
  64372. }
  64373. EdgeTable::EdgeTable (const EdgeTable& other)
  64374. {
  64375. operator= (other);
  64376. }
  64377. EdgeTable& EdgeTable::operator= (const EdgeTable& other)
  64378. {
  64379. bounds = other.bounds;
  64380. maxEdgesPerLine = other.maxEdgesPerLine;
  64381. lineStrideElements = other.lineStrideElements;
  64382. needToCheckEmptinesss = other.needToCheckEmptinesss;
  64383. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  64384. copyEdgeTableData (table, lineStrideElements, other.table, lineStrideElements, bounds.getHeight());
  64385. return *this;
  64386. }
  64387. EdgeTable::~EdgeTable()
  64388. {
  64389. }
  64390. void EdgeTable::copyEdgeTableData (int* dest, const int destLineStride, const int* src, const int srcLineStride, int numLines) throw()
  64391. {
  64392. while (--numLines >= 0)
  64393. {
  64394. memcpy (dest, src, (src[0] * 2 + 1) * sizeof (int));
  64395. src += srcLineStride;
  64396. dest += destLineStride;
  64397. }
  64398. }
  64399. void EdgeTable::sanitiseLevels (const bool useNonZeroWinding) throw()
  64400. {
  64401. // Convert the table from relative windings to absolute levels..
  64402. int* lineStart = table;
  64403. for (int i = bounds.getHeight(); --i >= 0;)
  64404. {
  64405. int* line = lineStart;
  64406. lineStart += lineStrideElements;
  64407. int num = *line;
  64408. if (num == 0)
  64409. continue;
  64410. int level = 0;
  64411. if (useNonZeroWinding)
  64412. {
  64413. while (--num > 0)
  64414. {
  64415. line += 2;
  64416. level += *line;
  64417. int corrected = abs (level);
  64418. if (corrected >> 8)
  64419. corrected = 255;
  64420. *line = corrected;
  64421. }
  64422. }
  64423. else
  64424. {
  64425. while (--num > 0)
  64426. {
  64427. line += 2;
  64428. level += *line;
  64429. int corrected = abs (level);
  64430. if (corrected >> 8)
  64431. {
  64432. corrected &= 511;
  64433. if (corrected >> 8)
  64434. corrected = 511 - corrected;
  64435. }
  64436. *line = corrected;
  64437. }
  64438. }
  64439. line[2] = 0; // force the last level to 0, just in case something went wrong in creating the table
  64440. }
  64441. }
  64442. void EdgeTable::remapTableForNumEdges (const int newNumEdgesPerLine) throw()
  64443. {
  64444. if (newNumEdgesPerLine != maxEdgesPerLine)
  64445. {
  64446. maxEdgesPerLine = newNumEdgesPerLine;
  64447. jassert (bounds.getHeight() > 0);
  64448. const int newLineStrideElements = maxEdgesPerLine * 2 + 1;
  64449. HeapBlock <int> newTable (bounds.getHeight() * newLineStrideElements);
  64450. copyEdgeTableData (newTable, newLineStrideElements, table, lineStrideElements, bounds.getHeight());
  64451. table.swapWith (newTable);
  64452. lineStrideElements = newLineStrideElements;
  64453. }
  64454. }
  64455. void EdgeTable::optimiseTable() throw()
  64456. {
  64457. int maxLineElements = 0;
  64458. for (int i = bounds.getHeight(); --i >= 0;)
  64459. maxLineElements = jmax (maxLineElements, table [i * lineStrideElements]);
  64460. remapTableForNumEdges (maxLineElements);
  64461. }
  64462. void EdgeTable::addEdgePoint (const int x, const int y, const int winding) throw()
  64463. {
  64464. jassert (y >= 0 && y < bounds.getHeight());
  64465. int* line = table + lineStrideElements * y;
  64466. const int numPoints = line[0];
  64467. int n = numPoints << 1;
  64468. if (n > 0)
  64469. {
  64470. while (n > 0)
  64471. {
  64472. const int cx = line [n - 1];
  64473. if (cx <= x)
  64474. {
  64475. if (cx == x)
  64476. {
  64477. line [n] += winding;
  64478. return;
  64479. }
  64480. break;
  64481. }
  64482. n -= 2;
  64483. }
  64484. if (numPoints >= maxEdgesPerLine)
  64485. {
  64486. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  64487. jassert (numPoints < maxEdgesPerLine);
  64488. line = table + lineStrideElements * y;
  64489. }
  64490. memmove (line + (n + 3), line + (n + 1), sizeof (int) * ((numPoints << 1) - n));
  64491. }
  64492. line [n + 1] = x;
  64493. line [n + 2] = winding;
  64494. line[0]++;
  64495. }
  64496. void EdgeTable::translate (float dx, const int dy) throw()
  64497. {
  64498. bounds.translate ((int) std::floor (dx), dy);
  64499. int* lineStart = table;
  64500. const int intDx = (int) (dx * 256.0f);
  64501. for (int i = bounds.getHeight(); --i >= 0;)
  64502. {
  64503. int* line = lineStart;
  64504. lineStart += lineStrideElements;
  64505. int num = *line++;
  64506. while (--num >= 0)
  64507. {
  64508. *line += intDx;
  64509. line += 2;
  64510. }
  64511. }
  64512. }
  64513. void EdgeTable::intersectWithEdgeTableLine (const int y, const int* otherLine) throw()
  64514. {
  64515. jassert (y >= 0 && y < bounds.getHeight());
  64516. int* dest = table + lineStrideElements * y;
  64517. if (dest[0] == 0)
  64518. return;
  64519. int otherNumPoints = *otherLine;
  64520. if (otherNumPoints == 0)
  64521. {
  64522. *dest = 0;
  64523. return;
  64524. }
  64525. const int right = bounds.getRight() << 8;
  64526. // optimise for the common case where our line lies entirely within a
  64527. // single pair of points, as happens when clipping to a simple rect.
  64528. if (otherNumPoints == 2 && otherLine[2] >= 255)
  64529. {
  64530. clipEdgeTableLineToRange (dest, otherLine[1], jmin (right, otherLine[3]));
  64531. return;
  64532. }
  64533. ++otherLine;
  64534. const size_t lineSizeBytes = (dest[0] * 2 + 1) * sizeof (int);
  64535. int* temp = (int*) alloca (lineSizeBytes);
  64536. memcpy (temp, dest, lineSizeBytes);
  64537. const int* src1 = temp;
  64538. int srcNum1 = *src1++;
  64539. int x1 = *src1++;
  64540. const int* src2 = otherLine;
  64541. int srcNum2 = otherNumPoints;
  64542. int x2 = *src2++;
  64543. int destIndex = 0, destTotal = 0;
  64544. int level1 = 0, level2 = 0;
  64545. int lastX = std::numeric_limits<int>::min(), lastLevel = 0;
  64546. while (srcNum1 > 0 && srcNum2 > 0)
  64547. {
  64548. int nextX;
  64549. if (x1 < x2)
  64550. {
  64551. nextX = x1;
  64552. level1 = *src1++;
  64553. x1 = *src1++;
  64554. --srcNum1;
  64555. }
  64556. else if (x1 == x2)
  64557. {
  64558. nextX = x1;
  64559. level1 = *src1++;
  64560. level2 = *src2++;
  64561. x1 = *src1++;
  64562. x2 = *src2++;
  64563. --srcNum1;
  64564. --srcNum2;
  64565. }
  64566. else
  64567. {
  64568. nextX = x2;
  64569. level2 = *src2++;
  64570. x2 = *src2++;
  64571. --srcNum2;
  64572. }
  64573. if (nextX > lastX)
  64574. {
  64575. if (nextX >= right)
  64576. break;
  64577. lastX = nextX;
  64578. const int nextLevel = (level1 * (level2 + 1)) >> 8;
  64579. jassert (((unsigned int) nextLevel) < (unsigned int) 256);
  64580. if (nextLevel != lastLevel)
  64581. {
  64582. if (destTotal >= maxEdgesPerLine)
  64583. {
  64584. dest[0] = destTotal;
  64585. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  64586. dest = table + lineStrideElements * y;
  64587. }
  64588. ++destTotal;
  64589. lastLevel = nextLevel;
  64590. dest[++destIndex] = nextX;
  64591. dest[++destIndex] = nextLevel;
  64592. }
  64593. }
  64594. }
  64595. if (lastLevel > 0)
  64596. {
  64597. if (destTotal >= maxEdgesPerLine)
  64598. {
  64599. dest[0] = destTotal;
  64600. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  64601. dest = table + lineStrideElements * y;
  64602. }
  64603. ++destTotal;
  64604. dest[++destIndex] = right;
  64605. dest[++destIndex] = 0;
  64606. }
  64607. dest[0] = destTotal;
  64608. #if JUCE_DEBUG
  64609. int last = std::numeric_limits<int>::min();
  64610. for (int i = 0; i < dest[0]; ++i)
  64611. {
  64612. jassert (dest[i * 2 + 1] > last);
  64613. last = dest[i * 2 + 1];
  64614. }
  64615. jassert (dest [dest[0] * 2] == 0);
  64616. #endif
  64617. }
  64618. void EdgeTable::clipEdgeTableLineToRange (int* dest, const int x1, const int x2) throw()
  64619. {
  64620. int* lastItem = dest + (dest[0] * 2 - 1);
  64621. if (x2 < lastItem[0])
  64622. {
  64623. if (x2 <= dest[1])
  64624. {
  64625. dest[0] = 0;
  64626. return;
  64627. }
  64628. while (x2 < lastItem[-2])
  64629. {
  64630. --(dest[0]);
  64631. lastItem -= 2;
  64632. }
  64633. lastItem[0] = x2;
  64634. lastItem[1] = 0;
  64635. }
  64636. if (x1 > dest[1])
  64637. {
  64638. while (lastItem[0] > x1)
  64639. lastItem -= 2;
  64640. const int itemsRemoved = (int) (lastItem - (dest + 1)) / 2;
  64641. if (itemsRemoved > 0)
  64642. {
  64643. dest[0] -= itemsRemoved;
  64644. memmove (dest + 1, lastItem, dest[0] * (sizeof (int) * 2));
  64645. }
  64646. dest[1] = x1;
  64647. }
  64648. }
  64649. void EdgeTable::clipToRectangle (const Rectangle<int>& r) throw()
  64650. {
  64651. const Rectangle<int> clipped (r.getIntersection (bounds));
  64652. if (clipped.isEmpty())
  64653. {
  64654. needToCheckEmptinesss = false;
  64655. bounds.setHeight (0);
  64656. }
  64657. else
  64658. {
  64659. const int top = clipped.getY() - bounds.getY();
  64660. const int bottom = clipped.getBottom() - bounds.getY();
  64661. if (bottom < bounds.getHeight())
  64662. bounds.setHeight (bottom);
  64663. if (clipped.getRight() < bounds.getRight())
  64664. bounds.setRight (clipped.getRight());
  64665. for (int i = top; --i >= 0;)
  64666. table [lineStrideElements * i] = 0;
  64667. if (clipped.getX() > bounds.getX())
  64668. {
  64669. const int x1 = clipped.getX() << 8;
  64670. const int x2 = jmin (bounds.getRight(), clipped.getRight()) << 8;
  64671. int* line = table + lineStrideElements * top;
  64672. for (int i = bottom - top; --i >= 0;)
  64673. {
  64674. if (line[0] != 0)
  64675. clipEdgeTableLineToRange (line, x1, x2);
  64676. line += lineStrideElements;
  64677. }
  64678. }
  64679. needToCheckEmptinesss = true;
  64680. }
  64681. }
  64682. void EdgeTable::excludeRectangle (const Rectangle<int>& r) throw()
  64683. {
  64684. const Rectangle<int> clipped (r.getIntersection (bounds));
  64685. if (! clipped.isEmpty())
  64686. {
  64687. const int top = clipped.getY() - bounds.getY();
  64688. const int bottom = clipped.getBottom() - bounds.getY();
  64689. //XXX optimise here by shortening the table if it fills top or bottom
  64690. const int rectLine[] = { 4, std::numeric_limits<int>::min(), 255,
  64691. clipped.getX() << 8, 0,
  64692. clipped.getRight() << 8, 255,
  64693. std::numeric_limits<int>::max(), 0 };
  64694. for (int i = top; i < bottom; ++i)
  64695. intersectWithEdgeTableLine (i, rectLine);
  64696. needToCheckEmptinesss = true;
  64697. }
  64698. }
  64699. void EdgeTable::clipToEdgeTable (const EdgeTable& other)
  64700. {
  64701. const Rectangle<int> clipped (other.bounds.getIntersection (bounds));
  64702. if (clipped.isEmpty())
  64703. {
  64704. needToCheckEmptinesss = false;
  64705. bounds.setHeight (0);
  64706. }
  64707. else
  64708. {
  64709. const int top = clipped.getY() - bounds.getY();
  64710. const int bottom = clipped.getBottom() - bounds.getY();
  64711. if (bottom < bounds.getHeight())
  64712. bounds.setHeight (bottom);
  64713. if (clipped.getRight() < bounds.getRight())
  64714. bounds.setRight (clipped.getRight());
  64715. int i = 0;
  64716. for (i = top; --i >= 0;)
  64717. table [lineStrideElements * i] = 0;
  64718. const int* otherLine = other.table + other.lineStrideElements * (clipped.getY() - other.bounds.getY());
  64719. for (i = top; i < bottom; ++i)
  64720. {
  64721. intersectWithEdgeTableLine (i, otherLine);
  64722. otherLine += other.lineStrideElements;
  64723. }
  64724. needToCheckEmptinesss = true;
  64725. }
  64726. }
  64727. void EdgeTable::clipLineToMask (int x, int y, const uint8* mask, int maskStride, int numPixels) throw()
  64728. {
  64729. y -= bounds.getY();
  64730. if (y < 0 || y >= bounds.getHeight())
  64731. return;
  64732. needToCheckEmptinesss = true;
  64733. if (numPixels <= 0)
  64734. {
  64735. table [lineStrideElements * y] = 0;
  64736. return;
  64737. }
  64738. int* tempLine = (int*) alloca ((numPixels * 2 + 4) * sizeof (int));
  64739. int destIndex = 0, lastLevel = 0;
  64740. while (--numPixels >= 0)
  64741. {
  64742. const int alpha = *mask;
  64743. mask += maskStride;
  64744. if (alpha != lastLevel)
  64745. {
  64746. tempLine[++destIndex] = (x << 8);
  64747. tempLine[++destIndex] = alpha;
  64748. lastLevel = alpha;
  64749. }
  64750. ++x;
  64751. }
  64752. if (lastLevel > 0)
  64753. {
  64754. tempLine[++destIndex] = (x << 8);
  64755. tempLine[++destIndex] = 0;
  64756. }
  64757. tempLine[0] = destIndex >> 1;
  64758. intersectWithEdgeTableLine (y, tempLine);
  64759. }
  64760. bool EdgeTable::isEmpty() throw()
  64761. {
  64762. if (needToCheckEmptinesss)
  64763. {
  64764. needToCheckEmptinesss = false;
  64765. int* t = table;
  64766. for (int i = bounds.getHeight(); --i >= 0;)
  64767. {
  64768. if (t[0] > 1)
  64769. return false;
  64770. t += lineStrideElements;
  64771. }
  64772. bounds.setHeight (0);
  64773. }
  64774. return bounds.getHeight() == 0;
  64775. }
  64776. END_JUCE_NAMESPACE
  64777. /*** End of inlined file: juce_EdgeTable.cpp ***/
  64778. /*** Start of inlined file: juce_FillType.cpp ***/
  64779. BEGIN_JUCE_NAMESPACE
  64780. FillType::FillType() throw()
  64781. : colour (0xff000000), image (0)
  64782. {
  64783. }
  64784. FillType::FillType (const Colour& colour_) throw()
  64785. : colour (colour_), image (0)
  64786. {
  64787. }
  64788. FillType::FillType (const ColourGradient& gradient_)
  64789. : colour (0xff000000), gradient (new ColourGradient (gradient_)), image (0)
  64790. {
  64791. }
  64792. FillType::FillType (const Image& image_, const AffineTransform& transform_) throw()
  64793. : colour (0xff000000), image (image_), transform (transform_)
  64794. {
  64795. }
  64796. FillType::FillType (const FillType& other)
  64797. : colour (other.colour),
  64798. gradient (other.gradient != 0 ? new ColourGradient (*other.gradient) : 0),
  64799. image (other.image), transform (other.transform)
  64800. {
  64801. }
  64802. FillType& FillType::operator= (const FillType& other)
  64803. {
  64804. if (this != &other)
  64805. {
  64806. colour = other.colour;
  64807. gradient = (other.gradient != 0 ? new ColourGradient (*other.gradient) : 0);
  64808. image = other.image;
  64809. transform = other.transform;
  64810. }
  64811. return *this;
  64812. }
  64813. FillType::~FillType() throw()
  64814. {
  64815. }
  64816. bool FillType::operator== (const FillType& other) const
  64817. {
  64818. return colour == other.colour && image == other.image
  64819. && (gradient == other.gradient
  64820. || (gradient != 0 && other.gradient != 0 && *gradient == *other.gradient));
  64821. }
  64822. bool FillType::operator!= (const FillType& other) const
  64823. {
  64824. return ! operator== (other);
  64825. }
  64826. void FillType::setColour (const Colour& newColour) throw()
  64827. {
  64828. gradient = 0;
  64829. image = Image();
  64830. colour = newColour;
  64831. }
  64832. void FillType::setGradient (const ColourGradient& newGradient)
  64833. {
  64834. if (gradient != 0)
  64835. {
  64836. *gradient = newGradient;
  64837. }
  64838. else
  64839. {
  64840. image = Image();
  64841. gradient = new ColourGradient (newGradient);
  64842. colour = Colours::black;
  64843. }
  64844. }
  64845. void FillType::setTiledImage (const Image& image_, const AffineTransform& transform_) throw()
  64846. {
  64847. gradient = 0;
  64848. image = image_;
  64849. transform = transform_;
  64850. colour = Colours::black;
  64851. }
  64852. void FillType::setOpacity (const float newOpacity) throw()
  64853. {
  64854. colour = colour.withAlpha (newOpacity);
  64855. }
  64856. bool FillType::isInvisible() const throw()
  64857. {
  64858. return colour.isTransparent() || (gradient != 0 && gradient->isInvisible());
  64859. }
  64860. END_JUCE_NAMESPACE
  64861. /*** End of inlined file: juce_FillType.cpp ***/
  64862. /*** Start of inlined file: juce_Graphics.cpp ***/
  64863. BEGIN_JUCE_NAMESPACE
  64864. static const Graphics::ResamplingQuality defaultQuality = Graphics::mediumResamplingQuality;
  64865. template <typename Type>
  64866. static bool areCoordsSensibleNumbers (Type x, Type y, Type w, Type h)
  64867. {
  64868. const int maxVal = 0x3fffffff;
  64869. return (int) x >= -maxVal && (int) x <= maxVal
  64870. && (int) y >= -maxVal && (int) y <= maxVal
  64871. && (int) w >= -maxVal && (int) w <= maxVal
  64872. && (int) h >= -maxVal && (int) h <= maxVal;
  64873. }
  64874. LowLevelGraphicsContext::LowLevelGraphicsContext()
  64875. {
  64876. }
  64877. LowLevelGraphicsContext::~LowLevelGraphicsContext()
  64878. {
  64879. }
  64880. Graphics::Graphics (const Image& imageToDrawOnto)
  64881. : context (imageToDrawOnto.createLowLevelContext()),
  64882. contextToDelete (context),
  64883. saveStatePending (false)
  64884. {
  64885. }
  64886. Graphics::Graphics (LowLevelGraphicsContext* const internalContext) throw()
  64887. : context (internalContext),
  64888. saveStatePending (false)
  64889. {
  64890. }
  64891. Graphics::~Graphics()
  64892. {
  64893. }
  64894. void Graphics::resetToDefaultState()
  64895. {
  64896. saveStateIfPending();
  64897. context->setFill (FillType());
  64898. context->setFont (Font());
  64899. context->setInterpolationQuality (defaultQuality);
  64900. }
  64901. bool Graphics::isVectorDevice() const
  64902. {
  64903. return context->isVectorDevice();
  64904. }
  64905. bool Graphics::reduceClipRegion (const int x, const int y, const int w, const int h)
  64906. {
  64907. saveStateIfPending();
  64908. return context->clipToRectangle (Rectangle<int> (x, y, w, h));
  64909. }
  64910. bool Graphics::reduceClipRegion (const RectangleList& clipRegion)
  64911. {
  64912. saveStateIfPending();
  64913. return context->clipToRectangleList (clipRegion);
  64914. }
  64915. bool Graphics::reduceClipRegion (const Path& path, const AffineTransform& transform)
  64916. {
  64917. saveStateIfPending();
  64918. context->clipToPath (path, transform);
  64919. return ! context->isClipEmpty();
  64920. }
  64921. bool Graphics::reduceClipRegion (const Image& image, const Rectangle<int>& sourceClipRegion, const AffineTransform& transform)
  64922. {
  64923. saveStateIfPending();
  64924. context->clipToImageAlpha (image, sourceClipRegion, transform);
  64925. return ! context->isClipEmpty();
  64926. }
  64927. void Graphics::excludeClipRegion (const Rectangle<int>& rectangleToExclude)
  64928. {
  64929. saveStateIfPending();
  64930. context->excludeClipRectangle (rectangleToExclude);
  64931. }
  64932. bool Graphics::isClipEmpty() const
  64933. {
  64934. return context->isClipEmpty();
  64935. }
  64936. const Rectangle<int> Graphics::getClipBounds() const
  64937. {
  64938. return context->getClipBounds();
  64939. }
  64940. void Graphics::saveState()
  64941. {
  64942. saveStateIfPending();
  64943. saveStatePending = true;
  64944. }
  64945. void Graphics::restoreState()
  64946. {
  64947. if (saveStatePending)
  64948. saveStatePending = false;
  64949. else
  64950. context->restoreState();
  64951. }
  64952. void Graphics::saveStateIfPending()
  64953. {
  64954. if (saveStatePending)
  64955. {
  64956. saveStatePending = false;
  64957. context->saveState();
  64958. }
  64959. }
  64960. void Graphics::setOrigin (const int newOriginX, const int newOriginY)
  64961. {
  64962. saveStateIfPending();
  64963. context->setOrigin (newOriginX, newOriginY);
  64964. }
  64965. bool Graphics::clipRegionIntersects (const Rectangle<int>& area) const
  64966. {
  64967. return context->clipRegionIntersects (area);
  64968. }
  64969. void Graphics::setColour (const Colour& newColour)
  64970. {
  64971. saveStateIfPending();
  64972. context->setFill (newColour);
  64973. }
  64974. void Graphics::setOpacity (const float newOpacity)
  64975. {
  64976. saveStateIfPending();
  64977. context->setOpacity (newOpacity);
  64978. }
  64979. void Graphics::setGradientFill (const ColourGradient& gradient)
  64980. {
  64981. setFillType (gradient);
  64982. }
  64983. void Graphics::setTiledImageFill (const Image& imageToUse, const int anchorX, const int anchorY, const float opacity)
  64984. {
  64985. saveStateIfPending();
  64986. context->setFill (FillType (imageToUse, AffineTransform::translation ((float) anchorX, (float) anchorY)));
  64987. context->setOpacity (opacity);
  64988. }
  64989. void Graphics::setFillType (const FillType& newFill)
  64990. {
  64991. saveStateIfPending();
  64992. context->setFill (newFill);
  64993. }
  64994. void Graphics::setFont (const Font& newFont)
  64995. {
  64996. saveStateIfPending();
  64997. context->setFont (newFont);
  64998. }
  64999. void Graphics::setFont (const float newFontHeight, const int newFontStyleFlags)
  65000. {
  65001. saveStateIfPending();
  65002. Font f (context->getFont());
  65003. f.setSizeAndStyle (newFontHeight, newFontStyleFlags, 1.0f, 0);
  65004. context->setFont (f);
  65005. }
  65006. const Font Graphics::getCurrentFont() const
  65007. {
  65008. return context->getFont();
  65009. }
  65010. void Graphics::drawSingleLineText (const String& text, const int startX, const int baselineY) const
  65011. {
  65012. if (text.isNotEmpty()
  65013. && startX < context->getClipBounds().getRight())
  65014. {
  65015. GlyphArrangement arr;
  65016. arr.addLineOfText (context->getFont(), text, (float) startX, (float) baselineY);
  65017. arr.draw (*this);
  65018. }
  65019. }
  65020. void Graphics::drawTextAsPath (const String& text, const AffineTransform& transform) const
  65021. {
  65022. if (text.isNotEmpty())
  65023. {
  65024. GlyphArrangement arr;
  65025. arr.addLineOfText (context->getFont(), text, 0.0f, 0.0f);
  65026. arr.draw (*this, transform);
  65027. }
  65028. }
  65029. void Graphics::drawMultiLineText (const String& text, const int startX, const int baselineY, const int maximumLineWidth) const
  65030. {
  65031. if (text.isNotEmpty()
  65032. && startX < context->getClipBounds().getRight())
  65033. {
  65034. GlyphArrangement arr;
  65035. arr.addJustifiedText (context->getFont(), text,
  65036. (float) startX, (float) baselineY, (float) maximumLineWidth,
  65037. Justification::left);
  65038. arr.draw (*this);
  65039. }
  65040. }
  65041. void Graphics::drawText (const String& text,
  65042. const int x, const int y, const int width, const int height,
  65043. const Justification& justificationType,
  65044. const bool useEllipsesIfTooBig) const
  65045. {
  65046. if (text.isNotEmpty() && context->clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  65047. {
  65048. GlyphArrangement arr;
  65049. arr.addCurtailedLineOfText (context->getFont(), text,
  65050. 0.0f, 0.0f, (float) width,
  65051. useEllipsesIfTooBig);
  65052. arr.justifyGlyphs (0, arr.getNumGlyphs(),
  65053. (float) x, (float) y, (float) width, (float) height,
  65054. justificationType);
  65055. arr.draw (*this);
  65056. }
  65057. }
  65058. void Graphics::drawFittedText (const String& text,
  65059. const int x, const int y, const int width, const int height,
  65060. const Justification& justification,
  65061. const int maximumNumberOfLines,
  65062. const float minimumHorizontalScale) const
  65063. {
  65064. if (text.isNotEmpty()
  65065. && width > 0 && height > 0
  65066. && context->clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  65067. {
  65068. GlyphArrangement arr;
  65069. arr.addFittedText (context->getFont(), text,
  65070. (float) x, (float) y, (float) width, (float) height,
  65071. justification,
  65072. maximumNumberOfLines,
  65073. minimumHorizontalScale);
  65074. arr.draw (*this);
  65075. }
  65076. }
  65077. void Graphics::fillRect (int x, int y, int width, int height) const
  65078. {
  65079. // passing in a silly number can cause maths problems in rendering!
  65080. jassert (areCoordsSensibleNumbers (x, y, width, height));
  65081. context->fillRect (Rectangle<int> (x, y, width, height), false);
  65082. }
  65083. void Graphics::fillRect (const Rectangle<int>& r) const
  65084. {
  65085. context->fillRect (r, false);
  65086. }
  65087. void Graphics::fillRect (const float x, const float y, const float width, const float height) const
  65088. {
  65089. // passing in a silly number can cause maths problems in rendering!
  65090. jassert (areCoordsSensibleNumbers (x, y, width, height));
  65091. Path p;
  65092. p.addRectangle (x, y, width, height);
  65093. fillPath (p);
  65094. }
  65095. void Graphics::setPixel (int x, int y) const
  65096. {
  65097. context->fillRect (Rectangle<int> (x, y, 1, 1), false);
  65098. }
  65099. void Graphics::fillAll() const
  65100. {
  65101. fillRect (context->getClipBounds());
  65102. }
  65103. void Graphics::fillAll (const Colour& colourToUse) const
  65104. {
  65105. if (! colourToUse.isTransparent())
  65106. {
  65107. const Rectangle<int> clip (context->getClipBounds());
  65108. context->saveState();
  65109. context->setFill (colourToUse);
  65110. context->fillRect (clip, false);
  65111. context->restoreState();
  65112. }
  65113. }
  65114. void Graphics::fillPath (const Path& path, const AffineTransform& transform) const
  65115. {
  65116. if ((! context->isClipEmpty()) && ! path.isEmpty())
  65117. context->fillPath (path, transform);
  65118. }
  65119. void Graphics::strokePath (const Path& path,
  65120. const PathStrokeType& strokeType,
  65121. const AffineTransform& transform) const
  65122. {
  65123. Path stroke;
  65124. strokeType.createStrokedPath (stroke, path, transform);
  65125. fillPath (stroke);
  65126. }
  65127. void Graphics::drawRect (const int x, const int y, const int width, const int height,
  65128. const int lineThickness) const
  65129. {
  65130. // passing in a silly number can cause maths problems in rendering!
  65131. jassert (areCoordsSensibleNumbers (x, y, width, height));
  65132. context->fillRect (Rectangle<int> (x, y, width, lineThickness), false);
  65133. context->fillRect (Rectangle<int> (x, y + lineThickness, lineThickness, height - lineThickness * 2), false);
  65134. context->fillRect (Rectangle<int> (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2), false);
  65135. context->fillRect (Rectangle<int> (x, y + height - lineThickness, width, lineThickness), false);
  65136. }
  65137. void Graphics::drawRect (const float x, const float y, const float width, const float height, const float lineThickness) const
  65138. {
  65139. // passing in a silly number can cause maths problems in rendering!
  65140. jassert (areCoordsSensibleNumbers (x, y, width, height));
  65141. Path p;
  65142. p.addRectangle (x, y, width, lineThickness);
  65143. p.addRectangle (x, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  65144. p.addRectangle (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  65145. p.addRectangle (x, y + height - lineThickness, width, lineThickness);
  65146. fillPath (p);
  65147. }
  65148. void Graphics::drawRect (const Rectangle<int>& r, const int lineThickness) const
  65149. {
  65150. drawRect (r.getX(), r.getY(), r.getWidth(), r.getHeight(), lineThickness);
  65151. }
  65152. void Graphics::drawBevel (const int x, const int y, const int width, const int height,
  65153. const int bevelThickness, const Colour& topLeftColour, const Colour& bottomRightColour,
  65154. const bool useGradient, const bool sharpEdgeOnOutside) const
  65155. {
  65156. // passing in a silly number can cause maths problems in rendering!
  65157. jassert (areCoordsSensibleNumbers (x, y, width, height));
  65158. if (clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  65159. {
  65160. context->saveState();
  65161. const float oldOpacity = 1.0f;//xxx state->colour.getFloatAlpha();
  65162. const float ramp = oldOpacity / bevelThickness;
  65163. for (int i = bevelThickness; --i >= 0;)
  65164. {
  65165. const float op = useGradient ? ramp * (sharpEdgeOnOutside ? bevelThickness - i : i)
  65166. : oldOpacity;
  65167. context->setFill (topLeftColour.withMultipliedAlpha (op));
  65168. context->fillRect (Rectangle<int> (x + i, y + i, width - i * 2, 1), false);
  65169. context->setFill (topLeftColour.withMultipliedAlpha (op * 0.75f));
  65170. context->fillRect (Rectangle<int> (x + i, y + i + 1, 1, height - i * 2 - 2), false);
  65171. context->setFill (bottomRightColour.withMultipliedAlpha (op));
  65172. context->fillRect (Rectangle<int> (x + i, y + height - i - 1, width - i * 2, 1), false);
  65173. context->setFill (bottomRightColour.withMultipliedAlpha (op * 0.75f));
  65174. context->fillRect (Rectangle<int> (x + width - i - 1, y + i + 1, 1, height - i * 2 - 2), false);
  65175. }
  65176. context->restoreState();
  65177. }
  65178. }
  65179. void Graphics::fillEllipse (const float x, const float y, const float width, const float height) const
  65180. {
  65181. // passing in a silly number can cause maths problems in rendering!
  65182. jassert (areCoordsSensibleNumbers (x, y, width, height));
  65183. Path p;
  65184. p.addEllipse (x, y, width, height);
  65185. fillPath (p);
  65186. }
  65187. void Graphics::drawEllipse (const float x, const float y, const float width, const float height,
  65188. const float lineThickness) const
  65189. {
  65190. // passing in a silly number can cause maths problems in rendering!
  65191. jassert (areCoordsSensibleNumbers (x, y, width, height));
  65192. Path p;
  65193. p.addEllipse (x, y, width, height);
  65194. strokePath (p, PathStrokeType (lineThickness));
  65195. }
  65196. void Graphics::fillRoundedRectangle (const float x, const float y, const float width, const float height, const float cornerSize) const
  65197. {
  65198. // passing in a silly number can cause maths problems in rendering!
  65199. jassert (areCoordsSensibleNumbers (x, y, width, height));
  65200. Path p;
  65201. p.addRoundedRectangle (x, y, width, height, cornerSize);
  65202. fillPath (p);
  65203. }
  65204. void Graphics::fillRoundedRectangle (const Rectangle<float>& r, const float cornerSize) const
  65205. {
  65206. fillRoundedRectangle (r.getX(), r.getY(), r.getWidth(), r.getHeight(), cornerSize);
  65207. }
  65208. void Graphics::drawRoundedRectangle (const float x, const float y, const float width, const float height,
  65209. const float cornerSize, const float lineThickness) const
  65210. {
  65211. // passing in a silly number can cause maths problems in rendering!
  65212. jassert (areCoordsSensibleNumbers (x, y, width, height));
  65213. Path p;
  65214. p.addRoundedRectangle (x, y, width, height, cornerSize);
  65215. strokePath (p, PathStrokeType (lineThickness));
  65216. }
  65217. void Graphics::drawRoundedRectangle (const Rectangle<float>& r, const float cornerSize, const float lineThickness) const
  65218. {
  65219. drawRoundedRectangle (r.getX(), r.getY(), r.getWidth(), r.getHeight(), cornerSize, lineThickness);
  65220. }
  65221. void Graphics::drawArrow (const Line<float>& line, const float lineThickness, const float arrowheadWidth, const float arrowheadLength) const
  65222. {
  65223. Path p;
  65224. p.addArrow (line, lineThickness, arrowheadWidth, arrowheadLength);
  65225. fillPath (p);
  65226. }
  65227. void Graphics::fillCheckerBoard (int x, int y, int width, int height,
  65228. const int checkWidth, const int checkHeight,
  65229. const Colour& colour1, const Colour& colour2) const
  65230. {
  65231. jassert (checkWidth > 0 && checkHeight > 0); // can't be zero or less!
  65232. if (checkWidth > 0 && checkHeight > 0)
  65233. {
  65234. context->saveState();
  65235. if (colour1 == colour2)
  65236. {
  65237. context->setFill (colour1);
  65238. context->fillRect (Rectangle<int> (x, y, width, height), false);
  65239. }
  65240. else
  65241. {
  65242. const Rectangle<int> clip (context->getClipBounds());
  65243. const int right = jmin (x + width, clip.getRight());
  65244. const int bottom = jmin (y + height, clip.getBottom());
  65245. int cy = 0;
  65246. while (y < bottom)
  65247. {
  65248. int cx = cy;
  65249. for (int xx = x; xx < right; xx += checkWidth)
  65250. {
  65251. context->setFill (((cx++ & 1) == 0) ? colour1 : colour2);
  65252. context->fillRect (Rectangle<int> (xx, y, jmin (checkWidth, right - xx), jmin (checkHeight, bottom - y)),
  65253. false);
  65254. }
  65255. ++cy;
  65256. y += checkHeight;
  65257. }
  65258. }
  65259. context->restoreState();
  65260. }
  65261. }
  65262. void Graphics::drawVerticalLine (const int x, float top, float bottom) const
  65263. {
  65264. context->drawVerticalLine (x, top, bottom);
  65265. }
  65266. void Graphics::drawHorizontalLine (const int y, float left, float right) const
  65267. {
  65268. context->drawHorizontalLine (y, left, right);
  65269. }
  65270. void Graphics::drawLine (float x1, float y1, float x2, float y2) const
  65271. {
  65272. context->drawLine (Line<float> (x1, y1, x2, y2));
  65273. }
  65274. void Graphics::drawLine (const float startX, const float startY,
  65275. const float endX, const float endY,
  65276. const float lineThickness) const
  65277. {
  65278. drawLine (Line<float> (startX, startY, endX, endY),lineThickness);
  65279. }
  65280. void Graphics::drawLine (const Line<float>& line) const
  65281. {
  65282. drawLine (line.getStartX(), line.getStartY(), line.getEndX(), line.getEndY());
  65283. }
  65284. void Graphics::drawLine (const Line<float>& line, const float lineThickness) const
  65285. {
  65286. Path p;
  65287. p.addLineSegment (line, lineThickness);
  65288. fillPath (p);
  65289. }
  65290. void Graphics::drawDashedLine (const float startX, const float startY,
  65291. const float endX, const float endY,
  65292. const float* const dashLengths,
  65293. const int numDashLengths,
  65294. const float lineThickness) const
  65295. {
  65296. const double dx = endX - startX;
  65297. const double dy = endY - startY;
  65298. const double totalLen = juce_hypot (dx, dy);
  65299. if (totalLen >= 0.5)
  65300. {
  65301. const double onePixAlpha = 1.0 / totalLen;
  65302. double alpha = 0.0;
  65303. float x = startX;
  65304. float y = startY;
  65305. int n = 0;
  65306. while (alpha < 1.0f)
  65307. {
  65308. alpha = jmin (1.0, alpha + dashLengths[n++] * onePixAlpha);
  65309. n = n % numDashLengths;
  65310. const float oldX = x;
  65311. const float oldY = y;
  65312. x = (float) (startX + dx * alpha);
  65313. y = (float) (startY + dy * alpha);
  65314. if ((n & 1) != 0)
  65315. {
  65316. if (lineThickness != 1.0f)
  65317. drawLine (oldX, oldY, x, y, lineThickness);
  65318. else
  65319. drawLine (oldX, oldY, x, y);
  65320. }
  65321. }
  65322. }
  65323. }
  65324. void Graphics::setImageResamplingQuality (const Graphics::ResamplingQuality newQuality)
  65325. {
  65326. saveStateIfPending();
  65327. context->setInterpolationQuality (newQuality);
  65328. }
  65329. void Graphics::drawImageAt (const Image& imageToDraw,
  65330. const int topLeftX, const int topLeftY,
  65331. const bool fillAlphaChannelWithCurrentBrush) const
  65332. {
  65333. const int imageW = imageToDraw.getWidth();
  65334. const int imageH = imageToDraw.getHeight();
  65335. drawImage (imageToDraw,
  65336. topLeftX, topLeftY, imageW, imageH,
  65337. 0, 0, imageW, imageH,
  65338. fillAlphaChannelWithCurrentBrush);
  65339. }
  65340. void Graphics::drawImageWithin (const Image& imageToDraw,
  65341. const int destX, const int destY,
  65342. const int destW, const int destH,
  65343. const RectanglePlacement& placementWithinTarget,
  65344. const bool fillAlphaChannelWithCurrentBrush) const
  65345. {
  65346. // passing in a silly number can cause maths problems in rendering!
  65347. jassert (areCoordsSensibleNumbers (destX, destY, destW, destH));
  65348. if (imageToDraw.isValid())
  65349. {
  65350. const int imageW = imageToDraw.getWidth();
  65351. const int imageH = imageToDraw.getHeight();
  65352. if (imageW > 0 && imageH > 0)
  65353. {
  65354. double newX = 0.0, newY = 0.0;
  65355. double newW = imageW;
  65356. double newH = imageH;
  65357. placementWithinTarget.applyTo (newX, newY, newW, newH,
  65358. destX, destY, destW, destH);
  65359. if (newW > 0 && newH > 0)
  65360. {
  65361. drawImage (imageToDraw,
  65362. roundToInt (newX), roundToInt (newY),
  65363. roundToInt (newW), roundToInt (newH),
  65364. 0, 0, imageW, imageH,
  65365. fillAlphaChannelWithCurrentBrush);
  65366. }
  65367. }
  65368. }
  65369. }
  65370. void Graphics::drawImage (const Image& imageToDraw,
  65371. int dx, int dy, int dw, int dh,
  65372. int sx, int sy, int sw, int sh,
  65373. const bool fillAlphaChannelWithCurrentBrush) const
  65374. {
  65375. // passing in a silly number can cause maths problems in rendering!
  65376. jassert (areCoordsSensibleNumbers (dx, dy, dw, dh));
  65377. jassert (areCoordsSensibleNumbers (sx, sy, sw, sh));
  65378. if (imageToDraw.isValid() && context->clipRegionIntersects (Rectangle<int> (dx, dy, dw, dh)))
  65379. {
  65380. drawImageTransformed (imageToDraw, Rectangle<int> (sx, sy, sw, sh),
  65381. AffineTransform::scale (dw / (float) sw, dh / (float) sh)
  65382. .translated ((float) dx, (float) dy),
  65383. fillAlphaChannelWithCurrentBrush);
  65384. }
  65385. }
  65386. void Graphics::drawImageTransformed (const Image& imageToDraw,
  65387. const Rectangle<int>& imageSubRegion,
  65388. const AffineTransform& transform,
  65389. const bool fillAlphaChannelWithCurrentBrush) const
  65390. {
  65391. if (imageToDraw.isValid() && ! context->isClipEmpty())
  65392. {
  65393. const Rectangle<int> srcClip (imageSubRegion.getIntersection (imageToDraw.getBounds()));
  65394. if (fillAlphaChannelWithCurrentBrush)
  65395. {
  65396. context->saveState();
  65397. context->clipToImageAlpha (imageToDraw, srcClip, transform);
  65398. fillAll();
  65399. context->restoreState();
  65400. }
  65401. else
  65402. {
  65403. context->drawImage (imageToDraw, srcClip, transform, false);
  65404. }
  65405. }
  65406. }
  65407. END_JUCE_NAMESPACE
  65408. /*** End of inlined file: juce_Graphics.cpp ***/
  65409. /*** Start of inlined file: juce_Justification.cpp ***/
  65410. BEGIN_JUCE_NAMESPACE
  65411. Justification::Justification (const Justification& other) throw()
  65412. : flags (other.flags)
  65413. {
  65414. }
  65415. Justification& Justification::operator= (const Justification& other) throw()
  65416. {
  65417. flags = other.flags;
  65418. return *this;
  65419. }
  65420. int Justification::getOnlyVerticalFlags() const throw()
  65421. {
  65422. return flags & (top | bottom | verticallyCentred);
  65423. }
  65424. int Justification::getOnlyHorizontalFlags() const throw()
  65425. {
  65426. return flags & (left | right | horizontallyCentred | horizontallyJustified);
  65427. }
  65428. void Justification::applyToRectangle (int& x, int& y,
  65429. const int w, const int h,
  65430. const int spaceX, const int spaceY,
  65431. const int spaceW, const int spaceH) const throw()
  65432. {
  65433. if ((flags & horizontallyCentred) != 0)
  65434. x = spaceX + ((spaceW - w) >> 1);
  65435. else if ((flags & right) != 0)
  65436. x = spaceX + spaceW - w;
  65437. else
  65438. x = spaceX;
  65439. if ((flags & verticallyCentred) != 0)
  65440. y = spaceY + ((spaceH - h) >> 1);
  65441. else if ((flags & bottom) != 0)
  65442. y = spaceY + spaceH - h;
  65443. else
  65444. y = spaceY;
  65445. }
  65446. END_JUCE_NAMESPACE
  65447. /*** End of inlined file: juce_Justification.cpp ***/
  65448. /*** Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp ***/
  65449. BEGIN_JUCE_NAMESPACE
  65450. // this will throw an assertion if you try to draw something that's not
  65451. // possible in postscript
  65452. #define WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS 0
  65453. #if JUCE_DEBUG && WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS
  65454. #define notPossibleInPostscriptAssert jassertfalse
  65455. #else
  65456. #define notPossibleInPostscriptAssert
  65457. #endif
  65458. LowLevelGraphicsPostScriptRenderer::LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  65459. const String& documentTitle,
  65460. const int totalWidth_,
  65461. const int totalHeight_)
  65462. : out (resultingPostScript),
  65463. totalWidth (totalWidth_),
  65464. totalHeight (totalHeight_),
  65465. needToClip (true)
  65466. {
  65467. stateStack.add (new SavedState());
  65468. stateStack.getLast()->clip = Rectangle<int> (0, 0, totalWidth_, totalHeight_);
  65469. const float scale = jmin ((520.0f / totalWidth_), (750.0f / totalHeight));
  65470. out << "%!PS-Adobe-3.0 EPSF-3.0"
  65471. "\n%%BoundingBox: 0 0 600 824"
  65472. "\n%%Pages: 0"
  65473. "\n%%Creator: Raw Material Software JUCE"
  65474. "\n%%Title: " << documentTitle <<
  65475. "\n%%CreationDate: none"
  65476. "\n%%LanguageLevel: 2"
  65477. "\n%%EndComments"
  65478. "\n%%BeginProlog"
  65479. "\n%%BeginResource: JRes"
  65480. "\n/bd {bind def} bind def"
  65481. "\n/c {setrgbcolor} bd"
  65482. "\n/m {moveto} bd"
  65483. "\n/l {lineto} bd"
  65484. "\n/rl {rlineto} bd"
  65485. "\n/ct {curveto} bd"
  65486. "\n/cp {closepath} bd"
  65487. "\n/pr {3 index 3 index moveto 1 index 0 rlineto 0 1 index rlineto pop neg 0 rlineto pop pop closepath} bd"
  65488. "\n/doclip {initclip newpath} bd"
  65489. "\n/endclip {clip newpath} bd"
  65490. "\n%%EndResource"
  65491. "\n%%EndProlog"
  65492. "\n%%BeginSetup"
  65493. "\n%%EndSetup"
  65494. "\n%%Page: 1 1"
  65495. "\n%%BeginPageSetup"
  65496. "\n%%EndPageSetup\n\n"
  65497. << "40 800 translate\n"
  65498. << scale << ' ' << scale << " scale\n\n";
  65499. }
  65500. LowLevelGraphicsPostScriptRenderer::~LowLevelGraphicsPostScriptRenderer()
  65501. {
  65502. }
  65503. bool LowLevelGraphicsPostScriptRenderer::isVectorDevice() const
  65504. {
  65505. return true;
  65506. }
  65507. void LowLevelGraphicsPostScriptRenderer::setOrigin (int x, int y)
  65508. {
  65509. if (x != 0 || y != 0)
  65510. {
  65511. stateStack.getLast()->xOffset += x;
  65512. stateStack.getLast()->yOffset += y;
  65513. needToClip = true;
  65514. }
  65515. }
  65516. bool LowLevelGraphicsPostScriptRenderer::clipToRectangle (const Rectangle<int>& r)
  65517. {
  65518. needToClip = true;
  65519. return stateStack.getLast()->clip.clipTo (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  65520. }
  65521. bool LowLevelGraphicsPostScriptRenderer::clipToRectangleList (const RectangleList& clipRegion)
  65522. {
  65523. needToClip = true;
  65524. return stateStack.getLast()->clip.clipTo (clipRegion);
  65525. }
  65526. void LowLevelGraphicsPostScriptRenderer::excludeClipRectangle (const Rectangle<int>& r)
  65527. {
  65528. needToClip = true;
  65529. stateStack.getLast()->clip.subtract (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  65530. }
  65531. void LowLevelGraphicsPostScriptRenderer::clipToPath (const Path& path, const AffineTransform& transform)
  65532. {
  65533. writeClip();
  65534. Path p (path);
  65535. p.applyTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset));
  65536. writePath (p);
  65537. out << "clip\n";
  65538. }
  65539. void LowLevelGraphicsPostScriptRenderer::clipToImageAlpha (const Image& /*sourceImage*/, const Rectangle<int>& /*srcClip*/, const AffineTransform& /*transform*/)
  65540. {
  65541. needToClip = true;
  65542. jassertfalse; // xxx
  65543. }
  65544. bool LowLevelGraphicsPostScriptRenderer::clipRegionIntersects (const Rectangle<int>& r)
  65545. {
  65546. return stateStack.getLast()->clip.intersectsRectangle (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  65547. }
  65548. const Rectangle<int> LowLevelGraphicsPostScriptRenderer::getClipBounds() const
  65549. {
  65550. return stateStack.getLast()->clip.getBounds().translated (-stateStack.getLast()->xOffset,
  65551. -stateStack.getLast()->yOffset);
  65552. }
  65553. bool LowLevelGraphicsPostScriptRenderer::isClipEmpty() const
  65554. {
  65555. return stateStack.getLast()->clip.isEmpty();
  65556. }
  65557. LowLevelGraphicsPostScriptRenderer::SavedState::SavedState()
  65558. : xOffset (0),
  65559. yOffset (0)
  65560. {
  65561. }
  65562. LowLevelGraphicsPostScriptRenderer::SavedState::~SavedState()
  65563. {
  65564. }
  65565. void LowLevelGraphicsPostScriptRenderer::saveState()
  65566. {
  65567. stateStack.add (new SavedState (*stateStack.getLast()));
  65568. }
  65569. void LowLevelGraphicsPostScriptRenderer::restoreState()
  65570. {
  65571. jassert (stateStack.size() > 0);
  65572. if (stateStack.size() > 0)
  65573. stateStack.removeLast();
  65574. }
  65575. void LowLevelGraphicsPostScriptRenderer::writeClip()
  65576. {
  65577. if (needToClip)
  65578. {
  65579. needToClip = false;
  65580. out << "doclip ";
  65581. int itemsOnLine = 0;
  65582. for (RectangleList::Iterator i (stateStack.getLast()->clip); i.next();)
  65583. {
  65584. if (++itemsOnLine == 6)
  65585. {
  65586. itemsOnLine = 0;
  65587. out << '\n';
  65588. }
  65589. const Rectangle<int>& r = *i.getRectangle();
  65590. out << r.getX() << ' ' << -r.getY() << ' '
  65591. << r.getWidth() << ' ' << -r.getHeight() << " pr ";
  65592. }
  65593. out << "endclip\n";
  65594. }
  65595. }
  65596. void LowLevelGraphicsPostScriptRenderer::writeColour (const Colour& colour)
  65597. {
  65598. Colour c (Colours::white.overlaidWith (colour));
  65599. if (lastColour != c)
  65600. {
  65601. lastColour = c;
  65602. out << String (c.getFloatRed(), 3) << ' '
  65603. << String (c.getFloatGreen(), 3) << ' '
  65604. << String (c.getFloatBlue(), 3) << " c\n";
  65605. }
  65606. }
  65607. void LowLevelGraphicsPostScriptRenderer::writeXY (const float x, const float y) const
  65608. {
  65609. out << String (x, 2) << ' '
  65610. << String (-y, 2) << ' ';
  65611. }
  65612. void LowLevelGraphicsPostScriptRenderer::writePath (const Path& path) const
  65613. {
  65614. out << "newpath ";
  65615. float lastX = 0.0f;
  65616. float lastY = 0.0f;
  65617. int itemsOnLine = 0;
  65618. Path::Iterator i (path);
  65619. while (i.next())
  65620. {
  65621. if (++itemsOnLine == 4)
  65622. {
  65623. itemsOnLine = 0;
  65624. out << '\n';
  65625. }
  65626. switch (i.elementType)
  65627. {
  65628. case Path::Iterator::startNewSubPath:
  65629. writeXY (i.x1, i.y1);
  65630. lastX = i.x1;
  65631. lastY = i.y1;
  65632. out << "m ";
  65633. break;
  65634. case Path::Iterator::lineTo:
  65635. writeXY (i.x1, i.y1);
  65636. lastX = i.x1;
  65637. lastY = i.y1;
  65638. out << "l ";
  65639. break;
  65640. case Path::Iterator::quadraticTo:
  65641. {
  65642. const float cp1x = lastX + (i.x1 - lastX) * 2.0f / 3.0f;
  65643. const float cp1y = lastY + (i.y1 - lastY) * 2.0f / 3.0f;
  65644. const float cp2x = cp1x + (i.x2 - lastX) / 3.0f;
  65645. const float cp2y = cp1y + (i.y2 - lastY) / 3.0f;
  65646. writeXY (cp1x, cp1y);
  65647. writeXY (cp2x, cp2y);
  65648. writeXY (i.x2, i.y2);
  65649. out << "ct ";
  65650. lastX = i.x2;
  65651. lastY = i.y2;
  65652. }
  65653. break;
  65654. case Path::Iterator::cubicTo:
  65655. writeXY (i.x1, i.y1);
  65656. writeXY (i.x2, i.y2);
  65657. writeXY (i.x3, i.y3);
  65658. out << "ct ";
  65659. lastX = i.x3;
  65660. lastY = i.y3;
  65661. break;
  65662. case Path::Iterator::closePath:
  65663. out << "cp ";
  65664. break;
  65665. default:
  65666. jassertfalse;
  65667. break;
  65668. }
  65669. }
  65670. out << '\n';
  65671. }
  65672. void LowLevelGraphicsPostScriptRenderer::writeTransform (const AffineTransform& trans) const
  65673. {
  65674. out << "[ "
  65675. << trans.mat00 << ' '
  65676. << trans.mat10 << ' '
  65677. << trans.mat01 << ' '
  65678. << trans.mat11 << ' '
  65679. << trans.mat02 << ' '
  65680. << trans.mat12 << " ] concat ";
  65681. }
  65682. void LowLevelGraphicsPostScriptRenderer::setFill (const FillType& fillType)
  65683. {
  65684. stateStack.getLast()->fillType = fillType;
  65685. }
  65686. void LowLevelGraphicsPostScriptRenderer::setOpacity (float /*opacity*/)
  65687. {
  65688. }
  65689. void LowLevelGraphicsPostScriptRenderer::setInterpolationQuality (Graphics::ResamplingQuality /*quality*/)
  65690. {
  65691. }
  65692. void LowLevelGraphicsPostScriptRenderer::fillRect (const Rectangle<int>& r, const bool /*replaceExistingContents*/)
  65693. {
  65694. if (stateStack.getLast()->fillType.isColour())
  65695. {
  65696. writeClip();
  65697. writeColour (stateStack.getLast()->fillType.colour);
  65698. Rectangle<int> r2 (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  65699. out << r2.getX() << ' ' << -r2.getBottom() << ' ' << r2.getWidth() << ' ' << r2.getHeight() << " rectfill\n";
  65700. }
  65701. else
  65702. {
  65703. Path p;
  65704. p.addRectangle (r);
  65705. fillPath (p, AffineTransform::identity);
  65706. }
  65707. }
  65708. void LowLevelGraphicsPostScriptRenderer::fillPath (const Path& path, const AffineTransform& t)
  65709. {
  65710. if (stateStack.getLast()->fillType.isColour())
  65711. {
  65712. writeClip();
  65713. Path p (path);
  65714. p.applyTransform (t.translated ((float) stateStack.getLast()->xOffset,
  65715. (float) stateStack.getLast()->yOffset));
  65716. writePath (p);
  65717. writeColour (stateStack.getLast()->fillType.colour);
  65718. out << "fill\n";
  65719. }
  65720. else if (stateStack.getLast()->fillType.isGradient())
  65721. {
  65722. // this doesn't work correctly yet - it could be improved to handle solid gradients, but
  65723. // postscript can't do semi-transparent ones.
  65724. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  65725. writeClip();
  65726. out << "gsave ";
  65727. {
  65728. Path p (path);
  65729. p.applyTransform (t.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset));
  65730. writePath (p);
  65731. out << "clip\n";
  65732. }
  65733. const Rectangle<int> bounds (stateStack.getLast()->clip.getBounds());
  65734. // ideally this would draw lots of lines or ellipses to approximate the gradient, but for the
  65735. // time-being, this just fills it with the average colour..
  65736. writeColour (stateStack.getLast()->fillType.gradient->getColourAtPosition (0.5f));
  65737. out << bounds.getX() << ' ' << -bounds.getBottom() << ' ' << bounds.getWidth() << ' ' << bounds.getHeight() << " rectfill\n";
  65738. out << "grestore\n";
  65739. }
  65740. }
  65741. void LowLevelGraphicsPostScriptRenderer::writeImage (const Image& im,
  65742. const int sx, const int sy,
  65743. const int maxW, const int maxH) const
  65744. {
  65745. out << "{<\n";
  65746. const int w = jmin (maxW, im.getWidth());
  65747. const int h = jmin (maxH, im.getHeight());
  65748. int charsOnLine = 0;
  65749. const Image::BitmapData srcData (im, 0, 0, w, h);
  65750. Colour pixel;
  65751. for (int y = h; --y >= 0;)
  65752. {
  65753. for (int x = 0; x < w; ++x)
  65754. {
  65755. const uint8* pixelData = srcData.getPixelPointer (x, y);
  65756. if (x >= sx && y >= sy)
  65757. {
  65758. if (im.isARGB())
  65759. {
  65760. PixelARGB p (*(const PixelARGB*) pixelData);
  65761. p.unpremultiply();
  65762. pixel = Colours::white.overlaidWith (Colour (p.getARGB()));
  65763. }
  65764. else if (im.isRGB())
  65765. {
  65766. pixel = Colour (((const PixelRGB*) pixelData)->getARGB());
  65767. }
  65768. else
  65769. {
  65770. pixel = Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixelData);
  65771. }
  65772. }
  65773. else
  65774. {
  65775. pixel = Colours::transparentWhite;
  65776. }
  65777. const uint8 pixelValues[3] = { pixel.getRed(), pixel.getGreen(), pixel.getBlue() };
  65778. out << String::toHexString (pixelValues, 3, 0);
  65779. charsOnLine += 3;
  65780. if (charsOnLine > 100)
  65781. {
  65782. out << '\n';
  65783. charsOnLine = 0;
  65784. }
  65785. }
  65786. }
  65787. out << "\n>}\n";
  65788. }
  65789. void LowLevelGraphicsPostScriptRenderer::drawImage (const Image& sourceImage, const Rectangle<int>& srcClip,
  65790. const AffineTransform& transform, const bool /*fillEntireClipAsTiles*/)
  65791. {
  65792. const int w = jmin (sourceImage.getWidth(), srcClip.getRight());
  65793. const int h = jmin (sourceImage.getHeight(), srcClip.getBottom());
  65794. writeClip();
  65795. out << "gsave ";
  65796. writeTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset)
  65797. .scaled (1.0f, -1.0f));
  65798. RectangleList imageClip;
  65799. sourceImage.createSolidAreaMask (imageClip, 0.5f);
  65800. imageClip.clipTo (srcClip);
  65801. out << "newpath ";
  65802. int itemsOnLine = 0;
  65803. for (RectangleList::Iterator i (imageClip); i.next();)
  65804. {
  65805. if (++itemsOnLine == 6)
  65806. {
  65807. out << '\n';
  65808. itemsOnLine = 0;
  65809. }
  65810. const Rectangle<int>& r = *i.getRectangle();
  65811. out << r.getX() << ' ' << r.getY() << ' ' << r.getWidth() << ' ' << r.getHeight() << " pr ";
  65812. }
  65813. out << " clip newpath\n";
  65814. out << w << ' ' << h << " scale\n";
  65815. out << w << ' ' << h << " 8 [" << w << " 0 0 -" << h << ' ' << (int) 0 << ' ' << h << " ]\n";
  65816. writeImage (sourceImage, srcClip.getX(), srcClip.getY(), srcClip.getWidth(), srcClip.getHeight());
  65817. out << "false 3 colorimage grestore\n";
  65818. needToClip = true;
  65819. }
  65820. void LowLevelGraphicsPostScriptRenderer::drawLine (const Line <float>& line)
  65821. {
  65822. Path p;
  65823. p.addLineSegment (line, 1.0f);
  65824. fillPath (p, AffineTransform::identity);
  65825. }
  65826. void LowLevelGraphicsPostScriptRenderer::drawVerticalLine (const int x, float top, float bottom)
  65827. {
  65828. drawLine (Line<float> ((float) x, top, (float) x, bottom));
  65829. }
  65830. void LowLevelGraphicsPostScriptRenderer::drawHorizontalLine (const int y, float left, float right)
  65831. {
  65832. drawLine (Line<float> (left, (float) y, right, (float) y));
  65833. }
  65834. void LowLevelGraphicsPostScriptRenderer::setFont (const Font& newFont)
  65835. {
  65836. stateStack.getLast()->font = newFont;
  65837. }
  65838. const Font LowLevelGraphicsPostScriptRenderer::getFont()
  65839. {
  65840. return stateStack.getLast()->font;
  65841. }
  65842. void LowLevelGraphicsPostScriptRenderer::drawGlyph (int glyphNumber, const AffineTransform& transform)
  65843. {
  65844. Path p;
  65845. Font& font = stateStack.getLast()->font;
  65846. font.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  65847. fillPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight()).followedBy (transform));
  65848. }
  65849. END_JUCE_NAMESPACE
  65850. /*** End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp ***/
  65851. /*** Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp ***/
  65852. BEGIN_JUCE_NAMESPACE
  65853. #if (JUCE_WINDOWS || JUCE_LINUX) && ! JUCE_64BIT
  65854. #define JUCE_USE_SSE_INSTRUCTIONS 1
  65855. #endif
  65856. #if JUCE_MSVC
  65857. #pragma warning (push)
  65858. #pragma warning (disable: 4127) // "expression is constant" warning
  65859. #if JUCE_DEBUG
  65860. #pragma optimize ("t", on) // optimise just this file, to avoid sluggish graphics when debugging
  65861. #pragma warning (disable: 4714) // warning about forcedinline methods not being inlined
  65862. #endif
  65863. #endif
  65864. namespace SoftwareRendererClasses
  65865. {
  65866. template <class PixelType, bool replaceExisting = false>
  65867. class SolidColourEdgeTableRenderer
  65868. {
  65869. public:
  65870. SolidColourEdgeTableRenderer (const Image::BitmapData& data_, const PixelARGB& colour)
  65871. : data (data_),
  65872. sourceColour (colour)
  65873. {
  65874. if (sizeof (PixelType) == 3)
  65875. {
  65876. areRGBComponentsEqual = sourceColour.getRed() == sourceColour.getGreen()
  65877. && sourceColour.getGreen() == sourceColour.getBlue();
  65878. filler[0].set (sourceColour);
  65879. filler[1].set (sourceColour);
  65880. filler[2].set (sourceColour);
  65881. filler[3].set (sourceColour);
  65882. }
  65883. }
  65884. forcedinline void setEdgeTableYPos (const int y) throw()
  65885. {
  65886. linePixels = (PixelType*) data.getLinePointer (y);
  65887. }
  65888. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  65889. {
  65890. if (replaceExisting)
  65891. linePixels[x].set (sourceColour);
  65892. else
  65893. linePixels[x].blend (sourceColour, alphaLevel);
  65894. }
  65895. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  65896. {
  65897. if (replaceExisting)
  65898. linePixels[x].set (sourceColour);
  65899. else
  65900. linePixels[x].blend (sourceColour);
  65901. }
  65902. forcedinline void handleEdgeTableLine (const int x, const int width, const int alphaLevel) const throw()
  65903. {
  65904. PixelARGB p (sourceColour);
  65905. p.multiplyAlpha (alphaLevel);
  65906. PixelType* dest = linePixels + x;
  65907. if (replaceExisting || p.getAlpha() >= 0xff)
  65908. replaceLine (dest, p, width);
  65909. else
  65910. blendLine (dest, p, width);
  65911. }
  65912. forcedinline void handleEdgeTableLineFull (const int x, const int width) const throw()
  65913. {
  65914. PixelType* dest = linePixels + x;
  65915. if (replaceExisting || sourceColour.getAlpha() >= 0xff)
  65916. replaceLine (dest, sourceColour, width);
  65917. else
  65918. blendLine (dest, sourceColour, width);
  65919. }
  65920. private:
  65921. const Image::BitmapData& data;
  65922. PixelType* linePixels;
  65923. PixelARGB sourceColour;
  65924. PixelRGB filler [4];
  65925. bool areRGBComponentsEqual;
  65926. inline void blendLine (PixelType* dest, const PixelARGB& colour, int width) const throw()
  65927. {
  65928. do
  65929. {
  65930. dest->blend (colour);
  65931. ++dest;
  65932. } while (--width > 0);
  65933. }
  65934. forcedinline void replaceLine (PixelRGB* dest, const PixelARGB& colour, int width) const throw()
  65935. {
  65936. if (areRGBComponentsEqual) // if all the component values are the same, we can cheat..
  65937. {
  65938. memset (dest, colour.getRed(), width * 3);
  65939. }
  65940. else
  65941. {
  65942. if (width >> 5)
  65943. {
  65944. const int* const intFiller = (const int*) filler;
  65945. while (width > 8 && (((pointer_sized_int) dest) & 7) != 0)
  65946. {
  65947. dest->set (colour);
  65948. ++dest;
  65949. --width;
  65950. }
  65951. while (width > 4)
  65952. {
  65953. ((int*) dest) [0] = intFiller[0];
  65954. ((int*) dest) [1] = intFiller[1];
  65955. ((int*) dest) [2] = intFiller[2];
  65956. dest = (PixelRGB*) (((uint8*) dest) + 12);
  65957. width -= 4;
  65958. }
  65959. }
  65960. while (--width >= 0)
  65961. {
  65962. dest->set (colour);
  65963. ++dest;
  65964. }
  65965. }
  65966. }
  65967. forcedinline void replaceLine (PixelAlpha* const dest, const PixelARGB& colour, int const width) const throw()
  65968. {
  65969. memset (dest, colour.getAlpha(), width);
  65970. }
  65971. forcedinline void replaceLine (PixelARGB* dest, const PixelARGB& colour, int width) const throw()
  65972. {
  65973. do
  65974. {
  65975. dest->set (colour);
  65976. ++dest;
  65977. } while (--width > 0);
  65978. }
  65979. SolidColourEdgeTableRenderer (const SolidColourEdgeTableRenderer&);
  65980. SolidColourEdgeTableRenderer& operator= (const SolidColourEdgeTableRenderer&);
  65981. };
  65982. class LinearGradientPixelGenerator
  65983. {
  65984. public:
  65985. LinearGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform& transform, const PixelARGB* const lookupTable_, const int numEntries_)
  65986. : lookupTable (lookupTable_), numEntries (numEntries_)
  65987. {
  65988. jassert (numEntries_ >= 0);
  65989. Point<float> p1 (gradient.point1);
  65990. Point<float> p2 (gradient.point2);
  65991. if (! transform.isIdentity())
  65992. {
  65993. const Line<float> l (p2, p1);
  65994. Point<float> p3 = l.getPointAlongLine (0.0f, 100.0f);
  65995. p1.applyTransform (transform);
  65996. p2.applyTransform (transform);
  65997. p3.applyTransform (transform);
  65998. p2 = Line<float> (p2, p3).findNearestPointTo (p1);
  65999. }
  66000. vertical = std::abs (p1.getX() - p2.getX()) < 0.001f;
  66001. horizontal = std::abs (p1.getY() - p2.getY()) < 0.001f;
  66002. if (vertical)
  66003. {
  66004. scale = roundToInt ((numEntries << (int) numScaleBits) / (double) (p2.getY() - p1.getY()));
  66005. start = roundToInt (p1.getY() * scale);
  66006. }
  66007. else if (horizontal)
  66008. {
  66009. scale = roundToInt ((numEntries << (int) numScaleBits) / (double) (p2.getX() - p1.getX()));
  66010. start = roundToInt (p1.getX() * scale);
  66011. }
  66012. else
  66013. {
  66014. grad = (p2.getY() - p1.getY()) / (double) (p1.getX() - p2.getX());
  66015. yTerm = p1.getY() - p1.getX() / grad;
  66016. scale = roundToInt ((numEntries << (int) numScaleBits) / (yTerm * grad - (p2.getY() * grad - p2.getX())));
  66017. grad *= scale;
  66018. }
  66019. }
  66020. forcedinline void setY (const int y) throw()
  66021. {
  66022. if (vertical)
  66023. linePix = lookupTable [jlimit (0, numEntries, (y * scale - start) >> (int) numScaleBits)];
  66024. else if (! horizontal)
  66025. start = roundToInt ((y - yTerm) * grad);
  66026. }
  66027. inline const PixelARGB getPixel (const int x) const throw()
  66028. {
  66029. return vertical ? linePix
  66030. : lookupTable [jlimit (0, numEntries, (x * scale - start) >> (int) numScaleBits)];
  66031. }
  66032. private:
  66033. const PixelARGB* const lookupTable;
  66034. const int numEntries;
  66035. PixelARGB linePix;
  66036. int start, scale;
  66037. double grad, yTerm;
  66038. bool vertical, horizontal;
  66039. enum { numScaleBits = 12 };
  66040. LinearGradientPixelGenerator (const LinearGradientPixelGenerator&);
  66041. LinearGradientPixelGenerator& operator= (const LinearGradientPixelGenerator&);
  66042. };
  66043. class RadialGradientPixelGenerator
  66044. {
  66045. public:
  66046. RadialGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform&,
  66047. const PixelARGB* const lookupTable_, const int numEntries_)
  66048. : lookupTable (lookupTable_),
  66049. numEntries (numEntries_),
  66050. gx1 (gradient.point1.getX()),
  66051. gy1 (gradient.point1.getY())
  66052. {
  66053. jassert (numEntries_ >= 0);
  66054. const Point<float> diff (gradient.point1 - gradient.point2);
  66055. maxDist = diff.getX() * diff.getX() + diff.getY() * diff.getY();
  66056. invScale = numEntries / std::sqrt (maxDist);
  66057. jassert (roundToInt (std::sqrt (maxDist) * invScale) <= numEntries);
  66058. }
  66059. forcedinline void setY (const int y) throw()
  66060. {
  66061. dy = y - gy1;
  66062. dy *= dy;
  66063. }
  66064. inline const PixelARGB getPixel (const int px) const throw()
  66065. {
  66066. double x = px - gx1;
  66067. x *= x;
  66068. x += dy;
  66069. return lookupTable [x >= maxDist ? numEntries : roundToInt (std::sqrt (x) * invScale)];
  66070. }
  66071. protected:
  66072. const PixelARGB* const lookupTable;
  66073. const int numEntries;
  66074. const double gx1, gy1;
  66075. double maxDist, invScale, dy;
  66076. RadialGradientPixelGenerator (const RadialGradientPixelGenerator&);
  66077. RadialGradientPixelGenerator& operator= (const RadialGradientPixelGenerator&);
  66078. };
  66079. class TransformedRadialGradientPixelGenerator : public RadialGradientPixelGenerator
  66080. {
  66081. public:
  66082. TransformedRadialGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform& transform,
  66083. const PixelARGB* const lookupTable_, const int numEntries_)
  66084. : RadialGradientPixelGenerator (gradient, transform, lookupTable_, numEntries_),
  66085. inverseTransform (transform.inverted())
  66086. {
  66087. tM10 = inverseTransform.mat10;
  66088. tM00 = inverseTransform.mat00;
  66089. }
  66090. forcedinline void setY (const int y) throw()
  66091. {
  66092. lineYM01 = inverseTransform.mat01 * y + inverseTransform.mat02 - gx1;
  66093. lineYM11 = inverseTransform.mat11 * y + inverseTransform.mat12 - gy1;
  66094. }
  66095. inline const PixelARGB getPixel (const int px) const throw()
  66096. {
  66097. double x = px;
  66098. const double y = tM10 * x + lineYM11;
  66099. x = tM00 * x + lineYM01;
  66100. x *= x;
  66101. x += y * y;
  66102. if (x >= maxDist)
  66103. return lookupTable [numEntries];
  66104. else
  66105. return lookupTable [jmin (numEntries, roundToInt (std::sqrt (x) * invScale))];
  66106. }
  66107. private:
  66108. double tM10, tM00, lineYM01, lineYM11;
  66109. const AffineTransform inverseTransform;
  66110. TransformedRadialGradientPixelGenerator (const TransformedRadialGradientPixelGenerator&);
  66111. TransformedRadialGradientPixelGenerator& operator= (const TransformedRadialGradientPixelGenerator&);
  66112. };
  66113. template <class PixelType, class GradientType>
  66114. class GradientEdgeTableRenderer : public GradientType
  66115. {
  66116. public:
  66117. GradientEdgeTableRenderer (const Image::BitmapData& destData_, const ColourGradient& gradient, const AffineTransform& transform,
  66118. const PixelARGB* const lookupTable_, const int numEntries_)
  66119. : GradientType (gradient, transform, lookupTable_, numEntries_ - 1),
  66120. destData (destData_)
  66121. {
  66122. }
  66123. forcedinline void setEdgeTableYPos (const int y) throw()
  66124. {
  66125. linePixels = (PixelType*) destData.getLinePointer (y);
  66126. GradientType::setY (y);
  66127. }
  66128. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  66129. {
  66130. linePixels[x].blend (GradientType::getPixel (x), alphaLevel);
  66131. }
  66132. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  66133. {
  66134. linePixels[x].blend (GradientType::getPixel (x));
  66135. }
  66136. void handleEdgeTableLine (int x, int width, const int alphaLevel) const throw()
  66137. {
  66138. PixelType* dest = linePixels + x;
  66139. if (alphaLevel < 0xff)
  66140. {
  66141. do
  66142. {
  66143. (dest++)->blend (GradientType::getPixel (x++), alphaLevel);
  66144. } while (--width > 0);
  66145. }
  66146. else
  66147. {
  66148. do
  66149. {
  66150. (dest++)->blend (GradientType::getPixel (x++));
  66151. } while (--width > 0);
  66152. }
  66153. }
  66154. void handleEdgeTableLineFull (int x, int width) const throw()
  66155. {
  66156. PixelType* dest = linePixels + x;
  66157. do
  66158. {
  66159. (dest++)->blend (GradientType::getPixel (x++));
  66160. } while (--width > 0);
  66161. }
  66162. private:
  66163. const Image::BitmapData& destData;
  66164. PixelType* linePixels;
  66165. GradientEdgeTableRenderer (const GradientEdgeTableRenderer&);
  66166. GradientEdgeTableRenderer& operator= (const GradientEdgeTableRenderer&);
  66167. };
  66168. static forcedinline int safeModulo (int n, const int divisor) throw()
  66169. {
  66170. jassert (divisor > 0);
  66171. n %= divisor;
  66172. return (n < 0) ? (n + divisor) : n;
  66173. }
  66174. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  66175. class ImageFillEdgeTableRenderer
  66176. {
  66177. public:
  66178. ImageFillEdgeTableRenderer (const Image::BitmapData& destData_,
  66179. const Image::BitmapData& srcData_,
  66180. const int extraAlpha_,
  66181. const int x, const int y)
  66182. : destData (destData_),
  66183. srcData (srcData_),
  66184. extraAlpha (extraAlpha_ + 1),
  66185. xOffset (repeatPattern ? safeModulo (x, srcData_.width) - srcData_.width : x),
  66186. yOffset (repeatPattern ? safeModulo (y, srcData_.height) - srcData_.height : y)
  66187. {
  66188. }
  66189. forcedinline void setEdgeTableYPos (int y) throw()
  66190. {
  66191. linePixels = (DestPixelType*) destData.getLinePointer (y);
  66192. y -= yOffset;
  66193. if (repeatPattern)
  66194. {
  66195. jassert (y >= 0);
  66196. y %= srcData.height;
  66197. }
  66198. sourceLineStart = (SrcPixelType*) srcData.getLinePointer (y);
  66199. }
  66200. forcedinline void handleEdgeTablePixel (const int x, int alphaLevel) const throw()
  66201. {
  66202. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  66203. linePixels[x].blend (sourceLineStart [repeatPattern ? ((x - xOffset) % srcData.width) : (x - xOffset)], alphaLevel);
  66204. }
  66205. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  66206. {
  66207. linePixels[x].blend (sourceLineStart [repeatPattern ? ((x - xOffset) % srcData.width) : (x - xOffset)], extraAlpha);
  66208. }
  66209. void handleEdgeTableLine (int x, int width, int alphaLevel) const throw()
  66210. {
  66211. DestPixelType* dest = linePixels + x;
  66212. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  66213. x -= xOffset;
  66214. jassert (repeatPattern || (x >= 0 && x + width <= srcData.width));
  66215. if (alphaLevel < 0xfe)
  66216. {
  66217. do
  66218. {
  66219. dest++ ->blend (sourceLineStart [repeatPattern ? (x++ % srcData.width) : x++], alphaLevel);
  66220. } while (--width > 0);
  66221. }
  66222. else
  66223. {
  66224. if (repeatPattern)
  66225. {
  66226. do
  66227. {
  66228. dest++ ->blend (sourceLineStart [x++ % srcData.width]);
  66229. } while (--width > 0);
  66230. }
  66231. else
  66232. {
  66233. copyRow (dest, sourceLineStart + x, width);
  66234. }
  66235. }
  66236. }
  66237. void handleEdgeTableLineFull (int x, int width) const throw()
  66238. {
  66239. DestPixelType* dest = linePixels + x;
  66240. x -= xOffset;
  66241. jassert (repeatPattern || (x >= 0 && x + width <= srcData.width));
  66242. if (extraAlpha < 0xfe)
  66243. {
  66244. do
  66245. {
  66246. dest++ ->blend (sourceLineStart [repeatPattern ? (x++ % srcData.width) : x++], extraAlpha);
  66247. } while (--width > 0);
  66248. }
  66249. else
  66250. {
  66251. if (repeatPattern)
  66252. {
  66253. do
  66254. {
  66255. dest++ ->blend (sourceLineStart [x++ % srcData.width]);
  66256. } while (--width > 0);
  66257. }
  66258. else
  66259. {
  66260. copyRow (dest, sourceLineStart + x, width);
  66261. }
  66262. }
  66263. }
  66264. void clipEdgeTableLine (EdgeTable& et, int x, int y, int width)
  66265. {
  66266. jassert (x - xOffset >= 0 && x + width - xOffset <= srcData.width);
  66267. SrcPixelType* s = (SrcPixelType*) srcData.getLinePointer (y - yOffset);
  66268. uint8* mask = (uint8*) (s + x - xOffset);
  66269. if (sizeof (SrcPixelType) == sizeof (PixelARGB))
  66270. mask += PixelARGB::indexA;
  66271. et.clipLineToMask (x, y, mask, sizeof (SrcPixelType), width);
  66272. }
  66273. private:
  66274. const Image::BitmapData& destData;
  66275. const Image::BitmapData& srcData;
  66276. const int extraAlpha, xOffset, yOffset;
  66277. DestPixelType* linePixels;
  66278. SrcPixelType* sourceLineStart;
  66279. template <class PixelType1, class PixelType2>
  66280. forcedinline static void copyRow (PixelType1* dest, PixelType2* src, int width) throw()
  66281. {
  66282. do
  66283. {
  66284. dest++ ->blend (*src++);
  66285. } while (--width > 0);
  66286. }
  66287. forcedinline static void copyRow (PixelRGB* dest, PixelRGB* src, int width) throw()
  66288. {
  66289. memcpy (dest, src, width * sizeof (PixelRGB));
  66290. }
  66291. ImageFillEdgeTableRenderer (const ImageFillEdgeTableRenderer&);
  66292. ImageFillEdgeTableRenderer& operator= (const ImageFillEdgeTableRenderer&);
  66293. };
  66294. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  66295. class TransformedImageFillEdgeTableRenderer
  66296. {
  66297. public:
  66298. TransformedImageFillEdgeTableRenderer (const Image::BitmapData& destData_,
  66299. const Image::BitmapData& srcData_,
  66300. const AffineTransform& transform,
  66301. const int extraAlpha_,
  66302. const bool betterQuality_)
  66303. : interpolator (transform),
  66304. destData (destData_),
  66305. srcData (srcData_),
  66306. extraAlpha (extraAlpha_ + 1),
  66307. betterQuality (betterQuality_),
  66308. pixelOffset (betterQuality_ ? 0.5f : 0.0f),
  66309. pixelOffsetInt (betterQuality_ ? -128 : 0),
  66310. maxX (srcData_.width - 1),
  66311. maxY (srcData_.height - 1),
  66312. scratchSize (2048)
  66313. {
  66314. scratchBuffer.malloc (scratchSize);
  66315. }
  66316. ~TransformedImageFillEdgeTableRenderer()
  66317. {
  66318. }
  66319. forcedinline void setEdgeTableYPos (const int newY) throw()
  66320. {
  66321. y = newY;
  66322. linePixels = (DestPixelType*) destData.getLinePointer (newY);
  66323. }
  66324. forcedinline void handleEdgeTablePixel (const int x, int alphaLevel) throw()
  66325. {
  66326. alphaLevel *= extraAlpha;
  66327. alphaLevel >>= 8;
  66328. SrcPixelType p;
  66329. generate (&p, x, 1);
  66330. linePixels[x].blend (p, alphaLevel);
  66331. }
  66332. forcedinline void handleEdgeTablePixelFull (const int x) throw()
  66333. {
  66334. SrcPixelType p;
  66335. generate (&p, x, 1);
  66336. linePixels[x].blend (p, extraAlpha);
  66337. }
  66338. void handleEdgeTableLine (const int x, int width, int alphaLevel) throw()
  66339. {
  66340. if (width > scratchSize)
  66341. {
  66342. scratchSize = width;
  66343. scratchBuffer.malloc (scratchSize);
  66344. }
  66345. SrcPixelType* span = scratchBuffer;
  66346. generate (span, x, width);
  66347. DestPixelType* dest = linePixels + x;
  66348. alphaLevel *= extraAlpha;
  66349. alphaLevel >>= 8;
  66350. if (alphaLevel < 0xfe)
  66351. {
  66352. do
  66353. {
  66354. dest++ ->blend (*span++, alphaLevel);
  66355. } while (--width > 0);
  66356. }
  66357. else
  66358. {
  66359. do
  66360. {
  66361. dest++ ->blend (*span++);
  66362. } while (--width > 0);
  66363. }
  66364. }
  66365. forcedinline void handleEdgeTableLineFull (const int x, int width) throw()
  66366. {
  66367. handleEdgeTableLine (x, width, 255);
  66368. }
  66369. void clipEdgeTableLine (EdgeTable& et, int x, int y_, int width)
  66370. {
  66371. if (width > scratchSize)
  66372. {
  66373. scratchSize = width;
  66374. scratchBuffer.malloc (scratchSize);
  66375. }
  66376. y = y_;
  66377. generate (scratchBuffer, x, width);
  66378. et.clipLineToMask (x, y_,
  66379. reinterpret_cast<uint8*> (scratchBuffer.getData()) + SrcPixelType::indexA,
  66380. sizeof (SrcPixelType), width);
  66381. }
  66382. private:
  66383. void generate (PixelARGB* dest, const int x, int numPixels) throw()
  66384. {
  66385. this->interpolator.setStartOfLine (x + pixelOffset, y + pixelOffset, numPixels);
  66386. do
  66387. {
  66388. int hiResX, hiResY;
  66389. this->interpolator.next (hiResX, hiResY);
  66390. hiResX += pixelOffsetInt;
  66391. hiResY += pixelOffsetInt;
  66392. int loResX = hiResX >> 8;
  66393. int loResY = hiResY >> 8;
  66394. if (repeatPattern)
  66395. {
  66396. loResX = safeModulo (loResX, srcData.width);
  66397. loResY = safeModulo (loResY, srcData.height);
  66398. }
  66399. if (betterQuality
  66400. && ((unsigned int) loResX) < (unsigned int) maxX
  66401. && ((unsigned int) loResY) < (unsigned int) maxY)
  66402. {
  66403. uint32 c[4] = { 256 * 128, 256 * 128, 256 * 128, 256 * 128 };
  66404. hiResX &= 255;
  66405. hiResY &= 255;
  66406. const uint8* src = this->srcData.getPixelPointer (loResX, loResY);
  66407. uint32 weight = (256 - hiResX) * (256 - hiResY);
  66408. c[0] += weight * src[0];
  66409. c[1] += weight * src[1];
  66410. c[2] += weight * src[2];
  66411. c[3] += weight * src[3];
  66412. weight = hiResX * (256 - hiResY);
  66413. c[0] += weight * src[4];
  66414. c[1] += weight * src[5];
  66415. c[2] += weight * src[6];
  66416. c[3] += weight * src[7];
  66417. src += this->srcData.lineStride;
  66418. weight = (256 - hiResX) * hiResY;
  66419. c[0] += weight * src[0];
  66420. c[1] += weight * src[1];
  66421. c[2] += weight * src[2];
  66422. c[3] += weight * src[3];
  66423. weight = hiResX * hiResY;
  66424. c[0] += weight * src[4];
  66425. c[1] += weight * src[5];
  66426. c[2] += weight * src[6];
  66427. c[3] += weight * src[7];
  66428. dest->setARGB ((uint8) (c[PixelARGB::indexA] >> 16),
  66429. (uint8) (c[PixelARGB::indexR] >> 16),
  66430. (uint8) (c[PixelARGB::indexG] >> 16),
  66431. (uint8) (c[PixelARGB::indexB] >> 16));
  66432. }
  66433. else
  66434. {
  66435. if (! repeatPattern)
  66436. {
  66437. // Beyond the edges, just repeat the edge pixels and leave the anti-aliasing to be handled by the edgetable
  66438. if (loResX < 0) loResX = 0;
  66439. if (loResY < 0) loResY = 0;
  66440. if (loResX > maxX) loResX = maxX;
  66441. if (loResY > maxY) loResY = maxY;
  66442. }
  66443. dest->set (*(const PixelARGB*) this->srcData.getPixelPointer (loResX, loResY));
  66444. }
  66445. ++dest;
  66446. } while (--numPixels > 0);
  66447. }
  66448. void generate (PixelRGB* dest, const int x, int numPixels) throw()
  66449. {
  66450. this->interpolator.setStartOfLine (x + pixelOffset, y + pixelOffset, numPixels);
  66451. do
  66452. {
  66453. int hiResX, hiResY;
  66454. this->interpolator.next (hiResX, hiResY);
  66455. hiResX += pixelOffsetInt;
  66456. hiResY += pixelOffsetInt;
  66457. int loResX = hiResX >> 8;
  66458. int loResY = hiResY >> 8;
  66459. if (repeatPattern)
  66460. {
  66461. loResX = safeModulo (loResX, srcData.width);
  66462. loResY = safeModulo (loResY, srcData.height);
  66463. }
  66464. if (betterQuality
  66465. && ((unsigned int) loResX) < (unsigned int) maxX
  66466. && ((unsigned int) loResY) < (unsigned int) maxY)
  66467. {
  66468. uint32 c[3] = { 256 * 128, 256 * 128, 256 * 128 };
  66469. hiResX &= 255;
  66470. hiResY &= 255;
  66471. const uint8* src = this->srcData.getPixelPointer (loResX, loResY);
  66472. unsigned int weight = (256 - hiResX) * (256 - hiResY);
  66473. c[0] += weight * src[0];
  66474. c[1] += weight * src[1];
  66475. c[2] += weight * src[2];
  66476. weight = hiResX * (256 - hiResY);
  66477. c[0] += weight * src[3];
  66478. c[1] += weight * src[4];
  66479. c[2] += weight * src[5];
  66480. src += this->srcData.lineStride;
  66481. weight = (256 - hiResX) * hiResY;
  66482. c[0] += weight * src[0];
  66483. c[1] += weight * src[1];
  66484. c[2] += weight * src[2];
  66485. weight = hiResX * hiResY;
  66486. c[0] += weight * src[3];
  66487. c[1] += weight * src[4];
  66488. c[2] += weight * src[5];
  66489. dest->setARGB ((uint8) 255,
  66490. (uint8) (c[PixelRGB::indexR] >> 16),
  66491. (uint8) (c[PixelRGB::indexG] >> 16),
  66492. (uint8) (c[PixelRGB::indexB] >> 16));
  66493. }
  66494. else
  66495. {
  66496. if (! repeatPattern)
  66497. {
  66498. // Beyond the edges, just repeat the edge pixels and leave the anti-aliasing to be handled by the edgetable
  66499. if (loResX < 0) loResX = 0;
  66500. if (loResY < 0) loResY = 0;
  66501. if (loResX > maxX) loResX = maxX;
  66502. if (loResY > maxY) loResY = maxY;
  66503. }
  66504. dest->set (*(const PixelRGB*) this->srcData.getPixelPointer (loResX, loResY));
  66505. }
  66506. ++dest;
  66507. } while (--numPixels > 0);
  66508. }
  66509. void generate (PixelAlpha* dest, const int x, int numPixels) throw()
  66510. {
  66511. this->interpolator.setStartOfLine (x + pixelOffset, y + pixelOffset, numPixels);
  66512. do
  66513. {
  66514. int hiResX, hiResY;
  66515. this->interpolator.next (hiResX, hiResY);
  66516. hiResX += pixelOffsetInt;
  66517. hiResY += pixelOffsetInt;
  66518. int loResX = hiResX >> 8;
  66519. int loResY = hiResY >> 8;
  66520. if (repeatPattern)
  66521. {
  66522. loResX = safeModulo (loResX, srcData.width);
  66523. loResY = safeModulo (loResY, srcData.height);
  66524. }
  66525. if (betterQuality
  66526. && ((unsigned int) loResX) < (unsigned int) maxX
  66527. && ((unsigned int) loResY) < (unsigned int) maxY)
  66528. {
  66529. hiResX &= 255;
  66530. hiResY &= 255;
  66531. const uint8* src = this->srcData.getPixelPointer (loResX, loResY);
  66532. uint32 c = 256 * 128;
  66533. c += src[0] * ((256 - hiResX) * (256 - hiResY));
  66534. c += src[1] * (hiResX * (256 - hiResY));
  66535. src += this->srcData.lineStride;
  66536. c += src[0] * ((256 - hiResX) * hiResY);
  66537. c += src[1] * (hiResX * hiResY);
  66538. *((uint8*) dest) = (uint8) c;
  66539. }
  66540. else
  66541. {
  66542. if (! repeatPattern)
  66543. {
  66544. // Beyond the edges, just repeat the edge pixels and leave the anti-aliasing to be handled by the edgetable
  66545. if (loResX < 0) loResX = 0;
  66546. if (loResY < 0) loResY = 0;
  66547. if (loResX > maxX) loResX = maxX;
  66548. if (loResY > maxY) loResY = maxY;
  66549. }
  66550. *((uint8*) dest) = *(this->srcData.getPixelPointer (loResX, loResY));
  66551. }
  66552. ++dest;
  66553. } while (--numPixels > 0);
  66554. }
  66555. class TransformedImageSpanInterpolator
  66556. {
  66557. public:
  66558. TransformedImageSpanInterpolator (const AffineTransform& transform) throw()
  66559. : inverseTransform (transform.inverted())
  66560. {}
  66561. void setStartOfLine (float x, float y, const int numPixels) throw()
  66562. {
  66563. float x1 = x, y1 = y;
  66564. inverseTransform.transformPoint (x1, y1);
  66565. x += numPixels;
  66566. inverseTransform.transformPoint (x, y);
  66567. xBresenham.set ((int) (x1 * 256.0f), (int) (x * 256.0f), numPixels);
  66568. yBresenham.set ((int) (y1 * 256.0f), (int) (y * 256.0f), numPixels);
  66569. }
  66570. void next (int& x, int& y) throw()
  66571. {
  66572. x = xBresenham.n;
  66573. xBresenham.stepToNext();
  66574. y = yBresenham.n;
  66575. yBresenham.stepToNext();
  66576. }
  66577. private:
  66578. class BresenhamInterpolator
  66579. {
  66580. public:
  66581. BresenhamInterpolator() throw() {}
  66582. void set (const int n1, const int n2, const int numSteps_) throw()
  66583. {
  66584. numSteps = jmax (1, numSteps_);
  66585. step = (n2 - n1) / numSteps;
  66586. remainder = modulo = (n2 - n1) % numSteps;
  66587. n = n1;
  66588. if (modulo <= 0)
  66589. {
  66590. modulo += numSteps;
  66591. remainder += numSteps;
  66592. --step;
  66593. }
  66594. modulo -= numSteps;
  66595. }
  66596. forcedinline void stepToNext() throw()
  66597. {
  66598. modulo += remainder;
  66599. n += step;
  66600. if (modulo > 0)
  66601. {
  66602. modulo -= numSteps;
  66603. ++n;
  66604. }
  66605. }
  66606. int n;
  66607. private:
  66608. int numSteps, step, modulo, remainder;
  66609. };
  66610. const AffineTransform inverseTransform;
  66611. BresenhamInterpolator xBresenham, yBresenham;
  66612. TransformedImageSpanInterpolator (const TransformedImageSpanInterpolator&);
  66613. TransformedImageSpanInterpolator& operator= (const TransformedImageSpanInterpolator&);
  66614. };
  66615. TransformedImageSpanInterpolator interpolator;
  66616. const Image::BitmapData& destData;
  66617. const Image::BitmapData& srcData;
  66618. const int extraAlpha;
  66619. const bool betterQuality;
  66620. const float pixelOffset;
  66621. const int pixelOffsetInt, maxX, maxY;
  66622. int y;
  66623. DestPixelType* linePixels;
  66624. HeapBlock <SrcPixelType> scratchBuffer;
  66625. int scratchSize;
  66626. TransformedImageFillEdgeTableRenderer (const TransformedImageFillEdgeTableRenderer&);
  66627. TransformedImageFillEdgeTableRenderer& operator= (const TransformedImageFillEdgeTableRenderer&);
  66628. };
  66629. class ClipRegionBase : public ReferenceCountedObject
  66630. {
  66631. public:
  66632. ClipRegionBase() {}
  66633. virtual ~ClipRegionBase() {}
  66634. typedef ReferenceCountedObjectPtr<ClipRegionBase> Ptr;
  66635. virtual const Ptr clone() const = 0;
  66636. virtual const Ptr applyClipTo (const Ptr& target) const = 0;
  66637. virtual const Ptr clipToRectangle (const Rectangle<int>& r) = 0;
  66638. virtual const Ptr clipToRectangleList (const RectangleList& r) = 0;
  66639. virtual const Ptr excludeClipRectangle (const Rectangle<int>& r) = 0;
  66640. virtual const Ptr clipToPath (const Path& p, const AffineTransform& transform) = 0;
  66641. virtual const Ptr clipToEdgeTable (const EdgeTable& et) = 0;
  66642. virtual const Ptr clipToImageAlpha (const Image& image, const Rectangle<int>& srcClip, const AffineTransform& t, const bool betterQuality) = 0;
  66643. virtual bool clipRegionIntersects (const Rectangle<int>& r) const = 0;
  66644. virtual const Rectangle<int> getClipBounds() const = 0;
  66645. virtual void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const = 0;
  66646. virtual void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const = 0;
  66647. virtual void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const = 0;
  66648. virtual void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const = 0;
  66649. virtual void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& t, bool betterQuality, bool tiledFill) const = 0;
  66650. virtual void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const = 0;
  66651. protected:
  66652. template <class Iterator>
  66653. static void renderImageTransformedInternal (Iterator& iter, const Image::BitmapData& destData, const Image::BitmapData& srcData,
  66654. const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill)
  66655. {
  66656. switch (destData.pixelFormat)
  66657. {
  66658. case Image::ARGB:
  66659. switch (srcData.pixelFormat)
  66660. {
  66661. case Image::ARGB:
  66662. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66663. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66664. break;
  66665. case Image::RGB:
  66666. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66667. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66668. break;
  66669. default:
  66670. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66671. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66672. break;
  66673. }
  66674. break;
  66675. case Image::RGB:
  66676. switch (srcData.pixelFormat)
  66677. {
  66678. case Image::ARGB:
  66679. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66680. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66681. break;
  66682. case Image::RGB:
  66683. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66684. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66685. break;
  66686. default:
  66687. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66688. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66689. break;
  66690. }
  66691. break;
  66692. default:
  66693. switch (srcData.pixelFormat)
  66694. {
  66695. case Image::ARGB:
  66696. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66697. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66698. break;
  66699. case Image::RGB:
  66700. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66701. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66702. break;
  66703. default:
  66704. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66705. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66706. break;
  66707. }
  66708. break;
  66709. }
  66710. }
  66711. template <class Iterator>
  66712. static void renderImageUntransformedInternal (Iterator& iter, const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill)
  66713. {
  66714. switch (destData.pixelFormat)
  66715. {
  66716. case Image::ARGB:
  66717. switch (srcData.pixelFormat)
  66718. {
  66719. case Image::ARGB:
  66720. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66721. else { ImageFillEdgeTableRenderer <PixelARGB, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66722. break;
  66723. case Image::RGB:
  66724. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66725. else { ImageFillEdgeTableRenderer <PixelARGB, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66726. break;
  66727. default:
  66728. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66729. else { ImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66730. break;
  66731. }
  66732. break;
  66733. case Image::RGB:
  66734. switch (srcData.pixelFormat)
  66735. {
  66736. case Image::ARGB:
  66737. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66738. else { ImageFillEdgeTableRenderer <PixelRGB, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66739. break;
  66740. case Image::RGB:
  66741. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66742. else { ImageFillEdgeTableRenderer <PixelRGB, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66743. break;
  66744. default:
  66745. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66746. else { ImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66747. break;
  66748. }
  66749. break;
  66750. default:
  66751. switch (srcData.pixelFormat)
  66752. {
  66753. case Image::ARGB:
  66754. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66755. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66756. break;
  66757. case Image::RGB:
  66758. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66759. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66760. break;
  66761. default:
  66762. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66763. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66764. break;
  66765. }
  66766. break;
  66767. }
  66768. }
  66769. template <class Iterator, class DestPixelType>
  66770. static void renderSolidFill (Iterator& iter, const Image::BitmapData& destData, const PixelARGB& fillColour, const bool replaceContents, DestPixelType*)
  66771. {
  66772. jassert (destData.pixelStride == sizeof (DestPixelType));
  66773. if (replaceContents)
  66774. {
  66775. SolidColourEdgeTableRenderer <DestPixelType, true> r (destData, fillColour);
  66776. iter.iterate (r);
  66777. }
  66778. else
  66779. {
  66780. SolidColourEdgeTableRenderer <DestPixelType, false> r (destData, fillColour);
  66781. iter.iterate (r);
  66782. }
  66783. }
  66784. template <class Iterator, class DestPixelType>
  66785. static void renderGradient (Iterator& iter, const Image::BitmapData& destData, const ColourGradient& g, const AffineTransform& transform,
  66786. const PixelARGB* const lookupTable, const int numLookupEntries, const bool isIdentity, DestPixelType*)
  66787. {
  66788. jassert (destData.pixelStride == sizeof (DestPixelType));
  66789. if (g.isRadial)
  66790. {
  66791. if (isIdentity)
  66792. {
  66793. GradientEdgeTableRenderer <DestPixelType, RadialGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  66794. iter.iterate (renderer);
  66795. }
  66796. else
  66797. {
  66798. GradientEdgeTableRenderer <DestPixelType, TransformedRadialGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  66799. iter.iterate (renderer);
  66800. }
  66801. }
  66802. else
  66803. {
  66804. GradientEdgeTableRenderer <DestPixelType, LinearGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  66805. iter.iterate (renderer);
  66806. }
  66807. }
  66808. };
  66809. class ClipRegion_EdgeTable : public ClipRegionBase
  66810. {
  66811. public:
  66812. ClipRegion_EdgeTable (const EdgeTable& e) : edgeTable (e) {}
  66813. ClipRegion_EdgeTable (const Rectangle<int>& r) : edgeTable (r) {}
  66814. ClipRegion_EdgeTable (const Rectangle<float>& r) : edgeTable (r) {}
  66815. ClipRegion_EdgeTable (const RectangleList& r) : edgeTable (r) {}
  66816. ClipRegion_EdgeTable (const Rectangle<int>& bounds, const Path& p, const AffineTransform& t) : edgeTable (bounds, p, t) {}
  66817. ClipRegion_EdgeTable (const ClipRegion_EdgeTable& other) : edgeTable (other.edgeTable) {}
  66818. ~ClipRegion_EdgeTable() {}
  66819. const Ptr clone() const
  66820. {
  66821. return new ClipRegion_EdgeTable (*this);
  66822. }
  66823. const Ptr applyClipTo (const Ptr& target) const
  66824. {
  66825. return target->clipToEdgeTable (edgeTable);
  66826. }
  66827. const Ptr clipToRectangle (const Rectangle<int>& r)
  66828. {
  66829. edgeTable.clipToRectangle (r);
  66830. return edgeTable.isEmpty() ? 0 : this;
  66831. }
  66832. const Ptr clipToRectangleList (const RectangleList& r)
  66833. {
  66834. RectangleList inverse (edgeTable.getMaximumBounds());
  66835. if (inverse.subtract (r))
  66836. for (RectangleList::Iterator iter (inverse); iter.next();)
  66837. edgeTable.excludeRectangle (*iter.getRectangle());
  66838. return edgeTable.isEmpty() ? 0 : this;
  66839. }
  66840. const Ptr excludeClipRectangle (const Rectangle<int>& r)
  66841. {
  66842. edgeTable.excludeRectangle (r);
  66843. return edgeTable.isEmpty() ? 0 : this;
  66844. }
  66845. const Ptr clipToPath (const Path& p, const AffineTransform& transform)
  66846. {
  66847. EdgeTable et (edgeTable.getMaximumBounds(), p, transform);
  66848. edgeTable.clipToEdgeTable (et);
  66849. return edgeTable.isEmpty() ? 0 : this;
  66850. }
  66851. const Ptr clipToEdgeTable (const EdgeTable& et)
  66852. {
  66853. edgeTable.clipToEdgeTable (et);
  66854. return edgeTable.isEmpty() ? 0 : this;
  66855. }
  66856. const Ptr clipToImageAlpha (const Image& image, const Rectangle<int>& srcClip, const AffineTransform& transform, const bool betterQuality)
  66857. {
  66858. const Image::BitmapData srcData (image, srcClip.getX(), srcClip.getY(), srcClip.getWidth(), srcClip.getHeight());
  66859. if (transform.isOnlyTranslation())
  66860. {
  66861. // If our translation doesn't involve any distortion, just use a simple blit..
  66862. const int tx = (int) (transform.getTranslationX() * 256.0f);
  66863. const int ty = (int) (transform.getTranslationY() * 256.0f);
  66864. if ((! betterQuality) || ((tx | ty) & 224) == 0)
  66865. {
  66866. const int imageX = ((tx + 128) >> 8);
  66867. const int imageY = ((ty + 128) >> 8);
  66868. if (image.getFormat() == Image::ARGB)
  66869. straightClipImage (srcData, imageX, imageY, (PixelARGB*) 0);
  66870. else
  66871. straightClipImage (srcData, imageX, imageY, (PixelAlpha*) 0);
  66872. return edgeTable.isEmpty() ? 0 : this;
  66873. }
  66874. }
  66875. if (transform.isSingularity())
  66876. return 0;
  66877. {
  66878. Path p;
  66879. p.addRectangle (0, 0, (float) srcData.width, (float) srcData.height);
  66880. EdgeTable et2 (edgeTable.getMaximumBounds(), p, transform);
  66881. edgeTable.clipToEdgeTable (et2);
  66882. }
  66883. if (! edgeTable.isEmpty())
  66884. {
  66885. if (image.getFormat() == Image::ARGB)
  66886. transformedClipImage (srcData, transform, betterQuality, (PixelARGB*) 0);
  66887. else
  66888. transformedClipImage (srcData, transform, betterQuality, (PixelAlpha*) 0);
  66889. }
  66890. return edgeTable.isEmpty() ? 0 : this;
  66891. }
  66892. bool clipRegionIntersects (const Rectangle<int>& r) const
  66893. {
  66894. return edgeTable.getMaximumBounds().intersects (r);
  66895. }
  66896. const Rectangle<int> getClipBounds() const
  66897. {
  66898. return edgeTable.getMaximumBounds();
  66899. }
  66900. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const
  66901. {
  66902. const Rectangle<int> totalClip (edgeTable.getMaximumBounds());
  66903. const Rectangle<int> clipped (totalClip.getIntersection (area));
  66904. if (! clipped.isEmpty())
  66905. {
  66906. ClipRegion_EdgeTable et (clipped);
  66907. et.edgeTable.clipToEdgeTable (edgeTable);
  66908. et.fillAllWithColour (destData, colour, replaceContents);
  66909. }
  66910. }
  66911. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const
  66912. {
  66913. const Rectangle<float> totalClip (edgeTable.getMaximumBounds().toFloat());
  66914. const Rectangle<float> clipped (totalClip.getIntersection (area));
  66915. if (! clipped.isEmpty())
  66916. {
  66917. ClipRegion_EdgeTable et (clipped);
  66918. et.edgeTable.clipToEdgeTable (edgeTable);
  66919. et.fillAllWithColour (destData, colour, false);
  66920. }
  66921. }
  66922. void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const
  66923. {
  66924. switch (destData.pixelFormat)
  66925. {
  66926. case Image::ARGB: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelARGB*) 0); break;
  66927. case Image::RGB: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelRGB*) 0); break;
  66928. default: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  66929. }
  66930. }
  66931. void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const
  66932. {
  66933. HeapBlock <PixelARGB> lookupTable;
  66934. const int numLookupEntries = gradient.createLookupTable (transform, lookupTable);
  66935. jassert (numLookupEntries > 0);
  66936. switch (destData.pixelFormat)
  66937. {
  66938. case Image::ARGB: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelARGB*) 0); break;
  66939. case Image::RGB: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelRGB*) 0); break;
  66940. default: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelAlpha*) 0); break;
  66941. }
  66942. }
  66943. void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill) const
  66944. {
  66945. renderImageTransformedInternal (edgeTable, destData, srcData, alpha, transform, betterQuality, tiledFill);
  66946. }
  66947. void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const
  66948. {
  66949. renderImageUntransformedInternal (edgeTable, destData, srcData, alpha, x, y, tiledFill);
  66950. }
  66951. EdgeTable edgeTable;
  66952. private:
  66953. template <class SrcPixelType>
  66954. void transformedClipImage (const Image::BitmapData& srcData, const AffineTransform& transform, const bool betterQuality, const SrcPixelType*)
  66955. {
  66956. TransformedImageFillEdgeTableRenderer <SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, transform, 255, betterQuality);
  66957. for (int y = 0; y < edgeTable.getMaximumBounds().getHeight(); ++y)
  66958. renderer.clipEdgeTableLine (edgeTable, edgeTable.getMaximumBounds().getX(), y + edgeTable.getMaximumBounds().getY(),
  66959. edgeTable.getMaximumBounds().getWidth());
  66960. }
  66961. template <class SrcPixelType>
  66962. void straightClipImage (const Image::BitmapData& srcData, int imageX, int imageY, const SrcPixelType*)
  66963. {
  66964. Rectangle<int> r (imageX, imageY, srcData.width, srcData.height);
  66965. edgeTable.clipToRectangle (r);
  66966. ImageFillEdgeTableRenderer <SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, 255, imageX, imageY);
  66967. for (int y = 0; y < r.getHeight(); ++y)
  66968. renderer.clipEdgeTableLine (edgeTable, r.getX(), y + r.getY(), r.getWidth());
  66969. }
  66970. ClipRegion_EdgeTable& operator= (const ClipRegion_EdgeTable&);
  66971. };
  66972. class ClipRegion_RectangleList : public ClipRegionBase
  66973. {
  66974. public:
  66975. ClipRegion_RectangleList (const Rectangle<int>& r) : clip (r) {}
  66976. ClipRegion_RectangleList (const RectangleList& r) : clip (r) {}
  66977. ClipRegion_RectangleList (const ClipRegion_RectangleList& other) : clip (other.clip) {}
  66978. ~ClipRegion_RectangleList() {}
  66979. const Ptr clone() const
  66980. {
  66981. return new ClipRegion_RectangleList (*this);
  66982. }
  66983. const Ptr applyClipTo (const Ptr& target) const
  66984. {
  66985. return target->clipToRectangleList (clip);
  66986. }
  66987. const Ptr clipToRectangle (const Rectangle<int>& r)
  66988. {
  66989. clip.clipTo (r);
  66990. return clip.isEmpty() ? 0 : this;
  66991. }
  66992. const Ptr clipToRectangleList (const RectangleList& r)
  66993. {
  66994. clip.clipTo (r);
  66995. return clip.isEmpty() ? 0 : this;
  66996. }
  66997. const Ptr excludeClipRectangle (const Rectangle<int>& r)
  66998. {
  66999. clip.subtract (r);
  67000. return clip.isEmpty() ? 0 : this;
  67001. }
  67002. const Ptr clipToPath (const Path& p, const AffineTransform& transform)
  67003. {
  67004. return Ptr (new ClipRegion_EdgeTable (clip))->clipToPath (p, transform);
  67005. }
  67006. const Ptr clipToEdgeTable (const EdgeTable& et)
  67007. {
  67008. return Ptr (new ClipRegion_EdgeTable (clip))->clipToEdgeTable (et);
  67009. }
  67010. const Ptr clipToImageAlpha (const Image& image, const Rectangle<int>& srcClip, const AffineTransform& transform, const bool betterQuality)
  67011. {
  67012. return Ptr (new ClipRegion_EdgeTable (clip))->clipToImageAlpha (image, srcClip, transform, betterQuality);
  67013. }
  67014. bool clipRegionIntersects (const Rectangle<int>& r) const
  67015. {
  67016. return clip.intersects (r);
  67017. }
  67018. const Rectangle<int> getClipBounds() const
  67019. {
  67020. return clip.getBounds();
  67021. }
  67022. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const
  67023. {
  67024. SubRectangleIterator iter (clip, area);
  67025. switch (destData.pixelFormat)
  67026. {
  67027. case Image::ARGB: renderSolidFill (iter, destData, colour, replaceContents, (PixelARGB*) 0); break;
  67028. case Image::RGB: renderSolidFill (iter, destData, colour, replaceContents, (PixelRGB*) 0); break;
  67029. default: renderSolidFill (iter, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  67030. }
  67031. }
  67032. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const
  67033. {
  67034. SubRectangleIteratorFloat iter (clip, area);
  67035. switch (destData.pixelFormat)
  67036. {
  67037. case Image::ARGB: renderSolidFill (iter, destData, colour, false, (PixelARGB*) 0); break;
  67038. case Image::RGB: renderSolidFill (iter, destData, colour, false, (PixelRGB*) 0); break;
  67039. default: renderSolidFill (iter, destData, colour, false, (PixelAlpha*) 0); break;
  67040. }
  67041. }
  67042. void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const
  67043. {
  67044. switch (destData.pixelFormat)
  67045. {
  67046. case Image::ARGB: renderSolidFill (*this, destData, colour, replaceContents, (PixelARGB*) 0); break;
  67047. case Image::RGB: renderSolidFill (*this, destData, colour, replaceContents, (PixelRGB*) 0); break;
  67048. default: renderSolidFill (*this, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  67049. }
  67050. }
  67051. void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const
  67052. {
  67053. HeapBlock <PixelARGB> lookupTable;
  67054. const int numLookupEntries = gradient.createLookupTable (transform, lookupTable);
  67055. jassert (numLookupEntries > 0);
  67056. switch (destData.pixelFormat)
  67057. {
  67058. case Image::ARGB: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelARGB*) 0); break;
  67059. case Image::RGB: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelRGB*) 0); break;
  67060. default: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelAlpha*) 0); break;
  67061. }
  67062. }
  67063. void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill) const
  67064. {
  67065. renderImageTransformedInternal (*this, destData, srcData, alpha, transform, betterQuality, tiledFill);
  67066. }
  67067. void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const
  67068. {
  67069. renderImageUntransformedInternal (*this, destData, srcData, alpha, x, y, tiledFill);
  67070. }
  67071. RectangleList clip;
  67072. template <class Renderer>
  67073. void iterate (Renderer& r) const throw()
  67074. {
  67075. RectangleList::Iterator iter (clip);
  67076. while (iter.next())
  67077. {
  67078. const Rectangle<int> rect (*iter.getRectangle());
  67079. const int x = rect.getX();
  67080. const int w = rect.getWidth();
  67081. jassert (w > 0);
  67082. const int bottom = rect.getBottom();
  67083. for (int y = rect.getY(); y < bottom; ++y)
  67084. {
  67085. r.setEdgeTableYPos (y);
  67086. r.handleEdgeTableLineFull (x, w);
  67087. }
  67088. }
  67089. }
  67090. private:
  67091. class SubRectangleIterator
  67092. {
  67093. public:
  67094. SubRectangleIterator (const RectangleList& clip_, const Rectangle<int>& area_)
  67095. : clip (clip_), area (area_)
  67096. {
  67097. }
  67098. template <class Renderer>
  67099. void iterate (Renderer& r) const throw()
  67100. {
  67101. RectangleList::Iterator iter (clip);
  67102. while (iter.next())
  67103. {
  67104. const Rectangle<int> rect (iter.getRectangle()->getIntersection (area));
  67105. if (! rect.isEmpty())
  67106. {
  67107. const int x = rect.getX();
  67108. const int w = rect.getWidth();
  67109. const int bottom = rect.getBottom();
  67110. for (int y = rect.getY(); y < bottom; ++y)
  67111. {
  67112. r.setEdgeTableYPos (y);
  67113. r.handleEdgeTableLineFull (x, w);
  67114. }
  67115. }
  67116. }
  67117. }
  67118. private:
  67119. const RectangleList& clip;
  67120. const Rectangle<int> area;
  67121. SubRectangleIterator (const SubRectangleIterator&);
  67122. SubRectangleIterator& operator= (const SubRectangleIterator&);
  67123. };
  67124. class SubRectangleIteratorFloat
  67125. {
  67126. public:
  67127. SubRectangleIteratorFloat (const RectangleList& clip_, const Rectangle<float>& area_)
  67128. : clip (clip_), area (area_)
  67129. {
  67130. }
  67131. template <class Renderer>
  67132. void iterate (Renderer& r) const throw()
  67133. {
  67134. int left = roundToInt (area.getX() * 256.0f);
  67135. int top = roundToInt (area.getY() * 256.0f);
  67136. int right = roundToInt (area.getRight() * 256.0f);
  67137. int bottom = roundToInt (area.getBottom() * 256.0f);
  67138. int totalTop, totalLeft, totalBottom, totalRight;
  67139. int topAlpha, leftAlpha, bottomAlpha, rightAlpha;
  67140. if ((top >> 8) == (bottom >> 8))
  67141. {
  67142. topAlpha = bottom - top;
  67143. bottomAlpha = 0;
  67144. totalTop = top >> 8;
  67145. totalBottom = bottom = top = totalTop + 1;
  67146. }
  67147. else
  67148. {
  67149. if ((top & 255) == 0)
  67150. {
  67151. topAlpha = 0;
  67152. top = totalTop = (top >> 8);
  67153. }
  67154. else
  67155. {
  67156. topAlpha = 255 - (top & 255);
  67157. totalTop = (top >> 8);
  67158. top = totalTop + 1;
  67159. }
  67160. bottomAlpha = bottom & 255;
  67161. bottom >>= 8;
  67162. totalBottom = bottom + (bottomAlpha != 0 ? 1 : 0);
  67163. }
  67164. if ((left >> 8) == (right >> 8))
  67165. {
  67166. leftAlpha = right - left;
  67167. rightAlpha = 0;
  67168. totalLeft = (left >> 8);
  67169. totalRight = right = left = totalLeft + 1;
  67170. }
  67171. else
  67172. {
  67173. if ((left & 255) == 0)
  67174. {
  67175. leftAlpha = 0;
  67176. left = totalLeft = (left >> 8);
  67177. }
  67178. else
  67179. {
  67180. leftAlpha = 255 - (left & 255);
  67181. totalLeft = (left >> 8);
  67182. left = totalLeft + 1;
  67183. }
  67184. rightAlpha = right & 255;
  67185. right >>= 8;
  67186. totalRight = right + (rightAlpha != 0 ? 1 : 0);
  67187. }
  67188. RectangleList::Iterator iter (clip);
  67189. while (iter.next())
  67190. {
  67191. const int clipLeft = iter.getRectangle()->getX();
  67192. const int clipRight = iter.getRectangle()->getRight();
  67193. const int clipTop = iter.getRectangle()->getY();
  67194. const int clipBottom = iter.getRectangle()->getBottom();
  67195. if (totalBottom > clipTop && totalTop < clipBottom && totalRight > clipLeft && totalLeft < clipRight)
  67196. {
  67197. if (right - left == 1 && leftAlpha + rightAlpha == 0) // special case for 1-pix vertical lines
  67198. {
  67199. if (topAlpha != 0 && totalTop >= clipTop)
  67200. {
  67201. r.setEdgeTableYPos (totalTop);
  67202. r.handleEdgeTablePixel (left, topAlpha);
  67203. }
  67204. const int endY = jmin (bottom, clipBottom);
  67205. for (int y = jmax (clipTop, top); y < endY; ++y)
  67206. {
  67207. r.setEdgeTableYPos (y);
  67208. r.handleEdgeTablePixelFull (left);
  67209. }
  67210. if (bottomAlpha != 0 && bottom < clipBottom)
  67211. {
  67212. r.setEdgeTableYPos (bottom);
  67213. r.handleEdgeTablePixel (left, bottomAlpha);
  67214. }
  67215. }
  67216. else
  67217. {
  67218. const int clippedLeft = jmax (left, clipLeft);
  67219. const int clippedWidth = jmin (right, clipRight) - clippedLeft;
  67220. const bool doLeftAlpha = leftAlpha != 0 && totalLeft >= clipLeft;
  67221. const bool doRightAlpha = rightAlpha != 0 && right < clipRight;
  67222. if (topAlpha != 0 && totalTop >= clipTop)
  67223. {
  67224. r.setEdgeTableYPos (totalTop);
  67225. if (doLeftAlpha)
  67226. r.handleEdgeTablePixel (totalLeft, (leftAlpha * topAlpha) >> 8);
  67227. if (clippedWidth > 0)
  67228. r.handleEdgeTableLine (clippedLeft, clippedWidth, topAlpha);
  67229. if (doRightAlpha)
  67230. r.handleEdgeTablePixel (right, (rightAlpha * topAlpha) >> 8);
  67231. }
  67232. const int endY = jmin (bottom, clipBottom);
  67233. for (int y = jmax (clipTop, top); y < endY; ++y)
  67234. {
  67235. r.setEdgeTableYPos (y);
  67236. if (doLeftAlpha)
  67237. r.handleEdgeTablePixel (totalLeft, leftAlpha);
  67238. if (clippedWidth > 0)
  67239. r.handleEdgeTableLineFull (clippedLeft, clippedWidth);
  67240. if (doRightAlpha)
  67241. r.handleEdgeTablePixel (right, rightAlpha);
  67242. }
  67243. if (bottomAlpha != 0 && bottom < clipBottom)
  67244. {
  67245. r.setEdgeTableYPos (bottom);
  67246. if (doLeftAlpha)
  67247. r.handleEdgeTablePixel (totalLeft, (leftAlpha * bottomAlpha) >> 8);
  67248. if (clippedWidth > 0)
  67249. r.handleEdgeTableLine (clippedLeft, clippedWidth, bottomAlpha);
  67250. if (doRightAlpha)
  67251. r.handleEdgeTablePixel (right, (rightAlpha * bottomAlpha) >> 8);
  67252. }
  67253. }
  67254. }
  67255. }
  67256. }
  67257. private:
  67258. const RectangleList& clip;
  67259. const Rectangle<float>& area;
  67260. SubRectangleIteratorFloat (const SubRectangleIteratorFloat&);
  67261. SubRectangleIteratorFloat& operator= (const SubRectangleIteratorFloat&);
  67262. };
  67263. ClipRegion_RectangleList& operator= (const ClipRegion_RectangleList&);
  67264. };
  67265. }
  67266. class LowLevelGraphicsSoftwareRenderer::SavedState
  67267. {
  67268. public:
  67269. SavedState (const Rectangle<int>& clip_, const int xOffset_, const int yOffset_)
  67270. : clip (new SoftwareRendererClasses::ClipRegion_RectangleList (clip_)),
  67271. xOffset (xOffset_), yOffset (yOffset_), interpolationQuality (Graphics::mediumResamplingQuality)
  67272. {
  67273. }
  67274. SavedState (const RectangleList& clip_, const int xOffset_, const int yOffset_)
  67275. : clip (new SoftwareRendererClasses::ClipRegion_RectangleList (clip_)),
  67276. xOffset (xOffset_), yOffset (yOffset_), interpolationQuality (Graphics::mediumResamplingQuality)
  67277. {
  67278. }
  67279. SavedState (const SavedState& other)
  67280. : clip (other.clip), xOffset (other.xOffset), yOffset (other.yOffset), font (other.font),
  67281. fillType (other.fillType), interpolationQuality (other.interpolationQuality)
  67282. {
  67283. }
  67284. ~SavedState()
  67285. {
  67286. }
  67287. void setOrigin (const int x, const int y) throw()
  67288. {
  67289. xOffset += x;
  67290. yOffset += y;
  67291. }
  67292. bool clipToRectangle (const Rectangle<int>& r)
  67293. {
  67294. if (clip != 0)
  67295. {
  67296. cloneClipIfMultiplyReferenced();
  67297. clip = clip->clipToRectangle (r.translated (xOffset, yOffset));
  67298. }
  67299. return clip != 0;
  67300. }
  67301. bool clipToRectangleList (const RectangleList& r)
  67302. {
  67303. if (clip != 0)
  67304. {
  67305. cloneClipIfMultiplyReferenced();
  67306. RectangleList offsetList (r);
  67307. offsetList.offsetAll (xOffset, yOffset);
  67308. clip = clip->clipToRectangleList (offsetList);
  67309. }
  67310. return clip != 0;
  67311. }
  67312. bool excludeClipRectangle (const Rectangle<int>& r)
  67313. {
  67314. if (clip != 0)
  67315. {
  67316. cloneClipIfMultiplyReferenced();
  67317. clip = clip->excludeClipRectangle (r.translated (xOffset, yOffset));
  67318. }
  67319. return clip != 0;
  67320. }
  67321. void clipToPath (const Path& p, const AffineTransform& transform)
  67322. {
  67323. if (clip != 0)
  67324. {
  67325. cloneClipIfMultiplyReferenced();
  67326. clip = clip->clipToPath (p, transform.translated ((float) xOffset, (float) yOffset));
  67327. }
  67328. }
  67329. void clipToImageAlpha (const Image& image, const Rectangle<int>& srcClip, const AffineTransform& t)
  67330. {
  67331. if (clip != 0)
  67332. {
  67333. if (image.hasAlphaChannel())
  67334. {
  67335. cloneClipIfMultiplyReferenced();
  67336. clip = clip->clipToImageAlpha (image, srcClip, t.translated ((float) xOffset, (float) yOffset),
  67337. interpolationQuality != Graphics::lowResamplingQuality);
  67338. }
  67339. else
  67340. {
  67341. Path p;
  67342. p.addRectangle (srcClip);
  67343. clipToPath (p, t);
  67344. }
  67345. }
  67346. }
  67347. bool clipRegionIntersects (const Rectangle<int>& r) const
  67348. {
  67349. return clip != 0 && clip->clipRegionIntersects (r.translated (xOffset, yOffset));
  67350. }
  67351. const Rectangle<int> getClipBounds() const
  67352. {
  67353. return clip == 0 ? Rectangle<int>() : clip->getClipBounds().translated (-xOffset, -yOffset);
  67354. }
  67355. void fillRect (Image& image, const Rectangle<int>& r, const bool replaceContents)
  67356. {
  67357. if (clip != 0)
  67358. {
  67359. if (fillType.isColour())
  67360. {
  67361. Image::BitmapData destData (image, 0, 0, image.getWidth(), image.getHeight(), true);
  67362. clip->fillRectWithColour (destData, r.translated (xOffset, yOffset), fillType.colour.getPixelARGB(), replaceContents);
  67363. }
  67364. else
  67365. {
  67366. const Rectangle<int> totalClip (clip->getClipBounds());
  67367. const Rectangle<int> clipped (totalClip.getIntersection (r.translated (xOffset, yOffset)));
  67368. if (! clipped.isEmpty())
  67369. fillShape (image, new SoftwareRendererClasses::ClipRegion_RectangleList (clipped), false);
  67370. }
  67371. }
  67372. }
  67373. void fillRect (Image& image, const Rectangle<float>& r)
  67374. {
  67375. if (clip != 0)
  67376. {
  67377. if (fillType.isColour())
  67378. {
  67379. Image::BitmapData destData (image, 0, 0, image.getWidth(), image.getHeight(), true);
  67380. clip->fillRectWithColour (destData, r.translated ((float) xOffset, (float) yOffset), fillType.colour.getPixelARGB());
  67381. }
  67382. else
  67383. {
  67384. const Rectangle<float> totalClip (clip->getClipBounds().toFloat());
  67385. const Rectangle<float> clipped (totalClip.getIntersection (r.translated ((float) xOffset, (float) yOffset)));
  67386. if (! clipped.isEmpty())
  67387. fillShape (image, new SoftwareRendererClasses::ClipRegion_EdgeTable (clipped), false);
  67388. }
  67389. }
  67390. }
  67391. void fillPath (Image& image, const Path& path, const AffineTransform& transform)
  67392. {
  67393. if (clip != 0)
  67394. fillShape (image, new SoftwareRendererClasses::ClipRegion_EdgeTable (clip->getClipBounds(), path, transform.translated ((float) xOffset, (float) yOffset)), false);
  67395. }
  67396. void fillEdgeTable (Image& image, const EdgeTable& edgeTable, const float x, const int y)
  67397. {
  67398. if (clip != 0)
  67399. {
  67400. SoftwareRendererClasses::ClipRegion_EdgeTable* edgeTableClip = new SoftwareRendererClasses::ClipRegion_EdgeTable (edgeTable);
  67401. SoftwareRendererClasses::ClipRegionBase::Ptr shapeToFill (edgeTableClip);
  67402. edgeTableClip->edgeTable.translate (x + xOffset, y + yOffset);
  67403. fillShape (image, shapeToFill, false);
  67404. }
  67405. }
  67406. void fillShape (Image& image, SoftwareRendererClasses::ClipRegionBase::Ptr shapeToFill, const bool replaceContents)
  67407. {
  67408. jassert (clip != 0);
  67409. shapeToFill = clip->applyClipTo (shapeToFill);
  67410. if (shapeToFill != 0)
  67411. {
  67412. Image::BitmapData destData (image, 0, 0, image.getWidth(), image.getHeight(), true);
  67413. if (fillType.isGradient())
  67414. {
  67415. jassert (! replaceContents); // that option is just for solid colours
  67416. ColourGradient g2 (*(fillType.gradient));
  67417. g2.multiplyOpacity (fillType.getOpacity());
  67418. g2.point1.addXY (-0.5f, -0.5f);
  67419. g2.point2.addXY (-0.5f, -0.5f);
  67420. AffineTransform transform (fillType.transform.translated ((float) xOffset, (float) yOffset));
  67421. const bool isIdentity = transform.isOnlyTranslation();
  67422. if (isIdentity)
  67423. {
  67424. // If our translation doesn't involve any distortion, we can speed it up..
  67425. g2.point1.applyTransform (transform);
  67426. g2.point2.applyTransform (transform);
  67427. transform = AffineTransform::identity;
  67428. }
  67429. shapeToFill->fillAllWithGradient (destData, g2, transform, isIdentity);
  67430. }
  67431. else if (fillType.isTiledImage())
  67432. {
  67433. renderImage (image, fillType.image, fillType.image.getBounds(), fillType.transform, shapeToFill);
  67434. }
  67435. else
  67436. {
  67437. shapeToFill->fillAllWithColour (destData, fillType.colour.getPixelARGB(), replaceContents);
  67438. }
  67439. }
  67440. }
  67441. void renderImage (Image& destImage, const Image& sourceImage, const Rectangle<int>& srcClip,
  67442. const AffineTransform& t, const SoftwareRendererClasses::ClipRegionBase* const tiledFillClipRegion)
  67443. {
  67444. const AffineTransform transform (t.translated ((float) xOffset, (float) yOffset));
  67445. const Image::BitmapData destData (destImage, 0, 0, destImage.getWidth(), destImage.getHeight(), true);
  67446. const Image::BitmapData srcData (sourceImage, srcClip.getX(), srcClip.getY(), srcClip.getWidth(), srcClip.getHeight());
  67447. const int alpha = fillType.colour.getAlpha();
  67448. const bool betterQuality = (interpolationQuality != Graphics::lowResamplingQuality);
  67449. if (transform.isOnlyTranslation())
  67450. {
  67451. // If our translation doesn't involve any distortion, just use a simple blit..
  67452. int tx = (int) (transform.getTranslationX() * 256.0f);
  67453. int ty = (int) (transform.getTranslationY() * 256.0f);
  67454. if ((! betterQuality) || ((tx | ty) & 224) == 0)
  67455. {
  67456. tx = ((tx + 128) >> 8);
  67457. ty = ((ty + 128) >> 8);
  67458. if (tiledFillClipRegion != 0)
  67459. {
  67460. tiledFillClipRegion->renderImageUntransformed (destData, srcData, alpha, tx, ty, true);
  67461. }
  67462. else
  67463. {
  67464. SoftwareRendererClasses::ClipRegionBase::Ptr c (new SoftwareRendererClasses::ClipRegion_EdgeTable (Rectangle<int> (tx, ty, srcClip.getWidth(), srcClip.getHeight()).getIntersection (destImage.getBounds())));
  67465. c = clip->applyClipTo (c);
  67466. if (c != 0)
  67467. c->renderImageUntransformed (destData, srcData, alpha, tx, ty, false);
  67468. }
  67469. return;
  67470. }
  67471. }
  67472. if (transform.isSingularity())
  67473. return;
  67474. if (tiledFillClipRegion != 0)
  67475. {
  67476. tiledFillClipRegion->renderImageTransformed (destData, srcData, alpha, transform, betterQuality, true);
  67477. }
  67478. else
  67479. {
  67480. Path p;
  67481. p.addRectangle (srcClip);
  67482. SoftwareRendererClasses::ClipRegionBase::Ptr c (clip->clone());
  67483. c = c->clipToPath (p, transform);
  67484. if (c != 0)
  67485. c->renderImageTransformed (destData, srcData, alpha, transform, betterQuality, false);
  67486. }
  67487. }
  67488. SoftwareRendererClasses::ClipRegionBase::Ptr clip;
  67489. int xOffset, yOffset;
  67490. Font font;
  67491. FillType fillType;
  67492. Graphics::ResamplingQuality interpolationQuality;
  67493. private:
  67494. void cloneClipIfMultiplyReferenced()
  67495. {
  67496. if (clip->getReferenceCount() > 1)
  67497. clip = clip->clone();
  67498. }
  67499. SavedState& operator= (const SavedState&);
  67500. };
  67501. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (const Image& image_)
  67502. : image (image_)
  67503. {
  67504. currentState = new SavedState (image_.getBounds(), 0, 0);
  67505. }
  67506. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (const Image& image_, const int xOffset, const int yOffset,
  67507. const RectangleList& initialClip)
  67508. : image (image_)
  67509. {
  67510. currentState = new SavedState (initialClip, xOffset, yOffset);
  67511. }
  67512. LowLevelGraphicsSoftwareRenderer::~LowLevelGraphicsSoftwareRenderer()
  67513. {
  67514. }
  67515. bool LowLevelGraphicsSoftwareRenderer::isVectorDevice() const
  67516. {
  67517. return false;
  67518. }
  67519. void LowLevelGraphicsSoftwareRenderer::setOrigin (int x, int y)
  67520. {
  67521. currentState->setOrigin (x, y);
  67522. }
  67523. bool LowLevelGraphicsSoftwareRenderer::clipToRectangle (const Rectangle<int>& r)
  67524. {
  67525. return currentState->clipToRectangle (r);
  67526. }
  67527. bool LowLevelGraphicsSoftwareRenderer::clipToRectangleList (const RectangleList& clipRegion)
  67528. {
  67529. return currentState->clipToRectangleList (clipRegion);
  67530. }
  67531. void LowLevelGraphicsSoftwareRenderer::excludeClipRectangle (const Rectangle<int>& r)
  67532. {
  67533. currentState->excludeClipRectangle (r);
  67534. }
  67535. void LowLevelGraphicsSoftwareRenderer::clipToPath (const Path& path, const AffineTransform& transform)
  67536. {
  67537. currentState->clipToPath (path, transform);
  67538. }
  67539. void LowLevelGraphicsSoftwareRenderer::clipToImageAlpha (const Image& sourceImage, const Rectangle<int>& srcClip, const AffineTransform& transform)
  67540. {
  67541. currentState->clipToImageAlpha (sourceImage, srcClip, transform);
  67542. }
  67543. bool LowLevelGraphicsSoftwareRenderer::clipRegionIntersects (const Rectangle<int>& r)
  67544. {
  67545. return currentState->clipRegionIntersects (r);
  67546. }
  67547. const Rectangle<int> LowLevelGraphicsSoftwareRenderer::getClipBounds() const
  67548. {
  67549. return currentState->getClipBounds();
  67550. }
  67551. bool LowLevelGraphicsSoftwareRenderer::isClipEmpty() const
  67552. {
  67553. return currentState->clip == 0;
  67554. }
  67555. void LowLevelGraphicsSoftwareRenderer::saveState()
  67556. {
  67557. stateStack.add (new SavedState (*currentState));
  67558. }
  67559. void LowLevelGraphicsSoftwareRenderer::restoreState()
  67560. {
  67561. SavedState* const top = stateStack.getLast();
  67562. if (top != 0)
  67563. {
  67564. currentState = top;
  67565. stateStack.removeLast (1, false);
  67566. }
  67567. else
  67568. {
  67569. jassertfalse; // trying to pop with an empty stack!
  67570. }
  67571. }
  67572. void LowLevelGraphicsSoftwareRenderer::setFill (const FillType& fillType)
  67573. {
  67574. currentState->fillType = fillType;
  67575. }
  67576. void LowLevelGraphicsSoftwareRenderer::setOpacity (float newOpacity)
  67577. {
  67578. currentState->fillType.setOpacity (newOpacity);
  67579. }
  67580. void LowLevelGraphicsSoftwareRenderer::setInterpolationQuality (Graphics::ResamplingQuality quality)
  67581. {
  67582. currentState->interpolationQuality = quality;
  67583. }
  67584. void LowLevelGraphicsSoftwareRenderer::fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  67585. {
  67586. currentState->fillRect (image, r, replaceExistingContents);
  67587. }
  67588. void LowLevelGraphicsSoftwareRenderer::fillPath (const Path& path, const AffineTransform& transform)
  67589. {
  67590. currentState->fillPath (image, path, transform);
  67591. }
  67592. void LowLevelGraphicsSoftwareRenderer::drawImage (const Image& sourceImage, const Rectangle<int>& srcClip,
  67593. const AffineTransform& transform, const bool fillEntireClipAsTiles)
  67594. {
  67595. jassert (sourceImage.getBounds().contains (srcClip));
  67596. currentState->renderImage (image, sourceImage, srcClip, transform,
  67597. fillEntireClipAsTiles ? currentState->clip : 0);
  67598. }
  67599. void LowLevelGraphicsSoftwareRenderer::drawLine (const Line <float>& line)
  67600. {
  67601. Path p;
  67602. p.addLineSegment (line, 1.0f);
  67603. fillPath (p, AffineTransform::identity);
  67604. }
  67605. void LowLevelGraphicsSoftwareRenderer::drawVerticalLine (const int x, float top, float bottom)
  67606. {
  67607. if (bottom > top)
  67608. currentState->fillRect (image, Rectangle<float> ((float) x, top, 1.0f, bottom - top));
  67609. }
  67610. void LowLevelGraphicsSoftwareRenderer::drawHorizontalLine (const int y, float left, float right)
  67611. {
  67612. if (right > left)
  67613. currentState->fillRect (image, Rectangle<float> (left, (float) y, right - left, 1.0f));
  67614. }
  67615. class LowLevelGraphicsSoftwareRenderer::CachedGlyph
  67616. {
  67617. public:
  67618. CachedGlyph() : glyph (0), lastAccessCount (0) {}
  67619. ~CachedGlyph() {}
  67620. void draw (SavedState& state, Image& image, const float x, const float y) const
  67621. {
  67622. if (edgeTable != 0)
  67623. state.fillEdgeTable (image, *edgeTable, x, roundToInt (y));
  67624. }
  67625. void generate (const Font& newFont, const int glyphNumber)
  67626. {
  67627. font = newFont;
  67628. glyph = glyphNumber;
  67629. edgeTable = 0;
  67630. Path glyphPath;
  67631. font.getTypeface()->getOutlineForGlyph (glyphNumber, glyphPath);
  67632. if (! glyphPath.isEmpty())
  67633. {
  67634. const float fontHeight = font.getHeight();
  67635. const AffineTransform transform (AffineTransform::scale (fontHeight * font.getHorizontalScale(), fontHeight)
  67636. .translated (0.0f, -0.5f));
  67637. edgeTable = new EdgeTable (glyphPath.getBoundsTransformed (transform).getSmallestIntegerContainer().expanded (1, 0),
  67638. glyphPath, transform);
  67639. }
  67640. }
  67641. int glyph, lastAccessCount;
  67642. Font font;
  67643. juce_UseDebuggingNewOperator
  67644. private:
  67645. ScopedPointer <EdgeTable> edgeTable;
  67646. CachedGlyph (const CachedGlyph&);
  67647. CachedGlyph& operator= (const CachedGlyph&);
  67648. };
  67649. class LowLevelGraphicsSoftwareRenderer::GlyphCache : private DeletedAtShutdown
  67650. {
  67651. public:
  67652. GlyphCache()
  67653. : accessCounter (0), hits (0), misses (0)
  67654. {
  67655. for (int i = 120; --i >= 0;)
  67656. glyphs.add (new CachedGlyph());
  67657. }
  67658. ~GlyphCache()
  67659. {
  67660. clearSingletonInstance();
  67661. }
  67662. juce_DeclareSingleton_SingleThreaded_Minimal (GlyphCache);
  67663. void drawGlyph (SavedState& state, Image& image, const Font& font, const int glyphNumber, float x, float y)
  67664. {
  67665. ++accessCounter;
  67666. int oldestCounter = std::numeric_limits<int>::max();
  67667. CachedGlyph* oldest = 0;
  67668. for (int i = glyphs.size(); --i >= 0;)
  67669. {
  67670. CachedGlyph* const glyph = glyphs.getUnchecked (i);
  67671. if (glyph->glyph == glyphNumber && glyph->font == font)
  67672. {
  67673. ++hits;
  67674. glyph->lastAccessCount = accessCounter;
  67675. glyph->draw (state, image, x, y);
  67676. return;
  67677. }
  67678. if (glyph->lastAccessCount <= oldestCounter)
  67679. {
  67680. oldestCounter = glyph->lastAccessCount;
  67681. oldest = glyph;
  67682. }
  67683. }
  67684. if (hits + ++misses > (glyphs.size() << 4))
  67685. {
  67686. if (misses * 2 > hits)
  67687. {
  67688. for (int i = 32; --i >= 0;)
  67689. glyphs.add (new CachedGlyph());
  67690. }
  67691. hits = misses = 0;
  67692. oldest = glyphs.getLast();
  67693. }
  67694. jassert (oldest != 0);
  67695. oldest->lastAccessCount = accessCounter;
  67696. oldest->generate (font, glyphNumber);
  67697. oldest->draw (state, image, x, y);
  67698. }
  67699. juce_UseDebuggingNewOperator
  67700. private:
  67701. friend class OwnedArray <CachedGlyph>;
  67702. OwnedArray <CachedGlyph> glyphs;
  67703. int accessCounter, hits, misses;
  67704. GlyphCache (const GlyphCache&);
  67705. GlyphCache& operator= (const GlyphCache&);
  67706. };
  67707. juce_ImplementSingleton_SingleThreaded (LowLevelGraphicsSoftwareRenderer::GlyphCache);
  67708. void LowLevelGraphicsSoftwareRenderer::setFont (const Font& newFont)
  67709. {
  67710. currentState->font = newFont;
  67711. }
  67712. const Font LowLevelGraphicsSoftwareRenderer::getFont()
  67713. {
  67714. return currentState->font;
  67715. }
  67716. void LowLevelGraphicsSoftwareRenderer::drawGlyph (int glyphNumber, const AffineTransform& transform)
  67717. {
  67718. Font& f = currentState->font;
  67719. if (transform.isOnlyTranslation())
  67720. {
  67721. GlyphCache::getInstance()->drawGlyph (*currentState, image, f, glyphNumber,
  67722. transform.getTranslationX(),
  67723. transform.getTranslationY());
  67724. }
  67725. else
  67726. {
  67727. Path p;
  67728. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  67729. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight()).followedBy (transform));
  67730. }
  67731. }
  67732. #if JUCE_MSVC
  67733. #pragma warning (pop)
  67734. #if JUCE_DEBUG
  67735. #pragma optimize ("", on) // resets optimisations to the project defaults
  67736. #endif
  67737. #endif
  67738. END_JUCE_NAMESPACE
  67739. /*** End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp ***/
  67740. /*** Start of inlined file: juce_RectanglePlacement.cpp ***/
  67741. BEGIN_JUCE_NAMESPACE
  67742. RectanglePlacement::RectanglePlacement (const RectanglePlacement& other) throw()
  67743. : flags (other.flags)
  67744. {
  67745. }
  67746. RectanglePlacement& RectanglePlacement::operator= (const RectanglePlacement& other) throw()
  67747. {
  67748. flags = other.flags;
  67749. return *this;
  67750. }
  67751. void RectanglePlacement::applyTo (double& x, double& y,
  67752. double& w, double& h,
  67753. const double dx, const double dy,
  67754. const double dw, const double dh) const throw()
  67755. {
  67756. if (w == 0 || h == 0)
  67757. return;
  67758. if ((flags & stretchToFit) != 0)
  67759. {
  67760. x = dx;
  67761. y = dy;
  67762. w = dw;
  67763. h = dh;
  67764. }
  67765. else
  67766. {
  67767. double scale = (flags & fillDestination) != 0 ? jmax (dw / w, dh / h)
  67768. : jmin (dw / w, dh / h);
  67769. if ((flags & onlyReduceInSize) != 0)
  67770. scale = jmin (scale, 1.0);
  67771. if ((flags & onlyIncreaseInSize) != 0)
  67772. scale = jmax (scale, 1.0);
  67773. w *= scale;
  67774. h *= scale;
  67775. if ((flags & xLeft) != 0)
  67776. x = dx;
  67777. else if ((flags & xRight) != 0)
  67778. x = dx + dw - w;
  67779. else
  67780. x = dx + (dw - w) * 0.5;
  67781. if ((flags & yTop) != 0)
  67782. y = dy;
  67783. else if ((flags & yBottom) != 0)
  67784. y = dy + dh - h;
  67785. else
  67786. y = dy + (dh - h) * 0.5;
  67787. }
  67788. }
  67789. const AffineTransform RectanglePlacement::getTransformToFit (float x, float y,
  67790. float w, float h,
  67791. const float dx, const float dy,
  67792. const float dw, const float dh) const throw()
  67793. {
  67794. if (w == 0 || h == 0)
  67795. return AffineTransform::identity;
  67796. const float scaleX = dw / w;
  67797. const float scaleY = dh / h;
  67798. if ((flags & stretchToFit) != 0)
  67799. return AffineTransform::translation (-x, -y)
  67800. .scaled (scaleX, scaleY)
  67801. .translated (dx, dy);
  67802. float scale = (flags & fillDestination) != 0 ? jmax (scaleX, scaleY)
  67803. : jmin (scaleX, scaleY);
  67804. if ((flags & onlyReduceInSize) != 0)
  67805. scale = jmin (scale, 1.0f);
  67806. if ((flags & onlyIncreaseInSize) != 0)
  67807. scale = jmax (scale, 1.0f);
  67808. w *= scale;
  67809. h *= scale;
  67810. float newX = dx;
  67811. if ((flags & xRight) != 0)
  67812. newX += dw - w; // right
  67813. else if ((flags & xLeft) == 0)
  67814. newX += (dw - w) / 2.0f; // centre
  67815. float newY = dy;
  67816. if ((flags & yBottom) != 0)
  67817. newY += dh - h; // bottom
  67818. else if ((flags & yTop) == 0)
  67819. newY += (dh - h) / 2.0f; // centre
  67820. return AffineTransform::translation (-x, -y)
  67821. .scaled (scale, scale)
  67822. .translated (newX, newY);
  67823. }
  67824. END_JUCE_NAMESPACE
  67825. /*** End of inlined file: juce_RectanglePlacement.cpp ***/
  67826. /*** Start of inlined file: juce_Drawable.cpp ***/
  67827. BEGIN_JUCE_NAMESPACE
  67828. Drawable::RenderingContext::RenderingContext (Graphics& g_,
  67829. const AffineTransform& transform_,
  67830. const float opacity_) throw()
  67831. : g (g_),
  67832. transform (transform_),
  67833. opacity (opacity_)
  67834. {
  67835. }
  67836. Drawable::Drawable()
  67837. : parent (0)
  67838. {
  67839. }
  67840. Drawable::~Drawable()
  67841. {
  67842. }
  67843. void Drawable::draw (Graphics& g, const float opacity, const AffineTransform& transform) const
  67844. {
  67845. render (RenderingContext (g, transform, opacity));
  67846. }
  67847. void Drawable::drawAt (Graphics& g, const float x, const float y, const float opacity) const
  67848. {
  67849. draw (g, opacity, AffineTransform::translation (x, y));
  67850. }
  67851. void Drawable::drawWithin (Graphics& g,
  67852. const int destX,
  67853. const int destY,
  67854. const int destW,
  67855. const int destH,
  67856. const RectanglePlacement& placement,
  67857. const float opacity) const
  67858. {
  67859. if (destW > 0 && destH > 0)
  67860. {
  67861. Rectangle<float> bounds (getBounds());
  67862. draw (g, opacity,
  67863. placement.getTransformToFit (bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight(),
  67864. (float) destX, (float) destY,
  67865. (float) destW, (float) destH));
  67866. }
  67867. }
  67868. Drawable* Drawable::createFromImageData (const void* data, const size_t numBytes)
  67869. {
  67870. Drawable* result = 0;
  67871. Image image (ImageFileFormat::loadFrom (data, (int) numBytes));
  67872. if (image.isValid())
  67873. {
  67874. DrawableImage* const di = new DrawableImage();
  67875. di->setImage (image);
  67876. result = di;
  67877. }
  67878. else
  67879. {
  67880. const String asString (String::createStringFromData (data, (int) numBytes));
  67881. XmlDocument doc (asString);
  67882. ScopedPointer <XmlElement> outer (doc.getDocumentElement (true));
  67883. if (outer != 0 && outer->hasTagName ("svg"))
  67884. {
  67885. ScopedPointer <XmlElement> svg (doc.getDocumentElement());
  67886. if (svg != 0)
  67887. result = Drawable::createFromSVG (*svg);
  67888. }
  67889. }
  67890. return result;
  67891. }
  67892. Drawable* Drawable::createFromImageDataStream (InputStream& dataSource)
  67893. {
  67894. MemoryBlock mb;
  67895. dataSource.readIntoMemoryBlock (mb);
  67896. return createFromImageData (mb.getData(), mb.getSize());
  67897. }
  67898. Drawable* Drawable::createFromImageFile (const File& file)
  67899. {
  67900. const ScopedPointer <FileInputStream> fin (file.createInputStream());
  67901. return fin != 0 ? createFromImageDataStream (*fin) : 0;
  67902. }
  67903. Drawable* Drawable::createFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  67904. {
  67905. return createChildFromValueTree (0, tree, imageProvider);
  67906. }
  67907. Drawable* Drawable::createChildFromValueTree (DrawableComposite* parent, const ValueTree& tree, ImageProvider* imageProvider)
  67908. {
  67909. const Identifier type (tree.getType());
  67910. Drawable* d = 0;
  67911. if (type == DrawablePath::valueTreeType)
  67912. d = new DrawablePath();
  67913. else if (type == DrawableComposite::valueTreeType)
  67914. d = new DrawableComposite();
  67915. else if (type == DrawableImage::valueTreeType)
  67916. d = new DrawableImage();
  67917. else if (type == DrawableText::valueTreeType)
  67918. d = new DrawableText();
  67919. if (d != 0)
  67920. {
  67921. d->parent = parent;
  67922. d->refreshFromValueTree (tree, imageProvider);
  67923. }
  67924. return d;
  67925. }
  67926. const Identifier Drawable::ValueTreeWrapperBase::idProperty ("id");
  67927. const Identifier Drawable::ValueTreeWrapperBase::type ("type");
  67928. const Identifier Drawable::ValueTreeWrapperBase::gradientPoint1 ("point1");
  67929. const Identifier Drawable::ValueTreeWrapperBase::gradientPoint2 ("point2");
  67930. const Identifier Drawable::ValueTreeWrapperBase::colour ("colour");
  67931. const Identifier Drawable::ValueTreeWrapperBase::radial ("radial");
  67932. const Identifier Drawable::ValueTreeWrapperBase::colours ("colours");
  67933. const Identifier Drawable::ValueTreeWrapperBase::imageId ("imageId");
  67934. const Identifier Drawable::ValueTreeWrapperBase::imageOpacity ("imageOpacity");
  67935. Drawable::ValueTreeWrapperBase::ValueTreeWrapperBase (const ValueTree& state_)
  67936. : state (state_)
  67937. {
  67938. }
  67939. Drawable::ValueTreeWrapperBase::~ValueTreeWrapperBase()
  67940. {
  67941. }
  67942. const String Drawable::ValueTreeWrapperBase::getID() const
  67943. {
  67944. return state [idProperty];
  67945. }
  67946. void Drawable::ValueTreeWrapperBase::setID (const String& newID, UndoManager* const undoManager)
  67947. {
  67948. if (newID.isEmpty())
  67949. state.removeProperty (idProperty, undoManager);
  67950. else
  67951. state.setProperty (idProperty, newID, undoManager);
  67952. }
  67953. const FillType Drawable::ValueTreeWrapperBase::readFillType (const ValueTree& v, RelativePoint* const gp1, RelativePoint* const gp2,
  67954. RelativeCoordinate::NamedCoordinateFinder* const nameFinder, ImageProvider* imageProvider)
  67955. {
  67956. const String newType (v[type].toString());
  67957. if (newType == "solid")
  67958. {
  67959. const String colourString (v [colour].toString());
  67960. return FillType (Colour (colourString.isEmpty() ? (uint32) 0xff000000
  67961. : (uint32) colourString.getHexValue32()));
  67962. }
  67963. else if (newType == "gradient")
  67964. {
  67965. RelativePoint p1 (v [gradientPoint1]), p2 (v [gradientPoint2]);
  67966. ColourGradient g;
  67967. if (gp1 != 0)
  67968. *gp1 = p1;
  67969. if (gp2 != 0)
  67970. *gp2 = p2;
  67971. g.point1 = p1.resolve (nameFinder);
  67972. g.point2 = p2.resolve (nameFinder);
  67973. g.isRadial = v[radial];
  67974. StringArray colourSteps;
  67975. colourSteps.addTokens (v[colours].toString(), false);
  67976. for (int i = 0; i < colourSteps.size() / 2; ++i)
  67977. g.addColour (colourSteps[i * 2].getDoubleValue(),
  67978. Colour ((uint32) colourSteps[i * 2 + 1].getHexValue32()));
  67979. return FillType (g);
  67980. }
  67981. else if (newType == "image")
  67982. {
  67983. Image im;
  67984. if (imageProvider != 0)
  67985. im = imageProvider->getImageForIdentifier (v[imageId]);
  67986. FillType f (im, AffineTransform::identity);
  67987. f.setOpacity ((float) v.getProperty (imageOpacity, 1.0f));
  67988. return f;
  67989. }
  67990. jassertfalse;
  67991. return FillType();
  67992. }
  67993. void Drawable::ValueTreeWrapperBase::writeFillType (ValueTree& v, const FillType& fillType,
  67994. const RelativePoint* const gp1, const RelativePoint* const gp2,
  67995. ImageProvider* imageProvider, UndoManager* const undoManager)
  67996. {
  67997. if (fillType.isColour())
  67998. {
  67999. v.setProperty (type, "solid", undoManager);
  68000. v.setProperty (colour, String::toHexString ((int) fillType.colour.getARGB()), undoManager);
  68001. }
  68002. else if (fillType.isGradient())
  68003. {
  68004. v.setProperty (type, "gradient", undoManager);
  68005. v.setProperty (gradientPoint1, gp1 != 0 ? gp1->toString() : fillType.gradient->point1.toString(), undoManager);
  68006. v.setProperty (gradientPoint2, gp2 != 0 ? gp2->toString() : fillType.gradient->point2.toString(), undoManager);
  68007. v.setProperty (radial, fillType.gradient->isRadial, undoManager);
  68008. String s;
  68009. for (int i = 0; i < fillType.gradient->getNumColours(); ++i)
  68010. s << ' ' << fillType.gradient->getColourPosition (i)
  68011. << ' ' << String::toHexString ((int) fillType.gradient->getColour(i).getARGB());
  68012. v.setProperty (colours, s.trimStart(), undoManager);
  68013. }
  68014. else if (fillType.isTiledImage())
  68015. {
  68016. v.setProperty (type, "image", undoManager);
  68017. if (imageProvider != 0)
  68018. v.setProperty (imageId, imageProvider->getIdentifierForImage (fillType.image), undoManager);
  68019. if (fillType.getOpacity() < 1.0f)
  68020. v.setProperty (imageOpacity, fillType.getOpacity(), undoManager);
  68021. else
  68022. v.removeProperty (imageOpacity, undoManager);
  68023. }
  68024. else
  68025. {
  68026. jassertfalse;
  68027. }
  68028. }
  68029. END_JUCE_NAMESPACE
  68030. /*** End of inlined file: juce_Drawable.cpp ***/
  68031. /*** Start of inlined file: juce_DrawableComposite.cpp ***/
  68032. BEGIN_JUCE_NAMESPACE
  68033. DrawableComposite::DrawableComposite()
  68034. : bounds (Point<float>(), Point<float> (100.0f, 0.0f), Point<float> (0.0f, 100.0f))
  68035. {
  68036. setContentArea (RelativeRectangle (RelativeCoordinate (0.0, true),
  68037. RelativeCoordinate (100.0, true),
  68038. RelativeCoordinate (0.0, false),
  68039. RelativeCoordinate (100.0, false)));
  68040. }
  68041. DrawableComposite::DrawableComposite (const DrawableComposite& other)
  68042. {
  68043. bounds = other.bounds;
  68044. for (int i = 0; i < other.drawables.size(); ++i)
  68045. drawables.add (other.drawables.getUnchecked(i)->createCopy());
  68046. markersX.addCopiesOf (other.markersX);
  68047. markersY.addCopiesOf (other.markersY);
  68048. }
  68049. DrawableComposite::~DrawableComposite()
  68050. {
  68051. }
  68052. void DrawableComposite::insertDrawable (Drawable* drawable, const int index)
  68053. {
  68054. if (drawable != 0)
  68055. {
  68056. jassert (! drawables.contains (drawable)); // trying to add a drawable that's already in here!
  68057. jassert (drawable->parent == 0); // A drawable can only live inside one parent at a time!
  68058. drawables.insert (index, drawable);
  68059. drawable->parent = this;
  68060. }
  68061. }
  68062. void DrawableComposite::insertDrawable (const Drawable& drawable, const int index)
  68063. {
  68064. insertDrawable (drawable.createCopy(), index);
  68065. }
  68066. void DrawableComposite::removeDrawable (const int index, const bool deleteDrawable)
  68067. {
  68068. drawables.remove (index, deleteDrawable);
  68069. }
  68070. Drawable* DrawableComposite::getDrawableWithName (const String& name) const throw()
  68071. {
  68072. for (int i = drawables.size(); --i >= 0;)
  68073. if (drawables.getUnchecked(i)->getName() == name)
  68074. return drawables.getUnchecked(i);
  68075. return 0;
  68076. }
  68077. void DrawableComposite::bringToFront (const int index)
  68078. {
  68079. if (index >= 0 && index < drawables.size() - 1)
  68080. drawables.move (index, -1);
  68081. }
  68082. void DrawableComposite::setBoundingBox (const RelativeParallelogram& newBoundingBox)
  68083. {
  68084. bounds = newBoundingBox;
  68085. }
  68086. DrawableComposite::Marker::Marker (const DrawableComposite::Marker& other)
  68087. : name (other.name), position (other.position)
  68088. {
  68089. }
  68090. DrawableComposite::Marker::Marker (const String& name_, const RelativeCoordinate& position_)
  68091. : name (name_), position (position_)
  68092. {
  68093. }
  68094. bool DrawableComposite::Marker::operator!= (const DrawableComposite::Marker& other) const throw()
  68095. {
  68096. return name != other.name || position != other.position;
  68097. }
  68098. const char* const DrawableComposite::contentLeftMarkerName ("left");
  68099. const char* const DrawableComposite::contentRightMarkerName ("right");
  68100. const char* const DrawableComposite::contentTopMarkerName ("top");
  68101. const char* const DrawableComposite::contentBottomMarkerName ("bottom");
  68102. const RelativeRectangle DrawableComposite::getContentArea() const
  68103. {
  68104. jassert (markersX.size() >= 2 && getMarker (true, 0)->name == contentLeftMarkerName && getMarker (true, 1)->name == contentRightMarkerName);
  68105. jassert (markersY.size() >= 2 && getMarker (false, 0)->name == contentTopMarkerName && getMarker (false, 1)->name == contentBottomMarkerName);
  68106. return RelativeRectangle (markersX.getUnchecked(0)->position, markersX.getUnchecked(1)->position,
  68107. markersY.getUnchecked(0)->position, markersY.getUnchecked(1)->position);
  68108. }
  68109. void DrawableComposite::setContentArea (const RelativeRectangle& newArea)
  68110. {
  68111. setMarker (contentLeftMarkerName, true, newArea.left);
  68112. setMarker (contentRightMarkerName, true, newArea.right);
  68113. setMarker (contentTopMarkerName, false, newArea.top);
  68114. setMarker (contentBottomMarkerName, false, newArea.bottom);
  68115. }
  68116. void DrawableComposite::resetBoundingBoxToContentArea()
  68117. {
  68118. const RelativeRectangle content (getContentArea());
  68119. setBoundingBox (RelativeParallelogram (RelativePoint (content.left, content.top),
  68120. RelativePoint (content.right, content.top),
  68121. RelativePoint (content.left, content.bottom)));
  68122. }
  68123. void DrawableComposite::resetContentAreaAndBoundingBoxToFitChildren()
  68124. {
  68125. const Rectangle<float> bounds (getUntransformedBounds (false));
  68126. setContentArea (RelativeRectangle (RelativeCoordinate (bounds.getX(), true),
  68127. RelativeCoordinate (bounds.getRight(), true),
  68128. RelativeCoordinate (bounds.getY(), false),
  68129. RelativeCoordinate (bounds.getBottom(), false)));
  68130. resetBoundingBoxToContentArea();
  68131. }
  68132. int DrawableComposite::getNumMarkers (const bool xAxis) const throw()
  68133. {
  68134. return (xAxis ? markersX : markersY).size();
  68135. }
  68136. const DrawableComposite::Marker* DrawableComposite::getMarker (const bool xAxis, const int index) const throw()
  68137. {
  68138. return (xAxis ? markersX : markersY) [index];
  68139. }
  68140. void DrawableComposite::setMarker (const String& name, const bool xAxis, const RelativeCoordinate& position)
  68141. {
  68142. OwnedArray <Marker>& markers = (xAxis ? markersX : markersY);
  68143. for (int i = 0; i < markers.size(); ++i)
  68144. {
  68145. Marker* const m = markers.getUnchecked(i);
  68146. if (m->name == name)
  68147. {
  68148. if (m->position != position)
  68149. {
  68150. m->position = position;
  68151. invalidatePoints();
  68152. }
  68153. return;
  68154. }
  68155. }
  68156. (xAxis ? markersX : markersY).add (new Marker (name, position));
  68157. invalidatePoints();
  68158. }
  68159. void DrawableComposite::removeMarker (const bool xAxis, const int index)
  68160. {
  68161. jassert (index >= 2);
  68162. if (index >= 2)
  68163. (xAxis ? markersX : markersY).remove (index);
  68164. }
  68165. const AffineTransform DrawableComposite::calculateTransform() const
  68166. {
  68167. Point<float> resolved[3];
  68168. bounds.resolveThreePoints (resolved, parent);
  68169. const Rectangle<float> content (getContentArea().resolve (parent));
  68170. return AffineTransform::fromTargetPoints (content.getX(), content.getY(), resolved[0].getX(), resolved[0].getY(),
  68171. content.getRight(), content.getY(), resolved[1].getX(), resolved[1].getY(),
  68172. content.getX(), content.getBottom(), resolved[2].getX(), resolved[2].getY());
  68173. }
  68174. void DrawableComposite::render (const Drawable::RenderingContext& context) const
  68175. {
  68176. if (drawables.size() > 0 && context.opacity > 0)
  68177. {
  68178. if (context.opacity >= 1.0f || drawables.size() == 1)
  68179. {
  68180. Drawable::RenderingContext contextCopy (context);
  68181. contextCopy.transform = calculateTransform().followedBy (context.transform);
  68182. for (int i = 0; i < drawables.size(); ++i)
  68183. drawables.getUnchecked(i)->render (contextCopy);
  68184. }
  68185. else
  68186. {
  68187. // To correctly render a whole composite layer with an overall transparency,
  68188. // we need to render everything opaquely into a temp buffer, then blend that
  68189. // with the target opacity...
  68190. const Rectangle<int> clipBounds (context.g.getClipBounds());
  68191. Image tempImage (Image::ARGB, clipBounds.getWidth(), clipBounds.getHeight(), true);
  68192. {
  68193. Graphics tempG (tempImage);
  68194. tempG.setOrigin (-clipBounds.getX(), -clipBounds.getY());
  68195. Drawable::RenderingContext tempContext (tempG, context.transform, 1.0f);
  68196. render (tempContext);
  68197. }
  68198. context.g.setOpacity (context.opacity);
  68199. context.g.drawImageAt (tempImage, clipBounds.getX(), clipBounds.getY());
  68200. }
  68201. }
  68202. }
  68203. const RelativeCoordinate DrawableComposite::findNamedCoordinate (const String& objectName, const String& edge) const
  68204. {
  68205. if (objectName == RelativeCoordinate::Strings::parent)
  68206. {
  68207. if (edge == RelativeCoordinate::Strings::right)
  68208. {
  68209. jassertfalse; // a Drawable doesn't have a fixed right-hand edge - use a marker instead if you need a point of reference.
  68210. return RelativeCoordinate (100.0, true);
  68211. }
  68212. if (edge == RelativeCoordinate::Strings::bottom)
  68213. {
  68214. jassertfalse; // a Drawable doesn't have a fixed bottom edge - use a marker instead if you need a point of reference.
  68215. return RelativeCoordinate (100.0, false);
  68216. }
  68217. }
  68218. int i;
  68219. for (i = 0; i < markersX.size(); ++i)
  68220. {
  68221. Marker* const m = markersX.getUnchecked(i);
  68222. if (m->name == objectName)
  68223. return m->position;
  68224. }
  68225. for (i = 0; i < markersY.size(); ++i)
  68226. {
  68227. Marker* const m = markersY.getUnchecked(i);
  68228. if (m->name == objectName)
  68229. return m->position;
  68230. }
  68231. return RelativeCoordinate();
  68232. }
  68233. const Rectangle<float> DrawableComposite::getUntransformedBounds (const bool includeMarkers) const
  68234. {
  68235. Rectangle<float> bounds;
  68236. int i;
  68237. for (i = 0; i < drawables.size(); ++i)
  68238. bounds = bounds.getUnion (drawables.getUnchecked(i)->getBounds());
  68239. if (includeMarkers)
  68240. {
  68241. if (markersX.size() > 0)
  68242. {
  68243. float minX = std::numeric_limits<float>::max();
  68244. float maxX = std::numeric_limits<float>::min();
  68245. for (i = markersX.size(); --i >= 0;)
  68246. {
  68247. const Marker* m = markersX.getUnchecked(i);
  68248. const float pos = (float) m->position.resolve (parent);
  68249. minX = jmin (minX, pos);
  68250. maxX = jmax (maxX, pos);
  68251. }
  68252. if (minX <= maxX)
  68253. {
  68254. if (bounds.getHeight() > 0)
  68255. {
  68256. minX = jmin (minX, bounds.getX());
  68257. maxX = jmax (maxX, bounds.getRight());
  68258. }
  68259. bounds.setLeft (minX);
  68260. bounds.setWidth (maxX - minX);
  68261. }
  68262. }
  68263. if (markersY.size() > 0)
  68264. {
  68265. float minY = std::numeric_limits<float>::max();
  68266. float maxY = std::numeric_limits<float>::min();
  68267. for (i = markersY.size(); --i >= 0;)
  68268. {
  68269. const Marker* m = markersY.getUnchecked(i);
  68270. const float pos = (float) m->position.resolve (parent);
  68271. minY = jmin (minY, pos);
  68272. maxY = jmax (maxY, pos);
  68273. }
  68274. if (minY <= maxY)
  68275. {
  68276. if (bounds.getHeight() > 0)
  68277. {
  68278. minY = jmin (minY, bounds.getY());
  68279. maxY = jmax (maxY, bounds.getBottom());
  68280. }
  68281. bounds.setTop (minY);
  68282. bounds.setHeight (maxY - minY);
  68283. }
  68284. }
  68285. }
  68286. return bounds;
  68287. }
  68288. const Rectangle<float> DrawableComposite::getBounds() const
  68289. {
  68290. return getUntransformedBounds (true).transformed (calculateTransform());
  68291. }
  68292. bool DrawableComposite::hitTest (float x, float y) const
  68293. {
  68294. calculateTransform().inverted().transformPoint (x, y);
  68295. for (int i = 0; i < drawables.size(); ++i)
  68296. if (drawables.getUnchecked(i)->hitTest (x, y))
  68297. return true;
  68298. return false;
  68299. }
  68300. Drawable* DrawableComposite::createCopy() const
  68301. {
  68302. return new DrawableComposite (*this);
  68303. }
  68304. void DrawableComposite::invalidatePoints()
  68305. {
  68306. for (int i = 0; i < drawables.size(); ++i)
  68307. drawables.getUnchecked(i)->invalidatePoints();
  68308. }
  68309. const Identifier DrawableComposite::valueTreeType ("Group");
  68310. const Identifier DrawableComposite::ValueTreeWrapper::topLeft ("topLeft");
  68311. const Identifier DrawableComposite::ValueTreeWrapper::topRight ("topRight");
  68312. const Identifier DrawableComposite::ValueTreeWrapper::bottomLeft ("bottomLeft");
  68313. const Identifier DrawableComposite::ValueTreeWrapper::childGroupTag ("Drawables");
  68314. const Identifier DrawableComposite::ValueTreeWrapper::markerGroupTagX ("MarkersX");
  68315. const Identifier DrawableComposite::ValueTreeWrapper::markerGroupTagY ("MarkersY");
  68316. const Identifier DrawableComposite::ValueTreeWrapper::markerTag ("Marker");
  68317. const Identifier DrawableComposite::ValueTreeWrapper::nameProperty ("name");
  68318. const Identifier DrawableComposite::ValueTreeWrapper::posProperty ("position");
  68319. DrawableComposite::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  68320. : ValueTreeWrapperBase (state_)
  68321. {
  68322. jassert (state.hasType (valueTreeType));
  68323. }
  68324. ValueTree DrawableComposite::ValueTreeWrapper::getChildList() const
  68325. {
  68326. return state.getChildWithName (childGroupTag);
  68327. }
  68328. ValueTree DrawableComposite::ValueTreeWrapper::getChildListCreating (UndoManager* undoManager)
  68329. {
  68330. return state.getOrCreateChildWithName (childGroupTag, undoManager);
  68331. }
  68332. int DrawableComposite::ValueTreeWrapper::getNumDrawables() const
  68333. {
  68334. return getChildList().getNumChildren();
  68335. }
  68336. ValueTree DrawableComposite::ValueTreeWrapper::getDrawableState (int index) const
  68337. {
  68338. return getChildList().getChild (index);
  68339. }
  68340. ValueTree DrawableComposite::ValueTreeWrapper::getDrawableWithId (const String& objectId, bool recursive) const
  68341. {
  68342. if (getID() == objectId)
  68343. return state;
  68344. if (! recursive)
  68345. {
  68346. return getChildList().getChildWithProperty (idProperty, objectId);
  68347. }
  68348. else
  68349. {
  68350. const ValueTree childList (getChildList());
  68351. for (int i = getNumDrawables(); --i >= 0;)
  68352. {
  68353. const ValueTree& child = childList.getChild (i);
  68354. if (child [Drawable::ValueTreeWrapperBase::idProperty] == objectId)
  68355. return child;
  68356. if (child.hasType (DrawableComposite::valueTreeType))
  68357. {
  68358. ValueTree v (DrawableComposite::ValueTreeWrapper (child).getDrawableWithId (objectId, true));
  68359. if (v.isValid())
  68360. return v;
  68361. }
  68362. }
  68363. return ValueTree::invalid;
  68364. }
  68365. }
  68366. int DrawableComposite::ValueTreeWrapper::indexOfDrawable (const ValueTree& item) const
  68367. {
  68368. return getChildList().indexOf (item);
  68369. }
  68370. void DrawableComposite::ValueTreeWrapper::addDrawable (const ValueTree& newDrawableState, int index, UndoManager* undoManager)
  68371. {
  68372. getChildListCreating (undoManager).addChild (newDrawableState, index, undoManager);
  68373. }
  68374. void DrawableComposite::ValueTreeWrapper::moveDrawableOrder (int currentIndex, int newIndex, UndoManager* undoManager)
  68375. {
  68376. getChildListCreating (undoManager).moveChild (currentIndex, newIndex, undoManager);
  68377. }
  68378. void DrawableComposite::ValueTreeWrapper::removeDrawable (const ValueTree& child, UndoManager* undoManager)
  68379. {
  68380. getChildList().removeChild (child, undoManager);
  68381. }
  68382. const RelativeParallelogram DrawableComposite::ValueTreeWrapper::getBoundingBox() const
  68383. {
  68384. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  68385. state.getProperty (topRight, "100, 0"),
  68386. state.getProperty (bottomLeft, "0, 100"));
  68387. }
  68388. void DrawableComposite::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  68389. {
  68390. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  68391. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  68392. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  68393. }
  68394. void DrawableComposite::ValueTreeWrapper::resetBoundingBoxToContentArea (UndoManager* undoManager)
  68395. {
  68396. const RelativeRectangle content (getContentArea());
  68397. setBoundingBox (RelativeParallelogram (RelativePoint (content.left, content.top),
  68398. RelativePoint (content.right, content.top),
  68399. RelativePoint (content.left, content.bottom)), undoManager);
  68400. }
  68401. const RelativeRectangle DrawableComposite::ValueTreeWrapper::getContentArea() const
  68402. {
  68403. return RelativeRectangle (getMarker (true, getMarkerState (true, 0)).position,
  68404. getMarker (true, getMarkerState (true, 1)).position,
  68405. getMarker (false, getMarkerState (false, 0)).position,
  68406. getMarker (false, getMarkerState (false, 1)).position);
  68407. }
  68408. void DrawableComposite::ValueTreeWrapper::setContentArea (const RelativeRectangle& newArea, UndoManager* undoManager)
  68409. {
  68410. setMarker (true, Marker (contentLeftMarkerName, newArea.left), undoManager);
  68411. setMarker (true, Marker (contentRightMarkerName, newArea.right), undoManager);
  68412. setMarker (false, Marker (contentTopMarkerName, newArea.top), undoManager);
  68413. setMarker (false, Marker (contentBottomMarkerName, newArea.bottom), undoManager);
  68414. }
  68415. ValueTree DrawableComposite::ValueTreeWrapper::getMarkerList (bool xAxis) const
  68416. {
  68417. return state.getChildWithName (xAxis ? markerGroupTagX : markerGroupTagY);
  68418. }
  68419. ValueTree DrawableComposite::ValueTreeWrapper::getMarkerListCreating (bool xAxis, UndoManager* undoManager)
  68420. {
  68421. return state.getOrCreateChildWithName (xAxis ? markerGroupTagX : markerGroupTagY, undoManager);
  68422. }
  68423. int DrawableComposite::ValueTreeWrapper::getNumMarkers (bool xAxis) const
  68424. {
  68425. return getMarkerList (xAxis).getNumChildren();
  68426. }
  68427. const ValueTree DrawableComposite::ValueTreeWrapper::getMarkerState (bool xAxis, int index) const
  68428. {
  68429. return getMarkerList (xAxis).getChild (index);
  68430. }
  68431. const ValueTree DrawableComposite::ValueTreeWrapper::getMarkerState (bool xAxis, const String& name) const
  68432. {
  68433. return getMarkerList (xAxis).getChildWithProperty (nameProperty, name);
  68434. }
  68435. bool DrawableComposite::ValueTreeWrapper::containsMarker (bool xAxis, const ValueTree& state) const
  68436. {
  68437. return state.isAChildOf (getMarkerList (xAxis));
  68438. }
  68439. const DrawableComposite::Marker DrawableComposite::ValueTreeWrapper::getMarker (bool xAxis, const ValueTree& state) const
  68440. {
  68441. jassert (containsMarker (xAxis, state));
  68442. return Marker (state [nameProperty], RelativeCoordinate (state [posProperty].toString(), xAxis));
  68443. }
  68444. void DrawableComposite::ValueTreeWrapper::setMarker (bool xAxis, const Marker& m, UndoManager* undoManager)
  68445. {
  68446. ValueTree markerList (getMarkerListCreating (xAxis, undoManager));
  68447. ValueTree marker (markerList.getChildWithProperty (nameProperty, m.name));
  68448. if (marker.isValid())
  68449. {
  68450. marker.setProperty (posProperty, m.position.toString(), undoManager);
  68451. }
  68452. else
  68453. {
  68454. marker = ValueTree (markerTag);
  68455. marker.setProperty (nameProperty, m.name, 0);
  68456. marker.setProperty (posProperty, m.position.toString(), 0);
  68457. markerList.addChild (marker, -1, undoManager);
  68458. }
  68459. }
  68460. void DrawableComposite::ValueTreeWrapper::removeMarker (bool xAxis, const ValueTree& state, UndoManager* undoManager)
  68461. {
  68462. if (state [nameProperty].toString() != contentLeftMarkerName
  68463. && state [nameProperty].toString() != contentRightMarkerName
  68464. && state [nameProperty].toString() != contentTopMarkerName
  68465. && state [nameProperty].toString() != contentBottomMarkerName)
  68466. return getMarkerList (xAxis).removeChild (state, undoManager);
  68467. }
  68468. const Rectangle<float> DrawableComposite::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  68469. {
  68470. const ValueTreeWrapper wrapper (tree);
  68471. setName (wrapper.getID());
  68472. Rectangle<float> damage;
  68473. bool redrawAll = false;
  68474. const RelativeParallelogram newBounds (wrapper.getBoundingBox());
  68475. if (bounds != newBounds)
  68476. {
  68477. redrawAll = true;
  68478. damage = getBounds();
  68479. bounds = newBounds;
  68480. }
  68481. const int numMarkersX = wrapper.getNumMarkers (true);
  68482. const int numMarkersY = wrapper.getNumMarkers (false);
  68483. // Remove deleted markers...
  68484. if (markersX.size() > numMarkersX || markersY.size() > numMarkersY)
  68485. {
  68486. if (! redrawAll)
  68487. {
  68488. redrawAll = true;
  68489. damage = getBounds();
  68490. }
  68491. markersX.removeRange (jmax (2, numMarkersX), markersX.size());
  68492. markersY.removeRange (jmax (2, numMarkersY), markersY.size());
  68493. }
  68494. // Update markers and add new ones..
  68495. int i;
  68496. for (i = 0; i < numMarkersX; ++i)
  68497. {
  68498. const Marker newMarker (wrapper.getMarker (true, wrapper.getMarkerState (true, i)));
  68499. Marker* m = markersX[i];
  68500. if (m == 0 || newMarker != *m)
  68501. {
  68502. if (! redrawAll)
  68503. {
  68504. redrawAll = true;
  68505. damage = getBounds();
  68506. }
  68507. if (m == 0)
  68508. markersX.add (new Marker (newMarker));
  68509. else
  68510. *m = newMarker;
  68511. }
  68512. }
  68513. for (i = 0; i < numMarkersY; ++i)
  68514. {
  68515. const Marker newMarker (wrapper.getMarker (false, wrapper.getMarkerState (false, i)));
  68516. Marker* m = markersY[i];
  68517. if (m == 0 || newMarker != *m)
  68518. {
  68519. if (! redrawAll)
  68520. {
  68521. redrawAll = true;
  68522. damage = getBounds();
  68523. }
  68524. if (m == 0)
  68525. markersY.add (new Marker (newMarker));
  68526. else
  68527. *m = newMarker;
  68528. }
  68529. }
  68530. // Remove deleted drawables..
  68531. for (i = drawables.size(); --i >= wrapper.getNumDrawables();)
  68532. {
  68533. Drawable* const d = drawables.getUnchecked(i);
  68534. if (! redrawAll)
  68535. damage = damage.getUnion (d->getBounds());
  68536. d->parent = 0;
  68537. drawables.remove (i);
  68538. }
  68539. // Update drawables and add new ones..
  68540. for (i = 0; i < wrapper.getNumDrawables(); ++i)
  68541. {
  68542. const ValueTree newDrawable (wrapper.getDrawableState (i));
  68543. Drawable* d = drawables[i];
  68544. if (d != 0)
  68545. {
  68546. if (newDrawable.hasType (d->getValueTreeType()))
  68547. {
  68548. const Rectangle<float> area (d->refreshFromValueTree (newDrawable, imageProvider));
  68549. if (! redrawAll)
  68550. damage = damage.getUnion (area);
  68551. }
  68552. else
  68553. {
  68554. if (! redrawAll)
  68555. damage = damage.getUnion (d->getBounds());
  68556. d = createChildFromValueTree (this, newDrawable, imageProvider);
  68557. drawables.set (i, d);
  68558. if (! redrawAll)
  68559. damage = damage.getUnion (d->getBounds());
  68560. }
  68561. }
  68562. else
  68563. {
  68564. d = createChildFromValueTree (this, newDrawable, imageProvider);
  68565. drawables.set (i, d);
  68566. if (! redrawAll)
  68567. damage = damage.getUnion (d->getBounds());
  68568. }
  68569. }
  68570. if (redrawAll)
  68571. damage = damage.getUnion (getBounds());
  68572. else if (! damage.isEmpty())
  68573. damage = damage.transformed (calculateTransform());
  68574. return damage;
  68575. }
  68576. const ValueTree DrawableComposite::createValueTree (ImageProvider* imageProvider) const
  68577. {
  68578. ValueTree tree (valueTreeType);
  68579. ValueTreeWrapper v (tree);
  68580. v.setID (getName(), 0);
  68581. v.setBoundingBox (bounds, 0);
  68582. int i;
  68583. for (i = 0; i < drawables.size(); ++i)
  68584. v.addDrawable (drawables.getUnchecked(i)->createValueTree (imageProvider), -1, 0);
  68585. for (i = 0; i < markersX.size(); ++i)
  68586. v.setMarker (true, *markersX.getUnchecked(i), 0);
  68587. for (i = 0; i < markersY.size(); ++i)
  68588. v.setMarker (false, *markersY.getUnchecked(i), 0);
  68589. return tree;
  68590. }
  68591. END_JUCE_NAMESPACE
  68592. /*** End of inlined file: juce_DrawableComposite.cpp ***/
  68593. /*** Start of inlined file: juce_DrawableImage.cpp ***/
  68594. BEGIN_JUCE_NAMESPACE
  68595. DrawableImage::DrawableImage()
  68596. : image (0),
  68597. opacity (1.0f),
  68598. overlayColour (0x00000000)
  68599. {
  68600. bounds.topRight = RelativePoint (Point<float> (1.0f, 0.0f));
  68601. bounds.bottomLeft = RelativePoint (Point<float> (0.0f, 1.0f));
  68602. }
  68603. DrawableImage::DrawableImage (const DrawableImage& other)
  68604. : image (other.image),
  68605. opacity (other.opacity),
  68606. overlayColour (other.overlayColour),
  68607. bounds (other.bounds)
  68608. {
  68609. }
  68610. DrawableImage::~DrawableImage()
  68611. {
  68612. }
  68613. void DrawableImage::setImage (const Image& imageToUse)
  68614. {
  68615. image = imageToUse;
  68616. if (image.isValid())
  68617. {
  68618. bounds.topLeft = RelativePoint (Point<float> (0.0f, 0.0f));
  68619. bounds.topRight = RelativePoint (Point<float> ((float) image.getWidth(), 0.0f));
  68620. bounds.bottomLeft = RelativePoint (Point<float> (0.0f, (float) image.getHeight()));
  68621. }
  68622. }
  68623. void DrawableImage::setOpacity (const float newOpacity)
  68624. {
  68625. opacity = newOpacity;
  68626. }
  68627. void DrawableImage::setOverlayColour (const Colour& newOverlayColour)
  68628. {
  68629. overlayColour = newOverlayColour;
  68630. }
  68631. void DrawableImage::setBoundingBox (const RelativeParallelogram& newBounds)
  68632. {
  68633. bounds = newBounds;
  68634. }
  68635. const AffineTransform DrawableImage::calculateTransform() const
  68636. {
  68637. if (image.isNull())
  68638. return AffineTransform::identity;
  68639. Point<float> resolved[3];
  68640. bounds.resolveThreePoints (resolved, parent);
  68641. const Point<float> tr (resolved[0] + (resolved[1] - resolved[0]) / (float) image.getWidth());
  68642. const Point<float> bl (resolved[0] + (resolved[2] - resolved[0]) / (float) image.getHeight());
  68643. return AffineTransform::fromTargetPoints (resolved[0].getX(), resolved[0].getY(),
  68644. tr.getX(), tr.getY(),
  68645. bl.getX(), bl.getY());
  68646. }
  68647. void DrawableImage::render (const Drawable::RenderingContext& context) const
  68648. {
  68649. if (image.isValid())
  68650. {
  68651. const AffineTransform t (calculateTransform().followedBy (context.transform));
  68652. if (opacity > 0.0f && ! overlayColour.isOpaque())
  68653. {
  68654. context.g.setOpacity (context.opacity * opacity);
  68655. context.g.drawImageTransformed (image, image.getBounds(), t, false);
  68656. }
  68657. if (! overlayColour.isTransparent())
  68658. {
  68659. context.g.setColour (overlayColour.withMultipliedAlpha (context.opacity));
  68660. context.g.drawImageTransformed (image, image.getBounds(), t, true);
  68661. }
  68662. }
  68663. }
  68664. const Rectangle<float> DrawableImage::getBounds() const
  68665. {
  68666. if (image.isNull())
  68667. return Rectangle<float>();
  68668. return bounds.getBounds (parent);
  68669. }
  68670. bool DrawableImage::hitTest (float x, float y) const
  68671. {
  68672. if (image.isNull())
  68673. return false;
  68674. calculateTransform().inverted().transformPoint (x, y);
  68675. const int ix = roundToInt (x);
  68676. const int iy = roundToInt (y);
  68677. return ix >= 0
  68678. && iy >= 0
  68679. && ix < image.getWidth()
  68680. && iy < image.getHeight()
  68681. && image.getPixelAt (ix, iy).getAlpha() >= 127;
  68682. }
  68683. Drawable* DrawableImage::createCopy() const
  68684. {
  68685. return new DrawableImage (*this);
  68686. }
  68687. void DrawableImage::invalidatePoints()
  68688. {
  68689. }
  68690. const Identifier DrawableImage::valueTreeType ("Image");
  68691. const Identifier DrawableImage::ValueTreeWrapper::opacity ("opacity");
  68692. const Identifier DrawableImage::ValueTreeWrapper::overlay ("overlay");
  68693. const Identifier DrawableImage::ValueTreeWrapper::image ("image");
  68694. const Identifier DrawableImage::ValueTreeWrapper::topLeft ("topLeft");
  68695. const Identifier DrawableImage::ValueTreeWrapper::topRight ("topRight");
  68696. const Identifier DrawableImage::ValueTreeWrapper::bottomLeft ("bottomLeft");
  68697. DrawableImage::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  68698. : ValueTreeWrapperBase (state_)
  68699. {
  68700. jassert (state.hasType (valueTreeType));
  68701. }
  68702. const var DrawableImage::ValueTreeWrapper::getImageIdentifier() const
  68703. {
  68704. return state [image];
  68705. }
  68706. Value DrawableImage::ValueTreeWrapper::getImageIdentifierValue (UndoManager* undoManager)
  68707. {
  68708. return state.getPropertyAsValue (image, undoManager);
  68709. }
  68710. void DrawableImage::ValueTreeWrapper::setImageIdentifier (const var& newIdentifier, UndoManager* undoManager)
  68711. {
  68712. state.setProperty (image, newIdentifier, undoManager);
  68713. }
  68714. float DrawableImage::ValueTreeWrapper::getOpacity() const
  68715. {
  68716. return (float) state.getProperty (opacity, 1.0);
  68717. }
  68718. Value DrawableImage::ValueTreeWrapper::getOpacityValue (UndoManager* undoManager)
  68719. {
  68720. if (! state.hasProperty (opacity))
  68721. state.setProperty (opacity, 1.0, undoManager);
  68722. return state.getPropertyAsValue (opacity, undoManager);
  68723. }
  68724. void DrawableImage::ValueTreeWrapper::setOpacity (float newOpacity, UndoManager* undoManager)
  68725. {
  68726. state.setProperty (opacity, newOpacity, undoManager);
  68727. }
  68728. const Colour DrawableImage::ValueTreeWrapper::getOverlayColour() const
  68729. {
  68730. return Colour (state [overlay].toString().getHexValue32());
  68731. }
  68732. void DrawableImage::ValueTreeWrapper::setOverlayColour (const Colour& newColour, UndoManager* undoManager)
  68733. {
  68734. if (newColour.isTransparent())
  68735. state.removeProperty (overlay, undoManager);
  68736. else
  68737. state.setProperty (overlay, String::toHexString ((int) newColour.getARGB()), undoManager);
  68738. }
  68739. Value DrawableImage::ValueTreeWrapper::getOverlayColourValue (UndoManager* undoManager)
  68740. {
  68741. return state.getPropertyAsValue (overlay, undoManager);
  68742. }
  68743. const RelativeParallelogram DrawableImage::ValueTreeWrapper::getBoundingBox() const
  68744. {
  68745. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  68746. state.getProperty (topRight, "100, 0"),
  68747. state.getProperty (bottomLeft, "0, 100"));
  68748. }
  68749. void DrawableImage::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  68750. {
  68751. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  68752. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  68753. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  68754. }
  68755. const Rectangle<float> DrawableImage::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  68756. {
  68757. const ValueTreeWrapper controller (tree);
  68758. setName (controller.getID());
  68759. const float newOpacity = controller.getOpacity();
  68760. const Colour newOverlayColour (controller.getOverlayColour());
  68761. Image newImage;
  68762. const var imageIdentifier (controller.getImageIdentifier());
  68763. jassert (imageProvider != 0 || imageIdentifier.isVoid()); // if you're using images, you need to provide something that can load and save them!
  68764. if (imageProvider != 0)
  68765. newImage = imageProvider->getImageForIdentifier (imageIdentifier);
  68766. const RelativeParallelogram newBounds (controller.getBoundingBox());
  68767. if (newOpacity != opacity || overlayColour != newOverlayColour || image != newImage || bounds != newBounds)
  68768. {
  68769. const Rectangle<float> damage (getBounds());
  68770. opacity = newOpacity;
  68771. overlayColour = newOverlayColour;
  68772. bounds = newBounds;
  68773. image = newImage;
  68774. return damage.getUnion (getBounds());
  68775. }
  68776. return Rectangle<float>();
  68777. }
  68778. const ValueTree DrawableImage::createValueTree (ImageProvider* imageProvider) const
  68779. {
  68780. ValueTree tree (valueTreeType);
  68781. ValueTreeWrapper v (tree);
  68782. v.setID (getName(), 0);
  68783. v.setOpacity (opacity, 0);
  68784. v.setOverlayColour (overlayColour, 0);
  68785. v.setBoundingBox (bounds, 0);
  68786. if (image.isValid())
  68787. {
  68788. jassert (imageProvider != 0); // if you're using images, you need to provide something that can load and save them!
  68789. if (imageProvider != 0)
  68790. v.setImageIdentifier (imageProvider->getIdentifierForImage (image), 0);
  68791. }
  68792. return tree;
  68793. }
  68794. END_JUCE_NAMESPACE
  68795. /*** End of inlined file: juce_DrawableImage.cpp ***/
  68796. /*** Start of inlined file: juce_DrawablePath.cpp ***/
  68797. BEGIN_JUCE_NAMESPACE
  68798. DrawablePath::DrawablePath()
  68799. : mainFill (Colours::black),
  68800. strokeFill (Colours::transparentBlack),
  68801. strokeType (0.0f),
  68802. pathNeedsUpdating (true),
  68803. strokeNeedsUpdating (true)
  68804. {
  68805. }
  68806. DrawablePath::DrawablePath (const DrawablePath& other)
  68807. : mainFill (other.mainFill),
  68808. strokeFill (other.strokeFill),
  68809. strokeType (other.strokeType),
  68810. pathNeedsUpdating (true),
  68811. strokeNeedsUpdating (true)
  68812. {
  68813. if (other.relativePath != 0)
  68814. relativePath = new RelativePointPath (*other.relativePath);
  68815. else
  68816. path = other.path;
  68817. }
  68818. DrawablePath::~DrawablePath()
  68819. {
  68820. }
  68821. void DrawablePath::setPath (const Path& newPath)
  68822. {
  68823. path = newPath;
  68824. strokeNeedsUpdating = true;
  68825. }
  68826. void DrawablePath::setFill (const FillType& newFill)
  68827. {
  68828. mainFill = newFill;
  68829. }
  68830. void DrawablePath::setStrokeFill (const FillType& newFill)
  68831. {
  68832. strokeFill = newFill;
  68833. }
  68834. void DrawablePath::setStrokeType (const PathStrokeType& newStrokeType)
  68835. {
  68836. strokeType = newStrokeType;
  68837. strokeNeedsUpdating = true;
  68838. }
  68839. void DrawablePath::setStrokeThickness (const float newThickness)
  68840. {
  68841. setStrokeType (PathStrokeType (newThickness, strokeType.getJointStyle(), strokeType.getEndStyle()));
  68842. }
  68843. void DrawablePath::updatePath() const
  68844. {
  68845. if (pathNeedsUpdating)
  68846. {
  68847. pathNeedsUpdating = false;
  68848. if (relativePath != 0)
  68849. {
  68850. path.clear();
  68851. relativePath->createPath (path, parent);
  68852. strokeNeedsUpdating = true;
  68853. }
  68854. }
  68855. }
  68856. void DrawablePath::updateStroke() const
  68857. {
  68858. if (strokeNeedsUpdating)
  68859. {
  68860. strokeNeedsUpdating = false;
  68861. updatePath();
  68862. stroke.clear();
  68863. strokeType.createStrokedPath (stroke, path, AffineTransform::identity, 4.0f);
  68864. }
  68865. }
  68866. const Path& DrawablePath::getPath() const
  68867. {
  68868. updatePath();
  68869. return path;
  68870. }
  68871. const Path& DrawablePath::getStrokePath() const
  68872. {
  68873. updateStroke();
  68874. return stroke;
  68875. }
  68876. bool DrawablePath::isStrokeVisible() const throw()
  68877. {
  68878. return strokeType.getStrokeThickness() > 0.0f && ! strokeFill.isInvisible();
  68879. }
  68880. void DrawablePath::invalidatePoints()
  68881. {
  68882. pathNeedsUpdating = true;
  68883. strokeNeedsUpdating = true;
  68884. }
  68885. void DrawablePath::render (const Drawable::RenderingContext& context) const
  68886. {
  68887. {
  68888. FillType f (mainFill);
  68889. if (f.isGradient())
  68890. f.gradient->multiplyOpacity (context.opacity);
  68891. f.transform = f.transform.followedBy (context.transform);
  68892. context.g.setFillType (f);
  68893. context.g.fillPath (getPath(), context.transform);
  68894. }
  68895. if (isStrokeVisible())
  68896. {
  68897. FillType f (strokeFill);
  68898. if (f.isGradient())
  68899. f.gradient->multiplyOpacity (context.opacity);
  68900. f.transform = f.transform.followedBy (context.transform);
  68901. context.g.setFillType (f);
  68902. context.g.fillPath (getStrokePath(), context.transform);
  68903. }
  68904. }
  68905. const Rectangle<float> DrawablePath::getBounds() const
  68906. {
  68907. if (isStrokeVisible())
  68908. return getStrokePath().getBounds();
  68909. else
  68910. return getPath().getBounds();
  68911. }
  68912. bool DrawablePath::hitTest (float x, float y) const
  68913. {
  68914. return getPath().contains (x, y)
  68915. || (isStrokeVisible() && getStrokePath().contains (x, y));
  68916. }
  68917. Drawable* DrawablePath::createCopy() const
  68918. {
  68919. return new DrawablePath (*this);
  68920. }
  68921. const Identifier DrawablePath::valueTreeType ("Path");
  68922. const Identifier DrawablePath::ValueTreeWrapper::fill ("Fill");
  68923. const Identifier DrawablePath::ValueTreeWrapper::stroke ("Stroke");
  68924. const Identifier DrawablePath::ValueTreeWrapper::path ("Path");
  68925. const Identifier DrawablePath::ValueTreeWrapper::jointStyle ("jointStyle");
  68926. const Identifier DrawablePath::ValueTreeWrapper::capStyle ("capStyle");
  68927. const Identifier DrawablePath::ValueTreeWrapper::strokeWidth ("strokeWidth");
  68928. const Identifier DrawablePath::ValueTreeWrapper::nonZeroWinding ("nonZeroWinding");
  68929. const Identifier DrawablePath::ValueTreeWrapper::point1 ("p1");
  68930. const Identifier DrawablePath::ValueTreeWrapper::point2 ("p2");
  68931. const Identifier DrawablePath::ValueTreeWrapper::point3 ("p3");
  68932. DrawablePath::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  68933. : ValueTreeWrapperBase (state_)
  68934. {
  68935. jassert (state.hasType (valueTreeType));
  68936. }
  68937. ValueTree DrawablePath::ValueTreeWrapper::getPathState()
  68938. {
  68939. return state.getOrCreateChildWithName (path, 0);
  68940. }
  68941. ValueTree DrawablePath::ValueTreeWrapper::getMainFillState()
  68942. {
  68943. ValueTree v (state.getChildWithName (fill));
  68944. if (v.isValid())
  68945. return v;
  68946. setMainFill (Colours::black, 0, 0, 0, 0);
  68947. return getMainFillState();
  68948. }
  68949. ValueTree DrawablePath::ValueTreeWrapper::getStrokeFillState()
  68950. {
  68951. ValueTree v (state.getChildWithName (stroke));
  68952. if (v.isValid())
  68953. return v;
  68954. setStrokeFill (Colours::black, 0, 0, 0, 0);
  68955. return getStrokeFillState();
  68956. }
  68957. const FillType DrawablePath::ValueTreeWrapper::getMainFill (RelativeCoordinate::NamedCoordinateFinder* nameFinder,
  68958. ImageProvider* imageProvider) const
  68959. {
  68960. return readFillType (state.getChildWithName (fill), 0, 0, nameFinder, imageProvider);
  68961. }
  68962. void DrawablePath::ValueTreeWrapper::setMainFill (const FillType& newFill, const RelativePoint* gp1,
  68963. const RelativePoint* gp2, ImageProvider* imageProvider, UndoManager* undoManager)
  68964. {
  68965. ValueTree v (state.getOrCreateChildWithName (fill, undoManager));
  68966. writeFillType (v, newFill, gp1, gp2, imageProvider, undoManager);
  68967. }
  68968. const FillType DrawablePath::ValueTreeWrapper::getStrokeFill (RelativeCoordinate::NamedCoordinateFinder* nameFinder,
  68969. ImageProvider* imageProvider) const
  68970. {
  68971. return readFillType (state.getChildWithName (stroke), 0, 0, nameFinder, imageProvider);
  68972. }
  68973. void DrawablePath::ValueTreeWrapper::setStrokeFill (const FillType& newFill, const RelativePoint* gp1,
  68974. const RelativePoint* gp2, ImageProvider* imageProvider, UndoManager* undoManager)
  68975. {
  68976. ValueTree v (state.getOrCreateChildWithName (stroke, undoManager));
  68977. writeFillType (v, newFill, gp1, gp2, imageProvider, undoManager);
  68978. }
  68979. const PathStrokeType DrawablePath::ValueTreeWrapper::getStrokeType() const
  68980. {
  68981. const String jointStyleString (state [jointStyle].toString());
  68982. const String capStyleString (state [capStyle].toString());
  68983. return PathStrokeType (state [strokeWidth],
  68984. jointStyleString == "curved" ? PathStrokeType::curved
  68985. : (jointStyleString == "bevel" ? PathStrokeType::beveled
  68986. : PathStrokeType::mitered),
  68987. capStyleString == "square" ? PathStrokeType::square
  68988. : (capStyleString == "round" ? PathStrokeType::rounded
  68989. : PathStrokeType::butt));
  68990. }
  68991. void DrawablePath::ValueTreeWrapper::setStrokeType (const PathStrokeType& newStrokeType, UndoManager* undoManager)
  68992. {
  68993. state.setProperty (strokeWidth, (double) newStrokeType.getStrokeThickness(), undoManager);
  68994. state.setProperty (jointStyle, newStrokeType.getJointStyle() == PathStrokeType::mitered
  68995. ? "miter" : (newStrokeType.getJointStyle() == PathStrokeType::curved ? "curved" : "bevel"), undoManager);
  68996. state.setProperty (capStyle, newStrokeType.getEndStyle() == PathStrokeType::butt
  68997. ? "butt" : (newStrokeType.getEndStyle() == PathStrokeType::square ? "square" : "round"), undoManager);
  68998. }
  68999. bool DrawablePath::ValueTreeWrapper::usesNonZeroWinding() const
  69000. {
  69001. return state [nonZeroWinding];
  69002. }
  69003. void DrawablePath::ValueTreeWrapper::setUsesNonZeroWinding (bool b, UndoManager* undoManager)
  69004. {
  69005. state.setProperty (nonZeroWinding, b, undoManager);
  69006. }
  69007. const Identifier DrawablePath::ValueTreeWrapper::Element::startSubPathElement ("Move");
  69008. const Identifier DrawablePath::ValueTreeWrapper::Element::closeSubPathElement ("Close");
  69009. const Identifier DrawablePath::ValueTreeWrapper::Element::lineToElement ("Line");
  69010. const Identifier DrawablePath::ValueTreeWrapper::Element::quadraticToElement ("Quad");
  69011. const Identifier DrawablePath::ValueTreeWrapper::Element::cubicToElement ("Cubic");
  69012. DrawablePath::ValueTreeWrapper::Element::Element (const ValueTree& state_)
  69013. : state (state_)
  69014. {
  69015. }
  69016. DrawablePath::ValueTreeWrapper::Element::~Element()
  69017. {
  69018. }
  69019. DrawablePath::ValueTreeWrapper DrawablePath::ValueTreeWrapper::Element::getParent() const
  69020. {
  69021. return ValueTreeWrapper (state.getParent().getParent());
  69022. }
  69023. int DrawablePath::ValueTreeWrapper::Element::getNumControlPoints() const throw()
  69024. {
  69025. const Identifier i (state.getType());
  69026. if (i == startSubPathElement || i == lineToElement) return 1;
  69027. if (i == quadraticToElement) return 2;
  69028. if (i == cubicToElement) return 3;
  69029. return 0;
  69030. }
  69031. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getControlPoint (const int index) const
  69032. {
  69033. jassert (index >= 0 && index < getNumControlPoints());
  69034. return RelativePoint (state [index == 0 ? point1 : (index == 1 ? point2 : point3)].toString());
  69035. }
  69036. Value DrawablePath::ValueTreeWrapper::Element::getControlPointValue (int index, UndoManager* undoManager) const
  69037. {
  69038. jassert (index >= 0 && index < getNumControlPoints());
  69039. return state.getPropertyAsValue (index == 0 ? point1 : (index == 1 ? point2 : point3), undoManager);
  69040. }
  69041. void DrawablePath::ValueTreeWrapper::Element::setControlPoint (const int index, const RelativePoint& point, UndoManager* undoManager)
  69042. {
  69043. jassert (index >= 0 && index < getNumControlPoints());
  69044. return state.setProperty (index == 0 ? point1 : (index == 1 ? point2 : point3), point.toString(), undoManager);
  69045. }
  69046. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getEndPoint() const
  69047. {
  69048. const Identifier i (state.getType());
  69049. if (i == startSubPathElement || i == lineToElement) return getControlPoint (0);
  69050. if (i == quadraticToElement) return getControlPoint (1);
  69051. if (i == cubicToElement) return getControlPoint (2);
  69052. return RelativePoint();
  69053. }
  69054. const Rectangle<float> DrawablePath::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  69055. {
  69056. Rectangle<float> damageRect;
  69057. ValueTreeWrapper v (tree);
  69058. setName (v.getID());
  69059. bool needsRedraw = false;
  69060. const FillType newFill (v.getMainFill (parent, imageProvider));
  69061. if (mainFill != newFill)
  69062. {
  69063. needsRedraw = true;
  69064. mainFill = newFill;
  69065. }
  69066. const FillType newStrokeFill (v.getStrokeFill (parent, imageProvider));
  69067. if (strokeFill != newStrokeFill)
  69068. {
  69069. needsRedraw = true;
  69070. strokeFill = newStrokeFill;
  69071. }
  69072. const PathStrokeType newStroke (v.getStrokeType());
  69073. ScopedPointer<RelativePointPath> newRelativePath (new RelativePointPath (tree));
  69074. Path newPath;
  69075. newRelativePath->createPath (newPath, parent);
  69076. if (! newRelativePath->containsAnyDynamicPoints())
  69077. newRelativePath = 0;
  69078. if (strokeType != newStroke || path != newPath)
  69079. {
  69080. damageRect = getBounds();
  69081. path.swapWithPath (newPath);
  69082. strokeNeedsUpdating = true;
  69083. strokeType = newStroke;
  69084. needsRedraw = true;
  69085. }
  69086. relativePath = newRelativePath.release();
  69087. if (needsRedraw)
  69088. damageRect = damageRect.getUnion (getBounds());
  69089. return damageRect;
  69090. }
  69091. const ValueTree DrawablePath::createValueTree (ImageProvider* imageProvider) const
  69092. {
  69093. ValueTree tree (valueTreeType);
  69094. ValueTreeWrapper v (tree);
  69095. v.setID (getName(), 0);
  69096. v.setMainFill (mainFill, 0, 0, imageProvider, 0);
  69097. v.setStrokeFill (strokeFill, 0, 0, imageProvider, 0);
  69098. v.setStrokeType (strokeType, 0);
  69099. if (relativePath != 0)
  69100. {
  69101. relativePath->writeTo (tree, 0);
  69102. }
  69103. else
  69104. {
  69105. RelativePointPath rp (path);
  69106. rp.writeTo (tree, 0);
  69107. }
  69108. return tree;
  69109. }
  69110. END_JUCE_NAMESPACE
  69111. /*** End of inlined file: juce_DrawablePath.cpp ***/
  69112. /*** Start of inlined file: juce_DrawableText.cpp ***/
  69113. BEGIN_JUCE_NAMESPACE
  69114. DrawableText::DrawableText()
  69115. : colour (Colours::black),
  69116. justification (Justification::centredLeft)
  69117. {
  69118. setFont (Font (15.0f), true);
  69119. }
  69120. DrawableText::DrawableText (const DrawableText& other)
  69121. : text (other.text),
  69122. font (other.font),
  69123. colour (other.colour),
  69124. justification (other.justification),
  69125. bounds (other.bounds),
  69126. fontSizeControlPoint (other.fontSizeControlPoint)
  69127. {
  69128. }
  69129. DrawableText::~DrawableText()
  69130. {
  69131. }
  69132. void DrawableText::setText (const String& newText)
  69133. {
  69134. text = newText;
  69135. }
  69136. void DrawableText::setColour (const Colour& newColour)
  69137. {
  69138. colour = newColour;
  69139. }
  69140. void DrawableText::setFont (const Font& newFont, bool applySizeAndScale)
  69141. {
  69142. font = newFont;
  69143. if (applySizeAndScale)
  69144. {
  69145. Point<float> corners[3];
  69146. bounds.resolveThreePoints (corners, parent);
  69147. setFontSizeControlPoint (RelativePoint (RelativeParallelogram::getPointForInternalCoord (corners,
  69148. Point<float> (font.getHorizontalScale() * font.getHeight(), font.getHeight()))));
  69149. }
  69150. }
  69151. void DrawableText::setJustification (const Justification& newJustification)
  69152. {
  69153. justification = newJustification;
  69154. }
  69155. void DrawableText::setBoundingBox (const RelativeParallelogram& newBounds)
  69156. {
  69157. bounds = newBounds;
  69158. }
  69159. void DrawableText::setFontSizeControlPoint (const RelativePoint& newPoint)
  69160. {
  69161. fontSizeControlPoint = newPoint;
  69162. }
  69163. void DrawableText::render (const Drawable::RenderingContext& context) const
  69164. {
  69165. Point<float> points[3];
  69166. bounds.resolveThreePoints (points, parent);
  69167. const float w = Line<float> (points[0], points[1]).getLength();
  69168. const float h = Line<float> (points[0], points[2]).getLength();
  69169. const Point<float> fontCoords (bounds.getInternalCoordForPoint (points, fontSizeControlPoint.resolve (parent)));
  69170. const float fontHeight = jlimit (1.0f, h, fontCoords.getY());
  69171. const float fontWidth = jlimit (0.01f, w, fontCoords.getX());
  69172. Font f (font);
  69173. f.setHeight (fontHeight);
  69174. f.setHorizontalScale (fontWidth / fontHeight);
  69175. context.g.setColour (colour.withMultipliedAlpha (context.opacity));
  69176. GlyphArrangement ga;
  69177. ga.addFittedText (f, text, 0, 0, w, h, justification, 0x100000);
  69178. ga.draw (context.g,
  69179. AffineTransform::fromTargetPoints (0, 0, points[0].getX(), points[0].getY(),
  69180. w, 0, points[1].getX(), points[1].getY(),
  69181. 0, h, points[2].getX(), points[2].getY())
  69182. .followedBy (context.transform));
  69183. }
  69184. const Rectangle<float> DrawableText::getBounds() const
  69185. {
  69186. return bounds.getBounds (parent);
  69187. }
  69188. bool DrawableText::hitTest (float x, float y) const
  69189. {
  69190. Path p;
  69191. bounds.getPath (p, parent);
  69192. return p.contains (x, y);
  69193. }
  69194. Drawable* DrawableText::createCopy() const
  69195. {
  69196. return new DrawableText (*this);
  69197. }
  69198. void DrawableText::invalidatePoints()
  69199. {
  69200. }
  69201. const Identifier DrawableText::valueTreeType ("Text");
  69202. const Identifier DrawableText::ValueTreeWrapper::text ("text");
  69203. const Identifier DrawableText::ValueTreeWrapper::colour ("colour");
  69204. const Identifier DrawableText::ValueTreeWrapper::font ("font");
  69205. const Identifier DrawableText::ValueTreeWrapper::justification ("justification");
  69206. const Identifier DrawableText::ValueTreeWrapper::topLeft ("topLeft");
  69207. const Identifier DrawableText::ValueTreeWrapper::topRight ("topRight");
  69208. const Identifier DrawableText::ValueTreeWrapper::bottomLeft ("bottomLeft");
  69209. const Identifier DrawableText::ValueTreeWrapper::fontSizeAnchor ("fontSizeAnchor");
  69210. DrawableText::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  69211. : ValueTreeWrapperBase (state_)
  69212. {
  69213. jassert (state.hasType (valueTreeType));
  69214. }
  69215. const String DrawableText::ValueTreeWrapper::getText() const
  69216. {
  69217. return state [text].toString();
  69218. }
  69219. void DrawableText::ValueTreeWrapper::setText (const String& newText, UndoManager* undoManager)
  69220. {
  69221. state.setProperty (text, newText, undoManager);
  69222. }
  69223. Value DrawableText::ValueTreeWrapper::getTextValue (UndoManager* undoManager)
  69224. {
  69225. return state.getPropertyAsValue (text, undoManager);
  69226. }
  69227. const Colour DrawableText::ValueTreeWrapper::getColour() const
  69228. {
  69229. return Colour::fromString (state [colour].toString());
  69230. }
  69231. void DrawableText::ValueTreeWrapper::setColour (const Colour& newColour, UndoManager* undoManager)
  69232. {
  69233. state.setProperty (colour, newColour.toString(), undoManager);
  69234. }
  69235. const Justification DrawableText::ValueTreeWrapper::getJustification() const
  69236. {
  69237. return Justification ((int) state [justification]);
  69238. }
  69239. void DrawableText::ValueTreeWrapper::setJustification (const Justification& newJustification, UndoManager* undoManager)
  69240. {
  69241. state.setProperty (justification, newJustification.getFlags(), undoManager);
  69242. }
  69243. const Font DrawableText::ValueTreeWrapper::getFont() const
  69244. {
  69245. return Font::fromString (state [font]);
  69246. }
  69247. void DrawableText::ValueTreeWrapper::setFont (const Font& newFont, UndoManager* undoManager)
  69248. {
  69249. state.setProperty (font, newFont.toString(), undoManager);
  69250. }
  69251. Value DrawableText::ValueTreeWrapper::getFontValue (UndoManager* undoManager)
  69252. {
  69253. return state.getPropertyAsValue (font, undoManager);
  69254. }
  69255. const RelativeParallelogram DrawableText::ValueTreeWrapper::getBoundingBox() const
  69256. {
  69257. return RelativeParallelogram (state [topLeft].toString(), state [topRight].toString(), state [bottomLeft].toString());
  69258. }
  69259. void DrawableText::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  69260. {
  69261. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  69262. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  69263. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  69264. }
  69265. const RelativePoint DrawableText::ValueTreeWrapper::getFontSizeControlPoint() const
  69266. {
  69267. return state [fontSizeAnchor].toString();
  69268. }
  69269. void DrawableText::ValueTreeWrapper::setFontSizeControlPoint (const RelativePoint& p, UndoManager* undoManager)
  69270. {
  69271. state.setProperty (fontSizeAnchor, p.toString(), undoManager);
  69272. }
  69273. const Rectangle<float> DrawableText::refreshFromValueTree (const ValueTree& tree, ImageProvider*)
  69274. {
  69275. ValueTreeWrapper v (tree);
  69276. setName (v.getID());
  69277. const RelativeParallelogram newBounds (v.getBoundingBox());
  69278. const RelativePoint newFontPoint (v.getFontSizeControlPoint());
  69279. const Colour newColour (v.getColour());
  69280. const Justification newJustification (v.getJustification());
  69281. const String newText (v.getText());
  69282. const Font newFont (v.getFont());
  69283. if (text != newText || font != newFont || justification != newJustification
  69284. || colour != newColour || bounds != newBounds || newFontPoint != fontSizeControlPoint)
  69285. {
  69286. const Rectangle<float> damage (getBounds());
  69287. setBoundingBox (newBounds);
  69288. setFontSizeControlPoint (newFontPoint);
  69289. setColour (newColour);
  69290. setFont (newFont, false);
  69291. setJustification (newJustification);
  69292. setText (newText);
  69293. return damage.getUnion (getBounds());
  69294. }
  69295. return Rectangle<float>();
  69296. }
  69297. const ValueTree DrawableText::createValueTree (ImageProvider*) const
  69298. {
  69299. ValueTree tree (valueTreeType);
  69300. ValueTreeWrapper v (tree);
  69301. v.setID (getName(), 0);
  69302. v.setText (text, 0);
  69303. v.setFont (font, 0);
  69304. v.setJustification (justification, 0);
  69305. v.setColour (colour, 0);
  69306. v.setBoundingBox (bounds, 0);
  69307. v.setFontSizeControlPoint (fontSizeControlPoint, 0);
  69308. return tree;
  69309. }
  69310. END_JUCE_NAMESPACE
  69311. /*** End of inlined file: juce_DrawableText.cpp ***/
  69312. /*** Start of inlined file: juce_SVGParser.cpp ***/
  69313. BEGIN_JUCE_NAMESPACE
  69314. class SVGState
  69315. {
  69316. public:
  69317. SVGState (const XmlElement* const topLevel)
  69318. : topLevelXml (topLevel),
  69319. elementX (0), elementY (0),
  69320. width (512), height (512),
  69321. viewBoxW (0), viewBoxH (0)
  69322. {
  69323. }
  69324. ~SVGState()
  69325. {
  69326. }
  69327. Drawable* parseSVGElement (const XmlElement& xml)
  69328. {
  69329. if (! xml.hasTagName ("svg"))
  69330. return 0;
  69331. DrawableComposite* const drawable = new DrawableComposite();
  69332. drawable->setName (xml.getStringAttribute ("id"));
  69333. SVGState newState (*this);
  69334. if (xml.hasAttribute ("transform"))
  69335. newState.addTransform (xml);
  69336. newState.elementX = getCoordLength (xml.getStringAttribute ("x", String (newState.elementX)), viewBoxW);
  69337. newState.elementY = getCoordLength (xml.getStringAttribute ("y", String (newState.elementY)), viewBoxH);
  69338. newState.width = getCoordLength (xml.getStringAttribute ("width", String (newState.width)), viewBoxW);
  69339. newState.height = getCoordLength (xml.getStringAttribute ("height", String (newState.height)), viewBoxH);
  69340. if (xml.hasAttribute ("viewBox"))
  69341. {
  69342. const String viewParams (xml.getStringAttribute ("viewBox"));
  69343. int i = 0;
  69344. float vx, vy, vw, vh;
  69345. if (parseCoords (viewParams, vx, vy, i, true)
  69346. && parseCoords (viewParams, vw, vh, i, true)
  69347. && vw > 0
  69348. && vh > 0)
  69349. {
  69350. newState.viewBoxW = vw;
  69351. newState.viewBoxH = vh;
  69352. int placementFlags = 0;
  69353. const String aspect (xml.getStringAttribute ("preserveAspectRatio"));
  69354. if (aspect.containsIgnoreCase ("none"))
  69355. {
  69356. placementFlags = RectanglePlacement::stretchToFit;
  69357. }
  69358. else
  69359. {
  69360. if (aspect.containsIgnoreCase ("slice"))
  69361. placementFlags |= RectanglePlacement::fillDestination;
  69362. if (aspect.containsIgnoreCase ("xMin"))
  69363. placementFlags |= RectanglePlacement::xLeft;
  69364. else if (aspect.containsIgnoreCase ("xMax"))
  69365. placementFlags |= RectanglePlacement::xRight;
  69366. else
  69367. placementFlags |= RectanglePlacement::xMid;
  69368. if (aspect.containsIgnoreCase ("yMin"))
  69369. placementFlags |= RectanglePlacement::yTop;
  69370. else if (aspect.containsIgnoreCase ("yMax"))
  69371. placementFlags |= RectanglePlacement::yBottom;
  69372. else
  69373. placementFlags |= RectanglePlacement::yMid;
  69374. }
  69375. const RectanglePlacement placement (placementFlags);
  69376. newState.transform
  69377. = placement.getTransformToFit (vx, vy, vw, vh,
  69378. 0.0f, 0.0f, newState.width, newState.height)
  69379. .followedBy (newState.transform);
  69380. }
  69381. }
  69382. else
  69383. {
  69384. if (viewBoxW == 0)
  69385. newState.viewBoxW = newState.width;
  69386. if (viewBoxH == 0)
  69387. newState.viewBoxH = newState.height;
  69388. }
  69389. newState.parseSubElements (xml, drawable);
  69390. drawable->resetContentAreaAndBoundingBoxToFitChildren();
  69391. return drawable;
  69392. }
  69393. private:
  69394. const XmlElement* const topLevelXml;
  69395. float elementX, elementY, width, height, viewBoxW, viewBoxH;
  69396. AffineTransform transform;
  69397. String cssStyleText;
  69398. void parseSubElements (const XmlElement& xml, DrawableComposite* const parentDrawable)
  69399. {
  69400. forEachXmlChildElement (xml, e)
  69401. {
  69402. Drawable* d = 0;
  69403. if (e->hasTagName ("g")) d = parseGroupElement (*e);
  69404. else if (e->hasTagName ("svg")) d = parseSVGElement (*e);
  69405. else if (e->hasTagName ("path")) d = parsePath (*e);
  69406. else if (e->hasTagName ("rect")) d = parseRect (*e);
  69407. else if (e->hasTagName ("circle")) d = parseCircle (*e);
  69408. else if (e->hasTagName ("ellipse")) d = parseEllipse (*e);
  69409. else if (e->hasTagName ("line")) d = parseLine (*e);
  69410. else if (e->hasTagName ("polyline")) d = parsePolygon (*e, true);
  69411. else if (e->hasTagName ("polygon")) d = parsePolygon (*e, false);
  69412. else if (e->hasTagName ("text")) d = parseText (*e);
  69413. else if (e->hasTagName ("switch")) d = parseSwitch (*e);
  69414. else if (e->hasTagName ("style")) parseCSSStyle (*e);
  69415. parentDrawable->insertDrawable (d);
  69416. }
  69417. }
  69418. DrawableComposite* parseSwitch (const XmlElement& xml)
  69419. {
  69420. const XmlElement* const group = xml.getChildByName ("g");
  69421. if (group != 0)
  69422. return parseGroupElement (*group);
  69423. return 0;
  69424. }
  69425. DrawableComposite* parseGroupElement (const XmlElement& xml)
  69426. {
  69427. DrawableComposite* const drawable = new DrawableComposite();
  69428. drawable->setName (xml.getStringAttribute ("id"));
  69429. if (xml.hasAttribute ("transform"))
  69430. {
  69431. SVGState newState (*this);
  69432. newState.addTransform (xml);
  69433. newState.parseSubElements (xml, drawable);
  69434. }
  69435. else
  69436. {
  69437. parseSubElements (xml, drawable);
  69438. }
  69439. drawable->resetContentAreaAndBoundingBoxToFitChildren();
  69440. return drawable;
  69441. }
  69442. Drawable* parsePath (const XmlElement& xml) const
  69443. {
  69444. const String d (xml.getStringAttribute ("d").trimStart());
  69445. Path path;
  69446. if (getStyleAttribute (&xml, "fill-rule").trim().equalsIgnoreCase ("evenodd"))
  69447. path.setUsingNonZeroWinding (false);
  69448. int index = 0;
  69449. float lastX = 0, lastY = 0;
  69450. float lastX2 = 0, lastY2 = 0;
  69451. juce_wchar lastCommandChar = 0;
  69452. bool isRelative = true;
  69453. bool carryOn = true;
  69454. const String validCommandChars ("MmLlHhVvCcSsQqTtAaZz");
  69455. while (d[index] != 0)
  69456. {
  69457. float x, y, x2, y2, x3, y3;
  69458. if (validCommandChars.containsChar (d[index]))
  69459. {
  69460. lastCommandChar = d [index++];
  69461. isRelative = (lastCommandChar >= 'a' && lastCommandChar <= 'z');
  69462. }
  69463. switch (lastCommandChar)
  69464. {
  69465. case 'M':
  69466. case 'm':
  69467. case 'L':
  69468. case 'l':
  69469. if (parseCoords (d, x, y, index, false))
  69470. {
  69471. if (isRelative)
  69472. {
  69473. x += lastX;
  69474. y += lastY;
  69475. }
  69476. if (lastCommandChar == 'M' || lastCommandChar == 'm')
  69477. {
  69478. path.startNewSubPath (x, y);
  69479. lastCommandChar = 'l';
  69480. }
  69481. else
  69482. path.lineTo (x, y);
  69483. lastX2 = lastX;
  69484. lastY2 = lastY;
  69485. lastX = x;
  69486. lastY = y;
  69487. }
  69488. else
  69489. {
  69490. ++index;
  69491. }
  69492. break;
  69493. case 'H':
  69494. case 'h':
  69495. if (parseCoord (d, x, index, false, true))
  69496. {
  69497. if (isRelative)
  69498. x += lastX;
  69499. path.lineTo (x, lastY);
  69500. lastX2 = lastX;
  69501. lastX = x;
  69502. }
  69503. else
  69504. {
  69505. ++index;
  69506. }
  69507. break;
  69508. case 'V':
  69509. case 'v':
  69510. if (parseCoord (d, y, index, false, false))
  69511. {
  69512. if (isRelative)
  69513. y += lastY;
  69514. path.lineTo (lastX, y);
  69515. lastY2 = lastY;
  69516. lastY = y;
  69517. }
  69518. else
  69519. {
  69520. ++index;
  69521. }
  69522. break;
  69523. case 'C':
  69524. case 'c':
  69525. if (parseCoords (d, x, y, index, false)
  69526. && parseCoords (d, x2, y2, index, false)
  69527. && parseCoords (d, x3, y3, index, false))
  69528. {
  69529. if (isRelative)
  69530. {
  69531. x += lastX;
  69532. y += lastY;
  69533. x2 += lastX;
  69534. y2 += lastY;
  69535. x3 += lastX;
  69536. y3 += lastY;
  69537. }
  69538. path.cubicTo (x, y, x2, y2, x3, y3);
  69539. lastX2 = x2;
  69540. lastY2 = y2;
  69541. lastX = x3;
  69542. lastY = y3;
  69543. }
  69544. else
  69545. {
  69546. ++index;
  69547. }
  69548. break;
  69549. case 'S':
  69550. case 's':
  69551. if (parseCoords (d, x, y, index, false)
  69552. && parseCoords (d, x3, y3, index, false))
  69553. {
  69554. if (isRelative)
  69555. {
  69556. x += lastX;
  69557. y += lastY;
  69558. x3 += lastX;
  69559. y3 += lastY;
  69560. }
  69561. x2 = lastX + (lastX - lastX2);
  69562. y2 = lastY + (lastY - lastY2);
  69563. path.cubicTo (x2, y2, x, y, x3, y3);
  69564. lastX2 = x;
  69565. lastY2 = y;
  69566. lastX = x3;
  69567. lastY = y3;
  69568. }
  69569. else
  69570. {
  69571. ++index;
  69572. }
  69573. break;
  69574. case 'Q':
  69575. case 'q':
  69576. if (parseCoords (d, x, y, index, false)
  69577. && parseCoords (d, x2, y2, index, false))
  69578. {
  69579. if (isRelative)
  69580. {
  69581. x += lastX;
  69582. y += lastY;
  69583. x2 += lastX;
  69584. y2 += lastY;
  69585. }
  69586. path.quadraticTo (x, y, x2, y2);
  69587. lastX2 = x;
  69588. lastY2 = y;
  69589. lastX = x2;
  69590. lastY = y2;
  69591. }
  69592. else
  69593. {
  69594. ++index;
  69595. }
  69596. break;
  69597. case 'T':
  69598. case 't':
  69599. if (parseCoords (d, x, y, index, false))
  69600. {
  69601. if (isRelative)
  69602. {
  69603. x += lastX;
  69604. y += lastY;
  69605. }
  69606. x2 = lastX + (lastX - lastX2);
  69607. y2 = lastY + (lastY - lastY2);
  69608. path.quadraticTo (x2, y2, x, y);
  69609. lastX2 = x2;
  69610. lastY2 = y2;
  69611. lastX = x;
  69612. lastY = y;
  69613. }
  69614. else
  69615. {
  69616. ++index;
  69617. }
  69618. break;
  69619. case 'A':
  69620. case 'a':
  69621. if (parseCoords (d, x, y, index, false))
  69622. {
  69623. String num;
  69624. if (parseNextNumber (d, num, index, false))
  69625. {
  69626. const float angle = num.getFloatValue() * (180.0f / float_Pi);
  69627. if (parseNextNumber (d, num, index, false))
  69628. {
  69629. const bool largeArc = num.getIntValue() != 0;
  69630. if (parseNextNumber (d, num, index, false))
  69631. {
  69632. const bool sweep = num.getIntValue() != 0;
  69633. if (parseCoords (d, x2, y2, index, false))
  69634. {
  69635. if (isRelative)
  69636. {
  69637. x2 += lastX;
  69638. y2 += lastY;
  69639. }
  69640. if (lastX != x2 || lastY != y2)
  69641. {
  69642. double centreX, centreY, startAngle, deltaAngle;
  69643. double rx = x, ry = y;
  69644. endpointToCentreParameters (lastX, lastY, x2, y2,
  69645. angle, largeArc, sweep,
  69646. rx, ry, centreX, centreY,
  69647. startAngle, deltaAngle);
  69648. path.addCentredArc ((float) centreX, (float) centreY,
  69649. (float) rx, (float) ry,
  69650. angle, (float) startAngle, (float) (startAngle + deltaAngle),
  69651. false);
  69652. path.lineTo (x2, y2);
  69653. }
  69654. lastX2 = lastX;
  69655. lastY2 = lastY;
  69656. lastX = x2;
  69657. lastY = y2;
  69658. }
  69659. }
  69660. }
  69661. }
  69662. }
  69663. else
  69664. {
  69665. ++index;
  69666. }
  69667. break;
  69668. case 'Z':
  69669. case 'z':
  69670. path.closeSubPath();
  69671. while (CharacterFunctions::isWhitespace (d [index]))
  69672. ++index;
  69673. break;
  69674. default:
  69675. carryOn = false;
  69676. break;
  69677. }
  69678. if (! carryOn)
  69679. break;
  69680. }
  69681. return parseShape (xml, path);
  69682. }
  69683. Drawable* parseRect (const XmlElement& xml) const
  69684. {
  69685. Path rect;
  69686. const bool hasRX = xml.hasAttribute ("rx");
  69687. const bool hasRY = xml.hasAttribute ("ry");
  69688. if (hasRX || hasRY)
  69689. {
  69690. float rx = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  69691. float ry = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  69692. if (! hasRX)
  69693. rx = ry;
  69694. else if (! hasRY)
  69695. ry = rx;
  69696. rect.addRoundedRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  69697. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  69698. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  69699. getCoordLength (xml.getStringAttribute ("height"), viewBoxH),
  69700. rx, ry);
  69701. }
  69702. else
  69703. {
  69704. rect.addRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  69705. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  69706. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  69707. getCoordLength (xml.getStringAttribute ("height"), viewBoxH));
  69708. }
  69709. return parseShape (xml, rect);
  69710. }
  69711. Drawable* parseCircle (const XmlElement& xml) const
  69712. {
  69713. Path circle;
  69714. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  69715. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  69716. const float radius = getCoordLength (xml.getStringAttribute ("r"), viewBoxW);
  69717. circle.addEllipse (cx - radius, cy - radius, radius * 2.0f, radius * 2.0f);
  69718. return parseShape (xml, circle);
  69719. }
  69720. Drawable* parseEllipse (const XmlElement& xml) const
  69721. {
  69722. Path ellipse;
  69723. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  69724. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  69725. const float radiusX = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  69726. const float radiusY = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  69727. ellipse.addEllipse (cx - radiusX, cy - radiusY, radiusX * 2.0f, radiusY * 2.0f);
  69728. return parseShape (xml, ellipse);
  69729. }
  69730. Drawable* parseLine (const XmlElement& xml) const
  69731. {
  69732. Path line;
  69733. const float x1 = getCoordLength (xml.getStringAttribute ("x1"), viewBoxW);
  69734. const float y1 = getCoordLength (xml.getStringAttribute ("y1"), viewBoxH);
  69735. const float x2 = getCoordLength (xml.getStringAttribute ("x2"), viewBoxW);
  69736. const float y2 = getCoordLength (xml.getStringAttribute ("y2"), viewBoxH);
  69737. line.startNewSubPath (x1, y1);
  69738. line.lineTo (x2, y2);
  69739. return parseShape (xml, line);
  69740. }
  69741. Drawable* parsePolygon (const XmlElement& xml, const bool isPolyline) const
  69742. {
  69743. const String points (xml.getStringAttribute ("points"));
  69744. Path path;
  69745. int index = 0;
  69746. float x, y;
  69747. if (parseCoords (points, x, y, index, true))
  69748. {
  69749. float firstX = x;
  69750. float firstY = y;
  69751. float lastX = 0, lastY = 0;
  69752. path.startNewSubPath (x, y);
  69753. while (parseCoords (points, x, y, index, true))
  69754. {
  69755. lastX = x;
  69756. lastY = y;
  69757. path.lineTo (x, y);
  69758. }
  69759. if ((! isPolyline) || (firstX == lastX && firstY == lastY))
  69760. path.closeSubPath();
  69761. }
  69762. return parseShape (xml, path);
  69763. }
  69764. Drawable* parseShape (const XmlElement& xml, Path& path,
  69765. const bool shouldParseTransform = true) const
  69766. {
  69767. if (shouldParseTransform && xml.hasAttribute ("transform"))
  69768. {
  69769. SVGState newState (*this);
  69770. newState.addTransform (xml);
  69771. return newState.parseShape (xml, path, false);
  69772. }
  69773. DrawablePath* dp = new DrawablePath();
  69774. dp->setName (xml.getStringAttribute ("id"));
  69775. dp->setFill (Colours::transparentBlack);
  69776. path.applyTransform (transform);
  69777. dp->setPath (path);
  69778. Path::Iterator iter (path);
  69779. bool containsClosedSubPath = false;
  69780. while (iter.next())
  69781. {
  69782. if (iter.elementType == Path::Iterator::closePath)
  69783. {
  69784. containsClosedSubPath = true;
  69785. break;
  69786. }
  69787. }
  69788. dp->setFill (getPathFillType (path,
  69789. getStyleAttribute (&xml, "fill"),
  69790. getStyleAttribute (&xml, "fill-opacity"),
  69791. getStyleAttribute (&xml, "opacity"),
  69792. containsClosedSubPath ? Colours::black
  69793. : Colours::transparentBlack));
  69794. const String strokeType (getStyleAttribute (&xml, "stroke"));
  69795. if (strokeType.isNotEmpty() && ! strokeType.equalsIgnoreCase ("none"))
  69796. {
  69797. dp->setStrokeFill (getPathFillType (path, strokeType,
  69798. getStyleAttribute (&xml, "stroke-opacity"),
  69799. getStyleAttribute (&xml, "opacity"),
  69800. Colours::transparentBlack));
  69801. dp->setStrokeType (getStrokeFor (&xml));
  69802. }
  69803. return dp;
  69804. }
  69805. const XmlElement* findLinkedElement (const XmlElement* e) const
  69806. {
  69807. const String id (e->getStringAttribute ("xlink:href"));
  69808. if (! id.startsWithChar ('#'))
  69809. return 0;
  69810. return findElementForId (topLevelXml, id.substring (1));
  69811. }
  69812. void addGradientStopsIn (ColourGradient& cg, const XmlElement* const fillXml) const
  69813. {
  69814. if (fillXml == 0)
  69815. return;
  69816. forEachXmlChildElementWithTagName (*fillXml, e, "stop")
  69817. {
  69818. int index = 0;
  69819. Colour col (parseColour (getStyleAttribute (e, "stop-color"), index, Colours::black));
  69820. const String opacity (getStyleAttribute (e, "stop-opacity", "1"));
  69821. col = col.withMultipliedAlpha (jlimit (0.0f, 1.0f, opacity.getFloatValue()));
  69822. double offset = e->getDoubleAttribute ("offset");
  69823. if (e->getStringAttribute ("offset").containsChar ('%'))
  69824. offset *= 0.01;
  69825. cg.addColour (jlimit (0.0, 1.0, offset), col);
  69826. }
  69827. }
  69828. const FillType getPathFillType (const Path& path,
  69829. const String& fill,
  69830. const String& fillOpacity,
  69831. const String& overallOpacity,
  69832. const Colour& defaultColour) const
  69833. {
  69834. float opacity = 1.0f;
  69835. if (overallOpacity.isNotEmpty())
  69836. opacity = jlimit (0.0f, 1.0f, overallOpacity.getFloatValue());
  69837. if (fillOpacity.isNotEmpty())
  69838. opacity *= (jlimit (0.0f, 1.0f, fillOpacity.getFloatValue()));
  69839. if (fill.startsWithIgnoreCase ("url"))
  69840. {
  69841. const String id (fill.fromFirstOccurrenceOf ("#", false, false)
  69842. .upToLastOccurrenceOf (")", false, false).trim());
  69843. const XmlElement* const fillXml = findElementForId (topLevelXml, id);
  69844. if (fillXml != 0
  69845. && (fillXml->hasTagName ("linearGradient")
  69846. || fillXml->hasTagName ("radialGradient")))
  69847. {
  69848. const XmlElement* inheritedFrom = findLinkedElement (fillXml);
  69849. ColourGradient gradient;
  69850. addGradientStopsIn (gradient, inheritedFrom);
  69851. addGradientStopsIn (gradient, fillXml);
  69852. if (gradient.getNumColours() > 0)
  69853. {
  69854. gradient.addColour (0.0, gradient.getColour (0));
  69855. gradient.addColour (1.0, gradient.getColour (gradient.getNumColours() - 1));
  69856. }
  69857. else
  69858. {
  69859. gradient.addColour (0.0, Colours::black);
  69860. gradient.addColour (1.0, Colours::black);
  69861. }
  69862. if (overallOpacity.isNotEmpty())
  69863. gradient.multiplyOpacity (overallOpacity.getFloatValue());
  69864. jassert (gradient.getNumColours() > 0);
  69865. gradient.isRadial = fillXml->hasTagName ("radialGradient");
  69866. float gradientWidth = viewBoxW;
  69867. float gradientHeight = viewBoxH;
  69868. float dx = 0.0f;
  69869. float dy = 0.0f;
  69870. const bool userSpace = fillXml->getStringAttribute ("gradientUnits").equalsIgnoreCase ("userSpaceOnUse");
  69871. if (! userSpace)
  69872. {
  69873. const Rectangle<float> bounds (path.getBounds());
  69874. dx = bounds.getX();
  69875. dy = bounds.getY();
  69876. gradientWidth = bounds.getWidth();
  69877. gradientHeight = bounds.getHeight();
  69878. }
  69879. if (gradient.isRadial)
  69880. {
  69881. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("cx", "50%"), gradientWidth),
  69882. dy + getCoordLength (fillXml->getStringAttribute ("cy", "50%"), gradientHeight));
  69883. const float radius = getCoordLength (fillXml->getStringAttribute ("r", "50%"), gradientWidth);
  69884. gradient.point2 = gradient.point1 + Point<float> (radius, 0.0f);
  69885. //xxx (the fx, fy focal point isn't handled properly here..)
  69886. }
  69887. else
  69888. {
  69889. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x1", "0%"), gradientWidth),
  69890. dy + getCoordLength (fillXml->getStringAttribute ("y1", "0%"), gradientHeight));
  69891. gradient.point2.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x2", "100%"), gradientWidth),
  69892. dy + getCoordLength (fillXml->getStringAttribute ("y2", "0%"), gradientHeight));
  69893. if (gradient.point1 == gradient.point2)
  69894. return Colour (gradient.getColour (gradient.getNumColours() - 1));
  69895. }
  69896. FillType type (gradient);
  69897. type.transform = parseTransform (fillXml->getStringAttribute ("gradientTransform"))
  69898. .followedBy (transform);
  69899. return type;
  69900. }
  69901. }
  69902. if (fill.equalsIgnoreCase ("none"))
  69903. return Colours::transparentBlack;
  69904. int i = 0;
  69905. const Colour colour (parseColour (fill, i, defaultColour));
  69906. return colour.withMultipliedAlpha (opacity);
  69907. }
  69908. const PathStrokeType getStrokeFor (const XmlElement* const xml) const
  69909. {
  69910. const String strokeWidth (getStyleAttribute (xml, "stroke-width"));
  69911. const String cap (getStyleAttribute (xml, "stroke-linecap"));
  69912. const String join (getStyleAttribute (xml, "stroke-linejoin"));
  69913. //const String mitreLimit (getStyleAttribute (xml, "stroke-miterlimit"));
  69914. //const String dashArray (getStyleAttribute (xml, "stroke-dasharray"));
  69915. //const String dashOffset (getStyleAttribute (xml, "stroke-dashoffset"));
  69916. PathStrokeType::JointStyle joinStyle = PathStrokeType::mitered;
  69917. PathStrokeType::EndCapStyle capStyle = PathStrokeType::butt;
  69918. if (join.equalsIgnoreCase ("round"))
  69919. joinStyle = PathStrokeType::curved;
  69920. else if (join.equalsIgnoreCase ("bevel"))
  69921. joinStyle = PathStrokeType::beveled;
  69922. if (cap.equalsIgnoreCase ("round"))
  69923. capStyle = PathStrokeType::rounded;
  69924. else if (cap.equalsIgnoreCase ("square"))
  69925. capStyle = PathStrokeType::square;
  69926. float ox = 0.0f, oy = 0.0f;
  69927. transform.transformPoint (ox, oy);
  69928. float x = getCoordLength (strokeWidth, viewBoxW), y = 0.0f;
  69929. transform.transformPoint (x, y);
  69930. return PathStrokeType (strokeWidth.isNotEmpty() ? juce_hypotf (x - ox, y - oy) : 1.0f,
  69931. joinStyle, capStyle);
  69932. }
  69933. Drawable* parseText (const XmlElement& xml)
  69934. {
  69935. Array <float> xCoords, yCoords, dxCoords, dyCoords;
  69936. getCoordList (xCoords, getInheritedAttribute (&xml, "x"), true, true);
  69937. getCoordList (yCoords, getInheritedAttribute (&xml, "y"), true, false);
  69938. getCoordList (dxCoords, getInheritedAttribute (&xml, "dx"), true, true);
  69939. getCoordList (dyCoords, getInheritedAttribute (&xml, "dy"), true, false);
  69940. //xxx not done text yet!
  69941. forEachXmlChildElement (xml, e)
  69942. {
  69943. if (e->isTextElement())
  69944. {
  69945. const String text (e->getText());
  69946. Path path;
  69947. Drawable* s = parseShape (*e, path);
  69948. delete s;
  69949. }
  69950. else if (e->hasTagName ("tspan"))
  69951. {
  69952. Drawable* s = parseText (*e);
  69953. delete s;
  69954. }
  69955. }
  69956. return 0;
  69957. }
  69958. void addTransform (const XmlElement& xml)
  69959. {
  69960. transform = parseTransform (xml.getStringAttribute ("transform"))
  69961. .followedBy (transform);
  69962. }
  69963. bool parseCoord (const String& s, float& value, int& index,
  69964. const bool allowUnits, const bool isX) const
  69965. {
  69966. String number;
  69967. if (! parseNextNumber (s, number, index, allowUnits))
  69968. {
  69969. value = 0;
  69970. return false;
  69971. }
  69972. value = getCoordLength (number, isX ? viewBoxW : viewBoxH);
  69973. return true;
  69974. }
  69975. bool parseCoords (const String& s, float& x, float& y,
  69976. int& index, const bool allowUnits) const
  69977. {
  69978. return parseCoord (s, x, index, allowUnits, true)
  69979. && parseCoord (s, y, index, allowUnits, false);
  69980. }
  69981. float getCoordLength (const String& s, const float sizeForProportions) const
  69982. {
  69983. float n = s.getFloatValue();
  69984. const int len = s.length();
  69985. if (len > 2)
  69986. {
  69987. const float dpi = 96.0f;
  69988. const juce_wchar n1 = s [len - 2];
  69989. const juce_wchar n2 = s [len - 1];
  69990. if (n1 == 'i' && n2 == 'n')
  69991. n *= dpi;
  69992. else if (n1 == 'm' && n2 == 'm')
  69993. n *= dpi / 25.4f;
  69994. else if (n1 == 'c' && n2 == 'm')
  69995. n *= dpi / 2.54f;
  69996. else if (n1 == 'p' && n2 == 'c')
  69997. n *= 15.0f;
  69998. else if (n2 == '%')
  69999. n *= 0.01f * sizeForProportions;
  70000. }
  70001. return n;
  70002. }
  70003. void getCoordList (Array <float>& coords, const String& list,
  70004. const bool allowUnits, const bool isX) const
  70005. {
  70006. int index = 0;
  70007. float value;
  70008. while (parseCoord (list, value, index, allowUnits, isX))
  70009. coords.add (value);
  70010. }
  70011. void parseCSSStyle (const XmlElement& xml)
  70012. {
  70013. cssStyleText = xml.getAllSubText() + "\n" + cssStyleText;
  70014. }
  70015. const String getStyleAttribute (const XmlElement* xml, const String& attributeName,
  70016. const String& defaultValue = String::empty) const
  70017. {
  70018. if (xml->hasAttribute (attributeName))
  70019. return xml->getStringAttribute (attributeName, defaultValue);
  70020. const String styleAtt (xml->getStringAttribute ("style"));
  70021. if (styleAtt.isNotEmpty())
  70022. {
  70023. const String value (getAttributeFromStyleList (styleAtt, attributeName, String::empty));
  70024. if (value.isNotEmpty())
  70025. return value;
  70026. }
  70027. else if (xml->hasAttribute ("class"))
  70028. {
  70029. const String className ("." + xml->getStringAttribute ("class"));
  70030. int index = cssStyleText.indexOfIgnoreCase (className + " ");
  70031. if (index < 0)
  70032. index = cssStyleText.indexOfIgnoreCase (className + "{");
  70033. if (index >= 0)
  70034. {
  70035. const int openBracket = cssStyleText.indexOfChar (index, '{');
  70036. if (openBracket > index)
  70037. {
  70038. const int closeBracket = cssStyleText.indexOfChar (openBracket, '}');
  70039. if (closeBracket > openBracket)
  70040. {
  70041. const String value (getAttributeFromStyleList (cssStyleText.substring (openBracket + 1, closeBracket), attributeName, defaultValue));
  70042. if (value.isNotEmpty())
  70043. return value;
  70044. }
  70045. }
  70046. }
  70047. }
  70048. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  70049. if (xml != 0)
  70050. return getStyleAttribute (xml, attributeName, defaultValue);
  70051. return defaultValue;
  70052. }
  70053. const String getInheritedAttribute (const XmlElement* xml, const String& attributeName) const
  70054. {
  70055. if (xml->hasAttribute (attributeName))
  70056. return xml->getStringAttribute (attributeName);
  70057. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  70058. if (xml != 0)
  70059. return getInheritedAttribute (xml, attributeName);
  70060. return String::empty;
  70061. }
  70062. static bool isIdentifierChar (const juce_wchar c)
  70063. {
  70064. return CharacterFunctions::isLetter (c) || c == '-';
  70065. }
  70066. static const String getAttributeFromStyleList (const String& list, const String& attributeName, const String& defaultValue)
  70067. {
  70068. int i = 0;
  70069. for (;;)
  70070. {
  70071. i = list.indexOf (i, attributeName);
  70072. if (i < 0)
  70073. break;
  70074. if ((i == 0 || (i > 0 && ! isIdentifierChar (list [i - 1])))
  70075. && ! isIdentifierChar (list [i + attributeName.length()]))
  70076. {
  70077. i = list.indexOfChar (i, ':');
  70078. if (i < 0)
  70079. break;
  70080. int end = list.indexOfChar (i, ';');
  70081. if (end < 0)
  70082. end = 0x7ffff;
  70083. return list.substring (i + 1, end).trim();
  70084. }
  70085. ++i;
  70086. }
  70087. return defaultValue;
  70088. }
  70089. static bool parseNextNumber (const String& source, String& value, int& index, const bool allowUnits)
  70090. {
  70091. const juce_wchar* const s = source;
  70092. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == ',')
  70093. ++index;
  70094. int start = index;
  70095. if (CharacterFunctions::isDigit (s[index]) || s[index] == '.' || s[index] == '-')
  70096. ++index;
  70097. while (CharacterFunctions::isDigit (s[index]) || s[index] == '.')
  70098. ++index;
  70099. if ((s[index] == 'e' || s[index] == 'E')
  70100. && (CharacterFunctions::isDigit (s[index + 1])
  70101. || s[index + 1] == '-'
  70102. || s[index + 1] == '+'))
  70103. {
  70104. index += 2;
  70105. while (CharacterFunctions::isDigit (s[index]))
  70106. ++index;
  70107. }
  70108. if (allowUnits)
  70109. {
  70110. while (CharacterFunctions::isLetter (s[index]))
  70111. ++index;
  70112. }
  70113. if (index == start)
  70114. return false;
  70115. value = String (s + start, index - start);
  70116. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == ',')
  70117. ++index;
  70118. return true;
  70119. }
  70120. static const Colour parseColour (const String& s, int& index, const Colour& defaultColour)
  70121. {
  70122. if (s [index] == '#')
  70123. {
  70124. uint32 hex [6];
  70125. zeromem (hex, sizeof (hex));
  70126. int numChars = 0;
  70127. for (int i = 6; --i >= 0;)
  70128. {
  70129. const int hexValue = CharacterFunctions::getHexDigitValue (s [++index]);
  70130. if (hexValue >= 0)
  70131. hex [numChars++] = hexValue;
  70132. else
  70133. break;
  70134. }
  70135. if (numChars <= 3)
  70136. return Colour ((uint8) (hex [0] * 0x11),
  70137. (uint8) (hex [1] * 0x11),
  70138. (uint8) (hex [2] * 0x11));
  70139. else
  70140. return Colour ((uint8) ((hex [0] << 4) + hex [1]),
  70141. (uint8) ((hex [2] << 4) + hex [3]),
  70142. (uint8) ((hex [4] << 4) + hex [5]));
  70143. }
  70144. else if (s [index] == 'r'
  70145. && s [index + 1] == 'g'
  70146. && s [index + 2] == 'b')
  70147. {
  70148. const int openBracket = s.indexOfChar (index, '(');
  70149. const int closeBracket = s.indexOfChar (openBracket, ')');
  70150. if (openBracket >= 3 && closeBracket > openBracket)
  70151. {
  70152. index = closeBracket;
  70153. StringArray tokens;
  70154. tokens.addTokens (s.substring (openBracket + 1, closeBracket), ",", "");
  70155. tokens.trim();
  70156. tokens.removeEmptyStrings();
  70157. if (tokens[0].containsChar ('%'))
  70158. return Colour ((uint8) roundToInt (2.55 * tokens[0].getDoubleValue()),
  70159. (uint8) roundToInt (2.55 * tokens[1].getDoubleValue()),
  70160. (uint8) roundToInt (2.55 * tokens[2].getDoubleValue()));
  70161. else
  70162. return Colour ((uint8) tokens[0].getIntValue(),
  70163. (uint8) tokens[1].getIntValue(),
  70164. (uint8) tokens[2].getIntValue());
  70165. }
  70166. }
  70167. return Colours::findColourForName (s, defaultColour);
  70168. }
  70169. static const AffineTransform parseTransform (String t)
  70170. {
  70171. AffineTransform result;
  70172. while (t.isNotEmpty())
  70173. {
  70174. StringArray tokens;
  70175. tokens.addTokens (t.fromFirstOccurrenceOf ("(", false, false)
  70176. .upToFirstOccurrenceOf (")", false, false),
  70177. ", ", String::empty);
  70178. tokens.removeEmptyStrings (true);
  70179. float numbers [6];
  70180. for (int i = 0; i < 6; ++i)
  70181. numbers[i] = tokens[i].getFloatValue();
  70182. AffineTransform trans;
  70183. if (t.startsWithIgnoreCase ("matrix"))
  70184. {
  70185. trans = AffineTransform (numbers[0], numbers[2], numbers[4],
  70186. numbers[1], numbers[3], numbers[5]);
  70187. }
  70188. else if (t.startsWithIgnoreCase ("translate"))
  70189. {
  70190. jassert (tokens.size() == 2);
  70191. trans = AffineTransform::translation (numbers[0], numbers[1]);
  70192. }
  70193. else if (t.startsWithIgnoreCase ("scale"))
  70194. {
  70195. if (tokens.size() == 1)
  70196. trans = AffineTransform::scale (numbers[0], numbers[0]);
  70197. else
  70198. trans = AffineTransform::scale (numbers[0], numbers[1]);
  70199. }
  70200. else if (t.startsWithIgnoreCase ("rotate"))
  70201. {
  70202. if (tokens.size() != 3)
  70203. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi));
  70204. else
  70205. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi),
  70206. numbers[1], numbers[2]);
  70207. }
  70208. else if (t.startsWithIgnoreCase ("skewX"))
  70209. {
  70210. trans = AffineTransform (1.0f, std::tan (numbers[0] * (float_Pi / 180.0f)), 0.0f,
  70211. 0.0f, 1.0f, 0.0f);
  70212. }
  70213. else if (t.startsWithIgnoreCase ("skewY"))
  70214. {
  70215. trans = AffineTransform (1.0f, 0.0f, 0.0f,
  70216. std::tan (numbers[0] * (float_Pi / 180.0f)), 1.0f, 0.0f);
  70217. }
  70218. result = trans.followedBy (result);
  70219. t = t.fromFirstOccurrenceOf (")", false, false).trimStart();
  70220. }
  70221. return result;
  70222. }
  70223. static void endpointToCentreParameters (const double x1, const double y1,
  70224. const double x2, const double y2,
  70225. const double angle,
  70226. const bool largeArc, const bool sweep,
  70227. double& rx, double& ry,
  70228. double& centreX, double& centreY,
  70229. double& startAngle, double& deltaAngle)
  70230. {
  70231. const double midX = (x1 - x2) * 0.5;
  70232. const double midY = (y1 - y2) * 0.5;
  70233. const double cosAngle = cos (angle);
  70234. const double sinAngle = sin (angle);
  70235. const double xp = cosAngle * midX + sinAngle * midY;
  70236. const double yp = cosAngle * midY - sinAngle * midX;
  70237. const double xp2 = xp * xp;
  70238. const double yp2 = yp * yp;
  70239. double rx2 = rx * rx;
  70240. double ry2 = ry * ry;
  70241. const double s = (xp2 / rx2) + (yp2 / ry2);
  70242. double c;
  70243. if (s <= 1.0)
  70244. {
  70245. c = std::sqrt (jmax (0.0, ((rx2 * ry2) - (rx2 * yp2) - (ry2 * xp2))
  70246. / (( rx2 * yp2) + (ry2 * xp2))));
  70247. if (largeArc == sweep)
  70248. c = -c;
  70249. }
  70250. else
  70251. {
  70252. const double s2 = std::sqrt (s);
  70253. rx *= s2;
  70254. ry *= s2;
  70255. rx2 = rx * rx;
  70256. ry2 = ry * ry;
  70257. c = 0;
  70258. }
  70259. const double cpx = ((rx * yp) / ry) * c;
  70260. const double cpy = ((-ry * xp) / rx) * c;
  70261. centreX = ((x1 + x2) * 0.5) + (cosAngle * cpx) - (sinAngle * cpy);
  70262. centreY = ((y1 + y2) * 0.5) + (sinAngle * cpx) + (cosAngle * cpy);
  70263. const double ux = (xp - cpx) / rx;
  70264. const double uy = (yp - cpy) / ry;
  70265. const double vx = (-xp - cpx) / rx;
  70266. const double vy = (-yp - cpy) / ry;
  70267. const double length = juce_hypot (ux, uy);
  70268. startAngle = acos (jlimit (-1.0, 1.0, ux / length));
  70269. if (uy < 0)
  70270. startAngle = -startAngle;
  70271. startAngle += double_Pi * 0.5;
  70272. deltaAngle = acos (jlimit (-1.0, 1.0, ((ux * vx) + (uy * vy))
  70273. / (length * juce_hypot (vx, vy))));
  70274. if ((ux * vy) - (uy * vx) < 0)
  70275. deltaAngle = -deltaAngle;
  70276. if (sweep)
  70277. {
  70278. if (deltaAngle < 0)
  70279. deltaAngle += double_Pi * 2.0;
  70280. }
  70281. else
  70282. {
  70283. if (deltaAngle > 0)
  70284. deltaAngle -= double_Pi * 2.0;
  70285. }
  70286. deltaAngle = fmod (deltaAngle, double_Pi * 2.0);
  70287. }
  70288. static const XmlElement* findElementForId (const XmlElement* const parent, const String& id)
  70289. {
  70290. forEachXmlChildElement (*parent, e)
  70291. {
  70292. if (e->compareAttribute ("id", id))
  70293. return e;
  70294. const XmlElement* const found = findElementForId (e, id);
  70295. if (found != 0)
  70296. return found;
  70297. }
  70298. return 0;
  70299. }
  70300. SVGState& operator= (const SVGState&);
  70301. };
  70302. Drawable* Drawable::createFromSVG (const XmlElement& svgDocument)
  70303. {
  70304. SVGState state (&svgDocument);
  70305. return state.parseSVGElement (svgDocument);
  70306. }
  70307. END_JUCE_NAMESPACE
  70308. /*** End of inlined file: juce_SVGParser.cpp ***/
  70309. /*** Start of inlined file: juce_DropShadowEffect.cpp ***/
  70310. BEGIN_JUCE_NAMESPACE
  70311. #if JUCE_MSVC && JUCE_DEBUG
  70312. #pragma optimize ("t", on)
  70313. #endif
  70314. DropShadowEffect::DropShadowEffect()
  70315. : offsetX (0),
  70316. offsetY (0),
  70317. radius (4),
  70318. opacity (0.6f)
  70319. {
  70320. }
  70321. DropShadowEffect::~DropShadowEffect()
  70322. {
  70323. }
  70324. void DropShadowEffect::setShadowProperties (const float newRadius,
  70325. const float newOpacity,
  70326. const int newShadowOffsetX,
  70327. const int newShadowOffsetY)
  70328. {
  70329. radius = jmax (1.1f, newRadius);
  70330. offsetX = newShadowOffsetX;
  70331. offsetY = newShadowOffsetY;
  70332. opacity = newOpacity;
  70333. }
  70334. void DropShadowEffect::applyEffect (Image& image, Graphics& g)
  70335. {
  70336. const int w = image.getWidth();
  70337. const int h = image.getHeight();
  70338. Image shadowImage (Image::SingleChannel, w, h, false);
  70339. const Image::BitmapData srcData (image, 0, 0, w, h);
  70340. const Image::BitmapData destData (shadowImage, 0, 0, w, h, true);
  70341. const int filter = roundToInt (63.0f / radius);
  70342. const int radiusMinus1 = roundToInt ((radius - 1.0f) * 63.0f);
  70343. for (int x = w; --x >= 0;)
  70344. {
  70345. int shadowAlpha = 0;
  70346. const PixelARGB* src = ((const PixelARGB*) srcData.data) + x;
  70347. uint8* shadowPix = destData.data + x;
  70348. for (int y = h; --y >= 0;)
  70349. {
  70350. shadowAlpha = ((shadowAlpha * radiusMinus1 + (src->getAlpha() << 6)) * filter) >> 12;
  70351. *shadowPix = (uint8) shadowAlpha;
  70352. src = (const PixelARGB*) (((const uint8*) src) + srcData.lineStride);
  70353. shadowPix += destData.lineStride;
  70354. }
  70355. }
  70356. for (int y = h; --y >= 0;)
  70357. {
  70358. int shadowAlpha = 0;
  70359. uint8* shadowPix = destData.getLinePointer (y);
  70360. for (int x = w; --x >= 0;)
  70361. {
  70362. shadowAlpha = ((shadowAlpha * radiusMinus1 + (*shadowPix << 6)) * filter) >> 12;
  70363. *shadowPix++ = (uint8) shadowAlpha;
  70364. }
  70365. }
  70366. g.setColour (Colours::black.withAlpha (opacity));
  70367. g.drawImageAt (shadowImage, offsetX, offsetY, true);
  70368. g.setOpacity (1.0f);
  70369. g.drawImageAt (image, 0, 0);
  70370. }
  70371. #if JUCE_MSVC && JUCE_DEBUG
  70372. #pragma optimize ("", on) // resets optimisations to the project defaults
  70373. #endif
  70374. END_JUCE_NAMESPACE
  70375. /*** End of inlined file: juce_DropShadowEffect.cpp ***/
  70376. /*** Start of inlined file: juce_GlowEffect.cpp ***/
  70377. BEGIN_JUCE_NAMESPACE
  70378. GlowEffect::GlowEffect()
  70379. : radius (2.0f),
  70380. colour (Colours::white)
  70381. {
  70382. }
  70383. GlowEffect::~GlowEffect()
  70384. {
  70385. }
  70386. void GlowEffect::setGlowProperties (const float newRadius,
  70387. const Colour& newColour)
  70388. {
  70389. radius = newRadius;
  70390. colour = newColour;
  70391. }
  70392. void GlowEffect::applyEffect (Image& image, Graphics& g)
  70393. {
  70394. Image temp (image.getFormat(), image.getWidth(), image.getHeight(), true);
  70395. ImageConvolutionKernel blurKernel (roundToInt (radius * 2.0f));
  70396. blurKernel.createGaussianBlur (radius);
  70397. blurKernel.rescaleAllValues (radius);
  70398. blurKernel.applyToImage (temp, image, image.getBounds());
  70399. g.setColour (colour);
  70400. g.drawImageAt (temp, 0, 0, true);
  70401. g.setOpacity (1.0f);
  70402. g.drawImageAt (image, 0, 0, false);
  70403. }
  70404. END_JUCE_NAMESPACE
  70405. /*** End of inlined file: juce_GlowEffect.cpp ***/
  70406. /*** Start of inlined file: juce_ReduceOpacityEffect.cpp ***/
  70407. BEGIN_JUCE_NAMESPACE
  70408. ReduceOpacityEffect::ReduceOpacityEffect (const float opacity_)
  70409. : opacity (opacity_)
  70410. {
  70411. }
  70412. ReduceOpacityEffect::~ReduceOpacityEffect()
  70413. {
  70414. }
  70415. void ReduceOpacityEffect::setOpacity (const float newOpacity)
  70416. {
  70417. opacity = jlimit (0.0f, 1.0f, newOpacity);
  70418. }
  70419. void ReduceOpacityEffect::applyEffect (Image& image, Graphics& g)
  70420. {
  70421. g.setOpacity (opacity);
  70422. g.drawImageAt (image, 0, 0);
  70423. }
  70424. END_JUCE_NAMESPACE
  70425. /*** End of inlined file: juce_ReduceOpacityEffect.cpp ***/
  70426. /*** Start of inlined file: juce_Font.cpp ***/
  70427. BEGIN_JUCE_NAMESPACE
  70428. namespace FontValues
  70429. {
  70430. static float limitFontHeight (const float height) throw()
  70431. {
  70432. return jlimit (0.1f, 10000.0f, height);
  70433. }
  70434. static const float defaultFontHeight = 14.0f;
  70435. static String fallbackFont;
  70436. }
  70437. Font::SharedFontInternal::SharedFontInternal (const String& typefaceName_, const float height_, const float horizontalScale_,
  70438. const float kerning_, const float ascent_, const int styleFlags_,
  70439. Typeface* const typeface_) throw()
  70440. : typefaceName (typefaceName_),
  70441. height (height_),
  70442. horizontalScale (horizontalScale_),
  70443. kerning (kerning_),
  70444. ascent (ascent_),
  70445. styleFlags (styleFlags_),
  70446. typeface (typeface_)
  70447. {
  70448. }
  70449. Font::SharedFontInternal::SharedFontInternal (const SharedFontInternal& other) throw()
  70450. : typefaceName (other.typefaceName),
  70451. height (other.height),
  70452. horizontalScale (other.horizontalScale),
  70453. kerning (other.kerning),
  70454. ascent (other.ascent),
  70455. styleFlags (other.styleFlags),
  70456. typeface (other.typeface)
  70457. {
  70458. }
  70459. Font::Font() throw()
  70460. : font (new SharedFontInternal (getDefaultSansSerifFontName(), FontValues::defaultFontHeight,
  70461. 1.0f, 0, 0, Font::plain, 0))
  70462. {
  70463. }
  70464. Font::Font (const float fontHeight, const int styleFlags_) throw()
  70465. : font (new SharedFontInternal (getDefaultSansSerifFontName(), FontValues::limitFontHeight (fontHeight),
  70466. 1.0f, 0, 0, styleFlags_, 0))
  70467. {
  70468. }
  70469. Font::Font (const String& typefaceName_,
  70470. const float fontHeight,
  70471. const int styleFlags_) throw()
  70472. : font (new SharedFontInternal (typefaceName_, FontValues::limitFontHeight (fontHeight),
  70473. 1.0f, 0, 0, styleFlags_, 0))
  70474. {
  70475. }
  70476. Font::Font (const Font& other) throw()
  70477. : font (other.font)
  70478. {
  70479. }
  70480. Font& Font::operator= (const Font& other) throw()
  70481. {
  70482. font = other.font;
  70483. return *this;
  70484. }
  70485. Font::~Font() throw()
  70486. {
  70487. }
  70488. Font::Font (const Typeface::Ptr& typeface) throw()
  70489. : font (new SharedFontInternal (typeface->getName(), FontValues::defaultFontHeight,
  70490. 1.0f, 0, 0, Font::plain, typeface))
  70491. {
  70492. }
  70493. bool Font::operator== (const Font& other) const throw()
  70494. {
  70495. return font == other.font
  70496. || (font->height == other.font->height
  70497. && font->styleFlags == other.font->styleFlags
  70498. && font->horizontalScale == other.font->horizontalScale
  70499. && font->kerning == other.font->kerning
  70500. && font->typefaceName == other.font->typefaceName);
  70501. }
  70502. bool Font::operator!= (const Font& other) const throw()
  70503. {
  70504. return ! operator== (other);
  70505. }
  70506. void Font::dupeInternalIfShared() throw()
  70507. {
  70508. if (font->getReferenceCount() > 1)
  70509. font = new SharedFontInternal (*font);
  70510. }
  70511. const String Font::getDefaultSansSerifFontName() throw()
  70512. {
  70513. static const String name ("<Sans-Serif>");
  70514. return name;
  70515. }
  70516. const String Font::getDefaultSerifFontName() throw()
  70517. {
  70518. static const String name ("<Serif>");
  70519. return name;
  70520. }
  70521. const String Font::getDefaultMonospacedFontName() throw()
  70522. {
  70523. static const String name ("<Monospaced>");
  70524. return name;
  70525. }
  70526. void Font::setTypefaceName (const String& faceName) throw()
  70527. {
  70528. if (faceName != font->typefaceName)
  70529. {
  70530. dupeInternalIfShared();
  70531. font->typefaceName = faceName;
  70532. font->typeface = 0;
  70533. font->ascent = 0;
  70534. }
  70535. }
  70536. const String Font::getFallbackFontName() throw()
  70537. {
  70538. return FontValues::fallbackFont;
  70539. }
  70540. void Font::setFallbackFontName (const String& name) throw()
  70541. {
  70542. FontValues::fallbackFont = name;
  70543. }
  70544. void Font::setHeight (float newHeight) throw()
  70545. {
  70546. newHeight = FontValues::limitFontHeight (newHeight);
  70547. if (font->height != newHeight)
  70548. {
  70549. dupeInternalIfShared();
  70550. font->height = newHeight;
  70551. }
  70552. }
  70553. void Font::setHeightWithoutChangingWidth (float newHeight) throw()
  70554. {
  70555. newHeight = FontValues::limitFontHeight (newHeight);
  70556. if (font->height != newHeight)
  70557. {
  70558. dupeInternalIfShared();
  70559. font->horizontalScale *= (font->height / newHeight);
  70560. font->height = newHeight;
  70561. }
  70562. }
  70563. void Font::setStyleFlags (const int newFlags) throw()
  70564. {
  70565. if (font->styleFlags != newFlags)
  70566. {
  70567. dupeInternalIfShared();
  70568. font->styleFlags = newFlags;
  70569. font->typeface = 0;
  70570. font->ascent = 0;
  70571. }
  70572. }
  70573. void Font::setSizeAndStyle (float newHeight,
  70574. const int newStyleFlags,
  70575. const float newHorizontalScale,
  70576. const float newKerningAmount) throw()
  70577. {
  70578. newHeight = FontValues::limitFontHeight (newHeight);
  70579. if (font->height != newHeight
  70580. || font->horizontalScale != newHorizontalScale
  70581. || font->kerning != newKerningAmount)
  70582. {
  70583. dupeInternalIfShared();
  70584. font->height = newHeight;
  70585. font->horizontalScale = newHorizontalScale;
  70586. font->kerning = newKerningAmount;
  70587. }
  70588. setStyleFlags (newStyleFlags);
  70589. }
  70590. void Font::setHorizontalScale (const float scaleFactor) throw()
  70591. {
  70592. dupeInternalIfShared();
  70593. font->horizontalScale = scaleFactor;
  70594. }
  70595. void Font::setExtraKerningFactor (const float extraKerning) throw()
  70596. {
  70597. dupeInternalIfShared();
  70598. font->kerning = extraKerning;
  70599. }
  70600. void Font::setBold (const bool shouldBeBold) throw()
  70601. {
  70602. setStyleFlags (shouldBeBold ? (font->styleFlags | bold)
  70603. : (font->styleFlags & ~bold));
  70604. }
  70605. bool Font::isBold() const throw()
  70606. {
  70607. return (font->styleFlags & bold) != 0;
  70608. }
  70609. void Font::setItalic (const bool shouldBeItalic) throw()
  70610. {
  70611. setStyleFlags (shouldBeItalic ? (font->styleFlags | italic)
  70612. : (font->styleFlags & ~italic));
  70613. }
  70614. bool Font::isItalic() const throw()
  70615. {
  70616. return (font->styleFlags & italic) != 0;
  70617. }
  70618. void Font::setUnderline (const bool shouldBeUnderlined) throw()
  70619. {
  70620. setStyleFlags (shouldBeUnderlined ? (font->styleFlags | underlined)
  70621. : (font->styleFlags & ~underlined));
  70622. }
  70623. bool Font::isUnderlined() const throw()
  70624. {
  70625. return (font->styleFlags & underlined) != 0;
  70626. }
  70627. float Font::getAscent() const throw()
  70628. {
  70629. if (font->ascent == 0)
  70630. font->ascent = getTypeface()->getAscent();
  70631. return font->height * font->ascent;
  70632. }
  70633. float Font::getDescent() const throw()
  70634. {
  70635. return font->height - getAscent();
  70636. }
  70637. int Font::getStringWidth (const String& text) const throw()
  70638. {
  70639. return roundToInt (getStringWidthFloat (text));
  70640. }
  70641. float Font::getStringWidthFloat (const String& text) const throw()
  70642. {
  70643. float w = getTypeface()->getStringWidth (text);
  70644. if (font->kerning != 0)
  70645. w += font->kerning * text.length();
  70646. return w * font->height * font->horizontalScale;
  70647. }
  70648. void Font::getGlyphPositions (const String& text, Array <int>& glyphs, Array <float>& xOffsets) const throw()
  70649. {
  70650. getTypeface()->getGlyphPositions (text, glyphs, xOffsets);
  70651. const float scale = font->height * font->horizontalScale;
  70652. const int num = xOffsets.size();
  70653. if (num > 0)
  70654. {
  70655. float* const x = &(xOffsets.getReference(0));
  70656. if (font->kerning != 0)
  70657. {
  70658. for (int i = 0; i < num; ++i)
  70659. x[i] = (x[i] + i * font->kerning) * scale;
  70660. }
  70661. else
  70662. {
  70663. for (int i = 0; i < num; ++i)
  70664. x[i] *= scale;
  70665. }
  70666. }
  70667. }
  70668. void Font::findFonts (Array<Font>& destArray) throw()
  70669. {
  70670. const StringArray names (findAllTypefaceNames());
  70671. for (int i = 0; i < names.size(); ++i)
  70672. destArray.add (Font (names[i], FontValues::defaultFontHeight, Font::plain));
  70673. }
  70674. const String Font::toString() const
  70675. {
  70676. String s (getTypefaceName());
  70677. if (s == getDefaultSansSerifFontName())
  70678. s = String::empty;
  70679. else
  70680. s += "; ";
  70681. s += String (getHeight(), 1);
  70682. if (isBold())
  70683. s += " bold";
  70684. if (isItalic())
  70685. s += " italic";
  70686. return s;
  70687. }
  70688. const Font Font::fromString (const String& fontDescription)
  70689. {
  70690. String name;
  70691. const int separator = fontDescription.indexOfChar (';');
  70692. if (separator > 0)
  70693. name = fontDescription.substring (0, separator).trim();
  70694. if (name.isEmpty())
  70695. name = getDefaultSansSerifFontName();
  70696. String sizeAndStyle (fontDescription.substring (separator + 1));
  70697. float height = sizeAndStyle.getFloatValue();
  70698. if (height <= 0)
  70699. height = 10.0f;
  70700. int flags = Font::plain;
  70701. if (sizeAndStyle.containsIgnoreCase ("bold"))
  70702. flags |= Font::bold;
  70703. if (sizeAndStyle.containsIgnoreCase ("italic"))
  70704. flags |= Font::italic;
  70705. return Font (name, height, flags);
  70706. }
  70707. class TypefaceCache : public DeletedAtShutdown
  70708. {
  70709. public:
  70710. TypefaceCache (int numToCache = 10) throw()
  70711. : counter (1)
  70712. {
  70713. while (--numToCache >= 0)
  70714. faces.add (new CachedFace());
  70715. }
  70716. ~TypefaceCache()
  70717. {
  70718. clearSingletonInstance();
  70719. }
  70720. juce_DeclareSingleton_SingleThreaded_Minimal (TypefaceCache)
  70721. const Typeface::Ptr findTypefaceFor (const Font& font) throw()
  70722. {
  70723. const int flags = font.getStyleFlags() & (Font::bold | Font::italic);
  70724. const String faceName (font.getTypefaceName());
  70725. int i;
  70726. for (i = faces.size(); --i >= 0;)
  70727. {
  70728. CachedFace* const face = faces.getUnchecked(i);
  70729. if (face->flags == flags
  70730. && face->typefaceName == faceName)
  70731. {
  70732. face->lastUsageCount = ++counter;
  70733. return face->typeFace;
  70734. }
  70735. }
  70736. int replaceIndex = 0;
  70737. int bestLastUsageCount = std::numeric_limits<int>::max();
  70738. for (i = faces.size(); --i >= 0;)
  70739. {
  70740. const int lu = faces.getUnchecked(i)->lastUsageCount;
  70741. if (bestLastUsageCount > lu)
  70742. {
  70743. bestLastUsageCount = lu;
  70744. replaceIndex = i;
  70745. }
  70746. }
  70747. CachedFace* const face = faces.getUnchecked (replaceIndex);
  70748. face->typefaceName = faceName;
  70749. face->flags = flags;
  70750. face->lastUsageCount = ++counter;
  70751. face->typeFace = LookAndFeel::getDefaultLookAndFeel().getTypefaceForFont (font);
  70752. jassert (face->typeFace != 0); // the look and feel must return a typeface!
  70753. return face->typeFace;
  70754. }
  70755. juce_UseDebuggingNewOperator
  70756. private:
  70757. struct CachedFace
  70758. {
  70759. CachedFace() throw()
  70760. : lastUsageCount (0), flags (-1)
  70761. {
  70762. }
  70763. String typefaceName;
  70764. int lastUsageCount;
  70765. int flags;
  70766. Typeface::Ptr typeFace;
  70767. };
  70768. int counter;
  70769. OwnedArray <CachedFace> faces;
  70770. TypefaceCache (const TypefaceCache&);
  70771. TypefaceCache& operator= (const TypefaceCache&);
  70772. };
  70773. juce_ImplementSingleton_SingleThreaded (TypefaceCache)
  70774. Typeface* Font::getTypeface() const throw()
  70775. {
  70776. if (font->typeface == 0)
  70777. font->typeface = TypefaceCache::getInstance()->findTypefaceFor (*this);
  70778. return font->typeface;
  70779. }
  70780. END_JUCE_NAMESPACE
  70781. /*** End of inlined file: juce_Font.cpp ***/
  70782. /*** Start of inlined file: juce_GlyphArrangement.cpp ***/
  70783. BEGIN_JUCE_NAMESPACE
  70784. PositionedGlyph::PositionedGlyph (const float x_, const float y_, const float w_, const Font& font_,
  70785. const juce_wchar character_, const int glyph_)
  70786. : x (x_),
  70787. y (y_),
  70788. w (w_),
  70789. font (font_),
  70790. character (character_),
  70791. glyph (glyph_)
  70792. {
  70793. }
  70794. PositionedGlyph::PositionedGlyph (const PositionedGlyph& other)
  70795. : x (other.x),
  70796. y (other.y),
  70797. w (other.w),
  70798. font (other.font),
  70799. character (other.character),
  70800. glyph (other.glyph)
  70801. {
  70802. }
  70803. void PositionedGlyph::draw (const Graphics& g) const
  70804. {
  70805. if (! isWhitespace())
  70806. {
  70807. g.getInternalContext()->setFont (font);
  70808. g.getInternalContext()->drawGlyph (glyph, AffineTransform::translation (x, y));
  70809. }
  70810. }
  70811. void PositionedGlyph::draw (const Graphics& g,
  70812. const AffineTransform& transform) const
  70813. {
  70814. if (! isWhitespace())
  70815. {
  70816. g.getInternalContext()->setFont (font);
  70817. g.getInternalContext()->drawGlyph (glyph, AffineTransform::translation (x, y)
  70818. .followedBy (transform));
  70819. }
  70820. }
  70821. void PositionedGlyph::createPath (Path& path) const
  70822. {
  70823. if (! isWhitespace())
  70824. {
  70825. Typeface* const t = font.getTypeface();
  70826. if (t != 0)
  70827. {
  70828. Path p;
  70829. t->getOutlineForGlyph (glyph, p);
  70830. path.addPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight())
  70831. .translated (x, y));
  70832. }
  70833. }
  70834. }
  70835. bool PositionedGlyph::hitTest (float px, float py) const
  70836. {
  70837. if (getBounds().contains (px, py) && ! isWhitespace())
  70838. {
  70839. Typeface* const t = font.getTypeface();
  70840. if (t != 0)
  70841. {
  70842. Path p;
  70843. t->getOutlineForGlyph (glyph, p);
  70844. AffineTransform::translation (-x, -y)
  70845. .scaled (1.0f / (font.getHeight() * font.getHorizontalScale()), 1.0f / font.getHeight())
  70846. .transformPoint (px, py);
  70847. return p.contains (px, py);
  70848. }
  70849. }
  70850. return false;
  70851. }
  70852. void PositionedGlyph::moveBy (const float deltaX,
  70853. const float deltaY)
  70854. {
  70855. x += deltaX;
  70856. y += deltaY;
  70857. }
  70858. GlyphArrangement::GlyphArrangement()
  70859. {
  70860. glyphs.ensureStorageAllocated (128);
  70861. }
  70862. GlyphArrangement::GlyphArrangement (const GlyphArrangement& other)
  70863. {
  70864. addGlyphArrangement (other);
  70865. }
  70866. GlyphArrangement& GlyphArrangement::operator= (const GlyphArrangement& other)
  70867. {
  70868. if (this != &other)
  70869. {
  70870. clear();
  70871. addGlyphArrangement (other);
  70872. }
  70873. return *this;
  70874. }
  70875. GlyphArrangement::~GlyphArrangement()
  70876. {
  70877. }
  70878. void GlyphArrangement::clear()
  70879. {
  70880. glyphs.clear();
  70881. }
  70882. PositionedGlyph& GlyphArrangement::getGlyph (const int index) const
  70883. {
  70884. jassert (((unsigned int) index) < (unsigned int) glyphs.size());
  70885. return *glyphs [index];
  70886. }
  70887. void GlyphArrangement::addGlyphArrangement (const GlyphArrangement& other)
  70888. {
  70889. glyphs.ensureStorageAllocated (glyphs.size() + other.glyphs.size());
  70890. glyphs.addCopiesOf (other.glyphs);
  70891. }
  70892. void GlyphArrangement::removeRangeOfGlyphs (int startIndex, const int num)
  70893. {
  70894. glyphs.removeRange (startIndex, num < 0 ? glyphs.size() : num);
  70895. }
  70896. void GlyphArrangement::addLineOfText (const Font& font,
  70897. const String& text,
  70898. const float xOffset,
  70899. const float yOffset)
  70900. {
  70901. addCurtailedLineOfText (font, text,
  70902. xOffset, yOffset,
  70903. 1.0e10f, false);
  70904. }
  70905. void GlyphArrangement::addCurtailedLineOfText (const Font& font,
  70906. const String& text,
  70907. float xOffset,
  70908. const float yOffset,
  70909. const float maxWidthPixels,
  70910. const bool useEllipsis)
  70911. {
  70912. if (text.isNotEmpty())
  70913. {
  70914. Array <int> newGlyphs;
  70915. Array <float> xOffsets;
  70916. font.getGlyphPositions (text, newGlyphs, xOffsets);
  70917. const int textLen = newGlyphs.size();
  70918. const juce_wchar* const unicodeText = text;
  70919. for (int i = 0; i < textLen; ++i)
  70920. {
  70921. const float thisX = xOffsets.getUnchecked (i);
  70922. const float nextX = xOffsets.getUnchecked (i + 1);
  70923. if (nextX > maxWidthPixels + 1.0f)
  70924. {
  70925. // curtail the string if it's too wide..
  70926. if (useEllipsis && textLen > 3 && glyphs.size() >= 3)
  70927. insertEllipsis (font, xOffset + maxWidthPixels, 0, glyphs.size());
  70928. break;
  70929. }
  70930. else
  70931. {
  70932. glyphs.add (new PositionedGlyph (xOffset + thisX, yOffset, nextX - thisX,
  70933. font, unicodeText[i], newGlyphs.getUnchecked(i)));
  70934. }
  70935. }
  70936. }
  70937. }
  70938. int GlyphArrangement::insertEllipsis (const Font& font, const float maxXPos,
  70939. const int startIndex, int endIndex)
  70940. {
  70941. int numDeleted = 0;
  70942. if (glyphs.size() > 0)
  70943. {
  70944. Array<int> dotGlyphs;
  70945. Array<float> dotXs;
  70946. font.getGlyphPositions ("..", dotGlyphs, dotXs);
  70947. const float dx = dotXs[1];
  70948. float xOffset = 0.0f, yOffset = 0.0f;
  70949. while (endIndex > startIndex)
  70950. {
  70951. const PositionedGlyph* pg = glyphs.getUnchecked (--endIndex);
  70952. xOffset = pg->x;
  70953. yOffset = pg->y;
  70954. glyphs.remove (endIndex);
  70955. ++numDeleted;
  70956. if (xOffset + dx * 3 <= maxXPos)
  70957. break;
  70958. }
  70959. for (int i = 3; --i >= 0;)
  70960. {
  70961. glyphs.insert (endIndex++, new PositionedGlyph (xOffset, yOffset, dx,
  70962. font, '.', dotGlyphs.getFirst()));
  70963. --numDeleted;
  70964. xOffset += dx;
  70965. if (xOffset > maxXPos)
  70966. break;
  70967. }
  70968. }
  70969. return numDeleted;
  70970. }
  70971. void GlyphArrangement::addJustifiedText (const Font& font,
  70972. const String& text,
  70973. float x, float y,
  70974. const float maxLineWidth,
  70975. const Justification& horizontalLayout)
  70976. {
  70977. int lineStartIndex = glyphs.size();
  70978. addLineOfText (font, text, x, y);
  70979. const float originalY = y;
  70980. while (lineStartIndex < glyphs.size())
  70981. {
  70982. int i = lineStartIndex;
  70983. if (glyphs.getUnchecked(i)->getCharacter() != '\n'
  70984. && glyphs.getUnchecked(i)->getCharacter() != '\r')
  70985. ++i;
  70986. const float lineMaxX = glyphs.getUnchecked (lineStartIndex)->getLeft() + maxLineWidth;
  70987. int lastWordBreakIndex = -1;
  70988. while (i < glyphs.size())
  70989. {
  70990. const PositionedGlyph* pg = glyphs.getUnchecked (i);
  70991. const juce_wchar c = pg->getCharacter();
  70992. if (c == '\r' || c == '\n')
  70993. {
  70994. ++i;
  70995. if (c == '\r' && i < glyphs.size()
  70996. && glyphs.getUnchecked(i)->getCharacter() == '\n')
  70997. ++i;
  70998. break;
  70999. }
  71000. else if (pg->isWhitespace())
  71001. {
  71002. lastWordBreakIndex = i + 1;
  71003. }
  71004. else if (pg->getRight() - 0.0001f >= lineMaxX)
  71005. {
  71006. if (lastWordBreakIndex >= 0)
  71007. i = lastWordBreakIndex;
  71008. break;
  71009. }
  71010. ++i;
  71011. }
  71012. const float currentLineStartX = glyphs.getUnchecked (lineStartIndex)->getLeft();
  71013. float currentLineEndX = currentLineStartX;
  71014. for (int j = i; --j >= lineStartIndex;)
  71015. {
  71016. if (! glyphs.getUnchecked (j)->isWhitespace())
  71017. {
  71018. currentLineEndX = glyphs.getUnchecked (j)->getRight();
  71019. break;
  71020. }
  71021. }
  71022. float deltaX = 0.0f;
  71023. if (horizontalLayout.testFlags (Justification::horizontallyJustified))
  71024. spreadOutLine (lineStartIndex, i - lineStartIndex, maxLineWidth);
  71025. else if (horizontalLayout.testFlags (Justification::horizontallyCentred))
  71026. deltaX = (maxLineWidth - (currentLineEndX - currentLineStartX)) * 0.5f;
  71027. else if (horizontalLayout.testFlags (Justification::right))
  71028. deltaX = maxLineWidth - (currentLineEndX - currentLineStartX);
  71029. moveRangeOfGlyphs (lineStartIndex, i - lineStartIndex,
  71030. x + deltaX - currentLineStartX, y - originalY);
  71031. lineStartIndex = i;
  71032. y += font.getHeight();
  71033. }
  71034. }
  71035. void GlyphArrangement::addFittedText (const Font& f,
  71036. const String& text,
  71037. const float x, const float y,
  71038. const float width, const float height,
  71039. const Justification& layout,
  71040. int maximumLines,
  71041. const float minimumHorizontalScale)
  71042. {
  71043. // doesn't make much sense if this is outside a sensible range of 0.5 to 1.0
  71044. jassert (minimumHorizontalScale > 0 && minimumHorizontalScale <= 1.0f);
  71045. if (text.containsAnyOf ("\r\n"))
  71046. {
  71047. GlyphArrangement ga;
  71048. ga.addJustifiedText (f, text, x, y, width, layout);
  71049. const Rectangle<float> bb (ga.getBoundingBox (0, -1, false));
  71050. float dy = y - bb.getY();
  71051. if (layout.testFlags (Justification::verticallyCentred))
  71052. dy += (height - bb.getHeight()) * 0.5f;
  71053. else if (layout.testFlags (Justification::bottom))
  71054. dy += height - bb.getHeight();
  71055. ga.moveRangeOfGlyphs (0, -1, 0.0f, dy);
  71056. glyphs.ensureStorageAllocated (glyphs.size() + ga.glyphs.size());
  71057. for (int i = 0; i < ga.glyphs.size(); ++i)
  71058. glyphs.add (ga.glyphs.getUnchecked (i));
  71059. ga.glyphs.clear (false);
  71060. return;
  71061. }
  71062. int startIndex = glyphs.size();
  71063. addLineOfText (f, text.trim(), x, y);
  71064. if (glyphs.size() > startIndex)
  71065. {
  71066. float lineWidth = glyphs.getUnchecked (glyphs.size() - 1)->getRight()
  71067. - glyphs.getUnchecked (startIndex)->getLeft();
  71068. if (lineWidth <= 0)
  71069. return;
  71070. if (lineWidth * minimumHorizontalScale < width)
  71071. {
  71072. if (lineWidth > width)
  71073. stretchRangeOfGlyphs (startIndex, glyphs.size() - startIndex,
  71074. width / lineWidth);
  71075. justifyGlyphs (startIndex, glyphs.size() - startIndex,
  71076. x, y, width, height, layout);
  71077. }
  71078. else if (maximumLines <= 1)
  71079. {
  71080. fitLineIntoSpace (startIndex, glyphs.size() - startIndex,
  71081. x, y, width, height, f, layout, minimumHorizontalScale);
  71082. }
  71083. else
  71084. {
  71085. Font font (f);
  71086. String txt (text.trim());
  71087. const int length = txt.length();
  71088. const int originalStartIndex = startIndex;
  71089. int numLines = 1;
  71090. if (length <= 12 && ! txt.containsAnyOf (" -\t\r\n"))
  71091. maximumLines = 1;
  71092. maximumLines = jmin (maximumLines, length);
  71093. while (numLines < maximumLines)
  71094. {
  71095. ++numLines;
  71096. const float newFontHeight = height / (float) numLines;
  71097. if (newFontHeight < font.getHeight())
  71098. {
  71099. font.setHeight (jmax (8.0f, newFontHeight));
  71100. removeRangeOfGlyphs (startIndex, -1);
  71101. addLineOfText (font, txt, x, y);
  71102. lineWidth = glyphs.getUnchecked (glyphs.size() - 1)->getRight()
  71103. - glyphs.getUnchecked (startIndex)->getLeft();
  71104. }
  71105. if (numLines > lineWidth / width || newFontHeight < 8.0f)
  71106. break;
  71107. }
  71108. if (numLines < 1)
  71109. numLines = 1;
  71110. float lineY = y;
  71111. float widthPerLine = lineWidth / numLines;
  71112. int lastLineStartIndex = 0;
  71113. for (int line = 0; line < numLines; ++line)
  71114. {
  71115. int i = startIndex;
  71116. lastLineStartIndex = i;
  71117. float lineStartX = glyphs.getUnchecked (startIndex)->getLeft();
  71118. if (line == numLines - 1)
  71119. {
  71120. widthPerLine = width;
  71121. i = glyphs.size();
  71122. }
  71123. else
  71124. {
  71125. while (i < glyphs.size())
  71126. {
  71127. lineWidth = (glyphs.getUnchecked (i)->getRight() - lineStartX);
  71128. if (lineWidth > widthPerLine)
  71129. {
  71130. // got to a point where the line's too long, so skip forward to find a
  71131. // good place to break it..
  71132. const int searchStartIndex = i;
  71133. while (i < glyphs.size())
  71134. {
  71135. if ((glyphs.getUnchecked (i)->getRight() - lineStartX) * minimumHorizontalScale < width)
  71136. {
  71137. if (glyphs.getUnchecked (i)->isWhitespace()
  71138. || glyphs.getUnchecked (i)->getCharacter() == '-')
  71139. {
  71140. ++i;
  71141. break;
  71142. }
  71143. }
  71144. else
  71145. {
  71146. // can't find a suitable break, so try looking backwards..
  71147. i = searchStartIndex;
  71148. for (int back = 1; back < jmin (5, i - startIndex - 1); ++back)
  71149. {
  71150. if (glyphs.getUnchecked (i - back)->isWhitespace()
  71151. || glyphs.getUnchecked (i - back)->getCharacter() == '-')
  71152. {
  71153. i -= back - 1;
  71154. break;
  71155. }
  71156. }
  71157. break;
  71158. }
  71159. ++i;
  71160. }
  71161. break;
  71162. }
  71163. ++i;
  71164. }
  71165. int wsStart = i;
  71166. while (wsStart > 0 && glyphs.getUnchecked (wsStart - 1)->isWhitespace())
  71167. --wsStart;
  71168. int wsEnd = i;
  71169. while (wsEnd < glyphs.size() && glyphs.getUnchecked (wsEnd)->isWhitespace())
  71170. ++wsEnd;
  71171. removeRangeOfGlyphs (wsStart, wsEnd - wsStart);
  71172. i = jmax (wsStart, startIndex + 1);
  71173. }
  71174. i -= fitLineIntoSpace (startIndex, i - startIndex,
  71175. x, lineY, width, font.getHeight(), font,
  71176. layout.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  71177. minimumHorizontalScale);
  71178. startIndex = i;
  71179. lineY += font.getHeight();
  71180. if (startIndex >= glyphs.size())
  71181. break;
  71182. }
  71183. justifyGlyphs (originalStartIndex, glyphs.size() - originalStartIndex,
  71184. x, y, width, height, layout.getFlags() & ~Justification::horizontallyJustified);
  71185. }
  71186. }
  71187. }
  71188. void GlyphArrangement::moveRangeOfGlyphs (int startIndex, int num,
  71189. const float dx, const float dy)
  71190. {
  71191. jassert (startIndex >= 0);
  71192. if (dx != 0.0f || dy != 0.0f)
  71193. {
  71194. if (num < 0 || startIndex + num > glyphs.size())
  71195. num = glyphs.size() - startIndex;
  71196. while (--num >= 0)
  71197. glyphs.getUnchecked (startIndex++)->moveBy (dx, dy);
  71198. }
  71199. }
  71200. int GlyphArrangement::fitLineIntoSpace (int start, int numGlyphs, float x, float y, float w, float h, const Font& font,
  71201. const Justification& justification, float minimumHorizontalScale)
  71202. {
  71203. int numDeleted = 0;
  71204. const float lineStartX = glyphs.getUnchecked (start)->getLeft();
  71205. float lineWidth = glyphs.getUnchecked (start + numGlyphs - 1)->getRight() - lineStartX;
  71206. if (lineWidth > w)
  71207. {
  71208. if (minimumHorizontalScale < 1.0f)
  71209. {
  71210. stretchRangeOfGlyphs (start, numGlyphs, jmax (minimumHorizontalScale, w / lineWidth));
  71211. lineWidth = glyphs.getUnchecked (start + numGlyphs - 1)->getRight() - lineStartX - 0.5f;
  71212. }
  71213. if (lineWidth > w)
  71214. {
  71215. numDeleted = insertEllipsis (font, lineStartX + w, start, start + numGlyphs);
  71216. numGlyphs -= numDeleted;
  71217. }
  71218. }
  71219. justifyGlyphs (start, numGlyphs, x, y, w, h, justification);
  71220. return numDeleted;
  71221. }
  71222. void GlyphArrangement::stretchRangeOfGlyphs (int startIndex, int num,
  71223. const float horizontalScaleFactor)
  71224. {
  71225. jassert (startIndex >= 0);
  71226. if (num < 0 || startIndex + num > glyphs.size())
  71227. num = glyphs.size() - startIndex;
  71228. if (num > 0)
  71229. {
  71230. const float xAnchor = glyphs.getUnchecked (startIndex)->getLeft();
  71231. while (--num >= 0)
  71232. {
  71233. PositionedGlyph* const pg = glyphs.getUnchecked (startIndex++);
  71234. pg->x = xAnchor + (pg->x - xAnchor) * horizontalScaleFactor;
  71235. pg->font.setHorizontalScale (pg->font.getHorizontalScale() * horizontalScaleFactor);
  71236. pg->w *= horizontalScaleFactor;
  71237. }
  71238. }
  71239. }
  71240. const Rectangle<float> GlyphArrangement::getBoundingBox (int startIndex, int num, const bool includeWhitespace) const
  71241. {
  71242. jassert (startIndex >= 0);
  71243. if (num < 0 || startIndex + num > glyphs.size())
  71244. num = glyphs.size() - startIndex;
  71245. Rectangle<float> result;
  71246. while (--num >= 0)
  71247. {
  71248. const PositionedGlyph* const pg = glyphs.getUnchecked (startIndex++);
  71249. if (includeWhitespace || ! pg->isWhitespace())
  71250. result = result.getUnion (pg->getBounds());
  71251. }
  71252. return result;
  71253. }
  71254. void GlyphArrangement::justifyGlyphs (const int startIndex, const int num,
  71255. const float x, const float y, const float width, const float height,
  71256. const Justification& justification)
  71257. {
  71258. jassert (num >= 0 && startIndex >= 0);
  71259. if (glyphs.size() > 0 && num > 0)
  71260. {
  71261. const Rectangle<float> bb (getBoundingBox (startIndex, num, ! justification.testFlags (Justification::horizontallyJustified
  71262. | Justification::horizontallyCentred)));
  71263. float deltaX = 0.0f;
  71264. if (justification.testFlags (Justification::horizontallyJustified))
  71265. deltaX = x - bb.getX();
  71266. else if (justification.testFlags (Justification::horizontallyCentred))
  71267. deltaX = x + (width - bb.getWidth()) * 0.5f - bb.getX();
  71268. else if (justification.testFlags (Justification::right))
  71269. deltaX = (x + width) - bb.getRight();
  71270. else
  71271. deltaX = x - bb.getX();
  71272. float deltaY = 0.0f;
  71273. if (justification.testFlags (Justification::top))
  71274. deltaY = y - bb.getY();
  71275. else if (justification.testFlags (Justification::bottom))
  71276. deltaY = (y + height) - bb.getBottom();
  71277. else
  71278. deltaY = y + (height - bb.getHeight()) * 0.5f - bb.getY();
  71279. moveRangeOfGlyphs (startIndex, num, deltaX, deltaY);
  71280. if (justification.testFlags (Justification::horizontallyJustified))
  71281. {
  71282. int lineStart = 0;
  71283. float baseY = glyphs.getUnchecked (startIndex)->getBaselineY();
  71284. int i;
  71285. for (i = 0; i < num; ++i)
  71286. {
  71287. const float glyphY = glyphs.getUnchecked (startIndex + i)->getBaselineY();
  71288. if (glyphY != baseY)
  71289. {
  71290. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  71291. lineStart = i;
  71292. baseY = glyphY;
  71293. }
  71294. }
  71295. if (i > lineStart)
  71296. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  71297. }
  71298. }
  71299. }
  71300. void GlyphArrangement::spreadOutLine (const int start, const int num, const float targetWidth)
  71301. {
  71302. if (start + num < glyphs.size()
  71303. && glyphs.getUnchecked (start + num - 1)->getCharacter() != '\r'
  71304. && glyphs.getUnchecked (start + num - 1)->getCharacter() != '\n')
  71305. {
  71306. int numSpaces = 0;
  71307. int spacesAtEnd = 0;
  71308. for (int i = 0; i < num; ++i)
  71309. {
  71310. if (glyphs.getUnchecked (start + i)->isWhitespace())
  71311. {
  71312. ++spacesAtEnd;
  71313. ++numSpaces;
  71314. }
  71315. else
  71316. {
  71317. spacesAtEnd = 0;
  71318. }
  71319. }
  71320. numSpaces -= spacesAtEnd;
  71321. if (numSpaces > 0)
  71322. {
  71323. const float startX = glyphs.getUnchecked (start)->getLeft();
  71324. const float endX = glyphs.getUnchecked (start + num - 1 - spacesAtEnd)->getRight();
  71325. const float extraPaddingBetweenWords
  71326. = (targetWidth - (endX - startX)) / (float) numSpaces;
  71327. float deltaX = 0.0f;
  71328. for (int i = 0; i < num; ++i)
  71329. {
  71330. glyphs.getUnchecked (start + i)->moveBy (deltaX, 0.0f);
  71331. if (glyphs.getUnchecked (start + i)->isWhitespace())
  71332. deltaX += extraPaddingBetweenWords;
  71333. }
  71334. }
  71335. }
  71336. }
  71337. void GlyphArrangement::draw (const Graphics& g) const
  71338. {
  71339. for (int i = 0; i < glyphs.size(); ++i)
  71340. {
  71341. const PositionedGlyph* const pg = glyphs.getUnchecked(i);
  71342. if (pg->font.isUnderlined())
  71343. {
  71344. const float lineThickness = (pg->font.getDescent()) * 0.3f;
  71345. float nextX = pg->x + pg->w;
  71346. if (i < glyphs.size() - 1 && glyphs.getUnchecked (i + 1)->y == pg->y)
  71347. nextX = glyphs.getUnchecked (i + 1)->x;
  71348. g.fillRect (pg->x, pg->y + lineThickness * 2.0f,
  71349. nextX - pg->x, lineThickness);
  71350. }
  71351. pg->draw (g);
  71352. }
  71353. }
  71354. void GlyphArrangement::draw (const Graphics& g, const AffineTransform& transform) const
  71355. {
  71356. for (int i = 0; i < glyphs.size(); ++i)
  71357. {
  71358. const PositionedGlyph* const pg = glyphs.getUnchecked(i);
  71359. if (pg->font.isUnderlined())
  71360. {
  71361. const float lineThickness = (pg->font.getDescent()) * 0.3f;
  71362. float nextX = pg->x + pg->w;
  71363. if (i < glyphs.size() - 1 && glyphs.getUnchecked (i + 1)->y == pg->y)
  71364. nextX = glyphs.getUnchecked (i + 1)->x;
  71365. Path p;
  71366. p.addLineSegment (Line<float> (pg->x, pg->y + lineThickness * 2.0f,
  71367. nextX, pg->y + lineThickness * 2.0f),
  71368. lineThickness);
  71369. g.fillPath (p, transform);
  71370. }
  71371. pg->draw (g, transform);
  71372. }
  71373. }
  71374. void GlyphArrangement::createPath (Path& path) const
  71375. {
  71376. for (int i = 0; i < glyphs.size(); ++i)
  71377. glyphs.getUnchecked (i)->createPath (path);
  71378. }
  71379. int GlyphArrangement::findGlyphIndexAt (float x, float y) const
  71380. {
  71381. for (int i = 0; i < glyphs.size(); ++i)
  71382. if (glyphs.getUnchecked (i)->hitTest (x, y))
  71383. return i;
  71384. return -1;
  71385. }
  71386. END_JUCE_NAMESPACE
  71387. /*** End of inlined file: juce_GlyphArrangement.cpp ***/
  71388. /*** Start of inlined file: juce_TextLayout.cpp ***/
  71389. BEGIN_JUCE_NAMESPACE
  71390. class TextLayout::Token
  71391. {
  71392. public:
  71393. String text;
  71394. Font font;
  71395. int x, y, w, h;
  71396. int line, lineHeight;
  71397. bool isWhitespace, isNewLine;
  71398. Token (const String& t,
  71399. const Font& f,
  71400. const bool isWhitespace_)
  71401. : text (t),
  71402. font (f),
  71403. x(0),
  71404. y(0),
  71405. isWhitespace (isWhitespace_)
  71406. {
  71407. w = font.getStringWidth (t);
  71408. h = roundToInt (f.getHeight());
  71409. isNewLine = t.containsChar ('\n') || t.containsChar ('\r');
  71410. }
  71411. Token (const Token& other)
  71412. : text (other.text),
  71413. font (other.font),
  71414. x (other.x),
  71415. y (other.y),
  71416. w (other.w),
  71417. h (other.h),
  71418. line (other.line),
  71419. lineHeight (other.lineHeight),
  71420. isWhitespace (other.isWhitespace),
  71421. isNewLine (other.isNewLine)
  71422. {
  71423. }
  71424. ~Token()
  71425. {
  71426. }
  71427. void draw (Graphics& g,
  71428. const int xOffset,
  71429. const int yOffset)
  71430. {
  71431. if (! isWhitespace)
  71432. {
  71433. g.setFont (font);
  71434. g.drawSingleLineText (text.trimEnd(),
  71435. xOffset + x,
  71436. yOffset + y + (lineHeight - h)
  71437. + roundToInt (font.getAscent()));
  71438. }
  71439. }
  71440. juce_UseDebuggingNewOperator
  71441. };
  71442. TextLayout::TextLayout()
  71443. : totalLines (0)
  71444. {
  71445. tokens.ensureStorageAllocated (64);
  71446. }
  71447. TextLayout::TextLayout (const String& text, const Font& font)
  71448. : totalLines (0)
  71449. {
  71450. tokens.ensureStorageAllocated (64);
  71451. appendText (text, font);
  71452. }
  71453. TextLayout::TextLayout (const TextLayout& other)
  71454. : totalLines (0)
  71455. {
  71456. *this = other;
  71457. }
  71458. TextLayout& TextLayout::operator= (const TextLayout& other)
  71459. {
  71460. if (this != &other)
  71461. {
  71462. clear();
  71463. totalLines = other.totalLines;
  71464. tokens.addCopiesOf (other.tokens);
  71465. }
  71466. return *this;
  71467. }
  71468. TextLayout::~TextLayout()
  71469. {
  71470. clear();
  71471. }
  71472. void TextLayout::clear()
  71473. {
  71474. tokens.clear();
  71475. totalLines = 0;
  71476. }
  71477. void TextLayout::appendText (const String& text, const Font& font)
  71478. {
  71479. const juce_wchar* t = text;
  71480. String currentString;
  71481. int lastCharType = 0;
  71482. for (;;)
  71483. {
  71484. const juce_wchar c = *t++;
  71485. if (c == 0)
  71486. break;
  71487. int charType;
  71488. if (c == '\r' || c == '\n')
  71489. {
  71490. charType = 0;
  71491. }
  71492. else if (CharacterFunctions::isWhitespace (c))
  71493. {
  71494. charType = 2;
  71495. }
  71496. else
  71497. {
  71498. charType = 1;
  71499. }
  71500. if (charType == 0 || charType != lastCharType)
  71501. {
  71502. if (currentString.isNotEmpty())
  71503. {
  71504. tokens.add (new Token (currentString, font,
  71505. lastCharType == 2 || lastCharType == 0));
  71506. }
  71507. currentString = String::charToString (c);
  71508. if (c == '\r' && *t == '\n')
  71509. currentString += *t++;
  71510. }
  71511. else
  71512. {
  71513. currentString += c;
  71514. }
  71515. lastCharType = charType;
  71516. }
  71517. if (currentString.isNotEmpty())
  71518. tokens.add (new Token (currentString, font, lastCharType == 2));
  71519. }
  71520. void TextLayout::setText (const String& text, const Font& font)
  71521. {
  71522. clear();
  71523. appendText (text, font);
  71524. }
  71525. void TextLayout::layout (int maxWidth,
  71526. const Justification& justification,
  71527. const bool attemptToBalanceLineLengths)
  71528. {
  71529. if (attemptToBalanceLineLengths)
  71530. {
  71531. const int originalW = maxWidth;
  71532. int bestWidth = maxWidth;
  71533. float bestLineProportion = 0.0f;
  71534. while (maxWidth > originalW / 2)
  71535. {
  71536. layout (maxWidth, justification, false);
  71537. if (getNumLines() <= 1)
  71538. return;
  71539. const int lastLineW = getLineWidth (getNumLines() - 1);
  71540. const int lastButOneLineW = getLineWidth (getNumLines() - 2);
  71541. const float prop = lastLineW / (float) lastButOneLineW;
  71542. if (prop > 0.9f)
  71543. return;
  71544. if (prop > bestLineProportion)
  71545. {
  71546. bestLineProportion = prop;
  71547. bestWidth = maxWidth;
  71548. }
  71549. maxWidth -= 10;
  71550. }
  71551. layout (bestWidth, justification, false);
  71552. }
  71553. else
  71554. {
  71555. int x = 0;
  71556. int y = 0;
  71557. int h = 0;
  71558. totalLines = 0;
  71559. int i;
  71560. for (i = 0; i < tokens.size(); ++i)
  71561. {
  71562. Token* const t = tokens.getUnchecked(i);
  71563. t->x = x;
  71564. t->y = y;
  71565. t->line = totalLines;
  71566. x += t->w;
  71567. h = jmax (h, t->h);
  71568. const Token* nextTok = tokens [i + 1];
  71569. if (nextTok == 0)
  71570. break;
  71571. if (t->isNewLine || ((! nextTok->isWhitespace) && x + nextTok->w > maxWidth))
  71572. {
  71573. // finished a line, so go back and update the heights of the things on it
  71574. for (int j = i; j >= 0; --j)
  71575. {
  71576. Token* const tok = tokens.getUnchecked(j);
  71577. if (tok->line == totalLines)
  71578. tok->lineHeight = h;
  71579. else
  71580. break;
  71581. }
  71582. x = 0;
  71583. y += h;
  71584. h = 0;
  71585. ++totalLines;
  71586. }
  71587. }
  71588. // finished a line, so go back and update the heights of the things on it
  71589. for (int j = jmin (i, tokens.size() - 1); j >= 0; --j)
  71590. {
  71591. Token* const t = tokens.getUnchecked(j);
  71592. if (t->line == totalLines)
  71593. t->lineHeight = h;
  71594. else
  71595. break;
  71596. }
  71597. ++totalLines;
  71598. if (! justification.testFlags (Justification::left))
  71599. {
  71600. int totalW = getWidth();
  71601. for (i = totalLines; --i >= 0;)
  71602. {
  71603. const int lineW = getLineWidth (i);
  71604. int dx = 0;
  71605. if (justification.testFlags (Justification::horizontallyCentred))
  71606. dx = (totalW - lineW) / 2;
  71607. else if (justification.testFlags (Justification::right))
  71608. dx = totalW - lineW;
  71609. for (int j = tokens.size(); --j >= 0;)
  71610. {
  71611. Token* const t = tokens.getUnchecked(j);
  71612. if (t->line == i)
  71613. t->x += dx;
  71614. }
  71615. }
  71616. }
  71617. }
  71618. }
  71619. int TextLayout::getLineWidth (const int lineNumber) const
  71620. {
  71621. int maxW = 0;
  71622. for (int i = tokens.size(); --i >= 0;)
  71623. {
  71624. const Token* const t = tokens.getUnchecked(i);
  71625. if (t->line == lineNumber && ! t->isWhitespace)
  71626. maxW = jmax (maxW, t->x + t->w);
  71627. }
  71628. return maxW;
  71629. }
  71630. int TextLayout::getWidth() const
  71631. {
  71632. int maxW = 0;
  71633. for (int i = tokens.size(); --i >= 0;)
  71634. {
  71635. const Token* const t = tokens.getUnchecked(i);
  71636. if (! t->isWhitespace)
  71637. maxW = jmax (maxW, t->x + t->w);
  71638. }
  71639. return maxW;
  71640. }
  71641. int TextLayout::getHeight() const
  71642. {
  71643. int maxH = 0;
  71644. for (int i = tokens.size(); --i >= 0;)
  71645. {
  71646. const Token* const t = tokens.getUnchecked(i);
  71647. if (! t->isWhitespace)
  71648. maxH = jmax (maxH, t->y + t->h);
  71649. }
  71650. return maxH;
  71651. }
  71652. void TextLayout::draw (Graphics& g,
  71653. const int xOffset,
  71654. const int yOffset) const
  71655. {
  71656. for (int i = tokens.size(); --i >= 0;)
  71657. tokens.getUnchecked(i)->draw (g, xOffset, yOffset);
  71658. }
  71659. void TextLayout::drawWithin (Graphics& g,
  71660. int x, int y, int w, int h,
  71661. const Justification& justification) const
  71662. {
  71663. justification.applyToRectangle (x, y, getWidth(), getHeight(),
  71664. x, y, w, h);
  71665. draw (g, x, y);
  71666. }
  71667. END_JUCE_NAMESPACE
  71668. /*** End of inlined file: juce_TextLayout.cpp ***/
  71669. /*** Start of inlined file: juce_Typeface.cpp ***/
  71670. BEGIN_JUCE_NAMESPACE
  71671. Typeface::Typeface (const String& name_) throw()
  71672. : name (name_)
  71673. {
  71674. }
  71675. Typeface::~Typeface()
  71676. {
  71677. }
  71678. class CustomTypeface::GlyphInfo
  71679. {
  71680. public:
  71681. GlyphInfo (const juce_wchar character_, const Path& path_, const float width_) throw()
  71682. : character (character_), path (path_), width (width_)
  71683. {
  71684. }
  71685. ~GlyphInfo() throw()
  71686. {
  71687. }
  71688. struct KerningPair
  71689. {
  71690. juce_wchar character2;
  71691. float kerningAmount;
  71692. };
  71693. void addKerningPair (const juce_wchar subsequentCharacter,
  71694. const float extraKerningAmount) throw()
  71695. {
  71696. KerningPair kp;
  71697. kp.character2 = subsequentCharacter;
  71698. kp.kerningAmount = extraKerningAmount;
  71699. kerningPairs.add (kp);
  71700. }
  71701. float getHorizontalSpacing (const juce_wchar subsequentCharacter) const throw()
  71702. {
  71703. if (subsequentCharacter != 0)
  71704. {
  71705. for (int i = kerningPairs.size(); --i >= 0;)
  71706. if (kerningPairs.getReference(i).character2 == subsequentCharacter)
  71707. return width + kerningPairs.getReference(i).kerningAmount;
  71708. }
  71709. return width;
  71710. }
  71711. const juce_wchar character;
  71712. const Path path;
  71713. float width;
  71714. Array <KerningPair> kerningPairs;
  71715. juce_UseDebuggingNewOperator
  71716. private:
  71717. GlyphInfo (const GlyphInfo&);
  71718. GlyphInfo& operator= (const GlyphInfo&);
  71719. };
  71720. CustomTypeface::CustomTypeface()
  71721. : Typeface (String::empty)
  71722. {
  71723. clear();
  71724. }
  71725. CustomTypeface::CustomTypeface (InputStream& serialisedTypefaceStream)
  71726. : Typeface (String::empty)
  71727. {
  71728. clear();
  71729. GZIPDecompressorInputStream gzin (&serialisedTypefaceStream, false);
  71730. BufferedInputStream in (&gzin, 32768, false);
  71731. name = in.readString();
  71732. isBold = in.readBool();
  71733. isItalic = in.readBool();
  71734. ascent = in.readFloat();
  71735. defaultCharacter = (juce_wchar) in.readShort();
  71736. int i, numChars = in.readInt();
  71737. for (i = 0; i < numChars; ++i)
  71738. {
  71739. const juce_wchar c = (juce_wchar) in.readShort();
  71740. const float width = in.readFloat();
  71741. Path p;
  71742. p.loadPathFromStream (in);
  71743. addGlyph (c, p, width);
  71744. }
  71745. const int numKerningPairs = in.readInt();
  71746. for (i = 0; i < numKerningPairs; ++i)
  71747. {
  71748. const juce_wchar char1 = (juce_wchar) in.readShort();
  71749. const juce_wchar char2 = (juce_wchar) in.readShort();
  71750. addKerningPair (char1, char2, in.readFloat());
  71751. }
  71752. }
  71753. CustomTypeface::~CustomTypeface()
  71754. {
  71755. }
  71756. void CustomTypeface::clear()
  71757. {
  71758. defaultCharacter = 0;
  71759. ascent = 1.0f;
  71760. isBold = isItalic = false;
  71761. zeromem (lookupTable, sizeof (lookupTable));
  71762. glyphs.clear();
  71763. }
  71764. void CustomTypeface::setCharacteristics (const String& name_, const float ascent_, const bool isBold_,
  71765. const bool isItalic_, const juce_wchar defaultCharacter_) throw()
  71766. {
  71767. name = name_;
  71768. defaultCharacter = defaultCharacter_;
  71769. ascent = ascent_;
  71770. isBold = isBold_;
  71771. isItalic = isItalic_;
  71772. }
  71773. void CustomTypeface::addGlyph (const juce_wchar character, const Path& path, const float width) throw()
  71774. {
  71775. // Check that you're not trying to add the same character twice..
  71776. jassert (findGlyph (character, false) == 0);
  71777. if (((unsigned int) character) < (unsigned int) numElementsInArray (lookupTable))
  71778. lookupTable [character] = (short) glyphs.size();
  71779. glyphs.add (new GlyphInfo (character, path, width));
  71780. }
  71781. void CustomTypeface::addKerningPair (const juce_wchar char1, const juce_wchar char2, const float extraAmount) throw()
  71782. {
  71783. if (extraAmount != 0)
  71784. {
  71785. GlyphInfo* const g = findGlyph (char1, true);
  71786. jassert (g != 0); // can only add kerning pairs for characters that exist!
  71787. if (g != 0)
  71788. g->addKerningPair (char2, extraAmount);
  71789. }
  71790. }
  71791. CustomTypeface::GlyphInfo* CustomTypeface::findGlyph (const juce_wchar character, const bool loadIfNeeded) throw()
  71792. {
  71793. if (((unsigned int) character) < (unsigned int) numElementsInArray (lookupTable) && lookupTable [character] > 0)
  71794. return glyphs [(int) lookupTable [(int) character]];
  71795. for (int i = 0; i < glyphs.size(); ++i)
  71796. {
  71797. GlyphInfo* const g = glyphs.getUnchecked(i);
  71798. if (g->character == character)
  71799. return g;
  71800. }
  71801. if (loadIfNeeded && loadGlyphIfPossible (character))
  71802. return findGlyph (character, false);
  71803. return 0;
  71804. }
  71805. CustomTypeface::GlyphInfo* CustomTypeface::findGlyphSubstituting (const juce_wchar character) throw()
  71806. {
  71807. GlyphInfo* glyph = findGlyph (character, true);
  71808. if (glyph == 0)
  71809. {
  71810. if (CharacterFunctions::isWhitespace (character) && character != L' ')
  71811. glyph = findGlyph (L' ', true);
  71812. if (glyph == 0)
  71813. {
  71814. const Font fallbackFont (Font::getFallbackFontName(), 10, 0);
  71815. Typeface* const fallbackTypeface = fallbackFont.getTypeface();
  71816. if (fallbackTypeface != 0 && fallbackTypeface != this)
  71817. {
  71818. //xxx
  71819. }
  71820. if (glyph == 0)
  71821. glyph = findGlyph (defaultCharacter, true);
  71822. }
  71823. }
  71824. return glyph;
  71825. }
  71826. bool CustomTypeface::loadGlyphIfPossible (const juce_wchar /*characterNeeded*/)
  71827. {
  71828. return false;
  71829. }
  71830. void CustomTypeface::addGlyphsFromOtherTypeface (Typeface& typefaceToCopy, juce_wchar characterStartIndex, int numCharacters) throw()
  71831. {
  71832. setCharacteristics (name, typefaceToCopy.getAscent(), isBold, isItalic, defaultCharacter);
  71833. for (int i = 0; i < numCharacters; ++i)
  71834. {
  71835. const juce_wchar c = (juce_wchar) (characterStartIndex + i);
  71836. Array <int> glyphIndexes;
  71837. Array <float> offsets;
  71838. typefaceToCopy.getGlyphPositions (String::charToString (c), glyphIndexes, offsets);
  71839. const int glyphIndex = glyphIndexes.getFirst();
  71840. if (glyphIndex >= 0 && glyphIndexes.size() > 0)
  71841. {
  71842. const float glyphWidth = offsets[1];
  71843. Path p;
  71844. typefaceToCopy.getOutlineForGlyph (glyphIndex, p);
  71845. addGlyph (c, p, glyphWidth);
  71846. for (int j = glyphs.size() - 1; --j >= 0;)
  71847. {
  71848. const juce_wchar char2 = glyphs.getUnchecked (j)->character;
  71849. glyphIndexes.clearQuick();
  71850. offsets.clearQuick();
  71851. typefaceToCopy.getGlyphPositions (String::charToString (c) + String::charToString (char2), glyphIndexes, offsets);
  71852. if (offsets.size() > 1)
  71853. addKerningPair (c, char2, offsets[1] - glyphWidth);
  71854. }
  71855. }
  71856. }
  71857. }
  71858. bool CustomTypeface::writeToStream (OutputStream& outputStream)
  71859. {
  71860. GZIPCompressorOutputStream out (&outputStream);
  71861. out.writeString (name);
  71862. out.writeBool (isBold);
  71863. out.writeBool (isItalic);
  71864. out.writeFloat (ascent);
  71865. out.writeShort ((short) (unsigned short) defaultCharacter);
  71866. out.writeInt (glyphs.size());
  71867. int i, numKerningPairs = 0;
  71868. for (i = 0; i < glyphs.size(); ++i)
  71869. {
  71870. const GlyphInfo* const g = glyphs.getUnchecked (i);
  71871. out.writeShort ((short) (unsigned short) g->character);
  71872. out.writeFloat (g->width);
  71873. g->path.writePathToStream (out);
  71874. numKerningPairs += g->kerningPairs.size();
  71875. }
  71876. out.writeInt (numKerningPairs);
  71877. for (i = 0; i < glyphs.size(); ++i)
  71878. {
  71879. const GlyphInfo* const g = glyphs.getUnchecked (i);
  71880. for (int j = 0; j < g->kerningPairs.size(); ++j)
  71881. {
  71882. const GlyphInfo::KerningPair& p = g->kerningPairs.getReference (j);
  71883. out.writeShort ((short) (unsigned short) g->character);
  71884. out.writeShort ((short) (unsigned short) p.character2);
  71885. out.writeFloat (p.kerningAmount);
  71886. }
  71887. }
  71888. return true;
  71889. }
  71890. float CustomTypeface::getAscent() const
  71891. {
  71892. return ascent;
  71893. }
  71894. float CustomTypeface::getDescent() const
  71895. {
  71896. return 1.0f - ascent;
  71897. }
  71898. float CustomTypeface::getStringWidth (const String& text)
  71899. {
  71900. float x = 0;
  71901. const juce_wchar* t = text;
  71902. while (*t != 0)
  71903. {
  71904. const GlyphInfo* const glyph = findGlyphSubstituting (*t++);
  71905. if (glyph != 0)
  71906. x += glyph->getHorizontalSpacing (*t);
  71907. }
  71908. return x;
  71909. }
  71910. void CustomTypeface::getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array<float>& xOffsets)
  71911. {
  71912. xOffsets.add (0);
  71913. float x = 0;
  71914. const juce_wchar* t = text;
  71915. while (*t != 0)
  71916. {
  71917. const juce_wchar c = *t++;
  71918. const GlyphInfo* const glyph = findGlyphSubstituting (c);
  71919. if (glyph != 0)
  71920. {
  71921. x += glyph->getHorizontalSpacing (*t);
  71922. resultGlyphs.add ((int) glyph->character);
  71923. xOffsets.add (x);
  71924. }
  71925. }
  71926. }
  71927. bool CustomTypeface::getOutlineForGlyph (int glyphNumber, Path& path)
  71928. {
  71929. const GlyphInfo* const glyph = findGlyphSubstituting ((juce_wchar) glyphNumber);
  71930. if (glyph != 0)
  71931. {
  71932. path = glyph->path;
  71933. return true;
  71934. }
  71935. return false;
  71936. }
  71937. END_JUCE_NAMESPACE
  71938. /*** End of inlined file: juce_Typeface.cpp ***/
  71939. /*** Start of inlined file: juce_AffineTransform.cpp ***/
  71940. BEGIN_JUCE_NAMESPACE
  71941. AffineTransform::AffineTransform() throw()
  71942. : mat00 (1.0f),
  71943. mat01 (0),
  71944. mat02 (0),
  71945. mat10 (0),
  71946. mat11 (1.0f),
  71947. mat12 (0)
  71948. {
  71949. }
  71950. AffineTransform::AffineTransform (const AffineTransform& other) throw()
  71951. : mat00 (other.mat00),
  71952. mat01 (other.mat01),
  71953. mat02 (other.mat02),
  71954. mat10 (other.mat10),
  71955. mat11 (other.mat11),
  71956. mat12 (other.mat12)
  71957. {
  71958. }
  71959. AffineTransform::AffineTransform (const float mat00_,
  71960. const float mat01_,
  71961. const float mat02_,
  71962. const float mat10_,
  71963. const float mat11_,
  71964. const float mat12_) throw()
  71965. : mat00 (mat00_),
  71966. mat01 (mat01_),
  71967. mat02 (mat02_),
  71968. mat10 (mat10_),
  71969. mat11 (mat11_),
  71970. mat12 (mat12_)
  71971. {
  71972. }
  71973. AffineTransform& AffineTransform::operator= (const AffineTransform& other) throw()
  71974. {
  71975. mat00 = other.mat00;
  71976. mat01 = other.mat01;
  71977. mat02 = other.mat02;
  71978. mat10 = other.mat10;
  71979. mat11 = other.mat11;
  71980. mat12 = other.mat12;
  71981. return *this;
  71982. }
  71983. bool AffineTransform::operator== (const AffineTransform& other) const throw()
  71984. {
  71985. return mat00 == other.mat00
  71986. && mat01 == other.mat01
  71987. && mat02 == other.mat02
  71988. && mat10 == other.mat10
  71989. && mat11 == other.mat11
  71990. && mat12 == other.mat12;
  71991. }
  71992. bool AffineTransform::operator!= (const AffineTransform& other) const throw()
  71993. {
  71994. return ! operator== (other);
  71995. }
  71996. bool AffineTransform::isIdentity() const throw()
  71997. {
  71998. return (mat01 == 0)
  71999. && (mat02 == 0)
  72000. && (mat10 == 0)
  72001. && (mat12 == 0)
  72002. && (mat00 == 1.0f)
  72003. && (mat11 == 1.0f);
  72004. }
  72005. const AffineTransform AffineTransform::identity;
  72006. const AffineTransform AffineTransform::followedBy (const AffineTransform& other) const throw()
  72007. {
  72008. return AffineTransform (other.mat00 * mat00 + other.mat01 * mat10,
  72009. other.mat00 * mat01 + other.mat01 * mat11,
  72010. other.mat00 * mat02 + other.mat01 * mat12 + other.mat02,
  72011. other.mat10 * mat00 + other.mat11 * mat10,
  72012. other.mat10 * mat01 + other.mat11 * mat11,
  72013. other.mat10 * mat02 + other.mat11 * mat12 + other.mat12);
  72014. }
  72015. const AffineTransform AffineTransform::followedBy (const float omat00,
  72016. const float omat01,
  72017. const float omat02,
  72018. const float omat10,
  72019. const float omat11,
  72020. const float omat12) const throw()
  72021. {
  72022. return AffineTransform (omat00 * mat00 + omat01 * mat10,
  72023. omat00 * mat01 + omat01 * mat11,
  72024. omat00 * mat02 + omat01 * mat12 + omat02,
  72025. omat10 * mat00 + omat11 * mat10,
  72026. omat10 * mat01 + omat11 * mat11,
  72027. omat10 * mat02 + omat11 * mat12 + omat12);
  72028. }
  72029. const AffineTransform AffineTransform::translated (const float dx,
  72030. const float dy) const throw()
  72031. {
  72032. return AffineTransform (mat00, mat01, mat02 + dx,
  72033. mat10, mat11, mat12 + dy);
  72034. }
  72035. const AffineTransform AffineTransform::translation (const float dx,
  72036. const float dy) throw()
  72037. {
  72038. return AffineTransform (1.0f, 0, dx,
  72039. 0, 1.0f, dy);
  72040. }
  72041. const AffineTransform AffineTransform::rotated (const float rad) const throw()
  72042. {
  72043. const float cosRad = std::cos (rad);
  72044. const float sinRad = std::sin (rad);
  72045. return followedBy (cosRad, -sinRad, 0,
  72046. sinRad, cosRad, 0);
  72047. }
  72048. const AffineTransform AffineTransform::rotation (const float rad) throw()
  72049. {
  72050. const float cosRad = std::cos (rad);
  72051. const float sinRad = std::sin (rad);
  72052. return AffineTransform (cosRad, -sinRad, 0,
  72053. sinRad, cosRad, 0);
  72054. }
  72055. const AffineTransform AffineTransform::rotated (const float angle,
  72056. const float pivotX,
  72057. const float pivotY) const throw()
  72058. {
  72059. return translated (-pivotX, -pivotY)
  72060. .rotated (angle)
  72061. .translated (pivotX, pivotY);
  72062. }
  72063. const AffineTransform AffineTransform::rotation (const float angle,
  72064. const float pivotX,
  72065. const float pivotY) throw()
  72066. {
  72067. return translation (-pivotX, -pivotY)
  72068. .rotated (angle)
  72069. .translated (pivotX, pivotY);
  72070. }
  72071. const AffineTransform AffineTransform::scaled (const float factorX,
  72072. const float factorY) const throw()
  72073. {
  72074. return AffineTransform (factorX * mat00, factorX * mat01, factorX * mat02,
  72075. factorY * mat10, factorY * mat11, factorY * mat12);
  72076. }
  72077. const AffineTransform AffineTransform::scale (const float factorX,
  72078. const float factorY) throw()
  72079. {
  72080. return AffineTransform (factorX, 0, 0,
  72081. 0, factorY, 0);
  72082. }
  72083. const AffineTransform AffineTransform::sheared (const float shearX,
  72084. const float shearY) const throw()
  72085. {
  72086. return followedBy (1.0f, shearX, 0,
  72087. shearY, 1.0f, 0);
  72088. }
  72089. const AffineTransform AffineTransform::inverted() const throw()
  72090. {
  72091. double determinant = (mat00 * mat11 - mat10 * mat01);
  72092. if (determinant != 0.0)
  72093. {
  72094. determinant = 1.0 / determinant;
  72095. const float dst00 = (float) (mat11 * determinant);
  72096. const float dst10 = (float) (-mat10 * determinant);
  72097. const float dst01 = (float) (-mat01 * determinant);
  72098. const float dst11 = (float) (mat00 * determinant);
  72099. return AffineTransform (dst00, dst01, -mat02 * dst00 - mat12 * dst01,
  72100. dst10, dst11, -mat02 * dst10 - mat12 * dst11);
  72101. }
  72102. else
  72103. {
  72104. // singularity..
  72105. return *this;
  72106. }
  72107. }
  72108. bool AffineTransform::isSingularity() const throw()
  72109. {
  72110. return (mat00 * mat11 - mat10 * mat01) == 0.0;
  72111. }
  72112. const AffineTransform AffineTransform::fromTargetPoints (const float x00, const float y00,
  72113. const float x10, const float y10,
  72114. const float x01, const float y01) throw()
  72115. {
  72116. return AffineTransform (x10 - x00, x01 - x00, x00,
  72117. y10 - y00, y01 - y00, y00);
  72118. }
  72119. const AffineTransform AffineTransform::fromTargetPoints (const float sx1, const float sy1, const float tx1, const float ty1,
  72120. const float sx2, const float sy2, const float tx2, const float ty2,
  72121. const float sx3, const float sy3, const float tx3, const float ty3) throw()
  72122. {
  72123. return fromTargetPoints (sx1, sy1, sx2, sy2, sx3, sy3)
  72124. .inverted()
  72125. .followedBy (fromTargetPoints (tx1, ty1, tx2, ty2, tx3, ty3));
  72126. }
  72127. bool AffineTransform::isOnlyTranslation() const throw()
  72128. {
  72129. return (mat01 == 0)
  72130. && (mat10 == 0)
  72131. && (mat00 == 1.0f)
  72132. && (mat11 == 1.0f);
  72133. }
  72134. void AffineTransform::transformPoint (float& x,
  72135. float& y) const throw()
  72136. {
  72137. const float oldX = x;
  72138. x = mat00 * oldX + mat01 * y + mat02;
  72139. y = mat10 * oldX + mat11 * y + mat12;
  72140. }
  72141. void AffineTransform::transformPoint (double& x,
  72142. double& y) const throw()
  72143. {
  72144. const double oldX = x;
  72145. x = mat00 * oldX + mat01 * y + mat02;
  72146. y = mat10 * oldX + mat11 * y + mat12;
  72147. }
  72148. END_JUCE_NAMESPACE
  72149. /*** End of inlined file: juce_AffineTransform.cpp ***/
  72150. /*** Start of inlined file: juce_BorderSize.cpp ***/
  72151. BEGIN_JUCE_NAMESPACE
  72152. BorderSize::BorderSize() throw()
  72153. : top (0),
  72154. left (0),
  72155. bottom (0),
  72156. right (0)
  72157. {
  72158. }
  72159. BorderSize::BorderSize (const BorderSize& other) throw()
  72160. : top (other.top),
  72161. left (other.left),
  72162. bottom (other.bottom),
  72163. right (other.right)
  72164. {
  72165. }
  72166. BorderSize::BorderSize (const int topGap,
  72167. const int leftGap,
  72168. const int bottomGap,
  72169. const int rightGap) throw()
  72170. : top (topGap),
  72171. left (leftGap),
  72172. bottom (bottomGap),
  72173. right (rightGap)
  72174. {
  72175. }
  72176. BorderSize::BorderSize (const int allGaps) throw()
  72177. : top (allGaps),
  72178. left (allGaps),
  72179. bottom (allGaps),
  72180. right (allGaps)
  72181. {
  72182. }
  72183. BorderSize::~BorderSize() throw()
  72184. {
  72185. }
  72186. void BorderSize::setTop (const int newTopGap) throw()
  72187. {
  72188. top = newTopGap;
  72189. }
  72190. void BorderSize::setLeft (const int newLeftGap) throw()
  72191. {
  72192. left = newLeftGap;
  72193. }
  72194. void BorderSize::setBottom (const int newBottomGap) throw()
  72195. {
  72196. bottom = newBottomGap;
  72197. }
  72198. void BorderSize::setRight (const int newRightGap) throw()
  72199. {
  72200. right = newRightGap;
  72201. }
  72202. const Rectangle<int> BorderSize::subtractedFrom (const Rectangle<int>& r) const throw()
  72203. {
  72204. return Rectangle<int> (r.getX() + left,
  72205. r.getY() + top,
  72206. r.getWidth() - (left + right),
  72207. r.getHeight() - (top + bottom));
  72208. }
  72209. void BorderSize::subtractFrom (Rectangle<int>& r) const throw()
  72210. {
  72211. r.setBounds (r.getX() + left,
  72212. r.getY() + top,
  72213. r.getWidth() - (left + right),
  72214. r.getHeight() - (top + bottom));
  72215. }
  72216. const Rectangle<int> BorderSize::addedTo (const Rectangle<int>& r) const throw()
  72217. {
  72218. return Rectangle<int> (r.getX() - left,
  72219. r.getY() - top,
  72220. r.getWidth() + (left + right),
  72221. r.getHeight() + (top + bottom));
  72222. }
  72223. void BorderSize::addTo (Rectangle<int>& r) const throw()
  72224. {
  72225. r.setBounds (r.getX() - left,
  72226. r.getY() - top,
  72227. r.getWidth() + (left + right),
  72228. r.getHeight() + (top + bottom));
  72229. }
  72230. bool BorderSize::operator== (const BorderSize& other) const throw()
  72231. {
  72232. return top == other.top
  72233. && left == other.left
  72234. && bottom == other.bottom
  72235. && right == other.right;
  72236. }
  72237. bool BorderSize::operator!= (const BorderSize& other) const throw()
  72238. {
  72239. return ! operator== (other);
  72240. }
  72241. END_JUCE_NAMESPACE
  72242. /*** End of inlined file: juce_BorderSize.cpp ***/
  72243. /*** Start of inlined file: juce_Path.cpp ***/
  72244. BEGIN_JUCE_NAMESPACE
  72245. // tests that some co-ords aren't NaNs
  72246. #define CHECK_COORDS_ARE_VALID(x, y) \
  72247. jassert (x == x && y == y);
  72248. namespace PathHelpers
  72249. {
  72250. static const float ellipseAngularIncrement = 0.05f;
  72251. static const String nextToken (const juce_wchar*& t)
  72252. {
  72253. while (CharacterFunctions::isWhitespace (*t))
  72254. ++t;
  72255. const juce_wchar* const start = t;
  72256. while (*t != 0 && ! CharacterFunctions::isWhitespace (*t))
  72257. ++t;
  72258. return String (start, (int) (t - start));
  72259. }
  72260. }
  72261. const float Path::lineMarker = 100001.0f;
  72262. const float Path::moveMarker = 100002.0f;
  72263. const float Path::quadMarker = 100003.0f;
  72264. const float Path::cubicMarker = 100004.0f;
  72265. const float Path::closeSubPathMarker = 100005.0f;
  72266. Path::Path()
  72267. : numElements (0),
  72268. pathXMin (0),
  72269. pathXMax (0),
  72270. pathYMin (0),
  72271. pathYMax (0),
  72272. useNonZeroWinding (true)
  72273. {
  72274. }
  72275. Path::~Path()
  72276. {
  72277. }
  72278. Path::Path (const Path& other)
  72279. : numElements (other.numElements),
  72280. pathXMin (other.pathXMin),
  72281. pathXMax (other.pathXMax),
  72282. pathYMin (other.pathYMin),
  72283. pathYMax (other.pathYMax),
  72284. useNonZeroWinding (other.useNonZeroWinding)
  72285. {
  72286. if (numElements > 0)
  72287. {
  72288. data.setAllocatedSize ((int) numElements);
  72289. memcpy (data.elements, other.data.elements, numElements * sizeof (float));
  72290. }
  72291. }
  72292. Path& Path::operator= (const Path& other)
  72293. {
  72294. if (this != &other)
  72295. {
  72296. data.ensureAllocatedSize ((int) other.numElements);
  72297. numElements = other.numElements;
  72298. pathXMin = other.pathXMin;
  72299. pathXMax = other.pathXMax;
  72300. pathYMin = other.pathYMin;
  72301. pathYMax = other.pathYMax;
  72302. useNonZeroWinding = other.useNonZeroWinding;
  72303. if (numElements > 0)
  72304. memcpy (data.elements, other.data.elements, numElements * sizeof (float));
  72305. }
  72306. return *this;
  72307. }
  72308. bool Path::operator== (const Path& other) const throw()
  72309. {
  72310. return ! operator!= (other);
  72311. }
  72312. bool Path::operator!= (const Path& other) const throw()
  72313. {
  72314. if (numElements != other.numElements || useNonZeroWinding != other.useNonZeroWinding)
  72315. return true;
  72316. for (size_t i = 0; i < numElements; ++i)
  72317. if (data.elements[i] != other.data.elements[i])
  72318. return true;
  72319. return false;
  72320. }
  72321. void Path::clear() throw()
  72322. {
  72323. numElements = 0;
  72324. pathXMin = 0;
  72325. pathYMin = 0;
  72326. pathYMax = 0;
  72327. pathXMax = 0;
  72328. }
  72329. void Path::swapWithPath (Path& other) throw()
  72330. {
  72331. data.swapWith (other.data);
  72332. swapVariables <size_t> (numElements, other.numElements);
  72333. swapVariables <float> (pathXMin, other.pathXMin);
  72334. swapVariables <float> (pathXMax, other.pathXMax);
  72335. swapVariables <float> (pathYMin, other.pathYMin);
  72336. swapVariables <float> (pathYMax, other.pathYMax);
  72337. swapVariables <bool> (useNonZeroWinding, other.useNonZeroWinding);
  72338. }
  72339. void Path::setUsingNonZeroWinding (const bool isNonZero) throw()
  72340. {
  72341. useNonZeroWinding = isNonZero;
  72342. }
  72343. void Path::scaleToFit (const float x, const float y, const float w, const float h,
  72344. const bool preserveProportions) throw()
  72345. {
  72346. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions));
  72347. }
  72348. bool Path::isEmpty() const throw()
  72349. {
  72350. size_t i = 0;
  72351. while (i < numElements)
  72352. {
  72353. const float type = data.elements [i++];
  72354. if (type == moveMarker)
  72355. {
  72356. i += 2;
  72357. }
  72358. else if (type == lineMarker
  72359. || type == quadMarker
  72360. || type == cubicMarker)
  72361. {
  72362. return false;
  72363. }
  72364. }
  72365. return true;
  72366. }
  72367. const Rectangle<float> Path::getBounds() const throw()
  72368. {
  72369. return Rectangle<float> (pathXMin, pathYMin,
  72370. pathXMax - pathXMin,
  72371. pathYMax - pathYMin);
  72372. }
  72373. const Rectangle<float> Path::getBoundsTransformed (const AffineTransform& transform) const throw()
  72374. {
  72375. return getBounds().transformed (transform);
  72376. }
  72377. void Path::startNewSubPath (const float x, const float y)
  72378. {
  72379. CHECK_COORDS_ARE_VALID (x, y);
  72380. if (numElements == 0)
  72381. {
  72382. pathXMin = pathXMax = x;
  72383. pathYMin = pathYMax = y;
  72384. }
  72385. else
  72386. {
  72387. pathXMin = jmin (pathXMin, x);
  72388. pathXMax = jmax (pathXMax, x);
  72389. pathYMin = jmin (pathYMin, y);
  72390. pathYMax = jmax (pathYMax, y);
  72391. }
  72392. data.ensureAllocatedSize ((int) numElements + 3);
  72393. data.elements [numElements++] = moveMarker;
  72394. data.elements [numElements++] = x;
  72395. data.elements [numElements++] = y;
  72396. }
  72397. void Path::startNewSubPath (const Point<float>& start)
  72398. {
  72399. startNewSubPath (start.getX(), start.getY());
  72400. }
  72401. void Path::lineTo (const float x, const float y)
  72402. {
  72403. CHECK_COORDS_ARE_VALID (x, y);
  72404. if (numElements == 0)
  72405. startNewSubPath (0, 0);
  72406. data.ensureAllocatedSize ((int) numElements + 3);
  72407. data.elements [numElements++] = lineMarker;
  72408. data.elements [numElements++] = x;
  72409. data.elements [numElements++] = y;
  72410. pathXMin = jmin (pathXMin, x);
  72411. pathXMax = jmax (pathXMax, x);
  72412. pathYMin = jmin (pathYMin, y);
  72413. pathYMax = jmax (pathYMax, y);
  72414. }
  72415. void Path::lineTo (const Point<float>& end)
  72416. {
  72417. lineTo (end.getX(), end.getY());
  72418. }
  72419. void Path::quadraticTo (const float x1, const float y1,
  72420. const float x2, const float y2)
  72421. {
  72422. CHECK_COORDS_ARE_VALID (x1, y1);
  72423. CHECK_COORDS_ARE_VALID (x2, y2);
  72424. if (numElements == 0)
  72425. startNewSubPath (0, 0);
  72426. data.ensureAllocatedSize ((int) numElements + 5);
  72427. data.elements [numElements++] = quadMarker;
  72428. data.elements [numElements++] = x1;
  72429. data.elements [numElements++] = y1;
  72430. data.elements [numElements++] = x2;
  72431. data.elements [numElements++] = y2;
  72432. pathXMin = jmin (pathXMin, x1, x2);
  72433. pathXMax = jmax (pathXMax, x1, x2);
  72434. pathYMin = jmin (pathYMin, y1, y2);
  72435. pathYMax = jmax (pathYMax, y1, y2);
  72436. }
  72437. void Path::quadraticTo (const Point<float>& controlPoint,
  72438. const Point<float>& endPoint)
  72439. {
  72440. quadraticTo (controlPoint.getX(), controlPoint.getY(),
  72441. endPoint.getX(), endPoint.getY());
  72442. }
  72443. void Path::cubicTo (const float x1, const float y1,
  72444. const float x2, const float y2,
  72445. const float x3, const float y3)
  72446. {
  72447. CHECK_COORDS_ARE_VALID (x1, y1);
  72448. CHECK_COORDS_ARE_VALID (x2, y2);
  72449. CHECK_COORDS_ARE_VALID (x3, y3);
  72450. if (numElements == 0)
  72451. startNewSubPath (0, 0);
  72452. data.ensureAllocatedSize ((int) numElements + 7);
  72453. data.elements [numElements++] = cubicMarker;
  72454. data.elements [numElements++] = x1;
  72455. data.elements [numElements++] = y1;
  72456. data.elements [numElements++] = x2;
  72457. data.elements [numElements++] = y2;
  72458. data.elements [numElements++] = x3;
  72459. data.elements [numElements++] = y3;
  72460. pathXMin = jmin (pathXMin, x1, x2, x3);
  72461. pathXMax = jmax (pathXMax, x1, x2, x3);
  72462. pathYMin = jmin (pathYMin, y1, y2, y3);
  72463. pathYMax = jmax (pathYMax, y1, y2, y3);
  72464. }
  72465. void Path::cubicTo (const Point<float>& controlPoint1,
  72466. const Point<float>& controlPoint2,
  72467. const Point<float>& endPoint)
  72468. {
  72469. cubicTo (controlPoint1.getX(), controlPoint1.getY(),
  72470. controlPoint2.getX(), controlPoint2.getY(),
  72471. endPoint.getX(), endPoint.getY());
  72472. }
  72473. void Path::closeSubPath()
  72474. {
  72475. if (numElements > 0
  72476. && data.elements [numElements - 1] != closeSubPathMarker)
  72477. {
  72478. data.ensureAllocatedSize ((int) numElements + 1);
  72479. data.elements [numElements++] = closeSubPathMarker;
  72480. }
  72481. }
  72482. const Point<float> Path::getCurrentPosition() const
  72483. {
  72484. size_t i = numElements - 1;
  72485. if (i > 0 && data.elements[i] == closeSubPathMarker)
  72486. {
  72487. while (i >= 0)
  72488. {
  72489. if (data.elements[i] == moveMarker)
  72490. {
  72491. i += 2;
  72492. break;
  72493. }
  72494. --i;
  72495. }
  72496. }
  72497. if (i > 0)
  72498. return Point<float> (data.elements [i - 1], data.elements [i]);
  72499. return Point<float>();
  72500. }
  72501. void Path::addRectangle (const float x, const float y,
  72502. const float w, const float h)
  72503. {
  72504. float x1 = x, y1 = y, x2 = x + w, y2 = y + h;
  72505. if (w < 0)
  72506. swapVariables (x1, x2);
  72507. if (h < 0)
  72508. swapVariables (y1, y2);
  72509. data.ensureAllocatedSize ((int) numElements + 13);
  72510. if (numElements == 0)
  72511. {
  72512. pathXMin = x1;
  72513. pathXMax = x2;
  72514. pathYMin = y1;
  72515. pathYMax = y2;
  72516. }
  72517. else
  72518. {
  72519. pathXMin = jmin (pathXMin, x1);
  72520. pathXMax = jmax (pathXMax, x2);
  72521. pathYMin = jmin (pathYMin, y1);
  72522. pathYMax = jmax (pathYMax, y2);
  72523. }
  72524. data.elements [numElements++] = moveMarker;
  72525. data.elements [numElements++] = x1;
  72526. data.elements [numElements++] = y2;
  72527. data.elements [numElements++] = lineMarker;
  72528. data.elements [numElements++] = x1;
  72529. data.elements [numElements++] = y1;
  72530. data.elements [numElements++] = lineMarker;
  72531. data.elements [numElements++] = x2;
  72532. data.elements [numElements++] = y1;
  72533. data.elements [numElements++] = lineMarker;
  72534. data.elements [numElements++] = x2;
  72535. data.elements [numElements++] = y2;
  72536. data.elements [numElements++] = closeSubPathMarker;
  72537. }
  72538. void Path::addRectangle (const Rectangle<int>& rectangle)
  72539. {
  72540. addRectangle ((float) rectangle.getX(), (float) rectangle.getY(),
  72541. (float) rectangle.getWidth(), (float) rectangle.getHeight());
  72542. }
  72543. void Path::addRoundedRectangle (const float x, const float y,
  72544. const float w, const float h,
  72545. float csx,
  72546. float csy)
  72547. {
  72548. csx = jmin (csx, w * 0.5f);
  72549. csy = jmin (csy, h * 0.5f);
  72550. const float cs45x = csx * 0.45f;
  72551. const float cs45y = csy * 0.45f;
  72552. const float x2 = x + w;
  72553. const float y2 = y + h;
  72554. startNewSubPath (x + csx, y);
  72555. lineTo (x2 - csx, y);
  72556. cubicTo (x2 - cs45x, y, x2, y + cs45y, x2, y + csy);
  72557. lineTo (x2, y2 - csy);
  72558. cubicTo (x2, y2 - cs45y, x2 - cs45x, y2, x2 - csx, y2);
  72559. lineTo (x + csx, y2);
  72560. cubicTo (x + cs45x, y2, x, y2 - cs45y, x, y2 - csy);
  72561. lineTo (x, y + csy);
  72562. cubicTo (x, y + cs45y, x + cs45x, y, x + csx, y);
  72563. closeSubPath();
  72564. }
  72565. void Path::addRoundedRectangle (const float x, const float y,
  72566. const float w, const float h,
  72567. float cs)
  72568. {
  72569. addRoundedRectangle (x, y, w, h, cs, cs);
  72570. }
  72571. void Path::addTriangle (const float x1, const float y1,
  72572. const float x2, const float y2,
  72573. const float x3, const float y3)
  72574. {
  72575. startNewSubPath (x1, y1);
  72576. lineTo (x2, y2);
  72577. lineTo (x3, y3);
  72578. closeSubPath();
  72579. }
  72580. void Path::addQuadrilateral (const float x1, const float y1,
  72581. const float x2, const float y2,
  72582. const float x3, const float y3,
  72583. const float x4, const float y4)
  72584. {
  72585. startNewSubPath (x1, y1);
  72586. lineTo (x2, y2);
  72587. lineTo (x3, y3);
  72588. lineTo (x4, y4);
  72589. closeSubPath();
  72590. }
  72591. void Path::addEllipse (const float x, const float y,
  72592. const float w, const float h)
  72593. {
  72594. const float hw = w * 0.5f;
  72595. const float hw55 = hw * 0.55f;
  72596. const float hh = h * 0.5f;
  72597. const float hh45 = hh * 0.55f;
  72598. const float cx = x + hw;
  72599. const float cy = y + hh;
  72600. startNewSubPath (cx, cy - hh);
  72601. cubicTo (cx + hw55, cy - hh, cx + hw, cy - hh45, cx + hw, cy);
  72602. cubicTo (cx + hw, cy + hh45, cx + hw55, cy + hh, cx, cy + hh);
  72603. cubicTo (cx - hw55, cy + hh, cx - hw, cy + hh45, cx - hw, cy);
  72604. cubicTo (cx - hw, cy - hh45, cx - hw55, cy - hh, cx, cy - hh);
  72605. closeSubPath();
  72606. }
  72607. void Path::addArc (const float x, const float y,
  72608. const float w, const float h,
  72609. const float fromRadians,
  72610. const float toRadians,
  72611. const bool startAsNewSubPath)
  72612. {
  72613. const float radiusX = w / 2.0f;
  72614. const float radiusY = h / 2.0f;
  72615. addCentredArc (x + radiusX,
  72616. y + radiusY,
  72617. radiusX, radiusY,
  72618. 0.0f,
  72619. fromRadians, toRadians,
  72620. startAsNewSubPath);
  72621. }
  72622. void Path::addCentredArc (const float centreX, const float centreY,
  72623. const float radiusX, const float radiusY,
  72624. const float rotationOfEllipse,
  72625. const float fromRadians,
  72626. const float toRadians,
  72627. const bool startAsNewSubPath)
  72628. {
  72629. if (radiusX > 0.0f && radiusY > 0.0f)
  72630. {
  72631. const Point<float> centre (centreX, centreY);
  72632. const AffineTransform rotation (AffineTransform::rotation (rotationOfEllipse, centreX, centreY));
  72633. float angle = fromRadians;
  72634. if (startAsNewSubPath)
  72635. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  72636. if (fromRadians < toRadians)
  72637. {
  72638. if (startAsNewSubPath)
  72639. angle += PathHelpers::ellipseAngularIncrement;
  72640. while (angle < toRadians)
  72641. {
  72642. lineTo (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  72643. angle += PathHelpers::ellipseAngularIncrement;
  72644. }
  72645. }
  72646. else
  72647. {
  72648. if (startAsNewSubPath)
  72649. angle -= PathHelpers::ellipseAngularIncrement;
  72650. while (angle > toRadians)
  72651. {
  72652. lineTo (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  72653. angle -= PathHelpers::ellipseAngularIncrement;
  72654. }
  72655. }
  72656. lineTo (centre.getPointOnCircumference (radiusX, radiusY, toRadians).transformedBy (rotation));
  72657. }
  72658. }
  72659. void Path::addPieSegment (const float x, const float y,
  72660. const float width, const float height,
  72661. const float fromRadians,
  72662. const float toRadians,
  72663. const float innerCircleProportionalSize)
  72664. {
  72665. float radiusX = width * 0.5f;
  72666. float radiusY = height * 0.5f;
  72667. const Point<float> centre (x + radiusX, y + radiusY);
  72668. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, fromRadians));
  72669. addArc (x, y, width, height, fromRadians, toRadians);
  72670. if (std::abs (fromRadians - toRadians) > float_Pi * 1.999f)
  72671. {
  72672. closeSubPath();
  72673. if (innerCircleProportionalSize > 0)
  72674. {
  72675. radiusX *= innerCircleProportionalSize;
  72676. radiusY *= innerCircleProportionalSize;
  72677. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, toRadians));
  72678. addArc (centre.getX() - radiusX, centre.getY() - radiusY, radiusX * 2.0f, radiusY * 2.0f, toRadians, fromRadians);
  72679. }
  72680. }
  72681. else
  72682. {
  72683. if (innerCircleProportionalSize > 0)
  72684. {
  72685. radiusX *= innerCircleProportionalSize;
  72686. radiusY *= innerCircleProportionalSize;
  72687. addArc (centre.getX() - radiusX, centre.getY() - radiusY, radiusX * 2.0f, radiusY * 2.0f, toRadians, fromRadians);
  72688. }
  72689. else
  72690. {
  72691. lineTo (centre);
  72692. }
  72693. }
  72694. closeSubPath();
  72695. }
  72696. void Path::addLineSegment (const Line<float>& line, float lineThickness)
  72697. {
  72698. const Line<float> reversed (line.reversed());
  72699. lineThickness *= 0.5f;
  72700. startNewSubPath (line.getPointAlongLine (0, lineThickness));
  72701. lineTo (line.getPointAlongLine (0, -lineThickness));
  72702. lineTo (reversed.getPointAlongLine (0, lineThickness));
  72703. lineTo (reversed.getPointAlongLine (0, -lineThickness));
  72704. closeSubPath();
  72705. }
  72706. void Path::addArrow (const Line<float>& line, float lineThickness,
  72707. float arrowheadWidth, float arrowheadLength)
  72708. {
  72709. const Line<float> reversed (line.reversed());
  72710. lineThickness *= 0.5f;
  72711. arrowheadWidth *= 0.5f;
  72712. arrowheadLength = jmin (arrowheadLength, 0.8f * line.getLength());
  72713. startNewSubPath (line.getPointAlongLine (0, lineThickness));
  72714. lineTo (line.getPointAlongLine (0, -lineThickness));
  72715. lineTo (reversed.getPointAlongLine (0, lineThickness));
  72716. lineTo (reversed.getPointAlongLine (arrowheadLength, arrowheadWidth));
  72717. lineTo (line.getEnd());
  72718. lineTo (reversed.getPointAlongLine (arrowheadLength, -arrowheadWidth));
  72719. lineTo (reversed.getPointAlongLine (arrowheadLength, -lineThickness));
  72720. closeSubPath();
  72721. }
  72722. void Path::addPolygon (const Point<float>& centre, const int numberOfSides,
  72723. const float radius, const float startAngle)
  72724. {
  72725. jassert (numberOfSides > 1); // this would be silly.
  72726. if (numberOfSides > 1)
  72727. {
  72728. const float angleBetweenPoints = float_Pi * 2.0f / numberOfSides;
  72729. for (int i = 0; i < numberOfSides; ++i)
  72730. {
  72731. const float angle = startAngle + i * angleBetweenPoints;
  72732. const Point<float> p (centre.getPointOnCircumference (radius, angle));
  72733. if (i == 0)
  72734. startNewSubPath (p);
  72735. else
  72736. lineTo (p);
  72737. }
  72738. closeSubPath();
  72739. }
  72740. }
  72741. void Path::addStar (const Point<float>& centre, const int numberOfPoints,
  72742. const float innerRadius, const float outerRadius, const float startAngle)
  72743. {
  72744. jassert (numberOfPoints > 1); // this would be silly.
  72745. if (numberOfPoints > 1)
  72746. {
  72747. const float angleBetweenPoints = float_Pi * 2.0f / numberOfPoints;
  72748. for (int i = 0; i < numberOfPoints; ++i)
  72749. {
  72750. const float angle = startAngle + i * angleBetweenPoints;
  72751. const Point<float> p (centre.getPointOnCircumference (outerRadius, angle));
  72752. if (i == 0)
  72753. startNewSubPath (p);
  72754. else
  72755. lineTo (p);
  72756. lineTo (centre.getPointOnCircumference (innerRadius, angle + angleBetweenPoints * 0.5f));
  72757. }
  72758. closeSubPath();
  72759. }
  72760. }
  72761. void Path::addBubble (float x, float y,
  72762. float w, float h,
  72763. float cs,
  72764. float tipX,
  72765. float tipY,
  72766. int whichSide,
  72767. float arrowPos,
  72768. float arrowWidth)
  72769. {
  72770. if (w > 1.0f && h > 1.0f)
  72771. {
  72772. cs = jmin (cs, w * 0.5f, h * 0.5f);
  72773. const float cs2 = 2.0f * cs;
  72774. startNewSubPath (x + cs, y);
  72775. if (whichSide == 0)
  72776. {
  72777. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  72778. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  72779. lineTo (arrowX1, y);
  72780. lineTo (tipX, tipY);
  72781. lineTo (arrowX1 + halfArrowW * 2.0f, y);
  72782. }
  72783. lineTo (x + w - cs, y);
  72784. if (cs > 0.0f)
  72785. addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  72786. if (whichSide == 3)
  72787. {
  72788. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  72789. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  72790. lineTo (x + w, arrowY1);
  72791. lineTo (tipX, tipY);
  72792. lineTo (x + w, arrowY1 + halfArrowH * 2.0f);
  72793. }
  72794. lineTo (x + w, y + h - cs);
  72795. if (cs > 0.0f)
  72796. addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  72797. if (whichSide == 2)
  72798. {
  72799. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  72800. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  72801. lineTo (arrowX1 + halfArrowW * 2.0f, y + h);
  72802. lineTo (tipX, tipY);
  72803. lineTo (arrowX1, y + h);
  72804. }
  72805. lineTo (x + cs, y + h);
  72806. if (cs > 0.0f)
  72807. addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  72808. if (whichSide == 1)
  72809. {
  72810. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  72811. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  72812. lineTo (x, arrowY1 + halfArrowH * 2.0f);
  72813. lineTo (tipX, tipY);
  72814. lineTo (x, arrowY1);
  72815. }
  72816. lineTo (x, y + cs);
  72817. if (cs > 0.0f)
  72818. addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f - PathHelpers::ellipseAngularIncrement);
  72819. closeSubPath();
  72820. }
  72821. }
  72822. void Path::addPath (const Path& other)
  72823. {
  72824. size_t i = 0;
  72825. while (i < other.numElements)
  72826. {
  72827. const float type = other.data.elements [i++];
  72828. if (type == moveMarker)
  72829. {
  72830. startNewSubPath (other.data.elements [i],
  72831. other.data.elements [i + 1]);
  72832. i += 2;
  72833. }
  72834. else if (type == lineMarker)
  72835. {
  72836. lineTo (other.data.elements [i],
  72837. other.data.elements [i + 1]);
  72838. i += 2;
  72839. }
  72840. else if (type == quadMarker)
  72841. {
  72842. quadraticTo (other.data.elements [i],
  72843. other.data.elements [i + 1],
  72844. other.data.elements [i + 2],
  72845. other.data.elements [i + 3]);
  72846. i += 4;
  72847. }
  72848. else if (type == cubicMarker)
  72849. {
  72850. cubicTo (other.data.elements [i],
  72851. other.data.elements [i + 1],
  72852. other.data.elements [i + 2],
  72853. other.data.elements [i + 3],
  72854. other.data.elements [i + 4],
  72855. other.data.elements [i + 5]);
  72856. i += 6;
  72857. }
  72858. else if (type == closeSubPathMarker)
  72859. {
  72860. closeSubPath();
  72861. }
  72862. else
  72863. {
  72864. // something's gone wrong with the element list!
  72865. jassertfalse;
  72866. }
  72867. }
  72868. }
  72869. void Path::addPath (const Path& other,
  72870. const AffineTransform& transformToApply)
  72871. {
  72872. size_t i = 0;
  72873. while (i < other.numElements)
  72874. {
  72875. const float type = other.data.elements [i++];
  72876. if (type == closeSubPathMarker)
  72877. {
  72878. closeSubPath();
  72879. }
  72880. else
  72881. {
  72882. float x = other.data.elements [i++];
  72883. float y = other.data.elements [i++];
  72884. transformToApply.transformPoint (x, y);
  72885. if (type == moveMarker)
  72886. {
  72887. startNewSubPath (x, y);
  72888. }
  72889. else if (type == lineMarker)
  72890. {
  72891. lineTo (x, y);
  72892. }
  72893. else if (type == quadMarker)
  72894. {
  72895. float x2 = other.data.elements [i++];
  72896. float y2 = other.data.elements [i++];
  72897. transformToApply.transformPoint (x2, y2);
  72898. quadraticTo (x, y, x2, y2);
  72899. }
  72900. else if (type == cubicMarker)
  72901. {
  72902. float x2 = other.data.elements [i++];
  72903. float y2 = other.data.elements [i++];
  72904. float x3 = other.data.elements [i++];
  72905. float y3 = other.data.elements [i++];
  72906. transformToApply.transformPoint (x2, y2);
  72907. transformToApply.transformPoint (x3, y3);
  72908. cubicTo (x, y, x2, y2, x3, y3);
  72909. }
  72910. else
  72911. {
  72912. // something's gone wrong with the element list!
  72913. jassertfalse;
  72914. }
  72915. }
  72916. }
  72917. }
  72918. void Path::applyTransform (const AffineTransform& transform) throw()
  72919. {
  72920. size_t i = 0;
  72921. pathYMin = pathXMin = 0;
  72922. pathYMax = pathXMax = 0;
  72923. bool setMaxMin = false;
  72924. while (i < numElements)
  72925. {
  72926. const float type = data.elements [i++];
  72927. if (type == moveMarker)
  72928. {
  72929. transform.transformPoint (data.elements [i],
  72930. data.elements [i + 1]);
  72931. if (setMaxMin)
  72932. {
  72933. pathXMin = jmin (pathXMin, data.elements [i]);
  72934. pathXMax = jmax (pathXMax, data.elements [i]);
  72935. pathYMin = jmin (pathYMin, data.elements [i + 1]);
  72936. pathYMax = jmax (pathYMax, data.elements [i + 1]);
  72937. }
  72938. else
  72939. {
  72940. pathXMin = pathXMax = data.elements [i];
  72941. pathYMin = pathYMax = data.elements [i + 1];
  72942. setMaxMin = true;
  72943. }
  72944. i += 2;
  72945. }
  72946. else if (type == lineMarker)
  72947. {
  72948. transform.transformPoint (data.elements [i],
  72949. data.elements [i + 1]);
  72950. pathXMin = jmin (pathXMin, data.elements [i]);
  72951. pathXMax = jmax (pathXMax, data.elements [i]);
  72952. pathYMin = jmin (pathYMin, data.elements [i + 1]);
  72953. pathYMax = jmax (pathYMax, data.elements [i + 1]);
  72954. i += 2;
  72955. }
  72956. else if (type == quadMarker)
  72957. {
  72958. transform.transformPoint (data.elements [i],
  72959. data.elements [i + 1]);
  72960. transform.transformPoint (data.elements [i + 2],
  72961. data.elements [i + 3]);
  72962. pathXMin = jmin (pathXMin, data.elements [i], data.elements [i + 2]);
  72963. pathXMax = jmax (pathXMax, data.elements [i], data.elements [i + 2]);
  72964. pathYMin = jmin (pathYMin, data.elements [i + 1], data.elements [i + 3]);
  72965. pathYMax = jmax (pathYMax, data.elements [i + 1], data.elements [i + 3]);
  72966. i += 4;
  72967. }
  72968. else if (type == cubicMarker)
  72969. {
  72970. transform.transformPoint (data.elements [i],
  72971. data.elements [i + 1]);
  72972. transform.transformPoint (data.elements [i + 2],
  72973. data.elements [i + 3]);
  72974. transform.transformPoint (data.elements [i + 4],
  72975. data.elements [i + 5]);
  72976. pathXMin = jmin (pathXMin, data.elements [i], data.elements [i + 2], data.elements [i + 4]);
  72977. pathXMax = jmax (pathXMax, data.elements [i], data.elements [i + 2], data.elements [i + 4]);
  72978. pathYMin = jmin (pathYMin, data.elements [i + 1], data.elements [i + 3], data.elements [i + 5]);
  72979. pathYMax = jmax (pathYMax, data.elements [i + 1], data.elements [i + 3], data.elements [i + 5]);
  72980. i += 6;
  72981. }
  72982. }
  72983. }
  72984. const AffineTransform Path::getTransformToScaleToFit (const float x, const float y,
  72985. const float w, const float h,
  72986. const bool preserveProportions,
  72987. const Justification& justification) const
  72988. {
  72989. Rectangle<float> bounds (getBounds());
  72990. if (preserveProportions)
  72991. {
  72992. if (w <= 0 || h <= 0 || bounds.isEmpty())
  72993. return AffineTransform::identity;
  72994. float newW, newH;
  72995. const float srcRatio = bounds.getHeight() / bounds.getWidth();
  72996. if (srcRatio > h / w)
  72997. {
  72998. newW = h / srcRatio;
  72999. newH = h;
  73000. }
  73001. else
  73002. {
  73003. newW = w;
  73004. newH = w * srcRatio;
  73005. }
  73006. float newXCentre = x;
  73007. float newYCentre = y;
  73008. if (justification.testFlags (Justification::left))
  73009. newXCentre += newW * 0.5f;
  73010. else if (justification.testFlags (Justification::right))
  73011. newXCentre += w - newW * 0.5f;
  73012. else
  73013. newXCentre += w * 0.5f;
  73014. if (justification.testFlags (Justification::top))
  73015. newYCentre += newH * 0.5f;
  73016. else if (justification.testFlags (Justification::bottom))
  73017. newYCentre += h - newH * 0.5f;
  73018. else
  73019. newYCentre += h * 0.5f;
  73020. return AffineTransform::translation (bounds.getWidth() * -0.5f - bounds.getX(),
  73021. bounds.getHeight() * -0.5f - bounds.getY())
  73022. .scaled (newW / bounds.getWidth(), newH / bounds.getHeight())
  73023. .translated (newXCentre, newYCentre);
  73024. }
  73025. else
  73026. {
  73027. return AffineTransform::translation (-bounds.getX(), -bounds.getY())
  73028. .scaled (w / bounds.getWidth(), h / bounds.getHeight())
  73029. .translated (x, y);
  73030. }
  73031. }
  73032. bool Path::contains (const float x, const float y, const float tolerence) const
  73033. {
  73034. if (x <= pathXMin || x >= pathXMax
  73035. || y <= pathYMin || y >= pathYMax)
  73036. return false;
  73037. PathFlatteningIterator i (*this, AffineTransform::identity, tolerence);
  73038. int positiveCrossings = 0;
  73039. int negativeCrossings = 0;
  73040. while (i.next())
  73041. {
  73042. if ((i.y1 <= y && i.y2 > y) || (i.y2 <= y && i.y1 > y))
  73043. {
  73044. const float intersectX = i.x1 + (i.x2 - i.x1) * (y - i.y1) / (i.y2 - i.y1);
  73045. if (intersectX <= x)
  73046. {
  73047. if (i.y1 < i.y2)
  73048. ++positiveCrossings;
  73049. else
  73050. ++negativeCrossings;
  73051. }
  73052. }
  73053. }
  73054. return useNonZeroWinding ? (negativeCrossings != positiveCrossings)
  73055. : ((negativeCrossings + positiveCrossings) & 1) != 0;
  73056. }
  73057. bool Path::contains (const Point<float>& point, const float tolerence) const
  73058. {
  73059. return contains (point.getX(), point.getY(), tolerence);
  73060. }
  73061. bool Path::intersectsLine (const Line<float>& line, const float tolerence)
  73062. {
  73063. PathFlatteningIterator i (*this, AffineTransform::identity, tolerence);
  73064. Point<float> intersection;
  73065. while (i.next())
  73066. if (line.intersects (Line<float> (i.x1, i.y1, i.x2, i.y2), intersection))
  73067. return true;
  73068. return false;
  73069. }
  73070. const Line<float> Path::getClippedLine (const Line<float>& line, const bool keepSectionOutsidePath) const
  73071. {
  73072. Line<float> result (line);
  73073. const bool startInside = contains (line.getStart());
  73074. const bool endInside = contains (line.getEnd());
  73075. if (startInside == endInside)
  73076. {
  73077. if (keepSectionOutsidePath == startInside)
  73078. result = Line<float>();
  73079. }
  73080. else
  73081. {
  73082. PathFlatteningIterator i (*this, AffineTransform::identity);
  73083. Point<float> intersection;
  73084. while (i.next())
  73085. {
  73086. if (line.intersects (Line<float> (i.x1, i.y1, i.x2, i.y2), intersection))
  73087. {
  73088. if ((startInside && keepSectionOutsidePath) || (endInside && ! keepSectionOutsidePath))
  73089. result.setStart (intersection);
  73090. else
  73091. result.setEnd (intersection);
  73092. }
  73093. }
  73094. }
  73095. return result;
  73096. }
  73097. const Path Path::createPathWithRoundedCorners (const float cornerRadius) const
  73098. {
  73099. if (cornerRadius <= 0.01f)
  73100. return *this;
  73101. size_t indexOfPathStart = 0, indexOfPathStartThis = 0;
  73102. size_t n = 0;
  73103. bool lastWasLine = false, firstWasLine = false;
  73104. Path p;
  73105. while (n < numElements)
  73106. {
  73107. const float type = data.elements [n++];
  73108. if (type == moveMarker)
  73109. {
  73110. indexOfPathStart = p.numElements;
  73111. indexOfPathStartThis = n - 1;
  73112. const float x = data.elements [n++];
  73113. const float y = data.elements [n++];
  73114. p.startNewSubPath (x, y);
  73115. lastWasLine = false;
  73116. firstWasLine = (data.elements [n] == lineMarker);
  73117. }
  73118. else if (type == lineMarker || type == closeSubPathMarker)
  73119. {
  73120. float startX = 0, startY = 0, joinX = 0, joinY = 0, endX, endY;
  73121. if (type == lineMarker)
  73122. {
  73123. endX = data.elements [n++];
  73124. endY = data.elements [n++];
  73125. if (n > 8)
  73126. {
  73127. startX = data.elements [n - 8];
  73128. startY = data.elements [n - 7];
  73129. joinX = data.elements [n - 5];
  73130. joinY = data.elements [n - 4];
  73131. }
  73132. }
  73133. else
  73134. {
  73135. endX = data.elements [indexOfPathStartThis + 1];
  73136. endY = data.elements [indexOfPathStartThis + 2];
  73137. if (n > 6)
  73138. {
  73139. startX = data.elements [n - 6];
  73140. startY = data.elements [n - 5];
  73141. joinX = data.elements [n - 3];
  73142. joinY = data.elements [n - 2];
  73143. }
  73144. }
  73145. if (lastWasLine)
  73146. {
  73147. const double len1 = juce_hypot (startX - joinX,
  73148. startY - joinY);
  73149. if (len1 > 0)
  73150. {
  73151. const double propNeeded = jmin (0.5, cornerRadius / len1);
  73152. p.data.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  73153. p.data.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  73154. }
  73155. const double len2 = juce_hypot (endX - joinX,
  73156. endY - joinY);
  73157. if (len2 > 0)
  73158. {
  73159. const double propNeeded = jmin (0.5, cornerRadius / len2);
  73160. p.quadraticTo (joinX, joinY,
  73161. (float) (joinX + (endX - joinX) * propNeeded),
  73162. (float) (joinY + (endY - joinY) * propNeeded));
  73163. }
  73164. p.lineTo (endX, endY);
  73165. }
  73166. else if (type == lineMarker)
  73167. {
  73168. p.lineTo (endX, endY);
  73169. lastWasLine = true;
  73170. }
  73171. if (type == closeSubPathMarker)
  73172. {
  73173. if (firstWasLine)
  73174. {
  73175. startX = data.elements [n - 3];
  73176. startY = data.elements [n - 2];
  73177. joinX = endX;
  73178. joinY = endY;
  73179. endX = data.elements [indexOfPathStartThis + 4];
  73180. endY = data.elements [indexOfPathStartThis + 5];
  73181. const double len1 = juce_hypot (startX - joinX,
  73182. startY - joinY);
  73183. if (len1 > 0)
  73184. {
  73185. const double propNeeded = jmin (0.5, cornerRadius / len1);
  73186. p.data.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  73187. p.data.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  73188. }
  73189. const double len2 = juce_hypot (endX - joinX,
  73190. endY - joinY);
  73191. if (len2 > 0)
  73192. {
  73193. const double propNeeded = jmin (0.5, cornerRadius / len2);
  73194. endX = (float) (joinX + (endX - joinX) * propNeeded);
  73195. endY = (float) (joinY + (endY - joinY) * propNeeded);
  73196. p.quadraticTo (joinX, joinY, endX, endY);
  73197. p.data.elements [indexOfPathStart + 1] = endX;
  73198. p.data.elements [indexOfPathStart + 2] = endY;
  73199. }
  73200. }
  73201. p.closeSubPath();
  73202. }
  73203. }
  73204. else if (type == quadMarker)
  73205. {
  73206. lastWasLine = false;
  73207. const float x1 = data.elements [n++];
  73208. const float y1 = data.elements [n++];
  73209. const float x2 = data.elements [n++];
  73210. const float y2 = data.elements [n++];
  73211. p.quadraticTo (x1, y1, x2, y2);
  73212. }
  73213. else if (type == cubicMarker)
  73214. {
  73215. lastWasLine = false;
  73216. const float x1 = data.elements [n++];
  73217. const float y1 = data.elements [n++];
  73218. const float x2 = data.elements [n++];
  73219. const float y2 = data.elements [n++];
  73220. const float x3 = data.elements [n++];
  73221. const float y3 = data.elements [n++];
  73222. p.cubicTo (x1, y1, x2, y2, x3, y3);
  73223. }
  73224. }
  73225. return p;
  73226. }
  73227. void Path::loadPathFromStream (InputStream& source)
  73228. {
  73229. while (! source.isExhausted())
  73230. {
  73231. switch (source.readByte())
  73232. {
  73233. case 'm':
  73234. {
  73235. const float x = source.readFloat();
  73236. const float y = source.readFloat();
  73237. startNewSubPath (x, y);
  73238. break;
  73239. }
  73240. case 'l':
  73241. {
  73242. const float x = source.readFloat();
  73243. const float y = source.readFloat();
  73244. lineTo (x, y);
  73245. break;
  73246. }
  73247. case 'q':
  73248. {
  73249. const float x1 = source.readFloat();
  73250. const float y1 = source.readFloat();
  73251. const float x2 = source.readFloat();
  73252. const float y2 = source.readFloat();
  73253. quadraticTo (x1, y1, x2, y2);
  73254. break;
  73255. }
  73256. case 'b':
  73257. {
  73258. const float x1 = source.readFloat();
  73259. const float y1 = source.readFloat();
  73260. const float x2 = source.readFloat();
  73261. const float y2 = source.readFloat();
  73262. const float x3 = source.readFloat();
  73263. const float y3 = source.readFloat();
  73264. cubicTo (x1, y1, x2, y2, x3, y3);
  73265. break;
  73266. }
  73267. case 'c':
  73268. closeSubPath();
  73269. break;
  73270. case 'n':
  73271. useNonZeroWinding = true;
  73272. break;
  73273. case 'z':
  73274. useNonZeroWinding = false;
  73275. break;
  73276. case 'e':
  73277. return; // end of path marker
  73278. default:
  73279. jassertfalse; // illegal char in the stream
  73280. break;
  73281. }
  73282. }
  73283. }
  73284. void Path::loadPathFromData (const void* const pathData, const int numberOfBytes)
  73285. {
  73286. MemoryInputStream in (pathData, numberOfBytes, false);
  73287. loadPathFromStream (in);
  73288. }
  73289. void Path::writePathToStream (OutputStream& dest) const
  73290. {
  73291. dest.writeByte (useNonZeroWinding ? 'n' : 'z');
  73292. size_t i = 0;
  73293. while (i < numElements)
  73294. {
  73295. const float type = data.elements [i++];
  73296. if (type == moveMarker)
  73297. {
  73298. dest.writeByte ('m');
  73299. dest.writeFloat (data.elements [i++]);
  73300. dest.writeFloat (data.elements [i++]);
  73301. }
  73302. else if (type == lineMarker)
  73303. {
  73304. dest.writeByte ('l');
  73305. dest.writeFloat (data.elements [i++]);
  73306. dest.writeFloat (data.elements [i++]);
  73307. }
  73308. else if (type == quadMarker)
  73309. {
  73310. dest.writeByte ('q');
  73311. dest.writeFloat (data.elements [i++]);
  73312. dest.writeFloat (data.elements [i++]);
  73313. dest.writeFloat (data.elements [i++]);
  73314. dest.writeFloat (data.elements [i++]);
  73315. }
  73316. else if (type == cubicMarker)
  73317. {
  73318. dest.writeByte ('b');
  73319. dest.writeFloat (data.elements [i++]);
  73320. dest.writeFloat (data.elements [i++]);
  73321. dest.writeFloat (data.elements [i++]);
  73322. dest.writeFloat (data.elements [i++]);
  73323. dest.writeFloat (data.elements [i++]);
  73324. dest.writeFloat (data.elements [i++]);
  73325. }
  73326. else if (type == closeSubPathMarker)
  73327. {
  73328. dest.writeByte ('c');
  73329. }
  73330. }
  73331. dest.writeByte ('e'); // marks the end-of-path
  73332. }
  73333. const String Path::toString() const
  73334. {
  73335. MemoryOutputStream s (2048, 2048);
  73336. if (! useNonZeroWinding)
  73337. s << 'a';
  73338. size_t i = 0;
  73339. float lastMarker = 0.0f;
  73340. while (i < numElements)
  73341. {
  73342. const float marker = data.elements [i++];
  73343. char markerChar = 0;
  73344. int numCoords = 0;
  73345. if (marker == moveMarker)
  73346. {
  73347. markerChar = 'm';
  73348. numCoords = 2;
  73349. }
  73350. else if (marker == lineMarker)
  73351. {
  73352. markerChar = 'l';
  73353. numCoords = 2;
  73354. }
  73355. else if (marker == quadMarker)
  73356. {
  73357. markerChar = 'q';
  73358. numCoords = 4;
  73359. }
  73360. else if (marker == cubicMarker)
  73361. {
  73362. markerChar = 'c';
  73363. numCoords = 6;
  73364. }
  73365. else
  73366. {
  73367. jassert (marker == closeSubPathMarker);
  73368. markerChar = 'z';
  73369. }
  73370. if (marker != lastMarker)
  73371. {
  73372. if (s.getDataSize() != 0)
  73373. s << ' ';
  73374. s << markerChar;
  73375. lastMarker = marker;
  73376. }
  73377. while (--numCoords >= 0 && i < numElements)
  73378. {
  73379. String coord (data.elements [i++], 3);
  73380. while (coord.endsWithChar ('0') && coord != "0")
  73381. coord = coord.dropLastCharacters (1);
  73382. if (coord.endsWithChar ('.'))
  73383. coord = coord.dropLastCharacters (1);
  73384. if (s.getDataSize() != 0)
  73385. s << ' ';
  73386. s << coord;
  73387. }
  73388. }
  73389. return s.toUTF8();
  73390. }
  73391. void Path::restoreFromString (const String& stringVersion)
  73392. {
  73393. clear();
  73394. setUsingNonZeroWinding (true);
  73395. const juce_wchar* t = stringVersion;
  73396. juce_wchar marker = 'm';
  73397. int numValues = 2;
  73398. float values [6];
  73399. for (;;)
  73400. {
  73401. const String token (PathHelpers::nextToken (t));
  73402. const juce_wchar firstChar = token[0];
  73403. int startNum = 0;
  73404. if (firstChar == 0)
  73405. break;
  73406. if (firstChar == 'm' || firstChar == 'l')
  73407. {
  73408. marker = firstChar;
  73409. numValues = 2;
  73410. }
  73411. else if (firstChar == 'q')
  73412. {
  73413. marker = firstChar;
  73414. numValues = 4;
  73415. }
  73416. else if (firstChar == 'c')
  73417. {
  73418. marker = firstChar;
  73419. numValues = 6;
  73420. }
  73421. else if (firstChar == 'z')
  73422. {
  73423. marker = firstChar;
  73424. numValues = 0;
  73425. }
  73426. else if (firstChar == 'a')
  73427. {
  73428. setUsingNonZeroWinding (false);
  73429. continue;
  73430. }
  73431. else
  73432. {
  73433. ++startNum;
  73434. values [0] = token.getFloatValue();
  73435. }
  73436. for (int i = startNum; i < numValues; ++i)
  73437. values [i] = PathHelpers::nextToken (t).getFloatValue();
  73438. switch (marker)
  73439. {
  73440. case 'm':
  73441. startNewSubPath (values[0], values[1]);
  73442. break;
  73443. case 'l':
  73444. lineTo (values[0], values[1]);
  73445. break;
  73446. case 'q':
  73447. quadraticTo (values[0], values[1],
  73448. values[2], values[3]);
  73449. break;
  73450. case 'c':
  73451. cubicTo (values[0], values[1],
  73452. values[2], values[3],
  73453. values[4], values[5]);
  73454. break;
  73455. case 'z':
  73456. closeSubPath();
  73457. break;
  73458. default:
  73459. jassertfalse; // illegal string format?
  73460. break;
  73461. }
  73462. }
  73463. }
  73464. Path::Iterator::Iterator (const Path& path_)
  73465. : path (path_),
  73466. index (0)
  73467. {
  73468. }
  73469. Path::Iterator::~Iterator()
  73470. {
  73471. }
  73472. bool Path::Iterator::next()
  73473. {
  73474. const float* const elements = path.data.elements;
  73475. if (index < path.numElements)
  73476. {
  73477. const float type = elements [index++];
  73478. if (type == moveMarker)
  73479. {
  73480. elementType = startNewSubPath;
  73481. x1 = elements [index++];
  73482. y1 = elements [index++];
  73483. }
  73484. else if (type == lineMarker)
  73485. {
  73486. elementType = lineTo;
  73487. x1 = elements [index++];
  73488. y1 = elements [index++];
  73489. }
  73490. else if (type == quadMarker)
  73491. {
  73492. elementType = quadraticTo;
  73493. x1 = elements [index++];
  73494. y1 = elements [index++];
  73495. x2 = elements [index++];
  73496. y2 = elements [index++];
  73497. }
  73498. else if (type == cubicMarker)
  73499. {
  73500. elementType = cubicTo;
  73501. x1 = elements [index++];
  73502. y1 = elements [index++];
  73503. x2 = elements [index++];
  73504. y2 = elements [index++];
  73505. x3 = elements [index++];
  73506. y3 = elements [index++];
  73507. }
  73508. else if (type == closeSubPathMarker)
  73509. {
  73510. elementType = closePath;
  73511. }
  73512. return true;
  73513. }
  73514. return false;
  73515. }
  73516. END_JUCE_NAMESPACE
  73517. /*** End of inlined file: juce_Path.cpp ***/
  73518. /*** Start of inlined file: juce_PathIterator.cpp ***/
  73519. BEGIN_JUCE_NAMESPACE
  73520. #if JUCE_MSVC && JUCE_DEBUG
  73521. #pragma optimize ("t", on)
  73522. #endif
  73523. PathFlatteningIterator::PathFlatteningIterator (const Path& path_,
  73524. const AffineTransform& transform_,
  73525. float tolerence_)
  73526. : x2 (0),
  73527. y2 (0),
  73528. closesSubPath (false),
  73529. subPathIndex (-1),
  73530. path (path_),
  73531. transform (transform_),
  73532. points (path_.data.elements),
  73533. tolerence (tolerence_ * tolerence_),
  73534. subPathCloseX (0),
  73535. subPathCloseY (0),
  73536. isIdentityTransform (transform_.isIdentity()),
  73537. stackBase (32),
  73538. index (0),
  73539. stackSize (32)
  73540. {
  73541. stackPos = stackBase;
  73542. }
  73543. PathFlatteningIterator::~PathFlatteningIterator()
  73544. {
  73545. }
  73546. bool PathFlatteningIterator::next()
  73547. {
  73548. x1 = x2;
  73549. y1 = y2;
  73550. float x3 = 0;
  73551. float y3 = 0;
  73552. float x4 = 0;
  73553. float y4 = 0;
  73554. float type;
  73555. for (;;)
  73556. {
  73557. if (stackPos == stackBase)
  73558. {
  73559. if (index >= path.numElements)
  73560. {
  73561. return false;
  73562. }
  73563. else
  73564. {
  73565. type = points [index++];
  73566. if (type != Path::closeSubPathMarker)
  73567. {
  73568. x2 = points [index++];
  73569. y2 = points [index++];
  73570. if (! isIdentityTransform)
  73571. transform.transformPoint (x2, y2);
  73572. if (type == Path::quadMarker)
  73573. {
  73574. x3 = points [index++];
  73575. y3 = points [index++];
  73576. if (! isIdentityTransform)
  73577. transform.transformPoint (x3, y3);
  73578. }
  73579. else if (type == Path::cubicMarker)
  73580. {
  73581. x3 = points [index++];
  73582. y3 = points [index++];
  73583. x4 = points [index++];
  73584. y4 = points [index++];
  73585. if (! isIdentityTransform)
  73586. {
  73587. transform.transformPoint (x3, y3);
  73588. transform.transformPoint (x4, y4);
  73589. }
  73590. }
  73591. }
  73592. }
  73593. }
  73594. else
  73595. {
  73596. type = *--stackPos;
  73597. if (type != Path::closeSubPathMarker)
  73598. {
  73599. x2 = *--stackPos;
  73600. y2 = *--stackPos;
  73601. if (type == Path::quadMarker)
  73602. {
  73603. x3 = *--stackPos;
  73604. y3 = *--stackPos;
  73605. }
  73606. else if (type == Path::cubicMarker)
  73607. {
  73608. x3 = *--stackPos;
  73609. y3 = *--stackPos;
  73610. x4 = *--stackPos;
  73611. y4 = *--stackPos;
  73612. }
  73613. }
  73614. }
  73615. if (type == Path::lineMarker)
  73616. {
  73617. ++subPathIndex;
  73618. closesSubPath = (stackPos == stackBase)
  73619. && (index < path.numElements)
  73620. && (points [index] == Path::closeSubPathMarker)
  73621. && x2 == subPathCloseX
  73622. && y2 == subPathCloseY;
  73623. return true;
  73624. }
  73625. else if (type == Path::quadMarker)
  73626. {
  73627. const size_t offset = (size_t) (stackPos - stackBase);
  73628. if (offset >= stackSize - 10)
  73629. {
  73630. stackSize <<= 1;
  73631. stackBase.realloc (stackSize);
  73632. stackPos = stackBase + offset;
  73633. }
  73634. const float dx1 = x1 - x2;
  73635. const float dy1 = y1 - y2;
  73636. const float dx2 = x2 - x3;
  73637. const float dy2 = y2 - y3;
  73638. const float m1x = (x1 + x2) * 0.5f;
  73639. const float m1y = (y1 + y2) * 0.5f;
  73640. const float m2x = (x2 + x3) * 0.5f;
  73641. const float m2y = (y2 + y3) * 0.5f;
  73642. const float m3x = (m1x + m2x) * 0.5f;
  73643. const float m3y = (m1y + m2y) * 0.5f;
  73644. if (dx1*dx1 + dy1*dy1 + dx2*dx2 + dy2*dy2 > tolerence)
  73645. {
  73646. *stackPos++ = y3;
  73647. *stackPos++ = x3;
  73648. *stackPos++ = m2y;
  73649. *stackPos++ = m2x;
  73650. *stackPos++ = Path::quadMarker;
  73651. *stackPos++ = m3y;
  73652. *stackPos++ = m3x;
  73653. *stackPos++ = m1y;
  73654. *stackPos++ = m1x;
  73655. *stackPos++ = Path::quadMarker;
  73656. }
  73657. else
  73658. {
  73659. *stackPos++ = y3;
  73660. *stackPos++ = x3;
  73661. *stackPos++ = Path::lineMarker;
  73662. *stackPos++ = m3y;
  73663. *stackPos++ = m3x;
  73664. *stackPos++ = Path::lineMarker;
  73665. }
  73666. jassert (stackPos < stackBase + stackSize);
  73667. }
  73668. else if (type == Path::cubicMarker)
  73669. {
  73670. const size_t offset = (size_t) (stackPos - stackBase);
  73671. if (offset >= stackSize - 16)
  73672. {
  73673. stackSize <<= 1;
  73674. stackBase.realloc (stackSize);
  73675. stackPos = stackBase + offset;
  73676. }
  73677. const float dx1 = x1 - x2;
  73678. const float dy1 = y1 - y2;
  73679. const float dx2 = x2 - x3;
  73680. const float dy2 = y2 - y3;
  73681. const float dx3 = x3 - x4;
  73682. const float dy3 = y3 - y4;
  73683. const float m1x = (x1 + x2) * 0.5f;
  73684. const float m1y = (y1 + y2) * 0.5f;
  73685. const float m2x = (x3 + x2) * 0.5f;
  73686. const float m2y = (y3 + y2) * 0.5f;
  73687. const float m3x = (x3 + x4) * 0.5f;
  73688. const float m3y = (y3 + y4) * 0.5f;
  73689. const float m4x = (m1x + m2x) * 0.5f;
  73690. const float m4y = (m1y + m2y) * 0.5f;
  73691. const float m5x = (m3x + m2x) * 0.5f;
  73692. const float m5y = (m3y + m2y) * 0.5f;
  73693. if (dx1*dx1 + dy1*dy1 + dx2*dx2
  73694. + dy2*dy2 + dx3*dx3 + dy3*dy3 > tolerence)
  73695. {
  73696. *stackPos++ = y4;
  73697. *stackPos++ = x4;
  73698. *stackPos++ = m3y;
  73699. *stackPos++ = m3x;
  73700. *stackPos++ = m5y;
  73701. *stackPos++ = m5x;
  73702. *stackPos++ = Path::cubicMarker;
  73703. *stackPos++ = (m4y + m5y) * 0.5f;
  73704. *stackPos++ = (m4x + m5x) * 0.5f;
  73705. *stackPos++ = m4y;
  73706. *stackPos++ = m4x;
  73707. *stackPos++ = m1y;
  73708. *stackPos++ = m1x;
  73709. *stackPos++ = Path::cubicMarker;
  73710. }
  73711. else
  73712. {
  73713. *stackPos++ = y4;
  73714. *stackPos++ = x4;
  73715. *stackPos++ = Path::lineMarker;
  73716. *stackPos++ = m5y;
  73717. *stackPos++ = m5x;
  73718. *stackPos++ = Path::lineMarker;
  73719. *stackPos++ = m4y;
  73720. *stackPos++ = m4x;
  73721. *stackPos++ = Path::lineMarker;
  73722. }
  73723. }
  73724. else if (type == Path::closeSubPathMarker)
  73725. {
  73726. if (x2 != subPathCloseX || y2 != subPathCloseY)
  73727. {
  73728. x1 = x2;
  73729. y1 = y2;
  73730. x2 = subPathCloseX;
  73731. y2 = subPathCloseY;
  73732. closesSubPath = true;
  73733. return true;
  73734. }
  73735. }
  73736. else
  73737. {
  73738. jassert (type == Path::moveMarker);
  73739. subPathIndex = -1;
  73740. subPathCloseX = x1 = x2;
  73741. subPathCloseY = y1 = y2;
  73742. }
  73743. }
  73744. }
  73745. #if JUCE_MSVC && JUCE_DEBUG
  73746. #pragma optimize ("", on) // resets optimisations to the project defaults
  73747. #endif
  73748. END_JUCE_NAMESPACE
  73749. /*** End of inlined file: juce_PathIterator.cpp ***/
  73750. /*** Start of inlined file: juce_PathStrokeType.cpp ***/
  73751. BEGIN_JUCE_NAMESPACE
  73752. PathStrokeType::PathStrokeType (const float strokeThickness,
  73753. const JointStyle jointStyle_,
  73754. const EndCapStyle endStyle_) throw()
  73755. : thickness (strokeThickness),
  73756. jointStyle (jointStyle_),
  73757. endStyle (endStyle_)
  73758. {
  73759. }
  73760. PathStrokeType::PathStrokeType (const PathStrokeType& other) throw()
  73761. : thickness (other.thickness),
  73762. jointStyle (other.jointStyle),
  73763. endStyle (other.endStyle)
  73764. {
  73765. }
  73766. PathStrokeType& PathStrokeType::operator= (const PathStrokeType& other) throw()
  73767. {
  73768. thickness = other.thickness;
  73769. jointStyle = other.jointStyle;
  73770. endStyle = other.endStyle;
  73771. return *this;
  73772. }
  73773. PathStrokeType::~PathStrokeType() throw()
  73774. {
  73775. }
  73776. bool PathStrokeType::operator== (const PathStrokeType& other) const throw()
  73777. {
  73778. return thickness == other.thickness
  73779. && jointStyle == other.jointStyle
  73780. && endStyle == other.endStyle;
  73781. }
  73782. bool PathStrokeType::operator!= (const PathStrokeType& other) const throw()
  73783. {
  73784. return ! operator== (other);
  73785. }
  73786. namespace PathStrokeHelpers
  73787. {
  73788. static bool lineIntersection (const float x1, const float y1,
  73789. const float x2, const float y2,
  73790. const float x3, const float y3,
  73791. const float x4, const float y4,
  73792. float& intersectionX,
  73793. float& intersectionY,
  73794. float& distanceBeyondLine1EndSquared) throw()
  73795. {
  73796. if (x2 != x3 || y2 != y3)
  73797. {
  73798. const float dx1 = x2 - x1;
  73799. const float dy1 = y2 - y1;
  73800. const float dx2 = x4 - x3;
  73801. const float dy2 = y4 - y3;
  73802. const float divisor = dx1 * dy2 - dx2 * dy1;
  73803. if (divisor == 0)
  73804. {
  73805. if (! ((dx1 == 0 && dy1 == 0) || (dx2 == 0 && dy2 == 0)))
  73806. {
  73807. if (dy1 == 0 && dy2 != 0)
  73808. {
  73809. const float along = (y1 - y3) / dy2;
  73810. intersectionX = x3 + along * dx2;
  73811. intersectionY = y1;
  73812. distanceBeyondLine1EndSquared = intersectionX - x2;
  73813. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  73814. if ((x2 > x1) == (intersectionX < x2))
  73815. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  73816. return along >= 0 && along <= 1.0f;
  73817. }
  73818. else if (dy2 == 0 && dy1 != 0)
  73819. {
  73820. const float along = (y3 - y1) / dy1;
  73821. intersectionX = x1 + along * dx1;
  73822. intersectionY = y3;
  73823. distanceBeyondLine1EndSquared = (along - 1.0f) * dx1;
  73824. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  73825. if (along < 1.0f)
  73826. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  73827. return along >= 0 && along <= 1.0f;
  73828. }
  73829. else if (dx1 == 0 && dx2 != 0)
  73830. {
  73831. const float along = (x1 - x3) / dx2;
  73832. intersectionX = x1;
  73833. intersectionY = y3 + along * dy2;
  73834. distanceBeyondLine1EndSquared = intersectionY - y2;
  73835. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  73836. if ((y2 > y1) == (intersectionY < y2))
  73837. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  73838. return along >= 0 && along <= 1.0f;
  73839. }
  73840. else if (dx2 == 0 && dx1 != 0)
  73841. {
  73842. const float along = (x3 - x1) / dx1;
  73843. intersectionX = x3;
  73844. intersectionY = y1 + along * dy1;
  73845. distanceBeyondLine1EndSquared = (along - 1.0f) * dy1;
  73846. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  73847. if (along < 1.0f)
  73848. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  73849. return along >= 0 && along <= 1.0f;
  73850. }
  73851. }
  73852. intersectionX = 0.5f * (x2 + x3);
  73853. intersectionY = 0.5f * (y2 + y3);
  73854. distanceBeyondLine1EndSquared = 0.0f;
  73855. return false;
  73856. }
  73857. else
  73858. {
  73859. const float along1 = ((y1 - y3) * dx2 - (x1 - x3) * dy2) / divisor;
  73860. intersectionX = x1 + along1 * dx1;
  73861. intersectionY = y1 + along1 * dy1;
  73862. if (along1 >= 0 && along1 <= 1.0f)
  73863. {
  73864. const float along2 = ((y1 - y3) * dx1 - (x1 - x3) * dy1);
  73865. if (along2 >= 0 && along2 <= divisor)
  73866. {
  73867. distanceBeyondLine1EndSquared = 0.0f;
  73868. return true;
  73869. }
  73870. }
  73871. distanceBeyondLine1EndSquared = along1 - 1.0f;
  73872. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  73873. distanceBeyondLine1EndSquared *= (dx1 * dx1 + dy1 * dy1);
  73874. if (along1 < 1.0f)
  73875. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  73876. return false;
  73877. }
  73878. }
  73879. intersectionX = x2;
  73880. intersectionY = y2;
  73881. distanceBeyondLine1EndSquared = 0.0f;
  73882. return true;
  73883. }
  73884. static void addEdgeAndJoint (Path& destPath,
  73885. const PathStrokeType::JointStyle style,
  73886. const float maxMiterExtensionSquared, const float width,
  73887. const float x1, const float y1,
  73888. const float x2, const float y2,
  73889. const float x3, const float y3,
  73890. const float x4, const float y4,
  73891. const float midX, const float midY)
  73892. {
  73893. if (style == PathStrokeType::beveled
  73894. || (x3 == x4 && y3 == y4)
  73895. || (x1 == x2 && y1 == y2))
  73896. {
  73897. destPath.lineTo (x2, y2);
  73898. destPath.lineTo (x3, y3);
  73899. }
  73900. else
  73901. {
  73902. float jx, jy, distanceBeyondLine1EndSquared;
  73903. // if they intersect, use this point..
  73904. if (lineIntersection (x1, y1, x2, y2,
  73905. x3, y3, x4, y4,
  73906. jx, jy, distanceBeyondLine1EndSquared))
  73907. {
  73908. destPath.lineTo (jx, jy);
  73909. }
  73910. else
  73911. {
  73912. if (style == PathStrokeType::mitered)
  73913. {
  73914. if (distanceBeyondLine1EndSquared < maxMiterExtensionSquared
  73915. && distanceBeyondLine1EndSquared > 0.0f)
  73916. {
  73917. destPath.lineTo (jx, jy);
  73918. }
  73919. else
  73920. {
  73921. // the end sticks out too far, so just use a blunt joint
  73922. destPath.lineTo (x2, y2);
  73923. destPath.lineTo (x3, y3);
  73924. }
  73925. }
  73926. else
  73927. {
  73928. // curved joints
  73929. float angle1 = std::atan2 (x2 - midX, y2 - midY);
  73930. float angle2 = std::atan2 (x3 - midX, y3 - midY);
  73931. const float angleIncrement = 0.1f;
  73932. destPath.lineTo (x2, y2);
  73933. if (std::abs (angle1 - angle2) > angleIncrement)
  73934. {
  73935. if (angle2 > angle1 + float_Pi
  73936. || (angle2 < angle1 && angle2 >= angle1 - float_Pi))
  73937. {
  73938. if (angle2 > angle1)
  73939. angle2 -= float_Pi * 2.0f;
  73940. jassert (angle1 <= angle2 + float_Pi);
  73941. angle1 -= angleIncrement;
  73942. while (angle1 > angle2)
  73943. {
  73944. destPath.lineTo (midX + width * std::sin (angle1),
  73945. midY + width * std::cos (angle1));
  73946. angle1 -= angleIncrement;
  73947. }
  73948. }
  73949. else
  73950. {
  73951. if (angle1 > angle2)
  73952. angle1 -= float_Pi * 2.0f;
  73953. jassert (angle1 >= angle2 - float_Pi);
  73954. angle1 += angleIncrement;
  73955. while (angle1 < angle2)
  73956. {
  73957. destPath.lineTo (midX + width * std::sin (angle1),
  73958. midY + width * std::cos (angle1));
  73959. angle1 += angleIncrement;
  73960. }
  73961. }
  73962. }
  73963. destPath.lineTo (x3, y3);
  73964. }
  73965. }
  73966. }
  73967. }
  73968. static void addLineEnd (Path& destPath,
  73969. const PathStrokeType::EndCapStyle style,
  73970. const float x1, const float y1,
  73971. const float x2, const float y2,
  73972. const float width)
  73973. {
  73974. if (style == PathStrokeType::butt)
  73975. {
  73976. destPath.lineTo (x2, y2);
  73977. }
  73978. else
  73979. {
  73980. float offx1, offy1, offx2, offy2;
  73981. float dx = x2 - x1;
  73982. float dy = y2 - y1;
  73983. const float len = juce_hypotf (dx, dy);
  73984. if (len == 0)
  73985. {
  73986. offx1 = offx2 = x1;
  73987. offy1 = offy2 = y1;
  73988. }
  73989. else
  73990. {
  73991. const float offset = width / len;
  73992. dx *= offset;
  73993. dy *= offset;
  73994. offx1 = x1 + dy;
  73995. offy1 = y1 - dx;
  73996. offx2 = x2 + dy;
  73997. offy2 = y2 - dx;
  73998. }
  73999. if (style == PathStrokeType::square)
  74000. {
  74001. // sqaure ends
  74002. destPath.lineTo (offx1, offy1);
  74003. destPath.lineTo (offx2, offy2);
  74004. destPath.lineTo (x2, y2);
  74005. }
  74006. else
  74007. {
  74008. // rounded ends
  74009. const float midx = (offx1 + offx2) * 0.5f;
  74010. const float midy = (offy1 + offy2) * 0.5f;
  74011. destPath.cubicTo (x1 + (offx1 - x1) * 0.55f, y1 + (offy1 - y1) * 0.55f,
  74012. offx1 + (midx - offx1) * 0.45f, offy1 + (midy - offy1) * 0.45f,
  74013. midx, midy);
  74014. destPath.cubicTo (midx + (offx2 - midx) * 0.55f, midy + (offy2 - midy) * 0.55f,
  74015. offx2 + (x2 - offx2) * 0.45f, offy2 + (y2 - offy2) * 0.45f,
  74016. x2, y2);
  74017. }
  74018. }
  74019. }
  74020. struct Arrowhead
  74021. {
  74022. float startWidth, startLength;
  74023. float endWidth, endLength;
  74024. };
  74025. static void addArrowhead (Path& destPath,
  74026. const float x1, const float y1,
  74027. const float x2, const float y2,
  74028. const float tipX, const float tipY,
  74029. const float width,
  74030. const float arrowheadWidth)
  74031. {
  74032. Line<float> line (x1, y1, x2, y2);
  74033. destPath.lineTo (line.getPointAlongLine (-(arrowheadWidth / 2.0f - width), 0));
  74034. destPath.lineTo (tipX, tipY);
  74035. destPath.lineTo (line.getPointAlongLine (arrowheadWidth - (arrowheadWidth / 2.0f - width), 0));
  74036. destPath.lineTo (x2, y2);
  74037. }
  74038. struct LineSection
  74039. {
  74040. float x1, y1, x2, y2; // original line
  74041. float lx1, ly1, lx2, ly2; // the left-hand stroke
  74042. float rx1, ry1, rx2, ry2; // the right-hand stroke
  74043. };
  74044. static void shortenSubPath (Array<LineSection>& subPath, float amountAtStart, float amountAtEnd)
  74045. {
  74046. while (amountAtEnd > 0 && subPath.size() > 0)
  74047. {
  74048. LineSection& l = subPath.getReference (subPath.size() - 1);
  74049. float dx = l.rx2 - l.rx1;
  74050. float dy = l.ry2 - l.ry1;
  74051. const float len = juce_hypotf (dx, dy);
  74052. if (len <= amountAtEnd && subPath.size() > 1)
  74053. {
  74054. LineSection& prev = subPath.getReference (subPath.size() - 2);
  74055. prev.x2 = l.x2;
  74056. prev.y2 = l.y2;
  74057. subPath.removeLast();
  74058. amountAtEnd -= len;
  74059. }
  74060. else
  74061. {
  74062. const float prop = jmin (0.9999f, amountAtEnd / len);
  74063. dx *= prop;
  74064. dy *= prop;
  74065. l.rx1 += dx;
  74066. l.ry1 += dy;
  74067. l.lx2 += dx;
  74068. l.ly2 += dy;
  74069. break;
  74070. }
  74071. }
  74072. while (amountAtStart > 0 && subPath.size() > 0)
  74073. {
  74074. LineSection& l = subPath.getReference (0);
  74075. float dx = l.rx2 - l.rx1;
  74076. float dy = l.ry2 - l.ry1;
  74077. const float len = juce_hypotf (dx, dy);
  74078. if (len <= amountAtStart && subPath.size() > 1)
  74079. {
  74080. LineSection& next = subPath.getReference (1);
  74081. next.x1 = l.x1;
  74082. next.y1 = l.y1;
  74083. subPath.remove (0);
  74084. amountAtStart -= len;
  74085. }
  74086. else
  74087. {
  74088. const float prop = jmin (0.9999f, amountAtStart / len);
  74089. dx *= prop;
  74090. dy *= prop;
  74091. l.rx2 -= dx;
  74092. l.ry2 -= dy;
  74093. l.lx1 -= dx;
  74094. l.ly1 -= dy;
  74095. break;
  74096. }
  74097. }
  74098. }
  74099. static void addSubPath (Path& destPath, Array<LineSection>& subPath,
  74100. const bool isClosed, const float width, const float maxMiterExtensionSquared,
  74101. const PathStrokeType::JointStyle jointStyle, const PathStrokeType::EndCapStyle endStyle,
  74102. const Arrowhead* const arrowhead)
  74103. {
  74104. jassert (subPath.size() > 0);
  74105. if (arrowhead != 0)
  74106. shortenSubPath (subPath, arrowhead->startLength, arrowhead->endLength);
  74107. const LineSection& firstLine = subPath.getReference (0);
  74108. float lastX1 = firstLine.lx1;
  74109. float lastY1 = firstLine.ly1;
  74110. float lastX2 = firstLine.lx2;
  74111. float lastY2 = firstLine.ly2;
  74112. if (isClosed)
  74113. {
  74114. destPath.startNewSubPath (lastX1, lastY1);
  74115. }
  74116. else
  74117. {
  74118. destPath.startNewSubPath (firstLine.rx2, firstLine.ry2);
  74119. if (arrowhead != 0)
  74120. addArrowhead (destPath, firstLine.rx2, firstLine.ry2, lastX1, lastY1, firstLine.x1, firstLine.y1,
  74121. width, arrowhead->startWidth);
  74122. else
  74123. addLineEnd (destPath, endStyle, firstLine.rx2, firstLine.ry2, lastX1, lastY1, width);
  74124. }
  74125. int i;
  74126. for (i = 1; i < subPath.size(); ++i)
  74127. {
  74128. const LineSection& l = subPath.getReference (i);
  74129. addEdgeAndJoint (destPath, jointStyle,
  74130. maxMiterExtensionSquared, width,
  74131. lastX1, lastY1, lastX2, lastY2,
  74132. l.lx1, l.ly1, l.lx2, l.ly2,
  74133. l.x1, l.y1);
  74134. lastX1 = l.lx1;
  74135. lastY1 = l.ly1;
  74136. lastX2 = l.lx2;
  74137. lastY2 = l.ly2;
  74138. }
  74139. const LineSection& lastLine = subPath.getReference (subPath.size() - 1);
  74140. if (isClosed)
  74141. {
  74142. const LineSection& l = subPath.getReference (0);
  74143. addEdgeAndJoint (destPath, jointStyle,
  74144. maxMiterExtensionSquared, width,
  74145. lastX1, lastY1, lastX2, lastY2,
  74146. l.lx1, l.ly1, l.lx2, l.ly2,
  74147. l.x1, l.y1);
  74148. destPath.closeSubPath();
  74149. destPath.startNewSubPath (lastLine.rx1, lastLine.ry1);
  74150. }
  74151. else
  74152. {
  74153. destPath.lineTo (lastX2, lastY2);
  74154. if (arrowhead != 0)
  74155. addArrowhead (destPath, lastX2, lastY2, lastLine.rx1, lastLine.ry1, lastLine.x2, lastLine.y2,
  74156. width, arrowhead->endWidth);
  74157. else
  74158. addLineEnd (destPath, endStyle, lastX2, lastY2, lastLine.rx1, lastLine.ry1, width);
  74159. }
  74160. lastX1 = lastLine.rx1;
  74161. lastY1 = lastLine.ry1;
  74162. lastX2 = lastLine.rx2;
  74163. lastY2 = lastLine.ry2;
  74164. for (i = subPath.size() - 1; --i >= 0;)
  74165. {
  74166. const LineSection& l = subPath.getReference (i);
  74167. addEdgeAndJoint (destPath, jointStyle,
  74168. maxMiterExtensionSquared, width,
  74169. lastX1, lastY1, lastX2, lastY2,
  74170. l.rx1, l.ry1, l.rx2, l.ry2,
  74171. l.x2, l.y2);
  74172. lastX1 = l.rx1;
  74173. lastY1 = l.ry1;
  74174. lastX2 = l.rx2;
  74175. lastY2 = l.ry2;
  74176. }
  74177. if (isClosed)
  74178. {
  74179. addEdgeAndJoint (destPath, jointStyle,
  74180. maxMiterExtensionSquared, width,
  74181. lastX1, lastY1, lastX2, lastY2,
  74182. lastLine.rx1, lastLine.ry1, lastLine.rx2, lastLine.ry2,
  74183. lastLine.x2, lastLine.y2);
  74184. }
  74185. else
  74186. {
  74187. // do the last line
  74188. destPath.lineTo (lastX2, lastY2);
  74189. }
  74190. destPath.closeSubPath();
  74191. }
  74192. static void createStroke (const float thickness, const PathStrokeType::JointStyle jointStyle,
  74193. const PathStrokeType::EndCapStyle endStyle,
  74194. Path& destPath, const Path& source,
  74195. const AffineTransform& transform,
  74196. const float extraAccuracy, const Arrowhead* const arrowhead)
  74197. {
  74198. if (thickness <= 0)
  74199. {
  74200. destPath.clear();
  74201. return;
  74202. }
  74203. const Path* sourcePath = &source;
  74204. Path temp;
  74205. if (sourcePath == &destPath)
  74206. {
  74207. destPath.swapWithPath (temp);
  74208. sourcePath = &temp;
  74209. }
  74210. else
  74211. {
  74212. destPath.clear();
  74213. }
  74214. destPath.setUsingNonZeroWinding (true);
  74215. const float maxMiterExtensionSquared = 9.0f * thickness * thickness;
  74216. const float width = 0.5f * thickness;
  74217. // Iterate the path, creating a list of the
  74218. // left/right-hand lines along either side of it...
  74219. PathFlatteningIterator it (*sourcePath, transform, 9.0f / extraAccuracy);
  74220. Array <LineSection> subPath;
  74221. subPath.ensureStorageAllocated (512);
  74222. LineSection l;
  74223. l.x1 = 0;
  74224. l.y1 = 0;
  74225. const float minSegmentLength = 2.0f / (extraAccuracy * extraAccuracy);
  74226. while (it.next())
  74227. {
  74228. if (it.subPathIndex == 0)
  74229. {
  74230. if (subPath.size() > 0)
  74231. {
  74232. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  74233. subPath.clearQuick();
  74234. }
  74235. l.x1 = it.x1;
  74236. l.y1 = it.y1;
  74237. }
  74238. l.x2 = it.x2;
  74239. l.y2 = it.y2;
  74240. float dx = l.x2 - l.x1;
  74241. float dy = l.y2 - l.y1;
  74242. const float hypotSquared = dx*dx + dy*dy;
  74243. if (it.closesSubPath || hypotSquared > minSegmentLength || it.isLastInSubpath())
  74244. {
  74245. const float len = std::sqrt (hypotSquared);
  74246. if (len == 0)
  74247. {
  74248. l.rx1 = l.rx2 = l.lx1 = l.lx2 = l.x1;
  74249. l.ry1 = l.ry2 = l.ly1 = l.ly2 = l.y1;
  74250. }
  74251. else
  74252. {
  74253. const float offset = width / len;
  74254. dx *= offset;
  74255. dy *= offset;
  74256. l.rx2 = l.x1 - dy;
  74257. l.ry2 = l.y1 + dx;
  74258. l.lx1 = l.x1 + dy;
  74259. l.ly1 = l.y1 - dx;
  74260. l.lx2 = l.x2 + dy;
  74261. l.ly2 = l.y2 - dx;
  74262. l.rx1 = l.x2 - dy;
  74263. l.ry1 = l.y2 + dx;
  74264. }
  74265. subPath.add (l);
  74266. if (it.closesSubPath)
  74267. {
  74268. addSubPath (destPath, subPath, true, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  74269. subPath.clearQuick();
  74270. }
  74271. else
  74272. {
  74273. l.x1 = it.x2;
  74274. l.y1 = it.y2;
  74275. }
  74276. }
  74277. }
  74278. if (subPath.size() > 0)
  74279. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  74280. }
  74281. }
  74282. void PathStrokeType::createStrokedPath (Path& destPath, const Path& sourcePath,
  74283. const AffineTransform& transform, const float extraAccuracy) const
  74284. {
  74285. PathStrokeHelpers::createStroke (thickness, jointStyle, endStyle, destPath, sourcePath,
  74286. transform, extraAccuracy, 0);
  74287. }
  74288. void PathStrokeType::createDashedStroke (Path& destPath,
  74289. const Path& sourcePath,
  74290. const float* dashLengths,
  74291. int numDashLengths,
  74292. const AffineTransform& transform,
  74293. const float extraAccuracy) const
  74294. {
  74295. if (thickness <= 0)
  74296. return;
  74297. // this should really be an even number..
  74298. jassert ((numDashLengths & 1) == 0);
  74299. Path newDestPath;
  74300. PathFlatteningIterator it (sourcePath, transform, 9.0f / extraAccuracy);
  74301. bool first = true;
  74302. int dashNum = 0;
  74303. float pos = 0.0f, lineLen = 0.0f, lineEndPos = 0.0f;
  74304. float dx = 0.0f, dy = 0.0f;
  74305. for (;;)
  74306. {
  74307. const bool isSolid = ((dashNum & 1) == 0);
  74308. const float dashLen = dashLengths [dashNum++ % numDashLengths];
  74309. jassert (dashLen > 0); // must be a positive increment!
  74310. if (dashLen <= 0)
  74311. break;
  74312. pos += dashLen;
  74313. while (pos > lineEndPos)
  74314. {
  74315. if (! it.next())
  74316. {
  74317. if (isSolid && ! first)
  74318. newDestPath.lineTo (it.x2, it.y2);
  74319. createStrokedPath (destPath, newDestPath, AffineTransform::identity, extraAccuracy);
  74320. return;
  74321. }
  74322. if (isSolid && ! first)
  74323. newDestPath.lineTo (it.x1, it.y1);
  74324. else
  74325. newDestPath.startNewSubPath (it.x1, it.y1);
  74326. dx = it.x2 - it.x1;
  74327. dy = it.y2 - it.y1;
  74328. lineLen = juce_hypotf (dx, dy);
  74329. lineEndPos += lineLen;
  74330. first = it.closesSubPath;
  74331. }
  74332. const float alpha = (pos - (lineEndPos - lineLen)) / lineLen;
  74333. if (isSolid)
  74334. newDestPath.lineTo (it.x1 + dx * alpha,
  74335. it.y1 + dy * alpha);
  74336. else
  74337. newDestPath.startNewSubPath (it.x1 + dx * alpha,
  74338. it.y1 + dy * alpha);
  74339. }
  74340. }
  74341. void PathStrokeType::createStrokeWithArrowheads (Path& destPath,
  74342. const Path& sourcePath,
  74343. const float arrowheadStartWidth, const float arrowheadStartLength,
  74344. const float arrowheadEndWidth, const float arrowheadEndLength,
  74345. const AffineTransform& transform,
  74346. const float extraAccuracy) const
  74347. {
  74348. PathStrokeHelpers::Arrowhead head;
  74349. head.startWidth = arrowheadStartWidth;
  74350. head.startLength = arrowheadStartLength;
  74351. head.endWidth = arrowheadEndWidth;
  74352. head.endLength = arrowheadEndLength;
  74353. PathStrokeHelpers::createStroke (thickness, jointStyle, endStyle,
  74354. destPath, sourcePath, transform, extraAccuracy, &head);
  74355. }
  74356. END_JUCE_NAMESPACE
  74357. /*** End of inlined file: juce_PathStrokeType.cpp ***/
  74358. /*** Start of inlined file: juce_PositionedRectangle.cpp ***/
  74359. BEGIN_JUCE_NAMESPACE
  74360. PositionedRectangle::PositionedRectangle() throw()
  74361. : x (0.0),
  74362. y (0.0),
  74363. w (0.0),
  74364. h (0.0),
  74365. xMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  74366. yMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  74367. wMode (absoluteSize),
  74368. hMode (absoluteSize)
  74369. {
  74370. }
  74371. PositionedRectangle::PositionedRectangle (const PositionedRectangle& other) throw()
  74372. : x (other.x),
  74373. y (other.y),
  74374. w (other.w),
  74375. h (other.h),
  74376. xMode (other.xMode),
  74377. yMode (other.yMode),
  74378. wMode (other.wMode),
  74379. hMode (other.hMode)
  74380. {
  74381. }
  74382. PositionedRectangle& PositionedRectangle::operator= (const PositionedRectangle& other) throw()
  74383. {
  74384. x = other.x;
  74385. y = other.y;
  74386. w = other.w;
  74387. h = other.h;
  74388. xMode = other.xMode;
  74389. yMode = other.yMode;
  74390. wMode = other.wMode;
  74391. hMode = other.hMode;
  74392. return *this;
  74393. }
  74394. PositionedRectangle::~PositionedRectangle() throw()
  74395. {
  74396. }
  74397. bool PositionedRectangle::operator== (const PositionedRectangle& other) const throw()
  74398. {
  74399. return x == other.x
  74400. && y == other.y
  74401. && w == other.w
  74402. && h == other.h
  74403. && xMode == other.xMode
  74404. && yMode == other.yMode
  74405. && wMode == other.wMode
  74406. && hMode == other.hMode;
  74407. }
  74408. bool PositionedRectangle::operator!= (const PositionedRectangle& other) const throw()
  74409. {
  74410. return ! operator== (other);
  74411. }
  74412. PositionedRectangle::PositionedRectangle (const String& stringVersion) throw()
  74413. {
  74414. StringArray tokens;
  74415. tokens.addTokens (stringVersion, false);
  74416. decodePosString (tokens [0], xMode, x);
  74417. decodePosString (tokens [1], yMode, y);
  74418. decodeSizeString (tokens [2], wMode, w);
  74419. decodeSizeString (tokens [3], hMode, h);
  74420. }
  74421. const String PositionedRectangle::toString() const throw()
  74422. {
  74423. String s;
  74424. s.preallocateStorage (12);
  74425. addPosDescription (s, xMode, x);
  74426. s << ' ';
  74427. addPosDescription (s, yMode, y);
  74428. s << ' ';
  74429. addSizeDescription (s, wMode, w);
  74430. s << ' ';
  74431. addSizeDescription (s, hMode, h);
  74432. return s;
  74433. }
  74434. const Rectangle<int> PositionedRectangle::getRectangle (const Rectangle<int>& target) const throw()
  74435. {
  74436. jassert (! target.isEmpty());
  74437. double x_, y_, w_, h_;
  74438. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  74439. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  74440. return Rectangle<int> (roundToInt (x_), roundToInt (y_),
  74441. roundToInt (w_), roundToInt (h_));
  74442. }
  74443. void PositionedRectangle::getRectangleDouble (const Rectangle<int>& target,
  74444. double& x_, double& y_,
  74445. double& w_, double& h_) const throw()
  74446. {
  74447. jassert (! target.isEmpty());
  74448. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  74449. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  74450. }
  74451. void PositionedRectangle::applyToComponent (Component& comp) const throw()
  74452. {
  74453. comp.setBounds (getRectangle (Rectangle<int> (0, 0, comp.getParentWidth(), comp.getParentHeight())));
  74454. }
  74455. void PositionedRectangle::updateFrom (const Rectangle<int>& rectangle,
  74456. const Rectangle<int>& target) throw()
  74457. {
  74458. updatePosAndSize (x, w, rectangle.getX(), rectangle.getWidth(), xMode, wMode, target.getX(), target.getWidth());
  74459. updatePosAndSize (y, h, rectangle.getY(), rectangle.getHeight(), yMode, hMode, target.getY(), target.getHeight());
  74460. }
  74461. void PositionedRectangle::updateFromDouble (const double newX, const double newY,
  74462. const double newW, const double newH,
  74463. const Rectangle<int>& target) throw()
  74464. {
  74465. updatePosAndSize (x, w, newX, newW, xMode, wMode, target.getX(), target.getWidth());
  74466. updatePosAndSize (y, h, newY, newH, yMode, hMode, target.getY(), target.getHeight());
  74467. }
  74468. void PositionedRectangle::updateFromComponent (const Component& comp) throw()
  74469. {
  74470. if (comp.getParentComponent() == 0 && ! comp.isOnDesktop())
  74471. updateFrom (comp.getBounds(), Rectangle<int>());
  74472. else
  74473. updateFrom (comp.getBounds(), Rectangle<int> (0, 0, comp.getParentWidth(), comp.getParentHeight()));
  74474. }
  74475. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointX() const throw()
  74476. {
  74477. return (AnchorPoint) (xMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  74478. }
  74479. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeX() const throw()
  74480. {
  74481. return (PositionMode) (xMode & (absoluteFromParentTopLeft
  74482. | absoluteFromParentBottomRight
  74483. | absoluteFromParentCentre
  74484. | proportionOfParentSize));
  74485. }
  74486. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointY() const throw()
  74487. {
  74488. return (AnchorPoint) (yMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  74489. }
  74490. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeY() const throw()
  74491. {
  74492. return (PositionMode) (yMode & (absoluteFromParentTopLeft
  74493. | absoluteFromParentBottomRight
  74494. | absoluteFromParentCentre
  74495. | proportionOfParentSize));
  74496. }
  74497. PositionedRectangle::SizeMode PositionedRectangle::getWidthMode() const throw()
  74498. {
  74499. return (SizeMode) wMode;
  74500. }
  74501. PositionedRectangle::SizeMode PositionedRectangle::getHeightMode() const throw()
  74502. {
  74503. return (SizeMode) hMode;
  74504. }
  74505. void PositionedRectangle::setModes (const AnchorPoint xAnchor,
  74506. const PositionMode xMode_,
  74507. const AnchorPoint yAnchor,
  74508. const PositionMode yMode_,
  74509. const SizeMode widthMode,
  74510. const SizeMode heightMode,
  74511. const Rectangle<int>& target) throw()
  74512. {
  74513. if (xMode != (xAnchor | xMode_) || wMode != widthMode)
  74514. {
  74515. double tx, tw;
  74516. applyPosAndSize (tx, tw, x, w, xMode, wMode, target.getX(), target.getWidth());
  74517. xMode = (uint8) (xAnchor | xMode_);
  74518. wMode = (uint8) widthMode;
  74519. updatePosAndSize (x, w, tx, tw, xMode, wMode, target.getX(), target.getWidth());
  74520. }
  74521. if (yMode != (yAnchor | yMode_) || hMode != heightMode)
  74522. {
  74523. double ty, th;
  74524. applyPosAndSize (ty, th, y, h, yMode, hMode, target.getY(), target.getHeight());
  74525. yMode = (uint8) (yAnchor | yMode_);
  74526. hMode = (uint8) heightMode;
  74527. updatePosAndSize (y, h, ty, th, yMode, hMode, target.getY(), target.getHeight());
  74528. }
  74529. }
  74530. bool PositionedRectangle::isPositionAbsolute() const throw()
  74531. {
  74532. return xMode == absoluteFromParentTopLeft
  74533. && yMode == absoluteFromParentTopLeft
  74534. && wMode == absoluteSize
  74535. && hMode == absoluteSize;
  74536. }
  74537. void PositionedRectangle::addPosDescription (String& s, const uint8 mode, const double value) const throw()
  74538. {
  74539. if ((mode & proportionOfParentSize) != 0)
  74540. {
  74541. s << (roundToInt (value * 100000.0) / 1000.0) << '%';
  74542. }
  74543. else
  74544. {
  74545. s << (roundToInt (value * 100.0) / 100.0);
  74546. if ((mode & absoluteFromParentBottomRight) != 0)
  74547. s << 'R';
  74548. else if ((mode & absoluteFromParentCentre) != 0)
  74549. s << 'C';
  74550. }
  74551. if ((mode & anchorAtRightOrBottom) != 0)
  74552. s << 'r';
  74553. else if ((mode & anchorAtCentre) != 0)
  74554. s << 'c';
  74555. }
  74556. void PositionedRectangle::addSizeDescription (String& s, const uint8 mode, const double value) const throw()
  74557. {
  74558. if (mode == proportionalSize)
  74559. s << (roundToInt (value * 100000.0) / 1000.0) << '%';
  74560. else if (mode == parentSizeMinusAbsolute)
  74561. s << (roundToInt (value * 100.0) / 100.0) << 'M';
  74562. else
  74563. s << (roundToInt (value * 100.0) / 100.0);
  74564. }
  74565. void PositionedRectangle::decodePosString (const String& s, uint8& mode, double& value) throw()
  74566. {
  74567. if (s.containsChar ('r'))
  74568. mode = anchorAtRightOrBottom;
  74569. else if (s.containsChar ('c'))
  74570. mode = anchorAtCentre;
  74571. else
  74572. mode = anchorAtLeftOrTop;
  74573. if (s.containsChar ('%'))
  74574. {
  74575. mode |= proportionOfParentSize;
  74576. value = s.removeCharacters ("%rcRC").getDoubleValue() / 100.0;
  74577. }
  74578. else
  74579. {
  74580. if (s.containsChar ('R'))
  74581. mode |= absoluteFromParentBottomRight;
  74582. else if (s.containsChar ('C'))
  74583. mode |= absoluteFromParentCentre;
  74584. else
  74585. mode |= absoluteFromParentTopLeft;
  74586. value = s.removeCharacters ("rcRC").getDoubleValue();
  74587. }
  74588. }
  74589. void PositionedRectangle::decodeSizeString (const String& s, uint8& mode, double& value) throw()
  74590. {
  74591. if (s.containsChar ('%'))
  74592. {
  74593. mode = proportionalSize;
  74594. value = s.upToFirstOccurrenceOf ("%", false, false).getDoubleValue() / 100.0;
  74595. }
  74596. else if (s.containsChar ('M'))
  74597. {
  74598. mode = parentSizeMinusAbsolute;
  74599. value = s.getDoubleValue();
  74600. }
  74601. else
  74602. {
  74603. mode = absoluteSize;
  74604. value = s.getDoubleValue();
  74605. }
  74606. }
  74607. void PositionedRectangle::applyPosAndSize (double& xOut, double& wOut,
  74608. const double x_, const double w_,
  74609. const uint8 xMode_, const uint8 wMode_,
  74610. const int parentPos,
  74611. const int parentSize) const throw()
  74612. {
  74613. if (wMode_ == proportionalSize)
  74614. wOut = roundToInt (w_ * parentSize);
  74615. else if (wMode_ == parentSizeMinusAbsolute)
  74616. wOut = jmax (0, parentSize - roundToInt (w_));
  74617. else
  74618. wOut = roundToInt (w_);
  74619. if ((xMode_ & proportionOfParentSize) != 0)
  74620. xOut = parentPos + x_ * parentSize;
  74621. else if ((xMode_ & absoluteFromParentBottomRight) != 0)
  74622. xOut = (parentPos + parentSize) - x_;
  74623. else if ((xMode_ & absoluteFromParentCentre) != 0)
  74624. xOut = x_ + (parentPos + parentSize / 2);
  74625. else
  74626. xOut = x_ + parentPos;
  74627. if ((xMode_ & anchorAtRightOrBottom) != 0)
  74628. xOut -= wOut;
  74629. else if ((xMode_ & anchorAtCentre) != 0)
  74630. xOut -= wOut / 2;
  74631. }
  74632. void PositionedRectangle::updatePosAndSize (double& xOut, double& wOut,
  74633. double x_, const double w_,
  74634. const uint8 xMode_, const uint8 wMode_,
  74635. const int parentPos,
  74636. const int parentSize) const throw()
  74637. {
  74638. if (wMode_ == proportionalSize)
  74639. {
  74640. if (parentSize > 0)
  74641. wOut = w_ / parentSize;
  74642. }
  74643. else if (wMode_ == parentSizeMinusAbsolute)
  74644. wOut = parentSize - w_;
  74645. else
  74646. wOut = w_;
  74647. if ((xMode_ & anchorAtRightOrBottom) != 0)
  74648. x_ += w_;
  74649. else if ((xMode_ & anchorAtCentre) != 0)
  74650. x_ += w_ / 2;
  74651. if ((xMode_ & proportionOfParentSize) != 0)
  74652. {
  74653. if (parentSize > 0)
  74654. xOut = (x_ - parentPos) / parentSize;
  74655. }
  74656. else if ((xMode_ & absoluteFromParentBottomRight) != 0)
  74657. xOut = (parentPos + parentSize) - x_;
  74658. else if ((xMode_ & absoluteFromParentCentre) != 0)
  74659. xOut = x_ - (parentPos + parentSize / 2);
  74660. else
  74661. xOut = x_ - parentPos;
  74662. }
  74663. END_JUCE_NAMESPACE
  74664. /*** End of inlined file: juce_PositionedRectangle.cpp ***/
  74665. /*** Start of inlined file: juce_RectangleList.cpp ***/
  74666. BEGIN_JUCE_NAMESPACE
  74667. RectangleList::RectangleList() throw()
  74668. {
  74669. }
  74670. RectangleList::RectangleList (const Rectangle<int>& rect)
  74671. {
  74672. if (! rect.isEmpty())
  74673. rects.add (rect);
  74674. }
  74675. RectangleList::RectangleList (const RectangleList& other)
  74676. : rects (other.rects)
  74677. {
  74678. }
  74679. RectangleList& RectangleList::operator= (const RectangleList& other)
  74680. {
  74681. rects = other.rects;
  74682. return *this;
  74683. }
  74684. RectangleList::~RectangleList()
  74685. {
  74686. }
  74687. void RectangleList::clear()
  74688. {
  74689. rects.clearQuick();
  74690. }
  74691. const Rectangle<int> RectangleList::getRectangle (const int index) const throw()
  74692. {
  74693. if (((unsigned int) index) < (unsigned int) rects.size())
  74694. return rects.getReference (index);
  74695. return Rectangle<int>();
  74696. }
  74697. bool RectangleList::isEmpty() const throw()
  74698. {
  74699. return rects.size() == 0;
  74700. }
  74701. RectangleList::Iterator::Iterator (const RectangleList& list) throw()
  74702. : current (0),
  74703. owner (list),
  74704. index (list.rects.size())
  74705. {
  74706. }
  74707. RectangleList::Iterator::~Iterator()
  74708. {
  74709. }
  74710. bool RectangleList::Iterator::next() throw()
  74711. {
  74712. if (--index >= 0)
  74713. {
  74714. current = & (owner.rects.getReference (index));
  74715. return true;
  74716. }
  74717. return false;
  74718. }
  74719. void RectangleList::add (const Rectangle<int>& rect)
  74720. {
  74721. if (! rect.isEmpty())
  74722. {
  74723. if (rects.size() == 0)
  74724. {
  74725. rects.add (rect);
  74726. }
  74727. else
  74728. {
  74729. bool anyOverlaps = false;
  74730. int i;
  74731. for (i = rects.size(); --i >= 0;)
  74732. {
  74733. Rectangle<int>& ourRect = rects.getReference (i);
  74734. if (rect.intersects (ourRect))
  74735. {
  74736. if (rect.contains (ourRect))
  74737. rects.remove (i);
  74738. else if (! ourRect.reduceIfPartlyContainedIn (rect))
  74739. anyOverlaps = true;
  74740. }
  74741. }
  74742. if (anyOverlaps && rects.size() > 0)
  74743. {
  74744. RectangleList r (rect);
  74745. for (i = rects.size(); --i >= 0;)
  74746. {
  74747. const Rectangle<int>& ourRect = rects.getReference (i);
  74748. if (rect.intersects (ourRect))
  74749. {
  74750. r.subtract (ourRect);
  74751. if (r.rects.size() == 0)
  74752. return;
  74753. }
  74754. }
  74755. for (i = r.getNumRectangles(); --i >= 0;)
  74756. rects.add (r.rects.getReference (i));
  74757. }
  74758. else
  74759. {
  74760. rects.add (rect);
  74761. }
  74762. }
  74763. }
  74764. }
  74765. void RectangleList::addWithoutMerging (const Rectangle<int>& rect)
  74766. {
  74767. if (! rect.isEmpty())
  74768. rects.add (rect);
  74769. }
  74770. void RectangleList::add (const int x, const int y, const int w, const int h)
  74771. {
  74772. if (rects.size() == 0)
  74773. {
  74774. if (w > 0 && h > 0)
  74775. rects.add (Rectangle<int> (x, y, w, h));
  74776. }
  74777. else
  74778. {
  74779. add (Rectangle<int> (x, y, w, h));
  74780. }
  74781. }
  74782. void RectangleList::add (const RectangleList& other)
  74783. {
  74784. for (int i = 0; i < other.rects.size(); ++i)
  74785. add (other.rects.getReference (i));
  74786. }
  74787. void RectangleList::subtract (const Rectangle<int>& rect)
  74788. {
  74789. const int originalNumRects = rects.size();
  74790. if (originalNumRects > 0)
  74791. {
  74792. const int x1 = rect.x;
  74793. const int y1 = rect.y;
  74794. const int x2 = x1 + rect.w;
  74795. const int y2 = y1 + rect.h;
  74796. for (int i = getNumRectangles(); --i >= 0;)
  74797. {
  74798. Rectangle<int>& r = rects.getReference (i);
  74799. const int rx1 = r.x;
  74800. const int ry1 = r.y;
  74801. const int rx2 = rx1 + r.w;
  74802. const int ry2 = ry1 + r.h;
  74803. if (! (x2 <= rx1 || x1 >= rx2 || y2 <= ry1 || y1 >= ry2))
  74804. {
  74805. if (x1 > rx1 && x1 < rx2)
  74806. {
  74807. if (y1 <= ry1 && y2 >= ry2 && x2 >= rx2)
  74808. {
  74809. r.w = x1 - rx1;
  74810. }
  74811. else
  74812. {
  74813. r.x = x1;
  74814. r.w = rx2 - x1;
  74815. rects.insert (i + 1, Rectangle<int> (rx1, ry1, x1 - rx1, ry2 - ry1));
  74816. i += 2;
  74817. }
  74818. }
  74819. else if (x2 > rx1 && x2 < rx2)
  74820. {
  74821. r.x = x2;
  74822. r.w = rx2 - x2;
  74823. if (y1 > ry1 || y2 < ry2 || x1 > rx1)
  74824. {
  74825. rects.insert (i + 1, Rectangle<int> (rx1, ry1, x2 - rx1, ry2 - ry1));
  74826. i += 2;
  74827. }
  74828. }
  74829. else if (y1 > ry1 && y1 < ry2)
  74830. {
  74831. if (x1 <= rx1 && x2 >= rx2 && y2 >= ry2)
  74832. {
  74833. r.h = y1 - ry1;
  74834. }
  74835. else
  74836. {
  74837. r.y = y1;
  74838. r.h = ry2 - y1;
  74839. rects.insert (i + 1, Rectangle<int> (rx1, ry1, rx2 - rx1, y1 - ry1));
  74840. i += 2;
  74841. }
  74842. }
  74843. else if (y2 > ry1 && y2 < ry2)
  74844. {
  74845. r.y = y2;
  74846. r.h = ry2 - y2;
  74847. if (x1 > rx1 || x2 < rx2 || y1 > ry1)
  74848. {
  74849. rects.insert (i + 1, Rectangle<int> (rx1, ry1, rx2 - rx1, y2 - ry1));
  74850. i += 2;
  74851. }
  74852. }
  74853. else
  74854. {
  74855. rects.remove (i);
  74856. }
  74857. }
  74858. }
  74859. }
  74860. }
  74861. bool RectangleList::subtract (const RectangleList& otherList)
  74862. {
  74863. for (int i = otherList.rects.size(); --i >= 0 && rects.size() > 0;)
  74864. subtract (otherList.rects.getReference (i));
  74865. return rects.size() > 0;
  74866. }
  74867. bool RectangleList::clipTo (const Rectangle<int>& rect)
  74868. {
  74869. bool notEmpty = false;
  74870. if (rect.isEmpty())
  74871. {
  74872. clear();
  74873. }
  74874. else
  74875. {
  74876. for (int i = rects.size(); --i >= 0;)
  74877. {
  74878. Rectangle<int>& r = rects.getReference (i);
  74879. if (! rect.intersectRectangle (r.x, r.y, r.w, r.h))
  74880. rects.remove (i);
  74881. else
  74882. notEmpty = true;
  74883. }
  74884. }
  74885. return notEmpty;
  74886. }
  74887. bool RectangleList::clipTo (const RectangleList& other)
  74888. {
  74889. if (rects.size() == 0)
  74890. return false;
  74891. RectangleList result;
  74892. for (int j = 0; j < rects.size(); ++j)
  74893. {
  74894. const Rectangle<int>& rect = rects.getReference (j);
  74895. for (int i = other.rects.size(); --i >= 0;)
  74896. {
  74897. Rectangle<int> r (other.rects.getReference (i));
  74898. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  74899. result.rects.add (r);
  74900. }
  74901. }
  74902. swapWith (result);
  74903. return ! isEmpty();
  74904. }
  74905. bool RectangleList::getIntersectionWith (const Rectangle<int>& rect, RectangleList& destRegion) const
  74906. {
  74907. destRegion.clear();
  74908. if (! rect.isEmpty())
  74909. {
  74910. for (int i = rects.size(); --i >= 0;)
  74911. {
  74912. Rectangle<int> r (rects.getReference (i));
  74913. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  74914. destRegion.rects.add (r);
  74915. }
  74916. }
  74917. return destRegion.rects.size() > 0;
  74918. }
  74919. void RectangleList::swapWith (RectangleList& otherList) throw()
  74920. {
  74921. rects.swapWithArray (otherList.rects);
  74922. }
  74923. void RectangleList::consolidate()
  74924. {
  74925. int i;
  74926. for (i = 0; i < getNumRectangles() - 1; ++i)
  74927. {
  74928. Rectangle<int>& r = rects.getReference (i);
  74929. const int rx1 = r.x;
  74930. const int ry1 = r.y;
  74931. const int rx2 = rx1 + r.w;
  74932. const int ry2 = ry1 + r.h;
  74933. for (int j = rects.size(); --j > i;)
  74934. {
  74935. Rectangle<int>& r2 = rects.getReference (j);
  74936. const int jrx1 = r2.x;
  74937. const int jry1 = r2.y;
  74938. const int jrx2 = jrx1 + r2.w;
  74939. const int jry2 = jry1 + r2.h;
  74940. // if the vertical edges of any blocks are touching and their horizontals don't
  74941. // line up, split them horizontally..
  74942. if (jrx1 == rx2 || jrx2 == rx1)
  74943. {
  74944. if (jry1 > ry1 && jry1 < ry2)
  74945. {
  74946. r.h = jry1 - ry1;
  74947. rects.add (Rectangle<int> (rx1, jry1, rx2 - rx1, ry2 - jry1));
  74948. i = -1;
  74949. break;
  74950. }
  74951. if (jry2 > ry1 && jry2 < ry2)
  74952. {
  74953. r.h = jry2 - ry1;
  74954. rects.add (Rectangle<int> (rx1, jry2, rx2 - rx1, ry2 - jry2));
  74955. i = -1;
  74956. break;
  74957. }
  74958. else if (ry1 > jry1 && ry1 < jry2)
  74959. {
  74960. r2.h = ry1 - jry1;
  74961. rects.add (Rectangle<int> (jrx1, ry1, jrx2 - jrx1, jry2 - ry1));
  74962. i = -1;
  74963. break;
  74964. }
  74965. else if (ry2 > jry1 && ry2 < jry2)
  74966. {
  74967. r2.h = ry2 - jry1;
  74968. rects.add (Rectangle<int> (jrx1, ry2, jrx2 - jrx1, jry2 - ry2));
  74969. i = -1;
  74970. break;
  74971. }
  74972. }
  74973. }
  74974. }
  74975. for (i = 0; i < rects.size() - 1; ++i)
  74976. {
  74977. Rectangle<int>& r = rects.getReference (i);
  74978. for (int j = rects.size(); --j > i;)
  74979. {
  74980. if (r.enlargeIfAdjacent (rects.getReference (j)))
  74981. {
  74982. rects.remove (j);
  74983. i = -1;
  74984. break;
  74985. }
  74986. }
  74987. }
  74988. }
  74989. bool RectangleList::containsPoint (const int x, const int y) const throw()
  74990. {
  74991. for (int i = getNumRectangles(); --i >= 0;)
  74992. if (rects.getReference (i).contains (x, y))
  74993. return true;
  74994. return false;
  74995. }
  74996. bool RectangleList::containsRectangle (const Rectangle<int>& rectangleToCheck) const
  74997. {
  74998. if (rects.size() > 1)
  74999. {
  75000. RectangleList r (rectangleToCheck);
  75001. for (int i = rects.size(); --i >= 0;)
  75002. {
  75003. r.subtract (rects.getReference (i));
  75004. if (r.rects.size() == 0)
  75005. return true;
  75006. }
  75007. }
  75008. else if (rects.size() > 0)
  75009. {
  75010. return rects.getReference (0).contains (rectangleToCheck);
  75011. }
  75012. return false;
  75013. }
  75014. bool RectangleList::intersectsRectangle (const Rectangle<int>& rectangleToCheck) const throw()
  75015. {
  75016. for (int i = rects.size(); --i >= 0;)
  75017. if (rects.getReference (i).intersects (rectangleToCheck))
  75018. return true;
  75019. return false;
  75020. }
  75021. bool RectangleList::intersects (const RectangleList& other) const throw()
  75022. {
  75023. for (int i = rects.size(); --i >= 0;)
  75024. if (other.intersectsRectangle (rects.getReference (i)))
  75025. return true;
  75026. return false;
  75027. }
  75028. const Rectangle<int> RectangleList::getBounds() const throw()
  75029. {
  75030. if (rects.size() <= 1)
  75031. {
  75032. if (rects.size() == 0)
  75033. return Rectangle<int>();
  75034. else
  75035. return rects.getReference (0);
  75036. }
  75037. else
  75038. {
  75039. const Rectangle<int>& r = rects.getReference (0);
  75040. int minX = r.x;
  75041. int minY = r.y;
  75042. int maxX = minX + r.w;
  75043. int maxY = minY + r.h;
  75044. for (int i = rects.size(); --i > 0;)
  75045. {
  75046. const Rectangle<int>& r2 = rects.getReference (i);
  75047. minX = jmin (minX, r2.x);
  75048. minY = jmin (minY, r2.y);
  75049. maxX = jmax (maxX, r2.getRight());
  75050. maxY = jmax (maxY, r2.getBottom());
  75051. }
  75052. return Rectangle<int> (minX, minY, maxX - minX, maxY - minY);
  75053. }
  75054. }
  75055. void RectangleList::offsetAll (const int dx, const int dy) throw()
  75056. {
  75057. for (int i = rects.size(); --i >= 0;)
  75058. {
  75059. Rectangle<int>& r = rects.getReference (i);
  75060. r.x += dx;
  75061. r.y += dy;
  75062. }
  75063. }
  75064. const Path RectangleList::toPath() const
  75065. {
  75066. Path p;
  75067. for (int i = rects.size(); --i >= 0;)
  75068. {
  75069. const Rectangle<int>& r = rects.getReference (i);
  75070. p.addRectangle ((float) r.x,
  75071. (float) r.y,
  75072. (float) r.w,
  75073. (float) r.h);
  75074. }
  75075. return p;
  75076. }
  75077. END_JUCE_NAMESPACE
  75078. /*** End of inlined file: juce_RectangleList.cpp ***/
  75079. /*** Start of inlined file: juce_RelativeCoordinate.cpp ***/
  75080. BEGIN_JUCE_NAMESPACE
  75081. namespace RelativeCoordinateHelpers
  75082. {
  75083. static bool isOrigin (const String& name)
  75084. {
  75085. return name.isEmpty()
  75086. || name == RelativeCoordinate::Strings::parentLeft
  75087. || name == RelativeCoordinate::Strings::parentTop;
  75088. }
  75089. static const String getOriginAnchorName (const bool isHorizontal) throw()
  75090. {
  75091. return isHorizontal ? RelativeCoordinate::Strings::parentLeft
  75092. : RelativeCoordinate::Strings::parentTop;
  75093. }
  75094. static const String getExtentAnchorName (const bool isHorizontal) throw()
  75095. {
  75096. return isHorizontal ? RelativeCoordinate::Strings::parentRight
  75097. : RelativeCoordinate::Strings::parentBottom;
  75098. }
  75099. static const String getObjectName (const String& fullName)
  75100. {
  75101. return fullName.upToFirstOccurrenceOf (".", false, false);
  75102. }
  75103. static const String getEdgeName (const String& fullName)
  75104. {
  75105. return fullName.fromFirstOccurrenceOf (".", false, false);
  75106. }
  75107. static const RelativeCoordinate findCoordinate (const String& name, const RelativeCoordinate::NamedCoordinateFinder* nameFinder)
  75108. {
  75109. return nameFinder != 0 ? nameFinder->findNamedCoordinate (getObjectName (name), getEdgeName (name))
  75110. : RelativeCoordinate();
  75111. }
  75112. struct RecursionException : public std::runtime_error
  75113. {
  75114. RecursionException() : std::runtime_error ("Recursive RelativeCoordinate expression")
  75115. {
  75116. }
  75117. };
  75118. static void skipWhitespace (const String& s, int& i)
  75119. {
  75120. while (CharacterFunctions::isWhitespace (s[i]))
  75121. ++i;
  75122. }
  75123. static void skipComma (const String& s, int& i)
  75124. {
  75125. skipWhitespace (s, i);
  75126. if (s[i] == ',')
  75127. ++i;
  75128. }
  75129. static const String readAnchorName (const String& s, int& i)
  75130. {
  75131. skipWhitespace (s, i);
  75132. if (CharacterFunctions::isLetter (s[i]) || s[i] == '_')
  75133. {
  75134. int start = i;
  75135. while (CharacterFunctions::isLetterOrDigit (s[i]) || s[i] == '_' || s[i] == '.')
  75136. ++i;
  75137. return s.substring (start, i);
  75138. }
  75139. return String::empty;
  75140. }
  75141. static double readNumber (const String& s, int& i)
  75142. {
  75143. skipWhitespace (s, i);
  75144. int start = i;
  75145. if (CharacterFunctions::isDigit (s[i]) || s[i] == '.' || s[i] == '-')
  75146. ++i;
  75147. while (CharacterFunctions::isDigit (s[i]) || s[i] == '.')
  75148. ++i;
  75149. if ((s[i] == 'e' || s[i] == 'E')
  75150. && (CharacterFunctions::isDigit (s[i + 1])
  75151. || s[i + 1] == '-'
  75152. || s[i + 1] == '+'))
  75153. {
  75154. i += 2;
  75155. while (CharacterFunctions::isDigit (s[i]))
  75156. ++i;
  75157. }
  75158. const double value = s.substring (start, i).getDoubleValue();
  75159. while (CharacterFunctions::isWhitespace (s[i]) || s[i] == ',')
  75160. ++i;
  75161. return value;
  75162. }
  75163. static const RelativeCoordinate readNextCoordinate (const String& s, int& i, const bool isHorizontal)
  75164. {
  75165. String anchor1 (readAnchorName (s, i));
  75166. double value = 0;
  75167. if (anchor1.isNotEmpty())
  75168. {
  75169. skipWhitespace (s, i);
  75170. if (s[i] == '+')
  75171. value = readNumber (s, ++i);
  75172. else if (s[i] == '-')
  75173. value = -readNumber (s, ++i);
  75174. return RelativeCoordinate (value, anchor1);
  75175. }
  75176. else
  75177. {
  75178. value = readNumber (s, i);
  75179. skipWhitespace (s, i);
  75180. if (s[i] == '%')
  75181. {
  75182. value /= 100.0;
  75183. skipWhitespace (s, ++i);
  75184. String anchor2;
  75185. if (s[i] == '*')
  75186. {
  75187. anchor1 = readAnchorName (s, ++i);
  75188. if (anchor1.isEmpty())
  75189. anchor1 = getOriginAnchorName (isHorizontal);
  75190. skipWhitespace (s, i);
  75191. if (s[i] == '-' && s[i + 1] == '>')
  75192. {
  75193. i += 2;
  75194. anchor2 = readAnchorName (s, i);
  75195. }
  75196. else
  75197. {
  75198. anchor2 = anchor1;
  75199. anchor1 = getOriginAnchorName (isHorizontal);
  75200. }
  75201. }
  75202. else
  75203. {
  75204. anchor1 = getOriginAnchorName (isHorizontal);
  75205. anchor2 = getExtentAnchorName (isHorizontal);
  75206. }
  75207. return RelativeCoordinate (value, anchor1, anchor2);
  75208. }
  75209. return RelativeCoordinate (value, isHorizontal);
  75210. }
  75211. }
  75212. static const String limitedAccuracyString (const double n)
  75213. {
  75214. if (! (n < -0.001 || n > 0.001)) // to detect NaN and inf as well as for rounding
  75215. return "0";
  75216. return String (n, 3).trimCharactersAtEnd ("0").trimCharactersAtEnd (".");
  75217. }
  75218. }
  75219. const String RelativeCoordinate::Strings::parent ("parent");
  75220. const String RelativeCoordinate::Strings::left ("left");
  75221. const String RelativeCoordinate::Strings::right ("right");
  75222. const String RelativeCoordinate::Strings::top ("top");
  75223. const String RelativeCoordinate::Strings::bottom ("bottom");
  75224. const String RelativeCoordinate::Strings::parentLeft ("parent.left");
  75225. const String RelativeCoordinate::Strings::parentTop ("parent.top");
  75226. const String RelativeCoordinate::Strings::parentRight ("parent.right");
  75227. const String RelativeCoordinate::Strings::parentBottom ("parent.bottom");
  75228. RelativeCoordinate::RelativeCoordinate()
  75229. : value (0)
  75230. {
  75231. }
  75232. RelativeCoordinate::RelativeCoordinate (const double absoluteDistanceFromOrigin, const bool horizontal_)
  75233. : anchor1 (RelativeCoordinateHelpers::getOriginAnchorName (horizontal_)),
  75234. value (absoluteDistanceFromOrigin)
  75235. {
  75236. }
  75237. RelativeCoordinate::RelativeCoordinate (const double absoluteDistance, const String& source)
  75238. : anchor1 (source.trim()),
  75239. value (absoluteDistance)
  75240. {
  75241. jassert (anchor1.isNotEmpty());
  75242. }
  75243. RelativeCoordinate::RelativeCoordinate (const double relativeProportion, const String& pos1, const String& pos2)
  75244. : anchor1 (pos1.trim()),
  75245. anchor2 (pos2.trim()),
  75246. value (relativeProportion)
  75247. {
  75248. jassert (anchor1.isNotEmpty());
  75249. jassert (anchor2.isNotEmpty());
  75250. }
  75251. RelativeCoordinate::RelativeCoordinate (const String& s, const bool isHorizontal)
  75252. : value (0)
  75253. {
  75254. int i = 0;
  75255. *this = RelativeCoordinateHelpers::readNextCoordinate (s, i, isHorizontal);
  75256. }
  75257. RelativeCoordinate::~RelativeCoordinate()
  75258. {
  75259. }
  75260. bool RelativeCoordinate::operator== (const RelativeCoordinate& other) const throw()
  75261. {
  75262. return value == other.value && anchor1 == other.anchor1 && anchor2 == other.anchor2;
  75263. }
  75264. bool RelativeCoordinate::operator!= (const RelativeCoordinate& other) const throw()
  75265. {
  75266. return ! operator== (other);
  75267. }
  75268. const RelativeCoordinate RelativeCoordinate::getAnchorCoordinate1() const
  75269. {
  75270. return RelativeCoordinate (0.0, anchor1);
  75271. }
  75272. const RelativeCoordinate RelativeCoordinate::getAnchorCoordinate2() const
  75273. {
  75274. return RelativeCoordinate (0.0, anchor2);
  75275. }
  75276. double RelativeCoordinate::resolveAnchor (const String& anchorName, const NamedCoordinateFinder* nameFinder, int recursionCounter)
  75277. {
  75278. if (RelativeCoordinateHelpers::isOrigin (anchorName))
  75279. return 0.0;
  75280. return RelativeCoordinateHelpers::findCoordinate (anchorName, nameFinder).resolve (nameFinder, recursionCounter + 1);
  75281. }
  75282. double RelativeCoordinate::resolve (const NamedCoordinateFinder* nameFinder, int recursionCounter) const
  75283. {
  75284. if (recursionCounter > 150)
  75285. {
  75286. jassertfalse
  75287. throw RelativeCoordinateHelpers::RecursionException();
  75288. }
  75289. const double pos1 = resolveAnchor (anchor1, nameFinder, recursionCounter);
  75290. return isProportional() ? pos1 + (resolveAnchor (anchor2, nameFinder, recursionCounter) - pos1) * value
  75291. : pos1 + value;
  75292. }
  75293. double RelativeCoordinate::resolve (const NamedCoordinateFinder* nameFinder) const
  75294. {
  75295. try
  75296. {
  75297. return resolve (nameFinder, 0);
  75298. }
  75299. catch (RelativeCoordinateHelpers::RecursionException&)
  75300. {}
  75301. return 0.0;
  75302. }
  75303. bool RelativeCoordinate::isRecursive (const NamedCoordinateFinder* nameFinder) const
  75304. {
  75305. try
  75306. {
  75307. (void) resolve (nameFinder, 0);
  75308. }
  75309. catch (RelativeCoordinateHelpers::RecursionException&)
  75310. {
  75311. return true;
  75312. }
  75313. return false;
  75314. }
  75315. void RelativeCoordinate::moveToAbsolute (double newPos, const NamedCoordinateFinder* nameFinder)
  75316. {
  75317. try
  75318. {
  75319. const double pos1 = resolveAnchor (anchor1, nameFinder, 0);
  75320. if (isProportional())
  75321. {
  75322. const double size = resolveAnchor (anchor2, nameFinder, 0) - pos1;
  75323. if (size != 0)
  75324. value = (newPos - pos1) / size;
  75325. }
  75326. else
  75327. {
  75328. value = newPos - pos1;
  75329. }
  75330. }
  75331. catch (RelativeCoordinateHelpers::RecursionException&)
  75332. {}
  75333. }
  75334. void RelativeCoordinate::toggleProportionality (const NamedCoordinateFinder* nameFinder, bool isHorizontal)
  75335. {
  75336. const double oldValue = resolve (nameFinder);
  75337. anchor1 = RelativeCoordinateHelpers::getOriginAnchorName (isHorizontal);
  75338. anchor2 = isProportional() ? String::empty
  75339. : RelativeCoordinateHelpers::getExtentAnchorName (isHorizontal);
  75340. moveToAbsolute (oldValue, nameFinder);
  75341. }
  75342. bool RelativeCoordinate::references (const String& coordName, const NamedCoordinateFinder* nameFinder) const
  75343. {
  75344. using namespace RelativeCoordinateHelpers;
  75345. if (isOrigin (anchor1) && ! isProportional())
  75346. return isOrigin (coordName);
  75347. return anchor1 == coordName
  75348. || anchor2 == coordName
  75349. || findCoordinate (anchor1, nameFinder).references (coordName, nameFinder)
  75350. || (isProportional() && findCoordinate (anchor2, nameFinder).references (coordName, nameFinder));
  75351. }
  75352. bool RelativeCoordinate::isDynamic() const
  75353. {
  75354. return anchor2.isNotEmpty() || ! RelativeCoordinateHelpers::isOrigin (anchor1);
  75355. }
  75356. const String RelativeCoordinate::toString() const
  75357. {
  75358. using namespace RelativeCoordinateHelpers;
  75359. if (isProportional())
  75360. {
  75361. const String percent (limitedAccuracyString (value * 100.0));
  75362. if (isOrigin (anchor1))
  75363. {
  75364. if (anchor2 == "parent.right" || anchor2 == "parent.bottom")
  75365. return percent + "%";
  75366. else
  75367. return percent + "% * " + anchor2;
  75368. }
  75369. else
  75370. return percent + "% * " + anchor1 + " -> " + anchor2;
  75371. }
  75372. else
  75373. {
  75374. if (isOrigin (anchor1))
  75375. return limitedAccuracyString (value);
  75376. else if (value > 0)
  75377. return anchor1 + " + " + limitedAccuracyString (value);
  75378. else if (value < 0)
  75379. return anchor1 + " - " + limitedAccuracyString (-value);
  75380. else
  75381. return anchor1;
  75382. }
  75383. }
  75384. const double RelativeCoordinate::getEditableNumber() const
  75385. {
  75386. return isProportional() ? value * 100.0 : value;
  75387. }
  75388. void RelativeCoordinate::setEditableNumber (const double newValue)
  75389. {
  75390. value = isProportional() ? newValue / 100.0 : newValue;
  75391. }
  75392. void RelativeCoordinate::changeAnchor1 (const String& newAnchorName, const NamedCoordinateFinder* nameFinder)
  75393. {
  75394. jassert (newAnchorName.toLowerCase().containsOnly ("abcdefghijklmnopqrstuvwxyz0123456789_."));
  75395. const double oldValue = resolve (nameFinder);
  75396. anchor1 = newAnchorName;
  75397. moveToAbsolute (oldValue, nameFinder);
  75398. }
  75399. void RelativeCoordinate::changeAnchor2 (const String& newAnchorName, const NamedCoordinateFinder* nameFinder)
  75400. {
  75401. jassert (isProportional());
  75402. jassert (newAnchorName.toLowerCase().containsOnly ("abcdefghijklmnopqrstuvwxyz0123456789_."));
  75403. const double oldValue = resolve (nameFinder);
  75404. anchor2 = newAnchorName;
  75405. moveToAbsolute (oldValue, nameFinder);
  75406. }
  75407. void RelativeCoordinate::renameAnchorIfUsed (const String& oldName, const String& newName, const NamedCoordinateFinder* nameFinder)
  75408. {
  75409. using namespace RelativeCoordinateHelpers;
  75410. jassert (oldName.isNotEmpty());
  75411. jassert (newName.toLowerCase().containsOnly ("abcdefghijklmnopqrstuvwxyz0123456789_"));
  75412. if (newName.isEmpty())
  75413. {
  75414. if (getObjectName (anchor1) == oldName
  75415. || getObjectName (anchor2) == oldName)
  75416. {
  75417. value = resolve (nameFinder);
  75418. anchor1 = String::empty;
  75419. anchor2 = String::empty;
  75420. }
  75421. }
  75422. else
  75423. {
  75424. if (getObjectName (anchor1) == oldName)
  75425. anchor1 = newName + "." + getEdgeName (anchor1);
  75426. if (getObjectName (anchor2) == oldName)
  75427. anchor2 = newName + "." + getEdgeName (anchor2);
  75428. }
  75429. }
  75430. RelativePoint::RelativePoint()
  75431. : x (0, true), y (0, false)
  75432. {
  75433. }
  75434. RelativePoint::RelativePoint (const Point<float>& absolutePoint)
  75435. : x (absolutePoint.getX(), true), y (absolutePoint.getY(), false)
  75436. {
  75437. }
  75438. RelativePoint::RelativePoint (const float x_, const float y_)
  75439. : x (x_, true), y (y_, false)
  75440. {
  75441. }
  75442. RelativePoint::RelativePoint (const RelativeCoordinate& x_, const RelativeCoordinate& y_)
  75443. : x (x_), y (y_)
  75444. {
  75445. }
  75446. RelativePoint::RelativePoint (const String& s)
  75447. {
  75448. int i = 0;
  75449. x = RelativeCoordinateHelpers::readNextCoordinate (s, i, true);
  75450. RelativeCoordinateHelpers::skipComma (s, i);
  75451. y = RelativeCoordinateHelpers::readNextCoordinate (s, i, false);
  75452. }
  75453. bool RelativePoint::operator== (const RelativePoint& other) const throw()
  75454. {
  75455. return x == other.x && y == other.y;
  75456. }
  75457. bool RelativePoint::operator!= (const RelativePoint& other) const throw()
  75458. {
  75459. return ! operator== (other);
  75460. }
  75461. const Point<float> RelativePoint::resolve (const RelativeCoordinate::NamedCoordinateFinder* nameFinder) const
  75462. {
  75463. return Point<float> ((float) x.resolve (nameFinder),
  75464. (float) y.resolve (nameFinder));
  75465. }
  75466. void RelativePoint::moveToAbsolute (const Point<float>& newPos, const RelativeCoordinate::NamedCoordinateFinder* nameFinder)
  75467. {
  75468. x.moveToAbsolute (newPos.getX(), nameFinder);
  75469. y.moveToAbsolute (newPos.getY(), nameFinder);
  75470. }
  75471. const String RelativePoint::toString() const
  75472. {
  75473. return x.toString() + ", " + y.toString();
  75474. }
  75475. void RelativePoint::renameAnchorIfUsed (const String& oldName, const String& newName, const RelativeCoordinate::NamedCoordinateFinder* nameFinder)
  75476. {
  75477. x.renameAnchorIfUsed (oldName, newName, nameFinder);
  75478. y.renameAnchorIfUsed (oldName, newName, nameFinder);
  75479. }
  75480. bool RelativePoint::isDynamic() const
  75481. {
  75482. return x.isDynamic() || y.isDynamic();
  75483. }
  75484. RelativeRectangle::RelativeRectangle()
  75485. {
  75486. }
  75487. RelativeRectangle::RelativeRectangle (const RelativeCoordinate& left_, const RelativeCoordinate& right_,
  75488. const RelativeCoordinate& top_, const RelativeCoordinate& bottom_)
  75489. : left (left_), right (right_), top (top_), bottom (bottom_)
  75490. {
  75491. }
  75492. RelativeRectangle::RelativeRectangle (const Rectangle<float>& rect, const String& componentName)
  75493. : left (rect.getX(), true),
  75494. right (rect.getWidth(), componentName + "." + RelativeCoordinate::Strings::left),
  75495. top (rect.getY(), false),
  75496. bottom (rect.getHeight(), componentName + "." + RelativeCoordinate::Strings::top)
  75497. {
  75498. }
  75499. RelativeRectangle::RelativeRectangle (const String& s)
  75500. {
  75501. int i = 0;
  75502. left = RelativeCoordinateHelpers::readNextCoordinate (s, i, true);
  75503. RelativeCoordinateHelpers::skipComma (s, i);
  75504. top = RelativeCoordinateHelpers::readNextCoordinate (s, i, false);
  75505. RelativeCoordinateHelpers::skipComma (s, i);
  75506. right = RelativeCoordinateHelpers::readNextCoordinate (s, i, true);
  75507. RelativeCoordinateHelpers::skipComma (s, i);
  75508. bottom = RelativeCoordinateHelpers::readNextCoordinate (s, i, false);
  75509. }
  75510. bool RelativeRectangle::operator== (const RelativeRectangle& other) const throw()
  75511. {
  75512. return left == other.left && top == other.top && right == other.right && bottom == other.bottom;
  75513. }
  75514. bool RelativeRectangle::operator!= (const RelativeRectangle& other) const throw()
  75515. {
  75516. return ! operator== (other);
  75517. }
  75518. const Rectangle<float> RelativeRectangle::resolve (const RelativeCoordinate::NamedCoordinateFinder* nameFinder) const
  75519. {
  75520. const double l = left.resolve (nameFinder);
  75521. const double r = right.resolve (nameFinder);
  75522. const double t = top.resolve (nameFinder);
  75523. const double b = bottom.resolve (nameFinder);
  75524. return Rectangle<float> ((float) l, (float) t, (float) (r - l), (float) (b - t));
  75525. }
  75526. void RelativeRectangle::moveToAbsolute (const Rectangle<float>& newPos, const RelativeCoordinate::NamedCoordinateFinder* nameFinder)
  75527. {
  75528. left.moveToAbsolute (newPos.getX(), nameFinder);
  75529. right.moveToAbsolute (newPos.getRight(), nameFinder);
  75530. top.moveToAbsolute (newPos.getY(), nameFinder);
  75531. bottom.moveToAbsolute (newPos.getBottom(), nameFinder);
  75532. }
  75533. const String RelativeRectangle::toString() const
  75534. {
  75535. return left.toString() + ", " + top.toString() + ", " + right.toString() + ", " + bottom.toString();
  75536. }
  75537. void RelativeRectangle::renameAnchorIfUsed (const String& oldName, const String& newName,
  75538. const RelativeCoordinate::NamedCoordinateFinder* nameFinder)
  75539. {
  75540. left.renameAnchorIfUsed (oldName, newName, nameFinder);
  75541. right.renameAnchorIfUsed (oldName, newName, nameFinder);
  75542. top.renameAnchorIfUsed (oldName, newName, nameFinder);
  75543. bottom.renameAnchorIfUsed (oldName, newName, nameFinder);
  75544. }
  75545. RelativePointPath::RelativePointPath()
  75546. : usesNonZeroWinding (true),
  75547. containsDynamicPoints (false)
  75548. {
  75549. }
  75550. RelativePointPath::RelativePointPath (const RelativePointPath& other)
  75551. : usesNonZeroWinding (true),
  75552. containsDynamicPoints (false)
  75553. {
  75554. ValueTree state (DrawablePath::valueTreeType);
  75555. other.writeTo (state, 0);
  75556. parse (state);
  75557. }
  75558. RelativePointPath::RelativePointPath (const ValueTree& drawable)
  75559. : usesNonZeroWinding (true),
  75560. containsDynamicPoints (false)
  75561. {
  75562. parse (drawable);
  75563. }
  75564. RelativePointPath::RelativePointPath (const Path& path)
  75565. {
  75566. usesNonZeroWinding = path.isUsingNonZeroWinding();
  75567. Path::Iterator i (path);
  75568. while (i.next())
  75569. {
  75570. switch (i.elementType)
  75571. {
  75572. case Path::Iterator::startNewSubPath: elements.add (new StartSubPath (RelativePoint (i.x1, i.y1))); break;
  75573. case Path::Iterator::lineTo: elements.add (new LineTo (RelativePoint (i.x1, i.y1))); break;
  75574. case Path::Iterator::quadraticTo: elements.add (new QuadraticTo (RelativePoint (i.x1, i.y1), RelativePoint (i.x2, i.y2))); break;
  75575. case Path::Iterator::cubicTo: elements.add (new CubicTo (RelativePoint (i.x1, i.y1), RelativePoint (i.x2, i.y2), RelativePoint (i.x3, i.y3))); break;
  75576. case Path::Iterator::closePath: elements.add (new CloseSubPath()); break;
  75577. default: jassertfalse; break;
  75578. }
  75579. }
  75580. }
  75581. void RelativePointPath::writeTo (ValueTree state, UndoManager* undoManager) const
  75582. {
  75583. DrawablePath::ValueTreeWrapper wrapper (state);
  75584. wrapper.setUsesNonZeroWinding (usesNonZeroWinding, undoManager);
  75585. ValueTree pathTree (wrapper.getPathState());
  75586. pathTree.removeAllChildren (undoManager);
  75587. for (int i = 0; i < elements.size(); ++i)
  75588. pathTree.addChild (elements.getUnchecked(i)->createTree(), -1, undoManager);
  75589. }
  75590. void RelativePointPath::parse (const ValueTree& state)
  75591. {
  75592. DrawablePath::ValueTreeWrapper wrapper (state);
  75593. usesNonZeroWinding = wrapper.usesNonZeroWinding();
  75594. RelativePoint points[3];
  75595. const ValueTree pathTree (wrapper.getPathState());
  75596. const int num = pathTree.getNumChildren();
  75597. for (int i = 0; i < num; ++i)
  75598. {
  75599. const DrawablePath::ValueTreeWrapper::Element e (pathTree.getChild(i));
  75600. const int numCps = e.getNumControlPoints();
  75601. for (int j = 0; j < numCps; ++j)
  75602. {
  75603. points[j] = e.getControlPoint (j);
  75604. containsDynamicPoints = containsDynamicPoints || points[j].isDynamic();
  75605. }
  75606. const Identifier type (e.getType());
  75607. if (type == DrawablePath::ValueTreeWrapper::Element::startSubPathElement)
  75608. elements.add (new StartSubPath (points[0]));
  75609. else if (type == DrawablePath::ValueTreeWrapper::Element::closeSubPathElement)
  75610. elements.add (new CloseSubPath());
  75611. else if (type == DrawablePath::ValueTreeWrapper::Element::lineToElement)
  75612. elements.add (new LineTo (points[0]));
  75613. else if (type == DrawablePath::ValueTreeWrapper::Element::quadraticToElement)
  75614. elements.add (new QuadraticTo (points[0], points[1]));
  75615. else if (type == DrawablePath::ValueTreeWrapper::Element::cubicToElement)
  75616. elements.add (new CubicTo (points[0], points[1], points[2]));
  75617. else
  75618. jassertfalse;
  75619. }
  75620. }
  75621. RelativePointPath::~RelativePointPath()
  75622. {
  75623. }
  75624. void RelativePointPath::swapWith (RelativePointPath& other) throw()
  75625. {
  75626. elements.swapWithArray (other.elements);
  75627. swapVariables (usesNonZeroWinding, other.usesNonZeroWinding);
  75628. }
  75629. void RelativePointPath::createPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder)
  75630. {
  75631. for (int i = 0; i < elements.size(); ++i)
  75632. elements.getUnchecked(i)->addToPath (path, coordFinder);
  75633. }
  75634. bool RelativePointPath::containsAnyDynamicPoints() const
  75635. {
  75636. return containsDynamicPoints;
  75637. }
  75638. RelativePointPath::ElementBase::ElementBase (const ElementType type_) : type (type_)
  75639. {
  75640. }
  75641. RelativePointPath::StartSubPath::StartSubPath (const RelativePoint& pos)
  75642. : ElementBase (startSubPathElement), startPos (pos)
  75643. {
  75644. }
  75645. const ValueTree RelativePointPath::StartSubPath::createTree() const
  75646. {
  75647. ValueTree v (DrawablePath::ValueTreeWrapper::Element::startSubPathElement);
  75648. v.setProperty (DrawablePath::ValueTreeWrapper::point1, startPos.toString(), 0);
  75649. return v;
  75650. }
  75651. void RelativePointPath::StartSubPath::addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const
  75652. {
  75653. path.startNewSubPath (startPos.resolve (coordFinder));
  75654. }
  75655. RelativePoint* RelativePointPath::StartSubPath::getControlPoints (int& numPoints)
  75656. {
  75657. numPoints = 1;
  75658. return &startPos;
  75659. }
  75660. RelativePointPath::CloseSubPath::CloseSubPath()
  75661. : ElementBase (closeSubPathElement)
  75662. {
  75663. }
  75664. const ValueTree RelativePointPath::CloseSubPath::createTree() const
  75665. {
  75666. return ValueTree (DrawablePath::ValueTreeWrapper::Element::closeSubPathElement);
  75667. }
  75668. void RelativePointPath::CloseSubPath::addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder*) const
  75669. {
  75670. path.closeSubPath();
  75671. }
  75672. RelativePoint* RelativePointPath::CloseSubPath::getControlPoints (int& numPoints)
  75673. {
  75674. numPoints = 0;
  75675. return 0;
  75676. }
  75677. RelativePointPath::LineTo::LineTo (const RelativePoint& endPoint_)
  75678. : ElementBase (lineToElement), endPoint (endPoint_)
  75679. {
  75680. }
  75681. const ValueTree RelativePointPath::LineTo::createTree() const
  75682. {
  75683. ValueTree v (DrawablePath::ValueTreeWrapper::Element::lineToElement);
  75684. v.setProperty (DrawablePath::ValueTreeWrapper::point1, endPoint.toString(), 0);
  75685. return v;
  75686. }
  75687. void RelativePointPath::LineTo::addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const
  75688. {
  75689. path.lineTo (endPoint.resolve (coordFinder));
  75690. }
  75691. RelativePoint* RelativePointPath::LineTo::getControlPoints (int& numPoints)
  75692. {
  75693. numPoints = 1;
  75694. return &endPoint;
  75695. }
  75696. RelativePointPath::QuadraticTo::QuadraticTo (const RelativePoint& controlPoint, const RelativePoint& endPoint)
  75697. : ElementBase (quadraticToElement)
  75698. {
  75699. controlPoints[0] = controlPoint;
  75700. controlPoints[1] = endPoint;
  75701. }
  75702. const ValueTree RelativePointPath::QuadraticTo::createTree() const
  75703. {
  75704. ValueTree v (DrawablePath::ValueTreeWrapper::Element::quadraticToElement);
  75705. v.setProperty (DrawablePath::ValueTreeWrapper::point1, controlPoints[0].toString(), 0);
  75706. v.setProperty (DrawablePath::ValueTreeWrapper::point2, controlPoints[1].toString(), 0);
  75707. return v;
  75708. }
  75709. void RelativePointPath::QuadraticTo::addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const
  75710. {
  75711. path.quadraticTo (controlPoints[0].resolve (coordFinder),
  75712. controlPoints[1].resolve (coordFinder));
  75713. }
  75714. RelativePoint* RelativePointPath::QuadraticTo::getControlPoints (int& numPoints)
  75715. {
  75716. numPoints = 2;
  75717. return controlPoints;
  75718. }
  75719. RelativePointPath::CubicTo::CubicTo (const RelativePoint& controlPoint1, const RelativePoint& controlPoint2, const RelativePoint& endPoint)
  75720. : ElementBase (cubicToElement)
  75721. {
  75722. controlPoints[0] = controlPoint1;
  75723. controlPoints[1] = controlPoint2;
  75724. controlPoints[2] = endPoint;
  75725. }
  75726. const ValueTree RelativePointPath::CubicTo::createTree() const
  75727. {
  75728. ValueTree v (DrawablePath::ValueTreeWrapper::Element::cubicToElement);
  75729. v.setProperty (DrawablePath::ValueTreeWrapper::point1, controlPoints[0].toString(), 0);
  75730. v.setProperty (DrawablePath::ValueTreeWrapper::point2, controlPoints[1].toString(), 0);
  75731. v.setProperty (DrawablePath::ValueTreeWrapper::point3, controlPoints[2].toString(), 0);
  75732. return v;
  75733. }
  75734. void RelativePointPath::CubicTo::addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const
  75735. {
  75736. path.cubicTo (controlPoints[0].resolve (coordFinder),
  75737. controlPoints[1].resolve (coordFinder),
  75738. controlPoints[2].resolve (coordFinder));
  75739. }
  75740. RelativePoint* RelativePointPath::CubicTo::getControlPoints (int& numPoints)
  75741. {
  75742. numPoints = 3;
  75743. return controlPoints;
  75744. }
  75745. RelativeParallelogram::RelativeParallelogram()
  75746. {
  75747. }
  75748. RelativeParallelogram::RelativeParallelogram (const RelativePoint& topLeft_, const RelativePoint& topRight_, const RelativePoint& bottomLeft_)
  75749. : topLeft (topLeft_), topRight (topRight_), bottomLeft (bottomLeft_)
  75750. {
  75751. }
  75752. RelativeParallelogram::RelativeParallelogram (const String& topLeft_, const String& topRight_, const String& bottomLeft_)
  75753. : topLeft (topLeft_), topRight (topRight_), bottomLeft (bottomLeft_)
  75754. {
  75755. }
  75756. RelativeParallelogram::~RelativeParallelogram()
  75757. {
  75758. }
  75759. void RelativeParallelogram::resolveThreePoints (Point<float>* points, RelativeCoordinate::NamedCoordinateFinder* const coordFinder) const
  75760. {
  75761. points[0] = topLeft.resolve (coordFinder);
  75762. points[1] = topRight.resolve (coordFinder);
  75763. points[2] = bottomLeft.resolve (coordFinder);
  75764. }
  75765. void RelativeParallelogram::resolveFourCorners (Point<float>* points, RelativeCoordinate::NamedCoordinateFinder* const coordFinder) const
  75766. {
  75767. resolveThreePoints (points, coordFinder);
  75768. points[3] = points[1] + (points[2] - points[0]);
  75769. }
  75770. const Rectangle<float> RelativeParallelogram::getBounds (RelativeCoordinate::NamedCoordinateFinder* const coordFinder) const
  75771. {
  75772. Point<float> points[4];
  75773. resolveFourCorners (points, coordFinder);
  75774. return Rectangle<float>::findAreaContainingPoints (points, 4);
  75775. }
  75776. void RelativeParallelogram::getPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* const coordFinder) const
  75777. {
  75778. Point<float> points[4];
  75779. resolveFourCorners (points, coordFinder);
  75780. path.startNewSubPath (points[0]);
  75781. path.lineTo (points[1]);
  75782. path.lineTo (points[3]);
  75783. path.lineTo (points[2]);
  75784. path.closeSubPath();
  75785. }
  75786. const AffineTransform RelativeParallelogram::resetToPerpendicular (RelativeCoordinate::NamedCoordinateFinder* const coordFinder)
  75787. {
  75788. Point<float> corners[3];
  75789. resolveThreePoints (corners, coordFinder);
  75790. const Line<float> top (corners[0], corners[1]);
  75791. const Line<float> left (corners[0], corners[2]);
  75792. const Point<float> newTopRight (corners[0] + Point<float> (top.getLength(), 0.0f));
  75793. const Point<float> newBottomLeft (corners[0] + Point<float> (0.0f, left.getLength()));
  75794. topRight.moveToAbsolute (newTopRight, coordFinder);
  75795. bottomLeft.moveToAbsolute (newBottomLeft, coordFinder);
  75796. return AffineTransform::fromTargetPoints (corners[0].getX(), corners[0].getY(), corners[0].getX(), corners[0].getY(),
  75797. corners[1].getX(), corners[1].getY(), newTopRight.getX(), newTopRight.getY(),
  75798. corners[2].getX(), corners[2].getY(), newBottomLeft.getX(), newBottomLeft.getY());
  75799. }
  75800. bool RelativeParallelogram::operator== (const RelativeParallelogram& other) const throw()
  75801. {
  75802. return topLeft == other.topLeft && topRight == other.topRight && bottomLeft == other.bottomLeft;
  75803. }
  75804. bool RelativeParallelogram::operator!= (const RelativeParallelogram& other) const throw()
  75805. {
  75806. return ! operator== (other);
  75807. }
  75808. const Point<float> RelativeParallelogram::getInternalCoordForPoint (const Point<float>* const corners, Point<float> target) throw()
  75809. {
  75810. const Point<float> tr (corners[1] - corners[0]);
  75811. const Point<float> bl (corners[2] - corners[0]);
  75812. target -= corners[0];
  75813. return Point<float> (Line<float> (Point<float>(), tr).getIntersection (Line<float> (target, target - bl)).getDistanceFromOrigin(),
  75814. Line<float> (Point<float>(), bl).getIntersection (Line<float> (target, target - tr)).getDistanceFromOrigin());
  75815. }
  75816. const Point<float> RelativeParallelogram::getPointForInternalCoord (const Point<float>* const corners, const Point<float>& point) throw()
  75817. {
  75818. return corners[0]
  75819. + Line<float> (Point<float>(), corners[1] - corners[0]).getPointAlongLine (point.getX())
  75820. + Line<float> (Point<float>(), corners[2] - corners[0]).getPointAlongLine (point.getY());
  75821. }
  75822. END_JUCE_NAMESPACE
  75823. /*** End of inlined file: juce_RelativeCoordinate.cpp ***/
  75824. /*** Start of inlined file: juce_Image.cpp ***/
  75825. BEGIN_JUCE_NAMESPACE
  75826. static const int fullAlphaThreshold = 253;
  75827. Image::SharedImage::SharedImage (const PixelFormat format_, const int width_, const int height_)
  75828. : format (format_), width (width_), height (height_)
  75829. {
  75830. jassert (format_ == RGB || format_ == ARGB || format_ == SingleChannel);
  75831. jassert (width > 0 && height > 0); // It's illegal to create a zero-sized image!
  75832. }
  75833. Image::SharedImage::~SharedImage()
  75834. {
  75835. }
  75836. inline uint8* Image::SharedImage::getPixelData (const int x, const int y) const throw()
  75837. {
  75838. return imageData + lineStride * y + pixelStride * x;
  75839. }
  75840. class SoftwareSharedImage : public Image::SharedImage
  75841. {
  75842. public:
  75843. SoftwareSharedImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  75844. : Image::SharedImage (format_, width_, height_)
  75845. {
  75846. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  75847. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  75848. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  75849. imageData = imageDataAllocated;
  75850. }
  75851. ~SoftwareSharedImage()
  75852. {
  75853. }
  75854. Image::ImageType getType() const
  75855. {
  75856. return Image::SoftwareImage;
  75857. }
  75858. LowLevelGraphicsContext* createLowLevelContext()
  75859. {
  75860. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  75861. }
  75862. SharedImage* clone()
  75863. {
  75864. SoftwareSharedImage* s = new SoftwareSharedImage (format, width, height, false);
  75865. memcpy (s->imageData, imageData, lineStride * height);
  75866. return s;
  75867. }
  75868. private:
  75869. HeapBlock<uint8> imageDataAllocated;
  75870. };
  75871. Image::SharedImage* Image::SharedImage::createSoftwareImage (Image::PixelFormat format, int width, int height, bool clearImage)
  75872. {
  75873. return new SoftwareSharedImage (format, width, height, clearImage);
  75874. }
  75875. Image::Image()
  75876. {
  75877. }
  75878. Image::Image (SharedImage* const instance)
  75879. : image (instance)
  75880. {
  75881. }
  75882. Image::Image (const PixelFormat format,
  75883. const int width, const int height,
  75884. const bool clearImage, const ImageType type)
  75885. : image (type == Image::NativeImage ? SharedImage::createNativeImage (format, width, height, clearImage)
  75886. : new SoftwareSharedImage (format, width, height, clearImage))
  75887. {
  75888. }
  75889. Image::Image (const Image& other)
  75890. : image (other.image)
  75891. {
  75892. }
  75893. Image& Image::operator= (const Image& other)
  75894. {
  75895. image = other.image;
  75896. return *this;
  75897. }
  75898. Image::~Image()
  75899. {
  75900. }
  75901. LowLevelGraphicsContext* Image::createLowLevelContext() const
  75902. {
  75903. return image == 0 ? 0 : image->createLowLevelContext();
  75904. }
  75905. void Image::duplicateIfShared()
  75906. {
  75907. if (image != 0 && image->getReferenceCount() > 1)
  75908. image = image->clone();
  75909. }
  75910. const Image Image::rescaled (const int newWidth, const int newHeight, const Graphics::ResamplingQuality quality) const
  75911. {
  75912. if (image == 0 || (image->width == newWidth && image->height == newHeight))
  75913. return *this;
  75914. Image newImage (image->format, newWidth, newHeight, hasAlphaChannel(), image->getType());
  75915. Graphics g (newImage);
  75916. g.setImageResamplingQuality (quality);
  75917. g.drawImage (*this, 0, 0, newWidth, newHeight, 0, 0, image->width, image->height, false);
  75918. return newImage;
  75919. }
  75920. const Image Image::convertedToFormat (PixelFormat newFormat) const
  75921. {
  75922. if (image == 0 || newFormat == image->format)
  75923. return *this;
  75924. Image newImage (newFormat, image->width, image->height, false, image->getType());
  75925. if (newFormat == SingleChannel)
  75926. {
  75927. if (! hasAlphaChannel())
  75928. {
  75929. newImage.clear (getBounds(), Colours::black);
  75930. }
  75931. else
  75932. {
  75933. const BitmapData destData (newImage, 0, 0, image->width, image->height, true);
  75934. const BitmapData srcData (*this, 0, 0, image->width, image->height);
  75935. for (int y = 0; y < image->height; ++y)
  75936. {
  75937. const PixelARGB* src = (const PixelARGB*) srcData.getLinePointer(y);
  75938. uint8* dst = destData.getLinePointer (y);
  75939. for (int x = image->width; --x >= 0;)
  75940. {
  75941. *dst++ = src->getAlpha();
  75942. ++src;
  75943. }
  75944. }
  75945. }
  75946. }
  75947. else
  75948. {
  75949. if (hasAlphaChannel())
  75950. newImage.clear (getBounds());
  75951. Graphics g (newImage);
  75952. g.drawImageAt (*this, 0, 0);
  75953. }
  75954. return newImage;
  75955. }
  75956. const var Image::getTag() const
  75957. {
  75958. return image == 0 ? var::null : image->userTag;
  75959. }
  75960. void Image::setTag (const var& newTag)
  75961. {
  75962. if (image != 0)
  75963. image->userTag = newTag;
  75964. }
  75965. Image::BitmapData::BitmapData (Image& image, const int x, const int y, const int w, const int h, const bool /*makeWritable*/)
  75966. : data (image.image == 0 ? 0 : image.image->getPixelData (x, y)),
  75967. pixelFormat (image.getFormat()),
  75968. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  75969. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  75970. width (w),
  75971. height (h)
  75972. {
  75973. jassert (data != 0);
  75974. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= image.getWidth() && y + h <= image.getHeight());
  75975. }
  75976. Image::BitmapData::BitmapData (const Image& image, const int x, const int y, const int w, const int h)
  75977. : data (image.image == 0 ? 0 : image.image->getPixelData (x, y)),
  75978. pixelFormat (image.getFormat()),
  75979. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  75980. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  75981. width (w),
  75982. height (h)
  75983. {
  75984. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= image.getWidth() && y + h <= image.getHeight());
  75985. }
  75986. Image::BitmapData::~BitmapData()
  75987. {
  75988. }
  75989. const Colour Image::BitmapData::getPixelColour (const int x, const int y) const throw()
  75990. {
  75991. jassert (((unsigned int) x) < (unsigned int) width && ((unsigned int) y) < (unsigned int) height);
  75992. const uint8* const pixel = getPixelPointer (x, y);
  75993. switch (pixelFormat)
  75994. {
  75995. case Image::ARGB:
  75996. {
  75997. PixelARGB p (*(const PixelARGB*) pixel);
  75998. p.unpremultiply();
  75999. return Colour (p.getARGB());
  76000. }
  76001. case Image::RGB:
  76002. return Colour (((const PixelRGB*) pixel)->getARGB());
  76003. case Image::SingleChannel:
  76004. return Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixel);
  76005. default:
  76006. jassertfalse;
  76007. break;
  76008. }
  76009. return Colour();
  76010. }
  76011. void Image::BitmapData::setPixelColour (const int x, const int y, const Colour& colour) const throw()
  76012. {
  76013. jassert (((unsigned int) x) < (unsigned int) width && ((unsigned int) y) < (unsigned int) height);
  76014. uint8* const pixel = getPixelPointer (x, y);
  76015. const PixelARGB col (colour.getPixelARGB());
  76016. switch (pixelFormat)
  76017. {
  76018. case Image::ARGB: ((PixelARGB*) pixel)->set (col); break;
  76019. case Image::RGB: ((PixelRGB*) pixel)->set (col); break;
  76020. case Image::SingleChannel: *pixel = col.getAlpha(); break;
  76021. default: jassertfalse; break;
  76022. }
  76023. }
  76024. void Image::setPixelData (int x, int y, int w, int h,
  76025. const uint8* const sourcePixelData, const int sourceLineStride)
  76026. {
  76027. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= getWidth() && y + h <= getHeight());
  76028. if (Rectangle<int>::intersectRectangles (x, y, w, h, 0, 0, getWidth(), getHeight()))
  76029. {
  76030. const BitmapData dest (*this, x, y, w, h, true);
  76031. for (int i = 0; i < h; ++i)
  76032. {
  76033. memcpy (dest.getLinePointer(i),
  76034. sourcePixelData + sourceLineStride * i,
  76035. w * dest.pixelStride);
  76036. }
  76037. }
  76038. }
  76039. void Image::clear (const Rectangle<int>& area, const Colour& colourToClearTo)
  76040. {
  76041. const Rectangle<int> clipped (area.getIntersection (getBounds()));
  76042. if (! clipped.isEmpty())
  76043. {
  76044. const PixelARGB col (colourToClearTo.getPixelARGB());
  76045. const BitmapData destData (*this, clipped.getX(), clipped.getY(), clipped.getWidth(), clipped.getHeight(), true);
  76046. uint8* dest = destData.data;
  76047. int dh = clipped.getHeight();
  76048. while (--dh >= 0)
  76049. {
  76050. uint8* line = dest;
  76051. dest += destData.lineStride;
  76052. if (isARGB())
  76053. {
  76054. for (int x = clipped.getWidth(); --x >= 0;)
  76055. {
  76056. ((PixelARGB*) line)->set (col);
  76057. line += destData.pixelStride;
  76058. }
  76059. }
  76060. else if (isRGB())
  76061. {
  76062. for (int x = clipped.getWidth(); --x >= 0;)
  76063. {
  76064. ((PixelRGB*) line)->set (col);
  76065. line += destData.pixelStride;
  76066. }
  76067. }
  76068. else
  76069. {
  76070. for (int x = clipped.getWidth(); --x >= 0;)
  76071. {
  76072. *line = col.getAlpha();
  76073. line += destData.pixelStride;
  76074. }
  76075. }
  76076. }
  76077. }
  76078. }
  76079. const Colour Image::getPixelAt (const int x, const int y) const
  76080. {
  76081. if (((unsigned int) x) < (unsigned int) getWidth()
  76082. && ((unsigned int) y) < (unsigned int) getHeight())
  76083. {
  76084. const BitmapData srcData (*this, x, y, 1, 1);
  76085. return srcData.getPixelColour (0, 0);
  76086. }
  76087. return Colour();
  76088. }
  76089. void Image::setPixelAt (const int x, const int y, const Colour& colour)
  76090. {
  76091. if (((unsigned int) x) < (unsigned int) getWidth()
  76092. && ((unsigned int) y) < (unsigned int) getHeight())
  76093. {
  76094. const BitmapData destData (*this, x, y, 1, 1, true);
  76095. destData.setPixelColour (0, 0, colour);
  76096. }
  76097. }
  76098. void Image::multiplyAlphaAt (const int x, const int y, const float multiplier)
  76099. {
  76100. if (((unsigned int) x) < (unsigned int) getWidth()
  76101. && ((unsigned int) y) < (unsigned int) getHeight()
  76102. && hasAlphaChannel())
  76103. {
  76104. const BitmapData destData (*this, x, y, 1, 1, true);
  76105. if (isARGB())
  76106. ((PixelARGB*) destData.data)->multiplyAlpha (multiplier);
  76107. else
  76108. *(destData.data) = (uint8) (*(destData.data) * multiplier);
  76109. }
  76110. }
  76111. void Image::multiplyAllAlphas (const float amountToMultiplyBy)
  76112. {
  76113. if (hasAlphaChannel())
  76114. {
  76115. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), true);
  76116. if (isARGB())
  76117. {
  76118. for (int y = 0; y < destData.height; ++y)
  76119. {
  76120. uint8* p = destData.getLinePointer (y);
  76121. for (int x = 0; x < destData.width; ++x)
  76122. {
  76123. ((PixelARGB*) p)->multiplyAlpha (amountToMultiplyBy);
  76124. p += destData.pixelStride;
  76125. }
  76126. }
  76127. }
  76128. else
  76129. {
  76130. for (int y = 0; y < destData.height; ++y)
  76131. {
  76132. uint8* p = destData.getLinePointer (y);
  76133. for (int x = 0; x < destData.width; ++x)
  76134. {
  76135. *p = (uint8) (*p * amountToMultiplyBy);
  76136. p += destData.pixelStride;
  76137. }
  76138. }
  76139. }
  76140. }
  76141. else
  76142. {
  76143. jassertfalse; // can't do this without an alpha-channel!
  76144. }
  76145. }
  76146. void Image::desaturate()
  76147. {
  76148. if (isARGB() || isRGB())
  76149. {
  76150. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), true);
  76151. if (isARGB())
  76152. {
  76153. for (int y = 0; y < destData.height; ++y)
  76154. {
  76155. uint8* p = destData.getLinePointer (y);
  76156. for (int x = 0; x < destData.width; ++x)
  76157. {
  76158. ((PixelARGB*) p)->desaturate();
  76159. p += destData.pixelStride;
  76160. }
  76161. }
  76162. }
  76163. else
  76164. {
  76165. for (int y = 0; y < destData.height; ++y)
  76166. {
  76167. uint8* p = destData.getLinePointer (y);
  76168. for (int x = 0; x < destData.width; ++x)
  76169. {
  76170. ((PixelRGB*) p)->desaturate();
  76171. p += destData.pixelStride;
  76172. }
  76173. }
  76174. }
  76175. }
  76176. }
  76177. void Image::createSolidAreaMask (RectangleList& result, const float alphaThreshold) const
  76178. {
  76179. if (hasAlphaChannel())
  76180. {
  76181. const uint8 threshold = (uint8) jlimit (0, 255, roundToInt (alphaThreshold * 255.0f));
  76182. SparseSet<int> pixelsOnRow;
  76183. const BitmapData srcData (*this, 0, 0, getWidth(), getHeight());
  76184. for (int y = 0; y < srcData.height; ++y)
  76185. {
  76186. pixelsOnRow.clear();
  76187. const uint8* lineData = srcData.getLinePointer (y);
  76188. if (isARGB())
  76189. {
  76190. for (int x = 0; x < srcData.width; ++x)
  76191. {
  76192. if (((const PixelARGB*) lineData)->getAlpha() >= threshold)
  76193. pixelsOnRow.addRange (Range<int> (x, x + 1));
  76194. lineData += srcData.pixelStride;
  76195. }
  76196. }
  76197. else
  76198. {
  76199. for (int x = 0; x < srcData.width; ++x)
  76200. {
  76201. if (*lineData >= threshold)
  76202. pixelsOnRow.addRange (Range<int> (x, x + 1));
  76203. lineData += srcData.pixelStride;
  76204. }
  76205. }
  76206. for (int i = 0; i < pixelsOnRow.getNumRanges(); ++i)
  76207. {
  76208. const Range<int> range (pixelsOnRow.getRange (i));
  76209. result.add (Rectangle<int> (range.getStart(), y, range.getLength(), 1));
  76210. }
  76211. result.consolidate();
  76212. }
  76213. }
  76214. else
  76215. {
  76216. result.add (0, 0, getWidth(), getHeight());
  76217. }
  76218. }
  76219. void Image::moveImageSection (int dx, int dy,
  76220. int sx, int sy,
  76221. int w, int h)
  76222. {
  76223. if (dx < 0)
  76224. {
  76225. w += dx;
  76226. sx -= dx;
  76227. dx = 0;
  76228. }
  76229. if (dy < 0)
  76230. {
  76231. h += dy;
  76232. sy -= dy;
  76233. dy = 0;
  76234. }
  76235. if (sx < 0)
  76236. {
  76237. w += sx;
  76238. dx -= sx;
  76239. sx = 0;
  76240. }
  76241. if (sy < 0)
  76242. {
  76243. h += sy;
  76244. dy -= sy;
  76245. sy = 0;
  76246. }
  76247. const int minX = jmin (dx, sx);
  76248. const int minY = jmin (dy, sy);
  76249. w = jmin (w, getWidth() - jmax (sx, dx));
  76250. h = jmin (h, getHeight() - jmax (sy, dy));
  76251. if (w > 0 && h > 0)
  76252. {
  76253. const int maxX = jmax (dx, sx) + w;
  76254. const int maxY = jmax (dy, sy) + h;
  76255. const BitmapData destData (*this, minX, minY, maxX - minX, maxY - minY, true);
  76256. uint8* dst = destData.getPixelPointer (dx - minX, dy - minY);
  76257. const uint8* src = destData.getPixelPointer (sx - minX, sy - minY);
  76258. const int lineSize = destData.pixelStride * w;
  76259. if (dy > sy)
  76260. {
  76261. while (--h >= 0)
  76262. {
  76263. const int offset = h * destData.lineStride;
  76264. memmove (dst + offset, src + offset, lineSize);
  76265. }
  76266. }
  76267. else if (dst != src)
  76268. {
  76269. while (--h >= 0)
  76270. {
  76271. memmove (dst, src, lineSize);
  76272. dst += destData.lineStride;
  76273. src += destData.lineStride;
  76274. }
  76275. }
  76276. }
  76277. }
  76278. END_JUCE_NAMESPACE
  76279. /*** End of inlined file: juce_Image.cpp ***/
  76280. /*** Start of inlined file: juce_ImageCache.cpp ***/
  76281. BEGIN_JUCE_NAMESPACE
  76282. class ImageCache::Pimpl : public Timer,
  76283. public DeletedAtShutdown
  76284. {
  76285. public:
  76286. Pimpl()
  76287. : cacheTimeout (5000)
  76288. {
  76289. }
  76290. ~Pimpl()
  76291. {
  76292. clearSingletonInstance();
  76293. }
  76294. const Image getFromHashCode (const int64 hashCode)
  76295. {
  76296. const ScopedLock sl (lock);
  76297. for (int i = images.size(); --i >= 0;)
  76298. {
  76299. Item* const item = images.getUnchecked(i);
  76300. if (item->hashCode == hashCode)
  76301. return item->image;
  76302. }
  76303. return Image();
  76304. }
  76305. void addImageToCache (const Image& image, const int64 hashCode)
  76306. {
  76307. if (image.isValid())
  76308. {
  76309. if (! isTimerRunning())
  76310. startTimer (2000);
  76311. Item* const item = new Item();
  76312. item->hashCode = hashCode;
  76313. item->image = image;
  76314. item->lastUseTime = Time::getApproximateMillisecondCounter();
  76315. const ScopedLock sl (lock);
  76316. images.add (item);
  76317. }
  76318. }
  76319. void timerCallback()
  76320. {
  76321. const uint32 now = Time::getApproximateMillisecondCounter();
  76322. const ScopedLock sl (lock);
  76323. for (int i = images.size(); --i >= 0;)
  76324. {
  76325. Item* const item = images.getUnchecked(i);
  76326. if (item->image.getReferenceCount() <= 1)
  76327. {
  76328. if (now > item->lastUseTime + cacheTimeout || now < item->lastUseTime - 1000)
  76329. images.remove (i);
  76330. }
  76331. else
  76332. {
  76333. item->lastUseTime = now; // multiply-referenced, so this image is still in use.
  76334. }
  76335. }
  76336. if (images.size() == 0)
  76337. stopTimer();
  76338. }
  76339. struct Item
  76340. {
  76341. Image image;
  76342. int64 hashCode;
  76343. uint32 lastUseTime;
  76344. };
  76345. int cacheTimeout;
  76346. juce_DeclareSingleton_SingleThreaded_Minimal (ImageCache::Pimpl);
  76347. private:
  76348. OwnedArray<Item> images;
  76349. CriticalSection lock;
  76350. Pimpl (const Pimpl&);
  76351. Pimpl& operator= (const Pimpl&);
  76352. };
  76353. juce_ImplementSingleton_SingleThreaded (ImageCache::Pimpl);
  76354. const Image ImageCache::getFromHashCode (const int64 hashCode)
  76355. {
  76356. if (Pimpl::getInstanceWithoutCreating() != 0)
  76357. return Pimpl::getInstanceWithoutCreating()->getFromHashCode (hashCode);
  76358. return Image();
  76359. }
  76360. void ImageCache::addImageToCache (const Image& image, const int64 hashCode)
  76361. {
  76362. Pimpl::getInstance()->addImageToCache (image, hashCode);
  76363. }
  76364. const Image ImageCache::getFromFile (const File& file)
  76365. {
  76366. const int64 hashCode = file.hashCode64();
  76367. Image image (getFromHashCode (hashCode));
  76368. if (image.isNull())
  76369. {
  76370. image = ImageFileFormat::loadFrom (file);
  76371. addImageToCache (image, hashCode);
  76372. }
  76373. return image;
  76374. }
  76375. const Image ImageCache::getFromMemory (const void* imageData, const int dataSize)
  76376. {
  76377. const int64 hashCode = (int64) (pointer_sized_int) imageData;
  76378. Image image (getFromHashCode (hashCode));
  76379. if (image.isNull())
  76380. {
  76381. image = ImageFileFormat::loadFrom (imageData, dataSize);
  76382. addImageToCache (image, hashCode);
  76383. }
  76384. return image;
  76385. }
  76386. void ImageCache::setCacheTimeout (const int millisecs)
  76387. {
  76388. Pimpl::getInstance()->cacheTimeout = millisecs;
  76389. }
  76390. END_JUCE_NAMESPACE
  76391. /*** End of inlined file: juce_ImageCache.cpp ***/
  76392. /*** Start of inlined file: juce_ImageConvolutionKernel.cpp ***/
  76393. BEGIN_JUCE_NAMESPACE
  76394. ImageConvolutionKernel::ImageConvolutionKernel (const int size_)
  76395. : values (size_ * size_),
  76396. size (size_)
  76397. {
  76398. clear();
  76399. }
  76400. ImageConvolutionKernel::~ImageConvolutionKernel()
  76401. {
  76402. }
  76403. float ImageConvolutionKernel::getKernelValue (const int x, const int y) const throw()
  76404. {
  76405. if (((unsigned int) x) < (unsigned int) size
  76406. && ((unsigned int) y) < (unsigned int) size)
  76407. {
  76408. return values [x + y * size];
  76409. }
  76410. else
  76411. {
  76412. jassertfalse;
  76413. return 0;
  76414. }
  76415. }
  76416. void ImageConvolutionKernel::setKernelValue (const int x, const int y, const float value) throw()
  76417. {
  76418. if (((unsigned int) x) < (unsigned int) size
  76419. && ((unsigned int) y) < (unsigned int) size)
  76420. {
  76421. values [x + y * size] = value;
  76422. }
  76423. else
  76424. {
  76425. jassertfalse;
  76426. }
  76427. }
  76428. void ImageConvolutionKernel::clear()
  76429. {
  76430. for (int i = size * size; --i >= 0;)
  76431. values[i] = 0;
  76432. }
  76433. void ImageConvolutionKernel::setOverallSum (const float desiredTotalSum)
  76434. {
  76435. double currentTotal = 0.0;
  76436. for (int i = size * size; --i >= 0;)
  76437. currentTotal += values[i];
  76438. rescaleAllValues ((float) (desiredTotalSum / currentTotal));
  76439. }
  76440. void ImageConvolutionKernel::rescaleAllValues (const float multiplier)
  76441. {
  76442. for (int i = size * size; --i >= 0;)
  76443. values[i] *= multiplier;
  76444. }
  76445. void ImageConvolutionKernel::createGaussianBlur (const float radius)
  76446. {
  76447. const double radiusFactor = -1.0 / (radius * radius * 2);
  76448. const int centre = size >> 1;
  76449. for (int y = size; --y >= 0;)
  76450. {
  76451. for (int x = size; --x >= 0;)
  76452. {
  76453. const int cx = x - centre;
  76454. const int cy = y - centre;
  76455. values [x + y * size] = (float) exp (radiusFactor * (cx * cx + cy * cy));
  76456. }
  76457. }
  76458. setOverallSum (1.0f);
  76459. }
  76460. void ImageConvolutionKernel::applyToImage (Image& destImage,
  76461. const Image& sourceImage,
  76462. const Rectangle<int>& destinationArea) const
  76463. {
  76464. if (sourceImage == destImage)
  76465. {
  76466. destImage.duplicateIfShared();
  76467. }
  76468. else
  76469. {
  76470. if (sourceImage.getWidth() != destImage.getWidth()
  76471. || sourceImage.getHeight() != destImage.getHeight()
  76472. || sourceImage.getFormat() != destImage.getFormat())
  76473. {
  76474. jassertfalse;
  76475. return;
  76476. }
  76477. }
  76478. const Rectangle<int> area (destinationArea.getIntersection (destImage.getBounds()));
  76479. if (area.isEmpty())
  76480. return;
  76481. const int right = area.getRight();
  76482. const int bottom = area.getBottom();
  76483. const Image::BitmapData destData (destImage, area.getX(), area.getY(), area.getWidth(), area.getHeight(), true);
  76484. uint8* line = destData.data;
  76485. const Image::BitmapData srcData (sourceImage, 0, 0, sourceImage.getWidth(), sourceImage.getHeight());
  76486. if (destData.pixelStride == 4)
  76487. {
  76488. for (int y = area.getY(); y < bottom; ++y)
  76489. {
  76490. uint8* dest = line;
  76491. line += destData.lineStride;
  76492. for (int x = area.getX(); x < right; ++x)
  76493. {
  76494. float c1 = 0;
  76495. float c2 = 0;
  76496. float c3 = 0;
  76497. float c4 = 0;
  76498. for (int yy = 0; yy < size; ++yy)
  76499. {
  76500. const int sy = y + yy - (size >> 1);
  76501. if (sy >= srcData.height)
  76502. break;
  76503. if (sy >= 0)
  76504. {
  76505. int sx = x - (size >> 1);
  76506. const uint8* src = srcData.getPixelPointer (sx, sy);
  76507. for (int xx = 0; xx < size; ++xx)
  76508. {
  76509. if (sx >= srcData.width)
  76510. break;
  76511. if (sx >= 0)
  76512. {
  76513. const float kernelMult = values [xx + yy * size];
  76514. c1 += kernelMult * *src++;
  76515. c2 += kernelMult * *src++;
  76516. c3 += kernelMult * *src++;
  76517. c4 += kernelMult * *src++;
  76518. }
  76519. else
  76520. {
  76521. src += 4;
  76522. }
  76523. ++sx;
  76524. }
  76525. }
  76526. }
  76527. *dest++ = (uint8) jmin (0xff, roundToInt (c1));
  76528. *dest++ = (uint8) jmin (0xff, roundToInt (c2));
  76529. *dest++ = (uint8) jmin (0xff, roundToInt (c3));
  76530. *dest++ = (uint8) jmin (0xff, roundToInt (c4));
  76531. }
  76532. }
  76533. }
  76534. else if (destData.pixelStride == 3)
  76535. {
  76536. for (int y = area.getY(); y < bottom; ++y)
  76537. {
  76538. uint8* dest = line;
  76539. line += destData.lineStride;
  76540. for (int x = area.getX(); x < right; ++x)
  76541. {
  76542. float c1 = 0;
  76543. float c2 = 0;
  76544. float c3 = 0;
  76545. for (int yy = 0; yy < size; ++yy)
  76546. {
  76547. const int sy = y + yy - (size >> 1);
  76548. if (sy >= srcData.height)
  76549. break;
  76550. if (sy >= 0)
  76551. {
  76552. int sx = x - (size >> 1);
  76553. const uint8* src = srcData.getPixelPointer (sx, sy);
  76554. for (int xx = 0; xx < size; ++xx)
  76555. {
  76556. if (sx >= srcData.width)
  76557. break;
  76558. if (sx >= 0)
  76559. {
  76560. const float kernelMult = values [xx + yy * size];
  76561. c1 += kernelMult * *src++;
  76562. c2 += kernelMult * *src++;
  76563. c3 += kernelMult * *src++;
  76564. }
  76565. else
  76566. {
  76567. src += 3;
  76568. }
  76569. ++sx;
  76570. }
  76571. }
  76572. }
  76573. *dest++ = (uint8) roundToInt (c1);
  76574. *dest++ = (uint8) roundToInt (c2);
  76575. *dest++ = (uint8) roundToInt (c3);
  76576. }
  76577. }
  76578. }
  76579. }
  76580. END_JUCE_NAMESPACE
  76581. /*** End of inlined file: juce_ImageConvolutionKernel.cpp ***/
  76582. /*** Start of inlined file: juce_ImageFileFormat.cpp ***/
  76583. BEGIN_JUCE_NAMESPACE
  76584. /*** Start of inlined file: juce_GIFLoader.h ***/
  76585. #ifndef __JUCE_GIFLOADER_JUCEHEADER__
  76586. #define __JUCE_GIFLOADER_JUCEHEADER__
  76587. #ifndef DOXYGEN
  76588. /**
  76589. Used internally by ImageFileFormat - don't use this class directly in your
  76590. application.
  76591. @see ImageFileFormat
  76592. */
  76593. class GIFLoader
  76594. {
  76595. public:
  76596. GIFLoader (InputStream& in);
  76597. ~GIFLoader();
  76598. const Image& getImage() const { return image; }
  76599. private:
  76600. Image image;
  76601. InputStream& input;
  76602. uint8 buffer [300];
  76603. uint8 palette [256][4];
  76604. bool dataBlockIsZero, fresh, finished;
  76605. int currentBit, lastBit, lastByteIndex;
  76606. int codeSize, setCodeSize;
  76607. int maxCode, maxCodeSize;
  76608. int firstcode, oldcode;
  76609. int clearCode, end_code;
  76610. enum { maxGifCode = 1 << 12 };
  76611. int table [2] [maxGifCode];
  76612. int stack [2 * maxGifCode];
  76613. int *sp;
  76614. bool getSizeFromHeader (int& width, int& height);
  76615. bool readPalette (const int numCols);
  76616. int readDataBlock (unsigned char* dest);
  76617. int processExtension (int type, int& transparent);
  76618. int readLZWByte (bool initialise, int input_code_size);
  76619. int getCode (int code_size, bool initialise);
  76620. bool readImage (int width, int height, int interlace, int transparent);
  76621. static inline int makeWord (const uint8 a, const uint8 b) { return (b << 8) | a; }
  76622. GIFLoader (const GIFLoader&);
  76623. GIFLoader& operator= (const GIFLoader&);
  76624. };
  76625. #endif // DOXYGEN
  76626. #endif // __JUCE_GIFLOADER_JUCEHEADER__
  76627. /*** End of inlined file: juce_GIFLoader.h ***/
  76628. class GIFImageFormat : public ImageFileFormat
  76629. {
  76630. public:
  76631. GIFImageFormat() {}
  76632. ~GIFImageFormat() {}
  76633. const String getFormatName()
  76634. {
  76635. return "GIF";
  76636. }
  76637. bool canUnderstand (InputStream& in)
  76638. {
  76639. const int bytesNeeded = 4;
  76640. char header [bytesNeeded];
  76641. return (in.read (header, bytesNeeded) == bytesNeeded)
  76642. && header[0] == 'G'
  76643. && header[1] == 'I'
  76644. && header[2] == 'F';
  76645. }
  76646. const Image decodeImage (InputStream& in)
  76647. {
  76648. const ScopedPointer <GIFLoader> loader (new GIFLoader (in));
  76649. return loader->getImage();
  76650. }
  76651. bool writeImageToStream (const Image& /*sourceImage*/, OutputStream& /*destStream*/)
  76652. {
  76653. return false;
  76654. }
  76655. };
  76656. ImageFileFormat* ImageFileFormat::findImageFormatForStream (InputStream& input)
  76657. {
  76658. static PNGImageFormat png;
  76659. static JPEGImageFormat jpg;
  76660. static GIFImageFormat gif;
  76661. ImageFileFormat* formats[4];
  76662. int numFormats = 0;
  76663. formats [numFormats++] = &png;
  76664. formats [numFormats++] = &jpg;
  76665. formats [numFormats++] = &gif;
  76666. const int64 streamPos = input.getPosition();
  76667. for (int i = 0; i < numFormats; ++i)
  76668. {
  76669. const bool found = formats[i]->canUnderstand (input);
  76670. input.setPosition (streamPos);
  76671. if (found)
  76672. return formats[i];
  76673. }
  76674. return 0;
  76675. }
  76676. const Image ImageFileFormat::loadFrom (InputStream& input)
  76677. {
  76678. ImageFileFormat* const format = findImageFormatForStream (input);
  76679. if (format != 0)
  76680. return format->decodeImage (input);
  76681. return Image();
  76682. }
  76683. const Image ImageFileFormat::loadFrom (const File& file)
  76684. {
  76685. InputStream* const in = file.createInputStream();
  76686. if (in != 0)
  76687. {
  76688. BufferedInputStream b (in, 8192, true);
  76689. return loadFrom (b);
  76690. }
  76691. return Image();
  76692. }
  76693. const Image ImageFileFormat::loadFrom (const void* rawData, const int numBytes)
  76694. {
  76695. if (rawData != 0 && numBytes > 4)
  76696. {
  76697. MemoryInputStream stream (rawData, numBytes, false);
  76698. return loadFrom (stream);
  76699. }
  76700. return Image();
  76701. }
  76702. END_JUCE_NAMESPACE
  76703. /*** End of inlined file: juce_ImageFileFormat.cpp ***/
  76704. /*** Start of inlined file: juce_GIFLoader.cpp ***/
  76705. BEGIN_JUCE_NAMESPACE
  76706. GIFLoader::GIFLoader (InputStream& in)
  76707. : image (0),
  76708. input (in),
  76709. dataBlockIsZero (false),
  76710. fresh (false),
  76711. finished (false)
  76712. {
  76713. currentBit = lastBit = lastByteIndex = 0;
  76714. maxCode = maxCodeSize = codeSize = setCodeSize = 0;
  76715. firstcode = oldcode = 0;
  76716. clearCode = end_code = 0;
  76717. int imageWidth, imageHeight;
  76718. int transparent = -1;
  76719. if (! getSizeFromHeader (imageWidth, imageHeight))
  76720. return;
  76721. if ((imageWidth <= 0) || (imageHeight <= 0))
  76722. return;
  76723. unsigned char buf [16];
  76724. if (in.read (buf, 3) != 3)
  76725. return;
  76726. int numColours = 2 << (buf[0] & 7);
  76727. if ((buf[0] & 0x80) != 0)
  76728. readPalette (numColours);
  76729. for (;;)
  76730. {
  76731. if (input.read (buf, 1) != 1)
  76732. break;
  76733. if (buf[0] == ';')
  76734. break;
  76735. if (buf[0] == '!')
  76736. {
  76737. if (input.read (buf, 1) != 1)
  76738. break;
  76739. if (processExtension (buf[0], transparent) < 0)
  76740. break;
  76741. continue;
  76742. }
  76743. if (buf[0] != ',')
  76744. continue;
  76745. if (input.read (buf, 9) != 9)
  76746. break;
  76747. imageWidth = makeWord (buf[4], buf[5]);
  76748. imageHeight = makeWord (buf[6], buf[7]);
  76749. numColours = 2 << (buf[8] & 7);
  76750. if ((buf[8] & 0x80) != 0)
  76751. if (! readPalette (numColours))
  76752. break;
  76753. image = Image ((transparent >= 0) ? Image::ARGB : Image::RGB,
  76754. imageWidth, imageHeight, (transparent >= 0));
  76755. readImage (imageWidth, imageHeight,
  76756. (buf[8] & 0x40) != 0,
  76757. transparent);
  76758. break;
  76759. }
  76760. }
  76761. GIFLoader::~GIFLoader()
  76762. {
  76763. }
  76764. bool GIFLoader::getSizeFromHeader (int& w, int& h)
  76765. {
  76766. char b[8];
  76767. if (input.read (b, 6) == 6)
  76768. {
  76769. if ((strncmp ("GIF87a", b, 6) == 0)
  76770. || (strncmp ("GIF89a", b, 6) == 0))
  76771. {
  76772. if (input.read (b, 4) == 4)
  76773. {
  76774. w = makeWord (b[0], b[1]);
  76775. h = makeWord (b[2], b[3]);
  76776. return true;
  76777. }
  76778. }
  76779. }
  76780. return false;
  76781. }
  76782. bool GIFLoader::readPalette (const int numCols)
  76783. {
  76784. unsigned char rgb[4];
  76785. for (int i = 0; i < numCols; ++i)
  76786. {
  76787. input.read (rgb, 3);
  76788. palette [i][0] = rgb[0];
  76789. palette [i][1] = rgb[1];
  76790. palette [i][2] = rgb[2];
  76791. palette [i][3] = 0xff;
  76792. }
  76793. return true;
  76794. }
  76795. int GIFLoader::readDataBlock (unsigned char* const dest)
  76796. {
  76797. unsigned char n;
  76798. if (input.read (&n, 1) == 1)
  76799. {
  76800. dataBlockIsZero = (n == 0);
  76801. if (dataBlockIsZero || (input.read (dest, n) == n))
  76802. return n;
  76803. }
  76804. return -1;
  76805. }
  76806. int GIFLoader::processExtension (const int type, int& transparent)
  76807. {
  76808. unsigned char b [300];
  76809. int n = 0;
  76810. if (type == 0xf9)
  76811. {
  76812. n = readDataBlock (b);
  76813. if (n < 0)
  76814. return 1;
  76815. if ((b[0] & 0x1) != 0)
  76816. transparent = b[3];
  76817. }
  76818. do
  76819. {
  76820. n = readDataBlock (b);
  76821. }
  76822. while (n > 0);
  76823. return n;
  76824. }
  76825. int GIFLoader::getCode (const int codeSize_, const bool initialise)
  76826. {
  76827. if (initialise)
  76828. {
  76829. currentBit = 0;
  76830. lastBit = 0;
  76831. finished = false;
  76832. return 0;
  76833. }
  76834. if ((currentBit + codeSize_) >= lastBit)
  76835. {
  76836. if (finished)
  76837. return -1;
  76838. buffer[0] = buffer [lastByteIndex - 2];
  76839. buffer[1] = buffer [lastByteIndex - 1];
  76840. const int n = readDataBlock (&buffer[2]);
  76841. if (n == 0)
  76842. finished = true;
  76843. lastByteIndex = 2 + n;
  76844. currentBit = (currentBit - lastBit) + 16;
  76845. lastBit = (2 + n) * 8 ;
  76846. }
  76847. int result = 0;
  76848. int i = currentBit;
  76849. for (int j = 0; j < codeSize_; ++j)
  76850. {
  76851. result |= ((buffer[i >> 3] & (1 << (i & 7))) != 0) << j;
  76852. ++i;
  76853. }
  76854. currentBit += codeSize_;
  76855. return result;
  76856. }
  76857. int GIFLoader::readLZWByte (const bool initialise, const int inputCodeSize)
  76858. {
  76859. int code, incode, i;
  76860. if (initialise)
  76861. {
  76862. setCodeSize = inputCodeSize;
  76863. codeSize = setCodeSize + 1;
  76864. clearCode = 1 << setCodeSize;
  76865. end_code = clearCode + 1;
  76866. maxCodeSize = 2 * clearCode;
  76867. maxCode = clearCode + 2;
  76868. getCode (0, true);
  76869. fresh = true;
  76870. for (i = 0; i < clearCode; ++i)
  76871. {
  76872. table[0][i] = 0;
  76873. table[1][i] = i;
  76874. }
  76875. for (; i < maxGifCode; ++i)
  76876. {
  76877. table[0][i] = 0;
  76878. table[1][i] = 0;
  76879. }
  76880. sp = stack;
  76881. return 0;
  76882. }
  76883. else if (fresh)
  76884. {
  76885. fresh = false;
  76886. do
  76887. {
  76888. firstcode = oldcode
  76889. = getCode (codeSize, false);
  76890. }
  76891. while (firstcode == clearCode);
  76892. return firstcode;
  76893. }
  76894. if (sp > stack)
  76895. return *--sp;
  76896. while ((code = getCode (codeSize, false)) >= 0)
  76897. {
  76898. if (code == clearCode)
  76899. {
  76900. for (i = 0; i < clearCode; ++i)
  76901. {
  76902. table[0][i] = 0;
  76903. table[1][i] = i;
  76904. }
  76905. for (; i < maxGifCode; ++i)
  76906. {
  76907. table[0][i] = 0;
  76908. table[1][i] = 0;
  76909. }
  76910. codeSize = setCodeSize + 1;
  76911. maxCodeSize = 2 * clearCode;
  76912. maxCode = clearCode + 2;
  76913. sp = stack;
  76914. firstcode = oldcode = getCode (codeSize, false);
  76915. return firstcode;
  76916. }
  76917. else if (code == end_code)
  76918. {
  76919. if (dataBlockIsZero)
  76920. return -2;
  76921. unsigned char buf [260];
  76922. int n;
  76923. while ((n = readDataBlock (buf)) > 0)
  76924. {}
  76925. if (n != 0)
  76926. return -2;
  76927. }
  76928. incode = code;
  76929. if (code >= maxCode)
  76930. {
  76931. *sp++ = firstcode;
  76932. code = oldcode;
  76933. }
  76934. while (code >= clearCode)
  76935. {
  76936. *sp++ = table[1][code];
  76937. if (code == table[0][code])
  76938. return -2;
  76939. code = table[0][code];
  76940. }
  76941. *sp++ = firstcode = table[1][code];
  76942. if ((code = maxCode) < maxGifCode)
  76943. {
  76944. table[0][code] = oldcode;
  76945. table[1][code] = firstcode;
  76946. ++maxCode;
  76947. if ((maxCode >= maxCodeSize)
  76948. && (maxCodeSize < maxGifCode))
  76949. {
  76950. maxCodeSize <<= 1;
  76951. ++codeSize;
  76952. }
  76953. }
  76954. oldcode = incode;
  76955. if (sp > stack)
  76956. return *--sp;
  76957. }
  76958. return code;
  76959. }
  76960. bool GIFLoader::readImage (const int width, const int height,
  76961. const int interlace, const int transparent)
  76962. {
  76963. unsigned char c;
  76964. if (input.read (&c, 1) != 1
  76965. || readLZWByte (true, c) < 0)
  76966. return false;
  76967. if (transparent >= 0)
  76968. {
  76969. palette [transparent][0] = 0;
  76970. palette [transparent][1] = 0;
  76971. palette [transparent][2] = 0;
  76972. palette [transparent][3] = 0;
  76973. }
  76974. int index;
  76975. int xpos = 0, ypos = 0, pass = 0;
  76976. const Image::BitmapData destData (image, 0, 0, width, height, true);
  76977. uint8* p = destData.data;
  76978. const bool hasAlpha = image.hasAlphaChannel();
  76979. while ((index = readLZWByte (false, c)) >= 0)
  76980. {
  76981. const uint8* const paletteEntry = palette [index];
  76982. if (hasAlpha)
  76983. {
  76984. ((PixelARGB*) p)->setARGB (paletteEntry[3],
  76985. paletteEntry[0],
  76986. paletteEntry[1],
  76987. paletteEntry[2]);
  76988. ((PixelARGB*) p)->premultiply();
  76989. }
  76990. else
  76991. {
  76992. ((PixelRGB*) p)->setARGB (0,
  76993. paletteEntry[0],
  76994. paletteEntry[1],
  76995. paletteEntry[2]);
  76996. }
  76997. p += destData.pixelStride;
  76998. ++xpos;
  76999. if (xpos == width)
  77000. {
  77001. xpos = 0;
  77002. if (interlace)
  77003. {
  77004. switch (pass)
  77005. {
  77006. case 0:
  77007. case 1: ypos += 8; break;
  77008. case 2: ypos += 4; break;
  77009. case 3: ypos += 2; break;
  77010. }
  77011. while (ypos >= height)
  77012. {
  77013. ++pass;
  77014. switch (pass)
  77015. {
  77016. case 1: ypos = 4; break;
  77017. case 2: ypos = 2; break;
  77018. case 3: ypos = 1; break;
  77019. default: return true;
  77020. }
  77021. }
  77022. }
  77023. else
  77024. {
  77025. ++ypos;
  77026. }
  77027. p = destData.getPixelPointer (xpos, ypos);
  77028. }
  77029. if (ypos >= height)
  77030. break;
  77031. }
  77032. return true;
  77033. }
  77034. END_JUCE_NAMESPACE
  77035. /*** End of inlined file: juce_GIFLoader.cpp ***/
  77036. #endif
  77037. //==============================================================================
  77038. // some files include lots of library code, so leave them to the end to avoid cluttering
  77039. // up the build for the clean files.
  77040. #if JUCE_BUILD_CORE
  77041. /*** Start of inlined file: juce_GZIPCompressorOutputStream.cpp ***/
  77042. namespace zlibNamespace
  77043. {
  77044. #if JUCE_INCLUDE_ZLIB_CODE
  77045. #undef OS_CODE
  77046. #undef fdopen
  77047. /*** Start of inlined file: zlib.h ***/
  77048. #ifndef ZLIB_H
  77049. #define ZLIB_H
  77050. /*** Start of inlined file: zconf.h ***/
  77051. /* @(#) $Id: zconf.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  77052. #ifndef ZCONF_H
  77053. #define ZCONF_H
  77054. // *** Just a few hacks here to make it compile nicely with Juce..
  77055. #define Z_PREFIX 1
  77056. #undef __MACTYPES__
  77057. #ifdef _MSC_VER
  77058. #pragma warning (disable : 4131 4127 4244 4267)
  77059. #endif
  77060. /*
  77061. * If you *really* need a unique prefix for all types and library functions,
  77062. * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
  77063. */
  77064. #ifdef Z_PREFIX
  77065. # define deflateInit_ z_deflateInit_
  77066. # define deflate z_deflate
  77067. # define deflateEnd z_deflateEnd
  77068. # define inflateInit_ z_inflateInit_
  77069. # define inflate z_inflate
  77070. # define inflateEnd z_inflateEnd
  77071. # define inflatePrime z_inflatePrime
  77072. # define inflateGetHeader z_inflateGetHeader
  77073. # define adler32_combine z_adler32_combine
  77074. # define crc32_combine z_crc32_combine
  77075. # define deflateInit2_ z_deflateInit2_
  77076. # define deflateSetDictionary z_deflateSetDictionary
  77077. # define deflateCopy z_deflateCopy
  77078. # define deflateReset z_deflateReset
  77079. # define deflateParams z_deflateParams
  77080. # define deflateBound z_deflateBound
  77081. # define deflatePrime z_deflatePrime
  77082. # define inflateInit2_ z_inflateInit2_
  77083. # define inflateSetDictionary z_inflateSetDictionary
  77084. # define inflateSync z_inflateSync
  77085. # define inflateSyncPoint z_inflateSyncPoint
  77086. # define inflateCopy z_inflateCopy
  77087. # define inflateReset z_inflateReset
  77088. # define inflateBack z_inflateBack
  77089. # define inflateBackEnd z_inflateBackEnd
  77090. # define compress z_compress
  77091. # define compress2 z_compress2
  77092. # define compressBound z_compressBound
  77093. # define uncompress z_uncompress
  77094. # define adler32 z_adler32
  77095. # define crc32 z_crc32
  77096. # define get_crc_table z_get_crc_table
  77097. # define zError z_zError
  77098. # define alloc_func z_alloc_func
  77099. # define free_func z_free_func
  77100. # define in_func z_in_func
  77101. # define out_func z_out_func
  77102. # define Byte z_Byte
  77103. # define uInt z_uInt
  77104. # define uLong z_uLong
  77105. # define Bytef z_Bytef
  77106. # define charf z_charf
  77107. # define intf z_intf
  77108. # define uIntf z_uIntf
  77109. # define uLongf z_uLongf
  77110. # define voidpf z_voidpf
  77111. # define voidp z_voidp
  77112. #endif
  77113. #if defined(__MSDOS__) && !defined(MSDOS)
  77114. # define MSDOS
  77115. #endif
  77116. #if (defined(OS_2) || defined(__OS2__)) && !defined(OS2)
  77117. # define OS2
  77118. #endif
  77119. #if defined(_WINDOWS) && !defined(WINDOWS)
  77120. # define WINDOWS
  77121. #endif
  77122. #if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)
  77123. # ifndef WIN32
  77124. # define WIN32
  77125. # endif
  77126. #endif
  77127. #if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)
  77128. # if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)
  77129. # ifndef SYS16BIT
  77130. # define SYS16BIT
  77131. # endif
  77132. # endif
  77133. #endif
  77134. /*
  77135. * Compile with -DMAXSEG_64K if the alloc function cannot allocate more
  77136. * than 64k bytes at a time (needed on systems with 16-bit int).
  77137. */
  77138. #ifdef SYS16BIT
  77139. # define MAXSEG_64K
  77140. #endif
  77141. #ifdef MSDOS
  77142. # define UNALIGNED_OK
  77143. #endif
  77144. #ifdef __STDC_VERSION__
  77145. # ifndef STDC
  77146. # define STDC
  77147. # endif
  77148. # if __STDC_VERSION__ >= 199901L
  77149. # ifndef STDC99
  77150. # define STDC99
  77151. # endif
  77152. # endif
  77153. #endif
  77154. #if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus))
  77155. # define STDC
  77156. #endif
  77157. #if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__))
  77158. # define STDC
  77159. #endif
  77160. #if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32))
  77161. # define STDC
  77162. #endif
  77163. #if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__))
  77164. # define STDC
  77165. #endif
  77166. #if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */
  77167. # define STDC
  77168. #endif
  77169. #ifndef STDC
  77170. # ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
  77171. # define const /* note: need a more gentle solution here */
  77172. # endif
  77173. #endif
  77174. /* Some Mac compilers merge all .h files incorrectly: */
  77175. #if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__)
  77176. # define NO_DUMMY_DECL
  77177. #endif
  77178. /* Maximum value for memLevel in deflateInit2 */
  77179. #ifndef MAX_MEM_LEVEL
  77180. # ifdef MAXSEG_64K
  77181. # define MAX_MEM_LEVEL 8
  77182. # else
  77183. # define MAX_MEM_LEVEL 9
  77184. # endif
  77185. #endif
  77186. /* Maximum value for windowBits in deflateInit2 and inflateInit2.
  77187. * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
  77188. * created by gzip. (Files created by minigzip can still be extracted by
  77189. * gzip.)
  77190. */
  77191. #ifndef MAX_WBITS
  77192. # define MAX_WBITS 15 /* 32K LZ77 window */
  77193. #endif
  77194. /* The memory requirements for deflate are (in bytes):
  77195. (1 << (windowBits+2)) + (1 << (memLevel+9))
  77196. that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values)
  77197. plus a few kilobytes for small objects. For example, if you want to reduce
  77198. the default memory requirements from 256K to 128K, compile with
  77199. make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
  77200. Of course this will generally degrade compression (there's no free lunch).
  77201. The memory requirements for inflate are (in bytes) 1 << windowBits
  77202. that is, 32K for windowBits=15 (default value) plus a few kilobytes
  77203. for small objects.
  77204. */
  77205. /* Type declarations */
  77206. #ifndef OF /* function prototypes */
  77207. # ifdef STDC
  77208. # define OF(args) args
  77209. # else
  77210. # define OF(args) ()
  77211. # endif
  77212. #endif
  77213. /* The following definitions for FAR are needed only for MSDOS mixed
  77214. * model programming (small or medium model with some far allocations).
  77215. * This was tested only with MSC; for other MSDOS compilers you may have
  77216. * to define NO_MEMCPY in zutil.h. If you don't need the mixed model,
  77217. * just define FAR to be empty.
  77218. */
  77219. #ifdef SYS16BIT
  77220. # if defined(M_I86SM) || defined(M_I86MM)
  77221. /* MSC small or medium model */
  77222. # define SMALL_MEDIUM
  77223. # ifdef _MSC_VER
  77224. # define FAR _far
  77225. # else
  77226. # define FAR far
  77227. # endif
  77228. # endif
  77229. # if (defined(__SMALL__) || defined(__MEDIUM__))
  77230. /* Turbo C small or medium model */
  77231. # define SMALL_MEDIUM
  77232. # ifdef __BORLANDC__
  77233. # define FAR _far
  77234. # else
  77235. # define FAR far
  77236. # endif
  77237. # endif
  77238. #endif
  77239. #if defined(WINDOWS) || defined(WIN32)
  77240. /* If building or using zlib as a DLL, define ZLIB_DLL.
  77241. * This is not mandatory, but it offers a little performance increase.
  77242. */
  77243. # ifdef ZLIB_DLL
  77244. # if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500))
  77245. # ifdef ZLIB_INTERNAL
  77246. # define ZEXTERN extern __declspec(dllexport)
  77247. # else
  77248. # define ZEXTERN extern __declspec(dllimport)
  77249. # endif
  77250. # endif
  77251. # endif /* ZLIB_DLL */
  77252. /* If building or using zlib with the WINAPI/WINAPIV calling convention,
  77253. * define ZLIB_WINAPI.
  77254. * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI.
  77255. */
  77256. # ifdef ZLIB_WINAPI
  77257. # ifdef FAR
  77258. # undef FAR
  77259. # endif
  77260. # include <windows.h>
  77261. /* No need for _export, use ZLIB.DEF instead. */
  77262. /* For complete Windows compatibility, use WINAPI, not __stdcall. */
  77263. # define ZEXPORT WINAPI
  77264. # ifdef WIN32
  77265. # define ZEXPORTVA WINAPIV
  77266. # else
  77267. # define ZEXPORTVA FAR CDECL
  77268. # endif
  77269. # endif
  77270. #endif
  77271. #if defined (__BEOS__)
  77272. # ifdef ZLIB_DLL
  77273. # ifdef ZLIB_INTERNAL
  77274. # define ZEXPORT __declspec(dllexport)
  77275. # define ZEXPORTVA __declspec(dllexport)
  77276. # else
  77277. # define ZEXPORT __declspec(dllimport)
  77278. # define ZEXPORTVA __declspec(dllimport)
  77279. # endif
  77280. # endif
  77281. #endif
  77282. #ifndef ZEXTERN
  77283. # define ZEXTERN extern
  77284. #endif
  77285. #ifndef ZEXPORT
  77286. # define ZEXPORT
  77287. #endif
  77288. #ifndef ZEXPORTVA
  77289. # define ZEXPORTVA
  77290. #endif
  77291. #ifndef FAR
  77292. # define FAR
  77293. #endif
  77294. #if !defined(__MACTYPES__)
  77295. typedef unsigned char Byte; /* 8 bits */
  77296. #endif
  77297. typedef unsigned int uInt; /* 16 bits or more */
  77298. typedef unsigned long uLong; /* 32 bits or more */
  77299. #ifdef SMALL_MEDIUM
  77300. /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
  77301. # define Bytef Byte FAR
  77302. #else
  77303. typedef Byte FAR Bytef;
  77304. #endif
  77305. typedef char FAR charf;
  77306. typedef int FAR intf;
  77307. typedef uInt FAR uIntf;
  77308. typedef uLong FAR uLongf;
  77309. #ifdef STDC
  77310. typedef void const *voidpc;
  77311. typedef void FAR *voidpf;
  77312. typedef void *voidp;
  77313. #else
  77314. typedef Byte const *voidpc;
  77315. typedef Byte FAR *voidpf;
  77316. typedef Byte *voidp;
  77317. #endif
  77318. #if 0 /* HAVE_UNISTD_H -- this line is updated by ./configure */
  77319. # include <sys/types.h> /* for off_t */
  77320. # include <unistd.h> /* for SEEK_* and off_t */
  77321. # ifdef VMS
  77322. # include <unixio.h> /* for off_t */
  77323. # endif
  77324. # define z_off_t off_t
  77325. #endif
  77326. #ifndef SEEK_SET
  77327. # define SEEK_SET 0 /* Seek from beginning of file. */
  77328. # define SEEK_CUR 1 /* Seek from current position. */
  77329. # define SEEK_END 2 /* Set file pointer to EOF plus "offset" */
  77330. #endif
  77331. #ifndef z_off_t
  77332. # define z_off_t long
  77333. #endif
  77334. #if defined(__OS400__)
  77335. # define NO_vsnprintf
  77336. #endif
  77337. #if defined(__MVS__)
  77338. # define NO_vsnprintf
  77339. # ifdef FAR
  77340. # undef FAR
  77341. # endif
  77342. #endif
  77343. /* MVS linker does not support external names larger than 8 bytes */
  77344. #if defined(__MVS__)
  77345. # pragma map(deflateInit_,"DEIN")
  77346. # pragma map(deflateInit2_,"DEIN2")
  77347. # pragma map(deflateEnd,"DEEND")
  77348. # pragma map(deflateBound,"DEBND")
  77349. # pragma map(inflateInit_,"ININ")
  77350. # pragma map(inflateInit2_,"ININ2")
  77351. # pragma map(inflateEnd,"INEND")
  77352. # pragma map(inflateSync,"INSY")
  77353. # pragma map(inflateSetDictionary,"INSEDI")
  77354. # pragma map(compressBound,"CMBND")
  77355. # pragma map(inflate_table,"INTABL")
  77356. # pragma map(inflate_fast,"INFA")
  77357. # pragma map(inflate_copyright,"INCOPY")
  77358. #endif
  77359. #endif /* ZCONF_H */
  77360. /*** End of inlined file: zconf.h ***/
  77361. #ifdef __cplusplus
  77362. extern "C" {
  77363. #endif
  77364. #define ZLIB_VERSION "1.2.3"
  77365. #define ZLIB_VERNUM 0x1230
  77366. /*
  77367. The 'zlib' compression library provides in-memory compression and
  77368. decompression functions, including integrity checks of the uncompressed
  77369. data. This version of the library supports only one compression method
  77370. (deflation) but other algorithms will be added later and will have the same
  77371. stream interface.
  77372. Compression can be done in a single step if the buffers are large
  77373. enough (for example if an input file is mmap'ed), or can be done by
  77374. repeated calls of the compression function. In the latter case, the
  77375. application must provide more input and/or consume the output
  77376. (providing more output space) before each call.
  77377. The compressed data format used by default by the in-memory functions is
  77378. the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped
  77379. around a deflate stream, which is itself documented in RFC 1951.
  77380. The library also supports reading and writing files in gzip (.gz) format
  77381. with an interface similar to that of stdio using the functions that start
  77382. with "gz". The gzip format is different from the zlib format. gzip is a
  77383. gzip wrapper, documented in RFC 1952, wrapped around a deflate stream.
  77384. This library can optionally read and write gzip streams in memory as well.
  77385. The zlib format was designed to be compact and fast for use in memory
  77386. and on communications channels. The gzip format was designed for single-
  77387. file compression on file systems, has a larger header than zlib to maintain
  77388. directory information, and uses a different, slower check method than zlib.
  77389. The library does not install any signal handler. The decoder checks
  77390. the consistency of the compressed data, so the library should never
  77391. crash even in case of corrupted input.
  77392. */
  77393. typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size));
  77394. typedef void (*free_func) OF((voidpf opaque, voidpf address));
  77395. struct internal_state;
  77396. typedef struct z_stream_s {
  77397. Bytef *next_in; /* next input byte */
  77398. uInt avail_in; /* number of bytes available at next_in */
  77399. uLong total_in; /* total nb of input bytes read so far */
  77400. Bytef *next_out; /* next output byte should be put there */
  77401. uInt avail_out; /* remaining free space at next_out */
  77402. uLong total_out; /* total nb of bytes output so far */
  77403. char *msg; /* last error message, NULL if no error */
  77404. struct internal_state FAR *state; /* not visible by applications */
  77405. alloc_func zalloc; /* used to allocate the internal state */
  77406. free_func zfree; /* used to free the internal state */
  77407. voidpf opaque; /* private data object passed to zalloc and zfree */
  77408. int data_type; /* best guess about the data type: binary or text */
  77409. uLong adler; /* adler32 value of the uncompressed data */
  77410. uLong reserved; /* reserved for future use */
  77411. } z_stream;
  77412. typedef z_stream FAR *z_streamp;
  77413. /*
  77414. gzip header information passed to and from zlib routines. See RFC 1952
  77415. for more details on the meanings of these fields.
  77416. */
  77417. typedef struct gz_header_s {
  77418. int text; /* true if compressed data believed to be text */
  77419. uLong time; /* modification time */
  77420. int xflags; /* extra flags (not used when writing a gzip file) */
  77421. int os; /* operating system */
  77422. Bytef *extra; /* pointer to extra field or Z_NULL if none */
  77423. uInt extra_len; /* extra field length (valid if extra != Z_NULL) */
  77424. uInt extra_max; /* space at extra (only when reading header) */
  77425. Bytef *name; /* pointer to zero-terminated file name or Z_NULL */
  77426. uInt name_max; /* space at name (only when reading header) */
  77427. Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */
  77428. uInt comm_max; /* space at comment (only when reading header) */
  77429. int hcrc; /* true if there was or will be a header crc */
  77430. int done; /* true when done reading gzip header (not used
  77431. when writing a gzip file) */
  77432. } gz_header;
  77433. typedef gz_header FAR *gz_headerp;
  77434. /*
  77435. The application must update next_in and avail_in when avail_in has
  77436. dropped to zero. It must update next_out and avail_out when avail_out
  77437. has dropped to zero. The application must initialize zalloc, zfree and
  77438. opaque before calling the init function. All other fields are set by the
  77439. compression library and must not be updated by the application.
  77440. The opaque value provided by the application will be passed as the first
  77441. parameter for calls of zalloc and zfree. This can be useful for custom
  77442. memory management. The compression library attaches no meaning to the
  77443. opaque value.
  77444. zalloc must return Z_NULL if there is not enough memory for the object.
  77445. If zlib is used in a multi-threaded application, zalloc and zfree must be
  77446. thread safe.
  77447. On 16-bit systems, the functions zalloc and zfree must be able to allocate
  77448. exactly 65536 bytes, but will not be required to allocate more than this
  77449. if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS,
  77450. pointers returned by zalloc for objects of exactly 65536 bytes *must*
  77451. have their offset normalized to zero. The default allocation function
  77452. provided by this library ensures this (see zutil.c). To reduce memory
  77453. requirements and avoid any allocation of 64K objects, at the expense of
  77454. compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h).
  77455. The fields total_in and total_out can be used for statistics or
  77456. progress reports. After compression, total_in holds the total size of
  77457. the uncompressed data and may be saved for use in the decompressor
  77458. (particularly if the decompressor wants to decompress everything in
  77459. a single step).
  77460. */
  77461. /* constants */
  77462. #define Z_NO_FLUSH 0
  77463. #define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */
  77464. #define Z_SYNC_FLUSH 2
  77465. #define Z_FULL_FLUSH 3
  77466. #define Z_FINISH 4
  77467. #define Z_BLOCK 5
  77468. /* Allowed flush values; see deflate() and inflate() below for details */
  77469. #define Z_OK 0
  77470. #define Z_STREAM_END 1
  77471. #define Z_NEED_DICT 2
  77472. #define Z_ERRNO (-1)
  77473. #define Z_STREAM_ERROR (-2)
  77474. #define Z_DATA_ERROR (-3)
  77475. #define Z_MEM_ERROR (-4)
  77476. #define Z_BUF_ERROR (-5)
  77477. #define Z_VERSION_ERROR (-6)
  77478. /* Return codes for the compression/decompression functions. Negative
  77479. * values are errors, positive values are used for special but normal events.
  77480. */
  77481. #define Z_NO_COMPRESSION 0
  77482. #define Z_BEST_SPEED 1
  77483. #define Z_BEST_COMPRESSION 9
  77484. #define Z_DEFAULT_COMPRESSION (-1)
  77485. /* compression levels */
  77486. #define Z_FILTERED 1
  77487. #define Z_HUFFMAN_ONLY 2
  77488. #define Z_RLE 3
  77489. #define Z_FIXED 4
  77490. #define Z_DEFAULT_STRATEGY 0
  77491. /* compression strategy; see deflateInit2() below for details */
  77492. #define Z_BINARY 0
  77493. #define Z_TEXT 1
  77494. #define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */
  77495. #define Z_UNKNOWN 2
  77496. /* Possible values of the data_type field (though see inflate()) */
  77497. #define Z_DEFLATED 8
  77498. /* The deflate compression method (the only one supported in this version) */
  77499. #define Z_NULL 0 /* for initializing zalloc, zfree, opaque */
  77500. #define zlib_version zlibVersion()
  77501. /* for compatibility with versions < 1.0.2 */
  77502. /* basic functions */
  77503. //ZEXTERN const char * ZEXPORT zlibVersion OF((void));
  77504. /* The application can compare zlibVersion and ZLIB_VERSION for consistency.
  77505. If the first character differs, the library code actually used is
  77506. not compatible with the zlib.h header file used by the application.
  77507. This check is automatically made by deflateInit and inflateInit.
  77508. */
  77509. /*
  77510. ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level));
  77511. Initializes the internal stream state for compression. The fields
  77512. zalloc, zfree and opaque must be initialized before by the caller.
  77513. If zalloc and zfree are set to Z_NULL, deflateInit updates them to
  77514. use default allocation functions.
  77515. The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
  77516. 1 gives best speed, 9 gives best compression, 0 gives no compression at
  77517. all (the input data is simply copied a block at a time).
  77518. Z_DEFAULT_COMPRESSION requests a default compromise between speed and
  77519. compression (currently equivalent to level 6).
  77520. deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not
  77521. enough memory, Z_STREAM_ERROR if level is not a valid compression level,
  77522. Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
  77523. with the version assumed by the caller (ZLIB_VERSION).
  77524. msg is set to null if there is no error message. deflateInit does not
  77525. perform any compression: this will be done by deflate().
  77526. */
  77527. ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));
  77528. /*
  77529. deflate compresses as much data as possible, and stops when the input
  77530. buffer becomes empty or the output buffer becomes full. It may introduce some
  77531. output latency (reading input without producing any output) except when
  77532. forced to flush.
  77533. The detailed semantics are as follows. deflate performs one or both of the
  77534. following actions:
  77535. - Compress more input starting at next_in and update next_in and avail_in
  77536. accordingly. If not all input can be processed (because there is not
  77537. enough room in the output buffer), next_in and avail_in are updated and
  77538. processing will resume at this point for the next call of deflate().
  77539. - Provide more output starting at next_out and update next_out and avail_out
  77540. accordingly. This action is forced if the parameter flush is non zero.
  77541. Forcing flush frequently degrades the compression ratio, so this parameter
  77542. should be set only when necessary (in interactive applications).
  77543. Some output may be provided even if flush is not set.
  77544. Before the call of deflate(), the application should ensure that at least
  77545. one of the actions is possible, by providing more input and/or consuming
  77546. more output, and updating avail_in or avail_out accordingly; avail_out
  77547. should never be zero before the call. The application can consume the
  77548. compressed output when it wants, for example when the output buffer is full
  77549. (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK
  77550. and with zero avail_out, it must be called again after making room in the
  77551. output buffer because there might be more output pending.
  77552. Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to
  77553. decide how much data to accumualte before producing output, in order to
  77554. maximize compression.
  77555. If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
  77556. flushed to the output buffer and the output is aligned on a byte boundary, so
  77557. that the decompressor can get all input data available so far. (In particular
  77558. avail_in is zero after the call if enough output space has been provided
  77559. before the call.) Flushing may degrade compression for some compression
  77560. algorithms and so it should be used only when necessary.
  77561. If flush is set to Z_FULL_FLUSH, all output is flushed as with
  77562. Z_SYNC_FLUSH, and the compression state is reset so that decompression can
  77563. restart from this point if previous compressed data has been damaged or if
  77564. random access is desired. Using Z_FULL_FLUSH too often can seriously degrade
  77565. compression.
  77566. If deflate returns with avail_out == 0, this function must be called again
  77567. with the same value of the flush parameter and more output space (updated
  77568. avail_out), until the flush is complete (deflate returns with non-zero
  77569. avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that
  77570. avail_out is greater than six to avoid repeated flush markers due to
  77571. avail_out == 0 on return.
  77572. If the parameter flush is set to Z_FINISH, pending input is processed,
  77573. pending output is flushed and deflate returns with Z_STREAM_END if there
  77574. was enough output space; if deflate returns with Z_OK, this function must be
  77575. called again with Z_FINISH and more output space (updated avail_out) but no
  77576. more input data, until it returns with Z_STREAM_END or an error. After
  77577. deflate has returned Z_STREAM_END, the only possible operations on the
  77578. stream are deflateReset or deflateEnd.
  77579. Z_FINISH can be used immediately after deflateInit if all the compression
  77580. is to be done in a single step. In this case, avail_out must be at least
  77581. the value returned by deflateBound (see below). If deflate does not return
  77582. Z_STREAM_END, then it must be called again as described above.
  77583. deflate() sets strm->adler to the adler32 checksum of all input read
  77584. so far (that is, total_in bytes).
  77585. deflate() may update strm->data_type if it can make a good guess about
  77586. the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered
  77587. binary. This field is only for information purposes and does not affect
  77588. the compression algorithm in any manner.
  77589. deflate() returns Z_OK if some progress has been made (more input
  77590. processed or more output produced), Z_STREAM_END if all input has been
  77591. consumed and all output has been produced (only when flush is set to
  77592. Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
  77593. if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible
  77594. (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not
  77595. fatal, and deflate() can be called again with more input and more output
  77596. space to continue compressing.
  77597. */
  77598. ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm));
  77599. /*
  77600. All dynamically allocated data structures for this stream are freed.
  77601. This function discards any unprocessed input and does not flush any
  77602. pending output.
  77603. deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
  77604. stream state was inconsistent, Z_DATA_ERROR if the stream was freed
  77605. prematurely (some input or output was discarded). In the error case,
  77606. msg may be set but then points to a static string (which must not be
  77607. deallocated).
  77608. */
  77609. /*
  77610. ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm));
  77611. Initializes the internal stream state for decompression. The fields
  77612. next_in, avail_in, zalloc, zfree and opaque must be initialized before by
  77613. the caller. If next_in is not Z_NULL and avail_in is large enough (the exact
  77614. value depends on the compression method), inflateInit determines the
  77615. compression method from the zlib header and allocates all data structures
  77616. accordingly; otherwise the allocation will be deferred to the first call of
  77617. inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to
  77618. use default allocation functions.
  77619. inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
  77620. memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
  77621. version assumed by the caller. msg is set to null if there is no error
  77622. message. inflateInit does not perform any decompression apart from reading
  77623. the zlib header if present: this will be done by inflate(). (So next_in and
  77624. avail_in may be modified, but next_out and avail_out are unchanged.)
  77625. */
  77626. ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush));
  77627. /*
  77628. inflate decompresses as much data as possible, and stops when the input
  77629. buffer becomes empty or the output buffer becomes full. It may introduce
  77630. some output latency (reading input without producing any output) except when
  77631. forced to flush.
  77632. The detailed semantics are as follows. inflate performs one or both of the
  77633. following actions:
  77634. - Decompress more input starting at next_in and update next_in and avail_in
  77635. accordingly. If not all input can be processed (because there is not
  77636. enough room in the output buffer), next_in is updated and processing
  77637. will resume at this point for the next call of inflate().
  77638. - Provide more output starting at next_out and update next_out and avail_out
  77639. accordingly. inflate() provides as much output as possible, until there
  77640. is no more input data or no more space in the output buffer (see below
  77641. about the flush parameter).
  77642. Before the call of inflate(), the application should ensure that at least
  77643. one of the actions is possible, by providing more input and/or consuming
  77644. more output, and updating the next_* and avail_* values accordingly.
  77645. The application can consume the uncompressed output when it wants, for
  77646. example when the output buffer is full (avail_out == 0), or after each
  77647. call of inflate(). If inflate returns Z_OK and with zero avail_out, it
  77648. must be called again after making room in the output buffer because there
  77649. might be more output pending.
  77650. The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH,
  77651. Z_FINISH, or Z_BLOCK. Z_SYNC_FLUSH requests that inflate() flush as much
  77652. output as possible to the output buffer. Z_BLOCK requests that inflate() stop
  77653. if and when it gets to the next deflate block boundary. When decoding the
  77654. zlib or gzip format, this will cause inflate() to return immediately after
  77655. the header and before the first block. When doing a raw inflate, inflate()
  77656. will go ahead and process the first block, and will return when it gets to
  77657. the end of that block, or when it runs out of data.
  77658. The Z_BLOCK option assists in appending to or combining deflate streams.
  77659. Also to assist in this, on return inflate() will set strm->data_type to the
  77660. number of unused bits in the last byte taken from strm->next_in, plus 64
  77661. if inflate() is currently decoding the last block in the deflate stream,
  77662. plus 128 if inflate() returned immediately after decoding an end-of-block
  77663. code or decoding the complete header up to just before the first byte of the
  77664. deflate stream. The end-of-block will not be indicated until all of the
  77665. uncompressed data from that block has been written to strm->next_out. The
  77666. number of unused bits may in general be greater than seven, except when
  77667. bit 7 of data_type is set, in which case the number of unused bits will be
  77668. less than eight.
  77669. inflate() should normally be called until it returns Z_STREAM_END or an
  77670. error. However if all decompression is to be performed in a single step
  77671. (a single call of inflate), the parameter flush should be set to
  77672. Z_FINISH. In this case all pending input is processed and all pending
  77673. output is flushed; avail_out must be large enough to hold all the
  77674. uncompressed data. (The size of the uncompressed data may have been saved
  77675. by the compressor for this purpose.) The next operation on this stream must
  77676. be inflateEnd to deallocate the decompression state. The use of Z_FINISH
  77677. is never required, but can be used to inform inflate that a faster approach
  77678. may be used for the single inflate() call.
  77679. In this implementation, inflate() always flushes as much output as
  77680. possible to the output buffer, and always uses the faster approach on the
  77681. first call. So the only effect of the flush parameter in this implementation
  77682. is on the return value of inflate(), as noted below, or when it returns early
  77683. because Z_BLOCK is used.
  77684. If a preset dictionary is needed after this call (see inflateSetDictionary
  77685. below), inflate sets strm->adler to the adler32 checksum of the dictionary
  77686. chosen by the compressor and returns Z_NEED_DICT; otherwise it sets
  77687. strm->adler to the adler32 checksum of all output produced so far (that is,
  77688. total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described
  77689. below. At the end of the stream, inflate() checks that its computed adler32
  77690. checksum is equal to that saved by the compressor and returns Z_STREAM_END
  77691. only if the checksum is correct.
  77692. inflate() will decompress and check either zlib-wrapped or gzip-wrapped
  77693. deflate data. The header type is detected automatically. Any information
  77694. contained in the gzip header is not retained, so applications that need that
  77695. information should instead use raw inflate, see inflateInit2() below, or
  77696. inflateBack() and perform their own processing of the gzip header and
  77697. trailer.
  77698. inflate() returns Z_OK if some progress has been made (more input processed
  77699. or more output produced), Z_STREAM_END if the end of the compressed data has
  77700. been reached and all uncompressed output has been produced, Z_NEED_DICT if a
  77701. preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
  77702. corrupted (input stream not conforming to the zlib format or incorrect check
  77703. value), Z_STREAM_ERROR if the stream structure was inconsistent (for example
  77704. if next_in or next_out was NULL), Z_MEM_ERROR if there was not enough memory,
  77705. Z_BUF_ERROR if no progress is possible or if there was not enough room in the
  77706. output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and
  77707. inflate() can be called again with more input and more output space to
  77708. continue decompressing. If Z_DATA_ERROR is returned, the application may then
  77709. call inflateSync() to look for a good compression block if a partial recovery
  77710. of the data is desired.
  77711. */
  77712. ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm));
  77713. /*
  77714. All dynamically allocated data structures for this stream are freed.
  77715. This function discards any unprocessed input and does not flush any
  77716. pending output.
  77717. inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state
  77718. was inconsistent. In the error case, msg may be set but then points to a
  77719. static string (which must not be deallocated).
  77720. */
  77721. /* Advanced functions */
  77722. /*
  77723. The following functions are needed only in some special applications.
  77724. */
  77725. /*
  77726. ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm,
  77727. int level,
  77728. int method,
  77729. int windowBits,
  77730. int memLevel,
  77731. int strategy));
  77732. This is another version of deflateInit with more compression options. The
  77733. fields next_in, zalloc, zfree and opaque must be initialized before by
  77734. the caller.
  77735. The method parameter is the compression method. It must be Z_DEFLATED in
  77736. this version of the library.
  77737. The windowBits parameter is the base two logarithm of the window size
  77738. (the size of the history buffer). It should be in the range 8..15 for this
  77739. version of the library. Larger values of this parameter result in better
  77740. compression at the expense of memory usage. The default value is 15 if
  77741. deflateInit is used instead.
  77742. windowBits can also be -8..-15 for raw deflate. In this case, -windowBits
  77743. determines the window size. deflate() will then generate raw deflate data
  77744. with no zlib header or trailer, and will not compute an adler32 check value.
  77745. windowBits can also be greater than 15 for optional gzip encoding. Add
  77746. 16 to windowBits to write a simple gzip header and trailer around the
  77747. compressed data instead of a zlib wrapper. The gzip header will have no
  77748. file name, no extra data, no comment, no modification time (set to zero),
  77749. no header crc, and the operating system will be set to 255 (unknown). If a
  77750. gzip stream is being written, strm->adler is a crc32 instead of an adler32.
  77751. The memLevel parameter specifies how much memory should be allocated
  77752. for the internal compression state. memLevel=1 uses minimum memory but
  77753. is slow and reduces compression ratio; memLevel=9 uses maximum memory
  77754. for optimal speed. The default value is 8. See zconf.h for total memory
  77755. usage as a function of windowBits and memLevel.
  77756. The strategy parameter is used to tune the compression algorithm. Use the
  77757. value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
  77758. filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no
  77759. string match), or Z_RLE to limit match distances to one (run-length
  77760. encoding). Filtered data consists mostly of small values with a somewhat
  77761. random distribution. In this case, the compression algorithm is tuned to
  77762. compress them better. The effect of Z_FILTERED is to force more Huffman
  77763. coding and less string matching; it is somewhat intermediate between
  77764. Z_DEFAULT and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as
  77765. Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy
  77766. parameter only affects the compression ratio but not the correctness of the
  77767. compressed output even if it is not set appropriately. Z_FIXED prevents the
  77768. use of dynamic Huffman codes, allowing for a simpler decoder for special
  77769. applications.
  77770. deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  77771. memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid
  77772. method). msg is set to null if there is no error message. deflateInit2 does
  77773. not perform any compression: this will be done by deflate().
  77774. */
  77775. ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm,
  77776. const Bytef *dictionary,
  77777. uInt dictLength));
  77778. /*
  77779. Initializes the compression dictionary from the given byte sequence
  77780. without producing any compressed output. This function must be called
  77781. immediately after deflateInit, deflateInit2 or deflateReset, before any
  77782. call of deflate. The compressor and decompressor must use exactly the same
  77783. dictionary (see inflateSetDictionary).
  77784. The dictionary should consist of strings (byte sequences) that are likely
  77785. to be encountered later in the data to be compressed, with the most commonly
  77786. used strings preferably put towards the end of the dictionary. Using a
  77787. dictionary is most useful when the data to be compressed is short and can be
  77788. predicted with good accuracy; the data can then be compressed better than
  77789. with the default empty dictionary.
  77790. Depending on the size of the compression data structures selected by
  77791. deflateInit or deflateInit2, a part of the dictionary may in effect be
  77792. discarded, for example if the dictionary is larger than the window size in
  77793. deflate or deflate2. Thus the strings most likely to be useful should be
  77794. put at the end of the dictionary, not at the front. In addition, the
  77795. current implementation of deflate will use at most the window size minus
  77796. 262 bytes of the provided dictionary.
  77797. Upon return of this function, strm->adler is set to the adler32 value
  77798. of the dictionary; the decompressor may later use this value to determine
  77799. which dictionary has been used by the compressor. (The adler32 value
  77800. applies to the whole dictionary even if only a subset of the dictionary is
  77801. actually used by the compressor.) If a raw deflate was requested, then the
  77802. adler32 value is not computed and strm->adler is not set.
  77803. deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
  77804. parameter is invalid (such as NULL dictionary) or the stream state is
  77805. inconsistent (for example if deflate has already been called for this stream
  77806. or if the compression method is bsort). deflateSetDictionary does not
  77807. perform any compression: this will be done by deflate().
  77808. */
  77809. ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest,
  77810. z_streamp source));
  77811. /*
  77812. Sets the destination stream as a complete copy of the source stream.
  77813. This function can be useful when several compression strategies will be
  77814. tried, for example when there are several ways of pre-processing the input
  77815. data with a filter. The streams that will be discarded should then be freed
  77816. by calling deflateEnd. Note that deflateCopy duplicates the internal
  77817. compression state which can be quite large, so this strategy is slow and
  77818. can consume lots of memory.
  77819. deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  77820. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  77821. (such as zalloc being NULL). msg is left unchanged in both source and
  77822. destination.
  77823. */
  77824. ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm));
  77825. /*
  77826. This function is equivalent to deflateEnd followed by deflateInit,
  77827. but does not free and reallocate all the internal compression state.
  77828. The stream will keep the same compression level and any other attributes
  77829. that may have been set by deflateInit2.
  77830. deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  77831. stream state was inconsistent (such as zalloc or state being NULL).
  77832. */
  77833. ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm,
  77834. int level,
  77835. int strategy));
  77836. /*
  77837. Dynamically update the compression level and compression strategy. The
  77838. interpretation of level and strategy is as in deflateInit2. This can be
  77839. used to switch between compression and straight copy of the input data, or
  77840. to switch to a different kind of input data requiring a different
  77841. strategy. If the compression level is changed, the input available so far
  77842. is compressed with the old level (and may be flushed); the new level will
  77843. take effect only at the next call of deflate().
  77844. Before the call of deflateParams, the stream state must be set as for
  77845. a call of deflate(), since the currently available input may have to
  77846. be compressed and flushed. In particular, strm->avail_out must be non-zero.
  77847. deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source
  77848. stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR
  77849. if strm->avail_out was zero.
  77850. */
  77851. ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm,
  77852. int good_length,
  77853. int max_lazy,
  77854. int nice_length,
  77855. int max_chain));
  77856. /*
  77857. Fine tune deflate's internal compression parameters. This should only be
  77858. used by someone who understands the algorithm used by zlib's deflate for
  77859. searching for the best matching string, and even then only by the most
  77860. fanatic optimizer trying to squeeze out the last compressed bit for their
  77861. specific input data. Read the deflate.c source code for the meaning of the
  77862. max_lazy, good_length, nice_length, and max_chain parameters.
  77863. deflateTune() can be called after deflateInit() or deflateInit2(), and
  77864. returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream.
  77865. */
  77866. ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm,
  77867. uLong sourceLen));
  77868. /*
  77869. deflateBound() returns an upper bound on the compressed size after
  77870. deflation of sourceLen bytes. It must be called after deflateInit()
  77871. or deflateInit2(). This would be used to allocate an output buffer
  77872. for deflation in a single pass, and so would be called before deflate().
  77873. */
  77874. ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm,
  77875. int bits,
  77876. int value));
  77877. /*
  77878. deflatePrime() inserts bits in the deflate output stream. The intent
  77879. is that this function is used to start off the deflate output with the
  77880. bits leftover from a previous deflate stream when appending to it. As such,
  77881. this function can only be used for raw deflate, and must be used before the
  77882. first deflate() call after a deflateInit2() or deflateReset(). bits must be
  77883. less than or equal to 16, and that many of the least significant bits of
  77884. value will be inserted in the output.
  77885. deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  77886. stream state was inconsistent.
  77887. */
  77888. ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm,
  77889. gz_headerp head));
  77890. /*
  77891. deflateSetHeader() provides gzip header information for when a gzip
  77892. stream is requested by deflateInit2(). deflateSetHeader() may be called
  77893. after deflateInit2() or deflateReset() and before the first call of
  77894. deflate(). The text, time, os, extra field, name, and comment information
  77895. in the provided gz_header structure are written to the gzip header (xflag is
  77896. ignored -- the extra flags are set according to the compression level). The
  77897. caller must assure that, if not Z_NULL, name and comment are terminated with
  77898. a zero byte, and that if extra is not Z_NULL, that extra_len bytes are
  77899. available there. If hcrc is true, a gzip header crc is included. Note that
  77900. the current versions of the command-line version of gzip (up through version
  77901. 1.3.x) do not support header crc's, and will report that it is a "multi-part
  77902. gzip file" and give up.
  77903. If deflateSetHeader is not used, the default gzip header has text false,
  77904. the time set to zero, and os set to 255, with no extra, name, or comment
  77905. fields. The gzip header is returned to the default state by deflateReset().
  77906. deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  77907. stream state was inconsistent.
  77908. */
  77909. /*
  77910. ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm,
  77911. int windowBits));
  77912. This is another version of inflateInit with an extra parameter. The
  77913. fields next_in, avail_in, zalloc, zfree and opaque must be initialized
  77914. before by the caller.
  77915. The windowBits parameter is the base two logarithm of the maximum window
  77916. size (the size of the history buffer). It should be in the range 8..15 for
  77917. this version of the library. The default value is 15 if inflateInit is used
  77918. instead. windowBits must be greater than or equal to the windowBits value
  77919. provided to deflateInit2() while compressing, or it must be equal to 15 if
  77920. deflateInit2() was not used. If a compressed stream with a larger window
  77921. size is given as input, inflate() will return with the error code
  77922. Z_DATA_ERROR instead of trying to allocate a larger window.
  77923. windowBits can also be -8..-15 for raw inflate. In this case, -windowBits
  77924. determines the window size. inflate() will then process raw deflate data,
  77925. not looking for a zlib or gzip header, not generating a check value, and not
  77926. looking for any check values for comparison at the end of the stream. This
  77927. is for use with other formats that use the deflate compressed data format
  77928. such as zip. Those formats provide their own check values. If a custom
  77929. format is developed using the raw deflate format for compressed data, it is
  77930. recommended that a check value such as an adler32 or a crc32 be applied to
  77931. the uncompressed data as is done in the zlib, gzip, and zip formats. For
  77932. most applications, the zlib format should be used as is. Note that comments
  77933. above on the use in deflateInit2() applies to the magnitude of windowBits.
  77934. windowBits can also be greater than 15 for optional gzip decoding. Add
  77935. 32 to windowBits to enable zlib and gzip decoding with automatic header
  77936. detection, or add 16 to decode only the gzip format (the zlib format will
  77937. return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is
  77938. a crc32 instead of an adler32.
  77939. inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  77940. memory, Z_STREAM_ERROR if a parameter is invalid (such as a null strm). msg
  77941. is set to null if there is no error message. inflateInit2 does not perform
  77942. any decompression apart from reading the zlib header if present: this will
  77943. be done by inflate(). (So next_in and avail_in may be modified, but next_out
  77944. and avail_out are unchanged.)
  77945. */
  77946. ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm,
  77947. const Bytef *dictionary,
  77948. uInt dictLength));
  77949. /*
  77950. Initializes the decompression dictionary from the given uncompressed byte
  77951. sequence. This function must be called immediately after a call of inflate,
  77952. if that call returned Z_NEED_DICT. The dictionary chosen by the compressor
  77953. can be determined from the adler32 value returned by that call of inflate.
  77954. The compressor and decompressor must use exactly the same dictionary (see
  77955. deflateSetDictionary). For raw inflate, this function can be called
  77956. immediately after inflateInit2() or inflateReset() and before any call of
  77957. inflate() to set the dictionary. The application must insure that the
  77958. dictionary that was used for compression is provided.
  77959. inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
  77960. parameter is invalid (such as NULL dictionary) or the stream state is
  77961. inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
  77962. expected one (incorrect adler32 value). inflateSetDictionary does not
  77963. perform any decompression: this will be done by subsequent calls of
  77964. inflate().
  77965. */
  77966. ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm));
  77967. /*
  77968. Skips invalid compressed data until a full flush point (see above the
  77969. description of deflate with Z_FULL_FLUSH) can be found, or until all
  77970. available input is skipped. No output is provided.
  77971. inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR
  77972. if no more input was provided, Z_DATA_ERROR if no flush point has been found,
  77973. or Z_STREAM_ERROR if the stream structure was inconsistent. In the success
  77974. case, the application may save the current current value of total_in which
  77975. indicates where valid compressed data was found. In the error case, the
  77976. application may repeatedly call inflateSync, providing more input each time,
  77977. until success or end of the input data.
  77978. */
  77979. ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest,
  77980. z_streamp source));
  77981. /*
  77982. Sets the destination stream as a complete copy of the source stream.
  77983. This function can be useful when randomly accessing a large stream. The
  77984. first pass through the stream can periodically record the inflate state,
  77985. allowing restarting inflate at those points when randomly accessing the
  77986. stream.
  77987. inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  77988. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  77989. (such as zalloc being NULL). msg is left unchanged in both source and
  77990. destination.
  77991. */
  77992. ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm));
  77993. /*
  77994. This function is equivalent to inflateEnd followed by inflateInit,
  77995. but does not free and reallocate all the internal decompression state.
  77996. The stream will keep attributes that may have been set by inflateInit2.
  77997. inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  77998. stream state was inconsistent (such as zalloc or state being NULL).
  77999. */
  78000. ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm,
  78001. int bits,
  78002. int value));
  78003. /*
  78004. This function inserts bits in the inflate input stream. The intent is
  78005. that this function is used to start inflating at a bit position in the
  78006. middle of a byte. The provided bits will be used before any bytes are used
  78007. from next_in. This function should only be used with raw inflate, and
  78008. should be used before the first inflate() call after inflateInit2() or
  78009. inflateReset(). bits must be less than or equal to 16, and that many of the
  78010. least significant bits of value will be inserted in the input.
  78011. inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  78012. stream state was inconsistent.
  78013. */
  78014. ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm,
  78015. gz_headerp head));
  78016. /*
  78017. inflateGetHeader() requests that gzip header information be stored in the
  78018. provided gz_header structure. inflateGetHeader() may be called after
  78019. inflateInit2() or inflateReset(), and before the first call of inflate().
  78020. As inflate() processes the gzip stream, head->done is zero until the header
  78021. is completed, at which time head->done is set to one. If a zlib stream is
  78022. being decoded, then head->done is set to -1 to indicate that there will be
  78023. no gzip header information forthcoming. Note that Z_BLOCK can be used to
  78024. force inflate() to return immediately after header processing is complete
  78025. and before any actual data is decompressed.
  78026. The text, time, xflags, and os fields are filled in with the gzip header
  78027. contents. hcrc is set to true if there is a header CRC. (The header CRC
  78028. was valid if done is set to one.) If extra is not Z_NULL, then extra_max
  78029. contains the maximum number of bytes to write to extra. Once done is true,
  78030. extra_len contains the actual extra field length, and extra contains the
  78031. extra field, or that field truncated if extra_max is less than extra_len.
  78032. If name is not Z_NULL, then up to name_max characters are written there,
  78033. terminated with a zero unless the length is greater than name_max. If
  78034. comment is not Z_NULL, then up to comm_max characters are written there,
  78035. terminated with a zero unless the length is greater than comm_max. When
  78036. any of extra, name, or comment are not Z_NULL and the respective field is
  78037. not present in the header, then that field is set to Z_NULL to signal its
  78038. absence. This allows the use of deflateSetHeader() with the returned
  78039. structure to duplicate the header. However if those fields are set to
  78040. allocated memory, then the application will need to save those pointers
  78041. elsewhere so that they can be eventually freed.
  78042. If inflateGetHeader is not used, then the header information is simply
  78043. discarded. The header is always checked for validity, including the header
  78044. CRC if present. inflateReset() will reset the process to discard the header
  78045. information. The application would need to call inflateGetHeader() again to
  78046. retrieve the header from the next gzip stream.
  78047. inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  78048. stream state was inconsistent.
  78049. */
  78050. /*
  78051. ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits,
  78052. unsigned char FAR *window));
  78053. Initialize the internal stream state for decompression using inflateBack()
  78054. calls. The fields zalloc, zfree and opaque in strm must be initialized
  78055. before the call. If zalloc and zfree are Z_NULL, then the default library-
  78056. derived memory allocation routines are used. windowBits is the base two
  78057. logarithm of the window size, in the range 8..15. window is a caller
  78058. supplied buffer of that size. Except for special applications where it is
  78059. assured that deflate was used with small window sizes, windowBits must be 15
  78060. and a 32K byte window must be supplied to be able to decompress general
  78061. deflate streams.
  78062. See inflateBack() for the usage of these routines.
  78063. inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of
  78064. the paramaters are invalid, Z_MEM_ERROR if the internal state could not
  78065. be allocated, or Z_VERSION_ERROR if the version of the library does not
  78066. match the version of the header file.
  78067. */
  78068. typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *));
  78069. typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned));
  78070. ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm,
  78071. in_func in, void FAR *in_desc,
  78072. out_func out, void FAR *out_desc));
  78073. /*
  78074. inflateBack() does a raw inflate with a single call using a call-back
  78075. interface for input and output. This is more efficient than inflate() for
  78076. file i/o applications in that it avoids copying between the output and the
  78077. sliding window by simply making the window itself the output buffer. This
  78078. function trusts the application to not change the output buffer passed by
  78079. the output function, at least until inflateBack() returns.
  78080. inflateBackInit() must be called first to allocate the internal state
  78081. and to initialize the state with the user-provided window buffer.
  78082. inflateBack() may then be used multiple times to inflate a complete, raw
  78083. deflate stream with each call. inflateBackEnd() is then called to free
  78084. the allocated state.
  78085. A raw deflate stream is one with no zlib or gzip header or trailer.
  78086. This routine would normally be used in a utility that reads zip or gzip
  78087. files and writes out uncompressed files. The utility would decode the
  78088. header and process the trailer on its own, hence this routine expects
  78089. only the raw deflate stream to decompress. This is different from the
  78090. normal behavior of inflate(), which expects either a zlib or gzip header and
  78091. trailer around the deflate stream.
  78092. inflateBack() uses two subroutines supplied by the caller that are then
  78093. called by inflateBack() for input and output. inflateBack() calls those
  78094. routines until it reads a complete deflate stream and writes out all of the
  78095. uncompressed data, or until it encounters an error. The function's
  78096. parameters and return types are defined above in the in_func and out_func
  78097. typedefs. inflateBack() will call in(in_desc, &buf) which should return the
  78098. number of bytes of provided input, and a pointer to that input in buf. If
  78099. there is no input available, in() must return zero--buf is ignored in that
  78100. case--and inflateBack() will return a buffer error. inflateBack() will call
  78101. out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out()
  78102. should return zero on success, or non-zero on failure. If out() returns
  78103. non-zero, inflateBack() will return with an error. Neither in() nor out()
  78104. are permitted to change the contents of the window provided to
  78105. inflateBackInit(), which is also the buffer that out() uses to write from.
  78106. The length written by out() will be at most the window size. Any non-zero
  78107. amount of input may be provided by in().
  78108. For convenience, inflateBack() can be provided input on the first call by
  78109. setting strm->next_in and strm->avail_in. If that input is exhausted, then
  78110. in() will be called. Therefore strm->next_in must be initialized before
  78111. calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called
  78112. immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in
  78113. must also be initialized, and then if strm->avail_in is not zero, input will
  78114. initially be taken from strm->next_in[0 .. strm->avail_in - 1].
  78115. The in_desc and out_desc parameters of inflateBack() is passed as the
  78116. first parameter of in() and out() respectively when they are called. These
  78117. descriptors can be optionally used to pass any information that the caller-
  78118. supplied in() and out() functions need to do their job.
  78119. On return, inflateBack() will set strm->next_in and strm->avail_in to
  78120. pass back any unused input that was provided by the last in() call. The
  78121. return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR
  78122. if in() or out() returned an error, Z_DATA_ERROR if there was a format
  78123. error in the deflate stream (in which case strm->msg is set to indicate the
  78124. nature of the error), or Z_STREAM_ERROR if the stream was not properly
  78125. initialized. In the case of Z_BUF_ERROR, an input or output error can be
  78126. distinguished using strm->next_in which will be Z_NULL only if in() returned
  78127. an error. If strm->next is not Z_NULL, then the Z_BUF_ERROR was due to
  78128. out() returning non-zero. (in() will always be called before out(), so
  78129. strm->next_in is assured to be defined if out() returns non-zero.) Note
  78130. that inflateBack() cannot return Z_OK.
  78131. */
  78132. ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm));
  78133. /*
  78134. All memory allocated by inflateBackInit() is freed.
  78135. inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream
  78136. state was inconsistent.
  78137. */
  78138. //ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void));
  78139. /* Return flags indicating compile-time options.
  78140. Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other:
  78141. 1.0: size of uInt
  78142. 3.2: size of uLong
  78143. 5.4: size of voidpf (pointer)
  78144. 7.6: size of z_off_t
  78145. Compiler, assembler, and debug options:
  78146. 8: DEBUG
  78147. 9: ASMV or ASMINF -- use ASM code
  78148. 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention
  78149. 11: 0 (reserved)
  78150. One-time table building (smaller code, but not thread-safe if true):
  78151. 12: BUILDFIXED -- build static block decoding tables when needed
  78152. 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed
  78153. 14,15: 0 (reserved)
  78154. Library content (indicates missing functionality):
  78155. 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking
  78156. deflate code when not needed)
  78157. 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect
  78158. and decode gzip streams (to avoid linking crc code)
  78159. 18-19: 0 (reserved)
  78160. Operation variations (changes in library functionality):
  78161. 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate
  78162. 21: FASTEST -- deflate algorithm with only one, lowest compression level
  78163. 22,23: 0 (reserved)
  78164. The sprintf variant used by gzprintf (zero is best):
  78165. 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format
  78166. 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure!
  78167. 26: 0 = returns value, 1 = void -- 1 means inferred string length returned
  78168. Remainder:
  78169. 27-31: 0 (reserved)
  78170. */
  78171. /* utility functions */
  78172. /*
  78173. The following utility functions are implemented on top of the
  78174. basic stream-oriented functions. To simplify the interface, some
  78175. default options are assumed (compression level and memory usage,
  78176. standard memory allocation functions). The source code of these
  78177. utility functions can easily be modified if you need special options.
  78178. */
  78179. ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen,
  78180. const Bytef *source, uLong sourceLen));
  78181. /*
  78182. Compresses the source buffer into the destination buffer. sourceLen is
  78183. the byte length of the source buffer. Upon entry, destLen is the total
  78184. size of the destination buffer, which must be at least the value returned
  78185. by compressBound(sourceLen). Upon exit, destLen is the actual size of the
  78186. compressed buffer.
  78187. This function can be used to compress a whole file at once if the
  78188. input file is mmap'ed.
  78189. compress returns Z_OK if success, Z_MEM_ERROR if there was not
  78190. enough memory, Z_BUF_ERROR if there was not enough room in the output
  78191. buffer.
  78192. */
  78193. ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen,
  78194. const Bytef *source, uLong sourceLen,
  78195. int level));
  78196. /*
  78197. Compresses the source buffer into the destination buffer. The level
  78198. parameter has the same meaning as in deflateInit. sourceLen is the byte
  78199. length of the source buffer. Upon entry, destLen is the total size of the
  78200. destination buffer, which must be at least the value returned by
  78201. compressBound(sourceLen). Upon exit, destLen is the actual size of the
  78202. compressed buffer.
  78203. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78204. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  78205. Z_STREAM_ERROR if the level parameter is invalid.
  78206. */
  78207. ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen));
  78208. /*
  78209. compressBound() returns an upper bound on the compressed size after
  78210. compress() or compress2() on sourceLen bytes. It would be used before
  78211. a compress() or compress2() call to allocate the destination buffer.
  78212. */
  78213. ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen,
  78214. const Bytef *source, uLong sourceLen));
  78215. /*
  78216. Decompresses the source buffer into the destination buffer. sourceLen is
  78217. the byte length of the source buffer. Upon entry, destLen is the total
  78218. size of the destination buffer, which must be large enough to hold the
  78219. entire uncompressed data. (The size of the uncompressed data must have
  78220. been saved previously by the compressor and transmitted to the decompressor
  78221. by some mechanism outside the scope of this compression library.)
  78222. Upon exit, destLen is the actual size of the compressed buffer.
  78223. This function can be used to decompress a whole file at once if the
  78224. input file is mmap'ed.
  78225. uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
  78226. enough memory, Z_BUF_ERROR if there was not enough room in the output
  78227. buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete.
  78228. */
  78229. typedef voidp gzFile;
  78230. ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode));
  78231. /*
  78232. Opens a gzip (.gz) file for reading or writing. The mode parameter
  78233. is as in fopen ("rb" or "wb") but can also include a compression level
  78234. ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for
  78235. Huffman only compression as in "wb1h", or 'R' for run-length encoding
  78236. as in "wb1R". (See the description of deflateInit2 for more information
  78237. about the strategy parameter.)
  78238. gzopen can be used to read a file which is not in gzip format; in this
  78239. case gzread will directly read from the file without decompression.
  78240. gzopen returns NULL if the file could not be opened or if there was
  78241. insufficient memory to allocate the (de)compression state; errno
  78242. can be checked to distinguish the two cases (if errno is zero, the
  78243. zlib error is Z_MEM_ERROR). */
  78244. ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode));
  78245. /*
  78246. gzdopen() associates a gzFile with the file descriptor fd. File
  78247. descriptors are obtained from calls like open, dup, creat, pipe or
  78248. fileno (in the file has been previously opened with fopen).
  78249. The mode parameter is as in gzopen.
  78250. The next call of gzclose on the returned gzFile will also close the
  78251. file descriptor fd, just like fclose(fdopen(fd), mode) closes the file
  78252. descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode).
  78253. gzdopen returns NULL if there was insufficient memory to allocate
  78254. the (de)compression state.
  78255. */
  78256. ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy));
  78257. /*
  78258. Dynamically update the compression level or strategy. See the description
  78259. of deflateInit2 for the meaning of these parameters.
  78260. gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not
  78261. opened for writing.
  78262. */
  78263. ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len));
  78264. /*
  78265. Reads the given number of uncompressed bytes from the compressed file.
  78266. If the input file was not in gzip format, gzread copies the given number
  78267. of bytes into the buffer.
  78268. gzread returns the number of uncompressed bytes actually read (0 for
  78269. end of file, -1 for error). */
  78270. ZEXTERN int ZEXPORT gzwrite OF((gzFile file,
  78271. voidpc buf, unsigned len));
  78272. /*
  78273. Writes the given number of uncompressed bytes into the compressed file.
  78274. gzwrite returns the number of uncompressed bytes actually written
  78275. (0 in case of error).
  78276. */
  78277. ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...));
  78278. /*
  78279. Converts, formats, and writes the args to the compressed file under
  78280. control of the format string, as in fprintf. gzprintf returns the number of
  78281. uncompressed bytes actually written (0 in case of error). The number of
  78282. uncompressed bytes written is limited to 4095. The caller should assure that
  78283. this limit is not exceeded. If it is exceeded, then gzprintf() will return
  78284. return an error (0) with nothing written. In this case, there may also be a
  78285. buffer overflow with unpredictable consequences, which is possible only if
  78286. zlib was compiled with the insecure functions sprintf() or vsprintf()
  78287. because the secure snprintf() or vsnprintf() functions were not available.
  78288. */
  78289. ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s));
  78290. /*
  78291. Writes the given null-terminated string to the compressed file, excluding
  78292. the terminating null character.
  78293. gzputs returns the number of characters written, or -1 in case of error.
  78294. */
  78295. ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len));
  78296. /*
  78297. Reads bytes from the compressed file until len-1 characters are read, or
  78298. a newline character is read and transferred to buf, or an end-of-file
  78299. condition is encountered. The string is then terminated with a null
  78300. character.
  78301. gzgets returns buf, or Z_NULL in case of error.
  78302. */
  78303. ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c));
  78304. /*
  78305. Writes c, converted to an unsigned char, into the compressed file.
  78306. gzputc returns the value that was written, or -1 in case of error.
  78307. */
  78308. ZEXTERN int ZEXPORT gzgetc OF((gzFile file));
  78309. /*
  78310. Reads one byte from the compressed file. gzgetc returns this byte
  78311. or -1 in case of end of file or error.
  78312. */
  78313. ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file));
  78314. /*
  78315. Push one character back onto the stream to be read again later.
  78316. Only one character of push-back is allowed. gzungetc() returns the
  78317. character pushed, or -1 on failure. gzungetc() will fail if a
  78318. character has been pushed but not read yet, or if c is -1. The pushed
  78319. character will be discarded if the stream is repositioned with gzseek()
  78320. or gzrewind().
  78321. */
  78322. ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush));
  78323. /*
  78324. Flushes all pending output into the compressed file. The parameter
  78325. flush is as in the deflate() function. The return value is the zlib
  78326. error number (see function gzerror below). gzflush returns Z_OK if
  78327. the flush parameter is Z_FINISH and all output could be flushed.
  78328. gzflush should be called only when strictly necessary because it can
  78329. degrade compression.
  78330. */
  78331. ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file,
  78332. z_off_t offset, int whence));
  78333. /*
  78334. Sets the starting position for the next gzread or gzwrite on the
  78335. given compressed file. The offset represents a number of bytes in the
  78336. uncompressed data stream. The whence parameter is defined as in lseek(2);
  78337. the value SEEK_END is not supported.
  78338. If the file is opened for reading, this function is emulated but can be
  78339. extremely slow. If the file is opened for writing, only forward seeks are
  78340. supported; gzseek then compresses a sequence of zeroes up to the new
  78341. starting position.
  78342. gzseek returns the resulting offset location as measured in bytes from
  78343. the beginning of the uncompressed stream, or -1 in case of error, in
  78344. particular if the file is opened for writing and the new starting position
  78345. would be before the current position.
  78346. */
  78347. ZEXTERN int ZEXPORT gzrewind OF((gzFile file));
  78348. /*
  78349. Rewinds the given file. This function is supported only for reading.
  78350. gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
  78351. */
  78352. ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file));
  78353. /*
  78354. Returns the starting position for the next gzread or gzwrite on the
  78355. given compressed file. This position represents a number of bytes in the
  78356. uncompressed data stream.
  78357. gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
  78358. */
  78359. ZEXTERN int ZEXPORT gzeof OF((gzFile file));
  78360. /*
  78361. Returns 1 when EOF has previously been detected reading the given
  78362. input stream, otherwise zero.
  78363. */
  78364. ZEXTERN int ZEXPORT gzdirect OF((gzFile file));
  78365. /*
  78366. Returns 1 if file is being read directly without decompression, otherwise
  78367. zero.
  78368. */
  78369. ZEXTERN int ZEXPORT gzclose OF((gzFile file));
  78370. /*
  78371. Flushes all pending output if necessary, closes the compressed file
  78372. and deallocates all the (de)compression state. The return value is the zlib
  78373. error number (see function gzerror below).
  78374. */
  78375. ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum));
  78376. /*
  78377. Returns the error message for the last error which occurred on the
  78378. given compressed file. errnum is set to zlib error number. If an
  78379. error occurred in the file system and not in the compression library,
  78380. errnum is set to Z_ERRNO and the application may consult errno
  78381. to get the exact error code.
  78382. */
  78383. ZEXTERN void ZEXPORT gzclearerr OF((gzFile file));
  78384. /*
  78385. Clears the error and end-of-file flags for file. This is analogous to the
  78386. clearerr() function in stdio. This is useful for continuing to read a gzip
  78387. file that is being written concurrently.
  78388. */
  78389. /* checksum functions */
  78390. /*
  78391. These functions are not related to compression but are exported
  78392. anyway because they might be useful in applications using the
  78393. compression library.
  78394. */
  78395. ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len));
  78396. /*
  78397. Update a running Adler-32 checksum with the bytes buf[0..len-1] and
  78398. return the updated checksum. If buf is NULL, this function returns
  78399. the required initial value for the checksum.
  78400. An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
  78401. much faster. Usage example:
  78402. uLong adler = adler32(0L, Z_NULL, 0);
  78403. while (read_buffer(buffer, length) != EOF) {
  78404. adler = adler32(adler, buffer, length);
  78405. }
  78406. if (adler != original_adler) error();
  78407. */
  78408. ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2,
  78409. z_off_t len2));
  78410. /*
  78411. Combine two Adler-32 checksums into one. For two sequences of bytes, seq1
  78412. and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for
  78413. each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of
  78414. seq1 and seq2 concatenated, requiring only adler1, adler2, and len2.
  78415. */
  78416. ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len));
  78417. /*
  78418. Update a running CRC-32 with the bytes buf[0..len-1] and return the
  78419. updated CRC-32. If buf is NULL, this function returns the required initial
  78420. value for the for the crc. Pre- and post-conditioning (one's complement) is
  78421. performed within this function so it shouldn't be done by the application.
  78422. Usage example:
  78423. uLong crc = crc32(0L, Z_NULL, 0);
  78424. while (read_buffer(buffer, length) != EOF) {
  78425. crc = crc32(crc, buffer, length);
  78426. }
  78427. if (crc != original_crc) error();
  78428. */
  78429. ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2));
  78430. /*
  78431. Combine two CRC-32 check values into one. For two sequences of bytes,
  78432. seq1 and seq2 with lengths len1 and len2, CRC-32 check values were
  78433. calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32
  78434. check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and
  78435. len2.
  78436. */
  78437. /* various hacks, don't look :) */
  78438. /* deflateInit and inflateInit are macros to allow checking the zlib version
  78439. * and the compiler's view of z_stream:
  78440. */
  78441. ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level,
  78442. const char *version, int stream_size));
  78443. ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm,
  78444. const char *version, int stream_size));
  78445. ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method,
  78446. int windowBits, int memLevel,
  78447. int strategy, const char *version,
  78448. int stream_size));
  78449. ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits,
  78450. const char *version, int stream_size));
  78451. ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits,
  78452. unsigned char FAR *window,
  78453. const char *version,
  78454. int stream_size));
  78455. #define deflateInit(strm, level) \
  78456. deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream))
  78457. #define inflateInit(strm) \
  78458. inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream))
  78459. #define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
  78460. deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
  78461. (strategy), ZLIB_VERSION, sizeof(z_stream))
  78462. #define inflateInit2(strm, windowBits) \
  78463. inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream))
  78464. #define inflateBackInit(strm, windowBits, window) \
  78465. inflateBackInit_((strm), (windowBits), (window), \
  78466. ZLIB_VERSION, sizeof(z_stream))
  78467. #if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL)
  78468. struct internal_state {int dummy;}; /* hack for buggy compilers */
  78469. #endif
  78470. ZEXTERN const char * ZEXPORT zError OF((int));
  78471. ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp z));
  78472. ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void));
  78473. #ifdef __cplusplus
  78474. }
  78475. #endif
  78476. #endif /* ZLIB_H */
  78477. /*** End of inlined file: zlib.h ***/
  78478. #undef OS_CODE
  78479. #else
  78480. #include <zlib.h>
  78481. #endif
  78482. }
  78483. BEGIN_JUCE_NAMESPACE
  78484. // internal helper object that holds the zlib structures so they don't have to be
  78485. // included publicly.
  78486. class GZIPCompressorHelper
  78487. {
  78488. public:
  78489. GZIPCompressorHelper (const int compressionLevel, const bool nowrap)
  78490. : data (0),
  78491. dataSize (0),
  78492. compLevel (compressionLevel),
  78493. strategy (0),
  78494. setParams (true),
  78495. streamIsValid (false),
  78496. finished (false),
  78497. shouldFinish (false)
  78498. {
  78499. using namespace zlibNamespace;
  78500. zerostruct (stream);
  78501. streamIsValid = (deflateInit2 (&stream, compLevel, Z_DEFLATED,
  78502. nowrap ? -MAX_WBITS : MAX_WBITS,
  78503. 8, strategy) == Z_OK);
  78504. }
  78505. ~GZIPCompressorHelper()
  78506. {
  78507. using namespace zlibNamespace;
  78508. if (streamIsValid)
  78509. deflateEnd (&stream);
  78510. }
  78511. bool needsInput() const throw()
  78512. {
  78513. return dataSize <= 0;
  78514. }
  78515. void setInput (const uint8* const newData, const int size) throw()
  78516. {
  78517. data = newData;
  78518. dataSize = size;
  78519. }
  78520. int doNextBlock (uint8* const dest, const int destSize) throw()
  78521. {
  78522. using namespace zlibNamespace;
  78523. if (streamIsValid)
  78524. {
  78525. stream.next_in = const_cast <uint8*> (data);
  78526. stream.next_out = dest;
  78527. stream.avail_in = dataSize;
  78528. stream.avail_out = destSize;
  78529. const int result = setParams ? deflateParams (&stream, compLevel, strategy)
  78530. : deflate (&stream, shouldFinish ? Z_FINISH : Z_NO_FLUSH);
  78531. setParams = false;
  78532. switch (result)
  78533. {
  78534. case Z_STREAM_END:
  78535. finished = true;
  78536. // Deliberate fall-through..
  78537. case Z_OK:
  78538. data += dataSize - stream.avail_in;
  78539. dataSize = stream.avail_in;
  78540. return destSize - stream.avail_out;
  78541. default:
  78542. break;
  78543. }
  78544. }
  78545. return 0;
  78546. }
  78547. private:
  78548. zlibNamespace::z_stream stream;
  78549. const uint8* data;
  78550. int dataSize, compLevel, strategy;
  78551. bool setParams, streamIsValid;
  78552. public:
  78553. bool finished, shouldFinish;
  78554. };
  78555. const int gzipCompBufferSize = 32768;
  78556. GZIPCompressorOutputStream::GZIPCompressorOutputStream (OutputStream* const destStream_,
  78557. int compressionLevel,
  78558. const bool deleteDestStream,
  78559. const bool noWrap)
  78560. : destStream (destStream_),
  78561. streamToDelete (deleteDestStream ? destStream_ : 0),
  78562. buffer (gzipCompBufferSize)
  78563. {
  78564. if (compressionLevel < 1 || compressionLevel > 9)
  78565. compressionLevel = -1;
  78566. helper = new GZIPCompressorHelper (compressionLevel, noWrap);
  78567. }
  78568. GZIPCompressorOutputStream::~GZIPCompressorOutputStream()
  78569. {
  78570. flush();
  78571. }
  78572. void GZIPCompressorOutputStream::flush()
  78573. {
  78574. if (! helper->finished)
  78575. {
  78576. helper->shouldFinish = true;
  78577. while (! helper->finished)
  78578. doNextBlock();
  78579. }
  78580. destStream->flush();
  78581. }
  78582. bool GZIPCompressorOutputStream::write (const void* destBuffer, int howMany)
  78583. {
  78584. if (! helper->finished)
  78585. {
  78586. helper->setInput (static_cast <const uint8*> (destBuffer), howMany);
  78587. while (! helper->needsInput())
  78588. {
  78589. if (! doNextBlock())
  78590. return false;
  78591. }
  78592. }
  78593. return true;
  78594. }
  78595. bool GZIPCompressorOutputStream::doNextBlock()
  78596. {
  78597. const int len = helper->doNextBlock (buffer, gzipCompBufferSize);
  78598. if (len > 0)
  78599. return destStream->write (buffer, len);
  78600. else
  78601. return true;
  78602. }
  78603. int64 GZIPCompressorOutputStream::getPosition()
  78604. {
  78605. return destStream->getPosition();
  78606. }
  78607. bool GZIPCompressorOutputStream::setPosition (int64 /*newPosition*/)
  78608. {
  78609. jassertfalse; // can't do it!
  78610. return false;
  78611. }
  78612. END_JUCE_NAMESPACE
  78613. /*** End of inlined file: juce_GZIPCompressorOutputStream.cpp ***/
  78614. /*** Start of inlined file: juce_GZIPDecompressorInputStream.cpp ***/
  78615. #if JUCE_MSVC
  78616. #pragma warning (push)
  78617. #pragma warning (disable: 4309 4305)
  78618. #endif
  78619. namespace zlibNamespace
  78620. {
  78621. #if JUCE_INCLUDE_ZLIB_CODE
  78622. extern "C"
  78623. {
  78624. #undef OS_CODE
  78625. #undef fdopen
  78626. #define ZLIB_INTERNAL
  78627. #define NO_DUMMY_DECL
  78628. /*** Start of inlined file: adler32.c ***/
  78629. /* @(#) $Id: adler32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  78630. #define ZLIB_INTERNAL
  78631. #define BASE 65521UL /* largest prime smaller than 65536 */
  78632. #define NMAX 5552
  78633. /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
  78634. #define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;}
  78635. #define DO2(buf,i) DO1(buf,i); DO1(buf,i+1);
  78636. #define DO4(buf,i) DO2(buf,i); DO2(buf,i+2);
  78637. #define DO8(buf,i) DO4(buf,i); DO4(buf,i+4);
  78638. #define DO16(buf) DO8(buf,0); DO8(buf,8);
  78639. /* use NO_DIVIDE if your processor does not do division in hardware */
  78640. #ifdef NO_DIVIDE
  78641. # define MOD(a) \
  78642. do { \
  78643. if (a >= (BASE << 16)) a -= (BASE << 16); \
  78644. if (a >= (BASE << 15)) a -= (BASE << 15); \
  78645. if (a >= (BASE << 14)) a -= (BASE << 14); \
  78646. if (a >= (BASE << 13)) a -= (BASE << 13); \
  78647. if (a >= (BASE << 12)) a -= (BASE << 12); \
  78648. if (a >= (BASE << 11)) a -= (BASE << 11); \
  78649. if (a >= (BASE << 10)) a -= (BASE << 10); \
  78650. if (a >= (BASE << 9)) a -= (BASE << 9); \
  78651. if (a >= (BASE << 8)) a -= (BASE << 8); \
  78652. if (a >= (BASE << 7)) a -= (BASE << 7); \
  78653. if (a >= (BASE << 6)) a -= (BASE << 6); \
  78654. if (a >= (BASE << 5)) a -= (BASE << 5); \
  78655. if (a >= (BASE << 4)) a -= (BASE << 4); \
  78656. if (a >= (BASE << 3)) a -= (BASE << 3); \
  78657. if (a >= (BASE << 2)) a -= (BASE << 2); \
  78658. if (a >= (BASE << 1)) a -= (BASE << 1); \
  78659. if (a >= BASE) a -= BASE; \
  78660. } while (0)
  78661. # define MOD4(a) \
  78662. do { \
  78663. if (a >= (BASE << 4)) a -= (BASE << 4); \
  78664. if (a >= (BASE << 3)) a -= (BASE << 3); \
  78665. if (a >= (BASE << 2)) a -= (BASE << 2); \
  78666. if (a >= (BASE << 1)) a -= (BASE << 1); \
  78667. if (a >= BASE) a -= BASE; \
  78668. } while (0)
  78669. #else
  78670. # define MOD(a) a %= BASE
  78671. # define MOD4(a) a %= BASE
  78672. #endif
  78673. /* ========================================================================= */
  78674. uLong ZEXPORT adler32(uLong adler, const Bytef *buf, uInt len)
  78675. {
  78676. unsigned long sum2;
  78677. unsigned n;
  78678. /* split Adler-32 into component sums */
  78679. sum2 = (adler >> 16) & 0xffff;
  78680. adler &= 0xffff;
  78681. /* in case user likes doing a byte at a time, keep it fast */
  78682. if (len == 1) {
  78683. adler += buf[0];
  78684. if (adler >= BASE)
  78685. adler -= BASE;
  78686. sum2 += adler;
  78687. if (sum2 >= BASE)
  78688. sum2 -= BASE;
  78689. return adler | (sum2 << 16);
  78690. }
  78691. /* initial Adler-32 value (deferred check for len == 1 speed) */
  78692. if (buf == Z_NULL)
  78693. return 1L;
  78694. /* in case short lengths are provided, keep it somewhat fast */
  78695. if (len < 16) {
  78696. while (len--) {
  78697. adler += *buf++;
  78698. sum2 += adler;
  78699. }
  78700. if (adler >= BASE)
  78701. adler -= BASE;
  78702. MOD4(sum2); /* only added so many BASE's */
  78703. return adler | (sum2 << 16);
  78704. }
  78705. /* do length NMAX blocks -- requires just one modulo operation */
  78706. while (len >= NMAX) {
  78707. len -= NMAX;
  78708. n = NMAX / 16; /* NMAX is divisible by 16 */
  78709. do {
  78710. DO16(buf); /* 16 sums unrolled */
  78711. buf += 16;
  78712. } while (--n);
  78713. MOD(adler);
  78714. MOD(sum2);
  78715. }
  78716. /* do remaining bytes (less than NMAX, still just one modulo) */
  78717. if (len) { /* avoid modulos if none remaining */
  78718. while (len >= 16) {
  78719. len -= 16;
  78720. DO16(buf);
  78721. buf += 16;
  78722. }
  78723. while (len--) {
  78724. adler += *buf++;
  78725. sum2 += adler;
  78726. }
  78727. MOD(adler);
  78728. MOD(sum2);
  78729. }
  78730. /* return recombined sums */
  78731. return adler | (sum2 << 16);
  78732. }
  78733. /* ========================================================================= */
  78734. uLong ZEXPORT adler32_combine(uLong adler1, uLong adler2, z_off_t len2)
  78735. {
  78736. unsigned long sum1;
  78737. unsigned long sum2;
  78738. unsigned rem;
  78739. /* the derivation of this formula is left as an exercise for the reader */
  78740. rem = (unsigned)(len2 % BASE);
  78741. sum1 = adler1 & 0xffff;
  78742. sum2 = rem * sum1;
  78743. MOD(sum2);
  78744. sum1 += (adler2 & 0xffff) + BASE - 1;
  78745. sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem;
  78746. if (sum1 > BASE) sum1 -= BASE;
  78747. if (sum1 > BASE) sum1 -= BASE;
  78748. if (sum2 > (BASE << 1)) sum2 -= (BASE << 1);
  78749. if (sum2 > BASE) sum2 -= BASE;
  78750. return sum1 | (sum2 << 16);
  78751. }
  78752. /*** End of inlined file: adler32.c ***/
  78753. /*** Start of inlined file: compress.c ***/
  78754. /* @(#) $Id: compress.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  78755. #define ZLIB_INTERNAL
  78756. /* ===========================================================================
  78757. Compresses the source buffer into the destination buffer. The level
  78758. parameter has the same meaning as in deflateInit. sourceLen is the byte
  78759. length of the source buffer. Upon entry, destLen is the total size of the
  78760. destination buffer, which must be at least 0.1% larger than sourceLen plus
  78761. 12 bytes. Upon exit, destLen is the actual size of the compressed buffer.
  78762. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78763. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  78764. Z_STREAM_ERROR if the level parameter is invalid.
  78765. */
  78766. int ZEXPORT compress2 (Bytef *dest, uLongf *destLen, const Bytef *source,
  78767. uLong sourceLen, int level)
  78768. {
  78769. z_stream stream;
  78770. int err;
  78771. stream.next_in = (Bytef*)source;
  78772. stream.avail_in = (uInt)sourceLen;
  78773. #ifdef MAXSEG_64K
  78774. /* Check for source > 64K on 16-bit machine: */
  78775. if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;
  78776. #endif
  78777. stream.next_out = dest;
  78778. stream.avail_out = (uInt)*destLen;
  78779. if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
  78780. stream.zalloc = (alloc_func)0;
  78781. stream.zfree = (free_func)0;
  78782. stream.opaque = (voidpf)0;
  78783. err = deflateInit(&stream, level);
  78784. if (err != Z_OK) return err;
  78785. err = deflate(&stream, Z_FINISH);
  78786. if (err != Z_STREAM_END) {
  78787. deflateEnd(&stream);
  78788. return err == Z_OK ? Z_BUF_ERROR : err;
  78789. }
  78790. *destLen = stream.total_out;
  78791. err = deflateEnd(&stream);
  78792. return err;
  78793. }
  78794. /* ===========================================================================
  78795. */
  78796. int ZEXPORT compress (Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen)
  78797. {
  78798. return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION);
  78799. }
  78800. /* ===========================================================================
  78801. If the default memLevel or windowBits for deflateInit() is changed, then
  78802. this function needs to be updated.
  78803. */
  78804. uLong ZEXPORT compressBound (uLong sourceLen)
  78805. {
  78806. return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + 11;
  78807. }
  78808. /*** End of inlined file: compress.c ***/
  78809. #undef DO1
  78810. #undef DO8
  78811. /*** Start of inlined file: crc32.c ***/
  78812. /* @(#) $Id: crc32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  78813. /*
  78814. Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore
  78815. protection on the static variables used to control the first-use generation
  78816. of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should
  78817. first call get_crc_table() to initialize the tables before allowing more than
  78818. one thread to use crc32().
  78819. */
  78820. #ifdef MAKECRCH
  78821. # include <stdio.h>
  78822. # ifndef DYNAMIC_CRC_TABLE
  78823. # define DYNAMIC_CRC_TABLE
  78824. # endif /* !DYNAMIC_CRC_TABLE */
  78825. #endif /* MAKECRCH */
  78826. /*** Start of inlined file: zutil.h ***/
  78827. /* WARNING: this file should *not* be used by applications. It is
  78828. part of the implementation of the compression library and is
  78829. subject to change. Applications should only use zlib.h.
  78830. */
  78831. /* @(#) $Id: zutil.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  78832. #ifndef ZUTIL_H
  78833. #define ZUTIL_H
  78834. #define ZLIB_INTERNAL
  78835. #ifdef STDC
  78836. # ifndef _WIN32_WCE
  78837. # include <stddef.h>
  78838. # endif
  78839. # include <string.h>
  78840. # include <stdlib.h>
  78841. #endif
  78842. #ifdef NO_ERRNO_H
  78843. # ifdef _WIN32_WCE
  78844. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  78845. * errno. We define it as a global variable to simplify porting.
  78846. * Its value is always 0 and should not be used. We rename it to
  78847. * avoid conflict with other libraries that use the same workaround.
  78848. */
  78849. # define errno z_errno
  78850. # endif
  78851. extern int errno;
  78852. #else
  78853. # ifndef _WIN32_WCE
  78854. # include <errno.h>
  78855. # endif
  78856. #endif
  78857. #ifndef local
  78858. # define local static
  78859. #endif
  78860. /* compile with -Dlocal if your debugger can't find static symbols */
  78861. typedef unsigned char uch;
  78862. typedef uch FAR uchf;
  78863. typedef unsigned short ush;
  78864. typedef ush FAR ushf;
  78865. typedef unsigned long ulg;
  78866. extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */
  78867. /* (size given to avoid silly warnings with Visual C++) */
  78868. #define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)]
  78869. #define ERR_RETURN(strm,err) \
  78870. return (strm->msg = (char*)ERR_MSG(err), (err))
  78871. /* To be used only when the state is known to be valid */
  78872. /* common constants */
  78873. #ifndef DEF_WBITS
  78874. # define DEF_WBITS MAX_WBITS
  78875. #endif
  78876. /* default windowBits for decompression. MAX_WBITS is for compression only */
  78877. #if MAX_MEM_LEVEL >= 8
  78878. # define DEF_MEM_LEVEL 8
  78879. #else
  78880. # define DEF_MEM_LEVEL MAX_MEM_LEVEL
  78881. #endif
  78882. /* default memLevel */
  78883. #define STORED_BLOCK 0
  78884. #define STATIC_TREES 1
  78885. #define DYN_TREES 2
  78886. /* The three kinds of block type */
  78887. #define MIN_MATCH 3
  78888. #define MAX_MATCH 258
  78889. /* The minimum and maximum match lengths */
  78890. #define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */
  78891. /* target dependencies */
  78892. #if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32))
  78893. # define OS_CODE 0x00
  78894. # if defined(__TURBOC__) || defined(__BORLANDC__)
  78895. # if(__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__))
  78896. /* Allow compilation with ANSI keywords only enabled */
  78897. void _Cdecl farfree( void *block );
  78898. void *_Cdecl farmalloc( unsigned long nbytes );
  78899. # else
  78900. # include <alloc.h>
  78901. # endif
  78902. # else /* MSC or DJGPP */
  78903. # include <malloc.h>
  78904. # endif
  78905. #endif
  78906. #ifdef AMIGA
  78907. # define OS_CODE 0x01
  78908. #endif
  78909. #if defined(VAXC) || defined(VMS)
  78910. # define OS_CODE 0x02
  78911. # define F_OPEN(name, mode) \
  78912. fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512")
  78913. #endif
  78914. #if defined(ATARI) || defined(atarist)
  78915. # define OS_CODE 0x05
  78916. #endif
  78917. #ifdef OS2
  78918. # define OS_CODE 0x06
  78919. # ifdef M_I86
  78920. #include <malloc.h>
  78921. # endif
  78922. #endif
  78923. #if defined(MACOS) || TARGET_OS_MAC
  78924. # define OS_CODE 0x07
  78925. # if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os
  78926. # include <unix.h> /* for fdopen */
  78927. # else
  78928. # ifndef fdopen
  78929. # define fdopen(fd,mode) NULL /* No fdopen() */
  78930. # endif
  78931. # endif
  78932. #endif
  78933. #ifdef TOPS20
  78934. # define OS_CODE 0x0a
  78935. #endif
  78936. #ifdef WIN32
  78937. # ifndef __CYGWIN__ /* Cygwin is Unix, not Win32 */
  78938. # define OS_CODE 0x0b
  78939. # endif
  78940. #endif
  78941. #ifdef __50SERIES /* Prime/PRIMOS */
  78942. # define OS_CODE 0x0f
  78943. #endif
  78944. #if defined(_BEOS_) || defined(RISCOS)
  78945. # define fdopen(fd,mode) NULL /* No fdopen() */
  78946. #endif
  78947. #if (defined(_MSC_VER) && (_MSC_VER > 600))
  78948. # if defined(_WIN32_WCE)
  78949. # define fdopen(fd,mode) NULL /* No fdopen() */
  78950. # ifndef _PTRDIFF_T_DEFINED
  78951. typedef int ptrdiff_t;
  78952. # define _PTRDIFF_T_DEFINED
  78953. # endif
  78954. # else
  78955. # define fdopen(fd,type) _fdopen(fd,type)
  78956. # endif
  78957. #endif
  78958. /* common defaults */
  78959. #ifndef OS_CODE
  78960. # define OS_CODE 0x03 /* assume Unix */
  78961. #endif
  78962. #ifndef F_OPEN
  78963. # define F_OPEN(name, mode) fopen((name), (mode))
  78964. #endif
  78965. /* functions */
  78966. #if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550)
  78967. # ifndef HAVE_VSNPRINTF
  78968. # define HAVE_VSNPRINTF
  78969. # endif
  78970. #endif
  78971. #if defined(__CYGWIN__)
  78972. # ifndef HAVE_VSNPRINTF
  78973. # define HAVE_VSNPRINTF
  78974. # endif
  78975. #endif
  78976. #ifndef HAVE_VSNPRINTF
  78977. # ifdef MSDOS
  78978. /* vsnprintf may exist on some MS-DOS compilers (DJGPP?),
  78979. but for now we just assume it doesn't. */
  78980. # define NO_vsnprintf
  78981. # endif
  78982. # ifdef __TURBOC__
  78983. # define NO_vsnprintf
  78984. # endif
  78985. # ifdef WIN32
  78986. /* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */
  78987. # if !defined(vsnprintf) && !defined(NO_vsnprintf)
  78988. # define vsnprintf _vsnprintf
  78989. # endif
  78990. # endif
  78991. # ifdef __SASC
  78992. # define NO_vsnprintf
  78993. # endif
  78994. #endif
  78995. #ifdef VMS
  78996. # define NO_vsnprintf
  78997. #endif
  78998. #if defined(pyr)
  78999. # define NO_MEMCPY
  79000. #endif
  79001. #if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__)
  79002. /* Use our own functions for small and medium model with MSC <= 5.0.
  79003. * You may have to use the same strategy for Borland C (untested).
  79004. * The __SC__ check is for Symantec.
  79005. */
  79006. # define NO_MEMCPY
  79007. #endif
  79008. #if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY)
  79009. # define HAVE_MEMCPY
  79010. #endif
  79011. #ifdef HAVE_MEMCPY
  79012. # ifdef SMALL_MEDIUM /* MSDOS small or medium model */
  79013. # define zmemcpy _fmemcpy
  79014. # define zmemcmp _fmemcmp
  79015. # define zmemzero(dest, len) _fmemset(dest, 0, len)
  79016. # else
  79017. # define zmemcpy memcpy
  79018. # define zmemcmp memcmp
  79019. # define zmemzero(dest, len) memset(dest, 0, len)
  79020. # endif
  79021. #else
  79022. extern void zmemcpy OF((Bytef* dest, const Bytef* source, uInt len));
  79023. extern int zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len));
  79024. extern void zmemzero OF((Bytef* dest, uInt len));
  79025. #endif
  79026. /* Diagnostic functions */
  79027. #ifdef DEBUG
  79028. # include <stdio.h>
  79029. extern int z_verbose;
  79030. extern void z_error OF((const char *m));
  79031. # define Assert(cond,msg) {if(!(cond)) z_error(msg);}
  79032. # define Trace(x) {if (z_verbose>=0) fprintf x ;}
  79033. # define Tracev(x) {if (z_verbose>0) fprintf x ;}
  79034. # define Tracevv(x) {if (z_verbose>1) fprintf x ;}
  79035. # define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;}
  79036. # define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;}
  79037. #else
  79038. # define Assert(cond,msg)
  79039. # define Trace(x)
  79040. # define Tracev(x)
  79041. # define Tracevv(x)
  79042. # define Tracec(c,x)
  79043. # define Tracecv(c,x)
  79044. #endif
  79045. voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size));
  79046. void zcfree OF((voidpf opaque, voidpf ptr));
  79047. #define ZALLOC(strm, items, size) \
  79048. (*((strm)->zalloc))((strm)->opaque, (items), (size))
  79049. #define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr))
  79050. #define TRY_FREE(s, p) {if (p) ZFREE(s, p);}
  79051. #endif /* ZUTIL_H */
  79052. /*** End of inlined file: zutil.h ***/
  79053. /* for STDC and FAR definitions */
  79054. #define local static
  79055. /* Find a four-byte integer type for crc32_little() and crc32_big(). */
  79056. #ifndef NOBYFOUR
  79057. # ifdef STDC /* need ANSI C limits.h to determine sizes */
  79058. # include <limits.h>
  79059. # define BYFOUR
  79060. # if (UINT_MAX == 0xffffffffUL)
  79061. typedef unsigned int u4;
  79062. # else
  79063. # if (ULONG_MAX == 0xffffffffUL)
  79064. typedef unsigned long u4;
  79065. # else
  79066. # if (USHRT_MAX == 0xffffffffUL)
  79067. typedef unsigned short u4;
  79068. # else
  79069. # undef BYFOUR /* can't find a four-byte integer type! */
  79070. # endif
  79071. # endif
  79072. # endif
  79073. # endif /* STDC */
  79074. #endif /* !NOBYFOUR */
  79075. /* Definitions for doing the crc four data bytes at a time. */
  79076. #ifdef BYFOUR
  79077. # define REV(w) (((w)>>24)+(((w)>>8)&0xff00)+ \
  79078. (((w)&0xff00)<<8)+(((w)&0xff)<<24))
  79079. local unsigned long crc32_little OF((unsigned long,
  79080. const unsigned char FAR *, unsigned));
  79081. local unsigned long crc32_big OF((unsigned long,
  79082. const unsigned char FAR *, unsigned));
  79083. # define TBLS 8
  79084. #else
  79085. # define TBLS 1
  79086. #endif /* BYFOUR */
  79087. /* Local functions for crc concatenation */
  79088. local unsigned long gf2_matrix_times OF((unsigned long *mat,
  79089. unsigned long vec));
  79090. local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat));
  79091. #ifdef DYNAMIC_CRC_TABLE
  79092. local volatile int crc_table_empty = 1;
  79093. local unsigned long FAR crc_table[TBLS][256];
  79094. local void make_crc_table OF((void));
  79095. #ifdef MAKECRCH
  79096. local void write_table OF((FILE *, const unsigned long FAR *));
  79097. #endif /* MAKECRCH */
  79098. /*
  79099. Generate tables for a byte-wise 32-bit CRC calculation on the polynomial:
  79100. 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.
  79101. Polynomials over GF(2) are represented in binary, one bit per coefficient,
  79102. with the lowest powers in the most significant bit. Then adding polynomials
  79103. is just exclusive-or, and multiplying a polynomial by x is a right shift by
  79104. one. If we call the above polynomial p, and represent a byte as the
  79105. polynomial q, also with the lowest power in the most significant bit (so the
  79106. byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
  79107. where a mod b means the remainder after dividing a by b.
  79108. This calculation is done using the shift-register method of multiplying and
  79109. taking the remainder. The register is initialized to zero, and for each
  79110. incoming bit, x^32 is added mod p to the register if the bit is a one (where
  79111. x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by
  79112. x (which is shifting right by one and adding x^32 mod p if the bit shifted
  79113. out is a one). We start with the highest power (least significant bit) of
  79114. q and repeat for all eight bits of q.
  79115. The first table is simply the CRC of all possible eight bit values. This is
  79116. all the information needed to generate CRCs on data a byte at a time for all
  79117. combinations of CRC register values and incoming bytes. The remaining tables
  79118. allow for word-at-a-time CRC calculation for both big-endian and little-
  79119. endian machines, where a word is four bytes.
  79120. */
  79121. local void make_crc_table()
  79122. {
  79123. unsigned long c;
  79124. int n, k;
  79125. unsigned long poly; /* polynomial exclusive-or pattern */
  79126. /* terms of polynomial defining this crc (except x^32): */
  79127. static volatile int first = 1; /* flag to limit concurrent making */
  79128. static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};
  79129. /* See if another task is already doing this (not thread-safe, but better
  79130. than nothing -- significantly reduces duration of vulnerability in
  79131. case the advice about DYNAMIC_CRC_TABLE is ignored) */
  79132. if (first) {
  79133. first = 0;
  79134. /* make exclusive-or pattern from polynomial (0xedb88320UL) */
  79135. poly = 0UL;
  79136. for (n = 0; n < sizeof(p)/sizeof(unsigned char); n++)
  79137. poly |= 1UL << (31 - p[n]);
  79138. /* generate a crc for every 8-bit value */
  79139. for (n = 0; n < 256; n++) {
  79140. c = (unsigned long)n;
  79141. for (k = 0; k < 8; k++)
  79142. c = c & 1 ? poly ^ (c >> 1) : c >> 1;
  79143. crc_table[0][n] = c;
  79144. }
  79145. #ifdef BYFOUR
  79146. /* generate crc for each value followed by one, two, and three zeros,
  79147. and then the byte reversal of those as well as the first table */
  79148. for (n = 0; n < 256; n++) {
  79149. c = crc_table[0][n];
  79150. crc_table[4][n] = REV(c);
  79151. for (k = 1; k < 4; k++) {
  79152. c = crc_table[0][c & 0xff] ^ (c >> 8);
  79153. crc_table[k][n] = c;
  79154. crc_table[k + 4][n] = REV(c);
  79155. }
  79156. }
  79157. #endif /* BYFOUR */
  79158. crc_table_empty = 0;
  79159. }
  79160. else { /* not first */
  79161. /* wait for the other guy to finish (not efficient, but rare) */
  79162. while (crc_table_empty)
  79163. ;
  79164. }
  79165. #ifdef MAKECRCH
  79166. /* write out CRC tables to crc32.h */
  79167. {
  79168. FILE *out;
  79169. out = fopen("crc32.h", "w");
  79170. if (out == NULL) return;
  79171. fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n");
  79172. fprintf(out, " * Generated automatically by crc32.c\n */\n\n");
  79173. fprintf(out, "local const unsigned long FAR ");
  79174. fprintf(out, "crc_table[TBLS][256] =\n{\n {\n");
  79175. write_table(out, crc_table[0]);
  79176. # ifdef BYFOUR
  79177. fprintf(out, "#ifdef BYFOUR\n");
  79178. for (k = 1; k < 8; k++) {
  79179. fprintf(out, " },\n {\n");
  79180. write_table(out, crc_table[k]);
  79181. }
  79182. fprintf(out, "#endif\n");
  79183. # endif /* BYFOUR */
  79184. fprintf(out, " }\n};\n");
  79185. fclose(out);
  79186. }
  79187. #endif /* MAKECRCH */
  79188. }
  79189. #ifdef MAKECRCH
  79190. local void write_table(out, table)
  79191. FILE *out;
  79192. const unsigned long FAR *table;
  79193. {
  79194. int n;
  79195. for (n = 0; n < 256; n++)
  79196. fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", table[n],
  79197. n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", "));
  79198. }
  79199. #endif /* MAKECRCH */
  79200. #else /* !DYNAMIC_CRC_TABLE */
  79201. /* ========================================================================
  79202. * Tables of CRC-32s of all single-byte values, made by make_crc_table().
  79203. */
  79204. /*** Start of inlined file: crc32.h ***/
  79205. local const unsigned long FAR crc_table[TBLS][256] =
  79206. {
  79207. {
  79208. 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL,
  79209. 0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL,
  79210. 0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL,
  79211. 0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL,
  79212. 0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL,
  79213. 0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL,
  79214. 0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL,
  79215. 0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL,
  79216. 0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL,
  79217. 0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL,
  79218. 0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL,
  79219. 0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL,
  79220. 0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL,
  79221. 0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL,
  79222. 0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL,
  79223. 0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL,
  79224. 0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL,
  79225. 0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL,
  79226. 0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL,
  79227. 0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL,
  79228. 0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL,
  79229. 0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL,
  79230. 0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL,
  79231. 0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL,
  79232. 0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL,
  79233. 0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL,
  79234. 0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL,
  79235. 0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL,
  79236. 0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL,
  79237. 0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL,
  79238. 0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL,
  79239. 0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL,
  79240. 0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL,
  79241. 0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL,
  79242. 0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL,
  79243. 0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL,
  79244. 0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL,
  79245. 0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL,
  79246. 0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL,
  79247. 0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL,
  79248. 0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL,
  79249. 0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL,
  79250. 0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL,
  79251. 0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL,
  79252. 0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL,
  79253. 0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL,
  79254. 0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL,
  79255. 0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL,
  79256. 0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL,
  79257. 0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL,
  79258. 0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL,
  79259. 0x2d02ef8dUL
  79260. #ifdef BYFOUR
  79261. },
  79262. {
  79263. 0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL,
  79264. 0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL,
  79265. 0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL,
  79266. 0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL,
  79267. 0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL,
  79268. 0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL,
  79269. 0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL,
  79270. 0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL,
  79271. 0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL,
  79272. 0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL,
  79273. 0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL,
  79274. 0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL,
  79275. 0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL,
  79276. 0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL,
  79277. 0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL,
  79278. 0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL,
  79279. 0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL,
  79280. 0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL,
  79281. 0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL,
  79282. 0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL,
  79283. 0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL,
  79284. 0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL,
  79285. 0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL,
  79286. 0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL,
  79287. 0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL,
  79288. 0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL,
  79289. 0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL,
  79290. 0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL,
  79291. 0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL,
  79292. 0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL,
  79293. 0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL,
  79294. 0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL,
  79295. 0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL,
  79296. 0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL,
  79297. 0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL,
  79298. 0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL,
  79299. 0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL,
  79300. 0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL,
  79301. 0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL,
  79302. 0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL,
  79303. 0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL,
  79304. 0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL,
  79305. 0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL,
  79306. 0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL,
  79307. 0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL,
  79308. 0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL,
  79309. 0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL,
  79310. 0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL,
  79311. 0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL,
  79312. 0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL,
  79313. 0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL,
  79314. 0x9324fd72UL
  79315. },
  79316. {
  79317. 0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL,
  79318. 0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL,
  79319. 0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL,
  79320. 0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL,
  79321. 0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL,
  79322. 0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL,
  79323. 0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL,
  79324. 0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL,
  79325. 0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL,
  79326. 0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL,
  79327. 0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL,
  79328. 0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL,
  79329. 0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL,
  79330. 0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL,
  79331. 0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL,
  79332. 0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL,
  79333. 0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL,
  79334. 0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL,
  79335. 0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL,
  79336. 0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL,
  79337. 0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL,
  79338. 0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL,
  79339. 0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL,
  79340. 0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL,
  79341. 0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL,
  79342. 0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL,
  79343. 0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL,
  79344. 0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL,
  79345. 0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL,
  79346. 0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL,
  79347. 0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL,
  79348. 0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL,
  79349. 0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL,
  79350. 0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL,
  79351. 0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL,
  79352. 0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL,
  79353. 0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL,
  79354. 0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL,
  79355. 0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL,
  79356. 0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL,
  79357. 0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL,
  79358. 0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL,
  79359. 0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL,
  79360. 0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL,
  79361. 0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL,
  79362. 0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL,
  79363. 0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL,
  79364. 0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL,
  79365. 0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL,
  79366. 0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL,
  79367. 0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL,
  79368. 0xbe9834edUL
  79369. },
  79370. {
  79371. 0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL,
  79372. 0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL,
  79373. 0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL,
  79374. 0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL,
  79375. 0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL,
  79376. 0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL,
  79377. 0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL,
  79378. 0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL,
  79379. 0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL,
  79380. 0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL,
  79381. 0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL,
  79382. 0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL,
  79383. 0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL,
  79384. 0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL,
  79385. 0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL,
  79386. 0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL,
  79387. 0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL,
  79388. 0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL,
  79389. 0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL,
  79390. 0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL,
  79391. 0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL,
  79392. 0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL,
  79393. 0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL,
  79394. 0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL,
  79395. 0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL,
  79396. 0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL,
  79397. 0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL,
  79398. 0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL,
  79399. 0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL,
  79400. 0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL,
  79401. 0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL,
  79402. 0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL,
  79403. 0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL,
  79404. 0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL,
  79405. 0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL,
  79406. 0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL,
  79407. 0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL,
  79408. 0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL,
  79409. 0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL,
  79410. 0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL,
  79411. 0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL,
  79412. 0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL,
  79413. 0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL,
  79414. 0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL,
  79415. 0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL,
  79416. 0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL,
  79417. 0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL,
  79418. 0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL,
  79419. 0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL,
  79420. 0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL,
  79421. 0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL,
  79422. 0xde0506f1UL
  79423. },
  79424. {
  79425. 0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL,
  79426. 0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL,
  79427. 0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL,
  79428. 0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL,
  79429. 0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL,
  79430. 0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL,
  79431. 0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL,
  79432. 0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL,
  79433. 0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL,
  79434. 0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL,
  79435. 0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL,
  79436. 0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL,
  79437. 0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL,
  79438. 0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL,
  79439. 0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL,
  79440. 0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL,
  79441. 0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL,
  79442. 0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL,
  79443. 0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL,
  79444. 0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL,
  79445. 0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL,
  79446. 0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL,
  79447. 0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL,
  79448. 0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL,
  79449. 0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL,
  79450. 0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL,
  79451. 0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL,
  79452. 0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL,
  79453. 0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL,
  79454. 0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL,
  79455. 0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL,
  79456. 0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL,
  79457. 0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL,
  79458. 0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL,
  79459. 0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL,
  79460. 0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL,
  79461. 0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL,
  79462. 0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL,
  79463. 0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL,
  79464. 0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL,
  79465. 0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL,
  79466. 0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL,
  79467. 0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL,
  79468. 0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL,
  79469. 0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL,
  79470. 0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL,
  79471. 0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL,
  79472. 0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL,
  79473. 0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL,
  79474. 0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL,
  79475. 0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL,
  79476. 0x8def022dUL
  79477. },
  79478. {
  79479. 0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL,
  79480. 0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL,
  79481. 0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL,
  79482. 0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL,
  79483. 0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL,
  79484. 0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL,
  79485. 0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL,
  79486. 0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL,
  79487. 0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL,
  79488. 0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL,
  79489. 0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL,
  79490. 0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL,
  79491. 0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL,
  79492. 0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL,
  79493. 0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL,
  79494. 0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL,
  79495. 0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL,
  79496. 0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL,
  79497. 0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL,
  79498. 0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL,
  79499. 0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL,
  79500. 0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL,
  79501. 0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL,
  79502. 0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL,
  79503. 0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL,
  79504. 0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL,
  79505. 0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL,
  79506. 0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL,
  79507. 0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL,
  79508. 0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL,
  79509. 0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL,
  79510. 0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL,
  79511. 0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL,
  79512. 0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL,
  79513. 0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL,
  79514. 0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL,
  79515. 0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL,
  79516. 0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL,
  79517. 0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL,
  79518. 0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL,
  79519. 0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL,
  79520. 0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL,
  79521. 0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL,
  79522. 0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL,
  79523. 0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL,
  79524. 0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL,
  79525. 0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL,
  79526. 0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL,
  79527. 0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL,
  79528. 0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL,
  79529. 0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL,
  79530. 0x72fd2493UL
  79531. },
  79532. {
  79533. 0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL,
  79534. 0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL,
  79535. 0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL,
  79536. 0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL,
  79537. 0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL,
  79538. 0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL,
  79539. 0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL,
  79540. 0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL,
  79541. 0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL,
  79542. 0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL,
  79543. 0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL,
  79544. 0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL,
  79545. 0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL,
  79546. 0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL,
  79547. 0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL,
  79548. 0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL,
  79549. 0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL,
  79550. 0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL,
  79551. 0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL,
  79552. 0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL,
  79553. 0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL,
  79554. 0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL,
  79555. 0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL,
  79556. 0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL,
  79557. 0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL,
  79558. 0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL,
  79559. 0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL,
  79560. 0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL,
  79561. 0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL,
  79562. 0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL,
  79563. 0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL,
  79564. 0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL,
  79565. 0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL,
  79566. 0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL,
  79567. 0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL,
  79568. 0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL,
  79569. 0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL,
  79570. 0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL,
  79571. 0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL,
  79572. 0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL,
  79573. 0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL,
  79574. 0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL,
  79575. 0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL,
  79576. 0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL,
  79577. 0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL,
  79578. 0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL,
  79579. 0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL,
  79580. 0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL,
  79581. 0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL,
  79582. 0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL,
  79583. 0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL,
  79584. 0xed3498beUL
  79585. },
  79586. {
  79587. 0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL,
  79588. 0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL,
  79589. 0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL,
  79590. 0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL,
  79591. 0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL,
  79592. 0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL,
  79593. 0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL,
  79594. 0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL,
  79595. 0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL,
  79596. 0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL,
  79597. 0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL,
  79598. 0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL,
  79599. 0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL,
  79600. 0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL,
  79601. 0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL,
  79602. 0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL,
  79603. 0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL,
  79604. 0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL,
  79605. 0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL,
  79606. 0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL,
  79607. 0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL,
  79608. 0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL,
  79609. 0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL,
  79610. 0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL,
  79611. 0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL,
  79612. 0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL,
  79613. 0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL,
  79614. 0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL,
  79615. 0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL,
  79616. 0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL,
  79617. 0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL,
  79618. 0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL,
  79619. 0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL,
  79620. 0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL,
  79621. 0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL,
  79622. 0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL,
  79623. 0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL,
  79624. 0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL,
  79625. 0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL,
  79626. 0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL,
  79627. 0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL,
  79628. 0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL,
  79629. 0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL,
  79630. 0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL,
  79631. 0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL,
  79632. 0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL,
  79633. 0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL,
  79634. 0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL,
  79635. 0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL,
  79636. 0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL,
  79637. 0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL,
  79638. 0xf10605deUL
  79639. #endif
  79640. }
  79641. };
  79642. /*** End of inlined file: crc32.h ***/
  79643. #endif /* DYNAMIC_CRC_TABLE */
  79644. /* =========================================================================
  79645. * This function can be used by asm versions of crc32()
  79646. */
  79647. const unsigned long FAR * ZEXPORT get_crc_table()
  79648. {
  79649. #ifdef DYNAMIC_CRC_TABLE
  79650. if (crc_table_empty)
  79651. make_crc_table();
  79652. #endif /* DYNAMIC_CRC_TABLE */
  79653. return (const unsigned long FAR *)crc_table;
  79654. }
  79655. /* ========================================================================= */
  79656. #define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8)
  79657. #define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1
  79658. /* ========================================================================= */
  79659. unsigned long ZEXPORT crc32 (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  79660. {
  79661. if (buf == Z_NULL) return 0UL;
  79662. #ifdef DYNAMIC_CRC_TABLE
  79663. if (crc_table_empty)
  79664. make_crc_table();
  79665. #endif /* DYNAMIC_CRC_TABLE */
  79666. #ifdef BYFOUR
  79667. if (sizeof(void *) == sizeof(ptrdiff_t)) {
  79668. u4 endian;
  79669. endian = 1;
  79670. if (*((unsigned char *)(&endian)))
  79671. return crc32_little(crc, buf, len);
  79672. else
  79673. return crc32_big(crc, buf, len);
  79674. }
  79675. #endif /* BYFOUR */
  79676. crc = crc ^ 0xffffffffUL;
  79677. while (len >= 8) {
  79678. DO8;
  79679. len -= 8;
  79680. }
  79681. if (len) do {
  79682. DO1;
  79683. } while (--len);
  79684. return crc ^ 0xffffffffUL;
  79685. }
  79686. #ifdef BYFOUR
  79687. /* ========================================================================= */
  79688. #define DOLIT4 c ^= *buf4++; \
  79689. c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \
  79690. crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24]
  79691. #define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4
  79692. /* ========================================================================= */
  79693. local unsigned long crc32_little(unsigned long crc, const unsigned char FAR *buf, unsigned len)
  79694. {
  79695. register u4 c;
  79696. register const u4 FAR *buf4;
  79697. c = (u4)crc;
  79698. c = ~c;
  79699. while (len && ((ptrdiff_t)buf & 3)) {
  79700. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  79701. len--;
  79702. }
  79703. buf4 = (const u4 FAR *)(const void FAR *)buf;
  79704. while (len >= 32) {
  79705. DOLIT32;
  79706. len -= 32;
  79707. }
  79708. while (len >= 4) {
  79709. DOLIT4;
  79710. len -= 4;
  79711. }
  79712. buf = (const unsigned char FAR *)buf4;
  79713. if (len) do {
  79714. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  79715. } while (--len);
  79716. c = ~c;
  79717. return (unsigned long)c;
  79718. }
  79719. /* ========================================================================= */
  79720. #define DOBIG4 c ^= *++buf4; \
  79721. c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \
  79722. crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24]
  79723. #define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4
  79724. /* ========================================================================= */
  79725. local unsigned long crc32_big (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  79726. {
  79727. register u4 c;
  79728. register const u4 FAR *buf4;
  79729. c = REV((u4)crc);
  79730. c = ~c;
  79731. while (len && ((ptrdiff_t)buf & 3)) {
  79732. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  79733. len--;
  79734. }
  79735. buf4 = (const u4 FAR *)(const void FAR *)buf;
  79736. buf4--;
  79737. while (len >= 32) {
  79738. DOBIG32;
  79739. len -= 32;
  79740. }
  79741. while (len >= 4) {
  79742. DOBIG4;
  79743. len -= 4;
  79744. }
  79745. buf4++;
  79746. buf = (const unsigned char FAR *)buf4;
  79747. if (len) do {
  79748. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  79749. } while (--len);
  79750. c = ~c;
  79751. return (unsigned long)(REV(c));
  79752. }
  79753. #endif /* BYFOUR */
  79754. #define GF2_DIM 32 /* dimension of GF(2) vectors (length of CRC) */
  79755. /* ========================================================================= */
  79756. local unsigned long gf2_matrix_times (unsigned long *mat, unsigned long vec)
  79757. {
  79758. unsigned long sum;
  79759. sum = 0;
  79760. while (vec) {
  79761. if (vec & 1)
  79762. sum ^= *mat;
  79763. vec >>= 1;
  79764. mat++;
  79765. }
  79766. return sum;
  79767. }
  79768. /* ========================================================================= */
  79769. local void gf2_matrix_square (unsigned long *square, unsigned long *mat)
  79770. {
  79771. int n;
  79772. for (n = 0; n < GF2_DIM; n++)
  79773. square[n] = gf2_matrix_times(mat, mat[n]);
  79774. }
  79775. /* ========================================================================= */
  79776. uLong ZEXPORT crc32_combine (uLong crc1, uLong crc2, z_off_t len2)
  79777. {
  79778. int n;
  79779. unsigned long row;
  79780. unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */
  79781. unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */
  79782. /* degenerate case */
  79783. if (len2 == 0)
  79784. return crc1;
  79785. /* put operator for one zero bit in odd */
  79786. odd[0] = 0xedb88320L; /* CRC-32 polynomial */
  79787. row = 1;
  79788. for (n = 1; n < GF2_DIM; n++) {
  79789. odd[n] = row;
  79790. row <<= 1;
  79791. }
  79792. /* put operator for two zero bits in even */
  79793. gf2_matrix_square(even, odd);
  79794. /* put operator for four zero bits in odd */
  79795. gf2_matrix_square(odd, even);
  79796. /* apply len2 zeros to crc1 (first square will put the operator for one
  79797. zero byte, eight zero bits, in even) */
  79798. do {
  79799. /* apply zeros operator for this bit of len2 */
  79800. gf2_matrix_square(even, odd);
  79801. if (len2 & 1)
  79802. crc1 = gf2_matrix_times(even, crc1);
  79803. len2 >>= 1;
  79804. /* if no more bits set, then done */
  79805. if (len2 == 0)
  79806. break;
  79807. /* another iteration of the loop with odd and even swapped */
  79808. gf2_matrix_square(odd, even);
  79809. if (len2 & 1)
  79810. crc1 = gf2_matrix_times(odd, crc1);
  79811. len2 >>= 1;
  79812. /* if no more bits set, then done */
  79813. } while (len2 != 0);
  79814. /* return combined crc */
  79815. crc1 ^= crc2;
  79816. return crc1;
  79817. }
  79818. /*** End of inlined file: crc32.c ***/
  79819. /*** Start of inlined file: deflate.c ***/
  79820. /*
  79821. * ALGORITHM
  79822. *
  79823. * The "deflation" process depends on being able to identify portions
  79824. * of the input text which are identical to earlier input (within a
  79825. * sliding window trailing behind the input currently being processed).
  79826. *
  79827. * The most straightforward technique turns out to be the fastest for
  79828. * most input files: try all possible matches and select the longest.
  79829. * The key feature of this algorithm is that insertions into the string
  79830. * dictionary are very simple and thus fast, and deletions are avoided
  79831. * completely. Insertions are performed at each input character, whereas
  79832. * string matches are performed only when the previous match ends. So it
  79833. * is preferable to spend more time in matches to allow very fast string
  79834. * insertions and avoid deletions. The matching algorithm for small
  79835. * strings is inspired from that of Rabin & Karp. A brute force approach
  79836. * is used to find longer strings when a small match has been found.
  79837. * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
  79838. * (by Leonid Broukhis).
  79839. * A previous version of this file used a more sophisticated algorithm
  79840. * (by Fiala and Greene) which is guaranteed to run in linear amortized
  79841. * time, but has a larger average cost, uses more memory and is patented.
  79842. * However the F&G algorithm may be faster for some highly redundant
  79843. * files if the parameter max_chain_length (described below) is too large.
  79844. *
  79845. * ACKNOWLEDGEMENTS
  79846. *
  79847. * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
  79848. * I found it in 'freeze' written by Leonid Broukhis.
  79849. * Thanks to many people for bug reports and testing.
  79850. *
  79851. * REFERENCES
  79852. *
  79853. * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
  79854. * Available in http://www.ietf.org/rfc/rfc1951.txt
  79855. *
  79856. * A description of the Rabin and Karp algorithm is given in the book
  79857. * "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
  79858. *
  79859. * Fiala,E.R., and Greene,D.H.
  79860. * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
  79861. *
  79862. */
  79863. /* @(#) $Id: deflate.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79864. /*** Start of inlined file: deflate.h ***/
  79865. /* WARNING: this file should *not* be used by applications. It is
  79866. part of the implementation of the compression library and is
  79867. subject to change. Applications should only use zlib.h.
  79868. */
  79869. /* @(#) $Id: deflate.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79870. #ifndef DEFLATE_H
  79871. #define DEFLATE_H
  79872. /* define NO_GZIP when compiling if you want to disable gzip header and
  79873. trailer creation by deflate(). NO_GZIP would be used to avoid linking in
  79874. the crc code when it is not needed. For shared libraries, gzip encoding
  79875. should be left enabled. */
  79876. #ifndef NO_GZIP
  79877. # define GZIP
  79878. #endif
  79879. #define NO_DUMMY_DECL
  79880. /* ===========================================================================
  79881. * Internal compression state.
  79882. */
  79883. #define LENGTH_CODES 29
  79884. /* number of length codes, not counting the special END_BLOCK code */
  79885. #define LITERALS 256
  79886. /* number of literal bytes 0..255 */
  79887. #define L_CODES (LITERALS+1+LENGTH_CODES)
  79888. /* number of Literal or Length codes, including the END_BLOCK code */
  79889. #define D_CODES 30
  79890. /* number of distance codes */
  79891. #define BL_CODES 19
  79892. /* number of codes used to transfer the bit lengths */
  79893. #define HEAP_SIZE (2*L_CODES+1)
  79894. /* maximum heap size */
  79895. #define MAX_BITS 15
  79896. /* All codes must not exceed MAX_BITS bits */
  79897. #define INIT_STATE 42
  79898. #define EXTRA_STATE 69
  79899. #define NAME_STATE 73
  79900. #define COMMENT_STATE 91
  79901. #define HCRC_STATE 103
  79902. #define BUSY_STATE 113
  79903. #define FINISH_STATE 666
  79904. /* Stream status */
  79905. /* Data structure describing a single value and its code string. */
  79906. typedef struct ct_data_s {
  79907. union {
  79908. ush freq; /* frequency count */
  79909. ush code; /* bit string */
  79910. } fc;
  79911. union {
  79912. ush dad; /* father node in Huffman tree */
  79913. ush len; /* length of bit string */
  79914. } dl;
  79915. } FAR ct_data;
  79916. #define Freq fc.freq
  79917. #define Code fc.code
  79918. #define Dad dl.dad
  79919. #define Len dl.len
  79920. typedef struct static_tree_desc_s static_tree_desc;
  79921. typedef struct tree_desc_s {
  79922. ct_data *dyn_tree; /* the dynamic tree */
  79923. int max_code; /* largest code with non zero frequency */
  79924. static_tree_desc *stat_desc; /* the corresponding static tree */
  79925. } FAR tree_desc;
  79926. typedef ush Pos;
  79927. typedef Pos FAR Posf;
  79928. typedef unsigned IPos;
  79929. /* A Pos is an index in the character window. We use short instead of int to
  79930. * save space in the various tables. IPos is used only for parameter passing.
  79931. */
  79932. typedef struct internal_state {
  79933. z_streamp strm; /* pointer back to this zlib stream */
  79934. int status; /* as the name implies */
  79935. Bytef *pending_buf; /* output still pending */
  79936. ulg pending_buf_size; /* size of pending_buf */
  79937. Bytef *pending_out; /* next pending byte to output to the stream */
  79938. uInt pending; /* nb of bytes in the pending buffer */
  79939. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  79940. gz_headerp gzhead; /* gzip header information to write */
  79941. uInt gzindex; /* where in extra, name, or comment */
  79942. Byte method; /* STORED (for zip only) or DEFLATED */
  79943. int last_flush; /* value of flush param for previous deflate call */
  79944. /* used by deflate.c: */
  79945. uInt w_size; /* LZ77 window size (32K by default) */
  79946. uInt w_bits; /* log2(w_size) (8..16) */
  79947. uInt w_mask; /* w_size - 1 */
  79948. Bytef *window;
  79949. /* Sliding window. Input bytes are read into the second half of the window,
  79950. * and move to the first half later to keep a dictionary of at least wSize
  79951. * bytes. With this organization, matches are limited to a distance of
  79952. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  79953. * performed with a length multiple of the block size. Also, it limits
  79954. * the window size to 64K, which is quite useful on MSDOS.
  79955. * To do: use the user input buffer as sliding window.
  79956. */
  79957. ulg window_size;
  79958. /* Actual size of window: 2*wSize, except when the user input buffer
  79959. * is directly used as sliding window.
  79960. */
  79961. Posf *prev;
  79962. /* Link to older string with same hash index. To limit the size of this
  79963. * array to 64K, this link is maintained only for the last 32K strings.
  79964. * An index in this array is thus a window index modulo 32K.
  79965. */
  79966. Posf *head; /* Heads of the hash chains or NIL. */
  79967. uInt ins_h; /* hash index of string to be inserted */
  79968. uInt hash_size; /* number of elements in hash table */
  79969. uInt hash_bits; /* log2(hash_size) */
  79970. uInt hash_mask; /* hash_size-1 */
  79971. uInt hash_shift;
  79972. /* Number of bits by which ins_h must be shifted at each input
  79973. * step. It must be such that after MIN_MATCH steps, the oldest
  79974. * byte no longer takes part in the hash key, that is:
  79975. * hash_shift * MIN_MATCH >= hash_bits
  79976. */
  79977. long block_start;
  79978. /* Window position at the beginning of the current output block. Gets
  79979. * negative when the window is moved backwards.
  79980. */
  79981. uInt match_length; /* length of best match */
  79982. IPos prev_match; /* previous match */
  79983. int match_available; /* set if previous match exists */
  79984. uInt strstart; /* start of string to insert */
  79985. uInt match_start; /* start of matching string */
  79986. uInt lookahead; /* number of valid bytes ahead in window */
  79987. uInt prev_length;
  79988. /* Length of the best match at previous step. Matches not greater than this
  79989. * are discarded. This is used in the lazy match evaluation.
  79990. */
  79991. uInt max_chain_length;
  79992. /* To speed up deflation, hash chains are never searched beyond this
  79993. * length. A higher limit improves compression ratio but degrades the
  79994. * speed.
  79995. */
  79996. uInt max_lazy_match;
  79997. /* Attempt to find a better match only when the current match is strictly
  79998. * smaller than this value. This mechanism is used only for compression
  79999. * levels >= 4.
  80000. */
  80001. # define max_insert_length max_lazy_match
  80002. /* Insert new strings in the hash table only if the match length is not
  80003. * greater than this length. This saves time but degrades compression.
  80004. * max_insert_length is used only for compression levels <= 3.
  80005. */
  80006. int level; /* compression level (1..9) */
  80007. int strategy; /* favor or force Huffman coding*/
  80008. uInt good_match;
  80009. /* Use a faster search when the previous match is longer than this */
  80010. int nice_match; /* Stop searching when current match exceeds this */
  80011. /* used by trees.c: */
  80012. /* Didn't use ct_data typedef below to supress compiler warning */
  80013. struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  80014. struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  80015. struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  80016. struct tree_desc_s l_desc; /* desc. for literal tree */
  80017. struct tree_desc_s d_desc; /* desc. for distance tree */
  80018. struct tree_desc_s bl_desc; /* desc. for bit length tree */
  80019. ush bl_count[MAX_BITS+1];
  80020. /* number of codes at each bit length for an optimal tree */
  80021. int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  80022. int heap_len; /* number of elements in the heap */
  80023. int heap_max; /* element of largest frequency */
  80024. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  80025. * The same heap array is used to build all trees.
  80026. */
  80027. uch depth[2*L_CODES+1];
  80028. /* Depth of each subtree used as tie breaker for trees of equal frequency
  80029. */
  80030. uchf *l_buf; /* buffer for literals or lengths */
  80031. uInt lit_bufsize;
  80032. /* Size of match buffer for literals/lengths. There are 4 reasons for
  80033. * limiting lit_bufsize to 64K:
  80034. * - frequencies can be kept in 16 bit counters
  80035. * - if compression is not successful for the first block, all input
  80036. * data is still in the window so we can still emit a stored block even
  80037. * when input comes from standard input. (This can also be done for
  80038. * all blocks if lit_bufsize is not greater than 32K.)
  80039. * - if compression is not successful for a file smaller than 64K, we can
  80040. * even emit a stored file instead of a stored block (saving 5 bytes).
  80041. * This is applicable only for zip (not gzip or zlib).
  80042. * - creating new Huffman trees less frequently may not provide fast
  80043. * adaptation to changes in the input data statistics. (Take for
  80044. * example a binary file with poorly compressible code followed by
  80045. * a highly compressible string table.) Smaller buffer sizes give
  80046. * fast adaptation but have of course the overhead of transmitting
  80047. * trees more frequently.
  80048. * - I can't count above 4
  80049. */
  80050. uInt last_lit; /* running index in l_buf */
  80051. ushf *d_buf;
  80052. /* Buffer for distances. To simplify the code, d_buf and l_buf have
  80053. * the same number of elements. To use different lengths, an extra flag
  80054. * array would be necessary.
  80055. */
  80056. ulg opt_len; /* bit length of current block with optimal trees */
  80057. ulg static_len; /* bit length of current block with static trees */
  80058. uInt matches; /* number of string matches in current block */
  80059. int last_eob_len; /* bit length of EOB code for last block */
  80060. #ifdef DEBUG
  80061. ulg compressed_len; /* total bit length of compressed file mod 2^32 */
  80062. ulg bits_sent; /* bit length of compressed data sent mod 2^32 */
  80063. #endif
  80064. ush bi_buf;
  80065. /* Output buffer. bits are inserted starting at the bottom (least
  80066. * significant bits).
  80067. */
  80068. int bi_valid;
  80069. /* Number of valid bits in bi_buf. All bits above the last valid bit
  80070. * are always zero.
  80071. */
  80072. } FAR deflate_state;
  80073. /* Output a byte on the stream.
  80074. * IN assertion: there is enough room in pending_buf.
  80075. */
  80076. #define put_byte(s, c) {s->pending_buf[s->pending++] = (c);}
  80077. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  80078. /* Minimum amount of lookahead, except at the end of the input file.
  80079. * See deflate.c for comments about the MIN_MATCH+1.
  80080. */
  80081. #define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD)
  80082. /* In order to simplify the code, particularly on 16 bit machines, match
  80083. * distances are limited to MAX_DIST instead of WSIZE.
  80084. */
  80085. /* in trees.c */
  80086. void _tr_init OF((deflate_state *s));
  80087. int _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc));
  80088. void _tr_flush_block OF((deflate_state *s, charf *buf, ulg stored_len,
  80089. int eof));
  80090. void _tr_align OF((deflate_state *s));
  80091. void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len,
  80092. int eof));
  80093. #define d_code(dist) \
  80094. ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)])
  80095. /* Mapping from a distance to a distance code. dist is the distance - 1 and
  80096. * must not have side effects. _dist_code[256] and _dist_code[257] are never
  80097. * used.
  80098. */
  80099. #ifndef DEBUG
  80100. /* Inline versions of _tr_tally for speed: */
  80101. #if defined(GEN_TREES_H) || !defined(STDC)
  80102. extern uch _length_code[];
  80103. extern uch _dist_code[];
  80104. #else
  80105. extern const uch _length_code[];
  80106. extern const uch _dist_code[];
  80107. #endif
  80108. # define _tr_tally_lit(s, c, flush) \
  80109. { uch cc = (c); \
  80110. s->d_buf[s->last_lit] = 0; \
  80111. s->l_buf[s->last_lit++] = cc; \
  80112. s->dyn_ltree[cc].Freq++; \
  80113. flush = (s->last_lit == s->lit_bufsize-1); \
  80114. }
  80115. # define _tr_tally_dist(s, distance, length, flush) \
  80116. { uch len = (length); \
  80117. ush dist = (distance); \
  80118. s->d_buf[s->last_lit] = dist; \
  80119. s->l_buf[s->last_lit++] = len; \
  80120. dist--; \
  80121. s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \
  80122. s->dyn_dtree[d_code(dist)].Freq++; \
  80123. flush = (s->last_lit == s->lit_bufsize-1); \
  80124. }
  80125. #else
  80126. # define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c)
  80127. # define _tr_tally_dist(s, distance, length, flush) \
  80128. flush = _tr_tally(s, distance, length)
  80129. #endif
  80130. #endif /* DEFLATE_H */
  80131. /*** End of inlined file: deflate.h ***/
  80132. const char deflate_copyright[] =
  80133. " deflate 1.2.3 Copyright 1995-2005 Jean-loup Gailly ";
  80134. /*
  80135. If you use the zlib library in a product, an acknowledgment is welcome
  80136. in the documentation of your product. If for some reason you cannot
  80137. include such an acknowledgment, I would appreciate that you keep this
  80138. copyright string in the executable of your product.
  80139. */
  80140. /* ===========================================================================
  80141. * Function prototypes.
  80142. */
  80143. typedef enum {
  80144. need_more, /* block not completed, need more input or more output */
  80145. block_done, /* block flush performed */
  80146. finish_started, /* finish started, need only more output at next deflate */
  80147. finish_done /* finish done, accept no more input or output */
  80148. } block_state;
  80149. typedef block_state (*compress_func) OF((deflate_state *s, int flush));
  80150. /* Compression function. Returns the block state after the call. */
  80151. local void fill_window OF((deflate_state *s));
  80152. local block_state deflate_stored OF((deflate_state *s, int flush));
  80153. local block_state deflate_fast OF((deflate_state *s, int flush));
  80154. #ifndef FASTEST
  80155. local block_state deflate_slow OF((deflate_state *s, int flush));
  80156. #endif
  80157. local void lm_init OF((deflate_state *s));
  80158. local void putShortMSB OF((deflate_state *s, uInt b));
  80159. local void flush_pending OF((z_streamp strm));
  80160. local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size));
  80161. #ifndef FASTEST
  80162. #ifdef ASMV
  80163. void match_init OF((void)); /* asm code initialization */
  80164. uInt longest_match OF((deflate_state *s, IPos cur_match));
  80165. #else
  80166. local uInt longest_match OF((deflate_state *s, IPos cur_match));
  80167. #endif
  80168. #endif
  80169. local uInt longest_match_fast OF((deflate_state *s, IPos cur_match));
  80170. #ifdef DEBUG
  80171. local void check_match OF((deflate_state *s, IPos start, IPos match,
  80172. int length));
  80173. #endif
  80174. /* ===========================================================================
  80175. * Local data
  80176. */
  80177. #define NIL 0
  80178. /* Tail of hash chains */
  80179. #ifndef TOO_FAR
  80180. # define TOO_FAR 4096
  80181. #endif
  80182. /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
  80183. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  80184. /* Minimum amount of lookahead, except at the end of the input file.
  80185. * See deflate.c for comments about the MIN_MATCH+1.
  80186. */
  80187. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  80188. * the desired pack level (0..9). The values given below have been tuned to
  80189. * exclude worst case performance for pathological files. Better values may be
  80190. * found for specific files.
  80191. */
  80192. typedef struct config_s {
  80193. ush good_length; /* reduce lazy search above this match length */
  80194. ush max_lazy; /* do not perform lazy search above this match length */
  80195. ush nice_length; /* quit search above this match length */
  80196. ush max_chain;
  80197. compress_func func;
  80198. } config;
  80199. #ifdef FASTEST
  80200. local const config configuration_table[2] = {
  80201. /* good lazy nice chain */
  80202. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  80203. /* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */
  80204. #else
  80205. local const config configuration_table[10] = {
  80206. /* good lazy nice chain */
  80207. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  80208. /* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */
  80209. /* 2 */ {4, 5, 16, 8, deflate_fast},
  80210. /* 3 */ {4, 6, 32, 32, deflate_fast},
  80211. /* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */
  80212. /* 5 */ {8, 16, 32, 32, deflate_slow},
  80213. /* 6 */ {8, 16, 128, 128, deflate_slow},
  80214. /* 7 */ {8, 32, 128, 256, deflate_slow},
  80215. /* 8 */ {32, 128, 258, 1024, deflate_slow},
  80216. /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
  80217. #endif
  80218. /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
  80219. * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
  80220. * meaning.
  80221. */
  80222. #define EQUAL 0
  80223. /* result of memcmp for equal strings */
  80224. #ifndef NO_DUMMY_DECL
  80225. struct static_tree_desc_s {int dummy;}; /* for buggy compilers */
  80226. #endif
  80227. /* ===========================================================================
  80228. * Update a hash value with the given input byte
  80229. * IN assertion: all calls to to UPDATE_HASH are made with consecutive
  80230. * input characters, so that a running hash key can be computed from the
  80231. * previous key instead of complete recalculation each time.
  80232. */
  80233. #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
  80234. /* ===========================================================================
  80235. * Insert string str in the dictionary and set match_head to the previous head
  80236. * of the hash chain (the most recent string with same hash key). Return
  80237. * the previous length of the hash chain.
  80238. * If this file is compiled with -DFASTEST, the compression level is forced
  80239. * to 1, and no hash chains are maintained.
  80240. * IN assertion: all calls to to INSERT_STRING are made with consecutive
  80241. * input characters and the first MIN_MATCH bytes of str are valid
  80242. * (except for the last MIN_MATCH-1 bytes of the input file).
  80243. */
  80244. #ifdef FASTEST
  80245. #define INSERT_STRING(s, str, match_head) \
  80246. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  80247. match_head = s->head[s->ins_h], \
  80248. s->head[s->ins_h] = (Pos)(str))
  80249. #else
  80250. #define INSERT_STRING(s, str, match_head) \
  80251. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  80252. match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \
  80253. s->head[s->ins_h] = (Pos)(str))
  80254. #endif
  80255. /* ===========================================================================
  80256. * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
  80257. * prev[] will be initialized on the fly.
  80258. */
  80259. #define CLEAR_HASH(s) \
  80260. s->head[s->hash_size-1] = NIL; \
  80261. zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
  80262. /* ========================================================================= */
  80263. int ZEXPORT deflateInit_(z_streamp strm, int level, const char *version, int stream_size)
  80264. {
  80265. return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
  80266. Z_DEFAULT_STRATEGY, version, stream_size);
  80267. /* To do: ignore strm->next_in if we use it as window */
  80268. }
  80269. /* ========================================================================= */
  80270. int ZEXPORT deflateInit2_ (z_streamp strm, int level, int method, int windowBits, int memLevel, int strategy, const char *version, int stream_size)
  80271. {
  80272. deflate_state *s;
  80273. int wrap = 1;
  80274. static const char my_version[] = ZLIB_VERSION;
  80275. ushf *overlay;
  80276. /* We overlay pending_buf and d_buf+l_buf. This works since the average
  80277. * output size for (length,distance) codes is <= 24 bits.
  80278. */
  80279. if (version == Z_NULL || version[0] != my_version[0] ||
  80280. stream_size != sizeof(z_stream)) {
  80281. return Z_VERSION_ERROR;
  80282. }
  80283. if (strm == Z_NULL) return Z_STREAM_ERROR;
  80284. strm->msg = Z_NULL;
  80285. if (strm->zalloc == (alloc_func)0) {
  80286. strm->zalloc = zcalloc;
  80287. strm->opaque = (voidpf)0;
  80288. }
  80289. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  80290. #ifdef FASTEST
  80291. if (level != 0) level = 1;
  80292. #else
  80293. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  80294. #endif
  80295. if (windowBits < 0) { /* suppress zlib wrapper */
  80296. wrap = 0;
  80297. windowBits = -windowBits;
  80298. }
  80299. #ifdef GZIP
  80300. else if (windowBits > 15) {
  80301. wrap = 2; /* write gzip wrapper instead */
  80302. windowBits -= 16;
  80303. }
  80304. #endif
  80305. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
  80306. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  80307. strategy < 0 || strategy > Z_FIXED) {
  80308. return Z_STREAM_ERROR;
  80309. }
  80310. if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */
  80311. s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
  80312. if (s == Z_NULL) return Z_MEM_ERROR;
  80313. strm->state = (struct internal_state FAR *)s;
  80314. s->strm = strm;
  80315. s->wrap = wrap;
  80316. s->gzhead = Z_NULL;
  80317. s->w_bits = windowBits;
  80318. s->w_size = 1 << s->w_bits;
  80319. s->w_mask = s->w_size - 1;
  80320. s->hash_bits = memLevel + 7;
  80321. s->hash_size = 1 << s->hash_bits;
  80322. s->hash_mask = s->hash_size - 1;
  80323. s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
  80324. s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
  80325. s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos));
  80326. s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos));
  80327. s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  80328. overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
  80329. s->pending_buf = (uchf *) overlay;
  80330. s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
  80331. if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
  80332. s->pending_buf == Z_NULL) {
  80333. s->status = FINISH_STATE;
  80334. strm->msg = (char*)ERR_MSG(Z_MEM_ERROR);
  80335. deflateEnd (strm);
  80336. return Z_MEM_ERROR;
  80337. }
  80338. s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  80339. s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  80340. s->level = level;
  80341. s->strategy = strategy;
  80342. s->method = (Byte)method;
  80343. return deflateReset(strm);
  80344. }
  80345. /* ========================================================================= */
  80346. int ZEXPORT deflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  80347. {
  80348. deflate_state *s;
  80349. uInt length = dictLength;
  80350. uInt n;
  80351. IPos hash_head = 0;
  80352. if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL ||
  80353. strm->state->wrap == 2 ||
  80354. (strm->state->wrap == 1 && strm->state->status != INIT_STATE))
  80355. return Z_STREAM_ERROR;
  80356. s = strm->state;
  80357. if (s->wrap)
  80358. strm->adler = adler32(strm->adler, dictionary, dictLength);
  80359. if (length < MIN_MATCH) return Z_OK;
  80360. if (length > MAX_DIST(s)) {
  80361. length = MAX_DIST(s);
  80362. dictionary += dictLength - length; /* use the tail of the dictionary */
  80363. }
  80364. zmemcpy(s->window, dictionary, length);
  80365. s->strstart = length;
  80366. s->block_start = (long)length;
  80367. /* Insert all strings in the hash table (except for the last two bytes).
  80368. * s->lookahead stays null, so s->ins_h will be recomputed at the next
  80369. * call of fill_window.
  80370. */
  80371. s->ins_h = s->window[0];
  80372. UPDATE_HASH(s, s->ins_h, s->window[1]);
  80373. for (n = 0; n <= length - MIN_MATCH; n++) {
  80374. INSERT_STRING(s, n, hash_head);
  80375. }
  80376. if (hash_head) hash_head = 0; /* to make compiler happy */
  80377. return Z_OK;
  80378. }
  80379. /* ========================================================================= */
  80380. int ZEXPORT deflateReset (z_streamp strm)
  80381. {
  80382. deflate_state *s;
  80383. if (strm == Z_NULL || strm->state == Z_NULL ||
  80384. strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) {
  80385. return Z_STREAM_ERROR;
  80386. }
  80387. strm->total_in = strm->total_out = 0;
  80388. strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
  80389. strm->data_type = Z_UNKNOWN;
  80390. s = (deflate_state *)strm->state;
  80391. s->pending = 0;
  80392. s->pending_out = s->pending_buf;
  80393. if (s->wrap < 0) {
  80394. s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
  80395. }
  80396. s->status = s->wrap ? INIT_STATE : BUSY_STATE;
  80397. strm->adler =
  80398. #ifdef GZIP
  80399. s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
  80400. #endif
  80401. adler32(0L, Z_NULL, 0);
  80402. s->last_flush = Z_NO_FLUSH;
  80403. _tr_init(s);
  80404. lm_init(s);
  80405. return Z_OK;
  80406. }
  80407. /* ========================================================================= */
  80408. int ZEXPORT deflateSetHeader (z_streamp strm, gz_headerp head)
  80409. {
  80410. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  80411. if (strm->state->wrap != 2) return Z_STREAM_ERROR;
  80412. strm->state->gzhead = head;
  80413. return Z_OK;
  80414. }
  80415. /* ========================================================================= */
  80416. int ZEXPORT deflatePrime (z_streamp strm, int bits, int value)
  80417. {
  80418. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  80419. strm->state->bi_valid = bits;
  80420. strm->state->bi_buf = (ush)(value & ((1 << bits) - 1));
  80421. return Z_OK;
  80422. }
  80423. /* ========================================================================= */
  80424. int ZEXPORT deflateParams (z_streamp strm, int level, int strategy)
  80425. {
  80426. deflate_state *s;
  80427. compress_func func;
  80428. int err = Z_OK;
  80429. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  80430. s = strm->state;
  80431. #ifdef FASTEST
  80432. if (level != 0) level = 1;
  80433. #else
  80434. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  80435. #endif
  80436. if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
  80437. return Z_STREAM_ERROR;
  80438. }
  80439. func = configuration_table[s->level].func;
  80440. if (func != configuration_table[level].func && strm->total_in != 0) {
  80441. /* Flush the last buffer: */
  80442. err = deflate(strm, Z_PARTIAL_FLUSH);
  80443. }
  80444. if (s->level != level) {
  80445. s->level = level;
  80446. s->max_lazy_match = configuration_table[level].max_lazy;
  80447. s->good_match = configuration_table[level].good_length;
  80448. s->nice_match = configuration_table[level].nice_length;
  80449. s->max_chain_length = configuration_table[level].max_chain;
  80450. }
  80451. s->strategy = strategy;
  80452. return err;
  80453. }
  80454. /* ========================================================================= */
  80455. int ZEXPORT deflateTune (z_streamp strm, int good_length, int max_lazy, int nice_length, int max_chain)
  80456. {
  80457. deflate_state *s;
  80458. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  80459. s = strm->state;
  80460. s->good_match = good_length;
  80461. s->max_lazy_match = max_lazy;
  80462. s->nice_match = nice_length;
  80463. s->max_chain_length = max_chain;
  80464. return Z_OK;
  80465. }
  80466. /* =========================================================================
  80467. * For the default windowBits of 15 and memLevel of 8, this function returns
  80468. * a close to exact, as well as small, upper bound on the compressed size.
  80469. * They are coded as constants here for a reason--if the #define's are
  80470. * changed, then this function needs to be changed as well. The return
  80471. * value for 15 and 8 only works for those exact settings.
  80472. *
  80473. * For any setting other than those defaults for windowBits and memLevel,
  80474. * the value returned is a conservative worst case for the maximum expansion
  80475. * resulting from using fixed blocks instead of stored blocks, which deflate
  80476. * can emit on compressed data for some combinations of the parameters.
  80477. *
  80478. * This function could be more sophisticated to provide closer upper bounds
  80479. * for every combination of windowBits and memLevel, as well as wrap.
  80480. * But even the conservative upper bound of about 14% expansion does not
  80481. * seem onerous for output buffer allocation.
  80482. */
  80483. uLong ZEXPORT deflateBound (z_streamp strm, uLong sourceLen)
  80484. {
  80485. deflate_state *s;
  80486. uLong destLen;
  80487. /* conservative upper bound */
  80488. destLen = sourceLen +
  80489. ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 11;
  80490. /* if can't get parameters, return conservative bound */
  80491. if (strm == Z_NULL || strm->state == Z_NULL)
  80492. return destLen;
  80493. /* if not default parameters, return conservative bound */
  80494. s = strm->state;
  80495. if (s->w_bits != 15 || s->hash_bits != 8 + 7)
  80496. return destLen;
  80497. /* default settings: return tight bound for that case */
  80498. return compressBound(sourceLen);
  80499. }
  80500. /* =========================================================================
  80501. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  80502. * IN assertion: the stream state is correct and there is enough room in
  80503. * pending_buf.
  80504. */
  80505. local void putShortMSB (deflate_state *s, uInt b)
  80506. {
  80507. put_byte(s, (Byte)(b >> 8));
  80508. put_byte(s, (Byte)(b & 0xff));
  80509. }
  80510. /* =========================================================================
  80511. * Flush as much pending output as possible. All deflate() output goes
  80512. * through this function so some applications may wish to modify it
  80513. * to avoid allocating a large strm->next_out buffer and copying into it.
  80514. * (See also read_buf()).
  80515. */
  80516. local void flush_pending (z_streamp strm)
  80517. {
  80518. unsigned len = strm->state->pending;
  80519. if (len > strm->avail_out) len = strm->avail_out;
  80520. if (len == 0) return;
  80521. zmemcpy(strm->next_out, strm->state->pending_out, len);
  80522. strm->next_out += len;
  80523. strm->state->pending_out += len;
  80524. strm->total_out += len;
  80525. strm->avail_out -= len;
  80526. strm->state->pending -= len;
  80527. if (strm->state->pending == 0) {
  80528. strm->state->pending_out = strm->state->pending_buf;
  80529. }
  80530. }
  80531. /* ========================================================================= */
  80532. int ZEXPORT deflate (z_streamp strm, int flush)
  80533. {
  80534. int old_flush; /* value of flush param for previous deflate call */
  80535. deflate_state *s;
  80536. if (strm == Z_NULL || strm->state == Z_NULL ||
  80537. flush > Z_FINISH || flush < 0) {
  80538. return Z_STREAM_ERROR;
  80539. }
  80540. s = strm->state;
  80541. if (strm->next_out == Z_NULL ||
  80542. (strm->next_in == Z_NULL && strm->avail_in != 0) ||
  80543. (s->status == FINISH_STATE && flush != Z_FINISH)) {
  80544. ERR_RETURN(strm, Z_STREAM_ERROR);
  80545. }
  80546. if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
  80547. s->strm = strm; /* just in case */
  80548. old_flush = s->last_flush;
  80549. s->last_flush = flush;
  80550. /* Write the header */
  80551. if (s->status == INIT_STATE) {
  80552. #ifdef GZIP
  80553. if (s->wrap == 2) {
  80554. strm->adler = crc32(0L, Z_NULL, 0);
  80555. put_byte(s, 31);
  80556. put_byte(s, 139);
  80557. put_byte(s, 8);
  80558. if (s->gzhead == NULL) {
  80559. put_byte(s, 0);
  80560. put_byte(s, 0);
  80561. put_byte(s, 0);
  80562. put_byte(s, 0);
  80563. put_byte(s, 0);
  80564. put_byte(s, s->level == 9 ? 2 :
  80565. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  80566. 4 : 0));
  80567. put_byte(s, OS_CODE);
  80568. s->status = BUSY_STATE;
  80569. }
  80570. else {
  80571. put_byte(s, (s->gzhead->text ? 1 : 0) +
  80572. (s->gzhead->hcrc ? 2 : 0) +
  80573. (s->gzhead->extra == Z_NULL ? 0 : 4) +
  80574. (s->gzhead->name == Z_NULL ? 0 : 8) +
  80575. (s->gzhead->comment == Z_NULL ? 0 : 16)
  80576. );
  80577. put_byte(s, (Byte)(s->gzhead->time & 0xff));
  80578. put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));
  80579. put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));
  80580. put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));
  80581. put_byte(s, s->level == 9 ? 2 :
  80582. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  80583. 4 : 0));
  80584. put_byte(s, s->gzhead->os & 0xff);
  80585. if (s->gzhead->extra != NULL) {
  80586. put_byte(s, s->gzhead->extra_len & 0xff);
  80587. put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
  80588. }
  80589. if (s->gzhead->hcrc)
  80590. strm->adler = crc32(strm->adler, s->pending_buf,
  80591. s->pending);
  80592. s->gzindex = 0;
  80593. s->status = EXTRA_STATE;
  80594. }
  80595. }
  80596. else
  80597. #endif
  80598. {
  80599. uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
  80600. uInt level_flags;
  80601. if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
  80602. level_flags = 0;
  80603. else if (s->level < 6)
  80604. level_flags = 1;
  80605. else if (s->level == 6)
  80606. level_flags = 2;
  80607. else
  80608. level_flags = 3;
  80609. header |= (level_flags << 6);
  80610. if (s->strstart != 0) header |= PRESET_DICT;
  80611. header += 31 - (header % 31);
  80612. s->status = BUSY_STATE;
  80613. putShortMSB(s, header);
  80614. /* Save the adler32 of the preset dictionary: */
  80615. if (s->strstart != 0) {
  80616. putShortMSB(s, (uInt)(strm->adler >> 16));
  80617. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  80618. }
  80619. strm->adler = adler32(0L, Z_NULL, 0);
  80620. }
  80621. }
  80622. #ifdef GZIP
  80623. if (s->status == EXTRA_STATE) {
  80624. if (s->gzhead->extra != NULL) {
  80625. uInt beg = s->pending; /* start of bytes to update crc */
  80626. while (s->gzindex < (s->gzhead->extra_len & 0xffff)) {
  80627. if (s->pending == s->pending_buf_size) {
  80628. if (s->gzhead->hcrc && s->pending > beg)
  80629. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  80630. s->pending - beg);
  80631. flush_pending(strm);
  80632. beg = s->pending;
  80633. if (s->pending == s->pending_buf_size)
  80634. break;
  80635. }
  80636. put_byte(s, s->gzhead->extra[s->gzindex]);
  80637. s->gzindex++;
  80638. }
  80639. if (s->gzhead->hcrc && s->pending > beg)
  80640. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  80641. s->pending - beg);
  80642. if (s->gzindex == s->gzhead->extra_len) {
  80643. s->gzindex = 0;
  80644. s->status = NAME_STATE;
  80645. }
  80646. }
  80647. else
  80648. s->status = NAME_STATE;
  80649. }
  80650. if (s->status == NAME_STATE) {
  80651. if (s->gzhead->name != NULL) {
  80652. uInt beg = s->pending; /* start of bytes to update crc */
  80653. int val;
  80654. do {
  80655. if (s->pending == s->pending_buf_size) {
  80656. if (s->gzhead->hcrc && s->pending > beg)
  80657. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  80658. s->pending - beg);
  80659. flush_pending(strm);
  80660. beg = s->pending;
  80661. if (s->pending == s->pending_buf_size) {
  80662. val = 1;
  80663. break;
  80664. }
  80665. }
  80666. val = s->gzhead->name[s->gzindex++];
  80667. put_byte(s, val);
  80668. } while (val != 0);
  80669. if (s->gzhead->hcrc && s->pending > beg)
  80670. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  80671. s->pending - beg);
  80672. if (val == 0) {
  80673. s->gzindex = 0;
  80674. s->status = COMMENT_STATE;
  80675. }
  80676. }
  80677. else
  80678. s->status = COMMENT_STATE;
  80679. }
  80680. if (s->status == COMMENT_STATE) {
  80681. if (s->gzhead->comment != NULL) {
  80682. uInt beg = s->pending; /* start of bytes to update crc */
  80683. int val;
  80684. do {
  80685. if (s->pending == s->pending_buf_size) {
  80686. if (s->gzhead->hcrc && s->pending > beg)
  80687. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  80688. s->pending - beg);
  80689. flush_pending(strm);
  80690. beg = s->pending;
  80691. if (s->pending == s->pending_buf_size) {
  80692. val = 1;
  80693. break;
  80694. }
  80695. }
  80696. val = s->gzhead->comment[s->gzindex++];
  80697. put_byte(s, val);
  80698. } while (val != 0);
  80699. if (s->gzhead->hcrc && s->pending > beg)
  80700. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  80701. s->pending - beg);
  80702. if (val == 0)
  80703. s->status = HCRC_STATE;
  80704. }
  80705. else
  80706. s->status = HCRC_STATE;
  80707. }
  80708. if (s->status == HCRC_STATE) {
  80709. if (s->gzhead->hcrc) {
  80710. if (s->pending + 2 > s->pending_buf_size)
  80711. flush_pending(strm);
  80712. if (s->pending + 2 <= s->pending_buf_size) {
  80713. put_byte(s, (Byte)(strm->adler & 0xff));
  80714. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  80715. strm->adler = crc32(0L, Z_NULL, 0);
  80716. s->status = BUSY_STATE;
  80717. }
  80718. }
  80719. else
  80720. s->status = BUSY_STATE;
  80721. }
  80722. #endif
  80723. /* Flush as much pending output as possible */
  80724. if (s->pending != 0) {
  80725. flush_pending(strm);
  80726. if (strm->avail_out == 0) {
  80727. /* Since avail_out is 0, deflate will be called again with
  80728. * more output space, but possibly with both pending and
  80729. * avail_in equal to zero. There won't be anything to do,
  80730. * but this is not an error situation so make sure we
  80731. * return OK instead of BUF_ERROR at next call of deflate:
  80732. */
  80733. s->last_flush = -1;
  80734. return Z_OK;
  80735. }
  80736. /* Make sure there is something to do and avoid duplicate consecutive
  80737. * flushes. For repeated and useless calls with Z_FINISH, we keep
  80738. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  80739. */
  80740. } else if (strm->avail_in == 0 && flush <= old_flush &&
  80741. flush != Z_FINISH) {
  80742. ERR_RETURN(strm, Z_BUF_ERROR);
  80743. }
  80744. /* User must not provide more input after the first FINISH: */
  80745. if (s->status == FINISH_STATE && strm->avail_in != 0) {
  80746. ERR_RETURN(strm, Z_BUF_ERROR);
  80747. }
  80748. /* Start a new block or continue the current one.
  80749. */
  80750. if (strm->avail_in != 0 || s->lookahead != 0 ||
  80751. (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
  80752. block_state bstate;
  80753. bstate = (*(configuration_table[s->level].func))(s, flush);
  80754. if (bstate == finish_started || bstate == finish_done) {
  80755. s->status = FINISH_STATE;
  80756. }
  80757. if (bstate == need_more || bstate == finish_started) {
  80758. if (strm->avail_out == 0) {
  80759. s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
  80760. }
  80761. return Z_OK;
  80762. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  80763. * of deflate should use the same flush parameter to make sure
  80764. * that the flush is complete. So we don't have to output an
  80765. * empty block here, this will be done at next call. This also
  80766. * ensures that for a very small output buffer, we emit at most
  80767. * one empty block.
  80768. */
  80769. }
  80770. if (bstate == block_done) {
  80771. if (flush == Z_PARTIAL_FLUSH) {
  80772. _tr_align(s);
  80773. } else { /* FULL_FLUSH or SYNC_FLUSH */
  80774. _tr_stored_block(s, (char*)0, 0L, 0);
  80775. /* For a full flush, this empty block will be recognized
  80776. * as a special marker by inflate_sync().
  80777. */
  80778. if (flush == Z_FULL_FLUSH) {
  80779. CLEAR_HASH(s); /* forget history */
  80780. }
  80781. }
  80782. flush_pending(strm);
  80783. if (strm->avail_out == 0) {
  80784. s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  80785. return Z_OK;
  80786. }
  80787. }
  80788. }
  80789. Assert(strm->avail_out > 0, "bug2");
  80790. if (flush != Z_FINISH) return Z_OK;
  80791. if (s->wrap <= 0) return Z_STREAM_END;
  80792. /* Write the trailer */
  80793. #ifdef GZIP
  80794. if (s->wrap == 2) {
  80795. put_byte(s, (Byte)(strm->adler & 0xff));
  80796. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  80797. put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
  80798. put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
  80799. put_byte(s, (Byte)(strm->total_in & 0xff));
  80800. put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
  80801. put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
  80802. put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
  80803. }
  80804. else
  80805. #endif
  80806. {
  80807. putShortMSB(s, (uInt)(strm->adler >> 16));
  80808. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  80809. }
  80810. flush_pending(strm);
  80811. /* If avail_out is zero, the application will call deflate again
  80812. * to flush the rest.
  80813. */
  80814. if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
  80815. return s->pending != 0 ? Z_OK : Z_STREAM_END;
  80816. }
  80817. /* ========================================================================= */
  80818. int ZEXPORT deflateEnd (z_streamp strm)
  80819. {
  80820. int status;
  80821. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  80822. status = strm->state->status;
  80823. if (status != INIT_STATE &&
  80824. status != EXTRA_STATE &&
  80825. status != NAME_STATE &&
  80826. status != COMMENT_STATE &&
  80827. status != HCRC_STATE &&
  80828. status != BUSY_STATE &&
  80829. status != FINISH_STATE) {
  80830. return Z_STREAM_ERROR;
  80831. }
  80832. /* Deallocate in reverse order of allocations: */
  80833. TRY_FREE(strm, strm->state->pending_buf);
  80834. TRY_FREE(strm, strm->state->head);
  80835. TRY_FREE(strm, strm->state->prev);
  80836. TRY_FREE(strm, strm->state->window);
  80837. ZFREE(strm, strm->state);
  80838. strm->state = Z_NULL;
  80839. return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
  80840. }
  80841. /* =========================================================================
  80842. * Copy the source state to the destination state.
  80843. * To simplify the source, this is not supported for 16-bit MSDOS (which
  80844. * doesn't have enough memory anyway to duplicate compression states).
  80845. */
  80846. int ZEXPORT deflateCopy (z_streamp dest, z_streamp source)
  80847. {
  80848. #ifdef MAXSEG_64K
  80849. return Z_STREAM_ERROR;
  80850. #else
  80851. deflate_state *ds;
  80852. deflate_state *ss;
  80853. ushf *overlay;
  80854. if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
  80855. return Z_STREAM_ERROR;
  80856. }
  80857. ss = source->state;
  80858. zmemcpy(dest, source, sizeof(z_stream));
  80859. ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
  80860. if (ds == Z_NULL) return Z_MEM_ERROR;
  80861. dest->state = (struct internal_state FAR *) ds;
  80862. zmemcpy(ds, ss, sizeof(deflate_state));
  80863. ds->strm = dest;
  80864. ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
  80865. ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos));
  80866. ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos));
  80867. overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);
  80868. ds->pending_buf = (uchf *) overlay;
  80869. if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
  80870. ds->pending_buf == Z_NULL) {
  80871. deflateEnd (dest);
  80872. return Z_MEM_ERROR;
  80873. }
  80874. /* following zmemcpy do not work for 16-bit MSDOS */
  80875. zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
  80876. zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos));
  80877. zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos));
  80878. zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
  80879. ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
  80880. ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
  80881. ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
  80882. ds->l_desc.dyn_tree = ds->dyn_ltree;
  80883. ds->d_desc.dyn_tree = ds->dyn_dtree;
  80884. ds->bl_desc.dyn_tree = ds->bl_tree;
  80885. return Z_OK;
  80886. #endif /* MAXSEG_64K */
  80887. }
  80888. /* ===========================================================================
  80889. * Read a new buffer from the current input stream, update the adler32
  80890. * and total number of bytes read. All deflate() input goes through
  80891. * this function so some applications may wish to modify it to avoid
  80892. * allocating a large strm->next_in buffer and copying from it.
  80893. * (See also flush_pending()).
  80894. */
  80895. local int read_buf (z_streamp strm, Bytef *buf, unsigned size)
  80896. {
  80897. unsigned len = strm->avail_in;
  80898. if (len > size) len = size;
  80899. if (len == 0) return 0;
  80900. strm->avail_in -= len;
  80901. if (strm->state->wrap == 1) {
  80902. strm->adler = adler32(strm->adler, strm->next_in, len);
  80903. }
  80904. #ifdef GZIP
  80905. else if (strm->state->wrap == 2) {
  80906. strm->adler = crc32(strm->adler, strm->next_in, len);
  80907. }
  80908. #endif
  80909. zmemcpy(buf, strm->next_in, len);
  80910. strm->next_in += len;
  80911. strm->total_in += len;
  80912. return (int)len;
  80913. }
  80914. /* ===========================================================================
  80915. * Initialize the "longest match" routines for a new zlib stream
  80916. */
  80917. local void lm_init (deflate_state *s)
  80918. {
  80919. s->window_size = (ulg)2L*s->w_size;
  80920. CLEAR_HASH(s);
  80921. /* Set the default configuration parameters:
  80922. */
  80923. s->max_lazy_match = configuration_table[s->level].max_lazy;
  80924. s->good_match = configuration_table[s->level].good_length;
  80925. s->nice_match = configuration_table[s->level].nice_length;
  80926. s->max_chain_length = configuration_table[s->level].max_chain;
  80927. s->strstart = 0;
  80928. s->block_start = 0L;
  80929. s->lookahead = 0;
  80930. s->match_length = s->prev_length = MIN_MATCH-1;
  80931. s->match_available = 0;
  80932. s->ins_h = 0;
  80933. #ifndef FASTEST
  80934. #ifdef ASMV
  80935. match_init(); /* initialize the asm code */
  80936. #endif
  80937. #endif
  80938. }
  80939. #ifndef FASTEST
  80940. /* ===========================================================================
  80941. * Set match_start to the longest match starting at the given string and
  80942. * return its length. Matches shorter or equal to prev_length are discarded,
  80943. * in which case the result is equal to prev_length and match_start is
  80944. * garbage.
  80945. * IN assertions: cur_match is the head of the hash chain for the current
  80946. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  80947. * OUT assertion: the match length is not greater than s->lookahead.
  80948. */
  80949. #ifndef ASMV
  80950. /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
  80951. * match.S. The code will be functionally equivalent.
  80952. */
  80953. local uInt longest_match(deflate_state *s, IPos cur_match)
  80954. {
  80955. unsigned chain_length = s->max_chain_length;/* max hash chain length */
  80956. register Bytef *scan = s->window + s->strstart; /* current string */
  80957. register Bytef *match; /* matched string */
  80958. register int len; /* length of current match */
  80959. int best_len = s->prev_length; /* best match length so far */
  80960. int nice_match = s->nice_match; /* stop if match long enough */
  80961. IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
  80962. s->strstart - (IPos)MAX_DIST(s) : NIL;
  80963. /* Stop when cur_match becomes <= limit. To simplify the code,
  80964. * we prevent matches with the string of window index 0.
  80965. */
  80966. Posf *prev = s->prev;
  80967. uInt wmask = s->w_mask;
  80968. #ifdef UNALIGNED_OK
  80969. /* Compare two bytes at a time. Note: this is not always beneficial.
  80970. * Try with and without -DUNALIGNED_OK to check.
  80971. */
  80972. register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
  80973. register ush scan_start = *(ushf*)scan;
  80974. register ush scan_end = *(ushf*)(scan+best_len-1);
  80975. #else
  80976. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  80977. register Byte scan_end1 = scan[best_len-1];
  80978. register Byte scan_end = scan[best_len];
  80979. #endif
  80980. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  80981. * It is easy to get rid of this optimization if necessary.
  80982. */
  80983. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  80984. /* Do not waste too much time if we already have a good match: */
  80985. if (s->prev_length >= s->good_match) {
  80986. chain_length >>= 2;
  80987. }
  80988. /* Do not look for matches beyond the end of the input. This is necessary
  80989. * to make deflate deterministic.
  80990. */
  80991. if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
  80992. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  80993. do {
  80994. Assert(cur_match < s->strstart, "no future");
  80995. match = s->window + cur_match;
  80996. /* Skip to next match if the match length cannot increase
  80997. * or if the match length is less than 2. Note that the checks below
  80998. * for insufficient lookahead only occur occasionally for performance
  80999. * reasons. Therefore uninitialized memory will be accessed, and
  81000. * conditional jumps will be made that depend on those values.
  81001. * However the length of the match is limited to the lookahead, so
  81002. * the output of deflate is not affected by the uninitialized values.
  81003. */
  81004. #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
  81005. /* This code assumes sizeof(unsigned short) == 2. Do not use
  81006. * UNALIGNED_OK if your compiler uses a different size.
  81007. */
  81008. if (*(ushf*)(match+best_len-1) != scan_end ||
  81009. *(ushf*)match != scan_start) continue;
  81010. /* It is not necessary to compare scan[2] and match[2] since they are
  81011. * always equal when the other bytes match, given that the hash keys
  81012. * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
  81013. * strstart+3, +5, ... up to strstart+257. We check for insufficient
  81014. * lookahead only every 4th comparison; the 128th check will be made
  81015. * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
  81016. * necessary to put more guard bytes at the end of the window, or
  81017. * to check more often for insufficient lookahead.
  81018. */
  81019. Assert(scan[2] == match[2], "scan[2]?");
  81020. scan++, match++;
  81021. do {
  81022. } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  81023. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  81024. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  81025. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  81026. scan < strend);
  81027. /* The funny "do {}" generates better code on most compilers */
  81028. /* Here, scan <= window+strstart+257 */
  81029. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  81030. if (*scan == *match) scan++;
  81031. len = (MAX_MATCH - 1) - (int)(strend-scan);
  81032. scan = strend - (MAX_MATCH-1);
  81033. #else /* UNALIGNED_OK */
  81034. if (match[best_len] != scan_end ||
  81035. match[best_len-1] != scan_end1 ||
  81036. *match != *scan ||
  81037. *++match != scan[1]) continue;
  81038. /* The check at best_len-1 can be removed because it will be made
  81039. * again later. (This heuristic is not always a win.)
  81040. * It is not necessary to compare scan[2] and match[2] since they
  81041. * are always equal when the other bytes match, given that
  81042. * the hash keys are equal and that HASH_BITS >= 8.
  81043. */
  81044. scan += 2, match++;
  81045. Assert(*scan == *match, "match[2]?");
  81046. /* We check for insufficient lookahead only every 8th comparison;
  81047. * the 256th check will be made at strstart+258.
  81048. */
  81049. do {
  81050. } while (*++scan == *++match && *++scan == *++match &&
  81051. *++scan == *++match && *++scan == *++match &&
  81052. *++scan == *++match && *++scan == *++match &&
  81053. *++scan == *++match && *++scan == *++match &&
  81054. scan < strend);
  81055. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  81056. len = MAX_MATCH - (int)(strend - scan);
  81057. scan = strend - MAX_MATCH;
  81058. #endif /* UNALIGNED_OK */
  81059. if (len > best_len) {
  81060. s->match_start = cur_match;
  81061. best_len = len;
  81062. if (len >= nice_match) break;
  81063. #ifdef UNALIGNED_OK
  81064. scan_end = *(ushf*)(scan+best_len-1);
  81065. #else
  81066. scan_end1 = scan[best_len-1];
  81067. scan_end = scan[best_len];
  81068. #endif
  81069. }
  81070. } while ((cur_match = prev[cur_match & wmask]) > limit
  81071. && --chain_length != 0);
  81072. if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
  81073. return s->lookahead;
  81074. }
  81075. #endif /* ASMV */
  81076. #endif /* FASTEST */
  81077. /* ---------------------------------------------------------------------------
  81078. * Optimized version for level == 1 or strategy == Z_RLE only
  81079. */
  81080. local uInt longest_match_fast (deflate_state *s, IPos cur_match)
  81081. {
  81082. register Bytef *scan = s->window + s->strstart; /* current string */
  81083. register Bytef *match; /* matched string */
  81084. register int len; /* length of current match */
  81085. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  81086. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  81087. * It is easy to get rid of this optimization if necessary.
  81088. */
  81089. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  81090. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  81091. Assert(cur_match < s->strstart, "no future");
  81092. match = s->window + cur_match;
  81093. /* Return failure if the match length is less than 2:
  81094. */
  81095. if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
  81096. /* The check at best_len-1 can be removed because it will be made
  81097. * again later. (This heuristic is not always a win.)
  81098. * It is not necessary to compare scan[2] and match[2] since they
  81099. * are always equal when the other bytes match, given that
  81100. * the hash keys are equal and that HASH_BITS >= 8.
  81101. */
  81102. scan += 2, match += 2;
  81103. Assert(*scan == *match, "match[2]?");
  81104. /* We check for insufficient lookahead only every 8th comparison;
  81105. * the 256th check will be made at strstart+258.
  81106. */
  81107. do {
  81108. } while (*++scan == *++match && *++scan == *++match &&
  81109. *++scan == *++match && *++scan == *++match &&
  81110. *++scan == *++match && *++scan == *++match &&
  81111. *++scan == *++match && *++scan == *++match &&
  81112. scan < strend);
  81113. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  81114. len = MAX_MATCH - (int)(strend - scan);
  81115. if (len < MIN_MATCH) return MIN_MATCH - 1;
  81116. s->match_start = cur_match;
  81117. return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
  81118. }
  81119. #ifdef DEBUG
  81120. /* ===========================================================================
  81121. * Check that the match at match_start is indeed a match.
  81122. */
  81123. local void check_match(deflate_state *s, IPos start, IPos match, int length)
  81124. {
  81125. /* check that the match is indeed a match */
  81126. if (zmemcmp(s->window + match,
  81127. s->window + start, length) != EQUAL) {
  81128. fprintf(stderr, " start %u, match %u, length %d\n",
  81129. start, match, length);
  81130. do {
  81131. fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
  81132. } while (--length != 0);
  81133. z_error("invalid match");
  81134. }
  81135. if (z_verbose > 1) {
  81136. fprintf(stderr,"\\[%d,%d]", start-match, length);
  81137. do { putc(s->window[start++], stderr); } while (--length != 0);
  81138. }
  81139. }
  81140. #else
  81141. # define check_match(s, start, match, length)
  81142. #endif /* DEBUG */
  81143. /* ===========================================================================
  81144. * Fill the window when the lookahead becomes insufficient.
  81145. * Updates strstart and lookahead.
  81146. *
  81147. * IN assertion: lookahead < MIN_LOOKAHEAD
  81148. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  81149. * At least one byte has been read, or avail_in == 0; reads are
  81150. * performed for at least two bytes (required for the zip translate_eol
  81151. * option -- not supported here).
  81152. */
  81153. local void fill_window (deflate_state *s)
  81154. {
  81155. register unsigned n, m;
  81156. register Posf *p;
  81157. unsigned more; /* Amount of free space at the end of the window. */
  81158. uInt wsize = s->w_size;
  81159. do {
  81160. more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
  81161. /* Deal with !@#$% 64K limit: */
  81162. if (sizeof(int) <= 2) {
  81163. if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  81164. more = wsize;
  81165. } else if (more == (unsigned)(-1)) {
  81166. /* Very unlikely, but possible on 16 bit machine if
  81167. * strstart == 0 && lookahead == 1 (input done a byte at time)
  81168. */
  81169. more--;
  81170. }
  81171. }
  81172. /* If the window is almost full and there is insufficient lookahead,
  81173. * move the upper half to the lower one to make room in the upper half.
  81174. */
  81175. if (s->strstart >= wsize+MAX_DIST(s)) {
  81176. zmemcpy(s->window, s->window+wsize, (unsigned)wsize);
  81177. s->match_start -= wsize;
  81178. s->strstart -= wsize; /* we now have strstart >= MAX_DIST */
  81179. s->block_start -= (long) wsize;
  81180. /* Slide the hash table (could be avoided with 32 bit values
  81181. at the expense of memory usage). We slide even when level == 0
  81182. to keep the hash table consistent if we switch back to level > 0
  81183. later. (Using level 0 permanently is not an optimal usage of
  81184. zlib, so we don't care about this pathological case.)
  81185. */
  81186. /* %%% avoid this when Z_RLE */
  81187. n = s->hash_size;
  81188. p = &s->head[n];
  81189. do {
  81190. m = *--p;
  81191. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  81192. } while (--n);
  81193. n = wsize;
  81194. #ifndef FASTEST
  81195. p = &s->prev[n];
  81196. do {
  81197. m = *--p;
  81198. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  81199. /* If n is not on any hash chain, prev[n] is garbage but
  81200. * its value will never be used.
  81201. */
  81202. } while (--n);
  81203. #endif
  81204. more += wsize;
  81205. }
  81206. if (s->strm->avail_in == 0) return;
  81207. /* If there was no sliding:
  81208. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  81209. * more == window_size - lookahead - strstart
  81210. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  81211. * => more >= window_size - 2*WSIZE + 2
  81212. * In the BIG_MEM or MMAP case (not yet supported),
  81213. * window_size == input_size + MIN_LOOKAHEAD &&
  81214. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  81215. * Otherwise, window_size == 2*WSIZE so more >= 2.
  81216. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  81217. */
  81218. Assert(more >= 2, "more < 2");
  81219. n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
  81220. s->lookahead += n;
  81221. /* Initialize the hash value now that we have some input: */
  81222. if (s->lookahead >= MIN_MATCH) {
  81223. s->ins_h = s->window[s->strstart];
  81224. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  81225. #if MIN_MATCH != 3
  81226. Call UPDATE_HASH() MIN_MATCH-3 more times
  81227. #endif
  81228. }
  81229. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  81230. * but this is not important since only literal bytes will be emitted.
  81231. */
  81232. } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
  81233. }
  81234. /* ===========================================================================
  81235. * Flush the current block, with given end-of-file flag.
  81236. * IN assertion: strstart is set to the end of the current match.
  81237. */
  81238. #define FLUSH_BLOCK_ONLY(s, eof) { \
  81239. _tr_flush_block(s, (s->block_start >= 0L ? \
  81240. (charf *)&s->window[(unsigned)s->block_start] : \
  81241. (charf *)Z_NULL), \
  81242. (ulg)((long)s->strstart - s->block_start), \
  81243. (eof)); \
  81244. s->block_start = s->strstart; \
  81245. flush_pending(s->strm); \
  81246. Tracev((stderr,"[FLUSH]")); \
  81247. }
  81248. /* Same but force premature exit if necessary. */
  81249. #define FLUSH_BLOCK(s, eof) { \
  81250. FLUSH_BLOCK_ONLY(s, eof); \
  81251. if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \
  81252. }
  81253. /* ===========================================================================
  81254. * Copy without compression as much as possible from the input stream, return
  81255. * the current block state.
  81256. * This function does not insert new strings in the dictionary since
  81257. * uncompressible data is probably not useful. This function is used
  81258. * only for the level=0 compression option.
  81259. * NOTE: this function should be optimized to avoid extra copying from
  81260. * window to pending_buf.
  81261. */
  81262. local block_state deflate_stored(deflate_state *s, int flush)
  81263. {
  81264. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  81265. * to pending_buf_size, and each stored block has a 5 byte header:
  81266. */
  81267. ulg max_block_size = 0xffff;
  81268. ulg max_start;
  81269. if (max_block_size > s->pending_buf_size - 5) {
  81270. max_block_size = s->pending_buf_size - 5;
  81271. }
  81272. /* Copy as much as possible from input to output: */
  81273. for (;;) {
  81274. /* Fill the window as much as possible: */
  81275. if (s->lookahead <= 1) {
  81276. Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  81277. s->block_start >= (long)s->w_size, "slide too late");
  81278. fill_window(s);
  81279. if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
  81280. if (s->lookahead == 0) break; /* flush the current block */
  81281. }
  81282. Assert(s->block_start >= 0L, "block gone");
  81283. s->strstart += s->lookahead;
  81284. s->lookahead = 0;
  81285. /* Emit a stored block if pending_buf will be full: */
  81286. max_start = s->block_start + max_block_size;
  81287. if (s->strstart == 0 || (ulg)s->strstart >= max_start) {
  81288. /* strstart == 0 is possible when wraparound on 16-bit machine */
  81289. s->lookahead = (uInt)(s->strstart - max_start);
  81290. s->strstart = (uInt)max_start;
  81291. FLUSH_BLOCK(s, 0);
  81292. }
  81293. /* Flush if we may have to slide, otherwise block_start may become
  81294. * negative and the data will be gone:
  81295. */
  81296. if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
  81297. FLUSH_BLOCK(s, 0);
  81298. }
  81299. }
  81300. FLUSH_BLOCK(s, flush == Z_FINISH);
  81301. return flush == Z_FINISH ? finish_done : block_done;
  81302. }
  81303. /* ===========================================================================
  81304. * Compress as much as possible from the input stream, return the current
  81305. * block state.
  81306. * This function does not perform lazy evaluation of matches and inserts
  81307. * new strings in the dictionary only for unmatched strings or for short
  81308. * matches. It is used only for the fast compression options.
  81309. */
  81310. local block_state deflate_fast(deflate_state *s, int flush)
  81311. {
  81312. IPos hash_head = NIL; /* head of the hash chain */
  81313. int bflush; /* set if current block must be flushed */
  81314. for (;;) {
  81315. /* Make sure that we always have enough lookahead, except
  81316. * at the end of the input file. We need MAX_MATCH bytes
  81317. * for the next match, plus MIN_MATCH bytes to insert the
  81318. * string following the next match.
  81319. */
  81320. if (s->lookahead < MIN_LOOKAHEAD) {
  81321. fill_window(s);
  81322. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  81323. return need_more;
  81324. }
  81325. if (s->lookahead == 0) break; /* flush the current block */
  81326. }
  81327. /* Insert the string window[strstart .. strstart+2] in the
  81328. * dictionary, and set hash_head to the head of the hash chain:
  81329. */
  81330. if (s->lookahead >= MIN_MATCH) {
  81331. INSERT_STRING(s, s->strstart, hash_head);
  81332. }
  81333. /* Find the longest match, discarding those <= prev_length.
  81334. * At this point we have always match_length < MIN_MATCH
  81335. */
  81336. if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
  81337. /* To simplify the code, we prevent matches with the string
  81338. * of window index 0 (in particular we have to avoid a match
  81339. * of the string with itself at the start of the input file).
  81340. */
  81341. #ifdef FASTEST
  81342. if ((s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) ||
  81343. (s->strategy == Z_RLE && s->strstart - hash_head == 1)) {
  81344. s->match_length = longest_match_fast (s, hash_head);
  81345. }
  81346. #else
  81347. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  81348. s->match_length = longest_match (s, hash_head);
  81349. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  81350. s->match_length = longest_match_fast (s, hash_head);
  81351. }
  81352. #endif
  81353. /* longest_match() or longest_match_fast() sets match_start */
  81354. }
  81355. if (s->match_length >= MIN_MATCH) {
  81356. check_match(s, s->strstart, s->match_start, s->match_length);
  81357. _tr_tally_dist(s, s->strstart - s->match_start,
  81358. s->match_length - MIN_MATCH, bflush);
  81359. s->lookahead -= s->match_length;
  81360. /* Insert new strings in the hash table only if the match length
  81361. * is not too large. This saves time but degrades compression.
  81362. */
  81363. #ifndef FASTEST
  81364. if (s->match_length <= s->max_insert_length &&
  81365. s->lookahead >= MIN_MATCH) {
  81366. s->match_length--; /* string at strstart already in table */
  81367. do {
  81368. s->strstart++;
  81369. INSERT_STRING(s, s->strstart, hash_head);
  81370. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  81371. * always MIN_MATCH bytes ahead.
  81372. */
  81373. } while (--s->match_length != 0);
  81374. s->strstart++;
  81375. } else
  81376. #endif
  81377. {
  81378. s->strstart += s->match_length;
  81379. s->match_length = 0;
  81380. s->ins_h = s->window[s->strstart];
  81381. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  81382. #if MIN_MATCH != 3
  81383. Call UPDATE_HASH() MIN_MATCH-3 more times
  81384. #endif
  81385. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  81386. * matter since it will be recomputed at next deflate call.
  81387. */
  81388. }
  81389. } else {
  81390. /* No match, output a literal byte */
  81391. Tracevv((stderr,"%c", s->window[s->strstart]));
  81392. _tr_tally_lit (s, s->window[s->strstart], bflush);
  81393. s->lookahead--;
  81394. s->strstart++;
  81395. }
  81396. if (bflush) FLUSH_BLOCK(s, 0);
  81397. }
  81398. FLUSH_BLOCK(s, flush == Z_FINISH);
  81399. return flush == Z_FINISH ? finish_done : block_done;
  81400. }
  81401. #ifndef FASTEST
  81402. /* ===========================================================================
  81403. * Same as above, but achieves better compression. We use a lazy
  81404. * evaluation for matches: a match is finally adopted only if there is
  81405. * no better match at the next window position.
  81406. */
  81407. local block_state deflate_slow(deflate_state *s, int flush)
  81408. {
  81409. IPos hash_head = NIL; /* head of hash chain */
  81410. int bflush; /* set if current block must be flushed */
  81411. /* Process the input block. */
  81412. for (;;) {
  81413. /* Make sure that we always have enough lookahead, except
  81414. * at the end of the input file. We need MAX_MATCH bytes
  81415. * for the next match, plus MIN_MATCH bytes to insert the
  81416. * string following the next match.
  81417. */
  81418. if (s->lookahead < MIN_LOOKAHEAD) {
  81419. fill_window(s);
  81420. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  81421. return need_more;
  81422. }
  81423. if (s->lookahead == 0) break; /* flush the current block */
  81424. }
  81425. /* Insert the string window[strstart .. strstart+2] in the
  81426. * dictionary, and set hash_head to the head of the hash chain:
  81427. */
  81428. if (s->lookahead >= MIN_MATCH) {
  81429. INSERT_STRING(s, s->strstart, hash_head);
  81430. }
  81431. /* Find the longest match, discarding those <= prev_length.
  81432. */
  81433. s->prev_length = s->match_length, s->prev_match = s->match_start;
  81434. s->match_length = MIN_MATCH-1;
  81435. if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
  81436. s->strstart - hash_head <= MAX_DIST(s)) {
  81437. /* To simplify the code, we prevent matches with the string
  81438. * of window index 0 (in particular we have to avoid a match
  81439. * of the string with itself at the start of the input file).
  81440. */
  81441. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  81442. s->match_length = longest_match (s, hash_head);
  81443. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  81444. s->match_length = longest_match_fast (s, hash_head);
  81445. }
  81446. /* longest_match() or longest_match_fast() sets match_start */
  81447. if (s->match_length <= 5 && (s->strategy == Z_FILTERED
  81448. #if TOO_FAR <= 32767
  81449. || (s->match_length == MIN_MATCH &&
  81450. s->strstart - s->match_start > TOO_FAR)
  81451. #endif
  81452. )) {
  81453. /* If prev_match is also MIN_MATCH, match_start is garbage
  81454. * but we will ignore the current match anyway.
  81455. */
  81456. s->match_length = MIN_MATCH-1;
  81457. }
  81458. }
  81459. /* If there was a match at the previous step and the current
  81460. * match is not better, output the previous match:
  81461. */
  81462. if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
  81463. uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
  81464. /* Do not insert strings in hash table beyond this. */
  81465. check_match(s, s->strstart-1, s->prev_match, s->prev_length);
  81466. _tr_tally_dist(s, s->strstart -1 - s->prev_match,
  81467. s->prev_length - MIN_MATCH, bflush);
  81468. /* Insert in hash table all strings up to the end of the match.
  81469. * strstart-1 and strstart are already inserted. If there is not
  81470. * enough lookahead, the last two strings are not inserted in
  81471. * the hash table.
  81472. */
  81473. s->lookahead -= s->prev_length-1;
  81474. s->prev_length -= 2;
  81475. do {
  81476. if (++s->strstart <= max_insert) {
  81477. INSERT_STRING(s, s->strstart, hash_head);
  81478. }
  81479. } while (--s->prev_length != 0);
  81480. s->match_available = 0;
  81481. s->match_length = MIN_MATCH-1;
  81482. s->strstart++;
  81483. if (bflush) FLUSH_BLOCK(s, 0);
  81484. } else if (s->match_available) {
  81485. /* If there was no match at the previous position, output a
  81486. * single literal. If there was a match but the current match
  81487. * is longer, truncate the previous match to a single literal.
  81488. */
  81489. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  81490. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  81491. if (bflush) {
  81492. FLUSH_BLOCK_ONLY(s, 0);
  81493. }
  81494. s->strstart++;
  81495. s->lookahead--;
  81496. if (s->strm->avail_out == 0) return need_more;
  81497. } else {
  81498. /* There is no previous match to compare with, wait for
  81499. * the next step to decide.
  81500. */
  81501. s->match_available = 1;
  81502. s->strstart++;
  81503. s->lookahead--;
  81504. }
  81505. }
  81506. Assert (flush != Z_NO_FLUSH, "no flush?");
  81507. if (s->match_available) {
  81508. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  81509. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  81510. s->match_available = 0;
  81511. }
  81512. FLUSH_BLOCK(s, flush == Z_FINISH);
  81513. return flush == Z_FINISH ? finish_done : block_done;
  81514. }
  81515. #endif /* FASTEST */
  81516. #if 0
  81517. /* ===========================================================================
  81518. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  81519. * one. Do not maintain a hash table. (It will be regenerated if this run of
  81520. * deflate switches away from Z_RLE.)
  81521. */
  81522. local block_state deflate_rle(s, flush)
  81523. deflate_state *s;
  81524. int flush;
  81525. {
  81526. int bflush; /* set if current block must be flushed */
  81527. uInt run; /* length of run */
  81528. uInt max; /* maximum length of run */
  81529. uInt prev; /* byte at distance one to match */
  81530. Bytef *scan; /* scan for end of run */
  81531. for (;;) {
  81532. /* Make sure that we always have enough lookahead, except
  81533. * at the end of the input file. We need MAX_MATCH bytes
  81534. * for the longest encodable run.
  81535. */
  81536. if (s->lookahead < MAX_MATCH) {
  81537. fill_window(s);
  81538. if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) {
  81539. return need_more;
  81540. }
  81541. if (s->lookahead == 0) break; /* flush the current block */
  81542. }
  81543. /* See how many times the previous byte repeats */
  81544. run = 0;
  81545. if (s->strstart > 0) { /* if there is a previous byte, that is */
  81546. max = s->lookahead < MAX_MATCH ? s->lookahead : MAX_MATCH;
  81547. scan = s->window + s->strstart - 1;
  81548. prev = *scan++;
  81549. do {
  81550. if (*scan++ != prev)
  81551. break;
  81552. } while (++run < max);
  81553. }
  81554. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  81555. if (run >= MIN_MATCH) {
  81556. check_match(s, s->strstart, s->strstart - 1, run);
  81557. _tr_tally_dist(s, 1, run - MIN_MATCH, bflush);
  81558. s->lookahead -= run;
  81559. s->strstart += run;
  81560. } else {
  81561. /* No match, output a literal byte */
  81562. Tracevv((stderr,"%c", s->window[s->strstart]));
  81563. _tr_tally_lit (s, s->window[s->strstart], bflush);
  81564. s->lookahead--;
  81565. s->strstart++;
  81566. }
  81567. if (bflush) FLUSH_BLOCK(s, 0);
  81568. }
  81569. FLUSH_BLOCK(s, flush == Z_FINISH);
  81570. return flush == Z_FINISH ? finish_done : block_done;
  81571. }
  81572. #endif
  81573. /*** End of inlined file: deflate.c ***/
  81574. /*** Start of inlined file: inffast.c ***/
  81575. /*** Start of inlined file: inftrees.h ***/
  81576. /* WARNING: this file should *not* be used by applications. It is
  81577. part of the implementation of the compression library and is
  81578. subject to change. Applications should only use zlib.h.
  81579. */
  81580. #ifndef _INFTREES_H_
  81581. #define _INFTREES_H_
  81582. /* Structure for decoding tables. Each entry provides either the
  81583. information needed to do the operation requested by the code that
  81584. indexed that table entry, or it provides a pointer to another
  81585. table that indexes more bits of the code. op indicates whether
  81586. the entry is a pointer to another table, a literal, a length or
  81587. distance, an end-of-block, or an invalid code. For a table
  81588. pointer, the low four bits of op is the number of index bits of
  81589. that table. For a length or distance, the low four bits of op
  81590. is the number of extra bits to get after the code. bits is
  81591. the number of bits in this code or part of the code to drop off
  81592. of the bit buffer. val is the actual byte to output in the case
  81593. of a literal, the base length or distance, or the offset from
  81594. the current table to the next table. Each entry is four bytes. */
  81595. typedef struct {
  81596. unsigned char op; /* operation, extra bits, table bits */
  81597. unsigned char bits; /* bits in this part of the code */
  81598. unsigned short val; /* offset in table or code value */
  81599. } code;
  81600. /* op values as set by inflate_table():
  81601. 00000000 - literal
  81602. 0000tttt - table link, tttt != 0 is the number of table index bits
  81603. 0001eeee - length or distance, eeee is the number of extra bits
  81604. 01100000 - end of block
  81605. 01000000 - invalid code
  81606. */
  81607. /* Maximum size of dynamic tree. The maximum found in a long but non-
  81608. exhaustive search was 1444 code structures (852 for length/literals
  81609. and 592 for distances, the latter actually the result of an
  81610. exhaustive search). The true maximum is not known, but the value
  81611. below is more than safe. */
  81612. #define ENOUGH 2048
  81613. #define MAXD 592
  81614. /* Type of code to build for inftable() */
  81615. typedef enum {
  81616. CODES,
  81617. LENS,
  81618. DISTS
  81619. } codetype;
  81620. extern int inflate_table OF((codetype type, unsigned short FAR *lens,
  81621. unsigned codes, code FAR * FAR *table,
  81622. unsigned FAR *bits, unsigned short FAR *work));
  81623. #endif
  81624. /*** End of inlined file: inftrees.h ***/
  81625. /*** Start of inlined file: inflate.h ***/
  81626. /* WARNING: this file should *not* be used by applications. It is
  81627. part of the implementation of the compression library and is
  81628. subject to change. Applications should only use zlib.h.
  81629. */
  81630. #ifndef _INFLATE_H_
  81631. #define _INFLATE_H_
  81632. /* define NO_GZIP when compiling if you want to disable gzip header and
  81633. trailer decoding by inflate(). NO_GZIP would be used to avoid linking in
  81634. the crc code when it is not needed. For shared libraries, gzip decoding
  81635. should be left enabled. */
  81636. #ifndef NO_GZIP
  81637. # define GUNZIP
  81638. #endif
  81639. /* Possible inflate modes between inflate() calls */
  81640. typedef enum {
  81641. HEAD, /* i: waiting for magic header */
  81642. FLAGS, /* i: waiting for method and flags (gzip) */
  81643. TIME, /* i: waiting for modification time (gzip) */
  81644. OS, /* i: waiting for extra flags and operating system (gzip) */
  81645. EXLEN, /* i: waiting for extra length (gzip) */
  81646. EXTRA, /* i: waiting for extra bytes (gzip) */
  81647. NAME, /* i: waiting for end of file name (gzip) */
  81648. COMMENT, /* i: waiting for end of comment (gzip) */
  81649. HCRC, /* i: waiting for header crc (gzip) */
  81650. DICTID, /* i: waiting for dictionary check value */
  81651. DICT, /* waiting for inflateSetDictionary() call */
  81652. TYPE, /* i: waiting for type bits, including last-flag bit */
  81653. TYPEDO, /* i: same, but skip check to exit inflate on new block */
  81654. STORED, /* i: waiting for stored size (length and complement) */
  81655. COPY, /* i/o: waiting for input or output to copy stored block */
  81656. TABLE, /* i: waiting for dynamic block table lengths */
  81657. LENLENS, /* i: waiting for code length code lengths */
  81658. CODELENS, /* i: waiting for length/lit and distance code lengths */
  81659. LEN, /* i: waiting for length/lit code */
  81660. LENEXT, /* i: waiting for length extra bits */
  81661. DIST, /* i: waiting for distance code */
  81662. DISTEXT, /* i: waiting for distance extra bits */
  81663. MATCH, /* o: waiting for output space to copy string */
  81664. LIT, /* o: waiting for output space to write literal */
  81665. CHECK, /* i: waiting for 32-bit check value */
  81666. LENGTH, /* i: waiting for 32-bit length (gzip) */
  81667. DONE, /* finished check, done -- remain here until reset */
  81668. BAD, /* got a data error -- remain here until reset */
  81669. MEM, /* got an inflate() memory error -- remain here until reset */
  81670. SYNC /* looking for synchronization bytes to restart inflate() */
  81671. } inflate_mode;
  81672. /*
  81673. State transitions between above modes -
  81674. (most modes can go to the BAD or MEM mode -- not shown for clarity)
  81675. Process header:
  81676. HEAD -> (gzip) or (zlib)
  81677. (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME
  81678. NAME -> COMMENT -> HCRC -> TYPE
  81679. (zlib) -> DICTID or TYPE
  81680. DICTID -> DICT -> TYPE
  81681. Read deflate blocks:
  81682. TYPE -> STORED or TABLE or LEN or CHECK
  81683. STORED -> COPY -> TYPE
  81684. TABLE -> LENLENS -> CODELENS -> LEN
  81685. Read deflate codes:
  81686. LEN -> LENEXT or LIT or TYPE
  81687. LENEXT -> DIST -> DISTEXT -> MATCH -> LEN
  81688. LIT -> LEN
  81689. Process trailer:
  81690. CHECK -> LENGTH -> DONE
  81691. */
  81692. /* state maintained between inflate() calls. Approximately 7K bytes. */
  81693. struct inflate_state {
  81694. inflate_mode mode; /* current inflate mode */
  81695. int last; /* true if processing last block */
  81696. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  81697. int havedict; /* true if dictionary provided */
  81698. int flags; /* gzip header method and flags (0 if zlib) */
  81699. unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */
  81700. unsigned long check; /* protected copy of check value */
  81701. unsigned long total; /* protected copy of output count */
  81702. gz_headerp head; /* where to save gzip header information */
  81703. /* sliding window */
  81704. unsigned wbits; /* log base 2 of requested window size */
  81705. unsigned wsize; /* window size or zero if not using window */
  81706. unsigned whave; /* valid bytes in the window */
  81707. unsigned write; /* window write index */
  81708. unsigned char FAR *window; /* allocated sliding window, if needed */
  81709. /* bit accumulator */
  81710. unsigned long hold; /* input bit accumulator */
  81711. unsigned bits; /* number of bits in "in" */
  81712. /* for string and stored block copying */
  81713. unsigned length; /* literal or length of data to copy */
  81714. unsigned offset; /* distance back to copy string from */
  81715. /* for table and code decoding */
  81716. unsigned extra; /* extra bits needed */
  81717. /* fixed and dynamic code tables */
  81718. code const FAR *lencode; /* starting table for length/literal codes */
  81719. code const FAR *distcode; /* starting table for distance codes */
  81720. unsigned lenbits; /* index bits for lencode */
  81721. unsigned distbits; /* index bits for distcode */
  81722. /* dynamic table building */
  81723. unsigned ncode; /* number of code length code lengths */
  81724. unsigned nlen; /* number of length code lengths */
  81725. unsigned ndist; /* number of distance code lengths */
  81726. unsigned have; /* number of code lengths in lens[] */
  81727. code FAR *next; /* next available space in codes[] */
  81728. unsigned short lens[320]; /* temporary storage for code lengths */
  81729. unsigned short work[288]; /* work area for code table building */
  81730. code codes[ENOUGH]; /* space for code tables */
  81731. };
  81732. #endif
  81733. /*** End of inlined file: inflate.h ***/
  81734. /*** Start of inlined file: inffast.h ***/
  81735. /* WARNING: this file should *not* be used by applications. It is
  81736. part of the implementation of the compression library and is
  81737. subject to change. Applications should only use zlib.h.
  81738. */
  81739. void inflate_fast OF((z_streamp strm, unsigned start));
  81740. /*** End of inlined file: inffast.h ***/
  81741. #ifndef ASMINF
  81742. /* Allow machine dependent optimization for post-increment or pre-increment.
  81743. Based on testing to date,
  81744. Pre-increment preferred for:
  81745. - PowerPC G3 (Adler)
  81746. - MIPS R5000 (Randers-Pehrson)
  81747. Post-increment preferred for:
  81748. - none
  81749. No measurable difference:
  81750. - Pentium III (Anderson)
  81751. - M68060 (Nikl)
  81752. */
  81753. #ifdef POSTINC
  81754. # define OFF 0
  81755. # define PUP(a) *(a)++
  81756. #else
  81757. # define OFF 1
  81758. # define PUP(a) *++(a)
  81759. #endif
  81760. /*
  81761. Decode literal, length, and distance codes and write out the resulting
  81762. literal and match bytes until either not enough input or output is
  81763. available, an end-of-block is encountered, or a data error is encountered.
  81764. When large enough input and output buffers are supplied to inflate(), for
  81765. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  81766. inflate execution time is spent in this routine.
  81767. Entry assumptions:
  81768. state->mode == LEN
  81769. strm->avail_in >= 6
  81770. strm->avail_out >= 258
  81771. start >= strm->avail_out
  81772. state->bits < 8
  81773. On return, state->mode is one of:
  81774. LEN -- ran out of enough output space or enough available input
  81775. TYPE -- reached end of block code, inflate() to interpret next block
  81776. BAD -- error in block data
  81777. Notes:
  81778. - The maximum input bits used by a length/distance pair is 15 bits for the
  81779. length code, 5 bits for the length extra, 15 bits for the distance code,
  81780. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  81781. Therefore if strm->avail_in >= 6, then there is enough input to avoid
  81782. checking for available input while decoding.
  81783. - The maximum bytes that a single length/distance pair can output is 258
  81784. bytes, which is the maximum length that can be coded. inflate_fast()
  81785. requires strm->avail_out >= 258 for each loop to avoid checking for
  81786. output space.
  81787. */
  81788. void inflate_fast (z_streamp strm, unsigned start)
  81789. {
  81790. struct inflate_state FAR *state;
  81791. unsigned char FAR *in; /* local strm->next_in */
  81792. unsigned char FAR *last; /* while in < last, enough input available */
  81793. unsigned char FAR *out; /* local strm->next_out */
  81794. unsigned char FAR *beg; /* inflate()'s initial strm->next_out */
  81795. unsigned char FAR *end; /* while out < end, enough space available */
  81796. #ifdef INFLATE_STRICT
  81797. unsigned dmax; /* maximum distance from zlib header */
  81798. #endif
  81799. unsigned wsize; /* window size or zero if not using window */
  81800. unsigned whave; /* valid bytes in the window */
  81801. unsigned write; /* window write index */
  81802. unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */
  81803. unsigned long hold; /* local strm->hold */
  81804. unsigned bits; /* local strm->bits */
  81805. code const FAR *lcode; /* local strm->lencode */
  81806. code const FAR *dcode; /* local strm->distcode */
  81807. unsigned lmask; /* mask for first level of length codes */
  81808. unsigned dmask; /* mask for first level of distance codes */
  81809. code thisx; /* retrieved table entry */
  81810. unsigned op; /* code bits, operation, extra bits, or */
  81811. /* window position, window bytes to copy */
  81812. unsigned len; /* match length, unused bytes */
  81813. unsigned dist; /* match distance */
  81814. unsigned char FAR *from; /* where to copy match from */
  81815. /* copy state to local variables */
  81816. state = (struct inflate_state FAR *)strm->state;
  81817. in = strm->next_in - OFF;
  81818. last = in + (strm->avail_in - 5);
  81819. out = strm->next_out - OFF;
  81820. beg = out - (start - strm->avail_out);
  81821. end = out + (strm->avail_out - 257);
  81822. #ifdef INFLATE_STRICT
  81823. dmax = state->dmax;
  81824. #endif
  81825. wsize = state->wsize;
  81826. whave = state->whave;
  81827. write = state->write;
  81828. window = state->window;
  81829. hold = state->hold;
  81830. bits = state->bits;
  81831. lcode = state->lencode;
  81832. dcode = state->distcode;
  81833. lmask = (1U << state->lenbits) - 1;
  81834. dmask = (1U << state->distbits) - 1;
  81835. /* decode literals and length/distances until end-of-block or not enough
  81836. input data or output space */
  81837. do {
  81838. if (bits < 15) {
  81839. hold += (unsigned long)(PUP(in)) << bits;
  81840. bits += 8;
  81841. hold += (unsigned long)(PUP(in)) << bits;
  81842. bits += 8;
  81843. }
  81844. thisx = lcode[hold & lmask];
  81845. dolen:
  81846. op = (unsigned)(thisx.bits);
  81847. hold >>= op;
  81848. bits -= op;
  81849. op = (unsigned)(thisx.op);
  81850. if (op == 0) { /* literal */
  81851. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  81852. "inflate: literal '%c'\n" :
  81853. "inflate: literal 0x%02x\n", thisx.val));
  81854. PUP(out) = (unsigned char)(thisx.val);
  81855. }
  81856. else if (op & 16) { /* length base */
  81857. len = (unsigned)(thisx.val);
  81858. op &= 15; /* number of extra bits */
  81859. if (op) {
  81860. if (bits < op) {
  81861. hold += (unsigned long)(PUP(in)) << bits;
  81862. bits += 8;
  81863. }
  81864. len += (unsigned)hold & ((1U << op) - 1);
  81865. hold >>= op;
  81866. bits -= op;
  81867. }
  81868. Tracevv((stderr, "inflate: length %u\n", len));
  81869. if (bits < 15) {
  81870. hold += (unsigned long)(PUP(in)) << bits;
  81871. bits += 8;
  81872. hold += (unsigned long)(PUP(in)) << bits;
  81873. bits += 8;
  81874. }
  81875. thisx = dcode[hold & dmask];
  81876. dodist:
  81877. op = (unsigned)(thisx.bits);
  81878. hold >>= op;
  81879. bits -= op;
  81880. op = (unsigned)(thisx.op);
  81881. if (op & 16) { /* distance base */
  81882. dist = (unsigned)(thisx.val);
  81883. op &= 15; /* number of extra bits */
  81884. if (bits < op) {
  81885. hold += (unsigned long)(PUP(in)) << bits;
  81886. bits += 8;
  81887. if (bits < op) {
  81888. hold += (unsigned long)(PUP(in)) << bits;
  81889. bits += 8;
  81890. }
  81891. }
  81892. dist += (unsigned)hold & ((1U << op) - 1);
  81893. #ifdef INFLATE_STRICT
  81894. if (dist > dmax) {
  81895. strm->msg = (char *)"invalid distance too far back";
  81896. state->mode = BAD;
  81897. break;
  81898. }
  81899. #endif
  81900. hold >>= op;
  81901. bits -= op;
  81902. Tracevv((stderr, "inflate: distance %u\n", dist));
  81903. op = (unsigned)(out - beg); /* max distance in output */
  81904. if (dist > op) { /* see if copy from window */
  81905. op = dist - op; /* distance back in window */
  81906. if (op > whave) {
  81907. strm->msg = (char *)"invalid distance too far back";
  81908. state->mode = BAD;
  81909. break;
  81910. }
  81911. from = window - OFF;
  81912. if (write == 0) { /* very common case */
  81913. from += wsize - op;
  81914. if (op < len) { /* some from window */
  81915. len -= op;
  81916. do {
  81917. PUP(out) = PUP(from);
  81918. } while (--op);
  81919. from = out - dist; /* rest from output */
  81920. }
  81921. }
  81922. else if (write < op) { /* wrap around window */
  81923. from += wsize + write - op;
  81924. op -= write;
  81925. if (op < len) { /* some from end of window */
  81926. len -= op;
  81927. do {
  81928. PUP(out) = PUP(from);
  81929. } while (--op);
  81930. from = window - OFF;
  81931. if (write < len) { /* some from start of window */
  81932. op = write;
  81933. len -= op;
  81934. do {
  81935. PUP(out) = PUP(from);
  81936. } while (--op);
  81937. from = out - dist; /* rest from output */
  81938. }
  81939. }
  81940. }
  81941. else { /* contiguous in window */
  81942. from += write - op;
  81943. if (op < len) { /* some from window */
  81944. len -= op;
  81945. do {
  81946. PUP(out) = PUP(from);
  81947. } while (--op);
  81948. from = out - dist; /* rest from output */
  81949. }
  81950. }
  81951. while (len > 2) {
  81952. PUP(out) = PUP(from);
  81953. PUP(out) = PUP(from);
  81954. PUP(out) = PUP(from);
  81955. len -= 3;
  81956. }
  81957. if (len) {
  81958. PUP(out) = PUP(from);
  81959. if (len > 1)
  81960. PUP(out) = PUP(from);
  81961. }
  81962. }
  81963. else {
  81964. from = out - dist; /* copy direct from output */
  81965. do { /* minimum length is three */
  81966. PUP(out) = PUP(from);
  81967. PUP(out) = PUP(from);
  81968. PUP(out) = PUP(from);
  81969. len -= 3;
  81970. } while (len > 2);
  81971. if (len) {
  81972. PUP(out) = PUP(from);
  81973. if (len > 1)
  81974. PUP(out) = PUP(from);
  81975. }
  81976. }
  81977. }
  81978. else if ((op & 64) == 0) { /* 2nd level distance code */
  81979. thisx = dcode[thisx.val + (hold & ((1U << op) - 1))];
  81980. goto dodist;
  81981. }
  81982. else {
  81983. strm->msg = (char *)"invalid distance code";
  81984. state->mode = BAD;
  81985. break;
  81986. }
  81987. }
  81988. else if ((op & 64) == 0) { /* 2nd level length code */
  81989. thisx = lcode[thisx.val + (hold & ((1U << op) - 1))];
  81990. goto dolen;
  81991. }
  81992. else if (op & 32) { /* end-of-block */
  81993. Tracevv((stderr, "inflate: end of block\n"));
  81994. state->mode = TYPE;
  81995. break;
  81996. }
  81997. else {
  81998. strm->msg = (char *)"invalid literal/length code";
  81999. state->mode = BAD;
  82000. break;
  82001. }
  82002. } while (in < last && out < end);
  82003. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  82004. len = bits >> 3;
  82005. in -= len;
  82006. bits -= len << 3;
  82007. hold &= (1U << bits) - 1;
  82008. /* update state and return */
  82009. strm->next_in = in + OFF;
  82010. strm->next_out = out + OFF;
  82011. strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last));
  82012. strm->avail_out = (unsigned)(out < end ?
  82013. 257 + (end - out) : 257 - (out - end));
  82014. state->hold = hold;
  82015. state->bits = bits;
  82016. return;
  82017. }
  82018. /*
  82019. inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe):
  82020. - Using bit fields for code structure
  82021. - Different op definition to avoid & for extra bits (do & for table bits)
  82022. - Three separate decoding do-loops for direct, window, and write == 0
  82023. - Special case for distance > 1 copies to do overlapped load and store copy
  82024. - Explicit branch predictions (based on measured branch probabilities)
  82025. - Deferring match copy and interspersed it with decoding subsequent codes
  82026. - Swapping literal/length else
  82027. - Swapping window/direct else
  82028. - Larger unrolled copy loops (three is about right)
  82029. - Moving len -= 3 statement into middle of loop
  82030. */
  82031. #endif /* !ASMINF */
  82032. /*** End of inlined file: inffast.c ***/
  82033. #undef PULLBYTE
  82034. #undef LOAD
  82035. #undef RESTORE
  82036. #undef INITBITS
  82037. #undef NEEDBITS
  82038. #undef DROPBITS
  82039. #undef BYTEBITS
  82040. /*** Start of inlined file: inflate.c ***/
  82041. /*
  82042. * Change history:
  82043. *
  82044. * 1.2.beta0 24 Nov 2002
  82045. * - First version -- complete rewrite of inflate to simplify code, avoid
  82046. * creation of window when not needed, minimize use of window when it is
  82047. * needed, make inffast.c even faster, implement gzip decoding, and to
  82048. * improve code readability and style over the previous zlib inflate code
  82049. *
  82050. * 1.2.beta1 25 Nov 2002
  82051. * - Use pointers for available input and output checking in inffast.c
  82052. * - Remove input and output counters in inffast.c
  82053. * - Change inffast.c entry and loop from avail_in >= 7 to >= 6
  82054. * - Remove unnecessary second byte pull from length extra in inffast.c
  82055. * - Unroll direct copy to three copies per loop in inffast.c
  82056. *
  82057. * 1.2.beta2 4 Dec 2002
  82058. * - Change external routine names to reduce potential conflicts
  82059. * - Correct filename to inffixed.h for fixed tables in inflate.c
  82060. * - Make hbuf[] unsigned char to match parameter type in inflate.c
  82061. * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset)
  82062. * to avoid negation problem on Alphas (64 bit) in inflate.c
  82063. *
  82064. * 1.2.beta3 22 Dec 2002
  82065. * - Add comments on state->bits assertion in inffast.c
  82066. * - Add comments on op field in inftrees.h
  82067. * - Fix bug in reuse of allocated window after inflateReset()
  82068. * - Remove bit fields--back to byte structure for speed
  82069. * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths
  82070. * - Change post-increments to pre-increments in inflate_fast(), PPC biased?
  82071. * - Add compile time option, POSTINC, to use post-increments instead (Intel?)
  82072. * - Make MATCH copy in inflate() much faster for when inflate_fast() not used
  82073. * - Use local copies of stream next and avail values, as well as local bit
  82074. * buffer and bit count in inflate()--for speed when inflate_fast() not used
  82075. *
  82076. * 1.2.beta4 1 Jan 2003
  82077. * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings
  82078. * - Move a comment on output buffer sizes from inffast.c to inflate.c
  82079. * - Add comments in inffast.c to introduce the inflate_fast() routine
  82080. * - Rearrange window copies in inflate_fast() for speed and simplification
  82081. * - Unroll last copy for window match in inflate_fast()
  82082. * - Use local copies of window variables in inflate_fast() for speed
  82083. * - Pull out common write == 0 case for speed in inflate_fast()
  82084. * - Make op and len in inflate_fast() unsigned for consistency
  82085. * - Add FAR to lcode and dcode declarations in inflate_fast()
  82086. * - Simplified bad distance check in inflate_fast()
  82087. * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new
  82088. * source file infback.c to provide a call-back interface to inflate for
  82089. * programs like gzip and unzip -- uses window as output buffer to avoid
  82090. * window copying
  82091. *
  82092. * 1.2.beta5 1 Jan 2003
  82093. * - Improved inflateBack() interface to allow the caller to provide initial
  82094. * input in strm.
  82095. * - Fixed stored blocks bug in inflateBack()
  82096. *
  82097. * 1.2.beta6 4 Jan 2003
  82098. * - Added comments in inffast.c on effectiveness of POSTINC
  82099. * - Typecasting all around to reduce compiler warnings
  82100. * - Changed loops from while (1) or do {} while (1) to for (;;), again to
  82101. * make compilers happy
  82102. * - Changed type of window in inflateBackInit() to unsigned char *
  82103. *
  82104. * 1.2.beta7 27 Jan 2003
  82105. * - Changed many types to unsigned or unsigned short to avoid warnings
  82106. * - Added inflateCopy() function
  82107. *
  82108. * 1.2.0 9 Mar 2003
  82109. * - Changed inflateBack() interface to provide separate opaque descriptors
  82110. * for the in() and out() functions
  82111. * - Changed inflateBack() argument and in_func typedef to swap the length
  82112. * and buffer address return values for the input function
  82113. * - Check next_in and next_out for Z_NULL on entry to inflate()
  82114. *
  82115. * The history for versions after 1.2.0 are in ChangeLog in zlib distribution.
  82116. */
  82117. /*** Start of inlined file: inffast.h ***/
  82118. /* WARNING: this file should *not* be used by applications. It is
  82119. part of the implementation of the compression library and is
  82120. subject to change. Applications should only use zlib.h.
  82121. */
  82122. void inflate_fast OF((z_streamp strm, unsigned start));
  82123. /*** End of inlined file: inffast.h ***/
  82124. #ifdef MAKEFIXED
  82125. # ifndef BUILDFIXED
  82126. # define BUILDFIXED
  82127. # endif
  82128. #endif
  82129. /* function prototypes */
  82130. local void fixedtables OF((struct inflate_state FAR *state));
  82131. local int updatewindow OF((z_streamp strm, unsigned out));
  82132. #ifdef BUILDFIXED
  82133. void makefixed OF((void));
  82134. #endif
  82135. local unsigned syncsearch OF((unsigned FAR *have, unsigned char FAR *buf,
  82136. unsigned len));
  82137. int ZEXPORT inflateReset (z_streamp strm)
  82138. {
  82139. struct inflate_state FAR *state;
  82140. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  82141. state = (struct inflate_state FAR *)strm->state;
  82142. strm->total_in = strm->total_out = state->total = 0;
  82143. strm->msg = Z_NULL;
  82144. strm->adler = 1; /* to support ill-conceived Java test suite */
  82145. state->mode = HEAD;
  82146. state->last = 0;
  82147. state->havedict = 0;
  82148. state->dmax = 32768U;
  82149. state->head = Z_NULL;
  82150. state->wsize = 0;
  82151. state->whave = 0;
  82152. state->write = 0;
  82153. state->hold = 0;
  82154. state->bits = 0;
  82155. state->lencode = state->distcode = state->next = state->codes;
  82156. Tracev((stderr, "inflate: reset\n"));
  82157. return Z_OK;
  82158. }
  82159. int ZEXPORT inflatePrime (z_streamp strm, int bits, int value)
  82160. {
  82161. struct inflate_state FAR *state;
  82162. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  82163. state = (struct inflate_state FAR *)strm->state;
  82164. if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR;
  82165. value &= (1L << bits) - 1;
  82166. state->hold += value << state->bits;
  82167. state->bits += bits;
  82168. return Z_OK;
  82169. }
  82170. int ZEXPORT inflateInit2_(z_streamp strm, int windowBits, const char *version, int stream_size)
  82171. {
  82172. struct inflate_state FAR *state;
  82173. if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
  82174. stream_size != (int)(sizeof(z_stream)))
  82175. return Z_VERSION_ERROR;
  82176. if (strm == Z_NULL) return Z_STREAM_ERROR;
  82177. strm->msg = Z_NULL; /* in case we return an error */
  82178. if (strm->zalloc == (alloc_func)0) {
  82179. strm->zalloc = zcalloc;
  82180. strm->opaque = (voidpf)0;
  82181. }
  82182. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  82183. state = (struct inflate_state FAR *)
  82184. ZALLOC(strm, 1, sizeof(struct inflate_state));
  82185. if (state == Z_NULL) return Z_MEM_ERROR;
  82186. Tracev((stderr, "inflate: allocated\n"));
  82187. strm->state = (struct internal_state FAR *)state;
  82188. if (windowBits < 0) {
  82189. state->wrap = 0;
  82190. windowBits = -windowBits;
  82191. }
  82192. else {
  82193. state->wrap = (windowBits >> 4) + 1;
  82194. #ifdef GUNZIP
  82195. if (windowBits < 48) windowBits &= 15;
  82196. #endif
  82197. }
  82198. if (windowBits < 8 || windowBits > 15) {
  82199. ZFREE(strm, state);
  82200. strm->state = Z_NULL;
  82201. return Z_STREAM_ERROR;
  82202. }
  82203. state->wbits = (unsigned)windowBits;
  82204. state->window = Z_NULL;
  82205. return inflateReset(strm);
  82206. }
  82207. int ZEXPORT inflateInit_ (z_streamp strm, const char *version, int stream_size)
  82208. {
  82209. return inflateInit2_(strm, DEF_WBITS, version, stream_size);
  82210. }
  82211. /*
  82212. Return state with length and distance decoding tables and index sizes set to
  82213. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  82214. If BUILDFIXED is defined, then instead this routine builds the tables the
  82215. first time it's called, and returns those tables the first time and
  82216. thereafter. This reduces the size of the code by about 2K bytes, in
  82217. exchange for a little execution time. However, BUILDFIXED should not be
  82218. used for threaded applications, since the rewriting of the tables and virgin
  82219. may not be thread-safe.
  82220. */
  82221. local void fixedtables (struct inflate_state FAR *state)
  82222. {
  82223. #ifdef BUILDFIXED
  82224. static int virgin = 1;
  82225. static code *lenfix, *distfix;
  82226. static code fixed[544];
  82227. /* build fixed huffman tables if first call (may not be thread safe) */
  82228. if (virgin) {
  82229. unsigned sym, bits;
  82230. static code *next;
  82231. /* literal/length table */
  82232. sym = 0;
  82233. while (sym < 144) state->lens[sym++] = 8;
  82234. while (sym < 256) state->lens[sym++] = 9;
  82235. while (sym < 280) state->lens[sym++] = 7;
  82236. while (sym < 288) state->lens[sym++] = 8;
  82237. next = fixed;
  82238. lenfix = next;
  82239. bits = 9;
  82240. inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
  82241. /* distance table */
  82242. sym = 0;
  82243. while (sym < 32) state->lens[sym++] = 5;
  82244. distfix = next;
  82245. bits = 5;
  82246. inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
  82247. /* do this just once */
  82248. virgin = 0;
  82249. }
  82250. #else /* !BUILDFIXED */
  82251. /*** Start of inlined file: inffixed.h ***/
  82252. /* WARNING: this file should *not* be used by applications. It
  82253. is part of the implementation of the compression library and
  82254. is subject to change. Applications should only use zlib.h.
  82255. */
  82256. static const code lenfix[512] = {
  82257. {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48},
  82258. {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128},
  82259. {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59},
  82260. {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176},
  82261. {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20},
  82262. {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100},
  82263. {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8},
  82264. {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216},
  82265. {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76},
  82266. {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114},
  82267. {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},
  82268. {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148},
  82269. {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42},
  82270. {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86},
  82271. {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15},
  82272. {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236},
  82273. {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62},
  82274. {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142},
  82275. {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31},
  82276. {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162},
  82277. {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25},
  82278. {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105},
  82279. {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4},
  82280. {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202},
  82281. {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69},
  82282. {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125},
  82283. {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13},
  82284. {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195},
  82285. {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35},
  82286. {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91},
  82287. {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19},
  82288. {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246},
  82289. {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55},
  82290. {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135},
  82291. {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99},
  82292. {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190},
  82293. {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16},
  82294. {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96},
  82295. {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6},
  82296. {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209},
  82297. {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},
  82298. {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116},
  82299. {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4},
  82300. {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153},
  82301. {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44},
  82302. {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82},
  82303. {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11},
  82304. {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229},
  82305. {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58},
  82306. {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138},
  82307. {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51},
  82308. {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173},
  82309. {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30},
  82310. {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110},
  82311. {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0},
  82312. {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195},
  82313. {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65},
  82314. {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121},
  82315. {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},
  82316. {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258},
  82317. {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37},
  82318. {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93},
  82319. {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23},
  82320. {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251},
  82321. {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51},
  82322. {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131},
  82323. {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67},
  82324. {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183},
  82325. {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23},
  82326. {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103},
  82327. {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9},
  82328. {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223},
  82329. {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79},
  82330. {0,9,255}
  82331. };
  82332. static const code distfix[32] = {
  82333. {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025},
  82334. {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193},
  82335. {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385},
  82336. {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577},
  82337. {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073},
  82338. {22,5,193},{64,5,0}
  82339. };
  82340. /*** End of inlined file: inffixed.h ***/
  82341. #endif /* BUILDFIXED */
  82342. state->lencode = lenfix;
  82343. state->lenbits = 9;
  82344. state->distcode = distfix;
  82345. state->distbits = 5;
  82346. }
  82347. #ifdef MAKEFIXED
  82348. #include <stdio.h>
  82349. /*
  82350. Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also
  82351. defines BUILDFIXED, so the tables are built on the fly. makefixed() writes
  82352. those tables to stdout, which would be piped to inffixed.h. A small program
  82353. can simply call makefixed to do this:
  82354. void makefixed(void);
  82355. int main(void)
  82356. {
  82357. makefixed();
  82358. return 0;
  82359. }
  82360. Then that can be linked with zlib built with MAKEFIXED defined and run:
  82361. a.out > inffixed.h
  82362. */
  82363. void makefixed()
  82364. {
  82365. unsigned low, size;
  82366. struct inflate_state state;
  82367. fixedtables(&state);
  82368. puts(" /* inffixed.h -- table for decoding fixed codes");
  82369. puts(" * Generated automatically by makefixed().");
  82370. puts(" */");
  82371. puts("");
  82372. puts(" /* WARNING: this file should *not* be used by applications.");
  82373. puts(" It is part of the implementation of this library and is");
  82374. puts(" subject to change. Applications should only use zlib.h.");
  82375. puts(" */");
  82376. puts("");
  82377. size = 1U << 9;
  82378. printf(" static const code lenfix[%u] = {", size);
  82379. low = 0;
  82380. for (;;) {
  82381. if ((low % 7) == 0) printf("\n ");
  82382. printf("{%u,%u,%d}", state.lencode[low].op, state.lencode[low].bits,
  82383. state.lencode[low].val);
  82384. if (++low == size) break;
  82385. putchar(',');
  82386. }
  82387. puts("\n };");
  82388. size = 1U << 5;
  82389. printf("\n static const code distfix[%u] = {", size);
  82390. low = 0;
  82391. for (;;) {
  82392. if ((low % 6) == 0) printf("\n ");
  82393. printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits,
  82394. state.distcode[low].val);
  82395. if (++low == size) break;
  82396. putchar(',');
  82397. }
  82398. puts("\n };");
  82399. }
  82400. #endif /* MAKEFIXED */
  82401. /*
  82402. Update the window with the last wsize (normally 32K) bytes written before
  82403. returning. If window does not exist yet, create it. This is only called
  82404. when a window is already in use, or when output has been written during this
  82405. inflate call, but the end of the deflate stream has not been reached yet.
  82406. It is also called to create a window for dictionary data when a dictionary
  82407. is loaded.
  82408. Providing output buffers larger than 32K to inflate() should provide a speed
  82409. advantage, since only the last 32K of output is copied to the sliding window
  82410. upon return from inflate(), and since all distances after the first 32K of
  82411. output will fall in the output data, making match copies simpler and faster.
  82412. The advantage may be dependent on the size of the processor's data caches.
  82413. */
  82414. local int updatewindow (z_streamp strm, unsigned out)
  82415. {
  82416. struct inflate_state FAR *state;
  82417. unsigned copy, dist;
  82418. state = (struct inflate_state FAR *)strm->state;
  82419. /* if it hasn't been done already, allocate space for the window */
  82420. if (state->window == Z_NULL) {
  82421. state->window = (unsigned char FAR *)
  82422. ZALLOC(strm, 1U << state->wbits,
  82423. sizeof(unsigned char));
  82424. if (state->window == Z_NULL) return 1;
  82425. }
  82426. /* if window not in use yet, initialize */
  82427. if (state->wsize == 0) {
  82428. state->wsize = 1U << state->wbits;
  82429. state->write = 0;
  82430. state->whave = 0;
  82431. }
  82432. /* copy state->wsize or less output bytes into the circular window */
  82433. copy = out - strm->avail_out;
  82434. if (copy >= state->wsize) {
  82435. zmemcpy(state->window, strm->next_out - state->wsize, state->wsize);
  82436. state->write = 0;
  82437. state->whave = state->wsize;
  82438. }
  82439. else {
  82440. dist = state->wsize - state->write;
  82441. if (dist > copy) dist = copy;
  82442. zmemcpy(state->window + state->write, strm->next_out - copy, dist);
  82443. copy -= dist;
  82444. if (copy) {
  82445. zmemcpy(state->window, strm->next_out - copy, copy);
  82446. state->write = copy;
  82447. state->whave = state->wsize;
  82448. }
  82449. else {
  82450. state->write += dist;
  82451. if (state->write == state->wsize) state->write = 0;
  82452. if (state->whave < state->wsize) state->whave += dist;
  82453. }
  82454. }
  82455. return 0;
  82456. }
  82457. /* Macros for inflate(): */
  82458. /* check function to use adler32() for zlib or crc32() for gzip */
  82459. #ifdef GUNZIP
  82460. # define UPDATE(check, buf, len) \
  82461. (state->flags ? crc32(check, buf, len) : adler32(check, buf, len))
  82462. #else
  82463. # define UPDATE(check, buf, len) adler32(check, buf, len)
  82464. #endif
  82465. /* check macros for header crc */
  82466. #ifdef GUNZIP
  82467. # define CRC2(check, word) \
  82468. do { \
  82469. hbuf[0] = (unsigned char)(word); \
  82470. hbuf[1] = (unsigned char)((word) >> 8); \
  82471. check = crc32(check, hbuf, 2); \
  82472. } while (0)
  82473. # define CRC4(check, word) \
  82474. do { \
  82475. hbuf[0] = (unsigned char)(word); \
  82476. hbuf[1] = (unsigned char)((word) >> 8); \
  82477. hbuf[2] = (unsigned char)((word) >> 16); \
  82478. hbuf[3] = (unsigned char)((word) >> 24); \
  82479. check = crc32(check, hbuf, 4); \
  82480. } while (0)
  82481. #endif
  82482. /* Load registers with state in inflate() for speed */
  82483. #define LOAD() \
  82484. do { \
  82485. put = strm->next_out; \
  82486. left = strm->avail_out; \
  82487. next = strm->next_in; \
  82488. have = strm->avail_in; \
  82489. hold = state->hold; \
  82490. bits = state->bits; \
  82491. } while (0)
  82492. /* Restore state from registers in inflate() */
  82493. #define RESTORE() \
  82494. do { \
  82495. strm->next_out = put; \
  82496. strm->avail_out = left; \
  82497. strm->next_in = next; \
  82498. strm->avail_in = have; \
  82499. state->hold = hold; \
  82500. state->bits = bits; \
  82501. } while (0)
  82502. /* Clear the input bit accumulator */
  82503. #define INITBITS() \
  82504. do { \
  82505. hold = 0; \
  82506. bits = 0; \
  82507. } while (0)
  82508. /* Get a byte of input into the bit accumulator, or return from inflate()
  82509. if there is no input available. */
  82510. #define PULLBYTE() \
  82511. do { \
  82512. if (have == 0) goto inf_leave; \
  82513. have--; \
  82514. hold += (unsigned long)(*next++) << bits; \
  82515. bits += 8; \
  82516. } while (0)
  82517. /* Assure that there are at least n bits in the bit accumulator. If there is
  82518. not enough available input to do that, then return from inflate(). */
  82519. #define NEEDBITS(n) \
  82520. do { \
  82521. while (bits < (unsigned)(n)) \
  82522. PULLBYTE(); \
  82523. } while (0)
  82524. /* Return the low n bits of the bit accumulator (n < 16) */
  82525. #define BITS(n) \
  82526. ((unsigned)hold & ((1U << (n)) - 1))
  82527. /* Remove n bits from the bit accumulator */
  82528. #define DROPBITS(n) \
  82529. do { \
  82530. hold >>= (n); \
  82531. bits -= (unsigned)(n); \
  82532. } while (0)
  82533. /* Remove zero to seven bits as needed to go to a byte boundary */
  82534. #define BYTEBITS() \
  82535. do { \
  82536. hold >>= bits & 7; \
  82537. bits -= bits & 7; \
  82538. } while (0)
  82539. /* Reverse the bytes in a 32-bit value */
  82540. #define REVERSE(q) \
  82541. ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \
  82542. (((q) & 0xff00) << 8) + (((q) & 0xff) << 24))
  82543. /*
  82544. inflate() uses a state machine to process as much input data and generate as
  82545. much output data as possible before returning. The state machine is
  82546. structured roughly as follows:
  82547. for (;;) switch (state) {
  82548. ...
  82549. case STATEn:
  82550. if (not enough input data or output space to make progress)
  82551. return;
  82552. ... make progress ...
  82553. state = STATEm;
  82554. break;
  82555. ...
  82556. }
  82557. so when inflate() is called again, the same case is attempted again, and
  82558. if the appropriate resources are provided, the machine proceeds to the
  82559. next state. The NEEDBITS() macro is usually the way the state evaluates
  82560. whether it can proceed or should return. NEEDBITS() does the return if
  82561. the requested bits are not available. The typical use of the BITS macros
  82562. is:
  82563. NEEDBITS(n);
  82564. ... do something with BITS(n) ...
  82565. DROPBITS(n);
  82566. where NEEDBITS(n) either returns from inflate() if there isn't enough
  82567. input left to load n bits into the accumulator, or it continues. BITS(n)
  82568. gives the low n bits in the accumulator. When done, DROPBITS(n) drops
  82569. the low n bits off the accumulator. INITBITS() clears the accumulator
  82570. and sets the number of available bits to zero. BYTEBITS() discards just
  82571. enough bits to put the accumulator on a byte boundary. After BYTEBITS()
  82572. and a NEEDBITS(8), then BITS(8) would return the next byte in the stream.
  82573. NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return
  82574. if there is no input available. The decoding of variable length codes uses
  82575. PULLBYTE() directly in order to pull just enough bytes to decode the next
  82576. code, and no more.
  82577. Some states loop until they get enough input, making sure that enough
  82578. state information is maintained to continue the loop where it left off
  82579. if NEEDBITS() returns in the loop. For example, want, need, and keep
  82580. would all have to actually be part of the saved state in case NEEDBITS()
  82581. returns:
  82582. case STATEw:
  82583. while (want < need) {
  82584. NEEDBITS(n);
  82585. keep[want++] = BITS(n);
  82586. DROPBITS(n);
  82587. }
  82588. state = STATEx;
  82589. case STATEx:
  82590. As shown above, if the next state is also the next case, then the break
  82591. is omitted.
  82592. A state may also return if there is not enough output space available to
  82593. complete that state. Those states are copying stored data, writing a
  82594. literal byte, and copying a matching string.
  82595. When returning, a "goto inf_leave" is used to update the total counters,
  82596. update the check value, and determine whether any progress has been made
  82597. during that inflate() call in order to return the proper return code.
  82598. Progress is defined as a change in either strm->avail_in or strm->avail_out.
  82599. When there is a window, goto inf_leave will update the window with the last
  82600. output written. If a goto inf_leave occurs in the middle of decompression
  82601. and there is no window currently, goto inf_leave will create one and copy
  82602. output to the window for the next call of inflate().
  82603. In this implementation, the flush parameter of inflate() only affects the
  82604. return code (per zlib.h). inflate() always writes as much as possible to
  82605. strm->next_out, given the space available and the provided input--the effect
  82606. documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers
  82607. the allocation of and copying into a sliding window until necessary, which
  82608. provides the effect documented in zlib.h for Z_FINISH when the entire input
  82609. stream available. So the only thing the flush parameter actually does is:
  82610. when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it
  82611. will return Z_BUF_ERROR if it has not reached the end of the stream.
  82612. */
  82613. int ZEXPORT inflate (z_streamp strm, int flush)
  82614. {
  82615. struct inflate_state FAR *state;
  82616. unsigned char FAR *next; /* next input */
  82617. unsigned char FAR *put; /* next output */
  82618. unsigned have, left; /* available input and output */
  82619. unsigned long hold; /* bit buffer */
  82620. unsigned bits; /* bits in bit buffer */
  82621. unsigned in, out; /* save starting available input and output */
  82622. unsigned copy; /* number of stored or match bytes to copy */
  82623. unsigned char FAR *from; /* where to copy match bytes from */
  82624. code thisx; /* current decoding table entry */
  82625. code last; /* parent table entry */
  82626. unsigned len; /* length to copy for repeats, bits to drop */
  82627. int ret; /* return code */
  82628. #ifdef GUNZIP
  82629. unsigned char hbuf[4]; /* buffer for gzip header crc calculation */
  82630. #endif
  82631. static const unsigned short order[19] = /* permutation of code lengths */
  82632. {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
  82633. if (strm == Z_NULL || strm->state == Z_NULL || strm->next_out == Z_NULL ||
  82634. (strm->next_in == Z_NULL && strm->avail_in != 0))
  82635. return Z_STREAM_ERROR;
  82636. state = (struct inflate_state FAR *)strm->state;
  82637. if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */
  82638. LOAD();
  82639. in = have;
  82640. out = left;
  82641. ret = Z_OK;
  82642. for (;;)
  82643. switch (state->mode) {
  82644. case HEAD:
  82645. if (state->wrap == 0) {
  82646. state->mode = TYPEDO;
  82647. break;
  82648. }
  82649. NEEDBITS(16);
  82650. #ifdef GUNZIP
  82651. if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */
  82652. state->check = crc32(0L, Z_NULL, 0);
  82653. CRC2(state->check, hold);
  82654. INITBITS();
  82655. state->mode = FLAGS;
  82656. break;
  82657. }
  82658. state->flags = 0; /* expect zlib header */
  82659. if (state->head != Z_NULL)
  82660. state->head->done = -1;
  82661. if (!(state->wrap & 1) || /* check if zlib header allowed */
  82662. #else
  82663. if (
  82664. #endif
  82665. ((BITS(8) << 8) + (hold >> 8)) % 31) {
  82666. strm->msg = (char *)"incorrect header check";
  82667. state->mode = BAD;
  82668. break;
  82669. }
  82670. if (BITS(4) != Z_DEFLATED) {
  82671. strm->msg = (char *)"unknown compression method";
  82672. state->mode = BAD;
  82673. break;
  82674. }
  82675. DROPBITS(4);
  82676. len = BITS(4) + 8;
  82677. if (len > state->wbits) {
  82678. strm->msg = (char *)"invalid window size";
  82679. state->mode = BAD;
  82680. break;
  82681. }
  82682. state->dmax = 1U << len;
  82683. Tracev((stderr, "inflate: zlib header ok\n"));
  82684. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  82685. state->mode = hold & 0x200 ? DICTID : TYPE;
  82686. INITBITS();
  82687. break;
  82688. #ifdef GUNZIP
  82689. case FLAGS:
  82690. NEEDBITS(16);
  82691. state->flags = (int)(hold);
  82692. if ((state->flags & 0xff) != Z_DEFLATED) {
  82693. strm->msg = (char *)"unknown compression method";
  82694. state->mode = BAD;
  82695. break;
  82696. }
  82697. if (state->flags & 0xe000) {
  82698. strm->msg = (char *)"unknown header flags set";
  82699. state->mode = BAD;
  82700. break;
  82701. }
  82702. if (state->head != Z_NULL)
  82703. state->head->text = (int)((hold >> 8) & 1);
  82704. if (state->flags & 0x0200) CRC2(state->check, hold);
  82705. INITBITS();
  82706. state->mode = TIME;
  82707. case TIME:
  82708. NEEDBITS(32);
  82709. if (state->head != Z_NULL)
  82710. state->head->time = hold;
  82711. if (state->flags & 0x0200) CRC4(state->check, hold);
  82712. INITBITS();
  82713. state->mode = OS;
  82714. case OS:
  82715. NEEDBITS(16);
  82716. if (state->head != Z_NULL) {
  82717. state->head->xflags = (int)(hold & 0xff);
  82718. state->head->os = (int)(hold >> 8);
  82719. }
  82720. if (state->flags & 0x0200) CRC2(state->check, hold);
  82721. INITBITS();
  82722. state->mode = EXLEN;
  82723. case EXLEN:
  82724. if (state->flags & 0x0400) {
  82725. NEEDBITS(16);
  82726. state->length = (unsigned)(hold);
  82727. if (state->head != Z_NULL)
  82728. state->head->extra_len = (unsigned)hold;
  82729. if (state->flags & 0x0200) CRC2(state->check, hold);
  82730. INITBITS();
  82731. }
  82732. else if (state->head != Z_NULL)
  82733. state->head->extra = Z_NULL;
  82734. state->mode = EXTRA;
  82735. case EXTRA:
  82736. if (state->flags & 0x0400) {
  82737. copy = state->length;
  82738. if (copy > have) copy = have;
  82739. if (copy) {
  82740. if (state->head != Z_NULL &&
  82741. state->head->extra != Z_NULL) {
  82742. len = state->head->extra_len - state->length;
  82743. zmemcpy(state->head->extra + len, next,
  82744. len + copy > state->head->extra_max ?
  82745. state->head->extra_max - len : copy);
  82746. }
  82747. if (state->flags & 0x0200)
  82748. state->check = crc32(state->check, next, copy);
  82749. have -= copy;
  82750. next += copy;
  82751. state->length -= copy;
  82752. }
  82753. if (state->length) goto inf_leave;
  82754. }
  82755. state->length = 0;
  82756. state->mode = NAME;
  82757. case NAME:
  82758. if (state->flags & 0x0800) {
  82759. if (have == 0) goto inf_leave;
  82760. copy = 0;
  82761. do {
  82762. len = (unsigned)(next[copy++]);
  82763. if (state->head != Z_NULL &&
  82764. state->head->name != Z_NULL &&
  82765. state->length < state->head->name_max)
  82766. state->head->name[state->length++] = len;
  82767. } while (len && copy < have);
  82768. if (state->flags & 0x0200)
  82769. state->check = crc32(state->check, next, copy);
  82770. have -= copy;
  82771. next += copy;
  82772. if (len) goto inf_leave;
  82773. }
  82774. else if (state->head != Z_NULL)
  82775. state->head->name = Z_NULL;
  82776. state->length = 0;
  82777. state->mode = COMMENT;
  82778. case COMMENT:
  82779. if (state->flags & 0x1000) {
  82780. if (have == 0) goto inf_leave;
  82781. copy = 0;
  82782. do {
  82783. len = (unsigned)(next[copy++]);
  82784. if (state->head != Z_NULL &&
  82785. state->head->comment != Z_NULL &&
  82786. state->length < state->head->comm_max)
  82787. state->head->comment[state->length++] = len;
  82788. } while (len && copy < have);
  82789. if (state->flags & 0x0200)
  82790. state->check = crc32(state->check, next, copy);
  82791. have -= copy;
  82792. next += copy;
  82793. if (len) goto inf_leave;
  82794. }
  82795. else if (state->head != Z_NULL)
  82796. state->head->comment = Z_NULL;
  82797. state->mode = HCRC;
  82798. case HCRC:
  82799. if (state->flags & 0x0200) {
  82800. NEEDBITS(16);
  82801. if (hold != (state->check & 0xffff)) {
  82802. strm->msg = (char *)"header crc mismatch";
  82803. state->mode = BAD;
  82804. break;
  82805. }
  82806. INITBITS();
  82807. }
  82808. if (state->head != Z_NULL) {
  82809. state->head->hcrc = (int)((state->flags >> 9) & 1);
  82810. state->head->done = 1;
  82811. }
  82812. strm->adler = state->check = crc32(0L, Z_NULL, 0);
  82813. state->mode = TYPE;
  82814. break;
  82815. #endif
  82816. case DICTID:
  82817. NEEDBITS(32);
  82818. strm->adler = state->check = REVERSE(hold);
  82819. INITBITS();
  82820. state->mode = DICT;
  82821. case DICT:
  82822. if (state->havedict == 0) {
  82823. RESTORE();
  82824. return Z_NEED_DICT;
  82825. }
  82826. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  82827. state->mode = TYPE;
  82828. case TYPE:
  82829. if (flush == Z_BLOCK) goto inf_leave;
  82830. case TYPEDO:
  82831. if (state->last) {
  82832. BYTEBITS();
  82833. state->mode = CHECK;
  82834. break;
  82835. }
  82836. NEEDBITS(3);
  82837. state->last = BITS(1);
  82838. DROPBITS(1);
  82839. switch (BITS(2)) {
  82840. case 0: /* stored block */
  82841. Tracev((stderr, "inflate: stored block%s\n",
  82842. state->last ? " (last)" : ""));
  82843. state->mode = STORED;
  82844. break;
  82845. case 1: /* fixed block */
  82846. fixedtables(state);
  82847. Tracev((stderr, "inflate: fixed codes block%s\n",
  82848. state->last ? " (last)" : ""));
  82849. state->mode = LEN; /* decode codes */
  82850. break;
  82851. case 2: /* dynamic block */
  82852. Tracev((stderr, "inflate: dynamic codes block%s\n",
  82853. state->last ? " (last)" : ""));
  82854. state->mode = TABLE;
  82855. break;
  82856. case 3:
  82857. strm->msg = (char *)"invalid block type";
  82858. state->mode = BAD;
  82859. }
  82860. DROPBITS(2);
  82861. break;
  82862. case STORED:
  82863. BYTEBITS(); /* go to byte boundary */
  82864. NEEDBITS(32);
  82865. if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
  82866. strm->msg = (char *)"invalid stored block lengths";
  82867. state->mode = BAD;
  82868. break;
  82869. }
  82870. state->length = (unsigned)hold & 0xffff;
  82871. Tracev((stderr, "inflate: stored length %u\n",
  82872. state->length));
  82873. INITBITS();
  82874. state->mode = COPY;
  82875. case COPY:
  82876. copy = state->length;
  82877. if (copy) {
  82878. if (copy > have) copy = have;
  82879. if (copy > left) copy = left;
  82880. if (copy == 0) goto inf_leave;
  82881. zmemcpy(put, next, copy);
  82882. have -= copy;
  82883. next += copy;
  82884. left -= copy;
  82885. put += copy;
  82886. state->length -= copy;
  82887. break;
  82888. }
  82889. Tracev((stderr, "inflate: stored end\n"));
  82890. state->mode = TYPE;
  82891. break;
  82892. case TABLE:
  82893. NEEDBITS(14);
  82894. state->nlen = BITS(5) + 257;
  82895. DROPBITS(5);
  82896. state->ndist = BITS(5) + 1;
  82897. DROPBITS(5);
  82898. state->ncode = BITS(4) + 4;
  82899. DROPBITS(4);
  82900. #ifndef PKZIP_BUG_WORKAROUND
  82901. if (state->nlen > 286 || state->ndist > 30) {
  82902. strm->msg = (char *)"too many length or distance symbols";
  82903. state->mode = BAD;
  82904. break;
  82905. }
  82906. #endif
  82907. Tracev((stderr, "inflate: table sizes ok\n"));
  82908. state->have = 0;
  82909. state->mode = LENLENS;
  82910. case LENLENS:
  82911. while (state->have < state->ncode) {
  82912. NEEDBITS(3);
  82913. state->lens[order[state->have++]] = (unsigned short)BITS(3);
  82914. DROPBITS(3);
  82915. }
  82916. while (state->have < 19)
  82917. state->lens[order[state->have++]] = 0;
  82918. state->next = state->codes;
  82919. state->lencode = (code const FAR *)(state->next);
  82920. state->lenbits = 7;
  82921. ret = inflate_table(CODES, state->lens, 19, &(state->next),
  82922. &(state->lenbits), state->work);
  82923. if (ret) {
  82924. strm->msg = (char *)"invalid code lengths set";
  82925. state->mode = BAD;
  82926. break;
  82927. }
  82928. Tracev((stderr, "inflate: code lengths ok\n"));
  82929. state->have = 0;
  82930. state->mode = CODELENS;
  82931. case CODELENS:
  82932. while (state->have < state->nlen + state->ndist) {
  82933. for (;;) {
  82934. thisx = state->lencode[BITS(state->lenbits)];
  82935. if ((unsigned)(thisx.bits) <= bits) break;
  82936. PULLBYTE();
  82937. }
  82938. if (thisx.val < 16) {
  82939. NEEDBITS(thisx.bits);
  82940. DROPBITS(thisx.bits);
  82941. state->lens[state->have++] = thisx.val;
  82942. }
  82943. else {
  82944. if (thisx.val == 16) {
  82945. NEEDBITS(thisx.bits + 2);
  82946. DROPBITS(thisx.bits);
  82947. if (state->have == 0) {
  82948. strm->msg = (char *)"invalid bit length repeat";
  82949. state->mode = BAD;
  82950. break;
  82951. }
  82952. len = state->lens[state->have - 1];
  82953. copy = 3 + BITS(2);
  82954. DROPBITS(2);
  82955. }
  82956. else if (thisx.val == 17) {
  82957. NEEDBITS(thisx.bits + 3);
  82958. DROPBITS(thisx.bits);
  82959. len = 0;
  82960. copy = 3 + BITS(3);
  82961. DROPBITS(3);
  82962. }
  82963. else {
  82964. NEEDBITS(thisx.bits + 7);
  82965. DROPBITS(thisx.bits);
  82966. len = 0;
  82967. copy = 11 + BITS(7);
  82968. DROPBITS(7);
  82969. }
  82970. if (state->have + copy > state->nlen + state->ndist) {
  82971. strm->msg = (char *)"invalid bit length repeat";
  82972. state->mode = BAD;
  82973. break;
  82974. }
  82975. while (copy--)
  82976. state->lens[state->have++] = (unsigned short)len;
  82977. }
  82978. }
  82979. /* handle error breaks in while */
  82980. if (state->mode == BAD) break;
  82981. /* build code tables */
  82982. state->next = state->codes;
  82983. state->lencode = (code const FAR *)(state->next);
  82984. state->lenbits = 9;
  82985. ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
  82986. &(state->lenbits), state->work);
  82987. if (ret) {
  82988. strm->msg = (char *)"invalid literal/lengths set";
  82989. state->mode = BAD;
  82990. break;
  82991. }
  82992. state->distcode = (code const FAR *)(state->next);
  82993. state->distbits = 6;
  82994. ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
  82995. &(state->next), &(state->distbits), state->work);
  82996. if (ret) {
  82997. strm->msg = (char *)"invalid distances set";
  82998. state->mode = BAD;
  82999. break;
  83000. }
  83001. Tracev((stderr, "inflate: codes ok\n"));
  83002. state->mode = LEN;
  83003. case LEN:
  83004. if (have >= 6 && left >= 258) {
  83005. RESTORE();
  83006. inflate_fast(strm, out);
  83007. LOAD();
  83008. break;
  83009. }
  83010. for (;;) {
  83011. thisx = state->lencode[BITS(state->lenbits)];
  83012. if ((unsigned)(thisx.bits) <= bits) break;
  83013. PULLBYTE();
  83014. }
  83015. if (thisx.op && (thisx.op & 0xf0) == 0) {
  83016. last = thisx;
  83017. for (;;) {
  83018. thisx = state->lencode[last.val +
  83019. (BITS(last.bits + last.op) >> last.bits)];
  83020. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  83021. PULLBYTE();
  83022. }
  83023. DROPBITS(last.bits);
  83024. }
  83025. DROPBITS(thisx.bits);
  83026. state->length = (unsigned)thisx.val;
  83027. if ((int)(thisx.op) == 0) {
  83028. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  83029. "inflate: literal '%c'\n" :
  83030. "inflate: literal 0x%02x\n", thisx.val));
  83031. state->mode = LIT;
  83032. break;
  83033. }
  83034. if (thisx.op & 32) {
  83035. Tracevv((stderr, "inflate: end of block\n"));
  83036. state->mode = TYPE;
  83037. break;
  83038. }
  83039. if (thisx.op & 64) {
  83040. strm->msg = (char *)"invalid literal/length code";
  83041. state->mode = BAD;
  83042. break;
  83043. }
  83044. state->extra = (unsigned)(thisx.op) & 15;
  83045. state->mode = LENEXT;
  83046. case LENEXT:
  83047. if (state->extra) {
  83048. NEEDBITS(state->extra);
  83049. state->length += BITS(state->extra);
  83050. DROPBITS(state->extra);
  83051. }
  83052. Tracevv((stderr, "inflate: length %u\n", state->length));
  83053. state->mode = DIST;
  83054. case DIST:
  83055. for (;;) {
  83056. thisx = state->distcode[BITS(state->distbits)];
  83057. if ((unsigned)(thisx.bits) <= bits) break;
  83058. PULLBYTE();
  83059. }
  83060. if ((thisx.op & 0xf0) == 0) {
  83061. last = thisx;
  83062. for (;;) {
  83063. thisx = state->distcode[last.val +
  83064. (BITS(last.bits + last.op) >> last.bits)];
  83065. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  83066. PULLBYTE();
  83067. }
  83068. DROPBITS(last.bits);
  83069. }
  83070. DROPBITS(thisx.bits);
  83071. if (thisx.op & 64) {
  83072. strm->msg = (char *)"invalid distance code";
  83073. state->mode = BAD;
  83074. break;
  83075. }
  83076. state->offset = (unsigned)thisx.val;
  83077. state->extra = (unsigned)(thisx.op) & 15;
  83078. state->mode = DISTEXT;
  83079. case DISTEXT:
  83080. if (state->extra) {
  83081. NEEDBITS(state->extra);
  83082. state->offset += BITS(state->extra);
  83083. DROPBITS(state->extra);
  83084. }
  83085. #ifdef INFLATE_STRICT
  83086. if (state->offset > state->dmax) {
  83087. strm->msg = (char *)"invalid distance too far back";
  83088. state->mode = BAD;
  83089. break;
  83090. }
  83091. #endif
  83092. if (state->offset > state->whave + out - left) {
  83093. strm->msg = (char *)"invalid distance too far back";
  83094. state->mode = BAD;
  83095. break;
  83096. }
  83097. Tracevv((stderr, "inflate: distance %u\n", state->offset));
  83098. state->mode = MATCH;
  83099. case MATCH:
  83100. if (left == 0) goto inf_leave;
  83101. copy = out - left;
  83102. if (state->offset > copy) { /* copy from window */
  83103. copy = state->offset - copy;
  83104. if (copy > state->write) {
  83105. copy -= state->write;
  83106. from = state->window + (state->wsize - copy);
  83107. }
  83108. else
  83109. from = state->window + (state->write - copy);
  83110. if (copy > state->length) copy = state->length;
  83111. }
  83112. else { /* copy from output */
  83113. from = put - state->offset;
  83114. copy = state->length;
  83115. }
  83116. if (copy > left) copy = left;
  83117. left -= copy;
  83118. state->length -= copy;
  83119. do {
  83120. *put++ = *from++;
  83121. } while (--copy);
  83122. if (state->length == 0) state->mode = LEN;
  83123. break;
  83124. case LIT:
  83125. if (left == 0) goto inf_leave;
  83126. *put++ = (unsigned char)(state->length);
  83127. left--;
  83128. state->mode = LEN;
  83129. break;
  83130. case CHECK:
  83131. if (state->wrap) {
  83132. NEEDBITS(32);
  83133. out -= left;
  83134. strm->total_out += out;
  83135. state->total += out;
  83136. if (out)
  83137. strm->adler = state->check =
  83138. UPDATE(state->check, put - out, out);
  83139. out = left;
  83140. if ((
  83141. #ifdef GUNZIP
  83142. state->flags ? hold :
  83143. #endif
  83144. REVERSE(hold)) != state->check) {
  83145. strm->msg = (char *)"incorrect data check";
  83146. state->mode = BAD;
  83147. break;
  83148. }
  83149. INITBITS();
  83150. Tracev((stderr, "inflate: check matches trailer\n"));
  83151. }
  83152. #ifdef GUNZIP
  83153. state->mode = LENGTH;
  83154. case LENGTH:
  83155. if (state->wrap && state->flags) {
  83156. NEEDBITS(32);
  83157. if (hold != (state->total & 0xffffffffUL)) {
  83158. strm->msg = (char *)"incorrect length check";
  83159. state->mode = BAD;
  83160. break;
  83161. }
  83162. INITBITS();
  83163. Tracev((stderr, "inflate: length matches trailer\n"));
  83164. }
  83165. #endif
  83166. state->mode = DONE;
  83167. case DONE:
  83168. ret = Z_STREAM_END;
  83169. goto inf_leave;
  83170. case BAD:
  83171. ret = Z_DATA_ERROR;
  83172. goto inf_leave;
  83173. case MEM:
  83174. return Z_MEM_ERROR;
  83175. case SYNC:
  83176. default:
  83177. return Z_STREAM_ERROR;
  83178. }
  83179. /*
  83180. Return from inflate(), updating the total counts and the check value.
  83181. If there was no progress during the inflate() call, return a buffer
  83182. error. Call updatewindow() to create and/or update the window state.
  83183. Note: a memory error from inflate() is non-recoverable.
  83184. */
  83185. inf_leave:
  83186. RESTORE();
  83187. if (state->wsize || (state->mode < CHECK && out != strm->avail_out))
  83188. if (updatewindow(strm, out)) {
  83189. state->mode = MEM;
  83190. return Z_MEM_ERROR;
  83191. }
  83192. in -= strm->avail_in;
  83193. out -= strm->avail_out;
  83194. strm->total_in += in;
  83195. strm->total_out += out;
  83196. state->total += out;
  83197. if (state->wrap && out)
  83198. strm->adler = state->check =
  83199. UPDATE(state->check, strm->next_out - out, out);
  83200. strm->data_type = state->bits + (state->last ? 64 : 0) +
  83201. (state->mode == TYPE ? 128 : 0);
  83202. if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)
  83203. ret = Z_BUF_ERROR;
  83204. return ret;
  83205. }
  83206. int ZEXPORT inflateEnd (z_streamp strm)
  83207. {
  83208. struct inflate_state FAR *state;
  83209. if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
  83210. return Z_STREAM_ERROR;
  83211. state = (struct inflate_state FAR *)strm->state;
  83212. if (state->window != Z_NULL) ZFREE(strm, state->window);
  83213. ZFREE(strm, strm->state);
  83214. strm->state = Z_NULL;
  83215. Tracev((stderr, "inflate: end\n"));
  83216. return Z_OK;
  83217. }
  83218. int ZEXPORT inflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  83219. {
  83220. struct inflate_state FAR *state;
  83221. unsigned long id_;
  83222. /* check state */
  83223. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83224. state = (struct inflate_state FAR *)strm->state;
  83225. if (state->wrap != 0 && state->mode != DICT)
  83226. return Z_STREAM_ERROR;
  83227. /* check for correct dictionary id */
  83228. if (state->mode == DICT) {
  83229. id_ = adler32(0L, Z_NULL, 0);
  83230. id_ = adler32(id_, dictionary, dictLength);
  83231. if (id_ != state->check)
  83232. return Z_DATA_ERROR;
  83233. }
  83234. /* copy dictionary to window */
  83235. if (updatewindow(strm, strm->avail_out)) {
  83236. state->mode = MEM;
  83237. return Z_MEM_ERROR;
  83238. }
  83239. if (dictLength > state->wsize) {
  83240. zmemcpy(state->window, dictionary + dictLength - state->wsize,
  83241. state->wsize);
  83242. state->whave = state->wsize;
  83243. }
  83244. else {
  83245. zmemcpy(state->window + state->wsize - dictLength, dictionary,
  83246. dictLength);
  83247. state->whave = dictLength;
  83248. }
  83249. state->havedict = 1;
  83250. Tracev((stderr, "inflate: dictionary set\n"));
  83251. return Z_OK;
  83252. }
  83253. int ZEXPORT inflateGetHeader (z_streamp strm, gz_headerp head)
  83254. {
  83255. struct inflate_state FAR *state;
  83256. /* check state */
  83257. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83258. state = (struct inflate_state FAR *)strm->state;
  83259. if ((state->wrap & 2) == 0) return Z_STREAM_ERROR;
  83260. /* save header structure */
  83261. state->head = head;
  83262. head->done = 0;
  83263. return Z_OK;
  83264. }
  83265. /*
  83266. Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found
  83267. or when out of input. When called, *have is the number of pattern bytes
  83268. found in order so far, in 0..3. On return *have is updated to the new
  83269. state. If on return *have equals four, then the pattern was found and the
  83270. return value is how many bytes were read including the last byte of the
  83271. pattern. If *have is less than four, then the pattern has not been found
  83272. yet and the return value is len. In the latter case, syncsearch() can be
  83273. called again with more data and the *have state. *have is initialized to
  83274. zero for the first call.
  83275. */
  83276. local unsigned syncsearch (unsigned FAR *have, unsigned char FAR *buf, unsigned len)
  83277. {
  83278. unsigned got;
  83279. unsigned next;
  83280. got = *have;
  83281. next = 0;
  83282. while (next < len && got < 4) {
  83283. if ((int)(buf[next]) == (got < 2 ? 0 : 0xff))
  83284. got++;
  83285. else if (buf[next])
  83286. got = 0;
  83287. else
  83288. got = 4 - got;
  83289. next++;
  83290. }
  83291. *have = got;
  83292. return next;
  83293. }
  83294. int ZEXPORT inflateSync (z_streamp strm)
  83295. {
  83296. unsigned len; /* number of bytes to look at or looked at */
  83297. unsigned long in, out; /* temporary to save total_in and total_out */
  83298. unsigned char buf[4]; /* to restore bit buffer to byte string */
  83299. struct inflate_state FAR *state;
  83300. /* check parameters */
  83301. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83302. state = (struct inflate_state FAR *)strm->state;
  83303. if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR;
  83304. /* if first time, start search in bit buffer */
  83305. if (state->mode != SYNC) {
  83306. state->mode = SYNC;
  83307. state->hold <<= state->bits & 7;
  83308. state->bits -= state->bits & 7;
  83309. len = 0;
  83310. while (state->bits >= 8) {
  83311. buf[len++] = (unsigned char)(state->hold);
  83312. state->hold >>= 8;
  83313. state->bits -= 8;
  83314. }
  83315. state->have = 0;
  83316. syncsearch(&(state->have), buf, len);
  83317. }
  83318. /* search available input */
  83319. len = syncsearch(&(state->have), strm->next_in, strm->avail_in);
  83320. strm->avail_in -= len;
  83321. strm->next_in += len;
  83322. strm->total_in += len;
  83323. /* return no joy or set up to restart inflate() on a new block */
  83324. if (state->have != 4) return Z_DATA_ERROR;
  83325. in = strm->total_in; out = strm->total_out;
  83326. inflateReset(strm);
  83327. strm->total_in = in; strm->total_out = out;
  83328. state->mode = TYPE;
  83329. return Z_OK;
  83330. }
  83331. /*
  83332. Returns true if inflate is currently at the end of a block generated by
  83333. Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
  83334. implementation to provide an additional safety check. PPP uses
  83335. Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored
  83336. block. When decompressing, PPP checks that at the end of input packet,
  83337. inflate is waiting for these length bytes.
  83338. */
  83339. int ZEXPORT inflateSyncPoint (z_streamp strm)
  83340. {
  83341. struct inflate_state FAR *state;
  83342. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83343. state = (struct inflate_state FAR *)strm->state;
  83344. return state->mode == STORED && state->bits == 0;
  83345. }
  83346. int ZEXPORT inflateCopy(z_streamp dest, z_streamp source)
  83347. {
  83348. struct inflate_state FAR *state;
  83349. struct inflate_state FAR *copy;
  83350. unsigned char FAR *window;
  83351. unsigned wsize;
  83352. /* check input */
  83353. if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL ||
  83354. source->zalloc == (alloc_func)0 || source->zfree == (free_func)0)
  83355. return Z_STREAM_ERROR;
  83356. state = (struct inflate_state FAR *)source->state;
  83357. /* allocate space */
  83358. copy = (struct inflate_state FAR *)
  83359. ZALLOC(source, 1, sizeof(struct inflate_state));
  83360. if (copy == Z_NULL) return Z_MEM_ERROR;
  83361. window = Z_NULL;
  83362. if (state->window != Z_NULL) {
  83363. window = (unsigned char FAR *)
  83364. ZALLOC(source, 1U << state->wbits, sizeof(unsigned char));
  83365. if (window == Z_NULL) {
  83366. ZFREE(source, copy);
  83367. return Z_MEM_ERROR;
  83368. }
  83369. }
  83370. /* copy state */
  83371. zmemcpy(dest, source, sizeof(z_stream));
  83372. zmemcpy(copy, state, sizeof(struct inflate_state));
  83373. if (state->lencode >= state->codes &&
  83374. state->lencode <= state->codes + ENOUGH - 1) {
  83375. copy->lencode = copy->codes + (state->lencode - state->codes);
  83376. copy->distcode = copy->codes + (state->distcode - state->codes);
  83377. }
  83378. copy->next = copy->codes + (state->next - state->codes);
  83379. if (window != Z_NULL) {
  83380. wsize = 1U << state->wbits;
  83381. zmemcpy(window, state->window, wsize);
  83382. }
  83383. copy->window = window;
  83384. dest->state = (struct internal_state FAR *)copy;
  83385. return Z_OK;
  83386. }
  83387. /*** End of inlined file: inflate.c ***/
  83388. /*** Start of inlined file: inftrees.c ***/
  83389. #define MAXBITS 15
  83390. const char inflate_copyright[] =
  83391. " inflate 1.2.3 Copyright 1995-2005 Mark Adler ";
  83392. /*
  83393. If you use the zlib library in a product, an acknowledgment is welcome
  83394. in the documentation of your product. If for some reason you cannot
  83395. include such an acknowledgment, I would appreciate that you keep this
  83396. copyright string in the executable of your product.
  83397. */
  83398. /*
  83399. Build a set of tables to decode the provided canonical Huffman code.
  83400. The code lengths are lens[0..codes-1]. The result starts at *table,
  83401. whose indices are 0..2^bits-1. work is a writable array of at least
  83402. lens shorts, which is used as a work area. type is the type of code
  83403. to be generated, CODES, LENS, or DISTS. On return, zero is success,
  83404. -1 is an invalid code, and +1 means that ENOUGH isn't enough. table
  83405. on return points to the next available entry's address. bits is the
  83406. requested root table index bits, and on return it is the actual root
  83407. table index bits. It will differ if the request is greater than the
  83408. longest code or if it is less than the shortest code.
  83409. */
  83410. int inflate_table (codetype type,
  83411. unsigned short FAR *lens,
  83412. unsigned codes,
  83413. code FAR * FAR *table,
  83414. unsigned FAR *bits,
  83415. unsigned short FAR *work)
  83416. {
  83417. unsigned len; /* a code's length in bits */
  83418. unsigned sym; /* index of code symbols */
  83419. unsigned min, max; /* minimum and maximum code lengths */
  83420. unsigned root; /* number of index bits for root table */
  83421. unsigned curr; /* number of index bits for current table */
  83422. unsigned drop; /* code bits to drop for sub-table */
  83423. int left; /* number of prefix codes available */
  83424. unsigned used; /* code entries in table used */
  83425. unsigned huff; /* Huffman code */
  83426. unsigned incr; /* for incrementing code, index */
  83427. unsigned fill; /* index for replicating entries */
  83428. unsigned low; /* low bits for current root entry */
  83429. unsigned mask; /* mask for low root bits */
  83430. code thisx; /* table entry for duplication */
  83431. code FAR *next; /* next available space in table */
  83432. const unsigned short FAR *base; /* base value table to use */
  83433. const unsigned short FAR *extra; /* extra bits table to use */
  83434. int end; /* use base and extra for symbol > end */
  83435. unsigned short count[MAXBITS+1]; /* number of codes of each length */
  83436. unsigned short offs[MAXBITS+1]; /* offsets in table for each length */
  83437. static const unsigned short lbase[31] = { /* Length codes 257..285 base */
  83438. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  83439. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
  83440. static const unsigned short lext[31] = { /* Length codes 257..285 extra */
  83441. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  83442. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 201, 196};
  83443. static const unsigned short dbase[32] = { /* Distance codes 0..29 base */
  83444. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  83445. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  83446. 8193, 12289, 16385, 24577, 0, 0};
  83447. static const unsigned short dext[32] = { /* Distance codes 0..29 extra */
  83448. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  83449. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  83450. 28, 28, 29, 29, 64, 64};
  83451. /*
  83452. Process a set of code lengths to create a canonical Huffman code. The
  83453. code lengths are lens[0..codes-1]. Each length corresponds to the
  83454. symbols 0..codes-1. The Huffman code is generated by first sorting the
  83455. symbols by length from short to long, and retaining the symbol order
  83456. for codes with equal lengths. Then the code starts with all zero bits
  83457. for the first code of the shortest length, and the codes are integer
  83458. increments for the same length, and zeros are appended as the length
  83459. increases. For the deflate format, these bits are stored backwards
  83460. from their more natural integer increment ordering, and so when the
  83461. decoding tables are built in the large loop below, the integer codes
  83462. are incremented backwards.
  83463. This routine assumes, but does not check, that all of the entries in
  83464. lens[] are in the range 0..MAXBITS. The caller must assure this.
  83465. 1..MAXBITS is interpreted as that code length. zero means that that
  83466. symbol does not occur in this code.
  83467. The codes are sorted by computing a count of codes for each length,
  83468. creating from that a table of starting indices for each length in the
  83469. sorted table, and then entering the symbols in order in the sorted
  83470. table. The sorted table is work[], with that space being provided by
  83471. the caller.
  83472. The length counts are used for other purposes as well, i.e. finding
  83473. the minimum and maximum length codes, determining if there are any
  83474. codes at all, checking for a valid set of lengths, and looking ahead
  83475. at length counts to determine sub-table sizes when building the
  83476. decoding tables.
  83477. */
  83478. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  83479. for (len = 0; len <= MAXBITS; len++)
  83480. count[len] = 0;
  83481. for (sym = 0; sym < codes; sym++)
  83482. count[lens[sym]]++;
  83483. /* bound code lengths, force root to be within code lengths */
  83484. root = *bits;
  83485. for (max = MAXBITS; max >= 1; max--)
  83486. if (count[max] != 0) break;
  83487. if (root > max) root = max;
  83488. if (max == 0) { /* no symbols to code at all */
  83489. thisx.op = (unsigned char)64; /* invalid code marker */
  83490. thisx.bits = (unsigned char)1;
  83491. thisx.val = (unsigned short)0;
  83492. *(*table)++ = thisx; /* make a table to force an error */
  83493. *(*table)++ = thisx;
  83494. *bits = 1;
  83495. return 0; /* no symbols, but wait for decoding to report error */
  83496. }
  83497. for (min = 1; min <= MAXBITS; min++)
  83498. if (count[min] != 0) break;
  83499. if (root < min) root = min;
  83500. /* check for an over-subscribed or incomplete set of lengths */
  83501. left = 1;
  83502. for (len = 1; len <= MAXBITS; len++) {
  83503. left <<= 1;
  83504. left -= count[len];
  83505. if (left < 0) return -1; /* over-subscribed */
  83506. }
  83507. if (left > 0 && (type == CODES || max != 1))
  83508. return -1; /* incomplete set */
  83509. /* generate offsets into symbol table for each length for sorting */
  83510. offs[1] = 0;
  83511. for (len = 1; len < MAXBITS; len++)
  83512. offs[len + 1] = offs[len] + count[len];
  83513. /* sort symbols by length, by symbol order within each length */
  83514. for (sym = 0; sym < codes; sym++)
  83515. if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym;
  83516. /*
  83517. Create and fill in decoding tables. In this loop, the table being
  83518. filled is at next and has curr index bits. The code being used is huff
  83519. with length len. That code is converted to an index by dropping drop
  83520. bits off of the bottom. For codes where len is less than drop + curr,
  83521. those top drop + curr - len bits are incremented through all values to
  83522. fill the table with replicated entries.
  83523. root is the number of index bits for the root table. When len exceeds
  83524. root, sub-tables are created pointed to by the root entry with an index
  83525. of the low root bits of huff. This is saved in low to check for when a
  83526. new sub-table should be started. drop is zero when the root table is
  83527. being filled, and drop is root when sub-tables are being filled.
  83528. When a new sub-table is needed, it is necessary to look ahead in the
  83529. code lengths to determine what size sub-table is needed. The length
  83530. counts are used for this, and so count[] is decremented as codes are
  83531. entered in the tables.
  83532. used keeps track of how many table entries have been allocated from the
  83533. provided *table space. It is checked when a LENS table is being made
  83534. against the space in *table, ENOUGH, minus the maximum space needed by
  83535. the worst case distance code, MAXD. This should never happen, but the
  83536. sufficiency of ENOUGH has not been proven exhaustively, hence the check.
  83537. This assumes that when type == LENS, bits == 9.
  83538. sym increments through all symbols, and the loop terminates when
  83539. all codes of length max, i.e. all codes, have been processed. This
  83540. routine permits incomplete codes, so another loop after this one fills
  83541. in the rest of the decoding tables with invalid code markers.
  83542. */
  83543. /* set up for code type */
  83544. switch (type) {
  83545. case CODES:
  83546. base = extra = work; /* dummy value--not used */
  83547. end = 19;
  83548. break;
  83549. case LENS:
  83550. base = lbase;
  83551. base -= 257;
  83552. extra = lext;
  83553. extra -= 257;
  83554. end = 256;
  83555. break;
  83556. default: /* DISTS */
  83557. base = dbase;
  83558. extra = dext;
  83559. end = -1;
  83560. }
  83561. /* initialize state for loop */
  83562. huff = 0; /* starting code */
  83563. sym = 0; /* starting code symbol */
  83564. len = min; /* starting code length */
  83565. next = *table; /* current table to fill in */
  83566. curr = root; /* current table index bits */
  83567. drop = 0; /* current bits to drop from code for index */
  83568. low = (unsigned)(-1); /* trigger new sub-table when len > root */
  83569. used = 1U << root; /* use root table entries */
  83570. mask = used - 1; /* mask for comparing low */
  83571. /* check available table space */
  83572. if (type == LENS && used >= ENOUGH - MAXD)
  83573. return 1;
  83574. /* process all codes and make table entries */
  83575. for (;;) {
  83576. /* create table entry */
  83577. thisx.bits = (unsigned char)(len - drop);
  83578. if ((int)(work[sym]) < end) {
  83579. thisx.op = (unsigned char)0;
  83580. thisx.val = work[sym];
  83581. }
  83582. else if ((int)(work[sym]) > end) {
  83583. thisx.op = (unsigned char)(extra[work[sym]]);
  83584. thisx.val = base[work[sym]];
  83585. }
  83586. else {
  83587. thisx.op = (unsigned char)(32 + 64); /* end of block */
  83588. thisx.val = 0;
  83589. }
  83590. /* replicate for those indices with low len bits equal to huff */
  83591. incr = 1U << (len - drop);
  83592. fill = 1U << curr;
  83593. min = fill; /* save offset to next table */
  83594. do {
  83595. fill -= incr;
  83596. next[(huff >> drop) + fill] = thisx;
  83597. } while (fill != 0);
  83598. /* backwards increment the len-bit code huff */
  83599. incr = 1U << (len - 1);
  83600. while (huff & incr)
  83601. incr >>= 1;
  83602. if (incr != 0) {
  83603. huff &= incr - 1;
  83604. huff += incr;
  83605. }
  83606. else
  83607. huff = 0;
  83608. /* go to next symbol, update count, len */
  83609. sym++;
  83610. if (--(count[len]) == 0) {
  83611. if (len == max) break;
  83612. len = lens[work[sym]];
  83613. }
  83614. /* create new sub-table if needed */
  83615. if (len > root && (huff & mask) != low) {
  83616. /* if first time, transition to sub-tables */
  83617. if (drop == 0)
  83618. drop = root;
  83619. /* increment past last table */
  83620. next += min; /* here min is 1 << curr */
  83621. /* determine length of next table */
  83622. curr = len - drop;
  83623. left = (int)(1 << curr);
  83624. while (curr + drop < max) {
  83625. left -= count[curr + drop];
  83626. if (left <= 0) break;
  83627. curr++;
  83628. left <<= 1;
  83629. }
  83630. /* check for enough space */
  83631. used += 1U << curr;
  83632. if (type == LENS && used >= ENOUGH - MAXD)
  83633. return 1;
  83634. /* point entry in root table to sub-table */
  83635. low = huff & mask;
  83636. (*table)[low].op = (unsigned char)curr;
  83637. (*table)[low].bits = (unsigned char)root;
  83638. (*table)[low].val = (unsigned short)(next - *table);
  83639. }
  83640. }
  83641. /*
  83642. Fill in rest of table for incomplete codes. This loop is similar to the
  83643. loop above in incrementing huff for table indices. It is assumed that
  83644. len is equal to curr + drop, so there is no loop needed to increment
  83645. through high index bits. When the current sub-table is filled, the loop
  83646. drops back to the root table to fill in any remaining entries there.
  83647. */
  83648. thisx.op = (unsigned char)64; /* invalid code marker */
  83649. thisx.bits = (unsigned char)(len - drop);
  83650. thisx.val = (unsigned short)0;
  83651. while (huff != 0) {
  83652. /* when done with sub-table, drop back to root table */
  83653. if (drop != 0 && (huff & mask) != low) {
  83654. drop = 0;
  83655. len = root;
  83656. next = *table;
  83657. thisx.bits = (unsigned char)len;
  83658. }
  83659. /* put invalid code marker in table */
  83660. next[huff >> drop] = thisx;
  83661. /* backwards increment the len-bit code huff */
  83662. incr = 1U << (len - 1);
  83663. while (huff & incr)
  83664. incr >>= 1;
  83665. if (incr != 0) {
  83666. huff &= incr - 1;
  83667. huff += incr;
  83668. }
  83669. else
  83670. huff = 0;
  83671. }
  83672. /* set return parameters */
  83673. *table += used;
  83674. *bits = root;
  83675. return 0;
  83676. }
  83677. /*** End of inlined file: inftrees.c ***/
  83678. /*** Start of inlined file: trees.c ***/
  83679. /*
  83680. * ALGORITHM
  83681. *
  83682. * The "deflation" process uses several Huffman trees. The more
  83683. * common source values are represented by shorter bit sequences.
  83684. *
  83685. * Each code tree is stored in a compressed form which is itself
  83686. * a Huffman encoding of the lengths of all the code strings (in
  83687. * ascending order by source values). The actual code strings are
  83688. * reconstructed from the lengths in the inflate process, as described
  83689. * in the deflate specification.
  83690. *
  83691. * REFERENCES
  83692. *
  83693. * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
  83694. * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
  83695. *
  83696. * Storer, James A.
  83697. * Data Compression: Methods and Theory, pp. 49-50.
  83698. * Computer Science Press, 1988. ISBN 0-7167-8156-5.
  83699. *
  83700. * Sedgewick, R.
  83701. * Algorithms, p290.
  83702. * Addison-Wesley, 1983. ISBN 0-201-06672-6.
  83703. */
  83704. /* @(#) $Id: trees.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  83705. /* #define GEN_TREES_H */
  83706. #ifdef DEBUG
  83707. # include <ctype.h>
  83708. #endif
  83709. /* ===========================================================================
  83710. * Constants
  83711. */
  83712. #define MAX_BL_BITS 7
  83713. /* Bit length codes must not exceed MAX_BL_BITS bits */
  83714. #define END_BLOCK 256
  83715. /* end of block literal code */
  83716. #define REP_3_6 16
  83717. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  83718. #define REPZ_3_10 17
  83719. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  83720. #define REPZ_11_138 18
  83721. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  83722. local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
  83723. = {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};
  83724. local const int extra_dbits[D_CODES] /* extra bits for each distance code */
  83725. = {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};
  83726. local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
  83727. = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
  83728. local const uch bl_order[BL_CODES]
  83729. = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
  83730. /* The lengths of the bit length codes are sent in order of decreasing
  83731. * probability, to avoid transmitting the lengths for unused bit length codes.
  83732. */
  83733. #define Buf_size (8 * 2*sizeof(char))
  83734. /* Number of bits used within bi_buf. (bi_buf might be implemented on
  83735. * more than 16 bits on some systems.)
  83736. */
  83737. /* ===========================================================================
  83738. * Local data. These are initialized only once.
  83739. */
  83740. #define DIST_CODE_LEN 512 /* see definition of array dist_code below */
  83741. #if defined(GEN_TREES_H) || !defined(STDC)
  83742. /* non ANSI compilers may not accept trees.h */
  83743. local ct_data static_ltree[L_CODES+2];
  83744. /* The static literal tree. Since the bit lengths are imposed, there is no
  83745. * need for the L_CODES extra codes used during heap construction. However
  83746. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  83747. * below).
  83748. */
  83749. local ct_data static_dtree[D_CODES];
  83750. /* The static distance tree. (Actually a trivial tree since all codes use
  83751. * 5 bits.)
  83752. */
  83753. uch _dist_code[DIST_CODE_LEN];
  83754. /* Distance codes. The first 256 values correspond to the distances
  83755. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  83756. * the 15 bit distances.
  83757. */
  83758. uch _length_code[MAX_MATCH-MIN_MATCH+1];
  83759. /* length code for each normalized match length (0 == MIN_MATCH) */
  83760. local int base_length[LENGTH_CODES];
  83761. /* First normalized length for each code (0 = MIN_MATCH) */
  83762. local int base_dist[D_CODES];
  83763. /* First normalized distance for each code (0 = distance of 1) */
  83764. #else
  83765. /*** Start of inlined file: trees.h ***/
  83766. local const ct_data static_ltree[L_CODES+2] = {
  83767. {{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}},
  83768. {{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}},
  83769. {{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}},
  83770. {{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}},
  83771. {{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}},
  83772. {{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}},
  83773. {{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}},
  83774. {{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}},
  83775. {{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}},
  83776. {{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}},
  83777. {{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}},
  83778. {{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}},
  83779. {{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}},
  83780. {{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}},
  83781. {{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}},
  83782. {{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}},
  83783. {{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}},
  83784. {{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}},
  83785. {{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}},
  83786. {{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}},
  83787. {{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}},
  83788. {{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}},
  83789. {{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}},
  83790. {{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}},
  83791. {{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}},
  83792. {{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}},
  83793. {{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}},
  83794. {{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}},
  83795. {{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}},
  83796. {{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}},
  83797. {{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}},
  83798. {{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}},
  83799. {{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}},
  83800. {{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}},
  83801. {{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}},
  83802. {{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}},
  83803. {{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}},
  83804. {{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}},
  83805. {{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}},
  83806. {{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}},
  83807. {{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}},
  83808. {{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}},
  83809. {{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}},
  83810. {{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}},
  83811. {{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}},
  83812. {{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}},
  83813. {{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}},
  83814. {{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}},
  83815. {{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}},
  83816. {{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}},
  83817. {{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}},
  83818. {{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}},
  83819. {{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}},
  83820. {{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}},
  83821. {{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}},
  83822. {{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}},
  83823. {{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}},
  83824. {{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}}
  83825. };
  83826. local const ct_data static_dtree[D_CODES] = {
  83827. {{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}},
  83828. {{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}},
  83829. {{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}},
  83830. {{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}},
  83831. {{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}},
  83832. {{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}}
  83833. };
  83834. const uch _dist_code[DIST_CODE_LEN] = {
  83835. 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8,
  83836. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10,
  83837. 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
  83838. 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
  83839. 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
  83840. 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
  83841. 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  83842. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  83843. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  83844. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
  83845. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  83846. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  83847. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17,
  83848. 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
  83849. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  83850. 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  83851. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  83852. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
  83853. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  83854. 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  83855. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  83856. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  83857. 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  83858. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  83859. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  83860. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
  83861. };
  83862. const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {
  83863. 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12,
  83864. 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
  83865. 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
  83866. 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
  83867. 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
  83868. 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
  83869. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  83870. 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  83871. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  83872. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
  83873. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  83874. 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  83875. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
  83876. };
  83877. local const int base_length[LENGTH_CODES] = {
  83878. 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
  83879. 64, 80, 96, 112, 128, 160, 192, 224, 0
  83880. };
  83881. local const int base_dist[D_CODES] = {
  83882. 0, 1, 2, 3, 4, 6, 8, 12, 16, 24,
  83883. 32, 48, 64, 96, 128, 192, 256, 384, 512, 768,
  83884. 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576
  83885. };
  83886. /*** End of inlined file: trees.h ***/
  83887. #endif /* GEN_TREES_H */
  83888. struct static_tree_desc_s {
  83889. const ct_data *static_tree; /* static tree or NULL */
  83890. const intf *extra_bits; /* extra bits for each code or NULL */
  83891. int extra_base; /* base index for extra_bits */
  83892. int elems; /* max number of elements in the tree */
  83893. int max_length; /* max bit length for the codes */
  83894. };
  83895. local static_tree_desc static_l_desc =
  83896. {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
  83897. local static_tree_desc static_d_desc =
  83898. {static_dtree, extra_dbits, 0, D_CODES, MAX_BITS};
  83899. local static_tree_desc static_bl_desc =
  83900. {(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS};
  83901. /* ===========================================================================
  83902. * Local (static) routines in this file.
  83903. */
  83904. local void tr_static_init OF((void));
  83905. local void init_block OF((deflate_state *s));
  83906. local void pqdownheap OF((deflate_state *s, ct_data *tree, int k));
  83907. local void gen_bitlen OF((deflate_state *s, tree_desc *desc));
  83908. local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count));
  83909. local void build_tree OF((deflate_state *s, tree_desc *desc));
  83910. local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code));
  83911. local void send_tree OF((deflate_state *s, ct_data *tree, int max_code));
  83912. local int build_bl_tree OF((deflate_state *s));
  83913. local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
  83914. int blcodes));
  83915. local void compress_block OF((deflate_state *s, ct_data *ltree,
  83916. ct_data *dtree));
  83917. local void set_data_type OF((deflate_state *s));
  83918. local unsigned bi_reverse OF((unsigned value, int length));
  83919. local void bi_windup OF((deflate_state *s));
  83920. local void bi_flush OF((deflate_state *s));
  83921. local void copy_block OF((deflate_state *s, charf *buf, unsigned len,
  83922. int header));
  83923. #ifdef GEN_TREES_H
  83924. local void gen_trees_header OF((void));
  83925. #endif
  83926. #ifndef DEBUG
  83927. # define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
  83928. /* Send a code of the given tree. c and tree must not have side effects */
  83929. #else /* DEBUG */
  83930. # define send_code(s, c, tree) \
  83931. { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
  83932. send_bits(s, tree[c].Code, tree[c].Len); }
  83933. #endif
  83934. /* ===========================================================================
  83935. * Output a short LSB first on the stream.
  83936. * IN assertion: there is enough room in pendingBuf.
  83937. */
  83938. #define put_short(s, w) { \
  83939. put_byte(s, (uch)((w) & 0xff)); \
  83940. put_byte(s, (uch)((ush)(w) >> 8)); \
  83941. }
  83942. /* ===========================================================================
  83943. * Send a value on a given number of bits.
  83944. * IN assertion: length <= 16 and value fits in length bits.
  83945. */
  83946. #ifdef DEBUG
  83947. local void send_bits OF((deflate_state *s, int value, int length));
  83948. local void send_bits (deflate_state *s, int value, int length)
  83949. {
  83950. Tracevv((stderr," l %2d v %4x ", length, value));
  83951. Assert(length > 0 && length <= 15, "invalid length");
  83952. s->bits_sent += (ulg)length;
  83953. /* If not enough room in bi_buf, use (valid) bits from bi_buf and
  83954. * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
  83955. * unused bits in value.
  83956. */
  83957. if (s->bi_valid > (int)Buf_size - length) {
  83958. s->bi_buf |= (value << s->bi_valid);
  83959. put_short(s, s->bi_buf);
  83960. s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
  83961. s->bi_valid += length - Buf_size;
  83962. } else {
  83963. s->bi_buf |= value << s->bi_valid;
  83964. s->bi_valid += length;
  83965. }
  83966. }
  83967. #else /* !DEBUG */
  83968. #define send_bits(s, value, length) \
  83969. { int len = length;\
  83970. if (s->bi_valid > (int)Buf_size - len) {\
  83971. int val = value;\
  83972. s->bi_buf |= (val << s->bi_valid);\
  83973. put_short(s, s->bi_buf);\
  83974. s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
  83975. s->bi_valid += len - Buf_size;\
  83976. } else {\
  83977. s->bi_buf |= (value) << s->bi_valid;\
  83978. s->bi_valid += len;\
  83979. }\
  83980. }
  83981. #endif /* DEBUG */
  83982. /* the arguments must not have side effects */
  83983. /* ===========================================================================
  83984. * Initialize the various 'constant' tables.
  83985. */
  83986. local void tr_static_init()
  83987. {
  83988. #if defined(GEN_TREES_H) || !defined(STDC)
  83989. static int static_init_done = 0;
  83990. int n; /* iterates over tree elements */
  83991. int bits; /* bit counter */
  83992. int length; /* length value */
  83993. int code; /* code value */
  83994. int dist; /* distance index */
  83995. ush bl_count[MAX_BITS+1];
  83996. /* number of codes at each bit length for an optimal tree */
  83997. if (static_init_done) return;
  83998. /* For some embedded targets, global variables are not initialized: */
  83999. static_l_desc.static_tree = static_ltree;
  84000. static_l_desc.extra_bits = extra_lbits;
  84001. static_d_desc.static_tree = static_dtree;
  84002. static_d_desc.extra_bits = extra_dbits;
  84003. static_bl_desc.extra_bits = extra_blbits;
  84004. /* Initialize the mapping length (0..255) -> length code (0..28) */
  84005. length = 0;
  84006. for (code = 0; code < LENGTH_CODES-1; code++) {
  84007. base_length[code] = length;
  84008. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  84009. _length_code[length++] = (uch)code;
  84010. }
  84011. }
  84012. Assert (length == 256, "tr_static_init: length != 256");
  84013. /* Note that the length 255 (match length 258) can be represented
  84014. * in two different ways: code 284 + 5 bits or code 285, so we
  84015. * overwrite length_code[255] to use the best encoding:
  84016. */
  84017. _length_code[length-1] = (uch)code;
  84018. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  84019. dist = 0;
  84020. for (code = 0 ; code < 16; code++) {
  84021. base_dist[code] = dist;
  84022. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  84023. _dist_code[dist++] = (uch)code;
  84024. }
  84025. }
  84026. Assert (dist == 256, "tr_static_init: dist != 256");
  84027. dist >>= 7; /* from now on, all distances are divided by 128 */
  84028. for ( ; code < D_CODES; code++) {
  84029. base_dist[code] = dist << 7;
  84030. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  84031. _dist_code[256 + dist++] = (uch)code;
  84032. }
  84033. }
  84034. Assert (dist == 256, "tr_static_init: 256+dist != 512");
  84035. /* Construct the codes of the static literal tree */
  84036. for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
  84037. n = 0;
  84038. while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
  84039. while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
  84040. while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
  84041. while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
  84042. /* Codes 286 and 287 do not exist, but we must include them in the
  84043. * tree construction to get a canonical Huffman tree (longest code
  84044. * all ones)
  84045. */
  84046. gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
  84047. /* The static distance tree is trivial: */
  84048. for (n = 0; n < D_CODES; n++) {
  84049. static_dtree[n].Len = 5;
  84050. static_dtree[n].Code = bi_reverse((unsigned)n, 5);
  84051. }
  84052. static_init_done = 1;
  84053. # ifdef GEN_TREES_H
  84054. gen_trees_header();
  84055. # endif
  84056. #endif /* defined(GEN_TREES_H) || !defined(STDC) */
  84057. }
  84058. /* ===========================================================================
  84059. * Genererate the file trees.h describing the static trees.
  84060. */
  84061. #ifdef GEN_TREES_H
  84062. # ifndef DEBUG
  84063. # include <stdio.h>
  84064. # endif
  84065. # define SEPARATOR(i, last, width) \
  84066. ((i) == (last)? "\n};\n\n" : \
  84067. ((i) % (width) == (width)-1 ? ",\n" : ", "))
  84068. void gen_trees_header()
  84069. {
  84070. FILE *header = fopen("trees.h", "w");
  84071. int i;
  84072. Assert (header != NULL, "Can't open trees.h");
  84073. fprintf(header,
  84074. "/* header created automatically with -DGEN_TREES_H */\n\n");
  84075. fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
  84076. for (i = 0; i < L_CODES+2; i++) {
  84077. fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
  84078. static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
  84079. }
  84080. fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
  84081. for (i = 0; i < D_CODES; i++) {
  84082. fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
  84083. static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
  84084. }
  84085. fprintf(header, "const uch _dist_code[DIST_CODE_LEN] = {\n");
  84086. for (i = 0; i < DIST_CODE_LEN; i++) {
  84087. fprintf(header, "%2u%s", _dist_code[i],
  84088. SEPARATOR(i, DIST_CODE_LEN-1, 20));
  84089. }
  84090. fprintf(header, "const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
  84091. for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
  84092. fprintf(header, "%2u%s", _length_code[i],
  84093. SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
  84094. }
  84095. fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
  84096. for (i = 0; i < LENGTH_CODES; i++) {
  84097. fprintf(header, "%1u%s", base_length[i],
  84098. SEPARATOR(i, LENGTH_CODES-1, 20));
  84099. }
  84100. fprintf(header, "local const int base_dist[D_CODES] = {\n");
  84101. for (i = 0; i < D_CODES; i++) {
  84102. fprintf(header, "%5u%s", base_dist[i],
  84103. SEPARATOR(i, D_CODES-1, 10));
  84104. }
  84105. fclose(header);
  84106. }
  84107. #endif /* GEN_TREES_H */
  84108. /* ===========================================================================
  84109. * Initialize the tree data structures for a new zlib stream.
  84110. */
  84111. void _tr_init(deflate_state *s)
  84112. {
  84113. tr_static_init();
  84114. s->l_desc.dyn_tree = s->dyn_ltree;
  84115. s->l_desc.stat_desc = &static_l_desc;
  84116. s->d_desc.dyn_tree = s->dyn_dtree;
  84117. s->d_desc.stat_desc = &static_d_desc;
  84118. s->bl_desc.dyn_tree = s->bl_tree;
  84119. s->bl_desc.stat_desc = &static_bl_desc;
  84120. s->bi_buf = 0;
  84121. s->bi_valid = 0;
  84122. s->last_eob_len = 8; /* enough lookahead for inflate */
  84123. #ifdef DEBUG
  84124. s->compressed_len = 0L;
  84125. s->bits_sent = 0L;
  84126. #endif
  84127. /* Initialize the first block of the first file: */
  84128. init_block(s);
  84129. }
  84130. /* ===========================================================================
  84131. * Initialize a new block.
  84132. */
  84133. local void init_block (deflate_state *s)
  84134. {
  84135. int n; /* iterates over tree elements */
  84136. /* Initialize the trees. */
  84137. for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0;
  84138. for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0;
  84139. for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
  84140. s->dyn_ltree[END_BLOCK].Freq = 1;
  84141. s->opt_len = s->static_len = 0L;
  84142. s->last_lit = s->matches = 0;
  84143. }
  84144. #define SMALLEST 1
  84145. /* Index within the heap array of least frequent node in the Huffman tree */
  84146. /* ===========================================================================
  84147. * Remove the smallest element from the heap and recreate the heap with
  84148. * one less element. Updates heap and heap_len.
  84149. */
  84150. #define pqremove(s, tree, top) \
  84151. {\
  84152. top = s->heap[SMALLEST]; \
  84153. s->heap[SMALLEST] = s->heap[s->heap_len--]; \
  84154. pqdownheap(s, tree, SMALLEST); \
  84155. }
  84156. /* ===========================================================================
  84157. * Compares to subtrees, using the tree depth as tie breaker when
  84158. * the subtrees have equal frequency. This minimizes the worst case length.
  84159. */
  84160. #define smaller(tree, n, m, depth) \
  84161. (tree[n].Freq < tree[m].Freq || \
  84162. (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
  84163. /* ===========================================================================
  84164. * Restore the heap property by moving down the tree starting at node k,
  84165. * exchanging a node with the smallest of its two sons if necessary, stopping
  84166. * when the heap property is re-established (each father smaller than its
  84167. * two sons).
  84168. */
  84169. local void pqdownheap (deflate_state *s,
  84170. ct_data *tree, /* the tree to restore */
  84171. int k) /* node to move down */
  84172. {
  84173. int v = s->heap[k];
  84174. int j = k << 1; /* left son of k */
  84175. while (j <= s->heap_len) {
  84176. /* Set j to the smallest of the two sons: */
  84177. if (j < s->heap_len &&
  84178. smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
  84179. j++;
  84180. }
  84181. /* Exit if v is smaller than both sons */
  84182. if (smaller(tree, v, s->heap[j], s->depth)) break;
  84183. /* Exchange v with the smallest son */
  84184. s->heap[k] = s->heap[j]; k = j;
  84185. /* And continue down the tree, setting j to the left son of k */
  84186. j <<= 1;
  84187. }
  84188. s->heap[k] = v;
  84189. }
  84190. /* ===========================================================================
  84191. * Compute the optimal bit lengths for a tree and update the total bit length
  84192. * for the current block.
  84193. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  84194. * above are the tree nodes sorted by increasing frequency.
  84195. * OUT assertions: the field len is set to the optimal bit length, the
  84196. * array bl_count contains the frequencies for each bit length.
  84197. * The length opt_len is updated; static_len is also updated if stree is
  84198. * not null.
  84199. */
  84200. local void gen_bitlen (deflate_state *s, tree_desc *desc)
  84201. {
  84202. ct_data *tree = desc->dyn_tree;
  84203. int max_code = desc->max_code;
  84204. const ct_data *stree = desc->stat_desc->static_tree;
  84205. const intf *extra = desc->stat_desc->extra_bits;
  84206. int base = desc->stat_desc->extra_base;
  84207. int max_length = desc->stat_desc->max_length;
  84208. int h; /* heap index */
  84209. int n, m; /* iterate over the tree elements */
  84210. int bits; /* bit length */
  84211. int xbits; /* extra bits */
  84212. ush f; /* frequency */
  84213. int overflow = 0; /* number of elements with bit length too large */
  84214. for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
  84215. /* In a first pass, compute the optimal bit lengths (which may
  84216. * overflow in the case of the bit length tree).
  84217. */
  84218. tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
  84219. for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
  84220. n = s->heap[h];
  84221. bits = tree[tree[n].Dad].Len + 1;
  84222. if (bits > max_length) bits = max_length, overflow++;
  84223. tree[n].Len = (ush)bits;
  84224. /* We overwrite tree[n].Dad which is no longer needed */
  84225. if (n > max_code) continue; /* not a leaf node */
  84226. s->bl_count[bits]++;
  84227. xbits = 0;
  84228. if (n >= base) xbits = extra[n-base];
  84229. f = tree[n].Freq;
  84230. s->opt_len += (ulg)f * (bits + xbits);
  84231. if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);
  84232. }
  84233. if (overflow == 0) return;
  84234. Trace((stderr,"\nbit length overflow\n"));
  84235. /* This happens for example on obj2 and pic of the Calgary corpus */
  84236. /* Find the first bit length which could increase: */
  84237. do {
  84238. bits = max_length-1;
  84239. while (s->bl_count[bits] == 0) bits--;
  84240. s->bl_count[bits]--; /* move one leaf down the tree */
  84241. s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
  84242. s->bl_count[max_length]--;
  84243. /* The brother of the overflow item also moves one step up,
  84244. * but this does not affect bl_count[max_length]
  84245. */
  84246. overflow -= 2;
  84247. } while (overflow > 0);
  84248. /* Now recompute all bit lengths, scanning in increasing frequency.
  84249. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  84250. * lengths instead of fixing only the wrong ones. This idea is taken
  84251. * from 'ar' written by Haruhiko Okumura.)
  84252. */
  84253. for (bits = max_length; bits != 0; bits--) {
  84254. n = s->bl_count[bits];
  84255. while (n != 0) {
  84256. m = s->heap[--h];
  84257. if (m > max_code) continue;
  84258. if ((unsigned) tree[m].Len != (unsigned) bits) {
  84259. Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  84260. s->opt_len += ((long)bits - (long)tree[m].Len)
  84261. *(long)tree[m].Freq;
  84262. tree[m].Len = (ush)bits;
  84263. }
  84264. n--;
  84265. }
  84266. }
  84267. }
  84268. /* ===========================================================================
  84269. * Generate the codes for a given tree and bit counts (which need not be
  84270. * optimal).
  84271. * IN assertion: the array bl_count contains the bit length statistics for
  84272. * the given tree and the field len is set for all tree elements.
  84273. * OUT assertion: the field code is set for all tree elements of non
  84274. * zero code length.
  84275. */
  84276. local void gen_codes (ct_data *tree, /* the tree to decorate */
  84277. int max_code, /* largest code with non zero frequency */
  84278. ushf *bl_count) /* number of codes at each bit length */
  84279. {
  84280. ush next_code[MAX_BITS+1]; /* next code value for each bit length */
  84281. ush code = 0; /* running code value */
  84282. int bits; /* bit index */
  84283. int n; /* code index */
  84284. /* The distribution counts are first used to generate the code values
  84285. * without bit reversal.
  84286. */
  84287. for (bits = 1; bits <= MAX_BITS; bits++) {
  84288. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  84289. }
  84290. /* Check that the bit counts in bl_count are consistent. The last code
  84291. * must be all ones.
  84292. */
  84293. Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  84294. "inconsistent bit counts");
  84295. Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  84296. for (n = 0; n <= max_code; n++) {
  84297. int len = tree[n].Len;
  84298. if (len == 0) continue;
  84299. /* Now reverse the bits */
  84300. tree[n].Code = bi_reverse(next_code[len]++, len);
  84301. Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  84302. n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  84303. }
  84304. }
  84305. /* ===========================================================================
  84306. * Construct one Huffman tree and assigns the code bit strings and lengths.
  84307. * Update the total bit length for the current block.
  84308. * IN assertion: the field freq is set for all tree elements.
  84309. * OUT assertions: the fields len and code are set to the optimal bit length
  84310. * and corresponding code. The length opt_len is updated; static_len is
  84311. * also updated if stree is not null. The field max_code is set.
  84312. */
  84313. local void build_tree (deflate_state *s,
  84314. tree_desc *desc) /* the tree descriptor */
  84315. {
  84316. ct_data *tree = desc->dyn_tree;
  84317. const ct_data *stree = desc->stat_desc->static_tree;
  84318. int elems = desc->stat_desc->elems;
  84319. int n, m; /* iterate over heap elements */
  84320. int max_code = -1; /* largest code with non zero frequency */
  84321. int node; /* new node being created */
  84322. /* Construct the initial heap, with least frequent element in
  84323. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  84324. * heap[0] is not used.
  84325. */
  84326. s->heap_len = 0, s->heap_max = HEAP_SIZE;
  84327. for (n = 0; n < elems; n++) {
  84328. if (tree[n].Freq != 0) {
  84329. s->heap[++(s->heap_len)] = max_code = n;
  84330. s->depth[n] = 0;
  84331. } else {
  84332. tree[n].Len = 0;
  84333. }
  84334. }
  84335. /* The pkzip format requires that at least one distance code exists,
  84336. * and that at least one bit should be sent even if there is only one
  84337. * possible code. So to avoid special checks later on we force at least
  84338. * two codes of non zero frequency.
  84339. */
  84340. while (s->heap_len < 2) {
  84341. node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
  84342. tree[node].Freq = 1;
  84343. s->depth[node] = 0;
  84344. s->opt_len--; if (stree) s->static_len -= stree[node].Len;
  84345. /* node is 0 or 1 so it does not have extra bits */
  84346. }
  84347. desc->max_code = max_code;
  84348. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  84349. * establish sub-heaps of increasing lengths:
  84350. */
  84351. for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
  84352. /* Construct the Huffman tree by repeatedly combining the least two
  84353. * frequent nodes.
  84354. */
  84355. node = elems; /* next internal node of the tree */
  84356. do {
  84357. pqremove(s, tree, n); /* n = node of least frequency */
  84358. m = s->heap[SMALLEST]; /* m = node of next least frequency */
  84359. s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
  84360. s->heap[--(s->heap_max)] = m;
  84361. /* Create a new node father of n and m */
  84362. tree[node].Freq = tree[n].Freq + tree[m].Freq;
  84363. s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
  84364. s->depth[n] : s->depth[m]) + 1);
  84365. tree[n].Dad = tree[m].Dad = (ush)node;
  84366. #ifdef DUMP_BL_TREE
  84367. if (tree == s->bl_tree) {
  84368. fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
  84369. node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
  84370. }
  84371. #endif
  84372. /* and insert the new node in the heap */
  84373. s->heap[SMALLEST] = node++;
  84374. pqdownheap(s, tree, SMALLEST);
  84375. } while (s->heap_len >= 2);
  84376. s->heap[--(s->heap_max)] = s->heap[SMALLEST];
  84377. /* At this point, the fields freq and dad are set. We can now
  84378. * generate the bit lengths.
  84379. */
  84380. gen_bitlen(s, (tree_desc *)desc);
  84381. /* The field len is now set, we can generate the bit codes */
  84382. gen_codes ((ct_data *)tree, max_code, s->bl_count);
  84383. }
  84384. /* ===========================================================================
  84385. * Scan a literal or distance tree to determine the frequencies of the codes
  84386. * in the bit length tree.
  84387. */
  84388. local void scan_tree (deflate_state *s,
  84389. ct_data *tree, /* the tree to be scanned */
  84390. int max_code) /* and its largest code of non zero frequency */
  84391. {
  84392. int n; /* iterates over all tree elements */
  84393. int prevlen = -1; /* last emitted length */
  84394. int curlen; /* length of current code */
  84395. int nextlen = tree[0].Len; /* length of next code */
  84396. int count = 0; /* repeat count of the current code */
  84397. int max_count = 7; /* max repeat count */
  84398. int min_count = 4; /* min repeat count */
  84399. if (nextlen == 0) max_count = 138, min_count = 3;
  84400. tree[max_code+1].Len = (ush)0xffff; /* guard */
  84401. for (n = 0; n <= max_code; n++) {
  84402. curlen = nextlen; nextlen = tree[n+1].Len;
  84403. if (++count < max_count && curlen == nextlen) {
  84404. continue;
  84405. } else if (count < min_count) {
  84406. s->bl_tree[curlen].Freq += count;
  84407. } else if (curlen != 0) {
  84408. if (curlen != prevlen) s->bl_tree[curlen].Freq++;
  84409. s->bl_tree[REP_3_6].Freq++;
  84410. } else if (count <= 10) {
  84411. s->bl_tree[REPZ_3_10].Freq++;
  84412. } else {
  84413. s->bl_tree[REPZ_11_138].Freq++;
  84414. }
  84415. count = 0; prevlen = curlen;
  84416. if (nextlen == 0) {
  84417. max_count = 138, min_count = 3;
  84418. } else if (curlen == nextlen) {
  84419. max_count = 6, min_count = 3;
  84420. } else {
  84421. max_count = 7, min_count = 4;
  84422. }
  84423. }
  84424. }
  84425. /* ===========================================================================
  84426. * Send a literal or distance tree in compressed form, using the codes in
  84427. * bl_tree.
  84428. */
  84429. local void send_tree (deflate_state *s,
  84430. ct_data *tree, /* the tree to be scanned */
  84431. int max_code) /* and its largest code of non zero frequency */
  84432. {
  84433. int n; /* iterates over all tree elements */
  84434. int prevlen = -1; /* last emitted length */
  84435. int curlen; /* length of current code */
  84436. int nextlen = tree[0].Len; /* length of next code */
  84437. int count = 0; /* repeat count of the current code */
  84438. int max_count = 7; /* max repeat count */
  84439. int min_count = 4; /* min repeat count */
  84440. /* tree[max_code+1].Len = -1; */ /* guard already set */
  84441. if (nextlen == 0) max_count = 138, min_count = 3;
  84442. for (n = 0; n <= max_code; n++) {
  84443. curlen = nextlen; nextlen = tree[n+1].Len;
  84444. if (++count < max_count && curlen == nextlen) {
  84445. continue;
  84446. } else if (count < min_count) {
  84447. do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
  84448. } else if (curlen != 0) {
  84449. if (curlen != prevlen) {
  84450. send_code(s, curlen, s->bl_tree); count--;
  84451. }
  84452. Assert(count >= 3 && count <= 6, " 3_6?");
  84453. send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
  84454. } else if (count <= 10) {
  84455. send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
  84456. } else {
  84457. send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
  84458. }
  84459. count = 0; prevlen = curlen;
  84460. if (nextlen == 0) {
  84461. max_count = 138, min_count = 3;
  84462. } else if (curlen == nextlen) {
  84463. max_count = 6, min_count = 3;
  84464. } else {
  84465. max_count = 7, min_count = 4;
  84466. }
  84467. }
  84468. }
  84469. /* ===========================================================================
  84470. * Construct the Huffman tree for the bit lengths and return the index in
  84471. * bl_order of the last bit length code to send.
  84472. */
  84473. local int build_bl_tree (deflate_state *s)
  84474. {
  84475. int max_blindex; /* index of last bit length code of non zero freq */
  84476. /* Determine the bit length frequencies for literal and distance trees */
  84477. scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
  84478. scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
  84479. /* Build the bit length tree: */
  84480. build_tree(s, (tree_desc *)(&(s->bl_desc)));
  84481. /* opt_len now includes the length of the tree representations, except
  84482. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  84483. */
  84484. /* Determine the number of bit length codes to send. The pkzip format
  84485. * requires that at least 4 bit length codes be sent. (appnote.txt says
  84486. * 3 but the actual value used is 4.)
  84487. */
  84488. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  84489. if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
  84490. }
  84491. /* Update opt_len to include the bit length tree and counts */
  84492. s->opt_len += 3*(max_blindex+1) + 5+5+4;
  84493. Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  84494. s->opt_len, s->static_len));
  84495. return max_blindex;
  84496. }
  84497. /* ===========================================================================
  84498. * Send the header for a block using dynamic Huffman trees: the counts, the
  84499. * lengths of the bit length codes, the literal tree and the distance tree.
  84500. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  84501. */
  84502. local void send_all_trees (deflate_state *s,
  84503. int lcodes, int dcodes, int blcodes) /* number of codes for each tree */
  84504. {
  84505. int rank; /* index in bl_order */
  84506. Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  84507. Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  84508. "too many codes");
  84509. Tracev((stderr, "\nbl counts: "));
  84510. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  84511. send_bits(s, dcodes-1, 5);
  84512. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  84513. for (rank = 0; rank < blcodes; rank++) {
  84514. Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  84515. send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
  84516. }
  84517. Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  84518. send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
  84519. Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  84520. send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
  84521. Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  84522. }
  84523. /* ===========================================================================
  84524. * Send a stored block
  84525. */
  84526. void _tr_stored_block (deflate_state *s, charf *buf, ulg stored_len, int eof)
  84527. {
  84528. send_bits(s, (STORED_BLOCK<<1)+eof, 3); /* send block type */
  84529. #ifdef DEBUG
  84530. s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
  84531. s->compressed_len += (stored_len + 4) << 3;
  84532. #endif
  84533. copy_block(s, buf, (unsigned)stored_len, 1); /* with header */
  84534. }
  84535. /* ===========================================================================
  84536. * Send one empty static block to give enough lookahead for inflate.
  84537. * This takes 10 bits, of which 7 may remain in the bit buffer.
  84538. * The current inflate code requires 9 bits of lookahead. If the
  84539. * last two codes for the previous block (real code plus EOB) were coded
  84540. * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
  84541. * the last real code. In this case we send two empty static blocks instead
  84542. * of one. (There are no problems if the previous block is stored or fixed.)
  84543. * To simplify the code, we assume the worst case of last real code encoded
  84544. * on one bit only.
  84545. */
  84546. void _tr_align (deflate_state *s)
  84547. {
  84548. send_bits(s, STATIC_TREES<<1, 3);
  84549. send_code(s, END_BLOCK, static_ltree);
  84550. #ifdef DEBUG
  84551. s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
  84552. #endif
  84553. bi_flush(s);
  84554. /* Of the 10 bits for the empty block, we have already sent
  84555. * (10 - bi_valid) bits. The lookahead for the last real code (before
  84556. * the EOB of the previous block) was thus at least one plus the length
  84557. * of the EOB plus what we have just sent of the empty static block.
  84558. */
  84559. if (1 + s->last_eob_len + 10 - s->bi_valid < 9) {
  84560. send_bits(s, STATIC_TREES<<1, 3);
  84561. send_code(s, END_BLOCK, static_ltree);
  84562. #ifdef DEBUG
  84563. s->compressed_len += 10L;
  84564. #endif
  84565. bi_flush(s);
  84566. }
  84567. s->last_eob_len = 7;
  84568. }
  84569. /* ===========================================================================
  84570. * Determine the best encoding for the current block: dynamic trees, static
  84571. * trees or store, and output the encoded block to the zip file.
  84572. */
  84573. void _tr_flush_block (deflate_state *s,
  84574. charf *buf, /* input block, or NULL if too old */
  84575. ulg stored_len, /* length of input block */
  84576. int eof) /* true if this is the last block for a file */
  84577. {
  84578. ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  84579. int max_blindex = 0; /* index of last bit length code of non zero freq */
  84580. /* Build the Huffman trees unless a stored block is forced */
  84581. if (s->level > 0) {
  84582. /* Check if the file is binary or text */
  84583. if (stored_len > 0 && s->strm->data_type == Z_UNKNOWN)
  84584. set_data_type(s);
  84585. /* Construct the literal and distance trees */
  84586. build_tree(s, (tree_desc *)(&(s->l_desc)));
  84587. Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  84588. s->static_len));
  84589. build_tree(s, (tree_desc *)(&(s->d_desc)));
  84590. Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  84591. s->static_len));
  84592. /* At this point, opt_len and static_len are the total bit lengths of
  84593. * the compressed block data, excluding the tree representations.
  84594. */
  84595. /* Build the bit length tree for the above two trees, and get the index
  84596. * in bl_order of the last bit length code to send.
  84597. */
  84598. max_blindex = build_bl_tree(s);
  84599. /* Determine the best encoding. Compute the block lengths in bytes. */
  84600. opt_lenb = (s->opt_len+3+7)>>3;
  84601. static_lenb = (s->static_len+3+7)>>3;
  84602. Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  84603. opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  84604. s->last_lit));
  84605. if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
  84606. } else {
  84607. Assert(buf != (char*)0, "lost buf");
  84608. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  84609. }
  84610. #ifdef FORCE_STORED
  84611. if (buf != (char*)0) { /* force stored block */
  84612. #else
  84613. if (stored_len+4 <= opt_lenb && buf != (char*)0) {
  84614. /* 4: two words for the lengths */
  84615. #endif
  84616. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  84617. * Otherwise we can't have processed more than WSIZE input bytes since
  84618. * the last block flush, because compression would have been
  84619. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  84620. * transform a block into a stored block.
  84621. */
  84622. _tr_stored_block(s, buf, stored_len, eof);
  84623. #ifdef FORCE_STATIC
  84624. } else if (static_lenb >= 0) { /* force static trees */
  84625. #else
  84626. } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {
  84627. #endif
  84628. send_bits(s, (STATIC_TREES<<1)+eof, 3);
  84629. compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);
  84630. #ifdef DEBUG
  84631. s->compressed_len += 3 + s->static_len;
  84632. #endif
  84633. } else {
  84634. send_bits(s, (DYN_TREES<<1)+eof, 3);
  84635. send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
  84636. max_blindex+1);
  84637. compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);
  84638. #ifdef DEBUG
  84639. s->compressed_len += 3 + s->opt_len;
  84640. #endif
  84641. }
  84642. Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  84643. /* The above check is made mod 2^32, for files larger than 512 MB
  84644. * and uLong implemented on 32 bits.
  84645. */
  84646. init_block(s);
  84647. if (eof) {
  84648. bi_windup(s);
  84649. #ifdef DEBUG
  84650. s->compressed_len += 7; /* align on byte boundary */
  84651. #endif
  84652. }
  84653. Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  84654. s->compressed_len-7*eof));
  84655. }
  84656. /* ===========================================================================
  84657. * Save the match info and tally the frequency counts. Return true if
  84658. * the current block must be flushed.
  84659. */
  84660. int _tr_tally (deflate_state *s,
  84661. unsigned dist, /* distance of matched string */
  84662. unsigned lc) /* match length-MIN_MATCH or unmatched char (if dist==0) */
  84663. {
  84664. s->d_buf[s->last_lit] = (ush)dist;
  84665. s->l_buf[s->last_lit++] = (uch)lc;
  84666. if (dist == 0) {
  84667. /* lc is the unmatched char */
  84668. s->dyn_ltree[lc].Freq++;
  84669. } else {
  84670. s->matches++;
  84671. /* Here, lc is the match length - MIN_MATCH */
  84672. dist--; /* dist = match distance - 1 */
  84673. Assert((ush)dist < (ush)MAX_DIST(s) &&
  84674. (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  84675. (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  84676. s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
  84677. s->dyn_dtree[d_code(dist)].Freq++;
  84678. }
  84679. #ifdef TRUNCATE_BLOCK
  84680. /* Try to guess if it is profitable to stop the current block here */
  84681. if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {
  84682. /* Compute an upper bound for the compressed length */
  84683. ulg out_length = (ulg)s->last_lit*8L;
  84684. ulg in_length = (ulg)((long)s->strstart - s->block_start);
  84685. int dcode;
  84686. for (dcode = 0; dcode < D_CODES; dcode++) {
  84687. out_length += (ulg)s->dyn_dtree[dcode].Freq *
  84688. (5L+extra_dbits[dcode]);
  84689. }
  84690. out_length >>= 3;
  84691. Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  84692. s->last_lit, in_length, out_length,
  84693. 100L - out_length*100L/in_length));
  84694. if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
  84695. }
  84696. #endif
  84697. return (s->last_lit == s->lit_bufsize-1);
  84698. /* We avoid equality with lit_bufsize because of wraparound at 64K
  84699. * on 16 bit machines and because stored blocks are restricted to
  84700. * 64K-1 bytes.
  84701. */
  84702. }
  84703. /* ===========================================================================
  84704. * Send the block data compressed using the given Huffman trees
  84705. */
  84706. local void compress_block (deflate_state *s,
  84707. ct_data *ltree, /* literal tree */
  84708. ct_data *dtree) /* distance tree */
  84709. {
  84710. unsigned dist; /* distance of matched string */
  84711. int lc; /* match length or unmatched char (if dist == 0) */
  84712. unsigned lx = 0; /* running index in l_buf */
  84713. unsigned code; /* the code to send */
  84714. int extra; /* number of extra bits to send */
  84715. if (s->last_lit != 0) do {
  84716. dist = s->d_buf[lx];
  84717. lc = s->l_buf[lx++];
  84718. if (dist == 0) {
  84719. send_code(s, lc, ltree); /* send a literal byte */
  84720. Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  84721. } else {
  84722. /* Here, lc is the match length - MIN_MATCH */
  84723. code = _length_code[lc];
  84724. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  84725. extra = extra_lbits[code];
  84726. if (extra != 0) {
  84727. lc -= base_length[code];
  84728. send_bits(s, lc, extra); /* send the extra length bits */
  84729. }
  84730. dist--; /* dist is now the match distance - 1 */
  84731. code = d_code(dist);
  84732. Assert (code < D_CODES, "bad d_code");
  84733. send_code(s, code, dtree); /* send the distance code */
  84734. extra = extra_dbits[code];
  84735. if (extra != 0) {
  84736. dist -= base_dist[code];
  84737. send_bits(s, dist, extra); /* send the extra distance bits */
  84738. }
  84739. } /* literal or match pair ? */
  84740. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  84741. Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  84742. "pendingBuf overflow");
  84743. } while (lx < s->last_lit);
  84744. send_code(s, END_BLOCK, ltree);
  84745. s->last_eob_len = ltree[END_BLOCK].Len;
  84746. }
  84747. /* ===========================================================================
  84748. * Set the data type to BINARY or TEXT, using a crude approximation:
  84749. * set it to Z_TEXT if all symbols are either printable characters (33 to 255)
  84750. * or white spaces (9 to 13, or 32); or set it to Z_BINARY otherwise.
  84751. * IN assertion: the fields Freq of dyn_ltree are set.
  84752. */
  84753. local void set_data_type (deflate_state *s)
  84754. {
  84755. int n;
  84756. for (n = 0; n < 9; n++)
  84757. if (s->dyn_ltree[n].Freq != 0)
  84758. break;
  84759. if (n == 9)
  84760. for (n = 14; n < 32; n++)
  84761. if (s->dyn_ltree[n].Freq != 0)
  84762. break;
  84763. s->strm->data_type = (n == 32) ? Z_TEXT : Z_BINARY;
  84764. }
  84765. /* ===========================================================================
  84766. * Reverse the first len bits of a code, using straightforward code (a faster
  84767. * method would use a table)
  84768. * IN assertion: 1 <= len <= 15
  84769. */
  84770. local unsigned bi_reverse (unsigned code, int len)
  84771. {
  84772. register unsigned res = 0;
  84773. do {
  84774. res |= code & 1;
  84775. code >>= 1, res <<= 1;
  84776. } while (--len > 0);
  84777. return res >> 1;
  84778. }
  84779. /* ===========================================================================
  84780. * Flush the bit buffer, keeping at most 7 bits in it.
  84781. */
  84782. local void bi_flush (deflate_state *s)
  84783. {
  84784. if (s->bi_valid == 16) {
  84785. put_short(s, s->bi_buf);
  84786. s->bi_buf = 0;
  84787. s->bi_valid = 0;
  84788. } else if (s->bi_valid >= 8) {
  84789. put_byte(s, (Byte)s->bi_buf);
  84790. s->bi_buf >>= 8;
  84791. s->bi_valid -= 8;
  84792. }
  84793. }
  84794. /* ===========================================================================
  84795. * Flush the bit buffer and align the output on a byte boundary
  84796. */
  84797. local void bi_windup (deflate_state *s)
  84798. {
  84799. if (s->bi_valid > 8) {
  84800. put_short(s, s->bi_buf);
  84801. } else if (s->bi_valid > 0) {
  84802. put_byte(s, (Byte)s->bi_buf);
  84803. }
  84804. s->bi_buf = 0;
  84805. s->bi_valid = 0;
  84806. #ifdef DEBUG
  84807. s->bits_sent = (s->bits_sent+7) & ~7;
  84808. #endif
  84809. }
  84810. /* ===========================================================================
  84811. * Copy a stored block, storing first the length and its
  84812. * one's complement if requested.
  84813. */
  84814. local void copy_block(deflate_state *s,
  84815. charf *buf, /* the input data */
  84816. unsigned len, /* its length */
  84817. int header) /* true if block header must be written */
  84818. {
  84819. bi_windup(s); /* align on byte boundary */
  84820. s->last_eob_len = 8; /* enough lookahead for inflate */
  84821. if (header) {
  84822. put_short(s, (ush)len);
  84823. put_short(s, (ush)~len);
  84824. #ifdef DEBUG
  84825. s->bits_sent += 2*16;
  84826. #endif
  84827. }
  84828. #ifdef DEBUG
  84829. s->bits_sent += (ulg)len<<3;
  84830. #endif
  84831. while (len--) {
  84832. put_byte(s, *buf++);
  84833. }
  84834. }
  84835. /*** End of inlined file: trees.c ***/
  84836. /*** Start of inlined file: zutil.c ***/
  84837. /* @(#) $Id: zutil.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  84838. #ifndef NO_DUMMY_DECL
  84839. struct internal_state {int dummy;}; /* for buggy compilers */
  84840. #endif
  84841. const char * const z_errmsg[10] = {
  84842. "need dictionary", /* Z_NEED_DICT 2 */
  84843. "stream end", /* Z_STREAM_END 1 */
  84844. "", /* Z_OK 0 */
  84845. "file error", /* Z_ERRNO (-1) */
  84846. "stream error", /* Z_STREAM_ERROR (-2) */
  84847. "data error", /* Z_DATA_ERROR (-3) */
  84848. "insufficient memory", /* Z_MEM_ERROR (-4) */
  84849. "buffer error", /* Z_BUF_ERROR (-5) */
  84850. "incompatible version",/* Z_VERSION_ERROR (-6) */
  84851. ""};
  84852. /*const char * ZEXPORT zlibVersion()
  84853. {
  84854. return ZLIB_VERSION;
  84855. }
  84856. uLong ZEXPORT zlibCompileFlags()
  84857. {
  84858. uLong flags;
  84859. flags = 0;
  84860. switch (sizeof(uInt)) {
  84861. case 2: break;
  84862. case 4: flags += 1; break;
  84863. case 8: flags += 2; break;
  84864. default: flags += 3;
  84865. }
  84866. switch (sizeof(uLong)) {
  84867. case 2: break;
  84868. case 4: flags += 1 << 2; break;
  84869. case 8: flags += 2 << 2; break;
  84870. default: flags += 3 << 2;
  84871. }
  84872. switch (sizeof(voidpf)) {
  84873. case 2: break;
  84874. case 4: flags += 1 << 4; break;
  84875. case 8: flags += 2 << 4; break;
  84876. default: flags += 3 << 4;
  84877. }
  84878. switch (sizeof(z_off_t)) {
  84879. case 2: break;
  84880. case 4: flags += 1 << 6; break;
  84881. case 8: flags += 2 << 6; break;
  84882. default: flags += 3 << 6;
  84883. }
  84884. #ifdef DEBUG
  84885. flags += 1 << 8;
  84886. #endif
  84887. #if defined(ASMV) || defined(ASMINF)
  84888. flags += 1 << 9;
  84889. #endif
  84890. #ifdef ZLIB_WINAPI
  84891. flags += 1 << 10;
  84892. #endif
  84893. #ifdef BUILDFIXED
  84894. flags += 1 << 12;
  84895. #endif
  84896. #ifdef DYNAMIC_CRC_TABLE
  84897. flags += 1 << 13;
  84898. #endif
  84899. #ifdef NO_GZCOMPRESS
  84900. flags += 1L << 16;
  84901. #endif
  84902. #ifdef NO_GZIP
  84903. flags += 1L << 17;
  84904. #endif
  84905. #ifdef PKZIP_BUG_WORKAROUND
  84906. flags += 1L << 20;
  84907. #endif
  84908. #ifdef FASTEST
  84909. flags += 1L << 21;
  84910. #endif
  84911. #ifdef STDC
  84912. # ifdef NO_vsnprintf
  84913. flags += 1L << 25;
  84914. # ifdef HAS_vsprintf_void
  84915. flags += 1L << 26;
  84916. # endif
  84917. # else
  84918. # ifdef HAS_vsnprintf_void
  84919. flags += 1L << 26;
  84920. # endif
  84921. # endif
  84922. #else
  84923. flags += 1L << 24;
  84924. # ifdef NO_snprintf
  84925. flags += 1L << 25;
  84926. # ifdef HAS_sprintf_void
  84927. flags += 1L << 26;
  84928. # endif
  84929. # else
  84930. # ifdef HAS_snprintf_void
  84931. flags += 1L << 26;
  84932. # endif
  84933. # endif
  84934. #endif
  84935. return flags;
  84936. }*/
  84937. #ifdef DEBUG
  84938. # ifndef verbose
  84939. # define verbose 0
  84940. # endif
  84941. int z_verbose = verbose;
  84942. void z_error (const char *m)
  84943. {
  84944. fprintf(stderr, "%s\n", m);
  84945. exit(1);
  84946. }
  84947. #endif
  84948. /* exported to allow conversion of error code to string for compress() and
  84949. * uncompress()
  84950. */
  84951. const char * ZEXPORT zError(int err)
  84952. {
  84953. return ERR_MSG(err);
  84954. }
  84955. #if defined(_WIN32_WCE)
  84956. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  84957. * errno. We define it as a global variable to simplify porting.
  84958. * Its value is always 0 and should not be used.
  84959. */
  84960. int errno = 0;
  84961. #endif
  84962. #ifndef HAVE_MEMCPY
  84963. void zmemcpy(dest, source, len)
  84964. Bytef* dest;
  84965. const Bytef* source;
  84966. uInt len;
  84967. {
  84968. if (len == 0) return;
  84969. do {
  84970. *dest++ = *source++; /* ??? to be unrolled */
  84971. } while (--len != 0);
  84972. }
  84973. int zmemcmp(s1, s2, len)
  84974. const Bytef* s1;
  84975. const Bytef* s2;
  84976. uInt len;
  84977. {
  84978. uInt j;
  84979. for (j = 0; j < len; j++) {
  84980. if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1;
  84981. }
  84982. return 0;
  84983. }
  84984. void zmemzero(dest, len)
  84985. Bytef* dest;
  84986. uInt len;
  84987. {
  84988. if (len == 0) return;
  84989. do {
  84990. *dest++ = 0; /* ??? to be unrolled */
  84991. } while (--len != 0);
  84992. }
  84993. #endif
  84994. #ifdef SYS16BIT
  84995. #ifdef __TURBOC__
  84996. /* Turbo C in 16-bit mode */
  84997. # define MY_ZCALLOC
  84998. /* Turbo C malloc() does not allow dynamic allocation of 64K bytes
  84999. * and farmalloc(64K) returns a pointer with an offset of 8, so we
  85000. * must fix the pointer. Warning: the pointer must be put back to its
  85001. * original form in order to free it, use zcfree().
  85002. */
  85003. #define MAX_PTR 10
  85004. /* 10*64K = 640K */
  85005. local int next_ptr = 0;
  85006. typedef struct ptr_table_s {
  85007. voidpf org_ptr;
  85008. voidpf new_ptr;
  85009. } ptr_table;
  85010. local ptr_table table[MAX_PTR];
  85011. /* This table is used to remember the original form of pointers
  85012. * to large buffers (64K). Such pointers are normalized with a zero offset.
  85013. * Since MSDOS is not a preemptive multitasking OS, this table is not
  85014. * protected from concurrent access. This hack doesn't work anyway on
  85015. * a protected system like OS/2. Use Microsoft C instead.
  85016. */
  85017. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  85018. {
  85019. voidpf buf = opaque; /* just to make some compilers happy */
  85020. ulg bsize = (ulg)items*size;
  85021. /* If we allocate less than 65520 bytes, we assume that farmalloc
  85022. * will return a usable pointer which doesn't have to be normalized.
  85023. */
  85024. if (bsize < 65520L) {
  85025. buf = farmalloc(bsize);
  85026. if (*(ush*)&buf != 0) return buf;
  85027. } else {
  85028. buf = farmalloc(bsize + 16L);
  85029. }
  85030. if (buf == NULL || next_ptr >= MAX_PTR) return NULL;
  85031. table[next_ptr].org_ptr = buf;
  85032. /* Normalize the pointer to seg:0 */
  85033. *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4;
  85034. *(ush*)&buf = 0;
  85035. table[next_ptr++].new_ptr = buf;
  85036. return buf;
  85037. }
  85038. void zcfree (voidpf opaque, voidpf ptr)
  85039. {
  85040. int n;
  85041. if (*(ush*)&ptr != 0) { /* object < 64K */
  85042. farfree(ptr);
  85043. return;
  85044. }
  85045. /* Find the original pointer */
  85046. for (n = 0; n < next_ptr; n++) {
  85047. if (ptr != table[n].new_ptr) continue;
  85048. farfree(table[n].org_ptr);
  85049. while (++n < next_ptr) {
  85050. table[n-1] = table[n];
  85051. }
  85052. next_ptr--;
  85053. return;
  85054. }
  85055. ptr = opaque; /* just to make some compilers happy */
  85056. Assert(0, "zcfree: ptr not found");
  85057. }
  85058. #endif /* __TURBOC__ */
  85059. #ifdef M_I86
  85060. /* Microsoft C in 16-bit mode */
  85061. # define MY_ZCALLOC
  85062. #if (!defined(_MSC_VER) || (_MSC_VER <= 600))
  85063. # define _halloc halloc
  85064. # define _hfree hfree
  85065. #endif
  85066. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  85067. {
  85068. if (opaque) opaque = 0; /* to make compiler happy */
  85069. return _halloc((long)items, size);
  85070. }
  85071. void zcfree (voidpf opaque, voidpf ptr)
  85072. {
  85073. if (opaque) opaque = 0; /* to make compiler happy */
  85074. _hfree(ptr);
  85075. }
  85076. #endif /* M_I86 */
  85077. #endif /* SYS16BIT */
  85078. #ifndef MY_ZCALLOC /* Any system without a special alloc function */
  85079. #ifndef STDC
  85080. extern voidp malloc OF((uInt size));
  85081. extern voidp calloc OF((uInt items, uInt size));
  85082. extern void free OF((voidpf ptr));
  85083. #endif
  85084. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  85085. {
  85086. if (opaque) items += size - size; /* make compiler happy */
  85087. return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) :
  85088. (voidpf)calloc(items, size);
  85089. }
  85090. void zcfree (voidpf opaque, voidpf ptr)
  85091. {
  85092. free(ptr);
  85093. if (opaque) return; /* make compiler happy */
  85094. }
  85095. #endif /* MY_ZCALLOC */
  85096. /*** End of inlined file: zutil.c ***/
  85097. #undef Byte
  85098. }
  85099. #else
  85100. #include <zlib.h>
  85101. #endif
  85102. }
  85103. #if JUCE_MSVC
  85104. #pragma warning (pop)
  85105. #endif
  85106. BEGIN_JUCE_NAMESPACE
  85107. // internal helper object that holds the zlib structures so they don't have to be
  85108. // included publicly.
  85109. class GZIPDecompressHelper
  85110. {
  85111. public:
  85112. GZIPDecompressHelper (const bool noWrap)
  85113. : finished (true),
  85114. needsDictionary (false),
  85115. error (true),
  85116. streamIsValid (false),
  85117. data (0),
  85118. dataSize (0)
  85119. {
  85120. using namespace zlibNamespace;
  85121. zerostruct (stream);
  85122. streamIsValid = (inflateInit2 (&stream, noWrap ? -MAX_WBITS : MAX_WBITS) == Z_OK);
  85123. finished = error = ! streamIsValid;
  85124. }
  85125. ~GZIPDecompressHelper()
  85126. {
  85127. using namespace zlibNamespace;
  85128. if (streamIsValid)
  85129. inflateEnd (&stream);
  85130. }
  85131. bool needsInput() const throw() { return dataSize <= 0; }
  85132. void setInput (uint8* const data_, const int size) throw()
  85133. {
  85134. data = data_;
  85135. dataSize = size;
  85136. }
  85137. int doNextBlock (uint8* const dest, const int destSize)
  85138. {
  85139. using namespace zlibNamespace;
  85140. if (streamIsValid && data != 0 && ! finished)
  85141. {
  85142. stream.next_in = data;
  85143. stream.next_out = dest;
  85144. stream.avail_in = dataSize;
  85145. stream.avail_out = destSize;
  85146. switch (inflate (&stream, Z_PARTIAL_FLUSH))
  85147. {
  85148. case Z_STREAM_END:
  85149. finished = true;
  85150. // deliberate fall-through
  85151. case Z_OK:
  85152. data += dataSize - stream.avail_in;
  85153. dataSize = stream.avail_in;
  85154. return destSize - stream.avail_out;
  85155. case Z_NEED_DICT:
  85156. needsDictionary = true;
  85157. data += dataSize - stream.avail_in;
  85158. dataSize = stream.avail_in;
  85159. break;
  85160. case Z_DATA_ERROR:
  85161. case Z_MEM_ERROR:
  85162. error = true;
  85163. default:
  85164. break;
  85165. }
  85166. }
  85167. return 0;
  85168. }
  85169. bool finished, needsDictionary, error, streamIsValid;
  85170. private:
  85171. zlibNamespace::z_stream stream;
  85172. uint8* data;
  85173. int dataSize;
  85174. GZIPDecompressHelper (const GZIPDecompressHelper&);
  85175. GZIPDecompressHelper& operator= (const GZIPDecompressHelper&);
  85176. };
  85177. const int gzipDecompBufferSize = 32768;
  85178. GZIPDecompressorInputStream::GZIPDecompressorInputStream (InputStream* const sourceStream_,
  85179. const bool deleteSourceWhenDestroyed,
  85180. const bool noWrap_,
  85181. const int64 uncompressedStreamLength_)
  85182. : sourceStream (sourceStream_),
  85183. streamToDelete (deleteSourceWhenDestroyed ? sourceStream_ : 0),
  85184. uncompressedStreamLength (uncompressedStreamLength_),
  85185. noWrap (noWrap_),
  85186. isEof (false),
  85187. activeBufferSize (0),
  85188. originalSourcePos (sourceStream_->getPosition()),
  85189. currentPos (0),
  85190. buffer (gzipDecompBufferSize),
  85191. helper (new GZIPDecompressHelper (noWrap_))
  85192. {
  85193. }
  85194. GZIPDecompressorInputStream::~GZIPDecompressorInputStream()
  85195. {
  85196. }
  85197. int64 GZIPDecompressorInputStream::getTotalLength()
  85198. {
  85199. return uncompressedStreamLength;
  85200. }
  85201. int GZIPDecompressorInputStream::read (void* destBuffer, int howMany)
  85202. {
  85203. if ((howMany > 0) && ! isEof)
  85204. {
  85205. jassert (destBuffer != 0);
  85206. if (destBuffer != 0)
  85207. {
  85208. int numRead = 0;
  85209. uint8* d = static_cast <uint8*> (destBuffer);
  85210. while (! helper->error)
  85211. {
  85212. const int n = helper->doNextBlock (d, howMany);
  85213. currentPos += n;
  85214. if (n == 0)
  85215. {
  85216. if (helper->finished || helper->needsDictionary)
  85217. {
  85218. isEof = true;
  85219. return numRead;
  85220. }
  85221. if (helper->needsInput())
  85222. {
  85223. activeBufferSize = sourceStream->read (buffer, gzipDecompBufferSize);
  85224. if (activeBufferSize > 0)
  85225. {
  85226. helper->setInput (buffer, activeBufferSize);
  85227. }
  85228. else
  85229. {
  85230. isEof = true;
  85231. return numRead;
  85232. }
  85233. }
  85234. }
  85235. else
  85236. {
  85237. numRead += n;
  85238. howMany -= n;
  85239. d += n;
  85240. if (howMany <= 0)
  85241. return numRead;
  85242. }
  85243. }
  85244. }
  85245. }
  85246. return 0;
  85247. }
  85248. bool GZIPDecompressorInputStream::isExhausted()
  85249. {
  85250. return helper->error || isEof;
  85251. }
  85252. int64 GZIPDecompressorInputStream::getPosition()
  85253. {
  85254. return currentPos;
  85255. }
  85256. bool GZIPDecompressorInputStream::setPosition (int64 newPos)
  85257. {
  85258. if (newPos < currentPos)
  85259. {
  85260. // to go backwards, reset the stream and start again..
  85261. isEof = false;
  85262. activeBufferSize = 0;
  85263. currentPos = 0;
  85264. helper = new GZIPDecompressHelper (noWrap);
  85265. sourceStream->setPosition (originalSourcePos);
  85266. }
  85267. skipNextBytes (newPos - currentPos);
  85268. return true;
  85269. }
  85270. END_JUCE_NAMESPACE
  85271. /*** End of inlined file: juce_GZIPDecompressorInputStream.cpp ***/
  85272. #endif
  85273. #if JUCE_BUILD_NATIVE && ! JUCE_ONLY_BUILD_CORE_LIBRARY
  85274. /*** Start of inlined file: juce_FlacAudioFormat.cpp ***/
  85275. #if JUCE_USE_FLAC
  85276. #if JUCE_WINDOWS
  85277. #include <windows.h>
  85278. #endif
  85279. namespace FlacNamespace
  85280. {
  85281. #if JUCE_INCLUDE_FLAC_CODE
  85282. #if JUCE_MSVC
  85283. #pragma warning (disable : 4505) // (unreferenced static function removal warning)
  85284. #endif
  85285. #define FLAC__NO_DLL 1
  85286. #if ! defined (SIZE_MAX)
  85287. #define SIZE_MAX 0xffffffff
  85288. #endif
  85289. #define __STDC_LIMIT_MACROS 1
  85290. /*** Start of inlined file: all.h ***/
  85291. #ifndef FLAC__ALL_H
  85292. #define FLAC__ALL_H
  85293. /*** Start of inlined file: export.h ***/
  85294. #ifndef FLAC__EXPORT_H
  85295. #define FLAC__EXPORT_H
  85296. /** \file include/FLAC/export.h
  85297. *
  85298. * \brief
  85299. * This module contains #defines and symbols for exporting function
  85300. * calls, and providing version information and compiled-in features.
  85301. *
  85302. * See the \link flac_export export \endlink module.
  85303. */
  85304. /** \defgroup flac_export FLAC/export.h: export symbols
  85305. * \ingroup flac
  85306. *
  85307. * \brief
  85308. * This module contains #defines and symbols for exporting function
  85309. * calls, and providing version information and compiled-in features.
  85310. *
  85311. * If you are compiling with MSVC and will link to the static library
  85312. * (libFLAC.lib) you should define FLAC__NO_DLL in your project to
  85313. * make sure the symbols are exported properly.
  85314. *
  85315. * \{
  85316. */
  85317. #if defined(FLAC__NO_DLL) || !defined(_MSC_VER)
  85318. #define FLAC_API
  85319. #else
  85320. #ifdef FLAC_API_EXPORTS
  85321. #define FLAC_API _declspec(dllexport)
  85322. #else
  85323. #define FLAC_API _declspec(dllimport)
  85324. #endif
  85325. #endif
  85326. /** These #defines will mirror the libtool-based library version number, see
  85327. * http://www.gnu.org/software/libtool/manual.html#Libtool-versioning
  85328. */
  85329. #define FLAC_API_VERSION_CURRENT 10
  85330. #define FLAC_API_VERSION_REVISION 0 /**< see above */
  85331. #define FLAC_API_VERSION_AGE 2 /**< see above */
  85332. #ifdef __cplusplus
  85333. extern "C" {
  85334. #endif
  85335. /** \c 1 if the library has been compiled with support for Ogg FLAC, else \c 0. */
  85336. extern FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC;
  85337. #ifdef __cplusplus
  85338. }
  85339. #endif
  85340. /* \} */
  85341. #endif
  85342. /*** End of inlined file: export.h ***/
  85343. /*** Start of inlined file: assert.h ***/
  85344. #ifndef FLAC__ASSERT_H
  85345. #define FLAC__ASSERT_H
  85346. /* we need this since some compilers (like MSVC) leave assert()s on release code (and we don't want to use their ASSERT) */
  85347. #ifdef DEBUG
  85348. #include <assert.h>
  85349. #define FLAC__ASSERT(x) assert(x)
  85350. #define FLAC__ASSERT_DECLARATION(x) x
  85351. #else
  85352. #define FLAC__ASSERT(x)
  85353. #define FLAC__ASSERT_DECLARATION(x)
  85354. #endif
  85355. #endif
  85356. /*** End of inlined file: assert.h ***/
  85357. /*** Start of inlined file: callback.h ***/
  85358. #ifndef FLAC__CALLBACK_H
  85359. #define FLAC__CALLBACK_H
  85360. /*** Start of inlined file: ordinals.h ***/
  85361. #ifndef FLAC__ORDINALS_H
  85362. #define FLAC__ORDINALS_H
  85363. #if !(defined(_MSC_VER) || defined(__BORLANDC__) || defined(__EMX__))
  85364. #include <inttypes.h>
  85365. #endif
  85366. typedef signed char FLAC__int8;
  85367. typedef unsigned char FLAC__uint8;
  85368. #if defined(_MSC_VER) || defined(__BORLANDC__)
  85369. typedef __int16 FLAC__int16;
  85370. typedef __int32 FLAC__int32;
  85371. typedef __int64 FLAC__int64;
  85372. typedef unsigned __int16 FLAC__uint16;
  85373. typedef unsigned __int32 FLAC__uint32;
  85374. typedef unsigned __int64 FLAC__uint64;
  85375. #elif defined(__EMX__)
  85376. typedef short FLAC__int16;
  85377. typedef long FLAC__int32;
  85378. typedef long long FLAC__int64;
  85379. typedef unsigned short FLAC__uint16;
  85380. typedef unsigned long FLAC__uint32;
  85381. typedef unsigned long long FLAC__uint64;
  85382. #else
  85383. typedef int16_t FLAC__int16;
  85384. typedef int32_t FLAC__int32;
  85385. typedef int64_t FLAC__int64;
  85386. typedef uint16_t FLAC__uint16;
  85387. typedef uint32_t FLAC__uint32;
  85388. typedef uint64_t FLAC__uint64;
  85389. #endif
  85390. typedef int FLAC__bool;
  85391. typedef FLAC__uint8 FLAC__byte;
  85392. #ifdef true
  85393. #undef true
  85394. #endif
  85395. #ifdef false
  85396. #undef false
  85397. #endif
  85398. #ifndef __cplusplus
  85399. #define true 1
  85400. #define false 0
  85401. #endif
  85402. #endif
  85403. /*** End of inlined file: ordinals.h ***/
  85404. #include <stdlib.h> /* for size_t */
  85405. /** \file include/FLAC/callback.h
  85406. *
  85407. * \brief
  85408. * This module defines the structures for describing I/O callbacks
  85409. * to the other FLAC interfaces.
  85410. *
  85411. * See the detailed documentation for callbacks in the
  85412. * \link flac_callbacks callbacks \endlink module.
  85413. */
  85414. /** \defgroup flac_callbacks FLAC/callback.h: I/O callback structures
  85415. * \ingroup flac
  85416. *
  85417. * \brief
  85418. * This module defines the structures for describing I/O callbacks
  85419. * to the other FLAC interfaces.
  85420. *
  85421. * The purpose of the I/O callback functions is to create a common way
  85422. * for the metadata interfaces to handle I/O.
  85423. *
  85424. * Originally the metadata interfaces required filenames as the way of
  85425. * specifying FLAC files to operate on. This is problematic in some
  85426. * environments so there is an additional option to specify a set of
  85427. * callbacks for doing I/O on the FLAC file, instead of the filename.
  85428. *
  85429. * In addition to the callbacks, a FLAC__IOHandle type is defined as an
  85430. * opaque structure for a data source.
  85431. *
  85432. * The callback function prototypes are similar (but not identical) to the
  85433. * stdio functions fread, fwrite, fseek, ftell, feof, and fclose. If you use
  85434. * stdio streams to implement the callbacks, you can pass fread, fwrite, and
  85435. * fclose anywhere a FLAC__IOCallback_Read, FLAC__IOCallback_Write, or
  85436. * FLAC__IOCallback_Close is required, and a FILE* anywhere a FLAC__IOHandle
  85437. * is required. \warning You generally CANNOT directly use fseek or ftell
  85438. * for FLAC__IOCallback_Seek or FLAC__IOCallback_Tell since on most systems
  85439. * these use 32-bit offsets and FLAC requires 64-bit offsets to deal with
  85440. * large files. You will have to find an equivalent function (e.g. ftello),
  85441. * or write a wrapper. The same is true for feof() since this is usually
  85442. * implemented as a macro, not as a function whose address can be taken.
  85443. *
  85444. * \{
  85445. */
  85446. #ifdef __cplusplus
  85447. extern "C" {
  85448. #endif
  85449. /** This is the opaque handle type used by the callbacks. Typically
  85450. * this is a \c FILE* or address of a file descriptor.
  85451. */
  85452. typedef void* FLAC__IOHandle;
  85453. /** Signature for the read callback.
  85454. * The signature and semantics match POSIX fread() implementations
  85455. * and can generally be used interchangeably.
  85456. *
  85457. * \param ptr The address of the read buffer.
  85458. * \param size The size of the records to be read.
  85459. * \param nmemb The number of records to be read.
  85460. * \param handle The handle to the data source.
  85461. * \retval size_t
  85462. * The number of records read.
  85463. */
  85464. typedef size_t (*FLAC__IOCallback_Read) (void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  85465. /** Signature for the write callback.
  85466. * The signature and semantics match POSIX fwrite() implementations
  85467. * and can generally be used interchangeably.
  85468. *
  85469. * \param ptr The address of the write buffer.
  85470. * \param size The size of the records to be written.
  85471. * \param nmemb The number of records to be written.
  85472. * \param handle The handle to the data source.
  85473. * \retval size_t
  85474. * The number of records written.
  85475. */
  85476. typedef size_t (*FLAC__IOCallback_Write) (const void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  85477. /** Signature for the seek callback.
  85478. * The signature and semantics mostly match POSIX fseek() WITH ONE IMPORTANT
  85479. * EXCEPTION: the offset is a 64-bit type whereas fseek() is generally 'long'
  85480. * and 32-bits wide.
  85481. *
  85482. * \param handle The handle to the data source.
  85483. * \param offset The new position, relative to \a whence
  85484. * \param whence \c SEEK_SET, \c SEEK_CUR, or \c SEEK_END
  85485. * \retval int
  85486. * \c 0 on success, \c -1 on error.
  85487. */
  85488. typedef int (*FLAC__IOCallback_Seek) (FLAC__IOHandle handle, FLAC__int64 offset, int whence);
  85489. /** Signature for the tell callback.
  85490. * The signature and semantics mostly match POSIX ftell() WITH ONE IMPORTANT
  85491. * EXCEPTION: the offset is a 64-bit type whereas ftell() is generally 'long'
  85492. * and 32-bits wide.
  85493. *
  85494. * \param handle The handle to the data source.
  85495. * \retval FLAC__int64
  85496. * The current position on success, \c -1 on error.
  85497. */
  85498. typedef FLAC__int64 (*FLAC__IOCallback_Tell) (FLAC__IOHandle handle);
  85499. /** Signature for the EOF callback.
  85500. * The signature and semantics mostly match POSIX feof() but WATCHOUT:
  85501. * on many systems, feof() is a macro, so in this case a wrapper function
  85502. * must be provided instead.
  85503. *
  85504. * \param handle The handle to the data source.
  85505. * \retval int
  85506. * \c 0 if not at end of file, nonzero if at end of file.
  85507. */
  85508. typedef int (*FLAC__IOCallback_Eof) (FLAC__IOHandle handle);
  85509. /** Signature for the close callback.
  85510. * The signature and semantics match POSIX fclose() implementations
  85511. * and can generally be used interchangeably.
  85512. *
  85513. * \param handle The handle to the data source.
  85514. * \retval int
  85515. * \c 0 on success, \c EOF on error.
  85516. */
  85517. typedef int (*FLAC__IOCallback_Close) (FLAC__IOHandle handle);
  85518. /** A structure for holding a set of callbacks.
  85519. * Each FLAC interface that requires a FLAC__IOCallbacks structure will
  85520. * describe which of the callbacks are required. The ones that are not
  85521. * required may be set to NULL.
  85522. *
  85523. * If the seek requirement for an interface is optional, you can signify that
  85524. * a data sorce is not seekable by setting the \a seek field to \c NULL.
  85525. */
  85526. typedef struct {
  85527. FLAC__IOCallback_Read read;
  85528. FLAC__IOCallback_Write write;
  85529. FLAC__IOCallback_Seek seek;
  85530. FLAC__IOCallback_Tell tell;
  85531. FLAC__IOCallback_Eof eof;
  85532. FLAC__IOCallback_Close close;
  85533. } FLAC__IOCallbacks;
  85534. /* \} */
  85535. #ifdef __cplusplus
  85536. }
  85537. #endif
  85538. #endif
  85539. /*** End of inlined file: callback.h ***/
  85540. /*** Start of inlined file: format.h ***/
  85541. #ifndef FLAC__FORMAT_H
  85542. #define FLAC__FORMAT_H
  85543. #ifdef __cplusplus
  85544. extern "C" {
  85545. #endif
  85546. /** \file include/FLAC/format.h
  85547. *
  85548. * \brief
  85549. * This module contains structure definitions for the representation
  85550. * of FLAC format components in memory. These are the basic
  85551. * structures used by the rest of the interfaces.
  85552. *
  85553. * See the detailed documentation in the
  85554. * \link flac_format format \endlink module.
  85555. */
  85556. /** \defgroup flac_format FLAC/format.h: format components
  85557. * \ingroup flac
  85558. *
  85559. * \brief
  85560. * This module contains structure definitions for the representation
  85561. * of FLAC format components in memory. These are the basic
  85562. * structures used by the rest of the interfaces.
  85563. *
  85564. * First, you should be familiar with the
  85565. * <A HREF="../format.html">FLAC format</A>. Many of the values here
  85566. * follow directly from the specification. As a user of libFLAC, the
  85567. * interesting parts really are the structures that describe the frame
  85568. * header and metadata blocks.
  85569. *
  85570. * The format structures here are very primitive, designed to store
  85571. * information in an efficient way. Reading information from the
  85572. * structures is easy but creating or modifying them directly is
  85573. * more complex. For the most part, as a user of a library, editing
  85574. * is not necessary; however, for metadata blocks it is, so there are
  85575. * convenience functions provided in the \link flac_metadata metadata
  85576. * module \endlink to simplify the manipulation of metadata blocks.
  85577. *
  85578. * \note
  85579. * It's not the best convention, but symbols ending in _LEN are in bits
  85580. * and _LENGTH are in bytes. _LENGTH symbols are \#defines instead of
  85581. * global variables because they are usually used when declaring byte
  85582. * arrays and some compilers require compile-time knowledge of array
  85583. * sizes when declared on the stack.
  85584. *
  85585. * \{
  85586. */
  85587. /*
  85588. Most of the values described in this file are defined by the FLAC
  85589. format specification. There is nothing to tune here.
  85590. */
  85591. /** The largest legal metadata type code. */
  85592. #define FLAC__MAX_METADATA_TYPE_CODE (126u)
  85593. /** The minimum block size, in samples, permitted by the format. */
  85594. #define FLAC__MIN_BLOCK_SIZE (16u)
  85595. /** The maximum block size, in samples, permitted by the format. */
  85596. #define FLAC__MAX_BLOCK_SIZE (65535u)
  85597. /** The maximum block size, in samples, permitted by the FLAC subset for
  85598. * sample rates up to 48kHz. */
  85599. #define FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ (4608u)
  85600. /** The maximum number of channels permitted by the format. */
  85601. #define FLAC__MAX_CHANNELS (8u)
  85602. /** The minimum sample resolution permitted by the format. */
  85603. #define FLAC__MIN_BITS_PER_SAMPLE (4u)
  85604. /** The maximum sample resolution permitted by the format. */
  85605. #define FLAC__MAX_BITS_PER_SAMPLE (32u)
  85606. /** The maximum sample resolution permitted by libFLAC.
  85607. *
  85608. * \warning
  85609. * FLAC__MAX_BITS_PER_SAMPLE is the limit of the FLAC format. However,
  85610. * the reference encoder/decoder is currently limited to 24 bits because
  85611. * of prevalent 32-bit math, so make sure and use this value when
  85612. * appropriate.
  85613. */
  85614. #define FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE (24u)
  85615. /** The maximum sample rate permitted by the format. The value is
  85616. * ((2 ^ 16) - 1) * 10; see <A HREF="../format.html">FLAC format</A>
  85617. * as to why.
  85618. */
  85619. #define FLAC__MAX_SAMPLE_RATE (655350u)
  85620. /** The maximum LPC order permitted by the format. */
  85621. #define FLAC__MAX_LPC_ORDER (32u)
  85622. /** The maximum LPC order permitted by the FLAC subset for sample rates
  85623. * up to 48kHz. */
  85624. #define FLAC__SUBSET_MAX_LPC_ORDER_48000HZ (12u)
  85625. /** The minimum quantized linear predictor coefficient precision
  85626. * permitted by the format.
  85627. */
  85628. #define FLAC__MIN_QLP_COEFF_PRECISION (5u)
  85629. /** The maximum quantized linear predictor coefficient precision
  85630. * permitted by the format.
  85631. */
  85632. #define FLAC__MAX_QLP_COEFF_PRECISION (15u)
  85633. /** The maximum order of the fixed predictors permitted by the format. */
  85634. #define FLAC__MAX_FIXED_ORDER (4u)
  85635. /** The maximum Rice partition order permitted by the format. */
  85636. #define FLAC__MAX_RICE_PARTITION_ORDER (15u)
  85637. /** The maximum Rice partition order permitted by the FLAC Subset. */
  85638. #define FLAC__SUBSET_MAX_RICE_PARTITION_ORDER (8u)
  85639. /** The version string of the release, stamped onto the libraries and binaries.
  85640. *
  85641. * \note
  85642. * This does not correspond to the shared library version number, which
  85643. * is used to determine binary compatibility.
  85644. */
  85645. extern FLAC_API const char *FLAC__VERSION_STRING;
  85646. /** The vendor string inserted by the encoder into the VORBIS_COMMENT block.
  85647. * This is a NUL-terminated ASCII string; when inserted into the
  85648. * VORBIS_COMMENT the trailing null is stripped.
  85649. */
  85650. extern FLAC_API const char *FLAC__VENDOR_STRING;
  85651. /** The byte string representation of the beginning of a FLAC stream. */
  85652. extern FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4]; /* = "fLaC" */
  85653. /** The 32-bit integer big-endian representation of the beginning of
  85654. * a FLAC stream.
  85655. */
  85656. extern FLAC_API const unsigned FLAC__STREAM_SYNC; /* = 0x664C6143 */
  85657. /** The length of the FLAC signature in bits. */
  85658. extern FLAC_API const unsigned FLAC__STREAM_SYNC_LEN; /* = 32 bits */
  85659. /** The length of the FLAC signature in bytes. */
  85660. #define FLAC__STREAM_SYNC_LENGTH (4u)
  85661. /*****************************************************************************
  85662. *
  85663. * Subframe structures
  85664. *
  85665. *****************************************************************************/
  85666. /*****************************************************************************/
  85667. /** An enumeration of the available entropy coding methods. */
  85668. typedef enum {
  85669. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE = 0,
  85670. /**< Residual is coded by partitioning into contexts, each with it's own
  85671. * 4-bit Rice parameter. */
  85672. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 = 1
  85673. /**< Residual is coded by partitioning into contexts, each with it's own
  85674. * 5-bit Rice parameter. */
  85675. } FLAC__EntropyCodingMethodType;
  85676. /** Maps a FLAC__EntropyCodingMethodType to a C string.
  85677. *
  85678. * Using a FLAC__EntropyCodingMethodType as the index to this array will
  85679. * give the string equivalent. The contents should not be modified.
  85680. */
  85681. extern FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[];
  85682. /** Contents of a Rice partitioned residual
  85683. */
  85684. typedef struct {
  85685. unsigned *parameters;
  85686. /**< The Rice parameters for each context. */
  85687. unsigned *raw_bits;
  85688. /**< Widths for escape-coded partitions. Will be non-zero for escaped
  85689. * partitions and zero for unescaped partitions.
  85690. */
  85691. unsigned capacity_by_order;
  85692. /**< The capacity of the \a parameters and \a raw_bits arrays
  85693. * specified as an order, i.e. the number of array elements
  85694. * allocated is 2 ^ \a capacity_by_order.
  85695. */
  85696. } FLAC__EntropyCodingMethod_PartitionedRiceContents;
  85697. /** Header for a Rice partitioned residual. (c.f. <A HREF="../format.html#partitioned_rice">format specification</A>)
  85698. */
  85699. typedef struct {
  85700. unsigned order;
  85701. /**< The partition order, i.e. # of contexts = 2 ^ \a order. */
  85702. const FLAC__EntropyCodingMethod_PartitionedRiceContents *contents;
  85703. /**< The context's Rice parameters and/or raw bits. */
  85704. } FLAC__EntropyCodingMethod_PartitionedRice;
  85705. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN; /**< == 4 (bits) */
  85706. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN; /**< == 4 (bits) */
  85707. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN; /**< == 5 (bits) */
  85708. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN; /**< == 5 (bits) */
  85709. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  85710. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  85711. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER;
  85712. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  85713. /** Header for the entropy coding method. (c.f. <A HREF="../format.html#residual">format specification</A>)
  85714. */
  85715. typedef struct {
  85716. FLAC__EntropyCodingMethodType type;
  85717. union {
  85718. FLAC__EntropyCodingMethod_PartitionedRice partitioned_rice;
  85719. } data;
  85720. } FLAC__EntropyCodingMethod;
  85721. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN; /**< == 2 (bits) */
  85722. /*****************************************************************************/
  85723. /** An enumeration of the available subframe types. */
  85724. typedef enum {
  85725. FLAC__SUBFRAME_TYPE_CONSTANT = 0, /**< constant signal */
  85726. FLAC__SUBFRAME_TYPE_VERBATIM = 1, /**< uncompressed signal */
  85727. FLAC__SUBFRAME_TYPE_FIXED = 2, /**< fixed polynomial prediction */
  85728. FLAC__SUBFRAME_TYPE_LPC = 3 /**< linear prediction */
  85729. } FLAC__SubframeType;
  85730. /** Maps a FLAC__SubframeType to a C string.
  85731. *
  85732. * Using a FLAC__SubframeType as the index to this array will
  85733. * give the string equivalent. The contents should not be modified.
  85734. */
  85735. extern FLAC_API const char * const FLAC__SubframeTypeString[];
  85736. /** CONSTANT subframe. (c.f. <A HREF="../format.html#subframe_constant">format specification</A>)
  85737. */
  85738. typedef struct {
  85739. FLAC__int32 value; /**< The constant signal value. */
  85740. } FLAC__Subframe_Constant;
  85741. /** VERBATIM subframe. (c.f. <A HREF="../format.html#subframe_verbatim">format specification</A>)
  85742. */
  85743. typedef struct {
  85744. const FLAC__int32 *data; /**< A pointer to verbatim signal. */
  85745. } FLAC__Subframe_Verbatim;
  85746. /** FIXED subframe. (c.f. <A HREF="../format.html#subframe_fixed">format specification</A>)
  85747. */
  85748. typedef struct {
  85749. FLAC__EntropyCodingMethod entropy_coding_method;
  85750. /**< The residual coding method. */
  85751. unsigned order;
  85752. /**< The polynomial order. */
  85753. FLAC__int32 warmup[FLAC__MAX_FIXED_ORDER];
  85754. /**< Warmup samples to prime the predictor, length == order. */
  85755. const FLAC__int32 *residual;
  85756. /**< The residual signal, length == (blocksize minus order) samples. */
  85757. } FLAC__Subframe_Fixed;
  85758. /** LPC subframe. (c.f. <A HREF="../format.html#subframe_lpc">format specification</A>)
  85759. */
  85760. typedef struct {
  85761. FLAC__EntropyCodingMethod entropy_coding_method;
  85762. /**< The residual coding method. */
  85763. unsigned order;
  85764. /**< The FIR order. */
  85765. unsigned qlp_coeff_precision;
  85766. /**< Quantized FIR filter coefficient precision in bits. */
  85767. int quantization_level;
  85768. /**< The qlp coeff shift needed. */
  85769. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  85770. /**< FIR filter coefficients. */
  85771. FLAC__int32 warmup[FLAC__MAX_LPC_ORDER];
  85772. /**< Warmup samples to prime the predictor, length == order. */
  85773. const FLAC__int32 *residual;
  85774. /**< The residual signal, length == (blocksize minus order) samples. */
  85775. } FLAC__Subframe_LPC;
  85776. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN; /**< == 4 (bits) */
  85777. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN; /**< == 5 (bits) */
  85778. /** FLAC subframe structure. (c.f. <A HREF="../format.html#subframe">format specification</A>)
  85779. */
  85780. typedef struct {
  85781. FLAC__SubframeType type;
  85782. union {
  85783. FLAC__Subframe_Constant constant;
  85784. FLAC__Subframe_Fixed fixed;
  85785. FLAC__Subframe_LPC lpc;
  85786. FLAC__Subframe_Verbatim verbatim;
  85787. } data;
  85788. unsigned wasted_bits;
  85789. } FLAC__Subframe;
  85790. /** == 1 (bit)
  85791. *
  85792. * This used to be a zero-padding bit (hence the name
  85793. * FLAC__SUBFRAME_ZERO_PAD_LEN) but is now a reserved bit. It still has a
  85794. * mandatory value of \c 0 but in the future may take on the value \c 0 or \c 1
  85795. * to mean something else.
  85796. */
  85797. extern FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN;
  85798. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN; /**< == 6 (bits) */
  85799. extern FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN; /**< == 1 (bit) */
  85800. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK; /**< = 0x00 */
  85801. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK; /**< = 0x02 */
  85802. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK; /**< = 0x10 */
  85803. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK; /**< = 0x40 */
  85804. /*****************************************************************************/
  85805. /*****************************************************************************
  85806. *
  85807. * Frame structures
  85808. *
  85809. *****************************************************************************/
  85810. /** An enumeration of the available channel assignments. */
  85811. typedef enum {
  85812. FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT = 0, /**< independent channels */
  85813. FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE = 1, /**< left+side stereo */
  85814. FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE = 2, /**< right+side stereo */
  85815. FLAC__CHANNEL_ASSIGNMENT_MID_SIDE = 3 /**< mid+side stereo */
  85816. } FLAC__ChannelAssignment;
  85817. /** Maps a FLAC__ChannelAssignment to a C string.
  85818. *
  85819. * Using a FLAC__ChannelAssignment as the index to this array will
  85820. * give the string equivalent. The contents should not be modified.
  85821. */
  85822. extern FLAC_API const char * const FLAC__ChannelAssignmentString[];
  85823. /** An enumeration of the possible frame numbering methods. */
  85824. typedef enum {
  85825. FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER, /**< number contains the frame number */
  85826. FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER /**< number contains the sample number of first sample in frame */
  85827. } FLAC__FrameNumberType;
  85828. /** Maps a FLAC__FrameNumberType to a C string.
  85829. *
  85830. * Using a FLAC__FrameNumberType as the index to this array will
  85831. * give the string equivalent. The contents should not be modified.
  85832. */
  85833. extern FLAC_API const char * const FLAC__FrameNumberTypeString[];
  85834. /** FLAC frame header structure. (c.f. <A HREF="../format.html#frame_header">format specification</A>)
  85835. */
  85836. typedef struct {
  85837. unsigned blocksize;
  85838. /**< The number of samples per subframe. */
  85839. unsigned sample_rate;
  85840. /**< The sample rate in Hz. */
  85841. unsigned channels;
  85842. /**< The number of channels (== number of subframes). */
  85843. FLAC__ChannelAssignment channel_assignment;
  85844. /**< The channel assignment for the frame. */
  85845. unsigned bits_per_sample;
  85846. /**< The sample resolution. */
  85847. FLAC__FrameNumberType number_type;
  85848. /**< The numbering scheme used for the frame. As a convenience, the
  85849. * decoder will always convert a frame number to a sample number because
  85850. * the rules are complex. */
  85851. union {
  85852. FLAC__uint32 frame_number;
  85853. FLAC__uint64 sample_number;
  85854. } number;
  85855. /**< The frame number or sample number of first sample in frame;
  85856. * use the \a number_type value to determine which to use. */
  85857. FLAC__uint8 crc;
  85858. /**< CRC-8 (polynomial = x^8 + x^2 + x^1 + x^0, initialized with 0)
  85859. * of the raw frame header bytes, meaning everything before the CRC byte
  85860. * including the sync code.
  85861. */
  85862. } FLAC__FrameHeader;
  85863. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC; /**< == 0x3ffe; the frame header sync code */
  85864. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN; /**< == 14 (bits) */
  85865. extern FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN; /**< == 1 (bits) */
  85866. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN; /**< == 1 (bits) */
  85867. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN; /**< == 4 (bits) */
  85868. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN; /**< == 4 (bits) */
  85869. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN; /**< == 4 (bits) */
  85870. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN; /**< == 3 (bits) */
  85871. extern FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN; /**< == 1 (bit) */
  85872. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN; /**< == 8 (bits) */
  85873. /** FLAC frame footer structure. (c.f. <A HREF="../format.html#frame_footer">format specification</A>)
  85874. */
  85875. typedef struct {
  85876. FLAC__uint16 crc;
  85877. /**< CRC-16 (polynomial = x^16 + x^15 + x^2 + x^0, initialized with
  85878. * 0) of the bytes before the crc, back to and including the frame header
  85879. * sync code.
  85880. */
  85881. } FLAC__FrameFooter;
  85882. extern FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN; /**< == 16 (bits) */
  85883. /** FLAC frame structure. (c.f. <A HREF="../format.html#frame">format specification</A>)
  85884. */
  85885. typedef struct {
  85886. FLAC__FrameHeader header;
  85887. FLAC__Subframe subframes[FLAC__MAX_CHANNELS];
  85888. FLAC__FrameFooter footer;
  85889. } FLAC__Frame;
  85890. /*****************************************************************************/
  85891. /*****************************************************************************
  85892. *
  85893. * Meta-data structures
  85894. *
  85895. *****************************************************************************/
  85896. /** An enumeration of the available metadata block types. */
  85897. typedef enum {
  85898. FLAC__METADATA_TYPE_STREAMINFO = 0,
  85899. /**< <A HREF="../format.html#metadata_block_streaminfo">STREAMINFO</A> block */
  85900. FLAC__METADATA_TYPE_PADDING = 1,
  85901. /**< <A HREF="../format.html#metadata_block_padding">PADDING</A> block */
  85902. FLAC__METADATA_TYPE_APPLICATION = 2,
  85903. /**< <A HREF="../format.html#metadata_block_application">APPLICATION</A> block */
  85904. FLAC__METADATA_TYPE_SEEKTABLE = 3,
  85905. /**< <A HREF="../format.html#metadata_block_seektable">SEEKTABLE</A> block */
  85906. FLAC__METADATA_TYPE_VORBIS_COMMENT = 4,
  85907. /**< <A HREF="../format.html#metadata_block_vorbis_comment">VORBISCOMMENT</A> block (a.k.a. FLAC tags) */
  85908. FLAC__METADATA_TYPE_CUESHEET = 5,
  85909. /**< <A HREF="../format.html#metadata_block_cuesheet">CUESHEET</A> block */
  85910. FLAC__METADATA_TYPE_PICTURE = 6,
  85911. /**< <A HREF="../format.html#metadata_block_picture">PICTURE</A> block */
  85912. FLAC__METADATA_TYPE_UNDEFINED = 7
  85913. /**< marker to denote beginning of undefined type range; this number will increase as new metadata types are added */
  85914. } FLAC__MetadataType;
  85915. /** Maps a FLAC__MetadataType to a C string.
  85916. *
  85917. * Using a FLAC__MetadataType as the index to this array will
  85918. * give the string equivalent. The contents should not be modified.
  85919. */
  85920. extern FLAC_API const char * const FLAC__MetadataTypeString[];
  85921. /** FLAC STREAMINFO structure. (c.f. <A HREF="../format.html#metadata_block_streaminfo">format specification</A>)
  85922. */
  85923. typedef struct {
  85924. unsigned min_blocksize, max_blocksize;
  85925. unsigned min_framesize, max_framesize;
  85926. unsigned sample_rate;
  85927. unsigned channels;
  85928. unsigned bits_per_sample;
  85929. FLAC__uint64 total_samples;
  85930. FLAC__byte md5sum[16];
  85931. } FLAC__StreamMetadata_StreamInfo;
  85932. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  85933. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  85934. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN; /**< == 24 (bits) */
  85935. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN; /**< == 24 (bits) */
  85936. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN; /**< == 20 (bits) */
  85937. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN; /**< == 3 (bits) */
  85938. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN; /**< == 5 (bits) */
  85939. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN; /**< == 36 (bits) */
  85940. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN; /**< == 128 (bits) */
  85941. /** The total stream length of the STREAMINFO block in bytes. */
  85942. #define FLAC__STREAM_METADATA_STREAMINFO_LENGTH (34u)
  85943. /** FLAC PADDING structure. (c.f. <A HREF="../format.html#metadata_block_padding">format specification</A>)
  85944. */
  85945. typedef struct {
  85946. int dummy;
  85947. /**< Conceptually this is an empty struct since we don't store the
  85948. * padding bytes. Empty structs are not allowed by some C compilers,
  85949. * hence the dummy.
  85950. */
  85951. } FLAC__StreamMetadata_Padding;
  85952. /** FLAC APPLICATION structure. (c.f. <A HREF="../format.html#metadata_block_application">format specification</A>)
  85953. */
  85954. typedef struct {
  85955. FLAC__byte id[4];
  85956. FLAC__byte *data;
  85957. } FLAC__StreamMetadata_Application;
  85958. extern FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN; /**< == 32 (bits) */
  85959. /** SeekPoint structure used in SEEKTABLE blocks. (c.f. <A HREF="../format.html#seekpoint">format specification</A>)
  85960. */
  85961. typedef struct {
  85962. FLAC__uint64 sample_number;
  85963. /**< The sample number of the target frame. */
  85964. FLAC__uint64 stream_offset;
  85965. /**< The offset, in bytes, of the target frame with respect to
  85966. * beginning of the first frame. */
  85967. unsigned frame_samples;
  85968. /**< The number of samples in the target frame. */
  85969. } FLAC__StreamMetadata_SeekPoint;
  85970. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN; /**< == 64 (bits) */
  85971. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN; /**< == 64 (bits) */
  85972. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN; /**< == 16 (bits) */
  85973. /** The total stream length of a seek point in bytes. */
  85974. #define FLAC__STREAM_METADATA_SEEKPOINT_LENGTH (18u)
  85975. /** The value used in the \a sample_number field of
  85976. * FLAC__StreamMetadataSeekPoint used to indicate a placeholder
  85977. * point (== 0xffffffffffffffff).
  85978. */
  85979. extern FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  85980. /** FLAC SEEKTABLE structure. (c.f. <A HREF="../format.html#metadata_block_seektable">format specification</A>)
  85981. *
  85982. * \note From the format specification:
  85983. * - The seek points must be sorted by ascending sample number.
  85984. * - Each seek point's sample number must be the first sample of the
  85985. * target frame.
  85986. * - Each seek point's sample number must be unique within the table.
  85987. * - Existence of a SEEKTABLE block implies a correct setting of
  85988. * total_samples in the stream_info block.
  85989. * - Behavior is undefined when more than one SEEKTABLE block is
  85990. * present in a stream.
  85991. */
  85992. typedef struct {
  85993. unsigned num_points;
  85994. FLAC__StreamMetadata_SeekPoint *points;
  85995. } FLAC__StreamMetadata_SeekTable;
  85996. /** Vorbis comment entry structure used in VORBIS_COMMENT blocks. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  85997. *
  85998. * For convenience, the APIs maintain a trailing NUL character at the end of
  85999. * \a entry which is not counted toward \a length, i.e.
  86000. * \code strlen(entry) == length \endcode
  86001. */
  86002. typedef struct {
  86003. FLAC__uint32 length;
  86004. FLAC__byte *entry;
  86005. } FLAC__StreamMetadata_VorbisComment_Entry;
  86006. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN; /**< == 32 (bits) */
  86007. /** FLAC VORBIS_COMMENT structure. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  86008. */
  86009. typedef struct {
  86010. FLAC__StreamMetadata_VorbisComment_Entry vendor_string;
  86011. FLAC__uint32 num_comments;
  86012. FLAC__StreamMetadata_VorbisComment_Entry *comments;
  86013. } FLAC__StreamMetadata_VorbisComment;
  86014. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN; /**< == 32 (bits) */
  86015. /** FLAC CUESHEET track index structure. (See the
  86016. * <A HREF="../format.html#cuesheet_track_index">format specification</A> for
  86017. * the full description of each field.)
  86018. */
  86019. typedef struct {
  86020. FLAC__uint64 offset;
  86021. /**< Offset in samples, relative to the track offset, of the index
  86022. * point.
  86023. */
  86024. FLAC__byte number;
  86025. /**< The index point number. */
  86026. } FLAC__StreamMetadata_CueSheet_Index;
  86027. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN; /**< == 64 (bits) */
  86028. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN; /**< == 8 (bits) */
  86029. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN; /**< == 3*8 (bits) */
  86030. /** FLAC CUESHEET track structure. (See the
  86031. * <A HREF="../format.html#cuesheet_track">format specification</A> for
  86032. * the full description of each field.)
  86033. */
  86034. typedef struct {
  86035. FLAC__uint64 offset;
  86036. /**< Track offset in samples, relative to the beginning of the FLAC audio stream. */
  86037. FLAC__byte number;
  86038. /**< The track number. */
  86039. char isrc[13];
  86040. /**< Track ISRC. This is a 12-digit alphanumeric code plus a trailing \c NUL byte */
  86041. unsigned type:1;
  86042. /**< The track type: 0 for audio, 1 for non-audio. */
  86043. unsigned pre_emphasis:1;
  86044. /**< The pre-emphasis flag: 0 for no pre-emphasis, 1 for pre-emphasis. */
  86045. FLAC__byte num_indices;
  86046. /**< The number of track index points. */
  86047. FLAC__StreamMetadata_CueSheet_Index *indices;
  86048. /**< NULL if num_indices == 0, else pointer to array of index points. */
  86049. } FLAC__StreamMetadata_CueSheet_Track;
  86050. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN; /**< == 64 (bits) */
  86051. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN; /**< == 8 (bits) */
  86052. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN; /**< == 12*8 (bits) */
  86053. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN; /**< == 1 (bit) */
  86054. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN; /**< == 1 (bit) */
  86055. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN; /**< == 6+13*8 (bits) */
  86056. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN; /**< == 8 (bits) */
  86057. /** FLAC CUESHEET structure. (See the
  86058. * <A HREF="../format.html#metadata_block_cuesheet">format specification</A>
  86059. * for the full description of each field.)
  86060. */
  86061. typedef struct {
  86062. char media_catalog_number[129];
  86063. /**< Media catalog number, in ASCII printable characters 0x20-0x7e. In
  86064. * general, the media catalog number may be 0 to 128 bytes long; any
  86065. * unused characters should be right-padded with NUL characters.
  86066. */
  86067. FLAC__uint64 lead_in;
  86068. /**< The number of lead-in samples. */
  86069. FLAC__bool is_cd;
  86070. /**< \c true if CUESHEET corresponds to a Compact Disc, else \c false. */
  86071. unsigned num_tracks;
  86072. /**< The number of tracks. */
  86073. FLAC__StreamMetadata_CueSheet_Track *tracks;
  86074. /**< NULL if num_tracks == 0, else pointer to array of tracks. */
  86075. } FLAC__StreamMetadata_CueSheet;
  86076. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN; /**< == 128*8 (bits) */
  86077. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN; /**< == 64 (bits) */
  86078. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN; /**< == 1 (bit) */
  86079. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN; /**< == 7+258*8 (bits) */
  86080. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN; /**< == 8 (bits) */
  86081. /** An enumeration of the PICTURE types (see FLAC__StreamMetadataPicture and id3 v2.4 APIC tag). */
  86082. typedef enum {
  86083. FLAC__STREAM_METADATA_PICTURE_TYPE_OTHER = 0, /**< Other */
  86084. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD = 1, /**< 32x32 pixels 'file icon' (PNG only) */
  86085. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON = 2, /**< Other file icon */
  86086. FLAC__STREAM_METADATA_PICTURE_TYPE_FRONT_COVER = 3, /**< Cover (front) */
  86087. FLAC__STREAM_METADATA_PICTURE_TYPE_BACK_COVER = 4, /**< Cover (back) */
  86088. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAFLET_PAGE = 5, /**< Leaflet page */
  86089. FLAC__STREAM_METADATA_PICTURE_TYPE_MEDIA = 6, /**< Media (e.g. label side of CD) */
  86090. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAD_ARTIST = 7, /**< Lead artist/lead performer/soloist */
  86091. FLAC__STREAM_METADATA_PICTURE_TYPE_ARTIST = 8, /**< Artist/performer */
  86092. FLAC__STREAM_METADATA_PICTURE_TYPE_CONDUCTOR = 9, /**< Conductor */
  86093. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND = 10, /**< Band/Orchestra */
  86094. FLAC__STREAM_METADATA_PICTURE_TYPE_COMPOSER = 11, /**< Composer */
  86095. FLAC__STREAM_METADATA_PICTURE_TYPE_LYRICIST = 12, /**< Lyricist/text writer */
  86096. FLAC__STREAM_METADATA_PICTURE_TYPE_RECORDING_LOCATION = 13, /**< Recording Location */
  86097. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_RECORDING = 14, /**< During recording */
  86098. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_PERFORMANCE = 15, /**< During performance */
  86099. FLAC__STREAM_METADATA_PICTURE_TYPE_VIDEO_SCREEN_CAPTURE = 16, /**< Movie/video screen capture */
  86100. FLAC__STREAM_METADATA_PICTURE_TYPE_FISH = 17, /**< A bright coloured fish */
  86101. FLAC__STREAM_METADATA_PICTURE_TYPE_ILLUSTRATION = 18, /**< Illustration */
  86102. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND_LOGOTYPE = 19, /**< Band/artist logotype */
  86103. FLAC__STREAM_METADATA_PICTURE_TYPE_PUBLISHER_LOGOTYPE = 20, /**< Publisher/Studio logotype */
  86104. FLAC__STREAM_METADATA_PICTURE_TYPE_UNDEFINED
  86105. } FLAC__StreamMetadata_Picture_Type;
  86106. /** Maps a FLAC__StreamMetadata_Picture_Type to a C string.
  86107. *
  86108. * Using a FLAC__StreamMetadata_Picture_Type as the index to this array
  86109. * will give the string equivalent. The contents should not be
  86110. * modified.
  86111. */
  86112. extern FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[];
  86113. /** FLAC PICTURE structure. (See the
  86114. * <A HREF="../format.html#metadata_block_picture">format specification</A>
  86115. * for the full description of each field.)
  86116. */
  86117. typedef struct {
  86118. FLAC__StreamMetadata_Picture_Type type;
  86119. /**< The kind of picture stored. */
  86120. char *mime_type;
  86121. /**< Picture data's MIME type, in ASCII printable characters
  86122. * 0x20-0x7e, NUL terminated. For best compatibility with players,
  86123. * use picture data of MIME type \c image/jpeg or \c image/png. A
  86124. * MIME type of '-->' is also allowed, in which case the picture
  86125. * data should be a complete URL. In file storage, the MIME type is
  86126. * stored as a 32-bit length followed by the ASCII string with no NUL
  86127. * terminator, but is converted to a plain C string in this structure
  86128. * for convenience.
  86129. */
  86130. FLAC__byte *description;
  86131. /**< Picture's description in UTF-8, NUL terminated. In file storage,
  86132. * the description is stored as a 32-bit length followed by the UTF-8
  86133. * string with no NUL terminator, but is converted to a plain C string
  86134. * in this structure for convenience.
  86135. */
  86136. FLAC__uint32 width;
  86137. /**< Picture's width in pixels. */
  86138. FLAC__uint32 height;
  86139. /**< Picture's height in pixels. */
  86140. FLAC__uint32 depth;
  86141. /**< Picture's color depth in bits-per-pixel. */
  86142. FLAC__uint32 colors;
  86143. /**< For indexed palettes (like GIF), picture's number of colors (the
  86144. * number of palette entries), or \c 0 for non-indexed (i.e. 2^depth).
  86145. */
  86146. FLAC__uint32 data_length;
  86147. /**< Length of binary picture data in bytes. */
  86148. FLAC__byte *data;
  86149. /**< Binary picture data. */
  86150. } FLAC__StreamMetadata_Picture;
  86151. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN; /**< == 32 (bits) */
  86152. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN; /**< == 32 (bits) */
  86153. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN; /**< == 32 (bits) */
  86154. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN; /**< == 32 (bits) */
  86155. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN; /**< == 32 (bits) */
  86156. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN; /**< == 32 (bits) */
  86157. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN; /**< == 32 (bits) */
  86158. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN; /**< == 32 (bits) */
  86159. /** Structure that is used when a metadata block of unknown type is loaded.
  86160. * The contents are opaque. The structure is used only internally to
  86161. * correctly handle unknown metadata.
  86162. */
  86163. typedef struct {
  86164. FLAC__byte *data;
  86165. } FLAC__StreamMetadata_Unknown;
  86166. /** FLAC metadata block structure. (c.f. <A HREF="../format.html#metadata_block">format specification</A>)
  86167. */
  86168. typedef struct {
  86169. FLAC__MetadataType type;
  86170. /**< The type of the metadata block; used determine which member of the
  86171. * \a data union to dereference. If type >= FLAC__METADATA_TYPE_UNDEFINED
  86172. * then \a data.unknown must be used. */
  86173. FLAC__bool is_last;
  86174. /**< \c true if this metadata block is the last, else \a false */
  86175. unsigned length;
  86176. /**< Length, in bytes, of the block data as it appears in the stream. */
  86177. union {
  86178. FLAC__StreamMetadata_StreamInfo stream_info;
  86179. FLAC__StreamMetadata_Padding padding;
  86180. FLAC__StreamMetadata_Application application;
  86181. FLAC__StreamMetadata_SeekTable seek_table;
  86182. FLAC__StreamMetadata_VorbisComment vorbis_comment;
  86183. FLAC__StreamMetadata_CueSheet cue_sheet;
  86184. FLAC__StreamMetadata_Picture picture;
  86185. FLAC__StreamMetadata_Unknown unknown;
  86186. } data;
  86187. /**< Polymorphic block data; use the \a type value to determine which
  86188. * to use. */
  86189. } FLAC__StreamMetadata;
  86190. extern FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN; /**< == 1 (bit) */
  86191. extern FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN; /**< == 7 (bits) */
  86192. extern FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN; /**< == 24 (bits) */
  86193. /** The total stream length of a metadata block header in bytes. */
  86194. #define FLAC__STREAM_METADATA_HEADER_LENGTH (4u)
  86195. /*****************************************************************************/
  86196. /*****************************************************************************
  86197. *
  86198. * Utility functions
  86199. *
  86200. *****************************************************************************/
  86201. /** Tests that a sample rate is valid for FLAC.
  86202. *
  86203. * \param sample_rate The sample rate to test for compliance.
  86204. * \retval FLAC__bool
  86205. * \c true if the given sample rate conforms to the specification, else
  86206. * \c false.
  86207. */
  86208. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate);
  86209. /** Tests that a sample rate is valid for the FLAC subset. The subset rules
  86210. * for valid sample rates are slightly more complex since the rate has to
  86211. * be expressible completely in the frame header.
  86212. *
  86213. * \param sample_rate The sample rate to test for compliance.
  86214. * \retval FLAC__bool
  86215. * \c true if the given sample rate conforms to the specification for the
  86216. * subset, else \c false.
  86217. */
  86218. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate);
  86219. /** Check a Vorbis comment entry name to see if it conforms to the Vorbis
  86220. * comment specification.
  86221. *
  86222. * Vorbis comment names must be composed only of characters from
  86223. * [0x20-0x3C,0x3E-0x7D].
  86224. *
  86225. * \param name A NUL-terminated string to be checked.
  86226. * \assert
  86227. * \code name != NULL \endcode
  86228. * \retval FLAC__bool
  86229. * \c false if entry name is illegal, else \c true.
  86230. */
  86231. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name);
  86232. /** Check a Vorbis comment entry value to see if it conforms to the Vorbis
  86233. * comment specification.
  86234. *
  86235. * Vorbis comment values must be valid UTF-8 sequences.
  86236. *
  86237. * \param value A string to be checked.
  86238. * \param length A the length of \a value in bytes. May be
  86239. * \c (unsigned)(-1) to indicate that \a value is a plain
  86240. * UTF-8 NUL-terminated string.
  86241. * \assert
  86242. * \code value != NULL \endcode
  86243. * \retval FLAC__bool
  86244. * \c false if entry name is illegal, else \c true.
  86245. */
  86246. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length);
  86247. /** Check a Vorbis comment entry to see if it conforms to the Vorbis
  86248. * comment specification.
  86249. *
  86250. * Vorbis comment entries must be of the form 'name=value', and 'name' and
  86251. * 'value' must be legal according to
  86252. * FLAC__format_vorbiscomment_entry_name_is_legal() and
  86253. * FLAC__format_vorbiscomment_entry_value_is_legal() respectively.
  86254. *
  86255. * \param entry An entry to be checked.
  86256. * \param length The length of \a entry in bytes.
  86257. * \assert
  86258. * \code value != NULL \endcode
  86259. * \retval FLAC__bool
  86260. * \c false if entry name is illegal, else \c true.
  86261. */
  86262. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length);
  86263. /** Check a seek table to see if it conforms to the FLAC specification.
  86264. * See the format specification for limits on the contents of the
  86265. * seek table.
  86266. *
  86267. * \param seek_table A pointer to a seek table to be checked.
  86268. * \assert
  86269. * \code seek_table != NULL \endcode
  86270. * \retval FLAC__bool
  86271. * \c false if seek table is illegal, else \c true.
  86272. */
  86273. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table);
  86274. /** Sort a seek table's seek points according to the format specification.
  86275. * This includes a "unique-ification" step to remove duplicates, i.e.
  86276. * seek points with identical \a sample_number values. Duplicate seek
  86277. * points are converted into placeholder points and sorted to the end of
  86278. * the table.
  86279. *
  86280. * \param seek_table A pointer to a seek table to be sorted.
  86281. * \assert
  86282. * \code seek_table != NULL \endcode
  86283. * \retval unsigned
  86284. * The number of duplicate seek points converted into placeholders.
  86285. */
  86286. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table);
  86287. /** Check a cue sheet to see if it conforms to the FLAC specification.
  86288. * See the format specification for limits on the contents of the
  86289. * cue sheet.
  86290. *
  86291. * \param cue_sheet A pointer to an existing cue sheet to be checked.
  86292. * \param check_cd_da_subset If \c true, check CUESHEET against more
  86293. * stringent requirements for a CD-DA (audio) disc.
  86294. * \param violation Address of a pointer to a string. If there is a
  86295. * violation, a pointer to a string explanation of the
  86296. * violation will be returned here. \a violation may be
  86297. * \c NULL if you don't need the returned string. Do not
  86298. * free the returned string; it will always point to static
  86299. * data.
  86300. * \assert
  86301. * \code cue_sheet != NULL \endcode
  86302. * \retval FLAC__bool
  86303. * \c false if cue sheet is illegal, else \c true.
  86304. */
  86305. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation);
  86306. /** Check picture data to see if it conforms to the FLAC specification.
  86307. * See the format specification for limits on the contents of the
  86308. * PICTURE block.
  86309. *
  86310. * \param picture A pointer to existing picture data to be checked.
  86311. * \param violation Address of a pointer to a string. If there is a
  86312. * violation, a pointer to a string explanation of the
  86313. * violation will be returned here. \a violation may be
  86314. * \c NULL if you don't need the returned string. Do not
  86315. * free the returned string; it will always point to static
  86316. * data.
  86317. * \assert
  86318. * \code picture != NULL \endcode
  86319. * \retval FLAC__bool
  86320. * \c false if picture data is illegal, else \c true.
  86321. */
  86322. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation);
  86323. /* \} */
  86324. #ifdef __cplusplus
  86325. }
  86326. #endif
  86327. #endif
  86328. /*** End of inlined file: format.h ***/
  86329. /*** Start of inlined file: metadata.h ***/
  86330. #ifndef FLAC__METADATA_H
  86331. #define FLAC__METADATA_H
  86332. #include <sys/types.h> /* for off_t */
  86333. /* --------------------------------------------------------------------
  86334. (For an example of how all these routines are used, see the source
  86335. code for the unit tests in src/test_libFLAC/metadata_*.c, or
  86336. metaflac in src/metaflac/)
  86337. ------------------------------------------------------------------*/
  86338. /** \file include/FLAC/metadata.h
  86339. *
  86340. * \brief
  86341. * This module provides functions for creating and manipulating FLAC
  86342. * metadata blocks in memory, and three progressively more powerful
  86343. * interfaces for traversing and editing metadata in FLAC files.
  86344. *
  86345. * See the detailed documentation for each interface in the
  86346. * \link flac_metadata metadata \endlink module.
  86347. */
  86348. /** \defgroup flac_metadata FLAC/metadata.h: metadata interfaces
  86349. * \ingroup flac
  86350. *
  86351. * \brief
  86352. * This module provides functions for creating and manipulating FLAC
  86353. * metadata blocks in memory, and three progressively more powerful
  86354. * interfaces for traversing and editing metadata in native FLAC files.
  86355. * Note that currently only the Chain interface (level 2) supports Ogg
  86356. * FLAC files, and it is read-only i.e. no writing back changed
  86357. * metadata to file.
  86358. *
  86359. * There are three metadata interfaces of increasing complexity:
  86360. *
  86361. * Level 0:
  86362. * Read-only access to the STREAMINFO, VORBIS_COMMENT, CUESHEET, and
  86363. * PICTURE blocks.
  86364. *
  86365. * Level 1:
  86366. * Read-write access to all metadata blocks. This level is write-
  86367. * efficient in most cases (more on this below), and uses less memory
  86368. * than level 2.
  86369. *
  86370. * Level 2:
  86371. * Read-write access to all metadata blocks. This level is write-
  86372. * efficient in all cases, but uses more memory since all metadata for
  86373. * the whole file is read into memory and manipulated before writing
  86374. * out again.
  86375. *
  86376. * What do we mean by efficient? Since FLAC metadata appears at the
  86377. * beginning of the file, when writing metadata back to a FLAC file
  86378. * it is possible to grow or shrink the metadata such that the entire
  86379. * file must be rewritten. However, if the size remains the same during
  86380. * changes or PADDING blocks are utilized, only the metadata needs to be
  86381. * overwritten, which is much faster.
  86382. *
  86383. * Efficient means the whole file is rewritten at most one time, and only
  86384. * when necessary. Level 1 is not efficient only in the case that you
  86385. * cause more than one metadata block to grow or shrink beyond what can
  86386. * be accomodated by padding. In this case you should probably use level
  86387. * 2, which allows you to edit all the metadata for a file in memory and
  86388. * write it out all at once.
  86389. *
  86390. * All levels know how to skip over and not disturb an ID3v2 tag at the
  86391. * front of the file.
  86392. *
  86393. * All levels access files via their filenames. In addition, level 2
  86394. * has additional alternative read and write functions that take an I/O
  86395. * handle and callbacks, for situations where access by filename is not
  86396. * possible.
  86397. *
  86398. * In addition to the three interfaces, this module defines functions for
  86399. * creating and manipulating various metadata objects in memory. As we see
  86400. * from the Format module, FLAC metadata blocks in memory are very primitive
  86401. * structures for storing information in an efficient way. Reading
  86402. * information from the structures is easy but creating or modifying them
  86403. * directly is more complex. The metadata object routines here facilitate
  86404. * this by taking care of the consistency and memory management drudgery.
  86405. *
  86406. * Unless you will be using the level 1 or 2 interfaces to modify existing
  86407. * metadata however, you will not probably not need these.
  86408. *
  86409. * From a dependency standpoint, none of the encoders or decoders require
  86410. * the metadata module. This is so that embedded users can strip out the
  86411. * metadata module from libFLAC to reduce the size and complexity.
  86412. */
  86413. #ifdef __cplusplus
  86414. extern "C" {
  86415. #endif
  86416. /** \defgroup flac_metadata_level0 FLAC/metadata.h: metadata level 0 interface
  86417. * \ingroup flac_metadata
  86418. *
  86419. * \brief
  86420. * The level 0 interface consists of individual routines to read the
  86421. * STREAMINFO, VORBIS_COMMENT, CUESHEET, and PICTURE blocks, requiring
  86422. * only a filename.
  86423. *
  86424. * They try to skip any ID3v2 tag at the head of the file.
  86425. *
  86426. * \{
  86427. */
  86428. /** Read the STREAMINFO metadata block of the given FLAC file. This function
  86429. * will try to skip any ID3v2 tag at the head of the file.
  86430. *
  86431. * \param filename The path to the FLAC file to read.
  86432. * \param streaminfo A pointer to space for the STREAMINFO block. Since
  86433. * FLAC__StreamMetadata is a simple structure with no
  86434. * memory allocation involved, you pass the address of
  86435. * an existing structure. It need not be initialized.
  86436. * \assert
  86437. * \code filename != NULL \endcode
  86438. * \code streaminfo != NULL \endcode
  86439. * \retval FLAC__bool
  86440. * \c true if a valid STREAMINFO block was read from \a filename. Returns
  86441. * \c false if there was a memory allocation error, a file decoder error,
  86442. * or the file contained no STREAMINFO block. (A memory allocation error
  86443. * is possible because this function must set up a file decoder.)
  86444. */
  86445. FLAC_API FLAC__bool FLAC__metadata_get_streaminfo(const char *filename, FLAC__StreamMetadata *streaminfo);
  86446. /** Read the VORBIS_COMMENT metadata block of the given FLAC file. This
  86447. * function will try to skip any ID3v2 tag at the head of the file.
  86448. *
  86449. * \param filename The path to the FLAC file to read.
  86450. * \param tags The address where the returned pointer will be
  86451. * stored. The \a tags object must be deleted by
  86452. * the caller using FLAC__metadata_object_delete().
  86453. * \assert
  86454. * \code filename != NULL \endcode
  86455. * \code tags != NULL \endcode
  86456. * \retval FLAC__bool
  86457. * \c true if a valid VORBIS_COMMENT block was read from \a filename,
  86458. * and \a *tags will be set to the address of the metadata structure.
  86459. * Returns \c false if there was a memory allocation error, a file
  86460. * decoder error, or the file contained no VORBIS_COMMENT block, and
  86461. * \a *tags will be set to \c NULL.
  86462. */
  86463. FLAC_API FLAC__bool FLAC__metadata_get_tags(const char *filename, FLAC__StreamMetadata **tags);
  86464. /** Read the CUESHEET metadata block of the given FLAC file. This
  86465. * function will try to skip any ID3v2 tag at the head of the file.
  86466. *
  86467. * \param filename The path to the FLAC file to read.
  86468. * \param cuesheet The address where the returned pointer will be
  86469. * stored. The \a cuesheet object must be deleted by
  86470. * the caller using FLAC__metadata_object_delete().
  86471. * \assert
  86472. * \code filename != NULL \endcode
  86473. * \code cuesheet != NULL \endcode
  86474. * \retval FLAC__bool
  86475. * \c true if a valid CUESHEET block was read from \a filename,
  86476. * and \a *cuesheet will be set to the address of the metadata
  86477. * structure. Returns \c false if there was a memory allocation
  86478. * error, a file decoder error, or the file contained no CUESHEET
  86479. * block, and \a *cuesheet will be set to \c NULL.
  86480. */
  86481. FLAC_API FLAC__bool FLAC__metadata_get_cuesheet(const char *filename, FLAC__StreamMetadata **cuesheet);
  86482. /** Read a PICTURE metadata block of the given FLAC file. This
  86483. * function will try to skip any ID3v2 tag at the head of the file.
  86484. * Since there can be more than one PICTURE block in a file, this
  86485. * function takes a number of parameters that act as constraints to
  86486. * the search. The PICTURE block with the largest area matching all
  86487. * the constraints will be returned, or \a *picture will be set to
  86488. * \c NULL if there was no such block.
  86489. *
  86490. * \param filename The path to the FLAC file to read.
  86491. * \param picture The address where the returned pointer will be
  86492. * stored. The \a picture object must be deleted by
  86493. * the caller using FLAC__metadata_object_delete().
  86494. * \param type The desired picture type. Use \c -1 to mean
  86495. * "any type".
  86496. * \param mime_type The desired MIME type, e.g. "image/jpeg". The
  86497. * string will be matched exactly. Use \c NULL to
  86498. * mean "any MIME type".
  86499. * \param description The desired description. The string will be
  86500. * matched exactly. Use \c NULL to mean "any
  86501. * description".
  86502. * \param max_width The maximum width in pixels desired. Use
  86503. * \c (unsigned)(-1) to mean "any width".
  86504. * \param max_height The maximum height in pixels desired. Use
  86505. * \c (unsigned)(-1) to mean "any height".
  86506. * \param max_depth The maximum color depth in bits-per-pixel desired.
  86507. * Use \c (unsigned)(-1) to mean "any depth".
  86508. * \param max_colors The maximum number of colors desired. Use
  86509. * \c (unsigned)(-1) to mean "any number of colors".
  86510. * \assert
  86511. * \code filename != NULL \endcode
  86512. * \code picture != NULL \endcode
  86513. * \retval FLAC__bool
  86514. * \c true if a valid PICTURE block was read from \a filename,
  86515. * and \a *picture will be set to the address of the metadata
  86516. * structure. Returns \c false if there was a memory allocation
  86517. * error, a file decoder error, or the file contained no PICTURE
  86518. * block, and \a *picture will be set to \c NULL.
  86519. */
  86520. 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);
  86521. /* \} */
  86522. /** \defgroup flac_metadata_level1 FLAC/metadata.h: metadata level 1 interface
  86523. * \ingroup flac_metadata
  86524. *
  86525. * \brief
  86526. * The level 1 interface provides read-write access to FLAC file metadata and
  86527. * operates directly on the FLAC file.
  86528. *
  86529. * The general usage of this interface is:
  86530. *
  86531. * - Create an iterator using FLAC__metadata_simple_iterator_new()
  86532. * - Attach it to a file using FLAC__metadata_simple_iterator_init() and check
  86533. * the exit code. Call FLAC__metadata_simple_iterator_is_writable() to
  86534. * see if the file is writable, or only read access is allowed.
  86535. * - Use FLAC__metadata_simple_iterator_next() and
  86536. * FLAC__metadata_simple_iterator_prev() to traverse the blocks.
  86537. * This is does not read the actual blocks themselves.
  86538. * FLAC__metadata_simple_iterator_next() is relatively fast.
  86539. * FLAC__metadata_simple_iterator_prev() is slower since it needs to search
  86540. * forward from the front of the file.
  86541. * - Use FLAC__metadata_simple_iterator_get_block_type() or
  86542. * FLAC__metadata_simple_iterator_get_block() to access the actual data at
  86543. * the current iterator position. The returned object is yours to modify
  86544. * and free.
  86545. * - Use FLAC__metadata_simple_iterator_set_block() to write a modified block
  86546. * back. You must have write permission to the original file. Make sure to
  86547. * read the whole comment to FLAC__metadata_simple_iterator_set_block()
  86548. * below.
  86549. * - Use FLAC__metadata_simple_iterator_insert_block_after() to add new blocks.
  86550. * Use the object creation functions from
  86551. * \link flac_metadata_object here \endlink to generate new objects.
  86552. * - Use FLAC__metadata_simple_iterator_delete_block() to remove the block
  86553. * currently referred to by the iterator, or replace it with padding.
  86554. * - Destroy the iterator with FLAC__metadata_simple_iterator_delete() when
  86555. * finished.
  86556. *
  86557. * \note
  86558. * The FLAC file remains open the whole time between
  86559. * FLAC__metadata_simple_iterator_init() and
  86560. * FLAC__metadata_simple_iterator_delete(), so make sure you are not altering
  86561. * the file during this time.
  86562. *
  86563. * \note
  86564. * Do not modify the \a is_last, \a length, or \a type fields of returned
  86565. * FLAC__StreamMetadata objects. These are managed automatically.
  86566. *
  86567. * \note
  86568. * If any of the modification functions
  86569. * (FLAC__metadata_simple_iterator_set_block(),
  86570. * FLAC__metadata_simple_iterator_delete_block(),
  86571. * FLAC__metadata_simple_iterator_insert_block_after(), etc.) return \c false,
  86572. * you should delete the iterator as it may no longer be valid.
  86573. *
  86574. * \{
  86575. */
  86576. struct FLAC__Metadata_SimpleIterator;
  86577. /** The opaque structure definition for the level 1 iterator type.
  86578. * See the
  86579. * \link flac_metadata_level1 metadata level 1 module \endlink
  86580. * for a detailed description.
  86581. */
  86582. typedef struct FLAC__Metadata_SimpleIterator FLAC__Metadata_SimpleIterator;
  86583. /** Status type for FLAC__Metadata_SimpleIterator.
  86584. *
  86585. * The iterator's current status can be obtained by calling FLAC__metadata_simple_iterator_status().
  86586. */
  86587. typedef enum {
  86588. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK = 0,
  86589. /**< The iterator is in the normal OK state */
  86590. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT,
  86591. /**< The data passed into a function violated the function's usage criteria */
  86592. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE,
  86593. /**< The iterator could not open the target file */
  86594. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_A_FLAC_FILE,
  86595. /**< The iterator could not find the FLAC signature at the start of the file */
  86596. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_WRITABLE,
  86597. /**< The iterator tried to write to a file that was not writable */
  86598. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_BAD_METADATA,
  86599. /**< The iterator encountered input that does not conform to the FLAC metadata specification */
  86600. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR,
  86601. /**< The iterator encountered an error while reading the FLAC file */
  86602. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR,
  86603. /**< The iterator encountered an error while seeking in the FLAC file */
  86604. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR,
  86605. /**< The iterator encountered an error while writing the FLAC file */
  86606. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_RENAME_ERROR,
  86607. /**< The iterator encountered an error renaming the FLAC file */
  86608. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_UNLINK_ERROR,
  86609. /**< The iterator encountered an error removing the temporary file */
  86610. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR,
  86611. /**< Memory allocation failed */
  86612. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_INTERNAL_ERROR
  86613. /**< The caller violated an assertion or an unexpected error occurred */
  86614. } FLAC__Metadata_SimpleIteratorStatus;
  86615. /** Maps a FLAC__Metadata_SimpleIteratorStatus to a C string.
  86616. *
  86617. * Using a FLAC__Metadata_SimpleIteratorStatus as the index to this array
  86618. * will give the string equivalent. The contents should not be modified.
  86619. */
  86620. extern FLAC_API const char * const FLAC__Metadata_SimpleIteratorStatusString[];
  86621. /** Create a new iterator instance.
  86622. *
  86623. * \retval FLAC__Metadata_SimpleIterator*
  86624. * \c NULL if there was an error allocating memory, else the new instance.
  86625. */
  86626. FLAC_API FLAC__Metadata_SimpleIterator *FLAC__metadata_simple_iterator_new(void);
  86627. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  86628. *
  86629. * \param iterator A pointer to an existing iterator.
  86630. * \assert
  86631. * \code iterator != NULL \endcode
  86632. */
  86633. FLAC_API void FLAC__metadata_simple_iterator_delete(FLAC__Metadata_SimpleIterator *iterator);
  86634. /** Get the current status of the iterator. Call this after a function
  86635. * returns \c false to get the reason for the error. Also resets the status
  86636. * to FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK.
  86637. *
  86638. * \param iterator A pointer to an existing iterator.
  86639. * \assert
  86640. * \code iterator != NULL \endcode
  86641. * \retval FLAC__Metadata_SimpleIteratorStatus
  86642. * The current status of the iterator.
  86643. */
  86644. FLAC_API FLAC__Metadata_SimpleIteratorStatus FLAC__metadata_simple_iterator_status(FLAC__Metadata_SimpleIterator *iterator);
  86645. /** Initialize the iterator to point to the first metadata block in the
  86646. * given FLAC file.
  86647. *
  86648. * \param iterator A pointer to an existing iterator.
  86649. * \param filename The path to the FLAC file.
  86650. * \param read_only If \c true, the FLAC file will be opened
  86651. * in read-only mode; if \c false, the FLAC
  86652. * file will be opened for edit even if no
  86653. * edits are performed.
  86654. * \param preserve_file_stats If \c true, the owner and modification
  86655. * time will be preserved even if the FLAC
  86656. * file is written to.
  86657. * \assert
  86658. * \code iterator != NULL \endcode
  86659. * \code filename != NULL \endcode
  86660. * \retval FLAC__bool
  86661. * \c false if a memory allocation error occurs, the file can't be
  86662. * opened, or another error occurs, else \c true.
  86663. */
  86664. 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);
  86665. /** Returns \c true if the FLAC file is writable. If \c false, calls to
  86666. * FLAC__metadata_simple_iterator_set_block() and
  86667. * FLAC__metadata_simple_iterator_insert_block_after() will fail.
  86668. *
  86669. * \param iterator A pointer to an existing iterator.
  86670. * \assert
  86671. * \code iterator != NULL \endcode
  86672. * \retval FLAC__bool
  86673. * See above.
  86674. */
  86675. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_writable(const FLAC__Metadata_SimpleIterator *iterator);
  86676. /** Moves the iterator forward one metadata block, returning \c false if
  86677. * already at the end.
  86678. *
  86679. * \param iterator A pointer to an existing initialized iterator.
  86680. * \assert
  86681. * \code iterator != NULL \endcode
  86682. * \a iterator has been successfully initialized with
  86683. * FLAC__metadata_simple_iterator_init()
  86684. * \retval FLAC__bool
  86685. * \c false if already at the last metadata block of the chain, else
  86686. * \c true.
  86687. */
  86688. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_next(FLAC__Metadata_SimpleIterator *iterator);
  86689. /** Moves the iterator backward one metadata block, returning \c false if
  86690. * already at the beginning.
  86691. *
  86692. * \param iterator A pointer to an existing initialized iterator.
  86693. * \assert
  86694. * \code iterator != NULL \endcode
  86695. * \a iterator has been successfully initialized with
  86696. * FLAC__metadata_simple_iterator_init()
  86697. * \retval FLAC__bool
  86698. * \c false if already at the first metadata block of the chain, else
  86699. * \c true.
  86700. */
  86701. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_prev(FLAC__Metadata_SimpleIterator *iterator);
  86702. /** Returns a flag telling if the current metadata block is the last.
  86703. *
  86704. * \param iterator A pointer to an existing initialized iterator.
  86705. * \assert
  86706. * \code iterator != NULL \endcode
  86707. * \a iterator has been successfully initialized with
  86708. * FLAC__metadata_simple_iterator_init()
  86709. * \retval FLAC__bool
  86710. * \c true if the current metadata block is the last in the file,
  86711. * else \c false.
  86712. */
  86713. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_last(const FLAC__Metadata_SimpleIterator *iterator);
  86714. /** Get the offset of the metadata block at the current position. This
  86715. * avoids reading the actual block data which can save time for large
  86716. * blocks.
  86717. *
  86718. * \param iterator A pointer to an existing initialized iterator.
  86719. * \assert
  86720. * \code iterator != NULL \endcode
  86721. * \a iterator has been successfully initialized with
  86722. * FLAC__metadata_simple_iterator_init()
  86723. * \retval off_t
  86724. * The offset of the metadata block at the current iterator position.
  86725. * This is the byte offset relative to the beginning of the file of
  86726. * the current metadata block's header.
  86727. */
  86728. FLAC_API off_t FLAC__metadata_simple_iterator_get_block_offset(const FLAC__Metadata_SimpleIterator *iterator);
  86729. /** Get the type of the metadata block at the current position. This
  86730. * avoids reading the actual block data which can save time for large
  86731. * blocks.
  86732. *
  86733. * \param iterator A pointer to an existing initialized iterator.
  86734. * \assert
  86735. * \code iterator != NULL \endcode
  86736. * \a iterator has been successfully initialized with
  86737. * FLAC__metadata_simple_iterator_init()
  86738. * \retval FLAC__MetadataType
  86739. * The type of the metadata block at the current iterator position.
  86740. */
  86741. FLAC_API FLAC__MetadataType FLAC__metadata_simple_iterator_get_block_type(const FLAC__Metadata_SimpleIterator *iterator);
  86742. /** Get the length of the metadata block at the current position. This
  86743. * avoids reading the actual block data which can save time for large
  86744. * blocks.
  86745. *
  86746. * \param iterator A pointer to an existing initialized iterator.
  86747. * \assert
  86748. * \code iterator != NULL \endcode
  86749. * \a iterator has been successfully initialized with
  86750. * FLAC__metadata_simple_iterator_init()
  86751. * \retval unsigned
  86752. * The length of the metadata block at the current iterator position.
  86753. * The is same length as that in the
  86754. * <a href="http://flac.sourceforge.net/format.html#metadata_block_header">metadata block header</a>,
  86755. * i.e. the length of the metadata body that follows the header.
  86756. */
  86757. FLAC_API unsigned FLAC__metadata_simple_iterator_get_block_length(const FLAC__Metadata_SimpleIterator *iterator);
  86758. /** Get the application ID of the \c APPLICATION block at the current
  86759. * position. This avoids reading the actual block data which can save
  86760. * time for large blocks.
  86761. *
  86762. * \param iterator A pointer to an existing initialized iterator.
  86763. * \param id A pointer to a buffer of at least \c 4 bytes where
  86764. * the ID will be stored.
  86765. * \assert
  86766. * \code iterator != NULL \endcode
  86767. * \code id != NULL \endcode
  86768. * \a iterator has been successfully initialized with
  86769. * FLAC__metadata_simple_iterator_init()
  86770. * \retval FLAC__bool
  86771. * \c true if the ID was successfully read, else \c false, in which
  86772. * case you should check FLAC__metadata_simple_iterator_status() to
  86773. * find out why. If the status is
  86774. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT, then the
  86775. * current metadata block is not an \c APPLICATION block. Otherwise
  86776. * if the status is
  86777. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR or
  86778. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR, an I/O error
  86779. * occurred and the iterator can no longer be used.
  86780. */
  86781. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_get_application_id(FLAC__Metadata_SimpleIterator *iterator, FLAC__byte *id);
  86782. /** Get the metadata block at the current position. You can modify the
  86783. * block but must use FLAC__metadata_simple_iterator_set_block() to
  86784. * write it back to the FLAC file.
  86785. *
  86786. * You must call FLAC__metadata_object_delete() on the returned object
  86787. * when you are finished with it.
  86788. *
  86789. * \param iterator A pointer to an existing initialized iterator.
  86790. * \assert
  86791. * \code iterator != NULL \endcode
  86792. * \a iterator has been successfully initialized with
  86793. * FLAC__metadata_simple_iterator_init()
  86794. * \retval FLAC__StreamMetadata*
  86795. * The current metadata block, or \c NULL if there was a memory
  86796. * allocation error.
  86797. */
  86798. FLAC_API FLAC__StreamMetadata *FLAC__metadata_simple_iterator_get_block(FLAC__Metadata_SimpleIterator *iterator);
  86799. /** Write a block back to the FLAC file. This function tries to be
  86800. * as efficient as possible; how the block is actually written is
  86801. * shown by the following:
  86802. *
  86803. * Existing block is a STREAMINFO block and the new block is a
  86804. * STREAMINFO block: the new block is written in place. Make sure
  86805. * you know what you're doing when changing the values of a
  86806. * STREAMINFO block.
  86807. *
  86808. * Existing block is a STREAMINFO block and the new block is a
  86809. * not a STREAMINFO block: this is an error since the first block
  86810. * must be a STREAMINFO block. Returns \c false without altering the
  86811. * file.
  86812. *
  86813. * Existing block is not a STREAMINFO block and the new block is a
  86814. * STREAMINFO block: this is an error since there may be only one
  86815. * STREAMINFO block. Returns \c false without altering the file.
  86816. *
  86817. * Existing block and new block are the same length: the existing
  86818. * block will be replaced by the new block, written in place.
  86819. *
  86820. * Existing block is longer than new block: if use_padding is \c true,
  86821. * the existing block will be overwritten in place with the new
  86822. * block followed by a PADDING block, if possible, to make the total
  86823. * size the same as the existing block. Remember that a padding
  86824. * block requires at least four bytes so if the difference in size
  86825. * between the new block and existing block is less than that, the
  86826. * entire file will have to be rewritten, using the new block's
  86827. * exact size. If use_padding is \c false, the entire file will be
  86828. * rewritten, replacing the existing block by the new block.
  86829. *
  86830. * Existing block is shorter than new block: if use_padding is \c true,
  86831. * the function will try and expand the new block into the following
  86832. * PADDING block, if it exists and doing so won't shrink the PADDING
  86833. * block to less than 4 bytes. If there is no following PADDING
  86834. * block, or it will shrink to less than 4 bytes, or use_padding is
  86835. * \c false, the entire file is rewritten, replacing the existing block
  86836. * with the new block. Note that in this case any following PADDING
  86837. * block is preserved as is.
  86838. *
  86839. * After writing the block, the iterator will remain in the same
  86840. * place, i.e. pointing to the new block.
  86841. *
  86842. * \param iterator A pointer to an existing initialized iterator.
  86843. * \param block The block to set.
  86844. * \param use_padding See above.
  86845. * \assert
  86846. * \code iterator != NULL \endcode
  86847. * \a iterator has been successfully initialized with
  86848. * FLAC__metadata_simple_iterator_init()
  86849. * \code block != NULL \endcode
  86850. * \retval FLAC__bool
  86851. * \c true if successful, else \c false.
  86852. */
  86853. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_set_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  86854. /** This is similar to FLAC__metadata_simple_iterator_set_block()
  86855. * except that instead of writing over an existing block, it appends
  86856. * a block after the existing block. \a use_padding is again used to
  86857. * tell the function to try an expand into following padding in an
  86858. * attempt to avoid rewriting the entire file.
  86859. *
  86860. * This function will fail and return \c false if given a STREAMINFO
  86861. * block.
  86862. *
  86863. * After writing the block, the iterator will be pointing to the
  86864. * new block.
  86865. *
  86866. * \param iterator A pointer to an existing initialized iterator.
  86867. * \param block The block to set.
  86868. * \param use_padding See above.
  86869. * \assert
  86870. * \code iterator != NULL \endcode
  86871. * \a iterator has been successfully initialized with
  86872. * FLAC__metadata_simple_iterator_init()
  86873. * \code block != NULL \endcode
  86874. * \retval FLAC__bool
  86875. * \c true if successful, else \c false.
  86876. */
  86877. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_insert_block_after(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  86878. /** Deletes the block at the current position. This will cause the
  86879. * entire FLAC file to be rewritten, unless \a use_padding is \c true,
  86880. * in which case the block will be replaced by an equal-sized PADDING
  86881. * block. The iterator will be left pointing to the block before the
  86882. * one just deleted.
  86883. *
  86884. * You may not delete the STREAMINFO block.
  86885. *
  86886. * \param iterator A pointer to an existing initialized iterator.
  86887. * \param use_padding See above.
  86888. * \assert
  86889. * \code iterator != NULL \endcode
  86890. * \a iterator has been successfully initialized with
  86891. * FLAC__metadata_simple_iterator_init()
  86892. * \retval FLAC__bool
  86893. * \c true if successful, else \c false.
  86894. */
  86895. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_delete_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__bool use_padding);
  86896. /* \} */
  86897. /** \defgroup flac_metadata_level2 FLAC/metadata.h: metadata level 2 interface
  86898. * \ingroup flac_metadata
  86899. *
  86900. * \brief
  86901. * The level 2 interface provides read-write access to FLAC file metadata;
  86902. * all metadata is read into memory, operated on in memory, and then written
  86903. * to file, which is more efficient than level 1 when editing multiple blocks.
  86904. *
  86905. * Currently Ogg FLAC is supported for read only, via
  86906. * FLAC__metadata_chain_read_ogg() but a subsequent
  86907. * FLAC__metadata_chain_write() will fail.
  86908. *
  86909. * The general usage of this interface is:
  86910. *
  86911. * - Create a new chain using FLAC__metadata_chain_new(). A chain is a
  86912. * linked list of FLAC metadata blocks.
  86913. * - Read all metadata into the the chain from a FLAC file using
  86914. * FLAC__metadata_chain_read() or FLAC__metadata_chain_read_ogg() and
  86915. * check the status.
  86916. * - Optionally, consolidate the padding using
  86917. * FLAC__metadata_chain_merge_padding() or
  86918. * FLAC__metadata_chain_sort_padding().
  86919. * - Create a new iterator using FLAC__metadata_iterator_new()
  86920. * - Initialize the iterator to point to the first element in the chain
  86921. * using FLAC__metadata_iterator_init()
  86922. * - Traverse the chain using FLAC__metadata_iterator_next and
  86923. * FLAC__metadata_iterator_prev().
  86924. * - Get a block for reading or modification using
  86925. * FLAC__metadata_iterator_get_block(). The pointer to the object
  86926. * inside the chain is returned, so the block is yours to modify.
  86927. * Changes will be reflected in the FLAC file when you write the
  86928. * chain. You can also add and delete blocks (see functions below).
  86929. * - When done, write out the chain using FLAC__metadata_chain_write().
  86930. * Make sure to read the whole comment to the function below.
  86931. * - Delete the chain using FLAC__metadata_chain_delete().
  86932. *
  86933. * \note
  86934. * Even though the FLAC file is not open while the chain is being
  86935. * manipulated, you must not alter the file externally during
  86936. * this time. The chain assumes the FLAC file will not change
  86937. * between the time of FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg()
  86938. * and FLAC__metadata_chain_write().
  86939. *
  86940. * \note
  86941. * Do not modify the is_last, length, or type fields of returned
  86942. * FLAC__StreamMetadata objects. These are managed automatically.
  86943. *
  86944. * \note
  86945. * The metadata objects returned by FLAC__metadata_iterator_get_block()
  86946. * are owned by the chain; do not FLAC__metadata_object_delete() them.
  86947. * In the same way, blocks passed to FLAC__metadata_iterator_set_block()
  86948. * become owned by the chain and they will be deleted when the chain is
  86949. * deleted.
  86950. *
  86951. * \{
  86952. */
  86953. struct FLAC__Metadata_Chain;
  86954. /** The opaque structure definition for the level 2 chain type.
  86955. */
  86956. typedef struct FLAC__Metadata_Chain FLAC__Metadata_Chain;
  86957. struct FLAC__Metadata_Iterator;
  86958. /** The opaque structure definition for the level 2 iterator type.
  86959. */
  86960. typedef struct FLAC__Metadata_Iterator FLAC__Metadata_Iterator;
  86961. typedef enum {
  86962. FLAC__METADATA_CHAIN_STATUS_OK = 0,
  86963. /**< The chain is in the normal OK state */
  86964. FLAC__METADATA_CHAIN_STATUS_ILLEGAL_INPUT,
  86965. /**< The data passed into a function violated the function's usage criteria */
  86966. FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE,
  86967. /**< The chain could not open the target file */
  86968. FLAC__METADATA_CHAIN_STATUS_NOT_A_FLAC_FILE,
  86969. /**< The chain could not find the FLAC signature at the start of the file */
  86970. FLAC__METADATA_CHAIN_STATUS_NOT_WRITABLE,
  86971. /**< The chain tried to write to a file that was not writable */
  86972. FLAC__METADATA_CHAIN_STATUS_BAD_METADATA,
  86973. /**< The chain encountered input that does not conform to the FLAC metadata specification */
  86974. FLAC__METADATA_CHAIN_STATUS_READ_ERROR,
  86975. /**< The chain encountered an error while reading the FLAC file */
  86976. FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR,
  86977. /**< The chain encountered an error while seeking in the FLAC file */
  86978. FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR,
  86979. /**< The chain encountered an error while writing the FLAC file */
  86980. FLAC__METADATA_CHAIN_STATUS_RENAME_ERROR,
  86981. /**< The chain encountered an error renaming the FLAC file */
  86982. FLAC__METADATA_CHAIN_STATUS_UNLINK_ERROR,
  86983. /**< The chain encountered an error removing the temporary file */
  86984. FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR,
  86985. /**< Memory allocation failed */
  86986. FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR,
  86987. /**< The caller violated an assertion or an unexpected error occurred */
  86988. FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS,
  86989. /**< One or more of the required callbacks was NULL */
  86990. FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH,
  86991. /**< FLAC__metadata_chain_write() was called on a chain read by
  86992. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  86993. * or
  86994. * FLAC__metadata_chain_write_with_callbacks()/FLAC__metadata_chain_write_with_callbacks_and_tempfile()
  86995. * was called on a chain read by
  86996. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  86997. * Matching read/write methods must always be used. */
  86998. FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL
  86999. /**< FLAC__metadata_chain_write_with_callbacks() was called when the
  87000. * chain write requires a tempfile; use
  87001. * FLAC__metadata_chain_write_with_callbacks_and_tempfile() instead.
  87002. * Or, FLAC__metadata_chain_write_with_callbacks_and_tempfile() was
  87003. * called when the chain write does not require a tempfile; use
  87004. * FLAC__metadata_chain_write_with_callbacks() instead.
  87005. * Always check FLAC__metadata_chain_check_if_tempfile_needed()
  87006. * before writing via callbacks. */
  87007. } FLAC__Metadata_ChainStatus;
  87008. /** Maps a FLAC__Metadata_ChainStatus to a C string.
  87009. *
  87010. * Using a FLAC__Metadata_ChainStatus as the index to this array
  87011. * will give the string equivalent. The contents should not be modified.
  87012. */
  87013. extern FLAC_API const char * const FLAC__Metadata_ChainStatusString[];
  87014. /*********** FLAC__Metadata_Chain ***********/
  87015. /** Create a new chain instance.
  87016. *
  87017. * \retval FLAC__Metadata_Chain*
  87018. * \c NULL if there was an error allocating memory, else the new instance.
  87019. */
  87020. FLAC_API FLAC__Metadata_Chain *FLAC__metadata_chain_new(void);
  87021. /** Free a chain instance. Deletes the object pointed to by \a chain.
  87022. *
  87023. * \param chain A pointer to an existing chain.
  87024. * \assert
  87025. * \code chain != NULL \endcode
  87026. */
  87027. FLAC_API void FLAC__metadata_chain_delete(FLAC__Metadata_Chain *chain);
  87028. /** Get the current status of the chain. Call this after a function
  87029. * returns \c false to get the reason for the error. Also resets the
  87030. * status to FLAC__METADATA_CHAIN_STATUS_OK.
  87031. *
  87032. * \param chain A pointer to an existing chain.
  87033. * \assert
  87034. * \code chain != NULL \endcode
  87035. * \retval FLAC__Metadata_ChainStatus
  87036. * The current status of the chain.
  87037. */
  87038. FLAC_API FLAC__Metadata_ChainStatus FLAC__metadata_chain_status(FLAC__Metadata_Chain *chain);
  87039. /** Read all metadata from a FLAC file into the chain.
  87040. *
  87041. * \param chain A pointer to an existing chain.
  87042. * \param filename The path to the FLAC file to read.
  87043. * \assert
  87044. * \code chain != NULL \endcode
  87045. * \code filename != NULL \endcode
  87046. * \retval FLAC__bool
  87047. * \c true if a valid list of metadata blocks was read from
  87048. * \a filename, else \c false. On failure, check the status with
  87049. * FLAC__metadata_chain_status().
  87050. */
  87051. FLAC_API FLAC__bool FLAC__metadata_chain_read(FLAC__Metadata_Chain *chain, const char *filename);
  87052. /** Read all metadata from an Ogg FLAC file into the chain.
  87053. *
  87054. * \note Ogg FLAC metadata data writing is not supported yet and
  87055. * FLAC__metadata_chain_write() will fail.
  87056. *
  87057. * \param chain A pointer to an existing chain.
  87058. * \param filename The path to the Ogg FLAC file to read.
  87059. * \assert
  87060. * \code chain != NULL \endcode
  87061. * \code filename != NULL \endcode
  87062. * \retval FLAC__bool
  87063. * \c true if a valid list of metadata blocks was read from
  87064. * \a filename, else \c false. On failure, check the status with
  87065. * FLAC__metadata_chain_status().
  87066. */
  87067. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg(FLAC__Metadata_Chain *chain, const char *filename);
  87068. /** Read all metadata from a FLAC stream into the chain via I/O callbacks.
  87069. *
  87070. * The \a handle need only be open for reading, but must be seekable.
  87071. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  87072. * for Windows).
  87073. *
  87074. * \param chain A pointer to an existing chain.
  87075. * \param handle The I/O handle of the FLAC stream to read. The
  87076. * handle will NOT be closed after the metadata is read;
  87077. * that is the duty of the caller.
  87078. * \param callbacks
  87079. * A set of callbacks to use for I/O. The mandatory
  87080. * callbacks are \a read, \a seek, and \a tell.
  87081. * \assert
  87082. * \code chain != NULL \endcode
  87083. * \retval FLAC__bool
  87084. * \c true if a valid list of metadata blocks was read from
  87085. * \a handle, else \c false. On failure, check the status with
  87086. * FLAC__metadata_chain_status().
  87087. */
  87088. FLAC_API FLAC__bool FLAC__metadata_chain_read_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  87089. /** Read all metadata from an Ogg FLAC stream into the chain via I/O callbacks.
  87090. *
  87091. * The \a handle need only be open for reading, but must be seekable.
  87092. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  87093. * for Windows).
  87094. *
  87095. * \note Ogg FLAC metadata data writing is not supported yet and
  87096. * FLAC__metadata_chain_write() will fail.
  87097. *
  87098. * \param chain A pointer to an existing chain.
  87099. * \param handle The I/O handle of the Ogg FLAC stream to read. The
  87100. * handle will NOT be closed after the metadata is read;
  87101. * that is the duty of the caller.
  87102. * \param callbacks
  87103. * A set of callbacks to use for I/O. The mandatory
  87104. * callbacks are \a read, \a seek, and \a tell.
  87105. * \assert
  87106. * \code chain != NULL \endcode
  87107. * \retval FLAC__bool
  87108. * \c true if a valid list of metadata blocks was read from
  87109. * \a handle, else \c false. On failure, check the status with
  87110. * FLAC__metadata_chain_status().
  87111. */
  87112. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  87113. /** Checks if writing the given chain would require the use of a
  87114. * temporary file, or if it could be written in place.
  87115. *
  87116. * Under certain conditions, padding can be utilized so that writing
  87117. * edited metadata back to the FLAC file does not require rewriting the
  87118. * entire file. If rewriting is required, then a temporary workfile is
  87119. * required. When writing metadata using callbacks, you must check
  87120. * this function to know whether to call
  87121. * FLAC__metadata_chain_write_with_callbacks() or
  87122. * FLAC__metadata_chain_write_with_callbacks_and_tempfile(). When
  87123. * writing with FLAC__metadata_chain_write(), the temporary file is
  87124. * handled internally.
  87125. *
  87126. * \param chain A pointer to an existing chain.
  87127. * \param use_padding
  87128. * Whether or not padding will be allowed to be used
  87129. * during the write. The value of \a use_padding given
  87130. * here must match the value later passed to
  87131. * FLAC__metadata_chain_write_with_callbacks() or
  87132. * FLAC__metadata_chain_write_with_callbacks_with_tempfile().
  87133. * \assert
  87134. * \code chain != NULL \endcode
  87135. * \retval FLAC__bool
  87136. * \c true if writing the current chain would require a tempfile, or
  87137. * \c false if metadata can be written in place.
  87138. */
  87139. FLAC_API FLAC__bool FLAC__metadata_chain_check_if_tempfile_needed(FLAC__Metadata_Chain *chain, FLAC__bool use_padding);
  87140. /** Write all metadata out to the FLAC file. This function tries to be as
  87141. * efficient as possible; how the metadata is actually written is shown by
  87142. * the following:
  87143. *
  87144. * If the current chain is the same size as the existing metadata, the new
  87145. * data is written in place.
  87146. *
  87147. * If the current chain is longer than the existing metadata, and
  87148. * \a use_padding is \c true, and the last block is a PADDING block of
  87149. * sufficient length, the function will truncate the final padding block
  87150. * so that the overall size of the metadata is the same as the existing
  87151. * metadata, and then just rewrite the metadata. Otherwise, if not all of
  87152. * the above conditions are met, the entire FLAC file must be rewritten.
  87153. * If you want to use padding this way it is a good idea to call
  87154. * FLAC__metadata_chain_sort_padding() first so that you have the maximum
  87155. * amount of padding to work with, unless you need to preserve ordering
  87156. * of the PADDING blocks for some reason.
  87157. *
  87158. * If the current chain is shorter than the existing metadata, and
  87159. * \a use_padding is \c true, and the final block is a PADDING block, the padding
  87160. * is extended to make the overall size the same as the existing data. If
  87161. * \a use_padding is \c true and the last block is not a PADDING block, a new
  87162. * PADDING block is added to the end of the new data to make it the same
  87163. * size as the existing data (if possible, see the note to
  87164. * FLAC__metadata_simple_iterator_set_block() about the four byte limit)
  87165. * and the new data is written in place. If none of the above apply or
  87166. * \a use_padding is \c false, the entire FLAC file is rewritten.
  87167. *
  87168. * If \a preserve_file_stats is \c true, the owner and modification time will
  87169. * be preserved even if the FLAC file is written.
  87170. *
  87171. * For this write function to be used, the chain must have been read with
  87172. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg(), not
  87173. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks().
  87174. *
  87175. * \param chain A pointer to an existing chain.
  87176. * \param use_padding See above.
  87177. * \param preserve_file_stats See above.
  87178. * \assert
  87179. * \code chain != NULL \endcode
  87180. * \retval FLAC__bool
  87181. * \c true if the write succeeded, else \c false. On failure,
  87182. * check the status with FLAC__metadata_chain_status().
  87183. */
  87184. FLAC_API FLAC__bool FLAC__metadata_chain_write(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__bool preserve_file_stats);
  87185. /** Write all metadata out to a FLAC stream via callbacks.
  87186. *
  87187. * (See FLAC__metadata_chain_write() for the details on how padding is
  87188. * used to write metadata in place if possible.)
  87189. *
  87190. * The \a handle must be open for updating and be seekable. The
  87191. * equivalent minimum stdio fopen() file mode is \c "r+" (or \c "r+b"
  87192. * for Windows).
  87193. *
  87194. * For this write function to be used, the chain must have been read with
  87195. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  87196. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  87197. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  87198. * \c false.
  87199. *
  87200. * \param chain A pointer to an existing chain.
  87201. * \param use_padding See FLAC__metadata_chain_write()
  87202. * \param handle The I/O handle of the FLAC stream to write. The
  87203. * handle will NOT be closed after the metadata is
  87204. * written; that is the duty of the caller.
  87205. * \param callbacks A set of callbacks to use for I/O. The mandatory
  87206. * callbacks are \a write and \a seek.
  87207. * \assert
  87208. * \code chain != NULL \endcode
  87209. * \retval FLAC__bool
  87210. * \c true if the write succeeded, else \c false. On failure,
  87211. * check the status with FLAC__metadata_chain_status().
  87212. */
  87213. FLAC_API FLAC__bool FLAC__metadata_chain_write_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  87214. /** Write all metadata out to a FLAC stream via callbacks.
  87215. *
  87216. * (See FLAC__metadata_chain_write() for the details on how padding is
  87217. * used to write metadata in place if possible.)
  87218. *
  87219. * This version of the write-with-callbacks function must be used when
  87220. * FLAC__metadata_chain_check_if_tempfile_needed() returns true. In
  87221. * this function, you must supply an I/O handle corresponding to the
  87222. * FLAC file to edit, and a temporary handle to which the new FLAC
  87223. * file will be written. It is the caller's job to move this temporary
  87224. * FLAC file on top of the original FLAC file to complete the metadata
  87225. * edit.
  87226. *
  87227. * The \a handle must be open for reading and be seekable. The
  87228. * equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  87229. * for Windows).
  87230. *
  87231. * The \a temp_handle must be open for writing. The
  87232. * equivalent minimum stdio fopen() file mode is \c "w" (or \c "wb"
  87233. * for Windows). It should be an empty stream, or at least positioned
  87234. * at the start-of-file (in which case it is the caller's duty to
  87235. * truncate it on return).
  87236. *
  87237. * For this write function to be used, the chain must have been read with
  87238. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  87239. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  87240. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  87241. * \c true.
  87242. *
  87243. * \param chain A pointer to an existing chain.
  87244. * \param use_padding See FLAC__metadata_chain_write()
  87245. * \param handle The I/O handle of the original FLAC stream to read.
  87246. * The handle will NOT be closed after the metadata is
  87247. * written; that is the duty of the caller.
  87248. * \param callbacks A set of callbacks to use for I/O on \a handle.
  87249. * The mandatory callbacks are \a read, \a seek, and
  87250. * \a eof.
  87251. * \param temp_handle The I/O handle of the FLAC stream to write. The
  87252. * handle will NOT be closed after the metadata is
  87253. * written; that is the duty of the caller.
  87254. * \param temp_callbacks
  87255. * A set of callbacks to use for I/O on temp_handle.
  87256. * The only mandatory callback is \a write.
  87257. * \assert
  87258. * \code chain != NULL \endcode
  87259. * \retval FLAC__bool
  87260. * \c true if the write succeeded, else \c false. On failure,
  87261. * check the status with FLAC__metadata_chain_status().
  87262. */
  87263. 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);
  87264. /** Merge adjacent PADDING blocks into a single block.
  87265. *
  87266. * \note This function does not write to the FLAC file, it only
  87267. * modifies the chain.
  87268. *
  87269. * \warning Any iterator on the current chain will become invalid after this
  87270. * call. You should delete the iterator and get a new one.
  87271. *
  87272. * \param chain A pointer to an existing chain.
  87273. * \assert
  87274. * \code chain != NULL \endcode
  87275. */
  87276. FLAC_API void FLAC__metadata_chain_merge_padding(FLAC__Metadata_Chain *chain);
  87277. /** This function will move all PADDING blocks to the end on the metadata,
  87278. * then merge them into a single block.
  87279. *
  87280. * \note This function does not write to the FLAC file, it only
  87281. * modifies the chain.
  87282. *
  87283. * \warning Any iterator on the current chain will become invalid after this
  87284. * call. You should delete the iterator and get a new one.
  87285. *
  87286. * \param chain A pointer to an existing chain.
  87287. * \assert
  87288. * \code chain != NULL \endcode
  87289. */
  87290. FLAC_API void FLAC__metadata_chain_sort_padding(FLAC__Metadata_Chain *chain);
  87291. /*********** FLAC__Metadata_Iterator ***********/
  87292. /** Create a new iterator instance.
  87293. *
  87294. * \retval FLAC__Metadata_Iterator*
  87295. * \c NULL if there was an error allocating memory, else the new instance.
  87296. */
  87297. FLAC_API FLAC__Metadata_Iterator *FLAC__metadata_iterator_new(void);
  87298. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  87299. *
  87300. * \param iterator A pointer to an existing iterator.
  87301. * \assert
  87302. * \code iterator != NULL \endcode
  87303. */
  87304. FLAC_API void FLAC__metadata_iterator_delete(FLAC__Metadata_Iterator *iterator);
  87305. /** Initialize the iterator to point to the first metadata block in the
  87306. * given chain.
  87307. *
  87308. * \param iterator A pointer to an existing iterator.
  87309. * \param chain A pointer to an existing and initialized (read) chain.
  87310. * \assert
  87311. * \code iterator != NULL \endcode
  87312. * \code chain != NULL \endcode
  87313. */
  87314. FLAC_API void FLAC__metadata_iterator_init(FLAC__Metadata_Iterator *iterator, FLAC__Metadata_Chain *chain);
  87315. /** Moves the iterator forward one metadata block, returning \c false if
  87316. * already at the end.
  87317. *
  87318. * \param iterator A pointer to an existing initialized iterator.
  87319. * \assert
  87320. * \code iterator != NULL \endcode
  87321. * \a iterator has been successfully initialized with
  87322. * FLAC__metadata_iterator_init()
  87323. * \retval FLAC__bool
  87324. * \c false if already at the last metadata block of the chain, else
  87325. * \c true.
  87326. */
  87327. FLAC_API FLAC__bool FLAC__metadata_iterator_next(FLAC__Metadata_Iterator *iterator);
  87328. /** Moves the iterator backward one metadata block, returning \c false if
  87329. * already at the beginning.
  87330. *
  87331. * \param iterator A pointer to an existing initialized iterator.
  87332. * \assert
  87333. * \code iterator != NULL \endcode
  87334. * \a iterator has been successfully initialized with
  87335. * FLAC__metadata_iterator_init()
  87336. * \retval FLAC__bool
  87337. * \c false if already at the first metadata block of the chain, else
  87338. * \c true.
  87339. */
  87340. FLAC_API FLAC__bool FLAC__metadata_iterator_prev(FLAC__Metadata_Iterator *iterator);
  87341. /** Get the type of the metadata block at the current position.
  87342. *
  87343. * \param iterator A pointer to an existing initialized iterator.
  87344. * \assert
  87345. * \code iterator != NULL \endcode
  87346. * \a iterator has been successfully initialized with
  87347. * FLAC__metadata_iterator_init()
  87348. * \retval FLAC__MetadataType
  87349. * The type of the metadata block at the current iterator position.
  87350. */
  87351. FLAC_API FLAC__MetadataType FLAC__metadata_iterator_get_block_type(const FLAC__Metadata_Iterator *iterator);
  87352. /** Get the metadata block at the current position. You can modify
  87353. * the block in place but must write the chain before the changes
  87354. * are reflected to the FLAC file. You do not need to call
  87355. * FLAC__metadata_iterator_set_block() to reflect the changes;
  87356. * the pointer returned by FLAC__metadata_iterator_get_block()
  87357. * points directly into the chain.
  87358. *
  87359. * \warning
  87360. * Do not call FLAC__metadata_object_delete() on the returned object;
  87361. * to delete a block use FLAC__metadata_iterator_delete_block().
  87362. *
  87363. * \param iterator A pointer to an existing initialized iterator.
  87364. * \assert
  87365. * \code iterator != NULL \endcode
  87366. * \a iterator has been successfully initialized with
  87367. * FLAC__metadata_iterator_init()
  87368. * \retval FLAC__StreamMetadata*
  87369. * The current metadata block.
  87370. */
  87371. FLAC_API FLAC__StreamMetadata *FLAC__metadata_iterator_get_block(FLAC__Metadata_Iterator *iterator);
  87372. /** Set the metadata block at the current position, replacing the existing
  87373. * block. The new block passed in becomes owned by the chain and it will be
  87374. * deleted when the chain is deleted.
  87375. *
  87376. * \param iterator A pointer to an existing initialized iterator.
  87377. * \param block A pointer to a metadata block.
  87378. * \assert
  87379. * \code iterator != NULL \endcode
  87380. * \a iterator has been successfully initialized with
  87381. * FLAC__metadata_iterator_init()
  87382. * \code block != NULL \endcode
  87383. * \retval FLAC__bool
  87384. * \c false if the conditions in the above description are not met, or
  87385. * a memory allocation error occurs, otherwise \c true.
  87386. */
  87387. FLAC_API FLAC__bool FLAC__metadata_iterator_set_block(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  87388. /** Removes the current block from the chain. If \a replace_with_padding is
  87389. * \c true, the block will instead be replaced with a padding block of equal
  87390. * size. You can not delete the STREAMINFO block. The iterator will be
  87391. * left pointing to the block before the one just "deleted", even if
  87392. * \a replace_with_padding is \c true.
  87393. *
  87394. * \param iterator A pointer to an existing initialized iterator.
  87395. * \param replace_with_padding See above.
  87396. * \assert
  87397. * \code iterator != NULL \endcode
  87398. * \a iterator has been successfully initialized with
  87399. * FLAC__metadata_iterator_init()
  87400. * \retval FLAC__bool
  87401. * \c false if the conditions in the above description are not met,
  87402. * otherwise \c true.
  87403. */
  87404. FLAC_API FLAC__bool FLAC__metadata_iterator_delete_block(FLAC__Metadata_Iterator *iterator, FLAC__bool replace_with_padding);
  87405. /** Insert a new block before the current block. You cannot insert a block
  87406. * before the first STREAMINFO block. You cannot insert a STREAMINFO block
  87407. * as there can be only one, the one that already exists at the head when you
  87408. * read in a chain. The chain takes ownership of the new block and it will be
  87409. * deleted when the chain is deleted. The iterator will be left pointing to
  87410. * the new block.
  87411. *
  87412. * \param iterator A pointer to an existing initialized iterator.
  87413. * \param block A pointer to a metadata block to insert.
  87414. * \assert
  87415. * \code iterator != NULL \endcode
  87416. * \a iterator has been successfully initialized with
  87417. * FLAC__metadata_iterator_init()
  87418. * \retval FLAC__bool
  87419. * \c false if the conditions in the above description are not met, or
  87420. * a memory allocation error occurs, otherwise \c true.
  87421. */
  87422. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_before(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  87423. /** Insert a new block after the current block. You cannot insert a STREAMINFO
  87424. * block as there can be only one, the one that already exists at the head when
  87425. * you read in a chain. The chain takes ownership of the new block and it will
  87426. * be deleted when the chain is deleted. The iterator will be left pointing to
  87427. * the new block.
  87428. *
  87429. * \param iterator A pointer to an existing initialized iterator.
  87430. * \param block A pointer to a metadata block to insert.
  87431. * \assert
  87432. * \code iterator != NULL \endcode
  87433. * \a iterator has been successfully initialized with
  87434. * FLAC__metadata_iterator_init()
  87435. * \retval FLAC__bool
  87436. * \c false if the conditions in the above description are not met, or
  87437. * a memory allocation error occurs, otherwise \c true.
  87438. */
  87439. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_after(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  87440. /* \} */
  87441. /** \defgroup flac_metadata_object FLAC/metadata.h: metadata object methods
  87442. * \ingroup flac_metadata
  87443. *
  87444. * \brief
  87445. * This module contains methods for manipulating FLAC metadata objects.
  87446. *
  87447. * Since many are variable length we have to be careful about the memory
  87448. * management. We decree that all pointers to data in the object are
  87449. * owned by the object and memory-managed by the object.
  87450. *
  87451. * Use the FLAC__metadata_object_new() and FLAC__metadata_object_delete()
  87452. * functions to create all instances. When using the
  87453. * FLAC__metadata_object_set_*() functions to set pointers to data, set
  87454. * \a copy to \c true to have the function make it's own copy of the data, or
  87455. * to \c false to give the object ownership of your data. In the latter case
  87456. * your pointer must be freeable by free() and will be free()d when the object
  87457. * is FLAC__metadata_object_delete()d. It is legal to pass a null pointer as
  87458. * the data pointer to a FLAC__metadata_object_set_*() function as long as
  87459. * the length argument is 0 and the \a copy argument is \c false.
  87460. *
  87461. * The FLAC__metadata_object_new() and FLAC__metadata_object_clone() function
  87462. * will return \c NULL in the case of a memory allocation error, otherwise a new
  87463. * object. The FLAC__metadata_object_set_*() functions return \c false in the
  87464. * case of a memory allocation error.
  87465. *
  87466. * We don't have the convenience of C++ here, so note that the library relies
  87467. * on you to keep the types straight. In other words, if you pass, for
  87468. * example, a FLAC__StreamMetadata* that represents a STREAMINFO block to
  87469. * FLAC__metadata_object_application_set_data(), you will get an assertion
  87470. * failure.
  87471. *
  87472. * For convenience the FLAC__metadata_object_vorbiscomment_*() functions
  87473. * maintain a trailing NUL on each Vorbis comment entry. This is not counted
  87474. * toward the length or stored in the stream, but it can make working with plain
  87475. * comments (those that don't contain embedded-NULs in the value) easier.
  87476. * Entries passed into these functions have trailing NULs added if missing, and
  87477. * returned entries are guaranteed to have a trailing NUL.
  87478. *
  87479. * The FLAC__metadata_object_vorbiscomment_*() functions that take a Vorbis
  87480. * comment entry/name/value will first validate that it complies with the Vorbis
  87481. * comment specification and return false if it does not.
  87482. *
  87483. * There is no need to recalculate the length field on metadata blocks you
  87484. * have modified. They will be calculated automatically before they are
  87485. * written back to a file.
  87486. *
  87487. * \{
  87488. */
  87489. /** Create a new metadata object instance of the given type.
  87490. *
  87491. * The object will be "empty"; i.e. values and data pointers will be \c 0,
  87492. * with the exception of FLAC__METADATA_TYPE_VORBIS_COMMENT, which will have
  87493. * the vendor string set (but zero comments).
  87494. *
  87495. * Do not pass in a value greater than or equal to
  87496. * \a FLAC__METADATA_TYPE_UNDEFINED unless you really know what you're
  87497. * doing.
  87498. *
  87499. * \param type Type of object to create
  87500. * \retval FLAC__StreamMetadata*
  87501. * \c NULL if there was an error allocating memory or the type code is
  87502. * greater than FLAC__MAX_METADATA_TYPE_CODE, else the new instance.
  87503. */
  87504. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_new(FLAC__MetadataType type);
  87505. /** Create a copy of an existing metadata object.
  87506. *
  87507. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  87508. * object is also copied. The caller takes ownership of the new block and
  87509. * is responsible for freeing it with FLAC__metadata_object_delete().
  87510. *
  87511. * \param object Pointer to object to copy.
  87512. * \assert
  87513. * \code object != NULL \endcode
  87514. * \retval FLAC__StreamMetadata*
  87515. * \c NULL if there was an error allocating memory, else the new instance.
  87516. */
  87517. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_clone(const FLAC__StreamMetadata *object);
  87518. /** Free a metadata object. Deletes the object pointed to by \a object.
  87519. *
  87520. * The delete is a "deep" delete, i.e. dynamically allocated data within the
  87521. * object is also deleted.
  87522. *
  87523. * \param object A pointer to an existing object.
  87524. * \assert
  87525. * \code object != NULL \endcode
  87526. */
  87527. FLAC_API void FLAC__metadata_object_delete(FLAC__StreamMetadata *object);
  87528. /** Compares two metadata objects.
  87529. *
  87530. * The compare is "deep", i.e. dynamically allocated data within the
  87531. * object is also compared.
  87532. *
  87533. * \param block1 A pointer to an existing object.
  87534. * \param block2 A pointer to an existing object.
  87535. * \assert
  87536. * \code block1 != NULL \endcode
  87537. * \code block2 != NULL \endcode
  87538. * \retval FLAC__bool
  87539. * \c true if objects are identical, else \c false.
  87540. */
  87541. FLAC_API FLAC__bool FLAC__metadata_object_is_equal(const FLAC__StreamMetadata *block1, const FLAC__StreamMetadata *block2);
  87542. /** Sets the application data of an APPLICATION block.
  87543. *
  87544. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  87545. * takes ownership of the pointer. The existing data will be freed if this
  87546. * function is successful, otherwise the original data will remain if \a copy
  87547. * is \c true and malloc() fails.
  87548. *
  87549. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  87550. *
  87551. * \param object A pointer to an existing APPLICATION object.
  87552. * \param data A pointer to the data to set.
  87553. * \param length The length of \a data in bytes.
  87554. * \param copy See above.
  87555. * \assert
  87556. * \code object != NULL \endcode
  87557. * \code object->type == FLAC__METADATA_TYPE_APPLICATION \endcode
  87558. * \code (data != NULL && length > 0) ||
  87559. * (data == NULL && length == 0 && copy == false) \endcode
  87560. * \retval FLAC__bool
  87561. * \c false if \a copy is \c true and malloc() fails, else \c true.
  87562. */
  87563. FLAC_API FLAC__bool FLAC__metadata_object_application_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, unsigned length, FLAC__bool copy);
  87564. /** Resize the seekpoint array.
  87565. *
  87566. * If the size shrinks, elements will truncated; if it grows, new placeholder
  87567. * points will be added to the end.
  87568. *
  87569. * \param object A pointer to an existing SEEKTABLE object.
  87570. * \param new_num_points The desired length of the array; may be \c 0.
  87571. * \assert
  87572. * \code object != NULL \endcode
  87573. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  87574. * \code (object->data.seek_table.points == NULL && object->data.seek_table.num_points == 0) ||
  87575. * (object->data.seek_table.points != NULL && object->data.seek_table.num_points > 0) \endcode
  87576. * \retval FLAC__bool
  87577. * \c false if memory allocation error, else \c true.
  87578. */
  87579. FLAC_API FLAC__bool FLAC__metadata_object_seektable_resize_points(FLAC__StreamMetadata *object, unsigned new_num_points);
  87580. /** Set a seekpoint in a seektable.
  87581. *
  87582. * \param object A pointer to an existing SEEKTABLE object.
  87583. * \param point_num Index into seekpoint array to set.
  87584. * \param point The point to set.
  87585. * \assert
  87586. * \code object != NULL \endcode
  87587. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  87588. * \code object->data.seek_table.num_points > point_num \endcode
  87589. */
  87590. FLAC_API void FLAC__metadata_object_seektable_set_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  87591. /** Insert a seekpoint into a seektable.
  87592. *
  87593. * \param object A pointer to an existing SEEKTABLE object.
  87594. * \param point_num Index into seekpoint array to set.
  87595. * \param point The point to set.
  87596. * \assert
  87597. * \code object != NULL \endcode
  87598. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  87599. * \code object->data.seek_table.num_points >= point_num \endcode
  87600. * \retval FLAC__bool
  87601. * \c false if memory allocation error, else \c true.
  87602. */
  87603. FLAC_API FLAC__bool FLAC__metadata_object_seektable_insert_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  87604. /** Delete a seekpoint from a seektable.
  87605. *
  87606. * \param object A pointer to an existing SEEKTABLE object.
  87607. * \param point_num Index into seekpoint array to set.
  87608. * \assert
  87609. * \code object != NULL \endcode
  87610. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  87611. * \code object->data.seek_table.num_points > point_num \endcode
  87612. * \retval FLAC__bool
  87613. * \c false if memory allocation error, else \c true.
  87614. */
  87615. FLAC_API FLAC__bool FLAC__metadata_object_seektable_delete_point(FLAC__StreamMetadata *object, unsigned point_num);
  87616. /** Check a seektable to see if it conforms to the FLAC specification.
  87617. * See the format specification for limits on the contents of the
  87618. * seektable.
  87619. *
  87620. * \param object A pointer to an existing SEEKTABLE object.
  87621. * \assert
  87622. * \code object != NULL \endcode
  87623. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  87624. * \retval FLAC__bool
  87625. * \c false if seek table is illegal, else \c true.
  87626. */
  87627. FLAC_API FLAC__bool FLAC__metadata_object_seektable_is_legal(const FLAC__StreamMetadata *object);
  87628. /** Append a number of placeholder points to the end of a seek table.
  87629. *
  87630. * \note
  87631. * As with the other ..._seektable_template_... functions, you should
  87632. * call FLAC__metadata_object_seektable_template_sort() when finished
  87633. * to make the seek table legal.
  87634. *
  87635. * \param object A pointer to an existing SEEKTABLE object.
  87636. * \param num The number of placeholder points to append.
  87637. * \assert
  87638. * \code object != NULL \endcode
  87639. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  87640. * \retval FLAC__bool
  87641. * \c false if memory allocation fails, else \c true.
  87642. */
  87643. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_placeholders(FLAC__StreamMetadata *object, unsigned num);
  87644. /** Append a specific seek point template to the end of a seek table.
  87645. *
  87646. * \note
  87647. * As with the other ..._seektable_template_... functions, you should
  87648. * call FLAC__metadata_object_seektable_template_sort() when finished
  87649. * to make the seek table legal.
  87650. *
  87651. * \param object A pointer to an existing SEEKTABLE object.
  87652. * \param sample_number The sample number of the seek point template.
  87653. * \assert
  87654. * \code object != NULL \endcode
  87655. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  87656. * \retval FLAC__bool
  87657. * \c false if memory allocation fails, else \c true.
  87658. */
  87659. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_point(FLAC__StreamMetadata *object, FLAC__uint64 sample_number);
  87660. /** Append specific seek point templates to the end of a seek table.
  87661. *
  87662. * \note
  87663. * As with the other ..._seektable_template_... functions, you should
  87664. * call FLAC__metadata_object_seektable_template_sort() when finished
  87665. * to make the seek table legal.
  87666. *
  87667. * \param object A pointer to an existing SEEKTABLE object.
  87668. * \param sample_numbers An array of sample numbers for the seek points.
  87669. * \param num The number of seek point templates to append.
  87670. * \assert
  87671. * \code object != NULL \endcode
  87672. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  87673. * \retval FLAC__bool
  87674. * \c false if memory allocation fails, else \c true.
  87675. */
  87676. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_points(FLAC__StreamMetadata *object, FLAC__uint64 sample_numbers[], unsigned num);
  87677. /** Append a set of evenly-spaced seek point templates to the end of a
  87678. * seek table.
  87679. *
  87680. * \note
  87681. * As with the other ..._seektable_template_... functions, you should
  87682. * call FLAC__metadata_object_seektable_template_sort() when finished
  87683. * to make the seek table legal.
  87684. *
  87685. * \param object A pointer to an existing SEEKTABLE object.
  87686. * \param num The number of placeholder points to append.
  87687. * \param total_samples The total number of samples to be encoded;
  87688. * the seekpoints will be spaced approximately
  87689. * \a total_samples / \a num samples apart.
  87690. * \assert
  87691. * \code object != NULL \endcode
  87692. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  87693. * \code total_samples > 0 \endcode
  87694. * \retval FLAC__bool
  87695. * \c false if memory allocation fails, else \c true.
  87696. */
  87697. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points(FLAC__StreamMetadata *object, unsigned num, FLAC__uint64 total_samples);
  87698. /** Append a set of evenly-spaced seek point templates to the end of a
  87699. * seek table.
  87700. *
  87701. * \note
  87702. * As with the other ..._seektable_template_... functions, you should
  87703. * call FLAC__metadata_object_seektable_template_sort() when finished
  87704. * to make the seek table legal.
  87705. *
  87706. * \param object A pointer to an existing SEEKTABLE object.
  87707. * \param samples The number of samples apart to space the placeholder
  87708. * points. The first point will be at sample \c 0, the
  87709. * second at sample \a samples, then 2*\a samples, and
  87710. * so on. As long as \a samples and \a total_samples
  87711. * are greater than \c 0, there will always be at least
  87712. * one seekpoint at sample \c 0.
  87713. * \param total_samples The total number of samples to be encoded;
  87714. * the seekpoints will be spaced
  87715. * \a samples samples apart.
  87716. * \assert
  87717. * \code object != NULL \endcode
  87718. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  87719. * \code samples > 0 \endcode
  87720. * \code total_samples > 0 \endcode
  87721. * \retval FLAC__bool
  87722. * \c false if memory allocation fails, else \c true.
  87723. */
  87724. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points_by_samples(FLAC__StreamMetadata *object, unsigned samples, FLAC__uint64 total_samples);
  87725. /** Sort a seek table's seek points according to the format specification,
  87726. * removing duplicates.
  87727. *
  87728. * \param object A pointer to a seek table to be sorted.
  87729. * \param compact If \c false, behaves like FLAC__format_seektable_sort().
  87730. * If \c true, duplicates are deleted and the seek table is
  87731. * shrunk appropriately; the number of placeholder points
  87732. * present in the seek table will be the same after the call
  87733. * as before.
  87734. * \assert
  87735. * \code object != NULL \endcode
  87736. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  87737. * \retval FLAC__bool
  87738. * \c false if realloc() fails, else \c true.
  87739. */
  87740. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_sort(FLAC__StreamMetadata *object, FLAC__bool compact);
  87741. /** Sets the vendor string in a VORBIS_COMMENT block.
  87742. *
  87743. * For convenience, a trailing NUL is added to the entry if it doesn't have
  87744. * one already.
  87745. *
  87746. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  87747. * takes ownership of the \c entry.entry pointer.
  87748. *
  87749. * \note If this function returns \c false, the caller still owns the
  87750. * pointer.
  87751. *
  87752. * \param object A pointer to an existing VORBIS_COMMENT object.
  87753. * \param entry The entry to set the vendor string to.
  87754. * \param copy See above.
  87755. * \assert
  87756. * \code object != NULL \endcode
  87757. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  87758. * \code (entry.entry != NULL && entry.length > 0) ||
  87759. * (entry.entry == NULL && entry.length == 0) \endcode
  87760. * \retval FLAC__bool
  87761. * \c false if memory allocation fails or \a entry does not comply with the
  87762. * Vorbis comment specification, else \c true.
  87763. */
  87764. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_vendor_string(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  87765. /** Resize the comment array.
  87766. *
  87767. * If the size shrinks, elements will truncated; if it grows, new empty
  87768. * fields will be added to the end.
  87769. *
  87770. * \param object A pointer to an existing VORBIS_COMMENT object.
  87771. * \param new_num_comments The desired length of the array; may be \c 0.
  87772. * \assert
  87773. * \code object != NULL \endcode
  87774. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  87775. * \code (object->data.vorbis_comment.comments == NULL && object->data.vorbis_comment.num_comments == 0) ||
  87776. * (object->data.vorbis_comment.comments != NULL && object->data.vorbis_comment.num_comments > 0) \endcode
  87777. * \retval FLAC__bool
  87778. * \c false if memory allocation fails, else \c true.
  87779. */
  87780. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_resize_comments(FLAC__StreamMetadata *object, unsigned new_num_comments);
  87781. /** Sets a comment in a VORBIS_COMMENT block.
  87782. *
  87783. * For convenience, a trailing NUL is added to the entry if it doesn't have
  87784. * one already.
  87785. *
  87786. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  87787. * takes ownership of the \c entry.entry pointer.
  87788. *
  87789. * \note If this function returns \c false, the caller still owns the
  87790. * pointer.
  87791. *
  87792. * \param object A pointer to an existing VORBIS_COMMENT object.
  87793. * \param comment_num Index into comment array to set.
  87794. * \param entry The entry to set the comment to.
  87795. * \param copy See above.
  87796. * \assert
  87797. * \code object != NULL \endcode
  87798. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  87799. * \code comment_num < object->data.vorbis_comment.num_comments \endcode
  87800. * \code (entry.entry != NULL && entry.length > 0) ||
  87801. * (entry.entry == NULL && entry.length == 0) \endcode
  87802. * \retval FLAC__bool
  87803. * \c false if memory allocation fails or \a entry does not comply with the
  87804. * Vorbis comment specification, else \c true.
  87805. */
  87806. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  87807. /** Insert a comment in a VORBIS_COMMENT block at the given index.
  87808. *
  87809. * For convenience, a trailing NUL is added to the entry if it doesn't have
  87810. * one already.
  87811. *
  87812. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  87813. * takes ownership of the \c entry.entry pointer.
  87814. *
  87815. * \note If this function returns \c false, the caller still owns the
  87816. * pointer.
  87817. *
  87818. * \param object A pointer to an existing VORBIS_COMMENT object.
  87819. * \param comment_num The index at which to insert the comment. The comments
  87820. * at and after \a comment_num move right one position.
  87821. * To append a comment to the end, set \a comment_num to
  87822. * \c object->data.vorbis_comment.num_comments .
  87823. * \param entry The comment to insert.
  87824. * \param copy See above.
  87825. * \assert
  87826. * \code object != NULL \endcode
  87827. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  87828. * \code object->data.vorbis_comment.num_comments >= comment_num \endcode
  87829. * \code (entry.entry != NULL && entry.length > 0) ||
  87830. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  87831. * \retval FLAC__bool
  87832. * \c false if memory allocation fails or \a entry does not comply with the
  87833. * Vorbis comment specification, else \c true.
  87834. */
  87835. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_insert_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  87836. /** Appends a comment to a VORBIS_COMMENT block.
  87837. *
  87838. * For convenience, a trailing NUL is added to the entry if it doesn't have
  87839. * one already.
  87840. *
  87841. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  87842. * takes ownership of the \c entry.entry pointer.
  87843. *
  87844. * \note If this function returns \c false, the caller still owns the
  87845. * pointer.
  87846. *
  87847. * \param object A pointer to an existing VORBIS_COMMENT object.
  87848. * \param entry The comment to insert.
  87849. * \param copy See above.
  87850. * \assert
  87851. * \code object != NULL \endcode
  87852. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  87853. * \code (entry.entry != NULL && entry.length > 0) ||
  87854. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  87855. * \retval FLAC__bool
  87856. * \c false if memory allocation fails or \a entry does not comply with the
  87857. * Vorbis comment specification, else \c true.
  87858. */
  87859. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_append_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  87860. /** Replaces comments in a VORBIS_COMMENT block with a new one.
  87861. *
  87862. * For convenience, a trailing NUL is added to the entry if it doesn't have
  87863. * one already.
  87864. *
  87865. * Depending on the the value of \a all, either all or just the first comment
  87866. * whose field name(s) match the given entry's name will be replaced by the
  87867. * given entry. If no comments match, \a entry will simply be appended.
  87868. *
  87869. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  87870. * takes ownership of the \c entry.entry pointer.
  87871. *
  87872. * \note If this function returns \c false, the caller still owns the
  87873. * pointer.
  87874. *
  87875. * \param object A pointer to an existing VORBIS_COMMENT object.
  87876. * \param entry The comment to insert.
  87877. * \param all If \c true, all comments whose field name matches
  87878. * \a entry's field name will be removed, and \a entry will
  87879. * be inserted at the position of the first matching
  87880. * comment. If \c false, only the first comment whose
  87881. * field name matches \a entry's field name will be
  87882. * replaced with \a entry.
  87883. * \param copy See above.
  87884. * \assert
  87885. * \code object != NULL \endcode
  87886. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  87887. * \code (entry.entry != NULL && entry.length > 0) ||
  87888. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  87889. * \retval FLAC__bool
  87890. * \c false if memory allocation fails or \a entry does not comply with the
  87891. * Vorbis comment specification, else \c true.
  87892. */
  87893. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_replace_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool all, FLAC__bool copy);
  87894. /** Delete a comment in a VORBIS_COMMENT block at the given index.
  87895. *
  87896. * \param object A pointer to an existing VORBIS_COMMENT object.
  87897. * \param comment_num The index of the comment to delete.
  87898. * \assert
  87899. * \code object != NULL \endcode
  87900. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  87901. * \code object->data.vorbis_comment.num_comments > comment_num \endcode
  87902. * \retval FLAC__bool
  87903. * \c false if realloc() fails, else \c true.
  87904. */
  87905. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_delete_comment(FLAC__StreamMetadata *object, unsigned comment_num);
  87906. /** Creates a Vorbis comment entry from NUL-terminated name and value strings.
  87907. *
  87908. * On return, the filled-in \a entry->entry pointer will point to malloc()ed
  87909. * memory and shall be owned by the caller. For convenience the entry will
  87910. * have a terminating NUL.
  87911. *
  87912. * \param entry A pointer to a Vorbis comment entry. The entry's
  87913. * \c entry pointer should not point to allocated
  87914. * memory as it will be overwritten.
  87915. * \param field_name The field name in ASCII, \c NUL terminated.
  87916. * \param field_value The field value in UTF-8, \c NUL terminated.
  87917. * \assert
  87918. * \code entry != NULL \endcode
  87919. * \code field_name != NULL \endcode
  87920. * \code field_value != NULL \endcode
  87921. * \retval FLAC__bool
  87922. * \c false if malloc() fails, or if \a field_name or \a field_value does
  87923. * not comply with the Vorbis comment specification, else \c true.
  87924. */
  87925. 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);
  87926. /** Splits a Vorbis comment entry into NUL-terminated name and value strings.
  87927. *
  87928. * The returned pointers to name and value will be allocated by malloc()
  87929. * and shall be owned by the caller.
  87930. *
  87931. * \param entry An existing Vorbis comment entry.
  87932. * \param field_name The address of where the returned pointer to the
  87933. * field name will be stored.
  87934. * \param field_value The address of where the returned pointer to the
  87935. * field value will be stored.
  87936. * \assert
  87937. * \code (entry.entry != NULL && entry.length > 0) \endcode
  87938. * \code memchr(entry.entry, '=', entry.length) != NULL \endcode
  87939. * \code field_name != NULL \endcode
  87940. * \code field_value != NULL \endcode
  87941. * \retval FLAC__bool
  87942. * \c false if memory allocation fails or \a entry does not comply with the
  87943. * Vorbis comment specification, else \c true.
  87944. */
  87945. 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);
  87946. /** Check if the given Vorbis comment entry's field name matches the given
  87947. * field name.
  87948. *
  87949. * \param entry An existing Vorbis comment entry.
  87950. * \param field_name The field name to check.
  87951. * \param field_name_length The length of \a field_name, not including the
  87952. * terminating \c NUL.
  87953. * \assert
  87954. * \code (entry.entry != NULL && entry.length > 0) \endcode
  87955. * \retval FLAC__bool
  87956. * \c true if the field names match, else \c false
  87957. */
  87958. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_matches(const FLAC__StreamMetadata_VorbisComment_Entry entry, const char *field_name, unsigned field_name_length);
  87959. /** Find a Vorbis comment with the given field name.
  87960. *
  87961. * The search begins at entry number \a offset; use an offset of 0 to
  87962. * search from the beginning of the comment array.
  87963. *
  87964. * \param object A pointer to an existing VORBIS_COMMENT object.
  87965. * \param offset The offset into the comment array from where to start
  87966. * the search.
  87967. * \param field_name The field name of the comment to find.
  87968. * \assert
  87969. * \code object != NULL \endcode
  87970. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  87971. * \code field_name != NULL \endcode
  87972. * \retval int
  87973. * The offset in the comment array of the first comment whose field
  87974. * name matches \a field_name, or \c -1 if no match was found.
  87975. */
  87976. FLAC_API int FLAC__metadata_object_vorbiscomment_find_entry_from(const FLAC__StreamMetadata *object, unsigned offset, const char *field_name);
  87977. /** Remove first Vorbis comment matching the given field name.
  87978. *
  87979. * \param object A pointer to an existing VORBIS_COMMENT object.
  87980. * \param field_name The field name of comment to delete.
  87981. * \assert
  87982. * \code object != NULL \endcode
  87983. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  87984. * \retval int
  87985. * \c -1 for memory allocation error, \c 0 for no matching entries,
  87986. * \c 1 for one matching entry deleted.
  87987. */
  87988. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entry_matching(FLAC__StreamMetadata *object, const char *field_name);
  87989. /** Remove all Vorbis comments matching the given field name.
  87990. *
  87991. * \param object A pointer to an existing VORBIS_COMMENT object.
  87992. * \param field_name The field name of comments to delete.
  87993. * \assert
  87994. * \code object != NULL \endcode
  87995. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  87996. * \retval int
  87997. * \c -1 for memory allocation error, \c 0 for no matching entries,
  87998. * else the number of matching entries deleted.
  87999. */
  88000. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entries_matching(FLAC__StreamMetadata *object, const char *field_name);
  88001. /** Create a new CUESHEET track instance.
  88002. *
  88003. * The object will be "empty"; i.e. values and data pointers will be \c 0.
  88004. *
  88005. * \retval FLAC__StreamMetadata_CueSheet_Track*
  88006. * \c NULL if there was an error allocating memory, else the new instance.
  88007. */
  88008. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_new(void);
  88009. /** Create a copy of an existing CUESHEET track 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 object and
  88013. * is responsible for freeing it with
  88014. * FLAC__metadata_object_cuesheet_track_delete().
  88015. *
  88016. * \param object Pointer to object to copy.
  88017. * \assert
  88018. * \code object != NULL \endcode
  88019. * \retval FLAC__StreamMetadata_CueSheet_Track*
  88020. * \c NULL if there was an error allocating memory, else the new instance.
  88021. */
  88022. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_clone(const FLAC__StreamMetadata_CueSheet_Track *object);
  88023. /** Delete a CUESHEET track object
  88024. *
  88025. * \param object A pointer to an existing CUESHEET track object.
  88026. * \assert
  88027. * \code object != NULL \endcode
  88028. */
  88029. FLAC_API void FLAC__metadata_object_cuesheet_track_delete(FLAC__StreamMetadata_CueSheet_Track *object);
  88030. /** Resize a track's index point array.
  88031. *
  88032. * If the size shrinks, elements will truncated; if it grows, new blank
  88033. * indices will be added to the end.
  88034. *
  88035. * \param object A pointer to an existing CUESHEET object.
  88036. * \param track_num The index of the track to modify. NOTE: this is not
  88037. * necessarily the same as the track's \a number field.
  88038. * \param new_num_indices The desired length of the array; may be \c 0.
  88039. * \assert
  88040. * \code object != NULL \endcode
  88041. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88042. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  88043. * \code (object->data.cue_sheet.tracks[track_num].indices == NULL && object->data.cue_sheet.tracks[track_num].num_indices == 0) ||
  88044. * (object->data.cue_sheet.tracks[track_num].indices != NULL && object->data.cue_sheet.tracks[track_num].num_indices > 0) \endcode
  88045. * \retval FLAC__bool
  88046. * \c false if memory allocation error, else \c true.
  88047. */
  88048. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_resize_indices(FLAC__StreamMetadata *object, unsigned track_num, unsigned new_num_indices);
  88049. /** Insert an index point in a CUESHEET track at the given index.
  88050. *
  88051. * \param object A pointer to an existing CUESHEET object.
  88052. * \param track_num The index of the track to modify. NOTE: this is not
  88053. * necessarily the same as the track's \a number field.
  88054. * \param index_num The index into the track's index array at which to
  88055. * insert the index point. NOTE: this is not necessarily
  88056. * the same as the index point's \a number field. The
  88057. * indices at and after \a index_num move right one
  88058. * position. To append an index point to the end, set
  88059. * \a index_num to
  88060. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  88061. * \param index The index point to insert.
  88062. * \assert
  88063. * \code object != NULL \endcode
  88064. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88065. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  88066. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  88067. * \retval FLAC__bool
  88068. * \c false if realloc() fails, else \c true.
  88069. */
  88070. 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);
  88071. /** Insert a blank index point in a CUESHEET track at the given index.
  88072. *
  88073. * A blank index point is one in which all field values are zero.
  88074. *
  88075. * \param object A pointer to an existing CUESHEET object.
  88076. * \param track_num The index of the track to modify. NOTE: this is not
  88077. * necessarily the same as the track's \a number field.
  88078. * \param index_num The index into the track's index array at which to
  88079. * insert the index point. NOTE: this is not necessarily
  88080. * the same as the index point's \a number field. The
  88081. * indices at and after \a index_num move right one
  88082. * position. To append an index point to the end, set
  88083. * \a index_num to
  88084. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  88085. * \assert
  88086. * \code object != NULL \endcode
  88087. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88088. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  88089. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  88090. * \retval FLAC__bool
  88091. * \c false if realloc() fails, else \c true.
  88092. */
  88093. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_insert_blank_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  88094. /** Delete an index point in a CUESHEET track at the given index.
  88095. *
  88096. * \param object A pointer to an existing CUESHEET object.
  88097. * \param track_num The index into the track array of the track to
  88098. * modify. NOTE: this is not necessarily the same
  88099. * as the track's \a number field.
  88100. * \param index_num The index into the track's index array of the index
  88101. * to delete. NOTE: this is not necessarily the same
  88102. * as the index's \a number field.
  88103. * \assert
  88104. * \code object != NULL \endcode
  88105. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88106. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  88107. * \code object->data.cue_sheet.tracks[track_num].num_indices > index_num \endcode
  88108. * \retval FLAC__bool
  88109. * \c false if realloc() fails, else \c true.
  88110. */
  88111. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_delete_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  88112. /** Resize the track array.
  88113. *
  88114. * If the size shrinks, elements will truncated; if it grows, new blank
  88115. * tracks will be added to the end.
  88116. *
  88117. * \param object A pointer to an existing CUESHEET object.
  88118. * \param new_num_tracks The desired length of the array; may be \c 0.
  88119. * \assert
  88120. * \code object != NULL \endcode
  88121. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88122. * \code (object->data.cue_sheet.tracks == NULL && object->data.cue_sheet.num_tracks == 0) ||
  88123. * (object->data.cue_sheet.tracks != NULL && object->data.cue_sheet.num_tracks > 0) \endcode
  88124. * \retval FLAC__bool
  88125. * \c false if memory allocation error, else \c true.
  88126. */
  88127. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_resize_tracks(FLAC__StreamMetadata *object, unsigned new_num_tracks);
  88128. /** Sets a track in a CUESHEET block.
  88129. *
  88130. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  88131. * takes ownership of the \a track pointer.
  88132. *
  88133. * \param object A pointer to an existing CUESHEET object.
  88134. * \param track_num Index into track array to set. NOTE: this is not
  88135. * necessarily the same as the track's \a number field.
  88136. * \param track The track to set the track to. You may safely pass in
  88137. * a const pointer if \a copy is \c true.
  88138. * \param copy See above.
  88139. * \assert
  88140. * \code object != NULL \endcode
  88141. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88142. * \code track_num < object->data.cue_sheet.num_tracks \endcode
  88143. * \code (track->indices != NULL && track->num_indices > 0) ||
  88144. * (track->indices == NULL && track->num_indices == 0)
  88145. * \retval FLAC__bool
  88146. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88147. */
  88148. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_set_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  88149. /** Insert a track in a CUESHEET block at the given index.
  88150. *
  88151. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  88152. * takes ownership of the \a track pointer.
  88153. *
  88154. * \param object A pointer to an existing CUESHEET object.
  88155. * \param track_num The index at which to insert the track. NOTE: this
  88156. * is not necessarily the same as the track's \a number
  88157. * field. The tracks at and after \a track_num move right
  88158. * one position. To append a track to the end, set
  88159. * \a track_num to \c object->data.cue_sheet.num_tracks .
  88160. * \param track The track to insert. You may safely pass in a const
  88161. * pointer if \a copy is \c true.
  88162. * \param copy See above.
  88163. * \assert
  88164. * \code object != NULL \endcode
  88165. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88166. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  88167. * \retval FLAC__bool
  88168. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88169. */
  88170. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  88171. /** Insert a blank track in a CUESHEET block at the given index.
  88172. *
  88173. * A blank track is one in which all field values are zero.
  88174. *
  88175. * \param object A pointer to an existing CUESHEET object.
  88176. * \param track_num The index at which to insert the track. NOTE: this
  88177. * is not necessarily the same as the track's \a number
  88178. * field. The tracks at and after \a track_num move right
  88179. * one position. To append a track to the end, set
  88180. * \a track_num to \c object->data.cue_sheet.num_tracks .
  88181. * \assert
  88182. * \code object != NULL \endcode
  88183. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88184. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  88185. * \retval FLAC__bool
  88186. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88187. */
  88188. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_blank_track(FLAC__StreamMetadata *object, unsigned track_num);
  88189. /** Delete a track in a CUESHEET block at the given index.
  88190. *
  88191. * \param object A pointer to an existing CUESHEET object.
  88192. * \param track_num The index into the track array of the track to
  88193. * delete. NOTE: this is not necessarily the same
  88194. * as the track's \a number field.
  88195. * \assert
  88196. * \code object != NULL \endcode
  88197. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88198. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  88199. * \retval FLAC__bool
  88200. * \c false if realloc() fails, else \c true.
  88201. */
  88202. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_delete_track(FLAC__StreamMetadata *object, unsigned track_num);
  88203. /** Check a cue sheet to see if it conforms to the FLAC specification.
  88204. * See the format specification for limits on the contents of the
  88205. * cue sheet.
  88206. *
  88207. * \param object A pointer to an existing CUESHEET object.
  88208. * \param check_cd_da_subset If \c true, check CUESHEET against more
  88209. * stringent requirements for a CD-DA (audio) disc.
  88210. * \param violation Address of a pointer to a string. If there is a
  88211. * violation, a pointer to a string explanation of the
  88212. * violation will be returned here. \a violation may be
  88213. * \c NULL if you don't need the returned string. Do not
  88214. * free the returned string; it will always point to static
  88215. * data.
  88216. * \assert
  88217. * \code object != NULL \endcode
  88218. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88219. * \retval FLAC__bool
  88220. * \c false if cue sheet is illegal, else \c true.
  88221. */
  88222. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_is_legal(const FLAC__StreamMetadata *object, FLAC__bool check_cd_da_subset, const char **violation);
  88223. /** Calculate and return the CDDB/freedb ID for a cue sheet. The function
  88224. * assumes the cue sheet corresponds to a CD; the result is undefined
  88225. * if the cuesheet's is_cd bit is not set.
  88226. *
  88227. * \param object A pointer to an existing CUESHEET object.
  88228. * \assert
  88229. * \code object != NULL \endcode
  88230. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88231. * \retval FLAC__uint32
  88232. * The unsigned integer representation of the CDDB/freedb ID
  88233. */
  88234. FLAC_API FLAC__uint32 FLAC__metadata_object_cuesheet_calculate_cddb_id(const FLAC__StreamMetadata *object);
  88235. /** Sets the MIME type of a PICTURE block.
  88236. *
  88237. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  88238. * takes ownership of the pointer. The existing string will be freed if this
  88239. * function is successful, otherwise the original string will remain if \a copy
  88240. * is \c true and malloc() fails.
  88241. *
  88242. * \note It is safe to pass a const pointer to \a mime_type if \a copy is \c true.
  88243. *
  88244. * \param object A pointer to an existing PICTURE object.
  88245. * \param mime_type A pointer to the MIME type string. The string must be
  88246. * ASCII characters 0x20-0x7e, NUL-terminated. No validation
  88247. * is done.
  88248. * \param copy See above.
  88249. * \assert
  88250. * \code object != NULL \endcode
  88251. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  88252. * \code (mime_type != NULL) \endcode
  88253. * \retval FLAC__bool
  88254. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88255. */
  88256. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_mime_type(FLAC__StreamMetadata *object, char *mime_type, FLAC__bool copy);
  88257. /** Sets the description of a PICTURE block.
  88258. *
  88259. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  88260. * takes ownership of the pointer. The existing string will be freed if this
  88261. * function is successful, otherwise the original string will remain if \a copy
  88262. * is \c true and malloc() fails.
  88263. *
  88264. * \note It is safe to pass a const pointer to \a description if \a copy is \c true.
  88265. *
  88266. * \param object A pointer to an existing PICTURE object.
  88267. * \param description A pointer to the description string. The string must be
  88268. * valid UTF-8, NUL-terminated. No validation is done.
  88269. * \param copy See above.
  88270. * \assert
  88271. * \code object != NULL \endcode
  88272. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  88273. * \code (description != NULL) \endcode
  88274. * \retval FLAC__bool
  88275. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88276. */
  88277. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_description(FLAC__StreamMetadata *object, FLAC__byte *description, FLAC__bool copy);
  88278. /** Sets the picture data of a PICTURE block.
  88279. *
  88280. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  88281. * takes ownership of the pointer. Also sets the \a data_length field of the
  88282. * metadata object to what is passed in as the \a length parameter. The
  88283. * existing data will be freed if this function is successful, otherwise the
  88284. * original data and data_length will remain if \a copy is \c true and
  88285. * malloc() fails.
  88286. *
  88287. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  88288. *
  88289. * \param object A pointer to an existing PICTURE object.
  88290. * \param data A pointer to the data to set.
  88291. * \param length The length of \a data in bytes.
  88292. * \param copy See above.
  88293. * \assert
  88294. * \code object != NULL \endcode
  88295. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  88296. * \code (data != NULL && length > 0) ||
  88297. * (data == NULL && length == 0 && copy == false) \endcode
  88298. * \retval FLAC__bool
  88299. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88300. */
  88301. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, FLAC__uint32 length, FLAC__bool copy);
  88302. /** Check a PICTURE block to see if it conforms to the FLAC specification.
  88303. * See the format specification for limits on the contents of the
  88304. * PICTURE block.
  88305. *
  88306. * \param object A pointer to existing PICTURE block to be checked.
  88307. * \param violation Address of a pointer to a string. If there is a
  88308. * violation, a pointer to a string explanation of the
  88309. * violation will be returned here. \a violation may be
  88310. * \c NULL if you don't need the returned string. Do not
  88311. * free the returned string; it will always point to static
  88312. * data.
  88313. * \assert
  88314. * \code object != NULL \endcode
  88315. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  88316. * \retval FLAC__bool
  88317. * \c false if PICTURE block is illegal, else \c true.
  88318. */
  88319. FLAC_API FLAC__bool FLAC__metadata_object_picture_is_legal(const FLAC__StreamMetadata *object, const char **violation);
  88320. /* \} */
  88321. #ifdef __cplusplus
  88322. }
  88323. #endif
  88324. #endif
  88325. /*** End of inlined file: metadata.h ***/
  88326. /*** Start of inlined file: stream_decoder.h ***/
  88327. #ifndef FLAC__STREAM_DECODER_H
  88328. #define FLAC__STREAM_DECODER_H
  88329. #include <stdio.h> /* for FILE */
  88330. #ifdef __cplusplus
  88331. extern "C" {
  88332. #endif
  88333. /** \file include/FLAC/stream_decoder.h
  88334. *
  88335. * \brief
  88336. * This module contains the functions which implement the stream
  88337. * decoder.
  88338. *
  88339. * See the detailed documentation in the
  88340. * \link flac_stream_decoder stream decoder \endlink module.
  88341. */
  88342. /** \defgroup flac_decoder FLAC/ \*_decoder.h: decoder interfaces
  88343. * \ingroup flac
  88344. *
  88345. * \brief
  88346. * This module describes the decoder layers provided by libFLAC.
  88347. *
  88348. * The stream decoder can be used to decode complete streams either from
  88349. * the client via callbacks, or directly from a file, depending on how
  88350. * it is initialized. When decoding via callbacks, the client provides
  88351. * callbacks for reading FLAC data and writing decoded samples, and
  88352. * handling metadata and errors. If the client also supplies seek-related
  88353. * callback, the decoder function for sample-accurate seeking within the
  88354. * FLAC input is also available. When decoding from a file, the client
  88355. * needs only supply a filename or open \c FILE* and write/metadata/error
  88356. * callbacks; the rest of the callbacks are supplied internally. For more
  88357. * info see the \link flac_stream_decoder stream decoder \endlink module.
  88358. */
  88359. /** \defgroup flac_stream_decoder FLAC/stream_decoder.h: stream decoder interface
  88360. * \ingroup flac_decoder
  88361. *
  88362. * \brief
  88363. * This module contains the functions which implement the stream
  88364. * decoder.
  88365. *
  88366. * The stream decoder can decode native FLAC, and optionally Ogg FLAC
  88367. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  88368. *
  88369. * The basic usage of this decoder is as follows:
  88370. * - The program creates an instance of a decoder using
  88371. * FLAC__stream_decoder_new().
  88372. * - The program overrides the default settings using
  88373. * FLAC__stream_decoder_set_*() functions.
  88374. * - The program initializes the instance to validate the settings and
  88375. * prepare for decoding using
  88376. * - FLAC__stream_decoder_init_stream() or FLAC__stream_decoder_init_FILE()
  88377. * or FLAC__stream_decoder_init_file() for native FLAC,
  88378. * - FLAC__stream_decoder_init_ogg_stream() or FLAC__stream_decoder_init_ogg_FILE()
  88379. * or FLAC__stream_decoder_init_ogg_file() for Ogg FLAC
  88380. * - The program calls the FLAC__stream_decoder_process_*() functions
  88381. * to decode data, which subsequently calls the callbacks.
  88382. * - The program finishes the decoding with FLAC__stream_decoder_finish(),
  88383. * which flushes the input and output and resets the decoder to the
  88384. * uninitialized state.
  88385. * - The instance may be used again or deleted with
  88386. * FLAC__stream_decoder_delete().
  88387. *
  88388. * In more detail, the program will create a new instance by calling
  88389. * FLAC__stream_decoder_new(), then call FLAC__stream_decoder_set_*()
  88390. * functions to override the default decoder options, and call
  88391. * one of the FLAC__stream_decoder_init_*() functions.
  88392. *
  88393. * There are three initialization functions for native FLAC, one for
  88394. * setting up the decoder to decode FLAC data from the client via
  88395. * callbacks, and two for decoding directly from a FLAC file.
  88396. *
  88397. * For decoding via callbacks, use FLAC__stream_decoder_init_stream().
  88398. * You must also supply several callbacks for handling I/O. Some (like
  88399. * seeking) are optional, depending on the capabilities of the input.
  88400. *
  88401. * For decoding directly from a file, use FLAC__stream_decoder_init_FILE()
  88402. * or FLAC__stream_decoder_init_file(). Then you must only supply an open
  88403. * \c FILE* or filename and fewer callbacks; the decoder will handle
  88404. * the other callbacks internally.
  88405. *
  88406. * There are three similarly-named init functions for decoding from Ogg
  88407. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  88408. * library has been built with Ogg support.
  88409. *
  88410. * Once the decoder is initialized, your program will call one of several
  88411. * functions to start the decoding process:
  88412. *
  88413. * - FLAC__stream_decoder_process_single() - Tells the decoder to process at
  88414. * most one metadata block or audio frame and return, calling either the
  88415. * metadata callback or write callback, respectively, once. If the decoder
  88416. * loses sync it will return with only the error callback being called.
  88417. * - FLAC__stream_decoder_process_until_end_of_metadata() - Tells the decoder
  88418. * to process the stream from the current location and stop upon reaching
  88419. * the first audio frame. The client will get one metadata, write, or error
  88420. * callback per metadata block, audio frame, or sync error, respectively.
  88421. * - FLAC__stream_decoder_process_until_end_of_stream() - Tells the decoder
  88422. * to process the stream from the current location until the read callback
  88423. * returns FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM or
  88424. * FLAC__STREAM_DECODER_READ_STATUS_ABORT. The client will get one metadata,
  88425. * write, or error callback per metadata block, audio frame, or sync error,
  88426. * respectively.
  88427. *
  88428. * When the decoder has finished decoding (normally or through an abort),
  88429. * the instance is finished by calling FLAC__stream_decoder_finish(), which
  88430. * ensures the decoder is in the correct state and frees memory. Then the
  88431. * instance may be deleted with FLAC__stream_decoder_delete() or initialized
  88432. * again to decode another stream.
  88433. *
  88434. * Seeking is exposed through the FLAC__stream_decoder_seek_absolute() method.
  88435. * At any point after the stream decoder has been initialized, the client can
  88436. * call this function to seek to an exact sample within the stream.
  88437. * Subsequently, the first time the write callback is called it will be
  88438. * passed a (possibly partial) block starting at that sample.
  88439. *
  88440. * If the client cannot seek via the callback interface provided, but still
  88441. * has another way of seeking, it can flush the decoder using
  88442. * FLAC__stream_decoder_flush() and start feeding data from the new position
  88443. * through the read callback.
  88444. *
  88445. * The stream decoder also provides MD5 signature checking. If this is
  88446. * turned on before initialization, FLAC__stream_decoder_finish() will
  88447. * report when the decoded MD5 signature does not match the one stored
  88448. * in the STREAMINFO block. MD5 checking is automatically turned off
  88449. * (until the next FLAC__stream_decoder_reset()) if there is no signature
  88450. * in the STREAMINFO block or when a seek is attempted.
  88451. *
  88452. * The FLAC__stream_decoder_set_metadata_*() functions deserve special
  88453. * attention. By default, the decoder only calls the metadata_callback for
  88454. * the STREAMINFO block. These functions allow you to tell the decoder
  88455. * explicitly which blocks to parse and return via the metadata_callback
  88456. * and/or which to skip. Use a FLAC__stream_decoder_set_metadata_respond_all(),
  88457. * FLAC__stream_decoder_set_metadata_ignore() ... or FLAC__stream_decoder_set_metadata_ignore_all(),
  88458. * FLAC__stream_decoder_set_metadata_respond() ... sequence to exactly specify
  88459. * which blocks to return. Remember that metadata blocks can potentially
  88460. * be big (for example, cover art) so filtering out the ones you don't
  88461. * use can reduce the memory requirements of the decoder. Also note the
  88462. * special forms FLAC__stream_decoder_set_metadata_respond_application(id)
  88463. * and FLAC__stream_decoder_set_metadata_ignore_application(id) for
  88464. * filtering APPLICATION blocks based on the application ID.
  88465. *
  88466. * STREAMINFO and SEEKTABLE blocks are always parsed and used internally, but
  88467. * they still can legally be filtered from the metadata_callback.
  88468. *
  88469. * \note
  88470. * The "set" functions may only be called when the decoder is in the
  88471. * state FLAC__STREAM_DECODER_UNINITIALIZED, i.e. after
  88472. * FLAC__stream_decoder_new() or FLAC__stream_decoder_finish(), but
  88473. * before FLAC__stream_decoder_init_*(). If this is the case they will
  88474. * return \c true, otherwise \c false.
  88475. *
  88476. * \note
  88477. * FLAC__stream_decoder_finish() resets all settings to the constructor
  88478. * defaults, including the callbacks.
  88479. *
  88480. * \{
  88481. */
  88482. /** State values for a FLAC__StreamDecoder
  88483. *
  88484. * The decoder's state can be obtained by calling FLAC__stream_decoder_get_state().
  88485. */
  88486. typedef enum {
  88487. FLAC__STREAM_DECODER_SEARCH_FOR_METADATA = 0,
  88488. /**< The decoder is ready to search for metadata. */
  88489. FLAC__STREAM_DECODER_READ_METADATA,
  88490. /**< The decoder is ready to or is in the process of reading metadata. */
  88491. FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC,
  88492. /**< The decoder is ready to or is in the process of searching for the
  88493. * frame sync code.
  88494. */
  88495. FLAC__STREAM_DECODER_READ_FRAME,
  88496. /**< The decoder is ready to or is in the process of reading a frame. */
  88497. FLAC__STREAM_DECODER_END_OF_STREAM,
  88498. /**< The decoder has reached the end of the stream. */
  88499. FLAC__STREAM_DECODER_OGG_ERROR,
  88500. /**< An error occurred in the underlying Ogg layer. */
  88501. FLAC__STREAM_DECODER_SEEK_ERROR,
  88502. /**< An error occurred while seeking. The decoder must be flushed
  88503. * with FLAC__stream_decoder_flush() or reset with
  88504. * FLAC__stream_decoder_reset() before decoding can continue.
  88505. */
  88506. FLAC__STREAM_DECODER_ABORTED,
  88507. /**< The decoder was aborted by the read callback. */
  88508. FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR,
  88509. /**< An error occurred allocating memory. The decoder is in an invalid
  88510. * state and can no longer be used.
  88511. */
  88512. FLAC__STREAM_DECODER_UNINITIALIZED
  88513. /**< The decoder is in the uninitialized state; one of the
  88514. * FLAC__stream_decoder_init_*() functions must be called before samples
  88515. * can be processed.
  88516. */
  88517. } FLAC__StreamDecoderState;
  88518. /** Maps a FLAC__StreamDecoderState to a C string.
  88519. *
  88520. * Using a FLAC__StreamDecoderState as the index to this array
  88521. * will give the string equivalent. The contents should not be modified.
  88522. */
  88523. extern FLAC_API const char * const FLAC__StreamDecoderStateString[];
  88524. /** Possible return values for the FLAC__stream_decoder_init_*() functions.
  88525. */
  88526. typedef enum {
  88527. FLAC__STREAM_DECODER_INIT_STATUS_OK = 0,
  88528. /**< Initialization was successful. */
  88529. FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  88530. /**< The library was not compiled with support for the given container
  88531. * format.
  88532. */
  88533. FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS,
  88534. /**< A required callback was not supplied. */
  88535. FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR,
  88536. /**< An error occurred allocating memory. */
  88537. FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE,
  88538. /**< fopen() failed in FLAC__stream_decoder_init_file() or
  88539. * FLAC__stream_decoder_init_ogg_file(). */
  88540. FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED
  88541. /**< FLAC__stream_decoder_init_*() was called when the decoder was
  88542. * already initialized, usually because
  88543. * FLAC__stream_decoder_finish() was not called.
  88544. */
  88545. } FLAC__StreamDecoderInitStatus;
  88546. /** Maps a FLAC__StreamDecoderInitStatus to a C string.
  88547. *
  88548. * Using a FLAC__StreamDecoderInitStatus as the index to this array
  88549. * will give the string equivalent. The contents should not be modified.
  88550. */
  88551. extern FLAC_API const char * const FLAC__StreamDecoderInitStatusString[];
  88552. /** Return values for the FLAC__StreamDecoder read callback.
  88553. */
  88554. typedef enum {
  88555. FLAC__STREAM_DECODER_READ_STATUS_CONTINUE,
  88556. /**< The read was OK and decoding can continue. */
  88557. FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM,
  88558. /**< The read was attempted while at the end of the stream. Note that
  88559. * the client must only return this value when the read callback was
  88560. * called when already at the end of the stream. Otherwise, if the read
  88561. * itself moves to the end of the stream, the client should still return
  88562. * the data and \c FLAC__STREAM_DECODER_READ_STATUS_CONTINUE, and then on
  88563. * the next read callback it should return
  88564. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM with a byte count
  88565. * of \c 0.
  88566. */
  88567. FLAC__STREAM_DECODER_READ_STATUS_ABORT
  88568. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  88569. } FLAC__StreamDecoderReadStatus;
  88570. /** Maps a FLAC__StreamDecoderReadStatus to a C string.
  88571. *
  88572. * Using a FLAC__StreamDecoderReadStatus as the index to this array
  88573. * will give the string equivalent. The contents should not be modified.
  88574. */
  88575. extern FLAC_API const char * const FLAC__StreamDecoderReadStatusString[];
  88576. /** Return values for the FLAC__StreamDecoder seek callback.
  88577. */
  88578. typedef enum {
  88579. FLAC__STREAM_DECODER_SEEK_STATUS_OK,
  88580. /**< The seek was OK and decoding can continue. */
  88581. FLAC__STREAM_DECODER_SEEK_STATUS_ERROR,
  88582. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  88583. FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  88584. /**< Client does not support seeking. */
  88585. } FLAC__StreamDecoderSeekStatus;
  88586. /** Maps a FLAC__StreamDecoderSeekStatus to a C string.
  88587. *
  88588. * Using a FLAC__StreamDecoderSeekStatus as the index to this array
  88589. * will give the string equivalent. The contents should not be modified.
  88590. */
  88591. extern FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[];
  88592. /** Return values for the FLAC__StreamDecoder tell callback.
  88593. */
  88594. typedef enum {
  88595. FLAC__STREAM_DECODER_TELL_STATUS_OK,
  88596. /**< The tell was OK and decoding can continue. */
  88597. FLAC__STREAM_DECODER_TELL_STATUS_ERROR,
  88598. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  88599. FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  88600. /**< Client does not support telling the position. */
  88601. } FLAC__StreamDecoderTellStatus;
  88602. /** Maps a FLAC__StreamDecoderTellStatus to a C string.
  88603. *
  88604. * Using a FLAC__StreamDecoderTellStatus as the index to this array
  88605. * will give the string equivalent. The contents should not be modified.
  88606. */
  88607. extern FLAC_API const char * const FLAC__StreamDecoderTellStatusString[];
  88608. /** Return values for the FLAC__StreamDecoder length callback.
  88609. */
  88610. typedef enum {
  88611. FLAC__STREAM_DECODER_LENGTH_STATUS_OK,
  88612. /**< The length call was OK and decoding can continue. */
  88613. FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR,
  88614. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  88615. FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  88616. /**< Client does not support reporting the length. */
  88617. } FLAC__StreamDecoderLengthStatus;
  88618. /** Maps a FLAC__StreamDecoderLengthStatus to a C string.
  88619. *
  88620. * Using a FLAC__StreamDecoderLengthStatus as the index to this array
  88621. * will give the string equivalent. The contents should not be modified.
  88622. */
  88623. extern FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[];
  88624. /** Return values for the FLAC__StreamDecoder write callback.
  88625. */
  88626. typedef enum {
  88627. FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE,
  88628. /**< The write was OK and decoding can continue. */
  88629. FLAC__STREAM_DECODER_WRITE_STATUS_ABORT
  88630. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  88631. } FLAC__StreamDecoderWriteStatus;
  88632. /** Maps a FLAC__StreamDecoderWriteStatus to a C string.
  88633. *
  88634. * Using a FLAC__StreamDecoderWriteStatus as the index to this array
  88635. * will give the string equivalent. The contents should not be modified.
  88636. */
  88637. extern FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[];
  88638. /** Possible values passed back to the FLAC__StreamDecoder error callback.
  88639. * \c FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC is the generic catch-
  88640. * all. The rest could be caused by bad sync (false synchronization on
  88641. * data that is not the start of a frame) or corrupted data. The error
  88642. * itself is the decoder's best guess at what happened assuming a correct
  88643. * sync. For example \c FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER
  88644. * could be caused by a correct sync on the start of a frame, but some
  88645. * data in the frame header was corrupted. Or it could be the result of
  88646. * syncing on a point the stream that looked like the starting of a frame
  88647. * but was not. \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  88648. * could be because the decoder encountered a valid frame made by a future
  88649. * version of the encoder which it cannot parse, or because of a false
  88650. * sync making it appear as though an encountered frame was generated by
  88651. * a future encoder.
  88652. */
  88653. typedef enum {
  88654. FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC,
  88655. /**< An error in the stream caused the decoder to lose synchronization. */
  88656. FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER,
  88657. /**< The decoder encountered a corrupted frame header. */
  88658. FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH,
  88659. /**< The frame's data did not match the CRC in the footer. */
  88660. FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  88661. /**< The decoder encountered reserved fields in use in the stream. */
  88662. } FLAC__StreamDecoderErrorStatus;
  88663. /** Maps a FLAC__StreamDecoderErrorStatus to a C string.
  88664. *
  88665. * Using a FLAC__StreamDecoderErrorStatus as the index to this array
  88666. * will give the string equivalent. The contents should not be modified.
  88667. */
  88668. extern FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[];
  88669. /***********************************************************************
  88670. *
  88671. * class FLAC__StreamDecoder
  88672. *
  88673. ***********************************************************************/
  88674. struct FLAC__StreamDecoderProtected;
  88675. struct FLAC__StreamDecoderPrivate;
  88676. /** The opaque structure definition for the stream decoder type.
  88677. * See the \link flac_stream_decoder stream decoder module \endlink
  88678. * for a detailed description.
  88679. */
  88680. typedef struct {
  88681. struct FLAC__StreamDecoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  88682. struct FLAC__StreamDecoderPrivate *private_; /* avoid the C++ keyword 'private' */
  88683. } FLAC__StreamDecoder;
  88684. /** Signature for the read callback.
  88685. *
  88686. * A function pointer matching this signature must be passed to
  88687. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  88688. * called when the decoder needs more input data. The address of the
  88689. * buffer to be filled is supplied, along with the number of bytes the
  88690. * buffer can hold. The callback may choose to supply less data and
  88691. * modify the byte count but must be careful not to overflow the buffer.
  88692. * The callback then returns a status code chosen from
  88693. * FLAC__StreamDecoderReadStatus.
  88694. *
  88695. * Here is an example of a read callback for stdio streams:
  88696. * \code
  88697. * FLAC__StreamDecoderReadStatus read_cb(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  88698. * {
  88699. * FILE *file = ((MyClientData*)client_data)->file;
  88700. * if(*bytes > 0) {
  88701. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  88702. * if(ferror(file))
  88703. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  88704. * else if(*bytes == 0)
  88705. * return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  88706. * else
  88707. * return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  88708. * }
  88709. * else
  88710. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  88711. * }
  88712. * \endcode
  88713. *
  88714. * \note In general, FLAC__StreamDecoder functions which change the
  88715. * state should not be called on the \a decoder while in the callback.
  88716. *
  88717. * \param decoder The decoder instance calling the callback.
  88718. * \param buffer A pointer to a location for the callee to store
  88719. * data to be decoded.
  88720. * \param bytes A pointer to the size of the buffer. On entry
  88721. * to the callback, it contains the maximum number
  88722. * of bytes that may be stored in \a buffer. The
  88723. * callee must set it to the actual number of bytes
  88724. * stored (0 in case of error or end-of-stream) before
  88725. * returning.
  88726. * \param client_data The callee's client data set through
  88727. * FLAC__stream_decoder_init_*().
  88728. * \retval FLAC__StreamDecoderReadStatus
  88729. * The callee's return status. Note that the callback should return
  88730. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM if and only if
  88731. * zero bytes were read and there is no more data to be read.
  88732. */
  88733. typedef FLAC__StreamDecoderReadStatus (*FLAC__StreamDecoderReadCallback)(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  88734. /** Signature for the seek callback.
  88735. *
  88736. * A function pointer matching this signature may be passed to
  88737. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  88738. * called when the decoder needs to seek the input stream. The decoder
  88739. * will pass the absolute byte offset to seek to, 0 meaning the
  88740. * beginning of the stream.
  88741. *
  88742. * Here is an example of a seek callback for stdio streams:
  88743. * \code
  88744. * FLAC__StreamDecoderSeekStatus seek_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  88745. * {
  88746. * FILE *file = ((MyClientData*)client_data)->file;
  88747. * if(file == stdin)
  88748. * return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  88749. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  88750. * return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  88751. * else
  88752. * return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  88753. * }
  88754. * \endcode
  88755. *
  88756. * \note In general, FLAC__StreamDecoder functions which change the
  88757. * state should not be called on the \a decoder while in the callback.
  88758. *
  88759. * \param decoder The decoder instance calling the callback.
  88760. * \param absolute_byte_offset The offset from the beginning of the stream
  88761. * to seek to.
  88762. * \param client_data The callee's client data set through
  88763. * FLAC__stream_decoder_init_*().
  88764. * \retval FLAC__StreamDecoderSeekStatus
  88765. * The callee's return status.
  88766. */
  88767. typedef FLAC__StreamDecoderSeekStatus (*FLAC__StreamDecoderSeekCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  88768. /** Signature for the tell callback.
  88769. *
  88770. * A function pointer matching this signature may be passed to
  88771. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  88772. * called when the decoder wants to know the current position of the
  88773. * stream. The callback should return the byte offset from the
  88774. * beginning of the stream.
  88775. *
  88776. * Here is an example of a tell callback for stdio streams:
  88777. * \code
  88778. * FLAC__StreamDecoderTellStatus tell_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  88779. * {
  88780. * FILE *file = ((MyClientData*)client_data)->file;
  88781. * off_t pos;
  88782. * if(file == stdin)
  88783. * return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  88784. * else if((pos = ftello(file)) < 0)
  88785. * return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  88786. * else {
  88787. * *absolute_byte_offset = (FLAC__uint64)pos;
  88788. * return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  88789. * }
  88790. * }
  88791. * \endcode
  88792. *
  88793. * \note In general, FLAC__StreamDecoder functions which change the
  88794. * state should not be called on the \a decoder while in the callback.
  88795. *
  88796. * \param decoder The decoder instance calling the callback.
  88797. * \param absolute_byte_offset A pointer to storage for the current offset
  88798. * from the beginning of the stream.
  88799. * \param client_data The callee's client data set through
  88800. * FLAC__stream_decoder_init_*().
  88801. * \retval FLAC__StreamDecoderTellStatus
  88802. * The callee's return status.
  88803. */
  88804. typedef FLAC__StreamDecoderTellStatus (*FLAC__StreamDecoderTellCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  88805. /** Signature for the length callback.
  88806. *
  88807. * A function pointer matching this signature may be passed to
  88808. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  88809. * called when the decoder wants to know the total length of the stream
  88810. * in bytes.
  88811. *
  88812. * Here is an example of a length callback for stdio streams:
  88813. * \code
  88814. * FLAC__StreamDecoderLengthStatus length_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  88815. * {
  88816. * FILE *file = ((MyClientData*)client_data)->file;
  88817. * struct stat filestats;
  88818. *
  88819. * if(file == stdin)
  88820. * return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  88821. * else if(fstat(fileno(file), &filestats) != 0)
  88822. * return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  88823. * else {
  88824. * *stream_length = (FLAC__uint64)filestats.st_size;
  88825. * return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  88826. * }
  88827. * }
  88828. * \endcode
  88829. *
  88830. * \note In general, FLAC__StreamDecoder functions which change the
  88831. * state should not be called on the \a decoder while in the callback.
  88832. *
  88833. * \param decoder The decoder instance calling the callback.
  88834. * \param stream_length A pointer to storage for the length of the stream
  88835. * in bytes.
  88836. * \param client_data The callee's client data set through
  88837. * FLAC__stream_decoder_init_*().
  88838. * \retval FLAC__StreamDecoderLengthStatus
  88839. * The callee's return status.
  88840. */
  88841. typedef FLAC__StreamDecoderLengthStatus (*FLAC__StreamDecoderLengthCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  88842. /** Signature for the EOF callback.
  88843. *
  88844. * A function pointer matching this signature may be passed to
  88845. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  88846. * called when the decoder needs to know if the end of the stream has
  88847. * been reached.
  88848. *
  88849. * Here is an example of a EOF callback for stdio streams:
  88850. * FLAC__bool eof_cb(const FLAC__StreamDecoder *decoder, void *client_data)
  88851. * \code
  88852. * {
  88853. * FILE *file = ((MyClientData*)client_data)->file;
  88854. * return feof(file)? true : false;
  88855. * }
  88856. * \endcode
  88857. *
  88858. * \note In general, FLAC__StreamDecoder functions which change the
  88859. * state should not be called on the \a decoder while in the callback.
  88860. *
  88861. * \param decoder The decoder instance calling the callback.
  88862. * \param client_data The callee's client data set through
  88863. * FLAC__stream_decoder_init_*().
  88864. * \retval FLAC__bool
  88865. * \c true if the currently at the end of the stream, else \c false.
  88866. */
  88867. typedef FLAC__bool (*FLAC__StreamDecoderEofCallback)(const FLAC__StreamDecoder *decoder, void *client_data);
  88868. /** Signature for the write callback.
  88869. *
  88870. * A function pointer matching this signature must be passed to one of
  88871. * the FLAC__stream_decoder_init_*() functions.
  88872. * The supplied function will be called when the decoder has decoded a
  88873. * single audio frame. The decoder will pass the frame metadata as well
  88874. * as an array of pointers (one for each channel) pointing to the
  88875. * decoded audio.
  88876. *
  88877. * \note In general, FLAC__StreamDecoder functions which change the
  88878. * state should not be called on the \a decoder while in the callback.
  88879. *
  88880. * \param decoder The decoder instance calling the callback.
  88881. * \param frame The description of the decoded frame. See
  88882. * FLAC__Frame.
  88883. * \param buffer An array of pointers to decoded channels of data.
  88884. * Each pointer will point to an array of signed
  88885. * samples of length \a frame->header.blocksize.
  88886. * Channels will be ordered according to the FLAC
  88887. * specification; see the documentation for the
  88888. * <A HREF="../format.html#frame_header">frame header</A>.
  88889. * \param client_data The callee's client data set through
  88890. * FLAC__stream_decoder_init_*().
  88891. * \retval FLAC__StreamDecoderWriteStatus
  88892. * The callee's return status.
  88893. */
  88894. typedef FLAC__StreamDecoderWriteStatus (*FLAC__StreamDecoderWriteCallback)(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  88895. /** Signature for the metadata callback.
  88896. *
  88897. * A function pointer matching this signature must be passed to one of
  88898. * the FLAC__stream_decoder_init_*() functions.
  88899. * The supplied function will be called when the decoder has decoded a
  88900. * metadata block. In a valid FLAC file there will always be one
  88901. * \c STREAMINFO block, followed by zero or more other metadata blocks.
  88902. * These will be supplied by the decoder in the same order as they
  88903. * appear in the stream and always before the first audio frame (i.e.
  88904. * write callback). The metadata block that is passed in must not be
  88905. * modified, and it doesn't live beyond the callback, so you should make
  88906. * a copy of it with FLAC__metadata_object_clone() if you will need it
  88907. * elsewhere. Since metadata blocks can potentially be large, by
  88908. * default the decoder only calls the metadata callback for the
  88909. * \c STREAMINFO block; you can instruct the decoder to pass or filter
  88910. * other blocks with FLAC__stream_decoder_set_metadata_*() calls.
  88911. *
  88912. * \note In general, FLAC__StreamDecoder functions which change the
  88913. * state should not be called on the \a decoder while in the callback.
  88914. *
  88915. * \param decoder The decoder instance calling the callback.
  88916. * \param metadata The decoded metadata block.
  88917. * \param client_data The callee's client data set through
  88918. * FLAC__stream_decoder_init_*().
  88919. */
  88920. typedef void (*FLAC__StreamDecoderMetadataCallback)(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  88921. /** Signature for the error callback.
  88922. *
  88923. * A function pointer matching this signature must be passed to one of
  88924. * the FLAC__stream_decoder_init_*() functions.
  88925. * The supplied function will be called whenever an error occurs during
  88926. * decoding.
  88927. *
  88928. * \note In general, FLAC__StreamDecoder functions which change the
  88929. * state should not be called on the \a decoder while in the callback.
  88930. *
  88931. * \param decoder The decoder instance calling the callback.
  88932. * \param status The error encountered by the decoder.
  88933. * \param client_data The callee's client data set through
  88934. * FLAC__stream_decoder_init_*().
  88935. */
  88936. typedef void (*FLAC__StreamDecoderErrorCallback)(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  88937. /***********************************************************************
  88938. *
  88939. * Class constructor/destructor
  88940. *
  88941. ***********************************************************************/
  88942. /** Create a new stream decoder instance. The instance is created with
  88943. * default settings; see the individual FLAC__stream_decoder_set_*()
  88944. * functions for each setting's default.
  88945. *
  88946. * \retval FLAC__StreamDecoder*
  88947. * \c NULL if there was an error allocating memory, else the new instance.
  88948. */
  88949. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void);
  88950. /** Free a decoder instance. Deletes the object pointed to by \a decoder.
  88951. *
  88952. * \param decoder A pointer to an existing decoder.
  88953. * \assert
  88954. * \code decoder != NULL \endcode
  88955. */
  88956. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder);
  88957. /***********************************************************************
  88958. *
  88959. * Public class method prototypes
  88960. *
  88961. ***********************************************************************/
  88962. /** Set the serial number for the FLAC stream within the Ogg container.
  88963. * The default behavior is to use the serial number of the first Ogg
  88964. * page. Setting a serial number here will explicitly specify which
  88965. * stream is to be decoded.
  88966. *
  88967. * \note
  88968. * This does not need to be set for native FLAC decoding.
  88969. *
  88970. * \default \c use serial number of first page
  88971. * \param decoder A decoder instance to set.
  88972. * \param serial_number See above.
  88973. * \assert
  88974. * \code decoder != NULL \endcode
  88975. * \retval FLAC__bool
  88976. * \c false if the decoder is already initialized, else \c true.
  88977. */
  88978. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long serial_number);
  88979. /** Set the "MD5 signature checking" flag. If \c true, the decoder will
  88980. * compute the MD5 signature of the unencoded audio data while decoding
  88981. * and compare it to the signature from the STREAMINFO block, if it
  88982. * exists, during FLAC__stream_decoder_finish().
  88983. *
  88984. * MD5 signature checking will be turned off (until the next
  88985. * FLAC__stream_decoder_reset()) if there is no signature in the
  88986. * STREAMINFO block or when a seek is attempted.
  88987. *
  88988. * Clients that do not use the MD5 check should leave this off to speed
  88989. * up decoding.
  88990. *
  88991. * \default \c false
  88992. * \param decoder A decoder instance to set.
  88993. * \param value Flag value (see above).
  88994. * \assert
  88995. * \code decoder != NULL \endcode
  88996. * \retval FLAC__bool
  88997. * \c false if the decoder is already initialized, else \c true.
  88998. */
  88999. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value);
  89000. /** Direct the decoder to pass on all metadata blocks of type \a type.
  89001. *
  89002. * \default By default, only the \c STREAMINFO block is returned via the
  89003. * metadata callback.
  89004. * \param decoder A decoder instance to set.
  89005. * \param type See above.
  89006. * \assert
  89007. * \code decoder != NULL \endcode
  89008. * \a type is valid
  89009. * \retval FLAC__bool
  89010. * \c false if the decoder is already initialized, else \c true.
  89011. */
  89012. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  89013. /** Direct the decoder to pass on all APPLICATION metadata blocks of the
  89014. * given \a id.
  89015. *
  89016. * \default By default, only the \c STREAMINFO block is returned via the
  89017. * metadata callback.
  89018. * \param decoder A decoder instance to set.
  89019. * \param id See above.
  89020. * \assert
  89021. * \code decoder != NULL \endcode
  89022. * \code id != NULL \endcode
  89023. * \retval FLAC__bool
  89024. * \c false if the decoder is already initialized, else \c true.
  89025. */
  89026. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  89027. /** Direct the decoder to pass on all metadata blocks of any type.
  89028. *
  89029. * \default By default, only the \c STREAMINFO block is returned via the
  89030. * metadata callback.
  89031. * \param decoder A decoder instance to set.
  89032. * \assert
  89033. * \code decoder != NULL \endcode
  89034. * \retval FLAC__bool
  89035. * \c false if the decoder is already initialized, else \c true.
  89036. */
  89037. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder);
  89038. /** Direct the decoder to filter out all metadata blocks of type \a type.
  89039. *
  89040. * \default By default, only the \c STREAMINFO block is returned via the
  89041. * metadata callback.
  89042. * \param decoder A decoder instance to set.
  89043. * \param type See above.
  89044. * \assert
  89045. * \code decoder != NULL \endcode
  89046. * \a type is valid
  89047. * \retval FLAC__bool
  89048. * \c false if the decoder is already initialized, else \c true.
  89049. */
  89050. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  89051. /** Direct the decoder to filter out all APPLICATION metadata blocks of
  89052. * the given \a id.
  89053. *
  89054. * \default By default, only the \c STREAMINFO block is returned via the
  89055. * metadata callback.
  89056. * \param decoder A decoder instance to set.
  89057. * \param id See above.
  89058. * \assert
  89059. * \code decoder != NULL \endcode
  89060. * \code id != NULL \endcode
  89061. * \retval FLAC__bool
  89062. * \c false if the decoder is already initialized, else \c true.
  89063. */
  89064. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  89065. /** Direct the decoder to filter out all metadata blocks of any type.
  89066. *
  89067. * \default By default, only the \c STREAMINFO block is returned via the
  89068. * metadata callback.
  89069. * \param decoder A decoder instance to set.
  89070. * \assert
  89071. * \code decoder != NULL \endcode
  89072. * \retval FLAC__bool
  89073. * \c false if the decoder is already initialized, else \c true.
  89074. */
  89075. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder);
  89076. /** Get the current decoder state.
  89077. *
  89078. * \param decoder A decoder instance to query.
  89079. * \assert
  89080. * \code decoder != NULL \endcode
  89081. * \retval FLAC__StreamDecoderState
  89082. * The current decoder state.
  89083. */
  89084. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder);
  89085. /** Get the current decoder state as a C string.
  89086. *
  89087. * \param decoder A decoder instance to query.
  89088. * \assert
  89089. * \code decoder != NULL \endcode
  89090. * \retval const char *
  89091. * The decoder state as a C string. Do not modify the contents.
  89092. */
  89093. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder);
  89094. /** Get the "MD5 signature checking" flag.
  89095. * This is the value of the setting, not whether or not the decoder is
  89096. * currently checking the MD5 (remember, it can be turned off automatically
  89097. * by a seek). When the decoder is reset the flag will be restored to the
  89098. * value returned by this function.
  89099. *
  89100. * \param decoder A decoder instance to query.
  89101. * \assert
  89102. * \code decoder != NULL \endcode
  89103. * \retval FLAC__bool
  89104. * See above.
  89105. */
  89106. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder);
  89107. /** Get the total number of samples in the stream being decoded.
  89108. * Will only be valid after decoding has started and will contain the
  89109. * value from the \c STREAMINFO block. A value of \c 0 means "unknown".
  89110. *
  89111. * \param decoder A decoder instance to query.
  89112. * \assert
  89113. * \code decoder != NULL \endcode
  89114. * \retval unsigned
  89115. * See above.
  89116. */
  89117. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder);
  89118. /** Get the current number of channels in the stream being decoded.
  89119. * Will only be valid after decoding has started and will contain the
  89120. * value from the most recently decoded frame header.
  89121. *
  89122. * \param decoder A decoder instance to query.
  89123. * \assert
  89124. * \code decoder != NULL \endcode
  89125. * \retval unsigned
  89126. * See above.
  89127. */
  89128. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder);
  89129. /** Get the current channel assignment in the stream being decoded.
  89130. * Will only be valid after decoding has started and will contain the
  89131. * value from the most recently decoded frame header.
  89132. *
  89133. * \param decoder A decoder instance to query.
  89134. * \assert
  89135. * \code decoder != NULL \endcode
  89136. * \retval FLAC__ChannelAssignment
  89137. * See above.
  89138. */
  89139. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder);
  89140. /** Get the current sample resolution in the stream being decoded.
  89141. * Will only be valid after decoding has started and will contain the
  89142. * value from the most recently decoded frame header.
  89143. *
  89144. * \param decoder A decoder instance to query.
  89145. * \assert
  89146. * \code decoder != NULL \endcode
  89147. * \retval unsigned
  89148. * See above.
  89149. */
  89150. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder);
  89151. /** Get the current sample rate in Hz of the stream being decoded.
  89152. * Will only be valid after decoding has started and will contain the
  89153. * value from the most recently decoded frame header.
  89154. *
  89155. * \param decoder A decoder instance to query.
  89156. * \assert
  89157. * \code decoder != NULL \endcode
  89158. * \retval unsigned
  89159. * See above.
  89160. */
  89161. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder);
  89162. /** Get the current blocksize of the stream being decoded.
  89163. * Will only be valid after decoding has started and will contain the
  89164. * value from the most recently decoded frame header.
  89165. *
  89166. * \param decoder A decoder instance to query.
  89167. * \assert
  89168. * \code decoder != NULL \endcode
  89169. * \retval unsigned
  89170. * See above.
  89171. */
  89172. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder);
  89173. /** Returns the decoder's current read position within the stream.
  89174. * The position is the byte offset from the start of the stream.
  89175. * Bytes before this position have been fully decoded. Note that
  89176. * there may still be undecoded bytes in the decoder's read FIFO.
  89177. * The returned position is correct even after a seek.
  89178. *
  89179. * \warning This function currently only works for native FLAC,
  89180. * not Ogg FLAC streams.
  89181. *
  89182. * \param decoder A decoder instance to query.
  89183. * \param position Address at which to return the desired position.
  89184. * \assert
  89185. * \code decoder != NULL \endcode
  89186. * \code position != NULL \endcode
  89187. * \retval FLAC__bool
  89188. * \c true if successful, \c false if the stream is not native FLAC,
  89189. * or there was an error from the 'tell' callback or it returned
  89190. * \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED.
  89191. */
  89192. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position);
  89193. /** Initialize the decoder instance to decode native FLAC streams.
  89194. *
  89195. * This flavor of initialization sets up the decoder to decode from a
  89196. * native FLAC stream. I/O is performed via callbacks to the client.
  89197. * For decoding from a plain file via filename or open FILE*,
  89198. * FLAC__stream_decoder_init_file() and FLAC__stream_decoder_init_FILE()
  89199. * provide a simpler interface.
  89200. *
  89201. * This function should be called after FLAC__stream_decoder_new() and
  89202. * FLAC__stream_decoder_set_*() but before any of the
  89203. * FLAC__stream_decoder_process_*() functions. Will set and return the
  89204. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  89205. * if initialization succeeded.
  89206. *
  89207. * \param decoder An uninitialized decoder instance.
  89208. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  89209. * pointer must not be \c NULL.
  89210. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  89211. * pointer may be \c NULL if seeking is not
  89212. * supported. If \a seek_callback is not \c NULL then a
  89213. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  89214. * Alternatively, a dummy seek callback that just
  89215. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  89216. * may also be supplied, all though this is slightly
  89217. * less efficient for the decoder.
  89218. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  89219. * pointer may be \c NULL if not supported by the client. If
  89220. * \a seek_callback is not \c NULL then a
  89221. * \a tell_callback must also be supplied.
  89222. * Alternatively, a dummy tell callback that just
  89223. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  89224. * may also be supplied, all though this is slightly
  89225. * less efficient for the decoder.
  89226. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  89227. * pointer may be \c NULL if not supported by the client. If
  89228. * \a seek_callback is not \c NULL then a
  89229. * \a length_callback must also be supplied.
  89230. * Alternatively, a dummy length callback that just
  89231. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  89232. * may also be supplied, all though this is slightly
  89233. * less efficient for the decoder.
  89234. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  89235. * pointer may be \c NULL if not supported by the client. If
  89236. * \a seek_callback is not \c NULL then a
  89237. * \a eof_callback must also be supplied.
  89238. * Alternatively, a dummy length callback that just
  89239. * returns \c false
  89240. * may also be supplied, all though this is slightly
  89241. * less efficient for the decoder.
  89242. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  89243. * pointer must not be \c NULL.
  89244. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  89245. * pointer may be \c NULL if the callback is not
  89246. * desired.
  89247. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  89248. * pointer must not be \c NULL.
  89249. * \param client_data This value will be supplied to callbacks in their
  89250. * \a client_data argument.
  89251. * \assert
  89252. * \code decoder != NULL \endcode
  89253. * \retval FLAC__StreamDecoderInitStatus
  89254. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  89255. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  89256. */
  89257. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  89258. FLAC__StreamDecoder *decoder,
  89259. FLAC__StreamDecoderReadCallback read_callback,
  89260. FLAC__StreamDecoderSeekCallback seek_callback,
  89261. FLAC__StreamDecoderTellCallback tell_callback,
  89262. FLAC__StreamDecoderLengthCallback length_callback,
  89263. FLAC__StreamDecoderEofCallback eof_callback,
  89264. FLAC__StreamDecoderWriteCallback write_callback,
  89265. FLAC__StreamDecoderMetadataCallback metadata_callback,
  89266. FLAC__StreamDecoderErrorCallback error_callback,
  89267. void *client_data
  89268. );
  89269. /** Initialize the decoder instance to decode Ogg FLAC streams.
  89270. *
  89271. * This flavor of initialization sets up the decoder to decode from a
  89272. * FLAC stream in an Ogg container. I/O is performed via callbacks to the
  89273. * client. For decoding from a plain file via filename or open FILE*,
  89274. * FLAC__stream_decoder_init_ogg_file() and FLAC__stream_decoder_init_ogg_FILE()
  89275. * provide a simpler interface.
  89276. *
  89277. * This function should be called after FLAC__stream_decoder_new() and
  89278. * FLAC__stream_decoder_set_*() but before any of the
  89279. * FLAC__stream_decoder_process_*() functions. Will set and return the
  89280. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  89281. * if initialization succeeded.
  89282. *
  89283. * \note Support for Ogg FLAC in the library is optional. If this
  89284. * library has been built without support for Ogg FLAC, this function
  89285. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  89286. *
  89287. * \param decoder An uninitialized decoder instance.
  89288. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  89289. * pointer must not be \c NULL.
  89290. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  89291. * pointer may be \c NULL if seeking is not
  89292. * supported. If \a seek_callback is not \c NULL then a
  89293. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  89294. * Alternatively, a dummy seek callback that just
  89295. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  89296. * may also be supplied, all though this is slightly
  89297. * less efficient for the decoder.
  89298. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  89299. * pointer may be \c NULL if not supported by the client. If
  89300. * \a seek_callback is not \c NULL then a
  89301. * \a tell_callback must also be supplied.
  89302. * Alternatively, a dummy tell callback that just
  89303. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  89304. * may also be supplied, all though this is slightly
  89305. * less efficient for the decoder.
  89306. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  89307. * pointer may be \c NULL if not supported by the client. If
  89308. * \a seek_callback is not \c NULL then a
  89309. * \a length_callback must also be supplied.
  89310. * Alternatively, a dummy length callback that just
  89311. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  89312. * may also be supplied, all though this is slightly
  89313. * less efficient for the decoder.
  89314. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  89315. * pointer may be \c NULL if not supported by the client. If
  89316. * \a seek_callback is not \c NULL then a
  89317. * \a eof_callback must also be supplied.
  89318. * Alternatively, a dummy length callback that just
  89319. * returns \c false
  89320. * may also be supplied, all though this is slightly
  89321. * less efficient for the decoder.
  89322. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  89323. * pointer must not be \c NULL.
  89324. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  89325. * pointer may be \c NULL if the callback is not
  89326. * desired.
  89327. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  89328. * pointer must not be \c NULL.
  89329. * \param client_data This value will be supplied to callbacks in their
  89330. * \a client_data argument.
  89331. * \assert
  89332. * \code decoder != NULL \endcode
  89333. * \retval FLAC__StreamDecoderInitStatus
  89334. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  89335. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  89336. */
  89337. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  89338. FLAC__StreamDecoder *decoder,
  89339. FLAC__StreamDecoderReadCallback read_callback,
  89340. FLAC__StreamDecoderSeekCallback seek_callback,
  89341. FLAC__StreamDecoderTellCallback tell_callback,
  89342. FLAC__StreamDecoderLengthCallback length_callback,
  89343. FLAC__StreamDecoderEofCallback eof_callback,
  89344. FLAC__StreamDecoderWriteCallback write_callback,
  89345. FLAC__StreamDecoderMetadataCallback metadata_callback,
  89346. FLAC__StreamDecoderErrorCallback error_callback,
  89347. void *client_data
  89348. );
  89349. /** Initialize the decoder instance to decode native FLAC files.
  89350. *
  89351. * This flavor of initialization sets up the decoder to decode from a
  89352. * plain native FLAC file. For non-stdio streams, you must use
  89353. * FLAC__stream_decoder_init_stream() and provide callbacks for the I/O.
  89354. *
  89355. * This function should be called after FLAC__stream_decoder_new() and
  89356. * FLAC__stream_decoder_set_*() but before any of the
  89357. * FLAC__stream_decoder_process_*() functions. Will set and return the
  89358. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  89359. * if initialization succeeded.
  89360. *
  89361. * \param decoder An uninitialized decoder instance.
  89362. * \param file An open FLAC file. The file should have been
  89363. * opened with mode \c "rb" and rewound. The file
  89364. * becomes owned by the decoder and should not be
  89365. * manipulated by the client while decoding.
  89366. * Unless \a file is \c stdin, it will be closed
  89367. * when FLAC__stream_decoder_finish() is called.
  89368. * Note however that seeking will not work when
  89369. * decoding from \c stdout since it is not seekable.
  89370. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  89371. * pointer must not be \c NULL.
  89372. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  89373. * pointer may be \c NULL if the callback is not
  89374. * desired.
  89375. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  89376. * pointer must not be \c NULL.
  89377. * \param client_data This value will be supplied to callbacks in their
  89378. * \a client_data argument.
  89379. * \assert
  89380. * \code decoder != NULL \endcode
  89381. * \code file != NULL \endcode
  89382. * \retval FLAC__StreamDecoderInitStatus
  89383. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  89384. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  89385. */
  89386. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  89387. FLAC__StreamDecoder *decoder,
  89388. FILE *file,
  89389. FLAC__StreamDecoderWriteCallback write_callback,
  89390. FLAC__StreamDecoderMetadataCallback metadata_callback,
  89391. FLAC__StreamDecoderErrorCallback error_callback,
  89392. void *client_data
  89393. );
  89394. /** Initialize the decoder instance to decode Ogg FLAC files.
  89395. *
  89396. * This flavor of initialization sets up the decoder to decode from a
  89397. * plain Ogg FLAC file. For non-stdio streams, you must use
  89398. * FLAC__stream_decoder_init_ogg_stream() and provide callbacks for the I/O.
  89399. *
  89400. * This function should be called after FLAC__stream_decoder_new() and
  89401. * FLAC__stream_decoder_set_*() but before any of the
  89402. * FLAC__stream_decoder_process_*() functions. Will set and return the
  89403. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  89404. * if initialization succeeded.
  89405. *
  89406. * \note Support for Ogg FLAC in the library is optional. If this
  89407. * library has been built without support for Ogg FLAC, this function
  89408. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  89409. *
  89410. * \param decoder An uninitialized decoder instance.
  89411. * \param file An open FLAC file. The file should have been
  89412. * opened with mode \c "rb" and rewound. The file
  89413. * becomes owned by the decoder and should not be
  89414. * manipulated by the client while decoding.
  89415. * Unless \a file is \c stdin, it will be closed
  89416. * when FLAC__stream_decoder_finish() is called.
  89417. * Note however that seeking will not work when
  89418. * decoding from \c stdout since it is not seekable.
  89419. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  89420. * pointer must not be \c NULL.
  89421. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  89422. * pointer may be \c NULL if the callback is not
  89423. * desired.
  89424. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  89425. * pointer must not be \c NULL.
  89426. * \param client_data This value will be supplied to callbacks in their
  89427. * \a client_data argument.
  89428. * \assert
  89429. * \code decoder != NULL \endcode
  89430. * \code file != NULL \endcode
  89431. * \retval FLAC__StreamDecoderInitStatus
  89432. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  89433. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  89434. */
  89435. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  89436. FLAC__StreamDecoder *decoder,
  89437. FILE *file,
  89438. FLAC__StreamDecoderWriteCallback write_callback,
  89439. FLAC__StreamDecoderMetadataCallback metadata_callback,
  89440. FLAC__StreamDecoderErrorCallback error_callback,
  89441. void *client_data
  89442. );
  89443. /** Initialize the decoder instance to decode native FLAC files.
  89444. *
  89445. * This flavor of initialization sets up the decoder to decode from a plain
  89446. * native FLAC file. If POSIX fopen() semantics are not sufficient, (for
  89447. * example, with Unicode filenames on Windows), you must use
  89448. * FLAC__stream_decoder_init_FILE(), or FLAC__stream_decoder_init_stream()
  89449. * and provide callbacks for the I/O.
  89450. *
  89451. * This function should be called after FLAC__stream_decoder_new() and
  89452. * FLAC__stream_decoder_set_*() but before any of the
  89453. * FLAC__stream_decoder_process_*() functions. Will set and return the
  89454. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  89455. * if initialization succeeded.
  89456. *
  89457. * \param decoder An uninitialized decoder instance.
  89458. * \param filename The name of the file to decode from. The file will
  89459. * be opened with fopen(). Use \c NULL to decode from
  89460. * \c stdin. Note that \c stdin is not seekable.
  89461. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  89462. * pointer must not be \c NULL.
  89463. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  89464. * pointer may be \c NULL if the callback is not
  89465. * desired.
  89466. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  89467. * pointer must not be \c NULL.
  89468. * \param client_data This value will be supplied to callbacks in their
  89469. * \a client_data argument.
  89470. * \assert
  89471. * \code decoder != NULL \endcode
  89472. * \retval FLAC__StreamDecoderInitStatus
  89473. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  89474. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  89475. */
  89476. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  89477. FLAC__StreamDecoder *decoder,
  89478. const char *filename,
  89479. FLAC__StreamDecoderWriteCallback write_callback,
  89480. FLAC__StreamDecoderMetadataCallback metadata_callback,
  89481. FLAC__StreamDecoderErrorCallback error_callback,
  89482. void *client_data
  89483. );
  89484. /** Initialize the decoder instance to decode Ogg FLAC files.
  89485. *
  89486. * This flavor of initialization sets up the decoder to decode from a plain
  89487. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient, (for
  89488. * example, with Unicode filenames on Windows), you must use
  89489. * FLAC__stream_decoder_init_ogg_FILE(), or FLAC__stream_decoder_init_ogg_stream()
  89490. * and provide callbacks for the I/O.
  89491. *
  89492. * This function should be called after FLAC__stream_decoder_new() and
  89493. * FLAC__stream_decoder_set_*() but before any of the
  89494. * FLAC__stream_decoder_process_*() functions. Will set and return the
  89495. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  89496. * if initialization succeeded.
  89497. *
  89498. * \note Support for Ogg FLAC in the library is optional. If this
  89499. * library has been built without support for Ogg FLAC, this function
  89500. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  89501. *
  89502. * \param decoder An uninitialized decoder instance.
  89503. * \param filename The name of the file to decode from. The file will
  89504. * be opened with fopen(). Use \c NULL to decode from
  89505. * \c stdin. Note that \c stdin is not seekable.
  89506. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  89507. * pointer must not be \c NULL.
  89508. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  89509. * pointer may be \c NULL if the callback is not
  89510. * desired.
  89511. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  89512. * pointer must not be \c NULL.
  89513. * \param client_data This value will be supplied to callbacks in their
  89514. * \a client_data argument.
  89515. * \assert
  89516. * \code decoder != NULL \endcode
  89517. * \retval FLAC__StreamDecoderInitStatus
  89518. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  89519. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  89520. */
  89521. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  89522. FLAC__StreamDecoder *decoder,
  89523. const char *filename,
  89524. FLAC__StreamDecoderWriteCallback write_callback,
  89525. FLAC__StreamDecoderMetadataCallback metadata_callback,
  89526. FLAC__StreamDecoderErrorCallback error_callback,
  89527. void *client_data
  89528. );
  89529. /** Finish the decoding process.
  89530. * Flushes the decoding buffer, releases resources, resets the decoder
  89531. * settings to their defaults, and returns the decoder state to
  89532. * FLAC__STREAM_DECODER_UNINITIALIZED.
  89533. *
  89534. * In the event of a prematurely-terminated decode, it is not strictly
  89535. * necessary to call this immediately before FLAC__stream_decoder_delete()
  89536. * but it is good practice to match every FLAC__stream_decoder_init_*()
  89537. * with a FLAC__stream_decoder_finish().
  89538. *
  89539. * \param decoder An uninitialized decoder instance.
  89540. * \assert
  89541. * \code decoder != NULL \endcode
  89542. * \retval FLAC__bool
  89543. * \c false if MD5 checking is on AND a STREAMINFO block was available
  89544. * AND the MD5 signature in the STREAMINFO block was non-zero AND the
  89545. * signature does not match the one computed by the decoder; else
  89546. * \c true.
  89547. */
  89548. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder);
  89549. /** Flush the stream input.
  89550. * The decoder's input buffer will be cleared and the state set to
  89551. * \c FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC. This will also turn
  89552. * off MD5 checking.
  89553. *
  89554. * \param decoder A decoder instance.
  89555. * \assert
  89556. * \code decoder != NULL \endcode
  89557. * \retval FLAC__bool
  89558. * \c true if successful, else \c false if a memory allocation
  89559. * error occurs (in which case the state will be set to
  89560. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR).
  89561. */
  89562. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder);
  89563. /** Reset the decoding process.
  89564. * The decoder's input buffer will be cleared and the state set to
  89565. * \c FLAC__STREAM_DECODER_SEARCH_FOR_METADATA. This is similar to
  89566. * FLAC__stream_decoder_finish() except that the settings are
  89567. * preserved; there is no need to call FLAC__stream_decoder_init_*()
  89568. * before decoding again. MD5 checking will be restored to its original
  89569. * setting.
  89570. *
  89571. * If the decoder is seekable, or was initialized with
  89572. * FLAC__stream_decoder_init*_FILE() or FLAC__stream_decoder_init*_file(),
  89573. * the decoder will also attempt to seek to the beginning of the file.
  89574. * If this rewind fails, this function will return \c false. It follows
  89575. * that FLAC__stream_decoder_reset() cannot be used when decoding from
  89576. * \c stdin.
  89577. *
  89578. * If the decoder was initialized with FLAC__stream_encoder_init*_stream()
  89579. * and is not seekable (i.e. no seek callback was provided or the seek
  89580. * callback returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED), it
  89581. * is the duty of the client to start feeding data from the beginning of
  89582. * the stream on the next FLAC__stream_decoder_process() or
  89583. * FLAC__stream_decoder_process_interleaved() call.
  89584. *
  89585. * \param decoder A decoder instance.
  89586. * \assert
  89587. * \code decoder != NULL \endcode
  89588. * \retval FLAC__bool
  89589. * \c true if successful, else \c false if a memory allocation occurs
  89590. * (in which case the state will be set to
  89591. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR) or a seek error
  89592. * occurs (the state will be unchanged).
  89593. */
  89594. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder);
  89595. /** Decode one metadata block or audio frame.
  89596. * This version instructs the decoder to decode a either a single metadata
  89597. * block or a single frame and stop, unless the callbacks return a fatal
  89598. * error or the read callback returns
  89599. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  89600. *
  89601. * As the decoder needs more input it will call the read callback.
  89602. * Depending on what was decoded, the metadata or write callback will be
  89603. * called with the decoded metadata block or audio frame.
  89604. *
  89605. * Unless there is a fatal read error or end of stream, this function
  89606. * will return once one whole frame is decoded. In other words, if the
  89607. * stream is not synchronized or points to a corrupt frame header, the
  89608. * decoder will continue to try and resync until it gets to a valid
  89609. * frame, then decode one frame, then return. If the decoder points to
  89610. * a frame whose frame CRC in the frame footer does not match the
  89611. * computed frame CRC, this function will issue a
  89612. * FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH error to the
  89613. * error callback, and return, having decoded one complete, although
  89614. * corrupt, frame. (Such corrupted frames are sent as silence of the
  89615. * correct length to the write callback.)
  89616. *
  89617. * \param decoder An initialized decoder instance.
  89618. * \assert
  89619. * \code decoder != NULL \endcode
  89620. * \retval FLAC__bool
  89621. * \c false if any fatal read, write, or memory allocation error
  89622. * occurred (meaning decoding must stop), else \c true; for more
  89623. * information about the decoder, check the decoder state with
  89624. * FLAC__stream_decoder_get_state().
  89625. */
  89626. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder);
  89627. /** Decode until the end of the metadata.
  89628. * This version instructs the decoder to decode from the current position
  89629. * and continue until all the metadata has been read, or until the
  89630. * callbacks return a fatal error or the read callback returns
  89631. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  89632. *
  89633. * As the decoder needs more input it will call the read callback.
  89634. * As each metadata block is decoded, the metadata callback will be called
  89635. * with the decoded metadata.
  89636. *
  89637. * \param decoder An initialized decoder instance.
  89638. * \assert
  89639. * \code decoder != NULL \endcode
  89640. * \retval FLAC__bool
  89641. * \c false if any fatal read, write, or memory allocation error
  89642. * occurred (meaning decoding must stop), else \c true; for more
  89643. * information about the decoder, check the decoder state with
  89644. * FLAC__stream_decoder_get_state().
  89645. */
  89646. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder);
  89647. /** Decode until the end of the stream.
  89648. * This version instructs the decoder to decode from the current position
  89649. * and continue until the end of stream (the read callback returns
  89650. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM), or until the
  89651. * callbacks return a fatal error.
  89652. *
  89653. * As the decoder needs more input it will call the read callback.
  89654. * As each metadata block and frame is decoded, the metadata or write
  89655. * callback will be called with the decoded metadata or frame.
  89656. *
  89657. * \param decoder An initialized decoder instance.
  89658. * \assert
  89659. * \code decoder != NULL \endcode
  89660. * \retval FLAC__bool
  89661. * \c false if any fatal read, write, or memory allocation error
  89662. * occurred (meaning decoding must stop), else \c true; for more
  89663. * information about the decoder, check the decoder state with
  89664. * FLAC__stream_decoder_get_state().
  89665. */
  89666. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder);
  89667. /** Skip one audio frame.
  89668. * This version instructs the decoder to 'skip' a single frame and stop,
  89669. * unless the callbacks return a fatal error or the read callback returns
  89670. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  89671. *
  89672. * The decoding flow is the same as what occurs when
  89673. * FLAC__stream_decoder_process_single() is called to process an audio
  89674. * frame, except that this function does not decode the parsed data into
  89675. * PCM or call the write callback. The integrity of the frame is still
  89676. * checked the same way as in the other process functions.
  89677. *
  89678. * This function will return once one whole frame is skipped, in the
  89679. * same way that FLAC__stream_decoder_process_single() will return once
  89680. * one whole frame is decoded.
  89681. *
  89682. * This function can be used in more quickly determining FLAC frame
  89683. * boundaries when decoding of the actual data is not needed, for
  89684. * example when an application is separating a FLAC stream into frames
  89685. * for editing or storing in a container. To do this, the application
  89686. * can use FLAC__stream_decoder_skip_single_frame() to quickly advance
  89687. * to the next frame, then use
  89688. * FLAC__stream_decoder_get_decode_position() to find the new frame
  89689. * boundary.
  89690. *
  89691. * This function should only be called when the stream has advanced
  89692. * past all the metadata, otherwise it will return \c false.
  89693. *
  89694. * \param decoder An initialized decoder instance not in a metadata
  89695. * state.
  89696. * \assert
  89697. * \code decoder != NULL \endcode
  89698. * \retval FLAC__bool
  89699. * \c false if any fatal read, write, or memory allocation error
  89700. * occurred (meaning decoding must stop), or if the decoder
  89701. * is in the FLAC__STREAM_DECODER_SEARCH_FOR_METADATA or
  89702. * FLAC__STREAM_DECODER_READ_METADATA state, else \c true; for more
  89703. * information about the decoder, check the decoder state with
  89704. * FLAC__stream_decoder_get_state().
  89705. */
  89706. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder);
  89707. /** Flush the input and seek to an absolute sample.
  89708. * Decoding will resume at the given sample. Note that because of
  89709. * this, the next write callback may contain a partial block. The
  89710. * client must support seeking the input or this function will fail
  89711. * and return \c false. Furthermore, if the decoder state is
  89712. * \c FLAC__STREAM_DECODER_SEEK_ERROR, then the decoder must be flushed
  89713. * with FLAC__stream_decoder_flush() or reset with
  89714. * FLAC__stream_decoder_reset() before decoding can continue.
  89715. *
  89716. * \param decoder A decoder instance.
  89717. * \param sample The target sample number to seek to.
  89718. * \assert
  89719. * \code decoder != NULL \endcode
  89720. * \retval FLAC__bool
  89721. * \c true if successful, else \c false.
  89722. */
  89723. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample);
  89724. /* \} */
  89725. #ifdef __cplusplus
  89726. }
  89727. #endif
  89728. #endif
  89729. /*** End of inlined file: stream_decoder.h ***/
  89730. /*** Start of inlined file: stream_encoder.h ***/
  89731. #ifndef FLAC__STREAM_ENCODER_H
  89732. #define FLAC__STREAM_ENCODER_H
  89733. #include <stdio.h> /* for FILE */
  89734. #ifdef __cplusplus
  89735. extern "C" {
  89736. #endif
  89737. /** \file include/FLAC/stream_encoder.h
  89738. *
  89739. * \brief
  89740. * This module contains the functions which implement the stream
  89741. * encoder.
  89742. *
  89743. * See the detailed documentation in the
  89744. * \link flac_stream_encoder stream encoder \endlink module.
  89745. */
  89746. /** \defgroup flac_encoder FLAC/ \*_encoder.h: encoder interfaces
  89747. * \ingroup flac
  89748. *
  89749. * \brief
  89750. * This module describes the encoder layers provided by libFLAC.
  89751. *
  89752. * The stream encoder can be used to encode complete streams either to the
  89753. * client via callbacks, or directly to a file, depending on how it is
  89754. * initialized. When encoding via callbacks, the client provides a write
  89755. * callback which will be called whenever FLAC data is ready to be written.
  89756. * If the client also supplies a seek callback, the encoder will also
  89757. * automatically handle the writing back of metadata discovered while
  89758. * encoding, like stream info, seek points offsets, etc. When encoding to
  89759. * a file, the client needs only supply a filename or open \c FILE* and an
  89760. * optional progress callback for periodic notification of progress; the
  89761. * write and seek callbacks are supplied internally. For more info see the
  89762. * \link flac_stream_encoder stream encoder \endlink module.
  89763. */
  89764. /** \defgroup flac_stream_encoder FLAC/stream_encoder.h: stream encoder interface
  89765. * \ingroup flac_encoder
  89766. *
  89767. * \brief
  89768. * This module contains the functions which implement the stream
  89769. * encoder.
  89770. *
  89771. * The stream encoder can encode to native FLAC, and optionally Ogg FLAC
  89772. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  89773. *
  89774. * The basic usage of this encoder is as follows:
  89775. * - The program creates an instance of an encoder using
  89776. * FLAC__stream_encoder_new().
  89777. * - The program overrides the default settings using
  89778. * FLAC__stream_encoder_set_*() functions. At a minimum, the following
  89779. * functions should be called:
  89780. * - FLAC__stream_encoder_set_channels()
  89781. * - FLAC__stream_encoder_set_bits_per_sample()
  89782. * - FLAC__stream_encoder_set_sample_rate()
  89783. * - FLAC__stream_encoder_set_ogg_serial_number() (if encoding to Ogg FLAC)
  89784. * - FLAC__stream_encoder_set_total_samples_estimate() (if known)
  89785. * - If the application wants to control the compression level or set its own
  89786. * metadata, then the following should also be called:
  89787. * - FLAC__stream_encoder_set_compression_level()
  89788. * - FLAC__stream_encoder_set_verify()
  89789. * - FLAC__stream_encoder_set_metadata()
  89790. * - The rest of the set functions should only be called if the client needs
  89791. * exact control over how the audio is compressed; thorough understanding
  89792. * of the FLAC format is necessary to achieve good results.
  89793. * - The program initializes the instance to validate the settings and
  89794. * prepare for encoding using
  89795. * - FLAC__stream_encoder_init_stream() or FLAC__stream_encoder_init_FILE()
  89796. * or FLAC__stream_encoder_init_file() for native FLAC
  89797. * - FLAC__stream_encoder_init_ogg_stream() or FLAC__stream_encoder_init_ogg_FILE()
  89798. * or FLAC__stream_encoder_init_ogg_file() for Ogg FLAC
  89799. * - The program calls FLAC__stream_encoder_process() or
  89800. * FLAC__stream_encoder_process_interleaved() to encode data, which
  89801. * subsequently calls the callbacks when there is encoder data ready
  89802. * to be written.
  89803. * - The program finishes the encoding with FLAC__stream_encoder_finish(),
  89804. * which causes the encoder to encode any data still in its input pipe,
  89805. * update the metadata with the final encoding statistics if output
  89806. * seeking is possible, and finally reset the encoder to the
  89807. * uninitialized state.
  89808. * - The instance may be used again or deleted with
  89809. * FLAC__stream_encoder_delete().
  89810. *
  89811. * In more detail, the stream encoder functions similarly to the
  89812. * \link flac_stream_decoder stream decoder \endlink, but has fewer
  89813. * callbacks and more options. Typically the client will create a new
  89814. * instance by calling FLAC__stream_encoder_new(), then set the necessary
  89815. * parameters with FLAC__stream_encoder_set_*(), and initialize it by
  89816. * calling one of the FLAC__stream_encoder_init_*() functions.
  89817. *
  89818. * Unlike the decoders, the stream encoder has many options that can
  89819. * affect the speed and compression ratio. When setting these parameters
  89820. * you should have some basic knowledge of the format (see the
  89821. * <A HREF="../documentation.html#format">user-level documentation</A>
  89822. * or the <A HREF="../format.html">formal description</A>). The
  89823. * FLAC__stream_encoder_set_*() functions themselves do not validate the
  89824. * values as many are interdependent. The FLAC__stream_encoder_init_*()
  89825. * functions will do this, so make sure to pay attention to the state
  89826. * returned by FLAC__stream_encoder_init_*() to make sure that it is
  89827. * FLAC__STREAM_ENCODER_INIT_STATUS_OK. Any parameters that are not set
  89828. * before FLAC__stream_encoder_init_*() will take on the defaults from
  89829. * the constructor.
  89830. *
  89831. * There are three initialization functions for native FLAC, one for
  89832. * setting up the encoder to encode FLAC data to the client via
  89833. * callbacks, and two for encoding directly to a file.
  89834. *
  89835. * For encoding via callbacks, use FLAC__stream_encoder_init_stream().
  89836. * You must also supply a write callback which will be called anytime
  89837. * there is raw encoded data to write. If the client can seek the output
  89838. * it is best to also supply seek and tell callbacks, as this allows the
  89839. * encoder to go back after encoding is finished to write back
  89840. * information that was collected while encoding, like seek point offsets,
  89841. * frame sizes, etc.
  89842. *
  89843. * For encoding directly to a file, use FLAC__stream_encoder_init_FILE()
  89844. * or FLAC__stream_encoder_init_file(). Then you must only supply a
  89845. * filename or open \c FILE*; the encoder will handle all the callbacks
  89846. * internally. You may also supply a progress callback for periodic
  89847. * notification of the encoding progress.
  89848. *
  89849. * There are three similarly-named init functions for encoding to Ogg
  89850. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  89851. * library has been built with Ogg support.
  89852. *
  89853. * The call to FLAC__stream_encoder_init_*() currently will also immediately
  89854. * call the write callback several times, once with the \c fLaC signature,
  89855. * and once for each encoded metadata block. Note that for Ogg FLAC
  89856. * encoding you will usually get at least twice the number of callbacks than
  89857. * with native FLAC, one for the Ogg page header and one for the page body.
  89858. *
  89859. * After initializing the instance, the client may feed audio data to the
  89860. * encoder in one of two ways:
  89861. *
  89862. * - Channel separate, through FLAC__stream_encoder_process() - The client
  89863. * will pass an array of pointers to buffers, one for each channel, to
  89864. * the encoder, each of the same length. The samples need not be
  89865. * block-aligned, but each channel should have the same number of samples.
  89866. * - Channel interleaved, through
  89867. * FLAC__stream_encoder_process_interleaved() - The client will pass a single
  89868. * pointer to data that is channel-interleaved (i.e. channel0_sample0,
  89869. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  89870. * Again, the samples need not be block-aligned but they must be
  89871. * sample-aligned, i.e. the first value should be channel0_sample0 and
  89872. * the last value channelN_sampleM.
  89873. *
  89874. * Note that for either process call, each sample in the buffers should be a
  89875. * signed integer, right-justified to the resolution set by
  89876. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the resolution
  89877. * is 16 bits per sample, the samples should all be in the range [-32768,32767].
  89878. *
  89879. * When the client is finished encoding data, it calls
  89880. * FLAC__stream_encoder_finish(), which causes the encoder to encode any
  89881. * data still in its input pipe, and call the metadata callback with the
  89882. * final encoding statistics. Then the instance may be deleted with
  89883. * FLAC__stream_encoder_delete() or initialized again to encode another
  89884. * stream.
  89885. *
  89886. * For programs that write their own metadata, but that do not know the
  89887. * actual metadata until after encoding, it is advantageous to instruct
  89888. * the encoder to write a PADDING block of the correct size, so that
  89889. * instead of rewriting the whole stream after encoding, the program can
  89890. * just overwrite the PADDING block. If only the maximum size of the
  89891. * metadata is known, the program can write a slightly larger padding
  89892. * block, then split it after encoding.
  89893. *
  89894. * Make sure you understand how lengths are calculated. All FLAC metadata
  89895. * blocks have a 4 byte header which contains the type and length. This
  89896. * length does not include the 4 bytes of the header. See the format page
  89897. * for the specification of metadata blocks and their lengths.
  89898. *
  89899. * \note
  89900. * If you are writing the FLAC data to a file via callbacks, make sure it
  89901. * is open for update (e.g. mode "w+" for stdio streams). This is because
  89902. * after the first encoding pass, the encoder will try to seek back to the
  89903. * beginning of the stream, to the STREAMINFO block, to write some data
  89904. * there. (If using FLAC__stream_encoder_init*_file() or
  89905. * FLAC__stream_encoder_init*_FILE(), the file is managed internally.)
  89906. *
  89907. * \note
  89908. * The "set" functions may only be called when the encoder is in the
  89909. * state FLAC__STREAM_ENCODER_UNINITIALIZED, i.e. after
  89910. * FLAC__stream_encoder_new() or FLAC__stream_encoder_finish(), but
  89911. * before FLAC__stream_encoder_init_*(). If this is the case they will
  89912. * return \c true, otherwise \c false.
  89913. *
  89914. * \note
  89915. * FLAC__stream_encoder_finish() resets all settings to the constructor
  89916. * defaults.
  89917. *
  89918. * \{
  89919. */
  89920. /** State values for a FLAC__StreamEncoder.
  89921. *
  89922. * The encoder's state can be obtained by calling FLAC__stream_encoder_get_state().
  89923. *
  89924. * If the encoder gets into any other state besides \c FLAC__STREAM_ENCODER_OK
  89925. * or \c FLAC__STREAM_ENCODER_UNINITIALIZED, it becomes invalid for encoding and
  89926. * must be deleted with FLAC__stream_encoder_delete().
  89927. */
  89928. typedef enum {
  89929. FLAC__STREAM_ENCODER_OK = 0,
  89930. /**< The encoder is in the normal OK state and samples can be processed. */
  89931. FLAC__STREAM_ENCODER_UNINITIALIZED,
  89932. /**< The encoder is in the uninitialized state; one of the
  89933. * FLAC__stream_encoder_init_*() functions must be called before samples
  89934. * can be processed.
  89935. */
  89936. FLAC__STREAM_ENCODER_OGG_ERROR,
  89937. /**< An error occurred in the underlying Ogg layer. */
  89938. FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR,
  89939. /**< An error occurred in the underlying verify stream decoder;
  89940. * check FLAC__stream_encoder_get_verify_decoder_state().
  89941. */
  89942. FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA,
  89943. /**< The verify decoder detected a mismatch between the original
  89944. * audio signal and the decoded audio signal.
  89945. */
  89946. FLAC__STREAM_ENCODER_CLIENT_ERROR,
  89947. /**< One of the callbacks returned a fatal error. */
  89948. FLAC__STREAM_ENCODER_IO_ERROR,
  89949. /**< An I/O error occurred while opening/reading/writing a file.
  89950. * Check \c errno.
  89951. */
  89952. FLAC__STREAM_ENCODER_FRAMING_ERROR,
  89953. /**< An error occurred while writing the stream; usually, the
  89954. * write_callback returned an error.
  89955. */
  89956. FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR
  89957. /**< Memory allocation failed. */
  89958. } FLAC__StreamEncoderState;
  89959. /** Maps a FLAC__StreamEncoderState to a C string.
  89960. *
  89961. * Using a FLAC__StreamEncoderState as the index to this array
  89962. * will give the string equivalent. The contents should not be modified.
  89963. */
  89964. extern FLAC_API const char * const FLAC__StreamEncoderStateString[];
  89965. /** Possible return values for the FLAC__stream_encoder_init_*() functions.
  89966. */
  89967. typedef enum {
  89968. FLAC__STREAM_ENCODER_INIT_STATUS_OK = 0,
  89969. /**< Initialization was successful. */
  89970. FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR,
  89971. /**< General failure to set up encoder; call FLAC__stream_encoder_get_state() for cause. */
  89972. FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  89973. /**< The library was not compiled with support for the given container
  89974. * format.
  89975. */
  89976. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS,
  89977. /**< A required callback was not supplied. */
  89978. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS,
  89979. /**< The encoder has an invalid setting for number of channels. */
  89980. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE,
  89981. /**< The encoder has an invalid setting for bits-per-sample.
  89982. * FLAC supports 4-32 bps but the reference encoder currently supports
  89983. * only up to 24 bps.
  89984. */
  89985. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE,
  89986. /**< The encoder has an invalid setting for the input sample rate. */
  89987. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE,
  89988. /**< The encoder has an invalid setting for the block size. */
  89989. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER,
  89990. /**< The encoder has an invalid setting for the maximum LPC order. */
  89991. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION,
  89992. /**< The encoder has an invalid setting for the precision of the quantized linear predictor coefficients. */
  89993. FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER,
  89994. /**< The specified block size is less than the maximum LPC order. */
  89995. FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE,
  89996. /**< The encoder is bound to the <A HREF="../format.html#subset">Subset</A> but other settings violate it. */
  89997. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA,
  89998. /**< The metadata input to the encoder is invalid, in one of the following ways:
  89999. * - FLAC__stream_encoder_set_metadata() was called with a null pointer but a block count > 0
  90000. * - One of the metadata blocks contains an undefined type
  90001. * - It contains an illegal CUESHEET as checked by FLAC__format_cuesheet_is_legal()
  90002. * - It contains an illegal SEEKTABLE as checked by FLAC__format_seektable_is_legal()
  90003. * - It contains more than one SEEKTABLE block or more than one VORBIS_COMMENT block
  90004. */
  90005. FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED
  90006. /**< FLAC__stream_encoder_init_*() was called when the encoder was
  90007. * already initialized, usually because
  90008. * FLAC__stream_encoder_finish() was not called.
  90009. */
  90010. } FLAC__StreamEncoderInitStatus;
  90011. /** Maps a FLAC__StreamEncoderInitStatus to a C string.
  90012. *
  90013. * Using a FLAC__StreamEncoderInitStatus as the index to this array
  90014. * will give the string equivalent. The contents should not be modified.
  90015. */
  90016. extern FLAC_API const char * const FLAC__StreamEncoderInitStatusString[];
  90017. /** Return values for the FLAC__StreamEncoder read callback.
  90018. */
  90019. typedef enum {
  90020. FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE,
  90021. /**< The read was OK and decoding can continue. */
  90022. FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM,
  90023. /**< The read was attempted at the end of the stream. */
  90024. FLAC__STREAM_ENCODER_READ_STATUS_ABORT,
  90025. /**< An unrecoverable error occurred. */
  90026. FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED
  90027. /**< Client does not support reading back from the output. */
  90028. } FLAC__StreamEncoderReadStatus;
  90029. /** Maps a FLAC__StreamEncoderReadStatus to a C string.
  90030. *
  90031. * Using a FLAC__StreamEncoderReadStatus as the index to this array
  90032. * will give the string equivalent. The contents should not be modified.
  90033. */
  90034. extern FLAC_API const char * const FLAC__StreamEncoderReadStatusString[];
  90035. /** Return values for the FLAC__StreamEncoder write callback.
  90036. */
  90037. typedef enum {
  90038. FLAC__STREAM_ENCODER_WRITE_STATUS_OK = 0,
  90039. /**< The write was OK and encoding can continue. */
  90040. FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR
  90041. /**< An unrecoverable error occurred. The encoder will return from the process call. */
  90042. } FLAC__StreamEncoderWriteStatus;
  90043. /** Maps a FLAC__StreamEncoderWriteStatus to a C string.
  90044. *
  90045. * Using a FLAC__StreamEncoderWriteStatus as the index to this array
  90046. * will give the string equivalent. The contents should not be modified.
  90047. */
  90048. extern FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[];
  90049. /** Return values for the FLAC__StreamEncoder seek callback.
  90050. */
  90051. typedef enum {
  90052. FLAC__STREAM_ENCODER_SEEK_STATUS_OK,
  90053. /**< The seek was OK and encoding can continue. */
  90054. FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR,
  90055. /**< An unrecoverable error occurred. */
  90056. FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  90057. /**< Client does not support seeking. */
  90058. } FLAC__StreamEncoderSeekStatus;
  90059. /** Maps a FLAC__StreamEncoderSeekStatus to a C string.
  90060. *
  90061. * Using a FLAC__StreamEncoderSeekStatus as the index to this array
  90062. * will give the string equivalent. The contents should not be modified.
  90063. */
  90064. extern FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[];
  90065. /** Return values for the FLAC__StreamEncoder tell callback.
  90066. */
  90067. typedef enum {
  90068. FLAC__STREAM_ENCODER_TELL_STATUS_OK,
  90069. /**< The tell was OK and encoding can continue. */
  90070. FLAC__STREAM_ENCODER_TELL_STATUS_ERROR,
  90071. /**< An unrecoverable error occurred. */
  90072. FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  90073. /**< Client does not support seeking. */
  90074. } FLAC__StreamEncoderTellStatus;
  90075. /** Maps a FLAC__StreamEncoderTellStatus to a C string.
  90076. *
  90077. * Using a FLAC__StreamEncoderTellStatus as the index to this array
  90078. * will give the string equivalent. The contents should not be modified.
  90079. */
  90080. extern FLAC_API const char * const FLAC__StreamEncoderTellStatusString[];
  90081. /***********************************************************************
  90082. *
  90083. * class FLAC__StreamEncoder
  90084. *
  90085. ***********************************************************************/
  90086. struct FLAC__StreamEncoderProtected;
  90087. struct FLAC__StreamEncoderPrivate;
  90088. /** The opaque structure definition for the stream encoder type.
  90089. * See the \link flac_stream_encoder stream encoder module \endlink
  90090. * for a detailed description.
  90091. */
  90092. typedef struct {
  90093. struct FLAC__StreamEncoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  90094. struct FLAC__StreamEncoderPrivate *private_; /* avoid the C++ keyword 'private' */
  90095. } FLAC__StreamEncoder;
  90096. /** Signature for the read callback.
  90097. *
  90098. * A function pointer matching this signature must be passed to
  90099. * FLAC__stream_encoder_init_ogg_stream() if seeking is supported.
  90100. * The supplied function will be called when the encoder needs to read back
  90101. * encoded data. This happens during the metadata callback, when the encoder
  90102. * has to read, modify, and rewrite the metadata (e.g. seekpoints) gathered
  90103. * while encoding. The address of the buffer to be filled is supplied, along
  90104. * with the number of bytes the buffer can hold. The callback may choose to
  90105. * supply less data and modify the byte count but must be careful not to
  90106. * overflow the buffer. The callback then returns a status code chosen from
  90107. * FLAC__StreamEncoderReadStatus.
  90108. *
  90109. * Here is an example of a read callback for stdio streams:
  90110. * \code
  90111. * FLAC__StreamEncoderReadStatus read_cb(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  90112. * {
  90113. * FILE *file = ((MyClientData*)client_data)->file;
  90114. * if(*bytes > 0) {
  90115. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  90116. * if(ferror(file))
  90117. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  90118. * else if(*bytes == 0)
  90119. * return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  90120. * else
  90121. * return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  90122. * }
  90123. * else
  90124. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  90125. * }
  90126. * \endcode
  90127. *
  90128. * \note In general, FLAC__StreamEncoder functions which change the
  90129. * state should not be called on the \a encoder while in the callback.
  90130. *
  90131. * \param encoder The encoder instance calling the callback.
  90132. * \param buffer A pointer to a location for the callee to store
  90133. * data to be encoded.
  90134. * \param bytes A pointer to the size of the buffer. On entry
  90135. * to the callback, it contains the maximum number
  90136. * of bytes that may be stored in \a buffer. The
  90137. * callee must set it to the actual number of bytes
  90138. * stored (0 in case of error or end-of-stream) before
  90139. * returning.
  90140. * \param client_data The callee's client data set through
  90141. * FLAC__stream_encoder_set_client_data().
  90142. * \retval FLAC__StreamEncoderReadStatus
  90143. * The callee's return status.
  90144. */
  90145. typedef FLAC__StreamEncoderReadStatus (*FLAC__StreamEncoderReadCallback)(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  90146. /** Signature for the write callback.
  90147. *
  90148. * A function pointer matching this signature must be passed to
  90149. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  90150. * by the encoder anytime there is raw encoded data ready to write. It may
  90151. * include metadata mixed with encoded audio frames and the data is not
  90152. * guaranteed to be aligned on frame or metadata block boundaries.
  90153. *
  90154. * The only duty of the callback is to write out the \a bytes worth of data
  90155. * in \a buffer to the current position in the output stream. The arguments
  90156. * \a samples and \a current_frame are purely informational. If \a samples
  90157. * is greater than \c 0, then \a current_frame will hold the current frame
  90158. * number that is being written; otherwise it indicates that the write
  90159. * callback is being called to write metadata.
  90160. *
  90161. * \note
  90162. * Unlike when writing to native FLAC, when writing to Ogg FLAC the
  90163. * write callback will be called twice when writing each audio
  90164. * frame; once for the page header, and once for the page body.
  90165. * When writing the page header, the \a samples argument to the
  90166. * write callback will be \c 0.
  90167. *
  90168. * \note In general, FLAC__StreamEncoder functions which change the
  90169. * state should not be called on the \a encoder while in the callback.
  90170. *
  90171. * \param encoder The encoder instance calling the callback.
  90172. * \param buffer An array of encoded data of length \a bytes.
  90173. * \param bytes The byte length of \a buffer.
  90174. * \param samples The number of samples encoded by \a buffer.
  90175. * \c 0 has a special meaning; see above.
  90176. * \param current_frame The number of the current frame being encoded.
  90177. * \param client_data The callee's client data set through
  90178. * FLAC__stream_encoder_init_*().
  90179. * \retval FLAC__StreamEncoderWriteStatus
  90180. * The callee's return status.
  90181. */
  90182. typedef FLAC__StreamEncoderWriteStatus (*FLAC__StreamEncoderWriteCallback)(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data);
  90183. /** Signature for the seek callback.
  90184. *
  90185. * A function pointer matching this signature may be passed to
  90186. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  90187. * when the encoder needs to seek the output stream. The encoder will pass
  90188. * the absolute byte offset to seek to, 0 meaning the beginning of the stream.
  90189. *
  90190. * Here is an example of a seek callback for stdio streams:
  90191. * \code
  90192. * FLAC__StreamEncoderSeekStatus seek_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  90193. * {
  90194. * FILE *file = ((MyClientData*)client_data)->file;
  90195. * if(file == stdin)
  90196. * return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  90197. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  90198. * return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  90199. * else
  90200. * return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  90201. * }
  90202. * \endcode
  90203. *
  90204. * \note In general, FLAC__StreamEncoder functions which change the
  90205. * state should not be called on the \a encoder while in the callback.
  90206. *
  90207. * \param encoder The encoder instance calling the callback.
  90208. * \param absolute_byte_offset The offset from the beginning of the stream
  90209. * to seek to.
  90210. * \param client_data The callee's client data set through
  90211. * FLAC__stream_encoder_init_*().
  90212. * \retval FLAC__StreamEncoderSeekStatus
  90213. * The callee's return status.
  90214. */
  90215. typedef FLAC__StreamEncoderSeekStatus (*FLAC__StreamEncoderSeekCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  90216. /** Signature for the tell callback.
  90217. *
  90218. * A function pointer matching this signature may be passed to
  90219. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  90220. * when the encoder needs to know the current position of the output stream.
  90221. *
  90222. * \warning
  90223. * The callback must return the true current byte offset of the output to
  90224. * which the encoder is writing. If you are buffering the output, make
  90225. * sure and take this into account. If you are writing directly to a
  90226. * FILE* from your write callback, ftell() is sufficient. If you are
  90227. * writing directly to a file descriptor from your write callback, you
  90228. * can use lseek(fd, SEEK_CUR, 0). The encoder may later seek back to
  90229. * these points to rewrite metadata after encoding.
  90230. *
  90231. * Here is an example of a tell callback for stdio streams:
  90232. * \code
  90233. * FLAC__StreamEncoderTellStatus tell_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  90234. * {
  90235. * FILE *file = ((MyClientData*)client_data)->file;
  90236. * off_t pos;
  90237. * if(file == stdin)
  90238. * return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  90239. * else if((pos = ftello(file)) < 0)
  90240. * return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  90241. * else {
  90242. * *absolute_byte_offset = (FLAC__uint64)pos;
  90243. * return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  90244. * }
  90245. * }
  90246. * \endcode
  90247. *
  90248. * \note In general, FLAC__StreamEncoder functions which change the
  90249. * state should not be called on the \a encoder while in the callback.
  90250. *
  90251. * \param encoder The encoder instance calling the callback.
  90252. * \param absolute_byte_offset The address at which to store the current
  90253. * position of the output.
  90254. * \param client_data The callee's client data set through
  90255. * FLAC__stream_encoder_init_*().
  90256. * \retval FLAC__StreamEncoderTellStatus
  90257. * The callee's return status.
  90258. */
  90259. typedef FLAC__StreamEncoderTellStatus (*FLAC__StreamEncoderTellCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  90260. /** Signature for the metadata callback.
  90261. *
  90262. * A function pointer matching this signature may be passed to
  90263. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  90264. * once at the end of encoding with the populated STREAMINFO structure. This
  90265. * is so the client can seek back to the beginning of the file and write the
  90266. * STREAMINFO block with the correct statistics after encoding (like
  90267. * minimum/maximum frame size and total samples).
  90268. *
  90269. * \note In general, FLAC__StreamEncoder functions which change the
  90270. * state should not be called on the \a encoder while in the callback.
  90271. *
  90272. * \param encoder The encoder instance calling the callback.
  90273. * \param metadata The final populated STREAMINFO block.
  90274. * \param client_data The callee's client data set through
  90275. * FLAC__stream_encoder_init_*().
  90276. */
  90277. typedef void (*FLAC__StreamEncoderMetadataCallback)(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data);
  90278. /** Signature for the progress callback.
  90279. *
  90280. * A function pointer matching this signature may be passed to
  90281. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE().
  90282. * The supplied function will be called when the encoder has finished
  90283. * writing a frame. The \c total_frames_estimate argument to the
  90284. * callback will be based on the value from
  90285. * FLAC__stream_encoder_set_total_samples_estimate().
  90286. *
  90287. * \note In general, FLAC__StreamEncoder functions which change the
  90288. * state should not be called on the \a encoder while in the callback.
  90289. *
  90290. * \param encoder The encoder instance calling the callback.
  90291. * \param bytes_written Bytes written so far.
  90292. * \param samples_written Samples written so far.
  90293. * \param frames_written Frames written so far.
  90294. * \param total_frames_estimate The estimate of the total number of
  90295. * frames to be written.
  90296. * \param client_data The callee's client data set through
  90297. * FLAC__stream_encoder_init_*().
  90298. */
  90299. 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);
  90300. /***********************************************************************
  90301. *
  90302. * Class constructor/destructor
  90303. *
  90304. ***********************************************************************/
  90305. /** Create a new stream encoder instance. The instance is created with
  90306. * default settings; see the individual FLAC__stream_encoder_set_*()
  90307. * functions for each setting's default.
  90308. *
  90309. * \retval FLAC__StreamEncoder*
  90310. * \c NULL if there was an error allocating memory, else the new instance.
  90311. */
  90312. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void);
  90313. /** Free an encoder instance. Deletes the object pointed to by \a encoder.
  90314. *
  90315. * \param encoder A pointer to an existing encoder.
  90316. * \assert
  90317. * \code encoder != NULL \endcode
  90318. */
  90319. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder);
  90320. /***********************************************************************
  90321. *
  90322. * Public class method prototypes
  90323. *
  90324. ***********************************************************************/
  90325. /** Set the serial number for the FLAC stream to use in the Ogg container.
  90326. *
  90327. * \note
  90328. * This does not need to be set for native FLAC encoding.
  90329. *
  90330. * \note
  90331. * It is recommended to set a serial number explicitly as the default of '0'
  90332. * may collide with other streams.
  90333. *
  90334. * \default \c 0
  90335. * \param encoder An encoder instance to set.
  90336. * \param serial_number See above.
  90337. * \assert
  90338. * \code encoder != NULL \endcode
  90339. * \retval FLAC__bool
  90340. * \c false if the encoder is already initialized, else \c true.
  90341. */
  90342. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long serial_number);
  90343. /** Set the "verify" flag. If \c true, the encoder will verify it's own
  90344. * encoded output by feeding it through an internal decoder and comparing
  90345. * the original signal against the decoded signal. If a mismatch occurs,
  90346. * the process call will return \c false. Note that this will slow the
  90347. * encoding process by the extra time required for decoding and comparison.
  90348. *
  90349. * \default \c false
  90350. * \param encoder An encoder instance to set.
  90351. * \param value Flag value (see above).
  90352. * \assert
  90353. * \code encoder != NULL \endcode
  90354. * \retval FLAC__bool
  90355. * \c false if the encoder is already initialized, else \c true.
  90356. */
  90357. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value);
  90358. /** Set the <A HREF="../format.html#subset">Subset</A> flag. If \c true,
  90359. * the encoder will comply with the Subset and will check the
  90360. * settings during FLAC__stream_encoder_init_*() to see if all settings
  90361. * comply. If \c false, the settings may take advantage of the full
  90362. * range that the format allows.
  90363. *
  90364. * Make sure you know what it entails before setting this to \c false.
  90365. *
  90366. * \default \c true
  90367. * \param encoder An encoder instance to set.
  90368. * \param value Flag value (see above).
  90369. * \assert
  90370. * \code encoder != NULL \endcode
  90371. * \retval FLAC__bool
  90372. * \c false if the encoder is already initialized, else \c true.
  90373. */
  90374. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value);
  90375. /** Set the number of channels to be encoded.
  90376. *
  90377. * \default \c 2
  90378. * \param encoder An encoder instance to set.
  90379. * \param value See above.
  90380. * \assert
  90381. * \code encoder != NULL \endcode
  90382. * \retval FLAC__bool
  90383. * \c false if the encoder is already initialized, else \c true.
  90384. */
  90385. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value);
  90386. /** Set the sample resolution of the input to be encoded.
  90387. *
  90388. * \warning
  90389. * Do not feed the encoder data that is wider than the value you
  90390. * set here or you will generate an invalid stream.
  90391. *
  90392. * \default \c 16
  90393. * \param encoder An encoder instance to set.
  90394. * \param value See above.
  90395. * \assert
  90396. * \code encoder != NULL \endcode
  90397. * \retval FLAC__bool
  90398. * \c false if the encoder is already initialized, else \c true.
  90399. */
  90400. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value);
  90401. /** Set the sample rate (in Hz) of the input to be encoded.
  90402. *
  90403. * \default \c 44100
  90404. * \param encoder An encoder instance to set.
  90405. * \param value See above.
  90406. * \assert
  90407. * \code encoder != NULL \endcode
  90408. * \retval FLAC__bool
  90409. * \c false if the encoder is already initialized, else \c true.
  90410. */
  90411. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value);
  90412. /** Set the compression level
  90413. *
  90414. * The compression level is roughly proportional to the amount of effort
  90415. * the encoder expends to compress the file. A higher level usually
  90416. * means more computation but higher compression. The default level is
  90417. * suitable for most applications.
  90418. *
  90419. * Currently the levels range from \c 0 (fastest, least compression) to
  90420. * \c 8 (slowest, most compression). A value larger than \c 8 will be
  90421. * treated as \c 8.
  90422. *
  90423. * This function automatically calls the following other \c _set_
  90424. * functions with appropriate values, so the client does not need to
  90425. * unless it specifically wants to override them:
  90426. * - FLAC__stream_encoder_set_do_mid_side_stereo()
  90427. * - FLAC__stream_encoder_set_loose_mid_side_stereo()
  90428. * - FLAC__stream_encoder_set_apodization()
  90429. * - FLAC__stream_encoder_set_max_lpc_order()
  90430. * - FLAC__stream_encoder_set_qlp_coeff_precision()
  90431. * - FLAC__stream_encoder_set_do_qlp_coeff_prec_search()
  90432. * - FLAC__stream_encoder_set_do_escape_coding()
  90433. * - FLAC__stream_encoder_set_do_exhaustive_model_search()
  90434. * - FLAC__stream_encoder_set_min_residual_partition_order()
  90435. * - FLAC__stream_encoder_set_max_residual_partition_order()
  90436. * - FLAC__stream_encoder_set_rice_parameter_search_dist()
  90437. *
  90438. * The actual values set for each level are:
  90439. * <table>
  90440. * <tr>
  90441. * <td><b>level</b><td>
  90442. * <td>do mid-side stereo<td>
  90443. * <td>loose mid-side stereo<td>
  90444. * <td>apodization<td>
  90445. * <td>max lpc order<td>
  90446. * <td>qlp coeff precision<td>
  90447. * <td>qlp coeff prec search<td>
  90448. * <td>escape coding<td>
  90449. * <td>exhaustive model search<td>
  90450. * <td>min residual partition order<td>
  90451. * <td>max residual partition order<td>
  90452. * <td>rice parameter search dist<td>
  90453. * </tr>
  90454. * <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>
  90455. * <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>
  90456. * <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>
  90457. * <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>
  90458. * <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>
  90459. * <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>
  90460. * <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>
  90461. * <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>
  90462. * <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>
  90463. * </table>
  90464. *
  90465. * \default \c 5
  90466. * \param encoder An encoder instance to set.
  90467. * \param value See above.
  90468. * \assert
  90469. * \code encoder != NULL \endcode
  90470. * \retval FLAC__bool
  90471. * \c false if the encoder is already initialized, else \c true.
  90472. */
  90473. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value);
  90474. /** Set the blocksize to use while encoding.
  90475. *
  90476. * The number of samples to use per frame. Use \c 0 to let the encoder
  90477. * estimate a blocksize; this is usually best.
  90478. *
  90479. * \default \c 0
  90480. * \param encoder An encoder instance to set.
  90481. * \param value See above.
  90482. * \assert
  90483. * \code encoder != NULL \endcode
  90484. * \retval FLAC__bool
  90485. * \c false if the encoder is already initialized, else \c true.
  90486. */
  90487. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value);
  90488. /** Set to \c true to enable mid-side encoding on stereo input. The
  90489. * number of channels must be 2 for this to have any effect. Set to
  90490. * \c false to use only independent channel coding.
  90491. *
  90492. * \default \c false
  90493. * \param encoder An encoder instance to set.
  90494. * \param value Flag value (see above).
  90495. * \assert
  90496. * \code encoder != NULL \endcode
  90497. * \retval FLAC__bool
  90498. * \c false if the encoder is already initialized, else \c true.
  90499. */
  90500. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  90501. /** Set to \c true to enable adaptive switching between mid-side and
  90502. * left-right encoding on stereo input. Set to \c false to use
  90503. * exhaustive searching. Setting this to \c true requires
  90504. * FLAC__stream_encoder_set_do_mid_side_stereo() to also be set to
  90505. * \c true in order to have any effect.
  90506. *
  90507. * \default \c false
  90508. * \param encoder An encoder instance to set.
  90509. * \param value Flag value (see above).
  90510. * \assert
  90511. * \code encoder != NULL \endcode
  90512. * \retval FLAC__bool
  90513. * \c false if the encoder is already initialized, else \c true.
  90514. */
  90515. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  90516. /** Sets the apodization function(s) the encoder will use when windowing
  90517. * audio data for LPC analysis.
  90518. *
  90519. * The \a specification is a plain ASCII string which specifies exactly
  90520. * which functions to use. There may be more than one (up to 32),
  90521. * separated by \c ';' characters. Some functions take one or more
  90522. * comma-separated arguments in parentheses.
  90523. *
  90524. * The available functions are \c bartlett, \c bartlett_hann,
  90525. * \c blackman, \c blackman_harris_4term_92db, \c connes, \c flattop,
  90526. * \c gauss(STDDEV), \c hamming, \c hann, \c kaiser_bessel, \c nuttall,
  90527. * \c rectangle, \c triangle, \c tukey(P), \c welch.
  90528. *
  90529. * For \c gauss(STDDEV), STDDEV specifies the standard deviation
  90530. * (0<STDDEV<=0.5).
  90531. *
  90532. * For \c tukey(P), P specifies the fraction of the window that is
  90533. * tapered (0<=P<=1). P=0 corresponds to \c rectangle and P=1
  90534. * corresponds to \c hann.
  90535. *
  90536. * Example specifications are \c "blackman" or
  90537. * \c "hann;triangle;tukey(0.5);tukey(0.25);tukey(0.125)"
  90538. *
  90539. * Any function that is specified erroneously is silently dropped. Up
  90540. * to 32 functions are kept, the rest are dropped. If the specification
  90541. * is empty the encoder defaults to \c "tukey(0.5)".
  90542. *
  90543. * When more than one function is specified, then for every subframe the
  90544. * encoder will try each of them separately and choose the window that
  90545. * results in the smallest compressed subframe.
  90546. *
  90547. * Note that each function specified causes the encoder to occupy a
  90548. * floating point array in which to store the window.
  90549. *
  90550. * \default \c "tukey(0.5)"
  90551. * \param encoder An encoder instance to set.
  90552. * \param specification See above.
  90553. * \assert
  90554. * \code encoder != NULL \endcode
  90555. * \code specification != NULL \endcode
  90556. * \retval FLAC__bool
  90557. * \c false if the encoder is already initialized, else \c true.
  90558. */
  90559. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification);
  90560. /** Set the maximum LPC order, or \c 0 to use only the fixed predictors.
  90561. *
  90562. * \default \c 0
  90563. * \param encoder An encoder instance to set.
  90564. * \param value See above.
  90565. * \assert
  90566. * \code encoder != NULL \endcode
  90567. * \retval FLAC__bool
  90568. * \c false if the encoder is already initialized, else \c true.
  90569. */
  90570. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value);
  90571. /** Set the precision, in bits, of the quantized linear predictor
  90572. * coefficients, or \c 0 to let the encoder select it based on the
  90573. * blocksize.
  90574. *
  90575. * \note
  90576. * In the current implementation, qlp_coeff_precision + bits_per_sample must
  90577. * be less than 32.
  90578. *
  90579. * \default \c 0
  90580. * \param encoder An encoder instance to set.
  90581. * \param value See above.
  90582. * \assert
  90583. * \code encoder != NULL \endcode
  90584. * \retval FLAC__bool
  90585. * \c false if the encoder is already initialized, else \c true.
  90586. */
  90587. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value);
  90588. /** Set to \c false to use only the specified quantized linear predictor
  90589. * coefficient precision, or \c true to search neighboring precision
  90590. * values and use the best one.
  90591. *
  90592. * \default \c false
  90593. * \param encoder An encoder instance to set.
  90594. * \param value See above.
  90595. * \assert
  90596. * \code encoder != NULL \endcode
  90597. * \retval FLAC__bool
  90598. * \c false if the encoder is already initialized, else \c true.
  90599. */
  90600. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  90601. /** Deprecated. Setting this value has no effect.
  90602. *
  90603. * \default \c false
  90604. * \param encoder An encoder instance to set.
  90605. * \param value See above.
  90606. * \assert
  90607. * \code encoder != NULL \endcode
  90608. * \retval FLAC__bool
  90609. * \c false if the encoder is already initialized, else \c true.
  90610. */
  90611. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value);
  90612. /** Set to \c false to let the encoder estimate the best model order
  90613. * based on the residual signal energy, or \c true to force the
  90614. * encoder to evaluate all order models and select the best.
  90615. *
  90616. * \default \c false
  90617. * \param encoder An encoder instance to set.
  90618. * \param value See above.
  90619. * \assert
  90620. * \code encoder != NULL \endcode
  90621. * \retval FLAC__bool
  90622. * \c false if the encoder is already initialized, else \c true.
  90623. */
  90624. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  90625. /** Set the minimum partition order to search when coding the residual.
  90626. * This is used in tandem with
  90627. * FLAC__stream_encoder_set_max_residual_partition_order().
  90628. *
  90629. * The partition order determines the context size in the residual.
  90630. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  90631. *
  90632. * Set both min and max values to \c 0 to force a single context,
  90633. * whose Rice parameter is based on the residual signal variance.
  90634. * Otherwise, set a min and max order, and the encoder will search
  90635. * all orders, using the mean of each context for its Rice parameter,
  90636. * and use the best.
  90637. *
  90638. * \default \c 0
  90639. * \param encoder An encoder instance to set.
  90640. * \param value See above.
  90641. * \assert
  90642. * \code encoder != NULL \endcode
  90643. * \retval FLAC__bool
  90644. * \c false if the encoder is already initialized, else \c true.
  90645. */
  90646. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  90647. /** Set the maximum partition order to search when coding the residual.
  90648. * This is used in tandem with
  90649. * FLAC__stream_encoder_set_min_residual_partition_order().
  90650. *
  90651. * The partition order determines the context size in the residual.
  90652. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  90653. *
  90654. * Set both min and max values to \c 0 to force a single context,
  90655. * whose Rice parameter is based on the residual signal variance.
  90656. * Otherwise, set a min and max order, and the encoder will search
  90657. * all orders, using the mean of each context for its Rice parameter,
  90658. * and use the best.
  90659. *
  90660. * \default \c 0
  90661. * \param encoder An encoder instance to set.
  90662. * \param value See above.
  90663. * \assert
  90664. * \code encoder != NULL \endcode
  90665. * \retval FLAC__bool
  90666. * \c false if the encoder is already initialized, else \c true.
  90667. */
  90668. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  90669. /** Deprecated. Setting this value has no effect.
  90670. *
  90671. * \default \c 0
  90672. * \param encoder An encoder instance to set.
  90673. * \param value See above.
  90674. * \assert
  90675. * \code encoder != NULL \endcode
  90676. * \retval FLAC__bool
  90677. * \c false if the encoder is already initialized, else \c true.
  90678. */
  90679. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value);
  90680. /** Set an estimate of the total samples that will be encoded.
  90681. * This is merely an estimate and may be set to \c 0 if unknown.
  90682. * This value will be written to the STREAMINFO block before encoding,
  90683. * and can remove the need for the caller to rewrite the value later
  90684. * if the value is known before encoding.
  90685. *
  90686. * \default \c 0
  90687. * \param encoder An encoder instance to set.
  90688. * \param value See above.
  90689. * \assert
  90690. * \code encoder != NULL \endcode
  90691. * \retval FLAC__bool
  90692. * \c false if the encoder is already initialized, else \c true.
  90693. */
  90694. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value);
  90695. /** Set the metadata blocks to be emitted to the stream before encoding.
  90696. * A value of \c NULL, \c 0 implies no metadata; otherwise, supply an
  90697. * array of pointers to metadata blocks. The array is non-const since
  90698. * the encoder may need to change the \a is_last flag inside them, and
  90699. * in some cases update seek point offsets. Otherwise, the encoder will
  90700. * not modify or free the blocks. It is up to the caller to free the
  90701. * metadata blocks after encoding finishes.
  90702. *
  90703. * \note
  90704. * The encoder stores only copies of the pointers in the \a metadata array;
  90705. * the metadata blocks themselves must survive at least until after
  90706. * FLAC__stream_encoder_finish() returns. Do not free the blocks until then.
  90707. *
  90708. * \note
  90709. * The STREAMINFO block is always written and no STREAMINFO block may
  90710. * occur in the supplied array.
  90711. *
  90712. * \note
  90713. * By default the encoder does not create a SEEKTABLE. If one is supplied
  90714. * in the \a metadata array, but the client has specified that it does not
  90715. * support seeking, then the SEEKTABLE will be written verbatim. However
  90716. * by itself this is not very useful as the client will not know the stream
  90717. * offsets for the seekpoints ahead of time. In order to get a proper
  90718. * seektable the client must support seeking. See next note.
  90719. *
  90720. * \note
  90721. * SEEKTABLE blocks are handled specially. Since you will not know
  90722. * the values for the seek point stream offsets, you should pass in
  90723. * a SEEKTABLE 'template', that is, a SEEKTABLE object with the
  90724. * required sample numbers (or placeholder points), with \c 0 for the
  90725. * \a frame_samples and \a stream_offset fields for each point. If the
  90726. * client has specified that it supports seeking by providing a seek
  90727. * callback to FLAC__stream_encoder_init_stream() or both seek AND read
  90728. * callback to FLAC__stream_encoder_init_ogg_stream() (or by using
  90729. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE()),
  90730. * then while it is encoding the encoder will fill the stream offsets in
  90731. * for you and when encoding is finished, it will seek back and write the
  90732. * real values into the SEEKTABLE block in the stream. There are helper
  90733. * routines for manipulating seektable template blocks; see metadata.h:
  90734. * FLAC__metadata_object_seektable_template_*(). If the client does
  90735. * not support seeking, the SEEKTABLE will have inaccurate offsets which
  90736. * will slow down or remove the ability to seek in the FLAC stream.
  90737. *
  90738. * \note
  90739. * The encoder instance \b will modify the first \c SEEKTABLE block
  90740. * as it transforms the template to a valid seektable while encoding,
  90741. * but it is still up to the caller to free all metadata blocks after
  90742. * encoding.
  90743. *
  90744. * \note
  90745. * A VORBIS_COMMENT block may be supplied. The vendor string in it
  90746. * will be ignored. libFLAC will use it's own vendor string. libFLAC
  90747. * will not modify the passed-in VORBIS_COMMENT's vendor string, it
  90748. * will simply write it's own into the stream. If no VORBIS_COMMENT
  90749. * block is present in the \a metadata array, libFLAC will write an
  90750. * empty one, containing only the vendor string.
  90751. *
  90752. * \note The Ogg FLAC mapping requires that the VORBIS_COMMENT block be
  90753. * the second metadata block of the stream. The encoder already supplies
  90754. * the STREAMINFO block automatically. If \a metadata does not contain a
  90755. * VORBIS_COMMENT block, the encoder will supply that too. Otherwise, if
  90756. * \a metadata does contain a VORBIS_COMMENT block and it is not the
  90757. * first, the init function will reorder \a metadata by moving the
  90758. * VORBIS_COMMENT block to the front; the relative ordering of the other
  90759. * blocks will remain as they were.
  90760. *
  90761. * \note The Ogg FLAC mapping limits the number of metadata blocks per
  90762. * stream to \c 65535. If \a num_blocks exceeds this the function will
  90763. * return \c false.
  90764. *
  90765. * \default \c NULL, 0
  90766. * \param encoder An encoder instance to set.
  90767. * \param metadata See above.
  90768. * \param num_blocks See above.
  90769. * \assert
  90770. * \code encoder != NULL \endcode
  90771. * \retval FLAC__bool
  90772. * \c false if the encoder is already initialized, else \c true.
  90773. * \c false if the encoder is already initialized, or if
  90774. * \a num_blocks > 65535 if encoding to Ogg FLAC, else \c true.
  90775. */
  90776. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks);
  90777. /** Get the current encoder state.
  90778. *
  90779. * \param encoder An encoder instance to query.
  90780. * \assert
  90781. * \code encoder != NULL \endcode
  90782. * \retval FLAC__StreamEncoderState
  90783. * The current encoder state.
  90784. */
  90785. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder);
  90786. /** Get the state of the verify stream decoder.
  90787. * Useful when the stream encoder state is
  90788. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR.
  90789. *
  90790. * \param encoder An encoder instance to query.
  90791. * \assert
  90792. * \code encoder != NULL \endcode
  90793. * \retval FLAC__StreamDecoderState
  90794. * The verify stream decoder state.
  90795. */
  90796. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder);
  90797. /** Get the current encoder state as a C string.
  90798. * This version automatically resolves
  90799. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR by getting the
  90800. * verify decoder's state.
  90801. *
  90802. * \param encoder A encoder instance to query.
  90803. * \assert
  90804. * \code encoder != NULL \endcode
  90805. * \retval const char *
  90806. * The encoder state as a C string. Do not modify the contents.
  90807. */
  90808. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder);
  90809. /** Get relevant values about the nature of a verify decoder error.
  90810. * Useful when the stream encoder state is
  90811. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR. The arguments should
  90812. * be addresses in which the stats will be returned, or NULL if value
  90813. * is not desired.
  90814. *
  90815. * \param encoder An encoder instance to query.
  90816. * \param absolute_sample The absolute sample number of the mismatch.
  90817. * \param frame_number The number of the frame in which the mismatch occurred.
  90818. * \param channel The channel in which the mismatch occurred.
  90819. * \param sample The number of the sample (relative to the frame) in
  90820. * which the mismatch occurred.
  90821. * \param expected The expected value for the sample in question.
  90822. * \param got The actual value returned by the decoder.
  90823. * \assert
  90824. * \code encoder != NULL \endcode
  90825. */
  90826. 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);
  90827. /** Get the "verify" flag.
  90828. *
  90829. * \param encoder An encoder instance to query.
  90830. * \assert
  90831. * \code encoder != NULL \endcode
  90832. * \retval FLAC__bool
  90833. * See FLAC__stream_encoder_set_verify().
  90834. */
  90835. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder);
  90836. /** Get the <A HREF="../format.html#subset>Subset</A> flag.
  90837. *
  90838. * \param encoder An encoder instance to query.
  90839. * \assert
  90840. * \code encoder != NULL \endcode
  90841. * \retval FLAC__bool
  90842. * See FLAC__stream_encoder_set_streamable_subset().
  90843. */
  90844. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder);
  90845. /** Get the number of input channels being processed.
  90846. *
  90847. * \param encoder An encoder instance to query.
  90848. * \assert
  90849. * \code encoder != NULL \endcode
  90850. * \retval unsigned
  90851. * See FLAC__stream_encoder_set_channels().
  90852. */
  90853. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder);
  90854. /** Get the input sample resolution setting.
  90855. *
  90856. * \param encoder An encoder instance to query.
  90857. * \assert
  90858. * \code encoder != NULL \endcode
  90859. * \retval unsigned
  90860. * See FLAC__stream_encoder_set_bits_per_sample().
  90861. */
  90862. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder);
  90863. /** Get the input sample rate setting.
  90864. *
  90865. * \param encoder An encoder instance to query.
  90866. * \assert
  90867. * \code encoder != NULL \endcode
  90868. * \retval unsigned
  90869. * See FLAC__stream_encoder_set_sample_rate().
  90870. */
  90871. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder);
  90872. /** Get the blocksize setting.
  90873. *
  90874. * \param encoder An encoder instance to query.
  90875. * \assert
  90876. * \code encoder != NULL \endcode
  90877. * \retval unsigned
  90878. * See FLAC__stream_encoder_set_blocksize().
  90879. */
  90880. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder);
  90881. /** Get the "mid/side stereo coding" flag.
  90882. *
  90883. * \param encoder An encoder instance to query.
  90884. * \assert
  90885. * \code encoder != NULL \endcode
  90886. * \retval FLAC__bool
  90887. * See FLAC__stream_encoder_get_do_mid_side_stereo().
  90888. */
  90889. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  90890. /** Get the "adaptive mid/side switching" flag.
  90891. *
  90892. * \param encoder An encoder instance to query.
  90893. * \assert
  90894. * \code encoder != NULL \endcode
  90895. * \retval FLAC__bool
  90896. * See FLAC__stream_encoder_set_loose_mid_side_stereo().
  90897. */
  90898. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  90899. /** Get the maximum LPC order setting.
  90900. *
  90901. * \param encoder An encoder instance to query.
  90902. * \assert
  90903. * \code encoder != NULL \endcode
  90904. * \retval unsigned
  90905. * See FLAC__stream_encoder_set_max_lpc_order().
  90906. */
  90907. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder);
  90908. /** Get the quantized linear predictor coefficient precision setting.
  90909. *
  90910. * \param encoder An encoder instance to query.
  90911. * \assert
  90912. * \code encoder != NULL \endcode
  90913. * \retval unsigned
  90914. * See FLAC__stream_encoder_set_qlp_coeff_precision().
  90915. */
  90916. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder);
  90917. /** Get the qlp coefficient precision search flag.
  90918. *
  90919. * \param encoder An encoder instance to query.
  90920. * \assert
  90921. * \code encoder != NULL \endcode
  90922. * \retval FLAC__bool
  90923. * See FLAC__stream_encoder_set_do_qlp_coeff_prec_search().
  90924. */
  90925. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder);
  90926. /** Get the "escape coding" flag.
  90927. *
  90928. * \param encoder An encoder instance to query.
  90929. * \assert
  90930. * \code encoder != NULL \endcode
  90931. * \retval FLAC__bool
  90932. * See FLAC__stream_encoder_set_do_escape_coding().
  90933. */
  90934. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder);
  90935. /** Get the exhaustive model search flag.
  90936. *
  90937. * \param encoder An encoder instance to query.
  90938. * \assert
  90939. * \code encoder != NULL \endcode
  90940. * \retval FLAC__bool
  90941. * See FLAC__stream_encoder_set_do_exhaustive_model_search().
  90942. */
  90943. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder);
  90944. /** Get the minimum residual partition order setting.
  90945. *
  90946. * \param encoder An encoder instance to query.
  90947. * \assert
  90948. * \code encoder != NULL \endcode
  90949. * \retval unsigned
  90950. * See FLAC__stream_encoder_set_min_residual_partition_order().
  90951. */
  90952. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder);
  90953. /** Get maximum residual partition order setting.
  90954. *
  90955. * \param encoder An encoder instance to query.
  90956. * \assert
  90957. * \code encoder != NULL \endcode
  90958. * \retval unsigned
  90959. * See FLAC__stream_encoder_set_max_residual_partition_order().
  90960. */
  90961. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder);
  90962. /** Get the Rice parameter search distance setting.
  90963. *
  90964. * \param encoder An encoder instance to query.
  90965. * \assert
  90966. * \code encoder != NULL \endcode
  90967. * \retval unsigned
  90968. * See FLAC__stream_encoder_set_rice_parameter_search_dist().
  90969. */
  90970. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder);
  90971. /** Get the previously set estimate of the total samples to be encoded.
  90972. * The encoder merely mimics back the value given to
  90973. * FLAC__stream_encoder_set_total_samples_estimate() since it has no
  90974. * other way of knowing how many samples the client will encode.
  90975. *
  90976. * \param encoder An encoder instance to set.
  90977. * \assert
  90978. * \code encoder != NULL \endcode
  90979. * \retval FLAC__uint64
  90980. * See FLAC__stream_encoder_get_total_samples_estimate().
  90981. */
  90982. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder);
  90983. /** Initialize the encoder instance to encode native FLAC streams.
  90984. *
  90985. * This flavor of initialization sets up the encoder to encode to a
  90986. * native FLAC stream. I/O is performed via callbacks to the client.
  90987. * For encoding to a plain file via filename or open \c FILE*,
  90988. * FLAC__stream_encoder_init_file() and FLAC__stream_encoder_init_FILE()
  90989. * provide a simpler interface.
  90990. *
  90991. * This function should be called after FLAC__stream_encoder_new() and
  90992. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  90993. * or FLAC__stream_encoder_process_interleaved().
  90994. * initialization succeeded.
  90995. *
  90996. * The call to FLAC__stream_encoder_init_stream() currently will also
  90997. * immediately call the write callback several times, once with the \c fLaC
  90998. * signature, and once for each encoded metadata block.
  90999. *
  91000. * \param encoder An uninitialized encoder instance.
  91001. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  91002. * pointer must not be \c NULL.
  91003. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  91004. * pointer may be \c NULL if seeking is not
  91005. * supported. The encoder uses seeking to go back
  91006. * and write some some stream statistics to the
  91007. * STREAMINFO block; this is recommended but not
  91008. * necessary to create a valid FLAC stream. If
  91009. * \a seek_callback is not \c NULL then a
  91010. * \a tell_callback must also be supplied.
  91011. * Alternatively, a dummy seek callback that just
  91012. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  91013. * may also be supplied, all though this is slightly
  91014. * less efficient for the encoder.
  91015. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  91016. * pointer may be \c NULL if seeking is not
  91017. * supported. If \a seek_callback is \c NULL then
  91018. * this argument will be ignored. If
  91019. * \a seek_callback is not \c NULL then a
  91020. * \a tell_callback must also be supplied.
  91021. * Alternatively, a dummy tell callback that just
  91022. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  91023. * may also be supplied, all though this is slightly
  91024. * less efficient for the encoder.
  91025. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  91026. * pointer may be \c NULL if the callback is not
  91027. * desired. If the client provides a seek callback,
  91028. * this function is not necessary as the encoder
  91029. * will automatically seek back and update the
  91030. * STREAMINFO block. It may also be \c NULL if the
  91031. * client does not support seeking, since it will
  91032. * have no way of going back to update the
  91033. * STREAMINFO. However the client can still supply
  91034. * a callback if it would like to know the details
  91035. * from the STREAMINFO.
  91036. * \param client_data This value will be supplied to callbacks in their
  91037. * \a client_data argument.
  91038. * \assert
  91039. * \code encoder != NULL \endcode
  91040. * \retval FLAC__StreamEncoderInitStatus
  91041. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  91042. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  91043. */
  91044. 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);
  91045. /** Initialize the encoder instance to encode Ogg FLAC streams.
  91046. *
  91047. * This flavor of initialization sets up the encoder to encode to a FLAC
  91048. * stream in an Ogg container. I/O is performed via callbacks to the
  91049. * client. For encoding to a plain file via filename or open \c FILE*,
  91050. * FLAC__stream_encoder_init_ogg_file() and FLAC__stream_encoder_init_ogg_FILE()
  91051. * provide a simpler interface.
  91052. *
  91053. * This function should be called after FLAC__stream_encoder_new() and
  91054. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91055. * or FLAC__stream_encoder_process_interleaved().
  91056. * initialization succeeded.
  91057. *
  91058. * The call to FLAC__stream_encoder_init_ogg_stream() currently will also
  91059. * immediately call the write callback several times to write the metadata
  91060. * packets.
  91061. *
  91062. * \param encoder An uninitialized encoder instance.
  91063. * \param read_callback See FLAC__StreamEncoderReadCallback. This
  91064. * pointer must not be \c NULL if \a seek_callback
  91065. * is non-NULL since they are both needed to be
  91066. * able to write data back to the Ogg FLAC stream
  91067. * in the post-encode phase.
  91068. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  91069. * pointer must not be \c NULL.
  91070. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  91071. * pointer may be \c NULL if seeking is not
  91072. * supported. The encoder uses seeking to go back
  91073. * and write some some stream statistics to the
  91074. * STREAMINFO block; this is recommended but not
  91075. * necessary to create a valid FLAC stream. If
  91076. * \a seek_callback is not \c NULL then a
  91077. * \a tell_callback must also be supplied.
  91078. * Alternatively, a dummy seek callback that just
  91079. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  91080. * may also be supplied, all though this is slightly
  91081. * less efficient for the encoder.
  91082. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  91083. * pointer may be \c NULL if seeking is not
  91084. * supported. If \a seek_callback is \c NULL then
  91085. * this argument will be ignored. If
  91086. * \a seek_callback is not \c NULL then a
  91087. * \a tell_callback must also be supplied.
  91088. * Alternatively, a dummy tell callback that just
  91089. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  91090. * may also be supplied, all though this is slightly
  91091. * less efficient for the encoder.
  91092. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  91093. * pointer may be \c NULL if the callback is not
  91094. * desired. If the client provides a seek callback,
  91095. * this function is not necessary as the encoder
  91096. * will automatically seek back and update the
  91097. * STREAMINFO block. It may also be \c NULL if the
  91098. * client does not support seeking, since it will
  91099. * have no way of going back to update the
  91100. * STREAMINFO. However the client can still supply
  91101. * a callback if it would like to know the details
  91102. * from the STREAMINFO.
  91103. * \param client_data This value will be supplied to callbacks in their
  91104. * \a client_data argument.
  91105. * \assert
  91106. * \code encoder != NULL \endcode
  91107. * \retval FLAC__StreamEncoderInitStatus
  91108. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  91109. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  91110. */
  91111. 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);
  91112. /** Initialize the encoder instance to encode native FLAC files.
  91113. *
  91114. * This flavor of initialization sets up the encoder to encode to a
  91115. * plain native FLAC file. For non-stdio streams, you must use
  91116. * FLAC__stream_encoder_init_stream() and provide callbacks for the I/O.
  91117. *
  91118. * This function should be called after FLAC__stream_encoder_new() and
  91119. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91120. * or FLAC__stream_encoder_process_interleaved().
  91121. * initialization succeeded.
  91122. *
  91123. * \param encoder An uninitialized encoder instance.
  91124. * \param file An open file. The file should have been opened
  91125. * with mode \c "w+b" and rewound. The file
  91126. * becomes owned by the encoder and should not be
  91127. * manipulated by the client while encoding.
  91128. * Unless \a file is \c stdout, it will be closed
  91129. * when FLAC__stream_encoder_finish() is called.
  91130. * Note however that a proper SEEKTABLE cannot be
  91131. * created when encoding to \c stdout since it is
  91132. * not seekable.
  91133. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  91134. * pointer may be \c NULL if the callback is not
  91135. * desired.
  91136. * \param client_data This value will be supplied to callbacks in their
  91137. * \a client_data argument.
  91138. * \assert
  91139. * \code encoder != NULL \endcode
  91140. * \code file != NULL \endcode
  91141. * \retval FLAC__StreamEncoderInitStatus
  91142. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  91143. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  91144. */
  91145. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  91146. /** Initialize the encoder instance to encode Ogg FLAC files.
  91147. *
  91148. * This flavor of initialization sets up the encoder to encode to a
  91149. * plain Ogg FLAC file. For non-stdio streams, you must use
  91150. * FLAC__stream_encoder_init_ogg_stream() and provide callbacks for the I/O.
  91151. *
  91152. * This function should be called after FLAC__stream_encoder_new() and
  91153. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91154. * or FLAC__stream_encoder_process_interleaved().
  91155. * initialization succeeded.
  91156. *
  91157. * \param encoder An uninitialized encoder instance.
  91158. * \param file An open file. The file should have been opened
  91159. * with mode \c "w+b" and rewound. The file
  91160. * becomes owned by the encoder and should not be
  91161. * manipulated by the client while encoding.
  91162. * Unless \a file is \c stdout, it will be closed
  91163. * when FLAC__stream_encoder_finish() is called.
  91164. * Note however that a proper SEEKTABLE cannot be
  91165. * created when encoding to \c stdout since it is
  91166. * not seekable.
  91167. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  91168. * pointer may be \c NULL if the callback is not
  91169. * desired.
  91170. * \param client_data This value will be supplied to callbacks in their
  91171. * \a client_data argument.
  91172. * \assert
  91173. * \code encoder != NULL \endcode
  91174. * \code file != NULL \endcode
  91175. * \retval FLAC__StreamEncoderInitStatus
  91176. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  91177. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  91178. */
  91179. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  91180. /** Initialize the encoder instance to encode native FLAC files.
  91181. *
  91182. * This flavor of initialization sets up the encoder to encode to a plain
  91183. * FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  91184. * with Unicode filenames on Windows), you must use
  91185. * FLAC__stream_encoder_init_FILE(), or FLAC__stream_encoder_init_stream()
  91186. * and provide callbacks for the I/O.
  91187. *
  91188. * This function should be called after FLAC__stream_encoder_new() and
  91189. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91190. * or FLAC__stream_encoder_process_interleaved().
  91191. * initialization succeeded.
  91192. *
  91193. * \param encoder An uninitialized encoder instance.
  91194. * \param filename The name of the file to encode to. The file will
  91195. * be opened with fopen(). Use \c NULL to encode to
  91196. * \c stdout. Note however that a proper SEEKTABLE
  91197. * cannot be created when encoding to \c stdout since
  91198. * it is not seekable.
  91199. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  91200. * pointer may be \c NULL if the callback is not
  91201. * desired.
  91202. * \param client_data This value will be supplied to callbacks in their
  91203. * \a client_data argument.
  91204. * \assert
  91205. * \code encoder != NULL \endcode
  91206. * \retval FLAC__StreamEncoderInitStatus
  91207. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  91208. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  91209. */
  91210. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  91211. /** Initialize the encoder instance to encode Ogg FLAC files.
  91212. *
  91213. * This flavor of initialization sets up the encoder to encode to a plain
  91214. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  91215. * with Unicode filenames on Windows), you must use
  91216. * FLAC__stream_encoder_init_ogg_FILE(), or FLAC__stream_encoder_init_ogg_stream()
  91217. * and provide callbacks for the I/O.
  91218. *
  91219. * This function should be called after FLAC__stream_encoder_new() and
  91220. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91221. * or FLAC__stream_encoder_process_interleaved().
  91222. * initialization succeeded.
  91223. *
  91224. * \param encoder An uninitialized encoder instance.
  91225. * \param filename The name of the file to encode to. The file will
  91226. * be opened with fopen(). Use \c NULL to encode to
  91227. * \c stdout. Note however that a proper SEEKTABLE
  91228. * cannot be created when encoding to \c stdout since
  91229. * it is not seekable.
  91230. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  91231. * pointer may be \c NULL if the callback is not
  91232. * desired.
  91233. * \param client_data This value will be supplied to callbacks in their
  91234. * \a client_data argument.
  91235. * \assert
  91236. * \code encoder != NULL \endcode
  91237. * \retval FLAC__StreamEncoderInitStatus
  91238. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  91239. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  91240. */
  91241. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  91242. /** Finish the encoding process.
  91243. * Flushes the encoding buffer, releases resources, resets the encoder
  91244. * settings to their defaults, and returns the encoder state to
  91245. * FLAC__STREAM_ENCODER_UNINITIALIZED. Note that this can generate
  91246. * one or more write callbacks before returning, and will generate
  91247. * a metadata callback.
  91248. *
  91249. * Note that in the course of processing the last frame, errors can
  91250. * occur, so the caller should be sure to check the return value to
  91251. * ensure the file was encoded properly.
  91252. *
  91253. * In the event of a prematurely-terminated encode, it is not strictly
  91254. * necessary to call this immediately before FLAC__stream_encoder_delete()
  91255. * but it is good practice to match every FLAC__stream_encoder_init_*()
  91256. * with a FLAC__stream_encoder_finish().
  91257. *
  91258. * \param encoder An uninitialized encoder instance.
  91259. * \assert
  91260. * \code encoder != NULL \endcode
  91261. * \retval FLAC__bool
  91262. * \c false if an error occurred processing the last frame; or if verify
  91263. * mode is set (see FLAC__stream_encoder_set_verify()), there was a
  91264. * verify mismatch; else \c true. If \c false, caller should check the
  91265. * state with FLAC__stream_encoder_get_state() for more information
  91266. * about the error.
  91267. */
  91268. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder);
  91269. /** Submit data for encoding.
  91270. * This version allows you to supply the input data via an array of
  91271. * pointers, each pointer pointing to an array of \a samples samples
  91272. * representing one channel. The samples need not be block-aligned,
  91273. * but each channel should have the same number of samples. Each sample
  91274. * should be a signed integer, right-justified to the resolution set by
  91275. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  91276. * resolution is 16 bits per sample, the samples should all be in the
  91277. * range [-32768,32767].
  91278. *
  91279. * For applications where channel order is important, channels must
  91280. * follow the order as described in the
  91281. * <A HREF="../format.html#frame_header">frame header</A>.
  91282. *
  91283. * \param encoder An initialized encoder instance in the OK state.
  91284. * \param buffer An array of pointers to each channel's signal.
  91285. * \param samples The number of samples in one channel.
  91286. * \assert
  91287. * \code encoder != NULL \endcode
  91288. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  91289. * \retval FLAC__bool
  91290. * \c true if successful, else \c false; in this case, check the
  91291. * encoder state with FLAC__stream_encoder_get_state() to see what
  91292. * went wrong.
  91293. */
  91294. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples);
  91295. /** Submit data for encoding.
  91296. * This version allows you to supply the input data where the channels
  91297. * are interleaved into a single array (i.e. channel0_sample0,
  91298. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  91299. * The samples need not be block-aligned but they must be
  91300. * sample-aligned, i.e. the first value should be channel0_sample0
  91301. * and the last value channelN_sampleM. Each sample should be a signed
  91302. * integer, right-justified to the resolution set by
  91303. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  91304. * resolution is 16 bits per sample, the samples should all be in the
  91305. * range [-32768,32767].
  91306. *
  91307. * For applications where channel order is important, channels must
  91308. * follow the order as described in the
  91309. * <A HREF="../format.html#frame_header">frame header</A>.
  91310. *
  91311. * \param encoder An initialized encoder instance in the OK state.
  91312. * \param buffer An array of channel-interleaved data (see above).
  91313. * \param samples The number of samples in one channel, the same as for
  91314. * FLAC__stream_encoder_process(). For example, if
  91315. * encoding two channels, \c 1000 \a samples corresponds
  91316. * to a \a buffer of 2000 values.
  91317. * \assert
  91318. * \code encoder != NULL \endcode
  91319. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  91320. * \retval FLAC__bool
  91321. * \c true if successful, else \c false; in this case, check the
  91322. * encoder state with FLAC__stream_encoder_get_state() to see what
  91323. * went wrong.
  91324. */
  91325. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples);
  91326. /* \} */
  91327. #ifdef __cplusplus
  91328. }
  91329. #endif
  91330. #endif
  91331. /*** End of inlined file: stream_encoder.h ***/
  91332. #ifdef _MSC_VER
  91333. /* OPT: an MSVC built-in would be better */
  91334. static _inline FLAC__uint32 local_swap32_(FLAC__uint32 x)
  91335. {
  91336. x = ((x<<8)&0xFF00FF00) | ((x>>8)&0x00FF00FF);
  91337. return (x>>16) | (x<<16);
  91338. }
  91339. #endif
  91340. #if defined(_MSC_VER) && defined(_X86_)
  91341. /* OPT: an MSVC built-in would be better */
  91342. static void local_swap32_block_(FLAC__uint32 *start, FLAC__uint32 len)
  91343. {
  91344. __asm {
  91345. mov edx, start
  91346. mov ecx, len
  91347. test ecx, ecx
  91348. loop1:
  91349. jz done1
  91350. mov eax, [edx]
  91351. bswap eax
  91352. mov [edx], eax
  91353. add edx, 4
  91354. dec ecx
  91355. jmp short loop1
  91356. done1:
  91357. }
  91358. }
  91359. #endif
  91360. /** \mainpage
  91361. *
  91362. * \section intro Introduction
  91363. *
  91364. * This is the documentation for the FLAC C and C++ APIs. It is
  91365. * highly interconnected; this introduction should give you a top
  91366. * level idea of the structure and how to find the information you
  91367. * need. As a prerequisite you should have at least a basic
  91368. * knowledge of the FLAC format, documented
  91369. * <A HREF="../format.html">here</A>.
  91370. *
  91371. * \section c_api FLAC C API
  91372. *
  91373. * The FLAC C API is the interface to libFLAC, a set of structures
  91374. * describing the components of FLAC streams, and functions for
  91375. * encoding and decoding streams, as well as manipulating FLAC
  91376. * metadata in files. The public include files will be installed
  91377. * in your include area (for example /usr/include/FLAC/...).
  91378. *
  91379. * By writing a little code and linking against libFLAC, it is
  91380. * relatively easy to add FLAC support to another program. The
  91381. * library is licensed under <A HREF="../license.html">Xiph's BSD license</A>.
  91382. * Complete source code of libFLAC as well as the command-line
  91383. * encoder and plugins is available and is a useful source of
  91384. * examples.
  91385. *
  91386. * Aside from encoders and decoders, libFLAC provides a powerful
  91387. * metadata interface for manipulating metadata in FLAC files. It
  91388. * allows the user to add, delete, and modify FLAC metadata blocks
  91389. * and it can automatically take advantage of PADDING blocks to avoid
  91390. * rewriting the entire FLAC file when changing the size of the
  91391. * metadata.
  91392. *
  91393. * libFLAC usually only requires the standard C library and C math
  91394. * library. In particular, threading is not used so there is no
  91395. * dependency on a thread library. However, libFLAC does not use
  91396. * global variables and should be thread-safe.
  91397. *
  91398. * libFLAC also supports encoding to and decoding from Ogg FLAC.
  91399. * However the metadata editing interfaces currently have limited
  91400. * read-only support for Ogg FLAC files.
  91401. *
  91402. * \section cpp_api FLAC C++ API
  91403. *
  91404. * The FLAC C++ API is a set of classes that encapsulate the
  91405. * structures and functions in libFLAC. They provide slightly more
  91406. * functionality with respect to metadata but are otherwise
  91407. * equivalent. For the most part, they share the same usage as
  91408. * their counterparts in libFLAC, and the FLAC C API documentation
  91409. * can be used as a supplement. The public include files
  91410. * for the C++ API will be installed in your include area (for
  91411. * example /usr/include/FLAC++/...).
  91412. *
  91413. * libFLAC++ is also licensed under
  91414. * <A HREF="../license.html">Xiph's BSD license</A>.
  91415. *
  91416. * \section getting_started Getting Started
  91417. *
  91418. * A good starting point for learning the API is to browse through
  91419. * the <A HREF="modules.html">modules</A>. Modules are logical
  91420. * groupings of related functions or classes, which correspond roughly
  91421. * to header files or sections of header files. Each module includes a
  91422. * detailed description of the general usage of its functions or
  91423. * classes.
  91424. *
  91425. * From there you can go on to look at the documentation of
  91426. * individual functions. You can see different views of the individual
  91427. * functions through the links in top bar across this page.
  91428. *
  91429. * If you prefer a more hands-on approach, you can jump right to some
  91430. * <A HREF="../documentation_example_code.html">example code</A>.
  91431. *
  91432. * \section porting_guide Porting Guide
  91433. *
  91434. * Starting with FLAC 1.1.3 a \link porting Porting Guide \endlink
  91435. * has been introduced which gives detailed instructions on how to
  91436. * port your code to newer versions of FLAC.
  91437. *
  91438. * \section embedded_developers Embedded Developers
  91439. *
  91440. * libFLAC has grown larger over time as more functionality has been
  91441. * included, but much of it may be unnecessary for a particular embedded
  91442. * implementation. Unused parts may be pruned by some simple editing of
  91443. * src/libFLAC/Makefile.am. In general, the decoders, encoders, and
  91444. * metadata interface are all independent from each other.
  91445. *
  91446. * It is easiest to just describe the dependencies:
  91447. *
  91448. * - All modules depend on the \link flac_format Format \endlink module.
  91449. * - The decoders and encoders depend on the bitbuffer.
  91450. * - The decoder is independent of the encoder. The encoder uses the
  91451. * decoder because of the verify feature, but this can be removed if
  91452. * not needed.
  91453. * - Parts of the metadata interface require the stream decoder (but not
  91454. * the encoder).
  91455. * - Ogg support is selectable through the compile time macro
  91456. * \c FLAC__HAS_OGG.
  91457. *
  91458. * For example, if your application only requires the stream decoder, no
  91459. * encoder, and no metadata interface, you can remove the stream encoder
  91460. * and the metadata interface, which will greatly reduce the size of the
  91461. * library.
  91462. *
  91463. * Also, there are several places in the libFLAC code with comments marked
  91464. * with "OPT:" where a #define can be changed to enable code that might be
  91465. * faster on a specific platform. Experimenting with these can yield faster
  91466. * binaries.
  91467. */
  91468. /** \defgroup porting Porting Guide for New Versions
  91469. *
  91470. * This module describes differences in the library interfaces from
  91471. * version to version. It assists in the porting of code that uses
  91472. * the libraries to newer versions of FLAC.
  91473. *
  91474. * One simple facility for making porting easier that has been added
  91475. * in FLAC 1.1.3 is a set of \c #defines in \c export.h of each
  91476. * library's includes (e.g. \c include/FLAC/export.h). The
  91477. * \c #defines mirror the libraries'
  91478. * <A HREF="http://www.gnu.org/software/libtool/manual.html#Libtool-versioning">libtool version numbers</A>,
  91479. * e.g. in libFLAC there are \c FLAC_API_VERSION_CURRENT,
  91480. * \c FLAC_API_VERSION_REVISION, and \c FLAC_API_VERSION_AGE.
  91481. * These can be used to support multiple versions of an API during the
  91482. * transition phase, e.g.
  91483. *
  91484. * \code
  91485. * #if !defined(FLAC_API_VERSION_CURRENT) || FLAC_API_VERSION_CURRENT <= 7
  91486. * legacy code
  91487. * #else
  91488. * new code
  91489. * #endif
  91490. * \endcode
  91491. *
  91492. * The the source will work for multiple versions and the legacy code can
  91493. * easily be removed when the transition is complete.
  91494. *
  91495. * Another available symbol is FLAC_API_SUPPORTS_OGG_FLAC (defined in
  91496. * include/FLAC/export.h), which can be used to determine whether or not
  91497. * the library has been compiled with support for Ogg FLAC. This is
  91498. * simpler than trying to call an Ogg init function and catching the
  91499. * error.
  91500. */
  91501. /** \defgroup porting_1_1_2_to_1_1_3 Porting from FLAC 1.1.2 to 1.1.3
  91502. * \ingroup porting
  91503. *
  91504. * \brief
  91505. * This module describes porting from FLAC 1.1.2 to FLAC 1.1.3.
  91506. *
  91507. * The main change between the APIs in 1.1.2 and 1.1.3 is that they have
  91508. * been simplified. First, libOggFLAC has been merged into libFLAC and
  91509. * libOggFLAC++ has been merged into libFLAC++. Second, both the three
  91510. * decoding layers and three encoding layers have been merged into a
  91511. * single stream decoder and stream encoder. That is, the functionality
  91512. * of FLAC__SeekableStreamDecoder and FLAC__FileDecoder has been merged
  91513. * into FLAC__StreamDecoder, and FLAC__SeekableStreamEncoder and
  91514. * FLAC__FileEncoder into FLAC__StreamEncoder. Only the
  91515. * FLAC__StreamDecoder and FLAC__StreamEncoder remain. What this means
  91516. * is there is now a single API that can be used to encode or decode
  91517. * streams to/from native FLAC or Ogg FLAC and the single API can work
  91518. * on both seekable and non-seekable streams.
  91519. *
  91520. * Instead of creating an encoder or decoder of a certain layer, now the
  91521. * client will always create a FLAC__StreamEncoder or
  91522. * FLAC__StreamDecoder. The old layers are now differentiated by the
  91523. * initialization function. For example, for the decoder,
  91524. * FLAC__stream_decoder_init() has been replaced by
  91525. * FLAC__stream_decoder_init_stream(). This init function takes
  91526. * callbacks for the I/O, and the seeking callbacks are optional. This
  91527. * allows the client to use the same object for seekable and
  91528. * non-seekable streams. For decoding a FLAC file directly, the client
  91529. * can use FLAC__stream_decoder_init_file() and pass just a filename
  91530. * and fewer callbacks; most of the other callbacks are supplied
  91531. * internally. For situations where fopen()ing by filename is not
  91532. * possible (e.g. Unicode filenames on Windows) the client can instead
  91533. * open the file itself and supply the FILE* to
  91534. * FLAC__stream_decoder_init_FILE(). The init functions now returns a
  91535. * FLAC__StreamDecoderInitStatus instead of FLAC__StreamDecoderState.
  91536. * Since the callbacks and client data are now passed to the init
  91537. * function, the FLAC__stream_decoder_set_*_callback() functions and
  91538. * FLAC__stream_decoder_set_client_data() are no longer needed. The
  91539. * rest of the calls to the decoder are the same as before.
  91540. *
  91541. * There are counterpart init functions for Ogg FLAC, e.g.
  91542. * FLAC__stream_decoder_init_ogg_stream(). All the rest of the calls
  91543. * and callbacks are the same as for native FLAC.
  91544. *
  91545. * As an example, in FLAC 1.1.2 a seekable stream decoder would have
  91546. * been set up like so:
  91547. *
  91548. * \code
  91549. * FLAC__SeekableStreamDecoder *decoder = FLAC__seekable_stream_decoder_new();
  91550. * if(decoder == NULL) do_something;
  91551. * FLAC__seekable_stream_decoder_set_md5_checking(decoder, true);
  91552. * [... other settings ...]
  91553. * FLAC__seekable_stream_decoder_set_read_callback(decoder, my_read_callback);
  91554. * FLAC__seekable_stream_decoder_set_seek_callback(decoder, my_seek_callback);
  91555. * FLAC__seekable_stream_decoder_set_tell_callback(decoder, my_tell_callback);
  91556. * FLAC__seekable_stream_decoder_set_length_callback(decoder, my_length_callback);
  91557. * FLAC__seekable_stream_decoder_set_eof_callback(decoder, my_eof_callback);
  91558. * FLAC__seekable_stream_decoder_set_write_callback(decoder, my_write_callback);
  91559. * FLAC__seekable_stream_decoder_set_metadata_callback(decoder, my_metadata_callback);
  91560. * FLAC__seekable_stream_decoder_set_error_callback(decoder, my_error_callback);
  91561. * FLAC__seekable_stream_decoder_set_client_data(decoder, my_client_data);
  91562. * if(FLAC__seekable_stream_decoder_init(decoder) != FLAC__SEEKABLE_STREAM_DECODER_OK) do_something;
  91563. * \endcode
  91564. *
  91565. * In FLAC 1.1.3 it is like this:
  91566. *
  91567. * \code
  91568. * FLAC__StreamDecoder *decoder = FLAC__stream_decoder_new();
  91569. * if(decoder == NULL) do_something;
  91570. * FLAC__stream_decoder_set_md5_checking(decoder, true);
  91571. * [... other settings ...]
  91572. * if(FLAC__stream_decoder_init_stream(
  91573. * decoder,
  91574. * my_read_callback,
  91575. * my_seek_callback, // or NULL
  91576. * my_tell_callback, // or NULL
  91577. * my_length_callback, // or NULL
  91578. * my_eof_callback, // or NULL
  91579. * my_write_callback,
  91580. * my_metadata_callback, // or NULL
  91581. * my_error_callback,
  91582. * my_client_data
  91583. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  91584. * \endcode
  91585. *
  91586. * or you could do;
  91587. *
  91588. * \code
  91589. * [...]
  91590. * FILE *file = fopen("somefile.flac","rb");
  91591. * if(file == NULL) do_somthing;
  91592. * if(FLAC__stream_decoder_init_FILE(
  91593. * decoder,
  91594. * file,
  91595. * my_write_callback,
  91596. * my_metadata_callback, // or NULL
  91597. * my_error_callback,
  91598. * my_client_data
  91599. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  91600. * \endcode
  91601. *
  91602. * or just:
  91603. *
  91604. * \code
  91605. * [...]
  91606. * if(FLAC__stream_decoder_init_file(
  91607. * decoder,
  91608. * "somefile.flac",
  91609. * my_write_callback,
  91610. * my_metadata_callback, // or NULL
  91611. * my_error_callback,
  91612. * my_client_data
  91613. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  91614. * \endcode
  91615. *
  91616. * Another small change to the decoder is in how it handles unparseable
  91617. * streams. Before, when the decoder found an unparseable stream
  91618. * (reserved for when the decoder encounters a stream from a future
  91619. * encoder that it can't parse), it changed the state to
  91620. * \c FLAC__STREAM_DECODER_UNPARSEABLE_STREAM. Now the decoder instead
  91621. * drops sync and calls the error callback with a new error code
  91622. * \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM. This is
  91623. * more robust. If your error callback does not discriminate on the the
  91624. * error state, your code does not need to be changed.
  91625. *
  91626. * The encoder now has a new setting:
  91627. * FLAC__stream_encoder_set_apodization(). This is for setting the
  91628. * method used to window the data before LPC analysis. You only need to
  91629. * add a call to this function if the default is not suitable. There
  91630. * are also two new convenience functions that may be useful:
  91631. * FLAC__metadata_object_cuesheet_calculate_cddb_id() and
  91632. * FLAC__metadata_get_cuesheet().
  91633. *
  91634. * The \a bytes parameter to FLAC__StreamDecoderReadCallback,
  91635. * FLAC__StreamEncoderReadCallback, and FLAC__StreamEncoderWriteCallback
  91636. * is now \c size_t instead of \c unsigned.
  91637. */
  91638. /** \defgroup porting_1_1_3_to_1_1_4 Porting from FLAC 1.1.3 to 1.1.4
  91639. * \ingroup porting
  91640. *
  91641. * \brief
  91642. * This module describes porting from FLAC 1.1.3 to FLAC 1.1.4.
  91643. *
  91644. * There were no changes to any of the interfaces from 1.1.3 to 1.1.4.
  91645. * There was a slight change in the implementation of
  91646. * FLAC__stream_encoder_set_metadata(); the function now makes a copy
  91647. * of the \a metadata array of pointers so the client no longer needs
  91648. * to maintain it after the call. The objects themselves that are
  91649. * pointed to by the array are still not copied though and must be
  91650. * maintained until the call to FLAC__stream_encoder_finish().
  91651. */
  91652. /** \defgroup porting_1_1_4_to_1_2_0 Porting from FLAC 1.1.4 to 1.2.0
  91653. * \ingroup porting
  91654. *
  91655. * \brief
  91656. * This module describes porting from FLAC 1.1.4 to FLAC 1.2.0.
  91657. *
  91658. * There were only very minor changes to the interfaces from 1.1.4 to 1.2.0.
  91659. * In libFLAC, \c FLAC__format_sample_rate_is_subset() was added.
  91660. * In libFLAC++, \c FLAC::Decoder::Stream::get_decode_position() was added.
  91661. *
  91662. * Finally, value of the constant \c FLAC__FRAME_HEADER_RESERVED_LEN
  91663. * has changed to reflect the conversion of one of the reserved bits
  91664. * into active use. It used to be \c 2 and now is \c 1. However the
  91665. * FLAC frame header length has not changed, so to skip the proper
  91666. * number of bits, use \c FLAC__FRAME_HEADER_RESERVED_LEN +
  91667. * \c FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN
  91668. */
  91669. /** \defgroup flac FLAC C API
  91670. *
  91671. * The FLAC C API is the interface to libFLAC, a set of structures
  91672. * describing the components of FLAC streams, and functions for
  91673. * encoding and decoding streams, as well as manipulating FLAC
  91674. * metadata in files.
  91675. *
  91676. * You should start with the format components as all other modules
  91677. * are dependent on it.
  91678. */
  91679. #endif
  91680. /*** End of inlined file: all.h ***/
  91681. /*** Start of inlined file: bitmath.c ***/
  91682. /*** Start of inlined file: juce_FlacHeader.h ***/
  91683. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  91684. // tasks..
  91685. #define VERSION "1.2.1"
  91686. #define FLAC__NO_DLL 1
  91687. #if JUCE_MSVC
  91688. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  91689. #endif
  91690. #if JUCE_MAC
  91691. #define FLAC__SYS_DARWIN 1
  91692. #endif
  91693. /*** End of inlined file: juce_FlacHeader.h ***/
  91694. #if JUCE_USE_FLAC
  91695. #if HAVE_CONFIG_H
  91696. # include <config.h>
  91697. #endif
  91698. /*** Start of inlined file: bitmath.h ***/
  91699. #ifndef FLAC__PRIVATE__BITMATH_H
  91700. #define FLAC__PRIVATE__BITMATH_H
  91701. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v);
  91702. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v);
  91703. unsigned FLAC__bitmath_silog2(int v);
  91704. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v);
  91705. #endif
  91706. /*** End of inlined file: bitmath.h ***/
  91707. /* An example of what FLAC__bitmath_ilog2() computes:
  91708. *
  91709. * ilog2( 0) = assertion failure
  91710. * ilog2( 1) = 0
  91711. * ilog2( 2) = 1
  91712. * ilog2( 3) = 1
  91713. * ilog2( 4) = 2
  91714. * ilog2( 5) = 2
  91715. * ilog2( 6) = 2
  91716. * ilog2( 7) = 2
  91717. * ilog2( 8) = 3
  91718. * ilog2( 9) = 3
  91719. * ilog2(10) = 3
  91720. * ilog2(11) = 3
  91721. * ilog2(12) = 3
  91722. * ilog2(13) = 3
  91723. * ilog2(14) = 3
  91724. * ilog2(15) = 3
  91725. * ilog2(16) = 4
  91726. * ilog2(17) = 4
  91727. * ilog2(18) = 4
  91728. */
  91729. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v)
  91730. {
  91731. unsigned l = 0;
  91732. FLAC__ASSERT(v > 0);
  91733. while(v >>= 1)
  91734. l++;
  91735. return l;
  91736. }
  91737. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v)
  91738. {
  91739. unsigned l = 0;
  91740. FLAC__ASSERT(v > 0);
  91741. while(v >>= 1)
  91742. l++;
  91743. return l;
  91744. }
  91745. /* An example of what FLAC__bitmath_silog2() computes:
  91746. *
  91747. * silog2(-10) = 5
  91748. * silog2(- 9) = 5
  91749. * silog2(- 8) = 4
  91750. * silog2(- 7) = 4
  91751. * silog2(- 6) = 4
  91752. * silog2(- 5) = 4
  91753. * silog2(- 4) = 3
  91754. * silog2(- 3) = 3
  91755. * silog2(- 2) = 2
  91756. * silog2(- 1) = 2
  91757. * silog2( 0) = 0
  91758. * silog2( 1) = 2
  91759. * silog2( 2) = 3
  91760. * silog2( 3) = 3
  91761. * silog2( 4) = 4
  91762. * silog2( 5) = 4
  91763. * silog2( 6) = 4
  91764. * silog2( 7) = 4
  91765. * silog2( 8) = 5
  91766. * silog2( 9) = 5
  91767. * silog2( 10) = 5
  91768. */
  91769. unsigned FLAC__bitmath_silog2(int v)
  91770. {
  91771. while(1) {
  91772. if(v == 0) {
  91773. return 0;
  91774. }
  91775. else if(v > 0) {
  91776. unsigned l = 0;
  91777. while(v) {
  91778. l++;
  91779. v >>= 1;
  91780. }
  91781. return l+1;
  91782. }
  91783. else if(v == -1) {
  91784. return 2;
  91785. }
  91786. else {
  91787. v++;
  91788. v = -v;
  91789. }
  91790. }
  91791. }
  91792. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v)
  91793. {
  91794. while(1) {
  91795. if(v == 0) {
  91796. return 0;
  91797. }
  91798. else if(v > 0) {
  91799. unsigned l = 0;
  91800. while(v) {
  91801. l++;
  91802. v >>= 1;
  91803. }
  91804. return l+1;
  91805. }
  91806. else if(v == -1) {
  91807. return 2;
  91808. }
  91809. else {
  91810. v++;
  91811. v = -v;
  91812. }
  91813. }
  91814. }
  91815. #endif
  91816. /*** End of inlined file: bitmath.c ***/
  91817. /*** Start of inlined file: bitreader.c ***/
  91818. /*** Start of inlined file: juce_FlacHeader.h ***/
  91819. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  91820. // tasks..
  91821. #define VERSION "1.2.1"
  91822. #define FLAC__NO_DLL 1
  91823. #if JUCE_MSVC
  91824. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  91825. #endif
  91826. #if JUCE_MAC
  91827. #define FLAC__SYS_DARWIN 1
  91828. #endif
  91829. /*** End of inlined file: juce_FlacHeader.h ***/
  91830. #if JUCE_USE_FLAC
  91831. #if HAVE_CONFIG_H
  91832. # include <config.h>
  91833. #endif
  91834. #include <stdlib.h> /* for malloc() */
  91835. #include <string.h> /* for memcpy(), memset() */
  91836. #ifdef _MSC_VER
  91837. #include <winsock.h> /* for ntohl() */
  91838. #elif defined FLAC__SYS_DARWIN
  91839. #include <machine/endian.h> /* for ntohl() */
  91840. #elif defined __MINGW32__
  91841. #include <winsock.h> /* for ntohl() */
  91842. #else
  91843. #include <netinet/in.h> /* for ntohl() */
  91844. #endif
  91845. /*** Start of inlined file: bitreader.h ***/
  91846. #ifndef FLAC__PRIVATE__BITREADER_H
  91847. #define FLAC__PRIVATE__BITREADER_H
  91848. #include <stdio.h> /* for FILE */
  91849. /*** Start of inlined file: cpu.h ***/
  91850. #ifndef FLAC__PRIVATE__CPU_H
  91851. #define FLAC__PRIVATE__CPU_H
  91852. #ifdef HAVE_CONFIG_H
  91853. #include <config.h>
  91854. #endif
  91855. typedef enum {
  91856. FLAC__CPUINFO_TYPE_IA32,
  91857. FLAC__CPUINFO_TYPE_PPC,
  91858. FLAC__CPUINFO_TYPE_UNKNOWN
  91859. } FLAC__CPUInfo_Type;
  91860. typedef struct {
  91861. FLAC__bool cpuid;
  91862. FLAC__bool bswap;
  91863. FLAC__bool cmov;
  91864. FLAC__bool mmx;
  91865. FLAC__bool fxsr;
  91866. FLAC__bool sse;
  91867. FLAC__bool sse2;
  91868. FLAC__bool sse3;
  91869. FLAC__bool ssse3;
  91870. FLAC__bool _3dnow;
  91871. FLAC__bool ext3dnow;
  91872. FLAC__bool extmmx;
  91873. } FLAC__CPUInfo_IA32;
  91874. typedef struct {
  91875. FLAC__bool altivec;
  91876. FLAC__bool ppc64;
  91877. } FLAC__CPUInfo_PPC;
  91878. typedef struct {
  91879. FLAC__bool use_asm;
  91880. FLAC__CPUInfo_Type type;
  91881. union {
  91882. FLAC__CPUInfo_IA32 ia32;
  91883. FLAC__CPUInfo_PPC ppc;
  91884. } data;
  91885. } FLAC__CPUInfo;
  91886. void FLAC__cpu_info(FLAC__CPUInfo *info);
  91887. #ifndef FLAC__NO_ASM
  91888. #ifdef FLAC__CPU_IA32
  91889. #ifdef FLAC__HAS_NASM
  91890. FLAC__uint32 FLAC__cpu_have_cpuid_asm_ia32(void);
  91891. void FLAC__cpu_info_asm_ia32(FLAC__uint32 *flags_edx, FLAC__uint32 *flags_ecx);
  91892. FLAC__uint32 FLAC__cpu_info_extended_amd_asm_ia32(void);
  91893. #endif
  91894. #endif
  91895. #endif
  91896. #endif
  91897. /*** End of inlined file: cpu.h ***/
  91898. /*
  91899. * opaque structure definition
  91900. */
  91901. struct FLAC__BitReader;
  91902. typedef struct FLAC__BitReader FLAC__BitReader;
  91903. typedef FLAC__bool (*FLAC__BitReaderReadCallback)(FLAC__byte buffer[], size_t *bytes, void *client_data);
  91904. /*
  91905. * construction, deletion, initialization, etc functions
  91906. */
  91907. FLAC__BitReader *FLAC__bitreader_new(void);
  91908. void FLAC__bitreader_delete(FLAC__BitReader *br);
  91909. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd);
  91910. void FLAC__bitreader_free(FLAC__BitReader *br); /* does not 'free(br)' */
  91911. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br);
  91912. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out);
  91913. /*
  91914. * CRC functions
  91915. */
  91916. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed);
  91917. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br);
  91918. /*
  91919. * info functions
  91920. */
  91921. FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br);
  91922. unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br);
  91923. unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br);
  91924. /*
  91925. * read functions
  91926. */
  91927. FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits);
  91928. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits);
  91929. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits);
  91930. FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val); /*only for bits=32*/
  91931. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits); /* WATCHOUT: does not CRC the skipped data! */ /*@@@@ add to unit tests */
  91932. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals); /* WATCHOUT: does not CRC the read data! */
  91933. 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! */
  91934. FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val);
  91935. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  91936. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  91937. #ifndef FLAC__NO_ASM
  91938. # ifdef FLAC__CPU_IA32
  91939. # ifdef FLAC__HAS_NASM
  91940. FLAC__bool FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  91941. # endif
  91942. # endif
  91943. #endif
  91944. #if 0 /* UNUSED */
  91945. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  91946. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter);
  91947. #endif
  91948. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen);
  91949. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen);
  91950. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br);
  91951. #endif
  91952. /*** End of inlined file: bitreader.h ***/
  91953. /*** Start of inlined file: crc.h ***/
  91954. #ifndef FLAC__PRIVATE__CRC_H
  91955. #define FLAC__PRIVATE__CRC_H
  91956. /* 8 bit CRC generator, MSB shifted first
  91957. ** polynomial = x^8 + x^2 + x^1 + x^0
  91958. ** init = 0
  91959. */
  91960. extern FLAC__byte const FLAC__crc8_table[256];
  91961. #define FLAC__CRC8_UPDATE(data, crc) (crc) = FLAC__crc8_table[(crc) ^ (data)];
  91962. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc);
  91963. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc);
  91964. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len);
  91965. /* 16 bit CRC generator, MSB shifted first
  91966. ** polynomial = x^16 + x^15 + x^2 + x^0
  91967. ** init = 0
  91968. */
  91969. extern unsigned FLAC__crc16_table[256];
  91970. #define FLAC__CRC16_UPDATE(data, crc) (((((crc)<<8) & 0xffff) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]))
  91971. /* this alternate may be faster on some systems/compilers */
  91972. #if 0
  91973. #define FLAC__CRC16_UPDATE(data, crc) ((((crc)<<8) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]) & 0xffff)
  91974. #endif
  91975. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len);
  91976. #endif
  91977. /*** End of inlined file: crc.h ***/
  91978. /* Things should be fastest when this matches the machine word size */
  91979. /* WATCHOUT: if you change this you must also change the following #defines down to COUNT_ZERO_MSBS below to match */
  91980. /* WATCHOUT: there are a few places where the code will not work unless brword is >= 32 bits wide */
  91981. /* also, some sections currently only have fast versions for 4 or 8 bytes per word */
  91982. typedef FLAC__uint32 brword;
  91983. #define FLAC__BYTES_PER_WORD 4
  91984. #define FLAC__BITS_PER_WORD 32
  91985. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  91986. /* SWAP_BE_WORD_TO_HOST swaps bytes in a brword (which is always big-endian) if necessary to match host byte order */
  91987. #if WORDS_BIGENDIAN
  91988. #define SWAP_BE_WORD_TO_HOST(x) (x)
  91989. #else
  91990. #if defined (_MSC_VER) && defined (_X86_)
  91991. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  91992. #else
  91993. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  91994. #endif
  91995. #endif
  91996. /* counts the # of zero MSBs in a word */
  91997. #define COUNT_ZERO_MSBS(word) ( \
  91998. (word) <= 0xffff ? \
  91999. ( (word) <= 0xff? byte_to_unary_table[word] + 24 : byte_to_unary_table[(word) >> 8] + 16 ) : \
  92000. ( (word) <= 0xffffff? byte_to_unary_table[word >> 16] + 8 : byte_to_unary_table[(word) >> 24] ) \
  92001. )
  92002. /* this alternate might be slightly faster on some systems/compilers: */
  92003. #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])) )
  92004. /*
  92005. * This should be at least twice as large as the largest number of words
  92006. * required to represent any 'number' (in any encoding) you are going to
  92007. * read. With FLAC this is on the order of maybe a few hundred bits.
  92008. * If the buffer is smaller than that, the decoder won't be able to read
  92009. * in a whole number that is in a variable length encoding (e.g. Rice).
  92010. * But to be practical it should be at least 1K bytes.
  92011. *
  92012. * Increase this number to decrease the number of read callbacks, at the
  92013. * expense of using more memory. Or decrease for the reverse effect,
  92014. * keeping in mind the limit from the first paragraph. The optimal size
  92015. * also depends on the CPU cache size and other factors; some twiddling
  92016. * may be necessary to squeeze out the best performance.
  92017. */
  92018. static const unsigned FLAC__BITREADER_DEFAULT_CAPACITY = 65536u / FLAC__BITS_PER_WORD; /* in words */
  92019. static const unsigned char byte_to_unary_table[] = {
  92020. 8, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4,
  92021. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  92022. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  92023. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  92024. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  92025. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  92026. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  92027. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  92028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
  92036. };
  92037. #ifdef min
  92038. #undef min
  92039. #endif
  92040. #define min(x,y) ((x)<(y)?(x):(y))
  92041. #ifdef max
  92042. #undef max
  92043. #endif
  92044. #define max(x,y) ((x)>(y)?(x):(y))
  92045. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  92046. #ifdef _MSC_VER
  92047. #define FLAC__U64L(x) x
  92048. #else
  92049. #define FLAC__U64L(x) x##LLU
  92050. #endif
  92051. #ifndef FLaC__INLINE
  92052. #define FLaC__INLINE
  92053. #endif
  92054. /* WATCHOUT: assembly routines rely on the order in which these fields are declared */
  92055. struct FLAC__BitReader {
  92056. /* any partially-consumed word at the head will stay right-justified as bits are consumed from the left */
  92057. /* any incomplete word at the tail will be left-justified, and bytes from the read callback are added on the right */
  92058. brword *buffer;
  92059. unsigned capacity; /* in words */
  92060. unsigned words; /* # of completed words in buffer */
  92061. unsigned bytes; /* # of bytes in incomplete word at buffer[words] */
  92062. unsigned consumed_words; /* #words ... */
  92063. unsigned consumed_bits; /* ... + (#bits of head word) already consumed from the front of buffer */
  92064. unsigned read_crc16; /* the running frame CRC */
  92065. unsigned crc16_align; /* the number of bits in the current consumed word that should not be CRC'd */
  92066. FLAC__BitReaderReadCallback read_callback;
  92067. void *client_data;
  92068. FLAC__CPUInfo cpu_info;
  92069. };
  92070. static FLaC__INLINE void crc16_update_word_(FLAC__BitReader *br, brword word)
  92071. {
  92072. register unsigned crc = br->read_crc16;
  92073. #if FLAC__BYTES_PER_WORD == 4
  92074. switch(br->crc16_align) {
  92075. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 24), crc);
  92076. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  92077. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  92078. case 24: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  92079. }
  92080. #elif FLAC__BYTES_PER_WORD == 8
  92081. switch(br->crc16_align) {
  92082. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 56), crc);
  92083. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 48) & 0xff), crc);
  92084. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 40) & 0xff), crc);
  92085. case 24: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 32) & 0xff), crc);
  92086. case 32: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 24) & 0xff), crc);
  92087. case 40: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  92088. case 48: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  92089. case 56: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  92090. }
  92091. #else
  92092. for( ; br->crc16_align < FLAC__BITS_PER_WORD; br->crc16_align += 8)
  92093. crc = FLAC__CRC16_UPDATE((unsigned)((word >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), crc);
  92094. br->read_crc16 = crc;
  92095. #endif
  92096. br->crc16_align = 0;
  92097. }
  92098. /* would be static except it needs to be called by asm routines */
  92099. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br)
  92100. {
  92101. unsigned start, end;
  92102. size_t bytes;
  92103. FLAC__byte *target;
  92104. /* first shift the unconsumed buffer data toward the front as much as possible */
  92105. if(br->consumed_words > 0) {
  92106. start = br->consumed_words;
  92107. end = br->words + (br->bytes? 1:0);
  92108. memmove(br->buffer, br->buffer+start, FLAC__BYTES_PER_WORD * (end - start));
  92109. br->words -= start;
  92110. br->consumed_words = 0;
  92111. }
  92112. /*
  92113. * set the target for reading, taking into account word alignment and endianness
  92114. */
  92115. bytes = (br->capacity - br->words) * FLAC__BYTES_PER_WORD - br->bytes;
  92116. if(bytes == 0)
  92117. return false; /* no space left, buffer is too small; see note for FLAC__BITREADER_DEFAULT_CAPACITY */
  92118. target = ((FLAC__byte*)(br->buffer+br->words)) + br->bytes;
  92119. /* before reading, if the existing reader looks like this (say brword is 32 bits wide)
  92120. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1 (partial tail word is left-justified)
  92121. * buffer[BE]: 11 22 33 44 55 ?? ?? ?? (shown layed out as bytes sequentially in memory)
  92122. * buffer[LE]: 44 33 22 11 ?? ?? ?? 55 (?? being don't-care)
  92123. * ^^-------target, bytes=3
  92124. * on LE machines, have to byteswap the odd tail word so nothing is
  92125. * overwritten:
  92126. */
  92127. #if WORDS_BIGENDIAN
  92128. #else
  92129. if(br->bytes)
  92130. br->buffer[br->words] = SWAP_BE_WORD_TO_HOST(br->buffer[br->words]);
  92131. #endif
  92132. /* now it looks like:
  92133. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1
  92134. * buffer[BE]: 11 22 33 44 55 ?? ?? ??
  92135. * buffer[LE]: 44 33 22 11 55 ?? ?? ??
  92136. * ^^-------target, bytes=3
  92137. */
  92138. /* read in the data; note that the callback may return a smaller number of bytes */
  92139. if(!br->read_callback(target, &bytes, br->client_data))
  92140. return false;
  92141. /* after reading bytes 66 77 88 99 AA BB CC DD EE FF from the client:
  92142. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  92143. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  92144. * buffer[LE]: 44 33 22 11 55 66 77 88 99 AA BB CC DD EE FF ??
  92145. * now have to byteswap on LE machines:
  92146. */
  92147. #if WORDS_BIGENDIAN
  92148. #else
  92149. end = (br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes + (FLAC__BYTES_PER_WORD-1)) / FLAC__BYTES_PER_WORD;
  92150. # if defined(_MSC_VER) && defined (_X86_) && (FLAC__BYTES_PER_WORD == 4)
  92151. if(br->cpu_info.type == FLAC__CPUINFO_TYPE_IA32 && br->cpu_info.data.ia32.bswap) {
  92152. start = br->words;
  92153. local_swap32_block_(br->buffer + start, end - start);
  92154. }
  92155. else
  92156. # endif
  92157. for(start = br->words; start < end; start++)
  92158. br->buffer[start] = SWAP_BE_WORD_TO_HOST(br->buffer[start]);
  92159. #endif
  92160. /* now it looks like:
  92161. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  92162. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  92163. * buffer[LE]: 44 33 22 11 88 77 66 55 CC BB AA 99 ?? FF EE DD
  92164. * finally we'll update the reader values:
  92165. */
  92166. end = br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes;
  92167. br->words = end / FLAC__BYTES_PER_WORD;
  92168. br->bytes = end % FLAC__BYTES_PER_WORD;
  92169. return true;
  92170. }
  92171. /***********************************************************************
  92172. *
  92173. * Class constructor/destructor
  92174. *
  92175. ***********************************************************************/
  92176. FLAC__BitReader *FLAC__bitreader_new(void)
  92177. {
  92178. FLAC__BitReader *br = (FLAC__BitReader*)calloc(1, sizeof(FLAC__BitReader));
  92179. /* calloc() implies:
  92180. memset(br, 0, sizeof(FLAC__BitReader));
  92181. br->buffer = 0;
  92182. br->capacity = 0;
  92183. br->words = br->bytes = 0;
  92184. br->consumed_words = br->consumed_bits = 0;
  92185. br->read_callback = 0;
  92186. br->client_data = 0;
  92187. */
  92188. return br;
  92189. }
  92190. void FLAC__bitreader_delete(FLAC__BitReader *br)
  92191. {
  92192. FLAC__ASSERT(0 != br);
  92193. FLAC__bitreader_free(br);
  92194. free(br);
  92195. }
  92196. /***********************************************************************
  92197. *
  92198. * Public class methods
  92199. *
  92200. ***********************************************************************/
  92201. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd)
  92202. {
  92203. FLAC__ASSERT(0 != br);
  92204. br->words = br->bytes = 0;
  92205. br->consumed_words = br->consumed_bits = 0;
  92206. br->capacity = FLAC__BITREADER_DEFAULT_CAPACITY;
  92207. br->buffer = (brword*)malloc(sizeof(brword) * br->capacity);
  92208. if(br->buffer == 0)
  92209. return false;
  92210. br->read_callback = rcb;
  92211. br->client_data = cd;
  92212. br->cpu_info = cpu;
  92213. return true;
  92214. }
  92215. void FLAC__bitreader_free(FLAC__BitReader *br)
  92216. {
  92217. FLAC__ASSERT(0 != br);
  92218. if(0 != br->buffer)
  92219. free(br->buffer);
  92220. br->buffer = 0;
  92221. br->capacity = 0;
  92222. br->words = br->bytes = 0;
  92223. br->consumed_words = br->consumed_bits = 0;
  92224. br->read_callback = 0;
  92225. br->client_data = 0;
  92226. }
  92227. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br)
  92228. {
  92229. br->words = br->bytes = 0;
  92230. br->consumed_words = br->consumed_bits = 0;
  92231. return true;
  92232. }
  92233. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out)
  92234. {
  92235. unsigned i, j;
  92236. if(br == 0) {
  92237. fprintf(out, "bitreader is NULL\n");
  92238. }
  92239. else {
  92240. 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);
  92241. for(i = 0; i < br->words; i++) {
  92242. fprintf(out, "%08X: ", i);
  92243. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  92244. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  92245. fprintf(out, ".");
  92246. else
  92247. fprintf(out, "%01u", br->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  92248. fprintf(out, "\n");
  92249. }
  92250. if(br->bytes > 0) {
  92251. fprintf(out, "%08X: ", i);
  92252. for(j = 0; j < br->bytes*8; j++)
  92253. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  92254. fprintf(out, ".");
  92255. else
  92256. fprintf(out, "%01u", br->buffer[i] & (1 << (br->bytes*8-j-1)) ? 1:0);
  92257. fprintf(out, "\n");
  92258. }
  92259. }
  92260. }
  92261. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed)
  92262. {
  92263. FLAC__ASSERT(0 != br);
  92264. FLAC__ASSERT(0 != br->buffer);
  92265. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  92266. br->read_crc16 = (unsigned)seed;
  92267. br->crc16_align = br->consumed_bits;
  92268. }
  92269. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br)
  92270. {
  92271. FLAC__ASSERT(0 != br);
  92272. FLAC__ASSERT(0 != br->buffer);
  92273. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  92274. FLAC__ASSERT(br->crc16_align <= br->consumed_bits);
  92275. /* CRC any tail bytes in a partially-consumed word */
  92276. if(br->consumed_bits) {
  92277. const brword tail = br->buffer[br->consumed_words];
  92278. for( ; br->crc16_align < br->consumed_bits; br->crc16_align += 8)
  92279. br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)((tail >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), br->read_crc16);
  92280. }
  92281. return br->read_crc16;
  92282. }
  92283. FLaC__INLINE FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br)
  92284. {
  92285. return ((br->consumed_bits & 7) == 0);
  92286. }
  92287. FLaC__INLINE unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br)
  92288. {
  92289. return 8 - (br->consumed_bits & 7);
  92290. }
  92291. FLaC__INLINE unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br)
  92292. {
  92293. return (br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits;
  92294. }
  92295. FLaC__INLINE FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits)
  92296. {
  92297. FLAC__ASSERT(0 != br);
  92298. FLAC__ASSERT(0 != br->buffer);
  92299. FLAC__ASSERT(bits <= 32);
  92300. FLAC__ASSERT((br->capacity*FLAC__BITS_PER_WORD) * 2 >= bits);
  92301. FLAC__ASSERT(br->consumed_words <= br->words);
  92302. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  92303. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  92304. if(bits == 0) { /* OPT: investigate if this can ever happen, maybe change to assertion */
  92305. *val = 0;
  92306. return true;
  92307. }
  92308. while((br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits < bits) {
  92309. if(!bitreader_read_from_client_(br))
  92310. return false;
  92311. }
  92312. if(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  92313. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  92314. if(br->consumed_bits) {
  92315. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  92316. const unsigned n = FLAC__BITS_PER_WORD - br->consumed_bits;
  92317. const brword word = br->buffer[br->consumed_words];
  92318. if(bits < n) {
  92319. *val = (word & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (n-bits);
  92320. br->consumed_bits += bits;
  92321. return true;
  92322. }
  92323. *val = word & (FLAC__WORD_ALL_ONES >> br->consumed_bits);
  92324. bits -= n;
  92325. crc16_update_word_(br, word);
  92326. br->consumed_words++;
  92327. br->consumed_bits = 0;
  92328. 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 */
  92329. *val <<= bits;
  92330. *val |= (br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits));
  92331. br->consumed_bits = bits;
  92332. }
  92333. return true;
  92334. }
  92335. else {
  92336. const brword word = br->buffer[br->consumed_words];
  92337. if(bits < FLAC__BITS_PER_WORD) {
  92338. *val = word >> (FLAC__BITS_PER_WORD-bits);
  92339. br->consumed_bits = bits;
  92340. return true;
  92341. }
  92342. /* at this point 'bits' must be == FLAC__BITS_PER_WORD; because of previous assertions, it can't be larger */
  92343. *val = word;
  92344. crc16_update_word_(br, word);
  92345. br->consumed_words++;
  92346. return true;
  92347. }
  92348. }
  92349. else {
  92350. /* in this case we're starting our read at a partial tail word;
  92351. * the reader has guaranteed that we have at least 'bits' bits
  92352. * available to read, which makes this case simpler.
  92353. */
  92354. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  92355. if(br->consumed_bits) {
  92356. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  92357. FLAC__ASSERT(br->consumed_bits + bits <= br->bytes*8);
  92358. *val = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (FLAC__BITS_PER_WORD-br->consumed_bits-bits);
  92359. br->consumed_bits += bits;
  92360. return true;
  92361. }
  92362. else {
  92363. *val = br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits);
  92364. br->consumed_bits += bits;
  92365. return true;
  92366. }
  92367. }
  92368. }
  92369. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits)
  92370. {
  92371. /* OPT: inline raw uint32 code here, or make into a macro if possible in the .h file */
  92372. if(!FLAC__bitreader_read_raw_uint32(br, (FLAC__uint32*)val, bits))
  92373. return false;
  92374. /* sign-extend: */
  92375. *val <<= (32-bits);
  92376. *val >>= (32-bits);
  92377. return true;
  92378. }
  92379. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits)
  92380. {
  92381. FLAC__uint32 hi, lo;
  92382. if(bits > 32) {
  92383. if(!FLAC__bitreader_read_raw_uint32(br, &hi, bits-32))
  92384. return false;
  92385. if(!FLAC__bitreader_read_raw_uint32(br, &lo, 32))
  92386. return false;
  92387. *val = hi;
  92388. *val <<= 32;
  92389. *val |= lo;
  92390. }
  92391. else {
  92392. if(!FLAC__bitreader_read_raw_uint32(br, &lo, bits))
  92393. return false;
  92394. *val = lo;
  92395. }
  92396. return true;
  92397. }
  92398. FLaC__INLINE FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val)
  92399. {
  92400. FLAC__uint32 x8, x32 = 0;
  92401. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  92402. if(!FLAC__bitreader_read_raw_uint32(br, &x32, 8))
  92403. return false;
  92404. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  92405. return false;
  92406. x32 |= (x8 << 8);
  92407. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  92408. return false;
  92409. x32 |= (x8 << 16);
  92410. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  92411. return false;
  92412. x32 |= (x8 << 24);
  92413. *val = x32;
  92414. return true;
  92415. }
  92416. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits)
  92417. {
  92418. /*
  92419. * OPT: a faster implementation is possible but probably not that useful
  92420. * since this is only called a couple of times in the metadata readers.
  92421. */
  92422. FLAC__ASSERT(0 != br);
  92423. FLAC__ASSERT(0 != br->buffer);
  92424. if(bits > 0) {
  92425. const unsigned n = br->consumed_bits & 7;
  92426. unsigned m;
  92427. FLAC__uint32 x;
  92428. if(n != 0) {
  92429. m = min(8-n, bits);
  92430. if(!FLAC__bitreader_read_raw_uint32(br, &x, m))
  92431. return false;
  92432. bits -= m;
  92433. }
  92434. m = bits / 8;
  92435. if(m > 0) {
  92436. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(br, m))
  92437. return false;
  92438. bits %= 8;
  92439. }
  92440. if(bits > 0) {
  92441. if(!FLAC__bitreader_read_raw_uint32(br, &x, bits))
  92442. return false;
  92443. }
  92444. }
  92445. return true;
  92446. }
  92447. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals)
  92448. {
  92449. FLAC__uint32 x;
  92450. FLAC__ASSERT(0 != br);
  92451. FLAC__ASSERT(0 != br->buffer);
  92452. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  92453. /* step 1: skip over partial head word to get word aligned */
  92454. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  92455. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  92456. return false;
  92457. nvals--;
  92458. }
  92459. if(0 == nvals)
  92460. return true;
  92461. /* step 2: skip whole words in chunks */
  92462. while(nvals >= FLAC__BYTES_PER_WORD) {
  92463. if(br->consumed_words < br->words) {
  92464. br->consumed_words++;
  92465. nvals -= FLAC__BYTES_PER_WORD;
  92466. }
  92467. else if(!bitreader_read_from_client_(br))
  92468. return false;
  92469. }
  92470. /* step 3: skip any remainder from partial tail bytes */
  92471. while(nvals) {
  92472. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  92473. return false;
  92474. nvals--;
  92475. }
  92476. return true;
  92477. }
  92478. FLAC__bool FLAC__bitreader_read_byte_block_aligned_no_crc(FLAC__BitReader *br, FLAC__byte *val, unsigned nvals)
  92479. {
  92480. FLAC__uint32 x;
  92481. FLAC__ASSERT(0 != br);
  92482. FLAC__ASSERT(0 != br->buffer);
  92483. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  92484. /* step 1: read from partial head word to get word aligned */
  92485. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  92486. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  92487. return false;
  92488. *val++ = (FLAC__byte)x;
  92489. nvals--;
  92490. }
  92491. if(0 == nvals)
  92492. return true;
  92493. /* step 2: read whole words in chunks */
  92494. while(nvals >= FLAC__BYTES_PER_WORD) {
  92495. if(br->consumed_words < br->words) {
  92496. const brword word = br->buffer[br->consumed_words++];
  92497. #if FLAC__BYTES_PER_WORD == 4
  92498. val[0] = (FLAC__byte)(word >> 24);
  92499. val[1] = (FLAC__byte)(word >> 16);
  92500. val[2] = (FLAC__byte)(word >> 8);
  92501. val[3] = (FLAC__byte)word;
  92502. #elif FLAC__BYTES_PER_WORD == 8
  92503. val[0] = (FLAC__byte)(word >> 56);
  92504. val[1] = (FLAC__byte)(word >> 48);
  92505. val[2] = (FLAC__byte)(word >> 40);
  92506. val[3] = (FLAC__byte)(word >> 32);
  92507. val[4] = (FLAC__byte)(word >> 24);
  92508. val[5] = (FLAC__byte)(word >> 16);
  92509. val[6] = (FLAC__byte)(word >> 8);
  92510. val[7] = (FLAC__byte)word;
  92511. #else
  92512. for(x = 0; x < FLAC__BYTES_PER_WORD; x++)
  92513. val[x] = (FLAC__byte)(word >> (8*(FLAC__BYTES_PER_WORD-x-1)));
  92514. #endif
  92515. val += FLAC__BYTES_PER_WORD;
  92516. nvals -= FLAC__BYTES_PER_WORD;
  92517. }
  92518. else if(!bitreader_read_from_client_(br))
  92519. return false;
  92520. }
  92521. /* step 3: read any remainder from partial tail bytes */
  92522. while(nvals) {
  92523. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  92524. return false;
  92525. *val++ = (FLAC__byte)x;
  92526. nvals--;
  92527. }
  92528. return true;
  92529. }
  92530. FLaC__INLINE FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val)
  92531. #if 0 /* slow but readable version */
  92532. {
  92533. unsigned bit;
  92534. FLAC__ASSERT(0 != br);
  92535. FLAC__ASSERT(0 != br->buffer);
  92536. *val = 0;
  92537. while(1) {
  92538. if(!FLAC__bitreader_read_bit(br, &bit))
  92539. return false;
  92540. if(bit)
  92541. break;
  92542. else
  92543. *val++;
  92544. }
  92545. return true;
  92546. }
  92547. #else
  92548. {
  92549. unsigned i;
  92550. FLAC__ASSERT(0 != br);
  92551. FLAC__ASSERT(0 != br->buffer);
  92552. *val = 0;
  92553. while(1) {
  92554. while(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  92555. brword b = br->buffer[br->consumed_words] << br->consumed_bits;
  92556. if(b) {
  92557. i = COUNT_ZERO_MSBS(b);
  92558. *val += i;
  92559. i++;
  92560. br->consumed_bits += i;
  92561. if(br->consumed_bits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(br->consumed_bits == FLAC__BITS_PER_WORD) */
  92562. crc16_update_word_(br, br->buffer[br->consumed_words]);
  92563. br->consumed_words++;
  92564. br->consumed_bits = 0;
  92565. }
  92566. return true;
  92567. }
  92568. else {
  92569. *val += FLAC__BITS_PER_WORD - br->consumed_bits;
  92570. crc16_update_word_(br, br->buffer[br->consumed_words]);
  92571. br->consumed_words++;
  92572. br->consumed_bits = 0;
  92573. /* didn't find stop bit yet, have to keep going... */
  92574. }
  92575. }
  92576. /* at this point we've eaten up all the whole words; have to try
  92577. * reading through any tail bytes before calling the read callback.
  92578. * this is a repeat of the above logic adjusted for the fact we
  92579. * don't have a whole word. note though if the client is feeding
  92580. * us data a byte at a time (unlikely), br->consumed_bits may not
  92581. * be zero.
  92582. */
  92583. if(br->bytes) {
  92584. const unsigned end = br->bytes * 8;
  92585. brword b = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << br->consumed_bits;
  92586. if(b) {
  92587. i = COUNT_ZERO_MSBS(b);
  92588. *val += i;
  92589. i++;
  92590. br->consumed_bits += i;
  92591. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  92592. return true;
  92593. }
  92594. else {
  92595. *val += end - br->consumed_bits;
  92596. br->consumed_bits += end;
  92597. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  92598. /* didn't find stop bit yet, have to keep going... */
  92599. }
  92600. }
  92601. if(!bitreader_read_from_client_(br))
  92602. return false;
  92603. }
  92604. }
  92605. #endif
  92606. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  92607. {
  92608. FLAC__uint32 lsbs = 0, msbs = 0;
  92609. unsigned uval;
  92610. FLAC__ASSERT(0 != br);
  92611. FLAC__ASSERT(0 != br->buffer);
  92612. FLAC__ASSERT(parameter <= 31);
  92613. /* read the unary MSBs and end bit */
  92614. if(!FLAC__bitreader_read_unary_unsigned(br, (unsigned int*) &msbs))
  92615. return false;
  92616. /* read the binary LSBs */
  92617. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, parameter))
  92618. return false;
  92619. /* compose the value */
  92620. uval = (msbs << parameter) | lsbs;
  92621. if(uval & 1)
  92622. *val = -((int)(uval >> 1)) - 1;
  92623. else
  92624. *val = (int)(uval >> 1);
  92625. return true;
  92626. }
  92627. /* this is by far the most heavily used reader call. it ain't pretty but it's fast */
  92628. /* a lot of the logic is copied, then adapted, from FLAC__bitreader_read_unary_unsigned() and FLAC__bitreader_read_raw_uint32() */
  92629. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter)
  92630. /* OPT: possibly faster version for use with MSVC */
  92631. #ifdef _MSC_VER
  92632. {
  92633. unsigned i;
  92634. unsigned uval = 0;
  92635. unsigned bits; /* the # of binary LSBs left to read to finish a rice codeword */
  92636. /* try and get br->consumed_words and br->consumed_bits into register;
  92637. * must remember to flush them back to *br before calling other
  92638. * bitwriter functions that use them, and before returning */
  92639. register unsigned cwords;
  92640. register unsigned cbits;
  92641. FLAC__ASSERT(0 != br);
  92642. FLAC__ASSERT(0 != br->buffer);
  92643. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  92644. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  92645. FLAC__ASSERT(parameter < 32);
  92646. /* 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 */
  92647. if(nvals == 0)
  92648. return true;
  92649. cbits = br->consumed_bits;
  92650. cwords = br->consumed_words;
  92651. while(1) {
  92652. /* read unary part */
  92653. while(1) {
  92654. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  92655. brword b = br->buffer[cwords] << cbits;
  92656. if(b) {
  92657. #if 0 /* slower, probably due to bad register allocation... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32
  92658. __asm {
  92659. bsr eax, b
  92660. not eax
  92661. and eax, 31
  92662. mov i, eax
  92663. }
  92664. #else
  92665. i = COUNT_ZERO_MSBS(b);
  92666. #endif
  92667. uval += i;
  92668. bits = parameter;
  92669. i++;
  92670. cbits += i;
  92671. if(cbits == FLAC__BITS_PER_WORD) {
  92672. crc16_update_word_(br, br->buffer[cwords]);
  92673. cwords++;
  92674. cbits = 0;
  92675. }
  92676. goto break1;
  92677. }
  92678. else {
  92679. uval += FLAC__BITS_PER_WORD - cbits;
  92680. crc16_update_word_(br, br->buffer[cwords]);
  92681. cwords++;
  92682. cbits = 0;
  92683. /* didn't find stop bit yet, have to keep going... */
  92684. }
  92685. }
  92686. /* at this point we've eaten up all the whole words; have to try
  92687. * reading through any tail bytes before calling the read callback.
  92688. * this is a repeat of the above logic adjusted for the fact we
  92689. * don't have a whole word. note though if the client is feeding
  92690. * us data a byte at a time (unlikely), br->consumed_bits may not
  92691. * be zero.
  92692. */
  92693. if(br->bytes) {
  92694. const unsigned end = br->bytes * 8;
  92695. brword b = (br->buffer[cwords] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << cbits;
  92696. if(b) {
  92697. i = COUNT_ZERO_MSBS(b);
  92698. uval += i;
  92699. bits = parameter;
  92700. i++;
  92701. cbits += i;
  92702. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  92703. goto break1;
  92704. }
  92705. else {
  92706. uval += end - cbits;
  92707. cbits += end;
  92708. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  92709. /* didn't find stop bit yet, have to keep going... */
  92710. }
  92711. }
  92712. /* flush registers and read; bitreader_read_from_client_() does
  92713. * not touch br->consumed_bits at all but we still need to set
  92714. * it in case it fails and we have to return false.
  92715. */
  92716. br->consumed_bits = cbits;
  92717. br->consumed_words = cwords;
  92718. if(!bitreader_read_from_client_(br))
  92719. return false;
  92720. cwords = br->consumed_words;
  92721. }
  92722. break1:
  92723. /* read binary part */
  92724. FLAC__ASSERT(cwords <= br->words);
  92725. if(bits) {
  92726. while((br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits < bits) {
  92727. /* flush registers and read; bitreader_read_from_client_() does
  92728. * not touch br->consumed_bits at all but we still need to set
  92729. * it in case it fails and we have to return false.
  92730. */
  92731. br->consumed_bits = cbits;
  92732. br->consumed_words = cwords;
  92733. if(!bitreader_read_from_client_(br))
  92734. return false;
  92735. cwords = br->consumed_words;
  92736. }
  92737. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  92738. if(cbits) {
  92739. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  92740. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  92741. const brword word = br->buffer[cwords];
  92742. if(bits < n) {
  92743. uval <<= bits;
  92744. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-bits);
  92745. cbits += bits;
  92746. goto break2;
  92747. }
  92748. uval <<= n;
  92749. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  92750. bits -= n;
  92751. crc16_update_word_(br, word);
  92752. cwords++;
  92753. cbits = 0;
  92754. 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 */
  92755. uval <<= bits;
  92756. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits));
  92757. cbits = bits;
  92758. }
  92759. goto break2;
  92760. }
  92761. else {
  92762. FLAC__ASSERT(bits < FLAC__BITS_PER_WORD);
  92763. uval <<= bits;
  92764. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  92765. cbits = bits;
  92766. goto break2;
  92767. }
  92768. }
  92769. else {
  92770. /* in this case we're starting our read at a partial tail word;
  92771. * the reader has guaranteed that we have at least 'bits' bits
  92772. * available to read, which makes this case simpler.
  92773. */
  92774. uval <<= bits;
  92775. if(cbits) {
  92776. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  92777. FLAC__ASSERT(cbits + bits <= br->bytes*8);
  92778. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-bits);
  92779. cbits += bits;
  92780. goto break2;
  92781. }
  92782. else {
  92783. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  92784. cbits += bits;
  92785. goto break2;
  92786. }
  92787. }
  92788. }
  92789. break2:
  92790. /* compose the value */
  92791. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  92792. /* are we done? */
  92793. --nvals;
  92794. if(nvals == 0) {
  92795. br->consumed_bits = cbits;
  92796. br->consumed_words = cwords;
  92797. return true;
  92798. }
  92799. uval = 0;
  92800. ++vals;
  92801. }
  92802. }
  92803. #else
  92804. {
  92805. unsigned i;
  92806. unsigned uval = 0;
  92807. /* try and get br->consumed_words and br->consumed_bits into register;
  92808. * must remember to flush them back to *br before calling other
  92809. * bitwriter functions that use them, and before returning */
  92810. register unsigned cwords;
  92811. register unsigned cbits;
  92812. unsigned ucbits; /* keep track of the number of unconsumed bits in the buffer */
  92813. FLAC__ASSERT(0 != br);
  92814. FLAC__ASSERT(0 != br->buffer);
  92815. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  92816. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  92817. FLAC__ASSERT(parameter < 32);
  92818. /* 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 */
  92819. if(nvals == 0)
  92820. return true;
  92821. cbits = br->consumed_bits;
  92822. cwords = br->consumed_words;
  92823. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  92824. while(1) {
  92825. /* read unary part */
  92826. while(1) {
  92827. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  92828. brword b = br->buffer[cwords] << cbits;
  92829. if(b) {
  92830. #if 0 /* is not discernably faster... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32 && defined __GNUC__
  92831. asm volatile (
  92832. "bsrl %1, %0;"
  92833. "notl %0;"
  92834. "andl $31, %0;"
  92835. : "=r"(i)
  92836. : "r"(b)
  92837. );
  92838. #else
  92839. i = COUNT_ZERO_MSBS(b);
  92840. #endif
  92841. uval += i;
  92842. cbits += i;
  92843. cbits++; /* skip over stop bit */
  92844. if(cbits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(cbits == FLAC__BITS_PER_WORD) */
  92845. crc16_update_word_(br, br->buffer[cwords]);
  92846. cwords++;
  92847. cbits = 0;
  92848. }
  92849. goto break1;
  92850. }
  92851. else {
  92852. uval += FLAC__BITS_PER_WORD - cbits;
  92853. crc16_update_word_(br, br->buffer[cwords]);
  92854. cwords++;
  92855. cbits = 0;
  92856. /* didn't find stop bit yet, have to keep going... */
  92857. }
  92858. }
  92859. /* at this point we've eaten up all the whole words; have to try
  92860. * reading through any tail bytes before calling the read callback.
  92861. * this is a repeat of the above logic adjusted for the fact we
  92862. * don't have a whole word. note though if the client is feeding
  92863. * us data a byte at a time (unlikely), br->consumed_bits may not
  92864. * be zero.
  92865. */
  92866. if(br->bytes) {
  92867. const unsigned end = br->bytes * 8;
  92868. brword b = (br->buffer[cwords] & ~(FLAC__WORD_ALL_ONES >> end)) << cbits;
  92869. if(b) {
  92870. i = COUNT_ZERO_MSBS(b);
  92871. uval += i;
  92872. cbits += i;
  92873. cbits++; /* skip over stop bit */
  92874. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  92875. goto break1;
  92876. }
  92877. else {
  92878. uval += end - cbits;
  92879. cbits += end;
  92880. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  92881. /* didn't find stop bit yet, have to keep going... */
  92882. }
  92883. }
  92884. /* flush registers and read; bitreader_read_from_client_() does
  92885. * not touch br->consumed_bits at all but we still need to set
  92886. * it in case it fails and we have to return false.
  92887. */
  92888. br->consumed_bits = cbits;
  92889. br->consumed_words = cwords;
  92890. if(!bitreader_read_from_client_(br))
  92891. return false;
  92892. cwords = br->consumed_words;
  92893. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits + uval;
  92894. /* + uval to offset our count by the # of unary bits already
  92895. * consumed before the read, because we will add these back
  92896. * in all at once at break1
  92897. */
  92898. }
  92899. break1:
  92900. ucbits -= uval;
  92901. ucbits--; /* account for stop bit */
  92902. /* read binary part */
  92903. FLAC__ASSERT(cwords <= br->words);
  92904. if(parameter) {
  92905. while(ucbits < parameter) {
  92906. /* flush registers and read; bitreader_read_from_client_() does
  92907. * not touch br->consumed_bits at all but we still need to set
  92908. * it in case it fails and we have to return false.
  92909. */
  92910. br->consumed_bits = cbits;
  92911. br->consumed_words = cwords;
  92912. if(!bitreader_read_from_client_(br))
  92913. return false;
  92914. cwords = br->consumed_words;
  92915. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  92916. }
  92917. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  92918. if(cbits) {
  92919. /* this also works when consumed_bits==0, it's just slower than necessary for that case */
  92920. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  92921. const brword word = br->buffer[cwords];
  92922. if(parameter < n) {
  92923. uval <<= parameter;
  92924. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-parameter);
  92925. cbits += parameter;
  92926. }
  92927. else {
  92928. uval <<= n;
  92929. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  92930. crc16_update_word_(br, word);
  92931. cwords++;
  92932. cbits = parameter - n;
  92933. 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 */
  92934. uval <<= cbits;
  92935. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits));
  92936. }
  92937. }
  92938. }
  92939. else {
  92940. cbits = parameter;
  92941. uval <<= parameter;
  92942. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  92943. }
  92944. }
  92945. else {
  92946. /* in this case we're starting our read at a partial tail word;
  92947. * the reader has guaranteed that we have at least 'parameter'
  92948. * bits available to read, which makes this case simpler.
  92949. */
  92950. uval <<= parameter;
  92951. if(cbits) {
  92952. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  92953. FLAC__ASSERT(cbits + parameter <= br->bytes*8);
  92954. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-parameter);
  92955. cbits += parameter;
  92956. }
  92957. else {
  92958. cbits = parameter;
  92959. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  92960. }
  92961. }
  92962. }
  92963. ucbits -= parameter;
  92964. /* compose the value */
  92965. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  92966. /* are we done? */
  92967. --nvals;
  92968. if(nvals == 0) {
  92969. br->consumed_bits = cbits;
  92970. br->consumed_words = cwords;
  92971. return true;
  92972. }
  92973. uval = 0;
  92974. ++vals;
  92975. }
  92976. }
  92977. #endif
  92978. #if 0 /* UNUSED */
  92979. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  92980. {
  92981. FLAC__uint32 lsbs = 0, msbs = 0;
  92982. unsigned bit, uval, k;
  92983. FLAC__ASSERT(0 != br);
  92984. FLAC__ASSERT(0 != br->buffer);
  92985. k = FLAC__bitmath_ilog2(parameter);
  92986. /* read the unary MSBs and end bit */
  92987. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  92988. return false;
  92989. /* read the binary LSBs */
  92990. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  92991. return false;
  92992. if(parameter == 1u<<k) {
  92993. /* compose the value */
  92994. uval = (msbs << k) | lsbs;
  92995. }
  92996. else {
  92997. unsigned d = (1 << (k+1)) - parameter;
  92998. if(lsbs >= d) {
  92999. if(!FLAC__bitreader_read_bit(br, &bit))
  93000. return false;
  93001. lsbs <<= 1;
  93002. lsbs |= bit;
  93003. lsbs -= d;
  93004. }
  93005. /* compose the value */
  93006. uval = msbs * parameter + lsbs;
  93007. }
  93008. /* unfold unsigned to signed */
  93009. if(uval & 1)
  93010. *val = -((int)(uval >> 1)) - 1;
  93011. else
  93012. *val = (int)(uval >> 1);
  93013. return true;
  93014. }
  93015. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter)
  93016. {
  93017. FLAC__uint32 lsbs, msbs = 0;
  93018. unsigned bit, k;
  93019. FLAC__ASSERT(0 != br);
  93020. FLAC__ASSERT(0 != br->buffer);
  93021. k = FLAC__bitmath_ilog2(parameter);
  93022. /* read the unary MSBs and end bit */
  93023. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  93024. return false;
  93025. /* read the binary LSBs */
  93026. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  93027. return false;
  93028. if(parameter == 1u<<k) {
  93029. /* compose the value */
  93030. *val = (msbs << k) | lsbs;
  93031. }
  93032. else {
  93033. unsigned d = (1 << (k+1)) - parameter;
  93034. if(lsbs >= d) {
  93035. if(!FLAC__bitreader_read_bit(br, &bit))
  93036. return false;
  93037. lsbs <<= 1;
  93038. lsbs |= bit;
  93039. lsbs -= d;
  93040. }
  93041. /* compose the value */
  93042. *val = msbs * parameter + lsbs;
  93043. }
  93044. return true;
  93045. }
  93046. #endif /* UNUSED */
  93047. /* on return, if *val == 0xffffffff then the utf-8 sequence was invalid, but the return value will be true */
  93048. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen)
  93049. {
  93050. FLAC__uint32 v = 0;
  93051. FLAC__uint32 x;
  93052. unsigned i;
  93053. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93054. return false;
  93055. if(raw)
  93056. raw[(*rawlen)++] = (FLAC__byte)x;
  93057. if(!(x & 0x80)) { /* 0xxxxxxx */
  93058. v = x;
  93059. i = 0;
  93060. }
  93061. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  93062. v = x & 0x1F;
  93063. i = 1;
  93064. }
  93065. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  93066. v = x & 0x0F;
  93067. i = 2;
  93068. }
  93069. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  93070. v = x & 0x07;
  93071. i = 3;
  93072. }
  93073. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  93074. v = x & 0x03;
  93075. i = 4;
  93076. }
  93077. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  93078. v = x & 0x01;
  93079. i = 5;
  93080. }
  93081. else {
  93082. *val = 0xffffffff;
  93083. return true;
  93084. }
  93085. for( ; i; i--) {
  93086. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93087. return false;
  93088. if(raw)
  93089. raw[(*rawlen)++] = (FLAC__byte)x;
  93090. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  93091. *val = 0xffffffff;
  93092. return true;
  93093. }
  93094. v <<= 6;
  93095. v |= (x & 0x3F);
  93096. }
  93097. *val = v;
  93098. return true;
  93099. }
  93100. /* on return, if *val == 0xffffffffffffffff then the utf-8 sequence was invalid, but the return value will be true */
  93101. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen)
  93102. {
  93103. FLAC__uint64 v = 0;
  93104. FLAC__uint32 x;
  93105. unsigned i;
  93106. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93107. return false;
  93108. if(raw)
  93109. raw[(*rawlen)++] = (FLAC__byte)x;
  93110. if(!(x & 0x80)) { /* 0xxxxxxx */
  93111. v = x;
  93112. i = 0;
  93113. }
  93114. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  93115. v = x & 0x1F;
  93116. i = 1;
  93117. }
  93118. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  93119. v = x & 0x0F;
  93120. i = 2;
  93121. }
  93122. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  93123. v = x & 0x07;
  93124. i = 3;
  93125. }
  93126. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  93127. v = x & 0x03;
  93128. i = 4;
  93129. }
  93130. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  93131. v = x & 0x01;
  93132. i = 5;
  93133. }
  93134. else if(x & 0xFE && !(x & 0x01)) { /* 11111110 */
  93135. v = 0;
  93136. i = 6;
  93137. }
  93138. else {
  93139. *val = FLAC__U64L(0xffffffffffffffff);
  93140. return true;
  93141. }
  93142. for( ; i; i--) {
  93143. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93144. return false;
  93145. if(raw)
  93146. raw[(*rawlen)++] = (FLAC__byte)x;
  93147. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  93148. *val = FLAC__U64L(0xffffffffffffffff);
  93149. return true;
  93150. }
  93151. v <<= 6;
  93152. v |= (x & 0x3F);
  93153. }
  93154. *val = v;
  93155. return true;
  93156. }
  93157. #endif
  93158. /*** End of inlined file: bitreader.c ***/
  93159. /*** Start of inlined file: bitwriter.c ***/
  93160. /*** Start of inlined file: juce_FlacHeader.h ***/
  93161. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  93162. // tasks..
  93163. #define VERSION "1.2.1"
  93164. #define FLAC__NO_DLL 1
  93165. #if JUCE_MSVC
  93166. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  93167. #endif
  93168. #if JUCE_MAC
  93169. #define FLAC__SYS_DARWIN 1
  93170. #endif
  93171. /*** End of inlined file: juce_FlacHeader.h ***/
  93172. #if JUCE_USE_FLAC
  93173. #if HAVE_CONFIG_H
  93174. # include <config.h>
  93175. #endif
  93176. #include <stdlib.h> /* for malloc() */
  93177. #include <string.h> /* for memcpy(), memset() */
  93178. #ifdef _MSC_VER
  93179. #include <winsock.h> /* for ntohl() */
  93180. #elif defined FLAC__SYS_DARWIN
  93181. #include <machine/endian.h> /* for ntohl() */
  93182. #elif defined __MINGW32__
  93183. #include <winsock.h> /* for ntohl() */
  93184. #else
  93185. #include <netinet/in.h> /* for ntohl() */
  93186. #endif
  93187. #if 0 /* UNUSED */
  93188. #endif
  93189. /*** Start of inlined file: bitwriter.h ***/
  93190. #ifndef FLAC__PRIVATE__BITWRITER_H
  93191. #define FLAC__PRIVATE__BITWRITER_H
  93192. #include <stdio.h> /* for FILE */
  93193. /*
  93194. * opaque structure definition
  93195. */
  93196. struct FLAC__BitWriter;
  93197. typedef struct FLAC__BitWriter FLAC__BitWriter;
  93198. /*
  93199. * construction, deletion, initialization, etc functions
  93200. */
  93201. FLAC__BitWriter *FLAC__bitwriter_new(void);
  93202. void FLAC__bitwriter_delete(FLAC__BitWriter *bw);
  93203. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw);
  93204. void FLAC__bitwriter_free(FLAC__BitWriter *bw); /* does not 'free(buffer)' */
  93205. void FLAC__bitwriter_clear(FLAC__BitWriter *bw);
  93206. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out);
  93207. /*
  93208. * CRC functions
  93209. *
  93210. * non-const *bw because they have to cal FLAC__bitwriter_get_buffer()
  93211. */
  93212. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc);
  93213. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc);
  93214. /*
  93215. * info functions
  93216. */
  93217. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw);
  93218. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw); /* can be called anytime, returns total # of bits unconsumed */
  93219. /*
  93220. * direct buffer access
  93221. *
  93222. * there may be no calls on the bitwriter between get and release.
  93223. * the bitwriter continues to own the returned buffer.
  93224. * before get, bitwriter MUST be byte aligned: check with FLAC__bitwriter_is_byte_aligned()
  93225. */
  93226. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes);
  93227. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw);
  93228. /*
  93229. * write functions
  93230. */
  93231. FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits);
  93232. FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits);
  93233. FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits);
  93234. FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits);
  93235. FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val); /*only for bits=32*/
  93236. FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals);
  93237. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val);
  93238. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter);
  93239. #if 0 /* UNUSED */
  93240. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter);
  93241. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned val, unsigned parameter);
  93242. #endif
  93243. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter);
  93244. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter);
  93245. #if 0 /* UNUSED */
  93246. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter);
  93247. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned val, unsigned parameter);
  93248. #endif
  93249. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val);
  93250. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val);
  93251. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw);
  93252. #endif
  93253. /*** End of inlined file: bitwriter.h ***/
  93254. /*** Start of inlined file: alloc.h ***/
  93255. #ifndef FLAC__SHARE__ALLOC_H
  93256. #define FLAC__SHARE__ALLOC_H
  93257. #if HAVE_CONFIG_H
  93258. # include <config.h>
  93259. #endif
  93260. /* WATCHOUT: for c++ you may have to #define __STDC_LIMIT_MACROS 1 real early
  93261. * before #including this file, otherwise SIZE_MAX might not be defined
  93262. */
  93263. #include <limits.h> /* for SIZE_MAX */
  93264. #if !defined _MSC_VER && !defined __MINGW32__ && !defined __EMX__
  93265. #include <stdint.h> /* for SIZE_MAX in case limits.h didn't get it */
  93266. #endif
  93267. #include <stdlib.h> /* for size_t, malloc(), etc */
  93268. #ifndef SIZE_MAX
  93269. # ifndef SIZE_T_MAX
  93270. # ifdef _MSC_VER
  93271. # define SIZE_T_MAX UINT_MAX
  93272. # else
  93273. # error
  93274. # endif
  93275. # endif
  93276. # define SIZE_MAX SIZE_T_MAX
  93277. #endif
  93278. #ifndef FLaC__INLINE
  93279. #define FLaC__INLINE
  93280. #endif
  93281. /* avoid malloc()ing 0 bytes, see:
  93282. * https://www.securecoding.cert.org/confluence/display/seccode/MEM04-A.+Do+not+make+assumptions+about+the+result+of+allocating+0+bytes?focusedCommentId=5407003
  93283. */
  93284. static FLaC__INLINE void *safe_malloc_(size_t size)
  93285. {
  93286. /* malloc(0) is undefined; FLAC src convention is to always allocate */
  93287. if(!size)
  93288. size++;
  93289. return malloc(size);
  93290. }
  93291. static FLaC__INLINE void *safe_calloc_(size_t nmemb, size_t size)
  93292. {
  93293. if(!nmemb || !size)
  93294. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  93295. return calloc(nmemb, size);
  93296. }
  93297. /*@@@@ there's probably a better way to prevent overflows when allocating untrusted sums but this works for now */
  93298. static FLaC__INLINE void *safe_malloc_add_2op_(size_t size1, size_t size2)
  93299. {
  93300. size2 += size1;
  93301. if(size2 < size1)
  93302. return 0;
  93303. return safe_malloc_(size2);
  93304. }
  93305. static FLaC__INLINE void *safe_malloc_add_3op_(size_t size1, size_t size2, size_t size3)
  93306. {
  93307. size2 += size1;
  93308. if(size2 < size1)
  93309. return 0;
  93310. size3 += size2;
  93311. if(size3 < size2)
  93312. return 0;
  93313. return safe_malloc_(size3);
  93314. }
  93315. static FLaC__INLINE void *safe_malloc_add_4op_(size_t size1, size_t size2, size_t size3, size_t size4)
  93316. {
  93317. size2 += size1;
  93318. if(size2 < size1)
  93319. return 0;
  93320. size3 += size2;
  93321. if(size3 < size2)
  93322. return 0;
  93323. size4 += size3;
  93324. if(size4 < size3)
  93325. return 0;
  93326. return safe_malloc_(size4);
  93327. }
  93328. static FLaC__INLINE void *safe_malloc_mul_2op_(size_t size1, size_t size2)
  93329. #if 0
  93330. needs support for cases where sizeof(size_t) != 4
  93331. {
  93332. /* could be faster #ifdef'ing off SIZEOF_SIZE_T */
  93333. if(sizeof(size_t) == 4) {
  93334. if ((double)size1 * (double)size2 < 4294967296.0)
  93335. return malloc(size1*size2);
  93336. }
  93337. return 0;
  93338. }
  93339. #else
  93340. /* better? */
  93341. {
  93342. if(!size1 || !size2)
  93343. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  93344. if(size1 > SIZE_MAX / size2)
  93345. return 0;
  93346. return malloc(size1*size2);
  93347. }
  93348. #endif
  93349. static FLaC__INLINE void *safe_malloc_mul_3op_(size_t size1, size_t size2, size_t size3)
  93350. {
  93351. if(!size1 || !size2 || !size3)
  93352. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  93353. if(size1 > SIZE_MAX / size2)
  93354. return 0;
  93355. size1 *= size2;
  93356. if(size1 > SIZE_MAX / size3)
  93357. return 0;
  93358. return malloc(size1*size3);
  93359. }
  93360. /* size1*size2 + size3 */
  93361. static FLaC__INLINE void *safe_malloc_mul2add_(size_t size1, size_t size2, size_t size3)
  93362. {
  93363. if(!size1 || !size2)
  93364. return safe_malloc_(size3);
  93365. if(size1 > SIZE_MAX / size2)
  93366. return 0;
  93367. return safe_malloc_add_2op_(size1*size2, size3);
  93368. }
  93369. /* size1 * (size2 + size3) */
  93370. static FLaC__INLINE void *safe_malloc_muladd2_(size_t size1, size_t size2, size_t size3)
  93371. {
  93372. if(!size1 || (!size2 && !size3))
  93373. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  93374. size2 += size3;
  93375. if(size2 < size3)
  93376. return 0;
  93377. return safe_malloc_mul_2op_(size1, size2);
  93378. }
  93379. static FLaC__INLINE void *safe_realloc_add_2op_(void *ptr, size_t size1, size_t size2)
  93380. {
  93381. size2 += size1;
  93382. if(size2 < size1)
  93383. return 0;
  93384. return realloc(ptr, size2);
  93385. }
  93386. static FLaC__INLINE void *safe_realloc_add_3op_(void *ptr, size_t size1, size_t size2, size_t size3)
  93387. {
  93388. size2 += size1;
  93389. if(size2 < size1)
  93390. return 0;
  93391. size3 += size2;
  93392. if(size3 < size2)
  93393. return 0;
  93394. return realloc(ptr, size3);
  93395. }
  93396. static FLaC__INLINE void *safe_realloc_add_4op_(void *ptr, size_t size1, size_t size2, size_t size3, size_t size4)
  93397. {
  93398. size2 += size1;
  93399. if(size2 < size1)
  93400. return 0;
  93401. size3 += size2;
  93402. if(size3 < size2)
  93403. return 0;
  93404. size4 += size3;
  93405. if(size4 < size3)
  93406. return 0;
  93407. return realloc(ptr, size4);
  93408. }
  93409. static FLaC__INLINE void *safe_realloc_mul_2op_(void *ptr, size_t size1, size_t size2)
  93410. {
  93411. if(!size1 || !size2)
  93412. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  93413. if(size1 > SIZE_MAX / size2)
  93414. return 0;
  93415. return realloc(ptr, size1*size2);
  93416. }
  93417. /* size1 * (size2 + size3) */
  93418. static FLaC__INLINE void *safe_realloc_muladd2_(void *ptr, size_t size1, size_t size2, size_t size3)
  93419. {
  93420. if(!size1 || (!size2 && !size3))
  93421. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  93422. size2 += size3;
  93423. if(size2 < size3)
  93424. return 0;
  93425. return safe_realloc_mul_2op_(ptr, size1, size2);
  93426. }
  93427. #endif
  93428. /*** End of inlined file: alloc.h ***/
  93429. /* Things should be fastest when this matches the machine word size */
  93430. /* WATCHOUT: if you change this you must also change the following #defines down to SWAP_BE_WORD_TO_HOST below to match */
  93431. /* WATCHOUT: there are a few places where the code will not work unless bwword is >= 32 bits wide */
  93432. typedef FLAC__uint32 bwword;
  93433. #define FLAC__BYTES_PER_WORD 4
  93434. #define FLAC__BITS_PER_WORD 32
  93435. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  93436. /* SWAP_BE_WORD_TO_HOST swaps bytes in a bwword (which is always big-endian) if necessary to match host byte order */
  93437. #if WORDS_BIGENDIAN
  93438. #define SWAP_BE_WORD_TO_HOST(x) (x)
  93439. #else
  93440. #ifdef _MSC_VER
  93441. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  93442. #else
  93443. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  93444. #endif
  93445. #endif
  93446. /*
  93447. * The default capacity here doesn't matter too much. The buffer always grows
  93448. * to hold whatever is written to it. Usually the encoder will stop adding at
  93449. * a frame or metadata block, then write that out and clear the buffer for the
  93450. * next one.
  93451. */
  93452. static const unsigned FLAC__BITWRITER_DEFAULT_CAPACITY = 32768u / sizeof(bwword); /* size in words */
  93453. /* When growing, increment 4K at a time */
  93454. static const unsigned FLAC__BITWRITER_DEFAULT_INCREMENT = 4096u / sizeof(bwword); /* size in words */
  93455. #define FLAC__WORDS_TO_BITS(words) ((words) * FLAC__BITS_PER_WORD)
  93456. #define FLAC__TOTAL_BITS(bw) (FLAC__WORDS_TO_BITS((bw)->words) + (bw)->bits)
  93457. #ifdef min
  93458. #undef min
  93459. #endif
  93460. #define min(x,y) ((x)<(y)?(x):(y))
  93461. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  93462. #ifdef _MSC_VER
  93463. #define FLAC__U64L(x) x
  93464. #else
  93465. #define FLAC__U64L(x) x##LLU
  93466. #endif
  93467. #ifndef FLaC__INLINE
  93468. #define FLaC__INLINE
  93469. #endif
  93470. struct FLAC__BitWriter {
  93471. bwword *buffer;
  93472. bwword accum; /* accumulator; bits are right-justified; when full, accum is appended to buffer */
  93473. unsigned capacity; /* capacity of buffer in words */
  93474. unsigned words; /* # of complete words in buffer */
  93475. unsigned bits; /* # of used bits in accum */
  93476. };
  93477. /* * WATCHOUT: The current implementation only grows the buffer. */
  93478. static FLAC__bool bitwriter_grow_(FLAC__BitWriter *bw, unsigned bits_to_add)
  93479. {
  93480. unsigned new_capacity;
  93481. bwword *new_buffer;
  93482. FLAC__ASSERT(0 != bw);
  93483. FLAC__ASSERT(0 != bw->buffer);
  93484. /* calculate total words needed to store 'bits_to_add' additional bits */
  93485. new_capacity = bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD);
  93486. /* it's possible (due to pessimism in the growth estimation that
  93487. * leads to this call) that we don't actually need to grow
  93488. */
  93489. if(bw->capacity >= new_capacity)
  93490. return true;
  93491. /* round up capacity increase to the nearest FLAC__BITWRITER_DEFAULT_INCREMENT */
  93492. if((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT)
  93493. new_capacity += FLAC__BITWRITER_DEFAULT_INCREMENT - ((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  93494. /* make sure we got everything right */
  93495. FLAC__ASSERT(0 == (new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  93496. FLAC__ASSERT(new_capacity > bw->capacity);
  93497. FLAC__ASSERT(new_capacity >= bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD));
  93498. new_buffer = (bwword*)safe_realloc_mul_2op_(bw->buffer, sizeof(bwword), /*times*/new_capacity);
  93499. if(new_buffer == 0)
  93500. return false;
  93501. bw->buffer = new_buffer;
  93502. bw->capacity = new_capacity;
  93503. return true;
  93504. }
  93505. /***********************************************************************
  93506. *
  93507. * Class constructor/destructor
  93508. *
  93509. ***********************************************************************/
  93510. FLAC__BitWriter *FLAC__bitwriter_new(void)
  93511. {
  93512. FLAC__BitWriter *bw = (FLAC__BitWriter*)calloc(1, sizeof(FLAC__BitWriter));
  93513. /* note that calloc() sets all members to 0 for us */
  93514. return bw;
  93515. }
  93516. void FLAC__bitwriter_delete(FLAC__BitWriter *bw)
  93517. {
  93518. FLAC__ASSERT(0 != bw);
  93519. FLAC__bitwriter_free(bw);
  93520. free(bw);
  93521. }
  93522. /***********************************************************************
  93523. *
  93524. * Public class methods
  93525. *
  93526. ***********************************************************************/
  93527. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw)
  93528. {
  93529. FLAC__ASSERT(0 != bw);
  93530. bw->words = bw->bits = 0;
  93531. bw->capacity = FLAC__BITWRITER_DEFAULT_CAPACITY;
  93532. bw->buffer = (bwword*)malloc(sizeof(bwword) * bw->capacity);
  93533. if(bw->buffer == 0)
  93534. return false;
  93535. return true;
  93536. }
  93537. void FLAC__bitwriter_free(FLAC__BitWriter *bw)
  93538. {
  93539. FLAC__ASSERT(0 != bw);
  93540. if(0 != bw->buffer)
  93541. free(bw->buffer);
  93542. bw->buffer = 0;
  93543. bw->capacity = 0;
  93544. bw->words = bw->bits = 0;
  93545. }
  93546. void FLAC__bitwriter_clear(FLAC__BitWriter *bw)
  93547. {
  93548. bw->words = bw->bits = 0;
  93549. }
  93550. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out)
  93551. {
  93552. unsigned i, j;
  93553. if(bw == 0) {
  93554. fprintf(out, "bitwriter is NULL\n");
  93555. }
  93556. else {
  93557. fprintf(out, "bitwriter: capacity=%u words=%u bits=%u total_bits=%u\n", bw->capacity, bw->words, bw->bits, FLAC__TOTAL_BITS(bw));
  93558. for(i = 0; i < bw->words; i++) {
  93559. fprintf(out, "%08X: ", i);
  93560. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  93561. fprintf(out, "%01u", bw->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  93562. fprintf(out, "\n");
  93563. }
  93564. if(bw->bits > 0) {
  93565. fprintf(out, "%08X: ", i);
  93566. for(j = 0; j < bw->bits; j++)
  93567. fprintf(out, "%01u", bw->accum & (1 << (bw->bits-j-1)) ? 1:0);
  93568. fprintf(out, "\n");
  93569. }
  93570. }
  93571. }
  93572. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc)
  93573. {
  93574. const FLAC__byte *buffer;
  93575. size_t bytes;
  93576. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  93577. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  93578. return false;
  93579. *crc = (FLAC__uint16)FLAC__crc16(buffer, bytes);
  93580. FLAC__bitwriter_release_buffer(bw);
  93581. return true;
  93582. }
  93583. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc)
  93584. {
  93585. const FLAC__byte *buffer;
  93586. size_t bytes;
  93587. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  93588. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  93589. return false;
  93590. *crc = FLAC__crc8(buffer, bytes);
  93591. FLAC__bitwriter_release_buffer(bw);
  93592. return true;
  93593. }
  93594. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw)
  93595. {
  93596. return ((bw->bits & 7) == 0);
  93597. }
  93598. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw)
  93599. {
  93600. return FLAC__TOTAL_BITS(bw);
  93601. }
  93602. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes)
  93603. {
  93604. FLAC__ASSERT((bw->bits & 7) == 0);
  93605. /* double protection */
  93606. if(bw->bits & 7)
  93607. return false;
  93608. /* if we have bits in the accumulator we have to flush those to the buffer first */
  93609. if(bw->bits) {
  93610. FLAC__ASSERT(bw->words <= bw->capacity);
  93611. if(bw->words == bw->capacity && !bitwriter_grow_(bw, FLAC__BITS_PER_WORD))
  93612. return false;
  93613. /* append bits as complete word to buffer, but don't change bw->accum or bw->bits */
  93614. bw->buffer[bw->words] = SWAP_BE_WORD_TO_HOST(bw->accum << (FLAC__BITS_PER_WORD-bw->bits));
  93615. }
  93616. /* now we can just return what we have */
  93617. *buffer = (FLAC__byte*)bw->buffer;
  93618. *bytes = (FLAC__BYTES_PER_WORD * bw->words) + (bw->bits >> 3);
  93619. return true;
  93620. }
  93621. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw)
  93622. {
  93623. /* nothing to do. in the future, strict checking of a 'writer-is-in-
  93624. * get-mode' flag could be added everywhere and then cleared here
  93625. */
  93626. (void)bw;
  93627. }
  93628. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits)
  93629. {
  93630. unsigned n;
  93631. FLAC__ASSERT(0 != bw);
  93632. FLAC__ASSERT(0 != bw->buffer);
  93633. if(bits == 0)
  93634. return true;
  93635. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  93636. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  93637. return false;
  93638. /* first part gets to word alignment */
  93639. if(bw->bits) {
  93640. n = min(FLAC__BITS_PER_WORD - bw->bits, bits);
  93641. bw->accum <<= n;
  93642. bits -= n;
  93643. bw->bits += n;
  93644. if(bw->bits == FLAC__BITS_PER_WORD) {
  93645. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  93646. bw->bits = 0;
  93647. }
  93648. else
  93649. return true;
  93650. }
  93651. /* do whole words */
  93652. while(bits >= FLAC__BITS_PER_WORD) {
  93653. bw->buffer[bw->words++] = 0;
  93654. bits -= FLAC__BITS_PER_WORD;
  93655. }
  93656. /* do any leftovers */
  93657. if(bits > 0) {
  93658. bw->accum = 0;
  93659. bw->bits = bits;
  93660. }
  93661. return true;
  93662. }
  93663. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits)
  93664. {
  93665. register unsigned left;
  93666. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93667. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93668. FLAC__ASSERT(0 != bw);
  93669. FLAC__ASSERT(0 != bw->buffer);
  93670. FLAC__ASSERT(bits <= 32);
  93671. if(bits == 0)
  93672. return true;
  93673. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  93674. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  93675. return false;
  93676. left = FLAC__BITS_PER_WORD - bw->bits;
  93677. if(bits < left) {
  93678. bw->accum <<= bits;
  93679. bw->accum |= val;
  93680. bw->bits += bits;
  93681. }
  93682. 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 */
  93683. bw->accum <<= left;
  93684. bw->accum |= val >> (bw->bits = bits - left);
  93685. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  93686. bw->accum = val;
  93687. }
  93688. else {
  93689. bw->accum = val;
  93690. bw->bits = 0;
  93691. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(val);
  93692. }
  93693. return true;
  93694. }
  93695. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits)
  93696. {
  93697. /* zero-out unused bits */
  93698. if(bits < 32)
  93699. val &= (~(0xffffffff << bits));
  93700. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  93701. }
  93702. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits)
  93703. {
  93704. /* this could be a little faster but it's not used for much */
  93705. if(bits > 32) {
  93706. return
  93707. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(val>>32), bits-32) &&
  93708. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 32);
  93709. }
  93710. else
  93711. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  93712. }
  93713. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val)
  93714. {
  93715. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  93716. if(!FLAC__bitwriter_write_raw_uint32(bw, val & 0xff, 8))
  93717. return false;
  93718. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>8) & 0xff, 8))
  93719. return false;
  93720. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>16) & 0xff, 8))
  93721. return false;
  93722. if(!FLAC__bitwriter_write_raw_uint32(bw, val>>24, 8))
  93723. return false;
  93724. return true;
  93725. }
  93726. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals)
  93727. {
  93728. unsigned i;
  93729. /* this could be faster but currently we don't need it to be since it's only used for writing metadata */
  93730. for(i = 0; i < nvals; i++) {
  93731. if(!FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(vals[i]), 8))
  93732. return false;
  93733. }
  93734. return true;
  93735. }
  93736. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val)
  93737. {
  93738. if(val < 32)
  93739. return FLAC__bitwriter_write_raw_uint32(bw, 1, ++val);
  93740. else
  93741. return
  93742. FLAC__bitwriter_write_zeroes(bw, val) &&
  93743. FLAC__bitwriter_write_raw_uint32(bw, 1, 1);
  93744. }
  93745. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter)
  93746. {
  93747. FLAC__uint32 uval;
  93748. FLAC__ASSERT(parameter < sizeof(unsigned)*8);
  93749. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  93750. uval = (val<<1) ^ (val>>31);
  93751. return 1 + parameter + (uval >> parameter);
  93752. }
  93753. #if 0 /* UNUSED */
  93754. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter)
  93755. {
  93756. unsigned bits, msbs, uval;
  93757. unsigned k;
  93758. FLAC__ASSERT(parameter > 0);
  93759. /* fold signed to unsigned */
  93760. if(val < 0)
  93761. uval = (unsigned)(((-(++val)) << 1) + 1);
  93762. else
  93763. uval = (unsigned)(val << 1);
  93764. k = FLAC__bitmath_ilog2(parameter);
  93765. if(parameter == 1u<<k) {
  93766. FLAC__ASSERT(k <= 30);
  93767. msbs = uval >> k;
  93768. bits = 1 + k + msbs;
  93769. }
  93770. else {
  93771. unsigned q, r, d;
  93772. d = (1 << (k+1)) - parameter;
  93773. q = uval / parameter;
  93774. r = uval - (q * parameter);
  93775. bits = 1 + q + k;
  93776. if(r >= d)
  93777. bits++;
  93778. }
  93779. return bits;
  93780. }
  93781. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned uval, unsigned parameter)
  93782. {
  93783. unsigned bits, msbs;
  93784. unsigned k;
  93785. FLAC__ASSERT(parameter > 0);
  93786. k = FLAC__bitmath_ilog2(parameter);
  93787. if(parameter == 1u<<k) {
  93788. FLAC__ASSERT(k <= 30);
  93789. msbs = uval >> k;
  93790. bits = 1 + k + msbs;
  93791. }
  93792. else {
  93793. unsigned q, r, d;
  93794. d = (1 << (k+1)) - parameter;
  93795. q = uval / parameter;
  93796. r = uval - (q * parameter);
  93797. bits = 1 + q + k;
  93798. if(r >= d)
  93799. bits++;
  93800. }
  93801. return bits;
  93802. }
  93803. #endif /* UNUSED */
  93804. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter)
  93805. {
  93806. unsigned total_bits, interesting_bits, msbs;
  93807. FLAC__uint32 uval, pattern;
  93808. FLAC__ASSERT(0 != bw);
  93809. FLAC__ASSERT(0 != bw->buffer);
  93810. FLAC__ASSERT(parameter < 8*sizeof(uval));
  93811. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  93812. uval = (val<<1) ^ (val>>31);
  93813. msbs = uval >> parameter;
  93814. interesting_bits = 1 + parameter;
  93815. total_bits = interesting_bits + msbs;
  93816. pattern = 1 << parameter; /* the unary end bit */
  93817. pattern |= (uval & ((1<<parameter)-1)); /* the binary LSBs */
  93818. if(total_bits <= 32)
  93819. return FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits);
  93820. else
  93821. return
  93822. FLAC__bitwriter_write_zeroes(bw, msbs) && /* write the unary MSBs */
  93823. FLAC__bitwriter_write_raw_uint32(bw, pattern, interesting_bits); /* write the unary end bit and binary LSBs */
  93824. }
  93825. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter)
  93826. {
  93827. const FLAC__uint32 mask1 = FLAC__WORD_ALL_ONES << parameter; /* we val|=mask1 to set the stop bit above it... */
  93828. const FLAC__uint32 mask2 = FLAC__WORD_ALL_ONES >> (31-parameter); /* ...then mask off the bits above the stop bit with val&=mask2*/
  93829. FLAC__uint32 uval;
  93830. unsigned left;
  93831. const unsigned lsbits = 1 + parameter;
  93832. unsigned msbits;
  93833. FLAC__ASSERT(0 != bw);
  93834. FLAC__ASSERT(0 != bw->buffer);
  93835. FLAC__ASSERT(parameter < 8*sizeof(bwword)-1);
  93836. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93837. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93838. while(nvals) {
  93839. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  93840. uval = (*vals<<1) ^ (*vals>>31);
  93841. msbits = uval >> parameter;
  93842. #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) */
  93843. if(bw->bits && bw->bits + msbits + lsbits <= FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  93844. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  93845. bw->bits = bw->bits + msbits + lsbits;
  93846. uval |= mask1; /* set stop bit */
  93847. uval &= mask2; /* mask off unused top bits */
  93848. /* NOT: bw->accum <<= msbits + lsbits because msbits+lsbits could be 32, then the shift would be a NOP */
  93849. bw->accum <<= msbits;
  93850. bw->accum <<= lsbits;
  93851. bw->accum |= uval;
  93852. if(bw->bits == FLAC__BITS_PER_WORD) {
  93853. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  93854. bw->bits = 0;
  93855. /* burying the capacity check down here means we have to grow the buffer a little if there are more vals to do */
  93856. if(bw->capacity <= bw->words && nvals > 1 && !bitwriter_grow_(bw, 1)) {
  93857. FLAC__ASSERT(bw->capacity == bw->words);
  93858. return false;
  93859. }
  93860. }
  93861. }
  93862. else {
  93863. #elif 1 /*@@@@@@ OPT: try this version with MSVC6 to see if better, not much difference for gcc-4 */
  93864. if(bw->bits && bw->bits + msbits + lsbits < FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  93865. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  93866. bw->bits = bw->bits + msbits + lsbits;
  93867. uval |= mask1; /* set stop bit */
  93868. uval &= mask2; /* mask off unused top bits */
  93869. bw->accum <<= msbits + lsbits;
  93870. bw->accum |= uval;
  93871. }
  93872. else {
  93873. #endif
  93874. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+msbits+lsbits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  93875. /* OPT: pessimism may cause flurry of false calls to grow_ which eat up all savings before it */
  93876. if(bw->capacity <= bw->words + bw->bits + msbits + 1/*lsbits always fit in 1 bwword*/ && !bitwriter_grow_(bw, msbits+lsbits))
  93877. return false;
  93878. if(msbits) {
  93879. /* first part gets to word alignment */
  93880. if(bw->bits) {
  93881. left = FLAC__BITS_PER_WORD - bw->bits;
  93882. if(msbits < left) {
  93883. bw->accum <<= msbits;
  93884. bw->bits += msbits;
  93885. goto break1;
  93886. }
  93887. else {
  93888. bw->accum <<= left;
  93889. msbits -= left;
  93890. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  93891. bw->bits = 0;
  93892. }
  93893. }
  93894. /* do whole words */
  93895. while(msbits >= FLAC__BITS_PER_WORD) {
  93896. bw->buffer[bw->words++] = 0;
  93897. msbits -= FLAC__BITS_PER_WORD;
  93898. }
  93899. /* do any leftovers */
  93900. if(msbits > 0) {
  93901. bw->accum = 0;
  93902. bw->bits = msbits;
  93903. }
  93904. }
  93905. break1:
  93906. uval |= mask1; /* set stop bit */
  93907. uval &= mask2; /* mask off unused top bits */
  93908. left = FLAC__BITS_PER_WORD - bw->bits;
  93909. if(lsbits < left) {
  93910. bw->accum <<= lsbits;
  93911. bw->accum |= uval;
  93912. bw->bits += lsbits;
  93913. }
  93914. else {
  93915. /* if bw->bits == 0, left==FLAC__BITS_PER_WORD which will always
  93916. * be > lsbits (because of previous assertions) so it would have
  93917. * triggered the (lsbits<left) case above.
  93918. */
  93919. FLAC__ASSERT(bw->bits);
  93920. FLAC__ASSERT(left < FLAC__BITS_PER_WORD);
  93921. bw->accum <<= left;
  93922. bw->accum |= uval >> (bw->bits = lsbits - left);
  93923. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  93924. bw->accum = uval;
  93925. }
  93926. #if 1
  93927. }
  93928. #endif
  93929. vals++;
  93930. nvals--;
  93931. }
  93932. return true;
  93933. }
  93934. #if 0 /* UNUSED */
  93935. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter)
  93936. {
  93937. unsigned total_bits, msbs, uval;
  93938. unsigned k;
  93939. FLAC__ASSERT(0 != bw);
  93940. FLAC__ASSERT(0 != bw->buffer);
  93941. FLAC__ASSERT(parameter > 0);
  93942. /* fold signed to unsigned */
  93943. if(val < 0)
  93944. uval = (unsigned)(((-(++val)) << 1) + 1);
  93945. else
  93946. uval = (unsigned)(val << 1);
  93947. k = FLAC__bitmath_ilog2(parameter);
  93948. if(parameter == 1u<<k) {
  93949. unsigned pattern;
  93950. FLAC__ASSERT(k <= 30);
  93951. msbs = uval >> k;
  93952. total_bits = 1 + k + msbs;
  93953. pattern = 1 << k; /* the unary end bit */
  93954. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  93955. if(total_bits <= 32) {
  93956. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  93957. return false;
  93958. }
  93959. else {
  93960. /* write the unary MSBs */
  93961. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  93962. return false;
  93963. /* write the unary end bit and binary LSBs */
  93964. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  93965. return false;
  93966. }
  93967. }
  93968. else {
  93969. unsigned q, r, d;
  93970. d = (1 << (k+1)) - parameter;
  93971. q = uval / parameter;
  93972. r = uval - (q * parameter);
  93973. /* write the unary MSBs */
  93974. if(!FLAC__bitwriter_write_zeroes(bw, q))
  93975. return false;
  93976. /* write the unary end bit */
  93977. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  93978. return false;
  93979. /* write the binary LSBs */
  93980. if(r >= d) {
  93981. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  93982. return false;
  93983. }
  93984. else {
  93985. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  93986. return false;
  93987. }
  93988. }
  93989. return true;
  93990. }
  93991. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned uval, unsigned parameter)
  93992. {
  93993. unsigned total_bits, msbs;
  93994. unsigned k;
  93995. FLAC__ASSERT(0 != bw);
  93996. FLAC__ASSERT(0 != bw->buffer);
  93997. FLAC__ASSERT(parameter > 0);
  93998. k = FLAC__bitmath_ilog2(parameter);
  93999. if(parameter == 1u<<k) {
  94000. unsigned pattern;
  94001. FLAC__ASSERT(k <= 30);
  94002. msbs = uval >> k;
  94003. total_bits = 1 + k + msbs;
  94004. pattern = 1 << k; /* the unary end bit */
  94005. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  94006. if(total_bits <= 32) {
  94007. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  94008. return false;
  94009. }
  94010. else {
  94011. /* write the unary MSBs */
  94012. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  94013. return false;
  94014. /* write the unary end bit and binary LSBs */
  94015. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  94016. return false;
  94017. }
  94018. }
  94019. else {
  94020. unsigned q, r, d;
  94021. d = (1 << (k+1)) - parameter;
  94022. q = uval / parameter;
  94023. r = uval - (q * parameter);
  94024. /* write the unary MSBs */
  94025. if(!FLAC__bitwriter_write_zeroes(bw, q))
  94026. return false;
  94027. /* write the unary end bit */
  94028. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  94029. return false;
  94030. /* write the binary LSBs */
  94031. if(r >= d) {
  94032. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  94033. return false;
  94034. }
  94035. else {
  94036. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  94037. return false;
  94038. }
  94039. }
  94040. return true;
  94041. }
  94042. #endif /* UNUSED */
  94043. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val)
  94044. {
  94045. FLAC__bool ok = 1;
  94046. FLAC__ASSERT(0 != bw);
  94047. FLAC__ASSERT(0 != bw->buffer);
  94048. FLAC__ASSERT(!(val & 0x80000000)); /* this version only handles 31 bits */
  94049. if(val < 0x80) {
  94050. return FLAC__bitwriter_write_raw_uint32(bw, val, 8);
  94051. }
  94052. else if(val < 0x800) {
  94053. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (val>>6), 8);
  94054. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  94055. }
  94056. else if(val < 0x10000) {
  94057. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (val>>12), 8);
  94058. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  94059. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  94060. }
  94061. else if(val < 0x200000) {
  94062. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (val>>18), 8);
  94063. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  94064. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  94065. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  94066. }
  94067. else if(val < 0x4000000) {
  94068. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (val>>24), 8);
  94069. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  94070. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  94071. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  94072. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  94073. }
  94074. else {
  94075. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (val>>30), 8);
  94076. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>24)&0x3F), 8);
  94077. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  94078. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  94079. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  94080. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  94081. }
  94082. return ok;
  94083. }
  94084. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val)
  94085. {
  94086. FLAC__bool ok = 1;
  94087. FLAC__ASSERT(0 != bw);
  94088. FLAC__ASSERT(0 != bw->buffer);
  94089. FLAC__ASSERT(!(val & FLAC__U64L(0xFFFFFFF000000000))); /* this version only handles 36 bits */
  94090. if(val < 0x80) {
  94091. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 8);
  94092. }
  94093. else if(val < 0x800) {
  94094. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (FLAC__uint32)(val>>6), 8);
  94095. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  94096. }
  94097. else if(val < 0x10000) {
  94098. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (FLAC__uint32)(val>>12), 8);
  94099. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  94100. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  94101. }
  94102. else if(val < 0x200000) {
  94103. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (FLAC__uint32)(val>>18), 8);
  94104. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  94105. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  94106. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  94107. }
  94108. else if(val < 0x4000000) {
  94109. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (FLAC__uint32)(val>>24), 8);
  94110. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  94111. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  94112. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  94113. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  94114. }
  94115. else if(val < 0x80000000) {
  94116. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (FLAC__uint32)(val>>30), 8);
  94117. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  94118. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  94119. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  94120. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  94121. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  94122. }
  94123. else {
  94124. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFE, 8);
  94125. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>30)&0x3F), 8);
  94126. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  94127. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  94128. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  94129. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  94130. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  94131. }
  94132. return ok;
  94133. }
  94134. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw)
  94135. {
  94136. /* 0-pad to byte boundary */
  94137. if(bw->bits & 7u)
  94138. return FLAC__bitwriter_write_zeroes(bw, 8 - (bw->bits & 7u));
  94139. else
  94140. return true;
  94141. }
  94142. #endif
  94143. /*** End of inlined file: bitwriter.c ***/
  94144. /*** Start of inlined file: cpu.c ***/
  94145. /*** Start of inlined file: juce_FlacHeader.h ***/
  94146. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  94147. // tasks..
  94148. #define VERSION "1.2.1"
  94149. #define FLAC__NO_DLL 1
  94150. #if JUCE_MSVC
  94151. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  94152. #endif
  94153. #if JUCE_MAC
  94154. #define FLAC__SYS_DARWIN 1
  94155. #endif
  94156. /*** End of inlined file: juce_FlacHeader.h ***/
  94157. #if JUCE_USE_FLAC
  94158. #if HAVE_CONFIG_H
  94159. # include <config.h>
  94160. #endif
  94161. #include <stdlib.h>
  94162. #include <stdio.h>
  94163. #if defined FLAC__CPU_IA32
  94164. # include <signal.h>
  94165. #elif defined FLAC__CPU_PPC
  94166. # if !defined FLAC__NO_ASM
  94167. # if defined FLAC__SYS_DARWIN
  94168. # include <sys/sysctl.h>
  94169. # include <mach/mach.h>
  94170. # include <mach/mach_host.h>
  94171. # include <mach/host_info.h>
  94172. # include <mach/machine.h>
  94173. # ifndef CPU_SUBTYPE_POWERPC_970
  94174. # define CPU_SUBTYPE_POWERPC_970 ((cpu_subtype_t) 100)
  94175. # endif
  94176. # else /* FLAC__SYS_DARWIN */
  94177. # include <signal.h>
  94178. # include <setjmp.h>
  94179. static sigjmp_buf jmpbuf;
  94180. static volatile sig_atomic_t canjump = 0;
  94181. static void sigill_handler (int sig)
  94182. {
  94183. if (!canjump) {
  94184. signal (sig, SIG_DFL);
  94185. raise (sig);
  94186. }
  94187. canjump = 0;
  94188. siglongjmp (jmpbuf, 1);
  94189. }
  94190. # endif /* FLAC__SYS_DARWIN */
  94191. # endif /* FLAC__NO_ASM */
  94192. #endif /* FLAC__CPU_PPC */
  94193. #if defined (__NetBSD__) || defined(__OpenBSD__)
  94194. #include <sys/param.h>
  94195. #include <sys/sysctl.h>
  94196. #include <machine/cpu.h>
  94197. #endif
  94198. #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
  94199. #include <sys/types.h>
  94200. #include <sys/sysctl.h>
  94201. #endif
  94202. #if defined(__APPLE__)
  94203. /* how to get sysctlbyname()? */
  94204. #endif
  94205. /* these are flags in EDX of CPUID AX=00000001 */
  94206. static const unsigned FLAC__CPUINFO_IA32_CPUID_CMOV = 0x00008000;
  94207. static const unsigned FLAC__CPUINFO_IA32_CPUID_MMX = 0x00800000;
  94208. static const unsigned FLAC__CPUINFO_IA32_CPUID_FXSR = 0x01000000;
  94209. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE = 0x02000000;
  94210. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE2 = 0x04000000;
  94211. /* these are flags in ECX of CPUID AX=00000001 */
  94212. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE3 = 0x00000001;
  94213. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSSE3 = 0x00000200;
  94214. /* these are flags in EDX of CPUID AX=80000001 */
  94215. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW = 0x80000000;
  94216. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW = 0x40000000;
  94217. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX = 0x00400000;
  94218. /*
  94219. * Extra stuff needed for detection of OS support for SSE on IA-32
  94220. */
  94221. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM && !defined FLAC__NO_SSE_OS && !defined FLAC__SSE_OS
  94222. # if defined(__linux__)
  94223. /*
  94224. * If the OS doesn't support SSE, we will get here with a SIGILL. We
  94225. * modify the return address to jump over the offending SSE instruction
  94226. * and also the operation following it that indicates the instruction
  94227. * executed successfully. In this way we use no global variables and
  94228. * stay thread-safe.
  94229. *
  94230. * 3 + 3 + 6:
  94231. * 3 bytes for "xorps xmm0,xmm0"
  94232. * 3 bytes for estimate of how long the follwing "inc var" instruction is
  94233. * 6 bytes extra in case our estimate is wrong
  94234. * 12 bytes puts us in the NOP "landing zone"
  94235. */
  94236. # undef USE_OBSOLETE_SIGCONTEXT_FLAVOR /* #define this to use the older signal handler method */
  94237. # ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  94238. static void sigill_handler_sse_os(int signal, struct sigcontext sc)
  94239. {
  94240. (void)signal;
  94241. sc.eip += 3 + 3 + 6;
  94242. }
  94243. # else
  94244. # include <sys/ucontext.h>
  94245. static void sigill_handler_sse_os(int signal, siginfo_t *si, void *uc)
  94246. {
  94247. (void)signal, (void)si;
  94248. ((ucontext_t*)uc)->uc_mcontext.gregs[14/*REG_EIP*/] += 3 + 3 + 6;
  94249. }
  94250. # endif
  94251. # elif defined(_MSC_VER)
  94252. # include <windows.h>
  94253. # undef USE_TRY_CATCH_FLAVOR /* #define this to use the try/catch method for catching illegal opcode exception */
  94254. # ifdef USE_TRY_CATCH_FLAVOR
  94255. # else
  94256. LONG CALLBACK sigill_handler_sse_os(EXCEPTION_POINTERS *ep)
  94257. {
  94258. if(ep->ExceptionRecord->ExceptionCode == EXCEPTION_ILLEGAL_INSTRUCTION) {
  94259. ep->ContextRecord->Eip += 3 + 3 + 6;
  94260. return EXCEPTION_CONTINUE_EXECUTION;
  94261. }
  94262. return EXCEPTION_CONTINUE_SEARCH;
  94263. }
  94264. # endif
  94265. # endif
  94266. #endif
  94267. void FLAC__cpu_info(FLAC__CPUInfo *info)
  94268. {
  94269. /*
  94270. * IA32-specific
  94271. */
  94272. #ifdef FLAC__CPU_IA32
  94273. info->type = FLAC__CPUINFO_TYPE_IA32;
  94274. #if !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  94275. info->use_asm = true; /* we assume a minimum of 80386 with FLAC__CPU_IA32 */
  94276. info->data.ia32.cpuid = FLAC__cpu_have_cpuid_asm_ia32()? true : false;
  94277. info->data.ia32.bswap = info->data.ia32.cpuid; /* CPUID => BSWAP since it came after */
  94278. info->data.ia32.cmov = false;
  94279. info->data.ia32.mmx = false;
  94280. info->data.ia32.fxsr = false;
  94281. info->data.ia32.sse = false;
  94282. info->data.ia32.sse2 = false;
  94283. info->data.ia32.sse3 = false;
  94284. info->data.ia32.ssse3 = false;
  94285. info->data.ia32._3dnow = false;
  94286. info->data.ia32.ext3dnow = false;
  94287. info->data.ia32.extmmx = false;
  94288. if(info->data.ia32.cpuid) {
  94289. /* http://www.sandpile.org/ia32/cpuid.htm */
  94290. FLAC__uint32 flags_edx, flags_ecx;
  94291. FLAC__cpu_info_asm_ia32(&flags_edx, &flags_ecx);
  94292. info->data.ia32.cmov = (flags_edx & FLAC__CPUINFO_IA32_CPUID_CMOV )? true : false;
  94293. info->data.ia32.mmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_MMX )? true : false;
  94294. info->data.ia32.fxsr = (flags_edx & FLAC__CPUINFO_IA32_CPUID_FXSR )? true : false;
  94295. info->data.ia32.sse = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE )? true : false;
  94296. info->data.ia32.sse2 = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE2 )? true : false;
  94297. info->data.ia32.sse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSE3 )? true : false;
  94298. info->data.ia32.ssse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSSE3)? true : false;
  94299. #ifdef FLAC__USE_3DNOW
  94300. flags_edx = FLAC__cpu_info_extended_amd_asm_ia32();
  94301. info->data.ia32._3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW )? true : false;
  94302. info->data.ia32.ext3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW)? true : false;
  94303. info->data.ia32.extmmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX )? true : false;
  94304. #else
  94305. info->data.ia32._3dnow = info->data.ia32.ext3dnow = info->data.ia32.extmmx = false;
  94306. #endif
  94307. #ifdef DEBUG
  94308. fprintf(stderr, "CPU info (IA-32):\n");
  94309. fprintf(stderr, " CPUID ...... %c\n", info->data.ia32.cpuid ? 'Y' : 'n');
  94310. fprintf(stderr, " BSWAP ...... %c\n", info->data.ia32.bswap ? 'Y' : 'n');
  94311. fprintf(stderr, " CMOV ....... %c\n", info->data.ia32.cmov ? 'Y' : 'n');
  94312. fprintf(stderr, " MMX ........ %c\n", info->data.ia32.mmx ? 'Y' : 'n');
  94313. fprintf(stderr, " FXSR ....... %c\n", info->data.ia32.fxsr ? 'Y' : 'n');
  94314. fprintf(stderr, " SSE ........ %c\n", info->data.ia32.sse ? 'Y' : 'n');
  94315. fprintf(stderr, " SSE2 ....... %c\n", info->data.ia32.sse2 ? 'Y' : 'n');
  94316. fprintf(stderr, " SSE3 ....... %c\n", info->data.ia32.sse3 ? 'Y' : 'n');
  94317. fprintf(stderr, " SSSE3 ...... %c\n", info->data.ia32.ssse3 ? 'Y' : 'n');
  94318. fprintf(stderr, " 3DNow! ..... %c\n", info->data.ia32._3dnow ? 'Y' : 'n');
  94319. fprintf(stderr, " 3DNow!-ext . %c\n", info->data.ia32.ext3dnow? 'Y' : 'n');
  94320. fprintf(stderr, " 3DNow!-MMX . %c\n", info->data.ia32.extmmx ? 'Y' : 'n');
  94321. #endif
  94322. /*
  94323. * now have to check for OS support of SSE/SSE2
  94324. */
  94325. if(info->data.ia32.fxsr || info->data.ia32.sse || info->data.ia32.sse2) {
  94326. #if defined FLAC__NO_SSE_OS
  94327. /* assume user knows better than us; turn it off */
  94328. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  94329. #elif defined FLAC__SSE_OS
  94330. /* assume user knows better than us; leave as detected above */
  94331. #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__APPLE__)
  94332. int sse = 0;
  94333. size_t len;
  94334. /* at least one of these must work: */
  94335. len = sizeof(sse); sse = sse || (sysctlbyname("hw.instruction_sse", &sse, &len, NULL, 0) == 0 && sse);
  94336. len = sizeof(sse); sse = sse || (sysctlbyname("hw.optional.sse" , &sse, &len, NULL, 0) == 0 && sse); /* __APPLE__ ? */
  94337. if(!sse)
  94338. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  94339. #elif defined(__NetBSD__) || defined (__OpenBSD__)
  94340. # if __NetBSD_Version__ >= 105250000 || (defined __OpenBSD__)
  94341. int val = 0, mib[2] = { CTL_MACHDEP, CPU_SSE };
  94342. size_t len = sizeof(val);
  94343. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  94344. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  94345. else { /* double-check SSE2 */
  94346. mib[1] = CPU_SSE2;
  94347. len = sizeof(val);
  94348. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  94349. info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  94350. }
  94351. # else
  94352. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  94353. # endif
  94354. #elif defined(__linux__)
  94355. int sse = 0;
  94356. struct sigaction sigill_save;
  94357. #ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  94358. if(0 == sigaction(SIGILL, NULL, &sigill_save) && signal(SIGILL, (void (*)(int))sigill_handler_sse_os) != SIG_ERR)
  94359. #else
  94360. struct sigaction sigill_sse;
  94361. sigill_sse.sa_sigaction = sigill_handler_sse_os;
  94362. __sigemptyset(&sigill_sse.sa_mask);
  94363. 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 */
  94364. if(0 == sigaction(SIGILL, &sigill_sse, &sigill_save))
  94365. #endif
  94366. {
  94367. /* http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html */
  94368. /* see sigill_handler_sse_os() for an explanation of the following: */
  94369. asm volatile (
  94370. "xorl %0,%0\n\t" /* for some reason, still need to do this to clear 'sse' var */
  94371. "xorps %%xmm0,%%xmm0\n\t" /* will cause SIGILL if unsupported by OS */
  94372. "incl %0\n\t" /* SIGILL handler will jump over this */
  94373. /* landing zone */
  94374. "nop\n\t" /* SIGILL jump lands here if "inc" is 9 bytes */
  94375. "nop\n\t"
  94376. "nop\n\t"
  94377. "nop\n\t"
  94378. "nop\n\t"
  94379. "nop\n\t"
  94380. "nop\n\t" /* SIGILL jump lands here if "inc" is 3 bytes (expected) */
  94381. "nop\n\t"
  94382. "nop" /* SIGILL jump lands here if "inc" is 1 byte */
  94383. : "=r"(sse)
  94384. : "r"(sse)
  94385. );
  94386. sigaction(SIGILL, &sigill_save, NULL);
  94387. }
  94388. if(!sse)
  94389. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  94390. #elif defined(_MSC_VER)
  94391. # ifdef USE_TRY_CATCH_FLAVOR
  94392. _try {
  94393. __asm {
  94394. # if _MSC_VER <= 1200
  94395. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  94396. _emit 0x0F
  94397. _emit 0x57
  94398. _emit 0xC0
  94399. # else
  94400. xorps xmm0,xmm0
  94401. # endif
  94402. }
  94403. }
  94404. _except(EXCEPTION_EXECUTE_HANDLER) {
  94405. if (_exception_code() == STATUS_ILLEGAL_INSTRUCTION)
  94406. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  94407. }
  94408. # else
  94409. int sse = 0;
  94410. LPTOP_LEVEL_EXCEPTION_FILTER save = SetUnhandledExceptionFilter(sigill_handler_sse_os);
  94411. /* see GCC version above for explanation */
  94412. /* http://msdn2.microsoft.com/en-us/library/4ks26t93.aspx */
  94413. /* http://www.codeproject.com/cpp/gccasm.asp */
  94414. /* http://www.hick.org/~mmiller/msvc_inline_asm.html */
  94415. __asm {
  94416. # if _MSC_VER <= 1200
  94417. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  94418. _emit 0x0F
  94419. _emit 0x57
  94420. _emit 0xC0
  94421. # else
  94422. xorps xmm0,xmm0
  94423. # endif
  94424. inc sse
  94425. nop
  94426. nop
  94427. nop
  94428. nop
  94429. nop
  94430. nop
  94431. nop
  94432. nop
  94433. nop
  94434. }
  94435. SetUnhandledExceptionFilter(save);
  94436. if(!sse)
  94437. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  94438. # endif
  94439. #else
  94440. /* no way to test, disable to be safe */
  94441. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  94442. #endif
  94443. #ifdef DEBUG
  94444. fprintf(stderr, " SSE OS sup . %c\n", info->data.ia32.sse ? 'Y' : 'n');
  94445. #endif
  94446. }
  94447. }
  94448. #else
  94449. info->use_asm = false;
  94450. #endif
  94451. /*
  94452. * PPC-specific
  94453. */
  94454. #elif defined FLAC__CPU_PPC
  94455. info->type = FLAC__CPUINFO_TYPE_PPC;
  94456. # if !defined FLAC__NO_ASM
  94457. info->use_asm = true;
  94458. # ifdef FLAC__USE_ALTIVEC
  94459. # if defined FLAC__SYS_DARWIN
  94460. {
  94461. int val = 0, mib[2] = { CTL_HW, HW_VECTORUNIT };
  94462. size_t len = sizeof(val);
  94463. info->data.ppc.altivec = !(sysctl(mib, 2, &val, &len, NULL, 0) || !val);
  94464. }
  94465. {
  94466. host_basic_info_data_t hostInfo;
  94467. mach_msg_type_number_t infoCount;
  94468. infoCount = HOST_BASIC_INFO_COUNT;
  94469. host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)&hostInfo, &infoCount);
  94470. info->data.ppc.ppc64 = (hostInfo.cpu_type == CPU_TYPE_POWERPC) && (hostInfo.cpu_subtype == CPU_SUBTYPE_POWERPC_970);
  94471. }
  94472. # else /* FLAC__USE_ALTIVEC && !FLAC__SYS_DARWIN */
  94473. {
  94474. /* no Darwin, do it the brute-force way */
  94475. /* @@@@@@ this is not thread-safe; replace with SSE OS method above or remove */
  94476. info->data.ppc.altivec = 0;
  94477. info->data.ppc.ppc64 = 0;
  94478. signal (SIGILL, sigill_handler);
  94479. canjump = 0;
  94480. if (!sigsetjmp (jmpbuf, 1)) {
  94481. canjump = 1;
  94482. asm volatile (
  94483. "mtspr 256, %0\n\t"
  94484. "vand %%v0, %%v0, %%v0"
  94485. :
  94486. : "r" (-1)
  94487. );
  94488. info->data.ppc.altivec = 1;
  94489. }
  94490. canjump = 0;
  94491. if (!sigsetjmp (jmpbuf, 1)) {
  94492. int x = 0;
  94493. canjump = 1;
  94494. /* PPC64 hardware implements the cntlzd instruction */
  94495. asm volatile ("cntlzd %0, %1" : "=r" (x) : "r" (x) );
  94496. info->data.ppc.ppc64 = 1;
  94497. }
  94498. signal (SIGILL, SIG_DFL); /*@@@@@@ should save and restore old signal */
  94499. }
  94500. # endif
  94501. # else /* !FLAC__USE_ALTIVEC */
  94502. info->data.ppc.altivec = 0;
  94503. info->data.ppc.ppc64 = 0;
  94504. # endif
  94505. # else
  94506. info->use_asm = false;
  94507. # endif
  94508. /*
  94509. * unknown CPI
  94510. */
  94511. #else
  94512. info->type = FLAC__CPUINFO_TYPE_UNKNOWN;
  94513. info->use_asm = false;
  94514. #endif
  94515. }
  94516. #endif
  94517. /*** End of inlined file: cpu.c ***/
  94518. /*** Start of inlined file: crc.c ***/
  94519. /*** Start of inlined file: juce_FlacHeader.h ***/
  94520. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  94521. // tasks..
  94522. #define VERSION "1.2.1"
  94523. #define FLAC__NO_DLL 1
  94524. #if JUCE_MSVC
  94525. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  94526. #endif
  94527. #if JUCE_MAC
  94528. #define FLAC__SYS_DARWIN 1
  94529. #endif
  94530. /*** End of inlined file: juce_FlacHeader.h ***/
  94531. #if JUCE_USE_FLAC
  94532. #if HAVE_CONFIG_H
  94533. # include <config.h>
  94534. #endif
  94535. /* CRC-8, poly = x^8 + x^2 + x^1 + x^0, init = 0 */
  94536. FLAC__byte const FLAC__crc8_table[256] = {
  94537. 0x00, 0x07, 0x0E, 0x09, 0x1C, 0x1B, 0x12, 0x15,
  94538. 0x38, 0x3F, 0x36, 0x31, 0x24, 0x23, 0x2A, 0x2D,
  94539. 0x70, 0x77, 0x7E, 0x79, 0x6C, 0x6B, 0x62, 0x65,
  94540. 0x48, 0x4F, 0x46, 0x41, 0x54, 0x53, 0x5A, 0x5D,
  94541. 0xE0, 0xE7, 0xEE, 0xE9, 0xFC, 0xFB, 0xF2, 0xF5,
  94542. 0xD8, 0xDF, 0xD6, 0xD1, 0xC4, 0xC3, 0xCA, 0xCD,
  94543. 0x90, 0x97, 0x9E, 0x99, 0x8C, 0x8B, 0x82, 0x85,
  94544. 0xA8, 0xAF, 0xA6, 0xA1, 0xB4, 0xB3, 0xBA, 0xBD,
  94545. 0xC7, 0xC0, 0xC9, 0xCE, 0xDB, 0xDC, 0xD5, 0xD2,
  94546. 0xFF, 0xF8, 0xF1, 0xF6, 0xE3, 0xE4, 0xED, 0xEA,
  94547. 0xB7, 0xB0, 0xB9, 0xBE, 0xAB, 0xAC, 0xA5, 0xA2,
  94548. 0x8F, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9D, 0x9A,
  94549. 0x27, 0x20, 0x29, 0x2E, 0x3B, 0x3C, 0x35, 0x32,
  94550. 0x1F, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0D, 0x0A,
  94551. 0x57, 0x50, 0x59, 0x5E, 0x4B, 0x4C, 0x45, 0x42,
  94552. 0x6F, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7D, 0x7A,
  94553. 0x89, 0x8E, 0x87, 0x80, 0x95, 0x92, 0x9B, 0x9C,
  94554. 0xB1, 0xB6, 0xBF, 0xB8, 0xAD, 0xAA, 0xA3, 0xA4,
  94555. 0xF9, 0xFE, 0xF7, 0xF0, 0xE5, 0xE2, 0xEB, 0xEC,
  94556. 0xC1, 0xC6, 0xCF, 0xC8, 0xDD, 0xDA, 0xD3, 0xD4,
  94557. 0x69, 0x6E, 0x67, 0x60, 0x75, 0x72, 0x7B, 0x7C,
  94558. 0x51, 0x56, 0x5F, 0x58, 0x4D, 0x4A, 0x43, 0x44,
  94559. 0x19, 0x1E, 0x17, 0x10, 0x05, 0x02, 0x0B, 0x0C,
  94560. 0x21, 0x26, 0x2F, 0x28, 0x3D, 0x3A, 0x33, 0x34,
  94561. 0x4E, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5C, 0x5B,
  94562. 0x76, 0x71, 0x78, 0x7F, 0x6A, 0x6D, 0x64, 0x63,
  94563. 0x3E, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2C, 0x2B,
  94564. 0x06, 0x01, 0x08, 0x0F, 0x1A, 0x1D, 0x14, 0x13,
  94565. 0xAE, 0xA9, 0xA0, 0xA7, 0xB2, 0xB5, 0xBC, 0xBB,
  94566. 0x96, 0x91, 0x98, 0x9F, 0x8A, 0x8D, 0x84, 0x83,
  94567. 0xDE, 0xD9, 0xD0, 0xD7, 0xC2, 0xC5, 0xCC, 0xCB,
  94568. 0xE6, 0xE1, 0xE8, 0xEF, 0xFA, 0xFD, 0xF4, 0xF3
  94569. };
  94570. /* CRC-16, poly = x^16 + x^15 + x^2 + x^0, init = 0 */
  94571. unsigned FLAC__crc16_table[256] = {
  94572. 0x0000, 0x8005, 0x800f, 0x000a, 0x801b, 0x001e, 0x0014, 0x8011,
  94573. 0x8033, 0x0036, 0x003c, 0x8039, 0x0028, 0x802d, 0x8027, 0x0022,
  94574. 0x8063, 0x0066, 0x006c, 0x8069, 0x0078, 0x807d, 0x8077, 0x0072,
  94575. 0x0050, 0x8055, 0x805f, 0x005a, 0x804b, 0x004e, 0x0044, 0x8041,
  94576. 0x80c3, 0x00c6, 0x00cc, 0x80c9, 0x00d8, 0x80dd, 0x80d7, 0x00d2,
  94577. 0x00f0, 0x80f5, 0x80ff, 0x00fa, 0x80eb, 0x00ee, 0x00e4, 0x80e1,
  94578. 0x00a0, 0x80a5, 0x80af, 0x00aa, 0x80bb, 0x00be, 0x00b4, 0x80b1,
  94579. 0x8093, 0x0096, 0x009c, 0x8099, 0x0088, 0x808d, 0x8087, 0x0082,
  94580. 0x8183, 0x0186, 0x018c, 0x8189, 0x0198, 0x819d, 0x8197, 0x0192,
  94581. 0x01b0, 0x81b5, 0x81bf, 0x01ba, 0x81ab, 0x01ae, 0x01a4, 0x81a1,
  94582. 0x01e0, 0x81e5, 0x81ef, 0x01ea, 0x81fb, 0x01fe, 0x01f4, 0x81f1,
  94583. 0x81d3, 0x01d6, 0x01dc, 0x81d9, 0x01c8, 0x81cd, 0x81c7, 0x01c2,
  94584. 0x0140, 0x8145, 0x814f, 0x014a, 0x815b, 0x015e, 0x0154, 0x8151,
  94585. 0x8173, 0x0176, 0x017c, 0x8179, 0x0168, 0x816d, 0x8167, 0x0162,
  94586. 0x8123, 0x0126, 0x012c, 0x8129, 0x0138, 0x813d, 0x8137, 0x0132,
  94587. 0x0110, 0x8115, 0x811f, 0x011a, 0x810b, 0x010e, 0x0104, 0x8101,
  94588. 0x8303, 0x0306, 0x030c, 0x8309, 0x0318, 0x831d, 0x8317, 0x0312,
  94589. 0x0330, 0x8335, 0x833f, 0x033a, 0x832b, 0x032e, 0x0324, 0x8321,
  94590. 0x0360, 0x8365, 0x836f, 0x036a, 0x837b, 0x037e, 0x0374, 0x8371,
  94591. 0x8353, 0x0356, 0x035c, 0x8359, 0x0348, 0x834d, 0x8347, 0x0342,
  94592. 0x03c0, 0x83c5, 0x83cf, 0x03ca, 0x83db, 0x03de, 0x03d4, 0x83d1,
  94593. 0x83f3, 0x03f6, 0x03fc, 0x83f9, 0x03e8, 0x83ed, 0x83e7, 0x03e2,
  94594. 0x83a3, 0x03a6, 0x03ac, 0x83a9, 0x03b8, 0x83bd, 0x83b7, 0x03b2,
  94595. 0x0390, 0x8395, 0x839f, 0x039a, 0x838b, 0x038e, 0x0384, 0x8381,
  94596. 0x0280, 0x8285, 0x828f, 0x028a, 0x829b, 0x029e, 0x0294, 0x8291,
  94597. 0x82b3, 0x02b6, 0x02bc, 0x82b9, 0x02a8, 0x82ad, 0x82a7, 0x02a2,
  94598. 0x82e3, 0x02e6, 0x02ec, 0x82e9, 0x02f8, 0x82fd, 0x82f7, 0x02f2,
  94599. 0x02d0, 0x82d5, 0x82df, 0x02da, 0x82cb, 0x02ce, 0x02c4, 0x82c1,
  94600. 0x8243, 0x0246, 0x024c, 0x8249, 0x0258, 0x825d, 0x8257, 0x0252,
  94601. 0x0270, 0x8275, 0x827f, 0x027a, 0x826b, 0x026e, 0x0264, 0x8261,
  94602. 0x0220, 0x8225, 0x822f, 0x022a, 0x823b, 0x023e, 0x0234, 0x8231,
  94603. 0x8213, 0x0216, 0x021c, 0x8219, 0x0208, 0x820d, 0x8207, 0x0202
  94604. };
  94605. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc)
  94606. {
  94607. *crc = FLAC__crc8_table[*crc ^ data];
  94608. }
  94609. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc)
  94610. {
  94611. while(len--)
  94612. *crc = FLAC__crc8_table[*crc ^ *data++];
  94613. }
  94614. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len)
  94615. {
  94616. FLAC__uint8 crc = 0;
  94617. while(len--)
  94618. crc = FLAC__crc8_table[crc ^ *data++];
  94619. return crc;
  94620. }
  94621. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len)
  94622. {
  94623. unsigned crc = 0;
  94624. while(len--)
  94625. crc = ((crc<<8) ^ FLAC__crc16_table[(crc>>8) ^ *data++]) & 0xffff;
  94626. return crc;
  94627. }
  94628. #endif
  94629. /*** End of inlined file: crc.c ***/
  94630. /*** Start of inlined file: fixed.c ***/
  94631. /*** Start of inlined file: juce_FlacHeader.h ***/
  94632. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  94633. // tasks..
  94634. #define VERSION "1.2.1"
  94635. #define FLAC__NO_DLL 1
  94636. #if JUCE_MSVC
  94637. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  94638. #endif
  94639. #if JUCE_MAC
  94640. #define FLAC__SYS_DARWIN 1
  94641. #endif
  94642. /*** End of inlined file: juce_FlacHeader.h ***/
  94643. #if JUCE_USE_FLAC
  94644. #if HAVE_CONFIG_H
  94645. # include <config.h>
  94646. #endif
  94647. #include <math.h>
  94648. #include <string.h>
  94649. /*** Start of inlined file: fixed.h ***/
  94650. #ifndef FLAC__PRIVATE__FIXED_H
  94651. #define FLAC__PRIVATE__FIXED_H
  94652. #ifdef HAVE_CONFIG_H
  94653. #include <config.h>
  94654. #endif
  94655. /*** Start of inlined file: float.h ***/
  94656. #ifndef FLAC__PRIVATE__FLOAT_H
  94657. #define FLAC__PRIVATE__FLOAT_H
  94658. #ifdef HAVE_CONFIG_H
  94659. #include <config.h>
  94660. #endif
  94661. /*
  94662. * These typedefs make it easier to ensure that integer versions of
  94663. * the library really only contain integer operations. All the code
  94664. * in libFLAC should use FLAC__float and FLAC__double in place of
  94665. * float and double, and be protected by checks of the macro
  94666. * FLAC__INTEGER_ONLY_LIBRARY.
  94667. *
  94668. * FLAC__real is the basic floating point type used in LPC analysis.
  94669. */
  94670. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  94671. typedef double FLAC__double;
  94672. typedef float FLAC__float;
  94673. /*
  94674. * WATCHOUT: changing FLAC__real will change the signatures of many
  94675. * functions that have assembly language equivalents and break them.
  94676. */
  94677. typedef float FLAC__real;
  94678. #else
  94679. /*
  94680. * The convention for FLAC__fixedpoint is to use the upper 16 bits
  94681. * for the integer part and lower 16 bits for the fractional part.
  94682. */
  94683. typedef FLAC__int32 FLAC__fixedpoint;
  94684. extern const FLAC__fixedpoint FLAC__FP_ZERO;
  94685. extern const FLAC__fixedpoint FLAC__FP_ONE_HALF;
  94686. extern const FLAC__fixedpoint FLAC__FP_ONE;
  94687. extern const FLAC__fixedpoint FLAC__FP_LN2;
  94688. extern const FLAC__fixedpoint FLAC__FP_E;
  94689. #define FLAC__fixedpoint_trunc(x) ((x)>>16)
  94690. #define FLAC__fixedpoint_mul(x, y) ( (FLAC__fixedpoint) ( ((FLAC__int64)(x)*(FLAC__int64)(y)) >> 16 ) )
  94691. #define FLAC__fixedpoint_div(x, y) ( (FLAC__fixedpoint) ( ( ((FLAC__int64)(x)<<32) / (FLAC__int64)(y) ) >> 16 ) )
  94692. /*
  94693. * FLAC__fixedpoint_log2()
  94694. * --------------------------------------------------------------------
  94695. * Returns the base-2 logarithm of the fixed-point number 'x' using an
  94696. * algorithm by Knuth for x >= 1.0
  94697. *
  94698. * 'fracbits' is the number of fractional bits of 'x'. 'fracbits' must
  94699. * be < 32 and evenly divisible by 4 (0 is OK but not very precise).
  94700. *
  94701. * 'precision' roughly limits the number of iterations that are done;
  94702. * use (unsigned)(-1) for maximum precision.
  94703. *
  94704. * If 'x' is less than one -- that is, x < (1<<fracbits) -- then this
  94705. * function will punt and return 0.
  94706. *
  94707. * The return value will also have 'fracbits' fractional bits.
  94708. */
  94709. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision);
  94710. #endif
  94711. #endif
  94712. /*** End of inlined file: float.h ***/
  94713. /*** Start of inlined file: format.h ***/
  94714. #ifndef FLAC__PRIVATE__FORMAT_H
  94715. #define FLAC__PRIVATE__FORMAT_H
  94716. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order);
  94717. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize);
  94718. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order);
  94719. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  94720. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  94721. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order);
  94722. #endif
  94723. /*** End of inlined file: format.h ***/
  94724. /*
  94725. * FLAC__fixed_compute_best_predictor()
  94726. * --------------------------------------------------------------------
  94727. * Compute the best fixed predictor and the expected bits-per-sample
  94728. * of the residual signal for each order. The _wide() version uses
  94729. * 64-bit integers which is statistically necessary when bits-per-
  94730. * sample + log2(blocksize) > 30
  94731. *
  94732. * IN data[0,data_len-1]
  94733. * IN data_len
  94734. * OUT residual_bits_per_sample[0,FLAC__MAX_FIXED_ORDER]
  94735. */
  94736. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  94737. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  94738. # ifndef FLAC__NO_ASM
  94739. # ifdef FLAC__CPU_IA32
  94740. # ifdef FLAC__HAS_NASM
  94741. 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]);
  94742. # endif
  94743. # endif
  94744. # endif
  94745. 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]);
  94746. #else
  94747. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  94748. 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]);
  94749. #endif
  94750. /*
  94751. * FLAC__fixed_compute_residual()
  94752. * --------------------------------------------------------------------
  94753. * Compute the residual signal obtained from sutracting the predicted
  94754. * signal from the original.
  94755. *
  94756. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  94757. * IN data_len length of original signal
  94758. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  94759. * OUT residual[0,data_len-1] residual signal
  94760. */
  94761. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[]);
  94762. /*
  94763. * FLAC__fixed_restore_signal()
  94764. * --------------------------------------------------------------------
  94765. * Restore the original signal by summing the residual and the
  94766. * predictor.
  94767. *
  94768. * IN residual[0,data_len-1] residual signal
  94769. * IN data_len length of original signal
  94770. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  94771. * *** IMPORTANT: the caller must pass in the historical samples:
  94772. * IN data[-order,-1] previously-reconstructed historical samples
  94773. * OUT data[0,data_len-1] original signal
  94774. */
  94775. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[]);
  94776. #endif
  94777. /*** End of inlined file: fixed.h ***/
  94778. #ifndef M_LN2
  94779. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  94780. #define M_LN2 0.69314718055994530942
  94781. #endif
  94782. #ifdef min
  94783. #undef min
  94784. #endif
  94785. #define min(x,y) ((x) < (y)? (x) : (y))
  94786. #ifdef local_abs
  94787. #undef local_abs
  94788. #endif
  94789. #define local_abs(x) ((unsigned)((x)<0? -(x) : (x)))
  94790. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  94791. /* rbps stands for residual bits per sample
  94792. *
  94793. * (ln(2) * err)
  94794. * rbps = log (-----------)
  94795. * 2 ( n )
  94796. */
  94797. static FLAC__fixedpoint local__compute_rbps_integerized(FLAC__uint32 err, FLAC__uint32 n)
  94798. {
  94799. FLAC__uint32 rbps;
  94800. unsigned bits; /* the number of bits required to represent a number */
  94801. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  94802. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  94803. FLAC__ASSERT(err > 0);
  94804. FLAC__ASSERT(n > 0);
  94805. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  94806. if(err <= n)
  94807. return 0;
  94808. /*
  94809. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  94810. * These allow us later to know we won't lose too much precision in the
  94811. * fixed-point division (err<<fracbits)/n.
  94812. */
  94813. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2(err)+1);
  94814. err <<= fracbits;
  94815. err /= n;
  94816. /* err now holds err/n with fracbits fractional bits */
  94817. /*
  94818. * Whittle err down to 16 bits max. 16 significant bits is enough for
  94819. * our purposes.
  94820. */
  94821. FLAC__ASSERT(err > 0);
  94822. bits = FLAC__bitmath_ilog2(err)+1;
  94823. if(bits > 16) {
  94824. err >>= (bits-16);
  94825. fracbits -= (bits-16);
  94826. }
  94827. rbps = (FLAC__uint32)err;
  94828. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  94829. rbps *= FLAC__FP_LN2;
  94830. fracbits += 16;
  94831. FLAC__ASSERT(fracbits >= 0);
  94832. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  94833. {
  94834. const int f = fracbits & 3;
  94835. if(f) {
  94836. rbps >>= f;
  94837. fracbits -= f;
  94838. }
  94839. }
  94840. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  94841. if(rbps == 0)
  94842. return 0;
  94843. /*
  94844. * The return value must have 16 fractional bits. Since the whole part
  94845. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  94846. * must be >= -3, these assertion allows us to be able to shift rbps
  94847. * left if necessary to get 16 fracbits without losing any bits of the
  94848. * whole part of rbps.
  94849. *
  94850. * There is a slight chance due to accumulated error that the whole part
  94851. * will require 6 bits, so we use 6 in the assertion. Really though as
  94852. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  94853. */
  94854. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  94855. FLAC__ASSERT(fracbits >= -3);
  94856. /* now shift the decimal point into place */
  94857. if(fracbits < 16)
  94858. return rbps << (16-fracbits);
  94859. else if(fracbits > 16)
  94860. return rbps >> (fracbits-16);
  94861. else
  94862. return rbps;
  94863. }
  94864. static FLAC__fixedpoint local__compute_rbps_wide_integerized(FLAC__uint64 err, FLAC__uint32 n)
  94865. {
  94866. FLAC__uint32 rbps;
  94867. unsigned bits; /* the number of bits required to represent a number */
  94868. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  94869. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  94870. FLAC__ASSERT(err > 0);
  94871. FLAC__ASSERT(n > 0);
  94872. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  94873. if(err <= n)
  94874. return 0;
  94875. /*
  94876. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  94877. * These allow us later to know we won't lose too much precision in the
  94878. * fixed-point division (err<<fracbits)/n.
  94879. */
  94880. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2_wide(err)+1);
  94881. err <<= fracbits;
  94882. err /= n;
  94883. /* err now holds err/n with fracbits fractional bits */
  94884. /*
  94885. * Whittle err down to 16 bits max. 16 significant bits is enough for
  94886. * our purposes.
  94887. */
  94888. FLAC__ASSERT(err > 0);
  94889. bits = FLAC__bitmath_ilog2_wide(err)+1;
  94890. if(bits > 16) {
  94891. err >>= (bits-16);
  94892. fracbits -= (bits-16);
  94893. }
  94894. rbps = (FLAC__uint32)err;
  94895. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  94896. rbps *= FLAC__FP_LN2;
  94897. fracbits += 16;
  94898. FLAC__ASSERT(fracbits >= 0);
  94899. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  94900. {
  94901. const int f = fracbits & 3;
  94902. if(f) {
  94903. rbps >>= f;
  94904. fracbits -= f;
  94905. }
  94906. }
  94907. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  94908. if(rbps == 0)
  94909. return 0;
  94910. /*
  94911. * The return value must have 16 fractional bits. Since the whole part
  94912. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  94913. * must be >= -3, these assertion allows us to be able to shift rbps
  94914. * left if necessary to get 16 fracbits without losing any bits of the
  94915. * whole part of rbps.
  94916. *
  94917. * There is a slight chance due to accumulated error that the whole part
  94918. * will require 6 bits, so we use 6 in the assertion. Really though as
  94919. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  94920. */
  94921. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  94922. FLAC__ASSERT(fracbits >= -3);
  94923. /* now shift the decimal point into place */
  94924. if(fracbits < 16)
  94925. return rbps << (16-fracbits);
  94926. else if(fracbits > 16)
  94927. return rbps >> (fracbits-16);
  94928. else
  94929. return rbps;
  94930. }
  94931. #endif
  94932. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  94933. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  94934. #else
  94935. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  94936. #endif
  94937. {
  94938. FLAC__int32 last_error_0 = data[-1];
  94939. FLAC__int32 last_error_1 = data[-1] - data[-2];
  94940. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  94941. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  94942. FLAC__int32 error, save;
  94943. FLAC__uint32 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  94944. unsigned i, order;
  94945. for(i = 0; i < data_len; i++) {
  94946. error = data[i] ; total_error_0 += local_abs(error); save = error;
  94947. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  94948. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  94949. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  94950. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  94951. }
  94952. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  94953. order = 0;
  94954. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  94955. order = 1;
  94956. else if(total_error_2 < min(total_error_3, total_error_4))
  94957. order = 2;
  94958. else if(total_error_3 < total_error_4)
  94959. order = 3;
  94960. else
  94961. order = 4;
  94962. /* Estimate the expected number of bits per residual signal sample. */
  94963. /* 'total_error*' is linearly related to the variance of the residual */
  94964. /* signal, so we use it directly to compute E(|x|) */
  94965. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  94966. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  94967. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  94968. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  94969. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  94970. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  94971. 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);
  94972. 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);
  94973. 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);
  94974. 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);
  94975. 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);
  94976. #else
  94977. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_integerized(total_error_0, data_len) : 0;
  94978. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_integerized(total_error_1, data_len) : 0;
  94979. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_integerized(total_error_2, data_len) : 0;
  94980. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_integerized(total_error_3, data_len) : 0;
  94981. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_integerized(total_error_4, data_len) : 0;
  94982. #endif
  94983. return order;
  94984. }
  94985. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  94986. 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])
  94987. #else
  94988. 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])
  94989. #endif
  94990. {
  94991. FLAC__int32 last_error_0 = data[-1];
  94992. FLAC__int32 last_error_1 = data[-1] - data[-2];
  94993. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  94994. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  94995. FLAC__int32 error, save;
  94996. /* total_error_* are 64-bits to avoid overflow when encoding
  94997. * erratic signals when the bits-per-sample and blocksize are
  94998. * large.
  94999. */
  95000. FLAC__uint64 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  95001. unsigned i, order;
  95002. for(i = 0; i < data_len; i++) {
  95003. error = data[i] ; total_error_0 += local_abs(error); save = error;
  95004. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  95005. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  95006. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  95007. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  95008. }
  95009. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  95010. order = 0;
  95011. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  95012. order = 1;
  95013. else if(total_error_2 < min(total_error_3, total_error_4))
  95014. order = 2;
  95015. else if(total_error_3 < total_error_4)
  95016. order = 3;
  95017. else
  95018. order = 4;
  95019. /* Estimate the expected number of bits per residual signal sample. */
  95020. /* 'total_error*' is linearly related to the variance of the residual */
  95021. /* signal, so we use it directly to compute E(|x|) */
  95022. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  95023. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  95024. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  95025. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  95026. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  95027. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95028. #if defined _MSC_VER || defined __MINGW32__
  95029. /* with MSVC you have to spoon feed it the casting */
  95030. 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);
  95031. 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);
  95032. 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);
  95033. 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);
  95034. 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);
  95035. #else
  95036. 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);
  95037. 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);
  95038. 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);
  95039. 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);
  95040. 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);
  95041. #endif
  95042. #else
  95043. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_wide_integerized(total_error_0, data_len) : 0;
  95044. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_wide_integerized(total_error_1, data_len) : 0;
  95045. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_wide_integerized(total_error_2, data_len) : 0;
  95046. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_wide_integerized(total_error_3, data_len) : 0;
  95047. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_wide_integerized(total_error_4, data_len) : 0;
  95048. #endif
  95049. return order;
  95050. }
  95051. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[])
  95052. {
  95053. const int idata_len = (int)data_len;
  95054. int i;
  95055. switch(order) {
  95056. case 0:
  95057. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  95058. memcpy(residual, data, sizeof(residual[0])*data_len);
  95059. break;
  95060. case 1:
  95061. for(i = 0; i < idata_len; i++)
  95062. residual[i] = data[i] - data[i-1];
  95063. break;
  95064. case 2:
  95065. for(i = 0; i < idata_len; i++)
  95066. #if 1 /* OPT: may be faster with some compilers on some systems */
  95067. residual[i] = data[i] - (data[i-1] << 1) + data[i-2];
  95068. #else
  95069. residual[i] = data[i] - 2*data[i-1] + data[i-2];
  95070. #endif
  95071. break;
  95072. case 3:
  95073. for(i = 0; i < idata_len; i++)
  95074. #if 1 /* OPT: may be faster with some compilers on some systems */
  95075. residual[i] = data[i] - (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) - data[i-3];
  95076. #else
  95077. residual[i] = data[i] - 3*data[i-1] + 3*data[i-2] - data[i-3];
  95078. #endif
  95079. break;
  95080. case 4:
  95081. for(i = 0; i < idata_len; i++)
  95082. #if 1 /* OPT: may be faster with some compilers on some systems */
  95083. residual[i] = data[i] - ((data[i-1]+data[i-3])<<2) + ((data[i-2]<<2) + (data[i-2]<<1)) + data[i-4];
  95084. #else
  95085. residual[i] = data[i] - 4*data[i-1] + 6*data[i-2] - 4*data[i-3] + data[i-4];
  95086. #endif
  95087. break;
  95088. default:
  95089. FLAC__ASSERT(0);
  95090. }
  95091. }
  95092. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[])
  95093. {
  95094. int i, idata_len = (int)data_len;
  95095. switch(order) {
  95096. case 0:
  95097. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  95098. memcpy(data, residual, sizeof(residual[0])*data_len);
  95099. break;
  95100. case 1:
  95101. for(i = 0; i < idata_len; i++)
  95102. data[i] = residual[i] + data[i-1];
  95103. break;
  95104. case 2:
  95105. for(i = 0; i < idata_len; i++)
  95106. #if 1 /* OPT: may be faster with some compilers on some systems */
  95107. data[i] = residual[i] + (data[i-1]<<1) - data[i-2];
  95108. #else
  95109. data[i] = residual[i] + 2*data[i-1] - data[i-2];
  95110. #endif
  95111. break;
  95112. case 3:
  95113. for(i = 0; i < idata_len; i++)
  95114. #if 1 /* OPT: may be faster with some compilers on some systems */
  95115. data[i] = residual[i] + (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) + data[i-3];
  95116. #else
  95117. data[i] = residual[i] + 3*data[i-1] - 3*data[i-2] + data[i-3];
  95118. #endif
  95119. break;
  95120. case 4:
  95121. for(i = 0; i < idata_len; i++)
  95122. #if 1 /* OPT: may be faster with some compilers on some systems */
  95123. data[i] = residual[i] + ((data[i-1]+data[i-3])<<2) - ((data[i-2]<<2) + (data[i-2]<<1)) - data[i-4];
  95124. #else
  95125. data[i] = residual[i] + 4*data[i-1] - 6*data[i-2] + 4*data[i-3] - data[i-4];
  95126. #endif
  95127. break;
  95128. default:
  95129. FLAC__ASSERT(0);
  95130. }
  95131. }
  95132. #endif
  95133. /*** End of inlined file: fixed.c ***/
  95134. /*** Start of inlined file: float.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. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  95152. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  95153. #ifdef _MSC_VER
  95154. #define FLAC__U64L(x) x
  95155. #else
  95156. #define FLAC__U64L(x) x##LLU
  95157. #endif
  95158. const FLAC__fixedpoint FLAC__FP_ZERO = 0;
  95159. const FLAC__fixedpoint FLAC__FP_ONE_HALF = 0x00008000;
  95160. const FLAC__fixedpoint FLAC__FP_ONE = 0x00010000;
  95161. const FLAC__fixedpoint FLAC__FP_LN2 = 45426;
  95162. const FLAC__fixedpoint FLAC__FP_E = 178145;
  95163. /* Lookup tables for Knuth's logarithm algorithm */
  95164. #define LOG2_LOOKUP_PRECISION 16
  95165. static const FLAC__uint32 log2_lookup[][LOG2_LOOKUP_PRECISION] = {
  95166. {
  95167. /*
  95168. * 0 fraction bits
  95169. */
  95170. /* undefined */ 0x00000000,
  95171. /* lg(2/1) = */ 0x00000001,
  95172. /* lg(4/3) = */ 0x00000000,
  95173. /* lg(8/7) = */ 0x00000000,
  95174. /* lg(16/15) = */ 0x00000000,
  95175. /* lg(32/31) = */ 0x00000000,
  95176. /* lg(64/63) = */ 0x00000000,
  95177. /* lg(128/127) = */ 0x00000000,
  95178. /* lg(256/255) = */ 0x00000000,
  95179. /* lg(512/511) = */ 0x00000000,
  95180. /* lg(1024/1023) = */ 0x00000000,
  95181. /* lg(2048/2047) = */ 0x00000000,
  95182. /* lg(4096/4095) = */ 0x00000000,
  95183. /* lg(8192/8191) = */ 0x00000000,
  95184. /* lg(16384/16383) = */ 0x00000000,
  95185. /* lg(32768/32767) = */ 0x00000000
  95186. },
  95187. {
  95188. /*
  95189. * 4 fraction bits
  95190. */
  95191. /* undefined */ 0x00000000,
  95192. /* lg(2/1) = */ 0x00000010,
  95193. /* lg(4/3) = */ 0x00000007,
  95194. /* lg(8/7) = */ 0x00000003,
  95195. /* lg(16/15) = */ 0x00000001,
  95196. /* lg(32/31) = */ 0x00000001,
  95197. /* lg(64/63) = */ 0x00000000,
  95198. /* lg(128/127) = */ 0x00000000,
  95199. /* lg(256/255) = */ 0x00000000,
  95200. /* lg(512/511) = */ 0x00000000,
  95201. /* lg(1024/1023) = */ 0x00000000,
  95202. /* lg(2048/2047) = */ 0x00000000,
  95203. /* lg(4096/4095) = */ 0x00000000,
  95204. /* lg(8192/8191) = */ 0x00000000,
  95205. /* lg(16384/16383) = */ 0x00000000,
  95206. /* lg(32768/32767) = */ 0x00000000
  95207. },
  95208. {
  95209. /*
  95210. * 8 fraction bits
  95211. */
  95212. /* undefined */ 0x00000000,
  95213. /* lg(2/1) = */ 0x00000100,
  95214. /* lg(4/3) = */ 0x0000006a,
  95215. /* lg(8/7) = */ 0x00000031,
  95216. /* lg(16/15) = */ 0x00000018,
  95217. /* lg(32/31) = */ 0x0000000c,
  95218. /* lg(64/63) = */ 0x00000006,
  95219. /* lg(128/127) = */ 0x00000003,
  95220. /* lg(256/255) = */ 0x00000001,
  95221. /* lg(512/511) = */ 0x00000001,
  95222. /* lg(1024/1023) = */ 0x00000000,
  95223. /* lg(2048/2047) = */ 0x00000000,
  95224. /* lg(4096/4095) = */ 0x00000000,
  95225. /* lg(8192/8191) = */ 0x00000000,
  95226. /* lg(16384/16383) = */ 0x00000000,
  95227. /* lg(32768/32767) = */ 0x00000000
  95228. },
  95229. {
  95230. /*
  95231. * 12 fraction bits
  95232. */
  95233. /* undefined */ 0x00000000,
  95234. /* lg(2/1) = */ 0x00001000,
  95235. /* lg(4/3) = */ 0x000006a4,
  95236. /* lg(8/7) = */ 0x00000315,
  95237. /* lg(16/15) = */ 0x0000017d,
  95238. /* lg(32/31) = */ 0x000000bc,
  95239. /* lg(64/63) = */ 0x0000005d,
  95240. /* lg(128/127) = */ 0x0000002e,
  95241. /* lg(256/255) = */ 0x00000017,
  95242. /* lg(512/511) = */ 0x0000000c,
  95243. /* lg(1024/1023) = */ 0x00000006,
  95244. /* lg(2048/2047) = */ 0x00000003,
  95245. /* lg(4096/4095) = */ 0x00000001,
  95246. /* lg(8192/8191) = */ 0x00000001,
  95247. /* lg(16384/16383) = */ 0x00000000,
  95248. /* lg(32768/32767) = */ 0x00000000
  95249. },
  95250. {
  95251. /*
  95252. * 16 fraction bits
  95253. */
  95254. /* undefined */ 0x00000000,
  95255. /* lg(2/1) = */ 0x00010000,
  95256. /* lg(4/3) = */ 0x00006a40,
  95257. /* lg(8/7) = */ 0x00003151,
  95258. /* lg(16/15) = */ 0x000017d6,
  95259. /* lg(32/31) = */ 0x00000bba,
  95260. /* lg(64/63) = */ 0x000005d1,
  95261. /* lg(128/127) = */ 0x000002e6,
  95262. /* lg(256/255) = */ 0x00000172,
  95263. /* lg(512/511) = */ 0x000000b9,
  95264. /* lg(1024/1023) = */ 0x0000005c,
  95265. /* lg(2048/2047) = */ 0x0000002e,
  95266. /* lg(4096/4095) = */ 0x00000017,
  95267. /* lg(8192/8191) = */ 0x0000000c,
  95268. /* lg(16384/16383) = */ 0x00000006,
  95269. /* lg(32768/32767) = */ 0x00000003
  95270. },
  95271. {
  95272. /*
  95273. * 20 fraction bits
  95274. */
  95275. /* undefined */ 0x00000000,
  95276. /* lg(2/1) = */ 0x00100000,
  95277. /* lg(4/3) = */ 0x0006a3fe,
  95278. /* lg(8/7) = */ 0x00031513,
  95279. /* lg(16/15) = */ 0x00017d60,
  95280. /* lg(32/31) = */ 0x0000bb9d,
  95281. /* lg(64/63) = */ 0x00005d10,
  95282. /* lg(128/127) = */ 0x00002e59,
  95283. /* lg(256/255) = */ 0x00001721,
  95284. /* lg(512/511) = */ 0x00000b8e,
  95285. /* lg(1024/1023) = */ 0x000005c6,
  95286. /* lg(2048/2047) = */ 0x000002e3,
  95287. /* lg(4096/4095) = */ 0x00000171,
  95288. /* lg(8192/8191) = */ 0x000000b9,
  95289. /* lg(16384/16383) = */ 0x0000005c,
  95290. /* lg(32768/32767) = */ 0x0000002e
  95291. },
  95292. {
  95293. /*
  95294. * 24 fraction bits
  95295. */
  95296. /* undefined */ 0x00000000,
  95297. /* lg(2/1) = */ 0x01000000,
  95298. /* lg(4/3) = */ 0x006a3fe6,
  95299. /* lg(8/7) = */ 0x00315130,
  95300. /* lg(16/15) = */ 0x0017d605,
  95301. /* lg(32/31) = */ 0x000bb9ca,
  95302. /* lg(64/63) = */ 0x0005d0fc,
  95303. /* lg(128/127) = */ 0x0002e58f,
  95304. /* lg(256/255) = */ 0x0001720e,
  95305. /* lg(512/511) = */ 0x0000b8d8,
  95306. /* lg(1024/1023) = */ 0x00005c61,
  95307. /* lg(2048/2047) = */ 0x00002e2d,
  95308. /* lg(4096/4095) = */ 0x00001716,
  95309. /* lg(8192/8191) = */ 0x00000b8b,
  95310. /* lg(16384/16383) = */ 0x000005c5,
  95311. /* lg(32768/32767) = */ 0x000002e3
  95312. },
  95313. {
  95314. /*
  95315. * 28 fraction bits
  95316. */
  95317. /* undefined */ 0x00000000,
  95318. /* lg(2/1) = */ 0x10000000,
  95319. /* lg(4/3) = */ 0x06a3fe5c,
  95320. /* lg(8/7) = */ 0x03151301,
  95321. /* lg(16/15) = */ 0x017d6049,
  95322. /* lg(32/31) = */ 0x00bb9ca6,
  95323. /* lg(64/63) = */ 0x005d0fba,
  95324. /* lg(128/127) = */ 0x002e58f7,
  95325. /* lg(256/255) = */ 0x001720da,
  95326. /* lg(512/511) = */ 0x000b8d87,
  95327. /* lg(1024/1023) = */ 0x0005c60b,
  95328. /* lg(2048/2047) = */ 0x0002e2d7,
  95329. /* lg(4096/4095) = */ 0x00017160,
  95330. /* lg(8192/8191) = */ 0x0000b8ad,
  95331. /* lg(16384/16383) = */ 0x00005c56,
  95332. /* lg(32768/32767) = */ 0x00002e2b
  95333. }
  95334. };
  95335. #if 0
  95336. static const FLAC__uint64 log2_lookup_wide[] = {
  95337. {
  95338. /*
  95339. * 32 fraction bits
  95340. */
  95341. /* undefined */ 0x00000000,
  95342. /* lg(2/1) = */ FLAC__U64L(0x100000000),
  95343. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c6),
  95344. /* lg(8/7) = */ FLAC__U64L(0x31513015),
  95345. /* lg(16/15) = */ FLAC__U64L(0x17d60497),
  95346. /* lg(32/31) = */ FLAC__U64L(0x0bb9ca65),
  95347. /* lg(64/63) = */ FLAC__U64L(0x05d0fba2),
  95348. /* lg(128/127) = */ FLAC__U64L(0x02e58f74),
  95349. /* lg(256/255) = */ FLAC__U64L(0x01720d9c),
  95350. /* lg(512/511) = */ FLAC__U64L(0x00b8d875),
  95351. /* lg(1024/1023) = */ FLAC__U64L(0x005c60aa),
  95352. /* lg(2048/2047) = */ FLAC__U64L(0x002e2d72),
  95353. /* lg(4096/4095) = */ FLAC__U64L(0x00171600),
  95354. /* lg(8192/8191) = */ FLAC__U64L(0x000b8ad2),
  95355. /* lg(16384/16383) = */ FLAC__U64L(0x0005c55d),
  95356. /* lg(32768/32767) = */ FLAC__U64L(0x0002e2ac)
  95357. },
  95358. {
  95359. /*
  95360. * 48 fraction bits
  95361. */
  95362. /* undefined */ 0x00000000,
  95363. /* lg(2/1) = */ FLAC__U64L(0x1000000000000),
  95364. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c60429),
  95365. /* lg(8/7) = */ FLAC__U64L(0x315130157f7a),
  95366. /* lg(16/15) = */ FLAC__U64L(0x17d60496cfbb),
  95367. /* lg(32/31) = */ FLAC__U64L(0xbb9ca64ecac),
  95368. /* lg(64/63) = */ FLAC__U64L(0x5d0fba187cd),
  95369. /* lg(128/127) = */ FLAC__U64L(0x2e58f7441ee),
  95370. /* lg(256/255) = */ FLAC__U64L(0x1720d9c06a8),
  95371. /* lg(512/511) = */ FLAC__U64L(0xb8d8752173),
  95372. /* lg(1024/1023) = */ FLAC__U64L(0x5c60aa252e),
  95373. /* lg(2048/2047) = */ FLAC__U64L(0x2e2d71b0d8),
  95374. /* lg(4096/4095) = */ FLAC__U64L(0x1716001719),
  95375. /* lg(8192/8191) = */ FLAC__U64L(0xb8ad1de1b),
  95376. /* lg(16384/16383) = */ FLAC__U64L(0x5c55d640d),
  95377. /* lg(32768/32767) = */ FLAC__U64L(0x2e2abcf52)
  95378. }
  95379. };
  95380. #endif
  95381. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision)
  95382. {
  95383. const FLAC__uint32 ONE = (1u << fracbits);
  95384. const FLAC__uint32 *table = log2_lookup[fracbits >> 2];
  95385. FLAC__ASSERT(fracbits < 32);
  95386. FLAC__ASSERT((fracbits & 0x3) == 0);
  95387. if(x < ONE)
  95388. return 0;
  95389. if(precision > LOG2_LOOKUP_PRECISION)
  95390. precision = LOG2_LOOKUP_PRECISION;
  95391. /* Knuth's algorithm for computing logarithms, optimized for base-2 with lookup tables */
  95392. {
  95393. FLAC__uint32 y = 0;
  95394. FLAC__uint32 z = x >> 1, k = 1;
  95395. while (x > ONE && k < precision) {
  95396. if (x - z >= ONE) {
  95397. x -= z;
  95398. z = x >> k;
  95399. y += table[k];
  95400. }
  95401. else {
  95402. z >>= 1;
  95403. k++;
  95404. }
  95405. }
  95406. return y;
  95407. }
  95408. }
  95409. #endif /* defined FLAC__INTEGER_ONLY_LIBRARY */
  95410. #endif
  95411. /*** End of inlined file: float.c ***/
  95412. /*** Start of inlined file: format.c ***/
  95413. /*** Start of inlined file: juce_FlacHeader.h ***/
  95414. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95415. // tasks..
  95416. #define VERSION "1.2.1"
  95417. #define FLAC__NO_DLL 1
  95418. #if JUCE_MSVC
  95419. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95420. #endif
  95421. #if JUCE_MAC
  95422. #define FLAC__SYS_DARWIN 1
  95423. #endif
  95424. /*** End of inlined file: juce_FlacHeader.h ***/
  95425. #if JUCE_USE_FLAC
  95426. #if HAVE_CONFIG_H
  95427. # include <config.h>
  95428. #endif
  95429. #include <stdio.h>
  95430. #include <stdlib.h> /* for qsort() */
  95431. #include <string.h> /* for memset() */
  95432. #ifndef FLaC__INLINE
  95433. #define FLaC__INLINE
  95434. #endif
  95435. #ifdef min
  95436. #undef min
  95437. #endif
  95438. #define min(a,b) ((a)<(b)?(a):(b))
  95439. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  95440. #ifdef _MSC_VER
  95441. #define FLAC__U64L(x) x
  95442. #else
  95443. #define FLAC__U64L(x) x##LLU
  95444. #endif
  95445. /* VERSION should come from configure */
  95446. FLAC_API const char *FLAC__VERSION_STRING = VERSION
  95447. ;
  95448. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINW32__
  95449. /* yet one more hack because of MSVC6: */
  95450. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC 1.2.1 20070917";
  95451. #else
  95452. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC " VERSION " 20070917";
  95453. #endif
  95454. FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4] = { 'f','L','a','C' };
  95455. FLAC_API const unsigned FLAC__STREAM_SYNC = 0x664C6143;
  95456. FLAC_API const unsigned FLAC__STREAM_SYNC_LEN = 32; /* bits */
  95457. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN = 16; /* bits */
  95458. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN = 16; /* bits */
  95459. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN = 24; /* bits */
  95460. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN = 24; /* bits */
  95461. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN = 20; /* bits */
  95462. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN = 3; /* bits */
  95463. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN = 5; /* bits */
  95464. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN = 36; /* bits */
  95465. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN = 128; /* bits */
  95466. FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN = 32; /* bits */
  95467. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN = 64; /* bits */
  95468. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN = 64; /* bits */
  95469. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN = 16; /* bits */
  95470. FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER = FLAC__U64L(0xffffffffffffffff);
  95471. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN = 32; /* bits */
  95472. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN = 32; /* bits */
  95473. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN = 64; /* bits */
  95474. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN = 8; /* bits */
  95475. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN = 3*8; /* bits */
  95476. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN = 64; /* bits */
  95477. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN = 8; /* bits */
  95478. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN = 12*8; /* bits */
  95479. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN = 1; /* bit */
  95480. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN = 1; /* bit */
  95481. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN = 6+13*8; /* bits */
  95482. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN = 8; /* bits */
  95483. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN = 128*8; /* bits */
  95484. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN = 64; /* bits */
  95485. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN = 1; /* bit */
  95486. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN = 7+258*8; /* bits */
  95487. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN = 8; /* bits */
  95488. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN = 32; /* bits */
  95489. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN = 32; /* bits */
  95490. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN = 32; /* bits */
  95491. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN = 32; /* bits */
  95492. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN = 32; /* bits */
  95493. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN = 32; /* bits */
  95494. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN = 32; /* bits */
  95495. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN = 32; /* bits */
  95496. FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN = 1; /* bits */
  95497. FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN = 7; /* bits */
  95498. FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN = 24; /* bits */
  95499. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC = 0x3ffe;
  95500. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN = 14; /* bits */
  95501. FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN = 1; /* bits */
  95502. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN = 1; /* bits */
  95503. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN = 4; /* bits */
  95504. FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN = 4; /* bits */
  95505. FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN = 4; /* bits */
  95506. FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN = 3; /* bits */
  95507. FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN = 1; /* bits */
  95508. FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN = 8; /* bits */
  95509. FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN = 16; /* bits */
  95510. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN = 2; /* bits */
  95511. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN = 4; /* bits */
  95512. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN = 4; /* bits */
  95513. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN = 5; /* bits */
  95514. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN = 5; /* bits */
  95515. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER = 15; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  95516. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER = 31; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  95517. FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[] = {
  95518. "PARTITIONED_RICE",
  95519. "PARTITIONED_RICE2"
  95520. };
  95521. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN = 4; /* bits */
  95522. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN = 5; /* bits */
  95523. FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN = 1; /* bits */
  95524. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN = 6; /* bits */
  95525. FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN = 1; /* bits */
  95526. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK = 0x00;
  95527. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK = 0x02;
  95528. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK = 0x10;
  95529. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK = 0x40;
  95530. FLAC_API const char * const FLAC__SubframeTypeString[] = {
  95531. "CONSTANT",
  95532. "VERBATIM",
  95533. "FIXED",
  95534. "LPC"
  95535. };
  95536. FLAC_API const char * const FLAC__ChannelAssignmentString[] = {
  95537. "INDEPENDENT",
  95538. "LEFT_SIDE",
  95539. "RIGHT_SIDE",
  95540. "MID_SIDE"
  95541. };
  95542. FLAC_API const char * const FLAC__FrameNumberTypeString[] = {
  95543. "FRAME_NUMBER_TYPE_FRAME_NUMBER",
  95544. "FRAME_NUMBER_TYPE_SAMPLE_NUMBER"
  95545. };
  95546. FLAC_API const char * const FLAC__MetadataTypeString[] = {
  95547. "STREAMINFO",
  95548. "PADDING",
  95549. "APPLICATION",
  95550. "SEEKTABLE",
  95551. "VORBIS_COMMENT",
  95552. "CUESHEET",
  95553. "PICTURE"
  95554. };
  95555. FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[] = {
  95556. "Other",
  95557. "32x32 pixels 'file icon' (PNG only)",
  95558. "Other file icon",
  95559. "Cover (front)",
  95560. "Cover (back)",
  95561. "Leaflet page",
  95562. "Media (e.g. label side of CD)",
  95563. "Lead artist/lead performer/soloist",
  95564. "Artist/performer",
  95565. "Conductor",
  95566. "Band/Orchestra",
  95567. "Composer",
  95568. "Lyricist/text writer",
  95569. "Recording Location",
  95570. "During recording",
  95571. "During performance",
  95572. "Movie/video screen capture",
  95573. "A bright coloured fish",
  95574. "Illustration",
  95575. "Band/artist logotype",
  95576. "Publisher/Studio logotype"
  95577. };
  95578. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate)
  95579. {
  95580. if(sample_rate == 0 || sample_rate > FLAC__MAX_SAMPLE_RATE) {
  95581. return false;
  95582. }
  95583. else
  95584. return true;
  95585. }
  95586. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate)
  95587. {
  95588. if(
  95589. !FLAC__format_sample_rate_is_valid(sample_rate) ||
  95590. (
  95591. sample_rate >= (1u << 16) &&
  95592. !(sample_rate % 1000 == 0 || sample_rate % 10 == 0)
  95593. )
  95594. ) {
  95595. return false;
  95596. }
  95597. else
  95598. return true;
  95599. }
  95600. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  95601. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table)
  95602. {
  95603. unsigned i;
  95604. FLAC__uint64 prev_sample_number = 0;
  95605. FLAC__bool got_prev = false;
  95606. FLAC__ASSERT(0 != seek_table);
  95607. for(i = 0; i < seek_table->num_points; i++) {
  95608. if(got_prev) {
  95609. if(
  95610. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  95611. seek_table->points[i].sample_number <= prev_sample_number
  95612. )
  95613. return false;
  95614. }
  95615. prev_sample_number = seek_table->points[i].sample_number;
  95616. got_prev = true;
  95617. }
  95618. return true;
  95619. }
  95620. /* used as the sort predicate for qsort() */
  95621. static int seekpoint_compare_(const FLAC__StreamMetadata_SeekPoint *l, const FLAC__StreamMetadata_SeekPoint *r)
  95622. {
  95623. /* we don't just 'return l->sample_number - r->sample_number' since the result (FLAC__int64) might overflow an 'int' */
  95624. if(l->sample_number == r->sample_number)
  95625. return 0;
  95626. else if(l->sample_number < r->sample_number)
  95627. return -1;
  95628. else
  95629. return 1;
  95630. }
  95631. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  95632. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table)
  95633. {
  95634. unsigned i, j;
  95635. FLAC__bool first;
  95636. FLAC__ASSERT(0 != seek_table);
  95637. /* sort the seekpoints */
  95638. qsort(seek_table->points, seek_table->num_points, sizeof(FLAC__StreamMetadata_SeekPoint), (int (*)(const void *, const void *))seekpoint_compare_);
  95639. /* uniquify the seekpoints */
  95640. first = true;
  95641. for(i = j = 0; i < seek_table->num_points; i++) {
  95642. if(seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER) {
  95643. if(!first) {
  95644. if(seek_table->points[i].sample_number == seek_table->points[j-1].sample_number)
  95645. continue;
  95646. }
  95647. }
  95648. first = false;
  95649. seek_table->points[j++] = seek_table->points[i];
  95650. }
  95651. for(i = j; i < seek_table->num_points; i++) {
  95652. seek_table->points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  95653. seek_table->points[i].stream_offset = 0;
  95654. seek_table->points[i].frame_samples = 0;
  95655. }
  95656. return j;
  95657. }
  95658. /*
  95659. * also disallows non-shortest-form encodings, c.f.
  95660. * http://www.unicode.org/versions/corrigendum1.html
  95661. * and a more clear explanation at the end of this section:
  95662. * http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  95663. */
  95664. static FLaC__INLINE unsigned utf8len_(const FLAC__byte *utf8)
  95665. {
  95666. FLAC__ASSERT(0 != utf8);
  95667. if ((utf8[0] & 0x80) == 0) {
  95668. return 1;
  95669. }
  95670. else if ((utf8[0] & 0xE0) == 0xC0 && (utf8[1] & 0xC0) == 0x80) {
  95671. if ((utf8[0] & 0xFE) == 0xC0) /* overlong sequence check */
  95672. return 0;
  95673. return 2;
  95674. }
  95675. else if ((utf8[0] & 0xF0) == 0xE0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80) {
  95676. if (utf8[0] == 0xE0 && (utf8[1] & 0xE0) == 0x80) /* overlong sequence check */
  95677. return 0;
  95678. /* illegal surrogates check (U+D800...U+DFFF and U+FFFE...U+FFFF) */
  95679. if (utf8[0] == 0xED && (utf8[1] & 0xE0) == 0xA0) /* D800-DFFF */
  95680. return 0;
  95681. if (utf8[0] == 0xEF && utf8[1] == 0xBF && (utf8[2] & 0xFE) == 0xBE) /* FFFE-FFFF */
  95682. return 0;
  95683. return 3;
  95684. }
  95685. else if ((utf8[0] & 0xF8) == 0xF0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80) {
  95686. if (utf8[0] == 0xF0 && (utf8[1] & 0xF0) == 0x80) /* overlong sequence check */
  95687. return 0;
  95688. return 4;
  95689. }
  95690. else if ((utf8[0] & 0xFC) == 0xF8 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80 && (utf8[4] & 0xC0) == 0x80) {
  95691. if (utf8[0] == 0xF8 && (utf8[1] & 0xF8) == 0x80) /* overlong sequence check */
  95692. return 0;
  95693. return 5;
  95694. }
  95695. 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) {
  95696. if (utf8[0] == 0xFC && (utf8[1] & 0xFC) == 0x80) /* overlong sequence check */
  95697. return 0;
  95698. return 6;
  95699. }
  95700. else {
  95701. return 0;
  95702. }
  95703. }
  95704. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name)
  95705. {
  95706. char c;
  95707. for(c = *name; c; c = *(++name))
  95708. if(c < 0x20 || c == 0x3d || c > 0x7d)
  95709. return false;
  95710. return true;
  95711. }
  95712. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length)
  95713. {
  95714. if(length == (unsigned)(-1)) {
  95715. while(*value) {
  95716. unsigned n = utf8len_(value);
  95717. if(n == 0)
  95718. return false;
  95719. value += n;
  95720. }
  95721. }
  95722. else {
  95723. const FLAC__byte *end = value + length;
  95724. while(value < end) {
  95725. unsigned n = utf8len_(value);
  95726. if(n == 0)
  95727. return false;
  95728. value += n;
  95729. }
  95730. if(value != end)
  95731. return false;
  95732. }
  95733. return true;
  95734. }
  95735. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length)
  95736. {
  95737. const FLAC__byte *s, *end;
  95738. for(s = entry, end = s + length; s < end && *s != '='; s++) {
  95739. if(*s < 0x20 || *s > 0x7D)
  95740. return false;
  95741. }
  95742. if(s == end)
  95743. return false;
  95744. s++; /* skip '=' */
  95745. while(s < end) {
  95746. unsigned n = utf8len_(s);
  95747. if(n == 0)
  95748. return false;
  95749. s += n;
  95750. }
  95751. if(s != end)
  95752. return false;
  95753. return true;
  95754. }
  95755. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  95756. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation)
  95757. {
  95758. unsigned i, j;
  95759. if(check_cd_da_subset) {
  95760. if(cue_sheet->lead_in < 2 * 44100) {
  95761. if(violation) *violation = "CD-DA cue sheet must have a lead-in length of at least 2 seconds";
  95762. return false;
  95763. }
  95764. if(cue_sheet->lead_in % 588 != 0) {
  95765. if(violation) *violation = "CD-DA cue sheet lead-in length must be evenly divisible by 588 samples";
  95766. return false;
  95767. }
  95768. }
  95769. if(cue_sheet->num_tracks == 0) {
  95770. if(violation) *violation = "cue sheet must have at least one track (the lead-out)";
  95771. return false;
  95772. }
  95773. if(check_cd_da_subset && cue_sheet->tracks[cue_sheet->num_tracks-1].number != 170) {
  95774. if(violation) *violation = "CD-DA cue sheet must have a lead-out track number 170 (0xAA)";
  95775. return false;
  95776. }
  95777. for(i = 0; i < cue_sheet->num_tracks; i++) {
  95778. if(cue_sheet->tracks[i].number == 0) {
  95779. if(violation) *violation = "cue sheet may not have a track number 0";
  95780. return false;
  95781. }
  95782. if(check_cd_da_subset) {
  95783. if(!((cue_sheet->tracks[i].number >= 1 && cue_sheet->tracks[i].number <= 99) || cue_sheet->tracks[i].number == 170)) {
  95784. if(violation) *violation = "CD-DA cue sheet track number must be 1-99 or 170";
  95785. return false;
  95786. }
  95787. }
  95788. if(check_cd_da_subset && cue_sheet->tracks[i].offset % 588 != 0) {
  95789. if(violation) {
  95790. if(i == cue_sheet->num_tracks-1) /* the lead-out track... */
  95791. *violation = "CD-DA cue sheet lead-out offset must be evenly divisible by 588 samples";
  95792. else
  95793. *violation = "CD-DA cue sheet track offset must be evenly divisible by 588 samples";
  95794. }
  95795. return false;
  95796. }
  95797. if(i < cue_sheet->num_tracks - 1) {
  95798. if(cue_sheet->tracks[i].num_indices == 0) {
  95799. if(violation) *violation = "cue sheet track must have at least one index point";
  95800. return false;
  95801. }
  95802. if(cue_sheet->tracks[i].indices[0].number > 1) {
  95803. if(violation) *violation = "cue sheet track's first index number must be 0 or 1";
  95804. return false;
  95805. }
  95806. }
  95807. for(j = 0; j < cue_sheet->tracks[i].num_indices; j++) {
  95808. if(check_cd_da_subset && cue_sheet->tracks[i].indices[j].offset % 588 != 0) {
  95809. if(violation) *violation = "CD-DA cue sheet track index offset must be evenly divisible by 588 samples";
  95810. return false;
  95811. }
  95812. if(j > 0) {
  95813. if(cue_sheet->tracks[i].indices[j].number != cue_sheet->tracks[i].indices[j-1].number + 1) {
  95814. if(violation) *violation = "cue sheet track index numbers must increase by 1";
  95815. return false;
  95816. }
  95817. }
  95818. }
  95819. }
  95820. return true;
  95821. }
  95822. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  95823. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation)
  95824. {
  95825. char *p;
  95826. FLAC__byte *b;
  95827. for(p = picture->mime_type; *p; p++) {
  95828. if(*p < 0x20 || *p > 0x7e) {
  95829. if(violation) *violation = "MIME type string must contain only printable ASCII characters (0x20-0x7e)";
  95830. return false;
  95831. }
  95832. }
  95833. for(b = picture->description; *b; ) {
  95834. unsigned n = utf8len_(b);
  95835. if(n == 0) {
  95836. if(violation) *violation = "description string must be valid UTF-8";
  95837. return false;
  95838. }
  95839. b += n;
  95840. }
  95841. return true;
  95842. }
  95843. /*
  95844. * These routines are private to libFLAC
  95845. */
  95846. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order)
  95847. {
  95848. return
  95849. FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(
  95850. FLAC__format_get_max_rice_partition_order_from_blocksize(blocksize),
  95851. blocksize,
  95852. predictor_order
  95853. );
  95854. }
  95855. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize)
  95856. {
  95857. unsigned max_rice_partition_order = 0;
  95858. while(!(blocksize & 1)) {
  95859. max_rice_partition_order++;
  95860. blocksize >>= 1;
  95861. }
  95862. return min(FLAC__MAX_RICE_PARTITION_ORDER, max_rice_partition_order);
  95863. }
  95864. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order)
  95865. {
  95866. unsigned max_rice_partition_order = limit;
  95867. while(max_rice_partition_order > 0 && (blocksize >> max_rice_partition_order) <= predictor_order)
  95868. max_rice_partition_order--;
  95869. FLAC__ASSERT(
  95870. (max_rice_partition_order == 0 && blocksize >= predictor_order) ||
  95871. (max_rice_partition_order > 0 && blocksize >> max_rice_partition_order > predictor_order)
  95872. );
  95873. return max_rice_partition_order;
  95874. }
  95875. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  95876. {
  95877. FLAC__ASSERT(0 != object);
  95878. object->parameters = 0;
  95879. object->raw_bits = 0;
  95880. object->capacity_by_order = 0;
  95881. }
  95882. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  95883. {
  95884. FLAC__ASSERT(0 != object);
  95885. if(0 != object->parameters)
  95886. free(object->parameters);
  95887. if(0 != object->raw_bits)
  95888. free(object->raw_bits);
  95889. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(object);
  95890. }
  95891. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order)
  95892. {
  95893. FLAC__ASSERT(0 != object);
  95894. FLAC__ASSERT(object->capacity_by_order > 0 || (0 == object->parameters && 0 == object->raw_bits));
  95895. if(object->capacity_by_order < max_partition_order) {
  95896. if(0 == (object->parameters = (unsigned*)realloc(object->parameters, sizeof(unsigned)*(1 << max_partition_order))))
  95897. return false;
  95898. if(0 == (object->raw_bits = (unsigned*)realloc(object->raw_bits, sizeof(unsigned)*(1 << max_partition_order))))
  95899. return false;
  95900. memset(object->raw_bits, 0, sizeof(unsigned)*(1 << max_partition_order));
  95901. object->capacity_by_order = max_partition_order;
  95902. }
  95903. return true;
  95904. }
  95905. #endif
  95906. /*** End of inlined file: format.c ***/
  95907. /*** Start of inlined file: lpc_flac.c ***/
  95908. /*** Start of inlined file: juce_FlacHeader.h ***/
  95909. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95910. // tasks..
  95911. #define VERSION "1.2.1"
  95912. #define FLAC__NO_DLL 1
  95913. #if JUCE_MSVC
  95914. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95915. #endif
  95916. #if JUCE_MAC
  95917. #define FLAC__SYS_DARWIN 1
  95918. #endif
  95919. /*** End of inlined file: juce_FlacHeader.h ***/
  95920. #if JUCE_USE_FLAC
  95921. #if HAVE_CONFIG_H
  95922. # include <config.h>
  95923. #endif
  95924. #include <math.h>
  95925. /*** Start of inlined file: lpc.h ***/
  95926. #ifndef FLAC__PRIVATE__LPC_H
  95927. #define FLAC__PRIVATE__LPC_H
  95928. #ifdef HAVE_CONFIG_H
  95929. #include <config.h>
  95930. #endif
  95931. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95932. /*
  95933. * FLAC__lpc_window_data()
  95934. * --------------------------------------------------------------------
  95935. * Applies the given window to the data.
  95936. * OPT: asm implementation
  95937. *
  95938. * IN in[0,data_len-1]
  95939. * IN window[0,data_len-1]
  95940. * OUT out[0,lag-1]
  95941. * IN data_len
  95942. */
  95943. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len);
  95944. /*
  95945. * FLAC__lpc_compute_autocorrelation()
  95946. * --------------------------------------------------------------------
  95947. * Compute the autocorrelation for lags between 0 and lag-1.
  95948. * Assumes data[] outside of [0,data_len-1] == 0.
  95949. * Asserts that lag > 0.
  95950. *
  95951. * IN data[0,data_len-1]
  95952. * IN data_len
  95953. * IN 0 < lag <= data_len
  95954. * OUT autoc[0,lag-1]
  95955. */
  95956. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  95957. #ifndef FLAC__NO_ASM
  95958. # ifdef FLAC__CPU_IA32
  95959. # ifdef FLAC__HAS_NASM
  95960. void FLAC__lpc_compute_autocorrelation_asm_ia32(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  95961. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  95962. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  95963. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  95964. void FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  95965. # endif
  95966. # endif
  95967. #endif
  95968. /*
  95969. * FLAC__lpc_compute_lp_coefficients()
  95970. * --------------------------------------------------------------------
  95971. * Computes LP coefficients for orders 1..max_order.
  95972. * Do not call if autoc[0] == 0.0. This means the signal is zero
  95973. * and there is no point in calculating a predictor.
  95974. *
  95975. * IN autoc[0,max_order] autocorrelation values
  95976. * IN 0 < max_order <= FLAC__MAX_LPC_ORDER max LP order to compute
  95977. * OUT lp_coeff[0,max_order-1][0,max_order-1] LP coefficients for each order
  95978. * *** IMPORTANT:
  95979. * *** lp_coeff[0,max_order-1][max_order,FLAC__MAX_LPC_ORDER-1] are untouched
  95980. * OUT error[0,max_order-1] error for each order (more
  95981. * specifically, the variance of
  95982. * the error signal times # of
  95983. * samples in the signal)
  95984. *
  95985. * Example: if max_order is 9, the LP coefficients for order 9 will be
  95986. * in lp_coeff[8][0,8], the LP coefficients for order 8 will be
  95987. * in lp_coeff[7][0,7], etc.
  95988. */
  95989. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[]);
  95990. /*
  95991. * FLAC__lpc_quantize_coefficients()
  95992. * --------------------------------------------------------------------
  95993. * Quantizes the LP coefficients. NOTE: precision + bits_per_sample
  95994. * must be less than 32 (sizeof(FLAC__int32)*8).
  95995. *
  95996. * IN lp_coeff[0,order-1] LP coefficients
  95997. * IN order LP order
  95998. * IN FLAC__MIN_QLP_COEFF_PRECISION < precision
  95999. * desired precision (in bits, including sign
  96000. * bit) of largest coefficient
  96001. * OUT qlp_coeff[0,order-1] quantized coefficients
  96002. * OUT shift # of bits to shift right to get approximated
  96003. * LP coefficients. NOTE: could be negative.
  96004. * RETURN 0 => quantization OK
  96005. * 1 => coefficients require too much shifting for *shift to
  96006. * fit in the LPC subframe header. 'shift' is unset.
  96007. * 2 => coefficients are all zero, which is bad. 'shift' is
  96008. * unset.
  96009. */
  96010. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift);
  96011. /*
  96012. * FLAC__lpc_compute_residual_from_qlp_coefficients()
  96013. * --------------------------------------------------------------------
  96014. * Compute the residual signal obtained from sutracting the predicted
  96015. * signal from the original.
  96016. *
  96017. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  96018. * IN data_len length of original signal
  96019. * IN qlp_coeff[0,order-1] quantized LP coefficients
  96020. * IN order > 0 LP order
  96021. * IN lp_quantization quantization of LP coefficients in bits
  96022. * OUT residual[0,data_len-1] residual signal
  96023. */
  96024. 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[]);
  96025. 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[]);
  96026. #ifndef FLAC__NO_ASM
  96027. # ifdef FLAC__CPU_IA32
  96028. # ifdef FLAC__HAS_NASM
  96029. 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[]);
  96030. 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[]);
  96031. # endif
  96032. # endif
  96033. #endif
  96034. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  96035. /*
  96036. * FLAC__lpc_restore_signal()
  96037. * --------------------------------------------------------------------
  96038. * Restore the original signal by summing the residual and the
  96039. * predictor.
  96040. *
  96041. * IN residual[0,data_len-1] residual signal
  96042. * IN data_len length of original signal
  96043. * IN qlp_coeff[0,order-1] quantized LP coefficients
  96044. * IN order > 0 LP order
  96045. * IN lp_quantization quantization of LP coefficients in bits
  96046. * *** IMPORTANT: the caller must pass in the historical samples:
  96047. * IN data[-order,-1] previously-reconstructed historical samples
  96048. * OUT data[0,data_len-1] original signal
  96049. */
  96050. 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[]);
  96051. 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[]);
  96052. #ifndef FLAC__NO_ASM
  96053. # ifdef FLAC__CPU_IA32
  96054. # ifdef FLAC__HAS_NASM
  96055. 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[]);
  96056. 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[]);
  96057. # endif /* FLAC__HAS_NASM */
  96058. # elif defined FLAC__CPU_PPC
  96059. 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[]);
  96060. 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[]);
  96061. # endif/* FLAC__CPU_IA32 || FLAC__CPU_PPC */
  96062. #endif /* FLAC__NO_ASM */
  96063. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96064. /*
  96065. * FLAC__lpc_compute_expected_bits_per_residual_sample()
  96066. * --------------------------------------------------------------------
  96067. * Compute the expected number of bits per residual signal sample
  96068. * based on the LP error (which is related to the residual variance).
  96069. *
  96070. * IN lpc_error >= 0.0 error returned from calculating LP coefficients
  96071. * IN total_samples > 0 # of samples in residual signal
  96072. * RETURN expected bits per sample
  96073. */
  96074. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples);
  96075. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale);
  96076. /*
  96077. * FLAC__lpc_compute_best_order()
  96078. * --------------------------------------------------------------------
  96079. * Compute the best order from the array of signal errors returned
  96080. * during coefficient computation.
  96081. *
  96082. * IN lpc_error[0,max_order-1] >= 0.0 error returned from calculating LP coefficients
  96083. * IN max_order > 0 max LP order
  96084. * IN total_samples > 0 # of samples in residual signal
  96085. * IN overhead_bits_per_order # of bits overhead for each increased LP order
  96086. * (includes warmup sample size and quantized LP coefficient)
  96087. * RETURN [1,max_order] best order
  96088. */
  96089. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order);
  96090. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  96091. #endif
  96092. /*** End of inlined file: lpc.h ***/
  96093. #if defined DEBUG || defined FLAC__OVERFLOW_DETECT || defined FLAC__OVERFLOW_DETECT_VERBOSE
  96094. #include <stdio.h>
  96095. #endif
  96096. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96097. #ifndef M_LN2
  96098. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  96099. #define M_LN2 0.69314718055994530942
  96100. #endif
  96101. /* OPT: #undef'ing this may improve the speed on some architectures */
  96102. #define FLAC__LPC_UNROLLED_FILTER_LOOPS
  96103. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len)
  96104. {
  96105. unsigned i;
  96106. for(i = 0; i < data_len; i++)
  96107. out[i] = in[i] * window[i];
  96108. }
  96109. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[])
  96110. {
  96111. /* a readable, but slower, version */
  96112. #if 0
  96113. FLAC__real d;
  96114. unsigned i;
  96115. FLAC__ASSERT(lag > 0);
  96116. FLAC__ASSERT(lag <= data_len);
  96117. /*
  96118. * Technically we should subtract the mean first like so:
  96119. * for(i = 0; i < data_len; i++)
  96120. * data[i] -= mean;
  96121. * but it appears not to make enough of a difference to matter, and
  96122. * most signals are already closely centered around zero
  96123. */
  96124. while(lag--) {
  96125. for(i = lag, d = 0.0; i < data_len; i++)
  96126. d += data[i] * data[i - lag];
  96127. autoc[lag] = d;
  96128. }
  96129. #endif
  96130. /*
  96131. * this version tends to run faster because of better data locality
  96132. * ('data_len' is usually much larger than 'lag')
  96133. */
  96134. FLAC__real d;
  96135. unsigned sample, coeff;
  96136. const unsigned limit = data_len - lag;
  96137. FLAC__ASSERT(lag > 0);
  96138. FLAC__ASSERT(lag <= data_len);
  96139. for(coeff = 0; coeff < lag; coeff++)
  96140. autoc[coeff] = 0.0;
  96141. for(sample = 0; sample <= limit; sample++) {
  96142. d = data[sample];
  96143. for(coeff = 0; coeff < lag; coeff++)
  96144. autoc[coeff] += d * data[sample+coeff];
  96145. }
  96146. for(; sample < data_len; sample++) {
  96147. d = data[sample];
  96148. for(coeff = 0; coeff < data_len - sample; coeff++)
  96149. autoc[coeff] += d * data[sample+coeff];
  96150. }
  96151. }
  96152. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[])
  96153. {
  96154. unsigned i, j;
  96155. FLAC__double r, err, ref[FLAC__MAX_LPC_ORDER], lpc[FLAC__MAX_LPC_ORDER];
  96156. FLAC__ASSERT(0 != max_order);
  96157. FLAC__ASSERT(0 < *max_order);
  96158. FLAC__ASSERT(*max_order <= FLAC__MAX_LPC_ORDER);
  96159. FLAC__ASSERT(autoc[0] != 0.0);
  96160. err = autoc[0];
  96161. for(i = 0; i < *max_order; i++) {
  96162. /* Sum up this iteration's reflection coefficient. */
  96163. r = -autoc[i+1];
  96164. for(j = 0; j < i; j++)
  96165. r -= lpc[j] * autoc[i-j];
  96166. ref[i] = (r/=err);
  96167. /* Update LPC coefficients and total error. */
  96168. lpc[i]=r;
  96169. for(j = 0; j < (i>>1); j++) {
  96170. FLAC__double tmp = lpc[j];
  96171. lpc[j] += r * lpc[i-1-j];
  96172. lpc[i-1-j] += r * tmp;
  96173. }
  96174. if(i & 1)
  96175. lpc[j] += lpc[j] * r;
  96176. err *= (1.0 - r * r);
  96177. /* save this order */
  96178. for(j = 0; j <= i; j++)
  96179. lp_coeff[i][j] = (FLAC__real)(-lpc[j]); /* negate FIR filter coeff to get predictor coeff */
  96180. error[i] = err;
  96181. /* see SF bug #1601812 http://sourceforge.net/tracker/index.php?func=detail&aid=1601812&group_id=13478&atid=113478 */
  96182. if(err == 0.0) {
  96183. *max_order = i+1;
  96184. return;
  96185. }
  96186. }
  96187. }
  96188. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift)
  96189. {
  96190. unsigned i;
  96191. FLAC__double cmax;
  96192. FLAC__int32 qmax, qmin;
  96193. FLAC__ASSERT(precision > 0);
  96194. FLAC__ASSERT(precision >= FLAC__MIN_QLP_COEFF_PRECISION);
  96195. /* drop one bit for the sign; from here on out we consider only |lp_coeff[i]| */
  96196. precision--;
  96197. qmax = 1 << precision;
  96198. qmin = -qmax;
  96199. qmax--;
  96200. /* calc cmax = max( |lp_coeff[i]| ) */
  96201. cmax = 0.0;
  96202. for(i = 0; i < order; i++) {
  96203. const FLAC__double d = fabs(lp_coeff[i]);
  96204. if(d > cmax)
  96205. cmax = d;
  96206. }
  96207. if(cmax <= 0.0) {
  96208. /* => coefficients are all 0, which means our constant-detect didn't work */
  96209. return 2;
  96210. }
  96211. else {
  96212. const int max_shiftlimit = (1 << (FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN-1)) - 1;
  96213. const int min_shiftlimit = -max_shiftlimit - 1;
  96214. int log2cmax;
  96215. (void)frexp(cmax, &log2cmax);
  96216. log2cmax--;
  96217. *shift = (int)precision - log2cmax - 1;
  96218. if(*shift > max_shiftlimit)
  96219. *shift = max_shiftlimit;
  96220. else if(*shift < min_shiftlimit)
  96221. return 1;
  96222. }
  96223. if(*shift >= 0) {
  96224. FLAC__double error = 0.0;
  96225. FLAC__int32 q;
  96226. for(i = 0; i < order; i++) {
  96227. error += lp_coeff[i] * (1 << *shift);
  96228. #if 1 /* unfortunately lround() is C99 */
  96229. if(error >= 0.0)
  96230. q = (FLAC__int32)(error + 0.5);
  96231. else
  96232. q = (FLAC__int32)(error - 0.5);
  96233. #else
  96234. q = lround(error);
  96235. #endif
  96236. #ifdef FLAC__OVERFLOW_DETECT
  96237. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  96238. 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]);
  96239. else if(q < qmin)
  96240. 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]);
  96241. #endif
  96242. if(q > qmax)
  96243. q = qmax;
  96244. else if(q < qmin)
  96245. q = qmin;
  96246. error -= q;
  96247. qlp_coeff[i] = q;
  96248. }
  96249. }
  96250. /* negative shift is very rare but due to design flaw, negative shift is
  96251. * a NOP in the decoder, so it must be handled specially by scaling down
  96252. * coeffs
  96253. */
  96254. else {
  96255. const int nshift = -(*shift);
  96256. FLAC__double error = 0.0;
  96257. FLAC__int32 q;
  96258. #ifdef DEBUG
  96259. fprintf(stderr,"FLAC__lpc_quantize_coefficients: negative shift=%d order=%u cmax=%f\n", *shift, order, cmax);
  96260. #endif
  96261. for(i = 0; i < order; i++) {
  96262. error += lp_coeff[i] / (1 << nshift);
  96263. #if 1 /* unfortunately lround() is C99 */
  96264. if(error >= 0.0)
  96265. q = (FLAC__int32)(error + 0.5);
  96266. else
  96267. q = (FLAC__int32)(error - 0.5);
  96268. #else
  96269. q = lround(error);
  96270. #endif
  96271. #ifdef FLAC__OVERFLOW_DETECT
  96272. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  96273. 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]);
  96274. else if(q < qmin)
  96275. 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]);
  96276. #endif
  96277. if(q > qmax)
  96278. q = qmax;
  96279. else if(q < qmin)
  96280. q = qmin;
  96281. error -= q;
  96282. qlp_coeff[i] = q;
  96283. }
  96284. *shift = 0;
  96285. }
  96286. return 0;
  96287. }
  96288. 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[])
  96289. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  96290. {
  96291. FLAC__int64 sumo;
  96292. unsigned i, j;
  96293. FLAC__int32 sum;
  96294. const FLAC__int32 *history;
  96295. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  96296. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  96297. for(i=0;i<order;i++)
  96298. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  96299. fprintf(stderr,"\n");
  96300. #endif
  96301. FLAC__ASSERT(order > 0);
  96302. for(i = 0; i < data_len; i++) {
  96303. sumo = 0;
  96304. sum = 0;
  96305. history = data;
  96306. for(j = 0; j < order; j++) {
  96307. sum += qlp_coeff[j] * (*(--history));
  96308. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  96309. #if defined _MSC_VER
  96310. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  96311. 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);
  96312. #else
  96313. if(sumo > 2147483647ll || sumo < -2147483648ll)
  96314. 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);
  96315. #endif
  96316. }
  96317. *(residual++) = *(data++) - (sum >> lp_quantization);
  96318. }
  96319. /* Here's a slower but clearer version:
  96320. for(i = 0; i < data_len; i++) {
  96321. sum = 0;
  96322. for(j = 0; j < order; j++)
  96323. sum += qlp_coeff[j] * data[i-j-1];
  96324. residual[i] = data[i] - (sum >> lp_quantization);
  96325. }
  96326. */
  96327. }
  96328. #else /* fully unrolled version for normal use */
  96329. {
  96330. int i;
  96331. FLAC__int32 sum;
  96332. FLAC__ASSERT(order > 0);
  96333. FLAC__ASSERT(order <= 32);
  96334. /*
  96335. * We do unique versions up to 12th order since that's the subset limit.
  96336. * Also they are roughly ordered to match frequency of occurrence to
  96337. * minimize branching.
  96338. */
  96339. if(order <= 12) {
  96340. if(order > 8) {
  96341. if(order > 10) {
  96342. if(order == 12) {
  96343. for(i = 0; i < (int)data_len; i++) {
  96344. sum = 0;
  96345. sum += qlp_coeff[11] * data[i-12];
  96346. sum += qlp_coeff[10] * data[i-11];
  96347. sum += qlp_coeff[9] * data[i-10];
  96348. sum += qlp_coeff[8] * data[i-9];
  96349. sum += qlp_coeff[7] * data[i-8];
  96350. sum += qlp_coeff[6] * data[i-7];
  96351. sum += qlp_coeff[5] * data[i-6];
  96352. sum += qlp_coeff[4] * data[i-5];
  96353. sum += qlp_coeff[3] * data[i-4];
  96354. sum += qlp_coeff[2] * data[i-3];
  96355. sum += qlp_coeff[1] * data[i-2];
  96356. sum += qlp_coeff[0] * data[i-1];
  96357. residual[i] = data[i] - (sum >> lp_quantization);
  96358. }
  96359. }
  96360. else { /* order == 11 */
  96361. for(i = 0; i < (int)data_len; i++) {
  96362. sum = 0;
  96363. sum += qlp_coeff[10] * data[i-11];
  96364. sum += qlp_coeff[9] * data[i-10];
  96365. sum += qlp_coeff[8] * data[i-9];
  96366. sum += qlp_coeff[7] * data[i-8];
  96367. sum += qlp_coeff[6] * data[i-7];
  96368. sum += qlp_coeff[5] * data[i-6];
  96369. sum += qlp_coeff[4] * data[i-5];
  96370. sum += qlp_coeff[3] * data[i-4];
  96371. sum += qlp_coeff[2] * data[i-3];
  96372. sum += qlp_coeff[1] * data[i-2];
  96373. sum += qlp_coeff[0] * data[i-1];
  96374. residual[i] = data[i] - (sum >> lp_quantization);
  96375. }
  96376. }
  96377. }
  96378. else {
  96379. if(order == 10) {
  96380. for(i = 0; i < (int)data_len; i++) {
  96381. sum = 0;
  96382. sum += qlp_coeff[9] * data[i-10];
  96383. sum += qlp_coeff[8] * data[i-9];
  96384. sum += qlp_coeff[7] * data[i-8];
  96385. sum += qlp_coeff[6] * data[i-7];
  96386. sum += qlp_coeff[5] * data[i-6];
  96387. sum += qlp_coeff[4] * data[i-5];
  96388. sum += qlp_coeff[3] * data[i-4];
  96389. sum += qlp_coeff[2] * data[i-3];
  96390. sum += qlp_coeff[1] * data[i-2];
  96391. sum += qlp_coeff[0] * data[i-1];
  96392. residual[i] = data[i] - (sum >> lp_quantization);
  96393. }
  96394. }
  96395. else { /* order == 9 */
  96396. for(i = 0; i < (int)data_len; i++) {
  96397. sum = 0;
  96398. sum += qlp_coeff[8] * data[i-9];
  96399. sum += qlp_coeff[7] * data[i-8];
  96400. sum += qlp_coeff[6] * data[i-7];
  96401. sum += qlp_coeff[5] * data[i-6];
  96402. sum += qlp_coeff[4] * data[i-5];
  96403. sum += qlp_coeff[3] * data[i-4];
  96404. sum += qlp_coeff[2] * data[i-3];
  96405. sum += qlp_coeff[1] * data[i-2];
  96406. sum += qlp_coeff[0] * data[i-1];
  96407. residual[i] = data[i] - (sum >> lp_quantization);
  96408. }
  96409. }
  96410. }
  96411. }
  96412. else if(order > 4) {
  96413. if(order > 6) {
  96414. if(order == 8) {
  96415. for(i = 0; i < (int)data_len; i++) {
  96416. sum = 0;
  96417. sum += qlp_coeff[7] * data[i-8];
  96418. sum += qlp_coeff[6] * data[i-7];
  96419. sum += qlp_coeff[5] * data[i-6];
  96420. sum += qlp_coeff[4] * data[i-5];
  96421. sum += qlp_coeff[3] * data[i-4];
  96422. sum += qlp_coeff[2] * data[i-3];
  96423. sum += qlp_coeff[1] * data[i-2];
  96424. sum += qlp_coeff[0] * data[i-1];
  96425. residual[i] = data[i] - (sum >> lp_quantization);
  96426. }
  96427. }
  96428. else { /* order == 7 */
  96429. for(i = 0; i < (int)data_len; i++) {
  96430. sum = 0;
  96431. sum += qlp_coeff[6] * data[i-7];
  96432. sum += qlp_coeff[5] * data[i-6];
  96433. sum += qlp_coeff[4] * data[i-5];
  96434. sum += qlp_coeff[3] * data[i-4];
  96435. sum += qlp_coeff[2] * data[i-3];
  96436. sum += qlp_coeff[1] * data[i-2];
  96437. sum += qlp_coeff[0] * data[i-1];
  96438. residual[i] = data[i] - (sum >> lp_quantization);
  96439. }
  96440. }
  96441. }
  96442. else {
  96443. if(order == 6) {
  96444. for(i = 0; i < (int)data_len; i++) {
  96445. sum = 0;
  96446. sum += qlp_coeff[5] * data[i-6];
  96447. sum += qlp_coeff[4] * data[i-5];
  96448. sum += qlp_coeff[3] * data[i-4];
  96449. sum += qlp_coeff[2] * data[i-3];
  96450. sum += qlp_coeff[1] * data[i-2];
  96451. sum += qlp_coeff[0] * data[i-1];
  96452. residual[i] = data[i] - (sum >> lp_quantization);
  96453. }
  96454. }
  96455. else { /* order == 5 */
  96456. for(i = 0; i < (int)data_len; i++) {
  96457. sum = 0;
  96458. sum += qlp_coeff[4] * data[i-5];
  96459. sum += qlp_coeff[3] * data[i-4];
  96460. sum += qlp_coeff[2] * data[i-3];
  96461. sum += qlp_coeff[1] * data[i-2];
  96462. sum += qlp_coeff[0] * data[i-1];
  96463. residual[i] = data[i] - (sum >> lp_quantization);
  96464. }
  96465. }
  96466. }
  96467. }
  96468. else {
  96469. if(order > 2) {
  96470. if(order == 4) {
  96471. for(i = 0; i < (int)data_len; i++) {
  96472. sum = 0;
  96473. sum += qlp_coeff[3] * data[i-4];
  96474. sum += qlp_coeff[2] * data[i-3];
  96475. sum += qlp_coeff[1] * data[i-2];
  96476. sum += qlp_coeff[0] * data[i-1];
  96477. residual[i] = data[i] - (sum >> lp_quantization);
  96478. }
  96479. }
  96480. else { /* order == 3 */
  96481. for(i = 0; i < (int)data_len; i++) {
  96482. sum = 0;
  96483. sum += qlp_coeff[2] * data[i-3];
  96484. sum += qlp_coeff[1] * data[i-2];
  96485. sum += qlp_coeff[0] * data[i-1];
  96486. residual[i] = data[i] - (sum >> lp_quantization);
  96487. }
  96488. }
  96489. }
  96490. else {
  96491. if(order == 2) {
  96492. for(i = 0; i < (int)data_len; i++) {
  96493. sum = 0;
  96494. sum += qlp_coeff[1] * data[i-2];
  96495. sum += qlp_coeff[0] * data[i-1];
  96496. residual[i] = data[i] - (sum >> lp_quantization);
  96497. }
  96498. }
  96499. else { /* order == 1 */
  96500. for(i = 0; i < (int)data_len; i++)
  96501. residual[i] = data[i] - ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  96502. }
  96503. }
  96504. }
  96505. }
  96506. else { /* order > 12 */
  96507. for(i = 0; i < (int)data_len; i++) {
  96508. sum = 0;
  96509. switch(order) {
  96510. case 32: sum += qlp_coeff[31] * data[i-32];
  96511. case 31: sum += qlp_coeff[30] * data[i-31];
  96512. case 30: sum += qlp_coeff[29] * data[i-30];
  96513. case 29: sum += qlp_coeff[28] * data[i-29];
  96514. case 28: sum += qlp_coeff[27] * data[i-28];
  96515. case 27: sum += qlp_coeff[26] * data[i-27];
  96516. case 26: sum += qlp_coeff[25] * data[i-26];
  96517. case 25: sum += qlp_coeff[24] * data[i-25];
  96518. case 24: sum += qlp_coeff[23] * data[i-24];
  96519. case 23: sum += qlp_coeff[22] * data[i-23];
  96520. case 22: sum += qlp_coeff[21] * data[i-22];
  96521. case 21: sum += qlp_coeff[20] * data[i-21];
  96522. case 20: sum += qlp_coeff[19] * data[i-20];
  96523. case 19: sum += qlp_coeff[18] * data[i-19];
  96524. case 18: sum += qlp_coeff[17] * data[i-18];
  96525. case 17: sum += qlp_coeff[16] * data[i-17];
  96526. case 16: sum += qlp_coeff[15] * data[i-16];
  96527. case 15: sum += qlp_coeff[14] * data[i-15];
  96528. case 14: sum += qlp_coeff[13] * data[i-14];
  96529. case 13: sum += qlp_coeff[12] * data[i-13];
  96530. sum += qlp_coeff[11] * data[i-12];
  96531. sum += qlp_coeff[10] * data[i-11];
  96532. sum += qlp_coeff[ 9] * data[i-10];
  96533. sum += qlp_coeff[ 8] * data[i- 9];
  96534. sum += qlp_coeff[ 7] * data[i- 8];
  96535. sum += qlp_coeff[ 6] * data[i- 7];
  96536. sum += qlp_coeff[ 5] * data[i- 6];
  96537. sum += qlp_coeff[ 4] * data[i- 5];
  96538. sum += qlp_coeff[ 3] * data[i- 4];
  96539. sum += qlp_coeff[ 2] * data[i- 3];
  96540. sum += qlp_coeff[ 1] * data[i- 2];
  96541. sum += qlp_coeff[ 0] * data[i- 1];
  96542. }
  96543. residual[i] = data[i] - (sum >> lp_quantization);
  96544. }
  96545. }
  96546. }
  96547. #endif
  96548. 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[])
  96549. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  96550. {
  96551. unsigned i, j;
  96552. FLAC__int64 sum;
  96553. const FLAC__int32 *history;
  96554. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  96555. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  96556. for(i=0;i<order;i++)
  96557. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  96558. fprintf(stderr,"\n");
  96559. #endif
  96560. FLAC__ASSERT(order > 0);
  96561. for(i = 0; i < data_len; i++) {
  96562. sum = 0;
  96563. history = data;
  96564. for(j = 0; j < order; j++)
  96565. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  96566. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  96567. #if defined _MSC_VER
  96568. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  96569. #else
  96570. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  96571. #endif
  96572. break;
  96573. }
  96574. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*data) - (sum >> lp_quantization)) > 32) {
  96575. #if defined _MSC_VER
  96576. 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));
  96577. #else
  96578. 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)));
  96579. #endif
  96580. break;
  96581. }
  96582. *(residual++) = *(data++) - (FLAC__int32)(sum >> lp_quantization);
  96583. }
  96584. }
  96585. #else /* fully unrolled version for normal use */
  96586. {
  96587. int i;
  96588. FLAC__int64 sum;
  96589. FLAC__ASSERT(order > 0);
  96590. FLAC__ASSERT(order <= 32);
  96591. /*
  96592. * We do unique versions up to 12th order since that's the subset limit.
  96593. * Also they are roughly ordered to match frequency of occurrence to
  96594. * minimize branching.
  96595. */
  96596. if(order <= 12) {
  96597. if(order > 8) {
  96598. if(order > 10) {
  96599. if(order == 12) {
  96600. for(i = 0; i < (int)data_len; i++) {
  96601. sum = 0;
  96602. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  96603. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  96604. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  96605. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  96606. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  96607. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  96608. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  96609. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  96610. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  96611. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  96612. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  96613. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  96614. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  96615. }
  96616. }
  96617. else { /* order == 11 */
  96618. for(i = 0; i < (int)data_len; i++) {
  96619. sum = 0;
  96620. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  96621. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  96622. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  96623. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  96624. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  96625. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  96626. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  96627. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  96628. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  96629. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  96630. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  96631. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  96632. }
  96633. }
  96634. }
  96635. else {
  96636. if(order == 10) {
  96637. for(i = 0; i < (int)data_len; i++) {
  96638. sum = 0;
  96639. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  96640. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  96641. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  96642. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  96643. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  96644. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  96645. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  96646. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  96647. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  96648. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  96649. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  96650. }
  96651. }
  96652. else { /* order == 9 */
  96653. for(i = 0; i < (int)data_len; i++) {
  96654. sum = 0;
  96655. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  96656. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  96657. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  96658. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  96659. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  96660. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  96661. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  96662. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  96663. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  96664. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  96665. }
  96666. }
  96667. }
  96668. }
  96669. else if(order > 4) {
  96670. if(order > 6) {
  96671. if(order == 8) {
  96672. for(i = 0; i < (int)data_len; i++) {
  96673. sum = 0;
  96674. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  96675. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  96676. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  96677. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  96678. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  96679. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  96680. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  96681. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  96682. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  96683. }
  96684. }
  96685. else { /* order == 7 */
  96686. for(i = 0; i < (int)data_len; i++) {
  96687. sum = 0;
  96688. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  96689. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  96690. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  96691. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  96692. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  96693. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  96694. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  96695. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  96696. }
  96697. }
  96698. }
  96699. else {
  96700. if(order == 6) {
  96701. for(i = 0; i < (int)data_len; i++) {
  96702. sum = 0;
  96703. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  96704. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  96705. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  96706. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  96707. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  96708. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  96709. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  96710. }
  96711. }
  96712. else { /* order == 5 */
  96713. for(i = 0; i < (int)data_len; i++) {
  96714. sum = 0;
  96715. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  96716. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  96717. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  96718. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  96719. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  96720. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  96721. }
  96722. }
  96723. }
  96724. }
  96725. else {
  96726. if(order > 2) {
  96727. if(order == 4) {
  96728. for(i = 0; i < (int)data_len; i++) {
  96729. sum = 0;
  96730. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  96731. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  96732. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  96733. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  96734. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  96735. }
  96736. }
  96737. else { /* order == 3 */
  96738. for(i = 0; i < (int)data_len; i++) {
  96739. sum = 0;
  96740. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  96741. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  96742. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  96743. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  96744. }
  96745. }
  96746. }
  96747. else {
  96748. if(order == 2) {
  96749. for(i = 0; i < (int)data_len; i++) {
  96750. sum = 0;
  96751. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  96752. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  96753. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  96754. }
  96755. }
  96756. else { /* order == 1 */
  96757. for(i = 0; i < (int)data_len; i++)
  96758. residual[i] = data[i] - (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  96759. }
  96760. }
  96761. }
  96762. }
  96763. else { /* order > 12 */
  96764. for(i = 0; i < (int)data_len; i++) {
  96765. sum = 0;
  96766. switch(order) {
  96767. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  96768. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  96769. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  96770. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  96771. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  96772. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  96773. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  96774. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  96775. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  96776. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  96777. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  96778. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  96779. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  96780. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  96781. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  96782. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  96783. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  96784. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  96785. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  96786. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  96787. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  96788. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  96789. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  96790. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  96791. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  96792. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  96793. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  96794. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  96795. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  96796. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  96797. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  96798. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  96799. }
  96800. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  96801. }
  96802. }
  96803. }
  96804. #endif
  96805. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  96806. 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[])
  96807. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  96808. {
  96809. FLAC__int64 sumo;
  96810. unsigned i, j;
  96811. FLAC__int32 sum;
  96812. const FLAC__int32 *r = residual, *history;
  96813. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  96814. fprintf(stderr,"FLAC__lpc_restore_signal: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  96815. for(i=0;i<order;i++)
  96816. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  96817. fprintf(stderr,"\n");
  96818. #endif
  96819. FLAC__ASSERT(order > 0);
  96820. for(i = 0; i < data_len; i++) {
  96821. sumo = 0;
  96822. sum = 0;
  96823. history = data;
  96824. for(j = 0; j < order; j++) {
  96825. sum += qlp_coeff[j] * (*(--history));
  96826. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  96827. #if defined _MSC_VER
  96828. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  96829. 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);
  96830. #else
  96831. if(sumo > 2147483647ll || sumo < -2147483648ll)
  96832. 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);
  96833. #endif
  96834. }
  96835. *(data++) = *(r++) + (sum >> lp_quantization);
  96836. }
  96837. /* Here's a slower but clearer version:
  96838. for(i = 0; i < data_len; i++) {
  96839. sum = 0;
  96840. for(j = 0; j < order; j++)
  96841. sum += qlp_coeff[j] * data[i-j-1];
  96842. data[i] = residual[i] + (sum >> lp_quantization);
  96843. }
  96844. */
  96845. }
  96846. #else /* fully unrolled version for normal use */
  96847. {
  96848. int i;
  96849. FLAC__int32 sum;
  96850. FLAC__ASSERT(order > 0);
  96851. FLAC__ASSERT(order <= 32);
  96852. /*
  96853. * We do unique versions up to 12th order since that's the subset limit.
  96854. * Also they are roughly ordered to match frequency of occurrence to
  96855. * minimize branching.
  96856. */
  96857. if(order <= 12) {
  96858. if(order > 8) {
  96859. if(order > 10) {
  96860. if(order == 12) {
  96861. for(i = 0; i < (int)data_len; i++) {
  96862. sum = 0;
  96863. sum += qlp_coeff[11] * data[i-12];
  96864. sum += qlp_coeff[10] * data[i-11];
  96865. sum += qlp_coeff[9] * data[i-10];
  96866. sum += qlp_coeff[8] * data[i-9];
  96867. sum += qlp_coeff[7] * data[i-8];
  96868. sum += qlp_coeff[6] * data[i-7];
  96869. sum += qlp_coeff[5] * data[i-6];
  96870. sum += qlp_coeff[4] * data[i-5];
  96871. sum += qlp_coeff[3] * data[i-4];
  96872. sum += qlp_coeff[2] * data[i-3];
  96873. sum += qlp_coeff[1] * data[i-2];
  96874. sum += qlp_coeff[0] * data[i-1];
  96875. data[i] = residual[i] + (sum >> lp_quantization);
  96876. }
  96877. }
  96878. else { /* order == 11 */
  96879. for(i = 0; i < (int)data_len; i++) {
  96880. sum = 0;
  96881. sum += qlp_coeff[10] * data[i-11];
  96882. sum += qlp_coeff[9] * data[i-10];
  96883. sum += qlp_coeff[8] * data[i-9];
  96884. sum += qlp_coeff[7] * data[i-8];
  96885. sum += qlp_coeff[6] * data[i-7];
  96886. sum += qlp_coeff[5] * data[i-6];
  96887. sum += qlp_coeff[4] * data[i-5];
  96888. sum += qlp_coeff[3] * data[i-4];
  96889. sum += qlp_coeff[2] * data[i-3];
  96890. sum += qlp_coeff[1] * data[i-2];
  96891. sum += qlp_coeff[0] * data[i-1];
  96892. data[i] = residual[i] + (sum >> lp_quantization);
  96893. }
  96894. }
  96895. }
  96896. else {
  96897. if(order == 10) {
  96898. for(i = 0; i < (int)data_len; i++) {
  96899. sum = 0;
  96900. sum += qlp_coeff[9] * data[i-10];
  96901. sum += qlp_coeff[8] * data[i-9];
  96902. sum += qlp_coeff[7] * data[i-8];
  96903. sum += qlp_coeff[6] * data[i-7];
  96904. sum += qlp_coeff[5] * data[i-6];
  96905. sum += qlp_coeff[4] * data[i-5];
  96906. sum += qlp_coeff[3] * data[i-4];
  96907. sum += qlp_coeff[2] * data[i-3];
  96908. sum += qlp_coeff[1] * data[i-2];
  96909. sum += qlp_coeff[0] * data[i-1];
  96910. data[i] = residual[i] + (sum >> lp_quantization);
  96911. }
  96912. }
  96913. else { /* order == 9 */
  96914. for(i = 0; i < (int)data_len; i++) {
  96915. sum = 0;
  96916. sum += qlp_coeff[8] * data[i-9];
  96917. sum += qlp_coeff[7] * data[i-8];
  96918. sum += qlp_coeff[6] * data[i-7];
  96919. sum += qlp_coeff[5] * data[i-6];
  96920. sum += qlp_coeff[4] * data[i-5];
  96921. sum += qlp_coeff[3] * data[i-4];
  96922. sum += qlp_coeff[2] * data[i-3];
  96923. sum += qlp_coeff[1] * data[i-2];
  96924. sum += qlp_coeff[0] * data[i-1];
  96925. data[i] = residual[i] + (sum >> lp_quantization);
  96926. }
  96927. }
  96928. }
  96929. }
  96930. else if(order > 4) {
  96931. if(order > 6) {
  96932. if(order == 8) {
  96933. for(i = 0; i < (int)data_len; i++) {
  96934. sum = 0;
  96935. sum += qlp_coeff[7] * data[i-8];
  96936. sum += qlp_coeff[6] * data[i-7];
  96937. sum += qlp_coeff[5] * data[i-6];
  96938. sum += qlp_coeff[4] * data[i-5];
  96939. sum += qlp_coeff[3] * data[i-4];
  96940. sum += qlp_coeff[2] * data[i-3];
  96941. sum += qlp_coeff[1] * data[i-2];
  96942. sum += qlp_coeff[0] * data[i-1];
  96943. data[i] = residual[i] + (sum >> lp_quantization);
  96944. }
  96945. }
  96946. else { /* order == 7 */
  96947. for(i = 0; i < (int)data_len; i++) {
  96948. sum = 0;
  96949. sum += qlp_coeff[6] * data[i-7];
  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. data[i] = residual[i] + (sum >> lp_quantization);
  96957. }
  96958. }
  96959. }
  96960. else {
  96961. if(order == 6) {
  96962. for(i = 0; i < (int)data_len; i++) {
  96963. sum = 0;
  96964. sum += qlp_coeff[5] * data[i-6];
  96965. sum += qlp_coeff[4] * data[i-5];
  96966. sum += qlp_coeff[3] * data[i-4];
  96967. sum += qlp_coeff[2] * data[i-3];
  96968. sum += qlp_coeff[1] * data[i-2];
  96969. sum += qlp_coeff[0] * data[i-1];
  96970. data[i] = residual[i] + (sum >> lp_quantization);
  96971. }
  96972. }
  96973. else { /* order == 5 */
  96974. for(i = 0; i < (int)data_len; i++) {
  96975. sum = 0;
  96976. sum += qlp_coeff[4] * data[i-5];
  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. data[i] = residual[i] + (sum >> lp_quantization);
  96982. }
  96983. }
  96984. }
  96985. }
  96986. else {
  96987. if(order > 2) {
  96988. if(order == 4) {
  96989. for(i = 0; i < (int)data_len; i++) {
  96990. sum = 0;
  96991. sum += qlp_coeff[3] * data[i-4];
  96992. sum += qlp_coeff[2] * data[i-3];
  96993. sum += qlp_coeff[1] * data[i-2];
  96994. sum += qlp_coeff[0] * data[i-1];
  96995. data[i] = residual[i] + (sum >> lp_quantization);
  96996. }
  96997. }
  96998. else { /* order == 3 */
  96999. for(i = 0; i < (int)data_len; i++) {
  97000. sum = 0;
  97001. sum += qlp_coeff[2] * data[i-3];
  97002. sum += qlp_coeff[1] * data[i-2];
  97003. sum += qlp_coeff[0] * data[i-1];
  97004. data[i] = residual[i] + (sum >> lp_quantization);
  97005. }
  97006. }
  97007. }
  97008. else {
  97009. if(order == 2) {
  97010. for(i = 0; i < (int)data_len; i++) {
  97011. sum = 0;
  97012. sum += qlp_coeff[1] * data[i-2];
  97013. sum += qlp_coeff[0] * data[i-1];
  97014. data[i] = residual[i] + (sum >> lp_quantization);
  97015. }
  97016. }
  97017. else { /* order == 1 */
  97018. for(i = 0; i < (int)data_len; i++)
  97019. data[i] = residual[i] + ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  97020. }
  97021. }
  97022. }
  97023. }
  97024. else { /* order > 12 */
  97025. for(i = 0; i < (int)data_len; i++) {
  97026. sum = 0;
  97027. switch(order) {
  97028. case 32: sum += qlp_coeff[31] * data[i-32];
  97029. case 31: sum += qlp_coeff[30] * data[i-31];
  97030. case 30: sum += qlp_coeff[29] * data[i-30];
  97031. case 29: sum += qlp_coeff[28] * data[i-29];
  97032. case 28: sum += qlp_coeff[27] * data[i-28];
  97033. case 27: sum += qlp_coeff[26] * data[i-27];
  97034. case 26: sum += qlp_coeff[25] * data[i-26];
  97035. case 25: sum += qlp_coeff[24] * data[i-25];
  97036. case 24: sum += qlp_coeff[23] * data[i-24];
  97037. case 23: sum += qlp_coeff[22] * data[i-23];
  97038. case 22: sum += qlp_coeff[21] * data[i-22];
  97039. case 21: sum += qlp_coeff[20] * data[i-21];
  97040. case 20: sum += qlp_coeff[19] * data[i-20];
  97041. case 19: sum += qlp_coeff[18] * data[i-19];
  97042. case 18: sum += qlp_coeff[17] * data[i-18];
  97043. case 17: sum += qlp_coeff[16] * data[i-17];
  97044. case 16: sum += qlp_coeff[15] * data[i-16];
  97045. case 15: sum += qlp_coeff[14] * data[i-15];
  97046. case 14: sum += qlp_coeff[13] * data[i-14];
  97047. case 13: sum += qlp_coeff[12] * data[i-13];
  97048. sum += qlp_coeff[11] * data[i-12];
  97049. sum += qlp_coeff[10] * data[i-11];
  97050. sum += qlp_coeff[ 9] * data[i-10];
  97051. sum += qlp_coeff[ 8] * data[i- 9];
  97052. sum += qlp_coeff[ 7] * data[i- 8];
  97053. sum += qlp_coeff[ 6] * data[i- 7];
  97054. sum += qlp_coeff[ 5] * data[i- 6];
  97055. sum += qlp_coeff[ 4] * data[i- 5];
  97056. sum += qlp_coeff[ 3] * data[i- 4];
  97057. sum += qlp_coeff[ 2] * data[i- 3];
  97058. sum += qlp_coeff[ 1] * data[i- 2];
  97059. sum += qlp_coeff[ 0] * data[i- 1];
  97060. }
  97061. data[i] = residual[i] + (sum >> lp_quantization);
  97062. }
  97063. }
  97064. }
  97065. #endif
  97066. 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[])
  97067. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97068. {
  97069. unsigned i, j;
  97070. FLAC__int64 sum;
  97071. const FLAC__int32 *r = residual, *history;
  97072. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97073. fprintf(stderr,"FLAC__lpc_restore_signal_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97074. for(i=0;i<order;i++)
  97075. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97076. fprintf(stderr,"\n");
  97077. #endif
  97078. FLAC__ASSERT(order > 0);
  97079. for(i = 0; i < data_len; i++) {
  97080. sum = 0;
  97081. history = data;
  97082. for(j = 0; j < order; j++)
  97083. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  97084. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  97085. #ifdef _MSC_VER
  97086. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  97087. #else
  97088. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  97089. #endif
  97090. break;
  97091. }
  97092. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*r) + (sum >> lp_quantization)) > 32) {
  97093. #ifdef _MSC_VER
  97094. 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));
  97095. #else
  97096. 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)));
  97097. #endif
  97098. break;
  97099. }
  97100. *(data++) = *(r++) + (FLAC__int32)(sum >> lp_quantization);
  97101. }
  97102. }
  97103. #else /* fully unrolled version for normal use */
  97104. {
  97105. int i;
  97106. FLAC__int64 sum;
  97107. FLAC__ASSERT(order > 0);
  97108. FLAC__ASSERT(order <= 32);
  97109. /*
  97110. * We do unique versions up to 12th order since that's the subset limit.
  97111. * Also they are roughly ordered to match frequency of occurrence to
  97112. * minimize branching.
  97113. */
  97114. if(order <= 12) {
  97115. if(order > 8) {
  97116. if(order > 10) {
  97117. if(order == 12) {
  97118. for(i = 0; i < (int)data_len; i++) {
  97119. sum = 0;
  97120. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  97121. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97122. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97123. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97124. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97125. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97126. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97127. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97128. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97129. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97130. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97131. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97132. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97133. }
  97134. }
  97135. else { /* order == 11 */
  97136. for(i = 0; i < (int)data_len; i++) {
  97137. sum = 0;
  97138. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97139. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97140. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97141. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97142. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97143. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97144. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97145. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97146. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97147. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97148. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97149. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97150. }
  97151. }
  97152. }
  97153. else {
  97154. if(order == 10) {
  97155. for(i = 0; i < (int)data_len; i++) {
  97156. sum = 0;
  97157. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97158. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97159. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97160. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97161. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97162. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97163. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97164. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97165. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97166. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97167. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97168. }
  97169. }
  97170. else { /* order == 9 */
  97171. for(i = 0; i < (int)data_len; i++) {
  97172. sum = 0;
  97173. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97174. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97175. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97176. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97177. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97178. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97179. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97180. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97181. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97182. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97183. }
  97184. }
  97185. }
  97186. }
  97187. else if(order > 4) {
  97188. if(order > 6) {
  97189. if(order == 8) {
  97190. for(i = 0; i < (int)data_len; i++) {
  97191. sum = 0;
  97192. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97193. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97194. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97195. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97196. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97197. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97198. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97199. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97200. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97201. }
  97202. }
  97203. else { /* order == 7 */
  97204. for(i = 0; i < (int)data_len; i++) {
  97205. sum = 0;
  97206. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  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. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97214. }
  97215. }
  97216. }
  97217. else {
  97218. if(order == 6) {
  97219. for(i = 0; i < (int)data_len; i++) {
  97220. sum = 0;
  97221. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97222. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97223. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97224. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97225. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97226. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97227. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97228. }
  97229. }
  97230. else { /* order == 5 */
  97231. for(i = 0; i < (int)data_len; i++) {
  97232. sum = 0;
  97233. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  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. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97239. }
  97240. }
  97241. }
  97242. }
  97243. else {
  97244. if(order > 2) {
  97245. if(order == 4) {
  97246. for(i = 0; i < (int)data_len; i++) {
  97247. sum = 0;
  97248. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97249. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97250. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97251. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97252. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97253. }
  97254. }
  97255. else { /* order == 3 */
  97256. for(i = 0; i < (int)data_len; i++) {
  97257. sum = 0;
  97258. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97259. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97260. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97261. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97262. }
  97263. }
  97264. }
  97265. else {
  97266. if(order == 2) {
  97267. for(i = 0; i < (int)data_len; i++) {
  97268. sum = 0;
  97269. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97270. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97271. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97272. }
  97273. }
  97274. else { /* order == 1 */
  97275. for(i = 0; i < (int)data_len; i++)
  97276. data[i] = residual[i] + (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  97277. }
  97278. }
  97279. }
  97280. }
  97281. else { /* order > 12 */
  97282. for(i = 0; i < (int)data_len; i++) {
  97283. sum = 0;
  97284. switch(order) {
  97285. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  97286. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  97287. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  97288. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  97289. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  97290. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  97291. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  97292. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  97293. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  97294. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  97295. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  97296. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  97297. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  97298. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  97299. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  97300. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  97301. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  97302. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  97303. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  97304. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  97305. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  97306. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97307. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  97308. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  97309. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  97310. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  97311. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  97312. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  97313. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  97314. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  97315. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  97316. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  97317. }
  97318. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97319. }
  97320. }
  97321. }
  97322. #endif
  97323. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97324. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples)
  97325. {
  97326. FLAC__double error_scale;
  97327. FLAC__ASSERT(total_samples > 0);
  97328. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  97329. return FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(lpc_error, error_scale);
  97330. }
  97331. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale)
  97332. {
  97333. if(lpc_error > 0.0) {
  97334. FLAC__double bps = (FLAC__double)0.5 * log(error_scale * lpc_error) / M_LN2;
  97335. if(bps >= 0.0)
  97336. return bps;
  97337. else
  97338. return 0.0;
  97339. }
  97340. else if(lpc_error < 0.0) { /* error should not be negative but can happen due to inadequate floating-point resolution */
  97341. return 1e32;
  97342. }
  97343. else {
  97344. return 0.0;
  97345. }
  97346. }
  97347. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order)
  97348. {
  97349. 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 */
  97350. FLAC__double bits, best_bits, error_scale;
  97351. FLAC__ASSERT(max_order > 0);
  97352. FLAC__ASSERT(total_samples > 0);
  97353. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  97354. best_index = 0;
  97355. best_bits = (unsigned)(-1);
  97356. for(index = 0, order = 1; index < max_order; index++, order++) {
  97357. 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);
  97358. if(bits < best_bits) {
  97359. best_index = index;
  97360. best_bits = bits;
  97361. }
  97362. }
  97363. return best_index+1; /* +1 since index of lpc_error[] is order-1 */
  97364. }
  97365. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  97366. #endif
  97367. /*** End of inlined file: lpc_flac.c ***/
  97368. /*** Start of inlined file: md5.c ***/
  97369. /*** Start of inlined file: juce_FlacHeader.h ***/
  97370. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  97371. // tasks..
  97372. #define VERSION "1.2.1"
  97373. #define FLAC__NO_DLL 1
  97374. #if JUCE_MSVC
  97375. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  97376. #endif
  97377. #if JUCE_MAC
  97378. #define FLAC__SYS_DARWIN 1
  97379. #endif
  97380. /*** End of inlined file: juce_FlacHeader.h ***/
  97381. #if JUCE_USE_FLAC
  97382. #if HAVE_CONFIG_H
  97383. # include <config.h>
  97384. #endif
  97385. #include <stdlib.h> /* for malloc() */
  97386. #include <string.h> /* for memcpy() */
  97387. /*** Start of inlined file: md5.h ***/
  97388. #ifndef FLAC__PRIVATE__MD5_H
  97389. #define FLAC__PRIVATE__MD5_H
  97390. /*
  97391. * This is the header file for the MD5 message-digest algorithm.
  97392. * The algorithm is due to Ron Rivest. This code was
  97393. * written by Colin Plumb in 1993, no copyright is claimed.
  97394. * This code is in the public domain; do with it what you wish.
  97395. *
  97396. * Equivalent code is available from RSA Data Security, Inc.
  97397. * This code has been tested against that, and is equivalent,
  97398. * except that you don't need to include two pages of legalese
  97399. * with every copy.
  97400. *
  97401. * To compute the message digest of a chunk of bytes, declare an
  97402. * MD5Context structure, pass it to MD5Init, call MD5Update as
  97403. * needed on buffers full of bytes, and then call MD5Final, which
  97404. * will fill a supplied 16-byte array with the digest.
  97405. *
  97406. * Changed so as no longer to depend on Colin Plumb's `usual.h'
  97407. * header definitions; now uses stuff from dpkg's config.h
  97408. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  97409. * Still in the public domain.
  97410. *
  97411. * Josh Coalson: made some changes to integrate with libFLAC.
  97412. * Still in the public domain, with no warranty.
  97413. */
  97414. typedef struct {
  97415. FLAC__uint32 in[16];
  97416. FLAC__uint32 buf[4];
  97417. FLAC__uint32 bytes[2];
  97418. FLAC__byte *internal_buf;
  97419. size_t capacity;
  97420. } FLAC__MD5Context;
  97421. void FLAC__MD5Init(FLAC__MD5Context *context);
  97422. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *context);
  97423. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample);
  97424. #endif
  97425. /*** End of inlined file: md5.h ***/
  97426. #ifndef FLaC__INLINE
  97427. #define FLaC__INLINE
  97428. #endif
  97429. /*
  97430. * This code implements the MD5 message-digest algorithm.
  97431. * The algorithm is due to Ron Rivest. This code was
  97432. * written by Colin Plumb in 1993, no copyright is claimed.
  97433. * This code is in the public domain; do with it what you wish.
  97434. *
  97435. * Equivalent code is available from RSA Data Security, Inc.
  97436. * This code has been tested against that, and is equivalent,
  97437. * except that you don't need to include two pages of legalese
  97438. * with every copy.
  97439. *
  97440. * To compute the message digest of a chunk of bytes, declare an
  97441. * MD5Context structure, pass it to MD5Init, call MD5Update as
  97442. * needed on buffers full of bytes, and then call MD5Final, which
  97443. * will fill a supplied 16-byte array with the digest.
  97444. *
  97445. * Changed so as no longer to depend on Colin Plumb's `usual.h' header
  97446. * definitions; now uses stuff from dpkg's config.h.
  97447. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  97448. * Still in the public domain.
  97449. *
  97450. * Josh Coalson: made some changes to integrate with libFLAC.
  97451. * Still in the public domain.
  97452. */
  97453. /* The four core functions - F1 is optimized somewhat */
  97454. /* #define F1(x, y, z) (x & y | ~x & z) */
  97455. #define F1(x, y, z) (z ^ (x & (y ^ z)))
  97456. #define F2(x, y, z) F1(z, x, y)
  97457. #define F3(x, y, z) (x ^ y ^ z)
  97458. #define F4(x, y, z) (y ^ (x | ~z))
  97459. /* This is the central step in the MD5 algorithm. */
  97460. #define MD5STEP(f,w,x,y,z,in,s) \
  97461. (w += f(x,y,z) + in, w = (w<<s | w>>(32-s)) + x)
  97462. /*
  97463. * The core of the MD5 algorithm, this alters an existing MD5 hash to
  97464. * reflect the addition of 16 longwords of new data. MD5Update blocks
  97465. * the data and converts bytes into longwords for this routine.
  97466. */
  97467. static void FLAC__MD5Transform(FLAC__uint32 buf[4], FLAC__uint32 const in[16])
  97468. {
  97469. register FLAC__uint32 a, b, c, d;
  97470. a = buf[0];
  97471. b = buf[1];
  97472. c = buf[2];
  97473. d = buf[3];
  97474. MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
  97475. MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
  97476. MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
  97477. MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
  97478. MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
  97479. MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
  97480. MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
  97481. MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
  97482. MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
  97483. MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
  97484. MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
  97485. MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
  97486. MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
  97487. MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
  97488. MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
  97489. MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
  97490. MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
  97491. MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
  97492. MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
  97493. MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
  97494. MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
  97495. MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
  97496. MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
  97497. MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
  97498. MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
  97499. MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
  97500. MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
  97501. MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
  97502. MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
  97503. MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
  97504. MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
  97505. MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
  97506. MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
  97507. MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
  97508. MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
  97509. MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
  97510. MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
  97511. MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
  97512. MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
  97513. MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
  97514. MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
  97515. MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
  97516. MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
  97517. MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
  97518. MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
  97519. MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
  97520. MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
  97521. MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
  97522. MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
  97523. MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
  97524. MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
  97525. MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
  97526. MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
  97527. MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
  97528. MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
  97529. MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
  97530. MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
  97531. MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
  97532. MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
  97533. MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
  97534. MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
  97535. MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
  97536. MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
  97537. MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
  97538. buf[0] += a;
  97539. buf[1] += b;
  97540. buf[2] += c;
  97541. buf[3] += d;
  97542. }
  97543. #if WORDS_BIGENDIAN
  97544. //@@@@@@ OPT: use bswap/intrinsics
  97545. static void byteSwap(FLAC__uint32 *buf, unsigned words)
  97546. {
  97547. register FLAC__uint32 x;
  97548. do {
  97549. x = *buf;
  97550. x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff);
  97551. *buf++ = (x >> 16) | (x << 16);
  97552. } while (--words);
  97553. }
  97554. static void byteSwapX16(FLAC__uint32 *buf)
  97555. {
  97556. register FLAC__uint32 x;
  97557. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  97558. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  97559. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  97560. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  97561. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  97562. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  97563. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  97564. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  97565. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  97566. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  97567. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  97568. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  97569. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  97570. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  97571. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  97572. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf = (x >> 16) | (x << 16);
  97573. }
  97574. #else
  97575. #define byteSwap(buf, words)
  97576. #define byteSwapX16(buf)
  97577. #endif
  97578. /*
  97579. * Update context to reflect the concatenation of another buffer full
  97580. * of bytes.
  97581. */
  97582. static void FLAC__MD5Update(FLAC__MD5Context *ctx, FLAC__byte const *buf, unsigned len)
  97583. {
  97584. FLAC__uint32 t;
  97585. /* Update byte count */
  97586. t = ctx->bytes[0];
  97587. if ((ctx->bytes[0] = t + len) < t)
  97588. ctx->bytes[1]++; /* Carry from low to high */
  97589. t = 64 - (t & 0x3f); /* Space available in ctx->in (at least 1) */
  97590. if (t > len) {
  97591. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, len);
  97592. return;
  97593. }
  97594. /* First chunk is an odd size */
  97595. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, t);
  97596. byteSwapX16(ctx->in);
  97597. FLAC__MD5Transform(ctx->buf, ctx->in);
  97598. buf += t;
  97599. len -= t;
  97600. /* Process data in 64-byte chunks */
  97601. while (len >= 64) {
  97602. memcpy(ctx->in, buf, 64);
  97603. byteSwapX16(ctx->in);
  97604. FLAC__MD5Transform(ctx->buf, ctx->in);
  97605. buf += 64;
  97606. len -= 64;
  97607. }
  97608. /* Handle any remaining bytes of data. */
  97609. memcpy(ctx->in, buf, len);
  97610. }
  97611. /*
  97612. * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
  97613. * initialization constants.
  97614. */
  97615. void FLAC__MD5Init(FLAC__MD5Context *ctx)
  97616. {
  97617. ctx->buf[0] = 0x67452301;
  97618. ctx->buf[1] = 0xefcdab89;
  97619. ctx->buf[2] = 0x98badcfe;
  97620. ctx->buf[3] = 0x10325476;
  97621. ctx->bytes[0] = 0;
  97622. ctx->bytes[1] = 0;
  97623. ctx->internal_buf = 0;
  97624. ctx->capacity = 0;
  97625. }
  97626. /*
  97627. * Final wrapup - pad to 64-byte boundary with the bit pattern
  97628. * 1 0* (64-bit count of bits processed, MSB-first)
  97629. */
  97630. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *ctx)
  97631. {
  97632. int count = ctx->bytes[0] & 0x3f; /* Number of bytes in ctx->in */
  97633. FLAC__byte *p = (FLAC__byte *)ctx->in + count;
  97634. /* Set the first char of padding to 0x80. There is always room. */
  97635. *p++ = 0x80;
  97636. /* Bytes of padding needed to make 56 bytes (-8..55) */
  97637. count = 56 - 1 - count;
  97638. if (count < 0) { /* Padding forces an extra block */
  97639. memset(p, 0, count + 8);
  97640. byteSwapX16(ctx->in);
  97641. FLAC__MD5Transform(ctx->buf, ctx->in);
  97642. p = (FLAC__byte *)ctx->in;
  97643. count = 56;
  97644. }
  97645. memset(p, 0, count);
  97646. byteSwap(ctx->in, 14);
  97647. /* Append length in bits and transform */
  97648. ctx->in[14] = ctx->bytes[0] << 3;
  97649. ctx->in[15] = ctx->bytes[1] << 3 | ctx->bytes[0] >> 29;
  97650. FLAC__MD5Transform(ctx->buf, ctx->in);
  97651. byteSwap(ctx->buf, 4);
  97652. memcpy(digest, ctx->buf, 16);
  97653. memset(ctx, 0, sizeof(ctx)); /* In case it's sensitive */
  97654. if(0 != ctx->internal_buf) {
  97655. free(ctx->internal_buf);
  97656. ctx->internal_buf = 0;
  97657. ctx->capacity = 0;
  97658. }
  97659. }
  97660. /*
  97661. * Convert the incoming audio signal to a byte stream
  97662. */
  97663. static void format_input_(FLAC__byte *buf, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  97664. {
  97665. unsigned channel, sample;
  97666. register FLAC__int32 a_word;
  97667. register FLAC__byte *buf_ = buf;
  97668. #if WORDS_BIGENDIAN
  97669. #else
  97670. if(channels == 2 && bytes_per_sample == 2) {
  97671. FLAC__int16 *buf1_ = ((FLAC__int16*)buf_) + 1;
  97672. memcpy(buf_, signal[0], sizeof(FLAC__int32) * samples);
  97673. for(sample = 0; sample < samples; sample++, buf1_+=2)
  97674. *buf1_ = (FLAC__int16)signal[1][sample];
  97675. }
  97676. else if(channels == 1 && bytes_per_sample == 2) {
  97677. FLAC__int16 *buf1_ = (FLAC__int16*)buf_;
  97678. for(sample = 0; sample < samples; sample++)
  97679. *buf1_++ = (FLAC__int16)signal[0][sample];
  97680. }
  97681. else
  97682. #endif
  97683. if(bytes_per_sample == 2) {
  97684. if(channels == 2) {
  97685. for(sample = 0; sample < samples; sample++) {
  97686. a_word = signal[0][sample];
  97687. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  97688. *buf_++ = (FLAC__byte)a_word;
  97689. a_word = signal[1][sample];
  97690. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  97691. *buf_++ = (FLAC__byte)a_word;
  97692. }
  97693. }
  97694. else if(channels == 1) {
  97695. for(sample = 0; sample < samples; sample++) {
  97696. a_word = signal[0][sample];
  97697. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  97698. *buf_++ = (FLAC__byte)a_word;
  97699. }
  97700. }
  97701. else {
  97702. for(sample = 0; sample < samples; sample++) {
  97703. for(channel = 0; channel < channels; channel++) {
  97704. a_word = signal[channel][sample];
  97705. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  97706. *buf_++ = (FLAC__byte)a_word;
  97707. }
  97708. }
  97709. }
  97710. }
  97711. else if(bytes_per_sample == 3) {
  97712. if(channels == 2) {
  97713. for(sample = 0; sample < samples; sample++) {
  97714. a_word = signal[0][sample];
  97715. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  97716. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  97717. *buf_++ = (FLAC__byte)a_word;
  97718. a_word = signal[1][sample];
  97719. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  97720. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  97721. *buf_++ = (FLAC__byte)a_word;
  97722. }
  97723. }
  97724. else if(channels == 1) {
  97725. for(sample = 0; sample < samples; sample++) {
  97726. a_word = signal[0][sample];
  97727. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  97728. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  97729. *buf_++ = (FLAC__byte)a_word;
  97730. }
  97731. }
  97732. else {
  97733. for(sample = 0; sample < samples; sample++) {
  97734. for(channel = 0; channel < channels; channel++) {
  97735. a_word = signal[channel][sample];
  97736. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  97737. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  97738. *buf_++ = (FLAC__byte)a_word;
  97739. }
  97740. }
  97741. }
  97742. }
  97743. else if(bytes_per_sample == 1) {
  97744. if(channels == 2) {
  97745. for(sample = 0; sample < samples; sample++) {
  97746. a_word = signal[0][sample];
  97747. *buf_++ = (FLAC__byte)a_word;
  97748. a_word = signal[1][sample];
  97749. *buf_++ = (FLAC__byte)a_word;
  97750. }
  97751. }
  97752. else if(channels == 1) {
  97753. for(sample = 0; sample < samples; sample++) {
  97754. a_word = signal[0][sample];
  97755. *buf_++ = (FLAC__byte)a_word;
  97756. }
  97757. }
  97758. else {
  97759. for(sample = 0; sample < samples; sample++) {
  97760. for(channel = 0; channel < channels; channel++) {
  97761. a_word = signal[channel][sample];
  97762. *buf_++ = (FLAC__byte)a_word;
  97763. }
  97764. }
  97765. }
  97766. }
  97767. else { /* bytes_per_sample == 4, maybe optimize more later */
  97768. for(sample = 0; sample < samples; sample++) {
  97769. for(channel = 0; channel < channels; channel++) {
  97770. a_word = signal[channel][sample];
  97771. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  97772. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  97773. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  97774. *buf_++ = (FLAC__byte)a_word;
  97775. }
  97776. }
  97777. }
  97778. }
  97779. /*
  97780. * Convert the incoming audio signal to a byte stream and FLAC__MD5Update it.
  97781. */
  97782. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  97783. {
  97784. const size_t bytes_needed = (size_t)channels * (size_t)samples * (size_t)bytes_per_sample;
  97785. /* overflow check */
  97786. if((size_t)channels > SIZE_MAX / (size_t)bytes_per_sample)
  97787. return false;
  97788. if((size_t)channels * (size_t)bytes_per_sample > SIZE_MAX / (size_t)samples)
  97789. return false;
  97790. if(ctx->capacity < bytes_needed) {
  97791. FLAC__byte *tmp = (FLAC__byte*)realloc(ctx->internal_buf, bytes_needed);
  97792. if(0 == tmp) {
  97793. free(ctx->internal_buf);
  97794. if(0 == (ctx->internal_buf = (FLAC__byte*)safe_malloc_(bytes_needed)))
  97795. return false;
  97796. }
  97797. ctx->internal_buf = tmp;
  97798. ctx->capacity = bytes_needed;
  97799. }
  97800. format_input_(ctx->internal_buf, signal, channels, samples, bytes_per_sample);
  97801. FLAC__MD5Update(ctx, ctx->internal_buf, bytes_needed);
  97802. return true;
  97803. }
  97804. #endif
  97805. /*** End of inlined file: md5.c ***/
  97806. /*** Start of inlined file: memory.c ***/
  97807. /*** Start of inlined file: juce_FlacHeader.h ***/
  97808. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  97809. // tasks..
  97810. #define VERSION "1.2.1"
  97811. #define FLAC__NO_DLL 1
  97812. #if JUCE_MSVC
  97813. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  97814. #endif
  97815. #if JUCE_MAC
  97816. #define FLAC__SYS_DARWIN 1
  97817. #endif
  97818. /*** End of inlined file: juce_FlacHeader.h ***/
  97819. #if JUCE_USE_FLAC
  97820. #if HAVE_CONFIG_H
  97821. # include <config.h>
  97822. #endif
  97823. /*** Start of inlined file: memory.h ***/
  97824. #ifndef FLAC__PRIVATE__MEMORY_H
  97825. #define FLAC__PRIVATE__MEMORY_H
  97826. #ifdef HAVE_CONFIG_H
  97827. #include <config.h>
  97828. #endif
  97829. #include <stdlib.h> /* for size_t */
  97830. /* Returns the unaligned address returned by malloc.
  97831. * Use free() on this address to deallocate.
  97832. */
  97833. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address);
  97834. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer);
  97835. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer);
  97836. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer);
  97837. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer);
  97838. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97839. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer);
  97840. #endif
  97841. #endif
  97842. /*** End of inlined file: memory.h ***/
  97843. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address)
  97844. {
  97845. void *x;
  97846. FLAC__ASSERT(0 != aligned_address);
  97847. #ifdef FLAC__ALIGN_MALLOC_DATA
  97848. /* align on 32-byte (256-bit) boundary */
  97849. x = safe_malloc_add_2op_(bytes, /*+*/31);
  97850. #ifdef SIZEOF_VOIDP
  97851. #if SIZEOF_VOIDP == 4
  97852. /* could do *aligned_address = x + ((unsigned) (32 - (((unsigned)x) & 31))) & 31; */
  97853. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  97854. #elif SIZEOF_VOIDP == 8
  97855. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  97856. #else
  97857. # error Unsupported sizeof(void*)
  97858. #endif
  97859. #else
  97860. /* there's got to be a better way to do this right for all archs */
  97861. if(sizeof(void*) == sizeof(unsigned))
  97862. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  97863. else if(sizeof(void*) == sizeof(FLAC__uint64))
  97864. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  97865. else
  97866. return 0;
  97867. #endif
  97868. #else
  97869. x = safe_malloc_(bytes);
  97870. *aligned_address = x;
  97871. #endif
  97872. return x;
  97873. }
  97874. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer)
  97875. {
  97876. FLAC__int32 *pu; /* unaligned pointer */
  97877. union { /* union needed to comply with C99 pointer aliasing rules */
  97878. FLAC__int32 *pa; /* aligned pointer */
  97879. void *pv; /* aligned pointer alias */
  97880. } u;
  97881. FLAC__ASSERT(elements > 0);
  97882. FLAC__ASSERT(0 != unaligned_pointer);
  97883. FLAC__ASSERT(0 != aligned_pointer);
  97884. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  97885. pu = (FLAC__int32*)FLAC__memory_alloc_aligned(sizeof(*pu) * (size_t)elements, &u.pv);
  97886. if(0 == pu) {
  97887. return false;
  97888. }
  97889. else {
  97890. if(*unaligned_pointer != 0)
  97891. free(*unaligned_pointer);
  97892. *unaligned_pointer = pu;
  97893. *aligned_pointer = u.pa;
  97894. return true;
  97895. }
  97896. }
  97897. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer)
  97898. {
  97899. FLAC__uint32 *pu; /* unaligned pointer */
  97900. union { /* union needed to comply with C99 pointer aliasing rules */
  97901. FLAC__uint32 *pa; /* aligned pointer */
  97902. void *pv; /* aligned pointer alias */
  97903. } u;
  97904. FLAC__ASSERT(elements > 0);
  97905. FLAC__ASSERT(0 != unaligned_pointer);
  97906. FLAC__ASSERT(0 != aligned_pointer);
  97907. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  97908. pu = (FLAC__uint32*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  97909. if(0 == pu) {
  97910. return false;
  97911. }
  97912. else {
  97913. if(*unaligned_pointer != 0)
  97914. free(*unaligned_pointer);
  97915. *unaligned_pointer = pu;
  97916. *aligned_pointer = u.pa;
  97917. return true;
  97918. }
  97919. }
  97920. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer)
  97921. {
  97922. FLAC__uint64 *pu; /* unaligned pointer */
  97923. union { /* union needed to comply with C99 pointer aliasing rules */
  97924. FLAC__uint64 *pa; /* aligned pointer */
  97925. void *pv; /* aligned pointer alias */
  97926. } u;
  97927. FLAC__ASSERT(elements > 0);
  97928. FLAC__ASSERT(0 != unaligned_pointer);
  97929. FLAC__ASSERT(0 != aligned_pointer);
  97930. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  97931. pu = (FLAC__uint64*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  97932. if(0 == pu) {
  97933. return false;
  97934. }
  97935. else {
  97936. if(*unaligned_pointer != 0)
  97937. free(*unaligned_pointer);
  97938. *unaligned_pointer = pu;
  97939. *aligned_pointer = u.pa;
  97940. return true;
  97941. }
  97942. }
  97943. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer)
  97944. {
  97945. unsigned *pu; /* unaligned pointer */
  97946. union { /* union needed to comply with C99 pointer aliasing rules */
  97947. unsigned *pa; /* aligned pointer */
  97948. void *pv; /* aligned pointer alias */
  97949. } u;
  97950. FLAC__ASSERT(elements > 0);
  97951. FLAC__ASSERT(0 != unaligned_pointer);
  97952. FLAC__ASSERT(0 != aligned_pointer);
  97953. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  97954. pu = (unsigned*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  97955. if(0 == pu) {
  97956. return false;
  97957. }
  97958. else {
  97959. if(*unaligned_pointer != 0)
  97960. free(*unaligned_pointer);
  97961. *unaligned_pointer = pu;
  97962. *aligned_pointer = u.pa;
  97963. return true;
  97964. }
  97965. }
  97966. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97967. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer)
  97968. {
  97969. FLAC__real *pu; /* unaligned pointer */
  97970. union { /* union needed to comply with C99 pointer aliasing rules */
  97971. FLAC__real *pa; /* aligned pointer */
  97972. void *pv; /* aligned pointer alias */
  97973. } u;
  97974. FLAC__ASSERT(elements > 0);
  97975. FLAC__ASSERT(0 != unaligned_pointer);
  97976. FLAC__ASSERT(0 != aligned_pointer);
  97977. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  97978. pu = (FLAC__real*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  97979. if(0 == pu) {
  97980. return false;
  97981. }
  97982. else {
  97983. if(*unaligned_pointer != 0)
  97984. free(*unaligned_pointer);
  97985. *unaligned_pointer = pu;
  97986. *aligned_pointer = u.pa;
  97987. return true;
  97988. }
  97989. }
  97990. #endif
  97991. #endif
  97992. /*** End of inlined file: memory.c ***/
  97993. /*** Start of inlined file: stream_decoder.c ***/
  97994. /*** Start of inlined file: juce_FlacHeader.h ***/
  97995. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  97996. // tasks..
  97997. #define VERSION "1.2.1"
  97998. #define FLAC__NO_DLL 1
  97999. #if JUCE_MSVC
  98000. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  98001. #endif
  98002. #if JUCE_MAC
  98003. #define FLAC__SYS_DARWIN 1
  98004. #endif
  98005. /*** End of inlined file: juce_FlacHeader.h ***/
  98006. #if JUCE_USE_FLAC
  98007. #if HAVE_CONFIG_H
  98008. # include <config.h>
  98009. #endif
  98010. #if defined _MSC_VER || defined __MINGW32__
  98011. #include <io.h> /* for _setmode() */
  98012. #include <fcntl.h> /* for _O_BINARY */
  98013. #endif
  98014. #if defined __CYGWIN__ || defined __EMX__
  98015. #include <io.h> /* for setmode(), O_BINARY */
  98016. #include <fcntl.h> /* for _O_BINARY */
  98017. #endif
  98018. #include <stdio.h>
  98019. #include <stdlib.h> /* for malloc() */
  98020. #include <string.h> /* for memset/memcpy() */
  98021. #include <sys/stat.h> /* for stat() */
  98022. #include <sys/types.h> /* for off_t */
  98023. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  98024. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  98025. #define fseeko fseek
  98026. #define ftello ftell
  98027. #endif
  98028. #endif
  98029. /*** Start of inlined file: stream_decoder.h ***/
  98030. #ifndef FLAC__PROTECTED__STREAM_DECODER_H
  98031. #define FLAC__PROTECTED__STREAM_DECODER_H
  98032. #if FLAC__HAS_OGG
  98033. #include "include/private/ogg_decoder_aspect.h"
  98034. #endif
  98035. typedef struct FLAC__StreamDecoderProtected {
  98036. FLAC__StreamDecoderState state;
  98037. unsigned channels;
  98038. FLAC__ChannelAssignment channel_assignment;
  98039. unsigned bits_per_sample;
  98040. unsigned sample_rate; /* in Hz */
  98041. unsigned blocksize; /* in samples (per channel) */
  98042. FLAC__bool md5_checking; /* if true, generate MD5 signature of decoded data and compare against signature in the STREAMINFO metadata block */
  98043. #if FLAC__HAS_OGG
  98044. FLAC__OggDecoderAspect ogg_decoder_aspect;
  98045. #endif
  98046. } FLAC__StreamDecoderProtected;
  98047. /*
  98048. * return the number of input bytes consumed
  98049. */
  98050. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder);
  98051. #endif
  98052. /*** End of inlined file: stream_decoder.h ***/
  98053. #ifdef max
  98054. #undef max
  98055. #endif
  98056. #define max(a,b) ((a)>(b)?(a):(b))
  98057. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  98058. #ifdef _MSC_VER
  98059. #define FLAC__U64L(x) x
  98060. #else
  98061. #define FLAC__U64L(x) x##LLU
  98062. #endif
  98063. /* technically this should be in an "export.c" but this is convenient enough */
  98064. FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC =
  98065. #if FLAC__HAS_OGG
  98066. 1
  98067. #else
  98068. 0
  98069. #endif
  98070. ;
  98071. /***********************************************************************
  98072. *
  98073. * Private static data
  98074. *
  98075. ***********************************************************************/
  98076. static FLAC__byte ID3V2_TAG_[3] = { 'I', 'D', '3' };
  98077. /***********************************************************************
  98078. *
  98079. * Private class method prototypes
  98080. *
  98081. ***********************************************************************/
  98082. static void set_defaults_dec(FLAC__StreamDecoder *decoder);
  98083. static FILE *get_binary_stdin_(void);
  98084. static FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels);
  98085. static FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id);
  98086. static FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder);
  98087. static FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder);
  98088. static FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  98089. static FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  98090. static FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj);
  98091. static FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj);
  98092. static FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj);
  98093. static FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder);
  98094. static FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder);
  98095. static FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode);
  98096. static FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder);
  98097. static FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  98098. static FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  98099. static FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  98100. static FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  98101. static FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  98102. 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);
  98103. static FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder);
  98104. static FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data);
  98105. #if FLAC__HAS_OGG
  98106. static FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes);
  98107. static FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  98108. #endif
  98109. static FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[]);
  98110. static void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status);
  98111. static FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  98112. #if FLAC__HAS_OGG
  98113. static FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  98114. #endif
  98115. static FLAC__StreamDecoderReadStatus file_read_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  98116. static FLAC__StreamDecoderSeekStatus file_seek_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  98117. static FLAC__StreamDecoderTellStatus file_tell_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  98118. static FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  98119. static FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data);
  98120. /***********************************************************************
  98121. *
  98122. * Private class data
  98123. *
  98124. ***********************************************************************/
  98125. typedef struct FLAC__StreamDecoderPrivate {
  98126. #if FLAC__HAS_OGG
  98127. FLAC__bool is_ogg;
  98128. #endif
  98129. FLAC__StreamDecoderReadCallback read_callback;
  98130. FLAC__StreamDecoderSeekCallback seek_callback;
  98131. FLAC__StreamDecoderTellCallback tell_callback;
  98132. FLAC__StreamDecoderLengthCallback length_callback;
  98133. FLAC__StreamDecoderEofCallback eof_callback;
  98134. FLAC__StreamDecoderWriteCallback write_callback;
  98135. FLAC__StreamDecoderMetadataCallback metadata_callback;
  98136. FLAC__StreamDecoderErrorCallback error_callback;
  98137. /* generic 32-bit datapath: */
  98138. 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[]);
  98139. /* generic 64-bit datapath: */
  98140. 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[]);
  98141. /* for use when the signal is <= 16 bits-per-sample, or <= 15 bits-per-sample on a side channel (which requires 1 extra bit): */
  98142. 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[]);
  98143. /* 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: */
  98144. 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[]);
  98145. FLAC__bool (*local_bitreader_read_rice_signed_block)(FLAC__BitReader *br, int* vals, unsigned nvals, unsigned parameter);
  98146. void *client_data;
  98147. FILE *file; /* only used if FLAC__stream_decoder_init_file()/FLAC__stream_decoder_init_file() called, else NULL */
  98148. FLAC__BitReader *input;
  98149. FLAC__int32 *output[FLAC__MAX_CHANNELS];
  98150. FLAC__int32 *residual[FLAC__MAX_CHANNELS]; /* WATCHOUT: these are the aligned pointers; the real pointers that should be free()'d are residual_unaligned[] below */
  98151. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents[FLAC__MAX_CHANNELS];
  98152. unsigned output_capacity, output_channels;
  98153. FLAC__uint32 fixed_block_size, next_fixed_block_size;
  98154. FLAC__uint64 samples_decoded;
  98155. FLAC__bool has_stream_info, has_seek_table;
  98156. FLAC__StreamMetadata stream_info;
  98157. FLAC__StreamMetadata seek_table;
  98158. FLAC__bool metadata_filter[128]; /* MAGIC number 128 == total number of metadata block types == 1 << 7 */
  98159. FLAC__byte *metadata_filter_ids;
  98160. size_t metadata_filter_ids_count, metadata_filter_ids_capacity; /* units for both are IDs, not bytes */
  98161. FLAC__Frame frame;
  98162. FLAC__bool cached; /* true if there is a byte in lookahead */
  98163. FLAC__CPUInfo cpuinfo;
  98164. FLAC__byte header_warmup[2]; /* contains the sync code and reserved bits */
  98165. FLAC__byte lookahead; /* temp storage when we need to look ahead one byte in the stream */
  98166. /* unaligned (original) pointers to allocated data */
  98167. FLAC__int32 *residual_unaligned[FLAC__MAX_CHANNELS];
  98168. 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 */
  98169. FLAC__bool internal_reset_hack; /* used only during init() so we can call reset to set up the decoder without rewinding the input */
  98170. FLAC__bool is_seeking;
  98171. FLAC__MD5Context md5context;
  98172. FLAC__byte computed_md5sum[16]; /* this is the sum we computed from the decoded data */
  98173. /* (the rest of these are only used for seeking) */
  98174. FLAC__Frame last_frame; /* holds the info of the last frame we seeked to */
  98175. FLAC__uint64 first_frame_offset; /* hint to the seek routine of where in the stream the first audio frame starts */
  98176. FLAC__uint64 target_sample;
  98177. unsigned unparseable_frame_count; /* used to tell whether we're decoding a future version of FLAC or just got a bad sync */
  98178. #if FLAC__HAS_OGG
  98179. FLAC__bool got_a_frame; /* hack needed in Ogg FLAC seek routine to check when process_single() actually writes a frame */
  98180. #endif
  98181. } FLAC__StreamDecoderPrivate;
  98182. /***********************************************************************
  98183. *
  98184. * Public static class data
  98185. *
  98186. ***********************************************************************/
  98187. FLAC_API const char * const FLAC__StreamDecoderStateString[] = {
  98188. "FLAC__STREAM_DECODER_SEARCH_FOR_METADATA",
  98189. "FLAC__STREAM_DECODER_READ_METADATA",
  98190. "FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC",
  98191. "FLAC__STREAM_DECODER_READ_FRAME",
  98192. "FLAC__STREAM_DECODER_END_OF_STREAM",
  98193. "FLAC__STREAM_DECODER_OGG_ERROR",
  98194. "FLAC__STREAM_DECODER_SEEK_ERROR",
  98195. "FLAC__STREAM_DECODER_ABORTED",
  98196. "FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR",
  98197. "FLAC__STREAM_DECODER_UNINITIALIZED"
  98198. };
  98199. FLAC_API const char * const FLAC__StreamDecoderInitStatusString[] = {
  98200. "FLAC__STREAM_DECODER_INIT_STATUS_OK",
  98201. "FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  98202. "FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS",
  98203. "FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR",
  98204. "FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE",
  98205. "FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED"
  98206. };
  98207. FLAC_API const char * const FLAC__StreamDecoderReadStatusString[] = {
  98208. "FLAC__STREAM_DECODER_READ_STATUS_CONTINUE",
  98209. "FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM",
  98210. "FLAC__STREAM_DECODER_READ_STATUS_ABORT"
  98211. };
  98212. FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[] = {
  98213. "FLAC__STREAM_DECODER_SEEK_STATUS_OK",
  98214. "FLAC__STREAM_DECODER_SEEK_STATUS_ERROR",
  98215. "FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED"
  98216. };
  98217. FLAC_API const char * const FLAC__StreamDecoderTellStatusString[] = {
  98218. "FLAC__STREAM_DECODER_TELL_STATUS_OK",
  98219. "FLAC__STREAM_DECODER_TELL_STATUS_ERROR",
  98220. "FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED"
  98221. };
  98222. FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[] = {
  98223. "FLAC__STREAM_DECODER_LENGTH_STATUS_OK",
  98224. "FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR",
  98225. "FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED"
  98226. };
  98227. FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[] = {
  98228. "FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE",
  98229. "FLAC__STREAM_DECODER_WRITE_STATUS_ABORT"
  98230. };
  98231. FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[] = {
  98232. "FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC",
  98233. "FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER",
  98234. "FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH",
  98235. "FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM"
  98236. };
  98237. /***********************************************************************
  98238. *
  98239. * Class constructor/destructor
  98240. *
  98241. ***********************************************************************/
  98242. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void)
  98243. {
  98244. FLAC__StreamDecoder *decoder;
  98245. unsigned i;
  98246. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  98247. decoder = (FLAC__StreamDecoder*)calloc(1, sizeof(FLAC__StreamDecoder));
  98248. if(decoder == 0) {
  98249. return 0;
  98250. }
  98251. decoder->protected_ = (FLAC__StreamDecoderProtected*)calloc(1, sizeof(FLAC__StreamDecoderProtected));
  98252. if(decoder->protected_ == 0) {
  98253. free(decoder);
  98254. return 0;
  98255. }
  98256. decoder->private_ = (FLAC__StreamDecoderPrivate*)calloc(1, sizeof(FLAC__StreamDecoderPrivate));
  98257. if(decoder->private_ == 0) {
  98258. free(decoder->protected_);
  98259. free(decoder);
  98260. return 0;
  98261. }
  98262. decoder->private_->input = FLAC__bitreader_new();
  98263. if(decoder->private_->input == 0) {
  98264. free(decoder->private_);
  98265. free(decoder->protected_);
  98266. free(decoder);
  98267. return 0;
  98268. }
  98269. decoder->private_->metadata_filter_ids_capacity = 16;
  98270. if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)malloc((FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) * decoder->private_->metadata_filter_ids_capacity))) {
  98271. FLAC__bitreader_delete(decoder->private_->input);
  98272. free(decoder->private_);
  98273. free(decoder->protected_);
  98274. free(decoder);
  98275. return 0;
  98276. }
  98277. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  98278. decoder->private_->output[i] = 0;
  98279. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  98280. }
  98281. decoder->private_->output_capacity = 0;
  98282. decoder->private_->output_channels = 0;
  98283. decoder->private_->has_seek_table = false;
  98284. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  98285. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&decoder->private_->partitioned_rice_contents[i]);
  98286. decoder->private_->file = 0;
  98287. set_defaults_dec(decoder);
  98288. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  98289. return decoder;
  98290. }
  98291. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder)
  98292. {
  98293. unsigned i;
  98294. FLAC__ASSERT(0 != decoder);
  98295. FLAC__ASSERT(0 != decoder->protected_);
  98296. FLAC__ASSERT(0 != decoder->private_);
  98297. FLAC__ASSERT(0 != decoder->private_->input);
  98298. (void)FLAC__stream_decoder_finish(decoder);
  98299. if(0 != decoder->private_->metadata_filter_ids)
  98300. free(decoder->private_->metadata_filter_ids);
  98301. FLAC__bitreader_delete(decoder->private_->input);
  98302. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  98303. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&decoder->private_->partitioned_rice_contents[i]);
  98304. free(decoder->private_);
  98305. free(decoder->protected_);
  98306. free(decoder);
  98307. }
  98308. /***********************************************************************
  98309. *
  98310. * Public class methods
  98311. *
  98312. ***********************************************************************/
  98313. static FLAC__StreamDecoderInitStatus init_stream_internal_dec(
  98314. FLAC__StreamDecoder *decoder,
  98315. FLAC__StreamDecoderReadCallback read_callback,
  98316. FLAC__StreamDecoderSeekCallback seek_callback,
  98317. FLAC__StreamDecoderTellCallback tell_callback,
  98318. FLAC__StreamDecoderLengthCallback length_callback,
  98319. FLAC__StreamDecoderEofCallback eof_callback,
  98320. FLAC__StreamDecoderWriteCallback write_callback,
  98321. FLAC__StreamDecoderMetadataCallback metadata_callback,
  98322. FLAC__StreamDecoderErrorCallback error_callback,
  98323. void *client_data,
  98324. FLAC__bool is_ogg
  98325. )
  98326. {
  98327. FLAC__ASSERT(0 != decoder);
  98328. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  98329. return FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
  98330. #if !FLAC__HAS_OGG
  98331. if(is_ogg)
  98332. return FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  98333. #endif
  98334. if(
  98335. 0 == read_callback ||
  98336. 0 == write_callback ||
  98337. 0 == error_callback ||
  98338. (seek_callback && (0 == tell_callback || 0 == length_callback || 0 == eof_callback))
  98339. )
  98340. return FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
  98341. #if FLAC__HAS_OGG
  98342. decoder->private_->is_ogg = is_ogg;
  98343. if(is_ogg && !FLAC__ogg_decoder_aspect_init(&decoder->protected_->ogg_decoder_aspect))
  98344. return decoder->protected_->state = FLAC__STREAM_DECODER_OGG_ERROR;
  98345. #endif
  98346. /*
  98347. * get the CPU info and set the function pointers
  98348. */
  98349. FLAC__cpu_info(&decoder->private_->cpuinfo);
  98350. /* first default to the non-asm routines */
  98351. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal;
  98352. decoder->private_->local_lpc_restore_signal_64bit = FLAC__lpc_restore_signal_wide;
  98353. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal;
  98354. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal;
  98355. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block;
  98356. /* now override with asm where appropriate */
  98357. #ifndef FLAC__NO_ASM
  98358. if(decoder->private_->cpuinfo.use_asm) {
  98359. #ifdef FLAC__CPU_IA32
  98360. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  98361. #ifdef FLAC__HAS_NASM
  98362. #if 1 /*@@@@@@ OPT: not clearly faster, needs more testing */
  98363. if(decoder->private_->cpuinfo.data.ia32.bswap)
  98364. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap;
  98365. #endif
  98366. if(decoder->private_->cpuinfo.data.ia32.mmx) {
  98367. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  98368. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32_mmx;
  98369. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32_mmx;
  98370. }
  98371. else {
  98372. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  98373. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32;
  98374. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32;
  98375. }
  98376. #endif
  98377. #elif defined FLAC__CPU_PPC
  98378. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_PPC);
  98379. if(decoder->private_->cpuinfo.data.ppc.altivec) {
  98380. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ppc_altivec_16;
  98381. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ppc_altivec_16_order8;
  98382. }
  98383. #endif
  98384. }
  98385. #endif
  98386. /* from here on, errors are fatal */
  98387. if(!FLAC__bitreader_init(decoder->private_->input, decoder->private_->cpuinfo, read_callback_, decoder)) {
  98388. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  98389. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  98390. }
  98391. decoder->private_->read_callback = read_callback;
  98392. decoder->private_->seek_callback = seek_callback;
  98393. decoder->private_->tell_callback = tell_callback;
  98394. decoder->private_->length_callback = length_callback;
  98395. decoder->private_->eof_callback = eof_callback;
  98396. decoder->private_->write_callback = write_callback;
  98397. decoder->private_->metadata_callback = metadata_callback;
  98398. decoder->private_->error_callback = error_callback;
  98399. decoder->private_->client_data = client_data;
  98400. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  98401. decoder->private_->samples_decoded = 0;
  98402. decoder->private_->has_stream_info = false;
  98403. decoder->private_->cached = false;
  98404. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  98405. decoder->private_->is_seeking = false;
  98406. decoder->private_->internal_reset_hack = true; /* so the following reset does not try to rewind the input */
  98407. if(!FLAC__stream_decoder_reset(decoder)) {
  98408. /* above call sets the state for us */
  98409. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  98410. }
  98411. return FLAC__STREAM_DECODER_INIT_STATUS_OK;
  98412. }
  98413. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  98414. FLAC__StreamDecoder *decoder,
  98415. FLAC__StreamDecoderReadCallback read_callback,
  98416. FLAC__StreamDecoderSeekCallback seek_callback,
  98417. FLAC__StreamDecoderTellCallback tell_callback,
  98418. FLAC__StreamDecoderLengthCallback length_callback,
  98419. FLAC__StreamDecoderEofCallback eof_callback,
  98420. FLAC__StreamDecoderWriteCallback write_callback,
  98421. FLAC__StreamDecoderMetadataCallback metadata_callback,
  98422. FLAC__StreamDecoderErrorCallback error_callback,
  98423. void *client_data
  98424. )
  98425. {
  98426. return init_stream_internal_dec(
  98427. decoder,
  98428. read_callback,
  98429. seek_callback,
  98430. tell_callback,
  98431. length_callback,
  98432. eof_callback,
  98433. write_callback,
  98434. metadata_callback,
  98435. error_callback,
  98436. client_data,
  98437. /*is_ogg=*/false
  98438. );
  98439. }
  98440. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  98441. FLAC__StreamDecoder *decoder,
  98442. FLAC__StreamDecoderReadCallback read_callback,
  98443. FLAC__StreamDecoderSeekCallback seek_callback,
  98444. FLAC__StreamDecoderTellCallback tell_callback,
  98445. FLAC__StreamDecoderLengthCallback length_callback,
  98446. FLAC__StreamDecoderEofCallback eof_callback,
  98447. FLAC__StreamDecoderWriteCallback write_callback,
  98448. FLAC__StreamDecoderMetadataCallback metadata_callback,
  98449. FLAC__StreamDecoderErrorCallback error_callback,
  98450. void *client_data
  98451. )
  98452. {
  98453. return init_stream_internal_dec(
  98454. decoder,
  98455. read_callback,
  98456. seek_callback,
  98457. tell_callback,
  98458. length_callback,
  98459. eof_callback,
  98460. write_callback,
  98461. metadata_callback,
  98462. error_callback,
  98463. client_data,
  98464. /*is_ogg=*/true
  98465. );
  98466. }
  98467. static FLAC__StreamDecoderInitStatus init_FILE_internal_(
  98468. FLAC__StreamDecoder *decoder,
  98469. FILE *file,
  98470. FLAC__StreamDecoderWriteCallback write_callback,
  98471. FLAC__StreamDecoderMetadataCallback metadata_callback,
  98472. FLAC__StreamDecoderErrorCallback error_callback,
  98473. void *client_data,
  98474. FLAC__bool is_ogg
  98475. )
  98476. {
  98477. FLAC__ASSERT(0 != decoder);
  98478. FLAC__ASSERT(0 != file);
  98479. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  98480. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  98481. if(0 == write_callback || 0 == error_callback)
  98482. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  98483. /*
  98484. * To make sure that our file does not go unclosed after an error, we
  98485. * must assign the FILE pointer before any further error can occur in
  98486. * this routine.
  98487. */
  98488. if(file == stdin)
  98489. file = get_binary_stdin_(); /* just to be safe */
  98490. decoder->private_->file = file;
  98491. return init_stream_internal_dec(
  98492. decoder,
  98493. file_read_callback_dec,
  98494. decoder->private_->file == stdin? 0: file_seek_callback_dec,
  98495. decoder->private_->file == stdin? 0: file_tell_callback_dec,
  98496. decoder->private_->file == stdin? 0: file_length_callback_,
  98497. file_eof_callback_,
  98498. write_callback,
  98499. metadata_callback,
  98500. error_callback,
  98501. client_data,
  98502. is_ogg
  98503. );
  98504. }
  98505. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  98506. FLAC__StreamDecoder *decoder,
  98507. FILE *file,
  98508. FLAC__StreamDecoderWriteCallback write_callback,
  98509. FLAC__StreamDecoderMetadataCallback metadata_callback,
  98510. FLAC__StreamDecoderErrorCallback error_callback,
  98511. void *client_data
  98512. )
  98513. {
  98514. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  98515. }
  98516. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  98517. FLAC__StreamDecoder *decoder,
  98518. FILE *file,
  98519. FLAC__StreamDecoderWriteCallback write_callback,
  98520. FLAC__StreamDecoderMetadataCallback metadata_callback,
  98521. FLAC__StreamDecoderErrorCallback error_callback,
  98522. void *client_data
  98523. )
  98524. {
  98525. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  98526. }
  98527. static FLAC__StreamDecoderInitStatus init_file_internal_(
  98528. FLAC__StreamDecoder *decoder,
  98529. const char *filename,
  98530. FLAC__StreamDecoderWriteCallback write_callback,
  98531. FLAC__StreamDecoderMetadataCallback metadata_callback,
  98532. FLAC__StreamDecoderErrorCallback error_callback,
  98533. void *client_data,
  98534. FLAC__bool is_ogg
  98535. )
  98536. {
  98537. FILE *file;
  98538. FLAC__ASSERT(0 != decoder);
  98539. /*
  98540. * To make sure that our file does not go unclosed after an error, we
  98541. * have to do the same entrance checks here that are later performed
  98542. * in FLAC__stream_decoder_init_FILE() before the FILE* is assigned.
  98543. */
  98544. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  98545. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  98546. if(0 == write_callback || 0 == error_callback)
  98547. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  98548. file = filename? fopen(filename, "rb") : stdin;
  98549. if(0 == file)
  98550. return FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE;
  98551. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, is_ogg);
  98552. }
  98553. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  98554. FLAC__StreamDecoder *decoder,
  98555. const char *filename,
  98556. FLAC__StreamDecoderWriteCallback write_callback,
  98557. FLAC__StreamDecoderMetadataCallback metadata_callback,
  98558. FLAC__StreamDecoderErrorCallback error_callback,
  98559. void *client_data
  98560. )
  98561. {
  98562. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  98563. }
  98564. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  98565. FLAC__StreamDecoder *decoder,
  98566. const char *filename,
  98567. FLAC__StreamDecoderWriteCallback write_callback,
  98568. FLAC__StreamDecoderMetadataCallback metadata_callback,
  98569. FLAC__StreamDecoderErrorCallback error_callback,
  98570. void *client_data
  98571. )
  98572. {
  98573. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  98574. }
  98575. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder)
  98576. {
  98577. FLAC__bool md5_failed = false;
  98578. unsigned i;
  98579. FLAC__ASSERT(0 != decoder);
  98580. FLAC__ASSERT(0 != decoder->private_);
  98581. FLAC__ASSERT(0 != decoder->protected_);
  98582. if(decoder->protected_->state == FLAC__STREAM_DECODER_UNINITIALIZED)
  98583. return true;
  98584. /* see the comment in FLAC__seekable_stream_decoder_reset() as to why we
  98585. * always call FLAC__MD5Final()
  98586. */
  98587. FLAC__MD5Final(decoder->private_->computed_md5sum, &decoder->private_->md5context);
  98588. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  98589. free(decoder->private_->seek_table.data.seek_table.points);
  98590. decoder->private_->seek_table.data.seek_table.points = 0;
  98591. decoder->private_->has_seek_table = false;
  98592. }
  98593. FLAC__bitreader_free(decoder->private_->input);
  98594. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  98595. /* WATCHOUT:
  98596. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  98597. * output arrays have a buffer of up to 3 zeroes in front
  98598. * (at negative indices) for alignment purposes; we use 4
  98599. * to keep the data well-aligned.
  98600. */
  98601. if(0 != decoder->private_->output[i]) {
  98602. free(decoder->private_->output[i]-4);
  98603. decoder->private_->output[i] = 0;
  98604. }
  98605. if(0 != decoder->private_->residual_unaligned[i]) {
  98606. free(decoder->private_->residual_unaligned[i]);
  98607. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  98608. }
  98609. }
  98610. decoder->private_->output_capacity = 0;
  98611. decoder->private_->output_channels = 0;
  98612. #if FLAC__HAS_OGG
  98613. if(decoder->private_->is_ogg)
  98614. FLAC__ogg_decoder_aspect_finish(&decoder->protected_->ogg_decoder_aspect);
  98615. #endif
  98616. if(0 != decoder->private_->file) {
  98617. if(decoder->private_->file != stdin)
  98618. fclose(decoder->private_->file);
  98619. decoder->private_->file = 0;
  98620. }
  98621. if(decoder->private_->do_md5_checking) {
  98622. if(memcmp(decoder->private_->stream_info.data.stream_info.md5sum, decoder->private_->computed_md5sum, 16))
  98623. md5_failed = true;
  98624. }
  98625. decoder->private_->is_seeking = false;
  98626. set_defaults_dec(decoder);
  98627. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  98628. return !md5_failed;
  98629. }
  98630. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long value)
  98631. {
  98632. FLAC__ASSERT(0 != decoder);
  98633. FLAC__ASSERT(0 != decoder->private_);
  98634. FLAC__ASSERT(0 != decoder->protected_);
  98635. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  98636. return false;
  98637. #if FLAC__HAS_OGG
  98638. /* can't check decoder->private_->is_ogg since that's not set until init time */
  98639. FLAC__ogg_decoder_aspect_set_serial_number(&decoder->protected_->ogg_decoder_aspect, value);
  98640. return true;
  98641. #else
  98642. (void)value;
  98643. return false;
  98644. #endif
  98645. }
  98646. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value)
  98647. {
  98648. FLAC__ASSERT(0 != decoder);
  98649. FLAC__ASSERT(0 != decoder->protected_);
  98650. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  98651. return false;
  98652. decoder->protected_->md5_checking = value;
  98653. return true;
  98654. }
  98655. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  98656. {
  98657. FLAC__ASSERT(0 != decoder);
  98658. FLAC__ASSERT(0 != decoder->private_);
  98659. FLAC__ASSERT(0 != decoder->protected_);
  98660. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  98661. /* double protection */
  98662. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  98663. return false;
  98664. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  98665. return false;
  98666. decoder->private_->metadata_filter[type] = true;
  98667. if(type == FLAC__METADATA_TYPE_APPLICATION)
  98668. decoder->private_->metadata_filter_ids_count = 0;
  98669. return true;
  98670. }
  98671. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  98672. {
  98673. FLAC__ASSERT(0 != decoder);
  98674. FLAC__ASSERT(0 != decoder->private_);
  98675. FLAC__ASSERT(0 != decoder->protected_);
  98676. FLAC__ASSERT(0 != id);
  98677. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  98678. return false;
  98679. if(decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  98680. return true;
  98681. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  98682. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  98683. 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))) {
  98684. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  98685. return false;
  98686. }
  98687. decoder->private_->metadata_filter_ids_capacity *= 2;
  98688. }
  98689. 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));
  98690. decoder->private_->metadata_filter_ids_count++;
  98691. return true;
  98692. }
  98693. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder)
  98694. {
  98695. unsigned i;
  98696. FLAC__ASSERT(0 != decoder);
  98697. FLAC__ASSERT(0 != decoder->private_);
  98698. FLAC__ASSERT(0 != decoder->protected_);
  98699. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  98700. return false;
  98701. for(i = 0; i < sizeof(decoder->private_->metadata_filter) / sizeof(decoder->private_->metadata_filter[0]); i++)
  98702. decoder->private_->metadata_filter[i] = true;
  98703. decoder->private_->metadata_filter_ids_count = 0;
  98704. return true;
  98705. }
  98706. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  98707. {
  98708. FLAC__ASSERT(0 != decoder);
  98709. FLAC__ASSERT(0 != decoder->private_);
  98710. FLAC__ASSERT(0 != decoder->protected_);
  98711. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  98712. /* double protection */
  98713. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  98714. return false;
  98715. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  98716. return false;
  98717. decoder->private_->metadata_filter[type] = false;
  98718. if(type == FLAC__METADATA_TYPE_APPLICATION)
  98719. decoder->private_->metadata_filter_ids_count = 0;
  98720. return true;
  98721. }
  98722. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  98723. {
  98724. FLAC__ASSERT(0 != decoder);
  98725. FLAC__ASSERT(0 != decoder->private_);
  98726. FLAC__ASSERT(0 != decoder->protected_);
  98727. FLAC__ASSERT(0 != id);
  98728. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  98729. return false;
  98730. if(!decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  98731. return true;
  98732. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  98733. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  98734. 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))) {
  98735. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  98736. return false;
  98737. }
  98738. decoder->private_->metadata_filter_ids_capacity *= 2;
  98739. }
  98740. 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));
  98741. decoder->private_->metadata_filter_ids_count++;
  98742. return true;
  98743. }
  98744. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder)
  98745. {
  98746. FLAC__ASSERT(0 != decoder);
  98747. FLAC__ASSERT(0 != decoder->private_);
  98748. FLAC__ASSERT(0 != decoder->protected_);
  98749. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  98750. return false;
  98751. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  98752. decoder->private_->metadata_filter_ids_count = 0;
  98753. return true;
  98754. }
  98755. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder)
  98756. {
  98757. FLAC__ASSERT(0 != decoder);
  98758. FLAC__ASSERT(0 != decoder->protected_);
  98759. return decoder->protected_->state;
  98760. }
  98761. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder)
  98762. {
  98763. return FLAC__StreamDecoderStateString[decoder->protected_->state];
  98764. }
  98765. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder)
  98766. {
  98767. FLAC__ASSERT(0 != decoder);
  98768. FLAC__ASSERT(0 != decoder->protected_);
  98769. return decoder->protected_->md5_checking;
  98770. }
  98771. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder)
  98772. {
  98773. FLAC__ASSERT(0 != decoder);
  98774. FLAC__ASSERT(0 != decoder->protected_);
  98775. return decoder->private_->has_stream_info? decoder->private_->stream_info.data.stream_info.total_samples : 0;
  98776. }
  98777. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder)
  98778. {
  98779. FLAC__ASSERT(0 != decoder);
  98780. FLAC__ASSERT(0 != decoder->protected_);
  98781. return decoder->protected_->channels;
  98782. }
  98783. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder)
  98784. {
  98785. FLAC__ASSERT(0 != decoder);
  98786. FLAC__ASSERT(0 != decoder->protected_);
  98787. return decoder->protected_->channel_assignment;
  98788. }
  98789. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder)
  98790. {
  98791. FLAC__ASSERT(0 != decoder);
  98792. FLAC__ASSERT(0 != decoder->protected_);
  98793. return decoder->protected_->bits_per_sample;
  98794. }
  98795. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder)
  98796. {
  98797. FLAC__ASSERT(0 != decoder);
  98798. FLAC__ASSERT(0 != decoder->protected_);
  98799. return decoder->protected_->sample_rate;
  98800. }
  98801. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder)
  98802. {
  98803. FLAC__ASSERT(0 != decoder);
  98804. FLAC__ASSERT(0 != decoder->protected_);
  98805. return decoder->protected_->blocksize;
  98806. }
  98807. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position)
  98808. {
  98809. FLAC__ASSERT(0 != decoder);
  98810. FLAC__ASSERT(0 != decoder->private_);
  98811. FLAC__ASSERT(0 != position);
  98812. #if FLAC__HAS_OGG
  98813. if(decoder->private_->is_ogg)
  98814. return false;
  98815. #endif
  98816. if(0 == decoder->private_->tell_callback)
  98817. return false;
  98818. if(decoder->private_->tell_callback(decoder, position, decoder->private_->client_data) != FLAC__STREAM_DECODER_TELL_STATUS_OK)
  98819. return false;
  98820. /* should never happen since all FLAC frames and metadata blocks are byte aligned, but check just in case */
  98821. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input))
  98822. return false;
  98823. FLAC__ASSERT(*position >= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder));
  98824. *position -= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder);
  98825. return true;
  98826. }
  98827. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder)
  98828. {
  98829. FLAC__ASSERT(0 != decoder);
  98830. FLAC__ASSERT(0 != decoder->private_);
  98831. FLAC__ASSERT(0 != decoder->protected_);
  98832. decoder->private_->samples_decoded = 0;
  98833. decoder->private_->do_md5_checking = false;
  98834. #if FLAC__HAS_OGG
  98835. if(decoder->private_->is_ogg)
  98836. FLAC__ogg_decoder_aspect_flush(&decoder->protected_->ogg_decoder_aspect);
  98837. #endif
  98838. if(!FLAC__bitreader_clear(decoder->private_->input)) {
  98839. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  98840. return false;
  98841. }
  98842. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  98843. return true;
  98844. }
  98845. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder)
  98846. {
  98847. FLAC__ASSERT(0 != decoder);
  98848. FLAC__ASSERT(0 != decoder->private_);
  98849. FLAC__ASSERT(0 != decoder->protected_);
  98850. if(!FLAC__stream_decoder_flush(decoder)) {
  98851. /* above call sets the state for us */
  98852. return false;
  98853. }
  98854. #if FLAC__HAS_OGG
  98855. /*@@@ could go in !internal_reset_hack block below */
  98856. if(decoder->private_->is_ogg)
  98857. FLAC__ogg_decoder_aspect_reset(&decoder->protected_->ogg_decoder_aspect);
  98858. #endif
  98859. /* Rewind if necessary. If FLAC__stream_decoder_init() is calling us,
  98860. * (internal_reset_hack) don't try to rewind since we are already at
  98861. * the beginning of the stream and don't want to fail if the input is
  98862. * not seekable.
  98863. */
  98864. if(!decoder->private_->internal_reset_hack) {
  98865. if(decoder->private_->file == stdin)
  98866. return false; /* can't rewind stdin, reset fails */
  98867. if(decoder->private_->seek_callback && decoder->private_->seek_callback(decoder, 0, decoder->private_->client_data) == FLAC__STREAM_DECODER_SEEK_STATUS_ERROR)
  98868. return false; /* seekable and seek fails, reset fails */
  98869. }
  98870. else
  98871. decoder->private_->internal_reset_hack = false;
  98872. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_METADATA;
  98873. decoder->private_->has_stream_info = false;
  98874. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  98875. free(decoder->private_->seek_table.data.seek_table.points);
  98876. decoder->private_->seek_table.data.seek_table.points = 0;
  98877. decoder->private_->has_seek_table = false;
  98878. }
  98879. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  98880. /*
  98881. * This goes in reset() and not flush() because according to the spec, a
  98882. * fixed-blocksize stream must stay that way through the whole stream.
  98883. */
  98884. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  98885. /* We initialize the FLAC__MD5Context even though we may never use it. This
  98886. * is because md5 checking may be turned on to start and then turned off if
  98887. * a seek occurs. So we init the context here and finalize it in
  98888. * FLAC__stream_decoder_finish() to make sure things are always cleaned up
  98889. * properly.
  98890. */
  98891. FLAC__MD5Init(&decoder->private_->md5context);
  98892. decoder->private_->first_frame_offset = 0;
  98893. decoder->private_->unparseable_frame_count = 0;
  98894. return true;
  98895. }
  98896. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder)
  98897. {
  98898. FLAC__bool got_a_frame;
  98899. FLAC__ASSERT(0 != decoder);
  98900. FLAC__ASSERT(0 != decoder->protected_);
  98901. while(1) {
  98902. switch(decoder->protected_->state) {
  98903. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  98904. if(!find_metadata_(decoder))
  98905. return false; /* above function sets the status for us */
  98906. break;
  98907. case FLAC__STREAM_DECODER_READ_METADATA:
  98908. if(!read_metadata_(decoder))
  98909. return false; /* above function sets the status for us */
  98910. else
  98911. return true;
  98912. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  98913. if(!frame_sync_(decoder))
  98914. return true; /* above function sets the status for us */
  98915. break;
  98916. case FLAC__STREAM_DECODER_READ_FRAME:
  98917. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/true))
  98918. return false; /* above function sets the status for us */
  98919. if(got_a_frame)
  98920. return true; /* above function sets the status for us */
  98921. break;
  98922. case FLAC__STREAM_DECODER_END_OF_STREAM:
  98923. case FLAC__STREAM_DECODER_ABORTED:
  98924. return true;
  98925. default:
  98926. FLAC__ASSERT(0);
  98927. return false;
  98928. }
  98929. }
  98930. }
  98931. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder)
  98932. {
  98933. FLAC__ASSERT(0 != decoder);
  98934. FLAC__ASSERT(0 != decoder->protected_);
  98935. while(1) {
  98936. switch(decoder->protected_->state) {
  98937. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  98938. if(!find_metadata_(decoder))
  98939. return false; /* above function sets the status for us */
  98940. break;
  98941. case FLAC__STREAM_DECODER_READ_METADATA:
  98942. if(!read_metadata_(decoder))
  98943. return false; /* above function sets the status for us */
  98944. break;
  98945. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  98946. case FLAC__STREAM_DECODER_READ_FRAME:
  98947. case FLAC__STREAM_DECODER_END_OF_STREAM:
  98948. case FLAC__STREAM_DECODER_ABORTED:
  98949. return true;
  98950. default:
  98951. FLAC__ASSERT(0);
  98952. return false;
  98953. }
  98954. }
  98955. }
  98956. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder)
  98957. {
  98958. FLAC__bool dummy;
  98959. FLAC__ASSERT(0 != decoder);
  98960. FLAC__ASSERT(0 != decoder->protected_);
  98961. while(1) {
  98962. switch(decoder->protected_->state) {
  98963. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  98964. if(!find_metadata_(decoder))
  98965. return false; /* above function sets the status for us */
  98966. break;
  98967. case FLAC__STREAM_DECODER_READ_METADATA:
  98968. if(!read_metadata_(decoder))
  98969. return false; /* above function sets the status for us */
  98970. break;
  98971. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  98972. if(!frame_sync_(decoder))
  98973. return true; /* above function sets the status for us */
  98974. break;
  98975. case FLAC__STREAM_DECODER_READ_FRAME:
  98976. if(!read_frame_(decoder, &dummy, /*do_full_decode=*/true))
  98977. return false; /* above function sets the status for us */
  98978. break;
  98979. case FLAC__STREAM_DECODER_END_OF_STREAM:
  98980. case FLAC__STREAM_DECODER_ABORTED:
  98981. return true;
  98982. default:
  98983. FLAC__ASSERT(0);
  98984. return false;
  98985. }
  98986. }
  98987. }
  98988. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder)
  98989. {
  98990. FLAC__bool got_a_frame;
  98991. FLAC__ASSERT(0 != decoder);
  98992. FLAC__ASSERT(0 != decoder->protected_);
  98993. while(1) {
  98994. switch(decoder->protected_->state) {
  98995. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  98996. case FLAC__STREAM_DECODER_READ_METADATA:
  98997. return false; /* above function sets the status for us */
  98998. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  98999. if(!frame_sync_(decoder))
  99000. return true; /* above function sets the status for us */
  99001. break;
  99002. case FLAC__STREAM_DECODER_READ_FRAME:
  99003. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/false))
  99004. return false; /* above function sets the status for us */
  99005. if(got_a_frame)
  99006. return true; /* above function sets the status for us */
  99007. break;
  99008. case FLAC__STREAM_DECODER_END_OF_STREAM:
  99009. case FLAC__STREAM_DECODER_ABORTED:
  99010. return true;
  99011. default:
  99012. FLAC__ASSERT(0);
  99013. return false;
  99014. }
  99015. }
  99016. }
  99017. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample)
  99018. {
  99019. FLAC__uint64 length;
  99020. FLAC__ASSERT(0 != decoder);
  99021. if(
  99022. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA &&
  99023. decoder->protected_->state != FLAC__STREAM_DECODER_READ_METADATA &&
  99024. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC &&
  99025. decoder->protected_->state != FLAC__STREAM_DECODER_READ_FRAME &&
  99026. decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM
  99027. )
  99028. return false;
  99029. if(0 == decoder->private_->seek_callback)
  99030. return false;
  99031. FLAC__ASSERT(decoder->private_->seek_callback);
  99032. FLAC__ASSERT(decoder->private_->tell_callback);
  99033. FLAC__ASSERT(decoder->private_->length_callback);
  99034. FLAC__ASSERT(decoder->private_->eof_callback);
  99035. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder))
  99036. return false;
  99037. decoder->private_->is_seeking = true;
  99038. /* turn off md5 checking if a seek is attempted */
  99039. decoder->private_->do_md5_checking = false;
  99040. /* 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) */
  99041. if(decoder->private_->length_callback(decoder, &length, decoder->private_->client_data) != FLAC__STREAM_DECODER_LENGTH_STATUS_OK) {
  99042. decoder->private_->is_seeking = false;
  99043. return false;
  99044. }
  99045. /* if we haven't finished processing the metadata yet, do that so we have the STREAMINFO, SEEK_TABLE, and first_frame_offset */
  99046. if(
  99047. decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_METADATA ||
  99048. decoder->protected_->state == FLAC__STREAM_DECODER_READ_METADATA
  99049. ) {
  99050. if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder)) {
  99051. /* above call sets the state for us */
  99052. decoder->private_->is_seeking = false;
  99053. return false;
  99054. }
  99055. /* check this again in case we didn't know total_samples the first time */
  99056. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder)) {
  99057. decoder->private_->is_seeking = false;
  99058. return false;
  99059. }
  99060. }
  99061. {
  99062. const FLAC__bool ok =
  99063. #if FLAC__HAS_OGG
  99064. decoder->private_->is_ogg?
  99065. seek_to_absolute_sample_ogg_(decoder, length, sample) :
  99066. #endif
  99067. seek_to_absolute_sample_(decoder, length, sample)
  99068. ;
  99069. decoder->private_->is_seeking = false;
  99070. return ok;
  99071. }
  99072. }
  99073. /***********************************************************************
  99074. *
  99075. * Protected class methods
  99076. *
  99077. ***********************************************************************/
  99078. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder)
  99079. {
  99080. FLAC__ASSERT(0 != decoder);
  99081. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  99082. FLAC__ASSERT(!(FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) & 7));
  99083. return FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) / 8;
  99084. }
  99085. /***********************************************************************
  99086. *
  99087. * Private class methods
  99088. *
  99089. ***********************************************************************/
  99090. void set_defaults_dec(FLAC__StreamDecoder *decoder)
  99091. {
  99092. #if FLAC__HAS_OGG
  99093. decoder->private_->is_ogg = false;
  99094. #endif
  99095. decoder->private_->read_callback = 0;
  99096. decoder->private_->seek_callback = 0;
  99097. decoder->private_->tell_callback = 0;
  99098. decoder->private_->length_callback = 0;
  99099. decoder->private_->eof_callback = 0;
  99100. decoder->private_->write_callback = 0;
  99101. decoder->private_->metadata_callback = 0;
  99102. decoder->private_->error_callback = 0;
  99103. decoder->private_->client_data = 0;
  99104. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  99105. decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] = true;
  99106. decoder->private_->metadata_filter_ids_count = 0;
  99107. decoder->protected_->md5_checking = false;
  99108. #if FLAC__HAS_OGG
  99109. FLAC__ogg_decoder_aspect_set_defaults(&decoder->protected_->ogg_decoder_aspect);
  99110. #endif
  99111. }
  99112. /*
  99113. * This will forcibly set stdin to binary mode (for OSes that require it)
  99114. */
  99115. FILE *get_binary_stdin_(void)
  99116. {
  99117. /* if something breaks here it is probably due to the presence or
  99118. * absence of an underscore before the identifiers 'setmode',
  99119. * 'fileno', and/or 'O_BINARY'; check your system header files.
  99120. */
  99121. #if defined _MSC_VER || defined __MINGW32__
  99122. _setmode(_fileno(stdin), _O_BINARY);
  99123. #elif defined __CYGWIN__
  99124. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  99125. setmode(_fileno(stdin), _O_BINARY);
  99126. #elif defined __EMX__
  99127. setmode(fileno(stdin), O_BINARY);
  99128. #endif
  99129. return stdin;
  99130. }
  99131. FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels)
  99132. {
  99133. unsigned i;
  99134. FLAC__int32 *tmp;
  99135. if(size <= decoder->private_->output_capacity && channels <= decoder->private_->output_channels)
  99136. return true;
  99137. /* simply using realloc() is not practical because the number of channels may change mid-stream */
  99138. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99139. if(0 != decoder->private_->output[i]) {
  99140. free(decoder->private_->output[i]-4);
  99141. decoder->private_->output[i] = 0;
  99142. }
  99143. if(0 != decoder->private_->residual_unaligned[i]) {
  99144. free(decoder->private_->residual_unaligned[i]);
  99145. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  99146. }
  99147. }
  99148. for(i = 0; i < channels; i++) {
  99149. /* WATCHOUT:
  99150. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  99151. * output arrays have a buffer of up to 3 zeroes in front
  99152. * (at negative indices) for alignment purposes; we use 4
  99153. * to keep the data well-aligned.
  99154. */
  99155. tmp = (FLAC__int32*)safe_malloc_muladd2_(sizeof(FLAC__int32), /*times (*/size, /*+*/4/*)*/);
  99156. if(tmp == 0) {
  99157. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99158. return false;
  99159. }
  99160. memset(tmp, 0, sizeof(FLAC__int32)*4);
  99161. decoder->private_->output[i] = tmp + 4;
  99162. /* WATCHOUT:
  99163. * minimum of quadword alignment for PPC vector optimizations is REQUIRED:
  99164. */
  99165. if(!FLAC__memory_alloc_aligned_int32_array(size, &decoder->private_->residual_unaligned[i], &decoder->private_->residual[i])) {
  99166. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99167. return false;
  99168. }
  99169. }
  99170. decoder->private_->output_capacity = size;
  99171. decoder->private_->output_channels = channels;
  99172. return true;
  99173. }
  99174. FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id)
  99175. {
  99176. size_t i;
  99177. FLAC__ASSERT(0 != decoder);
  99178. FLAC__ASSERT(0 != decoder->private_);
  99179. for(i = 0; i < decoder->private_->metadata_filter_ids_count; i++)
  99180. if(0 == memcmp(decoder->private_->metadata_filter_ids + i * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8)))
  99181. return true;
  99182. return false;
  99183. }
  99184. FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder)
  99185. {
  99186. FLAC__uint32 x;
  99187. unsigned i, id_;
  99188. FLAC__bool first = true;
  99189. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  99190. for(i = id_ = 0; i < 4; ) {
  99191. if(decoder->private_->cached) {
  99192. x = (FLAC__uint32)decoder->private_->lookahead;
  99193. decoder->private_->cached = false;
  99194. }
  99195. else {
  99196. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  99197. return false; /* read_callback_ sets the state for us */
  99198. }
  99199. if(x == FLAC__STREAM_SYNC_STRING[i]) {
  99200. first = true;
  99201. i++;
  99202. id_ = 0;
  99203. continue;
  99204. }
  99205. if(x == ID3V2_TAG_[id_]) {
  99206. id_++;
  99207. i = 0;
  99208. if(id_ == 3) {
  99209. if(!skip_id3v2_tag_(decoder))
  99210. return false; /* skip_id3v2_tag_ sets the state for us */
  99211. }
  99212. continue;
  99213. }
  99214. id_ = 0;
  99215. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  99216. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  99217. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  99218. return false; /* read_callback_ sets the state for us */
  99219. /* 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 */
  99220. /* else we have to check if the second byte is the end of a sync code */
  99221. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  99222. decoder->private_->lookahead = (FLAC__byte)x;
  99223. decoder->private_->cached = true;
  99224. }
  99225. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  99226. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  99227. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  99228. return true;
  99229. }
  99230. }
  99231. i = 0;
  99232. if(first) {
  99233. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  99234. first = false;
  99235. }
  99236. }
  99237. decoder->protected_->state = FLAC__STREAM_DECODER_READ_METADATA;
  99238. return true;
  99239. }
  99240. FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder)
  99241. {
  99242. FLAC__bool is_last;
  99243. FLAC__uint32 i, x, type, length;
  99244. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  99245. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_IS_LAST_LEN))
  99246. return false; /* read_callback_ sets the state for us */
  99247. is_last = x? true : false;
  99248. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &type, FLAC__STREAM_METADATA_TYPE_LEN))
  99249. return false; /* read_callback_ sets the state for us */
  99250. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &length, FLAC__STREAM_METADATA_LENGTH_LEN))
  99251. return false; /* read_callback_ sets the state for us */
  99252. if(type == FLAC__METADATA_TYPE_STREAMINFO) {
  99253. if(!read_metadata_streaminfo_(decoder, is_last, length))
  99254. return false;
  99255. decoder->private_->has_stream_info = true;
  99256. 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))
  99257. decoder->private_->do_md5_checking = false;
  99258. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] && decoder->private_->metadata_callback)
  99259. decoder->private_->metadata_callback(decoder, &decoder->private_->stream_info, decoder->private_->client_data);
  99260. }
  99261. else if(type == FLAC__METADATA_TYPE_SEEKTABLE) {
  99262. if(!read_metadata_seektable_(decoder, is_last, length))
  99263. return false;
  99264. decoder->private_->has_seek_table = true;
  99265. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_SEEKTABLE] && decoder->private_->metadata_callback)
  99266. decoder->private_->metadata_callback(decoder, &decoder->private_->seek_table, decoder->private_->client_data);
  99267. }
  99268. else {
  99269. FLAC__bool skip_it = !decoder->private_->metadata_filter[type];
  99270. unsigned real_length = length;
  99271. FLAC__StreamMetadata block;
  99272. block.is_last = is_last;
  99273. block.type = (FLAC__MetadataType)type;
  99274. block.length = length;
  99275. if(type == FLAC__METADATA_TYPE_APPLICATION) {
  99276. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8))
  99277. return false; /* read_callback_ sets the state for us */
  99278. if(real_length < FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) { /* underflow check */
  99279. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;/*@@@@@@ maybe wrong error? need to resync?*/
  99280. return false;
  99281. }
  99282. real_length -= FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8;
  99283. if(decoder->private_->metadata_filter_ids_count > 0 && has_id_filtered_(decoder, block.data.application.id))
  99284. skip_it = !skip_it;
  99285. }
  99286. if(skip_it) {
  99287. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  99288. return false; /* read_callback_ sets the state for us */
  99289. }
  99290. else {
  99291. switch(type) {
  99292. case FLAC__METADATA_TYPE_PADDING:
  99293. /* skip the padding bytes */
  99294. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  99295. return false; /* read_callback_ sets the state for us */
  99296. break;
  99297. case FLAC__METADATA_TYPE_APPLICATION:
  99298. /* remember, we read the ID already */
  99299. if(real_length > 0) {
  99300. if(0 == (block.data.application.data = (FLAC__byte*)malloc(real_length))) {
  99301. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99302. return false;
  99303. }
  99304. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.data, real_length))
  99305. return false; /* read_callback_ sets the state for us */
  99306. }
  99307. else
  99308. block.data.application.data = 0;
  99309. break;
  99310. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  99311. if(!read_metadata_vorbiscomment_(decoder, &block.data.vorbis_comment))
  99312. return false;
  99313. break;
  99314. case FLAC__METADATA_TYPE_CUESHEET:
  99315. if(!read_metadata_cuesheet_(decoder, &block.data.cue_sheet))
  99316. return false;
  99317. break;
  99318. case FLAC__METADATA_TYPE_PICTURE:
  99319. if(!read_metadata_picture_(decoder, &block.data.picture))
  99320. return false;
  99321. break;
  99322. case FLAC__METADATA_TYPE_STREAMINFO:
  99323. case FLAC__METADATA_TYPE_SEEKTABLE:
  99324. FLAC__ASSERT(0);
  99325. break;
  99326. default:
  99327. if(real_length > 0) {
  99328. if(0 == (block.data.unknown.data = (FLAC__byte*)malloc(real_length))) {
  99329. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99330. return false;
  99331. }
  99332. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.unknown.data, real_length))
  99333. return false; /* read_callback_ sets the state for us */
  99334. }
  99335. else
  99336. block.data.unknown.data = 0;
  99337. break;
  99338. }
  99339. if(!decoder->private_->is_seeking && decoder->private_->metadata_callback)
  99340. decoder->private_->metadata_callback(decoder, &block, decoder->private_->client_data);
  99341. /* now we have to free any malloc()ed data in the block */
  99342. switch(type) {
  99343. case FLAC__METADATA_TYPE_PADDING:
  99344. break;
  99345. case FLAC__METADATA_TYPE_APPLICATION:
  99346. if(0 != block.data.application.data)
  99347. free(block.data.application.data);
  99348. break;
  99349. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  99350. if(0 != block.data.vorbis_comment.vendor_string.entry)
  99351. free(block.data.vorbis_comment.vendor_string.entry);
  99352. if(block.data.vorbis_comment.num_comments > 0)
  99353. for(i = 0; i < block.data.vorbis_comment.num_comments; i++)
  99354. if(0 != block.data.vorbis_comment.comments[i].entry)
  99355. free(block.data.vorbis_comment.comments[i].entry);
  99356. if(0 != block.data.vorbis_comment.comments)
  99357. free(block.data.vorbis_comment.comments);
  99358. break;
  99359. case FLAC__METADATA_TYPE_CUESHEET:
  99360. if(block.data.cue_sheet.num_tracks > 0)
  99361. for(i = 0; i < block.data.cue_sheet.num_tracks; i++)
  99362. if(0 != block.data.cue_sheet.tracks[i].indices)
  99363. free(block.data.cue_sheet.tracks[i].indices);
  99364. if(0 != block.data.cue_sheet.tracks)
  99365. free(block.data.cue_sheet.tracks);
  99366. break;
  99367. case FLAC__METADATA_TYPE_PICTURE:
  99368. if(0 != block.data.picture.mime_type)
  99369. free(block.data.picture.mime_type);
  99370. if(0 != block.data.picture.description)
  99371. free(block.data.picture.description);
  99372. if(0 != block.data.picture.data)
  99373. free(block.data.picture.data);
  99374. break;
  99375. case FLAC__METADATA_TYPE_STREAMINFO:
  99376. case FLAC__METADATA_TYPE_SEEKTABLE:
  99377. FLAC__ASSERT(0);
  99378. default:
  99379. if(0 != block.data.unknown.data)
  99380. free(block.data.unknown.data);
  99381. break;
  99382. }
  99383. }
  99384. }
  99385. if(is_last) {
  99386. /* if this fails, it's OK, it's just a hint for the seek routine */
  99387. if(!FLAC__stream_decoder_get_decode_position(decoder, &decoder->private_->first_frame_offset))
  99388. decoder->private_->first_frame_offset = 0;
  99389. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  99390. }
  99391. return true;
  99392. }
  99393. FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  99394. {
  99395. FLAC__uint32 x;
  99396. unsigned bits, used_bits = 0;
  99397. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  99398. decoder->private_->stream_info.type = FLAC__METADATA_TYPE_STREAMINFO;
  99399. decoder->private_->stream_info.is_last = is_last;
  99400. decoder->private_->stream_info.length = length;
  99401. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN;
  99402. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, bits))
  99403. return false; /* read_callback_ sets the state for us */
  99404. decoder->private_->stream_info.data.stream_info.min_blocksize = x;
  99405. used_bits += bits;
  99406. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN;
  99407. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  99408. return false; /* read_callback_ sets the state for us */
  99409. decoder->private_->stream_info.data.stream_info.max_blocksize = x;
  99410. used_bits += bits;
  99411. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN;
  99412. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  99413. return false; /* read_callback_ sets the state for us */
  99414. decoder->private_->stream_info.data.stream_info.min_framesize = x;
  99415. used_bits += bits;
  99416. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN;
  99417. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  99418. return false; /* read_callback_ sets the state for us */
  99419. decoder->private_->stream_info.data.stream_info.max_framesize = x;
  99420. used_bits += bits;
  99421. bits = FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN;
  99422. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  99423. return false; /* read_callback_ sets the state for us */
  99424. decoder->private_->stream_info.data.stream_info.sample_rate = x;
  99425. used_bits += bits;
  99426. bits = FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN;
  99427. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  99428. return false; /* read_callback_ sets the state for us */
  99429. decoder->private_->stream_info.data.stream_info.channels = x+1;
  99430. used_bits += bits;
  99431. bits = FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN;
  99432. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  99433. return false; /* read_callback_ sets the state for us */
  99434. decoder->private_->stream_info.data.stream_info.bits_per_sample = x+1;
  99435. used_bits += bits;
  99436. bits = FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN;
  99437. 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))
  99438. return false; /* read_callback_ sets the state for us */
  99439. used_bits += bits;
  99440. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, decoder->private_->stream_info.data.stream_info.md5sum, 16))
  99441. return false; /* read_callback_ sets the state for us */
  99442. used_bits += 16*8;
  99443. /* skip the rest of the block */
  99444. FLAC__ASSERT(used_bits % 8 == 0);
  99445. length -= (used_bits / 8);
  99446. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  99447. return false; /* read_callback_ sets the state for us */
  99448. return true;
  99449. }
  99450. FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  99451. {
  99452. FLAC__uint32 i, x;
  99453. FLAC__uint64 xx;
  99454. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  99455. decoder->private_->seek_table.type = FLAC__METADATA_TYPE_SEEKTABLE;
  99456. decoder->private_->seek_table.is_last = is_last;
  99457. decoder->private_->seek_table.length = length;
  99458. decoder->private_->seek_table.data.seek_table.num_points = length / FLAC__STREAM_METADATA_SEEKPOINT_LENGTH;
  99459. /* use realloc since we may pass through here several times (e.g. after seeking) */
  99460. 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)))) {
  99461. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99462. return false;
  99463. }
  99464. for(i = 0; i < decoder->private_->seek_table.data.seek_table.num_points; i++) {
  99465. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  99466. return false; /* read_callback_ sets the state for us */
  99467. decoder->private_->seek_table.data.seek_table.points[i].sample_number = xx;
  99468. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  99469. return false; /* read_callback_ sets the state for us */
  99470. decoder->private_->seek_table.data.seek_table.points[i].stream_offset = xx;
  99471. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  99472. return false; /* read_callback_ sets the state for us */
  99473. decoder->private_->seek_table.data.seek_table.points[i].frame_samples = x;
  99474. }
  99475. length -= (decoder->private_->seek_table.data.seek_table.num_points * FLAC__STREAM_METADATA_SEEKPOINT_LENGTH);
  99476. /* if there is a partial point left, skip over it */
  99477. if(length > 0) {
  99478. /*@@@ do a send_error_to_client_() here? there's an argument for either way */
  99479. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  99480. return false; /* read_callback_ sets the state for us */
  99481. }
  99482. return true;
  99483. }
  99484. FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj)
  99485. {
  99486. FLAC__uint32 i;
  99487. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  99488. /* read vendor string */
  99489. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  99490. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->vendor_string.length))
  99491. return false; /* read_callback_ sets the state for us */
  99492. if(obj->vendor_string.length > 0) {
  99493. if(0 == (obj->vendor_string.entry = (FLAC__byte*)safe_malloc_add_2op_(obj->vendor_string.length, /*+*/1))) {
  99494. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99495. return false;
  99496. }
  99497. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->vendor_string.entry, obj->vendor_string.length))
  99498. return false; /* read_callback_ sets the state for us */
  99499. obj->vendor_string.entry[obj->vendor_string.length] = '\0';
  99500. }
  99501. else
  99502. obj->vendor_string.entry = 0;
  99503. /* read num comments */
  99504. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN == 32);
  99505. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->num_comments))
  99506. return false; /* read_callback_ sets the state for us */
  99507. /* read comments */
  99508. if(obj->num_comments > 0) {
  99509. if(0 == (obj->comments = (FLAC__StreamMetadata_VorbisComment_Entry*)safe_malloc_mul_2op_(obj->num_comments, /*times*/sizeof(FLAC__StreamMetadata_VorbisComment_Entry)))) {
  99510. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99511. return false;
  99512. }
  99513. for(i = 0; i < obj->num_comments; i++) {
  99514. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  99515. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->comments[i].length))
  99516. return false; /* read_callback_ sets the state for us */
  99517. if(obj->comments[i].length > 0) {
  99518. if(0 == (obj->comments[i].entry = (FLAC__byte*)safe_malloc_add_2op_(obj->comments[i].length, /*+*/1))) {
  99519. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99520. return false;
  99521. }
  99522. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->comments[i].entry, obj->comments[i].length))
  99523. return false; /* read_callback_ sets the state for us */
  99524. obj->comments[i].entry[obj->comments[i].length] = '\0';
  99525. }
  99526. else
  99527. obj->comments[i].entry = 0;
  99528. }
  99529. }
  99530. else {
  99531. obj->comments = 0;
  99532. }
  99533. return true;
  99534. }
  99535. FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj)
  99536. {
  99537. FLAC__uint32 i, j, x;
  99538. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  99539. memset(obj, 0, sizeof(FLAC__StreamMetadata_CueSheet));
  99540. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  99541. 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))
  99542. return false; /* read_callback_ sets the state for us */
  99543. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &obj->lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  99544. return false; /* read_callback_ sets the state for us */
  99545. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  99546. return false; /* read_callback_ sets the state for us */
  99547. obj->is_cd = x? true : false;
  99548. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  99549. return false; /* read_callback_ sets the state for us */
  99550. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  99551. return false; /* read_callback_ sets the state for us */
  99552. obj->num_tracks = x;
  99553. if(obj->num_tracks > 0) {
  99554. if(0 == (obj->tracks = (FLAC__StreamMetadata_CueSheet_Track*)safe_calloc_(obj->num_tracks, sizeof(FLAC__StreamMetadata_CueSheet_Track)))) {
  99555. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99556. return false;
  99557. }
  99558. for(i = 0; i < obj->num_tracks; i++) {
  99559. FLAC__StreamMetadata_CueSheet_Track *track = &obj->tracks[i];
  99560. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  99561. return false; /* read_callback_ sets the state for us */
  99562. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  99563. return false; /* read_callback_ sets the state for us */
  99564. track->number = (FLAC__byte)x;
  99565. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  99566. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  99567. return false; /* read_callback_ sets the state for us */
  99568. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  99569. return false; /* read_callback_ sets the state for us */
  99570. track->type = x;
  99571. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  99572. return false; /* read_callback_ sets the state for us */
  99573. track->pre_emphasis = x;
  99574. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  99575. return false; /* read_callback_ sets the state for us */
  99576. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  99577. return false; /* read_callback_ sets the state for us */
  99578. track->num_indices = (FLAC__byte)x;
  99579. if(track->num_indices > 0) {
  99580. if(0 == (track->indices = (FLAC__StreamMetadata_CueSheet_Index*)safe_calloc_(track->num_indices, sizeof(FLAC__StreamMetadata_CueSheet_Index)))) {
  99581. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99582. return false;
  99583. }
  99584. for(j = 0; j < track->num_indices; j++) {
  99585. FLAC__StreamMetadata_CueSheet_Index *index = &track->indices[j];
  99586. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  99587. return false; /* read_callback_ sets the state for us */
  99588. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  99589. return false; /* read_callback_ sets the state for us */
  99590. index->number = (FLAC__byte)x;
  99591. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  99592. return false; /* read_callback_ sets the state for us */
  99593. }
  99594. }
  99595. }
  99596. }
  99597. return true;
  99598. }
  99599. FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj)
  99600. {
  99601. FLAC__uint32 x;
  99602. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  99603. /* read type */
  99604. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  99605. return false; /* read_callback_ sets the state for us */
  99606. obj->type = (FLAC__StreamMetadata_Picture_Type) x;
  99607. /* read MIME type */
  99608. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  99609. return false; /* read_callback_ sets the state for us */
  99610. if(0 == (obj->mime_type = (char*)safe_malloc_add_2op_(x, /*+*/1))) {
  99611. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99612. return false;
  99613. }
  99614. if(x > 0) {
  99615. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)obj->mime_type, x))
  99616. return false; /* read_callback_ sets the state for us */
  99617. }
  99618. obj->mime_type[x] = '\0';
  99619. /* read description */
  99620. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  99621. return false; /* read_callback_ sets the state for us */
  99622. if(0 == (obj->description = (FLAC__byte*)safe_malloc_add_2op_(x, /*+*/1))) {
  99623. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99624. return false;
  99625. }
  99626. if(x > 0) {
  99627. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->description, x))
  99628. return false; /* read_callback_ sets the state for us */
  99629. }
  99630. obj->description[x] = '\0';
  99631. /* read width */
  99632. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  99633. return false; /* read_callback_ sets the state for us */
  99634. /* read height */
  99635. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  99636. return false; /* read_callback_ sets the state for us */
  99637. /* read depth */
  99638. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  99639. return false; /* read_callback_ sets the state for us */
  99640. /* read colors */
  99641. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  99642. return false; /* read_callback_ sets the state for us */
  99643. /* read data */
  99644. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &(obj->data_length), FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  99645. return false; /* read_callback_ sets the state for us */
  99646. if(0 == (obj->data = (FLAC__byte*)safe_malloc_(obj->data_length))) {
  99647. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99648. return false;
  99649. }
  99650. if(obj->data_length > 0) {
  99651. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->data, obj->data_length))
  99652. return false; /* read_callback_ sets the state for us */
  99653. }
  99654. return true;
  99655. }
  99656. FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder)
  99657. {
  99658. FLAC__uint32 x;
  99659. unsigned i, skip;
  99660. /* skip the version and flags bytes */
  99661. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 24))
  99662. return false; /* read_callback_ sets the state for us */
  99663. /* get the size (in bytes) to skip */
  99664. skip = 0;
  99665. for(i = 0; i < 4; i++) {
  99666. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  99667. return false; /* read_callback_ sets the state for us */
  99668. skip <<= 7;
  99669. skip |= (x & 0x7f);
  99670. }
  99671. /* skip the rest of the tag */
  99672. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, skip))
  99673. return false; /* read_callback_ sets the state for us */
  99674. return true;
  99675. }
  99676. FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder)
  99677. {
  99678. FLAC__uint32 x;
  99679. FLAC__bool first = true;
  99680. /* If we know the total number of samples in the stream, stop if we've read that many. */
  99681. /* This will stop us, for example, from wasting time trying to sync on an ID3V1 tag. */
  99682. if(FLAC__stream_decoder_get_total_samples(decoder) > 0) {
  99683. if(decoder->private_->samples_decoded >= FLAC__stream_decoder_get_total_samples(decoder)) {
  99684. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  99685. return true;
  99686. }
  99687. }
  99688. /* make sure we're byte aligned */
  99689. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  99690. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  99691. return false; /* read_callback_ sets the state for us */
  99692. }
  99693. while(1) {
  99694. if(decoder->private_->cached) {
  99695. x = (FLAC__uint32)decoder->private_->lookahead;
  99696. decoder->private_->cached = false;
  99697. }
  99698. else {
  99699. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  99700. return false; /* read_callback_ sets the state for us */
  99701. }
  99702. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  99703. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  99704. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  99705. return false; /* read_callback_ sets the state for us */
  99706. /* 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 */
  99707. /* else we have to check if the second byte is the end of a sync code */
  99708. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  99709. decoder->private_->lookahead = (FLAC__byte)x;
  99710. decoder->private_->cached = true;
  99711. }
  99712. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  99713. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  99714. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  99715. return true;
  99716. }
  99717. }
  99718. if(first) {
  99719. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  99720. first = false;
  99721. }
  99722. }
  99723. return true;
  99724. }
  99725. FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode)
  99726. {
  99727. unsigned channel;
  99728. unsigned i;
  99729. FLAC__int32 mid, side;
  99730. unsigned frame_crc; /* the one we calculate from the input stream */
  99731. FLAC__uint32 x;
  99732. *got_a_frame = false;
  99733. /* init the CRC */
  99734. frame_crc = 0;
  99735. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[0], frame_crc);
  99736. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[1], frame_crc);
  99737. FLAC__bitreader_reset_read_crc16(decoder->private_->input, (FLAC__uint16)frame_crc);
  99738. if(!read_frame_header_(decoder))
  99739. return false;
  99740. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means we didn't sync on a valid header */
  99741. return true;
  99742. if(!allocate_output_(decoder, decoder->private_->frame.header.blocksize, decoder->private_->frame.header.channels))
  99743. return false;
  99744. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  99745. /*
  99746. * first figure the correct bits-per-sample of the subframe
  99747. */
  99748. unsigned bps = decoder->private_->frame.header.bits_per_sample;
  99749. switch(decoder->private_->frame.header.channel_assignment) {
  99750. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  99751. /* no adjustment needed */
  99752. break;
  99753. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  99754. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  99755. if(channel == 1)
  99756. bps++;
  99757. break;
  99758. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  99759. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  99760. if(channel == 0)
  99761. bps++;
  99762. break;
  99763. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  99764. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  99765. if(channel == 1)
  99766. bps++;
  99767. break;
  99768. default:
  99769. FLAC__ASSERT(0);
  99770. }
  99771. /*
  99772. * now read it
  99773. */
  99774. if(!read_subframe_(decoder, channel, bps, do_full_decode))
  99775. return false;
  99776. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  99777. return true;
  99778. }
  99779. if(!read_zero_padding_(decoder))
  99780. return false;
  99781. 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) */
  99782. return true;
  99783. /*
  99784. * Read the frame CRC-16 from the footer and check
  99785. */
  99786. frame_crc = FLAC__bitreader_get_read_crc16(decoder->private_->input);
  99787. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__FRAME_FOOTER_CRC_LEN))
  99788. return false; /* read_callback_ sets the state for us */
  99789. if(frame_crc == x) {
  99790. if(do_full_decode) {
  99791. /* Undo any special channel coding */
  99792. switch(decoder->private_->frame.header.channel_assignment) {
  99793. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  99794. /* do nothing */
  99795. break;
  99796. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  99797. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  99798. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  99799. decoder->private_->output[1][i] = decoder->private_->output[0][i] - decoder->private_->output[1][i];
  99800. break;
  99801. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  99802. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  99803. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  99804. decoder->private_->output[0][i] += decoder->private_->output[1][i];
  99805. break;
  99806. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  99807. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  99808. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  99809. #if 1
  99810. mid = decoder->private_->output[0][i];
  99811. side = decoder->private_->output[1][i];
  99812. mid <<= 1;
  99813. mid |= (side & 1); /* i.e. if 'side' is odd... */
  99814. decoder->private_->output[0][i] = (mid + side) >> 1;
  99815. decoder->private_->output[1][i] = (mid - side) >> 1;
  99816. #else
  99817. /* OPT: without 'side' temp variable */
  99818. mid = (decoder->private_->output[0][i] << 1) | (decoder->private_->output[1][i] & 1); /* i.e. if 'side' is odd... */
  99819. decoder->private_->output[0][i] = (mid + decoder->private_->output[1][i]) >> 1;
  99820. decoder->private_->output[1][i] = (mid - decoder->private_->output[1][i]) >> 1;
  99821. #endif
  99822. }
  99823. break;
  99824. default:
  99825. FLAC__ASSERT(0);
  99826. break;
  99827. }
  99828. }
  99829. }
  99830. else {
  99831. /* Bad frame, emit error and zero the output signal */
  99832. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH);
  99833. if(do_full_decode) {
  99834. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  99835. memset(decoder->private_->output[channel], 0, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  99836. }
  99837. }
  99838. }
  99839. *got_a_frame = true;
  99840. /* we wait to update fixed_block_size until here, when we're sure we've got a proper frame and hence a correct blocksize */
  99841. if(decoder->private_->next_fixed_block_size)
  99842. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size;
  99843. /* put the latest values into the public section of the decoder instance */
  99844. decoder->protected_->channels = decoder->private_->frame.header.channels;
  99845. decoder->protected_->channel_assignment = decoder->private_->frame.header.channel_assignment;
  99846. decoder->protected_->bits_per_sample = decoder->private_->frame.header.bits_per_sample;
  99847. decoder->protected_->sample_rate = decoder->private_->frame.header.sample_rate;
  99848. decoder->protected_->blocksize = decoder->private_->frame.header.blocksize;
  99849. FLAC__ASSERT(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  99850. decoder->private_->samples_decoded = decoder->private_->frame.header.number.sample_number + decoder->private_->frame.header.blocksize;
  99851. /* write it */
  99852. if(do_full_decode) {
  99853. if(write_audio_frame_to_client_(decoder, &decoder->private_->frame, (const FLAC__int32 * const *)decoder->private_->output) != FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE)
  99854. return false;
  99855. }
  99856. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  99857. return true;
  99858. }
  99859. FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder)
  99860. {
  99861. FLAC__uint32 x;
  99862. FLAC__uint64 xx;
  99863. unsigned i, blocksize_hint = 0, sample_rate_hint = 0;
  99864. FLAC__byte crc8, raw_header[16]; /* MAGIC NUMBER based on the maximum frame header size, including CRC */
  99865. unsigned raw_header_len;
  99866. FLAC__bool is_unparseable = false;
  99867. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  99868. /* init the raw header with the saved bits from synchronization */
  99869. raw_header[0] = decoder->private_->header_warmup[0];
  99870. raw_header[1] = decoder->private_->header_warmup[1];
  99871. raw_header_len = 2;
  99872. /* check to make sure that reserved bit is 0 */
  99873. if(raw_header[1] & 0x02) /* MAGIC NUMBER */
  99874. is_unparseable = true;
  99875. /*
  99876. * Note that along the way as we read the header, we look for a sync
  99877. * code inside. If we find one it would indicate that our original
  99878. * sync was bad since there cannot be a sync code in a valid header.
  99879. *
  99880. * Three kinds of things can go wrong when reading the frame header:
  99881. * 1) We may have sync'ed incorrectly and not landed on a frame header.
  99882. * If we don't find a sync code, it can end up looking like we read
  99883. * a valid but unparseable header, until getting to the frame header
  99884. * CRC. Even then we could get a false positive on the CRC.
  99885. * 2) We may have sync'ed correctly but on an unparseable frame (from a
  99886. * future encoder).
  99887. * 3) We may be on a damaged frame which appears valid but unparseable.
  99888. *
  99889. * For all these reasons, we try and read a complete frame header as
  99890. * long as it seems valid, even if unparseable, up until the frame
  99891. * header CRC.
  99892. */
  99893. /*
  99894. * read in the raw header as bytes so we can CRC it, and parse it on the way
  99895. */
  99896. for(i = 0; i < 2; i++) {
  99897. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  99898. return false; /* read_callback_ sets the state for us */
  99899. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  99900. /* if we get here it means our original sync was erroneous since the sync code cannot appear in the header */
  99901. decoder->private_->lookahead = (FLAC__byte)x;
  99902. decoder->private_->cached = true;
  99903. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  99904. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  99905. return true;
  99906. }
  99907. raw_header[raw_header_len++] = (FLAC__byte)x;
  99908. }
  99909. switch(x = raw_header[2] >> 4) {
  99910. case 0:
  99911. is_unparseable = true;
  99912. break;
  99913. case 1:
  99914. decoder->private_->frame.header.blocksize = 192;
  99915. break;
  99916. case 2:
  99917. case 3:
  99918. case 4:
  99919. case 5:
  99920. decoder->private_->frame.header.blocksize = 576 << (x-2);
  99921. break;
  99922. case 6:
  99923. case 7:
  99924. blocksize_hint = x;
  99925. break;
  99926. case 8:
  99927. case 9:
  99928. case 10:
  99929. case 11:
  99930. case 12:
  99931. case 13:
  99932. case 14:
  99933. case 15:
  99934. decoder->private_->frame.header.blocksize = 256 << (x-8);
  99935. break;
  99936. default:
  99937. FLAC__ASSERT(0);
  99938. break;
  99939. }
  99940. switch(x = raw_header[2] & 0x0f) {
  99941. case 0:
  99942. if(decoder->private_->has_stream_info)
  99943. decoder->private_->frame.header.sample_rate = decoder->private_->stream_info.data.stream_info.sample_rate;
  99944. else
  99945. is_unparseable = true;
  99946. break;
  99947. case 1:
  99948. decoder->private_->frame.header.sample_rate = 88200;
  99949. break;
  99950. case 2:
  99951. decoder->private_->frame.header.sample_rate = 176400;
  99952. break;
  99953. case 3:
  99954. decoder->private_->frame.header.sample_rate = 192000;
  99955. break;
  99956. case 4:
  99957. decoder->private_->frame.header.sample_rate = 8000;
  99958. break;
  99959. case 5:
  99960. decoder->private_->frame.header.sample_rate = 16000;
  99961. break;
  99962. case 6:
  99963. decoder->private_->frame.header.sample_rate = 22050;
  99964. break;
  99965. case 7:
  99966. decoder->private_->frame.header.sample_rate = 24000;
  99967. break;
  99968. case 8:
  99969. decoder->private_->frame.header.sample_rate = 32000;
  99970. break;
  99971. case 9:
  99972. decoder->private_->frame.header.sample_rate = 44100;
  99973. break;
  99974. case 10:
  99975. decoder->private_->frame.header.sample_rate = 48000;
  99976. break;
  99977. case 11:
  99978. decoder->private_->frame.header.sample_rate = 96000;
  99979. break;
  99980. case 12:
  99981. case 13:
  99982. case 14:
  99983. sample_rate_hint = x;
  99984. break;
  99985. case 15:
  99986. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  99987. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  99988. return true;
  99989. default:
  99990. FLAC__ASSERT(0);
  99991. }
  99992. x = (unsigned)(raw_header[3] >> 4);
  99993. if(x & 8) {
  99994. decoder->private_->frame.header.channels = 2;
  99995. switch(x & 7) {
  99996. case 0:
  99997. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE;
  99998. break;
  99999. case 1:
  100000. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE;
  100001. break;
  100002. case 2:
  100003. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_MID_SIDE;
  100004. break;
  100005. default:
  100006. is_unparseable = true;
  100007. break;
  100008. }
  100009. }
  100010. else {
  100011. decoder->private_->frame.header.channels = (unsigned)x + 1;
  100012. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  100013. }
  100014. switch(x = (unsigned)(raw_header[3] & 0x0e) >> 1) {
  100015. case 0:
  100016. if(decoder->private_->has_stream_info)
  100017. decoder->private_->frame.header.bits_per_sample = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  100018. else
  100019. is_unparseable = true;
  100020. break;
  100021. case 1:
  100022. decoder->private_->frame.header.bits_per_sample = 8;
  100023. break;
  100024. case 2:
  100025. decoder->private_->frame.header.bits_per_sample = 12;
  100026. break;
  100027. case 4:
  100028. decoder->private_->frame.header.bits_per_sample = 16;
  100029. break;
  100030. case 5:
  100031. decoder->private_->frame.header.bits_per_sample = 20;
  100032. break;
  100033. case 6:
  100034. decoder->private_->frame.header.bits_per_sample = 24;
  100035. break;
  100036. case 3:
  100037. case 7:
  100038. is_unparseable = true;
  100039. break;
  100040. default:
  100041. FLAC__ASSERT(0);
  100042. break;
  100043. }
  100044. /* check to make sure that reserved bit is 0 */
  100045. if(raw_header[3] & 0x01) /* MAGIC NUMBER */
  100046. is_unparseable = true;
  100047. /* read the frame's starting sample number (or frame number as the case may be) */
  100048. if(
  100049. raw_header[1] & 0x01 ||
  100050. /*@@@ 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 */
  100051. (decoder->private_->has_stream_info && decoder->private_->stream_info.data.stream_info.min_blocksize != decoder->private_->stream_info.data.stream_info.max_blocksize)
  100052. ) { /* variable blocksize */
  100053. if(!FLAC__bitreader_read_utf8_uint64(decoder->private_->input, &xx, raw_header, &raw_header_len))
  100054. return false; /* read_callback_ sets the state for us */
  100055. if(xx == FLAC__U64L(0xffffffffffffffff)) { /* i.e. non-UTF8 code... */
  100056. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  100057. decoder->private_->cached = true;
  100058. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  100059. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100060. return true;
  100061. }
  100062. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  100063. decoder->private_->frame.header.number.sample_number = xx;
  100064. }
  100065. else { /* fixed blocksize */
  100066. if(!FLAC__bitreader_read_utf8_uint32(decoder->private_->input, &x, raw_header, &raw_header_len))
  100067. return false; /* read_callback_ sets the state for us */
  100068. if(x == 0xffffffff) { /* i.e. non-UTF8 code... */
  100069. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  100070. decoder->private_->cached = true;
  100071. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  100072. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100073. return true;
  100074. }
  100075. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  100076. decoder->private_->frame.header.number.frame_number = x;
  100077. }
  100078. if(blocksize_hint) {
  100079. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100080. return false; /* read_callback_ sets the state for us */
  100081. raw_header[raw_header_len++] = (FLAC__byte)x;
  100082. if(blocksize_hint == 7) {
  100083. FLAC__uint32 _x;
  100084. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  100085. return false; /* read_callback_ sets the state for us */
  100086. raw_header[raw_header_len++] = (FLAC__byte)_x;
  100087. x = (x << 8) | _x;
  100088. }
  100089. decoder->private_->frame.header.blocksize = x+1;
  100090. }
  100091. if(sample_rate_hint) {
  100092. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100093. return false; /* read_callback_ sets the state for us */
  100094. raw_header[raw_header_len++] = (FLAC__byte)x;
  100095. if(sample_rate_hint != 12) {
  100096. FLAC__uint32 _x;
  100097. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  100098. return false; /* read_callback_ sets the state for us */
  100099. raw_header[raw_header_len++] = (FLAC__byte)_x;
  100100. x = (x << 8) | _x;
  100101. }
  100102. if(sample_rate_hint == 12)
  100103. decoder->private_->frame.header.sample_rate = x*1000;
  100104. else if(sample_rate_hint == 13)
  100105. decoder->private_->frame.header.sample_rate = x;
  100106. else
  100107. decoder->private_->frame.header.sample_rate = x*10;
  100108. }
  100109. /* read the CRC-8 byte */
  100110. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100111. return false; /* read_callback_ sets the state for us */
  100112. crc8 = (FLAC__byte)x;
  100113. if(FLAC__crc8(raw_header, raw_header_len) != crc8) {
  100114. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  100115. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100116. return true;
  100117. }
  100118. /* calculate the sample number from the frame number if needed */
  100119. decoder->private_->next_fixed_block_size = 0;
  100120. if(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  100121. x = decoder->private_->frame.header.number.frame_number;
  100122. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  100123. if(decoder->private_->fixed_block_size)
  100124. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->fixed_block_size * (FLAC__uint64)x;
  100125. else if(decoder->private_->has_stream_info) {
  100126. if(decoder->private_->stream_info.data.stream_info.min_blocksize == decoder->private_->stream_info.data.stream_info.max_blocksize) {
  100127. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->stream_info.data.stream_info.min_blocksize * (FLAC__uint64)x;
  100128. decoder->private_->next_fixed_block_size = decoder->private_->stream_info.data.stream_info.max_blocksize;
  100129. }
  100130. else
  100131. is_unparseable = true;
  100132. }
  100133. else if(x == 0) {
  100134. decoder->private_->frame.header.number.sample_number = 0;
  100135. decoder->private_->next_fixed_block_size = decoder->private_->frame.header.blocksize;
  100136. }
  100137. else {
  100138. /* can only get here if the stream has invalid frame numbering and no STREAMINFO, so assume it's not the last (possibly short) frame */
  100139. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->frame.header.blocksize * (FLAC__uint64)x;
  100140. }
  100141. }
  100142. if(is_unparseable) {
  100143. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  100144. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100145. return true;
  100146. }
  100147. return true;
  100148. }
  100149. FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  100150. {
  100151. FLAC__uint32 x;
  100152. FLAC__bool wasted_bits;
  100153. unsigned i;
  100154. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8)) /* MAGIC NUMBER */
  100155. return false; /* read_callback_ sets the state for us */
  100156. wasted_bits = (x & 1);
  100157. x &= 0xfe;
  100158. if(wasted_bits) {
  100159. unsigned u;
  100160. if(!FLAC__bitreader_read_unary_unsigned(decoder->private_->input, &u))
  100161. return false; /* read_callback_ sets the state for us */
  100162. decoder->private_->frame.subframes[channel].wasted_bits = u+1;
  100163. bps -= decoder->private_->frame.subframes[channel].wasted_bits;
  100164. }
  100165. else
  100166. decoder->private_->frame.subframes[channel].wasted_bits = 0;
  100167. /*
  100168. * Lots of magic numbers here
  100169. */
  100170. if(x & 0x80) {
  100171. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100172. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100173. return true;
  100174. }
  100175. else if(x == 0) {
  100176. if(!read_subframe_constant_(decoder, channel, bps, do_full_decode))
  100177. return false;
  100178. }
  100179. else if(x == 2) {
  100180. if(!read_subframe_verbatim_(decoder, channel, bps, do_full_decode))
  100181. return false;
  100182. }
  100183. else if(x < 16) {
  100184. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  100185. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100186. return true;
  100187. }
  100188. else if(x <= 24) {
  100189. if(!read_subframe_fixed_(decoder, channel, bps, (x>>1)&7, do_full_decode))
  100190. return false;
  100191. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  100192. return true;
  100193. }
  100194. else if(x < 64) {
  100195. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  100196. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100197. return true;
  100198. }
  100199. else {
  100200. if(!read_subframe_lpc_(decoder, channel, bps, ((x>>1)&31)+1, do_full_decode))
  100201. return false;
  100202. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  100203. return true;
  100204. }
  100205. if(wasted_bits && do_full_decode) {
  100206. x = decoder->private_->frame.subframes[channel].wasted_bits;
  100207. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  100208. decoder->private_->output[channel][i] <<= x;
  100209. }
  100210. return true;
  100211. }
  100212. FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  100213. {
  100214. FLAC__Subframe_Constant *subframe = &decoder->private_->frame.subframes[channel].data.constant;
  100215. FLAC__int32 x;
  100216. unsigned i;
  100217. FLAC__int32 *output = decoder->private_->output[channel];
  100218. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_CONSTANT;
  100219. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  100220. return false; /* read_callback_ sets the state for us */
  100221. subframe->value = x;
  100222. /* decode the subframe */
  100223. if(do_full_decode) {
  100224. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  100225. output[i] = x;
  100226. }
  100227. return true;
  100228. }
  100229. FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  100230. {
  100231. FLAC__Subframe_Fixed *subframe = &decoder->private_->frame.subframes[channel].data.fixed;
  100232. FLAC__int32 i32;
  100233. FLAC__uint32 u32;
  100234. unsigned u;
  100235. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_FIXED;
  100236. subframe->residual = decoder->private_->residual[channel];
  100237. subframe->order = order;
  100238. /* read warm-up samples */
  100239. for(u = 0; u < order; u++) {
  100240. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  100241. return false; /* read_callback_ sets the state for us */
  100242. subframe->warmup[u] = i32;
  100243. }
  100244. /* read entropy coding method info */
  100245. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  100246. return false; /* read_callback_ sets the state for us */
  100247. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  100248. switch(subframe->entropy_coding_method.type) {
  100249. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  100250. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  100251. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  100252. return false; /* read_callback_ sets the state for us */
  100253. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  100254. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  100255. break;
  100256. default:
  100257. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  100258. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100259. return true;
  100260. }
  100261. /* read residual */
  100262. switch(subframe->entropy_coding_method.type) {
  100263. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  100264. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  100265. 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))
  100266. return false;
  100267. break;
  100268. default:
  100269. FLAC__ASSERT(0);
  100270. }
  100271. /* decode the subframe */
  100272. if(do_full_decode) {
  100273. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  100274. FLAC__fixed_restore_signal(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, order, decoder->private_->output[channel]+order);
  100275. }
  100276. return true;
  100277. }
  100278. FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  100279. {
  100280. FLAC__Subframe_LPC *subframe = &decoder->private_->frame.subframes[channel].data.lpc;
  100281. FLAC__int32 i32;
  100282. FLAC__uint32 u32;
  100283. unsigned u;
  100284. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_LPC;
  100285. subframe->residual = decoder->private_->residual[channel];
  100286. subframe->order = order;
  100287. /* read warm-up samples */
  100288. for(u = 0; u < order; u++) {
  100289. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  100290. return false; /* read_callback_ sets the state for us */
  100291. subframe->warmup[u] = i32;
  100292. }
  100293. /* read qlp coeff precision */
  100294. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  100295. return false; /* read_callback_ sets the state for us */
  100296. if(u32 == (1u << FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN) - 1) {
  100297. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100298. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100299. return true;
  100300. }
  100301. subframe->qlp_coeff_precision = u32+1;
  100302. /* read qlp shift */
  100303. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  100304. return false; /* read_callback_ sets the state for us */
  100305. subframe->quantization_level = i32;
  100306. /* read quantized lp coefficiencts */
  100307. for(u = 0; u < order; u++) {
  100308. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, subframe->qlp_coeff_precision))
  100309. return false; /* read_callback_ sets the state for us */
  100310. subframe->qlp_coeff[u] = i32;
  100311. }
  100312. /* read entropy coding method info */
  100313. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  100314. return false; /* read_callback_ sets the state for us */
  100315. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  100316. switch(subframe->entropy_coding_method.type) {
  100317. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  100318. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  100319. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  100320. return false; /* read_callback_ sets the state for us */
  100321. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  100322. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  100323. break;
  100324. default:
  100325. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  100326. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100327. return true;
  100328. }
  100329. /* read residual */
  100330. switch(subframe->entropy_coding_method.type) {
  100331. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  100332. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  100333. 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))
  100334. return false;
  100335. break;
  100336. default:
  100337. FLAC__ASSERT(0);
  100338. }
  100339. /* decode the subframe */
  100340. if(do_full_decode) {
  100341. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  100342. /*@@@@@@ technically not pessimistic enough, should be more like
  100343. if( (FLAC__uint64)order * ((((FLAC__uint64)1)<<bps)-1) * ((1<<subframe->qlp_coeff_precision)-1) < (((FLAC__uint64)-1) << 32) )
  100344. */
  100345. if(bps + subframe->qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  100346. if(bps <= 16 && subframe->qlp_coeff_precision <= 16) {
  100347. if(order <= 8)
  100348. 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);
  100349. else
  100350. 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);
  100351. }
  100352. else
  100353. 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);
  100354. else
  100355. 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);
  100356. }
  100357. return true;
  100358. }
  100359. FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  100360. {
  100361. FLAC__Subframe_Verbatim *subframe = &decoder->private_->frame.subframes[channel].data.verbatim;
  100362. FLAC__int32 x, *residual = decoder->private_->residual[channel];
  100363. unsigned i;
  100364. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_VERBATIM;
  100365. subframe->data = residual;
  100366. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  100367. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  100368. return false; /* read_callback_ sets the state for us */
  100369. residual[i] = x;
  100370. }
  100371. /* decode the subframe */
  100372. if(do_full_decode)
  100373. memcpy(decoder->private_->output[channel], subframe->data, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  100374. return true;
  100375. }
  100376. 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)
  100377. {
  100378. FLAC__uint32 rice_parameter;
  100379. int i;
  100380. unsigned partition, sample, u;
  100381. const unsigned partitions = 1u << partition_order;
  100382. const unsigned partition_samples = partition_order > 0? decoder->private_->frame.header.blocksize >> partition_order : decoder->private_->frame.header.blocksize - predictor_order;
  100383. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  100384. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  100385. /* sanity checks */
  100386. if(partition_order == 0) {
  100387. if(decoder->private_->frame.header.blocksize < predictor_order) {
  100388. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100389. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100390. return true;
  100391. }
  100392. }
  100393. else {
  100394. if(partition_samples < predictor_order) {
  100395. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100396. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100397. return true;
  100398. }
  100399. }
  100400. if(!FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order))) {
  100401. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100402. return false;
  100403. }
  100404. sample = 0;
  100405. for(partition = 0; partition < partitions; partition++) {
  100406. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, plen))
  100407. return false; /* read_callback_ sets the state for us */
  100408. partitioned_rice_contents->parameters[partition] = rice_parameter;
  100409. if(rice_parameter < pesc) {
  100410. partitioned_rice_contents->raw_bits[partition] = 0;
  100411. u = (partition_order == 0 || partition > 0)? partition_samples : partition_samples - predictor_order;
  100412. if(!decoder->private_->local_bitreader_read_rice_signed_block(decoder->private_->input, (int*) residual + sample, u, rice_parameter))
  100413. return false; /* read_callback_ sets the state for us */
  100414. sample += u;
  100415. }
  100416. else {
  100417. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  100418. return false; /* read_callback_ sets the state for us */
  100419. partitioned_rice_contents->raw_bits[partition] = rice_parameter;
  100420. for(u = (partition_order == 0 || partition > 0)? 0 : predictor_order; u < partition_samples; u++, sample++) {
  100421. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, (FLAC__int32*) &i, rice_parameter))
  100422. return false; /* read_callback_ sets the state for us */
  100423. residual[sample] = i;
  100424. }
  100425. }
  100426. }
  100427. return true;
  100428. }
  100429. FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder)
  100430. {
  100431. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  100432. FLAC__uint32 zero = 0;
  100433. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &zero, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  100434. return false; /* read_callback_ sets the state for us */
  100435. if(zero != 0) {
  100436. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100437. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100438. }
  100439. }
  100440. return true;
  100441. }
  100442. FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data)
  100443. {
  100444. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder *)client_data;
  100445. if(
  100446. #if FLAC__HAS_OGG
  100447. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  100448. !decoder->private_->is_ogg &&
  100449. #endif
  100450. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  100451. ) {
  100452. *bytes = 0;
  100453. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  100454. return false;
  100455. }
  100456. else if(*bytes > 0) {
  100457. /* While seeking, it is possible for our seek to land in the
  100458. * middle of audio data that looks exactly like a frame header
  100459. * from a future version of an encoder. When that happens, our
  100460. * error callback will get an
  100461. * FLAC__STREAM_DECODER_UNPARSEABLE_STREAM and increment its
  100462. * unparseable_frame_count. But there is a remote possibility
  100463. * that it is properly synced at such a "future-codec frame",
  100464. * so to make sure, we wait to see many "unparseable" errors in
  100465. * a row before bailing out.
  100466. */
  100467. if(decoder->private_->is_seeking && decoder->private_->unparseable_frame_count > 20) {
  100468. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  100469. return false;
  100470. }
  100471. else {
  100472. const FLAC__StreamDecoderReadStatus status =
  100473. #if FLAC__HAS_OGG
  100474. decoder->private_->is_ogg?
  100475. read_callback_ogg_aspect_(decoder, buffer, bytes) :
  100476. #endif
  100477. decoder->private_->read_callback(decoder, buffer, bytes, decoder->private_->client_data)
  100478. ;
  100479. if(status == FLAC__STREAM_DECODER_READ_STATUS_ABORT) {
  100480. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  100481. return false;
  100482. }
  100483. else if(*bytes == 0) {
  100484. if(
  100485. status == FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM ||
  100486. (
  100487. #if FLAC__HAS_OGG
  100488. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  100489. !decoder->private_->is_ogg &&
  100490. #endif
  100491. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  100492. )
  100493. ) {
  100494. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  100495. return false;
  100496. }
  100497. else
  100498. return true;
  100499. }
  100500. else
  100501. return true;
  100502. }
  100503. }
  100504. else {
  100505. /* abort to avoid a deadlock */
  100506. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  100507. return false;
  100508. }
  100509. /* [1] @@@ HACK NOTE: The end-of-stream checking has to be hacked around
  100510. * for Ogg FLAC. This is because the ogg decoder aspect can lose sync
  100511. * and at the same time hit the end of the stream (for example, seeking
  100512. * to a point that is after the beginning of the last Ogg page). There
  100513. * is no way to report an Ogg sync loss through the callbacks (see note
  100514. * in read_callback_ogg_aspect_()) so it returns CONTINUE with *bytes==0.
  100515. * So to keep the decoder from stopping at this point we gate the call
  100516. * to the eof_callback and let the Ogg decoder aspect set the
  100517. * end-of-stream state when it is needed.
  100518. */
  100519. }
  100520. #if FLAC__HAS_OGG
  100521. FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes)
  100522. {
  100523. switch(FLAC__ogg_decoder_aspect_read_callback_wrapper(&decoder->protected_->ogg_decoder_aspect, buffer, bytes, read_callback_proxy_, decoder, decoder->private_->client_data)) {
  100524. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK:
  100525. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  100526. /* we don't really have a way to handle lost sync via read
  100527. * callback so we'll let it pass and let the underlying
  100528. * FLAC decoder catch the error
  100529. */
  100530. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_LOST_SYNC:
  100531. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  100532. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM:
  100533. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  100534. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_NOT_FLAC:
  100535. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_UNSUPPORTED_MAPPING_VERSION:
  100536. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT:
  100537. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ERROR:
  100538. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_MEMORY_ALLOCATION_ERROR:
  100539. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  100540. default:
  100541. FLAC__ASSERT(0);
  100542. /* double protection */
  100543. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  100544. }
  100545. }
  100546. FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  100547. {
  100548. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder*)void_decoder;
  100549. switch(decoder->private_->read_callback(decoder, buffer, bytes, client_data)) {
  100550. case FLAC__STREAM_DECODER_READ_STATUS_CONTINUE:
  100551. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK;
  100552. case FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM:
  100553. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM;
  100554. case FLAC__STREAM_DECODER_READ_STATUS_ABORT:
  100555. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  100556. default:
  100557. /* double protection: */
  100558. FLAC__ASSERT(0);
  100559. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  100560. }
  100561. }
  100562. #endif
  100563. FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[])
  100564. {
  100565. if(decoder->private_->is_seeking) {
  100566. FLAC__uint64 this_frame_sample = frame->header.number.sample_number;
  100567. FLAC__uint64 next_frame_sample = this_frame_sample + (FLAC__uint64)frame->header.blocksize;
  100568. FLAC__uint64 target_sample = decoder->private_->target_sample;
  100569. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  100570. #if FLAC__HAS_OGG
  100571. decoder->private_->got_a_frame = true;
  100572. #endif
  100573. decoder->private_->last_frame = *frame; /* save the frame */
  100574. if(this_frame_sample <= target_sample && target_sample < next_frame_sample) { /* we hit our target frame */
  100575. unsigned delta = (unsigned)(target_sample - this_frame_sample);
  100576. /* kick out of seek mode */
  100577. decoder->private_->is_seeking = false;
  100578. /* shift out the samples before target_sample */
  100579. if(delta > 0) {
  100580. unsigned channel;
  100581. const FLAC__int32 *newbuffer[FLAC__MAX_CHANNELS];
  100582. for(channel = 0; channel < frame->header.channels; channel++)
  100583. newbuffer[channel] = buffer[channel] + delta;
  100584. decoder->private_->last_frame.header.blocksize -= delta;
  100585. decoder->private_->last_frame.header.number.sample_number += (FLAC__uint64)delta;
  100586. /* write the relevant samples */
  100587. return decoder->private_->write_callback(decoder, &decoder->private_->last_frame, newbuffer, decoder->private_->client_data);
  100588. }
  100589. else {
  100590. /* write the relevant samples */
  100591. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  100592. }
  100593. }
  100594. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  100595. }
  100596. /*
  100597. * If we never got STREAMINFO, turn off MD5 checking to save
  100598. * cycles since we don't have a sum to compare to anyway
  100599. */
  100600. if(!decoder->private_->has_stream_info)
  100601. decoder->private_->do_md5_checking = false;
  100602. if(decoder->private_->do_md5_checking) {
  100603. if(!FLAC__MD5Accumulate(&decoder->private_->md5context, buffer, frame->header.channels, frame->header.blocksize, (frame->header.bits_per_sample+7) / 8))
  100604. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  100605. }
  100606. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  100607. }
  100608. void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status)
  100609. {
  100610. if(!decoder->private_->is_seeking)
  100611. decoder->private_->error_callback(decoder, status, decoder->private_->client_data);
  100612. else if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM)
  100613. decoder->private_->unparseable_frame_count++;
  100614. }
  100615. FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  100616. {
  100617. FLAC__uint64 first_frame_offset = decoder->private_->first_frame_offset, lower_bound, upper_bound, lower_bound_sample, upper_bound_sample, this_frame_sample;
  100618. FLAC__int64 pos = -1;
  100619. int i;
  100620. unsigned approx_bytes_per_frame;
  100621. FLAC__bool first_seek = true;
  100622. const FLAC__uint64 total_samples = FLAC__stream_decoder_get_total_samples(decoder);
  100623. const unsigned min_blocksize = decoder->private_->stream_info.data.stream_info.min_blocksize;
  100624. const unsigned max_blocksize = decoder->private_->stream_info.data.stream_info.max_blocksize;
  100625. const unsigned max_framesize = decoder->private_->stream_info.data.stream_info.max_framesize;
  100626. const unsigned min_framesize = decoder->private_->stream_info.data.stream_info.min_framesize;
  100627. /* take these from the current frame in case they've changed mid-stream */
  100628. unsigned channels = FLAC__stream_decoder_get_channels(decoder);
  100629. unsigned bps = FLAC__stream_decoder_get_bits_per_sample(decoder);
  100630. const FLAC__StreamMetadata_SeekTable *seek_table = decoder->private_->has_seek_table? &decoder->private_->seek_table.data.seek_table : 0;
  100631. /* use values from stream info if we didn't decode a frame */
  100632. if(channels == 0)
  100633. channels = decoder->private_->stream_info.data.stream_info.channels;
  100634. if(bps == 0)
  100635. bps = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  100636. /* we are just guessing here */
  100637. if(max_framesize > 0)
  100638. approx_bytes_per_frame = (max_framesize + min_framesize) / 2 + 1;
  100639. /*
  100640. * Check if it's a known fixed-blocksize stream. Note that though
  100641. * the spec doesn't allow zeroes in the STREAMINFO block, we may
  100642. * never get a STREAMINFO block when decoding so the value of
  100643. * min_blocksize might be zero.
  100644. */
  100645. else if(min_blocksize == max_blocksize && min_blocksize > 0) {
  100646. /* note there are no () around 'bps/8' to keep precision up since it's an integer calulation */
  100647. approx_bytes_per_frame = min_blocksize * channels * bps/8 + 64;
  100648. }
  100649. else
  100650. approx_bytes_per_frame = 4096 * channels * bps/8 + 64;
  100651. /*
  100652. * First, we set an upper and lower bound on where in the
  100653. * stream we will search. For now we assume the worst case
  100654. * scenario, which is our best guess at the beginning of
  100655. * the first frame and end of the stream.
  100656. */
  100657. lower_bound = first_frame_offset;
  100658. lower_bound_sample = 0;
  100659. upper_bound = stream_length;
  100660. upper_bound_sample = total_samples > 0 ? total_samples : target_sample /*estimate it*/;
  100661. /*
  100662. * Now we refine the bounds if we have a seektable with
  100663. * suitable points. Note that according to the spec they
  100664. * must be ordered by ascending sample number.
  100665. *
  100666. * Note: to protect against invalid seek tables we will ignore points
  100667. * that have frame_samples==0 or sample_number>=total_samples
  100668. */
  100669. if(seek_table) {
  100670. FLAC__uint64 new_lower_bound = lower_bound;
  100671. FLAC__uint64 new_upper_bound = upper_bound;
  100672. FLAC__uint64 new_lower_bound_sample = lower_bound_sample;
  100673. FLAC__uint64 new_upper_bound_sample = upper_bound_sample;
  100674. /* find the closest seek point <= target_sample, if it exists */
  100675. for(i = (int)seek_table->num_points - 1; i >= 0; i--) {
  100676. if(
  100677. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  100678. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  100679. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  100680. seek_table->points[i].sample_number <= target_sample
  100681. )
  100682. break;
  100683. }
  100684. if(i >= 0) { /* i.e. we found a suitable seek point... */
  100685. new_lower_bound = first_frame_offset + seek_table->points[i].stream_offset;
  100686. new_lower_bound_sample = seek_table->points[i].sample_number;
  100687. }
  100688. /* find the closest seek point > target_sample, if it exists */
  100689. for(i = 0; i < (int)seek_table->num_points; i++) {
  100690. if(
  100691. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  100692. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  100693. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  100694. seek_table->points[i].sample_number > target_sample
  100695. )
  100696. break;
  100697. }
  100698. if(i < (int)seek_table->num_points) { /* i.e. we found a suitable seek point... */
  100699. new_upper_bound = first_frame_offset + seek_table->points[i].stream_offset;
  100700. new_upper_bound_sample = seek_table->points[i].sample_number;
  100701. }
  100702. /* final protection against unsorted seek tables; keep original values if bogus */
  100703. if(new_upper_bound >= new_lower_bound) {
  100704. lower_bound = new_lower_bound;
  100705. upper_bound = new_upper_bound;
  100706. lower_bound_sample = new_lower_bound_sample;
  100707. upper_bound_sample = new_upper_bound_sample;
  100708. }
  100709. }
  100710. FLAC__ASSERT(upper_bound_sample >= lower_bound_sample);
  100711. /* there are 2 insidious ways that the following equality occurs, which
  100712. * we need to fix:
  100713. * 1) total_samples is 0 (unknown) and target_sample is 0
  100714. * 2) total_samples is 0 (unknown) and target_sample happens to be
  100715. * exactly equal to the last seek point in the seek table; this
  100716. * means there is no seek point above it, and upper_bound_samples
  100717. * remains equal to the estimate (of target_samples) we made above
  100718. * in either case it does not hurt to move upper_bound_sample up by 1
  100719. */
  100720. if(upper_bound_sample == lower_bound_sample)
  100721. upper_bound_sample++;
  100722. decoder->private_->target_sample = target_sample;
  100723. while(1) {
  100724. /* check if the bounds are still ok */
  100725. if (lower_bound_sample >= upper_bound_sample || lower_bound > upper_bound) {
  100726. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  100727. return false;
  100728. }
  100729. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100730. #if defined _MSC_VER || defined __MINGW32__
  100731. /* with VC++ you have to spoon feed it the casting */
  100732. 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;
  100733. #else
  100734. 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;
  100735. #endif
  100736. #else
  100737. /* a little less accurate: */
  100738. if(upper_bound - lower_bound < 0xffffffff)
  100739. 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;
  100740. else /* @@@ WATCHOUT, ~2TB limit */
  100741. 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;
  100742. #endif
  100743. if(pos >= (FLAC__int64)upper_bound)
  100744. pos = (FLAC__int64)upper_bound - 1;
  100745. if(pos < (FLAC__int64)lower_bound)
  100746. pos = (FLAC__int64)lower_bound;
  100747. if(decoder->private_->seek_callback(decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  100748. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  100749. return false;
  100750. }
  100751. if(!FLAC__stream_decoder_flush(decoder)) {
  100752. /* above call sets the state for us */
  100753. return false;
  100754. }
  100755. /* Now we need to get a frame. First we need to reset our
  100756. * unparseable_frame_count; if we get too many unparseable
  100757. * frames in a row, the read callback will return
  100758. * FLAC__STREAM_DECODER_READ_STATUS_ABORT, causing
  100759. * FLAC__stream_decoder_process_single() to return false.
  100760. */
  100761. decoder->private_->unparseable_frame_count = 0;
  100762. if(!FLAC__stream_decoder_process_single(decoder)) {
  100763. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  100764. return false;
  100765. }
  100766. /* our write callback will change the state when it gets to the target frame */
  100767. /* 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 */
  100768. #if 0
  100769. /*@@@@@@ used to be the following; not clear if the check for end of stream is needed anymore */
  100770. if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_SEEKING && decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM)
  100771. break;
  100772. #endif
  100773. if(!decoder->private_->is_seeking)
  100774. break;
  100775. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  100776. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  100777. if (0 == decoder->private_->samples_decoded || (this_frame_sample + decoder->private_->last_frame.header.blocksize >= upper_bound_sample && !first_seek)) {
  100778. if (pos == (FLAC__int64)lower_bound) {
  100779. /* can't move back any more than the first frame, something is fatally wrong */
  100780. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  100781. return false;
  100782. }
  100783. /* our last move backwards wasn't big enough, try again */
  100784. approx_bytes_per_frame = approx_bytes_per_frame? approx_bytes_per_frame * 2 : 16;
  100785. continue;
  100786. }
  100787. /* allow one seek over upper bound, so we can get a correct upper_bound_sample for streams with unknown total_samples */
  100788. first_seek = false;
  100789. /* make sure we are not seeking in corrupted stream */
  100790. if (this_frame_sample < lower_bound_sample) {
  100791. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  100792. return false;
  100793. }
  100794. /* we need to narrow the search */
  100795. if(target_sample < this_frame_sample) {
  100796. upper_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  100797. /*@@@@@@ what will decode position be if at end of stream? */
  100798. if(!FLAC__stream_decoder_get_decode_position(decoder, &upper_bound)) {
  100799. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  100800. return false;
  100801. }
  100802. approx_bytes_per_frame = (unsigned)(2 * (upper_bound - pos) / 3 + 16);
  100803. }
  100804. else { /* target_sample >= this_frame_sample + this frame's blocksize */
  100805. lower_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  100806. if(!FLAC__stream_decoder_get_decode_position(decoder, &lower_bound)) {
  100807. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  100808. return false;
  100809. }
  100810. approx_bytes_per_frame = (unsigned)(2 * (lower_bound - pos) / 3 + 16);
  100811. }
  100812. }
  100813. return true;
  100814. }
  100815. #if FLAC__HAS_OGG
  100816. FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  100817. {
  100818. FLAC__uint64 left_pos = 0, right_pos = stream_length;
  100819. FLAC__uint64 left_sample = 0, right_sample = FLAC__stream_decoder_get_total_samples(decoder);
  100820. FLAC__uint64 this_frame_sample = (FLAC__uint64)0 - 1;
  100821. FLAC__uint64 pos = 0; /* only initialized to avoid compiler warning */
  100822. FLAC__bool did_a_seek;
  100823. unsigned iteration = 0;
  100824. /* In the first iterations, we will calculate the target byte position
  100825. * by the distance from the target sample to left_sample and
  100826. * right_sample (let's call it "proportional search"). After that, we
  100827. * will switch to binary search.
  100828. */
  100829. unsigned BINARY_SEARCH_AFTER_ITERATION = 2;
  100830. /* We will switch to a linear search once our current sample is less
  100831. * than this number of samples ahead of the target sample
  100832. */
  100833. static const FLAC__uint64 LINEAR_SEARCH_WITHIN_SAMPLES = FLAC__MAX_BLOCK_SIZE * 2;
  100834. /* If the total number of samples is unknown, use a large value, and
  100835. * force binary search immediately.
  100836. */
  100837. if(right_sample == 0) {
  100838. right_sample = (FLAC__uint64)(-1);
  100839. BINARY_SEARCH_AFTER_ITERATION = 0;
  100840. }
  100841. decoder->private_->target_sample = target_sample;
  100842. for( ; ; iteration++) {
  100843. if (iteration == 0 || this_frame_sample > target_sample || target_sample - this_frame_sample > LINEAR_SEARCH_WITHIN_SAMPLES) {
  100844. if (iteration >= BINARY_SEARCH_AFTER_ITERATION) {
  100845. pos = (right_pos + left_pos) / 2;
  100846. }
  100847. else {
  100848. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100849. #if defined _MSC_VER || defined __MINGW32__
  100850. /* with MSVC you have to spoon feed it the casting */
  100851. 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));
  100852. #else
  100853. pos = (FLAC__uint64)((FLAC__double)(target_sample - left_sample) / (FLAC__double)(right_sample - left_sample) * (FLAC__double)(right_pos - left_pos));
  100854. #endif
  100855. #else
  100856. /* a little less accurate: */
  100857. if ((target_sample-left_sample <= 0xffffffff) && (right_pos-left_pos <= 0xffffffff))
  100858. pos = (FLAC__int64)(((target_sample-left_sample) * (right_pos-left_pos)) / (right_sample-left_sample));
  100859. else /* @@@ WATCHOUT, ~2TB limit */
  100860. pos = (FLAC__int64)((((target_sample-left_sample)>>8) * ((right_pos-left_pos)>>8)) / ((right_sample-left_sample)>>16));
  100861. #endif
  100862. /* @@@ TODO: might want to limit pos to some distance
  100863. * before EOF, to make sure we land before the last frame,
  100864. * thereby getting a this_frame_sample and so having a better
  100865. * estimate.
  100866. */
  100867. }
  100868. /* physical seek */
  100869. if(decoder->private_->seek_callback((FLAC__StreamDecoder*)decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  100870. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  100871. return false;
  100872. }
  100873. if(!FLAC__stream_decoder_flush(decoder)) {
  100874. /* above call sets the state for us */
  100875. return false;
  100876. }
  100877. did_a_seek = true;
  100878. }
  100879. else
  100880. did_a_seek = false;
  100881. decoder->private_->got_a_frame = false;
  100882. if(!FLAC__stream_decoder_process_single(decoder)) {
  100883. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  100884. return false;
  100885. }
  100886. if(!decoder->private_->got_a_frame) {
  100887. if(did_a_seek) {
  100888. /* this can happen if we seek to a point after the last frame; we drop
  100889. * to binary search right away in this case to avoid any wasted
  100890. * iterations of proportional search.
  100891. */
  100892. right_pos = pos;
  100893. BINARY_SEARCH_AFTER_ITERATION = 0;
  100894. }
  100895. else {
  100896. /* this can probably only happen if total_samples is unknown and the
  100897. * target_sample is past the end of the stream
  100898. */
  100899. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  100900. return false;
  100901. }
  100902. }
  100903. /* our write callback will change the state when it gets to the target frame */
  100904. else if(!decoder->private_->is_seeking) {
  100905. break;
  100906. }
  100907. else {
  100908. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  100909. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  100910. if (did_a_seek) {
  100911. if (this_frame_sample <= target_sample) {
  100912. /* The 'equal' case should not happen, since
  100913. * FLAC__stream_decoder_process_single()
  100914. * should recognize that it has hit the
  100915. * target sample and we would exit through
  100916. * the 'break' above.
  100917. */
  100918. FLAC__ASSERT(this_frame_sample != target_sample);
  100919. left_sample = this_frame_sample;
  100920. /* sanity check to avoid infinite loop */
  100921. if (left_pos == pos) {
  100922. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  100923. return false;
  100924. }
  100925. left_pos = pos;
  100926. }
  100927. else if(this_frame_sample > target_sample) {
  100928. right_sample = this_frame_sample;
  100929. /* sanity check to avoid infinite loop */
  100930. if (right_pos == pos) {
  100931. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  100932. return false;
  100933. }
  100934. right_pos = pos;
  100935. }
  100936. }
  100937. }
  100938. }
  100939. return true;
  100940. }
  100941. #endif
  100942. FLAC__StreamDecoderReadStatus file_read_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  100943. {
  100944. (void)client_data;
  100945. if(*bytes > 0) {
  100946. *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, decoder->private_->file);
  100947. if(ferror(decoder->private_->file))
  100948. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  100949. else if(*bytes == 0)
  100950. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  100951. else
  100952. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  100953. }
  100954. else
  100955. return FLAC__STREAM_DECODER_READ_STATUS_ABORT; /* abort to avoid a deadlock */
  100956. }
  100957. FLAC__StreamDecoderSeekStatus file_seek_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  100958. {
  100959. (void)client_data;
  100960. if(decoder->private_->file == stdin)
  100961. return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  100962. else if(fseeko(decoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  100963. return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  100964. else
  100965. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  100966. }
  100967. FLAC__StreamDecoderTellStatus file_tell_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  100968. {
  100969. off_t pos;
  100970. (void)client_data;
  100971. if(decoder->private_->file == stdin)
  100972. return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  100973. else if((pos = ftello(decoder->private_->file)) < 0)
  100974. return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  100975. else {
  100976. *absolute_byte_offset = (FLAC__uint64)pos;
  100977. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  100978. }
  100979. }
  100980. FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  100981. {
  100982. struct stat filestats;
  100983. (void)client_data;
  100984. if(decoder->private_->file == stdin)
  100985. return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  100986. else if(fstat(fileno(decoder->private_->file), &filestats) != 0)
  100987. return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  100988. else {
  100989. *stream_length = (FLAC__uint64)filestats.st_size;
  100990. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  100991. }
  100992. }
  100993. FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data)
  100994. {
  100995. (void)client_data;
  100996. return feof(decoder->private_->file)? true : false;
  100997. }
  100998. #endif
  100999. /*** End of inlined file: stream_decoder.c ***/
  101000. /*** Start of inlined file: stream_encoder.c ***/
  101001. /*** Start of inlined file: juce_FlacHeader.h ***/
  101002. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  101003. // tasks..
  101004. #define VERSION "1.2.1"
  101005. #define FLAC__NO_DLL 1
  101006. #if JUCE_MSVC
  101007. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  101008. #endif
  101009. #if JUCE_MAC
  101010. #define FLAC__SYS_DARWIN 1
  101011. #endif
  101012. /*** End of inlined file: juce_FlacHeader.h ***/
  101013. #if JUCE_USE_FLAC
  101014. #if HAVE_CONFIG_H
  101015. # include <config.h>
  101016. #endif
  101017. #if defined _MSC_VER || defined __MINGW32__
  101018. #include <io.h> /* for _setmode() */
  101019. #include <fcntl.h> /* for _O_BINARY */
  101020. #endif
  101021. #if defined __CYGWIN__ || defined __EMX__
  101022. #include <io.h> /* for setmode(), O_BINARY */
  101023. #include <fcntl.h> /* for _O_BINARY */
  101024. #endif
  101025. #include <limits.h>
  101026. #include <stdio.h>
  101027. #include <stdlib.h> /* for malloc() */
  101028. #include <string.h> /* for memcpy() */
  101029. #include <sys/types.h> /* for off_t */
  101030. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  101031. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  101032. #define fseeko fseek
  101033. #define ftello ftell
  101034. #endif
  101035. #endif
  101036. /*** Start of inlined file: stream_encoder.h ***/
  101037. #ifndef FLAC__PROTECTED__STREAM_ENCODER_H
  101038. #define FLAC__PROTECTED__STREAM_ENCODER_H
  101039. #if FLAC__HAS_OGG
  101040. #include "private/ogg_encoder_aspect.h"
  101041. #endif
  101042. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101043. #define FLAC__MAX_APODIZATION_FUNCTIONS 32
  101044. typedef enum {
  101045. FLAC__APODIZATION_BARTLETT,
  101046. FLAC__APODIZATION_BARTLETT_HANN,
  101047. FLAC__APODIZATION_BLACKMAN,
  101048. FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE,
  101049. FLAC__APODIZATION_CONNES,
  101050. FLAC__APODIZATION_FLATTOP,
  101051. FLAC__APODIZATION_GAUSS,
  101052. FLAC__APODIZATION_HAMMING,
  101053. FLAC__APODIZATION_HANN,
  101054. FLAC__APODIZATION_KAISER_BESSEL,
  101055. FLAC__APODIZATION_NUTTALL,
  101056. FLAC__APODIZATION_RECTANGLE,
  101057. FLAC__APODIZATION_TRIANGLE,
  101058. FLAC__APODIZATION_TUKEY,
  101059. FLAC__APODIZATION_WELCH
  101060. } FLAC__ApodizationFunction;
  101061. typedef struct {
  101062. FLAC__ApodizationFunction type;
  101063. union {
  101064. struct {
  101065. FLAC__real stddev;
  101066. } gauss;
  101067. struct {
  101068. FLAC__real p;
  101069. } tukey;
  101070. } parameters;
  101071. } FLAC__ApodizationSpecification;
  101072. #endif // #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101073. typedef struct FLAC__StreamEncoderProtected {
  101074. FLAC__StreamEncoderState state;
  101075. FLAC__bool verify;
  101076. FLAC__bool streamable_subset;
  101077. FLAC__bool do_md5;
  101078. FLAC__bool do_mid_side_stereo;
  101079. FLAC__bool loose_mid_side_stereo;
  101080. unsigned channels;
  101081. unsigned bits_per_sample;
  101082. unsigned sample_rate;
  101083. unsigned blocksize;
  101084. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101085. unsigned num_apodizations;
  101086. FLAC__ApodizationSpecification apodizations[FLAC__MAX_APODIZATION_FUNCTIONS];
  101087. #endif
  101088. unsigned max_lpc_order;
  101089. unsigned qlp_coeff_precision;
  101090. FLAC__bool do_qlp_coeff_prec_search;
  101091. FLAC__bool do_exhaustive_model_search;
  101092. FLAC__bool do_escape_coding;
  101093. unsigned min_residual_partition_order;
  101094. unsigned max_residual_partition_order;
  101095. unsigned rice_parameter_search_dist;
  101096. FLAC__uint64 total_samples_estimate;
  101097. FLAC__StreamMetadata **metadata;
  101098. unsigned num_metadata_blocks;
  101099. FLAC__uint64 streaminfo_offset, seektable_offset, audio_offset;
  101100. #if FLAC__HAS_OGG
  101101. FLAC__OggEncoderAspect ogg_encoder_aspect;
  101102. #endif
  101103. } FLAC__StreamEncoderProtected;
  101104. #endif
  101105. /*** End of inlined file: stream_encoder.h ***/
  101106. #if FLAC__HAS_OGG
  101107. #include "include/private/ogg_helper.h"
  101108. #include "include/private/ogg_mapping.h"
  101109. #endif
  101110. /*** Start of inlined file: stream_encoder_framing.h ***/
  101111. #ifndef FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  101112. #define FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  101113. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw);
  101114. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw);
  101115. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  101116. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  101117. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  101118. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  101119. #endif
  101120. /*** End of inlined file: stream_encoder_framing.h ***/
  101121. /*** Start of inlined file: window.h ***/
  101122. #ifndef FLAC__PRIVATE__WINDOW_H
  101123. #define FLAC__PRIVATE__WINDOW_H
  101124. #ifdef HAVE_CONFIG_H
  101125. #include <config.h>
  101126. #endif
  101127. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101128. /*
  101129. * FLAC__window_*()
  101130. * --------------------------------------------------------------------
  101131. * Calculates window coefficients according to different apodization
  101132. * functions.
  101133. *
  101134. * OUT window[0,L-1]
  101135. * IN L (number of points in window)
  101136. */
  101137. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L);
  101138. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L);
  101139. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L);
  101140. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L);
  101141. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L);
  101142. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L);
  101143. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev); /* 0.0 < stddev <= 0.5 */
  101144. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L);
  101145. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L);
  101146. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L);
  101147. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L);
  101148. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L);
  101149. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L);
  101150. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p);
  101151. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L);
  101152. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  101153. #endif
  101154. /*** End of inlined file: window.h ***/
  101155. #ifndef FLaC__INLINE
  101156. #define FLaC__INLINE
  101157. #endif
  101158. #ifdef min
  101159. #undef min
  101160. #endif
  101161. #define min(x,y) ((x)<(y)?(x):(y))
  101162. #ifdef max
  101163. #undef max
  101164. #endif
  101165. #define max(x,y) ((x)>(y)?(x):(y))
  101166. /* Exact Rice codeword length calculation is off by default. The simple
  101167. * (and fast) estimation (of how many bits a residual value will be
  101168. * encoded with) in this encoder is very good, almost always yielding
  101169. * compression within 0.1% of exact calculation.
  101170. */
  101171. #undef EXACT_RICE_BITS_CALCULATION
  101172. /* Rice parameter searching is off by default. The simple (and fast)
  101173. * parameter estimation in this encoder is very good, almost always
  101174. * yielding compression within 0.1% of the optimal parameters.
  101175. */
  101176. #undef ENABLE_RICE_PARAMETER_SEARCH
  101177. typedef struct {
  101178. FLAC__int32 *data[FLAC__MAX_CHANNELS];
  101179. unsigned size; /* of each data[] in samples */
  101180. unsigned tail;
  101181. } verify_input_fifo;
  101182. typedef struct {
  101183. const FLAC__byte *data;
  101184. unsigned capacity;
  101185. unsigned bytes;
  101186. } verify_output;
  101187. typedef enum {
  101188. ENCODER_IN_MAGIC = 0,
  101189. ENCODER_IN_METADATA = 1,
  101190. ENCODER_IN_AUDIO = 2
  101191. } EncoderStateHint;
  101192. static struct CompressionLevels {
  101193. FLAC__bool do_mid_side_stereo;
  101194. FLAC__bool loose_mid_side_stereo;
  101195. unsigned max_lpc_order;
  101196. unsigned qlp_coeff_precision;
  101197. FLAC__bool do_qlp_coeff_prec_search;
  101198. FLAC__bool do_escape_coding;
  101199. FLAC__bool do_exhaustive_model_search;
  101200. unsigned min_residual_partition_order;
  101201. unsigned max_residual_partition_order;
  101202. unsigned rice_parameter_search_dist;
  101203. } compression_levels_[] = {
  101204. { false, false, 0, 0, false, false, false, 0, 3, 0 },
  101205. { true , true , 0, 0, false, false, false, 0, 3, 0 },
  101206. { true , false, 0, 0, false, false, false, 0, 3, 0 },
  101207. { false, false, 6, 0, false, false, false, 0, 4, 0 },
  101208. { true , true , 8, 0, false, false, false, 0, 4, 0 },
  101209. { true , false, 8, 0, false, false, false, 0, 5, 0 },
  101210. { true , false, 8, 0, false, false, false, 0, 6, 0 },
  101211. { true , false, 8, 0, false, false, true , 0, 6, 0 },
  101212. { true , false, 12, 0, false, false, true , 0, 6, 0 }
  101213. };
  101214. /***********************************************************************
  101215. *
  101216. * Private class method prototypes
  101217. *
  101218. ***********************************************************************/
  101219. static void set_defaults_enc(FLAC__StreamEncoder *encoder);
  101220. static void free_(FLAC__StreamEncoder *encoder);
  101221. static FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize);
  101222. static FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block);
  101223. static FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block);
  101224. static void update_metadata_(const FLAC__StreamEncoder *encoder);
  101225. #if FLAC__HAS_OGG
  101226. static void update_ogg_metadata_(FLAC__StreamEncoder *encoder);
  101227. #endif
  101228. static FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block);
  101229. static FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block);
  101230. static FLAC__bool process_subframe_(
  101231. FLAC__StreamEncoder *encoder,
  101232. unsigned min_partition_order,
  101233. unsigned max_partition_order,
  101234. const FLAC__FrameHeader *frame_header,
  101235. unsigned subframe_bps,
  101236. const FLAC__int32 integer_signal[],
  101237. FLAC__Subframe *subframe[2],
  101238. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  101239. FLAC__int32 *residual[2],
  101240. unsigned *best_subframe,
  101241. unsigned *best_bits
  101242. );
  101243. static FLAC__bool add_subframe_(
  101244. FLAC__StreamEncoder *encoder,
  101245. unsigned blocksize,
  101246. unsigned subframe_bps,
  101247. const FLAC__Subframe *subframe,
  101248. FLAC__BitWriter *frame
  101249. );
  101250. static unsigned evaluate_constant_subframe_(
  101251. FLAC__StreamEncoder *encoder,
  101252. const FLAC__int32 signal,
  101253. unsigned blocksize,
  101254. unsigned subframe_bps,
  101255. FLAC__Subframe *subframe
  101256. );
  101257. static unsigned evaluate_fixed_subframe_(
  101258. FLAC__StreamEncoder *encoder,
  101259. const FLAC__int32 signal[],
  101260. FLAC__int32 residual[],
  101261. FLAC__uint64 abs_residual_partition_sums[],
  101262. unsigned raw_bits_per_partition[],
  101263. unsigned blocksize,
  101264. unsigned subframe_bps,
  101265. unsigned order,
  101266. unsigned rice_parameter,
  101267. unsigned rice_parameter_limit,
  101268. unsigned min_partition_order,
  101269. unsigned max_partition_order,
  101270. FLAC__bool do_escape_coding,
  101271. unsigned rice_parameter_search_dist,
  101272. FLAC__Subframe *subframe,
  101273. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  101274. );
  101275. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101276. static unsigned evaluate_lpc_subframe_(
  101277. FLAC__StreamEncoder *encoder,
  101278. const FLAC__int32 signal[],
  101279. FLAC__int32 residual[],
  101280. FLAC__uint64 abs_residual_partition_sums[],
  101281. unsigned raw_bits_per_partition[],
  101282. const FLAC__real lp_coeff[],
  101283. unsigned blocksize,
  101284. unsigned subframe_bps,
  101285. unsigned order,
  101286. unsigned qlp_coeff_precision,
  101287. unsigned rice_parameter,
  101288. unsigned rice_parameter_limit,
  101289. unsigned min_partition_order,
  101290. unsigned max_partition_order,
  101291. FLAC__bool do_escape_coding,
  101292. unsigned rice_parameter_search_dist,
  101293. FLAC__Subframe *subframe,
  101294. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  101295. );
  101296. #endif
  101297. static unsigned evaluate_verbatim_subframe_(
  101298. FLAC__StreamEncoder *encoder,
  101299. const FLAC__int32 signal[],
  101300. unsigned blocksize,
  101301. unsigned subframe_bps,
  101302. FLAC__Subframe *subframe
  101303. );
  101304. static unsigned find_best_partition_order_(
  101305. struct FLAC__StreamEncoderPrivate *private_,
  101306. const FLAC__int32 residual[],
  101307. FLAC__uint64 abs_residual_partition_sums[],
  101308. unsigned raw_bits_per_partition[],
  101309. unsigned residual_samples,
  101310. unsigned predictor_order,
  101311. unsigned rice_parameter,
  101312. unsigned rice_parameter_limit,
  101313. unsigned min_partition_order,
  101314. unsigned max_partition_order,
  101315. unsigned bps,
  101316. FLAC__bool do_escape_coding,
  101317. unsigned rice_parameter_search_dist,
  101318. FLAC__EntropyCodingMethod *best_ecm
  101319. );
  101320. static void precompute_partition_info_sums_(
  101321. const FLAC__int32 residual[],
  101322. FLAC__uint64 abs_residual_partition_sums[],
  101323. unsigned residual_samples,
  101324. unsigned predictor_order,
  101325. unsigned min_partition_order,
  101326. unsigned max_partition_order,
  101327. unsigned bps
  101328. );
  101329. static void precompute_partition_info_escapes_(
  101330. const FLAC__int32 residual[],
  101331. unsigned raw_bits_per_partition[],
  101332. unsigned residual_samples,
  101333. unsigned predictor_order,
  101334. unsigned min_partition_order,
  101335. unsigned max_partition_order
  101336. );
  101337. static FLAC__bool set_partitioned_rice_(
  101338. #ifdef EXACT_RICE_BITS_CALCULATION
  101339. const FLAC__int32 residual[],
  101340. #endif
  101341. const FLAC__uint64 abs_residual_partition_sums[],
  101342. const unsigned raw_bits_per_partition[],
  101343. const unsigned residual_samples,
  101344. const unsigned predictor_order,
  101345. const unsigned suggested_rice_parameter,
  101346. const unsigned rice_parameter_limit,
  101347. const unsigned rice_parameter_search_dist,
  101348. const unsigned partition_order,
  101349. const FLAC__bool search_for_escapes,
  101350. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  101351. unsigned *bits
  101352. );
  101353. static unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples);
  101354. /* verify-related routines: */
  101355. static void append_to_verify_fifo_(
  101356. verify_input_fifo *fifo,
  101357. const FLAC__int32 * const input[],
  101358. unsigned input_offset,
  101359. unsigned channels,
  101360. unsigned wide_samples
  101361. );
  101362. static void append_to_verify_fifo_interleaved_(
  101363. verify_input_fifo *fifo,
  101364. const FLAC__int32 input[],
  101365. unsigned input_offset,
  101366. unsigned channels,
  101367. unsigned wide_samples
  101368. );
  101369. static FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  101370. static FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  101371. static void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  101372. static void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  101373. static FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  101374. static FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  101375. static FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  101376. 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);
  101377. static FILE *get_binary_stdout_(void);
  101378. /***********************************************************************
  101379. *
  101380. * Private class data
  101381. *
  101382. ***********************************************************************/
  101383. typedef struct FLAC__StreamEncoderPrivate {
  101384. unsigned input_capacity; /* current size (in samples) of the signal and residual buffers */
  101385. FLAC__int32 *integer_signal[FLAC__MAX_CHANNELS]; /* the integer version of the input signal */
  101386. FLAC__int32 *integer_signal_mid_side[2]; /* the integer version of the mid-side input signal (stereo only) */
  101387. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101388. FLAC__real *real_signal[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) the floating-point version of the input signal */
  101389. FLAC__real *real_signal_mid_side[2]; /* (@@@ currently unused) the floating-point version of the mid-side input signal (stereo only) */
  101390. FLAC__real *window[FLAC__MAX_APODIZATION_FUNCTIONS]; /* the pre-computed floating-point window for each apodization function */
  101391. FLAC__real *windowed_signal; /* the integer_signal[] * current window[] */
  101392. #endif
  101393. unsigned subframe_bps[FLAC__MAX_CHANNELS]; /* the effective bits per sample of the input signal (stream bps - wasted bits) */
  101394. unsigned subframe_bps_mid_side[2]; /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
  101395. FLAC__int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
  101396. FLAC__int32 *residual_workspace_mid_side[2][2];
  101397. FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
  101398. FLAC__Subframe subframe_workspace_mid_side[2][2];
  101399. FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
  101400. FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
  101401. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace[FLAC__MAX_CHANNELS][2];
  101402. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace_mid_side[FLAC__MAX_CHANNELS][2];
  101403. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr[FLAC__MAX_CHANNELS][2];
  101404. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr_mid_side[FLAC__MAX_CHANNELS][2];
  101405. unsigned best_subframe[FLAC__MAX_CHANNELS]; /* index (0 or 1) into 2nd dimension of the above workspaces */
  101406. unsigned best_subframe_mid_side[2];
  101407. unsigned best_subframe_bits[FLAC__MAX_CHANNELS]; /* size in bits of the best subframe for each channel */
  101408. unsigned best_subframe_bits_mid_side[2];
  101409. FLAC__uint64 *abs_residual_partition_sums; /* workspace where the sum of abs(candidate residual) for each partition is stored */
  101410. unsigned *raw_bits_per_partition; /* workspace where the sum of silog2(candidate residual) for each partition is stored */
  101411. FLAC__BitWriter *frame; /* the current frame being worked on */
  101412. unsigned loose_mid_side_stereo_frames; /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
  101413. unsigned loose_mid_side_stereo_frame_count; /* number of frames using the current channel assignment */
  101414. FLAC__ChannelAssignment last_channel_assignment;
  101415. FLAC__StreamMetadata streaminfo; /* scratchpad for STREAMINFO as it is built */
  101416. FLAC__StreamMetadata_SeekTable *seek_table; /* pointer into encoder->protected_->metadata_ where the seek table is */
  101417. unsigned current_sample_number;
  101418. unsigned current_frame_number;
  101419. FLAC__MD5Context md5context;
  101420. FLAC__CPUInfo cpuinfo;
  101421. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101422. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  101423. #else
  101424. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  101425. #endif
  101426. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101427. void (*local_lpc_compute_autocorrelation)(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  101428. 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[]);
  101429. 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[]);
  101430. 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[]);
  101431. #endif
  101432. FLAC__bool use_wide_by_block; /* use slow 64-bit versions of some functions because of the block size */
  101433. FLAC__bool use_wide_by_partition; /* use slow 64-bit versions of some functions because of the min partition order and blocksize */
  101434. FLAC__bool use_wide_by_order; /* use slow 64-bit versions of some functions because of the lpc order */
  101435. FLAC__bool disable_constant_subframes;
  101436. FLAC__bool disable_fixed_subframes;
  101437. FLAC__bool disable_verbatim_subframes;
  101438. #if FLAC__HAS_OGG
  101439. FLAC__bool is_ogg;
  101440. #endif
  101441. FLAC__StreamEncoderReadCallback read_callback; /* currently only needed for Ogg FLAC */
  101442. FLAC__StreamEncoderSeekCallback seek_callback;
  101443. FLAC__StreamEncoderTellCallback tell_callback;
  101444. FLAC__StreamEncoderWriteCallback write_callback;
  101445. FLAC__StreamEncoderMetadataCallback metadata_callback;
  101446. FLAC__StreamEncoderProgressCallback progress_callback;
  101447. void *client_data;
  101448. unsigned first_seekpoint_to_check;
  101449. FILE *file; /* only used when encoding to a file */
  101450. FLAC__uint64 bytes_written;
  101451. FLAC__uint64 samples_written;
  101452. unsigned frames_written;
  101453. unsigned total_frames_estimate;
  101454. /* unaligned (original) pointers to allocated data */
  101455. FLAC__int32 *integer_signal_unaligned[FLAC__MAX_CHANNELS];
  101456. FLAC__int32 *integer_signal_mid_side_unaligned[2];
  101457. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101458. FLAC__real *real_signal_unaligned[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) */
  101459. FLAC__real *real_signal_mid_side_unaligned[2]; /* (@@@ currently unused) */
  101460. FLAC__real *window_unaligned[FLAC__MAX_APODIZATION_FUNCTIONS];
  101461. FLAC__real *windowed_signal_unaligned;
  101462. #endif
  101463. FLAC__int32 *residual_workspace_unaligned[FLAC__MAX_CHANNELS][2];
  101464. FLAC__int32 *residual_workspace_mid_side_unaligned[2][2];
  101465. FLAC__uint64 *abs_residual_partition_sums_unaligned;
  101466. unsigned *raw_bits_per_partition_unaligned;
  101467. /*
  101468. * These fields have been moved here from private function local
  101469. * declarations merely to save stack space during encoding.
  101470. */
  101471. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101472. FLAC__real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER]; /* from process_subframe_() */
  101473. #endif
  101474. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_extra[2]; /* from find_best_partition_order_() */
  101475. /*
  101476. * The data for the verify section
  101477. */
  101478. struct {
  101479. FLAC__StreamDecoder *decoder;
  101480. EncoderStateHint state_hint;
  101481. FLAC__bool needs_magic_hack;
  101482. verify_input_fifo input_fifo;
  101483. verify_output output;
  101484. struct {
  101485. FLAC__uint64 absolute_sample;
  101486. unsigned frame_number;
  101487. unsigned channel;
  101488. unsigned sample;
  101489. FLAC__int32 expected;
  101490. FLAC__int32 got;
  101491. } error_stats;
  101492. } verify;
  101493. FLAC__bool is_being_deleted; /* if true, call to ..._finish() from ..._delete() will not call the callbacks */
  101494. } FLAC__StreamEncoderPrivate;
  101495. /***********************************************************************
  101496. *
  101497. * Public static class data
  101498. *
  101499. ***********************************************************************/
  101500. FLAC_API const char * const FLAC__StreamEncoderStateString[] = {
  101501. "FLAC__STREAM_ENCODER_OK",
  101502. "FLAC__STREAM_ENCODER_UNINITIALIZED",
  101503. "FLAC__STREAM_ENCODER_OGG_ERROR",
  101504. "FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR",
  101505. "FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA",
  101506. "FLAC__STREAM_ENCODER_CLIENT_ERROR",
  101507. "FLAC__STREAM_ENCODER_IO_ERROR",
  101508. "FLAC__STREAM_ENCODER_FRAMING_ERROR",
  101509. "FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR"
  101510. };
  101511. FLAC_API const char * const FLAC__StreamEncoderInitStatusString[] = {
  101512. "FLAC__STREAM_ENCODER_INIT_STATUS_OK",
  101513. "FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR",
  101514. "FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  101515. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS",
  101516. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS",
  101517. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE",
  101518. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE",
  101519. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE",
  101520. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER",
  101521. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION",
  101522. "FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
  101523. "FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE",
  101524. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA",
  101525. "FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED"
  101526. };
  101527. FLAC_API const char * const FLAC__treamEncoderReadStatusString[] = {
  101528. "FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE",
  101529. "FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM",
  101530. "FLAC__STREAM_ENCODER_READ_STATUS_ABORT",
  101531. "FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED"
  101532. };
  101533. FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[] = {
  101534. "FLAC__STREAM_ENCODER_WRITE_STATUS_OK",
  101535. "FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR"
  101536. };
  101537. FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[] = {
  101538. "FLAC__STREAM_ENCODER_SEEK_STATUS_OK",
  101539. "FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR",
  101540. "FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED"
  101541. };
  101542. FLAC_API const char * const FLAC__StreamEncoderTellStatusString[] = {
  101543. "FLAC__STREAM_ENCODER_TELL_STATUS_OK",
  101544. "FLAC__STREAM_ENCODER_TELL_STATUS_ERROR",
  101545. "FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED"
  101546. };
  101547. /* Number of samples that will be overread to watch for end of stream. By
  101548. * 'overread', we mean that the FLAC__stream_encoder_process*() calls will
  101549. * always try to read blocksize+1 samples before encoding a block, so that
  101550. * even if the stream has a total sample count that is an integral multiple
  101551. * of the blocksize, we will still notice when we are encoding the last
  101552. * block. This is needed, for example, to correctly set the end-of-stream
  101553. * marker in Ogg FLAC.
  101554. *
  101555. * WATCHOUT: some parts of the code assert that OVERREAD_ == 1 and there's
  101556. * not really any reason to change it.
  101557. */
  101558. static const unsigned OVERREAD_ = 1;
  101559. /***********************************************************************
  101560. *
  101561. * Class constructor/destructor
  101562. *
  101563. */
  101564. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void)
  101565. {
  101566. FLAC__StreamEncoder *encoder;
  101567. unsigned i;
  101568. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  101569. encoder = (FLAC__StreamEncoder*)calloc(1, sizeof(FLAC__StreamEncoder));
  101570. if(encoder == 0) {
  101571. return 0;
  101572. }
  101573. encoder->protected_ = (FLAC__StreamEncoderProtected*)calloc(1, sizeof(FLAC__StreamEncoderProtected));
  101574. if(encoder->protected_ == 0) {
  101575. free(encoder);
  101576. return 0;
  101577. }
  101578. encoder->private_ = (FLAC__StreamEncoderPrivate*)calloc(1, sizeof(FLAC__StreamEncoderPrivate));
  101579. if(encoder->private_ == 0) {
  101580. free(encoder->protected_);
  101581. free(encoder);
  101582. return 0;
  101583. }
  101584. encoder->private_->frame = FLAC__bitwriter_new();
  101585. if(encoder->private_->frame == 0) {
  101586. free(encoder->private_);
  101587. free(encoder->protected_);
  101588. free(encoder);
  101589. return 0;
  101590. }
  101591. encoder->private_->file = 0;
  101592. set_defaults_enc(encoder);
  101593. encoder->private_->is_being_deleted = false;
  101594. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  101595. encoder->private_->subframe_workspace_ptr[i][0] = &encoder->private_->subframe_workspace[i][0];
  101596. encoder->private_->subframe_workspace_ptr[i][1] = &encoder->private_->subframe_workspace[i][1];
  101597. }
  101598. for(i = 0; i < 2; i++) {
  101599. encoder->private_->subframe_workspace_ptr_mid_side[i][0] = &encoder->private_->subframe_workspace_mid_side[i][0];
  101600. encoder->private_->subframe_workspace_ptr_mid_side[i][1] = &encoder->private_->subframe_workspace_mid_side[i][1];
  101601. }
  101602. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  101603. encoder->private_->partitioned_rice_contents_workspace_ptr[i][0] = &encoder->private_->partitioned_rice_contents_workspace[i][0];
  101604. encoder->private_->partitioned_rice_contents_workspace_ptr[i][1] = &encoder->private_->partitioned_rice_contents_workspace[i][1];
  101605. }
  101606. for(i = 0; i < 2; i++) {
  101607. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][0] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0];
  101608. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][1] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1];
  101609. }
  101610. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  101611. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  101612. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  101613. }
  101614. for(i = 0; i < 2; i++) {
  101615. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  101616. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  101617. }
  101618. for(i = 0; i < 2; i++)
  101619. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_extra[i]);
  101620. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  101621. return encoder;
  101622. }
  101623. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder)
  101624. {
  101625. unsigned i;
  101626. FLAC__ASSERT(0 != encoder);
  101627. FLAC__ASSERT(0 != encoder->protected_);
  101628. FLAC__ASSERT(0 != encoder->private_);
  101629. FLAC__ASSERT(0 != encoder->private_->frame);
  101630. encoder->private_->is_being_deleted = true;
  101631. (void)FLAC__stream_encoder_finish(encoder);
  101632. if(0 != encoder->private_->verify.decoder)
  101633. FLAC__stream_decoder_delete(encoder->private_->verify.decoder);
  101634. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  101635. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  101636. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  101637. }
  101638. for(i = 0; i < 2; i++) {
  101639. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  101640. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  101641. }
  101642. for(i = 0; i < 2; i++)
  101643. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_extra[i]);
  101644. FLAC__bitwriter_delete(encoder->private_->frame);
  101645. free(encoder->private_);
  101646. free(encoder->protected_);
  101647. free(encoder);
  101648. }
  101649. /***********************************************************************
  101650. *
  101651. * Public class methods
  101652. *
  101653. ***********************************************************************/
  101654. static FLAC__StreamEncoderInitStatus init_stream_internal_enc(
  101655. FLAC__StreamEncoder *encoder,
  101656. FLAC__StreamEncoderReadCallback read_callback,
  101657. FLAC__StreamEncoderWriteCallback write_callback,
  101658. FLAC__StreamEncoderSeekCallback seek_callback,
  101659. FLAC__StreamEncoderTellCallback tell_callback,
  101660. FLAC__StreamEncoderMetadataCallback metadata_callback,
  101661. void *client_data,
  101662. FLAC__bool is_ogg
  101663. )
  101664. {
  101665. unsigned i;
  101666. FLAC__bool metadata_has_seektable, metadata_has_vorbis_comment, metadata_picture_has_type1, metadata_picture_has_type2;
  101667. FLAC__ASSERT(0 != encoder);
  101668. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  101669. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  101670. #if !FLAC__HAS_OGG
  101671. if(is_ogg)
  101672. return FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  101673. #endif
  101674. if(0 == write_callback || (seek_callback && 0 == tell_callback))
  101675. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS;
  101676. if(encoder->protected_->channels == 0 || encoder->protected_->channels > FLAC__MAX_CHANNELS)
  101677. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS;
  101678. if(encoder->protected_->channels != 2) {
  101679. encoder->protected_->do_mid_side_stereo = false;
  101680. encoder->protected_->loose_mid_side_stereo = false;
  101681. }
  101682. else if(!encoder->protected_->do_mid_side_stereo)
  101683. encoder->protected_->loose_mid_side_stereo = false;
  101684. if(encoder->protected_->bits_per_sample >= 32)
  101685. encoder->protected_->do_mid_side_stereo = false; /* since we currenty do 32-bit math, the side channel would have 33 bps and overflow */
  101686. if(encoder->protected_->bits_per_sample < FLAC__MIN_BITS_PER_SAMPLE || encoder->protected_->bits_per_sample > FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE)
  101687. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE;
  101688. if(!FLAC__format_sample_rate_is_valid(encoder->protected_->sample_rate))
  101689. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE;
  101690. if(encoder->protected_->blocksize == 0) {
  101691. if(encoder->protected_->max_lpc_order == 0)
  101692. encoder->protected_->blocksize = 1152;
  101693. else
  101694. encoder->protected_->blocksize = 4096;
  101695. }
  101696. if(encoder->protected_->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->protected_->blocksize > FLAC__MAX_BLOCK_SIZE)
  101697. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE;
  101698. if(encoder->protected_->max_lpc_order > FLAC__MAX_LPC_ORDER)
  101699. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER;
  101700. if(encoder->protected_->blocksize < encoder->protected_->max_lpc_order)
  101701. return FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
  101702. if(encoder->protected_->qlp_coeff_precision == 0) {
  101703. if(encoder->protected_->bits_per_sample < 16) {
  101704. /* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */
  101705. /* @@@ until then we'll make a guess */
  101706. encoder->protected_->qlp_coeff_precision = max(FLAC__MIN_QLP_COEFF_PRECISION, 2 + encoder->protected_->bits_per_sample / 2);
  101707. }
  101708. else if(encoder->protected_->bits_per_sample == 16) {
  101709. if(encoder->protected_->blocksize <= 192)
  101710. encoder->protected_->qlp_coeff_precision = 7;
  101711. else if(encoder->protected_->blocksize <= 384)
  101712. encoder->protected_->qlp_coeff_precision = 8;
  101713. else if(encoder->protected_->blocksize <= 576)
  101714. encoder->protected_->qlp_coeff_precision = 9;
  101715. else if(encoder->protected_->blocksize <= 1152)
  101716. encoder->protected_->qlp_coeff_precision = 10;
  101717. else if(encoder->protected_->blocksize <= 2304)
  101718. encoder->protected_->qlp_coeff_precision = 11;
  101719. else if(encoder->protected_->blocksize <= 4608)
  101720. encoder->protected_->qlp_coeff_precision = 12;
  101721. else
  101722. encoder->protected_->qlp_coeff_precision = 13;
  101723. }
  101724. else {
  101725. if(encoder->protected_->blocksize <= 384)
  101726. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-2;
  101727. else if(encoder->protected_->blocksize <= 1152)
  101728. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-1;
  101729. else
  101730. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  101731. }
  101732. FLAC__ASSERT(encoder->protected_->qlp_coeff_precision <= FLAC__MAX_QLP_COEFF_PRECISION);
  101733. }
  101734. else if(encoder->protected_->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->protected_->qlp_coeff_precision > FLAC__MAX_QLP_COEFF_PRECISION)
  101735. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION;
  101736. if(encoder->protected_->streamable_subset) {
  101737. if(
  101738. encoder->protected_->blocksize != 192 &&
  101739. encoder->protected_->blocksize != 576 &&
  101740. encoder->protected_->blocksize != 1152 &&
  101741. encoder->protected_->blocksize != 2304 &&
  101742. encoder->protected_->blocksize != 4608 &&
  101743. encoder->protected_->blocksize != 256 &&
  101744. encoder->protected_->blocksize != 512 &&
  101745. encoder->protected_->blocksize != 1024 &&
  101746. encoder->protected_->blocksize != 2048 &&
  101747. encoder->protected_->blocksize != 4096 &&
  101748. encoder->protected_->blocksize != 8192 &&
  101749. encoder->protected_->blocksize != 16384
  101750. )
  101751. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  101752. if(!FLAC__format_sample_rate_is_subset(encoder->protected_->sample_rate))
  101753. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  101754. if(
  101755. encoder->protected_->bits_per_sample != 8 &&
  101756. encoder->protected_->bits_per_sample != 12 &&
  101757. encoder->protected_->bits_per_sample != 16 &&
  101758. encoder->protected_->bits_per_sample != 20 &&
  101759. encoder->protected_->bits_per_sample != 24
  101760. )
  101761. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  101762. if(encoder->protected_->max_residual_partition_order > FLAC__SUBSET_MAX_RICE_PARTITION_ORDER)
  101763. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  101764. if(
  101765. encoder->protected_->sample_rate <= 48000 &&
  101766. (
  101767. encoder->protected_->blocksize > FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ ||
  101768. encoder->protected_->max_lpc_order > FLAC__SUBSET_MAX_LPC_ORDER_48000HZ
  101769. )
  101770. ) {
  101771. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  101772. }
  101773. }
  101774. if(encoder->protected_->max_residual_partition_order >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  101775. encoder->protected_->max_residual_partition_order = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
  101776. if(encoder->protected_->min_residual_partition_order >= encoder->protected_->max_residual_partition_order)
  101777. encoder->protected_->min_residual_partition_order = encoder->protected_->max_residual_partition_order;
  101778. #if FLAC__HAS_OGG
  101779. /* reorder metadata if necessary to ensure that any VORBIS_COMMENT is the first, according to the mapping spec */
  101780. if(is_ogg && 0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 1) {
  101781. unsigned i;
  101782. for(i = 1; i < encoder->protected_->num_metadata_blocks; i++) {
  101783. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  101784. FLAC__StreamMetadata *vc = encoder->protected_->metadata[i];
  101785. for( ; i > 0; i--)
  101786. encoder->protected_->metadata[i] = encoder->protected_->metadata[i-1];
  101787. encoder->protected_->metadata[0] = vc;
  101788. break;
  101789. }
  101790. }
  101791. }
  101792. #endif
  101793. /* keep track of any SEEKTABLE block */
  101794. if(0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0) {
  101795. unsigned i;
  101796. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  101797. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  101798. encoder->private_->seek_table = &encoder->protected_->metadata[i]->data.seek_table;
  101799. break; /* take only the first one */
  101800. }
  101801. }
  101802. }
  101803. /* validate metadata */
  101804. if(0 == encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0)
  101805. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  101806. metadata_has_seektable = false;
  101807. metadata_has_vorbis_comment = false;
  101808. metadata_picture_has_type1 = false;
  101809. metadata_picture_has_type2 = false;
  101810. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  101811. const FLAC__StreamMetadata *m = encoder->protected_->metadata[i];
  101812. if(m->type == FLAC__METADATA_TYPE_STREAMINFO)
  101813. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  101814. else if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  101815. if(metadata_has_seektable) /* only one is allowed */
  101816. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  101817. metadata_has_seektable = true;
  101818. if(!FLAC__format_seektable_is_legal(&m->data.seek_table))
  101819. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  101820. }
  101821. else if(m->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  101822. if(metadata_has_vorbis_comment) /* only one is allowed */
  101823. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  101824. metadata_has_vorbis_comment = true;
  101825. }
  101826. else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
  101827. if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0))
  101828. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  101829. }
  101830. else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
  101831. if(!FLAC__format_picture_is_legal(&m->data.picture, /*violation=*/0))
  101832. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  101833. if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
  101834. if(metadata_picture_has_type1) /* there should only be 1 per stream */
  101835. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  101836. metadata_picture_has_type1 = true;
  101837. /* standard icon must be 32x32 pixel PNG */
  101838. if(
  101839. m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD &&
  101840. (
  101841. (strcmp(m->data.picture.mime_type, "image/png") && strcmp(m->data.picture.mime_type, "-->")) ||
  101842. m->data.picture.width != 32 ||
  101843. m->data.picture.height != 32
  101844. )
  101845. )
  101846. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  101847. }
  101848. else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
  101849. if(metadata_picture_has_type2) /* there should only be 1 per stream */
  101850. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  101851. metadata_picture_has_type2 = true;
  101852. }
  101853. }
  101854. }
  101855. encoder->private_->input_capacity = 0;
  101856. for(i = 0; i < encoder->protected_->channels; i++) {
  101857. encoder->private_->integer_signal_unaligned[i] = encoder->private_->integer_signal[i] = 0;
  101858. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101859. encoder->private_->real_signal_unaligned[i] = encoder->private_->real_signal[i] = 0;
  101860. #endif
  101861. }
  101862. for(i = 0; i < 2; i++) {
  101863. encoder->private_->integer_signal_mid_side_unaligned[i] = encoder->private_->integer_signal_mid_side[i] = 0;
  101864. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101865. encoder->private_->real_signal_mid_side_unaligned[i] = encoder->private_->real_signal_mid_side[i] = 0;
  101866. #endif
  101867. }
  101868. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101869. for(i = 0; i < encoder->protected_->num_apodizations; i++)
  101870. encoder->private_->window_unaligned[i] = encoder->private_->window[i] = 0;
  101871. encoder->private_->windowed_signal_unaligned = encoder->private_->windowed_signal = 0;
  101872. #endif
  101873. for(i = 0; i < encoder->protected_->channels; i++) {
  101874. encoder->private_->residual_workspace_unaligned[i][0] = encoder->private_->residual_workspace[i][0] = 0;
  101875. encoder->private_->residual_workspace_unaligned[i][1] = encoder->private_->residual_workspace[i][1] = 0;
  101876. encoder->private_->best_subframe[i] = 0;
  101877. }
  101878. for(i = 0; i < 2; i++) {
  101879. encoder->private_->residual_workspace_mid_side_unaligned[i][0] = encoder->private_->residual_workspace_mid_side[i][0] = 0;
  101880. encoder->private_->residual_workspace_mid_side_unaligned[i][1] = encoder->private_->residual_workspace_mid_side[i][1] = 0;
  101881. encoder->private_->best_subframe_mid_side[i] = 0;
  101882. }
  101883. encoder->private_->abs_residual_partition_sums_unaligned = encoder->private_->abs_residual_partition_sums = 0;
  101884. encoder->private_->raw_bits_per_partition_unaligned = encoder->private_->raw_bits_per_partition = 0;
  101885. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101886. encoder->private_->loose_mid_side_stereo_frames = (unsigned)((FLAC__double)encoder->protected_->sample_rate * 0.4 / (FLAC__double)encoder->protected_->blocksize + 0.5);
  101887. #else
  101888. /* 26214 is the approximate fixed-point equivalent to 0.4 (0.4 * 2^16) */
  101889. /* sample rate can be up to 655350 Hz, and thus use 20 bits, so we do the multiply&divide by hand */
  101890. FLAC__ASSERT(FLAC__MAX_SAMPLE_RATE <= 655350);
  101891. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535);
  101892. FLAC__ASSERT(encoder->protected_->sample_rate <= 655350);
  101893. FLAC__ASSERT(encoder->protected_->blocksize <= 65535);
  101894. 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);
  101895. #endif
  101896. if(encoder->private_->loose_mid_side_stereo_frames == 0)
  101897. encoder->private_->loose_mid_side_stereo_frames = 1;
  101898. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  101899. encoder->private_->current_sample_number = 0;
  101900. encoder->private_->current_frame_number = 0;
  101901. encoder->private_->use_wide_by_block = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(encoder->protected_->blocksize)+1 > 30);
  101902. 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? */
  101903. encoder->private_->use_wide_by_partition = (false); /*@@@ need to set this */
  101904. /*
  101905. * get the CPU info and set the function pointers
  101906. */
  101907. FLAC__cpu_info(&encoder->private_->cpuinfo);
  101908. /* first default to the non-asm routines */
  101909. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101910. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
  101911. #endif
  101912. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor;
  101913. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101914. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients;
  101915. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide;
  101916. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients;
  101917. #endif
  101918. /* now override with asm where appropriate */
  101919. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101920. # ifndef FLAC__NO_ASM
  101921. if(encoder->private_->cpuinfo.use_asm) {
  101922. # ifdef FLAC__CPU_IA32
  101923. FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  101924. # ifdef FLAC__HAS_NASM
  101925. if(encoder->private_->cpuinfo.data.ia32.sse) {
  101926. if(encoder->protected_->max_lpc_order < 4)
  101927. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4;
  101928. else if(encoder->protected_->max_lpc_order < 8)
  101929. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8;
  101930. else if(encoder->protected_->max_lpc_order < 12)
  101931. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12;
  101932. else
  101933. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  101934. }
  101935. else if(encoder->private_->cpuinfo.data.ia32._3dnow)
  101936. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow;
  101937. else
  101938. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  101939. if(encoder->private_->cpuinfo.data.ia32.mmx) {
  101940. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  101941. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx;
  101942. }
  101943. else {
  101944. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  101945. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  101946. }
  101947. if(encoder->private_->cpuinfo.data.ia32.mmx && encoder->private_->cpuinfo.data.ia32.cmov)
  101948. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov;
  101949. # endif /* FLAC__HAS_NASM */
  101950. # endif /* FLAC__CPU_IA32 */
  101951. }
  101952. # endif /* !FLAC__NO_ASM */
  101953. #endif /* !FLAC__INTEGER_ONLY_LIBRARY */
  101954. /* finally override based on wide-ness if necessary */
  101955. if(encoder->private_->use_wide_by_block) {
  101956. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_wide;
  101957. }
  101958. /* set state to OK; from here on, errors are fatal and we'll override the state then */
  101959. encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
  101960. #if FLAC__HAS_OGG
  101961. encoder->private_->is_ogg = is_ogg;
  101962. if(is_ogg && !FLAC__ogg_encoder_aspect_init(&encoder->protected_->ogg_encoder_aspect)) {
  101963. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  101964. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  101965. }
  101966. #endif
  101967. encoder->private_->read_callback = read_callback;
  101968. encoder->private_->write_callback = write_callback;
  101969. encoder->private_->seek_callback = seek_callback;
  101970. encoder->private_->tell_callback = tell_callback;
  101971. encoder->private_->metadata_callback = metadata_callback;
  101972. encoder->private_->client_data = client_data;
  101973. if(!resize_buffers_(encoder, encoder->protected_->blocksize)) {
  101974. /* the above function sets the state for us in case of an error */
  101975. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  101976. }
  101977. if(!FLAC__bitwriter_init(encoder->private_->frame)) {
  101978. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  101979. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  101980. }
  101981. /*
  101982. * Set up the verify stuff if necessary
  101983. */
  101984. if(encoder->protected_->verify) {
  101985. /*
  101986. * First, set up the fifo which will hold the
  101987. * original signal to compare against
  101988. */
  101989. encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize+OVERREAD_;
  101990. for(i = 0; i < encoder->protected_->channels; i++) {
  101991. 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))) {
  101992. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  101993. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  101994. }
  101995. }
  101996. encoder->private_->verify.input_fifo.tail = 0;
  101997. /*
  101998. * Now set up a stream decoder for verification
  101999. */
  102000. encoder->private_->verify.decoder = FLAC__stream_decoder_new();
  102001. if(0 == encoder->private_->verify.decoder) {
  102002. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  102003. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102004. }
  102005. 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) {
  102006. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  102007. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102008. }
  102009. }
  102010. encoder->private_->verify.error_stats.absolute_sample = 0;
  102011. encoder->private_->verify.error_stats.frame_number = 0;
  102012. encoder->private_->verify.error_stats.channel = 0;
  102013. encoder->private_->verify.error_stats.sample = 0;
  102014. encoder->private_->verify.error_stats.expected = 0;
  102015. encoder->private_->verify.error_stats.got = 0;
  102016. /*
  102017. * These must be done before we write any metadata, because that
  102018. * calls the write_callback, which uses these values.
  102019. */
  102020. encoder->private_->first_seekpoint_to_check = 0;
  102021. encoder->private_->samples_written = 0;
  102022. encoder->protected_->streaminfo_offset = 0;
  102023. encoder->protected_->seektable_offset = 0;
  102024. encoder->protected_->audio_offset = 0;
  102025. /*
  102026. * write the stream header
  102027. */
  102028. if(encoder->protected_->verify)
  102029. encoder->private_->verify.state_hint = ENCODER_IN_MAGIC;
  102030. if(!FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN)) {
  102031. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  102032. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102033. }
  102034. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  102035. /* the above function sets the state for us in case of an error */
  102036. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102037. }
  102038. /*
  102039. * write the STREAMINFO metadata block
  102040. */
  102041. if(encoder->protected_->verify)
  102042. encoder->private_->verify.state_hint = ENCODER_IN_METADATA;
  102043. encoder->private_->streaminfo.type = FLAC__METADATA_TYPE_STREAMINFO;
  102044. encoder->private_->streaminfo.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */
  102045. encoder->private_->streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
  102046. encoder->private_->streaminfo.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
  102047. encoder->private_->streaminfo.data.stream_info.max_blocksize = encoder->protected_->blocksize;
  102048. encoder->private_->streaminfo.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
  102049. encoder->private_->streaminfo.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
  102050. encoder->private_->streaminfo.data.stream_info.sample_rate = encoder->protected_->sample_rate;
  102051. encoder->private_->streaminfo.data.stream_info.channels = encoder->protected_->channels;
  102052. encoder->private_->streaminfo.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
  102053. encoder->private_->streaminfo.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
  102054. memset(encoder->private_->streaminfo.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
  102055. if(encoder->protected_->do_md5)
  102056. FLAC__MD5Init(&encoder->private_->md5context);
  102057. if(!FLAC__add_metadata_block(&encoder->private_->streaminfo, encoder->private_->frame)) {
  102058. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  102059. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102060. }
  102061. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  102062. /* the above function sets the state for us in case of an error */
  102063. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102064. }
  102065. /*
  102066. * Now that the STREAMINFO block is written, we can init this to an
  102067. * absurdly-high value...
  102068. */
  102069. encoder->private_->streaminfo.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
  102070. /* ... and clear this to 0 */
  102071. encoder->private_->streaminfo.data.stream_info.total_samples = 0;
  102072. /*
  102073. * Check to see if the supplied metadata contains a VORBIS_COMMENT;
  102074. * if not, we will write an empty one (FLAC__add_metadata_block()
  102075. * automatically supplies the vendor string).
  102076. *
  102077. * WATCHOUT: the Ogg FLAC mapping requires us to write this block after
  102078. * the STREAMINFO. (In the case that metadata_has_vorbis_comment is
  102079. * true it will have already insured that the metadata list is properly
  102080. * ordered.)
  102081. */
  102082. if(!metadata_has_vorbis_comment) {
  102083. FLAC__StreamMetadata vorbis_comment;
  102084. vorbis_comment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
  102085. vorbis_comment.is_last = (encoder->protected_->num_metadata_blocks == 0);
  102086. vorbis_comment.length = 4 + 4; /* MAGIC NUMBER */
  102087. vorbis_comment.data.vorbis_comment.vendor_string.length = 0;
  102088. vorbis_comment.data.vorbis_comment.vendor_string.entry = 0;
  102089. vorbis_comment.data.vorbis_comment.num_comments = 0;
  102090. vorbis_comment.data.vorbis_comment.comments = 0;
  102091. if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame)) {
  102092. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  102093. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102094. }
  102095. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  102096. /* the above function sets the state for us in case of an error */
  102097. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102098. }
  102099. }
  102100. /*
  102101. * write the user's metadata blocks
  102102. */
  102103. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  102104. encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1);
  102105. if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame)) {
  102106. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  102107. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102108. }
  102109. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  102110. /* the above function sets the state for us in case of an error */
  102111. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102112. }
  102113. }
  102114. /* now that all the metadata is written, we save the stream offset */
  102115. 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 */
  102116. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  102117. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102118. }
  102119. if(encoder->protected_->verify)
  102120. encoder->private_->verify.state_hint = ENCODER_IN_AUDIO;
  102121. return FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  102122. }
  102123. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(
  102124. FLAC__StreamEncoder *encoder,
  102125. FLAC__StreamEncoderWriteCallback write_callback,
  102126. FLAC__StreamEncoderSeekCallback seek_callback,
  102127. FLAC__StreamEncoderTellCallback tell_callback,
  102128. FLAC__StreamEncoderMetadataCallback metadata_callback,
  102129. void *client_data
  102130. )
  102131. {
  102132. return init_stream_internal_enc(
  102133. encoder,
  102134. /*read_callback=*/0,
  102135. write_callback,
  102136. seek_callback,
  102137. tell_callback,
  102138. metadata_callback,
  102139. client_data,
  102140. /*is_ogg=*/false
  102141. );
  102142. }
  102143. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(
  102144. FLAC__StreamEncoder *encoder,
  102145. FLAC__StreamEncoderReadCallback read_callback,
  102146. FLAC__StreamEncoderWriteCallback write_callback,
  102147. FLAC__StreamEncoderSeekCallback seek_callback,
  102148. FLAC__StreamEncoderTellCallback tell_callback,
  102149. FLAC__StreamEncoderMetadataCallback metadata_callback,
  102150. void *client_data
  102151. )
  102152. {
  102153. return init_stream_internal_enc(
  102154. encoder,
  102155. read_callback,
  102156. write_callback,
  102157. seek_callback,
  102158. tell_callback,
  102159. metadata_callback,
  102160. client_data,
  102161. /*is_ogg=*/true
  102162. );
  102163. }
  102164. static FLAC__StreamEncoderInitStatus init_FILE_internal_enc(
  102165. FLAC__StreamEncoder *encoder,
  102166. FILE *file,
  102167. FLAC__StreamEncoderProgressCallback progress_callback,
  102168. void *client_data,
  102169. FLAC__bool is_ogg
  102170. )
  102171. {
  102172. FLAC__StreamEncoderInitStatus init_status;
  102173. FLAC__ASSERT(0 != encoder);
  102174. FLAC__ASSERT(0 != file);
  102175. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102176. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  102177. /* double protection */
  102178. if(file == 0) {
  102179. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  102180. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102181. }
  102182. /*
  102183. * To make sure that our file does not go unclosed after an error, we
  102184. * must assign the FILE pointer before any further error can occur in
  102185. * this routine.
  102186. */
  102187. if(file == stdout)
  102188. file = get_binary_stdout_(); /* just to be safe */
  102189. encoder->private_->file = file;
  102190. encoder->private_->progress_callback = progress_callback;
  102191. encoder->private_->bytes_written = 0;
  102192. encoder->private_->samples_written = 0;
  102193. encoder->private_->frames_written = 0;
  102194. init_status = init_stream_internal_enc(
  102195. encoder,
  102196. encoder->private_->file == stdout? 0 : is_ogg? file_read_callback_enc : 0,
  102197. file_write_callback_,
  102198. encoder->private_->file == stdout? 0 : file_seek_callback_enc,
  102199. encoder->private_->file == stdout? 0 : file_tell_callback_enc,
  102200. /*metadata_callback=*/0,
  102201. client_data,
  102202. is_ogg
  102203. );
  102204. if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
  102205. /* the above function sets the state for us in case of an error */
  102206. return init_status;
  102207. }
  102208. {
  102209. unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  102210. FLAC__ASSERT(blocksize != 0);
  102211. encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
  102212. }
  102213. return init_status;
  102214. }
  102215. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(
  102216. FLAC__StreamEncoder *encoder,
  102217. FILE *file,
  102218. FLAC__StreamEncoderProgressCallback progress_callback,
  102219. void *client_data
  102220. )
  102221. {
  102222. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/false);
  102223. }
  102224. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(
  102225. FLAC__StreamEncoder *encoder,
  102226. FILE *file,
  102227. FLAC__StreamEncoderProgressCallback progress_callback,
  102228. void *client_data
  102229. )
  102230. {
  102231. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/true);
  102232. }
  102233. static FLAC__StreamEncoderInitStatus init_file_internal_enc(
  102234. FLAC__StreamEncoder *encoder,
  102235. const char *filename,
  102236. FLAC__StreamEncoderProgressCallback progress_callback,
  102237. void *client_data,
  102238. FLAC__bool is_ogg
  102239. )
  102240. {
  102241. FILE *file;
  102242. FLAC__ASSERT(0 != encoder);
  102243. /*
  102244. * To make sure that our file does not go unclosed after an error, we
  102245. * have to do the same entrance checks here that are later performed
  102246. * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
  102247. */
  102248. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102249. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  102250. file = filename? fopen(filename, "w+b") : stdout;
  102251. if(file == 0) {
  102252. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  102253. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102254. }
  102255. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, is_ogg);
  102256. }
  102257. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(
  102258. FLAC__StreamEncoder *encoder,
  102259. const char *filename,
  102260. FLAC__StreamEncoderProgressCallback progress_callback,
  102261. void *client_data
  102262. )
  102263. {
  102264. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/false);
  102265. }
  102266. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(
  102267. FLAC__StreamEncoder *encoder,
  102268. const char *filename,
  102269. FLAC__StreamEncoderProgressCallback progress_callback,
  102270. void *client_data
  102271. )
  102272. {
  102273. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/true);
  102274. }
  102275. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
  102276. {
  102277. FLAC__bool error = false;
  102278. FLAC__ASSERT(0 != encoder);
  102279. FLAC__ASSERT(0 != encoder->private_);
  102280. FLAC__ASSERT(0 != encoder->protected_);
  102281. if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
  102282. return true;
  102283. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
  102284. if(encoder->private_->current_sample_number != 0) {
  102285. const FLAC__bool is_fractional_block = encoder->protected_->blocksize != encoder->private_->current_sample_number;
  102286. encoder->protected_->blocksize = encoder->private_->current_sample_number;
  102287. if(!process_frame_(encoder, is_fractional_block, /*is_last_block=*/true))
  102288. error = true;
  102289. }
  102290. }
  102291. if(encoder->protected_->do_md5)
  102292. FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
  102293. if(!encoder->private_->is_being_deleted) {
  102294. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK) {
  102295. if(encoder->private_->seek_callback) {
  102296. #if FLAC__HAS_OGG
  102297. if(encoder->private_->is_ogg)
  102298. update_ogg_metadata_(encoder);
  102299. else
  102300. #endif
  102301. update_metadata_(encoder);
  102302. /* check if an error occurred while updating metadata */
  102303. if(encoder->protected_->state != FLAC__STREAM_ENCODER_OK)
  102304. error = true;
  102305. }
  102306. if(encoder->private_->metadata_callback)
  102307. encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
  102308. }
  102309. if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder && !FLAC__stream_decoder_finish(encoder->private_->verify.decoder)) {
  102310. if(!error)
  102311. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  102312. error = true;
  102313. }
  102314. }
  102315. if(0 != encoder->private_->file) {
  102316. if(encoder->private_->file != stdout)
  102317. fclose(encoder->private_->file);
  102318. encoder->private_->file = 0;
  102319. }
  102320. #if FLAC__HAS_OGG
  102321. if(encoder->private_->is_ogg)
  102322. FLAC__ogg_encoder_aspect_finish(&encoder->protected_->ogg_encoder_aspect);
  102323. #endif
  102324. free_(encoder);
  102325. set_defaults_enc(encoder);
  102326. if(!error)
  102327. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  102328. return !error;
  102329. }
  102330. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long value)
  102331. {
  102332. FLAC__ASSERT(0 != encoder);
  102333. FLAC__ASSERT(0 != encoder->private_);
  102334. FLAC__ASSERT(0 != encoder->protected_);
  102335. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102336. return false;
  102337. #if FLAC__HAS_OGG
  102338. /* can't check encoder->private_->is_ogg since that's not set until init time */
  102339. FLAC__ogg_encoder_aspect_set_serial_number(&encoder->protected_->ogg_encoder_aspect, value);
  102340. return true;
  102341. #else
  102342. (void)value;
  102343. return false;
  102344. #endif
  102345. }
  102346. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value)
  102347. {
  102348. FLAC__ASSERT(0 != encoder);
  102349. FLAC__ASSERT(0 != encoder->private_);
  102350. FLAC__ASSERT(0 != encoder->protected_);
  102351. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102352. return false;
  102353. #ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  102354. encoder->protected_->verify = value;
  102355. #endif
  102356. return true;
  102357. }
  102358. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
  102359. {
  102360. FLAC__ASSERT(0 != encoder);
  102361. FLAC__ASSERT(0 != encoder->private_);
  102362. FLAC__ASSERT(0 != encoder->protected_);
  102363. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102364. return false;
  102365. encoder->protected_->streamable_subset = value;
  102366. return true;
  102367. }
  102368. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_md5(FLAC__StreamEncoder *encoder, FLAC__bool value)
  102369. {
  102370. FLAC__ASSERT(0 != encoder);
  102371. FLAC__ASSERT(0 != encoder->private_);
  102372. FLAC__ASSERT(0 != encoder->protected_);
  102373. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102374. return false;
  102375. encoder->protected_->do_md5 = value;
  102376. return true;
  102377. }
  102378. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value)
  102379. {
  102380. FLAC__ASSERT(0 != encoder);
  102381. FLAC__ASSERT(0 != encoder->private_);
  102382. FLAC__ASSERT(0 != encoder->protected_);
  102383. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102384. return false;
  102385. encoder->protected_->channels = value;
  102386. return true;
  102387. }
  102388. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value)
  102389. {
  102390. FLAC__ASSERT(0 != encoder);
  102391. FLAC__ASSERT(0 != encoder->private_);
  102392. FLAC__ASSERT(0 != encoder->protected_);
  102393. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102394. return false;
  102395. encoder->protected_->bits_per_sample = value;
  102396. return true;
  102397. }
  102398. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value)
  102399. {
  102400. FLAC__ASSERT(0 != encoder);
  102401. FLAC__ASSERT(0 != encoder->private_);
  102402. FLAC__ASSERT(0 != encoder->protected_);
  102403. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102404. return false;
  102405. encoder->protected_->sample_rate = value;
  102406. return true;
  102407. }
  102408. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value)
  102409. {
  102410. FLAC__bool ok = true;
  102411. FLAC__ASSERT(0 != encoder);
  102412. FLAC__ASSERT(0 != encoder->private_);
  102413. FLAC__ASSERT(0 != encoder->protected_);
  102414. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102415. return false;
  102416. if(value >= sizeof(compression_levels_)/sizeof(compression_levels_[0]))
  102417. value = sizeof(compression_levels_)/sizeof(compression_levels_[0]) - 1;
  102418. ok &= FLAC__stream_encoder_set_do_mid_side_stereo (encoder, compression_levels_[value].do_mid_side_stereo);
  102419. ok &= FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, compression_levels_[value].loose_mid_side_stereo);
  102420. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102421. #if 0
  102422. /* was: */
  102423. ok &= FLAC__stream_encoder_set_apodization (encoder, compression_levels_[value].apodization);
  102424. /* but it's too hard to specify the string in a locale-specific way */
  102425. #else
  102426. encoder->protected_->num_apodizations = 1;
  102427. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  102428. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  102429. #endif
  102430. #endif
  102431. ok &= FLAC__stream_encoder_set_max_lpc_order (encoder, compression_levels_[value].max_lpc_order);
  102432. ok &= FLAC__stream_encoder_set_qlp_coeff_precision (encoder, compression_levels_[value].qlp_coeff_precision);
  102433. ok &= FLAC__stream_encoder_set_do_qlp_coeff_prec_search (encoder, compression_levels_[value].do_qlp_coeff_prec_search);
  102434. ok &= FLAC__stream_encoder_set_do_escape_coding (encoder, compression_levels_[value].do_escape_coding);
  102435. ok &= FLAC__stream_encoder_set_do_exhaustive_model_search (encoder, compression_levels_[value].do_exhaustive_model_search);
  102436. ok &= FLAC__stream_encoder_set_min_residual_partition_order(encoder, compression_levels_[value].min_residual_partition_order);
  102437. ok &= FLAC__stream_encoder_set_max_residual_partition_order(encoder, compression_levels_[value].max_residual_partition_order);
  102438. ok &= FLAC__stream_encoder_set_rice_parameter_search_dist (encoder, compression_levels_[value].rice_parameter_search_dist);
  102439. return ok;
  102440. }
  102441. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
  102442. {
  102443. FLAC__ASSERT(0 != encoder);
  102444. FLAC__ASSERT(0 != encoder->private_);
  102445. FLAC__ASSERT(0 != encoder->protected_);
  102446. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102447. return false;
  102448. encoder->protected_->blocksize = value;
  102449. return true;
  102450. }
  102451. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  102452. {
  102453. FLAC__ASSERT(0 != encoder);
  102454. FLAC__ASSERT(0 != encoder->private_);
  102455. FLAC__ASSERT(0 != encoder->protected_);
  102456. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102457. return false;
  102458. encoder->protected_->do_mid_side_stereo = value;
  102459. return true;
  102460. }
  102461. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  102462. {
  102463. FLAC__ASSERT(0 != encoder);
  102464. FLAC__ASSERT(0 != encoder->private_);
  102465. FLAC__ASSERT(0 != encoder->protected_);
  102466. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102467. return false;
  102468. encoder->protected_->loose_mid_side_stereo = value;
  102469. return true;
  102470. }
  102471. /*@@@@add to tests*/
  102472. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
  102473. {
  102474. FLAC__ASSERT(0 != encoder);
  102475. FLAC__ASSERT(0 != encoder->private_);
  102476. FLAC__ASSERT(0 != encoder->protected_);
  102477. FLAC__ASSERT(0 != specification);
  102478. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102479. return false;
  102480. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  102481. (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
  102482. #else
  102483. encoder->protected_->num_apodizations = 0;
  102484. while(1) {
  102485. const char *s = strchr(specification, ';');
  102486. const size_t n = s? (size_t)(s - specification) : strlen(specification);
  102487. if (n==8 && 0 == strncmp("bartlett" , specification, n))
  102488. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
  102489. else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
  102490. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
  102491. else if(n==8 && 0 == strncmp("blackman" , specification, n))
  102492. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
  102493. else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
  102494. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
  102495. else if(n==6 && 0 == strncmp("connes" , specification, n))
  102496. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
  102497. else if(n==7 && 0 == strncmp("flattop" , specification, n))
  102498. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
  102499. else if(n>7 && 0 == strncmp("gauss(" , specification, 6)) {
  102500. FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
  102501. if (stddev > 0.0 && stddev <= 0.5) {
  102502. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
  102503. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
  102504. }
  102505. }
  102506. else if(n==7 && 0 == strncmp("hamming" , specification, n))
  102507. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
  102508. else if(n==4 && 0 == strncmp("hann" , specification, n))
  102509. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
  102510. else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
  102511. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
  102512. else if(n==7 && 0 == strncmp("nuttall" , specification, n))
  102513. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
  102514. else if(n==9 && 0 == strncmp("rectangle" , specification, n))
  102515. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
  102516. else if(n==8 && 0 == strncmp("triangle" , specification, n))
  102517. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
  102518. else if(n>7 && 0 == strncmp("tukey(" , specification, 6)) {
  102519. FLAC__real p = (FLAC__real)strtod(specification+6, 0);
  102520. if (p >= 0.0 && p <= 1.0) {
  102521. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
  102522. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
  102523. }
  102524. }
  102525. else if(n==5 && 0 == strncmp("welch" , specification, n))
  102526. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
  102527. if (encoder->protected_->num_apodizations == 32)
  102528. break;
  102529. if (s)
  102530. specification = s+1;
  102531. else
  102532. break;
  102533. }
  102534. if(encoder->protected_->num_apodizations == 0) {
  102535. encoder->protected_->num_apodizations = 1;
  102536. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  102537. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  102538. }
  102539. #endif
  102540. return true;
  102541. }
  102542. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
  102543. {
  102544. FLAC__ASSERT(0 != encoder);
  102545. FLAC__ASSERT(0 != encoder->private_);
  102546. FLAC__ASSERT(0 != encoder->protected_);
  102547. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102548. return false;
  102549. encoder->protected_->max_lpc_order = value;
  102550. return true;
  102551. }
  102552. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
  102553. {
  102554. FLAC__ASSERT(0 != encoder);
  102555. FLAC__ASSERT(0 != encoder->private_);
  102556. FLAC__ASSERT(0 != encoder->protected_);
  102557. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102558. return false;
  102559. encoder->protected_->qlp_coeff_precision = value;
  102560. return true;
  102561. }
  102562. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  102563. {
  102564. FLAC__ASSERT(0 != encoder);
  102565. FLAC__ASSERT(0 != encoder->private_);
  102566. FLAC__ASSERT(0 != encoder->protected_);
  102567. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102568. return false;
  102569. encoder->protected_->do_qlp_coeff_prec_search = value;
  102570. return true;
  102571. }
  102572. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value)
  102573. {
  102574. FLAC__ASSERT(0 != encoder);
  102575. FLAC__ASSERT(0 != encoder->private_);
  102576. FLAC__ASSERT(0 != encoder->protected_);
  102577. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102578. return false;
  102579. #if 0
  102580. /*@@@ deprecated: */
  102581. encoder->protected_->do_escape_coding = value;
  102582. #else
  102583. (void)value;
  102584. #endif
  102585. return true;
  102586. }
  102587. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  102588. {
  102589. FLAC__ASSERT(0 != encoder);
  102590. FLAC__ASSERT(0 != encoder->private_);
  102591. FLAC__ASSERT(0 != encoder->protected_);
  102592. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102593. return false;
  102594. encoder->protected_->do_exhaustive_model_search = value;
  102595. return true;
  102596. }
  102597. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  102598. {
  102599. FLAC__ASSERT(0 != encoder);
  102600. FLAC__ASSERT(0 != encoder->private_);
  102601. FLAC__ASSERT(0 != encoder->protected_);
  102602. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102603. return false;
  102604. encoder->protected_->min_residual_partition_order = value;
  102605. return true;
  102606. }
  102607. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  102608. {
  102609. FLAC__ASSERT(0 != encoder);
  102610. FLAC__ASSERT(0 != encoder->private_);
  102611. FLAC__ASSERT(0 != encoder->protected_);
  102612. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102613. return false;
  102614. encoder->protected_->max_residual_partition_order = value;
  102615. return true;
  102616. }
  102617. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value)
  102618. {
  102619. FLAC__ASSERT(0 != encoder);
  102620. FLAC__ASSERT(0 != encoder->private_);
  102621. FLAC__ASSERT(0 != encoder->protected_);
  102622. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102623. return false;
  102624. #if 0
  102625. /*@@@ deprecated: */
  102626. encoder->protected_->rice_parameter_search_dist = value;
  102627. #else
  102628. (void)value;
  102629. #endif
  102630. return true;
  102631. }
  102632. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
  102633. {
  102634. FLAC__ASSERT(0 != encoder);
  102635. FLAC__ASSERT(0 != encoder->private_);
  102636. FLAC__ASSERT(0 != encoder->protected_);
  102637. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102638. return false;
  102639. encoder->protected_->total_samples_estimate = value;
  102640. return true;
  102641. }
  102642. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
  102643. {
  102644. FLAC__ASSERT(0 != encoder);
  102645. FLAC__ASSERT(0 != encoder->private_);
  102646. FLAC__ASSERT(0 != encoder->protected_);
  102647. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102648. return false;
  102649. if(0 == metadata)
  102650. num_blocks = 0;
  102651. if(0 == num_blocks)
  102652. metadata = 0;
  102653. /* realloc() does not do exactly what we want so... */
  102654. if(encoder->protected_->metadata) {
  102655. free(encoder->protected_->metadata);
  102656. encoder->protected_->metadata = 0;
  102657. encoder->protected_->num_metadata_blocks = 0;
  102658. }
  102659. if(num_blocks) {
  102660. FLAC__StreamMetadata **m;
  102661. if(0 == (m = (FLAC__StreamMetadata**)safe_malloc_mul_2op_(sizeof(m[0]), /*times*/num_blocks)))
  102662. return false;
  102663. memcpy(m, metadata, sizeof(m[0]) * num_blocks);
  102664. encoder->protected_->metadata = m;
  102665. encoder->protected_->num_metadata_blocks = num_blocks;
  102666. }
  102667. #if FLAC__HAS_OGG
  102668. if(!FLAC__ogg_encoder_aspect_set_num_metadata(&encoder->protected_->ogg_encoder_aspect, num_blocks))
  102669. return false;
  102670. #endif
  102671. return true;
  102672. }
  102673. /*
  102674. * These three functions are not static, but not publically exposed in
  102675. * include/FLAC/ either. They are used by the test suite.
  102676. */
  102677. FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  102678. {
  102679. FLAC__ASSERT(0 != encoder);
  102680. FLAC__ASSERT(0 != encoder->private_);
  102681. FLAC__ASSERT(0 != encoder->protected_);
  102682. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102683. return false;
  102684. encoder->private_->disable_constant_subframes = value;
  102685. return true;
  102686. }
  102687. FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  102688. {
  102689. FLAC__ASSERT(0 != encoder);
  102690. FLAC__ASSERT(0 != encoder->private_);
  102691. FLAC__ASSERT(0 != encoder->protected_);
  102692. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102693. return false;
  102694. encoder->private_->disable_fixed_subframes = value;
  102695. return true;
  102696. }
  102697. FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  102698. {
  102699. FLAC__ASSERT(0 != encoder);
  102700. FLAC__ASSERT(0 != encoder->private_);
  102701. FLAC__ASSERT(0 != encoder->protected_);
  102702. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102703. return false;
  102704. encoder->private_->disable_verbatim_subframes = value;
  102705. return true;
  102706. }
  102707. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
  102708. {
  102709. FLAC__ASSERT(0 != encoder);
  102710. FLAC__ASSERT(0 != encoder->private_);
  102711. FLAC__ASSERT(0 != encoder->protected_);
  102712. return encoder->protected_->state;
  102713. }
  102714. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
  102715. {
  102716. FLAC__ASSERT(0 != encoder);
  102717. FLAC__ASSERT(0 != encoder->private_);
  102718. FLAC__ASSERT(0 != encoder->protected_);
  102719. if(encoder->protected_->verify)
  102720. return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
  102721. else
  102722. return FLAC__STREAM_DECODER_UNINITIALIZED;
  102723. }
  102724. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
  102725. {
  102726. FLAC__ASSERT(0 != encoder);
  102727. FLAC__ASSERT(0 != encoder->private_);
  102728. FLAC__ASSERT(0 != encoder->protected_);
  102729. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR)
  102730. return FLAC__StreamEncoderStateString[encoder->protected_->state];
  102731. else
  102732. return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder);
  102733. }
  102734. 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)
  102735. {
  102736. FLAC__ASSERT(0 != encoder);
  102737. FLAC__ASSERT(0 != encoder->private_);
  102738. FLAC__ASSERT(0 != encoder->protected_);
  102739. if(0 != absolute_sample)
  102740. *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
  102741. if(0 != frame_number)
  102742. *frame_number = encoder->private_->verify.error_stats.frame_number;
  102743. if(0 != channel)
  102744. *channel = encoder->private_->verify.error_stats.channel;
  102745. if(0 != sample)
  102746. *sample = encoder->private_->verify.error_stats.sample;
  102747. if(0 != expected)
  102748. *expected = encoder->private_->verify.error_stats.expected;
  102749. if(0 != got)
  102750. *got = encoder->private_->verify.error_stats.got;
  102751. }
  102752. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder)
  102753. {
  102754. FLAC__ASSERT(0 != encoder);
  102755. FLAC__ASSERT(0 != encoder->private_);
  102756. FLAC__ASSERT(0 != encoder->protected_);
  102757. return encoder->protected_->verify;
  102758. }
  102759. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder)
  102760. {
  102761. FLAC__ASSERT(0 != encoder);
  102762. FLAC__ASSERT(0 != encoder->private_);
  102763. FLAC__ASSERT(0 != encoder->protected_);
  102764. return encoder->protected_->streamable_subset;
  102765. }
  102766. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_md5(const FLAC__StreamEncoder *encoder)
  102767. {
  102768. FLAC__ASSERT(0 != encoder);
  102769. FLAC__ASSERT(0 != encoder->private_);
  102770. FLAC__ASSERT(0 != encoder->protected_);
  102771. return encoder->protected_->do_md5;
  102772. }
  102773. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder)
  102774. {
  102775. FLAC__ASSERT(0 != encoder);
  102776. FLAC__ASSERT(0 != encoder->private_);
  102777. FLAC__ASSERT(0 != encoder->protected_);
  102778. return encoder->protected_->channels;
  102779. }
  102780. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder)
  102781. {
  102782. FLAC__ASSERT(0 != encoder);
  102783. FLAC__ASSERT(0 != encoder->private_);
  102784. FLAC__ASSERT(0 != encoder->protected_);
  102785. return encoder->protected_->bits_per_sample;
  102786. }
  102787. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder)
  102788. {
  102789. FLAC__ASSERT(0 != encoder);
  102790. FLAC__ASSERT(0 != encoder->private_);
  102791. FLAC__ASSERT(0 != encoder->protected_);
  102792. return encoder->protected_->sample_rate;
  102793. }
  102794. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
  102795. {
  102796. FLAC__ASSERT(0 != encoder);
  102797. FLAC__ASSERT(0 != encoder->private_);
  102798. FLAC__ASSERT(0 != encoder->protected_);
  102799. return encoder->protected_->blocksize;
  102800. }
  102801. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  102802. {
  102803. FLAC__ASSERT(0 != encoder);
  102804. FLAC__ASSERT(0 != encoder->private_);
  102805. FLAC__ASSERT(0 != encoder->protected_);
  102806. return encoder->protected_->do_mid_side_stereo;
  102807. }
  102808. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  102809. {
  102810. FLAC__ASSERT(0 != encoder);
  102811. FLAC__ASSERT(0 != encoder->private_);
  102812. FLAC__ASSERT(0 != encoder->protected_);
  102813. return encoder->protected_->loose_mid_side_stereo;
  102814. }
  102815. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
  102816. {
  102817. FLAC__ASSERT(0 != encoder);
  102818. FLAC__ASSERT(0 != encoder->private_);
  102819. FLAC__ASSERT(0 != encoder->protected_);
  102820. return encoder->protected_->max_lpc_order;
  102821. }
  102822. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
  102823. {
  102824. FLAC__ASSERT(0 != encoder);
  102825. FLAC__ASSERT(0 != encoder->private_);
  102826. FLAC__ASSERT(0 != encoder->protected_);
  102827. return encoder->protected_->qlp_coeff_precision;
  102828. }
  102829. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
  102830. {
  102831. FLAC__ASSERT(0 != encoder);
  102832. FLAC__ASSERT(0 != encoder->private_);
  102833. FLAC__ASSERT(0 != encoder->protected_);
  102834. return encoder->protected_->do_qlp_coeff_prec_search;
  102835. }
  102836. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
  102837. {
  102838. FLAC__ASSERT(0 != encoder);
  102839. FLAC__ASSERT(0 != encoder->private_);
  102840. FLAC__ASSERT(0 != encoder->protected_);
  102841. return encoder->protected_->do_escape_coding;
  102842. }
  102843. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
  102844. {
  102845. FLAC__ASSERT(0 != encoder);
  102846. FLAC__ASSERT(0 != encoder->private_);
  102847. FLAC__ASSERT(0 != encoder->protected_);
  102848. return encoder->protected_->do_exhaustive_model_search;
  102849. }
  102850. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
  102851. {
  102852. FLAC__ASSERT(0 != encoder);
  102853. FLAC__ASSERT(0 != encoder->private_);
  102854. FLAC__ASSERT(0 != encoder->protected_);
  102855. return encoder->protected_->min_residual_partition_order;
  102856. }
  102857. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
  102858. {
  102859. FLAC__ASSERT(0 != encoder);
  102860. FLAC__ASSERT(0 != encoder->private_);
  102861. FLAC__ASSERT(0 != encoder->protected_);
  102862. return encoder->protected_->max_residual_partition_order;
  102863. }
  102864. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
  102865. {
  102866. FLAC__ASSERT(0 != encoder);
  102867. FLAC__ASSERT(0 != encoder->private_);
  102868. FLAC__ASSERT(0 != encoder->protected_);
  102869. return encoder->protected_->rice_parameter_search_dist;
  102870. }
  102871. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
  102872. {
  102873. FLAC__ASSERT(0 != encoder);
  102874. FLAC__ASSERT(0 != encoder->private_);
  102875. FLAC__ASSERT(0 != encoder->protected_);
  102876. return encoder->protected_->total_samples_estimate;
  102877. }
  102878. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
  102879. {
  102880. unsigned i, j = 0, channel;
  102881. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  102882. FLAC__ASSERT(0 != encoder);
  102883. FLAC__ASSERT(0 != encoder->private_);
  102884. FLAC__ASSERT(0 != encoder->protected_);
  102885. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  102886. do {
  102887. const unsigned n = min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j);
  102888. if(encoder->protected_->verify)
  102889. append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, n);
  102890. for(channel = 0; channel < channels; channel++)
  102891. memcpy(&encoder->private_->integer_signal[channel][encoder->private_->current_sample_number], &buffer[channel][j], sizeof(buffer[channel][0]) * n);
  102892. if(encoder->protected_->do_mid_side_stereo) {
  102893. FLAC__ASSERT(channels == 2);
  102894. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  102895. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  102896. encoder->private_->integer_signal_mid_side[1][i] = buffer[0][j] - buffer[1][j];
  102897. 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' ! */
  102898. }
  102899. }
  102900. else
  102901. j += n;
  102902. encoder->private_->current_sample_number += n;
  102903. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  102904. if(encoder->private_->current_sample_number > blocksize) {
  102905. FLAC__ASSERT(encoder->private_->current_sample_number == blocksize+OVERREAD_);
  102906. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  102907. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  102908. return false;
  102909. /* move unprocessed overread samples to beginnings of arrays */
  102910. for(channel = 0; channel < channels; channel++)
  102911. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  102912. if(encoder->protected_->do_mid_side_stereo) {
  102913. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  102914. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  102915. }
  102916. encoder->private_->current_sample_number = 1;
  102917. }
  102918. } while(j < samples);
  102919. return true;
  102920. }
  102921. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
  102922. {
  102923. unsigned i, j, k, channel;
  102924. FLAC__int32 x, mid, side;
  102925. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  102926. FLAC__ASSERT(0 != encoder);
  102927. FLAC__ASSERT(0 != encoder->private_);
  102928. FLAC__ASSERT(0 != encoder->protected_);
  102929. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  102930. j = k = 0;
  102931. /*
  102932. * we have several flavors of the same basic loop, optimized for
  102933. * different conditions:
  102934. */
  102935. if(encoder->protected_->do_mid_side_stereo && channels == 2) {
  102936. /*
  102937. * stereo coding: unroll channel loop
  102938. */
  102939. do {
  102940. if(encoder->protected_->verify)
  102941. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  102942. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  102943. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  102944. encoder->private_->integer_signal[0][i] = mid = side = buffer[k++];
  102945. x = buffer[k++];
  102946. encoder->private_->integer_signal[1][i] = x;
  102947. mid += x;
  102948. side -= x;
  102949. mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
  102950. encoder->private_->integer_signal_mid_side[1][i] = side;
  102951. encoder->private_->integer_signal_mid_side[0][i] = mid;
  102952. }
  102953. encoder->private_->current_sample_number = i;
  102954. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  102955. if(i > blocksize) {
  102956. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  102957. return false;
  102958. /* move unprocessed overread samples to beginnings of arrays */
  102959. FLAC__ASSERT(i == blocksize+OVERREAD_);
  102960. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  102961. encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][blocksize];
  102962. encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][blocksize];
  102963. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  102964. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  102965. encoder->private_->current_sample_number = 1;
  102966. }
  102967. } while(j < samples);
  102968. }
  102969. else {
  102970. /*
  102971. * independent channel coding: buffer each channel in inner loop
  102972. */
  102973. do {
  102974. if(encoder->protected_->verify)
  102975. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  102976. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  102977. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  102978. for(channel = 0; channel < channels; channel++)
  102979. encoder->private_->integer_signal[channel][i] = buffer[k++];
  102980. }
  102981. encoder->private_->current_sample_number = i;
  102982. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  102983. if(i > blocksize) {
  102984. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  102985. return false;
  102986. /* move unprocessed overread samples to beginnings of arrays */
  102987. FLAC__ASSERT(i == blocksize+OVERREAD_);
  102988. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  102989. for(channel = 0; channel < channels; channel++)
  102990. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  102991. encoder->private_->current_sample_number = 1;
  102992. }
  102993. } while(j < samples);
  102994. }
  102995. return true;
  102996. }
  102997. /***********************************************************************
  102998. *
  102999. * Private class methods
  103000. *
  103001. ***********************************************************************/
  103002. void set_defaults_enc(FLAC__StreamEncoder *encoder)
  103003. {
  103004. FLAC__ASSERT(0 != encoder);
  103005. #ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  103006. encoder->protected_->verify = true;
  103007. #else
  103008. encoder->protected_->verify = false;
  103009. #endif
  103010. encoder->protected_->streamable_subset = true;
  103011. encoder->protected_->do_md5 = true;
  103012. encoder->protected_->do_mid_side_stereo = false;
  103013. encoder->protected_->loose_mid_side_stereo = false;
  103014. encoder->protected_->channels = 2;
  103015. encoder->protected_->bits_per_sample = 16;
  103016. encoder->protected_->sample_rate = 44100;
  103017. encoder->protected_->blocksize = 0;
  103018. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103019. encoder->protected_->num_apodizations = 1;
  103020. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  103021. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  103022. #endif
  103023. encoder->protected_->max_lpc_order = 0;
  103024. encoder->protected_->qlp_coeff_precision = 0;
  103025. encoder->protected_->do_qlp_coeff_prec_search = false;
  103026. encoder->protected_->do_exhaustive_model_search = false;
  103027. encoder->protected_->do_escape_coding = false;
  103028. encoder->protected_->min_residual_partition_order = 0;
  103029. encoder->protected_->max_residual_partition_order = 0;
  103030. encoder->protected_->rice_parameter_search_dist = 0;
  103031. encoder->protected_->total_samples_estimate = 0;
  103032. encoder->protected_->metadata = 0;
  103033. encoder->protected_->num_metadata_blocks = 0;
  103034. encoder->private_->seek_table = 0;
  103035. encoder->private_->disable_constant_subframes = false;
  103036. encoder->private_->disable_fixed_subframes = false;
  103037. encoder->private_->disable_verbatim_subframes = false;
  103038. #if FLAC__HAS_OGG
  103039. encoder->private_->is_ogg = false;
  103040. #endif
  103041. encoder->private_->read_callback = 0;
  103042. encoder->private_->write_callback = 0;
  103043. encoder->private_->seek_callback = 0;
  103044. encoder->private_->tell_callback = 0;
  103045. encoder->private_->metadata_callback = 0;
  103046. encoder->private_->progress_callback = 0;
  103047. encoder->private_->client_data = 0;
  103048. #if FLAC__HAS_OGG
  103049. FLAC__ogg_encoder_aspect_set_defaults(&encoder->protected_->ogg_encoder_aspect);
  103050. #endif
  103051. }
  103052. void free_(FLAC__StreamEncoder *encoder)
  103053. {
  103054. unsigned i, channel;
  103055. FLAC__ASSERT(0 != encoder);
  103056. if(encoder->protected_->metadata) {
  103057. free(encoder->protected_->metadata);
  103058. encoder->protected_->metadata = 0;
  103059. encoder->protected_->num_metadata_blocks = 0;
  103060. }
  103061. for(i = 0; i < encoder->protected_->channels; i++) {
  103062. if(0 != encoder->private_->integer_signal_unaligned[i]) {
  103063. free(encoder->private_->integer_signal_unaligned[i]);
  103064. encoder->private_->integer_signal_unaligned[i] = 0;
  103065. }
  103066. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103067. if(0 != encoder->private_->real_signal_unaligned[i]) {
  103068. free(encoder->private_->real_signal_unaligned[i]);
  103069. encoder->private_->real_signal_unaligned[i] = 0;
  103070. }
  103071. #endif
  103072. }
  103073. for(i = 0; i < 2; i++) {
  103074. if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
  103075. free(encoder->private_->integer_signal_mid_side_unaligned[i]);
  103076. encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
  103077. }
  103078. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103079. if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
  103080. free(encoder->private_->real_signal_mid_side_unaligned[i]);
  103081. encoder->private_->real_signal_mid_side_unaligned[i] = 0;
  103082. }
  103083. #endif
  103084. }
  103085. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103086. for(i = 0; i < encoder->protected_->num_apodizations; i++) {
  103087. if(0 != encoder->private_->window_unaligned[i]) {
  103088. free(encoder->private_->window_unaligned[i]);
  103089. encoder->private_->window_unaligned[i] = 0;
  103090. }
  103091. }
  103092. if(0 != encoder->private_->windowed_signal_unaligned) {
  103093. free(encoder->private_->windowed_signal_unaligned);
  103094. encoder->private_->windowed_signal_unaligned = 0;
  103095. }
  103096. #endif
  103097. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  103098. for(i = 0; i < 2; i++) {
  103099. if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
  103100. free(encoder->private_->residual_workspace_unaligned[channel][i]);
  103101. encoder->private_->residual_workspace_unaligned[channel][i] = 0;
  103102. }
  103103. }
  103104. }
  103105. for(channel = 0; channel < 2; channel++) {
  103106. for(i = 0; i < 2; i++) {
  103107. if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
  103108. free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
  103109. encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
  103110. }
  103111. }
  103112. }
  103113. if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
  103114. free(encoder->private_->abs_residual_partition_sums_unaligned);
  103115. encoder->private_->abs_residual_partition_sums_unaligned = 0;
  103116. }
  103117. if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
  103118. free(encoder->private_->raw_bits_per_partition_unaligned);
  103119. encoder->private_->raw_bits_per_partition_unaligned = 0;
  103120. }
  103121. if(encoder->protected_->verify) {
  103122. for(i = 0; i < encoder->protected_->channels; i++) {
  103123. if(0 != encoder->private_->verify.input_fifo.data[i]) {
  103124. free(encoder->private_->verify.input_fifo.data[i]);
  103125. encoder->private_->verify.input_fifo.data[i] = 0;
  103126. }
  103127. }
  103128. }
  103129. FLAC__bitwriter_free(encoder->private_->frame);
  103130. }
  103131. FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize)
  103132. {
  103133. FLAC__bool ok;
  103134. unsigned i, channel;
  103135. FLAC__ASSERT(new_blocksize > 0);
  103136. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  103137. FLAC__ASSERT(encoder->private_->current_sample_number == 0);
  103138. /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
  103139. if(new_blocksize <= encoder->private_->input_capacity)
  103140. return true;
  103141. ok = true;
  103142. /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx()
  103143. * requires that the input arrays (in our case the integer signals)
  103144. * have a buffer of up to 3 zeroes in front (at negative indices) for
  103145. * alignment purposes; we use 4 in front to keep the data well-aligned.
  103146. */
  103147. for(i = 0; ok && i < encoder->protected_->channels; i++) {
  103148. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
  103149. memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
  103150. encoder->private_->integer_signal[i] += 4;
  103151. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103152. #if 0 /* @@@ currently unused */
  103153. if(encoder->protected_->max_lpc_order > 0)
  103154. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
  103155. #endif
  103156. #endif
  103157. }
  103158. for(i = 0; ok && i < 2; i++) {
  103159. 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]);
  103160. memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
  103161. encoder->private_->integer_signal_mid_side[i] += 4;
  103162. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103163. #if 0 /* @@@ currently unused */
  103164. if(encoder->protected_->max_lpc_order > 0)
  103165. 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]);
  103166. #endif
  103167. #endif
  103168. }
  103169. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103170. if(ok && encoder->protected_->max_lpc_order > 0) {
  103171. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
  103172. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
  103173. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
  103174. }
  103175. #endif
  103176. for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
  103177. for(i = 0; ok && i < 2; i++) {
  103178. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
  103179. }
  103180. }
  103181. for(channel = 0; ok && channel < 2; channel++) {
  103182. for(i = 0; ok && i < 2; i++) {
  103183. 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]);
  103184. }
  103185. }
  103186. /* the *2 is an approximation to the series 1 + 1/2 + 1/4 + ... that sums tree occupies in a flat array */
  103187. /*@@@ 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) */
  103188. ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_blocksize * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
  103189. if(encoder->protected_->do_escape_coding)
  103190. ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_blocksize * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
  103191. /* now adjust the windows if the blocksize has changed */
  103192. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103193. if(ok && new_blocksize != encoder->private_->input_capacity && encoder->protected_->max_lpc_order > 0) {
  103194. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
  103195. switch(encoder->protected_->apodizations[i].type) {
  103196. case FLAC__APODIZATION_BARTLETT:
  103197. FLAC__window_bartlett(encoder->private_->window[i], new_blocksize);
  103198. break;
  103199. case FLAC__APODIZATION_BARTLETT_HANN:
  103200. FLAC__window_bartlett_hann(encoder->private_->window[i], new_blocksize);
  103201. break;
  103202. case FLAC__APODIZATION_BLACKMAN:
  103203. FLAC__window_blackman(encoder->private_->window[i], new_blocksize);
  103204. break;
  103205. case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
  103206. FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_blocksize);
  103207. break;
  103208. case FLAC__APODIZATION_CONNES:
  103209. FLAC__window_connes(encoder->private_->window[i], new_blocksize);
  103210. break;
  103211. case FLAC__APODIZATION_FLATTOP:
  103212. FLAC__window_flattop(encoder->private_->window[i], new_blocksize);
  103213. break;
  103214. case FLAC__APODIZATION_GAUSS:
  103215. FLAC__window_gauss(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.gauss.stddev);
  103216. break;
  103217. case FLAC__APODIZATION_HAMMING:
  103218. FLAC__window_hamming(encoder->private_->window[i], new_blocksize);
  103219. break;
  103220. case FLAC__APODIZATION_HANN:
  103221. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  103222. break;
  103223. case FLAC__APODIZATION_KAISER_BESSEL:
  103224. FLAC__window_kaiser_bessel(encoder->private_->window[i], new_blocksize);
  103225. break;
  103226. case FLAC__APODIZATION_NUTTALL:
  103227. FLAC__window_nuttall(encoder->private_->window[i], new_blocksize);
  103228. break;
  103229. case FLAC__APODIZATION_RECTANGLE:
  103230. FLAC__window_rectangle(encoder->private_->window[i], new_blocksize);
  103231. break;
  103232. case FLAC__APODIZATION_TRIANGLE:
  103233. FLAC__window_triangle(encoder->private_->window[i], new_blocksize);
  103234. break;
  103235. case FLAC__APODIZATION_TUKEY:
  103236. FLAC__window_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.tukey.p);
  103237. break;
  103238. case FLAC__APODIZATION_WELCH:
  103239. FLAC__window_welch(encoder->private_->window[i], new_blocksize);
  103240. break;
  103241. default:
  103242. FLAC__ASSERT(0);
  103243. /* double protection */
  103244. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  103245. break;
  103246. }
  103247. }
  103248. }
  103249. #endif
  103250. if(ok)
  103251. encoder->private_->input_capacity = new_blocksize;
  103252. else
  103253. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  103254. return ok;
  103255. }
  103256. FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block)
  103257. {
  103258. const FLAC__byte *buffer;
  103259. size_t bytes;
  103260. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  103261. if(!FLAC__bitwriter_get_buffer(encoder->private_->frame, &buffer, &bytes)) {
  103262. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  103263. return false;
  103264. }
  103265. if(encoder->protected_->verify) {
  103266. encoder->private_->verify.output.data = buffer;
  103267. encoder->private_->verify.output.bytes = bytes;
  103268. if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
  103269. encoder->private_->verify.needs_magic_hack = true;
  103270. }
  103271. else {
  103272. if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
  103273. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  103274. FLAC__bitwriter_clear(encoder->private_->frame);
  103275. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
  103276. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  103277. return false;
  103278. }
  103279. }
  103280. }
  103281. if(write_frame_(encoder, buffer, bytes, samples, is_last_block) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  103282. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  103283. FLAC__bitwriter_clear(encoder->private_->frame);
  103284. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103285. return false;
  103286. }
  103287. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  103288. FLAC__bitwriter_clear(encoder->private_->frame);
  103289. if(samples > 0) {
  103290. encoder->private_->streaminfo.data.stream_info.min_framesize = min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
  103291. encoder->private_->streaminfo.data.stream_info.max_framesize = max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
  103292. }
  103293. return true;
  103294. }
  103295. FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block)
  103296. {
  103297. FLAC__StreamEncoderWriteStatus status;
  103298. FLAC__uint64 output_position = 0;
  103299. /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
  103300. if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
  103301. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103302. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  103303. }
  103304. /*
  103305. * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
  103306. */
  103307. if(samples == 0) {
  103308. FLAC__MetadataType type = (FLAC__MetadataType) (buffer[0] & 0x7f);
  103309. if(type == FLAC__METADATA_TYPE_STREAMINFO)
  103310. encoder->protected_->streaminfo_offset = output_position;
  103311. else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
  103312. encoder->protected_->seektable_offset = output_position;
  103313. }
  103314. /*
  103315. * Mark the current seek point if hit (if audio_offset == 0 that
  103316. * means we're still writing metadata and haven't hit the first
  103317. * frame yet)
  103318. */
  103319. if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
  103320. const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  103321. const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
  103322. const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
  103323. FLAC__uint64 test_sample;
  103324. unsigned i;
  103325. for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
  103326. test_sample = encoder->private_->seek_table->points[i].sample_number;
  103327. if(test_sample > frame_last_sample) {
  103328. break;
  103329. }
  103330. else if(test_sample >= frame_first_sample) {
  103331. encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
  103332. encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
  103333. encoder->private_->seek_table->points[i].frame_samples = blocksize;
  103334. encoder->private_->first_seekpoint_to_check++;
  103335. /* DO NOT: "break;" and here's why:
  103336. * The seektable template may contain more than one target
  103337. * sample for any given frame; we will keep looping, generating
  103338. * duplicate seekpoints for them, and we'll clean it up later,
  103339. * just before writing the seektable back to the metadata.
  103340. */
  103341. }
  103342. else {
  103343. encoder->private_->first_seekpoint_to_check++;
  103344. }
  103345. }
  103346. }
  103347. #if FLAC__HAS_OGG
  103348. if(encoder->private_->is_ogg) {
  103349. status = FLAC__ogg_encoder_aspect_write_callback_wrapper(
  103350. &encoder->protected_->ogg_encoder_aspect,
  103351. buffer,
  103352. bytes,
  103353. samples,
  103354. encoder->private_->current_frame_number,
  103355. is_last_block,
  103356. (FLAC__OggEncoderAspectWriteCallbackProxy)encoder->private_->write_callback,
  103357. encoder,
  103358. encoder->private_->client_data
  103359. );
  103360. }
  103361. else
  103362. #endif
  103363. status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
  103364. if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  103365. encoder->private_->bytes_written += bytes;
  103366. encoder->private_->samples_written += samples;
  103367. /* we keep a high watermark on the number of frames written because
  103368. * when the encoder goes back to write metadata, 'current_frame'
  103369. * will drop back to 0.
  103370. */
  103371. encoder->private_->frames_written = max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
  103372. }
  103373. else
  103374. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103375. return status;
  103376. }
  103377. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  103378. void update_metadata_(const FLAC__StreamEncoder *encoder)
  103379. {
  103380. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  103381. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  103382. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  103383. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  103384. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  103385. const unsigned bps = metadata->data.stream_info.bits_per_sample;
  103386. FLAC__StreamEncoderSeekStatus seek_status;
  103387. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  103388. /* All this is based on intimate knowledge of the stream header
  103389. * layout, but a change to the header format that would break this
  103390. * would also break all streams encoded in the previous format.
  103391. */
  103392. /*
  103393. * Write MD5 signature
  103394. */
  103395. {
  103396. const unsigned md5_offset =
  103397. FLAC__STREAM_METADATA_HEADER_LENGTH +
  103398. (
  103399. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  103400. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  103401. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  103402. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  103403. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  103404. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  103405. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  103406. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  103407. ) / 8;
  103408. if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
  103409. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  103410. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103411. return;
  103412. }
  103413. if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  103414. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103415. return;
  103416. }
  103417. }
  103418. /*
  103419. * Write total samples
  103420. */
  103421. {
  103422. const unsigned total_samples_byte_offset =
  103423. FLAC__STREAM_METADATA_HEADER_LENGTH +
  103424. (
  103425. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  103426. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  103427. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  103428. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  103429. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  103430. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  103431. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  103432. - 4
  103433. ) / 8;
  103434. b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
  103435. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  103436. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  103437. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  103438. b[4] = (FLAC__byte)(samples & 0xFF);
  103439. 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) {
  103440. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  103441. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103442. return;
  103443. }
  103444. if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  103445. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103446. return;
  103447. }
  103448. }
  103449. /*
  103450. * Write min/max framesize
  103451. */
  103452. {
  103453. const unsigned min_framesize_offset =
  103454. FLAC__STREAM_METADATA_HEADER_LENGTH +
  103455. (
  103456. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  103457. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  103458. ) / 8;
  103459. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  103460. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  103461. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  103462. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  103463. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  103464. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  103465. 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) {
  103466. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  103467. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103468. return;
  103469. }
  103470. if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  103471. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103472. return;
  103473. }
  103474. }
  103475. /*
  103476. * Write seektable
  103477. */
  103478. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  103479. unsigned i;
  103480. FLAC__format_seektable_sort(encoder->private_->seek_table);
  103481. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  103482. 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) {
  103483. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  103484. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103485. return;
  103486. }
  103487. for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
  103488. FLAC__uint64 xx;
  103489. unsigned x;
  103490. xx = encoder->private_->seek_table->points[i].sample_number;
  103491. b[7] = (FLAC__byte)xx; xx >>= 8;
  103492. b[6] = (FLAC__byte)xx; xx >>= 8;
  103493. b[5] = (FLAC__byte)xx; xx >>= 8;
  103494. b[4] = (FLAC__byte)xx; xx >>= 8;
  103495. b[3] = (FLAC__byte)xx; xx >>= 8;
  103496. b[2] = (FLAC__byte)xx; xx >>= 8;
  103497. b[1] = (FLAC__byte)xx; xx >>= 8;
  103498. b[0] = (FLAC__byte)xx; xx >>= 8;
  103499. xx = encoder->private_->seek_table->points[i].stream_offset;
  103500. b[15] = (FLAC__byte)xx; xx >>= 8;
  103501. b[14] = (FLAC__byte)xx; xx >>= 8;
  103502. b[13] = (FLAC__byte)xx; xx >>= 8;
  103503. b[12] = (FLAC__byte)xx; xx >>= 8;
  103504. b[11] = (FLAC__byte)xx; xx >>= 8;
  103505. b[10] = (FLAC__byte)xx; xx >>= 8;
  103506. b[9] = (FLAC__byte)xx; xx >>= 8;
  103507. b[8] = (FLAC__byte)xx; xx >>= 8;
  103508. x = encoder->private_->seek_table->points[i].frame_samples;
  103509. b[17] = (FLAC__byte)x; x >>= 8;
  103510. b[16] = (FLAC__byte)x; x >>= 8;
  103511. if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  103512. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103513. return;
  103514. }
  103515. }
  103516. }
  103517. }
  103518. #if FLAC__HAS_OGG
  103519. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  103520. void update_ogg_metadata_(FLAC__StreamEncoder *encoder)
  103521. {
  103522. /* the # of bytes in the 1st packet that precede the STREAMINFO */
  103523. static const unsigned FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH =
  103524. FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
  103525. FLAC__OGG_MAPPING_MAGIC_LENGTH +
  103526. FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
  103527. FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
  103528. FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH +
  103529. FLAC__STREAM_SYNC_LENGTH
  103530. ;
  103531. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  103532. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  103533. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  103534. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  103535. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  103536. ogg_page page;
  103537. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  103538. FLAC__ASSERT(0 != encoder->private_->seek_callback);
  103539. /* Pre-check that client supports seeking, since we don't want the
  103540. * ogg_helper code to ever have to deal with this condition.
  103541. */
  103542. if(encoder->private_->seek_callback(encoder, 0, encoder->private_->client_data) == FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED)
  103543. return;
  103544. /* All this is based on intimate knowledge of the stream header
  103545. * layout, but a change to the header format that would break this
  103546. * would also break all streams encoded in the previous format.
  103547. */
  103548. /**
  103549. ** Write STREAMINFO stats
  103550. **/
  103551. simple_ogg_page__init(&page);
  103552. if(!simple_ogg_page__get_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  103553. simple_ogg_page__clear(&page);
  103554. return; /* state already set */
  103555. }
  103556. /*
  103557. * Write MD5 signature
  103558. */
  103559. {
  103560. const unsigned md5_offset =
  103561. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  103562. FLAC__STREAM_METADATA_HEADER_LENGTH +
  103563. (
  103564. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  103565. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  103566. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  103567. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  103568. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  103569. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  103570. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  103571. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  103572. ) / 8;
  103573. if(md5_offset + 16 > (unsigned)page.body_len) {
  103574. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  103575. simple_ogg_page__clear(&page);
  103576. return;
  103577. }
  103578. memcpy(page.body + md5_offset, metadata->data.stream_info.md5sum, 16);
  103579. }
  103580. /*
  103581. * Write total samples
  103582. */
  103583. {
  103584. const unsigned total_samples_byte_offset =
  103585. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  103586. FLAC__STREAM_METADATA_HEADER_LENGTH +
  103587. (
  103588. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  103589. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  103590. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  103591. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  103592. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  103593. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  103594. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  103595. - 4
  103596. ) / 8;
  103597. if(total_samples_byte_offset + 5 > (unsigned)page.body_len) {
  103598. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  103599. simple_ogg_page__clear(&page);
  103600. return;
  103601. }
  103602. b[0] = (FLAC__byte)page.body[total_samples_byte_offset] & 0xF0;
  103603. b[0] |= (FLAC__byte)((samples >> 32) & 0x0F);
  103604. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  103605. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  103606. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  103607. b[4] = (FLAC__byte)(samples & 0xFF);
  103608. memcpy(page.body + total_samples_byte_offset, b, 5);
  103609. }
  103610. /*
  103611. * Write min/max framesize
  103612. */
  103613. {
  103614. const unsigned min_framesize_offset =
  103615. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  103616. FLAC__STREAM_METADATA_HEADER_LENGTH +
  103617. (
  103618. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  103619. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  103620. ) / 8;
  103621. if(min_framesize_offset + 6 > (unsigned)page.body_len) {
  103622. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  103623. simple_ogg_page__clear(&page);
  103624. return;
  103625. }
  103626. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  103627. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  103628. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  103629. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  103630. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  103631. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  103632. memcpy(page.body + min_framesize_offset, b, 6);
  103633. }
  103634. if(!simple_ogg_page__set_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  103635. simple_ogg_page__clear(&page);
  103636. return; /* state already set */
  103637. }
  103638. simple_ogg_page__clear(&page);
  103639. /*
  103640. * Write seektable
  103641. */
  103642. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  103643. unsigned i;
  103644. FLAC__byte *p;
  103645. FLAC__format_seektable_sort(encoder->private_->seek_table);
  103646. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  103647. simple_ogg_page__init(&page);
  103648. if(!simple_ogg_page__get_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  103649. simple_ogg_page__clear(&page);
  103650. return; /* state already set */
  103651. }
  103652. if((FLAC__STREAM_METADATA_HEADER_LENGTH + 18*encoder->private_->seek_table->num_points) != (unsigned)page.body_len) {
  103653. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  103654. simple_ogg_page__clear(&page);
  103655. return;
  103656. }
  103657. for(i = 0, p = page.body + FLAC__STREAM_METADATA_HEADER_LENGTH; i < encoder->private_->seek_table->num_points; i++, p += 18) {
  103658. FLAC__uint64 xx;
  103659. unsigned x;
  103660. xx = encoder->private_->seek_table->points[i].sample_number;
  103661. b[7] = (FLAC__byte)xx; xx >>= 8;
  103662. b[6] = (FLAC__byte)xx; xx >>= 8;
  103663. b[5] = (FLAC__byte)xx; xx >>= 8;
  103664. b[4] = (FLAC__byte)xx; xx >>= 8;
  103665. b[3] = (FLAC__byte)xx; xx >>= 8;
  103666. b[2] = (FLAC__byte)xx; xx >>= 8;
  103667. b[1] = (FLAC__byte)xx; xx >>= 8;
  103668. b[0] = (FLAC__byte)xx; xx >>= 8;
  103669. xx = encoder->private_->seek_table->points[i].stream_offset;
  103670. b[15] = (FLAC__byte)xx; xx >>= 8;
  103671. b[14] = (FLAC__byte)xx; xx >>= 8;
  103672. b[13] = (FLAC__byte)xx; xx >>= 8;
  103673. b[12] = (FLAC__byte)xx; xx >>= 8;
  103674. b[11] = (FLAC__byte)xx; xx >>= 8;
  103675. b[10] = (FLAC__byte)xx; xx >>= 8;
  103676. b[9] = (FLAC__byte)xx; xx >>= 8;
  103677. b[8] = (FLAC__byte)xx; xx >>= 8;
  103678. x = encoder->private_->seek_table->points[i].frame_samples;
  103679. b[17] = (FLAC__byte)x; x >>= 8;
  103680. b[16] = (FLAC__byte)x; x >>= 8;
  103681. memcpy(p, b, 18);
  103682. }
  103683. if(!simple_ogg_page__set_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  103684. simple_ogg_page__clear(&page);
  103685. return; /* state already set */
  103686. }
  103687. simple_ogg_page__clear(&page);
  103688. }
  103689. }
  103690. #endif
  103691. FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block)
  103692. {
  103693. FLAC__uint16 crc;
  103694. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  103695. /*
  103696. * Accumulate raw signal to the MD5 signature
  103697. */
  103698. 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)) {
  103699. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  103700. return false;
  103701. }
  103702. /*
  103703. * Process the frame header and subframes into the frame bitbuffer
  103704. */
  103705. if(!process_subframes_(encoder, is_fractional_block)) {
  103706. /* the above function sets the state for us in case of an error */
  103707. return false;
  103708. }
  103709. /*
  103710. * Zero-pad the frame to a byte_boundary
  103711. */
  103712. if(!FLAC__bitwriter_zero_pad_to_byte_boundary(encoder->private_->frame)) {
  103713. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  103714. return false;
  103715. }
  103716. /*
  103717. * CRC-16 the whole thing
  103718. */
  103719. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  103720. if(
  103721. !FLAC__bitwriter_get_write_crc16(encoder->private_->frame, &crc) ||
  103722. !FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, crc, FLAC__FRAME_FOOTER_CRC_LEN)
  103723. ) {
  103724. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  103725. return false;
  103726. }
  103727. /*
  103728. * Write it
  103729. */
  103730. if(!write_bitbuffer_(encoder, encoder->protected_->blocksize, is_last_block)) {
  103731. /* the above function sets the state for us in case of an error */
  103732. return false;
  103733. }
  103734. /*
  103735. * Get ready for the next frame
  103736. */
  103737. encoder->private_->current_sample_number = 0;
  103738. encoder->private_->current_frame_number++;
  103739. encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
  103740. return true;
  103741. }
  103742. FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block)
  103743. {
  103744. FLAC__FrameHeader frame_header;
  103745. unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
  103746. FLAC__bool do_independent, do_mid_side;
  103747. /*
  103748. * Calculate the min,max Rice partition orders
  103749. */
  103750. if(is_fractional_block) {
  103751. max_partition_order = 0;
  103752. }
  103753. else {
  103754. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize);
  103755. max_partition_order = min(max_partition_order, encoder->protected_->max_residual_partition_order);
  103756. }
  103757. min_partition_order = min(min_partition_order, max_partition_order);
  103758. /*
  103759. * Setup the frame
  103760. */
  103761. frame_header.blocksize = encoder->protected_->blocksize;
  103762. frame_header.sample_rate = encoder->protected_->sample_rate;
  103763. frame_header.channels = encoder->protected_->channels;
  103764. frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
  103765. frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
  103766. frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  103767. frame_header.number.frame_number = encoder->private_->current_frame_number;
  103768. /*
  103769. * Figure out what channel assignments to try
  103770. */
  103771. if(encoder->protected_->do_mid_side_stereo) {
  103772. if(encoder->protected_->loose_mid_side_stereo) {
  103773. if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
  103774. do_independent = true;
  103775. do_mid_side = true;
  103776. }
  103777. else {
  103778. do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
  103779. do_mid_side = !do_independent;
  103780. }
  103781. }
  103782. else {
  103783. do_independent = true;
  103784. do_mid_side = true;
  103785. }
  103786. }
  103787. else {
  103788. do_independent = true;
  103789. do_mid_side = false;
  103790. }
  103791. FLAC__ASSERT(do_independent || do_mid_side);
  103792. /*
  103793. * Check for wasted bits; set effective bps for each subframe
  103794. */
  103795. if(do_independent) {
  103796. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  103797. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
  103798. encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
  103799. encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
  103800. }
  103801. }
  103802. if(do_mid_side) {
  103803. FLAC__ASSERT(encoder->protected_->channels == 2);
  103804. for(channel = 0; channel < 2; channel++) {
  103805. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
  103806. encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
  103807. encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
  103808. }
  103809. }
  103810. /*
  103811. * First do a normal encoding pass of each independent channel
  103812. */
  103813. if(do_independent) {
  103814. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  103815. if(!
  103816. process_subframe_(
  103817. encoder,
  103818. min_partition_order,
  103819. max_partition_order,
  103820. &frame_header,
  103821. encoder->private_->subframe_bps[channel],
  103822. encoder->private_->integer_signal[channel],
  103823. encoder->private_->subframe_workspace_ptr[channel],
  103824. encoder->private_->partitioned_rice_contents_workspace_ptr[channel],
  103825. encoder->private_->residual_workspace[channel],
  103826. encoder->private_->best_subframe+channel,
  103827. encoder->private_->best_subframe_bits+channel
  103828. )
  103829. )
  103830. return false;
  103831. }
  103832. }
  103833. /*
  103834. * Now do mid and side channels if requested
  103835. */
  103836. if(do_mid_side) {
  103837. FLAC__ASSERT(encoder->protected_->channels == 2);
  103838. for(channel = 0; channel < 2; channel++) {
  103839. if(!
  103840. process_subframe_(
  103841. encoder,
  103842. min_partition_order,
  103843. max_partition_order,
  103844. &frame_header,
  103845. encoder->private_->subframe_bps_mid_side[channel],
  103846. encoder->private_->integer_signal_mid_side[channel],
  103847. encoder->private_->subframe_workspace_ptr_mid_side[channel],
  103848. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel],
  103849. encoder->private_->residual_workspace_mid_side[channel],
  103850. encoder->private_->best_subframe_mid_side+channel,
  103851. encoder->private_->best_subframe_bits_mid_side+channel
  103852. )
  103853. )
  103854. return false;
  103855. }
  103856. }
  103857. /*
  103858. * Compose the frame bitbuffer
  103859. */
  103860. if(do_mid_side) {
  103861. unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
  103862. FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
  103863. FLAC__ChannelAssignment channel_assignment;
  103864. FLAC__ASSERT(encoder->protected_->channels == 2);
  103865. if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
  103866. channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
  103867. }
  103868. else {
  103869. unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
  103870. unsigned min_bits;
  103871. int ca;
  103872. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT == 0);
  103873. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE == 1);
  103874. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE == 2);
  103875. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_MID_SIDE == 3);
  103876. FLAC__ASSERT(do_independent && do_mid_side);
  103877. /* We have to figure out which channel assignent results in the smallest frame */
  103878. bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits [1];
  103879. bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE ] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits_mid_side[1];
  103880. bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits [1] + encoder->private_->best_subframe_bits_mid_side[1];
  103881. bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
  103882. channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  103883. min_bits = bits[channel_assignment];
  103884. for(ca = 1; ca <= 3; ca++) {
  103885. if(bits[ca] < min_bits) {
  103886. min_bits = bits[ca];
  103887. channel_assignment = (FLAC__ChannelAssignment)ca;
  103888. }
  103889. }
  103890. }
  103891. frame_header.channel_assignment = channel_assignment;
  103892. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  103893. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103894. return false;
  103895. }
  103896. switch(channel_assignment) {
  103897. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  103898. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  103899. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  103900. break;
  103901. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  103902. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  103903. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  103904. break;
  103905. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  103906. left_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  103907. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  103908. break;
  103909. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  103910. left_subframe = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]];
  103911. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  103912. break;
  103913. default:
  103914. FLAC__ASSERT(0);
  103915. }
  103916. switch(channel_assignment) {
  103917. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  103918. left_bps = encoder->private_->subframe_bps [0];
  103919. right_bps = encoder->private_->subframe_bps [1];
  103920. break;
  103921. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  103922. left_bps = encoder->private_->subframe_bps [0];
  103923. right_bps = encoder->private_->subframe_bps_mid_side[1];
  103924. break;
  103925. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  103926. left_bps = encoder->private_->subframe_bps_mid_side[1];
  103927. right_bps = encoder->private_->subframe_bps [1];
  103928. break;
  103929. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  103930. left_bps = encoder->private_->subframe_bps_mid_side[0];
  103931. right_bps = encoder->private_->subframe_bps_mid_side[1];
  103932. break;
  103933. default:
  103934. FLAC__ASSERT(0);
  103935. }
  103936. /* note that encoder_add_subframe_ sets the state for us in case of an error */
  103937. if(!add_subframe_(encoder, frame_header.blocksize, left_bps , left_subframe , encoder->private_->frame))
  103938. return false;
  103939. if(!add_subframe_(encoder, frame_header.blocksize, right_bps, right_subframe, encoder->private_->frame))
  103940. return false;
  103941. }
  103942. else {
  103943. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  103944. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103945. return false;
  103946. }
  103947. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  103948. 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)) {
  103949. /* the above function sets the state for us in case of an error */
  103950. return false;
  103951. }
  103952. }
  103953. }
  103954. if(encoder->protected_->loose_mid_side_stereo) {
  103955. encoder->private_->loose_mid_side_stereo_frame_count++;
  103956. if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames)
  103957. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  103958. }
  103959. encoder->private_->last_channel_assignment = frame_header.channel_assignment;
  103960. return true;
  103961. }
  103962. FLAC__bool process_subframe_(
  103963. FLAC__StreamEncoder *encoder,
  103964. unsigned min_partition_order,
  103965. unsigned max_partition_order,
  103966. const FLAC__FrameHeader *frame_header,
  103967. unsigned subframe_bps,
  103968. const FLAC__int32 integer_signal[],
  103969. FLAC__Subframe *subframe[2],
  103970. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  103971. FLAC__int32 *residual[2],
  103972. unsigned *best_subframe,
  103973. unsigned *best_bits
  103974. )
  103975. {
  103976. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103977. FLAC__float fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  103978. #else
  103979. FLAC__fixedpoint fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  103980. #endif
  103981. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103982. FLAC__double lpc_residual_bits_per_sample;
  103983. 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 */
  103984. FLAC__double lpc_error[FLAC__MAX_LPC_ORDER];
  103985. unsigned min_lpc_order, max_lpc_order, lpc_order;
  103986. unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
  103987. #endif
  103988. unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
  103989. unsigned rice_parameter;
  103990. unsigned _candidate_bits, _best_bits;
  103991. unsigned _best_subframe;
  103992. /* only use RICE2 partitions if stream bps > 16 */
  103993. 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;
  103994. FLAC__ASSERT(frame_header->blocksize > 0);
  103995. /* verbatim subframe is the baseline against which we measure other compressed subframes */
  103996. _best_subframe = 0;
  103997. if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER)
  103998. _best_bits = UINT_MAX;
  103999. else
  104000. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  104001. if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
  104002. unsigned signal_is_constant = false;
  104003. 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);
  104004. /* check for constant subframe */
  104005. if(
  104006. !encoder->private_->disable_constant_subframes &&
  104007. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104008. fixed_residual_bits_per_sample[1] == 0.0
  104009. #else
  104010. fixed_residual_bits_per_sample[1] == FLAC__FP_ZERO
  104011. #endif
  104012. ) {
  104013. /* the above means it's possible all samples are the same value; now double-check it: */
  104014. unsigned i;
  104015. signal_is_constant = true;
  104016. for(i = 1; i < frame_header->blocksize; i++) {
  104017. if(integer_signal[0] != integer_signal[i]) {
  104018. signal_is_constant = false;
  104019. break;
  104020. }
  104021. }
  104022. }
  104023. if(signal_is_constant) {
  104024. _candidate_bits = evaluate_constant_subframe_(encoder, integer_signal[0], frame_header->blocksize, subframe_bps, subframe[!_best_subframe]);
  104025. if(_candidate_bits < _best_bits) {
  104026. _best_subframe = !_best_subframe;
  104027. _best_bits = _candidate_bits;
  104028. }
  104029. }
  104030. else {
  104031. if(!encoder->private_->disable_fixed_subframes || (encoder->protected_->max_lpc_order == 0 && _best_bits == UINT_MAX)) {
  104032. /* encode fixed */
  104033. if(encoder->protected_->do_exhaustive_model_search) {
  104034. min_fixed_order = 0;
  104035. max_fixed_order = FLAC__MAX_FIXED_ORDER;
  104036. }
  104037. else {
  104038. min_fixed_order = max_fixed_order = guess_fixed_order;
  104039. }
  104040. if(max_fixed_order >= frame_header->blocksize)
  104041. max_fixed_order = frame_header->blocksize - 1;
  104042. for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
  104043. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104044. if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__float)subframe_bps)
  104045. continue; /* don't even try */
  104046. 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 */
  104047. #else
  104048. if(FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]) >= (int)subframe_bps)
  104049. continue; /* don't even try */
  104050. 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 */
  104051. #endif
  104052. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  104053. if(rice_parameter >= rice_parameter_limit) {
  104054. #ifdef DEBUG_VERBOSE
  104055. fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, rice_parameter_limit - 1);
  104056. #endif
  104057. rice_parameter = rice_parameter_limit - 1;
  104058. }
  104059. _candidate_bits =
  104060. evaluate_fixed_subframe_(
  104061. encoder,
  104062. integer_signal,
  104063. residual[!_best_subframe],
  104064. encoder->private_->abs_residual_partition_sums,
  104065. encoder->private_->raw_bits_per_partition,
  104066. frame_header->blocksize,
  104067. subframe_bps,
  104068. fixed_order,
  104069. rice_parameter,
  104070. rice_parameter_limit,
  104071. min_partition_order,
  104072. max_partition_order,
  104073. encoder->protected_->do_escape_coding,
  104074. encoder->protected_->rice_parameter_search_dist,
  104075. subframe[!_best_subframe],
  104076. partitioned_rice_contents[!_best_subframe]
  104077. );
  104078. if(_candidate_bits < _best_bits) {
  104079. _best_subframe = !_best_subframe;
  104080. _best_bits = _candidate_bits;
  104081. }
  104082. }
  104083. }
  104084. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104085. /* encode lpc */
  104086. if(encoder->protected_->max_lpc_order > 0) {
  104087. if(encoder->protected_->max_lpc_order >= frame_header->blocksize)
  104088. max_lpc_order = frame_header->blocksize-1;
  104089. else
  104090. max_lpc_order = encoder->protected_->max_lpc_order;
  104091. if(max_lpc_order > 0) {
  104092. unsigned a;
  104093. for (a = 0; a < encoder->protected_->num_apodizations; a++) {
  104094. FLAC__lpc_window_data(integer_signal, encoder->private_->window[a], encoder->private_->windowed_signal, frame_header->blocksize);
  104095. encoder->private_->local_lpc_compute_autocorrelation(encoder->private_->windowed_signal, frame_header->blocksize, max_lpc_order+1, autoc);
  104096. /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
  104097. if(autoc[0] != 0.0) {
  104098. FLAC__lpc_compute_lp_coefficients(autoc, &max_lpc_order, encoder->private_->lp_coeff, lpc_error);
  104099. if(encoder->protected_->do_exhaustive_model_search) {
  104100. min_lpc_order = 1;
  104101. }
  104102. else {
  104103. const unsigned guess_lpc_order =
  104104. FLAC__lpc_compute_best_order(
  104105. lpc_error,
  104106. max_lpc_order,
  104107. frame_header->blocksize,
  104108. subframe_bps + (
  104109. encoder->protected_->do_qlp_coeff_prec_search?
  104110. FLAC__MIN_QLP_COEFF_PRECISION : /* have to guess; use the min possible size to avoid accidentally favoring lower orders */
  104111. encoder->protected_->qlp_coeff_precision
  104112. )
  104113. );
  104114. min_lpc_order = max_lpc_order = guess_lpc_order;
  104115. }
  104116. if(max_lpc_order >= frame_header->blocksize)
  104117. max_lpc_order = frame_header->blocksize - 1;
  104118. for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
  104119. lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
  104120. if(lpc_residual_bits_per_sample >= (FLAC__double)subframe_bps)
  104121. continue; /* don't even try */
  104122. rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
  104123. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  104124. if(rice_parameter >= rice_parameter_limit) {
  104125. #ifdef DEBUG_VERBOSE
  104126. fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, rice_parameter_limit - 1);
  104127. #endif
  104128. rice_parameter = rice_parameter_limit - 1;
  104129. }
  104130. if(encoder->protected_->do_qlp_coeff_prec_search) {
  104131. min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
  104132. /* try to ensure a 32-bit datapath throughout for 16bps(+1bps for side channel) or less */
  104133. if(subframe_bps <= 17) {
  104134. max_qlp_coeff_precision = min(32 - subframe_bps - lpc_order, FLAC__MAX_QLP_COEFF_PRECISION);
  104135. max_qlp_coeff_precision = max(max_qlp_coeff_precision, min_qlp_coeff_precision);
  104136. }
  104137. else
  104138. max_qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  104139. }
  104140. else {
  104141. min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision;
  104142. }
  104143. for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
  104144. _candidate_bits =
  104145. evaluate_lpc_subframe_(
  104146. encoder,
  104147. integer_signal,
  104148. residual[!_best_subframe],
  104149. encoder->private_->abs_residual_partition_sums,
  104150. encoder->private_->raw_bits_per_partition,
  104151. encoder->private_->lp_coeff[lpc_order-1],
  104152. frame_header->blocksize,
  104153. subframe_bps,
  104154. lpc_order,
  104155. qlp_coeff_precision,
  104156. rice_parameter,
  104157. rice_parameter_limit,
  104158. min_partition_order,
  104159. max_partition_order,
  104160. encoder->protected_->do_escape_coding,
  104161. encoder->protected_->rice_parameter_search_dist,
  104162. subframe[!_best_subframe],
  104163. partitioned_rice_contents[!_best_subframe]
  104164. );
  104165. if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
  104166. if(_candidate_bits < _best_bits) {
  104167. _best_subframe = !_best_subframe;
  104168. _best_bits = _candidate_bits;
  104169. }
  104170. }
  104171. }
  104172. }
  104173. }
  104174. }
  104175. }
  104176. }
  104177. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  104178. }
  104179. }
  104180. /* under rare circumstances this can happen when all but lpc subframe types are disabled: */
  104181. if(_best_bits == UINT_MAX) {
  104182. FLAC__ASSERT(_best_subframe == 0);
  104183. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  104184. }
  104185. *best_subframe = _best_subframe;
  104186. *best_bits = _best_bits;
  104187. return true;
  104188. }
  104189. FLAC__bool add_subframe_(
  104190. FLAC__StreamEncoder *encoder,
  104191. unsigned blocksize,
  104192. unsigned subframe_bps,
  104193. const FLAC__Subframe *subframe,
  104194. FLAC__BitWriter *frame
  104195. )
  104196. {
  104197. switch(subframe->type) {
  104198. case FLAC__SUBFRAME_TYPE_CONSTANT:
  104199. if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
  104200. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104201. return false;
  104202. }
  104203. break;
  104204. case FLAC__SUBFRAME_TYPE_FIXED:
  104205. if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
  104206. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104207. return false;
  104208. }
  104209. break;
  104210. case FLAC__SUBFRAME_TYPE_LPC:
  104211. if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
  104212. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104213. return false;
  104214. }
  104215. break;
  104216. case FLAC__SUBFRAME_TYPE_VERBATIM:
  104217. if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), blocksize, subframe_bps, subframe->wasted_bits, frame)) {
  104218. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104219. return false;
  104220. }
  104221. break;
  104222. default:
  104223. FLAC__ASSERT(0);
  104224. }
  104225. return true;
  104226. }
  104227. #define SPOTCHECK_ESTIMATE 0
  104228. #if SPOTCHECK_ESTIMATE
  104229. static void spotcheck_subframe_estimate_(
  104230. FLAC__StreamEncoder *encoder,
  104231. unsigned blocksize,
  104232. unsigned subframe_bps,
  104233. const FLAC__Subframe *subframe,
  104234. unsigned estimate
  104235. )
  104236. {
  104237. FLAC__bool ret;
  104238. FLAC__BitWriter *frame = FLAC__bitwriter_new();
  104239. if(frame == 0) {
  104240. fprintf(stderr, "EST: can't allocate frame\n");
  104241. return;
  104242. }
  104243. if(!FLAC__bitwriter_init(frame)) {
  104244. fprintf(stderr, "EST: can't init frame\n");
  104245. return;
  104246. }
  104247. ret = add_subframe_(encoder, blocksize, subframe_bps, subframe, frame);
  104248. FLAC__ASSERT(ret);
  104249. {
  104250. const unsigned actual = FLAC__bitwriter_get_input_bits_unconsumed(frame);
  104251. if(estimate != actual)
  104252. 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);
  104253. }
  104254. FLAC__bitwriter_delete(frame);
  104255. }
  104256. #endif
  104257. unsigned evaluate_constant_subframe_(
  104258. FLAC__StreamEncoder *encoder,
  104259. const FLAC__int32 signal,
  104260. unsigned blocksize,
  104261. unsigned subframe_bps,
  104262. FLAC__Subframe *subframe
  104263. )
  104264. {
  104265. unsigned estimate;
  104266. subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
  104267. subframe->data.constant.value = signal;
  104268. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + subframe_bps;
  104269. #if SPOTCHECK_ESTIMATE
  104270. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  104271. #else
  104272. (void)encoder, (void)blocksize;
  104273. #endif
  104274. return estimate;
  104275. }
  104276. unsigned evaluate_fixed_subframe_(
  104277. FLAC__StreamEncoder *encoder,
  104278. const FLAC__int32 signal[],
  104279. FLAC__int32 residual[],
  104280. FLAC__uint64 abs_residual_partition_sums[],
  104281. unsigned raw_bits_per_partition[],
  104282. unsigned blocksize,
  104283. unsigned subframe_bps,
  104284. unsigned order,
  104285. unsigned rice_parameter,
  104286. unsigned rice_parameter_limit,
  104287. unsigned min_partition_order,
  104288. unsigned max_partition_order,
  104289. FLAC__bool do_escape_coding,
  104290. unsigned rice_parameter_search_dist,
  104291. FLAC__Subframe *subframe,
  104292. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  104293. )
  104294. {
  104295. unsigned i, residual_bits, estimate;
  104296. const unsigned residual_samples = blocksize - order;
  104297. FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
  104298. subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
  104299. subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  104300. subframe->data.fixed.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  104301. subframe->data.fixed.residual = residual;
  104302. residual_bits =
  104303. find_best_partition_order_(
  104304. encoder->private_,
  104305. residual,
  104306. abs_residual_partition_sums,
  104307. raw_bits_per_partition,
  104308. residual_samples,
  104309. order,
  104310. rice_parameter,
  104311. rice_parameter_limit,
  104312. min_partition_order,
  104313. max_partition_order,
  104314. subframe_bps,
  104315. do_escape_coding,
  104316. rice_parameter_search_dist,
  104317. &subframe->data.fixed.entropy_coding_method
  104318. );
  104319. subframe->data.fixed.order = order;
  104320. for(i = 0; i < order; i++)
  104321. subframe->data.fixed.warmup[i] = signal[i];
  104322. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (order * subframe_bps) + residual_bits;
  104323. #if SPOTCHECK_ESTIMATE
  104324. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  104325. #endif
  104326. return estimate;
  104327. }
  104328. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104329. unsigned evaluate_lpc_subframe_(
  104330. FLAC__StreamEncoder *encoder,
  104331. const FLAC__int32 signal[],
  104332. FLAC__int32 residual[],
  104333. FLAC__uint64 abs_residual_partition_sums[],
  104334. unsigned raw_bits_per_partition[],
  104335. const FLAC__real lp_coeff[],
  104336. unsigned blocksize,
  104337. unsigned subframe_bps,
  104338. unsigned order,
  104339. unsigned qlp_coeff_precision,
  104340. unsigned rice_parameter,
  104341. unsigned rice_parameter_limit,
  104342. unsigned min_partition_order,
  104343. unsigned max_partition_order,
  104344. FLAC__bool do_escape_coding,
  104345. unsigned rice_parameter_search_dist,
  104346. FLAC__Subframe *subframe,
  104347. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  104348. )
  104349. {
  104350. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  104351. unsigned i, residual_bits, estimate;
  104352. int quantization, ret;
  104353. const unsigned residual_samples = blocksize - order;
  104354. /* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps streams */
  104355. if(subframe_bps <= 16) {
  104356. FLAC__ASSERT(order > 0);
  104357. FLAC__ASSERT(order <= FLAC__MAX_LPC_ORDER);
  104358. qlp_coeff_precision = min(qlp_coeff_precision, 32 - subframe_bps - FLAC__bitmath_ilog2(order));
  104359. }
  104360. ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, qlp_coeff, &quantization);
  104361. if(ret != 0)
  104362. return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
  104363. if(subframe_bps + qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  104364. if(subframe_bps <= 16 && qlp_coeff_precision <= 16)
  104365. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  104366. else
  104367. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  104368. else
  104369. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  104370. subframe->type = FLAC__SUBFRAME_TYPE_LPC;
  104371. subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  104372. subframe->data.lpc.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  104373. subframe->data.lpc.residual = residual;
  104374. residual_bits =
  104375. find_best_partition_order_(
  104376. encoder->private_,
  104377. residual,
  104378. abs_residual_partition_sums,
  104379. raw_bits_per_partition,
  104380. residual_samples,
  104381. order,
  104382. rice_parameter,
  104383. rice_parameter_limit,
  104384. min_partition_order,
  104385. max_partition_order,
  104386. subframe_bps,
  104387. do_escape_coding,
  104388. rice_parameter_search_dist,
  104389. &subframe->data.lpc.entropy_coding_method
  104390. );
  104391. subframe->data.lpc.order = order;
  104392. subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
  104393. subframe->data.lpc.quantization_level = quantization;
  104394. memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(FLAC__int32)*FLAC__MAX_LPC_ORDER);
  104395. for(i = 0; i < order; i++)
  104396. subframe->data.lpc.warmup[i] = signal[i];
  104397. 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;
  104398. #if SPOTCHECK_ESTIMATE
  104399. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  104400. #endif
  104401. return estimate;
  104402. }
  104403. #endif
  104404. unsigned evaluate_verbatim_subframe_(
  104405. FLAC__StreamEncoder *encoder,
  104406. const FLAC__int32 signal[],
  104407. unsigned blocksize,
  104408. unsigned subframe_bps,
  104409. FLAC__Subframe *subframe
  104410. )
  104411. {
  104412. unsigned estimate;
  104413. subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
  104414. subframe->data.verbatim.data = signal;
  104415. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (blocksize * subframe_bps);
  104416. #if SPOTCHECK_ESTIMATE
  104417. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  104418. #else
  104419. (void)encoder;
  104420. #endif
  104421. return estimate;
  104422. }
  104423. unsigned find_best_partition_order_(
  104424. FLAC__StreamEncoderPrivate *private_,
  104425. const FLAC__int32 residual[],
  104426. FLAC__uint64 abs_residual_partition_sums[],
  104427. unsigned raw_bits_per_partition[],
  104428. unsigned residual_samples,
  104429. unsigned predictor_order,
  104430. unsigned rice_parameter,
  104431. unsigned rice_parameter_limit,
  104432. unsigned min_partition_order,
  104433. unsigned max_partition_order,
  104434. unsigned bps,
  104435. FLAC__bool do_escape_coding,
  104436. unsigned rice_parameter_search_dist,
  104437. FLAC__EntropyCodingMethod *best_ecm
  104438. )
  104439. {
  104440. unsigned residual_bits, best_residual_bits = 0;
  104441. unsigned best_parameters_index = 0;
  104442. unsigned best_partition_order = 0;
  104443. const unsigned blocksize = residual_samples + predictor_order;
  104444. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(max_partition_order, blocksize, predictor_order);
  104445. min_partition_order = min(min_partition_order, max_partition_order);
  104446. precompute_partition_info_sums_(residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order, bps);
  104447. if(do_escape_coding)
  104448. precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order);
  104449. {
  104450. int partition_order;
  104451. unsigned sum;
  104452. for(partition_order = (int)max_partition_order, sum = 0; partition_order >= (int)min_partition_order; partition_order--) {
  104453. if(!
  104454. set_partitioned_rice_(
  104455. #ifdef EXACT_RICE_BITS_CALCULATION
  104456. residual,
  104457. #endif
  104458. abs_residual_partition_sums+sum,
  104459. raw_bits_per_partition+sum,
  104460. residual_samples,
  104461. predictor_order,
  104462. rice_parameter,
  104463. rice_parameter_limit,
  104464. rice_parameter_search_dist,
  104465. (unsigned)partition_order,
  104466. do_escape_coding,
  104467. &private_->partitioned_rice_contents_extra[!best_parameters_index],
  104468. &residual_bits
  104469. )
  104470. )
  104471. {
  104472. FLAC__ASSERT(best_residual_bits != 0);
  104473. break;
  104474. }
  104475. sum += 1u << partition_order;
  104476. if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
  104477. best_residual_bits = residual_bits;
  104478. best_parameters_index = !best_parameters_index;
  104479. best_partition_order = partition_order;
  104480. }
  104481. }
  104482. }
  104483. best_ecm->data.partitioned_rice.order = best_partition_order;
  104484. {
  104485. /*
  104486. * We are allowed to de-const the pointer based on our special
  104487. * knowledge; it is const to the outside world.
  104488. */
  104489. FLAC__EntropyCodingMethod_PartitionedRiceContents* prc = (FLAC__EntropyCodingMethod_PartitionedRiceContents*)best_ecm->data.partitioned_rice.contents;
  104490. unsigned partition;
  104491. /* save best parameters and raw_bits */
  104492. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(prc, max(6, best_partition_order));
  104493. memcpy(prc->parameters, private_->partitioned_rice_contents_extra[best_parameters_index].parameters, sizeof(unsigned)*(1<<(best_partition_order)));
  104494. if(do_escape_coding)
  104495. memcpy(prc->raw_bits, private_->partitioned_rice_contents_extra[best_parameters_index].raw_bits, sizeof(unsigned)*(1<<(best_partition_order)));
  104496. /*
  104497. * Now need to check if the type should be changed to
  104498. * FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 based on the
  104499. * size of the rice parameters.
  104500. */
  104501. for(partition = 0; partition < (1u<<best_partition_order); partition++) {
  104502. if(prc->parameters[partition] >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
  104503. best_ecm->type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2;
  104504. break;
  104505. }
  104506. }
  104507. }
  104508. return best_residual_bits;
  104509. }
  104510. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  104511. extern void precompute_partition_info_sums_32bit_asm_ia32_(
  104512. const FLAC__int32 residual[],
  104513. FLAC__uint64 abs_residual_partition_sums[],
  104514. unsigned blocksize,
  104515. unsigned predictor_order,
  104516. unsigned min_partition_order,
  104517. unsigned max_partition_order
  104518. );
  104519. #endif
  104520. void precompute_partition_info_sums_(
  104521. const FLAC__int32 residual[],
  104522. FLAC__uint64 abs_residual_partition_sums[],
  104523. unsigned residual_samples,
  104524. unsigned predictor_order,
  104525. unsigned min_partition_order,
  104526. unsigned max_partition_order,
  104527. unsigned bps
  104528. )
  104529. {
  104530. const unsigned default_partition_samples = (residual_samples + predictor_order) >> max_partition_order;
  104531. unsigned partitions = 1u << max_partition_order;
  104532. FLAC__ASSERT(default_partition_samples > predictor_order);
  104533. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  104534. /* slightly pessimistic but still catches all common cases */
  104535. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  104536. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  104537. precompute_partition_info_sums_32bit_asm_ia32_(residual, abs_residual_partition_sums, residual_samples + predictor_order, predictor_order, min_partition_order, max_partition_order);
  104538. return;
  104539. }
  104540. #endif
  104541. /* first do max_partition_order */
  104542. {
  104543. unsigned partition, residual_sample, end = (unsigned)(-(int)predictor_order);
  104544. /* slightly pessimistic but still catches all common cases */
  104545. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  104546. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  104547. FLAC__uint32 abs_residual_partition_sum;
  104548. for(partition = residual_sample = 0; partition < partitions; partition++) {
  104549. end += default_partition_samples;
  104550. abs_residual_partition_sum = 0;
  104551. for( ; residual_sample < end; residual_sample++)
  104552. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  104553. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  104554. }
  104555. }
  104556. else { /* have to pessimistically use 64 bits for accumulator */
  104557. FLAC__uint64 abs_residual_partition_sum;
  104558. for(partition = residual_sample = 0; partition < partitions; partition++) {
  104559. end += default_partition_samples;
  104560. abs_residual_partition_sum = 0;
  104561. for( ; residual_sample < end; residual_sample++)
  104562. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  104563. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  104564. }
  104565. }
  104566. }
  104567. /* now merge partitions for lower orders */
  104568. {
  104569. unsigned from_partition = 0, to_partition = partitions;
  104570. int partition_order;
  104571. for(partition_order = (int)max_partition_order - 1; partition_order >= (int)min_partition_order; partition_order--) {
  104572. unsigned i;
  104573. partitions >>= 1;
  104574. for(i = 0; i < partitions; i++) {
  104575. abs_residual_partition_sums[to_partition++] =
  104576. abs_residual_partition_sums[from_partition ] +
  104577. abs_residual_partition_sums[from_partition+1];
  104578. from_partition += 2;
  104579. }
  104580. }
  104581. }
  104582. }
  104583. void precompute_partition_info_escapes_(
  104584. const FLAC__int32 residual[],
  104585. unsigned raw_bits_per_partition[],
  104586. unsigned residual_samples,
  104587. unsigned predictor_order,
  104588. unsigned min_partition_order,
  104589. unsigned max_partition_order
  104590. )
  104591. {
  104592. int partition_order;
  104593. unsigned from_partition, to_partition = 0;
  104594. const unsigned blocksize = residual_samples + predictor_order;
  104595. /* first do max_partition_order */
  104596. for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
  104597. FLAC__int32 r;
  104598. FLAC__uint32 rmax;
  104599. unsigned partition, partition_sample, partition_samples, residual_sample;
  104600. const unsigned partitions = 1u << partition_order;
  104601. const unsigned default_partition_samples = blocksize >> partition_order;
  104602. FLAC__ASSERT(default_partition_samples > predictor_order);
  104603. for(partition = residual_sample = 0; partition < partitions; partition++) {
  104604. partition_samples = default_partition_samples;
  104605. if(partition == 0)
  104606. partition_samples -= predictor_order;
  104607. rmax = 0;
  104608. for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
  104609. r = residual[residual_sample++];
  104610. /* OPT: maybe faster: rmax |= r ^ (r>>31) */
  104611. if(r < 0)
  104612. rmax |= ~r;
  104613. else
  104614. rmax |= r;
  104615. }
  104616. /* now we know all residual values are in the range [-rmax-1,rmax] */
  104617. raw_bits_per_partition[partition] = rmax? FLAC__bitmath_ilog2(rmax) + 2 : 1;
  104618. }
  104619. to_partition = partitions;
  104620. break; /*@@@ yuck, should remove the 'for' loop instead */
  104621. }
  104622. /* now merge partitions for lower orders */
  104623. for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
  104624. unsigned m;
  104625. unsigned i;
  104626. const unsigned partitions = 1u << partition_order;
  104627. for(i = 0; i < partitions; i++) {
  104628. m = raw_bits_per_partition[from_partition];
  104629. from_partition++;
  104630. raw_bits_per_partition[to_partition] = max(m, raw_bits_per_partition[from_partition]);
  104631. from_partition++;
  104632. to_partition++;
  104633. }
  104634. }
  104635. }
  104636. #ifdef EXACT_RICE_BITS_CALCULATION
  104637. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  104638. const unsigned rice_parameter,
  104639. const unsigned partition_samples,
  104640. const FLAC__int32 *residual
  104641. )
  104642. {
  104643. unsigned i, partition_bits =
  104644. 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 */
  104645. (1+rice_parameter) * partition_samples /* 1 for unary stop bit + rice_parameter for the binary portion */
  104646. ;
  104647. for(i = 0; i < partition_samples; i++)
  104648. partition_bits += ( (FLAC__uint32)((residual[i]<<1)^(residual[i]>>31)) >> rice_parameter );
  104649. return partition_bits;
  104650. }
  104651. #else
  104652. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  104653. const unsigned rice_parameter,
  104654. const unsigned partition_samples,
  104655. const FLAC__uint64 abs_residual_partition_sum
  104656. )
  104657. {
  104658. return
  104659. 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 */
  104660. (1+rice_parameter) * partition_samples + /* 1 for unary stop bit + rice_parameter for the binary portion */
  104661. (
  104662. rice_parameter?
  104663. (unsigned)(abs_residual_partition_sum >> (rice_parameter-1)) /* rice_parameter-1 because the real coder sign-folds instead of using a sign bit */
  104664. : (unsigned)(abs_residual_partition_sum << 1) /* can't shift by negative number, so reverse */
  104665. )
  104666. - (partition_samples >> 1)
  104667. /* -(partition_samples>>1) to subtract out extra contributions to the abs_residual_partition_sum.
  104668. * The actual number of bits used is closer to the sum(for all i in the partition) of abs(residual[i])>>(rice_parameter-1)
  104669. * By using the abs_residual_partition sum, we also add in bits in the LSBs that would normally be shifted out.
  104670. * So the subtraction term tries to guess how many extra bits were contributed.
  104671. * If the LSBs are randomly distributed, this should average to 0.5 extra bits per sample.
  104672. */
  104673. ;
  104674. }
  104675. #endif
  104676. FLAC__bool set_partitioned_rice_(
  104677. #ifdef EXACT_RICE_BITS_CALCULATION
  104678. const FLAC__int32 residual[],
  104679. #endif
  104680. const FLAC__uint64 abs_residual_partition_sums[],
  104681. const unsigned raw_bits_per_partition[],
  104682. const unsigned residual_samples,
  104683. const unsigned predictor_order,
  104684. const unsigned suggested_rice_parameter,
  104685. const unsigned rice_parameter_limit,
  104686. const unsigned rice_parameter_search_dist,
  104687. const unsigned partition_order,
  104688. const FLAC__bool search_for_escapes,
  104689. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  104690. unsigned *bits
  104691. )
  104692. {
  104693. unsigned rice_parameter, partition_bits;
  104694. unsigned best_partition_bits, best_rice_parameter = 0;
  104695. unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
  104696. unsigned *parameters, *raw_bits;
  104697. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  104698. unsigned min_rice_parameter, max_rice_parameter;
  104699. #else
  104700. (void)rice_parameter_search_dist;
  104701. #endif
  104702. FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  104703. FLAC__ASSERT(rice_parameter_limit <= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  104704. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order));
  104705. parameters = partitioned_rice_contents->parameters;
  104706. raw_bits = partitioned_rice_contents->raw_bits;
  104707. if(partition_order == 0) {
  104708. best_partition_bits = (unsigned)(-1);
  104709. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  104710. if(rice_parameter_search_dist) {
  104711. if(suggested_rice_parameter < rice_parameter_search_dist)
  104712. min_rice_parameter = 0;
  104713. else
  104714. min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
  104715. max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
  104716. if(max_rice_parameter >= rice_parameter_limit) {
  104717. #ifdef DEBUG_VERBOSE
  104718. fprintf(stderr, "clipping rice_parameter (%u -> %u) @5\n", max_rice_parameter, rice_parameter_limit - 1);
  104719. #endif
  104720. max_rice_parameter = rice_parameter_limit - 1;
  104721. }
  104722. }
  104723. else
  104724. min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
  104725. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  104726. #else
  104727. rice_parameter = suggested_rice_parameter;
  104728. #endif
  104729. #ifdef EXACT_RICE_BITS_CALCULATION
  104730. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, residual);
  104731. #else
  104732. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, abs_residual_partition_sums[0]);
  104733. #endif
  104734. if(partition_bits < best_partition_bits) {
  104735. best_rice_parameter = rice_parameter;
  104736. best_partition_bits = partition_bits;
  104737. }
  104738. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  104739. }
  104740. #endif
  104741. if(search_for_escapes) {
  104742. 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;
  104743. if(partition_bits <= best_partition_bits) {
  104744. raw_bits[0] = raw_bits_per_partition[0];
  104745. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  104746. best_partition_bits = partition_bits;
  104747. }
  104748. else
  104749. raw_bits[0] = 0;
  104750. }
  104751. parameters[0] = best_rice_parameter;
  104752. bits_ += best_partition_bits;
  104753. }
  104754. else {
  104755. unsigned partition, residual_sample;
  104756. unsigned partition_samples;
  104757. FLAC__uint64 mean, k;
  104758. const unsigned partitions = 1u << partition_order;
  104759. for(partition = residual_sample = 0; partition < partitions; partition++) {
  104760. partition_samples = (residual_samples+predictor_order) >> partition_order;
  104761. if(partition == 0) {
  104762. if(partition_samples <= predictor_order)
  104763. return false;
  104764. else
  104765. partition_samples -= predictor_order;
  104766. }
  104767. mean = abs_residual_partition_sums[partition];
  104768. /* we are basically calculating the size in bits of the
  104769. * average residual magnitude in the partition:
  104770. * rice_parameter = floor(log2(mean/partition_samples))
  104771. * 'mean' is not a good name for the variable, it is
  104772. * actually the sum of magnitudes of all residual values
  104773. * in the partition, so the actual mean is
  104774. * mean/partition_samples
  104775. */
  104776. for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
  104777. ;
  104778. if(rice_parameter >= rice_parameter_limit) {
  104779. #ifdef DEBUG_VERBOSE
  104780. fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, rice_parameter_limit - 1);
  104781. #endif
  104782. rice_parameter = rice_parameter_limit - 1;
  104783. }
  104784. best_partition_bits = (unsigned)(-1);
  104785. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  104786. if(rice_parameter_search_dist) {
  104787. if(rice_parameter < rice_parameter_search_dist)
  104788. min_rice_parameter = 0;
  104789. else
  104790. min_rice_parameter = rice_parameter - rice_parameter_search_dist;
  104791. max_rice_parameter = rice_parameter + rice_parameter_search_dist;
  104792. if(max_rice_parameter >= rice_parameter_limit) {
  104793. #ifdef DEBUG_VERBOSE
  104794. fprintf(stderr, "clipping rice_parameter (%u -> %u) @7\n", max_rice_parameter, rice_parameter_limit - 1);
  104795. #endif
  104796. max_rice_parameter = rice_parameter_limit - 1;
  104797. }
  104798. }
  104799. else
  104800. min_rice_parameter = max_rice_parameter = rice_parameter;
  104801. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  104802. #endif
  104803. #ifdef EXACT_RICE_BITS_CALCULATION
  104804. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, residual+residual_sample);
  104805. #else
  104806. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, abs_residual_partition_sums[partition]);
  104807. #endif
  104808. if(partition_bits < best_partition_bits) {
  104809. best_rice_parameter = rice_parameter;
  104810. best_partition_bits = partition_bits;
  104811. }
  104812. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  104813. }
  104814. #endif
  104815. if(search_for_escapes) {
  104816. 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;
  104817. if(partition_bits <= best_partition_bits) {
  104818. raw_bits[partition] = raw_bits_per_partition[partition];
  104819. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  104820. best_partition_bits = partition_bits;
  104821. }
  104822. else
  104823. raw_bits[partition] = 0;
  104824. }
  104825. parameters[partition] = best_rice_parameter;
  104826. bits_ += best_partition_bits;
  104827. residual_sample += partition_samples;
  104828. }
  104829. }
  104830. *bits = bits_;
  104831. return true;
  104832. }
  104833. unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples)
  104834. {
  104835. unsigned i, shift;
  104836. FLAC__int32 x = 0;
  104837. for(i = 0; i < samples && !(x&1); i++)
  104838. x |= signal[i];
  104839. if(x == 0) {
  104840. shift = 0;
  104841. }
  104842. else {
  104843. for(shift = 0; !(x&1); shift++)
  104844. x >>= 1;
  104845. }
  104846. if(shift > 0) {
  104847. for(i = 0; i < samples; i++)
  104848. signal[i] >>= shift;
  104849. }
  104850. return shift;
  104851. }
  104852. void append_to_verify_fifo_(verify_input_fifo *fifo, const FLAC__int32 * const input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  104853. {
  104854. unsigned channel;
  104855. for(channel = 0; channel < channels; channel++)
  104856. memcpy(&fifo->data[channel][fifo->tail], &input[channel][input_offset], sizeof(FLAC__int32) * wide_samples);
  104857. fifo->tail += wide_samples;
  104858. FLAC__ASSERT(fifo->tail <= fifo->size);
  104859. }
  104860. void append_to_verify_fifo_interleaved_(verify_input_fifo *fifo, const FLAC__int32 input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  104861. {
  104862. unsigned channel;
  104863. unsigned sample, wide_sample;
  104864. unsigned tail = fifo->tail;
  104865. sample = input_offset * channels;
  104866. for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
  104867. for(channel = 0; channel < channels; channel++)
  104868. fifo->data[channel][tail] = input[sample++];
  104869. tail++;
  104870. }
  104871. fifo->tail = tail;
  104872. FLAC__ASSERT(fifo->tail <= fifo->size);
  104873. }
  104874. FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  104875. {
  104876. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  104877. const size_t encoded_bytes = encoder->private_->verify.output.bytes;
  104878. (void)decoder;
  104879. if(encoder->private_->verify.needs_magic_hack) {
  104880. FLAC__ASSERT(*bytes >= FLAC__STREAM_SYNC_LENGTH);
  104881. *bytes = FLAC__STREAM_SYNC_LENGTH;
  104882. memcpy(buffer, FLAC__STREAM_SYNC_STRING, *bytes);
  104883. encoder->private_->verify.needs_magic_hack = false;
  104884. }
  104885. else {
  104886. if(encoded_bytes == 0) {
  104887. /*
  104888. * If we get here, a FIFO underflow has occurred,
  104889. * which means there is a bug somewhere.
  104890. */
  104891. FLAC__ASSERT(0);
  104892. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  104893. }
  104894. else if(encoded_bytes < *bytes)
  104895. *bytes = encoded_bytes;
  104896. memcpy(buffer, encoder->private_->verify.output.data, *bytes);
  104897. encoder->private_->verify.output.data += *bytes;
  104898. encoder->private_->verify.output.bytes -= *bytes;
  104899. }
  104900. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  104901. }
  104902. FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
  104903. {
  104904. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder *)client_data;
  104905. unsigned channel;
  104906. const unsigned channels = frame->header.channels;
  104907. const unsigned blocksize = frame->header.blocksize;
  104908. const unsigned bytes_per_block = sizeof(FLAC__int32) * blocksize;
  104909. (void)decoder;
  104910. for(channel = 0; channel < channels; channel++) {
  104911. if(0 != memcmp(buffer[channel], encoder->private_->verify.input_fifo.data[channel], bytes_per_block)) {
  104912. unsigned i, sample = 0;
  104913. FLAC__int32 expect = 0, got = 0;
  104914. for(i = 0; i < blocksize; i++) {
  104915. if(buffer[channel][i] != encoder->private_->verify.input_fifo.data[channel][i]) {
  104916. sample = i;
  104917. expect = (FLAC__int32)encoder->private_->verify.input_fifo.data[channel][i];
  104918. got = (FLAC__int32)buffer[channel][i];
  104919. break;
  104920. }
  104921. }
  104922. FLAC__ASSERT(i < blocksize);
  104923. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  104924. encoder->private_->verify.error_stats.absolute_sample = frame->header.number.sample_number + sample;
  104925. encoder->private_->verify.error_stats.frame_number = (unsigned)(frame->header.number.sample_number / blocksize);
  104926. encoder->private_->verify.error_stats.channel = channel;
  104927. encoder->private_->verify.error_stats.sample = sample;
  104928. encoder->private_->verify.error_stats.expected = expect;
  104929. encoder->private_->verify.error_stats.got = got;
  104930. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  104931. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  104932. }
  104933. }
  104934. /* dequeue the frame from the fifo */
  104935. encoder->private_->verify.input_fifo.tail -= blocksize;
  104936. FLAC__ASSERT(encoder->private_->verify.input_fifo.tail <= OVERREAD_);
  104937. for(channel = 0; channel < channels; channel++)
  104938. 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]));
  104939. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  104940. }
  104941. void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
  104942. {
  104943. (void)decoder, (void)metadata, (void)client_data;
  104944. }
  104945. void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
  104946. {
  104947. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  104948. (void)decoder, (void)status;
  104949. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  104950. }
  104951. FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  104952. {
  104953. (void)client_data;
  104954. *bytes = fread(buffer, 1, *bytes, encoder->private_->file);
  104955. if (*bytes == 0) {
  104956. if (feof(encoder->private_->file))
  104957. return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  104958. else if (ferror(encoder->private_->file))
  104959. return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  104960. }
  104961. return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  104962. }
  104963. FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  104964. {
  104965. (void)client_data;
  104966. if(fseeko(encoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  104967. return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  104968. else
  104969. return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  104970. }
  104971. FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  104972. {
  104973. off_t offset;
  104974. (void)client_data;
  104975. offset = ftello(encoder->private_->file);
  104976. if(offset < 0) {
  104977. return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  104978. }
  104979. else {
  104980. *absolute_byte_offset = (FLAC__uint64)offset;
  104981. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  104982. }
  104983. }
  104984. #ifdef FLAC__VALGRIND_TESTING
  104985. static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
  104986. {
  104987. size_t ret = fwrite(ptr, size, nmemb, stream);
  104988. if(!ferror(stream))
  104989. fflush(stream);
  104990. return ret;
  104991. }
  104992. #else
  104993. #define local__fwrite fwrite
  104994. #endif
  104995. FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data)
  104996. {
  104997. (void)client_data, (void)current_frame;
  104998. if(local__fwrite(buffer, sizeof(FLAC__byte), bytes, encoder->private_->file) == bytes) {
  104999. FLAC__bool call_it = 0 != encoder->private_->progress_callback && (
  105000. #if FLAC__HAS_OGG
  105001. /* We would like to be able to use 'samples > 0' in the
  105002. * clause here but currently because of the nature of our
  105003. * Ogg writing implementation, 'samples' is always 0 (see
  105004. * ogg_encoder_aspect.c). The downside is extra progress
  105005. * callbacks.
  105006. */
  105007. encoder->private_->is_ogg? true :
  105008. #endif
  105009. samples > 0
  105010. );
  105011. if(call_it) {
  105012. /* NOTE: We have to add +bytes, +samples, and +1 to the stats
  105013. * because at this point in the callback chain, the stats
  105014. * have not been updated. Only after we return and control
  105015. * gets back to write_frame_() are the stats updated
  105016. */
  105017. 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);
  105018. }
  105019. return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
  105020. }
  105021. else
  105022. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  105023. }
  105024. /*
  105025. * This will forcibly set stdout to binary mode (for OSes that require it)
  105026. */
  105027. FILE *get_binary_stdout_(void)
  105028. {
  105029. /* if something breaks here it is probably due to the presence or
  105030. * absence of an underscore before the identifiers 'setmode',
  105031. * 'fileno', and/or 'O_BINARY'; check your system header files.
  105032. */
  105033. #if defined _MSC_VER || defined __MINGW32__
  105034. _setmode(_fileno(stdout), _O_BINARY);
  105035. #elif defined __CYGWIN__
  105036. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  105037. setmode(_fileno(stdout), _O_BINARY);
  105038. #elif defined __EMX__
  105039. setmode(fileno(stdout), O_BINARY);
  105040. #endif
  105041. return stdout;
  105042. }
  105043. #endif
  105044. /*** End of inlined file: stream_encoder.c ***/
  105045. /*** Start of inlined file: stream_encoder_framing.c ***/
  105046. /*** Start of inlined file: juce_FlacHeader.h ***/
  105047. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  105048. // tasks..
  105049. #define VERSION "1.2.1"
  105050. #define FLAC__NO_DLL 1
  105051. #if JUCE_MSVC
  105052. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  105053. #endif
  105054. #if JUCE_MAC
  105055. #define FLAC__SYS_DARWIN 1
  105056. #endif
  105057. /*** End of inlined file: juce_FlacHeader.h ***/
  105058. #if JUCE_USE_FLAC
  105059. #if HAVE_CONFIG_H
  105060. # include <config.h>
  105061. #endif
  105062. #include <stdio.h>
  105063. #include <string.h> /* for strlen() */
  105064. #ifdef max
  105065. #undef max
  105066. #endif
  105067. #define max(x,y) ((x)>(y)?(x):(y))
  105068. static FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method);
  105069. 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);
  105070. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw)
  105071. {
  105072. unsigned i, j;
  105073. const unsigned vendor_string_length = (unsigned)strlen(FLAC__VENDOR_STRING);
  105074. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->is_last, FLAC__STREAM_METADATA_IS_LAST_LEN))
  105075. return false;
  105076. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->type, FLAC__STREAM_METADATA_TYPE_LEN))
  105077. return false;
  105078. /*
  105079. * First, for VORBIS_COMMENTs, adjust the length to reflect our vendor string
  105080. */
  105081. i = metadata->length;
  105082. if(metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  105083. FLAC__ASSERT(metadata->data.vorbis_comment.vendor_string.length == 0 || 0 != metadata->data.vorbis_comment.vendor_string.entry);
  105084. i -= metadata->data.vorbis_comment.vendor_string.length;
  105085. i += vendor_string_length;
  105086. }
  105087. FLAC__ASSERT(i < (1u << FLAC__STREAM_METADATA_LENGTH_LEN));
  105088. if(!FLAC__bitwriter_write_raw_uint32(bw, i, FLAC__STREAM_METADATA_LENGTH_LEN))
  105089. return false;
  105090. switch(metadata->type) {
  105091. case FLAC__METADATA_TYPE_STREAMINFO:
  105092. FLAC__ASSERT(metadata->data.stream_info.min_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN));
  105093. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN))
  105094. return false;
  105095. FLAC__ASSERT(metadata->data.stream_info.max_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN));
  105096. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  105097. return false;
  105098. FLAC__ASSERT(metadata->data.stream_info.min_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN));
  105099. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_framesize, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  105100. return false;
  105101. FLAC__ASSERT(metadata->data.stream_info.max_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN));
  105102. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_framesize, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  105103. return false;
  105104. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(metadata->data.stream_info.sample_rate));
  105105. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.sample_rate, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  105106. return false;
  105107. FLAC__ASSERT(metadata->data.stream_info.channels > 0);
  105108. FLAC__ASSERT(metadata->data.stream_info.channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN));
  105109. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.channels-1, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  105110. return false;
  105111. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample > 0);
  105112. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  105113. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.bits_per_sample-1, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  105114. return false;
  105115. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.stream_info.total_samples, FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN))
  105116. return false;
  105117. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.stream_info.md5sum, 16))
  105118. return false;
  105119. break;
  105120. case FLAC__METADATA_TYPE_PADDING:
  105121. if(!FLAC__bitwriter_write_zeroes(bw, metadata->length * 8))
  105122. return false;
  105123. break;
  105124. case FLAC__METADATA_TYPE_APPLICATION:
  105125. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8))
  105126. return false;
  105127. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.data, metadata->length - (FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8)))
  105128. return false;
  105129. break;
  105130. case FLAC__METADATA_TYPE_SEEKTABLE:
  105131. for(i = 0; i < metadata->data.seek_table.num_points; i++) {
  105132. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].sample_number, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  105133. return false;
  105134. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].stream_offset, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  105135. return false;
  105136. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.seek_table.points[i].frame_samples, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  105137. return false;
  105138. }
  105139. break;
  105140. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  105141. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, vendor_string_length))
  105142. return false;
  105143. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)FLAC__VENDOR_STRING, vendor_string_length))
  105144. return false;
  105145. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.num_comments))
  105146. return false;
  105147. for(i = 0; i < metadata->data.vorbis_comment.num_comments; i++) {
  105148. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.comments[i].length))
  105149. return false;
  105150. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.vorbis_comment.comments[i].entry, metadata->data.vorbis_comment.comments[i].length))
  105151. return false;
  105152. }
  105153. break;
  105154. case FLAC__METADATA_TYPE_CUESHEET:
  105155. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  105156. 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))
  105157. return false;
  105158. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.cue_sheet.lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  105159. return false;
  105160. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.is_cd? 1 : 0, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  105161. return false;
  105162. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  105163. return false;
  105164. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.num_tracks, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  105165. return false;
  105166. for(i = 0; i < metadata->data.cue_sheet.num_tracks; i++) {
  105167. const FLAC__StreamMetadata_CueSheet_Track *track = metadata->data.cue_sheet.tracks + i;
  105168. if(!FLAC__bitwriter_write_raw_uint64(bw, track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  105169. return false;
  105170. if(!FLAC__bitwriter_write_raw_uint32(bw, track->number, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  105171. return false;
  105172. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  105173. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  105174. return false;
  105175. if(!FLAC__bitwriter_write_raw_uint32(bw, track->type, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  105176. return false;
  105177. if(!FLAC__bitwriter_write_raw_uint32(bw, track->pre_emphasis, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  105178. return false;
  105179. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  105180. return false;
  105181. if(!FLAC__bitwriter_write_raw_uint32(bw, track->num_indices, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  105182. return false;
  105183. for(j = 0; j < track->num_indices; j++) {
  105184. const FLAC__StreamMetadata_CueSheet_Index *index = track->indices + j;
  105185. if(!FLAC__bitwriter_write_raw_uint64(bw, index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  105186. return false;
  105187. if(!FLAC__bitwriter_write_raw_uint32(bw, index->number, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  105188. return false;
  105189. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  105190. return false;
  105191. }
  105192. }
  105193. break;
  105194. case FLAC__METADATA_TYPE_PICTURE:
  105195. {
  105196. size_t len;
  105197. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.type, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  105198. return false;
  105199. len = strlen(metadata->data.picture.mime_type);
  105200. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  105201. return false;
  105202. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)metadata->data.picture.mime_type, len))
  105203. return false;
  105204. len = strlen((const char *)metadata->data.picture.description);
  105205. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  105206. return false;
  105207. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.description, len))
  105208. return false;
  105209. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  105210. return false;
  105211. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  105212. return false;
  105213. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  105214. return false;
  105215. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  105216. return false;
  105217. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.data_length, FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  105218. return false;
  105219. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.data, metadata->data.picture.data_length))
  105220. return false;
  105221. }
  105222. break;
  105223. default:
  105224. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.unknown.data, metadata->length))
  105225. return false;
  105226. break;
  105227. }
  105228. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  105229. return true;
  105230. }
  105231. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw)
  105232. {
  105233. unsigned u, blocksize_hint, sample_rate_hint;
  105234. FLAC__byte crc;
  105235. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  105236. if(!FLAC__bitwriter_write_raw_uint32(bw, FLAC__FRAME_HEADER_SYNC, FLAC__FRAME_HEADER_SYNC_LEN))
  105237. return false;
  105238. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_RESERVED_LEN))
  105239. return false;
  105240. if(!FLAC__bitwriter_write_raw_uint32(bw, (header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER)? 0 : 1, FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN))
  105241. return false;
  105242. FLAC__ASSERT(header->blocksize > 0 && header->blocksize <= FLAC__MAX_BLOCK_SIZE);
  105243. /* when this assertion holds true, any legal blocksize can be expressed in the frame header */
  105244. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535u);
  105245. blocksize_hint = 0;
  105246. switch(header->blocksize) {
  105247. case 192: u = 1; break;
  105248. case 576: u = 2; break;
  105249. case 1152: u = 3; break;
  105250. case 2304: u = 4; break;
  105251. case 4608: u = 5; break;
  105252. case 256: u = 8; break;
  105253. case 512: u = 9; break;
  105254. case 1024: u = 10; break;
  105255. case 2048: u = 11; break;
  105256. case 4096: u = 12; break;
  105257. case 8192: u = 13; break;
  105258. case 16384: u = 14; break;
  105259. case 32768: u = 15; break;
  105260. default:
  105261. if(header->blocksize <= 0x100)
  105262. blocksize_hint = u = 6;
  105263. else
  105264. blocksize_hint = u = 7;
  105265. break;
  105266. }
  105267. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BLOCK_SIZE_LEN))
  105268. return false;
  105269. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(header->sample_rate));
  105270. sample_rate_hint = 0;
  105271. switch(header->sample_rate) {
  105272. case 88200: u = 1; break;
  105273. case 176400: u = 2; break;
  105274. case 192000: u = 3; break;
  105275. case 8000: u = 4; break;
  105276. case 16000: u = 5; break;
  105277. case 22050: u = 6; break;
  105278. case 24000: u = 7; break;
  105279. case 32000: u = 8; break;
  105280. case 44100: u = 9; break;
  105281. case 48000: u = 10; break;
  105282. case 96000: u = 11; break;
  105283. default:
  105284. if(header->sample_rate <= 255000 && header->sample_rate % 1000 == 0)
  105285. sample_rate_hint = u = 12;
  105286. else if(header->sample_rate % 10 == 0)
  105287. sample_rate_hint = u = 14;
  105288. else if(header->sample_rate <= 0xffff)
  105289. sample_rate_hint = u = 13;
  105290. else
  105291. u = 0;
  105292. break;
  105293. }
  105294. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_SAMPLE_RATE_LEN))
  105295. return false;
  105296. FLAC__ASSERT(header->channels > 0 && header->channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN) && header->channels <= FLAC__MAX_CHANNELS);
  105297. switch(header->channel_assignment) {
  105298. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  105299. u = header->channels - 1;
  105300. break;
  105301. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  105302. FLAC__ASSERT(header->channels == 2);
  105303. u = 8;
  105304. break;
  105305. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  105306. FLAC__ASSERT(header->channels == 2);
  105307. u = 9;
  105308. break;
  105309. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  105310. FLAC__ASSERT(header->channels == 2);
  105311. u = 10;
  105312. break;
  105313. default:
  105314. FLAC__ASSERT(0);
  105315. }
  105316. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN))
  105317. return false;
  105318. FLAC__ASSERT(header->bits_per_sample > 0 && header->bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  105319. switch(header->bits_per_sample) {
  105320. case 8 : u = 1; break;
  105321. case 12: u = 2; break;
  105322. case 16: u = 4; break;
  105323. case 20: u = 5; break;
  105324. case 24: u = 6; break;
  105325. default: u = 0; break;
  105326. }
  105327. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN))
  105328. return false;
  105329. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_ZERO_PAD_LEN))
  105330. return false;
  105331. if(header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  105332. if(!FLAC__bitwriter_write_utf8_uint32(bw, header->number.frame_number))
  105333. return false;
  105334. }
  105335. else {
  105336. if(!FLAC__bitwriter_write_utf8_uint64(bw, header->number.sample_number))
  105337. return false;
  105338. }
  105339. if(blocksize_hint)
  105340. if(!FLAC__bitwriter_write_raw_uint32(bw, header->blocksize-1, (blocksize_hint==6)? 8:16))
  105341. return false;
  105342. switch(sample_rate_hint) {
  105343. case 12:
  105344. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 1000, 8))
  105345. return false;
  105346. break;
  105347. case 13:
  105348. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate, 16))
  105349. return false;
  105350. break;
  105351. case 14:
  105352. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 10, 16))
  105353. return false;
  105354. break;
  105355. }
  105356. /* write the CRC */
  105357. if(!FLAC__bitwriter_get_write_crc8(bw, &crc))
  105358. return false;
  105359. if(!FLAC__bitwriter_write_raw_uint32(bw, crc, FLAC__FRAME_HEADER_CRC_LEN))
  105360. return false;
  105361. return true;
  105362. }
  105363. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  105364. {
  105365. FLAC__bool ok;
  105366. ok =
  105367. 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) &&
  105368. (wasted_bits? FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1) : true) &&
  105369. FLAC__bitwriter_write_raw_int32(bw, subframe->value, subframe_bps)
  105370. ;
  105371. return ok;
  105372. }
  105373. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  105374. {
  105375. unsigned i;
  105376. 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))
  105377. return false;
  105378. if(wasted_bits)
  105379. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  105380. return false;
  105381. for(i = 0; i < subframe->order; i++)
  105382. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  105383. return false;
  105384. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  105385. return false;
  105386. switch(subframe->entropy_coding_method.type) {
  105387. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  105388. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  105389. if(!add_residual_partitioned_rice_(
  105390. bw,
  105391. subframe->residual,
  105392. residual_samples,
  105393. subframe->order,
  105394. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  105395. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  105396. subframe->entropy_coding_method.data.partitioned_rice.order,
  105397. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  105398. ))
  105399. return false;
  105400. break;
  105401. default:
  105402. FLAC__ASSERT(0);
  105403. }
  105404. return true;
  105405. }
  105406. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  105407. {
  105408. unsigned i;
  105409. 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))
  105410. return false;
  105411. if(wasted_bits)
  105412. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  105413. return false;
  105414. for(i = 0; i < subframe->order; i++)
  105415. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  105416. return false;
  105417. if(!FLAC__bitwriter_write_raw_uint32(bw, subframe->qlp_coeff_precision-1, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  105418. return false;
  105419. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->quantization_level, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  105420. return false;
  105421. for(i = 0; i < subframe->order; i++)
  105422. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->qlp_coeff[i], subframe->qlp_coeff_precision))
  105423. return false;
  105424. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  105425. return false;
  105426. switch(subframe->entropy_coding_method.type) {
  105427. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  105428. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  105429. if(!add_residual_partitioned_rice_(
  105430. bw,
  105431. subframe->residual,
  105432. residual_samples,
  105433. subframe->order,
  105434. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  105435. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  105436. subframe->entropy_coding_method.data.partitioned_rice.order,
  105437. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  105438. ))
  105439. return false;
  105440. break;
  105441. default:
  105442. FLAC__ASSERT(0);
  105443. }
  105444. return true;
  105445. }
  105446. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  105447. {
  105448. unsigned i;
  105449. const FLAC__int32 *signal = subframe->data;
  105450. 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))
  105451. return false;
  105452. if(wasted_bits)
  105453. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  105454. return false;
  105455. for(i = 0; i < samples; i++)
  105456. if(!FLAC__bitwriter_write_raw_int32(bw, signal[i], subframe_bps))
  105457. return false;
  105458. return true;
  105459. }
  105460. FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method)
  105461. {
  105462. if(!FLAC__bitwriter_write_raw_uint32(bw, method->type, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  105463. return false;
  105464. switch(method->type) {
  105465. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  105466. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  105467. if(!FLAC__bitwriter_write_raw_uint32(bw, method->data.partitioned_rice.order, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  105468. return false;
  105469. break;
  105470. default:
  105471. FLAC__ASSERT(0);
  105472. }
  105473. return true;
  105474. }
  105475. 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)
  105476. {
  105477. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  105478. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  105479. if(partition_order == 0) {
  105480. unsigned i;
  105481. if(raw_bits[0] == 0) {
  105482. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[0], plen))
  105483. return false;
  105484. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual, residual_samples, rice_parameters[0]))
  105485. return false;
  105486. }
  105487. else {
  105488. FLAC__ASSERT(rice_parameters[0] == 0);
  105489. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  105490. return false;
  105491. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[0], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  105492. return false;
  105493. for(i = 0; i < residual_samples; i++) {
  105494. if(!FLAC__bitwriter_write_raw_int32(bw, residual[i], raw_bits[0]))
  105495. return false;
  105496. }
  105497. }
  105498. return true;
  105499. }
  105500. else {
  105501. unsigned i, j, k = 0, k_last = 0;
  105502. unsigned partition_samples;
  105503. const unsigned default_partition_samples = (residual_samples+predictor_order) >> partition_order;
  105504. for(i = 0; i < (1u<<partition_order); i++) {
  105505. partition_samples = default_partition_samples;
  105506. if(i == 0)
  105507. partition_samples -= predictor_order;
  105508. k += partition_samples;
  105509. if(raw_bits[i] == 0) {
  105510. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[i], plen))
  105511. return false;
  105512. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual+k_last, k-k_last, rice_parameters[i]))
  105513. return false;
  105514. }
  105515. else {
  105516. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  105517. return false;
  105518. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[i], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  105519. return false;
  105520. for(j = k_last; j < k; j++) {
  105521. if(!FLAC__bitwriter_write_raw_int32(bw, residual[j], raw_bits[i]))
  105522. return false;
  105523. }
  105524. }
  105525. k_last = k;
  105526. }
  105527. return true;
  105528. }
  105529. }
  105530. #endif
  105531. /*** End of inlined file: stream_encoder_framing.c ***/
  105532. /*** Start of inlined file: window_flac.c ***/
  105533. /*** Start of inlined file: juce_FlacHeader.h ***/
  105534. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  105535. // tasks..
  105536. #define VERSION "1.2.1"
  105537. #define FLAC__NO_DLL 1
  105538. #if JUCE_MSVC
  105539. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  105540. #endif
  105541. #if JUCE_MAC
  105542. #define FLAC__SYS_DARWIN 1
  105543. #endif
  105544. /*** End of inlined file: juce_FlacHeader.h ***/
  105545. #if JUCE_USE_FLAC
  105546. #if HAVE_CONFIG_H
  105547. # include <config.h>
  105548. #endif
  105549. #include <math.h>
  105550. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105551. #ifndef M_PI
  105552. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  105553. #define M_PI 3.14159265358979323846
  105554. #endif
  105555. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L)
  105556. {
  105557. const FLAC__int32 N = L - 1;
  105558. FLAC__int32 n;
  105559. if (L & 1) {
  105560. for (n = 0; n <= N/2; n++)
  105561. window[n] = 2.0f * n / (float)N;
  105562. for (; n <= N; n++)
  105563. window[n] = 2.0f - 2.0f * n / (float)N;
  105564. }
  105565. else {
  105566. for (n = 0; n <= L/2-1; n++)
  105567. window[n] = 2.0f * n / (float)N;
  105568. for (; n <= N; n++)
  105569. window[n] = 2.0f - 2.0f * (N-n) / (float)N;
  105570. }
  105571. }
  105572. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L)
  105573. {
  105574. const FLAC__int32 N = L - 1;
  105575. FLAC__int32 n;
  105576. for (n = 0; n < L; n++)
  105577. 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)));
  105578. }
  105579. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L)
  105580. {
  105581. const FLAC__int32 N = L - 1;
  105582. FLAC__int32 n;
  105583. for (n = 0; n < L; n++)
  105584. window[n] = (FLAC__real)(0.42f - 0.5f * cos(2.0f * M_PI * n / N) + 0.08f * cos(4.0f * M_PI * n / N));
  105585. }
  105586. /* 4-term -92dB side-lobe */
  105587. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L)
  105588. {
  105589. const FLAC__int32 N = L - 1;
  105590. FLAC__int32 n;
  105591. for (n = 0; n <= N; n++)
  105592. 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));
  105593. }
  105594. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L)
  105595. {
  105596. const FLAC__int32 N = L - 1;
  105597. const double N2 = (double)N / 2.;
  105598. FLAC__int32 n;
  105599. for (n = 0; n <= N; n++) {
  105600. double k = ((double)n - N2) / N2;
  105601. k = 1.0f - k * k;
  105602. window[n] = (FLAC__real)(k * k);
  105603. }
  105604. }
  105605. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L)
  105606. {
  105607. const FLAC__int32 N = L - 1;
  105608. FLAC__int32 n;
  105609. for (n = 0; n < L; n++)
  105610. 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));
  105611. }
  105612. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev)
  105613. {
  105614. const FLAC__int32 N = L - 1;
  105615. const double N2 = (double)N / 2.;
  105616. FLAC__int32 n;
  105617. for (n = 0; n <= N; n++) {
  105618. const double k = ((double)n - N2) / (stddev * N2);
  105619. window[n] = (FLAC__real)exp(-0.5f * k * k);
  105620. }
  105621. }
  105622. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L)
  105623. {
  105624. const FLAC__int32 N = L - 1;
  105625. FLAC__int32 n;
  105626. for (n = 0; n < L; n++)
  105627. window[n] = (FLAC__real)(0.54f - 0.46f * cos(2.0f * M_PI * n / N));
  105628. }
  105629. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L)
  105630. {
  105631. const FLAC__int32 N = L - 1;
  105632. FLAC__int32 n;
  105633. for (n = 0; n < L; n++)
  105634. window[n] = (FLAC__real)(0.5f - 0.5f * cos(2.0f * M_PI * n / N));
  105635. }
  105636. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L)
  105637. {
  105638. const FLAC__int32 N = L - 1;
  105639. FLAC__int32 n;
  105640. for (n = 0; n < L; n++)
  105641. 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));
  105642. }
  105643. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L)
  105644. {
  105645. const FLAC__int32 N = L - 1;
  105646. FLAC__int32 n;
  105647. for (n = 0; n < L; n++)
  105648. 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));
  105649. }
  105650. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L)
  105651. {
  105652. FLAC__int32 n;
  105653. for (n = 0; n < L; n++)
  105654. window[n] = 1.0f;
  105655. }
  105656. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L)
  105657. {
  105658. FLAC__int32 n;
  105659. if (L & 1) {
  105660. for (n = 1; n <= L+1/2; n++)
  105661. window[n-1] = 2.0f * n / ((float)L + 1.0f);
  105662. for (; n <= L; n++)
  105663. window[n-1] = - (float)(2 * (L - n + 1)) / ((float)L + 1.0f);
  105664. }
  105665. else {
  105666. for (n = 1; n <= L/2; n++)
  105667. window[n-1] = 2.0f * n / (float)L;
  105668. for (; n <= L; n++)
  105669. window[n-1] = ((float)(2 * (L - n)) + 1.0f) / (float)L;
  105670. }
  105671. }
  105672. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p)
  105673. {
  105674. if (p <= 0.0)
  105675. FLAC__window_rectangle(window, L);
  105676. else if (p >= 1.0)
  105677. FLAC__window_hann(window, L);
  105678. else {
  105679. const FLAC__int32 Np = (FLAC__int32)(p / 2.0f * L) - 1;
  105680. FLAC__int32 n;
  105681. /* start with rectangle... */
  105682. FLAC__window_rectangle(window, L);
  105683. /* ...replace ends with hann */
  105684. if (Np > 0) {
  105685. for (n = 0; n <= Np; n++) {
  105686. window[n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * n / Np));
  105687. window[L-Np-1+n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * (n+Np) / Np));
  105688. }
  105689. }
  105690. }
  105691. }
  105692. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L)
  105693. {
  105694. const FLAC__int32 N = L - 1;
  105695. const double N2 = (double)N / 2.;
  105696. FLAC__int32 n;
  105697. for (n = 0; n <= N; n++) {
  105698. const double k = ((double)n - N2) / N2;
  105699. window[n] = (FLAC__real)(1.0f - k * k);
  105700. }
  105701. }
  105702. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  105703. #endif
  105704. /*** End of inlined file: window_flac.c ***/
  105705. #else
  105706. #include <FLAC/all.h>
  105707. #endif
  105708. }
  105709. #undef max
  105710. #undef min
  105711. BEGIN_JUCE_NAMESPACE
  105712. static const char* const flacFormatName = "FLAC file";
  105713. static const char* const flacExtensions[] = { ".flac", 0 };
  105714. class FlacReader : public AudioFormatReader
  105715. {
  105716. public:
  105717. FlacReader (InputStream* const in)
  105718. : AudioFormatReader (in, TRANS (flacFormatName)),
  105719. reservoir (2, 0),
  105720. reservoirStart (0),
  105721. samplesInReservoir (0),
  105722. scanningForLength (false)
  105723. {
  105724. using namespace FlacNamespace;
  105725. lengthInSamples = 0;
  105726. decoder = FLAC__stream_decoder_new();
  105727. ok = FLAC__stream_decoder_init_stream (decoder,
  105728. readCallback_, seekCallback_, tellCallback_, lengthCallback_,
  105729. eofCallback_, writeCallback_, metadataCallback_, errorCallback_,
  105730. this) == FLAC__STREAM_DECODER_INIT_STATUS_OK;
  105731. if (ok)
  105732. {
  105733. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  105734. if (lengthInSamples == 0 && sampleRate > 0)
  105735. {
  105736. // the length hasn't been stored in the metadata, so we'll need to
  105737. // work it out the length the hard way, by scanning the whole file..
  105738. scanningForLength = true;
  105739. FLAC__stream_decoder_process_until_end_of_stream (decoder);
  105740. scanningForLength = false;
  105741. const int64 tempLength = lengthInSamples;
  105742. FLAC__stream_decoder_reset (decoder);
  105743. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  105744. lengthInSamples = tempLength;
  105745. }
  105746. }
  105747. }
  105748. ~FlacReader()
  105749. {
  105750. FlacNamespace::FLAC__stream_decoder_delete (decoder);
  105751. }
  105752. void useMetadata (const FlacNamespace::FLAC__StreamMetadata_StreamInfo& info)
  105753. {
  105754. sampleRate = info.sample_rate;
  105755. bitsPerSample = info.bits_per_sample;
  105756. lengthInSamples = (unsigned int) info.total_samples;
  105757. numChannels = info.channels;
  105758. reservoir.setSize (numChannels, 2 * info.max_blocksize, false, false, true);
  105759. }
  105760. // returns the number of samples read
  105761. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  105762. int64 startSampleInFile, int numSamples)
  105763. {
  105764. using namespace FlacNamespace;
  105765. if (! ok)
  105766. return false;
  105767. while (numSamples > 0)
  105768. {
  105769. if (startSampleInFile >= reservoirStart
  105770. && startSampleInFile < reservoirStart + samplesInReservoir)
  105771. {
  105772. const int num = (int) jmin ((int64) numSamples,
  105773. reservoirStart + samplesInReservoir - startSampleInFile);
  105774. jassert (num > 0);
  105775. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  105776. if (destSamples[i] != 0)
  105777. memcpy (destSamples[i] + startOffsetInDestBuffer,
  105778. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  105779. sizeof (int) * num);
  105780. startOffsetInDestBuffer += num;
  105781. startSampleInFile += num;
  105782. numSamples -= num;
  105783. }
  105784. else
  105785. {
  105786. if (startSampleInFile >= (int) lengthInSamples)
  105787. {
  105788. samplesInReservoir = 0;
  105789. }
  105790. else if (startSampleInFile < reservoirStart
  105791. || startSampleInFile > reservoirStart + jmax (samplesInReservoir, 511))
  105792. {
  105793. // had some problems with flac crashing if the read pos is aligned more
  105794. // accurately than this. Probably fixed in newer versions of the library, though.
  105795. reservoirStart = (int) (startSampleInFile & ~511);
  105796. samplesInReservoir = 0;
  105797. FLAC__stream_decoder_seek_absolute (decoder, (FLAC__uint64) reservoirStart);
  105798. }
  105799. else
  105800. {
  105801. reservoirStart += samplesInReservoir;
  105802. samplesInReservoir = 0;
  105803. FLAC__stream_decoder_process_single (decoder);
  105804. }
  105805. if (samplesInReservoir == 0)
  105806. break;
  105807. }
  105808. }
  105809. if (numSamples > 0)
  105810. {
  105811. for (int i = numDestChannels; --i >= 0;)
  105812. if (destSamples[i] != 0)
  105813. zeromem (destSamples[i] + startOffsetInDestBuffer,
  105814. sizeof (int) * numSamples);
  105815. }
  105816. return true;
  105817. }
  105818. void useSamples (const FlacNamespace::FLAC__int32* const buffer[], int numSamples)
  105819. {
  105820. if (scanningForLength)
  105821. {
  105822. lengthInSamples += numSamples;
  105823. }
  105824. else
  105825. {
  105826. if (numSamples > reservoir.getNumSamples())
  105827. reservoir.setSize (numChannels, numSamples, false, false, true);
  105828. const int bitsToShift = 32 - bitsPerSample;
  105829. for (int i = 0; i < (int) numChannels; ++i)
  105830. {
  105831. const FlacNamespace::FLAC__int32* src = buffer[i];
  105832. int n = i;
  105833. while (src == 0 && n > 0)
  105834. src = buffer [--n];
  105835. if (src != 0)
  105836. {
  105837. int* dest = (int*) reservoir.getSampleData(i);
  105838. for (int j = 0; j < numSamples; ++j)
  105839. dest[j] = src[j] << bitsToShift;
  105840. }
  105841. }
  105842. samplesInReservoir = numSamples;
  105843. }
  105844. }
  105845. static FlacNamespace::FLAC__StreamDecoderReadStatus readCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__byte buffer[], size_t* bytes, void* client_data)
  105846. {
  105847. using namespace FlacNamespace;
  105848. *bytes = (size_t) static_cast <const FlacReader*> (client_data)->input->read (buffer, (int) *bytes);
  105849. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  105850. }
  105851. static FlacNamespace::FLAC__StreamDecoderSeekStatus seekCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64 absolute_byte_offset, void* client_data)
  105852. {
  105853. using namespace FlacNamespace;
  105854. static_cast <const FlacReader*> (client_data)->input->setPosition ((int) absolute_byte_offset);
  105855. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  105856. }
  105857. static FlacNamespace::FLAC__StreamDecoderTellStatus tellCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  105858. {
  105859. using namespace FlacNamespace;
  105860. *absolute_byte_offset = static_cast <const FlacReader*> (client_data)->input->getPosition();
  105861. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  105862. }
  105863. static FlacNamespace::FLAC__StreamDecoderLengthStatus lengthCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64* stream_length, void* client_data)
  105864. {
  105865. using namespace FlacNamespace;
  105866. *stream_length = static_cast <const FlacReader*> (client_data)->input->getTotalLength();
  105867. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  105868. }
  105869. static FlacNamespace::FLAC__bool eofCallback_ (const FlacNamespace::FLAC__StreamDecoder*, void* client_data)
  105870. {
  105871. return static_cast <const FlacReader*> (client_data)->input->isExhausted();
  105872. }
  105873. static FlacNamespace::FLAC__StreamDecoderWriteStatus writeCallback_ (const FlacNamespace::FLAC__StreamDecoder*,
  105874. const FlacNamespace::FLAC__Frame* frame,
  105875. const FlacNamespace::FLAC__int32* const buffer[],
  105876. void* client_data)
  105877. {
  105878. using namespace FlacNamespace;
  105879. static_cast <FlacReader*> (client_data)->useSamples (buffer, frame->header.blocksize);
  105880. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  105881. }
  105882. static void metadataCallback_ (const FlacNamespace::FLAC__StreamDecoder*,
  105883. const FlacNamespace::FLAC__StreamMetadata* metadata,
  105884. void* client_data)
  105885. {
  105886. static_cast <FlacReader*> (client_data)->useMetadata (metadata->data.stream_info);
  105887. }
  105888. static void errorCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__StreamDecoderErrorStatus, void*)
  105889. {
  105890. }
  105891. juce_UseDebuggingNewOperator
  105892. private:
  105893. FlacNamespace::FLAC__StreamDecoder* decoder;
  105894. AudioSampleBuffer reservoir;
  105895. int reservoirStart, samplesInReservoir;
  105896. bool ok, scanningForLength;
  105897. FlacReader (const FlacReader&);
  105898. FlacReader& operator= (const FlacReader&);
  105899. };
  105900. class FlacWriter : public AudioFormatWriter
  105901. {
  105902. public:
  105903. FlacWriter (OutputStream* const out,
  105904. const double sampleRate_,
  105905. const int numChannels_,
  105906. const int bitsPerSample_)
  105907. : AudioFormatWriter (out, TRANS (flacFormatName),
  105908. sampleRate_,
  105909. numChannels_,
  105910. bitsPerSample_)
  105911. {
  105912. using namespace FlacNamespace;
  105913. encoder = FLAC__stream_encoder_new();
  105914. FLAC__stream_encoder_set_do_mid_side_stereo (encoder, numChannels == 2);
  105915. FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, numChannels == 2);
  105916. FLAC__stream_encoder_set_channels (encoder, numChannels);
  105917. FLAC__stream_encoder_set_bits_per_sample (encoder, jmin ((unsigned int) 24, bitsPerSample));
  105918. FLAC__stream_encoder_set_sample_rate (encoder, (unsigned int) sampleRate);
  105919. FLAC__stream_encoder_set_blocksize (encoder, 2048);
  105920. FLAC__stream_encoder_set_do_escape_coding (encoder, true);
  105921. ok = FLAC__stream_encoder_init_stream (encoder,
  105922. encodeWriteCallback, encodeSeekCallback,
  105923. encodeTellCallback, encodeMetadataCallback,
  105924. this) == FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  105925. }
  105926. ~FlacWriter()
  105927. {
  105928. if (ok)
  105929. {
  105930. FlacNamespace::FLAC__stream_encoder_finish (encoder);
  105931. output->flush();
  105932. }
  105933. else
  105934. {
  105935. output = 0; // to stop the base class deleting this, as it needs to be returned
  105936. // to the caller of createWriter()
  105937. }
  105938. FlacNamespace::FLAC__stream_encoder_delete (encoder);
  105939. }
  105940. bool write (const int** samplesToWrite, int numSamples)
  105941. {
  105942. using namespace FlacNamespace;
  105943. if (! ok)
  105944. return false;
  105945. int* buf[3];
  105946. const int bitsToShift = 32 - bitsPerSample;
  105947. if (bitsToShift > 0)
  105948. {
  105949. const int numChannelsToWrite = (samplesToWrite[1] == 0) ? 1 : 2;
  105950. temp.setSize (sizeof (int) * numSamples * numChannelsToWrite);
  105951. buf[0] = (int*) temp.getData();
  105952. buf[1] = buf[0] + numSamples;
  105953. buf[2] = 0;
  105954. for (int i = numChannelsToWrite; --i >= 0;)
  105955. {
  105956. if (samplesToWrite[i] != 0)
  105957. {
  105958. for (int j = 0; j < numSamples; ++j)
  105959. buf [i][j] = (samplesToWrite [i][j] >> bitsToShift);
  105960. }
  105961. }
  105962. samplesToWrite = (const int**) buf;
  105963. }
  105964. return FLAC__stream_encoder_process (encoder,
  105965. (const FLAC__int32**) samplesToWrite,
  105966. numSamples) != 0;
  105967. }
  105968. bool writeData (const void* const data, const int size) const
  105969. {
  105970. return output->write (data, size);
  105971. }
  105972. static void packUint32 (FlacNamespace::FLAC__uint32 val, FlacNamespace::FLAC__byte* b, const int bytes)
  105973. {
  105974. using namespace FlacNamespace;
  105975. b += bytes;
  105976. for (int i = 0; i < bytes; ++i)
  105977. {
  105978. *(--b) = (FLAC__byte) (val & 0xff);
  105979. val >>= 8;
  105980. }
  105981. }
  105982. void writeMetaData (const FlacNamespace::FLAC__StreamMetadata* metadata)
  105983. {
  105984. using namespace FlacNamespace;
  105985. const FLAC__StreamMetadata_StreamInfo& info = metadata->data.stream_info;
  105986. unsigned char buffer [FLAC__STREAM_METADATA_STREAMINFO_LENGTH];
  105987. const unsigned int channelsMinus1 = info.channels - 1;
  105988. const unsigned int bitsMinus1 = info.bits_per_sample - 1;
  105989. packUint32 (info.min_blocksize, buffer, 2);
  105990. packUint32 (info.max_blocksize, buffer + 2, 2);
  105991. packUint32 (info.min_framesize, buffer + 4, 3);
  105992. packUint32 (info.max_framesize, buffer + 7, 3);
  105993. buffer[10] = (uint8) ((info.sample_rate >> 12) & 0xff);
  105994. buffer[11] = (uint8) ((info.sample_rate >> 4) & 0xff);
  105995. buffer[12] = (uint8) (((info.sample_rate & 0x0f) << 4) | (channelsMinus1 << 1) | (bitsMinus1 >> 4));
  105996. buffer[13] = (FLAC__byte) (((bitsMinus1 & 0x0f) << 4) | (unsigned int) ((info.total_samples >> 32) & 0x0f));
  105997. packUint32 ((FLAC__uint32) info.total_samples, buffer + 14, 4);
  105998. memcpy (buffer + 18, info.md5sum, 16);
  105999. const bool seekOk = output->setPosition (4);
  106000. (void) seekOk;
  106001. // if this fails, you've given it an output stream that can't seek! It needs
  106002. // to be able to seek back to write the header
  106003. jassert (seekOk);
  106004. output->writeIntBigEndian (FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  106005. output->write (buffer, FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  106006. }
  106007. static FlacNamespace::FLAC__StreamEncoderWriteStatus encodeWriteCallback (const FlacNamespace::FLAC__StreamEncoder*,
  106008. const FlacNamespace::FLAC__byte buffer[],
  106009. size_t bytes,
  106010. unsigned int /*samples*/,
  106011. unsigned int /*current_frame*/,
  106012. void* client_data)
  106013. {
  106014. using namespace FlacNamespace;
  106015. return static_cast <FlacWriter*> (client_data)->writeData (buffer, (int) bytes)
  106016. ? FLAC__STREAM_ENCODER_WRITE_STATUS_OK
  106017. : FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  106018. }
  106019. static FlacNamespace::FLAC__StreamEncoderSeekStatus encodeSeekCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64, void*)
  106020. {
  106021. using namespace FlacNamespace;
  106022. return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  106023. }
  106024. static FlacNamespace::FLAC__StreamEncoderTellStatus encodeTellCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  106025. {
  106026. using namespace FlacNamespace;
  106027. if (client_data == 0)
  106028. return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  106029. *absolute_byte_offset = (FLAC__uint64) static_cast <FlacWriter*> (client_data)->output->getPosition();
  106030. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  106031. }
  106032. static void encodeMetadataCallback (const FlacNamespace::FLAC__StreamEncoder*, const FlacNamespace::FLAC__StreamMetadata* metadata, void* client_data)
  106033. {
  106034. static_cast <FlacWriter*> (client_data)->writeMetaData (metadata);
  106035. }
  106036. juce_UseDebuggingNewOperator
  106037. bool ok;
  106038. private:
  106039. FlacNamespace::FLAC__StreamEncoder* encoder;
  106040. MemoryBlock temp;
  106041. FlacWriter (const FlacWriter&);
  106042. FlacWriter& operator= (const FlacWriter&);
  106043. };
  106044. FlacAudioFormat::FlacAudioFormat()
  106045. : AudioFormat (TRANS (flacFormatName), StringArray (flacExtensions))
  106046. {
  106047. }
  106048. FlacAudioFormat::~FlacAudioFormat()
  106049. {
  106050. }
  106051. const Array <int> FlacAudioFormat::getPossibleSampleRates()
  106052. {
  106053. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 0 };
  106054. return Array <int> (rates);
  106055. }
  106056. const Array <int> FlacAudioFormat::getPossibleBitDepths()
  106057. {
  106058. const int depths[] = { 16, 24, 0 };
  106059. return Array <int> (depths);
  106060. }
  106061. bool FlacAudioFormat::canDoStereo()
  106062. {
  106063. return true;
  106064. }
  106065. bool FlacAudioFormat::canDoMono()
  106066. {
  106067. return true;
  106068. }
  106069. bool FlacAudioFormat::isCompressed()
  106070. {
  106071. return true;
  106072. }
  106073. AudioFormatReader* FlacAudioFormat::createReaderFor (InputStream* in,
  106074. const bool deleteStreamIfOpeningFails)
  106075. {
  106076. ScopedPointer<FlacReader> r (new FlacReader (in));
  106077. if (r->sampleRate != 0)
  106078. return r.release();
  106079. if (! deleteStreamIfOpeningFails)
  106080. r->input = 0;
  106081. return 0;
  106082. }
  106083. AudioFormatWriter* FlacAudioFormat::createWriterFor (OutputStream* out,
  106084. double sampleRate,
  106085. unsigned int numberOfChannels,
  106086. int bitsPerSample,
  106087. const StringPairArray& /*metadataValues*/,
  106088. int /*qualityOptionIndex*/)
  106089. {
  106090. if (getPossibleBitDepths().contains (bitsPerSample))
  106091. {
  106092. ScopedPointer<FlacWriter> w (new FlacWriter (out, sampleRate, numberOfChannels, bitsPerSample));
  106093. if (w->ok)
  106094. return w.release();
  106095. }
  106096. return 0;
  106097. }
  106098. END_JUCE_NAMESPACE
  106099. #endif
  106100. /*** End of inlined file: juce_FlacAudioFormat.cpp ***/
  106101. /*** Start of inlined file: juce_OggVorbisAudioFormat.cpp ***/
  106102. #if JUCE_USE_OGGVORBIS
  106103. #if JUCE_MAC
  106104. #define __MACOSX__ 1
  106105. #endif
  106106. namespace OggVorbisNamespace
  106107. {
  106108. #if JUCE_INCLUDE_OGGVORBIS_CODE
  106109. /*** Start of inlined file: vorbisenc.h ***/
  106110. #ifndef _OV_ENC_H_
  106111. #define _OV_ENC_H_
  106112. #ifdef __cplusplus
  106113. extern "C"
  106114. {
  106115. #endif /* __cplusplus */
  106116. /*** Start of inlined file: codec.h ***/
  106117. #ifndef _vorbis_codec_h_
  106118. #define _vorbis_codec_h_
  106119. #ifdef __cplusplus
  106120. extern "C"
  106121. {
  106122. #endif /* __cplusplus */
  106123. /*** Start of inlined file: ogg.h ***/
  106124. #ifndef _OGG_H
  106125. #define _OGG_H
  106126. #ifdef __cplusplus
  106127. extern "C" {
  106128. #endif
  106129. /*** Start of inlined file: os_types.h ***/
  106130. #ifndef _OS_TYPES_H
  106131. #define _OS_TYPES_H
  106132. /* make it easy on the folks that want to compile the libs with a
  106133. different malloc than stdlib */
  106134. #define _ogg_malloc malloc
  106135. #define _ogg_calloc calloc
  106136. #define _ogg_realloc realloc
  106137. #define _ogg_free free
  106138. #if defined(_WIN32)
  106139. # if defined(__CYGWIN__)
  106140. # include <_G_config.h>
  106141. typedef _G_int64_t ogg_int64_t;
  106142. typedef _G_int32_t ogg_int32_t;
  106143. typedef _G_uint32_t ogg_uint32_t;
  106144. typedef _G_int16_t ogg_int16_t;
  106145. typedef _G_uint16_t ogg_uint16_t;
  106146. # elif defined(__MINGW32__)
  106147. typedef short ogg_int16_t;
  106148. typedef unsigned short ogg_uint16_t;
  106149. typedef int ogg_int32_t;
  106150. typedef unsigned int ogg_uint32_t;
  106151. typedef long long ogg_int64_t;
  106152. typedef unsigned long long ogg_uint64_t;
  106153. # elif defined(__MWERKS__)
  106154. typedef long long ogg_int64_t;
  106155. typedef int ogg_int32_t;
  106156. typedef unsigned int ogg_uint32_t;
  106157. typedef short ogg_int16_t;
  106158. typedef unsigned short ogg_uint16_t;
  106159. # else
  106160. /* MSVC/Borland */
  106161. typedef __int64 ogg_int64_t;
  106162. typedef __int32 ogg_int32_t;
  106163. typedef unsigned __int32 ogg_uint32_t;
  106164. typedef __int16 ogg_int16_t;
  106165. typedef unsigned __int16 ogg_uint16_t;
  106166. # endif
  106167. #elif defined(__MACOS__)
  106168. # include <sys/types.h>
  106169. typedef SInt16 ogg_int16_t;
  106170. typedef UInt16 ogg_uint16_t;
  106171. typedef SInt32 ogg_int32_t;
  106172. typedef UInt32 ogg_uint32_t;
  106173. typedef SInt64 ogg_int64_t;
  106174. #elif defined(__MACOSX__) /* MacOS X Framework build */
  106175. # include <sys/types.h>
  106176. typedef int16_t ogg_int16_t;
  106177. typedef u_int16_t ogg_uint16_t;
  106178. typedef int32_t ogg_int32_t;
  106179. typedef u_int32_t ogg_uint32_t;
  106180. typedef int64_t ogg_int64_t;
  106181. #elif defined(__BEOS__)
  106182. /* Be */
  106183. # include <inttypes.h>
  106184. typedef int16_t ogg_int16_t;
  106185. typedef u_int16_t ogg_uint16_t;
  106186. typedef int32_t ogg_int32_t;
  106187. typedef u_int32_t ogg_uint32_t;
  106188. typedef int64_t ogg_int64_t;
  106189. #elif defined (__EMX__)
  106190. /* OS/2 GCC */
  106191. typedef short ogg_int16_t;
  106192. typedef unsigned short ogg_uint16_t;
  106193. typedef int ogg_int32_t;
  106194. typedef unsigned int ogg_uint32_t;
  106195. typedef long long ogg_int64_t;
  106196. #elif defined (DJGPP)
  106197. /* DJGPP */
  106198. typedef short ogg_int16_t;
  106199. typedef int ogg_int32_t;
  106200. typedef unsigned int ogg_uint32_t;
  106201. typedef long long ogg_int64_t;
  106202. #elif defined(R5900)
  106203. /* PS2 EE */
  106204. typedef long ogg_int64_t;
  106205. typedef int ogg_int32_t;
  106206. typedef unsigned ogg_uint32_t;
  106207. typedef short ogg_int16_t;
  106208. #elif defined(__SYMBIAN32__)
  106209. /* Symbian GCC */
  106210. typedef signed short ogg_int16_t;
  106211. typedef unsigned short ogg_uint16_t;
  106212. typedef signed int ogg_int32_t;
  106213. typedef unsigned int ogg_uint32_t;
  106214. typedef long long int ogg_int64_t;
  106215. #else
  106216. # include <sys/types.h>
  106217. /*** Start of inlined file: config_types.h ***/
  106218. #ifndef __CONFIG_TYPES_H__
  106219. #define __CONFIG_TYPES_H__
  106220. typedef int16_t ogg_int16_t;
  106221. typedef unsigned short ogg_uint16_t;
  106222. typedef int32_t ogg_int32_t;
  106223. typedef unsigned int ogg_uint32_t;
  106224. typedef int64_t ogg_int64_t;
  106225. #endif
  106226. /*** End of inlined file: config_types.h ***/
  106227. #endif
  106228. #endif /* _OS_TYPES_H */
  106229. /*** End of inlined file: os_types.h ***/
  106230. typedef struct {
  106231. long endbyte;
  106232. int endbit;
  106233. unsigned char *buffer;
  106234. unsigned char *ptr;
  106235. long storage;
  106236. } oggpack_buffer;
  106237. /* ogg_page is used to encapsulate the data in one Ogg bitstream page *****/
  106238. typedef struct {
  106239. unsigned char *header;
  106240. long header_len;
  106241. unsigned char *body;
  106242. long body_len;
  106243. } ogg_page;
  106244. ogg_uint32_t ogg_bitreverse(ogg_uint32_t x){
  106245. x= ((x>>16)&0x0000ffffUL) | ((x<<16)&0xffff0000UL);
  106246. x= ((x>> 8)&0x00ff00ffUL) | ((x<< 8)&0xff00ff00UL);
  106247. x= ((x>> 4)&0x0f0f0f0fUL) | ((x<< 4)&0xf0f0f0f0UL);
  106248. x= ((x>> 2)&0x33333333UL) | ((x<< 2)&0xccccccccUL);
  106249. return((x>> 1)&0x55555555UL) | ((x<< 1)&0xaaaaaaaaUL);
  106250. }
  106251. /* ogg_stream_state contains the current encode/decode state of a logical
  106252. Ogg bitstream **********************************************************/
  106253. typedef struct {
  106254. unsigned char *body_data; /* bytes from packet bodies */
  106255. long body_storage; /* storage elements allocated */
  106256. long body_fill; /* elements stored; fill mark */
  106257. long body_returned; /* elements of fill returned */
  106258. int *lacing_vals; /* The values that will go to the segment table */
  106259. ogg_int64_t *granule_vals; /* granulepos values for headers. Not compact
  106260. this way, but it is simple coupled to the
  106261. lacing fifo */
  106262. long lacing_storage;
  106263. long lacing_fill;
  106264. long lacing_packet;
  106265. long lacing_returned;
  106266. unsigned char header[282]; /* working space for header encode */
  106267. int header_fill;
  106268. int e_o_s; /* set when we have buffered the last packet in the
  106269. logical bitstream */
  106270. int b_o_s; /* set after we've written the initial page
  106271. of a logical bitstream */
  106272. long serialno;
  106273. long pageno;
  106274. ogg_int64_t packetno; /* sequence number for decode; the framing
  106275. knows where there's a hole in the data,
  106276. but we need coupling so that the codec
  106277. (which is in a seperate abstraction
  106278. layer) also knows about the gap */
  106279. ogg_int64_t granulepos;
  106280. } ogg_stream_state;
  106281. /* ogg_packet is used to encapsulate the data and metadata belonging
  106282. to a single raw Ogg/Vorbis packet *************************************/
  106283. typedef struct {
  106284. unsigned char *packet;
  106285. long bytes;
  106286. long b_o_s;
  106287. long e_o_s;
  106288. ogg_int64_t granulepos;
  106289. ogg_int64_t packetno; /* sequence number for decode; the framing
  106290. knows where there's a hole in the data,
  106291. but we need coupling so that the codec
  106292. (which is in a seperate abstraction
  106293. layer) also knows about the gap */
  106294. } ogg_packet;
  106295. typedef struct {
  106296. unsigned char *data;
  106297. int storage;
  106298. int fill;
  106299. int returned;
  106300. int unsynced;
  106301. int headerbytes;
  106302. int bodybytes;
  106303. } ogg_sync_state;
  106304. /* Ogg BITSTREAM PRIMITIVES: bitstream ************************/
  106305. extern void oggpack_writeinit(oggpack_buffer *b);
  106306. extern void oggpack_writetrunc(oggpack_buffer *b,long bits);
  106307. extern void oggpack_writealign(oggpack_buffer *b);
  106308. extern void oggpack_writecopy(oggpack_buffer *b,void *source,long bits);
  106309. extern void oggpack_reset(oggpack_buffer *b);
  106310. extern void oggpack_writeclear(oggpack_buffer *b);
  106311. extern void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  106312. extern void oggpack_write(oggpack_buffer *b,unsigned long value,int bits);
  106313. extern long oggpack_look(oggpack_buffer *b,int bits);
  106314. extern long oggpack_look1(oggpack_buffer *b);
  106315. extern void oggpack_adv(oggpack_buffer *b,int bits);
  106316. extern void oggpack_adv1(oggpack_buffer *b);
  106317. extern long oggpack_read(oggpack_buffer *b,int bits);
  106318. extern long oggpack_read1(oggpack_buffer *b);
  106319. extern long oggpack_bytes(oggpack_buffer *b);
  106320. extern long oggpack_bits(oggpack_buffer *b);
  106321. extern unsigned char *oggpack_get_buffer(oggpack_buffer *b);
  106322. extern void oggpackB_writeinit(oggpack_buffer *b);
  106323. extern void oggpackB_writetrunc(oggpack_buffer *b,long bits);
  106324. extern void oggpackB_writealign(oggpack_buffer *b);
  106325. extern void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits);
  106326. extern void oggpackB_reset(oggpack_buffer *b);
  106327. extern void oggpackB_writeclear(oggpack_buffer *b);
  106328. extern void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  106329. extern void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits);
  106330. extern long oggpackB_look(oggpack_buffer *b,int bits);
  106331. extern long oggpackB_look1(oggpack_buffer *b);
  106332. extern void oggpackB_adv(oggpack_buffer *b,int bits);
  106333. extern void oggpackB_adv1(oggpack_buffer *b);
  106334. extern long oggpackB_read(oggpack_buffer *b,int bits);
  106335. extern long oggpackB_read1(oggpack_buffer *b);
  106336. extern long oggpackB_bytes(oggpack_buffer *b);
  106337. extern long oggpackB_bits(oggpack_buffer *b);
  106338. extern unsigned char *oggpackB_get_buffer(oggpack_buffer *b);
  106339. /* Ogg BITSTREAM PRIMITIVES: encoding **************************/
  106340. extern int ogg_stream_packetin(ogg_stream_state *os, ogg_packet *op);
  106341. extern int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og);
  106342. extern int ogg_stream_flush(ogg_stream_state *os, ogg_page *og);
  106343. /* Ogg BITSTREAM PRIMITIVES: decoding **************************/
  106344. extern int ogg_sync_init(ogg_sync_state *oy);
  106345. extern int ogg_sync_clear(ogg_sync_state *oy);
  106346. extern int ogg_sync_reset(ogg_sync_state *oy);
  106347. extern int ogg_sync_destroy(ogg_sync_state *oy);
  106348. extern char *ogg_sync_buffer(ogg_sync_state *oy, long size);
  106349. extern int ogg_sync_wrote(ogg_sync_state *oy, long bytes);
  106350. extern long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og);
  106351. extern int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og);
  106352. extern int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og);
  106353. extern int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op);
  106354. extern int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op);
  106355. /* Ogg BITSTREAM PRIMITIVES: general ***************************/
  106356. extern int ogg_stream_init(ogg_stream_state *os,int serialno);
  106357. extern int ogg_stream_clear(ogg_stream_state *os);
  106358. extern int ogg_stream_reset(ogg_stream_state *os);
  106359. extern int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno);
  106360. extern int ogg_stream_destroy(ogg_stream_state *os);
  106361. extern int ogg_stream_eos(ogg_stream_state *os);
  106362. extern void ogg_page_checksum_set(ogg_page *og);
  106363. extern int ogg_page_version(ogg_page *og);
  106364. extern int ogg_page_continued(ogg_page *og);
  106365. extern int ogg_page_bos(ogg_page *og);
  106366. extern int ogg_page_eos(ogg_page *og);
  106367. extern ogg_int64_t ogg_page_granulepos(ogg_page *og);
  106368. extern int ogg_page_serialno(ogg_page *og);
  106369. extern long ogg_page_pageno(ogg_page *og);
  106370. extern int ogg_page_packets(ogg_page *og);
  106371. extern void ogg_packet_clear(ogg_packet *op);
  106372. #ifdef __cplusplus
  106373. }
  106374. #endif
  106375. #endif /* _OGG_H */
  106376. /*** End of inlined file: ogg.h ***/
  106377. typedef struct vorbis_info{
  106378. int version;
  106379. int channels;
  106380. long rate;
  106381. /* The below bitrate declarations are *hints*.
  106382. Combinations of the three values carry the following implications:
  106383. all three set to the same value:
  106384. implies a fixed rate bitstream
  106385. only nominal set:
  106386. implies a VBR stream that averages the nominal bitrate. No hard
  106387. upper/lower limit
  106388. upper and or lower set:
  106389. implies a VBR bitstream that obeys the bitrate limits. nominal
  106390. may also be set to give a nominal rate.
  106391. none set:
  106392. the coder does not care to speculate.
  106393. */
  106394. long bitrate_upper;
  106395. long bitrate_nominal;
  106396. long bitrate_lower;
  106397. long bitrate_window;
  106398. void *codec_setup;
  106399. } vorbis_info;
  106400. /* vorbis_dsp_state buffers the current vorbis audio
  106401. analysis/synthesis state. The DSP state belongs to a specific
  106402. logical bitstream ****************************************************/
  106403. typedef struct vorbis_dsp_state{
  106404. int analysisp;
  106405. vorbis_info *vi;
  106406. float **pcm;
  106407. float **pcmret;
  106408. int pcm_storage;
  106409. int pcm_current;
  106410. int pcm_returned;
  106411. int preextrapolate;
  106412. int eofflag;
  106413. long lW;
  106414. long W;
  106415. long nW;
  106416. long centerW;
  106417. ogg_int64_t granulepos;
  106418. ogg_int64_t sequence;
  106419. ogg_int64_t glue_bits;
  106420. ogg_int64_t time_bits;
  106421. ogg_int64_t floor_bits;
  106422. ogg_int64_t res_bits;
  106423. void *backend_state;
  106424. } vorbis_dsp_state;
  106425. typedef struct vorbis_block{
  106426. /* necessary stream state for linking to the framing abstraction */
  106427. float **pcm; /* this is a pointer into local storage */
  106428. oggpack_buffer opb;
  106429. long lW;
  106430. long W;
  106431. long nW;
  106432. int pcmend;
  106433. int mode;
  106434. int eofflag;
  106435. ogg_int64_t granulepos;
  106436. ogg_int64_t sequence;
  106437. vorbis_dsp_state *vd; /* For read-only access of configuration */
  106438. /* local storage to avoid remallocing; it's up to the mapping to
  106439. structure it */
  106440. void *localstore;
  106441. long localtop;
  106442. long localalloc;
  106443. long totaluse;
  106444. struct alloc_chain *reap;
  106445. /* bitmetrics for the frame */
  106446. long glue_bits;
  106447. long time_bits;
  106448. long floor_bits;
  106449. long res_bits;
  106450. void *internal;
  106451. } vorbis_block;
  106452. /* vorbis_block is a single block of data to be processed as part of
  106453. the analysis/synthesis stream; it belongs to a specific logical
  106454. bitstream, but is independant from other vorbis_blocks belonging to
  106455. that logical bitstream. *************************************************/
  106456. struct alloc_chain{
  106457. void *ptr;
  106458. struct alloc_chain *next;
  106459. };
  106460. /* vorbis_info contains all the setup information specific to the
  106461. specific compression/decompression mode in progress (eg,
  106462. psychoacoustic settings, channel setup, options, codebook
  106463. etc). vorbis_info and substructures are in backends.h.
  106464. *********************************************************************/
  106465. /* the comments are not part of vorbis_info so that vorbis_info can be
  106466. static storage */
  106467. typedef struct vorbis_comment{
  106468. /* unlimited user comment fields. libvorbis writes 'libvorbis'
  106469. whatever vendor is set to in encode */
  106470. char **user_comments;
  106471. int *comment_lengths;
  106472. int comments;
  106473. char *vendor;
  106474. } vorbis_comment;
  106475. /* libvorbis encodes in two abstraction layers; first we perform DSP
  106476. and produce a packet (see docs/analysis.txt). The packet is then
  106477. coded into a framed OggSquish bitstream by the second layer (see
  106478. docs/framing.txt). Decode is the reverse process; we sync/frame
  106479. the bitstream and extract individual packets, then decode the
  106480. packet back into PCM audio.
  106481. The extra framing/packetizing is used in streaming formats, such as
  106482. files. Over the net (such as with UDP), the framing and
  106483. packetization aren't necessary as they're provided by the transport
  106484. and the streaming layer is not used */
  106485. /* Vorbis PRIMITIVES: general ***************************************/
  106486. extern void vorbis_info_init(vorbis_info *vi);
  106487. extern void vorbis_info_clear(vorbis_info *vi);
  106488. extern int vorbis_info_blocksize(vorbis_info *vi,int zo);
  106489. extern void vorbis_comment_init(vorbis_comment *vc);
  106490. extern void vorbis_comment_add(vorbis_comment *vc, char *comment);
  106491. extern void vorbis_comment_add_tag(vorbis_comment *vc,
  106492. const char *tag, char *contents);
  106493. extern char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count);
  106494. extern int vorbis_comment_query_count(vorbis_comment *vc, char *tag);
  106495. extern void vorbis_comment_clear(vorbis_comment *vc);
  106496. extern int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb);
  106497. extern int vorbis_block_clear(vorbis_block *vb);
  106498. extern void vorbis_dsp_clear(vorbis_dsp_state *v);
  106499. extern double vorbis_granule_time(vorbis_dsp_state *v,
  106500. ogg_int64_t granulepos);
  106501. /* Vorbis PRIMITIVES: analysis/DSP layer ****************************/
  106502. extern int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi);
  106503. extern int vorbis_commentheader_out(vorbis_comment *vc, ogg_packet *op);
  106504. extern int vorbis_analysis_headerout(vorbis_dsp_state *v,
  106505. vorbis_comment *vc,
  106506. ogg_packet *op,
  106507. ogg_packet *op_comm,
  106508. ogg_packet *op_code);
  106509. extern float **vorbis_analysis_buffer(vorbis_dsp_state *v,int vals);
  106510. extern int vorbis_analysis_wrote(vorbis_dsp_state *v,int vals);
  106511. extern int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb);
  106512. extern int vorbis_analysis(vorbis_block *vb,ogg_packet *op);
  106513. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  106514. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,
  106515. ogg_packet *op);
  106516. /* Vorbis PRIMITIVES: synthesis layer *******************************/
  106517. extern int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,
  106518. ogg_packet *op);
  106519. extern int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi);
  106520. extern int vorbis_synthesis_restart(vorbis_dsp_state *v);
  106521. extern int vorbis_synthesis(vorbis_block *vb,ogg_packet *op);
  106522. extern int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op);
  106523. extern int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb);
  106524. extern int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm);
  106525. extern int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm);
  106526. extern int vorbis_synthesis_read(vorbis_dsp_state *v,int samples);
  106527. extern long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op);
  106528. extern int vorbis_synthesis_halfrate(vorbis_info *v,int flag);
  106529. extern int vorbis_synthesis_halfrate_p(vorbis_info *v);
  106530. /* Vorbis ERRORS and return codes ***********************************/
  106531. #define OV_FALSE -1
  106532. #define OV_EOF -2
  106533. #define OV_HOLE -3
  106534. #define OV_EREAD -128
  106535. #define OV_EFAULT -129
  106536. #define OV_EIMPL -130
  106537. #define OV_EINVAL -131
  106538. #define OV_ENOTVORBIS -132
  106539. #define OV_EBADHEADER -133
  106540. #define OV_EVERSION -134
  106541. #define OV_ENOTAUDIO -135
  106542. #define OV_EBADPACKET -136
  106543. #define OV_EBADLINK -137
  106544. #define OV_ENOSEEK -138
  106545. #ifdef __cplusplus
  106546. }
  106547. #endif /* __cplusplus */
  106548. #endif
  106549. /*** End of inlined file: codec.h ***/
  106550. extern int vorbis_encode_init(vorbis_info *vi,
  106551. long channels,
  106552. long rate,
  106553. long max_bitrate,
  106554. long nominal_bitrate,
  106555. long min_bitrate);
  106556. extern int vorbis_encode_setup_managed(vorbis_info *vi,
  106557. long channels,
  106558. long rate,
  106559. long max_bitrate,
  106560. long nominal_bitrate,
  106561. long min_bitrate);
  106562. extern int vorbis_encode_setup_vbr(vorbis_info *vi,
  106563. long channels,
  106564. long rate,
  106565. float quality /* quality level from 0. (lo) to 1. (hi) */
  106566. );
  106567. extern int vorbis_encode_init_vbr(vorbis_info *vi,
  106568. long channels,
  106569. long rate,
  106570. float base_quality /* quality level from 0. (lo) to 1. (hi) */
  106571. );
  106572. extern int vorbis_encode_setup_init(vorbis_info *vi);
  106573. extern int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg);
  106574. /* deprecated rate management supported only for compatability */
  106575. #define OV_ECTL_RATEMANAGE_GET 0x10
  106576. #define OV_ECTL_RATEMANAGE_SET 0x11
  106577. #define OV_ECTL_RATEMANAGE_AVG 0x12
  106578. #define OV_ECTL_RATEMANAGE_HARD 0x13
  106579. struct ovectl_ratemanage_arg {
  106580. int management_active;
  106581. long bitrate_hard_min;
  106582. long bitrate_hard_max;
  106583. double bitrate_hard_window;
  106584. long bitrate_av_lo;
  106585. long bitrate_av_hi;
  106586. double bitrate_av_window;
  106587. double bitrate_av_window_center;
  106588. };
  106589. /* new rate setup */
  106590. #define OV_ECTL_RATEMANAGE2_GET 0x14
  106591. #define OV_ECTL_RATEMANAGE2_SET 0x15
  106592. struct ovectl_ratemanage2_arg {
  106593. int management_active;
  106594. long bitrate_limit_min_kbps;
  106595. long bitrate_limit_max_kbps;
  106596. long bitrate_limit_reservoir_bits;
  106597. double bitrate_limit_reservoir_bias;
  106598. long bitrate_average_kbps;
  106599. double bitrate_average_damping;
  106600. };
  106601. #define OV_ECTL_LOWPASS_GET 0x20
  106602. #define OV_ECTL_LOWPASS_SET 0x21
  106603. #define OV_ECTL_IBLOCK_GET 0x30
  106604. #define OV_ECTL_IBLOCK_SET 0x31
  106605. #ifdef __cplusplus
  106606. }
  106607. #endif /* __cplusplus */
  106608. #endif
  106609. /*** End of inlined file: vorbisenc.h ***/
  106610. /*** Start of inlined file: vorbisfile.h ***/
  106611. #ifndef _OV_FILE_H_
  106612. #define _OV_FILE_H_
  106613. #ifdef __cplusplus
  106614. extern "C"
  106615. {
  106616. #endif /* __cplusplus */
  106617. #include <stdio.h>
  106618. /* The function prototypes for the callbacks are basically the same as for
  106619. * the stdio functions fread, fseek, fclose, ftell.
  106620. * The one difference is that the FILE * arguments have been replaced with
  106621. * a void * - this is to be used as a pointer to whatever internal data these
  106622. * functions might need. In the stdio case, it's just a FILE * cast to a void *
  106623. *
  106624. * If you use other functions, check the docs for these functions and return
  106625. * the right values. For seek_func(), you *MUST* return -1 if the stream is
  106626. * unseekable
  106627. */
  106628. typedef struct {
  106629. size_t (*read_func) (void *ptr, size_t size, size_t nmemb, void *datasource);
  106630. int (*seek_func) (void *datasource, ogg_int64_t offset, int whence);
  106631. int (*close_func) (void *datasource);
  106632. long (*tell_func) (void *datasource);
  106633. } ov_callbacks;
  106634. #define NOTOPEN 0
  106635. #define PARTOPEN 1
  106636. #define OPENED 2
  106637. #define STREAMSET 3
  106638. #define INITSET 4
  106639. typedef struct OggVorbis_File {
  106640. void *datasource; /* Pointer to a FILE *, etc. */
  106641. int seekable;
  106642. ogg_int64_t offset;
  106643. ogg_int64_t end;
  106644. ogg_sync_state oy;
  106645. /* If the FILE handle isn't seekable (eg, a pipe), only the current
  106646. stream appears */
  106647. int links;
  106648. ogg_int64_t *offsets;
  106649. ogg_int64_t *dataoffsets;
  106650. long *serialnos;
  106651. ogg_int64_t *pcmlengths; /* overloaded to maintain binary
  106652. compatability; x2 size, stores both
  106653. beginning and end values */
  106654. vorbis_info *vi;
  106655. vorbis_comment *vc;
  106656. /* Decoding working state local storage */
  106657. ogg_int64_t pcm_offset;
  106658. int ready_state;
  106659. long current_serialno;
  106660. int current_link;
  106661. double bittrack;
  106662. double samptrack;
  106663. ogg_stream_state os; /* take physical pages, weld into a logical
  106664. stream of packets */
  106665. vorbis_dsp_state vd; /* central working state for the packet->PCM decoder */
  106666. vorbis_block vb; /* local working space for packet->PCM decode */
  106667. ov_callbacks callbacks;
  106668. } OggVorbis_File;
  106669. extern int ov_clear(OggVorbis_File *vf);
  106670. extern int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  106671. extern int ov_open_callbacks(void *datasource, OggVorbis_File *vf,
  106672. char *initial, long ibytes, ov_callbacks callbacks);
  106673. extern int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  106674. extern int ov_test_callbacks(void *datasource, OggVorbis_File *vf,
  106675. char *initial, long ibytes, ov_callbacks callbacks);
  106676. extern int ov_test_open(OggVorbis_File *vf);
  106677. extern long ov_bitrate(OggVorbis_File *vf,int i);
  106678. extern long ov_bitrate_instant(OggVorbis_File *vf);
  106679. extern long ov_streams(OggVorbis_File *vf);
  106680. extern long ov_seekable(OggVorbis_File *vf);
  106681. extern long ov_serialnumber(OggVorbis_File *vf,int i);
  106682. extern ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i);
  106683. extern ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i);
  106684. extern double ov_time_total(OggVorbis_File *vf,int i);
  106685. extern int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos);
  106686. extern int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos);
  106687. extern int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos);
  106688. extern int ov_time_seek(OggVorbis_File *vf,double pos);
  106689. extern int ov_time_seek_page(OggVorbis_File *vf,double pos);
  106690. extern int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  106691. extern int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  106692. extern int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos);
  106693. extern int ov_time_seek_lap(OggVorbis_File *vf,double pos);
  106694. extern int ov_time_seek_page_lap(OggVorbis_File *vf,double pos);
  106695. extern ogg_int64_t ov_raw_tell(OggVorbis_File *vf);
  106696. extern ogg_int64_t ov_pcm_tell(OggVorbis_File *vf);
  106697. extern double ov_time_tell(OggVorbis_File *vf);
  106698. extern vorbis_info *ov_info(OggVorbis_File *vf,int link);
  106699. extern vorbis_comment *ov_comment(OggVorbis_File *vf,int link);
  106700. extern long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int samples,
  106701. int *bitstream);
  106702. extern long ov_read(OggVorbis_File *vf,char *buffer,int length,
  106703. int bigendianp,int word,int sgned,int *bitstream);
  106704. extern int ov_crosslap(OggVorbis_File *vf1,OggVorbis_File *vf2);
  106705. extern int ov_halfrate(OggVorbis_File *vf,int flag);
  106706. extern int ov_halfrate_p(OggVorbis_File *vf);
  106707. #ifdef __cplusplus
  106708. }
  106709. #endif /* __cplusplus */
  106710. #endif
  106711. /*** End of inlined file: vorbisfile.h ***/
  106712. /*** Start of inlined file: bitwise.c ***/
  106713. /* We're 'LSb' endian; if we write a word but read individual bits,
  106714. then we'll read the lsb first */
  106715. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  106716. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  106717. // tasks..
  106718. #if JUCE_MSVC
  106719. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  106720. #endif
  106721. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  106722. #if JUCE_USE_OGGVORBIS
  106723. #include <string.h>
  106724. #include <stdlib.h>
  106725. #define BUFFER_INCREMENT 256
  106726. static const unsigned long mask[]=
  106727. {0x00000000,0x00000001,0x00000003,0x00000007,0x0000000f,
  106728. 0x0000001f,0x0000003f,0x0000007f,0x000000ff,0x000001ff,
  106729. 0x000003ff,0x000007ff,0x00000fff,0x00001fff,0x00003fff,
  106730. 0x00007fff,0x0000ffff,0x0001ffff,0x0003ffff,0x0007ffff,
  106731. 0x000fffff,0x001fffff,0x003fffff,0x007fffff,0x00ffffff,
  106732. 0x01ffffff,0x03ffffff,0x07ffffff,0x0fffffff,0x1fffffff,
  106733. 0x3fffffff,0x7fffffff,0xffffffff };
  106734. static const unsigned int mask8B[]=
  106735. {0x00,0x80,0xc0,0xe0,0xf0,0xf8,0xfc,0xfe,0xff};
  106736. void oggpack_writeinit(oggpack_buffer *b){
  106737. memset(b,0,sizeof(*b));
  106738. b->ptr=b->buffer=(unsigned char*) _ogg_malloc(BUFFER_INCREMENT);
  106739. b->buffer[0]='\0';
  106740. b->storage=BUFFER_INCREMENT;
  106741. }
  106742. void oggpackB_writeinit(oggpack_buffer *b){
  106743. oggpack_writeinit(b);
  106744. }
  106745. void oggpack_writetrunc(oggpack_buffer *b,long bits){
  106746. long bytes=bits>>3;
  106747. bits-=bytes*8;
  106748. b->ptr=b->buffer+bytes;
  106749. b->endbit=bits;
  106750. b->endbyte=bytes;
  106751. *b->ptr&=mask[bits];
  106752. }
  106753. void oggpackB_writetrunc(oggpack_buffer *b,long bits){
  106754. long bytes=bits>>3;
  106755. bits-=bytes*8;
  106756. b->ptr=b->buffer+bytes;
  106757. b->endbit=bits;
  106758. b->endbyte=bytes;
  106759. *b->ptr&=mask8B[bits];
  106760. }
  106761. /* Takes only up to 32 bits. */
  106762. void oggpack_write(oggpack_buffer *b,unsigned long value,int bits){
  106763. if(b->endbyte+4>=b->storage){
  106764. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  106765. b->storage+=BUFFER_INCREMENT;
  106766. b->ptr=b->buffer+b->endbyte;
  106767. }
  106768. value&=mask[bits];
  106769. bits+=b->endbit;
  106770. b->ptr[0]|=value<<b->endbit;
  106771. if(bits>=8){
  106772. b->ptr[1]=(unsigned char)(value>>(8-b->endbit));
  106773. if(bits>=16){
  106774. b->ptr[2]=(unsigned char)(value>>(16-b->endbit));
  106775. if(bits>=24){
  106776. b->ptr[3]=(unsigned char)(value>>(24-b->endbit));
  106777. if(bits>=32){
  106778. if(b->endbit)
  106779. b->ptr[4]=(unsigned char)(value>>(32-b->endbit));
  106780. else
  106781. b->ptr[4]=0;
  106782. }
  106783. }
  106784. }
  106785. }
  106786. b->endbyte+=bits/8;
  106787. b->ptr+=bits/8;
  106788. b->endbit=bits&7;
  106789. }
  106790. /* Takes only up to 32 bits. */
  106791. void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits){
  106792. if(b->endbyte+4>=b->storage){
  106793. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  106794. b->storage+=BUFFER_INCREMENT;
  106795. b->ptr=b->buffer+b->endbyte;
  106796. }
  106797. value=(value&mask[bits])<<(32-bits);
  106798. bits+=b->endbit;
  106799. b->ptr[0]|=value>>(24+b->endbit);
  106800. if(bits>=8){
  106801. b->ptr[1]=(unsigned char)(value>>(16+b->endbit));
  106802. if(bits>=16){
  106803. b->ptr[2]=(unsigned char)(value>>(8+b->endbit));
  106804. if(bits>=24){
  106805. b->ptr[3]=(unsigned char)(value>>(b->endbit));
  106806. if(bits>=32){
  106807. if(b->endbit)
  106808. b->ptr[4]=(unsigned char)(value<<(8-b->endbit));
  106809. else
  106810. b->ptr[4]=0;
  106811. }
  106812. }
  106813. }
  106814. }
  106815. b->endbyte+=bits/8;
  106816. b->ptr+=bits/8;
  106817. b->endbit=bits&7;
  106818. }
  106819. void oggpack_writealign(oggpack_buffer *b){
  106820. int bits=8-b->endbit;
  106821. if(bits<8)
  106822. oggpack_write(b,0,bits);
  106823. }
  106824. void oggpackB_writealign(oggpack_buffer *b){
  106825. int bits=8-b->endbit;
  106826. if(bits<8)
  106827. oggpackB_write(b,0,bits);
  106828. }
  106829. static void oggpack_writecopy_helper(oggpack_buffer *b,
  106830. void *source,
  106831. long bits,
  106832. void (*w)(oggpack_buffer *,
  106833. unsigned long,
  106834. int),
  106835. int msb){
  106836. unsigned char *ptr=(unsigned char *)source;
  106837. long bytes=bits/8;
  106838. bits-=bytes*8;
  106839. if(b->endbit){
  106840. int i;
  106841. /* unaligned copy. Do it the hard way. */
  106842. for(i=0;i<bytes;i++)
  106843. w(b,(unsigned long)(ptr[i]),8);
  106844. }else{
  106845. /* aligned block copy */
  106846. if(b->endbyte+bytes+1>=b->storage){
  106847. b->storage=b->endbyte+bytes+BUFFER_INCREMENT;
  106848. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage);
  106849. b->ptr=b->buffer+b->endbyte;
  106850. }
  106851. memmove(b->ptr,source,bytes);
  106852. b->ptr+=bytes;
  106853. b->endbyte+=bytes;
  106854. *b->ptr=0;
  106855. }
  106856. if(bits){
  106857. if(msb)
  106858. w(b,(unsigned long)(ptr[bytes]>>(8-bits)),bits);
  106859. else
  106860. w(b,(unsigned long)(ptr[bytes]),bits);
  106861. }
  106862. }
  106863. void oggpack_writecopy(oggpack_buffer *b,void *source,long bits){
  106864. oggpack_writecopy_helper(b,source,bits,oggpack_write,0);
  106865. }
  106866. void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits){
  106867. oggpack_writecopy_helper(b,source,bits,oggpackB_write,1);
  106868. }
  106869. void oggpack_reset(oggpack_buffer *b){
  106870. b->ptr=b->buffer;
  106871. b->buffer[0]=0;
  106872. b->endbit=b->endbyte=0;
  106873. }
  106874. void oggpackB_reset(oggpack_buffer *b){
  106875. oggpack_reset(b);
  106876. }
  106877. void oggpack_writeclear(oggpack_buffer *b){
  106878. _ogg_free(b->buffer);
  106879. memset(b,0,sizeof(*b));
  106880. }
  106881. void oggpackB_writeclear(oggpack_buffer *b){
  106882. oggpack_writeclear(b);
  106883. }
  106884. void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  106885. memset(b,0,sizeof(*b));
  106886. b->buffer=b->ptr=buf;
  106887. b->storage=bytes;
  106888. }
  106889. void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  106890. oggpack_readinit(b,buf,bytes);
  106891. }
  106892. /* Read in bits without advancing the bitptr; bits <= 32 */
  106893. long oggpack_look(oggpack_buffer *b,int bits){
  106894. unsigned long ret;
  106895. unsigned long m=mask[bits];
  106896. bits+=b->endbit;
  106897. if(b->endbyte+4>=b->storage){
  106898. /* not the main path */
  106899. if(b->endbyte*8+bits>b->storage*8)return(-1);
  106900. }
  106901. ret=b->ptr[0]>>b->endbit;
  106902. if(bits>8){
  106903. ret|=b->ptr[1]<<(8-b->endbit);
  106904. if(bits>16){
  106905. ret|=b->ptr[2]<<(16-b->endbit);
  106906. if(bits>24){
  106907. ret|=b->ptr[3]<<(24-b->endbit);
  106908. if(bits>32 && b->endbit)
  106909. ret|=b->ptr[4]<<(32-b->endbit);
  106910. }
  106911. }
  106912. }
  106913. return(m&ret);
  106914. }
  106915. /* Read in bits without advancing the bitptr; bits <= 32 */
  106916. long oggpackB_look(oggpack_buffer *b,int bits){
  106917. unsigned long ret;
  106918. int m=32-bits;
  106919. bits+=b->endbit;
  106920. if(b->endbyte+4>=b->storage){
  106921. /* not the main path */
  106922. if(b->endbyte*8+bits>b->storage*8)return(-1);
  106923. }
  106924. ret=b->ptr[0]<<(24+b->endbit);
  106925. if(bits>8){
  106926. ret|=b->ptr[1]<<(16+b->endbit);
  106927. if(bits>16){
  106928. ret|=b->ptr[2]<<(8+b->endbit);
  106929. if(bits>24){
  106930. ret|=b->ptr[3]<<(b->endbit);
  106931. if(bits>32 && b->endbit)
  106932. ret|=b->ptr[4]>>(8-b->endbit);
  106933. }
  106934. }
  106935. }
  106936. return ((ret&0xffffffff)>>(m>>1))>>((m+1)>>1);
  106937. }
  106938. long oggpack_look1(oggpack_buffer *b){
  106939. if(b->endbyte>=b->storage)return(-1);
  106940. return((b->ptr[0]>>b->endbit)&1);
  106941. }
  106942. long oggpackB_look1(oggpack_buffer *b){
  106943. if(b->endbyte>=b->storage)return(-1);
  106944. return((b->ptr[0]>>(7-b->endbit))&1);
  106945. }
  106946. void oggpack_adv(oggpack_buffer *b,int bits){
  106947. bits+=b->endbit;
  106948. b->ptr+=bits/8;
  106949. b->endbyte+=bits/8;
  106950. b->endbit=bits&7;
  106951. }
  106952. void oggpackB_adv(oggpack_buffer *b,int bits){
  106953. oggpack_adv(b,bits);
  106954. }
  106955. void oggpack_adv1(oggpack_buffer *b){
  106956. if(++(b->endbit)>7){
  106957. b->endbit=0;
  106958. b->ptr++;
  106959. b->endbyte++;
  106960. }
  106961. }
  106962. void oggpackB_adv1(oggpack_buffer *b){
  106963. oggpack_adv1(b);
  106964. }
  106965. /* bits <= 32 */
  106966. long oggpack_read(oggpack_buffer *b,int bits){
  106967. long ret;
  106968. unsigned long m=mask[bits];
  106969. bits+=b->endbit;
  106970. if(b->endbyte+4>=b->storage){
  106971. /* not the main path */
  106972. ret=-1L;
  106973. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  106974. }
  106975. ret=b->ptr[0]>>b->endbit;
  106976. if(bits>8){
  106977. ret|=b->ptr[1]<<(8-b->endbit);
  106978. if(bits>16){
  106979. ret|=b->ptr[2]<<(16-b->endbit);
  106980. if(bits>24){
  106981. ret|=b->ptr[3]<<(24-b->endbit);
  106982. if(bits>32 && b->endbit){
  106983. ret|=b->ptr[4]<<(32-b->endbit);
  106984. }
  106985. }
  106986. }
  106987. }
  106988. ret&=m;
  106989. overflow:
  106990. b->ptr+=bits/8;
  106991. b->endbyte+=bits/8;
  106992. b->endbit=bits&7;
  106993. return(ret);
  106994. }
  106995. /* bits <= 32 */
  106996. long oggpackB_read(oggpack_buffer *b,int bits){
  106997. long ret;
  106998. long m=32-bits;
  106999. bits+=b->endbit;
  107000. if(b->endbyte+4>=b->storage){
  107001. /* not the main path */
  107002. ret=-1L;
  107003. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  107004. }
  107005. ret=b->ptr[0]<<(24+b->endbit);
  107006. if(bits>8){
  107007. ret|=b->ptr[1]<<(16+b->endbit);
  107008. if(bits>16){
  107009. ret|=b->ptr[2]<<(8+b->endbit);
  107010. if(bits>24){
  107011. ret|=b->ptr[3]<<(b->endbit);
  107012. if(bits>32 && b->endbit)
  107013. ret|=b->ptr[4]>>(8-b->endbit);
  107014. }
  107015. }
  107016. }
  107017. ret=((ret&0xffffffffUL)>>(m>>1))>>((m+1)>>1);
  107018. overflow:
  107019. b->ptr+=bits/8;
  107020. b->endbyte+=bits/8;
  107021. b->endbit=bits&7;
  107022. return(ret);
  107023. }
  107024. long oggpack_read1(oggpack_buffer *b){
  107025. long ret;
  107026. if(b->endbyte>=b->storage){
  107027. /* not the main path */
  107028. ret=-1L;
  107029. goto overflow;
  107030. }
  107031. ret=(b->ptr[0]>>b->endbit)&1;
  107032. overflow:
  107033. b->endbit++;
  107034. if(b->endbit>7){
  107035. b->endbit=0;
  107036. b->ptr++;
  107037. b->endbyte++;
  107038. }
  107039. return(ret);
  107040. }
  107041. long oggpackB_read1(oggpack_buffer *b){
  107042. long ret;
  107043. if(b->endbyte>=b->storage){
  107044. /* not the main path */
  107045. ret=-1L;
  107046. goto overflow;
  107047. }
  107048. ret=(b->ptr[0]>>(7-b->endbit))&1;
  107049. overflow:
  107050. b->endbit++;
  107051. if(b->endbit>7){
  107052. b->endbit=0;
  107053. b->ptr++;
  107054. b->endbyte++;
  107055. }
  107056. return(ret);
  107057. }
  107058. long oggpack_bytes(oggpack_buffer *b){
  107059. return(b->endbyte+(b->endbit+7)/8);
  107060. }
  107061. long oggpack_bits(oggpack_buffer *b){
  107062. return(b->endbyte*8+b->endbit);
  107063. }
  107064. long oggpackB_bytes(oggpack_buffer *b){
  107065. return oggpack_bytes(b);
  107066. }
  107067. long oggpackB_bits(oggpack_buffer *b){
  107068. return oggpack_bits(b);
  107069. }
  107070. unsigned char *oggpack_get_buffer(oggpack_buffer *b){
  107071. return(b->buffer);
  107072. }
  107073. unsigned char *oggpackB_get_buffer(oggpack_buffer *b){
  107074. return oggpack_get_buffer(b);
  107075. }
  107076. /* Self test of the bitwise routines; everything else is based on
  107077. them, so they damned well better be solid. */
  107078. #ifdef _V_SELFTEST
  107079. #include <stdio.h>
  107080. static int ilog(unsigned int v){
  107081. int ret=0;
  107082. while(v){
  107083. ret++;
  107084. v>>=1;
  107085. }
  107086. return(ret);
  107087. }
  107088. oggpack_buffer o;
  107089. oggpack_buffer r;
  107090. void report(char *in){
  107091. fprintf(stderr,"%s",in);
  107092. exit(1);
  107093. }
  107094. void cliptest(unsigned long *b,int vals,int bits,int *comp,int compsize){
  107095. long bytes,i;
  107096. unsigned char *buffer;
  107097. oggpack_reset(&o);
  107098. for(i=0;i<vals;i++)
  107099. oggpack_write(&o,b[i],bits?bits:ilog(b[i]));
  107100. buffer=oggpack_get_buffer(&o);
  107101. bytes=oggpack_bytes(&o);
  107102. if(bytes!=compsize)report("wrong number of bytes!\n");
  107103. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  107104. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  107105. report("wrote incorrect value!\n");
  107106. }
  107107. oggpack_readinit(&r,buffer,bytes);
  107108. for(i=0;i<vals;i++){
  107109. int tbit=bits?bits:ilog(b[i]);
  107110. if(oggpack_look(&r,tbit)==-1)
  107111. report("out of data!\n");
  107112. if(oggpack_look(&r,tbit)!=(b[i]&mask[tbit]))
  107113. report("looked at incorrect value!\n");
  107114. if(tbit==1)
  107115. if(oggpack_look1(&r)!=(b[i]&mask[tbit]))
  107116. report("looked at single bit incorrect value!\n");
  107117. if(tbit==1){
  107118. if(oggpack_read1(&r)!=(b[i]&mask[tbit]))
  107119. report("read incorrect single bit value!\n");
  107120. }else{
  107121. if(oggpack_read(&r,tbit)!=(b[i]&mask[tbit]))
  107122. report("read incorrect value!\n");
  107123. }
  107124. }
  107125. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  107126. }
  107127. void cliptestB(unsigned long *b,int vals,int bits,int *comp,int compsize){
  107128. long bytes,i;
  107129. unsigned char *buffer;
  107130. oggpackB_reset(&o);
  107131. for(i=0;i<vals;i++)
  107132. oggpackB_write(&o,b[i],bits?bits:ilog(b[i]));
  107133. buffer=oggpackB_get_buffer(&o);
  107134. bytes=oggpackB_bytes(&o);
  107135. if(bytes!=compsize)report("wrong number of bytes!\n");
  107136. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  107137. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  107138. report("wrote incorrect value!\n");
  107139. }
  107140. oggpackB_readinit(&r,buffer,bytes);
  107141. for(i=0;i<vals;i++){
  107142. int tbit=bits?bits:ilog(b[i]);
  107143. if(oggpackB_look(&r,tbit)==-1)
  107144. report("out of data!\n");
  107145. if(oggpackB_look(&r,tbit)!=(b[i]&mask[tbit]))
  107146. report("looked at incorrect value!\n");
  107147. if(tbit==1)
  107148. if(oggpackB_look1(&r)!=(b[i]&mask[tbit]))
  107149. report("looked at single bit incorrect value!\n");
  107150. if(tbit==1){
  107151. if(oggpackB_read1(&r)!=(b[i]&mask[tbit]))
  107152. report("read incorrect single bit value!\n");
  107153. }else{
  107154. if(oggpackB_read(&r,tbit)!=(b[i]&mask[tbit]))
  107155. report("read incorrect value!\n");
  107156. }
  107157. }
  107158. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  107159. }
  107160. int main(void){
  107161. unsigned char *buffer;
  107162. long bytes,i;
  107163. static unsigned long testbuffer1[]=
  107164. {18,12,103948,4325,543,76,432,52,3,65,4,56,32,42,34,21,1,23,32,546,456,7,
  107165. 567,56,8,8,55,3,52,342,341,4,265,7,67,86,2199,21,7,1,5,1,4};
  107166. int test1size=43;
  107167. static unsigned long testbuffer2[]=
  107168. {216531625L,1237861823,56732452,131,3212421,12325343,34547562,12313212,
  107169. 1233432,534,5,346435231,14436467,7869299,76326614,167548585,
  107170. 85525151,0,12321,1,349528352};
  107171. int test2size=21;
  107172. static unsigned long testbuffer3[]=
  107173. {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,
  107174. 0,1,30,1,1,1,0,0,1,0,0,0,12,0,11,0,1,0,0,1};
  107175. int test3size=56;
  107176. static unsigned long large[]=
  107177. {2136531625L,2137861823,56732452,131,3212421,12325343,34547562,12313212,
  107178. 1233432,534,5,2146435231,14436467,7869299,76326614,167548585,
  107179. 85525151,0,12321,1,2146528352};
  107180. int onesize=33;
  107181. static int one[33]={146,25,44,151,195,15,153,176,233,131,196,65,85,172,47,40,
  107182. 34,242,223,136,35,222,211,86,171,50,225,135,214,75,172,
  107183. 223,4};
  107184. static int oneB[33]={150,101,131,33,203,15,204,216,105,193,156,65,84,85,222,
  107185. 8,139,145,227,126,34,55,244,171,85,100,39,195,173,18,
  107186. 245,251,128};
  107187. int twosize=6;
  107188. static int two[6]={61,255,255,251,231,29};
  107189. static int twoB[6]={247,63,255,253,249,120};
  107190. int threesize=54;
  107191. static int three[54]={169,2,232,252,91,132,156,36,89,13,123,176,144,32,254,
  107192. 142,224,85,59,121,144,79,124,23,67,90,90,216,79,23,83,
  107193. 58,135,196,61,55,129,183,54,101,100,170,37,127,126,10,
  107194. 100,52,4,14,18,86,77,1};
  107195. static int threeB[54]={206,128,42,153,57,8,183,251,13,89,36,30,32,144,183,
  107196. 130,59,240,121,59,85,223,19,228,180,134,33,107,74,98,
  107197. 233,253,196,135,63,2,110,114,50,155,90,127,37,170,104,
  107198. 200,20,254,4,58,106,176,144,0};
  107199. int foursize=38;
  107200. static int four[38]={18,6,163,252,97,194,104,131,32,1,7,82,137,42,129,11,72,
  107201. 132,60,220,112,8,196,109,64,179,86,9,137,195,208,122,169,
  107202. 28,2,133,0,1};
  107203. static int fourB[38]={36,48,102,83,243,24,52,7,4,35,132,10,145,21,2,93,2,41,
  107204. 1,219,184,16,33,184,54,149,170,132,18,30,29,98,229,67,
  107205. 129,10,4,32};
  107206. int fivesize=45;
  107207. static int five[45]={169,2,126,139,144,172,30,4,80,72,240,59,130,218,73,62,
  107208. 241,24,210,44,4,20,0,248,116,49,135,100,110,130,181,169,
  107209. 84,75,159,2,1,0,132,192,8,0,0,18,22};
  107210. static int fiveB[45]={1,84,145,111,245,100,128,8,56,36,40,71,126,78,213,226,
  107211. 124,105,12,0,133,128,0,162,233,242,67,152,77,205,77,
  107212. 172,150,169,129,79,128,0,6,4,32,0,27,9,0};
  107213. int sixsize=7;
  107214. static int six[7]={17,177,170,242,169,19,148};
  107215. static int sixB[7]={136,141,85,79,149,200,41};
  107216. /* Test read/write together */
  107217. /* Later we test against pregenerated bitstreams */
  107218. oggpack_writeinit(&o);
  107219. fprintf(stderr,"\nSmall preclipped packing (LSb): ");
  107220. cliptest(testbuffer1,test1size,0,one,onesize);
  107221. fprintf(stderr,"ok.");
  107222. fprintf(stderr,"\nNull bit call (LSb): ");
  107223. cliptest(testbuffer3,test3size,0,two,twosize);
  107224. fprintf(stderr,"ok.");
  107225. fprintf(stderr,"\nLarge preclipped packing (LSb): ");
  107226. cliptest(testbuffer2,test2size,0,three,threesize);
  107227. fprintf(stderr,"ok.");
  107228. fprintf(stderr,"\n32 bit preclipped packing (LSb): ");
  107229. oggpack_reset(&o);
  107230. for(i=0;i<test2size;i++)
  107231. oggpack_write(&o,large[i],32);
  107232. buffer=oggpack_get_buffer(&o);
  107233. bytes=oggpack_bytes(&o);
  107234. oggpack_readinit(&r,buffer,bytes);
  107235. for(i=0;i<test2size;i++){
  107236. if(oggpack_look(&r,32)==-1)report("out of data. failed!");
  107237. if(oggpack_look(&r,32)!=large[i]){
  107238. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpack_look(&r,32),large[i],
  107239. oggpack_look(&r,32),large[i]);
  107240. report("read incorrect value!\n");
  107241. }
  107242. oggpack_adv(&r,32);
  107243. }
  107244. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  107245. fprintf(stderr,"ok.");
  107246. fprintf(stderr,"\nSmall unclipped packing (LSb): ");
  107247. cliptest(testbuffer1,test1size,7,four,foursize);
  107248. fprintf(stderr,"ok.");
  107249. fprintf(stderr,"\nLarge unclipped packing (LSb): ");
  107250. cliptest(testbuffer2,test2size,17,five,fivesize);
  107251. fprintf(stderr,"ok.");
  107252. fprintf(stderr,"\nSingle bit unclipped packing (LSb): ");
  107253. cliptest(testbuffer3,test3size,1,six,sixsize);
  107254. fprintf(stderr,"ok.");
  107255. fprintf(stderr,"\nTesting read past end (LSb): ");
  107256. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  107257. for(i=0;i<64;i++){
  107258. if(oggpack_read(&r,1)!=0){
  107259. fprintf(stderr,"failed; got -1 prematurely.\n");
  107260. exit(1);
  107261. }
  107262. }
  107263. if(oggpack_look(&r,1)!=-1 ||
  107264. oggpack_read(&r,1)!=-1){
  107265. fprintf(stderr,"failed; read past end without -1.\n");
  107266. exit(1);
  107267. }
  107268. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  107269. if(oggpack_read(&r,30)!=0 || oggpack_read(&r,16)!=0){
  107270. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  107271. exit(1);
  107272. }
  107273. if(oggpack_look(&r,18)!=0 ||
  107274. oggpack_look(&r,18)!=0){
  107275. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  107276. exit(1);
  107277. }
  107278. if(oggpack_look(&r,19)!=-1 ||
  107279. oggpack_look(&r,19)!=-1){
  107280. fprintf(stderr,"failed; read past end without -1.\n");
  107281. exit(1);
  107282. }
  107283. if(oggpack_look(&r,32)!=-1 ||
  107284. oggpack_look(&r,32)!=-1){
  107285. fprintf(stderr,"failed; read past end without -1.\n");
  107286. exit(1);
  107287. }
  107288. oggpack_writeclear(&o);
  107289. fprintf(stderr,"ok.\n");
  107290. /********** lazy, cut-n-paste retest with MSb packing ***********/
  107291. /* Test read/write together */
  107292. /* Later we test against pregenerated bitstreams */
  107293. oggpackB_writeinit(&o);
  107294. fprintf(stderr,"\nSmall preclipped packing (MSb): ");
  107295. cliptestB(testbuffer1,test1size,0,oneB,onesize);
  107296. fprintf(stderr,"ok.");
  107297. fprintf(stderr,"\nNull bit call (MSb): ");
  107298. cliptestB(testbuffer3,test3size,0,twoB,twosize);
  107299. fprintf(stderr,"ok.");
  107300. fprintf(stderr,"\nLarge preclipped packing (MSb): ");
  107301. cliptestB(testbuffer2,test2size,0,threeB,threesize);
  107302. fprintf(stderr,"ok.");
  107303. fprintf(stderr,"\n32 bit preclipped packing (MSb): ");
  107304. oggpackB_reset(&o);
  107305. for(i=0;i<test2size;i++)
  107306. oggpackB_write(&o,large[i],32);
  107307. buffer=oggpackB_get_buffer(&o);
  107308. bytes=oggpackB_bytes(&o);
  107309. oggpackB_readinit(&r,buffer,bytes);
  107310. for(i=0;i<test2size;i++){
  107311. if(oggpackB_look(&r,32)==-1)report("out of data. failed!");
  107312. if(oggpackB_look(&r,32)!=large[i]){
  107313. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpackB_look(&r,32),large[i],
  107314. oggpackB_look(&r,32),large[i]);
  107315. report("read incorrect value!\n");
  107316. }
  107317. oggpackB_adv(&r,32);
  107318. }
  107319. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  107320. fprintf(stderr,"ok.");
  107321. fprintf(stderr,"\nSmall unclipped packing (MSb): ");
  107322. cliptestB(testbuffer1,test1size,7,fourB,foursize);
  107323. fprintf(stderr,"ok.");
  107324. fprintf(stderr,"\nLarge unclipped packing (MSb): ");
  107325. cliptestB(testbuffer2,test2size,17,fiveB,fivesize);
  107326. fprintf(stderr,"ok.");
  107327. fprintf(stderr,"\nSingle bit unclipped packing (MSb): ");
  107328. cliptestB(testbuffer3,test3size,1,sixB,sixsize);
  107329. fprintf(stderr,"ok.");
  107330. fprintf(stderr,"\nTesting read past end (MSb): ");
  107331. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  107332. for(i=0;i<64;i++){
  107333. if(oggpackB_read(&r,1)!=0){
  107334. fprintf(stderr,"failed; got -1 prematurely.\n");
  107335. exit(1);
  107336. }
  107337. }
  107338. if(oggpackB_look(&r,1)!=-1 ||
  107339. oggpackB_read(&r,1)!=-1){
  107340. fprintf(stderr,"failed; read past end without -1.\n");
  107341. exit(1);
  107342. }
  107343. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  107344. if(oggpackB_read(&r,30)!=0 || oggpackB_read(&r,16)!=0){
  107345. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  107346. exit(1);
  107347. }
  107348. if(oggpackB_look(&r,18)!=0 ||
  107349. oggpackB_look(&r,18)!=0){
  107350. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  107351. exit(1);
  107352. }
  107353. if(oggpackB_look(&r,19)!=-1 ||
  107354. oggpackB_look(&r,19)!=-1){
  107355. fprintf(stderr,"failed; read past end without -1.\n");
  107356. exit(1);
  107357. }
  107358. if(oggpackB_look(&r,32)!=-1 ||
  107359. oggpackB_look(&r,32)!=-1){
  107360. fprintf(stderr,"failed; read past end without -1.\n");
  107361. exit(1);
  107362. }
  107363. oggpackB_writeclear(&o);
  107364. fprintf(stderr,"ok.\n\n");
  107365. return(0);
  107366. }
  107367. #endif /* _V_SELFTEST */
  107368. #undef BUFFER_INCREMENT
  107369. #endif
  107370. /*** End of inlined file: bitwise.c ***/
  107371. /*** Start of inlined file: framing.c ***/
  107372. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  107373. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  107374. // tasks..
  107375. #if JUCE_MSVC
  107376. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  107377. #endif
  107378. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  107379. #if JUCE_USE_OGGVORBIS
  107380. #include <stdlib.h>
  107381. #include <string.h>
  107382. /* A complete description of Ogg framing exists in docs/framing.html */
  107383. int ogg_page_version(ogg_page *og){
  107384. return((int)(og->header[4]));
  107385. }
  107386. int ogg_page_continued(ogg_page *og){
  107387. return((int)(og->header[5]&0x01));
  107388. }
  107389. int ogg_page_bos(ogg_page *og){
  107390. return((int)(og->header[5]&0x02));
  107391. }
  107392. int ogg_page_eos(ogg_page *og){
  107393. return((int)(og->header[5]&0x04));
  107394. }
  107395. ogg_int64_t ogg_page_granulepos(ogg_page *og){
  107396. unsigned char *page=og->header;
  107397. ogg_int64_t granulepos=page[13]&(0xff);
  107398. granulepos= (granulepos<<8)|(page[12]&0xff);
  107399. granulepos= (granulepos<<8)|(page[11]&0xff);
  107400. granulepos= (granulepos<<8)|(page[10]&0xff);
  107401. granulepos= (granulepos<<8)|(page[9]&0xff);
  107402. granulepos= (granulepos<<8)|(page[8]&0xff);
  107403. granulepos= (granulepos<<8)|(page[7]&0xff);
  107404. granulepos= (granulepos<<8)|(page[6]&0xff);
  107405. return(granulepos);
  107406. }
  107407. int ogg_page_serialno(ogg_page *og){
  107408. return(og->header[14] |
  107409. (og->header[15]<<8) |
  107410. (og->header[16]<<16) |
  107411. (og->header[17]<<24));
  107412. }
  107413. long ogg_page_pageno(ogg_page *og){
  107414. return(og->header[18] |
  107415. (og->header[19]<<8) |
  107416. (og->header[20]<<16) |
  107417. (og->header[21]<<24));
  107418. }
  107419. /* returns the number of packets that are completed on this page (if
  107420. the leading packet is begun on a previous page, but ends on this
  107421. page, it's counted */
  107422. /* NOTE:
  107423. If a page consists of a packet begun on a previous page, and a new
  107424. packet begun (but not completed) on this page, the return will be:
  107425. ogg_page_packets(page) ==1,
  107426. ogg_page_continued(page) !=0
  107427. If a page happens to be a single packet that was begun on a
  107428. previous page, and spans to the next page (in the case of a three or
  107429. more page packet), the return will be:
  107430. ogg_page_packets(page) ==0,
  107431. ogg_page_continued(page) !=0
  107432. */
  107433. int ogg_page_packets(ogg_page *og){
  107434. int i,n=og->header[26],count=0;
  107435. for(i=0;i<n;i++)
  107436. if(og->header[27+i]<255)count++;
  107437. return(count);
  107438. }
  107439. #if 0
  107440. /* helper to initialize lookup for direct-table CRC (illustrative; we
  107441. use the static init below) */
  107442. static ogg_uint32_t _ogg_crc_entry(unsigned long index){
  107443. int i;
  107444. unsigned long r;
  107445. r = index << 24;
  107446. for (i=0; i<8; i++)
  107447. if (r & 0x80000000UL)
  107448. r = (r << 1) ^ 0x04c11db7; /* The same as the ethernet generator
  107449. polynomial, although we use an
  107450. unreflected alg and an init/final
  107451. of 0, not 0xffffffff */
  107452. else
  107453. r<<=1;
  107454. return (r & 0xffffffffUL);
  107455. }
  107456. #endif
  107457. static const ogg_uint32_t crc_lookup[256]={
  107458. 0x00000000,0x04c11db7,0x09823b6e,0x0d4326d9,
  107459. 0x130476dc,0x17c56b6b,0x1a864db2,0x1e475005,
  107460. 0x2608edb8,0x22c9f00f,0x2f8ad6d6,0x2b4bcb61,
  107461. 0x350c9b64,0x31cd86d3,0x3c8ea00a,0x384fbdbd,
  107462. 0x4c11db70,0x48d0c6c7,0x4593e01e,0x4152fda9,
  107463. 0x5f15adac,0x5bd4b01b,0x569796c2,0x52568b75,
  107464. 0x6a1936c8,0x6ed82b7f,0x639b0da6,0x675a1011,
  107465. 0x791d4014,0x7ddc5da3,0x709f7b7a,0x745e66cd,
  107466. 0x9823b6e0,0x9ce2ab57,0x91a18d8e,0x95609039,
  107467. 0x8b27c03c,0x8fe6dd8b,0x82a5fb52,0x8664e6e5,
  107468. 0xbe2b5b58,0xbaea46ef,0xb7a96036,0xb3687d81,
  107469. 0xad2f2d84,0xa9ee3033,0xa4ad16ea,0xa06c0b5d,
  107470. 0xd4326d90,0xd0f37027,0xddb056fe,0xd9714b49,
  107471. 0xc7361b4c,0xc3f706fb,0xceb42022,0xca753d95,
  107472. 0xf23a8028,0xf6fb9d9f,0xfbb8bb46,0xff79a6f1,
  107473. 0xe13ef6f4,0xe5ffeb43,0xe8bccd9a,0xec7dd02d,
  107474. 0x34867077,0x30476dc0,0x3d044b19,0x39c556ae,
  107475. 0x278206ab,0x23431b1c,0x2e003dc5,0x2ac12072,
  107476. 0x128e9dcf,0x164f8078,0x1b0ca6a1,0x1fcdbb16,
  107477. 0x018aeb13,0x054bf6a4,0x0808d07d,0x0cc9cdca,
  107478. 0x7897ab07,0x7c56b6b0,0x71159069,0x75d48dde,
  107479. 0x6b93dddb,0x6f52c06c,0x6211e6b5,0x66d0fb02,
  107480. 0x5e9f46bf,0x5a5e5b08,0x571d7dd1,0x53dc6066,
  107481. 0x4d9b3063,0x495a2dd4,0x44190b0d,0x40d816ba,
  107482. 0xaca5c697,0xa864db20,0xa527fdf9,0xa1e6e04e,
  107483. 0xbfa1b04b,0xbb60adfc,0xb6238b25,0xb2e29692,
  107484. 0x8aad2b2f,0x8e6c3698,0x832f1041,0x87ee0df6,
  107485. 0x99a95df3,0x9d684044,0x902b669d,0x94ea7b2a,
  107486. 0xe0b41de7,0xe4750050,0xe9362689,0xedf73b3e,
  107487. 0xf3b06b3b,0xf771768c,0xfa325055,0xfef34de2,
  107488. 0xc6bcf05f,0xc27dede8,0xcf3ecb31,0xcbffd686,
  107489. 0xd5b88683,0xd1799b34,0xdc3abded,0xd8fba05a,
  107490. 0x690ce0ee,0x6dcdfd59,0x608edb80,0x644fc637,
  107491. 0x7a089632,0x7ec98b85,0x738aad5c,0x774bb0eb,
  107492. 0x4f040d56,0x4bc510e1,0x46863638,0x42472b8f,
  107493. 0x5c007b8a,0x58c1663d,0x558240e4,0x51435d53,
  107494. 0x251d3b9e,0x21dc2629,0x2c9f00f0,0x285e1d47,
  107495. 0x36194d42,0x32d850f5,0x3f9b762c,0x3b5a6b9b,
  107496. 0x0315d626,0x07d4cb91,0x0a97ed48,0x0e56f0ff,
  107497. 0x1011a0fa,0x14d0bd4d,0x19939b94,0x1d528623,
  107498. 0xf12f560e,0xf5ee4bb9,0xf8ad6d60,0xfc6c70d7,
  107499. 0xe22b20d2,0xe6ea3d65,0xeba91bbc,0xef68060b,
  107500. 0xd727bbb6,0xd3e6a601,0xdea580d8,0xda649d6f,
  107501. 0xc423cd6a,0xc0e2d0dd,0xcda1f604,0xc960ebb3,
  107502. 0xbd3e8d7e,0xb9ff90c9,0xb4bcb610,0xb07daba7,
  107503. 0xae3afba2,0xaafbe615,0xa7b8c0cc,0xa379dd7b,
  107504. 0x9b3660c6,0x9ff77d71,0x92b45ba8,0x9675461f,
  107505. 0x8832161a,0x8cf30bad,0x81b02d74,0x857130c3,
  107506. 0x5d8a9099,0x594b8d2e,0x5408abf7,0x50c9b640,
  107507. 0x4e8ee645,0x4a4ffbf2,0x470cdd2b,0x43cdc09c,
  107508. 0x7b827d21,0x7f436096,0x7200464f,0x76c15bf8,
  107509. 0x68860bfd,0x6c47164a,0x61043093,0x65c52d24,
  107510. 0x119b4be9,0x155a565e,0x18197087,0x1cd86d30,
  107511. 0x029f3d35,0x065e2082,0x0b1d065b,0x0fdc1bec,
  107512. 0x3793a651,0x3352bbe6,0x3e119d3f,0x3ad08088,
  107513. 0x2497d08d,0x2056cd3a,0x2d15ebe3,0x29d4f654,
  107514. 0xc5a92679,0xc1683bce,0xcc2b1d17,0xc8ea00a0,
  107515. 0xd6ad50a5,0xd26c4d12,0xdf2f6bcb,0xdbee767c,
  107516. 0xe3a1cbc1,0xe760d676,0xea23f0af,0xeee2ed18,
  107517. 0xf0a5bd1d,0xf464a0aa,0xf9278673,0xfde69bc4,
  107518. 0x89b8fd09,0x8d79e0be,0x803ac667,0x84fbdbd0,
  107519. 0x9abc8bd5,0x9e7d9662,0x933eb0bb,0x97ffad0c,
  107520. 0xafb010b1,0xab710d06,0xa6322bdf,0xa2f33668,
  107521. 0xbcb4666d,0xb8757bda,0xb5365d03,0xb1f740b4};
  107522. /* init the encode/decode logical stream state */
  107523. int ogg_stream_init(ogg_stream_state *os,int serialno){
  107524. if(os){
  107525. memset(os,0,sizeof(*os));
  107526. os->body_storage=16*1024;
  107527. os->body_data=(unsigned char*) _ogg_malloc(os->body_storage*sizeof(*os->body_data));
  107528. os->lacing_storage=1024;
  107529. os->lacing_vals=(int*) _ogg_malloc(os->lacing_storage*sizeof(*os->lacing_vals));
  107530. os->granule_vals=(ogg_int64_t*) _ogg_malloc(os->lacing_storage*sizeof(*os->granule_vals));
  107531. os->serialno=serialno;
  107532. return(0);
  107533. }
  107534. return(-1);
  107535. }
  107536. /* _clear does not free os, only the non-flat storage within */
  107537. int ogg_stream_clear(ogg_stream_state *os){
  107538. if(os){
  107539. if(os->body_data)_ogg_free(os->body_data);
  107540. if(os->lacing_vals)_ogg_free(os->lacing_vals);
  107541. if(os->granule_vals)_ogg_free(os->granule_vals);
  107542. memset(os,0,sizeof(*os));
  107543. }
  107544. return(0);
  107545. }
  107546. int ogg_stream_destroy(ogg_stream_state *os){
  107547. if(os){
  107548. ogg_stream_clear(os);
  107549. _ogg_free(os);
  107550. }
  107551. return(0);
  107552. }
  107553. /* Helpers for ogg_stream_encode; this keeps the structure and
  107554. what's happening fairly clear */
  107555. static void _os_body_expand(ogg_stream_state *os,int needed){
  107556. if(os->body_storage<=os->body_fill+needed){
  107557. os->body_storage+=(needed+1024);
  107558. os->body_data=(unsigned char*) _ogg_realloc(os->body_data,os->body_storage*sizeof(*os->body_data));
  107559. }
  107560. }
  107561. static void _os_lacing_expand(ogg_stream_state *os,int needed){
  107562. if(os->lacing_storage<=os->lacing_fill+needed){
  107563. os->lacing_storage+=(needed+32);
  107564. os->lacing_vals=(int*)_ogg_realloc(os->lacing_vals,os->lacing_storage*sizeof(*os->lacing_vals));
  107565. os->granule_vals=(ogg_int64_t*)_ogg_realloc(os->granule_vals,os->lacing_storage*sizeof(*os->granule_vals));
  107566. }
  107567. }
  107568. /* checksum the page */
  107569. /* Direct table CRC; note that this will be faster in the future if we
  107570. perform the checksum silmultaneously with other copies */
  107571. void ogg_page_checksum_set(ogg_page *og){
  107572. if(og){
  107573. ogg_uint32_t crc_reg=0;
  107574. int i;
  107575. /* safety; needed for API behavior, but not framing code */
  107576. og->header[22]=0;
  107577. og->header[23]=0;
  107578. og->header[24]=0;
  107579. og->header[25]=0;
  107580. for(i=0;i<og->header_len;i++)
  107581. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->header[i]];
  107582. for(i=0;i<og->body_len;i++)
  107583. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->body[i]];
  107584. og->header[22]=(unsigned char)(crc_reg&0xff);
  107585. og->header[23]=(unsigned char)((crc_reg>>8)&0xff);
  107586. og->header[24]=(unsigned char)((crc_reg>>16)&0xff);
  107587. og->header[25]=(unsigned char)((crc_reg>>24)&0xff);
  107588. }
  107589. }
  107590. /* submit data to the internal buffer of the framing engine */
  107591. int ogg_stream_packetin(ogg_stream_state *os,ogg_packet *op){
  107592. int lacing_vals=op->bytes/255+1,i;
  107593. if(os->body_returned){
  107594. /* advance packet data according to the body_returned pointer. We
  107595. had to keep it around to return a pointer into the buffer last
  107596. call */
  107597. os->body_fill-=os->body_returned;
  107598. if(os->body_fill)
  107599. memmove(os->body_data,os->body_data+os->body_returned,
  107600. os->body_fill);
  107601. os->body_returned=0;
  107602. }
  107603. /* make sure we have the buffer storage */
  107604. _os_body_expand(os,op->bytes);
  107605. _os_lacing_expand(os,lacing_vals);
  107606. /* Copy in the submitted packet. Yes, the copy is a waste; this is
  107607. the liability of overly clean abstraction for the time being. It
  107608. will actually be fairly easy to eliminate the extra copy in the
  107609. future */
  107610. memcpy(os->body_data+os->body_fill,op->packet,op->bytes);
  107611. os->body_fill+=op->bytes;
  107612. /* Store lacing vals for this packet */
  107613. for(i=0;i<lacing_vals-1;i++){
  107614. os->lacing_vals[os->lacing_fill+i]=255;
  107615. os->granule_vals[os->lacing_fill+i]=os->granulepos;
  107616. }
  107617. os->lacing_vals[os->lacing_fill+i]=(op->bytes)%255;
  107618. os->granulepos=os->granule_vals[os->lacing_fill+i]=op->granulepos;
  107619. /* flag the first segment as the beginning of the packet */
  107620. os->lacing_vals[os->lacing_fill]|= 0x100;
  107621. os->lacing_fill+=lacing_vals;
  107622. /* for the sake of completeness */
  107623. os->packetno++;
  107624. if(op->e_o_s)os->e_o_s=1;
  107625. return(0);
  107626. }
  107627. /* This will flush remaining packets into a page (returning nonzero),
  107628. even if there is not enough data to trigger a flush normally
  107629. (undersized page). If there are no packets or partial packets to
  107630. flush, ogg_stream_flush returns 0. Note that ogg_stream_flush will
  107631. try to flush a normal sized page like ogg_stream_pageout; a call to
  107632. ogg_stream_flush does not guarantee that all packets have flushed.
  107633. Only a return value of 0 from ogg_stream_flush indicates all packet
  107634. data is flushed into pages.
  107635. since ogg_stream_flush will flush the last page in a stream even if
  107636. it's undersized, you almost certainly want to use ogg_stream_pageout
  107637. (and *not* ogg_stream_flush) unless you specifically need to flush
  107638. an page regardless of size in the middle of a stream. */
  107639. int ogg_stream_flush(ogg_stream_state *os,ogg_page *og){
  107640. int i;
  107641. int vals=0;
  107642. int maxvals=(os->lacing_fill>255?255:os->lacing_fill);
  107643. int bytes=0;
  107644. long acc=0;
  107645. ogg_int64_t granule_pos=-1;
  107646. if(maxvals==0)return(0);
  107647. /* construct a page */
  107648. /* decide how many segments to include */
  107649. /* If this is the initial header case, the first page must only include
  107650. the initial header packet */
  107651. if(os->b_o_s==0){ /* 'initial header page' case */
  107652. granule_pos=0;
  107653. for(vals=0;vals<maxvals;vals++){
  107654. if((os->lacing_vals[vals]&0x0ff)<255){
  107655. vals++;
  107656. break;
  107657. }
  107658. }
  107659. }else{
  107660. for(vals=0;vals<maxvals;vals++){
  107661. if(acc>4096)break;
  107662. acc+=os->lacing_vals[vals]&0x0ff;
  107663. if((os->lacing_vals[vals]&0xff)<255)
  107664. granule_pos=os->granule_vals[vals];
  107665. }
  107666. }
  107667. /* construct the header in temp storage */
  107668. memcpy(os->header,"OggS",4);
  107669. /* stream structure version */
  107670. os->header[4]=0x00;
  107671. /* continued packet flag? */
  107672. os->header[5]=0x00;
  107673. if((os->lacing_vals[0]&0x100)==0)os->header[5]|=0x01;
  107674. /* first page flag? */
  107675. if(os->b_o_s==0)os->header[5]|=0x02;
  107676. /* last page flag? */
  107677. if(os->e_o_s && os->lacing_fill==vals)os->header[5]|=0x04;
  107678. os->b_o_s=1;
  107679. /* 64 bits of PCM position */
  107680. for(i=6;i<14;i++){
  107681. os->header[i]=(unsigned char)(granule_pos&0xff);
  107682. granule_pos>>=8;
  107683. }
  107684. /* 32 bits of stream serial number */
  107685. {
  107686. long serialno=os->serialno;
  107687. for(i=14;i<18;i++){
  107688. os->header[i]=(unsigned char)(serialno&0xff);
  107689. serialno>>=8;
  107690. }
  107691. }
  107692. /* 32 bits of page counter (we have both counter and page header
  107693. because this val can roll over) */
  107694. if(os->pageno==-1)os->pageno=0; /* because someone called
  107695. stream_reset; this would be a
  107696. strange thing to do in an
  107697. encode stream, but it has
  107698. plausible uses */
  107699. {
  107700. long pageno=os->pageno++;
  107701. for(i=18;i<22;i++){
  107702. os->header[i]=(unsigned char)(pageno&0xff);
  107703. pageno>>=8;
  107704. }
  107705. }
  107706. /* zero for computation; filled in later */
  107707. os->header[22]=0;
  107708. os->header[23]=0;
  107709. os->header[24]=0;
  107710. os->header[25]=0;
  107711. /* segment table */
  107712. os->header[26]=(unsigned char)(vals&0xff);
  107713. for(i=0;i<vals;i++)
  107714. bytes+=os->header[i+27]=(unsigned char)(os->lacing_vals[i]&0xff);
  107715. /* set pointers in the ogg_page struct */
  107716. og->header=os->header;
  107717. og->header_len=os->header_fill=vals+27;
  107718. og->body=os->body_data+os->body_returned;
  107719. og->body_len=bytes;
  107720. /* advance the lacing data and set the body_returned pointer */
  107721. os->lacing_fill-=vals;
  107722. memmove(os->lacing_vals,os->lacing_vals+vals,os->lacing_fill*sizeof(*os->lacing_vals));
  107723. memmove(os->granule_vals,os->granule_vals+vals,os->lacing_fill*sizeof(*os->granule_vals));
  107724. os->body_returned+=bytes;
  107725. /* calculate the checksum */
  107726. ogg_page_checksum_set(og);
  107727. /* done */
  107728. return(1);
  107729. }
  107730. /* This constructs pages from buffered packet segments. The pointers
  107731. returned are to static buffers; do not free. The returned buffers are
  107732. good only until the next call (using the same ogg_stream_state) */
  107733. int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og){
  107734. if((os->e_o_s&&os->lacing_fill) || /* 'were done, now flush' case */
  107735. os->body_fill-os->body_returned > 4096 ||/* 'page nominal size' case */
  107736. os->lacing_fill>=255 || /* 'segment table full' case */
  107737. (os->lacing_fill&&!os->b_o_s)){ /* 'initial header page' case */
  107738. return(ogg_stream_flush(os,og));
  107739. }
  107740. /* not enough data to construct a page and not end of stream */
  107741. return(0);
  107742. }
  107743. int ogg_stream_eos(ogg_stream_state *os){
  107744. return os->e_o_s;
  107745. }
  107746. /* DECODING PRIMITIVES: packet streaming layer **********************/
  107747. /* This has two layers to place more of the multi-serialno and paging
  107748. control in the application's hands. First, we expose a data buffer
  107749. using ogg_sync_buffer(). The app either copies into the
  107750. buffer, or passes it directly to read(), etc. We then call
  107751. ogg_sync_wrote() to tell how many bytes we just added.
  107752. Pages are returned (pointers into the buffer in ogg_sync_state)
  107753. by ogg_sync_pageout(). The page is then submitted to
  107754. ogg_stream_pagein() along with the appropriate
  107755. ogg_stream_state* (ie, matching serialno). We then get raw
  107756. packets out calling ogg_stream_packetout() with a
  107757. ogg_stream_state. */
  107758. /* initialize the struct to a known state */
  107759. int ogg_sync_init(ogg_sync_state *oy){
  107760. if(oy){
  107761. memset(oy,0,sizeof(*oy));
  107762. }
  107763. return(0);
  107764. }
  107765. /* clear non-flat storage within */
  107766. int ogg_sync_clear(ogg_sync_state *oy){
  107767. if(oy){
  107768. if(oy->data)_ogg_free(oy->data);
  107769. ogg_sync_init(oy);
  107770. }
  107771. return(0);
  107772. }
  107773. int ogg_sync_destroy(ogg_sync_state *oy){
  107774. if(oy){
  107775. ogg_sync_clear(oy);
  107776. _ogg_free(oy);
  107777. }
  107778. return(0);
  107779. }
  107780. char *ogg_sync_buffer(ogg_sync_state *oy, long size){
  107781. /* first, clear out any space that has been previously returned */
  107782. if(oy->returned){
  107783. oy->fill-=oy->returned;
  107784. if(oy->fill>0)
  107785. memmove(oy->data,oy->data+oy->returned,oy->fill);
  107786. oy->returned=0;
  107787. }
  107788. if(size>oy->storage-oy->fill){
  107789. /* We need to extend the internal buffer */
  107790. long newsize=size+oy->fill+4096; /* an extra page to be nice */
  107791. if(oy->data)
  107792. oy->data=(unsigned char*) _ogg_realloc(oy->data,newsize);
  107793. else
  107794. oy->data=(unsigned char*) _ogg_malloc(newsize);
  107795. oy->storage=newsize;
  107796. }
  107797. /* expose a segment at least as large as requested at the fill mark */
  107798. return((char *)oy->data+oy->fill);
  107799. }
  107800. int ogg_sync_wrote(ogg_sync_state *oy, long bytes){
  107801. if(oy->fill+bytes>oy->storage)return(-1);
  107802. oy->fill+=bytes;
  107803. return(0);
  107804. }
  107805. /* sync the stream. This is meant to be useful for finding page
  107806. boundaries.
  107807. return values for this:
  107808. -n) skipped n bytes
  107809. 0) page not ready; more data (no bytes skipped)
  107810. n) page synced at current location; page length n bytes
  107811. */
  107812. long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og){
  107813. unsigned char *page=oy->data+oy->returned;
  107814. unsigned char *next;
  107815. long bytes=oy->fill-oy->returned;
  107816. if(oy->headerbytes==0){
  107817. int headerbytes,i;
  107818. if(bytes<27)return(0); /* not enough for a header */
  107819. /* verify capture pattern */
  107820. if(memcmp(page,"OggS",4))goto sync_fail;
  107821. headerbytes=page[26]+27;
  107822. if(bytes<headerbytes)return(0); /* not enough for header + seg table */
  107823. /* count up body length in the segment table */
  107824. for(i=0;i<page[26];i++)
  107825. oy->bodybytes+=page[27+i];
  107826. oy->headerbytes=headerbytes;
  107827. }
  107828. if(oy->bodybytes+oy->headerbytes>bytes)return(0);
  107829. /* The whole test page is buffered. Verify the checksum */
  107830. {
  107831. /* Grab the checksum bytes, set the header field to zero */
  107832. char chksum[4];
  107833. ogg_page log;
  107834. memcpy(chksum,page+22,4);
  107835. memset(page+22,0,4);
  107836. /* set up a temp page struct and recompute the checksum */
  107837. log.header=page;
  107838. log.header_len=oy->headerbytes;
  107839. log.body=page+oy->headerbytes;
  107840. log.body_len=oy->bodybytes;
  107841. ogg_page_checksum_set(&log);
  107842. /* Compare */
  107843. if(memcmp(chksum,page+22,4)){
  107844. /* D'oh. Mismatch! Corrupt page (or miscapture and not a page
  107845. at all) */
  107846. /* replace the computed checksum with the one actually read in */
  107847. memcpy(page+22,chksum,4);
  107848. /* Bad checksum. Lose sync */
  107849. goto sync_fail;
  107850. }
  107851. }
  107852. /* yes, have a whole page all ready to go */
  107853. {
  107854. unsigned char *page=oy->data+oy->returned;
  107855. long bytes;
  107856. if(og){
  107857. og->header=page;
  107858. og->header_len=oy->headerbytes;
  107859. og->body=page+oy->headerbytes;
  107860. og->body_len=oy->bodybytes;
  107861. }
  107862. oy->unsynced=0;
  107863. oy->returned+=(bytes=oy->headerbytes+oy->bodybytes);
  107864. oy->headerbytes=0;
  107865. oy->bodybytes=0;
  107866. return(bytes);
  107867. }
  107868. sync_fail:
  107869. oy->headerbytes=0;
  107870. oy->bodybytes=0;
  107871. /* search for possible capture */
  107872. next=(unsigned char*)memchr(page+1,'O',bytes-1);
  107873. if(!next)
  107874. next=oy->data+oy->fill;
  107875. oy->returned=next-oy->data;
  107876. return(-(next-page));
  107877. }
  107878. /* sync the stream and get a page. Keep trying until we find a page.
  107879. Supress 'sync errors' after reporting the first.
  107880. return values:
  107881. -1) recapture (hole in data)
  107882. 0) need more data
  107883. 1) page returned
  107884. Returns pointers into buffered data; invalidated by next call to
  107885. _stream, _clear, _init, or _buffer */
  107886. int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og){
  107887. /* all we need to do is verify a page at the head of the stream
  107888. buffer. If it doesn't verify, we look for the next potential
  107889. frame */
  107890. for(;;){
  107891. long ret=ogg_sync_pageseek(oy,og);
  107892. if(ret>0){
  107893. /* have a page */
  107894. return(1);
  107895. }
  107896. if(ret==0){
  107897. /* need more data */
  107898. return(0);
  107899. }
  107900. /* head did not start a synced page... skipped some bytes */
  107901. if(!oy->unsynced){
  107902. oy->unsynced=1;
  107903. return(-1);
  107904. }
  107905. /* loop. keep looking */
  107906. }
  107907. }
  107908. /* add the incoming page to the stream state; we decompose the page
  107909. into packet segments here as well. */
  107910. int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og){
  107911. unsigned char *header=og->header;
  107912. unsigned char *body=og->body;
  107913. long bodysize=og->body_len;
  107914. int segptr=0;
  107915. int version=ogg_page_version(og);
  107916. int continued=ogg_page_continued(og);
  107917. int bos=ogg_page_bos(og);
  107918. int eos=ogg_page_eos(og);
  107919. ogg_int64_t granulepos=ogg_page_granulepos(og);
  107920. int serialno=ogg_page_serialno(og);
  107921. long pageno=ogg_page_pageno(og);
  107922. int segments=header[26];
  107923. /* clean up 'returned data' */
  107924. {
  107925. long lr=os->lacing_returned;
  107926. long br=os->body_returned;
  107927. /* body data */
  107928. if(br){
  107929. os->body_fill-=br;
  107930. if(os->body_fill)
  107931. memmove(os->body_data,os->body_data+br,os->body_fill);
  107932. os->body_returned=0;
  107933. }
  107934. if(lr){
  107935. /* segment table */
  107936. if(os->lacing_fill-lr){
  107937. memmove(os->lacing_vals,os->lacing_vals+lr,
  107938. (os->lacing_fill-lr)*sizeof(*os->lacing_vals));
  107939. memmove(os->granule_vals,os->granule_vals+lr,
  107940. (os->lacing_fill-lr)*sizeof(*os->granule_vals));
  107941. }
  107942. os->lacing_fill-=lr;
  107943. os->lacing_packet-=lr;
  107944. os->lacing_returned=0;
  107945. }
  107946. }
  107947. /* check the serial number */
  107948. if(serialno!=os->serialno)return(-1);
  107949. if(version>0)return(-1);
  107950. _os_lacing_expand(os,segments+1);
  107951. /* are we in sequence? */
  107952. if(pageno!=os->pageno){
  107953. int i;
  107954. /* unroll previous partial packet (if any) */
  107955. for(i=os->lacing_packet;i<os->lacing_fill;i++)
  107956. os->body_fill-=os->lacing_vals[i]&0xff;
  107957. os->lacing_fill=os->lacing_packet;
  107958. /* make a note of dropped data in segment table */
  107959. if(os->pageno!=-1){
  107960. os->lacing_vals[os->lacing_fill++]=0x400;
  107961. os->lacing_packet++;
  107962. }
  107963. }
  107964. /* are we a 'continued packet' page? If so, we may need to skip
  107965. some segments */
  107966. if(continued){
  107967. if(os->lacing_fill<1 ||
  107968. os->lacing_vals[os->lacing_fill-1]==0x400){
  107969. bos=0;
  107970. for(;segptr<segments;segptr++){
  107971. int val=header[27+segptr];
  107972. body+=val;
  107973. bodysize-=val;
  107974. if(val<255){
  107975. segptr++;
  107976. break;
  107977. }
  107978. }
  107979. }
  107980. }
  107981. if(bodysize){
  107982. _os_body_expand(os,bodysize);
  107983. memcpy(os->body_data+os->body_fill,body,bodysize);
  107984. os->body_fill+=bodysize;
  107985. }
  107986. {
  107987. int saved=-1;
  107988. while(segptr<segments){
  107989. int val=header[27+segptr];
  107990. os->lacing_vals[os->lacing_fill]=val;
  107991. os->granule_vals[os->lacing_fill]=-1;
  107992. if(bos){
  107993. os->lacing_vals[os->lacing_fill]|=0x100;
  107994. bos=0;
  107995. }
  107996. if(val<255)saved=os->lacing_fill;
  107997. os->lacing_fill++;
  107998. segptr++;
  107999. if(val<255)os->lacing_packet=os->lacing_fill;
  108000. }
  108001. /* set the granulepos on the last granuleval of the last full packet */
  108002. if(saved!=-1){
  108003. os->granule_vals[saved]=granulepos;
  108004. }
  108005. }
  108006. if(eos){
  108007. os->e_o_s=1;
  108008. if(os->lacing_fill>0)
  108009. os->lacing_vals[os->lacing_fill-1]|=0x200;
  108010. }
  108011. os->pageno=pageno+1;
  108012. return(0);
  108013. }
  108014. /* clear things to an initial state. Good to call, eg, before seeking */
  108015. int ogg_sync_reset(ogg_sync_state *oy){
  108016. oy->fill=0;
  108017. oy->returned=0;
  108018. oy->unsynced=0;
  108019. oy->headerbytes=0;
  108020. oy->bodybytes=0;
  108021. return(0);
  108022. }
  108023. int ogg_stream_reset(ogg_stream_state *os){
  108024. os->body_fill=0;
  108025. os->body_returned=0;
  108026. os->lacing_fill=0;
  108027. os->lacing_packet=0;
  108028. os->lacing_returned=0;
  108029. os->header_fill=0;
  108030. os->e_o_s=0;
  108031. os->b_o_s=0;
  108032. os->pageno=-1;
  108033. os->packetno=0;
  108034. os->granulepos=0;
  108035. return(0);
  108036. }
  108037. int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno){
  108038. ogg_stream_reset(os);
  108039. os->serialno=serialno;
  108040. return(0);
  108041. }
  108042. static int _packetout(ogg_stream_state *os,ogg_packet *op,int adv){
  108043. /* The last part of decode. We have the stream broken into packet
  108044. segments. Now we need to group them into packets (or return the
  108045. out of sync markers) */
  108046. int ptr=os->lacing_returned;
  108047. if(os->lacing_packet<=ptr)return(0);
  108048. if(os->lacing_vals[ptr]&0x400){
  108049. /* we need to tell the codec there's a gap; it might need to
  108050. handle previous packet dependencies. */
  108051. os->lacing_returned++;
  108052. os->packetno++;
  108053. return(-1);
  108054. }
  108055. if(!op && !adv)return(1); /* just using peek as an inexpensive way
  108056. to ask if there's a whole packet
  108057. waiting */
  108058. /* Gather the whole packet. We'll have no holes or a partial packet */
  108059. {
  108060. int size=os->lacing_vals[ptr]&0xff;
  108061. int bytes=size;
  108062. int eos=os->lacing_vals[ptr]&0x200; /* last packet of the stream? */
  108063. int bos=os->lacing_vals[ptr]&0x100; /* first packet of the stream? */
  108064. while(size==255){
  108065. int val=os->lacing_vals[++ptr];
  108066. size=val&0xff;
  108067. if(val&0x200)eos=0x200;
  108068. bytes+=size;
  108069. }
  108070. if(op){
  108071. op->e_o_s=eos;
  108072. op->b_o_s=bos;
  108073. op->packet=os->body_data+os->body_returned;
  108074. op->packetno=os->packetno;
  108075. op->granulepos=os->granule_vals[ptr];
  108076. op->bytes=bytes;
  108077. }
  108078. if(adv){
  108079. os->body_returned+=bytes;
  108080. os->lacing_returned=ptr+1;
  108081. os->packetno++;
  108082. }
  108083. }
  108084. return(1);
  108085. }
  108086. int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op){
  108087. return _packetout(os,op,1);
  108088. }
  108089. int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op){
  108090. return _packetout(os,op,0);
  108091. }
  108092. void ogg_packet_clear(ogg_packet *op) {
  108093. _ogg_free(op->packet);
  108094. memset(op, 0, sizeof(*op));
  108095. }
  108096. #ifdef _V_SELFTEST
  108097. #include <stdio.h>
  108098. ogg_stream_state os_en, os_de;
  108099. ogg_sync_state oy;
  108100. void checkpacket(ogg_packet *op,int len, int no, int pos){
  108101. long j;
  108102. static int sequence=0;
  108103. static int lastno=0;
  108104. if(op->bytes!=len){
  108105. fprintf(stderr,"incorrect packet length!\n");
  108106. exit(1);
  108107. }
  108108. if(op->granulepos!=pos){
  108109. fprintf(stderr,"incorrect packet position!\n");
  108110. exit(1);
  108111. }
  108112. /* packet number just follows sequence/gap; adjust the input number
  108113. for that */
  108114. if(no==0){
  108115. sequence=0;
  108116. }else{
  108117. sequence++;
  108118. if(no>lastno+1)
  108119. sequence++;
  108120. }
  108121. lastno=no;
  108122. if(op->packetno!=sequence){
  108123. fprintf(stderr,"incorrect packet sequence %ld != %d\n",
  108124. (long)(op->packetno),sequence);
  108125. exit(1);
  108126. }
  108127. /* Test data */
  108128. for(j=0;j<op->bytes;j++)
  108129. if(op->packet[j]!=((j+no)&0xff)){
  108130. fprintf(stderr,"body data mismatch (1) at pos %ld: %x!=%lx!\n\n",
  108131. j,op->packet[j],(j+no)&0xff);
  108132. exit(1);
  108133. }
  108134. }
  108135. void check_page(unsigned char *data,const int *header,ogg_page *og){
  108136. long j;
  108137. /* Test data */
  108138. for(j=0;j<og->body_len;j++)
  108139. if(og->body[j]!=data[j]){
  108140. fprintf(stderr,"body data mismatch (2) at pos %ld: %x!=%x!\n\n",
  108141. j,data[j],og->body[j]);
  108142. exit(1);
  108143. }
  108144. /* Test header */
  108145. for(j=0;j<og->header_len;j++){
  108146. if(og->header[j]!=header[j]){
  108147. fprintf(stderr,"header content mismatch at pos %ld:\n",j);
  108148. for(j=0;j<header[26]+27;j++)
  108149. fprintf(stderr," (%ld)%02x:%02x",j,header[j],og->header[j]);
  108150. fprintf(stderr,"\n");
  108151. exit(1);
  108152. }
  108153. }
  108154. if(og->header_len!=header[26]+27){
  108155. fprintf(stderr,"header length incorrect! (%ld!=%d)\n",
  108156. og->header_len,header[26]+27);
  108157. exit(1);
  108158. }
  108159. }
  108160. void print_header(ogg_page *og){
  108161. int j;
  108162. fprintf(stderr,"\nHEADER:\n");
  108163. fprintf(stderr," capture: %c %c %c %c version: %d flags: %x\n",
  108164. og->header[0],og->header[1],og->header[2],og->header[3],
  108165. (int)og->header[4],(int)og->header[5]);
  108166. fprintf(stderr," granulepos: %d serialno: %d pageno: %ld\n",
  108167. (og->header[9]<<24)|(og->header[8]<<16)|
  108168. (og->header[7]<<8)|og->header[6],
  108169. (og->header[17]<<24)|(og->header[16]<<16)|
  108170. (og->header[15]<<8)|og->header[14],
  108171. ((long)(og->header[21])<<24)|(og->header[20]<<16)|
  108172. (og->header[19]<<8)|og->header[18]);
  108173. fprintf(stderr," checksum: %02x:%02x:%02x:%02x\n segments: %d (",
  108174. (int)og->header[22],(int)og->header[23],
  108175. (int)og->header[24],(int)og->header[25],
  108176. (int)og->header[26]);
  108177. for(j=27;j<og->header_len;j++)
  108178. fprintf(stderr,"%d ",(int)og->header[j]);
  108179. fprintf(stderr,")\n\n");
  108180. }
  108181. void copy_page(ogg_page *og){
  108182. unsigned char *temp=_ogg_malloc(og->header_len);
  108183. memcpy(temp,og->header,og->header_len);
  108184. og->header=temp;
  108185. temp=_ogg_malloc(og->body_len);
  108186. memcpy(temp,og->body,og->body_len);
  108187. og->body=temp;
  108188. }
  108189. void free_page(ogg_page *og){
  108190. _ogg_free (og->header);
  108191. _ogg_free (og->body);
  108192. }
  108193. void error(void){
  108194. fprintf(stderr,"error!\n");
  108195. exit(1);
  108196. }
  108197. /* 17 only */
  108198. const int head1_0[] = {0x4f,0x67,0x67,0x53,0,0x06,
  108199. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108200. 0x01,0x02,0x03,0x04,0,0,0,0,
  108201. 0x15,0xed,0xec,0x91,
  108202. 1,
  108203. 17};
  108204. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  108205. const int head1_1[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108206. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108207. 0x01,0x02,0x03,0x04,0,0,0,0,
  108208. 0x59,0x10,0x6c,0x2c,
  108209. 1,
  108210. 17};
  108211. const int head2_1[] = {0x4f,0x67,0x67,0x53,0,0x04,
  108212. 0x07,0x18,0x00,0x00,0x00,0x00,0x00,0x00,
  108213. 0x01,0x02,0x03,0x04,1,0,0,0,
  108214. 0x89,0x33,0x85,0xce,
  108215. 13,
  108216. 254,255,0,255,1,255,245,255,255,0,
  108217. 255,255,90};
  108218. /* nil packets; beginning,middle,end */
  108219. const int head1_2[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108220. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108221. 0x01,0x02,0x03,0x04,0,0,0,0,
  108222. 0xff,0x7b,0x23,0x17,
  108223. 1,
  108224. 0};
  108225. const int head2_2[] = {0x4f,0x67,0x67,0x53,0,0x04,
  108226. 0x07,0x28,0x00,0x00,0x00,0x00,0x00,0x00,
  108227. 0x01,0x02,0x03,0x04,1,0,0,0,
  108228. 0x5c,0x3f,0x66,0xcb,
  108229. 17,
  108230. 17,254,255,0,0,255,1,0,255,245,255,255,0,
  108231. 255,255,90,0};
  108232. /* large initial packet */
  108233. const int head1_3[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108234. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108235. 0x01,0x02,0x03,0x04,0,0,0,0,
  108236. 0x01,0x27,0x31,0xaa,
  108237. 18,
  108238. 255,255,255,255,255,255,255,255,
  108239. 255,255,255,255,255,255,255,255,255,10};
  108240. const int head2_3[] = {0x4f,0x67,0x67,0x53,0,0x04,
  108241. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  108242. 0x01,0x02,0x03,0x04,1,0,0,0,
  108243. 0x7f,0x4e,0x8a,0xd2,
  108244. 4,
  108245. 255,4,255,0};
  108246. /* continuing packet test */
  108247. const int head1_4[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108248. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108249. 0x01,0x02,0x03,0x04,0,0,0,0,
  108250. 0xff,0x7b,0x23,0x17,
  108251. 1,
  108252. 0};
  108253. const int head2_4[] = {0x4f,0x67,0x67,0x53,0,0x00,
  108254. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  108255. 0x01,0x02,0x03,0x04,1,0,0,0,
  108256. 0x54,0x05,0x51,0xc8,
  108257. 17,
  108258. 255,255,255,255,255,255,255,255,
  108259. 255,255,255,255,255,255,255,255,255};
  108260. const int head3_4[] = {0x4f,0x67,0x67,0x53,0,0x05,
  108261. 0x07,0x0c,0x00,0x00,0x00,0x00,0x00,0x00,
  108262. 0x01,0x02,0x03,0x04,2,0,0,0,
  108263. 0xc8,0xc3,0xcb,0xed,
  108264. 5,
  108265. 10,255,4,255,0};
  108266. /* page with the 255 segment limit */
  108267. const int head1_5[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108268. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108269. 0x01,0x02,0x03,0x04,0,0,0,0,
  108270. 0xff,0x7b,0x23,0x17,
  108271. 1,
  108272. 0};
  108273. const int head2_5[] = {0x4f,0x67,0x67,0x53,0,0x00,
  108274. 0x07,0xfc,0x03,0x00,0x00,0x00,0x00,0x00,
  108275. 0x01,0x02,0x03,0x04,1,0,0,0,
  108276. 0xed,0x2a,0x2e,0xa7,
  108277. 255,
  108278. 10,10,10,10,10,10,10,10,
  108279. 10,10,10,10,10,10,10,10,
  108280. 10,10,10,10,10,10,10,10,
  108281. 10,10,10,10,10,10,10,10,
  108282. 10,10,10,10,10,10,10,10,
  108283. 10,10,10,10,10,10,10,10,
  108284. 10,10,10,10,10,10,10,10,
  108285. 10,10,10,10,10,10,10,10,
  108286. 10,10,10,10,10,10,10,10,
  108287. 10,10,10,10,10,10,10,10,
  108288. 10,10,10,10,10,10,10,10,
  108289. 10,10,10,10,10,10,10,10,
  108290. 10,10,10,10,10,10,10,10,
  108291. 10,10,10,10,10,10,10,10,
  108292. 10,10,10,10,10,10,10,10,
  108293. 10,10,10,10,10,10,10,10,
  108294. 10,10,10,10,10,10,10,10,
  108295. 10,10,10,10,10,10,10,10,
  108296. 10,10,10,10,10,10,10,10,
  108297. 10,10,10,10,10,10,10,10,
  108298. 10,10,10,10,10,10,10,10,
  108299. 10,10,10,10,10,10,10,10,
  108300. 10,10,10,10,10,10,10,10,
  108301. 10,10,10,10,10,10,10,10,
  108302. 10,10,10,10,10,10,10,10,
  108303. 10,10,10,10,10,10,10,10,
  108304. 10,10,10,10,10,10,10,10,
  108305. 10,10,10,10,10,10,10,10,
  108306. 10,10,10,10,10,10,10,10,
  108307. 10,10,10,10,10,10,10,10,
  108308. 10,10,10,10,10,10,10,10,
  108309. 10,10,10,10,10,10,10};
  108310. const int head3_5[] = {0x4f,0x67,0x67,0x53,0,0x04,
  108311. 0x07,0x00,0x04,0x00,0x00,0x00,0x00,0x00,
  108312. 0x01,0x02,0x03,0x04,2,0,0,0,
  108313. 0x6c,0x3b,0x82,0x3d,
  108314. 1,
  108315. 50};
  108316. /* packet that overspans over an entire page */
  108317. const int head1_6[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108318. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108319. 0x01,0x02,0x03,0x04,0,0,0,0,
  108320. 0xff,0x7b,0x23,0x17,
  108321. 1,
  108322. 0};
  108323. const int head2_6[] = {0x4f,0x67,0x67,0x53,0,0x00,
  108324. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  108325. 0x01,0x02,0x03,0x04,1,0,0,0,
  108326. 0x3c,0xd9,0x4d,0x3f,
  108327. 17,
  108328. 100,255,255,255,255,255,255,255,255,
  108329. 255,255,255,255,255,255,255,255};
  108330. const int head3_6[] = {0x4f,0x67,0x67,0x53,0,0x01,
  108331. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  108332. 0x01,0x02,0x03,0x04,2,0,0,0,
  108333. 0x01,0xd2,0xe5,0xe5,
  108334. 17,
  108335. 255,255,255,255,255,255,255,255,
  108336. 255,255,255,255,255,255,255,255,255};
  108337. const int head4_6[] = {0x4f,0x67,0x67,0x53,0,0x05,
  108338. 0x07,0x10,0x00,0x00,0x00,0x00,0x00,0x00,
  108339. 0x01,0x02,0x03,0x04,3,0,0,0,
  108340. 0xef,0xdd,0x88,0xde,
  108341. 7,
  108342. 255,255,75,255,4,255,0};
  108343. /* packet that overspans over an entire page */
  108344. const int head1_7[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108345. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108346. 0x01,0x02,0x03,0x04,0,0,0,0,
  108347. 0xff,0x7b,0x23,0x17,
  108348. 1,
  108349. 0};
  108350. const int head2_7[] = {0x4f,0x67,0x67,0x53,0,0x00,
  108351. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  108352. 0x01,0x02,0x03,0x04,1,0,0,0,
  108353. 0x3c,0xd9,0x4d,0x3f,
  108354. 17,
  108355. 100,255,255,255,255,255,255,255,255,
  108356. 255,255,255,255,255,255,255,255};
  108357. const int head3_7[] = {0x4f,0x67,0x67,0x53,0,0x05,
  108358. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  108359. 0x01,0x02,0x03,0x04,2,0,0,0,
  108360. 0xd4,0xe0,0x60,0xe5,
  108361. 1,0};
  108362. void test_pack(const int *pl, const int **headers, int byteskip,
  108363. int pageskip, int packetskip){
  108364. unsigned char *data=_ogg_malloc(1024*1024); /* for scripted test cases only */
  108365. long inptr=0;
  108366. long outptr=0;
  108367. long deptr=0;
  108368. long depacket=0;
  108369. long granule_pos=7,pageno=0;
  108370. int i,j,packets,pageout=pageskip;
  108371. int eosflag=0;
  108372. int bosflag=0;
  108373. int byteskipcount=0;
  108374. ogg_stream_reset(&os_en);
  108375. ogg_stream_reset(&os_de);
  108376. ogg_sync_reset(&oy);
  108377. for(packets=0;packets<packetskip;packets++)
  108378. depacket+=pl[packets];
  108379. for(packets=0;;packets++)if(pl[packets]==-1)break;
  108380. for(i=0;i<packets;i++){
  108381. /* construct a test packet */
  108382. ogg_packet op;
  108383. int len=pl[i];
  108384. op.packet=data+inptr;
  108385. op.bytes=len;
  108386. op.e_o_s=(pl[i+1]<0?1:0);
  108387. op.granulepos=granule_pos;
  108388. granule_pos+=1024;
  108389. for(j=0;j<len;j++)data[inptr++]=i+j;
  108390. /* submit the test packet */
  108391. ogg_stream_packetin(&os_en,&op);
  108392. /* retrieve any finished pages */
  108393. {
  108394. ogg_page og;
  108395. while(ogg_stream_pageout(&os_en,&og)){
  108396. /* We have a page. Check it carefully */
  108397. fprintf(stderr,"%ld, ",pageno);
  108398. if(headers[pageno]==NULL){
  108399. fprintf(stderr,"coded too many pages!\n");
  108400. exit(1);
  108401. }
  108402. check_page(data+outptr,headers[pageno],&og);
  108403. outptr+=og.body_len;
  108404. pageno++;
  108405. if(pageskip){
  108406. bosflag=1;
  108407. pageskip--;
  108408. deptr+=og.body_len;
  108409. }
  108410. /* have a complete page; submit it to sync/decode */
  108411. {
  108412. ogg_page og_de;
  108413. ogg_packet op_de,op_de2;
  108414. char *buf=ogg_sync_buffer(&oy,og.header_len+og.body_len);
  108415. char *next=buf;
  108416. byteskipcount+=og.header_len;
  108417. if(byteskipcount>byteskip){
  108418. memcpy(next,og.header,byteskipcount-byteskip);
  108419. next+=byteskipcount-byteskip;
  108420. byteskipcount=byteskip;
  108421. }
  108422. byteskipcount+=og.body_len;
  108423. if(byteskipcount>byteskip){
  108424. memcpy(next,og.body,byteskipcount-byteskip);
  108425. next+=byteskipcount-byteskip;
  108426. byteskipcount=byteskip;
  108427. }
  108428. ogg_sync_wrote(&oy,next-buf);
  108429. while(1){
  108430. int ret=ogg_sync_pageout(&oy,&og_de);
  108431. if(ret==0)break;
  108432. if(ret<0)continue;
  108433. /* got a page. Happy happy. Verify that it's good. */
  108434. fprintf(stderr,"(%ld), ",pageout);
  108435. check_page(data+deptr,headers[pageout],&og_de);
  108436. deptr+=og_de.body_len;
  108437. pageout++;
  108438. /* submit it to deconstitution */
  108439. ogg_stream_pagein(&os_de,&og_de);
  108440. /* packets out? */
  108441. while(ogg_stream_packetpeek(&os_de,&op_de2)>0){
  108442. ogg_stream_packetpeek(&os_de,NULL);
  108443. ogg_stream_packetout(&os_de,&op_de); /* just catching them all */
  108444. /* verify peek and out match */
  108445. if(memcmp(&op_de,&op_de2,sizeof(op_de))){
  108446. fprintf(stderr,"packetout != packetpeek! pos=%ld\n",
  108447. depacket);
  108448. exit(1);
  108449. }
  108450. /* verify the packet! */
  108451. /* check data */
  108452. if(memcmp(data+depacket,op_de.packet,op_de.bytes)){
  108453. fprintf(stderr,"packet data mismatch in decode! pos=%ld\n",
  108454. depacket);
  108455. exit(1);
  108456. }
  108457. /* check bos flag */
  108458. if(bosflag==0 && op_de.b_o_s==0){
  108459. fprintf(stderr,"b_o_s flag not set on packet!\n");
  108460. exit(1);
  108461. }
  108462. if(bosflag && op_de.b_o_s){
  108463. fprintf(stderr,"b_o_s flag incorrectly set on packet!\n");
  108464. exit(1);
  108465. }
  108466. bosflag=1;
  108467. depacket+=op_de.bytes;
  108468. /* check eos flag */
  108469. if(eosflag){
  108470. fprintf(stderr,"Multiple decoded packets with eos flag!\n");
  108471. exit(1);
  108472. }
  108473. if(op_de.e_o_s)eosflag=1;
  108474. /* check granulepos flag */
  108475. if(op_de.granulepos!=-1){
  108476. fprintf(stderr," granule:%ld ",(long)op_de.granulepos);
  108477. }
  108478. }
  108479. }
  108480. }
  108481. }
  108482. }
  108483. }
  108484. _ogg_free(data);
  108485. if(headers[pageno]!=NULL){
  108486. fprintf(stderr,"did not write last page!\n");
  108487. exit(1);
  108488. }
  108489. if(headers[pageout]!=NULL){
  108490. fprintf(stderr,"did not decode last page!\n");
  108491. exit(1);
  108492. }
  108493. if(inptr!=outptr){
  108494. fprintf(stderr,"encoded page data incomplete!\n");
  108495. exit(1);
  108496. }
  108497. if(inptr!=deptr){
  108498. fprintf(stderr,"decoded page data incomplete!\n");
  108499. exit(1);
  108500. }
  108501. if(inptr!=depacket){
  108502. fprintf(stderr,"decoded packet data incomplete!\n");
  108503. exit(1);
  108504. }
  108505. if(!eosflag){
  108506. fprintf(stderr,"Never got a packet with EOS set!\n");
  108507. exit(1);
  108508. }
  108509. fprintf(stderr,"ok.\n");
  108510. }
  108511. int main(void){
  108512. ogg_stream_init(&os_en,0x04030201);
  108513. ogg_stream_init(&os_de,0x04030201);
  108514. ogg_sync_init(&oy);
  108515. /* Exercise each code path in the framing code. Also verify that
  108516. the checksums are working. */
  108517. {
  108518. /* 17 only */
  108519. const int packets[]={17, -1};
  108520. const int *headret[]={head1_0,NULL};
  108521. fprintf(stderr,"testing single page encoding... ");
  108522. test_pack(packets,headret,0,0,0);
  108523. }
  108524. {
  108525. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  108526. const int packets[]={17, 254, 255, 256, 500, 510, 600, -1};
  108527. const int *headret[]={head1_1,head2_1,NULL};
  108528. fprintf(stderr,"testing basic page encoding... ");
  108529. test_pack(packets,headret,0,0,0);
  108530. }
  108531. {
  108532. /* nil packets; beginning,middle,end */
  108533. const int packets[]={0,17, 254, 255, 0, 256, 0, 500, 510, 600, 0, -1};
  108534. const int *headret[]={head1_2,head2_2,NULL};
  108535. fprintf(stderr,"testing basic nil packets... ");
  108536. test_pack(packets,headret,0,0,0);
  108537. }
  108538. {
  108539. /* large initial packet */
  108540. const int packets[]={4345,259,255,-1};
  108541. const int *headret[]={head1_3,head2_3,NULL};
  108542. fprintf(stderr,"testing initial-packet lacing > 4k... ");
  108543. test_pack(packets,headret,0,0,0);
  108544. }
  108545. {
  108546. /* continuing packet test */
  108547. const int packets[]={0,4345,259,255,-1};
  108548. const int *headret[]={head1_4,head2_4,head3_4,NULL};
  108549. fprintf(stderr,"testing single packet page span... ");
  108550. test_pack(packets,headret,0,0,0);
  108551. }
  108552. /* page with the 255 segment limit */
  108553. {
  108554. const int packets[]={0,10,10,10,10,10,10,10,10,
  108555. 10,10,10,10,10,10,10,10,
  108556. 10,10,10,10,10,10,10,10,
  108557. 10,10,10,10,10,10,10,10,
  108558. 10,10,10,10,10,10,10,10,
  108559. 10,10,10,10,10,10,10,10,
  108560. 10,10,10,10,10,10,10,10,
  108561. 10,10,10,10,10,10,10,10,
  108562. 10,10,10,10,10,10,10,10,
  108563. 10,10,10,10,10,10,10,10,
  108564. 10,10,10,10,10,10,10,10,
  108565. 10,10,10,10,10,10,10,10,
  108566. 10,10,10,10,10,10,10,10,
  108567. 10,10,10,10,10,10,10,10,
  108568. 10,10,10,10,10,10,10,10,
  108569. 10,10,10,10,10,10,10,10,
  108570. 10,10,10,10,10,10,10,10,
  108571. 10,10,10,10,10,10,10,10,
  108572. 10,10,10,10,10,10,10,10,
  108573. 10,10,10,10,10,10,10,10,
  108574. 10,10,10,10,10,10,10,10,
  108575. 10,10,10,10,10,10,10,10,
  108576. 10,10,10,10,10,10,10,10,
  108577. 10,10,10,10,10,10,10,10,
  108578. 10,10,10,10,10,10,10,10,
  108579. 10,10,10,10,10,10,10,10,
  108580. 10,10,10,10,10,10,10,10,
  108581. 10,10,10,10,10,10,10,10,
  108582. 10,10,10,10,10,10,10,10,
  108583. 10,10,10,10,10,10,10,10,
  108584. 10,10,10,10,10,10,10,10,
  108585. 10,10,10,10,10,10,10,50,-1};
  108586. const int *headret[]={head1_5,head2_5,head3_5,NULL};
  108587. fprintf(stderr,"testing max packet segments... ");
  108588. test_pack(packets,headret,0,0,0);
  108589. }
  108590. {
  108591. /* packet that overspans over an entire page */
  108592. const int packets[]={0,100,9000,259,255,-1};
  108593. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  108594. fprintf(stderr,"testing very large packets... ");
  108595. test_pack(packets,headret,0,0,0);
  108596. }
  108597. {
  108598. /* test for the libogg 1.1.1 resync in large continuation bug
  108599. found by Josh Coalson) */
  108600. const int packets[]={0,100,9000,259,255,-1};
  108601. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  108602. fprintf(stderr,"testing continuation resync in very large packets... ");
  108603. test_pack(packets,headret,100,2,3);
  108604. }
  108605. {
  108606. /* term only page. why not? */
  108607. const int packets[]={0,100,4080,-1};
  108608. const int *headret[]={head1_7,head2_7,head3_7,NULL};
  108609. fprintf(stderr,"testing zero data page (1 nil packet)... ");
  108610. test_pack(packets,headret,0,0,0);
  108611. }
  108612. {
  108613. /* build a bunch of pages for testing */
  108614. unsigned char *data=_ogg_malloc(1024*1024);
  108615. int pl[]={0,100,4079,2956,2057,76,34,912,0,234,1000,1000,1000,300,-1};
  108616. int inptr=0,i,j;
  108617. ogg_page og[5];
  108618. ogg_stream_reset(&os_en);
  108619. for(i=0;pl[i]!=-1;i++){
  108620. ogg_packet op;
  108621. int len=pl[i];
  108622. op.packet=data+inptr;
  108623. op.bytes=len;
  108624. op.e_o_s=(pl[i+1]<0?1:0);
  108625. op.granulepos=(i+1)*1000;
  108626. for(j=0;j<len;j++)data[inptr++]=i+j;
  108627. ogg_stream_packetin(&os_en,&op);
  108628. }
  108629. _ogg_free(data);
  108630. /* retrieve finished pages */
  108631. for(i=0;i<5;i++){
  108632. if(ogg_stream_pageout(&os_en,&og[i])==0){
  108633. fprintf(stderr,"Too few pages output building sync tests!\n");
  108634. exit(1);
  108635. }
  108636. copy_page(&og[i]);
  108637. }
  108638. /* Test lost pages on pagein/packetout: no rollback */
  108639. {
  108640. ogg_page temp;
  108641. ogg_packet test;
  108642. fprintf(stderr,"Testing loss of pages... ");
  108643. ogg_sync_reset(&oy);
  108644. ogg_stream_reset(&os_de);
  108645. for(i=0;i<5;i++){
  108646. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  108647. og[i].header_len);
  108648. ogg_sync_wrote(&oy,og[i].header_len);
  108649. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  108650. ogg_sync_wrote(&oy,og[i].body_len);
  108651. }
  108652. ogg_sync_pageout(&oy,&temp);
  108653. ogg_stream_pagein(&os_de,&temp);
  108654. ogg_sync_pageout(&oy,&temp);
  108655. ogg_stream_pagein(&os_de,&temp);
  108656. ogg_sync_pageout(&oy,&temp);
  108657. /* skip */
  108658. ogg_sync_pageout(&oy,&temp);
  108659. ogg_stream_pagein(&os_de,&temp);
  108660. /* do we get the expected results/packets? */
  108661. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  108662. checkpacket(&test,0,0,0);
  108663. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  108664. checkpacket(&test,100,1,-1);
  108665. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  108666. checkpacket(&test,4079,2,3000);
  108667. if(ogg_stream_packetout(&os_de,&test)!=-1){
  108668. fprintf(stderr,"Error: loss of page did not return error\n");
  108669. exit(1);
  108670. }
  108671. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  108672. checkpacket(&test,76,5,-1);
  108673. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  108674. checkpacket(&test,34,6,-1);
  108675. fprintf(stderr,"ok.\n");
  108676. }
  108677. /* Test lost pages on pagein/packetout: rollback with continuation */
  108678. {
  108679. ogg_page temp;
  108680. ogg_packet test;
  108681. fprintf(stderr,"Testing loss of pages (rollback required)... ");
  108682. ogg_sync_reset(&oy);
  108683. ogg_stream_reset(&os_de);
  108684. for(i=0;i<5;i++){
  108685. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  108686. og[i].header_len);
  108687. ogg_sync_wrote(&oy,og[i].header_len);
  108688. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  108689. ogg_sync_wrote(&oy,og[i].body_len);
  108690. }
  108691. ogg_sync_pageout(&oy,&temp);
  108692. ogg_stream_pagein(&os_de,&temp);
  108693. ogg_sync_pageout(&oy,&temp);
  108694. ogg_stream_pagein(&os_de,&temp);
  108695. ogg_sync_pageout(&oy,&temp);
  108696. ogg_stream_pagein(&os_de,&temp);
  108697. ogg_sync_pageout(&oy,&temp);
  108698. /* skip */
  108699. ogg_sync_pageout(&oy,&temp);
  108700. ogg_stream_pagein(&os_de,&temp);
  108701. /* do we get the expected results/packets? */
  108702. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  108703. checkpacket(&test,0,0,0);
  108704. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  108705. checkpacket(&test,100,1,-1);
  108706. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  108707. checkpacket(&test,4079,2,3000);
  108708. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  108709. checkpacket(&test,2956,3,4000);
  108710. if(ogg_stream_packetout(&os_de,&test)!=-1){
  108711. fprintf(stderr,"Error: loss of page did not return error\n");
  108712. exit(1);
  108713. }
  108714. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  108715. checkpacket(&test,300,13,14000);
  108716. fprintf(stderr,"ok.\n");
  108717. }
  108718. /* the rest only test sync */
  108719. {
  108720. ogg_page og_de;
  108721. /* Test fractional page inputs: incomplete capture */
  108722. fprintf(stderr,"Testing sync on partial inputs... ");
  108723. ogg_sync_reset(&oy);
  108724. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  108725. 3);
  108726. ogg_sync_wrote(&oy,3);
  108727. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  108728. /* Test fractional page inputs: incomplete fixed header */
  108729. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+3,
  108730. 20);
  108731. ogg_sync_wrote(&oy,20);
  108732. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  108733. /* Test fractional page inputs: incomplete header */
  108734. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+23,
  108735. 5);
  108736. ogg_sync_wrote(&oy,5);
  108737. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  108738. /* Test fractional page inputs: incomplete body */
  108739. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+28,
  108740. og[1].header_len-28);
  108741. ogg_sync_wrote(&oy,og[1].header_len-28);
  108742. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  108743. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,1000);
  108744. ogg_sync_wrote(&oy,1000);
  108745. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  108746. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body+1000,
  108747. og[1].body_len-1000);
  108748. ogg_sync_wrote(&oy,og[1].body_len-1000);
  108749. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  108750. fprintf(stderr,"ok.\n");
  108751. }
  108752. /* Test fractional page inputs: page + incomplete capture */
  108753. {
  108754. ogg_page og_de;
  108755. fprintf(stderr,"Testing sync on 1+partial inputs... ");
  108756. ogg_sync_reset(&oy);
  108757. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  108758. og[1].header_len);
  108759. ogg_sync_wrote(&oy,og[1].header_len);
  108760. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  108761. og[1].body_len);
  108762. ogg_sync_wrote(&oy,og[1].body_len);
  108763. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  108764. 20);
  108765. ogg_sync_wrote(&oy,20);
  108766. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  108767. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  108768. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+20,
  108769. og[1].header_len-20);
  108770. ogg_sync_wrote(&oy,og[1].header_len-20);
  108771. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  108772. og[1].body_len);
  108773. ogg_sync_wrote(&oy,og[1].body_len);
  108774. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  108775. fprintf(stderr,"ok.\n");
  108776. }
  108777. /* Test recapture: garbage + page */
  108778. {
  108779. ogg_page og_de;
  108780. fprintf(stderr,"Testing search for capture... ");
  108781. ogg_sync_reset(&oy);
  108782. /* 'garbage' */
  108783. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  108784. og[1].body_len);
  108785. ogg_sync_wrote(&oy,og[1].body_len);
  108786. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  108787. og[1].header_len);
  108788. ogg_sync_wrote(&oy,og[1].header_len);
  108789. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  108790. og[1].body_len);
  108791. ogg_sync_wrote(&oy,og[1].body_len);
  108792. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  108793. 20);
  108794. ogg_sync_wrote(&oy,20);
  108795. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  108796. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  108797. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  108798. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header+20,
  108799. og[2].header_len-20);
  108800. ogg_sync_wrote(&oy,og[2].header_len-20);
  108801. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  108802. og[2].body_len);
  108803. ogg_sync_wrote(&oy,og[2].body_len);
  108804. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  108805. fprintf(stderr,"ok.\n");
  108806. }
  108807. /* Test recapture: page + garbage + page */
  108808. {
  108809. ogg_page og_de;
  108810. fprintf(stderr,"Testing recapture... ");
  108811. ogg_sync_reset(&oy);
  108812. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  108813. og[1].header_len);
  108814. ogg_sync_wrote(&oy,og[1].header_len);
  108815. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  108816. og[1].body_len);
  108817. ogg_sync_wrote(&oy,og[1].body_len);
  108818. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  108819. og[2].header_len);
  108820. ogg_sync_wrote(&oy,og[2].header_len);
  108821. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  108822. og[2].header_len);
  108823. ogg_sync_wrote(&oy,og[2].header_len);
  108824. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  108825. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  108826. og[2].body_len-5);
  108827. ogg_sync_wrote(&oy,og[2].body_len-5);
  108828. memcpy(ogg_sync_buffer(&oy,og[3].header_len),og[3].header,
  108829. og[3].header_len);
  108830. ogg_sync_wrote(&oy,og[3].header_len);
  108831. memcpy(ogg_sync_buffer(&oy,og[3].body_len),og[3].body,
  108832. og[3].body_len);
  108833. ogg_sync_wrote(&oy,og[3].body_len);
  108834. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  108835. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  108836. fprintf(stderr,"ok.\n");
  108837. }
  108838. /* Free page data that was previously copied */
  108839. {
  108840. for(i=0;i<5;i++){
  108841. free_page(&og[i]);
  108842. }
  108843. }
  108844. }
  108845. return(0);
  108846. }
  108847. #endif
  108848. #endif
  108849. /*** End of inlined file: framing.c ***/
  108850. /*** Start of inlined file: analysis.c ***/
  108851. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  108852. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  108853. // tasks..
  108854. #if JUCE_MSVC
  108855. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  108856. #endif
  108857. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  108858. #if JUCE_USE_OGGVORBIS
  108859. #include <stdio.h>
  108860. #include <string.h>
  108861. #include <math.h>
  108862. /*** Start of inlined file: codec_internal.h ***/
  108863. #ifndef _V_CODECI_H_
  108864. #define _V_CODECI_H_
  108865. /*** Start of inlined file: envelope.h ***/
  108866. #ifndef _V_ENVELOPE_
  108867. #define _V_ENVELOPE_
  108868. /*** Start of inlined file: mdct.h ***/
  108869. #ifndef _OGG_mdct_H_
  108870. #define _OGG_mdct_H_
  108871. /*#define MDCT_INTEGERIZED <- be warned there could be some hurt left here*/
  108872. #ifdef MDCT_INTEGERIZED
  108873. #define DATA_TYPE int
  108874. #define REG_TYPE register int
  108875. #define TRIGBITS 14
  108876. #define cPI3_8 6270
  108877. #define cPI2_8 11585
  108878. #define cPI1_8 15137
  108879. #define FLOAT_CONV(x) ((int)((x)*(1<<TRIGBITS)+.5))
  108880. #define MULT_NORM(x) ((x)>>TRIGBITS)
  108881. #define HALVE(x) ((x)>>1)
  108882. #else
  108883. #define DATA_TYPE float
  108884. #define REG_TYPE float
  108885. #define cPI3_8 .38268343236508977175F
  108886. #define cPI2_8 .70710678118654752441F
  108887. #define cPI1_8 .92387953251128675613F
  108888. #define FLOAT_CONV(x) (x)
  108889. #define MULT_NORM(x) (x)
  108890. #define HALVE(x) ((x)*.5f)
  108891. #endif
  108892. typedef struct {
  108893. int n;
  108894. int log2n;
  108895. DATA_TYPE *trig;
  108896. int *bitrev;
  108897. DATA_TYPE scale;
  108898. } mdct_lookup;
  108899. extern void mdct_init(mdct_lookup *lookup,int n);
  108900. extern void mdct_clear(mdct_lookup *l);
  108901. extern void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  108902. extern void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  108903. #endif
  108904. /*** End of inlined file: mdct.h ***/
  108905. #define VE_PRE 16
  108906. #define VE_WIN 4
  108907. #define VE_POST 2
  108908. #define VE_AMP (VE_PRE+VE_POST-1)
  108909. #define VE_BANDS 7
  108910. #define VE_NEARDC 15
  108911. #define VE_MINSTRETCH 2 /* a bit less than short block */
  108912. #define VE_MAXSTRETCH 12 /* one-third full block */
  108913. typedef struct {
  108914. float ampbuf[VE_AMP];
  108915. int ampptr;
  108916. float nearDC[VE_NEARDC];
  108917. float nearDC_acc;
  108918. float nearDC_partialacc;
  108919. int nearptr;
  108920. } envelope_filter_state;
  108921. typedef struct {
  108922. int begin;
  108923. int end;
  108924. float *window;
  108925. float total;
  108926. } envelope_band;
  108927. typedef struct {
  108928. int ch;
  108929. int winlength;
  108930. int searchstep;
  108931. float minenergy;
  108932. mdct_lookup mdct;
  108933. float *mdct_win;
  108934. envelope_band band[VE_BANDS];
  108935. envelope_filter_state *filter;
  108936. int stretch;
  108937. int *mark;
  108938. long storage;
  108939. long current;
  108940. long curmark;
  108941. long cursor;
  108942. } envelope_lookup;
  108943. extern void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi);
  108944. extern void _ve_envelope_clear(envelope_lookup *e);
  108945. extern long _ve_envelope_search(vorbis_dsp_state *v);
  108946. extern void _ve_envelope_shift(envelope_lookup *e,long shift);
  108947. extern int _ve_envelope_mark(vorbis_dsp_state *v);
  108948. #endif
  108949. /*** End of inlined file: envelope.h ***/
  108950. /*** Start of inlined file: codebook.h ***/
  108951. #ifndef _V_CODEBOOK_H_
  108952. #define _V_CODEBOOK_H_
  108953. /* This structure encapsulates huffman and VQ style encoding books; it
  108954. doesn't do anything specific to either.
  108955. valuelist/quantlist are nonNULL (and q_* significant) only if
  108956. there's entry->value mapping to be done.
  108957. If encode-side mapping must be done (and thus the entry needs to be
  108958. hunted), the auxiliary encode pointer will point to a decision
  108959. tree. This is true of both VQ and huffman, but is mostly useful
  108960. with VQ.
  108961. */
  108962. typedef struct static_codebook{
  108963. long dim; /* codebook dimensions (elements per vector) */
  108964. long entries; /* codebook entries */
  108965. long *lengthlist; /* codeword lengths in bits */
  108966. /* mapping ***************************************************************/
  108967. int maptype; /* 0=none
  108968. 1=implicitly populated values from map column
  108969. 2=listed arbitrary values */
  108970. /* The below does a linear, single monotonic sequence mapping. */
  108971. long q_min; /* packed 32 bit float; quant value 0 maps to minval */
  108972. long q_delta; /* packed 32 bit float; val 1 - val 0 == delta */
  108973. int q_quant; /* bits: 0 < quant <= 16 */
  108974. int q_sequencep; /* bitflag */
  108975. long *quantlist; /* map == 1: (int)(entries^(1/dim)) element column map
  108976. map == 2: list of dim*entries quantized entry vals
  108977. */
  108978. /* encode helpers ********************************************************/
  108979. struct encode_aux_nearestmatch *nearest_tree;
  108980. struct encode_aux_threshmatch *thresh_tree;
  108981. struct encode_aux_pigeonhole *pigeon_tree;
  108982. int allocedp;
  108983. } static_codebook;
  108984. /* this structures an arbitrary trained book to quickly find the
  108985. nearest cell match */
  108986. typedef struct encode_aux_nearestmatch{
  108987. /* pre-calculated partitioning tree */
  108988. long *ptr0;
  108989. long *ptr1;
  108990. long *p; /* decision points (each is an entry) */
  108991. long *q; /* decision points (each is an entry) */
  108992. long aux; /* number of tree entries */
  108993. long alloc;
  108994. } encode_aux_nearestmatch;
  108995. /* assumes a maptype of 1; encode side only, so that's OK */
  108996. typedef struct encode_aux_threshmatch{
  108997. float *quantthresh;
  108998. long *quantmap;
  108999. int quantvals;
  109000. int threshvals;
  109001. } encode_aux_threshmatch;
  109002. typedef struct encode_aux_pigeonhole{
  109003. float min;
  109004. float del;
  109005. int mapentries;
  109006. int quantvals;
  109007. long *pigeonmap;
  109008. long fittotal;
  109009. long *fitlist;
  109010. long *fitmap;
  109011. long *fitlength;
  109012. } encode_aux_pigeonhole;
  109013. typedef struct codebook{
  109014. long dim; /* codebook dimensions (elements per vector) */
  109015. long entries; /* codebook entries */
  109016. long used_entries; /* populated codebook entries */
  109017. const static_codebook *c;
  109018. /* for encode, the below are entry-ordered, fully populated */
  109019. /* for decode, the below are ordered by bitreversed codeword and only
  109020. used entries are populated */
  109021. float *valuelist; /* list of dim*entries actual entry values */
  109022. ogg_uint32_t *codelist; /* list of bitstream codewords for each entry */
  109023. int *dec_index; /* only used if sparseness collapsed */
  109024. char *dec_codelengths;
  109025. ogg_uint32_t *dec_firsttable;
  109026. int dec_firsttablen;
  109027. int dec_maxlength;
  109028. } codebook;
  109029. extern void vorbis_staticbook_clear(static_codebook *b);
  109030. extern void vorbis_staticbook_destroy(static_codebook *b);
  109031. extern int vorbis_book_init_encode(codebook *dest,const static_codebook *source);
  109032. extern int vorbis_book_init_decode(codebook *dest,const static_codebook *source);
  109033. extern void vorbis_book_clear(codebook *b);
  109034. extern float *_book_unquantize(const static_codebook *b,int n,int *map);
  109035. extern float *_book_logdist(const static_codebook *b,float *vals);
  109036. extern float _float32_unpack(long val);
  109037. extern long _float32_pack(float val);
  109038. extern int _best(codebook *book, float *a, int step);
  109039. extern int _ilog(unsigned int v);
  109040. extern long _book_maptype1_quantvals(const static_codebook *b);
  109041. extern int vorbis_book_besterror(codebook *book,float *a,int step,int addmul);
  109042. extern long vorbis_book_codeword(codebook *book,int entry);
  109043. extern long vorbis_book_codelen(codebook *book,int entry);
  109044. extern int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *b);
  109045. extern int vorbis_staticbook_unpack(oggpack_buffer *b,static_codebook *c);
  109046. extern int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b);
  109047. extern int vorbis_book_errorv(codebook *book, float *a);
  109048. extern int vorbis_book_encodev(codebook *book, int best,float *a,
  109049. oggpack_buffer *b);
  109050. extern long vorbis_book_decode(codebook *book, oggpack_buffer *b);
  109051. extern long vorbis_book_decodevs_add(codebook *book, float *a,
  109052. oggpack_buffer *b,int n);
  109053. extern long vorbis_book_decodev_set(codebook *book, float *a,
  109054. oggpack_buffer *b,int n);
  109055. extern long vorbis_book_decodev_add(codebook *book, float *a,
  109056. oggpack_buffer *b,int n);
  109057. extern long vorbis_book_decodevv_add(codebook *book, float **a,
  109058. long off,int ch,
  109059. oggpack_buffer *b,int n);
  109060. #endif
  109061. /*** End of inlined file: codebook.h ***/
  109062. #define BLOCKTYPE_IMPULSE 0
  109063. #define BLOCKTYPE_PADDING 1
  109064. #define BLOCKTYPE_TRANSITION 0
  109065. #define BLOCKTYPE_LONG 1
  109066. #define PACKETBLOBS 15
  109067. typedef struct vorbis_block_internal{
  109068. float **pcmdelay; /* this is a pointer into local storage */
  109069. float ampmax;
  109070. int blocktype;
  109071. oggpack_buffer *packetblob[PACKETBLOBS]; /* initialized, must be freed;
  109072. blob [PACKETBLOBS/2] points to
  109073. the oggpack_buffer in the
  109074. main vorbis_block */
  109075. } vorbis_block_internal;
  109076. typedef void vorbis_look_floor;
  109077. typedef void vorbis_look_residue;
  109078. typedef void vorbis_look_transform;
  109079. /* mode ************************************************************/
  109080. typedef struct {
  109081. int blockflag;
  109082. int windowtype;
  109083. int transformtype;
  109084. int mapping;
  109085. } vorbis_info_mode;
  109086. typedef void vorbis_info_floor;
  109087. typedef void vorbis_info_residue;
  109088. typedef void vorbis_info_mapping;
  109089. /*** Start of inlined file: psy.h ***/
  109090. #ifndef _V_PSY_H_
  109091. #define _V_PSY_H_
  109092. /*** Start of inlined file: smallft.h ***/
  109093. #ifndef _V_SMFT_H_
  109094. #define _V_SMFT_H_
  109095. typedef struct {
  109096. int n;
  109097. float *trigcache;
  109098. int *splitcache;
  109099. } drft_lookup;
  109100. extern void drft_forward(drft_lookup *l,float *data);
  109101. extern void drft_backward(drft_lookup *l,float *data);
  109102. extern void drft_init(drft_lookup *l,int n);
  109103. extern void drft_clear(drft_lookup *l);
  109104. #endif
  109105. /*** End of inlined file: smallft.h ***/
  109106. /*** Start of inlined file: backends.h ***/
  109107. /* this is exposed up here because we need it for static modes.
  109108. Lookups for each backend aren't exposed because there's no reason
  109109. to do so */
  109110. #ifndef _vorbis_backend_h_
  109111. #define _vorbis_backend_h_
  109112. /* this would all be simpler/shorter with templates, but.... */
  109113. /* Floor backend generic *****************************************/
  109114. typedef struct{
  109115. void (*pack) (vorbis_info_floor *,oggpack_buffer *);
  109116. vorbis_info_floor *(*unpack)(vorbis_info *,oggpack_buffer *);
  109117. vorbis_look_floor *(*look) (vorbis_dsp_state *,vorbis_info_floor *);
  109118. void (*free_info) (vorbis_info_floor *);
  109119. void (*free_look) (vorbis_look_floor *);
  109120. void *(*inverse1) (struct vorbis_block *,vorbis_look_floor *);
  109121. int (*inverse2) (struct vorbis_block *,vorbis_look_floor *,
  109122. void *buffer,float *);
  109123. } vorbis_func_floor;
  109124. typedef struct{
  109125. int order;
  109126. long rate;
  109127. long barkmap;
  109128. int ampbits;
  109129. int ampdB;
  109130. int numbooks; /* <= 16 */
  109131. int books[16];
  109132. float lessthan; /* encode-only config setting hacks for libvorbis */
  109133. float greaterthan; /* encode-only config setting hacks for libvorbis */
  109134. } vorbis_info_floor0;
  109135. #define VIF_POSIT 63
  109136. #define VIF_CLASS 16
  109137. #define VIF_PARTS 31
  109138. typedef struct{
  109139. int partitions; /* 0 to 31 */
  109140. int partitionclass[VIF_PARTS]; /* 0 to 15 */
  109141. int class_dim[VIF_CLASS]; /* 1 to 8 */
  109142. int class_subs[VIF_CLASS]; /* 0,1,2,3 (bits: 1<<n poss) */
  109143. int class_book[VIF_CLASS]; /* subs ^ dim entries */
  109144. int class_subbook[VIF_CLASS][8]; /* [VIF_CLASS][subs] */
  109145. int mult; /* 1 2 3 or 4 */
  109146. int postlist[VIF_POSIT+2]; /* first two implicit */
  109147. /* encode side analysis parameters */
  109148. float maxover;
  109149. float maxunder;
  109150. float maxerr;
  109151. float twofitweight;
  109152. float twofitatten;
  109153. int n;
  109154. } vorbis_info_floor1;
  109155. /* Residue backend generic *****************************************/
  109156. typedef struct{
  109157. void (*pack) (vorbis_info_residue *,oggpack_buffer *);
  109158. vorbis_info_residue *(*unpack)(vorbis_info *,oggpack_buffer *);
  109159. vorbis_look_residue *(*look) (vorbis_dsp_state *,
  109160. vorbis_info_residue *);
  109161. void (*free_info) (vorbis_info_residue *);
  109162. void (*free_look) (vorbis_look_residue *);
  109163. long **(*classx) (struct vorbis_block *,vorbis_look_residue *,
  109164. float **,int *,int);
  109165. int (*forward) (oggpack_buffer *,struct vorbis_block *,
  109166. vorbis_look_residue *,
  109167. float **,float **,int *,int,long **);
  109168. int (*inverse) (struct vorbis_block *,vorbis_look_residue *,
  109169. float **,int *,int);
  109170. } vorbis_func_residue;
  109171. typedef struct vorbis_info_residue0{
  109172. /* block-partitioned VQ coded straight residue */
  109173. long begin;
  109174. long end;
  109175. /* first stage (lossless partitioning) */
  109176. int grouping; /* group n vectors per partition */
  109177. int partitions; /* possible codebooks for a partition */
  109178. int groupbook; /* huffbook for partitioning */
  109179. int secondstages[64]; /* expanded out to pointers in lookup */
  109180. int booklist[256]; /* list of second stage books */
  109181. float classmetric1[64];
  109182. float classmetric2[64];
  109183. } vorbis_info_residue0;
  109184. /* Mapping backend generic *****************************************/
  109185. typedef struct{
  109186. void (*pack) (vorbis_info *,vorbis_info_mapping *,
  109187. oggpack_buffer *);
  109188. vorbis_info_mapping *(*unpack)(vorbis_info *,oggpack_buffer *);
  109189. void (*free_info) (vorbis_info_mapping *);
  109190. int (*forward) (struct vorbis_block *vb);
  109191. int (*inverse) (struct vorbis_block *vb,vorbis_info_mapping *);
  109192. } vorbis_func_mapping;
  109193. typedef struct vorbis_info_mapping0{
  109194. int submaps; /* <= 16 */
  109195. int chmuxlist[256]; /* up to 256 channels in a Vorbis stream */
  109196. int floorsubmap[16]; /* [mux] submap to floors */
  109197. int residuesubmap[16]; /* [mux] submap to residue */
  109198. int coupling_steps;
  109199. int coupling_mag[256];
  109200. int coupling_ang[256];
  109201. } vorbis_info_mapping0;
  109202. #endif
  109203. /*** End of inlined file: backends.h ***/
  109204. #ifndef EHMER_MAX
  109205. #define EHMER_MAX 56
  109206. #endif
  109207. /* psychoacoustic setup ********************************************/
  109208. #define P_BANDS 17 /* 62Hz to 16kHz */
  109209. #define P_LEVELS 8 /* 30dB to 100dB */
  109210. #define P_LEVEL_0 30. /* 30 dB */
  109211. #define P_NOISECURVES 3
  109212. #define NOISE_COMPAND_LEVELS 40
  109213. typedef struct vorbis_info_psy{
  109214. int blockflag;
  109215. float ath_adjatt;
  109216. float ath_maxatt;
  109217. float tone_masteratt[P_NOISECURVES];
  109218. float tone_centerboost;
  109219. float tone_decay;
  109220. float tone_abs_limit;
  109221. float toneatt[P_BANDS];
  109222. int noisemaskp;
  109223. float noisemaxsupp;
  109224. float noisewindowlo;
  109225. float noisewindowhi;
  109226. int noisewindowlomin;
  109227. int noisewindowhimin;
  109228. int noisewindowfixed;
  109229. float noiseoff[P_NOISECURVES][P_BANDS];
  109230. float noisecompand[NOISE_COMPAND_LEVELS];
  109231. float max_curve_dB;
  109232. int normal_channel_p;
  109233. int normal_point_p;
  109234. int normal_start;
  109235. int normal_partition;
  109236. double normal_thresh;
  109237. } vorbis_info_psy;
  109238. typedef struct{
  109239. int eighth_octave_lines;
  109240. /* for block long/short tuning; encode only */
  109241. float preecho_thresh[VE_BANDS];
  109242. float postecho_thresh[VE_BANDS];
  109243. float stretch_penalty;
  109244. float preecho_minenergy;
  109245. float ampmax_att_per_sec;
  109246. /* channel coupling config */
  109247. int coupling_pkHz[PACKETBLOBS];
  109248. int coupling_pointlimit[2][PACKETBLOBS];
  109249. int coupling_prepointamp[PACKETBLOBS];
  109250. int coupling_postpointamp[PACKETBLOBS];
  109251. int sliding_lowpass[2][PACKETBLOBS];
  109252. } vorbis_info_psy_global;
  109253. typedef struct {
  109254. float ampmax;
  109255. int channels;
  109256. vorbis_info_psy_global *gi;
  109257. int coupling_pointlimit[2][P_NOISECURVES];
  109258. } vorbis_look_psy_global;
  109259. typedef struct {
  109260. int n;
  109261. struct vorbis_info_psy *vi;
  109262. float ***tonecurves;
  109263. float **noiseoffset;
  109264. float *ath;
  109265. long *octave; /* in n.ocshift format */
  109266. long *bark;
  109267. long firstoc;
  109268. long shiftoc;
  109269. int eighth_octave_lines; /* power of two, please */
  109270. int total_octave_lines;
  109271. long rate; /* cache it */
  109272. float m_val; /* Masking compensation value */
  109273. } vorbis_look_psy;
  109274. extern void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  109275. vorbis_info_psy_global *gi,int n,long rate);
  109276. extern void _vp_psy_clear(vorbis_look_psy *p);
  109277. extern void *_vi_psy_dup(void *source);
  109278. extern void _vi_psy_free(vorbis_info_psy *i);
  109279. extern vorbis_info_psy *_vi_psy_copy(vorbis_info_psy *i);
  109280. extern void _vp_remove_floor(vorbis_look_psy *p,
  109281. float *mdct,
  109282. int *icodedflr,
  109283. float *residue,
  109284. int sliding_lowpass);
  109285. extern void _vp_noisemask(vorbis_look_psy *p,
  109286. float *logmdct,
  109287. float *logmask);
  109288. extern void _vp_tonemask(vorbis_look_psy *p,
  109289. float *logfft,
  109290. float *logmask,
  109291. float global_specmax,
  109292. float local_specmax);
  109293. extern void _vp_offset_and_mix(vorbis_look_psy *p,
  109294. float *noise,
  109295. float *tone,
  109296. int offset_select,
  109297. float *logmask,
  109298. float *mdct,
  109299. float *logmdct);
  109300. extern float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd);
  109301. extern float **_vp_quantize_couple_memo(vorbis_block *vb,
  109302. vorbis_info_psy_global *g,
  109303. vorbis_look_psy *p,
  109304. vorbis_info_mapping0 *vi,
  109305. float **mdct);
  109306. extern void _vp_couple(int blobno,
  109307. vorbis_info_psy_global *g,
  109308. vorbis_look_psy *p,
  109309. vorbis_info_mapping0 *vi,
  109310. float **res,
  109311. float **mag_memo,
  109312. int **mag_sort,
  109313. int **ifloor,
  109314. int *nonzero,
  109315. int sliding_lowpass);
  109316. extern void _vp_noise_normalize(vorbis_look_psy *p,
  109317. float *in,float *out,int *sortedindex);
  109318. extern void _vp_noise_normalize_sort(vorbis_look_psy *p,
  109319. float *magnitudes,int *sortedindex);
  109320. extern int **_vp_quantize_couple_sort(vorbis_block *vb,
  109321. vorbis_look_psy *p,
  109322. vorbis_info_mapping0 *vi,
  109323. float **mags);
  109324. extern void hf_reduction(vorbis_info_psy_global *g,
  109325. vorbis_look_psy *p,
  109326. vorbis_info_mapping0 *vi,
  109327. float **mdct);
  109328. #endif
  109329. /*** End of inlined file: psy.h ***/
  109330. /*** Start of inlined file: bitrate.h ***/
  109331. #ifndef _V_BITRATE_H_
  109332. #define _V_BITRATE_H_
  109333. /*** Start of inlined file: os.h ***/
  109334. #ifndef _OS_H
  109335. #define _OS_H
  109336. /********************************************************************
  109337. * *
  109338. * THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. *
  109339. * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
  109340. * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
  109341. * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
  109342. * *
  109343. * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2002 *
  109344. * by the XIPHOPHORUS Company http://www.xiph.org/ *
  109345. * *
  109346. ********************************************************************
  109347. function: #ifdef jail to whip a few platforms into the UNIX ideal.
  109348. last mod: $Id: os.h,v 1.1 2007/06/07 17:49:18 jules_rms Exp $
  109349. ********************************************************************/
  109350. #ifdef HAVE_CONFIG_H
  109351. #include "config.h"
  109352. #endif
  109353. #include <math.h>
  109354. /*** Start of inlined file: misc.h ***/
  109355. #ifndef _V_RANDOM_H_
  109356. #define _V_RANDOM_H_
  109357. extern int analysis_noisy;
  109358. extern void *_vorbis_block_alloc(vorbis_block *vb,long bytes);
  109359. extern void _vorbis_block_ripcord(vorbis_block *vb);
  109360. extern void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  109361. ogg_int64_t off);
  109362. #ifdef DEBUG_MALLOC
  109363. #define _VDBG_GRAPHFILE "malloc.m"
  109364. extern void *_VDBG_malloc(void *ptr,long bytes,char *file,long line);
  109365. extern void _VDBG_free(void *ptr,char *file,long line);
  109366. #ifndef MISC_C
  109367. #undef _ogg_malloc
  109368. #undef _ogg_calloc
  109369. #undef _ogg_realloc
  109370. #undef _ogg_free
  109371. #define _ogg_malloc(x) _VDBG_malloc(NULL,(x),__FILE__,__LINE__)
  109372. #define _ogg_calloc(x,y) _VDBG_malloc(NULL,(x)*(y),__FILE__,__LINE__)
  109373. #define _ogg_realloc(x,y) _VDBG_malloc((x),(y),__FILE__,__LINE__)
  109374. #define _ogg_free(x) _VDBG_free((x),__FILE__,__LINE__)
  109375. #endif
  109376. #endif
  109377. #endif
  109378. /*** End of inlined file: misc.h ***/
  109379. #ifndef _V_IFDEFJAIL_H_
  109380. # define _V_IFDEFJAIL_H_
  109381. # ifdef __GNUC__
  109382. # define STIN static __inline__
  109383. # elif _WIN32
  109384. # define STIN static __inline
  109385. # else
  109386. # define STIN static
  109387. # endif
  109388. #ifdef DJGPP
  109389. # define rint(x) (floor((x)+0.5f))
  109390. #endif
  109391. #ifndef M_PI
  109392. # define M_PI (3.1415926536f)
  109393. #endif
  109394. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  109395. # include <malloc.h>
  109396. # define rint(x) (floor((x)+0.5f))
  109397. # define NO_FLOAT_MATH_LIB
  109398. # define FAST_HYPOT(a, b) sqrt((a)*(a) + (b)*(b))
  109399. #endif
  109400. #if defined(__SYMBIAN32__) && defined(__WINS__)
  109401. void *_alloca(size_t size);
  109402. # define alloca _alloca
  109403. #endif
  109404. #ifndef FAST_HYPOT
  109405. # define FAST_HYPOT hypot
  109406. #endif
  109407. #endif
  109408. #ifdef HAVE_ALLOCA_H
  109409. # include <alloca.h>
  109410. #endif
  109411. #ifdef USE_MEMORY_H
  109412. # include <memory.h>
  109413. #endif
  109414. #ifndef min
  109415. # define min(x,y) ((x)>(y)?(y):(x))
  109416. #endif
  109417. #ifndef max
  109418. # define max(x,y) ((x)<(y)?(y):(x))
  109419. #endif
  109420. #if defined(__i386__) && defined(__GNUC__) && !defined(__BEOS__)
  109421. # define VORBIS_FPU_CONTROL
  109422. /* both GCC and MSVC are kinda stupid about rounding/casting to int.
  109423. Because of encapsulation constraints (GCC can't see inside the asm
  109424. block and so we end up doing stupid things like a store/load that
  109425. is collectively a noop), we do it this way */
  109426. /* we must set up the fpu before this works!! */
  109427. typedef ogg_int16_t vorbis_fpu_control;
  109428. static inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  109429. ogg_int16_t ret;
  109430. ogg_int16_t temp;
  109431. __asm__ __volatile__("fnstcw %0\n\t"
  109432. "movw %0,%%dx\n\t"
  109433. "orw $62463,%%dx\n\t"
  109434. "movw %%dx,%1\n\t"
  109435. "fldcw %1\n\t":"=m"(ret):"m"(temp): "dx");
  109436. *fpu=ret;
  109437. }
  109438. static inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  109439. __asm__ __volatile__("fldcw %0":: "m"(fpu));
  109440. }
  109441. /* assumes the FPU is in round mode! */
  109442. static inline int vorbis_ftoi(double f){ /* yes, double! Otherwise,
  109443. we get extra fst/fld to
  109444. truncate precision */
  109445. int i;
  109446. __asm__("fistl %0": "=m"(i) : "t"(f));
  109447. return(i);
  109448. }
  109449. #endif
  109450. #if defined(_WIN32) && defined(_X86_) && !defined(__GNUC__) && !defined(__BORLANDC__)
  109451. # define VORBIS_FPU_CONTROL
  109452. typedef ogg_int16_t vorbis_fpu_control;
  109453. static __inline int vorbis_ftoi(double f){
  109454. int i;
  109455. __asm{
  109456. fld f
  109457. fistp i
  109458. }
  109459. return i;
  109460. }
  109461. static __inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  109462. }
  109463. static __inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  109464. }
  109465. #endif
  109466. #ifndef VORBIS_FPU_CONTROL
  109467. typedef int vorbis_fpu_control;
  109468. static int vorbis_ftoi(double f){
  109469. return (int)(f+.5);
  109470. }
  109471. /* We don't have special code for this compiler/arch, so do it the slow way */
  109472. # define vorbis_fpu_setround(vorbis_fpu_control) {}
  109473. # define vorbis_fpu_restore(vorbis_fpu_control) {}
  109474. #endif
  109475. #endif /* _OS_H */
  109476. /*** End of inlined file: os.h ***/
  109477. /* encode side bitrate tracking */
  109478. typedef struct bitrate_manager_state {
  109479. int managed;
  109480. long avg_reservoir;
  109481. long minmax_reservoir;
  109482. long avg_bitsper;
  109483. long min_bitsper;
  109484. long max_bitsper;
  109485. long short_per_long;
  109486. double avgfloat;
  109487. vorbis_block *vb;
  109488. int choice;
  109489. } bitrate_manager_state;
  109490. typedef struct bitrate_manager_info{
  109491. long avg_rate;
  109492. long min_rate;
  109493. long max_rate;
  109494. long reservoir_bits;
  109495. double reservoir_bias;
  109496. double slew_damp;
  109497. } bitrate_manager_info;
  109498. extern void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bs);
  109499. extern void vorbis_bitrate_clear(bitrate_manager_state *bs);
  109500. extern int vorbis_bitrate_managed(vorbis_block *vb);
  109501. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  109502. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd, ogg_packet *op);
  109503. #endif
  109504. /*** End of inlined file: bitrate.h ***/
  109505. static int ilog(unsigned int v){
  109506. int ret=0;
  109507. while(v){
  109508. ret++;
  109509. v>>=1;
  109510. }
  109511. return(ret);
  109512. }
  109513. static int ilog2(unsigned int v){
  109514. int ret=0;
  109515. if(v)--v;
  109516. while(v){
  109517. ret++;
  109518. v>>=1;
  109519. }
  109520. return(ret);
  109521. }
  109522. typedef struct private_state {
  109523. /* local lookup storage */
  109524. envelope_lookup *ve; /* envelope lookup */
  109525. int window[2];
  109526. vorbis_look_transform **transform[2]; /* block, type */
  109527. drft_lookup fft_look[2];
  109528. int modebits;
  109529. vorbis_look_floor **flr;
  109530. vorbis_look_residue **residue;
  109531. vorbis_look_psy *psy;
  109532. vorbis_look_psy_global *psy_g_look;
  109533. /* local storage, only used on the encoding side. This way the
  109534. application does not need to worry about freeing some packets'
  109535. memory and not others'; packet storage is always tracked.
  109536. Cleared next call to a _dsp_ function */
  109537. unsigned char *header;
  109538. unsigned char *header1;
  109539. unsigned char *header2;
  109540. bitrate_manager_state bms;
  109541. ogg_int64_t sample_count;
  109542. } private_state;
  109543. /* codec_setup_info contains all the setup information specific to the
  109544. specific compression/decompression mode in progress (eg,
  109545. psychoacoustic settings, channel setup, options, codebook
  109546. etc).
  109547. *********************************************************************/
  109548. /*** Start of inlined file: highlevel.h ***/
  109549. typedef struct highlevel_byblocktype {
  109550. double tone_mask_setting;
  109551. double tone_peaklimit_setting;
  109552. double noise_bias_setting;
  109553. double noise_compand_setting;
  109554. } highlevel_byblocktype;
  109555. typedef struct highlevel_encode_setup {
  109556. void *setup;
  109557. int set_in_stone;
  109558. double base_setting;
  109559. double long_setting;
  109560. double short_setting;
  109561. double impulse_noisetune;
  109562. int managed;
  109563. long bitrate_min;
  109564. long bitrate_av;
  109565. double bitrate_av_damp;
  109566. long bitrate_max;
  109567. long bitrate_reservoir;
  109568. double bitrate_reservoir_bias;
  109569. int impulse_block_p;
  109570. int noise_normalize_p;
  109571. double stereo_point_setting;
  109572. double lowpass_kHz;
  109573. double ath_floating_dB;
  109574. double ath_absolute_dB;
  109575. double amplitude_track_dBpersec;
  109576. double trigger_setting;
  109577. highlevel_byblocktype block[4]; /* padding, impulse, transition, long */
  109578. } highlevel_encode_setup;
  109579. /*** End of inlined file: highlevel.h ***/
  109580. typedef struct codec_setup_info {
  109581. /* Vorbis supports only short and long blocks, but allows the
  109582. encoder to choose the sizes */
  109583. long blocksizes[2];
  109584. /* modes are the primary means of supporting on-the-fly different
  109585. blocksizes, different channel mappings (LR or M/A),
  109586. different residue backends, etc. Each mode consists of a
  109587. blocksize flag and a mapping (along with the mapping setup */
  109588. int modes;
  109589. int maps;
  109590. int floors;
  109591. int residues;
  109592. int books;
  109593. int psys; /* encode only */
  109594. vorbis_info_mode *mode_param[64];
  109595. int map_type[64];
  109596. vorbis_info_mapping *map_param[64];
  109597. int floor_type[64];
  109598. vorbis_info_floor *floor_param[64];
  109599. int residue_type[64];
  109600. vorbis_info_residue *residue_param[64];
  109601. static_codebook *book_param[256];
  109602. codebook *fullbooks;
  109603. vorbis_info_psy *psy_param[4]; /* encode only */
  109604. vorbis_info_psy_global psy_g_param;
  109605. bitrate_manager_info bi;
  109606. highlevel_encode_setup hi; /* used only by vorbisenc.c. It's a
  109607. highly redundant structure, but
  109608. improves clarity of program flow. */
  109609. int halfrate_flag; /* painless downsample for decode */
  109610. } codec_setup_info;
  109611. extern vorbis_look_psy_global *_vp_global_look(vorbis_info *vi);
  109612. extern void _vp_global_free(vorbis_look_psy_global *look);
  109613. #endif
  109614. /*** End of inlined file: codec_internal.h ***/
  109615. /*** Start of inlined file: registry.h ***/
  109616. #ifndef _V_REG_H_
  109617. #define _V_REG_H_
  109618. #define VI_TRANSFORMB 1
  109619. #define VI_WINDOWB 1
  109620. #define VI_TIMEB 1
  109621. #define VI_FLOORB 2
  109622. #define VI_RESB 3
  109623. #define VI_MAPB 1
  109624. extern vorbis_func_floor *_floor_P[];
  109625. extern vorbis_func_residue *_residue_P[];
  109626. extern vorbis_func_mapping *_mapping_P[];
  109627. #endif
  109628. /*** End of inlined file: registry.h ***/
  109629. /*** Start of inlined file: scales.h ***/
  109630. #ifndef _V_SCALES_H_
  109631. #define _V_SCALES_H_
  109632. #include <math.h>
  109633. /* 20log10(x) */
  109634. #define VORBIS_IEEE_FLOAT32 1
  109635. #ifdef VORBIS_IEEE_FLOAT32
  109636. static float unitnorm(float x){
  109637. union {
  109638. ogg_uint32_t i;
  109639. float f;
  109640. } ix;
  109641. ix.f = x;
  109642. ix.i = (ix.i & 0x80000000U) | (0x3f800000U);
  109643. return ix.f;
  109644. }
  109645. /* Segher was off (too high) by ~ .3 decibel. Center the conversion correctly. */
  109646. static float todB(const float *x){
  109647. union {
  109648. ogg_uint32_t i;
  109649. float f;
  109650. } ix;
  109651. ix.f = *x;
  109652. ix.i = ix.i&0x7fffffff;
  109653. return (float)(ix.i * 7.17711438e-7f -764.6161886f);
  109654. }
  109655. #define todB_nn(x) todB(x)
  109656. #else
  109657. static float unitnorm(float x){
  109658. if(x<0)return(-1.f);
  109659. return(1.f);
  109660. }
  109661. #define todB(x) (*(x)==0?-400.f:log(*(x)**(x))*4.34294480f)
  109662. #define todB_nn(x) (*(x)==0.f?-400.f:log(*(x))*8.6858896f)
  109663. #endif
  109664. #define fromdB(x) (exp((x)*.11512925f))
  109665. /* The bark scale equations are approximations, since the original
  109666. table was somewhat hand rolled. The below are chosen to have the
  109667. best possible fit to the rolled tables, thus their somewhat odd
  109668. appearance (these are more accurate and over a longer range than
  109669. the oft-quoted bark equations found in the texts I have). The
  109670. approximations are valid from 0 - 30kHz (nyquist) or so.
  109671. all f in Hz, z in Bark */
  109672. #define toBARK(n) (13.1f*atan(.00074f*(n))+2.24f*atan((n)*(n)*1.85e-8f)+1e-4f*(n))
  109673. #define fromBARK(z) (102.f*(z)-2.f*pow(z,2.f)+.4f*pow(z,3.f)+pow(1.46f,z)-1.f)
  109674. #define toMEL(n) (log(1.f+(n)*.001f)*1442.695f)
  109675. #define fromMEL(m) (1000.f*exp((m)/1442.695f)-1000.f)
  109676. /* Frequency to octave. We arbitrarily declare 63.5 Hz to be octave
  109677. 0.0 */
  109678. #define toOC(n) (log(n)*1.442695f-5.965784f)
  109679. #define fromOC(o) (exp(((o)+5.965784f)*.693147f))
  109680. #endif
  109681. /*** End of inlined file: scales.h ***/
  109682. int analysis_noisy=1;
  109683. /* decides between modes, dispatches to the appropriate mapping. */
  109684. int vorbis_analysis(vorbis_block *vb, ogg_packet *op){
  109685. int ret,i;
  109686. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  109687. vb->glue_bits=0;
  109688. vb->time_bits=0;
  109689. vb->floor_bits=0;
  109690. vb->res_bits=0;
  109691. /* first things first. Make sure encode is ready */
  109692. for(i=0;i<PACKETBLOBS;i++)
  109693. oggpack_reset(vbi->packetblob[i]);
  109694. /* we only have one mapping type (0), and we let the mapping code
  109695. itself figure out what soft mode to use. This allows easier
  109696. bitrate management */
  109697. if((ret=_mapping_P[0]->forward(vb)))
  109698. return(ret);
  109699. if(op){
  109700. if(vorbis_bitrate_managed(vb))
  109701. /* The app is using a bitmanaged mode... but not using the
  109702. bitrate management interface. */
  109703. return(OV_EINVAL);
  109704. op->packet=oggpack_get_buffer(&vb->opb);
  109705. op->bytes=oggpack_bytes(&vb->opb);
  109706. op->b_o_s=0;
  109707. op->e_o_s=vb->eofflag;
  109708. op->granulepos=vb->granulepos;
  109709. op->packetno=vb->sequence; /* for sake of completeness */
  109710. }
  109711. return(0);
  109712. }
  109713. /* there was no great place to put this.... */
  109714. void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,ogg_int64_t off){
  109715. int j;
  109716. FILE *of;
  109717. char buffer[80];
  109718. /* if(i==5870){*/
  109719. sprintf(buffer,"%s_%d.m",base,i);
  109720. of=fopen(buffer,"w");
  109721. if(!of)perror("failed to open data dump file");
  109722. for(j=0;j<n;j++){
  109723. if(bark){
  109724. float b=toBARK((4000.f*j/n)+.25);
  109725. fprintf(of,"%f ",b);
  109726. }else
  109727. if(off!=0)
  109728. fprintf(of,"%f ",(double)(j+off)/8000.);
  109729. else
  109730. fprintf(of,"%f ",(double)j);
  109731. if(dB){
  109732. float val;
  109733. if(v[j]==0.)
  109734. val=-140.;
  109735. else
  109736. val=todB(v+j);
  109737. fprintf(of,"%f\n",val);
  109738. }else{
  109739. fprintf(of,"%f\n",v[j]);
  109740. }
  109741. }
  109742. fclose(of);
  109743. /* } */
  109744. }
  109745. void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  109746. ogg_int64_t off){
  109747. if(analysis_noisy)_analysis_output_always(base,i,v,n,bark,dB,off);
  109748. }
  109749. #endif
  109750. /*** End of inlined file: analysis.c ***/
  109751. /*** Start of inlined file: bitrate.c ***/
  109752. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  109753. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  109754. // tasks..
  109755. #if JUCE_MSVC
  109756. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  109757. #endif
  109758. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  109759. #if JUCE_USE_OGGVORBIS
  109760. #include <stdlib.h>
  109761. #include <string.h>
  109762. #include <math.h>
  109763. /* compute bitrate tracking setup */
  109764. void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bm){
  109765. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  109766. bitrate_manager_info *bi=&ci->bi;
  109767. memset(bm,0,sizeof(*bm));
  109768. if(bi && (bi->reservoir_bits>0)){
  109769. long ratesamples=vi->rate;
  109770. int halfsamples=ci->blocksizes[0]>>1;
  109771. bm->short_per_long=ci->blocksizes[1]/ci->blocksizes[0];
  109772. bm->managed=1;
  109773. bm->avg_bitsper= rint(1.*bi->avg_rate*halfsamples/ratesamples);
  109774. bm->min_bitsper= rint(1.*bi->min_rate*halfsamples/ratesamples);
  109775. bm->max_bitsper= rint(1.*bi->max_rate*halfsamples/ratesamples);
  109776. bm->avgfloat=PACKETBLOBS/2;
  109777. /* not a necessary fix, but one that leads to a more balanced
  109778. typical initialization */
  109779. {
  109780. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  109781. bm->minmax_reservoir=desired_fill;
  109782. bm->avg_reservoir=desired_fill;
  109783. }
  109784. }
  109785. }
  109786. void vorbis_bitrate_clear(bitrate_manager_state *bm){
  109787. memset(bm,0,sizeof(*bm));
  109788. return;
  109789. }
  109790. int vorbis_bitrate_managed(vorbis_block *vb){
  109791. vorbis_dsp_state *vd=vb->vd;
  109792. private_state *b=(private_state*)vd->backend_state;
  109793. bitrate_manager_state *bm=&b->bms;
  109794. if(bm && bm->managed)return(1);
  109795. return(0);
  109796. }
  109797. /* finish taking in the block we just processed */
  109798. int vorbis_bitrate_addblock(vorbis_block *vb){
  109799. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  109800. vorbis_dsp_state *vd=vb->vd;
  109801. private_state *b=(private_state*)vd->backend_state;
  109802. bitrate_manager_state *bm=&b->bms;
  109803. vorbis_info *vi=vd->vi;
  109804. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  109805. bitrate_manager_info *bi=&ci->bi;
  109806. int choice=rint(bm->avgfloat);
  109807. long this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  109808. long min_target_bits=(vb->W?bm->min_bitsper*bm->short_per_long:bm->min_bitsper);
  109809. long max_target_bits=(vb->W?bm->max_bitsper*bm->short_per_long:bm->max_bitsper);
  109810. int samples=ci->blocksizes[vb->W]>>1;
  109811. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  109812. if(!bm->managed){
  109813. /* not a bitrate managed stream, but for API simplicity, we'll
  109814. buffer the packet to keep the code path clean */
  109815. if(bm->vb)return(-1); /* one has been submitted without
  109816. being claimed */
  109817. bm->vb=vb;
  109818. return(0);
  109819. }
  109820. bm->vb=vb;
  109821. /* look ahead for avg floater */
  109822. if(bm->avg_bitsper>0){
  109823. double slew=0.;
  109824. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  109825. double slewlimit= 15./bi->slew_damp;
  109826. /* choosing a new floater:
  109827. if we're over target, we slew down
  109828. if we're under target, we slew up
  109829. choose slew as follows: look through packetblobs of this frame
  109830. and set slew as the first in the appropriate direction that
  109831. gives us the slew we want. This may mean no slew if delta is
  109832. already favorable.
  109833. Then limit slew to slew max */
  109834. if(bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  109835. while(choice>0 && this_bits>avg_target_bits &&
  109836. bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  109837. choice--;
  109838. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  109839. }
  109840. }else if(bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  109841. while(choice+1<PACKETBLOBS && this_bits<avg_target_bits &&
  109842. bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  109843. choice++;
  109844. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  109845. }
  109846. }
  109847. slew=rint(choice-bm->avgfloat)/samples*vi->rate;
  109848. if(slew<-slewlimit)slew=-slewlimit;
  109849. if(slew>slewlimit)slew=slewlimit;
  109850. choice=rint(bm->avgfloat+= slew/vi->rate*samples);
  109851. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  109852. }
  109853. /* enforce min(if used) on the current floater (if used) */
  109854. if(bm->min_bitsper>0){
  109855. /* do we need to force the bitrate up? */
  109856. if(this_bits<min_target_bits){
  109857. while(bm->minmax_reservoir-(min_target_bits-this_bits)<0){
  109858. choice++;
  109859. if(choice>=PACKETBLOBS)break;
  109860. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  109861. }
  109862. }
  109863. }
  109864. /* enforce max (if used) on the current floater (if used) */
  109865. if(bm->max_bitsper>0){
  109866. /* do we need to force the bitrate down? */
  109867. if(this_bits>max_target_bits){
  109868. while(bm->minmax_reservoir+(this_bits-max_target_bits)>bi->reservoir_bits){
  109869. choice--;
  109870. if(choice<0)break;
  109871. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  109872. }
  109873. }
  109874. }
  109875. /* Choice of packetblobs now made based on floater, and min/max
  109876. requirements. Now boundary check extreme choices */
  109877. if(choice<0){
  109878. /* choosing a smaller packetblob is insufficient to trim bitrate.
  109879. frame will need to be truncated */
  109880. long maxsize=(max_target_bits+(bi->reservoir_bits-bm->minmax_reservoir))/8;
  109881. bm->choice=choice=0;
  109882. if(oggpack_bytes(vbi->packetblob[choice])>maxsize){
  109883. oggpack_writetrunc(vbi->packetblob[choice],maxsize*8);
  109884. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  109885. }
  109886. }else{
  109887. long minsize=(min_target_bits-bm->minmax_reservoir+7)/8;
  109888. if(choice>=PACKETBLOBS)
  109889. choice=PACKETBLOBS-1;
  109890. bm->choice=choice;
  109891. /* prop up bitrate according to demand. pad this frame out with zeroes */
  109892. minsize-=oggpack_bytes(vbi->packetblob[choice]);
  109893. while(minsize-->0)oggpack_write(vbi->packetblob[choice],0,8);
  109894. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  109895. }
  109896. /* now we have the final packet and the final packet size. Update statistics */
  109897. /* min and max reservoir */
  109898. if(bm->min_bitsper>0 || bm->max_bitsper>0){
  109899. if(max_target_bits>0 && this_bits>max_target_bits){
  109900. bm->minmax_reservoir+=(this_bits-max_target_bits);
  109901. }else if(min_target_bits>0 && this_bits<min_target_bits){
  109902. bm->minmax_reservoir+=(this_bits-min_target_bits);
  109903. }else{
  109904. /* inbetween; we want to take reservoir toward but not past desired_fill */
  109905. if(bm->minmax_reservoir>desired_fill){
  109906. if(max_target_bits>0){ /* logical bulletproofing against initialization state */
  109907. bm->minmax_reservoir+=(this_bits-max_target_bits);
  109908. if(bm->minmax_reservoir<desired_fill)bm->minmax_reservoir=desired_fill;
  109909. }else{
  109910. bm->minmax_reservoir=desired_fill;
  109911. }
  109912. }else{
  109913. if(min_target_bits>0){ /* logical bulletproofing against initialization state */
  109914. bm->minmax_reservoir+=(this_bits-min_target_bits);
  109915. if(bm->minmax_reservoir>desired_fill)bm->minmax_reservoir=desired_fill;
  109916. }else{
  109917. bm->minmax_reservoir=desired_fill;
  109918. }
  109919. }
  109920. }
  109921. }
  109922. /* avg reservoir */
  109923. if(bm->avg_bitsper>0){
  109924. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  109925. bm->avg_reservoir+=this_bits-avg_target_bits;
  109926. }
  109927. return(0);
  109928. }
  109929. int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,ogg_packet *op){
  109930. private_state *b=(private_state*)vd->backend_state;
  109931. bitrate_manager_state *bm=&b->bms;
  109932. vorbis_block *vb=bm->vb;
  109933. int choice=PACKETBLOBS/2;
  109934. if(!vb)return 0;
  109935. if(op){
  109936. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  109937. if(vorbis_bitrate_managed(vb))
  109938. choice=bm->choice;
  109939. op->packet=oggpack_get_buffer(vbi->packetblob[choice]);
  109940. op->bytes=oggpack_bytes(vbi->packetblob[choice]);
  109941. op->b_o_s=0;
  109942. op->e_o_s=vb->eofflag;
  109943. op->granulepos=vb->granulepos;
  109944. op->packetno=vb->sequence; /* for sake of completeness */
  109945. }
  109946. bm->vb=0;
  109947. return(1);
  109948. }
  109949. #endif
  109950. /*** End of inlined file: bitrate.c ***/
  109951. /*** Start of inlined file: block.c ***/
  109952. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  109953. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  109954. // tasks..
  109955. #if JUCE_MSVC
  109956. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  109957. #endif
  109958. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  109959. #if JUCE_USE_OGGVORBIS
  109960. #include <stdio.h>
  109961. #include <stdlib.h>
  109962. #include <string.h>
  109963. /*** Start of inlined file: window.h ***/
  109964. #ifndef _V_WINDOW_
  109965. #define _V_WINDOW_
  109966. extern float *_vorbis_window_get(int n);
  109967. extern void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  109968. int lW,int W,int nW);
  109969. #endif
  109970. /*** End of inlined file: window.h ***/
  109971. /*** Start of inlined file: lpc.h ***/
  109972. #ifndef _V_LPC_H_
  109973. #define _V_LPC_H_
  109974. /* simple linear scale LPC code */
  109975. extern float vorbis_lpc_from_data(float *data,float *lpc,int n,int m);
  109976. extern void vorbis_lpc_predict(float *coeff,float *prime,int m,
  109977. float *data,long n);
  109978. #endif
  109979. /*** End of inlined file: lpc.h ***/
  109980. /* pcm accumulator examples (not exhaustive):
  109981. <-------------- lW ---------------->
  109982. <--------------- W ---------------->
  109983. : .....|..... _______________ |
  109984. : .''' | '''_--- | |\ |
  109985. :.....''' |_____--- '''......| | \_______|
  109986. :.................|__________________|_______|__|______|
  109987. |<------ Sl ------>| > Sr < |endW
  109988. |beginSl |endSl | |endSr
  109989. |beginW |endlW |beginSr
  109990. |< lW >|
  109991. <--------------- W ---------------->
  109992. | | .. ______________ |
  109993. | | ' `/ | ---_ |
  109994. |___.'___/`. | ---_____|
  109995. |_______|__|_______|_________________|
  109996. | >|Sl|< |<------ Sr ----->|endW
  109997. | | |endSl |beginSr |endSr
  109998. |beginW | |endlW
  109999. mult[0] |beginSl mult[n]
  110000. <-------------- lW ----------------->
  110001. |<--W-->|
  110002. : .............. ___ | |
  110003. : .''' |`/ \ | |
  110004. :.....''' |/`....\|...|
  110005. :.........................|___|___|___|
  110006. |Sl |Sr |endW
  110007. | | |endSr
  110008. | |beginSr
  110009. | |endSl
  110010. |beginSl
  110011. |beginW
  110012. */
  110013. /* block abstraction setup *********************************************/
  110014. #ifndef WORD_ALIGN
  110015. #define WORD_ALIGN 8
  110016. #endif
  110017. int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb){
  110018. int i;
  110019. memset(vb,0,sizeof(*vb));
  110020. vb->vd=v;
  110021. vb->localalloc=0;
  110022. vb->localstore=NULL;
  110023. if(v->analysisp){
  110024. vorbis_block_internal *vbi=(vorbis_block_internal*)
  110025. (vb->internal=(vorbis_block_internal*)_ogg_calloc(1,sizeof(vorbis_block_internal)));
  110026. vbi->ampmax=-9999;
  110027. for(i=0;i<PACKETBLOBS;i++){
  110028. if(i==PACKETBLOBS/2){
  110029. vbi->packetblob[i]=&vb->opb;
  110030. }else{
  110031. vbi->packetblob[i]=
  110032. (oggpack_buffer*) _ogg_calloc(1,sizeof(oggpack_buffer));
  110033. }
  110034. oggpack_writeinit(vbi->packetblob[i]);
  110035. }
  110036. }
  110037. return(0);
  110038. }
  110039. void *_vorbis_block_alloc(vorbis_block *vb,long bytes){
  110040. bytes=(bytes+(WORD_ALIGN-1)) & ~(WORD_ALIGN-1);
  110041. if(bytes+vb->localtop>vb->localalloc){
  110042. /* can't just _ogg_realloc... there are outstanding pointers */
  110043. if(vb->localstore){
  110044. struct alloc_chain *link=(struct alloc_chain*)_ogg_malloc(sizeof(*link));
  110045. vb->totaluse+=vb->localtop;
  110046. link->next=vb->reap;
  110047. link->ptr=vb->localstore;
  110048. vb->reap=link;
  110049. }
  110050. /* highly conservative */
  110051. vb->localalloc=bytes;
  110052. vb->localstore=_ogg_malloc(vb->localalloc);
  110053. vb->localtop=0;
  110054. }
  110055. {
  110056. void *ret=(void *)(((char *)vb->localstore)+vb->localtop);
  110057. vb->localtop+=bytes;
  110058. return ret;
  110059. }
  110060. }
  110061. /* reap the chain, pull the ripcord */
  110062. void _vorbis_block_ripcord(vorbis_block *vb){
  110063. /* reap the chain */
  110064. struct alloc_chain *reap=vb->reap;
  110065. while(reap){
  110066. struct alloc_chain *next=reap->next;
  110067. _ogg_free(reap->ptr);
  110068. memset(reap,0,sizeof(*reap));
  110069. _ogg_free(reap);
  110070. reap=next;
  110071. }
  110072. /* consolidate storage */
  110073. if(vb->totaluse){
  110074. vb->localstore=_ogg_realloc(vb->localstore,vb->totaluse+vb->localalloc);
  110075. vb->localalloc+=vb->totaluse;
  110076. vb->totaluse=0;
  110077. }
  110078. /* pull the ripcord */
  110079. vb->localtop=0;
  110080. vb->reap=NULL;
  110081. }
  110082. int vorbis_block_clear(vorbis_block *vb){
  110083. int i;
  110084. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  110085. _vorbis_block_ripcord(vb);
  110086. if(vb->localstore)_ogg_free(vb->localstore);
  110087. if(vbi){
  110088. for(i=0;i<PACKETBLOBS;i++){
  110089. oggpack_writeclear(vbi->packetblob[i]);
  110090. if(i!=PACKETBLOBS/2)_ogg_free(vbi->packetblob[i]);
  110091. }
  110092. _ogg_free(vbi);
  110093. }
  110094. memset(vb,0,sizeof(*vb));
  110095. return(0);
  110096. }
  110097. /* Analysis side code, but directly related to blocking. Thus it's
  110098. here and not in analysis.c (which is for analysis transforms only).
  110099. The init is here because some of it is shared */
  110100. static int _vds_shared_init(vorbis_dsp_state *v,vorbis_info *vi,int encp){
  110101. int i;
  110102. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110103. private_state *b=NULL;
  110104. int hs;
  110105. if(ci==NULL) return 1;
  110106. hs=ci->halfrate_flag;
  110107. memset(v,0,sizeof(*v));
  110108. b=(private_state*) (v->backend_state=(private_state*)_ogg_calloc(1,sizeof(*b)));
  110109. v->vi=vi;
  110110. b->modebits=ilog2(ci->modes);
  110111. b->transform[0]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[0]));
  110112. b->transform[1]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[1]));
  110113. /* MDCT is tranform 0 */
  110114. b->transform[0][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  110115. b->transform[1][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  110116. mdct_init((mdct_lookup*)b->transform[0][0],ci->blocksizes[0]>>hs);
  110117. mdct_init((mdct_lookup*)b->transform[1][0],ci->blocksizes[1]>>hs);
  110118. /* Vorbis I uses only window type 0 */
  110119. b->window[0]=ilog2(ci->blocksizes[0])-6;
  110120. b->window[1]=ilog2(ci->blocksizes[1])-6;
  110121. if(encp){ /* encode/decode differ here */
  110122. /* analysis always needs an fft */
  110123. drft_init(&b->fft_look[0],ci->blocksizes[0]);
  110124. drft_init(&b->fft_look[1],ci->blocksizes[1]);
  110125. /* finish the codebooks */
  110126. if(!ci->fullbooks){
  110127. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  110128. for(i=0;i<ci->books;i++)
  110129. vorbis_book_init_encode(ci->fullbooks+i,ci->book_param[i]);
  110130. }
  110131. b->psy=(vorbis_look_psy*)_ogg_calloc(ci->psys,sizeof(*b->psy));
  110132. for(i=0;i<ci->psys;i++){
  110133. _vp_psy_init(b->psy+i,
  110134. ci->psy_param[i],
  110135. &ci->psy_g_param,
  110136. ci->blocksizes[ci->psy_param[i]->blockflag]/2,
  110137. vi->rate);
  110138. }
  110139. v->analysisp=1;
  110140. }else{
  110141. /* finish the codebooks */
  110142. if(!ci->fullbooks){
  110143. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  110144. for(i=0;i<ci->books;i++){
  110145. vorbis_book_init_decode(ci->fullbooks+i,ci->book_param[i]);
  110146. /* decode codebooks are now standalone after init */
  110147. vorbis_staticbook_destroy(ci->book_param[i]);
  110148. ci->book_param[i]=NULL;
  110149. }
  110150. }
  110151. }
  110152. /* initialize the storage vectors. blocksize[1] is small for encode,
  110153. but the correct size for decode */
  110154. v->pcm_storage=ci->blocksizes[1];
  110155. v->pcm=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcm));
  110156. v->pcmret=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcmret));
  110157. {
  110158. int i;
  110159. for(i=0;i<vi->channels;i++)
  110160. v->pcm[i]=(float*)_ogg_calloc(v->pcm_storage,sizeof(*v->pcm[i]));
  110161. }
  110162. /* all 1 (large block) or 0 (small block) */
  110163. /* explicitly set for the sake of clarity */
  110164. v->lW=0; /* previous window size */
  110165. v->W=0; /* current window size */
  110166. /* all vector indexes */
  110167. v->centerW=ci->blocksizes[1]/2;
  110168. v->pcm_current=v->centerW;
  110169. /* initialize all the backend lookups */
  110170. b->flr=(vorbis_look_floor**)_ogg_calloc(ci->floors,sizeof(*b->flr));
  110171. b->residue=(vorbis_look_residue**)_ogg_calloc(ci->residues,sizeof(*b->residue));
  110172. for(i=0;i<ci->floors;i++)
  110173. b->flr[i]=_floor_P[ci->floor_type[i]]->
  110174. look(v,ci->floor_param[i]);
  110175. for(i=0;i<ci->residues;i++)
  110176. b->residue[i]=_residue_P[ci->residue_type[i]]->
  110177. look(v,ci->residue_param[i]);
  110178. return 0;
  110179. }
  110180. /* arbitrary settings and spec-mandated numbers get filled in here */
  110181. int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi){
  110182. private_state *b=NULL;
  110183. if(_vds_shared_init(v,vi,1))return 1;
  110184. b=(private_state*)v->backend_state;
  110185. b->psy_g_look=_vp_global_look(vi);
  110186. /* Initialize the envelope state storage */
  110187. b->ve=(envelope_lookup*)_ogg_calloc(1,sizeof(*b->ve));
  110188. _ve_envelope_init(b->ve,vi);
  110189. vorbis_bitrate_init(vi,&b->bms);
  110190. /* compressed audio packets start after the headers
  110191. with sequence number 3 */
  110192. v->sequence=3;
  110193. return(0);
  110194. }
  110195. void vorbis_dsp_clear(vorbis_dsp_state *v){
  110196. int i;
  110197. if(v){
  110198. vorbis_info *vi=v->vi;
  110199. codec_setup_info *ci=(codec_setup_info*)(vi?vi->codec_setup:NULL);
  110200. private_state *b=(private_state*)v->backend_state;
  110201. if(b){
  110202. if(b->ve){
  110203. _ve_envelope_clear(b->ve);
  110204. _ogg_free(b->ve);
  110205. }
  110206. if(b->transform[0]){
  110207. mdct_clear((mdct_lookup*) b->transform[0][0]);
  110208. _ogg_free(b->transform[0][0]);
  110209. _ogg_free(b->transform[0]);
  110210. }
  110211. if(b->transform[1]){
  110212. mdct_clear((mdct_lookup*) b->transform[1][0]);
  110213. _ogg_free(b->transform[1][0]);
  110214. _ogg_free(b->transform[1]);
  110215. }
  110216. if(b->flr){
  110217. for(i=0;i<ci->floors;i++)
  110218. _floor_P[ci->floor_type[i]]->
  110219. free_look(b->flr[i]);
  110220. _ogg_free(b->flr);
  110221. }
  110222. if(b->residue){
  110223. for(i=0;i<ci->residues;i++)
  110224. _residue_P[ci->residue_type[i]]->
  110225. free_look(b->residue[i]);
  110226. _ogg_free(b->residue);
  110227. }
  110228. if(b->psy){
  110229. for(i=0;i<ci->psys;i++)
  110230. _vp_psy_clear(b->psy+i);
  110231. _ogg_free(b->psy);
  110232. }
  110233. if(b->psy_g_look)_vp_global_free(b->psy_g_look);
  110234. vorbis_bitrate_clear(&b->bms);
  110235. drft_clear(&b->fft_look[0]);
  110236. drft_clear(&b->fft_look[1]);
  110237. }
  110238. if(v->pcm){
  110239. for(i=0;i<vi->channels;i++)
  110240. if(v->pcm[i])_ogg_free(v->pcm[i]);
  110241. _ogg_free(v->pcm);
  110242. if(v->pcmret)_ogg_free(v->pcmret);
  110243. }
  110244. if(b){
  110245. /* free header, header1, header2 */
  110246. if(b->header)_ogg_free(b->header);
  110247. if(b->header1)_ogg_free(b->header1);
  110248. if(b->header2)_ogg_free(b->header2);
  110249. _ogg_free(b);
  110250. }
  110251. memset(v,0,sizeof(*v));
  110252. }
  110253. }
  110254. float **vorbis_analysis_buffer(vorbis_dsp_state *v, int vals){
  110255. int i;
  110256. vorbis_info *vi=v->vi;
  110257. private_state *b=(private_state*)v->backend_state;
  110258. /* free header, header1, header2 */
  110259. if(b->header)_ogg_free(b->header);b->header=NULL;
  110260. if(b->header1)_ogg_free(b->header1);b->header1=NULL;
  110261. if(b->header2)_ogg_free(b->header2);b->header2=NULL;
  110262. /* Do we have enough storage space for the requested buffer? If not,
  110263. expand the PCM (and envelope) storage */
  110264. if(v->pcm_current+vals>=v->pcm_storage){
  110265. v->pcm_storage=v->pcm_current+vals*2;
  110266. for(i=0;i<vi->channels;i++){
  110267. v->pcm[i]=(float*)_ogg_realloc(v->pcm[i],v->pcm_storage*sizeof(*v->pcm[i]));
  110268. }
  110269. }
  110270. for(i=0;i<vi->channels;i++)
  110271. v->pcmret[i]=v->pcm[i]+v->pcm_current;
  110272. return(v->pcmret);
  110273. }
  110274. static void _preextrapolate_helper(vorbis_dsp_state *v){
  110275. int i;
  110276. int order=32;
  110277. float *lpc=(float*)alloca(order*sizeof(*lpc));
  110278. float *work=(float*)alloca(v->pcm_current*sizeof(*work));
  110279. long j;
  110280. v->preextrapolate=1;
  110281. if(v->pcm_current-v->centerW>order*2){ /* safety */
  110282. for(i=0;i<v->vi->channels;i++){
  110283. /* need to run the extrapolation in reverse! */
  110284. for(j=0;j<v->pcm_current;j++)
  110285. work[j]=v->pcm[i][v->pcm_current-j-1];
  110286. /* prime as above */
  110287. vorbis_lpc_from_data(work,lpc,v->pcm_current-v->centerW,order);
  110288. /* run the predictor filter */
  110289. vorbis_lpc_predict(lpc,work+v->pcm_current-v->centerW-order,
  110290. order,
  110291. work+v->pcm_current-v->centerW,
  110292. v->centerW);
  110293. for(j=0;j<v->pcm_current;j++)
  110294. v->pcm[i][v->pcm_current-j-1]=work[j];
  110295. }
  110296. }
  110297. }
  110298. /* call with val<=0 to set eof */
  110299. int vorbis_analysis_wrote(vorbis_dsp_state *v, int vals){
  110300. vorbis_info *vi=v->vi;
  110301. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110302. if(vals<=0){
  110303. int order=32;
  110304. int i;
  110305. float *lpc=(float*) alloca(order*sizeof(*lpc));
  110306. /* if it wasn't done earlier (very short sample) */
  110307. if(!v->preextrapolate)
  110308. _preextrapolate_helper(v);
  110309. /* We're encoding the end of the stream. Just make sure we have
  110310. [at least] a few full blocks of zeroes at the end. */
  110311. /* actually, we don't want zeroes; that could drop a large
  110312. amplitude off a cliff, creating spread spectrum noise that will
  110313. suck to encode. Extrapolate for the sake of cleanliness. */
  110314. vorbis_analysis_buffer(v,ci->blocksizes[1]*3);
  110315. v->eofflag=v->pcm_current;
  110316. v->pcm_current+=ci->blocksizes[1]*3;
  110317. for(i=0;i<vi->channels;i++){
  110318. if(v->eofflag>order*2){
  110319. /* extrapolate with LPC to fill in */
  110320. long n;
  110321. /* make a predictor filter */
  110322. n=v->eofflag;
  110323. if(n>ci->blocksizes[1])n=ci->blocksizes[1];
  110324. vorbis_lpc_from_data(v->pcm[i]+v->eofflag-n,lpc,n,order);
  110325. /* run the predictor filter */
  110326. vorbis_lpc_predict(lpc,v->pcm[i]+v->eofflag-order,order,
  110327. v->pcm[i]+v->eofflag,v->pcm_current-v->eofflag);
  110328. }else{
  110329. /* not enough data to extrapolate (unlikely to happen due to
  110330. guarding the overlap, but bulletproof in case that
  110331. assumtion goes away). zeroes will do. */
  110332. memset(v->pcm[i]+v->eofflag,0,
  110333. (v->pcm_current-v->eofflag)*sizeof(*v->pcm[i]));
  110334. }
  110335. }
  110336. }else{
  110337. if(v->pcm_current+vals>v->pcm_storage)
  110338. return(OV_EINVAL);
  110339. v->pcm_current+=vals;
  110340. /* we may want to reverse extrapolate the beginning of a stream
  110341. too... in case we're beginning on a cliff! */
  110342. /* clumsy, but simple. It only runs once, so simple is good. */
  110343. if(!v->preextrapolate && v->pcm_current-v->centerW>ci->blocksizes[1])
  110344. _preextrapolate_helper(v);
  110345. }
  110346. return(0);
  110347. }
  110348. /* do the deltas, envelope shaping, pre-echo and determine the size of
  110349. the next block on which to continue analysis */
  110350. int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb){
  110351. int i;
  110352. vorbis_info *vi=v->vi;
  110353. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110354. private_state *b=(private_state*)v->backend_state;
  110355. vorbis_look_psy_global *g=b->psy_g_look;
  110356. long beginW=v->centerW-ci->blocksizes[v->W]/2,centerNext;
  110357. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  110358. /* check to see if we're started... */
  110359. if(!v->preextrapolate)return(0);
  110360. /* check to see if we're done... */
  110361. if(v->eofflag==-1)return(0);
  110362. /* By our invariant, we have lW, W and centerW set. Search for
  110363. the next boundary so we can determine nW (the next window size)
  110364. which lets us compute the shape of the current block's window */
  110365. /* we do an envelope search even on a single blocksize; we may still
  110366. be throwing more bits at impulses, and envelope search handles
  110367. marking impulses too. */
  110368. {
  110369. long bp=_ve_envelope_search(v);
  110370. if(bp==-1){
  110371. if(v->eofflag==0)return(0); /* not enough data currently to search for a
  110372. full long block */
  110373. v->nW=0;
  110374. }else{
  110375. if(ci->blocksizes[0]==ci->blocksizes[1])
  110376. v->nW=0;
  110377. else
  110378. v->nW=bp;
  110379. }
  110380. }
  110381. centerNext=v->centerW+ci->blocksizes[v->W]/4+ci->blocksizes[v->nW]/4;
  110382. {
  110383. /* center of next block + next block maximum right side. */
  110384. long blockbound=centerNext+ci->blocksizes[v->nW]/2;
  110385. if(v->pcm_current<blockbound)return(0); /* not enough data yet;
  110386. although this check is
  110387. less strict that the
  110388. _ve_envelope_search,
  110389. the search is not run
  110390. if we only use one
  110391. block size */
  110392. }
  110393. /* fill in the block. Note that for a short window, lW and nW are *short*
  110394. regardless of actual settings in the stream */
  110395. _vorbis_block_ripcord(vb);
  110396. vb->lW=v->lW;
  110397. vb->W=v->W;
  110398. vb->nW=v->nW;
  110399. if(v->W){
  110400. if(!v->lW || !v->nW){
  110401. vbi->blocktype=BLOCKTYPE_TRANSITION;
  110402. /*fprintf(stderr,"-");*/
  110403. }else{
  110404. vbi->blocktype=BLOCKTYPE_LONG;
  110405. /*fprintf(stderr,"_");*/
  110406. }
  110407. }else{
  110408. if(_ve_envelope_mark(v)){
  110409. vbi->blocktype=BLOCKTYPE_IMPULSE;
  110410. /*fprintf(stderr,"|");*/
  110411. }else{
  110412. vbi->blocktype=BLOCKTYPE_PADDING;
  110413. /*fprintf(stderr,".");*/
  110414. }
  110415. }
  110416. vb->vd=v;
  110417. vb->sequence=v->sequence++;
  110418. vb->granulepos=v->granulepos;
  110419. vb->pcmend=ci->blocksizes[v->W];
  110420. /* copy the vectors; this uses the local storage in vb */
  110421. /* this tracks 'strongest peak' for later psychoacoustics */
  110422. /* moved to the global psy state; clean this mess up */
  110423. if(vbi->ampmax>g->ampmax)g->ampmax=vbi->ampmax;
  110424. g->ampmax=_vp_ampmax_decay(g->ampmax,v);
  110425. vbi->ampmax=g->ampmax;
  110426. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  110427. vbi->pcmdelay=(float**)_vorbis_block_alloc(vb,sizeof(*vbi->pcmdelay)*vi->channels);
  110428. for(i=0;i<vi->channels;i++){
  110429. vbi->pcmdelay[i]=
  110430. (float*) _vorbis_block_alloc(vb,(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  110431. memcpy(vbi->pcmdelay[i],v->pcm[i],(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  110432. vb->pcm[i]=vbi->pcmdelay[i]+beginW;
  110433. /* before we added the delay
  110434. vb->pcm[i]=_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  110435. memcpy(vb->pcm[i],v->pcm[i]+beginW,ci->blocksizes[v->W]*sizeof(*vb->pcm[i]));
  110436. */
  110437. }
  110438. /* handle eof detection: eof==0 means that we've not yet received EOF
  110439. eof>0 marks the last 'real' sample in pcm[]
  110440. eof<0 'no more to do'; doesn't get here */
  110441. if(v->eofflag){
  110442. if(v->centerW>=v->eofflag){
  110443. v->eofflag=-1;
  110444. vb->eofflag=1;
  110445. return(1);
  110446. }
  110447. }
  110448. /* advance storage vectors and clean up */
  110449. {
  110450. int new_centerNext=ci->blocksizes[1]/2;
  110451. int movementW=centerNext-new_centerNext;
  110452. if(movementW>0){
  110453. _ve_envelope_shift(b->ve,movementW);
  110454. v->pcm_current-=movementW;
  110455. for(i=0;i<vi->channels;i++)
  110456. memmove(v->pcm[i],v->pcm[i]+movementW,
  110457. v->pcm_current*sizeof(*v->pcm[i]));
  110458. v->lW=v->W;
  110459. v->W=v->nW;
  110460. v->centerW=new_centerNext;
  110461. if(v->eofflag){
  110462. v->eofflag-=movementW;
  110463. if(v->eofflag<=0)v->eofflag=-1;
  110464. /* do not add padding to end of stream! */
  110465. if(v->centerW>=v->eofflag){
  110466. v->granulepos+=movementW-(v->centerW-v->eofflag);
  110467. }else{
  110468. v->granulepos+=movementW;
  110469. }
  110470. }else{
  110471. v->granulepos+=movementW;
  110472. }
  110473. }
  110474. }
  110475. /* done */
  110476. return(1);
  110477. }
  110478. int vorbis_synthesis_restart(vorbis_dsp_state *v){
  110479. vorbis_info *vi=v->vi;
  110480. codec_setup_info *ci;
  110481. int hs;
  110482. if(!v->backend_state)return -1;
  110483. if(!vi)return -1;
  110484. ci=(codec_setup_info*) vi->codec_setup;
  110485. if(!ci)return -1;
  110486. hs=ci->halfrate_flag;
  110487. v->centerW=ci->blocksizes[1]>>(hs+1);
  110488. v->pcm_current=v->centerW>>hs;
  110489. v->pcm_returned=-1;
  110490. v->granulepos=-1;
  110491. v->sequence=-1;
  110492. v->eofflag=0;
  110493. ((private_state *)(v->backend_state))->sample_count=-1;
  110494. return(0);
  110495. }
  110496. int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi){
  110497. if(_vds_shared_init(v,vi,0)) return 1;
  110498. vorbis_synthesis_restart(v);
  110499. return 0;
  110500. }
  110501. /* Unlike in analysis, the window is only partially applied for each
  110502. block. The time domain envelope is not yet handled at the point of
  110503. calling (as it relies on the previous block). */
  110504. int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb){
  110505. vorbis_info *vi=v->vi;
  110506. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110507. private_state *b=(private_state*)v->backend_state;
  110508. int hs=ci->halfrate_flag;
  110509. int i,j;
  110510. if(!vb)return(OV_EINVAL);
  110511. if(v->pcm_current>v->pcm_returned && v->pcm_returned!=-1)return(OV_EINVAL);
  110512. v->lW=v->W;
  110513. v->W=vb->W;
  110514. v->nW=-1;
  110515. if((v->sequence==-1)||
  110516. (v->sequence+1 != vb->sequence)){
  110517. v->granulepos=-1; /* out of sequence; lose count */
  110518. b->sample_count=-1;
  110519. }
  110520. v->sequence=vb->sequence;
  110521. if(vb->pcm){ /* no pcm to process if vorbis_synthesis_trackonly
  110522. was called on block */
  110523. int n=ci->blocksizes[v->W]>>(hs+1);
  110524. int n0=ci->blocksizes[0]>>(hs+1);
  110525. int n1=ci->blocksizes[1]>>(hs+1);
  110526. int thisCenter;
  110527. int prevCenter;
  110528. v->glue_bits+=vb->glue_bits;
  110529. v->time_bits+=vb->time_bits;
  110530. v->floor_bits+=vb->floor_bits;
  110531. v->res_bits+=vb->res_bits;
  110532. if(v->centerW){
  110533. thisCenter=n1;
  110534. prevCenter=0;
  110535. }else{
  110536. thisCenter=0;
  110537. prevCenter=n1;
  110538. }
  110539. /* v->pcm is now used like a two-stage double buffer. We don't want
  110540. to have to constantly shift *or* adjust memory usage. Don't
  110541. accept a new block until the old is shifted out */
  110542. for(j=0;j<vi->channels;j++){
  110543. /* the overlap/add section */
  110544. if(v->lW){
  110545. if(v->W){
  110546. /* large/large */
  110547. float *w=_vorbis_window_get(b->window[1]-hs);
  110548. float *pcm=v->pcm[j]+prevCenter;
  110549. float *p=vb->pcm[j];
  110550. for(i=0;i<n1;i++)
  110551. pcm[i]=pcm[i]*w[n1-i-1] + p[i]*w[i];
  110552. }else{
  110553. /* large/small */
  110554. float *w=_vorbis_window_get(b->window[0]-hs);
  110555. float *pcm=v->pcm[j]+prevCenter+n1/2-n0/2;
  110556. float *p=vb->pcm[j];
  110557. for(i=0;i<n0;i++)
  110558. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  110559. }
  110560. }else{
  110561. if(v->W){
  110562. /* small/large */
  110563. float *w=_vorbis_window_get(b->window[0]-hs);
  110564. float *pcm=v->pcm[j]+prevCenter;
  110565. float *p=vb->pcm[j]+n1/2-n0/2;
  110566. for(i=0;i<n0;i++)
  110567. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  110568. for(;i<n1/2+n0/2;i++)
  110569. pcm[i]=p[i];
  110570. }else{
  110571. /* small/small */
  110572. float *w=_vorbis_window_get(b->window[0]-hs);
  110573. float *pcm=v->pcm[j]+prevCenter;
  110574. float *p=vb->pcm[j];
  110575. for(i=0;i<n0;i++)
  110576. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  110577. }
  110578. }
  110579. /* the copy section */
  110580. {
  110581. float *pcm=v->pcm[j]+thisCenter;
  110582. float *p=vb->pcm[j]+n;
  110583. for(i=0;i<n;i++)
  110584. pcm[i]=p[i];
  110585. }
  110586. }
  110587. if(v->centerW)
  110588. v->centerW=0;
  110589. else
  110590. v->centerW=n1;
  110591. /* deal with initial packet state; we do this using the explicit
  110592. pcm_returned==-1 flag otherwise we're sensitive to first block
  110593. being short or long */
  110594. if(v->pcm_returned==-1){
  110595. v->pcm_returned=thisCenter;
  110596. v->pcm_current=thisCenter;
  110597. }else{
  110598. v->pcm_returned=prevCenter;
  110599. v->pcm_current=prevCenter+
  110600. ((ci->blocksizes[v->lW]/4+
  110601. ci->blocksizes[v->W]/4)>>hs);
  110602. }
  110603. }
  110604. /* track the frame number... This is for convenience, but also
  110605. making sure our last packet doesn't end with added padding. If
  110606. the last packet is partial, the number of samples we'll have to
  110607. return will be past the vb->granulepos.
  110608. This is not foolproof! It will be confused if we begin
  110609. decoding at the last page after a seek or hole. In that case,
  110610. we don't have a starting point to judge where the last frame
  110611. is. For this reason, vorbisfile will always try to make sure
  110612. it reads the last two marked pages in proper sequence */
  110613. if(b->sample_count==-1){
  110614. b->sample_count=0;
  110615. }else{
  110616. b->sample_count+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  110617. }
  110618. if(v->granulepos==-1){
  110619. if(vb->granulepos!=-1){ /* only set if we have a position to set to */
  110620. v->granulepos=vb->granulepos;
  110621. /* is this a short page? */
  110622. if(b->sample_count>v->granulepos){
  110623. /* corner case; if this is both the first and last audio page,
  110624. then spec says the end is cut, not beginning */
  110625. if(vb->eofflag){
  110626. /* trim the end */
  110627. /* no preceeding granulepos; assume we started at zero (we'd
  110628. have to in a short single-page stream) */
  110629. /* granulepos could be -1 due to a seek, but that would result
  110630. in a long count, not short count */
  110631. v->pcm_current-=(b->sample_count-v->granulepos)>>hs;
  110632. }else{
  110633. /* trim the beginning */
  110634. v->pcm_returned+=(b->sample_count-v->granulepos)>>hs;
  110635. if(v->pcm_returned>v->pcm_current)
  110636. v->pcm_returned=v->pcm_current;
  110637. }
  110638. }
  110639. }
  110640. }else{
  110641. v->granulepos+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  110642. if(vb->granulepos!=-1 && v->granulepos!=vb->granulepos){
  110643. if(v->granulepos>vb->granulepos){
  110644. long extra=v->granulepos-vb->granulepos;
  110645. if(extra)
  110646. if(vb->eofflag){
  110647. /* partial last frame. Strip the extra samples off */
  110648. v->pcm_current-=extra>>hs;
  110649. } /* else {Shouldn't happen *unless* the bitstream is out of
  110650. spec. Either way, believe the bitstream } */
  110651. } /* else {Shouldn't happen *unless* the bitstream is out of
  110652. spec. Either way, believe the bitstream } */
  110653. v->granulepos=vb->granulepos;
  110654. }
  110655. }
  110656. /* Update, cleanup */
  110657. if(vb->eofflag)v->eofflag=1;
  110658. return(0);
  110659. }
  110660. /* pcm==NULL indicates we just want the pending samples, no more */
  110661. int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm){
  110662. vorbis_info *vi=v->vi;
  110663. if(v->pcm_returned>-1 && v->pcm_returned<v->pcm_current){
  110664. if(pcm){
  110665. int i;
  110666. for(i=0;i<vi->channels;i++)
  110667. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  110668. *pcm=v->pcmret;
  110669. }
  110670. return(v->pcm_current-v->pcm_returned);
  110671. }
  110672. return(0);
  110673. }
  110674. int vorbis_synthesis_read(vorbis_dsp_state *v,int n){
  110675. if(n && v->pcm_returned+n>v->pcm_current)return(OV_EINVAL);
  110676. v->pcm_returned+=n;
  110677. return(0);
  110678. }
  110679. /* intended for use with a specific vorbisfile feature; we want access
  110680. to the [usually synthetic/postextrapolated] buffer and lapping at
  110681. the end of a decode cycle, specifically, a half-short-block worth.
  110682. This funtion works like pcmout above, except it will also expose
  110683. this implicit buffer data not normally decoded. */
  110684. int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm){
  110685. vorbis_info *vi=v->vi;
  110686. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  110687. int hs=ci->halfrate_flag;
  110688. int n=ci->blocksizes[v->W]>>(hs+1);
  110689. int n0=ci->blocksizes[0]>>(hs+1);
  110690. int n1=ci->blocksizes[1]>>(hs+1);
  110691. int i,j;
  110692. if(v->pcm_returned<0)return 0;
  110693. /* our returned data ends at pcm_returned; because the synthesis pcm
  110694. buffer is a two-fragment ring, that means our data block may be
  110695. fragmented by buffering, wrapping or a short block not filling
  110696. out a buffer. To simplify things, we unfragment if it's at all
  110697. possibly needed. Otherwise, we'd need to call lapout more than
  110698. once as well as hold additional dsp state. Opt for
  110699. simplicity. */
  110700. /* centerW was advanced by blockin; it would be the center of the
  110701. *next* block */
  110702. if(v->centerW==n1){
  110703. /* the data buffer wraps; swap the halves */
  110704. /* slow, sure, small */
  110705. for(j=0;j<vi->channels;j++){
  110706. float *p=v->pcm[j];
  110707. for(i=0;i<n1;i++){
  110708. float temp=p[i];
  110709. p[i]=p[i+n1];
  110710. p[i+n1]=temp;
  110711. }
  110712. }
  110713. v->pcm_current-=n1;
  110714. v->pcm_returned-=n1;
  110715. v->centerW=0;
  110716. }
  110717. /* solidify buffer into contiguous space */
  110718. if((v->lW^v->W)==1){
  110719. /* long/short or short/long */
  110720. for(j=0;j<vi->channels;j++){
  110721. float *s=v->pcm[j];
  110722. float *d=v->pcm[j]+(n1-n0)/2;
  110723. for(i=(n1+n0)/2-1;i>=0;--i)
  110724. d[i]=s[i];
  110725. }
  110726. v->pcm_returned+=(n1-n0)/2;
  110727. v->pcm_current+=(n1-n0)/2;
  110728. }else{
  110729. if(v->lW==0){
  110730. /* short/short */
  110731. for(j=0;j<vi->channels;j++){
  110732. float *s=v->pcm[j];
  110733. float *d=v->pcm[j]+n1-n0;
  110734. for(i=n0-1;i>=0;--i)
  110735. d[i]=s[i];
  110736. }
  110737. v->pcm_returned+=n1-n0;
  110738. v->pcm_current+=n1-n0;
  110739. }
  110740. }
  110741. if(pcm){
  110742. int i;
  110743. for(i=0;i<vi->channels;i++)
  110744. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  110745. *pcm=v->pcmret;
  110746. }
  110747. return(n1+n-v->pcm_returned);
  110748. }
  110749. float *vorbis_window(vorbis_dsp_state *v,int W){
  110750. vorbis_info *vi=v->vi;
  110751. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  110752. int hs=ci->halfrate_flag;
  110753. private_state *b=(private_state*)v->backend_state;
  110754. if(b->window[W]-1<0)return NULL;
  110755. return _vorbis_window_get(b->window[W]-hs);
  110756. }
  110757. #endif
  110758. /*** End of inlined file: block.c ***/
  110759. /*** Start of inlined file: codebook.c ***/
  110760. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  110761. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110762. // tasks..
  110763. #if JUCE_MSVC
  110764. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110765. #endif
  110766. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  110767. #if JUCE_USE_OGGVORBIS
  110768. #include <stdlib.h>
  110769. #include <string.h>
  110770. #include <math.h>
  110771. /* packs the given codebook into the bitstream **************************/
  110772. int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *opb){
  110773. long i,j;
  110774. int ordered=0;
  110775. /* first the basic parameters */
  110776. oggpack_write(opb,0x564342,24);
  110777. oggpack_write(opb,c->dim,16);
  110778. oggpack_write(opb,c->entries,24);
  110779. /* pack the codewords. There are two packings; length ordered and
  110780. length random. Decide between the two now. */
  110781. for(i=1;i<c->entries;i++)
  110782. if(c->lengthlist[i-1]==0 || c->lengthlist[i]<c->lengthlist[i-1])break;
  110783. if(i==c->entries)ordered=1;
  110784. if(ordered){
  110785. /* length ordered. We only need to say how many codewords of
  110786. each length. The actual codewords are generated
  110787. deterministically */
  110788. long count=0;
  110789. oggpack_write(opb,1,1); /* ordered */
  110790. oggpack_write(opb,c->lengthlist[0]-1,5); /* 1 to 32 */
  110791. for(i=1;i<c->entries;i++){
  110792. long thisx=c->lengthlist[i];
  110793. long last=c->lengthlist[i-1];
  110794. if(thisx>last){
  110795. for(j=last;j<thisx;j++){
  110796. oggpack_write(opb,i-count,_ilog(c->entries-count));
  110797. count=i;
  110798. }
  110799. }
  110800. }
  110801. oggpack_write(opb,i-count,_ilog(c->entries-count));
  110802. }else{
  110803. /* length random. Again, we don't code the codeword itself, just
  110804. the length. This time, though, we have to encode each length */
  110805. oggpack_write(opb,0,1); /* unordered */
  110806. /* algortihmic mapping has use for 'unused entries', which we tag
  110807. here. The algorithmic mapping happens as usual, but the unused
  110808. entry has no codeword. */
  110809. for(i=0;i<c->entries;i++)
  110810. if(c->lengthlist[i]==0)break;
  110811. if(i==c->entries){
  110812. oggpack_write(opb,0,1); /* no unused entries */
  110813. for(i=0;i<c->entries;i++)
  110814. oggpack_write(opb,c->lengthlist[i]-1,5);
  110815. }else{
  110816. oggpack_write(opb,1,1); /* we have unused entries; thus we tag */
  110817. for(i=0;i<c->entries;i++){
  110818. if(c->lengthlist[i]==0){
  110819. oggpack_write(opb,0,1);
  110820. }else{
  110821. oggpack_write(opb,1,1);
  110822. oggpack_write(opb,c->lengthlist[i]-1,5);
  110823. }
  110824. }
  110825. }
  110826. }
  110827. /* is the entry number the desired return value, or do we have a
  110828. mapping? If we have a mapping, what type? */
  110829. oggpack_write(opb,c->maptype,4);
  110830. switch(c->maptype){
  110831. case 0:
  110832. /* no mapping */
  110833. break;
  110834. case 1:case 2:
  110835. /* implicitly populated value mapping */
  110836. /* explicitly populated value mapping */
  110837. if(!c->quantlist){
  110838. /* no quantlist? error */
  110839. return(-1);
  110840. }
  110841. /* values that define the dequantization */
  110842. oggpack_write(opb,c->q_min,32);
  110843. oggpack_write(opb,c->q_delta,32);
  110844. oggpack_write(opb,c->q_quant-1,4);
  110845. oggpack_write(opb,c->q_sequencep,1);
  110846. {
  110847. int quantvals;
  110848. switch(c->maptype){
  110849. case 1:
  110850. /* a single column of (c->entries/c->dim) quantized values for
  110851. building a full value list algorithmically (square lattice) */
  110852. quantvals=_book_maptype1_quantvals(c);
  110853. break;
  110854. case 2:
  110855. /* every value (c->entries*c->dim total) specified explicitly */
  110856. quantvals=c->entries*c->dim;
  110857. break;
  110858. default: /* NOT_REACHABLE */
  110859. quantvals=-1;
  110860. }
  110861. /* quantized values */
  110862. for(i=0;i<quantvals;i++)
  110863. oggpack_write(opb,labs(c->quantlist[i]),c->q_quant);
  110864. }
  110865. break;
  110866. default:
  110867. /* error case; we don't have any other map types now */
  110868. return(-1);
  110869. }
  110870. return(0);
  110871. }
  110872. /* unpacks a codebook from the packet buffer into the codebook struct,
  110873. readies the codebook auxiliary structures for decode *************/
  110874. int vorbis_staticbook_unpack(oggpack_buffer *opb,static_codebook *s){
  110875. long i,j;
  110876. memset(s,0,sizeof(*s));
  110877. s->allocedp=1;
  110878. /* make sure alignment is correct */
  110879. if(oggpack_read(opb,24)!=0x564342)goto _eofout;
  110880. /* first the basic parameters */
  110881. s->dim=oggpack_read(opb,16);
  110882. s->entries=oggpack_read(opb,24);
  110883. if(s->entries==-1)goto _eofout;
  110884. /* codeword ordering.... length ordered or unordered? */
  110885. switch((int)oggpack_read(opb,1)){
  110886. case 0:
  110887. /* unordered */
  110888. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  110889. /* allocated but unused entries? */
  110890. if(oggpack_read(opb,1)){
  110891. /* yes, unused entries */
  110892. for(i=0;i<s->entries;i++){
  110893. if(oggpack_read(opb,1)){
  110894. long num=oggpack_read(opb,5);
  110895. if(num==-1)goto _eofout;
  110896. s->lengthlist[i]=num+1;
  110897. }else
  110898. s->lengthlist[i]=0;
  110899. }
  110900. }else{
  110901. /* all entries used; no tagging */
  110902. for(i=0;i<s->entries;i++){
  110903. long num=oggpack_read(opb,5);
  110904. if(num==-1)goto _eofout;
  110905. s->lengthlist[i]=num+1;
  110906. }
  110907. }
  110908. break;
  110909. case 1:
  110910. /* ordered */
  110911. {
  110912. long length=oggpack_read(opb,5)+1;
  110913. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  110914. for(i=0;i<s->entries;){
  110915. long num=oggpack_read(opb,_ilog(s->entries-i));
  110916. if(num==-1)goto _eofout;
  110917. for(j=0;j<num && i<s->entries;j++,i++)
  110918. s->lengthlist[i]=length;
  110919. length++;
  110920. }
  110921. }
  110922. break;
  110923. default:
  110924. /* EOF */
  110925. return(-1);
  110926. }
  110927. /* Do we have a mapping to unpack? */
  110928. switch((s->maptype=oggpack_read(opb,4))){
  110929. case 0:
  110930. /* no mapping */
  110931. break;
  110932. case 1: case 2:
  110933. /* implicitly populated value mapping */
  110934. /* explicitly populated value mapping */
  110935. s->q_min=oggpack_read(opb,32);
  110936. s->q_delta=oggpack_read(opb,32);
  110937. s->q_quant=oggpack_read(opb,4)+1;
  110938. s->q_sequencep=oggpack_read(opb,1);
  110939. {
  110940. int quantvals=0;
  110941. switch(s->maptype){
  110942. case 1:
  110943. quantvals=_book_maptype1_quantvals(s);
  110944. break;
  110945. case 2:
  110946. quantvals=s->entries*s->dim;
  110947. break;
  110948. }
  110949. /* quantized values */
  110950. s->quantlist=(long*)_ogg_malloc(sizeof(*s->quantlist)*quantvals);
  110951. for(i=0;i<quantvals;i++)
  110952. s->quantlist[i]=oggpack_read(opb,s->q_quant);
  110953. if(quantvals&&s->quantlist[quantvals-1]==-1)goto _eofout;
  110954. }
  110955. break;
  110956. default:
  110957. goto _errout;
  110958. }
  110959. /* all set */
  110960. return(0);
  110961. _errout:
  110962. _eofout:
  110963. vorbis_staticbook_clear(s);
  110964. return(-1);
  110965. }
  110966. /* returns the number of bits ************************************************/
  110967. int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b){
  110968. oggpack_write(b,book->codelist[a],book->c->lengthlist[a]);
  110969. return(book->c->lengthlist[a]);
  110970. }
  110971. /* One the encode side, our vector writers are each designed for a
  110972. specific purpose, and the encoder is not flexible without modification:
  110973. The LSP vector coder uses a single stage nearest-match with no
  110974. interleave, so no step and no error return. This is specced by floor0
  110975. and doesn't change.
  110976. Residue0 encoding interleaves, uses multiple stages, and each stage
  110977. peels of a specific amount of resolution from a lattice (thus we want
  110978. to match by threshold, not nearest match). Residue doesn't *have* to
  110979. be encoded that way, but to change it, one will need to add more
  110980. infrastructure on the encode side (decode side is specced and simpler) */
  110981. /* floor0 LSP (single stage, non interleaved, nearest match) */
  110982. /* returns entry number and *modifies a* to the quantization value *****/
  110983. int vorbis_book_errorv(codebook *book,float *a){
  110984. int dim=book->dim,k;
  110985. int best=_best(book,a,1);
  110986. for(k=0;k<dim;k++)
  110987. a[k]=(book->valuelist+best*dim)[k];
  110988. return(best);
  110989. }
  110990. /* returns the number of bits and *modifies a* to the quantization value *****/
  110991. int vorbis_book_encodev(codebook *book,int best,float *a,oggpack_buffer *b){
  110992. int k,dim=book->dim;
  110993. for(k=0;k<dim;k++)
  110994. a[k]=(book->valuelist+best*dim)[k];
  110995. return(vorbis_book_encode(book,best,b));
  110996. }
  110997. /* the 'eliminate the decode tree' optimization actually requires the
  110998. codewords to be MSb first, not LSb. This is an annoying inelegancy
  110999. (and one of the first places where carefully thought out design
  111000. turned out to be wrong; Vorbis II and future Ogg codecs should go
  111001. to an MSb bitpacker), but not actually the huge hit it appears to
  111002. be. The first-stage decode table catches most words so that
  111003. bitreverse is not in the main execution path. */
  111004. STIN long decode_packed_entry_number(codebook *book, oggpack_buffer *b){
  111005. int read=book->dec_maxlength;
  111006. long lo,hi;
  111007. long lok = oggpack_look(b,book->dec_firsttablen);
  111008. if (lok >= 0) {
  111009. long entry = book->dec_firsttable[lok];
  111010. if(entry&0x80000000UL){
  111011. lo=(entry>>15)&0x7fff;
  111012. hi=book->used_entries-(entry&0x7fff);
  111013. }else{
  111014. oggpack_adv(b, book->dec_codelengths[entry-1]);
  111015. return(entry-1);
  111016. }
  111017. }else{
  111018. lo=0;
  111019. hi=book->used_entries;
  111020. }
  111021. lok = oggpack_look(b, read);
  111022. while(lok<0 && read>1)
  111023. lok = oggpack_look(b, --read);
  111024. if(lok<0)return -1;
  111025. /* bisect search for the codeword in the ordered list */
  111026. {
  111027. ogg_uint32_t testword=ogg_bitreverse((ogg_uint32_t)lok);
  111028. while(hi-lo>1){
  111029. long p=(hi-lo)>>1;
  111030. long test=book->codelist[lo+p]>testword;
  111031. lo+=p&(test-1);
  111032. hi-=p&(-test);
  111033. }
  111034. if(book->dec_codelengths[lo]<=read){
  111035. oggpack_adv(b, book->dec_codelengths[lo]);
  111036. return(lo);
  111037. }
  111038. }
  111039. oggpack_adv(b, read);
  111040. return(-1);
  111041. }
  111042. /* Decode side is specced and easier, because we don't need to find
  111043. matches using different criteria; we simply read and map. There are
  111044. two things we need to do 'depending':
  111045. We may need to support interleave. We don't really, but it's
  111046. convenient to do it here rather than rebuild the vector later.
  111047. Cascades may be additive or multiplicitive; this is not inherent in
  111048. the codebook, but set in the code using the codebook. Like
  111049. interleaving, it's easiest to do it here.
  111050. addmul==0 -> declarative (set the value)
  111051. addmul==1 -> additive
  111052. addmul==2 -> multiplicitive */
  111053. /* returns the [original, not compacted] entry number or -1 on eof *********/
  111054. long vorbis_book_decode(codebook *book, oggpack_buffer *b){
  111055. long packed_entry=decode_packed_entry_number(book,b);
  111056. if(packed_entry>=0)
  111057. return(book->dec_index[packed_entry]);
  111058. /* if there's no dec_index, the codebook unpacking isn't collapsed */
  111059. return(packed_entry);
  111060. }
  111061. /* returns 0 on OK or -1 on eof *************************************/
  111062. long vorbis_book_decodevs_add(codebook *book,float *a,oggpack_buffer *b,int n){
  111063. int step=n/book->dim;
  111064. long *entry = (long*)alloca(sizeof(*entry)*step);
  111065. float **t = (float**)alloca(sizeof(*t)*step);
  111066. int i,j,o;
  111067. for (i = 0; i < step; i++) {
  111068. entry[i]=decode_packed_entry_number(book,b);
  111069. if(entry[i]==-1)return(-1);
  111070. t[i] = book->valuelist+entry[i]*book->dim;
  111071. }
  111072. for(i=0,o=0;i<book->dim;i++,o+=step)
  111073. for (j=0;j<step;j++)
  111074. a[o+j]+=t[j][i];
  111075. return(0);
  111076. }
  111077. long vorbis_book_decodev_add(codebook *book,float *a,oggpack_buffer *b,int n){
  111078. int i,j,entry;
  111079. float *t;
  111080. if(book->dim>8){
  111081. for(i=0;i<n;){
  111082. entry = decode_packed_entry_number(book,b);
  111083. if(entry==-1)return(-1);
  111084. t = book->valuelist+entry*book->dim;
  111085. for (j=0;j<book->dim;)
  111086. a[i++]+=t[j++];
  111087. }
  111088. }else{
  111089. for(i=0;i<n;){
  111090. entry = decode_packed_entry_number(book,b);
  111091. if(entry==-1)return(-1);
  111092. t = book->valuelist+entry*book->dim;
  111093. j=0;
  111094. switch((int)book->dim){
  111095. case 8:
  111096. a[i++]+=t[j++];
  111097. case 7:
  111098. a[i++]+=t[j++];
  111099. case 6:
  111100. a[i++]+=t[j++];
  111101. case 5:
  111102. a[i++]+=t[j++];
  111103. case 4:
  111104. a[i++]+=t[j++];
  111105. case 3:
  111106. a[i++]+=t[j++];
  111107. case 2:
  111108. a[i++]+=t[j++];
  111109. case 1:
  111110. a[i++]+=t[j++];
  111111. case 0:
  111112. break;
  111113. }
  111114. }
  111115. }
  111116. return(0);
  111117. }
  111118. long vorbis_book_decodev_set(codebook *book,float *a,oggpack_buffer *b,int n){
  111119. int i,j,entry;
  111120. float *t;
  111121. for(i=0;i<n;){
  111122. entry = decode_packed_entry_number(book,b);
  111123. if(entry==-1)return(-1);
  111124. t = book->valuelist+entry*book->dim;
  111125. for (j=0;j<book->dim;)
  111126. a[i++]=t[j++];
  111127. }
  111128. return(0);
  111129. }
  111130. long vorbis_book_decodevv_add(codebook *book,float **a,long offset,int ch,
  111131. oggpack_buffer *b,int n){
  111132. long i,j,entry;
  111133. int chptr=0;
  111134. for(i=offset/ch;i<(offset+n)/ch;){
  111135. entry = decode_packed_entry_number(book,b);
  111136. if(entry==-1)return(-1);
  111137. {
  111138. const float *t = book->valuelist+entry*book->dim;
  111139. for (j=0;j<book->dim;j++){
  111140. a[chptr++][i]+=t[j];
  111141. if(chptr==ch){
  111142. chptr=0;
  111143. i++;
  111144. }
  111145. }
  111146. }
  111147. }
  111148. return(0);
  111149. }
  111150. #ifdef _V_SELFTEST
  111151. /* Simple enough; pack a few candidate codebooks, unpack them. Code a
  111152. number of vectors through (keeping track of the quantized values),
  111153. and decode using the unpacked book. quantized version of in should
  111154. exactly equal out */
  111155. #include <stdio.h>
  111156. #include "vorbis/book/lsp20_0.vqh"
  111157. #include "vorbis/book/res0a_13.vqh"
  111158. #define TESTSIZE 40
  111159. float test1[TESTSIZE]={
  111160. 0.105939f,
  111161. 0.215373f,
  111162. 0.429117f,
  111163. 0.587974f,
  111164. 0.181173f,
  111165. 0.296583f,
  111166. 0.515707f,
  111167. 0.715261f,
  111168. 0.162327f,
  111169. 0.263834f,
  111170. 0.342876f,
  111171. 0.406025f,
  111172. 0.103571f,
  111173. 0.223561f,
  111174. 0.368513f,
  111175. 0.540313f,
  111176. 0.136672f,
  111177. 0.395882f,
  111178. 0.587183f,
  111179. 0.652476f,
  111180. 0.114338f,
  111181. 0.417300f,
  111182. 0.525486f,
  111183. 0.698679f,
  111184. 0.147492f,
  111185. 0.324481f,
  111186. 0.643089f,
  111187. 0.757582f,
  111188. 0.139556f,
  111189. 0.215795f,
  111190. 0.324559f,
  111191. 0.399387f,
  111192. 0.120236f,
  111193. 0.267420f,
  111194. 0.446940f,
  111195. 0.608760f,
  111196. 0.115587f,
  111197. 0.287234f,
  111198. 0.571081f,
  111199. 0.708603f,
  111200. };
  111201. float test3[TESTSIZE]={
  111202. 0,1,-2,3,4,-5,6,7,8,9,
  111203. 8,-2,7,-1,4,6,8,3,1,-9,
  111204. 10,11,12,13,14,15,26,17,18,19,
  111205. 30,-25,-30,-1,-5,-32,4,3,-2,0};
  111206. static_codebook *testlist[]={&_vq_book_lsp20_0,
  111207. &_vq_book_res0a_13,NULL};
  111208. float *testvec[]={test1,test3};
  111209. int main(){
  111210. oggpack_buffer write;
  111211. oggpack_buffer read;
  111212. long ptr=0,i;
  111213. oggpack_writeinit(&write);
  111214. fprintf(stderr,"Testing codebook abstraction...:\n");
  111215. while(testlist[ptr]){
  111216. codebook c;
  111217. static_codebook s;
  111218. float *qv=alloca(sizeof(*qv)*TESTSIZE);
  111219. float *iv=alloca(sizeof(*iv)*TESTSIZE);
  111220. memcpy(qv,testvec[ptr],sizeof(*qv)*TESTSIZE);
  111221. memset(iv,0,sizeof(*iv)*TESTSIZE);
  111222. fprintf(stderr,"\tpacking/coding %ld... ",ptr);
  111223. /* pack the codebook, write the testvector */
  111224. oggpack_reset(&write);
  111225. vorbis_book_init_encode(&c,testlist[ptr]); /* get it into memory
  111226. we can write */
  111227. vorbis_staticbook_pack(testlist[ptr],&write);
  111228. fprintf(stderr,"Codebook size %ld bytes... ",oggpack_bytes(&write));
  111229. for(i=0;i<TESTSIZE;i+=c.dim){
  111230. int best=_best(&c,qv+i,1);
  111231. vorbis_book_encodev(&c,best,qv+i,&write);
  111232. }
  111233. vorbis_book_clear(&c);
  111234. fprintf(stderr,"OK.\n");
  111235. fprintf(stderr,"\tunpacking/decoding %ld... ",ptr);
  111236. /* transfer the write data to a read buffer and unpack/read */
  111237. oggpack_readinit(&read,oggpack_get_buffer(&write),oggpack_bytes(&write));
  111238. if(vorbis_staticbook_unpack(&read,&s)){
  111239. fprintf(stderr,"Error unpacking codebook.\n");
  111240. exit(1);
  111241. }
  111242. if(vorbis_book_init_decode(&c,&s)){
  111243. fprintf(stderr,"Error initializing codebook.\n");
  111244. exit(1);
  111245. }
  111246. for(i=0;i<TESTSIZE;i+=c.dim)
  111247. if(vorbis_book_decodev_set(&c,iv+i,&read,c.dim)==-1){
  111248. fprintf(stderr,"Error reading codebook test data (EOP).\n");
  111249. exit(1);
  111250. }
  111251. for(i=0;i<TESTSIZE;i++)
  111252. if(fabs(qv[i]-iv[i])>.000001){
  111253. fprintf(stderr,"read (%g) != written (%g) at position (%ld)\n",
  111254. iv[i],qv[i],i);
  111255. exit(1);
  111256. }
  111257. fprintf(stderr,"OK\n");
  111258. ptr++;
  111259. }
  111260. /* The above is the trivial stuff; now try unquantizing a log scale codebook */
  111261. exit(0);
  111262. }
  111263. #endif
  111264. #endif
  111265. /*** End of inlined file: codebook.c ***/
  111266. /*** Start of inlined file: envelope.c ***/
  111267. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  111268. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111269. // tasks..
  111270. #if JUCE_MSVC
  111271. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111272. #endif
  111273. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  111274. #if JUCE_USE_OGGVORBIS
  111275. #include <stdlib.h>
  111276. #include <string.h>
  111277. #include <stdio.h>
  111278. #include <math.h>
  111279. void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi){
  111280. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111281. vorbis_info_psy_global *gi=&ci->psy_g_param;
  111282. int ch=vi->channels;
  111283. int i,j;
  111284. int n=e->winlength=128;
  111285. e->searchstep=64; /* not random */
  111286. e->minenergy=gi->preecho_minenergy;
  111287. e->ch=ch;
  111288. e->storage=128;
  111289. e->cursor=ci->blocksizes[1]/2;
  111290. e->mdct_win=(float*)_ogg_calloc(n,sizeof(*e->mdct_win));
  111291. mdct_init(&e->mdct,n);
  111292. for(i=0;i<n;i++){
  111293. e->mdct_win[i]=sin(i/(n-1.)*M_PI);
  111294. e->mdct_win[i]*=e->mdct_win[i];
  111295. }
  111296. /* magic follows */
  111297. e->band[0].begin=2; e->band[0].end=4;
  111298. e->band[1].begin=4; e->band[1].end=5;
  111299. e->band[2].begin=6; e->band[2].end=6;
  111300. e->band[3].begin=9; e->band[3].end=8;
  111301. e->band[4].begin=13; e->band[4].end=8;
  111302. e->band[5].begin=17; e->band[5].end=8;
  111303. e->band[6].begin=22; e->band[6].end=8;
  111304. for(j=0;j<VE_BANDS;j++){
  111305. n=e->band[j].end;
  111306. e->band[j].window=(float*)_ogg_malloc(n*sizeof(*e->band[0].window));
  111307. for(i=0;i<n;i++){
  111308. e->band[j].window[i]=sin((i+.5)/n*M_PI);
  111309. e->band[j].total+=e->band[j].window[i];
  111310. }
  111311. e->band[j].total=1./e->band[j].total;
  111312. }
  111313. e->filter=(envelope_filter_state*)_ogg_calloc(VE_BANDS*ch,sizeof(*e->filter));
  111314. e->mark=(int*)_ogg_calloc(e->storage,sizeof(*e->mark));
  111315. }
  111316. void _ve_envelope_clear(envelope_lookup *e){
  111317. int i;
  111318. mdct_clear(&e->mdct);
  111319. for(i=0;i<VE_BANDS;i++)
  111320. _ogg_free(e->band[i].window);
  111321. _ogg_free(e->mdct_win);
  111322. _ogg_free(e->filter);
  111323. _ogg_free(e->mark);
  111324. memset(e,0,sizeof(*e));
  111325. }
  111326. /* fairly straight threshhold-by-band based until we find something
  111327. that works better and isn't patented. */
  111328. static int _ve_amp(envelope_lookup *ve,
  111329. vorbis_info_psy_global *gi,
  111330. float *data,
  111331. envelope_band *bands,
  111332. envelope_filter_state *filters,
  111333. long pos){
  111334. long n=ve->winlength;
  111335. int ret=0;
  111336. long i,j;
  111337. float decay;
  111338. /* we want to have a 'minimum bar' for energy, else we're just
  111339. basing blocks on quantization noise that outweighs the signal
  111340. itself (for low power signals) */
  111341. float minV=ve->minenergy;
  111342. float *vec=(float*) alloca(n*sizeof(*vec));
  111343. /* stretch is used to gradually lengthen the number of windows
  111344. considered prevoius-to-potential-trigger */
  111345. int stretch=max(VE_MINSTRETCH,ve->stretch/2);
  111346. float penalty=gi->stretch_penalty-(ve->stretch/2-VE_MINSTRETCH);
  111347. if(penalty<0.f)penalty=0.f;
  111348. if(penalty>gi->stretch_penalty)penalty=gi->stretch_penalty;
  111349. /*_analysis_output_always("lpcm",seq2,data,n,0,0,
  111350. totalshift+pos*ve->searchstep);*/
  111351. /* window and transform */
  111352. for(i=0;i<n;i++)
  111353. vec[i]=data[i]*ve->mdct_win[i];
  111354. mdct_forward(&ve->mdct,vec,vec);
  111355. /*_analysis_output_always("mdct",seq2,vec,n/2,0,1,0); */
  111356. /* near-DC spreading function; this has nothing to do with
  111357. psychoacoustics, just sidelobe leakage and window size */
  111358. {
  111359. float temp=vec[0]*vec[0]+.7*vec[1]*vec[1]+.2*vec[2]*vec[2];
  111360. int ptr=filters->nearptr;
  111361. /* the accumulation is regularly refreshed from scratch to avoid
  111362. floating point creep */
  111363. if(ptr==0){
  111364. decay=filters->nearDC_acc=filters->nearDC_partialacc+temp;
  111365. filters->nearDC_partialacc=temp;
  111366. }else{
  111367. decay=filters->nearDC_acc+=temp;
  111368. filters->nearDC_partialacc+=temp;
  111369. }
  111370. filters->nearDC_acc-=filters->nearDC[ptr];
  111371. filters->nearDC[ptr]=temp;
  111372. decay*=(1./(VE_NEARDC+1));
  111373. filters->nearptr++;
  111374. if(filters->nearptr>=VE_NEARDC)filters->nearptr=0;
  111375. decay=todB(&decay)*.5-15.f;
  111376. }
  111377. /* perform spreading and limiting, also smooth the spectrum. yes,
  111378. the MDCT results in all real coefficients, but it still *behaves*
  111379. like real/imaginary pairs */
  111380. for(i=0;i<n/2;i+=2){
  111381. float val=vec[i]*vec[i]+vec[i+1]*vec[i+1];
  111382. val=todB(&val)*.5f;
  111383. if(val<decay)val=decay;
  111384. if(val<minV)val=minV;
  111385. vec[i>>1]=val;
  111386. decay-=8.;
  111387. }
  111388. /*_analysis_output_always("spread",seq2++,vec,n/4,0,0,0);*/
  111389. /* perform preecho/postecho triggering by band */
  111390. for(j=0;j<VE_BANDS;j++){
  111391. float acc=0.;
  111392. float valmax,valmin;
  111393. /* accumulate amplitude */
  111394. for(i=0;i<bands[j].end;i++)
  111395. acc+=vec[i+bands[j].begin]*bands[j].window[i];
  111396. acc*=bands[j].total;
  111397. /* convert amplitude to delta */
  111398. {
  111399. int p,thisx=filters[j].ampptr;
  111400. float postmax,postmin,premax=-99999.f,premin=99999.f;
  111401. p=thisx;
  111402. p--;
  111403. if(p<0)p+=VE_AMP;
  111404. postmax=max(acc,filters[j].ampbuf[p]);
  111405. postmin=min(acc,filters[j].ampbuf[p]);
  111406. for(i=0;i<stretch;i++){
  111407. p--;
  111408. if(p<0)p+=VE_AMP;
  111409. premax=max(premax,filters[j].ampbuf[p]);
  111410. premin=min(premin,filters[j].ampbuf[p]);
  111411. }
  111412. valmin=postmin-premin;
  111413. valmax=postmax-premax;
  111414. /*filters[j].markers[pos]=valmax;*/
  111415. filters[j].ampbuf[thisx]=acc;
  111416. filters[j].ampptr++;
  111417. if(filters[j].ampptr>=VE_AMP)filters[j].ampptr=0;
  111418. }
  111419. /* look at min/max, decide trigger */
  111420. if(valmax>gi->preecho_thresh[j]+penalty){
  111421. ret|=1;
  111422. ret|=4;
  111423. }
  111424. if(valmin<gi->postecho_thresh[j]-penalty)ret|=2;
  111425. }
  111426. return(ret);
  111427. }
  111428. #if 0
  111429. static int seq=0;
  111430. static ogg_int64_t totalshift=-1024;
  111431. #endif
  111432. long _ve_envelope_search(vorbis_dsp_state *v){
  111433. vorbis_info *vi=v->vi;
  111434. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  111435. vorbis_info_psy_global *gi=&ci->psy_g_param;
  111436. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  111437. long i,j;
  111438. int first=ve->current/ve->searchstep;
  111439. int last=v->pcm_current/ve->searchstep-VE_WIN;
  111440. if(first<0)first=0;
  111441. /* make sure we have enough storage to match the PCM */
  111442. if(last+VE_WIN+VE_POST>ve->storage){
  111443. ve->storage=last+VE_WIN+VE_POST; /* be sure */
  111444. ve->mark=(int*)_ogg_realloc(ve->mark,ve->storage*sizeof(*ve->mark));
  111445. }
  111446. for(j=first;j<last;j++){
  111447. int ret=0;
  111448. ve->stretch++;
  111449. if(ve->stretch>VE_MAXSTRETCH*2)
  111450. ve->stretch=VE_MAXSTRETCH*2;
  111451. for(i=0;i<ve->ch;i++){
  111452. float *pcm=v->pcm[i]+ve->searchstep*(j);
  111453. ret|=_ve_amp(ve,gi,pcm,ve->band,ve->filter+i*VE_BANDS,j);
  111454. }
  111455. ve->mark[j+VE_POST]=0;
  111456. if(ret&1){
  111457. ve->mark[j]=1;
  111458. ve->mark[j+1]=1;
  111459. }
  111460. if(ret&2){
  111461. ve->mark[j]=1;
  111462. if(j>0)ve->mark[j-1]=1;
  111463. }
  111464. if(ret&4)ve->stretch=-1;
  111465. }
  111466. ve->current=last*ve->searchstep;
  111467. {
  111468. long centerW=v->centerW;
  111469. long testW=
  111470. centerW+
  111471. ci->blocksizes[v->W]/4+
  111472. ci->blocksizes[1]/2+
  111473. ci->blocksizes[0]/4;
  111474. j=ve->cursor;
  111475. while(j<ve->current-(ve->searchstep)){/* account for postecho
  111476. working back one window */
  111477. if(j>=testW)return(1);
  111478. ve->cursor=j;
  111479. if(ve->mark[j/ve->searchstep]){
  111480. if(j>centerW){
  111481. #if 0
  111482. if(j>ve->curmark){
  111483. float *marker=alloca(v->pcm_current*sizeof(*marker));
  111484. int l,m;
  111485. memset(marker,0,sizeof(*marker)*v->pcm_current);
  111486. fprintf(stderr,"mark! seq=%d, cursor:%fs time:%fs\n",
  111487. seq,
  111488. (totalshift+ve->cursor)/44100.,
  111489. (totalshift+j)/44100.);
  111490. _analysis_output_always("pcmL",seq,v->pcm[0],v->pcm_current,0,0,totalshift);
  111491. _analysis_output_always("pcmR",seq,v->pcm[1],v->pcm_current,0,0,totalshift);
  111492. _analysis_output_always("markL",seq,v->pcm[0],j,0,0,totalshift);
  111493. _analysis_output_always("markR",seq,v->pcm[1],j,0,0,totalshift);
  111494. for(m=0;m<VE_BANDS;m++){
  111495. char buf[80];
  111496. sprintf(buf,"delL%d",m);
  111497. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m].markers[l]*.1;
  111498. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  111499. }
  111500. for(m=0;m<VE_BANDS;m++){
  111501. char buf[80];
  111502. sprintf(buf,"delR%d",m);
  111503. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m+VE_BANDS].markers[l]*.1;
  111504. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  111505. }
  111506. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->mark[l]*.4;
  111507. _analysis_output_always("mark",seq,marker,v->pcm_current,0,0,totalshift);
  111508. seq++;
  111509. }
  111510. #endif
  111511. ve->curmark=j;
  111512. if(j>=testW)return(1);
  111513. return(0);
  111514. }
  111515. }
  111516. j+=ve->searchstep;
  111517. }
  111518. }
  111519. return(-1);
  111520. }
  111521. int _ve_envelope_mark(vorbis_dsp_state *v){
  111522. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  111523. vorbis_info *vi=v->vi;
  111524. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111525. long centerW=v->centerW;
  111526. long beginW=centerW-ci->blocksizes[v->W]/4;
  111527. long endW=centerW+ci->blocksizes[v->W]/4;
  111528. if(v->W){
  111529. beginW-=ci->blocksizes[v->lW]/4;
  111530. endW+=ci->blocksizes[v->nW]/4;
  111531. }else{
  111532. beginW-=ci->blocksizes[0]/4;
  111533. endW+=ci->blocksizes[0]/4;
  111534. }
  111535. if(ve->curmark>=beginW && ve->curmark<endW)return(1);
  111536. {
  111537. long first=beginW/ve->searchstep;
  111538. long last=endW/ve->searchstep;
  111539. long i;
  111540. for(i=first;i<last;i++)
  111541. if(ve->mark[i])return(1);
  111542. }
  111543. return(0);
  111544. }
  111545. void _ve_envelope_shift(envelope_lookup *e,long shift){
  111546. int smallsize=e->current/e->searchstep+VE_POST; /* adjust for placing marks
  111547. ahead of ve->current */
  111548. int smallshift=shift/e->searchstep;
  111549. memmove(e->mark,e->mark+smallshift,(smallsize-smallshift)*sizeof(*e->mark));
  111550. #if 0
  111551. for(i=0;i<VE_BANDS*e->ch;i++)
  111552. memmove(e->filter[i].markers,
  111553. e->filter[i].markers+smallshift,
  111554. (1024-smallshift)*sizeof(*(*e->filter).markers));
  111555. totalshift+=shift;
  111556. #endif
  111557. e->current-=shift;
  111558. if(e->curmark>=0)
  111559. e->curmark-=shift;
  111560. e->cursor-=shift;
  111561. }
  111562. #endif
  111563. /*** End of inlined file: envelope.c ***/
  111564. /*** Start of inlined file: floor0.c ***/
  111565. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  111566. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111567. // tasks..
  111568. #if JUCE_MSVC
  111569. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111570. #endif
  111571. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  111572. #if JUCE_USE_OGGVORBIS
  111573. #include <stdlib.h>
  111574. #include <string.h>
  111575. #include <math.h>
  111576. /*** Start of inlined file: lsp.h ***/
  111577. #ifndef _V_LSP_H_
  111578. #define _V_LSP_H_
  111579. extern int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m);
  111580. extern void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,
  111581. float *lsp,int m,
  111582. float amp,float ampoffset);
  111583. #endif
  111584. /*** End of inlined file: lsp.h ***/
  111585. #include <stdio.h>
  111586. typedef struct {
  111587. int ln;
  111588. int m;
  111589. int **linearmap;
  111590. int n[2];
  111591. vorbis_info_floor0 *vi;
  111592. long bits;
  111593. long frames;
  111594. } vorbis_look_floor0;
  111595. /***********************************************/
  111596. static void floor0_free_info(vorbis_info_floor *i){
  111597. vorbis_info_floor0 *info=(vorbis_info_floor0 *)i;
  111598. if(info){
  111599. memset(info,0,sizeof(*info));
  111600. _ogg_free(info);
  111601. }
  111602. }
  111603. static void floor0_free_look(vorbis_look_floor *i){
  111604. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  111605. if(look){
  111606. if(look->linearmap){
  111607. if(look->linearmap[0])_ogg_free(look->linearmap[0]);
  111608. if(look->linearmap[1])_ogg_free(look->linearmap[1]);
  111609. _ogg_free(look->linearmap);
  111610. }
  111611. memset(look,0,sizeof(*look));
  111612. _ogg_free(look);
  111613. }
  111614. }
  111615. static vorbis_info_floor *floor0_unpack (vorbis_info *vi,oggpack_buffer *opb){
  111616. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111617. int j;
  111618. vorbis_info_floor0 *info=(vorbis_info_floor0*)_ogg_malloc(sizeof(*info));
  111619. info->order=oggpack_read(opb,8);
  111620. info->rate=oggpack_read(opb,16);
  111621. info->barkmap=oggpack_read(opb,16);
  111622. info->ampbits=oggpack_read(opb,6);
  111623. info->ampdB=oggpack_read(opb,8);
  111624. info->numbooks=oggpack_read(opb,4)+1;
  111625. if(info->order<1)goto err_out;
  111626. if(info->rate<1)goto err_out;
  111627. if(info->barkmap<1)goto err_out;
  111628. if(info->numbooks<1)goto err_out;
  111629. for(j=0;j<info->numbooks;j++){
  111630. info->books[j]=oggpack_read(opb,8);
  111631. if(info->books[j]<0 || info->books[j]>=ci->books)goto err_out;
  111632. }
  111633. return(info);
  111634. err_out:
  111635. floor0_free_info(info);
  111636. return(NULL);
  111637. }
  111638. /* initialize Bark scale and normalization lookups. We could do this
  111639. with static tables, but Vorbis allows a number of possible
  111640. combinations, so it's best to do it computationally.
  111641. The below is authoritative in terms of defining scale mapping.
  111642. Note that the scale depends on the sampling rate as well as the
  111643. linear block and mapping sizes */
  111644. static void floor0_map_lazy_init(vorbis_block *vb,
  111645. vorbis_info_floor *infoX,
  111646. vorbis_look_floor0 *look){
  111647. if(!look->linearmap[vb->W]){
  111648. vorbis_dsp_state *vd=vb->vd;
  111649. vorbis_info *vi=vd->vi;
  111650. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111651. vorbis_info_floor0 *info=(vorbis_info_floor0 *)infoX;
  111652. int W=vb->W;
  111653. int n=ci->blocksizes[W]/2,j;
  111654. /* we choose a scaling constant so that:
  111655. floor(bark(rate/2-1)*C)=mapped-1
  111656. floor(bark(rate/2)*C)=mapped */
  111657. float scale=look->ln/toBARK(info->rate/2.f);
  111658. /* the mapping from a linear scale to a smaller bark scale is
  111659. straightforward. We do *not* make sure that the linear mapping
  111660. does not skip bark-scale bins; the decoder simply skips them and
  111661. the encoder may do what it wishes in filling them. They're
  111662. necessary in some mapping combinations to keep the scale spacing
  111663. accurate */
  111664. look->linearmap[W]=(int*)_ogg_malloc((n+1)*sizeof(**look->linearmap));
  111665. for(j=0;j<n;j++){
  111666. int val=floor( toBARK((info->rate/2.f)/n*j)
  111667. *scale); /* bark numbers represent band edges */
  111668. if(val>=look->ln)val=look->ln-1; /* guard against the approximation */
  111669. look->linearmap[W][j]=val;
  111670. }
  111671. look->linearmap[W][j]=-1;
  111672. look->n[W]=n;
  111673. }
  111674. }
  111675. static vorbis_look_floor *floor0_look(vorbis_dsp_state *vd,
  111676. vorbis_info_floor *i){
  111677. vorbis_info_floor0 *info=(vorbis_info_floor0*)i;
  111678. vorbis_look_floor0 *look=(vorbis_look_floor0*)_ogg_calloc(1,sizeof(*look));
  111679. look->m=info->order;
  111680. look->ln=info->barkmap;
  111681. look->vi=info;
  111682. look->linearmap=(int**)_ogg_calloc(2,sizeof(*look->linearmap));
  111683. return look;
  111684. }
  111685. static void *floor0_inverse1(vorbis_block *vb,vorbis_look_floor *i){
  111686. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  111687. vorbis_info_floor0 *info=look->vi;
  111688. int j,k;
  111689. int ampraw=oggpack_read(&vb->opb,info->ampbits);
  111690. if(ampraw>0){ /* also handles the -1 out of data case */
  111691. long maxval=(1<<info->ampbits)-1;
  111692. float amp=(float)ampraw/maxval*info->ampdB;
  111693. int booknum=oggpack_read(&vb->opb,_ilog(info->numbooks));
  111694. if(booknum!=-1 && booknum<info->numbooks){ /* be paranoid */
  111695. codec_setup_info *ci=(codec_setup_info *)vb->vd->vi->codec_setup;
  111696. codebook *b=ci->fullbooks+info->books[booknum];
  111697. float last=0.f;
  111698. /* the additional b->dim is a guard against any possible stack
  111699. smash; b->dim is provably more than we can overflow the
  111700. vector */
  111701. float *lsp=(float*)_vorbis_block_alloc(vb,sizeof(*lsp)*(look->m+b->dim+1));
  111702. for(j=0;j<look->m;j+=b->dim)
  111703. if(vorbis_book_decodev_set(b,lsp+j,&vb->opb,b->dim)==-1)goto eop;
  111704. for(j=0;j<look->m;){
  111705. for(k=0;k<b->dim;k++,j++)lsp[j]+=last;
  111706. last=lsp[j-1];
  111707. }
  111708. lsp[look->m]=amp;
  111709. return(lsp);
  111710. }
  111711. }
  111712. eop:
  111713. return(NULL);
  111714. }
  111715. static int floor0_inverse2(vorbis_block *vb,vorbis_look_floor *i,
  111716. void *memo,float *out){
  111717. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  111718. vorbis_info_floor0 *info=look->vi;
  111719. floor0_map_lazy_init(vb,info,look);
  111720. if(memo){
  111721. float *lsp=(float *)memo;
  111722. float amp=lsp[look->m];
  111723. /* take the coefficients back to a spectral envelope curve */
  111724. vorbis_lsp_to_curve(out,
  111725. look->linearmap[vb->W],
  111726. look->n[vb->W],
  111727. look->ln,
  111728. lsp,look->m,amp,(float)info->ampdB);
  111729. return(1);
  111730. }
  111731. memset(out,0,sizeof(*out)*look->n[vb->W]);
  111732. return(0);
  111733. }
  111734. /* export hooks */
  111735. vorbis_func_floor floor0_exportbundle={
  111736. NULL,&floor0_unpack,&floor0_look,&floor0_free_info,
  111737. &floor0_free_look,&floor0_inverse1,&floor0_inverse2
  111738. };
  111739. #endif
  111740. /*** End of inlined file: floor0.c ***/
  111741. /*** Start of inlined file: floor1.c ***/
  111742. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  111743. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111744. // tasks..
  111745. #if JUCE_MSVC
  111746. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111747. #endif
  111748. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  111749. #if JUCE_USE_OGGVORBIS
  111750. #include <stdlib.h>
  111751. #include <string.h>
  111752. #include <math.h>
  111753. #include <stdio.h>
  111754. #define floor1_rangedB 140 /* floor 1 fixed at -140dB to 0dB range */
  111755. typedef struct {
  111756. int sorted_index[VIF_POSIT+2];
  111757. int forward_index[VIF_POSIT+2];
  111758. int reverse_index[VIF_POSIT+2];
  111759. int hineighbor[VIF_POSIT];
  111760. int loneighbor[VIF_POSIT];
  111761. int posts;
  111762. int n;
  111763. int quant_q;
  111764. vorbis_info_floor1 *vi;
  111765. long phrasebits;
  111766. long postbits;
  111767. long frames;
  111768. } vorbis_look_floor1;
  111769. typedef struct lsfit_acc{
  111770. long x0;
  111771. long x1;
  111772. long xa;
  111773. long ya;
  111774. long x2a;
  111775. long y2a;
  111776. long xya;
  111777. long an;
  111778. } lsfit_acc;
  111779. /***********************************************/
  111780. static void floor1_free_info(vorbis_info_floor *i){
  111781. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  111782. if(info){
  111783. memset(info,0,sizeof(*info));
  111784. _ogg_free(info);
  111785. }
  111786. }
  111787. static void floor1_free_look(vorbis_look_floor *i){
  111788. vorbis_look_floor1 *look=(vorbis_look_floor1 *)i;
  111789. if(look){
  111790. /*fprintf(stderr,"floor 1 bit usage %f:%f (%f total)\n",
  111791. (float)look->phrasebits/look->frames,
  111792. (float)look->postbits/look->frames,
  111793. (float)(look->postbits+look->phrasebits)/look->frames);*/
  111794. memset(look,0,sizeof(*look));
  111795. _ogg_free(look);
  111796. }
  111797. }
  111798. static void floor1_pack (vorbis_info_floor *i,oggpack_buffer *opb){
  111799. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  111800. int j,k;
  111801. int count=0;
  111802. int rangebits;
  111803. int maxposit=info->postlist[1];
  111804. int maxclass=-1;
  111805. /* save out partitions */
  111806. oggpack_write(opb,info->partitions,5); /* only 0 to 31 legal */
  111807. for(j=0;j<info->partitions;j++){
  111808. oggpack_write(opb,info->partitionclass[j],4); /* only 0 to 15 legal */
  111809. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  111810. }
  111811. /* save out partition classes */
  111812. for(j=0;j<maxclass+1;j++){
  111813. oggpack_write(opb,info->class_dim[j]-1,3); /* 1 to 8 */
  111814. oggpack_write(opb,info->class_subs[j],2); /* 0 to 3 */
  111815. if(info->class_subs[j])oggpack_write(opb,info->class_book[j],8);
  111816. for(k=0;k<(1<<info->class_subs[j]);k++)
  111817. oggpack_write(opb,info->class_subbook[j][k]+1,8);
  111818. }
  111819. /* save out the post list */
  111820. oggpack_write(opb,info->mult-1,2); /* only 1,2,3,4 legal now */
  111821. oggpack_write(opb,ilog2(maxposit),4);
  111822. rangebits=ilog2(maxposit);
  111823. for(j=0,k=0;j<info->partitions;j++){
  111824. count+=info->class_dim[info->partitionclass[j]];
  111825. for(;k<count;k++)
  111826. oggpack_write(opb,info->postlist[k+2],rangebits);
  111827. }
  111828. }
  111829. static vorbis_info_floor *floor1_unpack (vorbis_info *vi,oggpack_buffer *opb){
  111830. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111831. int j,k,count=0,maxclass=-1,rangebits;
  111832. vorbis_info_floor1 *info=(vorbis_info_floor1*)_ogg_calloc(1,sizeof(*info));
  111833. /* read partitions */
  111834. info->partitions=oggpack_read(opb,5); /* only 0 to 31 legal */
  111835. for(j=0;j<info->partitions;j++){
  111836. info->partitionclass[j]=oggpack_read(opb,4); /* only 0 to 15 legal */
  111837. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  111838. }
  111839. /* read partition classes */
  111840. for(j=0;j<maxclass+1;j++){
  111841. info->class_dim[j]=oggpack_read(opb,3)+1; /* 1 to 8 */
  111842. info->class_subs[j]=oggpack_read(opb,2); /* 0,1,2,3 bits */
  111843. if(info->class_subs[j]<0)
  111844. goto err_out;
  111845. if(info->class_subs[j])info->class_book[j]=oggpack_read(opb,8);
  111846. if(info->class_book[j]<0 || info->class_book[j]>=ci->books)
  111847. goto err_out;
  111848. for(k=0;k<(1<<info->class_subs[j]);k++){
  111849. info->class_subbook[j][k]=oggpack_read(opb,8)-1;
  111850. if(info->class_subbook[j][k]<-1 || info->class_subbook[j][k]>=ci->books)
  111851. goto err_out;
  111852. }
  111853. }
  111854. /* read the post list */
  111855. info->mult=oggpack_read(opb,2)+1; /* only 1,2,3,4 legal now */
  111856. rangebits=oggpack_read(opb,4);
  111857. for(j=0,k=0;j<info->partitions;j++){
  111858. count+=info->class_dim[info->partitionclass[j]];
  111859. for(;k<count;k++){
  111860. int t=info->postlist[k+2]=oggpack_read(opb,rangebits);
  111861. if(t<0 || t>=(1<<rangebits))
  111862. goto err_out;
  111863. }
  111864. }
  111865. info->postlist[0]=0;
  111866. info->postlist[1]=1<<rangebits;
  111867. return(info);
  111868. err_out:
  111869. floor1_free_info(info);
  111870. return(NULL);
  111871. }
  111872. static int icomp(const void *a,const void *b){
  111873. return(**(int **)a-**(int **)b);
  111874. }
  111875. static vorbis_look_floor *floor1_look(vorbis_dsp_state *vd,
  111876. vorbis_info_floor *in){
  111877. int *sortpointer[VIF_POSIT+2];
  111878. vorbis_info_floor1 *info=(vorbis_info_floor1*)in;
  111879. vorbis_look_floor1 *look=(vorbis_look_floor1*)_ogg_calloc(1,sizeof(*look));
  111880. int i,j,n=0;
  111881. look->vi=info;
  111882. look->n=info->postlist[1];
  111883. /* we drop each position value in-between already decoded values,
  111884. and use linear interpolation to predict each new value past the
  111885. edges. The positions are read in the order of the position
  111886. list... we precompute the bounding positions in the lookup. Of
  111887. course, the neighbors can change (if a position is declined), but
  111888. this is an initial mapping */
  111889. for(i=0;i<info->partitions;i++)n+=info->class_dim[info->partitionclass[i]];
  111890. n+=2;
  111891. look->posts=n;
  111892. /* also store a sorted position index */
  111893. for(i=0;i<n;i++)sortpointer[i]=info->postlist+i;
  111894. qsort(sortpointer,n,sizeof(*sortpointer),icomp);
  111895. /* points from sort order back to range number */
  111896. for(i=0;i<n;i++)look->forward_index[i]=sortpointer[i]-info->postlist;
  111897. /* points from range order to sorted position */
  111898. for(i=0;i<n;i++)look->reverse_index[look->forward_index[i]]=i;
  111899. /* we actually need the post values too */
  111900. for(i=0;i<n;i++)look->sorted_index[i]=info->postlist[look->forward_index[i]];
  111901. /* quantize values to multiplier spec */
  111902. switch(info->mult){
  111903. case 1: /* 1024 -> 256 */
  111904. look->quant_q=256;
  111905. break;
  111906. case 2: /* 1024 -> 128 */
  111907. look->quant_q=128;
  111908. break;
  111909. case 3: /* 1024 -> 86 */
  111910. look->quant_q=86;
  111911. break;
  111912. case 4: /* 1024 -> 64 */
  111913. look->quant_q=64;
  111914. break;
  111915. }
  111916. /* discover our neighbors for decode where we don't use fit flags
  111917. (that would push the neighbors outward) */
  111918. for(i=0;i<n-2;i++){
  111919. int lo=0;
  111920. int hi=1;
  111921. int lx=0;
  111922. int hx=look->n;
  111923. int currentx=info->postlist[i+2];
  111924. for(j=0;j<i+2;j++){
  111925. int x=info->postlist[j];
  111926. if(x>lx && x<currentx){
  111927. lo=j;
  111928. lx=x;
  111929. }
  111930. if(x<hx && x>currentx){
  111931. hi=j;
  111932. hx=x;
  111933. }
  111934. }
  111935. look->loneighbor[i]=lo;
  111936. look->hineighbor[i]=hi;
  111937. }
  111938. return(look);
  111939. }
  111940. static int render_point(int x0,int x1,int y0,int y1,int x){
  111941. y0&=0x7fff; /* mask off flag */
  111942. y1&=0x7fff;
  111943. {
  111944. int dy=y1-y0;
  111945. int adx=x1-x0;
  111946. int ady=abs(dy);
  111947. int err=ady*(x-x0);
  111948. int off=err/adx;
  111949. if(dy<0)return(y0-off);
  111950. return(y0+off);
  111951. }
  111952. }
  111953. static int vorbis_dBquant(const float *x){
  111954. int i= *x*7.3142857f+1023.5f;
  111955. if(i>1023)return(1023);
  111956. if(i<0)return(0);
  111957. return i;
  111958. }
  111959. static float FLOOR1_fromdB_LOOKUP[256]={
  111960. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  111961. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  111962. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  111963. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  111964. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  111965. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  111966. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  111967. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  111968. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  111969. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  111970. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  111971. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  111972. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  111973. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  111974. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  111975. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  111976. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  111977. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  111978. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  111979. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  111980. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  111981. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  111982. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  111983. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  111984. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  111985. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  111986. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  111987. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  111988. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  111989. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  111990. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  111991. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  111992. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  111993. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  111994. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  111995. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  111996. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  111997. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  111998. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  111999. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  112000. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  112001. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  112002. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  112003. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  112004. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  112005. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  112006. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  112007. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  112008. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  112009. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  112010. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  112011. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  112012. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  112013. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  112014. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  112015. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  112016. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  112017. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  112018. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  112019. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  112020. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  112021. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  112022. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  112023. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  112024. };
  112025. static void render_line(int x0,int x1,int y0,int y1,float *d){
  112026. int dy=y1-y0;
  112027. int adx=x1-x0;
  112028. int ady=abs(dy);
  112029. int base=dy/adx;
  112030. int sy=(dy<0?base-1:base+1);
  112031. int x=x0;
  112032. int y=y0;
  112033. int err=0;
  112034. ady-=abs(base*adx);
  112035. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  112036. while(++x<x1){
  112037. err=err+ady;
  112038. if(err>=adx){
  112039. err-=adx;
  112040. y+=sy;
  112041. }else{
  112042. y+=base;
  112043. }
  112044. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  112045. }
  112046. }
  112047. static void render_line0(int x0,int x1,int y0,int y1,int *d){
  112048. int dy=y1-y0;
  112049. int adx=x1-x0;
  112050. int ady=abs(dy);
  112051. int base=dy/adx;
  112052. int sy=(dy<0?base-1:base+1);
  112053. int x=x0;
  112054. int y=y0;
  112055. int err=0;
  112056. ady-=abs(base*adx);
  112057. d[x]=y;
  112058. while(++x<x1){
  112059. err=err+ady;
  112060. if(err>=adx){
  112061. err-=adx;
  112062. y+=sy;
  112063. }else{
  112064. y+=base;
  112065. }
  112066. d[x]=y;
  112067. }
  112068. }
  112069. /* the floor has already been filtered to only include relevant sections */
  112070. static int accumulate_fit(const float *flr,const float *mdct,
  112071. int x0, int x1,lsfit_acc *a,
  112072. int n,vorbis_info_floor1 *info){
  112073. long i;
  112074. 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;
  112075. memset(a,0,sizeof(*a));
  112076. a->x0=x0;
  112077. a->x1=x1;
  112078. if(x1>=n)x1=n-1;
  112079. for(i=x0;i<=x1;i++){
  112080. int quantized=vorbis_dBquant(flr+i);
  112081. if(quantized){
  112082. if(mdct[i]+info->twofitatten>=flr[i]){
  112083. xa += i;
  112084. ya += quantized;
  112085. x2a += i*i;
  112086. y2a += quantized*quantized;
  112087. xya += i*quantized;
  112088. na++;
  112089. }else{
  112090. xb += i;
  112091. yb += quantized;
  112092. x2b += i*i;
  112093. y2b += quantized*quantized;
  112094. xyb += i*quantized;
  112095. nb++;
  112096. }
  112097. }
  112098. }
  112099. xb+=xa;
  112100. yb+=ya;
  112101. x2b+=x2a;
  112102. y2b+=y2a;
  112103. xyb+=xya;
  112104. nb+=na;
  112105. /* weight toward the actually used frequencies if we meet the threshhold */
  112106. {
  112107. int weight=nb*info->twofitweight/(na+1);
  112108. a->xa=xa*weight+xb;
  112109. a->ya=ya*weight+yb;
  112110. a->x2a=x2a*weight+x2b;
  112111. a->y2a=y2a*weight+y2b;
  112112. a->xya=xya*weight+xyb;
  112113. a->an=na*weight+nb;
  112114. }
  112115. return(na);
  112116. }
  112117. static void fit_line(lsfit_acc *a,int fits,int *y0,int *y1){
  112118. long x=0,y=0,x2=0,y2=0,xy=0,an=0,i;
  112119. long x0=a[0].x0;
  112120. long x1=a[fits-1].x1;
  112121. for(i=0;i<fits;i++){
  112122. x+=a[i].xa;
  112123. y+=a[i].ya;
  112124. x2+=a[i].x2a;
  112125. y2+=a[i].y2a;
  112126. xy+=a[i].xya;
  112127. an+=a[i].an;
  112128. }
  112129. if(*y0>=0){
  112130. x+= x0;
  112131. y+= *y0;
  112132. x2+= x0 * x0;
  112133. y2+= *y0 * *y0;
  112134. xy+= *y0 * x0;
  112135. an++;
  112136. }
  112137. if(*y1>=0){
  112138. x+= x1;
  112139. y+= *y1;
  112140. x2+= x1 * x1;
  112141. y2+= *y1 * *y1;
  112142. xy+= *y1 * x1;
  112143. an++;
  112144. }
  112145. if(an){
  112146. /* need 64 bit multiplies, which C doesn't give portably as int */
  112147. double fx=x;
  112148. double fy=y;
  112149. double fx2=x2;
  112150. double fxy=xy;
  112151. double denom=1./(an*fx2-fx*fx);
  112152. double a=(fy*fx2-fxy*fx)*denom;
  112153. double b=(an*fxy-fx*fy)*denom;
  112154. *y0=rint(a+b*x0);
  112155. *y1=rint(a+b*x1);
  112156. /* limit to our range! */
  112157. if(*y0>1023)*y0=1023;
  112158. if(*y1>1023)*y1=1023;
  112159. if(*y0<0)*y0=0;
  112160. if(*y1<0)*y1=0;
  112161. }else{
  112162. *y0=0;
  112163. *y1=0;
  112164. }
  112165. }
  112166. /*static void fit_line_point(lsfit_acc *a,int fits,int *y0,int *y1){
  112167. long y=0;
  112168. int i;
  112169. for(i=0;i<fits && y==0;i++)
  112170. y+=a[i].ya;
  112171. *y0=*y1=y;
  112172. }*/
  112173. static int inspect_error(int x0,int x1,int y0,int y1,const float *mask,
  112174. const float *mdct,
  112175. vorbis_info_floor1 *info){
  112176. int dy=y1-y0;
  112177. int adx=x1-x0;
  112178. int ady=abs(dy);
  112179. int base=dy/adx;
  112180. int sy=(dy<0?base-1:base+1);
  112181. int x=x0;
  112182. int y=y0;
  112183. int err=0;
  112184. int val=vorbis_dBquant(mask+x);
  112185. int mse=0;
  112186. int n=0;
  112187. ady-=abs(base*adx);
  112188. mse=(y-val);
  112189. mse*=mse;
  112190. n++;
  112191. if(mdct[x]+info->twofitatten>=mask[x]){
  112192. if(y+info->maxover<val)return(1);
  112193. if(y-info->maxunder>val)return(1);
  112194. }
  112195. while(++x<x1){
  112196. err=err+ady;
  112197. if(err>=adx){
  112198. err-=adx;
  112199. y+=sy;
  112200. }else{
  112201. y+=base;
  112202. }
  112203. val=vorbis_dBquant(mask+x);
  112204. mse+=((y-val)*(y-val));
  112205. n++;
  112206. if(mdct[x]+info->twofitatten>=mask[x]){
  112207. if(val){
  112208. if(y+info->maxover<val)return(1);
  112209. if(y-info->maxunder>val)return(1);
  112210. }
  112211. }
  112212. }
  112213. if(info->maxover*info->maxover/n>info->maxerr)return(0);
  112214. if(info->maxunder*info->maxunder/n>info->maxerr)return(0);
  112215. if(mse/n>info->maxerr)return(1);
  112216. return(0);
  112217. }
  112218. static int post_Y(int *A,int *B,int pos){
  112219. if(A[pos]<0)
  112220. return B[pos];
  112221. if(B[pos]<0)
  112222. return A[pos];
  112223. return (A[pos]+B[pos])>>1;
  112224. }
  112225. int *floor1_fit(vorbis_block *vb,void *look_,
  112226. const float *logmdct, /* in */
  112227. const float *logmask){
  112228. long i,j;
  112229. vorbis_look_floor1 *look = (vorbis_look_floor1*) look_;
  112230. vorbis_info_floor1 *info=look->vi;
  112231. long n=look->n;
  112232. long posts=look->posts;
  112233. long nonzero=0;
  112234. lsfit_acc fits[VIF_POSIT+1];
  112235. int fit_valueA[VIF_POSIT+2]; /* index by range list position */
  112236. int fit_valueB[VIF_POSIT+2]; /* index by range list position */
  112237. int loneighbor[VIF_POSIT+2]; /* sorted index of range list position (+2) */
  112238. int hineighbor[VIF_POSIT+2];
  112239. int *output=NULL;
  112240. int memo[VIF_POSIT+2];
  112241. for(i=0;i<posts;i++)fit_valueA[i]=-200; /* mark all unused */
  112242. for(i=0;i<posts;i++)fit_valueB[i]=-200; /* mark all unused */
  112243. for(i=0;i<posts;i++)loneighbor[i]=0; /* 0 for the implicit 0 post */
  112244. for(i=0;i<posts;i++)hineighbor[i]=1; /* 1 for the implicit post at n */
  112245. for(i=0;i<posts;i++)memo[i]=-1; /* no neighbor yet */
  112246. /* quantize the relevant floor points and collect them into line fit
  112247. structures (one per minimal division) at the same time */
  112248. if(posts==0){
  112249. nonzero+=accumulate_fit(logmask,logmdct,0,n,fits,n,info);
  112250. }else{
  112251. for(i=0;i<posts-1;i++)
  112252. nonzero+=accumulate_fit(logmask,logmdct,look->sorted_index[i],
  112253. look->sorted_index[i+1],fits+i,
  112254. n,info);
  112255. }
  112256. if(nonzero){
  112257. /* start by fitting the implicit base case.... */
  112258. int y0=-200;
  112259. int y1=-200;
  112260. fit_line(fits,posts-1,&y0,&y1);
  112261. fit_valueA[0]=y0;
  112262. fit_valueB[0]=y0;
  112263. fit_valueB[1]=y1;
  112264. fit_valueA[1]=y1;
  112265. /* Non degenerate case */
  112266. /* start progressive splitting. This is a greedy, non-optimal
  112267. algorithm, but simple and close enough to the best
  112268. answer. */
  112269. for(i=2;i<posts;i++){
  112270. int sortpos=look->reverse_index[i];
  112271. int ln=loneighbor[sortpos];
  112272. int hn=hineighbor[sortpos];
  112273. /* eliminate repeat searches of a particular range with a memo */
  112274. if(memo[ln]!=hn){
  112275. /* haven't performed this error search yet */
  112276. int lsortpos=look->reverse_index[ln];
  112277. int hsortpos=look->reverse_index[hn];
  112278. memo[ln]=hn;
  112279. {
  112280. /* A note: we want to bound/minimize *local*, not global, error */
  112281. int lx=info->postlist[ln];
  112282. int hx=info->postlist[hn];
  112283. int ly=post_Y(fit_valueA,fit_valueB,ln);
  112284. int hy=post_Y(fit_valueA,fit_valueB,hn);
  112285. if(ly==-1 || hy==-1){
  112286. exit(1);
  112287. }
  112288. if(inspect_error(lx,hx,ly,hy,logmask,logmdct,info)){
  112289. /* outside error bounds/begin search area. Split it. */
  112290. int ly0=-200;
  112291. int ly1=-200;
  112292. int hy0=-200;
  112293. int hy1=-200;
  112294. fit_line(fits+lsortpos,sortpos-lsortpos,&ly0,&ly1);
  112295. fit_line(fits+sortpos,hsortpos-sortpos,&hy0,&hy1);
  112296. /* store new edge values */
  112297. fit_valueB[ln]=ly0;
  112298. if(ln==0)fit_valueA[ln]=ly0;
  112299. fit_valueA[i]=ly1;
  112300. fit_valueB[i]=hy0;
  112301. fit_valueA[hn]=hy1;
  112302. if(hn==1)fit_valueB[hn]=hy1;
  112303. if(ly1>=0 || hy0>=0){
  112304. /* store new neighbor values */
  112305. for(j=sortpos-1;j>=0;j--)
  112306. if(hineighbor[j]==hn)
  112307. hineighbor[j]=i;
  112308. else
  112309. break;
  112310. for(j=sortpos+1;j<posts;j++)
  112311. if(loneighbor[j]==ln)
  112312. loneighbor[j]=i;
  112313. else
  112314. break;
  112315. }
  112316. }else{
  112317. fit_valueA[i]=-200;
  112318. fit_valueB[i]=-200;
  112319. }
  112320. }
  112321. }
  112322. }
  112323. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  112324. output[0]=post_Y(fit_valueA,fit_valueB,0);
  112325. output[1]=post_Y(fit_valueA,fit_valueB,1);
  112326. /* fill in posts marked as not using a fit; we will zero
  112327. back out to 'unused' when encoding them so long as curve
  112328. interpolation doesn't force them into use */
  112329. for(i=2;i<posts;i++){
  112330. int ln=look->loneighbor[i-2];
  112331. int hn=look->hineighbor[i-2];
  112332. int x0=info->postlist[ln];
  112333. int x1=info->postlist[hn];
  112334. int y0=output[ln];
  112335. int y1=output[hn];
  112336. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  112337. int vx=post_Y(fit_valueA,fit_valueB,i);
  112338. if(vx>=0 && predicted!=vx){
  112339. output[i]=vx;
  112340. }else{
  112341. output[i]= predicted|0x8000;
  112342. }
  112343. }
  112344. }
  112345. return(output);
  112346. }
  112347. int *floor1_interpolate_fit(vorbis_block *vb,void *look_,
  112348. int *A,int *B,
  112349. int del){
  112350. long i;
  112351. vorbis_look_floor1* look = (vorbis_look_floor1*) look_;
  112352. long posts=look->posts;
  112353. int *output=NULL;
  112354. if(A && B){
  112355. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  112356. for(i=0;i<posts;i++){
  112357. output[i]=((65536-del)*(A[i]&0x7fff)+del*(B[i]&0x7fff)+32768)>>16;
  112358. if(A[i]&0x8000 && B[i]&0x8000)output[i]|=0x8000;
  112359. }
  112360. }
  112361. return(output);
  112362. }
  112363. int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  112364. void*look_,
  112365. int *post,int *ilogmask){
  112366. long i,j;
  112367. vorbis_look_floor1 *look = (vorbis_look_floor1 *) look_;
  112368. vorbis_info_floor1 *info=look->vi;
  112369. long posts=look->posts;
  112370. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  112371. int out[VIF_POSIT+2];
  112372. static_codebook **sbooks=ci->book_param;
  112373. codebook *books=ci->fullbooks;
  112374. static long seq=0;
  112375. /* quantize values to multiplier spec */
  112376. if(post){
  112377. for(i=0;i<posts;i++){
  112378. int val=post[i]&0x7fff;
  112379. switch(info->mult){
  112380. case 1: /* 1024 -> 256 */
  112381. val>>=2;
  112382. break;
  112383. case 2: /* 1024 -> 128 */
  112384. val>>=3;
  112385. break;
  112386. case 3: /* 1024 -> 86 */
  112387. val/=12;
  112388. break;
  112389. case 4: /* 1024 -> 64 */
  112390. val>>=4;
  112391. break;
  112392. }
  112393. post[i]=val | (post[i]&0x8000);
  112394. }
  112395. out[0]=post[0];
  112396. out[1]=post[1];
  112397. /* find prediction values for each post and subtract them */
  112398. for(i=2;i<posts;i++){
  112399. int ln=look->loneighbor[i-2];
  112400. int hn=look->hineighbor[i-2];
  112401. int x0=info->postlist[ln];
  112402. int x1=info->postlist[hn];
  112403. int y0=post[ln];
  112404. int y1=post[hn];
  112405. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  112406. if((post[i]&0x8000) || (predicted==post[i])){
  112407. post[i]=predicted|0x8000; /* in case there was roundoff jitter
  112408. in interpolation */
  112409. out[i]=0;
  112410. }else{
  112411. int headroom=(look->quant_q-predicted<predicted?
  112412. look->quant_q-predicted:predicted);
  112413. int val=post[i]-predicted;
  112414. /* at this point the 'deviation' value is in the range +/- max
  112415. range, but the real, unique range can always be mapped to
  112416. only [0-maxrange). So we want to wrap the deviation into
  112417. this limited range, but do it in the way that least screws
  112418. an essentially gaussian probability distribution. */
  112419. if(val<0)
  112420. if(val<-headroom)
  112421. val=headroom-val-1;
  112422. else
  112423. val=-1-(val<<1);
  112424. else
  112425. if(val>=headroom)
  112426. val= val+headroom;
  112427. else
  112428. val<<=1;
  112429. out[i]=val;
  112430. post[ln]&=0x7fff;
  112431. post[hn]&=0x7fff;
  112432. }
  112433. }
  112434. /* we have everything we need. pack it out */
  112435. /* mark nontrivial floor */
  112436. oggpack_write(opb,1,1);
  112437. /* beginning/end post */
  112438. look->frames++;
  112439. look->postbits+=ilog(look->quant_q-1)*2;
  112440. oggpack_write(opb,out[0],ilog(look->quant_q-1));
  112441. oggpack_write(opb,out[1],ilog(look->quant_q-1));
  112442. /* partition by partition */
  112443. for(i=0,j=2;i<info->partitions;i++){
  112444. int classx=info->partitionclass[i];
  112445. int cdim=info->class_dim[classx];
  112446. int csubbits=info->class_subs[classx];
  112447. int csub=1<<csubbits;
  112448. int bookas[8]={0,0,0,0,0,0,0,0};
  112449. int cval=0;
  112450. int cshift=0;
  112451. int k,l;
  112452. /* generate the partition's first stage cascade value */
  112453. if(csubbits){
  112454. int maxval[8];
  112455. for(k=0;k<csub;k++){
  112456. int booknum=info->class_subbook[classx][k];
  112457. if(booknum<0){
  112458. maxval[k]=1;
  112459. }else{
  112460. maxval[k]=sbooks[info->class_subbook[classx][k]]->entries;
  112461. }
  112462. }
  112463. for(k=0;k<cdim;k++){
  112464. for(l=0;l<csub;l++){
  112465. int val=out[j+k];
  112466. if(val<maxval[l]){
  112467. bookas[k]=l;
  112468. break;
  112469. }
  112470. }
  112471. cval|= bookas[k]<<cshift;
  112472. cshift+=csubbits;
  112473. }
  112474. /* write it */
  112475. look->phrasebits+=
  112476. vorbis_book_encode(books+info->class_book[classx],cval,opb);
  112477. #ifdef TRAIN_FLOOR1
  112478. {
  112479. FILE *of;
  112480. char buffer[80];
  112481. sprintf(buffer,"line_%dx%ld_class%d.vqd",
  112482. vb->pcmend/2,posts-2,class);
  112483. of=fopen(buffer,"a");
  112484. fprintf(of,"%d\n",cval);
  112485. fclose(of);
  112486. }
  112487. #endif
  112488. }
  112489. /* write post values */
  112490. for(k=0;k<cdim;k++){
  112491. int book=info->class_subbook[classx][bookas[k]];
  112492. if(book>=0){
  112493. /* hack to allow training with 'bad' books */
  112494. if(out[j+k]<(books+book)->entries)
  112495. look->postbits+=vorbis_book_encode(books+book,
  112496. out[j+k],opb);
  112497. /*else
  112498. fprintf(stderr,"+!");*/
  112499. #ifdef TRAIN_FLOOR1
  112500. {
  112501. FILE *of;
  112502. char buffer[80];
  112503. sprintf(buffer,"line_%dx%ld_%dsub%d.vqd",
  112504. vb->pcmend/2,posts-2,class,bookas[k]);
  112505. of=fopen(buffer,"a");
  112506. fprintf(of,"%d\n",out[j+k]);
  112507. fclose(of);
  112508. }
  112509. #endif
  112510. }
  112511. }
  112512. j+=cdim;
  112513. }
  112514. {
  112515. /* generate quantized floor equivalent to what we'd unpack in decode */
  112516. /* render the lines */
  112517. int hx=0;
  112518. int lx=0;
  112519. int ly=post[0]*info->mult;
  112520. for(j=1;j<look->posts;j++){
  112521. int current=look->forward_index[j];
  112522. int hy=post[current]&0x7fff;
  112523. if(hy==post[current]){
  112524. hy*=info->mult;
  112525. hx=info->postlist[current];
  112526. render_line0(lx,hx,ly,hy,ilogmask);
  112527. lx=hx;
  112528. ly=hy;
  112529. }
  112530. }
  112531. for(j=hx;j<vb->pcmend/2;j++)ilogmask[j]=ly; /* be certain */
  112532. seq++;
  112533. return(1);
  112534. }
  112535. }else{
  112536. oggpack_write(opb,0,1);
  112537. memset(ilogmask,0,vb->pcmend/2*sizeof(*ilogmask));
  112538. seq++;
  112539. return(0);
  112540. }
  112541. }
  112542. static void *floor1_inverse1(vorbis_block *vb,vorbis_look_floor *in){
  112543. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  112544. vorbis_info_floor1 *info=look->vi;
  112545. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  112546. int i,j,k;
  112547. codebook *books=ci->fullbooks;
  112548. /* unpack wrapped/predicted values from stream */
  112549. if(oggpack_read(&vb->opb,1)==1){
  112550. int *fit_value=(int*)_vorbis_block_alloc(vb,(look->posts)*sizeof(*fit_value));
  112551. fit_value[0]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  112552. fit_value[1]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  112553. /* partition by partition */
  112554. for(i=0,j=2;i<info->partitions;i++){
  112555. int classx=info->partitionclass[i];
  112556. int cdim=info->class_dim[classx];
  112557. int csubbits=info->class_subs[classx];
  112558. int csub=1<<csubbits;
  112559. int cval=0;
  112560. /* decode the partition's first stage cascade value */
  112561. if(csubbits){
  112562. cval=vorbis_book_decode(books+info->class_book[classx],&vb->opb);
  112563. if(cval==-1)goto eop;
  112564. }
  112565. for(k=0;k<cdim;k++){
  112566. int book=info->class_subbook[classx][cval&(csub-1)];
  112567. cval>>=csubbits;
  112568. if(book>=0){
  112569. if((fit_value[j+k]=vorbis_book_decode(books+book,&vb->opb))==-1)
  112570. goto eop;
  112571. }else{
  112572. fit_value[j+k]=0;
  112573. }
  112574. }
  112575. j+=cdim;
  112576. }
  112577. /* unwrap positive values and reconsitute via linear interpolation */
  112578. for(i=2;i<look->posts;i++){
  112579. int predicted=render_point(info->postlist[look->loneighbor[i-2]],
  112580. info->postlist[look->hineighbor[i-2]],
  112581. fit_value[look->loneighbor[i-2]],
  112582. fit_value[look->hineighbor[i-2]],
  112583. info->postlist[i]);
  112584. int hiroom=look->quant_q-predicted;
  112585. int loroom=predicted;
  112586. int room=(hiroom<loroom?hiroom:loroom)<<1;
  112587. int val=fit_value[i];
  112588. if(val){
  112589. if(val>=room){
  112590. if(hiroom>loroom){
  112591. val = val-loroom;
  112592. }else{
  112593. val = -1-(val-hiroom);
  112594. }
  112595. }else{
  112596. if(val&1){
  112597. val= -((val+1)>>1);
  112598. }else{
  112599. val>>=1;
  112600. }
  112601. }
  112602. fit_value[i]=val+predicted;
  112603. fit_value[look->loneighbor[i-2]]&=0x7fff;
  112604. fit_value[look->hineighbor[i-2]]&=0x7fff;
  112605. }else{
  112606. fit_value[i]=predicted|0x8000;
  112607. }
  112608. }
  112609. return(fit_value);
  112610. }
  112611. eop:
  112612. return(NULL);
  112613. }
  112614. static int floor1_inverse2(vorbis_block *vb,vorbis_look_floor *in,void *memo,
  112615. float *out){
  112616. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  112617. vorbis_info_floor1 *info=look->vi;
  112618. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  112619. int n=ci->blocksizes[vb->W]/2;
  112620. int j;
  112621. if(memo){
  112622. /* render the lines */
  112623. int *fit_value=(int *)memo;
  112624. int hx=0;
  112625. int lx=0;
  112626. int ly=fit_value[0]*info->mult;
  112627. for(j=1;j<look->posts;j++){
  112628. int current=look->forward_index[j];
  112629. int hy=fit_value[current]&0x7fff;
  112630. if(hy==fit_value[current]){
  112631. hy*=info->mult;
  112632. hx=info->postlist[current];
  112633. render_line(lx,hx,ly,hy,out);
  112634. lx=hx;
  112635. ly=hy;
  112636. }
  112637. }
  112638. for(j=hx;j<n;j++)out[j]*=FLOOR1_fromdB_LOOKUP[ly]; /* be certain */
  112639. return(1);
  112640. }
  112641. memset(out,0,sizeof(*out)*n);
  112642. return(0);
  112643. }
  112644. /* export hooks */
  112645. vorbis_func_floor floor1_exportbundle={
  112646. &floor1_pack,&floor1_unpack,&floor1_look,&floor1_free_info,
  112647. &floor1_free_look,&floor1_inverse1,&floor1_inverse2
  112648. };
  112649. #endif
  112650. /*** End of inlined file: floor1.c ***/
  112651. /*** Start of inlined file: info.c ***/
  112652. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112653. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112654. // tasks..
  112655. #if JUCE_MSVC
  112656. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112657. #endif
  112658. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112659. #if JUCE_USE_OGGVORBIS
  112660. /* general handling of the header and the vorbis_info structure (and
  112661. substructures) */
  112662. #include <stdlib.h>
  112663. #include <string.h>
  112664. #include <ctype.h>
  112665. static void _v_writestring(oggpack_buffer *o, const char *s, int bytes){
  112666. while(bytes--){
  112667. oggpack_write(o,*s++,8);
  112668. }
  112669. }
  112670. static void _v_readstring(oggpack_buffer *o,char *buf,int bytes){
  112671. while(bytes--){
  112672. *buf++=oggpack_read(o,8);
  112673. }
  112674. }
  112675. void vorbis_comment_init(vorbis_comment *vc){
  112676. memset(vc,0,sizeof(*vc));
  112677. }
  112678. void vorbis_comment_add(vorbis_comment *vc,char *comment){
  112679. vc->user_comments=(char**)_ogg_realloc(vc->user_comments,
  112680. (vc->comments+2)*sizeof(*vc->user_comments));
  112681. vc->comment_lengths=(int*)_ogg_realloc(vc->comment_lengths,
  112682. (vc->comments+2)*sizeof(*vc->comment_lengths));
  112683. vc->comment_lengths[vc->comments]=strlen(comment);
  112684. vc->user_comments[vc->comments]=(char*)_ogg_malloc(vc->comment_lengths[vc->comments]+1);
  112685. strcpy(vc->user_comments[vc->comments], comment);
  112686. vc->comments++;
  112687. vc->user_comments[vc->comments]=NULL;
  112688. }
  112689. void vorbis_comment_add_tag(vorbis_comment *vc, const char *tag, char *contents){
  112690. char *comment=(char*)alloca(strlen(tag)+strlen(contents)+2); /* +2 for = and \0 */
  112691. strcpy(comment, tag);
  112692. strcat(comment, "=");
  112693. strcat(comment, contents);
  112694. vorbis_comment_add(vc, comment);
  112695. }
  112696. /* This is more or less the same as strncasecmp - but that doesn't exist
  112697. * everywhere, and this is a fairly trivial function, so we include it */
  112698. static int tagcompare(const char *s1, const char *s2, int n){
  112699. int c=0;
  112700. while(c < n){
  112701. if(toupper(s1[c]) != toupper(s2[c]))
  112702. return !0;
  112703. c++;
  112704. }
  112705. return 0;
  112706. }
  112707. char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count){
  112708. long i;
  112709. int found = 0;
  112710. int taglen = strlen(tag)+1; /* +1 for the = we append */
  112711. char *fulltag = (char*)alloca(taglen+ 1);
  112712. strcpy(fulltag, tag);
  112713. strcat(fulltag, "=");
  112714. for(i=0;i<vc->comments;i++){
  112715. if(!tagcompare(vc->user_comments[i], fulltag, taglen)){
  112716. if(count == found)
  112717. /* We return a pointer to the data, not a copy */
  112718. return vc->user_comments[i] + taglen;
  112719. else
  112720. found++;
  112721. }
  112722. }
  112723. return NULL; /* didn't find anything */
  112724. }
  112725. int vorbis_comment_query_count(vorbis_comment *vc, char *tag){
  112726. int i,count=0;
  112727. int taglen = strlen(tag)+1; /* +1 for the = we append */
  112728. char *fulltag = (char*)alloca(taglen+1);
  112729. strcpy(fulltag,tag);
  112730. strcat(fulltag, "=");
  112731. for(i=0;i<vc->comments;i++){
  112732. if(!tagcompare(vc->user_comments[i], fulltag, taglen))
  112733. count++;
  112734. }
  112735. return count;
  112736. }
  112737. void vorbis_comment_clear(vorbis_comment *vc){
  112738. if(vc){
  112739. long i;
  112740. for(i=0;i<vc->comments;i++)
  112741. if(vc->user_comments[i])_ogg_free(vc->user_comments[i]);
  112742. if(vc->user_comments)_ogg_free(vc->user_comments);
  112743. if(vc->comment_lengths)_ogg_free(vc->comment_lengths);
  112744. if(vc->vendor)_ogg_free(vc->vendor);
  112745. }
  112746. memset(vc,0,sizeof(*vc));
  112747. }
  112748. /* blocksize 0 is guaranteed to be short, 1 is guarantted to be long.
  112749. They may be equal, but short will never ge greater than long */
  112750. int vorbis_info_blocksize(vorbis_info *vi,int zo){
  112751. codec_setup_info *ci = (codec_setup_info*)vi->codec_setup;
  112752. return ci ? ci->blocksizes[zo] : -1;
  112753. }
  112754. /* used by synthesis, which has a full, alloced vi */
  112755. void vorbis_info_init(vorbis_info *vi){
  112756. memset(vi,0,sizeof(*vi));
  112757. vi->codec_setup=_ogg_calloc(1,sizeof(codec_setup_info));
  112758. }
  112759. void vorbis_info_clear(vorbis_info *vi){
  112760. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112761. int i;
  112762. if(ci){
  112763. for(i=0;i<ci->modes;i++)
  112764. if(ci->mode_param[i])_ogg_free(ci->mode_param[i]);
  112765. for(i=0;i<ci->maps;i++) /* unpack does the range checking */
  112766. _mapping_P[ci->map_type[i]]->free_info(ci->map_param[i]);
  112767. for(i=0;i<ci->floors;i++) /* unpack does the range checking */
  112768. _floor_P[ci->floor_type[i]]->free_info(ci->floor_param[i]);
  112769. for(i=0;i<ci->residues;i++) /* unpack does the range checking */
  112770. _residue_P[ci->residue_type[i]]->free_info(ci->residue_param[i]);
  112771. for(i=0;i<ci->books;i++){
  112772. if(ci->book_param[i]){
  112773. /* knows if the book was not alloced */
  112774. vorbis_staticbook_destroy(ci->book_param[i]);
  112775. }
  112776. if(ci->fullbooks)
  112777. vorbis_book_clear(ci->fullbooks+i);
  112778. }
  112779. if(ci->fullbooks)
  112780. _ogg_free(ci->fullbooks);
  112781. for(i=0;i<ci->psys;i++)
  112782. _vi_psy_free(ci->psy_param[i]);
  112783. _ogg_free(ci);
  112784. }
  112785. memset(vi,0,sizeof(*vi));
  112786. }
  112787. /* Header packing/unpacking ********************************************/
  112788. static int _vorbis_unpack_info(vorbis_info *vi,oggpack_buffer *opb){
  112789. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112790. if(!ci)return(OV_EFAULT);
  112791. vi->version=oggpack_read(opb,32);
  112792. if(vi->version!=0)return(OV_EVERSION);
  112793. vi->channels=oggpack_read(opb,8);
  112794. vi->rate=oggpack_read(opb,32);
  112795. vi->bitrate_upper=oggpack_read(opb,32);
  112796. vi->bitrate_nominal=oggpack_read(opb,32);
  112797. vi->bitrate_lower=oggpack_read(opb,32);
  112798. ci->blocksizes[0]=1<<oggpack_read(opb,4);
  112799. ci->blocksizes[1]=1<<oggpack_read(opb,4);
  112800. if(vi->rate<1)goto err_out;
  112801. if(vi->channels<1)goto err_out;
  112802. if(ci->blocksizes[0]<8)goto err_out;
  112803. if(ci->blocksizes[1]<ci->blocksizes[0])goto err_out;
  112804. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  112805. return(0);
  112806. err_out:
  112807. vorbis_info_clear(vi);
  112808. return(OV_EBADHEADER);
  112809. }
  112810. static int _vorbis_unpack_comment(vorbis_comment *vc,oggpack_buffer *opb){
  112811. int i;
  112812. int vendorlen=oggpack_read(opb,32);
  112813. if(vendorlen<0)goto err_out;
  112814. vc->vendor=(char*)_ogg_calloc(vendorlen+1,1);
  112815. _v_readstring(opb,vc->vendor,vendorlen);
  112816. vc->comments=oggpack_read(opb,32);
  112817. if(vc->comments<0)goto err_out;
  112818. vc->user_comments=(char**)_ogg_calloc(vc->comments+1,sizeof(*vc->user_comments));
  112819. vc->comment_lengths=(int*)_ogg_calloc(vc->comments+1, sizeof(*vc->comment_lengths));
  112820. for(i=0;i<vc->comments;i++){
  112821. int len=oggpack_read(opb,32);
  112822. if(len<0)goto err_out;
  112823. vc->comment_lengths[i]=len;
  112824. vc->user_comments[i]=(char*)_ogg_calloc(len+1,1);
  112825. _v_readstring(opb,vc->user_comments[i],len);
  112826. }
  112827. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  112828. return(0);
  112829. err_out:
  112830. vorbis_comment_clear(vc);
  112831. return(OV_EBADHEADER);
  112832. }
  112833. /* all of the real encoding details are here. The modes, books,
  112834. everything */
  112835. static int _vorbis_unpack_books(vorbis_info *vi,oggpack_buffer *opb){
  112836. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112837. int i;
  112838. if(!ci)return(OV_EFAULT);
  112839. /* codebooks */
  112840. ci->books=oggpack_read(opb,8)+1;
  112841. /*ci->book_param=_ogg_calloc(ci->books,sizeof(*ci->book_param));*/
  112842. for(i=0;i<ci->books;i++){
  112843. ci->book_param[i]=(static_codebook*)_ogg_calloc(1,sizeof(*ci->book_param[i]));
  112844. if(vorbis_staticbook_unpack(opb,ci->book_param[i]))goto err_out;
  112845. }
  112846. /* time backend settings; hooks are unused */
  112847. {
  112848. int times=oggpack_read(opb,6)+1;
  112849. for(i=0;i<times;i++){
  112850. int test=oggpack_read(opb,16);
  112851. if(test<0 || test>=VI_TIMEB)goto err_out;
  112852. }
  112853. }
  112854. /* floor backend settings */
  112855. ci->floors=oggpack_read(opb,6)+1;
  112856. /*ci->floor_type=_ogg_malloc(ci->floors*sizeof(*ci->floor_type));*/
  112857. /*ci->floor_param=_ogg_calloc(ci->floors,sizeof(void *));*/
  112858. for(i=0;i<ci->floors;i++){
  112859. ci->floor_type[i]=oggpack_read(opb,16);
  112860. if(ci->floor_type[i]<0 || ci->floor_type[i]>=VI_FLOORB)goto err_out;
  112861. ci->floor_param[i]=_floor_P[ci->floor_type[i]]->unpack(vi,opb);
  112862. if(!ci->floor_param[i])goto err_out;
  112863. }
  112864. /* residue backend settings */
  112865. ci->residues=oggpack_read(opb,6)+1;
  112866. /*ci->residue_type=_ogg_malloc(ci->residues*sizeof(*ci->residue_type));*/
  112867. /*ci->residue_param=_ogg_calloc(ci->residues,sizeof(void *));*/
  112868. for(i=0;i<ci->residues;i++){
  112869. ci->residue_type[i]=oggpack_read(opb,16);
  112870. if(ci->residue_type[i]<0 || ci->residue_type[i]>=VI_RESB)goto err_out;
  112871. ci->residue_param[i]=_residue_P[ci->residue_type[i]]->unpack(vi,opb);
  112872. if(!ci->residue_param[i])goto err_out;
  112873. }
  112874. /* map backend settings */
  112875. ci->maps=oggpack_read(opb,6)+1;
  112876. /*ci->map_type=_ogg_malloc(ci->maps*sizeof(*ci->map_type));*/
  112877. /*ci->map_param=_ogg_calloc(ci->maps,sizeof(void *));*/
  112878. for(i=0;i<ci->maps;i++){
  112879. ci->map_type[i]=oggpack_read(opb,16);
  112880. if(ci->map_type[i]<0 || ci->map_type[i]>=VI_MAPB)goto err_out;
  112881. ci->map_param[i]=_mapping_P[ci->map_type[i]]->unpack(vi,opb);
  112882. if(!ci->map_param[i])goto err_out;
  112883. }
  112884. /* mode settings */
  112885. ci->modes=oggpack_read(opb,6)+1;
  112886. /*vi->mode_param=_ogg_calloc(vi->modes,sizeof(void *));*/
  112887. for(i=0;i<ci->modes;i++){
  112888. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*ci->mode_param[i]));
  112889. ci->mode_param[i]->blockflag=oggpack_read(opb,1);
  112890. ci->mode_param[i]->windowtype=oggpack_read(opb,16);
  112891. ci->mode_param[i]->transformtype=oggpack_read(opb,16);
  112892. ci->mode_param[i]->mapping=oggpack_read(opb,8);
  112893. if(ci->mode_param[i]->windowtype>=VI_WINDOWB)goto err_out;
  112894. if(ci->mode_param[i]->transformtype>=VI_WINDOWB)goto err_out;
  112895. if(ci->mode_param[i]->mapping>=ci->maps)goto err_out;
  112896. }
  112897. if(oggpack_read(opb,1)!=1)goto err_out; /* top level EOP check */
  112898. return(0);
  112899. err_out:
  112900. vorbis_info_clear(vi);
  112901. return(OV_EBADHEADER);
  112902. }
  112903. /* The Vorbis header is in three packets; the initial small packet in
  112904. the first page that identifies basic parameters, a second packet
  112905. with bitstream comments and a third packet that holds the
  112906. codebook. */
  112907. int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,ogg_packet *op){
  112908. oggpack_buffer opb;
  112909. if(op){
  112910. oggpack_readinit(&opb,op->packet,op->bytes);
  112911. /* Which of the three types of header is this? */
  112912. /* Also verify header-ness, vorbis */
  112913. {
  112914. char buffer[6];
  112915. int packtype=oggpack_read(&opb,8);
  112916. memset(buffer,0,6);
  112917. _v_readstring(&opb,buffer,6);
  112918. if(memcmp(buffer,"vorbis",6)){
  112919. /* not a vorbis header */
  112920. return(OV_ENOTVORBIS);
  112921. }
  112922. switch(packtype){
  112923. case 0x01: /* least significant *bit* is read first */
  112924. if(!op->b_o_s){
  112925. /* Not the initial packet */
  112926. return(OV_EBADHEADER);
  112927. }
  112928. if(vi->rate!=0){
  112929. /* previously initialized info header */
  112930. return(OV_EBADHEADER);
  112931. }
  112932. return(_vorbis_unpack_info(vi,&opb));
  112933. case 0x03: /* least significant *bit* is read first */
  112934. if(vi->rate==0){
  112935. /* um... we didn't get the initial header */
  112936. return(OV_EBADHEADER);
  112937. }
  112938. return(_vorbis_unpack_comment(vc,&opb));
  112939. case 0x05: /* least significant *bit* is read first */
  112940. if(vi->rate==0 || vc->vendor==NULL){
  112941. /* um... we didn;t get the initial header or comments yet */
  112942. return(OV_EBADHEADER);
  112943. }
  112944. return(_vorbis_unpack_books(vi,&opb));
  112945. default:
  112946. /* Not a valid vorbis header type */
  112947. return(OV_EBADHEADER);
  112948. break;
  112949. }
  112950. }
  112951. }
  112952. return(OV_EBADHEADER);
  112953. }
  112954. /* pack side **********************************************************/
  112955. static int _vorbis_pack_info(oggpack_buffer *opb,vorbis_info *vi){
  112956. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112957. if(!ci)return(OV_EFAULT);
  112958. /* preamble */
  112959. oggpack_write(opb,0x01,8);
  112960. _v_writestring(opb,"vorbis", 6);
  112961. /* basic information about the stream */
  112962. oggpack_write(opb,0x00,32);
  112963. oggpack_write(opb,vi->channels,8);
  112964. oggpack_write(opb,vi->rate,32);
  112965. oggpack_write(opb,vi->bitrate_upper,32);
  112966. oggpack_write(opb,vi->bitrate_nominal,32);
  112967. oggpack_write(opb,vi->bitrate_lower,32);
  112968. oggpack_write(opb,ilog2(ci->blocksizes[0]),4);
  112969. oggpack_write(opb,ilog2(ci->blocksizes[1]),4);
  112970. oggpack_write(opb,1,1);
  112971. return(0);
  112972. }
  112973. static int _vorbis_pack_comment(oggpack_buffer *opb,vorbis_comment *vc){
  112974. char temp[]="Xiph.Org libVorbis I 20050304";
  112975. int bytes = strlen(temp);
  112976. /* preamble */
  112977. oggpack_write(opb,0x03,8);
  112978. _v_writestring(opb,"vorbis", 6);
  112979. /* vendor */
  112980. oggpack_write(opb,bytes,32);
  112981. _v_writestring(opb,temp, bytes);
  112982. /* comments */
  112983. oggpack_write(opb,vc->comments,32);
  112984. if(vc->comments){
  112985. int i;
  112986. for(i=0;i<vc->comments;i++){
  112987. if(vc->user_comments[i]){
  112988. oggpack_write(opb,vc->comment_lengths[i],32);
  112989. _v_writestring(opb,vc->user_comments[i], vc->comment_lengths[i]);
  112990. }else{
  112991. oggpack_write(opb,0,32);
  112992. }
  112993. }
  112994. }
  112995. oggpack_write(opb,1,1);
  112996. return(0);
  112997. }
  112998. static int _vorbis_pack_books(oggpack_buffer *opb,vorbis_info *vi){
  112999. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113000. int i;
  113001. if(!ci)return(OV_EFAULT);
  113002. oggpack_write(opb,0x05,8);
  113003. _v_writestring(opb,"vorbis", 6);
  113004. /* books */
  113005. oggpack_write(opb,ci->books-1,8);
  113006. for(i=0;i<ci->books;i++)
  113007. if(vorbis_staticbook_pack(ci->book_param[i],opb))goto err_out;
  113008. /* times; hook placeholders */
  113009. oggpack_write(opb,0,6);
  113010. oggpack_write(opb,0,16);
  113011. /* floors */
  113012. oggpack_write(opb,ci->floors-1,6);
  113013. for(i=0;i<ci->floors;i++){
  113014. oggpack_write(opb,ci->floor_type[i],16);
  113015. if(_floor_P[ci->floor_type[i]]->pack)
  113016. _floor_P[ci->floor_type[i]]->pack(ci->floor_param[i],opb);
  113017. else
  113018. goto err_out;
  113019. }
  113020. /* residues */
  113021. oggpack_write(opb,ci->residues-1,6);
  113022. for(i=0;i<ci->residues;i++){
  113023. oggpack_write(opb,ci->residue_type[i],16);
  113024. _residue_P[ci->residue_type[i]]->pack(ci->residue_param[i],opb);
  113025. }
  113026. /* maps */
  113027. oggpack_write(opb,ci->maps-1,6);
  113028. for(i=0;i<ci->maps;i++){
  113029. oggpack_write(opb,ci->map_type[i],16);
  113030. _mapping_P[ci->map_type[i]]->pack(vi,ci->map_param[i],opb);
  113031. }
  113032. /* modes */
  113033. oggpack_write(opb,ci->modes-1,6);
  113034. for(i=0;i<ci->modes;i++){
  113035. oggpack_write(opb,ci->mode_param[i]->blockflag,1);
  113036. oggpack_write(opb,ci->mode_param[i]->windowtype,16);
  113037. oggpack_write(opb,ci->mode_param[i]->transformtype,16);
  113038. oggpack_write(opb,ci->mode_param[i]->mapping,8);
  113039. }
  113040. oggpack_write(opb,1,1);
  113041. return(0);
  113042. err_out:
  113043. return(-1);
  113044. }
  113045. int vorbis_commentheader_out(vorbis_comment *vc,
  113046. ogg_packet *op){
  113047. oggpack_buffer opb;
  113048. oggpack_writeinit(&opb);
  113049. if(_vorbis_pack_comment(&opb,vc)) return OV_EIMPL;
  113050. op->packet = (unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  113051. memcpy(op->packet, opb.buffer, oggpack_bytes(&opb));
  113052. op->bytes=oggpack_bytes(&opb);
  113053. op->b_o_s=0;
  113054. op->e_o_s=0;
  113055. op->granulepos=0;
  113056. op->packetno=1;
  113057. return 0;
  113058. }
  113059. int vorbis_analysis_headerout(vorbis_dsp_state *v,
  113060. vorbis_comment *vc,
  113061. ogg_packet *op,
  113062. ogg_packet *op_comm,
  113063. ogg_packet *op_code){
  113064. int ret=OV_EIMPL;
  113065. vorbis_info *vi=v->vi;
  113066. oggpack_buffer opb;
  113067. private_state *b=(private_state*)v->backend_state;
  113068. if(!b){
  113069. ret=OV_EFAULT;
  113070. goto err_out;
  113071. }
  113072. /* first header packet **********************************************/
  113073. oggpack_writeinit(&opb);
  113074. if(_vorbis_pack_info(&opb,vi))goto err_out;
  113075. /* build the packet */
  113076. if(b->header)_ogg_free(b->header);
  113077. b->header=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  113078. memcpy(b->header,opb.buffer,oggpack_bytes(&opb));
  113079. op->packet=b->header;
  113080. op->bytes=oggpack_bytes(&opb);
  113081. op->b_o_s=1;
  113082. op->e_o_s=0;
  113083. op->granulepos=0;
  113084. op->packetno=0;
  113085. /* second header packet (comments) **********************************/
  113086. oggpack_reset(&opb);
  113087. if(_vorbis_pack_comment(&opb,vc))goto err_out;
  113088. if(b->header1)_ogg_free(b->header1);
  113089. b->header1=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  113090. memcpy(b->header1,opb.buffer,oggpack_bytes(&opb));
  113091. op_comm->packet=b->header1;
  113092. op_comm->bytes=oggpack_bytes(&opb);
  113093. op_comm->b_o_s=0;
  113094. op_comm->e_o_s=0;
  113095. op_comm->granulepos=0;
  113096. op_comm->packetno=1;
  113097. /* third header packet (modes/codebooks) ****************************/
  113098. oggpack_reset(&opb);
  113099. if(_vorbis_pack_books(&opb,vi))goto err_out;
  113100. if(b->header2)_ogg_free(b->header2);
  113101. b->header2=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  113102. memcpy(b->header2,opb.buffer,oggpack_bytes(&opb));
  113103. op_code->packet=b->header2;
  113104. op_code->bytes=oggpack_bytes(&opb);
  113105. op_code->b_o_s=0;
  113106. op_code->e_o_s=0;
  113107. op_code->granulepos=0;
  113108. op_code->packetno=2;
  113109. oggpack_writeclear(&opb);
  113110. return(0);
  113111. err_out:
  113112. oggpack_writeclear(&opb);
  113113. memset(op,0,sizeof(*op));
  113114. memset(op_comm,0,sizeof(*op_comm));
  113115. memset(op_code,0,sizeof(*op_code));
  113116. if(b->header)_ogg_free(b->header);
  113117. if(b->header1)_ogg_free(b->header1);
  113118. if(b->header2)_ogg_free(b->header2);
  113119. b->header=NULL;
  113120. b->header1=NULL;
  113121. b->header2=NULL;
  113122. return(ret);
  113123. }
  113124. double vorbis_granule_time(vorbis_dsp_state *v,ogg_int64_t granulepos){
  113125. if(granulepos>=0)
  113126. return((double)granulepos/v->vi->rate);
  113127. return(-1);
  113128. }
  113129. #endif
  113130. /*** End of inlined file: info.c ***/
  113131. /*** Start of inlined file: lpc.c ***/
  113132. /* Some of these routines (autocorrelator, LPC coefficient estimator)
  113133. are derived from code written by Jutta Degener and Carsten Bormann;
  113134. thus we include their copyright below. The entirety of this file
  113135. is freely redistributable on the condition that both of these
  113136. copyright notices are preserved without modification. */
  113137. /* Preserved Copyright: *********************************************/
  113138. /* Copyright 1992, 1993, 1994 by Jutta Degener and Carsten Bormann,
  113139. Technische Universita"t Berlin
  113140. Any use of this software is permitted provided that this notice is not
  113141. removed and that neither the authors nor the Technische Universita"t
  113142. Berlin are deemed to have made any representations as to the
  113143. suitability of this software for any purpose nor are held responsible
  113144. for any defects of this software. THERE IS ABSOLUTELY NO WARRANTY FOR
  113145. THIS SOFTWARE.
  113146. As a matter of courtesy, the authors request to be informed about uses
  113147. this software has found, about bugs in this software, and about any
  113148. improvements that may be of general interest.
  113149. Berlin, 28.11.1994
  113150. Jutta Degener
  113151. Carsten Bormann
  113152. *********************************************************************/
  113153. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  113154. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113155. // tasks..
  113156. #if JUCE_MSVC
  113157. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113158. #endif
  113159. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  113160. #if JUCE_USE_OGGVORBIS
  113161. #include <stdlib.h>
  113162. #include <string.h>
  113163. #include <math.h>
  113164. /* Autocorrelation LPC coeff generation algorithm invented by
  113165. N. Levinson in 1947, modified by J. Durbin in 1959. */
  113166. /* Input : n elements of time doamin data
  113167. Output: m lpc coefficients, excitation energy */
  113168. float vorbis_lpc_from_data(float *data,float *lpci,int n,int m){
  113169. double *aut=(double*)alloca(sizeof(*aut)*(m+1));
  113170. double *lpc=(double*)alloca(sizeof(*lpc)*(m));
  113171. double error;
  113172. int i,j;
  113173. /* autocorrelation, p+1 lag coefficients */
  113174. j=m+1;
  113175. while(j--){
  113176. double d=0; /* double needed for accumulator depth */
  113177. for(i=j;i<n;i++)d+=(double)data[i]*data[i-j];
  113178. aut[j]=d;
  113179. }
  113180. /* Generate lpc coefficients from autocorr values */
  113181. error=aut[0];
  113182. for(i=0;i<m;i++){
  113183. double r= -aut[i+1];
  113184. if(error==0){
  113185. memset(lpci,0,m*sizeof(*lpci));
  113186. return 0;
  113187. }
  113188. /* Sum up this iteration's reflection coefficient; note that in
  113189. Vorbis we don't save it. If anyone wants to recycle this code
  113190. and needs reflection coefficients, save the results of 'r' from
  113191. each iteration. */
  113192. for(j=0;j<i;j++)r-=lpc[j]*aut[i-j];
  113193. r/=error;
  113194. /* Update LPC coefficients and total error */
  113195. lpc[i]=r;
  113196. for(j=0;j<i/2;j++){
  113197. double tmp=lpc[j];
  113198. lpc[j]+=r*lpc[i-1-j];
  113199. lpc[i-1-j]+=r*tmp;
  113200. }
  113201. if(i%2)lpc[j]+=lpc[j]*r;
  113202. error*=1.f-r*r;
  113203. }
  113204. for(j=0;j<m;j++)lpci[j]=(float)lpc[j];
  113205. /* we need the error value to know how big an impulse to hit the
  113206. filter with later */
  113207. return error;
  113208. }
  113209. void vorbis_lpc_predict(float *coeff,float *prime,int m,
  113210. float *data,long n){
  113211. /* in: coeff[0...m-1] LPC coefficients
  113212. prime[0...m-1] initial values (allocated size of n+m-1)
  113213. out: data[0...n-1] data samples */
  113214. long i,j,o,p;
  113215. float y;
  113216. float *work=(float*)alloca(sizeof(*work)*(m+n));
  113217. if(!prime)
  113218. for(i=0;i<m;i++)
  113219. work[i]=0.f;
  113220. else
  113221. for(i=0;i<m;i++)
  113222. work[i]=prime[i];
  113223. for(i=0;i<n;i++){
  113224. y=0;
  113225. o=i;
  113226. p=m;
  113227. for(j=0;j<m;j++)
  113228. y-=work[o++]*coeff[--p];
  113229. data[i]=work[o]=y;
  113230. }
  113231. }
  113232. #endif
  113233. /*** End of inlined file: lpc.c ***/
  113234. /*** Start of inlined file: lsp.c ***/
  113235. /* Note that the lpc-lsp conversion finds the roots of polynomial with
  113236. an iterative root polisher (CACM algorithm 283). It *is* possible
  113237. to confuse this algorithm into not converging; that should only
  113238. happen with absurdly closely spaced roots (very sharp peaks in the
  113239. LPC f response) which in turn should be impossible in our use of
  113240. the code. If this *does* happen anyway, it's a bug in the floor
  113241. finder; find the cause of the confusion (probably a single bin
  113242. spike or accidental near-float-limit resolution problems) and
  113243. correct it. */
  113244. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  113245. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113246. // tasks..
  113247. #if JUCE_MSVC
  113248. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113249. #endif
  113250. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  113251. #if JUCE_USE_OGGVORBIS
  113252. #include <math.h>
  113253. #include <string.h>
  113254. #include <stdlib.h>
  113255. /*** Start of inlined file: lookup.h ***/
  113256. #ifndef _V_LOOKUP_H_
  113257. #ifdef FLOAT_LOOKUP
  113258. extern float vorbis_coslook(float a);
  113259. extern float vorbis_invsqlook(float a);
  113260. extern float vorbis_invsq2explook(int a);
  113261. extern float vorbis_fromdBlook(float a);
  113262. #endif
  113263. #ifdef INT_LOOKUP
  113264. extern long vorbis_invsqlook_i(long a,long e);
  113265. extern long vorbis_coslook_i(long a);
  113266. extern float vorbis_fromdBlook_i(long a);
  113267. #endif
  113268. #endif
  113269. /*** End of inlined file: lookup.h ***/
  113270. /* three possible LSP to f curve functions; the exact computation
  113271. (float), a lookup based float implementation, and an integer
  113272. implementation. The float lookup is likely the optimal choice on
  113273. any machine with an FPU. The integer implementation is *not* fixed
  113274. point (due to the need for a large dynamic range and thus a
  113275. seperately tracked exponent) and thus much more complex than the
  113276. relatively simple float implementations. It's mostly for future
  113277. work on a fully fixed point implementation for processors like the
  113278. ARM family. */
  113279. /* undefine both for the 'old' but more precise implementation */
  113280. #define FLOAT_LOOKUP
  113281. #undef INT_LOOKUP
  113282. #ifdef FLOAT_LOOKUP
  113283. /*** Start of inlined file: lookup.c ***/
  113284. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  113285. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113286. // tasks..
  113287. #if JUCE_MSVC
  113288. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113289. #endif
  113290. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  113291. #if JUCE_USE_OGGVORBIS
  113292. #include <math.h>
  113293. /*** Start of inlined file: lookup.h ***/
  113294. #ifndef _V_LOOKUP_H_
  113295. #ifdef FLOAT_LOOKUP
  113296. extern float vorbis_coslook(float a);
  113297. extern float vorbis_invsqlook(float a);
  113298. extern float vorbis_invsq2explook(int a);
  113299. extern float vorbis_fromdBlook(float a);
  113300. #endif
  113301. #ifdef INT_LOOKUP
  113302. extern long vorbis_invsqlook_i(long a,long e);
  113303. extern long vorbis_coslook_i(long a);
  113304. extern float vorbis_fromdBlook_i(long a);
  113305. #endif
  113306. #endif
  113307. /*** End of inlined file: lookup.h ***/
  113308. /*** Start of inlined file: lookup_data.h ***/
  113309. #ifndef _V_LOOKUP_DATA_H_
  113310. #ifdef FLOAT_LOOKUP
  113311. #define COS_LOOKUP_SZ 128
  113312. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  113313. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  113314. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  113315. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  113316. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  113317. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  113318. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  113319. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  113320. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  113321. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  113322. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  113323. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  113324. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  113325. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  113326. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  113327. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  113328. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  113329. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  113330. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  113331. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  113332. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  113333. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  113334. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  113335. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  113336. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  113337. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  113338. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  113339. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  113340. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  113341. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  113342. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  113343. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  113344. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  113345. -1.0000000000000f,
  113346. };
  113347. #define INVSQ_LOOKUP_SZ 32
  113348. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  113349. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  113350. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  113351. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  113352. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  113353. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  113354. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  113355. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  113356. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  113357. 1.000000000000f,
  113358. };
  113359. #define INVSQ2EXP_LOOKUP_MIN (-32)
  113360. #define INVSQ2EXP_LOOKUP_MAX 32
  113361. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  113362. INVSQ2EXP_LOOKUP_MIN+1]={
  113363. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  113364. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  113365. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  113366. 1024.f, 724.0773439f, 512.f, 362.038672f,
  113367. 256.f, 181.019336f, 128.f, 90.50966799f,
  113368. 64.f, 45.254834f, 32.f, 22.627417f,
  113369. 16.f, 11.3137085f, 8.f, 5.656854249f,
  113370. 4.f, 2.828427125f, 2.f, 1.414213562f,
  113371. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  113372. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  113373. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  113374. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  113375. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  113376. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  113377. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  113378. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  113379. 1.525878906e-05f,
  113380. };
  113381. #endif
  113382. #define FROMdB_LOOKUP_SZ 35
  113383. #define FROMdB2_LOOKUP_SZ 32
  113384. #define FROMdB_SHIFT 5
  113385. #define FROMdB2_SHIFT 3
  113386. #define FROMdB2_MASK 31
  113387. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  113388. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  113389. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  113390. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  113391. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  113392. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  113393. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  113394. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  113395. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  113396. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  113397. };
  113398. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  113399. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  113400. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  113401. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  113402. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  113403. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  113404. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  113405. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  113406. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  113407. };
  113408. #ifdef INT_LOOKUP
  113409. #define INVSQ_LOOKUP_I_SHIFT 10
  113410. #define INVSQ_LOOKUP_I_MASK 1023
  113411. static long INVSQ_LOOKUP_I[64+1]={
  113412. 92682l, 91966l, 91267l, 90583l,
  113413. 89915l, 89261l, 88621l, 87995l,
  113414. 87381l, 86781l, 86192l, 85616l,
  113415. 85051l, 84497l, 83953l, 83420l,
  113416. 82897l, 82384l, 81880l, 81385l,
  113417. 80899l, 80422l, 79953l, 79492l,
  113418. 79039l, 78594l, 78156l, 77726l,
  113419. 77302l, 76885l, 76475l, 76072l,
  113420. 75674l, 75283l, 74898l, 74519l,
  113421. 74146l, 73778l, 73415l, 73058l,
  113422. 72706l, 72359l, 72016l, 71679l,
  113423. 71347l, 71019l, 70695l, 70376l,
  113424. 70061l, 69750l, 69444l, 69141l,
  113425. 68842l, 68548l, 68256l, 67969l,
  113426. 67685l, 67405l, 67128l, 66855l,
  113427. 66585l, 66318l, 66054l, 65794l,
  113428. 65536l,
  113429. };
  113430. #define COS_LOOKUP_I_SHIFT 9
  113431. #define COS_LOOKUP_I_MASK 511
  113432. #define COS_LOOKUP_I_SZ 128
  113433. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  113434. 16384l, 16379l, 16364l, 16340l,
  113435. 16305l, 16261l, 16207l, 16143l,
  113436. 16069l, 15986l, 15893l, 15791l,
  113437. 15679l, 15557l, 15426l, 15286l,
  113438. 15137l, 14978l, 14811l, 14635l,
  113439. 14449l, 14256l, 14053l, 13842l,
  113440. 13623l, 13395l, 13160l, 12916l,
  113441. 12665l, 12406l, 12140l, 11866l,
  113442. 11585l, 11297l, 11003l, 10702l,
  113443. 10394l, 10080l, 9760l, 9434l,
  113444. 9102l, 8765l, 8423l, 8076l,
  113445. 7723l, 7366l, 7005l, 6639l,
  113446. 6270l, 5897l, 5520l, 5139l,
  113447. 4756l, 4370l, 3981l, 3590l,
  113448. 3196l, 2801l, 2404l, 2006l,
  113449. 1606l, 1205l, 804l, 402l,
  113450. 0l, -401l, -803l, -1204l,
  113451. -1605l, -2005l, -2403l, -2800l,
  113452. -3195l, -3589l, -3980l, -4369l,
  113453. -4755l, -5138l, -5519l, -5896l,
  113454. -6269l, -6638l, -7004l, -7365l,
  113455. -7722l, -8075l, -8422l, -8764l,
  113456. -9101l, -9433l, -9759l, -10079l,
  113457. -10393l, -10701l, -11002l, -11296l,
  113458. -11584l, -11865l, -12139l, -12405l,
  113459. -12664l, -12915l, -13159l, -13394l,
  113460. -13622l, -13841l, -14052l, -14255l,
  113461. -14448l, -14634l, -14810l, -14977l,
  113462. -15136l, -15285l, -15425l, -15556l,
  113463. -15678l, -15790l, -15892l, -15985l,
  113464. -16068l, -16142l, -16206l, -16260l,
  113465. -16304l, -16339l, -16363l, -16378l,
  113466. -16383l,
  113467. };
  113468. #endif
  113469. #endif
  113470. /*** End of inlined file: lookup_data.h ***/
  113471. #ifdef FLOAT_LOOKUP
  113472. /* interpolated lookup based cos function, domain 0 to PI only */
  113473. float vorbis_coslook(float a){
  113474. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  113475. int i=vorbis_ftoi(d-.5);
  113476. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  113477. }
  113478. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  113479. float vorbis_invsqlook(float a){
  113480. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  113481. int i=vorbis_ftoi(d-.5f);
  113482. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  113483. }
  113484. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  113485. float vorbis_invsq2explook(int a){
  113486. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  113487. }
  113488. #include <stdio.h>
  113489. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  113490. float vorbis_fromdBlook(float a){
  113491. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  113492. return (i<0)?1.f:
  113493. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  113494. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  113495. }
  113496. #endif
  113497. #ifdef INT_LOOKUP
  113498. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  113499. 16.16 format
  113500. returns in m.8 format */
  113501. long vorbis_invsqlook_i(long a,long e){
  113502. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  113503. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  113504. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  113505. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  113506. d)>>16); /* result 1.16 */
  113507. e+=32;
  113508. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  113509. e=(e>>1)-8;
  113510. return(val>>e);
  113511. }
  113512. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  113513. /* a is in n.12 format */
  113514. float vorbis_fromdBlook_i(long a){
  113515. int i=(-a)>>(12-FROMdB2_SHIFT);
  113516. return (i<0)?1.f:
  113517. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  113518. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  113519. }
  113520. /* interpolated lookup based cos function, domain 0 to PI only */
  113521. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  113522. long vorbis_coslook_i(long a){
  113523. int i=a>>COS_LOOKUP_I_SHIFT;
  113524. int d=a&COS_LOOKUP_I_MASK;
  113525. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  113526. COS_LOOKUP_I_SHIFT);
  113527. }
  113528. #endif
  113529. #endif
  113530. /*** End of inlined file: lookup.c ***/
  113531. /* catch this in the build system; we #include for
  113532. compilers (like gcc) that can't inline across
  113533. modules */
  113534. /* side effect: changes *lsp to cosines of lsp */
  113535. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  113536. float amp,float ampoffset){
  113537. int i;
  113538. float wdel=M_PI/ln;
  113539. vorbis_fpu_control fpu;
  113540. (void) fpu; // to avoid an unused variable warning
  113541. vorbis_fpu_setround(&fpu);
  113542. for(i=0;i<m;i++)lsp[i]=vorbis_coslook(lsp[i]);
  113543. i=0;
  113544. while(i<n){
  113545. int k=map[i];
  113546. int qexp;
  113547. float p=.7071067812f;
  113548. float q=.7071067812f;
  113549. float w=vorbis_coslook(wdel*k);
  113550. float *ftmp=lsp;
  113551. int c=m>>1;
  113552. do{
  113553. q*=ftmp[0]-w;
  113554. p*=ftmp[1]-w;
  113555. ftmp+=2;
  113556. }while(--c);
  113557. if(m&1){
  113558. /* odd order filter; slightly assymetric */
  113559. /* the last coefficient */
  113560. q*=ftmp[0]-w;
  113561. q*=q;
  113562. p*=p*(1.f-w*w);
  113563. }else{
  113564. /* even order filter; still symmetric */
  113565. q*=q*(1.f+w);
  113566. p*=p*(1.f-w);
  113567. }
  113568. q=frexp(p+q,&qexp);
  113569. q=vorbis_fromdBlook(amp*
  113570. vorbis_invsqlook(q)*
  113571. vorbis_invsq2explook(qexp+m)-
  113572. ampoffset);
  113573. do{
  113574. curve[i++]*=q;
  113575. }while(map[i]==k);
  113576. }
  113577. vorbis_fpu_restore(fpu);
  113578. }
  113579. #else
  113580. #ifdef INT_LOOKUP
  113581. /*** Start of inlined file: lookup.c ***/
  113582. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  113583. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113584. // tasks..
  113585. #if JUCE_MSVC
  113586. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113587. #endif
  113588. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  113589. #if JUCE_USE_OGGVORBIS
  113590. #include <math.h>
  113591. /*** Start of inlined file: lookup.h ***/
  113592. #ifndef _V_LOOKUP_H_
  113593. #ifdef FLOAT_LOOKUP
  113594. extern float vorbis_coslook(float a);
  113595. extern float vorbis_invsqlook(float a);
  113596. extern float vorbis_invsq2explook(int a);
  113597. extern float vorbis_fromdBlook(float a);
  113598. #endif
  113599. #ifdef INT_LOOKUP
  113600. extern long vorbis_invsqlook_i(long a,long e);
  113601. extern long vorbis_coslook_i(long a);
  113602. extern float vorbis_fromdBlook_i(long a);
  113603. #endif
  113604. #endif
  113605. /*** End of inlined file: lookup.h ***/
  113606. /*** Start of inlined file: lookup_data.h ***/
  113607. #ifndef _V_LOOKUP_DATA_H_
  113608. #ifdef FLOAT_LOOKUP
  113609. #define COS_LOOKUP_SZ 128
  113610. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  113611. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  113612. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  113613. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  113614. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  113615. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  113616. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  113617. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  113618. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  113619. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  113620. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  113621. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  113622. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  113623. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  113624. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  113625. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  113626. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  113627. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  113628. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  113629. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  113630. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  113631. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  113632. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  113633. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  113634. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  113635. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  113636. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  113637. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  113638. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  113639. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  113640. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  113641. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  113642. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  113643. -1.0000000000000f,
  113644. };
  113645. #define INVSQ_LOOKUP_SZ 32
  113646. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  113647. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  113648. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  113649. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  113650. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  113651. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  113652. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  113653. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  113654. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  113655. 1.000000000000f,
  113656. };
  113657. #define INVSQ2EXP_LOOKUP_MIN (-32)
  113658. #define INVSQ2EXP_LOOKUP_MAX 32
  113659. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  113660. INVSQ2EXP_LOOKUP_MIN+1]={
  113661. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  113662. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  113663. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  113664. 1024.f, 724.0773439f, 512.f, 362.038672f,
  113665. 256.f, 181.019336f, 128.f, 90.50966799f,
  113666. 64.f, 45.254834f, 32.f, 22.627417f,
  113667. 16.f, 11.3137085f, 8.f, 5.656854249f,
  113668. 4.f, 2.828427125f, 2.f, 1.414213562f,
  113669. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  113670. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  113671. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  113672. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  113673. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  113674. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  113675. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  113676. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  113677. 1.525878906e-05f,
  113678. };
  113679. #endif
  113680. #define FROMdB_LOOKUP_SZ 35
  113681. #define FROMdB2_LOOKUP_SZ 32
  113682. #define FROMdB_SHIFT 5
  113683. #define FROMdB2_SHIFT 3
  113684. #define FROMdB2_MASK 31
  113685. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  113686. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  113687. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  113688. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  113689. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  113690. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  113691. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  113692. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  113693. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  113694. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  113695. };
  113696. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  113697. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  113698. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  113699. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  113700. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  113701. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  113702. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  113703. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  113704. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  113705. };
  113706. #ifdef INT_LOOKUP
  113707. #define INVSQ_LOOKUP_I_SHIFT 10
  113708. #define INVSQ_LOOKUP_I_MASK 1023
  113709. static long INVSQ_LOOKUP_I[64+1]={
  113710. 92682l, 91966l, 91267l, 90583l,
  113711. 89915l, 89261l, 88621l, 87995l,
  113712. 87381l, 86781l, 86192l, 85616l,
  113713. 85051l, 84497l, 83953l, 83420l,
  113714. 82897l, 82384l, 81880l, 81385l,
  113715. 80899l, 80422l, 79953l, 79492l,
  113716. 79039l, 78594l, 78156l, 77726l,
  113717. 77302l, 76885l, 76475l, 76072l,
  113718. 75674l, 75283l, 74898l, 74519l,
  113719. 74146l, 73778l, 73415l, 73058l,
  113720. 72706l, 72359l, 72016l, 71679l,
  113721. 71347l, 71019l, 70695l, 70376l,
  113722. 70061l, 69750l, 69444l, 69141l,
  113723. 68842l, 68548l, 68256l, 67969l,
  113724. 67685l, 67405l, 67128l, 66855l,
  113725. 66585l, 66318l, 66054l, 65794l,
  113726. 65536l,
  113727. };
  113728. #define COS_LOOKUP_I_SHIFT 9
  113729. #define COS_LOOKUP_I_MASK 511
  113730. #define COS_LOOKUP_I_SZ 128
  113731. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  113732. 16384l, 16379l, 16364l, 16340l,
  113733. 16305l, 16261l, 16207l, 16143l,
  113734. 16069l, 15986l, 15893l, 15791l,
  113735. 15679l, 15557l, 15426l, 15286l,
  113736. 15137l, 14978l, 14811l, 14635l,
  113737. 14449l, 14256l, 14053l, 13842l,
  113738. 13623l, 13395l, 13160l, 12916l,
  113739. 12665l, 12406l, 12140l, 11866l,
  113740. 11585l, 11297l, 11003l, 10702l,
  113741. 10394l, 10080l, 9760l, 9434l,
  113742. 9102l, 8765l, 8423l, 8076l,
  113743. 7723l, 7366l, 7005l, 6639l,
  113744. 6270l, 5897l, 5520l, 5139l,
  113745. 4756l, 4370l, 3981l, 3590l,
  113746. 3196l, 2801l, 2404l, 2006l,
  113747. 1606l, 1205l, 804l, 402l,
  113748. 0l, -401l, -803l, -1204l,
  113749. -1605l, -2005l, -2403l, -2800l,
  113750. -3195l, -3589l, -3980l, -4369l,
  113751. -4755l, -5138l, -5519l, -5896l,
  113752. -6269l, -6638l, -7004l, -7365l,
  113753. -7722l, -8075l, -8422l, -8764l,
  113754. -9101l, -9433l, -9759l, -10079l,
  113755. -10393l, -10701l, -11002l, -11296l,
  113756. -11584l, -11865l, -12139l, -12405l,
  113757. -12664l, -12915l, -13159l, -13394l,
  113758. -13622l, -13841l, -14052l, -14255l,
  113759. -14448l, -14634l, -14810l, -14977l,
  113760. -15136l, -15285l, -15425l, -15556l,
  113761. -15678l, -15790l, -15892l, -15985l,
  113762. -16068l, -16142l, -16206l, -16260l,
  113763. -16304l, -16339l, -16363l, -16378l,
  113764. -16383l,
  113765. };
  113766. #endif
  113767. #endif
  113768. /*** End of inlined file: lookup_data.h ***/
  113769. #ifdef FLOAT_LOOKUP
  113770. /* interpolated lookup based cos function, domain 0 to PI only */
  113771. float vorbis_coslook(float a){
  113772. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  113773. int i=vorbis_ftoi(d-.5);
  113774. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  113775. }
  113776. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  113777. float vorbis_invsqlook(float a){
  113778. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  113779. int i=vorbis_ftoi(d-.5f);
  113780. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  113781. }
  113782. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  113783. float vorbis_invsq2explook(int a){
  113784. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  113785. }
  113786. #include <stdio.h>
  113787. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  113788. float vorbis_fromdBlook(float a){
  113789. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  113790. return (i<0)?1.f:
  113791. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  113792. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  113793. }
  113794. #endif
  113795. #ifdef INT_LOOKUP
  113796. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  113797. 16.16 format
  113798. returns in m.8 format */
  113799. long vorbis_invsqlook_i(long a,long e){
  113800. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  113801. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  113802. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  113803. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  113804. d)>>16); /* result 1.16 */
  113805. e+=32;
  113806. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  113807. e=(e>>1)-8;
  113808. return(val>>e);
  113809. }
  113810. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  113811. /* a is in n.12 format */
  113812. float vorbis_fromdBlook_i(long a){
  113813. int i=(-a)>>(12-FROMdB2_SHIFT);
  113814. return (i<0)?1.f:
  113815. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  113816. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  113817. }
  113818. /* interpolated lookup based cos function, domain 0 to PI only */
  113819. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  113820. long vorbis_coslook_i(long a){
  113821. int i=a>>COS_LOOKUP_I_SHIFT;
  113822. int d=a&COS_LOOKUP_I_MASK;
  113823. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  113824. COS_LOOKUP_I_SHIFT);
  113825. }
  113826. #endif
  113827. #endif
  113828. /*** End of inlined file: lookup.c ***/
  113829. /* catch this in the build system; we #include for
  113830. compilers (like gcc) that can't inline across
  113831. modules */
  113832. static int MLOOP_1[64]={
  113833. 0,10,11,11, 12,12,12,12, 13,13,13,13, 13,13,13,13,
  113834. 14,14,14,14, 14,14,14,14, 14,14,14,14, 14,14,14,14,
  113835. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  113836. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  113837. };
  113838. static int MLOOP_2[64]={
  113839. 0,4,5,5, 6,6,6,6, 7,7,7,7, 7,7,7,7,
  113840. 8,8,8,8, 8,8,8,8, 8,8,8,8, 8,8,8,8,
  113841. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  113842. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  113843. };
  113844. static int MLOOP_3[8]={0,1,2,2,3,3,3,3};
  113845. /* side effect: changes *lsp to cosines of lsp */
  113846. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  113847. float amp,float ampoffset){
  113848. /* 0 <= m < 256 */
  113849. /* set up for using all int later */
  113850. int i;
  113851. int ampoffseti=rint(ampoffset*4096.f);
  113852. int ampi=rint(amp*16.f);
  113853. long *ilsp=alloca(m*sizeof(*ilsp));
  113854. for(i=0;i<m;i++)ilsp[i]=vorbis_coslook_i(lsp[i]/M_PI*65536.f+.5f);
  113855. i=0;
  113856. while(i<n){
  113857. int j,k=map[i];
  113858. unsigned long pi=46341; /* 2**-.5 in 0.16 */
  113859. unsigned long qi=46341;
  113860. int qexp=0,shift;
  113861. long wi=vorbis_coslook_i(k*65536/ln);
  113862. qi*=labs(ilsp[0]-wi);
  113863. pi*=labs(ilsp[1]-wi);
  113864. for(j=3;j<m;j+=2){
  113865. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  113866. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  113867. shift=MLOOP_3[(pi|qi)>>16];
  113868. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  113869. pi=(pi>>shift)*labs(ilsp[j]-wi);
  113870. qexp+=shift;
  113871. }
  113872. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  113873. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  113874. shift=MLOOP_3[(pi|qi)>>16];
  113875. /* pi,qi normalized collectively, both tracked using qexp */
  113876. if(m&1){
  113877. /* odd order filter; slightly assymetric */
  113878. /* the last coefficient */
  113879. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  113880. pi=(pi>>shift)<<14;
  113881. qexp+=shift;
  113882. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  113883. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  113884. shift=MLOOP_3[(pi|qi)>>16];
  113885. pi>>=shift;
  113886. qi>>=shift;
  113887. qexp+=shift-14*((m+1)>>1);
  113888. pi=((pi*pi)>>16);
  113889. qi=((qi*qi)>>16);
  113890. qexp=qexp*2+m;
  113891. pi*=(1<<14)-((wi*wi)>>14);
  113892. qi+=pi>>14;
  113893. }else{
  113894. /* even order filter; still symmetric */
  113895. /* p*=p(1-w), q*=q(1+w), let normalization drift because it isn't
  113896. worth tracking step by step */
  113897. pi>>=shift;
  113898. qi>>=shift;
  113899. qexp+=shift-7*m;
  113900. pi=((pi*pi)>>16);
  113901. qi=((qi*qi)>>16);
  113902. qexp=qexp*2+m;
  113903. pi*=(1<<14)-wi;
  113904. qi*=(1<<14)+wi;
  113905. qi=(qi+pi)>>14;
  113906. }
  113907. /* we've let the normalization drift because it wasn't important;
  113908. however, for the lookup, things must be normalized again. We
  113909. need at most one right shift or a number of left shifts */
  113910. if(qi&0xffff0000){ /* checks for 1.xxxxxxxxxxxxxxxx */
  113911. qi>>=1; qexp++;
  113912. }else
  113913. while(qi && !(qi&0x8000)){ /* checks for 0.0xxxxxxxxxxxxxxx or less*/
  113914. qi<<=1; qexp--;
  113915. }
  113916. amp=vorbis_fromdBlook_i(ampi* /* n.4 */
  113917. vorbis_invsqlook_i(qi,qexp)-
  113918. /* m.8, m+n<=8 */
  113919. ampoffseti); /* 8.12[0] */
  113920. curve[i]*=amp;
  113921. while(map[++i]==k)curve[i]*=amp;
  113922. }
  113923. }
  113924. #else
  113925. /* old, nonoptimized but simple version for any poor sap who needs to
  113926. figure out what the hell this code does, or wants the other
  113927. fraction of a dB precision */
  113928. /* side effect: changes *lsp to cosines of lsp */
  113929. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  113930. float amp,float ampoffset){
  113931. int i;
  113932. float wdel=M_PI/ln;
  113933. for(i=0;i<m;i++)lsp[i]=2.f*cos(lsp[i]);
  113934. i=0;
  113935. while(i<n){
  113936. int j,k=map[i];
  113937. float p=.5f;
  113938. float q=.5f;
  113939. float w=2.f*cos(wdel*k);
  113940. for(j=1;j<m;j+=2){
  113941. q *= w-lsp[j-1];
  113942. p *= w-lsp[j];
  113943. }
  113944. if(j==m){
  113945. /* odd order filter; slightly assymetric */
  113946. /* the last coefficient */
  113947. q*=w-lsp[j-1];
  113948. p*=p*(4.f-w*w);
  113949. q*=q;
  113950. }else{
  113951. /* even order filter; still symmetric */
  113952. p*=p*(2.f-w);
  113953. q*=q*(2.f+w);
  113954. }
  113955. q=fromdB(amp/sqrt(p+q)-ampoffset);
  113956. curve[i]*=q;
  113957. while(map[++i]==k)curve[i]*=q;
  113958. }
  113959. }
  113960. #endif
  113961. #endif
  113962. static void cheby(float *g, int ord) {
  113963. int i, j;
  113964. g[0] *= .5f;
  113965. for(i=2; i<= ord; i++) {
  113966. for(j=ord; j >= i; j--) {
  113967. g[j-2] -= g[j];
  113968. g[j] += g[j];
  113969. }
  113970. }
  113971. }
  113972. static int comp(const void *a,const void *b){
  113973. return (*(float *)a<*(float *)b)-(*(float *)a>*(float *)b);
  113974. }
  113975. /* Newton-Raphson-Maehly actually functioned as a decent root finder,
  113976. but there are root sets for which it gets into limit cycles
  113977. (exacerbated by zero suppression) and fails. We can't afford to
  113978. fail, even if the failure is 1 in 100,000,000, so we now use
  113979. Laguerre and later polish with Newton-Raphson (which can then
  113980. afford to fail) */
  113981. #define EPSILON 10e-7
  113982. static int Laguerre_With_Deflation(float *a,int ord,float *r){
  113983. int i,m;
  113984. double lastdelta=0.f;
  113985. double *defl=(double*)alloca(sizeof(*defl)*(ord+1));
  113986. for(i=0;i<=ord;i++)defl[i]=a[i];
  113987. for(m=ord;m>0;m--){
  113988. double newx=0.f,delta;
  113989. /* iterate a root */
  113990. while(1){
  113991. double p=defl[m],pp=0.f,ppp=0.f,denom;
  113992. /* eval the polynomial and its first two derivatives */
  113993. for(i=m;i>0;i--){
  113994. ppp = newx*ppp + pp;
  113995. pp = newx*pp + p;
  113996. p = newx*p + defl[i-1];
  113997. }
  113998. /* Laguerre's method */
  113999. denom=(m-1) * ((m-1)*pp*pp - m*p*ppp);
  114000. if(denom<0)
  114001. return(-1); /* complex root! The LPC generator handed us a bad filter */
  114002. if(pp>0){
  114003. denom = pp + sqrt(denom);
  114004. if(denom<EPSILON)denom=EPSILON;
  114005. }else{
  114006. denom = pp - sqrt(denom);
  114007. if(denom>-(EPSILON))denom=-(EPSILON);
  114008. }
  114009. delta = m*p/denom;
  114010. newx -= delta;
  114011. if(delta<0.f)delta*=-1;
  114012. if(fabs(delta/newx)<10e-12)break;
  114013. lastdelta=delta;
  114014. }
  114015. r[m-1]=newx;
  114016. /* forward deflation */
  114017. for(i=m;i>0;i--)
  114018. defl[i-1]+=newx*defl[i];
  114019. defl++;
  114020. }
  114021. return(0);
  114022. }
  114023. /* for spit-and-polish only */
  114024. static int Newton_Raphson(float *a,int ord,float *r){
  114025. int i, k, count=0;
  114026. double error=1.f;
  114027. double *root=(double*)alloca(ord*sizeof(*root));
  114028. for(i=0; i<ord;i++) root[i] = r[i];
  114029. while(error>1e-20){
  114030. error=0;
  114031. for(i=0; i<ord; i++) { /* Update each point. */
  114032. double pp=0.,delta;
  114033. double rooti=root[i];
  114034. double p=a[ord];
  114035. for(k=ord-1; k>= 0; k--) {
  114036. pp= pp* rooti + p;
  114037. p = p * rooti + a[k];
  114038. }
  114039. delta = p/pp;
  114040. root[i] -= delta;
  114041. error+= delta*delta;
  114042. }
  114043. if(count>40)return(-1);
  114044. count++;
  114045. }
  114046. /* Replaced the original bubble sort with a real sort. With your
  114047. help, we can eliminate the bubble sort in our lifetime. --Monty */
  114048. for(i=0; i<ord;i++) r[i] = root[i];
  114049. return(0);
  114050. }
  114051. /* Convert lpc coefficients to lsp coefficients */
  114052. int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m){
  114053. int order2=(m+1)>>1;
  114054. int g1_order,g2_order;
  114055. float *g1=(float*)alloca(sizeof(*g1)*(order2+1));
  114056. float *g2=(float*)alloca(sizeof(*g2)*(order2+1));
  114057. float *g1r=(float*)alloca(sizeof(*g1r)*(order2+1));
  114058. float *g2r=(float*)alloca(sizeof(*g2r)*(order2+1));
  114059. int i;
  114060. /* even and odd are slightly different base cases */
  114061. g1_order=(m+1)>>1;
  114062. g2_order=(m) >>1;
  114063. /* Compute the lengths of the x polynomials. */
  114064. /* Compute the first half of K & R F1 & F2 polynomials. */
  114065. /* Compute half of the symmetric and antisymmetric polynomials. */
  114066. /* Remove the roots at +1 and -1. */
  114067. g1[g1_order] = 1.f;
  114068. for(i=1;i<=g1_order;i++) g1[g1_order-i] = lpc[i-1]+lpc[m-i];
  114069. g2[g2_order] = 1.f;
  114070. for(i=1;i<=g2_order;i++) g2[g2_order-i] = lpc[i-1]-lpc[m-i];
  114071. if(g1_order>g2_order){
  114072. for(i=2; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+2];
  114073. }else{
  114074. for(i=1; i<=g1_order;i++) g1[g1_order-i] -= g1[g1_order-i+1];
  114075. for(i=1; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+1];
  114076. }
  114077. /* Convert into polynomials in cos(alpha) */
  114078. cheby(g1,g1_order);
  114079. cheby(g2,g2_order);
  114080. /* Find the roots of the 2 even polynomials.*/
  114081. if(Laguerre_With_Deflation(g1,g1_order,g1r) ||
  114082. Laguerre_With_Deflation(g2,g2_order,g2r))
  114083. return(-1);
  114084. Newton_Raphson(g1,g1_order,g1r); /* if it fails, it leaves g1r alone */
  114085. Newton_Raphson(g2,g2_order,g2r); /* if it fails, it leaves g2r alone */
  114086. qsort(g1r,g1_order,sizeof(*g1r),comp);
  114087. qsort(g2r,g2_order,sizeof(*g2r),comp);
  114088. for(i=0;i<g1_order;i++)
  114089. lsp[i*2] = acos(g1r[i]);
  114090. for(i=0;i<g2_order;i++)
  114091. lsp[i*2+1] = acos(g2r[i]);
  114092. return(0);
  114093. }
  114094. #endif
  114095. /*** End of inlined file: lsp.c ***/
  114096. /*** Start of inlined file: mapping0.c ***/
  114097. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114098. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114099. // tasks..
  114100. #if JUCE_MSVC
  114101. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114102. #endif
  114103. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114104. #if JUCE_USE_OGGVORBIS
  114105. #include <stdlib.h>
  114106. #include <stdio.h>
  114107. #include <string.h>
  114108. #include <math.h>
  114109. /* simplistic, wasteful way of doing this (unique lookup for each
  114110. mode/submapping); there should be a central repository for
  114111. identical lookups. That will require minor work, so I'm putting it
  114112. off as low priority.
  114113. Why a lookup for each backend in a given mode? Because the
  114114. blocksize is set by the mode, and low backend lookups may require
  114115. parameters from other areas of the mode/mapping */
  114116. static void mapping0_free_info(vorbis_info_mapping *i){
  114117. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)i;
  114118. if(info){
  114119. memset(info,0,sizeof(*info));
  114120. _ogg_free(info);
  114121. }
  114122. }
  114123. static int ilog3(unsigned int v){
  114124. int ret=0;
  114125. if(v)--v;
  114126. while(v){
  114127. ret++;
  114128. v>>=1;
  114129. }
  114130. return(ret);
  114131. }
  114132. static void mapping0_pack(vorbis_info *vi,vorbis_info_mapping *vm,
  114133. oggpack_buffer *opb){
  114134. int i;
  114135. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)vm;
  114136. /* another 'we meant to do it this way' hack... up to beta 4, we
  114137. packed 4 binary zeros here to signify one submapping in use. We
  114138. now redefine that to mean four bitflags that indicate use of
  114139. deeper features; bit0:submappings, bit1:coupling,
  114140. bit2,3:reserved. This is backward compatable with all actual uses
  114141. of the beta code. */
  114142. if(info->submaps>1){
  114143. oggpack_write(opb,1,1);
  114144. oggpack_write(opb,info->submaps-1,4);
  114145. }else
  114146. oggpack_write(opb,0,1);
  114147. if(info->coupling_steps>0){
  114148. oggpack_write(opb,1,1);
  114149. oggpack_write(opb,info->coupling_steps-1,8);
  114150. for(i=0;i<info->coupling_steps;i++){
  114151. oggpack_write(opb,info->coupling_mag[i],ilog3(vi->channels));
  114152. oggpack_write(opb,info->coupling_ang[i],ilog3(vi->channels));
  114153. }
  114154. }else
  114155. oggpack_write(opb,0,1);
  114156. oggpack_write(opb,0,2); /* 2,3:reserved */
  114157. /* we don't write the channel submappings if we only have one... */
  114158. if(info->submaps>1){
  114159. for(i=0;i<vi->channels;i++)
  114160. oggpack_write(opb,info->chmuxlist[i],4);
  114161. }
  114162. for(i=0;i<info->submaps;i++){
  114163. oggpack_write(opb,0,8); /* time submap unused */
  114164. oggpack_write(opb,info->floorsubmap[i],8);
  114165. oggpack_write(opb,info->residuesubmap[i],8);
  114166. }
  114167. }
  114168. /* also responsible for range checking */
  114169. static vorbis_info_mapping *mapping0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  114170. int i;
  114171. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)_ogg_calloc(1,sizeof(*info));
  114172. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114173. memset(info,0,sizeof(*info));
  114174. if(oggpack_read(opb,1))
  114175. info->submaps=oggpack_read(opb,4)+1;
  114176. else
  114177. info->submaps=1;
  114178. if(oggpack_read(opb,1)){
  114179. info->coupling_steps=oggpack_read(opb,8)+1;
  114180. for(i=0;i<info->coupling_steps;i++){
  114181. int testM=info->coupling_mag[i]=oggpack_read(opb,ilog3(vi->channels));
  114182. int testA=info->coupling_ang[i]=oggpack_read(opb,ilog3(vi->channels));
  114183. if(testM<0 ||
  114184. testA<0 ||
  114185. testM==testA ||
  114186. testM>=vi->channels ||
  114187. testA>=vi->channels) goto err_out;
  114188. }
  114189. }
  114190. if(oggpack_read(opb,2)>0)goto err_out; /* 2,3:reserved */
  114191. if(info->submaps>1){
  114192. for(i=0;i<vi->channels;i++){
  114193. info->chmuxlist[i]=oggpack_read(opb,4);
  114194. if(info->chmuxlist[i]>=info->submaps)goto err_out;
  114195. }
  114196. }
  114197. for(i=0;i<info->submaps;i++){
  114198. oggpack_read(opb,8); /* time submap unused */
  114199. info->floorsubmap[i]=oggpack_read(opb,8);
  114200. if(info->floorsubmap[i]>=ci->floors)goto err_out;
  114201. info->residuesubmap[i]=oggpack_read(opb,8);
  114202. if(info->residuesubmap[i]>=ci->residues)goto err_out;
  114203. }
  114204. return info;
  114205. err_out:
  114206. mapping0_free_info(info);
  114207. return(NULL);
  114208. }
  114209. #if 0
  114210. static long seq=0;
  114211. static ogg_int64_t total=0;
  114212. static float FLOOR1_fromdB_LOOKUP[256]={
  114213. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  114214. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  114215. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  114216. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  114217. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  114218. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  114219. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  114220. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  114221. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  114222. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  114223. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  114224. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  114225. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  114226. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  114227. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  114228. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  114229. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  114230. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  114231. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  114232. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  114233. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  114234. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  114235. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  114236. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  114237. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  114238. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  114239. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  114240. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  114241. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  114242. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  114243. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  114244. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  114245. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  114246. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  114247. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  114248. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  114249. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  114250. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  114251. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  114252. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  114253. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  114254. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  114255. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  114256. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  114257. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  114258. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  114259. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  114260. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  114261. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  114262. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  114263. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  114264. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  114265. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  114266. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  114267. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  114268. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  114269. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  114270. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  114271. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  114272. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  114273. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  114274. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  114275. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  114276. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  114277. };
  114278. #endif
  114279. extern int *floor1_fit(vorbis_block *vb,void *look,
  114280. const float *logmdct, /* in */
  114281. const float *logmask);
  114282. extern int *floor1_interpolate_fit(vorbis_block *vb,void *look,
  114283. int *A,int *B,
  114284. int del);
  114285. extern int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  114286. void*look,
  114287. int *post,int *ilogmask);
  114288. static int mapping0_forward(vorbis_block *vb){
  114289. vorbis_dsp_state *vd=vb->vd;
  114290. vorbis_info *vi=vd->vi;
  114291. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114292. private_state *b=(private_state*)vb->vd->backend_state;
  114293. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  114294. int n=vb->pcmend;
  114295. int i,j,k;
  114296. int *nonzero = (int*) alloca(sizeof(*nonzero)*vi->channels);
  114297. float **gmdct = (float**) _vorbis_block_alloc(vb,vi->channels*sizeof(*gmdct));
  114298. int **ilogmaskch= (int**) _vorbis_block_alloc(vb,vi->channels*sizeof(*ilogmaskch));
  114299. int ***floor_posts = (int***) _vorbis_block_alloc(vb,vi->channels*sizeof(*floor_posts));
  114300. float global_ampmax=vbi->ampmax;
  114301. float *local_ampmax=(float*)alloca(sizeof(*local_ampmax)*vi->channels);
  114302. int blocktype=vbi->blocktype;
  114303. int modenumber=vb->W;
  114304. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)ci->map_param[modenumber];
  114305. vorbis_look_psy *psy_look=
  114306. b->psy+blocktype+(vb->W?2:0);
  114307. vb->mode=modenumber;
  114308. for(i=0;i<vi->channels;i++){
  114309. float scale=4.f/n;
  114310. float scale_dB;
  114311. float *pcm =vb->pcm[i];
  114312. float *logfft =pcm;
  114313. gmdct[i]=(float*)_vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  114314. scale_dB=todB(&scale) + .345; /* + .345 is a hack; the original
  114315. todB estimation used on IEEE 754
  114316. compliant machines had a bug that
  114317. returned dB values about a third
  114318. of a decibel too high. The bug
  114319. was harmless because tunings
  114320. implicitly took that into
  114321. account. However, fixing the bug
  114322. in the estimator requires
  114323. changing all the tunings as well.
  114324. For now, it's easier to sync
  114325. things back up here, and
  114326. recalibrate the tunings in the
  114327. next major model upgrade. */
  114328. #if 0
  114329. if(vi->channels==2)
  114330. if(i==0)
  114331. _analysis_output("pcmL",seq,pcm,n,0,0,total-n/2);
  114332. else
  114333. _analysis_output("pcmR",seq,pcm,n,0,0,total-n/2);
  114334. #endif
  114335. /* window the PCM data */
  114336. _vorbis_apply_window(pcm,b->window,ci->blocksizes,vb->lW,vb->W,vb->nW);
  114337. #if 0
  114338. if(vi->channels==2)
  114339. if(i==0)
  114340. _analysis_output("windowedL",seq,pcm,n,0,0,total-n/2);
  114341. else
  114342. _analysis_output("windowedR",seq,pcm,n,0,0,total-n/2);
  114343. #endif
  114344. /* transform the PCM data */
  114345. /* only MDCT right now.... */
  114346. mdct_forward((mdct_lookup*) b->transform[vb->W][0],pcm,gmdct[i]);
  114347. /* FFT yields more accurate tonal estimation (not phase sensitive) */
  114348. drft_forward(&b->fft_look[vb->W],pcm);
  114349. logfft[0]=scale_dB+todB(pcm) + .345; /* + .345 is a hack; the
  114350. original todB estimation used on
  114351. IEEE 754 compliant machines had a
  114352. bug that returned dB values about
  114353. a third of a decibel too high.
  114354. The bug was harmless because
  114355. tunings implicitly took that into
  114356. account. However, fixing the bug
  114357. in the estimator requires
  114358. changing all the tunings as well.
  114359. For now, it's easier to sync
  114360. things back up here, and
  114361. recalibrate the tunings in the
  114362. next major model upgrade. */
  114363. local_ampmax[i]=logfft[0];
  114364. for(j=1;j<n-1;j+=2){
  114365. float temp=pcm[j]*pcm[j]+pcm[j+1]*pcm[j+1];
  114366. temp=logfft[(j+1)>>1]=scale_dB+.5f*todB(&temp) + .345; /* +
  114367. .345 is a hack; the original todB
  114368. estimation used on IEEE 754
  114369. compliant machines had a bug that
  114370. returned dB values about a third
  114371. of a decibel too high. The bug
  114372. was harmless because tunings
  114373. implicitly took that into
  114374. account. However, fixing the bug
  114375. in the estimator requires
  114376. changing all the tunings as well.
  114377. For now, it's easier to sync
  114378. things back up here, and
  114379. recalibrate the tunings in the
  114380. next major model upgrade. */
  114381. if(temp>local_ampmax[i])local_ampmax[i]=temp;
  114382. }
  114383. if(local_ampmax[i]>0.f)local_ampmax[i]=0.f;
  114384. if(local_ampmax[i]>global_ampmax)global_ampmax=local_ampmax[i];
  114385. #if 0
  114386. if(vi->channels==2){
  114387. if(i==0){
  114388. _analysis_output("fftL",seq,logfft,n/2,1,0,0);
  114389. }else{
  114390. _analysis_output("fftR",seq,logfft,n/2,1,0,0);
  114391. }
  114392. }
  114393. #endif
  114394. }
  114395. {
  114396. float *noise = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*noise));
  114397. float *tone = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*tone));
  114398. for(i=0;i<vi->channels;i++){
  114399. /* the encoder setup assumes that all the modes used by any
  114400. specific bitrate tweaking use the same floor */
  114401. int submap=info->chmuxlist[i];
  114402. /* the following makes things clearer to *me* anyway */
  114403. float *mdct =gmdct[i];
  114404. float *logfft =vb->pcm[i];
  114405. float *logmdct =logfft+n/2;
  114406. float *logmask =logfft;
  114407. vb->mode=modenumber;
  114408. floor_posts[i]=(int**) _vorbis_block_alloc(vb,PACKETBLOBS*sizeof(**floor_posts));
  114409. memset(floor_posts[i],0,sizeof(**floor_posts)*PACKETBLOBS);
  114410. for(j=0;j<n/2;j++)
  114411. logmdct[j]=todB(mdct+j) + .345; /* + .345 is a hack; the original
  114412. todB estimation used on IEEE 754
  114413. compliant machines had a bug that
  114414. returned dB values about a third
  114415. of a decibel too high. The bug
  114416. was harmless because tunings
  114417. implicitly took that into
  114418. account. However, fixing the bug
  114419. in the estimator requires
  114420. changing all the tunings as well.
  114421. For now, it's easier to sync
  114422. things back up here, and
  114423. recalibrate the tunings in the
  114424. next major model upgrade. */
  114425. #if 0
  114426. if(vi->channels==2){
  114427. if(i==0)
  114428. _analysis_output("mdctL",seq,logmdct,n/2,1,0,0);
  114429. else
  114430. _analysis_output("mdctR",seq,logmdct,n/2,1,0,0);
  114431. }else{
  114432. _analysis_output("mdct",seq,logmdct,n/2,1,0,0);
  114433. }
  114434. #endif
  114435. /* first step; noise masking. Not only does 'noise masking'
  114436. give us curves from which we can decide how much resolution
  114437. to give noise parts of the spectrum, it also implicitly hands
  114438. us a tonality estimate (the larger the value in the
  114439. 'noise_depth' vector, the more tonal that area is) */
  114440. _vp_noisemask(psy_look,
  114441. logmdct,
  114442. noise); /* noise does not have by-frequency offset
  114443. bias applied yet */
  114444. #if 0
  114445. if(vi->channels==2){
  114446. if(i==0)
  114447. _analysis_output("noiseL",seq,noise,n/2,1,0,0);
  114448. else
  114449. _analysis_output("noiseR",seq,noise,n/2,1,0,0);
  114450. }
  114451. #endif
  114452. /* second step: 'all the other crap'; all the stuff that isn't
  114453. computed/fit for bitrate management goes in the second psy
  114454. vector. This includes tone masking, peak limiting and ATH */
  114455. _vp_tonemask(psy_look,
  114456. logfft,
  114457. tone,
  114458. global_ampmax,
  114459. local_ampmax[i]);
  114460. #if 0
  114461. if(vi->channels==2){
  114462. if(i==0)
  114463. _analysis_output("toneL",seq,tone,n/2,1,0,0);
  114464. else
  114465. _analysis_output("toneR",seq,tone,n/2,1,0,0);
  114466. }
  114467. #endif
  114468. /* third step; we offset the noise vectors, overlay tone
  114469. masking. We then do a floor1-specific line fit. If we're
  114470. performing bitrate management, the line fit is performed
  114471. multiple times for up/down tweakage on demand. */
  114472. #if 0
  114473. {
  114474. float aotuv[psy_look->n];
  114475. #endif
  114476. _vp_offset_and_mix(psy_look,
  114477. noise,
  114478. tone,
  114479. 1,
  114480. logmask,
  114481. mdct,
  114482. logmdct);
  114483. #if 0
  114484. if(vi->channels==2){
  114485. if(i==0)
  114486. _analysis_output("aotuvM1_L",seq,aotuv,psy_look->n,1,1,0);
  114487. else
  114488. _analysis_output("aotuvM1_R",seq,aotuv,psy_look->n,1,1,0);
  114489. }
  114490. }
  114491. #endif
  114492. #if 0
  114493. if(vi->channels==2){
  114494. if(i==0)
  114495. _analysis_output("mask1L",seq,logmask,n/2,1,0,0);
  114496. else
  114497. _analysis_output("mask1R",seq,logmask,n/2,1,0,0);
  114498. }
  114499. #endif
  114500. /* this algorithm is hardwired to floor 1 for now; abort out if
  114501. we're *not* floor1. This won't happen unless someone has
  114502. broken the encode setup lib. Guard it anyway. */
  114503. if(ci->floor_type[info->floorsubmap[submap]]!=1)return(-1);
  114504. floor_posts[i][PACKETBLOBS/2]=
  114505. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  114506. logmdct,
  114507. logmask);
  114508. /* are we managing bitrate? If so, perform two more fits for
  114509. later rate tweaking (fits represent hi/lo) */
  114510. if(vorbis_bitrate_managed(vb) && floor_posts[i][PACKETBLOBS/2]){
  114511. /* higher rate by way of lower noise curve */
  114512. _vp_offset_and_mix(psy_look,
  114513. noise,
  114514. tone,
  114515. 2,
  114516. logmask,
  114517. mdct,
  114518. logmdct);
  114519. #if 0
  114520. if(vi->channels==2){
  114521. if(i==0)
  114522. _analysis_output("mask2L",seq,logmask,n/2,1,0,0);
  114523. else
  114524. _analysis_output("mask2R",seq,logmask,n/2,1,0,0);
  114525. }
  114526. #endif
  114527. floor_posts[i][PACKETBLOBS-1]=
  114528. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  114529. logmdct,
  114530. logmask);
  114531. /* lower rate by way of higher noise curve */
  114532. _vp_offset_and_mix(psy_look,
  114533. noise,
  114534. tone,
  114535. 0,
  114536. logmask,
  114537. mdct,
  114538. logmdct);
  114539. #if 0
  114540. if(vi->channels==2)
  114541. if(i==0)
  114542. _analysis_output("mask0L",seq,logmask,n/2,1,0,0);
  114543. else
  114544. _analysis_output("mask0R",seq,logmask,n/2,1,0,0);
  114545. #endif
  114546. floor_posts[i][0]=
  114547. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  114548. logmdct,
  114549. logmask);
  114550. /* we also interpolate a range of intermediate curves for
  114551. intermediate rates */
  114552. for(k=1;k<PACKETBLOBS/2;k++)
  114553. floor_posts[i][k]=
  114554. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  114555. floor_posts[i][0],
  114556. floor_posts[i][PACKETBLOBS/2],
  114557. k*65536/(PACKETBLOBS/2));
  114558. for(k=PACKETBLOBS/2+1;k<PACKETBLOBS-1;k++)
  114559. floor_posts[i][k]=
  114560. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  114561. floor_posts[i][PACKETBLOBS/2],
  114562. floor_posts[i][PACKETBLOBS-1],
  114563. (k-PACKETBLOBS/2)*65536/(PACKETBLOBS/2));
  114564. }
  114565. }
  114566. }
  114567. vbi->ampmax=global_ampmax;
  114568. /*
  114569. the next phases are performed once for vbr-only and PACKETBLOB
  114570. times for bitrate managed modes.
  114571. 1) encode actual mode being used
  114572. 2) encode the floor for each channel, compute coded mask curve/res
  114573. 3) normalize and couple.
  114574. 4) encode residue
  114575. 5) save packet bytes to the packetblob vector
  114576. */
  114577. /* iterate over the many masking curve fits we've created */
  114578. {
  114579. float **res_bundle=(float**) alloca(sizeof(*res_bundle)*vi->channels);
  114580. float **couple_bundle=(float**) alloca(sizeof(*couple_bundle)*vi->channels);
  114581. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  114582. int **sortindex=(int**) alloca(sizeof(*sortindex)*vi->channels);
  114583. float **mag_memo;
  114584. int **mag_sort;
  114585. if(info->coupling_steps){
  114586. mag_memo=_vp_quantize_couple_memo(vb,
  114587. &ci->psy_g_param,
  114588. psy_look,
  114589. info,
  114590. gmdct);
  114591. mag_sort=_vp_quantize_couple_sort(vb,
  114592. psy_look,
  114593. info,
  114594. mag_memo);
  114595. hf_reduction(&ci->psy_g_param,
  114596. psy_look,
  114597. info,
  114598. mag_memo);
  114599. }
  114600. memset(sortindex,0,sizeof(*sortindex)*vi->channels);
  114601. if(psy_look->vi->normal_channel_p){
  114602. for(i=0;i<vi->channels;i++){
  114603. float *mdct =gmdct[i];
  114604. sortindex[i]=(int*) alloca(sizeof(**sortindex)*n/2);
  114605. _vp_noise_normalize_sort(psy_look,mdct,sortindex[i]);
  114606. }
  114607. }
  114608. for(k=(vorbis_bitrate_managed(vb)?0:PACKETBLOBS/2);
  114609. k<=(vorbis_bitrate_managed(vb)?PACKETBLOBS-1:PACKETBLOBS/2);
  114610. k++){
  114611. oggpack_buffer *opb=vbi->packetblob[k];
  114612. /* start out our new packet blob with packet type and mode */
  114613. /* Encode the packet type */
  114614. oggpack_write(opb,0,1);
  114615. /* Encode the modenumber */
  114616. /* Encode frame mode, pre,post windowsize, then dispatch */
  114617. oggpack_write(opb,modenumber,b->modebits);
  114618. if(vb->W){
  114619. oggpack_write(opb,vb->lW,1);
  114620. oggpack_write(opb,vb->nW,1);
  114621. }
  114622. /* encode floor, compute masking curve, sep out residue */
  114623. for(i=0;i<vi->channels;i++){
  114624. int submap=info->chmuxlist[i];
  114625. float *mdct =gmdct[i];
  114626. float *res =vb->pcm[i];
  114627. int *ilogmask=ilogmaskch[i]=
  114628. (int*) _vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  114629. nonzero[i]=floor1_encode(opb,vb,b->flr[info->floorsubmap[submap]],
  114630. floor_posts[i][k],
  114631. ilogmask);
  114632. #if 0
  114633. {
  114634. char buf[80];
  114635. sprintf(buf,"maskI%c%d",i?'R':'L',k);
  114636. float work[n/2];
  114637. for(j=0;j<n/2;j++)
  114638. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]];
  114639. _analysis_output(buf,seq,work,n/2,1,1,0);
  114640. }
  114641. #endif
  114642. _vp_remove_floor(psy_look,
  114643. mdct,
  114644. ilogmask,
  114645. res,
  114646. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  114647. _vp_noise_normalize(psy_look,res,res+n/2,sortindex[i]);
  114648. #if 0
  114649. {
  114650. char buf[80];
  114651. float work[n/2];
  114652. for(j=0;j<n/2;j++)
  114653. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]]*(res+n/2)[j];
  114654. sprintf(buf,"resI%c%d",i?'R':'L',k);
  114655. _analysis_output(buf,seq,work,n/2,1,1,0);
  114656. }
  114657. #endif
  114658. }
  114659. /* our iteration is now based on masking curve, not prequant and
  114660. coupling. Only one prequant/coupling step */
  114661. /* quantize/couple */
  114662. /* incomplete implementation that assumes the tree is all depth
  114663. one, or no tree at all */
  114664. if(info->coupling_steps){
  114665. _vp_couple(k,
  114666. &ci->psy_g_param,
  114667. psy_look,
  114668. info,
  114669. vb->pcm,
  114670. mag_memo,
  114671. mag_sort,
  114672. ilogmaskch,
  114673. nonzero,
  114674. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  114675. }
  114676. /* classify and encode by submap */
  114677. for(i=0;i<info->submaps;i++){
  114678. int ch_in_bundle=0;
  114679. long **classifications;
  114680. int resnum=info->residuesubmap[i];
  114681. for(j=0;j<vi->channels;j++){
  114682. if(info->chmuxlist[j]==i){
  114683. zerobundle[ch_in_bundle]=0;
  114684. if(nonzero[j])zerobundle[ch_in_bundle]=1;
  114685. res_bundle[ch_in_bundle]=vb->pcm[j];
  114686. couple_bundle[ch_in_bundle++]=vb->pcm[j]+n/2;
  114687. }
  114688. }
  114689. classifications=_residue_P[ci->residue_type[resnum]]->
  114690. classx(vb,b->residue[resnum],couple_bundle,zerobundle,ch_in_bundle);
  114691. _residue_P[ci->residue_type[resnum]]->
  114692. forward(opb,vb,b->residue[resnum],
  114693. couple_bundle,NULL,zerobundle,ch_in_bundle,classifications);
  114694. }
  114695. /* ok, done encoding. Next protopacket. */
  114696. }
  114697. }
  114698. #if 0
  114699. seq++;
  114700. total+=ci->blocksizes[vb->W]/4+ci->blocksizes[vb->nW]/4;
  114701. #endif
  114702. return(0);
  114703. }
  114704. static int mapping0_inverse(vorbis_block *vb,vorbis_info_mapping *l){
  114705. vorbis_dsp_state *vd=vb->vd;
  114706. vorbis_info *vi=vd->vi;
  114707. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  114708. private_state *b=(private_state*)vd->backend_state;
  114709. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)l;
  114710. int i,j;
  114711. long n=vb->pcmend=ci->blocksizes[vb->W];
  114712. float **pcmbundle=(float**) alloca(sizeof(*pcmbundle)*vi->channels);
  114713. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  114714. int *nonzero =(int*) alloca(sizeof(*nonzero)*vi->channels);
  114715. void **floormemo=(void**) alloca(sizeof(*floormemo)*vi->channels);
  114716. /* recover the spectral envelope; store it in the PCM vector for now */
  114717. for(i=0;i<vi->channels;i++){
  114718. int submap=info->chmuxlist[i];
  114719. floormemo[i]=_floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  114720. inverse1(vb,b->flr[info->floorsubmap[submap]]);
  114721. if(floormemo[i])
  114722. nonzero[i]=1;
  114723. else
  114724. nonzero[i]=0;
  114725. memset(vb->pcm[i],0,sizeof(*vb->pcm[i])*n/2);
  114726. }
  114727. /* channel coupling can 'dirty' the nonzero listing */
  114728. for(i=0;i<info->coupling_steps;i++){
  114729. if(nonzero[info->coupling_mag[i]] ||
  114730. nonzero[info->coupling_ang[i]]){
  114731. nonzero[info->coupling_mag[i]]=1;
  114732. nonzero[info->coupling_ang[i]]=1;
  114733. }
  114734. }
  114735. /* recover the residue into our working vectors */
  114736. for(i=0;i<info->submaps;i++){
  114737. int ch_in_bundle=0;
  114738. for(j=0;j<vi->channels;j++){
  114739. if(info->chmuxlist[j]==i){
  114740. if(nonzero[j])
  114741. zerobundle[ch_in_bundle]=1;
  114742. else
  114743. zerobundle[ch_in_bundle]=0;
  114744. pcmbundle[ch_in_bundle++]=vb->pcm[j];
  114745. }
  114746. }
  114747. _residue_P[ci->residue_type[info->residuesubmap[i]]]->
  114748. inverse(vb,b->residue[info->residuesubmap[i]],
  114749. pcmbundle,zerobundle,ch_in_bundle);
  114750. }
  114751. /* channel coupling */
  114752. for(i=info->coupling_steps-1;i>=0;i--){
  114753. float *pcmM=vb->pcm[info->coupling_mag[i]];
  114754. float *pcmA=vb->pcm[info->coupling_ang[i]];
  114755. for(j=0;j<n/2;j++){
  114756. float mag=pcmM[j];
  114757. float ang=pcmA[j];
  114758. if(mag>0)
  114759. if(ang>0){
  114760. pcmM[j]=mag;
  114761. pcmA[j]=mag-ang;
  114762. }else{
  114763. pcmA[j]=mag;
  114764. pcmM[j]=mag+ang;
  114765. }
  114766. else
  114767. if(ang>0){
  114768. pcmM[j]=mag;
  114769. pcmA[j]=mag+ang;
  114770. }else{
  114771. pcmA[j]=mag;
  114772. pcmM[j]=mag-ang;
  114773. }
  114774. }
  114775. }
  114776. /* compute and apply spectral envelope */
  114777. for(i=0;i<vi->channels;i++){
  114778. float *pcm=vb->pcm[i];
  114779. int submap=info->chmuxlist[i];
  114780. _floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  114781. inverse2(vb,b->flr[info->floorsubmap[submap]],
  114782. floormemo[i],pcm);
  114783. }
  114784. /* transform the PCM data; takes PCM vector, vb; modifies PCM vector */
  114785. /* only MDCT right now.... */
  114786. for(i=0;i<vi->channels;i++){
  114787. float *pcm=vb->pcm[i];
  114788. mdct_backward((mdct_lookup*) b->transform[vb->W][0],pcm,pcm);
  114789. }
  114790. /* all done! */
  114791. return(0);
  114792. }
  114793. /* export hooks */
  114794. vorbis_func_mapping mapping0_exportbundle={
  114795. &mapping0_pack,
  114796. &mapping0_unpack,
  114797. &mapping0_free_info,
  114798. &mapping0_forward,
  114799. &mapping0_inverse
  114800. };
  114801. #endif
  114802. /*** End of inlined file: mapping0.c ***/
  114803. /*** Start of inlined file: mdct.c ***/
  114804. /* this can also be run as an integer transform by uncommenting a
  114805. define in mdct.h; the integerization is a first pass and although
  114806. it's likely stable for Vorbis, the dynamic range is constrained and
  114807. roundoff isn't done (so it's noisy). Consider it functional, but
  114808. only a starting point. There's no point on a machine with an FPU */
  114809. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114810. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114811. // tasks..
  114812. #if JUCE_MSVC
  114813. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114814. #endif
  114815. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114816. #if JUCE_USE_OGGVORBIS
  114817. #include <stdio.h>
  114818. #include <stdlib.h>
  114819. #include <string.h>
  114820. #include <math.h>
  114821. /* build lookups for trig functions; also pre-figure scaling and
  114822. some window function algebra. */
  114823. void mdct_init(mdct_lookup *lookup,int n){
  114824. int *bitrev=(int*) _ogg_malloc(sizeof(*bitrev)*(n/4));
  114825. DATA_TYPE *T=(DATA_TYPE*) _ogg_malloc(sizeof(*T)*(n+n/4));
  114826. int i;
  114827. int n2=n>>1;
  114828. int log2n=lookup->log2n=rint(log((float)n)/log(2.f));
  114829. lookup->n=n;
  114830. lookup->trig=T;
  114831. lookup->bitrev=bitrev;
  114832. /* trig lookups... */
  114833. for(i=0;i<n/4;i++){
  114834. T[i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i)));
  114835. T[i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i)));
  114836. T[n2+i*2]=FLOAT_CONV(cos((M_PI/(2*n))*(2*i+1)));
  114837. T[n2+i*2+1]=FLOAT_CONV(sin((M_PI/(2*n))*(2*i+1)));
  114838. }
  114839. for(i=0;i<n/8;i++){
  114840. T[n+i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i+2))*.5);
  114841. T[n+i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i+2))*.5);
  114842. }
  114843. /* bitreverse lookup... */
  114844. {
  114845. int mask=(1<<(log2n-1))-1,i,j;
  114846. int msb=1<<(log2n-2);
  114847. for(i=0;i<n/8;i++){
  114848. int acc=0;
  114849. for(j=0;msb>>j;j++)
  114850. if((msb>>j)&i)acc|=1<<j;
  114851. bitrev[i*2]=((~acc)&mask)-1;
  114852. bitrev[i*2+1]=acc;
  114853. }
  114854. }
  114855. lookup->scale=FLOAT_CONV(4.f/n);
  114856. }
  114857. /* 8 point butterfly (in place, 4 register) */
  114858. STIN void mdct_butterfly_8(DATA_TYPE *x){
  114859. REG_TYPE r0 = x[6] + x[2];
  114860. REG_TYPE r1 = x[6] - x[2];
  114861. REG_TYPE r2 = x[4] + x[0];
  114862. REG_TYPE r3 = x[4] - x[0];
  114863. x[6] = r0 + r2;
  114864. x[4] = r0 - r2;
  114865. r0 = x[5] - x[1];
  114866. r2 = x[7] - x[3];
  114867. x[0] = r1 + r0;
  114868. x[2] = r1 - r0;
  114869. r0 = x[5] + x[1];
  114870. r1 = x[7] + x[3];
  114871. x[3] = r2 + r3;
  114872. x[1] = r2 - r3;
  114873. x[7] = r1 + r0;
  114874. x[5] = r1 - r0;
  114875. }
  114876. /* 16 point butterfly (in place, 4 register) */
  114877. STIN void mdct_butterfly_16(DATA_TYPE *x){
  114878. REG_TYPE r0 = x[1] - x[9];
  114879. REG_TYPE r1 = x[0] - x[8];
  114880. x[8] += x[0];
  114881. x[9] += x[1];
  114882. x[0] = MULT_NORM((r0 + r1) * cPI2_8);
  114883. x[1] = MULT_NORM((r0 - r1) * cPI2_8);
  114884. r0 = x[3] - x[11];
  114885. r1 = x[10] - x[2];
  114886. x[10] += x[2];
  114887. x[11] += x[3];
  114888. x[2] = r0;
  114889. x[3] = r1;
  114890. r0 = x[12] - x[4];
  114891. r1 = x[13] - x[5];
  114892. x[12] += x[4];
  114893. x[13] += x[5];
  114894. x[4] = MULT_NORM((r0 - r1) * cPI2_8);
  114895. x[5] = MULT_NORM((r0 + r1) * cPI2_8);
  114896. r0 = x[14] - x[6];
  114897. r1 = x[15] - x[7];
  114898. x[14] += x[6];
  114899. x[15] += x[7];
  114900. x[6] = r0;
  114901. x[7] = r1;
  114902. mdct_butterfly_8(x);
  114903. mdct_butterfly_8(x+8);
  114904. }
  114905. /* 32 point butterfly (in place, 4 register) */
  114906. STIN void mdct_butterfly_32(DATA_TYPE *x){
  114907. REG_TYPE r0 = x[30] - x[14];
  114908. REG_TYPE r1 = x[31] - x[15];
  114909. x[30] += x[14];
  114910. x[31] += x[15];
  114911. x[14] = r0;
  114912. x[15] = r1;
  114913. r0 = x[28] - x[12];
  114914. r1 = x[29] - x[13];
  114915. x[28] += x[12];
  114916. x[29] += x[13];
  114917. x[12] = MULT_NORM( r0 * cPI1_8 - r1 * cPI3_8 );
  114918. x[13] = MULT_NORM( r0 * cPI3_8 + r1 * cPI1_8 );
  114919. r0 = x[26] - x[10];
  114920. r1 = x[27] - x[11];
  114921. x[26] += x[10];
  114922. x[27] += x[11];
  114923. x[10] = MULT_NORM(( r0 - r1 ) * cPI2_8);
  114924. x[11] = MULT_NORM(( r0 + r1 ) * cPI2_8);
  114925. r0 = x[24] - x[8];
  114926. r1 = x[25] - x[9];
  114927. x[24] += x[8];
  114928. x[25] += x[9];
  114929. x[8] = MULT_NORM( r0 * cPI3_8 - r1 * cPI1_8 );
  114930. x[9] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  114931. r0 = x[22] - x[6];
  114932. r1 = x[7] - x[23];
  114933. x[22] += x[6];
  114934. x[23] += x[7];
  114935. x[6] = r1;
  114936. x[7] = r0;
  114937. r0 = x[4] - x[20];
  114938. r1 = x[5] - x[21];
  114939. x[20] += x[4];
  114940. x[21] += x[5];
  114941. x[4] = MULT_NORM( r1 * cPI1_8 + r0 * cPI3_8 );
  114942. x[5] = MULT_NORM( r1 * cPI3_8 - r0 * cPI1_8 );
  114943. r0 = x[2] - x[18];
  114944. r1 = x[3] - x[19];
  114945. x[18] += x[2];
  114946. x[19] += x[3];
  114947. x[2] = MULT_NORM(( r1 + r0 ) * cPI2_8);
  114948. x[3] = MULT_NORM(( r1 - r0 ) * cPI2_8);
  114949. r0 = x[0] - x[16];
  114950. r1 = x[1] - x[17];
  114951. x[16] += x[0];
  114952. x[17] += x[1];
  114953. x[0] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  114954. x[1] = MULT_NORM( r1 * cPI1_8 - r0 * cPI3_8 );
  114955. mdct_butterfly_16(x);
  114956. mdct_butterfly_16(x+16);
  114957. }
  114958. /* N point first stage butterfly (in place, 2 register) */
  114959. STIN void mdct_butterfly_first(DATA_TYPE *T,
  114960. DATA_TYPE *x,
  114961. int points){
  114962. DATA_TYPE *x1 = x + points - 8;
  114963. DATA_TYPE *x2 = x + (points>>1) - 8;
  114964. REG_TYPE r0;
  114965. REG_TYPE r1;
  114966. do{
  114967. r0 = x1[6] - x2[6];
  114968. r1 = x1[7] - x2[7];
  114969. x1[6] += x2[6];
  114970. x1[7] += x2[7];
  114971. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  114972. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  114973. r0 = x1[4] - x2[4];
  114974. r1 = x1[5] - x2[5];
  114975. x1[4] += x2[4];
  114976. x1[5] += x2[5];
  114977. x2[4] = MULT_NORM(r1 * T[5] + r0 * T[4]);
  114978. x2[5] = MULT_NORM(r1 * T[4] - r0 * T[5]);
  114979. r0 = x1[2] - x2[2];
  114980. r1 = x1[3] - x2[3];
  114981. x1[2] += x2[2];
  114982. x1[3] += x2[3];
  114983. x2[2] = MULT_NORM(r1 * T[9] + r0 * T[8]);
  114984. x2[3] = MULT_NORM(r1 * T[8] - r0 * T[9]);
  114985. r0 = x1[0] - x2[0];
  114986. r1 = x1[1] - x2[1];
  114987. x1[0] += x2[0];
  114988. x1[1] += x2[1];
  114989. x2[0] = MULT_NORM(r1 * T[13] + r0 * T[12]);
  114990. x2[1] = MULT_NORM(r1 * T[12] - r0 * T[13]);
  114991. x1-=8;
  114992. x2-=8;
  114993. T+=16;
  114994. }while(x2>=x);
  114995. }
  114996. /* N/stage point generic N stage butterfly (in place, 2 register) */
  114997. STIN void mdct_butterfly_generic(DATA_TYPE *T,
  114998. DATA_TYPE *x,
  114999. int points,
  115000. int trigint){
  115001. DATA_TYPE *x1 = x + points - 8;
  115002. DATA_TYPE *x2 = x + (points>>1) - 8;
  115003. REG_TYPE r0;
  115004. REG_TYPE r1;
  115005. do{
  115006. r0 = x1[6] - x2[6];
  115007. r1 = x1[7] - x2[7];
  115008. x1[6] += x2[6];
  115009. x1[7] += x2[7];
  115010. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115011. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115012. T+=trigint;
  115013. r0 = x1[4] - x2[4];
  115014. r1 = x1[5] - x2[5];
  115015. x1[4] += x2[4];
  115016. x1[5] += x2[5];
  115017. x2[4] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115018. x2[5] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115019. T+=trigint;
  115020. r0 = x1[2] - x2[2];
  115021. r1 = x1[3] - x2[3];
  115022. x1[2] += x2[2];
  115023. x1[3] += x2[3];
  115024. x2[2] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115025. x2[3] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115026. T+=trigint;
  115027. r0 = x1[0] - x2[0];
  115028. r1 = x1[1] - x2[1];
  115029. x1[0] += x2[0];
  115030. x1[1] += x2[1];
  115031. x2[0] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115032. x2[1] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115033. T+=trigint;
  115034. x1-=8;
  115035. x2-=8;
  115036. }while(x2>=x);
  115037. }
  115038. STIN void mdct_butterflies(mdct_lookup *init,
  115039. DATA_TYPE *x,
  115040. int points){
  115041. DATA_TYPE *T=init->trig;
  115042. int stages=init->log2n-5;
  115043. int i,j;
  115044. if(--stages>0){
  115045. mdct_butterfly_first(T,x,points);
  115046. }
  115047. for(i=1;--stages>0;i++){
  115048. for(j=0;j<(1<<i);j++)
  115049. mdct_butterfly_generic(T,x+(points>>i)*j,points>>i,4<<i);
  115050. }
  115051. for(j=0;j<points;j+=32)
  115052. mdct_butterfly_32(x+j);
  115053. }
  115054. void mdct_clear(mdct_lookup *l){
  115055. if(l){
  115056. if(l->trig)_ogg_free(l->trig);
  115057. if(l->bitrev)_ogg_free(l->bitrev);
  115058. memset(l,0,sizeof(*l));
  115059. }
  115060. }
  115061. STIN void mdct_bitreverse(mdct_lookup *init,
  115062. DATA_TYPE *x){
  115063. int n = init->n;
  115064. int *bit = init->bitrev;
  115065. DATA_TYPE *w0 = x;
  115066. DATA_TYPE *w1 = x = w0+(n>>1);
  115067. DATA_TYPE *T = init->trig+n;
  115068. do{
  115069. DATA_TYPE *x0 = x+bit[0];
  115070. DATA_TYPE *x1 = x+bit[1];
  115071. REG_TYPE r0 = x0[1] - x1[1];
  115072. REG_TYPE r1 = x0[0] + x1[0];
  115073. REG_TYPE r2 = MULT_NORM(r1 * T[0] + r0 * T[1]);
  115074. REG_TYPE r3 = MULT_NORM(r1 * T[1] - r0 * T[0]);
  115075. w1 -= 4;
  115076. r0 = HALVE(x0[1] + x1[1]);
  115077. r1 = HALVE(x0[0] - x1[0]);
  115078. w0[0] = r0 + r2;
  115079. w1[2] = r0 - r2;
  115080. w0[1] = r1 + r3;
  115081. w1[3] = r3 - r1;
  115082. x0 = x+bit[2];
  115083. x1 = x+bit[3];
  115084. r0 = x0[1] - x1[1];
  115085. r1 = x0[0] + x1[0];
  115086. r2 = MULT_NORM(r1 * T[2] + r0 * T[3]);
  115087. r3 = MULT_NORM(r1 * T[3] - r0 * T[2]);
  115088. r0 = HALVE(x0[1] + x1[1]);
  115089. r1 = HALVE(x0[0] - x1[0]);
  115090. w0[2] = r0 + r2;
  115091. w1[0] = r0 - r2;
  115092. w0[3] = r1 + r3;
  115093. w1[1] = r3 - r1;
  115094. T += 4;
  115095. bit += 4;
  115096. w0 += 4;
  115097. }while(w0<w1);
  115098. }
  115099. void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  115100. int n=init->n;
  115101. int n2=n>>1;
  115102. int n4=n>>2;
  115103. /* rotate */
  115104. DATA_TYPE *iX = in+n2-7;
  115105. DATA_TYPE *oX = out+n2+n4;
  115106. DATA_TYPE *T = init->trig+n4;
  115107. do{
  115108. oX -= 4;
  115109. oX[0] = MULT_NORM(-iX[2] * T[3] - iX[0] * T[2]);
  115110. oX[1] = MULT_NORM (iX[0] * T[3] - iX[2] * T[2]);
  115111. oX[2] = MULT_NORM(-iX[6] * T[1] - iX[4] * T[0]);
  115112. oX[3] = MULT_NORM (iX[4] * T[1] - iX[6] * T[0]);
  115113. iX -= 8;
  115114. T += 4;
  115115. }while(iX>=in);
  115116. iX = in+n2-8;
  115117. oX = out+n2+n4;
  115118. T = init->trig+n4;
  115119. do{
  115120. T -= 4;
  115121. oX[0] = MULT_NORM (iX[4] * T[3] + iX[6] * T[2]);
  115122. oX[1] = MULT_NORM (iX[4] * T[2] - iX[6] * T[3]);
  115123. oX[2] = MULT_NORM (iX[0] * T[1] + iX[2] * T[0]);
  115124. oX[3] = MULT_NORM (iX[0] * T[0] - iX[2] * T[1]);
  115125. iX -= 8;
  115126. oX += 4;
  115127. }while(iX>=in);
  115128. mdct_butterflies(init,out+n2,n2);
  115129. mdct_bitreverse(init,out);
  115130. /* roatate + window */
  115131. {
  115132. DATA_TYPE *oX1=out+n2+n4;
  115133. DATA_TYPE *oX2=out+n2+n4;
  115134. DATA_TYPE *iX =out;
  115135. T =init->trig+n2;
  115136. do{
  115137. oX1-=4;
  115138. oX1[3] = MULT_NORM (iX[0] * T[1] - iX[1] * T[0]);
  115139. oX2[0] = -MULT_NORM (iX[0] * T[0] + iX[1] * T[1]);
  115140. oX1[2] = MULT_NORM (iX[2] * T[3] - iX[3] * T[2]);
  115141. oX2[1] = -MULT_NORM (iX[2] * T[2] + iX[3] * T[3]);
  115142. oX1[1] = MULT_NORM (iX[4] * T[5] - iX[5] * T[4]);
  115143. oX2[2] = -MULT_NORM (iX[4] * T[4] + iX[5] * T[5]);
  115144. oX1[0] = MULT_NORM (iX[6] * T[7] - iX[7] * T[6]);
  115145. oX2[3] = -MULT_NORM (iX[6] * T[6] + iX[7] * T[7]);
  115146. oX2+=4;
  115147. iX += 8;
  115148. T += 8;
  115149. }while(iX<oX1);
  115150. iX=out+n2+n4;
  115151. oX1=out+n4;
  115152. oX2=oX1;
  115153. do{
  115154. oX1-=4;
  115155. iX-=4;
  115156. oX2[0] = -(oX1[3] = iX[3]);
  115157. oX2[1] = -(oX1[2] = iX[2]);
  115158. oX2[2] = -(oX1[1] = iX[1]);
  115159. oX2[3] = -(oX1[0] = iX[0]);
  115160. oX2+=4;
  115161. }while(oX2<iX);
  115162. iX=out+n2+n4;
  115163. oX1=out+n2+n4;
  115164. oX2=out+n2;
  115165. do{
  115166. oX1-=4;
  115167. oX1[0]= iX[3];
  115168. oX1[1]= iX[2];
  115169. oX1[2]= iX[1];
  115170. oX1[3]= iX[0];
  115171. iX+=4;
  115172. }while(oX1>oX2);
  115173. }
  115174. }
  115175. void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  115176. int n=init->n;
  115177. int n2=n>>1;
  115178. int n4=n>>2;
  115179. int n8=n>>3;
  115180. DATA_TYPE *w=(DATA_TYPE*) alloca(n*sizeof(*w)); /* forward needs working space */
  115181. DATA_TYPE *w2=w+n2;
  115182. /* rotate */
  115183. /* window + rotate + step 1 */
  115184. REG_TYPE r0;
  115185. REG_TYPE r1;
  115186. DATA_TYPE *x0=in+n2+n4;
  115187. DATA_TYPE *x1=x0+1;
  115188. DATA_TYPE *T=init->trig+n2;
  115189. int i=0;
  115190. for(i=0;i<n8;i+=2){
  115191. x0 -=4;
  115192. T-=2;
  115193. r0= x0[2] + x1[0];
  115194. r1= x0[0] + x1[2];
  115195. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  115196. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  115197. x1 +=4;
  115198. }
  115199. x1=in+1;
  115200. for(;i<n2-n8;i+=2){
  115201. T-=2;
  115202. x0 -=4;
  115203. r0= x0[2] - x1[0];
  115204. r1= x0[0] - x1[2];
  115205. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  115206. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  115207. x1 +=4;
  115208. }
  115209. x0=in+n;
  115210. for(;i<n2;i+=2){
  115211. T-=2;
  115212. x0 -=4;
  115213. r0= -x0[2] - x1[0];
  115214. r1= -x0[0] - x1[2];
  115215. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  115216. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  115217. x1 +=4;
  115218. }
  115219. mdct_butterflies(init,w+n2,n2);
  115220. mdct_bitreverse(init,w);
  115221. /* roatate + window */
  115222. T=init->trig+n2;
  115223. x0=out+n2;
  115224. for(i=0;i<n4;i++){
  115225. x0--;
  115226. out[i] =MULT_NORM((w[0]*T[0]+w[1]*T[1])*init->scale);
  115227. x0[0] =MULT_NORM((w[0]*T[1]-w[1]*T[0])*init->scale);
  115228. w+=2;
  115229. T+=2;
  115230. }
  115231. }
  115232. #endif
  115233. /*** End of inlined file: mdct.c ***/
  115234. /*** Start of inlined file: psy.c ***/
  115235. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  115236. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  115237. // tasks..
  115238. #if JUCE_MSVC
  115239. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  115240. #endif
  115241. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  115242. #if JUCE_USE_OGGVORBIS
  115243. #include <stdlib.h>
  115244. #include <math.h>
  115245. #include <string.h>
  115246. /*** Start of inlined file: masking.h ***/
  115247. #ifndef _V_MASKING_H_
  115248. #define _V_MASKING_H_
  115249. /* more detailed ATH; the bass if flat to save stressing the floor
  115250. overly for only a bin or two of savings. */
  115251. #define MAX_ATH 88
  115252. static float ATH[]={
  115253. /*15*/ -51, -52, -53, -54, -55, -56, -57, -58,
  115254. /*31*/ -59, -60, -61, -62, -63, -64, -65, -66,
  115255. /*63*/ -67, -68, -69, -70, -71, -72, -73, -74,
  115256. /*125*/ -75, -76, -77, -78, -80, -81, -82, -83,
  115257. /*250*/ -84, -85, -86, -87, -88, -88, -89, -89,
  115258. /*500*/ -90, -91, -91, -92, -93, -94, -95, -96,
  115259. /*1k*/ -96, -97, -98, -98, -99, -99,-100,-100,
  115260. /*2k*/ -101,-102,-103,-104,-106,-107,-107,-107,
  115261. /*4k*/ -107,-105,-103,-102,-101, -99, -98, -96,
  115262. /*8k*/ -95, -95, -96, -97, -96, -95, -93, -90,
  115263. /*16k*/ -80, -70, -50, -40, -30, -30, -30, -30
  115264. };
  115265. /* The tone masking curves from Ehmer's and Fielder's papers have been
  115266. replaced by an empirically collected data set. The previously
  115267. published values were, far too often, simply on crack. */
  115268. #define EHMER_OFFSET 16
  115269. #define EHMER_MAX 56
  115270. /* masking tones from -50 to 0dB, 62.5 through 16kHz at half octaves
  115271. test tones from -2 octaves to +5 octaves sampled at eighth octaves */
  115272. /* (Vorbis 0dB, the loudest possible tone, is assumed to be ~100dB SPL
  115273. for collection of these curves) */
  115274. static float tonemasks[P_BANDS][6][EHMER_MAX]={
  115275. /* 62.5 Hz */
  115276. {{ -60, -60, -60, -60, -60, -60, -60, -60,
  115277. -60, -60, -60, -60, -62, -62, -65, -73,
  115278. -69, -68, -68, -67, -70, -70, -72, -74,
  115279. -75, -79, -79, -80, -83, -88, -93, -100,
  115280. -110, -999, -999, -999, -999, -999, -999, -999,
  115281. -999, -999, -999, -999, -999, -999, -999, -999,
  115282. -999, -999, -999, -999, -999, -999, -999, -999},
  115283. { -48, -48, -48, -48, -48, -48, -48, -48,
  115284. -48, -48, -48, -48, -48, -53, -61, -66,
  115285. -66, -68, -67, -70, -76, -76, -72, -73,
  115286. -75, -76, -78, -79, -83, -88, -93, -100,
  115287. -110, -999, -999, -999, -999, -999, -999, -999,
  115288. -999, -999, -999, -999, -999, -999, -999, -999,
  115289. -999, -999, -999, -999, -999, -999, -999, -999},
  115290. { -37, -37, -37, -37, -37, -37, -37, -37,
  115291. -38, -40, -42, -46, -48, -53, -55, -62,
  115292. -65, -58, -56, -56, -61, -60, -65, -67,
  115293. -69, -71, -77, -77, -78, -80, -82, -84,
  115294. -88, -93, -98, -106, -112, -999, -999, -999,
  115295. -999, -999, -999, -999, -999, -999, -999, -999,
  115296. -999, -999, -999, -999, -999, -999, -999, -999},
  115297. { -25, -25, -25, -25, -25, -25, -25, -25,
  115298. -25, -26, -27, -29, -32, -38, -48, -52,
  115299. -52, -50, -48, -48, -51, -52, -54, -60,
  115300. -67, -67, -66, -68, -69, -73, -73, -76,
  115301. -80, -81, -81, -85, -85, -86, -88, -93,
  115302. -100, -110, -999, -999, -999, -999, -999, -999,
  115303. -999, -999, -999, -999, -999, -999, -999, -999},
  115304. { -16, -16, -16, -16, -16, -16, -16, -16,
  115305. -17, -19, -20, -22, -26, -28, -31, -40,
  115306. -47, -39, -39, -40, -42, -43, -47, -51,
  115307. -57, -52, -55, -55, -60, -58, -62, -63,
  115308. -70, -67, -69, -72, -73, -77, -80, -82,
  115309. -83, -87, -90, -94, -98, -104, -115, -999,
  115310. -999, -999, -999, -999, -999, -999, -999, -999},
  115311. { -8, -8, -8, -8, -8, -8, -8, -8,
  115312. -8, -8, -10, -11, -15, -19, -25, -30,
  115313. -34, -31, -30, -31, -29, -32, -35, -42,
  115314. -48, -42, -44, -46, -50, -50, -51, -52,
  115315. -59, -54, -55, -55, -58, -62, -63, -66,
  115316. -72, -73, -76, -75, -78, -80, -80, -81,
  115317. -84, -88, -90, -94, -98, -101, -106, -110}},
  115318. /* 88Hz */
  115319. {{ -66, -66, -66, -66, -66, -66, -66, -66,
  115320. -66, -66, -66, -66, -66, -67, -67, -67,
  115321. -76, -72, -71, -74, -76, -76, -75, -78,
  115322. -79, -79, -81, -83, -86, -89, -93, -97,
  115323. -100, -105, -110, -999, -999, -999, -999, -999,
  115324. -999, -999, -999, -999, -999, -999, -999, -999,
  115325. -999, -999, -999, -999, -999, -999, -999, -999},
  115326. { -47, -47, -47, -47, -47, -47, -47, -47,
  115327. -47, -47, -47, -48, -51, -55, -59, -66,
  115328. -66, -66, -67, -66, -68, -69, -70, -74,
  115329. -79, -77, -77, -78, -80, -81, -82, -84,
  115330. -86, -88, -91, -95, -100, -108, -116, -999,
  115331. -999, -999, -999, -999, -999, -999, -999, -999,
  115332. -999, -999, -999, -999, -999, -999, -999, -999},
  115333. { -36, -36, -36, -36, -36, -36, -36, -36,
  115334. -36, -37, -37, -41, -44, -48, -51, -58,
  115335. -62, -60, -57, -59, -59, -60, -63, -65,
  115336. -72, -71, -70, -72, -74, -77, -76, -78,
  115337. -81, -81, -80, -83, -86, -91, -96, -100,
  115338. -105, -110, -999, -999, -999, -999, -999, -999,
  115339. -999, -999, -999, -999, -999, -999, -999, -999},
  115340. { -28, -28, -28, -28, -28, -28, -28, -28,
  115341. -28, -30, -32, -32, -33, -35, -41, -49,
  115342. -50, -49, -47, -48, -48, -52, -51, -57,
  115343. -65, -61, -59, -61, -64, -69, -70, -74,
  115344. -77, -77, -78, -81, -84, -85, -87, -90,
  115345. -92, -96, -100, -107, -112, -999, -999, -999,
  115346. -999, -999, -999, -999, -999, -999, -999, -999},
  115347. { -19, -19, -19, -19, -19, -19, -19, -19,
  115348. -20, -21, -23, -27, -30, -35, -36, -41,
  115349. -46, -44, -42, -40, -41, -41, -43, -48,
  115350. -55, -53, -52, -53, -56, -59, -58, -60,
  115351. -67, -66, -69, -71, -72, -75, -79, -81,
  115352. -84, -87, -90, -93, -97, -101, -107, -114,
  115353. -999, -999, -999, -999, -999, -999, -999, -999},
  115354. { -9, -9, -9, -9, -9, -9, -9, -9,
  115355. -11, -12, -12, -15, -16, -20, -23, -30,
  115356. -37, -34, -33, -34, -31, -32, -32, -38,
  115357. -47, -44, -41, -40, -47, -49, -46, -46,
  115358. -58, -50, -50, -54, -58, -62, -64, -67,
  115359. -67, -70, -72, -76, -79, -83, -87, -91,
  115360. -96, -100, -104, -110, -999, -999, -999, -999}},
  115361. /* 125 Hz */
  115362. {{ -62, -62, -62, -62, -62, -62, -62, -62,
  115363. -62, -62, -63, -64, -66, -67, -66, -68,
  115364. -75, -72, -76, -75, -76, -78, -79, -82,
  115365. -84, -85, -90, -94, -101, -110, -999, -999,
  115366. -999, -999, -999, -999, -999, -999, -999, -999,
  115367. -999, -999, -999, -999, -999, -999, -999, -999,
  115368. -999, -999, -999, -999, -999, -999, -999, -999},
  115369. { -59, -59, -59, -59, -59, -59, -59, -59,
  115370. -59, -59, -59, -60, -60, -61, -63, -66,
  115371. -71, -68, -70, -70, -71, -72, -72, -75,
  115372. -81, -78, -79, -82, -83, -86, -90, -97,
  115373. -103, -113, -999, -999, -999, -999, -999, -999,
  115374. -999, -999, -999, -999, -999, -999, -999, -999,
  115375. -999, -999, -999, -999, -999, -999, -999, -999},
  115376. { -53, -53, -53, -53, -53, -53, -53, -53,
  115377. -53, -54, -55, -57, -56, -57, -55, -61,
  115378. -65, -60, -60, -62, -63, -63, -66, -68,
  115379. -74, -73, -75, -75, -78, -80, -80, -82,
  115380. -85, -90, -96, -101, -108, -999, -999, -999,
  115381. -999, -999, -999, -999, -999, -999, -999, -999,
  115382. -999, -999, -999, -999, -999, -999, -999, -999},
  115383. { -46, -46, -46, -46, -46, -46, -46, -46,
  115384. -46, -46, -47, -47, -47, -47, -48, -51,
  115385. -57, -51, -49, -50, -51, -53, -54, -59,
  115386. -66, -60, -62, -67, -67, -70, -72, -75,
  115387. -76, -78, -81, -85, -88, -94, -97, -104,
  115388. -112, -999, -999, -999, -999, -999, -999, -999,
  115389. -999, -999, -999, -999, -999, -999, -999, -999},
  115390. { -36, -36, -36, -36, -36, -36, -36, -36,
  115391. -39, -41, -42, -42, -39, -38, -41, -43,
  115392. -52, -44, -40, -39, -37, -37, -40, -47,
  115393. -54, -50, -48, -50, -55, -61, -59, -62,
  115394. -66, -66, -66, -69, -69, -73, -74, -74,
  115395. -75, -77, -79, -82, -87, -91, -95, -100,
  115396. -108, -115, -999, -999, -999, -999, -999, -999},
  115397. { -28, -26, -24, -22, -20, -20, -23, -29,
  115398. -30, -31, -28, -27, -28, -28, -28, -35,
  115399. -40, -33, -32, -29, -30, -30, -30, -37,
  115400. -45, -41, -37, -38, -45, -47, -47, -48,
  115401. -53, -49, -48, -50, -49, -49, -51, -52,
  115402. -58, -56, -57, -56, -60, -61, -62, -70,
  115403. -72, -74, -78, -83, -88, -93, -100, -106}},
  115404. /* 177 Hz */
  115405. {{-999, -999, -999, -999, -999, -999, -999, -999,
  115406. -999, -110, -105, -100, -95, -91, -87, -83,
  115407. -80, -78, -76, -78, -78, -81, -83, -85,
  115408. -86, -85, -86, -87, -90, -97, -107, -999,
  115409. -999, -999, -999, -999, -999, -999, -999, -999,
  115410. -999, -999, -999, -999, -999, -999, -999, -999,
  115411. -999, -999, -999, -999, -999, -999, -999, -999},
  115412. {-999, -999, -999, -110, -105, -100, -95, -90,
  115413. -85, -81, -77, -73, -70, -67, -67, -68,
  115414. -75, -73, -70, -69, -70, -72, -75, -79,
  115415. -84, -83, -84, -86, -88, -89, -89, -93,
  115416. -98, -105, -112, -999, -999, -999, -999, -999,
  115417. -999, -999, -999, -999, -999, -999, -999, -999,
  115418. -999, -999, -999, -999, -999, -999, -999, -999},
  115419. {-105, -100, -95, -90, -85, -80, -76, -71,
  115420. -68, -68, -65, -63, -63, -62, -62, -64,
  115421. -65, -64, -61, -62, -63, -64, -66, -68,
  115422. -73, -73, -74, -75, -76, -81, -83, -85,
  115423. -88, -89, -92, -95, -100, -108, -999, -999,
  115424. -999, -999, -999, -999, -999, -999, -999, -999,
  115425. -999, -999, -999, -999, -999, -999, -999, -999},
  115426. { -80, -75, -71, -68, -65, -63, -62, -61,
  115427. -61, -61, -61, -59, -56, -57, -53, -50,
  115428. -58, -52, -50, -50, -52, -53, -54, -58,
  115429. -67, -63, -67, -68, -72, -75, -78, -80,
  115430. -81, -81, -82, -85, -89, -90, -93, -97,
  115431. -101, -107, -114, -999, -999, -999, -999, -999,
  115432. -999, -999, -999, -999, -999, -999, -999, -999},
  115433. { -65, -61, -59, -57, -56, -55, -55, -56,
  115434. -56, -57, -55, -53, -52, -47, -44, -44,
  115435. -50, -44, -41, -39, -39, -42, -40, -46,
  115436. -51, -49, -50, -53, -54, -63, -60, -61,
  115437. -62, -66, -66, -66, -70, -73, -74, -75,
  115438. -76, -75, -79, -85, -89, -91, -96, -102,
  115439. -110, -999, -999, -999, -999, -999, -999, -999},
  115440. { -52, -50, -49, -49, -48, -48, -48, -49,
  115441. -50, -50, -49, -46, -43, -39, -35, -33,
  115442. -38, -36, -32, -29, -32, -32, -32, -35,
  115443. -44, -39, -38, -38, -46, -50, -45, -46,
  115444. -53, -50, -50, -50, -54, -54, -53, -53,
  115445. -56, -57, -59, -66, -70, -72, -74, -79,
  115446. -83, -85, -90, -97, -114, -999, -999, -999}},
  115447. /* 250 Hz */
  115448. {{-999, -999, -999, -999, -999, -999, -110, -105,
  115449. -100, -95, -90, -86, -80, -75, -75, -79,
  115450. -80, -79, -80, -81, -82, -88, -95, -103,
  115451. -110, -999, -999, -999, -999, -999, -999, -999,
  115452. -999, -999, -999, -999, -999, -999, -999, -999,
  115453. -999, -999, -999, -999, -999, -999, -999, -999,
  115454. -999, -999, -999, -999, -999, -999, -999, -999},
  115455. {-999, -999, -999, -999, -108, -103, -98, -93,
  115456. -88, -83, -79, -78, -75, -71, -67, -68,
  115457. -73, -73, -72, -73, -75, -77, -80, -82,
  115458. -88, -93, -100, -107, -114, -999, -999, -999,
  115459. -999, -999, -999, -999, -999, -999, -999, -999,
  115460. -999, -999, -999, -999, -999, -999, -999, -999,
  115461. -999, -999, -999, -999, -999, -999, -999, -999},
  115462. {-999, -999, -999, -110, -105, -101, -96, -90,
  115463. -86, -81, -77, -73, -69, -66, -61, -62,
  115464. -66, -64, -62, -65, -66, -70, -72, -76,
  115465. -81, -80, -84, -90, -95, -102, -110, -999,
  115466. -999, -999, -999, -999, -999, -999, -999, -999,
  115467. -999, -999, -999, -999, -999, -999, -999, -999,
  115468. -999, -999, -999, -999, -999, -999, -999, -999},
  115469. {-999, -999, -999, -107, -103, -97, -92, -88,
  115470. -83, -79, -74, -70, -66, -59, -53, -58,
  115471. -62, -55, -54, -54, -54, -58, -61, -62,
  115472. -72, -70, -72, -75, -78, -80, -81, -80,
  115473. -83, -83, -88, -93, -100, -107, -115, -999,
  115474. -999, -999, -999, -999, -999, -999, -999, -999,
  115475. -999, -999, -999, -999, -999, -999, -999, -999},
  115476. {-999, -999, -999, -105, -100, -95, -90, -85,
  115477. -80, -75, -70, -66, -62, -56, -48, -44,
  115478. -48, -46, -46, -43, -46, -48, -48, -51,
  115479. -58, -58, -59, -60, -62, -62, -61, -61,
  115480. -65, -64, -65, -68, -70, -74, -75, -78,
  115481. -81, -86, -95, -110, -999, -999, -999, -999,
  115482. -999, -999, -999, -999, -999, -999, -999, -999},
  115483. {-999, -999, -105, -100, -95, -90, -85, -80,
  115484. -75, -70, -65, -61, -55, -49, -39, -33,
  115485. -40, -35, -32, -38, -40, -33, -35, -37,
  115486. -46, -41, -45, -44, -46, -42, -45, -46,
  115487. -52, -50, -50, -50, -54, -54, -55, -57,
  115488. -62, -64, -66, -68, -70, -76, -81, -90,
  115489. -100, -110, -999, -999, -999, -999, -999, -999}},
  115490. /* 354 hz */
  115491. {{-999, -999, -999, -999, -999, -999, -999, -999,
  115492. -105, -98, -90, -85, -82, -83, -80, -78,
  115493. -84, -79, -80, -83, -87, -89, -91, -93,
  115494. -99, -106, -117, -999, -999, -999, -999, -999,
  115495. -999, -999, -999, -999, -999, -999, -999, -999,
  115496. -999, -999, -999, -999, -999, -999, -999, -999,
  115497. -999, -999, -999, -999, -999, -999, -999, -999},
  115498. {-999, -999, -999, -999, -999, -999, -999, -999,
  115499. -105, -98, -90, -85, -80, -75, -70, -68,
  115500. -74, -72, -74, -77, -80, -82, -85, -87,
  115501. -92, -89, -91, -95, -100, -106, -112, -999,
  115502. -999, -999, -999, -999, -999, -999, -999, -999,
  115503. -999, -999, -999, -999, -999, -999, -999, -999,
  115504. -999, -999, -999, -999, -999, -999, -999, -999},
  115505. {-999, -999, -999, -999, -999, -999, -999, -999,
  115506. -105, -98, -90, -83, -75, -71, -63, -64,
  115507. -67, -62, -64, -67, -70, -73, -77, -81,
  115508. -84, -83, -85, -89, -90, -93, -98, -104,
  115509. -109, -114, -999, -999, -999, -999, -999, -999,
  115510. -999, -999, -999, -999, -999, -999, -999, -999,
  115511. -999, -999, -999, -999, -999, -999, -999, -999},
  115512. {-999, -999, -999, -999, -999, -999, -999, -999,
  115513. -103, -96, -88, -81, -75, -68, -58, -54,
  115514. -56, -54, -56, -56, -58, -60, -63, -66,
  115515. -74, -69, -72, -72, -75, -74, -77, -81,
  115516. -81, -82, -84, -87, -93, -96, -99, -104,
  115517. -110, -999, -999, -999, -999, -999, -999, -999,
  115518. -999, -999, -999, -999, -999, -999, -999, -999},
  115519. {-999, -999, -999, -999, -999, -108, -102, -96,
  115520. -91, -85, -80, -74, -68, -60, -51, -46,
  115521. -48, -46, -43, -45, -47, -47, -49, -48,
  115522. -56, -53, -55, -58, -57, -63, -58, -60,
  115523. -66, -64, -67, -70, -70, -74, -77, -84,
  115524. -86, -89, -91, -93, -94, -101, -109, -118,
  115525. -999, -999, -999, -999, -999, -999, -999, -999},
  115526. {-999, -999, -999, -108, -103, -98, -93, -88,
  115527. -83, -78, -73, -68, -60, -53, -44, -35,
  115528. -38, -38, -34, -34, -36, -40, -41, -44,
  115529. -51, -45, -46, -47, -46, -54, -50, -49,
  115530. -50, -50, -50, -51, -54, -57, -58, -60,
  115531. -66, -66, -66, -64, -65, -68, -77, -82,
  115532. -87, -95, -110, -999, -999, -999, -999, -999}},
  115533. /* 500 Hz */
  115534. {{-999, -999, -999, -999, -999, -999, -999, -999,
  115535. -107, -102, -97, -92, -87, -83, -78, -75,
  115536. -82, -79, -83, -85, -89, -92, -95, -98,
  115537. -101, -105, -109, -113, -999, -999, -999, -999,
  115538. -999, -999, -999, -999, -999, -999, -999, -999,
  115539. -999, -999, -999, -999, -999, -999, -999, -999,
  115540. -999, -999, -999, -999, -999, -999, -999, -999},
  115541. {-999, -999, -999, -999, -999, -999, -999, -106,
  115542. -100, -95, -90, -86, -81, -78, -74, -69,
  115543. -74, -74, -76, -79, -83, -84, -86, -89,
  115544. -92, -97, -93, -100, -103, -107, -110, -999,
  115545. -999, -999, -999, -999, -999, -999, -999, -999,
  115546. -999, -999, -999, -999, -999, -999, -999, -999,
  115547. -999, -999, -999, -999, -999, -999, -999, -999},
  115548. {-999, -999, -999, -999, -999, -999, -106, -100,
  115549. -95, -90, -87, -83, -80, -75, -69, -60,
  115550. -66, -66, -68, -70, -74, -78, -79, -81,
  115551. -81, -83, -84, -87, -93, -96, -99, -103,
  115552. -107, -110, -999, -999, -999, -999, -999, -999,
  115553. -999, -999, -999, -999, -999, -999, -999, -999,
  115554. -999, -999, -999, -999, -999, -999, -999, -999},
  115555. {-999, -999, -999, -999, -999, -108, -103, -98,
  115556. -93, -89, -85, -82, -78, -71, -62, -55,
  115557. -58, -58, -54, -54, -55, -59, -61, -62,
  115558. -70, -66, -66, -67, -70, -72, -75, -78,
  115559. -84, -84, -84, -88, -91, -90, -95, -98,
  115560. -102, -103, -106, -110, -999, -999, -999, -999,
  115561. -999, -999, -999, -999, -999, -999, -999, -999},
  115562. {-999, -999, -999, -999, -108, -103, -98, -94,
  115563. -90, -87, -82, -79, -73, -67, -58, -47,
  115564. -50, -45, -41, -45, -48, -44, -44, -49,
  115565. -54, -51, -48, -47, -49, -50, -51, -57,
  115566. -58, -60, -63, -69, -70, -69, -71, -74,
  115567. -78, -82, -90, -95, -101, -105, -110, -999,
  115568. -999, -999, -999, -999, -999, -999, -999, -999},
  115569. {-999, -999, -999, -105, -101, -97, -93, -90,
  115570. -85, -80, -77, -72, -65, -56, -48, -37,
  115571. -40, -36, -34, -40, -50, -47, -38, -41,
  115572. -47, -38, -35, -39, -38, -43, -40, -45,
  115573. -50, -45, -44, -47, -50, -55, -48, -48,
  115574. -52, -66, -70, -76, -82, -90, -97, -105,
  115575. -110, -999, -999, -999, -999, -999, -999, -999}},
  115576. /* 707 Hz */
  115577. {{-999, -999, -999, -999, -999, -999, -999, -999,
  115578. -999, -108, -103, -98, -93, -86, -79, -76,
  115579. -83, -81, -85, -87, -89, -93, -98, -102,
  115580. -107, -112, -999, -999, -999, -999, -999, -999,
  115581. -999, -999, -999, -999, -999, -999, -999, -999,
  115582. -999, -999, -999, -999, -999, -999, -999, -999,
  115583. -999, -999, -999, -999, -999, -999, -999, -999},
  115584. {-999, -999, -999, -999, -999, -999, -999, -999,
  115585. -999, -108, -103, -98, -93, -86, -79, -71,
  115586. -77, -74, -77, -79, -81, -84, -85, -90,
  115587. -92, -93, -92, -98, -101, -108, -112, -999,
  115588. -999, -999, -999, -999, -999, -999, -999, -999,
  115589. -999, -999, -999, -999, -999, -999, -999, -999,
  115590. -999, -999, -999, -999, -999, -999, -999, -999},
  115591. {-999, -999, -999, -999, -999, -999, -999, -999,
  115592. -108, -103, -98, -93, -87, -78, -68, -65,
  115593. -66, -62, -65, -67, -70, -73, -75, -78,
  115594. -82, -82, -83, -84, -91, -93, -98, -102,
  115595. -106, -110, -999, -999, -999, -999, -999, -999,
  115596. -999, -999, -999, -999, -999, -999, -999, -999,
  115597. -999, -999, -999, -999, -999, -999, -999, -999},
  115598. {-999, -999, -999, -999, -999, -999, -999, -999,
  115599. -105, -100, -95, -90, -82, -74, -62, -57,
  115600. -58, -56, -51, -52, -52, -54, -54, -58,
  115601. -66, -59, -60, -63, -66, -69, -73, -79,
  115602. -83, -84, -80, -81, -81, -82, -88, -92,
  115603. -98, -105, -113, -999, -999, -999, -999, -999,
  115604. -999, -999, -999, -999, -999, -999, -999, -999},
  115605. {-999, -999, -999, -999, -999, -999, -999, -107,
  115606. -102, -97, -92, -84, -79, -69, -57, -47,
  115607. -52, -47, -44, -45, -50, -52, -42, -42,
  115608. -53, -43, -43, -48, -51, -56, -55, -52,
  115609. -57, -59, -61, -62, -67, -71, -78, -83,
  115610. -86, -94, -98, -103, -110, -999, -999, -999,
  115611. -999, -999, -999, -999, -999, -999, -999, -999},
  115612. {-999, -999, -999, -999, -999, -999, -105, -100,
  115613. -95, -90, -84, -78, -70, -61, -51, -41,
  115614. -40, -38, -40, -46, -52, -51, -41, -40,
  115615. -46, -40, -38, -38, -41, -46, -41, -46,
  115616. -47, -43, -43, -45, -41, -45, -56, -67,
  115617. -68, -83, -87, -90, -95, -102, -107, -113,
  115618. -999, -999, -999, -999, -999, -999, -999, -999}},
  115619. /* 1000 Hz */
  115620. {{-999, -999, -999, -999, -999, -999, -999, -999,
  115621. -999, -109, -105, -101, -96, -91, -84, -77,
  115622. -82, -82, -85, -89, -94, -100, -106, -110,
  115623. -999, -999, -999, -999, -999, -999, -999, -999,
  115624. -999, -999, -999, -999, -999, -999, -999, -999,
  115625. -999, -999, -999, -999, -999, -999, -999, -999,
  115626. -999, -999, -999, -999, -999, -999, -999, -999},
  115627. {-999, -999, -999, -999, -999, -999, -999, -999,
  115628. -999, -106, -103, -98, -92, -85, -80, -71,
  115629. -75, -72, -76, -80, -84, -86, -89, -93,
  115630. -100, -107, -113, -999, -999, -999, -999, -999,
  115631. -999, -999, -999, -999, -999, -999, -999, -999,
  115632. -999, -999, -999, -999, -999, -999, -999, -999,
  115633. -999, -999, -999, -999, -999, -999, -999, -999},
  115634. {-999, -999, -999, -999, -999, -999, -999, -107,
  115635. -104, -101, -97, -92, -88, -84, -80, -64,
  115636. -66, -63, -64, -66, -69, -73, -77, -83,
  115637. -83, -86, -91, -98, -104, -111, -999, -999,
  115638. -999, -999, -999, -999, -999, -999, -999, -999,
  115639. -999, -999, -999, -999, -999, -999, -999, -999,
  115640. -999, -999, -999, -999, -999, -999, -999, -999},
  115641. {-999, -999, -999, -999, -999, -999, -999, -107,
  115642. -104, -101, -97, -92, -90, -84, -74, -57,
  115643. -58, -52, -55, -54, -50, -52, -50, -52,
  115644. -63, -62, -69, -76, -77, -78, -78, -79,
  115645. -82, -88, -94, -100, -106, -111, -999, -999,
  115646. -999, -999, -999, -999, -999, -999, -999, -999,
  115647. -999, -999, -999, -999, -999, -999, -999, -999},
  115648. {-999, -999, -999, -999, -999, -999, -106, -102,
  115649. -98, -95, -90, -85, -83, -78, -70, -50,
  115650. -50, -41, -44, -49, -47, -50, -50, -44,
  115651. -55, -46, -47, -48, -48, -54, -49, -49,
  115652. -58, -62, -71, -81, -87, -92, -97, -102,
  115653. -108, -114, -999, -999, -999, -999, -999, -999,
  115654. -999, -999, -999, -999, -999, -999, -999, -999},
  115655. {-999, -999, -999, -999, -999, -999, -106, -102,
  115656. -98, -95, -90, -85, -83, -78, -70, -45,
  115657. -43, -41, -47, -50, -51, -50, -49, -45,
  115658. -47, -41, -44, -41, -39, -43, -38, -37,
  115659. -40, -41, -44, -50, -58, -65, -73, -79,
  115660. -85, -92, -97, -101, -105, -109, -113, -999,
  115661. -999, -999, -999, -999, -999, -999, -999, -999}},
  115662. /* 1414 Hz */
  115663. {{-999, -999, -999, -999, -999, -999, -999, -999,
  115664. -999, -999, -999, -107, -100, -95, -87, -81,
  115665. -85, -83, -88, -93, -100, -107, -114, -999,
  115666. -999, -999, -999, -999, -999, -999, -999, -999,
  115667. -999, -999, -999, -999, -999, -999, -999, -999,
  115668. -999, -999, -999, -999, -999, -999, -999, -999,
  115669. -999, -999, -999, -999, -999, -999, -999, -999},
  115670. {-999, -999, -999, -999, -999, -999, -999, -999,
  115671. -999, -999, -107, -101, -95, -88, -83, -76,
  115672. -73, -72, -79, -84, -90, -95, -100, -105,
  115673. -110, -115, -999, -999, -999, -999, -999, -999,
  115674. -999, -999, -999, -999, -999, -999, -999, -999,
  115675. -999, -999, -999, -999, -999, -999, -999, -999,
  115676. -999, -999, -999, -999, -999, -999, -999, -999},
  115677. {-999, -999, -999, -999, -999, -999, -999, -999,
  115678. -999, -999, -104, -98, -92, -87, -81, -70,
  115679. -65, -62, -67, -71, -74, -80, -85, -91,
  115680. -95, -99, -103, -108, -111, -114, -999, -999,
  115681. -999, -999, -999, -999, -999, -999, -999, -999,
  115682. -999, -999, -999, -999, -999, -999, -999, -999,
  115683. -999, -999, -999, -999, -999, -999, -999, -999},
  115684. {-999, -999, -999, -999, -999, -999, -999, -999,
  115685. -999, -999, -103, -97, -90, -85, -76, -60,
  115686. -56, -54, -60, -62, -61, -56, -63, -65,
  115687. -73, -74, -77, -75, -78, -81, -86, -87,
  115688. -88, -91, -94, -98, -103, -110, -999, -999,
  115689. -999, -999, -999, -999, -999, -999, -999, -999,
  115690. -999, -999, -999, -999, -999, -999, -999, -999},
  115691. {-999, -999, -999, -999, -999, -999, -999, -105,
  115692. -100, -97, -92, -86, -81, -79, -70, -57,
  115693. -51, -47, -51, -58, -60, -56, -53, -50,
  115694. -58, -52, -50, -50, -53, -55, -64, -69,
  115695. -71, -85, -82, -78, -81, -85, -95, -102,
  115696. -112, -999, -999, -999, -999, -999, -999, -999,
  115697. -999, -999, -999, -999, -999, -999, -999, -999},
  115698. {-999, -999, -999, -999, -999, -999, -999, -105,
  115699. -100, -97, -92, -85, -83, -79, -72, -49,
  115700. -40, -43, -43, -54, -56, -51, -50, -40,
  115701. -43, -38, -36, -35, -37, -38, -37, -44,
  115702. -54, -60, -57, -60, -70, -75, -84, -92,
  115703. -103, -112, -999, -999, -999, -999, -999, -999,
  115704. -999, -999, -999, -999, -999, -999, -999, -999}},
  115705. /* 2000 Hz */
  115706. {{-999, -999, -999, -999, -999, -999, -999, -999,
  115707. -999, -999, -999, -110, -102, -95, -89, -82,
  115708. -83, -84, -90, -92, -99, -107, -113, -999,
  115709. -999, -999, -999, -999, -999, -999, -999, -999,
  115710. -999, -999, -999, -999, -999, -999, -999, -999,
  115711. -999, -999, -999, -999, -999, -999, -999, -999,
  115712. -999, -999, -999, -999, -999, -999, -999, -999},
  115713. {-999, -999, -999, -999, -999, -999, -999, -999,
  115714. -999, -999, -107, -101, -95, -89, -83, -72,
  115715. -74, -78, -85, -88, -88, -90, -92, -98,
  115716. -105, -111, -999, -999, -999, -999, -999, -999,
  115717. -999, -999, -999, -999, -999, -999, -999, -999,
  115718. -999, -999, -999, -999, -999, -999, -999, -999,
  115719. -999, -999, -999, -999, -999, -999, -999, -999},
  115720. {-999, -999, -999, -999, -999, -999, -999, -999,
  115721. -999, -109, -103, -97, -93, -87, -81, -70,
  115722. -70, -67, -75, -73, -76, -79, -81, -83,
  115723. -88, -89, -97, -103, -110, -999, -999, -999,
  115724. -999, -999, -999, -999, -999, -999, -999, -999,
  115725. -999, -999, -999, -999, -999, -999, -999, -999,
  115726. -999, -999, -999, -999, -999, -999, -999, -999},
  115727. {-999, -999, -999, -999, -999, -999, -999, -999,
  115728. -999, -107, -100, -94, -88, -83, -75, -63,
  115729. -59, -59, -63, -66, -60, -62, -67, -67,
  115730. -77, -76, -81, -88, -86, -92, -96, -102,
  115731. -109, -116, -999, -999, -999, -999, -999, -999,
  115732. -999, -999, -999, -999, -999, -999, -999, -999,
  115733. -999, -999, -999, -999, -999, -999, -999, -999},
  115734. {-999, -999, -999, -999, -999, -999, -999, -999,
  115735. -999, -105, -98, -92, -86, -81, -73, -56,
  115736. -52, -47, -55, -60, -58, -52, -51, -45,
  115737. -49, -50, -53, -54, -61, -71, -70, -69,
  115738. -78, -79, -87, -90, -96, -104, -112, -999,
  115739. -999, -999, -999, -999, -999, -999, -999, -999,
  115740. -999, -999, -999, -999, -999, -999, -999, -999},
  115741. {-999, -999, -999, -999, -999, -999, -999, -999,
  115742. -999, -103, -96, -90, -86, -78, -70, -51,
  115743. -42, -47, -48, -55, -54, -54, -53, -42,
  115744. -35, -28, -33, -38, -37, -44, -47, -49,
  115745. -54, -63, -68, -78, -82, -89, -94, -99,
  115746. -104, -109, -114, -999, -999, -999, -999, -999,
  115747. -999, -999, -999, -999, -999, -999, -999, -999}},
  115748. /* 2828 Hz */
  115749. {{-999, -999, -999, -999, -999, -999, -999, -999,
  115750. -999, -999, -999, -999, -110, -100, -90, -79,
  115751. -85, -81, -82, -82, -89, -94, -99, -103,
  115752. -109, -115, -999, -999, -999, -999, -999, -999,
  115753. -999, -999, -999, -999, -999, -999, -999, -999,
  115754. -999, -999, -999, -999, -999, -999, -999, -999,
  115755. -999, -999, -999, -999, -999, -999, -999, -999},
  115756. {-999, -999, -999, -999, -999, -999, -999, -999,
  115757. -999, -999, -999, -999, -105, -97, -85, -72,
  115758. -74, -70, -70, -70, -76, -85, -91, -93,
  115759. -97, -103, -109, -115, -999, -999, -999, -999,
  115760. -999, -999, -999, -999, -999, -999, -999, -999,
  115761. -999, -999, -999, -999, -999, -999, -999, -999,
  115762. -999, -999, -999, -999, -999, -999, -999, -999},
  115763. {-999, -999, -999, -999, -999, -999, -999, -999,
  115764. -999, -999, -999, -999, -112, -93, -81, -68,
  115765. -62, -60, -60, -57, -63, -70, -77, -82,
  115766. -90, -93, -98, -104, -109, -113, -999, -999,
  115767. -999, -999, -999, -999, -999, -999, -999, -999,
  115768. -999, -999, -999, -999, -999, -999, -999, -999,
  115769. -999, -999, -999, -999, -999, -999, -999, -999},
  115770. {-999, -999, -999, -999, -999, -999, -999, -999,
  115771. -999, -999, -999, -113, -100, -93, -84, -63,
  115772. -58, -48, -53, -54, -52, -52, -57, -64,
  115773. -66, -76, -83, -81, -85, -85, -90, -95,
  115774. -98, -101, -103, -106, -108, -111, -999, -999,
  115775. -999, -999, -999, -999, -999, -999, -999, -999,
  115776. -999, -999, -999, -999, -999, -999, -999, -999},
  115777. {-999, -999, -999, -999, -999, -999, -999, -999,
  115778. -999, -999, -999, -105, -95, -86, -74, -53,
  115779. -50, -38, -43, -49, -43, -42, -39, -39,
  115780. -46, -52, -57, -56, -72, -69, -74, -81,
  115781. -87, -92, -94, -97, -99, -102, -105, -108,
  115782. -999, -999, -999, -999, -999, -999, -999, -999,
  115783. -999, -999, -999, -999, -999, -999, -999, -999},
  115784. {-999, -999, -999, -999, -999, -999, -999, -999,
  115785. -999, -999, -108, -99, -90, -76, -66, -45,
  115786. -43, -41, -44, -47, -43, -47, -40, -30,
  115787. -31, -31, -39, -33, -40, -41, -43, -53,
  115788. -59, -70, -73, -77, -79, -82, -84, -87,
  115789. -999, -999, -999, -999, -999, -999, -999, -999,
  115790. -999, -999, -999, -999, -999, -999, -999, -999}},
  115791. /* 4000 Hz */
  115792. {{-999, -999, -999, -999, -999, -999, -999, -999,
  115793. -999, -999, -999, -999, -999, -110, -91, -76,
  115794. -75, -85, -93, -98, -104, -110, -999, -999,
  115795. -999, -999, -999, -999, -999, -999, -999, -999,
  115796. -999, -999, -999, -999, -999, -999, -999, -999,
  115797. -999, -999, -999, -999, -999, -999, -999, -999,
  115798. -999, -999, -999, -999, -999, -999, -999, -999},
  115799. {-999, -999, -999, -999, -999, -999, -999, -999,
  115800. -999, -999, -999, -999, -999, -110, -91, -70,
  115801. -70, -75, -86, -89, -94, -98, -101, -106,
  115802. -110, -999, -999, -999, -999, -999, -999, -999,
  115803. -999, -999, -999, -999, -999, -999, -999, -999,
  115804. -999, -999, -999, -999, -999, -999, -999, -999,
  115805. -999, -999, -999, -999, -999, -999, -999, -999},
  115806. {-999, -999, -999, -999, -999, -999, -999, -999,
  115807. -999, -999, -999, -999, -110, -95, -80, -60,
  115808. -65, -64, -74, -83, -88, -91, -95, -99,
  115809. -103, -107, -110, -999, -999, -999, -999, -999,
  115810. -999, -999, -999, -999, -999, -999, -999, -999,
  115811. -999, -999, -999, -999, -999, -999, -999, -999,
  115812. -999, -999, -999, -999, -999, -999, -999, -999},
  115813. {-999, -999, -999, -999, -999, -999, -999, -999,
  115814. -999, -999, -999, -999, -110, -95, -80, -58,
  115815. -55, -49, -66, -68, -71, -78, -78, -80,
  115816. -88, -85, -89, -97, -100, -105, -110, -999,
  115817. -999, -999, -999, -999, -999, -999, -999, -999,
  115818. -999, -999, -999, -999, -999, -999, -999, -999,
  115819. -999, -999, -999, -999, -999, -999, -999, -999},
  115820. {-999, -999, -999, -999, -999, -999, -999, -999,
  115821. -999, -999, -999, -999, -110, -95, -80, -53,
  115822. -52, -41, -59, -59, -49, -58, -56, -63,
  115823. -86, -79, -90, -93, -98, -103, -107, -112,
  115824. -999, -999, -999, -999, -999, -999, -999, -999,
  115825. -999, -999, -999, -999, -999, -999, -999, -999,
  115826. -999, -999, -999, -999, -999, -999, -999, -999},
  115827. {-999, -999, -999, -999, -999, -999, -999, -999,
  115828. -999, -999, -999, -110, -97, -91, -73, -45,
  115829. -40, -33, -53, -61, -49, -54, -50, -50,
  115830. -60, -52, -67, -74, -81, -92, -96, -100,
  115831. -105, -110, -999, -999, -999, -999, -999, -999,
  115832. -999, -999, -999, -999, -999, -999, -999, -999,
  115833. -999, -999, -999, -999, -999, -999, -999, -999}},
  115834. /* 5657 Hz */
  115835. {{-999, -999, -999, -999, -999, -999, -999, -999,
  115836. -999, -999, -999, -113, -106, -99, -92, -77,
  115837. -80, -88, -97, -106, -115, -999, -999, -999,
  115838. -999, -999, -999, -999, -999, -999, -999, -999,
  115839. -999, -999, -999, -999, -999, -999, -999, -999,
  115840. -999, -999, -999, -999, -999, -999, -999, -999,
  115841. -999, -999, -999, -999, -999, -999, -999, -999},
  115842. {-999, -999, -999, -999, -999, -999, -999, -999,
  115843. -999, -999, -116, -109, -102, -95, -89, -74,
  115844. -72, -88, -87, -95, -102, -109, -116, -999,
  115845. -999, -999, -999, -999, -999, -999, -999, -999,
  115846. -999, -999, -999, -999, -999, -999, -999, -999,
  115847. -999, -999, -999, -999, -999, -999, -999, -999,
  115848. -999, -999, -999, -999, -999, -999, -999, -999},
  115849. {-999, -999, -999, -999, -999, -999, -999, -999,
  115850. -999, -999, -116, -109, -102, -95, -89, -75,
  115851. -66, -74, -77, -78, -86, -87, -90, -96,
  115852. -105, -115, -999, -999, -999, -999, -999, -999,
  115853. -999, -999, -999, -999, -999, -999, -999, -999,
  115854. -999, -999, -999, -999, -999, -999, -999, -999,
  115855. -999, -999, -999, -999, -999, -999, -999, -999},
  115856. {-999, -999, -999, -999, -999, -999, -999, -999,
  115857. -999, -999, -115, -108, -101, -94, -88, -66,
  115858. -56, -61, -70, -65, -78, -72, -83, -84,
  115859. -93, -98, -105, -110, -999, -999, -999, -999,
  115860. -999, -999, -999, -999, -999, -999, -999, -999,
  115861. -999, -999, -999, -999, -999, -999, -999, -999,
  115862. -999, -999, -999, -999, -999, -999, -999, -999},
  115863. {-999, -999, -999, -999, -999, -999, -999, -999,
  115864. -999, -999, -110, -105, -95, -89, -82, -57,
  115865. -52, -52, -59, -56, -59, -58, -69, -67,
  115866. -88, -82, -82, -89, -94, -100, -108, -999,
  115867. -999, -999, -999, -999, -999, -999, -999, -999,
  115868. -999, -999, -999, -999, -999, -999, -999, -999,
  115869. -999, -999, -999, -999, -999, -999, -999, -999},
  115870. {-999, -999, -999, -999, -999, -999, -999, -999,
  115871. -999, -110, -101, -96, -90, -83, -77, -54,
  115872. -43, -38, -50, -48, -52, -48, -42, -42,
  115873. -51, -52, -53, -59, -65, -71, -78, -85,
  115874. -95, -999, -999, -999, -999, -999, -999, -999,
  115875. -999, -999, -999, -999, -999, -999, -999, -999,
  115876. -999, -999, -999, -999, -999, -999, -999, -999}},
  115877. /* 8000 Hz */
  115878. {{-999, -999, -999, -999, -999, -999, -999, -999,
  115879. -999, -999, -999, -999, -120, -105, -86, -68,
  115880. -78, -79, -90, -100, -110, -999, -999, -999,
  115881. -999, -999, -999, -999, -999, -999, -999, -999,
  115882. -999, -999, -999, -999, -999, -999, -999, -999,
  115883. -999, -999, -999, -999, -999, -999, -999, -999,
  115884. -999, -999, -999, -999, -999, -999, -999, -999},
  115885. {-999, -999, -999, -999, -999, -999, -999, -999,
  115886. -999, -999, -999, -999, -120, -105, -86, -66,
  115887. -73, -77, -88, -96, -105, -115, -999, -999,
  115888. -999, -999, -999, -999, -999, -999, -999, -999,
  115889. -999, -999, -999, -999, -999, -999, -999, -999,
  115890. -999, -999, -999, -999, -999, -999, -999, -999,
  115891. -999, -999, -999, -999, -999, -999, -999, -999},
  115892. {-999, -999, -999, -999, -999, -999, -999, -999,
  115893. -999, -999, -999, -120, -105, -92, -80, -61,
  115894. -64, -68, -80, -87, -92, -100, -110, -999,
  115895. -999, -999, -999, -999, -999, -999, -999, -999,
  115896. -999, -999, -999, -999, -999, -999, -999, -999,
  115897. -999, -999, -999, -999, -999, -999, -999, -999,
  115898. -999, -999, -999, -999, -999, -999, -999, -999},
  115899. {-999, -999, -999, -999, -999, -999, -999, -999,
  115900. -999, -999, -999, -120, -104, -91, -79, -52,
  115901. -60, -54, -64, -69, -77, -80, -82, -84,
  115902. -85, -87, -88, -90, -999, -999, -999, -999,
  115903. -999, -999, -999, -999, -999, -999, -999, -999,
  115904. -999, -999, -999, -999, -999, -999, -999, -999,
  115905. -999, -999, -999, -999, -999, -999, -999, -999},
  115906. {-999, -999, -999, -999, -999, -999, -999, -999,
  115907. -999, -999, -999, -118, -100, -87, -77, -49,
  115908. -50, -44, -58, -61, -61, -67, -65, -62,
  115909. -62, -62, -65, -68, -999, -999, -999, -999,
  115910. -999, -999, -999, -999, -999, -999, -999, -999,
  115911. -999, -999, -999, -999, -999, -999, -999, -999,
  115912. -999, -999, -999, -999, -999, -999, -999, -999},
  115913. {-999, -999, -999, -999, -999, -999, -999, -999,
  115914. -999, -999, -999, -115, -98, -84, -62, -49,
  115915. -44, -38, -46, -49, -49, -46, -39, -37,
  115916. -39, -40, -42, -43, -999, -999, -999, -999,
  115917. -999, -999, -999, -999, -999, -999, -999, -999,
  115918. -999, -999, -999, -999, -999, -999, -999, -999,
  115919. -999, -999, -999, -999, -999, -999, -999, -999}},
  115920. /* 11314 Hz */
  115921. {{-999, -999, -999, -999, -999, -999, -999, -999,
  115922. -999, -999, -999, -999, -999, -110, -88, -74,
  115923. -77, -82, -82, -85, -90, -94, -99, -104,
  115924. -999, -999, -999, -999, -999, -999, -999, -999,
  115925. -999, -999, -999, -999, -999, -999, -999, -999,
  115926. -999, -999, -999, -999, -999, -999, -999, -999,
  115927. -999, -999, -999, -999, -999, -999, -999, -999},
  115928. {-999, -999, -999, -999, -999, -999, -999, -999,
  115929. -999, -999, -999, -999, -999, -110, -88, -66,
  115930. -70, -81, -80, -81, -84, -88, -91, -93,
  115931. -999, -999, -999, -999, -999, -999, -999, -999,
  115932. -999, -999, -999, -999, -999, -999, -999, -999,
  115933. -999, -999, -999, -999, -999, -999, -999, -999,
  115934. -999, -999, -999, -999, -999, -999, -999, -999},
  115935. {-999, -999, -999, -999, -999, -999, -999, -999,
  115936. -999, -999, -999, -999, -999, -110, -88, -61,
  115937. -63, -70, -71, -74, -77, -80, -83, -85,
  115938. -999, -999, -999, -999, -999, -999, -999, -999,
  115939. -999, -999, -999, -999, -999, -999, -999, -999,
  115940. -999, -999, -999, -999, -999, -999, -999, -999,
  115941. -999, -999, -999, -999, -999, -999, -999, -999},
  115942. {-999, -999, -999, -999, -999, -999, -999, -999,
  115943. -999, -999, -999, -999, -999, -110, -86, -62,
  115944. -63, -62, -62, -58, -52, -50, -50, -52,
  115945. -54, -999, -999, -999, -999, -999, -999, -999,
  115946. -999, -999, -999, -999, -999, -999, -999, -999,
  115947. -999, -999, -999, -999, -999, -999, -999, -999,
  115948. -999, -999, -999, -999, -999, -999, -999, -999},
  115949. {-999, -999, -999, -999, -999, -999, -999, -999,
  115950. -999, -999, -999, -999, -118, -108, -84, -53,
  115951. -50, -50, -50, -55, -47, -45, -40, -40,
  115952. -40, -999, -999, -999, -999, -999, -999, -999,
  115953. -999, -999, -999, -999, -999, -999, -999, -999,
  115954. -999, -999, -999, -999, -999, -999, -999, -999,
  115955. -999, -999, -999, -999, -999, -999, -999, -999},
  115956. {-999, -999, -999, -999, -999, -999, -999, -999,
  115957. -999, -999, -999, -999, -118, -100, -73, -43,
  115958. -37, -42, -43, -53, -38, -37, -35, -35,
  115959. -38, -999, -999, -999, -999, -999, -999, -999,
  115960. -999, -999, -999, -999, -999, -999, -999, -999,
  115961. -999, -999, -999, -999, -999, -999, -999, -999,
  115962. -999, -999, -999, -999, -999, -999, -999, -999}},
  115963. /* 16000 Hz */
  115964. {{-999, -999, -999, -999, -999, -999, -999, -999,
  115965. -999, -999, -999, -110, -100, -91, -84, -74,
  115966. -80, -80, -80, -80, -80, -999, -999, -999,
  115967. -999, -999, -999, -999, -999, -999, -999, -999,
  115968. -999, -999, -999, -999, -999, -999, -999, -999,
  115969. -999, -999, -999, -999, -999, -999, -999, -999,
  115970. -999, -999, -999, -999, -999, -999, -999, -999},
  115971. {-999, -999, -999, -999, -999, -999, -999, -999,
  115972. -999, -999, -999, -110, -100, -91, -84, -74,
  115973. -68, -68, -68, -68, -68, -999, -999, -999,
  115974. -999, -999, -999, -999, -999, -999, -999, -999,
  115975. -999, -999, -999, -999, -999, -999, -999, -999,
  115976. -999, -999, -999, -999, -999, -999, -999, -999,
  115977. -999, -999, -999, -999, -999, -999, -999, -999},
  115978. {-999, -999, -999, -999, -999, -999, -999, -999,
  115979. -999, -999, -999, -110, -100, -86, -78, -70,
  115980. -60, -45, -30, -21, -999, -999, -999, -999,
  115981. -999, -999, -999, -999, -999, -999, -999, -999,
  115982. -999, -999, -999, -999, -999, -999, -999, -999,
  115983. -999, -999, -999, -999, -999, -999, -999, -999,
  115984. -999, -999, -999, -999, -999, -999, -999, -999},
  115985. {-999, -999, -999, -999, -999, -999, -999, -999,
  115986. -999, -999, -999, -110, -100, -87, -78, -67,
  115987. -48, -38, -29, -21, -999, -999, -999, -999,
  115988. -999, -999, -999, -999, -999, -999, -999, -999,
  115989. -999, -999, -999, -999, -999, -999, -999, -999,
  115990. -999, -999, -999, -999, -999, -999, -999, -999,
  115991. -999, -999, -999, -999, -999, -999, -999, -999},
  115992. {-999, -999, -999, -999, -999, -999, -999, -999,
  115993. -999, -999, -999, -110, -100, -86, -69, -56,
  115994. -45, -35, -33, -29, -999, -999, -999, -999,
  115995. -999, -999, -999, -999, -999, -999, -999, -999,
  115996. -999, -999, -999, -999, -999, -999, -999, -999,
  115997. -999, -999, -999, -999, -999, -999, -999, -999,
  115998. -999, -999, -999, -999, -999, -999, -999, -999},
  115999. {-999, -999, -999, -999, -999, -999, -999, -999,
  116000. -999, -999, -999, -110, -100, -83, -71, -48,
  116001. -27, -38, -37, -34, -999, -999, -999, -999,
  116002. -999, -999, -999, -999, -999, -999, -999, -999,
  116003. -999, -999, -999, -999, -999, -999, -999, -999,
  116004. -999, -999, -999, -999, -999, -999, -999, -999,
  116005. -999, -999, -999, -999, -999, -999, -999, -999}}
  116006. };
  116007. #endif
  116008. /*** End of inlined file: masking.h ***/
  116009. #define NEGINF -9999.f
  116010. static double stereo_threshholds[]={0.0, .5, 1.0, 1.5, 2.5, 4.5, 8.5, 16.5, 9e10};
  116011. static double stereo_threshholds_limited[]={0.0, .5, 1.0, 1.5, 2.0, 2.5, 4.5, 8.5, 9e10};
  116012. vorbis_look_psy_global *_vp_global_look(vorbis_info *vi){
  116013. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  116014. vorbis_info_psy_global *gi=&ci->psy_g_param;
  116015. vorbis_look_psy_global *look=(vorbis_look_psy_global*)_ogg_calloc(1,sizeof(*look));
  116016. look->channels=vi->channels;
  116017. look->ampmax=-9999.;
  116018. look->gi=gi;
  116019. return(look);
  116020. }
  116021. void _vp_global_free(vorbis_look_psy_global *look){
  116022. if(look){
  116023. memset(look,0,sizeof(*look));
  116024. _ogg_free(look);
  116025. }
  116026. }
  116027. void _vi_gpsy_free(vorbis_info_psy_global *i){
  116028. if(i){
  116029. memset(i,0,sizeof(*i));
  116030. _ogg_free(i);
  116031. }
  116032. }
  116033. void _vi_psy_free(vorbis_info_psy *i){
  116034. if(i){
  116035. memset(i,0,sizeof(*i));
  116036. _ogg_free(i);
  116037. }
  116038. }
  116039. static void min_curve(float *c,
  116040. float *c2){
  116041. int i;
  116042. for(i=0;i<EHMER_MAX;i++)if(c2[i]<c[i])c[i]=c2[i];
  116043. }
  116044. static void max_curve(float *c,
  116045. float *c2){
  116046. int i;
  116047. for(i=0;i<EHMER_MAX;i++)if(c2[i]>c[i])c[i]=c2[i];
  116048. }
  116049. static void attenuate_curve(float *c,float att){
  116050. int i;
  116051. for(i=0;i<EHMER_MAX;i++)
  116052. c[i]+=att;
  116053. }
  116054. static float ***setup_tone_curves(float curveatt_dB[P_BANDS],float binHz,int n,
  116055. float center_boost, float center_decay_rate){
  116056. int i,j,k,m;
  116057. float ath[EHMER_MAX];
  116058. float workc[P_BANDS][P_LEVELS][EHMER_MAX];
  116059. float athc[P_LEVELS][EHMER_MAX];
  116060. float *brute_buffer=(float*) alloca(n*sizeof(*brute_buffer));
  116061. float ***ret=(float***) _ogg_malloc(sizeof(*ret)*P_BANDS);
  116062. memset(workc,0,sizeof(workc));
  116063. for(i=0;i<P_BANDS;i++){
  116064. /* we add back in the ATH to avoid low level curves falling off to
  116065. -infinity and unnecessarily cutting off high level curves in the
  116066. curve limiting (last step). */
  116067. /* A half-band's settings must be valid over the whole band, and
  116068. it's better to mask too little than too much */
  116069. int ath_offset=i*4;
  116070. for(j=0;j<EHMER_MAX;j++){
  116071. float min=999.;
  116072. for(k=0;k<4;k++)
  116073. if(j+k+ath_offset<MAX_ATH){
  116074. if(min>ATH[j+k+ath_offset])min=ATH[j+k+ath_offset];
  116075. }else{
  116076. if(min>ATH[MAX_ATH-1])min=ATH[MAX_ATH-1];
  116077. }
  116078. ath[j]=min;
  116079. }
  116080. /* copy curves into working space, replicate the 50dB curve to 30
  116081. and 40, replicate the 100dB curve to 110 */
  116082. for(j=0;j<6;j++)
  116083. memcpy(workc[i][j+2],tonemasks[i][j],EHMER_MAX*sizeof(*tonemasks[i][j]));
  116084. memcpy(workc[i][0],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  116085. memcpy(workc[i][1],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  116086. /* apply centered curve boost/decay */
  116087. for(j=0;j<P_LEVELS;j++){
  116088. for(k=0;k<EHMER_MAX;k++){
  116089. float adj=center_boost+abs(EHMER_OFFSET-k)*center_decay_rate;
  116090. if(adj<0. && center_boost>0)adj=0.;
  116091. if(adj>0. && center_boost<0)adj=0.;
  116092. workc[i][j][k]+=adj;
  116093. }
  116094. }
  116095. /* normalize curves so the driving amplitude is 0dB */
  116096. /* make temp curves with the ATH overlayed */
  116097. for(j=0;j<P_LEVELS;j++){
  116098. attenuate_curve(workc[i][j],curveatt_dB[i]+100.-(j<2?2:j)*10.-P_LEVEL_0);
  116099. memcpy(athc[j],ath,EHMER_MAX*sizeof(**athc));
  116100. attenuate_curve(athc[j],+100.-j*10.f-P_LEVEL_0);
  116101. max_curve(athc[j],workc[i][j]);
  116102. }
  116103. /* Now limit the louder curves.
  116104. the idea is this: We don't know what the playback attenuation
  116105. will be; 0dB SL moves every time the user twiddles the volume
  116106. knob. So that means we have to use a single 'most pessimal' curve
  116107. for all masking amplitudes, right? Wrong. The *loudest* sound
  116108. can be in (we assume) a range of ...+100dB] SL. However, sounds
  116109. 20dB down will be in a range ...+80], 40dB down is from ...+60],
  116110. etc... */
  116111. for(j=1;j<P_LEVELS;j++){
  116112. min_curve(athc[j],athc[j-1]);
  116113. min_curve(workc[i][j],athc[j]);
  116114. }
  116115. }
  116116. for(i=0;i<P_BANDS;i++){
  116117. int hi_curve,lo_curve,bin;
  116118. ret[i]=(float**)_ogg_malloc(sizeof(**ret)*P_LEVELS);
  116119. /* low frequency curves are measured with greater resolution than
  116120. the MDCT/FFT will actually give us; we want the curve applied
  116121. to the tone data to be pessimistic and thus apply the minimum
  116122. masking possible for a given bin. That means that a single bin
  116123. could span more than one octave and that the curve will be a
  116124. composite of multiple octaves. It also may mean that a single
  116125. bin may span > an eighth of an octave and that the eighth
  116126. octave values may also be composited. */
  116127. /* which octave curves will we be compositing? */
  116128. bin=floor(fromOC(i*.5)/binHz);
  116129. lo_curve= ceil(toOC(bin*binHz+1)*2);
  116130. hi_curve= floor(toOC((bin+1)*binHz)*2);
  116131. if(lo_curve>i)lo_curve=i;
  116132. if(lo_curve<0)lo_curve=0;
  116133. if(hi_curve>=P_BANDS)hi_curve=P_BANDS-1;
  116134. for(m=0;m<P_LEVELS;m++){
  116135. ret[i][m]=(float*)_ogg_malloc(sizeof(***ret)*(EHMER_MAX+2));
  116136. for(j=0;j<n;j++)brute_buffer[j]=999.;
  116137. /* render the curve into bins, then pull values back into curve.
  116138. The point is that any inherent subsampling aliasing results in
  116139. a safe minimum */
  116140. for(k=lo_curve;k<=hi_curve;k++){
  116141. int l=0;
  116142. for(j=0;j<EHMER_MAX;j++){
  116143. int lo_bin= fromOC(j*.125+k*.5-2.0625)/binHz;
  116144. int hi_bin= fromOC(j*.125+k*.5-1.9375)/binHz+1;
  116145. if(lo_bin<0)lo_bin=0;
  116146. if(lo_bin>n)lo_bin=n;
  116147. if(lo_bin<l)l=lo_bin;
  116148. if(hi_bin<0)hi_bin=0;
  116149. if(hi_bin>n)hi_bin=n;
  116150. for(;l<hi_bin && l<n;l++)
  116151. if(brute_buffer[l]>workc[k][m][j])
  116152. brute_buffer[l]=workc[k][m][j];
  116153. }
  116154. for(;l<n;l++)
  116155. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  116156. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  116157. }
  116158. /* be equally paranoid about being valid up to next half ocatve */
  116159. if(i+1<P_BANDS){
  116160. int l=0;
  116161. k=i+1;
  116162. for(j=0;j<EHMER_MAX;j++){
  116163. int lo_bin= fromOC(j*.125+i*.5-2.0625)/binHz;
  116164. int hi_bin= fromOC(j*.125+i*.5-1.9375)/binHz+1;
  116165. if(lo_bin<0)lo_bin=0;
  116166. if(lo_bin>n)lo_bin=n;
  116167. if(lo_bin<l)l=lo_bin;
  116168. if(hi_bin<0)hi_bin=0;
  116169. if(hi_bin>n)hi_bin=n;
  116170. for(;l<hi_bin && l<n;l++)
  116171. if(brute_buffer[l]>workc[k][m][j])
  116172. brute_buffer[l]=workc[k][m][j];
  116173. }
  116174. for(;l<n;l++)
  116175. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  116176. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  116177. }
  116178. for(j=0;j<EHMER_MAX;j++){
  116179. int bin=fromOC(j*.125+i*.5-2.)/binHz;
  116180. if(bin<0){
  116181. ret[i][m][j+2]=-999.;
  116182. }else{
  116183. if(bin>=n){
  116184. ret[i][m][j+2]=-999.;
  116185. }else{
  116186. ret[i][m][j+2]=brute_buffer[bin];
  116187. }
  116188. }
  116189. }
  116190. /* add fenceposts */
  116191. for(j=0;j<EHMER_OFFSET;j++)
  116192. if(ret[i][m][j+2]>-200.f)break;
  116193. ret[i][m][0]=j;
  116194. for(j=EHMER_MAX-1;j>EHMER_OFFSET+1;j--)
  116195. if(ret[i][m][j+2]>-200.f)
  116196. break;
  116197. ret[i][m][1]=j;
  116198. }
  116199. }
  116200. return(ret);
  116201. }
  116202. void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  116203. vorbis_info_psy_global *gi,int n,long rate){
  116204. long i,j,lo=-99,hi=1;
  116205. long maxoc;
  116206. memset(p,0,sizeof(*p));
  116207. p->eighth_octave_lines=gi->eighth_octave_lines;
  116208. p->shiftoc=rint(log(gi->eighth_octave_lines*8.f)/log(2.f))-1;
  116209. p->firstoc=toOC(.25f*rate*.5/n)*(1<<(p->shiftoc+1))-gi->eighth_octave_lines;
  116210. maxoc=toOC((n+.25f)*rate*.5/n)*(1<<(p->shiftoc+1))+.5f;
  116211. p->total_octave_lines=maxoc-p->firstoc+1;
  116212. p->ath=(float*)_ogg_malloc(n*sizeof(*p->ath));
  116213. p->octave=(long*)_ogg_malloc(n*sizeof(*p->octave));
  116214. p->bark=(long*)_ogg_malloc(n*sizeof(*p->bark));
  116215. p->vi=vi;
  116216. p->n=n;
  116217. p->rate=rate;
  116218. /* AoTuV HF weighting */
  116219. p->m_val = 1.;
  116220. if(rate < 26000) p->m_val = 0;
  116221. else if(rate < 38000) p->m_val = .94; /* 32kHz */
  116222. else if(rate > 46000) p->m_val = 1.275; /* 48kHz */
  116223. /* set up the lookups for a given blocksize and sample rate */
  116224. for(i=0,j=0;i<MAX_ATH-1;i++){
  116225. int endpos=rint(fromOC((i+1)*.125-2.)*2*n/rate);
  116226. float base=ATH[i];
  116227. if(j<endpos){
  116228. float delta=(ATH[i+1]-base)/(endpos-j);
  116229. for(;j<endpos && j<n;j++){
  116230. p->ath[j]=base+100.;
  116231. base+=delta;
  116232. }
  116233. }
  116234. }
  116235. for(i=0;i<n;i++){
  116236. float bark=toBARK(rate/(2*n)*i);
  116237. for(;lo+vi->noisewindowlomin<i &&
  116238. toBARK(rate/(2*n)*lo)<(bark-vi->noisewindowlo);lo++);
  116239. for(;hi<=n && (hi<i+vi->noisewindowhimin ||
  116240. toBARK(rate/(2*n)*hi)<(bark+vi->noisewindowhi));hi++);
  116241. p->bark[i]=((lo-1)<<16)+(hi-1);
  116242. }
  116243. for(i=0;i<n;i++)
  116244. p->octave[i]=toOC((i+.25f)*.5*rate/n)*(1<<(p->shiftoc+1))+.5f;
  116245. p->tonecurves=setup_tone_curves(vi->toneatt,rate*.5/n,n,
  116246. vi->tone_centerboost,vi->tone_decay);
  116247. /* set up rolling noise median */
  116248. p->noiseoffset=(float**)_ogg_malloc(P_NOISECURVES*sizeof(*p->noiseoffset));
  116249. for(i=0;i<P_NOISECURVES;i++)
  116250. p->noiseoffset[i]=(float*)_ogg_malloc(n*sizeof(**p->noiseoffset));
  116251. for(i=0;i<n;i++){
  116252. float halfoc=toOC((i+.5)*rate/(2.*n))*2.;
  116253. int inthalfoc;
  116254. float del;
  116255. if(halfoc<0)halfoc=0;
  116256. if(halfoc>=P_BANDS-1)halfoc=P_BANDS-1;
  116257. inthalfoc=(int)halfoc;
  116258. del=halfoc-inthalfoc;
  116259. for(j=0;j<P_NOISECURVES;j++)
  116260. p->noiseoffset[j][i]=
  116261. p->vi->noiseoff[j][inthalfoc]*(1.-del) +
  116262. p->vi->noiseoff[j][inthalfoc+1]*del;
  116263. }
  116264. #if 0
  116265. {
  116266. static int ls=0;
  116267. _analysis_output_always("noiseoff0",ls,p->noiseoffset[0],n,1,0,0);
  116268. _analysis_output_always("noiseoff1",ls,p->noiseoffset[1],n,1,0,0);
  116269. _analysis_output_always("noiseoff2",ls++,p->noiseoffset[2],n,1,0,0);
  116270. }
  116271. #endif
  116272. }
  116273. void _vp_psy_clear(vorbis_look_psy *p){
  116274. int i,j;
  116275. if(p){
  116276. if(p->ath)_ogg_free(p->ath);
  116277. if(p->octave)_ogg_free(p->octave);
  116278. if(p->bark)_ogg_free(p->bark);
  116279. if(p->tonecurves){
  116280. for(i=0;i<P_BANDS;i++){
  116281. for(j=0;j<P_LEVELS;j++){
  116282. _ogg_free(p->tonecurves[i][j]);
  116283. }
  116284. _ogg_free(p->tonecurves[i]);
  116285. }
  116286. _ogg_free(p->tonecurves);
  116287. }
  116288. if(p->noiseoffset){
  116289. for(i=0;i<P_NOISECURVES;i++){
  116290. _ogg_free(p->noiseoffset[i]);
  116291. }
  116292. _ogg_free(p->noiseoffset);
  116293. }
  116294. memset(p,0,sizeof(*p));
  116295. }
  116296. }
  116297. /* octave/(8*eighth_octave_lines) x scale and dB y scale */
  116298. static void seed_curve(float *seed,
  116299. const float **curves,
  116300. float amp,
  116301. int oc, int n,
  116302. int linesper,float dBoffset){
  116303. int i,post1;
  116304. int seedptr;
  116305. const float *posts,*curve;
  116306. int choice=(int)((amp+dBoffset-P_LEVEL_0)*.1f);
  116307. choice=max(choice,0);
  116308. choice=min(choice,P_LEVELS-1);
  116309. posts=curves[choice];
  116310. curve=posts+2;
  116311. post1=(int)posts[1];
  116312. seedptr=oc+(posts[0]-EHMER_OFFSET)*linesper-(linesper>>1);
  116313. for(i=posts[0];i<post1;i++){
  116314. if(seedptr>0){
  116315. float lin=amp+curve[i];
  116316. if(seed[seedptr]<lin)seed[seedptr]=lin;
  116317. }
  116318. seedptr+=linesper;
  116319. if(seedptr>=n)break;
  116320. }
  116321. }
  116322. static void seed_loop(vorbis_look_psy *p,
  116323. const float ***curves,
  116324. const float *f,
  116325. const float *flr,
  116326. float *seed,
  116327. float specmax){
  116328. vorbis_info_psy *vi=p->vi;
  116329. long n=p->n,i;
  116330. float dBoffset=vi->max_curve_dB-specmax;
  116331. /* prime the working vector with peak values */
  116332. for(i=0;i<n;i++){
  116333. float max=f[i];
  116334. long oc=p->octave[i];
  116335. while(i+1<n && p->octave[i+1]==oc){
  116336. i++;
  116337. if(f[i]>max)max=f[i];
  116338. }
  116339. if(max+6.f>flr[i]){
  116340. oc=oc>>p->shiftoc;
  116341. if(oc>=P_BANDS)oc=P_BANDS-1;
  116342. if(oc<0)oc=0;
  116343. seed_curve(seed,
  116344. curves[oc],
  116345. max,
  116346. p->octave[i]-p->firstoc,
  116347. p->total_octave_lines,
  116348. p->eighth_octave_lines,
  116349. dBoffset);
  116350. }
  116351. }
  116352. }
  116353. static void seed_chase(float *seeds, int linesper, long n){
  116354. long *posstack=(long*)alloca(n*sizeof(*posstack));
  116355. float *ampstack=(float*)alloca(n*sizeof(*ampstack));
  116356. long stack=0;
  116357. long pos=0;
  116358. long i;
  116359. for(i=0;i<n;i++){
  116360. if(stack<2){
  116361. posstack[stack]=i;
  116362. ampstack[stack++]=seeds[i];
  116363. }else{
  116364. while(1){
  116365. if(seeds[i]<ampstack[stack-1]){
  116366. posstack[stack]=i;
  116367. ampstack[stack++]=seeds[i];
  116368. break;
  116369. }else{
  116370. if(i<posstack[stack-1]+linesper){
  116371. if(stack>1 && ampstack[stack-1]<=ampstack[stack-2] &&
  116372. i<posstack[stack-2]+linesper){
  116373. /* we completely overlap, making stack-1 irrelevant. pop it */
  116374. stack--;
  116375. continue;
  116376. }
  116377. }
  116378. posstack[stack]=i;
  116379. ampstack[stack++]=seeds[i];
  116380. break;
  116381. }
  116382. }
  116383. }
  116384. }
  116385. /* the stack now contains only the positions that are relevant. Scan
  116386. 'em straight through */
  116387. for(i=0;i<stack;i++){
  116388. long endpos;
  116389. if(i<stack-1 && ampstack[i+1]>ampstack[i]){
  116390. endpos=posstack[i+1];
  116391. }else{
  116392. endpos=posstack[i]+linesper+1; /* +1 is important, else bin 0 is
  116393. discarded in short frames */
  116394. }
  116395. if(endpos>n)endpos=n;
  116396. for(;pos<endpos;pos++)
  116397. seeds[pos]=ampstack[i];
  116398. }
  116399. /* there. Linear time. I now remember this was on a problem set I
  116400. had in Grad Skool... I didn't solve it at the time ;-) */
  116401. }
  116402. /* bleaugh, this is more complicated than it needs to be */
  116403. #include<stdio.h>
  116404. static void max_seeds(vorbis_look_psy *p,
  116405. float *seed,
  116406. float *flr){
  116407. long n=p->total_octave_lines;
  116408. int linesper=p->eighth_octave_lines;
  116409. long linpos=0;
  116410. long pos;
  116411. seed_chase(seed,linesper,n); /* for masking */
  116412. pos=p->octave[0]-p->firstoc-(linesper>>1);
  116413. while(linpos+1<p->n){
  116414. float minV=seed[pos];
  116415. long end=((p->octave[linpos]+p->octave[linpos+1])>>1)-p->firstoc;
  116416. if(minV>p->vi->tone_abs_limit)minV=p->vi->tone_abs_limit;
  116417. while(pos+1<=end){
  116418. pos++;
  116419. if((seed[pos]>NEGINF && seed[pos]<minV) || minV==NEGINF)
  116420. minV=seed[pos];
  116421. }
  116422. end=pos+p->firstoc;
  116423. for(;linpos<p->n && p->octave[linpos]<=end;linpos++)
  116424. if(flr[linpos]<minV)flr[linpos]=minV;
  116425. }
  116426. {
  116427. float minV=seed[p->total_octave_lines-1];
  116428. for(;linpos<p->n;linpos++)
  116429. if(flr[linpos]<minV)flr[linpos]=minV;
  116430. }
  116431. }
  116432. static void bark_noise_hybridmp(int n,const long *b,
  116433. const float *f,
  116434. float *noise,
  116435. const float offset,
  116436. const int fixed){
  116437. float *N=(float*) alloca(n*sizeof(*N));
  116438. float *X=(float*) alloca(n*sizeof(*N));
  116439. float *XX=(float*) alloca(n*sizeof(*N));
  116440. float *Y=(float*) alloca(n*sizeof(*N));
  116441. float *XY=(float*) alloca(n*sizeof(*N));
  116442. float tN, tX, tXX, tY, tXY;
  116443. int i;
  116444. int lo, hi;
  116445. float R, A, B, D;
  116446. float w, x, y;
  116447. tN = tX = tXX = tY = tXY = 0.f;
  116448. y = f[0] + offset;
  116449. if (y < 1.f) y = 1.f;
  116450. w = y * y * .5;
  116451. tN += w;
  116452. tX += w;
  116453. tY += w * y;
  116454. N[0] = tN;
  116455. X[0] = tX;
  116456. XX[0] = tXX;
  116457. Y[0] = tY;
  116458. XY[0] = tXY;
  116459. for (i = 1, x = 1.f; i < n; i++, x += 1.f) {
  116460. y = f[i] + offset;
  116461. if (y < 1.f) y = 1.f;
  116462. w = y * y;
  116463. tN += w;
  116464. tX += w * x;
  116465. tXX += w * x * x;
  116466. tY += w * y;
  116467. tXY += w * x * y;
  116468. N[i] = tN;
  116469. X[i] = tX;
  116470. XX[i] = tXX;
  116471. Y[i] = tY;
  116472. XY[i] = tXY;
  116473. }
  116474. for (i = 0, x = 0.f;; i++, x += 1.f) {
  116475. lo = b[i] >> 16;
  116476. if( lo>=0 ) break;
  116477. hi = b[i] & 0xffff;
  116478. tN = N[hi] + N[-lo];
  116479. tX = X[hi] - X[-lo];
  116480. tXX = XX[hi] + XX[-lo];
  116481. tY = Y[hi] + Y[-lo];
  116482. tXY = XY[hi] - XY[-lo];
  116483. A = tY * tXX - tX * tXY;
  116484. B = tN * tXY - tX * tY;
  116485. D = tN * tXX - tX * tX;
  116486. R = (A + x * B) / D;
  116487. if (R < 0.f)
  116488. R = 0.f;
  116489. noise[i] = R - offset;
  116490. }
  116491. for ( ;; i++, x += 1.f) {
  116492. lo = b[i] >> 16;
  116493. hi = b[i] & 0xffff;
  116494. if(hi>=n)break;
  116495. tN = N[hi] - N[lo];
  116496. tX = X[hi] - X[lo];
  116497. tXX = XX[hi] - XX[lo];
  116498. tY = Y[hi] - Y[lo];
  116499. tXY = XY[hi] - XY[lo];
  116500. A = tY * tXX - tX * tXY;
  116501. B = tN * tXY - tX * tY;
  116502. D = tN * tXX - tX * tX;
  116503. R = (A + x * B) / D;
  116504. if (R < 0.f) R = 0.f;
  116505. noise[i] = R - offset;
  116506. }
  116507. for ( ; i < n; i++, x += 1.f) {
  116508. R = (A + x * B) / D;
  116509. if (R < 0.f) R = 0.f;
  116510. noise[i] = R - offset;
  116511. }
  116512. if (fixed <= 0) return;
  116513. for (i = 0, x = 0.f;; i++, x += 1.f) {
  116514. hi = i + fixed / 2;
  116515. lo = hi - fixed;
  116516. if(lo>=0)break;
  116517. tN = N[hi] + N[-lo];
  116518. tX = X[hi] - X[-lo];
  116519. tXX = XX[hi] + XX[-lo];
  116520. tY = Y[hi] + Y[-lo];
  116521. tXY = XY[hi] - XY[-lo];
  116522. A = tY * tXX - tX * tXY;
  116523. B = tN * tXY - tX * tY;
  116524. D = tN * tXX - tX * tX;
  116525. R = (A + x * B) / D;
  116526. if (R - offset < noise[i]) noise[i] = R - offset;
  116527. }
  116528. for ( ;; i++, x += 1.f) {
  116529. hi = i + fixed / 2;
  116530. lo = hi - fixed;
  116531. if(hi>=n)break;
  116532. tN = N[hi] - N[lo];
  116533. tX = X[hi] - X[lo];
  116534. tXX = XX[hi] - XX[lo];
  116535. tY = Y[hi] - Y[lo];
  116536. tXY = XY[hi] - XY[lo];
  116537. A = tY * tXX - tX * tXY;
  116538. B = tN * tXY - tX * tY;
  116539. D = tN * tXX - tX * tX;
  116540. R = (A + x * B) / D;
  116541. if (R - offset < noise[i]) noise[i] = R - offset;
  116542. }
  116543. for ( ; i < n; i++, x += 1.f) {
  116544. R = (A + x * B) / D;
  116545. if (R - offset < noise[i]) noise[i] = R - offset;
  116546. }
  116547. }
  116548. static float FLOOR1_fromdB_INV_LOOKUP[256]={
  116549. 0.F, 8.81683e+06F, 8.27882e+06F, 7.77365e+06F,
  116550. 7.29930e+06F, 6.85389e+06F, 6.43567e+06F, 6.04296e+06F,
  116551. 5.67422e+06F, 5.32798e+06F, 5.00286e+06F, 4.69759e+06F,
  116552. 4.41094e+06F, 4.14178e+06F, 3.88905e+06F, 3.65174e+06F,
  116553. 3.42891e+06F, 3.21968e+06F, 3.02321e+06F, 2.83873e+06F,
  116554. 2.66551e+06F, 2.50286e+06F, 2.35014e+06F, 2.20673e+06F,
  116555. 2.07208e+06F, 1.94564e+06F, 1.82692e+06F, 1.71544e+06F,
  116556. 1.61076e+06F, 1.51247e+06F, 1.42018e+06F, 1.33352e+06F,
  116557. 1.25215e+06F, 1.17574e+06F, 1.10400e+06F, 1.03663e+06F,
  116558. 973377.F, 913981.F, 858210.F, 805842.F,
  116559. 756669.F, 710497.F, 667142.F, 626433.F,
  116560. 588208.F, 552316.F, 518613.F, 486967.F,
  116561. 457252.F, 429351.F, 403152.F, 378551.F,
  116562. 355452.F, 333762.F, 313396.F, 294273.F,
  116563. 276316.F, 259455.F, 243623.F, 228757.F,
  116564. 214798.F, 201691.F, 189384.F, 177828.F,
  116565. 166977.F, 156788.F, 147221.F, 138237.F,
  116566. 129802.F, 121881.F, 114444.F, 107461.F,
  116567. 100903.F, 94746.3F, 88964.9F, 83536.2F,
  116568. 78438.8F, 73652.5F, 69158.2F, 64938.1F,
  116569. 60975.6F, 57254.9F, 53761.2F, 50480.6F,
  116570. 47400.3F, 44507.9F, 41792.0F, 39241.9F,
  116571. 36847.3F, 34598.9F, 32487.7F, 30505.3F,
  116572. 28643.8F, 26896.0F, 25254.8F, 23713.7F,
  116573. 22266.7F, 20908.0F, 19632.2F, 18434.2F,
  116574. 17309.4F, 16253.1F, 15261.4F, 14330.1F,
  116575. 13455.7F, 12634.6F, 11863.7F, 11139.7F,
  116576. 10460.0F, 9821.72F, 9222.39F, 8659.64F,
  116577. 8131.23F, 7635.06F, 7169.17F, 6731.70F,
  116578. 6320.93F, 5935.23F, 5573.06F, 5232.99F,
  116579. 4913.67F, 4613.84F, 4332.30F, 4067.94F,
  116580. 3819.72F, 3586.64F, 3367.78F, 3162.28F,
  116581. 2969.31F, 2788.13F, 2617.99F, 2458.24F,
  116582. 2308.24F, 2167.39F, 2035.14F, 1910.95F,
  116583. 1794.35F, 1684.85F, 1582.04F, 1485.51F,
  116584. 1394.86F, 1309.75F, 1229.83F, 1154.78F,
  116585. 1084.32F, 1018.15F, 956.024F, 897.687F,
  116586. 842.910F, 791.475F, 743.179F, 697.830F,
  116587. 655.249F, 615.265F, 577.722F, 542.469F,
  116588. 509.367F, 478.286F, 449.101F, 421.696F,
  116589. 395.964F, 371.803F, 349.115F, 327.812F,
  116590. 307.809F, 289.026F, 271.390F, 254.830F,
  116591. 239.280F, 224.679F, 210.969F, 198.096F,
  116592. 186.008F, 174.658F, 164.000F, 153.993F,
  116593. 144.596F, 135.773F, 127.488F, 119.708F,
  116594. 112.404F, 105.545F, 99.1046F, 93.0572F,
  116595. 87.3788F, 82.0469F, 77.0404F, 72.3394F,
  116596. 67.9252F, 63.7804F, 59.8885F, 56.2341F,
  116597. 52.8027F, 49.5807F, 46.5553F, 43.7144F,
  116598. 41.0470F, 38.5423F, 36.1904F, 33.9821F,
  116599. 31.9085F, 29.9614F, 28.1332F, 26.4165F,
  116600. 24.8045F, 23.2910F, 21.8697F, 20.5352F,
  116601. 19.2822F, 18.1056F, 17.0008F, 15.9634F,
  116602. 14.9893F, 14.0746F, 13.2158F, 12.4094F,
  116603. 11.6522F, 10.9411F, 10.2735F, 9.64662F,
  116604. 9.05798F, 8.50526F, 7.98626F, 7.49894F,
  116605. 7.04135F, 6.61169F, 6.20824F, 5.82941F,
  116606. 5.47370F, 5.13970F, 4.82607F, 4.53158F,
  116607. 4.25507F, 3.99542F, 3.75162F, 3.52269F,
  116608. 3.30774F, 3.10590F, 2.91638F, 2.73842F,
  116609. 2.57132F, 2.41442F, 2.26709F, 2.12875F,
  116610. 1.99885F, 1.87688F, 1.76236F, 1.65482F,
  116611. 1.55384F, 1.45902F, 1.36999F, 1.28640F,
  116612. 1.20790F, 1.13419F, 1.06499F, 1.F
  116613. };
  116614. void _vp_remove_floor(vorbis_look_psy *p,
  116615. float *mdct,
  116616. int *codedflr,
  116617. float *residue,
  116618. int sliding_lowpass){
  116619. int i,n=p->n;
  116620. if(sliding_lowpass>n)sliding_lowpass=n;
  116621. for(i=0;i<sliding_lowpass;i++){
  116622. residue[i]=
  116623. mdct[i]*FLOOR1_fromdB_INV_LOOKUP[codedflr[i]];
  116624. }
  116625. for(;i<n;i++)
  116626. residue[i]=0.;
  116627. }
  116628. void _vp_noisemask(vorbis_look_psy *p,
  116629. float *logmdct,
  116630. float *logmask){
  116631. int i,n=p->n;
  116632. float *work=(float*) alloca(n*sizeof(*work));
  116633. bark_noise_hybridmp(n,p->bark,logmdct,logmask,
  116634. 140.,-1);
  116635. for(i=0;i<n;i++)work[i]=logmdct[i]-logmask[i];
  116636. bark_noise_hybridmp(n,p->bark,work,logmask,0.,
  116637. p->vi->noisewindowfixed);
  116638. for(i=0;i<n;i++)work[i]=logmdct[i]-work[i];
  116639. #if 0
  116640. {
  116641. static int seq=0;
  116642. float work2[n];
  116643. for(i=0;i<n;i++){
  116644. work2[i]=logmask[i]+work[i];
  116645. }
  116646. if(seq&1)
  116647. _analysis_output("median2R",seq/2,work,n,1,0,0);
  116648. else
  116649. _analysis_output("median2L",seq/2,work,n,1,0,0);
  116650. if(seq&1)
  116651. _analysis_output("envelope2R",seq/2,work2,n,1,0,0);
  116652. else
  116653. _analysis_output("envelope2L",seq/2,work2,n,1,0,0);
  116654. seq++;
  116655. }
  116656. #endif
  116657. for(i=0;i<n;i++){
  116658. int dB=logmask[i]+.5;
  116659. if(dB>=NOISE_COMPAND_LEVELS)dB=NOISE_COMPAND_LEVELS-1;
  116660. if(dB<0)dB=0;
  116661. logmask[i]= work[i]+p->vi->noisecompand[dB];
  116662. }
  116663. }
  116664. void _vp_tonemask(vorbis_look_psy *p,
  116665. float *logfft,
  116666. float *logmask,
  116667. float global_specmax,
  116668. float local_specmax){
  116669. int i,n=p->n;
  116670. float *seed=(float*) alloca(sizeof(*seed)*p->total_octave_lines);
  116671. float att=local_specmax+p->vi->ath_adjatt;
  116672. for(i=0;i<p->total_octave_lines;i++)seed[i]=NEGINF;
  116673. /* set the ATH (floating below localmax, not global max by a
  116674. specified att) */
  116675. if(att<p->vi->ath_maxatt)att=p->vi->ath_maxatt;
  116676. for(i=0;i<n;i++)
  116677. logmask[i]=p->ath[i]+att;
  116678. /* tone masking */
  116679. seed_loop(p,(const float ***)p->tonecurves,logfft,logmask,seed,global_specmax);
  116680. max_seeds(p,seed,logmask);
  116681. }
  116682. void _vp_offset_and_mix(vorbis_look_psy *p,
  116683. float *noise,
  116684. float *tone,
  116685. int offset_select,
  116686. float *logmask,
  116687. float *mdct,
  116688. float *logmdct){
  116689. int i,n=p->n;
  116690. float de, coeffi, cx;/* AoTuV */
  116691. float toneatt=p->vi->tone_masteratt[offset_select];
  116692. cx = p->m_val;
  116693. for(i=0;i<n;i++){
  116694. float val= noise[i]+p->noiseoffset[offset_select][i];
  116695. if(val>p->vi->noisemaxsupp)val=p->vi->noisemaxsupp;
  116696. logmask[i]=max(val,tone[i]+toneatt);
  116697. /* AoTuV */
  116698. /** @ M1 **
  116699. The following codes improve a noise problem.
  116700. A fundamental idea uses the value of masking and carries out
  116701. the relative compensation of the MDCT.
  116702. However, this code is not perfect and all noise problems cannot be solved.
  116703. by Aoyumi @ 2004/04/18
  116704. */
  116705. if(offset_select == 1) {
  116706. coeffi = -17.2; /* coeffi is a -17.2dB threshold */
  116707. val = val - logmdct[i]; /* val == mdct line value relative to floor in dB */
  116708. if(val > coeffi){
  116709. /* mdct value is > -17.2 dB below floor */
  116710. de = 1.0-((val-coeffi)*0.005*cx);
  116711. /* pro-rated attenuation:
  116712. -0.00 dB boost if mdct value is -17.2dB (relative to floor)
  116713. -0.77 dB boost if mdct value is 0dB (relative to floor)
  116714. -1.64 dB boost if mdct value is +17.2dB (relative to floor)
  116715. etc... */
  116716. if(de < 0) de = 0.0001;
  116717. }else
  116718. /* mdct value is <= -17.2 dB below floor */
  116719. de = 1.0-((val-coeffi)*0.0003*cx);
  116720. /* pro-rated attenuation:
  116721. +0.00 dB atten if mdct value is -17.2dB (relative to floor)
  116722. +0.45 dB atten if mdct value is -34.4dB (relative to floor)
  116723. etc... */
  116724. mdct[i] *= de;
  116725. }
  116726. }
  116727. }
  116728. float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd){
  116729. vorbis_info *vi=vd->vi;
  116730. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  116731. vorbis_info_psy_global *gi=&ci->psy_g_param;
  116732. int n=ci->blocksizes[vd->W]/2;
  116733. float secs=(float)n/vi->rate;
  116734. amp+=secs*gi->ampmax_att_per_sec;
  116735. if(amp<-9999)amp=-9999;
  116736. return(amp);
  116737. }
  116738. static void couple_lossless(float A, float B,
  116739. float *qA, float *qB){
  116740. int test1=fabs(*qA)>fabs(*qB);
  116741. test1-= fabs(*qA)<fabs(*qB);
  116742. if(!test1)test1=((fabs(A)>fabs(B))<<1)-1;
  116743. if(test1==1){
  116744. *qB=(*qA>0.f?*qA-*qB:*qB-*qA);
  116745. }else{
  116746. float temp=*qB;
  116747. *qB=(*qB>0.f?*qA-*qB:*qB-*qA);
  116748. *qA=temp;
  116749. }
  116750. if(*qB>fabs(*qA)*1.9999f){
  116751. *qB= -fabs(*qA)*2.f;
  116752. *qA= -*qA;
  116753. }
  116754. }
  116755. static float hypot_lookup[32]={
  116756. -0.009935, -0.011245, -0.012726, -0.014397,
  116757. -0.016282, -0.018407, -0.020800, -0.023494,
  116758. -0.026522, -0.029923, -0.033737, -0.038010,
  116759. -0.042787, -0.048121, -0.054064, -0.060671,
  116760. -0.068000, -0.076109, -0.085054, -0.094892,
  116761. -0.105675, -0.117451, -0.130260, -0.144134,
  116762. -0.159093, -0.175146, -0.192286, -0.210490,
  116763. -0.229718, -0.249913, -0.271001, -0.292893};
  116764. static void precomputed_couple_point(float premag,
  116765. int floorA,int floorB,
  116766. float *mag, float *ang){
  116767. int test=(floorA>floorB)-1;
  116768. int offset=31-abs(floorA-floorB);
  116769. float floormag=hypot_lookup[((offset<0)-1)&offset]+1.f;
  116770. floormag*=FLOOR1_fromdB_INV_LOOKUP[(floorB&test)|(floorA&(~test))];
  116771. *mag=premag*floormag;
  116772. *ang=0.f;
  116773. }
  116774. /* just like below, this is currently set up to only do
  116775. single-step-depth coupling. Otherwise, we'd have to do more
  116776. copying (which will be inevitable later) */
  116777. /* doing the real circular magnitude calculation is audibly superior
  116778. to (A+B)/sqrt(2) */
  116779. static float dipole_hypot(float a, float b){
  116780. if(a>0.){
  116781. if(b>0.)return sqrt(a*a+b*b);
  116782. if(a>-b)return sqrt(a*a-b*b);
  116783. return -sqrt(b*b-a*a);
  116784. }
  116785. if(b<0.)return -sqrt(a*a+b*b);
  116786. if(-a>b)return -sqrt(a*a-b*b);
  116787. return sqrt(b*b-a*a);
  116788. }
  116789. static float round_hypot(float a, float b){
  116790. if(a>0.){
  116791. if(b>0.)return sqrt(a*a+b*b);
  116792. if(a>-b)return sqrt(a*a+b*b);
  116793. return -sqrt(b*b+a*a);
  116794. }
  116795. if(b<0.)return -sqrt(a*a+b*b);
  116796. if(-a>b)return -sqrt(a*a+b*b);
  116797. return sqrt(b*b+a*a);
  116798. }
  116799. /* revert to round hypot for now */
  116800. float **_vp_quantize_couple_memo(vorbis_block *vb,
  116801. vorbis_info_psy_global *g,
  116802. vorbis_look_psy *p,
  116803. vorbis_info_mapping0 *vi,
  116804. float **mdct){
  116805. int i,j,n=p->n;
  116806. float **ret=(float**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  116807. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  116808. for(i=0;i<vi->coupling_steps;i++){
  116809. float *mdctM=mdct[vi->coupling_mag[i]];
  116810. float *mdctA=mdct[vi->coupling_ang[i]];
  116811. ret[i]=(float*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  116812. for(j=0;j<limit;j++)
  116813. ret[i][j]=dipole_hypot(mdctM[j],mdctA[j]);
  116814. for(;j<n;j++)
  116815. ret[i][j]=round_hypot(mdctM[j],mdctA[j]);
  116816. }
  116817. return(ret);
  116818. }
  116819. /* this is for per-channel noise normalization */
  116820. static int apsort(const void *a, const void *b){
  116821. float f1=fabs(**(float**)a);
  116822. float f2=fabs(**(float**)b);
  116823. return (f1<f2)-(f1>f2);
  116824. }
  116825. int **_vp_quantize_couple_sort(vorbis_block *vb,
  116826. vorbis_look_psy *p,
  116827. vorbis_info_mapping0 *vi,
  116828. float **mags){
  116829. if(p->vi->normal_point_p){
  116830. int i,j,k,n=p->n;
  116831. int **ret=(int**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  116832. int partition=p->vi->normal_partition;
  116833. float **work=(float**) alloca(sizeof(*work)*partition);
  116834. for(i=0;i<vi->coupling_steps;i++){
  116835. ret[i]=(int*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  116836. for(j=0;j<n;j+=partition){
  116837. for(k=0;k<partition;k++)work[k]=mags[i]+k+j;
  116838. qsort(work,partition,sizeof(*work),apsort);
  116839. for(k=0;k<partition;k++)ret[i][k+j]=work[k]-mags[i];
  116840. }
  116841. }
  116842. return(ret);
  116843. }
  116844. return(NULL);
  116845. }
  116846. void _vp_noise_normalize_sort(vorbis_look_psy *p,
  116847. float *magnitudes,int *sortedindex){
  116848. int i,j,n=p->n;
  116849. vorbis_info_psy *vi=p->vi;
  116850. int partition=vi->normal_partition;
  116851. float **work=(float**) alloca(sizeof(*work)*partition);
  116852. int start=vi->normal_start;
  116853. for(j=start;j<n;j+=partition){
  116854. if(j+partition>n)partition=n-j;
  116855. for(i=0;i<partition;i++)work[i]=magnitudes+i+j;
  116856. qsort(work,partition,sizeof(*work),apsort);
  116857. for(i=0;i<partition;i++){
  116858. sortedindex[i+j-start]=work[i]-magnitudes;
  116859. }
  116860. }
  116861. }
  116862. void _vp_noise_normalize(vorbis_look_psy *p,
  116863. float *in,float *out,int *sortedindex){
  116864. int flag=0,i,j=0,n=p->n;
  116865. vorbis_info_psy *vi=p->vi;
  116866. int partition=vi->normal_partition;
  116867. int start=vi->normal_start;
  116868. if(start>n)start=n;
  116869. if(vi->normal_channel_p){
  116870. for(;j<start;j++)
  116871. out[j]=rint(in[j]);
  116872. for(;j+partition<=n;j+=partition){
  116873. float acc=0.;
  116874. int k;
  116875. for(i=j;i<j+partition;i++)
  116876. acc+=in[i]*in[i];
  116877. for(i=0;i<partition;i++){
  116878. k=sortedindex[i+j-start];
  116879. if(in[k]*in[k]>=.25f){
  116880. out[k]=rint(in[k]);
  116881. acc-=in[k]*in[k];
  116882. flag=1;
  116883. }else{
  116884. if(acc<vi->normal_thresh)break;
  116885. out[k]=unitnorm(in[k]);
  116886. acc-=1.;
  116887. }
  116888. }
  116889. for(;i<partition;i++){
  116890. k=sortedindex[i+j-start];
  116891. out[k]=0.;
  116892. }
  116893. }
  116894. }
  116895. for(;j<n;j++)
  116896. out[j]=rint(in[j]);
  116897. }
  116898. void _vp_couple(int blobno,
  116899. vorbis_info_psy_global *g,
  116900. vorbis_look_psy *p,
  116901. vorbis_info_mapping0 *vi,
  116902. float **res,
  116903. float **mag_memo,
  116904. int **mag_sort,
  116905. int **ifloor,
  116906. int *nonzero,
  116907. int sliding_lowpass){
  116908. int i,j,k,n=p->n;
  116909. /* perform any requested channel coupling */
  116910. /* point stereo can only be used in a first stage (in this encoder)
  116911. because of the dependency on floor lookups */
  116912. for(i=0;i<vi->coupling_steps;i++){
  116913. /* once we're doing multistage coupling in which a channel goes
  116914. through more than one coupling step, the floor vector
  116915. magnitudes will also have to be recalculated an propogated
  116916. along with PCM. Right now, we're not (that will wait until 5.1
  116917. most likely), so the code isn't here yet. The memory management
  116918. here is all assuming single depth couplings anyway. */
  116919. /* make sure coupling a zero and a nonzero channel results in two
  116920. nonzero channels. */
  116921. if(nonzero[vi->coupling_mag[i]] ||
  116922. nonzero[vi->coupling_ang[i]]){
  116923. float *rM=res[vi->coupling_mag[i]];
  116924. float *rA=res[vi->coupling_ang[i]];
  116925. float *qM=rM+n;
  116926. float *qA=rA+n;
  116927. int *floorM=ifloor[vi->coupling_mag[i]];
  116928. int *floorA=ifloor[vi->coupling_ang[i]];
  116929. float prepoint=stereo_threshholds[g->coupling_prepointamp[blobno]];
  116930. float postpoint=stereo_threshholds[g->coupling_postpointamp[blobno]];
  116931. int partition=(p->vi->normal_point_p?p->vi->normal_partition:p->n);
  116932. int limit=g->coupling_pointlimit[p->vi->blockflag][blobno];
  116933. int pointlimit=limit;
  116934. nonzero[vi->coupling_mag[i]]=1;
  116935. nonzero[vi->coupling_ang[i]]=1;
  116936. /* The threshold of a stereo is changed with the size of n */
  116937. if(n > 1000)
  116938. postpoint=stereo_threshholds_limited[g->coupling_postpointamp[blobno]];
  116939. for(j=0;j<p->n;j+=partition){
  116940. float acc=0.f;
  116941. for(k=0;k<partition;k++){
  116942. int l=k+j;
  116943. if(l<sliding_lowpass){
  116944. if((l>=limit && fabs(rM[l])<postpoint && fabs(rA[l])<postpoint) ||
  116945. (fabs(rM[l])<prepoint && fabs(rA[l])<prepoint)){
  116946. precomputed_couple_point(mag_memo[i][l],
  116947. floorM[l],floorA[l],
  116948. qM+l,qA+l);
  116949. if(rint(qM[l])==0.f)acc+=qM[l]*qM[l];
  116950. }else{
  116951. couple_lossless(rM[l],rA[l],qM+l,qA+l);
  116952. }
  116953. }else{
  116954. qM[l]=0.;
  116955. qA[l]=0.;
  116956. }
  116957. }
  116958. if(p->vi->normal_point_p){
  116959. for(k=0;k<partition && acc>=p->vi->normal_thresh;k++){
  116960. int l=mag_sort[i][j+k];
  116961. if(l<sliding_lowpass && l>=pointlimit && rint(qM[l])==0.f){
  116962. qM[l]=unitnorm(qM[l]);
  116963. acc-=1.f;
  116964. }
  116965. }
  116966. }
  116967. }
  116968. }
  116969. }
  116970. }
  116971. /* AoTuV */
  116972. /** @ M2 **
  116973. The boost problem by the combination of noise normalization and point stereo is eased.
  116974. However, this is a temporary patch.
  116975. by Aoyumi @ 2004/04/18
  116976. */
  116977. void hf_reduction(vorbis_info_psy_global *g,
  116978. vorbis_look_psy *p,
  116979. vorbis_info_mapping0 *vi,
  116980. float **mdct){
  116981. int i,j,n=p->n, de=0.3*p->m_val;
  116982. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  116983. for(i=0; i<vi->coupling_steps; i++){
  116984. /* for(j=start; j<limit; j++){} // ???*/
  116985. for(j=limit; j<n; j++)
  116986. mdct[i][j] *= (1.0 - de*((float)(j-limit) / (float)(n-limit)));
  116987. }
  116988. }
  116989. #endif
  116990. /*** End of inlined file: psy.c ***/
  116991. /*** Start of inlined file: registry.c ***/
  116992. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  116993. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  116994. // tasks..
  116995. #if JUCE_MSVC
  116996. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  116997. #endif
  116998. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  116999. #if JUCE_USE_OGGVORBIS
  117000. /* seems like major overkill now; the backend numbers will grow into
  117001. the infrastructure soon enough */
  117002. extern vorbis_func_floor floor0_exportbundle;
  117003. extern vorbis_func_floor floor1_exportbundle;
  117004. extern vorbis_func_residue residue0_exportbundle;
  117005. extern vorbis_func_residue residue1_exportbundle;
  117006. extern vorbis_func_residue residue2_exportbundle;
  117007. extern vorbis_func_mapping mapping0_exportbundle;
  117008. vorbis_func_floor *_floor_P[]={
  117009. &floor0_exportbundle,
  117010. &floor1_exportbundle,
  117011. };
  117012. vorbis_func_residue *_residue_P[]={
  117013. &residue0_exportbundle,
  117014. &residue1_exportbundle,
  117015. &residue2_exportbundle,
  117016. };
  117017. vorbis_func_mapping *_mapping_P[]={
  117018. &mapping0_exportbundle,
  117019. };
  117020. #endif
  117021. /*** End of inlined file: registry.c ***/
  117022. /*** Start of inlined file: res0.c ***/
  117023. /* Slow, slow, slow, simpleminded and did I mention it was slow? The
  117024. encode/decode loops are coded for clarity and performance is not
  117025. yet even a nagging little idea lurking in the shadows. Oh and BTW,
  117026. it's slow. */
  117027. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  117028. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  117029. // tasks..
  117030. #if JUCE_MSVC
  117031. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  117032. #endif
  117033. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  117034. #if JUCE_USE_OGGVORBIS
  117035. #include <stdlib.h>
  117036. #include <string.h>
  117037. #include <math.h>
  117038. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  117039. #include <stdio.h>
  117040. #endif
  117041. typedef struct {
  117042. vorbis_info_residue0 *info;
  117043. int parts;
  117044. int stages;
  117045. codebook *fullbooks;
  117046. codebook *phrasebook;
  117047. codebook ***partbooks;
  117048. int partvals;
  117049. int **decodemap;
  117050. long postbits;
  117051. long phrasebits;
  117052. long frames;
  117053. #if defined(TRAIN_RES) || defined(TRAIN_RESAUX)
  117054. int train_seq;
  117055. long *training_data[8][64];
  117056. float training_max[8][64];
  117057. float training_min[8][64];
  117058. float tmin;
  117059. float tmax;
  117060. #endif
  117061. } vorbis_look_residue0;
  117062. void res0_free_info(vorbis_info_residue *i){
  117063. vorbis_info_residue0 *info=(vorbis_info_residue0 *)i;
  117064. if(info){
  117065. memset(info,0,sizeof(*info));
  117066. _ogg_free(info);
  117067. }
  117068. }
  117069. void res0_free_look(vorbis_look_residue *i){
  117070. int j;
  117071. if(i){
  117072. vorbis_look_residue0 *look=(vorbis_look_residue0 *)i;
  117073. #ifdef TRAIN_RES
  117074. {
  117075. int j,k,l;
  117076. for(j=0;j<look->parts;j++){
  117077. /*fprintf(stderr,"partition %d: ",j);*/
  117078. for(k=0;k<8;k++)
  117079. if(look->training_data[k][j]){
  117080. char buffer[80];
  117081. FILE *of;
  117082. codebook *statebook=look->partbooks[j][k];
  117083. /* long and short into the same bucket by current convention */
  117084. sprintf(buffer,"res_part%d_pass%d.vqd",j,k);
  117085. of=fopen(buffer,"a");
  117086. for(l=0;l<statebook->entries;l++)
  117087. fprintf(of,"%d:%ld\n",l,look->training_data[k][j][l]);
  117088. fclose(of);
  117089. /*fprintf(stderr,"%d(%.2f|%.2f) ",k,
  117090. look->training_min[k][j],look->training_max[k][j]);*/
  117091. _ogg_free(look->training_data[k][j]);
  117092. look->training_data[k][j]=NULL;
  117093. }
  117094. /*fprintf(stderr,"\n");*/
  117095. }
  117096. }
  117097. fprintf(stderr,"min/max residue: %g::%g\n",look->tmin,look->tmax);
  117098. /*fprintf(stderr,"residue bit usage %f:%f (%f total)\n",
  117099. (float)look->phrasebits/look->frames,
  117100. (float)look->postbits/look->frames,
  117101. (float)(look->postbits+look->phrasebits)/look->frames);*/
  117102. #endif
  117103. /*vorbis_info_residue0 *info=look->info;
  117104. fprintf(stderr,
  117105. "%ld frames encoded in %ld phrasebits and %ld residue bits "
  117106. "(%g/frame) \n",look->frames,look->phrasebits,
  117107. look->resbitsflat,
  117108. (look->phrasebits+look->resbitsflat)/(float)look->frames);
  117109. for(j=0;j<look->parts;j++){
  117110. long acc=0;
  117111. fprintf(stderr,"\t[%d] == ",j);
  117112. for(k=0;k<look->stages;k++)
  117113. if((info->secondstages[j]>>k)&1){
  117114. fprintf(stderr,"%ld,",look->resbits[j][k]);
  117115. acc+=look->resbits[j][k];
  117116. }
  117117. fprintf(stderr,":: (%ld vals) %1.2fbits/sample\n",look->resvals[j],
  117118. acc?(float)acc/(look->resvals[j]*info->grouping):0);
  117119. }
  117120. fprintf(stderr,"\n");*/
  117121. for(j=0;j<look->parts;j++)
  117122. if(look->partbooks[j])_ogg_free(look->partbooks[j]);
  117123. _ogg_free(look->partbooks);
  117124. for(j=0;j<look->partvals;j++)
  117125. _ogg_free(look->decodemap[j]);
  117126. _ogg_free(look->decodemap);
  117127. memset(look,0,sizeof(*look));
  117128. _ogg_free(look);
  117129. }
  117130. }
  117131. static int icount(unsigned int v){
  117132. int ret=0;
  117133. while(v){
  117134. ret+=v&1;
  117135. v>>=1;
  117136. }
  117137. return(ret);
  117138. }
  117139. void res0_pack(vorbis_info_residue *vr,oggpack_buffer *opb){
  117140. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  117141. int j,acc=0;
  117142. oggpack_write(opb,info->begin,24);
  117143. oggpack_write(opb,info->end,24);
  117144. oggpack_write(opb,info->grouping-1,24); /* residue vectors to group and
  117145. code with a partitioned book */
  117146. oggpack_write(opb,info->partitions-1,6); /* possible partition choices */
  117147. oggpack_write(opb,info->groupbook,8); /* group huffman book */
  117148. /* secondstages is a bitmask; as encoding progresses pass by pass, a
  117149. bitmask of one indicates this partition class has bits to write
  117150. this pass */
  117151. for(j=0;j<info->partitions;j++){
  117152. if(ilog(info->secondstages[j])>3){
  117153. /* yes, this is a minor hack due to not thinking ahead */
  117154. oggpack_write(opb,info->secondstages[j],3);
  117155. oggpack_write(opb,1,1);
  117156. oggpack_write(opb,info->secondstages[j]>>3,5);
  117157. }else
  117158. oggpack_write(opb,info->secondstages[j],4); /* trailing zero */
  117159. acc+=icount(info->secondstages[j]);
  117160. }
  117161. for(j=0;j<acc;j++)
  117162. oggpack_write(opb,info->booklist[j],8);
  117163. }
  117164. /* vorbis_info is for range checking */
  117165. vorbis_info_residue *res0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  117166. int j,acc=0;
  117167. vorbis_info_residue0 *info=(vorbis_info_residue0*) _ogg_calloc(1,sizeof(*info));
  117168. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  117169. info->begin=oggpack_read(opb,24);
  117170. info->end=oggpack_read(opb,24);
  117171. info->grouping=oggpack_read(opb,24)+1;
  117172. info->partitions=oggpack_read(opb,6)+1;
  117173. info->groupbook=oggpack_read(opb,8);
  117174. for(j=0;j<info->partitions;j++){
  117175. int cascade=oggpack_read(opb,3);
  117176. if(oggpack_read(opb,1))
  117177. cascade|=(oggpack_read(opb,5)<<3);
  117178. info->secondstages[j]=cascade;
  117179. acc+=icount(cascade);
  117180. }
  117181. for(j=0;j<acc;j++)
  117182. info->booklist[j]=oggpack_read(opb,8);
  117183. if(info->groupbook>=ci->books)goto errout;
  117184. for(j=0;j<acc;j++)
  117185. if(info->booklist[j]>=ci->books)goto errout;
  117186. return(info);
  117187. errout:
  117188. res0_free_info(info);
  117189. return(NULL);
  117190. }
  117191. vorbis_look_residue *res0_look(vorbis_dsp_state *vd,
  117192. vorbis_info_residue *vr){
  117193. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  117194. vorbis_look_residue0 *look=(vorbis_look_residue0 *)_ogg_calloc(1,sizeof(*look));
  117195. codec_setup_info *ci=(codec_setup_info*)vd->vi->codec_setup;
  117196. int j,k,acc=0;
  117197. int dim;
  117198. int maxstage=0;
  117199. look->info=info;
  117200. look->parts=info->partitions;
  117201. look->fullbooks=ci->fullbooks;
  117202. look->phrasebook=ci->fullbooks+info->groupbook;
  117203. dim=look->phrasebook->dim;
  117204. look->partbooks=(codebook***)_ogg_calloc(look->parts,sizeof(*look->partbooks));
  117205. for(j=0;j<look->parts;j++){
  117206. int stages=ilog(info->secondstages[j]);
  117207. if(stages){
  117208. if(stages>maxstage)maxstage=stages;
  117209. look->partbooks[j]=(codebook**) _ogg_calloc(stages,sizeof(*look->partbooks[j]));
  117210. for(k=0;k<stages;k++)
  117211. if(info->secondstages[j]&(1<<k)){
  117212. look->partbooks[j][k]=ci->fullbooks+info->booklist[acc++];
  117213. #ifdef TRAIN_RES
  117214. look->training_data[k][j]=_ogg_calloc(look->partbooks[j][k]->entries,
  117215. sizeof(***look->training_data));
  117216. #endif
  117217. }
  117218. }
  117219. }
  117220. look->partvals=rint(pow((float)look->parts,(float)dim));
  117221. look->stages=maxstage;
  117222. look->decodemap=(int**)_ogg_malloc(look->partvals*sizeof(*look->decodemap));
  117223. for(j=0;j<look->partvals;j++){
  117224. long val=j;
  117225. long mult=look->partvals/look->parts;
  117226. look->decodemap[j]=(int*)_ogg_malloc(dim*sizeof(*look->decodemap[j]));
  117227. for(k=0;k<dim;k++){
  117228. long deco=val/mult;
  117229. val-=deco*mult;
  117230. mult/=look->parts;
  117231. look->decodemap[j][k]=deco;
  117232. }
  117233. }
  117234. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  117235. {
  117236. static int train_seq=0;
  117237. look->train_seq=train_seq++;
  117238. }
  117239. #endif
  117240. return(look);
  117241. }
  117242. /* break an abstraction and copy some code for performance purposes */
  117243. static int local_book_besterror(codebook *book,float *a){
  117244. int dim=book->dim,i,k,o;
  117245. int best=0;
  117246. encode_aux_threshmatch *tt=book->c->thresh_tree;
  117247. /* find the quant val of each scalar */
  117248. for(k=0,o=dim;k<dim;++k){
  117249. float val=a[--o];
  117250. i=tt->threshvals>>1;
  117251. if(val<tt->quantthresh[i]){
  117252. if(val<tt->quantthresh[i-1]){
  117253. for(--i;i>0;--i)
  117254. if(val>=tt->quantthresh[i-1])
  117255. break;
  117256. }
  117257. }else{
  117258. for(++i;i<tt->threshvals-1;++i)
  117259. if(val<tt->quantthresh[i])break;
  117260. }
  117261. best=(best*tt->quantvals)+tt->quantmap[i];
  117262. }
  117263. /* regular lattices are easy :-) */
  117264. if(book->c->lengthlist[best]<=0){
  117265. const static_codebook *c=book->c;
  117266. int i,j;
  117267. float bestf=0.f;
  117268. float *e=book->valuelist;
  117269. best=-1;
  117270. for(i=0;i<book->entries;i++){
  117271. if(c->lengthlist[i]>0){
  117272. float thisx=0.f;
  117273. for(j=0;j<dim;j++){
  117274. float val=(e[j]-a[j]);
  117275. thisx+=val*val;
  117276. }
  117277. if(best==-1 || thisx<bestf){
  117278. bestf=thisx;
  117279. best=i;
  117280. }
  117281. }
  117282. e+=dim;
  117283. }
  117284. }
  117285. {
  117286. float *ptr=book->valuelist+best*dim;
  117287. for(i=0;i<dim;i++)
  117288. *a++ -= *ptr++;
  117289. }
  117290. return(best);
  117291. }
  117292. static int _encodepart(oggpack_buffer *opb,float *vec, int n,
  117293. codebook *book,long *acc){
  117294. int i,bits=0;
  117295. int dim=book->dim;
  117296. int step=n/dim;
  117297. for(i=0;i<step;i++){
  117298. int entry=local_book_besterror(book,vec+i*dim);
  117299. #ifdef TRAIN_RES
  117300. acc[entry]++;
  117301. #endif
  117302. bits+=vorbis_book_encode(book,entry,opb);
  117303. }
  117304. return(bits);
  117305. }
  117306. static long **_01class(vorbis_block *vb,vorbis_look_residue *vl,
  117307. float **in,int ch){
  117308. long i,j,k;
  117309. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  117310. vorbis_info_residue0 *info=look->info;
  117311. /* move all this setup out later */
  117312. int samples_per_partition=info->grouping;
  117313. int possible_partitions=info->partitions;
  117314. int n=info->end-info->begin;
  117315. int partvals=n/samples_per_partition;
  117316. long **partword=(long**)_vorbis_block_alloc(vb,ch*sizeof(*partword));
  117317. float scale=100./samples_per_partition;
  117318. /* we find the partition type for each partition of each
  117319. channel. We'll go back and do the interleaved encoding in a
  117320. bit. For now, clarity */
  117321. for(i=0;i<ch;i++){
  117322. partword[i]=(long*)_vorbis_block_alloc(vb,n/samples_per_partition*sizeof(*partword[i]));
  117323. memset(partword[i],0,n/samples_per_partition*sizeof(*partword[i]));
  117324. }
  117325. for(i=0;i<partvals;i++){
  117326. int offset=i*samples_per_partition+info->begin;
  117327. for(j=0;j<ch;j++){
  117328. float max=0.;
  117329. float ent=0.;
  117330. for(k=0;k<samples_per_partition;k++){
  117331. if(fabs(in[j][offset+k])>max)max=fabs(in[j][offset+k]);
  117332. ent+=fabs(rint(in[j][offset+k]));
  117333. }
  117334. ent*=scale;
  117335. for(k=0;k<possible_partitions-1;k++)
  117336. if(max<=info->classmetric1[k] &&
  117337. (info->classmetric2[k]<0 || (int)ent<info->classmetric2[k]))
  117338. break;
  117339. partword[j][i]=k;
  117340. }
  117341. }
  117342. #ifdef TRAIN_RESAUX
  117343. {
  117344. FILE *of;
  117345. char buffer[80];
  117346. for(i=0;i<ch;i++){
  117347. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  117348. of=fopen(buffer,"a");
  117349. for(j=0;j<partvals;j++)
  117350. fprintf(of,"%ld, ",partword[i][j]);
  117351. fprintf(of,"\n");
  117352. fclose(of);
  117353. }
  117354. }
  117355. #endif
  117356. look->frames++;
  117357. return(partword);
  117358. }
  117359. /* designed for stereo or other modes where the partition size is an
  117360. integer multiple of the number of channels encoded in the current
  117361. submap */
  117362. static long **_2class(vorbis_block *vb,vorbis_look_residue *vl,float **in,
  117363. int ch){
  117364. long i,j,k,l;
  117365. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  117366. vorbis_info_residue0 *info=look->info;
  117367. /* move all this setup out later */
  117368. int samples_per_partition=info->grouping;
  117369. int possible_partitions=info->partitions;
  117370. int n=info->end-info->begin;
  117371. int partvals=n/samples_per_partition;
  117372. long **partword=(long**)_vorbis_block_alloc(vb,sizeof(*partword));
  117373. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  117374. FILE *of;
  117375. char buffer[80];
  117376. #endif
  117377. partword[0]=(long*)_vorbis_block_alloc(vb,n*ch/samples_per_partition*sizeof(*partword[0]));
  117378. memset(partword[0],0,n*ch/samples_per_partition*sizeof(*partword[0]));
  117379. for(i=0,l=info->begin/ch;i<partvals;i++){
  117380. float magmax=0.f;
  117381. float angmax=0.f;
  117382. for(j=0;j<samples_per_partition;j+=ch){
  117383. if(fabs(in[0][l])>magmax)magmax=fabs(in[0][l]);
  117384. for(k=1;k<ch;k++)
  117385. if(fabs(in[k][l])>angmax)angmax=fabs(in[k][l]);
  117386. l++;
  117387. }
  117388. for(j=0;j<possible_partitions-1;j++)
  117389. if(magmax<=info->classmetric1[j] &&
  117390. angmax<=info->classmetric2[j])
  117391. break;
  117392. partword[0][i]=j;
  117393. }
  117394. #ifdef TRAIN_RESAUX
  117395. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  117396. of=fopen(buffer,"a");
  117397. for(i=0;i<partvals;i++)
  117398. fprintf(of,"%ld, ",partword[0][i]);
  117399. fprintf(of,"\n");
  117400. fclose(of);
  117401. #endif
  117402. look->frames++;
  117403. return(partword);
  117404. }
  117405. static int _01forward(oggpack_buffer *opb,
  117406. vorbis_block *vb,vorbis_look_residue *vl,
  117407. float **in,int ch,
  117408. long **partword,
  117409. int (*encode)(oggpack_buffer *,float *,int,
  117410. codebook *,long *)){
  117411. long i,j,k,s;
  117412. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  117413. vorbis_info_residue0 *info=look->info;
  117414. /* move all this setup out later */
  117415. int samples_per_partition=info->grouping;
  117416. int possible_partitions=info->partitions;
  117417. int partitions_per_word=look->phrasebook->dim;
  117418. int n=info->end-info->begin;
  117419. int partvals=n/samples_per_partition;
  117420. long resbits[128];
  117421. long resvals[128];
  117422. #ifdef TRAIN_RES
  117423. for(i=0;i<ch;i++)
  117424. for(j=info->begin;j<info->end;j++){
  117425. if(in[i][j]>look->tmax)look->tmax=in[i][j];
  117426. if(in[i][j]<look->tmin)look->tmin=in[i][j];
  117427. }
  117428. #endif
  117429. memset(resbits,0,sizeof(resbits));
  117430. memset(resvals,0,sizeof(resvals));
  117431. /* we code the partition words for each channel, then the residual
  117432. words for a partition per channel until we've written all the
  117433. residual words for that partition word. Then write the next
  117434. partition channel words... */
  117435. for(s=0;s<look->stages;s++){
  117436. for(i=0;i<partvals;){
  117437. /* first we encode a partition codeword for each channel */
  117438. if(s==0){
  117439. for(j=0;j<ch;j++){
  117440. long val=partword[j][i];
  117441. for(k=1;k<partitions_per_word;k++){
  117442. val*=possible_partitions;
  117443. if(i+k<partvals)
  117444. val+=partword[j][i+k];
  117445. }
  117446. /* training hack */
  117447. if(val<look->phrasebook->entries)
  117448. look->phrasebits+=vorbis_book_encode(look->phrasebook,val,opb);
  117449. #if 0 /*def TRAIN_RES*/
  117450. else
  117451. fprintf(stderr,"!");
  117452. #endif
  117453. }
  117454. }
  117455. /* now we encode interleaved residual values for the partitions */
  117456. for(k=0;k<partitions_per_word && i<partvals;k++,i++){
  117457. long offset=i*samples_per_partition+info->begin;
  117458. for(j=0;j<ch;j++){
  117459. if(s==0)resvals[partword[j][i]]+=samples_per_partition;
  117460. if(info->secondstages[partword[j][i]]&(1<<s)){
  117461. codebook *statebook=look->partbooks[partword[j][i]][s];
  117462. if(statebook){
  117463. int ret;
  117464. long *accumulator=NULL;
  117465. #ifdef TRAIN_RES
  117466. accumulator=look->training_data[s][partword[j][i]];
  117467. {
  117468. int l;
  117469. float *samples=in[j]+offset;
  117470. for(l=0;l<samples_per_partition;l++){
  117471. if(samples[l]<look->training_min[s][partword[j][i]])
  117472. look->training_min[s][partword[j][i]]=samples[l];
  117473. if(samples[l]>look->training_max[s][partword[j][i]])
  117474. look->training_max[s][partword[j][i]]=samples[l];
  117475. }
  117476. }
  117477. #endif
  117478. ret=encode(opb,in[j]+offset,samples_per_partition,
  117479. statebook,accumulator);
  117480. look->postbits+=ret;
  117481. resbits[partword[j][i]]+=ret;
  117482. }
  117483. }
  117484. }
  117485. }
  117486. }
  117487. }
  117488. /*{
  117489. long total=0;
  117490. long totalbits=0;
  117491. fprintf(stderr,"%d :: ",vb->mode);
  117492. for(k=0;k<possible_partitions;k++){
  117493. fprintf(stderr,"%ld/%1.2g, ",resvals[k],(float)resbits[k]/resvals[k]);
  117494. total+=resvals[k];
  117495. totalbits+=resbits[k];
  117496. }
  117497. fprintf(stderr,":: %ld:%1.2g\n",total,(double)totalbits/total);
  117498. }*/
  117499. return(0);
  117500. }
  117501. /* a truncated packet here just means 'stop working'; it's not an error */
  117502. static int _01inverse(vorbis_block *vb,vorbis_look_residue *vl,
  117503. float **in,int ch,
  117504. long (*decodepart)(codebook *, float *,
  117505. oggpack_buffer *,int)){
  117506. long i,j,k,l,s;
  117507. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  117508. vorbis_info_residue0 *info=look->info;
  117509. /* move all this setup out later */
  117510. int samples_per_partition=info->grouping;
  117511. int partitions_per_word=look->phrasebook->dim;
  117512. int n=info->end-info->begin;
  117513. int partvals=n/samples_per_partition;
  117514. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  117515. int ***partword=(int***)alloca(ch*sizeof(*partword));
  117516. for(j=0;j<ch;j++)
  117517. partword[j]=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword[j]));
  117518. for(s=0;s<look->stages;s++){
  117519. /* each loop decodes on partition codeword containing
  117520. partitions_pre_word partitions */
  117521. for(i=0,l=0;i<partvals;l++){
  117522. if(s==0){
  117523. /* fetch the partition word for each channel */
  117524. for(j=0;j<ch;j++){
  117525. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  117526. if(temp==-1)goto eopbreak;
  117527. partword[j][l]=look->decodemap[temp];
  117528. if(partword[j][l]==NULL)goto errout;
  117529. }
  117530. }
  117531. /* now we decode residual values for the partitions */
  117532. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  117533. for(j=0;j<ch;j++){
  117534. long offset=info->begin+i*samples_per_partition;
  117535. if(info->secondstages[partword[j][l][k]]&(1<<s)){
  117536. codebook *stagebook=look->partbooks[partword[j][l][k]][s];
  117537. if(stagebook){
  117538. if(decodepart(stagebook,in[j]+offset,&vb->opb,
  117539. samples_per_partition)==-1)goto eopbreak;
  117540. }
  117541. }
  117542. }
  117543. }
  117544. }
  117545. errout:
  117546. eopbreak:
  117547. return(0);
  117548. }
  117549. #if 0
  117550. /* residue 0 and 1 are just slight variants of one another. 0 is
  117551. interleaved, 1 is not */
  117552. long **res0_class(vorbis_block *vb,vorbis_look_residue *vl,
  117553. float **in,int *nonzero,int ch){
  117554. /* we encode only the nonzero parts of a bundle */
  117555. int i,used=0;
  117556. for(i=0;i<ch;i++)
  117557. if(nonzero[i])
  117558. in[used++]=in[i];
  117559. if(used)
  117560. /*return(_01class(vb,vl,in,used,_interleaved_testhack));*/
  117561. return(_01class(vb,vl,in,used));
  117562. else
  117563. return(0);
  117564. }
  117565. int res0_forward(vorbis_block *vb,vorbis_look_residue *vl,
  117566. float **in,float **out,int *nonzero,int ch,
  117567. long **partword){
  117568. /* we encode only the nonzero parts of a bundle */
  117569. int i,j,used=0,n=vb->pcmend/2;
  117570. for(i=0;i<ch;i++)
  117571. if(nonzero[i]){
  117572. if(out)
  117573. for(j=0;j<n;j++)
  117574. out[i][j]+=in[i][j];
  117575. in[used++]=in[i];
  117576. }
  117577. if(used){
  117578. int ret=_01forward(vb,vl,in,used,partword,
  117579. _interleaved_encodepart);
  117580. if(out){
  117581. used=0;
  117582. for(i=0;i<ch;i++)
  117583. if(nonzero[i]){
  117584. for(j=0;j<n;j++)
  117585. out[i][j]-=in[used][j];
  117586. used++;
  117587. }
  117588. }
  117589. return(ret);
  117590. }else{
  117591. return(0);
  117592. }
  117593. }
  117594. #endif
  117595. int res0_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  117596. float **in,int *nonzero,int ch){
  117597. int i,used=0;
  117598. for(i=0;i<ch;i++)
  117599. if(nonzero[i])
  117600. in[used++]=in[i];
  117601. if(used)
  117602. return(_01inverse(vb,vl,in,used,vorbis_book_decodevs_add));
  117603. else
  117604. return(0);
  117605. }
  117606. int res1_forward(oggpack_buffer *opb,vorbis_block *vb,vorbis_look_residue *vl,
  117607. float **in,float **out,int *nonzero,int ch,
  117608. long **partword){
  117609. int i,j,used=0,n=vb->pcmend/2;
  117610. for(i=0;i<ch;i++)
  117611. if(nonzero[i]){
  117612. if(out)
  117613. for(j=0;j<n;j++)
  117614. out[i][j]+=in[i][j];
  117615. in[used++]=in[i];
  117616. }
  117617. if(used){
  117618. int ret=_01forward(opb,vb,vl,in,used,partword,_encodepart);
  117619. if(out){
  117620. used=0;
  117621. for(i=0;i<ch;i++)
  117622. if(nonzero[i]){
  117623. for(j=0;j<n;j++)
  117624. out[i][j]-=in[used][j];
  117625. used++;
  117626. }
  117627. }
  117628. return(ret);
  117629. }else{
  117630. return(0);
  117631. }
  117632. }
  117633. long **res1_class(vorbis_block *vb,vorbis_look_residue *vl,
  117634. float **in,int *nonzero,int ch){
  117635. int i,used=0;
  117636. for(i=0;i<ch;i++)
  117637. if(nonzero[i])
  117638. in[used++]=in[i];
  117639. if(used)
  117640. return(_01class(vb,vl,in,used));
  117641. else
  117642. return(0);
  117643. }
  117644. int res1_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  117645. float **in,int *nonzero,int ch){
  117646. int i,used=0;
  117647. for(i=0;i<ch;i++)
  117648. if(nonzero[i])
  117649. in[used++]=in[i];
  117650. if(used)
  117651. return(_01inverse(vb,vl,in,used,vorbis_book_decodev_add));
  117652. else
  117653. return(0);
  117654. }
  117655. long **res2_class(vorbis_block *vb,vorbis_look_residue *vl,
  117656. float **in,int *nonzero,int ch){
  117657. int i,used=0;
  117658. for(i=0;i<ch;i++)
  117659. if(nonzero[i])used++;
  117660. if(used)
  117661. return(_2class(vb,vl,in,ch));
  117662. else
  117663. return(0);
  117664. }
  117665. /* res2 is slightly more different; all the channels are interleaved
  117666. into a single vector and encoded. */
  117667. int res2_forward(oggpack_buffer *opb,
  117668. vorbis_block *vb,vorbis_look_residue *vl,
  117669. float **in,float **out,int *nonzero,int ch,
  117670. long **partword){
  117671. long i,j,k,n=vb->pcmend/2,used=0;
  117672. /* don't duplicate the code; use a working vector hack for now and
  117673. reshape ourselves into a single channel res1 */
  117674. /* ugly; reallocs for each coupling pass :-( */
  117675. float *work=(float*)_vorbis_block_alloc(vb,ch*n*sizeof(*work));
  117676. for(i=0;i<ch;i++){
  117677. float *pcm=in[i];
  117678. if(nonzero[i])used++;
  117679. for(j=0,k=i;j<n;j++,k+=ch)
  117680. work[k]=pcm[j];
  117681. }
  117682. if(used){
  117683. int ret=_01forward(opb,vb,vl,&work,1,partword,_encodepart);
  117684. /* update the sofar vector */
  117685. if(out){
  117686. for(i=0;i<ch;i++){
  117687. float *pcm=in[i];
  117688. float *sofar=out[i];
  117689. for(j=0,k=i;j<n;j++,k+=ch)
  117690. sofar[j]+=pcm[j]-work[k];
  117691. }
  117692. }
  117693. return(ret);
  117694. }else{
  117695. return(0);
  117696. }
  117697. }
  117698. /* duplicate code here as speed is somewhat more important */
  117699. int res2_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  117700. float **in,int *nonzero,int ch){
  117701. long i,k,l,s;
  117702. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  117703. vorbis_info_residue0 *info=look->info;
  117704. /* move all this setup out later */
  117705. int samples_per_partition=info->grouping;
  117706. int partitions_per_word=look->phrasebook->dim;
  117707. int n=info->end-info->begin;
  117708. int partvals=n/samples_per_partition;
  117709. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  117710. int **partword=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword));
  117711. for(i=0;i<ch;i++)if(nonzero[i])break;
  117712. if(i==ch)return(0); /* no nonzero vectors */
  117713. for(s=0;s<look->stages;s++){
  117714. for(i=0,l=0;i<partvals;l++){
  117715. if(s==0){
  117716. /* fetch the partition word */
  117717. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  117718. if(temp==-1)goto eopbreak;
  117719. partword[l]=look->decodemap[temp];
  117720. if(partword[l]==NULL)goto errout;
  117721. }
  117722. /* now we decode residual values for the partitions */
  117723. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  117724. if(info->secondstages[partword[l][k]]&(1<<s)){
  117725. codebook *stagebook=look->partbooks[partword[l][k]][s];
  117726. if(stagebook){
  117727. if(vorbis_book_decodevv_add(stagebook,in,
  117728. i*samples_per_partition+info->begin,ch,
  117729. &vb->opb,samples_per_partition)==-1)
  117730. goto eopbreak;
  117731. }
  117732. }
  117733. }
  117734. }
  117735. errout:
  117736. eopbreak:
  117737. return(0);
  117738. }
  117739. vorbis_func_residue residue0_exportbundle={
  117740. NULL,
  117741. &res0_unpack,
  117742. &res0_look,
  117743. &res0_free_info,
  117744. &res0_free_look,
  117745. NULL,
  117746. NULL,
  117747. &res0_inverse
  117748. };
  117749. vorbis_func_residue residue1_exportbundle={
  117750. &res0_pack,
  117751. &res0_unpack,
  117752. &res0_look,
  117753. &res0_free_info,
  117754. &res0_free_look,
  117755. &res1_class,
  117756. &res1_forward,
  117757. &res1_inverse
  117758. };
  117759. vorbis_func_residue residue2_exportbundle={
  117760. &res0_pack,
  117761. &res0_unpack,
  117762. &res0_look,
  117763. &res0_free_info,
  117764. &res0_free_look,
  117765. &res2_class,
  117766. &res2_forward,
  117767. &res2_inverse
  117768. };
  117769. #endif
  117770. /*** End of inlined file: res0.c ***/
  117771. /*** Start of inlined file: sharedbook.c ***/
  117772. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  117773. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  117774. // tasks..
  117775. #if JUCE_MSVC
  117776. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  117777. #endif
  117778. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  117779. #if JUCE_USE_OGGVORBIS
  117780. #include <stdlib.h>
  117781. #include <math.h>
  117782. #include <string.h>
  117783. /**** pack/unpack helpers ******************************************/
  117784. int _ilog(unsigned int v){
  117785. int ret=0;
  117786. while(v){
  117787. ret++;
  117788. v>>=1;
  117789. }
  117790. return(ret);
  117791. }
  117792. /* 32 bit float (not IEEE; nonnormalized mantissa +
  117793. biased exponent) : neeeeeee eeemmmmm mmmmmmmm mmmmmmmm
  117794. Why not IEEE? It's just not that important here. */
  117795. #define VQ_FEXP 10
  117796. #define VQ_FMAN 21
  117797. #define VQ_FEXP_BIAS 768 /* bias toward values smaller than 1. */
  117798. /* doesn't currently guard under/overflow */
  117799. long _float32_pack(float val){
  117800. int sign=0;
  117801. long exp;
  117802. long mant;
  117803. if(val<0){
  117804. sign=0x80000000;
  117805. val= -val;
  117806. }
  117807. exp= floor(log(val)/log(2.f));
  117808. mant=rint(ldexp(val,(VQ_FMAN-1)-exp));
  117809. exp=(exp+VQ_FEXP_BIAS)<<VQ_FMAN;
  117810. return(sign|exp|mant);
  117811. }
  117812. float _float32_unpack(long val){
  117813. double mant=val&0x1fffff;
  117814. int sign=val&0x80000000;
  117815. long exp =(val&0x7fe00000L)>>VQ_FMAN;
  117816. if(sign)mant= -mant;
  117817. return(ldexp(mant,exp-(VQ_FMAN-1)-VQ_FEXP_BIAS));
  117818. }
  117819. /* given a list of word lengths, generate a list of codewords. Works
  117820. for length ordered or unordered, always assigns the lowest valued
  117821. codewords first. Extended to handle unused entries (length 0) */
  117822. ogg_uint32_t *_make_words(long *l,long n,long sparsecount){
  117823. long i,j,count=0;
  117824. ogg_uint32_t marker[33];
  117825. ogg_uint32_t *r=(ogg_uint32_t*)_ogg_malloc((sparsecount?sparsecount:n)*sizeof(*r));
  117826. memset(marker,0,sizeof(marker));
  117827. for(i=0;i<n;i++){
  117828. long length=l[i];
  117829. if(length>0){
  117830. ogg_uint32_t entry=marker[length];
  117831. /* when we claim a node for an entry, we also claim the nodes
  117832. below it (pruning off the imagined tree that may have dangled
  117833. from it) as well as blocking the use of any nodes directly
  117834. above for leaves */
  117835. /* update ourself */
  117836. if(length<32 && (entry>>length)){
  117837. /* error condition; the lengths must specify an overpopulated tree */
  117838. _ogg_free(r);
  117839. return(NULL);
  117840. }
  117841. r[count++]=entry;
  117842. /* Look to see if the next shorter marker points to the node
  117843. above. if so, update it and repeat. */
  117844. {
  117845. for(j=length;j>0;j--){
  117846. if(marker[j]&1){
  117847. /* have to jump branches */
  117848. if(j==1)
  117849. marker[1]++;
  117850. else
  117851. marker[j]=marker[j-1]<<1;
  117852. break; /* invariant says next upper marker would already
  117853. have been moved if it was on the same path */
  117854. }
  117855. marker[j]++;
  117856. }
  117857. }
  117858. /* prune the tree; the implicit invariant says all the longer
  117859. markers were dangling from our just-taken node. Dangle them
  117860. from our *new* node. */
  117861. for(j=length+1;j<33;j++)
  117862. if((marker[j]>>1) == entry){
  117863. entry=marker[j];
  117864. marker[j]=marker[j-1]<<1;
  117865. }else
  117866. break;
  117867. }else
  117868. if(sparsecount==0)count++;
  117869. }
  117870. /* bitreverse the words because our bitwise packer/unpacker is LSb
  117871. endian */
  117872. for(i=0,count=0;i<n;i++){
  117873. ogg_uint32_t temp=0;
  117874. for(j=0;j<l[i];j++){
  117875. temp<<=1;
  117876. temp|=(r[count]>>j)&1;
  117877. }
  117878. if(sparsecount){
  117879. if(l[i])
  117880. r[count++]=temp;
  117881. }else
  117882. r[count++]=temp;
  117883. }
  117884. return(r);
  117885. }
  117886. /* there might be a straightforward one-line way to do the below
  117887. that's portable and totally safe against roundoff, but I haven't
  117888. thought of it. Therefore, we opt on the side of caution */
  117889. long _book_maptype1_quantvals(const static_codebook *b){
  117890. long vals=floor(pow((float)b->entries,1.f/b->dim));
  117891. /* the above *should* be reliable, but we'll not assume that FP is
  117892. ever reliable when bitstream sync is at stake; verify via integer
  117893. means that vals really is the greatest value of dim for which
  117894. vals^b->bim <= b->entries */
  117895. /* treat the above as an initial guess */
  117896. while(1){
  117897. long acc=1;
  117898. long acc1=1;
  117899. int i;
  117900. for(i=0;i<b->dim;i++){
  117901. acc*=vals;
  117902. acc1*=vals+1;
  117903. }
  117904. if(acc<=b->entries && acc1>b->entries){
  117905. return(vals);
  117906. }else{
  117907. if(acc>b->entries){
  117908. vals--;
  117909. }else{
  117910. vals++;
  117911. }
  117912. }
  117913. }
  117914. }
  117915. /* unpack the quantized list of values for encode/decode ***********/
  117916. /* we need to deal with two map types: in map type 1, the values are
  117917. generated algorithmically (each column of the vector counts through
  117918. the values in the quant vector). in map type 2, all the values came
  117919. in in an explicit list. Both value lists must be unpacked */
  117920. float *_book_unquantize(const static_codebook *b,int n,int *sparsemap){
  117921. long j,k,count=0;
  117922. if(b->maptype==1 || b->maptype==2){
  117923. int quantvals;
  117924. float mindel=_float32_unpack(b->q_min);
  117925. float delta=_float32_unpack(b->q_delta);
  117926. float *r=(float*)_ogg_calloc(n*b->dim,sizeof(*r));
  117927. /* maptype 1 and 2 both use a quantized value vector, but
  117928. different sizes */
  117929. switch(b->maptype){
  117930. case 1:
  117931. /* most of the time, entries%dimensions == 0, but we need to be
  117932. well defined. We define that the possible vales at each
  117933. scalar is values == entries/dim. If entries%dim != 0, we'll
  117934. have 'too few' values (values*dim<entries), which means that
  117935. we'll have 'left over' entries; left over entries use zeroed
  117936. values (and are wasted). So don't generate codebooks like
  117937. that */
  117938. quantvals=_book_maptype1_quantvals(b);
  117939. for(j=0;j<b->entries;j++){
  117940. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  117941. float last=0.f;
  117942. int indexdiv=1;
  117943. for(k=0;k<b->dim;k++){
  117944. int index= (j/indexdiv)%quantvals;
  117945. float val=b->quantlist[index];
  117946. val=fabs(val)*delta+mindel+last;
  117947. if(b->q_sequencep)last=val;
  117948. if(sparsemap)
  117949. r[sparsemap[count]*b->dim+k]=val;
  117950. else
  117951. r[count*b->dim+k]=val;
  117952. indexdiv*=quantvals;
  117953. }
  117954. count++;
  117955. }
  117956. }
  117957. break;
  117958. case 2:
  117959. for(j=0;j<b->entries;j++){
  117960. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  117961. float last=0.f;
  117962. for(k=0;k<b->dim;k++){
  117963. float val=b->quantlist[j*b->dim+k];
  117964. val=fabs(val)*delta+mindel+last;
  117965. if(b->q_sequencep)last=val;
  117966. if(sparsemap)
  117967. r[sparsemap[count]*b->dim+k]=val;
  117968. else
  117969. r[count*b->dim+k]=val;
  117970. }
  117971. count++;
  117972. }
  117973. }
  117974. break;
  117975. }
  117976. return(r);
  117977. }
  117978. return(NULL);
  117979. }
  117980. void vorbis_staticbook_clear(static_codebook *b){
  117981. if(b->allocedp){
  117982. if(b->quantlist)_ogg_free(b->quantlist);
  117983. if(b->lengthlist)_ogg_free(b->lengthlist);
  117984. if(b->nearest_tree){
  117985. _ogg_free(b->nearest_tree->ptr0);
  117986. _ogg_free(b->nearest_tree->ptr1);
  117987. _ogg_free(b->nearest_tree->p);
  117988. _ogg_free(b->nearest_tree->q);
  117989. memset(b->nearest_tree,0,sizeof(*b->nearest_tree));
  117990. _ogg_free(b->nearest_tree);
  117991. }
  117992. if(b->thresh_tree){
  117993. _ogg_free(b->thresh_tree->quantthresh);
  117994. _ogg_free(b->thresh_tree->quantmap);
  117995. memset(b->thresh_tree,0,sizeof(*b->thresh_tree));
  117996. _ogg_free(b->thresh_tree);
  117997. }
  117998. memset(b,0,sizeof(*b));
  117999. }
  118000. }
  118001. void vorbis_staticbook_destroy(static_codebook *b){
  118002. if(b->allocedp){
  118003. vorbis_staticbook_clear(b);
  118004. _ogg_free(b);
  118005. }
  118006. }
  118007. void vorbis_book_clear(codebook *b){
  118008. /* static book is not cleared; we're likely called on the lookup and
  118009. the static codebook belongs to the info struct */
  118010. if(b->valuelist)_ogg_free(b->valuelist);
  118011. if(b->codelist)_ogg_free(b->codelist);
  118012. if(b->dec_index)_ogg_free(b->dec_index);
  118013. if(b->dec_codelengths)_ogg_free(b->dec_codelengths);
  118014. if(b->dec_firsttable)_ogg_free(b->dec_firsttable);
  118015. memset(b,0,sizeof(*b));
  118016. }
  118017. int vorbis_book_init_encode(codebook *c,const static_codebook *s){
  118018. memset(c,0,sizeof(*c));
  118019. c->c=s;
  118020. c->entries=s->entries;
  118021. c->used_entries=s->entries;
  118022. c->dim=s->dim;
  118023. c->codelist=_make_words(s->lengthlist,s->entries,0);
  118024. c->valuelist=_book_unquantize(s,s->entries,NULL);
  118025. return(0);
  118026. }
  118027. static int sort32a(const void *a,const void *b){
  118028. return ( **(ogg_uint32_t **)a>**(ogg_uint32_t **)b)-
  118029. ( **(ogg_uint32_t **)a<**(ogg_uint32_t **)b);
  118030. }
  118031. /* decode codebook arrangement is more heavily optimized than encode */
  118032. int vorbis_book_init_decode(codebook *c,const static_codebook *s){
  118033. int i,j,n=0,tabn;
  118034. int *sortindex;
  118035. memset(c,0,sizeof(*c));
  118036. /* count actually used entries */
  118037. for(i=0;i<s->entries;i++)
  118038. if(s->lengthlist[i]>0)
  118039. n++;
  118040. c->entries=s->entries;
  118041. c->used_entries=n;
  118042. c->dim=s->dim;
  118043. /* two different remappings go on here.
  118044. First, we collapse the likely sparse codebook down only to
  118045. actually represented values/words. This collapsing needs to be
  118046. indexed as map-valueless books are used to encode original entry
  118047. positions as integers.
  118048. Second, we reorder all vectors, including the entry index above,
  118049. by sorted bitreversed codeword to allow treeless decode. */
  118050. {
  118051. /* perform sort */
  118052. ogg_uint32_t *codes=_make_words(s->lengthlist,s->entries,c->used_entries);
  118053. ogg_uint32_t **codep=(ogg_uint32_t**)alloca(sizeof(*codep)*n);
  118054. if(codes==NULL)goto err_out;
  118055. for(i=0;i<n;i++){
  118056. codes[i]=ogg_bitreverse(codes[i]);
  118057. codep[i]=codes+i;
  118058. }
  118059. qsort(codep,n,sizeof(*codep),sort32a);
  118060. sortindex=(int*)alloca(n*sizeof(*sortindex));
  118061. c->codelist=(ogg_uint32_t*)_ogg_malloc(n*sizeof(*c->codelist));
  118062. /* the index is a reverse index */
  118063. for(i=0;i<n;i++){
  118064. int position=codep[i]-codes;
  118065. sortindex[position]=i;
  118066. }
  118067. for(i=0;i<n;i++)
  118068. c->codelist[sortindex[i]]=codes[i];
  118069. _ogg_free(codes);
  118070. }
  118071. c->valuelist=_book_unquantize(s,n,sortindex);
  118072. c->dec_index=(int*)_ogg_malloc(n*sizeof(*c->dec_index));
  118073. for(n=0,i=0;i<s->entries;i++)
  118074. if(s->lengthlist[i]>0)
  118075. c->dec_index[sortindex[n++]]=i;
  118076. c->dec_codelengths=(char*)_ogg_malloc(n*sizeof(*c->dec_codelengths));
  118077. for(n=0,i=0;i<s->entries;i++)
  118078. if(s->lengthlist[i]>0)
  118079. c->dec_codelengths[sortindex[n++]]=s->lengthlist[i];
  118080. c->dec_firsttablen=_ilog(c->used_entries)-4; /* this is magic */
  118081. if(c->dec_firsttablen<5)c->dec_firsttablen=5;
  118082. if(c->dec_firsttablen>8)c->dec_firsttablen=8;
  118083. tabn=1<<c->dec_firsttablen;
  118084. c->dec_firsttable=(ogg_uint32_t*)_ogg_calloc(tabn,sizeof(*c->dec_firsttable));
  118085. c->dec_maxlength=0;
  118086. for(i=0;i<n;i++){
  118087. if(c->dec_maxlength<c->dec_codelengths[i])
  118088. c->dec_maxlength=c->dec_codelengths[i];
  118089. if(c->dec_codelengths[i]<=c->dec_firsttablen){
  118090. ogg_uint32_t orig=ogg_bitreverse(c->codelist[i]);
  118091. for(j=0;j<(1<<(c->dec_firsttablen-c->dec_codelengths[i]));j++)
  118092. c->dec_firsttable[orig|(j<<c->dec_codelengths[i])]=i+1;
  118093. }
  118094. }
  118095. /* now fill in 'unused' entries in the firsttable with hi/lo search
  118096. hints for the non-direct-hits */
  118097. {
  118098. ogg_uint32_t mask=0xfffffffeUL<<(31-c->dec_firsttablen);
  118099. long lo=0,hi=0;
  118100. for(i=0;i<tabn;i++){
  118101. ogg_uint32_t word=i<<(32-c->dec_firsttablen);
  118102. if(c->dec_firsttable[ogg_bitreverse(word)]==0){
  118103. while((lo+1)<n && c->codelist[lo+1]<=word)lo++;
  118104. while( hi<n && word>=(c->codelist[hi]&mask))hi++;
  118105. /* we only actually have 15 bits per hint to play with here.
  118106. In order to overflow gracefully (nothing breaks, efficiency
  118107. just drops), encode as the difference from the extremes. */
  118108. {
  118109. unsigned long loval=lo;
  118110. unsigned long hival=n-hi;
  118111. if(loval>0x7fff)loval=0x7fff;
  118112. if(hival>0x7fff)hival=0x7fff;
  118113. c->dec_firsttable[ogg_bitreverse(word)]=
  118114. 0x80000000UL | (loval<<15) | hival;
  118115. }
  118116. }
  118117. }
  118118. }
  118119. return(0);
  118120. err_out:
  118121. vorbis_book_clear(c);
  118122. return(-1);
  118123. }
  118124. static float _dist(int el,float *ref, float *b,int step){
  118125. int i;
  118126. float acc=0.f;
  118127. for(i=0;i<el;i++){
  118128. float val=(ref[i]-b[i*step]);
  118129. acc+=val*val;
  118130. }
  118131. return(acc);
  118132. }
  118133. int _best(codebook *book, float *a, int step){
  118134. encode_aux_threshmatch *tt=book->c->thresh_tree;
  118135. #if 0
  118136. encode_aux_nearestmatch *nt=book->c->nearest_tree;
  118137. encode_aux_pigeonhole *pt=book->c->pigeon_tree;
  118138. #endif
  118139. int dim=book->dim;
  118140. int k,o;
  118141. /*int savebest=-1;
  118142. float saverr;*/
  118143. /* do we have a threshhold encode hint? */
  118144. if(tt){
  118145. int index=0,i;
  118146. /* find the quant val of each scalar */
  118147. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  118148. i=tt->threshvals>>1;
  118149. if(a[o]<tt->quantthresh[i]){
  118150. for(;i>0;i--)
  118151. if(a[o]>=tt->quantthresh[i-1])
  118152. break;
  118153. }else{
  118154. for(i++;i<tt->threshvals-1;i++)
  118155. if(a[o]<tt->quantthresh[i])break;
  118156. }
  118157. index=(index*tt->quantvals)+tt->quantmap[i];
  118158. }
  118159. /* regular lattices are easy :-) */
  118160. if(book->c->lengthlist[index]>0) /* is this unused? If so, we'll
  118161. use a decision tree after all
  118162. and fall through*/
  118163. return(index);
  118164. }
  118165. #if 0
  118166. /* do we have a pigeonhole encode hint? */
  118167. if(pt){
  118168. const static_codebook *c=book->c;
  118169. int i,besti=-1;
  118170. float best=0.f;
  118171. int entry=0;
  118172. /* dealing with sequentialness is a pain in the ass */
  118173. if(c->q_sequencep){
  118174. int pv;
  118175. long mul=1;
  118176. float qlast=0;
  118177. for(k=0,o=0;k<dim;k++,o+=step){
  118178. pv=(int)((a[o]-qlast-pt->min)/pt->del);
  118179. if(pv<0 || pv>=pt->mapentries)break;
  118180. entry+=pt->pigeonmap[pv]*mul;
  118181. mul*=pt->quantvals;
  118182. qlast+=pv*pt->del+pt->min;
  118183. }
  118184. }else{
  118185. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  118186. int pv=(int)((a[o]-pt->min)/pt->del);
  118187. if(pv<0 || pv>=pt->mapentries)break;
  118188. entry=entry*pt->quantvals+pt->pigeonmap[pv];
  118189. }
  118190. }
  118191. /* must be within the pigeonholable range; if we quant outside (or
  118192. in an entry that we define no list for), brute force it */
  118193. if(k==dim && pt->fitlength[entry]){
  118194. /* search the abbreviated list */
  118195. long *list=pt->fitlist+pt->fitmap[entry];
  118196. for(i=0;i<pt->fitlength[entry];i++){
  118197. float this=_dist(dim,book->valuelist+list[i]*dim,a,step);
  118198. if(besti==-1 || this<best){
  118199. best=this;
  118200. besti=list[i];
  118201. }
  118202. }
  118203. return(besti);
  118204. }
  118205. }
  118206. if(nt){
  118207. /* optimized using the decision tree */
  118208. while(1){
  118209. float c=0.f;
  118210. float *p=book->valuelist+nt->p[ptr];
  118211. float *q=book->valuelist+nt->q[ptr];
  118212. for(k=0,o=0;k<dim;k++,o+=step)
  118213. c+=(p[k]-q[k])*(a[o]-(p[k]+q[k])*.5);
  118214. if(c>0.f) /* in A */
  118215. ptr= -nt->ptr0[ptr];
  118216. else /* in B */
  118217. ptr= -nt->ptr1[ptr];
  118218. if(ptr<=0)break;
  118219. }
  118220. return(-ptr);
  118221. }
  118222. #endif
  118223. /* brute force it! */
  118224. {
  118225. const static_codebook *c=book->c;
  118226. int i,besti=-1;
  118227. float best=0.f;
  118228. float *e=book->valuelist;
  118229. for(i=0;i<book->entries;i++){
  118230. if(c->lengthlist[i]>0){
  118231. float thisx=_dist(dim,e,a,step);
  118232. if(besti==-1 || thisx<best){
  118233. best=thisx;
  118234. besti=i;
  118235. }
  118236. }
  118237. e+=dim;
  118238. }
  118239. /*if(savebest!=-1 && savebest!=besti){
  118240. fprintf(stderr,"brute force/pigeonhole disagreement:\n"
  118241. "original:");
  118242. for(i=0;i<dim*step;i+=step)fprintf(stderr,"%g,",a[i]);
  118243. fprintf(stderr,"\n"
  118244. "pigeonhole (entry %d, err %g):",savebest,saverr);
  118245. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  118246. (book->valuelist+savebest*dim)[i]);
  118247. fprintf(stderr,"\n"
  118248. "bruteforce (entry %d, err %g):",besti,best);
  118249. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  118250. (book->valuelist+besti*dim)[i]);
  118251. fprintf(stderr,"\n");
  118252. }*/
  118253. return(besti);
  118254. }
  118255. }
  118256. long vorbis_book_codeword(codebook *book,int entry){
  118257. if(book->c) /* only use with encode; decode optimizations are
  118258. allowed to break this */
  118259. return book->codelist[entry];
  118260. return -1;
  118261. }
  118262. long vorbis_book_codelen(codebook *book,int entry){
  118263. if(book->c) /* only use with encode; decode optimizations are
  118264. allowed to break this */
  118265. return book->c->lengthlist[entry];
  118266. return -1;
  118267. }
  118268. #ifdef _V_SELFTEST
  118269. /* Unit tests of the dequantizer; this stuff will be OK
  118270. cross-platform, I simply want to be sure that special mapping cases
  118271. actually work properly; a bug could go unnoticed for a while */
  118272. #include <stdio.h>
  118273. /* cases:
  118274. no mapping
  118275. full, explicit mapping
  118276. algorithmic mapping
  118277. nonsequential
  118278. sequential
  118279. */
  118280. static long full_quantlist1[]={0,1,2,3, 4,5,6,7, 8,3,6,1};
  118281. static long partial_quantlist1[]={0,7,2};
  118282. /* no mapping */
  118283. static_codebook test1={
  118284. 4,16,
  118285. NULL,
  118286. 0,
  118287. 0,0,0,0,
  118288. NULL,
  118289. NULL,NULL
  118290. };
  118291. static float *test1_result=NULL;
  118292. /* linear, full mapping, nonsequential */
  118293. static_codebook test2={
  118294. 4,3,
  118295. NULL,
  118296. 2,
  118297. -533200896,1611661312,4,0,
  118298. full_quantlist1,
  118299. NULL,NULL
  118300. };
  118301. static float test2_result[]={-3,-2,-1,0, 1,2,3,4, 5,0,3,-2};
  118302. /* linear, full mapping, sequential */
  118303. static_codebook test3={
  118304. 4,3,
  118305. NULL,
  118306. 2,
  118307. -533200896,1611661312,4,1,
  118308. full_quantlist1,
  118309. NULL,NULL
  118310. };
  118311. static float test3_result[]={-3,-5,-6,-6, 1,3,6,10, 5,5,8,6};
  118312. /* linear, algorithmic mapping, nonsequential */
  118313. static_codebook test4={
  118314. 3,27,
  118315. NULL,
  118316. 1,
  118317. -533200896,1611661312,4,0,
  118318. partial_quantlist1,
  118319. NULL,NULL
  118320. };
  118321. static float test4_result[]={-3,-3,-3, 4,-3,-3, -1,-3,-3,
  118322. -3, 4,-3, 4, 4,-3, -1, 4,-3,
  118323. -3,-1,-3, 4,-1,-3, -1,-1,-3,
  118324. -3,-3, 4, 4,-3, 4, -1,-3, 4,
  118325. -3, 4, 4, 4, 4, 4, -1, 4, 4,
  118326. -3,-1, 4, 4,-1, 4, -1,-1, 4,
  118327. -3,-3,-1, 4,-3,-1, -1,-3,-1,
  118328. -3, 4,-1, 4, 4,-1, -1, 4,-1,
  118329. -3,-1,-1, 4,-1,-1, -1,-1,-1};
  118330. /* linear, algorithmic mapping, sequential */
  118331. static_codebook test5={
  118332. 3,27,
  118333. NULL,
  118334. 1,
  118335. -533200896,1611661312,4,1,
  118336. partial_quantlist1,
  118337. NULL,NULL
  118338. };
  118339. static float test5_result[]={-3,-6,-9, 4, 1,-2, -1,-4,-7,
  118340. -3, 1,-2, 4, 8, 5, -1, 3, 0,
  118341. -3,-4,-7, 4, 3, 0, -1,-2,-5,
  118342. -3,-6,-2, 4, 1, 5, -1,-4, 0,
  118343. -3, 1, 5, 4, 8,12, -1, 3, 7,
  118344. -3,-4, 0, 4, 3, 7, -1,-2, 2,
  118345. -3,-6,-7, 4, 1, 0, -1,-4,-5,
  118346. -3, 1, 0, 4, 8, 7, -1, 3, 2,
  118347. -3,-4,-5, 4, 3, 2, -1,-2,-3};
  118348. void run_test(static_codebook *b,float *comp){
  118349. float *out=_book_unquantize(b,b->entries,NULL);
  118350. int i;
  118351. if(comp){
  118352. if(!out){
  118353. fprintf(stderr,"_book_unquantize incorrectly returned NULL\n");
  118354. exit(1);
  118355. }
  118356. for(i=0;i<b->entries*b->dim;i++)
  118357. if(fabs(out[i]-comp[i])>.0001){
  118358. fprintf(stderr,"disagreement in unquantized and reference data:\n"
  118359. "position %d, %g != %g\n",i,out[i],comp[i]);
  118360. exit(1);
  118361. }
  118362. }else{
  118363. if(out){
  118364. fprintf(stderr,"_book_unquantize returned a value array: \n"
  118365. " correct result should have been NULL\n");
  118366. exit(1);
  118367. }
  118368. }
  118369. }
  118370. int main(){
  118371. /* run the nine dequant tests, and compare to the hand-rolled results */
  118372. fprintf(stderr,"Dequant test 1... ");
  118373. run_test(&test1,test1_result);
  118374. fprintf(stderr,"OK\nDequant test 2... ");
  118375. run_test(&test2,test2_result);
  118376. fprintf(stderr,"OK\nDequant test 3... ");
  118377. run_test(&test3,test3_result);
  118378. fprintf(stderr,"OK\nDequant test 4... ");
  118379. run_test(&test4,test4_result);
  118380. fprintf(stderr,"OK\nDequant test 5... ");
  118381. run_test(&test5,test5_result);
  118382. fprintf(stderr,"OK\n\n");
  118383. return(0);
  118384. }
  118385. #endif
  118386. #endif
  118387. /*** End of inlined file: sharedbook.c ***/
  118388. /*** Start of inlined file: smallft.c ***/
  118389. /* FFT implementation from OggSquish, minus cosine transforms,
  118390. * minus all but radix 2/4 case. In Vorbis we only need this
  118391. * cut-down version.
  118392. *
  118393. * To do more than just power-of-two sized vectors, see the full
  118394. * version I wrote for NetLib.
  118395. *
  118396. * Note that the packing is a little strange; rather than the FFT r/i
  118397. * packing following R_0, I_n, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1,
  118398. * it follows R_0, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1, I_n like the
  118399. * FORTRAN version
  118400. */
  118401. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  118402. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  118403. // tasks..
  118404. #if JUCE_MSVC
  118405. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  118406. #endif
  118407. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  118408. #if JUCE_USE_OGGVORBIS
  118409. #include <stdlib.h>
  118410. #include <string.h>
  118411. #include <math.h>
  118412. static void drfti1(int n, float *wa, int *ifac){
  118413. static int ntryh[4] = { 4,2,3,5 };
  118414. static float tpi = 6.28318530717958648f;
  118415. float arg,argh,argld,fi;
  118416. int ntry=0,i,j=-1;
  118417. int k1, l1, l2, ib;
  118418. int ld, ii, ip, is, nq, nr;
  118419. int ido, ipm, nfm1;
  118420. int nl=n;
  118421. int nf=0;
  118422. L101:
  118423. j++;
  118424. if (j < 4)
  118425. ntry=ntryh[j];
  118426. else
  118427. ntry+=2;
  118428. L104:
  118429. nq=nl/ntry;
  118430. nr=nl-ntry*nq;
  118431. if (nr!=0) goto L101;
  118432. nf++;
  118433. ifac[nf+1]=ntry;
  118434. nl=nq;
  118435. if(ntry!=2)goto L107;
  118436. if(nf==1)goto L107;
  118437. for (i=1;i<nf;i++){
  118438. ib=nf-i+1;
  118439. ifac[ib+1]=ifac[ib];
  118440. }
  118441. ifac[2] = 2;
  118442. L107:
  118443. if(nl!=1)goto L104;
  118444. ifac[0]=n;
  118445. ifac[1]=nf;
  118446. argh=tpi/n;
  118447. is=0;
  118448. nfm1=nf-1;
  118449. l1=1;
  118450. if(nfm1==0)return;
  118451. for (k1=0;k1<nfm1;k1++){
  118452. ip=ifac[k1+2];
  118453. ld=0;
  118454. l2=l1*ip;
  118455. ido=n/l2;
  118456. ipm=ip-1;
  118457. for (j=0;j<ipm;j++){
  118458. ld+=l1;
  118459. i=is;
  118460. argld=(float)ld*argh;
  118461. fi=0.f;
  118462. for (ii=2;ii<ido;ii+=2){
  118463. fi+=1.f;
  118464. arg=fi*argld;
  118465. wa[i++]=cos(arg);
  118466. wa[i++]=sin(arg);
  118467. }
  118468. is+=ido;
  118469. }
  118470. l1=l2;
  118471. }
  118472. }
  118473. static void fdrffti(int n, float *wsave, int *ifac){
  118474. if (n == 1) return;
  118475. drfti1(n, wsave+n, ifac);
  118476. }
  118477. static void dradf2(int ido,int l1,float *cc,float *ch,float *wa1){
  118478. int i,k;
  118479. float ti2,tr2;
  118480. int t0,t1,t2,t3,t4,t5,t6;
  118481. t1=0;
  118482. t0=(t2=l1*ido);
  118483. t3=ido<<1;
  118484. for(k=0;k<l1;k++){
  118485. ch[t1<<1]=cc[t1]+cc[t2];
  118486. ch[(t1<<1)+t3-1]=cc[t1]-cc[t2];
  118487. t1+=ido;
  118488. t2+=ido;
  118489. }
  118490. if(ido<2)return;
  118491. if(ido==2)goto L105;
  118492. t1=0;
  118493. t2=t0;
  118494. for(k=0;k<l1;k++){
  118495. t3=t2;
  118496. t4=(t1<<1)+(ido<<1);
  118497. t5=t1;
  118498. t6=t1+t1;
  118499. for(i=2;i<ido;i+=2){
  118500. t3+=2;
  118501. t4-=2;
  118502. t5+=2;
  118503. t6+=2;
  118504. tr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  118505. ti2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  118506. ch[t6]=cc[t5]+ti2;
  118507. ch[t4]=ti2-cc[t5];
  118508. ch[t6-1]=cc[t5-1]+tr2;
  118509. ch[t4-1]=cc[t5-1]-tr2;
  118510. }
  118511. t1+=ido;
  118512. t2+=ido;
  118513. }
  118514. if(ido%2==1)return;
  118515. L105:
  118516. t3=(t2=(t1=ido)-1);
  118517. t2+=t0;
  118518. for(k=0;k<l1;k++){
  118519. ch[t1]=-cc[t2];
  118520. ch[t1-1]=cc[t3];
  118521. t1+=ido<<1;
  118522. t2+=ido;
  118523. t3+=ido;
  118524. }
  118525. }
  118526. static void dradf4(int ido,int l1,float *cc,float *ch,float *wa1,
  118527. float *wa2,float *wa3){
  118528. static float hsqt2 = .70710678118654752f;
  118529. int i,k,t0,t1,t2,t3,t4,t5,t6;
  118530. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  118531. t0=l1*ido;
  118532. t1=t0;
  118533. t4=t1<<1;
  118534. t2=t1+(t1<<1);
  118535. t3=0;
  118536. for(k=0;k<l1;k++){
  118537. tr1=cc[t1]+cc[t2];
  118538. tr2=cc[t3]+cc[t4];
  118539. ch[t5=t3<<2]=tr1+tr2;
  118540. ch[(ido<<2)+t5-1]=tr2-tr1;
  118541. ch[(t5+=(ido<<1))-1]=cc[t3]-cc[t4];
  118542. ch[t5]=cc[t2]-cc[t1];
  118543. t1+=ido;
  118544. t2+=ido;
  118545. t3+=ido;
  118546. t4+=ido;
  118547. }
  118548. if(ido<2)return;
  118549. if(ido==2)goto L105;
  118550. t1=0;
  118551. for(k=0;k<l1;k++){
  118552. t2=t1;
  118553. t4=t1<<2;
  118554. t5=(t6=ido<<1)+t4;
  118555. for(i=2;i<ido;i+=2){
  118556. t3=(t2+=2);
  118557. t4+=2;
  118558. t5-=2;
  118559. t3+=t0;
  118560. cr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  118561. ci2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  118562. t3+=t0;
  118563. cr3=wa2[i-2]*cc[t3-1]+wa2[i-1]*cc[t3];
  118564. ci3=wa2[i-2]*cc[t3]-wa2[i-1]*cc[t3-1];
  118565. t3+=t0;
  118566. cr4=wa3[i-2]*cc[t3-1]+wa3[i-1]*cc[t3];
  118567. ci4=wa3[i-2]*cc[t3]-wa3[i-1]*cc[t3-1];
  118568. tr1=cr2+cr4;
  118569. tr4=cr4-cr2;
  118570. ti1=ci2+ci4;
  118571. ti4=ci2-ci4;
  118572. ti2=cc[t2]+ci3;
  118573. ti3=cc[t2]-ci3;
  118574. tr2=cc[t2-1]+cr3;
  118575. tr3=cc[t2-1]-cr3;
  118576. ch[t4-1]=tr1+tr2;
  118577. ch[t4]=ti1+ti2;
  118578. ch[t5-1]=tr3-ti4;
  118579. ch[t5]=tr4-ti3;
  118580. ch[t4+t6-1]=ti4+tr3;
  118581. ch[t4+t6]=tr4+ti3;
  118582. ch[t5+t6-1]=tr2-tr1;
  118583. ch[t5+t6]=ti1-ti2;
  118584. }
  118585. t1+=ido;
  118586. }
  118587. if(ido&1)return;
  118588. L105:
  118589. t2=(t1=t0+ido-1)+(t0<<1);
  118590. t3=ido<<2;
  118591. t4=ido;
  118592. t5=ido<<1;
  118593. t6=ido;
  118594. for(k=0;k<l1;k++){
  118595. ti1=-hsqt2*(cc[t1]+cc[t2]);
  118596. tr1=hsqt2*(cc[t1]-cc[t2]);
  118597. ch[t4-1]=tr1+cc[t6-1];
  118598. ch[t4+t5-1]=cc[t6-1]-tr1;
  118599. ch[t4]=ti1-cc[t1+t0];
  118600. ch[t4+t5]=ti1+cc[t1+t0];
  118601. t1+=ido;
  118602. t2+=ido;
  118603. t4+=t3;
  118604. t6+=ido;
  118605. }
  118606. }
  118607. static void dradfg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  118608. float *c2,float *ch,float *ch2,float *wa){
  118609. static float tpi=6.283185307179586f;
  118610. int idij,ipph,i,j,k,l,ic,ik,is;
  118611. int t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  118612. float dc2,ai1,ai2,ar1,ar2,ds2;
  118613. int nbd;
  118614. float dcp,arg,dsp,ar1h,ar2h;
  118615. int idp2,ipp2;
  118616. arg=tpi/(float)ip;
  118617. dcp=cos(arg);
  118618. dsp=sin(arg);
  118619. ipph=(ip+1)>>1;
  118620. ipp2=ip;
  118621. idp2=ido;
  118622. nbd=(ido-1)>>1;
  118623. t0=l1*ido;
  118624. t10=ip*ido;
  118625. if(ido==1)goto L119;
  118626. for(ik=0;ik<idl1;ik++)ch2[ik]=c2[ik];
  118627. t1=0;
  118628. for(j=1;j<ip;j++){
  118629. t1+=t0;
  118630. t2=t1;
  118631. for(k=0;k<l1;k++){
  118632. ch[t2]=c1[t2];
  118633. t2+=ido;
  118634. }
  118635. }
  118636. is=-ido;
  118637. t1=0;
  118638. if(nbd>l1){
  118639. for(j=1;j<ip;j++){
  118640. t1+=t0;
  118641. is+=ido;
  118642. t2= -ido+t1;
  118643. for(k=0;k<l1;k++){
  118644. idij=is-1;
  118645. t2+=ido;
  118646. t3=t2;
  118647. for(i=2;i<ido;i+=2){
  118648. idij+=2;
  118649. t3+=2;
  118650. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  118651. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  118652. }
  118653. }
  118654. }
  118655. }else{
  118656. for(j=1;j<ip;j++){
  118657. is+=ido;
  118658. idij=is-1;
  118659. t1+=t0;
  118660. t2=t1;
  118661. for(i=2;i<ido;i+=2){
  118662. idij+=2;
  118663. t2+=2;
  118664. t3=t2;
  118665. for(k=0;k<l1;k++){
  118666. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  118667. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  118668. t3+=ido;
  118669. }
  118670. }
  118671. }
  118672. }
  118673. t1=0;
  118674. t2=ipp2*t0;
  118675. if(nbd<l1){
  118676. for(j=1;j<ipph;j++){
  118677. t1+=t0;
  118678. t2-=t0;
  118679. t3=t1;
  118680. t4=t2;
  118681. for(i=2;i<ido;i+=2){
  118682. t3+=2;
  118683. t4+=2;
  118684. t5=t3-ido;
  118685. t6=t4-ido;
  118686. for(k=0;k<l1;k++){
  118687. t5+=ido;
  118688. t6+=ido;
  118689. c1[t5-1]=ch[t5-1]+ch[t6-1];
  118690. c1[t6-1]=ch[t5]-ch[t6];
  118691. c1[t5]=ch[t5]+ch[t6];
  118692. c1[t6]=ch[t6-1]-ch[t5-1];
  118693. }
  118694. }
  118695. }
  118696. }else{
  118697. for(j=1;j<ipph;j++){
  118698. t1+=t0;
  118699. t2-=t0;
  118700. t3=t1;
  118701. t4=t2;
  118702. for(k=0;k<l1;k++){
  118703. t5=t3;
  118704. t6=t4;
  118705. for(i=2;i<ido;i+=2){
  118706. t5+=2;
  118707. t6+=2;
  118708. c1[t5-1]=ch[t5-1]+ch[t6-1];
  118709. c1[t6-1]=ch[t5]-ch[t6];
  118710. c1[t5]=ch[t5]+ch[t6];
  118711. c1[t6]=ch[t6-1]-ch[t5-1];
  118712. }
  118713. t3+=ido;
  118714. t4+=ido;
  118715. }
  118716. }
  118717. }
  118718. L119:
  118719. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  118720. t1=0;
  118721. t2=ipp2*idl1;
  118722. for(j=1;j<ipph;j++){
  118723. t1+=t0;
  118724. t2-=t0;
  118725. t3=t1-ido;
  118726. t4=t2-ido;
  118727. for(k=0;k<l1;k++){
  118728. t3+=ido;
  118729. t4+=ido;
  118730. c1[t3]=ch[t3]+ch[t4];
  118731. c1[t4]=ch[t4]-ch[t3];
  118732. }
  118733. }
  118734. ar1=1.f;
  118735. ai1=0.f;
  118736. t1=0;
  118737. t2=ipp2*idl1;
  118738. t3=(ip-1)*idl1;
  118739. for(l=1;l<ipph;l++){
  118740. t1+=idl1;
  118741. t2-=idl1;
  118742. ar1h=dcp*ar1-dsp*ai1;
  118743. ai1=dcp*ai1+dsp*ar1;
  118744. ar1=ar1h;
  118745. t4=t1;
  118746. t5=t2;
  118747. t6=t3;
  118748. t7=idl1;
  118749. for(ik=0;ik<idl1;ik++){
  118750. ch2[t4++]=c2[ik]+ar1*c2[t7++];
  118751. ch2[t5++]=ai1*c2[t6++];
  118752. }
  118753. dc2=ar1;
  118754. ds2=ai1;
  118755. ar2=ar1;
  118756. ai2=ai1;
  118757. t4=idl1;
  118758. t5=(ipp2-1)*idl1;
  118759. for(j=2;j<ipph;j++){
  118760. t4+=idl1;
  118761. t5-=idl1;
  118762. ar2h=dc2*ar2-ds2*ai2;
  118763. ai2=dc2*ai2+ds2*ar2;
  118764. ar2=ar2h;
  118765. t6=t1;
  118766. t7=t2;
  118767. t8=t4;
  118768. t9=t5;
  118769. for(ik=0;ik<idl1;ik++){
  118770. ch2[t6++]+=ar2*c2[t8++];
  118771. ch2[t7++]+=ai2*c2[t9++];
  118772. }
  118773. }
  118774. }
  118775. t1=0;
  118776. for(j=1;j<ipph;j++){
  118777. t1+=idl1;
  118778. t2=t1;
  118779. for(ik=0;ik<idl1;ik++)ch2[ik]+=c2[t2++];
  118780. }
  118781. if(ido<l1)goto L132;
  118782. t1=0;
  118783. t2=0;
  118784. for(k=0;k<l1;k++){
  118785. t3=t1;
  118786. t4=t2;
  118787. for(i=0;i<ido;i++)cc[t4++]=ch[t3++];
  118788. t1+=ido;
  118789. t2+=t10;
  118790. }
  118791. goto L135;
  118792. L132:
  118793. for(i=0;i<ido;i++){
  118794. t1=i;
  118795. t2=i;
  118796. for(k=0;k<l1;k++){
  118797. cc[t2]=ch[t1];
  118798. t1+=ido;
  118799. t2+=t10;
  118800. }
  118801. }
  118802. L135:
  118803. t1=0;
  118804. t2=ido<<1;
  118805. t3=0;
  118806. t4=ipp2*t0;
  118807. for(j=1;j<ipph;j++){
  118808. t1+=t2;
  118809. t3+=t0;
  118810. t4-=t0;
  118811. t5=t1;
  118812. t6=t3;
  118813. t7=t4;
  118814. for(k=0;k<l1;k++){
  118815. cc[t5-1]=ch[t6];
  118816. cc[t5]=ch[t7];
  118817. t5+=t10;
  118818. t6+=ido;
  118819. t7+=ido;
  118820. }
  118821. }
  118822. if(ido==1)return;
  118823. if(nbd<l1)goto L141;
  118824. t1=-ido;
  118825. t3=0;
  118826. t4=0;
  118827. t5=ipp2*t0;
  118828. for(j=1;j<ipph;j++){
  118829. t1+=t2;
  118830. t3+=t2;
  118831. t4+=t0;
  118832. t5-=t0;
  118833. t6=t1;
  118834. t7=t3;
  118835. t8=t4;
  118836. t9=t5;
  118837. for(k=0;k<l1;k++){
  118838. for(i=2;i<ido;i+=2){
  118839. ic=idp2-i;
  118840. cc[i+t7-1]=ch[i+t8-1]+ch[i+t9-1];
  118841. cc[ic+t6-1]=ch[i+t8-1]-ch[i+t9-1];
  118842. cc[i+t7]=ch[i+t8]+ch[i+t9];
  118843. cc[ic+t6]=ch[i+t9]-ch[i+t8];
  118844. }
  118845. t6+=t10;
  118846. t7+=t10;
  118847. t8+=ido;
  118848. t9+=ido;
  118849. }
  118850. }
  118851. return;
  118852. L141:
  118853. t1=-ido;
  118854. t3=0;
  118855. t4=0;
  118856. t5=ipp2*t0;
  118857. for(j=1;j<ipph;j++){
  118858. t1+=t2;
  118859. t3+=t2;
  118860. t4+=t0;
  118861. t5-=t0;
  118862. for(i=2;i<ido;i+=2){
  118863. t6=idp2+t1-i;
  118864. t7=i+t3;
  118865. t8=i+t4;
  118866. t9=i+t5;
  118867. for(k=0;k<l1;k++){
  118868. cc[t7-1]=ch[t8-1]+ch[t9-1];
  118869. cc[t6-1]=ch[t8-1]-ch[t9-1];
  118870. cc[t7]=ch[t8]+ch[t9];
  118871. cc[t6]=ch[t9]-ch[t8];
  118872. t6+=t10;
  118873. t7+=t10;
  118874. t8+=ido;
  118875. t9+=ido;
  118876. }
  118877. }
  118878. }
  118879. }
  118880. static void drftf1(int n,float *c,float *ch,float *wa,int *ifac){
  118881. int i,k1,l1,l2;
  118882. int na,kh,nf;
  118883. int ip,iw,ido,idl1,ix2,ix3;
  118884. nf=ifac[1];
  118885. na=1;
  118886. l2=n;
  118887. iw=n;
  118888. for(k1=0;k1<nf;k1++){
  118889. kh=nf-k1;
  118890. ip=ifac[kh+1];
  118891. l1=l2/ip;
  118892. ido=n/l2;
  118893. idl1=ido*l1;
  118894. iw-=(ip-1)*ido;
  118895. na=1-na;
  118896. if(ip!=4)goto L102;
  118897. ix2=iw+ido;
  118898. ix3=ix2+ido;
  118899. if(na!=0)
  118900. dradf4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  118901. else
  118902. dradf4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  118903. goto L110;
  118904. L102:
  118905. if(ip!=2)goto L104;
  118906. if(na!=0)goto L103;
  118907. dradf2(ido,l1,c,ch,wa+iw-1);
  118908. goto L110;
  118909. L103:
  118910. dradf2(ido,l1,ch,c,wa+iw-1);
  118911. goto L110;
  118912. L104:
  118913. if(ido==1)na=1-na;
  118914. if(na!=0)goto L109;
  118915. dradfg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  118916. na=1;
  118917. goto L110;
  118918. L109:
  118919. dradfg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  118920. na=0;
  118921. L110:
  118922. l2=l1;
  118923. }
  118924. if(na==1)return;
  118925. for(i=0;i<n;i++)c[i]=ch[i];
  118926. }
  118927. static void dradb2(int ido,int l1,float *cc,float *ch,float *wa1){
  118928. int i,k,t0,t1,t2,t3,t4,t5,t6;
  118929. float ti2,tr2;
  118930. t0=l1*ido;
  118931. t1=0;
  118932. t2=0;
  118933. t3=(ido<<1)-1;
  118934. for(k=0;k<l1;k++){
  118935. ch[t1]=cc[t2]+cc[t3+t2];
  118936. ch[t1+t0]=cc[t2]-cc[t3+t2];
  118937. t2=(t1+=ido)<<1;
  118938. }
  118939. if(ido<2)return;
  118940. if(ido==2)goto L105;
  118941. t1=0;
  118942. t2=0;
  118943. for(k=0;k<l1;k++){
  118944. t3=t1;
  118945. t5=(t4=t2)+(ido<<1);
  118946. t6=t0+t1;
  118947. for(i=2;i<ido;i+=2){
  118948. t3+=2;
  118949. t4+=2;
  118950. t5-=2;
  118951. t6+=2;
  118952. ch[t3-1]=cc[t4-1]+cc[t5-1];
  118953. tr2=cc[t4-1]-cc[t5-1];
  118954. ch[t3]=cc[t4]-cc[t5];
  118955. ti2=cc[t4]+cc[t5];
  118956. ch[t6-1]=wa1[i-2]*tr2-wa1[i-1]*ti2;
  118957. ch[t6]=wa1[i-2]*ti2+wa1[i-1]*tr2;
  118958. }
  118959. t2=(t1+=ido)<<1;
  118960. }
  118961. if(ido%2==1)return;
  118962. L105:
  118963. t1=ido-1;
  118964. t2=ido-1;
  118965. for(k=0;k<l1;k++){
  118966. ch[t1]=cc[t2]+cc[t2];
  118967. ch[t1+t0]=-(cc[t2+1]+cc[t2+1]);
  118968. t1+=ido;
  118969. t2+=ido<<1;
  118970. }
  118971. }
  118972. static void dradb3(int ido,int l1,float *cc,float *ch,float *wa1,
  118973. float *wa2){
  118974. static float taur = -.5f;
  118975. static float taui = .8660254037844386f;
  118976. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  118977. float ci2,ci3,di2,di3,cr2,cr3,dr2,dr3,ti2,tr2;
  118978. t0=l1*ido;
  118979. t1=0;
  118980. t2=t0<<1;
  118981. t3=ido<<1;
  118982. t4=ido+(ido<<1);
  118983. t5=0;
  118984. for(k=0;k<l1;k++){
  118985. tr2=cc[t3-1]+cc[t3-1];
  118986. cr2=cc[t5]+(taur*tr2);
  118987. ch[t1]=cc[t5]+tr2;
  118988. ci3=taui*(cc[t3]+cc[t3]);
  118989. ch[t1+t0]=cr2-ci3;
  118990. ch[t1+t2]=cr2+ci3;
  118991. t1+=ido;
  118992. t3+=t4;
  118993. t5+=t4;
  118994. }
  118995. if(ido==1)return;
  118996. t1=0;
  118997. t3=ido<<1;
  118998. for(k=0;k<l1;k++){
  118999. t7=t1+(t1<<1);
  119000. t6=(t5=t7+t3);
  119001. t8=t1;
  119002. t10=(t9=t1+t0)+t0;
  119003. for(i=2;i<ido;i+=2){
  119004. t5+=2;
  119005. t6-=2;
  119006. t7+=2;
  119007. t8+=2;
  119008. t9+=2;
  119009. t10+=2;
  119010. tr2=cc[t5-1]+cc[t6-1];
  119011. cr2=cc[t7-1]+(taur*tr2);
  119012. ch[t8-1]=cc[t7-1]+tr2;
  119013. ti2=cc[t5]-cc[t6];
  119014. ci2=cc[t7]+(taur*ti2);
  119015. ch[t8]=cc[t7]+ti2;
  119016. cr3=taui*(cc[t5-1]-cc[t6-1]);
  119017. ci3=taui*(cc[t5]+cc[t6]);
  119018. dr2=cr2-ci3;
  119019. dr3=cr2+ci3;
  119020. di2=ci2+cr3;
  119021. di3=ci2-cr3;
  119022. ch[t9-1]=wa1[i-2]*dr2-wa1[i-1]*di2;
  119023. ch[t9]=wa1[i-2]*di2+wa1[i-1]*dr2;
  119024. ch[t10-1]=wa2[i-2]*dr3-wa2[i-1]*di3;
  119025. ch[t10]=wa2[i-2]*di3+wa2[i-1]*dr3;
  119026. }
  119027. t1+=ido;
  119028. }
  119029. }
  119030. static void dradb4(int ido,int l1,float *cc,float *ch,float *wa1,
  119031. float *wa2,float *wa3){
  119032. static float sqrt2=1.414213562373095f;
  119033. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8;
  119034. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  119035. t0=l1*ido;
  119036. t1=0;
  119037. t2=ido<<2;
  119038. t3=0;
  119039. t6=ido<<1;
  119040. for(k=0;k<l1;k++){
  119041. t4=t3+t6;
  119042. t5=t1;
  119043. tr3=cc[t4-1]+cc[t4-1];
  119044. tr4=cc[t4]+cc[t4];
  119045. tr1=cc[t3]-cc[(t4+=t6)-1];
  119046. tr2=cc[t3]+cc[t4-1];
  119047. ch[t5]=tr2+tr3;
  119048. ch[t5+=t0]=tr1-tr4;
  119049. ch[t5+=t0]=tr2-tr3;
  119050. ch[t5+=t0]=tr1+tr4;
  119051. t1+=ido;
  119052. t3+=t2;
  119053. }
  119054. if(ido<2)return;
  119055. if(ido==2)goto L105;
  119056. t1=0;
  119057. for(k=0;k<l1;k++){
  119058. t5=(t4=(t3=(t2=t1<<2)+t6))+t6;
  119059. t7=t1;
  119060. for(i=2;i<ido;i+=2){
  119061. t2+=2;
  119062. t3+=2;
  119063. t4-=2;
  119064. t5-=2;
  119065. t7+=2;
  119066. ti1=cc[t2]+cc[t5];
  119067. ti2=cc[t2]-cc[t5];
  119068. ti3=cc[t3]-cc[t4];
  119069. tr4=cc[t3]+cc[t4];
  119070. tr1=cc[t2-1]-cc[t5-1];
  119071. tr2=cc[t2-1]+cc[t5-1];
  119072. ti4=cc[t3-1]-cc[t4-1];
  119073. tr3=cc[t3-1]+cc[t4-1];
  119074. ch[t7-1]=tr2+tr3;
  119075. cr3=tr2-tr3;
  119076. ch[t7]=ti2+ti3;
  119077. ci3=ti2-ti3;
  119078. cr2=tr1-tr4;
  119079. cr4=tr1+tr4;
  119080. ci2=ti1+ti4;
  119081. ci4=ti1-ti4;
  119082. ch[(t8=t7+t0)-1]=wa1[i-2]*cr2-wa1[i-1]*ci2;
  119083. ch[t8]=wa1[i-2]*ci2+wa1[i-1]*cr2;
  119084. ch[(t8+=t0)-1]=wa2[i-2]*cr3-wa2[i-1]*ci3;
  119085. ch[t8]=wa2[i-2]*ci3+wa2[i-1]*cr3;
  119086. ch[(t8+=t0)-1]=wa3[i-2]*cr4-wa3[i-1]*ci4;
  119087. ch[t8]=wa3[i-2]*ci4+wa3[i-1]*cr4;
  119088. }
  119089. t1+=ido;
  119090. }
  119091. if(ido%2 == 1)return;
  119092. L105:
  119093. t1=ido;
  119094. t2=ido<<2;
  119095. t3=ido-1;
  119096. t4=ido+(ido<<1);
  119097. for(k=0;k<l1;k++){
  119098. t5=t3;
  119099. ti1=cc[t1]+cc[t4];
  119100. ti2=cc[t4]-cc[t1];
  119101. tr1=cc[t1-1]-cc[t4-1];
  119102. tr2=cc[t1-1]+cc[t4-1];
  119103. ch[t5]=tr2+tr2;
  119104. ch[t5+=t0]=sqrt2*(tr1-ti1);
  119105. ch[t5+=t0]=ti2+ti2;
  119106. ch[t5+=t0]=-sqrt2*(tr1+ti1);
  119107. t3+=ido;
  119108. t1+=t2;
  119109. t4+=t2;
  119110. }
  119111. }
  119112. static void dradbg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  119113. float *c2,float *ch,float *ch2,float *wa){
  119114. static float tpi=6.283185307179586f;
  119115. int idij,ipph,i,j,k,l,ik,is,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,
  119116. t11,t12;
  119117. float dc2,ai1,ai2,ar1,ar2,ds2;
  119118. int nbd;
  119119. float dcp,arg,dsp,ar1h,ar2h;
  119120. int ipp2;
  119121. t10=ip*ido;
  119122. t0=l1*ido;
  119123. arg=tpi/(float)ip;
  119124. dcp=cos(arg);
  119125. dsp=sin(arg);
  119126. nbd=(ido-1)>>1;
  119127. ipp2=ip;
  119128. ipph=(ip+1)>>1;
  119129. if(ido<l1)goto L103;
  119130. t1=0;
  119131. t2=0;
  119132. for(k=0;k<l1;k++){
  119133. t3=t1;
  119134. t4=t2;
  119135. for(i=0;i<ido;i++){
  119136. ch[t3]=cc[t4];
  119137. t3++;
  119138. t4++;
  119139. }
  119140. t1+=ido;
  119141. t2+=t10;
  119142. }
  119143. goto L106;
  119144. L103:
  119145. t1=0;
  119146. for(i=0;i<ido;i++){
  119147. t2=t1;
  119148. t3=t1;
  119149. for(k=0;k<l1;k++){
  119150. ch[t2]=cc[t3];
  119151. t2+=ido;
  119152. t3+=t10;
  119153. }
  119154. t1++;
  119155. }
  119156. L106:
  119157. t1=0;
  119158. t2=ipp2*t0;
  119159. t7=(t5=ido<<1);
  119160. for(j=1;j<ipph;j++){
  119161. t1+=t0;
  119162. t2-=t0;
  119163. t3=t1;
  119164. t4=t2;
  119165. t6=t5;
  119166. for(k=0;k<l1;k++){
  119167. ch[t3]=cc[t6-1]+cc[t6-1];
  119168. ch[t4]=cc[t6]+cc[t6];
  119169. t3+=ido;
  119170. t4+=ido;
  119171. t6+=t10;
  119172. }
  119173. t5+=t7;
  119174. }
  119175. if (ido == 1)goto L116;
  119176. if(nbd<l1)goto L112;
  119177. t1=0;
  119178. t2=ipp2*t0;
  119179. t7=0;
  119180. for(j=1;j<ipph;j++){
  119181. t1+=t0;
  119182. t2-=t0;
  119183. t3=t1;
  119184. t4=t2;
  119185. t7+=(ido<<1);
  119186. t8=t7;
  119187. for(k=0;k<l1;k++){
  119188. t5=t3;
  119189. t6=t4;
  119190. t9=t8;
  119191. t11=t8;
  119192. for(i=2;i<ido;i+=2){
  119193. t5+=2;
  119194. t6+=2;
  119195. t9+=2;
  119196. t11-=2;
  119197. ch[t5-1]=cc[t9-1]+cc[t11-1];
  119198. ch[t6-1]=cc[t9-1]-cc[t11-1];
  119199. ch[t5]=cc[t9]-cc[t11];
  119200. ch[t6]=cc[t9]+cc[t11];
  119201. }
  119202. t3+=ido;
  119203. t4+=ido;
  119204. t8+=t10;
  119205. }
  119206. }
  119207. goto L116;
  119208. L112:
  119209. t1=0;
  119210. t2=ipp2*t0;
  119211. t7=0;
  119212. for(j=1;j<ipph;j++){
  119213. t1+=t0;
  119214. t2-=t0;
  119215. t3=t1;
  119216. t4=t2;
  119217. t7+=(ido<<1);
  119218. t8=t7;
  119219. t9=t7;
  119220. for(i=2;i<ido;i+=2){
  119221. t3+=2;
  119222. t4+=2;
  119223. t8+=2;
  119224. t9-=2;
  119225. t5=t3;
  119226. t6=t4;
  119227. t11=t8;
  119228. t12=t9;
  119229. for(k=0;k<l1;k++){
  119230. ch[t5-1]=cc[t11-1]+cc[t12-1];
  119231. ch[t6-1]=cc[t11-1]-cc[t12-1];
  119232. ch[t5]=cc[t11]-cc[t12];
  119233. ch[t6]=cc[t11]+cc[t12];
  119234. t5+=ido;
  119235. t6+=ido;
  119236. t11+=t10;
  119237. t12+=t10;
  119238. }
  119239. }
  119240. }
  119241. L116:
  119242. ar1=1.f;
  119243. ai1=0.f;
  119244. t1=0;
  119245. t9=(t2=ipp2*idl1);
  119246. t3=(ip-1)*idl1;
  119247. for(l=1;l<ipph;l++){
  119248. t1+=idl1;
  119249. t2-=idl1;
  119250. ar1h=dcp*ar1-dsp*ai1;
  119251. ai1=dcp*ai1+dsp*ar1;
  119252. ar1=ar1h;
  119253. t4=t1;
  119254. t5=t2;
  119255. t6=0;
  119256. t7=idl1;
  119257. t8=t3;
  119258. for(ik=0;ik<idl1;ik++){
  119259. c2[t4++]=ch2[t6++]+ar1*ch2[t7++];
  119260. c2[t5++]=ai1*ch2[t8++];
  119261. }
  119262. dc2=ar1;
  119263. ds2=ai1;
  119264. ar2=ar1;
  119265. ai2=ai1;
  119266. t6=idl1;
  119267. t7=t9-idl1;
  119268. for(j=2;j<ipph;j++){
  119269. t6+=idl1;
  119270. t7-=idl1;
  119271. ar2h=dc2*ar2-ds2*ai2;
  119272. ai2=dc2*ai2+ds2*ar2;
  119273. ar2=ar2h;
  119274. t4=t1;
  119275. t5=t2;
  119276. t11=t6;
  119277. t12=t7;
  119278. for(ik=0;ik<idl1;ik++){
  119279. c2[t4++]+=ar2*ch2[t11++];
  119280. c2[t5++]+=ai2*ch2[t12++];
  119281. }
  119282. }
  119283. }
  119284. t1=0;
  119285. for(j=1;j<ipph;j++){
  119286. t1+=idl1;
  119287. t2=t1;
  119288. for(ik=0;ik<idl1;ik++)ch2[ik]+=ch2[t2++];
  119289. }
  119290. t1=0;
  119291. t2=ipp2*t0;
  119292. for(j=1;j<ipph;j++){
  119293. t1+=t0;
  119294. t2-=t0;
  119295. t3=t1;
  119296. t4=t2;
  119297. for(k=0;k<l1;k++){
  119298. ch[t3]=c1[t3]-c1[t4];
  119299. ch[t4]=c1[t3]+c1[t4];
  119300. t3+=ido;
  119301. t4+=ido;
  119302. }
  119303. }
  119304. if(ido==1)goto L132;
  119305. if(nbd<l1)goto L128;
  119306. t1=0;
  119307. t2=ipp2*t0;
  119308. for(j=1;j<ipph;j++){
  119309. t1+=t0;
  119310. t2-=t0;
  119311. t3=t1;
  119312. t4=t2;
  119313. for(k=0;k<l1;k++){
  119314. t5=t3;
  119315. t6=t4;
  119316. for(i=2;i<ido;i+=2){
  119317. t5+=2;
  119318. t6+=2;
  119319. ch[t5-1]=c1[t5-1]-c1[t6];
  119320. ch[t6-1]=c1[t5-1]+c1[t6];
  119321. ch[t5]=c1[t5]+c1[t6-1];
  119322. ch[t6]=c1[t5]-c1[t6-1];
  119323. }
  119324. t3+=ido;
  119325. t4+=ido;
  119326. }
  119327. }
  119328. goto L132;
  119329. L128:
  119330. t1=0;
  119331. t2=ipp2*t0;
  119332. for(j=1;j<ipph;j++){
  119333. t1+=t0;
  119334. t2-=t0;
  119335. t3=t1;
  119336. t4=t2;
  119337. for(i=2;i<ido;i+=2){
  119338. t3+=2;
  119339. t4+=2;
  119340. t5=t3;
  119341. t6=t4;
  119342. for(k=0;k<l1;k++){
  119343. ch[t5-1]=c1[t5-1]-c1[t6];
  119344. ch[t6-1]=c1[t5-1]+c1[t6];
  119345. ch[t5]=c1[t5]+c1[t6-1];
  119346. ch[t6]=c1[t5]-c1[t6-1];
  119347. t5+=ido;
  119348. t6+=ido;
  119349. }
  119350. }
  119351. }
  119352. L132:
  119353. if(ido==1)return;
  119354. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  119355. t1=0;
  119356. for(j=1;j<ip;j++){
  119357. t2=(t1+=t0);
  119358. for(k=0;k<l1;k++){
  119359. c1[t2]=ch[t2];
  119360. t2+=ido;
  119361. }
  119362. }
  119363. if(nbd>l1)goto L139;
  119364. is= -ido-1;
  119365. t1=0;
  119366. for(j=1;j<ip;j++){
  119367. is+=ido;
  119368. t1+=t0;
  119369. idij=is;
  119370. t2=t1;
  119371. for(i=2;i<ido;i+=2){
  119372. t2+=2;
  119373. idij+=2;
  119374. t3=t2;
  119375. for(k=0;k<l1;k++){
  119376. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  119377. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  119378. t3+=ido;
  119379. }
  119380. }
  119381. }
  119382. return;
  119383. L139:
  119384. is= -ido-1;
  119385. t1=0;
  119386. for(j=1;j<ip;j++){
  119387. is+=ido;
  119388. t1+=t0;
  119389. t2=t1;
  119390. for(k=0;k<l1;k++){
  119391. idij=is;
  119392. t3=t2;
  119393. for(i=2;i<ido;i+=2){
  119394. idij+=2;
  119395. t3+=2;
  119396. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  119397. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  119398. }
  119399. t2+=ido;
  119400. }
  119401. }
  119402. }
  119403. static void drftb1(int n, float *c, float *ch, float *wa, int *ifac){
  119404. int i,k1,l1,l2;
  119405. int na;
  119406. int nf,ip,iw,ix2,ix3,ido,idl1;
  119407. nf=ifac[1];
  119408. na=0;
  119409. l1=1;
  119410. iw=1;
  119411. for(k1=0;k1<nf;k1++){
  119412. ip=ifac[k1 + 2];
  119413. l2=ip*l1;
  119414. ido=n/l2;
  119415. idl1=ido*l1;
  119416. if(ip!=4)goto L103;
  119417. ix2=iw+ido;
  119418. ix3=ix2+ido;
  119419. if(na!=0)
  119420. dradb4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  119421. else
  119422. dradb4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  119423. na=1-na;
  119424. goto L115;
  119425. L103:
  119426. if(ip!=2)goto L106;
  119427. if(na!=0)
  119428. dradb2(ido,l1,ch,c,wa+iw-1);
  119429. else
  119430. dradb2(ido,l1,c,ch,wa+iw-1);
  119431. na=1-na;
  119432. goto L115;
  119433. L106:
  119434. if(ip!=3)goto L109;
  119435. ix2=iw+ido;
  119436. if(na!=0)
  119437. dradb3(ido,l1,ch,c,wa+iw-1,wa+ix2-1);
  119438. else
  119439. dradb3(ido,l1,c,ch,wa+iw-1,wa+ix2-1);
  119440. na=1-na;
  119441. goto L115;
  119442. L109:
  119443. /* The radix five case can be translated later..... */
  119444. /* if(ip!=5)goto L112;
  119445. ix2=iw+ido;
  119446. ix3=ix2+ido;
  119447. ix4=ix3+ido;
  119448. if(na!=0)
  119449. dradb5(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  119450. else
  119451. dradb5(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  119452. na=1-na;
  119453. goto L115;
  119454. L112:*/
  119455. if(na!=0)
  119456. dradbg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  119457. else
  119458. dradbg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  119459. if(ido==1)na=1-na;
  119460. L115:
  119461. l1=l2;
  119462. iw+=(ip-1)*ido;
  119463. }
  119464. if(na==0)return;
  119465. for(i=0;i<n;i++)c[i]=ch[i];
  119466. }
  119467. void drft_forward(drft_lookup *l,float *data){
  119468. if(l->n==1)return;
  119469. drftf1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  119470. }
  119471. void drft_backward(drft_lookup *l,float *data){
  119472. if (l->n==1)return;
  119473. drftb1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  119474. }
  119475. void drft_init(drft_lookup *l,int n){
  119476. l->n=n;
  119477. l->trigcache=(float*)_ogg_calloc(3*n,sizeof(*l->trigcache));
  119478. l->splitcache=(int*)_ogg_calloc(32,sizeof(*l->splitcache));
  119479. fdrffti(n, l->trigcache, l->splitcache);
  119480. }
  119481. void drft_clear(drft_lookup *l){
  119482. if(l){
  119483. if(l->trigcache)_ogg_free(l->trigcache);
  119484. if(l->splitcache)_ogg_free(l->splitcache);
  119485. memset(l,0,sizeof(*l));
  119486. }
  119487. }
  119488. #endif
  119489. /*** End of inlined file: smallft.c ***/
  119490. /*** Start of inlined file: synthesis.c ***/
  119491. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  119492. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  119493. // tasks..
  119494. #if JUCE_MSVC
  119495. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  119496. #endif
  119497. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  119498. #if JUCE_USE_OGGVORBIS
  119499. #include <stdio.h>
  119500. int vorbis_synthesis(vorbis_block *vb,ogg_packet *op){
  119501. vorbis_dsp_state *vd=vb->vd;
  119502. private_state *b=(private_state*)vd->backend_state;
  119503. vorbis_info *vi=vd->vi;
  119504. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  119505. oggpack_buffer *opb=&vb->opb;
  119506. int type,mode,i;
  119507. /* first things first. Make sure decode is ready */
  119508. _vorbis_block_ripcord(vb);
  119509. oggpack_readinit(opb,op->packet,op->bytes);
  119510. /* Check the packet type */
  119511. if(oggpack_read(opb,1)!=0){
  119512. /* Oops. This is not an audio data packet */
  119513. return(OV_ENOTAUDIO);
  119514. }
  119515. /* read our mode and pre/post windowsize */
  119516. mode=oggpack_read(opb,b->modebits);
  119517. if(mode==-1)return(OV_EBADPACKET);
  119518. vb->mode=mode;
  119519. vb->W=ci->mode_param[mode]->blockflag;
  119520. if(vb->W){
  119521. /* this doesn;t get mapped through mode selection as it's used
  119522. only for window selection */
  119523. vb->lW=oggpack_read(opb,1);
  119524. vb->nW=oggpack_read(opb,1);
  119525. if(vb->nW==-1) return(OV_EBADPACKET);
  119526. }else{
  119527. vb->lW=0;
  119528. vb->nW=0;
  119529. }
  119530. /* more setup */
  119531. vb->granulepos=op->granulepos;
  119532. vb->sequence=op->packetno;
  119533. vb->eofflag=op->e_o_s;
  119534. /* alloc pcm passback storage */
  119535. vb->pcmend=ci->blocksizes[vb->W];
  119536. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  119537. for(i=0;i<vi->channels;i++)
  119538. vb->pcm[i]=(float*)_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  119539. /* unpack_header enforces range checking */
  119540. type=ci->map_type[ci->mode_param[mode]->mapping];
  119541. return(_mapping_P[type]->inverse(vb,ci->map_param[ci->mode_param[mode]->
  119542. mapping]));
  119543. }
  119544. /* used to track pcm position without actually performing decode.
  119545. Useful for sequential 'fast forward' */
  119546. int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op){
  119547. vorbis_dsp_state *vd=vb->vd;
  119548. private_state *b=(private_state*)vd->backend_state;
  119549. vorbis_info *vi=vd->vi;
  119550. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  119551. oggpack_buffer *opb=&vb->opb;
  119552. int mode;
  119553. /* first things first. Make sure decode is ready */
  119554. _vorbis_block_ripcord(vb);
  119555. oggpack_readinit(opb,op->packet,op->bytes);
  119556. /* Check the packet type */
  119557. if(oggpack_read(opb,1)!=0){
  119558. /* Oops. This is not an audio data packet */
  119559. return(OV_ENOTAUDIO);
  119560. }
  119561. /* read our mode and pre/post windowsize */
  119562. mode=oggpack_read(opb,b->modebits);
  119563. if(mode==-1)return(OV_EBADPACKET);
  119564. vb->mode=mode;
  119565. vb->W=ci->mode_param[mode]->blockflag;
  119566. if(vb->W){
  119567. vb->lW=oggpack_read(opb,1);
  119568. vb->nW=oggpack_read(opb,1);
  119569. if(vb->nW==-1) return(OV_EBADPACKET);
  119570. }else{
  119571. vb->lW=0;
  119572. vb->nW=0;
  119573. }
  119574. /* more setup */
  119575. vb->granulepos=op->granulepos;
  119576. vb->sequence=op->packetno;
  119577. vb->eofflag=op->e_o_s;
  119578. /* no pcm */
  119579. vb->pcmend=0;
  119580. vb->pcm=NULL;
  119581. return(0);
  119582. }
  119583. long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op){
  119584. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  119585. oggpack_buffer opb;
  119586. int mode;
  119587. oggpack_readinit(&opb,op->packet,op->bytes);
  119588. /* Check the packet type */
  119589. if(oggpack_read(&opb,1)!=0){
  119590. /* Oops. This is not an audio data packet */
  119591. return(OV_ENOTAUDIO);
  119592. }
  119593. {
  119594. int modebits=0;
  119595. int v=ci->modes;
  119596. while(v>1){
  119597. modebits++;
  119598. v>>=1;
  119599. }
  119600. /* read our mode and pre/post windowsize */
  119601. mode=oggpack_read(&opb,modebits);
  119602. }
  119603. if(mode==-1)return(OV_EBADPACKET);
  119604. return(ci->blocksizes[ci->mode_param[mode]->blockflag]);
  119605. }
  119606. int vorbis_synthesis_halfrate(vorbis_info *vi,int flag){
  119607. /* set / clear half-sample-rate mode */
  119608. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  119609. /* right now, our MDCT can't handle < 64 sample windows. */
  119610. if(ci->blocksizes[0]<=64 && flag)return -1;
  119611. ci->halfrate_flag=(flag?1:0);
  119612. return 0;
  119613. }
  119614. int vorbis_synthesis_halfrate_p(vorbis_info *vi){
  119615. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  119616. return ci->halfrate_flag;
  119617. }
  119618. #endif
  119619. /*** End of inlined file: synthesis.c ***/
  119620. /*** Start of inlined file: vorbisenc.c ***/
  119621. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  119622. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  119623. // tasks..
  119624. #if JUCE_MSVC
  119625. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  119626. #endif
  119627. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  119628. #if JUCE_USE_OGGVORBIS
  119629. #include <stdlib.h>
  119630. #include <string.h>
  119631. #include <math.h>
  119632. /* careful with this; it's using static array sizing to make managing
  119633. all the modes a little less annoying. If we use a residue backend
  119634. with > 12 partition types, or a different division of iteration,
  119635. this needs to be updated. */
  119636. typedef struct {
  119637. static_codebook *books[12][3];
  119638. } static_bookblock;
  119639. typedef struct {
  119640. int res_type;
  119641. int limit_type; /* 0 lowpass limited, 1 point stereo limited */
  119642. vorbis_info_residue0 *res;
  119643. static_codebook *book_aux;
  119644. static_codebook *book_aux_managed;
  119645. static_bookblock *books_base;
  119646. static_bookblock *books_base_managed;
  119647. } vorbis_residue_template;
  119648. typedef struct {
  119649. vorbis_info_mapping0 *map;
  119650. vorbis_residue_template *res;
  119651. } vorbis_mapping_template;
  119652. typedef struct vp_adjblock{
  119653. int block[P_BANDS];
  119654. } vp_adjblock;
  119655. typedef struct {
  119656. int data[NOISE_COMPAND_LEVELS];
  119657. } compandblock;
  119658. /* high level configuration information for setting things up
  119659. step-by-step with the detailed vorbis_encode_ctl interface.
  119660. There's a fair amount of redundancy such that interactive setup
  119661. does not directly deal with any vorbis_info or codec_setup_info
  119662. initialization; it's all stored (until full init) in this highlevel
  119663. setup, then flushed out to the real codec setup structs later. */
  119664. typedef struct {
  119665. int att[P_NOISECURVES];
  119666. float boost;
  119667. float decay;
  119668. } att3;
  119669. typedef struct { int data[P_NOISECURVES]; } adj3;
  119670. typedef struct {
  119671. int pre[PACKETBLOBS];
  119672. int post[PACKETBLOBS];
  119673. float kHz[PACKETBLOBS];
  119674. float lowpasskHz[PACKETBLOBS];
  119675. } adj_stereo;
  119676. typedef struct {
  119677. int lo;
  119678. int hi;
  119679. int fixed;
  119680. } noiseguard;
  119681. typedef struct {
  119682. int data[P_NOISECURVES][17];
  119683. } noise3;
  119684. typedef struct {
  119685. int mappings;
  119686. double *rate_mapping;
  119687. double *quality_mapping;
  119688. int coupling_restriction;
  119689. long samplerate_min_restriction;
  119690. long samplerate_max_restriction;
  119691. int *blocksize_short;
  119692. int *blocksize_long;
  119693. att3 *psy_tone_masteratt;
  119694. int *psy_tone_0dB;
  119695. int *psy_tone_dBsuppress;
  119696. vp_adjblock *psy_tone_adj_impulse;
  119697. vp_adjblock *psy_tone_adj_long;
  119698. vp_adjblock *psy_tone_adj_other;
  119699. noiseguard *psy_noiseguards;
  119700. noise3 *psy_noise_bias_impulse;
  119701. noise3 *psy_noise_bias_padding;
  119702. noise3 *psy_noise_bias_trans;
  119703. noise3 *psy_noise_bias_long;
  119704. int *psy_noise_dBsuppress;
  119705. compandblock *psy_noise_compand;
  119706. double *psy_noise_compand_short_mapping;
  119707. double *psy_noise_compand_long_mapping;
  119708. int *psy_noise_normal_start[2];
  119709. int *psy_noise_normal_partition[2];
  119710. double *psy_noise_normal_thresh;
  119711. int *psy_ath_float;
  119712. int *psy_ath_abs;
  119713. double *psy_lowpass;
  119714. vorbis_info_psy_global *global_params;
  119715. double *global_mapping;
  119716. adj_stereo *stereo_modes;
  119717. static_codebook ***floor_books;
  119718. vorbis_info_floor1 *floor_params;
  119719. int *floor_short_mapping;
  119720. int *floor_long_mapping;
  119721. vorbis_mapping_template *maps;
  119722. } ve_setup_data_template;
  119723. /* a few static coder conventions */
  119724. static vorbis_info_mode _mode_template[2]={
  119725. {0,0,0,0},
  119726. {1,0,0,1}
  119727. };
  119728. static vorbis_info_mapping0 _map_nominal[2]={
  119729. {1, {0,0}, {0}, {0}, 1,{0},{1}},
  119730. {1, {0,0}, {1}, {1}, 1,{0},{1}}
  119731. };
  119732. /*** Start of inlined file: setup_44.h ***/
  119733. /*** Start of inlined file: floor_all.h ***/
  119734. /*** Start of inlined file: floor_books.h ***/
  119735. static long _huff_lengthlist_line_256x7_0sub1[] = {
  119736. 0, 2, 3, 3, 3, 3, 4, 3, 4,
  119737. };
  119738. static static_codebook _huff_book_line_256x7_0sub1 = {
  119739. 1, 9,
  119740. _huff_lengthlist_line_256x7_0sub1,
  119741. 0, 0, 0, 0, 0,
  119742. NULL,
  119743. NULL,
  119744. NULL,
  119745. NULL,
  119746. 0
  119747. };
  119748. static long _huff_lengthlist_line_256x7_0sub2[] = {
  119749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 4, 3, 5, 3,
  119750. 6, 3, 6, 4, 6, 4, 7, 5, 7,
  119751. };
  119752. static static_codebook _huff_book_line_256x7_0sub2 = {
  119753. 1, 25,
  119754. _huff_lengthlist_line_256x7_0sub2,
  119755. 0, 0, 0, 0, 0,
  119756. NULL,
  119757. NULL,
  119758. NULL,
  119759. NULL,
  119760. 0
  119761. };
  119762. static long _huff_lengthlist_line_256x7_0sub3[] = {
  119763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 2, 5, 3, 5, 3,
  119765. 6, 3, 6, 4, 7, 6, 7, 8, 7, 9, 8, 9, 9, 9,10, 9,
  119766. 11,13,11,13,10,10,13,13,13,13,13,13,12,12,12,12,
  119767. };
  119768. static static_codebook _huff_book_line_256x7_0sub3 = {
  119769. 1, 64,
  119770. _huff_lengthlist_line_256x7_0sub3,
  119771. 0, 0, 0, 0, 0,
  119772. NULL,
  119773. NULL,
  119774. NULL,
  119775. NULL,
  119776. 0
  119777. };
  119778. static long _huff_lengthlist_line_256x7_1sub1[] = {
  119779. 0, 3, 3, 3, 3, 2, 4, 3, 4,
  119780. };
  119781. static static_codebook _huff_book_line_256x7_1sub1 = {
  119782. 1, 9,
  119783. _huff_lengthlist_line_256x7_1sub1,
  119784. 0, 0, 0, 0, 0,
  119785. NULL,
  119786. NULL,
  119787. NULL,
  119788. NULL,
  119789. 0
  119790. };
  119791. static long _huff_lengthlist_line_256x7_1sub2[] = {
  119792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 3, 4, 3, 4, 4,
  119793. 5, 4, 6, 5, 6, 7, 6, 8, 8,
  119794. };
  119795. static static_codebook _huff_book_line_256x7_1sub2 = {
  119796. 1, 25,
  119797. _huff_lengthlist_line_256x7_1sub2,
  119798. 0, 0, 0, 0, 0,
  119799. NULL,
  119800. NULL,
  119801. NULL,
  119802. NULL,
  119803. 0
  119804. };
  119805. static long _huff_lengthlist_line_256x7_1sub3[] = {
  119806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 4, 3, 6, 3, 7,
  119808. 3, 8, 5, 8, 6, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  119809. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7,
  119810. };
  119811. static static_codebook _huff_book_line_256x7_1sub3 = {
  119812. 1, 64,
  119813. _huff_lengthlist_line_256x7_1sub3,
  119814. 0, 0, 0, 0, 0,
  119815. NULL,
  119816. NULL,
  119817. NULL,
  119818. NULL,
  119819. 0
  119820. };
  119821. static long _huff_lengthlist_line_256x7_class0[] = {
  119822. 7, 5, 5, 9, 9, 6, 6, 9,12, 8, 7, 8,11, 8, 9,15,
  119823. 6, 3, 3, 7, 7, 4, 3, 6, 9, 6, 5, 6, 8, 6, 8,15,
  119824. 8, 5, 5, 9, 8, 5, 4, 6,10, 7, 5, 5,11, 8, 7,15,
  119825. 14,15,13,13,13,13, 8,11,15,10, 7, 6,11, 9,10,15,
  119826. };
  119827. static static_codebook _huff_book_line_256x7_class0 = {
  119828. 1, 64,
  119829. _huff_lengthlist_line_256x7_class0,
  119830. 0, 0, 0, 0, 0,
  119831. NULL,
  119832. NULL,
  119833. NULL,
  119834. NULL,
  119835. 0
  119836. };
  119837. static long _huff_lengthlist_line_256x7_class1[] = {
  119838. 5, 6, 8,15, 6, 9,10,15,10,11,12,15,15,15,15,15,
  119839. 4, 6, 7,15, 6, 7, 8,15, 9, 8, 9,15,15,15,15,15,
  119840. 6, 8, 9,15, 7, 7, 8,15,10, 9,10,15,15,15,15,15,
  119841. 15,13,15,15,15,10,11,15,15,13,13,15,15,15,15,15,
  119842. 4, 6, 7,15, 6, 8, 9,15,10,10,12,15,15,15,15,15,
  119843. 2, 5, 6,15, 5, 6, 7,15, 8, 6, 7,15,15,15,15,15,
  119844. 5, 6, 8,15, 5, 6, 7,15, 9, 6, 7,15,15,15,15,15,
  119845. 14,12,13,15,12,10,11,15,15,15,15,15,15,15,15,15,
  119846. 7, 8, 9,15, 9,10,10,15,15,14,14,15,15,15,15,15,
  119847. 5, 6, 7,15, 7, 8, 9,15,12, 9,10,15,15,15,15,15,
  119848. 7, 7, 9,15, 7, 7, 8,15,12, 8, 9,15,15,15,15,15,
  119849. 13,13,14,15,12,11,12,15,15,15,15,15,15,15,15,15,
  119850. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  119851. 13,13,13,15,15,15,15,15,15,15,15,15,15,15,15,15,
  119852. 15,12,13,15,15,12,13,15,15,14,15,15,15,15,15,15,
  119853. 15,15,15,15,15,15,13,15,15,15,15,15,15,15,15,15,
  119854. };
  119855. static static_codebook _huff_book_line_256x7_class1 = {
  119856. 1, 256,
  119857. _huff_lengthlist_line_256x7_class1,
  119858. 0, 0, 0, 0, 0,
  119859. NULL,
  119860. NULL,
  119861. NULL,
  119862. NULL,
  119863. 0
  119864. };
  119865. static long _huff_lengthlist_line_512x17_0sub0[] = {
  119866. 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  119867. 5, 6, 5, 6, 6, 6, 6, 5, 6, 6, 7, 6, 7, 6, 7, 6,
  119868. 7, 6, 8, 7, 8, 7, 8, 7, 8, 7, 8, 7, 9, 7, 9, 7,
  119869. 9, 7, 9, 8, 9, 8,10, 8,10, 8,10, 7,10, 6,10, 8,
  119870. 10, 8,11, 7,10, 7,11, 8,11,11,12,12,11,11,12,11,
  119871. 13,11,13,11,13,12,15,12,13,13,14,14,14,14,14,15,
  119872. 15,15,16,14,17,19,19,18,18,18,18,18,18,18,18,18,
  119873. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  119874. };
  119875. static static_codebook _huff_book_line_512x17_0sub0 = {
  119876. 1, 128,
  119877. _huff_lengthlist_line_512x17_0sub0,
  119878. 0, 0, 0, 0, 0,
  119879. NULL,
  119880. NULL,
  119881. NULL,
  119882. NULL,
  119883. 0
  119884. };
  119885. static long _huff_lengthlist_line_512x17_1sub0[] = {
  119886. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  119887. 6, 5, 6, 6, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 8, 7,
  119888. };
  119889. static static_codebook _huff_book_line_512x17_1sub0 = {
  119890. 1, 32,
  119891. _huff_lengthlist_line_512x17_1sub0,
  119892. 0, 0, 0, 0, 0,
  119893. NULL,
  119894. NULL,
  119895. NULL,
  119896. NULL,
  119897. 0
  119898. };
  119899. static long _huff_lengthlist_line_512x17_1sub1[] = {
  119900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119902. 4, 3, 5, 3, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 6, 5,
  119903. 6, 5, 7, 5, 8, 6, 8, 6, 8, 6, 8, 6, 8, 7, 9, 7,
  119904. 9, 7,11, 9,11,11,12,11,14,12,14,16,14,16,13,16,
  119905. 14,16,12,15,13,16,14,16,13,14,12,15,13,15,13,13,
  119906. 13,15,12,14,14,15,13,15,12,15,15,15,15,15,15,15,
  119907. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  119908. };
  119909. static static_codebook _huff_book_line_512x17_1sub1 = {
  119910. 1, 128,
  119911. _huff_lengthlist_line_512x17_1sub1,
  119912. 0, 0, 0, 0, 0,
  119913. NULL,
  119914. NULL,
  119915. NULL,
  119916. NULL,
  119917. 0
  119918. };
  119919. static long _huff_lengthlist_line_512x17_2sub1[] = {
  119920. 0, 4, 5, 4, 4, 4, 5, 4, 4, 4, 5, 4, 5, 4, 5, 3,
  119921. 5, 3,
  119922. };
  119923. static static_codebook _huff_book_line_512x17_2sub1 = {
  119924. 1, 18,
  119925. _huff_lengthlist_line_512x17_2sub1,
  119926. 0, 0, 0, 0, 0,
  119927. NULL,
  119928. NULL,
  119929. NULL,
  119930. NULL,
  119931. 0
  119932. };
  119933. static long _huff_lengthlist_line_512x17_2sub2[] = {
  119934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119935. 0, 0, 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 6, 4, 6, 5,
  119936. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 7, 8, 7, 9, 7,
  119937. 9, 8,
  119938. };
  119939. static static_codebook _huff_book_line_512x17_2sub2 = {
  119940. 1, 50,
  119941. _huff_lengthlist_line_512x17_2sub2,
  119942. 0, 0, 0, 0, 0,
  119943. NULL,
  119944. NULL,
  119945. NULL,
  119946. NULL,
  119947. 0
  119948. };
  119949. static long _huff_lengthlist_line_512x17_2sub3[] = {
  119950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119953. 0, 0, 3, 3, 3, 3, 4, 3, 4, 4, 5, 5, 6, 6, 7, 7,
  119954. 7, 8, 8,11, 8, 9, 9, 9,10,11,11,11, 9,10,10,11,
  119955. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  119956. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  119957. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  119958. };
  119959. static static_codebook _huff_book_line_512x17_2sub3 = {
  119960. 1, 128,
  119961. _huff_lengthlist_line_512x17_2sub3,
  119962. 0, 0, 0, 0, 0,
  119963. NULL,
  119964. NULL,
  119965. NULL,
  119966. NULL,
  119967. 0
  119968. };
  119969. static long _huff_lengthlist_line_512x17_3sub1[] = {
  119970. 0, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, 4, 4, 5, 4, 5,
  119971. 5, 5,
  119972. };
  119973. static static_codebook _huff_book_line_512x17_3sub1 = {
  119974. 1, 18,
  119975. _huff_lengthlist_line_512x17_3sub1,
  119976. 0, 0, 0, 0, 0,
  119977. NULL,
  119978. NULL,
  119979. NULL,
  119980. NULL,
  119981. 0
  119982. };
  119983. static long _huff_lengthlist_line_512x17_3sub2[] = {
  119984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119985. 0, 0, 2, 3, 3, 4, 3, 5, 4, 6, 4, 6, 5, 7, 6, 7,
  119986. 6, 8, 6, 8, 7, 9, 8,10, 8,12, 9,13,10,15,10,15,
  119987. 11,14,
  119988. };
  119989. static static_codebook _huff_book_line_512x17_3sub2 = {
  119990. 1, 50,
  119991. _huff_lengthlist_line_512x17_3sub2,
  119992. 0, 0, 0, 0, 0,
  119993. NULL,
  119994. NULL,
  119995. NULL,
  119996. NULL,
  119997. 0
  119998. };
  119999. static long _huff_lengthlist_line_512x17_3sub3[] = {
  120000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120003. 0, 0, 4, 8, 4, 8, 4, 8, 4, 8, 5, 8, 5, 8, 6, 8,
  120004. 4, 8, 4, 8, 5, 8, 5, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120005. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120006. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120007. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120008. };
  120009. static static_codebook _huff_book_line_512x17_3sub3 = {
  120010. 1, 128,
  120011. _huff_lengthlist_line_512x17_3sub3,
  120012. 0, 0, 0, 0, 0,
  120013. NULL,
  120014. NULL,
  120015. NULL,
  120016. NULL,
  120017. 0
  120018. };
  120019. static long _huff_lengthlist_line_512x17_class1[] = {
  120020. 1, 2, 3, 6, 5, 4, 7, 7,
  120021. };
  120022. static static_codebook _huff_book_line_512x17_class1 = {
  120023. 1, 8,
  120024. _huff_lengthlist_line_512x17_class1,
  120025. 0, 0, 0, 0, 0,
  120026. NULL,
  120027. NULL,
  120028. NULL,
  120029. NULL,
  120030. 0
  120031. };
  120032. static long _huff_lengthlist_line_512x17_class2[] = {
  120033. 3, 3, 3,14, 5, 4, 4,11, 8, 6, 6,10,17,12,11,17,
  120034. 6, 5, 5,15, 5, 3, 4,11, 8, 5, 5, 8,16, 9,10,14,
  120035. 10, 8, 9,17, 8, 6, 6,13,10, 7, 7,10,16,11,13,14,
  120036. 17,17,17,17,17,16,16,16,16,15,16,16,16,16,16,16,
  120037. };
  120038. static static_codebook _huff_book_line_512x17_class2 = {
  120039. 1, 64,
  120040. _huff_lengthlist_line_512x17_class2,
  120041. 0, 0, 0, 0, 0,
  120042. NULL,
  120043. NULL,
  120044. NULL,
  120045. NULL,
  120046. 0
  120047. };
  120048. static long _huff_lengthlist_line_512x17_class3[] = {
  120049. 2, 4, 6,17, 4, 5, 7,17, 8, 7,10,17,17,17,17,17,
  120050. 3, 4, 6,15, 3, 3, 6,15, 7, 6, 9,17,17,17,17,17,
  120051. 6, 8,10,17, 6, 6, 8,16, 9, 8,10,17,17,15,16,17,
  120052. 17,17,17,17,12,15,15,16,12,15,15,16,16,16,16,16,
  120053. };
  120054. static static_codebook _huff_book_line_512x17_class3 = {
  120055. 1, 64,
  120056. _huff_lengthlist_line_512x17_class3,
  120057. 0, 0, 0, 0, 0,
  120058. NULL,
  120059. NULL,
  120060. NULL,
  120061. NULL,
  120062. 0
  120063. };
  120064. static long _huff_lengthlist_line_128x4_class0[] = {
  120065. 7, 7, 7,11, 6, 6, 7,11, 7, 6, 6,10,12,10,10,13,
  120066. 7, 7, 8,11, 7, 7, 7,11, 7, 6, 7,10,11,10,10,13,
  120067. 10,10, 9,12, 9, 9, 9,11, 8, 8, 8,11,13,11,10,14,
  120068. 15,15,14,15,15,14,13,14,15,12,12,17,17,17,17,17,
  120069. 7, 7, 6, 9, 6, 6, 6, 9, 7, 6, 6, 8,11,11,10,12,
  120070. 7, 7, 7, 9, 7, 6, 6, 9, 7, 6, 6, 9,13,10,10,11,
  120071. 10, 9, 8,10, 9, 8, 8,10, 8, 8, 7, 9,13,12,10,11,
  120072. 17,14,14,13,15,14,12,13,17,13,12,15,17,17,14,17,
  120073. 7, 6, 6, 7, 6, 6, 5, 7, 6, 6, 6, 6,11, 9, 9, 9,
  120074. 7, 7, 6, 7, 7, 6, 6, 7, 6, 6, 6, 6,10, 9, 8, 9,
  120075. 10, 9, 8, 8, 9, 8, 7, 8, 8, 7, 6, 8,11,10, 9,10,
  120076. 17,17,12,15,15,15,12,14,14,14,10,12,15,13,12,13,
  120077. 11,10, 8,10,11,10, 8, 8,10, 9, 7, 7,10, 9, 9,11,
  120078. 11,11, 9,10,11,10, 8, 9,10, 8, 6, 8,10, 9, 9,11,
  120079. 14,13,10,12,12,11,10,10, 8, 7, 8,10,10,11,11,12,
  120080. 17,17,15,17,17,17,17,17,17,13,12,17,17,17,14,17,
  120081. };
  120082. static static_codebook _huff_book_line_128x4_class0 = {
  120083. 1, 256,
  120084. _huff_lengthlist_line_128x4_class0,
  120085. 0, 0, 0, 0, 0,
  120086. NULL,
  120087. NULL,
  120088. NULL,
  120089. NULL,
  120090. 0
  120091. };
  120092. static long _huff_lengthlist_line_128x4_0sub0[] = {
  120093. 2, 2, 2, 2,
  120094. };
  120095. static static_codebook _huff_book_line_128x4_0sub0 = {
  120096. 1, 4,
  120097. _huff_lengthlist_line_128x4_0sub0,
  120098. 0, 0, 0, 0, 0,
  120099. NULL,
  120100. NULL,
  120101. NULL,
  120102. NULL,
  120103. 0
  120104. };
  120105. static long _huff_lengthlist_line_128x4_0sub1[] = {
  120106. 0, 0, 0, 0, 3, 2, 3, 2, 3, 3,
  120107. };
  120108. static static_codebook _huff_book_line_128x4_0sub1 = {
  120109. 1, 10,
  120110. _huff_lengthlist_line_128x4_0sub1,
  120111. 0, 0, 0, 0, 0,
  120112. NULL,
  120113. NULL,
  120114. NULL,
  120115. NULL,
  120116. 0
  120117. };
  120118. static long _huff_lengthlist_line_128x4_0sub2[] = {
  120119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 4, 3, 4, 3,
  120120. 4, 4, 5, 4, 5, 4, 6, 5, 6,
  120121. };
  120122. static static_codebook _huff_book_line_128x4_0sub2 = {
  120123. 1, 25,
  120124. _huff_lengthlist_line_128x4_0sub2,
  120125. 0, 0, 0, 0, 0,
  120126. NULL,
  120127. NULL,
  120128. NULL,
  120129. NULL,
  120130. 0
  120131. };
  120132. static long _huff_lengthlist_line_128x4_0sub3[] = {
  120133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  120135. 5, 4, 6, 5, 6, 5, 7, 6, 6, 7, 7, 9, 9,11,11,16,
  120136. 11,14,10,11,11,13,16,15,15,15,15,15,15,15,15,15,
  120137. };
  120138. static static_codebook _huff_book_line_128x4_0sub3 = {
  120139. 1, 64,
  120140. _huff_lengthlist_line_128x4_0sub3,
  120141. 0, 0, 0, 0, 0,
  120142. NULL,
  120143. NULL,
  120144. NULL,
  120145. NULL,
  120146. 0
  120147. };
  120148. static long _huff_lengthlist_line_256x4_class0[] = {
  120149. 6, 7, 7,12, 6, 6, 7,12, 7, 6, 6,10,15,12,11,13,
  120150. 7, 7, 8,13, 7, 7, 8,12, 7, 7, 7,11,12,12,11,13,
  120151. 10, 9, 9,11, 9, 9, 9,10,10, 8, 8,12,14,12,12,14,
  120152. 11,11,12,14,11,12,11,15,15,12,13,15,15,15,15,15,
  120153. 6, 6, 7,10, 6, 6, 6,11, 7, 6, 6, 9,14,12,11,13,
  120154. 7, 7, 7,10, 6, 6, 7, 9, 7, 7, 6,10,13,12,10,12,
  120155. 9, 9, 9,11, 9, 9, 8, 9, 9, 8, 8,10,13,12,10,12,
  120156. 12,12,11,13,12,12,11,12,15,13,12,15,15,15,14,14,
  120157. 6, 6, 6, 8, 6, 6, 5, 6, 7, 7, 6, 5,11,10, 9, 8,
  120158. 7, 6, 6, 7, 6, 6, 5, 6, 7, 7, 6, 6,11,10, 9, 8,
  120159. 8, 8, 8, 9, 8, 8, 7, 8, 8, 8, 6, 7,11,10, 9, 9,
  120160. 14,11,10,14,14,11,10,15,13,11, 9,11,15,12,12,11,
  120161. 11, 9, 8, 8,10, 9, 8, 9,11,10, 9, 8,12,11,12,11,
  120162. 13,10, 8, 9,11,10, 8, 9,10, 9, 8, 9,10, 8,12,12,
  120163. 15,11,10,10,13,11,10,10, 8, 8, 7,12,10, 9,11,12,
  120164. 15,12,11,15,13,11,11,15,12,14,11,13,15,15,13,13,
  120165. };
  120166. static static_codebook _huff_book_line_256x4_class0 = {
  120167. 1, 256,
  120168. _huff_lengthlist_line_256x4_class0,
  120169. 0, 0, 0, 0, 0,
  120170. NULL,
  120171. NULL,
  120172. NULL,
  120173. NULL,
  120174. 0
  120175. };
  120176. static long _huff_lengthlist_line_256x4_0sub0[] = {
  120177. 2, 2, 2, 2,
  120178. };
  120179. static static_codebook _huff_book_line_256x4_0sub0 = {
  120180. 1, 4,
  120181. _huff_lengthlist_line_256x4_0sub0,
  120182. 0, 0, 0, 0, 0,
  120183. NULL,
  120184. NULL,
  120185. NULL,
  120186. NULL,
  120187. 0
  120188. };
  120189. static long _huff_lengthlist_line_256x4_0sub1[] = {
  120190. 0, 0, 0, 0, 2, 2, 3, 3, 3, 3,
  120191. };
  120192. static static_codebook _huff_book_line_256x4_0sub1 = {
  120193. 1, 10,
  120194. _huff_lengthlist_line_256x4_0sub1,
  120195. 0, 0, 0, 0, 0,
  120196. NULL,
  120197. NULL,
  120198. NULL,
  120199. NULL,
  120200. 0
  120201. };
  120202. static long _huff_lengthlist_line_256x4_0sub2[] = {
  120203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 3, 4, 3, 4, 3,
  120204. 5, 3, 5, 4, 5, 4, 6, 4, 6,
  120205. };
  120206. static static_codebook _huff_book_line_256x4_0sub2 = {
  120207. 1, 25,
  120208. _huff_lengthlist_line_256x4_0sub2,
  120209. 0, 0, 0, 0, 0,
  120210. NULL,
  120211. NULL,
  120212. NULL,
  120213. NULL,
  120214. 0
  120215. };
  120216. static long _huff_lengthlist_line_256x4_0sub3[] = {
  120217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  120219. 6, 4, 7, 4, 7, 5, 7, 6, 7, 6, 7, 8,10,13,13,13,
  120220. 13,13,13,13,13,13,13,13,13,13,13,12,12,12,12,12,
  120221. };
  120222. static static_codebook _huff_book_line_256x4_0sub3 = {
  120223. 1, 64,
  120224. _huff_lengthlist_line_256x4_0sub3,
  120225. 0, 0, 0, 0, 0,
  120226. NULL,
  120227. NULL,
  120228. NULL,
  120229. NULL,
  120230. 0
  120231. };
  120232. static long _huff_lengthlist_line_128x7_class0[] = {
  120233. 10, 7, 8,13, 9, 6, 7,11,10, 8, 8,12,17,17,17,17,
  120234. 7, 5, 5, 9, 6, 4, 4, 8, 8, 5, 5, 8,16,14,13,16,
  120235. 7, 5, 5, 7, 6, 3, 3, 5, 8, 5, 4, 7,14,12,12,15,
  120236. 10, 7, 8, 9, 7, 5, 5, 6, 9, 6, 5, 5,15,12, 9,10,
  120237. };
  120238. static static_codebook _huff_book_line_128x7_class0 = {
  120239. 1, 64,
  120240. _huff_lengthlist_line_128x7_class0,
  120241. 0, 0, 0, 0, 0,
  120242. NULL,
  120243. NULL,
  120244. NULL,
  120245. NULL,
  120246. 0
  120247. };
  120248. static long _huff_lengthlist_line_128x7_class1[] = {
  120249. 8,13,17,17, 8,11,17,17,11,13,17,17,17,17,17,17,
  120250. 6,10,16,17, 6,10,15,17, 8,10,16,17,17,17,17,17,
  120251. 9,13,15,17, 8,11,17,17,10,12,17,17,17,17,17,17,
  120252. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  120253. 6,11,15,17, 7,10,15,17, 8,10,17,17,17,15,17,17,
  120254. 4, 8,13,17, 4, 7,13,17, 6, 8,15,17,16,15,17,17,
  120255. 6,11,15,17, 6, 9,13,17, 8,10,17,17,15,17,17,17,
  120256. 16,17,17,17,12,14,15,17,13,14,15,17,17,17,17,17,
  120257. 5,10,14,17, 5, 9,14,17, 7, 9,15,17,15,15,17,17,
  120258. 3, 7,12,17, 3, 6,11,17, 5, 7,13,17,12,12,17,17,
  120259. 5, 9,14,17, 3, 7,11,17, 5, 8,13,17,13,11,16,17,
  120260. 12,17,17,17, 9,14,15,17,10,11,14,17,16,14,17,17,
  120261. 8,12,17,17, 8,12,17,17,10,12,17,17,17,17,17,17,
  120262. 5,10,17,17, 5, 9,15,17, 7, 9,17,17,13,13,17,17,
  120263. 7,11,17,17, 6,10,15,17, 7, 9,15,17,12,11,17,17,
  120264. 12,15,17,17,11,14,17,17,11,10,15,17,17,16,17,17,
  120265. };
  120266. static static_codebook _huff_book_line_128x7_class1 = {
  120267. 1, 256,
  120268. _huff_lengthlist_line_128x7_class1,
  120269. 0, 0, 0, 0, 0,
  120270. NULL,
  120271. NULL,
  120272. NULL,
  120273. NULL,
  120274. 0
  120275. };
  120276. static long _huff_lengthlist_line_128x7_0sub1[] = {
  120277. 0, 3, 3, 3, 3, 3, 3, 3, 3,
  120278. };
  120279. static static_codebook _huff_book_line_128x7_0sub1 = {
  120280. 1, 9,
  120281. _huff_lengthlist_line_128x7_0sub1,
  120282. 0, 0, 0, 0, 0,
  120283. NULL,
  120284. NULL,
  120285. NULL,
  120286. NULL,
  120287. 0
  120288. };
  120289. static long _huff_lengthlist_line_128x7_0sub2[] = {
  120290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 4, 4, 4,
  120291. 5, 4, 5, 4, 5, 4, 6, 4, 6,
  120292. };
  120293. static static_codebook _huff_book_line_128x7_0sub2 = {
  120294. 1, 25,
  120295. _huff_lengthlist_line_128x7_0sub2,
  120296. 0, 0, 0, 0, 0,
  120297. NULL,
  120298. NULL,
  120299. NULL,
  120300. NULL,
  120301. 0
  120302. };
  120303. static long _huff_lengthlist_line_128x7_0sub3[] = {
  120304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 3, 5, 3, 5, 4,
  120306. 5, 4, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  120307. 7, 8, 9,11,13,13,13,13,13,13,13,13,13,13,13,13,
  120308. };
  120309. static static_codebook _huff_book_line_128x7_0sub3 = {
  120310. 1, 64,
  120311. _huff_lengthlist_line_128x7_0sub3,
  120312. 0, 0, 0, 0, 0,
  120313. NULL,
  120314. NULL,
  120315. NULL,
  120316. NULL,
  120317. 0
  120318. };
  120319. static long _huff_lengthlist_line_128x7_1sub1[] = {
  120320. 0, 3, 3, 2, 3, 3, 4, 3, 4,
  120321. };
  120322. static static_codebook _huff_book_line_128x7_1sub1 = {
  120323. 1, 9,
  120324. _huff_lengthlist_line_128x7_1sub1,
  120325. 0, 0, 0, 0, 0,
  120326. NULL,
  120327. NULL,
  120328. NULL,
  120329. NULL,
  120330. 0
  120331. };
  120332. static long _huff_lengthlist_line_128x7_1sub2[] = {
  120333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 6, 3, 6, 3,
  120334. 6, 3, 7, 3, 8, 4, 9, 4, 9,
  120335. };
  120336. static static_codebook _huff_book_line_128x7_1sub2 = {
  120337. 1, 25,
  120338. _huff_lengthlist_line_128x7_1sub2,
  120339. 0, 0, 0, 0, 0,
  120340. NULL,
  120341. NULL,
  120342. NULL,
  120343. NULL,
  120344. 0
  120345. };
  120346. static long _huff_lengthlist_line_128x7_1sub3[] = {
  120347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 7, 2, 7, 3, 8, 4,
  120349. 9, 5, 9, 8,10,11,11,12,14,14,14,14,14,14,14,14,
  120350. 14,14,14,14,14,14,14,14,14,14,14,14,13,13,13,13,
  120351. };
  120352. static static_codebook _huff_book_line_128x7_1sub3 = {
  120353. 1, 64,
  120354. _huff_lengthlist_line_128x7_1sub3,
  120355. 0, 0, 0, 0, 0,
  120356. NULL,
  120357. NULL,
  120358. NULL,
  120359. NULL,
  120360. 0
  120361. };
  120362. static long _huff_lengthlist_line_128x11_class1[] = {
  120363. 1, 6, 3, 7, 2, 4, 5, 7,
  120364. };
  120365. static static_codebook _huff_book_line_128x11_class1 = {
  120366. 1, 8,
  120367. _huff_lengthlist_line_128x11_class1,
  120368. 0, 0, 0, 0, 0,
  120369. NULL,
  120370. NULL,
  120371. NULL,
  120372. NULL,
  120373. 0
  120374. };
  120375. static long _huff_lengthlist_line_128x11_class2[] = {
  120376. 1, 6,12,16, 4,12,15,16, 9,15,16,16,16,16,16,16,
  120377. 2, 5,11,16, 5,11,13,16, 9,13,16,16,16,16,16,16,
  120378. 4, 8,12,16, 5, 9,12,16, 9,13,15,16,16,16,16,16,
  120379. 15,16,16,16,11,14,13,16,12,15,16,16,16,16,16,15,
  120380. };
  120381. static static_codebook _huff_book_line_128x11_class2 = {
  120382. 1, 64,
  120383. _huff_lengthlist_line_128x11_class2,
  120384. 0, 0, 0, 0, 0,
  120385. NULL,
  120386. NULL,
  120387. NULL,
  120388. NULL,
  120389. 0
  120390. };
  120391. static long _huff_lengthlist_line_128x11_class3[] = {
  120392. 7, 6, 9,17, 7, 6, 8,17,12, 9,11,16,16,16,16,16,
  120393. 5, 4, 7,16, 5, 3, 6,14, 9, 6, 8,15,16,16,16,16,
  120394. 5, 4, 6,13, 3, 2, 4,11, 7, 4, 6,13,16,11,10,14,
  120395. 12,12,12,16, 9, 7,10,15,12, 9,11,16,16,15,15,16,
  120396. };
  120397. static static_codebook _huff_book_line_128x11_class3 = {
  120398. 1, 64,
  120399. _huff_lengthlist_line_128x11_class3,
  120400. 0, 0, 0, 0, 0,
  120401. NULL,
  120402. NULL,
  120403. NULL,
  120404. NULL,
  120405. 0
  120406. };
  120407. static long _huff_lengthlist_line_128x11_0sub0[] = {
  120408. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  120409. 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 6, 6, 6, 7, 6,
  120410. 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6, 8, 7,
  120411. 8, 7, 8, 7, 8, 7, 9, 7, 9, 8, 9, 8, 9, 8,10, 8,
  120412. 10, 9,10, 9,10, 9,11, 9,11, 9,10,10,11,10,11,10,
  120413. 11,11,11,11,11,11,12,13,14,14,14,15,15,16,16,16,
  120414. 17,15,16,15,16,16,17,17,16,17,17,17,17,17,17,17,
  120415. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  120416. };
  120417. static static_codebook _huff_book_line_128x11_0sub0 = {
  120418. 1, 128,
  120419. _huff_lengthlist_line_128x11_0sub0,
  120420. 0, 0, 0, 0, 0,
  120421. NULL,
  120422. NULL,
  120423. NULL,
  120424. NULL,
  120425. 0
  120426. };
  120427. static long _huff_lengthlist_line_128x11_1sub0[] = {
  120428. 2, 5, 5, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  120429. 6, 5, 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6,
  120430. };
  120431. static static_codebook _huff_book_line_128x11_1sub0 = {
  120432. 1, 32,
  120433. _huff_lengthlist_line_128x11_1sub0,
  120434. 0, 0, 0, 0, 0,
  120435. NULL,
  120436. NULL,
  120437. NULL,
  120438. NULL,
  120439. 0
  120440. };
  120441. static long _huff_lengthlist_line_128x11_1sub1[] = {
  120442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120444. 5, 3, 5, 3, 6, 4, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  120445. 8, 4, 9, 5, 9, 5, 9, 5, 9, 6,10, 6,10, 6,11, 7,
  120446. 10, 7,10, 8,11, 9,11, 9,11,10,11,11,12,11,11,12,
  120447. 15,15,12,14,11,14,12,14,11,14,13,14,12,14,11,14,
  120448. 11,14,12,14,11,14,11,14,13,13,14,14,14,14,14,14,
  120449. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  120450. };
  120451. static static_codebook _huff_book_line_128x11_1sub1 = {
  120452. 1, 128,
  120453. _huff_lengthlist_line_128x11_1sub1,
  120454. 0, 0, 0, 0, 0,
  120455. NULL,
  120456. NULL,
  120457. NULL,
  120458. NULL,
  120459. 0
  120460. };
  120461. static long _huff_lengthlist_line_128x11_2sub1[] = {
  120462. 0, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4,
  120463. 5, 5,
  120464. };
  120465. static static_codebook _huff_book_line_128x11_2sub1 = {
  120466. 1, 18,
  120467. _huff_lengthlist_line_128x11_2sub1,
  120468. 0, 0, 0, 0, 0,
  120469. NULL,
  120470. NULL,
  120471. NULL,
  120472. NULL,
  120473. 0
  120474. };
  120475. static long _huff_lengthlist_line_128x11_2sub2[] = {
  120476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120477. 0, 0, 3, 3, 3, 4, 4, 4, 4, 5, 4, 5, 4, 6, 5, 7,
  120478. 5, 7, 6, 8, 6, 8, 6, 9, 7, 9, 7,10, 7, 9, 8,11,
  120479. 8,11,
  120480. };
  120481. static static_codebook _huff_book_line_128x11_2sub2 = {
  120482. 1, 50,
  120483. _huff_lengthlist_line_128x11_2sub2,
  120484. 0, 0, 0, 0, 0,
  120485. NULL,
  120486. NULL,
  120487. NULL,
  120488. NULL,
  120489. 0
  120490. };
  120491. static long _huff_lengthlist_line_128x11_2sub3[] = {
  120492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120495. 0, 0, 4, 8, 3, 8, 4, 8, 4, 8, 6, 8, 5, 8, 4, 8,
  120496. 4, 8, 6, 8, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120497. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120498. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120499. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120500. };
  120501. static static_codebook _huff_book_line_128x11_2sub3 = {
  120502. 1, 128,
  120503. _huff_lengthlist_line_128x11_2sub3,
  120504. 0, 0, 0, 0, 0,
  120505. NULL,
  120506. NULL,
  120507. NULL,
  120508. NULL,
  120509. 0
  120510. };
  120511. static long _huff_lengthlist_line_128x11_3sub1[] = {
  120512. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4,
  120513. 5, 4,
  120514. };
  120515. static static_codebook _huff_book_line_128x11_3sub1 = {
  120516. 1, 18,
  120517. _huff_lengthlist_line_128x11_3sub1,
  120518. 0, 0, 0, 0, 0,
  120519. NULL,
  120520. NULL,
  120521. NULL,
  120522. NULL,
  120523. 0
  120524. };
  120525. static long _huff_lengthlist_line_128x11_3sub2[] = {
  120526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120527. 0, 0, 5, 3, 5, 4, 6, 4, 6, 4, 7, 4, 7, 4, 8, 4,
  120528. 8, 4, 9, 4, 9, 4,10, 4,10, 5,10, 5,11, 5,12, 6,
  120529. 12, 6,
  120530. };
  120531. static static_codebook _huff_book_line_128x11_3sub2 = {
  120532. 1, 50,
  120533. _huff_lengthlist_line_128x11_3sub2,
  120534. 0, 0, 0, 0, 0,
  120535. NULL,
  120536. NULL,
  120537. NULL,
  120538. NULL,
  120539. 0
  120540. };
  120541. static long _huff_lengthlist_line_128x11_3sub3[] = {
  120542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120545. 0, 0, 7, 1, 6, 3, 7, 3, 8, 4, 8, 5, 8, 8, 8, 9,
  120546. 7, 8, 8, 7, 7, 7, 8, 9,10, 9, 9,10,10,10,10,10,
  120547. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120548. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120549. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  120550. };
  120551. static static_codebook _huff_book_line_128x11_3sub3 = {
  120552. 1, 128,
  120553. _huff_lengthlist_line_128x11_3sub3,
  120554. 0, 0, 0, 0, 0,
  120555. NULL,
  120556. NULL,
  120557. NULL,
  120558. NULL,
  120559. 0
  120560. };
  120561. static long _huff_lengthlist_line_128x17_class1[] = {
  120562. 1, 3, 4, 7, 2, 5, 6, 7,
  120563. };
  120564. static static_codebook _huff_book_line_128x17_class1 = {
  120565. 1, 8,
  120566. _huff_lengthlist_line_128x17_class1,
  120567. 0, 0, 0, 0, 0,
  120568. NULL,
  120569. NULL,
  120570. NULL,
  120571. NULL,
  120572. 0
  120573. };
  120574. static long _huff_lengthlist_line_128x17_class2[] = {
  120575. 1, 4,10,19, 3, 8,13,19, 7,12,19,19,19,19,19,19,
  120576. 2, 6,11,19, 8,13,19,19, 9,11,19,19,19,19,19,19,
  120577. 6, 7,13,19, 9,13,19,19,10,13,18,18,18,18,18,18,
  120578. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  120579. };
  120580. static static_codebook _huff_book_line_128x17_class2 = {
  120581. 1, 64,
  120582. _huff_lengthlist_line_128x17_class2,
  120583. 0, 0, 0, 0, 0,
  120584. NULL,
  120585. NULL,
  120586. NULL,
  120587. NULL,
  120588. 0
  120589. };
  120590. static long _huff_lengthlist_line_128x17_class3[] = {
  120591. 3, 6,10,17, 4, 8,11,20, 8,10,11,20,20,20,20,20,
  120592. 2, 4, 8,18, 4, 6, 8,17, 7, 8,10,20,20,17,20,20,
  120593. 3, 5, 8,17, 3, 4, 6,17, 8, 8,10,17,17,12,16,20,
  120594. 13,13,15,20,10,10,12,20,15,14,15,20,20,20,19,19,
  120595. };
  120596. static static_codebook _huff_book_line_128x17_class3 = {
  120597. 1, 64,
  120598. _huff_lengthlist_line_128x17_class3,
  120599. 0, 0, 0, 0, 0,
  120600. NULL,
  120601. NULL,
  120602. NULL,
  120603. NULL,
  120604. 0
  120605. };
  120606. static long _huff_lengthlist_line_128x17_0sub0[] = {
  120607. 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  120608. 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5,
  120609. 8, 5, 8, 5, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6, 9, 6,
  120610. 9, 6, 9, 7, 9, 7, 9, 7, 9, 7,10, 7,10, 8,10, 8,
  120611. 10, 8,10, 8,10, 8,11, 8,11, 8,11, 8,11, 8,11, 9,
  120612. 12, 9,12, 9,12, 9,12, 9,12,10,12,10,13,11,13,11,
  120613. 14,12,14,13,15,14,16,14,17,15,18,16,20,20,20,20,
  120614. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  120615. };
  120616. static static_codebook _huff_book_line_128x17_0sub0 = {
  120617. 1, 128,
  120618. _huff_lengthlist_line_128x17_0sub0,
  120619. 0, 0, 0, 0, 0,
  120620. NULL,
  120621. NULL,
  120622. NULL,
  120623. NULL,
  120624. 0
  120625. };
  120626. static long _huff_lengthlist_line_128x17_1sub0[] = {
  120627. 2, 5, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  120628. 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7,
  120629. };
  120630. static static_codebook _huff_book_line_128x17_1sub0 = {
  120631. 1, 32,
  120632. _huff_lengthlist_line_128x17_1sub0,
  120633. 0, 0, 0, 0, 0,
  120634. NULL,
  120635. NULL,
  120636. NULL,
  120637. NULL,
  120638. 0
  120639. };
  120640. static long _huff_lengthlist_line_128x17_1sub1[] = {
  120641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120643. 4, 3, 5, 3, 5, 3, 6, 3, 6, 4, 6, 4, 7, 4, 7, 5,
  120644. 8, 5, 8, 6, 9, 7, 9, 7, 9, 8,10, 9,10, 9,11,10,
  120645. 11,11,11,11,11,11,12,12,12,13,12,13,12,14,12,15,
  120646. 12,14,12,16,13,17,13,17,14,17,14,16,13,17,14,17,
  120647. 14,17,15,17,15,15,16,17,17,17,17,17,17,17,17,17,
  120648. 17,17,17,17,17,17,16,16,16,16,16,16,16,16,16,16,
  120649. };
  120650. static static_codebook _huff_book_line_128x17_1sub1 = {
  120651. 1, 128,
  120652. _huff_lengthlist_line_128x17_1sub1,
  120653. 0, 0, 0, 0, 0,
  120654. NULL,
  120655. NULL,
  120656. NULL,
  120657. NULL,
  120658. 0
  120659. };
  120660. static long _huff_lengthlist_line_128x17_2sub1[] = {
  120661. 0, 4, 5, 4, 6, 4, 8, 3, 9, 3, 9, 2, 9, 3, 8, 4,
  120662. 9, 4,
  120663. };
  120664. static static_codebook _huff_book_line_128x17_2sub1 = {
  120665. 1, 18,
  120666. _huff_lengthlist_line_128x17_2sub1,
  120667. 0, 0, 0, 0, 0,
  120668. NULL,
  120669. NULL,
  120670. NULL,
  120671. NULL,
  120672. 0
  120673. };
  120674. static long _huff_lengthlist_line_128x17_2sub2[] = {
  120675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120676. 0, 0, 5, 1, 5, 3, 5, 3, 5, 4, 7, 5,10, 7,10, 7,
  120677. 12,10,14,10,14, 9,14,11,14,14,14,13,13,13,13,13,
  120678. 13,13,
  120679. };
  120680. static static_codebook _huff_book_line_128x17_2sub2 = {
  120681. 1, 50,
  120682. _huff_lengthlist_line_128x17_2sub2,
  120683. 0, 0, 0, 0, 0,
  120684. NULL,
  120685. NULL,
  120686. NULL,
  120687. NULL,
  120688. 0
  120689. };
  120690. static long _huff_lengthlist_line_128x17_2sub3[] = {
  120691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120694. 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120695. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6,
  120696. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  120697. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  120698. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  120699. };
  120700. static static_codebook _huff_book_line_128x17_2sub3 = {
  120701. 1, 128,
  120702. _huff_lengthlist_line_128x17_2sub3,
  120703. 0, 0, 0, 0, 0,
  120704. NULL,
  120705. NULL,
  120706. NULL,
  120707. NULL,
  120708. 0
  120709. };
  120710. static long _huff_lengthlist_line_128x17_3sub1[] = {
  120711. 0, 4, 4, 4, 4, 4, 4, 4, 5, 3, 5, 3, 5, 4, 6, 4,
  120712. 6, 4,
  120713. };
  120714. static static_codebook _huff_book_line_128x17_3sub1 = {
  120715. 1, 18,
  120716. _huff_lengthlist_line_128x17_3sub1,
  120717. 0, 0, 0, 0, 0,
  120718. NULL,
  120719. NULL,
  120720. NULL,
  120721. NULL,
  120722. 0
  120723. };
  120724. static long _huff_lengthlist_line_128x17_3sub2[] = {
  120725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120726. 0, 0, 5, 3, 6, 3, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  120727. 8, 4, 8, 4, 8, 4, 9, 4, 9, 5,10, 5,10, 7,10, 8,
  120728. 10, 8,
  120729. };
  120730. static static_codebook _huff_book_line_128x17_3sub2 = {
  120731. 1, 50,
  120732. _huff_lengthlist_line_128x17_3sub2,
  120733. 0, 0, 0, 0, 0,
  120734. NULL,
  120735. NULL,
  120736. NULL,
  120737. NULL,
  120738. 0
  120739. };
  120740. static long _huff_lengthlist_line_128x17_3sub3[] = {
  120741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120744. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 4, 7, 5, 8, 5,11,
  120745. 6,10, 6,12, 7,12, 7,12, 8,12, 8,12,10,12,12,12,
  120746. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  120747. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  120748. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  120749. };
  120750. static static_codebook _huff_book_line_128x17_3sub3 = {
  120751. 1, 128,
  120752. _huff_lengthlist_line_128x17_3sub3,
  120753. 0, 0, 0, 0, 0,
  120754. NULL,
  120755. NULL,
  120756. NULL,
  120757. NULL,
  120758. 0
  120759. };
  120760. static long _huff_lengthlist_line_1024x27_class1[] = {
  120761. 2,10, 8,14, 7,12,11,14, 1, 5, 3, 7, 4, 9, 7,13,
  120762. };
  120763. static static_codebook _huff_book_line_1024x27_class1 = {
  120764. 1, 16,
  120765. _huff_lengthlist_line_1024x27_class1,
  120766. 0, 0, 0, 0, 0,
  120767. NULL,
  120768. NULL,
  120769. NULL,
  120770. NULL,
  120771. 0
  120772. };
  120773. static long _huff_lengthlist_line_1024x27_class2[] = {
  120774. 1, 4, 2, 6, 3, 7, 5, 7,
  120775. };
  120776. static static_codebook _huff_book_line_1024x27_class2 = {
  120777. 1, 8,
  120778. _huff_lengthlist_line_1024x27_class2,
  120779. 0, 0, 0, 0, 0,
  120780. NULL,
  120781. NULL,
  120782. NULL,
  120783. NULL,
  120784. 0
  120785. };
  120786. static long _huff_lengthlist_line_1024x27_class3[] = {
  120787. 1, 5, 7,21, 5, 8, 9,21,10, 9,12,20,20,16,20,20,
  120788. 4, 8, 9,20, 6, 8, 9,20,11,11,13,20,20,15,17,20,
  120789. 9,11,14,20, 8,10,15,20,11,13,15,20,20,20,20,20,
  120790. 20,20,20,20,13,20,20,20,18,18,20,20,20,20,20,20,
  120791. 3, 6, 8,20, 6, 7, 9,20,10, 9,12,20,20,20,20,20,
  120792. 5, 7, 9,20, 6, 6, 9,20,10, 9,12,20,20,20,20,20,
  120793. 8,10,13,20, 8, 9,12,20,11,10,12,20,20,20,20,20,
  120794. 18,20,20,20,15,17,18,20,18,17,18,20,20,20,20,20,
  120795. 7,10,12,20, 8, 9,11,20,14,13,14,20,20,20,20,20,
  120796. 6, 9,12,20, 7, 8,11,20,12,11,13,20,20,20,20,20,
  120797. 9,11,15,20, 8,10,14,20,12,11,14,20,20,20,20,20,
  120798. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  120799. 11,16,18,20,15,15,17,20,20,17,20,20,20,20,20,20,
  120800. 9,14,16,20,12,12,15,20,17,15,18,20,20,20,20,20,
  120801. 16,19,18,20,15,16,20,20,17,17,20,20,20,20,20,20,
  120802. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  120803. };
  120804. static static_codebook _huff_book_line_1024x27_class3 = {
  120805. 1, 256,
  120806. _huff_lengthlist_line_1024x27_class3,
  120807. 0, 0, 0, 0, 0,
  120808. NULL,
  120809. NULL,
  120810. NULL,
  120811. NULL,
  120812. 0
  120813. };
  120814. static long _huff_lengthlist_line_1024x27_class4[] = {
  120815. 2, 3, 7,13, 4, 4, 7,15, 8, 6, 9,17,21,16,15,21,
  120816. 2, 5, 7,11, 5, 5, 7,14, 9, 7,10,16,17,15,16,21,
  120817. 4, 7,10,17, 7, 7, 9,15,11, 9,11,16,21,18,15,21,
  120818. 18,21,21,21,15,17,17,19,21,19,18,20,21,21,21,20,
  120819. };
  120820. static static_codebook _huff_book_line_1024x27_class4 = {
  120821. 1, 64,
  120822. _huff_lengthlist_line_1024x27_class4,
  120823. 0, 0, 0, 0, 0,
  120824. NULL,
  120825. NULL,
  120826. NULL,
  120827. NULL,
  120828. 0
  120829. };
  120830. static long _huff_lengthlist_line_1024x27_0sub0[] = {
  120831. 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  120832. 6, 5, 6, 5, 6, 5, 6, 5, 7, 5, 7, 5, 7, 5, 7, 5,
  120833. 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,10, 6,10, 6,11, 6,
  120834. 11, 7,11, 7,12, 7,12, 7,12, 7,12, 7,12, 7,12, 7,
  120835. 12, 7,12, 8,13, 8,12, 8,12, 8,13, 8,13, 9,13, 9,
  120836. 13, 9,13, 9,12,10,12,10,13,10,14,11,14,12,14,13,
  120837. 14,13,14,14,15,16,15,15,15,14,15,17,21,22,22,21,
  120838. 22,22,22,22,22,22,21,21,21,21,21,21,21,21,21,21,
  120839. };
  120840. static static_codebook _huff_book_line_1024x27_0sub0 = {
  120841. 1, 128,
  120842. _huff_lengthlist_line_1024x27_0sub0,
  120843. 0, 0, 0, 0, 0,
  120844. NULL,
  120845. NULL,
  120846. NULL,
  120847. NULL,
  120848. 0
  120849. };
  120850. static long _huff_lengthlist_line_1024x27_1sub0[] = {
  120851. 2, 5, 5, 4, 5, 4, 5, 4, 5, 4, 6, 5, 6, 5, 6, 5,
  120852. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,
  120853. };
  120854. static static_codebook _huff_book_line_1024x27_1sub0 = {
  120855. 1, 32,
  120856. _huff_lengthlist_line_1024x27_1sub0,
  120857. 0, 0, 0, 0, 0,
  120858. NULL,
  120859. NULL,
  120860. NULL,
  120861. NULL,
  120862. 0
  120863. };
  120864. static long _huff_lengthlist_line_1024x27_1sub1[] = {
  120865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120867. 8, 5, 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4,
  120868. 9, 4, 9, 4, 9, 4, 8, 4, 8, 4, 9, 5, 9, 5, 9, 5,
  120869. 9, 5, 9, 6,10, 6,10, 7,10, 8,11, 9,11,11,12,13,
  120870. 12,14,13,15,13,15,14,16,14,17,15,17,15,15,16,16,
  120871. 15,16,16,16,15,18,16,15,17,17,19,19,19,19,19,19,
  120872. 19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,
  120873. };
  120874. static static_codebook _huff_book_line_1024x27_1sub1 = {
  120875. 1, 128,
  120876. _huff_lengthlist_line_1024x27_1sub1,
  120877. 0, 0, 0, 0, 0,
  120878. NULL,
  120879. NULL,
  120880. NULL,
  120881. NULL,
  120882. 0
  120883. };
  120884. static long _huff_lengthlist_line_1024x27_2sub0[] = {
  120885. 1, 5, 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  120886. 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 9, 8,10, 9,10, 9,
  120887. };
  120888. static static_codebook _huff_book_line_1024x27_2sub0 = {
  120889. 1, 32,
  120890. _huff_lengthlist_line_1024x27_2sub0,
  120891. 0, 0, 0, 0, 0,
  120892. NULL,
  120893. NULL,
  120894. NULL,
  120895. NULL,
  120896. 0
  120897. };
  120898. static long _huff_lengthlist_line_1024x27_2sub1[] = {
  120899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120901. 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 5, 5, 6, 5, 6, 5,
  120902. 7, 5, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 9, 8, 9, 9,
  120903. 9, 9,10,10,10,11, 9,12, 9,12, 9,15,10,14, 9,13,
  120904. 10,13,10,12,10,12,10,13,10,12,11,13,11,14,12,13,
  120905. 13,14,14,13,14,15,14,16,13,13,14,16,16,16,16,16,
  120906. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,15,15,
  120907. };
  120908. static static_codebook _huff_book_line_1024x27_2sub1 = {
  120909. 1, 128,
  120910. _huff_lengthlist_line_1024x27_2sub1,
  120911. 0, 0, 0, 0, 0,
  120912. NULL,
  120913. NULL,
  120914. NULL,
  120915. NULL,
  120916. 0
  120917. };
  120918. static long _huff_lengthlist_line_1024x27_3sub1[] = {
  120919. 0, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4, 4, 5,
  120920. 5, 5,
  120921. };
  120922. static static_codebook _huff_book_line_1024x27_3sub1 = {
  120923. 1, 18,
  120924. _huff_lengthlist_line_1024x27_3sub1,
  120925. 0, 0, 0, 0, 0,
  120926. NULL,
  120927. NULL,
  120928. NULL,
  120929. NULL,
  120930. 0
  120931. };
  120932. static long _huff_lengthlist_line_1024x27_3sub2[] = {
  120933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120934. 0, 0, 3, 3, 4, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6,
  120935. 5, 7, 5, 8, 6, 8, 6, 9, 7,10, 7,10, 8,10, 8,11,
  120936. 9,11,
  120937. };
  120938. static static_codebook _huff_book_line_1024x27_3sub2 = {
  120939. 1, 50,
  120940. _huff_lengthlist_line_1024x27_3sub2,
  120941. 0, 0, 0, 0, 0,
  120942. NULL,
  120943. NULL,
  120944. NULL,
  120945. NULL,
  120946. 0
  120947. };
  120948. static long _huff_lengthlist_line_1024x27_3sub3[] = {
  120949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120952. 0, 0, 3, 7, 3, 8, 3,10, 3, 8, 3, 9, 3, 8, 4, 9,
  120953. 4, 9, 5, 9, 6,10, 6, 9, 7,11, 7,12, 9,13,10,13,
  120954. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  120955. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  120956. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  120957. };
  120958. static static_codebook _huff_book_line_1024x27_3sub3 = {
  120959. 1, 128,
  120960. _huff_lengthlist_line_1024x27_3sub3,
  120961. 0, 0, 0, 0, 0,
  120962. NULL,
  120963. NULL,
  120964. NULL,
  120965. NULL,
  120966. 0
  120967. };
  120968. static long _huff_lengthlist_line_1024x27_4sub1[] = {
  120969. 0, 4, 5, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4,
  120970. 5, 4,
  120971. };
  120972. static static_codebook _huff_book_line_1024x27_4sub1 = {
  120973. 1, 18,
  120974. _huff_lengthlist_line_1024x27_4sub1,
  120975. 0, 0, 0, 0, 0,
  120976. NULL,
  120977. NULL,
  120978. NULL,
  120979. NULL,
  120980. 0
  120981. };
  120982. static long _huff_lengthlist_line_1024x27_4sub2[] = {
  120983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120984. 0, 0, 4, 2, 4, 2, 5, 3, 5, 4, 6, 6, 6, 7, 7, 8,
  120985. 7, 8, 7, 8, 7, 9, 8, 9, 8, 9, 8,10, 8,11, 9,12,
  120986. 9,12,
  120987. };
  120988. static static_codebook _huff_book_line_1024x27_4sub2 = {
  120989. 1, 50,
  120990. _huff_lengthlist_line_1024x27_4sub2,
  120991. 0, 0, 0, 0, 0,
  120992. NULL,
  120993. NULL,
  120994. NULL,
  120995. NULL,
  120996. 0
  120997. };
  120998. static long _huff_lengthlist_line_1024x27_4sub3[] = {
  120999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121002. 0, 0, 2, 5, 2, 6, 3, 6, 4, 7, 4, 7, 5, 9, 5,11,
  121003. 6,11, 6,11, 7,11, 6,11, 6,11, 9,11, 8,11,11,11,
  121004. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121005. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121006. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  121007. };
  121008. static static_codebook _huff_book_line_1024x27_4sub3 = {
  121009. 1, 128,
  121010. _huff_lengthlist_line_1024x27_4sub3,
  121011. 0, 0, 0, 0, 0,
  121012. NULL,
  121013. NULL,
  121014. NULL,
  121015. NULL,
  121016. 0
  121017. };
  121018. static long _huff_lengthlist_line_2048x27_class1[] = {
  121019. 2, 6, 8, 9, 7,11,13,13, 1, 3, 5, 5, 6, 6,12,10,
  121020. };
  121021. static static_codebook _huff_book_line_2048x27_class1 = {
  121022. 1, 16,
  121023. _huff_lengthlist_line_2048x27_class1,
  121024. 0, 0, 0, 0, 0,
  121025. NULL,
  121026. NULL,
  121027. NULL,
  121028. NULL,
  121029. 0
  121030. };
  121031. static long _huff_lengthlist_line_2048x27_class2[] = {
  121032. 1, 2, 3, 6, 4, 7, 5, 7,
  121033. };
  121034. static static_codebook _huff_book_line_2048x27_class2 = {
  121035. 1, 8,
  121036. _huff_lengthlist_line_2048x27_class2,
  121037. 0, 0, 0, 0, 0,
  121038. NULL,
  121039. NULL,
  121040. NULL,
  121041. NULL,
  121042. 0
  121043. };
  121044. static long _huff_lengthlist_line_2048x27_class3[] = {
  121045. 3, 3, 6,16, 5, 5, 7,16, 9, 8,11,16,16,16,16,16,
  121046. 5, 5, 8,16, 5, 5, 7,16, 8, 7, 9,16,16,16,16,16,
  121047. 9, 9,12,16, 6, 8,11,16, 9,10,11,16,16,16,16,16,
  121048. 16,16,16,16,13,16,16,16,15,16,16,16,16,16,16,16,
  121049. 5, 4, 7,16, 6, 5, 8,16, 9, 8,10,16,16,16,16,16,
  121050. 5, 5, 7,15, 5, 4, 6,15, 7, 6, 8,16,16,16,16,16,
  121051. 9, 9,11,15, 7, 7, 9,16, 8, 8, 9,16,16,16,16,16,
  121052. 16,16,16,16,15,15,15,16,15,15,14,16,16,16,16,16,
  121053. 8, 8,11,16, 8, 9,10,16,11,10,14,16,16,16,16,16,
  121054. 6, 8,10,16, 6, 7,10,16, 8, 8,11,16,14,16,16,16,
  121055. 10,11,14,16, 9, 9,11,16,10,10,11,16,16,16,16,16,
  121056. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  121057. 16,16,16,16,15,16,16,16,16,16,16,16,16,16,16,16,
  121058. 12,16,15,16,12,14,16,16,16,16,16,16,16,16,16,16,
  121059. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  121060. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  121061. };
  121062. static static_codebook _huff_book_line_2048x27_class3 = {
  121063. 1, 256,
  121064. _huff_lengthlist_line_2048x27_class3,
  121065. 0, 0, 0, 0, 0,
  121066. NULL,
  121067. NULL,
  121068. NULL,
  121069. NULL,
  121070. 0
  121071. };
  121072. static long _huff_lengthlist_line_2048x27_class4[] = {
  121073. 2, 4, 7,13, 4, 5, 7,15, 8, 7,10,16,16,14,16,16,
  121074. 2, 4, 7,16, 3, 4, 7,14, 8, 8,10,16,16,16,15,16,
  121075. 6, 8,11,16, 7, 7, 9,16,11, 9,13,16,16,16,15,16,
  121076. 16,16,16,16,14,16,16,16,16,16,16,16,16,16,16,16,
  121077. };
  121078. static static_codebook _huff_book_line_2048x27_class4 = {
  121079. 1, 64,
  121080. _huff_lengthlist_line_2048x27_class4,
  121081. 0, 0, 0, 0, 0,
  121082. NULL,
  121083. NULL,
  121084. NULL,
  121085. NULL,
  121086. 0
  121087. };
  121088. static long _huff_lengthlist_line_2048x27_0sub0[] = {
  121089. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121090. 6, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5, 8, 5, 9, 5,
  121091. 9, 6,10, 6,10, 6,11, 6,11, 6,11, 6,11, 6,11, 6,
  121092. 11, 6,11, 6,12, 7,11, 7,11, 7,11, 7,11, 7,10, 7,
  121093. 11, 7,11, 7,12, 7,11, 8,11, 8,11, 8,11, 8,13, 8,
  121094. 12, 9,11, 9,11, 9,11,10,12,10,12, 9,12,10,12,11,
  121095. 14,12,16,12,12,11,14,16,17,17,17,17,17,17,17,17,
  121096. 17,17,17,17,17,17,17,17,17,17,17,17,16,16,16,16,
  121097. };
  121098. static static_codebook _huff_book_line_2048x27_0sub0 = {
  121099. 1, 128,
  121100. _huff_lengthlist_line_2048x27_0sub0,
  121101. 0, 0, 0, 0, 0,
  121102. NULL,
  121103. NULL,
  121104. NULL,
  121105. NULL,
  121106. 0
  121107. };
  121108. static long _huff_lengthlist_line_2048x27_1sub0[] = {
  121109. 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  121110. 5, 5, 6, 6, 6, 6, 6, 6, 7, 6, 7, 6, 7, 6, 7, 6,
  121111. };
  121112. static static_codebook _huff_book_line_2048x27_1sub0 = {
  121113. 1, 32,
  121114. _huff_lengthlist_line_2048x27_1sub0,
  121115. 0, 0, 0, 0, 0,
  121116. NULL,
  121117. NULL,
  121118. NULL,
  121119. NULL,
  121120. 0
  121121. };
  121122. static long _huff_lengthlist_line_2048x27_1sub1[] = {
  121123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121125. 6, 5, 7, 5, 7, 4, 7, 4, 8, 4, 8, 4, 8, 4, 8, 3,
  121126. 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 5, 9, 5, 9, 6,
  121127. 9, 7, 9, 8, 9, 9, 9,10, 9,11, 9,14, 9,15,10,15,
  121128. 10,15,10,15,10,15,11,15,10,14,12,14,11,14,13,14,
  121129. 13,15,15,15,12,15,15,15,13,15,13,15,13,15,15,15,
  121130. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,14,
  121131. };
  121132. static static_codebook _huff_book_line_2048x27_1sub1 = {
  121133. 1, 128,
  121134. _huff_lengthlist_line_2048x27_1sub1,
  121135. 0, 0, 0, 0, 0,
  121136. NULL,
  121137. NULL,
  121138. NULL,
  121139. NULL,
  121140. 0
  121141. };
  121142. static long _huff_lengthlist_line_2048x27_2sub0[] = {
  121143. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  121144. 6, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  121145. };
  121146. static static_codebook _huff_book_line_2048x27_2sub0 = {
  121147. 1, 32,
  121148. _huff_lengthlist_line_2048x27_2sub0,
  121149. 0, 0, 0, 0, 0,
  121150. NULL,
  121151. NULL,
  121152. NULL,
  121153. NULL,
  121154. 0
  121155. };
  121156. static long _huff_lengthlist_line_2048x27_2sub1[] = {
  121157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121159. 3, 4, 3, 4, 3, 4, 4, 5, 4, 5, 5, 5, 6, 6, 6, 7,
  121160. 6, 8, 6, 8, 6, 9, 7,10, 7,10, 7,10, 7,12, 7,12,
  121161. 7,12, 9,12,11,12,10,12,10,12,11,12,12,12,10,12,
  121162. 10,12,10,12, 9,12,11,12,12,12,12,12,11,12,11,12,
  121163. 12,12,12,12,12,12,12,12,10,10,12,12,12,12,12,10,
  121164. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  121165. };
  121166. static static_codebook _huff_book_line_2048x27_2sub1 = {
  121167. 1, 128,
  121168. _huff_lengthlist_line_2048x27_2sub1,
  121169. 0, 0, 0, 0, 0,
  121170. NULL,
  121171. NULL,
  121172. NULL,
  121173. NULL,
  121174. 0
  121175. };
  121176. static long _huff_lengthlist_line_2048x27_3sub1[] = {
  121177. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  121178. 5, 5,
  121179. };
  121180. static static_codebook _huff_book_line_2048x27_3sub1 = {
  121181. 1, 18,
  121182. _huff_lengthlist_line_2048x27_3sub1,
  121183. 0, 0, 0, 0, 0,
  121184. NULL,
  121185. NULL,
  121186. NULL,
  121187. NULL,
  121188. 0
  121189. };
  121190. static long _huff_lengthlist_line_2048x27_3sub2[] = {
  121191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121192. 0, 0, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6,
  121193. 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7, 9, 9,11, 9,12,
  121194. 10,12,
  121195. };
  121196. static static_codebook _huff_book_line_2048x27_3sub2 = {
  121197. 1, 50,
  121198. _huff_lengthlist_line_2048x27_3sub2,
  121199. 0, 0, 0, 0, 0,
  121200. NULL,
  121201. NULL,
  121202. NULL,
  121203. NULL,
  121204. 0
  121205. };
  121206. static long _huff_lengthlist_line_2048x27_3sub3[] = {
  121207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121210. 0, 0, 3, 6, 3, 7, 3, 7, 5, 7, 7, 7, 7, 7, 6, 7,
  121211. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121212. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121213. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121214. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121215. };
  121216. static static_codebook _huff_book_line_2048x27_3sub3 = {
  121217. 1, 128,
  121218. _huff_lengthlist_line_2048x27_3sub3,
  121219. 0, 0, 0, 0, 0,
  121220. NULL,
  121221. NULL,
  121222. NULL,
  121223. NULL,
  121224. 0
  121225. };
  121226. static long _huff_lengthlist_line_2048x27_4sub1[] = {
  121227. 0, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4, 5, 4, 5, 4,
  121228. 4, 5,
  121229. };
  121230. static static_codebook _huff_book_line_2048x27_4sub1 = {
  121231. 1, 18,
  121232. _huff_lengthlist_line_2048x27_4sub1,
  121233. 0, 0, 0, 0, 0,
  121234. NULL,
  121235. NULL,
  121236. NULL,
  121237. NULL,
  121238. 0
  121239. };
  121240. static long _huff_lengthlist_line_2048x27_4sub2[] = {
  121241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121242. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 5, 6, 5, 6, 5, 7,
  121243. 6, 6, 6, 7, 7, 7, 8, 9, 9, 9,12,10,11,10,10,12,
  121244. 10,10,
  121245. };
  121246. static static_codebook _huff_book_line_2048x27_4sub2 = {
  121247. 1, 50,
  121248. _huff_lengthlist_line_2048x27_4sub2,
  121249. 0, 0, 0, 0, 0,
  121250. NULL,
  121251. NULL,
  121252. NULL,
  121253. NULL,
  121254. 0
  121255. };
  121256. static long _huff_lengthlist_line_2048x27_4sub3[] = {
  121257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121260. 0, 0, 3, 6, 5, 7, 5, 7, 7, 7, 7, 7, 5, 7, 5, 7,
  121261. 5, 7, 5, 7, 7, 7, 7, 7, 4, 7, 7, 7, 7, 7, 7, 7,
  121262. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121263. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121264. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121265. };
  121266. static static_codebook _huff_book_line_2048x27_4sub3 = {
  121267. 1, 128,
  121268. _huff_lengthlist_line_2048x27_4sub3,
  121269. 0, 0, 0, 0, 0,
  121270. NULL,
  121271. NULL,
  121272. NULL,
  121273. NULL,
  121274. 0
  121275. };
  121276. static long _huff_lengthlist_line_256x4low_class0[] = {
  121277. 4, 5, 6,11, 5, 5, 6,10, 7, 7, 6, 6,14,13, 9, 9,
  121278. 6, 6, 6,10, 6, 6, 6, 9, 8, 7, 7, 9,14,12, 8,11,
  121279. 8, 7, 7,11, 8, 8, 7,11, 9, 9, 7, 9,13,11, 9,13,
  121280. 19,19,18,19,15,16,16,19,11,11,10,13,10,10, 9,15,
  121281. 5, 5, 6,13, 6, 6, 6,11, 8, 7, 6, 7,14,11,10,11,
  121282. 6, 6, 6,12, 7, 6, 6,11, 8, 7, 7,11,13,11, 9,11,
  121283. 9, 7, 6,12, 8, 7, 6,12, 9, 8, 8,11,13,10, 7,13,
  121284. 19,19,17,19,17,14,14,19,12,10, 8,12,13,10, 9,16,
  121285. 7, 8, 7,12, 7, 7, 7,11, 8, 7, 7, 8,12,12,11,11,
  121286. 8, 8, 7,12, 8, 7, 6,11, 8, 7, 7,10,10,11,10,11,
  121287. 9, 8, 8,13, 9, 8, 7,12,10, 9, 7,11, 9, 8, 7,11,
  121288. 18,18,15,18,18,16,17,18,15,11,10,18,11, 9, 9,18,
  121289. 16,16,13,16,12,11,10,16,12,11, 9, 6,15,12,11,13,
  121290. 16,16,14,14,13,11,12,16,12, 9, 9,13,13,10,10,12,
  121291. 17,18,17,17,14,15,14,16,14,12,14,15,12,10,11,12,
  121292. 18,18,18,18,18,18,18,18,18,12,13,18,16,11, 9,18,
  121293. };
  121294. static static_codebook _huff_book_line_256x4low_class0 = {
  121295. 1, 256,
  121296. _huff_lengthlist_line_256x4low_class0,
  121297. 0, 0, 0, 0, 0,
  121298. NULL,
  121299. NULL,
  121300. NULL,
  121301. NULL,
  121302. 0
  121303. };
  121304. static long _huff_lengthlist_line_256x4low_0sub0[] = {
  121305. 1, 3, 2, 3,
  121306. };
  121307. static static_codebook _huff_book_line_256x4low_0sub0 = {
  121308. 1, 4,
  121309. _huff_lengthlist_line_256x4low_0sub0,
  121310. 0, 0, 0, 0, 0,
  121311. NULL,
  121312. NULL,
  121313. NULL,
  121314. NULL,
  121315. 0
  121316. };
  121317. static long _huff_lengthlist_line_256x4low_0sub1[] = {
  121318. 0, 0, 0, 0, 2, 3, 2, 3, 3, 3,
  121319. };
  121320. static static_codebook _huff_book_line_256x4low_0sub1 = {
  121321. 1, 10,
  121322. _huff_lengthlist_line_256x4low_0sub1,
  121323. 0, 0, 0, 0, 0,
  121324. NULL,
  121325. NULL,
  121326. NULL,
  121327. NULL,
  121328. 0
  121329. };
  121330. static long _huff_lengthlist_line_256x4low_0sub2[] = {
  121331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 3, 4,
  121332. 4, 4, 4, 4, 5, 5, 5, 6, 6,
  121333. };
  121334. static static_codebook _huff_book_line_256x4low_0sub2 = {
  121335. 1, 25,
  121336. _huff_lengthlist_line_256x4low_0sub2,
  121337. 0, 0, 0, 0, 0,
  121338. NULL,
  121339. NULL,
  121340. NULL,
  121341. NULL,
  121342. 0
  121343. };
  121344. static long _huff_lengthlist_line_256x4low_0sub3[] = {
  121345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 2, 4, 3, 5, 4,
  121347. 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 7, 7, 8, 6, 9,
  121348. 7,12,11,16,13,16,12,15,13,15,12,14,12,15,15,15,
  121349. };
  121350. static static_codebook _huff_book_line_256x4low_0sub3 = {
  121351. 1, 64,
  121352. _huff_lengthlist_line_256x4low_0sub3,
  121353. 0, 0, 0, 0, 0,
  121354. NULL,
  121355. NULL,
  121356. NULL,
  121357. NULL,
  121358. 0
  121359. };
  121360. /*** End of inlined file: floor_books.h ***/
  121361. static static_codebook *_floor_128x4_books[]={
  121362. &_huff_book_line_128x4_class0,
  121363. &_huff_book_line_128x4_0sub0,
  121364. &_huff_book_line_128x4_0sub1,
  121365. &_huff_book_line_128x4_0sub2,
  121366. &_huff_book_line_128x4_0sub3,
  121367. };
  121368. static static_codebook *_floor_256x4_books[]={
  121369. &_huff_book_line_256x4_class0,
  121370. &_huff_book_line_256x4_0sub0,
  121371. &_huff_book_line_256x4_0sub1,
  121372. &_huff_book_line_256x4_0sub2,
  121373. &_huff_book_line_256x4_0sub3,
  121374. };
  121375. static static_codebook *_floor_128x7_books[]={
  121376. &_huff_book_line_128x7_class0,
  121377. &_huff_book_line_128x7_class1,
  121378. &_huff_book_line_128x7_0sub1,
  121379. &_huff_book_line_128x7_0sub2,
  121380. &_huff_book_line_128x7_0sub3,
  121381. &_huff_book_line_128x7_1sub1,
  121382. &_huff_book_line_128x7_1sub2,
  121383. &_huff_book_line_128x7_1sub3,
  121384. };
  121385. static static_codebook *_floor_256x7_books[]={
  121386. &_huff_book_line_256x7_class0,
  121387. &_huff_book_line_256x7_class1,
  121388. &_huff_book_line_256x7_0sub1,
  121389. &_huff_book_line_256x7_0sub2,
  121390. &_huff_book_line_256x7_0sub3,
  121391. &_huff_book_line_256x7_1sub1,
  121392. &_huff_book_line_256x7_1sub2,
  121393. &_huff_book_line_256x7_1sub3,
  121394. };
  121395. static static_codebook *_floor_128x11_books[]={
  121396. &_huff_book_line_128x11_class1,
  121397. &_huff_book_line_128x11_class2,
  121398. &_huff_book_line_128x11_class3,
  121399. &_huff_book_line_128x11_0sub0,
  121400. &_huff_book_line_128x11_1sub0,
  121401. &_huff_book_line_128x11_1sub1,
  121402. &_huff_book_line_128x11_2sub1,
  121403. &_huff_book_line_128x11_2sub2,
  121404. &_huff_book_line_128x11_2sub3,
  121405. &_huff_book_line_128x11_3sub1,
  121406. &_huff_book_line_128x11_3sub2,
  121407. &_huff_book_line_128x11_3sub3,
  121408. };
  121409. static static_codebook *_floor_128x17_books[]={
  121410. &_huff_book_line_128x17_class1,
  121411. &_huff_book_line_128x17_class2,
  121412. &_huff_book_line_128x17_class3,
  121413. &_huff_book_line_128x17_0sub0,
  121414. &_huff_book_line_128x17_1sub0,
  121415. &_huff_book_line_128x17_1sub1,
  121416. &_huff_book_line_128x17_2sub1,
  121417. &_huff_book_line_128x17_2sub2,
  121418. &_huff_book_line_128x17_2sub3,
  121419. &_huff_book_line_128x17_3sub1,
  121420. &_huff_book_line_128x17_3sub2,
  121421. &_huff_book_line_128x17_3sub3,
  121422. };
  121423. static static_codebook *_floor_256x4low_books[]={
  121424. &_huff_book_line_256x4low_class0,
  121425. &_huff_book_line_256x4low_0sub0,
  121426. &_huff_book_line_256x4low_0sub1,
  121427. &_huff_book_line_256x4low_0sub2,
  121428. &_huff_book_line_256x4low_0sub3,
  121429. };
  121430. static static_codebook *_floor_1024x27_books[]={
  121431. &_huff_book_line_1024x27_class1,
  121432. &_huff_book_line_1024x27_class2,
  121433. &_huff_book_line_1024x27_class3,
  121434. &_huff_book_line_1024x27_class4,
  121435. &_huff_book_line_1024x27_0sub0,
  121436. &_huff_book_line_1024x27_1sub0,
  121437. &_huff_book_line_1024x27_1sub1,
  121438. &_huff_book_line_1024x27_2sub0,
  121439. &_huff_book_line_1024x27_2sub1,
  121440. &_huff_book_line_1024x27_3sub1,
  121441. &_huff_book_line_1024x27_3sub2,
  121442. &_huff_book_line_1024x27_3sub3,
  121443. &_huff_book_line_1024x27_4sub1,
  121444. &_huff_book_line_1024x27_4sub2,
  121445. &_huff_book_line_1024x27_4sub3,
  121446. };
  121447. static static_codebook *_floor_2048x27_books[]={
  121448. &_huff_book_line_2048x27_class1,
  121449. &_huff_book_line_2048x27_class2,
  121450. &_huff_book_line_2048x27_class3,
  121451. &_huff_book_line_2048x27_class4,
  121452. &_huff_book_line_2048x27_0sub0,
  121453. &_huff_book_line_2048x27_1sub0,
  121454. &_huff_book_line_2048x27_1sub1,
  121455. &_huff_book_line_2048x27_2sub0,
  121456. &_huff_book_line_2048x27_2sub1,
  121457. &_huff_book_line_2048x27_3sub1,
  121458. &_huff_book_line_2048x27_3sub2,
  121459. &_huff_book_line_2048x27_3sub3,
  121460. &_huff_book_line_2048x27_4sub1,
  121461. &_huff_book_line_2048x27_4sub2,
  121462. &_huff_book_line_2048x27_4sub3,
  121463. };
  121464. static static_codebook *_floor_512x17_books[]={
  121465. &_huff_book_line_512x17_class1,
  121466. &_huff_book_line_512x17_class2,
  121467. &_huff_book_line_512x17_class3,
  121468. &_huff_book_line_512x17_0sub0,
  121469. &_huff_book_line_512x17_1sub0,
  121470. &_huff_book_line_512x17_1sub1,
  121471. &_huff_book_line_512x17_2sub1,
  121472. &_huff_book_line_512x17_2sub2,
  121473. &_huff_book_line_512x17_2sub3,
  121474. &_huff_book_line_512x17_3sub1,
  121475. &_huff_book_line_512x17_3sub2,
  121476. &_huff_book_line_512x17_3sub3,
  121477. };
  121478. static static_codebook **_floor_books[10]={
  121479. _floor_128x4_books,
  121480. _floor_256x4_books,
  121481. _floor_128x7_books,
  121482. _floor_256x7_books,
  121483. _floor_128x11_books,
  121484. _floor_128x17_books,
  121485. _floor_256x4low_books,
  121486. _floor_1024x27_books,
  121487. _floor_2048x27_books,
  121488. _floor_512x17_books,
  121489. };
  121490. static vorbis_info_floor1 _floor[10]={
  121491. /* 128 x 4 */
  121492. {
  121493. 1,{0},{4},{2},{0},
  121494. {{1,2,3,4}},
  121495. 4,{0,128, 33,8,16,70},
  121496. 60,30,500, 1.,18., -1
  121497. },
  121498. /* 256 x 4 */
  121499. {
  121500. 1,{0},{4},{2},{0},
  121501. {{1,2,3,4}},
  121502. 4,{0,256, 66,16,32,140},
  121503. 60,30,500, 1.,18., -1
  121504. },
  121505. /* 128 x 7 */
  121506. {
  121507. 2,{0,1},{3,4},{2,2},{0,1},
  121508. {{-1,2,3,4},{-1,5,6,7}},
  121509. 4,{0,128, 14,4,58, 2,8,28,90},
  121510. 60,30,500, 1.,18., -1
  121511. },
  121512. /* 256 x 7 */
  121513. {
  121514. 2,{0,1},{3,4},{2,2},{0,1},
  121515. {{-1,2,3,4},{-1,5,6,7}},
  121516. 4,{0,256, 28,8,116, 4,16,56,180},
  121517. 60,30,500, 1.,18., -1
  121518. },
  121519. /* 128 x 11 */
  121520. {
  121521. 4,{0,1,2,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  121522. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  121523. 2,{0,128, 8,33, 4,16,70, 2,6,12, 23,46,90},
  121524. 60,30,500, 1,18., -1
  121525. },
  121526. /* 128 x 17 */
  121527. {
  121528. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  121529. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  121530. 2,{0,128, 12,46, 4,8,16, 23,33,70, 2,6,10, 14,19,28, 39,58,90},
  121531. 60,30,500, 1,18., -1
  121532. },
  121533. /* 256 x 4 (low bitrate version) */
  121534. {
  121535. 1,{0},{4},{2},{0},
  121536. {{1,2,3,4}},
  121537. 4,{0,256, 66,16,32,140},
  121538. 60,30,500, 1.,18., -1
  121539. },
  121540. /* 1024 x 27 */
  121541. {
  121542. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  121543. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  121544. 2,{0,1024, 93,23,372, 6,46,186,750, 14,33,65, 130,260,556,
  121545. 3,10,18,28, 39,55,79,111, 158,220,312, 464,650,850},
  121546. 60,30,500, 3,18., -1 /* lowpass */
  121547. },
  121548. /* 2048 x 27 */
  121549. {
  121550. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  121551. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  121552. 2,{0,2048, 186,46,744, 12,92,372,1500, 28,66,130, 260,520,1112,
  121553. 6,20,36,56, 78,110,158,222, 316,440,624, 928,1300,1700},
  121554. 60,30,500, 3,18., -1 /* lowpass */
  121555. },
  121556. /* 512 x 17 */
  121557. {
  121558. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  121559. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  121560. 2,{0,512, 46,186, 16,33,65, 93,130,278,
  121561. 7,23,39, 55,79,110, 156,232,360},
  121562. 60,30,500, 1,18., -1 /* lowpass! */
  121563. },
  121564. };
  121565. /*** End of inlined file: floor_all.h ***/
  121566. /*** Start of inlined file: residue_44.h ***/
  121567. /*** Start of inlined file: res_books_stereo.h ***/
  121568. static long _vq_quantlist__16c0_s_p1_0[] = {
  121569. 1,
  121570. 0,
  121571. 2,
  121572. };
  121573. static long _vq_lengthlist__16c0_s_p1_0[] = {
  121574. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  121575. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121579. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0,
  121580. 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121584. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  121585. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  121620. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  121621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0, 0,
  121625. 0, 0, 0, 9, 9,12, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  121626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0,
  121630. 0, 0, 0, 0, 9,12,10, 0, 0, 0, 0, 0, 0,10,11,12,
  121631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121665. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  121666. 0, 0, 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121670. 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  121671. 0, 0, 0, 0, 0, 9,10,12, 0, 0, 0, 0, 0, 0, 0, 0,
  121672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121675. 0, 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,12,
  121676. 0, 0, 0, 0, 0, 0, 9,12, 9, 0, 0, 0, 0, 0, 0, 0,
  121677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 0, 0, 0, 0, 0, 0, 0,
  121851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121984. 0,
  121985. };
  121986. static float _vq_quantthresh__16c0_s_p1_0[] = {
  121987. -0.5, 0.5,
  121988. };
  121989. static long _vq_quantmap__16c0_s_p1_0[] = {
  121990. 1, 0, 2,
  121991. };
  121992. static encode_aux_threshmatch _vq_auxt__16c0_s_p1_0 = {
  121993. _vq_quantthresh__16c0_s_p1_0,
  121994. _vq_quantmap__16c0_s_p1_0,
  121995. 3,
  121996. 3
  121997. };
  121998. static static_codebook _16c0_s_p1_0 = {
  121999. 8, 6561,
  122000. _vq_lengthlist__16c0_s_p1_0,
  122001. 1, -535822336, 1611661312, 2, 0,
  122002. _vq_quantlist__16c0_s_p1_0,
  122003. NULL,
  122004. &_vq_auxt__16c0_s_p1_0,
  122005. NULL,
  122006. 0
  122007. };
  122008. static long _vq_quantlist__16c0_s_p2_0[] = {
  122009. 2,
  122010. 1,
  122011. 3,
  122012. 0,
  122013. 4,
  122014. };
  122015. static long _vq_lengthlist__16c0_s_p2_0[] = {
  122016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122055. 0,
  122056. };
  122057. static float _vq_quantthresh__16c0_s_p2_0[] = {
  122058. -1.5, -0.5, 0.5, 1.5,
  122059. };
  122060. static long _vq_quantmap__16c0_s_p2_0[] = {
  122061. 3, 1, 0, 2, 4,
  122062. };
  122063. static encode_aux_threshmatch _vq_auxt__16c0_s_p2_0 = {
  122064. _vq_quantthresh__16c0_s_p2_0,
  122065. _vq_quantmap__16c0_s_p2_0,
  122066. 5,
  122067. 5
  122068. };
  122069. static static_codebook _16c0_s_p2_0 = {
  122070. 4, 625,
  122071. _vq_lengthlist__16c0_s_p2_0,
  122072. 1, -533725184, 1611661312, 3, 0,
  122073. _vq_quantlist__16c0_s_p2_0,
  122074. NULL,
  122075. &_vq_auxt__16c0_s_p2_0,
  122076. NULL,
  122077. 0
  122078. };
  122079. static long _vq_quantlist__16c0_s_p3_0[] = {
  122080. 2,
  122081. 1,
  122082. 3,
  122083. 0,
  122084. 4,
  122085. };
  122086. static long _vq_lengthlist__16c0_s_p3_0[] = {
  122087. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 7, 6, 0, 0,
  122089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122090. 0, 0, 4, 6, 6, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  122092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122093. 0, 0, 0, 0, 6, 6, 6, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0,
  122124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122126. 0,
  122127. };
  122128. static float _vq_quantthresh__16c0_s_p3_0[] = {
  122129. -1.5, -0.5, 0.5, 1.5,
  122130. };
  122131. static long _vq_quantmap__16c0_s_p3_0[] = {
  122132. 3, 1, 0, 2, 4,
  122133. };
  122134. static encode_aux_threshmatch _vq_auxt__16c0_s_p3_0 = {
  122135. _vq_quantthresh__16c0_s_p3_0,
  122136. _vq_quantmap__16c0_s_p3_0,
  122137. 5,
  122138. 5
  122139. };
  122140. static static_codebook _16c0_s_p3_0 = {
  122141. 4, 625,
  122142. _vq_lengthlist__16c0_s_p3_0,
  122143. 1, -533725184, 1611661312, 3, 0,
  122144. _vq_quantlist__16c0_s_p3_0,
  122145. NULL,
  122146. &_vq_auxt__16c0_s_p3_0,
  122147. NULL,
  122148. 0
  122149. };
  122150. static long _vq_quantlist__16c0_s_p4_0[] = {
  122151. 4,
  122152. 3,
  122153. 5,
  122154. 2,
  122155. 6,
  122156. 1,
  122157. 7,
  122158. 0,
  122159. 8,
  122160. };
  122161. static long _vq_lengthlist__16c0_s_p4_0[] = {
  122162. 1, 3, 2, 7, 8, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  122163. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  122164. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  122165. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  122166. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122167. 0,
  122168. };
  122169. static float _vq_quantthresh__16c0_s_p4_0[] = {
  122170. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  122171. };
  122172. static long _vq_quantmap__16c0_s_p4_0[] = {
  122173. 7, 5, 3, 1, 0, 2, 4, 6,
  122174. 8,
  122175. };
  122176. static encode_aux_threshmatch _vq_auxt__16c0_s_p4_0 = {
  122177. _vq_quantthresh__16c0_s_p4_0,
  122178. _vq_quantmap__16c0_s_p4_0,
  122179. 9,
  122180. 9
  122181. };
  122182. static static_codebook _16c0_s_p4_0 = {
  122183. 2, 81,
  122184. _vq_lengthlist__16c0_s_p4_0,
  122185. 1, -531628032, 1611661312, 4, 0,
  122186. _vq_quantlist__16c0_s_p4_0,
  122187. NULL,
  122188. &_vq_auxt__16c0_s_p4_0,
  122189. NULL,
  122190. 0
  122191. };
  122192. static long _vq_quantlist__16c0_s_p5_0[] = {
  122193. 4,
  122194. 3,
  122195. 5,
  122196. 2,
  122197. 6,
  122198. 1,
  122199. 7,
  122200. 0,
  122201. 8,
  122202. };
  122203. static long _vq_lengthlist__16c0_s_p5_0[] = {
  122204. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  122205. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 8, 0, 0, 0, 7, 7,
  122206. 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0, 0, 0,
  122207. 8, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  122208. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  122209. 10,
  122210. };
  122211. static float _vq_quantthresh__16c0_s_p5_0[] = {
  122212. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  122213. };
  122214. static long _vq_quantmap__16c0_s_p5_0[] = {
  122215. 7, 5, 3, 1, 0, 2, 4, 6,
  122216. 8,
  122217. };
  122218. static encode_aux_threshmatch _vq_auxt__16c0_s_p5_0 = {
  122219. _vq_quantthresh__16c0_s_p5_0,
  122220. _vq_quantmap__16c0_s_p5_0,
  122221. 9,
  122222. 9
  122223. };
  122224. static static_codebook _16c0_s_p5_0 = {
  122225. 2, 81,
  122226. _vq_lengthlist__16c0_s_p5_0,
  122227. 1, -531628032, 1611661312, 4, 0,
  122228. _vq_quantlist__16c0_s_p5_0,
  122229. NULL,
  122230. &_vq_auxt__16c0_s_p5_0,
  122231. NULL,
  122232. 0
  122233. };
  122234. static long _vq_quantlist__16c0_s_p6_0[] = {
  122235. 8,
  122236. 7,
  122237. 9,
  122238. 6,
  122239. 10,
  122240. 5,
  122241. 11,
  122242. 4,
  122243. 12,
  122244. 3,
  122245. 13,
  122246. 2,
  122247. 14,
  122248. 1,
  122249. 15,
  122250. 0,
  122251. 16,
  122252. };
  122253. static long _vq_lengthlist__16c0_s_p6_0[] = {
  122254. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  122255. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  122256. 11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  122257. 11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  122258. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  122259. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  122260. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  122261. 10,11,11,12,12,12,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  122262. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10,10,10,
  122263. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  122264. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  122265. 9,10,10,11,11,12,12,13,13,13,14, 0, 0, 0, 0, 0,
  122266. 10,10,10,11,11,11,12,12,13,13,13,14, 0, 0, 0, 0,
  122267. 0, 0, 0,10,10,11,11,12,12,13,13,14,14, 0, 0, 0,
  122268. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  122269. 0, 0, 0, 0, 0,11,11,12,12,12,13,13,14,15,14, 0,
  122270. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,14,14,15,
  122271. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,13,14,
  122272. 14,
  122273. };
  122274. static float _vq_quantthresh__16c0_s_p6_0[] = {
  122275. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  122276. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  122277. };
  122278. static long _vq_quantmap__16c0_s_p6_0[] = {
  122279. 15, 13, 11, 9, 7, 5, 3, 1,
  122280. 0, 2, 4, 6, 8, 10, 12, 14,
  122281. 16,
  122282. };
  122283. static encode_aux_threshmatch _vq_auxt__16c0_s_p6_0 = {
  122284. _vq_quantthresh__16c0_s_p6_0,
  122285. _vq_quantmap__16c0_s_p6_0,
  122286. 17,
  122287. 17
  122288. };
  122289. static static_codebook _16c0_s_p6_0 = {
  122290. 2, 289,
  122291. _vq_lengthlist__16c0_s_p6_0,
  122292. 1, -529530880, 1611661312, 5, 0,
  122293. _vq_quantlist__16c0_s_p6_0,
  122294. NULL,
  122295. &_vq_auxt__16c0_s_p6_0,
  122296. NULL,
  122297. 0
  122298. };
  122299. static long _vq_quantlist__16c0_s_p7_0[] = {
  122300. 1,
  122301. 0,
  122302. 2,
  122303. };
  122304. static long _vq_lengthlist__16c0_s_p7_0[] = {
  122305. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,11,10,10,11,
  122306. 11,10, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  122307. 11,11,11,10, 6, 9, 9,11,12,12,11, 9, 9, 6, 9,10,
  122308. 11,12,12,11, 9,10, 7,11,11,11,11,11,12,13,12, 6,
  122309. 9,10,11,10,10,12,13,13, 6,10, 9,11,10,10,11,12,
  122310. 13,
  122311. };
  122312. static float _vq_quantthresh__16c0_s_p7_0[] = {
  122313. -5.5, 5.5,
  122314. };
  122315. static long _vq_quantmap__16c0_s_p7_0[] = {
  122316. 1, 0, 2,
  122317. };
  122318. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_0 = {
  122319. _vq_quantthresh__16c0_s_p7_0,
  122320. _vq_quantmap__16c0_s_p7_0,
  122321. 3,
  122322. 3
  122323. };
  122324. static static_codebook _16c0_s_p7_0 = {
  122325. 4, 81,
  122326. _vq_lengthlist__16c0_s_p7_0,
  122327. 1, -529137664, 1618345984, 2, 0,
  122328. _vq_quantlist__16c0_s_p7_0,
  122329. NULL,
  122330. &_vq_auxt__16c0_s_p7_0,
  122331. NULL,
  122332. 0
  122333. };
  122334. static long _vq_quantlist__16c0_s_p7_1[] = {
  122335. 5,
  122336. 4,
  122337. 6,
  122338. 3,
  122339. 7,
  122340. 2,
  122341. 8,
  122342. 1,
  122343. 9,
  122344. 0,
  122345. 10,
  122346. };
  122347. static long _vq_lengthlist__16c0_s_p7_1[] = {
  122348. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7,
  122349. 8, 8, 8, 9, 9, 9,10,10,10, 6, 7, 8, 8, 8, 8, 9,
  122350. 8,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10, 7,
  122351. 7, 8, 8, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9, 9,
  122352. 9, 9,11,11,11, 8, 8, 9, 9, 9, 9, 9,10,10,11,11,
  122353. 9, 9, 9, 9, 9, 9, 9,10,11,11,11,10,11, 9, 9, 9,
  122354. 9,10, 9,11,11,11,10,11,10,10, 9, 9,10,10,11,11,
  122355. 11,11,11, 9, 9, 9, 9,10,10,
  122356. };
  122357. static float _vq_quantthresh__16c0_s_p7_1[] = {
  122358. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  122359. 3.5, 4.5,
  122360. };
  122361. static long _vq_quantmap__16c0_s_p7_1[] = {
  122362. 9, 7, 5, 3, 1, 0, 2, 4,
  122363. 6, 8, 10,
  122364. };
  122365. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_1 = {
  122366. _vq_quantthresh__16c0_s_p7_1,
  122367. _vq_quantmap__16c0_s_p7_1,
  122368. 11,
  122369. 11
  122370. };
  122371. static static_codebook _16c0_s_p7_1 = {
  122372. 2, 121,
  122373. _vq_lengthlist__16c0_s_p7_1,
  122374. 1, -531365888, 1611661312, 4, 0,
  122375. _vq_quantlist__16c0_s_p7_1,
  122376. NULL,
  122377. &_vq_auxt__16c0_s_p7_1,
  122378. NULL,
  122379. 0
  122380. };
  122381. static long _vq_quantlist__16c0_s_p8_0[] = {
  122382. 6,
  122383. 5,
  122384. 7,
  122385. 4,
  122386. 8,
  122387. 3,
  122388. 9,
  122389. 2,
  122390. 10,
  122391. 1,
  122392. 11,
  122393. 0,
  122394. 12,
  122395. };
  122396. static long _vq_lengthlist__16c0_s_p8_0[] = {
  122397. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8,10,10, 6, 5, 6,
  122398. 8, 8, 8, 8, 8, 8, 8, 9,10,10, 7, 6, 6, 8, 8, 8,
  122399. 8, 8, 8, 8, 8,10,10, 0, 8, 8, 8, 8, 9, 8, 9, 9,
  122400. 9,10,10,10, 0, 9, 8, 8, 8, 9, 9, 8, 8, 9, 9,10,
  122401. 10, 0,12,11, 8, 8, 9, 9, 9, 9,10,10,11,10, 0,12,
  122402. 13, 8, 8, 9,10, 9, 9,11,11,11,12, 0, 0, 0, 8, 8,
  122403. 8, 8,10, 9,12,13,12,14, 0, 0, 0, 8, 8, 8, 9,10,
  122404. 10,12,12,13,14, 0, 0, 0,13,13, 9, 9,11,11, 0, 0,
  122405. 14, 0, 0, 0, 0,14,14,10,10,12,11,12,14,14,14, 0,
  122406. 0, 0, 0, 0,11,11,13,13,14,13,14,14, 0, 0, 0, 0,
  122407. 0,12,13,13,12,13,14,14,14,
  122408. };
  122409. static float _vq_quantthresh__16c0_s_p8_0[] = {
  122410. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  122411. 12.5, 17.5, 22.5, 27.5,
  122412. };
  122413. static long _vq_quantmap__16c0_s_p8_0[] = {
  122414. 11, 9, 7, 5, 3, 1, 0, 2,
  122415. 4, 6, 8, 10, 12,
  122416. };
  122417. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_0 = {
  122418. _vq_quantthresh__16c0_s_p8_0,
  122419. _vq_quantmap__16c0_s_p8_0,
  122420. 13,
  122421. 13
  122422. };
  122423. static static_codebook _16c0_s_p8_0 = {
  122424. 2, 169,
  122425. _vq_lengthlist__16c0_s_p8_0,
  122426. 1, -526516224, 1616117760, 4, 0,
  122427. _vq_quantlist__16c0_s_p8_0,
  122428. NULL,
  122429. &_vq_auxt__16c0_s_p8_0,
  122430. NULL,
  122431. 0
  122432. };
  122433. static long _vq_quantlist__16c0_s_p8_1[] = {
  122434. 2,
  122435. 1,
  122436. 3,
  122437. 0,
  122438. 4,
  122439. };
  122440. static long _vq_lengthlist__16c0_s_p8_1[] = {
  122441. 1, 4, 3, 5, 5, 7, 7, 7, 6, 6, 7, 7, 7, 5, 5, 7,
  122442. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  122443. };
  122444. static float _vq_quantthresh__16c0_s_p8_1[] = {
  122445. -1.5, -0.5, 0.5, 1.5,
  122446. };
  122447. static long _vq_quantmap__16c0_s_p8_1[] = {
  122448. 3, 1, 0, 2, 4,
  122449. };
  122450. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_1 = {
  122451. _vq_quantthresh__16c0_s_p8_1,
  122452. _vq_quantmap__16c0_s_p8_1,
  122453. 5,
  122454. 5
  122455. };
  122456. static static_codebook _16c0_s_p8_1 = {
  122457. 2, 25,
  122458. _vq_lengthlist__16c0_s_p8_1,
  122459. 1, -533725184, 1611661312, 3, 0,
  122460. _vq_quantlist__16c0_s_p8_1,
  122461. NULL,
  122462. &_vq_auxt__16c0_s_p8_1,
  122463. NULL,
  122464. 0
  122465. };
  122466. static long _vq_quantlist__16c0_s_p9_0[] = {
  122467. 1,
  122468. 0,
  122469. 2,
  122470. };
  122471. static long _vq_lengthlist__16c0_s_p9_0[] = {
  122472. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  122473. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  122474. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122475. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122476. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122477. 7,
  122478. };
  122479. static float _vq_quantthresh__16c0_s_p9_0[] = {
  122480. -157.5, 157.5,
  122481. };
  122482. static long _vq_quantmap__16c0_s_p9_0[] = {
  122483. 1, 0, 2,
  122484. };
  122485. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_0 = {
  122486. _vq_quantthresh__16c0_s_p9_0,
  122487. _vq_quantmap__16c0_s_p9_0,
  122488. 3,
  122489. 3
  122490. };
  122491. static static_codebook _16c0_s_p9_0 = {
  122492. 4, 81,
  122493. _vq_lengthlist__16c0_s_p9_0,
  122494. 1, -518803456, 1628680192, 2, 0,
  122495. _vq_quantlist__16c0_s_p9_0,
  122496. NULL,
  122497. &_vq_auxt__16c0_s_p9_0,
  122498. NULL,
  122499. 0
  122500. };
  122501. static long _vq_quantlist__16c0_s_p9_1[] = {
  122502. 7,
  122503. 6,
  122504. 8,
  122505. 5,
  122506. 9,
  122507. 4,
  122508. 10,
  122509. 3,
  122510. 11,
  122511. 2,
  122512. 12,
  122513. 1,
  122514. 13,
  122515. 0,
  122516. 14,
  122517. };
  122518. static long _vq_lengthlist__16c0_s_p9_1[] = {
  122519. 1, 5, 5, 5, 5, 9,11,11,10,10,10,10,10,10,10, 7,
  122520. 6, 6, 6, 6,10,10,10,10,10,10,10,10,10,10, 7, 6,
  122521. 6, 6, 6,10, 9,10,10,10,10,10,10,10,10,10, 7, 7,
  122522. 8, 9,10,10,10,10,10,10,10,10,10,10,10, 8, 7,10,
  122523. 10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122524. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122525. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122526. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122527. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122528. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122529. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122530. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122531. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122532. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122533. 10,
  122534. };
  122535. static float _vq_quantthresh__16c0_s_p9_1[] = {
  122536. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  122537. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  122538. };
  122539. static long _vq_quantmap__16c0_s_p9_1[] = {
  122540. 13, 11, 9, 7, 5, 3, 1, 0,
  122541. 2, 4, 6, 8, 10, 12, 14,
  122542. };
  122543. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_1 = {
  122544. _vq_quantthresh__16c0_s_p9_1,
  122545. _vq_quantmap__16c0_s_p9_1,
  122546. 15,
  122547. 15
  122548. };
  122549. static static_codebook _16c0_s_p9_1 = {
  122550. 2, 225,
  122551. _vq_lengthlist__16c0_s_p9_1,
  122552. 1, -520986624, 1620377600, 4, 0,
  122553. _vq_quantlist__16c0_s_p9_1,
  122554. NULL,
  122555. &_vq_auxt__16c0_s_p9_1,
  122556. NULL,
  122557. 0
  122558. };
  122559. static long _vq_quantlist__16c0_s_p9_2[] = {
  122560. 10,
  122561. 9,
  122562. 11,
  122563. 8,
  122564. 12,
  122565. 7,
  122566. 13,
  122567. 6,
  122568. 14,
  122569. 5,
  122570. 15,
  122571. 4,
  122572. 16,
  122573. 3,
  122574. 17,
  122575. 2,
  122576. 18,
  122577. 1,
  122578. 19,
  122579. 0,
  122580. 20,
  122581. };
  122582. static long _vq_lengthlist__16c0_s_p9_2[] = {
  122583. 1, 5, 5, 7, 8, 8, 7, 9, 9, 9,12,12,11,12,12,10,
  122584. 10,11,12,12,12,11,12,12, 8, 9, 8, 7, 9,10,10,11,
  122585. 11,10,11,12,10,12,10,12,12,12,11,12,11, 9, 8, 8,
  122586. 9,10, 9, 8, 9,10,12,12,11,11,12,11,10,11,12,11,
  122587. 12,12, 8, 9, 9, 9,10,11,12,11,12,11,11,11,11,12,
  122588. 12,11,11,12,12,11,11, 9, 9, 8, 9, 9,11, 9, 9,10,
  122589. 9,11,11,11,11,12,11,11,10,12,12,12, 9,12,11,10,
  122590. 11,11,11,11,12,12,12,11,11,11,12,10,12,12,12,10,
  122591. 10, 9,10, 9,10,10, 9, 9, 9,10,10,12,10,11,11, 9,
  122592. 11,11,10,11,11,11,10,10,10, 9, 9,10,10, 9, 9,10,
  122593. 11,11,10,11,10,11,10,11,11,10,11,11,11,10, 9,10,
  122594. 10, 9,10, 9, 9,11, 9, 9,11,10,10,11,11,10,10,11,
  122595. 10,11, 8, 9,11,11,10, 9,10,11,11,10,11,11,10,10,
  122596. 10,11,10, 9,10,10,11, 9,10,10, 9,11,10,10,10,10,
  122597. 11,10,11,11, 9,11,10,11,10,10,11,11,10,10,10, 9,
  122598. 10,10,11,11,11, 9,10,10,10,10,10,11,10,10,10, 9,
  122599. 10,10,11,10,10,10,10,10, 9,10,11,10,10,10,10,11,
  122600. 11,11,10,10,10,10,10,11,10,11,10,11,10,10,10, 9,
  122601. 11,11,10,10,10,11,11,10,10,10,10,10,10,10,10,11,
  122602. 11, 9,10,10,10,11,10,11,10,10,10,11, 9,10,11,10,
  122603. 11,10,10, 9,10,10,10,11,10,11,10,10,10,10,10,11,
  122604. 11,10,11,11,10,10,11,11,10, 9, 9,10,10,10,10,10,
  122605. 9,11, 9,10,10,10,11,11,10,10,10,10,11,11,11,10,
  122606. 9, 9,10,10,11,10,10,10,10,10,11,11,11,10,10,10,
  122607. 11,11,11, 9,10,10,10,10, 9,10, 9,10,11,10,11,10,
  122608. 10,11,11,10,11,11,11,11,11,10,11,10,10,10, 9,11,
  122609. 11,10,11,11,11,11,11,11,11,11,11,10,11,10,10,10,
  122610. 10,11,10,10,11, 9,10,10,10,
  122611. };
  122612. static float _vq_quantthresh__16c0_s_p9_2[] = {
  122613. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  122614. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  122615. 6.5, 7.5, 8.5, 9.5,
  122616. };
  122617. static long _vq_quantmap__16c0_s_p9_2[] = {
  122618. 19, 17, 15, 13, 11, 9, 7, 5,
  122619. 3, 1, 0, 2, 4, 6, 8, 10,
  122620. 12, 14, 16, 18, 20,
  122621. };
  122622. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_2 = {
  122623. _vq_quantthresh__16c0_s_p9_2,
  122624. _vq_quantmap__16c0_s_p9_2,
  122625. 21,
  122626. 21
  122627. };
  122628. static static_codebook _16c0_s_p9_2 = {
  122629. 2, 441,
  122630. _vq_lengthlist__16c0_s_p9_2,
  122631. 1, -529268736, 1611661312, 5, 0,
  122632. _vq_quantlist__16c0_s_p9_2,
  122633. NULL,
  122634. &_vq_auxt__16c0_s_p9_2,
  122635. NULL,
  122636. 0
  122637. };
  122638. static long _huff_lengthlist__16c0_s_single[] = {
  122639. 3, 4,19, 7, 9, 7, 8,11, 9,12, 4, 1,19, 6, 7, 7,
  122640. 8,10,11,13,18,18,18,18,18,18,18,18,18,18, 8, 6,
  122641. 18, 8, 9, 9,11,12,14,18, 9, 6,18, 9, 7, 8, 9,11,
  122642. 12,18, 7, 6,18, 8, 7, 7, 7, 9,11,17, 8, 8,18, 9,
  122643. 7, 6, 6, 8,11,17,10,10,18,12, 9, 8, 7, 9,12,18,
  122644. 13,15,18,15,13,11,10,11,15,18,14,18,18,18,18,18,
  122645. 16,16,18,18,
  122646. };
  122647. static static_codebook _huff_book__16c0_s_single = {
  122648. 2, 100,
  122649. _huff_lengthlist__16c0_s_single,
  122650. 0, 0, 0, 0, 0,
  122651. NULL,
  122652. NULL,
  122653. NULL,
  122654. NULL,
  122655. 0
  122656. };
  122657. static long _huff_lengthlist__16c1_s_long[] = {
  122658. 2, 5,20, 7,10, 7, 8,10,11,11, 4, 2,20, 5, 8, 6,
  122659. 7, 9,10,10,20,20,20,20,19,19,19,19,19,19, 7, 5,
  122660. 19, 6,10, 7, 9,11,13,17,11, 8,19,10, 7, 7, 8,10,
  122661. 11,15, 7, 5,19, 7, 7, 5, 6, 9,11,16, 7, 6,19, 8,
  122662. 7, 6, 6, 7, 9,13, 9, 9,19,11, 9, 8, 6, 7, 8,13,
  122663. 12,14,19,16,13,10, 9, 8, 9,13,14,17,19,18,18,17,
  122664. 12,11,11,13,
  122665. };
  122666. static static_codebook _huff_book__16c1_s_long = {
  122667. 2, 100,
  122668. _huff_lengthlist__16c1_s_long,
  122669. 0, 0, 0, 0, 0,
  122670. NULL,
  122671. NULL,
  122672. NULL,
  122673. NULL,
  122674. 0
  122675. };
  122676. static long _vq_quantlist__16c1_s_p1_0[] = {
  122677. 1,
  122678. 0,
  122679. 2,
  122680. };
  122681. static long _vq_lengthlist__16c1_s_p1_0[] = {
  122682. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  122683. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122687. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  122688. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122692. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  122693. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  122728. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  122729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  122733. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  122734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  122738. 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  122739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122773. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  122774. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122778. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  122779. 0, 0, 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  122780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122783. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  122784. 0, 0, 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 0,
  122785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123092. 0,
  123093. };
  123094. static float _vq_quantthresh__16c1_s_p1_0[] = {
  123095. -0.5, 0.5,
  123096. };
  123097. static long _vq_quantmap__16c1_s_p1_0[] = {
  123098. 1, 0, 2,
  123099. };
  123100. static encode_aux_threshmatch _vq_auxt__16c1_s_p1_0 = {
  123101. _vq_quantthresh__16c1_s_p1_0,
  123102. _vq_quantmap__16c1_s_p1_0,
  123103. 3,
  123104. 3
  123105. };
  123106. static static_codebook _16c1_s_p1_0 = {
  123107. 8, 6561,
  123108. _vq_lengthlist__16c1_s_p1_0,
  123109. 1, -535822336, 1611661312, 2, 0,
  123110. _vq_quantlist__16c1_s_p1_0,
  123111. NULL,
  123112. &_vq_auxt__16c1_s_p1_0,
  123113. NULL,
  123114. 0
  123115. };
  123116. static long _vq_quantlist__16c1_s_p2_0[] = {
  123117. 2,
  123118. 1,
  123119. 3,
  123120. 0,
  123121. 4,
  123122. };
  123123. static long _vq_lengthlist__16c1_s_p2_0[] = {
  123124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123163. 0,
  123164. };
  123165. static float _vq_quantthresh__16c1_s_p2_0[] = {
  123166. -1.5, -0.5, 0.5, 1.5,
  123167. };
  123168. static long _vq_quantmap__16c1_s_p2_0[] = {
  123169. 3, 1, 0, 2, 4,
  123170. };
  123171. static encode_aux_threshmatch _vq_auxt__16c1_s_p2_0 = {
  123172. _vq_quantthresh__16c1_s_p2_0,
  123173. _vq_quantmap__16c1_s_p2_0,
  123174. 5,
  123175. 5
  123176. };
  123177. static static_codebook _16c1_s_p2_0 = {
  123178. 4, 625,
  123179. _vq_lengthlist__16c1_s_p2_0,
  123180. 1, -533725184, 1611661312, 3, 0,
  123181. _vq_quantlist__16c1_s_p2_0,
  123182. NULL,
  123183. &_vq_auxt__16c1_s_p2_0,
  123184. NULL,
  123185. 0
  123186. };
  123187. static long _vq_quantlist__16c1_s_p3_0[] = {
  123188. 2,
  123189. 1,
  123190. 3,
  123191. 0,
  123192. 4,
  123193. };
  123194. static long _vq_lengthlist__16c1_s_p3_0[] = {
  123195. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  123197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123198. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 7, 9, 9,
  123200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123201. 0, 0, 0, 0, 6, 7, 7, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0,
  123232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123234. 0,
  123235. };
  123236. static float _vq_quantthresh__16c1_s_p3_0[] = {
  123237. -1.5, -0.5, 0.5, 1.5,
  123238. };
  123239. static long _vq_quantmap__16c1_s_p3_0[] = {
  123240. 3, 1, 0, 2, 4,
  123241. };
  123242. static encode_aux_threshmatch _vq_auxt__16c1_s_p3_0 = {
  123243. _vq_quantthresh__16c1_s_p3_0,
  123244. _vq_quantmap__16c1_s_p3_0,
  123245. 5,
  123246. 5
  123247. };
  123248. static static_codebook _16c1_s_p3_0 = {
  123249. 4, 625,
  123250. _vq_lengthlist__16c1_s_p3_0,
  123251. 1, -533725184, 1611661312, 3, 0,
  123252. _vq_quantlist__16c1_s_p3_0,
  123253. NULL,
  123254. &_vq_auxt__16c1_s_p3_0,
  123255. NULL,
  123256. 0
  123257. };
  123258. static long _vq_quantlist__16c1_s_p4_0[] = {
  123259. 4,
  123260. 3,
  123261. 5,
  123262. 2,
  123263. 6,
  123264. 1,
  123265. 7,
  123266. 0,
  123267. 8,
  123268. };
  123269. static long _vq_lengthlist__16c1_s_p4_0[] = {
  123270. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  123271. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  123272. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  123273. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 9, 0, 0, 0, 0, 0,
  123274. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123275. 0,
  123276. };
  123277. static float _vq_quantthresh__16c1_s_p4_0[] = {
  123278. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123279. };
  123280. static long _vq_quantmap__16c1_s_p4_0[] = {
  123281. 7, 5, 3, 1, 0, 2, 4, 6,
  123282. 8,
  123283. };
  123284. static encode_aux_threshmatch _vq_auxt__16c1_s_p4_0 = {
  123285. _vq_quantthresh__16c1_s_p4_0,
  123286. _vq_quantmap__16c1_s_p4_0,
  123287. 9,
  123288. 9
  123289. };
  123290. static static_codebook _16c1_s_p4_0 = {
  123291. 2, 81,
  123292. _vq_lengthlist__16c1_s_p4_0,
  123293. 1, -531628032, 1611661312, 4, 0,
  123294. _vq_quantlist__16c1_s_p4_0,
  123295. NULL,
  123296. &_vq_auxt__16c1_s_p4_0,
  123297. NULL,
  123298. 0
  123299. };
  123300. static long _vq_quantlist__16c1_s_p5_0[] = {
  123301. 4,
  123302. 3,
  123303. 5,
  123304. 2,
  123305. 6,
  123306. 1,
  123307. 7,
  123308. 0,
  123309. 8,
  123310. };
  123311. static long _vq_lengthlist__16c1_s_p5_0[] = {
  123312. 1, 3, 3, 5, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  123313. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 8, 8,
  123314. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  123315. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  123316. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  123317. 10,
  123318. };
  123319. static float _vq_quantthresh__16c1_s_p5_0[] = {
  123320. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123321. };
  123322. static long _vq_quantmap__16c1_s_p5_0[] = {
  123323. 7, 5, 3, 1, 0, 2, 4, 6,
  123324. 8,
  123325. };
  123326. static encode_aux_threshmatch _vq_auxt__16c1_s_p5_0 = {
  123327. _vq_quantthresh__16c1_s_p5_0,
  123328. _vq_quantmap__16c1_s_p5_0,
  123329. 9,
  123330. 9
  123331. };
  123332. static static_codebook _16c1_s_p5_0 = {
  123333. 2, 81,
  123334. _vq_lengthlist__16c1_s_p5_0,
  123335. 1, -531628032, 1611661312, 4, 0,
  123336. _vq_quantlist__16c1_s_p5_0,
  123337. NULL,
  123338. &_vq_auxt__16c1_s_p5_0,
  123339. NULL,
  123340. 0
  123341. };
  123342. static long _vq_quantlist__16c1_s_p6_0[] = {
  123343. 8,
  123344. 7,
  123345. 9,
  123346. 6,
  123347. 10,
  123348. 5,
  123349. 11,
  123350. 4,
  123351. 12,
  123352. 3,
  123353. 13,
  123354. 2,
  123355. 14,
  123356. 1,
  123357. 15,
  123358. 0,
  123359. 16,
  123360. };
  123361. static long _vq_lengthlist__16c1_s_p6_0[] = {
  123362. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,12,
  123363. 12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  123364. 12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  123365. 11,12,12, 0, 0, 0, 8, 8, 8, 9,10, 9,10,10,10,10,
  123366. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,11,
  123367. 11,11,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  123368. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  123369. 10,11,11,12,12,13,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  123370. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  123371. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  123372. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  123373. 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0,
  123374. 10,10,11,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0,
  123375. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  123376. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  123377. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0,
  123378. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  123379. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  123380. 14,
  123381. };
  123382. static float _vq_quantthresh__16c1_s_p6_0[] = {
  123383. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  123384. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  123385. };
  123386. static long _vq_quantmap__16c1_s_p6_0[] = {
  123387. 15, 13, 11, 9, 7, 5, 3, 1,
  123388. 0, 2, 4, 6, 8, 10, 12, 14,
  123389. 16,
  123390. };
  123391. static encode_aux_threshmatch _vq_auxt__16c1_s_p6_0 = {
  123392. _vq_quantthresh__16c1_s_p6_0,
  123393. _vq_quantmap__16c1_s_p6_0,
  123394. 17,
  123395. 17
  123396. };
  123397. static static_codebook _16c1_s_p6_0 = {
  123398. 2, 289,
  123399. _vq_lengthlist__16c1_s_p6_0,
  123400. 1, -529530880, 1611661312, 5, 0,
  123401. _vq_quantlist__16c1_s_p6_0,
  123402. NULL,
  123403. &_vq_auxt__16c1_s_p6_0,
  123404. NULL,
  123405. 0
  123406. };
  123407. static long _vq_quantlist__16c1_s_p7_0[] = {
  123408. 1,
  123409. 0,
  123410. 2,
  123411. };
  123412. static long _vq_lengthlist__16c1_s_p7_0[] = {
  123413. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9,10,10,
  123414. 10, 9, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  123415. 11,11,10,10, 6,10, 9,11,11,11,11,10,10, 6,10,10,
  123416. 11,11,11,11,10,10, 7,11,11,11,11,11,12,12,11, 6,
  123417. 10,10,11,10,10,11,11,11, 6,10,10,10,11,10,11,11,
  123418. 11,
  123419. };
  123420. static float _vq_quantthresh__16c1_s_p7_0[] = {
  123421. -5.5, 5.5,
  123422. };
  123423. static long _vq_quantmap__16c1_s_p7_0[] = {
  123424. 1, 0, 2,
  123425. };
  123426. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_0 = {
  123427. _vq_quantthresh__16c1_s_p7_0,
  123428. _vq_quantmap__16c1_s_p7_0,
  123429. 3,
  123430. 3
  123431. };
  123432. static static_codebook _16c1_s_p7_0 = {
  123433. 4, 81,
  123434. _vq_lengthlist__16c1_s_p7_0,
  123435. 1, -529137664, 1618345984, 2, 0,
  123436. _vq_quantlist__16c1_s_p7_0,
  123437. NULL,
  123438. &_vq_auxt__16c1_s_p7_0,
  123439. NULL,
  123440. 0
  123441. };
  123442. static long _vq_quantlist__16c1_s_p7_1[] = {
  123443. 5,
  123444. 4,
  123445. 6,
  123446. 3,
  123447. 7,
  123448. 2,
  123449. 8,
  123450. 1,
  123451. 9,
  123452. 0,
  123453. 10,
  123454. };
  123455. static long _vq_lengthlist__16c1_s_p7_1[] = {
  123456. 2, 3, 3, 5, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  123457. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  123458. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  123459. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  123460. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  123461. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  123462. 8, 9, 9,10,10,10,10,10, 9, 9, 8, 8, 9, 9,10,10,
  123463. 10,10,10, 8, 8, 8, 8, 9, 9,
  123464. };
  123465. static float _vq_quantthresh__16c1_s_p7_1[] = {
  123466. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  123467. 3.5, 4.5,
  123468. };
  123469. static long _vq_quantmap__16c1_s_p7_1[] = {
  123470. 9, 7, 5, 3, 1, 0, 2, 4,
  123471. 6, 8, 10,
  123472. };
  123473. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_1 = {
  123474. _vq_quantthresh__16c1_s_p7_1,
  123475. _vq_quantmap__16c1_s_p7_1,
  123476. 11,
  123477. 11
  123478. };
  123479. static static_codebook _16c1_s_p7_1 = {
  123480. 2, 121,
  123481. _vq_lengthlist__16c1_s_p7_1,
  123482. 1, -531365888, 1611661312, 4, 0,
  123483. _vq_quantlist__16c1_s_p7_1,
  123484. NULL,
  123485. &_vq_auxt__16c1_s_p7_1,
  123486. NULL,
  123487. 0
  123488. };
  123489. static long _vq_quantlist__16c1_s_p8_0[] = {
  123490. 6,
  123491. 5,
  123492. 7,
  123493. 4,
  123494. 8,
  123495. 3,
  123496. 9,
  123497. 2,
  123498. 10,
  123499. 1,
  123500. 11,
  123501. 0,
  123502. 12,
  123503. };
  123504. static long _vq_lengthlist__16c1_s_p8_0[] = {
  123505. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  123506. 7, 8, 8, 9, 8, 8, 9, 9,10,11, 6, 5, 5, 8, 8, 9,
  123507. 9, 8, 8, 9,10,10,11, 0, 8, 8, 8, 9, 9, 9, 9, 9,
  123508. 10,10,11,11, 0, 9, 9, 9, 8, 9, 9, 9, 9,10,10,11,
  123509. 11, 0,13,13, 9, 9,10,10,10,10,11,11,12,12, 0,14,
  123510. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  123511. 9, 9,11,11,12,12,13,12, 0, 0, 0,10,10, 9, 9,10,
  123512. 10,12,12,13,13, 0, 0, 0,13,14,11,10,11,11,12,12,
  123513. 13,14, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  123514. 0, 0, 0, 0,12,12,12,12,13,13,14,15, 0, 0, 0, 0,
  123515. 0,12,12,12,12,13,13,14,15,
  123516. };
  123517. static float _vq_quantthresh__16c1_s_p8_0[] = {
  123518. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  123519. 12.5, 17.5, 22.5, 27.5,
  123520. };
  123521. static long _vq_quantmap__16c1_s_p8_0[] = {
  123522. 11, 9, 7, 5, 3, 1, 0, 2,
  123523. 4, 6, 8, 10, 12,
  123524. };
  123525. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_0 = {
  123526. _vq_quantthresh__16c1_s_p8_0,
  123527. _vq_quantmap__16c1_s_p8_0,
  123528. 13,
  123529. 13
  123530. };
  123531. static static_codebook _16c1_s_p8_0 = {
  123532. 2, 169,
  123533. _vq_lengthlist__16c1_s_p8_0,
  123534. 1, -526516224, 1616117760, 4, 0,
  123535. _vq_quantlist__16c1_s_p8_0,
  123536. NULL,
  123537. &_vq_auxt__16c1_s_p8_0,
  123538. NULL,
  123539. 0
  123540. };
  123541. static long _vq_quantlist__16c1_s_p8_1[] = {
  123542. 2,
  123543. 1,
  123544. 3,
  123545. 0,
  123546. 4,
  123547. };
  123548. static long _vq_lengthlist__16c1_s_p8_1[] = {
  123549. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  123550. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  123551. };
  123552. static float _vq_quantthresh__16c1_s_p8_1[] = {
  123553. -1.5, -0.5, 0.5, 1.5,
  123554. };
  123555. static long _vq_quantmap__16c1_s_p8_1[] = {
  123556. 3, 1, 0, 2, 4,
  123557. };
  123558. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_1 = {
  123559. _vq_quantthresh__16c1_s_p8_1,
  123560. _vq_quantmap__16c1_s_p8_1,
  123561. 5,
  123562. 5
  123563. };
  123564. static static_codebook _16c1_s_p8_1 = {
  123565. 2, 25,
  123566. _vq_lengthlist__16c1_s_p8_1,
  123567. 1, -533725184, 1611661312, 3, 0,
  123568. _vq_quantlist__16c1_s_p8_1,
  123569. NULL,
  123570. &_vq_auxt__16c1_s_p8_1,
  123571. NULL,
  123572. 0
  123573. };
  123574. static long _vq_quantlist__16c1_s_p9_0[] = {
  123575. 6,
  123576. 5,
  123577. 7,
  123578. 4,
  123579. 8,
  123580. 3,
  123581. 9,
  123582. 2,
  123583. 10,
  123584. 1,
  123585. 11,
  123586. 0,
  123587. 12,
  123588. };
  123589. static long _vq_lengthlist__16c1_s_p9_0[] = {
  123590. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  123591. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  123592. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  123593. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  123594. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  123595. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123596. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123597. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123598. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123599. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123600. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123601. };
  123602. static float _vq_quantthresh__16c1_s_p9_0[] = {
  123603. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  123604. 787.5, 1102.5, 1417.5, 1732.5,
  123605. };
  123606. static long _vq_quantmap__16c1_s_p9_0[] = {
  123607. 11, 9, 7, 5, 3, 1, 0, 2,
  123608. 4, 6, 8, 10, 12,
  123609. };
  123610. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_0 = {
  123611. _vq_quantthresh__16c1_s_p9_0,
  123612. _vq_quantmap__16c1_s_p9_0,
  123613. 13,
  123614. 13
  123615. };
  123616. static static_codebook _16c1_s_p9_0 = {
  123617. 2, 169,
  123618. _vq_lengthlist__16c1_s_p9_0,
  123619. 1, -513964032, 1628680192, 4, 0,
  123620. _vq_quantlist__16c1_s_p9_0,
  123621. NULL,
  123622. &_vq_auxt__16c1_s_p9_0,
  123623. NULL,
  123624. 0
  123625. };
  123626. static long _vq_quantlist__16c1_s_p9_1[] = {
  123627. 7,
  123628. 6,
  123629. 8,
  123630. 5,
  123631. 9,
  123632. 4,
  123633. 10,
  123634. 3,
  123635. 11,
  123636. 2,
  123637. 12,
  123638. 1,
  123639. 13,
  123640. 0,
  123641. 14,
  123642. };
  123643. static long _vq_lengthlist__16c1_s_p9_1[] = {
  123644. 1, 4, 4, 4, 4, 8, 8,12,13,14,14,14,14,14,14, 6,
  123645. 6, 6, 6, 6,10, 9,14,14,14,14,14,14,14,14, 7, 6,
  123646. 5, 6, 6,10, 9,12,13,13,13,13,13,13,13,13, 7, 7,
  123647. 9, 9,11,11,12,13,13,13,13,13,13,13,13, 7, 7, 8,
  123648. 8,11,12,13,13,13,13,13,13,13,13,13,12,12,10,10,
  123649. 13,12,13,13,13,13,13,13,13,13,13,12,12,10,10,13,
  123650. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,13,12,
  123651. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  123652. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  123653. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  123654. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  123655. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  123656. 13,13,13,13,13,13,13,13,13,12,13,13,13,13,13,13,
  123657. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  123658. 13,
  123659. };
  123660. static float _vq_quantthresh__16c1_s_p9_1[] = {
  123661. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  123662. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  123663. };
  123664. static long _vq_quantmap__16c1_s_p9_1[] = {
  123665. 13, 11, 9, 7, 5, 3, 1, 0,
  123666. 2, 4, 6, 8, 10, 12, 14,
  123667. };
  123668. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_1 = {
  123669. _vq_quantthresh__16c1_s_p9_1,
  123670. _vq_quantmap__16c1_s_p9_1,
  123671. 15,
  123672. 15
  123673. };
  123674. static static_codebook _16c1_s_p9_1 = {
  123675. 2, 225,
  123676. _vq_lengthlist__16c1_s_p9_1,
  123677. 1, -520986624, 1620377600, 4, 0,
  123678. _vq_quantlist__16c1_s_p9_1,
  123679. NULL,
  123680. &_vq_auxt__16c1_s_p9_1,
  123681. NULL,
  123682. 0
  123683. };
  123684. static long _vq_quantlist__16c1_s_p9_2[] = {
  123685. 10,
  123686. 9,
  123687. 11,
  123688. 8,
  123689. 12,
  123690. 7,
  123691. 13,
  123692. 6,
  123693. 14,
  123694. 5,
  123695. 15,
  123696. 4,
  123697. 16,
  123698. 3,
  123699. 17,
  123700. 2,
  123701. 18,
  123702. 1,
  123703. 19,
  123704. 0,
  123705. 20,
  123706. };
  123707. static long _vq_lengthlist__16c1_s_p9_2[] = {
  123708. 1, 4, 4, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9,10,
  123709. 10,10, 9,10,10,11,12,12, 8, 8, 8, 8, 9, 9, 9, 9,
  123710. 10,10,10,10,10,11,11,10,12,11,11,13,11, 7, 7, 8,
  123711. 8, 8, 8, 9, 9, 9,10,10,10,10, 9,10,10,11,11,12,
  123712. 11,11, 8, 8, 8, 8, 9, 9,10,10,10,10,11,11,11,11,
  123713. 11,11,11,12,11,12,12, 8, 8, 9, 9, 9, 9, 9,10,10,
  123714. 10,10,10,10,11,11,11,11,11,11,12,11, 9, 9, 9, 9,
  123715. 10,10,10,10,11,10,11,11,11,11,11,11,12,12,12,12,
  123716. 11, 9, 9, 9, 9,10,10,10,10,11,11,11,11,11,11,11,
  123717. 11,11,12,12,12,13, 9,10,10, 9,11,10,10,10,10,11,
  123718. 11,11,11,11,10,11,12,11,12,12,11,12,11,10, 9,10,
  123719. 10,11,10,11,11,11,11,11,11,11,11,11,12,12,11,12,
  123720. 12,12,10,10,10,11,10,11,11,11,11,11,11,11,11,11,
  123721. 11,11,12,13,12,12,11, 9,10,10,11,11,10,11,11,11,
  123722. 12,11,11,11,11,11,12,12,13,13,12,13,10,10,12,10,
  123723. 11,11,11,11,11,11,11,11,11,12,12,11,13,12,12,12,
  123724. 12,13,12,11,11,11,11,11,11,12,11,12,11,11,11,11,
  123725. 12,12,13,12,11,12,12,11,11,11,11,11,12,11,11,11,
  123726. 11,12,11,11,12,11,12,13,13,12,12,12,12,11,11,11,
  123727. 11,11,12,11,11,12,11,12,11,11,11,11,13,12,12,12,
  123728. 12,13,11,11,11,12,12,11,11,11,12,11,12,12,12,11,
  123729. 12,13,12,11,11,12,12,11,12,11,11,11,12,12,11,12,
  123730. 11,11,11,12,12,12,12,13,12,13,12,12,12,12,11,11,
  123731. 12,11,11,11,11,11,11,12,12,12,13,12,11,13,13,12,
  123732. 12,11,12,10,11,11,11,11,12,11,12,12,11,12,12,13,
  123733. 12,12,13,12,12,12,12,12,11,12,12,12,11,12,11,11,
  123734. 11,12,13,12,13,13,13,13,13,12,13,13,12,12,13,11,
  123735. 11,11,11,11,12,11,11,12,11,
  123736. };
  123737. static float _vq_quantthresh__16c1_s_p9_2[] = {
  123738. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  123739. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  123740. 6.5, 7.5, 8.5, 9.5,
  123741. };
  123742. static long _vq_quantmap__16c1_s_p9_2[] = {
  123743. 19, 17, 15, 13, 11, 9, 7, 5,
  123744. 3, 1, 0, 2, 4, 6, 8, 10,
  123745. 12, 14, 16, 18, 20,
  123746. };
  123747. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_2 = {
  123748. _vq_quantthresh__16c1_s_p9_2,
  123749. _vq_quantmap__16c1_s_p9_2,
  123750. 21,
  123751. 21
  123752. };
  123753. static static_codebook _16c1_s_p9_2 = {
  123754. 2, 441,
  123755. _vq_lengthlist__16c1_s_p9_2,
  123756. 1, -529268736, 1611661312, 5, 0,
  123757. _vq_quantlist__16c1_s_p9_2,
  123758. NULL,
  123759. &_vq_auxt__16c1_s_p9_2,
  123760. NULL,
  123761. 0
  123762. };
  123763. static long _huff_lengthlist__16c1_s_short[] = {
  123764. 5, 6,17, 8,12, 9,10,10,12,13, 5, 2,17, 4, 9, 5,
  123765. 7, 8,11,13,16,16,16,16,16,16,16,16,16,16, 6, 4,
  123766. 16, 5,10, 5, 7,10,14,16,13, 9,16,11, 8, 7, 8, 9,
  123767. 13,16, 7, 4,16, 5, 7, 4, 6, 8,11,13, 8, 6,16, 7,
  123768. 8, 5, 5, 7, 9,13, 9, 8,16, 9, 8, 6, 6, 7, 9,13,
  123769. 11,11,16,10,10, 7, 7, 7, 9,13,13,13,16,13,13, 9,
  123770. 9, 9,10,13,
  123771. };
  123772. static static_codebook _huff_book__16c1_s_short = {
  123773. 2, 100,
  123774. _huff_lengthlist__16c1_s_short,
  123775. 0, 0, 0, 0, 0,
  123776. NULL,
  123777. NULL,
  123778. NULL,
  123779. NULL,
  123780. 0
  123781. };
  123782. static long _huff_lengthlist__16c2_s_long[] = {
  123783. 4, 7, 9, 9, 9, 8, 9,10,15,19, 5, 4, 5, 6, 7, 7,
  123784. 8, 9,14,16, 6, 5, 4, 5, 6, 7, 8,10,12,19, 7, 6,
  123785. 5, 4, 5, 6, 7, 9,11,18, 8, 7, 6, 5, 5, 5, 7, 9,
  123786. 10,17, 8, 7, 7, 5, 5, 5, 6, 7,12,18, 8, 8, 8, 7,
  123787. 7, 5, 5, 7,12,18, 8, 9,10, 9, 9, 7, 6, 7,12,17,
  123788. 14,18,16,16,15,12,11,10,12,18,15,17,18,18,18,15,
  123789. 14,14,16,18,
  123790. };
  123791. static static_codebook _huff_book__16c2_s_long = {
  123792. 2, 100,
  123793. _huff_lengthlist__16c2_s_long,
  123794. 0, 0, 0, 0, 0,
  123795. NULL,
  123796. NULL,
  123797. NULL,
  123798. NULL,
  123799. 0
  123800. };
  123801. static long _vq_quantlist__16c2_s_p1_0[] = {
  123802. 1,
  123803. 0,
  123804. 2,
  123805. };
  123806. static long _vq_lengthlist__16c2_s_p1_0[] = {
  123807. 1, 3, 3, 0, 0, 0, 0, 0, 0, 4, 5, 5, 0, 0, 0, 0,
  123808. 0, 0, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123812. 0,
  123813. };
  123814. static float _vq_quantthresh__16c2_s_p1_0[] = {
  123815. -0.5, 0.5,
  123816. };
  123817. static long _vq_quantmap__16c2_s_p1_0[] = {
  123818. 1, 0, 2,
  123819. };
  123820. static encode_aux_threshmatch _vq_auxt__16c2_s_p1_0 = {
  123821. _vq_quantthresh__16c2_s_p1_0,
  123822. _vq_quantmap__16c2_s_p1_0,
  123823. 3,
  123824. 3
  123825. };
  123826. static static_codebook _16c2_s_p1_0 = {
  123827. 4, 81,
  123828. _vq_lengthlist__16c2_s_p1_0,
  123829. 1, -535822336, 1611661312, 2, 0,
  123830. _vq_quantlist__16c2_s_p1_0,
  123831. NULL,
  123832. &_vq_auxt__16c2_s_p1_0,
  123833. NULL,
  123834. 0
  123835. };
  123836. static long _vq_quantlist__16c2_s_p2_0[] = {
  123837. 2,
  123838. 1,
  123839. 3,
  123840. 0,
  123841. 4,
  123842. };
  123843. static long _vq_lengthlist__16c2_s_p2_0[] = {
  123844. 2, 4, 3, 7, 7, 0, 0, 0, 7, 8, 0, 0, 0, 8, 8, 0,
  123845. 0, 0, 8, 8, 0, 0, 0, 8, 8, 4, 5, 4, 8, 8, 0, 0,
  123846. 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0,
  123847. 9, 9, 4, 4, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8,
  123848. 8, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 7, 8, 8,10,10,
  123849. 0, 0, 0,12,11, 0, 0, 0,11,11, 0, 0, 0,14,13, 0,
  123850. 0, 0,14,13, 7, 8, 8, 9,10, 0, 0, 0,11,12, 0, 0,
  123851. 0,11,11, 0, 0, 0,14,14, 0, 0, 0,13,14, 0, 0, 0,
  123852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123856. 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8,11,11, 0, 0, 0,
  123857. 11,11, 0, 0, 0,12,11, 0, 0, 0,12,12, 0, 0, 0,13,
  123858. 13, 8, 8, 8,11,11, 0, 0, 0,11,11, 0, 0, 0,11,12,
  123859. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  123860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123864. 0, 0, 0, 0, 0, 8, 8, 8,12,11, 0, 0, 0,12,11, 0,
  123865. 0, 0,11,11, 0, 0, 0,13,13, 0, 0, 0,13,12, 8, 8,
  123866. 8,11,12, 0, 0, 0,11,12, 0, 0, 0,11,11, 0, 0, 0,
  123867. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123872. 0, 0, 8, 9, 9,14,13, 0, 0, 0,13,12, 0, 0, 0,13,
  123873. 13, 0, 0, 0,13,12, 0, 0, 0,13,13, 8, 9, 9,13,14,
  123874. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,13, 0,
  123875. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8,
  123880. 9, 9,14,13, 0, 0, 0,13,13, 0, 0, 0,13,12, 0, 0,
  123881. 0,13,13, 0, 0, 0,13,12, 8, 9, 9,14,14, 0, 0, 0,
  123882. 13,13, 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,
  123883. 13,
  123884. };
  123885. static float _vq_quantthresh__16c2_s_p2_0[] = {
  123886. -1.5, -0.5, 0.5, 1.5,
  123887. };
  123888. static long _vq_quantmap__16c2_s_p2_0[] = {
  123889. 3, 1, 0, 2, 4,
  123890. };
  123891. static encode_aux_threshmatch _vq_auxt__16c2_s_p2_0 = {
  123892. _vq_quantthresh__16c2_s_p2_0,
  123893. _vq_quantmap__16c2_s_p2_0,
  123894. 5,
  123895. 5
  123896. };
  123897. static static_codebook _16c2_s_p2_0 = {
  123898. 4, 625,
  123899. _vq_lengthlist__16c2_s_p2_0,
  123900. 1, -533725184, 1611661312, 3, 0,
  123901. _vq_quantlist__16c2_s_p2_0,
  123902. NULL,
  123903. &_vq_auxt__16c2_s_p2_0,
  123904. NULL,
  123905. 0
  123906. };
  123907. static long _vq_quantlist__16c2_s_p3_0[] = {
  123908. 4,
  123909. 3,
  123910. 5,
  123911. 2,
  123912. 6,
  123913. 1,
  123914. 7,
  123915. 0,
  123916. 8,
  123917. };
  123918. static long _vq_lengthlist__16c2_s_p3_0[] = {
  123919. 1, 3, 3, 6, 6, 7, 7, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  123920. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  123921. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  123922. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 9, 9,10,10, 0,
  123923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123924. 0,
  123925. };
  123926. static float _vq_quantthresh__16c2_s_p3_0[] = {
  123927. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123928. };
  123929. static long _vq_quantmap__16c2_s_p3_0[] = {
  123930. 7, 5, 3, 1, 0, 2, 4, 6,
  123931. 8,
  123932. };
  123933. static encode_aux_threshmatch _vq_auxt__16c2_s_p3_0 = {
  123934. _vq_quantthresh__16c2_s_p3_0,
  123935. _vq_quantmap__16c2_s_p3_0,
  123936. 9,
  123937. 9
  123938. };
  123939. static static_codebook _16c2_s_p3_0 = {
  123940. 2, 81,
  123941. _vq_lengthlist__16c2_s_p3_0,
  123942. 1, -531628032, 1611661312, 4, 0,
  123943. _vq_quantlist__16c2_s_p3_0,
  123944. NULL,
  123945. &_vq_auxt__16c2_s_p3_0,
  123946. NULL,
  123947. 0
  123948. };
  123949. static long _vq_quantlist__16c2_s_p4_0[] = {
  123950. 8,
  123951. 7,
  123952. 9,
  123953. 6,
  123954. 10,
  123955. 5,
  123956. 11,
  123957. 4,
  123958. 12,
  123959. 3,
  123960. 13,
  123961. 2,
  123962. 14,
  123963. 1,
  123964. 15,
  123965. 0,
  123966. 16,
  123967. };
  123968. static long _vq_lengthlist__16c2_s_p4_0[] = {
  123969. 2, 3, 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,
  123970. 10, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  123971. 11,11, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  123972. 10,10,11, 0, 0, 0, 6, 6, 8, 8, 8, 8, 9, 9,10,10,
  123973. 10,11,11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,
  123974. 10,11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,
  123975. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9,
  123976. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  123977. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  123978. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  123979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123987. 0,
  123988. };
  123989. static float _vq_quantthresh__16c2_s_p4_0[] = {
  123990. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  123991. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  123992. };
  123993. static long _vq_quantmap__16c2_s_p4_0[] = {
  123994. 15, 13, 11, 9, 7, 5, 3, 1,
  123995. 0, 2, 4, 6, 8, 10, 12, 14,
  123996. 16,
  123997. };
  123998. static encode_aux_threshmatch _vq_auxt__16c2_s_p4_0 = {
  123999. _vq_quantthresh__16c2_s_p4_0,
  124000. _vq_quantmap__16c2_s_p4_0,
  124001. 17,
  124002. 17
  124003. };
  124004. static static_codebook _16c2_s_p4_0 = {
  124005. 2, 289,
  124006. _vq_lengthlist__16c2_s_p4_0,
  124007. 1, -529530880, 1611661312, 5, 0,
  124008. _vq_quantlist__16c2_s_p4_0,
  124009. NULL,
  124010. &_vq_auxt__16c2_s_p4_0,
  124011. NULL,
  124012. 0
  124013. };
  124014. static long _vq_quantlist__16c2_s_p5_0[] = {
  124015. 1,
  124016. 0,
  124017. 2,
  124018. };
  124019. static long _vq_lengthlist__16c2_s_p5_0[] = {
  124020. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6,10,10,10,10,
  124021. 10,10, 4, 7, 6,10,10,10,10,10,10, 5, 9, 9, 9,12,
  124022. 11,10,11,12, 7,10,10,12,12,12,12,12,12, 7,10,10,
  124023. 11,12,12,12,12,13, 6,10,10,10,12,12,10,12,12, 7,
  124024. 10,10,11,13,12,12,12,12, 7,10,10,11,12,12,12,12,
  124025. 12,
  124026. };
  124027. static float _vq_quantthresh__16c2_s_p5_0[] = {
  124028. -5.5, 5.5,
  124029. };
  124030. static long _vq_quantmap__16c2_s_p5_0[] = {
  124031. 1, 0, 2,
  124032. };
  124033. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_0 = {
  124034. _vq_quantthresh__16c2_s_p5_0,
  124035. _vq_quantmap__16c2_s_p5_0,
  124036. 3,
  124037. 3
  124038. };
  124039. static static_codebook _16c2_s_p5_0 = {
  124040. 4, 81,
  124041. _vq_lengthlist__16c2_s_p5_0,
  124042. 1, -529137664, 1618345984, 2, 0,
  124043. _vq_quantlist__16c2_s_p5_0,
  124044. NULL,
  124045. &_vq_auxt__16c2_s_p5_0,
  124046. NULL,
  124047. 0
  124048. };
  124049. static long _vq_quantlist__16c2_s_p5_1[] = {
  124050. 5,
  124051. 4,
  124052. 6,
  124053. 3,
  124054. 7,
  124055. 2,
  124056. 8,
  124057. 1,
  124058. 9,
  124059. 0,
  124060. 10,
  124061. };
  124062. static long _vq_lengthlist__16c2_s_p5_1[] = {
  124063. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11, 6, 6,
  124064. 7, 7, 8, 8, 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8,
  124065. 8,11,11,11, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  124066. 6, 8, 8, 8, 8, 9, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  124067. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 9,11,11,11,
  124068. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,11,11, 8, 8, 8,
  124069. 8, 8, 8,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  124070. 11,11,11, 7, 7, 8, 8, 8, 8,
  124071. };
  124072. static float _vq_quantthresh__16c2_s_p5_1[] = {
  124073. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  124074. 3.5, 4.5,
  124075. };
  124076. static long _vq_quantmap__16c2_s_p5_1[] = {
  124077. 9, 7, 5, 3, 1, 0, 2, 4,
  124078. 6, 8, 10,
  124079. };
  124080. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_1 = {
  124081. _vq_quantthresh__16c2_s_p5_1,
  124082. _vq_quantmap__16c2_s_p5_1,
  124083. 11,
  124084. 11
  124085. };
  124086. static static_codebook _16c2_s_p5_1 = {
  124087. 2, 121,
  124088. _vq_lengthlist__16c2_s_p5_1,
  124089. 1, -531365888, 1611661312, 4, 0,
  124090. _vq_quantlist__16c2_s_p5_1,
  124091. NULL,
  124092. &_vq_auxt__16c2_s_p5_1,
  124093. NULL,
  124094. 0
  124095. };
  124096. static long _vq_quantlist__16c2_s_p6_0[] = {
  124097. 6,
  124098. 5,
  124099. 7,
  124100. 4,
  124101. 8,
  124102. 3,
  124103. 9,
  124104. 2,
  124105. 10,
  124106. 1,
  124107. 11,
  124108. 0,
  124109. 12,
  124110. };
  124111. static long _vq_lengthlist__16c2_s_p6_0[] = {
  124112. 1, 4, 4, 7, 6, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  124113. 7, 7, 9, 9, 9, 9,11,11,12,12, 6, 5, 5, 7, 7, 9,
  124114. 9,10,10,11,11,12,12, 0, 6, 6, 7, 7, 9, 9,10,10,
  124115. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,12,12,
  124116. 12, 0,11,11, 8, 8,10,10,11,11,12,12,13,13, 0,11,
  124117. 12, 8, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  124118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124122. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124123. };
  124124. static float _vq_quantthresh__16c2_s_p6_0[] = {
  124125. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  124126. 12.5, 17.5, 22.5, 27.5,
  124127. };
  124128. static long _vq_quantmap__16c2_s_p6_0[] = {
  124129. 11, 9, 7, 5, 3, 1, 0, 2,
  124130. 4, 6, 8, 10, 12,
  124131. };
  124132. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_0 = {
  124133. _vq_quantthresh__16c2_s_p6_0,
  124134. _vq_quantmap__16c2_s_p6_0,
  124135. 13,
  124136. 13
  124137. };
  124138. static static_codebook _16c2_s_p6_0 = {
  124139. 2, 169,
  124140. _vq_lengthlist__16c2_s_p6_0,
  124141. 1, -526516224, 1616117760, 4, 0,
  124142. _vq_quantlist__16c2_s_p6_0,
  124143. NULL,
  124144. &_vq_auxt__16c2_s_p6_0,
  124145. NULL,
  124146. 0
  124147. };
  124148. static long _vq_quantlist__16c2_s_p6_1[] = {
  124149. 2,
  124150. 1,
  124151. 3,
  124152. 0,
  124153. 4,
  124154. };
  124155. static long _vq_lengthlist__16c2_s_p6_1[] = {
  124156. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  124157. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  124158. };
  124159. static float _vq_quantthresh__16c2_s_p6_1[] = {
  124160. -1.5, -0.5, 0.5, 1.5,
  124161. };
  124162. static long _vq_quantmap__16c2_s_p6_1[] = {
  124163. 3, 1, 0, 2, 4,
  124164. };
  124165. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_1 = {
  124166. _vq_quantthresh__16c2_s_p6_1,
  124167. _vq_quantmap__16c2_s_p6_1,
  124168. 5,
  124169. 5
  124170. };
  124171. static static_codebook _16c2_s_p6_1 = {
  124172. 2, 25,
  124173. _vq_lengthlist__16c2_s_p6_1,
  124174. 1, -533725184, 1611661312, 3, 0,
  124175. _vq_quantlist__16c2_s_p6_1,
  124176. NULL,
  124177. &_vq_auxt__16c2_s_p6_1,
  124178. NULL,
  124179. 0
  124180. };
  124181. static long _vq_quantlist__16c2_s_p7_0[] = {
  124182. 6,
  124183. 5,
  124184. 7,
  124185. 4,
  124186. 8,
  124187. 3,
  124188. 9,
  124189. 2,
  124190. 10,
  124191. 1,
  124192. 11,
  124193. 0,
  124194. 12,
  124195. };
  124196. static long _vq_lengthlist__16c2_s_p7_0[] = {
  124197. 1, 4, 4, 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  124198. 8, 8, 9, 9,10,10,11,11,12,12, 6, 5, 5, 8, 8, 9,
  124199. 9,10,10,11,11,12,13,18, 6, 6, 7, 7, 9, 9,10,10,
  124200. 12,12,13,13,18, 6, 6, 7, 7, 9, 9,10,10,12,12,13,
  124201. 13,18,11,10, 8, 8,10,10,11,11,12,12,13,13,18,11,
  124202. 11, 8, 8,10,10,11,11,12,13,13,13,18,18,18,10,11,
  124203. 11,11,12,12,13,13,14,14,18,18,18,11,11,11,11,12,
  124204. 12,13,13,14,14,18,18,18,14,14,12,12,12,12,14,14,
  124205. 15,14,18,18,18,15,15,11,12,12,12,13,13,15,15,18,
  124206. 18,18,18,18,13,13,13,13,13,14,17,16,18,18,18,18,
  124207. 18,13,14,13,13,14,13,15,14,
  124208. };
  124209. static float _vq_quantthresh__16c2_s_p7_0[] = {
  124210. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  124211. 27.5, 38.5, 49.5, 60.5,
  124212. };
  124213. static long _vq_quantmap__16c2_s_p7_0[] = {
  124214. 11, 9, 7, 5, 3, 1, 0, 2,
  124215. 4, 6, 8, 10, 12,
  124216. };
  124217. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_0 = {
  124218. _vq_quantthresh__16c2_s_p7_0,
  124219. _vq_quantmap__16c2_s_p7_0,
  124220. 13,
  124221. 13
  124222. };
  124223. static static_codebook _16c2_s_p7_0 = {
  124224. 2, 169,
  124225. _vq_lengthlist__16c2_s_p7_0,
  124226. 1, -523206656, 1618345984, 4, 0,
  124227. _vq_quantlist__16c2_s_p7_0,
  124228. NULL,
  124229. &_vq_auxt__16c2_s_p7_0,
  124230. NULL,
  124231. 0
  124232. };
  124233. static long _vq_quantlist__16c2_s_p7_1[] = {
  124234. 5,
  124235. 4,
  124236. 6,
  124237. 3,
  124238. 7,
  124239. 2,
  124240. 8,
  124241. 1,
  124242. 9,
  124243. 0,
  124244. 10,
  124245. };
  124246. static long _vq_lengthlist__16c2_s_p7_1[] = {
  124247. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 9, 9, 6, 6,
  124248. 7, 7, 8, 8, 8, 8, 9, 9, 9, 6, 6, 7, 7, 8, 8, 8,
  124249. 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7,
  124250. 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  124251. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  124252. 7, 7, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 9, 7, 7, 7,
  124253. 7, 8, 8, 9, 9, 9, 9, 9, 8, 8, 7, 7, 8, 8, 9, 9,
  124254. 9, 9, 9, 7, 7, 7, 7, 8, 8,
  124255. };
  124256. static float _vq_quantthresh__16c2_s_p7_1[] = {
  124257. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  124258. 3.5, 4.5,
  124259. };
  124260. static long _vq_quantmap__16c2_s_p7_1[] = {
  124261. 9, 7, 5, 3, 1, 0, 2, 4,
  124262. 6, 8, 10,
  124263. };
  124264. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_1 = {
  124265. _vq_quantthresh__16c2_s_p7_1,
  124266. _vq_quantmap__16c2_s_p7_1,
  124267. 11,
  124268. 11
  124269. };
  124270. static static_codebook _16c2_s_p7_1 = {
  124271. 2, 121,
  124272. _vq_lengthlist__16c2_s_p7_1,
  124273. 1, -531365888, 1611661312, 4, 0,
  124274. _vq_quantlist__16c2_s_p7_1,
  124275. NULL,
  124276. &_vq_auxt__16c2_s_p7_1,
  124277. NULL,
  124278. 0
  124279. };
  124280. static long _vq_quantlist__16c2_s_p8_0[] = {
  124281. 7,
  124282. 6,
  124283. 8,
  124284. 5,
  124285. 9,
  124286. 4,
  124287. 10,
  124288. 3,
  124289. 11,
  124290. 2,
  124291. 12,
  124292. 1,
  124293. 13,
  124294. 0,
  124295. 14,
  124296. };
  124297. static long _vq_lengthlist__16c2_s_p8_0[] = {
  124298. 1, 4, 4, 7, 6, 7, 7, 6, 6, 8, 8, 9, 9,10,10, 6,
  124299. 6, 6, 8, 8, 9, 8, 8, 8, 9, 9,11,10,11,11, 7, 6,
  124300. 6, 8, 8, 9, 8, 7, 7, 9, 9,10,10,12,11,14, 8, 8,
  124301. 8, 9, 9, 9, 9, 9,10, 9,10,10,11,13,14, 8, 8, 8,
  124302. 8, 9, 9, 8, 8, 9, 9,10,10,11,12,14,13,11, 9, 9,
  124303. 9, 9, 9, 9, 9,10,11,10,13,12,14,11,13, 8, 9, 9,
  124304. 9, 9, 9,10,10,11,10,13,12,14,14,14, 8, 9, 9, 9,
  124305. 11,11,11,11,11,12,13,13,14,14,14, 9, 8, 9, 9,10,
  124306. 10,12,10,11,12,12,14,14,14,14,11,12,10,10,12,12,
  124307. 12,12,13,14,12,12,14,14,14,12,12, 9,10,11,11,12,
  124308. 14,12,14,14,14,14,14,14,14,14,11,11,12,11,12,14,
  124309. 14,14,14,14,14,14,14,14,14,12,11,11,11,11,14,14,
  124310. 14,14,14,14,14,14,14,14,14,14,13,12,14,14,14,14,
  124311. 14,14,14,14,14,14,14,14,14,12,12,12,13,14,14,13,
  124312. 13,
  124313. };
  124314. static float _vq_quantthresh__16c2_s_p8_0[] = {
  124315. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  124316. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  124317. };
  124318. static long _vq_quantmap__16c2_s_p8_0[] = {
  124319. 13, 11, 9, 7, 5, 3, 1, 0,
  124320. 2, 4, 6, 8, 10, 12, 14,
  124321. };
  124322. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_0 = {
  124323. _vq_quantthresh__16c2_s_p8_0,
  124324. _vq_quantmap__16c2_s_p8_0,
  124325. 15,
  124326. 15
  124327. };
  124328. static static_codebook _16c2_s_p8_0 = {
  124329. 2, 225,
  124330. _vq_lengthlist__16c2_s_p8_0,
  124331. 1, -520986624, 1620377600, 4, 0,
  124332. _vq_quantlist__16c2_s_p8_0,
  124333. NULL,
  124334. &_vq_auxt__16c2_s_p8_0,
  124335. NULL,
  124336. 0
  124337. };
  124338. static long _vq_quantlist__16c2_s_p8_1[] = {
  124339. 10,
  124340. 9,
  124341. 11,
  124342. 8,
  124343. 12,
  124344. 7,
  124345. 13,
  124346. 6,
  124347. 14,
  124348. 5,
  124349. 15,
  124350. 4,
  124351. 16,
  124352. 3,
  124353. 17,
  124354. 2,
  124355. 18,
  124356. 1,
  124357. 19,
  124358. 0,
  124359. 20,
  124360. };
  124361. static long _vq_lengthlist__16c2_s_p8_1[] = {
  124362. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  124363. 8, 8, 8, 8, 8,11,12,11, 7, 7, 8, 8, 8, 8, 9, 9,
  124364. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,11,11,10, 7, 7, 8,
  124365. 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  124366. 11,11, 8, 7, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 9,10,
  124367. 10, 9,10,10,11,11,12, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  124368. 9, 9, 9,10, 9,10,10,10,10,11,11,11, 8, 8, 9, 9,
  124369. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  124370. 11, 8, 8, 9, 8, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,
  124371. 10, 9,10,11,11,11, 9, 9, 9, 9,10, 9, 9, 9,10,10,
  124372. 9,10, 9,10,10,10,10,10,11,12,11,11,11, 9, 9, 9,
  124373. 9, 9,10,10, 9,10,10,10,10,10,10,10,10,12,11,13,
  124374. 13,11, 9, 9, 9, 9,10,10, 9,10,10,10,10,11,10,10,
  124375. 10,10,11,12,11,12,11, 9, 9, 9,10,10, 9,10,10,10,
  124376. 10,10,10,10,10,10,10,11,11,11,12,11, 9,10,10,10,
  124377. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,12,12,
  124378. 11,11,11,10, 9,10,10,10,10,10,10,10,10,11,10,10,
  124379. 10,11,11,11,11,11,11,11,10,10,10,11,10,10,10,10,
  124380. 10,10,10,10,10,10,11,11,11,11,12,12,11,10,10,10,
  124381. 10,10,10,10,10,11,10,10,10,11,10,12,11,11,12,11,
  124382. 11,11,10,10,10,10,10,11,10,10,10,10,10,11,10,10,
  124383. 11,11,11,12,11,12,11,11,12,10,10,10,10,10,10,10,
  124384. 11,10,10,11,10,12,11,11,11,12,11,11,11,11,10,10,
  124385. 10,10,10,10,10,11,11,11,10,11,12,11,11,11,12,11,
  124386. 12,11,12,10,11,10,10,10,10,11,10,10,10,10,10,10,
  124387. 12,11,11,11,11,11,12,12,10,10,10,10,10,11,10,10,
  124388. 11,10,11,11,11,11,11,11,11,11,11,11,11,11,12,11,
  124389. 10,11,10,10,10,10,10,10,10,
  124390. };
  124391. static float _vq_quantthresh__16c2_s_p8_1[] = {
  124392. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  124393. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  124394. 6.5, 7.5, 8.5, 9.5,
  124395. };
  124396. static long _vq_quantmap__16c2_s_p8_1[] = {
  124397. 19, 17, 15, 13, 11, 9, 7, 5,
  124398. 3, 1, 0, 2, 4, 6, 8, 10,
  124399. 12, 14, 16, 18, 20,
  124400. };
  124401. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_1 = {
  124402. _vq_quantthresh__16c2_s_p8_1,
  124403. _vq_quantmap__16c2_s_p8_1,
  124404. 21,
  124405. 21
  124406. };
  124407. static static_codebook _16c2_s_p8_1 = {
  124408. 2, 441,
  124409. _vq_lengthlist__16c2_s_p8_1,
  124410. 1, -529268736, 1611661312, 5, 0,
  124411. _vq_quantlist__16c2_s_p8_1,
  124412. NULL,
  124413. &_vq_auxt__16c2_s_p8_1,
  124414. NULL,
  124415. 0
  124416. };
  124417. static long _vq_quantlist__16c2_s_p9_0[] = {
  124418. 6,
  124419. 5,
  124420. 7,
  124421. 4,
  124422. 8,
  124423. 3,
  124424. 9,
  124425. 2,
  124426. 10,
  124427. 1,
  124428. 11,
  124429. 0,
  124430. 12,
  124431. };
  124432. static long _vq_lengthlist__16c2_s_p9_0[] = {
  124433. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124434. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124435. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124436. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124437. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124438. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124439. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124440. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124441. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124442. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124443. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124444. };
  124445. static float _vq_quantthresh__16c2_s_p9_0[] = {
  124446. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5,
  124447. 2327.5, 3258.5, 4189.5, 5120.5,
  124448. };
  124449. static long _vq_quantmap__16c2_s_p9_0[] = {
  124450. 11, 9, 7, 5, 3, 1, 0, 2,
  124451. 4, 6, 8, 10, 12,
  124452. };
  124453. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_0 = {
  124454. _vq_quantthresh__16c2_s_p9_0,
  124455. _vq_quantmap__16c2_s_p9_0,
  124456. 13,
  124457. 13
  124458. };
  124459. static static_codebook _16c2_s_p9_0 = {
  124460. 2, 169,
  124461. _vq_lengthlist__16c2_s_p9_0,
  124462. 1, -510275072, 1631393792, 4, 0,
  124463. _vq_quantlist__16c2_s_p9_0,
  124464. NULL,
  124465. &_vq_auxt__16c2_s_p9_0,
  124466. NULL,
  124467. 0
  124468. };
  124469. static long _vq_quantlist__16c2_s_p9_1[] = {
  124470. 8,
  124471. 7,
  124472. 9,
  124473. 6,
  124474. 10,
  124475. 5,
  124476. 11,
  124477. 4,
  124478. 12,
  124479. 3,
  124480. 13,
  124481. 2,
  124482. 14,
  124483. 1,
  124484. 15,
  124485. 0,
  124486. 16,
  124487. };
  124488. static long _vq_lengthlist__16c2_s_p9_1[] = {
  124489. 1, 5, 5, 9, 8, 7, 7, 7, 6,10,11,11,11,11,11,11,
  124490. 11, 8, 7, 6, 8, 8,10, 9,10,10,10, 9,11,10,10,10,
  124491. 10,10, 8, 6, 6, 8, 8, 9, 8, 9, 8, 9,10,10,10,10,
  124492. 10,10,10,10, 8,10, 9, 9, 9, 9,10,10,10,10,10,10,
  124493. 10,10,10,10,10, 8, 9, 9, 9,10,10, 9,10,10,10,10,
  124494. 10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,10,10,10,
  124495. 10,10,10,10,10,10,10,10, 9, 8, 8, 9, 9,10,10,10,
  124496. 10,10,10,10,10,10,10,10,10,10, 9,10, 9, 9,10,10,
  124497. 10,10,10,10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,
  124498. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  124499. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124500. 8,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124501. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124502. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124503. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124504. 10,10,10,10, 9,10, 9,10,10,10,10,10,10,10,10,10,
  124505. 10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,
  124506. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124507. 10,
  124508. };
  124509. static float _vq_quantthresh__16c2_s_p9_1[] = {
  124510. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -24.5,
  124511. 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5, 367.5,
  124512. };
  124513. static long _vq_quantmap__16c2_s_p9_1[] = {
  124514. 15, 13, 11, 9, 7, 5, 3, 1,
  124515. 0, 2, 4, 6, 8, 10, 12, 14,
  124516. 16,
  124517. };
  124518. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_1 = {
  124519. _vq_quantthresh__16c2_s_p9_1,
  124520. _vq_quantmap__16c2_s_p9_1,
  124521. 17,
  124522. 17
  124523. };
  124524. static static_codebook _16c2_s_p9_1 = {
  124525. 2, 289,
  124526. _vq_lengthlist__16c2_s_p9_1,
  124527. 1, -518488064, 1622704128, 5, 0,
  124528. _vq_quantlist__16c2_s_p9_1,
  124529. NULL,
  124530. &_vq_auxt__16c2_s_p9_1,
  124531. NULL,
  124532. 0
  124533. };
  124534. static long _vq_quantlist__16c2_s_p9_2[] = {
  124535. 13,
  124536. 12,
  124537. 14,
  124538. 11,
  124539. 15,
  124540. 10,
  124541. 16,
  124542. 9,
  124543. 17,
  124544. 8,
  124545. 18,
  124546. 7,
  124547. 19,
  124548. 6,
  124549. 20,
  124550. 5,
  124551. 21,
  124552. 4,
  124553. 22,
  124554. 3,
  124555. 23,
  124556. 2,
  124557. 24,
  124558. 1,
  124559. 25,
  124560. 0,
  124561. 26,
  124562. };
  124563. static long _vq_lengthlist__16c2_s_p9_2[] = {
  124564. 1, 4, 4, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  124565. 7, 7, 7, 7, 8, 7, 8, 7, 7, 4, 4,
  124566. };
  124567. static float _vq_quantthresh__16c2_s_p9_2[] = {
  124568. -12.5, -11.5, -10.5, -9.5, -8.5, -7.5, -6.5, -5.5,
  124569. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  124570. 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 10.5,
  124571. 11.5, 12.5,
  124572. };
  124573. static long _vq_quantmap__16c2_s_p9_2[] = {
  124574. 25, 23, 21, 19, 17, 15, 13, 11,
  124575. 9, 7, 5, 3, 1, 0, 2, 4,
  124576. 6, 8, 10, 12, 14, 16, 18, 20,
  124577. 22, 24, 26,
  124578. };
  124579. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_2 = {
  124580. _vq_quantthresh__16c2_s_p9_2,
  124581. _vq_quantmap__16c2_s_p9_2,
  124582. 27,
  124583. 27
  124584. };
  124585. static static_codebook _16c2_s_p9_2 = {
  124586. 1, 27,
  124587. _vq_lengthlist__16c2_s_p9_2,
  124588. 1, -528875520, 1611661312, 5, 0,
  124589. _vq_quantlist__16c2_s_p9_2,
  124590. NULL,
  124591. &_vq_auxt__16c2_s_p9_2,
  124592. NULL,
  124593. 0
  124594. };
  124595. static long _huff_lengthlist__16c2_s_short[] = {
  124596. 7,10,11,11,11,14,15,15,17,14, 8, 6, 7, 7, 8, 9,
  124597. 11,11,14,17, 9, 6, 6, 6, 7, 7,10,11,15,16, 9, 6,
  124598. 6, 4, 4, 5, 8, 9,12,16,10, 6, 6, 4, 4, 4, 6, 9,
  124599. 13,16,10, 7, 6, 5, 4, 3, 5, 7,13,16,11, 9, 8, 7,
  124600. 6, 5, 5, 6,12,15,10,10,10, 9, 7, 6, 6, 7,11,15,
  124601. 13,13,13,13,11,10,10, 9,12,16,16,16,16,14,16,15,
  124602. 15,12,14,14,
  124603. };
  124604. static static_codebook _huff_book__16c2_s_short = {
  124605. 2, 100,
  124606. _huff_lengthlist__16c2_s_short,
  124607. 0, 0, 0, 0, 0,
  124608. NULL,
  124609. NULL,
  124610. NULL,
  124611. NULL,
  124612. 0
  124613. };
  124614. static long _vq_quantlist__8c0_s_p1_0[] = {
  124615. 1,
  124616. 0,
  124617. 2,
  124618. };
  124619. static long _vq_lengthlist__8c0_s_p1_0[] = {
  124620. 1, 5, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  124621. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124625. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  124626. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124630. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  124631. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  124666. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  124667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0, 0,
  124671. 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  124672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9,10, 0, 0,
  124676. 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  124677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124711. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  124712. 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124716. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  124717. 0, 0, 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 0, 0,
  124718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124721. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  124722. 0, 0, 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 0,
  124723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125030. 0,
  125031. };
  125032. static float _vq_quantthresh__8c0_s_p1_0[] = {
  125033. -0.5, 0.5,
  125034. };
  125035. static long _vq_quantmap__8c0_s_p1_0[] = {
  125036. 1, 0, 2,
  125037. };
  125038. static encode_aux_threshmatch _vq_auxt__8c0_s_p1_0 = {
  125039. _vq_quantthresh__8c0_s_p1_0,
  125040. _vq_quantmap__8c0_s_p1_0,
  125041. 3,
  125042. 3
  125043. };
  125044. static static_codebook _8c0_s_p1_0 = {
  125045. 8, 6561,
  125046. _vq_lengthlist__8c0_s_p1_0,
  125047. 1, -535822336, 1611661312, 2, 0,
  125048. _vq_quantlist__8c0_s_p1_0,
  125049. NULL,
  125050. &_vq_auxt__8c0_s_p1_0,
  125051. NULL,
  125052. 0
  125053. };
  125054. static long _vq_quantlist__8c0_s_p2_0[] = {
  125055. 2,
  125056. 1,
  125057. 3,
  125058. 0,
  125059. 4,
  125060. };
  125061. static long _vq_lengthlist__8c0_s_p2_0[] = {
  125062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125101. 0,
  125102. };
  125103. static float _vq_quantthresh__8c0_s_p2_0[] = {
  125104. -1.5, -0.5, 0.5, 1.5,
  125105. };
  125106. static long _vq_quantmap__8c0_s_p2_0[] = {
  125107. 3, 1, 0, 2, 4,
  125108. };
  125109. static encode_aux_threshmatch _vq_auxt__8c0_s_p2_0 = {
  125110. _vq_quantthresh__8c0_s_p2_0,
  125111. _vq_quantmap__8c0_s_p2_0,
  125112. 5,
  125113. 5
  125114. };
  125115. static static_codebook _8c0_s_p2_0 = {
  125116. 4, 625,
  125117. _vq_lengthlist__8c0_s_p2_0,
  125118. 1, -533725184, 1611661312, 3, 0,
  125119. _vq_quantlist__8c0_s_p2_0,
  125120. NULL,
  125121. &_vq_auxt__8c0_s_p2_0,
  125122. NULL,
  125123. 0
  125124. };
  125125. static long _vq_quantlist__8c0_s_p3_0[] = {
  125126. 2,
  125127. 1,
  125128. 3,
  125129. 0,
  125130. 4,
  125131. };
  125132. static long _vq_lengthlist__8c0_s_p3_0[] = {
  125133. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 6, 7, 7, 0, 0,
  125135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125136. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 8, 8,
  125138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125139. 0, 0, 0, 0, 6, 7, 7, 8, 8, 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, 0, 0, 0, 0, 0, 0, 0,
  125170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125172. 0,
  125173. };
  125174. static float _vq_quantthresh__8c0_s_p3_0[] = {
  125175. -1.5, -0.5, 0.5, 1.5,
  125176. };
  125177. static long _vq_quantmap__8c0_s_p3_0[] = {
  125178. 3, 1, 0, 2, 4,
  125179. };
  125180. static encode_aux_threshmatch _vq_auxt__8c0_s_p3_0 = {
  125181. _vq_quantthresh__8c0_s_p3_0,
  125182. _vq_quantmap__8c0_s_p3_0,
  125183. 5,
  125184. 5
  125185. };
  125186. static static_codebook _8c0_s_p3_0 = {
  125187. 4, 625,
  125188. _vq_lengthlist__8c0_s_p3_0,
  125189. 1, -533725184, 1611661312, 3, 0,
  125190. _vq_quantlist__8c0_s_p3_0,
  125191. NULL,
  125192. &_vq_auxt__8c0_s_p3_0,
  125193. NULL,
  125194. 0
  125195. };
  125196. static long _vq_quantlist__8c0_s_p4_0[] = {
  125197. 4,
  125198. 3,
  125199. 5,
  125200. 2,
  125201. 6,
  125202. 1,
  125203. 7,
  125204. 0,
  125205. 8,
  125206. };
  125207. static long _vq_lengthlist__8c0_s_p4_0[] = {
  125208. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  125209. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  125210. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  125211. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  125212. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125213. 0,
  125214. };
  125215. static float _vq_quantthresh__8c0_s_p4_0[] = {
  125216. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  125217. };
  125218. static long _vq_quantmap__8c0_s_p4_0[] = {
  125219. 7, 5, 3, 1, 0, 2, 4, 6,
  125220. 8,
  125221. };
  125222. static encode_aux_threshmatch _vq_auxt__8c0_s_p4_0 = {
  125223. _vq_quantthresh__8c0_s_p4_0,
  125224. _vq_quantmap__8c0_s_p4_0,
  125225. 9,
  125226. 9
  125227. };
  125228. static static_codebook _8c0_s_p4_0 = {
  125229. 2, 81,
  125230. _vq_lengthlist__8c0_s_p4_0,
  125231. 1, -531628032, 1611661312, 4, 0,
  125232. _vq_quantlist__8c0_s_p4_0,
  125233. NULL,
  125234. &_vq_auxt__8c0_s_p4_0,
  125235. NULL,
  125236. 0
  125237. };
  125238. static long _vq_quantlist__8c0_s_p5_0[] = {
  125239. 4,
  125240. 3,
  125241. 5,
  125242. 2,
  125243. 6,
  125244. 1,
  125245. 7,
  125246. 0,
  125247. 8,
  125248. };
  125249. static long _vq_lengthlist__8c0_s_p5_0[] = {
  125250. 1, 3, 3, 5, 5, 7, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  125251. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 9, 0, 0, 0, 8, 8,
  125252. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8, 9, 9, 0, 0, 0,
  125253. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  125254. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  125255. 10,
  125256. };
  125257. static float _vq_quantthresh__8c0_s_p5_0[] = {
  125258. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  125259. };
  125260. static long _vq_quantmap__8c0_s_p5_0[] = {
  125261. 7, 5, 3, 1, 0, 2, 4, 6,
  125262. 8,
  125263. };
  125264. static encode_aux_threshmatch _vq_auxt__8c0_s_p5_0 = {
  125265. _vq_quantthresh__8c0_s_p5_0,
  125266. _vq_quantmap__8c0_s_p5_0,
  125267. 9,
  125268. 9
  125269. };
  125270. static static_codebook _8c0_s_p5_0 = {
  125271. 2, 81,
  125272. _vq_lengthlist__8c0_s_p5_0,
  125273. 1, -531628032, 1611661312, 4, 0,
  125274. _vq_quantlist__8c0_s_p5_0,
  125275. NULL,
  125276. &_vq_auxt__8c0_s_p5_0,
  125277. NULL,
  125278. 0
  125279. };
  125280. static long _vq_quantlist__8c0_s_p6_0[] = {
  125281. 8,
  125282. 7,
  125283. 9,
  125284. 6,
  125285. 10,
  125286. 5,
  125287. 11,
  125288. 4,
  125289. 12,
  125290. 3,
  125291. 13,
  125292. 2,
  125293. 14,
  125294. 1,
  125295. 15,
  125296. 0,
  125297. 16,
  125298. };
  125299. static long _vq_lengthlist__8c0_s_p6_0[] = {
  125300. 1, 3, 3, 6, 6, 8, 8, 9, 9, 8, 8,10, 9,10,10,11,
  125301. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  125302. 11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  125303. 11,12,11, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,10,10,
  125304. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,11,
  125305. 10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,10,
  125306. 11,11,11,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,
  125307. 10,11,11,12,12,13,13, 0, 0, 0,10,10,10,10,11,11,
  125308. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10, 9,10,
  125309. 11,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  125310. 10, 9,10,11,12,12,13,13,14,13, 0, 0, 0, 0, 0, 9,
  125311. 9, 9,10,10,10,11,11,13,12,13,13, 0, 0, 0, 0, 0,
  125312. 10,10,10,10,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  125313. 0, 0, 0,10,10,11,11,12,12,13,13,13,14, 0, 0, 0,
  125314. 0, 0, 0, 0,11,11,11,11,12,12,13,14,14,14, 0, 0,
  125315. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,14,13, 0,
  125316. 0, 0, 0, 0, 0, 0,11,11,12,12,13,13,14,14,14,14,
  125317. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  125318. 14,
  125319. };
  125320. static float _vq_quantthresh__8c0_s_p6_0[] = {
  125321. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  125322. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  125323. };
  125324. static long _vq_quantmap__8c0_s_p6_0[] = {
  125325. 15, 13, 11, 9, 7, 5, 3, 1,
  125326. 0, 2, 4, 6, 8, 10, 12, 14,
  125327. 16,
  125328. };
  125329. static encode_aux_threshmatch _vq_auxt__8c0_s_p6_0 = {
  125330. _vq_quantthresh__8c0_s_p6_0,
  125331. _vq_quantmap__8c0_s_p6_0,
  125332. 17,
  125333. 17
  125334. };
  125335. static static_codebook _8c0_s_p6_0 = {
  125336. 2, 289,
  125337. _vq_lengthlist__8c0_s_p6_0,
  125338. 1, -529530880, 1611661312, 5, 0,
  125339. _vq_quantlist__8c0_s_p6_0,
  125340. NULL,
  125341. &_vq_auxt__8c0_s_p6_0,
  125342. NULL,
  125343. 0
  125344. };
  125345. static long _vq_quantlist__8c0_s_p7_0[] = {
  125346. 1,
  125347. 0,
  125348. 2,
  125349. };
  125350. static long _vq_lengthlist__8c0_s_p7_0[] = {
  125351. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,11, 9,10,12,
  125352. 9,10, 4, 7, 7,10,10,10,11, 9, 9, 6,11,10,11,11,
  125353. 12,11,11,11, 6,10,10,11,11,12,11,10,10, 6, 9,10,
  125354. 11,11,11,11,10,10, 7,10,11,12,11,11,12,11,12, 6,
  125355. 9, 9,10, 9, 9,11,10,10, 6, 9, 9,10,10,10,11,10,
  125356. 10,
  125357. };
  125358. static float _vq_quantthresh__8c0_s_p7_0[] = {
  125359. -5.5, 5.5,
  125360. };
  125361. static long _vq_quantmap__8c0_s_p7_0[] = {
  125362. 1, 0, 2,
  125363. };
  125364. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_0 = {
  125365. _vq_quantthresh__8c0_s_p7_0,
  125366. _vq_quantmap__8c0_s_p7_0,
  125367. 3,
  125368. 3
  125369. };
  125370. static static_codebook _8c0_s_p7_0 = {
  125371. 4, 81,
  125372. _vq_lengthlist__8c0_s_p7_0,
  125373. 1, -529137664, 1618345984, 2, 0,
  125374. _vq_quantlist__8c0_s_p7_0,
  125375. NULL,
  125376. &_vq_auxt__8c0_s_p7_0,
  125377. NULL,
  125378. 0
  125379. };
  125380. static long _vq_quantlist__8c0_s_p7_1[] = {
  125381. 5,
  125382. 4,
  125383. 6,
  125384. 3,
  125385. 7,
  125386. 2,
  125387. 8,
  125388. 1,
  125389. 9,
  125390. 0,
  125391. 10,
  125392. };
  125393. static long _vq_lengthlist__8c0_s_p7_1[] = {
  125394. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10, 7, 7,
  125395. 8, 8, 9, 9, 9, 9,10,10, 9, 7, 7, 8, 8, 9, 9, 9,
  125396. 9,10,10,10, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10, 8,
  125397. 8, 9, 9, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9,10,
  125398. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,11,10,11,
  125399. 9, 9, 9, 9,10,10,10,10,11,11,11,10,10, 9, 9,10,
  125400. 10,10, 9,11,10,10,10,10,10,10, 9, 9,10,10,11,11,
  125401. 10,10,10, 9, 9, 9,10,10,10,
  125402. };
  125403. static float _vq_quantthresh__8c0_s_p7_1[] = {
  125404. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125405. 3.5, 4.5,
  125406. };
  125407. static long _vq_quantmap__8c0_s_p7_1[] = {
  125408. 9, 7, 5, 3, 1, 0, 2, 4,
  125409. 6, 8, 10,
  125410. };
  125411. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_1 = {
  125412. _vq_quantthresh__8c0_s_p7_1,
  125413. _vq_quantmap__8c0_s_p7_1,
  125414. 11,
  125415. 11
  125416. };
  125417. static static_codebook _8c0_s_p7_1 = {
  125418. 2, 121,
  125419. _vq_lengthlist__8c0_s_p7_1,
  125420. 1, -531365888, 1611661312, 4, 0,
  125421. _vq_quantlist__8c0_s_p7_1,
  125422. NULL,
  125423. &_vq_auxt__8c0_s_p7_1,
  125424. NULL,
  125425. 0
  125426. };
  125427. static long _vq_quantlist__8c0_s_p8_0[] = {
  125428. 6,
  125429. 5,
  125430. 7,
  125431. 4,
  125432. 8,
  125433. 3,
  125434. 9,
  125435. 2,
  125436. 10,
  125437. 1,
  125438. 11,
  125439. 0,
  125440. 12,
  125441. };
  125442. static long _vq_lengthlist__8c0_s_p8_0[] = {
  125443. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 6, 6,
  125444. 7, 7, 8, 8, 7, 7, 8, 9,10,10, 7, 6, 6, 7, 7, 8,
  125445. 7, 7, 7, 9, 9,10,12, 0, 8, 8, 8, 8, 8, 9, 8, 8,
  125446. 9, 9,10,10, 0, 8, 8, 8, 8, 8, 9, 8, 9, 9, 9,11,
  125447. 10, 0, 0,13, 9, 8, 9, 9, 9, 9,10,10,11,11, 0,13,
  125448. 0, 9, 9, 9, 9, 9, 9,11,10,11,11, 0, 0, 0, 8, 9,
  125449. 10, 9,10,10,13,11,12,12, 0, 0, 0, 8, 9, 9, 9,10,
  125450. 10,13,12,12,13, 0, 0, 0,12, 0,10,10,12,11,10,11,
  125451. 12,12, 0, 0, 0,13,13,10,10,10,11,12, 0,13, 0, 0,
  125452. 0, 0, 0, 0,13,11, 0,12,12,12,13,12, 0, 0, 0, 0,
  125453. 0, 0,13,13,11,13,13,11,12,
  125454. };
  125455. static float _vq_quantthresh__8c0_s_p8_0[] = {
  125456. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  125457. 12.5, 17.5, 22.5, 27.5,
  125458. };
  125459. static long _vq_quantmap__8c0_s_p8_0[] = {
  125460. 11, 9, 7, 5, 3, 1, 0, 2,
  125461. 4, 6, 8, 10, 12,
  125462. };
  125463. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_0 = {
  125464. _vq_quantthresh__8c0_s_p8_0,
  125465. _vq_quantmap__8c0_s_p8_0,
  125466. 13,
  125467. 13
  125468. };
  125469. static static_codebook _8c0_s_p8_0 = {
  125470. 2, 169,
  125471. _vq_lengthlist__8c0_s_p8_0,
  125472. 1, -526516224, 1616117760, 4, 0,
  125473. _vq_quantlist__8c0_s_p8_0,
  125474. NULL,
  125475. &_vq_auxt__8c0_s_p8_0,
  125476. NULL,
  125477. 0
  125478. };
  125479. static long _vq_quantlist__8c0_s_p8_1[] = {
  125480. 2,
  125481. 1,
  125482. 3,
  125483. 0,
  125484. 4,
  125485. };
  125486. static long _vq_lengthlist__8c0_s_p8_1[] = {
  125487. 1, 3, 4, 5, 5, 7, 6, 6, 6, 5, 7, 7, 7, 6, 6, 7,
  125488. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  125489. };
  125490. static float _vq_quantthresh__8c0_s_p8_1[] = {
  125491. -1.5, -0.5, 0.5, 1.5,
  125492. };
  125493. static long _vq_quantmap__8c0_s_p8_1[] = {
  125494. 3, 1, 0, 2, 4,
  125495. };
  125496. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_1 = {
  125497. _vq_quantthresh__8c0_s_p8_1,
  125498. _vq_quantmap__8c0_s_p8_1,
  125499. 5,
  125500. 5
  125501. };
  125502. static static_codebook _8c0_s_p8_1 = {
  125503. 2, 25,
  125504. _vq_lengthlist__8c0_s_p8_1,
  125505. 1, -533725184, 1611661312, 3, 0,
  125506. _vq_quantlist__8c0_s_p8_1,
  125507. NULL,
  125508. &_vq_auxt__8c0_s_p8_1,
  125509. NULL,
  125510. 0
  125511. };
  125512. static long _vq_quantlist__8c0_s_p9_0[] = {
  125513. 1,
  125514. 0,
  125515. 2,
  125516. };
  125517. static long _vq_lengthlist__8c0_s_p9_0[] = {
  125518. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125519. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125520. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  125521. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  125522. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  125523. 7,
  125524. };
  125525. static float _vq_quantthresh__8c0_s_p9_0[] = {
  125526. -157.5, 157.5,
  125527. };
  125528. static long _vq_quantmap__8c0_s_p9_0[] = {
  125529. 1, 0, 2,
  125530. };
  125531. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_0 = {
  125532. _vq_quantthresh__8c0_s_p9_0,
  125533. _vq_quantmap__8c0_s_p9_0,
  125534. 3,
  125535. 3
  125536. };
  125537. static static_codebook _8c0_s_p9_0 = {
  125538. 4, 81,
  125539. _vq_lengthlist__8c0_s_p9_0,
  125540. 1, -518803456, 1628680192, 2, 0,
  125541. _vq_quantlist__8c0_s_p9_0,
  125542. NULL,
  125543. &_vq_auxt__8c0_s_p9_0,
  125544. NULL,
  125545. 0
  125546. };
  125547. static long _vq_quantlist__8c0_s_p9_1[] = {
  125548. 7,
  125549. 6,
  125550. 8,
  125551. 5,
  125552. 9,
  125553. 4,
  125554. 10,
  125555. 3,
  125556. 11,
  125557. 2,
  125558. 12,
  125559. 1,
  125560. 13,
  125561. 0,
  125562. 14,
  125563. };
  125564. static long _vq_lengthlist__8c0_s_p9_1[] = {
  125565. 1, 4, 4, 5, 5,10, 8,11,11,11,11,11,11,11,11, 6,
  125566. 6, 6, 7, 6,11,10,11,11,11,11,11,11,11,11, 7, 5,
  125567. 6, 6, 6, 8, 7,11,11,11,11,11,11,11,11,11, 7, 8,
  125568. 8, 8, 9, 9,11,11,11,11,11,11,11,11,11, 9, 8, 7,
  125569. 8, 9,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  125570. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  125571. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  125572. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  125573. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  125574. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  125575. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  125576. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  125577. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  125578. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  125579. 11,
  125580. };
  125581. static float _vq_quantthresh__8c0_s_p9_1[] = {
  125582. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  125583. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  125584. };
  125585. static long _vq_quantmap__8c0_s_p9_1[] = {
  125586. 13, 11, 9, 7, 5, 3, 1, 0,
  125587. 2, 4, 6, 8, 10, 12, 14,
  125588. };
  125589. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_1 = {
  125590. _vq_quantthresh__8c0_s_p9_1,
  125591. _vq_quantmap__8c0_s_p9_1,
  125592. 15,
  125593. 15
  125594. };
  125595. static static_codebook _8c0_s_p9_1 = {
  125596. 2, 225,
  125597. _vq_lengthlist__8c0_s_p9_1,
  125598. 1, -520986624, 1620377600, 4, 0,
  125599. _vq_quantlist__8c0_s_p9_1,
  125600. NULL,
  125601. &_vq_auxt__8c0_s_p9_1,
  125602. NULL,
  125603. 0
  125604. };
  125605. static long _vq_quantlist__8c0_s_p9_2[] = {
  125606. 10,
  125607. 9,
  125608. 11,
  125609. 8,
  125610. 12,
  125611. 7,
  125612. 13,
  125613. 6,
  125614. 14,
  125615. 5,
  125616. 15,
  125617. 4,
  125618. 16,
  125619. 3,
  125620. 17,
  125621. 2,
  125622. 18,
  125623. 1,
  125624. 19,
  125625. 0,
  125626. 20,
  125627. };
  125628. static long _vq_lengthlist__8c0_s_p9_2[] = {
  125629. 1, 5, 5, 7, 7, 8, 7, 8, 8,10,10, 9, 9,10,10,10,
  125630. 11,11,10,12,11,12,12,12, 9, 8, 8, 8, 8, 8, 9,10,
  125631. 10,10,10,11,11,11,10,11,11,12,12,11,12, 8, 8, 7,
  125632. 7, 8, 9,10,10,10, 9,10,10, 9,10,10,11,11,11,11,
  125633. 11,11, 9, 9, 9, 9, 8, 9,10,10,11,10,10,11,11,12,
  125634. 10,10,12,12,11,11,10, 9, 9,10, 8, 9,10,10,10, 9,
  125635. 10,10,11,11,10,11,10,10,10,12,12,12, 9,10, 9,10,
  125636. 9, 9,10,10,11,11,11,11,10,10,10,11,12,11,12,11,
  125637. 12,10,11,10,11, 9,10, 9,10, 9,10,10, 9,10,10,11,
  125638. 10,11,11,11,11,12,11, 9,10,10,10,10,11,11,11,11,
  125639. 11,10,11,11,11,11,10,12,10,12,12,11,12,10,10,11,
  125640. 10, 9,11,10,11, 9,10,11,10,10,10,11,11,11,11,12,
  125641. 12,10, 9, 9,11,10, 9,12,11,10,12,12,11,11,11,11,
  125642. 10,11,11,12,11,10,12, 9,11,10,11,10,10,11,10,11,
  125643. 9,10,10,10,11,12,11,11,12,11,10,10,11,11, 9,10,
  125644. 10,12,10,11,10,10,10, 9,10,10,10,10, 9,10,10,11,
  125645. 11,11,11,12,11,10,10,10,10,11,11,10,11,11, 9,11,
  125646. 10,12,10,12,11,10,11,10,10,10,11,10,10,11,11,10,
  125647. 11,10,10,10,10,11,11,12,10,10,10,11,10,11,12,11,
  125648. 10,11,10,10,11,11,10,12,10, 9,10,10,11,11,11,10,
  125649. 12,10,10,11,11,11,10,10,11,10,10,10,11,10,11,10,
  125650. 12,11,11,10,10,10,12,10,10,11, 9,10,11,11,11,10,
  125651. 10,11,10,10, 9,11,11,12,12,11,12,11,11,11,11,11,
  125652. 11, 9,10,11,10,12,10,10,10,10,11,10,10,11,10,10,
  125653. 12,10,10,10,10,10, 9,12,10,10,10,10,12, 9,11,10,
  125654. 10,11,10,12,12,10,12,12,12,10,10,10,10, 9,10,11,
  125655. 10,10,12,10,10,12,11,10,11,10,10,12,11,10,12,10,
  125656. 10,11, 9,11,10, 9,10, 9,10,
  125657. };
  125658. static float _vq_quantthresh__8c0_s_p9_2[] = {
  125659. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  125660. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  125661. 6.5, 7.5, 8.5, 9.5,
  125662. };
  125663. static long _vq_quantmap__8c0_s_p9_2[] = {
  125664. 19, 17, 15, 13, 11, 9, 7, 5,
  125665. 3, 1, 0, 2, 4, 6, 8, 10,
  125666. 12, 14, 16, 18, 20,
  125667. };
  125668. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_2 = {
  125669. _vq_quantthresh__8c0_s_p9_2,
  125670. _vq_quantmap__8c0_s_p9_2,
  125671. 21,
  125672. 21
  125673. };
  125674. static static_codebook _8c0_s_p9_2 = {
  125675. 2, 441,
  125676. _vq_lengthlist__8c0_s_p9_2,
  125677. 1, -529268736, 1611661312, 5, 0,
  125678. _vq_quantlist__8c0_s_p9_2,
  125679. NULL,
  125680. &_vq_auxt__8c0_s_p9_2,
  125681. NULL,
  125682. 0
  125683. };
  125684. static long _huff_lengthlist__8c0_s_single[] = {
  125685. 4, 5,18, 7,10, 6, 7, 8, 9,10, 5, 2,18, 5, 7, 5,
  125686. 6, 7, 8,11,17,17,17,17,17,17,17,17,17,17, 7, 4,
  125687. 17, 6, 9, 6, 8,10,12,15,11, 7,17, 9, 6, 6, 7, 9,
  125688. 11,15, 6, 4,17, 6, 6, 4, 5, 8,11,16, 6, 6,17, 8,
  125689. 6, 5, 6, 9,13,16, 8, 9,17,11, 9, 8, 8,11,13,17,
  125690. 9,12,17,15,14,13,12,13,14,17,12,15,17,17,17,17,
  125691. 17,16,17,17,
  125692. };
  125693. static static_codebook _huff_book__8c0_s_single = {
  125694. 2, 100,
  125695. _huff_lengthlist__8c0_s_single,
  125696. 0, 0, 0, 0, 0,
  125697. NULL,
  125698. NULL,
  125699. NULL,
  125700. NULL,
  125701. 0
  125702. };
  125703. static long _vq_quantlist__8c1_s_p1_0[] = {
  125704. 1,
  125705. 0,
  125706. 2,
  125707. };
  125708. static long _vq_lengthlist__8c1_s_p1_0[] = {
  125709. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  125710. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125714. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  125715. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125719. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  125720. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  125755. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  125756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  125760. 0, 0, 0, 8, 8,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  125761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  125765. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  125766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125800. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  125801. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125805. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  125806. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  125807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125810. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  125811. 0, 0, 0, 0, 0, 0, 8,10, 8, 0, 0, 0, 0, 0, 0, 0,
  125812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126119. 0,
  126120. };
  126121. static float _vq_quantthresh__8c1_s_p1_0[] = {
  126122. -0.5, 0.5,
  126123. };
  126124. static long _vq_quantmap__8c1_s_p1_0[] = {
  126125. 1, 0, 2,
  126126. };
  126127. static encode_aux_threshmatch _vq_auxt__8c1_s_p1_0 = {
  126128. _vq_quantthresh__8c1_s_p1_0,
  126129. _vq_quantmap__8c1_s_p1_0,
  126130. 3,
  126131. 3
  126132. };
  126133. static static_codebook _8c1_s_p1_0 = {
  126134. 8, 6561,
  126135. _vq_lengthlist__8c1_s_p1_0,
  126136. 1, -535822336, 1611661312, 2, 0,
  126137. _vq_quantlist__8c1_s_p1_0,
  126138. NULL,
  126139. &_vq_auxt__8c1_s_p1_0,
  126140. NULL,
  126141. 0
  126142. };
  126143. static long _vq_quantlist__8c1_s_p2_0[] = {
  126144. 2,
  126145. 1,
  126146. 3,
  126147. 0,
  126148. 4,
  126149. };
  126150. static long _vq_lengthlist__8c1_s_p2_0[] = {
  126151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126190. 0,
  126191. };
  126192. static float _vq_quantthresh__8c1_s_p2_0[] = {
  126193. -1.5, -0.5, 0.5, 1.5,
  126194. };
  126195. static long _vq_quantmap__8c1_s_p2_0[] = {
  126196. 3, 1, 0, 2, 4,
  126197. };
  126198. static encode_aux_threshmatch _vq_auxt__8c1_s_p2_0 = {
  126199. _vq_quantthresh__8c1_s_p2_0,
  126200. _vq_quantmap__8c1_s_p2_0,
  126201. 5,
  126202. 5
  126203. };
  126204. static static_codebook _8c1_s_p2_0 = {
  126205. 4, 625,
  126206. _vq_lengthlist__8c1_s_p2_0,
  126207. 1, -533725184, 1611661312, 3, 0,
  126208. _vq_quantlist__8c1_s_p2_0,
  126209. NULL,
  126210. &_vq_auxt__8c1_s_p2_0,
  126211. NULL,
  126212. 0
  126213. };
  126214. static long _vq_quantlist__8c1_s_p3_0[] = {
  126215. 2,
  126216. 1,
  126217. 3,
  126218. 0,
  126219. 4,
  126220. };
  126221. static long _vq_lengthlist__8c1_s_p3_0[] = {
  126222. 2, 4, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  126224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126225. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 7, 7,
  126227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126228. 0, 0, 0, 0, 6, 6, 6, 7, 7, 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, 0, 0, 0, 0, 0, 0, 0,
  126259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126261. 0,
  126262. };
  126263. static float _vq_quantthresh__8c1_s_p3_0[] = {
  126264. -1.5, -0.5, 0.5, 1.5,
  126265. };
  126266. static long _vq_quantmap__8c1_s_p3_0[] = {
  126267. 3, 1, 0, 2, 4,
  126268. };
  126269. static encode_aux_threshmatch _vq_auxt__8c1_s_p3_0 = {
  126270. _vq_quantthresh__8c1_s_p3_0,
  126271. _vq_quantmap__8c1_s_p3_0,
  126272. 5,
  126273. 5
  126274. };
  126275. static static_codebook _8c1_s_p3_0 = {
  126276. 4, 625,
  126277. _vq_lengthlist__8c1_s_p3_0,
  126278. 1, -533725184, 1611661312, 3, 0,
  126279. _vq_quantlist__8c1_s_p3_0,
  126280. NULL,
  126281. &_vq_auxt__8c1_s_p3_0,
  126282. NULL,
  126283. 0
  126284. };
  126285. static long _vq_quantlist__8c1_s_p4_0[] = {
  126286. 4,
  126287. 3,
  126288. 5,
  126289. 2,
  126290. 6,
  126291. 1,
  126292. 7,
  126293. 0,
  126294. 8,
  126295. };
  126296. static long _vq_lengthlist__8c1_s_p4_0[] = {
  126297. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  126298. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  126299. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  126300. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  126301. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126302. 0,
  126303. };
  126304. static float _vq_quantthresh__8c1_s_p4_0[] = {
  126305. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126306. };
  126307. static long _vq_quantmap__8c1_s_p4_0[] = {
  126308. 7, 5, 3, 1, 0, 2, 4, 6,
  126309. 8,
  126310. };
  126311. static encode_aux_threshmatch _vq_auxt__8c1_s_p4_0 = {
  126312. _vq_quantthresh__8c1_s_p4_0,
  126313. _vq_quantmap__8c1_s_p4_0,
  126314. 9,
  126315. 9
  126316. };
  126317. static static_codebook _8c1_s_p4_0 = {
  126318. 2, 81,
  126319. _vq_lengthlist__8c1_s_p4_0,
  126320. 1, -531628032, 1611661312, 4, 0,
  126321. _vq_quantlist__8c1_s_p4_0,
  126322. NULL,
  126323. &_vq_auxt__8c1_s_p4_0,
  126324. NULL,
  126325. 0
  126326. };
  126327. static long _vq_quantlist__8c1_s_p5_0[] = {
  126328. 4,
  126329. 3,
  126330. 5,
  126331. 2,
  126332. 6,
  126333. 1,
  126334. 7,
  126335. 0,
  126336. 8,
  126337. };
  126338. static long _vq_lengthlist__8c1_s_p5_0[] = {
  126339. 1, 3, 3, 4, 5, 6, 6, 8, 8, 0, 0, 0, 8, 8, 7, 7,
  126340. 9, 9, 0, 0, 0, 8, 8, 7, 7, 9, 9, 0, 0, 0, 9,10,
  126341. 8, 8, 9, 9, 0, 0, 0,10,10, 8, 8, 9, 9, 0, 0, 0,
  126342. 11,10, 8, 8,10,10, 0, 0, 0,11,11, 8, 8,10,10, 0,
  126343. 0, 0,12,12, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  126344. 10,
  126345. };
  126346. static float _vq_quantthresh__8c1_s_p5_0[] = {
  126347. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126348. };
  126349. static long _vq_quantmap__8c1_s_p5_0[] = {
  126350. 7, 5, 3, 1, 0, 2, 4, 6,
  126351. 8,
  126352. };
  126353. static encode_aux_threshmatch _vq_auxt__8c1_s_p5_0 = {
  126354. _vq_quantthresh__8c1_s_p5_0,
  126355. _vq_quantmap__8c1_s_p5_0,
  126356. 9,
  126357. 9
  126358. };
  126359. static static_codebook _8c1_s_p5_0 = {
  126360. 2, 81,
  126361. _vq_lengthlist__8c1_s_p5_0,
  126362. 1, -531628032, 1611661312, 4, 0,
  126363. _vq_quantlist__8c1_s_p5_0,
  126364. NULL,
  126365. &_vq_auxt__8c1_s_p5_0,
  126366. NULL,
  126367. 0
  126368. };
  126369. static long _vq_quantlist__8c1_s_p6_0[] = {
  126370. 8,
  126371. 7,
  126372. 9,
  126373. 6,
  126374. 10,
  126375. 5,
  126376. 11,
  126377. 4,
  126378. 12,
  126379. 3,
  126380. 13,
  126381. 2,
  126382. 14,
  126383. 1,
  126384. 15,
  126385. 0,
  126386. 16,
  126387. };
  126388. static long _vq_lengthlist__8c1_s_p6_0[] = {
  126389. 1, 3, 3, 5, 5, 8, 8, 8, 8, 9, 9,10,10,11,11,11,
  126390. 11, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11,
  126391. 12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  126392. 11,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,11,
  126393. 12,12,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,
  126394. 11,12,12,12,12, 0, 0, 0,10,10, 9, 9,10,10,10,10,
  126395. 11,11,12,12,13,13, 0, 0, 0,10,10, 9, 9,10,10,10,
  126396. 10,11,11,12,12,13,13, 0, 0, 0,11,11, 9, 9,10,10,
  126397. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  126398. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  126399. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  126400. 9,10,10,11,11,12,11,12,12,13,13, 0, 0, 0, 0, 0,
  126401. 10,10,11,11,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  126402. 0, 0, 0,11,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  126403. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  126404. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,13, 0,
  126405. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  126406. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  126407. 14,
  126408. };
  126409. static float _vq_quantthresh__8c1_s_p6_0[] = {
  126410. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  126411. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  126412. };
  126413. static long _vq_quantmap__8c1_s_p6_0[] = {
  126414. 15, 13, 11, 9, 7, 5, 3, 1,
  126415. 0, 2, 4, 6, 8, 10, 12, 14,
  126416. 16,
  126417. };
  126418. static encode_aux_threshmatch _vq_auxt__8c1_s_p6_0 = {
  126419. _vq_quantthresh__8c1_s_p6_0,
  126420. _vq_quantmap__8c1_s_p6_0,
  126421. 17,
  126422. 17
  126423. };
  126424. static static_codebook _8c1_s_p6_0 = {
  126425. 2, 289,
  126426. _vq_lengthlist__8c1_s_p6_0,
  126427. 1, -529530880, 1611661312, 5, 0,
  126428. _vq_quantlist__8c1_s_p6_0,
  126429. NULL,
  126430. &_vq_auxt__8c1_s_p6_0,
  126431. NULL,
  126432. 0
  126433. };
  126434. static long _vq_quantlist__8c1_s_p7_0[] = {
  126435. 1,
  126436. 0,
  126437. 2,
  126438. };
  126439. static long _vq_lengthlist__8c1_s_p7_0[] = {
  126440. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  126441. 9, 9, 5, 7, 7,10, 9, 9,10, 9, 9, 6,10,10,10,10,
  126442. 10,11,10,10, 6, 9, 9,10, 9,10,11,10,10, 6, 9, 9,
  126443. 10, 9, 9,11, 9,10, 7,10,10,11,11,11,11,10,10, 6,
  126444. 9, 9,10,10,10,11, 9, 9, 6, 9, 9,10,10,10,10, 9,
  126445. 9,
  126446. };
  126447. static float _vq_quantthresh__8c1_s_p7_0[] = {
  126448. -5.5, 5.5,
  126449. };
  126450. static long _vq_quantmap__8c1_s_p7_0[] = {
  126451. 1, 0, 2,
  126452. };
  126453. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_0 = {
  126454. _vq_quantthresh__8c1_s_p7_0,
  126455. _vq_quantmap__8c1_s_p7_0,
  126456. 3,
  126457. 3
  126458. };
  126459. static static_codebook _8c1_s_p7_0 = {
  126460. 4, 81,
  126461. _vq_lengthlist__8c1_s_p7_0,
  126462. 1, -529137664, 1618345984, 2, 0,
  126463. _vq_quantlist__8c1_s_p7_0,
  126464. NULL,
  126465. &_vq_auxt__8c1_s_p7_0,
  126466. NULL,
  126467. 0
  126468. };
  126469. static long _vq_quantlist__8c1_s_p7_1[] = {
  126470. 5,
  126471. 4,
  126472. 6,
  126473. 3,
  126474. 7,
  126475. 2,
  126476. 8,
  126477. 1,
  126478. 9,
  126479. 0,
  126480. 10,
  126481. };
  126482. static long _vq_lengthlist__8c1_s_p7_1[] = {
  126483. 2, 3, 3, 5, 5, 7, 7, 7, 7, 7, 7,10,10, 9, 7, 7,
  126484. 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8,
  126485. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  126486. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  126487. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  126488. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  126489. 8, 8, 8,10,10,10,10,10, 8, 8, 8, 8, 8, 8,10,10,
  126490. 10,10,10, 8, 8, 8, 8, 8, 8,
  126491. };
  126492. static float _vq_quantthresh__8c1_s_p7_1[] = {
  126493. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  126494. 3.5, 4.5,
  126495. };
  126496. static long _vq_quantmap__8c1_s_p7_1[] = {
  126497. 9, 7, 5, 3, 1, 0, 2, 4,
  126498. 6, 8, 10,
  126499. };
  126500. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_1 = {
  126501. _vq_quantthresh__8c1_s_p7_1,
  126502. _vq_quantmap__8c1_s_p7_1,
  126503. 11,
  126504. 11
  126505. };
  126506. static static_codebook _8c1_s_p7_1 = {
  126507. 2, 121,
  126508. _vq_lengthlist__8c1_s_p7_1,
  126509. 1, -531365888, 1611661312, 4, 0,
  126510. _vq_quantlist__8c1_s_p7_1,
  126511. NULL,
  126512. &_vq_auxt__8c1_s_p7_1,
  126513. NULL,
  126514. 0
  126515. };
  126516. static long _vq_quantlist__8c1_s_p8_0[] = {
  126517. 6,
  126518. 5,
  126519. 7,
  126520. 4,
  126521. 8,
  126522. 3,
  126523. 9,
  126524. 2,
  126525. 10,
  126526. 1,
  126527. 11,
  126528. 0,
  126529. 12,
  126530. };
  126531. static long _vq_lengthlist__8c1_s_p8_0[] = {
  126532. 1, 4, 4, 6, 6, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5,
  126533. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  126534. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  126535. 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  126536. 11, 0,12,12, 9, 9, 9, 9,10, 9,10,11,11,11, 0,13,
  126537. 12, 9, 8, 9, 9,10,10,11,11,12,11, 0, 0, 0, 9, 9,
  126538. 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10, 9, 9,10,
  126539. 10,11,11,12,12, 0, 0, 0,13,13,10,10,11,11,12,11,
  126540. 13,12, 0, 0, 0,14,14,10,10,11,10,11,11,12,12, 0,
  126541. 0, 0, 0, 0,12,12,11,11,12,12,13,13, 0, 0, 0, 0,
  126542. 0,12,12,11,10,12,11,13,12,
  126543. };
  126544. static float _vq_quantthresh__8c1_s_p8_0[] = {
  126545. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  126546. 12.5, 17.5, 22.5, 27.5,
  126547. };
  126548. static long _vq_quantmap__8c1_s_p8_0[] = {
  126549. 11, 9, 7, 5, 3, 1, 0, 2,
  126550. 4, 6, 8, 10, 12,
  126551. };
  126552. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_0 = {
  126553. _vq_quantthresh__8c1_s_p8_0,
  126554. _vq_quantmap__8c1_s_p8_0,
  126555. 13,
  126556. 13
  126557. };
  126558. static static_codebook _8c1_s_p8_0 = {
  126559. 2, 169,
  126560. _vq_lengthlist__8c1_s_p8_0,
  126561. 1, -526516224, 1616117760, 4, 0,
  126562. _vq_quantlist__8c1_s_p8_0,
  126563. NULL,
  126564. &_vq_auxt__8c1_s_p8_0,
  126565. NULL,
  126566. 0
  126567. };
  126568. static long _vq_quantlist__8c1_s_p8_1[] = {
  126569. 2,
  126570. 1,
  126571. 3,
  126572. 0,
  126573. 4,
  126574. };
  126575. static long _vq_lengthlist__8c1_s_p8_1[] = {
  126576. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  126577. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  126578. };
  126579. static float _vq_quantthresh__8c1_s_p8_1[] = {
  126580. -1.5, -0.5, 0.5, 1.5,
  126581. };
  126582. static long _vq_quantmap__8c1_s_p8_1[] = {
  126583. 3, 1, 0, 2, 4,
  126584. };
  126585. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_1 = {
  126586. _vq_quantthresh__8c1_s_p8_1,
  126587. _vq_quantmap__8c1_s_p8_1,
  126588. 5,
  126589. 5
  126590. };
  126591. static static_codebook _8c1_s_p8_1 = {
  126592. 2, 25,
  126593. _vq_lengthlist__8c1_s_p8_1,
  126594. 1, -533725184, 1611661312, 3, 0,
  126595. _vq_quantlist__8c1_s_p8_1,
  126596. NULL,
  126597. &_vq_auxt__8c1_s_p8_1,
  126598. NULL,
  126599. 0
  126600. };
  126601. static long _vq_quantlist__8c1_s_p9_0[] = {
  126602. 6,
  126603. 5,
  126604. 7,
  126605. 4,
  126606. 8,
  126607. 3,
  126608. 9,
  126609. 2,
  126610. 10,
  126611. 1,
  126612. 11,
  126613. 0,
  126614. 12,
  126615. };
  126616. static long _vq_lengthlist__8c1_s_p9_0[] = {
  126617. 1, 3, 3,10,10,10,10,10,10,10,10,10,10, 5, 6, 6,
  126618. 10,10,10,10,10,10,10,10,10,10, 6, 7, 8,10,10,10,
  126619. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  126620. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  126621. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  126622. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  126623. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  126624. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  126625. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  126626. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  126627. 10,10,10,10,10, 9, 9, 9, 9,
  126628. };
  126629. static float _vq_quantthresh__8c1_s_p9_0[] = {
  126630. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  126631. 787.5, 1102.5, 1417.5, 1732.5,
  126632. };
  126633. static long _vq_quantmap__8c1_s_p9_0[] = {
  126634. 11, 9, 7, 5, 3, 1, 0, 2,
  126635. 4, 6, 8, 10, 12,
  126636. };
  126637. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_0 = {
  126638. _vq_quantthresh__8c1_s_p9_0,
  126639. _vq_quantmap__8c1_s_p9_0,
  126640. 13,
  126641. 13
  126642. };
  126643. static static_codebook _8c1_s_p9_0 = {
  126644. 2, 169,
  126645. _vq_lengthlist__8c1_s_p9_0,
  126646. 1, -513964032, 1628680192, 4, 0,
  126647. _vq_quantlist__8c1_s_p9_0,
  126648. NULL,
  126649. &_vq_auxt__8c1_s_p9_0,
  126650. NULL,
  126651. 0
  126652. };
  126653. static long _vq_quantlist__8c1_s_p9_1[] = {
  126654. 7,
  126655. 6,
  126656. 8,
  126657. 5,
  126658. 9,
  126659. 4,
  126660. 10,
  126661. 3,
  126662. 11,
  126663. 2,
  126664. 12,
  126665. 1,
  126666. 13,
  126667. 0,
  126668. 14,
  126669. };
  126670. static long _vq_lengthlist__8c1_s_p9_1[] = {
  126671. 1, 4, 4, 5, 5, 7, 7, 9, 9,11,11,12,12,13,13, 6,
  126672. 5, 5, 6, 6, 9, 9,10,10,12,12,12,13,15,14, 6, 5,
  126673. 5, 7, 7, 9, 9,10,10,12,12,12,13,14,13,17, 7, 7,
  126674. 8, 8,10,10,11,11,12,13,13,13,13,13,17, 7, 7, 8,
  126675. 8,10,10,11,11,13,13,13,13,14,14,17,11,11, 9, 9,
  126676. 11,11,12,12,12,13,13,14,15,13,17,12,12, 9, 9,11,
  126677. 11,12,12,13,13,13,13,14,16,17,17,17,11,12,12,12,
  126678. 13,13,13,14,15,14,15,15,17,17,17,12,12,11,11,13,
  126679. 13,14,14,15,14,15,15,17,17,17,15,15,13,13,14,14,
  126680. 15,14,15,15,16,15,17,17,17,15,15,13,13,13,14,14,
  126681. 15,15,15,15,16,17,17,17,17,16,14,15,14,14,15,14,
  126682. 14,15,15,15,17,17,17,17,17,14,14,16,14,15,15,15,
  126683. 15,15,15,17,17,17,17,17,17,16,16,15,17,15,15,14,
  126684. 17,15,17,16,17,17,17,17,16,15,14,15,15,15,15,15,
  126685. 15,
  126686. };
  126687. static float _vq_quantthresh__8c1_s_p9_1[] = {
  126688. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  126689. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  126690. };
  126691. static long _vq_quantmap__8c1_s_p9_1[] = {
  126692. 13, 11, 9, 7, 5, 3, 1, 0,
  126693. 2, 4, 6, 8, 10, 12, 14,
  126694. };
  126695. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_1 = {
  126696. _vq_quantthresh__8c1_s_p9_1,
  126697. _vq_quantmap__8c1_s_p9_1,
  126698. 15,
  126699. 15
  126700. };
  126701. static static_codebook _8c1_s_p9_1 = {
  126702. 2, 225,
  126703. _vq_lengthlist__8c1_s_p9_1,
  126704. 1, -520986624, 1620377600, 4, 0,
  126705. _vq_quantlist__8c1_s_p9_1,
  126706. NULL,
  126707. &_vq_auxt__8c1_s_p9_1,
  126708. NULL,
  126709. 0
  126710. };
  126711. static long _vq_quantlist__8c1_s_p9_2[] = {
  126712. 10,
  126713. 9,
  126714. 11,
  126715. 8,
  126716. 12,
  126717. 7,
  126718. 13,
  126719. 6,
  126720. 14,
  126721. 5,
  126722. 15,
  126723. 4,
  126724. 16,
  126725. 3,
  126726. 17,
  126727. 2,
  126728. 18,
  126729. 1,
  126730. 19,
  126731. 0,
  126732. 20,
  126733. };
  126734. static long _vq_lengthlist__8c1_s_p9_2[] = {
  126735. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  126736. 9, 9, 9, 9, 9,11,11,12, 7, 7, 7, 7, 8, 8, 9, 9,
  126737. 9, 9,10,10,10,10,10,10,10,10,11,11,11, 7, 7, 7,
  126738. 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,11,
  126739. 11,12, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,
  126740. 10,10,10,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  126741. 9,10,10,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  126742. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,11,11,
  126743. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  126744. 10,10,10,11,12,11, 9, 9, 8, 9, 9, 9, 9, 9,10,10,
  126745. 10,10,10,10,10,10,10,10,11,11,11,11,11, 8, 8, 9,
  126746. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,11,12,11,
  126747. 12,11, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  126748. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  126749. 10,10,10,10,10,10,10,12,11,12,11,11, 9, 9, 9,10,
  126750. 10,10,10,10,10,10,10,10,10,10,10,10,12,11,11,11,
  126751. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  126752. 11,11,11,12,11,11,12,11,10,10,10,10,10,10,10,10,
  126753. 10,10,10,10,11,10,11,11,11,11,11,11,11,10,10,10,
  126754. 10,10,10,10,10,10,10,10,10,10,10,11,11,12,11,12,
  126755. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  126756. 11,11,12,11,12,11,11,11,11,10,10,10,10,10,10,10,
  126757. 10,10,10,10,10,11,11,12,11,11,12,11,11,12,10,10,
  126758. 11,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  126759. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,12,
  126760. 12,11,12,11,11,12,12,12,11,11,10,10,10,10,10,10,
  126761. 10,10,10,11,12,12,11,12,12,11,12,11,11,11,11,10,
  126762. 10,10,10,10,10,10,10,10,10,
  126763. };
  126764. static float _vq_quantthresh__8c1_s_p9_2[] = {
  126765. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  126766. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  126767. 6.5, 7.5, 8.5, 9.5,
  126768. };
  126769. static long _vq_quantmap__8c1_s_p9_2[] = {
  126770. 19, 17, 15, 13, 11, 9, 7, 5,
  126771. 3, 1, 0, 2, 4, 6, 8, 10,
  126772. 12, 14, 16, 18, 20,
  126773. };
  126774. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_2 = {
  126775. _vq_quantthresh__8c1_s_p9_2,
  126776. _vq_quantmap__8c1_s_p9_2,
  126777. 21,
  126778. 21
  126779. };
  126780. static static_codebook _8c1_s_p9_2 = {
  126781. 2, 441,
  126782. _vq_lengthlist__8c1_s_p9_2,
  126783. 1, -529268736, 1611661312, 5, 0,
  126784. _vq_quantlist__8c1_s_p9_2,
  126785. NULL,
  126786. &_vq_auxt__8c1_s_p9_2,
  126787. NULL,
  126788. 0
  126789. };
  126790. static long _huff_lengthlist__8c1_s_single[] = {
  126791. 4, 6,18, 8,11, 8, 8, 9, 9,10, 4, 4,18, 5, 9, 5,
  126792. 6, 7, 8,10,18,18,18,18,17,17,17,17,17,17, 7, 5,
  126793. 17, 6,11, 6, 7, 8, 9,12,12, 9,17,12, 8, 8, 9,10,
  126794. 10,13, 7, 5,17, 6, 8, 4, 5, 6, 8,10, 6, 5,17, 6,
  126795. 8, 5, 4, 5, 7, 9, 7, 7,17, 8, 9, 6, 5, 5, 6, 8,
  126796. 8, 8,17, 9,11, 8, 6, 6, 6, 7, 9,10,17,12,12,10,
  126797. 9, 7, 7, 8,
  126798. };
  126799. static static_codebook _huff_book__8c1_s_single = {
  126800. 2, 100,
  126801. _huff_lengthlist__8c1_s_single,
  126802. 0, 0, 0, 0, 0,
  126803. NULL,
  126804. NULL,
  126805. NULL,
  126806. NULL,
  126807. 0
  126808. };
  126809. static long _huff_lengthlist__44c2_s_long[] = {
  126810. 6, 6,12,10,10,10, 9,10,12,12, 6, 1,10, 5, 6, 6,
  126811. 7, 9,11,14,12, 9, 8,11, 7, 8, 9,11,13,15,10, 5,
  126812. 12, 7, 8, 7, 9,12,14,15,10, 6, 7, 8, 5, 6, 7, 9,
  126813. 12,14, 9, 6, 8, 7, 6, 6, 7, 9,12,12, 9, 7, 9, 9,
  126814. 7, 6, 6, 7,10,10,10, 9,10,11, 8, 7, 6, 6, 8,10,
  126815. 12,11,13,13,11,10, 8, 8, 8,10,11,13,15,15,14,13,
  126816. 10, 8, 8, 9,
  126817. };
  126818. static static_codebook _huff_book__44c2_s_long = {
  126819. 2, 100,
  126820. _huff_lengthlist__44c2_s_long,
  126821. 0, 0, 0, 0, 0,
  126822. NULL,
  126823. NULL,
  126824. NULL,
  126825. NULL,
  126826. 0
  126827. };
  126828. static long _vq_quantlist__44c2_s_p1_0[] = {
  126829. 1,
  126830. 0,
  126831. 2,
  126832. };
  126833. static long _vq_lengthlist__44c2_s_p1_0[] = {
  126834. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  126835. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126839. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  126840. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126844. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  126845. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  126880. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  126881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  126885. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  126886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  126890. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  126891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126925. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  126926. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126930. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  126931. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  126932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126935. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  126936. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  126937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127244. 0,
  127245. };
  127246. static float _vq_quantthresh__44c2_s_p1_0[] = {
  127247. -0.5, 0.5,
  127248. };
  127249. static long _vq_quantmap__44c2_s_p1_0[] = {
  127250. 1, 0, 2,
  127251. };
  127252. static encode_aux_threshmatch _vq_auxt__44c2_s_p1_0 = {
  127253. _vq_quantthresh__44c2_s_p1_0,
  127254. _vq_quantmap__44c2_s_p1_0,
  127255. 3,
  127256. 3
  127257. };
  127258. static static_codebook _44c2_s_p1_0 = {
  127259. 8, 6561,
  127260. _vq_lengthlist__44c2_s_p1_0,
  127261. 1, -535822336, 1611661312, 2, 0,
  127262. _vq_quantlist__44c2_s_p1_0,
  127263. NULL,
  127264. &_vq_auxt__44c2_s_p1_0,
  127265. NULL,
  127266. 0
  127267. };
  127268. static long _vq_quantlist__44c2_s_p2_0[] = {
  127269. 2,
  127270. 1,
  127271. 3,
  127272. 0,
  127273. 4,
  127274. };
  127275. static long _vq_lengthlist__44c2_s_p2_0[] = {
  127276. 1, 4, 4, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0,
  127277. 8, 8, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  127278. 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  127279. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0,
  127280. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127285. 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,11,11, 0, 0,
  127286. 0,11,11, 0, 0, 0,12,11, 0, 0, 0, 0, 0, 0, 0, 7,
  127287. 8, 8, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0, 0,11,
  127288. 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127293. 0, 0, 0, 6, 8, 8, 0, 0, 0,11,11, 0, 0, 0,11,11,
  127294. 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0,
  127295. 0, 0,10,11, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0,
  127296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127301. 8, 9, 9, 0, 0, 0,11,12, 0, 0, 0,11,12, 0, 0, 0,
  127302. 12,11, 0, 0, 0, 0, 0, 0, 0, 8,10, 9, 0, 0, 0,12,
  127303. 11, 0, 0, 0,12,11, 0, 0, 0,11,12, 0, 0, 0, 0, 0,
  127304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127315. 0,
  127316. };
  127317. static float _vq_quantthresh__44c2_s_p2_0[] = {
  127318. -1.5, -0.5, 0.5, 1.5,
  127319. };
  127320. static long _vq_quantmap__44c2_s_p2_0[] = {
  127321. 3, 1, 0, 2, 4,
  127322. };
  127323. static encode_aux_threshmatch _vq_auxt__44c2_s_p2_0 = {
  127324. _vq_quantthresh__44c2_s_p2_0,
  127325. _vq_quantmap__44c2_s_p2_0,
  127326. 5,
  127327. 5
  127328. };
  127329. static static_codebook _44c2_s_p2_0 = {
  127330. 4, 625,
  127331. _vq_lengthlist__44c2_s_p2_0,
  127332. 1, -533725184, 1611661312, 3, 0,
  127333. _vq_quantlist__44c2_s_p2_0,
  127334. NULL,
  127335. &_vq_auxt__44c2_s_p2_0,
  127336. NULL,
  127337. 0
  127338. };
  127339. static long _vq_quantlist__44c2_s_p3_0[] = {
  127340. 2,
  127341. 1,
  127342. 3,
  127343. 0,
  127344. 4,
  127345. };
  127346. static long _vq_lengthlist__44c2_s_p3_0[] = {
  127347. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  127349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127350. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  127352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127353. 0, 0, 0, 0, 6, 6, 7, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0,
  127384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127386. 0,
  127387. };
  127388. static float _vq_quantthresh__44c2_s_p3_0[] = {
  127389. -1.5, -0.5, 0.5, 1.5,
  127390. };
  127391. static long _vq_quantmap__44c2_s_p3_0[] = {
  127392. 3, 1, 0, 2, 4,
  127393. };
  127394. static encode_aux_threshmatch _vq_auxt__44c2_s_p3_0 = {
  127395. _vq_quantthresh__44c2_s_p3_0,
  127396. _vq_quantmap__44c2_s_p3_0,
  127397. 5,
  127398. 5
  127399. };
  127400. static static_codebook _44c2_s_p3_0 = {
  127401. 4, 625,
  127402. _vq_lengthlist__44c2_s_p3_0,
  127403. 1, -533725184, 1611661312, 3, 0,
  127404. _vq_quantlist__44c2_s_p3_0,
  127405. NULL,
  127406. &_vq_auxt__44c2_s_p3_0,
  127407. NULL,
  127408. 0
  127409. };
  127410. static long _vq_quantlist__44c2_s_p4_0[] = {
  127411. 4,
  127412. 3,
  127413. 5,
  127414. 2,
  127415. 6,
  127416. 1,
  127417. 7,
  127418. 0,
  127419. 8,
  127420. };
  127421. static long _vq_lengthlist__44c2_s_p4_0[] = {
  127422. 1, 3, 3, 6, 6, 0, 0, 0, 0, 0, 6, 6, 6, 6, 0, 0,
  127423. 0, 0, 0, 6, 6, 6, 6, 0, 0, 0, 0, 0, 7, 7, 6, 6,
  127424. 0, 0, 0, 0, 0, 0, 0, 6, 7, 0, 0, 0, 0, 0, 0, 0,
  127425. 7, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  127426. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127427. 0,
  127428. };
  127429. static float _vq_quantthresh__44c2_s_p4_0[] = {
  127430. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127431. };
  127432. static long _vq_quantmap__44c2_s_p4_0[] = {
  127433. 7, 5, 3, 1, 0, 2, 4, 6,
  127434. 8,
  127435. };
  127436. static encode_aux_threshmatch _vq_auxt__44c2_s_p4_0 = {
  127437. _vq_quantthresh__44c2_s_p4_0,
  127438. _vq_quantmap__44c2_s_p4_0,
  127439. 9,
  127440. 9
  127441. };
  127442. static static_codebook _44c2_s_p4_0 = {
  127443. 2, 81,
  127444. _vq_lengthlist__44c2_s_p4_0,
  127445. 1, -531628032, 1611661312, 4, 0,
  127446. _vq_quantlist__44c2_s_p4_0,
  127447. NULL,
  127448. &_vq_auxt__44c2_s_p4_0,
  127449. NULL,
  127450. 0
  127451. };
  127452. static long _vq_quantlist__44c2_s_p5_0[] = {
  127453. 4,
  127454. 3,
  127455. 5,
  127456. 2,
  127457. 6,
  127458. 1,
  127459. 7,
  127460. 0,
  127461. 8,
  127462. };
  127463. static long _vq_lengthlist__44c2_s_p5_0[] = {
  127464. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 7, 7, 7, 7, 7, 7,
  127465. 9, 9, 0, 7, 7, 7, 7, 7, 7, 9, 9, 0, 8, 8, 7, 7,
  127466. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  127467. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  127468. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  127469. 11,
  127470. };
  127471. static float _vq_quantthresh__44c2_s_p5_0[] = {
  127472. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127473. };
  127474. static long _vq_quantmap__44c2_s_p5_0[] = {
  127475. 7, 5, 3, 1, 0, 2, 4, 6,
  127476. 8,
  127477. };
  127478. static encode_aux_threshmatch _vq_auxt__44c2_s_p5_0 = {
  127479. _vq_quantthresh__44c2_s_p5_0,
  127480. _vq_quantmap__44c2_s_p5_0,
  127481. 9,
  127482. 9
  127483. };
  127484. static static_codebook _44c2_s_p5_0 = {
  127485. 2, 81,
  127486. _vq_lengthlist__44c2_s_p5_0,
  127487. 1, -531628032, 1611661312, 4, 0,
  127488. _vq_quantlist__44c2_s_p5_0,
  127489. NULL,
  127490. &_vq_auxt__44c2_s_p5_0,
  127491. NULL,
  127492. 0
  127493. };
  127494. static long _vq_quantlist__44c2_s_p6_0[] = {
  127495. 8,
  127496. 7,
  127497. 9,
  127498. 6,
  127499. 10,
  127500. 5,
  127501. 11,
  127502. 4,
  127503. 12,
  127504. 3,
  127505. 13,
  127506. 2,
  127507. 14,
  127508. 1,
  127509. 15,
  127510. 0,
  127511. 16,
  127512. };
  127513. static long _vq_lengthlist__44c2_s_p6_0[] = {
  127514. 1, 4, 3, 6, 6, 8, 8, 9, 9, 9, 9, 9, 9,10,10,11,
  127515. 11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  127516. 12,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  127517. 11,11,12, 0, 8, 8, 7, 7, 9, 9,10,10, 9, 9,10,10,
  127518. 11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10, 9,10,
  127519. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  127520. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  127521. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  127522. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  127523. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  127524. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  127525. 9,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  127526. 10,10,10,10,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  127527. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  127528. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  127529. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  127530. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  127531. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  127532. 14,
  127533. };
  127534. static float _vq_quantthresh__44c2_s_p6_0[] = {
  127535. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  127536. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  127537. };
  127538. static long _vq_quantmap__44c2_s_p6_0[] = {
  127539. 15, 13, 11, 9, 7, 5, 3, 1,
  127540. 0, 2, 4, 6, 8, 10, 12, 14,
  127541. 16,
  127542. };
  127543. static encode_aux_threshmatch _vq_auxt__44c2_s_p6_0 = {
  127544. _vq_quantthresh__44c2_s_p6_0,
  127545. _vq_quantmap__44c2_s_p6_0,
  127546. 17,
  127547. 17
  127548. };
  127549. static static_codebook _44c2_s_p6_0 = {
  127550. 2, 289,
  127551. _vq_lengthlist__44c2_s_p6_0,
  127552. 1, -529530880, 1611661312, 5, 0,
  127553. _vq_quantlist__44c2_s_p6_0,
  127554. NULL,
  127555. &_vq_auxt__44c2_s_p6_0,
  127556. NULL,
  127557. 0
  127558. };
  127559. static long _vq_quantlist__44c2_s_p7_0[] = {
  127560. 1,
  127561. 0,
  127562. 2,
  127563. };
  127564. static long _vq_lengthlist__44c2_s_p7_0[] = {
  127565. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  127566. 9, 9, 4, 7, 7,10, 9, 9,10, 9, 9, 7,10,10,11,10,
  127567. 11,11,10,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  127568. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 6,
  127569. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,12,10,
  127570. 11,
  127571. };
  127572. static float _vq_quantthresh__44c2_s_p7_0[] = {
  127573. -5.5, 5.5,
  127574. };
  127575. static long _vq_quantmap__44c2_s_p7_0[] = {
  127576. 1, 0, 2,
  127577. };
  127578. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_0 = {
  127579. _vq_quantthresh__44c2_s_p7_0,
  127580. _vq_quantmap__44c2_s_p7_0,
  127581. 3,
  127582. 3
  127583. };
  127584. static static_codebook _44c2_s_p7_0 = {
  127585. 4, 81,
  127586. _vq_lengthlist__44c2_s_p7_0,
  127587. 1, -529137664, 1618345984, 2, 0,
  127588. _vq_quantlist__44c2_s_p7_0,
  127589. NULL,
  127590. &_vq_auxt__44c2_s_p7_0,
  127591. NULL,
  127592. 0
  127593. };
  127594. static long _vq_quantlist__44c2_s_p7_1[] = {
  127595. 5,
  127596. 4,
  127597. 6,
  127598. 3,
  127599. 7,
  127600. 2,
  127601. 8,
  127602. 1,
  127603. 9,
  127604. 0,
  127605. 10,
  127606. };
  127607. static long _vq_lengthlist__44c2_s_p7_1[] = {
  127608. 2, 3, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 7, 7, 6, 6,
  127609. 7, 7, 8, 8, 8, 8, 9, 6, 6, 6, 6, 7, 7, 8, 8, 8,
  127610. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  127611. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  127612. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  127613. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  127614. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  127615. 10,10,10, 8, 8, 8, 8, 8, 8,
  127616. };
  127617. static float _vq_quantthresh__44c2_s_p7_1[] = {
  127618. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  127619. 3.5, 4.5,
  127620. };
  127621. static long _vq_quantmap__44c2_s_p7_1[] = {
  127622. 9, 7, 5, 3, 1, 0, 2, 4,
  127623. 6, 8, 10,
  127624. };
  127625. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_1 = {
  127626. _vq_quantthresh__44c2_s_p7_1,
  127627. _vq_quantmap__44c2_s_p7_1,
  127628. 11,
  127629. 11
  127630. };
  127631. static static_codebook _44c2_s_p7_1 = {
  127632. 2, 121,
  127633. _vq_lengthlist__44c2_s_p7_1,
  127634. 1, -531365888, 1611661312, 4, 0,
  127635. _vq_quantlist__44c2_s_p7_1,
  127636. NULL,
  127637. &_vq_auxt__44c2_s_p7_1,
  127638. NULL,
  127639. 0
  127640. };
  127641. static long _vq_quantlist__44c2_s_p8_0[] = {
  127642. 6,
  127643. 5,
  127644. 7,
  127645. 4,
  127646. 8,
  127647. 3,
  127648. 9,
  127649. 2,
  127650. 10,
  127651. 1,
  127652. 11,
  127653. 0,
  127654. 12,
  127655. };
  127656. static long _vq_lengthlist__44c2_s_p8_0[] = {
  127657. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  127658. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  127659. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  127660. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  127661. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  127662. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  127663. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  127664. 11,12,12,12,12, 0, 0, 0,14,14,10,11,11,11,12,12,
  127665. 13,13, 0, 0, 0,14,14,11,10,11,11,13,12,13,13, 0,
  127666. 0, 0, 0, 0,12,12,11,12,13,12,14,14, 0, 0, 0, 0,
  127667. 0,12,12,12,12,13,12,14,14,
  127668. };
  127669. static float _vq_quantthresh__44c2_s_p8_0[] = {
  127670. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  127671. 12.5, 17.5, 22.5, 27.5,
  127672. };
  127673. static long _vq_quantmap__44c2_s_p8_0[] = {
  127674. 11, 9, 7, 5, 3, 1, 0, 2,
  127675. 4, 6, 8, 10, 12,
  127676. };
  127677. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_0 = {
  127678. _vq_quantthresh__44c2_s_p8_0,
  127679. _vq_quantmap__44c2_s_p8_0,
  127680. 13,
  127681. 13
  127682. };
  127683. static static_codebook _44c2_s_p8_0 = {
  127684. 2, 169,
  127685. _vq_lengthlist__44c2_s_p8_0,
  127686. 1, -526516224, 1616117760, 4, 0,
  127687. _vq_quantlist__44c2_s_p8_0,
  127688. NULL,
  127689. &_vq_auxt__44c2_s_p8_0,
  127690. NULL,
  127691. 0
  127692. };
  127693. static long _vq_quantlist__44c2_s_p8_1[] = {
  127694. 2,
  127695. 1,
  127696. 3,
  127697. 0,
  127698. 4,
  127699. };
  127700. static long _vq_lengthlist__44c2_s_p8_1[] = {
  127701. 2, 4, 4, 5, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  127702. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  127703. };
  127704. static float _vq_quantthresh__44c2_s_p8_1[] = {
  127705. -1.5, -0.5, 0.5, 1.5,
  127706. };
  127707. static long _vq_quantmap__44c2_s_p8_1[] = {
  127708. 3, 1, 0, 2, 4,
  127709. };
  127710. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_1 = {
  127711. _vq_quantthresh__44c2_s_p8_1,
  127712. _vq_quantmap__44c2_s_p8_1,
  127713. 5,
  127714. 5
  127715. };
  127716. static static_codebook _44c2_s_p8_1 = {
  127717. 2, 25,
  127718. _vq_lengthlist__44c2_s_p8_1,
  127719. 1, -533725184, 1611661312, 3, 0,
  127720. _vq_quantlist__44c2_s_p8_1,
  127721. NULL,
  127722. &_vq_auxt__44c2_s_p8_1,
  127723. NULL,
  127724. 0
  127725. };
  127726. static long _vq_quantlist__44c2_s_p9_0[] = {
  127727. 6,
  127728. 5,
  127729. 7,
  127730. 4,
  127731. 8,
  127732. 3,
  127733. 9,
  127734. 2,
  127735. 10,
  127736. 1,
  127737. 11,
  127738. 0,
  127739. 12,
  127740. };
  127741. static long _vq_lengthlist__44c2_s_p9_0[] = {
  127742. 1, 5, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  127743. 11,11,11,11,11,11,11,11,11,11, 2, 8, 7,11,11,11,
  127744. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127745. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  127746. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127747. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127748. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127749. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127750. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127751. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127752. 11,11,11,11,11,11,11,11,11,
  127753. };
  127754. static float _vq_quantthresh__44c2_s_p9_0[] = {
  127755. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  127756. 552.5, 773.5, 994.5, 1215.5,
  127757. };
  127758. static long _vq_quantmap__44c2_s_p9_0[] = {
  127759. 11, 9, 7, 5, 3, 1, 0, 2,
  127760. 4, 6, 8, 10, 12,
  127761. };
  127762. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_0 = {
  127763. _vq_quantthresh__44c2_s_p9_0,
  127764. _vq_quantmap__44c2_s_p9_0,
  127765. 13,
  127766. 13
  127767. };
  127768. static static_codebook _44c2_s_p9_0 = {
  127769. 2, 169,
  127770. _vq_lengthlist__44c2_s_p9_0,
  127771. 1, -514541568, 1627103232, 4, 0,
  127772. _vq_quantlist__44c2_s_p9_0,
  127773. NULL,
  127774. &_vq_auxt__44c2_s_p9_0,
  127775. NULL,
  127776. 0
  127777. };
  127778. static long _vq_quantlist__44c2_s_p9_1[] = {
  127779. 6,
  127780. 5,
  127781. 7,
  127782. 4,
  127783. 8,
  127784. 3,
  127785. 9,
  127786. 2,
  127787. 10,
  127788. 1,
  127789. 11,
  127790. 0,
  127791. 12,
  127792. };
  127793. static long _vq_lengthlist__44c2_s_p9_1[] = {
  127794. 1, 4, 4, 6, 6, 7, 6, 8, 8,10, 9,10,10, 6, 5, 5,
  127795. 7, 7, 8, 7,10, 9,11,11,12,13, 6, 5, 5, 7, 7, 8,
  127796. 8,10,10,11,11,13,13,18, 8, 8, 8, 8, 9, 9,10,10,
  127797. 12,12,12,13,18, 8, 8, 8, 8, 9, 9,10,10,12,12,13,
  127798. 13,18,11,11, 8, 8,10,10,11,11,12,11,13,12,18,11,
  127799. 11, 9, 7,10,10,11,11,11,12,12,13,17,17,17,10,10,
  127800. 11,11,12,12,12,10,12,12,17,17,17,11,10,11,10,13,
  127801. 12,11,12,12,12,17,17,17,15,14,11,11,12,11,13,10,
  127802. 13,12,17,17,17,14,14,12,10,11,11,13,13,13,13,17,
  127803. 17,16,17,16,13,13,12,10,13,10,14,13,17,16,17,16,
  127804. 17,13,12,12,10,13,11,14,14,
  127805. };
  127806. static float _vq_quantthresh__44c2_s_p9_1[] = {
  127807. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  127808. 42.5, 59.5, 76.5, 93.5,
  127809. };
  127810. static long _vq_quantmap__44c2_s_p9_1[] = {
  127811. 11, 9, 7, 5, 3, 1, 0, 2,
  127812. 4, 6, 8, 10, 12,
  127813. };
  127814. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_1 = {
  127815. _vq_quantthresh__44c2_s_p9_1,
  127816. _vq_quantmap__44c2_s_p9_1,
  127817. 13,
  127818. 13
  127819. };
  127820. static static_codebook _44c2_s_p9_1 = {
  127821. 2, 169,
  127822. _vq_lengthlist__44c2_s_p9_1,
  127823. 1, -522616832, 1620115456, 4, 0,
  127824. _vq_quantlist__44c2_s_p9_1,
  127825. NULL,
  127826. &_vq_auxt__44c2_s_p9_1,
  127827. NULL,
  127828. 0
  127829. };
  127830. static long _vq_quantlist__44c2_s_p9_2[] = {
  127831. 8,
  127832. 7,
  127833. 9,
  127834. 6,
  127835. 10,
  127836. 5,
  127837. 11,
  127838. 4,
  127839. 12,
  127840. 3,
  127841. 13,
  127842. 2,
  127843. 14,
  127844. 1,
  127845. 15,
  127846. 0,
  127847. 16,
  127848. };
  127849. static long _vq_lengthlist__44c2_s_p9_2[] = {
  127850. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  127851. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  127852. 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  127853. 9, 9, 9,10, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  127854. 9, 9, 9, 9,10,10,10, 8, 7, 8, 8, 8, 8, 9, 9, 9,
  127855. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  127856. 9, 9,10, 9, 9, 9,10,11,10, 8, 8, 8, 8, 9, 9, 9,
  127857. 9, 9, 9, 9,10,10,10,10,11,10, 8, 8, 9, 9, 9, 9,
  127858. 9, 9,10, 9, 9,10, 9,10,11,10,11,11,11, 8, 8, 9,
  127859. 9, 9, 9, 9, 9, 9, 9,10,10,11,11,11,11,11, 9, 9,
  127860. 9, 9, 9, 9,10, 9, 9, 9,10,10,11,11,11,11,11, 9,
  127861. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,11,11,11,11,11,
  127862. 9, 9, 9, 9,10,10, 9, 9, 9,10,10,10,11,11,11,11,
  127863. 11,11,11, 9, 9, 9,10, 9, 9,10,10,10,10,11,11,10,
  127864. 11,11,11,11,10, 9,10,10, 9, 9, 9, 9,10,10,11,10,
  127865. 11,11,11,11,11, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  127866. 10,11,11,11,11,11,10,10, 9, 9,10, 9,10,10,10,10,
  127867. 10,10,10,11,11,11,11,11,11, 9, 9,10, 9,10, 9,10,
  127868. 10,
  127869. };
  127870. static float _vq_quantthresh__44c2_s_p9_2[] = {
  127871. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  127872. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  127873. };
  127874. static long _vq_quantmap__44c2_s_p9_2[] = {
  127875. 15, 13, 11, 9, 7, 5, 3, 1,
  127876. 0, 2, 4, 6, 8, 10, 12, 14,
  127877. 16,
  127878. };
  127879. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_2 = {
  127880. _vq_quantthresh__44c2_s_p9_2,
  127881. _vq_quantmap__44c2_s_p9_2,
  127882. 17,
  127883. 17
  127884. };
  127885. static static_codebook _44c2_s_p9_2 = {
  127886. 2, 289,
  127887. _vq_lengthlist__44c2_s_p9_2,
  127888. 1, -529530880, 1611661312, 5, 0,
  127889. _vq_quantlist__44c2_s_p9_2,
  127890. NULL,
  127891. &_vq_auxt__44c2_s_p9_2,
  127892. NULL,
  127893. 0
  127894. };
  127895. static long _huff_lengthlist__44c2_s_short[] = {
  127896. 11, 9,13,12,12,11,12,12,13,15, 8, 2,11, 4, 8, 5,
  127897. 7,10,12,15,13, 7,10, 9, 8, 8,10,13,17,17,11, 4,
  127898. 12, 5, 9, 5, 8,11,14,16,12, 6, 8, 7, 6, 6, 8,11,
  127899. 13,16,11, 4, 9, 5, 6, 4, 6,10,13,16,11, 6,11, 7,
  127900. 7, 6, 7,10,13,15,13, 9,12, 9, 8, 6, 8,10,12,14,
  127901. 14,10,10, 8, 6, 5, 6, 9,11,13,15,11,11, 9, 6, 5,
  127902. 6, 8, 9,12,
  127903. };
  127904. static static_codebook _huff_book__44c2_s_short = {
  127905. 2, 100,
  127906. _huff_lengthlist__44c2_s_short,
  127907. 0, 0, 0, 0, 0,
  127908. NULL,
  127909. NULL,
  127910. NULL,
  127911. NULL,
  127912. 0
  127913. };
  127914. static long _huff_lengthlist__44c3_s_long[] = {
  127915. 5, 6,11,11,11,11,10,10,12,11, 5, 2,11, 5, 6, 6,
  127916. 7, 9,11,13,13,10, 7,11, 6, 7, 8, 9,10,12,11, 5,
  127917. 11, 6, 8, 7, 9,11,14,15,11, 6, 6, 8, 4, 5, 7, 8,
  127918. 10,13,10, 5, 7, 7, 5, 5, 6, 8,10,11,10, 7, 7, 8,
  127919. 6, 5, 5, 7, 9, 9,11, 8, 8,11, 8, 7, 6, 6, 7, 9,
  127920. 12,11,10,13, 9, 9, 7, 7, 7, 9,11,13,12,15,12,11,
  127921. 9, 8, 8, 8,
  127922. };
  127923. static static_codebook _huff_book__44c3_s_long = {
  127924. 2, 100,
  127925. _huff_lengthlist__44c3_s_long,
  127926. 0, 0, 0, 0, 0,
  127927. NULL,
  127928. NULL,
  127929. NULL,
  127930. NULL,
  127931. 0
  127932. };
  127933. static long _vq_quantlist__44c3_s_p1_0[] = {
  127934. 1,
  127935. 0,
  127936. 2,
  127937. };
  127938. static long _vq_lengthlist__44c3_s_p1_0[] = {
  127939. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  127940. 0, 0, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127944. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  127945. 0, 0, 0, 6, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127949. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  127950. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  127985. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  127986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  127990. 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  127991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  127995. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  127996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128030. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  128031. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128035. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  128036. 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  128037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128040. 0, 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  128041. 0, 0, 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 0,
  128042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128349. 0,
  128350. };
  128351. static float _vq_quantthresh__44c3_s_p1_0[] = {
  128352. -0.5, 0.5,
  128353. };
  128354. static long _vq_quantmap__44c3_s_p1_0[] = {
  128355. 1, 0, 2,
  128356. };
  128357. static encode_aux_threshmatch _vq_auxt__44c3_s_p1_0 = {
  128358. _vq_quantthresh__44c3_s_p1_0,
  128359. _vq_quantmap__44c3_s_p1_0,
  128360. 3,
  128361. 3
  128362. };
  128363. static static_codebook _44c3_s_p1_0 = {
  128364. 8, 6561,
  128365. _vq_lengthlist__44c3_s_p1_0,
  128366. 1, -535822336, 1611661312, 2, 0,
  128367. _vq_quantlist__44c3_s_p1_0,
  128368. NULL,
  128369. &_vq_auxt__44c3_s_p1_0,
  128370. NULL,
  128371. 0
  128372. };
  128373. static long _vq_quantlist__44c3_s_p2_0[] = {
  128374. 2,
  128375. 1,
  128376. 3,
  128377. 0,
  128378. 4,
  128379. };
  128380. static long _vq_lengthlist__44c3_s_p2_0[] = {
  128381. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  128382. 7, 8, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  128383. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  128384. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  128385. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128390. 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0,
  128391. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  128392. 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  128393. 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128398. 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  128399. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  128400. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0,
  128401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128406. 8,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  128407. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  128408. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  128409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128420. 0,
  128421. };
  128422. static float _vq_quantthresh__44c3_s_p2_0[] = {
  128423. -1.5, -0.5, 0.5, 1.5,
  128424. };
  128425. static long _vq_quantmap__44c3_s_p2_0[] = {
  128426. 3, 1, 0, 2, 4,
  128427. };
  128428. static encode_aux_threshmatch _vq_auxt__44c3_s_p2_0 = {
  128429. _vq_quantthresh__44c3_s_p2_0,
  128430. _vq_quantmap__44c3_s_p2_0,
  128431. 5,
  128432. 5
  128433. };
  128434. static static_codebook _44c3_s_p2_0 = {
  128435. 4, 625,
  128436. _vq_lengthlist__44c3_s_p2_0,
  128437. 1, -533725184, 1611661312, 3, 0,
  128438. _vq_quantlist__44c3_s_p2_0,
  128439. NULL,
  128440. &_vq_auxt__44c3_s_p2_0,
  128441. NULL,
  128442. 0
  128443. };
  128444. static long _vq_quantlist__44c3_s_p3_0[] = {
  128445. 2,
  128446. 1,
  128447. 3,
  128448. 0,
  128449. 4,
  128450. };
  128451. static long _vq_lengthlist__44c3_s_p3_0[] = {
  128452. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  128454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128455. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  128457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128458. 0, 0, 0, 0, 6, 6, 7, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0,
  128489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128491. 0,
  128492. };
  128493. static float _vq_quantthresh__44c3_s_p3_0[] = {
  128494. -1.5, -0.5, 0.5, 1.5,
  128495. };
  128496. static long _vq_quantmap__44c3_s_p3_0[] = {
  128497. 3, 1, 0, 2, 4,
  128498. };
  128499. static encode_aux_threshmatch _vq_auxt__44c3_s_p3_0 = {
  128500. _vq_quantthresh__44c3_s_p3_0,
  128501. _vq_quantmap__44c3_s_p3_0,
  128502. 5,
  128503. 5
  128504. };
  128505. static static_codebook _44c3_s_p3_0 = {
  128506. 4, 625,
  128507. _vq_lengthlist__44c3_s_p3_0,
  128508. 1, -533725184, 1611661312, 3, 0,
  128509. _vq_quantlist__44c3_s_p3_0,
  128510. NULL,
  128511. &_vq_auxt__44c3_s_p3_0,
  128512. NULL,
  128513. 0
  128514. };
  128515. static long _vq_quantlist__44c3_s_p4_0[] = {
  128516. 4,
  128517. 3,
  128518. 5,
  128519. 2,
  128520. 6,
  128521. 1,
  128522. 7,
  128523. 0,
  128524. 8,
  128525. };
  128526. static long _vq_lengthlist__44c3_s_p4_0[] = {
  128527. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  128528. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  128529. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  128530. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  128531. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128532. 0,
  128533. };
  128534. static float _vq_quantthresh__44c3_s_p4_0[] = {
  128535. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128536. };
  128537. static long _vq_quantmap__44c3_s_p4_0[] = {
  128538. 7, 5, 3, 1, 0, 2, 4, 6,
  128539. 8,
  128540. };
  128541. static encode_aux_threshmatch _vq_auxt__44c3_s_p4_0 = {
  128542. _vq_quantthresh__44c3_s_p4_0,
  128543. _vq_quantmap__44c3_s_p4_0,
  128544. 9,
  128545. 9
  128546. };
  128547. static static_codebook _44c3_s_p4_0 = {
  128548. 2, 81,
  128549. _vq_lengthlist__44c3_s_p4_0,
  128550. 1, -531628032, 1611661312, 4, 0,
  128551. _vq_quantlist__44c3_s_p4_0,
  128552. NULL,
  128553. &_vq_auxt__44c3_s_p4_0,
  128554. NULL,
  128555. 0
  128556. };
  128557. static long _vq_quantlist__44c3_s_p5_0[] = {
  128558. 4,
  128559. 3,
  128560. 5,
  128561. 2,
  128562. 6,
  128563. 1,
  128564. 7,
  128565. 0,
  128566. 8,
  128567. };
  128568. static long _vq_lengthlist__44c3_s_p5_0[] = {
  128569. 1, 3, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 7, 8,
  128570. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  128571. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  128572. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  128573. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  128574. 11,
  128575. };
  128576. static float _vq_quantthresh__44c3_s_p5_0[] = {
  128577. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128578. };
  128579. static long _vq_quantmap__44c3_s_p5_0[] = {
  128580. 7, 5, 3, 1, 0, 2, 4, 6,
  128581. 8,
  128582. };
  128583. static encode_aux_threshmatch _vq_auxt__44c3_s_p5_0 = {
  128584. _vq_quantthresh__44c3_s_p5_0,
  128585. _vq_quantmap__44c3_s_p5_0,
  128586. 9,
  128587. 9
  128588. };
  128589. static static_codebook _44c3_s_p5_0 = {
  128590. 2, 81,
  128591. _vq_lengthlist__44c3_s_p5_0,
  128592. 1, -531628032, 1611661312, 4, 0,
  128593. _vq_quantlist__44c3_s_p5_0,
  128594. NULL,
  128595. &_vq_auxt__44c3_s_p5_0,
  128596. NULL,
  128597. 0
  128598. };
  128599. static long _vq_quantlist__44c3_s_p6_0[] = {
  128600. 8,
  128601. 7,
  128602. 9,
  128603. 6,
  128604. 10,
  128605. 5,
  128606. 11,
  128607. 4,
  128608. 12,
  128609. 3,
  128610. 13,
  128611. 2,
  128612. 14,
  128613. 1,
  128614. 15,
  128615. 0,
  128616. 16,
  128617. };
  128618. static long _vq_lengthlist__44c3_s_p6_0[] = {
  128619. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  128620. 10, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  128621. 11,11, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  128622. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  128623. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  128624. 10,11,11,11,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  128625. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  128626. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  128627. 10,10,11,10,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  128628. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 8,
  128629. 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8,
  128630. 8, 9, 9,10,10,11,11,12,11,12,12, 0, 0, 0, 0, 0,
  128631. 9,10,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0,
  128632. 0, 0, 0,10,10,10,10,11,11,12,12,13,13, 0, 0, 0,
  128633. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  128634. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  128635. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13,
  128636. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  128637. 13,
  128638. };
  128639. static float _vq_quantthresh__44c3_s_p6_0[] = {
  128640. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128641. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128642. };
  128643. static long _vq_quantmap__44c3_s_p6_0[] = {
  128644. 15, 13, 11, 9, 7, 5, 3, 1,
  128645. 0, 2, 4, 6, 8, 10, 12, 14,
  128646. 16,
  128647. };
  128648. static encode_aux_threshmatch _vq_auxt__44c3_s_p6_0 = {
  128649. _vq_quantthresh__44c3_s_p6_0,
  128650. _vq_quantmap__44c3_s_p6_0,
  128651. 17,
  128652. 17
  128653. };
  128654. static static_codebook _44c3_s_p6_0 = {
  128655. 2, 289,
  128656. _vq_lengthlist__44c3_s_p6_0,
  128657. 1, -529530880, 1611661312, 5, 0,
  128658. _vq_quantlist__44c3_s_p6_0,
  128659. NULL,
  128660. &_vq_auxt__44c3_s_p6_0,
  128661. NULL,
  128662. 0
  128663. };
  128664. static long _vq_quantlist__44c3_s_p7_0[] = {
  128665. 1,
  128666. 0,
  128667. 2,
  128668. };
  128669. static long _vq_lengthlist__44c3_s_p7_0[] = {
  128670. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  128671. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  128672. 10,12,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  128673. 11,10,10,11,10,10, 7,11,11,11,11,11,12,11,11, 6,
  128674. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  128675. 10,
  128676. };
  128677. static float _vq_quantthresh__44c3_s_p7_0[] = {
  128678. -5.5, 5.5,
  128679. };
  128680. static long _vq_quantmap__44c3_s_p7_0[] = {
  128681. 1, 0, 2,
  128682. };
  128683. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_0 = {
  128684. _vq_quantthresh__44c3_s_p7_0,
  128685. _vq_quantmap__44c3_s_p7_0,
  128686. 3,
  128687. 3
  128688. };
  128689. static static_codebook _44c3_s_p7_0 = {
  128690. 4, 81,
  128691. _vq_lengthlist__44c3_s_p7_0,
  128692. 1, -529137664, 1618345984, 2, 0,
  128693. _vq_quantlist__44c3_s_p7_0,
  128694. NULL,
  128695. &_vq_auxt__44c3_s_p7_0,
  128696. NULL,
  128697. 0
  128698. };
  128699. static long _vq_quantlist__44c3_s_p7_1[] = {
  128700. 5,
  128701. 4,
  128702. 6,
  128703. 3,
  128704. 7,
  128705. 2,
  128706. 8,
  128707. 1,
  128708. 9,
  128709. 0,
  128710. 10,
  128711. };
  128712. static long _vq_lengthlist__44c3_s_p7_1[] = {
  128713. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  128714. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  128715. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  128716. 7, 8, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  128717. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  128718. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  128719. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  128720. 10,10,10, 8, 8, 8, 8, 8, 8,
  128721. };
  128722. static float _vq_quantthresh__44c3_s_p7_1[] = {
  128723. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  128724. 3.5, 4.5,
  128725. };
  128726. static long _vq_quantmap__44c3_s_p7_1[] = {
  128727. 9, 7, 5, 3, 1, 0, 2, 4,
  128728. 6, 8, 10,
  128729. };
  128730. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_1 = {
  128731. _vq_quantthresh__44c3_s_p7_1,
  128732. _vq_quantmap__44c3_s_p7_1,
  128733. 11,
  128734. 11
  128735. };
  128736. static static_codebook _44c3_s_p7_1 = {
  128737. 2, 121,
  128738. _vq_lengthlist__44c3_s_p7_1,
  128739. 1, -531365888, 1611661312, 4, 0,
  128740. _vq_quantlist__44c3_s_p7_1,
  128741. NULL,
  128742. &_vq_auxt__44c3_s_p7_1,
  128743. NULL,
  128744. 0
  128745. };
  128746. static long _vq_quantlist__44c3_s_p8_0[] = {
  128747. 6,
  128748. 5,
  128749. 7,
  128750. 4,
  128751. 8,
  128752. 3,
  128753. 9,
  128754. 2,
  128755. 10,
  128756. 1,
  128757. 11,
  128758. 0,
  128759. 12,
  128760. };
  128761. static long _vq_lengthlist__44c3_s_p8_0[] = {
  128762. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  128763. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  128764. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  128765. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  128766. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,12, 0,13,
  128767. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  128768. 10,10,11,11,12,12,12,12, 0, 0, 0,10,10,10,10,11,
  128769. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  128770. 13,13, 0, 0, 0,14,14,11,11,11,11,12,12,13,13, 0,
  128771. 0, 0, 0, 0,12,12,12,12,13,13,14,13, 0, 0, 0, 0,
  128772. 0,13,13,12,12,13,12,14,13,
  128773. };
  128774. static float _vq_quantthresh__44c3_s_p8_0[] = {
  128775. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  128776. 12.5, 17.5, 22.5, 27.5,
  128777. };
  128778. static long _vq_quantmap__44c3_s_p8_0[] = {
  128779. 11, 9, 7, 5, 3, 1, 0, 2,
  128780. 4, 6, 8, 10, 12,
  128781. };
  128782. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_0 = {
  128783. _vq_quantthresh__44c3_s_p8_0,
  128784. _vq_quantmap__44c3_s_p8_0,
  128785. 13,
  128786. 13
  128787. };
  128788. static static_codebook _44c3_s_p8_0 = {
  128789. 2, 169,
  128790. _vq_lengthlist__44c3_s_p8_0,
  128791. 1, -526516224, 1616117760, 4, 0,
  128792. _vq_quantlist__44c3_s_p8_0,
  128793. NULL,
  128794. &_vq_auxt__44c3_s_p8_0,
  128795. NULL,
  128796. 0
  128797. };
  128798. static long _vq_quantlist__44c3_s_p8_1[] = {
  128799. 2,
  128800. 1,
  128801. 3,
  128802. 0,
  128803. 4,
  128804. };
  128805. static long _vq_lengthlist__44c3_s_p8_1[] = {
  128806. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  128807. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  128808. };
  128809. static float _vq_quantthresh__44c3_s_p8_1[] = {
  128810. -1.5, -0.5, 0.5, 1.5,
  128811. };
  128812. static long _vq_quantmap__44c3_s_p8_1[] = {
  128813. 3, 1, 0, 2, 4,
  128814. };
  128815. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_1 = {
  128816. _vq_quantthresh__44c3_s_p8_1,
  128817. _vq_quantmap__44c3_s_p8_1,
  128818. 5,
  128819. 5
  128820. };
  128821. static static_codebook _44c3_s_p8_1 = {
  128822. 2, 25,
  128823. _vq_lengthlist__44c3_s_p8_1,
  128824. 1, -533725184, 1611661312, 3, 0,
  128825. _vq_quantlist__44c3_s_p8_1,
  128826. NULL,
  128827. &_vq_auxt__44c3_s_p8_1,
  128828. NULL,
  128829. 0
  128830. };
  128831. static long _vq_quantlist__44c3_s_p9_0[] = {
  128832. 6,
  128833. 5,
  128834. 7,
  128835. 4,
  128836. 8,
  128837. 3,
  128838. 9,
  128839. 2,
  128840. 10,
  128841. 1,
  128842. 11,
  128843. 0,
  128844. 12,
  128845. };
  128846. static long _vq_lengthlist__44c3_s_p9_0[] = {
  128847. 1, 4, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  128848. 12,12,12,12,12,12,12,12,12,12, 2, 9, 7,12,12,12,
  128849. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  128850. 12,12,12,12,12,12,11,12,12,12,12,12,12,12,12,12,
  128851. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  128852. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  128853. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  128854. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  128855. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  128856. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128857. 11,11,11,11,11,11,11,11,11,
  128858. };
  128859. static float _vq_quantthresh__44c3_s_p9_0[] = {
  128860. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  128861. 637.5, 892.5, 1147.5, 1402.5,
  128862. };
  128863. static long _vq_quantmap__44c3_s_p9_0[] = {
  128864. 11, 9, 7, 5, 3, 1, 0, 2,
  128865. 4, 6, 8, 10, 12,
  128866. };
  128867. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_0 = {
  128868. _vq_quantthresh__44c3_s_p9_0,
  128869. _vq_quantmap__44c3_s_p9_0,
  128870. 13,
  128871. 13
  128872. };
  128873. static static_codebook _44c3_s_p9_0 = {
  128874. 2, 169,
  128875. _vq_lengthlist__44c3_s_p9_0,
  128876. 1, -514332672, 1627381760, 4, 0,
  128877. _vq_quantlist__44c3_s_p9_0,
  128878. NULL,
  128879. &_vq_auxt__44c3_s_p9_0,
  128880. NULL,
  128881. 0
  128882. };
  128883. static long _vq_quantlist__44c3_s_p9_1[] = {
  128884. 7,
  128885. 6,
  128886. 8,
  128887. 5,
  128888. 9,
  128889. 4,
  128890. 10,
  128891. 3,
  128892. 11,
  128893. 2,
  128894. 12,
  128895. 1,
  128896. 13,
  128897. 0,
  128898. 14,
  128899. };
  128900. static long _vq_lengthlist__44c3_s_p9_1[] = {
  128901. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 9,10,10,10,10, 6,
  128902. 5, 5, 7, 7, 8, 8,10, 8,11,10,12,12,13,13, 6, 5,
  128903. 5, 7, 7, 8, 8,10, 9,11,11,12,12,13,12,18, 8, 8,
  128904. 8, 8, 9, 9,10, 9,11,10,12,12,13,13,18, 8, 8, 8,
  128905. 8, 9, 9,10,10,11,11,13,12,14,13,18,11,11, 9, 9,
  128906. 10,10,11,11,11,12,13,12,13,14,18,11,11, 9, 8,11,
  128907. 10,11,11,11,11,12,12,14,13,18,18,18,10,11,10,11,
  128908. 12,12,12,12,13,12,14,13,18,18,18,10,11,11, 9,12,
  128909. 11,12,12,12,13,13,13,18,18,17,14,14,11,11,12,12,
  128910. 13,12,14,12,14,13,18,18,18,14,14,11,10,12, 9,12,
  128911. 13,13,13,13,13,18,18,17,16,18,13,13,12,12,13,11,
  128912. 14,12,14,14,17,18,18,17,18,13,12,13,10,12,11,14,
  128913. 14,14,14,17,18,18,18,18,15,16,12,12,13,10,14,12,
  128914. 14,15,18,18,18,16,17,16,14,12,11,13,10,13,13,14,
  128915. 15,
  128916. };
  128917. static float _vq_quantthresh__44c3_s_p9_1[] = {
  128918. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  128919. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  128920. };
  128921. static long _vq_quantmap__44c3_s_p9_1[] = {
  128922. 13, 11, 9, 7, 5, 3, 1, 0,
  128923. 2, 4, 6, 8, 10, 12, 14,
  128924. };
  128925. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_1 = {
  128926. _vq_quantthresh__44c3_s_p9_1,
  128927. _vq_quantmap__44c3_s_p9_1,
  128928. 15,
  128929. 15
  128930. };
  128931. static static_codebook _44c3_s_p9_1 = {
  128932. 2, 225,
  128933. _vq_lengthlist__44c3_s_p9_1,
  128934. 1, -522338304, 1620115456, 4, 0,
  128935. _vq_quantlist__44c3_s_p9_1,
  128936. NULL,
  128937. &_vq_auxt__44c3_s_p9_1,
  128938. NULL,
  128939. 0
  128940. };
  128941. static long _vq_quantlist__44c3_s_p9_2[] = {
  128942. 8,
  128943. 7,
  128944. 9,
  128945. 6,
  128946. 10,
  128947. 5,
  128948. 11,
  128949. 4,
  128950. 12,
  128951. 3,
  128952. 13,
  128953. 2,
  128954. 14,
  128955. 1,
  128956. 15,
  128957. 0,
  128958. 16,
  128959. };
  128960. static long _vq_lengthlist__44c3_s_p9_2[] = {
  128961. 2, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  128962. 8,10, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 8, 9, 9, 9,
  128963. 9, 9,10, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  128964. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  128965. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  128966. 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  128967. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  128968. 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 9, 9, 9, 9, 9,
  128969. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 9, 9, 9,
  128970. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  128971. 9, 9, 9, 9,10,10, 9, 9,10, 9,11,10,11,11,11, 9,
  128972. 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,11,11,11,11,11,
  128973. 9, 9, 9, 9,10,10, 9, 9, 9, 9,10, 9,11,11,11,11,
  128974. 11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11,
  128975. 11,11,11,11,10, 9,10,10, 9,10, 9, 9,10, 9,11,10,
  128976. 10,11,11,11,11, 9,10, 9, 9, 9, 9,10,10,10,10,11,
  128977. 11,11,11,11,11,10,10,10, 9, 9,10, 9,10, 9,10,10,
  128978. 10,10,11,11,11,11,11,11,11, 9, 9, 9, 9, 9,10,10,
  128979. 10,
  128980. };
  128981. static float _vq_quantthresh__44c3_s_p9_2[] = {
  128982. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128983. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128984. };
  128985. static long _vq_quantmap__44c3_s_p9_2[] = {
  128986. 15, 13, 11, 9, 7, 5, 3, 1,
  128987. 0, 2, 4, 6, 8, 10, 12, 14,
  128988. 16,
  128989. };
  128990. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_2 = {
  128991. _vq_quantthresh__44c3_s_p9_2,
  128992. _vq_quantmap__44c3_s_p9_2,
  128993. 17,
  128994. 17
  128995. };
  128996. static static_codebook _44c3_s_p9_2 = {
  128997. 2, 289,
  128998. _vq_lengthlist__44c3_s_p9_2,
  128999. 1, -529530880, 1611661312, 5, 0,
  129000. _vq_quantlist__44c3_s_p9_2,
  129001. NULL,
  129002. &_vq_auxt__44c3_s_p9_2,
  129003. NULL,
  129004. 0
  129005. };
  129006. static long _huff_lengthlist__44c3_s_short[] = {
  129007. 10, 9,13,11,14,10,12,13,13,14, 7, 2,12, 5,10, 5,
  129008. 7,10,12,14,12, 6, 9, 8, 7, 7, 9,11,13,16,10, 4,
  129009. 12, 5,10, 6, 8,12,14,16,12, 6, 8, 7, 6, 5, 7,11,
  129010. 12,16,10, 4, 8, 5, 6, 4, 6, 9,13,16,10, 6,10, 7,
  129011. 7, 6, 7, 9,13,15,12, 9,11, 9, 8, 6, 7,10,12,14,
  129012. 14,11,10, 9, 6, 5, 6, 9,11,13,15,13,11,10, 6, 5,
  129013. 6, 8, 9,11,
  129014. };
  129015. static static_codebook _huff_book__44c3_s_short = {
  129016. 2, 100,
  129017. _huff_lengthlist__44c3_s_short,
  129018. 0, 0, 0, 0, 0,
  129019. NULL,
  129020. NULL,
  129021. NULL,
  129022. NULL,
  129023. 0
  129024. };
  129025. static long _huff_lengthlist__44c4_s_long[] = {
  129026. 4, 7,11,11,11,11,10,11,12,11, 5, 2,11, 5, 6, 6,
  129027. 7, 9,11,12,11, 9, 6,10, 6, 7, 8, 9,10,11,11, 5,
  129028. 11, 7, 8, 8, 9,11,13,14,11, 6, 5, 8, 4, 5, 7, 8,
  129029. 10,11,10, 6, 7, 7, 5, 5, 6, 8, 9,11,10, 7, 8, 9,
  129030. 6, 6, 6, 7, 8, 9,11, 9, 9,11, 7, 7, 6, 6, 7, 9,
  129031. 12,12,10,13, 9, 8, 7, 7, 7, 8,11,13,11,14,11,10,
  129032. 9, 8, 7, 7,
  129033. };
  129034. static static_codebook _huff_book__44c4_s_long = {
  129035. 2, 100,
  129036. _huff_lengthlist__44c4_s_long,
  129037. 0, 0, 0, 0, 0,
  129038. NULL,
  129039. NULL,
  129040. NULL,
  129041. NULL,
  129042. 0
  129043. };
  129044. static long _vq_quantlist__44c4_s_p1_0[] = {
  129045. 1,
  129046. 0,
  129047. 2,
  129048. };
  129049. static long _vq_lengthlist__44c4_s_p1_0[] = {
  129050. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  129051. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129055. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  129056. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129060. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  129061. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  129096. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  129097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  129101. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  129102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  129106. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  129107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129141. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  129142. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129146. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  129147. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  129148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129151. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  129152. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  129153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129460. 0,
  129461. };
  129462. static float _vq_quantthresh__44c4_s_p1_0[] = {
  129463. -0.5, 0.5,
  129464. };
  129465. static long _vq_quantmap__44c4_s_p1_0[] = {
  129466. 1, 0, 2,
  129467. };
  129468. static encode_aux_threshmatch _vq_auxt__44c4_s_p1_0 = {
  129469. _vq_quantthresh__44c4_s_p1_0,
  129470. _vq_quantmap__44c4_s_p1_0,
  129471. 3,
  129472. 3
  129473. };
  129474. static static_codebook _44c4_s_p1_0 = {
  129475. 8, 6561,
  129476. _vq_lengthlist__44c4_s_p1_0,
  129477. 1, -535822336, 1611661312, 2, 0,
  129478. _vq_quantlist__44c4_s_p1_0,
  129479. NULL,
  129480. &_vq_auxt__44c4_s_p1_0,
  129481. NULL,
  129482. 0
  129483. };
  129484. static long _vq_quantlist__44c4_s_p2_0[] = {
  129485. 2,
  129486. 1,
  129487. 3,
  129488. 0,
  129489. 4,
  129490. };
  129491. static long _vq_lengthlist__44c4_s_p2_0[] = {
  129492. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  129493. 7, 7, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  129494. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  129495. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  129496. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129501. 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 7, 7, 0, 0,
  129502. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  129503. 7, 8, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  129504. 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129509. 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  129510. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  129511. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0,
  129512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129517. 7,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  129518. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  129519. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  129520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129531. 0,
  129532. };
  129533. static float _vq_quantthresh__44c4_s_p2_0[] = {
  129534. -1.5, -0.5, 0.5, 1.5,
  129535. };
  129536. static long _vq_quantmap__44c4_s_p2_0[] = {
  129537. 3, 1, 0, 2, 4,
  129538. };
  129539. static encode_aux_threshmatch _vq_auxt__44c4_s_p2_0 = {
  129540. _vq_quantthresh__44c4_s_p2_0,
  129541. _vq_quantmap__44c4_s_p2_0,
  129542. 5,
  129543. 5
  129544. };
  129545. static static_codebook _44c4_s_p2_0 = {
  129546. 4, 625,
  129547. _vq_lengthlist__44c4_s_p2_0,
  129548. 1, -533725184, 1611661312, 3, 0,
  129549. _vq_quantlist__44c4_s_p2_0,
  129550. NULL,
  129551. &_vq_auxt__44c4_s_p2_0,
  129552. NULL,
  129553. 0
  129554. };
  129555. static long _vq_quantlist__44c4_s_p3_0[] = {
  129556. 2,
  129557. 1,
  129558. 3,
  129559. 0,
  129560. 4,
  129561. };
  129562. static long _vq_lengthlist__44c4_s_p3_0[] = {
  129563. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 4, 6, 6, 0, 0,
  129565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129566. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  129568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129569. 0, 0, 0, 0, 6, 6, 7, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0,
  129600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129602. 0,
  129603. };
  129604. static float _vq_quantthresh__44c4_s_p3_0[] = {
  129605. -1.5, -0.5, 0.5, 1.5,
  129606. };
  129607. static long _vq_quantmap__44c4_s_p3_0[] = {
  129608. 3, 1, 0, 2, 4,
  129609. };
  129610. static encode_aux_threshmatch _vq_auxt__44c4_s_p3_0 = {
  129611. _vq_quantthresh__44c4_s_p3_0,
  129612. _vq_quantmap__44c4_s_p3_0,
  129613. 5,
  129614. 5
  129615. };
  129616. static static_codebook _44c4_s_p3_0 = {
  129617. 4, 625,
  129618. _vq_lengthlist__44c4_s_p3_0,
  129619. 1, -533725184, 1611661312, 3, 0,
  129620. _vq_quantlist__44c4_s_p3_0,
  129621. NULL,
  129622. &_vq_auxt__44c4_s_p3_0,
  129623. NULL,
  129624. 0
  129625. };
  129626. static long _vq_quantlist__44c4_s_p4_0[] = {
  129627. 4,
  129628. 3,
  129629. 5,
  129630. 2,
  129631. 6,
  129632. 1,
  129633. 7,
  129634. 0,
  129635. 8,
  129636. };
  129637. static long _vq_lengthlist__44c4_s_p4_0[] = {
  129638. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  129639. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  129640. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  129641. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  129642. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129643. 0,
  129644. };
  129645. static float _vq_quantthresh__44c4_s_p4_0[] = {
  129646. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129647. };
  129648. static long _vq_quantmap__44c4_s_p4_0[] = {
  129649. 7, 5, 3, 1, 0, 2, 4, 6,
  129650. 8,
  129651. };
  129652. static encode_aux_threshmatch _vq_auxt__44c4_s_p4_0 = {
  129653. _vq_quantthresh__44c4_s_p4_0,
  129654. _vq_quantmap__44c4_s_p4_0,
  129655. 9,
  129656. 9
  129657. };
  129658. static static_codebook _44c4_s_p4_0 = {
  129659. 2, 81,
  129660. _vq_lengthlist__44c4_s_p4_0,
  129661. 1, -531628032, 1611661312, 4, 0,
  129662. _vq_quantlist__44c4_s_p4_0,
  129663. NULL,
  129664. &_vq_auxt__44c4_s_p4_0,
  129665. NULL,
  129666. 0
  129667. };
  129668. static long _vq_quantlist__44c4_s_p5_0[] = {
  129669. 4,
  129670. 3,
  129671. 5,
  129672. 2,
  129673. 6,
  129674. 1,
  129675. 7,
  129676. 0,
  129677. 8,
  129678. };
  129679. static long _vq_lengthlist__44c4_s_p5_0[] = {
  129680. 2, 3, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  129681. 9, 9, 0, 4, 5, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  129682. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10, 9, 0, 0, 0,
  129683. 9, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  129684. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,10,
  129685. 10,
  129686. };
  129687. static float _vq_quantthresh__44c4_s_p5_0[] = {
  129688. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129689. };
  129690. static long _vq_quantmap__44c4_s_p5_0[] = {
  129691. 7, 5, 3, 1, 0, 2, 4, 6,
  129692. 8,
  129693. };
  129694. static encode_aux_threshmatch _vq_auxt__44c4_s_p5_0 = {
  129695. _vq_quantthresh__44c4_s_p5_0,
  129696. _vq_quantmap__44c4_s_p5_0,
  129697. 9,
  129698. 9
  129699. };
  129700. static static_codebook _44c4_s_p5_0 = {
  129701. 2, 81,
  129702. _vq_lengthlist__44c4_s_p5_0,
  129703. 1, -531628032, 1611661312, 4, 0,
  129704. _vq_quantlist__44c4_s_p5_0,
  129705. NULL,
  129706. &_vq_auxt__44c4_s_p5_0,
  129707. NULL,
  129708. 0
  129709. };
  129710. static long _vq_quantlist__44c4_s_p6_0[] = {
  129711. 8,
  129712. 7,
  129713. 9,
  129714. 6,
  129715. 10,
  129716. 5,
  129717. 11,
  129718. 4,
  129719. 12,
  129720. 3,
  129721. 13,
  129722. 2,
  129723. 14,
  129724. 1,
  129725. 15,
  129726. 0,
  129727. 16,
  129728. };
  129729. static long _vq_lengthlist__44c4_s_p6_0[] = {
  129730. 2, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  129731. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  129732. 11,11, 0, 4, 4, 7, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  129733. 11,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  129734. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  129735. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  129736. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  129737. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  129738. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  129739. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  129740. 9,10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9,
  129741. 9, 9, 9,10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0,
  129742. 10,10,10,10,11,11,11,11,12,12,13,12, 0, 0, 0, 0,
  129743. 0, 0, 0,10,10,11,11,11,11,12,12,12,12, 0, 0, 0,
  129744. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  129745. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  129746. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,13,13,
  129747. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,
  129748. 13,
  129749. };
  129750. static float _vq_quantthresh__44c4_s_p6_0[] = {
  129751. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129752. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129753. };
  129754. static long _vq_quantmap__44c4_s_p6_0[] = {
  129755. 15, 13, 11, 9, 7, 5, 3, 1,
  129756. 0, 2, 4, 6, 8, 10, 12, 14,
  129757. 16,
  129758. };
  129759. static encode_aux_threshmatch _vq_auxt__44c4_s_p6_0 = {
  129760. _vq_quantthresh__44c4_s_p6_0,
  129761. _vq_quantmap__44c4_s_p6_0,
  129762. 17,
  129763. 17
  129764. };
  129765. static static_codebook _44c4_s_p6_0 = {
  129766. 2, 289,
  129767. _vq_lengthlist__44c4_s_p6_0,
  129768. 1, -529530880, 1611661312, 5, 0,
  129769. _vq_quantlist__44c4_s_p6_0,
  129770. NULL,
  129771. &_vq_auxt__44c4_s_p6_0,
  129772. NULL,
  129773. 0
  129774. };
  129775. static long _vq_quantlist__44c4_s_p7_0[] = {
  129776. 1,
  129777. 0,
  129778. 2,
  129779. };
  129780. static long _vq_lengthlist__44c4_s_p7_0[] = {
  129781. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  129782. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  129783. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  129784. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  129785. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  129786. 10,
  129787. };
  129788. static float _vq_quantthresh__44c4_s_p7_0[] = {
  129789. -5.5, 5.5,
  129790. };
  129791. static long _vq_quantmap__44c4_s_p7_0[] = {
  129792. 1, 0, 2,
  129793. };
  129794. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_0 = {
  129795. _vq_quantthresh__44c4_s_p7_0,
  129796. _vq_quantmap__44c4_s_p7_0,
  129797. 3,
  129798. 3
  129799. };
  129800. static static_codebook _44c4_s_p7_0 = {
  129801. 4, 81,
  129802. _vq_lengthlist__44c4_s_p7_0,
  129803. 1, -529137664, 1618345984, 2, 0,
  129804. _vq_quantlist__44c4_s_p7_0,
  129805. NULL,
  129806. &_vq_auxt__44c4_s_p7_0,
  129807. NULL,
  129808. 0
  129809. };
  129810. static long _vq_quantlist__44c4_s_p7_1[] = {
  129811. 5,
  129812. 4,
  129813. 6,
  129814. 3,
  129815. 7,
  129816. 2,
  129817. 8,
  129818. 1,
  129819. 9,
  129820. 0,
  129821. 10,
  129822. };
  129823. static long _vq_lengthlist__44c4_s_p7_1[] = {
  129824. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  129825. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  129826. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  129827. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  129828. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  129829. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  129830. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  129831. 10,10,10, 8, 8, 8, 8, 9, 9,
  129832. };
  129833. static float _vq_quantthresh__44c4_s_p7_1[] = {
  129834. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  129835. 3.5, 4.5,
  129836. };
  129837. static long _vq_quantmap__44c4_s_p7_1[] = {
  129838. 9, 7, 5, 3, 1, 0, 2, 4,
  129839. 6, 8, 10,
  129840. };
  129841. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_1 = {
  129842. _vq_quantthresh__44c4_s_p7_1,
  129843. _vq_quantmap__44c4_s_p7_1,
  129844. 11,
  129845. 11
  129846. };
  129847. static static_codebook _44c4_s_p7_1 = {
  129848. 2, 121,
  129849. _vq_lengthlist__44c4_s_p7_1,
  129850. 1, -531365888, 1611661312, 4, 0,
  129851. _vq_quantlist__44c4_s_p7_1,
  129852. NULL,
  129853. &_vq_auxt__44c4_s_p7_1,
  129854. NULL,
  129855. 0
  129856. };
  129857. static long _vq_quantlist__44c4_s_p8_0[] = {
  129858. 6,
  129859. 5,
  129860. 7,
  129861. 4,
  129862. 8,
  129863. 3,
  129864. 9,
  129865. 2,
  129866. 10,
  129867. 1,
  129868. 11,
  129869. 0,
  129870. 12,
  129871. };
  129872. static long _vq_lengthlist__44c4_s_p8_0[] = {
  129873. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  129874. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  129875. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  129876. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  129877. 11, 0,12,12, 9, 9, 9, 9,10,10,10,10,11,11, 0,13,
  129878. 13, 9, 9,10, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  129879. 10,10,10,10,11,11,12,12, 0, 0, 0,10,10,10,10,10,
  129880. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  129881. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,13, 0,
  129882. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  129883. 0,13,12,12,12,12,12,13,13,
  129884. };
  129885. static float _vq_quantthresh__44c4_s_p8_0[] = {
  129886. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  129887. 12.5, 17.5, 22.5, 27.5,
  129888. };
  129889. static long _vq_quantmap__44c4_s_p8_0[] = {
  129890. 11, 9, 7, 5, 3, 1, 0, 2,
  129891. 4, 6, 8, 10, 12,
  129892. };
  129893. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_0 = {
  129894. _vq_quantthresh__44c4_s_p8_0,
  129895. _vq_quantmap__44c4_s_p8_0,
  129896. 13,
  129897. 13
  129898. };
  129899. static static_codebook _44c4_s_p8_0 = {
  129900. 2, 169,
  129901. _vq_lengthlist__44c4_s_p8_0,
  129902. 1, -526516224, 1616117760, 4, 0,
  129903. _vq_quantlist__44c4_s_p8_0,
  129904. NULL,
  129905. &_vq_auxt__44c4_s_p8_0,
  129906. NULL,
  129907. 0
  129908. };
  129909. static long _vq_quantlist__44c4_s_p8_1[] = {
  129910. 2,
  129911. 1,
  129912. 3,
  129913. 0,
  129914. 4,
  129915. };
  129916. static long _vq_lengthlist__44c4_s_p8_1[] = {
  129917. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 5, 4, 5, 5, 6,
  129918. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  129919. };
  129920. static float _vq_quantthresh__44c4_s_p8_1[] = {
  129921. -1.5, -0.5, 0.5, 1.5,
  129922. };
  129923. static long _vq_quantmap__44c4_s_p8_1[] = {
  129924. 3, 1, 0, 2, 4,
  129925. };
  129926. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_1 = {
  129927. _vq_quantthresh__44c4_s_p8_1,
  129928. _vq_quantmap__44c4_s_p8_1,
  129929. 5,
  129930. 5
  129931. };
  129932. static static_codebook _44c4_s_p8_1 = {
  129933. 2, 25,
  129934. _vq_lengthlist__44c4_s_p8_1,
  129935. 1, -533725184, 1611661312, 3, 0,
  129936. _vq_quantlist__44c4_s_p8_1,
  129937. NULL,
  129938. &_vq_auxt__44c4_s_p8_1,
  129939. NULL,
  129940. 0
  129941. };
  129942. static long _vq_quantlist__44c4_s_p9_0[] = {
  129943. 6,
  129944. 5,
  129945. 7,
  129946. 4,
  129947. 8,
  129948. 3,
  129949. 9,
  129950. 2,
  129951. 10,
  129952. 1,
  129953. 11,
  129954. 0,
  129955. 12,
  129956. };
  129957. static long _vq_lengthlist__44c4_s_p9_0[] = {
  129958. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 4, 7, 7,
  129959. 12,12,12,12,12,12,12,12,12,12, 3, 8, 8,12,12,12,
  129960. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129961. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129962. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129963. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129964. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129965. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129966. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129967. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129968. 12,12,12,12,12,12,12,12,12,
  129969. };
  129970. static float _vq_quantthresh__44c4_s_p9_0[] = {
  129971. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  129972. 787.5, 1102.5, 1417.5, 1732.5,
  129973. };
  129974. static long _vq_quantmap__44c4_s_p9_0[] = {
  129975. 11, 9, 7, 5, 3, 1, 0, 2,
  129976. 4, 6, 8, 10, 12,
  129977. };
  129978. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_0 = {
  129979. _vq_quantthresh__44c4_s_p9_0,
  129980. _vq_quantmap__44c4_s_p9_0,
  129981. 13,
  129982. 13
  129983. };
  129984. static static_codebook _44c4_s_p9_0 = {
  129985. 2, 169,
  129986. _vq_lengthlist__44c4_s_p9_0,
  129987. 1, -513964032, 1628680192, 4, 0,
  129988. _vq_quantlist__44c4_s_p9_0,
  129989. NULL,
  129990. &_vq_auxt__44c4_s_p9_0,
  129991. NULL,
  129992. 0
  129993. };
  129994. static long _vq_quantlist__44c4_s_p9_1[] = {
  129995. 7,
  129996. 6,
  129997. 8,
  129998. 5,
  129999. 9,
  130000. 4,
  130001. 10,
  130002. 3,
  130003. 11,
  130004. 2,
  130005. 12,
  130006. 1,
  130007. 13,
  130008. 0,
  130009. 14,
  130010. };
  130011. static long _vq_lengthlist__44c4_s_p9_1[] = {
  130012. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,10,10, 6,
  130013. 5, 5, 7, 7, 9, 8,10, 9,11,10,12,12,13,13, 6, 5,
  130014. 5, 7, 7, 9, 9,10,10,11,11,12,12,12,13,19, 8, 8,
  130015. 8, 8, 9, 9,10,10,12,11,12,12,13,13,19, 8, 8, 8,
  130016. 8, 9, 9,11,11,12,12,13,13,13,13,19,12,12, 9, 9,
  130017. 11,11,11,11,12,11,13,12,13,13,18,12,12, 9, 9,11,
  130018. 10,11,11,12,12,12,13,13,14,19,18,18,11,11,11,11,
  130019. 12,12,13,12,13,13,14,14,16,18,18,11,11,11,10,12,
  130020. 11,13,13,13,13,13,14,17,18,18,14,15,11,12,12,13,
  130021. 13,13,13,14,14,14,18,18,18,15,15,12,10,13,10,13,
  130022. 13,13,13,13,14,18,17,18,17,18,12,13,12,13,13,13,
  130023. 14,14,16,14,18,17,18,18,17,13,12,13,10,12,12,14,
  130024. 14,14,14,17,18,18,18,18,14,15,12,12,13,12,14,14,
  130025. 15,15,18,18,18,17,18,15,14,12,11,12,12,14,14,14,
  130026. 15,
  130027. };
  130028. static float _vq_quantthresh__44c4_s_p9_1[] = {
  130029. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  130030. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  130031. };
  130032. static long _vq_quantmap__44c4_s_p9_1[] = {
  130033. 13, 11, 9, 7, 5, 3, 1, 0,
  130034. 2, 4, 6, 8, 10, 12, 14,
  130035. };
  130036. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_1 = {
  130037. _vq_quantthresh__44c4_s_p9_1,
  130038. _vq_quantmap__44c4_s_p9_1,
  130039. 15,
  130040. 15
  130041. };
  130042. static static_codebook _44c4_s_p9_1 = {
  130043. 2, 225,
  130044. _vq_lengthlist__44c4_s_p9_1,
  130045. 1, -520986624, 1620377600, 4, 0,
  130046. _vq_quantlist__44c4_s_p9_1,
  130047. NULL,
  130048. &_vq_auxt__44c4_s_p9_1,
  130049. NULL,
  130050. 0
  130051. };
  130052. static long _vq_quantlist__44c4_s_p9_2[] = {
  130053. 10,
  130054. 9,
  130055. 11,
  130056. 8,
  130057. 12,
  130058. 7,
  130059. 13,
  130060. 6,
  130061. 14,
  130062. 5,
  130063. 15,
  130064. 4,
  130065. 16,
  130066. 3,
  130067. 17,
  130068. 2,
  130069. 18,
  130070. 1,
  130071. 19,
  130072. 0,
  130073. 20,
  130074. };
  130075. static long _vq_lengthlist__44c4_s_p9_2[] = {
  130076. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  130077. 8, 9, 9, 9, 9,11, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  130078. 9, 9, 9, 9, 9, 9,10,10,10,10,11, 6, 6, 7, 7, 8,
  130079. 8, 8, 8, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  130080. 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  130081. 10,10,10,10,12,11,11, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  130082. 9,10,10,10,10,10,10,10,10,12,11,12, 8, 8, 8, 8,
  130083. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  130084. 11, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,
  130085. 10,10,10,11,11,12, 9, 9, 9, 9, 9, 9,10, 9,10,10,
  130086. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  130087. 9,10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,
  130088. 11,11, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  130089. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  130090. 10,10,10,10,10,10,10,11,11,11,12,12,10,10,10,10,
  130091. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,12,
  130092. 11,11,11, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  130093. 10,11,12,11,11,11,11,11,10,10,10,10,10,10,10,10,
  130094. 10,10,10,10,10,10,11,11,11,12,11,11,11,10,10,10,
  130095. 10,10,10,10,10,10,10,10,10,10,10,12,11,11,12,11,
  130096. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130097. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  130098. 10,10,10,10,10,11,11,11,11,12,12,11,11,11,11,11,
  130099. 11,11,10,10,10,10,10,10,10,10,12,12,12,11,11,11,
  130100. 12,11,11,11,10,10,10,10,10,10,10,10,10,10,10,12,
  130101. 11,12,12,12,12,12,11,12,11,11,10,10,10,10,10,10,
  130102. 10,10,10,10,12,12,12,12,11,11,11,11,11,11,11,10,
  130103. 10,10,10,10,10,10,10,10,10,
  130104. };
  130105. static float _vq_quantthresh__44c4_s_p9_2[] = {
  130106. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  130107. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  130108. 6.5, 7.5, 8.5, 9.5,
  130109. };
  130110. static long _vq_quantmap__44c4_s_p9_2[] = {
  130111. 19, 17, 15, 13, 11, 9, 7, 5,
  130112. 3, 1, 0, 2, 4, 6, 8, 10,
  130113. 12, 14, 16, 18, 20,
  130114. };
  130115. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_2 = {
  130116. _vq_quantthresh__44c4_s_p9_2,
  130117. _vq_quantmap__44c4_s_p9_2,
  130118. 21,
  130119. 21
  130120. };
  130121. static static_codebook _44c4_s_p9_2 = {
  130122. 2, 441,
  130123. _vq_lengthlist__44c4_s_p9_2,
  130124. 1, -529268736, 1611661312, 5, 0,
  130125. _vq_quantlist__44c4_s_p9_2,
  130126. NULL,
  130127. &_vq_auxt__44c4_s_p9_2,
  130128. NULL,
  130129. 0
  130130. };
  130131. static long _huff_lengthlist__44c4_s_short[] = {
  130132. 4, 7,14,10,15,10,12,15,16,15, 4, 2,11, 5,10, 6,
  130133. 8,11,14,14,14,10, 7,11, 6, 8,10,11,13,15, 9, 4,
  130134. 11, 5, 9, 6, 9,12,14,15,14, 9, 6, 9, 4, 5, 7,10,
  130135. 12,13, 9, 5, 7, 6, 5, 5, 7,10,13,13,10, 8, 9, 8,
  130136. 7, 6, 8,10,14,14,13,11,10,10, 7, 7, 8,11,14,15,
  130137. 13,12, 9, 9, 6, 5, 7,10,14,17,15,13,11,10, 6, 6,
  130138. 7, 9,12,17,
  130139. };
  130140. static static_codebook _huff_book__44c4_s_short = {
  130141. 2, 100,
  130142. _huff_lengthlist__44c4_s_short,
  130143. 0, 0, 0, 0, 0,
  130144. NULL,
  130145. NULL,
  130146. NULL,
  130147. NULL,
  130148. 0
  130149. };
  130150. static long _huff_lengthlist__44c5_s_long[] = {
  130151. 3, 8, 9,13,10,12,12,12,12,12, 6, 4, 6, 8, 6, 8,
  130152. 10,10,11,12, 8, 5, 4,10, 4, 7, 8, 9,10,11,13, 8,
  130153. 10, 8, 9, 9,11,12,13,14,10, 6, 4, 9, 3, 5, 6, 8,
  130154. 10,11,11, 8, 6, 9, 5, 5, 6, 7, 9,11,12, 9, 7,11,
  130155. 6, 6, 6, 7, 8,10,12,11, 9,12, 7, 7, 6, 6, 7, 9,
  130156. 13,12,10,13, 9, 8, 7, 7, 7, 8,11,15,11,15,11,10,
  130157. 9, 8, 7, 7,
  130158. };
  130159. static static_codebook _huff_book__44c5_s_long = {
  130160. 2, 100,
  130161. _huff_lengthlist__44c5_s_long,
  130162. 0, 0, 0, 0, 0,
  130163. NULL,
  130164. NULL,
  130165. NULL,
  130166. NULL,
  130167. 0
  130168. };
  130169. static long _vq_quantlist__44c5_s_p1_0[] = {
  130170. 1,
  130171. 0,
  130172. 2,
  130173. };
  130174. static long _vq_lengthlist__44c5_s_p1_0[] = {
  130175. 2, 4, 4, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  130176. 0, 0, 4, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130180. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  130181. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130185. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  130186. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  130221. 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  130222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  130226. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  130227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  130231. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  130232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130266. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  130267. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130271. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  130272. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  130273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130276. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  130277. 0, 0, 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 0,
  130278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130585. 0,
  130586. };
  130587. static float _vq_quantthresh__44c5_s_p1_0[] = {
  130588. -0.5, 0.5,
  130589. };
  130590. static long _vq_quantmap__44c5_s_p1_0[] = {
  130591. 1, 0, 2,
  130592. };
  130593. static encode_aux_threshmatch _vq_auxt__44c5_s_p1_0 = {
  130594. _vq_quantthresh__44c5_s_p1_0,
  130595. _vq_quantmap__44c5_s_p1_0,
  130596. 3,
  130597. 3
  130598. };
  130599. static static_codebook _44c5_s_p1_0 = {
  130600. 8, 6561,
  130601. _vq_lengthlist__44c5_s_p1_0,
  130602. 1, -535822336, 1611661312, 2, 0,
  130603. _vq_quantlist__44c5_s_p1_0,
  130604. NULL,
  130605. &_vq_auxt__44c5_s_p1_0,
  130606. NULL,
  130607. 0
  130608. };
  130609. static long _vq_quantlist__44c5_s_p2_0[] = {
  130610. 2,
  130611. 1,
  130612. 3,
  130613. 0,
  130614. 4,
  130615. };
  130616. static long _vq_lengthlist__44c5_s_p2_0[] = {
  130617. 2, 4, 4, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  130618. 8, 7, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  130619. 8, 0, 0, 0, 8, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  130620. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 7, 8, 0,
  130621. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130626. 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 8, 8, 0, 0,
  130627. 0, 8, 8, 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5,
  130628. 7, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,
  130629. 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130634. 0, 0, 0, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8,
  130635. 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0,
  130636. 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,10, 0, 0,
  130637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130642. 8,10,10, 0, 0, 0,10,10, 0, 0, 0, 9,10, 0, 0, 0,
  130643. 11,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0,10,
  130644. 10, 0, 0, 0,10,10, 0, 0, 0,10,11, 0, 0, 0, 0, 0,
  130645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130656. 0,
  130657. };
  130658. static float _vq_quantthresh__44c5_s_p2_0[] = {
  130659. -1.5, -0.5, 0.5, 1.5,
  130660. };
  130661. static long _vq_quantmap__44c5_s_p2_0[] = {
  130662. 3, 1, 0, 2, 4,
  130663. };
  130664. static encode_aux_threshmatch _vq_auxt__44c5_s_p2_0 = {
  130665. _vq_quantthresh__44c5_s_p2_0,
  130666. _vq_quantmap__44c5_s_p2_0,
  130667. 5,
  130668. 5
  130669. };
  130670. static static_codebook _44c5_s_p2_0 = {
  130671. 4, 625,
  130672. _vq_lengthlist__44c5_s_p2_0,
  130673. 1, -533725184, 1611661312, 3, 0,
  130674. _vq_quantlist__44c5_s_p2_0,
  130675. NULL,
  130676. &_vq_auxt__44c5_s_p2_0,
  130677. NULL,
  130678. 0
  130679. };
  130680. static long _vq_quantlist__44c5_s_p3_0[] = {
  130681. 2,
  130682. 1,
  130683. 3,
  130684. 0,
  130685. 4,
  130686. };
  130687. static long _vq_lengthlist__44c5_s_p3_0[] = {
  130688. 2, 4, 3, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 6, 6, 0, 0,
  130690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130691. 0, 0, 3, 5, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  130693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130694. 0, 0, 0, 0, 5, 6, 6, 8, 8, 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, 0, 0, 0, 0, 0, 0, 0,
  130725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130727. 0,
  130728. };
  130729. static float _vq_quantthresh__44c5_s_p3_0[] = {
  130730. -1.5, -0.5, 0.5, 1.5,
  130731. };
  130732. static long _vq_quantmap__44c5_s_p3_0[] = {
  130733. 3, 1, 0, 2, 4,
  130734. };
  130735. static encode_aux_threshmatch _vq_auxt__44c5_s_p3_0 = {
  130736. _vq_quantthresh__44c5_s_p3_0,
  130737. _vq_quantmap__44c5_s_p3_0,
  130738. 5,
  130739. 5
  130740. };
  130741. static static_codebook _44c5_s_p3_0 = {
  130742. 4, 625,
  130743. _vq_lengthlist__44c5_s_p3_0,
  130744. 1, -533725184, 1611661312, 3, 0,
  130745. _vq_quantlist__44c5_s_p3_0,
  130746. NULL,
  130747. &_vq_auxt__44c5_s_p3_0,
  130748. NULL,
  130749. 0
  130750. };
  130751. static long _vq_quantlist__44c5_s_p4_0[] = {
  130752. 4,
  130753. 3,
  130754. 5,
  130755. 2,
  130756. 6,
  130757. 1,
  130758. 7,
  130759. 0,
  130760. 8,
  130761. };
  130762. static long _vq_lengthlist__44c5_s_p4_0[] = {
  130763. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  130764. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  130765. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  130766. 7, 7, 0, 0, 0, 0, 0, 0, 0, 8, 7, 0, 0, 0, 0, 0,
  130767. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130768. 0,
  130769. };
  130770. static float _vq_quantthresh__44c5_s_p4_0[] = {
  130771. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130772. };
  130773. static long _vq_quantmap__44c5_s_p4_0[] = {
  130774. 7, 5, 3, 1, 0, 2, 4, 6,
  130775. 8,
  130776. };
  130777. static encode_aux_threshmatch _vq_auxt__44c5_s_p4_0 = {
  130778. _vq_quantthresh__44c5_s_p4_0,
  130779. _vq_quantmap__44c5_s_p4_0,
  130780. 9,
  130781. 9
  130782. };
  130783. static static_codebook _44c5_s_p4_0 = {
  130784. 2, 81,
  130785. _vq_lengthlist__44c5_s_p4_0,
  130786. 1, -531628032, 1611661312, 4, 0,
  130787. _vq_quantlist__44c5_s_p4_0,
  130788. NULL,
  130789. &_vq_auxt__44c5_s_p4_0,
  130790. NULL,
  130791. 0
  130792. };
  130793. static long _vq_quantlist__44c5_s_p5_0[] = {
  130794. 4,
  130795. 3,
  130796. 5,
  130797. 2,
  130798. 6,
  130799. 1,
  130800. 7,
  130801. 0,
  130802. 8,
  130803. };
  130804. static long _vq_lengthlist__44c5_s_p5_0[] = {
  130805. 2, 4, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  130806. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  130807. 7, 7, 9, 9, 0, 0, 0, 7, 6, 7, 7, 9, 9, 0, 0, 0,
  130808. 8, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  130809. 0, 0, 9, 9, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  130810. 10,
  130811. };
  130812. static float _vq_quantthresh__44c5_s_p5_0[] = {
  130813. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130814. };
  130815. static long _vq_quantmap__44c5_s_p5_0[] = {
  130816. 7, 5, 3, 1, 0, 2, 4, 6,
  130817. 8,
  130818. };
  130819. static encode_aux_threshmatch _vq_auxt__44c5_s_p5_0 = {
  130820. _vq_quantthresh__44c5_s_p5_0,
  130821. _vq_quantmap__44c5_s_p5_0,
  130822. 9,
  130823. 9
  130824. };
  130825. static static_codebook _44c5_s_p5_0 = {
  130826. 2, 81,
  130827. _vq_lengthlist__44c5_s_p5_0,
  130828. 1, -531628032, 1611661312, 4, 0,
  130829. _vq_quantlist__44c5_s_p5_0,
  130830. NULL,
  130831. &_vq_auxt__44c5_s_p5_0,
  130832. NULL,
  130833. 0
  130834. };
  130835. static long _vq_quantlist__44c5_s_p6_0[] = {
  130836. 8,
  130837. 7,
  130838. 9,
  130839. 6,
  130840. 10,
  130841. 5,
  130842. 11,
  130843. 4,
  130844. 12,
  130845. 3,
  130846. 13,
  130847. 2,
  130848. 14,
  130849. 1,
  130850. 15,
  130851. 0,
  130852. 16,
  130853. };
  130854. static long _vq_lengthlist__44c5_s_p6_0[] = {
  130855. 2, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,11,
  130856. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  130857. 12,12, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  130858. 11,12,12, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  130859. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  130860. 10,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  130861. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 9,10,10,10,
  130862. 10,11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,
  130863. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  130864. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  130865. 10,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9,
  130866. 9, 9,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  130867. 10,10,10,10,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  130868. 0, 0, 0,10,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  130869. 0, 0, 0, 0,11,11,11,11,12,12,12,13,13,13, 0, 0,
  130870. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  130871. 0, 0, 0, 0, 0, 0,12,12,12,12,13,12,13,13,13,13,
  130872. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  130873. 13,
  130874. };
  130875. static float _vq_quantthresh__44c5_s_p6_0[] = {
  130876. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  130877. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  130878. };
  130879. static long _vq_quantmap__44c5_s_p6_0[] = {
  130880. 15, 13, 11, 9, 7, 5, 3, 1,
  130881. 0, 2, 4, 6, 8, 10, 12, 14,
  130882. 16,
  130883. };
  130884. static encode_aux_threshmatch _vq_auxt__44c5_s_p6_0 = {
  130885. _vq_quantthresh__44c5_s_p6_0,
  130886. _vq_quantmap__44c5_s_p6_0,
  130887. 17,
  130888. 17
  130889. };
  130890. static static_codebook _44c5_s_p6_0 = {
  130891. 2, 289,
  130892. _vq_lengthlist__44c5_s_p6_0,
  130893. 1, -529530880, 1611661312, 5, 0,
  130894. _vq_quantlist__44c5_s_p6_0,
  130895. NULL,
  130896. &_vq_auxt__44c5_s_p6_0,
  130897. NULL,
  130898. 0
  130899. };
  130900. static long _vq_quantlist__44c5_s_p7_0[] = {
  130901. 1,
  130902. 0,
  130903. 2,
  130904. };
  130905. static long _vq_lengthlist__44c5_s_p7_0[] = {
  130906. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  130907. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  130908. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  130909. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  130910. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  130911. 10,
  130912. };
  130913. static float _vq_quantthresh__44c5_s_p7_0[] = {
  130914. -5.5, 5.5,
  130915. };
  130916. static long _vq_quantmap__44c5_s_p7_0[] = {
  130917. 1, 0, 2,
  130918. };
  130919. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_0 = {
  130920. _vq_quantthresh__44c5_s_p7_0,
  130921. _vq_quantmap__44c5_s_p7_0,
  130922. 3,
  130923. 3
  130924. };
  130925. static static_codebook _44c5_s_p7_0 = {
  130926. 4, 81,
  130927. _vq_lengthlist__44c5_s_p7_0,
  130928. 1, -529137664, 1618345984, 2, 0,
  130929. _vq_quantlist__44c5_s_p7_0,
  130930. NULL,
  130931. &_vq_auxt__44c5_s_p7_0,
  130932. NULL,
  130933. 0
  130934. };
  130935. static long _vq_quantlist__44c5_s_p7_1[] = {
  130936. 5,
  130937. 4,
  130938. 6,
  130939. 3,
  130940. 7,
  130941. 2,
  130942. 8,
  130943. 1,
  130944. 9,
  130945. 0,
  130946. 10,
  130947. };
  130948. static long _vq_lengthlist__44c5_s_p7_1[] = {
  130949. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6,
  130950. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  130951. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  130952. 7, 8, 8, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  130953. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  130954. 8, 8, 8, 8, 8, 8, 8, 9,10,10,10,10,10, 8, 8, 8,
  130955. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  130956. 10,10,10, 8, 8, 8, 8, 8, 8,
  130957. };
  130958. static float _vq_quantthresh__44c5_s_p7_1[] = {
  130959. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  130960. 3.5, 4.5,
  130961. };
  130962. static long _vq_quantmap__44c5_s_p7_1[] = {
  130963. 9, 7, 5, 3, 1, 0, 2, 4,
  130964. 6, 8, 10,
  130965. };
  130966. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_1 = {
  130967. _vq_quantthresh__44c5_s_p7_1,
  130968. _vq_quantmap__44c5_s_p7_1,
  130969. 11,
  130970. 11
  130971. };
  130972. static static_codebook _44c5_s_p7_1 = {
  130973. 2, 121,
  130974. _vq_lengthlist__44c5_s_p7_1,
  130975. 1, -531365888, 1611661312, 4, 0,
  130976. _vq_quantlist__44c5_s_p7_1,
  130977. NULL,
  130978. &_vq_auxt__44c5_s_p7_1,
  130979. NULL,
  130980. 0
  130981. };
  130982. static long _vq_quantlist__44c5_s_p8_0[] = {
  130983. 6,
  130984. 5,
  130985. 7,
  130986. 4,
  130987. 8,
  130988. 3,
  130989. 9,
  130990. 2,
  130991. 10,
  130992. 1,
  130993. 11,
  130994. 0,
  130995. 12,
  130996. };
  130997. static long _vq_lengthlist__44c5_s_p8_0[] = {
  130998. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  130999. 7, 7, 8, 8, 8, 9,10,10,10,10, 7, 5, 5, 7, 7, 8,
  131000. 8, 9, 9,10,10,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  131001. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  131002. 11, 0,12,12, 9, 9, 9,10,10,10,10,10,11,11, 0,13,
  131003. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  131004. 10,10,10,10,11,11,11,11, 0, 0, 0,10,10,10,10,10,
  131005. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  131006. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,12, 0,
  131007. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  131008. 0,12,12,12,12,12,12,13,13,
  131009. };
  131010. static float _vq_quantthresh__44c5_s_p8_0[] = {
  131011. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  131012. 12.5, 17.5, 22.5, 27.5,
  131013. };
  131014. static long _vq_quantmap__44c5_s_p8_0[] = {
  131015. 11, 9, 7, 5, 3, 1, 0, 2,
  131016. 4, 6, 8, 10, 12,
  131017. };
  131018. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_0 = {
  131019. _vq_quantthresh__44c5_s_p8_0,
  131020. _vq_quantmap__44c5_s_p8_0,
  131021. 13,
  131022. 13
  131023. };
  131024. static static_codebook _44c5_s_p8_0 = {
  131025. 2, 169,
  131026. _vq_lengthlist__44c5_s_p8_0,
  131027. 1, -526516224, 1616117760, 4, 0,
  131028. _vq_quantlist__44c5_s_p8_0,
  131029. NULL,
  131030. &_vq_auxt__44c5_s_p8_0,
  131031. NULL,
  131032. 0
  131033. };
  131034. static long _vq_quantlist__44c5_s_p8_1[] = {
  131035. 2,
  131036. 1,
  131037. 3,
  131038. 0,
  131039. 4,
  131040. };
  131041. static long _vq_lengthlist__44c5_s_p8_1[] = {
  131042. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  131043. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  131044. };
  131045. static float _vq_quantthresh__44c5_s_p8_1[] = {
  131046. -1.5, -0.5, 0.5, 1.5,
  131047. };
  131048. static long _vq_quantmap__44c5_s_p8_1[] = {
  131049. 3, 1, 0, 2, 4,
  131050. };
  131051. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_1 = {
  131052. _vq_quantthresh__44c5_s_p8_1,
  131053. _vq_quantmap__44c5_s_p8_1,
  131054. 5,
  131055. 5
  131056. };
  131057. static static_codebook _44c5_s_p8_1 = {
  131058. 2, 25,
  131059. _vq_lengthlist__44c5_s_p8_1,
  131060. 1, -533725184, 1611661312, 3, 0,
  131061. _vq_quantlist__44c5_s_p8_1,
  131062. NULL,
  131063. &_vq_auxt__44c5_s_p8_1,
  131064. NULL,
  131065. 0
  131066. };
  131067. static long _vq_quantlist__44c5_s_p9_0[] = {
  131068. 7,
  131069. 6,
  131070. 8,
  131071. 5,
  131072. 9,
  131073. 4,
  131074. 10,
  131075. 3,
  131076. 11,
  131077. 2,
  131078. 12,
  131079. 1,
  131080. 13,
  131081. 0,
  131082. 14,
  131083. };
  131084. static long _vq_lengthlist__44c5_s_p9_0[] = {
  131085. 1, 3, 3,13,13,13,13,13,13,13,13,13,13,13,13, 4,
  131086. 7, 7,13,13,13,13,13,13,13,13,13,13,13,13, 3, 8,
  131087. 6,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131088. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131089. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131090. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131091. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131092. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131093. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131094. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131095. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131096. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131097. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131098. 13,13,13,13,13,13,13,13,13,12,12,12,12,12,12,12,
  131099. 12,
  131100. };
  131101. static float _vq_quantthresh__44c5_s_p9_0[] = {
  131102. -2320.5, -1963.5, -1606.5, -1249.5, -892.5, -535.5, -178.5, 178.5,
  131103. 535.5, 892.5, 1249.5, 1606.5, 1963.5, 2320.5,
  131104. };
  131105. static long _vq_quantmap__44c5_s_p9_0[] = {
  131106. 13, 11, 9, 7, 5, 3, 1, 0,
  131107. 2, 4, 6, 8, 10, 12, 14,
  131108. };
  131109. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_0 = {
  131110. _vq_quantthresh__44c5_s_p9_0,
  131111. _vq_quantmap__44c5_s_p9_0,
  131112. 15,
  131113. 15
  131114. };
  131115. static static_codebook _44c5_s_p9_0 = {
  131116. 2, 225,
  131117. _vq_lengthlist__44c5_s_p9_0,
  131118. 1, -512522752, 1628852224, 4, 0,
  131119. _vq_quantlist__44c5_s_p9_0,
  131120. NULL,
  131121. &_vq_auxt__44c5_s_p9_0,
  131122. NULL,
  131123. 0
  131124. };
  131125. static long _vq_quantlist__44c5_s_p9_1[] = {
  131126. 8,
  131127. 7,
  131128. 9,
  131129. 6,
  131130. 10,
  131131. 5,
  131132. 11,
  131133. 4,
  131134. 12,
  131135. 3,
  131136. 13,
  131137. 2,
  131138. 14,
  131139. 1,
  131140. 15,
  131141. 0,
  131142. 16,
  131143. };
  131144. static long _vq_lengthlist__44c5_s_p9_1[] = {
  131145. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,11,10,11,
  131146. 11, 6, 5, 5, 7, 7, 8, 9,10,10,11,10,12,11,12,11,
  131147. 13,12, 6, 5, 5, 7, 7, 9, 9,10,10,11,11,12,12,13,
  131148. 12,13,13,18, 8, 8, 8, 8, 9, 9,10,11,11,11,12,11,
  131149. 13,11,13,12,18, 8, 8, 8, 8,10,10,11,11,12,12,13,
  131150. 13,13,13,13,14,18,12,12, 9, 9,11,11,11,11,12,12,
  131151. 13,12,13,12,13,13,20,13,12, 9, 9,11,11,11,11,12,
  131152. 12,13,13,13,14,14,13,20,18,19,11,12,11,11,12,12,
  131153. 13,13,13,13,13,13,14,13,18,19,19,12,11,11,11,12,
  131154. 12,13,12,13,13,13,14,14,13,18,17,19,14,15,12,12,
  131155. 12,13,13,13,14,14,14,14,14,14,19,19,19,16,15,12,
  131156. 11,13,12,14,14,14,13,13,14,14,14,19,18,19,18,19,
  131157. 13,13,13,13,14,14,14,13,14,14,14,14,18,17,19,19,
  131158. 19,13,13,13,11,13,11,13,14,14,14,14,14,19,17,17,
  131159. 18,18,16,16,13,13,13,13,14,13,15,15,14,14,19,19,
  131160. 17,17,18,16,16,13,11,14,10,13,12,14,14,14,14,19,
  131161. 19,19,19,19,18,17,13,14,13,11,14,13,14,14,15,15,
  131162. 19,19,19,17,19,18,18,14,13,12,11,14,11,15,15,15,
  131163. 15,
  131164. };
  131165. static float _vq_quantthresh__44c5_s_p9_1[] = {
  131166. -157.5, -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5,
  131167. 10.5, 31.5, 52.5, 73.5, 94.5, 115.5, 136.5, 157.5,
  131168. };
  131169. static long _vq_quantmap__44c5_s_p9_1[] = {
  131170. 15, 13, 11, 9, 7, 5, 3, 1,
  131171. 0, 2, 4, 6, 8, 10, 12, 14,
  131172. 16,
  131173. };
  131174. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_1 = {
  131175. _vq_quantthresh__44c5_s_p9_1,
  131176. _vq_quantmap__44c5_s_p9_1,
  131177. 17,
  131178. 17
  131179. };
  131180. static static_codebook _44c5_s_p9_1 = {
  131181. 2, 289,
  131182. _vq_lengthlist__44c5_s_p9_1,
  131183. 1, -520814592, 1620377600, 5, 0,
  131184. _vq_quantlist__44c5_s_p9_1,
  131185. NULL,
  131186. &_vq_auxt__44c5_s_p9_1,
  131187. NULL,
  131188. 0
  131189. };
  131190. static long _vq_quantlist__44c5_s_p9_2[] = {
  131191. 10,
  131192. 9,
  131193. 11,
  131194. 8,
  131195. 12,
  131196. 7,
  131197. 13,
  131198. 6,
  131199. 14,
  131200. 5,
  131201. 15,
  131202. 4,
  131203. 16,
  131204. 3,
  131205. 17,
  131206. 2,
  131207. 18,
  131208. 1,
  131209. 19,
  131210. 0,
  131211. 20,
  131212. };
  131213. static long _vq_lengthlist__44c5_s_p9_2[] = {
  131214. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  131215. 8, 8, 8, 8, 9,11, 5, 6, 7, 7, 8, 7, 8, 8, 8, 8,
  131216. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11, 5, 5, 7, 7, 7,
  131217. 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  131218. 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  131219. 9,10, 9,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  131220. 9, 9, 9,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  131221. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,11,11,
  131222. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  131223. 10,10,10,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  131224. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  131225. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,11,11,11,
  131226. 11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,
  131227. 10,10,11,11,11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,
  131228. 10,10,10,10,10,10,10,11,11,11,11,11, 9, 9,10, 9,
  131229. 10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,
  131230. 11,11,11, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  131231. 10,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  131232. 10,10,10,10,10,10,11,11,11,11,11,11,11,10,10,10,
  131233. 10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,
  131234. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131235. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  131236. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  131237. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  131238. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,11,
  131239. 11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  131240. 10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,10,
  131241. 10,10,10,10,10,10,10,10,10,
  131242. };
  131243. static float _vq_quantthresh__44c5_s_p9_2[] = {
  131244. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  131245. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  131246. 6.5, 7.5, 8.5, 9.5,
  131247. };
  131248. static long _vq_quantmap__44c5_s_p9_2[] = {
  131249. 19, 17, 15, 13, 11, 9, 7, 5,
  131250. 3, 1, 0, 2, 4, 6, 8, 10,
  131251. 12, 14, 16, 18, 20,
  131252. };
  131253. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_2 = {
  131254. _vq_quantthresh__44c5_s_p9_2,
  131255. _vq_quantmap__44c5_s_p9_2,
  131256. 21,
  131257. 21
  131258. };
  131259. static static_codebook _44c5_s_p9_2 = {
  131260. 2, 441,
  131261. _vq_lengthlist__44c5_s_p9_2,
  131262. 1, -529268736, 1611661312, 5, 0,
  131263. _vq_quantlist__44c5_s_p9_2,
  131264. NULL,
  131265. &_vq_auxt__44c5_s_p9_2,
  131266. NULL,
  131267. 0
  131268. };
  131269. static long _huff_lengthlist__44c5_s_short[] = {
  131270. 5, 8,10,14,11,11,12,16,15,17, 5, 5, 7, 9, 7, 8,
  131271. 10,13,17,17, 7, 5, 5,10, 5, 7, 8,11,13,15,10, 8,
  131272. 10, 8, 8, 8,11,15,18,18, 8, 5, 5, 8, 3, 4, 6,10,
  131273. 14,16, 9, 7, 6, 7, 4, 3, 5, 9,14,18,10, 9, 8,10,
  131274. 6, 5, 6, 9,14,18,12,12,11,12, 8, 7, 8,11,14,18,
  131275. 14,13,12,10, 7, 5, 6, 9,14,18,14,14,13,10, 6, 5,
  131276. 6, 8,11,16,
  131277. };
  131278. static static_codebook _huff_book__44c5_s_short = {
  131279. 2, 100,
  131280. _huff_lengthlist__44c5_s_short,
  131281. 0, 0, 0, 0, 0,
  131282. NULL,
  131283. NULL,
  131284. NULL,
  131285. NULL,
  131286. 0
  131287. };
  131288. static long _huff_lengthlist__44c6_s_long[] = {
  131289. 3, 8,11,13,14,14,13,13,16,14, 6, 3, 4, 7, 9, 9,
  131290. 10,11,14,13,10, 4, 3, 5, 7, 7, 9,10,13,15,12, 7,
  131291. 4, 4, 6, 6, 8,10,13,15,12, 8, 6, 6, 6, 6, 8,10,
  131292. 13,14,11, 9, 7, 6, 6, 6, 7, 8,12,11,13,10, 9, 8,
  131293. 7, 6, 6, 7,11,11,13,11,10, 9, 9, 7, 7, 6,10,11,
  131294. 13,13,13,13,13,11, 9, 8,10,12,12,15,15,16,15,12,
  131295. 11,10,10,12,
  131296. };
  131297. static static_codebook _huff_book__44c6_s_long = {
  131298. 2, 100,
  131299. _huff_lengthlist__44c6_s_long,
  131300. 0, 0, 0, 0, 0,
  131301. NULL,
  131302. NULL,
  131303. NULL,
  131304. NULL,
  131305. 0
  131306. };
  131307. static long _vq_quantlist__44c6_s_p1_0[] = {
  131308. 1,
  131309. 0,
  131310. 2,
  131311. };
  131312. static long _vq_lengthlist__44c6_s_p1_0[] = {
  131313. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  131314. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  131315. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  131316. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  131317. 9, 9, 0, 8, 8, 0, 8, 8, 5, 9, 9, 0, 8, 8, 0, 8,
  131318. 8,
  131319. };
  131320. static float _vq_quantthresh__44c6_s_p1_0[] = {
  131321. -0.5, 0.5,
  131322. };
  131323. static long _vq_quantmap__44c6_s_p1_0[] = {
  131324. 1, 0, 2,
  131325. };
  131326. static encode_aux_threshmatch _vq_auxt__44c6_s_p1_0 = {
  131327. _vq_quantthresh__44c6_s_p1_0,
  131328. _vq_quantmap__44c6_s_p1_0,
  131329. 3,
  131330. 3
  131331. };
  131332. static static_codebook _44c6_s_p1_0 = {
  131333. 4, 81,
  131334. _vq_lengthlist__44c6_s_p1_0,
  131335. 1, -535822336, 1611661312, 2, 0,
  131336. _vq_quantlist__44c6_s_p1_0,
  131337. NULL,
  131338. &_vq_auxt__44c6_s_p1_0,
  131339. NULL,
  131340. 0
  131341. };
  131342. static long _vq_quantlist__44c6_s_p2_0[] = {
  131343. 2,
  131344. 1,
  131345. 3,
  131346. 0,
  131347. 4,
  131348. };
  131349. static long _vq_lengthlist__44c6_s_p2_0[] = {
  131350. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  131351. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  131352. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  131353. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  131354. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,11,
  131355. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  131356. 0, 0,14,13, 8, 9, 9,11,11, 0,11,11,12,12, 0,10,
  131357. 11,12,12, 0,14,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  131358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131359. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  131360. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  131361. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  131362. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  131363. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  131364. 13, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,12,12,
  131365. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  131366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131367. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  131368. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,11,
  131369. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,11,
  131370. 0, 0, 0,10,11, 8,10,10,12,12, 0,10,10,12,12, 0,
  131371. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,14,13, 8,10,
  131372. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  131373. 13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131375. 7,10,10,14,13, 0, 9, 9,13,12, 0, 9, 9,12,12, 0,
  131376. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  131377. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  131378. 12,12, 9,11,11,14,13, 0,11,10,14,13, 0,11,11,13,
  131379. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  131380. 0,10,11,13,14, 0,11,11,13,13, 0,12,12,13,13, 0,
  131381. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  131386. 11,11,14,14, 0,11,11,13,13, 0,11,10,13,13, 0,12,
  131387. 12,13,13, 0, 0, 0,13,13, 9,11,11,14,14, 0,11,11,
  131388. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  131389. 13,
  131390. };
  131391. static float _vq_quantthresh__44c6_s_p2_0[] = {
  131392. -1.5, -0.5, 0.5, 1.5,
  131393. };
  131394. static long _vq_quantmap__44c6_s_p2_0[] = {
  131395. 3, 1, 0, 2, 4,
  131396. };
  131397. static encode_aux_threshmatch _vq_auxt__44c6_s_p2_0 = {
  131398. _vq_quantthresh__44c6_s_p2_0,
  131399. _vq_quantmap__44c6_s_p2_0,
  131400. 5,
  131401. 5
  131402. };
  131403. static static_codebook _44c6_s_p2_0 = {
  131404. 4, 625,
  131405. _vq_lengthlist__44c6_s_p2_0,
  131406. 1, -533725184, 1611661312, 3, 0,
  131407. _vq_quantlist__44c6_s_p2_0,
  131408. NULL,
  131409. &_vq_auxt__44c6_s_p2_0,
  131410. NULL,
  131411. 0
  131412. };
  131413. static long _vq_quantlist__44c6_s_p3_0[] = {
  131414. 4,
  131415. 3,
  131416. 5,
  131417. 2,
  131418. 6,
  131419. 1,
  131420. 7,
  131421. 0,
  131422. 8,
  131423. };
  131424. static long _vq_lengthlist__44c6_s_p3_0[] = {
  131425. 2, 3, 4, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  131426. 9,10, 0, 4, 4, 6, 6, 7, 7,10, 9, 0, 5, 5, 7, 7,
  131427. 8, 8,10,10, 0, 0, 0, 7, 6, 8, 8,10,10, 0, 0, 0,
  131428. 7, 7, 9, 9,11,11, 0, 0, 0, 7, 7, 9, 9,11,11, 0,
  131429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131430. 0,
  131431. };
  131432. static float _vq_quantthresh__44c6_s_p3_0[] = {
  131433. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  131434. };
  131435. static long _vq_quantmap__44c6_s_p3_0[] = {
  131436. 7, 5, 3, 1, 0, 2, 4, 6,
  131437. 8,
  131438. };
  131439. static encode_aux_threshmatch _vq_auxt__44c6_s_p3_0 = {
  131440. _vq_quantthresh__44c6_s_p3_0,
  131441. _vq_quantmap__44c6_s_p3_0,
  131442. 9,
  131443. 9
  131444. };
  131445. static static_codebook _44c6_s_p3_0 = {
  131446. 2, 81,
  131447. _vq_lengthlist__44c6_s_p3_0,
  131448. 1, -531628032, 1611661312, 4, 0,
  131449. _vq_quantlist__44c6_s_p3_0,
  131450. NULL,
  131451. &_vq_auxt__44c6_s_p3_0,
  131452. NULL,
  131453. 0
  131454. };
  131455. static long _vq_quantlist__44c6_s_p4_0[] = {
  131456. 8,
  131457. 7,
  131458. 9,
  131459. 6,
  131460. 10,
  131461. 5,
  131462. 11,
  131463. 4,
  131464. 12,
  131465. 3,
  131466. 13,
  131467. 2,
  131468. 14,
  131469. 1,
  131470. 15,
  131471. 0,
  131472. 16,
  131473. };
  131474. static long _vq_lengthlist__44c6_s_p4_0[] = {
  131475. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,10,10,
  131476. 10, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  131477. 11,11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  131478. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  131479. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  131480. 10,11,11,11,11, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  131481. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,
  131482. 10,11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  131483. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  131484. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  131485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131493. 0,
  131494. };
  131495. static float _vq_quantthresh__44c6_s_p4_0[] = {
  131496. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  131497. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  131498. };
  131499. static long _vq_quantmap__44c6_s_p4_0[] = {
  131500. 15, 13, 11, 9, 7, 5, 3, 1,
  131501. 0, 2, 4, 6, 8, 10, 12, 14,
  131502. 16,
  131503. };
  131504. static encode_aux_threshmatch _vq_auxt__44c6_s_p4_0 = {
  131505. _vq_quantthresh__44c6_s_p4_0,
  131506. _vq_quantmap__44c6_s_p4_0,
  131507. 17,
  131508. 17
  131509. };
  131510. static static_codebook _44c6_s_p4_0 = {
  131511. 2, 289,
  131512. _vq_lengthlist__44c6_s_p4_0,
  131513. 1, -529530880, 1611661312, 5, 0,
  131514. _vq_quantlist__44c6_s_p4_0,
  131515. NULL,
  131516. &_vq_auxt__44c6_s_p4_0,
  131517. NULL,
  131518. 0
  131519. };
  131520. static long _vq_quantlist__44c6_s_p5_0[] = {
  131521. 1,
  131522. 0,
  131523. 2,
  131524. };
  131525. static long _vq_lengthlist__44c6_s_p5_0[] = {
  131526. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6, 9, 9,10,10,
  131527. 10, 9, 4, 6, 6, 9,10, 9,10, 9,10, 6, 9, 9,10,12,
  131528. 11,10,11,11, 7,10, 9,11,12,12,12,12,12, 7,10,10,
  131529. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  131530. 9,10,11,12,12,12,12,12, 7,10, 9,12,12,12,12,12,
  131531. 12,
  131532. };
  131533. static float _vq_quantthresh__44c6_s_p5_0[] = {
  131534. -5.5, 5.5,
  131535. };
  131536. static long _vq_quantmap__44c6_s_p5_0[] = {
  131537. 1, 0, 2,
  131538. };
  131539. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_0 = {
  131540. _vq_quantthresh__44c6_s_p5_0,
  131541. _vq_quantmap__44c6_s_p5_0,
  131542. 3,
  131543. 3
  131544. };
  131545. static static_codebook _44c6_s_p5_0 = {
  131546. 4, 81,
  131547. _vq_lengthlist__44c6_s_p5_0,
  131548. 1, -529137664, 1618345984, 2, 0,
  131549. _vq_quantlist__44c6_s_p5_0,
  131550. NULL,
  131551. &_vq_auxt__44c6_s_p5_0,
  131552. NULL,
  131553. 0
  131554. };
  131555. static long _vq_quantlist__44c6_s_p5_1[] = {
  131556. 5,
  131557. 4,
  131558. 6,
  131559. 3,
  131560. 7,
  131561. 2,
  131562. 8,
  131563. 1,
  131564. 9,
  131565. 0,
  131566. 10,
  131567. };
  131568. static long _vq_lengthlist__44c6_s_p5_1[] = {
  131569. 3, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  131570. 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6, 7, 7, 8, 8, 8,
  131571. 8,11, 6, 6, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  131572. 6, 7, 8, 8, 8, 8, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  131573. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 8,11,11,11,
  131574. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,10,10, 8, 8, 8,
  131575. 8, 8, 8,11,11,11,10,10, 8, 8, 8, 8, 8, 8,11,11,
  131576. 11,10,10, 7, 7, 8, 8, 8, 8,
  131577. };
  131578. static float _vq_quantthresh__44c6_s_p5_1[] = {
  131579. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  131580. 3.5, 4.5,
  131581. };
  131582. static long _vq_quantmap__44c6_s_p5_1[] = {
  131583. 9, 7, 5, 3, 1, 0, 2, 4,
  131584. 6, 8, 10,
  131585. };
  131586. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_1 = {
  131587. _vq_quantthresh__44c6_s_p5_1,
  131588. _vq_quantmap__44c6_s_p5_1,
  131589. 11,
  131590. 11
  131591. };
  131592. static static_codebook _44c6_s_p5_1 = {
  131593. 2, 121,
  131594. _vq_lengthlist__44c6_s_p5_1,
  131595. 1, -531365888, 1611661312, 4, 0,
  131596. _vq_quantlist__44c6_s_p5_1,
  131597. NULL,
  131598. &_vq_auxt__44c6_s_p5_1,
  131599. NULL,
  131600. 0
  131601. };
  131602. static long _vq_quantlist__44c6_s_p6_0[] = {
  131603. 6,
  131604. 5,
  131605. 7,
  131606. 4,
  131607. 8,
  131608. 3,
  131609. 9,
  131610. 2,
  131611. 10,
  131612. 1,
  131613. 11,
  131614. 0,
  131615. 12,
  131616. };
  131617. static long _vq_lengthlist__44c6_s_p6_0[] = {
  131618. 1, 4, 4, 6, 6, 8, 8, 8, 8,10, 9,10,10, 6, 5, 5,
  131619. 7, 7, 9, 9, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 9,
  131620. 9,10, 9,11,10,11,11, 0, 6, 6, 7, 7, 9, 9,10,10,
  131621. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  131622. 12, 0,11,11, 8, 8,10,10,11,11,12,12,12,12, 0,11,
  131623. 12, 9, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  131624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131628. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131629. };
  131630. static float _vq_quantthresh__44c6_s_p6_0[] = {
  131631. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  131632. 12.5, 17.5, 22.5, 27.5,
  131633. };
  131634. static long _vq_quantmap__44c6_s_p6_0[] = {
  131635. 11, 9, 7, 5, 3, 1, 0, 2,
  131636. 4, 6, 8, 10, 12,
  131637. };
  131638. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_0 = {
  131639. _vq_quantthresh__44c6_s_p6_0,
  131640. _vq_quantmap__44c6_s_p6_0,
  131641. 13,
  131642. 13
  131643. };
  131644. static static_codebook _44c6_s_p6_0 = {
  131645. 2, 169,
  131646. _vq_lengthlist__44c6_s_p6_0,
  131647. 1, -526516224, 1616117760, 4, 0,
  131648. _vq_quantlist__44c6_s_p6_0,
  131649. NULL,
  131650. &_vq_auxt__44c6_s_p6_0,
  131651. NULL,
  131652. 0
  131653. };
  131654. static long _vq_quantlist__44c6_s_p6_1[] = {
  131655. 2,
  131656. 1,
  131657. 3,
  131658. 0,
  131659. 4,
  131660. };
  131661. static long _vq_lengthlist__44c6_s_p6_1[] = {
  131662. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  131663. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  131664. };
  131665. static float _vq_quantthresh__44c6_s_p6_1[] = {
  131666. -1.5, -0.5, 0.5, 1.5,
  131667. };
  131668. static long _vq_quantmap__44c6_s_p6_1[] = {
  131669. 3, 1, 0, 2, 4,
  131670. };
  131671. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_1 = {
  131672. _vq_quantthresh__44c6_s_p6_1,
  131673. _vq_quantmap__44c6_s_p6_1,
  131674. 5,
  131675. 5
  131676. };
  131677. static static_codebook _44c6_s_p6_1 = {
  131678. 2, 25,
  131679. _vq_lengthlist__44c6_s_p6_1,
  131680. 1, -533725184, 1611661312, 3, 0,
  131681. _vq_quantlist__44c6_s_p6_1,
  131682. NULL,
  131683. &_vq_auxt__44c6_s_p6_1,
  131684. NULL,
  131685. 0
  131686. };
  131687. static long _vq_quantlist__44c6_s_p7_0[] = {
  131688. 6,
  131689. 5,
  131690. 7,
  131691. 4,
  131692. 8,
  131693. 3,
  131694. 9,
  131695. 2,
  131696. 10,
  131697. 1,
  131698. 11,
  131699. 0,
  131700. 12,
  131701. };
  131702. static long _vq_lengthlist__44c6_s_p7_0[] = {
  131703. 1, 4, 4, 6, 6, 8, 8, 8, 8,10,10,11,10, 6, 5, 5,
  131704. 7, 7, 8, 8, 9, 9,10,10,12,11, 6, 5, 5, 7, 7, 8,
  131705. 8, 9, 9,10,10,12,11,21, 7, 7, 7, 7, 9, 9,10,10,
  131706. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  131707. 12,21,12,12, 9, 9,10,10,11,11,11,11,12,12,21,12,
  131708. 12, 9, 9,10,10,11,11,12,12,12,12,21,21,21,11,11,
  131709. 10,10,11,12,12,12,13,13,21,21,21,11,11,10,10,12,
  131710. 12,12,12,13,13,21,21,21,15,15,11,11,12,12,13,13,
  131711. 13,13,21,21,21,15,16,11,11,12,12,13,13,14,14,21,
  131712. 21,21,21,20,13,13,13,13,13,13,14,14,20,20,20,20,
  131713. 20,13,13,13,13,13,13,14,14,
  131714. };
  131715. static float _vq_quantthresh__44c6_s_p7_0[] = {
  131716. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  131717. 27.5, 38.5, 49.5, 60.5,
  131718. };
  131719. static long _vq_quantmap__44c6_s_p7_0[] = {
  131720. 11, 9, 7, 5, 3, 1, 0, 2,
  131721. 4, 6, 8, 10, 12,
  131722. };
  131723. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_0 = {
  131724. _vq_quantthresh__44c6_s_p7_0,
  131725. _vq_quantmap__44c6_s_p7_0,
  131726. 13,
  131727. 13
  131728. };
  131729. static static_codebook _44c6_s_p7_0 = {
  131730. 2, 169,
  131731. _vq_lengthlist__44c6_s_p7_0,
  131732. 1, -523206656, 1618345984, 4, 0,
  131733. _vq_quantlist__44c6_s_p7_0,
  131734. NULL,
  131735. &_vq_auxt__44c6_s_p7_0,
  131736. NULL,
  131737. 0
  131738. };
  131739. static long _vq_quantlist__44c6_s_p7_1[] = {
  131740. 5,
  131741. 4,
  131742. 6,
  131743. 3,
  131744. 7,
  131745. 2,
  131746. 8,
  131747. 1,
  131748. 9,
  131749. 0,
  131750. 10,
  131751. };
  131752. static long _vq_lengthlist__44c6_s_p7_1[] = {
  131753. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 9, 5, 5, 6, 6,
  131754. 7, 7, 7, 7, 8, 7, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7,
  131755. 7, 9, 6, 6, 7, 7, 7, 7, 8, 7, 7, 8, 9, 9, 9, 7,
  131756. 7, 7, 7, 7, 7, 7, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  131757. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  131758. 8, 8, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 8, 8, 8, 7,
  131759. 7, 8, 8, 9, 9, 9, 8, 8, 8, 8, 7, 7, 8, 8, 9, 9,
  131760. 9, 8, 8, 7, 7, 7, 7, 8, 8,
  131761. };
  131762. static float _vq_quantthresh__44c6_s_p7_1[] = {
  131763. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  131764. 3.5, 4.5,
  131765. };
  131766. static long _vq_quantmap__44c6_s_p7_1[] = {
  131767. 9, 7, 5, 3, 1, 0, 2, 4,
  131768. 6, 8, 10,
  131769. };
  131770. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_1 = {
  131771. _vq_quantthresh__44c6_s_p7_1,
  131772. _vq_quantmap__44c6_s_p7_1,
  131773. 11,
  131774. 11
  131775. };
  131776. static static_codebook _44c6_s_p7_1 = {
  131777. 2, 121,
  131778. _vq_lengthlist__44c6_s_p7_1,
  131779. 1, -531365888, 1611661312, 4, 0,
  131780. _vq_quantlist__44c6_s_p7_1,
  131781. NULL,
  131782. &_vq_auxt__44c6_s_p7_1,
  131783. NULL,
  131784. 0
  131785. };
  131786. static long _vq_quantlist__44c6_s_p8_0[] = {
  131787. 7,
  131788. 6,
  131789. 8,
  131790. 5,
  131791. 9,
  131792. 4,
  131793. 10,
  131794. 3,
  131795. 11,
  131796. 2,
  131797. 12,
  131798. 1,
  131799. 13,
  131800. 0,
  131801. 14,
  131802. };
  131803. static long _vq_lengthlist__44c6_s_p8_0[] = {
  131804. 1, 4, 4, 7, 7, 8, 8, 7, 7, 8, 7, 9, 8,10, 9, 6,
  131805. 5, 5, 8, 8, 9, 9, 8, 8, 9, 9,11,10,11,10, 6, 5,
  131806. 5, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,11,18, 8, 8,
  131807. 9, 8,10,10, 9, 9,10,10,10,10,11,10,18, 8, 8, 9,
  131808. 9,10,10, 9, 9,10,10,11,11,12,12,18,12,13, 9,10,
  131809. 10,10, 9,10,10,10,11,11,12,11,18,13,13, 9, 9,10,
  131810. 10,10,10,10,10,11,11,12,12,18,18,18,10,10, 9, 9,
  131811. 11,11,11,11,11,12,12,12,18,18,18,10, 9,10, 9,11,
  131812. 10,11,11,11,11,13,12,18,18,18,14,13,10,10,11,11,
  131813. 12,12,12,12,12,12,18,18,18,14,13,10,10,11,10,12,
  131814. 12,12,12,12,12,18,18,18,18,18,12,12,11,11,12,12,
  131815. 13,13,13,14,18,18,18,18,18,12,12,11,11,12,11,13,
  131816. 13,14,13,18,18,18,18,18,16,16,11,12,12,13,13,13,
  131817. 14,13,18,18,18,18,18,16,15,12,11,12,11,13,11,15,
  131818. 14,
  131819. };
  131820. static float _vq_quantthresh__44c6_s_p8_0[] = {
  131821. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  131822. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  131823. };
  131824. static long _vq_quantmap__44c6_s_p8_0[] = {
  131825. 13, 11, 9, 7, 5, 3, 1, 0,
  131826. 2, 4, 6, 8, 10, 12, 14,
  131827. };
  131828. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_0 = {
  131829. _vq_quantthresh__44c6_s_p8_0,
  131830. _vq_quantmap__44c6_s_p8_0,
  131831. 15,
  131832. 15
  131833. };
  131834. static static_codebook _44c6_s_p8_0 = {
  131835. 2, 225,
  131836. _vq_lengthlist__44c6_s_p8_0,
  131837. 1, -520986624, 1620377600, 4, 0,
  131838. _vq_quantlist__44c6_s_p8_0,
  131839. NULL,
  131840. &_vq_auxt__44c6_s_p8_0,
  131841. NULL,
  131842. 0
  131843. };
  131844. static long _vq_quantlist__44c6_s_p8_1[] = {
  131845. 10,
  131846. 9,
  131847. 11,
  131848. 8,
  131849. 12,
  131850. 7,
  131851. 13,
  131852. 6,
  131853. 14,
  131854. 5,
  131855. 15,
  131856. 4,
  131857. 16,
  131858. 3,
  131859. 17,
  131860. 2,
  131861. 18,
  131862. 1,
  131863. 19,
  131864. 0,
  131865. 20,
  131866. };
  131867. static long _vq_lengthlist__44c6_s_p8_1[] = {
  131868. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  131869. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,
  131870. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  131871. 8, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10,
  131872. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  131873. 9, 9, 9, 9,10,11,11, 8, 7, 8, 8, 8, 9, 9, 9, 9,
  131874. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8,
  131875. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,
  131876. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  131877. 9, 9, 9,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  131878. 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9, 9,
  131879. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,
  131880. 11,11, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9,10, 9, 9,
  131881. 10, 9,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,10,10,
  131882. 10,10, 9,10,10, 9,10,11,11,11,11,11, 9, 9, 9, 9,
  131883. 10,10,10, 9,10,10,10,10, 9,10,10, 9,11,11,11,11,
  131884. 11,11,11, 9, 9, 9, 9,10,10,10,10, 9,10,10,10,10,
  131885. 10,11,11,11,11,11,11,11,10, 9,10,10,10,10,10,10,
  131886. 10, 9,10, 9,10,10,11,11,11,11,11,11,11,10, 9,10,
  131887. 9,10,10, 9,10,10,10,10,10,10,10,11,11,11,11,11,
  131888. 11,11,10,10,10,10,10,10,10, 9,10,10,10,10,10, 9,
  131889. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  131890. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  131891. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  131892. 11,11,11,10,10,10,10,10,10,10,10,10, 9,10,10,11,
  131893. 11,11,11,11,11,11,11,11,10,10,10, 9,10,10,10,10,
  131894. 10,10,10,10,10,11,11,11,11,11,11,11,11,10,11, 9,
  131895. 10,10,10,10,10,10,10,10,10,
  131896. };
  131897. static float _vq_quantthresh__44c6_s_p8_1[] = {
  131898. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  131899. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  131900. 6.5, 7.5, 8.5, 9.5,
  131901. };
  131902. static long _vq_quantmap__44c6_s_p8_1[] = {
  131903. 19, 17, 15, 13, 11, 9, 7, 5,
  131904. 3, 1, 0, 2, 4, 6, 8, 10,
  131905. 12, 14, 16, 18, 20,
  131906. };
  131907. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_1 = {
  131908. _vq_quantthresh__44c6_s_p8_1,
  131909. _vq_quantmap__44c6_s_p8_1,
  131910. 21,
  131911. 21
  131912. };
  131913. static static_codebook _44c6_s_p8_1 = {
  131914. 2, 441,
  131915. _vq_lengthlist__44c6_s_p8_1,
  131916. 1, -529268736, 1611661312, 5, 0,
  131917. _vq_quantlist__44c6_s_p8_1,
  131918. NULL,
  131919. &_vq_auxt__44c6_s_p8_1,
  131920. NULL,
  131921. 0
  131922. };
  131923. static long _vq_quantlist__44c6_s_p9_0[] = {
  131924. 6,
  131925. 5,
  131926. 7,
  131927. 4,
  131928. 8,
  131929. 3,
  131930. 9,
  131931. 2,
  131932. 10,
  131933. 1,
  131934. 11,
  131935. 0,
  131936. 12,
  131937. };
  131938. static long _vq_lengthlist__44c6_s_p9_0[] = {
  131939. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 7, 7,
  131940. 11,11,11,11,11,11,11,11,11,11, 5, 8, 9,11,11,11,
  131941. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131942. 11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,10,
  131943. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131944. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131945. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131946. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131947. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131948. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131949. 10,10,10,10,10,10,10,10,10,
  131950. };
  131951. static float _vq_quantthresh__44c6_s_p9_0[] = {
  131952. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  131953. 1592.5, 2229.5, 2866.5, 3503.5,
  131954. };
  131955. static long _vq_quantmap__44c6_s_p9_0[] = {
  131956. 11, 9, 7, 5, 3, 1, 0, 2,
  131957. 4, 6, 8, 10, 12,
  131958. };
  131959. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_0 = {
  131960. _vq_quantthresh__44c6_s_p9_0,
  131961. _vq_quantmap__44c6_s_p9_0,
  131962. 13,
  131963. 13
  131964. };
  131965. static static_codebook _44c6_s_p9_0 = {
  131966. 2, 169,
  131967. _vq_lengthlist__44c6_s_p9_0,
  131968. 1, -511845376, 1630791680, 4, 0,
  131969. _vq_quantlist__44c6_s_p9_0,
  131970. NULL,
  131971. &_vq_auxt__44c6_s_p9_0,
  131972. NULL,
  131973. 0
  131974. };
  131975. static long _vq_quantlist__44c6_s_p9_1[] = {
  131976. 6,
  131977. 5,
  131978. 7,
  131979. 4,
  131980. 8,
  131981. 3,
  131982. 9,
  131983. 2,
  131984. 10,
  131985. 1,
  131986. 11,
  131987. 0,
  131988. 12,
  131989. };
  131990. static long _vq_lengthlist__44c6_s_p9_1[] = {
  131991. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  131992. 8, 8, 8, 8, 8, 7, 9, 8,10,10, 5, 6, 6, 8, 8, 9,
  131993. 9, 8, 8,10,10,10,10,16, 9, 9, 9, 9, 9, 9, 9, 8,
  131994. 10, 9,11,11,16, 8, 9, 9, 9, 9, 9, 9, 9,10,10,11,
  131995. 11,16,13,13, 9, 9,10, 9, 9,10,11,11,11,12,16,13,
  131996. 14, 9, 8,10, 8, 9, 9,10,10,12,11,16,14,16, 9, 9,
  131997. 9, 9,11,11,12,11,12,11,16,16,16, 9, 7, 9, 6,11,
  131998. 11,11,10,11,11,16,16,16,11,12, 9,10,11,11,12,11,
  131999. 13,13,16,16,16,12,11,10, 7,12,10,12,12,12,12,16,
  132000. 16,15,16,16,10,11,10,11,13,13,14,12,16,16,16,15,
  132001. 15,12,10,11,11,13,11,12,13,
  132002. };
  132003. static float _vq_quantthresh__44c6_s_p9_1[] = {
  132004. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  132005. 122.5, 171.5, 220.5, 269.5,
  132006. };
  132007. static long _vq_quantmap__44c6_s_p9_1[] = {
  132008. 11, 9, 7, 5, 3, 1, 0, 2,
  132009. 4, 6, 8, 10, 12,
  132010. };
  132011. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_1 = {
  132012. _vq_quantthresh__44c6_s_p9_1,
  132013. _vq_quantmap__44c6_s_p9_1,
  132014. 13,
  132015. 13
  132016. };
  132017. static static_codebook _44c6_s_p9_1 = {
  132018. 2, 169,
  132019. _vq_lengthlist__44c6_s_p9_1,
  132020. 1, -518889472, 1622704128, 4, 0,
  132021. _vq_quantlist__44c6_s_p9_1,
  132022. NULL,
  132023. &_vq_auxt__44c6_s_p9_1,
  132024. NULL,
  132025. 0
  132026. };
  132027. static long _vq_quantlist__44c6_s_p9_2[] = {
  132028. 24,
  132029. 23,
  132030. 25,
  132031. 22,
  132032. 26,
  132033. 21,
  132034. 27,
  132035. 20,
  132036. 28,
  132037. 19,
  132038. 29,
  132039. 18,
  132040. 30,
  132041. 17,
  132042. 31,
  132043. 16,
  132044. 32,
  132045. 15,
  132046. 33,
  132047. 14,
  132048. 34,
  132049. 13,
  132050. 35,
  132051. 12,
  132052. 36,
  132053. 11,
  132054. 37,
  132055. 10,
  132056. 38,
  132057. 9,
  132058. 39,
  132059. 8,
  132060. 40,
  132061. 7,
  132062. 41,
  132063. 6,
  132064. 42,
  132065. 5,
  132066. 43,
  132067. 4,
  132068. 44,
  132069. 3,
  132070. 45,
  132071. 2,
  132072. 46,
  132073. 1,
  132074. 47,
  132075. 0,
  132076. 48,
  132077. };
  132078. static long _vq_lengthlist__44c6_s_p9_2[] = {
  132079. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  132080. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  132081. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  132082. 7,
  132083. };
  132084. static float _vq_quantthresh__44c6_s_p9_2[] = {
  132085. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  132086. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  132087. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132088. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132089. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  132090. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  132091. };
  132092. static long _vq_quantmap__44c6_s_p9_2[] = {
  132093. 47, 45, 43, 41, 39, 37, 35, 33,
  132094. 31, 29, 27, 25, 23, 21, 19, 17,
  132095. 15, 13, 11, 9, 7, 5, 3, 1,
  132096. 0, 2, 4, 6, 8, 10, 12, 14,
  132097. 16, 18, 20, 22, 24, 26, 28, 30,
  132098. 32, 34, 36, 38, 40, 42, 44, 46,
  132099. 48,
  132100. };
  132101. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_2 = {
  132102. _vq_quantthresh__44c6_s_p9_2,
  132103. _vq_quantmap__44c6_s_p9_2,
  132104. 49,
  132105. 49
  132106. };
  132107. static static_codebook _44c6_s_p9_2 = {
  132108. 1, 49,
  132109. _vq_lengthlist__44c6_s_p9_2,
  132110. 1, -526909440, 1611661312, 6, 0,
  132111. _vq_quantlist__44c6_s_p9_2,
  132112. NULL,
  132113. &_vq_auxt__44c6_s_p9_2,
  132114. NULL,
  132115. 0
  132116. };
  132117. static long _huff_lengthlist__44c6_s_short[] = {
  132118. 3, 9,11,11,13,14,19,17,17,19, 5, 4, 5, 8,10,10,
  132119. 13,16,18,19, 7, 4, 4, 5, 8, 9,12,14,17,19, 8, 6,
  132120. 5, 5, 7, 7,10,13,16,18,10, 8, 7, 6, 5, 5, 8,11,
  132121. 17,19,11, 9, 7, 7, 5, 4, 5, 8,17,19,13,11, 8, 7,
  132122. 7, 5, 5, 7,16,18,14,13, 8, 6, 6, 5, 5, 7,16,18,
  132123. 18,16,10, 8, 8, 7, 7, 9,16,18,18,18,12,10,10, 9,
  132124. 9,10,17,18,
  132125. };
  132126. static static_codebook _huff_book__44c6_s_short = {
  132127. 2, 100,
  132128. _huff_lengthlist__44c6_s_short,
  132129. 0, 0, 0, 0, 0,
  132130. NULL,
  132131. NULL,
  132132. NULL,
  132133. NULL,
  132134. 0
  132135. };
  132136. static long _huff_lengthlist__44c7_s_long[] = {
  132137. 3, 8,11,13,15,14,14,13,15,14, 6, 4, 5, 7, 9,10,
  132138. 11,11,14,13,10, 4, 3, 5, 7, 8, 9,10,13,13,12, 7,
  132139. 4, 4, 5, 6, 8, 9,12,14,13, 9, 6, 5, 5, 6, 8, 9,
  132140. 12,14,12, 9, 7, 6, 5, 5, 6, 8,11,11,12,11, 9, 8,
  132141. 7, 6, 6, 7,10,11,13,11,10, 9, 8, 7, 6, 6, 9,11,
  132142. 13,13,12,12,12,10, 9, 8, 9,11,12,14,15,15,14,12,
  132143. 11,10,10,12,
  132144. };
  132145. static static_codebook _huff_book__44c7_s_long = {
  132146. 2, 100,
  132147. _huff_lengthlist__44c7_s_long,
  132148. 0, 0, 0, 0, 0,
  132149. NULL,
  132150. NULL,
  132151. NULL,
  132152. NULL,
  132153. 0
  132154. };
  132155. static long _vq_quantlist__44c7_s_p1_0[] = {
  132156. 1,
  132157. 0,
  132158. 2,
  132159. };
  132160. static long _vq_lengthlist__44c7_s_p1_0[] = {
  132161. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  132162. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  132163. 0, 0, 0, 0, 5, 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  132164. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  132165. 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  132166. 8,
  132167. };
  132168. static float _vq_quantthresh__44c7_s_p1_0[] = {
  132169. -0.5, 0.5,
  132170. };
  132171. static long _vq_quantmap__44c7_s_p1_0[] = {
  132172. 1, 0, 2,
  132173. };
  132174. static encode_aux_threshmatch _vq_auxt__44c7_s_p1_0 = {
  132175. _vq_quantthresh__44c7_s_p1_0,
  132176. _vq_quantmap__44c7_s_p1_0,
  132177. 3,
  132178. 3
  132179. };
  132180. static static_codebook _44c7_s_p1_0 = {
  132181. 4, 81,
  132182. _vq_lengthlist__44c7_s_p1_0,
  132183. 1, -535822336, 1611661312, 2, 0,
  132184. _vq_quantlist__44c7_s_p1_0,
  132185. NULL,
  132186. &_vq_auxt__44c7_s_p1_0,
  132187. NULL,
  132188. 0
  132189. };
  132190. static long _vq_quantlist__44c7_s_p2_0[] = {
  132191. 2,
  132192. 1,
  132193. 3,
  132194. 0,
  132195. 4,
  132196. };
  132197. static long _vq_lengthlist__44c7_s_p2_0[] = {
  132198. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  132199. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  132200. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  132201. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  132202. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  132203. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  132204. 0, 0,14,13, 8, 9, 9,10,11, 0,11,11,12,12, 0,10,
  132205. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  132206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132207. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  132208. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  132209. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  132210. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  132211. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  132212. 13, 8, 9,10,12,12, 0,10,10,12,12, 0,10,10,11,12,
  132213. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  132214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132215. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  132216. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,10,
  132217. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,10,
  132218. 0, 0, 0,10,11, 9,10,10,12,12, 0,10,10,12,12, 0,
  132219. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,13,12, 9,10,
  132220. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  132221. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132223. 7,10,10,14,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  132224. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  132225. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  132226. 12,12, 9,11,11,14,13, 0,11,10,13,12, 0,11,11,13,
  132227. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  132228. 0,10,11,12,13, 0,11,11,13,13, 0,12,12,13,13, 0,
  132229. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  132234. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,12,
  132235. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  132236. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  132237. 13,
  132238. };
  132239. static float _vq_quantthresh__44c7_s_p2_0[] = {
  132240. -1.5, -0.5, 0.5, 1.5,
  132241. };
  132242. static long _vq_quantmap__44c7_s_p2_0[] = {
  132243. 3, 1, 0, 2, 4,
  132244. };
  132245. static encode_aux_threshmatch _vq_auxt__44c7_s_p2_0 = {
  132246. _vq_quantthresh__44c7_s_p2_0,
  132247. _vq_quantmap__44c7_s_p2_0,
  132248. 5,
  132249. 5
  132250. };
  132251. static static_codebook _44c7_s_p2_0 = {
  132252. 4, 625,
  132253. _vq_lengthlist__44c7_s_p2_0,
  132254. 1, -533725184, 1611661312, 3, 0,
  132255. _vq_quantlist__44c7_s_p2_0,
  132256. NULL,
  132257. &_vq_auxt__44c7_s_p2_0,
  132258. NULL,
  132259. 0
  132260. };
  132261. static long _vq_quantlist__44c7_s_p3_0[] = {
  132262. 4,
  132263. 3,
  132264. 5,
  132265. 2,
  132266. 6,
  132267. 1,
  132268. 7,
  132269. 0,
  132270. 8,
  132271. };
  132272. static long _vq_lengthlist__44c7_s_p3_0[] = {
  132273. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  132274. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  132275. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  132276. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  132277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132278. 0,
  132279. };
  132280. static float _vq_quantthresh__44c7_s_p3_0[] = {
  132281. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132282. };
  132283. static long _vq_quantmap__44c7_s_p3_0[] = {
  132284. 7, 5, 3, 1, 0, 2, 4, 6,
  132285. 8,
  132286. };
  132287. static encode_aux_threshmatch _vq_auxt__44c7_s_p3_0 = {
  132288. _vq_quantthresh__44c7_s_p3_0,
  132289. _vq_quantmap__44c7_s_p3_0,
  132290. 9,
  132291. 9
  132292. };
  132293. static static_codebook _44c7_s_p3_0 = {
  132294. 2, 81,
  132295. _vq_lengthlist__44c7_s_p3_0,
  132296. 1, -531628032, 1611661312, 4, 0,
  132297. _vq_quantlist__44c7_s_p3_0,
  132298. NULL,
  132299. &_vq_auxt__44c7_s_p3_0,
  132300. NULL,
  132301. 0
  132302. };
  132303. static long _vq_quantlist__44c7_s_p4_0[] = {
  132304. 8,
  132305. 7,
  132306. 9,
  132307. 6,
  132308. 10,
  132309. 5,
  132310. 11,
  132311. 4,
  132312. 12,
  132313. 3,
  132314. 13,
  132315. 2,
  132316. 14,
  132317. 1,
  132318. 15,
  132319. 0,
  132320. 16,
  132321. };
  132322. static long _vq_lengthlist__44c7_s_p4_0[] = {
  132323. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  132324. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  132325. 12,12, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  132326. 11,12,12, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,
  132327. 11,12,12,12, 0, 0, 0, 6, 6, 8, 7, 9, 9, 9, 9,10,
  132328. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  132329. 11,11,12,12,13,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  132330. 10,11,11,12,12,12,13, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  132331. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  132332. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  132333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132341. 0,
  132342. };
  132343. static float _vq_quantthresh__44c7_s_p4_0[] = {
  132344. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132345. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132346. };
  132347. static long _vq_quantmap__44c7_s_p4_0[] = {
  132348. 15, 13, 11, 9, 7, 5, 3, 1,
  132349. 0, 2, 4, 6, 8, 10, 12, 14,
  132350. 16,
  132351. };
  132352. static encode_aux_threshmatch _vq_auxt__44c7_s_p4_0 = {
  132353. _vq_quantthresh__44c7_s_p4_0,
  132354. _vq_quantmap__44c7_s_p4_0,
  132355. 17,
  132356. 17
  132357. };
  132358. static static_codebook _44c7_s_p4_0 = {
  132359. 2, 289,
  132360. _vq_lengthlist__44c7_s_p4_0,
  132361. 1, -529530880, 1611661312, 5, 0,
  132362. _vq_quantlist__44c7_s_p4_0,
  132363. NULL,
  132364. &_vq_auxt__44c7_s_p4_0,
  132365. NULL,
  132366. 0
  132367. };
  132368. static long _vq_quantlist__44c7_s_p5_0[] = {
  132369. 1,
  132370. 0,
  132371. 2,
  132372. };
  132373. static long _vq_lengthlist__44c7_s_p5_0[] = {
  132374. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 7,10,10,10,10,
  132375. 10, 9, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  132376. 12,10,11,12, 7,10,10,11,12,12,12,12,12, 7,10,10,
  132377. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  132378. 10,10,12,12,12,12,11,12, 7,10,10,11,12,12,12,12,
  132379. 12,
  132380. };
  132381. static float _vq_quantthresh__44c7_s_p5_0[] = {
  132382. -5.5, 5.5,
  132383. };
  132384. static long _vq_quantmap__44c7_s_p5_0[] = {
  132385. 1, 0, 2,
  132386. };
  132387. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_0 = {
  132388. _vq_quantthresh__44c7_s_p5_0,
  132389. _vq_quantmap__44c7_s_p5_0,
  132390. 3,
  132391. 3
  132392. };
  132393. static static_codebook _44c7_s_p5_0 = {
  132394. 4, 81,
  132395. _vq_lengthlist__44c7_s_p5_0,
  132396. 1, -529137664, 1618345984, 2, 0,
  132397. _vq_quantlist__44c7_s_p5_0,
  132398. NULL,
  132399. &_vq_auxt__44c7_s_p5_0,
  132400. NULL,
  132401. 0
  132402. };
  132403. static long _vq_quantlist__44c7_s_p5_1[] = {
  132404. 5,
  132405. 4,
  132406. 6,
  132407. 3,
  132408. 7,
  132409. 2,
  132410. 8,
  132411. 1,
  132412. 9,
  132413. 0,
  132414. 10,
  132415. };
  132416. static long _vq_lengthlist__44c7_s_p5_1[] = {
  132417. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  132418. 7, 7, 8, 8, 9, 9,11, 4, 4, 6, 6, 7, 7, 8, 8, 9,
  132419. 9,12, 5, 5, 6, 6, 7, 7, 9, 9, 9, 9,12,12,12, 6,
  132420. 6, 7, 7, 9, 9, 9, 9,11,11,11, 7, 7, 7, 7, 8, 8,
  132421. 9, 9,11,11,11, 7, 7, 7, 7, 8, 8, 9, 9,11,11,11,
  132422. 7, 7, 8, 8, 8, 8, 9, 9,11,11,11,11,11, 8, 8, 8,
  132423. 8, 8, 9,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  132424. 11,11,11, 7, 7, 8, 8, 8, 8,
  132425. };
  132426. static float _vq_quantthresh__44c7_s_p5_1[] = {
  132427. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132428. 3.5, 4.5,
  132429. };
  132430. static long _vq_quantmap__44c7_s_p5_1[] = {
  132431. 9, 7, 5, 3, 1, 0, 2, 4,
  132432. 6, 8, 10,
  132433. };
  132434. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_1 = {
  132435. _vq_quantthresh__44c7_s_p5_1,
  132436. _vq_quantmap__44c7_s_p5_1,
  132437. 11,
  132438. 11
  132439. };
  132440. static static_codebook _44c7_s_p5_1 = {
  132441. 2, 121,
  132442. _vq_lengthlist__44c7_s_p5_1,
  132443. 1, -531365888, 1611661312, 4, 0,
  132444. _vq_quantlist__44c7_s_p5_1,
  132445. NULL,
  132446. &_vq_auxt__44c7_s_p5_1,
  132447. NULL,
  132448. 0
  132449. };
  132450. static long _vq_quantlist__44c7_s_p6_0[] = {
  132451. 6,
  132452. 5,
  132453. 7,
  132454. 4,
  132455. 8,
  132456. 3,
  132457. 9,
  132458. 2,
  132459. 10,
  132460. 1,
  132461. 11,
  132462. 0,
  132463. 12,
  132464. };
  132465. static long _vq_lengthlist__44c7_s_p6_0[] = {
  132466. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 8,10,10, 6, 5, 5,
  132467. 7, 7, 8, 8, 9, 9, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  132468. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 8, 9, 9,
  132469. 10,10,11,11, 0, 8, 8, 7, 7, 8, 9, 9, 9,10,10,11,
  132470. 11, 0,11,11, 9, 9,10,10,11,10,11,11,12,12, 0,12,
  132471. 12, 9, 9,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0,
  132472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132476. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132477. };
  132478. static float _vq_quantthresh__44c7_s_p6_0[] = {
  132479. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  132480. 12.5, 17.5, 22.5, 27.5,
  132481. };
  132482. static long _vq_quantmap__44c7_s_p6_0[] = {
  132483. 11, 9, 7, 5, 3, 1, 0, 2,
  132484. 4, 6, 8, 10, 12,
  132485. };
  132486. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_0 = {
  132487. _vq_quantthresh__44c7_s_p6_0,
  132488. _vq_quantmap__44c7_s_p6_0,
  132489. 13,
  132490. 13
  132491. };
  132492. static static_codebook _44c7_s_p6_0 = {
  132493. 2, 169,
  132494. _vq_lengthlist__44c7_s_p6_0,
  132495. 1, -526516224, 1616117760, 4, 0,
  132496. _vq_quantlist__44c7_s_p6_0,
  132497. NULL,
  132498. &_vq_auxt__44c7_s_p6_0,
  132499. NULL,
  132500. 0
  132501. };
  132502. static long _vq_quantlist__44c7_s_p6_1[] = {
  132503. 2,
  132504. 1,
  132505. 3,
  132506. 0,
  132507. 4,
  132508. };
  132509. static long _vq_lengthlist__44c7_s_p6_1[] = {
  132510. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  132511. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  132512. };
  132513. static float _vq_quantthresh__44c7_s_p6_1[] = {
  132514. -1.5, -0.5, 0.5, 1.5,
  132515. };
  132516. static long _vq_quantmap__44c7_s_p6_1[] = {
  132517. 3, 1, 0, 2, 4,
  132518. };
  132519. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_1 = {
  132520. _vq_quantthresh__44c7_s_p6_1,
  132521. _vq_quantmap__44c7_s_p6_1,
  132522. 5,
  132523. 5
  132524. };
  132525. static static_codebook _44c7_s_p6_1 = {
  132526. 2, 25,
  132527. _vq_lengthlist__44c7_s_p6_1,
  132528. 1, -533725184, 1611661312, 3, 0,
  132529. _vq_quantlist__44c7_s_p6_1,
  132530. NULL,
  132531. &_vq_auxt__44c7_s_p6_1,
  132532. NULL,
  132533. 0
  132534. };
  132535. static long _vq_quantlist__44c7_s_p7_0[] = {
  132536. 6,
  132537. 5,
  132538. 7,
  132539. 4,
  132540. 8,
  132541. 3,
  132542. 9,
  132543. 2,
  132544. 10,
  132545. 1,
  132546. 11,
  132547. 0,
  132548. 12,
  132549. };
  132550. static long _vq_lengthlist__44c7_s_p7_0[] = {
  132551. 1, 4, 4, 6, 6, 7, 8, 9, 9,10,10,12,11, 6, 5, 5,
  132552. 7, 7, 8, 8, 9,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  132553. 8,10,10,11,11,12,12,20, 7, 7, 7, 7, 8, 9,10,10,
  132554. 11,11,12,13,20, 7, 7, 7, 7, 9, 9,10,10,11,12,13,
  132555. 13,20,11,11, 8, 8, 9, 9,11,11,12,12,13,13,20,11,
  132556. 11, 8, 8, 9, 9,11,11,12,12,13,13,20,20,20,10,10,
  132557. 10,10,12,12,13,13,13,13,20,20,20,10,10,10,10,12,
  132558. 12,13,13,13,14,20,20,20,14,14,11,11,12,12,13,13,
  132559. 14,14,20,20,20,14,14,11,11,12,12,13,13,14,14,20,
  132560. 20,20,20,19,13,13,13,13,14,14,15,14,19,19,19,19,
  132561. 19,13,13,13,13,14,14,15,15,
  132562. };
  132563. static float _vq_quantthresh__44c7_s_p7_0[] = {
  132564. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  132565. 27.5, 38.5, 49.5, 60.5,
  132566. };
  132567. static long _vq_quantmap__44c7_s_p7_0[] = {
  132568. 11, 9, 7, 5, 3, 1, 0, 2,
  132569. 4, 6, 8, 10, 12,
  132570. };
  132571. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_0 = {
  132572. _vq_quantthresh__44c7_s_p7_0,
  132573. _vq_quantmap__44c7_s_p7_0,
  132574. 13,
  132575. 13
  132576. };
  132577. static static_codebook _44c7_s_p7_0 = {
  132578. 2, 169,
  132579. _vq_lengthlist__44c7_s_p7_0,
  132580. 1, -523206656, 1618345984, 4, 0,
  132581. _vq_quantlist__44c7_s_p7_0,
  132582. NULL,
  132583. &_vq_auxt__44c7_s_p7_0,
  132584. NULL,
  132585. 0
  132586. };
  132587. static long _vq_quantlist__44c7_s_p7_1[] = {
  132588. 5,
  132589. 4,
  132590. 6,
  132591. 3,
  132592. 7,
  132593. 2,
  132594. 8,
  132595. 1,
  132596. 9,
  132597. 0,
  132598. 10,
  132599. };
  132600. static long _vq_lengthlist__44c7_s_p7_1[] = {
  132601. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 7, 7,
  132602. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  132603. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  132604. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  132605. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  132606. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  132607. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  132608. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  132609. };
  132610. static float _vq_quantthresh__44c7_s_p7_1[] = {
  132611. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132612. 3.5, 4.5,
  132613. };
  132614. static long _vq_quantmap__44c7_s_p7_1[] = {
  132615. 9, 7, 5, 3, 1, 0, 2, 4,
  132616. 6, 8, 10,
  132617. };
  132618. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_1 = {
  132619. _vq_quantthresh__44c7_s_p7_1,
  132620. _vq_quantmap__44c7_s_p7_1,
  132621. 11,
  132622. 11
  132623. };
  132624. static static_codebook _44c7_s_p7_1 = {
  132625. 2, 121,
  132626. _vq_lengthlist__44c7_s_p7_1,
  132627. 1, -531365888, 1611661312, 4, 0,
  132628. _vq_quantlist__44c7_s_p7_1,
  132629. NULL,
  132630. &_vq_auxt__44c7_s_p7_1,
  132631. NULL,
  132632. 0
  132633. };
  132634. static long _vq_quantlist__44c7_s_p8_0[] = {
  132635. 7,
  132636. 6,
  132637. 8,
  132638. 5,
  132639. 9,
  132640. 4,
  132641. 10,
  132642. 3,
  132643. 11,
  132644. 2,
  132645. 12,
  132646. 1,
  132647. 13,
  132648. 0,
  132649. 14,
  132650. };
  132651. static long _vq_lengthlist__44c7_s_p8_0[] = {
  132652. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8, 9, 9,10,10, 6,
  132653. 5, 5, 7, 7, 9, 9, 8, 8,10, 9,11,10,12,11, 6, 5,
  132654. 5, 8, 7, 9, 9, 8, 8,10,10,11,11,12,11,19, 8, 8,
  132655. 8, 8,10,10, 9, 9,10,10,11,11,12,11,19, 8, 8, 8,
  132656. 8,10,10, 9, 9,10,10,11,11,12,12,19,12,12, 9, 9,
  132657. 10,10, 9,10,10,10,11,11,12,12,19,12,12, 9, 9,10,
  132658. 10,10,10,10,10,12,12,12,12,19,19,19, 9, 9, 9, 9,
  132659. 11,10,11,11,12,11,13,13,19,19,19, 9, 9, 9, 9,11,
  132660. 10,11,11,11,12,13,13,19,19,19,13,13,10,10,11,11,
  132661. 12,12,12,12,13,12,19,19,19,14,13,10,10,11,11,12,
  132662. 12,12,13,13,13,19,19,19,19,19,12,12,12,11,12,13,
  132663. 14,13,13,13,19,19,19,19,19,12,12,12,11,12,12,13,
  132664. 14,13,14,19,19,19,19,19,16,16,12,13,12,13,13,14,
  132665. 15,14,19,18,18,18,18,16,15,12,11,12,11,14,12,14,
  132666. 14,
  132667. };
  132668. static float _vq_quantthresh__44c7_s_p8_0[] = {
  132669. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  132670. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  132671. };
  132672. static long _vq_quantmap__44c7_s_p8_0[] = {
  132673. 13, 11, 9, 7, 5, 3, 1, 0,
  132674. 2, 4, 6, 8, 10, 12, 14,
  132675. };
  132676. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_0 = {
  132677. _vq_quantthresh__44c7_s_p8_0,
  132678. _vq_quantmap__44c7_s_p8_0,
  132679. 15,
  132680. 15
  132681. };
  132682. static static_codebook _44c7_s_p8_0 = {
  132683. 2, 225,
  132684. _vq_lengthlist__44c7_s_p8_0,
  132685. 1, -520986624, 1620377600, 4, 0,
  132686. _vq_quantlist__44c7_s_p8_0,
  132687. NULL,
  132688. &_vq_auxt__44c7_s_p8_0,
  132689. NULL,
  132690. 0
  132691. };
  132692. static long _vq_quantlist__44c7_s_p8_1[] = {
  132693. 10,
  132694. 9,
  132695. 11,
  132696. 8,
  132697. 12,
  132698. 7,
  132699. 13,
  132700. 6,
  132701. 14,
  132702. 5,
  132703. 15,
  132704. 4,
  132705. 16,
  132706. 3,
  132707. 17,
  132708. 2,
  132709. 18,
  132710. 1,
  132711. 19,
  132712. 0,
  132713. 20,
  132714. };
  132715. static long _vq_lengthlist__44c7_s_p8_1[] = {
  132716. 3, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  132717. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  132718. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  132719. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  132720. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132721. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  132722. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  132723. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  132724. 10, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132725. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132726. 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,10,10, 9, 9, 9,
  132727. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9, 9,10,11,10,
  132728. 11,10, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9, 9,
  132729. 9, 9,11,10,11,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,
  132730. 10, 9, 9,10, 9, 9,10,11,10,10,11,10, 9, 9, 9, 9,
  132731. 9,10,10, 9,10,10,10,10, 9,10,10,10,10,10,10,11,
  132732. 11,11,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  132733. 10,10,10,11,11,10,10,10,10,10,10,10,10,10,10,10,
  132734. 10, 9,10,10, 9,10,11,11,10,11,10,11,10, 9,10,10,
  132735. 9,10,10,10,10,10,10,10,10,10,10,11,11,11,11,10,
  132736. 11,11,10,10,10,10,10,10, 9,10, 9,10,10, 9,10, 9,
  132737. 10,10,10,11,10,11,10,11,11,10,10,10,10,10,10, 9,
  132738. 10,10,10,10,10,10,10,11,10,10,10,10,10,10,10,10,
  132739. 10,10,10,10,10,10,10,10,10,10,10,10,10,11,10,11,
  132740. 11,10,10,10,10, 9, 9,10,10, 9, 9,10, 9,10,10,10,
  132741. 10,11,11,10,10,10,10,10,10,10, 9, 9,10,10,10, 9,
  132742. 9,10,10,10,10,10,11,10,11,10,10,10,10,10,10, 9,
  132743. 10,10,10,10,10,10,10,10,10,
  132744. };
  132745. static float _vq_quantthresh__44c7_s_p8_1[] = {
  132746. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  132747. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  132748. 6.5, 7.5, 8.5, 9.5,
  132749. };
  132750. static long _vq_quantmap__44c7_s_p8_1[] = {
  132751. 19, 17, 15, 13, 11, 9, 7, 5,
  132752. 3, 1, 0, 2, 4, 6, 8, 10,
  132753. 12, 14, 16, 18, 20,
  132754. };
  132755. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_1 = {
  132756. _vq_quantthresh__44c7_s_p8_1,
  132757. _vq_quantmap__44c7_s_p8_1,
  132758. 21,
  132759. 21
  132760. };
  132761. static static_codebook _44c7_s_p8_1 = {
  132762. 2, 441,
  132763. _vq_lengthlist__44c7_s_p8_1,
  132764. 1, -529268736, 1611661312, 5, 0,
  132765. _vq_quantlist__44c7_s_p8_1,
  132766. NULL,
  132767. &_vq_auxt__44c7_s_p8_1,
  132768. NULL,
  132769. 0
  132770. };
  132771. static long _vq_quantlist__44c7_s_p9_0[] = {
  132772. 6,
  132773. 5,
  132774. 7,
  132775. 4,
  132776. 8,
  132777. 3,
  132778. 9,
  132779. 2,
  132780. 10,
  132781. 1,
  132782. 11,
  132783. 0,
  132784. 12,
  132785. };
  132786. static long _vq_lengthlist__44c7_s_p9_0[] = {
  132787. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 6, 6,
  132788. 11,11,11,11,11,11,11,11,11,11, 4, 7, 7,11,11,11,
  132789. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132790. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132791. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132792. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132793. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132794. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132795. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132796. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132797. 11,11,11,11,11,11,11,11,11,
  132798. };
  132799. static float _vq_quantthresh__44c7_s_p9_0[] = {
  132800. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  132801. 1592.5, 2229.5, 2866.5, 3503.5,
  132802. };
  132803. static long _vq_quantmap__44c7_s_p9_0[] = {
  132804. 11, 9, 7, 5, 3, 1, 0, 2,
  132805. 4, 6, 8, 10, 12,
  132806. };
  132807. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_0 = {
  132808. _vq_quantthresh__44c7_s_p9_0,
  132809. _vq_quantmap__44c7_s_p9_0,
  132810. 13,
  132811. 13
  132812. };
  132813. static static_codebook _44c7_s_p9_0 = {
  132814. 2, 169,
  132815. _vq_lengthlist__44c7_s_p9_0,
  132816. 1, -511845376, 1630791680, 4, 0,
  132817. _vq_quantlist__44c7_s_p9_0,
  132818. NULL,
  132819. &_vq_auxt__44c7_s_p9_0,
  132820. NULL,
  132821. 0
  132822. };
  132823. static long _vq_quantlist__44c7_s_p9_1[] = {
  132824. 6,
  132825. 5,
  132826. 7,
  132827. 4,
  132828. 8,
  132829. 3,
  132830. 9,
  132831. 2,
  132832. 10,
  132833. 1,
  132834. 11,
  132835. 0,
  132836. 12,
  132837. };
  132838. static long _vq_lengthlist__44c7_s_p9_1[] = {
  132839. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  132840. 8, 8, 9, 8, 8, 7, 9, 8,11,10, 5, 6, 6, 8, 8, 9,
  132841. 8, 8, 8,10, 9,11,11,16, 8, 8, 9, 8, 9, 9, 9, 8,
  132842. 10, 9,11,10,16, 8, 8, 9, 9,10,10, 9, 9,10,10,11,
  132843. 11,16,13,13, 9, 9,10,10, 9,10,11,11,12,11,16,13,
  132844. 13, 9, 8,10, 9,10,10,10,10,11,11,16,14,16, 8, 9,
  132845. 9, 9,11,10,11,11,12,11,16,16,16, 9, 7,10, 7,11,
  132846. 10,11,11,12,11,16,16,16,12,12, 9,10,11,11,12,11,
  132847. 12,12,16,16,16,12,10,10, 7,11, 8,12,11,12,12,16,
  132848. 16,15,16,16,11,12,10,10,12,11,12,12,16,16,16,15,
  132849. 15,11,11,10,10,12,12,12,12,
  132850. };
  132851. static float _vq_quantthresh__44c7_s_p9_1[] = {
  132852. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  132853. 122.5, 171.5, 220.5, 269.5,
  132854. };
  132855. static long _vq_quantmap__44c7_s_p9_1[] = {
  132856. 11, 9, 7, 5, 3, 1, 0, 2,
  132857. 4, 6, 8, 10, 12,
  132858. };
  132859. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_1 = {
  132860. _vq_quantthresh__44c7_s_p9_1,
  132861. _vq_quantmap__44c7_s_p9_1,
  132862. 13,
  132863. 13
  132864. };
  132865. static static_codebook _44c7_s_p9_1 = {
  132866. 2, 169,
  132867. _vq_lengthlist__44c7_s_p9_1,
  132868. 1, -518889472, 1622704128, 4, 0,
  132869. _vq_quantlist__44c7_s_p9_1,
  132870. NULL,
  132871. &_vq_auxt__44c7_s_p9_1,
  132872. NULL,
  132873. 0
  132874. };
  132875. static long _vq_quantlist__44c7_s_p9_2[] = {
  132876. 24,
  132877. 23,
  132878. 25,
  132879. 22,
  132880. 26,
  132881. 21,
  132882. 27,
  132883. 20,
  132884. 28,
  132885. 19,
  132886. 29,
  132887. 18,
  132888. 30,
  132889. 17,
  132890. 31,
  132891. 16,
  132892. 32,
  132893. 15,
  132894. 33,
  132895. 14,
  132896. 34,
  132897. 13,
  132898. 35,
  132899. 12,
  132900. 36,
  132901. 11,
  132902. 37,
  132903. 10,
  132904. 38,
  132905. 9,
  132906. 39,
  132907. 8,
  132908. 40,
  132909. 7,
  132910. 41,
  132911. 6,
  132912. 42,
  132913. 5,
  132914. 43,
  132915. 4,
  132916. 44,
  132917. 3,
  132918. 45,
  132919. 2,
  132920. 46,
  132921. 1,
  132922. 47,
  132923. 0,
  132924. 48,
  132925. };
  132926. static long _vq_lengthlist__44c7_s_p9_2[] = {
  132927. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  132928. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  132929. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  132930. 7,
  132931. };
  132932. static float _vq_quantthresh__44c7_s_p9_2[] = {
  132933. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  132934. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  132935. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132936. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132937. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  132938. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  132939. };
  132940. static long _vq_quantmap__44c7_s_p9_2[] = {
  132941. 47, 45, 43, 41, 39, 37, 35, 33,
  132942. 31, 29, 27, 25, 23, 21, 19, 17,
  132943. 15, 13, 11, 9, 7, 5, 3, 1,
  132944. 0, 2, 4, 6, 8, 10, 12, 14,
  132945. 16, 18, 20, 22, 24, 26, 28, 30,
  132946. 32, 34, 36, 38, 40, 42, 44, 46,
  132947. 48,
  132948. };
  132949. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_2 = {
  132950. _vq_quantthresh__44c7_s_p9_2,
  132951. _vq_quantmap__44c7_s_p9_2,
  132952. 49,
  132953. 49
  132954. };
  132955. static static_codebook _44c7_s_p9_2 = {
  132956. 1, 49,
  132957. _vq_lengthlist__44c7_s_p9_2,
  132958. 1, -526909440, 1611661312, 6, 0,
  132959. _vq_quantlist__44c7_s_p9_2,
  132960. NULL,
  132961. &_vq_auxt__44c7_s_p9_2,
  132962. NULL,
  132963. 0
  132964. };
  132965. static long _huff_lengthlist__44c7_s_short[] = {
  132966. 4,11,12,14,15,15,17,17,18,18, 5, 6, 6, 8, 9,10,
  132967. 13,17,18,19, 7, 5, 4, 6, 8, 9,11,15,19,19, 8, 6,
  132968. 5, 5, 6, 7,11,14,16,17, 9, 7, 7, 6, 7, 7,10,13,
  132969. 15,19,10, 8, 7, 6, 7, 6, 7, 9,14,16,12,10, 9, 7,
  132970. 7, 6, 4, 5,10,15,14,13,11, 7, 6, 6, 4, 2, 7,13,
  132971. 16,16,15, 9, 8, 8, 8, 6, 9,13,19,19,17,12,11,10,
  132972. 10, 9,11,14,
  132973. };
  132974. static static_codebook _huff_book__44c7_s_short = {
  132975. 2, 100,
  132976. _huff_lengthlist__44c7_s_short,
  132977. 0, 0, 0, 0, 0,
  132978. NULL,
  132979. NULL,
  132980. NULL,
  132981. NULL,
  132982. 0
  132983. };
  132984. static long _huff_lengthlist__44c8_s_long[] = {
  132985. 3, 8,12,13,14,14,14,13,14,14, 6, 4, 5, 8,10,10,
  132986. 11,11,14,13, 9, 5, 4, 5, 7, 8, 9,10,13,13,12, 7,
  132987. 5, 4, 5, 6, 8, 9,12,13,13, 9, 6, 5, 5, 5, 7, 9,
  132988. 11,14,12,10, 7, 6, 5, 4, 6, 7,10,11,12,11, 9, 8,
  132989. 7, 5, 5, 6,10,10,13,12,10, 9, 8, 6, 6, 5, 8,10,
  132990. 14,13,12,12,11,10, 9, 7, 8,10,12,13,14,14,13,12,
  132991. 11, 9, 9,10,
  132992. };
  132993. static static_codebook _huff_book__44c8_s_long = {
  132994. 2, 100,
  132995. _huff_lengthlist__44c8_s_long,
  132996. 0, 0, 0, 0, 0,
  132997. NULL,
  132998. NULL,
  132999. NULL,
  133000. NULL,
  133001. 0
  133002. };
  133003. static long _vq_quantlist__44c8_s_p1_0[] = {
  133004. 1,
  133005. 0,
  133006. 2,
  133007. };
  133008. static long _vq_lengthlist__44c8_s_p1_0[] = {
  133009. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 7, 7, 0, 9, 8, 0,
  133010. 9, 8, 6, 7, 7, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  133011. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  133012. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  133013. 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  133014. 8,
  133015. };
  133016. static float _vq_quantthresh__44c8_s_p1_0[] = {
  133017. -0.5, 0.5,
  133018. };
  133019. static long _vq_quantmap__44c8_s_p1_0[] = {
  133020. 1, 0, 2,
  133021. };
  133022. static encode_aux_threshmatch _vq_auxt__44c8_s_p1_0 = {
  133023. _vq_quantthresh__44c8_s_p1_0,
  133024. _vq_quantmap__44c8_s_p1_0,
  133025. 3,
  133026. 3
  133027. };
  133028. static static_codebook _44c8_s_p1_0 = {
  133029. 4, 81,
  133030. _vq_lengthlist__44c8_s_p1_0,
  133031. 1, -535822336, 1611661312, 2, 0,
  133032. _vq_quantlist__44c8_s_p1_0,
  133033. NULL,
  133034. &_vq_auxt__44c8_s_p1_0,
  133035. NULL,
  133036. 0
  133037. };
  133038. static long _vq_quantlist__44c8_s_p2_0[] = {
  133039. 2,
  133040. 1,
  133041. 3,
  133042. 0,
  133043. 4,
  133044. };
  133045. static long _vq_lengthlist__44c8_s_p2_0[] = {
  133046. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  133047. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  133048. 7,10, 9, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  133049. 11,11, 5, 7, 7, 9, 9, 0, 7, 8, 9,10, 0, 7, 8, 9,
  133050. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  133051. 0,11,10,12,11, 0,11,10,12,12, 0,13,13,14,14, 0,
  133052. 0, 0,14,13, 8, 9, 9,10,11, 0,10,11,12,12, 0,10,
  133053. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  133054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133055. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  133056. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,11,10, 5,
  133057. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  133058. 9,10,10, 0, 0, 0,10,10, 8,10, 9,12,12, 0,10,10,
  133059. 12,11, 0,10,10,12,12, 0,12,12,13,12, 0, 0, 0,13,
  133060. 12, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,11,12,
  133061. 0,12,12,13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0,
  133062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133063. 0, 0, 0, 6, 8, 7,11,10, 0, 7, 7,10,10, 0, 7, 7,
  133064. 10,10, 0, 9, 9,10,11, 0, 0, 0,10,10, 6, 7, 8,10,
  133065. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,10,10,
  133066. 0, 0, 0,10,10, 9,10, 9,12,12, 0,10,10,12,12, 0,
  133067. 10,10,12,11, 0,12,12,13,13, 0, 0, 0,13,12, 8, 9,
  133068. 10,12,12, 0,10,10,12,12, 0,10,10,11,12, 0,12,12,
  133069. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133071. 7,10,10,13,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  133072. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,13, 0, 9,
  133073. 9,12,12, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  133074. 12,12, 9,11,11,14,13, 0,10,10,13,12, 0,11,10,13,
  133075. 12, 0,12,12,13,12, 0, 0, 0,13,13, 9,11,11,13,14,
  133076. 0,10,11,12,13, 0,10,11,13,13, 0,12,12,12,13, 0,
  133077. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  133082. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,11,
  133083. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  133084. 13,13, 0,10,11,13,13, 0,12,12,13,13, 0, 0, 0,12,
  133085. 13,
  133086. };
  133087. static float _vq_quantthresh__44c8_s_p2_0[] = {
  133088. -1.5, -0.5, 0.5, 1.5,
  133089. };
  133090. static long _vq_quantmap__44c8_s_p2_0[] = {
  133091. 3, 1, 0, 2, 4,
  133092. };
  133093. static encode_aux_threshmatch _vq_auxt__44c8_s_p2_0 = {
  133094. _vq_quantthresh__44c8_s_p2_0,
  133095. _vq_quantmap__44c8_s_p2_0,
  133096. 5,
  133097. 5
  133098. };
  133099. static static_codebook _44c8_s_p2_0 = {
  133100. 4, 625,
  133101. _vq_lengthlist__44c8_s_p2_0,
  133102. 1, -533725184, 1611661312, 3, 0,
  133103. _vq_quantlist__44c8_s_p2_0,
  133104. NULL,
  133105. &_vq_auxt__44c8_s_p2_0,
  133106. NULL,
  133107. 0
  133108. };
  133109. static long _vq_quantlist__44c8_s_p3_0[] = {
  133110. 4,
  133111. 3,
  133112. 5,
  133113. 2,
  133114. 6,
  133115. 1,
  133116. 7,
  133117. 0,
  133118. 8,
  133119. };
  133120. static long _vq_lengthlist__44c8_s_p3_0[] = {
  133121. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  133122. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  133123. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  133124. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  133125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133126. 0,
  133127. };
  133128. static float _vq_quantthresh__44c8_s_p3_0[] = {
  133129. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  133130. };
  133131. static long _vq_quantmap__44c8_s_p3_0[] = {
  133132. 7, 5, 3, 1, 0, 2, 4, 6,
  133133. 8,
  133134. };
  133135. static encode_aux_threshmatch _vq_auxt__44c8_s_p3_0 = {
  133136. _vq_quantthresh__44c8_s_p3_0,
  133137. _vq_quantmap__44c8_s_p3_0,
  133138. 9,
  133139. 9
  133140. };
  133141. static static_codebook _44c8_s_p3_0 = {
  133142. 2, 81,
  133143. _vq_lengthlist__44c8_s_p3_0,
  133144. 1, -531628032, 1611661312, 4, 0,
  133145. _vq_quantlist__44c8_s_p3_0,
  133146. NULL,
  133147. &_vq_auxt__44c8_s_p3_0,
  133148. NULL,
  133149. 0
  133150. };
  133151. static long _vq_quantlist__44c8_s_p4_0[] = {
  133152. 8,
  133153. 7,
  133154. 9,
  133155. 6,
  133156. 10,
  133157. 5,
  133158. 11,
  133159. 4,
  133160. 12,
  133161. 3,
  133162. 13,
  133163. 2,
  133164. 14,
  133165. 1,
  133166. 15,
  133167. 0,
  133168. 16,
  133169. };
  133170. static long _vq_lengthlist__44c8_s_p4_0[] = {
  133171. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  133172. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 8,10,10,11,11,
  133173. 11,11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  133174. 11,11,11, 0, 6, 5, 6, 6, 7, 7, 9, 9, 9, 9,10,10,
  133175. 11,11,12,12, 0, 0, 0, 6, 6, 7, 7, 9, 9, 9, 9,10,
  133176. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  133177. 11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  133178. 10,11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  133179. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  133180. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  133181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133189. 0,
  133190. };
  133191. static float _vq_quantthresh__44c8_s_p4_0[] = {
  133192. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133193. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133194. };
  133195. static long _vq_quantmap__44c8_s_p4_0[] = {
  133196. 15, 13, 11, 9, 7, 5, 3, 1,
  133197. 0, 2, 4, 6, 8, 10, 12, 14,
  133198. 16,
  133199. };
  133200. static encode_aux_threshmatch _vq_auxt__44c8_s_p4_0 = {
  133201. _vq_quantthresh__44c8_s_p4_0,
  133202. _vq_quantmap__44c8_s_p4_0,
  133203. 17,
  133204. 17
  133205. };
  133206. static static_codebook _44c8_s_p4_0 = {
  133207. 2, 289,
  133208. _vq_lengthlist__44c8_s_p4_0,
  133209. 1, -529530880, 1611661312, 5, 0,
  133210. _vq_quantlist__44c8_s_p4_0,
  133211. NULL,
  133212. &_vq_auxt__44c8_s_p4_0,
  133213. NULL,
  133214. 0
  133215. };
  133216. static long _vq_quantlist__44c8_s_p5_0[] = {
  133217. 1,
  133218. 0,
  133219. 2,
  133220. };
  133221. static long _vq_lengthlist__44c8_s_p5_0[] = {
  133222. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6,10,10,10,10,
  133223. 10,10, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  133224. 11,10,11,11, 7,10,10,11,12,12,12,12,12, 7,10,10,
  133225. 11,12,12,12,12,12, 6,10,10,10,12,12,10,12,12, 7,
  133226. 10,10,11,12,12,12,12,12, 7,10,10,11,12,12,12,12,
  133227. 12,
  133228. };
  133229. static float _vq_quantthresh__44c8_s_p5_0[] = {
  133230. -5.5, 5.5,
  133231. };
  133232. static long _vq_quantmap__44c8_s_p5_0[] = {
  133233. 1, 0, 2,
  133234. };
  133235. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_0 = {
  133236. _vq_quantthresh__44c8_s_p5_0,
  133237. _vq_quantmap__44c8_s_p5_0,
  133238. 3,
  133239. 3
  133240. };
  133241. static static_codebook _44c8_s_p5_0 = {
  133242. 4, 81,
  133243. _vq_lengthlist__44c8_s_p5_0,
  133244. 1, -529137664, 1618345984, 2, 0,
  133245. _vq_quantlist__44c8_s_p5_0,
  133246. NULL,
  133247. &_vq_auxt__44c8_s_p5_0,
  133248. NULL,
  133249. 0
  133250. };
  133251. static long _vq_quantlist__44c8_s_p5_1[] = {
  133252. 5,
  133253. 4,
  133254. 6,
  133255. 3,
  133256. 7,
  133257. 2,
  133258. 8,
  133259. 1,
  133260. 9,
  133261. 0,
  133262. 10,
  133263. };
  133264. static long _vq_lengthlist__44c8_s_p5_1[] = {
  133265. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 5, 6, 6,
  133266. 7, 7, 8, 8, 8, 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  133267. 9,12, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,12,12,12, 6,
  133268. 6, 7, 7, 8, 8, 9, 9,11,11,11, 6, 6, 7, 7, 8, 8,
  133269. 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11,
  133270. 7, 7, 7, 8, 8, 8, 8, 8,11,11,11,11,11, 7, 7, 8,
  133271. 8, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 8, 8,11,11,
  133272. 11,11,11, 7, 7, 7, 7, 8, 8,
  133273. };
  133274. static float _vq_quantthresh__44c8_s_p5_1[] = {
  133275. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133276. 3.5, 4.5,
  133277. };
  133278. static long _vq_quantmap__44c8_s_p5_1[] = {
  133279. 9, 7, 5, 3, 1, 0, 2, 4,
  133280. 6, 8, 10,
  133281. };
  133282. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_1 = {
  133283. _vq_quantthresh__44c8_s_p5_1,
  133284. _vq_quantmap__44c8_s_p5_1,
  133285. 11,
  133286. 11
  133287. };
  133288. static static_codebook _44c8_s_p5_1 = {
  133289. 2, 121,
  133290. _vq_lengthlist__44c8_s_p5_1,
  133291. 1, -531365888, 1611661312, 4, 0,
  133292. _vq_quantlist__44c8_s_p5_1,
  133293. NULL,
  133294. &_vq_auxt__44c8_s_p5_1,
  133295. NULL,
  133296. 0
  133297. };
  133298. static long _vq_quantlist__44c8_s_p6_0[] = {
  133299. 6,
  133300. 5,
  133301. 7,
  133302. 4,
  133303. 8,
  133304. 3,
  133305. 9,
  133306. 2,
  133307. 10,
  133308. 1,
  133309. 11,
  133310. 0,
  133311. 12,
  133312. };
  133313. static long _vq_lengthlist__44c8_s_p6_0[] = {
  133314. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  133315. 7, 7, 8, 8, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 8,
  133316. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,
  133317. 10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,10,10,11,
  133318. 11, 0,11,11, 9, 9,10,10,11,11,11,11,12,12, 0,12,
  133319. 12, 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  133320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133324. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133325. };
  133326. static float _vq_quantthresh__44c8_s_p6_0[] = {
  133327. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  133328. 12.5, 17.5, 22.5, 27.5,
  133329. };
  133330. static long _vq_quantmap__44c8_s_p6_0[] = {
  133331. 11, 9, 7, 5, 3, 1, 0, 2,
  133332. 4, 6, 8, 10, 12,
  133333. };
  133334. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_0 = {
  133335. _vq_quantthresh__44c8_s_p6_0,
  133336. _vq_quantmap__44c8_s_p6_0,
  133337. 13,
  133338. 13
  133339. };
  133340. static static_codebook _44c8_s_p6_0 = {
  133341. 2, 169,
  133342. _vq_lengthlist__44c8_s_p6_0,
  133343. 1, -526516224, 1616117760, 4, 0,
  133344. _vq_quantlist__44c8_s_p6_0,
  133345. NULL,
  133346. &_vq_auxt__44c8_s_p6_0,
  133347. NULL,
  133348. 0
  133349. };
  133350. static long _vq_quantlist__44c8_s_p6_1[] = {
  133351. 2,
  133352. 1,
  133353. 3,
  133354. 0,
  133355. 4,
  133356. };
  133357. static long _vq_lengthlist__44c8_s_p6_1[] = {
  133358. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  133359. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  133360. };
  133361. static float _vq_quantthresh__44c8_s_p6_1[] = {
  133362. -1.5, -0.5, 0.5, 1.5,
  133363. };
  133364. static long _vq_quantmap__44c8_s_p6_1[] = {
  133365. 3, 1, 0, 2, 4,
  133366. };
  133367. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_1 = {
  133368. _vq_quantthresh__44c8_s_p6_1,
  133369. _vq_quantmap__44c8_s_p6_1,
  133370. 5,
  133371. 5
  133372. };
  133373. static static_codebook _44c8_s_p6_1 = {
  133374. 2, 25,
  133375. _vq_lengthlist__44c8_s_p6_1,
  133376. 1, -533725184, 1611661312, 3, 0,
  133377. _vq_quantlist__44c8_s_p6_1,
  133378. NULL,
  133379. &_vq_auxt__44c8_s_p6_1,
  133380. NULL,
  133381. 0
  133382. };
  133383. static long _vq_quantlist__44c8_s_p7_0[] = {
  133384. 6,
  133385. 5,
  133386. 7,
  133387. 4,
  133388. 8,
  133389. 3,
  133390. 9,
  133391. 2,
  133392. 10,
  133393. 1,
  133394. 11,
  133395. 0,
  133396. 12,
  133397. };
  133398. static long _vq_lengthlist__44c8_s_p7_0[] = {
  133399. 1, 4, 4, 6, 6, 8, 7, 9, 9,10,10,12,12, 6, 5, 5,
  133400. 7, 7, 8, 8,10,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  133401. 8,10,10,11,11,12,12,21, 7, 7, 7, 7, 8, 9,10,10,
  133402. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,12,12,13,
  133403. 13,21,11,11, 8, 8, 9, 9,11,11,12,12,13,13,21,11,
  133404. 11, 8, 8, 9, 9,11,11,12,12,13,13,21,21,21,10,10,
  133405. 10,10,11,11,12,13,13,13,21,21,21,10,10,10,10,11,
  133406. 11,13,13,14,13,21,21,21,13,13,11,11,12,12,13,13,
  133407. 14,14,21,21,21,14,14,11,11,12,12,13,13,14,14,21,
  133408. 21,21,21,20,13,13,13,12,14,14,16,15,20,20,20,20,
  133409. 20,13,13,13,13,14,13,15,15,
  133410. };
  133411. static float _vq_quantthresh__44c8_s_p7_0[] = {
  133412. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  133413. 27.5, 38.5, 49.5, 60.5,
  133414. };
  133415. static long _vq_quantmap__44c8_s_p7_0[] = {
  133416. 11, 9, 7, 5, 3, 1, 0, 2,
  133417. 4, 6, 8, 10, 12,
  133418. };
  133419. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_0 = {
  133420. _vq_quantthresh__44c8_s_p7_0,
  133421. _vq_quantmap__44c8_s_p7_0,
  133422. 13,
  133423. 13
  133424. };
  133425. static static_codebook _44c8_s_p7_0 = {
  133426. 2, 169,
  133427. _vq_lengthlist__44c8_s_p7_0,
  133428. 1, -523206656, 1618345984, 4, 0,
  133429. _vq_quantlist__44c8_s_p7_0,
  133430. NULL,
  133431. &_vq_auxt__44c8_s_p7_0,
  133432. NULL,
  133433. 0
  133434. };
  133435. static long _vq_quantlist__44c8_s_p7_1[] = {
  133436. 5,
  133437. 4,
  133438. 6,
  133439. 3,
  133440. 7,
  133441. 2,
  133442. 8,
  133443. 1,
  133444. 9,
  133445. 0,
  133446. 10,
  133447. };
  133448. static long _vq_lengthlist__44c8_s_p7_1[] = {
  133449. 4, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7,
  133450. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  133451. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  133452. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  133453. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  133454. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  133455. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  133456. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  133457. };
  133458. static float _vq_quantthresh__44c8_s_p7_1[] = {
  133459. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133460. 3.5, 4.5,
  133461. };
  133462. static long _vq_quantmap__44c8_s_p7_1[] = {
  133463. 9, 7, 5, 3, 1, 0, 2, 4,
  133464. 6, 8, 10,
  133465. };
  133466. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_1 = {
  133467. _vq_quantthresh__44c8_s_p7_1,
  133468. _vq_quantmap__44c8_s_p7_1,
  133469. 11,
  133470. 11
  133471. };
  133472. static static_codebook _44c8_s_p7_1 = {
  133473. 2, 121,
  133474. _vq_lengthlist__44c8_s_p7_1,
  133475. 1, -531365888, 1611661312, 4, 0,
  133476. _vq_quantlist__44c8_s_p7_1,
  133477. NULL,
  133478. &_vq_auxt__44c8_s_p7_1,
  133479. NULL,
  133480. 0
  133481. };
  133482. static long _vq_quantlist__44c8_s_p8_0[] = {
  133483. 7,
  133484. 6,
  133485. 8,
  133486. 5,
  133487. 9,
  133488. 4,
  133489. 10,
  133490. 3,
  133491. 11,
  133492. 2,
  133493. 12,
  133494. 1,
  133495. 13,
  133496. 0,
  133497. 14,
  133498. };
  133499. static long _vq_lengthlist__44c8_s_p8_0[] = {
  133500. 1, 4, 4, 7, 6, 8, 8, 8, 7, 9, 8,10,10,11,10, 6,
  133501. 5, 5, 7, 7, 9, 9, 8, 8,10,10,11,11,12,11, 6, 5,
  133502. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8,
  133503. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8, 8,
  133504. 8,10, 9, 9, 9,10,10,11,11,12,12,20,12,12, 9, 9,
  133505. 10,10,10,10,10,11,12,12,12,12,20,12,12, 9, 9,10,
  133506. 10,10,10,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,
  133507. 11,10,11,11,12,12,12,13,20,19,19, 9, 9, 9, 9,11,
  133508. 11,11,12,12,12,13,13,19,19,19,13,13,10,10,11,11,
  133509. 12,12,13,13,13,13,19,19,19,14,13,11,10,11,11,12,
  133510. 12,12,13,13,13,19,19,19,19,19,12,12,12,12,13,13,
  133511. 13,13,14,13,19,19,19,19,19,12,12,12,11,12,12,13,
  133512. 14,14,14,19,19,19,19,19,16,15,13,12,13,13,13,14,
  133513. 14,14,19,19,19,19,19,17,17,13,12,13,11,14,13,15,
  133514. 15,
  133515. };
  133516. static float _vq_quantthresh__44c8_s_p8_0[] = {
  133517. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  133518. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  133519. };
  133520. static long _vq_quantmap__44c8_s_p8_0[] = {
  133521. 13, 11, 9, 7, 5, 3, 1, 0,
  133522. 2, 4, 6, 8, 10, 12, 14,
  133523. };
  133524. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_0 = {
  133525. _vq_quantthresh__44c8_s_p8_0,
  133526. _vq_quantmap__44c8_s_p8_0,
  133527. 15,
  133528. 15
  133529. };
  133530. static static_codebook _44c8_s_p8_0 = {
  133531. 2, 225,
  133532. _vq_lengthlist__44c8_s_p8_0,
  133533. 1, -520986624, 1620377600, 4, 0,
  133534. _vq_quantlist__44c8_s_p8_0,
  133535. NULL,
  133536. &_vq_auxt__44c8_s_p8_0,
  133537. NULL,
  133538. 0
  133539. };
  133540. static long _vq_quantlist__44c8_s_p8_1[] = {
  133541. 10,
  133542. 9,
  133543. 11,
  133544. 8,
  133545. 12,
  133546. 7,
  133547. 13,
  133548. 6,
  133549. 14,
  133550. 5,
  133551. 15,
  133552. 4,
  133553. 16,
  133554. 3,
  133555. 17,
  133556. 2,
  133557. 18,
  133558. 1,
  133559. 19,
  133560. 0,
  133561. 20,
  133562. };
  133563. static long _vq_lengthlist__44c8_s_p8_1[] = {
  133564. 4, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  133565. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  133566. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  133567. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  133568. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133569. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  133570. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  133571. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  133572. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133573. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133574. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  133575. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  133576. 10,10, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9,
  133577. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133578. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  133579. 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,10,10,10,10,
  133580. 10,10,10, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  133581. 9,10,10,10,10,10,10,10, 9,10,10, 9,10,10,10,10,
  133582. 9,10, 9,10,10, 9,10,10,10,10,10,10,10, 9,10,10,
  133583. 10,10,10,10, 9, 9,10,10, 9,10,10,10,10,10,10,10,
  133584. 10,10,10,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9, 9,
  133585. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  133586. 10, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  133587. 10,10,10,10, 9, 9,10, 9, 9, 9,10,10,10,10,10,10,
  133588. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,10,10,
  133589. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10, 9,
  133590. 9,10, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  133591. 10, 9, 9,10,10, 9,10, 9, 9,
  133592. };
  133593. static float _vq_quantthresh__44c8_s_p8_1[] = {
  133594. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  133595. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  133596. 6.5, 7.5, 8.5, 9.5,
  133597. };
  133598. static long _vq_quantmap__44c8_s_p8_1[] = {
  133599. 19, 17, 15, 13, 11, 9, 7, 5,
  133600. 3, 1, 0, 2, 4, 6, 8, 10,
  133601. 12, 14, 16, 18, 20,
  133602. };
  133603. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_1 = {
  133604. _vq_quantthresh__44c8_s_p8_1,
  133605. _vq_quantmap__44c8_s_p8_1,
  133606. 21,
  133607. 21
  133608. };
  133609. static static_codebook _44c8_s_p8_1 = {
  133610. 2, 441,
  133611. _vq_lengthlist__44c8_s_p8_1,
  133612. 1, -529268736, 1611661312, 5, 0,
  133613. _vq_quantlist__44c8_s_p8_1,
  133614. NULL,
  133615. &_vq_auxt__44c8_s_p8_1,
  133616. NULL,
  133617. 0
  133618. };
  133619. static long _vq_quantlist__44c8_s_p9_0[] = {
  133620. 8,
  133621. 7,
  133622. 9,
  133623. 6,
  133624. 10,
  133625. 5,
  133626. 11,
  133627. 4,
  133628. 12,
  133629. 3,
  133630. 13,
  133631. 2,
  133632. 14,
  133633. 1,
  133634. 15,
  133635. 0,
  133636. 16,
  133637. };
  133638. static long _vq_lengthlist__44c8_s_p9_0[] = {
  133639. 1, 4, 3,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133640. 11, 4, 7, 7,11,11,11,11,11,11,11,11,11,11,11,11,
  133641. 11,11, 4, 8,11,11,11,11,11,11,11,11,11,11,11,11,
  133642. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133643. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133644. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133645. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133646. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133647. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133648. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133649. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133650. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133651. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133652. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133653. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133654. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133655. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133656. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133657. 10,
  133658. };
  133659. static float _vq_quantthresh__44c8_s_p9_0[] = {
  133660. -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5,
  133661. 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5, 6982.5,
  133662. };
  133663. static long _vq_quantmap__44c8_s_p9_0[] = {
  133664. 15, 13, 11, 9, 7, 5, 3, 1,
  133665. 0, 2, 4, 6, 8, 10, 12, 14,
  133666. 16,
  133667. };
  133668. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_0 = {
  133669. _vq_quantthresh__44c8_s_p9_0,
  133670. _vq_quantmap__44c8_s_p9_0,
  133671. 17,
  133672. 17
  133673. };
  133674. static static_codebook _44c8_s_p9_0 = {
  133675. 2, 289,
  133676. _vq_lengthlist__44c8_s_p9_0,
  133677. 1, -509798400, 1631393792, 5, 0,
  133678. _vq_quantlist__44c8_s_p9_0,
  133679. NULL,
  133680. &_vq_auxt__44c8_s_p9_0,
  133681. NULL,
  133682. 0
  133683. };
  133684. static long _vq_quantlist__44c8_s_p9_1[] = {
  133685. 9,
  133686. 8,
  133687. 10,
  133688. 7,
  133689. 11,
  133690. 6,
  133691. 12,
  133692. 5,
  133693. 13,
  133694. 4,
  133695. 14,
  133696. 3,
  133697. 15,
  133698. 2,
  133699. 16,
  133700. 1,
  133701. 17,
  133702. 0,
  133703. 18,
  133704. };
  133705. static long _vq_lengthlist__44c8_s_p9_1[] = {
  133706. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,10,10,
  133707. 10,11,11, 6, 6, 6, 8, 8, 9, 8, 8, 7,10, 8,11,10,
  133708. 12,11,12,12,13,13, 5, 5, 6, 8, 8, 9, 9, 8, 8,10,
  133709. 9,11,11,12,12,13,13,13,13,17, 8, 8, 9, 9, 9, 9,
  133710. 9, 9,10, 9,12,10,12,12,13,12,13,13,17, 9, 8, 9,
  133711. 9, 9, 9, 9, 9,10,10,12,12,12,12,13,13,13,13,17,
  133712. 13,13, 9, 9,10,10,10,10,11,11,12,11,13,12,13,13,
  133713. 14,15,17,13,13, 9, 8,10, 9,10,10,11,11,12,12,14,
  133714. 13,15,13,14,15,17,17,17, 9,10, 9,10,11,11,12,12,
  133715. 12,12,13,13,14,14,15,15,17,17,17, 9, 8, 9, 8,11,
  133716. 11,12,12,12,12,14,13,14,14,14,15,17,17,17,12,14,
  133717. 9,10,11,11,12,12,14,13,13,14,15,13,15,15,17,17,
  133718. 17,13,11,10, 8,11, 9,13,12,13,13,13,13,13,14,14,
  133719. 14,17,17,17,17,17,11,12,11,11,13,13,14,13,15,14,
  133720. 13,15,16,15,17,17,17,17,17,11,11,12, 8,13,12,14,
  133721. 13,17,14,15,14,15,14,17,17,17,17,17,15,15,12,12,
  133722. 12,12,13,14,14,14,15,14,17,14,17,17,17,17,17,16,
  133723. 17,12,12,13,12,13,13,14,14,14,14,14,14,17,17,17,
  133724. 17,17,17,17,14,14,13,12,13,13,15,15,14,13,15,17,
  133725. 17,17,17,17,17,17,17,13,14,13,13,13,13,14,15,15,
  133726. 15,14,15,17,17,17,17,17,17,17,16,15,13,14,13,13,
  133727. 14,14,15,14,14,16,17,17,17,17,17,17,17,16,16,13,
  133728. 14,13,13,14,14,15,14,15,14,
  133729. };
  133730. static float _vq_quantthresh__44c8_s_p9_1[] = {
  133731. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  133732. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  133733. 367.5, 416.5,
  133734. };
  133735. static long _vq_quantmap__44c8_s_p9_1[] = {
  133736. 17, 15, 13, 11, 9, 7, 5, 3,
  133737. 1, 0, 2, 4, 6, 8, 10, 12,
  133738. 14, 16, 18,
  133739. };
  133740. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_1 = {
  133741. _vq_quantthresh__44c8_s_p9_1,
  133742. _vq_quantmap__44c8_s_p9_1,
  133743. 19,
  133744. 19
  133745. };
  133746. static static_codebook _44c8_s_p9_1 = {
  133747. 2, 361,
  133748. _vq_lengthlist__44c8_s_p9_1,
  133749. 1, -518287360, 1622704128, 5, 0,
  133750. _vq_quantlist__44c8_s_p9_1,
  133751. NULL,
  133752. &_vq_auxt__44c8_s_p9_1,
  133753. NULL,
  133754. 0
  133755. };
  133756. static long _vq_quantlist__44c8_s_p9_2[] = {
  133757. 24,
  133758. 23,
  133759. 25,
  133760. 22,
  133761. 26,
  133762. 21,
  133763. 27,
  133764. 20,
  133765. 28,
  133766. 19,
  133767. 29,
  133768. 18,
  133769. 30,
  133770. 17,
  133771. 31,
  133772. 16,
  133773. 32,
  133774. 15,
  133775. 33,
  133776. 14,
  133777. 34,
  133778. 13,
  133779. 35,
  133780. 12,
  133781. 36,
  133782. 11,
  133783. 37,
  133784. 10,
  133785. 38,
  133786. 9,
  133787. 39,
  133788. 8,
  133789. 40,
  133790. 7,
  133791. 41,
  133792. 6,
  133793. 42,
  133794. 5,
  133795. 43,
  133796. 4,
  133797. 44,
  133798. 3,
  133799. 45,
  133800. 2,
  133801. 46,
  133802. 1,
  133803. 47,
  133804. 0,
  133805. 48,
  133806. };
  133807. static long _vq_lengthlist__44c8_s_p9_2[] = {
  133808. 2, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  133809. 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133810. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133811. 7,
  133812. };
  133813. static float _vq_quantthresh__44c8_s_p9_2[] = {
  133814. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  133815. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  133816. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133817. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133818. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  133819. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  133820. };
  133821. static long _vq_quantmap__44c8_s_p9_2[] = {
  133822. 47, 45, 43, 41, 39, 37, 35, 33,
  133823. 31, 29, 27, 25, 23, 21, 19, 17,
  133824. 15, 13, 11, 9, 7, 5, 3, 1,
  133825. 0, 2, 4, 6, 8, 10, 12, 14,
  133826. 16, 18, 20, 22, 24, 26, 28, 30,
  133827. 32, 34, 36, 38, 40, 42, 44, 46,
  133828. 48,
  133829. };
  133830. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_2 = {
  133831. _vq_quantthresh__44c8_s_p9_2,
  133832. _vq_quantmap__44c8_s_p9_2,
  133833. 49,
  133834. 49
  133835. };
  133836. static static_codebook _44c8_s_p9_2 = {
  133837. 1, 49,
  133838. _vq_lengthlist__44c8_s_p9_2,
  133839. 1, -526909440, 1611661312, 6, 0,
  133840. _vq_quantlist__44c8_s_p9_2,
  133841. NULL,
  133842. &_vq_auxt__44c8_s_p9_2,
  133843. NULL,
  133844. 0
  133845. };
  133846. static long _huff_lengthlist__44c8_s_short[] = {
  133847. 4,11,13,14,15,15,18,17,19,17, 5, 6, 8, 9,10,10,
  133848. 12,15,19,19, 6, 6, 6, 6, 8, 8,11,14,18,19, 8, 6,
  133849. 5, 4, 6, 7,10,13,16,17, 9, 7, 6, 5, 6, 7, 9,12,
  133850. 15,19,10, 8, 7, 6, 6, 6, 7, 9,13,15,12,10, 9, 8,
  133851. 7, 6, 4, 5,10,15,13,13,11, 8, 6, 6, 4, 2, 7,12,
  133852. 17,15,16,10, 8, 8, 7, 6, 9,12,19,18,17,13,11,10,
  133853. 10, 9,11,14,
  133854. };
  133855. static static_codebook _huff_book__44c8_s_short = {
  133856. 2, 100,
  133857. _huff_lengthlist__44c8_s_short,
  133858. 0, 0, 0, 0, 0,
  133859. NULL,
  133860. NULL,
  133861. NULL,
  133862. NULL,
  133863. 0
  133864. };
  133865. static long _huff_lengthlist__44c9_s_long[] = {
  133866. 3, 8,12,14,15,15,15,13,15,15, 6, 5, 8,10,12,12,
  133867. 13,12,14,13,10, 6, 5, 6, 8, 9,11,11,13,13,13, 8,
  133868. 5, 4, 5, 6, 8,10,11,13,14,10, 7, 5, 4, 5, 7, 9,
  133869. 11,12,13,11, 8, 6, 5, 4, 5, 7, 9,11,12,11,10, 8,
  133870. 7, 5, 4, 5, 9,10,13,13,11,10, 8, 6, 5, 4, 7, 9,
  133871. 15,14,13,12,10, 9, 8, 7, 8, 9,12,12,14,13,12,11,
  133872. 10, 9, 8, 9,
  133873. };
  133874. static static_codebook _huff_book__44c9_s_long = {
  133875. 2, 100,
  133876. _huff_lengthlist__44c9_s_long,
  133877. 0, 0, 0, 0, 0,
  133878. NULL,
  133879. NULL,
  133880. NULL,
  133881. NULL,
  133882. 0
  133883. };
  133884. static long _vq_quantlist__44c9_s_p1_0[] = {
  133885. 1,
  133886. 0,
  133887. 2,
  133888. };
  133889. static long _vq_lengthlist__44c9_s_p1_0[] = {
  133890. 1, 5, 5, 0, 5, 5, 0, 5, 5, 6, 8, 8, 0, 9, 8, 0,
  133891. 9, 8, 6, 8, 8, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  133892. 0, 0, 0, 0, 5, 8, 8, 0, 7, 7, 0, 8, 8, 5, 8, 8,
  133893. 0, 7, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  133894. 9, 8, 0, 8, 8, 0, 7, 7, 5, 8, 9, 0, 8, 8, 0, 7,
  133895. 7,
  133896. };
  133897. static float _vq_quantthresh__44c9_s_p1_0[] = {
  133898. -0.5, 0.5,
  133899. };
  133900. static long _vq_quantmap__44c9_s_p1_0[] = {
  133901. 1, 0, 2,
  133902. };
  133903. static encode_aux_threshmatch _vq_auxt__44c9_s_p1_0 = {
  133904. _vq_quantthresh__44c9_s_p1_0,
  133905. _vq_quantmap__44c9_s_p1_0,
  133906. 3,
  133907. 3
  133908. };
  133909. static static_codebook _44c9_s_p1_0 = {
  133910. 4, 81,
  133911. _vq_lengthlist__44c9_s_p1_0,
  133912. 1, -535822336, 1611661312, 2, 0,
  133913. _vq_quantlist__44c9_s_p1_0,
  133914. NULL,
  133915. &_vq_auxt__44c9_s_p1_0,
  133916. NULL,
  133917. 0
  133918. };
  133919. static long _vq_quantlist__44c9_s_p2_0[] = {
  133920. 2,
  133921. 1,
  133922. 3,
  133923. 0,
  133924. 4,
  133925. };
  133926. static long _vq_lengthlist__44c9_s_p2_0[] = {
  133927. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  133928. 7, 7, 9, 9, 0, 0, 0, 9, 9, 6, 7, 7, 9, 8, 0, 8,
  133929. 8, 9, 9, 0, 8, 7, 9, 9, 0, 9,10,10,10, 0, 0, 0,
  133930. 11,10, 6, 7, 7, 8, 9, 0, 8, 8, 9, 9, 0, 7, 8, 9,
  133931. 9, 0,10, 9,11,10, 0, 0, 0,10,10, 8, 9, 8,10,10,
  133932. 0,10,10,12,11, 0,10,10,11,11, 0,12,13,13,13, 0,
  133933. 0, 0,13,12, 8, 8, 9,10,10, 0,10,10,11,12, 0,10,
  133934. 10,11,11, 0,13,12,13,13, 0, 0, 0,13,13, 0, 0, 0,
  133935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133936. 0, 0, 0, 0, 0, 0, 6, 8, 7,10,10, 0, 7, 7,10, 9,
  133937. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,10,10, 6,
  133938. 7, 8,10,10, 0, 7, 7, 9,10, 0, 7, 7,10,10, 0, 9,
  133939. 9,10,10, 0, 0, 0,10,10, 8, 9, 9,11,11, 0,10,10,
  133940. 11,11, 0,10,10,11,11, 0,12,12,12,12, 0, 0, 0,12,
  133941. 12, 8, 9,10,11,11, 0, 9,10,11,11, 0,10,10,11,11,
  133942. 0,12,12,12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0,
  133943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133944. 0, 0, 0, 5, 8, 7,10,10, 0, 7, 7,10,10, 0, 7, 7,
  133945. 10, 9, 0, 9, 9,10,10, 0, 0, 0,10,10, 6, 7, 8,10,
  133946. 10, 0, 7, 7,10,10, 0, 7, 7, 9,10, 0, 9, 9,10,10,
  133947. 0, 0, 0,10,10, 8,10, 9,12,11, 0,10,10,12,11, 0,
  133948. 10, 9,11,11, 0,11,12,12,12, 0, 0, 0,12,12, 8, 9,
  133949. 10,11,12, 0,10,10,11,11, 0, 9,10,11,11, 0,12,11,
  133950. 12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133952. 7,10, 9,12,12, 0, 9, 9,12,11, 0, 9, 9,11,11, 0,
  133953. 10,10,12,11, 0, 0, 0,11,12, 7, 9,10,12,12, 0, 9,
  133954. 9,11,12, 0, 9, 9,11,11, 0,10,10,11,12, 0, 0, 0,
  133955. 11,11, 9,11,10,13,12, 0,10,10,12,12, 0,10,10,12,
  133956. 12, 0,11,11,12,12, 0, 0, 0,13,12, 9,10,11,12,13,
  133957. 0,10,10,12,12, 0,10,10,12,12, 0,11,12,12,12, 0,
  133958. 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  133963. 11,10,13,13, 0,10,10,12,12, 0,10,10,12,12, 0,11,
  133964. 12,12,12, 0, 0, 0,12,12, 9,10,11,13,13, 0,10,10,
  133965. 12,12, 0,10,10,12,12, 0,12,11,13,12, 0, 0, 0,12,
  133966. 12,
  133967. };
  133968. static float _vq_quantthresh__44c9_s_p2_0[] = {
  133969. -1.5, -0.5, 0.5, 1.5,
  133970. };
  133971. static long _vq_quantmap__44c9_s_p2_0[] = {
  133972. 3, 1, 0, 2, 4,
  133973. };
  133974. static encode_aux_threshmatch _vq_auxt__44c9_s_p2_0 = {
  133975. _vq_quantthresh__44c9_s_p2_0,
  133976. _vq_quantmap__44c9_s_p2_0,
  133977. 5,
  133978. 5
  133979. };
  133980. static static_codebook _44c9_s_p2_0 = {
  133981. 4, 625,
  133982. _vq_lengthlist__44c9_s_p2_0,
  133983. 1, -533725184, 1611661312, 3, 0,
  133984. _vq_quantlist__44c9_s_p2_0,
  133985. NULL,
  133986. &_vq_auxt__44c9_s_p2_0,
  133987. NULL,
  133988. 0
  133989. };
  133990. static long _vq_quantlist__44c9_s_p3_0[] = {
  133991. 4,
  133992. 3,
  133993. 5,
  133994. 2,
  133995. 6,
  133996. 1,
  133997. 7,
  133998. 0,
  133999. 8,
  134000. };
  134001. static long _vq_lengthlist__44c9_s_p3_0[] = {
  134002. 3, 4, 4, 5, 5, 6, 6, 8, 8, 0, 4, 4, 5, 5, 6, 7,
  134003. 8, 8, 0, 4, 4, 5, 5, 7, 7, 8, 8, 0, 5, 5, 6, 6,
  134004. 7, 7, 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0,
  134005. 7, 7, 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0,
  134006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134007. 0,
  134008. };
  134009. static float _vq_quantthresh__44c9_s_p3_0[] = {
  134010. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  134011. };
  134012. static long _vq_quantmap__44c9_s_p3_0[] = {
  134013. 7, 5, 3, 1, 0, 2, 4, 6,
  134014. 8,
  134015. };
  134016. static encode_aux_threshmatch _vq_auxt__44c9_s_p3_0 = {
  134017. _vq_quantthresh__44c9_s_p3_0,
  134018. _vq_quantmap__44c9_s_p3_0,
  134019. 9,
  134020. 9
  134021. };
  134022. static static_codebook _44c9_s_p3_0 = {
  134023. 2, 81,
  134024. _vq_lengthlist__44c9_s_p3_0,
  134025. 1, -531628032, 1611661312, 4, 0,
  134026. _vq_quantlist__44c9_s_p3_0,
  134027. NULL,
  134028. &_vq_auxt__44c9_s_p3_0,
  134029. NULL,
  134030. 0
  134031. };
  134032. static long _vq_quantlist__44c9_s_p4_0[] = {
  134033. 8,
  134034. 7,
  134035. 9,
  134036. 6,
  134037. 10,
  134038. 5,
  134039. 11,
  134040. 4,
  134041. 12,
  134042. 3,
  134043. 13,
  134044. 2,
  134045. 14,
  134046. 1,
  134047. 15,
  134048. 0,
  134049. 16,
  134050. };
  134051. static long _vq_lengthlist__44c9_s_p4_0[] = {
  134052. 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,10,
  134053. 10, 0, 5, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  134054. 11,11, 0, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  134055. 10,11,11, 0, 6, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,
  134056. 11,11,11,12, 0, 0, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,
  134057. 10,11,11,12,12, 0, 0, 0, 7, 7, 7, 7, 9, 9, 9, 9,
  134058. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 7, 8, 9, 9, 9,
  134059. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  134060. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  134061. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  134062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134070. 0,
  134071. };
  134072. static float _vq_quantthresh__44c9_s_p4_0[] = {
  134073. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134074. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134075. };
  134076. static long _vq_quantmap__44c9_s_p4_0[] = {
  134077. 15, 13, 11, 9, 7, 5, 3, 1,
  134078. 0, 2, 4, 6, 8, 10, 12, 14,
  134079. 16,
  134080. };
  134081. static encode_aux_threshmatch _vq_auxt__44c9_s_p4_0 = {
  134082. _vq_quantthresh__44c9_s_p4_0,
  134083. _vq_quantmap__44c9_s_p4_0,
  134084. 17,
  134085. 17
  134086. };
  134087. static static_codebook _44c9_s_p4_0 = {
  134088. 2, 289,
  134089. _vq_lengthlist__44c9_s_p4_0,
  134090. 1, -529530880, 1611661312, 5, 0,
  134091. _vq_quantlist__44c9_s_p4_0,
  134092. NULL,
  134093. &_vq_auxt__44c9_s_p4_0,
  134094. NULL,
  134095. 0
  134096. };
  134097. static long _vq_quantlist__44c9_s_p5_0[] = {
  134098. 1,
  134099. 0,
  134100. 2,
  134101. };
  134102. static long _vq_lengthlist__44c9_s_p5_0[] = {
  134103. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6, 9,10,10,10,
  134104. 10, 9, 4, 6, 7, 9,10,10,10, 9,10, 5, 9, 9, 9,11,
  134105. 11,10,11,11, 7,10, 9,11,12,11,12,12,12, 7, 9,10,
  134106. 11,11,12,12,12,12, 6,10,10,10,12,12,10,12,11, 7,
  134107. 10,10,11,12,12,11,12,12, 7,10,10,11,12,12,12,12,
  134108. 12,
  134109. };
  134110. static float _vq_quantthresh__44c9_s_p5_0[] = {
  134111. -5.5, 5.5,
  134112. };
  134113. static long _vq_quantmap__44c9_s_p5_0[] = {
  134114. 1, 0, 2,
  134115. };
  134116. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_0 = {
  134117. _vq_quantthresh__44c9_s_p5_0,
  134118. _vq_quantmap__44c9_s_p5_0,
  134119. 3,
  134120. 3
  134121. };
  134122. static static_codebook _44c9_s_p5_0 = {
  134123. 4, 81,
  134124. _vq_lengthlist__44c9_s_p5_0,
  134125. 1, -529137664, 1618345984, 2, 0,
  134126. _vq_quantlist__44c9_s_p5_0,
  134127. NULL,
  134128. &_vq_auxt__44c9_s_p5_0,
  134129. NULL,
  134130. 0
  134131. };
  134132. static long _vq_quantlist__44c9_s_p5_1[] = {
  134133. 5,
  134134. 4,
  134135. 6,
  134136. 3,
  134137. 7,
  134138. 2,
  134139. 8,
  134140. 1,
  134141. 9,
  134142. 0,
  134143. 10,
  134144. };
  134145. static long _vq_lengthlist__44c9_s_p5_1[] = {
  134146. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7,11, 5, 5, 6, 6,
  134147. 7, 7, 7, 7, 8, 8,11, 5, 5, 6, 6, 7, 7, 7, 7, 8,
  134148. 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11, 6,
  134149. 6, 7, 7, 7, 8, 8, 8,11,11,11, 6, 6, 7, 7, 7, 8,
  134150. 8, 8,11,11,11, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11,
  134151. 7, 7, 7, 7, 7, 7, 8, 8,11,11,11,10,10, 7, 7, 7,
  134152. 7, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 7, 7,11,11,
  134153. 11,11,11, 7, 7, 7, 7, 7, 7,
  134154. };
  134155. static float _vq_quantthresh__44c9_s_p5_1[] = {
  134156. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134157. 3.5, 4.5,
  134158. };
  134159. static long _vq_quantmap__44c9_s_p5_1[] = {
  134160. 9, 7, 5, 3, 1, 0, 2, 4,
  134161. 6, 8, 10,
  134162. };
  134163. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_1 = {
  134164. _vq_quantthresh__44c9_s_p5_1,
  134165. _vq_quantmap__44c9_s_p5_1,
  134166. 11,
  134167. 11
  134168. };
  134169. static static_codebook _44c9_s_p5_1 = {
  134170. 2, 121,
  134171. _vq_lengthlist__44c9_s_p5_1,
  134172. 1, -531365888, 1611661312, 4, 0,
  134173. _vq_quantlist__44c9_s_p5_1,
  134174. NULL,
  134175. &_vq_auxt__44c9_s_p5_1,
  134176. NULL,
  134177. 0
  134178. };
  134179. static long _vq_quantlist__44c9_s_p6_0[] = {
  134180. 6,
  134181. 5,
  134182. 7,
  134183. 4,
  134184. 8,
  134185. 3,
  134186. 9,
  134187. 2,
  134188. 10,
  134189. 1,
  134190. 11,
  134191. 0,
  134192. 12,
  134193. };
  134194. static long _vq_lengthlist__44c9_s_p6_0[] = {
  134195. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 5, 4, 4,
  134196. 6, 6, 8, 8, 9, 9, 9, 9,10,10, 6, 4, 4, 6, 6, 8,
  134197. 8, 9, 9, 9, 9,10,10, 0, 6, 6, 7, 7, 8, 8, 9, 9,
  134198. 10,10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  134199. 11, 0,10,10, 8, 8, 9, 9,10,10,11,11,12,12, 0,11,
  134200. 11, 8, 8, 9, 9,10,10,11,11,12,12, 0, 0, 0, 0, 0,
  134201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134205. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134206. };
  134207. static float _vq_quantthresh__44c9_s_p6_0[] = {
  134208. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  134209. 12.5, 17.5, 22.5, 27.5,
  134210. };
  134211. static long _vq_quantmap__44c9_s_p6_0[] = {
  134212. 11, 9, 7, 5, 3, 1, 0, 2,
  134213. 4, 6, 8, 10, 12,
  134214. };
  134215. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_0 = {
  134216. _vq_quantthresh__44c9_s_p6_0,
  134217. _vq_quantmap__44c9_s_p6_0,
  134218. 13,
  134219. 13
  134220. };
  134221. static static_codebook _44c9_s_p6_0 = {
  134222. 2, 169,
  134223. _vq_lengthlist__44c9_s_p6_0,
  134224. 1, -526516224, 1616117760, 4, 0,
  134225. _vq_quantlist__44c9_s_p6_0,
  134226. NULL,
  134227. &_vq_auxt__44c9_s_p6_0,
  134228. NULL,
  134229. 0
  134230. };
  134231. static long _vq_quantlist__44c9_s_p6_1[] = {
  134232. 2,
  134233. 1,
  134234. 3,
  134235. 0,
  134236. 4,
  134237. };
  134238. static long _vq_lengthlist__44c9_s_p6_1[] = {
  134239. 4, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5,
  134240. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  134241. };
  134242. static float _vq_quantthresh__44c9_s_p6_1[] = {
  134243. -1.5, -0.5, 0.5, 1.5,
  134244. };
  134245. static long _vq_quantmap__44c9_s_p6_1[] = {
  134246. 3, 1, 0, 2, 4,
  134247. };
  134248. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_1 = {
  134249. _vq_quantthresh__44c9_s_p6_1,
  134250. _vq_quantmap__44c9_s_p6_1,
  134251. 5,
  134252. 5
  134253. };
  134254. static static_codebook _44c9_s_p6_1 = {
  134255. 2, 25,
  134256. _vq_lengthlist__44c9_s_p6_1,
  134257. 1, -533725184, 1611661312, 3, 0,
  134258. _vq_quantlist__44c9_s_p6_1,
  134259. NULL,
  134260. &_vq_auxt__44c9_s_p6_1,
  134261. NULL,
  134262. 0
  134263. };
  134264. static long _vq_quantlist__44c9_s_p7_0[] = {
  134265. 6,
  134266. 5,
  134267. 7,
  134268. 4,
  134269. 8,
  134270. 3,
  134271. 9,
  134272. 2,
  134273. 10,
  134274. 1,
  134275. 11,
  134276. 0,
  134277. 12,
  134278. };
  134279. static long _vq_lengthlist__44c9_s_p7_0[] = {
  134280. 2, 4, 4, 6, 6, 7, 7, 8, 8,10,10,11,11, 6, 4, 4,
  134281. 6, 6, 8, 8, 9, 9,10,10,12,12, 6, 4, 5, 6, 6, 8,
  134282. 8, 9, 9,10,10,12,12,20, 6, 6, 6, 6, 8, 8, 9,10,
  134283. 11,11,12,12,20, 6, 6, 6, 6, 8, 8,10,10,11,11,12,
  134284. 12,20,10,10, 7, 7, 9, 9,10,10,11,11,12,12,20,11,
  134285. 11, 7, 7, 9, 9,10,10,11,11,12,12,20,20,20, 9, 9,
  134286. 9, 9,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,11,
  134287. 11,12,12,13,13,20,20,20,13,13,10,10,11,11,12,13,
  134288. 13,13,20,20,20,13,13,10,10,11,11,12,13,13,13,20,
  134289. 20,20,20,19,12,12,12,12,13,13,14,15,19,19,19,19,
  134290. 19,12,12,12,12,13,13,14,14,
  134291. };
  134292. static float _vq_quantthresh__44c9_s_p7_0[] = {
  134293. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  134294. 27.5, 38.5, 49.5, 60.5,
  134295. };
  134296. static long _vq_quantmap__44c9_s_p7_0[] = {
  134297. 11, 9, 7, 5, 3, 1, 0, 2,
  134298. 4, 6, 8, 10, 12,
  134299. };
  134300. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_0 = {
  134301. _vq_quantthresh__44c9_s_p7_0,
  134302. _vq_quantmap__44c9_s_p7_0,
  134303. 13,
  134304. 13
  134305. };
  134306. static static_codebook _44c9_s_p7_0 = {
  134307. 2, 169,
  134308. _vq_lengthlist__44c9_s_p7_0,
  134309. 1, -523206656, 1618345984, 4, 0,
  134310. _vq_quantlist__44c9_s_p7_0,
  134311. NULL,
  134312. &_vq_auxt__44c9_s_p7_0,
  134313. NULL,
  134314. 0
  134315. };
  134316. static long _vq_quantlist__44c9_s_p7_1[] = {
  134317. 5,
  134318. 4,
  134319. 6,
  134320. 3,
  134321. 7,
  134322. 2,
  134323. 8,
  134324. 1,
  134325. 9,
  134326. 0,
  134327. 10,
  134328. };
  134329. static long _vq_lengthlist__44c9_s_p7_1[] = {
  134330. 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6,
  134331. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  134332. 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 6,
  134333. 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  134334. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  134335. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  134336. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  134337. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  134338. };
  134339. static float _vq_quantthresh__44c9_s_p7_1[] = {
  134340. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134341. 3.5, 4.5,
  134342. };
  134343. static long _vq_quantmap__44c9_s_p7_1[] = {
  134344. 9, 7, 5, 3, 1, 0, 2, 4,
  134345. 6, 8, 10,
  134346. };
  134347. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_1 = {
  134348. _vq_quantthresh__44c9_s_p7_1,
  134349. _vq_quantmap__44c9_s_p7_1,
  134350. 11,
  134351. 11
  134352. };
  134353. static static_codebook _44c9_s_p7_1 = {
  134354. 2, 121,
  134355. _vq_lengthlist__44c9_s_p7_1,
  134356. 1, -531365888, 1611661312, 4, 0,
  134357. _vq_quantlist__44c9_s_p7_1,
  134358. NULL,
  134359. &_vq_auxt__44c9_s_p7_1,
  134360. NULL,
  134361. 0
  134362. };
  134363. static long _vq_quantlist__44c9_s_p8_0[] = {
  134364. 7,
  134365. 6,
  134366. 8,
  134367. 5,
  134368. 9,
  134369. 4,
  134370. 10,
  134371. 3,
  134372. 11,
  134373. 2,
  134374. 12,
  134375. 1,
  134376. 13,
  134377. 0,
  134378. 14,
  134379. };
  134380. static long _vq_lengthlist__44c9_s_p8_0[] = {
  134381. 1, 4, 4, 7, 6, 8, 8, 8, 8, 9, 9,10,10,11,10, 6,
  134382. 5, 5, 7, 7, 9, 9, 8, 9,10,10,11,11,12,12, 6, 5,
  134383. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,21, 7, 8,
  134384. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,21, 8, 8, 8,
  134385. 8, 9, 9, 9, 9,10,10,11,11,12,12,21,11,12, 9, 9,
  134386. 10,10,10,10,10,11,11,12,12,12,21,12,12, 9, 8,10,
  134387. 10,10,10,11,11,12,12,13,13,21,21,21, 9, 9, 9, 9,
  134388. 11,11,11,11,12,12,12,13,21,20,20, 9, 9, 9, 9,10,
  134389. 11,11,11,12,12,13,13,20,20,20,13,13,10,10,11,11,
  134390. 12,12,13,13,13,13,20,20,20,13,13,10,10,11,11,12,
  134391. 12,13,13,13,13,20,20,20,20,20,12,12,12,12,12,12,
  134392. 13,13,14,14,20,20,20,20,20,12,12,12,11,13,12,13,
  134393. 13,14,14,20,20,20,20,20,15,16,13,12,13,13,14,13,
  134394. 14,14,20,20,20,20,20,16,15,12,12,13,12,14,13,14,
  134395. 14,
  134396. };
  134397. static float _vq_quantthresh__44c9_s_p8_0[] = {
  134398. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  134399. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  134400. };
  134401. static long _vq_quantmap__44c9_s_p8_0[] = {
  134402. 13, 11, 9, 7, 5, 3, 1, 0,
  134403. 2, 4, 6, 8, 10, 12, 14,
  134404. };
  134405. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_0 = {
  134406. _vq_quantthresh__44c9_s_p8_0,
  134407. _vq_quantmap__44c9_s_p8_0,
  134408. 15,
  134409. 15
  134410. };
  134411. static static_codebook _44c9_s_p8_0 = {
  134412. 2, 225,
  134413. _vq_lengthlist__44c9_s_p8_0,
  134414. 1, -520986624, 1620377600, 4, 0,
  134415. _vq_quantlist__44c9_s_p8_0,
  134416. NULL,
  134417. &_vq_auxt__44c9_s_p8_0,
  134418. NULL,
  134419. 0
  134420. };
  134421. static long _vq_quantlist__44c9_s_p8_1[] = {
  134422. 10,
  134423. 9,
  134424. 11,
  134425. 8,
  134426. 12,
  134427. 7,
  134428. 13,
  134429. 6,
  134430. 14,
  134431. 5,
  134432. 15,
  134433. 4,
  134434. 16,
  134435. 3,
  134436. 17,
  134437. 2,
  134438. 18,
  134439. 1,
  134440. 19,
  134441. 0,
  134442. 20,
  134443. };
  134444. static long _vq_lengthlist__44c9_s_p8_1[] = {
  134445. 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  134446. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  134447. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  134448. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  134449. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134450. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  134451. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8,
  134452. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  134453. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134454. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134455. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  134456. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  134457. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134458. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134459. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  134460. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,
  134461. 10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,
  134462. 9,10,10,10,10,10,10,10, 9, 9, 9,10,10,10,10,10,
  134463. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10, 9, 9,10,
  134464. 9,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  134465. 10,10,10,10, 9, 9,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  134466. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  134467. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  134468. 10,10, 9, 9,10, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  134469. 10,10,10,10,10, 9, 9,10,10, 9, 9,10, 9, 9, 9,10,
  134470. 10,10,10,10,10,10,10,10,10,10, 9, 9,10, 9, 9, 9,
  134471. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9,
  134472. 9, 9, 9,10, 9, 9, 9, 9, 9,
  134473. };
  134474. static float _vq_quantthresh__44c9_s_p8_1[] = {
  134475. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  134476. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  134477. 6.5, 7.5, 8.5, 9.5,
  134478. };
  134479. static long _vq_quantmap__44c9_s_p8_1[] = {
  134480. 19, 17, 15, 13, 11, 9, 7, 5,
  134481. 3, 1, 0, 2, 4, 6, 8, 10,
  134482. 12, 14, 16, 18, 20,
  134483. };
  134484. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_1 = {
  134485. _vq_quantthresh__44c9_s_p8_1,
  134486. _vq_quantmap__44c9_s_p8_1,
  134487. 21,
  134488. 21
  134489. };
  134490. static static_codebook _44c9_s_p8_1 = {
  134491. 2, 441,
  134492. _vq_lengthlist__44c9_s_p8_1,
  134493. 1, -529268736, 1611661312, 5, 0,
  134494. _vq_quantlist__44c9_s_p8_1,
  134495. NULL,
  134496. &_vq_auxt__44c9_s_p8_1,
  134497. NULL,
  134498. 0
  134499. };
  134500. static long _vq_quantlist__44c9_s_p9_0[] = {
  134501. 9,
  134502. 8,
  134503. 10,
  134504. 7,
  134505. 11,
  134506. 6,
  134507. 12,
  134508. 5,
  134509. 13,
  134510. 4,
  134511. 14,
  134512. 3,
  134513. 15,
  134514. 2,
  134515. 16,
  134516. 1,
  134517. 17,
  134518. 0,
  134519. 18,
  134520. };
  134521. static long _vq_lengthlist__44c9_s_p9_0[] = {
  134522. 1, 4, 3,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134523. 12,12,12, 4, 5, 6,12,12,12,12,12,12,12,12,12,12,
  134524. 12,12,12,12,12,12, 4, 6, 6,12,12,12,12,12,12,12,
  134525. 12,12,12,12,12,12,12,12,12,12,12,11,12,12,12,12,
  134526. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134527. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134528. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134529. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134530. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134531. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134532. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134533. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134534. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134535. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134536. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134537. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134538. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  134539. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134540. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134541. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134542. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134543. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134544. 11,11,11,11,11,11,11,11,11,
  134545. };
  134546. static float _vq_quantthresh__44c9_s_p9_0[] = {
  134547. -7913.5, -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5,
  134548. -465.5, 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  134549. 6982.5, 7913.5,
  134550. };
  134551. static long _vq_quantmap__44c9_s_p9_0[] = {
  134552. 17, 15, 13, 11, 9, 7, 5, 3,
  134553. 1, 0, 2, 4, 6, 8, 10, 12,
  134554. 14, 16, 18,
  134555. };
  134556. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_0 = {
  134557. _vq_quantthresh__44c9_s_p9_0,
  134558. _vq_quantmap__44c9_s_p9_0,
  134559. 19,
  134560. 19
  134561. };
  134562. static static_codebook _44c9_s_p9_0 = {
  134563. 2, 361,
  134564. _vq_lengthlist__44c9_s_p9_0,
  134565. 1, -508535424, 1631393792, 5, 0,
  134566. _vq_quantlist__44c9_s_p9_0,
  134567. NULL,
  134568. &_vq_auxt__44c9_s_p9_0,
  134569. NULL,
  134570. 0
  134571. };
  134572. static long _vq_quantlist__44c9_s_p9_1[] = {
  134573. 9,
  134574. 8,
  134575. 10,
  134576. 7,
  134577. 11,
  134578. 6,
  134579. 12,
  134580. 5,
  134581. 13,
  134582. 4,
  134583. 14,
  134584. 3,
  134585. 15,
  134586. 2,
  134587. 16,
  134588. 1,
  134589. 17,
  134590. 0,
  134591. 18,
  134592. };
  134593. static long _vq_lengthlist__44c9_s_p9_1[] = {
  134594. 1, 4, 4, 7, 7, 7, 7, 8, 7, 9, 8, 9, 9,10,10,11,
  134595. 11,11,11, 6, 5, 5, 8, 8, 9, 9, 9, 8,10, 9,11,10,
  134596. 12,12,13,12,13,13, 5, 5, 5, 8, 8, 9, 9, 9, 9,10,
  134597. 10,11,11,12,12,13,12,13,13,17, 8, 8, 9, 9, 9, 9,
  134598. 9, 9,10,10,12,11,13,12,13,13,13,13,18, 8, 8, 9,
  134599. 9, 9, 9, 9, 9,11,11,12,12,13,13,13,13,13,13,17,
  134600. 13,12, 9, 9,10,10,10,10,11,11,12,12,12,13,13,13,
  134601. 14,14,18,13,12, 9, 9,10,10,10,10,11,11,12,12,13,
  134602. 13,13,14,14,14,17,18,18,10,10,10,10,11,11,11,12,
  134603. 12,12,14,13,14,13,13,14,18,18,18,10, 9,10, 9,11,
  134604. 11,12,12,12,12,13,13,15,14,14,14,18,18,16,13,14,
  134605. 10,11,11,11,12,13,13,13,13,14,13,13,14,14,18,18,
  134606. 18,14,12,11, 9,11,10,13,12,13,13,13,14,14,14,13,
  134607. 14,18,18,17,18,18,11,12,12,12,13,13,14,13,14,14,
  134608. 13,14,14,14,18,18,18,18,17,12,10,12, 9,13,11,13,
  134609. 14,14,14,14,14,15,14,18,18,17,17,18,14,15,12,13,
  134610. 13,13,14,13,14,14,15,14,15,14,18,17,18,18,18,15,
  134611. 15,12,10,14,10,14,14,13,13,14,14,14,14,18,16,18,
  134612. 18,18,18,17,14,14,13,14,14,13,13,14,14,14,15,15,
  134613. 18,18,18,18,17,17,17,14,14,14,12,14,13,14,14,15,
  134614. 14,15,14,18,18,18,18,18,18,18,17,16,13,13,13,14,
  134615. 14,14,14,15,16,15,18,18,18,18,18,18,18,17,17,13,
  134616. 13,13,13,14,13,14,15,15,15,
  134617. };
  134618. static float _vq_quantthresh__44c9_s_p9_1[] = {
  134619. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  134620. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  134621. 367.5, 416.5,
  134622. };
  134623. static long _vq_quantmap__44c9_s_p9_1[] = {
  134624. 17, 15, 13, 11, 9, 7, 5, 3,
  134625. 1, 0, 2, 4, 6, 8, 10, 12,
  134626. 14, 16, 18,
  134627. };
  134628. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_1 = {
  134629. _vq_quantthresh__44c9_s_p9_1,
  134630. _vq_quantmap__44c9_s_p9_1,
  134631. 19,
  134632. 19
  134633. };
  134634. static static_codebook _44c9_s_p9_1 = {
  134635. 2, 361,
  134636. _vq_lengthlist__44c9_s_p9_1,
  134637. 1, -518287360, 1622704128, 5, 0,
  134638. _vq_quantlist__44c9_s_p9_1,
  134639. NULL,
  134640. &_vq_auxt__44c9_s_p9_1,
  134641. NULL,
  134642. 0
  134643. };
  134644. static long _vq_quantlist__44c9_s_p9_2[] = {
  134645. 24,
  134646. 23,
  134647. 25,
  134648. 22,
  134649. 26,
  134650. 21,
  134651. 27,
  134652. 20,
  134653. 28,
  134654. 19,
  134655. 29,
  134656. 18,
  134657. 30,
  134658. 17,
  134659. 31,
  134660. 16,
  134661. 32,
  134662. 15,
  134663. 33,
  134664. 14,
  134665. 34,
  134666. 13,
  134667. 35,
  134668. 12,
  134669. 36,
  134670. 11,
  134671. 37,
  134672. 10,
  134673. 38,
  134674. 9,
  134675. 39,
  134676. 8,
  134677. 40,
  134678. 7,
  134679. 41,
  134680. 6,
  134681. 42,
  134682. 5,
  134683. 43,
  134684. 4,
  134685. 44,
  134686. 3,
  134687. 45,
  134688. 2,
  134689. 46,
  134690. 1,
  134691. 47,
  134692. 0,
  134693. 48,
  134694. };
  134695. static long _vq_lengthlist__44c9_s_p9_2[] = {
  134696. 2, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  134697. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  134698. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  134699. 7,
  134700. };
  134701. static float _vq_quantthresh__44c9_s_p9_2[] = {
  134702. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  134703. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  134704. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134705. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134706. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  134707. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  134708. };
  134709. static long _vq_quantmap__44c9_s_p9_2[] = {
  134710. 47, 45, 43, 41, 39, 37, 35, 33,
  134711. 31, 29, 27, 25, 23, 21, 19, 17,
  134712. 15, 13, 11, 9, 7, 5, 3, 1,
  134713. 0, 2, 4, 6, 8, 10, 12, 14,
  134714. 16, 18, 20, 22, 24, 26, 28, 30,
  134715. 32, 34, 36, 38, 40, 42, 44, 46,
  134716. 48,
  134717. };
  134718. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_2 = {
  134719. _vq_quantthresh__44c9_s_p9_2,
  134720. _vq_quantmap__44c9_s_p9_2,
  134721. 49,
  134722. 49
  134723. };
  134724. static static_codebook _44c9_s_p9_2 = {
  134725. 1, 49,
  134726. _vq_lengthlist__44c9_s_p9_2,
  134727. 1, -526909440, 1611661312, 6, 0,
  134728. _vq_quantlist__44c9_s_p9_2,
  134729. NULL,
  134730. &_vq_auxt__44c9_s_p9_2,
  134731. NULL,
  134732. 0
  134733. };
  134734. static long _huff_lengthlist__44c9_s_short[] = {
  134735. 5,13,18,16,17,17,19,18,19,19, 5, 7,10,11,12,12,
  134736. 13,16,17,18, 6, 6, 7, 7, 9, 9,10,14,17,19, 8, 7,
  134737. 6, 5, 6, 7, 9,12,19,17, 8, 7, 7, 6, 5, 6, 8,11,
  134738. 15,19, 9, 8, 7, 6, 5, 5, 6, 8,13,15,11,10, 8, 8,
  134739. 7, 5, 4, 4,10,14,12,13,11, 9, 7, 6, 4, 2, 6,12,
  134740. 18,16,16,13, 8, 7, 7, 5, 8,13,16,17,18,15,11, 9,
  134741. 9, 8,10,13,
  134742. };
  134743. static static_codebook _huff_book__44c9_s_short = {
  134744. 2, 100,
  134745. _huff_lengthlist__44c9_s_short,
  134746. 0, 0, 0, 0, 0,
  134747. NULL,
  134748. NULL,
  134749. NULL,
  134750. NULL,
  134751. 0
  134752. };
  134753. static long _huff_lengthlist__44c0_s_long[] = {
  134754. 5, 4, 8, 9, 8, 9,10,12,15, 4, 1, 5, 5, 6, 8,11,
  134755. 12,12, 8, 5, 8, 9, 9,11,13,12,12, 9, 5, 8, 5, 7,
  134756. 9,12,13,13, 8, 6, 8, 7, 7, 9,11,11,11, 9, 7, 9,
  134757. 7, 7, 7, 7,10,12,10,10,11, 9, 8, 7, 7, 9,11,11,
  134758. 12,13,12,11, 9, 8, 9,11,13,16,16,15,15,12,10,11,
  134759. 12,
  134760. };
  134761. static static_codebook _huff_book__44c0_s_long = {
  134762. 2, 81,
  134763. _huff_lengthlist__44c0_s_long,
  134764. 0, 0, 0, 0, 0,
  134765. NULL,
  134766. NULL,
  134767. NULL,
  134768. NULL,
  134769. 0
  134770. };
  134771. static long _vq_quantlist__44c0_s_p1_0[] = {
  134772. 1,
  134773. 0,
  134774. 2,
  134775. };
  134776. static long _vq_lengthlist__44c0_s_p1_0[] = {
  134777. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  134778. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134782. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  134783. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134787. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  134788. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  134823. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  134824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  134828. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  134829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  134833. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  134834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134868. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  134869. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134873. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  134874. 0, 0, 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  134875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134878. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,11,
  134879. 0, 0, 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 0,
  134880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135187. 0,
  135188. };
  135189. static float _vq_quantthresh__44c0_s_p1_0[] = {
  135190. -0.5, 0.5,
  135191. };
  135192. static long _vq_quantmap__44c0_s_p1_0[] = {
  135193. 1, 0, 2,
  135194. };
  135195. static encode_aux_threshmatch _vq_auxt__44c0_s_p1_0 = {
  135196. _vq_quantthresh__44c0_s_p1_0,
  135197. _vq_quantmap__44c0_s_p1_0,
  135198. 3,
  135199. 3
  135200. };
  135201. static static_codebook _44c0_s_p1_0 = {
  135202. 8, 6561,
  135203. _vq_lengthlist__44c0_s_p1_0,
  135204. 1, -535822336, 1611661312, 2, 0,
  135205. _vq_quantlist__44c0_s_p1_0,
  135206. NULL,
  135207. &_vq_auxt__44c0_s_p1_0,
  135208. NULL,
  135209. 0
  135210. };
  135211. static long _vq_quantlist__44c0_s_p2_0[] = {
  135212. 2,
  135213. 1,
  135214. 3,
  135215. 0,
  135216. 4,
  135217. };
  135218. static long _vq_lengthlist__44c0_s_p2_0[] = {
  135219. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 6, 0, 0,
  135221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135222. 0, 0, 4, 5, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  135224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135225. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  135226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135258. 0,
  135259. };
  135260. static float _vq_quantthresh__44c0_s_p2_0[] = {
  135261. -1.5, -0.5, 0.5, 1.5,
  135262. };
  135263. static long _vq_quantmap__44c0_s_p2_0[] = {
  135264. 3, 1, 0, 2, 4,
  135265. };
  135266. static encode_aux_threshmatch _vq_auxt__44c0_s_p2_0 = {
  135267. _vq_quantthresh__44c0_s_p2_0,
  135268. _vq_quantmap__44c0_s_p2_0,
  135269. 5,
  135270. 5
  135271. };
  135272. static static_codebook _44c0_s_p2_0 = {
  135273. 4, 625,
  135274. _vq_lengthlist__44c0_s_p2_0,
  135275. 1, -533725184, 1611661312, 3, 0,
  135276. _vq_quantlist__44c0_s_p2_0,
  135277. NULL,
  135278. &_vq_auxt__44c0_s_p2_0,
  135279. NULL,
  135280. 0
  135281. };
  135282. static long _vq_quantlist__44c0_s_p3_0[] = {
  135283. 4,
  135284. 3,
  135285. 5,
  135286. 2,
  135287. 6,
  135288. 1,
  135289. 7,
  135290. 0,
  135291. 8,
  135292. };
  135293. static long _vq_lengthlist__44c0_s_p3_0[] = {
  135294. 1, 3, 2, 8, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  135295. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  135296. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  135297. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  135298. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135299. 0,
  135300. };
  135301. static float _vq_quantthresh__44c0_s_p3_0[] = {
  135302. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  135303. };
  135304. static long _vq_quantmap__44c0_s_p3_0[] = {
  135305. 7, 5, 3, 1, 0, 2, 4, 6,
  135306. 8,
  135307. };
  135308. static encode_aux_threshmatch _vq_auxt__44c0_s_p3_0 = {
  135309. _vq_quantthresh__44c0_s_p3_0,
  135310. _vq_quantmap__44c0_s_p3_0,
  135311. 9,
  135312. 9
  135313. };
  135314. static static_codebook _44c0_s_p3_0 = {
  135315. 2, 81,
  135316. _vq_lengthlist__44c0_s_p3_0,
  135317. 1, -531628032, 1611661312, 4, 0,
  135318. _vq_quantlist__44c0_s_p3_0,
  135319. NULL,
  135320. &_vq_auxt__44c0_s_p3_0,
  135321. NULL,
  135322. 0
  135323. };
  135324. static long _vq_quantlist__44c0_s_p4_0[] = {
  135325. 4,
  135326. 3,
  135327. 5,
  135328. 2,
  135329. 6,
  135330. 1,
  135331. 7,
  135332. 0,
  135333. 8,
  135334. };
  135335. static long _vq_lengthlist__44c0_s_p4_0[] = {
  135336. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  135337. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  135338. 7, 8, 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0,
  135339. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 9, 8, 8,10,10, 0,
  135340. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  135341. 10,
  135342. };
  135343. static float _vq_quantthresh__44c0_s_p4_0[] = {
  135344. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  135345. };
  135346. static long _vq_quantmap__44c0_s_p4_0[] = {
  135347. 7, 5, 3, 1, 0, 2, 4, 6,
  135348. 8,
  135349. };
  135350. static encode_aux_threshmatch _vq_auxt__44c0_s_p4_0 = {
  135351. _vq_quantthresh__44c0_s_p4_0,
  135352. _vq_quantmap__44c0_s_p4_0,
  135353. 9,
  135354. 9
  135355. };
  135356. static static_codebook _44c0_s_p4_0 = {
  135357. 2, 81,
  135358. _vq_lengthlist__44c0_s_p4_0,
  135359. 1, -531628032, 1611661312, 4, 0,
  135360. _vq_quantlist__44c0_s_p4_0,
  135361. NULL,
  135362. &_vq_auxt__44c0_s_p4_0,
  135363. NULL,
  135364. 0
  135365. };
  135366. static long _vq_quantlist__44c0_s_p5_0[] = {
  135367. 8,
  135368. 7,
  135369. 9,
  135370. 6,
  135371. 10,
  135372. 5,
  135373. 11,
  135374. 4,
  135375. 12,
  135376. 3,
  135377. 13,
  135378. 2,
  135379. 14,
  135380. 1,
  135381. 15,
  135382. 0,
  135383. 16,
  135384. };
  135385. static long _vq_lengthlist__44c0_s_p5_0[] = {
  135386. 1, 4, 3, 6, 6, 8, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  135387. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9, 9,10,10,10,
  135388. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  135389. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  135390. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  135391. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  135392. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  135393. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  135394. 10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  135395. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  135396. 10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  135397. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  135398. 10,10,11,11,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  135399. 0, 0, 0,11,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  135400. 0, 0, 0, 0,11,11,12,11,12,12,12,12,13,13, 0, 0,
  135401. 0, 0, 0, 0, 0,11,11,11,12,12,12,12,13,13,13, 0,
  135402. 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,13,14,14,
  135403. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  135404. 14,
  135405. };
  135406. static float _vq_quantthresh__44c0_s_p5_0[] = {
  135407. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135408. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135409. };
  135410. static long _vq_quantmap__44c0_s_p5_0[] = {
  135411. 15, 13, 11, 9, 7, 5, 3, 1,
  135412. 0, 2, 4, 6, 8, 10, 12, 14,
  135413. 16,
  135414. };
  135415. static encode_aux_threshmatch _vq_auxt__44c0_s_p5_0 = {
  135416. _vq_quantthresh__44c0_s_p5_0,
  135417. _vq_quantmap__44c0_s_p5_0,
  135418. 17,
  135419. 17
  135420. };
  135421. static static_codebook _44c0_s_p5_0 = {
  135422. 2, 289,
  135423. _vq_lengthlist__44c0_s_p5_0,
  135424. 1, -529530880, 1611661312, 5, 0,
  135425. _vq_quantlist__44c0_s_p5_0,
  135426. NULL,
  135427. &_vq_auxt__44c0_s_p5_0,
  135428. NULL,
  135429. 0
  135430. };
  135431. static long _vq_quantlist__44c0_s_p6_0[] = {
  135432. 1,
  135433. 0,
  135434. 2,
  135435. };
  135436. static long _vq_lengthlist__44c0_s_p6_0[] = {
  135437. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  135438. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  135439. 11,12,10,11, 6, 9, 9,11,10,11,11,10,10, 6, 9, 9,
  135440. 11,10,11,11,10,10, 7,11,10,12,11,11,11,11,11, 7,
  135441. 9, 9,10,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  135442. 10,
  135443. };
  135444. static float _vq_quantthresh__44c0_s_p6_0[] = {
  135445. -5.5, 5.5,
  135446. };
  135447. static long _vq_quantmap__44c0_s_p6_0[] = {
  135448. 1, 0, 2,
  135449. };
  135450. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_0 = {
  135451. _vq_quantthresh__44c0_s_p6_0,
  135452. _vq_quantmap__44c0_s_p6_0,
  135453. 3,
  135454. 3
  135455. };
  135456. static static_codebook _44c0_s_p6_0 = {
  135457. 4, 81,
  135458. _vq_lengthlist__44c0_s_p6_0,
  135459. 1, -529137664, 1618345984, 2, 0,
  135460. _vq_quantlist__44c0_s_p6_0,
  135461. NULL,
  135462. &_vq_auxt__44c0_s_p6_0,
  135463. NULL,
  135464. 0
  135465. };
  135466. static long _vq_quantlist__44c0_s_p6_1[] = {
  135467. 5,
  135468. 4,
  135469. 6,
  135470. 3,
  135471. 7,
  135472. 2,
  135473. 8,
  135474. 1,
  135475. 9,
  135476. 0,
  135477. 10,
  135478. };
  135479. static long _vq_lengthlist__44c0_s_p6_1[] = {
  135480. 2, 3, 3, 6, 6, 7, 7, 7, 7, 7, 8,10,10,10, 6, 6,
  135481. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  135482. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  135483. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  135484. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  135485. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  135486. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  135487. 10,10,10, 8, 8, 8, 8, 8, 8,
  135488. };
  135489. static float _vq_quantthresh__44c0_s_p6_1[] = {
  135490. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  135491. 3.5, 4.5,
  135492. };
  135493. static long _vq_quantmap__44c0_s_p6_1[] = {
  135494. 9, 7, 5, 3, 1, 0, 2, 4,
  135495. 6, 8, 10,
  135496. };
  135497. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_1 = {
  135498. _vq_quantthresh__44c0_s_p6_1,
  135499. _vq_quantmap__44c0_s_p6_1,
  135500. 11,
  135501. 11
  135502. };
  135503. static static_codebook _44c0_s_p6_1 = {
  135504. 2, 121,
  135505. _vq_lengthlist__44c0_s_p6_1,
  135506. 1, -531365888, 1611661312, 4, 0,
  135507. _vq_quantlist__44c0_s_p6_1,
  135508. NULL,
  135509. &_vq_auxt__44c0_s_p6_1,
  135510. NULL,
  135511. 0
  135512. };
  135513. static long _vq_quantlist__44c0_s_p7_0[] = {
  135514. 6,
  135515. 5,
  135516. 7,
  135517. 4,
  135518. 8,
  135519. 3,
  135520. 9,
  135521. 2,
  135522. 10,
  135523. 1,
  135524. 11,
  135525. 0,
  135526. 12,
  135527. };
  135528. static long _vq_lengthlist__44c0_s_p7_0[] = {
  135529. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  135530. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  135531. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  135532. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  135533. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  135534. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  135535. 10,10,11,11,11,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  135536. 11,11,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  135537. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  135538. 0, 0, 0, 0,11,11,11,11,13,12,13,13, 0, 0, 0, 0,
  135539. 0,12,12,11,11,12,12,13,13,
  135540. };
  135541. static float _vq_quantthresh__44c0_s_p7_0[] = {
  135542. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  135543. 12.5, 17.5, 22.5, 27.5,
  135544. };
  135545. static long _vq_quantmap__44c0_s_p7_0[] = {
  135546. 11, 9, 7, 5, 3, 1, 0, 2,
  135547. 4, 6, 8, 10, 12,
  135548. };
  135549. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_0 = {
  135550. _vq_quantthresh__44c0_s_p7_0,
  135551. _vq_quantmap__44c0_s_p7_0,
  135552. 13,
  135553. 13
  135554. };
  135555. static static_codebook _44c0_s_p7_0 = {
  135556. 2, 169,
  135557. _vq_lengthlist__44c0_s_p7_0,
  135558. 1, -526516224, 1616117760, 4, 0,
  135559. _vq_quantlist__44c0_s_p7_0,
  135560. NULL,
  135561. &_vq_auxt__44c0_s_p7_0,
  135562. NULL,
  135563. 0
  135564. };
  135565. static long _vq_quantlist__44c0_s_p7_1[] = {
  135566. 2,
  135567. 1,
  135568. 3,
  135569. 0,
  135570. 4,
  135571. };
  135572. static long _vq_lengthlist__44c0_s_p7_1[] = {
  135573. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  135574. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  135575. };
  135576. static float _vq_quantthresh__44c0_s_p7_1[] = {
  135577. -1.5, -0.5, 0.5, 1.5,
  135578. };
  135579. static long _vq_quantmap__44c0_s_p7_1[] = {
  135580. 3, 1, 0, 2, 4,
  135581. };
  135582. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_1 = {
  135583. _vq_quantthresh__44c0_s_p7_1,
  135584. _vq_quantmap__44c0_s_p7_1,
  135585. 5,
  135586. 5
  135587. };
  135588. static static_codebook _44c0_s_p7_1 = {
  135589. 2, 25,
  135590. _vq_lengthlist__44c0_s_p7_1,
  135591. 1, -533725184, 1611661312, 3, 0,
  135592. _vq_quantlist__44c0_s_p7_1,
  135593. NULL,
  135594. &_vq_auxt__44c0_s_p7_1,
  135595. NULL,
  135596. 0
  135597. };
  135598. static long _vq_quantlist__44c0_s_p8_0[] = {
  135599. 2,
  135600. 1,
  135601. 3,
  135602. 0,
  135603. 4,
  135604. };
  135605. static long _vq_lengthlist__44c0_s_p8_0[] = {
  135606. 1, 5, 5,10,10, 6, 9, 8,10,10, 6,10, 9,10,10,10,
  135607. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135608. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135609. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135610. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135611. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135612. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135613. 10,10,10,10,10,10,10,10,10,10,10,10,10, 8,10,10,
  135614. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135615. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135616. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135617. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135618. 10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,
  135619. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135620. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135621. 11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,
  135622. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135623. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135624. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135625. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135626. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135627. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135628. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135629. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135630. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135631. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135632. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135633. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135634. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135635. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135636. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135637. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135638. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135639. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135640. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135641. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135642. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135643. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135644. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135645. 11,
  135646. };
  135647. static float _vq_quantthresh__44c0_s_p8_0[] = {
  135648. -331.5, -110.5, 110.5, 331.5,
  135649. };
  135650. static long _vq_quantmap__44c0_s_p8_0[] = {
  135651. 3, 1, 0, 2, 4,
  135652. };
  135653. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_0 = {
  135654. _vq_quantthresh__44c0_s_p8_0,
  135655. _vq_quantmap__44c0_s_p8_0,
  135656. 5,
  135657. 5
  135658. };
  135659. static static_codebook _44c0_s_p8_0 = {
  135660. 4, 625,
  135661. _vq_lengthlist__44c0_s_p8_0,
  135662. 1, -518283264, 1627103232, 3, 0,
  135663. _vq_quantlist__44c0_s_p8_0,
  135664. NULL,
  135665. &_vq_auxt__44c0_s_p8_0,
  135666. NULL,
  135667. 0
  135668. };
  135669. static long _vq_quantlist__44c0_s_p8_1[] = {
  135670. 6,
  135671. 5,
  135672. 7,
  135673. 4,
  135674. 8,
  135675. 3,
  135676. 9,
  135677. 2,
  135678. 10,
  135679. 1,
  135680. 11,
  135681. 0,
  135682. 12,
  135683. };
  135684. static long _vq_lengthlist__44c0_s_p8_1[] = {
  135685. 1, 4, 4, 6, 6, 7, 7, 9, 9,11,12,13,12, 6, 5, 5,
  135686. 7, 7, 8, 8,10, 9,12,12,12,12, 6, 5, 5, 7, 7, 8,
  135687. 8,10, 9,12,11,11,13,16, 7, 7, 8, 8, 9, 9,10,10,
  135688. 12,12,13,12,16, 7, 7, 8, 7, 9, 9,10,10,11,12,12,
  135689. 13,16,10,10, 8, 8,10,10,11,12,12,12,13,13,16,11,
  135690. 10, 8, 7,11,10,11,11,12,11,13,13,16,16,16,10,10,
  135691. 10,10,11,11,13,12,13,13,16,16,16,11, 9,11, 9,15,
  135692. 13,12,13,13,13,16,16,16,15,13,11,11,12,13,12,12,
  135693. 14,13,16,16,16,14,13,11,11,13,12,14,13,13,13,16,
  135694. 16,16,16,16,13,13,13,12,14,13,14,14,16,16,16,16,
  135695. 16,13,13,12,12,14,14,15,13,
  135696. };
  135697. static float _vq_quantthresh__44c0_s_p8_1[] = {
  135698. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  135699. 42.5, 59.5, 76.5, 93.5,
  135700. };
  135701. static long _vq_quantmap__44c0_s_p8_1[] = {
  135702. 11, 9, 7, 5, 3, 1, 0, 2,
  135703. 4, 6, 8, 10, 12,
  135704. };
  135705. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_1 = {
  135706. _vq_quantthresh__44c0_s_p8_1,
  135707. _vq_quantmap__44c0_s_p8_1,
  135708. 13,
  135709. 13
  135710. };
  135711. static static_codebook _44c0_s_p8_1 = {
  135712. 2, 169,
  135713. _vq_lengthlist__44c0_s_p8_1,
  135714. 1, -522616832, 1620115456, 4, 0,
  135715. _vq_quantlist__44c0_s_p8_1,
  135716. NULL,
  135717. &_vq_auxt__44c0_s_p8_1,
  135718. NULL,
  135719. 0
  135720. };
  135721. static long _vq_quantlist__44c0_s_p8_2[] = {
  135722. 8,
  135723. 7,
  135724. 9,
  135725. 6,
  135726. 10,
  135727. 5,
  135728. 11,
  135729. 4,
  135730. 12,
  135731. 3,
  135732. 13,
  135733. 2,
  135734. 14,
  135735. 1,
  135736. 15,
  135737. 0,
  135738. 16,
  135739. };
  135740. static long _vq_lengthlist__44c0_s_p8_2[] = {
  135741. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  135742. 8,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  135743. 9, 9,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  135744. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  135745. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  135746. 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 8, 9, 9,
  135747. 9, 9, 9,10, 9,10,10,10,10, 7, 7, 8, 8, 9, 9, 9,
  135748. 9, 9, 9,10, 9,10,10,10,10,10, 8, 8, 8, 9, 9, 9,
  135749. 9, 9, 9, 9,10,10,10, 9,11,10,10,10,10, 8, 8, 9,
  135750. 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,11,11, 9, 9,
  135751. 9, 9, 9, 9, 9, 9,10, 9, 9,10,11,10,10,11,11, 9,
  135752. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  135753. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,10,11,
  135754. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  135755. 11,11,11,11, 9,10, 9,10, 9, 9, 9, 9,10, 9,10,11,
  135756. 10,11,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9,10,11,
  135757. 11,10,11,11,10,11,10,10,10, 9, 9, 9, 9,10, 9, 9,
  135758. 10,11,10,11,11,11,11,10,11,10,10, 9,10, 9, 9, 9,
  135759. 10,
  135760. };
  135761. static float _vq_quantthresh__44c0_s_p8_2[] = {
  135762. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135763. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135764. };
  135765. static long _vq_quantmap__44c0_s_p8_2[] = {
  135766. 15, 13, 11, 9, 7, 5, 3, 1,
  135767. 0, 2, 4, 6, 8, 10, 12, 14,
  135768. 16,
  135769. };
  135770. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_2 = {
  135771. _vq_quantthresh__44c0_s_p8_2,
  135772. _vq_quantmap__44c0_s_p8_2,
  135773. 17,
  135774. 17
  135775. };
  135776. static static_codebook _44c0_s_p8_2 = {
  135777. 2, 289,
  135778. _vq_lengthlist__44c0_s_p8_2,
  135779. 1, -529530880, 1611661312, 5, 0,
  135780. _vq_quantlist__44c0_s_p8_2,
  135781. NULL,
  135782. &_vq_auxt__44c0_s_p8_2,
  135783. NULL,
  135784. 0
  135785. };
  135786. static long _huff_lengthlist__44c0_s_short[] = {
  135787. 9, 8,12,11,12,13,14,14,16, 6, 1, 5, 6, 6, 9,12,
  135788. 14,17, 9, 4, 5, 9, 7, 9,13,15,16, 8, 5, 8, 6, 8,
  135789. 10,13,17,17, 9, 6, 7, 7, 8, 9,13,15,17,11, 8, 9,
  135790. 9, 9,10,12,16,16,13, 7, 8, 7, 7, 9,12,14,15,13,
  135791. 6, 7, 5, 5, 7,10,13,13,14, 7, 8, 5, 6, 7, 9,10,
  135792. 12,
  135793. };
  135794. static static_codebook _huff_book__44c0_s_short = {
  135795. 2, 81,
  135796. _huff_lengthlist__44c0_s_short,
  135797. 0, 0, 0, 0, 0,
  135798. NULL,
  135799. NULL,
  135800. NULL,
  135801. NULL,
  135802. 0
  135803. };
  135804. static long _huff_lengthlist__44c0_sm_long[] = {
  135805. 5, 4, 9,10, 9,10,11,12,13, 4, 1, 5, 7, 7, 9,11,
  135806. 12,14, 8, 5, 7, 9, 8,10,13,13,13,10, 7, 9, 4, 6,
  135807. 7,10,12,14, 9, 6, 7, 6, 6, 7,10,12,12, 9, 8, 9,
  135808. 7, 6, 7, 8,11,12,11,11,11, 9, 8, 7, 8,10,12,12,
  135809. 13,14,12,11, 9, 9, 9,12,12,17,17,15,16,12,10,11,
  135810. 13,
  135811. };
  135812. static static_codebook _huff_book__44c0_sm_long = {
  135813. 2, 81,
  135814. _huff_lengthlist__44c0_sm_long,
  135815. 0, 0, 0, 0, 0,
  135816. NULL,
  135817. NULL,
  135818. NULL,
  135819. NULL,
  135820. 0
  135821. };
  135822. static long _vq_quantlist__44c0_sm_p1_0[] = {
  135823. 1,
  135824. 0,
  135825. 2,
  135826. };
  135827. static long _vq_lengthlist__44c0_sm_p1_0[] = {
  135828. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  135829. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135833. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  135834. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135838. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  135839. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  135874. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  135875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  135879. 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  135880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135884. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  135885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135919. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135920. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135924. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  135925. 0, 0, 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  135926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135929. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  135930. 0, 0, 0, 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 0,
  135931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136238. 0,
  136239. };
  136240. static float _vq_quantthresh__44c0_sm_p1_0[] = {
  136241. -0.5, 0.5,
  136242. };
  136243. static long _vq_quantmap__44c0_sm_p1_0[] = {
  136244. 1, 0, 2,
  136245. };
  136246. static encode_aux_threshmatch _vq_auxt__44c0_sm_p1_0 = {
  136247. _vq_quantthresh__44c0_sm_p1_0,
  136248. _vq_quantmap__44c0_sm_p1_0,
  136249. 3,
  136250. 3
  136251. };
  136252. static static_codebook _44c0_sm_p1_0 = {
  136253. 8, 6561,
  136254. _vq_lengthlist__44c0_sm_p1_0,
  136255. 1, -535822336, 1611661312, 2, 0,
  136256. _vq_quantlist__44c0_sm_p1_0,
  136257. NULL,
  136258. &_vq_auxt__44c0_sm_p1_0,
  136259. NULL,
  136260. 0
  136261. };
  136262. static long _vq_quantlist__44c0_sm_p2_0[] = {
  136263. 2,
  136264. 1,
  136265. 3,
  136266. 0,
  136267. 4,
  136268. };
  136269. static long _vq_lengthlist__44c0_sm_p2_0[] = {
  136270. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  136272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136273. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  136275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136276. 0, 0, 0, 0, 7, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  136277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136309. 0,
  136310. };
  136311. static float _vq_quantthresh__44c0_sm_p2_0[] = {
  136312. -1.5, -0.5, 0.5, 1.5,
  136313. };
  136314. static long _vq_quantmap__44c0_sm_p2_0[] = {
  136315. 3, 1, 0, 2, 4,
  136316. };
  136317. static encode_aux_threshmatch _vq_auxt__44c0_sm_p2_0 = {
  136318. _vq_quantthresh__44c0_sm_p2_0,
  136319. _vq_quantmap__44c0_sm_p2_0,
  136320. 5,
  136321. 5
  136322. };
  136323. static static_codebook _44c0_sm_p2_0 = {
  136324. 4, 625,
  136325. _vq_lengthlist__44c0_sm_p2_0,
  136326. 1, -533725184, 1611661312, 3, 0,
  136327. _vq_quantlist__44c0_sm_p2_0,
  136328. NULL,
  136329. &_vq_auxt__44c0_sm_p2_0,
  136330. NULL,
  136331. 0
  136332. };
  136333. static long _vq_quantlist__44c0_sm_p3_0[] = {
  136334. 4,
  136335. 3,
  136336. 5,
  136337. 2,
  136338. 6,
  136339. 1,
  136340. 7,
  136341. 0,
  136342. 8,
  136343. };
  136344. static long _vq_lengthlist__44c0_sm_p3_0[] = {
  136345. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 4, 7, 7, 0, 0,
  136346. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  136347. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  136348. 9,10, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  136349. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136350. 0,
  136351. };
  136352. static float _vq_quantthresh__44c0_sm_p3_0[] = {
  136353. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136354. };
  136355. static long _vq_quantmap__44c0_sm_p3_0[] = {
  136356. 7, 5, 3, 1, 0, 2, 4, 6,
  136357. 8,
  136358. };
  136359. static encode_aux_threshmatch _vq_auxt__44c0_sm_p3_0 = {
  136360. _vq_quantthresh__44c0_sm_p3_0,
  136361. _vq_quantmap__44c0_sm_p3_0,
  136362. 9,
  136363. 9
  136364. };
  136365. static static_codebook _44c0_sm_p3_0 = {
  136366. 2, 81,
  136367. _vq_lengthlist__44c0_sm_p3_0,
  136368. 1, -531628032, 1611661312, 4, 0,
  136369. _vq_quantlist__44c0_sm_p3_0,
  136370. NULL,
  136371. &_vq_auxt__44c0_sm_p3_0,
  136372. NULL,
  136373. 0
  136374. };
  136375. static long _vq_quantlist__44c0_sm_p4_0[] = {
  136376. 4,
  136377. 3,
  136378. 5,
  136379. 2,
  136380. 6,
  136381. 1,
  136382. 7,
  136383. 0,
  136384. 8,
  136385. };
  136386. static long _vq_lengthlist__44c0_sm_p4_0[] = {
  136387. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  136388. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  136389. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  136390. 9, 9, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  136391. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  136392. 11,
  136393. };
  136394. static float _vq_quantthresh__44c0_sm_p4_0[] = {
  136395. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136396. };
  136397. static long _vq_quantmap__44c0_sm_p4_0[] = {
  136398. 7, 5, 3, 1, 0, 2, 4, 6,
  136399. 8,
  136400. };
  136401. static encode_aux_threshmatch _vq_auxt__44c0_sm_p4_0 = {
  136402. _vq_quantthresh__44c0_sm_p4_0,
  136403. _vq_quantmap__44c0_sm_p4_0,
  136404. 9,
  136405. 9
  136406. };
  136407. static static_codebook _44c0_sm_p4_0 = {
  136408. 2, 81,
  136409. _vq_lengthlist__44c0_sm_p4_0,
  136410. 1, -531628032, 1611661312, 4, 0,
  136411. _vq_quantlist__44c0_sm_p4_0,
  136412. NULL,
  136413. &_vq_auxt__44c0_sm_p4_0,
  136414. NULL,
  136415. 0
  136416. };
  136417. static long _vq_quantlist__44c0_sm_p5_0[] = {
  136418. 8,
  136419. 7,
  136420. 9,
  136421. 6,
  136422. 10,
  136423. 5,
  136424. 11,
  136425. 4,
  136426. 12,
  136427. 3,
  136428. 13,
  136429. 2,
  136430. 14,
  136431. 1,
  136432. 15,
  136433. 0,
  136434. 16,
  136435. };
  136436. static long _vq_lengthlist__44c0_sm_p5_0[] = {
  136437. 1, 4, 4, 6, 6, 8, 8, 8, 8, 8, 8, 9, 9,10,10,11,
  136438. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  136439. 11,11, 0, 5, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  136440. 11,11,11, 0, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  136441. 11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,
  136442. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  136443. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  136444. 10,11,11,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  136445. 10,10,11,11,12,12,12,13, 0, 0, 0, 0, 0, 9, 9,10,
  136446. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  136447. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  136448. 9,10,10,11,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  136449. 10,10,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0,
  136450. 0, 0, 0,10,10,11,11,12,12,12,13,13,13, 0, 0, 0,
  136451. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  136452. 0, 0, 0, 0, 0,11,11,12,11,12,12,13,13,13,13, 0,
  136453. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  136454. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  136455. 14,
  136456. };
  136457. static float _vq_quantthresh__44c0_sm_p5_0[] = {
  136458. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136459. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136460. };
  136461. static long _vq_quantmap__44c0_sm_p5_0[] = {
  136462. 15, 13, 11, 9, 7, 5, 3, 1,
  136463. 0, 2, 4, 6, 8, 10, 12, 14,
  136464. 16,
  136465. };
  136466. static encode_aux_threshmatch _vq_auxt__44c0_sm_p5_0 = {
  136467. _vq_quantthresh__44c0_sm_p5_0,
  136468. _vq_quantmap__44c0_sm_p5_0,
  136469. 17,
  136470. 17
  136471. };
  136472. static static_codebook _44c0_sm_p5_0 = {
  136473. 2, 289,
  136474. _vq_lengthlist__44c0_sm_p5_0,
  136475. 1, -529530880, 1611661312, 5, 0,
  136476. _vq_quantlist__44c0_sm_p5_0,
  136477. NULL,
  136478. &_vq_auxt__44c0_sm_p5_0,
  136479. NULL,
  136480. 0
  136481. };
  136482. static long _vq_quantlist__44c0_sm_p6_0[] = {
  136483. 1,
  136484. 0,
  136485. 2,
  136486. };
  136487. static long _vq_lengthlist__44c0_sm_p6_0[] = {
  136488. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  136489. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  136490. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  136491. 11,10,11,11,10,10, 7,11,10,11,11,11,11,11,11, 6,
  136492. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  136493. 11,
  136494. };
  136495. static float _vq_quantthresh__44c0_sm_p6_0[] = {
  136496. -5.5, 5.5,
  136497. };
  136498. static long _vq_quantmap__44c0_sm_p6_0[] = {
  136499. 1, 0, 2,
  136500. };
  136501. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_0 = {
  136502. _vq_quantthresh__44c0_sm_p6_0,
  136503. _vq_quantmap__44c0_sm_p6_0,
  136504. 3,
  136505. 3
  136506. };
  136507. static static_codebook _44c0_sm_p6_0 = {
  136508. 4, 81,
  136509. _vq_lengthlist__44c0_sm_p6_0,
  136510. 1, -529137664, 1618345984, 2, 0,
  136511. _vq_quantlist__44c0_sm_p6_0,
  136512. NULL,
  136513. &_vq_auxt__44c0_sm_p6_0,
  136514. NULL,
  136515. 0
  136516. };
  136517. static long _vq_quantlist__44c0_sm_p6_1[] = {
  136518. 5,
  136519. 4,
  136520. 6,
  136521. 3,
  136522. 7,
  136523. 2,
  136524. 8,
  136525. 1,
  136526. 9,
  136527. 0,
  136528. 10,
  136529. };
  136530. static long _vq_lengthlist__44c0_sm_p6_1[] = {
  136531. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 8, 9, 5, 5, 6, 6,
  136532. 7, 7, 8, 8, 8, 8, 9, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  136533. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  136534. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  136535. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  136536. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  136537. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  136538. 10,10,10, 8, 8, 8, 8, 8, 8,
  136539. };
  136540. static float _vq_quantthresh__44c0_sm_p6_1[] = {
  136541. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  136542. 3.5, 4.5,
  136543. };
  136544. static long _vq_quantmap__44c0_sm_p6_1[] = {
  136545. 9, 7, 5, 3, 1, 0, 2, 4,
  136546. 6, 8, 10,
  136547. };
  136548. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_1 = {
  136549. _vq_quantthresh__44c0_sm_p6_1,
  136550. _vq_quantmap__44c0_sm_p6_1,
  136551. 11,
  136552. 11
  136553. };
  136554. static static_codebook _44c0_sm_p6_1 = {
  136555. 2, 121,
  136556. _vq_lengthlist__44c0_sm_p6_1,
  136557. 1, -531365888, 1611661312, 4, 0,
  136558. _vq_quantlist__44c0_sm_p6_1,
  136559. NULL,
  136560. &_vq_auxt__44c0_sm_p6_1,
  136561. NULL,
  136562. 0
  136563. };
  136564. static long _vq_quantlist__44c0_sm_p7_0[] = {
  136565. 6,
  136566. 5,
  136567. 7,
  136568. 4,
  136569. 8,
  136570. 3,
  136571. 9,
  136572. 2,
  136573. 10,
  136574. 1,
  136575. 11,
  136576. 0,
  136577. 12,
  136578. };
  136579. static long _vq_lengthlist__44c0_sm_p7_0[] = {
  136580. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  136581. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  136582. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  136583. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  136584. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  136585. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0, 9,10,
  136586. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  136587. 11,12,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  136588. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  136589. 0, 0, 0, 0,11,12,11,11,13,12,13,13, 0, 0, 0, 0,
  136590. 0,12,12,11,11,13,12,14,14,
  136591. };
  136592. static float _vq_quantthresh__44c0_sm_p7_0[] = {
  136593. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  136594. 12.5, 17.5, 22.5, 27.5,
  136595. };
  136596. static long _vq_quantmap__44c0_sm_p7_0[] = {
  136597. 11, 9, 7, 5, 3, 1, 0, 2,
  136598. 4, 6, 8, 10, 12,
  136599. };
  136600. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_0 = {
  136601. _vq_quantthresh__44c0_sm_p7_0,
  136602. _vq_quantmap__44c0_sm_p7_0,
  136603. 13,
  136604. 13
  136605. };
  136606. static static_codebook _44c0_sm_p7_0 = {
  136607. 2, 169,
  136608. _vq_lengthlist__44c0_sm_p7_0,
  136609. 1, -526516224, 1616117760, 4, 0,
  136610. _vq_quantlist__44c0_sm_p7_0,
  136611. NULL,
  136612. &_vq_auxt__44c0_sm_p7_0,
  136613. NULL,
  136614. 0
  136615. };
  136616. static long _vq_quantlist__44c0_sm_p7_1[] = {
  136617. 2,
  136618. 1,
  136619. 3,
  136620. 0,
  136621. 4,
  136622. };
  136623. static long _vq_lengthlist__44c0_sm_p7_1[] = {
  136624. 2, 4, 4, 4, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  136625. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  136626. };
  136627. static float _vq_quantthresh__44c0_sm_p7_1[] = {
  136628. -1.5, -0.5, 0.5, 1.5,
  136629. };
  136630. static long _vq_quantmap__44c0_sm_p7_1[] = {
  136631. 3, 1, 0, 2, 4,
  136632. };
  136633. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_1 = {
  136634. _vq_quantthresh__44c0_sm_p7_1,
  136635. _vq_quantmap__44c0_sm_p7_1,
  136636. 5,
  136637. 5
  136638. };
  136639. static static_codebook _44c0_sm_p7_1 = {
  136640. 2, 25,
  136641. _vq_lengthlist__44c0_sm_p7_1,
  136642. 1, -533725184, 1611661312, 3, 0,
  136643. _vq_quantlist__44c0_sm_p7_1,
  136644. NULL,
  136645. &_vq_auxt__44c0_sm_p7_1,
  136646. NULL,
  136647. 0
  136648. };
  136649. static long _vq_quantlist__44c0_sm_p8_0[] = {
  136650. 4,
  136651. 3,
  136652. 5,
  136653. 2,
  136654. 6,
  136655. 1,
  136656. 7,
  136657. 0,
  136658. 8,
  136659. };
  136660. static long _vq_lengthlist__44c0_sm_p8_0[] = {
  136661. 1, 3, 3,11,11,11,11,11,11, 3, 7, 6,11,11,11,11,
  136662. 11,11, 4, 8, 7,11,11,11,11,11,11,11,11,11,11,11,
  136663. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136664. 11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  136665. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  136666. 12,
  136667. };
  136668. static float _vq_quantthresh__44c0_sm_p8_0[] = {
  136669. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  136670. };
  136671. static long _vq_quantmap__44c0_sm_p8_0[] = {
  136672. 7, 5, 3, 1, 0, 2, 4, 6,
  136673. 8,
  136674. };
  136675. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_0 = {
  136676. _vq_quantthresh__44c0_sm_p8_0,
  136677. _vq_quantmap__44c0_sm_p8_0,
  136678. 9,
  136679. 9
  136680. };
  136681. static static_codebook _44c0_sm_p8_0 = {
  136682. 2, 81,
  136683. _vq_lengthlist__44c0_sm_p8_0,
  136684. 1, -516186112, 1627103232, 4, 0,
  136685. _vq_quantlist__44c0_sm_p8_0,
  136686. NULL,
  136687. &_vq_auxt__44c0_sm_p8_0,
  136688. NULL,
  136689. 0
  136690. };
  136691. static long _vq_quantlist__44c0_sm_p8_1[] = {
  136692. 6,
  136693. 5,
  136694. 7,
  136695. 4,
  136696. 8,
  136697. 3,
  136698. 9,
  136699. 2,
  136700. 10,
  136701. 1,
  136702. 11,
  136703. 0,
  136704. 12,
  136705. };
  136706. static long _vq_lengthlist__44c0_sm_p8_1[] = {
  136707. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  136708. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  136709. 8,10,10,12,11,12,12,17, 7, 7, 8, 8, 9, 9,10,10,
  136710. 12,12,13,13,18, 7, 7, 8, 7, 9, 9,10,10,12,12,12,
  136711. 13,19,10,10, 8, 8,10,10,11,11,12,12,13,14,19,11,
  136712. 10, 8, 7,10,10,11,11,12,12,13,12,19,19,19,10,10,
  136713. 10,10,11,11,12,12,13,13,19,19,19,11, 9,11, 9,14,
  136714. 12,13,12,13,13,19,20,18,13,14,11,11,12,12,13,13,
  136715. 14,13,20,20,20,15,13,11,10,13,11,13,13,14,13,20,
  136716. 20,20,20,20,13,14,12,12,13,13,13,13,20,20,20,20,
  136717. 20,13,13,12,12,16,13,15,13,
  136718. };
  136719. static float _vq_quantthresh__44c0_sm_p8_1[] = {
  136720. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  136721. 42.5, 59.5, 76.5, 93.5,
  136722. };
  136723. static long _vq_quantmap__44c0_sm_p8_1[] = {
  136724. 11, 9, 7, 5, 3, 1, 0, 2,
  136725. 4, 6, 8, 10, 12,
  136726. };
  136727. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_1 = {
  136728. _vq_quantthresh__44c0_sm_p8_1,
  136729. _vq_quantmap__44c0_sm_p8_1,
  136730. 13,
  136731. 13
  136732. };
  136733. static static_codebook _44c0_sm_p8_1 = {
  136734. 2, 169,
  136735. _vq_lengthlist__44c0_sm_p8_1,
  136736. 1, -522616832, 1620115456, 4, 0,
  136737. _vq_quantlist__44c0_sm_p8_1,
  136738. NULL,
  136739. &_vq_auxt__44c0_sm_p8_1,
  136740. NULL,
  136741. 0
  136742. };
  136743. static long _vq_quantlist__44c0_sm_p8_2[] = {
  136744. 8,
  136745. 7,
  136746. 9,
  136747. 6,
  136748. 10,
  136749. 5,
  136750. 11,
  136751. 4,
  136752. 12,
  136753. 3,
  136754. 13,
  136755. 2,
  136756. 14,
  136757. 1,
  136758. 15,
  136759. 0,
  136760. 16,
  136761. };
  136762. static long _vq_lengthlist__44c0_sm_p8_2[] = {
  136763. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  136764. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  136765. 9, 9,10, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  136766. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  136767. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  136768. 9,10, 9, 9,10,10,10,11, 8, 8, 8, 8, 9, 9, 9, 9,
  136769. 9, 9, 9,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  136770. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  136771. 9, 9, 9, 9, 9, 9,10,10,10,10,10,11,11, 8, 8, 9,
  136772. 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,11,11,11, 9, 9,
  136773. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,10,11,11, 9,
  136774. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  136775. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,11,11,
  136776. 11,11,11, 9, 9,10, 9, 9, 9, 9, 9, 9, 9,10,11,10,
  136777. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  136778. 11,11,11,11,11, 9,10, 9, 9, 9, 9, 9, 9, 9, 9,11,
  136779. 11,10,11,11,11,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  136780. 10,11,10,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  136781. 9,
  136782. };
  136783. static float _vq_quantthresh__44c0_sm_p8_2[] = {
  136784. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136785. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136786. };
  136787. static long _vq_quantmap__44c0_sm_p8_2[] = {
  136788. 15, 13, 11, 9, 7, 5, 3, 1,
  136789. 0, 2, 4, 6, 8, 10, 12, 14,
  136790. 16,
  136791. };
  136792. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_2 = {
  136793. _vq_quantthresh__44c0_sm_p8_2,
  136794. _vq_quantmap__44c0_sm_p8_2,
  136795. 17,
  136796. 17
  136797. };
  136798. static static_codebook _44c0_sm_p8_2 = {
  136799. 2, 289,
  136800. _vq_lengthlist__44c0_sm_p8_2,
  136801. 1, -529530880, 1611661312, 5, 0,
  136802. _vq_quantlist__44c0_sm_p8_2,
  136803. NULL,
  136804. &_vq_auxt__44c0_sm_p8_2,
  136805. NULL,
  136806. 0
  136807. };
  136808. static long _huff_lengthlist__44c0_sm_short[] = {
  136809. 6, 6,12,13,13,14,16,17,17, 4, 2, 5, 8, 7, 9,12,
  136810. 15,15, 9, 4, 5, 9, 7, 9,12,16,18,11, 6, 7, 4, 6,
  136811. 8,11,14,18,10, 5, 6, 5, 5, 7,10,14,17,10, 5, 7,
  136812. 7, 6, 7,10,13,16,11, 5, 7, 7, 7, 8,10,12,15,13,
  136813. 6, 7, 5, 5, 7, 9,12,13,16, 8, 9, 6, 6, 7, 9,10,
  136814. 12,
  136815. };
  136816. static static_codebook _huff_book__44c0_sm_short = {
  136817. 2, 81,
  136818. _huff_lengthlist__44c0_sm_short,
  136819. 0, 0, 0, 0, 0,
  136820. NULL,
  136821. NULL,
  136822. NULL,
  136823. NULL,
  136824. 0
  136825. };
  136826. static long _huff_lengthlist__44c1_s_long[] = {
  136827. 5, 5, 9,10, 9, 9,10,11,12, 5, 1, 5, 6, 6, 7,10,
  136828. 12,14, 9, 5, 6, 8, 8,10,12,14,14,10, 5, 8, 5, 6,
  136829. 8,11,13,14, 9, 5, 7, 6, 6, 8,10,12,11, 9, 7, 9,
  136830. 7, 6, 6, 7,10,10,10, 9,12, 9, 8, 7, 7,10,12,11,
  136831. 11,13,12,10, 9, 8, 9,11,11,14,15,15,13,11, 9, 9,
  136832. 11,
  136833. };
  136834. static static_codebook _huff_book__44c1_s_long = {
  136835. 2, 81,
  136836. _huff_lengthlist__44c1_s_long,
  136837. 0, 0, 0, 0, 0,
  136838. NULL,
  136839. NULL,
  136840. NULL,
  136841. NULL,
  136842. 0
  136843. };
  136844. static long _vq_quantlist__44c1_s_p1_0[] = {
  136845. 1,
  136846. 0,
  136847. 2,
  136848. };
  136849. static long _vq_lengthlist__44c1_s_p1_0[] = {
  136850. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 6, 0, 0, 0, 0,
  136851. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136855. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  136856. 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136860. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  136861. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  136896. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  136897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  136901. 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  136902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  136906. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  136907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136941. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  136942. 0, 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136946. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8,10, 9, 0,
  136947. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  136948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136951. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  136952. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  136953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137260. 0,
  137261. };
  137262. static float _vq_quantthresh__44c1_s_p1_0[] = {
  137263. -0.5, 0.5,
  137264. };
  137265. static long _vq_quantmap__44c1_s_p1_0[] = {
  137266. 1, 0, 2,
  137267. };
  137268. static encode_aux_threshmatch _vq_auxt__44c1_s_p1_0 = {
  137269. _vq_quantthresh__44c1_s_p1_0,
  137270. _vq_quantmap__44c1_s_p1_0,
  137271. 3,
  137272. 3
  137273. };
  137274. static static_codebook _44c1_s_p1_0 = {
  137275. 8, 6561,
  137276. _vq_lengthlist__44c1_s_p1_0,
  137277. 1, -535822336, 1611661312, 2, 0,
  137278. _vq_quantlist__44c1_s_p1_0,
  137279. NULL,
  137280. &_vq_auxt__44c1_s_p1_0,
  137281. NULL,
  137282. 0
  137283. };
  137284. static long _vq_quantlist__44c1_s_p2_0[] = {
  137285. 2,
  137286. 1,
  137287. 3,
  137288. 0,
  137289. 4,
  137290. };
  137291. static long _vq_lengthlist__44c1_s_p2_0[] = {
  137292. 2, 3, 4, 6, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  137294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137295. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  137297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137298. 0, 0, 0, 0, 6, 6, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  137299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137331. 0,
  137332. };
  137333. static float _vq_quantthresh__44c1_s_p2_0[] = {
  137334. -1.5, -0.5, 0.5, 1.5,
  137335. };
  137336. static long _vq_quantmap__44c1_s_p2_0[] = {
  137337. 3, 1, 0, 2, 4,
  137338. };
  137339. static encode_aux_threshmatch _vq_auxt__44c1_s_p2_0 = {
  137340. _vq_quantthresh__44c1_s_p2_0,
  137341. _vq_quantmap__44c1_s_p2_0,
  137342. 5,
  137343. 5
  137344. };
  137345. static static_codebook _44c1_s_p2_0 = {
  137346. 4, 625,
  137347. _vq_lengthlist__44c1_s_p2_0,
  137348. 1, -533725184, 1611661312, 3, 0,
  137349. _vq_quantlist__44c1_s_p2_0,
  137350. NULL,
  137351. &_vq_auxt__44c1_s_p2_0,
  137352. NULL,
  137353. 0
  137354. };
  137355. static long _vq_quantlist__44c1_s_p3_0[] = {
  137356. 4,
  137357. 3,
  137358. 5,
  137359. 2,
  137360. 6,
  137361. 1,
  137362. 7,
  137363. 0,
  137364. 8,
  137365. };
  137366. static long _vq_lengthlist__44c1_s_p3_0[] = {
  137367. 1, 3, 2, 7, 7, 0, 0, 0, 0, 0,13,13, 6, 6, 0, 0,
  137368. 0, 0, 0,12, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  137369. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  137370. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  137371. 0, 0,11,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137372. 0,
  137373. };
  137374. static float _vq_quantthresh__44c1_s_p3_0[] = {
  137375. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137376. };
  137377. static long _vq_quantmap__44c1_s_p3_0[] = {
  137378. 7, 5, 3, 1, 0, 2, 4, 6,
  137379. 8,
  137380. };
  137381. static encode_aux_threshmatch _vq_auxt__44c1_s_p3_0 = {
  137382. _vq_quantthresh__44c1_s_p3_0,
  137383. _vq_quantmap__44c1_s_p3_0,
  137384. 9,
  137385. 9
  137386. };
  137387. static static_codebook _44c1_s_p3_0 = {
  137388. 2, 81,
  137389. _vq_lengthlist__44c1_s_p3_0,
  137390. 1, -531628032, 1611661312, 4, 0,
  137391. _vq_quantlist__44c1_s_p3_0,
  137392. NULL,
  137393. &_vq_auxt__44c1_s_p3_0,
  137394. NULL,
  137395. 0
  137396. };
  137397. static long _vq_quantlist__44c1_s_p4_0[] = {
  137398. 4,
  137399. 3,
  137400. 5,
  137401. 2,
  137402. 6,
  137403. 1,
  137404. 7,
  137405. 0,
  137406. 8,
  137407. };
  137408. static long _vq_lengthlist__44c1_s_p4_0[] = {
  137409. 1, 3, 3, 6, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  137410. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  137411. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  137412. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  137413. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  137414. 11,
  137415. };
  137416. static float _vq_quantthresh__44c1_s_p4_0[] = {
  137417. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137418. };
  137419. static long _vq_quantmap__44c1_s_p4_0[] = {
  137420. 7, 5, 3, 1, 0, 2, 4, 6,
  137421. 8,
  137422. };
  137423. static encode_aux_threshmatch _vq_auxt__44c1_s_p4_0 = {
  137424. _vq_quantthresh__44c1_s_p4_0,
  137425. _vq_quantmap__44c1_s_p4_0,
  137426. 9,
  137427. 9
  137428. };
  137429. static static_codebook _44c1_s_p4_0 = {
  137430. 2, 81,
  137431. _vq_lengthlist__44c1_s_p4_0,
  137432. 1, -531628032, 1611661312, 4, 0,
  137433. _vq_quantlist__44c1_s_p4_0,
  137434. NULL,
  137435. &_vq_auxt__44c1_s_p4_0,
  137436. NULL,
  137437. 0
  137438. };
  137439. static long _vq_quantlist__44c1_s_p5_0[] = {
  137440. 8,
  137441. 7,
  137442. 9,
  137443. 6,
  137444. 10,
  137445. 5,
  137446. 11,
  137447. 4,
  137448. 12,
  137449. 3,
  137450. 13,
  137451. 2,
  137452. 14,
  137453. 1,
  137454. 15,
  137455. 0,
  137456. 16,
  137457. };
  137458. static long _vq_lengthlist__44c1_s_p5_0[] = {
  137459. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  137460. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  137461. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  137462. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  137463. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  137464. 10,11,11,12,11, 0, 0, 0, 8, 8, 9, 9, 9,10,10,10,
  137465. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10, 9,10,
  137466. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  137467. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  137468. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  137469. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  137470. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  137471. 10,10,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  137472. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  137473. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13, 0, 0,
  137474. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  137475. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,14,14,
  137476. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  137477. 14,
  137478. };
  137479. static float _vq_quantthresh__44c1_s_p5_0[] = {
  137480. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137481. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137482. };
  137483. static long _vq_quantmap__44c1_s_p5_0[] = {
  137484. 15, 13, 11, 9, 7, 5, 3, 1,
  137485. 0, 2, 4, 6, 8, 10, 12, 14,
  137486. 16,
  137487. };
  137488. static encode_aux_threshmatch _vq_auxt__44c1_s_p5_0 = {
  137489. _vq_quantthresh__44c1_s_p5_0,
  137490. _vq_quantmap__44c1_s_p5_0,
  137491. 17,
  137492. 17
  137493. };
  137494. static static_codebook _44c1_s_p5_0 = {
  137495. 2, 289,
  137496. _vq_lengthlist__44c1_s_p5_0,
  137497. 1, -529530880, 1611661312, 5, 0,
  137498. _vq_quantlist__44c1_s_p5_0,
  137499. NULL,
  137500. &_vq_auxt__44c1_s_p5_0,
  137501. NULL,
  137502. 0
  137503. };
  137504. static long _vq_quantlist__44c1_s_p6_0[] = {
  137505. 1,
  137506. 0,
  137507. 2,
  137508. };
  137509. static long _vq_lengthlist__44c1_s_p6_0[] = {
  137510. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  137511. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 6,10,10,11,11,
  137512. 11,11,10,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  137513. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 7,
  137514. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,12,10,
  137515. 11,
  137516. };
  137517. static float _vq_quantthresh__44c1_s_p6_0[] = {
  137518. -5.5, 5.5,
  137519. };
  137520. static long _vq_quantmap__44c1_s_p6_0[] = {
  137521. 1, 0, 2,
  137522. };
  137523. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_0 = {
  137524. _vq_quantthresh__44c1_s_p6_0,
  137525. _vq_quantmap__44c1_s_p6_0,
  137526. 3,
  137527. 3
  137528. };
  137529. static static_codebook _44c1_s_p6_0 = {
  137530. 4, 81,
  137531. _vq_lengthlist__44c1_s_p6_0,
  137532. 1, -529137664, 1618345984, 2, 0,
  137533. _vq_quantlist__44c1_s_p6_0,
  137534. NULL,
  137535. &_vq_auxt__44c1_s_p6_0,
  137536. NULL,
  137537. 0
  137538. };
  137539. static long _vq_quantlist__44c1_s_p6_1[] = {
  137540. 5,
  137541. 4,
  137542. 6,
  137543. 3,
  137544. 7,
  137545. 2,
  137546. 8,
  137547. 1,
  137548. 9,
  137549. 0,
  137550. 10,
  137551. };
  137552. static long _vq_lengthlist__44c1_s_p6_1[] = {
  137553. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  137554. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  137555. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  137556. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  137557. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  137558. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  137559. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  137560. 10,10,10, 8, 8, 8, 8, 8, 8,
  137561. };
  137562. static float _vq_quantthresh__44c1_s_p6_1[] = {
  137563. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  137564. 3.5, 4.5,
  137565. };
  137566. static long _vq_quantmap__44c1_s_p6_1[] = {
  137567. 9, 7, 5, 3, 1, 0, 2, 4,
  137568. 6, 8, 10,
  137569. };
  137570. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_1 = {
  137571. _vq_quantthresh__44c1_s_p6_1,
  137572. _vq_quantmap__44c1_s_p6_1,
  137573. 11,
  137574. 11
  137575. };
  137576. static static_codebook _44c1_s_p6_1 = {
  137577. 2, 121,
  137578. _vq_lengthlist__44c1_s_p6_1,
  137579. 1, -531365888, 1611661312, 4, 0,
  137580. _vq_quantlist__44c1_s_p6_1,
  137581. NULL,
  137582. &_vq_auxt__44c1_s_p6_1,
  137583. NULL,
  137584. 0
  137585. };
  137586. static long _vq_quantlist__44c1_s_p7_0[] = {
  137587. 6,
  137588. 5,
  137589. 7,
  137590. 4,
  137591. 8,
  137592. 3,
  137593. 9,
  137594. 2,
  137595. 10,
  137596. 1,
  137597. 11,
  137598. 0,
  137599. 12,
  137600. };
  137601. static long _vq_lengthlist__44c1_s_p7_0[] = {
  137602. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 9, 7, 5, 6,
  137603. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  137604. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  137605. 10,10,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  137606. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,11, 0,13,
  137607. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  137608. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10,10, 9,11,
  137609. 11,12,11,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  137610. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  137611. 0, 0, 0, 0,11,12,11,11,12,12,14,13, 0, 0, 0, 0,
  137612. 0,12,11,11,11,13,10,14,13,
  137613. };
  137614. static float _vq_quantthresh__44c1_s_p7_0[] = {
  137615. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  137616. 12.5, 17.5, 22.5, 27.5,
  137617. };
  137618. static long _vq_quantmap__44c1_s_p7_0[] = {
  137619. 11, 9, 7, 5, 3, 1, 0, 2,
  137620. 4, 6, 8, 10, 12,
  137621. };
  137622. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_0 = {
  137623. _vq_quantthresh__44c1_s_p7_0,
  137624. _vq_quantmap__44c1_s_p7_0,
  137625. 13,
  137626. 13
  137627. };
  137628. static static_codebook _44c1_s_p7_0 = {
  137629. 2, 169,
  137630. _vq_lengthlist__44c1_s_p7_0,
  137631. 1, -526516224, 1616117760, 4, 0,
  137632. _vq_quantlist__44c1_s_p7_0,
  137633. NULL,
  137634. &_vq_auxt__44c1_s_p7_0,
  137635. NULL,
  137636. 0
  137637. };
  137638. static long _vq_quantlist__44c1_s_p7_1[] = {
  137639. 2,
  137640. 1,
  137641. 3,
  137642. 0,
  137643. 4,
  137644. };
  137645. static long _vq_lengthlist__44c1_s_p7_1[] = {
  137646. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  137647. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  137648. };
  137649. static float _vq_quantthresh__44c1_s_p7_1[] = {
  137650. -1.5, -0.5, 0.5, 1.5,
  137651. };
  137652. static long _vq_quantmap__44c1_s_p7_1[] = {
  137653. 3, 1, 0, 2, 4,
  137654. };
  137655. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_1 = {
  137656. _vq_quantthresh__44c1_s_p7_1,
  137657. _vq_quantmap__44c1_s_p7_1,
  137658. 5,
  137659. 5
  137660. };
  137661. static static_codebook _44c1_s_p7_1 = {
  137662. 2, 25,
  137663. _vq_lengthlist__44c1_s_p7_1,
  137664. 1, -533725184, 1611661312, 3, 0,
  137665. _vq_quantlist__44c1_s_p7_1,
  137666. NULL,
  137667. &_vq_auxt__44c1_s_p7_1,
  137668. NULL,
  137669. 0
  137670. };
  137671. static long _vq_quantlist__44c1_s_p8_0[] = {
  137672. 6,
  137673. 5,
  137674. 7,
  137675. 4,
  137676. 8,
  137677. 3,
  137678. 9,
  137679. 2,
  137680. 10,
  137681. 1,
  137682. 11,
  137683. 0,
  137684. 12,
  137685. };
  137686. static long _vq_lengthlist__44c1_s_p8_0[] = {
  137687. 1, 4, 3,10,10,10,10,10,10,10,10,10,10, 4, 8, 6,
  137688. 10,10,10,10,10,10,10,10,10,10, 4, 8, 7,10,10,10,
  137689. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  137690. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  137691. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  137692. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  137693. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  137694. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  137695. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  137696. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  137697. 10,10,10,10,10,10,10,10,10,
  137698. };
  137699. static float _vq_quantthresh__44c1_s_p8_0[] = {
  137700. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  137701. 552.5, 773.5, 994.5, 1215.5,
  137702. };
  137703. static long _vq_quantmap__44c1_s_p8_0[] = {
  137704. 11, 9, 7, 5, 3, 1, 0, 2,
  137705. 4, 6, 8, 10, 12,
  137706. };
  137707. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_0 = {
  137708. _vq_quantthresh__44c1_s_p8_0,
  137709. _vq_quantmap__44c1_s_p8_0,
  137710. 13,
  137711. 13
  137712. };
  137713. static static_codebook _44c1_s_p8_0 = {
  137714. 2, 169,
  137715. _vq_lengthlist__44c1_s_p8_0,
  137716. 1, -514541568, 1627103232, 4, 0,
  137717. _vq_quantlist__44c1_s_p8_0,
  137718. NULL,
  137719. &_vq_auxt__44c1_s_p8_0,
  137720. NULL,
  137721. 0
  137722. };
  137723. static long _vq_quantlist__44c1_s_p8_1[] = {
  137724. 6,
  137725. 5,
  137726. 7,
  137727. 4,
  137728. 8,
  137729. 3,
  137730. 9,
  137731. 2,
  137732. 10,
  137733. 1,
  137734. 11,
  137735. 0,
  137736. 12,
  137737. };
  137738. static long _vq_lengthlist__44c1_s_p8_1[] = {
  137739. 1, 4, 4, 6, 5, 7, 7, 9, 9,10,10,12,12, 6, 5, 5,
  137740. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  137741. 8,10,10,11,11,12,12,15, 7, 7, 8, 8, 9, 9,11,11,
  137742. 12,12,13,12,15, 8, 8, 8, 7, 9, 9,10,10,12,12,13,
  137743. 13,16,11,10, 8, 8,10,10,11,11,12,12,13,13,16,11,
  137744. 11, 9, 8,11,10,11,11,12,12,13,12,16,16,16,10,11,
  137745. 10,11,12,12,12,12,13,13,16,16,16,11, 9,11, 9,14,
  137746. 12,12,12,13,13,16,16,16,12,14,11,12,12,12,13,13,
  137747. 14,13,16,16,16,15,13,12,10,13,10,13,14,13,13,16,
  137748. 16,16,16,16,13,14,12,13,13,12,13,13,16,16,16,16,
  137749. 16,13,12,12,11,14,12,15,13,
  137750. };
  137751. static float _vq_quantthresh__44c1_s_p8_1[] = {
  137752. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  137753. 42.5, 59.5, 76.5, 93.5,
  137754. };
  137755. static long _vq_quantmap__44c1_s_p8_1[] = {
  137756. 11, 9, 7, 5, 3, 1, 0, 2,
  137757. 4, 6, 8, 10, 12,
  137758. };
  137759. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_1 = {
  137760. _vq_quantthresh__44c1_s_p8_1,
  137761. _vq_quantmap__44c1_s_p8_1,
  137762. 13,
  137763. 13
  137764. };
  137765. static static_codebook _44c1_s_p8_1 = {
  137766. 2, 169,
  137767. _vq_lengthlist__44c1_s_p8_1,
  137768. 1, -522616832, 1620115456, 4, 0,
  137769. _vq_quantlist__44c1_s_p8_1,
  137770. NULL,
  137771. &_vq_auxt__44c1_s_p8_1,
  137772. NULL,
  137773. 0
  137774. };
  137775. static long _vq_quantlist__44c1_s_p8_2[] = {
  137776. 8,
  137777. 7,
  137778. 9,
  137779. 6,
  137780. 10,
  137781. 5,
  137782. 11,
  137783. 4,
  137784. 12,
  137785. 3,
  137786. 13,
  137787. 2,
  137788. 14,
  137789. 1,
  137790. 15,
  137791. 0,
  137792. 16,
  137793. };
  137794. static long _vq_lengthlist__44c1_s_p8_2[] = {
  137795. 2, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  137796. 8,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  137797. 9, 9,10,10,10, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  137798. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  137799. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  137800. 9,10, 9, 9,10,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  137801. 9, 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  137802. 9, 9, 9, 9, 9,10,10,11,11,11, 8, 8, 9, 9, 9, 9,
  137803. 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11, 8, 8, 9,
  137804. 9, 9, 9,10, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  137805. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 9,
  137806. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  137807. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10,11,11,
  137808. 11,11,11, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,10,11,11,
  137809. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  137810. 11,11,11,11,11, 9,10, 9, 9, 9, 9,10, 9, 9, 9,11,
  137811. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  137812. 11,11,10,11,11,11,11,10,11, 9, 9, 9, 9, 9, 9, 9,
  137813. 9,
  137814. };
  137815. static float _vq_quantthresh__44c1_s_p8_2[] = {
  137816. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137817. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137818. };
  137819. static long _vq_quantmap__44c1_s_p8_2[] = {
  137820. 15, 13, 11, 9, 7, 5, 3, 1,
  137821. 0, 2, 4, 6, 8, 10, 12, 14,
  137822. 16,
  137823. };
  137824. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_2 = {
  137825. _vq_quantthresh__44c1_s_p8_2,
  137826. _vq_quantmap__44c1_s_p8_2,
  137827. 17,
  137828. 17
  137829. };
  137830. static static_codebook _44c1_s_p8_2 = {
  137831. 2, 289,
  137832. _vq_lengthlist__44c1_s_p8_2,
  137833. 1, -529530880, 1611661312, 5, 0,
  137834. _vq_quantlist__44c1_s_p8_2,
  137835. NULL,
  137836. &_vq_auxt__44c1_s_p8_2,
  137837. NULL,
  137838. 0
  137839. };
  137840. static long _huff_lengthlist__44c1_s_short[] = {
  137841. 6, 8,13,12,13,14,15,16,16, 4, 2, 4, 7, 6, 8,11,
  137842. 13,15,10, 4, 4, 8, 6, 8,11,14,17,11, 5, 6, 5, 6,
  137843. 8,12,14,17,11, 5, 5, 6, 5, 7,10,13,16,12, 6, 7,
  137844. 8, 7, 8,10,13,15,13, 8, 8, 7, 7, 8,10,12,15,15,
  137845. 7, 7, 5, 5, 7, 9,12,14,15, 8, 8, 6, 6, 7, 8,10,
  137846. 11,
  137847. };
  137848. static static_codebook _huff_book__44c1_s_short = {
  137849. 2, 81,
  137850. _huff_lengthlist__44c1_s_short,
  137851. 0, 0, 0, 0, 0,
  137852. NULL,
  137853. NULL,
  137854. NULL,
  137855. NULL,
  137856. 0
  137857. };
  137858. static long _huff_lengthlist__44c1_sm_long[] = {
  137859. 5, 4, 8,10, 9, 9,10,11,12, 4, 2, 5, 6, 6, 8,10,
  137860. 11,13, 8, 4, 6, 8, 7, 9,12,12,14,10, 6, 8, 4, 5,
  137861. 6, 9,11,12, 9, 5, 6, 5, 5, 6, 9,11,11, 9, 7, 9,
  137862. 6, 5, 5, 7,10,10,10, 9,11, 8, 7, 6, 7, 9,11,11,
  137863. 12,13,10,10, 9, 8, 9,11,11,15,15,12,13,11, 9,10,
  137864. 11,
  137865. };
  137866. static static_codebook _huff_book__44c1_sm_long = {
  137867. 2, 81,
  137868. _huff_lengthlist__44c1_sm_long,
  137869. 0, 0, 0, 0, 0,
  137870. NULL,
  137871. NULL,
  137872. NULL,
  137873. NULL,
  137874. 0
  137875. };
  137876. static long _vq_quantlist__44c1_sm_p1_0[] = {
  137877. 1,
  137878. 0,
  137879. 2,
  137880. };
  137881. static long _vq_lengthlist__44c1_sm_p1_0[] = {
  137882. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  137883. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137887. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  137888. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137892. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  137893. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  137928. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  137929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  137933. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  137934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  137938. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  137939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137973. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  137974. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137978. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  137979. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  137980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137983. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  137984. 0, 0, 0, 0, 0, 0, 9,10, 9, 0, 0, 0, 0, 0, 0, 0,
  137985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138292. 0,
  138293. };
  138294. static float _vq_quantthresh__44c1_sm_p1_0[] = {
  138295. -0.5, 0.5,
  138296. };
  138297. static long _vq_quantmap__44c1_sm_p1_0[] = {
  138298. 1, 0, 2,
  138299. };
  138300. static encode_aux_threshmatch _vq_auxt__44c1_sm_p1_0 = {
  138301. _vq_quantthresh__44c1_sm_p1_0,
  138302. _vq_quantmap__44c1_sm_p1_0,
  138303. 3,
  138304. 3
  138305. };
  138306. static static_codebook _44c1_sm_p1_0 = {
  138307. 8, 6561,
  138308. _vq_lengthlist__44c1_sm_p1_0,
  138309. 1, -535822336, 1611661312, 2, 0,
  138310. _vq_quantlist__44c1_sm_p1_0,
  138311. NULL,
  138312. &_vq_auxt__44c1_sm_p1_0,
  138313. NULL,
  138314. 0
  138315. };
  138316. static long _vq_quantlist__44c1_sm_p2_0[] = {
  138317. 2,
  138318. 1,
  138319. 3,
  138320. 0,
  138321. 4,
  138322. };
  138323. static long _vq_lengthlist__44c1_sm_p2_0[] = {
  138324. 2, 3, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  138326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138327. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  138329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138330. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  138331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138363. 0,
  138364. };
  138365. static float _vq_quantthresh__44c1_sm_p2_0[] = {
  138366. -1.5, -0.5, 0.5, 1.5,
  138367. };
  138368. static long _vq_quantmap__44c1_sm_p2_0[] = {
  138369. 3, 1, 0, 2, 4,
  138370. };
  138371. static encode_aux_threshmatch _vq_auxt__44c1_sm_p2_0 = {
  138372. _vq_quantthresh__44c1_sm_p2_0,
  138373. _vq_quantmap__44c1_sm_p2_0,
  138374. 5,
  138375. 5
  138376. };
  138377. static static_codebook _44c1_sm_p2_0 = {
  138378. 4, 625,
  138379. _vq_lengthlist__44c1_sm_p2_0,
  138380. 1, -533725184, 1611661312, 3, 0,
  138381. _vq_quantlist__44c1_sm_p2_0,
  138382. NULL,
  138383. &_vq_auxt__44c1_sm_p2_0,
  138384. NULL,
  138385. 0
  138386. };
  138387. static long _vq_quantlist__44c1_sm_p3_0[] = {
  138388. 4,
  138389. 3,
  138390. 5,
  138391. 2,
  138392. 6,
  138393. 1,
  138394. 7,
  138395. 0,
  138396. 8,
  138397. };
  138398. static long _vq_lengthlist__44c1_sm_p3_0[] = {
  138399. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 5, 6, 6, 0, 0,
  138400. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 7, 7, 7, 7,
  138401. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  138402. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  138403. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138404. 0,
  138405. };
  138406. static float _vq_quantthresh__44c1_sm_p3_0[] = {
  138407. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138408. };
  138409. static long _vq_quantmap__44c1_sm_p3_0[] = {
  138410. 7, 5, 3, 1, 0, 2, 4, 6,
  138411. 8,
  138412. };
  138413. static encode_aux_threshmatch _vq_auxt__44c1_sm_p3_0 = {
  138414. _vq_quantthresh__44c1_sm_p3_0,
  138415. _vq_quantmap__44c1_sm_p3_0,
  138416. 9,
  138417. 9
  138418. };
  138419. static static_codebook _44c1_sm_p3_0 = {
  138420. 2, 81,
  138421. _vq_lengthlist__44c1_sm_p3_0,
  138422. 1, -531628032, 1611661312, 4, 0,
  138423. _vq_quantlist__44c1_sm_p3_0,
  138424. NULL,
  138425. &_vq_auxt__44c1_sm_p3_0,
  138426. NULL,
  138427. 0
  138428. };
  138429. static long _vq_quantlist__44c1_sm_p4_0[] = {
  138430. 4,
  138431. 3,
  138432. 5,
  138433. 2,
  138434. 6,
  138435. 1,
  138436. 7,
  138437. 0,
  138438. 8,
  138439. };
  138440. static long _vq_lengthlist__44c1_sm_p4_0[] = {
  138441. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7, 8, 8,
  138442. 9, 9, 0, 6, 6, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  138443. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  138444. 8, 8, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  138445. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  138446. 11,
  138447. };
  138448. static float _vq_quantthresh__44c1_sm_p4_0[] = {
  138449. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138450. };
  138451. static long _vq_quantmap__44c1_sm_p4_0[] = {
  138452. 7, 5, 3, 1, 0, 2, 4, 6,
  138453. 8,
  138454. };
  138455. static encode_aux_threshmatch _vq_auxt__44c1_sm_p4_0 = {
  138456. _vq_quantthresh__44c1_sm_p4_0,
  138457. _vq_quantmap__44c1_sm_p4_0,
  138458. 9,
  138459. 9
  138460. };
  138461. static static_codebook _44c1_sm_p4_0 = {
  138462. 2, 81,
  138463. _vq_lengthlist__44c1_sm_p4_0,
  138464. 1, -531628032, 1611661312, 4, 0,
  138465. _vq_quantlist__44c1_sm_p4_0,
  138466. NULL,
  138467. &_vq_auxt__44c1_sm_p4_0,
  138468. NULL,
  138469. 0
  138470. };
  138471. static long _vq_quantlist__44c1_sm_p5_0[] = {
  138472. 8,
  138473. 7,
  138474. 9,
  138475. 6,
  138476. 10,
  138477. 5,
  138478. 11,
  138479. 4,
  138480. 12,
  138481. 3,
  138482. 13,
  138483. 2,
  138484. 14,
  138485. 1,
  138486. 15,
  138487. 0,
  138488. 16,
  138489. };
  138490. static long _vq_lengthlist__44c1_sm_p5_0[] = {
  138491. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  138492. 11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  138493. 11,11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  138494. 10,11,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  138495. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  138496. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,10,
  138497. 10,11,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,
  138498. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  138499. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  138500. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  138501. 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  138502. 9, 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  138503. 9, 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  138504. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  138505. 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0, 0,
  138506. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  138507. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14,
  138508. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  138509. 14,
  138510. };
  138511. static float _vq_quantthresh__44c1_sm_p5_0[] = {
  138512. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138513. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138514. };
  138515. static long _vq_quantmap__44c1_sm_p5_0[] = {
  138516. 15, 13, 11, 9, 7, 5, 3, 1,
  138517. 0, 2, 4, 6, 8, 10, 12, 14,
  138518. 16,
  138519. };
  138520. static encode_aux_threshmatch _vq_auxt__44c1_sm_p5_0 = {
  138521. _vq_quantthresh__44c1_sm_p5_0,
  138522. _vq_quantmap__44c1_sm_p5_0,
  138523. 17,
  138524. 17
  138525. };
  138526. static static_codebook _44c1_sm_p5_0 = {
  138527. 2, 289,
  138528. _vq_lengthlist__44c1_sm_p5_0,
  138529. 1, -529530880, 1611661312, 5, 0,
  138530. _vq_quantlist__44c1_sm_p5_0,
  138531. NULL,
  138532. &_vq_auxt__44c1_sm_p5_0,
  138533. NULL,
  138534. 0
  138535. };
  138536. static long _vq_quantlist__44c1_sm_p6_0[] = {
  138537. 1,
  138538. 0,
  138539. 2,
  138540. };
  138541. static long _vq_lengthlist__44c1_sm_p6_0[] = {
  138542. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  138543. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  138544. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  138545. 11,10,11,11,10,10, 7,11,11,11,11,11,11,11,11, 6,
  138546. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,11,10,
  138547. 11,
  138548. };
  138549. static float _vq_quantthresh__44c1_sm_p6_0[] = {
  138550. -5.5, 5.5,
  138551. };
  138552. static long _vq_quantmap__44c1_sm_p6_0[] = {
  138553. 1, 0, 2,
  138554. };
  138555. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_0 = {
  138556. _vq_quantthresh__44c1_sm_p6_0,
  138557. _vq_quantmap__44c1_sm_p6_0,
  138558. 3,
  138559. 3
  138560. };
  138561. static static_codebook _44c1_sm_p6_0 = {
  138562. 4, 81,
  138563. _vq_lengthlist__44c1_sm_p6_0,
  138564. 1, -529137664, 1618345984, 2, 0,
  138565. _vq_quantlist__44c1_sm_p6_0,
  138566. NULL,
  138567. &_vq_auxt__44c1_sm_p6_0,
  138568. NULL,
  138569. 0
  138570. };
  138571. static long _vq_quantlist__44c1_sm_p6_1[] = {
  138572. 5,
  138573. 4,
  138574. 6,
  138575. 3,
  138576. 7,
  138577. 2,
  138578. 8,
  138579. 1,
  138580. 9,
  138581. 0,
  138582. 10,
  138583. };
  138584. static long _vq_lengthlist__44c1_sm_p6_1[] = {
  138585. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  138586. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  138587. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  138588. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  138589. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  138590. 8, 8, 8, 8, 8, 8, 9, 8,10,10,10,10,10, 8, 8, 8,
  138591. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  138592. 10,10,10, 8, 8, 8, 8, 8, 8,
  138593. };
  138594. static float _vq_quantthresh__44c1_sm_p6_1[] = {
  138595. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  138596. 3.5, 4.5,
  138597. };
  138598. static long _vq_quantmap__44c1_sm_p6_1[] = {
  138599. 9, 7, 5, 3, 1, 0, 2, 4,
  138600. 6, 8, 10,
  138601. };
  138602. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_1 = {
  138603. _vq_quantthresh__44c1_sm_p6_1,
  138604. _vq_quantmap__44c1_sm_p6_1,
  138605. 11,
  138606. 11
  138607. };
  138608. static static_codebook _44c1_sm_p6_1 = {
  138609. 2, 121,
  138610. _vq_lengthlist__44c1_sm_p6_1,
  138611. 1, -531365888, 1611661312, 4, 0,
  138612. _vq_quantlist__44c1_sm_p6_1,
  138613. NULL,
  138614. &_vq_auxt__44c1_sm_p6_1,
  138615. NULL,
  138616. 0
  138617. };
  138618. static long _vq_quantlist__44c1_sm_p7_0[] = {
  138619. 6,
  138620. 5,
  138621. 7,
  138622. 4,
  138623. 8,
  138624. 3,
  138625. 9,
  138626. 2,
  138627. 10,
  138628. 1,
  138629. 11,
  138630. 0,
  138631. 12,
  138632. };
  138633. static long _vq_lengthlist__44c1_sm_p7_0[] = {
  138634. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  138635. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  138636. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  138637. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  138638. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  138639. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0, 9,10,
  138640. 9,10,11,11,12,11,13,12, 0, 0, 0,10,10, 9, 9,11,
  138641. 11,12,12,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  138642. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  138643. 0, 0, 0, 0,11,12,11,11,12,13,14,13, 0, 0, 0, 0,
  138644. 0,12,12,11,11,13,12,14,13,
  138645. };
  138646. static float _vq_quantthresh__44c1_sm_p7_0[] = {
  138647. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  138648. 12.5, 17.5, 22.5, 27.5,
  138649. };
  138650. static long _vq_quantmap__44c1_sm_p7_0[] = {
  138651. 11, 9, 7, 5, 3, 1, 0, 2,
  138652. 4, 6, 8, 10, 12,
  138653. };
  138654. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_0 = {
  138655. _vq_quantthresh__44c1_sm_p7_0,
  138656. _vq_quantmap__44c1_sm_p7_0,
  138657. 13,
  138658. 13
  138659. };
  138660. static static_codebook _44c1_sm_p7_0 = {
  138661. 2, 169,
  138662. _vq_lengthlist__44c1_sm_p7_0,
  138663. 1, -526516224, 1616117760, 4, 0,
  138664. _vq_quantlist__44c1_sm_p7_0,
  138665. NULL,
  138666. &_vq_auxt__44c1_sm_p7_0,
  138667. NULL,
  138668. 0
  138669. };
  138670. static long _vq_quantlist__44c1_sm_p7_1[] = {
  138671. 2,
  138672. 1,
  138673. 3,
  138674. 0,
  138675. 4,
  138676. };
  138677. static long _vq_lengthlist__44c1_sm_p7_1[] = {
  138678. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  138679. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  138680. };
  138681. static float _vq_quantthresh__44c1_sm_p7_1[] = {
  138682. -1.5, -0.5, 0.5, 1.5,
  138683. };
  138684. static long _vq_quantmap__44c1_sm_p7_1[] = {
  138685. 3, 1, 0, 2, 4,
  138686. };
  138687. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_1 = {
  138688. _vq_quantthresh__44c1_sm_p7_1,
  138689. _vq_quantmap__44c1_sm_p7_1,
  138690. 5,
  138691. 5
  138692. };
  138693. static static_codebook _44c1_sm_p7_1 = {
  138694. 2, 25,
  138695. _vq_lengthlist__44c1_sm_p7_1,
  138696. 1, -533725184, 1611661312, 3, 0,
  138697. _vq_quantlist__44c1_sm_p7_1,
  138698. NULL,
  138699. &_vq_auxt__44c1_sm_p7_1,
  138700. NULL,
  138701. 0
  138702. };
  138703. static long _vq_quantlist__44c1_sm_p8_0[] = {
  138704. 6,
  138705. 5,
  138706. 7,
  138707. 4,
  138708. 8,
  138709. 3,
  138710. 9,
  138711. 2,
  138712. 10,
  138713. 1,
  138714. 11,
  138715. 0,
  138716. 12,
  138717. };
  138718. static long _vq_lengthlist__44c1_sm_p8_0[] = {
  138719. 1, 3, 3,13,13,13,13,13,13,13,13,13,13, 3, 6, 6,
  138720. 13,13,13,13,13,13,13,13,13,13, 4, 8, 7,13,13,13,
  138721. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  138722. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  138723. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  138724. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  138725. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  138726. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  138727. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  138728. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  138729. 13,13,13,13,13,13,13,13,13,
  138730. };
  138731. static float _vq_quantthresh__44c1_sm_p8_0[] = {
  138732. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  138733. 552.5, 773.5, 994.5, 1215.5,
  138734. };
  138735. static long _vq_quantmap__44c1_sm_p8_0[] = {
  138736. 11, 9, 7, 5, 3, 1, 0, 2,
  138737. 4, 6, 8, 10, 12,
  138738. };
  138739. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_0 = {
  138740. _vq_quantthresh__44c1_sm_p8_0,
  138741. _vq_quantmap__44c1_sm_p8_0,
  138742. 13,
  138743. 13
  138744. };
  138745. static static_codebook _44c1_sm_p8_0 = {
  138746. 2, 169,
  138747. _vq_lengthlist__44c1_sm_p8_0,
  138748. 1, -514541568, 1627103232, 4, 0,
  138749. _vq_quantlist__44c1_sm_p8_0,
  138750. NULL,
  138751. &_vq_auxt__44c1_sm_p8_0,
  138752. NULL,
  138753. 0
  138754. };
  138755. static long _vq_quantlist__44c1_sm_p8_1[] = {
  138756. 6,
  138757. 5,
  138758. 7,
  138759. 4,
  138760. 8,
  138761. 3,
  138762. 9,
  138763. 2,
  138764. 10,
  138765. 1,
  138766. 11,
  138767. 0,
  138768. 12,
  138769. };
  138770. static long _vq_lengthlist__44c1_sm_p8_1[] = {
  138771. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  138772. 7, 7, 8, 7,10,10,11,11,12,12, 6, 5, 5, 7, 7, 8,
  138773. 8,10,10,11,11,12,12,16, 7, 7, 8, 8, 9, 9,11,11,
  138774. 12,12,13,13,17, 7, 7, 8, 7, 9, 9,11,10,12,12,13,
  138775. 13,19,11,10, 8, 8,10,10,11,11,12,12,13,13,19,11,
  138776. 11, 9, 7,11,10,11,11,12,12,13,12,19,19,19,10,10,
  138777. 10,10,11,12,12,12,13,14,18,19,19,11, 9,11, 9,13,
  138778. 12,12,12,13,13,19,20,19,13,15,11,11,12,12,13,13,
  138779. 14,13,18,19,20,15,13,12,10,13,10,13,13,13,14,20,
  138780. 20,20,20,20,13,14,12,12,13,12,13,13,20,20,20,20,
  138781. 20,13,12,12,12,14,12,14,13,
  138782. };
  138783. static float _vq_quantthresh__44c1_sm_p8_1[] = {
  138784. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  138785. 42.5, 59.5, 76.5, 93.5,
  138786. };
  138787. static long _vq_quantmap__44c1_sm_p8_1[] = {
  138788. 11, 9, 7, 5, 3, 1, 0, 2,
  138789. 4, 6, 8, 10, 12,
  138790. };
  138791. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_1 = {
  138792. _vq_quantthresh__44c1_sm_p8_1,
  138793. _vq_quantmap__44c1_sm_p8_1,
  138794. 13,
  138795. 13
  138796. };
  138797. static static_codebook _44c1_sm_p8_1 = {
  138798. 2, 169,
  138799. _vq_lengthlist__44c1_sm_p8_1,
  138800. 1, -522616832, 1620115456, 4, 0,
  138801. _vq_quantlist__44c1_sm_p8_1,
  138802. NULL,
  138803. &_vq_auxt__44c1_sm_p8_1,
  138804. NULL,
  138805. 0
  138806. };
  138807. static long _vq_quantlist__44c1_sm_p8_2[] = {
  138808. 8,
  138809. 7,
  138810. 9,
  138811. 6,
  138812. 10,
  138813. 5,
  138814. 11,
  138815. 4,
  138816. 12,
  138817. 3,
  138818. 13,
  138819. 2,
  138820. 14,
  138821. 1,
  138822. 15,
  138823. 0,
  138824. 16,
  138825. };
  138826. static long _vq_lengthlist__44c1_sm_p8_2[] = {
  138827. 2, 5, 5, 6, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  138828. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  138829. 9, 9,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  138830. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  138831. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  138832. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  138833. 9, 9,10,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  138834. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  138835. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 8, 8, 9,
  138836. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  138837. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,11,11,11, 9,
  138838. 8, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,10,11,11,
  138839. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,11,
  138840. 11,11,11, 9, 9,10, 9, 9, 9, 9,10, 9,10,10,11,10,
  138841. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  138842. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,
  138843. 11,10,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  138844. 10,11,10,11,11,11,11,11,11, 9, 9,10, 9, 9, 9, 9,
  138845. 9,
  138846. };
  138847. static float _vq_quantthresh__44c1_sm_p8_2[] = {
  138848. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138849. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138850. };
  138851. static long _vq_quantmap__44c1_sm_p8_2[] = {
  138852. 15, 13, 11, 9, 7, 5, 3, 1,
  138853. 0, 2, 4, 6, 8, 10, 12, 14,
  138854. 16,
  138855. };
  138856. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_2 = {
  138857. _vq_quantthresh__44c1_sm_p8_2,
  138858. _vq_quantmap__44c1_sm_p8_2,
  138859. 17,
  138860. 17
  138861. };
  138862. static static_codebook _44c1_sm_p8_2 = {
  138863. 2, 289,
  138864. _vq_lengthlist__44c1_sm_p8_2,
  138865. 1, -529530880, 1611661312, 5, 0,
  138866. _vq_quantlist__44c1_sm_p8_2,
  138867. NULL,
  138868. &_vq_auxt__44c1_sm_p8_2,
  138869. NULL,
  138870. 0
  138871. };
  138872. static long _huff_lengthlist__44c1_sm_short[] = {
  138873. 4, 7,13,14,14,15,16,18,18, 4, 2, 5, 8, 7, 9,12,
  138874. 15,15,10, 4, 5,10, 6, 8,11,15,17,12, 5, 7, 5, 6,
  138875. 8,11,14,17,11, 5, 6, 6, 5, 6, 9,13,17,12, 6, 7,
  138876. 6, 5, 6, 8,12,14,14, 7, 8, 6, 6, 7, 9,11,14,14,
  138877. 8, 9, 6, 5, 6, 9,11,13,16,10,10, 7, 6, 7, 8,10,
  138878. 11,
  138879. };
  138880. static static_codebook _huff_book__44c1_sm_short = {
  138881. 2, 81,
  138882. _huff_lengthlist__44c1_sm_short,
  138883. 0, 0, 0, 0, 0,
  138884. NULL,
  138885. NULL,
  138886. NULL,
  138887. NULL,
  138888. 0
  138889. };
  138890. static long _huff_lengthlist__44cn1_s_long[] = {
  138891. 4, 4, 7, 8, 7, 8,10,12,17, 3, 1, 6, 6, 7, 8,10,
  138892. 12,15, 7, 6, 9, 9, 9,11,12,14,17, 8, 6, 9, 6, 7,
  138893. 9,11,13,17, 7, 6, 9, 7, 7, 8, 9,12,15, 8, 8,10,
  138894. 8, 7, 7, 7,10,14, 9,10,12,10, 8, 8, 8,10,14,11,
  138895. 13,15,13,12,11,11,12,16,17,18,18,19,20,18,16,16,
  138896. 20,
  138897. };
  138898. static static_codebook _huff_book__44cn1_s_long = {
  138899. 2, 81,
  138900. _huff_lengthlist__44cn1_s_long,
  138901. 0, 0, 0, 0, 0,
  138902. NULL,
  138903. NULL,
  138904. NULL,
  138905. NULL,
  138906. 0
  138907. };
  138908. static long _vq_quantlist__44cn1_s_p1_0[] = {
  138909. 1,
  138910. 0,
  138911. 2,
  138912. };
  138913. static long _vq_lengthlist__44cn1_s_p1_0[] = {
  138914. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  138915. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138919. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  138920. 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138924. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0,
  138925. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  138960. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0,
  138961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0, 0,
  138965. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  138966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0,
  138970. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0,10,11,11,
  138971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139005. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  139006. 0, 0, 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139010. 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  139011. 0, 0, 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  139012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139015. 0, 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11,
  139016. 0, 0, 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 0,
  139017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139324. 0,
  139325. };
  139326. static float _vq_quantthresh__44cn1_s_p1_0[] = {
  139327. -0.5, 0.5,
  139328. };
  139329. static long _vq_quantmap__44cn1_s_p1_0[] = {
  139330. 1, 0, 2,
  139331. };
  139332. static encode_aux_threshmatch _vq_auxt__44cn1_s_p1_0 = {
  139333. _vq_quantthresh__44cn1_s_p1_0,
  139334. _vq_quantmap__44cn1_s_p1_0,
  139335. 3,
  139336. 3
  139337. };
  139338. static static_codebook _44cn1_s_p1_0 = {
  139339. 8, 6561,
  139340. _vq_lengthlist__44cn1_s_p1_0,
  139341. 1, -535822336, 1611661312, 2, 0,
  139342. _vq_quantlist__44cn1_s_p1_0,
  139343. NULL,
  139344. &_vq_auxt__44cn1_s_p1_0,
  139345. NULL,
  139346. 0
  139347. };
  139348. static long _vq_quantlist__44cn1_s_p2_0[] = {
  139349. 2,
  139350. 1,
  139351. 3,
  139352. 0,
  139353. 4,
  139354. };
  139355. static long _vq_lengthlist__44cn1_s_p2_0[] = {
  139356. 1, 4, 4, 7, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  139358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139359. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  139361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139362. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  139363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139395. 0,
  139396. };
  139397. static float _vq_quantthresh__44cn1_s_p2_0[] = {
  139398. -1.5, -0.5, 0.5, 1.5,
  139399. };
  139400. static long _vq_quantmap__44cn1_s_p2_0[] = {
  139401. 3, 1, 0, 2, 4,
  139402. };
  139403. static encode_aux_threshmatch _vq_auxt__44cn1_s_p2_0 = {
  139404. _vq_quantthresh__44cn1_s_p2_0,
  139405. _vq_quantmap__44cn1_s_p2_0,
  139406. 5,
  139407. 5
  139408. };
  139409. static static_codebook _44cn1_s_p2_0 = {
  139410. 4, 625,
  139411. _vq_lengthlist__44cn1_s_p2_0,
  139412. 1, -533725184, 1611661312, 3, 0,
  139413. _vq_quantlist__44cn1_s_p2_0,
  139414. NULL,
  139415. &_vq_auxt__44cn1_s_p2_0,
  139416. NULL,
  139417. 0
  139418. };
  139419. static long _vq_quantlist__44cn1_s_p3_0[] = {
  139420. 4,
  139421. 3,
  139422. 5,
  139423. 2,
  139424. 6,
  139425. 1,
  139426. 7,
  139427. 0,
  139428. 8,
  139429. };
  139430. static long _vq_lengthlist__44cn1_s_p3_0[] = {
  139431. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  139432. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  139433. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  139434. 9, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  139435. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139436. 0,
  139437. };
  139438. static float _vq_quantthresh__44cn1_s_p3_0[] = {
  139439. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139440. };
  139441. static long _vq_quantmap__44cn1_s_p3_0[] = {
  139442. 7, 5, 3, 1, 0, 2, 4, 6,
  139443. 8,
  139444. };
  139445. static encode_aux_threshmatch _vq_auxt__44cn1_s_p3_0 = {
  139446. _vq_quantthresh__44cn1_s_p3_0,
  139447. _vq_quantmap__44cn1_s_p3_0,
  139448. 9,
  139449. 9
  139450. };
  139451. static static_codebook _44cn1_s_p3_0 = {
  139452. 2, 81,
  139453. _vq_lengthlist__44cn1_s_p3_0,
  139454. 1, -531628032, 1611661312, 4, 0,
  139455. _vq_quantlist__44cn1_s_p3_0,
  139456. NULL,
  139457. &_vq_auxt__44cn1_s_p3_0,
  139458. NULL,
  139459. 0
  139460. };
  139461. static long _vq_quantlist__44cn1_s_p4_0[] = {
  139462. 4,
  139463. 3,
  139464. 5,
  139465. 2,
  139466. 6,
  139467. 1,
  139468. 7,
  139469. 0,
  139470. 8,
  139471. };
  139472. static long _vq_lengthlist__44cn1_s_p4_0[] = {
  139473. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  139474. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  139475. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  139476. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  139477. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  139478. 11,
  139479. };
  139480. static float _vq_quantthresh__44cn1_s_p4_0[] = {
  139481. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139482. };
  139483. static long _vq_quantmap__44cn1_s_p4_0[] = {
  139484. 7, 5, 3, 1, 0, 2, 4, 6,
  139485. 8,
  139486. };
  139487. static encode_aux_threshmatch _vq_auxt__44cn1_s_p4_0 = {
  139488. _vq_quantthresh__44cn1_s_p4_0,
  139489. _vq_quantmap__44cn1_s_p4_0,
  139490. 9,
  139491. 9
  139492. };
  139493. static static_codebook _44cn1_s_p4_0 = {
  139494. 2, 81,
  139495. _vq_lengthlist__44cn1_s_p4_0,
  139496. 1, -531628032, 1611661312, 4, 0,
  139497. _vq_quantlist__44cn1_s_p4_0,
  139498. NULL,
  139499. &_vq_auxt__44cn1_s_p4_0,
  139500. NULL,
  139501. 0
  139502. };
  139503. static long _vq_quantlist__44cn1_s_p5_0[] = {
  139504. 8,
  139505. 7,
  139506. 9,
  139507. 6,
  139508. 10,
  139509. 5,
  139510. 11,
  139511. 4,
  139512. 12,
  139513. 3,
  139514. 13,
  139515. 2,
  139516. 14,
  139517. 1,
  139518. 15,
  139519. 0,
  139520. 16,
  139521. };
  139522. static long _vq_lengthlist__44cn1_s_p5_0[] = {
  139523. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  139524. 10, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  139525. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  139526. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  139527. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  139528. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  139529. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  139530. 10,10,11,11,11,12,12, 0, 0, 0, 9, 9,10, 9,10,10,
  139531. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  139532. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  139533. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  139534. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  139535. 10,10,11,10,11,11,11,12,13,12,13,13, 0, 0, 0, 0,
  139536. 0, 0, 0,11,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  139537. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  139538. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  139539. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,13,13,14,14,
  139540. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,12,13,13,14,
  139541. 14,
  139542. };
  139543. static float _vq_quantthresh__44cn1_s_p5_0[] = {
  139544. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139545. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139546. };
  139547. static long _vq_quantmap__44cn1_s_p5_0[] = {
  139548. 15, 13, 11, 9, 7, 5, 3, 1,
  139549. 0, 2, 4, 6, 8, 10, 12, 14,
  139550. 16,
  139551. };
  139552. static encode_aux_threshmatch _vq_auxt__44cn1_s_p5_0 = {
  139553. _vq_quantthresh__44cn1_s_p5_0,
  139554. _vq_quantmap__44cn1_s_p5_0,
  139555. 17,
  139556. 17
  139557. };
  139558. static static_codebook _44cn1_s_p5_0 = {
  139559. 2, 289,
  139560. _vq_lengthlist__44cn1_s_p5_0,
  139561. 1, -529530880, 1611661312, 5, 0,
  139562. _vq_quantlist__44cn1_s_p5_0,
  139563. NULL,
  139564. &_vq_auxt__44cn1_s_p5_0,
  139565. NULL,
  139566. 0
  139567. };
  139568. static long _vq_quantlist__44cn1_s_p6_0[] = {
  139569. 1,
  139570. 0,
  139571. 2,
  139572. };
  139573. static long _vq_lengthlist__44cn1_s_p6_0[] = {
  139574. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 6, 6,10, 9, 9,11,
  139575. 9, 9, 4, 6, 6,10, 9, 9,10, 9, 9, 7,10,10,11,11,
  139576. 11,12,11,11, 7, 9, 9,11,11,10,11,10,10, 7, 9, 9,
  139577. 11,10,11,11,10,10, 7,10,10,11,11,11,12,11,11, 7,
  139578. 9, 9,11,10,10,11,10,10, 7, 9, 9,11,10,10,11,10,
  139579. 10,
  139580. };
  139581. static float _vq_quantthresh__44cn1_s_p6_0[] = {
  139582. -5.5, 5.5,
  139583. };
  139584. static long _vq_quantmap__44cn1_s_p6_0[] = {
  139585. 1, 0, 2,
  139586. };
  139587. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_0 = {
  139588. _vq_quantthresh__44cn1_s_p6_0,
  139589. _vq_quantmap__44cn1_s_p6_0,
  139590. 3,
  139591. 3
  139592. };
  139593. static static_codebook _44cn1_s_p6_0 = {
  139594. 4, 81,
  139595. _vq_lengthlist__44cn1_s_p6_0,
  139596. 1, -529137664, 1618345984, 2, 0,
  139597. _vq_quantlist__44cn1_s_p6_0,
  139598. NULL,
  139599. &_vq_auxt__44cn1_s_p6_0,
  139600. NULL,
  139601. 0
  139602. };
  139603. static long _vq_quantlist__44cn1_s_p6_1[] = {
  139604. 5,
  139605. 4,
  139606. 6,
  139607. 3,
  139608. 7,
  139609. 2,
  139610. 8,
  139611. 1,
  139612. 9,
  139613. 0,
  139614. 10,
  139615. };
  139616. static long _vq_lengthlist__44cn1_s_p6_1[] = {
  139617. 1, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 6,
  139618. 8, 8, 8, 8, 8, 8,10,10,10, 7, 6, 7, 7, 8, 8, 8,
  139619. 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  139620. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 9, 9,
  139621. 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,
  139622. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  139623. 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,
  139624. 10,10,10, 9, 9, 9, 9, 9, 9,
  139625. };
  139626. static float _vq_quantthresh__44cn1_s_p6_1[] = {
  139627. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  139628. 3.5, 4.5,
  139629. };
  139630. static long _vq_quantmap__44cn1_s_p6_1[] = {
  139631. 9, 7, 5, 3, 1, 0, 2, 4,
  139632. 6, 8, 10,
  139633. };
  139634. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_1 = {
  139635. _vq_quantthresh__44cn1_s_p6_1,
  139636. _vq_quantmap__44cn1_s_p6_1,
  139637. 11,
  139638. 11
  139639. };
  139640. static static_codebook _44cn1_s_p6_1 = {
  139641. 2, 121,
  139642. _vq_lengthlist__44cn1_s_p6_1,
  139643. 1, -531365888, 1611661312, 4, 0,
  139644. _vq_quantlist__44cn1_s_p6_1,
  139645. NULL,
  139646. &_vq_auxt__44cn1_s_p6_1,
  139647. NULL,
  139648. 0
  139649. };
  139650. static long _vq_quantlist__44cn1_s_p7_0[] = {
  139651. 6,
  139652. 5,
  139653. 7,
  139654. 4,
  139655. 8,
  139656. 3,
  139657. 9,
  139658. 2,
  139659. 10,
  139660. 1,
  139661. 11,
  139662. 0,
  139663. 12,
  139664. };
  139665. static long _vq_lengthlist__44cn1_s_p7_0[] = {
  139666. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  139667. 7, 7, 8, 8, 8, 8, 9, 9,11,11, 7, 5, 5, 7, 7, 8,
  139668. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  139669. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  139670. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,12, 0,13,
  139671. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  139672. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  139673. 11,12,12,13,12, 0, 0, 0,14,14,11,10,11,12,12,13,
  139674. 13,14, 0, 0, 0,15,15,11,11,12,11,12,12,14,13, 0,
  139675. 0, 0, 0, 0,12,12,12,12,13,13,14,14, 0, 0, 0, 0,
  139676. 0,13,13,12,12,13,13,13,14,
  139677. };
  139678. static float _vq_quantthresh__44cn1_s_p7_0[] = {
  139679. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  139680. 12.5, 17.5, 22.5, 27.5,
  139681. };
  139682. static long _vq_quantmap__44cn1_s_p7_0[] = {
  139683. 11, 9, 7, 5, 3, 1, 0, 2,
  139684. 4, 6, 8, 10, 12,
  139685. };
  139686. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_0 = {
  139687. _vq_quantthresh__44cn1_s_p7_0,
  139688. _vq_quantmap__44cn1_s_p7_0,
  139689. 13,
  139690. 13
  139691. };
  139692. static static_codebook _44cn1_s_p7_0 = {
  139693. 2, 169,
  139694. _vq_lengthlist__44cn1_s_p7_0,
  139695. 1, -526516224, 1616117760, 4, 0,
  139696. _vq_quantlist__44cn1_s_p7_0,
  139697. NULL,
  139698. &_vq_auxt__44cn1_s_p7_0,
  139699. NULL,
  139700. 0
  139701. };
  139702. static long _vq_quantlist__44cn1_s_p7_1[] = {
  139703. 2,
  139704. 1,
  139705. 3,
  139706. 0,
  139707. 4,
  139708. };
  139709. static long _vq_lengthlist__44cn1_s_p7_1[] = {
  139710. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  139711. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  139712. };
  139713. static float _vq_quantthresh__44cn1_s_p7_1[] = {
  139714. -1.5, -0.5, 0.5, 1.5,
  139715. };
  139716. static long _vq_quantmap__44cn1_s_p7_1[] = {
  139717. 3, 1, 0, 2, 4,
  139718. };
  139719. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_1 = {
  139720. _vq_quantthresh__44cn1_s_p7_1,
  139721. _vq_quantmap__44cn1_s_p7_1,
  139722. 5,
  139723. 5
  139724. };
  139725. static static_codebook _44cn1_s_p7_1 = {
  139726. 2, 25,
  139727. _vq_lengthlist__44cn1_s_p7_1,
  139728. 1, -533725184, 1611661312, 3, 0,
  139729. _vq_quantlist__44cn1_s_p7_1,
  139730. NULL,
  139731. &_vq_auxt__44cn1_s_p7_1,
  139732. NULL,
  139733. 0
  139734. };
  139735. static long _vq_quantlist__44cn1_s_p8_0[] = {
  139736. 2,
  139737. 1,
  139738. 3,
  139739. 0,
  139740. 4,
  139741. };
  139742. static long _vq_lengthlist__44cn1_s_p8_0[] = {
  139743. 1, 7, 7,11,11, 8,11,11,11,11, 4,11, 3,11,11,11,
  139744. 11,11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,
  139745. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139746. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  139747. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139748. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139749. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139750. 11,11,11,11,11,11,11,11,11,11,11,11,11, 7,11,11,
  139751. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139752. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  139753. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  139754. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139755. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139756. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139757. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139758. 11,11,11,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  139759. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139760. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139761. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139762. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139763. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139764. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139765. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139766. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139767. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139768. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139769. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139770. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139771. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139772. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139773. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139774. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139775. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139776. 11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,
  139777. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  139778. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  139779. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  139780. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  139781. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  139782. 12,
  139783. };
  139784. static float _vq_quantthresh__44cn1_s_p8_0[] = {
  139785. -331.5, -110.5, 110.5, 331.5,
  139786. };
  139787. static long _vq_quantmap__44cn1_s_p8_0[] = {
  139788. 3, 1, 0, 2, 4,
  139789. };
  139790. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_0 = {
  139791. _vq_quantthresh__44cn1_s_p8_0,
  139792. _vq_quantmap__44cn1_s_p8_0,
  139793. 5,
  139794. 5
  139795. };
  139796. static static_codebook _44cn1_s_p8_0 = {
  139797. 4, 625,
  139798. _vq_lengthlist__44cn1_s_p8_0,
  139799. 1, -518283264, 1627103232, 3, 0,
  139800. _vq_quantlist__44cn1_s_p8_0,
  139801. NULL,
  139802. &_vq_auxt__44cn1_s_p8_0,
  139803. NULL,
  139804. 0
  139805. };
  139806. static long _vq_quantlist__44cn1_s_p8_1[] = {
  139807. 6,
  139808. 5,
  139809. 7,
  139810. 4,
  139811. 8,
  139812. 3,
  139813. 9,
  139814. 2,
  139815. 10,
  139816. 1,
  139817. 11,
  139818. 0,
  139819. 12,
  139820. };
  139821. static long _vq_lengthlist__44cn1_s_p8_1[] = {
  139822. 1, 4, 4, 6, 6, 8, 8, 9,10,10,11,11,11, 6, 5, 5,
  139823. 7, 7, 8, 8, 9,10, 9,11,11,12, 5, 5, 5, 7, 7, 8,
  139824. 9,10,10,12,12,14,13,15, 7, 7, 8, 8, 9,10,11,11,
  139825. 10,12,10,11,15, 7, 8, 8, 8, 9, 9,11,11,13,12,12,
  139826. 13,15,10,10, 8, 8,10,10,12,12,11,14,10,10,15,11,
  139827. 11, 8, 8,10,10,12,13,13,14,15,13,15,15,15,10,10,
  139828. 10,10,12,12,13,12,13,10,15,15,15,10,10,11,10,13,
  139829. 11,13,13,15,13,15,15,15,13,13,10,11,11,11,12,10,
  139830. 14,11,15,15,14,14,13,10,10,12,11,13,13,14,14,15,
  139831. 15,15,15,15,11,11,11,11,12,11,15,12,15,15,15,15,
  139832. 15,12,12,11,11,14,12,13,14,
  139833. };
  139834. static float _vq_quantthresh__44cn1_s_p8_1[] = {
  139835. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  139836. 42.5, 59.5, 76.5, 93.5,
  139837. };
  139838. static long _vq_quantmap__44cn1_s_p8_1[] = {
  139839. 11, 9, 7, 5, 3, 1, 0, 2,
  139840. 4, 6, 8, 10, 12,
  139841. };
  139842. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_1 = {
  139843. _vq_quantthresh__44cn1_s_p8_1,
  139844. _vq_quantmap__44cn1_s_p8_1,
  139845. 13,
  139846. 13
  139847. };
  139848. static static_codebook _44cn1_s_p8_1 = {
  139849. 2, 169,
  139850. _vq_lengthlist__44cn1_s_p8_1,
  139851. 1, -522616832, 1620115456, 4, 0,
  139852. _vq_quantlist__44cn1_s_p8_1,
  139853. NULL,
  139854. &_vq_auxt__44cn1_s_p8_1,
  139855. NULL,
  139856. 0
  139857. };
  139858. static long _vq_quantlist__44cn1_s_p8_2[] = {
  139859. 8,
  139860. 7,
  139861. 9,
  139862. 6,
  139863. 10,
  139864. 5,
  139865. 11,
  139866. 4,
  139867. 12,
  139868. 3,
  139869. 13,
  139870. 2,
  139871. 14,
  139872. 1,
  139873. 15,
  139874. 0,
  139875. 16,
  139876. };
  139877. static long _vq_lengthlist__44cn1_s_p8_2[] = {
  139878. 3, 4, 3, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  139879. 9,10,11,11, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  139880. 9, 9,10,10,10, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  139881. 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  139882. 9, 9,10, 9,10,11,10, 7, 6, 7, 7, 8, 8, 9, 9, 9,
  139883. 9, 9, 9, 9,10,10,10,11, 7, 7, 8, 8, 8, 8, 9, 9,
  139884. 9, 9, 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9,
  139885. 9, 9, 9, 9, 9, 9,10,11,11,11, 8, 8, 8, 8, 8, 8,
  139886. 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 8, 8, 8,
  139887. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,11, 9, 9,
  139888. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,10,11,11, 9,
  139889. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  139890. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,
  139891. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11,
  139892. 10,11,11,11, 9,10,10, 9, 9, 9, 9, 9, 9, 9,10,11,
  139893. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  139894. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  139895. 11,11,11,10,11,11,11,11,11, 9, 9, 9,10, 9, 9, 9,
  139896. 9,
  139897. };
  139898. static float _vq_quantthresh__44cn1_s_p8_2[] = {
  139899. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139900. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139901. };
  139902. static long _vq_quantmap__44cn1_s_p8_2[] = {
  139903. 15, 13, 11, 9, 7, 5, 3, 1,
  139904. 0, 2, 4, 6, 8, 10, 12, 14,
  139905. 16,
  139906. };
  139907. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_2 = {
  139908. _vq_quantthresh__44cn1_s_p8_2,
  139909. _vq_quantmap__44cn1_s_p8_2,
  139910. 17,
  139911. 17
  139912. };
  139913. static static_codebook _44cn1_s_p8_2 = {
  139914. 2, 289,
  139915. _vq_lengthlist__44cn1_s_p8_2,
  139916. 1, -529530880, 1611661312, 5, 0,
  139917. _vq_quantlist__44cn1_s_p8_2,
  139918. NULL,
  139919. &_vq_auxt__44cn1_s_p8_2,
  139920. NULL,
  139921. 0
  139922. };
  139923. static long _huff_lengthlist__44cn1_s_short[] = {
  139924. 10, 9,12,15,12,13,16,14,16, 7, 1, 5,14, 7,10,13,
  139925. 16,16, 9, 4, 6,16, 8,11,16,16,16,14, 4, 7,16, 9,
  139926. 12,14,16,16,10, 5, 7,14, 9,12,14,15,15,13, 8, 9,
  139927. 14,10,12,13,14,15,13, 9, 9, 7, 6, 8,11,12,12,14,
  139928. 8, 8, 5, 4, 5, 8,11,12,16,10,10, 6, 5, 6, 8, 9,
  139929. 10,
  139930. };
  139931. static static_codebook _huff_book__44cn1_s_short = {
  139932. 2, 81,
  139933. _huff_lengthlist__44cn1_s_short,
  139934. 0, 0, 0, 0, 0,
  139935. NULL,
  139936. NULL,
  139937. NULL,
  139938. NULL,
  139939. 0
  139940. };
  139941. static long _huff_lengthlist__44cn1_sm_long[] = {
  139942. 3, 3, 8, 8, 8, 8,10,12,14, 3, 2, 6, 7, 7, 8,10,
  139943. 12,16, 7, 6, 7, 9, 8,10,12,14,16, 8, 6, 8, 4, 5,
  139944. 7, 9,11,13, 7, 6, 8, 5, 6, 7, 9,11,14, 8, 8,10,
  139945. 7, 7, 6, 8,10,13, 9,11,12, 9, 9, 7, 8,10,12,10,
  139946. 13,15,11,11,10, 9,10,13,13,16,17,14,15,14,13,14,
  139947. 17,
  139948. };
  139949. static static_codebook _huff_book__44cn1_sm_long = {
  139950. 2, 81,
  139951. _huff_lengthlist__44cn1_sm_long,
  139952. 0, 0, 0, 0, 0,
  139953. NULL,
  139954. NULL,
  139955. NULL,
  139956. NULL,
  139957. 0
  139958. };
  139959. static long _vq_quantlist__44cn1_sm_p1_0[] = {
  139960. 1,
  139961. 0,
  139962. 2,
  139963. };
  139964. static long _vq_lengthlist__44cn1_sm_p1_0[] = {
  139965. 1, 4, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  139966. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139970. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  139971. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139975. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  139976. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  140011. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  140012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0, 0,
  140016. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  140017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  140021. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  140022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140056. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  140057. 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140061. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  140062. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  140063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140066. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10,
  140067. 0, 0, 0, 0, 0, 0, 9,10, 9, 0, 0, 0, 0, 0, 0, 0,
  140068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140375. 0,
  140376. };
  140377. static float _vq_quantthresh__44cn1_sm_p1_0[] = {
  140378. -0.5, 0.5,
  140379. };
  140380. static long _vq_quantmap__44cn1_sm_p1_0[] = {
  140381. 1, 0, 2,
  140382. };
  140383. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p1_0 = {
  140384. _vq_quantthresh__44cn1_sm_p1_0,
  140385. _vq_quantmap__44cn1_sm_p1_0,
  140386. 3,
  140387. 3
  140388. };
  140389. static static_codebook _44cn1_sm_p1_0 = {
  140390. 8, 6561,
  140391. _vq_lengthlist__44cn1_sm_p1_0,
  140392. 1, -535822336, 1611661312, 2, 0,
  140393. _vq_quantlist__44cn1_sm_p1_0,
  140394. NULL,
  140395. &_vq_auxt__44cn1_sm_p1_0,
  140396. NULL,
  140397. 0
  140398. };
  140399. static long _vq_quantlist__44cn1_sm_p2_0[] = {
  140400. 2,
  140401. 1,
  140402. 3,
  140403. 0,
  140404. 4,
  140405. };
  140406. static long _vq_lengthlist__44cn1_sm_p2_0[] = {
  140407. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  140409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140410. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  140412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140413. 0, 0, 0, 0, 7, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  140414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140446. 0,
  140447. };
  140448. static float _vq_quantthresh__44cn1_sm_p2_0[] = {
  140449. -1.5, -0.5, 0.5, 1.5,
  140450. };
  140451. static long _vq_quantmap__44cn1_sm_p2_0[] = {
  140452. 3, 1, 0, 2, 4,
  140453. };
  140454. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p2_0 = {
  140455. _vq_quantthresh__44cn1_sm_p2_0,
  140456. _vq_quantmap__44cn1_sm_p2_0,
  140457. 5,
  140458. 5
  140459. };
  140460. static static_codebook _44cn1_sm_p2_0 = {
  140461. 4, 625,
  140462. _vq_lengthlist__44cn1_sm_p2_0,
  140463. 1, -533725184, 1611661312, 3, 0,
  140464. _vq_quantlist__44cn1_sm_p2_0,
  140465. NULL,
  140466. &_vq_auxt__44cn1_sm_p2_0,
  140467. NULL,
  140468. 0
  140469. };
  140470. static long _vq_quantlist__44cn1_sm_p3_0[] = {
  140471. 4,
  140472. 3,
  140473. 5,
  140474. 2,
  140475. 6,
  140476. 1,
  140477. 7,
  140478. 0,
  140479. 8,
  140480. };
  140481. static long _vq_lengthlist__44cn1_sm_p3_0[] = {
  140482. 1, 3, 4, 7, 7, 0, 0, 0, 0, 0, 4, 4, 7, 7, 0, 0,
  140483. 0, 0, 0, 4, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  140484. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  140485. 9, 9, 0, 0, 0, 0, 0, 0, 0,10, 9, 0, 0, 0, 0, 0,
  140486. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140487. 0,
  140488. };
  140489. static float _vq_quantthresh__44cn1_sm_p3_0[] = {
  140490. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140491. };
  140492. static long _vq_quantmap__44cn1_sm_p3_0[] = {
  140493. 7, 5, 3, 1, 0, 2, 4, 6,
  140494. 8,
  140495. };
  140496. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p3_0 = {
  140497. _vq_quantthresh__44cn1_sm_p3_0,
  140498. _vq_quantmap__44cn1_sm_p3_0,
  140499. 9,
  140500. 9
  140501. };
  140502. static static_codebook _44cn1_sm_p3_0 = {
  140503. 2, 81,
  140504. _vq_lengthlist__44cn1_sm_p3_0,
  140505. 1, -531628032, 1611661312, 4, 0,
  140506. _vq_quantlist__44cn1_sm_p3_0,
  140507. NULL,
  140508. &_vq_auxt__44cn1_sm_p3_0,
  140509. NULL,
  140510. 0
  140511. };
  140512. static long _vq_quantlist__44cn1_sm_p4_0[] = {
  140513. 4,
  140514. 3,
  140515. 5,
  140516. 2,
  140517. 6,
  140518. 1,
  140519. 7,
  140520. 0,
  140521. 8,
  140522. };
  140523. static long _vq_lengthlist__44cn1_sm_p4_0[] = {
  140524. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  140525. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  140526. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  140527. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  140528. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  140529. 11,
  140530. };
  140531. static float _vq_quantthresh__44cn1_sm_p4_0[] = {
  140532. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140533. };
  140534. static long _vq_quantmap__44cn1_sm_p4_0[] = {
  140535. 7, 5, 3, 1, 0, 2, 4, 6,
  140536. 8,
  140537. };
  140538. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p4_0 = {
  140539. _vq_quantthresh__44cn1_sm_p4_0,
  140540. _vq_quantmap__44cn1_sm_p4_0,
  140541. 9,
  140542. 9
  140543. };
  140544. static static_codebook _44cn1_sm_p4_0 = {
  140545. 2, 81,
  140546. _vq_lengthlist__44cn1_sm_p4_0,
  140547. 1, -531628032, 1611661312, 4, 0,
  140548. _vq_quantlist__44cn1_sm_p4_0,
  140549. NULL,
  140550. &_vq_auxt__44cn1_sm_p4_0,
  140551. NULL,
  140552. 0
  140553. };
  140554. static long _vq_quantlist__44cn1_sm_p5_0[] = {
  140555. 8,
  140556. 7,
  140557. 9,
  140558. 6,
  140559. 10,
  140560. 5,
  140561. 11,
  140562. 4,
  140563. 12,
  140564. 3,
  140565. 13,
  140566. 2,
  140567. 14,
  140568. 1,
  140569. 15,
  140570. 0,
  140571. 16,
  140572. };
  140573. static long _vq_lengthlist__44cn1_sm_p5_0[] = {
  140574. 1, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  140575. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  140576. 12,12, 0, 6, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  140577. 11,12,12, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  140578. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,11,
  140579. 11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  140580. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  140581. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  140582. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  140583. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  140584. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  140585. 9,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0, 0,
  140586. 10,10,11,11,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  140587. 0, 0, 0,11,11,11,11,12,12,13,13,14,14, 0, 0, 0,
  140588. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  140589. 0, 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0,
  140590. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,14,14,14,14,
  140591. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,14,14,
  140592. 14,
  140593. };
  140594. static float _vq_quantthresh__44cn1_sm_p5_0[] = {
  140595. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140596. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140597. };
  140598. static long _vq_quantmap__44cn1_sm_p5_0[] = {
  140599. 15, 13, 11, 9, 7, 5, 3, 1,
  140600. 0, 2, 4, 6, 8, 10, 12, 14,
  140601. 16,
  140602. };
  140603. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p5_0 = {
  140604. _vq_quantthresh__44cn1_sm_p5_0,
  140605. _vq_quantmap__44cn1_sm_p5_0,
  140606. 17,
  140607. 17
  140608. };
  140609. static static_codebook _44cn1_sm_p5_0 = {
  140610. 2, 289,
  140611. _vq_lengthlist__44cn1_sm_p5_0,
  140612. 1, -529530880, 1611661312, 5, 0,
  140613. _vq_quantlist__44cn1_sm_p5_0,
  140614. NULL,
  140615. &_vq_auxt__44cn1_sm_p5_0,
  140616. NULL,
  140617. 0
  140618. };
  140619. static long _vq_quantlist__44cn1_sm_p6_0[] = {
  140620. 1,
  140621. 0,
  140622. 2,
  140623. };
  140624. static long _vq_lengthlist__44cn1_sm_p6_0[] = {
  140625. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 6,10, 9, 9,11,
  140626. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  140627. 11,11,11,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  140628. 11,10,11,11,10,10, 7,11,11,11,11,11,12,11,11, 7,
  140629. 9, 9,11,10,10,12,10,10, 7, 9, 9,11,10,10,11,10,
  140630. 10,
  140631. };
  140632. static float _vq_quantthresh__44cn1_sm_p6_0[] = {
  140633. -5.5, 5.5,
  140634. };
  140635. static long _vq_quantmap__44cn1_sm_p6_0[] = {
  140636. 1, 0, 2,
  140637. };
  140638. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_0 = {
  140639. _vq_quantthresh__44cn1_sm_p6_0,
  140640. _vq_quantmap__44cn1_sm_p6_0,
  140641. 3,
  140642. 3
  140643. };
  140644. static static_codebook _44cn1_sm_p6_0 = {
  140645. 4, 81,
  140646. _vq_lengthlist__44cn1_sm_p6_0,
  140647. 1, -529137664, 1618345984, 2, 0,
  140648. _vq_quantlist__44cn1_sm_p6_0,
  140649. NULL,
  140650. &_vq_auxt__44cn1_sm_p6_0,
  140651. NULL,
  140652. 0
  140653. };
  140654. static long _vq_quantlist__44cn1_sm_p6_1[] = {
  140655. 5,
  140656. 4,
  140657. 6,
  140658. 3,
  140659. 7,
  140660. 2,
  140661. 8,
  140662. 1,
  140663. 9,
  140664. 0,
  140665. 10,
  140666. };
  140667. static long _vq_lengthlist__44cn1_sm_p6_1[] = {
  140668. 2, 4, 4, 5, 5, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  140669. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  140670. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  140671. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  140672. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  140673. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  140674. 8, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 8, 9,10,10,
  140675. 10,10,10, 8, 9, 8, 8, 9, 8,
  140676. };
  140677. static float _vq_quantthresh__44cn1_sm_p6_1[] = {
  140678. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  140679. 3.5, 4.5,
  140680. };
  140681. static long _vq_quantmap__44cn1_sm_p6_1[] = {
  140682. 9, 7, 5, 3, 1, 0, 2, 4,
  140683. 6, 8, 10,
  140684. };
  140685. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_1 = {
  140686. _vq_quantthresh__44cn1_sm_p6_1,
  140687. _vq_quantmap__44cn1_sm_p6_1,
  140688. 11,
  140689. 11
  140690. };
  140691. static static_codebook _44cn1_sm_p6_1 = {
  140692. 2, 121,
  140693. _vq_lengthlist__44cn1_sm_p6_1,
  140694. 1, -531365888, 1611661312, 4, 0,
  140695. _vq_quantlist__44cn1_sm_p6_1,
  140696. NULL,
  140697. &_vq_auxt__44cn1_sm_p6_1,
  140698. NULL,
  140699. 0
  140700. };
  140701. static long _vq_quantlist__44cn1_sm_p7_0[] = {
  140702. 6,
  140703. 5,
  140704. 7,
  140705. 4,
  140706. 8,
  140707. 3,
  140708. 9,
  140709. 2,
  140710. 10,
  140711. 1,
  140712. 11,
  140713. 0,
  140714. 12,
  140715. };
  140716. static long _vq_lengthlist__44cn1_sm_p7_0[] = {
  140717. 1, 4, 4, 6, 6, 7, 7, 7, 7, 9, 9,10,10, 7, 5, 5,
  140718. 7, 7, 8, 8, 8, 8,10, 9,11,10, 7, 5, 5, 7, 7, 8,
  140719. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  140720. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  140721. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,12,12, 0,13,
  140722. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10,
  140723. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  140724. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,13,
  140725. 13,13, 0, 0, 0,14,14,11,10,11,11,12,12,13,13, 0,
  140726. 0, 0, 0, 0,12,12,12,12,13,13,13,14, 0, 0, 0, 0,
  140727. 0,13,12,12,12,13,13,13,14,
  140728. };
  140729. static float _vq_quantthresh__44cn1_sm_p7_0[] = {
  140730. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  140731. 12.5, 17.5, 22.5, 27.5,
  140732. };
  140733. static long _vq_quantmap__44cn1_sm_p7_0[] = {
  140734. 11, 9, 7, 5, 3, 1, 0, 2,
  140735. 4, 6, 8, 10, 12,
  140736. };
  140737. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_0 = {
  140738. _vq_quantthresh__44cn1_sm_p7_0,
  140739. _vq_quantmap__44cn1_sm_p7_0,
  140740. 13,
  140741. 13
  140742. };
  140743. static static_codebook _44cn1_sm_p7_0 = {
  140744. 2, 169,
  140745. _vq_lengthlist__44cn1_sm_p7_0,
  140746. 1, -526516224, 1616117760, 4, 0,
  140747. _vq_quantlist__44cn1_sm_p7_0,
  140748. NULL,
  140749. &_vq_auxt__44cn1_sm_p7_0,
  140750. NULL,
  140751. 0
  140752. };
  140753. static long _vq_quantlist__44cn1_sm_p7_1[] = {
  140754. 2,
  140755. 1,
  140756. 3,
  140757. 0,
  140758. 4,
  140759. };
  140760. static long _vq_lengthlist__44cn1_sm_p7_1[] = {
  140761. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  140762. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  140763. };
  140764. static float _vq_quantthresh__44cn1_sm_p7_1[] = {
  140765. -1.5, -0.5, 0.5, 1.5,
  140766. };
  140767. static long _vq_quantmap__44cn1_sm_p7_1[] = {
  140768. 3, 1, 0, 2, 4,
  140769. };
  140770. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_1 = {
  140771. _vq_quantthresh__44cn1_sm_p7_1,
  140772. _vq_quantmap__44cn1_sm_p7_1,
  140773. 5,
  140774. 5
  140775. };
  140776. static static_codebook _44cn1_sm_p7_1 = {
  140777. 2, 25,
  140778. _vq_lengthlist__44cn1_sm_p7_1,
  140779. 1, -533725184, 1611661312, 3, 0,
  140780. _vq_quantlist__44cn1_sm_p7_1,
  140781. NULL,
  140782. &_vq_auxt__44cn1_sm_p7_1,
  140783. NULL,
  140784. 0
  140785. };
  140786. static long _vq_quantlist__44cn1_sm_p8_0[] = {
  140787. 4,
  140788. 3,
  140789. 5,
  140790. 2,
  140791. 6,
  140792. 1,
  140793. 7,
  140794. 0,
  140795. 8,
  140796. };
  140797. static long _vq_lengthlist__44cn1_sm_p8_0[] = {
  140798. 1, 4, 4,12,11,13,13,14,14, 4, 7, 7,11,13,14,14,
  140799. 14,14, 3, 8, 3,14,14,14,14,14,14,14,10,12,14,14,
  140800. 14,14,14,14,14,14, 5,14, 8,14,14,14,14,14,12,14,
  140801. 13,14,14,14,14,14,14,14,13,14,10,14,14,14,14,14,
  140802. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  140803. 14,
  140804. };
  140805. static float _vq_quantthresh__44cn1_sm_p8_0[] = {
  140806. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  140807. };
  140808. static long _vq_quantmap__44cn1_sm_p8_0[] = {
  140809. 7, 5, 3, 1, 0, 2, 4, 6,
  140810. 8,
  140811. };
  140812. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_0 = {
  140813. _vq_quantthresh__44cn1_sm_p8_0,
  140814. _vq_quantmap__44cn1_sm_p8_0,
  140815. 9,
  140816. 9
  140817. };
  140818. static static_codebook _44cn1_sm_p8_0 = {
  140819. 2, 81,
  140820. _vq_lengthlist__44cn1_sm_p8_0,
  140821. 1, -516186112, 1627103232, 4, 0,
  140822. _vq_quantlist__44cn1_sm_p8_0,
  140823. NULL,
  140824. &_vq_auxt__44cn1_sm_p8_0,
  140825. NULL,
  140826. 0
  140827. };
  140828. static long _vq_quantlist__44cn1_sm_p8_1[] = {
  140829. 6,
  140830. 5,
  140831. 7,
  140832. 4,
  140833. 8,
  140834. 3,
  140835. 9,
  140836. 2,
  140837. 10,
  140838. 1,
  140839. 11,
  140840. 0,
  140841. 12,
  140842. };
  140843. static long _vq_lengthlist__44cn1_sm_p8_1[] = {
  140844. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,11,11, 6, 5, 5,
  140845. 7, 7, 8, 8,10,10,10,11,11,11, 6, 5, 5, 7, 7, 8,
  140846. 8,10,10,11,12,12,12,14, 7, 7, 7, 8, 9, 9,11,11,
  140847. 11,12,11,12,17, 7, 7, 8, 7, 9, 9,11,11,12,12,12,
  140848. 12,14,11,11, 8, 8,10,10,11,12,12,13,11,12,14,11,
  140849. 11, 8, 8,10,10,11,12,12,13,13,12,14,15,14,10,10,
  140850. 10,10,11,12,12,12,12,11,14,13,16,10,10,10, 9,12,
  140851. 11,12,12,13,14,14,15,14,14,13,10,10,11,11,12,11,
  140852. 13,11,14,12,15,13,14,11,10,12,10,12,12,13,13,13,
  140853. 13,14,15,15,12,12,11,11,12,11,13,12,14,14,14,14,
  140854. 17,12,12,11,10,13,11,13,13,
  140855. };
  140856. static float _vq_quantthresh__44cn1_sm_p8_1[] = {
  140857. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  140858. 42.5, 59.5, 76.5, 93.5,
  140859. };
  140860. static long _vq_quantmap__44cn1_sm_p8_1[] = {
  140861. 11, 9, 7, 5, 3, 1, 0, 2,
  140862. 4, 6, 8, 10, 12,
  140863. };
  140864. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_1 = {
  140865. _vq_quantthresh__44cn1_sm_p8_1,
  140866. _vq_quantmap__44cn1_sm_p8_1,
  140867. 13,
  140868. 13
  140869. };
  140870. static static_codebook _44cn1_sm_p8_1 = {
  140871. 2, 169,
  140872. _vq_lengthlist__44cn1_sm_p8_1,
  140873. 1, -522616832, 1620115456, 4, 0,
  140874. _vq_quantlist__44cn1_sm_p8_1,
  140875. NULL,
  140876. &_vq_auxt__44cn1_sm_p8_1,
  140877. NULL,
  140878. 0
  140879. };
  140880. static long _vq_quantlist__44cn1_sm_p8_2[] = {
  140881. 8,
  140882. 7,
  140883. 9,
  140884. 6,
  140885. 10,
  140886. 5,
  140887. 11,
  140888. 4,
  140889. 12,
  140890. 3,
  140891. 13,
  140892. 2,
  140893. 14,
  140894. 1,
  140895. 15,
  140896. 0,
  140897. 16,
  140898. };
  140899. static long _vq_lengthlist__44cn1_sm_p8_2[] = {
  140900. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  140901. 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  140902. 9, 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  140903. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  140904. 9, 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,
  140905. 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9, 9,
  140906. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9,
  140907. 9, 9, 9, 9, 9, 9, 9,11,10,11, 8, 8, 8, 8, 8, 8,
  140908. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11, 8, 8, 8,
  140909. 8, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  140910. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,11,11, 9,
  140911. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,10,11,11,
  140912. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,
  140913. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,
  140914. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,11,10,
  140915. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  140916. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  140917. 10,11,11,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  140918. 9,
  140919. };
  140920. static float _vq_quantthresh__44cn1_sm_p8_2[] = {
  140921. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140922. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140923. };
  140924. static long _vq_quantmap__44cn1_sm_p8_2[] = {
  140925. 15, 13, 11, 9, 7, 5, 3, 1,
  140926. 0, 2, 4, 6, 8, 10, 12, 14,
  140927. 16,
  140928. };
  140929. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_2 = {
  140930. _vq_quantthresh__44cn1_sm_p8_2,
  140931. _vq_quantmap__44cn1_sm_p8_2,
  140932. 17,
  140933. 17
  140934. };
  140935. static static_codebook _44cn1_sm_p8_2 = {
  140936. 2, 289,
  140937. _vq_lengthlist__44cn1_sm_p8_2,
  140938. 1, -529530880, 1611661312, 5, 0,
  140939. _vq_quantlist__44cn1_sm_p8_2,
  140940. NULL,
  140941. &_vq_auxt__44cn1_sm_p8_2,
  140942. NULL,
  140943. 0
  140944. };
  140945. static long _huff_lengthlist__44cn1_sm_short[] = {
  140946. 5, 6,12,14,12,14,16,17,18, 4, 2, 5,11, 7,10,12,
  140947. 14,15, 9, 4, 5,11, 7,10,13,15,18,15, 6, 7, 5, 6,
  140948. 8,11,13,16,11, 5, 6, 5, 5, 6, 9,13,15,12, 5, 7,
  140949. 6, 5, 6, 9,12,14,12, 6, 7, 8, 6, 7, 9,12,13,14,
  140950. 8, 8, 7, 5, 5, 8,10,12,16, 9, 9, 8, 6, 6, 7, 9,
  140951. 9,
  140952. };
  140953. static static_codebook _huff_book__44cn1_sm_short = {
  140954. 2, 81,
  140955. _huff_lengthlist__44cn1_sm_short,
  140956. 0, 0, 0, 0, 0,
  140957. NULL,
  140958. NULL,
  140959. NULL,
  140960. NULL,
  140961. 0
  140962. };
  140963. /*** End of inlined file: res_books_stereo.h ***/
  140964. /***** residue backends *********************************************/
  140965. static vorbis_info_residue0 _residue_44_low={
  140966. 0,-1, -1, 9,-1,
  140967. /* 0 1 2 3 4 5 6 7 */
  140968. {0},
  140969. {-1},
  140970. { .5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  140971. { .5, .5, .5, 999., 4.5, 8.5, 16.5, 32.5},
  140972. };
  140973. static vorbis_info_residue0 _residue_44_mid={
  140974. 0,-1, -1, 10,-1,
  140975. /* 0 1 2 3 4 5 6 7 8 */
  140976. {0},
  140977. {-1},
  140978. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  140979. { .5, .5, 999., .5, 999., 4.5, 8.5, 16.5, 32.5},
  140980. };
  140981. static vorbis_info_residue0 _residue_44_high={
  140982. 0,-1, -1, 10,-1,
  140983. /* 0 1 2 3 4 5 6 7 8 */
  140984. {0},
  140985. {-1},
  140986. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  140987. { .5, 1.5, 2.5, 3.5, 4.5, 8.5, 16.5, 71.5,157.5},
  140988. };
  140989. static static_bookblock _resbook_44s_n1={
  140990. {
  140991. {0},{0,0,&_44cn1_s_p1_0},{0,0,&_44cn1_s_p2_0},
  140992. {0,0,&_44cn1_s_p3_0},{0,0,&_44cn1_s_p4_0},{0,0,&_44cn1_s_p5_0},
  140993. {&_44cn1_s_p6_0,&_44cn1_s_p6_1},{&_44cn1_s_p7_0,&_44cn1_s_p7_1},
  140994. {&_44cn1_s_p8_0,&_44cn1_s_p8_1,&_44cn1_s_p8_2}
  140995. }
  140996. };
  140997. static static_bookblock _resbook_44sm_n1={
  140998. {
  140999. {0},{0,0,&_44cn1_sm_p1_0},{0,0,&_44cn1_sm_p2_0},
  141000. {0,0,&_44cn1_sm_p3_0},{0,0,&_44cn1_sm_p4_0},{0,0,&_44cn1_sm_p5_0},
  141001. {&_44cn1_sm_p6_0,&_44cn1_sm_p6_1},{&_44cn1_sm_p7_0,&_44cn1_sm_p7_1},
  141002. {&_44cn1_sm_p8_0,&_44cn1_sm_p8_1,&_44cn1_sm_p8_2}
  141003. }
  141004. };
  141005. static static_bookblock _resbook_44s_0={
  141006. {
  141007. {0},{0,0,&_44c0_s_p1_0},{0,0,&_44c0_s_p2_0},
  141008. {0,0,&_44c0_s_p3_0},{0,0,&_44c0_s_p4_0},{0,0,&_44c0_s_p5_0},
  141009. {&_44c0_s_p6_0,&_44c0_s_p6_1},{&_44c0_s_p7_0,&_44c0_s_p7_1},
  141010. {&_44c0_s_p8_0,&_44c0_s_p8_1,&_44c0_s_p8_2}
  141011. }
  141012. };
  141013. static static_bookblock _resbook_44sm_0={
  141014. {
  141015. {0},{0,0,&_44c0_sm_p1_0},{0,0,&_44c0_sm_p2_0},
  141016. {0,0,&_44c0_sm_p3_0},{0,0,&_44c0_sm_p4_0},{0,0,&_44c0_sm_p5_0},
  141017. {&_44c0_sm_p6_0,&_44c0_sm_p6_1},{&_44c0_sm_p7_0,&_44c0_sm_p7_1},
  141018. {&_44c0_sm_p8_0,&_44c0_sm_p8_1,&_44c0_sm_p8_2}
  141019. }
  141020. };
  141021. static static_bookblock _resbook_44s_1={
  141022. {
  141023. {0},{0,0,&_44c1_s_p1_0},{0,0,&_44c1_s_p2_0},
  141024. {0,0,&_44c1_s_p3_0},{0,0,&_44c1_s_p4_0},{0,0,&_44c1_s_p5_0},
  141025. {&_44c1_s_p6_0,&_44c1_s_p6_1},{&_44c1_s_p7_0,&_44c1_s_p7_1},
  141026. {&_44c1_s_p8_0,&_44c1_s_p8_1,&_44c1_s_p8_2}
  141027. }
  141028. };
  141029. static static_bookblock _resbook_44sm_1={
  141030. {
  141031. {0},{0,0,&_44c1_sm_p1_0},{0,0,&_44c1_sm_p2_0},
  141032. {0,0,&_44c1_sm_p3_0},{0,0,&_44c1_sm_p4_0},{0,0,&_44c1_sm_p5_0},
  141033. {&_44c1_sm_p6_0,&_44c1_sm_p6_1},{&_44c1_sm_p7_0,&_44c1_sm_p7_1},
  141034. {&_44c1_sm_p8_0,&_44c1_sm_p8_1,&_44c1_sm_p8_2}
  141035. }
  141036. };
  141037. static static_bookblock _resbook_44s_2={
  141038. {
  141039. {0},{0,0,&_44c2_s_p1_0},{0,0,&_44c2_s_p2_0},{0,0,&_44c2_s_p3_0},
  141040. {0,0,&_44c2_s_p4_0},{0,0,&_44c2_s_p5_0},{0,0,&_44c2_s_p6_0},
  141041. {&_44c2_s_p7_0,&_44c2_s_p7_1},{&_44c2_s_p8_0,&_44c2_s_p8_1},
  141042. {&_44c2_s_p9_0,&_44c2_s_p9_1,&_44c2_s_p9_2}
  141043. }
  141044. };
  141045. static static_bookblock _resbook_44s_3={
  141046. {
  141047. {0},{0,0,&_44c3_s_p1_0},{0,0,&_44c3_s_p2_0},{0,0,&_44c3_s_p3_0},
  141048. {0,0,&_44c3_s_p4_0},{0,0,&_44c3_s_p5_0},{0,0,&_44c3_s_p6_0},
  141049. {&_44c3_s_p7_0,&_44c3_s_p7_1},{&_44c3_s_p8_0,&_44c3_s_p8_1},
  141050. {&_44c3_s_p9_0,&_44c3_s_p9_1,&_44c3_s_p9_2}
  141051. }
  141052. };
  141053. static static_bookblock _resbook_44s_4={
  141054. {
  141055. {0},{0,0,&_44c4_s_p1_0},{0,0,&_44c4_s_p2_0},{0,0,&_44c4_s_p3_0},
  141056. {0,0,&_44c4_s_p4_0},{0,0,&_44c4_s_p5_0},{0,0,&_44c4_s_p6_0},
  141057. {&_44c4_s_p7_0,&_44c4_s_p7_1},{&_44c4_s_p8_0,&_44c4_s_p8_1},
  141058. {&_44c4_s_p9_0,&_44c4_s_p9_1,&_44c4_s_p9_2}
  141059. }
  141060. };
  141061. static static_bookblock _resbook_44s_5={
  141062. {
  141063. {0},{0,0,&_44c5_s_p1_0},{0,0,&_44c5_s_p2_0},{0,0,&_44c5_s_p3_0},
  141064. {0,0,&_44c5_s_p4_0},{0,0,&_44c5_s_p5_0},{0,0,&_44c5_s_p6_0},
  141065. {&_44c5_s_p7_0,&_44c5_s_p7_1},{&_44c5_s_p8_0,&_44c5_s_p8_1},
  141066. {&_44c5_s_p9_0,&_44c5_s_p9_1,&_44c5_s_p9_2}
  141067. }
  141068. };
  141069. static static_bookblock _resbook_44s_6={
  141070. {
  141071. {0},{0,0,&_44c6_s_p1_0},{0,0,&_44c6_s_p2_0},{0,0,&_44c6_s_p3_0},
  141072. {0,0,&_44c6_s_p4_0},
  141073. {&_44c6_s_p5_0,&_44c6_s_p5_1},
  141074. {&_44c6_s_p6_0,&_44c6_s_p6_1},
  141075. {&_44c6_s_p7_0,&_44c6_s_p7_1},
  141076. {&_44c6_s_p8_0,&_44c6_s_p8_1},
  141077. {&_44c6_s_p9_0,&_44c6_s_p9_1,&_44c6_s_p9_2}
  141078. }
  141079. };
  141080. static static_bookblock _resbook_44s_7={
  141081. {
  141082. {0},{0,0,&_44c7_s_p1_0},{0,0,&_44c7_s_p2_0},{0,0,&_44c7_s_p3_0},
  141083. {0,0,&_44c7_s_p4_0},
  141084. {&_44c7_s_p5_0,&_44c7_s_p5_1},
  141085. {&_44c7_s_p6_0,&_44c7_s_p6_1},
  141086. {&_44c7_s_p7_0,&_44c7_s_p7_1},
  141087. {&_44c7_s_p8_0,&_44c7_s_p8_1},
  141088. {&_44c7_s_p9_0,&_44c7_s_p9_1,&_44c7_s_p9_2}
  141089. }
  141090. };
  141091. static static_bookblock _resbook_44s_8={
  141092. {
  141093. {0},{0,0,&_44c8_s_p1_0},{0,0,&_44c8_s_p2_0},{0,0,&_44c8_s_p3_0},
  141094. {0,0,&_44c8_s_p4_0},
  141095. {&_44c8_s_p5_0,&_44c8_s_p5_1},
  141096. {&_44c8_s_p6_0,&_44c8_s_p6_1},
  141097. {&_44c8_s_p7_0,&_44c8_s_p7_1},
  141098. {&_44c8_s_p8_0,&_44c8_s_p8_1},
  141099. {&_44c8_s_p9_0,&_44c8_s_p9_1,&_44c8_s_p9_2}
  141100. }
  141101. };
  141102. static static_bookblock _resbook_44s_9={
  141103. {
  141104. {0},{0,0,&_44c9_s_p1_0},{0,0,&_44c9_s_p2_0},{0,0,&_44c9_s_p3_0},
  141105. {0,0,&_44c9_s_p4_0},
  141106. {&_44c9_s_p5_0,&_44c9_s_p5_1},
  141107. {&_44c9_s_p6_0,&_44c9_s_p6_1},
  141108. {&_44c9_s_p7_0,&_44c9_s_p7_1},
  141109. {&_44c9_s_p8_0,&_44c9_s_p8_1},
  141110. {&_44c9_s_p9_0,&_44c9_s_p9_1,&_44c9_s_p9_2}
  141111. }
  141112. };
  141113. static vorbis_residue_template _res_44s_n1[]={
  141114. {2,0, &_residue_44_low,
  141115. &_huff_book__44cn1_s_short,&_huff_book__44cn1_sm_short,
  141116. &_resbook_44s_n1,&_resbook_44sm_n1},
  141117. {2,0, &_residue_44_low,
  141118. &_huff_book__44cn1_s_long,&_huff_book__44cn1_sm_long,
  141119. &_resbook_44s_n1,&_resbook_44sm_n1}
  141120. };
  141121. static vorbis_residue_template _res_44s_0[]={
  141122. {2,0, &_residue_44_low,
  141123. &_huff_book__44c0_s_short,&_huff_book__44c0_sm_short,
  141124. &_resbook_44s_0,&_resbook_44sm_0},
  141125. {2,0, &_residue_44_low,
  141126. &_huff_book__44c0_s_long,&_huff_book__44c0_sm_long,
  141127. &_resbook_44s_0,&_resbook_44sm_0}
  141128. };
  141129. static vorbis_residue_template _res_44s_1[]={
  141130. {2,0, &_residue_44_low,
  141131. &_huff_book__44c1_s_short,&_huff_book__44c1_sm_short,
  141132. &_resbook_44s_1,&_resbook_44sm_1},
  141133. {2,0, &_residue_44_low,
  141134. &_huff_book__44c1_s_long,&_huff_book__44c1_sm_long,
  141135. &_resbook_44s_1,&_resbook_44sm_1}
  141136. };
  141137. static vorbis_residue_template _res_44s_2[]={
  141138. {2,0, &_residue_44_mid,
  141139. &_huff_book__44c2_s_short,&_huff_book__44c2_s_short,
  141140. &_resbook_44s_2,&_resbook_44s_2},
  141141. {2,0, &_residue_44_mid,
  141142. &_huff_book__44c2_s_long,&_huff_book__44c2_s_long,
  141143. &_resbook_44s_2,&_resbook_44s_2}
  141144. };
  141145. static vorbis_residue_template _res_44s_3[]={
  141146. {2,0, &_residue_44_mid,
  141147. &_huff_book__44c3_s_short,&_huff_book__44c3_s_short,
  141148. &_resbook_44s_3,&_resbook_44s_3},
  141149. {2,0, &_residue_44_mid,
  141150. &_huff_book__44c3_s_long,&_huff_book__44c3_s_long,
  141151. &_resbook_44s_3,&_resbook_44s_3}
  141152. };
  141153. static vorbis_residue_template _res_44s_4[]={
  141154. {2,0, &_residue_44_mid,
  141155. &_huff_book__44c4_s_short,&_huff_book__44c4_s_short,
  141156. &_resbook_44s_4,&_resbook_44s_4},
  141157. {2,0, &_residue_44_mid,
  141158. &_huff_book__44c4_s_long,&_huff_book__44c4_s_long,
  141159. &_resbook_44s_4,&_resbook_44s_4}
  141160. };
  141161. static vorbis_residue_template _res_44s_5[]={
  141162. {2,0, &_residue_44_mid,
  141163. &_huff_book__44c5_s_short,&_huff_book__44c5_s_short,
  141164. &_resbook_44s_5,&_resbook_44s_5},
  141165. {2,0, &_residue_44_mid,
  141166. &_huff_book__44c5_s_long,&_huff_book__44c5_s_long,
  141167. &_resbook_44s_5,&_resbook_44s_5}
  141168. };
  141169. static vorbis_residue_template _res_44s_6[]={
  141170. {2,0, &_residue_44_high,
  141171. &_huff_book__44c6_s_short,&_huff_book__44c6_s_short,
  141172. &_resbook_44s_6,&_resbook_44s_6},
  141173. {2,0, &_residue_44_high,
  141174. &_huff_book__44c6_s_long,&_huff_book__44c6_s_long,
  141175. &_resbook_44s_6,&_resbook_44s_6}
  141176. };
  141177. static vorbis_residue_template _res_44s_7[]={
  141178. {2,0, &_residue_44_high,
  141179. &_huff_book__44c7_s_short,&_huff_book__44c7_s_short,
  141180. &_resbook_44s_7,&_resbook_44s_7},
  141181. {2,0, &_residue_44_high,
  141182. &_huff_book__44c7_s_long,&_huff_book__44c7_s_long,
  141183. &_resbook_44s_7,&_resbook_44s_7}
  141184. };
  141185. static vorbis_residue_template _res_44s_8[]={
  141186. {2,0, &_residue_44_high,
  141187. &_huff_book__44c8_s_short,&_huff_book__44c8_s_short,
  141188. &_resbook_44s_8,&_resbook_44s_8},
  141189. {2,0, &_residue_44_high,
  141190. &_huff_book__44c8_s_long,&_huff_book__44c8_s_long,
  141191. &_resbook_44s_8,&_resbook_44s_8}
  141192. };
  141193. static vorbis_residue_template _res_44s_9[]={
  141194. {2,0, &_residue_44_high,
  141195. &_huff_book__44c9_s_short,&_huff_book__44c9_s_short,
  141196. &_resbook_44s_9,&_resbook_44s_9},
  141197. {2,0, &_residue_44_high,
  141198. &_huff_book__44c9_s_long,&_huff_book__44c9_s_long,
  141199. &_resbook_44s_9,&_resbook_44s_9}
  141200. };
  141201. static vorbis_mapping_template _mapres_template_44_stereo[]={
  141202. { _map_nominal, _res_44s_n1 }, /* -1 */
  141203. { _map_nominal, _res_44s_0 }, /* 0 */
  141204. { _map_nominal, _res_44s_1 }, /* 1 */
  141205. { _map_nominal, _res_44s_2 }, /* 2 */
  141206. { _map_nominal, _res_44s_3 }, /* 3 */
  141207. { _map_nominal, _res_44s_4 }, /* 4 */
  141208. { _map_nominal, _res_44s_5 }, /* 5 */
  141209. { _map_nominal, _res_44s_6 }, /* 6 */
  141210. { _map_nominal, _res_44s_7 }, /* 7 */
  141211. { _map_nominal, _res_44s_8 }, /* 8 */
  141212. { _map_nominal, _res_44s_9 }, /* 9 */
  141213. };
  141214. /*** End of inlined file: residue_44.h ***/
  141215. /*** Start of inlined file: psych_44.h ***/
  141216. /* preecho trigger settings *****************************************/
  141217. static vorbis_info_psy_global _psy_global_44[5]={
  141218. {8, /* lines per eighth octave */
  141219. {20.f,14.f,12.f,12.f,12.f,12.f,12.f},
  141220. {-60.f,-30.f,-40.f,-40.f,-40.f,-40.f,-40.f}, 2,-75.f,
  141221. -6.f,
  141222. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  141223. },
  141224. {8, /* lines per eighth octave */
  141225. {14.f,10.f,10.f,10.f,10.f,10.f,10.f},
  141226. {-40.f,-30.f,-25.f,-25.f,-25.f,-25.f,-25.f}, 2,-80.f,
  141227. -6.f,
  141228. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  141229. },
  141230. {8, /* lines per eighth octave */
  141231. {12.f,10.f,10.f,10.f,10.f,10.f,10.f},
  141232. {-20.f,-20.f,-15.f,-15.f,-15.f,-15.f,-15.f}, 0,-80.f,
  141233. -6.f,
  141234. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  141235. },
  141236. {8, /* lines per eighth octave */
  141237. {10.f,8.f,8.f,8.f,8.f,8.f,8.f},
  141238. {-20.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-80.f,
  141239. -6.f,
  141240. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  141241. },
  141242. {8, /* lines per eighth octave */
  141243. {10.f,6.f,6.f,6.f,6.f,6.f,6.f},
  141244. {-15.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-85.f,
  141245. -6.f,
  141246. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  141247. },
  141248. };
  141249. /* noise compander lookups * low, mid, high quality ****************/
  141250. static compandblock _psy_compand_44[6]={
  141251. /* sub-mode Z short */
  141252. {{
  141253. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  141254. 8, 9,10,11,12,13,14, 15, /* 15dB */
  141255. 16,17,18,19,20,21,22, 23, /* 23dB */
  141256. 24,25,26,27,28,29,30, 31, /* 31dB */
  141257. 32,33,34,35,36,37,38, 39, /* 39dB */
  141258. }},
  141259. /* mode_Z nominal short */
  141260. {{
  141261. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  141262. 7, 7, 7, 7, 6, 6, 6, 7, /* 15dB */
  141263. 7, 8, 9,10,11,12,13, 14, /* 23dB */
  141264. 15,16,17,17,17,18,18, 19, /* 31dB */
  141265. 19,19,20,21,22,23,24, 25, /* 39dB */
  141266. }},
  141267. /* mode A short */
  141268. {{
  141269. 0, 1, 2, 3, 4, 5, 5, 5, /* 7dB */
  141270. 6, 6, 6, 5, 4, 4, 4, 4, /* 15dB */
  141271. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  141272. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  141273. 11,12,13,14,15,16,17, 18, /* 39dB */
  141274. }},
  141275. /* sub-mode Z long */
  141276. {{
  141277. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  141278. 8, 9,10,11,12,13,14, 15, /* 15dB */
  141279. 16,17,18,19,20,21,22, 23, /* 23dB */
  141280. 24,25,26,27,28,29,30, 31, /* 31dB */
  141281. 32,33,34,35,36,37,38, 39, /* 39dB */
  141282. }},
  141283. /* mode_Z nominal long */
  141284. {{
  141285. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  141286. 8, 9,10,11,12,12,13, 13, /* 15dB */
  141287. 13,14,14,14,15,15,15, 15, /* 23dB */
  141288. 16,16,17,17,17,18,18, 19, /* 31dB */
  141289. 19,19,20,21,22,23,24, 25, /* 39dB */
  141290. }},
  141291. /* mode A long */
  141292. {{
  141293. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  141294. 8, 8, 7, 6, 5, 4, 4, 4, /* 15dB */
  141295. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  141296. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  141297. 11,12,13,14,15,16,17, 18, /* 39dB */
  141298. }}
  141299. };
  141300. /* tonal masking curve level adjustments *************************/
  141301. static vp_adjblock _vp_tonemask_adj_longblock[12]={
  141302. /* 63 125 250 500 1 2 4 8 16 */
  141303. {{ -3, -8,-13,-15,-10,-10,-10,-10,-10,-10,-10, 0, 0, 0, 0, 0, 0}}, /* -1 */
  141304. /* {{-15,-15,-15,-15,-10, -8, -4, -2, 0, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  141305. {{ -4,-10,-14,-16,-15,-14,-13,-12,-12,-12,-11, -1, -1, -1, -1, -1, 0}}, /* 0 */
  141306. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  141307. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, -1, -1, 0}}, /* 1 */
  141308. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  141309. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -6, -3, -1, -1, -1, 0}}, /* 2 */
  141310. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  141311. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, -1, -1, 0}}, /* 3 */
  141312. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, *//* 4 */
  141313. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  141314. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  141315. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  141316. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  141317. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  141318. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  141319. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  141320. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  141321. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  141322. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  141323. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  141324. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  141325. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  141326. };
  141327. static vp_adjblock _vp_tonemask_adj_otherblock[12]={
  141328. /* 63 125 250 500 1 2 4 8 16 */
  141329. {{ -3, -8,-13,-15,-10,-10, -9, -9, -9, -9, -9, 1, 1, 1, 1, 1, 1}}, /* -1 */
  141330. /* {{-20,-20,-20,-20,-14,-12,-10, -8, -4, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  141331. {{ -4,-10,-14,-16,-14,-13,-12,-12,-11,-11,-10, 0, 0, 0, 0, 0, 0}}, /* 0 */
  141332. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  141333. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, 0, 0, 0}}, /* 1 */
  141334. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  141335. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -5, -2, -1, 0, 0, 0}}, /* 2 */
  141336. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  141337. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, 0, 0, 0}}, /* 3 */
  141338. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 4 */
  141339. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  141340. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  141341. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  141342. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  141343. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  141344. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  141345. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  141346. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  141347. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  141348. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  141349. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  141350. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  141351. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  141352. };
  141353. /* noise bias (transition block) */
  141354. static noise3 _psy_noisebias_trans[12]={
  141355. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  141356. /* -1 */
  141357. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  141358. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  141359. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  141360. /* 0
  141361. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  141362. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 4, 10},
  141363. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  141364. {{{-15,-15,-15,-15,-15,-12, -6, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  141365. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 3, 6},
  141366. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},
  141367. /* 1
  141368. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  141369. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  141370. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  141371. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  141372. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  141373. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  141374. /* 2
  141375. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  141376. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  141377. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}}, */
  141378. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  141379. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  141380. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -7, -4}}},
  141381. /* 3
  141382. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  141383. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  141384. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  141385. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  141386. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  141387. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  141388. /* 4
  141389. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  141390. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  141391. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  141392. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  141393. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  141394. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  141395. /* 5
  141396. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  141397. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  141398. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}}, */
  141399. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  141400. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  141401. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},
  141402. /* 6
  141403. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  141404. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  141405. {-34,-34,-34,-34,-30,-26,-24,-18,-17,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  141406. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  141407. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  141408. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},
  141409. /* 7
  141410. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  141411. {-32,-32,-32,-32,-28,-24,-24,-18,-14,-12,-10, -8, -8, -8, -6, -4, 0},
  141412. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},*/
  141413. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  141414. {-32,-32,-32,-32,-28,-24,-24,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  141415. {-34,-34,-34,-34,-30,-26,-26,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  141416. /* 8
  141417. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  141418. {-36,-36,-36,-36,-30,-30,-30,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  141419. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  141420. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  141421. {-36,-36,-36,-36,-30,-30,-30,-24,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  141422. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-30,-30,-30,-30,-30,-30,-24,-20}}},
  141423. /* 9
  141424. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  141425. {-36,-36,-36,-36,-34,-32,-32,-28,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  141426. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  141427. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  141428. {-38,-38,-38,-38,-36,-34,-34,-30,-24,-20,-20,-20,-20,-18,-16,-12,-10},
  141429. {-40,-40,-40,-40,-40,-40,-40,-38,-35,-35,-35,-35,-35,-35,-35,-35,-30}}},
  141430. /* 10 */
  141431. {{{-30,-30,-30,-30,-30,-30,-30,-28,-20,-14,-14,-14,-14,-14,-14,-12,-10},
  141432. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-20},
  141433. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  141434. };
  141435. /* noise bias (long block) */
  141436. static noise3 _psy_noisebias_long[12]={
  141437. /*63 125 250 500 1k 2k 4k 8k 16k*/
  141438. /* -1 */
  141439. {{{-10,-10,-10,-10,-10, -4, 0, 0, 0, 6, 6, 6, 6, 10, 10, 12, 20},
  141440. {-20,-20,-20,-20,-20,-20,-10, -2, 0, 0, 0, 0, 0, 2, 4, 6, 15},
  141441. {-20,-20,-20,-20,-20,-20,-20,-10, -6, -6, -6, -6, -6, -4, -4, -4, -2}}},
  141442. /* 0 */
  141443. /* {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  141444. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 4, 10},
  141445. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  141446. {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  141447. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 3, 6},
  141448. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},
  141449. /* 1 */
  141450. /* {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  141451. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  141452. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  141453. {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  141454. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  141455. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  141456. /* 2 */
  141457. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  141458. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  141459. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  141460. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  141461. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  141462. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  141463. /* 3 */
  141464. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  141465. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  141466. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  141467. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  141468. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  141469. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -5}}},
  141470. /* 4 */
  141471. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  141472. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  141473. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  141474. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  141475. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  141476. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -7}}},
  141477. /* 5 */
  141478. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  141479. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  141480. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},*/
  141481. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  141482. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  141483. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -8}}},
  141484. /* 6 */
  141485. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  141486. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  141487. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  141488. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  141489. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  141490. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12,-10}}},
  141491. /* 7 */
  141492. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  141493. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-10, -8, -8, -8, -8, -6, -4, 0},
  141494. {-26,-26,-26,-26,-26,-26,-26,-22,-20,-19,-19,-19,-19,-18,-17,-16,-12}}},
  141495. /* 8 */
  141496. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 0, 0, 0, 0, 1, 2, 3, 7},
  141497. {-26,-26,-26,-26,-26,-26,-26,-20,-16,-12,-10,-10,-10,-10, -8, -6, -2},
  141498. {-28,-28,-28,-28,-28,-28,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  141499. /* 9 */
  141500. {{{-22,-22,-22,-22,-22,-22,-22,-18,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  141501. {-26,-26,-26,-26,-26,-26,-26,-22,-18,-16,-16,-16,-16,-14,-12,-10, -7},
  141502. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  141503. /* 10 */
  141504. {{{-24,-24,-24,-24,-24,-24,-24,-24,-24,-18,-14,-14,-14,-14,-14,-12,-10},
  141505. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-20},
  141506. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  141507. };
  141508. /* noise bias (impulse block) */
  141509. static noise3 _psy_noisebias_impulse[12]={
  141510. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  141511. /* -1 */
  141512. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  141513. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  141514. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  141515. /* 0 */
  141516. /* {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  141517. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 4, 10},
  141518. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},*/
  141519. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  141520. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 3, 6},
  141521. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  141522. /* 1 */
  141523. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  141524. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -4, -4, -2, -2, -2, -2, 2},
  141525. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8,-10,-10, -8, -8, -8, -6, -4}}},
  141526. /* 2 */
  141527. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  141528. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  141529. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  141530. /* 3 */
  141531. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  141532. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  141533. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  141534. /* 4 */
  141535. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  141536. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  141537. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  141538. /* 5 */
  141539. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  141540. {-32,-32,-32,-32,-28,-24,-22,-16,-10, -6, -8, -8, -6, -6, -6, -4, -2},
  141541. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-12,-12,-12,-12,-12,-10, -9, -5}}},
  141542. /* 6
  141543. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  141544. {-34,-34,-34,-34,-30,-30,-24,-20,-12,-12,-14,-14,-10, -9, -8, -6, -4},
  141545. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-15,-15,-15,-15,-15,-13,-12, -8}}},*/
  141546. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  141547. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-16,-16,-16,-16,-16,-14,-14,-12},
  141548. {-36,-36,-36,-36,-36,-34,-28,-24,-20,-20,-20,-20,-20,-20,-20,-18,-16}}},
  141549. /* 7 */
  141550. /* {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  141551. {-34,-34,-34,-34,-30,-30,-24,-20,-14,-14,-16,-16,-14,-12,-10,-10,-10},
  141552. {-34,-34,-34,-34,-32,-32,-30,-24,-20,-19,-19,-19,-19,-19,-17,-16,-12}}},*/
  141553. {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  141554. {-34,-34,-34,-34,-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-24,-22},
  141555. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  141556. /* 8 */
  141557. /* {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  141558. {-34,-34,-34,-34,-30,-30,-30,-24,-20,-20,-20,-20,-20,-18,-16,-16,-14},
  141559. {-36,-36,-36,-36,-36,-34,-28,-24,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  141560. {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  141561. {-34,-34,-34,-34,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-24},
  141562. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  141563. /* 9 */
  141564. /* {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  141565. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-22,-20,-20,-18},
  141566. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  141567. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  141568. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26},
  141569. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  141570. /* 10 */
  141571. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-16,-16,-16,-16,-16,-14,-12},
  141572. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-26},
  141573. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  141574. };
  141575. /* noise bias (padding block) */
  141576. static noise3 _psy_noisebias_padding[12]={
  141577. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  141578. /* -1 */
  141579. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  141580. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  141581. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  141582. /* 0 */
  141583. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  141584. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, 2, 3, 6, 6, 8, 10},
  141585. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -4, -4, -4, -4, -2, 0, 2}}},
  141586. /* 1 */
  141587. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  141588. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  141589. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -6, -4, -2, 0}}},
  141590. /* 2 */
  141591. /* {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  141592. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  141593. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},*/
  141594. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  141595. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  141596. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  141597. /* 3 */
  141598. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  141599. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  141600. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  141601. /* 4 */
  141602. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  141603. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, -1, 0, 2, 6},
  141604. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  141605. /* 5 */
  141606. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  141607. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -3, -3, -3, -3, -2, 0, 4},
  141608. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-10,-10,-10,-10,-10, -8, -5, -3}}},
  141609. /* 6 */
  141610. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  141611. {-34,-34,-34,-34,-30,-30,-24,-20,-14, -8, -4, -4, -4, -4, -3, -1, 4},
  141612. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-13,-13,-13,-13,-13,-11, -8, -6}}},
  141613. /* 7 */
  141614. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  141615. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-10, -8, -6, -6, -6, -5, -3, 1},
  141616. {-34,-34,-34,-34,-32,-32,-28,-22,-18,-16,-16,-16,-16,-16,-14,-12,-10}}},
  141617. /* 8 */
  141618. {{{-22,-22,-22,-22,-22,-20,-14,-10, -4, 0, 0, 0, 0, 3, 5, 5, 11},
  141619. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-12,-10, -8, -8, -8, -7, -5, -2},
  141620. {-36,-36,-36,-36,-36,-34,-28,-22,-20,-20,-20,-20,-20,-20,-20,-16,-14}}},
  141621. /* 9 */
  141622. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -2, -2, -2, -2, 0, 2, 6},
  141623. {-36,-36,-36,-36,-34,-32,-32,-24,-16,-12,-12,-12,-12,-12,-10, -8, -5},
  141624. {-40,-40,-40,-40,-40,-40,-40,-32,-26,-24,-24,-24,-24,-24,-24,-20,-18}}},
  141625. /* 10 */
  141626. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-12,-12,-12,-12,-12,-10, -8},
  141627. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-25,-25,-25,-25,-25,-25,-15},
  141628. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  141629. };
  141630. static noiseguard _psy_noiseguards_44[4]={
  141631. {3,3,15},
  141632. {3,3,15},
  141633. {10,10,100},
  141634. {10,10,100},
  141635. };
  141636. static int _psy_tone_suppress[12]={
  141637. -20,-20,-20,-20,-20,-24,-30,-40,-40,-45,-45,-45,
  141638. };
  141639. static int _psy_tone_0dB[12]={
  141640. 90,90,95,95,95,95,105,105,105,105,105,105,
  141641. };
  141642. static int _psy_noise_suppress[12]={
  141643. -20,-20,-24,-24,-24,-24,-30,-40,-40,-45,-45,-45,
  141644. };
  141645. static vorbis_info_psy _psy_info_template={
  141646. /* blockflag */
  141647. -1,
  141648. /* ath_adjatt, ath_maxatt */
  141649. -140.,-140.,
  141650. /* tonemask att boost/decay,suppr,curves */
  141651. {0.f,0.f,0.f}, 0.,0., -40.f, {0.},
  141652. /*noisemaskp,supp, low/high window, low/hi guard, minimum */
  141653. 1, -0.f, .5f, .5f, 0,0,0,
  141654. /* noiseoffset*3, noisecompand, max_curve_dB */
  141655. {{-1},{-1},{-1}},{-1},105.f,
  141656. /* noise normalization - channel_p, point_p, start, partition, thresh. */
  141657. 0,0,-1,-1,0.,
  141658. };
  141659. /* ath ****************/
  141660. static int _psy_ath_floater[12]={
  141661. -100,-100,-100,-100,-100,-100,-105,-105,-105,-105,-110,-120,
  141662. };
  141663. static int _psy_ath_abs[12]={
  141664. -130,-130,-130,-130,-140,-140,-140,-140,-140,-140,-140,-150,
  141665. };
  141666. /* stereo setup. These don't map directly to quality level, there's
  141667. an additional indirection as several of the below may be used in a
  141668. single bitmanaged stream
  141669. ****************/
  141670. /* various stereo possibilities */
  141671. /* stereo mode by base quality level */
  141672. static adj_stereo _psy_stereo_modes_44[12]={
  141673. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 -1 */
  141674. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  141675. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  141676. { 1, 2, 3, 4, 4, 4, 4, 4, 4, 5, 6, 7, 8, 8, 8},
  141677. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  141678. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 0 */
  141679. /*{{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  141680. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  141681. { 1, 2, 3, 4, 5, 5, 6, 6, 6, 6, 6, 7, 8, 8, 8},
  141682. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  141683. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 1, 0, 0, 0, 0, 0},
  141684. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  141685. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  141686. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  141687. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 */
  141688. {{ 3, 3, 3, 3, 3, 3, 3, 3, 2, 1, 0, 0, 0, 0, 0},
  141689. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  141690. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  141691. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  141692. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 2 */
  141693. /* {{ 3, 3, 3, 3, 3, 3, 2, 2, 2, 1, 0, 0, 0, 0, 0},
  141694. { 8, 8, 8, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3, 2, 1},
  141695. { 3, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  141696. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  141697. {{ 3, 3, 3, 3, 3, 3, 3, 2, 1, 1, 0, 0, 0, 0, 0},
  141698. { 8, 8, 6, 6, 5, 5, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  141699. { 3, 4, 4, 5, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  141700. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  141701. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 3 */
  141702. {{ 2, 2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0},
  141703. { 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  141704. { 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 10, 10, 10, 10, 10},
  141705. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  141706. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 4 */
  141707. {{ 2, 2, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141708. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 2, 1, 0},
  141709. { 6, 6, 6, 8, 8, 8, 8, 8, 8, 8, 10, 10, 10, 10, 10},
  141710. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  141711. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 5 */
  141712. /* {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141713. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  141714. { 6, 6, 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  141715. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  141716. {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141717. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  141718. { 6, 7, 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12},
  141719. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  141720. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 6 */
  141721. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141722. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141723. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  141724. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  141725. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141726. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141727. { 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  141728. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  141729. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 7 */
  141730. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141731. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141732. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  141733. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  141734. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141735. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141736. { 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  141737. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  141738. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 8 */
  141739. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141740. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141741. { 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  141742. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  141743. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141744. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141745. { 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  141746. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  141747. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 9 */
  141748. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141749. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141750. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  141751. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  141752. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 10 */
  141753. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141754. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141755. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  141756. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  141757. };
  141758. /* tone master attenuation by base quality mode and bitrate tweak */
  141759. static att3 _psy_tone_masteratt_44[12]={
  141760. {{ 35, 21, 9}, 0, 0}, /* -1 */
  141761. {{ 30, 20, 8}, -2, 1.25}, /* 0 */
  141762. /* {{ 25, 14, 4}, 0, 0}, *//* 1 */
  141763. {{ 25, 12, 2}, 0, 0}, /* 1 */
  141764. /* {{ 20, 10, -2}, 0, 0}, *//* 2 */
  141765. {{ 20, 9, -3}, 0, 0}, /* 2 */
  141766. {{ 20, 9, -4}, 0, 0}, /* 3 */
  141767. {{ 20, 9, -4}, 0, 0}, /* 4 */
  141768. {{ 20, 6, -6}, 0, 0}, /* 5 */
  141769. {{ 20, 3, -10}, 0, 0}, /* 6 */
  141770. {{ 18, 1, -14}, 0, 0}, /* 7 */
  141771. {{ 18, 0, -16}, 0, 0}, /* 8 */
  141772. {{ 18, -2, -16}, 0, 0}, /* 9 */
  141773. {{ 12, -2, -20}, 0, 0}, /* 10 */
  141774. };
  141775. /* lowpass by mode **************/
  141776. static double _psy_lowpass_44[12]={
  141777. /* 15.1,15.8,16.5,17.9,20.5,48.,999.,999.,999.,999.,999. */
  141778. 13.9,15.1,15.8,16.5,17.2,18.9,20.1,48.,999.,999.,999.,999.
  141779. };
  141780. /* noise normalization **********/
  141781. static int _noise_start_short_44[11]={
  141782. /* 16,16,16,16,32,32,9999,9999,9999,9999 */
  141783. 32,16,16,16,32,9999,9999,9999,9999,9999,9999
  141784. };
  141785. static int _noise_start_long_44[11]={
  141786. /* 128,128,128,256,512,512,9999,9999,9999,9999 */
  141787. 256,128,128,256,512,9999,9999,9999,9999,9999,9999
  141788. };
  141789. static int _noise_part_short_44[11]={
  141790. 8,8,8,8,8,8,8,8,8,8,8
  141791. };
  141792. static int _noise_part_long_44[11]={
  141793. 32,32,32,32,32,32,32,32,32,32,32
  141794. };
  141795. static double _noise_thresh_44[11]={
  141796. /* .2,.2,.3,.4,.5,.5,9999.,9999.,9999.,9999., */
  141797. .2,.2,.2,.4,.6,9999.,9999.,9999.,9999.,9999.,9999.,
  141798. };
  141799. static double _noise_thresh_5only[2]={
  141800. .5,.5,
  141801. };
  141802. /*** End of inlined file: psych_44.h ***/
  141803. static double rate_mapping_44_stereo[12]={
  141804. 22500.,32000.,40000.,48000.,56000.,64000.,
  141805. 80000.,96000.,112000.,128000.,160000.,250001.
  141806. };
  141807. static double quality_mapping_44[12]={
  141808. -.1,.0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1.0
  141809. };
  141810. static int blocksize_short_44[11]={
  141811. 512,256,256,256,256,256,256,256,256,256,256
  141812. };
  141813. static int blocksize_long_44[11]={
  141814. 4096,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048
  141815. };
  141816. static double _psy_compand_short_mapping[12]={
  141817. 0.5, 1., 1., 1.3, 1.6, 2., 2., 2., 2., 2., 2., 2.
  141818. };
  141819. static double _psy_compand_long_mapping[12]={
  141820. 3.5, 4., 4., 4.3, 4.6, 5., 5., 5., 5., 5., 5., 5.
  141821. };
  141822. static double _global_mapping_44[12]={
  141823. /* 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.5, 4., 4. */
  141824. 0., 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.7, 4., 4.
  141825. };
  141826. static int _floor_short_mapping_44[11]={
  141827. 1,0,0,2,2,4,5,5,5,5,5
  141828. };
  141829. static int _floor_long_mapping_44[11]={
  141830. 8,7,7,7,7,7,7,7,7,7,7
  141831. };
  141832. ve_setup_data_template ve_setup_44_stereo={
  141833. 11,
  141834. rate_mapping_44_stereo,
  141835. quality_mapping_44,
  141836. 2,
  141837. 40000,
  141838. 50000,
  141839. blocksize_short_44,
  141840. blocksize_long_44,
  141841. _psy_tone_masteratt_44,
  141842. _psy_tone_0dB,
  141843. _psy_tone_suppress,
  141844. _vp_tonemask_adj_otherblock,
  141845. _vp_tonemask_adj_longblock,
  141846. _vp_tonemask_adj_otherblock,
  141847. _psy_noiseguards_44,
  141848. _psy_noisebias_impulse,
  141849. _psy_noisebias_padding,
  141850. _psy_noisebias_trans,
  141851. _psy_noisebias_long,
  141852. _psy_noise_suppress,
  141853. _psy_compand_44,
  141854. _psy_compand_short_mapping,
  141855. _psy_compand_long_mapping,
  141856. {_noise_start_short_44,_noise_start_long_44},
  141857. {_noise_part_short_44,_noise_part_long_44},
  141858. _noise_thresh_44,
  141859. _psy_ath_floater,
  141860. _psy_ath_abs,
  141861. _psy_lowpass_44,
  141862. _psy_global_44,
  141863. _global_mapping_44,
  141864. _psy_stereo_modes_44,
  141865. _floor_books,
  141866. _floor,
  141867. _floor_short_mapping_44,
  141868. _floor_long_mapping_44,
  141869. _mapres_template_44_stereo
  141870. };
  141871. /*** End of inlined file: setup_44.h ***/
  141872. /*** Start of inlined file: setup_44u.h ***/
  141873. /*** Start of inlined file: residue_44u.h ***/
  141874. /*** Start of inlined file: res_books_uncoupled.h ***/
  141875. static long _vq_quantlist__16u0__p1_0[] = {
  141876. 1,
  141877. 0,
  141878. 2,
  141879. };
  141880. static long _vq_lengthlist__16u0__p1_0[] = {
  141881. 1, 4, 4, 5, 7, 7, 5, 7, 8, 5, 8, 8, 8,10,10, 8,
  141882. 10,11, 5, 8, 8, 8,10,10, 8,10,10, 4, 9, 9, 9,12,
  141883. 11, 8,11,11, 8,12,11,10,12,14,10,13,13, 7,11,11,
  141884. 10,14,12,11,14,14, 4, 9, 9, 8,11,11, 9,11,12, 7,
  141885. 11,11,10,13,14,10,12,14, 8,11,12,10,14,14,10,13,
  141886. 12,
  141887. };
  141888. static float _vq_quantthresh__16u0__p1_0[] = {
  141889. -0.5, 0.5,
  141890. };
  141891. static long _vq_quantmap__16u0__p1_0[] = {
  141892. 1, 0, 2,
  141893. };
  141894. static encode_aux_threshmatch _vq_auxt__16u0__p1_0 = {
  141895. _vq_quantthresh__16u0__p1_0,
  141896. _vq_quantmap__16u0__p1_0,
  141897. 3,
  141898. 3
  141899. };
  141900. static static_codebook _16u0__p1_0 = {
  141901. 4, 81,
  141902. _vq_lengthlist__16u0__p1_0,
  141903. 1, -535822336, 1611661312, 2, 0,
  141904. _vq_quantlist__16u0__p1_0,
  141905. NULL,
  141906. &_vq_auxt__16u0__p1_0,
  141907. NULL,
  141908. 0
  141909. };
  141910. static long _vq_quantlist__16u0__p2_0[] = {
  141911. 1,
  141912. 0,
  141913. 2,
  141914. };
  141915. static long _vq_lengthlist__16u0__p2_0[] = {
  141916. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 9, 7,
  141917. 8, 9, 5, 7, 7, 7, 9, 8, 7, 9, 7, 4, 7, 7, 7, 9,
  141918. 9, 7, 8, 8, 6, 9, 8, 7, 8,11, 9,11,10, 6, 8, 9,
  141919. 8,11, 8, 9,10,11, 4, 7, 7, 7, 8, 8, 7, 9, 9, 6,
  141920. 9, 8, 9,11,10, 8, 8,11, 6, 8, 9, 9,10,11, 8,11,
  141921. 8,
  141922. };
  141923. static float _vq_quantthresh__16u0__p2_0[] = {
  141924. -0.5, 0.5,
  141925. };
  141926. static long _vq_quantmap__16u0__p2_0[] = {
  141927. 1, 0, 2,
  141928. };
  141929. static encode_aux_threshmatch _vq_auxt__16u0__p2_0 = {
  141930. _vq_quantthresh__16u0__p2_0,
  141931. _vq_quantmap__16u0__p2_0,
  141932. 3,
  141933. 3
  141934. };
  141935. static static_codebook _16u0__p2_0 = {
  141936. 4, 81,
  141937. _vq_lengthlist__16u0__p2_0,
  141938. 1, -535822336, 1611661312, 2, 0,
  141939. _vq_quantlist__16u0__p2_0,
  141940. NULL,
  141941. &_vq_auxt__16u0__p2_0,
  141942. NULL,
  141943. 0
  141944. };
  141945. static long _vq_quantlist__16u0__p3_0[] = {
  141946. 2,
  141947. 1,
  141948. 3,
  141949. 0,
  141950. 4,
  141951. };
  141952. static long _vq_lengthlist__16u0__p3_0[] = {
  141953. 1, 5, 5, 7, 7, 6, 7, 7, 8, 8, 6, 7, 8, 8, 8, 8,
  141954. 9, 9,11,11, 8, 9, 9,11,11, 6, 9, 8,10,10, 8,10,
  141955. 10,11,11, 8,10,10,11,11,10,11,10,13,12, 9,11,10,
  141956. 13,13, 6, 8, 9,10,10, 8,10,10,11,11, 8,10,10,11,
  141957. 11, 9,10,11,13,12,10,10,11,12,12, 8,11,11,14,13,
  141958. 10,12,11,15,13, 9,12,11,15,14,12,14,13,16,14,12,
  141959. 13,13,17,14, 8,11,11,13,14, 9,11,12,14,15,10,11,
  141960. 12,13,15,11,13,13,14,16,12,13,14,14,16, 5, 9, 9,
  141961. 11,11, 9,11,11,12,12, 8,11,11,12,12,11,12,12,15,
  141962. 14,10,12,12,15,15, 8,11,11,13,12,10,12,12,13,13,
  141963. 10,12,12,14,13,12,12,13,14,15,11,13,13,17,16, 7,
  141964. 11,11,13,13,10,12,12,14,13,10,12,12,13,14,12,13,
  141965. 12,15,14,11,13,13,15,14, 9,12,12,16,15,11,13,13,
  141966. 17,16,10,13,13,16,16,13,14,15,15,16,13,15,14,19,
  141967. 17, 9,12,12,14,16,11,13,13,15,16,10,13,13,17,16,
  141968. 13,14,13,17,15,12,15,15,16,17, 5, 9, 9,11,11, 8,
  141969. 11,11,13,12, 9,11,11,12,12,10,12,12,14,15,11,12,
  141970. 12,14,14, 7,11,10,13,12,10,12,12,14,13,10,11,12,
  141971. 13,13,11,13,13,15,16,12,12,13,15,15, 7,11,11,13,
  141972. 13,10,13,13,14,14,10,12,12,13,13,11,13,13,16,15,
  141973. 12,13,13,15,14, 9,12,12,15,15,10,13,13,17,16,11,
  141974. 12,13,15,15,12,15,14,18,18,13,14,14,16,17, 9,12,
  141975. 12,15,16,10,13,13,15,16,11,13,13,15,16,13,15,15,
  141976. 17,17,13,15,14,16,15, 7,11,11,15,16,10,13,12,16,
  141977. 17,10,12,13,15,17,15,16,16,18,17,13,15,15,17,18,
  141978. 8,12,12,16,16,11,13,14,17,18,11,13,13,18,16,15,
  141979. 17,16,17,19,14,15,15,17,16, 8,12,12,16,15,11,14,
  141980. 13,18,17,11,13,14,18,17,15,16,16,18,17,13,16,16,
  141981. 18,18,11,15,14,18,17,13,14,15,18, 0,12,15,15, 0,
  141982. 17,17,16,17,17,18,14,16,18,18, 0,11,14,14,17, 0,
  141983. 12,15,14,17,19,12,15,14,18, 0,15,18,16, 0,17,14,
  141984. 18,16,18, 0, 7,11,11,16,15,10,12,12,18,16,10,13,
  141985. 13,16,15,13,15,14,17,17,14,16,16,19,18, 8,12,12,
  141986. 16,16,11,13,13,18,16,11,13,14,17,16,14,15,15,19,
  141987. 18,15,16,16, 0,19, 8,12,12,16,17,11,13,13,17,17,
  141988. 11,14,13,17,17,13,15,15,17,19,15,17,17,19, 0,11,
  141989. 14,15,19,17,12,15,16,18,18,12,14,15,19,17,14,16,
  141990. 17, 0,18,16,16,19,17, 0,11,14,14,18,19,12,15,14,
  141991. 17,17,13,16,14,17,16,14,17,16,18,18,15,18,15, 0,
  141992. 18,
  141993. };
  141994. static float _vq_quantthresh__16u0__p3_0[] = {
  141995. -1.5, -0.5, 0.5, 1.5,
  141996. };
  141997. static long _vq_quantmap__16u0__p3_0[] = {
  141998. 3, 1, 0, 2, 4,
  141999. };
  142000. static encode_aux_threshmatch _vq_auxt__16u0__p3_0 = {
  142001. _vq_quantthresh__16u0__p3_0,
  142002. _vq_quantmap__16u0__p3_0,
  142003. 5,
  142004. 5
  142005. };
  142006. static static_codebook _16u0__p3_0 = {
  142007. 4, 625,
  142008. _vq_lengthlist__16u0__p3_0,
  142009. 1, -533725184, 1611661312, 3, 0,
  142010. _vq_quantlist__16u0__p3_0,
  142011. NULL,
  142012. &_vq_auxt__16u0__p3_0,
  142013. NULL,
  142014. 0
  142015. };
  142016. static long _vq_quantlist__16u0__p4_0[] = {
  142017. 2,
  142018. 1,
  142019. 3,
  142020. 0,
  142021. 4,
  142022. };
  142023. static long _vq_lengthlist__16u0__p4_0[] = {
  142024. 3, 5, 5, 8, 8, 6, 6, 6, 9, 9, 6, 6, 6, 9, 9, 9,
  142025. 10, 9,11,11, 9, 9, 9,11,11, 6, 7, 7,10,10, 7, 7,
  142026. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  142027. 11,12, 6, 7, 7,10,10, 7, 8, 7,10,10, 7, 8, 7,10,
  142028. 10,10,11,10,12,11,10,10,10,13,10, 9,10,10,12,12,
  142029. 10,11,10,14,12, 9,11,11,13,13,11,12,13,13,13,11,
  142030. 12,12,15,13, 9,10,10,12,13, 9,11,10,12,13,10,10,
  142031. 11,12,13,11,12,12,12,13,11,12,12,13,13, 5, 7, 7,
  142032. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  142033. 13,10,10,11,12,12, 6, 8, 8,11,10, 7, 8, 9,10,12,
  142034. 8, 9, 9,11,11,11,10,11,11,12,10,11,11,13,12, 7,
  142035. 8, 8,10,11, 8, 9, 8,11,10, 8, 9, 9,11,11,10,12,
  142036. 10,13,11,10,11,11,13,13,10,11,10,14,13,10,10,11,
  142037. 13,13,10,12,11,14,13,12,11,13,12,13,13,12,13,14,
  142038. 14,10,11,11,13,13,10,11,10,12,13,10,12,12,12,14,
  142039. 12,12,12,14,12,12,13,12,17,15, 5, 7, 7,10,10, 7,
  142040. 8, 8,10,10, 7, 8, 8,11,10,10,10,11,12,12,10,11,
  142041. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  142042. 10,11,11,11,11,12,12,10,10,11,12,13, 6, 8, 8,10,
  142043. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,12,12,13,13,
  142044. 11,11,10,13,11, 9,11,10,14,13,11,11,11,15,13,10,
  142045. 10,11,13,13,12,13,13,14,14,12,11,12,12,13,10,11,
  142046. 11,12,13,10,11,12,13,13,10,11,10,13,12,12,12,13,
  142047. 14, 0,12,13,11,13,11, 8,10,10,13,13,10,11,11,14,
  142048. 13,10,11,11,13,12,13,14,14,14,15,12,12,12,15,14,
  142049. 9,11,10,13,12,10,10,11,13,14,11,11,11,15,12,13,
  142050. 12,14,15,16,13,13,13,14,13, 9,11,11,12,12,10,12,
  142051. 11,13,13,10,11,11,13,14,13,13,13,15,15,13,13,14,
  142052. 17,15,11,12,12,14,14,10,11,12,13,15,12,13,13, 0,
  142053. 15,13,11,14,12,16,14,16,14, 0,15,11,12,12,14,16,
  142054. 11,13,12,16,15,12,13,13,14,15,12,14,12,15,13,15,
  142055. 14,14,16,16, 8,10,10,13,13,10,11,10,13,14,10,11,
  142056. 11,13,13,13,13,12,14,14,14,13,13,16,17, 9,10,10,
  142057. 12,14,10,12,11,14,13,10,11,12,13,14,12,12,12,15,
  142058. 15,13,13,13,14,14, 9,10,10,13,13,10,11,12,12,14,
  142059. 10,11,10,13,13,13,13,13,14,16,13,13,13,14,14,11,
  142060. 12,13,15,13,12,14,13,14,16,12,12,13,13,14,13,14,
  142061. 14,17,15,13,12,17,13,16,11,12,13,14,15,12,13,14,
  142062. 14,17,11,12,11,14,14,13,16,14,16, 0,14,15,11,15,
  142063. 11,
  142064. };
  142065. static float _vq_quantthresh__16u0__p4_0[] = {
  142066. -1.5, -0.5, 0.5, 1.5,
  142067. };
  142068. static long _vq_quantmap__16u0__p4_0[] = {
  142069. 3, 1, 0, 2, 4,
  142070. };
  142071. static encode_aux_threshmatch _vq_auxt__16u0__p4_0 = {
  142072. _vq_quantthresh__16u0__p4_0,
  142073. _vq_quantmap__16u0__p4_0,
  142074. 5,
  142075. 5
  142076. };
  142077. static static_codebook _16u0__p4_0 = {
  142078. 4, 625,
  142079. _vq_lengthlist__16u0__p4_0,
  142080. 1, -533725184, 1611661312, 3, 0,
  142081. _vq_quantlist__16u0__p4_0,
  142082. NULL,
  142083. &_vq_auxt__16u0__p4_0,
  142084. NULL,
  142085. 0
  142086. };
  142087. static long _vq_quantlist__16u0__p5_0[] = {
  142088. 4,
  142089. 3,
  142090. 5,
  142091. 2,
  142092. 6,
  142093. 1,
  142094. 7,
  142095. 0,
  142096. 8,
  142097. };
  142098. static long _vq_lengthlist__16u0__p5_0[] = {
  142099. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  142100. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  142101. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 7, 8, 8,
  142102. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  142103. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,10,11,11,12,
  142104. 12,
  142105. };
  142106. static float _vq_quantthresh__16u0__p5_0[] = {
  142107. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  142108. };
  142109. static long _vq_quantmap__16u0__p5_0[] = {
  142110. 7, 5, 3, 1, 0, 2, 4, 6,
  142111. 8,
  142112. };
  142113. static encode_aux_threshmatch _vq_auxt__16u0__p5_0 = {
  142114. _vq_quantthresh__16u0__p5_0,
  142115. _vq_quantmap__16u0__p5_0,
  142116. 9,
  142117. 9
  142118. };
  142119. static static_codebook _16u0__p5_0 = {
  142120. 2, 81,
  142121. _vq_lengthlist__16u0__p5_0,
  142122. 1, -531628032, 1611661312, 4, 0,
  142123. _vq_quantlist__16u0__p5_0,
  142124. NULL,
  142125. &_vq_auxt__16u0__p5_0,
  142126. NULL,
  142127. 0
  142128. };
  142129. static long _vq_quantlist__16u0__p6_0[] = {
  142130. 6,
  142131. 5,
  142132. 7,
  142133. 4,
  142134. 8,
  142135. 3,
  142136. 9,
  142137. 2,
  142138. 10,
  142139. 1,
  142140. 11,
  142141. 0,
  142142. 12,
  142143. };
  142144. static long _vq_lengthlist__16u0__p6_0[] = {
  142145. 1, 4, 4, 7, 7,10,10,12,12,13,13,18,17, 3, 6, 6,
  142146. 9, 9,11,11,13,13,14,14,18,17, 3, 6, 6, 9, 9,11,
  142147. 11,13,13,14,14,17,18, 7, 9, 9,11,11,13,13,14,14,
  142148. 15,15, 0, 0, 7, 9, 9,11,11,13,13,14,14,15,16,19,
  142149. 18,10,11,11,13,13,14,14,16,15,17,18, 0, 0,10,11,
  142150. 11,13,13,14,14,15,15,16,18, 0, 0,11,13,13,14,14,
  142151. 15,15,17,17, 0,19, 0, 0,11,13,13,14,14,14,15,16,
  142152. 18, 0,19, 0, 0,13,14,14,15,15,18,17,18,18, 0,19,
  142153. 0, 0,13,14,14,15,16,16,16,18,18,19, 0, 0, 0,16,
  142154. 17,17, 0,17,19,19, 0,19, 0, 0, 0, 0,16,19,16,17,
  142155. 18, 0,19, 0, 0, 0, 0, 0, 0,
  142156. };
  142157. static float _vq_quantthresh__16u0__p6_0[] = {
  142158. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  142159. 12.5, 17.5, 22.5, 27.5,
  142160. };
  142161. static long _vq_quantmap__16u0__p6_0[] = {
  142162. 11, 9, 7, 5, 3, 1, 0, 2,
  142163. 4, 6, 8, 10, 12,
  142164. };
  142165. static encode_aux_threshmatch _vq_auxt__16u0__p6_0 = {
  142166. _vq_quantthresh__16u0__p6_0,
  142167. _vq_quantmap__16u0__p6_0,
  142168. 13,
  142169. 13
  142170. };
  142171. static static_codebook _16u0__p6_0 = {
  142172. 2, 169,
  142173. _vq_lengthlist__16u0__p6_0,
  142174. 1, -526516224, 1616117760, 4, 0,
  142175. _vq_quantlist__16u0__p6_0,
  142176. NULL,
  142177. &_vq_auxt__16u0__p6_0,
  142178. NULL,
  142179. 0
  142180. };
  142181. static long _vq_quantlist__16u0__p6_1[] = {
  142182. 2,
  142183. 1,
  142184. 3,
  142185. 0,
  142186. 4,
  142187. };
  142188. static long _vq_lengthlist__16u0__p6_1[] = {
  142189. 1, 4, 5, 6, 6, 4, 6, 6, 6, 6, 4, 6, 6, 6, 6, 6,
  142190. 6, 6, 7, 7, 6, 6, 6, 7, 7,
  142191. };
  142192. static float _vq_quantthresh__16u0__p6_1[] = {
  142193. -1.5, -0.5, 0.5, 1.5,
  142194. };
  142195. static long _vq_quantmap__16u0__p6_1[] = {
  142196. 3, 1, 0, 2, 4,
  142197. };
  142198. static encode_aux_threshmatch _vq_auxt__16u0__p6_1 = {
  142199. _vq_quantthresh__16u0__p6_1,
  142200. _vq_quantmap__16u0__p6_1,
  142201. 5,
  142202. 5
  142203. };
  142204. static static_codebook _16u0__p6_1 = {
  142205. 2, 25,
  142206. _vq_lengthlist__16u0__p6_1,
  142207. 1, -533725184, 1611661312, 3, 0,
  142208. _vq_quantlist__16u0__p6_1,
  142209. NULL,
  142210. &_vq_auxt__16u0__p6_1,
  142211. NULL,
  142212. 0
  142213. };
  142214. static long _vq_quantlist__16u0__p7_0[] = {
  142215. 1,
  142216. 0,
  142217. 2,
  142218. };
  142219. static long _vq_lengthlist__16u0__p7_0[] = {
  142220. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  142221. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  142222. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  142223. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  142224. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  142225. 7,
  142226. };
  142227. static float _vq_quantthresh__16u0__p7_0[] = {
  142228. -157.5, 157.5,
  142229. };
  142230. static long _vq_quantmap__16u0__p7_0[] = {
  142231. 1, 0, 2,
  142232. };
  142233. static encode_aux_threshmatch _vq_auxt__16u0__p7_0 = {
  142234. _vq_quantthresh__16u0__p7_0,
  142235. _vq_quantmap__16u0__p7_0,
  142236. 3,
  142237. 3
  142238. };
  142239. static static_codebook _16u0__p7_0 = {
  142240. 4, 81,
  142241. _vq_lengthlist__16u0__p7_0,
  142242. 1, -518803456, 1628680192, 2, 0,
  142243. _vq_quantlist__16u0__p7_0,
  142244. NULL,
  142245. &_vq_auxt__16u0__p7_0,
  142246. NULL,
  142247. 0
  142248. };
  142249. static long _vq_quantlist__16u0__p7_1[] = {
  142250. 7,
  142251. 6,
  142252. 8,
  142253. 5,
  142254. 9,
  142255. 4,
  142256. 10,
  142257. 3,
  142258. 11,
  142259. 2,
  142260. 12,
  142261. 1,
  142262. 13,
  142263. 0,
  142264. 14,
  142265. };
  142266. static long _vq_lengthlist__16u0__p7_1[] = {
  142267. 1, 5, 5, 6, 5, 9,10,11,11,10,10,10,10,10,10, 5,
  142268. 8, 8, 8,10,10,10,10,10,10,10,10,10,10,10, 5, 8,
  142269. 9, 9, 9,10,10,10,10,10,10,10,10,10,10, 5,10, 8,
  142270. 10,10,10,10,10,10,10,10,10,10,10,10, 4, 8, 9,10,
  142271. 10,10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,
  142272. 10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,
  142273. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142274. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142275. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142276. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142277. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142278. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142279. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142280. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142281. 10,
  142282. };
  142283. static float _vq_quantthresh__16u0__p7_1[] = {
  142284. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  142285. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  142286. };
  142287. static long _vq_quantmap__16u0__p7_1[] = {
  142288. 13, 11, 9, 7, 5, 3, 1, 0,
  142289. 2, 4, 6, 8, 10, 12, 14,
  142290. };
  142291. static encode_aux_threshmatch _vq_auxt__16u0__p7_1 = {
  142292. _vq_quantthresh__16u0__p7_1,
  142293. _vq_quantmap__16u0__p7_1,
  142294. 15,
  142295. 15
  142296. };
  142297. static static_codebook _16u0__p7_1 = {
  142298. 2, 225,
  142299. _vq_lengthlist__16u0__p7_1,
  142300. 1, -520986624, 1620377600, 4, 0,
  142301. _vq_quantlist__16u0__p7_1,
  142302. NULL,
  142303. &_vq_auxt__16u0__p7_1,
  142304. NULL,
  142305. 0
  142306. };
  142307. static long _vq_quantlist__16u0__p7_2[] = {
  142308. 10,
  142309. 9,
  142310. 11,
  142311. 8,
  142312. 12,
  142313. 7,
  142314. 13,
  142315. 6,
  142316. 14,
  142317. 5,
  142318. 15,
  142319. 4,
  142320. 16,
  142321. 3,
  142322. 17,
  142323. 2,
  142324. 18,
  142325. 1,
  142326. 19,
  142327. 0,
  142328. 20,
  142329. };
  142330. static long _vq_lengthlist__16u0__p7_2[] = {
  142331. 1, 6, 6, 7, 8, 7, 7,10, 9,10, 9,11,10, 9,11,10,
  142332. 9, 9, 9, 9,10, 6, 8, 7, 9, 9, 8, 8,10,10, 9,11,
  142333. 11,12,12,10, 9,11, 9,12,10, 9, 6, 9, 8, 9,12, 8,
  142334. 8,11, 9,11,11,12,11,12,12,10,11,11,10,10,11, 7,
  142335. 10, 9, 9, 9, 9, 9,10, 9,10, 9,10,10,12,10,10,10,
  142336. 11,12,10,10, 7, 9, 9, 9,10, 9, 9,10,10, 9, 9, 9,
  142337. 11,11,10,10,10,10, 9, 9,12, 7, 9,10, 9,11, 9,10,
  142338. 9,10,11,11,11,10,11,12, 9,12,11,10,10,10, 7, 9,
  142339. 9, 9, 9,10,12,10, 9,11,12,10,11,12,12,11, 9,10,
  142340. 11,10,11, 7, 9,10,10,11,10, 9,10,11,11,11,10,12,
  142341. 12,12,11,11,10,11,11,12, 8, 9,10,12,11,10,10,12,
  142342. 12,12,12,12,10,11,11, 9,11,10,12,11,11, 8, 9,10,
  142343. 10,11,12,11,11,10,10,10,12,12,12, 9,10,12,12,12,
  142344. 12,12, 8,10,11,10,10,12, 9,11,12,12,11,12,12,12,
  142345. 12,10,12,10,10,10,10, 8,12,11,11,11,10,10,11,12,
  142346. 12,12,12,11,12,12,12,11,11,11,12,10, 9,10,10,12,
  142347. 10,12,10,12,12,10,10,10,11,12,12,12,11,12,12,12,
  142348. 11,10,11,12,12,12,11,12,12,11,12,12,11,12,12,12,
  142349. 12,11,12,12,10,10,10,10,11,11,12,11,12,12,12,12,
  142350. 12,12,12,11,12,11,10,11,11,12,11,11, 9,10,10,10,
  142351. 12,10,10,11, 9,11,12,11,12,11,12,12,10,11,10,12,
  142352. 9, 9, 9,12,11,10,11,10,12,10,12,10,12,12,12,11,
  142353. 11,11,11,11,10, 9,10,10,11,10,11,11,12,11,10,11,
  142354. 12,12,12,11,11, 9,12,10,12, 9,10,12,10,10,11,10,
  142355. 11,11,12,11,10,11,10,11,11,11,11,12,11,11,10, 9,
  142356. 10,10,10, 9,11,11,10, 9,12,10,11,12,11,12,12,11,
  142357. 12,11,12,11,10,11,10,12,11,12,11,12,11,12,10,11,
  142358. 10,10,12,11,10,11,11,11,10,
  142359. };
  142360. static float _vq_quantthresh__16u0__p7_2[] = {
  142361. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  142362. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  142363. 6.5, 7.5, 8.5, 9.5,
  142364. };
  142365. static long _vq_quantmap__16u0__p7_2[] = {
  142366. 19, 17, 15, 13, 11, 9, 7, 5,
  142367. 3, 1, 0, 2, 4, 6, 8, 10,
  142368. 12, 14, 16, 18, 20,
  142369. };
  142370. static encode_aux_threshmatch _vq_auxt__16u0__p7_2 = {
  142371. _vq_quantthresh__16u0__p7_2,
  142372. _vq_quantmap__16u0__p7_2,
  142373. 21,
  142374. 21
  142375. };
  142376. static static_codebook _16u0__p7_2 = {
  142377. 2, 441,
  142378. _vq_lengthlist__16u0__p7_2,
  142379. 1, -529268736, 1611661312, 5, 0,
  142380. _vq_quantlist__16u0__p7_2,
  142381. NULL,
  142382. &_vq_auxt__16u0__p7_2,
  142383. NULL,
  142384. 0
  142385. };
  142386. static long _huff_lengthlist__16u0__single[] = {
  142387. 3, 5, 8, 7,14, 8, 9,19, 5, 2, 5, 5, 9, 6, 9,19,
  142388. 8, 4, 5, 7, 8, 9,13,19, 7, 4, 6, 5, 9, 6, 9,19,
  142389. 12, 8, 7, 9,10,11,13,19, 8, 5, 8, 6, 9, 6, 7,19,
  142390. 8, 8,10, 7, 7, 4, 5,19,12,17,19,15,18,13,11,18,
  142391. };
  142392. static static_codebook _huff_book__16u0__single = {
  142393. 2, 64,
  142394. _huff_lengthlist__16u0__single,
  142395. 0, 0, 0, 0, 0,
  142396. NULL,
  142397. NULL,
  142398. NULL,
  142399. NULL,
  142400. 0
  142401. };
  142402. static long _huff_lengthlist__16u1__long[] = {
  142403. 3, 6,10, 8,12, 8,14, 8,14,19, 5, 3, 5, 5, 7, 6,
  142404. 11, 7,16,19, 7, 5, 6, 7, 7, 9,11,12,19,19, 6, 4,
  142405. 7, 5, 7, 6,10, 7,18,18, 8, 6, 7, 7, 7, 7, 8, 9,
  142406. 18,18, 7, 5, 8, 5, 7, 5, 8, 6,18,18,12, 9,10, 9,
  142407. 9, 9, 8, 9,18,18, 8, 7,10, 6, 8, 5, 6, 4,11,18,
  142408. 11,15,16,12,11, 8, 8, 6, 9,18,14,18,18,18,16,16,
  142409. 16,13,16,18,
  142410. };
  142411. static static_codebook _huff_book__16u1__long = {
  142412. 2, 100,
  142413. _huff_lengthlist__16u1__long,
  142414. 0, 0, 0, 0, 0,
  142415. NULL,
  142416. NULL,
  142417. NULL,
  142418. NULL,
  142419. 0
  142420. };
  142421. static long _vq_quantlist__16u1__p1_0[] = {
  142422. 1,
  142423. 0,
  142424. 2,
  142425. };
  142426. static long _vq_lengthlist__16u1__p1_0[] = {
  142427. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 7, 7,10,10, 7,
  142428. 9,10, 5, 7, 8, 7,10, 9, 7,10,10, 5, 8, 8, 8,10,
  142429. 10, 8,10,10, 7,10,10,10,11,12,10,12,13, 7,10,10,
  142430. 9,13,11,10,12,13, 5, 8, 8, 8,10,10, 8,10,10, 7,
  142431. 10,10,10,12,12, 9,11,12, 7,10,11,10,12,12,10,13,
  142432. 11,
  142433. };
  142434. static float _vq_quantthresh__16u1__p1_0[] = {
  142435. -0.5, 0.5,
  142436. };
  142437. static long _vq_quantmap__16u1__p1_0[] = {
  142438. 1, 0, 2,
  142439. };
  142440. static encode_aux_threshmatch _vq_auxt__16u1__p1_0 = {
  142441. _vq_quantthresh__16u1__p1_0,
  142442. _vq_quantmap__16u1__p1_0,
  142443. 3,
  142444. 3
  142445. };
  142446. static static_codebook _16u1__p1_0 = {
  142447. 4, 81,
  142448. _vq_lengthlist__16u1__p1_0,
  142449. 1, -535822336, 1611661312, 2, 0,
  142450. _vq_quantlist__16u1__p1_0,
  142451. NULL,
  142452. &_vq_auxt__16u1__p1_0,
  142453. NULL,
  142454. 0
  142455. };
  142456. static long _vq_quantlist__16u1__p2_0[] = {
  142457. 1,
  142458. 0,
  142459. 2,
  142460. };
  142461. static long _vq_lengthlist__16u1__p2_0[] = {
  142462. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 7, 8, 6,
  142463. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 6, 8,
  142464. 8, 6, 8, 8, 6, 8, 8, 7, 7,10, 8, 9, 9, 6, 8, 8,
  142465. 7, 9, 8, 8, 9,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  142466. 8, 8, 8,10, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 7,10,
  142467. 8,
  142468. };
  142469. static float _vq_quantthresh__16u1__p2_0[] = {
  142470. -0.5, 0.5,
  142471. };
  142472. static long _vq_quantmap__16u1__p2_0[] = {
  142473. 1, 0, 2,
  142474. };
  142475. static encode_aux_threshmatch _vq_auxt__16u1__p2_0 = {
  142476. _vq_quantthresh__16u1__p2_0,
  142477. _vq_quantmap__16u1__p2_0,
  142478. 3,
  142479. 3
  142480. };
  142481. static static_codebook _16u1__p2_0 = {
  142482. 4, 81,
  142483. _vq_lengthlist__16u1__p2_0,
  142484. 1, -535822336, 1611661312, 2, 0,
  142485. _vq_quantlist__16u1__p2_0,
  142486. NULL,
  142487. &_vq_auxt__16u1__p2_0,
  142488. NULL,
  142489. 0
  142490. };
  142491. static long _vq_quantlist__16u1__p3_0[] = {
  142492. 2,
  142493. 1,
  142494. 3,
  142495. 0,
  142496. 4,
  142497. };
  142498. static long _vq_lengthlist__16u1__p3_0[] = {
  142499. 1, 5, 5, 8, 8, 6, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  142500. 10, 9,11,11, 9, 9,10,11,11, 6, 8, 8,10,10, 8, 9,
  142501. 10,11,11, 8, 9,10,11,11,10,11,11,12,13,10,11,11,
  142502. 13,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  142503. 11,10,11,11,13,13,10,11,11,13,12, 9,11,11,14,13,
  142504. 10,12,12,15,14,10,12,11,14,13,12,13,13,15,15,12,
  142505. 13,13,16,14, 9,11,11,13,14,10,11,12,14,14,10,12,
  142506. 12,14,15,12,13,13,14,15,12,13,14,15,16, 5, 8, 8,
  142507. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  142508. 14,11,12,12,14,14, 8,10,10,12,12, 9,11,12,12,13,
  142509. 10,12,12,13,13,12,12,13,14,15,11,13,13,15,15, 7,
  142510. 10,10,12,12, 9,12,11,13,12,10,11,12,13,13,12,13,
  142511. 12,15,14,11,12,13,15,15,10,12,12,15,14,11,13,13,
  142512. 16,15,11,13,13,16,15,14,13,14,15,16,13,15,15,17,
  142513. 17,10,12,12,14,15,11,12,12,15,15,11,13,13,15,16,
  142514. 13,15,13,16,15,13,15,15,16,17, 5, 8, 8,11,11, 8,
  142515. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  142516. 12,14,14, 7,10,10,12,12,10,12,12,14,13, 9,11,12,
  142517. 12,13,12,13,13,15,15,12,12,13,13,15, 7,10,10,12,
  142518. 13,10,11,12,13,13,10,12,11,13,13,11,13,13,15,15,
  142519. 12,13,12,15,14, 9,12,12,15,14,11,13,13,15,15,11,
  142520. 12,13,15,15,13,14,14,17,19,13,13,14,16,16,10,12,
  142521. 12,14,15,11,13,13,15,16,11,13,12,16,15,13,15,15,
  142522. 17,18,14,15,13,16,15, 8,11,11,15,14,10,12,12,16,
  142523. 15,10,12,12,16,16,14,15,15,18,17,13,14,15,16,18,
  142524. 9,12,12,15,15,11,12,14,16,17,11,13,13,16,15,15,
  142525. 15,15,17,18,14,15,16,17,17, 9,12,12,15,15,11,14,
  142526. 13,16,16,11,13,13,16,16,15,16,15,17,18,14,16,15,
  142527. 17,16,12,14,14,17,16,12,14,15,18,17,13,15,15,17,
  142528. 17,15,15,18,16,20,15,16,17,18,18,11,14,14,16,17,
  142529. 13,15,14,18,17,13,15,15,17,17,15,17,15,18,17,15,
  142530. 17,16,19,18, 8,11,11,14,15,10,12,12,15,15,10,12,
  142531. 12,16,16,13,14,14,17,16,14,15,15,17,17, 9,12,12,
  142532. 15,16,11,13,13,16,16,11,12,13,16,16,14,16,15,20,
  142533. 17,14,16,16,17,17, 9,12,12,15,16,11,13,13,16,17,
  142534. 11,13,13,17,16,14,15,15,17,18,15,15,15,18,18,11,
  142535. 14,14,17,16,13,15,15,17,17,13,14,14,18,17,15,16,
  142536. 16,18,19,15,15,17,17,19,11,14,14,16,17,13,15,14,
  142537. 17,19,13,15,14,18,17,15,17,16,18,18,15,17,15,18,
  142538. 16,
  142539. };
  142540. static float _vq_quantthresh__16u1__p3_0[] = {
  142541. -1.5, -0.5, 0.5, 1.5,
  142542. };
  142543. static long _vq_quantmap__16u1__p3_0[] = {
  142544. 3, 1, 0, 2, 4,
  142545. };
  142546. static encode_aux_threshmatch _vq_auxt__16u1__p3_0 = {
  142547. _vq_quantthresh__16u1__p3_0,
  142548. _vq_quantmap__16u1__p3_0,
  142549. 5,
  142550. 5
  142551. };
  142552. static static_codebook _16u1__p3_0 = {
  142553. 4, 625,
  142554. _vq_lengthlist__16u1__p3_0,
  142555. 1, -533725184, 1611661312, 3, 0,
  142556. _vq_quantlist__16u1__p3_0,
  142557. NULL,
  142558. &_vq_auxt__16u1__p3_0,
  142559. NULL,
  142560. 0
  142561. };
  142562. static long _vq_quantlist__16u1__p4_0[] = {
  142563. 2,
  142564. 1,
  142565. 3,
  142566. 0,
  142567. 4,
  142568. };
  142569. static long _vq_lengthlist__16u1__p4_0[] = {
  142570. 4, 5, 5, 8, 8, 6, 6, 7, 9, 9, 6, 6, 6, 9, 9, 9,
  142571. 10, 9,11,11, 9, 9,10,11,11, 6, 7, 7,10, 9, 7, 7,
  142572. 8, 9,10, 7, 7, 8,10,10,10,10,10,10,12, 9, 9,10,
  142573. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 7,10,
  142574. 10, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  142575. 10,10,10,12,12, 9,10,10,12,12,12,11,12,13,13,11,
  142576. 11,12,12,13, 9,10,10,11,12, 9,10,10,12,12,10,10,
  142577. 10,12,12,11,12,11,14,13,11,12,12,14,13, 5, 7, 7,
  142578. 10,10, 7, 8, 8,10,10, 7, 8, 7,10,10,10,10,10,12,
  142579. 12,10,10,10,12,12, 6, 8, 7,10,10, 7, 7, 9,10,11,
  142580. 8, 9, 9,11,10,10,10,11,11,13,10,10,11,12,13, 6,
  142581. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,10,11,10,11,
  142582. 10,13,11,10,11,10,12,12,10,11,10,12,11,10,10,10,
  142583. 12,13,10,11,11,13,12,11,11,13,11,14,12,12,13,14,
  142584. 14, 9,10,10,12,13,10,11,10,13,12,10,11,11,12,13,
  142585. 11,12,11,14,12,12,13,13,15,14, 5, 7, 7,10,10, 7,
  142586. 7, 8,10,10, 7, 8, 8,10,10,10,10,10,11,12,10,10,
  142587. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  142588. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 7, 8,10,
  142589. 10, 8, 8, 9,10,11, 7, 9, 7,11,10,10,11,11,13,12,
  142590. 11,11,10,13,11, 9,10,10,12,12,10,11,11,13,12,10,
  142591. 10,11,12,12,12,13,13,14,14,11,11,12,12,14,10,10,
  142592. 11,12,12,10,11,11,12,13,10,10,10,13,12,12,13,13,
  142593. 15,14,12,13,10,14,11, 8,10,10,12,12,10,11,10,13,
  142594. 13, 9,10,10,12,12,12,13,13,15,14,11,12,12,13,13,
  142595. 9,10,10,13,12,10,10,11,13,13,10,11,10,13,12,12,
  142596. 12,13,14,15,12,13,12,15,13, 9,10,10,12,13,10,11,
  142597. 10,13,12,10,10,11,12,13,12,14,12,15,13,12,12,13,
  142598. 14,15,11,12,11,14,13,11,11,12,14,15,12,13,12,15,
  142599. 14,13,11,15,11,16,13,14,14,16,15,11,12,12,14,14,
  142600. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,12,14,
  142601. 14,14,15,15, 8,10,10,12,12, 9,10,10,12,12,10,10,
  142602. 11,13,13,11,12,12,13,13,12,13,13,14,15, 9,10,10,
  142603. 13,12,10,11,11,13,12,10,10,11,13,13,12,13,12,15,
  142604. 14,12,12,13,13,16, 9, 9,10,12,13,10,10,11,12,13,
  142605. 10,11,10,13,13,12,12,13,13,15,13,13,12,15,13,11,
  142606. 12,12,14,14,12,13,12,15,14,11,11,12,13,14,14,14,
  142607. 14,16,15,13,12,15,12,16,11,11,12,13,14,12,13,13,
  142608. 14,15,10,12,11,14,13,14,15,14,16,16,13,14,11,15,
  142609. 11,
  142610. };
  142611. static float _vq_quantthresh__16u1__p4_0[] = {
  142612. -1.5, -0.5, 0.5, 1.5,
  142613. };
  142614. static long _vq_quantmap__16u1__p4_0[] = {
  142615. 3, 1, 0, 2, 4,
  142616. };
  142617. static encode_aux_threshmatch _vq_auxt__16u1__p4_0 = {
  142618. _vq_quantthresh__16u1__p4_0,
  142619. _vq_quantmap__16u1__p4_0,
  142620. 5,
  142621. 5
  142622. };
  142623. static static_codebook _16u1__p4_0 = {
  142624. 4, 625,
  142625. _vq_lengthlist__16u1__p4_0,
  142626. 1, -533725184, 1611661312, 3, 0,
  142627. _vq_quantlist__16u1__p4_0,
  142628. NULL,
  142629. &_vq_auxt__16u1__p4_0,
  142630. NULL,
  142631. 0
  142632. };
  142633. static long _vq_quantlist__16u1__p5_0[] = {
  142634. 4,
  142635. 3,
  142636. 5,
  142637. 2,
  142638. 6,
  142639. 1,
  142640. 7,
  142641. 0,
  142642. 8,
  142643. };
  142644. static long _vq_lengthlist__16u1__p5_0[] = {
  142645. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  142646. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  142647. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  142648. 10, 9,11,11,12,11, 7, 8, 8, 9, 9,11,11,12,12, 9,
  142649. 10,10,11,11,12,12,13,12, 9,10,10,11,11,12,12,12,
  142650. 13,
  142651. };
  142652. static float _vq_quantthresh__16u1__p5_0[] = {
  142653. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  142654. };
  142655. static long _vq_quantmap__16u1__p5_0[] = {
  142656. 7, 5, 3, 1, 0, 2, 4, 6,
  142657. 8,
  142658. };
  142659. static encode_aux_threshmatch _vq_auxt__16u1__p5_0 = {
  142660. _vq_quantthresh__16u1__p5_0,
  142661. _vq_quantmap__16u1__p5_0,
  142662. 9,
  142663. 9
  142664. };
  142665. static static_codebook _16u1__p5_0 = {
  142666. 2, 81,
  142667. _vq_lengthlist__16u1__p5_0,
  142668. 1, -531628032, 1611661312, 4, 0,
  142669. _vq_quantlist__16u1__p5_0,
  142670. NULL,
  142671. &_vq_auxt__16u1__p5_0,
  142672. NULL,
  142673. 0
  142674. };
  142675. static long _vq_quantlist__16u1__p6_0[] = {
  142676. 4,
  142677. 3,
  142678. 5,
  142679. 2,
  142680. 6,
  142681. 1,
  142682. 7,
  142683. 0,
  142684. 8,
  142685. };
  142686. static long _vq_lengthlist__16u1__p6_0[] = {
  142687. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 4, 6, 6, 8, 8,
  142688. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  142689. 8, 8,10, 9, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  142690. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  142691. 9, 9,10,10,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  142692. 11,
  142693. };
  142694. static float _vq_quantthresh__16u1__p6_0[] = {
  142695. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  142696. };
  142697. static long _vq_quantmap__16u1__p6_0[] = {
  142698. 7, 5, 3, 1, 0, 2, 4, 6,
  142699. 8,
  142700. };
  142701. static encode_aux_threshmatch _vq_auxt__16u1__p6_0 = {
  142702. _vq_quantthresh__16u1__p6_0,
  142703. _vq_quantmap__16u1__p6_0,
  142704. 9,
  142705. 9
  142706. };
  142707. static static_codebook _16u1__p6_0 = {
  142708. 2, 81,
  142709. _vq_lengthlist__16u1__p6_0,
  142710. 1, -531628032, 1611661312, 4, 0,
  142711. _vq_quantlist__16u1__p6_0,
  142712. NULL,
  142713. &_vq_auxt__16u1__p6_0,
  142714. NULL,
  142715. 0
  142716. };
  142717. static long _vq_quantlist__16u1__p7_0[] = {
  142718. 1,
  142719. 0,
  142720. 2,
  142721. };
  142722. static long _vq_lengthlist__16u1__p7_0[] = {
  142723. 1, 4, 4, 4, 8, 8, 4, 8, 8, 5,11, 9, 8,12,11, 8,
  142724. 12,11, 5,10,11, 8,11,12, 8,11,12, 4,11,11,11,14,
  142725. 13,10,13,13, 8,14,13,12,14,16,12,16,15, 8,14,14,
  142726. 13,16,14,12,15,16, 4,11,11,10,14,13,11,14,14, 8,
  142727. 15,14,12,15,15,12,14,16, 8,14,14,11,16,15,12,15,
  142728. 13,
  142729. };
  142730. static float _vq_quantthresh__16u1__p7_0[] = {
  142731. -5.5, 5.5,
  142732. };
  142733. static long _vq_quantmap__16u1__p7_0[] = {
  142734. 1, 0, 2,
  142735. };
  142736. static encode_aux_threshmatch _vq_auxt__16u1__p7_0 = {
  142737. _vq_quantthresh__16u1__p7_0,
  142738. _vq_quantmap__16u1__p7_0,
  142739. 3,
  142740. 3
  142741. };
  142742. static static_codebook _16u1__p7_0 = {
  142743. 4, 81,
  142744. _vq_lengthlist__16u1__p7_0,
  142745. 1, -529137664, 1618345984, 2, 0,
  142746. _vq_quantlist__16u1__p7_0,
  142747. NULL,
  142748. &_vq_auxt__16u1__p7_0,
  142749. NULL,
  142750. 0
  142751. };
  142752. static long _vq_quantlist__16u1__p7_1[] = {
  142753. 5,
  142754. 4,
  142755. 6,
  142756. 3,
  142757. 7,
  142758. 2,
  142759. 8,
  142760. 1,
  142761. 9,
  142762. 0,
  142763. 10,
  142764. };
  142765. static long _vq_lengthlist__16u1__p7_1[] = {
  142766. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 5, 7, 7,
  142767. 8, 8, 8, 8, 8, 8, 4, 5, 6, 7, 7, 8, 8, 8, 8, 8,
  142768. 8, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  142769. 8, 8, 8, 9, 9, 9, 9, 7, 8, 8, 8, 8, 9, 9, 9,10,
  142770. 9,10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10, 9, 8, 8, 8,
  142771. 9, 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,10,
  142772. 10,10,10, 8, 8, 8, 9, 9, 9,10,10,10,10,10, 8, 8,
  142773. 8, 9, 9,10,10,10,10,10,10,
  142774. };
  142775. static float _vq_quantthresh__16u1__p7_1[] = {
  142776. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  142777. 3.5, 4.5,
  142778. };
  142779. static long _vq_quantmap__16u1__p7_1[] = {
  142780. 9, 7, 5, 3, 1, 0, 2, 4,
  142781. 6, 8, 10,
  142782. };
  142783. static encode_aux_threshmatch _vq_auxt__16u1__p7_1 = {
  142784. _vq_quantthresh__16u1__p7_1,
  142785. _vq_quantmap__16u1__p7_1,
  142786. 11,
  142787. 11
  142788. };
  142789. static static_codebook _16u1__p7_1 = {
  142790. 2, 121,
  142791. _vq_lengthlist__16u1__p7_1,
  142792. 1, -531365888, 1611661312, 4, 0,
  142793. _vq_quantlist__16u1__p7_1,
  142794. NULL,
  142795. &_vq_auxt__16u1__p7_1,
  142796. NULL,
  142797. 0
  142798. };
  142799. static long _vq_quantlist__16u1__p8_0[] = {
  142800. 5,
  142801. 4,
  142802. 6,
  142803. 3,
  142804. 7,
  142805. 2,
  142806. 8,
  142807. 1,
  142808. 9,
  142809. 0,
  142810. 10,
  142811. };
  142812. static long _vq_lengthlist__16u1__p8_0[] = {
  142813. 1, 4, 4, 5, 5, 8, 8,10,10,12,12, 4, 7, 7, 8, 8,
  142814. 9, 9,12,11,14,13, 4, 7, 7, 7, 8, 9,10,11,11,13,
  142815. 12, 5, 8, 8, 9, 9,11,11,12,13,15,14, 5, 7, 8, 9,
  142816. 9,11,11,13,13,17,15, 8, 9,10,11,11,12,13,17,14,
  142817. 17,16, 8,10, 9,11,11,12,12,13,15,15,17,10,11,11,
  142818. 12,13,14,15,15,16,16,17, 9,11,11,12,12,14,15,17,
  142819. 15,15,16,11,14,12,14,15,16,15,16,16,16,15,11,13,
  142820. 13,14,14,15,15,16,16,15,16,
  142821. };
  142822. static float _vq_quantthresh__16u1__p8_0[] = {
  142823. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  142824. 38.5, 49.5,
  142825. };
  142826. static long _vq_quantmap__16u1__p8_0[] = {
  142827. 9, 7, 5, 3, 1, 0, 2, 4,
  142828. 6, 8, 10,
  142829. };
  142830. static encode_aux_threshmatch _vq_auxt__16u1__p8_0 = {
  142831. _vq_quantthresh__16u1__p8_0,
  142832. _vq_quantmap__16u1__p8_0,
  142833. 11,
  142834. 11
  142835. };
  142836. static static_codebook _16u1__p8_0 = {
  142837. 2, 121,
  142838. _vq_lengthlist__16u1__p8_0,
  142839. 1, -524582912, 1618345984, 4, 0,
  142840. _vq_quantlist__16u1__p8_0,
  142841. NULL,
  142842. &_vq_auxt__16u1__p8_0,
  142843. NULL,
  142844. 0
  142845. };
  142846. static long _vq_quantlist__16u1__p8_1[] = {
  142847. 5,
  142848. 4,
  142849. 6,
  142850. 3,
  142851. 7,
  142852. 2,
  142853. 8,
  142854. 1,
  142855. 9,
  142856. 0,
  142857. 10,
  142858. };
  142859. static long _vq_lengthlist__16u1__p8_1[] = {
  142860. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7,
  142861. 8, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  142862. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 6, 7, 7, 7,
  142863. 7, 8, 8, 8, 8, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  142864. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  142865. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  142866. 9, 9, 9, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  142867. 8, 9, 9, 9, 9, 9, 9, 9, 9,
  142868. };
  142869. static float _vq_quantthresh__16u1__p8_1[] = {
  142870. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  142871. 3.5, 4.5,
  142872. };
  142873. static long _vq_quantmap__16u1__p8_1[] = {
  142874. 9, 7, 5, 3, 1, 0, 2, 4,
  142875. 6, 8, 10,
  142876. };
  142877. static encode_aux_threshmatch _vq_auxt__16u1__p8_1 = {
  142878. _vq_quantthresh__16u1__p8_1,
  142879. _vq_quantmap__16u1__p8_1,
  142880. 11,
  142881. 11
  142882. };
  142883. static static_codebook _16u1__p8_1 = {
  142884. 2, 121,
  142885. _vq_lengthlist__16u1__p8_1,
  142886. 1, -531365888, 1611661312, 4, 0,
  142887. _vq_quantlist__16u1__p8_1,
  142888. NULL,
  142889. &_vq_auxt__16u1__p8_1,
  142890. NULL,
  142891. 0
  142892. };
  142893. static long _vq_quantlist__16u1__p9_0[] = {
  142894. 7,
  142895. 6,
  142896. 8,
  142897. 5,
  142898. 9,
  142899. 4,
  142900. 10,
  142901. 3,
  142902. 11,
  142903. 2,
  142904. 12,
  142905. 1,
  142906. 13,
  142907. 0,
  142908. 14,
  142909. };
  142910. static long _vq_lengthlist__16u1__p9_0[] = {
  142911. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  142912. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  142913. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  142914. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  142915. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  142916. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  142917. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  142918. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  142919. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  142920. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  142921. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  142922. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  142923. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  142924. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  142925. 8,
  142926. };
  142927. static float _vq_quantthresh__16u1__p9_0[] = {
  142928. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  142929. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  142930. };
  142931. static long _vq_quantmap__16u1__p9_0[] = {
  142932. 13, 11, 9, 7, 5, 3, 1, 0,
  142933. 2, 4, 6, 8, 10, 12, 14,
  142934. };
  142935. static encode_aux_threshmatch _vq_auxt__16u1__p9_0 = {
  142936. _vq_quantthresh__16u1__p9_0,
  142937. _vq_quantmap__16u1__p9_0,
  142938. 15,
  142939. 15
  142940. };
  142941. static static_codebook _16u1__p9_0 = {
  142942. 2, 225,
  142943. _vq_lengthlist__16u1__p9_0,
  142944. 1, -514071552, 1627381760, 4, 0,
  142945. _vq_quantlist__16u1__p9_0,
  142946. NULL,
  142947. &_vq_auxt__16u1__p9_0,
  142948. NULL,
  142949. 0
  142950. };
  142951. static long _vq_quantlist__16u1__p9_1[] = {
  142952. 7,
  142953. 6,
  142954. 8,
  142955. 5,
  142956. 9,
  142957. 4,
  142958. 10,
  142959. 3,
  142960. 11,
  142961. 2,
  142962. 12,
  142963. 1,
  142964. 13,
  142965. 0,
  142966. 14,
  142967. };
  142968. static long _vq_lengthlist__16u1__p9_1[] = {
  142969. 1, 6, 5, 9, 9,10,10, 6, 7, 9, 9,10,10,10,10, 5,
  142970. 10, 8,10, 8,10,10, 8, 8,10, 9,10,10,10,10, 5, 8,
  142971. 9,10,10,10,10, 8,10,10,10,10,10,10,10, 9,10,10,
  142972. 10,10,10,10, 9, 9,10,10,10,10,10,10, 9, 9, 8, 9,
  142973. 10,10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  142974. 10,10,10,10,10,10,10,10,10,10,10, 8,10,10,10,10,
  142975. 10,10,10,10,10,10,10,10,10, 6, 8, 8,10,10,10, 8,
  142976. 10,10,10,10,10,10,10,10, 5, 8, 8,10,10,10, 9, 9,
  142977. 10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,10,
  142978. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142979. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  142980. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  142981. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  142982. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  142983. 9,
  142984. };
  142985. static float _vq_quantthresh__16u1__p9_1[] = {
  142986. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  142987. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  142988. };
  142989. static long _vq_quantmap__16u1__p9_1[] = {
  142990. 13, 11, 9, 7, 5, 3, 1, 0,
  142991. 2, 4, 6, 8, 10, 12, 14,
  142992. };
  142993. static encode_aux_threshmatch _vq_auxt__16u1__p9_1 = {
  142994. _vq_quantthresh__16u1__p9_1,
  142995. _vq_quantmap__16u1__p9_1,
  142996. 15,
  142997. 15
  142998. };
  142999. static static_codebook _16u1__p9_1 = {
  143000. 2, 225,
  143001. _vq_lengthlist__16u1__p9_1,
  143002. 1, -522338304, 1620115456, 4, 0,
  143003. _vq_quantlist__16u1__p9_1,
  143004. NULL,
  143005. &_vq_auxt__16u1__p9_1,
  143006. NULL,
  143007. 0
  143008. };
  143009. static long _vq_quantlist__16u1__p9_2[] = {
  143010. 8,
  143011. 7,
  143012. 9,
  143013. 6,
  143014. 10,
  143015. 5,
  143016. 11,
  143017. 4,
  143018. 12,
  143019. 3,
  143020. 13,
  143021. 2,
  143022. 14,
  143023. 1,
  143024. 15,
  143025. 0,
  143026. 16,
  143027. };
  143028. static long _vq_lengthlist__16u1__p9_2[] = {
  143029. 1, 6, 6, 7, 8, 8,11,10, 9, 9,11, 9,10, 9,11,11,
  143030. 9, 6, 7, 6,11, 8,11, 9,10,10,11, 9,11,10,10,10,
  143031. 11, 9, 5, 7, 7, 8, 8,10,11, 8, 8,11, 9, 9,10,11,
  143032. 9,10,11, 8, 9, 6, 8, 8, 9, 9,10,10,11,11,11, 9,
  143033. 11,10, 9,11, 8, 8, 8, 9, 8, 9,10,11, 9, 9,11,11,
  143034. 10, 9, 9,11,10, 8,11, 8, 9, 8,11, 9,10, 9,10,11,
  143035. 11,10,10, 9,10,10, 8, 8, 9,10,10,10, 9,11, 9,10,
  143036. 11,11,11,11,10, 9,11, 9, 9,11,11,10, 8,11,11,11,
  143037. 9,10,10,11,10,11,11, 9,11,10, 9,11,10,10,10,10,
  143038. 9,11,10,11,10, 9, 9,10,11, 9, 8,10,11,11,10,10,
  143039. 11, 9,11,10,11,11,10,11, 9, 9, 8,10, 8, 9,11, 9,
  143040. 8,10,10, 9,11,10,11,10,11, 9,11, 8,10,11,11,11,
  143041. 11,10,10,11,11,11,11,10,11,11,10, 9, 8,10,10, 9,
  143042. 11,10,11,11,11, 9, 9, 9,11,11,11,10,10, 9, 9,10,
  143043. 9,11,11,11,11, 8,10,11,10,11,11,10,11,11, 9, 9,
  143044. 9,10, 9,11, 9,11,11,11,11,11,10,11,11,10,11,10,
  143045. 11,11, 9,11,10,11,10, 9,10, 9,10,10,11,11,11,11,
  143046. 9,10, 9,10,11,11,10,11,11,11,11,11,11,10,11,11,
  143047. 10,
  143048. };
  143049. static float _vq_quantthresh__16u1__p9_2[] = {
  143050. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  143051. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  143052. };
  143053. static long _vq_quantmap__16u1__p9_2[] = {
  143054. 15, 13, 11, 9, 7, 5, 3, 1,
  143055. 0, 2, 4, 6, 8, 10, 12, 14,
  143056. 16,
  143057. };
  143058. static encode_aux_threshmatch _vq_auxt__16u1__p9_2 = {
  143059. _vq_quantthresh__16u1__p9_2,
  143060. _vq_quantmap__16u1__p9_2,
  143061. 17,
  143062. 17
  143063. };
  143064. static static_codebook _16u1__p9_2 = {
  143065. 2, 289,
  143066. _vq_lengthlist__16u1__p9_2,
  143067. 1, -529530880, 1611661312, 5, 0,
  143068. _vq_quantlist__16u1__p9_2,
  143069. NULL,
  143070. &_vq_auxt__16u1__p9_2,
  143071. NULL,
  143072. 0
  143073. };
  143074. static long _huff_lengthlist__16u1__short[] = {
  143075. 5, 7,10, 9,11,10,15,11,13,16, 6, 4, 6, 6, 7, 7,
  143076. 10, 9,12,16,10, 6, 5, 6, 6, 7,10,11,16,16, 9, 6,
  143077. 7, 6, 7, 7,10, 8,14,16,11, 6, 5, 4, 5, 6, 8, 9,
  143078. 15,16, 9, 6, 6, 5, 6, 6, 9, 8,14,16,12, 7, 6, 6,
  143079. 5, 6, 6, 7,13,16, 8, 6, 7, 6, 5, 5, 4, 4,11,16,
  143080. 9, 8, 9, 9, 7, 7, 6, 5,13,16,14,14,16,15,16,15,
  143081. 16,16,16,16,
  143082. };
  143083. static static_codebook _huff_book__16u1__short = {
  143084. 2, 100,
  143085. _huff_lengthlist__16u1__short,
  143086. 0, 0, 0, 0, 0,
  143087. NULL,
  143088. NULL,
  143089. NULL,
  143090. NULL,
  143091. 0
  143092. };
  143093. static long _huff_lengthlist__16u2__long[] = {
  143094. 5, 7,10,10,10,11,11,13,18,19, 6, 5, 5, 6, 7, 8,
  143095. 9,12,19,19, 8, 5, 4, 4, 6, 7, 9,13,19,19, 8, 5,
  143096. 4, 4, 5, 6, 8,12,17,19, 7, 5, 5, 4, 4, 5, 7,12,
  143097. 18,18, 8, 7, 7, 6, 5, 5, 6,10,18,18, 9, 9, 9, 8,
  143098. 6, 5, 6, 9,18,18,11,13,13,13, 8, 7, 7, 9,16,18,
  143099. 13,17,18,16,11, 9, 9, 9,17,18,15,18,18,18,15,13,
  143100. 13,14,18,18,
  143101. };
  143102. static static_codebook _huff_book__16u2__long = {
  143103. 2, 100,
  143104. _huff_lengthlist__16u2__long,
  143105. 0, 0, 0, 0, 0,
  143106. NULL,
  143107. NULL,
  143108. NULL,
  143109. NULL,
  143110. 0
  143111. };
  143112. static long _huff_lengthlist__16u2__short[] = {
  143113. 8,11,12,12,14,15,16,16,16,16, 9, 7, 7, 8, 9,11,
  143114. 13,14,16,16,13, 7, 6, 6, 7, 9,12,13,15,16,15, 7,
  143115. 6, 5, 4, 6,10,11,14,16,12, 8, 7, 4, 2, 4, 7,10,
  143116. 14,16,11, 9, 7, 5, 3, 4, 6, 9,14,16,11,10, 9, 7,
  143117. 5, 5, 6, 9,16,16,10,10, 9, 8, 6, 6, 7,10,16,16,
  143118. 11,11,11,10,10,10,11,14,16,16,16,14,14,13,14,16,
  143119. 16,16,16,16,
  143120. };
  143121. static static_codebook _huff_book__16u2__short = {
  143122. 2, 100,
  143123. _huff_lengthlist__16u2__short,
  143124. 0, 0, 0, 0, 0,
  143125. NULL,
  143126. NULL,
  143127. NULL,
  143128. NULL,
  143129. 0
  143130. };
  143131. static long _vq_quantlist__16u2_p1_0[] = {
  143132. 1,
  143133. 0,
  143134. 2,
  143135. };
  143136. static long _vq_lengthlist__16u2_p1_0[] = {
  143137. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  143138. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 8, 9,
  143139. 9, 7, 9, 9, 7, 9, 9, 9,10,10, 9,10,10, 7, 9, 9,
  143140. 9,10,10, 9,10,11, 5, 7, 8, 8, 9, 9, 8, 9, 9, 7,
  143141. 9, 9, 9,10,10, 9, 9,10, 7, 9, 9, 9,10,10, 9,11,
  143142. 10,
  143143. };
  143144. static float _vq_quantthresh__16u2_p1_0[] = {
  143145. -0.5, 0.5,
  143146. };
  143147. static long _vq_quantmap__16u2_p1_0[] = {
  143148. 1, 0, 2,
  143149. };
  143150. static encode_aux_threshmatch _vq_auxt__16u2_p1_0 = {
  143151. _vq_quantthresh__16u2_p1_0,
  143152. _vq_quantmap__16u2_p1_0,
  143153. 3,
  143154. 3
  143155. };
  143156. static static_codebook _16u2_p1_0 = {
  143157. 4, 81,
  143158. _vq_lengthlist__16u2_p1_0,
  143159. 1, -535822336, 1611661312, 2, 0,
  143160. _vq_quantlist__16u2_p1_0,
  143161. NULL,
  143162. &_vq_auxt__16u2_p1_0,
  143163. NULL,
  143164. 0
  143165. };
  143166. static long _vq_quantlist__16u2_p2_0[] = {
  143167. 2,
  143168. 1,
  143169. 3,
  143170. 0,
  143171. 4,
  143172. };
  143173. static long _vq_lengthlist__16u2_p2_0[] = {
  143174. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  143175. 10, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  143176. 8,10,10, 7, 8, 8,10,10,10,10,10,12,12, 9,10,10,
  143177. 11,12, 5, 7, 7, 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,
  143178. 10, 9,10,10,12,11,10,10,10,12,12, 9,10,10,12,12,
  143179. 10,11,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  143180. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,12,10,10,
  143181. 10,12,12,11,12,12,14,13,12,13,12,14,14, 5, 7, 7,
  143182. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  143183. 12,10,10,11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  143184. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,12,13, 7,
  143185. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  143186. 10,13,12,10,11,11,13,13, 9,11,10,13,13,10,11,11,
  143187. 13,13,10,11,11,13,13,12,12,13,13,15,12,12,13,14,
  143188. 15, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  143189. 11,13,11,14,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  143190. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  143191. 11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  143192. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  143193. 11, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,12,
  143194. 11,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  143195. 10,11,12,13,12,13,13,15,14,11,11,13,12,14,10,10,
  143196. 11,13,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  143197. 14,14,12,13,12,14,13, 8,10, 9,12,12, 9,11,10,13,
  143198. 13, 9,10,10,12,13,12,13,13,14,14,12,12,13,14,14,
  143199. 9,11,10,13,13,10,11,11,13,13,10,11,11,13,13,12,
  143200. 13,13,15,15,13,13,13,14,15, 9,10,10,12,13,10,11,
  143201. 10,13,12,10,11,11,13,13,12,13,12,15,14,13,13,13,
  143202. 14,15,11,12,12,15,14,12,12,13,15,15,12,13,13,15,
  143203. 14,14,13,15,14,16,13,14,15,16,16,11,12,12,14,14,
  143204. 11,12,12,15,14,12,13,13,15,15,13,14,13,16,14,14,
  143205. 14,14,16,16, 8, 9, 9,12,12, 9,10,10,13,12, 9,10,
  143206. 10,13,13,12,12,12,14,14,12,12,13,15,15, 9,10,10,
  143207. 13,12,10,11,11,13,13,10,10,11,13,14,12,13,13,15,
  143208. 15,12,12,13,14,15, 9,10,10,13,13,10,11,11,13,13,
  143209. 10,11,11,13,13,12,13,13,14,14,13,14,13,15,14,11,
  143210. 12,12,14,14,12,13,13,15,14,11,12,12,14,15,14,14,
  143211. 14,16,15,13,12,14,14,16,11,12,13,14,15,12,13,13,
  143212. 14,16,12,13,12,15,14,13,15,14,16,16,14,15,13,16,
  143213. 13,
  143214. };
  143215. static float _vq_quantthresh__16u2_p2_0[] = {
  143216. -1.5, -0.5, 0.5, 1.5,
  143217. };
  143218. static long _vq_quantmap__16u2_p2_0[] = {
  143219. 3, 1, 0, 2, 4,
  143220. };
  143221. static encode_aux_threshmatch _vq_auxt__16u2_p2_0 = {
  143222. _vq_quantthresh__16u2_p2_0,
  143223. _vq_quantmap__16u2_p2_0,
  143224. 5,
  143225. 5
  143226. };
  143227. static static_codebook _16u2_p2_0 = {
  143228. 4, 625,
  143229. _vq_lengthlist__16u2_p2_0,
  143230. 1, -533725184, 1611661312, 3, 0,
  143231. _vq_quantlist__16u2_p2_0,
  143232. NULL,
  143233. &_vq_auxt__16u2_p2_0,
  143234. NULL,
  143235. 0
  143236. };
  143237. static long _vq_quantlist__16u2_p3_0[] = {
  143238. 4,
  143239. 3,
  143240. 5,
  143241. 2,
  143242. 6,
  143243. 1,
  143244. 7,
  143245. 0,
  143246. 8,
  143247. };
  143248. static long _vq_lengthlist__16u2_p3_0[] = {
  143249. 2, 4, 4, 6, 6, 7, 7, 9, 9, 4, 5, 5, 6, 6, 8, 7,
  143250. 9, 9, 4, 5, 5, 6, 6, 7, 8, 9, 9, 6, 6, 6, 7, 7,
  143251. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  143252. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  143253. 9, 9,10, 9,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  143254. 11,
  143255. };
  143256. static float _vq_quantthresh__16u2_p3_0[] = {
  143257. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143258. };
  143259. static long _vq_quantmap__16u2_p3_0[] = {
  143260. 7, 5, 3, 1, 0, 2, 4, 6,
  143261. 8,
  143262. };
  143263. static encode_aux_threshmatch _vq_auxt__16u2_p3_0 = {
  143264. _vq_quantthresh__16u2_p3_0,
  143265. _vq_quantmap__16u2_p3_0,
  143266. 9,
  143267. 9
  143268. };
  143269. static static_codebook _16u2_p3_0 = {
  143270. 2, 81,
  143271. _vq_lengthlist__16u2_p3_0,
  143272. 1, -531628032, 1611661312, 4, 0,
  143273. _vq_quantlist__16u2_p3_0,
  143274. NULL,
  143275. &_vq_auxt__16u2_p3_0,
  143276. NULL,
  143277. 0
  143278. };
  143279. static long _vq_quantlist__16u2_p4_0[] = {
  143280. 8,
  143281. 7,
  143282. 9,
  143283. 6,
  143284. 10,
  143285. 5,
  143286. 11,
  143287. 4,
  143288. 12,
  143289. 3,
  143290. 13,
  143291. 2,
  143292. 14,
  143293. 1,
  143294. 15,
  143295. 0,
  143296. 16,
  143297. };
  143298. static long _vq_lengthlist__16u2_p4_0[] = {
  143299. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,11,
  143300. 11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  143301. 12,11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  143302. 11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  143303. 11,11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,
  143304. 10,11,11,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  143305. 11,11,12,12,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  143306. 10,11,11,11,12,12,12, 9, 9, 9, 9, 9, 9,10,10,10,
  143307. 10,10,11,11,12,12,13,13, 8, 9, 9, 9, 9,10, 9,10,
  143308. 10,10,10,11,11,12,12,13,13, 9, 9, 9, 9, 9,10,10,
  143309. 10,10,11,11,11,12,12,12,13,13, 9, 9, 9, 9, 9,10,
  143310. 10,10,10,11,11,12,11,12,12,13,13,10,10,10,10,10,
  143311. 11,11,11,11,11,12,12,12,12,13,13,14,10,10,10,10,
  143312. 10,11,11,11,11,12,11,12,12,13,12,13,13,11,11,11,
  143313. 11,11,12,12,12,12,12,12,13,13,13,13,14,14,11,11,
  143314. 11,11,11,12,12,12,12,12,12,13,12,13,13,14,14,11,
  143315. 12,12,12,12,12,12,13,13,13,13,13,13,14,14,14,14,
  143316. 11,12,12,12,12,12,12,13,13,13,13,14,13,14,14,14,
  143317. 14,
  143318. };
  143319. static float _vq_quantthresh__16u2_p4_0[] = {
  143320. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  143321. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  143322. };
  143323. static long _vq_quantmap__16u2_p4_0[] = {
  143324. 15, 13, 11, 9, 7, 5, 3, 1,
  143325. 0, 2, 4, 6, 8, 10, 12, 14,
  143326. 16,
  143327. };
  143328. static encode_aux_threshmatch _vq_auxt__16u2_p4_0 = {
  143329. _vq_quantthresh__16u2_p4_0,
  143330. _vq_quantmap__16u2_p4_0,
  143331. 17,
  143332. 17
  143333. };
  143334. static static_codebook _16u2_p4_0 = {
  143335. 2, 289,
  143336. _vq_lengthlist__16u2_p4_0,
  143337. 1, -529530880, 1611661312, 5, 0,
  143338. _vq_quantlist__16u2_p4_0,
  143339. NULL,
  143340. &_vq_auxt__16u2_p4_0,
  143341. NULL,
  143342. 0
  143343. };
  143344. static long _vq_quantlist__16u2_p5_0[] = {
  143345. 1,
  143346. 0,
  143347. 2,
  143348. };
  143349. static long _vq_lengthlist__16u2_p5_0[] = {
  143350. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10, 9, 7,
  143351. 10, 9, 5, 8, 9, 7, 9,10, 7, 9,10, 4, 9, 9, 9,11,
  143352. 11, 8,11,11, 7,11,11,10,10,13,10,14,13, 7,11,11,
  143353. 10,13,11,10,13,14, 5, 9, 9, 8,11,11, 9,11,11, 7,
  143354. 11,11,10,14,13,10,12,14, 7,11,11,10,13,13,10,13,
  143355. 10,
  143356. };
  143357. static float _vq_quantthresh__16u2_p5_0[] = {
  143358. -5.5, 5.5,
  143359. };
  143360. static long _vq_quantmap__16u2_p5_0[] = {
  143361. 1, 0, 2,
  143362. };
  143363. static encode_aux_threshmatch _vq_auxt__16u2_p5_0 = {
  143364. _vq_quantthresh__16u2_p5_0,
  143365. _vq_quantmap__16u2_p5_0,
  143366. 3,
  143367. 3
  143368. };
  143369. static static_codebook _16u2_p5_0 = {
  143370. 4, 81,
  143371. _vq_lengthlist__16u2_p5_0,
  143372. 1, -529137664, 1618345984, 2, 0,
  143373. _vq_quantlist__16u2_p5_0,
  143374. NULL,
  143375. &_vq_auxt__16u2_p5_0,
  143376. NULL,
  143377. 0
  143378. };
  143379. static long _vq_quantlist__16u2_p5_1[] = {
  143380. 5,
  143381. 4,
  143382. 6,
  143383. 3,
  143384. 7,
  143385. 2,
  143386. 8,
  143387. 1,
  143388. 9,
  143389. 0,
  143390. 10,
  143391. };
  143392. static long _vq_lengthlist__16u2_p5_1[] = {
  143393. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 5, 5, 5, 7, 7,
  143394. 7, 7, 8, 8, 8, 8, 5, 5, 6, 7, 7, 7, 7, 8, 8, 8,
  143395. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  143396. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  143397. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  143398. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  143399. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  143400. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  143401. };
  143402. static float _vq_quantthresh__16u2_p5_1[] = {
  143403. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  143404. 3.5, 4.5,
  143405. };
  143406. static long _vq_quantmap__16u2_p5_1[] = {
  143407. 9, 7, 5, 3, 1, 0, 2, 4,
  143408. 6, 8, 10,
  143409. };
  143410. static encode_aux_threshmatch _vq_auxt__16u2_p5_1 = {
  143411. _vq_quantthresh__16u2_p5_1,
  143412. _vq_quantmap__16u2_p5_1,
  143413. 11,
  143414. 11
  143415. };
  143416. static static_codebook _16u2_p5_1 = {
  143417. 2, 121,
  143418. _vq_lengthlist__16u2_p5_1,
  143419. 1, -531365888, 1611661312, 4, 0,
  143420. _vq_quantlist__16u2_p5_1,
  143421. NULL,
  143422. &_vq_auxt__16u2_p5_1,
  143423. NULL,
  143424. 0
  143425. };
  143426. static long _vq_quantlist__16u2_p6_0[] = {
  143427. 6,
  143428. 5,
  143429. 7,
  143430. 4,
  143431. 8,
  143432. 3,
  143433. 9,
  143434. 2,
  143435. 10,
  143436. 1,
  143437. 11,
  143438. 0,
  143439. 12,
  143440. };
  143441. static long _vq_lengthlist__16u2_p6_0[] = {
  143442. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6,
  143443. 8, 8, 9, 9, 9, 9,10,10,12,11, 4, 6, 6, 8, 8, 9,
  143444. 9, 9, 9,10,10,11,12, 7, 8, 8, 9, 9,10,10,10,10,
  143445. 12,12,13,12, 7, 8, 8, 9, 9,10,10,10,10,11,12,12,
  143446. 12, 8, 9, 9,10,10,11,11,11,11,12,12,13,13, 8, 9,
  143447. 9,10,10,11,11,11,11,12,13,13,13, 8, 9, 9,10,10,
  143448. 11,11,12,12,13,13,14,14, 8, 9, 9,10,10,11,11,12,
  143449. 12,13,13,14,14, 9,10,10,11,12,13,12,13,14,14,14,
  143450. 14,14, 9,10,10,11,12,12,13,13,13,14,14,14,14,10,
  143451. 11,11,12,12,13,13,14,14,15,15,15,15,10,11,11,12,
  143452. 12,13,13,14,14,14,14,15,15,
  143453. };
  143454. static float _vq_quantthresh__16u2_p6_0[] = {
  143455. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  143456. 12.5, 17.5, 22.5, 27.5,
  143457. };
  143458. static long _vq_quantmap__16u2_p6_0[] = {
  143459. 11, 9, 7, 5, 3, 1, 0, 2,
  143460. 4, 6, 8, 10, 12,
  143461. };
  143462. static encode_aux_threshmatch _vq_auxt__16u2_p6_0 = {
  143463. _vq_quantthresh__16u2_p6_0,
  143464. _vq_quantmap__16u2_p6_0,
  143465. 13,
  143466. 13
  143467. };
  143468. static static_codebook _16u2_p6_0 = {
  143469. 2, 169,
  143470. _vq_lengthlist__16u2_p6_0,
  143471. 1, -526516224, 1616117760, 4, 0,
  143472. _vq_quantlist__16u2_p6_0,
  143473. NULL,
  143474. &_vq_auxt__16u2_p6_0,
  143475. NULL,
  143476. 0
  143477. };
  143478. static long _vq_quantlist__16u2_p6_1[] = {
  143479. 2,
  143480. 1,
  143481. 3,
  143482. 0,
  143483. 4,
  143484. };
  143485. static long _vq_lengthlist__16u2_p6_1[] = {
  143486. 2, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  143487. 5, 5, 6, 6, 5, 5, 5, 6, 6,
  143488. };
  143489. static float _vq_quantthresh__16u2_p6_1[] = {
  143490. -1.5, -0.5, 0.5, 1.5,
  143491. };
  143492. static long _vq_quantmap__16u2_p6_1[] = {
  143493. 3, 1, 0, 2, 4,
  143494. };
  143495. static encode_aux_threshmatch _vq_auxt__16u2_p6_1 = {
  143496. _vq_quantthresh__16u2_p6_1,
  143497. _vq_quantmap__16u2_p6_1,
  143498. 5,
  143499. 5
  143500. };
  143501. static static_codebook _16u2_p6_1 = {
  143502. 2, 25,
  143503. _vq_lengthlist__16u2_p6_1,
  143504. 1, -533725184, 1611661312, 3, 0,
  143505. _vq_quantlist__16u2_p6_1,
  143506. NULL,
  143507. &_vq_auxt__16u2_p6_1,
  143508. NULL,
  143509. 0
  143510. };
  143511. static long _vq_quantlist__16u2_p7_0[] = {
  143512. 6,
  143513. 5,
  143514. 7,
  143515. 4,
  143516. 8,
  143517. 3,
  143518. 9,
  143519. 2,
  143520. 10,
  143521. 1,
  143522. 11,
  143523. 0,
  143524. 12,
  143525. };
  143526. static long _vq_lengthlist__16u2_p7_0[] = {
  143527. 1, 4, 4, 7, 7, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 6,
  143528. 9, 9, 9, 9, 9, 9,10,10,11,11, 4, 6, 6, 8, 9, 9,
  143529. 9, 9, 9,10,11,12,11, 7, 8, 9,10,10,10,10,11,10,
  143530. 11,12,12,13, 7, 9, 9,10,10,10,10,10,10,11,12,13,
  143531. 13, 7, 9, 8,10,10,11,11,11,12,12,13,13,14, 7, 9,
  143532. 9,10,10,11,11,11,12,13,13,13,13, 8, 9, 9,10,11,
  143533. 11,12,12,12,13,13,13,13, 8, 9, 9,10,11,11,11,12,
  143534. 12,13,13,14,14, 9,10,10,12,11,12,13,13,13,14,13,
  143535. 13,13, 9,10,10,11,11,12,12,13,14,13,13,14,13,10,
  143536. 11,11,12,13,14,14,14,15,14,14,14,14,10,11,11,12,
  143537. 12,13,13,13,14,14,14,15,14,
  143538. };
  143539. static float _vq_quantthresh__16u2_p7_0[] = {
  143540. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  143541. 27.5, 38.5, 49.5, 60.5,
  143542. };
  143543. static long _vq_quantmap__16u2_p7_0[] = {
  143544. 11, 9, 7, 5, 3, 1, 0, 2,
  143545. 4, 6, 8, 10, 12,
  143546. };
  143547. static encode_aux_threshmatch _vq_auxt__16u2_p7_0 = {
  143548. _vq_quantthresh__16u2_p7_0,
  143549. _vq_quantmap__16u2_p7_0,
  143550. 13,
  143551. 13
  143552. };
  143553. static static_codebook _16u2_p7_0 = {
  143554. 2, 169,
  143555. _vq_lengthlist__16u2_p7_0,
  143556. 1, -523206656, 1618345984, 4, 0,
  143557. _vq_quantlist__16u2_p7_0,
  143558. NULL,
  143559. &_vq_auxt__16u2_p7_0,
  143560. NULL,
  143561. 0
  143562. };
  143563. static long _vq_quantlist__16u2_p7_1[] = {
  143564. 5,
  143565. 4,
  143566. 6,
  143567. 3,
  143568. 7,
  143569. 2,
  143570. 8,
  143571. 1,
  143572. 9,
  143573. 0,
  143574. 10,
  143575. };
  143576. static long _vq_lengthlist__16u2_p7_1[] = {
  143577. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  143578. 7, 7, 7, 7, 8, 8, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8,
  143579. 8, 6, 6, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 7, 7, 7,
  143580. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  143581. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  143582. 8, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8,
  143583. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  143584. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143585. };
  143586. static float _vq_quantthresh__16u2_p7_1[] = {
  143587. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  143588. 3.5, 4.5,
  143589. };
  143590. static long _vq_quantmap__16u2_p7_1[] = {
  143591. 9, 7, 5, 3, 1, 0, 2, 4,
  143592. 6, 8, 10,
  143593. };
  143594. static encode_aux_threshmatch _vq_auxt__16u2_p7_1 = {
  143595. _vq_quantthresh__16u2_p7_1,
  143596. _vq_quantmap__16u2_p7_1,
  143597. 11,
  143598. 11
  143599. };
  143600. static static_codebook _16u2_p7_1 = {
  143601. 2, 121,
  143602. _vq_lengthlist__16u2_p7_1,
  143603. 1, -531365888, 1611661312, 4, 0,
  143604. _vq_quantlist__16u2_p7_1,
  143605. NULL,
  143606. &_vq_auxt__16u2_p7_1,
  143607. NULL,
  143608. 0
  143609. };
  143610. static long _vq_quantlist__16u2_p8_0[] = {
  143611. 7,
  143612. 6,
  143613. 8,
  143614. 5,
  143615. 9,
  143616. 4,
  143617. 10,
  143618. 3,
  143619. 11,
  143620. 2,
  143621. 12,
  143622. 1,
  143623. 13,
  143624. 0,
  143625. 14,
  143626. };
  143627. static long _vq_lengthlist__16u2_p8_0[] = {
  143628. 1, 5, 5, 7, 7, 8, 8, 7, 7, 8, 8,10, 9,11,11, 4,
  143629. 6, 6, 8, 8,10, 9, 9, 8, 9, 9,10,10,12,14, 4, 6,
  143630. 7, 8, 9, 9,10, 9, 8, 9, 9,10,12,12,11, 7, 8, 8,
  143631. 10,10,10,10, 9, 9,10,10,11,13,13,12, 7, 8, 8, 9,
  143632. 11,11,10, 9, 9,11,10,12,11,11,14, 8, 9, 9,11,10,
  143633. 11,11,10,10,11,11,13,12,14,12, 8, 9, 9,11,12,11,
  143634. 11,10,10,12,11,12,12,12,14, 7, 8, 8, 9, 9,10,10,
  143635. 10,11,12,11,13,13,14,12, 7, 8, 9, 9, 9,10,10,11,
  143636. 11,11,12,12,14,14,14, 8,10, 9,10,11,11,11,11,14,
  143637. 12,12,13,14,14,13, 9, 9, 9,10,11,11,11,12,12,12,
  143638. 14,12,14,13,14,10,10,10,12,11,12,11,14,13,14,13,
  143639. 14,14,13,14, 9,10,10,11,12,11,13,12,13,13,14,14,
  143640. 14,13,14,10,13,13,12,12,11,12,14,13,14,13,14,12,
  143641. 14,13,10,11,11,12,11,12,12,14,14,14,13,14,14,14,
  143642. 14,
  143643. };
  143644. static float _vq_quantthresh__16u2_p8_0[] = {
  143645. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  143646. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  143647. };
  143648. static long _vq_quantmap__16u2_p8_0[] = {
  143649. 13, 11, 9, 7, 5, 3, 1, 0,
  143650. 2, 4, 6, 8, 10, 12, 14,
  143651. };
  143652. static encode_aux_threshmatch _vq_auxt__16u2_p8_0 = {
  143653. _vq_quantthresh__16u2_p8_0,
  143654. _vq_quantmap__16u2_p8_0,
  143655. 15,
  143656. 15
  143657. };
  143658. static static_codebook _16u2_p8_0 = {
  143659. 2, 225,
  143660. _vq_lengthlist__16u2_p8_0,
  143661. 1, -520986624, 1620377600, 4, 0,
  143662. _vq_quantlist__16u2_p8_0,
  143663. NULL,
  143664. &_vq_auxt__16u2_p8_0,
  143665. NULL,
  143666. 0
  143667. };
  143668. static long _vq_quantlist__16u2_p8_1[] = {
  143669. 10,
  143670. 9,
  143671. 11,
  143672. 8,
  143673. 12,
  143674. 7,
  143675. 13,
  143676. 6,
  143677. 14,
  143678. 5,
  143679. 15,
  143680. 4,
  143681. 16,
  143682. 3,
  143683. 17,
  143684. 2,
  143685. 18,
  143686. 1,
  143687. 19,
  143688. 0,
  143689. 20,
  143690. };
  143691. static long _vq_lengthlist__16u2_p8_1[] = {
  143692. 2, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,10, 9, 9,
  143693. 9,10,10,10,10, 5, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,
  143694. 10, 9,10,10,10,10,10,10,11,10, 5, 6, 6, 7, 7, 8,
  143695. 8, 8, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 7,
  143696. 7, 7, 8, 8, 9, 8, 9, 9,10, 9,10,10,10,10,10,10,
  143697. 11,10,11,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,10, 9,10,
  143698. 10,10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,
  143699. 10, 9,10,10,10,10,10,10,10,11,10,10,11,10, 8, 8,
  143700. 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,
  143701. 11,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  143702. 11,10,11,10,11,10,11,10, 8, 9, 9, 9, 9, 9,10,10,
  143703. 10,10,10,10,10,10,10,10,11,11,10,10,10, 9,10, 9,
  143704. 9,10,10,10,11,10,10,10,10,10,10,10,10,11,11,11,
  143705. 11,11, 9, 9, 9,10, 9,10,10,10,10,10,10,11,10,11,
  143706. 10,11,11,11,11,10,10, 9,10, 9,10,10,10,10,11,10,
  143707. 10,10,10,10,11,10,11,10,11,10,10,11, 9,10,10,10,
  143708. 10,10,10,10,10,10,11,10,10,11,11,10,11,11,11,11,
  143709. 11, 9, 9,10,10,10,10,10,11,10,10,11,10,10,11,10,
  143710. 10,11,11,11,11,11, 9,10,10,10,10,10,10,10,11,10,
  143711. 11,10,11,10,11,11,11,11,11,10,11,10,10,10,10,10,
  143712. 10,10,10,10,11,11,11,11,11,11,11,11,11,10,11,11,
  143713. 10,10,10,10,10,11,10,10,10,11,10,11,11,11,11,10,
  143714. 12,11,11,11,10,10,10,10,10,10,11,10,10,10,11,11,
  143715. 12,11,11,11,11,11,11,11,11,11,10,10,10,11,10,11,
  143716. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  143717. 10,10,11,10,11,10,10,11,11,11,11,11,11,11,11,11,
  143718. 11,11,11,10,10,10,10,10,10,10,11,11,10,11,11,10,
  143719. 11,11,10,11,11,11,10,11,11,
  143720. };
  143721. static float _vq_quantthresh__16u2_p8_1[] = {
  143722. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  143723. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  143724. 6.5, 7.5, 8.5, 9.5,
  143725. };
  143726. static long _vq_quantmap__16u2_p8_1[] = {
  143727. 19, 17, 15, 13, 11, 9, 7, 5,
  143728. 3, 1, 0, 2, 4, 6, 8, 10,
  143729. 12, 14, 16, 18, 20,
  143730. };
  143731. static encode_aux_threshmatch _vq_auxt__16u2_p8_1 = {
  143732. _vq_quantthresh__16u2_p8_1,
  143733. _vq_quantmap__16u2_p8_1,
  143734. 21,
  143735. 21
  143736. };
  143737. static static_codebook _16u2_p8_1 = {
  143738. 2, 441,
  143739. _vq_lengthlist__16u2_p8_1,
  143740. 1, -529268736, 1611661312, 5, 0,
  143741. _vq_quantlist__16u2_p8_1,
  143742. NULL,
  143743. &_vq_auxt__16u2_p8_1,
  143744. NULL,
  143745. 0
  143746. };
  143747. static long _vq_quantlist__16u2_p9_0[] = {
  143748. 5586,
  143749. 4655,
  143750. 6517,
  143751. 3724,
  143752. 7448,
  143753. 2793,
  143754. 8379,
  143755. 1862,
  143756. 9310,
  143757. 931,
  143758. 10241,
  143759. 0,
  143760. 11172,
  143761. 5521,
  143762. 5651,
  143763. };
  143764. static long _vq_lengthlist__16u2_p9_0[] = {
  143765. 1,10,10,10,10,10,10,10,10,10,10,10,10, 5, 4,10,
  143766. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143767. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143768. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143769. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143770. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143771. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143772. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143773. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143774. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143775. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143776. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143777. 10,10,10, 4,10,10,10,10,10,10,10,10,10,10,10,10,
  143778. 6, 6, 5,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 5,
  143779. 5,
  143780. };
  143781. static float _vq_quantthresh__16u2_p9_0[] = {
  143782. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -498, -32.5, 32.5,
  143783. 498, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5,
  143784. };
  143785. static long _vq_quantmap__16u2_p9_0[] = {
  143786. 11, 9, 7, 5, 3, 1, 13, 0,
  143787. 14, 2, 4, 6, 8, 10, 12,
  143788. };
  143789. static encode_aux_threshmatch _vq_auxt__16u2_p9_0 = {
  143790. _vq_quantthresh__16u2_p9_0,
  143791. _vq_quantmap__16u2_p9_0,
  143792. 15,
  143793. 15
  143794. };
  143795. static static_codebook _16u2_p9_0 = {
  143796. 2, 225,
  143797. _vq_lengthlist__16u2_p9_0,
  143798. 1, -510275072, 1611661312, 14, 0,
  143799. _vq_quantlist__16u2_p9_0,
  143800. NULL,
  143801. &_vq_auxt__16u2_p9_0,
  143802. NULL,
  143803. 0
  143804. };
  143805. static long _vq_quantlist__16u2_p9_1[] = {
  143806. 392,
  143807. 343,
  143808. 441,
  143809. 294,
  143810. 490,
  143811. 245,
  143812. 539,
  143813. 196,
  143814. 588,
  143815. 147,
  143816. 637,
  143817. 98,
  143818. 686,
  143819. 49,
  143820. 735,
  143821. 0,
  143822. 784,
  143823. 388,
  143824. 396,
  143825. };
  143826. static long _vq_lengthlist__16u2_p9_1[] = {
  143827. 1,12,10,12,10,12,10,12,11,12,12,12,12,12,12,12,
  143828. 12, 5, 5, 9,10,12,11,11,12,12,12,12,12,12,12,12,
  143829. 12,12,12,12,10, 9, 9,11, 9,11,11,12,11,12,12,12,
  143830. 12,12,12,12,12,12,12, 8, 8,10,11, 9,12,11,12,12,
  143831. 12,12,12,12,12,12,12,12,12,12, 9, 8,10,11,12,11,
  143832. 12,11,12,12,12,12,12,12,12,12,12,12,12, 8, 9,11,
  143833. 11,10,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  143834. 9,10,11,12,11,12,11,12,12,12,12,12,12,12,12,12,
  143835. 12,12,12, 9, 9,11,12,12,12,12,12,12,12,12,12,12,
  143836. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  143837. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  143838. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  143839. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  143840. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  143841. 12,12,12,12,11,11,11,11,11,11,11,11,11,11,11,11,
  143842. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143843. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143844. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143845. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143846. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143847. 11,11,11, 5, 8, 9, 9, 8,11, 9,11,11,11,11,11,11,
  143848. 11,11,11,11, 5, 5, 4, 8, 8, 8, 8,10, 9,10,10,11,
  143849. 11,11,11,11,11,11,11, 5, 4,
  143850. };
  143851. static float _vq_quantthresh__16u2_p9_1[] = {
  143852. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -26.5,
  143853. -2, 2, 26.5, 73.5, 122.5, 171.5, 220.5, 269.5,
  143854. 318.5, 367.5,
  143855. };
  143856. static long _vq_quantmap__16u2_p9_1[] = {
  143857. 15, 13, 11, 9, 7, 5, 3, 1,
  143858. 17, 0, 18, 2, 4, 6, 8, 10,
  143859. 12, 14, 16,
  143860. };
  143861. static encode_aux_threshmatch _vq_auxt__16u2_p9_1 = {
  143862. _vq_quantthresh__16u2_p9_1,
  143863. _vq_quantmap__16u2_p9_1,
  143864. 19,
  143865. 19
  143866. };
  143867. static static_codebook _16u2_p9_1 = {
  143868. 2, 361,
  143869. _vq_lengthlist__16u2_p9_1,
  143870. 1, -518488064, 1611661312, 10, 0,
  143871. _vq_quantlist__16u2_p9_1,
  143872. NULL,
  143873. &_vq_auxt__16u2_p9_1,
  143874. NULL,
  143875. 0
  143876. };
  143877. static long _vq_quantlist__16u2_p9_2[] = {
  143878. 24,
  143879. 23,
  143880. 25,
  143881. 22,
  143882. 26,
  143883. 21,
  143884. 27,
  143885. 20,
  143886. 28,
  143887. 19,
  143888. 29,
  143889. 18,
  143890. 30,
  143891. 17,
  143892. 31,
  143893. 16,
  143894. 32,
  143895. 15,
  143896. 33,
  143897. 14,
  143898. 34,
  143899. 13,
  143900. 35,
  143901. 12,
  143902. 36,
  143903. 11,
  143904. 37,
  143905. 10,
  143906. 38,
  143907. 9,
  143908. 39,
  143909. 8,
  143910. 40,
  143911. 7,
  143912. 41,
  143913. 6,
  143914. 42,
  143915. 5,
  143916. 43,
  143917. 4,
  143918. 44,
  143919. 3,
  143920. 45,
  143921. 2,
  143922. 46,
  143923. 1,
  143924. 47,
  143925. 0,
  143926. 48,
  143927. };
  143928. static long _vq_lengthlist__16u2_p9_2[] = {
  143929. 1, 3, 3, 4, 7, 7, 7, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  143930. 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 9, 9, 8, 9, 9,
  143931. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,12,12,10,
  143932. 11,
  143933. };
  143934. static float _vq_quantthresh__16u2_p9_2[] = {
  143935. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  143936. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  143937. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  143938. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  143939. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  143940. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  143941. };
  143942. static long _vq_quantmap__16u2_p9_2[] = {
  143943. 47, 45, 43, 41, 39, 37, 35, 33,
  143944. 31, 29, 27, 25, 23, 21, 19, 17,
  143945. 15, 13, 11, 9, 7, 5, 3, 1,
  143946. 0, 2, 4, 6, 8, 10, 12, 14,
  143947. 16, 18, 20, 22, 24, 26, 28, 30,
  143948. 32, 34, 36, 38, 40, 42, 44, 46,
  143949. 48,
  143950. };
  143951. static encode_aux_threshmatch _vq_auxt__16u2_p9_2 = {
  143952. _vq_quantthresh__16u2_p9_2,
  143953. _vq_quantmap__16u2_p9_2,
  143954. 49,
  143955. 49
  143956. };
  143957. static static_codebook _16u2_p9_2 = {
  143958. 1, 49,
  143959. _vq_lengthlist__16u2_p9_2,
  143960. 1, -526909440, 1611661312, 6, 0,
  143961. _vq_quantlist__16u2_p9_2,
  143962. NULL,
  143963. &_vq_auxt__16u2_p9_2,
  143964. NULL,
  143965. 0
  143966. };
  143967. static long _vq_quantlist__8u0__p1_0[] = {
  143968. 1,
  143969. 0,
  143970. 2,
  143971. };
  143972. static long _vq_lengthlist__8u0__p1_0[] = {
  143973. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  143974. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 4, 9, 8, 8,11,
  143975. 11, 8,11,11, 7,11,11,10,11,13,10,13,13, 7,11,11,
  143976. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 8,11,11, 7,
  143977. 11,11, 9,13,13,10,12,13, 7,11,11,10,13,13,10,13,
  143978. 11,
  143979. };
  143980. static float _vq_quantthresh__8u0__p1_0[] = {
  143981. -0.5, 0.5,
  143982. };
  143983. static long _vq_quantmap__8u0__p1_0[] = {
  143984. 1, 0, 2,
  143985. };
  143986. static encode_aux_threshmatch _vq_auxt__8u0__p1_0 = {
  143987. _vq_quantthresh__8u0__p1_0,
  143988. _vq_quantmap__8u0__p1_0,
  143989. 3,
  143990. 3
  143991. };
  143992. static static_codebook _8u0__p1_0 = {
  143993. 4, 81,
  143994. _vq_lengthlist__8u0__p1_0,
  143995. 1, -535822336, 1611661312, 2, 0,
  143996. _vq_quantlist__8u0__p1_0,
  143997. NULL,
  143998. &_vq_auxt__8u0__p1_0,
  143999. NULL,
  144000. 0
  144001. };
  144002. static long _vq_quantlist__8u0__p2_0[] = {
  144003. 1,
  144004. 0,
  144005. 2,
  144006. };
  144007. static long _vq_lengthlist__8u0__p2_0[] = {
  144008. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 6, 7, 8, 6,
  144009. 7, 8, 5, 7, 7, 6, 8, 8, 7, 9, 7, 5, 7, 7, 7, 9,
  144010. 9, 7, 8, 8, 6, 9, 8, 7, 7,10, 8,10,10, 6, 8, 8,
  144011. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  144012. 8, 8, 8,10,10, 8, 8,10, 6, 8, 9, 8,10,10, 7,10,
  144013. 8,
  144014. };
  144015. static float _vq_quantthresh__8u0__p2_0[] = {
  144016. -0.5, 0.5,
  144017. };
  144018. static long _vq_quantmap__8u0__p2_0[] = {
  144019. 1, 0, 2,
  144020. };
  144021. static encode_aux_threshmatch _vq_auxt__8u0__p2_0 = {
  144022. _vq_quantthresh__8u0__p2_0,
  144023. _vq_quantmap__8u0__p2_0,
  144024. 3,
  144025. 3
  144026. };
  144027. static static_codebook _8u0__p2_0 = {
  144028. 4, 81,
  144029. _vq_lengthlist__8u0__p2_0,
  144030. 1, -535822336, 1611661312, 2, 0,
  144031. _vq_quantlist__8u0__p2_0,
  144032. NULL,
  144033. &_vq_auxt__8u0__p2_0,
  144034. NULL,
  144035. 0
  144036. };
  144037. static long _vq_quantlist__8u0__p3_0[] = {
  144038. 2,
  144039. 1,
  144040. 3,
  144041. 0,
  144042. 4,
  144043. };
  144044. static long _vq_lengthlist__8u0__p3_0[] = {
  144045. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  144046. 10, 9,11,11, 8, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  144047. 10,11,11, 8,10,10,11,11,10,11,11,12,12,10,11,11,
  144048. 12,13, 6, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  144049. 11, 9,10,11,12,12,10,11,11,12,12, 8,11,11,14,13,
  144050. 10,12,11,15,13,10,12,11,14,14,12,13,12,16,14,12,
  144051. 14,12,16,15, 8,11,11,13,14,10,11,12,13,15,10,11,
  144052. 12,13,15,11,12,13,14,15,12,12,14,14,16, 5, 8, 8,
  144053. 11,11, 9,11,11,12,12, 8,10,11,12,12,11,12,12,15,
  144054. 14,11,12,12,14,14, 7,11,10,13,12,10,11,12,13,14,
  144055. 10,12,12,14,13,12,13,13,14,15,12,13,13,15,15, 7,
  144056. 10,11,12,13,10,12,11,14,13,10,12,13,13,15,12,13,
  144057. 12,14,14,11,13,13,15,16, 9,12,12,15,14,11,13,13,
  144058. 15,16,11,13,13,16,16,13,14,15,15,15,12,14,15,17,
  144059. 16, 9,12,12,14,15,11,13,13,15,16,11,13,13,16,18,
  144060. 13,14,14,17,16,13,15,15,17,18, 5, 8, 9,11,11, 8,
  144061. 11,11,12,12, 8,10,11,12,12,11,12,12,14,14,11,12,
  144062. 12,14,15, 7,11,10,12,13,10,12,12,14,13,10,11,12,
  144063. 13,14,11,13,13,15,14,12,13,13,14,15, 7,10,11,13,
  144064. 13,10,12,12,13,14,10,12,12,13,13,11,13,13,16,16,
  144065. 12,13,13,15,14, 9,12,12,16,15,10,13,13,15,15,11,
  144066. 13,13,17,15,12,15,15,18,17,13,14,14,15,16, 9,12,
  144067. 12,15,15,11,13,13,15,16,11,13,13,15,15,12,15,15,
  144068. 16,16,13,15,14,17,15, 7,11,11,15,15,10,13,13,16,
  144069. 15,10,13,13,15,16,14,15,15,17,19,13,15,14,15,18,
  144070. 9,12,12,16,16,11,13,14,17,16,11,13,13,17,16,15,
  144071. 15,16,17,19,13,15,16, 0,18, 9,12,12,16,15,11,14,
  144072. 13,17,17,11,13,14,16,16,15,16,16,19,18,13,15,15,
  144073. 17,19,11,14,14,19,16,12,14,15, 0,18,12,16,15,18,
  144074. 17,15,15,18,16,19,14,15,17,19,19,11,14,14,18,19,
  144075. 13,15,14,19,19,12,16,15,18,17,15,17,15, 0,16,14,
  144076. 17,16,19, 0, 7,11,11,14,14,10,12,12,15,15,10,13,
  144077. 13,16,15,13,15,15,17, 0,14,15,15,16,19, 9,12,12,
  144078. 16,16,11,14,14,16,16,11,13,13,16,16,14,17,16,19,
  144079. 0,14,18,17,17,19, 9,12,12,15,16,11,13,13,15,17,
  144080. 12,14,13,19,16,13,15,15,17,19,15,17,16,17,19,11,
  144081. 14,14,19,16,12,15,15,19,17,13,14,15,17,19,14,16,
  144082. 17,19,19,16,15,16,17,19,11,15,14,16,16,12,15,15,
  144083. 19, 0,12,14,15,19,19,14,16,16, 0,18,15,19,14,18,
  144084. 16,
  144085. };
  144086. static float _vq_quantthresh__8u0__p3_0[] = {
  144087. -1.5, -0.5, 0.5, 1.5,
  144088. };
  144089. static long _vq_quantmap__8u0__p3_0[] = {
  144090. 3, 1, 0, 2, 4,
  144091. };
  144092. static encode_aux_threshmatch _vq_auxt__8u0__p3_0 = {
  144093. _vq_quantthresh__8u0__p3_0,
  144094. _vq_quantmap__8u0__p3_0,
  144095. 5,
  144096. 5
  144097. };
  144098. static static_codebook _8u0__p3_0 = {
  144099. 4, 625,
  144100. _vq_lengthlist__8u0__p3_0,
  144101. 1, -533725184, 1611661312, 3, 0,
  144102. _vq_quantlist__8u0__p3_0,
  144103. NULL,
  144104. &_vq_auxt__8u0__p3_0,
  144105. NULL,
  144106. 0
  144107. };
  144108. static long _vq_quantlist__8u0__p4_0[] = {
  144109. 2,
  144110. 1,
  144111. 3,
  144112. 0,
  144113. 4,
  144114. };
  144115. static long _vq_lengthlist__8u0__p4_0[] = {
  144116. 3, 5, 5, 8, 8, 5, 6, 7, 9, 9, 6, 7, 6, 9, 9, 9,
  144117. 9, 9,10,11, 9, 9, 9,11,10, 6, 7, 7,10,10, 7, 7,
  144118. 8,10,10, 7, 8, 8,10,10,10,10,10,10,11, 9,10,10,
  144119. 11,12, 6, 7, 7,10,10, 7, 8, 8,10,10, 7, 8, 7,10,
  144120. 10, 9,10,10,12,11,10,10,10,11,10, 9,10,10,12,11,
  144121. 10,10,10,13,11, 9,10,10,12,12,11,11,12,12,13,11,
  144122. 11,11,12,13, 9,10,10,12,12,10,10,11,12,12,10,10,
  144123. 11,12,12,11,11,11,13,13,11,12,12,13,13, 5, 7, 7,
  144124. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,11,12,
  144125. 12,10,11,10,12,12, 7, 8, 8,11,11, 7, 8, 9,10,11,
  144126. 8, 9, 9,11,11,11,10,11,10,12,10,11,11,12,13, 7,
  144127. 8, 8,10,11, 8, 9, 8,12,10, 8, 9, 9,11,12,10,11,
  144128. 10,13,11,10,11,11,13,12, 9,11,10,13,12,10,10,11,
  144129. 12,12,10,11,11,13,13,12,10,13,11,14,11,12,12,15,
  144130. 13, 9,11,11,13,13,10,11,11,13,12,10,11,11,12,14,
  144131. 12,13,11,14,12,12,12,12,14,14, 5, 7, 7,10,10, 7,
  144132. 8, 8,10,10, 7, 8, 8,11,10,10,11,11,12,12,10,11,
  144133. 10,12,12, 7, 8, 8,10,11, 8, 9, 9,12,11, 8, 8, 9,
  144134. 10,11,10,11,11,12,13,11,10,11,11,13, 6, 8, 8,10,
  144135. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,11,11,12,12,
  144136. 10,11,10,13,10, 9,11,10,13,12,10,12,11,13,13,10,
  144137. 10,11,12,13,11,12,13,15,14,11,11,13,12,13, 9,10,
  144138. 11,12,13,10,11,11,12,13,10,11,10,13,12,12,13,13,
  144139. 13,14,12,12,11,14,11, 8,10,10,12,13,10,11,11,13,
  144140. 13,10,11,10,13,13,12,13,14,15,14,12,12,12,14,13,
  144141. 9,10,10,13,12,10,10,12,13,13,10,11,11,15,12,12,
  144142. 12,13,15,14,12,13,13,15,13, 9,10,11,12,13,10,12,
  144143. 10,13,12,10,11,11,12,13,12,14,12,15,13,12,12,12,
  144144. 15,14,11,12,11,14,13,11,11,12,14,14,12,13,13,14,
  144145. 13,13,11,15,11,15,14,14,14,16,15,11,12,12,13,14,
  144146. 11,13,11,14,14,12,12,13,14,15,12,14,12,15,12,13,
  144147. 15,14,16,15, 8,10,10,12,12,10,10,10,12,13,10,11,
  144148. 11,13,13,12,12,12,13,14,13,13,13,15,15, 9,10,10,
  144149. 12,12,10,11,11,13,12,10,10,11,13,13,12,12,12,14,
  144150. 14,12,12,13,15,14, 9,10,10,13,12,10,10,12,12,13,
  144151. 10,11,10,13,13,12,13,13,14,14,12,13,12,14,13,11,
  144152. 12,12,14,13,12,13,12,14,14,10,12,12,14,14,14,14,
  144153. 14,16,14,13,12,14,12,15,10,12,12,14,15,12,13,13,
  144154. 14,16,11,12,11,15,14,13,14,14,14,15,13,14,11,14,
  144155. 12,
  144156. };
  144157. static float _vq_quantthresh__8u0__p4_0[] = {
  144158. -1.5, -0.5, 0.5, 1.5,
  144159. };
  144160. static long _vq_quantmap__8u0__p4_0[] = {
  144161. 3, 1, 0, 2, 4,
  144162. };
  144163. static encode_aux_threshmatch _vq_auxt__8u0__p4_0 = {
  144164. _vq_quantthresh__8u0__p4_0,
  144165. _vq_quantmap__8u0__p4_0,
  144166. 5,
  144167. 5
  144168. };
  144169. static static_codebook _8u0__p4_0 = {
  144170. 4, 625,
  144171. _vq_lengthlist__8u0__p4_0,
  144172. 1, -533725184, 1611661312, 3, 0,
  144173. _vq_quantlist__8u0__p4_0,
  144174. NULL,
  144175. &_vq_auxt__8u0__p4_0,
  144176. NULL,
  144177. 0
  144178. };
  144179. static long _vq_quantlist__8u0__p5_0[] = {
  144180. 4,
  144181. 3,
  144182. 5,
  144183. 2,
  144184. 6,
  144185. 1,
  144186. 7,
  144187. 0,
  144188. 8,
  144189. };
  144190. static long _vq_lengthlist__8u0__p5_0[] = {
  144191. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 7, 8, 8,
  144192. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 6, 8, 8, 9, 9,
  144193. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  144194. 9, 9,10,10,12,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  144195. 10,10,11,11,11,12,12,12, 9,10,10,11,11,12,12,12,
  144196. 12,
  144197. };
  144198. static float _vq_quantthresh__8u0__p5_0[] = {
  144199. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144200. };
  144201. static long _vq_quantmap__8u0__p5_0[] = {
  144202. 7, 5, 3, 1, 0, 2, 4, 6,
  144203. 8,
  144204. };
  144205. static encode_aux_threshmatch _vq_auxt__8u0__p5_0 = {
  144206. _vq_quantthresh__8u0__p5_0,
  144207. _vq_quantmap__8u0__p5_0,
  144208. 9,
  144209. 9
  144210. };
  144211. static static_codebook _8u0__p5_0 = {
  144212. 2, 81,
  144213. _vq_lengthlist__8u0__p5_0,
  144214. 1, -531628032, 1611661312, 4, 0,
  144215. _vq_quantlist__8u0__p5_0,
  144216. NULL,
  144217. &_vq_auxt__8u0__p5_0,
  144218. NULL,
  144219. 0
  144220. };
  144221. static long _vq_quantlist__8u0__p6_0[] = {
  144222. 6,
  144223. 5,
  144224. 7,
  144225. 4,
  144226. 8,
  144227. 3,
  144228. 9,
  144229. 2,
  144230. 10,
  144231. 1,
  144232. 11,
  144233. 0,
  144234. 12,
  144235. };
  144236. static long _vq_lengthlist__8u0__p6_0[] = {
  144237. 1, 4, 4, 7, 7, 9, 9,11,11,12,12,16,16, 3, 6, 6,
  144238. 9, 9,11,11,12,12,13,14,18,16, 3, 6, 7, 9, 9,11,
  144239. 11,13,12,14,14,17,16, 7, 9, 9,11,11,12,12,14,14,
  144240. 14,14,17,16, 7, 9, 9,11,11,13,12,13,13,14,14,17,
  144241. 0, 9,11,11,12,13,14,14,14,13,15,14,17,17, 9,11,
  144242. 11,12,12,14,14,13,14,14,15, 0, 0,11,12,12,15,14,
  144243. 15,14,15,14,15,16,17, 0,11,12,13,13,13,14,14,15,
  144244. 14,15,15, 0, 0,12,14,14,15,15,14,16,15,15,17,16,
  144245. 0,18,13,14,14,15,14,15,14,15,16,17,16, 0, 0,17,
  144246. 17,18, 0,16,18,16, 0, 0, 0,17, 0, 0,16, 0, 0,16,
  144247. 16, 0,15, 0,17, 0, 0, 0, 0,
  144248. };
  144249. static float _vq_quantthresh__8u0__p6_0[] = {
  144250. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  144251. 12.5, 17.5, 22.5, 27.5,
  144252. };
  144253. static long _vq_quantmap__8u0__p6_0[] = {
  144254. 11, 9, 7, 5, 3, 1, 0, 2,
  144255. 4, 6, 8, 10, 12,
  144256. };
  144257. static encode_aux_threshmatch _vq_auxt__8u0__p6_0 = {
  144258. _vq_quantthresh__8u0__p6_0,
  144259. _vq_quantmap__8u0__p6_0,
  144260. 13,
  144261. 13
  144262. };
  144263. static static_codebook _8u0__p6_0 = {
  144264. 2, 169,
  144265. _vq_lengthlist__8u0__p6_0,
  144266. 1, -526516224, 1616117760, 4, 0,
  144267. _vq_quantlist__8u0__p6_0,
  144268. NULL,
  144269. &_vq_auxt__8u0__p6_0,
  144270. NULL,
  144271. 0
  144272. };
  144273. static long _vq_quantlist__8u0__p6_1[] = {
  144274. 2,
  144275. 1,
  144276. 3,
  144277. 0,
  144278. 4,
  144279. };
  144280. static long _vq_lengthlist__8u0__p6_1[] = {
  144281. 1, 4, 4, 6, 6, 4, 6, 5, 7, 7, 4, 5, 6, 7, 7, 6,
  144282. 7, 7, 7, 7, 6, 7, 7, 7, 7,
  144283. };
  144284. static float _vq_quantthresh__8u0__p6_1[] = {
  144285. -1.5, -0.5, 0.5, 1.5,
  144286. };
  144287. static long _vq_quantmap__8u0__p6_1[] = {
  144288. 3, 1, 0, 2, 4,
  144289. };
  144290. static encode_aux_threshmatch _vq_auxt__8u0__p6_1 = {
  144291. _vq_quantthresh__8u0__p6_1,
  144292. _vq_quantmap__8u0__p6_1,
  144293. 5,
  144294. 5
  144295. };
  144296. static static_codebook _8u0__p6_1 = {
  144297. 2, 25,
  144298. _vq_lengthlist__8u0__p6_1,
  144299. 1, -533725184, 1611661312, 3, 0,
  144300. _vq_quantlist__8u0__p6_1,
  144301. NULL,
  144302. &_vq_auxt__8u0__p6_1,
  144303. NULL,
  144304. 0
  144305. };
  144306. static long _vq_quantlist__8u0__p7_0[] = {
  144307. 1,
  144308. 0,
  144309. 2,
  144310. };
  144311. static long _vq_lengthlist__8u0__p7_0[] = {
  144312. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144313. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144314. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  144315. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  144316. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  144317. 7,
  144318. };
  144319. static float _vq_quantthresh__8u0__p7_0[] = {
  144320. -157.5, 157.5,
  144321. };
  144322. static long _vq_quantmap__8u0__p7_0[] = {
  144323. 1, 0, 2,
  144324. };
  144325. static encode_aux_threshmatch _vq_auxt__8u0__p7_0 = {
  144326. _vq_quantthresh__8u0__p7_0,
  144327. _vq_quantmap__8u0__p7_0,
  144328. 3,
  144329. 3
  144330. };
  144331. static static_codebook _8u0__p7_0 = {
  144332. 4, 81,
  144333. _vq_lengthlist__8u0__p7_0,
  144334. 1, -518803456, 1628680192, 2, 0,
  144335. _vq_quantlist__8u0__p7_0,
  144336. NULL,
  144337. &_vq_auxt__8u0__p7_0,
  144338. NULL,
  144339. 0
  144340. };
  144341. static long _vq_quantlist__8u0__p7_1[] = {
  144342. 7,
  144343. 6,
  144344. 8,
  144345. 5,
  144346. 9,
  144347. 4,
  144348. 10,
  144349. 3,
  144350. 11,
  144351. 2,
  144352. 12,
  144353. 1,
  144354. 13,
  144355. 0,
  144356. 14,
  144357. };
  144358. static long _vq_lengthlist__8u0__p7_1[] = {
  144359. 1, 5, 5, 5, 5,10,10,11,11,11,11,11,11,11,11, 5,
  144360. 7, 6, 8, 8, 9,10,11,11,11,11,11,11,11,11, 6, 6,
  144361. 7, 9, 7,11,10,11,11,11,11,11,11,11,11, 5, 6, 6,
  144362. 11, 8,11,11,11,11,11,11,11,11,11,11, 5, 6, 6, 9,
  144363. 10,11,10,11,11,11,11,11,11,11,11, 7,10,10,11,11,
  144364. 11,11,11,11,11,11,11,11,11,11, 7,11, 8,11,11,11,
  144365. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144366. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144367. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144368. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144369. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144370. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144371. 11,11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,
  144372. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144373. 10,
  144374. };
  144375. static float _vq_quantthresh__8u0__p7_1[] = {
  144376. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  144377. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  144378. };
  144379. static long _vq_quantmap__8u0__p7_1[] = {
  144380. 13, 11, 9, 7, 5, 3, 1, 0,
  144381. 2, 4, 6, 8, 10, 12, 14,
  144382. };
  144383. static encode_aux_threshmatch _vq_auxt__8u0__p7_1 = {
  144384. _vq_quantthresh__8u0__p7_1,
  144385. _vq_quantmap__8u0__p7_1,
  144386. 15,
  144387. 15
  144388. };
  144389. static static_codebook _8u0__p7_1 = {
  144390. 2, 225,
  144391. _vq_lengthlist__8u0__p7_1,
  144392. 1, -520986624, 1620377600, 4, 0,
  144393. _vq_quantlist__8u0__p7_1,
  144394. NULL,
  144395. &_vq_auxt__8u0__p7_1,
  144396. NULL,
  144397. 0
  144398. };
  144399. static long _vq_quantlist__8u0__p7_2[] = {
  144400. 10,
  144401. 9,
  144402. 11,
  144403. 8,
  144404. 12,
  144405. 7,
  144406. 13,
  144407. 6,
  144408. 14,
  144409. 5,
  144410. 15,
  144411. 4,
  144412. 16,
  144413. 3,
  144414. 17,
  144415. 2,
  144416. 18,
  144417. 1,
  144418. 19,
  144419. 0,
  144420. 20,
  144421. };
  144422. static long _vq_lengthlist__8u0__p7_2[] = {
  144423. 1, 6, 5, 7, 7, 9, 9, 9, 9,10,12,12,10,11,11,10,
  144424. 11,11,11,10,11, 6, 8, 8, 9, 9,10,10, 9,10,11,11,
  144425. 10,11,11,11,11,10,11,11,11,11, 6, 7, 8, 9, 9, 9,
  144426. 10,11,10,11,12,11,10,11,11,11,11,11,11,12,10, 8,
  144427. 9, 9,10, 9,10,10, 9,10,10,10,10,10, 9,10,10,10,
  144428. 10, 9,10,10, 9, 9, 9, 9,10,10, 9, 9,10,10,11,10,
  144429. 9,12,10,11,10, 9,10,10,10, 8, 9, 9,10, 9,10, 9,
  144430. 9,10,10, 9,10, 9,11,10,10,10,10,10, 9,10, 8, 8,
  144431. 9, 9,10, 9,11, 9, 8, 9, 9,10,11,10,10,10,11,12,
  144432. 9, 9,11, 8, 9, 8,11,10,11,10,10, 9,11,10,10,10,
  144433. 10,10,10,10,11,11,11,11, 8, 9, 9, 9,10,10,10,11,
  144434. 11,12,11,12,11,10,10,10,12,11,11,11,10, 8,10, 9,
  144435. 11,10,10,11,12,10,11,12,11,11,12,11,12,12,10,11,
  144436. 11,10, 9, 9,10,11,12,10,10,10,11,10,11,11,10,12,
  144437. 12,10,11,10,11,12,10, 9,10,10,11,10,11,11,11,11,
  144438. 11,12,11,11,11, 9,11,10,11,10,11,10, 9, 9,10,11,
  144439. 11,11,10,10,11,12,12,11,12,11,11,11,12,12,12,12,
  144440. 11, 9,11,11,12,10,11,11,11,11,11,11,12,11,11,12,
  144441. 11,11,11,10,11,11, 9,11,10,11,11,11,10,10,10,11,
  144442. 11,11,12,10,11,10,11,11,11,11,12, 9,11,10,11,11,
  144443. 10,10,11,11, 9,11,11,12,10,10,10,10,10,11,11,10,
  144444. 9,10,11,11,12,11,10,10,12,11,11,12,11,12,11,11,
  144445. 10,10,11,11,10,12,11,10,11,10,11,10,10,10,11,11,
  144446. 10,10,11,11,11,11,10,10,10,12,11,11,11,11,10, 9,
  144447. 10,11,11,11,12,11,11,11,12,10,11,11,11, 9,10,11,
  144448. 11,11,11,11,11,10,10,11,11,12,11,10,11,12,11,10,
  144449. 10,11, 9,10,11,11,11,11,11,10,11,11,10,12,11,11,
  144450. 11,12,11,11,11,10,10,11,11,
  144451. };
  144452. static float _vq_quantthresh__8u0__p7_2[] = {
  144453. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  144454. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  144455. 6.5, 7.5, 8.5, 9.5,
  144456. };
  144457. static long _vq_quantmap__8u0__p7_2[] = {
  144458. 19, 17, 15, 13, 11, 9, 7, 5,
  144459. 3, 1, 0, 2, 4, 6, 8, 10,
  144460. 12, 14, 16, 18, 20,
  144461. };
  144462. static encode_aux_threshmatch _vq_auxt__8u0__p7_2 = {
  144463. _vq_quantthresh__8u0__p7_2,
  144464. _vq_quantmap__8u0__p7_2,
  144465. 21,
  144466. 21
  144467. };
  144468. static static_codebook _8u0__p7_2 = {
  144469. 2, 441,
  144470. _vq_lengthlist__8u0__p7_2,
  144471. 1, -529268736, 1611661312, 5, 0,
  144472. _vq_quantlist__8u0__p7_2,
  144473. NULL,
  144474. &_vq_auxt__8u0__p7_2,
  144475. NULL,
  144476. 0
  144477. };
  144478. static long _huff_lengthlist__8u0__single[] = {
  144479. 4, 7,11, 9,12, 8, 7,10, 6, 4, 5, 5, 7, 5, 6,16,
  144480. 9, 5, 5, 6, 7, 7, 9,16, 7, 4, 6, 5, 7, 5, 7,17,
  144481. 10, 7, 7, 8, 7, 7, 8,18, 7, 5, 6, 4, 5, 4, 5,15,
  144482. 7, 6, 7, 5, 6, 4, 5,15,12,13,18,12,17,11, 9,17,
  144483. };
  144484. static static_codebook _huff_book__8u0__single = {
  144485. 2, 64,
  144486. _huff_lengthlist__8u0__single,
  144487. 0, 0, 0, 0, 0,
  144488. NULL,
  144489. NULL,
  144490. NULL,
  144491. NULL,
  144492. 0
  144493. };
  144494. static long _vq_quantlist__8u1__p1_0[] = {
  144495. 1,
  144496. 0,
  144497. 2,
  144498. };
  144499. static long _vq_lengthlist__8u1__p1_0[] = {
  144500. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 7, 9,10, 7,
  144501. 9, 9, 5, 8, 8, 7,10, 9, 7, 9, 9, 5, 8, 8, 8,10,
  144502. 10, 8,10,10, 7,10,10, 9,10,12,10,12,12, 7,10,10,
  144503. 9,12,11,10,12,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  144504. 10,10,10,12,12, 9,11,12, 7,10,10,10,12,12, 9,12,
  144505. 10,
  144506. };
  144507. static float _vq_quantthresh__8u1__p1_0[] = {
  144508. -0.5, 0.5,
  144509. };
  144510. static long _vq_quantmap__8u1__p1_0[] = {
  144511. 1, 0, 2,
  144512. };
  144513. static encode_aux_threshmatch _vq_auxt__8u1__p1_0 = {
  144514. _vq_quantthresh__8u1__p1_0,
  144515. _vq_quantmap__8u1__p1_0,
  144516. 3,
  144517. 3
  144518. };
  144519. static static_codebook _8u1__p1_0 = {
  144520. 4, 81,
  144521. _vq_lengthlist__8u1__p1_0,
  144522. 1, -535822336, 1611661312, 2, 0,
  144523. _vq_quantlist__8u1__p1_0,
  144524. NULL,
  144525. &_vq_auxt__8u1__p1_0,
  144526. NULL,
  144527. 0
  144528. };
  144529. static long _vq_quantlist__8u1__p2_0[] = {
  144530. 1,
  144531. 0,
  144532. 2,
  144533. };
  144534. static long _vq_lengthlist__8u1__p2_0[] = {
  144535. 3, 4, 5, 5, 6, 6, 5, 6, 6, 5, 7, 6, 6, 7, 8, 6,
  144536. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 7, 8,
  144537. 8, 6, 7, 7, 6, 8, 7, 7, 7, 9, 8, 9, 9, 6, 7, 8,
  144538. 7, 9, 7, 8, 9, 9, 5, 6, 6, 6, 7, 7, 7, 8, 8, 6,
  144539. 8, 7, 8, 9, 9, 7, 7, 9, 6, 7, 8, 8, 9, 9, 7, 9,
  144540. 7,
  144541. };
  144542. static float _vq_quantthresh__8u1__p2_0[] = {
  144543. -0.5, 0.5,
  144544. };
  144545. static long _vq_quantmap__8u1__p2_0[] = {
  144546. 1, 0, 2,
  144547. };
  144548. static encode_aux_threshmatch _vq_auxt__8u1__p2_0 = {
  144549. _vq_quantthresh__8u1__p2_0,
  144550. _vq_quantmap__8u1__p2_0,
  144551. 3,
  144552. 3
  144553. };
  144554. static static_codebook _8u1__p2_0 = {
  144555. 4, 81,
  144556. _vq_lengthlist__8u1__p2_0,
  144557. 1, -535822336, 1611661312, 2, 0,
  144558. _vq_quantlist__8u1__p2_0,
  144559. NULL,
  144560. &_vq_auxt__8u1__p2_0,
  144561. NULL,
  144562. 0
  144563. };
  144564. static long _vq_quantlist__8u1__p3_0[] = {
  144565. 2,
  144566. 1,
  144567. 3,
  144568. 0,
  144569. 4,
  144570. };
  144571. static long _vq_lengthlist__8u1__p3_0[] = {
  144572. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  144573. 10, 9,11,11, 9, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  144574. 10,11,11, 8, 9,10,11,11,10,11,11,12,12,10,11,11,
  144575. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  144576. 11,10,11,11,12,12,10,11,11,12,12, 9,11,11,14,13,
  144577. 10,12,11,14,14,10,12,11,14,13,12,13,13,15,14,12,
  144578. 13,13,15,14, 8,11,11,13,14,10,11,12,13,15,10,11,
  144579. 12,14,14,12,13,13,14,15,12,13,13,14,15, 5, 8, 8,
  144580. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  144581. 13,11,12,12,13,14, 8,10,10,12,12, 9,11,12,13,14,
  144582. 10,12,12,13,13,12,12,13,14,14,11,13,13,15,15, 7,
  144583. 10,10,12,12, 9,12,11,14,12,10,11,12,13,14,12,13,
  144584. 12,14,14,12,13,13,15,16,10,12,12,15,14,11,12,13,
  144585. 15,15,11,13,13,15,16,14,14,15,15,16,13,14,15,17,
  144586. 15, 9,12,12,14,15,11,13,12,15,15,11,13,13,15,15,
  144587. 13,14,13,15,14,13,14,14,17, 0, 5, 8, 8,11,11, 8,
  144588. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  144589. 12,14,14, 7,10,10,12,12,10,12,12,13,13, 9,11,12,
  144590. 12,13,11,12,13,15,15,11,12,13,14,15, 8,10,10,12,
  144591. 12,10,12,11,13,13,10,12,11,13,13,11,13,13,15,14,
  144592. 12,13,12,15,13, 9,12,12,14,14,11,13,13,16,15,11,
  144593. 12,13,16,15,13,14,15,16,16,13,13,15,15,16,10,12,
  144594. 12,15,14,11,13,13,14,16,11,13,13,15,16,13,15,15,
  144595. 16,17,13,15,14,16,15, 8,11,11,14,15,10,12,12,15,
  144596. 15,10,12,12,15,16,14,15,15,16,17,13,14,14,16,16,
  144597. 9,12,12,15,15,11,13,14,15,17,11,13,13,15,16,14,
  144598. 15,16,19,17,13,15,15, 0,17, 9,12,12,15,15,11,14,
  144599. 13,16,15,11,13,13,15,16,15,15,15,18,17,13,15,15,
  144600. 17,17,11,15,14,18,16,12,14,15,17,17,12,15,15,18,
  144601. 18,15,15,16,15,19,14,16,16, 0, 0,11,14,14,16,17,
  144602. 12,15,14,18,17,12,15,15,18,18,15,17,15,18,16,14,
  144603. 16,16,18,18, 7,11,11,14,14,10,12,12,15,15,10,12,
  144604. 13,15,15,13,14,15,16,16,14,15,15,18,18, 9,12,12,
  144605. 15,15,11,13,13,16,15,11,12,13,16,16,14,15,15,17,
  144606. 16,15,16,16,17,17, 9,12,12,15,15,11,13,13,15,17,
  144607. 11,14,13,16,15,13,15,15,17,17,15,15,15,18,17,11,
  144608. 14,14,17,15,12,14,15,17,18,13,13,15,17,17,14,16,
  144609. 16,19,18,16,15,17,17, 0,11,14,14,17,17,12,15,15,
  144610. 18, 0,12,15,14,18,16,14,17,17,19, 0,16,18,15, 0,
  144611. 16,
  144612. };
  144613. static float _vq_quantthresh__8u1__p3_0[] = {
  144614. -1.5, -0.5, 0.5, 1.5,
  144615. };
  144616. static long _vq_quantmap__8u1__p3_0[] = {
  144617. 3, 1, 0, 2, 4,
  144618. };
  144619. static encode_aux_threshmatch _vq_auxt__8u1__p3_0 = {
  144620. _vq_quantthresh__8u1__p3_0,
  144621. _vq_quantmap__8u1__p3_0,
  144622. 5,
  144623. 5
  144624. };
  144625. static static_codebook _8u1__p3_0 = {
  144626. 4, 625,
  144627. _vq_lengthlist__8u1__p3_0,
  144628. 1, -533725184, 1611661312, 3, 0,
  144629. _vq_quantlist__8u1__p3_0,
  144630. NULL,
  144631. &_vq_auxt__8u1__p3_0,
  144632. NULL,
  144633. 0
  144634. };
  144635. static long _vq_quantlist__8u1__p4_0[] = {
  144636. 2,
  144637. 1,
  144638. 3,
  144639. 0,
  144640. 4,
  144641. };
  144642. static long _vq_lengthlist__8u1__p4_0[] = {
  144643. 4, 5, 5, 9, 9, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 9,
  144644. 9, 9,11,11, 9, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 7,
  144645. 8, 9,10, 7, 7, 8, 9,10, 9, 9,10,10,11, 9, 9,10,
  144646. 10,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 7,10,
  144647. 9, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  144648. 9,10,10,12,11, 9,10,10,12,12,11,11,12,12,13,11,
  144649. 11,12,12,13, 9, 9,10,12,11, 9,10,10,12,12,10,10,
  144650. 10,12,12,11,12,11,13,12,11,12,11,13,12, 6, 7, 7,
  144651. 9, 9, 7, 8, 8,10,10, 7, 8, 7,10, 9,10,10,10,12,
  144652. 12,10,10,10,12,11, 7, 8, 7,10,10, 7, 7, 9,10,11,
  144653. 8, 9, 9,11,10,10,10,11,10,12,10,10,11,12,12, 7,
  144654. 8, 8,10,10, 7, 9, 8,11,10, 8, 8, 9,11,11,10,11,
  144655. 10,12,11,10,11,11,12,12, 9,10,10,12,12, 9,10,10,
  144656. 12,12,10,11,11,13,12,11,10,12,10,14,12,12,12,13,
  144657. 14, 9,10,10,12,12, 9,11,10,12,12,10,11,11,12,12,
  144658. 11,12,11,14,12,12,12,12,14,14, 5, 7, 7, 9, 9, 7,
  144659. 7, 7, 9,10, 7, 8, 8,10,10,10,10,10,11,11,10,10,
  144660. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  144661. 10,11,10,10,10,11,12,10,10,11,11,13, 6, 7, 8,10,
  144662. 10, 8, 9, 9,10,10, 7, 9, 7,11,10,10,11,10,12,12,
  144663. 10,11,10,12,10, 9,10,10,12,12,10,11,11,13,12, 9,
  144664. 10,10,12,12,12,12,12,14,13,11,11,12,11,14, 9,10,
  144665. 10,11,12,10,11,11,12,13, 9,10,10,12,12,12,12,12,
  144666. 14,13,11,12,10,14,11, 9, 9,10,11,12, 9,10,10,12,
  144667. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,13,12,
  144668. 9,10, 9,12,12, 9,10,11,12,13,10,11,10,13,11,12,
  144669. 12,13,13,14,12,12,12,13,13, 9,10,10,12,12,10,11,
  144670. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,12,
  144671. 13,14,11,12,11,14,13,10,10,11,13,13,12,12,12,14,
  144672. 13,12,10,14,10,15,13,14,14,14,14,11,11,12,13,14,
  144673. 10,12,11,13,13,12,12,12,13,15,12,13,11,15,12,13,
  144674. 13,14,14,14, 9,10, 9,12,12, 9,10,10,12,12,10,10,
  144675. 10,12,12,11,11,12,12,13,12,12,12,14,14, 9,10,10,
  144676. 12,12,10,11,10,13,12,10,10,11,12,13,12,12,12,14,
  144677. 13,12,12,13,13,14, 9,10,10,12,13,10,10,11,11,12,
  144678. 9,11,10,13,12,12,12,12,13,14,12,13,12,14,13,11,
  144679. 12,11,13,13,12,13,12,14,13,10,11,12,13,13,13,13,
  144680. 13,14,15,12,11,14,12,14,11,11,12,12,13,12,12,12,
  144681. 13,14,10,12,10,14,13,13,13,13,14,15,12,14,11,15,
  144682. 10,
  144683. };
  144684. static float _vq_quantthresh__8u1__p4_0[] = {
  144685. -1.5, -0.5, 0.5, 1.5,
  144686. };
  144687. static long _vq_quantmap__8u1__p4_0[] = {
  144688. 3, 1, 0, 2, 4,
  144689. };
  144690. static encode_aux_threshmatch _vq_auxt__8u1__p4_0 = {
  144691. _vq_quantthresh__8u1__p4_0,
  144692. _vq_quantmap__8u1__p4_0,
  144693. 5,
  144694. 5
  144695. };
  144696. static static_codebook _8u1__p4_0 = {
  144697. 4, 625,
  144698. _vq_lengthlist__8u1__p4_0,
  144699. 1, -533725184, 1611661312, 3, 0,
  144700. _vq_quantlist__8u1__p4_0,
  144701. NULL,
  144702. &_vq_auxt__8u1__p4_0,
  144703. NULL,
  144704. 0
  144705. };
  144706. static long _vq_quantlist__8u1__p5_0[] = {
  144707. 4,
  144708. 3,
  144709. 5,
  144710. 2,
  144711. 6,
  144712. 1,
  144713. 7,
  144714. 0,
  144715. 8,
  144716. };
  144717. static long _vq_lengthlist__8u1__p5_0[] = {
  144718. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  144719. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  144720. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  144721. 9, 9,10,10,12,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  144722. 10,10,11,11,11,11,13,12, 9,10,10,11,11,12,12,12,
  144723. 13,
  144724. };
  144725. static float _vq_quantthresh__8u1__p5_0[] = {
  144726. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144727. };
  144728. static long _vq_quantmap__8u1__p5_0[] = {
  144729. 7, 5, 3, 1, 0, 2, 4, 6,
  144730. 8,
  144731. };
  144732. static encode_aux_threshmatch _vq_auxt__8u1__p5_0 = {
  144733. _vq_quantthresh__8u1__p5_0,
  144734. _vq_quantmap__8u1__p5_0,
  144735. 9,
  144736. 9
  144737. };
  144738. static static_codebook _8u1__p5_0 = {
  144739. 2, 81,
  144740. _vq_lengthlist__8u1__p5_0,
  144741. 1, -531628032, 1611661312, 4, 0,
  144742. _vq_quantlist__8u1__p5_0,
  144743. NULL,
  144744. &_vq_auxt__8u1__p5_0,
  144745. NULL,
  144746. 0
  144747. };
  144748. static long _vq_quantlist__8u1__p6_0[] = {
  144749. 4,
  144750. 3,
  144751. 5,
  144752. 2,
  144753. 6,
  144754. 1,
  144755. 7,
  144756. 0,
  144757. 8,
  144758. };
  144759. static long _vq_lengthlist__8u1__p6_0[] = {
  144760. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 5, 6, 6, 7, 7,
  144761. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  144762. 8, 8, 9, 9, 6, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  144763. 8, 8, 8, 9,10,10, 7, 7, 7, 8, 8, 9, 8,10,10, 9,
  144764. 9, 9, 9, 9,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  144765. 10,
  144766. };
  144767. static float _vq_quantthresh__8u1__p6_0[] = {
  144768. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144769. };
  144770. static long _vq_quantmap__8u1__p6_0[] = {
  144771. 7, 5, 3, 1, 0, 2, 4, 6,
  144772. 8,
  144773. };
  144774. static encode_aux_threshmatch _vq_auxt__8u1__p6_0 = {
  144775. _vq_quantthresh__8u1__p6_0,
  144776. _vq_quantmap__8u1__p6_0,
  144777. 9,
  144778. 9
  144779. };
  144780. static static_codebook _8u1__p6_0 = {
  144781. 2, 81,
  144782. _vq_lengthlist__8u1__p6_0,
  144783. 1, -531628032, 1611661312, 4, 0,
  144784. _vq_quantlist__8u1__p6_0,
  144785. NULL,
  144786. &_vq_auxt__8u1__p6_0,
  144787. NULL,
  144788. 0
  144789. };
  144790. static long _vq_quantlist__8u1__p7_0[] = {
  144791. 1,
  144792. 0,
  144793. 2,
  144794. };
  144795. static long _vq_lengthlist__8u1__p7_0[] = {
  144796. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,10,10, 8,
  144797. 10,10, 5, 9, 9, 7,10,10, 8,10,10, 4,10,10, 9,12,
  144798. 12, 9,11,11, 7,12,11,10,11,13,10,13,13, 7,12,12,
  144799. 10,13,12,10,13,13, 4,10,10, 9,12,12, 9,12,12, 7,
  144800. 12,12,10,13,13,10,12,13, 7,11,12,10,13,13,10,13,
  144801. 11,
  144802. };
  144803. static float _vq_quantthresh__8u1__p7_0[] = {
  144804. -5.5, 5.5,
  144805. };
  144806. static long _vq_quantmap__8u1__p7_0[] = {
  144807. 1, 0, 2,
  144808. };
  144809. static encode_aux_threshmatch _vq_auxt__8u1__p7_0 = {
  144810. _vq_quantthresh__8u1__p7_0,
  144811. _vq_quantmap__8u1__p7_0,
  144812. 3,
  144813. 3
  144814. };
  144815. static static_codebook _8u1__p7_0 = {
  144816. 4, 81,
  144817. _vq_lengthlist__8u1__p7_0,
  144818. 1, -529137664, 1618345984, 2, 0,
  144819. _vq_quantlist__8u1__p7_0,
  144820. NULL,
  144821. &_vq_auxt__8u1__p7_0,
  144822. NULL,
  144823. 0
  144824. };
  144825. static long _vq_quantlist__8u1__p7_1[] = {
  144826. 5,
  144827. 4,
  144828. 6,
  144829. 3,
  144830. 7,
  144831. 2,
  144832. 8,
  144833. 1,
  144834. 9,
  144835. 0,
  144836. 10,
  144837. };
  144838. static long _vq_lengthlist__8u1__p7_1[] = {
  144839. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  144840. 8, 8, 9, 9, 9, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 9,
  144841. 9, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  144842. 8, 8, 8, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  144843. 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  144844. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  144845. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  144846. 9, 9, 9, 9, 9,10,10,10,10,
  144847. };
  144848. static float _vq_quantthresh__8u1__p7_1[] = {
  144849. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144850. 3.5, 4.5,
  144851. };
  144852. static long _vq_quantmap__8u1__p7_1[] = {
  144853. 9, 7, 5, 3, 1, 0, 2, 4,
  144854. 6, 8, 10,
  144855. };
  144856. static encode_aux_threshmatch _vq_auxt__8u1__p7_1 = {
  144857. _vq_quantthresh__8u1__p7_1,
  144858. _vq_quantmap__8u1__p7_1,
  144859. 11,
  144860. 11
  144861. };
  144862. static static_codebook _8u1__p7_1 = {
  144863. 2, 121,
  144864. _vq_lengthlist__8u1__p7_1,
  144865. 1, -531365888, 1611661312, 4, 0,
  144866. _vq_quantlist__8u1__p7_1,
  144867. NULL,
  144868. &_vq_auxt__8u1__p7_1,
  144869. NULL,
  144870. 0
  144871. };
  144872. static long _vq_quantlist__8u1__p8_0[] = {
  144873. 5,
  144874. 4,
  144875. 6,
  144876. 3,
  144877. 7,
  144878. 2,
  144879. 8,
  144880. 1,
  144881. 9,
  144882. 0,
  144883. 10,
  144884. };
  144885. static long _vq_lengthlist__8u1__p8_0[] = {
  144886. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  144887. 9, 9,11,11,13,12, 4, 6, 6, 7, 7, 9, 9,11,11,12,
  144888. 12, 6, 7, 7, 9, 9,11,11,12,12,13,13, 6, 7, 7, 9,
  144889. 9,11,11,12,12,13,13, 8, 9, 9,11,11,12,12,13,13,
  144890. 14,14, 8, 9, 9,11,11,12,12,13,13,14,14, 9,11,11,
  144891. 12,12,13,13,14,14,15,15, 9,11,11,12,12,13,13,14,
  144892. 14,15,14,11,12,12,13,13,14,14,15,15,16,16,11,12,
  144893. 12,13,13,14,14,15,15,15,15,
  144894. };
  144895. static float _vq_quantthresh__8u1__p8_0[] = {
  144896. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  144897. 38.5, 49.5,
  144898. };
  144899. static long _vq_quantmap__8u1__p8_0[] = {
  144900. 9, 7, 5, 3, 1, 0, 2, 4,
  144901. 6, 8, 10,
  144902. };
  144903. static encode_aux_threshmatch _vq_auxt__8u1__p8_0 = {
  144904. _vq_quantthresh__8u1__p8_0,
  144905. _vq_quantmap__8u1__p8_0,
  144906. 11,
  144907. 11
  144908. };
  144909. static static_codebook _8u1__p8_0 = {
  144910. 2, 121,
  144911. _vq_lengthlist__8u1__p8_0,
  144912. 1, -524582912, 1618345984, 4, 0,
  144913. _vq_quantlist__8u1__p8_0,
  144914. NULL,
  144915. &_vq_auxt__8u1__p8_0,
  144916. NULL,
  144917. 0
  144918. };
  144919. static long _vq_quantlist__8u1__p8_1[] = {
  144920. 5,
  144921. 4,
  144922. 6,
  144923. 3,
  144924. 7,
  144925. 2,
  144926. 8,
  144927. 1,
  144928. 9,
  144929. 0,
  144930. 10,
  144931. };
  144932. static long _vq_lengthlist__8u1__p8_1[] = {
  144933. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 6, 6, 7, 7,
  144934. 7, 7, 8, 8, 8, 8, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  144935. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  144936. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  144937. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144938. 8, 8, 8, 8, 9, 8, 9, 9, 7, 8, 8, 8, 8, 8, 8, 9,
  144939. 8, 9, 9, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8,
  144940. 8, 8, 8, 8, 8, 9, 9, 9, 9,
  144941. };
  144942. static float _vq_quantthresh__8u1__p8_1[] = {
  144943. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144944. 3.5, 4.5,
  144945. };
  144946. static long _vq_quantmap__8u1__p8_1[] = {
  144947. 9, 7, 5, 3, 1, 0, 2, 4,
  144948. 6, 8, 10,
  144949. };
  144950. static encode_aux_threshmatch _vq_auxt__8u1__p8_1 = {
  144951. _vq_quantthresh__8u1__p8_1,
  144952. _vq_quantmap__8u1__p8_1,
  144953. 11,
  144954. 11
  144955. };
  144956. static static_codebook _8u1__p8_1 = {
  144957. 2, 121,
  144958. _vq_lengthlist__8u1__p8_1,
  144959. 1, -531365888, 1611661312, 4, 0,
  144960. _vq_quantlist__8u1__p8_1,
  144961. NULL,
  144962. &_vq_auxt__8u1__p8_1,
  144963. NULL,
  144964. 0
  144965. };
  144966. static long _vq_quantlist__8u1__p9_0[] = {
  144967. 7,
  144968. 6,
  144969. 8,
  144970. 5,
  144971. 9,
  144972. 4,
  144973. 10,
  144974. 3,
  144975. 11,
  144976. 2,
  144977. 12,
  144978. 1,
  144979. 13,
  144980. 0,
  144981. 14,
  144982. };
  144983. static long _vq_lengthlist__8u1__p9_0[] = {
  144984. 1, 4, 4,11,11,11,11,11,11,11,11,11,11,11,11, 3,
  144985. 11, 8,11,11,11,11,11,11,11,11,11,11,11,11, 3, 9,
  144986. 9,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144987. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144988. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144989. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144990. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144991. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144992. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144993. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144994. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144995. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144996. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  144997. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144998. 10,
  144999. };
  145000. static float _vq_quantthresh__8u1__p9_0[] = {
  145001. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  145002. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  145003. };
  145004. static long _vq_quantmap__8u1__p9_0[] = {
  145005. 13, 11, 9, 7, 5, 3, 1, 0,
  145006. 2, 4, 6, 8, 10, 12, 14,
  145007. };
  145008. static encode_aux_threshmatch _vq_auxt__8u1__p9_0 = {
  145009. _vq_quantthresh__8u1__p9_0,
  145010. _vq_quantmap__8u1__p9_0,
  145011. 15,
  145012. 15
  145013. };
  145014. static static_codebook _8u1__p9_0 = {
  145015. 2, 225,
  145016. _vq_lengthlist__8u1__p9_0,
  145017. 1, -514071552, 1627381760, 4, 0,
  145018. _vq_quantlist__8u1__p9_0,
  145019. NULL,
  145020. &_vq_auxt__8u1__p9_0,
  145021. NULL,
  145022. 0
  145023. };
  145024. static long _vq_quantlist__8u1__p9_1[] = {
  145025. 7,
  145026. 6,
  145027. 8,
  145028. 5,
  145029. 9,
  145030. 4,
  145031. 10,
  145032. 3,
  145033. 11,
  145034. 2,
  145035. 12,
  145036. 1,
  145037. 13,
  145038. 0,
  145039. 14,
  145040. };
  145041. static long _vq_lengthlist__8u1__p9_1[] = {
  145042. 1, 4, 4, 7, 7, 9, 9, 7, 7, 8, 8,10,10,11,11, 4,
  145043. 7, 7, 9, 9,10,10, 8, 8,10,10,10,11,10,11, 4, 7,
  145044. 7, 9, 9,10,10, 8, 8,10, 9,11,11,11,11, 7, 9, 9,
  145045. 12,12,11,12,10,10,11,10,12,11,11,11, 7, 9, 9,11,
  145046. 11,13,12, 9, 9,11,10,11,11,12,11, 9,10,10,12,12,
  145047. 14,14,10,10,11,12,12,11,11,11, 9,10,11,11,13,14,
  145048. 13,10,11,11,11,12,11,12,12, 7, 8, 8,10, 9,11,10,
  145049. 11,12,12,11,12,14,12,13, 7, 8, 8, 9,10,10,11,12,
  145050. 12,12,11,12,12,12,13, 9, 9, 9,11,11,13,12,12,12,
  145051. 12,11,12,12,13,12, 8,10,10,11,10,11,12,12,12,12,
  145052. 12,12,14,12,12, 9,11,11,11,12,12,12,12,13,13,12,
  145053. 12,13,13,12,10,11,11,12,11,12,12,12,11,12,13,12,
  145054. 12,12,13,11,11,12,12,12,13,12,12,11,12,13,13,12,
  145055. 12,13,12,11,12,12,13,13,12,13,12,13,13,13,13,14,
  145056. 13,
  145057. };
  145058. static float _vq_quantthresh__8u1__p9_1[] = {
  145059. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  145060. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  145061. };
  145062. static long _vq_quantmap__8u1__p9_1[] = {
  145063. 13, 11, 9, 7, 5, 3, 1, 0,
  145064. 2, 4, 6, 8, 10, 12, 14,
  145065. };
  145066. static encode_aux_threshmatch _vq_auxt__8u1__p9_1 = {
  145067. _vq_quantthresh__8u1__p9_1,
  145068. _vq_quantmap__8u1__p9_1,
  145069. 15,
  145070. 15
  145071. };
  145072. static static_codebook _8u1__p9_1 = {
  145073. 2, 225,
  145074. _vq_lengthlist__8u1__p9_1,
  145075. 1, -522338304, 1620115456, 4, 0,
  145076. _vq_quantlist__8u1__p9_1,
  145077. NULL,
  145078. &_vq_auxt__8u1__p9_1,
  145079. NULL,
  145080. 0
  145081. };
  145082. static long _vq_quantlist__8u1__p9_2[] = {
  145083. 8,
  145084. 7,
  145085. 9,
  145086. 6,
  145087. 10,
  145088. 5,
  145089. 11,
  145090. 4,
  145091. 12,
  145092. 3,
  145093. 13,
  145094. 2,
  145095. 14,
  145096. 1,
  145097. 15,
  145098. 0,
  145099. 16,
  145100. };
  145101. static long _vq_lengthlist__8u1__p9_2[] = {
  145102. 2, 5, 4, 6, 6, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  145103. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  145104. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  145105. 9, 9, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  145106. 9,10,10, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  145107. 9, 9, 9,10,10, 8, 8, 8, 9, 9, 9, 9,10,10,10, 9,
  145108. 10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  145109. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,
  145110. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  145111. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  145112. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  145113. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  145114. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  145115. 9,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  145116. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10,
  145117. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  145118. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145119. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145120. 10,
  145121. };
  145122. static float _vq_quantthresh__8u1__p9_2[] = {
  145123. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  145124. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  145125. };
  145126. static long _vq_quantmap__8u1__p9_2[] = {
  145127. 15, 13, 11, 9, 7, 5, 3, 1,
  145128. 0, 2, 4, 6, 8, 10, 12, 14,
  145129. 16,
  145130. };
  145131. static encode_aux_threshmatch _vq_auxt__8u1__p9_2 = {
  145132. _vq_quantthresh__8u1__p9_2,
  145133. _vq_quantmap__8u1__p9_2,
  145134. 17,
  145135. 17
  145136. };
  145137. static static_codebook _8u1__p9_2 = {
  145138. 2, 289,
  145139. _vq_lengthlist__8u1__p9_2,
  145140. 1, -529530880, 1611661312, 5, 0,
  145141. _vq_quantlist__8u1__p9_2,
  145142. NULL,
  145143. &_vq_auxt__8u1__p9_2,
  145144. NULL,
  145145. 0
  145146. };
  145147. static long _huff_lengthlist__8u1__single[] = {
  145148. 4, 7,13, 9,15, 9,16, 8,10,13, 7, 5, 8, 6, 9, 7,
  145149. 10, 7,10,11,11, 6, 7, 8, 8, 9, 9, 9,12,16, 8, 5,
  145150. 8, 6, 8, 6, 9, 7,10,12,11, 7, 7, 7, 6, 7, 7, 7,
  145151. 11,15, 7, 5, 8, 6, 7, 5, 7, 6, 9,13,13, 9, 9, 8,
  145152. 6, 6, 5, 5, 9,14, 8, 6, 8, 6, 6, 4, 5, 3, 5,13,
  145153. 9, 9,11, 8,10, 7, 8, 4, 5,12,11,16,17,15,17,12,
  145154. 13, 8, 8,15,
  145155. };
  145156. static static_codebook _huff_book__8u1__single = {
  145157. 2, 100,
  145158. _huff_lengthlist__8u1__single,
  145159. 0, 0, 0, 0, 0,
  145160. NULL,
  145161. NULL,
  145162. NULL,
  145163. NULL,
  145164. 0
  145165. };
  145166. static long _huff_lengthlist__44u0__long[] = {
  145167. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  145168. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  145169. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  145170. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  145171. };
  145172. static static_codebook _huff_book__44u0__long = {
  145173. 2, 64,
  145174. _huff_lengthlist__44u0__long,
  145175. 0, 0, 0, 0, 0,
  145176. NULL,
  145177. NULL,
  145178. NULL,
  145179. NULL,
  145180. 0
  145181. };
  145182. static long _vq_quantlist__44u0__p1_0[] = {
  145183. 1,
  145184. 0,
  145185. 2,
  145186. };
  145187. static long _vq_lengthlist__44u0__p1_0[] = {
  145188. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  145189. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  145190. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  145191. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  145192. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  145193. 13,
  145194. };
  145195. static float _vq_quantthresh__44u0__p1_0[] = {
  145196. -0.5, 0.5,
  145197. };
  145198. static long _vq_quantmap__44u0__p1_0[] = {
  145199. 1, 0, 2,
  145200. };
  145201. static encode_aux_threshmatch _vq_auxt__44u0__p1_0 = {
  145202. _vq_quantthresh__44u0__p1_0,
  145203. _vq_quantmap__44u0__p1_0,
  145204. 3,
  145205. 3
  145206. };
  145207. static static_codebook _44u0__p1_0 = {
  145208. 4, 81,
  145209. _vq_lengthlist__44u0__p1_0,
  145210. 1, -535822336, 1611661312, 2, 0,
  145211. _vq_quantlist__44u0__p1_0,
  145212. NULL,
  145213. &_vq_auxt__44u0__p1_0,
  145214. NULL,
  145215. 0
  145216. };
  145217. static long _vq_quantlist__44u0__p2_0[] = {
  145218. 1,
  145219. 0,
  145220. 2,
  145221. };
  145222. static long _vq_lengthlist__44u0__p2_0[] = {
  145223. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  145224. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  145225. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  145226. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  145227. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  145228. 9,
  145229. };
  145230. static float _vq_quantthresh__44u0__p2_0[] = {
  145231. -0.5, 0.5,
  145232. };
  145233. static long _vq_quantmap__44u0__p2_0[] = {
  145234. 1, 0, 2,
  145235. };
  145236. static encode_aux_threshmatch _vq_auxt__44u0__p2_0 = {
  145237. _vq_quantthresh__44u0__p2_0,
  145238. _vq_quantmap__44u0__p2_0,
  145239. 3,
  145240. 3
  145241. };
  145242. static static_codebook _44u0__p2_0 = {
  145243. 4, 81,
  145244. _vq_lengthlist__44u0__p2_0,
  145245. 1, -535822336, 1611661312, 2, 0,
  145246. _vq_quantlist__44u0__p2_0,
  145247. NULL,
  145248. &_vq_auxt__44u0__p2_0,
  145249. NULL,
  145250. 0
  145251. };
  145252. static long _vq_quantlist__44u0__p3_0[] = {
  145253. 2,
  145254. 1,
  145255. 3,
  145256. 0,
  145257. 4,
  145258. };
  145259. static long _vq_lengthlist__44u0__p3_0[] = {
  145260. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  145261. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  145262. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  145263. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  145264. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  145265. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  145266. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  145267. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  145268. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  145269. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  145270. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  145271. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  145272. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  145273. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  145274. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  145275. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  145276. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  145277. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  145278. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  145279. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  145280. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  145281. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  145282. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  145283. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  145284. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  145285. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  145286. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  145287. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  145288. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  145289. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  145290. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  145291. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  145292. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  145293. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  145294. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  145295. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  145296. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  145297. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  145298. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  145299. 19,
  145300. };
  145301. static float _vq_quantthresh__44u0__p3_0[] = {
  145302. -1.5, -0.5, 0.5, 1.5,
  145303. };
  145304. static long _vq_quantmap__44u0__p3_0[] = {
  145305. 3, 1, 0, 2, 4,
  145306. };
  145307. static encode_aux_threshmatch _vq_auxt__44u0__p3_0 = {
  145308. _vq_quantthresh__44u0__p3_0,
  145309. _vq_quantmap__44u0__p3_0,
  145310. 5,
  145311. 5
  145312. };
  145313. static static_codebook _44u0__p3_0 = {
  145314. 4, 625,
  145315. _vq_lengthlist__44u0__p3_0,
  145316. 1, -533725184, 1611661312, 3, 0,
  145317. _vq_quantlist__44u0__p3_0,
  145318. NULL,
  145319. &_vq_auxt__44u0__p3_0,
  145320. NULL,
  145321. 0
  145322. };
  145323. static long _vq_quantlist__44u0__p4_0[] = {
  145324. 2,
  145325. 1,
  145326. 3,
  145327. 0,
  145328. 4,
  145329. };
  145330. static long _vq_lengthlist__44u0__p4_0[] = {
  145331. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  145332. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  145333. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  145334. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  145335. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  145336. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  145337. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  145338. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  145339. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  145340. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  145341. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  145342. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  145343. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  145344. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  145345. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  145346. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  145347. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  145348. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  145349. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  145350. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  145351. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  145352. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  145353. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  145354. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  145355. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  145356. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  145357. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  145358. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  145359. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  145360. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  145361. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  145362. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  145363. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  145364. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  145365. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  145366. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  145367. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  145368. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  145369. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  145370. 12,
  145371. };
  145372. static float _vq_quantthresh__44u0__p4_0[] = {
  145373. -1.5, -0.5, 0.5, 1.5,
  145374. };
  145375. static long _vq_quantmap__44u0__p4_0[] = {
  145376. 3, 1, 0, 2, 4,
  145377. };
  145378. static encode_aux_threshmatch _vq_auxt__44u0__p4_0 = {
  145379. _vq_quantthresh__44u0__p4_0,
  145380. _vq_quantmap__44u0__p4_0,
  145381. 5,
  145382. 5
  145383. };
  145384. static static_codebook _44u0__p4_0 = {
  145385. 4, 625,
  145386. _vq_lengthlist__44u0__p4_0,
  145387. 1, -533725184, 1611661312, 3, 0,
  145388. _vq_quantlist__44u0__p4_0,
  145389. NULL,
  145390. &_vq_auxt__44u0__p4_0,
  145391. NULL,
  145392. 0
  145393. };
  145394. static long _vq_quantlist__44u0__p5_0[] = {
  145395. 4,
  145396. 3,
  145397. 5,
  145398. 2,
  145399. 6,
  145400. 1,
  145401. 7,
  145402. 0,
  145403. 8,
  145404. };
  145405. static long _vq_lengthlist__44u0__p5_0[] = {
  145406. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  145407. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  145408. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  145409. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  145410. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  145411. 12,
  145412. };
  145413. static float _vq_quantthresh__44u0__p5_0[] = {
  145414. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145415. };
  145416. static long _vq_quantmap__44u0__p5_0[] = {
  145417. 7, 5, 3, 1, 0, 2, 4, 6,
  145418. 8,
  145419. };
  145420. static encode_aux_threshmatch _vq_auxt__44u0__p5_0 = {
  145421. _vq_quantthresh__44u0__p5_0,
  145422. _vq_quantmap__44u0__p5_0,
  145423. 9,
  145424. 9
  145425. };
  145426. static static_codebook _44u0__p5_0 = {
  145427. 2, 81,
  145428. _vq_lengthlist__44u0__p5_0,
  145429. 1, -531628032, 1611661312, 4, 0,
  145430. _vq_quantlist__44u0__p5_0,
  145431. NULL,
  145432. &_vq_auxt__44u0__p5_0,
  145433. NULL,
  145434. 0
  145435. };
  145436. static long _vq_quantlist__44u0__p6_0[] = {
  145437. 6,
  145438. 5,
  145439. 7,
  145440. 4,
  145441. 8,
  145442. 3,
  145443. 9,
  145444. 2,
  145445. 10,
  145446. 1,
  145447. 11,
  145448. 0,
  145449. 12,
  145450. };
  145451. static long _vq_lengthlist__44u0__p6_0[] = {
  145452. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  145453. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  145454. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  145455. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  145456. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  145457. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  145458. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  145459. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  145460. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  145461. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  145462. 15,17,16,17,18,17,17,18, 0,
  145463. };
  145464. static float _vq_quantthresh__44u0__p6_0[] = {
  145465. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  145466. 12.5, 17.5, 22.5, 27.5,
  145467. };
  145468. static long _vq_quantmap__44u0__p6_0[] = {
  145469. 11, 9, 7, 5, 3, 1, 0, 2,
  145470. 4, 6, 8, 10, 12,
  145471. };
  145472. static encode_aux_threshmatch _vq_auxt__44u0__p6_0 = {
  145473. _vq_quantthresh__44u0__p6_0,
  145474. _vq_quantmap__44u0__p6_0,
  145475. 13,
  145476. 13
  145477. };
  145478. static static_codebook _44u0__p6_0 = {
  145479. 2, 169,
  145480. _vq_lengthlist__44u0__p6_0,
  145481. 1, -526516224, 1616117760, 4, 0,
  145482. _vq_quantlist__44u0__p6_0,
  145483. NULL,
  145484. &_vq_auxt__44u0__p6_0,
  145485. NULL,
  145486. 0
  145487. };
  145488. static long _vq_quantlist__44u0__p6_1[] = {
  145489. 2,
  145490. 1,
  145491. 3,
  145492. 0,
  145493. 4,
  145494. };
  145495. static long _vq_lengthlist__44u0__p6_1[] = {
  145496. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  145497. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  145498. };
  145499. static float _vq_quantthresh__44u0__p6_1[] = {
  145500. -1.5, -0.5, 0.5, 1.5,
  145501. };
  145502. static long _vq_quantmap__44u0__p6_1[] = {
  145503. 3, 1, 0, 2, 4,
  145504. };
  145505. static encode_aux_threshmatch _vq_auxt__44u0__p6_1 = {
  145506. _vq_quantthresh__44u0__p6_1,
  145507. _vq_quantmap__44u0__p6_1,
  145508. 5,
  145509. 5
  145510. };
  145511. static static_codebook _44u0__p6_1 = {
  145512. 2, 25,
  145513. _vq_lengthlist__44u0__p6_1,
  145514. 1, -533725184, 1611661312, 3, 0,
  145515. _vq_quantlist__44u0__p6_1,
  145516. NULL,
  145517. &_vq_auxt__44u0__p6_1,
  145518. NULL,
  145519. 0
  145520. };
  145521. static long _vq_quantlist__44u0__p7_0[] = {
  145522. 2,
  145523. 1,
  145524. 3,
  145525. 0,
  145526. 4,
  145527. };
  145528. static long _vq_lengthlist__44u0__p7_0[] = {
  145529. 1, 4, 4,11,11, 9,11,11,11,11,11,11,11,11,11,11,
  145530. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145531. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145532. 11,11, 9,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145533. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145534. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145535. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145536. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  145537. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145538. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145539. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145540. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145541. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145542. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145543. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145544. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145545. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145546. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145547. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145548. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145549. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145550. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145551. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145552. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145553. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145554. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145555. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145556. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145557. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145558. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145559. 11,11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,
  145560. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145561. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145562. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145563. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145564. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145565. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145566. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145567. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145568. 10,
  145569. };
  145570. static float _vq_quantthresh__44u0__p7_0[] = {
  145571. -253.5, -84.5, 84.5, 253.5,
  145572. };
  145573. static long _vq_quantmap__44u0__p7_0[] = {
  145574. 3, 1, 0, 2, 4,
  145575. };
  145576. static encode_aux_threshmatch _vq_auxt__44u0__p7_0 = {
  145577. _vq_quantthresh__44u0__p7_0,
  145578. _vq_quantmap__44u0__p7_0,
  145579. 5,
  145580. 5
  145581. };
  145582. static static_codebook _44u0__p7_0 = {
  145583. 4, 625,
  145584. _vq_lengthlist__44u0__p7_0,
  145585. 1, -518709248, 1626677248, 3, 0,
  145586. _vq_quantlist__44u0__p7_0,
  145587. NULL,
  145588. &_vq_auxt__44u0__p7_0,
  145589. NULL,
  145590. 0
  145591. };
  145592. static long _vq_quantlist__44u0__p7_1[] = {
  145593. 6,
  145594. 5,
  145595. 7,
  145596. 4,
  145597. 8,
  145598. 3,
  145599. 9,
  145600. 2,
  145601. 10,
  145602. 1,
  145603. 11,
  145604. 0,
  145605. 12,
  145606. };
  145607. static long _vq_lengthlist__44u0__p7_1[] = {
  145608. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  145609. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  145610. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  145611. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  145612. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  145613. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  145614. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  145615. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  145616. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  145617. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  145618. 15,15,15,15,15,15,15,15,15,
  145619. };
  145620. static float _vq_quantthresh__44u0__p7_1[] = {
  145621. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  145622. 32.5, 45.5, 58.5, 71.5,
  145623. };
  145624. static long _vq_quantmap__44u0__p7_1[] = {
  145625. 11, 9, 7, 5, 3, 1, 0, 2,
  145626. 4, 6, 8, 10, 12,
  145627. };
  145628. static encode_aux_threshmatch _vq_auxt__44u0__p7_1 = {
  145629. _vq_quantthresh__44u0__p7_1,
  145630. _vq_quantmap__44u0__p7_1,
  145631. 13,
  145632. 13
  145633. };
  145634. static static_codebook _44u0__p7_1 = {
  145635. 2, 169,
  145636. _vq_lengthlist__44u0__p7_1,
  145637. 1, -523010048, 1618608128, 4, 0,
  145638. _vq_quantlist__44u0__p7_1,
  145639. NULL,
  145640. &_vq_auxt__44u0__p7_1,
  145641. NULL,
  145642. 0
  145643. };
  145644. static long _vq_quantlist__44u0__p7_2[] = {
  145645. 6,
  145646. 5,
  145647. 7,
  145648. 4,
  145649. 8,
  145650. 3,
  145651. 9,
  145652. 2,
  145653. 10,
  145654. 1,
  145655. 11,
  145656. 0,
  145657. 12,
  145658. };
  145659. static long _vq_lengthlist__44u0__p7_2[] = {
  145660. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  145661. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  145662. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  145663. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  145664. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  145665. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  145666. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  145667. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  145668. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  145669. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  145670. 9, 9, 9,10, 9, 9,10,10, 9,
  145671. };
  145672. static float _vq_quantthresh__44u0__p7_2[] = {
  145673. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  145674. 2.5, 3.5, 4.5, 5.5,
  145675. };
  145676. static long _vq_quantmap__44u0__p7_2[] = {
  145677. 11, 9, 7, 5, 3, 1, 0, 2,
  145678. 4, 6, 8, 10, 12,
  145679. };
  145680. static encode_aux_threshmatch _vq_auxt__44u0__p7_2 = {
  145681. _vq_quantthresh__44u0__p7_2,
  145682. _vq_quantmap__44u0__p7_2,
  145683. 13,
  145684. 13
  145685. };
  145686. static static_codebook _44u0__p7_2 = {
  145687. 2, 169,
  145688. _vq_lengthlist__44u0__p7_2,
  145689. 1, -531103744, 1611661312, 4, 0,
  145690. _vq_quantlist__44u0__p7_2,
  145691. NULL,
  145692. &_vq_auxt__44u0__p7_2,
  145693. NULL,
  145694. 0
  145695. };
  145696. static long _huff_lengthlist__44u0__short[] = {
  145697. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  145698. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  145699. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  145700. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  145701. };
  145702. static static_codebook _huff_book__44u0__short = {
  145703. 2, 64,
  145704. _huff_lengthlist__44u0__short,
  145705. 0, 0, 0, 0, 0,
  145706. NULL,
  145707. NULL,
  145708. NULL,
  145709. NULL,
  145710. 0
  145711. };
  145712. static long _huff_lengthlist__44u1__long[] = {
  145713. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  145714. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  145715. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  145716. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  145717. };
  145718. static static_codebook _huff_book__44u1__long = {
  145719. 2, 64,
  145720. _huff_lengthlist__44u1__long,
  145721. 0, 0, 0, 0, 0,
  145722. NULL,
  145723. NULL,
  145724. NULL,
  145725. NULL,
  145726. 0
  145727. };
  145728. static long _vq_quantlist__44u1__p1_0[] = {
  145729. 1,
  145730. 0,
  145731. 2,
  145732. };
  145733. static long _vq_lengthlist__44u1__p1_0[] = {
  145734. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  145735. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  145736. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  145737. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  145738. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  145739. 13,
  145740. };
  145741. static float _vq_quantthresh__44u1__p1_0[] = {
  145742. -0.5, 0.5,
  145743. };
  145744. static long _vq_quantmap__44u1__p1_0[] = {
  145745. 1, 0, 2,
  145746. };
  145747. static encode_aux_threshmatch _vq_auxt__44u1__p1_0 = {
  145748. _vq_quantthresh__44u1__p1_0,
  145749. _vq_quantmap__44u1__p1_0,
  145750. 3,
  145751. 3
  145752. };
  145753. static static_codebook _44u1__p1_0 = {
  145754. 4, 81,
  145755. _vq_lengthlist__44u1__p1_0,
  145756. 1, -535822336, 1611661312, 2, 0,
  145757. _vq_quantlist__44u1__p1_0,
  145758. NULL,
  145759. &_vq_auxt__44u1__p1_0,
  145760. NULL,
  145761. 0
  145762. };
  145763. static long _vq_quantlist__44u1__p2_0[] = {
  145764. 1,
  145765. 0,
  145766. 2,
  145767. };
  145768. static long _vq_lengthlist__44u1__p2_0[] = {
  145769. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  145770. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  145771. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  145772. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  145773. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  145774. 9,
  145775. };
  145776. static float _vq_quantthresh__44u1__p2_0[] = {
  145777. -0.5, 0.5,
  145778. };
  145779. static long _vq_quantmap__44u1__p2_0[] = {
  145780. 1, 0, 2,
  145781. };
  145782. static encode_aux_threshmatch _vq_auxt__44u1__p2_0 = {
  145783. _vq_quantthresh__44u1__p2_0,
  145784. _vq_quantmap__44u1__p2_0,
  145785. 3,
  145786. 3
  145787. };
  145788. static static_codebook _44u1__p2_0 = {
  145789. 4, 81,
  145790. _vq_lengthlist__44u1__p2_0,
  145791. 1, -535822336, 1611661312, 2, 0,
  145792. _vq_quantlist__44u1__p2_0,
  145793. NULL,
  145794. &_vq_auxt__44u1__p2_0,
  145795. NULL,
  145796. 0
  145797. };
  145798. static long _vq_quantlist__44u1__p3_0[] = {
  145799. 2,
  145800. 1,
  145801. 3,
  145802. 0,
  145803. 4,
  145804. };
  145805. static long _vq_lengthlist__44u1__p3_0[] = {
  145806. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  145807. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  145808. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  145809. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  145810. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  145811. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  145812. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  145813. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  145814. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  145815. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  145816. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  145817. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  145818. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  145819. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  145820. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  145821. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  145822. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  145823. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  145824. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  145825. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  145826. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  145827. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  145828. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  145829. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  145830. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  145831. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  145832. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  145833. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  145834. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  145835. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  145836. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  145837. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  145838. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  145839. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  145840. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  145841. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  145842. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  145843. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  145844. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  145845. 19,
  145846. };
  145847. static float _vq_quantthresh__44u1__p3_0[] = {
  145848. -1.5, -0.5, 0.5, 1.5,
  145849. };
  145850. static long _vq_quantmap__44u1__p3_0[] = {
  145851. 3, 1, 0, 2, 4,
  145852. };
  145853. static encode_aux_threshmatch _vq_auxt__44u1__p3_0 = {
  145854. _vq_quantthresh__44u1__p3_0,
  145855. _vq_quantmap__44u1__p3_0,
  145856. 5,
  145857. 5
  145858. };
  145859. static static_codebook _44u1__p3_0 = {
  145860. 4, 625,
  145861. _vq_lengthlist__44u1__p3_0,
  145862. 1, -533725184, 1611661312, 3, 0,
  145863. _vq_quantlist__44u1__p3_0,
  145864. NULL,
  145865. &_vq_auxt__44u1__p3_0,
  145866. NULL,
  145867. 0
  145868. };
  145869. static long _vq_quantlist__44u1__p4_0[] = {
  145870. 2,
  145871. 1,
  145872. 3,
  145873. 0,
  145874. 4,
  145875. };
  145876. static long _vq_lengthlist__44u1__p4_0[] = {
  145877. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  145878. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  145879. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  145880. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  145881. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  145882. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  145883. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  145884. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  145885. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  145886. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  145887. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  145888. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  145889. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  145890. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  145891. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  145892. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  145893. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  145894. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  145895. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  145896. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  145897. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  145898. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  145899. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  145900. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  145901. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  145902. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  145903. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  145904. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  145905. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  145906. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  145907. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  145908. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  145909. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  145910. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  145911. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  145912. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  145913. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  145914. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  145915. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  145916. 12,
  145917. };
  145918. static float _vq_quantthresh__44u1__p4_0[] = {
  145919. -1.5, -0.5, 0.5, 1.5,
  145920. };
  145921. static long _vq_quantmap__44u1__p4_0[] = {
  145922. 3, 1, 0, 2, 4,
  145923. };
  145924. static encode_aux_threshmatch _vq_auxt__44u1__p4_0 = {
  145925. _vq_quantthresh__44u1__p4_0,
  145926. _vq_quantmap__44u1__p4_0,
  145927. 5,
  145928. 5
  145929. };
  145930. static static_codebook _44u1__p4_0 = {
  145931. 4, 625,
  145932. _vq_lengthlist__44u1__p4_0,
  145933. 1, -533725184, 1611661312, 3, 0,
  145934. _vq_quantlist__44u1__p4_0,
  145935. NULL,
  145936. &_vq_auxt__44u1__p4_0,
  145937. NULL,
  145938. 0
  145939. };
  145940. static long _vq_quantlist__44u1__p5_0[] = {
  145941. 4,
  145942. 3,
  145943. 5,
  145944. 2,
  145945. 6,
  145946. 1,
  145947. 7,
  145948. 0,
  145949. 8,
  145950. };
  145951. static long _vq_lengthlist__44u1__p5_0[] = {
  145952. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  145953. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  145954. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  145955. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  145956. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  145957. 12,
  145958. };
  145959. static float _vq_quantthresh__44u1__p5_0[] = {
  145960. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145961. };
  145962. static long _vq_quantmap__44u1__p5_0[] = {
  145963. 7, 5, 3, 1, 0, 2, 4, 6,
  145964. 8,
  145965. };
  145966. static encode_aux_threshmatch _vq_auxt__44u1__p5_0 = {
  145967. _vq_quantthresh__44u1__p5_0,
  145968. _vq_quantmap__44u1__p5_0,
  145969. 9,
  145970. 9
  145971. };
  145972. static static_codebook _44u1__p5_0 = {
  145973. 2, 81,
  145974. _vq_lengthlist__44u1__p5_0,
  145975. 1, -531628032, 1611661312, 4, 0,
  145976. _vq_quantlist__44u1__p5_0,
  145977. NULL,
  145978. &_vq_auxt__44u1__p5_0,
  145979. NULL,
  145980. 0
  145981. };
  145982. static long _vq_quantlist__44u1__p6_0[] = {
  145983. 6,
  145984. 5,
  145985. 7,
  145986. 4,
  145987. 8,
  145988. 3,
  145989. 9,
  145990. 2,
  145991. 10,
  145992. 1,
  145993. 11,
  145994. 0,
  145995. 12,
  145996. };
  145997. static long _vq_lengthlist__44u1__p6_0[] = {
  145998. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  145999. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  146000. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  146001. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  146002. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  146003. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  146004. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  146005. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  146006. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  146007. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  146008. 15,17,16,17,18,17,17,18, 0,
  146009. };
  146010. static float _vq_quantthresh__44u1__p6_0[] = {
  146011. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  146012. 12.5, 17.5, 22.5, 27.5,
  146013. };
  146014. static long _vq_quantmap__44u1__p6_0[] = {
  146015. 11, 9, 7, 5, 3, 1, 0, 2,
  146016. 4, 6, 8, 10, 12,
  146017. };
  146018. static encode_aux_threshmatch _vq_auxt__44u1__p6_0 = {
  146019. _vq_quantthresh__44u1__p6_0,
  146020. _vq_quantmap__44u1__p6_0,
  146021. 13,
  146022. 13
  146023. };
  146024. static static_codebook _44u1__p6_0 = {
  146025. 2, 169,
  146026. _vq_lengthlist__44u1__p6_0,
  146027. 1, -526516224, 1616117760, 4, 0,
  146028. _vq_quantlist__44u1__p6_0,
  146029. NULL,
  146030. &_vq_auxt__44u1__p6_0,
  146031. NULL,
  146032. 0
  146033. };
  146034. static long _vq_quantlist__44u1__p6_1[] = {
  146035. 2,
  146036. 1,
  146037. 3,
  146038. 0,
  146039. 4,
  146040. };
  146041. static long _vq_lengthlist__44u1__p6_1[] = {
  146042. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  146043. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  146044. };
  146045. static float _vq_quantthresh__44u1__p6_1[] = {
  146046. -1.5, -0.5, 0.5, 1.5,
  146047. };
  146048. static long _vq_quantmap__44u1__p6_1[] = {
  146049. 3, 1, 0, 2, 4,
  146050. };
  146051. static encode_aux_threshmatch _vq_auxt__44u1__p6_1 = {
  146052. _vq_quantthresh__44u1__p6_1,
  146053. _vq_quantmap__44u1__p6_1,
  146054. 5,
  146055. 5
  146056. };
  146057. static static_codebook _44u1__p6_1 = {
  146058. 2, 25,
  146059. _vq_lengthlist__44u1__p6_1,
  146060. 1, -533725184, 1611661312, 3, 0,
  146061. _vq_quantlist__44u1__p6_1,
  146062. NULL,
  146063. &_vq_auxt__44u1__p6_1,
  146064. NULL,
  146065. 0
  146066. };
  146067. static long _vq_quantlist__44u1__p7_0[] = {
  146068. 3,
  146069. 2,
  146070. 4,
  146071. 1,
  146072. 5,
  146073. 0,
  146074. 6,
  146075. };
  146076. static long _vq_lengthlist__44u1__p7_0[] = {
  146077. 1, 3, 2, 9, 9, 7, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146078. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146079. 9, 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  146080. 8,
  146081. };
  146082. static float _vq_quantthresh__44u1__p7_0[] = {
  146083. -422.5, -253.5, -84.5, 84.5, 253.5, 422.5,
  146084. };
  146085. static long _vq_quantmap__44u1__p7_0[] = {
  146086. 5, 3, 1, 0, 2, 4, 6,
  146087. };
  146088. static encode_aux_threshmatch _vq_auxt__44u1__p7_0 = {
  146089. _vq_quantthresh__44u1__p7_0,
  146090. _vq_quantmap__44u1__p7_0,
  146091. 7,
  146092. 7
  146093. };
  146094. static static_codebook _44u1__p7_0 = {
  146095. 2, 49,
  146096. _vq_lengthlist__44u1__p7_0,
  146097. 1, -518017024, 1626677248, 3, 0,
  146098. _vq_quantlist__44u1__p7_0,
  146099. NULL,
  146100. &_vq_auxt__44u1__p7_0,
  146101. NULL,
  146102. 0
  146103. };
  146104. static long _vq_quantlist__44u1__p7_1[] = {
  146105. 6,
  146106. 5,
  146107. 7,
  146108. 4,
  146109. 8,
  146110. 3,
  146111. 9,
  146112. 2,
  146113. 10,
  146114. 1,
  146115. 11,
  146116. 0,
  146117. 12,
  146118. };
  146119. static long _vq_lengthlist__44u1__p7_1[] = {
  146120. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  146121. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  146122. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  146123. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  146124. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  146125. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  146126. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  146127. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  146128. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  146129. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  146130. 15,15,15,15,15,15,15,15,15,
  146131. };
  146132. static float _vq_quantthresh__44u1__p7_1[] = {
  146133. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  146134. 32.5, 45.5, 58.5, 71.5,
  146135. };
  146136. static long _vq_quantmap__44u1__p7_1[] = {
  146137. 11, 9, 7, 5, 3, 1, 0, 2,
  146138. 4, 6, 8, 10, 12,
  146139. };
  146140. static encode_aux_threshmatch _vq_auxt__44u1__p7_1 = {
  146141. _vq_quantthresh__44u1__p7_1,
  146142. _vq_quantmap__44u1__p7_1,
  146143. 13,
  146144. 13
  146145. };
  146146. static static_codebook _44u1__p7_1 = {
  146147. 2, 169,
  146148. _vq_lengthlist__44u1__p7_1,
  146149. 1, -523010048, 1618608128, 4, 0,
  146150. _vq_quantlist__44u1__p7_1,
  146151. NULL,
  146152. &_vq_auxt__44u1__p7_1,
  146153. NULL,
  146154. 0
  146155. };
  146156. static long _vq_quantlist__44u1__p7_2[] = {
  146157. 6,
  146158. 5,
  146159. 7,
  146160. 4,
  146161. 8,
  146162. 3,
  146163. 9,
  146164. 2,
  146165. 10,
  146166. 1,
  146167. 11,
  146168. 0,
  146169. 12,
  146170. };
  146171. static long _vq_lengthlist__44u1__p7_2[] = {
  146172. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  146173. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  146174. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  146175. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  146176. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  146177. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  146178. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  146179. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146180. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146181. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  146182. 9, 9, 9,10, 9, 9,10,10, 9,
  146183. };
  146184. static float _vq_quantthresh__44u1__p7_2[] = {
  146185. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  146186. 2.5, 3.5, 4.5, 5.5,
  146187. };
  146188. static long _vq_quantmap__44u1__p7_2[] = {
  146189. 11, 9, 7, 5, 3, 1, 0, 2,
  146190. 4, 6, 8, 10, 12,
  146191. };
  146192. static encode_aux_threshmatch _vq_auxt__44u1__p7_2 = {
  146193. _vq_quantthresh__44u1__p7_2,
  146194. _vq_quantmap__44u1__p7_2,
  146195. 13,
  146196. 13
  146197. };
  146198. static static_codebook _44u1__p7_2 = {
  146199. 2, 169,
  146200. _vq_lengthlist__44u1__p7_2,
  146201. 1, -531103744, 1611661312, 4, 0,
  146202. _vq_quantlist__44u1__p7_2,
  146203. NULL,
  146204. &_vq_auxt__44u1__p7_2,
  146205. NULL,
  146206. 0
  146207. };
  146208. static long _huff_lengthlist__44u1__short[] = {
  146209. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  146210. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  146211. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  146212. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  146213. };
  146214. static static_codebook _huff_book__44u1__short = {
  146215. 2, 64,
  146216. _huff_lengthlist__44u1__short,
  146217. 0, 0, 0, 0, 0,
  146218. NULL,
  146219. NULL,
  146220. NULL,
  146221. NULL,
  146222. 0
  146223. };
  146224. static long _huff_lengthlist__44u2__long[] = {
  146225. 5, 9,14,12,15,13,10,13, 7, 4, 5, 6, 8, 7, 8,12,
  146226. 13, 4, 3, 5, 5, 6, 9,15,12, 6, 5, 6, 6, 6, 7,14,
  146227. 14, 7, 4, 6, 4, 6, 8,15,12, 6, 6, 5, 5, 5, 6,14,
  146228. 9, 7, 8, 6, 7, 5, 4,10,10,13,14,14,15,10, 6, 8,
  146229. };
  146230. static static_codebook _huff_book__44u2__long = {
  146231. 2, 64,
  146232. _huff_lengthlist__44u2__long,
  146233. 0, 0, 0, 0, 0,
  146234. NULL,
  146235. NULL,
  146236. NULL,
  146237. NULL,
  146238. 0
  146239. };
  146240. static long _vq_quantlist__44u2__p1_0[] = {
  146241. 1,
  146242. 0,
  146243. 2,
  146244. };
  146245. static long _vq_lengthlist__44u2__p1_0[] = {
  146246. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  146247. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  146248. 11, 8,11,11, 8,11,11,11,13,14,11,13,13, 7,11,11,
  146249. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 8,
  146250. 11,11,11,14,13,10,12,13, 8,11,11,11,13,13,11,13,
  146251. 13,
  146252. };
  146253. static float _vq_quantthresh__44u2__p1_0[] = {
  146254. -0.5, 0.5,
  146255. };
  146256. static long _vq_quantmap__44u2__p1_0[] = {
  146257. 1, 0, 2,
  146258. };
  146259. static encode_aux_threshmatch _vq_auxt__44u2__p1_0 = {
  146260. _vq_quantthresh__44u2__p1_0,
  146261. _vq_quantmap__44u2__p1_0,
  146262. 3,
  146263. 3
  146264. };
  146265. static static_codebook _44u2__p1_0 = {
  146266. 4, 81,
  146267. _vq_lengthlist__44u2__p1_0,
  146268. 1, -535822336, 1611661312, 2, 0,
  146269. _vq_quantlist__44u2__p1_0,
  146270. NULL,
  146271. &_vq_auxt__44u2__p1_0,
  146272. NULL,
  146273. 0
  146274. };
  146275. static long _vq_quantlist__44u2__p2_0[] = {
  146276. 1,
  146277. 0,
  146278. 2,
  146279. };
  146280. static long _vq_lengthlist__44u2__p2_0[] = {
  146281. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  146282. 8, 8, 5, 6, 6, 6, 8, 7, 7, 8, 8, 5, 6, 6, 7, 8,
  146283. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  146284. 7,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  146285. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  146286. 9,
  146287. };
  146288. static float _vq_quantthresh__44u2__p2_0[] = {
  146289. -0.5, 0.5,
  146290. };
  146291. static long _vq_quantmap__44u2__p2_0[] = {
  146292. 1, 0, 2,
  146293. };
  146294. static encode_aux_threshmatch _vq_auxt__44u2__p2_0 = {
  146295. _vq_quantthresh__44u2__p2_0,
  146296. _vq_quantmap__44u2__p2_0,
  146297. 3,
  146298. 3
  146299. };
  146300. static static_codebook _44u2__p2_0 = {
  146301. 4, 81,
  146302. _vq_lengthlist__44u2__p2_0,
  146303. 1, -535822336, 1611661312, 2, 0,
  146304. _vq_quantlist__44u2__p2_0,
  146305. NULL,
  146306. &_vq_auxt__44u2__p2_0,
  146307. NULL,
  146308. 0
  146309. };
  146310. static long _vq_quantlist__44u2__p3_0[] = {
  146311. 2,
  146312. 1,
  146313. 3,
  146314. 0,
  146315. 4,
  146316. };
  146317. static long _vq_lengthlist__44u2__p3_0[] = {
  146318. 2, 4, 4, 7, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  146319. 9, 9,12,11, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  146320. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  146321. 12,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  146322. 11, 9,11,10,13,13,10,11,11,13,13, 8,10,10,14,13,
  146323. 10,11,11,15,14, 9,11,11,15,14,13,14,13,16,14,12,
  146324. 13,13,15,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  146325. 11,14,15,12,13,13,15,15,12,13,14,15,16, 5, 7, 7,
  146326. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  146327. 13,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  146328. 9,11,11,13,13,12,13,12,14,14,11,12,13,15,15, 7,
  146329. 9, 9,12,12, 8,11,10,13,12, 9,11,11,13,13,11,13,
  146330. 12,15,13,11,13,13,15,16, 9,12,11,15,15,11,12,12,
  146331. 16,15,11,12,13,16,16,13,14,15,16,15,13,15,15,17,
  146332. 17, 9,11,11,14,15,10,12,12,15,15,11,13,12,15,16,
  146333. 13,15,14,16,16,13,15,15,17,19, 5, 7, 7,10,10, 7,
  146334. 9, 9,12,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  146335. 11,13,14, 7, 9, 9,12,12, 9,11,11,13,13, 9,10,11,
  146336. 12,13,11,13,12,16,15,11,12,12,14,15, 7, 9, 9,12,
  146337. 12, 9,11,11,13,13, 9,11,11,13,12,11,13,12,15,16,
  146338. 12,13,13,15,14, 9,11,11,15,14,11,13,12,16,15,10,
  146339. 11,12,15,15,13,14,14,18,17,13,14,14,15,17,10,11,
  146340. 11,14,15,11,13,12,15,17,11,13,12,15,16,13,15,14,
  146341. 18,17,14,15,15,16,18, 7,10,10,14,14,10,12,12,15,
  146342. 15,10,12,12,15,15,14,15,15,18,17,13,15,15,16,16,
  146343. 9,11,11,16,15,11,13,13,16,18,11,13,13,16,16,15,
  146344. 16,16, 0, 0,14,15,16,18,17, 9,11,11,15,15,10,13,
  146345. 12,17,16,11,12,13,16,17,14,15,16,19,19,14,15,15,
  146346. 0,20,12,14,14, 0, 0,13,14,16,19,18,13,15,16,20,
  146347. 17,16,18, 0, 0, 0,15,16,17,18,19,11,14,14, 0,19,
  146348. 12,15,14,17,17,13,15,15, 0, 0,16,17,15,20,19,15,
  146349. 17,16,19, 0, 8,10,10,14,15,10,12,11,15,15,10,11,
  146350. 12,16,15,13,14,14,19,17,14,15,15, 0, 0, 9,11,11,
  146351. 16,15,11,13,13,17,16,10,12,13,16,17,14,15,15,18,
  146352. 18,14,15,16,20,19, 9,12,12, 0,15,11,13,13,16,17,
  146353. 11,13,13,19,17,14,16,16,18,17,15,16,16,17,19,11,
  146354. 14,14,18,18,13,14,15, 0, 0,12,14,15,19,18,15,16,
  146355. 19, 0,19,15,16,19,19,17,12,14,14,16,19,13,15,15,
  146356. 0,17,13,15,14,18,18,15,16,15, 0,18,16,17,17, 0,
  146357. 0,
  146358. };
  146359. static float _vq_quantthresh__44u2__p3_0[] = {
  146360. -1.5, -0.5, 0.5, 1.5,
  146361. };
  146362. static long _vq_quantmap__44u2__p3_0[] = {
  146363. 3, 1, 0, 2, 4,
  146364. };
  146365. static encode_aux_threshmatch _vq_auxt__44u2__p3_0 = {
  146366. _vq_quantthresh__44u2__p3_0,
  146367. _vq_quantmap__44u2__p3_0,
  146368. 5,
  146369. 5
  146370. };
  146371. static static_codebook _44u2__p3_0 = {
  146372. 4, 625,
  146373. _vq_lengthlist__44u2__p3_0,
  146374. 1, -533725184, 1611661312, 3, 0,
  146375. _vq_quantlist__44u2__p3_0,
  146376. NULL,
  146377. &_vq_auxt__44u2__p3_0,
  146378. NULL,
  146379. 0
  146380. };
  146381. static long _vq_quantlist__44u2__p4_0[] = {
  146382. 2,
  146383. 1,
  146384. 3,
  146385. 0,
  146386. 4,
  146387. };
  146388. static long _vq_lengthlist__44u2__p4_0[] = {
  146389. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  146390. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  146391. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  146392. 11,12, 5, 7, 7, 9, 9, 6, 8, 7,10,10, 7, 8, 8,10,
  146393. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10,10,12,12,
  146394. 10,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  146395. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,13,10,10,
  146396. 10,12,13,11,12,12,14,13,12,12,12,14,13, 5, 7, 7,
  146397. 10, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  146398. 12,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  146399. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,13,13, 6,
  146400. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  146401. 10,13,11,10,11,11,13,13, 9,10,10,13,13,10,11,11,
  146402. 13,13,10,11,11,14,13,12,11,13,12,15,12,13,13,15,
  146403. 15, 9,10,10,12,13,10,11,10,13,13,10,11,11,13,13,
  146404. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9,10, 7,
  146405. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  146406. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  146407. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  146408. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  146409. 10,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  146410. 10,11,13,13,12,13,13,15,15,12,11,13,12,14, 9,10,
  146411. 10,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  146412. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  146413. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  146414. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,12,13,
  146415. 13,14,14,16,12,13,13,15,14, 9,10,10,13,13,10,11,
  146416. 10,14,13,10,11,11,13,14,12,14,13,16,14,13,13,13,
  146417. 14,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  146418. 15,14,12,15,12,16,14,15,15,17,16,11,12,12,14,15,
  146419. 11,13,11,15,14,12,13,13,15,16,13,15,12,17,13,14,
  146420. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,13,13, 9,10,
  146421. 10,13,13,12,13,12,14,14,12,13,13,15,15, 9,10,10,
  146422. 13,13,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  146423. 14,12,12,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  146424. 10,11,11,14,13,13,13,13,15,15,13,14,13,16,14,11,
  146425. 12,12,14,14,12,13,13,16,15,11,12,13,14,15,14,15,
  146426. 15,16,16,14,13,15,13,17,11,12,12,14,15,12,13,13,
  146427. 15,16,11,13,12,15,15,14,15,14,16,16,14,15,12,17,
  146428. 13,
  146429. };
  146430. static float _vq_quantthresh__44u2__p4_0[] = {
  146431. -1.5, -0.5, 0.5, 1.5,
  146432. };
  146433. static long _vq_quantmap__44u2__p4_0[] = {
  146434. 3, 1, 0, 2, 4,
  146435. };
  146436. static encode_aux_threshmatch _vq_auxt__44u2__p4_0 = {
  146437. _vq_quantthresh__44u2__p4_0,
  146438. _vq_quantmap__44u2__p4_0,
  146439. 5,
  146440. 5
  146441. };
  146442. static static_codebook _44u2__p4_0 = {
  146443. 4, 625,
  146444. _vq_lengthlist__44u2__p4_0,
  146445. 1, -533725184, 1611661312, 3, 0,
  146446. _vq_quantlist__44u2__p4_0,
  146447. NULL,
  146448. &_vq_auxt__44u2__p4_0,
  146449. NULL,
  146450. 0
  146451. };
  146452. static long _vq_quantlist__44u2__p5_0[] = {
  146453. 4,
  146454. 3,
  146455. 5,
  146456. 2,
  146457. 6,
  146458. 1,
  146459. 7,
  146460. 0,
  146461. 8,
  146462. };
  146463. static long _vq_lengthlist__44u2__p5_0[] = {
  146464. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 8, 8, 8,
  146465. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  146466. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  146467. 9, 9,10,11,12,12, 8, 8, 8, 9, 9,10,10,12,12,10,
  146468. 10,10,11,11,12,12,13,13,10,10,10,11,11,12,12,13,
  146469. 13,
  146470. };
  146471. static float _vq_quantthresh__44u2__p5_0[] = {
  146472. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146473. };
  146474. static long _vq_quantmap__44u2__p5_0[] = {
  146475. 7, 5, 3, 1, 0, 2, 4, 6,
  146476. 8,
  146477. };
  146478. static encode_aux_threshmatch _vq_auxt__44u2__p5_0 = {
  146479. _vq_quantthresh__44u2__p5_0,
  146480. _vq_quantmap__44u2__p5_0,
  146481. 9,
  146482. 9
  146483. };
  146484. static static_codebook _44u2__p5_0 = {
  146485. 2, 81,
  146486. _vq_lengthlist__44u2__p5_0,
  146487. 1, -531628032, 1611661312, 4, 0,
  146488. _vq_quantlist__44u2__p5_0,
  146489. NULL,
  146490. &_vq_auxt__44u2__p5_0,
  146491. NULL,
  146492. 0
  146493. };
  146494. static long _vq_quantlist__44u2__p6_0[] = {
  146495. 6,
  146496. 5,
  146497. 7,
  146498. 4,
  146499. 8,
  146500. 3,
  146501. 9,
  146502. 2,
  146503. 10,
  146504. 1,
  146505. 11,
  146506. 0,
  146507. 12,
  146508. };
  146509. static long _vq_lengthlist__44u2__p6_0[] = {
  146510. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,14,13, 4, 6, 5,
  146511. 8, 8, 9, 9,11,10,12,11,15,14, 4, 5, 6, 8, 8, 9,
  146512. 9,11,11,11,11,14,14, 6, 8, 8,10, 9,11,11,11,11,
  146513. 12,12,15,15, 6, 8, 8, 9, 9,11,11,11,12,12,12,15,
  146514. 15, 8,10,10,11,11,11,11,12,12,13,13,15,16, 8,10,
  146515. 10,11,11,11,11,12,12,13,13,16,16,10,11,11,12,12,
  146516. 12,12,13,13,13,13,17,16,10,11,11,12,12,12,12,13,
  146517. 13,13,14,16,17,11,12,12,13,13,13,13,14,14,15,14,
  146518. 18,17,11,12,12,13,13,13,13,14,14,14,15,19,18,14,
  146519. 15,15,15,15,16,16,18,19,18,18, 0, 0,14,15,15,16,
  146520. 15,17,17,16,18,17,18, 0, 0,
  146521. };
  146522. static float _vq_quantthresh__44u2__p6_0[] = {
  146523. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  146524. 12.5, 17.5, 22.5, 27.5,
  146525. };
  146526. static long _vq_quantmap__44u2__p6_0[] = {
  146527. 11, 9, 7, 5, 3, 1, 0, 2,
  146528. 4, 6, 8, 10, 12,
  146529. };
  146530. static encode_aux_threshmatch _vq_auxt__44u2__p6_0 = {
  146531. _vq_quantthresh__44u2__p6_0,
  146532. _vq_quantmap__44u2__p6_0,
  146533. 13,
  146534. 13
  146535. };
  146536. static static_codebook _44u2__p6_0 = {
  146537. 2, 169,
  146538. _vq_lengthlist__44u2__p6_0,
  146539. 1, -526516224, 1616117760, 4, 0,
  146540. _vq_quantlist__44u2__p6_0,
  146541. NULL,
  146542. &_vq_auxt__44u2__p6_0,
  146543. NULL,
  146544. 0
  146545. };
  146546. static long _vq_quantlist__44u2__p6_1[] = {
  146547. 2,
  146548. 1,
  146549. 3,
  146550. 0,
  146551. 4,
  146552. };
  146553. static long _vq_lengthlist__44u2__p6_1[] = {
  146554. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  146555. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  146556. };
  146557. static float _vq_quantthresh__44u2__p6_1[] = {
  146558. -1.5, -0.5, 0.5, 1.5,
  146559. };
  146560. static long _vq_quantmap__44u2__p6_1[] = {
  146561. 3, 1, 0, 2, 4,
  146562. };
  146563. static encode_aux_threshmatch _vq_auxt__44u2__p6_1 = {
  146564. _vq_quantthresh__44u2__p6_1,
  146565. _vq_quantmap__44u2__p6_1,
  146566. 5,
  146567. 5
  146568. };
  146569. static static_codebook _44u2__p6_1 = {
  146570. 2, 25,
  146571. _vq_lengthlist__44u2__p6_1,
  146572. 1, -533725184, 1611661312, 3, 0,
  146573. _vq_quantlist__44u2__p6_1,
  146574. NULL,
  146575. &_vq_auxt__44u2__p6_1,
  146576. NULL,
  146577. 0
  146578. };
  146579. static long _vq_quantlist__44u2__p7_0[] = {
  146580. 4,
  146581. 3,
  146582. 5,
  146583. 2,
  146584. 6,
  146585. 1,
  146586. 7,
  146587. 0,
  146588. 8,
  146589. };
  146590. static long _vq_lengthlist__44u2__p7_0[] = {
  146591. 1, 3, 2,12,12,12,12,12,12, 4,12,12,12,12,12,12,
  146592. 12,12, 5,12,12,12,12,12,12,12,12,12,12,11,11,11,
  146593. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146594. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146595. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146596. 11,
  146597. };
  146598. static float _vq_quantthresh__44u2__p7_0[] = {
  146599. -591.5, -422.5, -253.5, -84.5, 84.5, 253.5, 422.5, 591.5,
  146600. };
  146601. static long _vq_quantmap__44u2__p7_0[] = {
  146602. 7, 5, 3, 1, 0, 2, 4, 6,
  146603. 8,
  146604. };
  146605. static encode_aux_threshmatch _vq_auxt__44u2__p7_0 = {
  146606. _vq_quantthresh__44u2__p7_0,
  146607. _vq_quantmap__44u2__p7_0,
  146608. 9,
  146609. 9
  146610. };
  146611. static static_codebook _44u2__p7_0 = {
  146612. 2, 81,
  146613. _vq_lengthlist__44u2__p7_0,
  146614. 1, -516612096, 1626677248, 4, 0,
  146615. _vq_quantlist__44u2__p7_0,
  146616. NULL,
  146617. &_vq_auxt__44u2__p7_0,
  146618. NULL,
  146619. 0
  146620. };
  146621. static long _vq_quantlist__44u2__p7_1[] = {
  146622. 6,
  146623. 5,
  146624. 7,
  146625. 4,
  146626. 8,
  146627. 3,
  146628. 9,
  146629. 2,
  146630. 10,
  146631. 1,
  146632. 11,
  146633. 0,
  146634. 12,
  146635. };
  146636. static long _vq_lengthlist__44u2__p7_1[] = {
  146637. 1, 4, 4, 7, 6, 7, 6, 8, 7, 9, 7, 9, 8, 4, 7, 6,
  146638. 8, 8, 9, 8,10, 9,10,10,11,11, 4, 7, 7, 8, 8, 8,
  146639. 8, 9,10,11,11,11,11, 6, 8, 8,10,10,10,10,11,11,
  146640. 12,12,12,12, 7, 8, 8,10,10,10,10,11,11,12,12,13,
  146641. 13, 7, 9, 9,11,10,12,12,13,13,14,13,14,14, 7, 9,
  146642. 9,10,11,11,12,13,13,13,13,16,14, 9,10,10,12,12,
  146643. 13,13,14,14,15,16,15,16, 9,10,10,12,12,12,13,14,
  146644. 14,14,15,16,15,10,12,12,13,13,15,13,16,16,15,17,
  146645. 17,17,10,11,11,12,14,14,14,15,15,17,17,15,17,11,
  146646. 12,12,14,14,14,15,15,15,17,16,17,17,10,12,12,13,
  146647. 14,14,14,17,15,17,17,17,17,
  146648. };
  146649. static float _vq_quantthresh__44u2__p7_1[] = {
  146650. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  146651. 32.5, 45.5, 58.5, 71.5,
  146652. };
  146653. static long _vq_quantmap__44u2__p7_1[] = {
  146654. 11, 9, 7, 5, 3, 1, 0, 2,
  146655. 4, 6, 8, 10, 12,
  146656. };
  146657. static encode_aux_threshmatch _vq_auxt__44u2__p7_1 = {
  146658. _vq_quantthresh__44u2__p7_1,
  146659. _vq_quantmap__44u2__p7_1,
  146660. 13,
  146661. 13
  146662. };
  146663. static static_codebook _44u2__p7_1 = {
  146664. 2, 169,
  146665. _vq_lengthlist__44u2__p7_1,
  146666. 1, -523010048, 1618608128, 4, 0,
  146667. _vq_quantlist__44u2__p7_1,
  146668. NULL,
  146669. &_vq_auxt__44u2__p7_1,
  146670. NULL,
  146671. 0
  146672. };
  146673. static long _vq_quantlist__44u2__p7_2[] = {
  146674. 6,
  146675. 5,
  146676. 7,
  146677. 4,
  146678. 8,
  146679. 3,
  146680. 9,
  146681. 2,
  146682. 10,
  146683. 1,
  146684. 11,
  146685. 0,
  146686. 12,
  146687. };
  146688. static long _vq_lengthlist__44u2__p7_2[] = {
  146689. 2, 5, 5, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 5, 6, 6,
  146690. 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 5, 6, 6, 7, 7, 8,
  146691. 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7, 8, 8, 8, 8, 8,
  146692. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  146693. 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 7, 8,
  146694. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 9,
  146695. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  146696. 9, 9, 9, 9, 9, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146697. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8,
  146698. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9,
  146699. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146700. };
  146701. static float _vq_quantthresh__44u2__p7_2[] = {
  146702. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  146703. 2.5, 3.5, 4.5, 5.5,
  146704. };
  146705. static long _vq_quantmap__44u2__p7_2[] = {
  146706. 11, 9, 7, 5, 3, 1, 0, 2,
  146707. 4, 6, 8, 10, 12,
  146708. };
  146709. static encode_aux_threshmatch _vq_auxt__44u2__p7_2 = {
  146710. _vq_quantthresh__44u2__p7_2,
  146711. _vq_quantmap__44u2__p7_2,
  146712. 13,
  146713. 13
  146714. };
  146715. static static_codebook _44u2__p7_2 = {
  146716. 2, 169,
  146717. _vq_lengthlist__44u2__p7_2,
  146718. 1, -531103744, 1611661312, 4, 0,
  146719. _vq_quantlist__44u2__p7_2,
  146720. NULL,
  146721. &_vq_auxt__44u2__p7_2,
  146722. NULL,
  146723. 0
  146724. };
  146725. static long _huff_lengthlist__44u2__short[] = {
  146726. 13,15,17,17,15,15,12,17,11, 9, 7,10,10, 9,12,17,
  146727. 10, 6, 3, 6, 5, 7,10,17,15,10, 6, 9, 8, 9,11,17,
  146728. 15, 8, 4, 7, 3, 5, 9,16,16,10, 5, 8, 4, 5, 8,16,
  146729. 13,11, 5, 8, 3, 3, 5,14,13,12, 7,10, 5, 5, 7,14,
  146730. };
  146731. static static_codebook _huff_book__44u2__short = {
  146732. 2, 64,
  146733. _huff_lengthlist__44u2__short,
  146734. 0, 0, 0, 0, 0,
  146735. NULL,
  146736. NULL,
  146737. NULL,
  146738. NULL,
  146739. 0
  146740. };
  146741. static long _huff_lengthlist__44u3__long[] = {
  146742. 6, 9,13,12,14,11,10,13, 8, 4, 5, 7, 8, 7, 8,12,
  146743. 11, 4, 3, 5, 5, 7, 9,14,11, 6, 5, 6, 6, 6, 7,13,
  146744. 13, 7, 5, 6, 4, 5, 7,14,11, 7, 6, 6, 5, 5, 6,13,
  146745. 9, 7, 8, 6, 7, 5, 3, 9, 9,12,13,12,14,10, 6, 7,
  146746. };
  146747. static static_codebook _huff_book__44u3__long = {
  146748. 2, 64,
  146749. _huff_lengthlist__44u3__long,
  146750. 0, 0, 0, 0, 0,
  146751. NULL,
  146752. NULL,
  146753. NULL,
  146754. NULL,
  146755. 0
  146756. };
  146757. static long _vq_quantlist__44u3__p1_0[] = {
  146758. 1,
  146759. 0,
  146760. 2,
  146761. };
  146762. static long _vq_lengthlist__44u3__p1_0[] = {
  146763. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  146764. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  146765. 11, 8,11,11, 8,11,11,11,13,14,11,14,14, 8,11,11,
  146766. 10,14,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  146767. 11,11,11,14,14,10,12,14, 8,11,11,11,14,14,11,14,
  146768. 13,
  146769. };
  146770. static float _vq_quantthresh__44u3__p1_0[] = {
  146771. -0.5, 0.5,
  146772. };
  146773. static long _vq_quantmap__44u3__p1_0[] = {
  146774. 1, 0, 2,
  146775. };
  146776. static encode_aux_threshmatch _vq_auxt__44u3__p1_0 = {
  146777. _vq_quantthresh__44u3__p1_0,
  146778. _vq_quantmap__44u3__p1_0,
  146779. 3,
  146780. 3
  146781. };
  146782. static static_codebook _44u3__p1_0 = {
  146783. 4, 81,
  146784. _vq_lengthlist__44u3__p1_0,
  146785. 1, -535822336, 1611661312, 2, 0,
  146786. _vq_quantlist__44u3__p1_0,
  146787. NULL,
  146788. &_vq_auxt__44u3__p1_0,
  146789. NULL,
  146790. 0
  146791. };
  146792. static long _vq_quantlist__44u3__p2_0[] = {
  146793. 1,
  146794. 0,
  146795. 2,
  146796. };
  146797. static long _vq_lengthlist__44u3__p2_0[] = {
  146798. 2, 5, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  146799. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 7, 8,
  146800. 8, 6, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  146801. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  146802. 8, 8, 8,10,10, 8, 8,10, 7, 8, 8, 8,10,10, 8,10,
  146803. 9,
  146804. };
  146805. static float _vq_quantthresh__44u3__p2_0[] = {
  146806. -0.5, 0.5,
  146807. };
  146808. static long _vq_quantmap__44u3__p2_0[] = {
  146809. 1, 0, 2,
  146810. };
  146811. static encode_aux_threshmatch _vq_auxt__44u3__p2_0 = {
  146812. _vq_quantthresh__44u3__p2_0,
  146813. _vq_quantmap__44u3__p2_0,
  146814. 3,
  146815. 3
  146816. };
  146817. static static_codebook _44u3__p2_0 = {
  146818. 4, 81,
  146819. _vq_lengthlist__44u3__p2_0,
  146820. 1, -535822336, 1611661312, 2, 0,
  146821. _vq_quantlist__44u3__p2_0,
  146822. NULL,
  146823. &_vq_auxt__44u3__p2_0,
  146824. NULL,
  146825. 0
  146826. };
  146827. static long _vq_quantlist__44u3__p3_0[] = {
  146828. 2,
  146829. 1,
  146830. 3,
  146831. 0,
  146832. 4,
  146833. };
  146834. static long _vq_lengthlist__44u3__p3_0[] = {
  146835. 2, 4, 4, 7, 7, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  146836. 9, 9,12,12, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  146837. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  146838. 13,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  146839. 11, 9,11,10,13,13,10,11,11,14,13, 8,10,10,14,13,
  146840. 10,11,11,15,14, 9,11,11,14,14,13,14,13,16,16,12,
  146841. 13,13,15,15, 8,10,10,13,14, 9,11,11,14,14,10,11,
  146842. 11,14,15,12,13,13,15,15,13,14,14,15,16, 5, 7, 7,
  146843. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  146844. 14,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  146845. 9,11,11,13,13,12,12,13,15,15,11,12,13,15,16, 7,
  146846. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  146847. 12,15,13,11,13,13,15,16, 9,12,11,15,14,11,12,13,
  146848. 16,15,11,13,13,15,16,14,14,15,17,16,13,15,16, 0,
  146849. 17, 9,11,11,15,15,10,13,12,15,15,11,13,13,15,16,
  146850. 13,15,13,16,15,14,16,15, 0,19, 5, 7, 7,10,10, 7,
  146851. 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,14,10,11,
  146852. 12,14,14, 7, 9, 9,12,12, 9,11,11,14,13, 9,10,11,
  146853. 12,13,11,13,13,16,16,11,12,13,13,16, 7, 9, 9,12,
  146854. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,15,
  146855. 12,13,12,15,14, 9,11,11,15,14,11,13,12,16,16,10,
  146856. 12,12,15,15,13,15,15,17,19,13,14,15,16,17,10,12,
  146857. 12,15,15,11,13,13,16,16,11,13,13,15,16,13,15,15,
  146858. 0, 0,14,15,15,16,16, 8,10,10,14,14,10,12,12,15,
  146859. 15,10,12,11,15,16,14,15,15,19,20,13,14,14,18,16,
  146860. 9,11,11,15,15,11,13,13,17,16,11,13,13,16,16,15,
  146861. 17,17,20,20,14,15,16,17,20, 9,11,11,15,15,10,13,
  146862. 12,16,15,11,13,13,15,17,14,16,15,18, 0,14,16,15,
  146863. 18,20,12,14,14, 0, 0,14,14,16, 0, 0,13,16,15, 0,
  146864. 0,17,17,18, 0, 0,16,17,19,19, 0,12,14,14,18, 0,
  146865. 12,16,14, 0,17,13,15,15,18, 0,16,18,17, 0,17,16,
  146866. 18,17, 0, 0, 7,10,10,14,14,10,12,11,15,15,10,12,
  146867. 12,16,15,13,15,15,18, 0,14,15,15,17, 0, 9,11,11,
  146868. 15,15,11,13,13,16,16,11,12,13,16,16,14,15,16,17,
  146869. 17,14,16,16,16,18, 9,11,12,16,16,11,13,13,17,17,
  146870. 11,14,13,20,17,15,16,16,19, 0,15,16,17, 0,19,11,
  146871. 13,14,17,16,14,15,15,20,18,13,14,15,17,19,16,18,
  146872. 18, 0,20,16,16,19,17, 0,12,15,14,17, 0,14,15,15,
  146873. 18,19,13,16,15,19,20,15,18,18, 0,20,17, 0,16, 0,
  146874. 0,
  146875. };
  146876. static float _vq_quantthresh__44u3__p3_0[] = {
  146877. -1.5, -0.5, 0.5, 1.5,
  146878. };
  146879. static long _vq_quantmap__44u3__p3_0[] = {
  146880. 3, 1, 0, 2, 4,
  146881. };
  146882. static encode_aux_threshmatch _vq_auxt__44u3__p3_0 = {
  146883. _vq_quantthresh__44u3__p3_0,
  146884. _vq_quantmap__44u3__p3_0,
  146885. 5,
  146886. 5
  146887. };
  146888. static static_codebook _44u3__p3_0 = {
  146889. 4, 625,
  146890. _vq_lengthlist__44u3__p3_0,
  146891. 1, -533725184, 1611661312, 3, 0,
  146892. _vq_quantlist__44u3__p3_0,
  146893. NULL,
  146894. &_vq_auxt__44u3__p3_0,
  146895. NULL,
  146896. 0
  146897. };
  146898. static long _vq_quantlist__44u3__p4_0[] = {
  146899. 2,
  146900. 1,
  146901. 3,
  146902. 0,
  146903. 4,
  146904. };
  146905. static long _vq_lengthlist__44u3__p4_0[] = {
  146906. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  146907. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  146908. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  146909. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  146910. 10, 9,10, 9,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  146911. 9,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  146912. 12,12,13,14, 9, 9,10,12,12, 9,10,10,12,12, 9,10,
  146913. 10,12,13,11,12,11,14,13,12,12,12,14,13, 5, 7, 7,
  146914. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  146915. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  146916. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  146917. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  146918. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  146919. 13,13,10,11,11,13,13,12,12,13,12,15,12,13,13,15,
  146920. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  146921. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  146922. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  146923. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  146924. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  146925. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  146926. 11,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  146927. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  146928. 11,12,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  146929. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  146930. 13, 9,10,10,13,13,12,13,13,15,14,12,12,12,14,13,
  146931. 9,10,10,13,12,10,11,11,13,13,10,11,11,14,12,13,
  146932. 13,14,14,16,12,13,13,15,15, 9,10,10,13,13,10,11,
  146933. 10,14,13,10,11,11,13,14,12,14,13,15,14,13,13,13,
  146934. 15,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  146935. 14,14,12,15,12,16,14,15,15,17,15,11,12,12,14,14,
  146936. 11,13,11,15,14,12,13,13,15,15,13,15,12,17,13,14,
  146937. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  146938. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  146939. 13,12,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  146940. 15,12,12,13,14,16, 9,10,10,13,13,10,11,11,13,14,
  146941. 10,11,11,14,13,12,13,13,14,15,13,14,13,16,14,11,
  146942. 12,12,14,14,12,13,13,15,14,11,12,13,14,15,14,15,
  146943. 15,16,16,13,13,15,13,16,11,12,12,14,15,12,13,13,
  146944. 14,15,11,13,12,15,14,14,15,15,16,16,14,15,12,16,
  146945. 13,
  146946. };
  146947. static float _vq_quantthresh__44u3__p4_0[] = {
  146948. -1.5, -0.5, 0.5, 1.5,
  146949. };
  146950. static long _vq_quantmap__44u3__p4_0[] = {
  146951. 3, 1, 0, 2, 4,
  146952. };
  146953. static encode_aux_threshmatch _vq_auxt__44u3__p4_0 = {
  146954. _vq_quantthresh__44u3__p4_0,
  146955. _vq_quantmap__44u3__p4_0,
  146956. 5,
  146957. 5
  146958. };
  146959. static static_codebook _44u3__p4_0 = {
  146960. 4, 625,
  146961. _vq_lengthlist__44u3__p4_0,
  146962. 1, -533725184, 1611661312, 3, 0,
  146963. _vq_quantlist__44u3__p4_0,
  146964. NULL,
  146965. &_vq_auxt__44u3__p4_0,
  146966. NULL,
  146967. 0
  146968. };
  146969. static long _vq_quantlist__44u3__p5_0[] = {
  146970. 4,
  146971. 3,
  146972. 5,
  146973. 2,
  146974. 6,
  146975. 1,
  146976. 7,
  146977. 0,
  146978. 8,
  146979. };
  146980. static long _vq_lengthlist__44u3__p5_0[] = {
  146981. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  146982. 10,10, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  146983. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,10, 7, 8, 8,
  146984. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  146985. 10,10,11,10,11,11,12,12, 9,10,10,10,10,11,11,12,
  146986. 12,
  146987. };
  146988. static float _vq_quantthresh__44u3__p5_0[] = {
  146989. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146990. };
  146991. static long _vq_quantmap__44u3__p5_0[] = {
  146992. 7, 5, 3, 1, 0, 2, 4, 6,
  146993. 8,
  146994. };
  146995. static encode_aux_threshmatch _vq_auxt__44u3__p5_0 = {
  146996. _vq_quantthresh__44u3__p5_0,
  146997. _vq_quantmap__44u3__p5_0,
  146998. 9,
  146999. 9
  147000. };
  147001. static static_codebook _44u3__p5_0 = {
  147002. 2, 81,
  147003. _vq_lengthlist__44u3__p5_0,
  147004. 1, -531628032, 1611661312, 4, 0,
  147005. _vq_quantlist__44u3__p5_0,
  147006. NULL,
  147007. &_vq_auxt__44u3__p5_0,
  147008. NULL,
  147009. 0
  147010. };
  147011. static long _vq_quantlist__44u3__p6_0[] = {
  147012. 6,
  147013. 5,
  147014. 7,
  147015. 4,
  147016. 8,
  147017. 3,
  147018. 9,
  147019. 2,
  147020. 10,
  147021. 1,
  147022. 11,
  147023. 0,
  147024. 12,
  147025. };
  147026. static long _vq_lengthlist__44u3__p6_0[] = {
  147027. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,13,14, 4, 6, 5,
  147028. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  147029. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  147030. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  147031. 15, 8, 9, 9,11,10,11,11,12,12,13,13,15,16, 8, 9,
  147032. 9,10,11,11,11,12,12,13,13,16,16,10,10,11,11,11,
  147033. 12,12,13,13,13,14,17,16, 9,10,11,12,11,12,12,13,
  147034. 13,13,13,16,18,11,12,11,12,12,13,13,13,14,15,14,
  147035. 17,17,11,11,12,12,12,13,13,13,14,14,15,18,17,14,
  147036. 15,15,15,15,16,16,17,17,19,18, 0,20,14,15,14,15,
  147037. 15,16,16,16,17,18,16,20,18,
  147038. };
  147039. static float _vq_quantthresh__44u3__p6_0[] = {
  147040. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147041. 12.5, 17.5, 22.5, 27.5,
  147042. };
  147043. static long _vq_quantmap__44u3__p6_0[] = {
  147044. 11, 9, 7, 5, 3, 1, 0, 2,
  147045. 4, 6, 8, 10, 12,
  147046. };
  147047. static encode_aux_threshmatch _vq_auxt__44u3__p6_0 = {
  147048. _vq_quantthresh__44u3__p6_0,
  147049. _vq_quantmap__44u3__p6_0,
  147050. 13,
  147051. 13
  147052. };
  147053. static static_codebook _44u3__p6_0 = {
  147054. 2, 169,
  147055. _vq_lengthlist__44u3__p6_0,
  147056. 1, -526516224, 1616117760, 4, 0,
  147057. _vq_quantlist__44u3__p6_0,
  147058. NULL,
  147059. &_vq_auxt__44u3__p6_0,
  147060. NULL,
  147061. 0
  147062. };
  147063. static long _vq_quantlist__44u3__p6_1[] = {
  147064. 2,
  147065. 1,
  147066. 3,
  147067. 0,
  147068. 4,
  147069. };
  147070. static long _vq_lengthlist__44u3__p6_1[] = {
  147071. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  147072. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  147073. };
  147074. static float _vq_quantthresh__44u3__p6_1[] = {
  147075. -1.5, -0.5, 0.5, 1.5,
  147076. };
  147077. static long _vq_quantmap__44u3__p6_1[] = {
  147078. 3, 1, 0, 2, 4,
  147079. };
  147080. static encode_aux_threshmatch _vq_auxt__44u3__p6_1 = {
  147081. _vq_quantthresh__44u3__p6_1,
  147082. _vq_quantmap__44u3__p6_1,
  147083. 5,
  147084. 5
  147085. };
  147086. static static_codebook _44u3__p6_1 = {
  147087. 2, 25,
  147088. _vq_lengthlist__44u3__p6_1,
  147089. 1, -533725184, 1611661312, 3, 0,
  147090. _vq_quantlist__44u3__p6_1,
  147091. NULL,
  147092. &_vq_auxt__44u3__p6_1,
  147093. NULL,
  147094. 0
  147095. };
  147096. static long _vq_quantlist__44u3__p7_0[] = {
  147097. 4,
  147098. 3,
  147099. 5,
  147100. 2,
  147101. 6,
  147102. 1,
  147103. 7,
  147104. 0,
  147105. 8,
  147106. };
  147107. static long _vq_lengthlist__44u3__p7_0[] = {
  147108. 1, 3, 3,10,10,10,10,10,10, 4,10,10,10,10,10,10,
  147109. 10,10, 4,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  147110. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147111. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147112. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147113. 9,
  147114. };
  147115. static float _vq_quantthresh__44u3__p7_0[] = {
  147116. -892.5, -637.5, -382.5, -127.5, 127.5, 382.5, 637.5, 892.5,
  147117. };
  147118. static long _vq_quantmap__44u3__p7_0[] = {
  147119. 7, 5, 3, 1, 0, 2, 4, 6,
  147120. 8,
  147121. };
  147122. static encode_aux_threshmatch _vq_auxt__44u3__p7_0 = {
  147123. _vq_quantthresh__44u3__p7_0,
  147124. _vq_quantmap__44u3__p7_0,
  147125. 9,
  147126. 9
  147127. };
  147128. static static_codebook _44u3__p7_0 = {
  147129. 2, 81,
  147130. _vq_lengthlist__44u3__p7_0,
  147131. 1, -515907584, 1627381760, 4, 0,
  147132. _vq_quantlist__44u3__p7_0,
  147133. NULL,
  147134. &_vq_auxt__44u3__p7_0,
  147135. NULL,
  147136. 0
  147137. };
  147138. static long _vq_quantlist__44u3__p7_1[] = {
  147139. 7,
  147140. 6,
  147141. 8,
  147142. 5,
  147143. 9,
  147144. 4,
  147145. 10,
  147146. 3,
  147147. 11,
  147148. 2,
  147149. 12,
  147150. 1,
  147151. 13,
  147152. 0,
  147153. 14,
  147154. };
  147155. static long _vq_lengthlist__44u3__p7_1[] = {
  147156. 1, 4, 4, 6, 6, 7, 6, 8, 7, 9, 8,10, 9,11,11, 4,
  147157. 7, 7, 8, 7, 9, 9,10,10,11,11,11,11,12,12, 4, 7,
  147158. 7, 7, 7, 9, 9,10,10,11,11,12,12,12,11, 6, 8, 8,
  147159. 9, 9,10,10,11,11,12,12,13,12,13,13, 6, 8, 8, 9,
  147160. 9,10,11,11,11,12,12,13,14,13,13, 8, 9, 9,11,11,
  147161. 12,12,12,13,14,13,14,14,14,15, 8, 9, 9,11,11,11,
  147162. 12,13,14,13,14,15,17,14,15, 9,10,10,12,12,13,13,
  147163. 13,14,15,15,15,16,16,16, 9,11,11,12,12,13,13,14,
  147164. 14,14,15,16,16,16,16,10,12,12,13,13,14,14,15,15,
  147165. 15,16,17,17,17,17,10,12,11,13,13,15,14,15,14,16,
  147166. 17,16,16,16,16,11,13,12,14,14,14,14,15,16,17,16,
  147167. 17,17,17,17,11,13,12,14,14,14,15,17,16,17,17,17,
  147168. 17,17,17,12,13,13,15,16,15,16,17,17,16,16,17,17,
  147169. 17,17,12,13,13,15,15,15,16,17,17,17,16,17,16,17,
  147170. 17,
  147171. };
  147172. static float _vq_quantthresh__44u3__p7_1[] = {
  147173. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  147174. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  147175. };
  147176. static long _vq_quantmap__44u3__p7_1[] = {
  147177. 13, 11, 9, 7, 5, 3, 1, 0,
  147178. 2, 4, 6, 8, 10, 12, 14,
  147179. };
  147180. static encode_aux_threshmatch _vq_auxt__44u3__p7_1 = {
  147181. _vq_quantthresh__44u3__p7_1,
  147182. _vq_quantmap__44u3__p7_1,
  147183. 15,
  147184. 15
  147185. };
  147186. static static_codebook _44u3__p7_1 = {
  147187. 2, 225,
  147188. _vq_lengthlist__44u3__p7_1,
  147189. 1, -522338304, 1620115456, 4, 0,
  147190. _vq_quantlist__44u3__p7_1,
  147191. NULL,
  147192. &_vq_auxt__44u3__p7_1,
  147193. NULL,
  147194. 0
  147195. };
  147196. static long _vq_quantlist__44u3__p7_2[] = {
  147197. 8,
  147198. 7,
  147199. 9,
  147200. 6,
  147201. 10,
  147202. 5,
  147203. 11,
  147204. 4,
  147205. 12,
  147206. 3,
  147207. 13,
  147208. 2,
  147209. 14,
  147210. 1,
  147211. 15,
  147212. 0,
  147213. 16,
  147214. };
  147215. static long _vq_lengthlist__44u3__p7_2[] = {
  147216. 2, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  147217. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  147218. 10,10, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  147219. 9,10, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  147220. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  147221. 9,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  147222. 10,10,10,10,10,10, 7, 8, 8, 9, 8, 9, 9, 9, 9,10,
  147223. 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  147224. 9,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9,10,
  147225. 9,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  147226. 9,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  147227. 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,
  147228. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10,
  147229. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  147230. 10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,10,
  147231. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,
  147232. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  147233. 9,10,10,10,10,10,10,10,10,10,10,10,11,11,11,10,
  147234. 11,
  147235. };
  147236. static float _vq_quantthresh__44u3__p7_2[] = {
  147237. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  147238. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  147239. };
  147240. static long _vq_quantmap__44u3__p7_2[] = {
  147241. 15, 13, 11, 9, 7, 5, 3, 1,
  147242. 0, 2, 4, 6, 8, 10, 12, 14,
  147243. 16,
  147244. };
  147245. static encode_aux_threshmatch _vq_auxt__44u3__p7_2 = {
  147246. _vq_quantthresh__44u3__p7_2,
  147247. _vq_quantmap__44u3__p7_2,
  147248. 17,
  147249. 17
  147250. };
  147251. static static_codebook _44u3__p7_2 = {
  147252. 2, 289,
  147253. _vq_lengthlist__44u3__p7_2,
  147254. 1, -529530880, 1611661312, 5, 0,
  147255. _vq_quantlist__44u3__p7_2,
  147256. NULL,
  147257. &_vq_auxt__44u3__p7_2,
  147258. NULL,
  147259. 0
  147260. };
  147261. static long _huff_lengthlist__44u3__short[] = {
  147262. 14,14,14,15,13,15,12,16,10, 8, 7, 9, 9, 8,12,16,
  147263. 10, 5, 4, 6, 5, 6, 9,16,14, 8, 6, 8, 7, 8,10,16,
  147264. 14, 7, 4, 6, 3, 5, 8,16,15, 9, 5, 7, 4, 4, 7,16,
  147265. 13,10, 6, 7, 4, 3, 4,13,13,12, 7, 9, 5, 5, 6,12,
  147266. };
  147267. static static_codebook _huff_book__44u3__short = {
  147268. 2, 64,
  147269. _huff_lengthlist__44u3__short,
  147270. 0, 0, 0, 0, 0,
  147271. NULL,
  147272. NULL,
  147273. NULL,
  147274. NULL,
  147275. 0
  147276. };
  147277. static long _huff_lengthlist__44u4__long[] = {
  147278. 3, 8,12,12,13,12,11,13, 5, 4, 6, 7, 8, 8, 9,13,
  147279. 9, 5, 4, 5, 5, 7, 9,13, 9, 6, 5, 6, 6, 7, 8,12,
  147280. 12, 7, 5, 6, 4, 5, 8,13,11, 7, 6, 6, 5, 5, 6,12,
  147281. 10, 8, 8, 7, 7, 5, 3, 8,10,12,13,12,12, 9, 6, 7,
  147282. };
  147283. static static_codebook _huff_book__44u4__long = {
  147284. 2, 64,
  147285. _huff_lengthlist__44u4__long,
  147286. 0, 0, 0, 0, 0,
  147287. NULL,
  147288. NULL,
  147289. NULL,
  147290. NULL,
  147291. 0
  147292. };
  147293. static long _vq_quantlist__44u4__p1_0[] = {
  147294. 1,
  147295. 0,
  147296. 2,
  147297. };
  147298. static long _vq_lengthlist__44u4__p1_0[] = {
  147299. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  147300. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  147301. 11, 8,11,11, 8,11,11,11,13,14,11,15,14, 8,11,11,
  147302. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  147303. 11,11,11,15,14,10,12,14, 8,11,11,11,14,14,11,14,
  147304. 13,
  147305. };
  147306. static float _vq_quantthresh__44u4__p1_0[] = {
  147307. -0.5, 0.5,
  147308. };
  147309. static long _vq_quantmap__44u4__p1_0[] = {
  147310. 1, 0, 2,
  147311. };
  147312. static encode_aux_threshmatch _vq_auxt__44u4__p1_0 = {
  147313. _vq_quantthresh__44u4__p1_0,
  147314. _vq_quantmap__44u4__p1_0,
  147315. 3,
  147316. 3
  147317. };
  147318. static static_codebook _44u4__p1_0 = {
  147319. 4, 81,
  147320. _vq_lengthlist__44u4__p1_0,
  147321. 1, -535822336, 1611661312, 2, 0,
  147322. _vq_quantlist__44u4__p1_0,
  147323. NULL,
  147324. &_vq_auxt__44u4__p1_0,
  147325. NULL,
  147326. 0
  147327. };
  147328. static long _vq_quantlist__44u4__p2_0[] = {
  147329. 1,
  147330. 0,
  147331. 2,
  147332. };
  147333. static long _vq_lengthlist__44u4__p2_0[] = {
  147334. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  147335. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 6, 8,
  147336. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  147337. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 6, 8, 8, 6,
  147338. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  147339. 9,
  147340. };
  147341. static float _vq_quantthresh__44u4__p2_0[] = {
  147342. -0.5, 0.5,
  147343. };
  147344. static long _vq_quantmap__44u4__p2_0[] = {
  147345. 1, 0, 2,
  147346. };
  147347. static encode_aux_threshmatch _vq_auxt__44u4__p2_0 = {
  147348. _vq_quantthresh__44u4__p2_0,
  147349. _vq_quantmap__44u4__p2_0,
  147350. 3,
  147351. 3
  147352. };
  147353. static static_codebook _44u4__p2_0 = {
  147354. 4, 81,
  147355. _vq_lengthlist__44u4__p2_0,
  147356. 1, -535822336, 1611661312, 2, 0,
  147357. _vq_quantlist__44u4__p2_0,
  147358. NULL,
  147359. &_vq_auxt__44u4__p2_0,
  147360. NULL,
  147361. 0
  147362. };
  147363. static long _vq_quantlist__44u4__p3_0[] = {
  147364. 2,
  147365. 1,
  147366. 3,
  147367. 0,
  147368. 4,
  147369. };
  147370. static long _vq_lengthlist__44u4__p3_0[] = {
  147371. 2, 4, 4, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  147372. 10, 9,12,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  147373. 9,11,11, 7, 9, 9,11,11,10,12,11,14,14, 9,10,11,
  147374. 13,14, 5, 7, 7,10,10, 7, 9, 9,11,11, 7, 9, 9,11,
  147375. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  147376. 10,12,12,15,14, 9,11,11,15,14,13,14,14,17,17,12,
  147377. 14,14,16,16, 8,10,10,14,14, 9,11,11,14,15,10,12,
  147378. 12,14,15,12,14,13,16,16,13,14,15,15,18, 4, 7, 7,
  147379. 10,10, 7, 9, 9,12,11, 7, 9, 9,11,12,10,12,11,15,
  147380. 14,10,11,12,14,15, 7, 9, 9,12,12, 9,11,12,13,13,
  147381. 9,11,12,13,13,12,13,13,15,16,11,13,13,15,16, 7,
  147382. 9, 9,12,12, 9,11,10,13,12, 9,11,12,13,14,11,13,
  147383. 12,16,14,12,13,13,15,16,10,12,12,16,15,11,13,13,
  147384. 17,16,11,13,13,17,16,14,15,15,17,17,14,16,16,18,
  147385. 20, 9,11,11,15,16,11,13,12,16,16,11,13,13,16,17,
  147386. 14,15,14,18,16,14,16,16,17,20, 5, 7, 7,10,10, 7,
  147387. 9, 9,12,11, 7, 9,10,11,12,10,12,11,15,15,10,12,
  147388. 12,14,14, 7, 9, 9,12,12, 9,12,11,14,13, 9,10,11,
  147389. 12,13,12,13,14,16,16,11,12,13,14,16, 7, 9, 9,12,
  147390. 12, 9,12,11,13,13, 9,12,11,13,13,11,13,13,16,16,
  147391. 12,13,13,16,15, 9,11,11,16,14,11,13,13,16,16,11,
  147392. 12,13,16,16,14,16,16,17,17,13,14,15,16,17,10,12,
  147393. 12,15,15,11,13,13,16,17,11,13,13,16,16,14,16,15,
  147394. 19,19,14,15,15,17,18, 8,10,10,14,14,10,12,12,15,
  147395. 15,10,12,12,16,16,14,16,15,20,19,13,15,15,17,16,
  147396. 9,12,12,16,16,11,13,13,16,18,11,14,13,16,17,16,
  147397. 17,16,20, 0,15,16,18,18,20, 9,11,11,15,15,11,14,
  147398. 12,17,16,11,13,13,17,17,15,17,15,20,20,14,16,16,
  147399. 17, 0,13,15,14,18,16,14,15,16, 0,18,14,16,16, 0,
  147400. 0,18,16, 0, 0,20,16,18,18, 0, 0,12,14,14,17,18,
  147401. 13,15,14,20,18,14,16,15,19,19,16,20,16, 0,18,16,
  147402. 19,17,19, 0, 8,10,10,14,14,10,12,12,16,15,10,12,
  147403. 12,16,16,13,15,15,18,17,14,16,16,19, 0, 9,11,11,
  147404. 16,15,11,14,13,18,17,11,12,13,17,18,14,17,16,18,
  147405. 18,15,16,17,18,18, 9,12,12,16,16,11,13,13,16,18,
  147406. 11,14,13,17,17,15,16,16,18,20,16,17,17,20,20,12,
  147407. 14,14,18,17,14,16,16, 0,19,13,14,15,18, 0,16, 0,
  147408. 0, 0, 0,16,16, 0,19,20,13,15,14, 0, 0,14,16,16,
  147409. 18,19,14,16,15, 0,20,16,20,18, 0,20,17,20,17, 0,
  147410. 0,
  147411. };
  147412. static float _vq_quantthresh__44u4__p3_0[] = {
  147413. -1.5, -0.5, 0.5, 1.5,
  147414. };
  147415. static long _vq_quantmap__44u4__p3_0[] = {
  147416. 3, 1, 0, 2, 4,
  147417. };
  147418. static encode_aux_threshmatch _vq_auxt__44u4__p3_0 = {
  147419. _vq_quantthresh__44u4__p3_0,
  147420. _vq_quantmap__44u4__p3_0,
  147421. 5,
  147422. 5
  147423. };
  147424. static static_codebook _44u4__p3_0 = {
  147425. 4, 625,
  147426. _vq_lengthlist__44u4__p3_0,
  147427. 1, -533725184, 1611661312, 3, 0,
  147428. _vq_quantlist__44u4__p3_0,
  147429. NULL,
  147430. &_vq_auxt__44u4__p3_0,
  147431. NULL,
  147432. 0
  147433. };
  147434. static long _vq_quantlist__44u4__p4_0[] = {
  147435. 2,
  147436. 1,
  147437. 3,
  147438. 0,
  147439. 4,
  147440. };
  147441. static long _vq_lengthlist__44u4__p4_0[] = {
  147442. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  147443. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  147444. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  147445. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  147446. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  147447. 9,10,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  147448. 12,12,13,14, 9, 9,10,12,12, 9,10,10,13,13, 9,10,
  147449. 10,12,13,11,12,12,14,13,11,12,12,14,14, 5, 7, 7,
  147450. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  147451. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  147452. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  147453. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  147454. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  147455. 13,14,10,11,11,14,13,12,12,13,12,15,12,13,13,15,
  147456. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  147457. 12,13,11,15,13,13,13,13,15,15, 5, 7, 7, 9, 9, 7,
  147458. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  147459. 11,12,13, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  147460. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  147461. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  147462. 11,12,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  147463. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  147464. 11,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  147465. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  147466. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  147467. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,13,13,
  147468. 13,14,14,16,13,13,13,15,15, 9,10,10,13,13,10,11,
  147469. 10,14,13,10,11,11,13,14,12,14,13,16,14,12,13,13,
  147470. 14,15,11,12,12,15,14,11,12,13,14,15,12,13,13,16,
  147471. 15,14,12,15,12,16,14,15,15,16,16,11,12,12,14,14,
  147472. 11,13,12,15,14,12,13,13,15,16,13,15,13,17,13,14,
  147473. 15,15,16,17, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  147474. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  147475. 13,12,10,11,11,14,13,10,10,11,13,14,13,13,13,15,
  147476. 15,12,13,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  147477. 10,11,11,14,14,13,13,13,15,15,13,14,13,16,14,11,
  147478. 12,12,15,14,12,13,13,16,15,11,12,13,14,15,14,15,
  147479. 15,17,16,13,13,15,13,16,11,12,13,14,15,13,13,13,
  147480. 15,16,11,13,12,15,14,14,15,15,16,16,14,15,12,17,
  147481. 13,
  147482. };
  147483. static float _vq_quantthresh__44u4__p4_0[] = {
  147484. -1.5, -0.5, 0.5, 1.5,
  147485. };
  147486. static long _vq_quantmap__44u4__p4_0[] = {
  147487. 3, 1, 0, 2, 4,
  147488. };
  147489. static encode_aux_threshmatch _vq_auxt__44u4__p4_0 = {
  147490. _vq_quantthresh__44u4__p4_0,
  147491. _vq_quantmap__44u4__p4_0,
  147492. 5,
  147493. 5
  147494. };
  147495. static static_codebook _44u4__p4_0 = {
  147496. 4, 625,
  147497. _vq_lengthlist__44u4__p4_0,
  147498. 1, -533725184, 1611661312, 3, 0,
  147499. _vq_quantlist__44u4__p4_0,
  147500. NULL,
  147501. &_vq_auxt__44u4__p4_0,
  147502. NULL,
  147503. 0
  147504. };
  147505. static long _vq_quantlist__44u4__p5_0[] = {
  147506. 4,
  147507. 3,
  147508. 5,
  147509. 2,
  147510. 6,
  147511. 1,
  147512. 7,
  147513. 0,
  147514. 8,
  147515. };
  147516. static long _vq_lengthlist__44u4__p5_0[] = {
  147517. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  147518. 10, 9, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  147519. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,11, 7, 8, 8,
  147520. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  147521. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  147522. 12,
  147523. };
  147524. static float _vq_quantthresh__44u4__p5_0[] = {
  147525. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147526. };
  147527. static long _vq_quantmap__44u4__p5_0[] = {
  147528. 7, 5, 3, 1, 0, 2, 4, 6,
  147529. 8,
  147530. };
  147531. static encode_aux_threshmatch _vq_auxt__44u4__p5_0 = {
  147532. _vq_quantthresh__44u4__p5_0,
  147533. _vq_quantmap__44u4__p5_0,
  147534. 9,
  147535. 9
  147536. };
  147537. static static_codebook _44u4__p5_0 = {
  147538. 2, 81,
  147539. _vq_lengthlist__44u4__p5_0,
  147540. 1, -531628032, 1611661312, 4, 0,
  147541. _vq_quantlist__44u4__p5_0,
  147542. NULL,
  147543. &_vq_auxt__44u4__p5_0,
  147544. NULL,
  147545. 0
  147546. };
  147547. static long _vq_quantlist__44u4__p6_0[] = {
  147548. 6,
  147549. 5,
  147550. 7,
  147551. 4,
  147552. 8,
  147553. 3,
  147554. 9,
  147555. 2,
  147556. 10,
  147557. 1,
  147558. 11,
  147559. 0,
  147560. 12,
  147561. };
  147562. static long _vq_lengthlist__44u4__p6_0[] = {
  147563. 1, 4, 4, 6, 6, 8, 8, 9, 9,11,10,13,13, 4, 6, 5,
  147564. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  147565. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  147566. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  147567. 15, 8, 9, 9,11,10,11,11,12,12,13,13,16,16, 8, 9,
  147568. 9,10,10,11,11,12,12,13,13,16,16,10,10,10,12,11,
  147569. 12,12,13,13,14,14,16,16,10,10,10,11,12,12,12,13,
  147570. 13,13,14,16,17,11,12,11,12,12,13,13,14,14,15,14,
  147571. 18,17,11,11,12,12,12,13,13,14,14,14,15,19,18,14,
  147572. 15,14,15,15,17,16,17,17,17,17,21, 0,14,15,15,16,
  147573. 16,16,16,17,17,18,17,20,21,
  147574. };
  147575. static float _vq_quantthresh__44u4__p6_0[] = {
  147576. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147577. 12.5, 17.5, 22.5, 27.5,
  147578. };
  147579. static long _vq_quantmap__44u4__p6_0[] = {
  147580. 11, 9, 7, 5, 3, 1, 0, 2,
  147581. 4, 6, 8, 10, 12,
  147582. };
  147583. static encode_aux_threshmatch _vq_auxt__44u4__p6_0 = {
  147584. _vq_quantthresh__44u4__p6_0,
  147585. _vq_quantmap__44u4__p6_0,
  147586. 13,
  147587. 13
  147588. };
  147589. static static_codebook _44u4__p6_0 = {
  147590. 2, 169,
  147591. _vq_lengthlist__44u4__p6_0,
  147592. 1, -526516224, 1616117760, 4, 0,
  147593. _vq_quantlist__44u4__p6_0,
  147594. NULL,
  147595. &_vq_auxt__44u4__p6_0,
  147596. NULL,
  147597. 0
  147598. };
  147599. static long _vq_quantlist__44u4__p6_1[] = {
  147600. 2,
  147601. 1,
  147602. 3,
  147603. 0,
  147604. 4,
  147605. };
  147606. static long _vq_lengthlist__44u4__p6_1[] = {
  147607. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  147608. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  147609. };
  147610. static float _vq_quantthresh__44u4__p6_1[] = {
  147611. -1.5, -0.5, 0.5, 1.5,
  147612. };
  147613. static long _vq_quantmap__44u4__p6_1[] = {
  147614. 3, 1, 0, 2, 4,
  147615. };
  147616. static encode_aux_threshmatch _vq_auxt__44u4__p6_1 = {
  147617. _vq_quantthresh__44u4__p6_1,
  147618. _vq_quantmap__44u4__p6_1,
  147619. 5,
  147620. 5
  147621. };
  147622. static static_codebook _44u4__p6_1 = {
  147623. 2, 25,
  147624. _vq_lengthlist__44u4__p6_1,
  147625. 1, -533725184, 1611661312, 3, 0,
  147626. _vq_quantlist__44u4__p6_1,
  147627. NULL,
  147628. &_vq_auxt__44u4__p6_1,
  147629. NULL,
  147630. 0
  147631. };
  147632. static long _vq_quantlist__44u4__p7_0[] = {
  147633. 6,
  147634. 5,
  147635. 7,
  147636. 4,
  147637. 8,
  147638. 3,
  147639. 9,
  147640. 2,
  147641. 10,
  147642. 1,
  147643. 11,
  147644. 0,
  147645. 12,
  147646. };
  147647. static long _vq_lengthlist__44u4__p7_0[] = {
  147648. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 3,12,11,
  147649. 12,12,12,12,12,12,12,12,12,12, 4,11,10,12,12,12,
  147650. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  147651. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  147652. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  147653. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147654. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147655. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147656. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147657. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147658. 11,11,11,11,11,11,11,11,11,
  147659. };
  147660. static float _vq_quantthresh__44u4__p7_0[] = {
  147661. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  147662. 637.5, 892.5, 1147.5, 1402.5,
  147663. };
  147664. static long _vq_quantmap__44u4__p7_0[] = {
  147665. 11, 9, 7, 5, 3, 1, 0, 2,
  147666. 4, 6, 8, 10, 12,
  147667. };
  147668. static encode_aux_threshmatch _vq_auxt__44u4__p7_0 = {
  147669. _vq_quantthresh__44u4__p7_0,
  147670. _vq_quantmap__44u4__p7_0,
  147671. 13,
  147672. 13
  147673. };
  147674. static static_codebook _44u4__p7_0 = {
  147675. 2, 169,
  147676. _vq_lengthlist__44u4__p7_0,
  147677. 1, -514332672, 1627381760, 4, 0,
  147678. _vq_quantlist__44u4__p7_0,
  147679. NULL,
  147680. &_vq_auxt__44u4__p7_0,
  147681. NULL,
  147682. 0
  147683. };
  147684. static long _vq_quantlist__44u4__p7_1[] = {
  147685. 7,
  147686. 6,
  147687. 8,
  147688. 5,
  147689. 9,
  147690. 4,
  147691. 10,
  147692. 3,
  147693. 11,
  147694. 2,
  147695. 12,
  147696. 1,
  147697. 13,
  147698. 0,
  147699. 14,
  147700. };
  147701. static long _vq_lengthlist__44u4__p7_1[] = {
  147702. 1, 4, 4, 6, 6, 7, 7, 9, 8,10, 8,10, 9,11,11, 4,
  147703. 7, 6, 8, 7, 9, 9,10,10,11,10,11,10,12,10, 4, 6,
  147704. 7, 8, 8, 9, 9,10,10,11,11,11,11,12,12, 6, 8, 8,
  147705. 10, 9,11,10,12,11,12,12,12,12,13,13, 6, 8, 8,10,
  147706. 10,10,11,11,11,12,12,13,12,13,13, 8, 9, 9,11,11,
  147707. 12,11,12,12,13,13,13,13,13,13, 8, 9, 9,11,11,11,
  147708. 12,12,12,13,13,13,13,13,13, 9,10,10,12,11,13,13,
  147709. 13,13,14,13,13,14,14,14, 9,10,11,11,12,12,13,13,
  147710. 13,13,13,14,15,14,14,10,11,11,12,12,13,13,14,14,
  147711. 14,14,14,15,16,16,10,11,11,12,13,13,13,13,15,14,
  147712. 14,15,16,15,16,10,12,12,13,13,14,14,14,15,15,15,
  147713. 15,15,15,16,11,12,12,13,13,14,14,14,15,15,15,16,
  147714. 15,17,16,11,12,12,13,13,13,15,15,14,16,16,16,16,
  147715. 16,17,11,12,12,13,13,14,14,15,14,15,15,17,17,16,
  147716. 16,
  147717. };
  147718. static float _vq_quantthresh__44u4__p7_1[] = {
  147719. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  147720. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  147721. };
  147722. static long _vq_quantmap__44u4__p7_1[] = {
  147723. 13, 11, 9, 7, 5, 3, 1, 0,
  147724. 2, 4, 6, 8, 10, 12, 14,
  147725. };
  147726. static encode_aux_threshmatch _vq_auxt__44u4__p7_1 = {
  147727. _vq_quantthresh__44u4__p7_1,
  147728. _vq_quantmap__44u4__p7_1,
  147729. 15,
  147730. 15
  147731. };
  147732. static static_codebook _44u4__p7_1 = {
  147733. 2, 225,
  147734. _vq_lengthlist__44u4__p7_1,
  147735. 1, -522338304, 1620115456, 4, 0,
  147736. _vq_quantlist__44u4__p7_1,
  147737. NULL,
  147738. &_vq_auxt__44u4__p7_1,
  147739. NULL,
  147740. 0
  147741. };
  147742. static long _vq_quantlist__44u4__p7_2[] = {
  147743. 8,
  147744. 7,
  147745. 9,
  147746. 6,
  147747. 10,
  147748. 5,
  147749. 11,
  147750. 4,
  147751. 12,
  147752. 3,
  147753. 13,
  147754. 2,
  147755. 14,
  147756. 1,
  147757. 15,
  147758. 0,
  147759. 16,
  147760. };
  147761. static long _vq_lengthlist__44u4__p7_2[] = {
  147762. 2, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  147763. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  147764. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  147765. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  147766. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  147767. 9,10, 9,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  147768. 10,10,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  147769. 9,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  147770. 10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  147771. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,
  147772. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  147773. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  147774. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  147775. 10,10,10,10,10,10,10,10,10,11,10,10,10, 9, 9, 9,
  147776. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  147777. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  147778. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  147779. 9,10, 9,10,10,10,10,10,10,10,10,10,10,11,10,10,
  147780. 10,
  147781. };
  147782. static float _vq_quantthresh__44u4__p7_2[] = {
  147783. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  147784. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  147785. };
  147786. static long _vq_quantmap__44u4__p7_2[] = {
  147787. 15, 13, 11, 9, 7, 5, 3, 1,
  147788. 0, 2, 4, 6, 8, 10, 12, 14,
  147789. 16,
  147790. };
  147791. static encode_aux_threshmatch _vq_auxt__44u4__p7_2 = {
  147792. _vq_quantthresh__44u4__p7_2,
  147793. _vq_quantmap__44u4__p7_2,
  147794. 17,
  147795. 17
  147796. };
  147797. static static_codebook _44u4__p7_2 = {
  147798. 2, 289,
  147799. _vq_lengthlist__44u4__p7_2,
  147800. 1, -529530880, 1611661312, 5, 0,
  147801. _vq_quantlist__44u4__p7_2,
  147802. NULL,
  147803. &_vq_auxt__44u4__p7_2,
  147804. NULL,
  147805. 0
  147806. };
  147807. static long _huff_lengthlist__44u4__short[] = {
  147808. 14,17,15,17,16,14,13,16,10, 7, 7,10,13,10,15,16,
  147809. 9, 4, 4, 6, 5, 7, 9,16,12, 8, 7, 8, 8, 8,11,16,
  147810. 14, 7, 4, 6, 3, 5, 8,15,13, 8, 5, 7, 4, 5, 7,16,
  147811. 12, 9, 6, 8, 3, 3, 5,16,14,13, 7,10, 5, 5, 7,15,
  147812. };
  147813. static static_codebook _huff_book__44u4__short = {
  147814. 2, 64,
  147815. _huff_lengthlist__44u4__short,
  147816. 0, 0, 0, 0, 0,
  147817. NULL,
  147818. NULL,
  147819. NULL,
  147820. NULL,
  147821. 0
  147822. };
  147823. static long _huff_lengthlist__44u5__long[] = {
  147824. 3, 8,13,12,14,12,16,11,13,14, 5, 4, 5, 6, 7, 8,
  147825. 10, 9,12,15,10, 5, 5, 5, 6, 8, 9, 9,13,15,10, 5,
  147826. 5, 6, 6, 7, 8, 8,11,13,12, 7, 5, 6, 4, 6, 7, 7,
  147827. 11,14,11, 7, 7, 6, 6, 6, 7, 6,10,14,14, 9, 8, 8,
  147828. 6, 7, 7, 7,11,16,11, 8, 8, 7, 6, 6, 7, 4, 7,12,
  147829. 10,10,12,10,10, 9,10, 5, 6, 9,10,12,15,13,14,14,
  147830. 14, 8, 7, 8,
  147831. };
  147832. static static_codebook _huff_book__44u5__long = {
  147833. 2, 100,
  147834. _huff_lengthlist__44u5__long,
  147835. 0, 0, 0, 0, 0,
  147836. NULL,
  147837. NULL,
  147838. NULL,
  147839. NULL,
  147840. 0
  147841. };
  147842. static long _vq_quantlist__44u5__p1_0[] = {
  147843. 1,
  147844. 0,
  147845. 2,
  147846. };
  147847. static long _vq_lengthlist__44u5__p1_0[] = {
  147848. 1, 4, 4, 5, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  147849. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  147850. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  147851. 10,13,11,10,13,13, 4, 8, 8, 8,11,10, 8,10,10, 7,
  147852. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  147853. 12,
  147854. };
  147855. static float _vq_quantthresh__44u5__p1_0[] = {
  147856. -0.5, 0.5,
  147857. };
  147858. static long _vq_quantmap__44u5__p1_0[] = {
  147859. 1, 0, 2,
  147860. };
  147861. static encode_aux_threshmatch _vq_auxt__44u5__p1_0 = {
  147862. _vq_quantthresh__44u5__p1_0,
  147863. _vq_quantmap__44u5__p1_0,
  147864. 3,
  147865. 3
  147866. };
  147867. static static_codebook _44u5__p1_0 = {
  147868. 4, 81,
  147869. _vq_lengthlist__44u5__p1_0,
  147870. 1, -535822336, 1611661312, 2, 0,
  147871. _vq_quantlist__44u5__p1_0,
  147872. NULL,
  147873. &_vq_auxt__44u5__p1_0,
  147874. NULL,
  147875. 0
  147876. };
  147877. static long _vq_quantlist__44u5__p2_0[] = {
  147878. 1,
  147879. 0,
  147880. 2,
  147881. };
  147882. static long _vq_lengthlist__44u5__p2_0[] = {
  147883. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  147884. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  147885. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  147886. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  147887. 8, 7, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  147888. 9,
  147889. };
  147890. static float _vq_quantthresh__44u5__p2_0[] = {
  147891. -0.5, 0.5,
  147892. };
  147893. static long _vq_quantmap__44u5__p2_0[] = {
  147894. 1, 0, 2,
  147895. };
  147896. static encode_aux_threshmatch _vq_auxt__44u5__p2_0 = {
  147897. _vq_quantthresh__44u5__p2_0,
  147898. _vq_quantmap__44u5__p2_0,
  147899. 3,
  147900. 3
  147901. };
  147902. static static_codebook _44u5__p2_0 = {
  147903. 4, 81,
  147904. _vq_lengthlist__44u5__p2_0,
  147905. 1, -535822336, 1611661312, 2, 0,
  147906. _vq_quantlist__44u5__p2_0,
  147907. NULL,
  147908. &_vq_auxt__44u5__p2_0,
  147909. NULL,
  147910. 0
  147911. };
  147912. static long _vq_quantlist__44u5__p3_0[] = {
  147913. 2,
  147914. 1,
  147915. 3,
  147916. 0,
  147917. 4,
  147918. };
  147919. static long _vq_lengthlist__44u5__p3_0[] = {
  147920. 2, 4, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  147921. 10, 9,13,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  147922. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  147923. 13,14, 5, 7, 7, 9,10, 7, 9, 8,11,11, 7, 9, 9,11,
  147924. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,13,13,
  147925. 10,11,11,15,14, 9,11,11,14,14,13,14,14,17,16,12,
  147926. 13,13,15,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  147927. 11,14,15,12,14,13,16,16,13,15,14,15,17, 5, 7, 7,
  147928. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,
  147929. 14,10,11,12,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  147930. 9,11,11,13,13,12,13,13,15,16,11,12,13,15,16, 6,
  147931. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,14,11,13,
  147932. 12,16,14,11,13,13,16,17,10,12,11,15,15,11,13,13,
  147933. 16,16,11,13,13,17,16,14,15,15,17,17,14,16,16,17,
  147934. 18, 9,11,11,14,15,10,12,12,15,15,11,13,13,16,17,
  147935. 13,15,13,17,15,14,15,16,18, 0, 5, 7, 7,10,10, 7,
  147936. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  147937. 12,14,15, 6, 9, 9,12,11, 9,11,11,13,13, 8,10,11,
  147938. 12,13,11,13,13,16,15,11,12,13,14,15, 7, 9, 9,11,
  147939. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,16,
  147940. 11,13,13,15,14, 9,11,11,15,14,11,13,13,17,15,10,
  147941. 12,12,15,15,14,16,16,17,17,13,13,15,15,17,10,11,
  147942. 12,15,15,11,13,13,16,16,11,13,13,15,15,14,15,15,
  147943. 18,18,14,15,15,17,17, 8,10,10,13,13,10,12,11,15,
  147944. 15,10,11,12,15,15,14,15,15,18,18,13,14,14,18,18,
  147945. 9,11,11,15,16,11,13,13,17,17,11,13,13,16,16,15,
  147946. 15,16,17, 0,14,15,17, 0, 0, 9,11,11,15,15,10,13,
  147947. 12,18,16,11,13,13,15,16,14,16,15,20,20,14,15,16,
  147948. 17, 0,13,14,14,20,16,14,15,16,19,18,14,15,15,19,
  147949. 0,18,16, 0,20,20,16,18,18, 0, 0,12,14,14,18,18,
  147950. 13,15,14,18,16,14,15,16,18,20,16,19,16, 0,17,17,
  147951. 18,18,19, 0, 8,10,10,14,14,10,11,11,14,15,10,11,
  147952. 12,15,15,13,15,14,19,17,13,15,15,17, 0, 9,11,11,
  147953. 16,15,11,13,13,16,16,10,12,13,15,17,14,16,16,18,
  147954. 18,14,15,15,18, 0, 9,11,11,15,15,11,13,13,16,17,
  147955. 11,13,13,18,17,14,18,16,18,18,15,17,17,18, 0,12,
  147956. 14,14,18,18,14,15,15,20, 0,13,14,15,17, 0,16,18,
  147957. 17, 0, 0,16,16, 0,17,20,12,14,14,18,18,14,16,15,
  147958. 0,18,14,16,15,18, 0,16,19,17, 0, 0,17,18,16, 0,
  147959. 0,
  147960. };
  147961. static float _vq_quantthresh__44u5__p3_0[] = {
  147962. -1.5, -0.5, 0.5, 1.5,
  147963. };
  147964. static long _vq_quantmap__44u5__p3_0[] = {
  147965. 3, 1, 0, 2, 4,
  147966. };
  147967. static encode_aux_threshmatch _vq_auxt__44u5__p3_0 = {
  147968. _vq_quantthresh__44u5__p3_0,
  147969. _vq_quantmap__44u5__p3_0,
  147970. 5,
  147971. 5
  147972. };
  147973. static static_codebook _44u5__p3_0 = {
  147974. 4, 625,
  147975. _vq_lengthlist__44u5__p3_0,
  147976. 1, -533725184, 1611661312, 3, 0,
  147977. _vq_quantlist__44u5__p3_0,
  147978. NULL,
  147979. &_vq_auxt__44u5__p3_0,
  147980. NULL,
  147981. 0
  147982. };
  147983. static long _vq_quantlist__44u5__p4_0[] = {
  147984. 2,
  147985. 1,
  147986. 3,
  147987. 0,
  147988. 4,
  147989. };
  147990. static long _vq_lengthlist__44u5__p4_0[] = {
  147991. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  147992. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  147993. 8,10,10, 6, 7, 8, 9,10, 9,10,10,11,12, 9, 9,10,
  147994. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  147995. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,12,11,
  147996. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  147997. 11,12,13,14, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  147998. 10,12,12,11,12,11,14,13,11,12,12,13,13, 5, 7, 7,
  147999. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  148000. 12, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,10,11,
  148001. 8, 9, 9,11,11,10,10,11,11,13,10,11,11,12,13, 6,
  148002. 7, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  148003. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  148004. 12,13,10,11,11,13,13,12,11,13,12,15,12,13,13,14,
  148005. 15, 9,10,10,12,12, 9,11,10,13,12,10,11,11,13,13,
  148006. 11,13,11,14,12,12,13,13,14,15, 5, 7, 7, 9, 9, 7,
  148007. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  148008. 10,12,12, 6, 8, 7,10,10, 8, 9, 9,11,11, 7, 8, 9,
  148009. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  148010. 10, 8, 9, 9,11,11, 8, 9, 8,11,10,10,11,11,13,12,
  148011. 10,11,10,13,11, 9,10,10,12,12,10,11,11,13,12, 9,
  148012. 10,10,12,13,12,13,13,14,15,11,11,13,12,14, 9,10,
  148013. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,13,13,
  148014. 14,14,12,13,11,14,12, 8, 9, 9,12,12, 9,10,10,12,
  148015. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,14,13,
  148016. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  148017. 12,13,14,15,12,13,13,15,14, 9,10,10,12,12,10,11,
  148018. 10,13,12,10,11,11,12,13,12,13,12,15,13,12,13,13,
  148019. 14,15,11,12,12,14,13,11,12,12,14,15,12,13,13,15,
  148020. 14,13,12,14,12,16,13,14,14,15,15,11,11,12,14,14,
  148021. 11,12,11,14,13,12,13,13,14,15,13,14,12,16,12,14,
  148022. 14,15,16,16, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  148023. 10,12,13,11,12,12,13,13,12,12,13,14,14, 9,10,10,
  148024. 12,12,10,11,10,13,12,10,10,11,12,13,12,13,13,15,
  148025. 14,12,12,13,13,15, 9,10,10,12,13,10,11,11,12,13,
  148026. 10,11,11,13,13,12,13,13,14,15,12,13,12,15,14,11,
  148027. 12,11,14,13,12,13,13,15,14,11,11,12,13,14,14,15,
  148028. 14,16,15,13,12,14,13,16,11,12,12,13,14,12,13,13,
  148029. 14,15,11,12,11,14,14,14,14,14,15,16,13,15,12,16,
  148030. 12,
  148031. };
  148032. static float _vq_quantthresh__44u5__p4_0[] = {
  148033. -1.5, -0.5, 0.5, 1.5,
  148034. };
  148035. static long _vq_quantmap__44u5__p4_0[] = {
  148036. 3, 1, 0, 2, 4,
  148037. };
  148038. static encode_aux_threshmatch _vq_auxt__44u5__p4_0 = {
  148039. _vq_quantthresh__44u5__p4_0,
  148040. _vq_quantmap__44u5__p4_0,
  148041. 5,
  148042. 5
  148043. };
  148044. static static_codebook _44u5__p4_0 = {
  148045. 4, 625,
  148046. _vq_lengthlist__44u5__p4_0,
  148047. 1, -533725184, 1611661312, 3, 0,
  148048. _vq_quantlist__44u5__p4_0,
  148049. NULL,
  148050. &_vq_auxt__44u5__p4_0,
  148051. NULL,
  148052. 0
  148053. };
  148054. static long _vq_quantlist__44u5__p5_0[] = {
  148055. 4,
  148056. 3,
  148057. 5,
  148058. 2,
  148059. 6,
  148060. 1,
  148061. 7,
  148062. 0,
  148063. 8,
  148064. };
  148065. static long _vq_lengthlist__44u5__p5_0[] = {
  148066. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  148067. 11,10, 3, 5, 5, 7, 8, 8, 8,10,11, 6, 8, 7,10, 9,
  148068. 10,10,11,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  148069. 10,10,11,11,13,12, 8, 8, 9, 9,10,11,11,12,13,10,
  148070. 11,10,12,11,13,12,14,14,10,10,11,11,12,12,13,14,
  148071. 14,
  148072. };
  148073. static float _vq_quantthresh__44u5__p5_0[] = {
  148074. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148075. };
  148076. static long _vq_quantmap__44u5__p5_0[] = {
  148077. 7, 5, 3, 1, 0, 2, 4, 6,
  148078. 8,
  148079. };
  148080. static encode_aux_threshmatch _vq_auxt__44u5__p5_0 = {
  148081. _vq_quantthresh__44u5__p5_0,
  148082. _vq_quantmap__44u5__p5_0,
  148083. 9,
  148084. 9
  148085. };
  148086. static static_codebook _44u5__p5_0 = {
  148087. 2, 81,
  148088. _vq_lengthlist__44u5__p5_0,
  148089. 1, -531628032, 1611661312, 4, 0,
  148090. _vq_quantlist__44u5__p5_0,
  148091. NULL,
  148092. &_vq_auxt__44u5__p5_0,
  148093. NULL,
  148094. 0
  148095. };
  148096. static long _vq_quantlist__44u5__p6_0[] = {
  148097. 4,
  148098. 3,
  148099. 5,
  148100. 2,
  148101. 6,
  148102. 1,
  148103. 7,
  148104. 0,
  148105. 8,
  148106. };
  148107. static long _vq_lengthlist__44u5__p6_0[] = {
  148108. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  148109. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  148110. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  148111. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  148112. 9, 9,10,10,11,10,11,11, 9, 9, 9,10,10,11,10,11,
  148113. 11,
  148114. };
  148115. static float _vq_quantthresh__44u5__p6_0[] = {
  148116. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148117. };
  148118. static long _vq_quantmap__44u5__p6_0[] = {
  148119. 7, 5, 3, 1, 0, 2, 4, 6,
  148120. 8,
  148121. };
  148122. static encode_aux_threshmatch _vq_auxt__44u5__p6_0 = {
  148123. _vq_quantthresh__44u5__p6_0,
  148124. _vq_quantmap__44u5__p6_0,
  148125. 9,
  148126. 9
  148127. };
  148128. static static_codebook _44u5__p6_0 = {
  148129. 2, 81,
  148130. _vq_lengthlist__44u5__p6_0,
  148131. 1, -531628032, 1611661312, 4, 0,
  148132. _vq_quantlist__44u5__p6_0,
  148133. NULL,
  148134. &_vq_auxt__44u5__p6_0,
  148135. NULL,
  148136. 0
  148137. };
  148138. static long _vq_quantlist__44u5__p7_0[] = {
  148139. 1,
  148140. 0,
  148141. 2,
  148142. };
  148143. static long _vq_lengthlist__44u5__p7_0[] = {
  148144. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,11,10, 7,
  148145. 11,10, 5, 9, 9, 7,10,10, 8,10,11, 4, 9, 9, 9,12,
  148146. 12, 9,12,12, 8,12,12,11,12,12,10,12,13, 7,12,12,
  148147. 11,12,12,10,12,13, 4, 9, 9, 9,12,12, 9,12,12, 7,
  148148. 12,11,10,13,13,11,12,12, 7,12,12,10,13,13,11,12,
  148149. 12,
  148150. };
  148151. static float _vq_quantthresh__44u5__p7_0[] = {
  148152. -5.5, 5.5,
  148153. };
  148154. static long _vq_quantmap__44u5__p7_0[] = {
  148155. 1, 0, 2,
  148156. };
  148157. static encode_aux_threshmatch _vq_auxt__44u5__p7_0 = {
  148158. _vq_quantthresh__44u5__p7_0,
  148159. _vq_quantmap__44u5__p7_0,
  148160. 3,
  148161. 3
  148162. };
  148163. static static_codebook _44u5__p7_0 = {
  148164. 4, 81,
  148165. _vq_lengthlist__44u5__p7_0,
  148166. 1, -529137664, 1618345984, 2, 0,
  148167. _vq_quantlist__44u5__p7_0,
  148168. NULL,
  148169. &_vq_auxt__44u5__p7_0,
  148170. NULL,
  148171. 0
  148172. };
  148173. static long _vq_quantlist__44u5__p7_1[] = {
  148174. 5,
  148175. 4,
  148176. 6,
  148177. 3,
  148178. 7,
  148179. 2,
  148180. 8,
  148181. 1,
  148182. 9,
  148183. 0,
  148184. 10,
  148185. };
  148186. static long _vq_lengthlist__44u5__p7_1[] = {
  148187. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  148188. 8, 8, 9, 8, 8, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 8,
  148189. 9, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  148190. 8, 9, 9, 9, 9, 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  148191. 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  148192. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  148193. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  148194. 9, 9, 9, 9, 9,10,10,10,10,
  148195. };
  148196. static float _vq_quantthresh__44u5__p7_1[] = {
  148197. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  148198. 3.5, 4.5,
  148199. };
  148200. static long _vq_quantmap__44u5__p7_1[] = {
  148201. 9, 7, 5, 3, 1, 0, 2, 4,
  148202. 6, 8, 10,
  148203. };
  148204. static encode_aux_threshmatch _vq_auxt__44u5__p7_1 = {
  148205. _vq_quantthresh__44u5__p7_1,
  148206. _vq_quantmap__44u5__p7_1,
  148207. 11,
  148208. 11
  148209. };
  148210. static static_codebook _44u5__p7_1 = {
  148211. 2, 121,
  148212. _vq_lengthlist__44u5__p7_1,
  148213. 1, -531365888, 1611661312, 4, 0,
  148214. _vq_quantlist__44u5__p7_1,
  148215. NULL,
  148216. &_vq_auxt__44u5__p7_1,
  148217. NULL,
  148218. 0
  148219. };
  148220. static long _vq_quantlist__44u5__p8_0[] = {
  148221. 5,
  148222. 4,
  148223. 6,
  148224. 3,
  148225. 7,
  148226. 2,
  148227. 8,
  148228. 1,
  148229. 9,
  148230. 0,
  148231. 10,
  148232. };
  148233. static long _vq_lengthlist__44u5__p8_0[] = {
  148234. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  148235. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  148236. 11, 6, 8, 7, 9, 9,10,10,11,11,13,12, 6, 8, 8, 9,
  148237. 9,10,10,11,11,12,13, 8, 9, 9,10,10,12,12,13,12,
  148238. 14,13, 8, 9, 9,10,10,12,12,13,13,14,14, 9,11,11,
  148239. 12,12,13,13,14,14,15,14, 9,11,11,12,12,13,13,14,
  148240. 14,15,14,11,12,12,13,13,14,14,15,14,15,14,11,11,
  148241. 12,13,13,14,14,14,14,15,15,
  148242. };
  148243. static float _vq_quantthresh__44u5__p8_0[] = {
  148244. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  148245. 38.5, 49.5,
  148246. };
  148247. static long _vq_quantmap__44u5__p8_0[] = {
  148248. 9, 7, 5, 3, 1, 0, 2, 4,
  148249. 6, 8, 10,
  148250. };
  148251. static encode_aux_threshmatch _vq_auxt__44u5__p8_0 = {
  148252. _vq_quantthresh__44u5__p8_0,
  148253. _vq_quantmap__44u5__p8_0,
  148254. 11,
  148255. 11
  148256. };
  148257. static static_codebook _44u5__p8_0 = {
  148258. 2, 121,
  148259. _vq_lengthlist__44u5__p8_0,
  148260. 1, -524582912, 1618345984, 4, 0,
  148261. _vq_quantlist__44u5__p8_0,
  148262. NULL,
  148263. &_vq_auxt__44u5__p8_0,
  148264. NULL,
  148265. 0
  148266. };
  148267. static long _vq_quantlist__44u5__p8_1[] = {
  148268. 5,
  148269. 4,
  148270. 6,
  148271. 3,
  148272. 7,
  148273. 2,
  148274. 8,
  148275. 1,
  148276. 9,
  148277. 0,
  148278. 10,
  148279. };
  148280. static long _vq_lengthlist__44u5__p8_1[] = {
  148281. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 6,
  148282. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  148283. 8, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 6, 6, 7, 7,
  148284. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  148285. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8,
  148286. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  148287. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  148288. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  148289. };
  148290. static float _vq_quantthresh__44u5__p8_1[] = {
  148291. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  148292. 3.5, 4.5,
  148293. };
  148294. static long _vq_quantmap__44u5__p8_1[] = {
  148295. 9, 7, 5, 3, 1, 0, 2, 4,
  148296. 6, 8, 10,
  148297. };
  148298. static encode_aux_threshmatch _vq_auxt__44u5__p8_1 = {
  148299. _vq_quantthresh__44u5__p8_1,
  148300. _vq_quantmap__44u5__p8_1,
  148301. 11,
  148302. 11
  148303. };
  148304. static static_codebook _44u5__p8_1 = {
  148305. 2, 121,
  148306. _vq_lengthlist__44u5__p8_1,
  148307. 1, -531365888, 1611661312, 4, 0,
  148308. _vq_quantlist__44u5__p8_1,
  148309. NULL,
  148310. &_vq_auxt__44u5__p8_1,
  148311. NULL,
  148312. 0
  148313. };
  148314. static long _vq_quantlist__44u5__p9_0[] = {
  148315. 6,
  148316. 5,
  148317. 7,
  148318. 4,
  148319. 8,
  148320. 3,
  148321. 9,
  148322. 2,
  148323. 10,
  148324. 1,
  148325. 11,
  148326. 0,
  148327. 12,
  148328. };
  148329. static long _vq_lengthlist__44u5__p9_0[] = {
  148330. 1, 3, 2,12,10,13,13,13,13,13,13,13,13, 4, 9, 9,
  148331. 13,13,13,13,13,13,13,13,13,13, 5,10, 9,13,13,13,
  148332. 13,13,13,13,13,13,13,12,13,13,13,13,13,13,13,13,
  148333. 13,13,13,13,11,13,13,13,13,13,13,13,13,13,13,13,
  148334. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  148335. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  148336. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  148337. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  148338. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,12,12,
  148339. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148340. 12,12,12,12,12,12,12,12,12,
  148341. };
  148342. static float _vq_quantthresh__44u5__p9_0[] = {
  148343. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  148344. 637.5, 892.5, 1147.5, 1402.5,
  148345. };
  148346. static long _vq_quantmap__44u5__p9_0[] = {
  148347. 11, 9, 7, 5, 3, 1, 0, 2,
  148348. 4, 6, 8, 10, 12,
  148349. };
  148350. static encode_aux_threshmatch _vq_auxt__44u5__p9_0 = {
  148351. _vq_quantthresh__44u5__p9_0,
  148352. _vq_quantmap__44u5__p9_0,
  148353. 13,
  148354. 13
  148355. };
  148356. static static_codebook _44u5__p9_0 = {
  148357. 2, 169,
  148358. _vq_lengthlist__44u5__p9_0,
  148359. 1, -514332672, 1627381760, 4, 0,
  148360. _vq_quantlist__44u5__p9_0,
  148361. NULL,
  148362. &_vq_auxt__44u5__p9_0,
  148363. NULL,
  148364. 0
  148365. };
  148366. static long _vq_quantlist__44u5__p9_1[] = {
  148367. 7,
  148368. 6,
  148369. 8,
  148370. 5,
  148371. 9,
  148372. 4,
  148373. 10,
  148374. 3,
  148375. 11,
  148376. 2,
  148377. 12,
  148378. 1,
  148379. 13,
  148380. 0,
  148381. 14,
  148382. };
  148383. static long _vq_lengthlist__44u5__p9_1[] = {
  148384. 1, 4, 4, 7, 7, 8, 8, 8, 7, 8, 7, 9, 8, 9, 9, 4,
  148385. 7, 6, 9, 8,10,10, 9, 8, 9, 9, 9, 9, 9, 8, 5, 6,
  148386. 6, 8, 9,10,10, 9, 9, 9,10,10,10,10,11, 7, 8, 8,
  148387. 10,10,11,11,10,10,11,11,11,12,11,11, 7, 8, 8,10,
  148388. 10,11,11,10,10,11,11,12,11,11,11, 8, 9, 9,11,11,
  148389. 12,12,11,11,12,11,12,12,12,12, 8, 9,10,11,11,12,
  148390. 12,11,11,12,12,12,12,12,12, 8, 9, 9,10,10,12,11,
  148391. 12,12,12,12,12,12,12,13, 8, 9, 9,11,11,11,11,12,
  148392. 12,12,12,13,12,13,13, 9,10,10,11,11,12,12,12,13,
  148393. 12,13,13,13,14,13, 9,10,10,11,11,12,12,12,13,13,
  148394. 12,13,13,14,13, 9,11,10,12,11,13,12,12,13,13,13,
  148395. 13,13,13,14, 9,10,10,12,12,12,12,12,13,13,13,13,
  148396. 13,14,14,10,11,11,12,12,12,13,13,13,14,14,13,14,
  148397. 14,14,10,11,11,12,12,12,12,13,12,13,14,13,14,14,
  148398. 14,
  148399. };
  148400. static float _vq_quantthresh__44u5__p9_1[] = {
  148401. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  148402. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  148403. };
  148404. static long _vq_quantmap__44u5__p9_1[] = {
  148405. 13, 11, 9, 7, 5, 3, 1, 0,
  148406. 2, 4, 6, 8, 10, 12, 14,
  148407. };
  148408. static encode_aux_threshmatch _vq_auxt__44u5__p9_1 = {
  148409. _vq_quantthresh__44u5__p9_1,
  148410. _vq_quantmap__44u5__p9_1,
  148411. 15,
  148412. 15
  148413. };
  148414. static static_codebook _44u5__p9_1 = {
  148415. 2, 225,
  148416. _vq_lengthlist__44u5__p9_1,
  148417. 1, -522338304, 1620115456, 4, 0,
  148418. _vq_quantlist__44u5__p9_1,
  148419. NULL,
  148420. &_vq_auxt__44u5__p9_1,
  148421. NULL,
  148422. 0
  148423. };
  148424. static long _vq_quantlist__44u5__p9_2[] = {
  148425. 8,
  148426. 7,
  148427. 9,
  148428. 6,
  148429. 10,
  148430. 5,
  148431. 11,
  148432. 4,
  148433. 12,
  148434. 3,
  148435. 13,
  148436. 2,
  148437. 14,
  148438. 1,
  148439. 15,
  148440. 0,
  148441. 16,
  148442. };
  148443. static long _vq_lengthlist__44u5__p9_2[] = {
  148444. 2, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148445. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  148446. 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  148447. 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  148448. 9, 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  148449. 9, 9, 9, 9, 9, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  148450. 9,10, 9,10,10,10, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  148451. 9, 9,10, 9,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  148452. 9,10, 9,10,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  148453. 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,10, 9,
  148454. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,
  148455. 9,10, 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  148456. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  148457. 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  148458. 9,10,10, 9,10,10,10,10,10,10,10,10,10,10, 9, 9,
  148459. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  148460. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  148461. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,
  148462. 10,
  148463. };
  148464. static float _vq_quantthresh__44u5__p9_2[] = {
  148465. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  148466. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  148467. };
  148468. static long _vq_quantmap__44u5__p9_2[] = {
  148469. 15, 13, 11, 9, 7, 5, 3, 1,
  148470. 0, 2, 4, 6, 8, 10, 12, 14,
  148471. 16,
  148472. };
  148473. static encode_aux_threshmatch _vq_auxt__44u5__p9_2 = {
  148474. _vq_quantthresh__44u5__p9_2,
  148475. _vq_quantmap__44u5__p9_2,
  148476. 17,
  148477. 17
  148478. };
  148479. static static_codebook _44u5__p9_2 = {
  148480. 2, 289,
  148481. _vq_lengthlist__44u5__p9_2,
  148482. 1, -529530880, 1611661312, 5, 0,
  148483. _vq_quantlist__44u5__p9_2,
  148484. NULL,
  148485. &_vq_auxt__44u5__p9_2,
  148486. NULL,
  148487. 0
  148488. };
  148489. static long _huff_lengthlist__44u5__short[] = {
  148490. 4,10,17,13,17,13,17,17,17,17, 3, 6, 8, 9,11, 9,
  148491. 15,12,16,17, 6, 5, 5, 7, 7, 8,10,11,17,17, 7, 8,
  148492. 7, 9, 9,10,13,13,17,17, 8, 6, 5, 7, 4, 7, 5, 8,
  148493. 14,17, 9, 9, 8, 9, 7, 9, 8,10,16,17,12,10, 7, 8,
  148494. 4, 7, 4, 7,16,17,12,11, 9,10, 6, 9, 5, 7,14,17,
  148495. 14,13,10,15, 4, 8, 3, 5,14,17,17,14,11,15, 6,10,
  148496. 6, 8,15,17,
  148497. };
  148498. static static_codebook _huff_book__44u5__short = {
  148499. 2, 100,
  148500. _huff_lengthlist__44u5__short,
  148501. 0, 0, 0, 0, 0,
  148502. NULL,
  148503. NULL,
  148504. NULL,
  148505. NULL,
  148506. 0
  148507. };
  148508. static long _huff_lengthlist__44u6__long[] = {
  148509. 3, 9,14,13,14,13,16,12,13,14, 5, 4, 6, 6, 8, 9,
  148510. 11,10,12,15,10, 5, 5, 6, 6, 8,10,10,13,16,10, 6,
  148511. 6, 6, 6, 8, 9, 9,12,14,13, 7, 6, 6, 4, 6, 6, 7,
  148512. 11,14,10, 7, 7, 7, 6, 6, 6, 7,10,13,15,10, 9, 8,
  148513. 5, 6, 5, 6,10,14,10, 9, 8, 8, 6, 6, 5, 4, 6,11,
  148514. 11,11,12,11,10, 9, 9, 5, 5, 9,10,12,15,13,13,13,
  148515. 13, 8, 7, 7,
  148516. };
  148517. static static_codebook _huff_book__44u6__long = {
  148518. 2, 100,
  148519. _huff_lengthlist__44u6__long,
  148520. 0, 0, 0, 0, 0,
  148521. NULL,
  148522. NULL,
  148523. NULL,
  148524. NULL,
  148525. 0
  148526. };
  148527. static long _vq_quantlist__44u6__p1_0[] = {
  148528. 1,
  148529. 0,
  148530. 2,
  148531. };
  148532. static long _vq_lengthlist__44u6__p1_0[] = {
  148533. 1, 4, 4, 4, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  148534. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  148535. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  148536. 10,13,11,10,13,13, 5, 8, 8, 8,11,10, 8,10,10, 7,
  148537. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  148538. 12,
  148539. };
  148540. static float _vq_quantthresh__44u6__p1_0[] = {
  148541. -0.5, 0.5,
  148542. };
  148543. static long _vq_quantmap__44u6__p1_0[] = {
  148544. 1, 0, 2,
  148545. };
  148546. static encode_aux_threshmatch _vq_auxt__44u6__p1_0 = {
  148547. _vq_quantthresh__44u6__p1_0,
  148548. _vq_quantmap__44u6__p1_0,
  148549. 3,
  148550. 3
  148551. };
  148552. static static_codebook _44u6__p1_0 = {
  148553. 4, 81,
  148554. _vq_lengthlist__44u6__p1_0,
  148555. 1, -535822336, 1611661312, 2, 0,
  148556. _vq_quantlist__44u6__p1_0,
  148557. NULL,
  148558. &_vq_auxt__44u6__p1_0,
  148559. NULL,
  148560. 0
  148561. };
  148562. static long _vq_quantlist__44u6__p2_0[] = {
  148563. 1,
  148564. 0,
  148565. 2,
  148566. };
  148567. static long _vq_lengthlist__44u6__p2_0[] = {
  148568. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  148569. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  148570. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 7, 7,
  148571. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  148572. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  148573. 9,
  148574. };
  148575. static float _vq_quantthresh__44u6__p2_0[] = {
  148576. -0.5, 0.5,
  148577. };
  148578. static long _vq_quantmap__44u6__p2_0[] = {
  148579. 1, 0, 2,
  148580. };
  148581. static encode_aux_threshmatch _vq_auxt__44u6__p2_0 = {
  148582. _vq_quantthresh__44u6__p2_0,
  148583. _vq_quantmap__44u6__p2_0,
  148584. 3,
  148585. 3
  148586. };
  148587. static static_codebook _44u6__p2_0 = {
  148588. 4, 81,
  148589. _vq_lengthlist__44u6__p2_0,
  148590. 1, -535822336, 1611661312, 2, 0,
  148591. _vq_quantlist__44u6__p2_0,
  148592. NULL,
  148593. &_vq_auxt__44u6__p2_0,
  148594. NULL,
  148595. 0
  148596. };
  148597. static long _vq_quantlist__44u6__p3_0[] = {
  148598. 2,
  148599. 1,
  148600. 3,
  148601. 0,
  148602. 4,
  148603. };
  148604. static long _vq_lengthlist__44u6__p3_0[] = {
  148605. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  148606. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  148607. 9,11,11, 7, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  148608. 13,14, 5, 7, 7, 9,10, 6, 9, 8,11,11, 7, 9, 9,11,
  148609. 11, 9,11,10,14,13,10,11,11,14,13, 8,10,10,13,13,
  148610. 10,11,11,15,15, 9,11,11,14,14,13,14,14,17,16,12,
  148611. 13,14,16,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  148612. 12,14,15,12,14,13,16,15,13,14,14,15,17, 5, 7, 7,
  148613. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,
  148614. 14,10,11,11,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  148615. 9,11,11,13,13,11,13,13,14,15,11,12,13,15,16, 6,
  148616. 9, 9,11,12, 8,11,10,13,12, 9,11,11,13,14,11,13,
  148617. 12,16,14,11,13,13,15,16,10,12,11,14,15,11,13,13,
  148618. 15,17,11,13,13,17,16,15,15,16,17,16,14,15,16,18,
  148619. 0, 9,11,11,14,15,10,12,12,16,15,11,13,13,16,16,
  148620. 13,15,14,18,15,14,16,16, 0, 0, 5, 7, 7,10,10, 7,
  148621. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  148622. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  148623. 12,13,11,13,13,16,15,11,12,13,14,16, 7, 9, 9,11,
  148624. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,16,15,
  148625. 11,13,12,15,15, 9,11,11,15,14,11,13,13,17,16,10,
  148626. 12,13,15,16,14,16,16, 0,18,14,14,15,15,17,10,11,
  148627. 12,15,15,11,13,13,16,16,11,13,13,16,16,14,16,16,
  148628. 19,17,14,15,15,17,17, 8,10,10,14,14,10,12,11,15,
  148629. 15,10,11,12,16,15,14,15,15,18,20,13,14,16,17,18,
  148630. 9,11,11,15,16,11,13,13,17,17,11,13,13,17,16,15,
  148631. 16,16, 0, 0,15,16,16, 0, 0, 9,11,11,15,15,10,13,
  148632. 12,17,15,11,13,13,17,16,15,17,15,20,19,15,16,16,
  148633. 19, 0,13,15,14, 0,17,14,15,16, 0,20,15,16,16, 0,
  148634. 19,17,18, 0, 0, 0,16,17,18, 0, 0,12,14,14,19,18,
  148635. 13,15,14, 0,17,14,15,16,19,19,16,18,16, 0,19,19,
  148636. 20,17,20, 0, 8,10,10,13,14,10,11,11,15,15,10,12,
  148637. 12,15,16,14,15,14,19,16,14,15,15, 0,18, 9,11,11,
  148638. 16,15,11,13,13, 0,16,11,12,13,16,17,14,16,17, 0,
  148639. 19,15,16,16,18, 0, 9,11,11,15,16,11,13,13,16,16,
  148640. 11,14,13,18,17,15,16,16,18,20,15,17,19, 0, 0,12,
  148641. 14,14,17,17,14,16,15, 0, 0,13,14,15,19, 0,16,18,
  148642. 20, 0, 0,16,16,18,18, 0,12,14,14,17,20,14,16,16,
  148643. 19, 0,14,16,14, 0,20,16,20,17, 0, 0,17, 0,15, 0,
  148644. 19,
  148645. };
  148646. static float _vq_quantthresh__44u6__p3_0[] = {
  148647. -1.5, -0.5, 0.5, 1.5,
  148648. };
  148649. static long _vq_quantmap__44u6__p3_0[] = {
  148650. 3, 1, 0, 2, 4,
  148651. };
  148652. static encode_aux_threshmatch _vq_auxt__44u6__p3_0 = {
  148653. _vq_quantthresh__44u6__p3_0,
  148654. _vq_quantmap__44u6__p3_0,
  148655. 5,
  148656. 5
  148657. };
  148658. static static_codebook _44u6__p3_0 = {
  148659. 4, 625,
  148660. _vq_lengthlist__44u6__p3_0,
  148661. 1, -533725184, 1611661312, 3, 0,
  148662. _vq_quantlist__44u6__p3_0,
  148663. NULL,
  148664. &_vq_auxt__44u6__p3_0,
  148665. NULL,
  148666. 0
  148667. };
  148668. static long _vq_quantlist__44u6__p4_0[] = {
  148669. 2,
  148670. 1,
  148671. 3,
  148672. 0,
  148673. 4,
  148674. };
  148675. static long _vq_lengthlist__44u6__p4_0[] = {
  148676. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  148677. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  148678. 8,10,10, 7, 7, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  148679. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 8,10,
  148680. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  148681. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,13,11,
  148682. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  148683. 10,12,12,11,12,11,13,12,11,12,12,13,13, 5, 7, 7,
  148684. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  148685. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  148686. 8, 9, 9,11,11,10,10,11,12,13,10,10,11,12,12, 6,
  148687. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  148688. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  148689. 13,13,10,11,11,12,13,12,12,12,13,14,12,12,13,14,
  148690. 14, 9,10,10,12,12, 9,10,10,13,12,10,11,11,13,13,
  148691. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  148692. 8, 7,10,10, 7, 8, 8,10,10, 9,10,10,12,11, 9,10,
  148693. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  148694. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  148695. 10, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,10,13,12,
  148696. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,12, 9,
  148697. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  148698. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,12,12,
  148699. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  148700. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,14,
  148701. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  148702. 12,13,14,15,12,12,13,14,14, 9,10,10,12,12, 9,11,
  148703. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,13,
  148704. 14,15,11,12,12,14,13,11,12,12,14,14,12,13,13,14,
  148705. 14,13,13,14,14,16,13,14,14,15,15,11,12,11,13,13,
  148706. 11,12,11,14,13,12,12,13,14,15,12,14,12,15,12,13,
  148707. 14,15,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  148708. 10,12,12,11,12,12,14,13,11,12,12,13,13, 9,10,10,
  148709. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  148710. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  148711. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  148712. 11,11,13,13,12,13,12,14,14,11,11,12,13,14,14,14,
  148713. 14,16,15,12,12,14,12,15,11,12,12,13,14,12,13,13,
  148714. 14,15,11,12,12,14,14,13,14,14,16,16,13,14,13,16,
  148715. 13,
  148716. };
  148717. static float _vq_quantthresh__44u6__p4_0[] = {
  148718. -1.5, -0.5, 0.5, 1.5,
  148719. };
  148720. static long _vq_quantmap__44u6__p4_0[] = {
  148721. 3, 1, 0, 2, 4,
  148722. };
  148723. static encode_aux_threshmatch _vq_auxt__44u6__p4_0 = {
  148724. _vq_quantthresh__44u6__p4_0,
  148725. _vq_quantmap__44u6__p4_0,
  148726. 5,
  148727. 5
  148728. };
  148729. static static_codebook _44u6__p4_0 = {
  148730. 4, 625,
  148731. _vq_lengthlist__44u6__p4_0,
  148732. 1, -533725184, 1611661312, 3, 0,
  148733. _vq_quantlist__44u6__p4_0,
  148734. NULL,
  148735. &_vq_auxt__44u6__p4_0,
  148736. NULL,
  148737. 0
  148738. };
  148739. static long _vq_quantlist__44u6__p5_0[] = {
  148740. 4,
  148741. 3,
  148742. 5,
  148743. 2,
  148744. 6,
  148745. 1,
  148746. 7,
  148747. 0,
  148748. 8,
  148749. };
  148750. static long _vq_lengthlist__44u6__p5_0[] = {
  148751. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  148752. 11,11, 3, 5, 5, 7, 8, 8, 8,11,11, 6, 8, 7, 9, 9,
  148753. 10, 9,12,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  148754. 10, 9,12,11,13,13, 8, 8, 9, 9,10,11,12,13,13,10,
  148755. 11,11,12,12,13,13,14,14,10,10,11,11,12,13,13,14,
  148756. 14,
  148757. };
  148758. static float _vq_quantthresh__44u6__p5_0[] = {
  148759. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148760. };
  148761. static long _vq_quantmap__44u6__p5_0[] = {
  148762. 7, 5, 3, 1, 0, 2, 4, 6,
  148763. 8,
  148764. };
  148765. static encode_aux_threshmatch _vq_auxt__44u6__p5_0 = {
  148766. _vq_quantthresh__44u6__p5_0,
  148767. _vq_quantmap__44u6__p5_0,
  148768. 9,
  148769. 9
  148770. };
  148771. static static_codebook _44u6__p5_0 = {
  148772. 2, 81,
  148773. _vq_lengthlist__44u6__p5_0,
  148774. 1, -531628032, 1611661312, 4, 0,
  148775. _vq_quantlist__44u6__p5_0,
  148776. NULL,
  148777. &_vq_auxt__44u6__p5_0,
  148778. NULL,
  148779. 0
  148780. };
  148781. static long _vq_quantlist__44u6__p6_0[] = {
  148782. 4,
  148783. 3,
  148784. 5,
  148785. 2,
  148786. 6,
  148787. 1,
  148788. 7,
  148789. 0,
  148790. 8,
  148791. };
  148792. static long _vq_lengthlist__44u6__p6_0[] = {
  148793. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  148794. 9, 9, 4, 4, 5, 6, 6, 7, 8, 9, 9, 5, 6, 6, 7, 7,
  148795. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  148796. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,10,11, 9,
  148797. 9, 9,10,10,11,11,12,11, 9, 9, 9,10,10,11,11,11,
  148798. 12,
  148799. };
  148800. static float _vq_quantthresh__44u6__p6_0[] = {
  148801. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148802. };
  148803. static long _vq_quantmap__44u6__p6_0[] = {
  148804. 7, 5, 3, 1, 0, 2, 4, 6,
  148805. 8,
  148806. };
  148807. static encode_aux_threshmatch _vq_auxt__44u6__p6_0 = {
  148808. _vq_quantthresh__44u6__p6_0,
  148809. _vq_quantmap__44u6__p6_0,
  148810. 9,
  148811. 9
  148812. };
  148813. static static_codebook _44u6__p6_0 = {
  148814. 2, 81,
  148815. _vq_lengthlist__44u6__p6_0,
  148816. 1, -531628032, 1611661312, 4, 0,
  148817. _vq_quantlist__44u6__p6_0,
  148818. NULL,
  148819. &_vq_auxt__44u6__p6_0,
  148820. NULL,
  148821. 0
  148822. };
  148823. static long _vq_quantlist__44u6__p7_0[] = {
  148824. 1,
  148825. 0,
  148826. 2,
  148827. };
  148828. static long _vq_lengthlist__44u6__p7_0[] = {
  148829. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10,10, 8,
  148830. 10,10, 5, 8, 9, 7,10,10, 7,10, 9, 4, 8, 8, 9,11,
  148831. 11, 8,11,11, 7,11,11,10,10,13,10,13,13, 7,11,11,
  148832. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 9,11,11, 7,
  148833. 11,11,10,13,13,10,12,13, 7,11,11,10,13,13, 9,13,
  148834. 10,
  148835. };
  148836. static float _vq_quantthresh__44u6__p7_0[] = {
  148837. -5.5, 5.5,
  148838. };
  148839. static long _vq_quantmap__44u6__p7_0[] = {
  148840. 1, 0, 2,
  148841. };
  148842. static encode_aux_threshmatch _vq_auxt__44u6__p7_0 = {
  148843. _vq_quantthresh__44u6__p7_0,
  148844. _vq_quantmap__44u6__p7_0,
  148845. 3,
  148846. 3
  148847. };
  148848. static static_codebook _44u6__p7_0 = {
  148849. 4, 81,
  148850. _vq_lengthlist__44u6__p7_0,
  148851. 1, -529137664, 1618345984, 2, 0,
  148852. _vq_quantlist__44u6__p7_0,
  148853. NULL,
  148854. &_vq_auxt__44u6__p7_0,
  148855. NULL,
  148856. 0
  148857. };
  148858. static long _vq_quantlist__44u6__p7_1[] = {
  148859. 5,
  148860. 4,
  148861. 6,
  148862. 3,
  148863. 7,
  148864. 2,
  148865. 8,
  148866. 1,
  148867. 9,
  148868. 0,
  148869. 10,
  148870. };
  148871. static long _vq_lengthlist__44u6__p7_1[] = {
  148872. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 6,
  148873. 8, 8, 8, 8, 8, 8, 4, 5, 5, 6, 7, 8, 8, 8, 8, 8,
  148874. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  148875. 7, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 9, 9,
  148876. 9, 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  148877. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  148878. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  148879. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148880. };
  148881. static float _vq_quantthresh__44u6__p7_1[] = {
  148882. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  148883. 3.5, 4.5,
  148884. };
  148885. static long _vq_quantmap__44u6__p7_1[] = {
  148886. 9, 7, 5, 3, 1, 0, 2, 4,
  148887. 6, 8, 10,
  148888. };
  148889. static encode_aux_threshmatch _vq_auxt__44u6__p7_1 = {
  148890. _vq_quantthresh__44u6__p7_1,
  148891. _vq_quantmap__44u6__p7_1,
  148892. 11,
  148893. 11
  148894. };
  148895. static static_codebook _44u6__p7_1 = {
  148896. 2, 121,
  148897. _vq_lengthlist__44u6__p7_1,
  148898. 1, -531365888, 1611661312, 4, 0,
  148899. _vq_quantlist__44u6__p7_1,
  148900. NULL,
  148901. &_vq_auxt__44u6__p7_1,
  148902. NULL,
  148903. 0
  148904. };
  148905. static long _vq_quantlist__44u6__p8_0[] = {
  148906. 5,
  148907. 4,
  148908. 6,
  148909. 3,
  148910. 7,
  148911. 2,
  148912. 8,
  148913. 1,
  148914. 9,
  148915. 0,
  148916. 10,
  148917. };
  148918. static long _vq_lengthlist__44u6__p8_0[] = {
  148919. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  148920. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  148921. 11, 6, 8, 8, 9, 9,10,10,11,11,12,12, 6, 8, 8, 9,
  148922. 9,10,10,11,11,12,12, 8, 9, 9,10,10,11,11,12,12,
  148923. 13,13, 8, 9, 9,10,10,11,11,12,12,13,13,10,10,10,
  148924. 11,11,13,13,13,13,15,14, 9,10,10,12,11,12,13,13,
  148925. 13,14,15,11,12,12,13,13,13,13,15,14,15,15,11,11,
  148926. 12,13,13,14,14,14,15,15,15,
  148927. };
  148928. static float _vq_quantthresh__44u6__p8_0[] = {
  148929. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  148930. 38.5, 49.5,
  148931. };
  148932. static long _vq_quantmap__44u6__p8_0[] = {
  148933. 9, 7, 5, 3, 1, 0, 2, 4,
  148934. 6, 8, 10,
  148935. };
  148936. static encode_aux_threshmatch _vq_auxt__44u6__p8_0 = {
  148937. _vq_quantthresh__44u6__p8_0,
  148938. _vq_quantmap__44u6__p8_0,
  148939. 11,
  148940. 11
  148941. };
  148942. static static_codebook _44u6__p8_0 = {
  148943. 2, 121,
  148944. _vq_lengthlist__44u6__p8_0,
  148945. 1, -524582912, 1618345984, 4, 0,
  148946. _vq_quantlist__44u6__p8_0,
  148947. NULL,
  148948. &_vq_auxt__44u6__p8_0,
  148949. NULL,
  148950. 0
  148951. };
  148952. static long _vq_quantlist__44u6__p8_1[] = {
  148953. 5,
  148954. 4,
  148955. 6,
  148956. 3,
  148957. 7,
  148958. 2,
  148959. 8,
  148960. 1,
  148961. 9,
  148962. 0,
  148963. 10,
  148964. };
  148965. static long _vq_lengthlist__44u6__p8_1[] = {
  148966. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 7,
  148967. 7, 7, 8, 7, 8, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7, 8,
  148968. 8, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 6, 7, 7,
  148969. 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  148970. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  148971. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  148972. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  148973. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  148974. };
  148975. static float _vq_quantthresh__44u6__p8_1[] = {
  148976. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  148977. 3.5, 4.5,
  148978. };
  148979. static long _vq_quantmap__44u6__p8_1[] = {
  148980. 9, 7, 5, 3, 1, 0, 2, 4,
  148981. 6, 8, 10,
  148982. };
  148983. static encode_aux_threshmatch _vq_auxt__44u6__p8_1 = {
  148984. _vq_quantthresh__44u6__p8_1,
  148985. _vq_quantmap__44u6__p8_1,
  148986. 11,
  148987. 11
  148988. };
  148989. static static_codebook _44u6__p8_1 = {
  148990. 2, 121,
  148991. _vq_lengthlist__44u6__p8_1,
  148992. 1, -531365888, 1611661312, 4, 0,
  148993. _vq_quantlist__44u6__p8_1,
  148994. NULL,
  148995. &_vq_auxt__44u6__p8_1,
  148996. NULL,
  148997. 0
  148998. };
  148999. static long _vq_quantlist__44u6__p9_0[] = {
  149000. 7,
  149001. 6,
  149002. 8,
  149003. 5,
  149004. 9,
  149005. 4,
  149006. 10,
  149007. 3,
  149008. 11,
  149009. 2,
  149010. 12,
  149011. 1,
  149012. 13,
  149013. 0,
  149014. 14,
  149015. };
  149016. static long _vq_lengthlist__44u6__p9_0[] = {
  149017. 1, 3, 2, 9, 8,15,15,15,15,15,15,15,15,15,15, 4,
  149018. 8, 9,13,14,14,14,14,14,14,14,14,14,14,14, 5, 8,
  149019. 9,14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,
  149020. 14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,14,
  149021. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149022. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149023. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149024. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149025. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149026. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149027. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149028. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149029. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149030. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149031. 14,
  149032. };
  149033. static float _vq_quantthresh__44u6__p9_0[] = {
  149034. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  149035. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  149036. };
  149037. static long _vq_quantmap__44u6__p9_0[] = {
  149038. 13, 11, 9, 7, 5, 3, 1, 0,
  149039. 2, 4, 6, 8, 10, 12, 14,
  149040. };
  149041. static encode_aux_threshmatch _vq_auxt__44u6__p9_0 = {
  149042. _vq_quantthresh__44u6__p9_0,
  149043. _vq_quantmap__44u6__p9_0,
  149044. 15,
  149045. 15
  149046. };
  149047. static static_codebook _44u6__p9_0 = {
  149048. 2, 225,
  149049. _vq_lengthlist__44u6__p9_0,
  149050. 1, -514071552, 1627381760, 4, 0,
  149051. _vq_quantlist__44u6__p9_0,
  149052. NULL,
  149053. &_vq_auxt__44u6__p9_0,
  149054. NULL,
  149055. 0
  149056. };
  149057. static long _vq_quantlist__44u6__p9_1[] = {
  149058. 7,
  149059. 6,
  149060. 8,
  149061. 5,
  149062. 9,
  149063. 4,
  149064. 10,
  149065. 3,
  149066. 11,
  149067. 2,
  149068. 12,
  149069. 1,
  149070. 13,
  149071. 0,
  149072. 14,
  149073. };
  149074. static long _vq_lengthlist__44u6__p9_1[] = {
  149075. 1, 4, 4, 7, 7, 8, 9, 8, 8, 9, 8, 9, 8, 9, 9, 4,
  149076. 7, 6, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 4, 7,
  149077. 6, 9, 9,10,10, 9, 9,10,10,10,10,11,11, 7, 9, 8,
  149078. 10,10,11,11,10,10,11,11,11,11,11,11, 7, 8, 9,10,
  149079. 10,11,11,10,10,11,11,11,11,11,12, 8,10,10,11,11,
  149080. 12,12,11,11,12,12,12,12,13,12, 8,10,10,11,11,12,
  149081. 11,11,11,11,12,12,12,12,13, 8, 9, 9,11,10,11,11,
  149082. 12,12,12,12,13,12,13,12, 8, 9, 9,11,11,11,11,12,
  149083. 12,12,12,12,13,13,13, 9,10,10,11,12,12,12,12,12,
  149084. 13,13,13,13,13,13, 9,10,10,11,11,12,12,12,12,13,
  149085. 13,13,13,14,13,10,10,10,12,11,12,12,13,13,13,13,
  149086. 13,13,13,13,10,10,11,11,11,12,12,13,13,13,13,13,
  149087. 13,13,13,10,11,11,12,12,13,12,12,13,13,13,13,13,
  149088. 13,14,10,11,11,12,12,13,12,13,13,13,14,13,13,14,
  149089. 13,
  149090. };
  149091. static float _vq_quantthresh__44u6__p9_1[] = {
  149092. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  149093. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  149094. };
  149095. static long _vq_quantmap__44u6__p9_1[] = {
  149096. 13, 11, 9, 7, 5, 3, 1, 0,
  149097. 2, 4, 6, 8, 10, 12, 14,
  149098. };
  149099. static encode_aux_threshmatch _vq_auxt__44u6__p9_1 = {
  149100. _vq_quantthresh__44u6__p9_1,
  149101. _vq_quantmap__44u6__p9_1,
  149102. 15,
  149103. 15
  149104. };
  149105. static static_codebook _44u6__p9_1 = {
  149106. 2, 225,
  149107. _vq_lengthlist__44u6__p9_1,
  149108. 1, -522338304, 1620115456, 4, 0,
  149109. _vq_quantlist__44u6__p9_1,
  149110. NULL,
  149111. &_vq_auxt__44u6__p9_1,
  149112. NULL,
  149113. 0
  149114. };
  149115. static long _vq_quantlist__44u6__p9_2[] = {
  149116. 8,
  149117. 7,
  149118. 9,
  149119. 6,
  149120. 10,
  149121. 5,
  149122. 11,
  149123. 4,
  149124. 12,
  149125. 3,
  149126. 13,
  149127. 2,
  149128. 14,
  149129. 1,
  149130. 15,
  149131. 0,
  149132. 16,
  149133. };
  149134. static long _vq_lengthlist__44u6__p9_2[] = {
  149135. 3, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 8, 8, 9, 9,
  149136. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  149137. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  149138. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149139. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  149140. 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149141. 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  149142. 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149143. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  149144. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9, 9, 9, 9,
  149145. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 8, 9, 9, 9, 9, 9,
  149146. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  149147. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9, 9, 9, 9, 9,
  149148. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,
  149149. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9, 9,
  149150. 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9,10, 9,
  149151. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9,10,10,
  149152. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10, 9, 9,
  149153. 10,
  149154. };
  149155. static float _vq_quantthresh__44u6__p9_2[] = {
  149156. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  149157. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  149158. };
  149159. static long _vq_quantmap__44u6__p9_2[] = {
  149160. 15, 13, 11, 9, 7, 5, 3, 1,
  149161. 0, 2, 4, 6, 8, 10, 12, 14,
  149162. 16,
  149163. };
  149164. static encode_aux_threshmatch _vq_auxt__44u6__p9_2 = {
  149165. _vq_quantthresh__44u6__p9_2,
  149166. _vq_quantmap__44u6__p9_2,
  149167. 17,
  149168. 17
  149169. };
  149170. static static_codebook _44u6__p9_2 = {
  149171. 2, 289,
  149172. _vq_lengthlist__44u6__p9_2,
  149173. 1, -529530880, 1611661312, 5, 0,
  149174. _vq_quantlist__44u6__p9_2,
  149175. NULL,
  149176. &_vq_auxt__44u6__p9_2,
  149177. NULL,
  149178. 0
  149179. };
  149180. static long _huff_lengthlist__44u6__short[] = {
  149181. 4,11,16,13,17,13,17,16,17,17, 4, 7, 9, 9,13,10,
  149182. 16,12,16,17, 7, 6, 5, 7, 8, 9,12,12,16,17, 6, 9,
  149183. 7, 9,10,10,15,15,17,17, 6, 7, 5, 7, 5, 7, 7,10,
  149184. 16,17, 7, 9, 8, 9, 8,10,11,11,15,17, 7, 7, 7, 8,
  149185. 5, 8, 8, 9,15,17, 8, 7, 9, 9, 7, 8, 7, 2, 7,15,
  149186. 14,13,13,15, 5,10, 4, 3, 6,17,17,15,13,17, 7,11,
  149187. 7, 6, 9,16,
  149188. };
  149189. static static_codebook _huff_book__44u6__short = {
  149190. 2, 100,
  149191. _huff_lengthlist__44u6__short,
  149192. 0, 0, 0, 0, 0,
  149193. NULL,
  149194. NULL,
  149195. NULL,
  149196. NULL,
  149197. 0
  149198. };
  149199. static long _huff_lengthlist__44u7__long[] = {
  149200. 3, 9,14,13,15,14,16,13,13,14, 5, 5, 7, 7, 8, 9,
  149201. 11,10,12,15,10, 6, 5, 6, 6, 9,10,10,13,16,10, 6,
  149202. 6, 6, 6, 8, 9, 9,12,15,14, 7, 6, 6, 5, 6, 6, 8,
  149203. 12,15,10, 8, 7, 7, 6, 7, 7, 7,11,13,14,10, 9, 8,
  149204. 5, 6, 4, 5, 9,12,10, 9, 9, 8, 6, 6, 5, 3, 6,11,
  149205. 12,11,12,12,10, 9, 8, 5, 5, 8,10,11,15,13,13,13,
  149206. 12, 8, 6, 7,
  149207. };
  149208. static static_codebook _huff_book__44u7__long = {
  149209. 2, 100,
  149210. _huff_lengthlist__44u7__long,
  149211. 0, 0, 0, 0, 0,
  149212. NULL,
  149213. NULL,
  149214. NULL,
  149215. NULL,
  149216. 0
  149217. };
  149218. static long _vq_quantlist__44u7__p1_0[] = {
  149219. 1,
  149220. 0,
  149221. 2,
  149222. };
  149223. static long _vq_lengthlist__44u7__p1_0[] = {
  149224. 1, 4, 4, 4, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  149225. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 5, 8, 8, 8,11,
  149226. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  149227. 10,13,12,10,13,13, 5, 8, 8, 8,11,10, 8,10,11, 7,
  149228. 10,10,10,13,13,10,12,13, 8,11,11,10,13,13,10,13,
  149229. 12,
  149230. };
  149231. static float _vq_quantthresh__44u7__p1_0[] = {
  149232. -0.5, 0.5,
  149233. };
  149234. static long _vq_quantmap__44u7__p1_0[] = {
  149235. 1, 0, 2,
  149236. };
  149237. static encode_aux_threshmatch _vq_auxt__44u7__p1_0 = {
  149238. _vq_quantthresh__44u7__p1_0,
  149239. _vq_quantmap__44u7__p1_0,
  149240. 3,
  149241. 3
  149242. };
  149243. static static_codebook _44u7__p1_0 = {
  149244. 4, 81,
  149245. _vq_lengthlist__44u7__p1_0,
  149246. 1, -535822336, 1611661312, 2, 0,
  149247. _vq_quantlist__44u7__p1_0,
  149248. NULL,
  149249. &_vq_auxt__44u7__p1_0,
  149250. NULL,
  149251. 0
  149252. };
  149253. static long _vq_quantlist__44u7__p2_0[] = {
  149254. 1,
  149255. 0,
  149256. 2,
  149257. };
  149258. static long _vq_lengthlist__44u7__p2_0[] = {
  149259. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  149260. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  149261. 7, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  149262. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  149263. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  149264. 9,
  149265. };
  149266. static float _vq_quantthresh__44u7__p2_0[] = {
  149267. -0.5, 0.5,
  149268. };
  149269. static long _vq_quantmap__44u7__p2_0[] = {
  149270. 1, 0, 2,
  149271. };
  149272. static encode_aux_threshmatch _vq_auxt__44u7__p2_0 = {
  149273. _vq_quantthresh__44u7__p2_0,
  149274. _vq_quantmap__44u7__p2_0,
  149275. 3,
  149276. 3
  149277. };
  149278. static static_codebook _44u7__p2_0 = {
  149279. 4, 81,
  149280. _vq_lengthlist__44u7__p2_0,
  149281. 1, -535822336, 1611661312, 2, 0,
  149282. _vq_quantlist__44u7__p2_0,
  149283. NULL,
  149284. &_vq_auxt__44u7__p2_0,
  149285. NULL,
  149286. 0
  149287. };
  149288. static long _vq_quantlist__44u7__p3_0[] = {
  149289. 2,
  149290. 1,
  149291. 3,
  149292. 0,
  149293. 4,
  149294. };
  149295. static long _vq_lengthlist__44u7__p3_0[] = {
  149296. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  149297. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  149298. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  149299. 13,14, 5, 7, 7, 9, 9, 7, 9, 8,11,11, 7, 9, 9,11,
  149300. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  149301. 10,11,12,15,14, 9,11,11,15,14,13,14,14,16,16,12,
  149302. 13,14,17,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  149303. 12,14,15,12,14,13,16,16,13,14,15,15,17, 5, 7, 7,
  149304. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,15,
  149305. 14,10,11,12,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  149306. 9,11,11,13,13,11,13,13,14,17,11,13,13,15,16, 6,
  149307. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  149308. 12,16,14,11,13,13,16,16,10,12,12,15,15,11,13,13,
  149309. 16,16,11,13,13,16,15,14,16,17,17,19,14,16,16,18,
  149310. 0, 9,11,11,14,15,10,13,12,16,15,11,13,13,16,16,
  149311. 14,15,14, 0,16,14,16,16,18, 0, 5, 7, 7,10,10, 7,
  149312. 9, 9,12,11, 7, 9, 9,11,12,10,11,11,15,14,10,11,
  149313. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  149314. 12,13,11,13,13,17,15,11,12,13,14,15, 7, 9, 9,11,
  149315. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,12,16,16,
  149316. 11,13,13,15,14, 9,11,11,14,15,11,13,13,16,15,10,
  149317. 12,13,16,16,15,16,16, 0, 0,14,13,15,16,18,10,11,
  149318. 11,15,15,11,13,14,16,18,11,13,13,16,15,15,16,16,
  149319. 19, 0,14,15,15,16,16, 8,10,10,13,13,10,12,11,16,
  149320. 15,10,11,11,16,15,13,15,16,18, 0,13,14,15,17,17,
  149321. 9,11,11,15,15,11,13,13,16,18,11,13,13,16,17,15,
  149322. 16,16, 0, 0,15,18,16, 0,17, 9,11,11,15,15,11,13,
  149323. 12,17,15,11,13,14,16,17,15,18,15, 0,17,15,16,16,
  149324. 18,19,13,15,14, 0,18,14,16,16,19,18,14,16,15,19,
  149325. 19,16,18,19, 0, 0,16,17, 0, 0, 0,12,14,14,17,17,
  149326. 13,16,14, 0,18,14,16,15,18, 0,16,18,16,19,17,18,
  149327. 19,17, 0, 0, 8,10,10,14,14, 9,12,11,15,15,10,11,
  149328. 12,15,17,13,15,15,18,16,14,16,15,18,17, 9,11,11,
  149329. 16,15,11,13,13, 0,16,11,12,13,16,15,15,16,16, 0,
  149330. 17,15,15,16,18,17, 9,12,11,15,17,11,13,13,16,16,
  149331. 11,14,13,16,16,15,15,16,18,19,16,18,16, 0, 0,12,
  149332. 14,14, 0,16,14,16,16, 0,18,13,14,15,16, 0,17,16,
  149333. 18, 0, 0,16,16,17,19, 0,13,14,14,17, 0,14,17,16,
  149334. 0,19,14,15,15,18,19,17,16,18, 0, 0,15,19,16, 0,
  149335. 0,
  149336. };
  149337. static float _vq_quantthresh__44u7__p3_0[] = {
  149338. -1.5, -0.5, 0.5, 1.5,
  149339. };
  149340. static long _vq_quantmap__44u7__p3_0[] = {
  149341. 3, 1, 0, 2, 4,
  149342. };
  149343. static encode_aux_threshmatch _vq_auxt__44u7__p3_0 = {
  149344. _vq_quantthresh__44u7__p3_0,
  149345. _vq_quantmap__44u7__p3_0,
  149346. 5,
  149347. 5
  149348. };
  149349. static static_codebook _44u7__p3_0 = {
  149350. 4, 625,
  149351. _vq_lengthlist__44u7__p3_0,
  149352. 1, -533725184, 1611661312, 3, 0,
  149353. _vq_quantlist__44u7__p3_0,
  149354. NULL,
  149355. &_vq_auxt__44u7__p3_0,
  149356. NULL,
  149357. 0
  149358. };
  149359. static long _vq_quantlist__44u7__p4_0[] = {
  149360. 2,
  149361. 1,
  149362. 3,
  149363. 0,
  149364. 4,
  149365. };
  149366. static long _vq_lengthlist__44u7__p4_0[] = {
  149367. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  149368. 9, 9,11,11, 8, 9, 9,10,11, 6, 7, 7, 9, 9, 7, 8,
  149369. 8,10,10, 6, 7, 8, 9,10, 9,10,10,12,12, 9, 9,10,
  149370. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  149371. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  149372. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  149373. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,11, 9,10,
  149374. 10,12,12,11,12,11,13,13,11,12,12,13,13, 6, 7, 7,
  149375. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  149376. 11, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  149377. 8, 9, 9,11,11,10,11,11,12,12,10,10,11,12,13, 6,
  149378. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  149379. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  149380. 13,13,10,11,11,13,12,12,12,13,13,14,12,12,13,14,
  149381. 14, 9,10,10,12,12, 9,10,10,12,12,10,11,11,13,13,
  149382. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  149383. 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,11, 9,10,
  149384. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  149385. 10,11,10,11,11,13,12,10,10,11,11,13, 7, 8, 8,10,
  149386. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,10,13,12,
  149387. 10,11,11,12,12, 9,10,10,12,12,10,11,11,13,12, 9,
  149388. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  149389. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,12,
  149390. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  149391. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,13,
  149392. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  149393. 13,13,14,14,12,12,13,14,14, 9,10,10,12,12, 9,11,
  149394. 10,13,12,10,10,11,12,13,11,13,12,14,13,12,12,13,
  149395. 14,14,11,12,12,13,13,11,12,13,14,14,12,13,13,14,
  149396. 14,13,13,14,14,16,13,14,14,16,16,11,11,11,13,13,
  149397. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,13,14,
  149398. 14,14,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  149399. 10,12,12,11,12,12,14,13,11,12,12,13,14, 9,10,10,
  149400. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  149401. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,12,13,
  149402. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  149403. 12,12,13,13,12,13,12,14,14,11,11,12,13,14,13,15,
  149404. 14,16,15,13,12,14,13,16,11,12,12,13,13,12,13,13,
  149405. 14,14,12,12,12,14,14,13,14,14,15,15,13,14,13,16,
  149406. 14,
  149407. };
  149408. static float _vq_quantthresh__44u7__p4_0[] = {
  149409. -1.5, -0.5, 0.5, 1.5,
  149410. };
  149411. static long _vq_quantmap__44u7__p4_0[] = {
  149412. 3, 1, 0, 2, 4,
  149413. };
  149414. static encode_aux_threshmatch _vq_auxt__44u7__p4_0 = {
  149415. _vq_quantthresh__44u7__p4_0,
  149416. _vq_quantmap__44u7__p4_0,
  149417. 5,
  149418. 5
  149419. };
  149420. static static_codebook _44u7__p4_0 = {
  149421. 4, 625,
  149422. _vq_lengthlist__44u7__p4_0,
  149423. 1, -533725184, 1611661312, 3, 0,
  149424. _vq_quantlist__44u7__p4_0,
  149425. NULL,
  149426. &_vq_auxt__44u7__p4_0,
  149427. NULL,
  149428. 0
  149429. };
  149430. static long _vq_quantlist__44u7__p5_0[] = {
  149431. 4,
  149432. 3,
  149433. 5,
  149434. 2,
  149435. 6,
  149436. 1,
  149437. 7,
  149438. 0,
  149439. 8,
  149440. };
  149441. static long _vq_lengthlist__44u7__p5_0[] = {
  149442. 2, 3, 3, 6, 6, 7, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  149443. 11,11, 3, 5, 5, 7, 7, 8, 9,11,11, 6, 8, 7, 9, 9,
  149444. 10,10,12,12, 6, 7, 8, 9,10,10,10,12,12, 8, 8, 8,
  149445. 10,10,12,11,13,13, 8, 8, 9,10,10,11,11,13,13,10,
  149446. 11,11,12,12,13,13,14,14,10,11,11,12,12,13,13,14,
  149447. 14,
  149448. };
  149449. static float _vq_quantthresh__44u7__p5_0[] = {
  149450. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149451. };
  149452. static long _vq_quantmap__44u7__p5_0[] = {
  149453. 7, 5, 3, 1, 0, 2, 4, 6,
  149454. 8,
  149455. };
  149456. static encode_aux_threshmatch _vq_auxt__44u7__p5_0 = {
  149457. _vq_quantthresh__44u7__p5_0,
  149458. _vq_quantmap__44u7__p5_0,
  149459. 9,
  149460. 9
  149461. };
  149462. static static_codebook _44u7__p5_0 = {
  149463. 2, 81,
  149464. _vq_lengthlist__44u7__p5_0,
  149465. 1, -531628032, 1611661312, 4, 0,
  149466. _vq_quantlist__44u7__p5_0,
  149467. NULL,
  149468. &_vq_auxt__44u7__p5_0,
  149469. NULL,
  149470. 0
  149471. };
  149472. static long _vq_quantlist__44u7__p6_0[] = {
  149473. 4,
  149474. 3,
  149475. 5,
  149476. 2,
  149477. 6,
  149478. 1,
  149479. 7,
  149480. 0,
  149481. 8,
  149482. };
  149483. static long _vq_lengthlist__44u7__p6_0[] = {
  149484. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 8, 7,
  149485. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  149486. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  149487. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,11,11, 9,
  149488. 9, 9,10,10,11,10,12,11, 9, 9, 9,10,10,11,11,11,
  149489. 12,
  149490. };
  149491. static float _vq_quantthresh__44u7__p6_0[] = {
  149492. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149493. };
  149494. static long _vq_quantmap__44u7__p6_0[] = {
  149495. 7, 5, 3, 1, 0, 2, 4, 6,
  149496. 8,
  149497. };
  149498. static encode_aux_threshmatch _vq_auxt__44u7__p6_0 = {
  149499. _vq_quantthresh__44u7__p6_0,
  149500. _vq_quantmap__44u7__p6_0,
  149501. 9,
  149502. 9
  149503. };
  149504. static static_codebook _44u7__p6_0 = {
  149505. 2, 81,
  149506. _vq_lengthlist__44u7__p6_0,
  149507. 1, -531628032, 1611661312, 4, 0,
  149508. _vq_quantlist__44u7__p6_0,
  149509. NULL,
  149510. &_vq_auxt__44u7__p6_0,
  149511. NULL,
  149512. 0
  149513. };
  149514. static long _vq_quantlist__44u7__p7_0[] = {
  149515. 1,
  149516. 0,
  149517. 2,
  149518. };
  149519. static long _vq_lengthlist__44u7__p7_0[] = {
  149520. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 8, 9, 9, 7,
  149521. 10,10, 5, 8, 9, 7, 9,10, 8, 9, 9, 4, 9, 9, 9,11,
  149522. 10, 8,10,10, 7,11,10,10,10,12,10,12,12, 7,10,10,
  149523. 10,12,11,10,12,12, 5, 9, 9, 8,10,10, 9,11,11, 7,
  149524. 11,10,10,12,12,10,11,12, 7,10,11,10,12,12,10,12,
  149525. 10,
  149526. };
  149527. static float _vq_quantthresh__44u7__p7_0[] = {
  149528. -5.5, 5.5,
  149529. };
  149530. static long _vq_quantmap__44u7__p7_0[] = {
  149531. 1, 0, 2,
  149532. };
  149533. static encode_aux_threshmatch _vq_auxt__44u7__p7_0 = {
  149534. _vq_quantthresh__44u7__p7_0,
  149535. _vq_quantmap__44u7__p7_0,
  149536. 3,
  149537. 3
  149538. };
  149539. static static_codebook _44u7__p7_0 = {
  149540. 4, 81,
  149541. _vq_lengthlist__44u7__p7_0,
  149542. 1, -529137664, 1618345984, 2, 0,
  149543. _vq_quantlist__44u7__p7_0,
  149544. NULL,
  149545. &_vq_auxt__44u7__p7_0,
  149546. NULL,
  149547. 0
  149548. };
  149549. static long _vq_quantlist__44u7__p7_1[] = {
  149550. 5,
  149551. 4,
  149552. 6,
  149553. 3,
  149554. 7,
  149555. 2,
  149556. 8,
  149557. 1,
  149558. 9,
  149559. 0,
  149560. 10,
  149561. };
  149562. static long _vq_lengthlist__44u7__p7_1[] = {
  149563. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6,
  149564. 8, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6, 7, 8, 8, 8, 8,
  149565. 8, 6, 7, 6, 7, 7, 8, 8, 9, 9, 9, 9, 6, 6, 7, 7,
  149566. 7, 8, 8, 9, 9, 9, 9, 7, 8, 7, 8, 8, 9, 9, 9, 9,
  149567. 9, 9, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  149568. 9, 9, 9, 9,10, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  149569. 9, 9,10, 8, 8, 8, 9, 9, 9, 9,10, 9,10,10, 8, 8,
  149570. 8, 9, 9, 9, 9, 9,10,10,10,
  149571. };
  149572. static float _vq_quantthresh__44u7__p7_1[] = {
  149573. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149574. 3.5, 4.5,
  149575. };
  149576. static long _vq_quantmap__44u7__p7_1[] = {
  149577. 9, 7, 5, 3, 1, 0, 2, 4,
  149578. 6, 8, 10,
  149579. };
  149580. static encode_aux_threshmatch _vq_auxt__44u7__p7_1 = {
  149581. _vq_quantthresh__44u7__p7_1,
  149582. _vq_quantmap__44u7__p7_1,
  149583. 11,
  149584. 11
  149585. };
  149586. static static_codebook _44u7__p7_1 = {
  149587. 2, 121,
  149588. _vq_lengthlist__44u7__p7_1,
  149589. 1, -531365888, 1611661312, 4, 0,
  149590. _vq_quantlist__44u7__p7_1,
  149591. NULL,
  149592. &_vq_auxt__44u7__p7_1,
  149593. NULL,
  149594. 0
  149595. };
  149596. static long _vq_quantlist__44u7__p8_0[] = {
  149597. 5,
  149598. 4,
  149599. 6,
  149600. 3,
  149601. 7,
  149602. 2,
  149603. 8,
  149604. 1,
  149605. 9,
  149606. 0,
  149607. 10,
  149608. };
  149609. static long _vq_lengthlist__44u7__p8_0[] = {
  149610. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  149611. 9, 9,11,10,12,12, 5, 6, 5, 7, 7, 9, 9,10,11,12,
  149612. 12, 6, 7, 7, 8, 8,10,10,11,11,13,13, 6, 7, 7, 8,
  149613. 8,10,10,11,12,13,13, 8, 9, 9,10,10,11,11,12,12,
  149614. 14,14, 8, 9, 9,10,10,11,11,12,12,14,14,10,10,10,
  149615. 11,11,13,12,14,14,15,15,10,10,10,12,12,13,13,14,
  149616. 14,15,15,11,12,12,13,13,14,14,15,14,16,15,11,12,
  149617. 12,13,13,14,14,15,15,15,16,
  149618. };
  149619. static float _vq_quantthresh__44u7__p8_0[] = {
  149620. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  149621. 38.5, 49.5,
  149622. };
  149623. static long _vq_quantmap__44u7__p8_0[] = {
  149624. 9, 7, 5, 3, 1, 0, 2, 4,
  149625. 6, 8, 10,
  149626. };
  149627. static encode_aux_threshmatch _vq_auxt__44u7__p8_0 = {
  149628. _vq_quantthresh__44u7__p8_0,
  149629. _vq_quantmap__44u7__p8_0,
  149630. 11,
  149631. 11
  149632. };
  149633. static static_codebook _44u7__p8_0 = {
  149634. 2, 121,
  149635. _vq_lengthlist__44u7__p8_0,
  149636. 1, -524582912, 1618345984, 4, 0,
  149637. _vq_quantlist__44u7__p8_0,
  149638. NULL,
  149639. &_vq_auxt__44u7__p8_0,
  149640. NULL,
  149641. 0
  149642. };
  149643. static long _vq_quantlist__44u7__p8_1[] = {
  149644. 5,
  149645. 4,
  149646. 6,
  149647. 3,
  149648. 7,
  149649. 2,
  149650. 8,
  149651. 1,
  149652. 9,
  149653. 0,
  149654. 10,
  149655. };
  149656. static long _vq_lengthlist__44u7__p8_1[] = {
  149657. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  149658. 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  149659. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  149660. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  149661. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  149662. 7, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  149663. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  149664. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  149665. };
  149666. static float _vq_quantthresh__44u7__p8_1[] = {
  149667. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149668. 3.5, 4.5,
  149669. };
  149670. static long _vq_quantmap__44u7__p8_1[] = {
  149671. 9, 7, 5, 3, 1, 0, 2, 4,
  149672. 6, 8, 10,
  149673. };
  149674. static encode_aux_threshmatch _vq_auxt__44u7__p8_1 = {
  149675. _vq_quantthresh__44u7__p8_1,
  149676. _vq_quantmap__44u7__p8_1,
  149677. 11,
  149678. 11
  149679. };
  149680. static static_codebook _44u7__p8_1 = {
  149681. 2, 121,
  149682. _vq_lengthlist__44u7__p8_1,
  149683. 1, -531365888, 1611661312, 4, 0,
  149684. _vq_quantlist__44u7__p8_1,
  149685. NULL,
  149686. &_vq_auxt__44u7__p8_1,
  149687. NULL,
  149688. 0
  149689. };
  149690. static long _vq_quantlist__44u7__p9_0[] = {
  149691. 5,
  149692. 4,
  149693. 6,
  149694. 3,
  149695. 7,
  149696. 2,
  149697. 8,
  149698. 1,
  149699. 9,
  149700. 0,
  149701. 10,
  149702. };
  149703. static long _vq_lengthlist__44u7__p9_0[] = {
  149704. 1, 3, 3,10,10,10,10,10,10,10,10, 4,10,10,10,10,
  149705. 10,10,10,10,10,10, 4,10,10,10,10,10,10,10,10,10,
  149706. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  149707. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  149708. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  149709. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  149710. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  149711. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  149712. };
  149713. static float _vq_quantthresh__44u7__p9_0[] = {
  149714. -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5, 1592.5,
  149715. 2229.5, 2866.5,
  149716. };
  149717. static long _vq_quantmap__44u7__p9_0[] = {
  149718. 9, 7, 5, 3, 1, 0, 2, 4,
  149719. 6, 8, 10,
  149720. };
  149721. static encode_aux_threshmatch _vq_auxt__44u7__p9_0 = {
  149722. _vq_quantthresh__44u7__p9_0,
  149723. _vq_quantmap__44u7__p9_0,
  149724. 11,
  149725. 11
  149726. };
  149727. static static_codebook _44u7__p9_0 = {
  149728. 2, 121,
  149729. _vq_lengthlist__44u7__p9_0,
  149730. 1, -512171520, 1630791680, 4, 0,
  149731. _vq_quantlist__44u7__p9_0,
  149732. NULL,
  149733. &_vq_auxt__44u7__p9_0,
  149734. NULL,
  149735. 0
  149736. };
  149737. static long _vq_quantlist__44u7__p9_1[] = {
  149738. 6,
  149739. 5,
  149740. 7,
  149741. 4,
  149742. 8,
  149743. 3,
  149744. 9,
  149745. 2,
  149746. 10,
  149747. 1,
  149748. 11,
  149749. 0,
  149750. 12,
  149751. };
  149752. static long _vq_lengthlist__44u7__p9_1[] = {
  149753. 1, 4, 4, 6, 5, 8, 6, 9, 8,10, 9,11,10, 4, 6, 6,
  149754. 8, 8, 9, 9,11,10,11,11,11,11, 4, 6, 6, 8, 8,10,
  149755. 9,11,11,11,11,11,12, 6, 8, 8,10,10,11,11,12,12,
  149756. 13,12,13,13, 6, 8, 8,10,10,11,11,12,12,12,13,14,
  149757. 13, 8,10,10,11,11,12,13,14,14,14,14,15,15, 8,10,
  149758. 10,11,12,12,13,13,14,14,14,14,15, 9,11,11,13,13,
  149759. 14,14,15,14,16,15,17,15, 9,11,11,12,13,14,14,15,
  149760. 14,15,15,15,16,10,12,12,13,14,15,15,15,15,16,17,
  149761. 16,17,10,13,12,13,14,14,16,16,16,16,15,16,17,11,
  149762. 13,13,14,15,14,17,15,16,17,17,17,17,11,13,13,14,
  149763. 15,15,15,15,17,17,16,17,16,
  149764. };
  149765. static float _vq_quantthresh__44u7__p9_1[] = {
  149766. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  149767. 122.5, 171.5, 220.5, 269.5,
  149768. };
  149769. static long _vq_quantmap__44u7__p9_1[] = {
  149770. 11, 9, 7, 5, 3, 1, 0, 2,
  149771. 4, 6, 8, 10, 12,
  149772. };
  149773. static encode_aux_threshmatch _vq_auxt__44u7__p9_1 = {
  149774. _vq_quantthresh__44u7__p9_1,
  149775. _vq_quantmap__44u7__p9_1,
  149776. 13,
  149777. 13
  149778. };
  149779. static static_codebook _44u7__p9_1 = {
  149780. 2, 169,
  149781. _vq_lengthlist__44u7__p9_1,
  149782. 1, -518889472, 1622704128, 4, 0,
  149783. _vq_quantlist__44u7__p9_1,
  149784. NULL,
  149785. &_vq_auxt__44u7__p9_1,
  149786. NULL,
  149787. 0
  149788. };
  149789. static long _vq_quantlist__44u7__p9_2[] = {
  149790. 24,
  149791. 23,
  149792. 25,
  149793. 22,
  149794. 26,
  149795. 21,
  149796. 27,
  149797. 20,
  149798. 28,
  149799. 19,
  149800. 29,
  149801. 18,
  149802. 30,
  149803. 17,
  149804. 31,
  149805. 16,
  149806. 32,
  149807. 15,
  149808. 33,
  149809. 14,
  149810. 34,
  149811. 13,
  149812. 35,
  149813. 12,
  149814. 36,
  149815. 11,
  149816. 37,
  149817. 10,
  149818. 38,
  149819. 9,
  149820. 39,
  149821. 8,
  149822. 40,
  149823. 7,
  149824. 41,
  149825. 6,
  149826. 42,
  149827. 5,
  149828. 43,
  149829. 4,
  149830. 44,
  149831. 3,
  149832. 45,
  149833. 2,
  149834. 46,
  149835. 1,
  149836. 47,
  149837. 0,
  149838. 48,
  149839. };
  149840. static long _vq_lengthlist__44u7__p9_2[] = {
  149841. 2, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  149842. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  149843. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  149844. 8,
  149845. };
  149846. static float _vq_quantthresh__44u7__p9_2[] = {
  149847. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  149848. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  149849. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  149850. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  149851. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  149852. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  149853. };
  149854. static long _vq_quantmap__44u7__p9_2[] = {
  149855. 47, 45, 43, 41, 39, 37, 35, 33,
  149856. 31, 29, 27, 25, 23, 21, 19, 17,
  149857. 15, 13, 11, 9, 7, 5, 3, 1,
  149858. 0, 2, 4, 6, 8, 10, 12, 14,
  149859. 16, 18, 20, 22, 24, 26, 28, 30,
  149860. 32, 34, 36, 38, 40, 42, 44, 46,
  149861. 48,
  149862. };
  149863. static encode_aux_threshmatch _vq_auxt__44u7__p9_2 = {
  149864. _vq_quantthresh__44u7__p9_2,
  149865. _vq_quantmap__44u7__p9_2,
  149866. 49,
  149867. 49
  149868. };
  149869. static static_codebook _44u7__p9_2 = {
  149870. 1, 49,
  149871. _vq_lengthlist__44u7__p9_2,
  149872. 1, -526909440, 1611661312, 6, 0,
  149873. _vq_quantlist__44u7__p9_2,
  149874. NULL,
  149875. &_vq_auxt__44u7__p9_2,
  149876. NULL,
  149877. 0
  149878. };
  149879. static long _huff_lengthlist__44u7__short[] = {
  149880. 5,12,17,16,16,17,17,17,17,17, 4, 7,11,11,12, 9,
  149881. 17,10,17,17, 7, 7, 8, 9, 7, 9,11,10,15,17, 7, 9,
  149882. 10,11,10,12,14,12,16,17, 7, 8, 5, 7, 4, 7, 7, 8,
  149883. 16,16, 6,10, 9,10, 7,10,11,11,16,17, 6, 8, 8, 9,
  149884. 5, 7, 5, 8,16,17, 5, 5, 8, 7, 6, 7, 7, 6, 6,14,
  149885. 12,10,12,11, 7,11, 4, 4, 2, 7,17,15,15,15, 8,15,
  149886. 6, 8, 5, 9,
  149887. };
  149888. static static_codebook _huff_book__44u7__short = {
  149889. 2, 100,
  149890. _huff_lengthlist__44u7__short,
  149891. 0, 0, 0, 0, 0,
  149892. NULL,
  149893. NULL,
  149894. NULL,
  149895. NULL,
  149896. 0
  149897. };
  149898. static long _huff_lengthlist__44u8__long[] = {
  149899. 3, 9,13,14,14,15,14,14,15,15, 5, 4, 6, 8,10,12,
  149900. 12,14,15,15, 9, 5, 4, 5, 8,10,11,13,16,16,10, 7,
  149901. 4, 3, 5, 7, 9,11,13,13,10, 9, 7, 4, 4, 6, 8,10,
  149902. 12,14,13,11, 9, 6, 5, 5, 6, 8,12,14,13,11,10, 8,
  149903. 7, 6, 6, 7,10,14,13,11,12,10, 8, 7, 6, 6, 9,13,
  149904. 12,11,14,12,11, 9, 8, 7, 9,11,11,12,14,13,14,11,
  149905. 10, 8, 8, 9,
  149906. };
  149907. static static_codebook _huff_book__44u8__long = {
  149908. 2, 100,
  149909. _huff_lengthlist__44u8__long,
  149910. 0, 0, 0, 0, 0,
  149911. NULL,
  149912. NULL,
  149913. NULL,
  149914. NULL,
  149915. 0
  149916. };
  149917. static long _huff_lengthlist__44u8__short[] = {
  149918. 6,14,18,18,17,17,17,17,17,17, 4, 7, 9, 9,10,13,
  149919. 15,17,17,17, 6, 7, 5, 6, 8,11,16,17,16,17, 5, 7,
  149920. 5, 4, 6,10,14,17,17,17, 6, 6, 6, 5, 7,10,13,16,
  149921. 17,17, 7, 6, 7, 7, 7, 8, 7,10,15,16,12, 9, 9, 6,
  149922. 6, 5, 3, 5,11,15,14,14,13, 5, 5, 7, 3, 4, 8,15,
  149923. 17,17,13, 7, 7,10, 6, 6,10,15,17,17,16,10,11,14,
  149924. 10,10,15,17,
  149925. };
  149926. static static_codebook _huff_book__44u8__short = {
  149927. 2, 100,
  149928. _huff_lengthlist__44u8__short,
  149929. 0, 0, 0, 0, 0,
  149930. NULL,
  149931. NULL,
  149932. NULL,
  149933. NULL,
  149934. 0
  149935. };
  149936. static long _vq_quantlist__44u8_p1_0[] = {
  149937. 1,
  149938. 0,
  149939. 2,
  149940. };
  149941. static long _vq_lengthlist__44u8_p1_0[] = {
  149942. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 8, 9, 9, 7,
  149943. 9, 9, 5, 7, 7, 7, 9, 9, 8, 9, 9, 5, 7, 7, 7, 9,
  149944. 9, 7, 9, 9, 7, 9, 9, 9,10,11, 9,11,10, 7, 9, 9,
  149945. 9,11,10, 9,10,11, 5, 7, 7, 7, 9, 9, 7, 9, 9, 7,
  149946. 9, 9, 9,11,10, 9,10,10, 8, 9, 9, 9,11,11, 9,11,
  149947. 10,
  149948. };
  149949. static float _vq_quantthresh__44u8_p1_0[] = {
  149950. -0.5, 0.5,
  149951. };
  149952. static long _vq_quantmap__44u8_p1_0[] = {
  149953. 1, 0, 2,
  149954. };
  149955. static encode_aux_threshmatch _vq_auxt__44u8_p1_0 = {
  149956. _vq_quantthresh__44u8_p1_0,
  149957. _vq_quantmap__44u8_p1_0,
  149958. 3,
  149959. 3
  149960. };
  149961. static static_codebook _44u8_p1_0 = {
  149962. 4, 81,
  149963. _vq_lengthlist__44u8_p1_0,
  149964. 1, -535822336, 1611661312, 2, 0,
  149965. _vq_quantlist__44u8_p1_0,
  149966. NULL,
  149967. &_vq_auxt__44u8_p1_0,
  149968. NULL,
  149969. 0
  149970. };
  149971. static long _vq_quantlist__44u8_p2_0[] = {
  149972. 2,
  149973. 1,
  149974. 3,
  149975. 0,
  149976. 4,
  149977. };
  149978. static long _vq_lengthlist__44u8_p2_0[] = {
  149979. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  149980. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  149981. 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,10,
  149982. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  149983. 10, 9,10, 9,12,11, 9,10,10,12,12, 8, 9, 9,12,11,
  149984. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,14,11,
  149985. 11,12,13,14, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  149986. 10,12,12,11,12,11,13,13,11,12,12,14,14, 5, 7, 7,
  149987. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  149988. 12, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  149989. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,12,13, 6,
  149990. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  149991. 10,13,12,10,11,11,13,13, 9,10,10,12,12,10,11,11,
  149992. 13,13,10,11,11,13,13,12,12,13,13,14,12,13,13,14,
  149993. 14, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  149994. 11,13,12,14,13,12,13,13,14,14, 5, 7, 7, 9, 9, 7,
  149995. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  149996. 10,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  149997. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  149998. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  149999. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  150000. 10,11,12,13,12,13,13,14,14,12,12,13,13,14, 9,10,
  150001. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,13,
  150002. 15,14,12,13,13,14,13, 8, 9, 9,11,11, 9,10,10,12,
  150003. 12, 9,10,10,12,12,12,12,12,14,13,11,12,12,14,14,
  150004. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  150005. 13,13,14,15,12,13,13,14,15, 9,10,10,12,12,10,11,
  150006. 10,13,12,10,11,11,13,13,12,13,12,15,14,12,13,13,
  150007. 14,15,11,12,12,14,14,12,13,13,14,14,12,13,13,15,
  150008. 14,14,14,14,14,16,14,14,15,16,16,11,12,12,14,14,
  150009. 11,12,12,14,14,12,13,13,14,15,13,14,13,16,14,14,
  150010. 14,14,16,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  150011. 10,12,12,11,12,12,14,13,11,12,12,14,14, 9,10,10,
  150012. 12,12,10,11,11,13,13,10,10,11,12,13,12,13,13,15,
  150013. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  150014. 10,11,11,13,13,12,13,13,14,14,12,13,13,15,14,11,
  150015. 12,12,14,13,12,13,13,15,14,11,12,12,13,14,14,15,
  150016. 14,16,15,13,13,14,13,16,11,12,12,14,14,12,13,13,
  150017. 14,15,12,13,12,15,14,14,14,14,16,15,14,15,13,16,
  150018. 14,
  150019. };
  150020. static float _vq_quantthresh__44u8_p2_0[] = {
  150021. -1.5, -0.5, 0.5, 1.5,
  150022. };
  150023. static long _vq_quantmap__44u8_p2_0[] = {
  150024. 3, 1, 0, 2, 4,
  150025. };
  150026. static encode_aux_threshmatch _vq_auxt__44u8_p2_0 = {
  150027. _vq_quantthresh__44u8_p2_0,
  150028. _vq_quantmap__44u8_p2_0,
  150029. 5,
  150030. 5
  150031. };
  150032. static static_codebook _44u8_p2_0 = {
  150033. 4, 625,
  150034. _vq_lengthlist__44u8_p2_0,
  150035. 1, -533725184, 1611661312, 3, 0,
  150036. _vq_quantlist__44u8_p2_0,
  150037. NULL,
  150038. &_vq_auxt__44u8_p2_0,
  150039. NULL,
  150040. 0
  150041. };
  150042. static long _vq_quantlist__44u8_p3_0[] = {
  150043. 4,
  150044. 3,
  150045. 5,
  150046. 2,
  150047. 6,
  150048. 1,
  150049. 7,
  150050. 0,
  150051. 8,
  150052. };
  150053. static long _vq_lengthlist__44u8_p3_0[] = {
  150054. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  150055. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  150056. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  150057. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  150058. 9, 9,10,10,11,10,12,11, 9, 9, 9, 9,10,11,11,11,
  150059. 12,
  150060. };
  150061. static float _vq_quantthresh__44u8_p3_0[] = {
  150062. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150063. };
  150064. static long _vq_quantmap__44u8_p3_0[] = {
  150065. 7, 5, 3, 1, 0, 2, 4, 6,
  150066. 8,
  150067. };
  150068. static encode_aux_threshmatch _vq_auxt__44u8_p3_0 = {
  150069. _vq_quantthresh__44u8_p3_0,
  150070. _vq_quantmap__44u8_p3_0,
  150071. 9,
  150072. 9
  150073. };
  150074. static static_codebook _44u8_p3_0 = {
  150075. 2, 81,
  150076. _vq_lengthlist__44u8_p3_0,
  150077. 1, -531628032, 1611661312, 4, 0,
  150078. _vq_quantlist__44u8_p3_0,
  150079. NULL,
  150080. &_vq_auxt__44u8_p3_0,
  150081. NULL,
  150082. 0
  150083. };
  150084. static long _vq_quantlist__44u8_p4_0[] = {
  150085. 8,
  150086. 7,
  150087. 9,
  150088. 6,
  150089. 10,
  150090. 5,
  150091. 11,
  150092. 4,
  150093. 12,
  150094. 3,
  150095. 13,
  150096. 2,
  150097. 14,
  150098. 1,
  150099. 15,
  150100. 0,
  150101. 16,
  150102. };
  150103. static long _vq_lengthlist__44u8_p4_0[] = {
  150104. 4, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,11,11,11,
  150105. 11, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  150106. 12,12, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  150107. 11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  150108. 11,11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,
  150109. 10,11,11,12,12, 7, 7, 7, 8, 8, 9, 8,10, 9,10, 9,
  150110. 11,10,12,11,13,12, 7, 7, 7, 8, 8, 8, 9, 9,10, 9,
  150111. 10,10,11,11,12,12,13, 8, 8, 8, 9, 9, 9, 9,10,10,
  150112. 11,10,11,11,12,12,13,13, 8, 8, 8, 9, 9, 9,10,10,
  150113. 10,10,11,11,11,12,12,12,13, 8, 9, 9, 9, 9,10, 9,
  150114. 11,10,11,11,12,11,13,12,13,13, 8, 9, 9, 9, 9, 9,
  150115. 10,10,11,11,11,11,12,12,13,13,13,10,10,10,10,10,
  150116. 11,10,11,11,12,11,13,12,13,13,14,13,10,10,10,10,
  150117. 10,10,11,11,11,11,12,12,13,13,13,13,14,11,11,11,
  150118. 11,11,12,11,12,12,13,12,13,13,14,13,14,14,11,11,
  150119. 11,11,11,11,12,12,12,12,13,13,13,13,14,14,14,11,
  150120. 12,12,12,12,13,12,13,12,13,13,14,13,14,14,14,14,
  150121. 11,12,12,12,12,12,12,13,13,13,13,13,14,14,14,14,
  150122. 14,
  150123. };
  150124. static float _vq_quantthresh__44u8_p4_0[] = {
  150125. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  150126. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  150127. };
  150128. static long _vq_quantmap__44u8_p4_0[] = {
  150129. 15, 13, 11, 9, 7, 5, 3, 1,
  150130. 0, 2, 4, 6, 8, 10, 12, 14,
  150131. 16,
  150132. };
  150133. static encode_aux_threshmatch _vq_auxt__44u8_p4_0 = {
  150134. _vq_quantthresh__44u8_p4_0,
  150135. _vq_quantmap__44u8_p4_0,
  150136. 17,
  150137. 17
  150138. };
  150139. static static_codebook _44u8_p4_0 = {
  150140. 2, 289,
  150141. _vq_lengthlist__44u8_p4_0,
  150142. 1, -529530880, 1611661312, 5, 0,
  150143. _vq_quantlist__44u8_p4_0,
  150144. NULL,
  150145. &_vq_auxt__44u8_p4_0,
  150146. NULL,
  150147. 0
  150148. };
  150149. static long _vq_quantlist__44u8_p5_0[] = {
  150150. 1,
  150151. 0,
  150152. 2,
  150153. };
  150154. static long _vq_lengthlist__44u8_p5_0[] = {
  150155. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  150156. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  150157. 10, 8,10,10, 7,10,10, 9,10,12, 9,12,11, 7,10,10,
  150158. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  150159. 10,10, 9,11,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  150160. 10,
  150161. };
  150162. static float _vq_quantthresh__44u8_p5_0[] = {
  150163. -5.5, 5.5,
  150164. };
  150165. static long _vq_quantmap__44u8_p5_0[] = {
  150166. 1, 0, 2,
  150167. };
  150168. static encode_aux_threshmatch _vq_auxt__44u8_p5_0 = {
  150169. _vq_quantthresh__44u8_p5_0,
  150170. _vq_quantmap__44u8_p5_0,
  150171. 3,
  150172. 3
  150173. };
  150174. static static_codebook _44u8_p5_0 = {
  150175. 4, 81,
  150176. _vq_lengthlist__44u8_p5_0,
  150177. 1, -529137664, 1618345984, 2, 0,
  150178. _vq_quantlist__44u8_p5_0,
  150179. NULL,
  150180. &_vq_auxt__44u8_p5_0,
  150181. NULL,
  150182. 0
  150183. };
  150184. static long _vq_quantlist__44u8_p5_1[] = {
  150185. 5,
  150186. 4,
  150187. 6,
  150188. 3,
  150189. 7,
  150190. 2,
  150191. 8,
  150192. 1,
  150193. 9,
  150194. 0,
  150195. 10,
  150196. };
  150197. static long _vq_lengthlist__44u8_p5_1[] = {
  150198. 4, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 5, 5, 6, 6,
  150199. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 7, 8, 8,
  150200. 8, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 6, 6, 6, 7,
  150201. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  150202. 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 7, 8, 7,
  150203. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  150204. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 8, 8,
  150205. 8, 8, 8, 8, 8, 8, 8, 9, 9,
  150206. };
  150207. static float _vq_quantthresh__44u8_p5_1[] = {
  150208. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150209. 3.5, 4.5,
  150210. };
  150211. static long _vq_quantmap__44u8_p5_1[] = {
  150212. 9, 7, 5, 3, 1, 0, 2, 4,
  150213. 6, 8, 10,
  150214. };
  150215. static encode_aux_threshmatch _vq_auxt__44u8_p5_1 = {
  150216. _vq_quantthresh__44u8_p5_1,
  150217. _vq_quantmap__44u8_p5_1,
  150218. 11,
  150219. 11
  150220. };
  150221. static static_codebook _44u8_p5_1 = {
  150222. 2, 121,
  150223. _vq_lengthlist__44u8_p5_1,
  150224. 1, -531365888, 1611661312, 4, 0,
  150225. _vq_quantlist__44u8_p5_1,
  150226. NULL,
  150227. &_vq_auxt__44u8_p5_1,
  150228. NULL,
  150229. 0
  150230. };
  150231. static long _vq_quantlist__44u8_p6_0[] = {
  150232. 6,
  150233. 5,
  150234. 7,
  150235. 4,
  150236. 8,
  150237. 3,
  150238. 9,
  150239. 2,
  150240. 10,
  150241. 1,
  150242. 11,
  150243. 0,
  150244. 12,
  150245. };
  150246. static long _vq_lengthlist__44u8_p6_0[] = {
  150247. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  150248. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7, 8,
  150249. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 7, 8, 8, 8, 8, 9,
  150250. 9,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 8,10, 9,11,
  150251. 10, 7, 8, 8, 8, 8, 8, 9, 9, 9,10,10,11,11, 7, 8,
  150252. 8, 8, 8, 9, 8, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  150253. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  150254. 9,10,10,11,11, 9, 9, 9, 9,10,10,10,10,10,10,11,
  150255. 11,12, 9, 9, 9,10, 9,10,10,10,10,11,10,12,11,10,
  150256. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  150257. 11,11,11,11,11,12,11,12,12,
  150258. };
  150259. static float _vq_quantthresh__44u8_p6_0[] = {
  150260. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  150261. 12.5, 17.5, 22.5, 27.5,
  150262. };
  150263. static long _vq_quantmap__44u8_p6_0[] = {
  150264. 11, 9, 7, 5, 3, 1, 0, 2,
  150265. 4, 6, 8, 10, 12,
  150266. };
  150267. static encode_aux_threshmatch _vq_auxt__44u8_p6_0 = {
  150268. _vq_quantthresh__44u8_p6_0,
  150269. _vq_quantmap__44u8_p6_0,
  150270. 13,
  150271. 13
  150272. };
  150273. static static_codebook _44u8_p6_0 = {
  150274. 2, 169,
  150275. _vq_lengthlist__44u8_p6_0,
  150276. 1, -526516224, 1616117760, 4, 0,
  150277. _vq_quantlist__44u8_p6_0,
  150278. NULL,
  150279. &_vq_auxt__44u8_p6_0,
  150280. NULL,
  150281. 0
  150282. };
  150283. static long _vq_quantlist__44u8_p6_1[] = {
  150284. 2,
  150285. 1,
  150286. 3,
  150287. 0,
  150288. 4,
  150289. };
  150290. static long _vq_lengthlist__44u8_p6_1[] = {
  150291. 3, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  150292. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  150293. };
  150294. static float _vq_quantthresh__44u8_p6_1[] = {
  150295. -1.5, -0.5, 0.5, 1.5,
  150296. };
  150297. static long _vq_quantmap__44u8_p6_1[] = {
  150298. 3, 1, 0, 2, 4,
  150299. };
  150300. static encode_aux_threshmatch _vq_auxt__44u8_p6_1 = {
  150301. _vq_quantthresh__44u8_p6_1,
  150302. _vq_quantmap__44u8_p6_1,
  150303. 5,
  150304. 5
  150305. };
  150306. static static_codebook _44u8_p6_1 = {
  150307. 2, 25,
  150308. _vq_lengthlist__44u8_p6_1,
  150309. 1, -533725184, 1611661312, 3, 0,
  150310. _vq_quantlist__44u8_p6_1,
  150311. NULL,
  150312. &_vq_auxt__44u8_p6_1,
  150313. NULL,
  150314. 0
  150315. };
  150316. static long _vq_quantlist__44u8_p7_0[] = {
  150317. 6,
  150318. 5,
  150319. 7,
  150320. 4,
  150321. 8,
  150322. 3,
  150323. 9,
  150324. 2,
  150325. 10,
  150326. 1,
  150327. 11,
  150328. 0,
  150329. 12,
  150330. };
  150331. static long _vq_lengthlist__44u8_p7_0[] = {
  150332. 1, 4, 5, 6, 6, 7, 7, 8, 8,10,10,11,11, 5, 6, 6,
  150333. 7, 7, 8, 8, 9, 9,11,10,12,11, 5, 6, 6, 7, 7, 8,
  150334. 8, 9, 9,10,11,11,12, 6, 7, 7, 8, 8, 9, 9,10,10,
  150335. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,12,13,
  150336. 12, 7, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  150337. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  150338. 11,11,12,12,13,13,14,14, 9, 9, 9,10,10,11,11,12,
  150339. 12,13,13,14,14,10,11,11,12,11,13,12,13,13,14,14,
  150340. 15,15,10,11,11,11,12,12,13,13,14,14,14,15,15,11,
  150341. 12,12,13,13,14,13,15,14,15,15,16,15,11,11,12,13,
  150342. 13,13,14,14,14,15,15,15,16,
  150343. };
  150344. static float _vq_quantthresh__44u8_p7_0[] = {
  150345. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  150346. 27.5, 38.5, 49.5, 60.5,
  150347. };
  150348. static long _vq_quantmap__44u8_p7_0[] = {
  150349. 11, 9, 7, 5, 3, 1, 0, 2,
  150350. 4, 6, 8, 10, 12,
  150351. };
  150352. static encode_aux_threshmatch _vq_auxt__44u8_p7_0 = {
  150353. _vq_quantthresh__44u8_p7_0,
  150354. _vq_quantmap__44u8_p7_0,
  150355. 13,
  150356. 13
  150357. };
  150358. static static_codebook _44u8_p7_0 = {
  150359. 2, 169,
  150360. _vq_lengthlist__44u8_p7_0,
  150361. 1, -523206656, 1618345984, 4, 0,
  150362. _vq_quantlist__44u8_p7_0,
  150363. NULL,
  150364. &_vq_auxt__44u8_p7_0,
  150365. NULL,
  150366. 0
  150367. };
  150368. static long _vq_quantlist__44u8_p7_1[] = {
  150369. 5,
  150370. 4,
  150371. 6,
  150372. 3,
  150373. 7,
  150374. 2,
  150375. 8,
  150376. 1,
  150377. 9,
  150378. 0,
  150379. 10,
  150380. };
  150381. static long _vq_lengthlist__44u8_p7_1[] = {
  150382. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  150383. 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  150384. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  150385. 7, 7, 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8,
  150386. 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 7, 7, 7,
  150387. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  150388. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  150389. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  150390. };
  150391. static float _vq_quantthresh__44u8_p7_1[] = {
  150392. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150393. 3.5, 4.5,
  150394. };
  150395. static long _vq_quantmap__44u8_p7_1[] = {
  150396. 9, 7, 5, 3, 1, 0, 2, 4,
  150397. 6, 8, 10,
  150398. };
  150399. static encode_aux_threshmatch _vq_auxt__44u8_p7_1 = {
  150400. _vq_quantthresh__44u8_p7_1,
  150401. _vq_quantmap__44u8_p7_1,
  150402. 11,
  150403. 11
  150404. };
  150405. static static_codebook _44u8_p7_1 = {
  150406. 2, 121,
  150407. _vq_lengthlist__44u8_p7_1,
  150408. 1, -531365888, 1611661312, 4, 0,
  150409. _vq_quantlist__44u8_p7_1,
  150410. NULL,
  150411. &_vq_auxt__44u8_p7_1,
  150412. NULL,
  150413. 0
  150414. };
  150415. static long _vq_quantlist__44u8_p8_0[] = {
  150416. 7,
  150417. 6,
  150418. 8,
  150419. 5,
  150420. 9,
  150421. 4,
  150422. 10,
  150423. 3,
  150424. 11,
  150425. 2,
  150426. 12,
  150427. 1,
  150428. 13,
  150429. 0,
  150430. 14,
  150431. };
  150432. static long _vq_lengthlist__44u8_p8_0[] = {
  150433. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8,10, 9,11,10, 4,
  150434. 6, 6, 8, 8,10, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  150435. 6, 8, 8,10,10, 9, 9,10,10,11,11,11,12, 7, 8, 8,
  150436. 10,10,11,11,11,10,12,11,12,12,13,11, 7, 8, 8,10,
  150437. 10,11,11,10,10,11,11,12,12,13,13, 8,10,10,11,11,
  150438. 12,11,12,11,13,12,13,12,14,13, 8,10, 9,11,11,12,
  150439. 12,12,12,12,12,13,13,14,13, 8, 9, 9,11,10,12,11,
  150440. 13,12,13,13,14,13,14,13, 8, 9, 9,10,11,12,12,12,
  150441. 12,13,13,14,15,14,14, 9,10,10,12,11,13,12,13,13,
  150442. 14,13,14,14,14,14, 9,10,10,12,12,12,12,13,13,14,
  150443. 14,14,15,14,14,10,11,11,13,12,13,12,14,14,14,14,
  150444. 14,14,15,15,10,11,11,12,12,13,13,14,14,14,15,15,
  150445. 14,16,15,11,12,12,13,12,14,14,14,13,15,14,15,15,
  150446. 15,17,11,12,12,13,13,14,14,14,15,15,14,15,15,14,
  150447. 17,
  150448. };
  150449. static float _vq_quantthresh__44u8_p8_0[] = {
  150450. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  150451. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  150452. };
  150453. static long _vq_quantmap__44u8_p8_0[] = {
  150454. 13, 11, 9, 7, 5, 3, 1, 0,
  150455. 2, 4, 6, 8, 10, 12, 14,
  150456. };
  150457. static encode_aux_threshmatch _vq_auxt__44u8_p8_0 = {
  150458. _vq_quantthresh__44u8_p8_0,
  150459. _vq_quantmap__44u8_p8_0,
  150460. 15,
  150461. 15
  150462. };
  150463. static static_codebook _44u8_p8_0 = {
  150464. 2, 225,
  150465. _vq_lengthlist__44u8_p8_0,
  150466. 1, -520986624, 1620377600, 4, 0,
  150467. _vq_quantlist__44u8_p8_0,
  150468. NULL,
  150469. &_vq_auxt__44u8_p8_0,
  150470. NULL,
  150471. 0
  150472. };
  150473. static long _vq_quantlist__44u8_p8_1[] = {
  150474. 10,
  150475. 9,
  150476. 11,
  150477. 8,
  150478. 12,
  150479. 7,
  150480. 13,
  150481. 6,
  150482. 14,
  150483. 5,
  150484. 15,
  150485. 4,
  150486. 16,
  150487. 3,
  150488. 17,
  150489. 2,
  150490. 18,
  150491. 1,
  150492. 19,
  150493. 0,
  150494. 20,
  150495. };
  150496. static long _vq_lengthlist__44u8_p8_1[] = {
  150497. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  150498. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  150499. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 5, 6, 6, 7, 7, 8,
  150500. 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  150501. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  150502. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  150503. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  150504. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10, 8, 8,
  150505. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  150506. 10, 9,10, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,
  150507. 10,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9,
  150508. 9, 9, 9, 9, 9, 9,10,10,10,10, 9,10,10, 9, 9, 9,
  150509. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  150510. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  150511. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,
  150512. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  150513. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  150514. 10, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  150515. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  150516. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  150517. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150518. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  150519. 10,10,10,10,10, 9, 9, 9,10, 9,10,10,10,10,10,10,
  150520. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  150521. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  150522. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  150523. 10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,10,
  150524. 10,10,10,10,10,10,10,10,10,
  150525. };
  150526. static float _vq_quantthresh__44u8_p8_1[] = {
  150527. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  150528. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  150529. 6.5, 7.5, 8.5, 9.5,
  150530. };
  150531. static long _vq_quantmap__44u8_p8_1[] = {
  150532. 19, 17, 15, 13, 11, 9, 7, 5,
  150533. 3, 1, 0, 2, 4, 6, 8, 10,
  150534. 12, 14, 16, 18, 20,
  150535. };
  150536. static encode_aux_threshmatch _vq_auxt__44u8_p8_1 = {
  150537. _vq_quantthresh__44u8_p8_1,
  150538. _vq_quantmap__44u8_p8_1,
  150539. 21,
  150540. 21
  150541. };
  150542. static static_codebook _44u8_p8_1 = {
  150543. 2, 441,
  150544. _vq_lengthlist__44u8_p8_1,
  150545. 1, -529268736, 1611661312, 5, 0,
  150546. _vq_quantlist__44u8_p8_1,
  150547. NULL,
  150548. &_vq_auxt__44u8_p8_1,
  150549. NULL,
  150550. 0
  150551. };
  150552. static long _vq_quantlist__44u8_p9_0[] = {
  150553. 4,
  150554. 3,
  150555. 5,
  150556. 2,
  150557. 6,
  150558. 1,
  150559. 7,
  150560. 0,
  150561. 8,
  150562. };
  150563. static long _vq_lengthlist__44u8_p9_0[] = {
  150564. 1, 3, 3, 9, 9, 9, 9, 9, 9, 4, 9, 9, 9, 9, 9, 9,
  150565. 9, 9, 5, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  150566. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  150567. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  150568. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  150569. 8,
  150570. };
  150571. static float _vq_quantthresh__44u8_p9_0[] = {
  150572. -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5, 2327.5, 3258.5,
  150573. };
  150574. static long _vq_quantmap__44u8_p9_0[] = {
  150575. 7, 5, 3, 1, 0, 2, 4, 6,
  150576. 8,
  150577. };
  150578. static encode_aux_threshmatch _vq_auxt__44u8_p9_0 = {
  150579. _vq_quantthresh__44u8_p9_0,
  150580. _vq_quantmap__44u8_p9_0,
  150581. 9,
  150582. 9
  150583. };
  150584. static static_codebook _44u8_p9_0 = {
  150585. 2, 81,
  150586. _vq_lengthlist__44u8_p9_0,
  150587. 1, -511895552, 1631393792, 4, 0,
  150588. _vq_quantlist__44u8_p9_0,
  150589. NULL,
  150590. &_vq_auxt__44u8_p9_0,
  150591. NULL,
  150592. 0
  150593. };
  150594. static long _vq_quantlist__44u8_p9_1[] = {
  150595. 9,
  150596. 8,
  150597. 10,
  150598. 7,
  150599. 11,
  150600. 6,
  150601. 12,
  150602. 5,
  150603. 13,
  150604. 4,
  150605. 14,
  150606. 3,
  150607. 15,
  150608. 2,
  150609. 16,
  150610. 1,
  150611. 17,
  150612. 0,
  150613. 18,
  150614. };
  150615. static long _vq_lengthlist__44u8_p9_1[] = {
  150616. 1, 4, 4, 7, 7, 8, 7, 8, 6, 9, 7,10, 8,11,10,11,
  150617. 11,11,11, 4, 7, 6, 9, 9,10, 9, 9, 9,10,10,11,10,
  150618. 11,10,11,11,13,11, 4, 7, 7, 9, 9, 9, 9, 9, 9,10,
  150619. 10,11,10,11,11,11,12,11,12, 7, 9, 8,11,11,11,11,
  150620. 10,10,11,11,12,12,12,12,12,12,14,13, 7, 8, 9,10,
  150621. 11,11,11,10,10,11,11,11,11,12,12,14,12,13,14, 8,
  150622. 9, 9,11,11,11,11,11,11,12,12,14,12,15,14,14,14,
  150623. 15,14, 8, 9, 9,11,11,11,11,12,11,12,12,13,13,13,
  150624. 13,13,13,14,14, 8, 9, 9,11,10,12,11,12,12,13,13,
  150625. 13,13,15,14,14,14,16,16, 8, 9, 9,10,11,11,12,12,
  150626. 12,13,13,13,14,14,14,15,16,15,15, 9,10,10,11,12,
  150627. 12,13,13,13,14,14,16,14,14,16,16,16,16,15, 9,10,
  150628. 10,11,11,12,13,13,14,15,14,16,14,15,16,16,16,16,
  150629. 15,10,11,11,12,13,13,14,15,15,15,15,15,16,15,16,
  150630. 15,16,15,15,10,11,11,13,13,14,13,13,15,14,15,15,
  150631. 16,15,15,15,16,15,16,10,12,12,14,14,14,14,14,16,
  150632. 16,15,15,15,16,16,16,16,16,16,11,12,12,14,14,14,
  150633. 14,15,15,16,15,16,15,16,15,16,16,16,16,12,12,13,
  150634. 14,14,15,16,16,16,16,16,16,15,16,16,16,16,16,16,
  150635. 12,13,13,14,14,14,14,15,16,15,16,16,16,16,16,16,
  150636. 16,16,16,12,13,14,14,14,16,15,16,15,16,16,16,16,
  150637. 16,16,16,16,16,16,12,14,13,14,15,15,15,16,15,16,
  150638. 16,15,16,16,16,16,16,16,16,
  150639. };
  150640. static float _vq_quantthresh__44u8_p9_1[] = {
  150641. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  150642. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  150643. 367.5, 416.5,
  150644. };
  150645. static long _vq_quantmap__44u8_p9_1[] = {
  150646. 17, 15, 13, 11, 9, 7, 5, 3,
  150647. 1, 0, 2, 4, 6, 8, 10, 12,
  150648. 14, 16, 18,
  150649. };
  150650. static encode_aux_threshmatch _vq_auxt__44u8_p9_1 = {
  150651. _vq_quantthresh__44u8_p9_1,
  150652. _vq_quantmap__44u8_p9_1,
  150653. 19,
  150654. 19
  150655. };
  150656. static static_codebook _44u8_p9_1 = {
  150657. 2, 361,
  150658. _vq_lengthlist__44u8_p9_1,
  150659. 1, -518287360, 1622704128, 5, 0,
  150660. _vq_quantlist__44u8_p9_1,
  150661. NULL,
  150662. &_vq_auxt__44u8_p9_1,
  150663. NULL,
  150664. 0
  150665. };
  150666. static long _vq_quantlist__44u8_p9_2[] = {
  150667. 24,
  150668. 23,
  150669. 25,
  150670. 22,
  150671. 26,
  150672. 21,
  150673. 27,
  150674. 20,
  150675. 28,
  150676. 19,
  150677. 29,
  150678. 18,
  150679. 30,
  150680. 17,
  150681. 31,
  150682. 16,
  150683. 32,
  150684. 15,
  150685. 33,
  150686. 14,
  150687. 34,
  150688. 13,
  150689. 35,
  150690. 12,
  150691. 36,
  150692. 11,
  150693. 37,
  150694. 10,
  150695. 38,
  150696. 9,
  150697. 39,
  150698. 8,
  150699. 40,
  150700. 7,
  150701. 41,
  150702. 6,
  150703. 42,
  150704. 5,
  150705. 43,
  150706. 4,
  150707. 44,
  150708. 3,
  150709. 45,
  150710. 2,
  150711. 46,
  150712. 1,
  150713. 47,
  150714. 0,
  150715. 48,
  150716. };
  150717. static long _vq_lengthlist__44u8_p9_2[] = {
  150718. 2, 3, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  150719. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  150720. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  150721. 7,
  150722. };
  150723. static float _vq_quantthresh__44u8_p9_2[] = {
  150724. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  150725. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  150726. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  150727. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  150728. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  150729. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  150730. };
  150731. static long _vq_quantmap__44u8_p9_2[] = {
  150732. 47, 45, 43, 41, 39, 37, 35, 33,
  150733. 31, 29, 27, 25, 23, 21, 19, 17,
  150734. 15, 13, 11, 9, 7, 5, 3, 1,
  150735. 0, 2, 4, 6, 8, 10, 12, 14,
  150736. 16, 18, 20, 22, 24, 26, 28, 30,
  150737. 32, 34, 36, 38, 40, 42, 44, 46,
  150738. 48,
  150739. };
  150740. static encode_aux_threshmatch _vq_auxt__44u8_p9_2 = {
  150741. _vq_quantthresh__44u8_p9_2,
  150742. _vq_quantmap__44u8_p9_2,
  150743. 49,
  150744. 49
  150745. };
  150746. static static_codebook _44u8_p9_2 = {
  150747. 1, 49,
  150748. _vq_lengthlist__44u8_p9_2,
  150749. 1, -526909440, 1611661312, 6, 0,
  150750. _vq_quantlist__44u8_p9_2,
  150751. NULL,
  150752. &_vq_auxt__44u8_p9_2,
  150753. NULL,
  150754. 0
  150755. };
  150756. static long _huff_lengthlist__44u9__long[] = {
  150757. 3, 9,13,13,14,15,14,14,15,15, 5, 5, 9,10,12,12,
  150758. 13,14,16,15,10, 6, 6, 6, 8,11,12,13,16,15,11, 7,
  150759. 5, 3, 5, 8,10,12,15,15,10,10, 7, 4, 3, 5, 8,10,
  150760. 12,12,12,12, 9, 7, 5, 4, 6, 8,10,13,13,12,11, 9,
  150761. 7, 5, 5, 6, 9,12,14,12,12,10, 8, 6, 6, 6, 7,11,
  150762. 13,12,14,13,10, 8, 7, 7, 7,10,11,11,12,13,12,11,
  150763. 10, 8, 8, 9,
  150764. };
  150765. static static_codebook _huff_book__44u9__long = {
  150766. 2, 100,
  150767. _huff_lengthlist__44u9__long,
  150768. 0, 0, 0, 0, 0,
  150769. NULL,
  150770. NULL,
  150771. NULL,
  150772. NULL,
  150773. 0
  150774. };
  150775. static long _huff_lengthlist__44u9__short[] = {
  150776. 9,16,18,18,17,17,17,17,17,17, 5, 8,11,12,11,12,
  150777. 17,17,16,16, 6, 6, 8, 8, 9,10,14,15,16,16, 6, 7,
  150778. 7, 4, 6, 9,13,16,16,16, 6, 6, 7, 4, 5, 8,11,15,
  150779. 17,16, 7, 6, 7, 6, 6, 8, 9,10,14,16,11, 8, 8, 7,
  150780. 6, 6, 3, 4,10,15,14,12,12,10, 5, 6, 3, 3, 8,13,
  150781. 15,17,15,11, 6, 8, 6, 6, 9,14,17,15,15,12, 8,10,
  150782. 9, 9,12,15,
  150783. };
  150784. static static_codebook _huff_book__44u9__short = {
  150785. 2, 100,
  150786. _huff_lengthlist__44u9__short,
  150787. 0, 0, 0, 0, 0,
  150788. NULL,
  150789. NULL,
  150790. NULL,
  150791. NULL,
  150792. 0
  150793. };
  150794. static long _vq_quantlist__44u9_p1_0[] = {
  150795. 1,
  150796. 0,
  150797. 2,
  150798. };
  150799. static long _vq_lengthlist__44u9_p1_0[] = {
  150800. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  150801. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 7, 9,
  150802. 9, 7, 9, 9, 8, 9, 9, 9,10,11, 9,11,11, 7, 9, 9,
  150803. 9,11,10, 9,11,11, 5, 7, 7, 7, 9, 9, 8, 9,10, 7,
  150804. 9, 9, 9,11,11, 9,10,11, 7, 9,10, 9,11,11, 9,11,
  150805. 10,
  150806. };
  150807. static float _vq_quantthresh__44u9_p1_0[] = {
  150808. -0.5, 0.5,
  150809. };
  150810. static long _vq_quantmap__44u9_p1_0[] = {
  150811. 1, 0, 2,
  150812. };
  150813. static encode_aux_threshmatch _vq_auxt__44u9_p1_0 = {
  150814. _vq_quantthresh__44u9_p1_0,
  150815. _vq_quantmap__44u9_p1_0,
  150816. 3,
  150817. 3
  150818. };
  150819. static static_codebook _44u9_p1_0 = {
  150820. 4, 81,
  150821. _vq_lengthlist__44u9_p1_0,
  150822. 1, -535822336, 1611661312, 2, 0,
  150823. _vq_quantlist__44u9_p1_0,
  150824. NULL,
  150825. &_vq_auxt__44u9_p1_0,
  150826. NULL,
  150827. 0
  150828. };
  150829. static long _vq_quantlist__44u9_p2_0[] = {
  150830. 2,
  150831. 1,
  150832. 3,
  150833. 0,
  150834. 4,
  150835. };
  150836. static long _vq_lengthlist__44u9_p2_0[] = {
  150837. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  150838. 9, 9,11,10, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  150839. 8,10,10, 7, 8, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  150840. 11,11, 6, 7, 7, 9, 9, 7, 8, 8,10, 9, 7, 8, 8,10,
  150841. 10, 9,10, 9,11,11, 9,10,10,11,11, 8, 9, 9,11,11,
  150842. 9,10,10,12,11, 9,10,10,11,12,11,11,11,13,13,11,
  150843. 11,11,12,13, 8, 9, 9,11,11, 9,10,10,11,11, 9,10,
  150844. 10,12,11,11,12,11,13,12,11,11,12,13,13, 6, 7, 7,
  150845. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  150846. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  150847. 8, 9, 9,10,10,10,11,11,12,12,10,10,11,12,12, 7,
  150848. 8, 8,10,10, 8, 9, 8,10,10, 8, 9, 9,10,10,10,11,
  150849. 10,12,11,10,10,11,12,12, 9,10,10,11,12,10,11,11,
  150850. 12,12,10,11,10,12,12,12,12,12,13,13,11,12,12,13,
  150851. 13, 9,10,10,11,11, 9,10,10,12,12,10,11,11,12,13,
  150852. 11,12,11,13,12,12,12,12,13,14, 6, 7, 7, 9, 9, 7,
  150853. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,11,11, 9,10,
  150854. 10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,10, 8, 8, 9,
  150855. 10,10,10,11,10,12,12,10,10,11,11,12, 7, 8, 8,10,
  150856. 10, 8, 9, 9,10,10, 8, 9, 9,10,10,10,11,10,12,12,
  150857. 10,11,10,12,12, 9,10,10,12,11,10,11,11,12,12, 9,
  150858. 10,10,12,12,12,12,12,13,13,11,11,12,12,14, 9,10,
  150859. 10,11,12,10,11,11,12,12,10,11,11,12,12,11,12,12,
  150860. 14,14,12,12,12,13,13, 8, 9, 9,11,11, 9,10,10,12,
  150861. 11, 9,10,10,12,12,11,12,11,13,13,11,11,12,13,13,
  150862. 9,10,10,12,12,10,11,11,12,12,10,11,11,12,12,12,
  150863. 12,12,14,14,12,12,12,13,13, 9,10,10,12,11,10,11,
  150864. 10,12,12,10,11,11,12,12,11,12,12,14,13,12,12,12,
  150865. 13,14,11,12,11,13,13,11,12,12,13,13,12,12,12,14,
  150866. 14,13,13,13,13,15,13,13,14,15,15,11,11,11,13,13,
  150867. 11,12,11,13,13,11,12,12,13,13,12,13,12,15,13,13,
  150868. 13,14,14,15, 8, 9, 9,11,11, 9,10,10,11,12, 9,10,
  150869. 10,11,12,11,12,11,13,13,11,12,12,13,13, 9,10,10,
  150870. 11,12,10,11,10,12,12,10,10,11,12,13,12,12,12,14,
  150871. 13,11,12,12,13,14, 9,10,10,12,12,10,11,11,12,12,
  150872. 10,11,11,12,12,12,12,12,14,13,12,12,12,14,13,11,
  150873. 11,11,13,13,11,12,12,14,13,11,11,12,13,13,13,13,
  150874. 13,15,14,12,12,13,13,15,11,12,12,13,13,12,12,12,
  150875. 13,14,11,12,12,13,13,13,13,14,14,15,13,13,13,14,
  150876. 14,
  150877. };
  150878. static float _vq_quantthresh__44u9_p2_0[] = {
  150879. -1.5, -0.5, 0.5, 1.5,
  150880. };
  150881. static long _vq_quantmap__44u9_p2_0[] = {
  150882. 3, 1, 0, 2, 4,
  150883. };
  150884. static encode_aux_threshmatch _vq_auxt__44u9_p2_0 = {
  150885. _vq_quantthresh__44u9_p2_0,
  150886. _vq_quantmap__44u9_p2_0,
  150887. 5,
  150888. 5
  150889. };
  150890. static static_codebook _44u9_p2_0 = {
  150891. 4, 625,
  150892. _vq_lengthlist__44u9_p2_0,
  150893. 1, -533725184, 1611661312, 3, 0,
  150894. _vq_quantlist__44u9_p2_0,
  150895. NULL,
  150896. &_vq_auxt__44u9_p2_0,
  150897. NULL,
  150898. 0
  150899. };
  150900. static long _vq_quantlist__44u9_p3_0[] = {
  150901. 4,
  150902. 3,
  150903. 5,
  150904. 2,
  150905. 6,
  150906. 1,
  150907. 7,
  150908. 0,
  150909. 8,
  150910. };
  150911. static long _vq_lengthlist__44u9_p3_0[] = {
  150912. 3, 4, 4, 5, 5, 7, 7, 8, 8, 4, 5, 5, 6, 6, 7, 7,
  150913. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  150914. 8, 8, 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  150915. 8, 8, 9, 9,10,10, 7, 7, 7, 8, 8, 9, 9,10,10, 8,
  150916. 9, 9,10, 9,10,10,11,11, 8, 9, 9, 9,10,10,10,11,
  150917. 11,
  150918. };
  150919. static float _vq_quantthresh__44u9_p3_0[] = {
  150920. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150921. };
  150922. static long _vq_quantmap__44u9_p3_0[] = {
  150923. 7, 5, 3, 1, 0, 2, 4, 6,
  150924. 8,
  150925. };
  150926. static encode_aux_threshmatch _vq_auxt__44u9_p3_0 = {
  150927. _vq_quantthresh__44u9_p3_0,
  150928. _vq_quantmap__44u9_p3_0,
  150929. 9,
  150930. 9
  150931. };
  150932. static static_codebook _44u9_p3_0 = {
  150933. 2, 81,
  150934. _vq_lengthlist__44u9_p3_0,
  150935. 1, -531628032, 1611661312, 4, 0,
  150936. _vq_quantlist__44u9_p3_0,
  150937. NULL,
  150938. &_vq_auxt__44u9_p3_0,
  150939. NULL,
  150940. 0
  150941. };
  150942. static long _vq_quantlist__44u9_p4_0[] = {
  150943. 8,
  150944. 7,
  150945. 9,
  150946. 6,
  150947. 10,
  150948. 5,
  150949. 11,
  150950. 4,
  150951. 12,
  150952. 3,
  150953. 13,
  150954. 2,
  150955. 14,
  150956. 1,
  150957. 15,
  150958. 0,
  150959. 16,
  150960. };
  150961. static long _vq_lengthlist__44u9_p4_0[] = {
  150962. 4, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  150963. 11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  150964. 11,11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  150965. 10,11,11, 6, 6, 6, 7, 6, 7, 7, 8, 8, 9, 9,10,10,
  150966. 11,11,12,11, 6, 6, 6, 6, 7, 7, 7, 8, 8, 9, 9,10,
  150967. 10,11,11,11,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,
  150968. 10,10,11,11,12,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  150969. 9,10,10,11,11,12,12, 8, 8, 8, 8, 8, 9, 8,10, 9,
  150970. 10,10,11,10,12,11,13,12, 8, 8, 8, 8, 8, 9, 9, 9,
  150971. 10,10,10,10,11,11,12,12,12, 8, 8, 8, 9, 9, 9, 9,
  150972. 10,10,11,10,12,11,12,12,13,12, 8, 8, 8, 9, 9, 9,
  150973. 9,10,10,10,11,11,11,12,12,12,13, 9, 9, 9,10,10,
  150974. 10,10,11,10,11,11,12,11,13,12,13,13, 9, 9,10,10,
  150975. 10,10,10,10,11,11,11,11,12,12,13,13,13,10,11,10,
  150976. 11,11,11,11,12,11,12,12,13,12,13,13,14,13,10,10,
  150977. 10,11,11,11,11,11,12,12,12,12,13,13,13,13,14,11,
  150978. 11,11,12,11,12,12,12,12,13,13,13,13,14,13,14,14,
  150979. 11,11,11,11,12,12,12,12,12,12,13,13,13,13,14,14,
  150980. 14,
  150981. };
  150982. static float _vq_quantthresh__44u9_p4_0[] = {
  150983. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  150984. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  150985. };
  150986. static long _vq_quantmap__44u9_p4_0[] = {
  150987. 15, 13, 11, 9, 7, 5, 3, 1,
  150988. 0, 2, 4, 6, 8, 10, 12, 14,
  150989. 16,
  150990. };
  150991. static encode_aux_threshmatch _vq_auxt__44u9_p4_0 = {
  150992. _vq_quantthresh__44u9_p4_0,
  150993. _vq_quantmap__44u9_p4_0,
  150994. 17,
  150995. 17
  150996. };
  150997. static static_codebook _44u9_p4_0 = {
  150998. 2, 289,
  150999. _vq_lengthlist__44u9_p4_0,
  151000. 1, -529530880, 1611661312, 5, 0,
  151001. _vq_quantlist__44u9_p4_0,
  151002. NULL,
  151003. &_vq_auxt__44u9_p4_0,
  151004. NULL,
  151005. 0
  151006. };
  151007. static long _vq_quantlist__44u9_p5_0[] = {
  151008. 1,
  151009. 0,
  151010. 2,
  151011. };
  151012. static long _vq_lengthlist__44u9_p5_0[] = {
  151013. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  151014. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  151015. 10, 8,10,10, 7,10,10, 9,10,12, 9,11,11, 7,10,10,
  151016. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  151017. 10,10, 9,12,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  151018. 10,
  151019. };
  151020. static float _vq_quantthresh__44u9_p5_0[] = {
  151021. -5.5, 5.5,
  151022. };
  151023. static long _vq_quantmap__44u9_p5_0[] = {
  151024. 1, 0, 2,
  151025. };
  151026. static encode_aux_threshmatch _vq_auxt__44u9_p5_0 = {
  151027. _vq_quantthresh__44u9_p5_0,
  151028. _vq_quantmap__44u9_p5_0,
  151029. 3,
  151030. 3
  151031. };
  151032. static static_codebook _44u9_p5_0 = {
  151033. 4, 81,
  151034. _vq_lengthlist__44u9_p5_0,
  151035. 1, -529137664, 1618345984, 2, 0,
  151036. _vq_quantlist__44u9_p5_0,
  151037. NULL,
  151038. &_vq_auxt__44u9_p5_0,
  151039. NULL,
  151040. 0
  151041. };
  151042. static long _vq_quantlist__44u9_p5_1[] = {
  151043. 5,
  151044. 4,
  151045. 6,
  151046. 3,
  151047. 7,
  151048. 2,
  151049. 8,
  151050. 1,
  151051. 9,
  151052. 0,
  151053. 10,
  151054. };
  151055. static long _vq_lengthlist__44u9_p5_1[] = {
  151056. 5, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 6,
  151057. 7, 7, 7, 7, 8, 7, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  151058. 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 6, 6, 6, 7,
  151059. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  151060. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  151061. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  151062. 8, 8, 8, 7, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  151063. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  151064. };
  151065. static float _vq_quantthresh__44u9_p5_1[] = {
  151066. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  151067. 3.5, 4.5,
  151068. };
  151069. static long _vq_quantmap__44u9_p5_1[] = {
  151070. 9, 7, 5, 3, 1, 0, 2, 4,
  151071. 6, 8, 10,
  151072. };
  151073. static encode_aux_threshmatch _vq_auxt__44u9_p5_1 = {
  151074. _vq_quantthresh__44u9_p5_1,
  151075. _vq_quantmap__44u9_p5_1,
  151076. 11,
  151077. 11
  151078. };
  151079. static static_codebook _44u9_p5_1 = {
  151080. 2, 121,
  151081. _vq_lengthlist__44u9_p5_1,
  151082. 1, -531365888, 1611661312, 4, 0,
  151083. _vq_quantlist__44u9_p5_1,
  151084. NULL,
  151085. &_vq_auxt__44u9_p5_1,
  151086. NULL,
  151087. 0
  151088. };
  151089. static long _vq_quantlist__44u9_p6_0[] = {
  151090. 6,
  151091. 5,
  151092. 7,
  151093. 4,
  151094. 8,
  151095. 3,
  151096. 9,
  151097. 2,
  151098. 10,
  151099. 1,
  151100. 11,
  151101. 0,
  151102. 12,
  151103. };
  151104. static long _vq_lengthlist__44u9_p6_0[] = {
  151105. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  151106. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 5, 6, 7, 7, 8,
  151107. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  151108. 10,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  151109. 10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 7, 8,
  151110. 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  151111. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  151112. 9,10,10,11,11, 9, 9, 9,10,10,10,10,10,11,11,11,
  151113. 11,12, 9, 9, 9,10,10,10,10,10,10,11,10,12,11,10,
  151114. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  151115. 10,11,11,11,11,12,11,12,12,
  151116. };
  151117. static float _vq_quantthresh__44u9_p6_0[] = {
  151118. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  151119. 12.5, 17.5, 22.5, 27.5,
  151120. };
  151121. static long _vq_quantmap__44u9_p6_0[] = {
  151122. 11, 9, 7, 5, 3, 1, 0, 2,
  151123. 4, 6, 8, 10, 12,
  151124. };
  151125. static encode_aux_threshmatch _vq_auxt__44u9_p6_0 = {
  151126. _vq_quantthresh__44u9_p6_0,
  151127. _vq_quantmap__44u9_p6_0,
  151128. 13,
  151129. 13
  151130. };
  151131. static static_codebook _44u9_p6_0 = {
  151132. 2, 169,
  151133. _vq_lengthlist__44u9_p6_0,
  151134. 1, -526516224, 1616117760, 4, 0,
  151135. _vq_quantlist__44u9_p6_0,
  151136. NULL,
  151137. &_vq_auxt__44u9_p6_0,
  151138. NULL,
  151139. 0
  151140. };
  151141. static long _vq_quantlist__44u9_p6_1[] = {
  151142. 2,
  151143. 1,
  151144. 3,
  151145. 0,
  151146. 4,
  151147. };
  151148. static long _vq_lengthlist__44u9_p6_1[] = {
  151149. 4, 4, 4, 5, 5, 4, 5, 4, 5, 5, 4, 4, 5, 5, 5, 5,
  151150. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  151151. };
  151152. static float _vq_quantthresh__44u9_p6_1[] = {
  151153. -1.5, -0.5, 0.5, 1.5,
  151154. };
  151155. static long _vq_quantmap__44u9_p6_1[] = {
  151156. 3, 1, 0, 2, 4,
  151157. };
  151158. static encode_aux_threshmatch _vq_auxt__44u9_p6_1 = {
  151159. _vq_quantthresh__44u9_p6_1,
  151160. _vq_quantmap__44u9_p6_1,
  151161. 5,
  151162. 5
  151163. };
  151164. static static_codebook _44u9_p6_1 = {
  151165. 2, 25,
  151166. _vq_lengthlist__44u9_p6_1,
  151167. 1, -533725184, 1611661312, 3, 0,
  151168. _vq_quantlist__44u9_p6_1,
  151169. NULL,
  151170. &_vq_auxt__44u9_p6_1,
  151171. NULL,
  151172. 0
  151173. };
  151174. static long _vq_quantlist__44u9_p7_0[] = {
  151175. 6,
  151176. 5,
  151177. 7,
  151178. 4,
  151179. 8,
  151180. 3,
  151181. 9,
  151182. 2,
  151183. 10,
  151184. 1,
  151185. 11,
  151186. 0,
  151187. 12,
  151188. };
  151189. static long _vq_lengthlist__44u9_p7_0[] = {
  151190. 1, 4, 5, 6, 6, 7, 7, 8, 9,10,10,11,11, 5, 6, 6,
  151191. 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 6, 6, 7, 7, 8,
  151192. 8, 9, 9,10,10,11,11, 6, 7, 7, 8, 8, 9, 9,10,10,
  151193. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,12,
  151194. 12, 8, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  151195. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  151196. 11,11,12,12,13,13,13,13, 9, 9, 9,10,10,11,11,12,
  151197. 12,13,13,14,14,10,10,10,11,11,12,12,13,13,14,13,
  151198. 15,14,10,10,10,11,11,12,12,13,13,14,14,14,14,11,
  151199. 11,12,12,12,13,13,14,14,14,14,15,15,11,11,12,12,
  151200. 12,13,13,14,14,14,15,15,15,
  151201. };
  151202. static float _vq_quantthresh__44u9_p7_0[] = {
  151203. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  151204. 27.5, 38.5, 49.5, 60.5,
  151205. };
  151206. static long _vq_quantmap__44u9_p7_0[] = {
  151207. 11, 9, 7, 5, 3, 1, 0, 2,
  151208. 4, 6, 8, 10, 12,
  151209. };
  151210. static encode_aux_threshmatch _vq_auxt__44u9_p7_0 = {
  151211. _vq_quantthresh__44u9_p7_0,
  151212. _vq_quantmap__44u9_p7_0,
  151213. 13,
  151214. 13
  151215. };
  151216. static static_codebook _44u9_p7_0 = {
  151217. 2, 169,
  151218. _vq_lengthlist__44u9_p7_0,
  151219. 1, -523206656, 1618345984, 4, 0,
  151220. _vq_quantlist__44u9_p7_0,
  151221. NULL,
  151222. &_vq_auxt__44u9_p7_0,
  151223. NULL,
  151224. 0
  151225. };
  151226. static long _vq_quantlist__44u9_p7_1[] = {
  151227. 5,
  151228. 4,
  151229. 6,
  151230. 3,
  151231. 7,
  151232. 2,
  151233. 8,
  151234. 1,
  151235. 9,
  151236. 0,
  151237. 10,
  151238. };
  151239. static long _vq_lengthlist__44u9_p7_1[] = {
  151240. 5, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7,
  151241. 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  151242. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 7, 7, 7,
  151243. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151244. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151245. 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151246. 7, 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 7, 8, 8, 7, 7,
  151247. 7, 7, 7, 7, 7, 8, 8, 8, 8,
  151248. };
  151249. static float _vq_quantthresh__44u9_p7_1[] = {
  151250. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  151251. 3.5, 4.5,
  151252. };
  151253. static long _vq_quantmap__44u9_p7_1[] = {
  151254. 9, 7, 5, 3, 1, 0, 2, 4,
  151255. 6, 8, 10,
  151256. };
  151257. static encode_aux_threshmatch _vq_auxt__44u9_p7_1 = {
  151258. _vq_quantthresh__44u9_p7_1,
  151259. _vq_quantmap__44u9_p7_1,
  151260. 11,
  151261. 11
  151262. };
  151263. static static_codebook _44u9_p7_1 = {
  151264. 2, 121,
  151265. _vq_lengthlist__44u9_p7_1,
  151266. 1, -531365888, 1611661312, 4, 0,
  151267. _vq_quantlist__44u9_p7_1,
  151268. NULL,
  151269. &_vq_auxt__44u9_p7_1,
  151270. NULL,
  151271. 0
  151272. };
  151273. static long _vq_quantlist__44u9_p8_0[] = {
  151274. 7,
  151275. 6,
  151276. 8,
  151277. 5,
  151278. 9,
  151279. 4,
  151280. 10,
  151281. 3,
  151282. 11,
  151283. 2,
  151284. 12,
  151285. 1,
  151286. 13,
  151287. 0,
  151288. 14,
  151289. };
  151290. static long _vq_lengthlist__44u9_p8_0[] = {
  151291. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,11,10, 4,
  151292. 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  151293. 6, 8, 8, 9,10, 9, 9,10,10,11,11,12,12, 7, 8, 8,
  151294. 10,10,11,11,10,10,11,11,12,12,13,12, 7, 8, 8,10,
  151295. 10,11,11,10,10,11,11,12,12,12,13, 8,10, 9,11,11,
  151296. 12,12,11,11,12,12,13,13,14,13, 8, 9, 9,11,11,12,
  151297. 12,11,12,12,12,13,13,14,13, 8, 9, 9,10,10,12,11,
  151298. 13,12,13,13,14,13,15,14, 8, 9, 9,10,10,11,12,12,
  151299. 12,13,13,13,14,14,14, 9,10,10,12,11,13,12,13,13,
  151300. 14,13,14,14,14,15, 9,10,10,11,12,12,12,13,13,14,
  151301. 14,14,15,15,15,10,11,11,12,12,13,13,14,14,14,14,
  151302. 15,14,16,15,10,11,11,12,12,13,13,13,14,14,14,14,
  151303. 14,15,16,11,12,12,13,13,14,13,14,14,15,14,15,16,
  151304. 16,16,11,12,12,13,13,14,13,14,14,15,15,15,16,15,
  151305. 15,
  151306. };
  151307. static float _vq_quantthresh__44u9_p8_0[] = {
  151308. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  151309. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  151310. };
  151311. static long _vq_quantmap__44u9_p8_0[] = {
  151312. 13, 11, 9, 7, 5, 3, 1, 0,
  151313. 2, 4, 6, 8, 10, 12, 14,
  151314. };
  151315. static encode_aux_threshmatch _vq_auxt__44u9_p8_0 = {
  151316. _vq_quantthresh__44u9_p8_0,
  151317. _vq_quantmap__44u9_p8_0,
  151318. 15,
  151319. 15
  151320. };
  151321. static static_codebook _44u9_p8_0 = {
  151322. 2, 225,
  151323. _vq_lengthlist__44u9_p8_0,
  151324. 1, -520986624, 1620377600, 4, 0,
  151325. _vq_quantlist__44u9_p8_0,
  151326. NULL,
  151327. &_vq_auxt__44u9_p8_0,
  151328. NULL,
  151329. 0
  151330. };
  151331. static long _vq_quantlist__44u9_p8_1[] = {
  151332. 10,
  151333. 9,
  151334. 11,
  151335. 8,
  151336. 12,
  151337. 7,
  151338. 13,
  151339. 6,
  151340. 14,
  151341. 5,
  151342. 15,
  151343. 4,
  151344. 16,
  151345. 3,
  151346. 17,
  151347. 2,
  151348. 18,
  151349. 1,
  151350. 19,
  151351. 0,
  151352. 20,
  151353. };
  151354. static long _vq_lengthlist__44u9_p8_1[] = {
  151355. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  151356. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  151357. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8,
  151358. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  151359. 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  151360. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  151361. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  151362. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10, 8, 8,
  151363. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151364. 9,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151365. 10, 9,10, 9,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  151366. 9, 9, 9, 9, 9,10,10, 9,10,10,10,10,10, 9, 9, 9,
  151367. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  151368. 10,10, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  151369. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151370. 9, 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  151371. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  151372. 10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  151373. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  151374. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  151375. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  151376. 9, 9, 9, 9,10, 9, 9,10,10,10,10,10,10,10,10,10,
  151377. 10,10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,
  151378. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,10,
  151379. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  151380. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  151381. 10,10,10,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  151382. 10,10,10,10,10,10,10,10,10,
  151383. };
  151384. static float _vq_quantthresh__44u9_p8_1[] = {
  151385. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  151386. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  151387. 6.5, 7.5, 8.5, 9.5,
  151388. };
  151389. static long _vq_quantmap__44u9_p8_1[] = {
  151390. 19, 17, 15, 13, 11, 9, 7, 5,
  151391. 3, 1, 0, 2, 4, 6, 8, 10,
  151392. 12, 14, 16, 18, 20,
  151393. };
  151394. static encode_aux_threshmatch _vq_auxt__44u9_p8_1 = {
  151395. _vq_quantthresh__44u9_p8_1,
  151396. _vq_quantmap__44u9_p8_1,
  151397. 21,
  151398. 21
  151399. };
  151400. static static_codebook _44u9_p8_1 = {
  151401. 2, 441,
  151402. _vq_lengthlist__44u9_p8_1,
  151403. 1, -529268736, 1611661312, 5, 0,
  151404. _vq_quantlist__44u9_p8_1,
  151405. NULL,
  151406. &_vq_auxt__44u9_p8_1,
  151407. NULL,
  151408. 0
  151409. };
  151410. static long _vq_quantlist__44u9_p9_0[] = {
  151411. 7,
  151412. 6,
  151413. 8,
  151414. 5,
  151415. 9,
  151416. 4,
  151417. 10,
  151418. 3,
  151419. 11,
  151420. 2,
  151421. 12,
  151422. 1,
  151423. 13,
  151424. 0,
  151425. 14,
  151426. };
  151427. static long _vq_lengthlist__44u9_p9_0[] = {
  151428. 1, 3, 3,11,11,11,11,11,11,11,11,11,11,11,11, 4,
  151429. 10,11,11,11,11,11,11,11,11,11,11,11,11,11, 4,10,
  151430. 10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151431. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151432. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151433. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151434. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151435. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151436. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151437. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151438. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151439. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151440. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  151441. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  151442. 10,
  151443. };
  151444. static float _vq_quantthresh__44u9_p9_0[] = {
  151445. -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5,
  151446. 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  151447. };
  151448. static long _vq_quantmap__44u9_p9_0[] = {
  151449. 13, 11, 9, 7, 5, 3, 1, 0,
  151450. 2, 4, 6, 8, 10, 12, 14,
  151451. };
  151452. static encode_aux_threshmatch _vq_auxt__44u9_p9_0 = {
  151453. _vq_quantthresh__44u9_p9_0,
  151454. _vq_quantmap__44u9_p9_0,
  151455. 15,
  151456. 15
  151457. };
  151458. static static_codebook _44u9_p9_0 = {
  151459. 2, 225,
  151460. _vq_lengthlist__44u9_p9_0,
  151461. 1, -510036736, 1631393792, 4, 0,
  151462. _vq_quantlist__44u9_p9_0,
  151463. NULL,
  151464. &_vq_auxt__44u9_p9_0,
  151465. NULL,
  151466. 0
  151467. };
  151468. static long _vq_quantlist__44u9_p9_1[] = {
  151469. 9,
  151470. 8,
  151471. 10,
  151472. 7,
  151473. 11,
  151474. 6,
  151475. 12,
  151476. 5,
  151477. 13,
  151478. 4,
  151479. 14,
  151480. 3,
  151481. 15,
  151482. 2,
  151483. 16,
  151484. 1,
  151485. 17,
  151486. 0,
  151487. 18,
  151488. };
  151489. static long _vq_lengthlist__44u9_p9_1[] = {
  151490. 1, 4, 4, 7, 7, 8, 7, 8, 7, 9, 8,10, 9,10,10,11,
  151491. 11,12,12, 4, 7, 6, 9, 9,10, 9, 9, 8,10,10,11,10,
  151492. 12,10,13,12,13,12, 4, 6, 6, 9, 9, 9, 9, 9, 9,10,
  151493. 10,11,11,11,12,12,12,12,12, 7, 9, 8,11,10,10,10,
  151494. 11,10,11,11,12,12,13,12,13,13,13,13, 7, 8, 9,10,
  151495. 10,11,11,10,10,11,11,11,12,13,13,13,13,14,14, 8,
  151496. 9, 9,11,11,12,11,12,12,13,12,12,13,13,14,15,14,
  151497. 14,14, 8, 9, 9,10,11,11,11,12,12,13,12,13,13,14,
  151498. 14,14,15,14,16, 8, 9, 9,11,10,12,12,12,12,15,13,
  151499. 13,13,17,14,15,15,15,14, 8, 9, 9,10,11,11,12,13,
  151500. 12,13,13,13,14,15,14,14,14,16,15, 9,11,10,12,12,
  151501. 13,13,13,13,14,14,16,15,14,14,14,15,15,17, 9,10,
  151502. 10,11,11,13,13,13,14,14,13,15,14,15,14,15,16,15,
  151503. 16,10,11,11,12,12,13,14,15,14,15,14,14,15,17,16,
  151504. 15,15,17,17,10,12,11,13,12,14,14,13,14,15,15,15,
  151505. 15,16,17,17,15,17,16,11,12,12,14,13,15,14,15,16,
  151506. 17,15,17,15,17,15,15,16,17,15,11,11,12,14,14,14,
  151507. 14,14,15,15,16,15,17,17,17,16,17,16,15,12,12,13,
  151508. 14,14,14,15,14,15,15,16,16,17,16,17,15,17,17,16,
  151509. 12,14,12,14,14,15,15,15,14,14,16,16,16,15,16,16,
  151510. 15,17,15,12,13,13,14,15,14,15,17,15,17,16,17,17,
  151511. 17,16,17,16,17,17,12,13,13,14,16,15,15,15,16,15,
  151512. 17,17,15,17,15,17,16,16,17,
  151513. };
  151514. static float _vq_quantthresh__44u9_p9_1[] = {
  151515. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  151516. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  151517. 367.5, 416.5,
  151518. };
  151519. static long _vq_quantmap__44u9_p9_1[] = {
  151520. 17, 15, 13, 11, 9, 7, 5, 3,
  151521. 1, 0, 2, 4, 6, 8, 10, 12,
  151522. 14, 16, 18,
  151523. };
  151524. static encode_aux_threshmatch _vq_auxt__44u9_p9_1 = {
  151525. _vq_quantthresh__44u9_p9_1,
  151526. _vq_quantmap__44u9_p9_1,
  151527. 19,
  151528. 19
  151529. };
  151530. static static_codebook _44u9_p9_1 = {
  151531. 2, 361,
  151532. _vq_lengthlist__44u9_p9_1,
  151533. 1, -518287360, 1622704128, 5, 0,
  151534. _vq_quantlist__44u9_p9_1,
  151535. NULL,
  151536. &_vq_auxt__44u9_p9_1,
  151537. NULL,
  151538. 0
  151539. };
  151540. static long _vq_quantlist__44u9_p9_2[] = {
  151541. 24,
  151542. 23,
  151543. 25,
  151544. 22,
  151545. 26,
  151546. 21,
  151547. 27,
  151548. 20,
  151549. 28,
  151550. 19,
  151551. 29,
  151552. 18,
  151553. 30,
  151554. 17,
  151555. 31,
  151556. 16,
  151557. 32,
  151558. 15,
  151559. 33,
  151560. 14,
  151561. 34,
  151562. 13,
  151563. 35,
  151564. 12,
  151565. 36,
  151566. 11,
  151567. 37,
  151568. 10,
  151569. 38,
  151570. 9,
  151571. 39,
  151572. 8,
  151573. 40,
  151574. 7,
  151575. 41,
  151576. 6,
  151577. 42,
  151578. 5,
  151579. 43,
  151580. 4,
  151581. 44,
  151582. 3,
  151583. 45,
  151584. 2,
  151585. 46,
  151586. 1,
  151587. 47,
  151588. 0,
  151589. 48,
  151590. };
  151591. static long _vq_lengthlist__44u9_p9_2[] = {
  151592. 2, 4, 4, 5, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  151593. 6, 6, 6, 7, 6, 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151594. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151595. 7,
  151596. };
  151597. static float _vq_quantthresh__44u9_p9_2[] = {
  151598. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  151599. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  151600. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151601. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151602. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  151603. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  151604. };
  151605. static long _vq_quantmap__44u9_p9_2[] = {
  151606. 47, 45, 43, 41, 39, 37, 35, 33,
  151607. 31, 29, 27, 25, 23, 21, 19, 17,
  151608. 15, 13, 11, 9, 7, 5, 3, 1,
  151609. 0, 2, 4, 6, 8, 10, 12, 14,
  151610. 16, 18, 20, 22, 24, 26, 28, 30,
  151611. 32, 34, 36, 38, 40, 42, 44, 46,
  151612. 48,
  151613. };
  151614. static encode_aux_threshmatch _vq_auxt__44u9_p9_2 = {
  151615. _vq_quantthresh__44u9_p9_2,
  151616. _vq_quantmap__44u9_p9_2,
  151617. 49,
  151618. 49
  151619. };
  151620. static static_codebook _44u9_p9_2 = {
  151621. 1, 49,
  151622. _vq_lengthlist__44u9_p9_2,
  151623. 1, -526909440, 1611661312, 6, 0,
  151624. _vq_quantlist__44u9_p9_2,
  151625. NULL,
  151626. &_vq_auxt__44u9_p9_2,
  151627. NULL,
  151628. 0
  151629. };
  151630. static long _huff_lengthlist__44un1__long[] = {
  151631. 5, 6,12, 9,14, 9, 9,19, 6, 1, 5, 5, 8, 7, 9,19,
  151632. 12, 4, 4, 7, 7, 9,11,18, 9, 5, 6, 6, 8, 7, 8,17,
  151633. 14, 8, 7, 8, 8,10,12,18, 9, 6, 8, 6, 8, 6, 8,18,
  151634. 9, 8,11, 8,11, 7, 5,15,16,18,18,18,17,15,11,18,
  151635. };
  151636. static static_codebook _huff_book__44un1__long = {
  151637. 2, 64,
  151638. _huff_lengthlist__44un1__long,
  151639. 0, 0, 0, 0, 0,
  151640. NULL,
  151641. NULL,
  151642. NULL,
  151643. NULL,
  151644. 0
  151645. };
  151646. static long _vq_quantlist__44un1__p1_0[] = {
  151647. 1,
  151648. 0,
  151649. 2,
  151650. };
  151651. static long _vq_lengthlist__44un1__p1_0[] = {
  151652. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  151653. 10,11, 5, 8, 8, 8,11,10, 8,11,10, 4, 9, 9, 8,11,
  151654. 11, 8,11,11, 8,12,11,10,12,14,11,13,13, 7,11,11,
  151655. 10,13,11,11,13,14, 4, 8, 9, 8,11,11, 8,11,12, 7,
  151656. 11,11,11,14,13,10,11,13, 8,11,12,11,13,13,10,14,
  151657. 12,
  151658. };
  151659. static float _vq_quantthresh__44un1__p1_0[] = {
  151660. -0.5, 0.5,
  151661. };
  151662. static long _vq_quantmap__44un1__p1_0[] = {
  151663. 1, 0, 2,
  151664. };
  151665. static encode_aux_threshmatch _vq_auxt__44un1__p1_0 = {
  151666. _vq_quantthresh__44un1__p1_0,
  151667. _vq_quantmap__44un1__p1_0,
  151668. 3,
  151669. 3
  151670. };
  151671. static static_codebook _44un1__p1_0 = {
  151672. 4, 81,
  151673. _vq_lengthlist__44un1__p1_0,
  151674. 1, -535822336, 1611661312, 2, 0,
  151675. _vq_quantlist__44un1__p1_0,
  151676. NULL,
  151677. &_vq_auxt__44un1__p1_0,
  151678. NULL,
  151679. 0
  151680. };
  151681. static long _vq_quantlist__44un1__p2_0[] = {
  151682. 1,
  151683. 0,
  151684. 2,
  151685. };
  151686. static long _vq_lengthlist__44un1__p2_0[] = {
  151687. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  151688. 7, 9, 5, 7, 7, 6, 8, 7, 7, 9, 8, 4, 7, 7, 7, 9,
  151689. 8, 7, 8, 8, 7, 9, 8, 8, 8,10, 9,10,10, 6, 8, 8,
  151690. 7,10, 8, 9,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  151691. 8, 8, 9,10,10, 7, 8,10, 6, 8, 9, 9,10,10, 8,10,
  151692. 8,
  151693. };
  151694. static float _vq_quantthresh__44un1__p2_0[] = {
  151695. -0.5, 0.5,
  151696. };
  151697. static long _vq_quantmap__44un1__p2_0[] = {
  151698. 1, 0, 2,
  151699. };
  151700. static encode_aux_threshmatch _vq_auxt__44un1__p2_0 = {
  151701. _vq_quantthresh__44un1__p2_0,
  151702. _vq_quantmap__44un1__p2_0,
  151703. 3,
  151704. 3
  151705. };
  151706. static static_codebook _44un1__p2_0 = {
  151707. 4, 81,
  151708. _vq_lengthlist__44un1__p2_0,
  151709. 1, -535822336, 1611661312, 2, 0,
  151710. _vq_quantlist__44un1__p2_0,
  151711. NULL,
  151712. &_vq_auxt__44un1__p2_0,
  151713. NULL,
  151714. 0
  151715. };
  151716. static long _vq_quantlist__44un1__p3_0[] = {
  151717. 2,
  151718. 1,
  151719. 3,
  151720. 0,
  151721. 4,
  151722. };
  151723. static long _vq_lengthlist__44un1__p3_0[] = {
  151724. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  151725. 10, 9,12,12, 9, 9,10,11,12, 6, 8, 8,10,10, 8,10,
  151726. 10,11,11, 8, 9,10,11,11,10,11,11,13,13,10,11,11,
  151727. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10,10,11,
  151728. 11,10,11,11,13,12,10,11,11,13,12, 9,11,11,15,13,
  151729. 10,12,11,15,13,10,11,11,15,14,12,14,13,16,15,12,
  151730. 13,13,17,16, 9,11,11,13,15,10,11,12,14,15,10,11,
  151731. 12,14,15,12,13,13,15,16,12,13,13,16,16, 5, 8, 8,
  151732. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  151733. 14,11,12,12,14,14, 8,11,10,13,12,10,11,12,12,13,
  151734. 10,12,12,13,13,12,12,13,13,15,11,12,13,15,14, 7,
  151735. 10,10,12,12, 9,12,11,13,12,10,12,12,13,14,12,13,
  151736. 12,15,13,11,13,12,14,15,10,12,12,16,14,11,12,12,
  151737. 16,15,11,13,12,17,16,13,13,15,15,17,13,15,15,20,
  151738. 17,10,12,12,14,16,11,12,12,15,15,11,13,13,15,18,
  151739. 13,14,13,15,15,13,15,14,16,16, 5, 8, 8,11,11, 8,
  151740. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  151741. 12,14,15, 7,10,10,13,12,10,12,12,14,13, 9,10,12,
  151742. 12,13,11,13,13,15,15,11,12,13,13,15, 8,10,10,12,
  151743. 13,10,12,12,13,13,10,12,11,13,13,11,13,12,15,15,
  151744. 12,13,12,15,13,10,12,12,16,14,11,12,12,16,15,10,
  151745. 12,12,16,14,14,15,14,18,16,13,13,14,15,16,10,12,
  151746. 12,14,16,11,13,13,16,16,11,13,12,14,16,13,15,15,
  151747. 18,18,13,15,13,16,14, 8,11,11,16,16,10,13,13,17,
  151748. 16,10,12,12,16,15,14,16,15,20,17,13,14,14,17,17,
  151749. 9,12,12,16,16,11,13,14,16,17,11,13,13,16,16,15,
  151750. 15,19,18, 0,14,15,15,18,18, 9,12,12,17,16,11,13,
  151751. 12,17,16,11,12,13,15,17,15,16,15, 0,19,14,15,14,
  151752. 19,18,12,14,14, 0,16,13,14,14,19,18,13,15,16,17,
  151753. 16,15,15,17,18, 0,14,16,16,19, 0,12,14,14,16,18,
  151754. 13,15,13,17,18,13,15,14,17,18,15,18,14,18,18,16,
  151755. 17,16, 0,17, 8,11,11,15,15,10,12,12,16,16,10,13,
  151756. 13,16,16,13,15,14,17,17,14,15,17,17,18, 9,12,12,
  151757. 16,15,11,13,13,16,16,11,12,13,17,17,14,14,15,17,
  151758. 17,14,15,16, 0,18, 9,12,12,16,17,11,13,13,16,17,
  151759. 11,14,13,18,17,14,16,14,17,17,15,17,17,18,18,12,
  151760. 14,14, 0,16,13,15,15,19, 0,12,13,15, 0, 0,14,17,
  151761. 16,19, 0,16,15,18,18, 0,12,14,14,17, 0,13,14,14,
  151762. 17, 0,13,15,14, 0,18,15,16,16, 0,18,15,18,15, 0,
  151763. 17,
  151764. };
  151765. static float _vq_quantthresh__44un1__p3_0[] = {
  151766. -1.5, -0.5, 0.5, 1.5,
  151767. };
  151768. static long _vq_quantmap__44un1__p3_0[] = {
  151769. 3, 1, 0, 2, 4,
  151770. };
  151771. static encode_aux_threshmatch _vq_auxt__44un1__p3_0 = {
  151772. _vq_quantthresh__44un1__p3_0,
  151773. _vq_quantmap__44un1__p3_0,
  151774. 5,
  151775. 5
  151776. };
  151777. static static_codebook _44un1__p3_0 = {
  151778. 4, 625,
  151779. _vq_lengthlist__44un1__p3_0,
  151780. 1, -533725184, 1611661312, 3, 0,
  151781. _vq_quantlist__44un1__p3_0,
  151782. NULL,
  151783. &_vq_auxt__44un1__p3_0,
  151784. NULL,
  151785. 0
  151786. };
  151787. static long _vq_quantlist__44un1__p4_0[] = {
  151788. 2,
  151789. 1,
  151790. 3,
  151791. 0,
  151792. 4,
  151793. };
  151794. static long _vq_lengthlist__44un1__p4_0[] = {
  151795. 3, 5, 5, 9, 9, 5, 6, 6,10, 9, 5, 6, 6, 9,10,10,
  151796. 10,10,12,11, 9,10,10,12,12, 5, 7, 7,10,10, 7, 7,
  151797. 8,10,11, 7, 7, 8,10,11,10,10,11,11,13,10,10,11,
  151798. 11,13, 6, 7, 7,10,10, 7, 8, 7,11,10, 7, 8, 7,10,
  151799. 10,10,11, 9,13,11,10,11,10,13,11,10,10,10,14,13,
  151800. 10,11,11,14,13,10,10,11,13,14,12,12,13,15,15,12,
  151801. 12,13,13,14,10,10,10,12,13,10,11,10,13,13,10,11,
  151802. 11,13,13,12,13,12,14,13,12,13,13,14,13, 5, 7, 7,
  151803. 10,10, 7, 8, 8,11,10, 7, 8, 8,10,10,11,11,11,13,
  151804. 13,10,11,11,12,12, 7, 8, 8,11,11, 7, 8, 9,10,12,
  151805. 8, 9, 9,11,11,11,10,12,11,14,11,11,12,13,13, 6,
  151806. 8, 8,10,11, 7, 9, 7,12,10, 8, 9,10,11,12,10,12,
  151807. 10,14,11,11,12,11,13,13,10,11,11,14,14,10,10,11,
  151808. 13,14,11,12,12,15,13,12,11,14,12,16,12,13,14,15,
  151809. 16,10,10,11,13,14,10,11,10,14,12,11,12,12,13,14,
  151810. 12,13,11,15,12,14,14,14,15,15, 5, 7, 7,10,10, 7,
  151811. 8, 8,10,10, 7, 8, 8,10,11,10,11,10,12,12,10,11,
  151812. 11,12,13, 6, 8, 8,11,11, 8, 9, 9,12,11, 7, 7, 9,
  151813. 10,12,11,11,11,12,13,11,10,12,11,15, 7, 8, 8,11,
  151814. 11, 8, 9, 9,11,11, 7, 9, 8,12,10,11,12,11,13,12,
  151815. 11,12,10,15,11,10,11,10,14,12,11,12,11,14,13,10,
  151816. 10,11,13,14,13,13,13,17,15,12,11,14,12,15,10,10,
  151817. 11,13,14,11,12,12,14,14,10,11,10,14,13,13,14,13,
  151818. 16,17,12,14,11,16,12, 9,10,10,14,13,10,11,10,14,
  151819. 14,10,11,11,13,13,13,14,14,16,15,12,13,13,14,14,
  151820. 9,11,10,14,13,10,10,12,13,14,11,12,11,14,13,13,
  151821. 14,14,14,15,13,14,14,15,15, 9,10,11,13,14,10,11,
  151822. 10,15,13,11,11,12,12,15,13,14,12,15,14,13,13,14,
  151823. 14,15,12,13,12,16,14,11,11,12,15,14,13,15,13,16,
  151824. 14,13,12,15,12,17,15,16,15,16,16,12,12,13,13,15,
  151825. 11,13,11,15,14,13,13,14,15,17,13,14,12, 0,13,14,
  151826. 15,14,15, 0, 9,10,10,13,13,10,11,11,13,13,10,11,
  151827. 11,13,13,12,13,12,14,14,13,14,14,15,17, 9,10,10,
  151828. 13,13,11,12,11,15,12,10,10,11,13,16,13,14,13,15,
  151829. 14,13,13,14,15,16,10,10,11,13,14,11,11,12,13,14,
  151830. 10,12,11,14,14,13,13,13,14,15,13,15,13,16,15,12,
  151831. 13,12,15,13,12,15,13,15,15,11,11,13,14,15,15,15,
  151832. 15,15,17,13,12,14,13,17,12,12,14,14,15,13,13,14,
  151833. 14,16,11,13,11,16,15,14,16,16,17, 0,14,13,11,16,
  151834. 12,
  151835. };
  151836. static float _vq_quantthresh__44un1__p4_0[] = {
  151837. -1.5, -0.5, 0.5, 1.5,
  151838. };
  151839. static long _vq_quantmap__44un1__p4_0[] = {
  151840. 3, 1, 0, 2, 4,
  151841. };
  151842. static encode_aux_threshmatch _vq_auxt__44un1__p4_0 = {
  151843. _vq_quantthresh__44un1__p4_0,
  151844. _vq_quantmap__44un1__p4_0,
  151845. 5,
  151846. 5
  151847. };
  151848. static static_codebook _44un1__p4_0 = {
  151849. 4, 625,
  151850. _vq_lengthlist__44un1__p4_0,
  151851. 1, -533725184, 1611661312, 3, 0,
  151852. _vq_quantlist__44un1__p4_0,
  151853. NULL,
  151854. &_vq_auxt__44un1__p4_0,
  151855. NULL,
  151856. 0
  151857. };
  151858. static long _vq_quantlist__44un1__p5_0[] = {
  151859. 4,
  151860. 3,
  151861. 5,
  151862. 2,
  151863. 6,
  151864. 1,
  151865. 7,
  151866. 0,
  151867. 8,
  151868. };
  151869. static long _vq_lengthlist__44un1__p5_0[] = {
  151870. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  151871. 10, 9, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 7, 9, 9,
  151872. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 8, 8, 8,
  151873. 9, 9,10,10,11,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  151874. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  151875. 12,
  151876. };
  151877. static float _vq_quantthresh__44un1__p5_0[] = {
  151878. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  151879. };
  151880. static long _vq_quantmap__44un1__p5_0[] = {
  151881. 7, 5, 3, 1, 0, 2, 4, 6,
  151882. 8,
  151883. };
  151884. static encode_aux_threshmatch _vq_auxt__44un1__p5_0 = {
  151885. _vq_quantthresh__44un1__p5_0,
  151886. _vq_quantmap__44un1__p5_0,
  151887. 9,
  151888. 9
  151889. };
  151890. static static_codebook _44un1__p5_0 = {
  151891. 2, 81,
  151892. _vq_lengthlist__44un1__p5_0,
  151893. 1, -531628032, 1611661312, 4, 0,
  151894. _vq_quantlist__44un1__p5_0,
  151895. NULL,
  151896. &_vq_auxt__44un1__p5_0,
  151897. NULL,
  151898. 0
  151899. };
  151900. static long _vq_quantlist__44un1__p6_0[] = {
  151901. 6,
  151902. 5,
  151903. 7,
  151904. 4,
  151905. 8,
  151906. 3,
  151907. 9,
  151908. 2,
  151909. 10,
  151910. 1,
  151911. 11,
  151912. 0,
  151913. 12,
  151914. };
  151915. static long _vq_lengthlist__44un1__p6_0[] = {
  151916. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,15,15, 4, 5, 5,
  151917. 8, 8, 9, 9,11,11,12,12,16,16, 4, 5, 6, 8, 8, 9,
  151918. 9,11,11,12,12,14,14, 7, 8, 8, 9, 9,10,10,11,12,
  151919. 13,13,16,17, 7, 8, 8, 9, 9,10,10,12,12,12,13,15,
  151920. 15, 9,10,10,10,10,11,11,12,12,13,13,15,16, 9, 9,
  151921. 9,10,10,11,11,13,12,13,13,17,17,10,11,11,11,12,
  151922. 12,12,13,13,14,15, 0,18,10,11,11,12,12,12,13,14,
  151923. 13,14,14,17,16,11,12,12,13,13,14,14,14,14,15,16,
  151924. 17,16,11,12,12,13,13,14,14,14,14,15,15,17,17,14,
  151925. 15,15,16,16,16,17,17,16, 0,17, 0,18,14,15,15,16,
  151926. 16, 0,15,18,18, 0,16, 0, 0,
  151927. };
  151928. static float _vq_quantthresh__44un1__p6_0[] = {
  151929. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  151930. 12.5, 17.5, 22.5, 27.5,
  151931. };
  151932. static long _vq_quantmap__44un1__p6_0[] = {
  151933. 11, 9, 7, 5, 3, 1, 0, 2,
  151934. 4, 6, 8, 10, 12,
  151935. };
  151936. static encode_aux_threshmatch _vq_auxt__44un1__p6_0 = {
  151937. _vq_quantthresh__44un1__p6_0,
  151938. _vq_quantmap__44un1__p6_0,
  151939. 13,
  151940. 13
  151941. };
  151942. static static_codebook _44un1__p6_0 = {
  151943. 2, 169,
  151944. _vq_lengthlist__44un1__p6_0,
  151945. 1, -526516224, 1616117760, 4, 0,
  151946. _vq_quantlist__44un1__p6_0,
  151947. NULL,
  151948. &_vq_auxt__44un1__p6_0,
  151949. NULL,
  151950. 0
  151951. };
  151952. static long _vq_quantlist__44un1__p6_1[] = {
  151953. 2,
  151954. 1,
  151955. 3,
  151956. 0,
  151957. 4,
  151958. };
  151959. static long _vq_lengthlist__44un1__p6_1[] = {
  151960. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 6, 5, 5,
  151961. 6, 5, 6, 6, 5, 6, 6, 6, 6,
  151962. };
  151963. static float _vq_quantthresh__44un1__p6_1[] = {
  151964. -1.5, -0.5, 0.5, 1.5,
  151965. };
  151966. static long _vq_quantmap__44un1__p6_1[] = {
  151967. 3, 1, 0, 2, 4,
  151968. };
  151969. static encode_aux_threshmatch _vq_auxt__44un1__p6_1 = {
  151970. _vq_quantthresh__44un1__p6_1,
  151971. _vq_quantmap__44un1__p6_1,
  151972. 5,
  151973. 5
  151974. };
  151975. static static_codebook _44un1__p6_1 = {
  151976. 2, 25,
  151977. _vq_lengthlist__44un1__p6_1,
  151978. 1, -533725184, 1611661312, 3, 0,
  151979. _vq_quantlist__44un1__p6_1,
  151980. NULL,
  151981. &_vq_auxt__44un1__p6_1,
  151982. NULL,
  151983. 0
  151984. };
  151985. static long _vq_quantlist__44un1__p7_0[] = {
  151986. 2,
  151987. 1,
  151988. 3,
  151989. 0,
  151990. 4,
  151991. };
  151992. static long _vq_lengthlist__44un1__p7_0[] = {
  151993. 1, 5, 3,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  151994. 11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,11,
  151995. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151996. 11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151997. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151998. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151999. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152000. 11,11,11,11,11,11,11,11,11,11,11,11,11, 8,11,11,
  152001. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152002. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152003. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  152004. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152005. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152006. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152007. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152008. 11,11,11,11,11,11,11,11,11,11, 7,11,11,11,11,11,
  152009. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152010. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  152011. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152012. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152013. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152014. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152015. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152016. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152017. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152018. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152019. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152020. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152021. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152022. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152023. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152024. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152025. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152026. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152027. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152028. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152029. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152030. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152031. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152032. 10,
  152033. };
  152034. static float _vq_quantthresh__44un1__p7_0[] = {
  152035. -253.5, -84.5, 84.5, 253.5,
  152036. };
  152037. static long _vq_quantmap__44un1__p7_0[] = {
  152038. 3, 1, 0, 2, 4,
  152039. };
  152040. static encode_aux_threshmatch _vq_auxt__44un1__p7_0 = {
  152041. _vq_quantthresh__44un1__p7_0,
  152042. _vq_quantmap__44un1__p7_0,
  152043. 5,
  152044. 5
  152045. };
  152046. static static_codebook _44un1__p7_0 = {
  152047. 4, 625,
  152048. _vq_lengthlist__44un1__p7_0,
  152049. 1, -518709248, 1626677248, 3, 0,
  152050. _vq_quantlist__44un1__p7_0,
  152051. NULL,
  152052. &_vq_auxt__44un1__p7_0,
  152053. NULL,
  152054. 0
  152055. };
  152056. static long _vq_quantlist__44un1__p7_1[] = {
  152057. 6,
  152058. 5,
  152059. 7,
  152060. 4,
  152061. 8,
  152062. 3,
  152063. 9,
  152064. 2,
  152065. 10,
  152066. 1,
  152067. 11,
  152068. 0,
  152069. 12,
  152070. };
  152071. static long _vq_lengthlist__44un1__p7_1[] = {
  152072. 1, 4, 4, 6, 6, 6, 6, 9, 8, 9, 8, 8, 8, 5, 7, 7,
  152073. 7, 7, 8, 8, 8,10, 8,10, 8, 9, 5, 7, 7, 8, 7, 7,
  152074. 8,10,10,11,10,12,11, 7, 8, 8, 9, 9, 9,10,11,11,
  152075. 11,11,11,11, 7, 8, 8, 8, 9, 9, 9,10,10,10,11,11,
  152076. 12, 7, 8, 8, 9, 9,10,11,11,12,11,12,11,11, 7, 8,
  152077. 8, 9, 9,10,10,11,11,11,12,12,11, 8,10,10,10,10,
  152078. 11,11,14,11,12,12,12,13, 9,10,10,10,10,12,11,14,
  152079. 11,14,11,12,13,10,11,11,11,11,13,11,14,14,13,13,
  152080. 13,14,11,11,11,12,11,12,12,12,13,14,14,13,14,12,
  152081. 11,12,12,12,12,13,13,13,14,13,14,14,11,12,12,14,
  152082. 12,13,13,12,13,13,14,14,14,
  152083. };
  152084. static float _vq_quantthresh__44un1__p7_1[] = {
  152085. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  152086. 32.5, 45.5, 58.5, 71.5,
  152087. };
  152088. static long _vq_quantmap__44un1__p7_1[] = {
  152089. 11, 9, 7, 5, 3, 1, 0, 2,
  152090. 4, 6, 8, 10, 12,
  152091. };
  152092. static encode_aux_threshmatch _vq_auxt__44un1__p7_1 = {
  152093. _vq_quantthresh__44un1__p7_1,
  152094. _vq_quantmap__44un1__p7_1,
  152095. 13,
  152096. 13
  152097. };
  152098. static static_codebook _44un1__p7_1 = {
  152099. 2, 169,
  152100. _vq_lengthlist__44un1__p7_1,
  152101. 1, -523010048, 1618608128, 4, 0,
  152102. _vq_quantlist__44un1__p7_1,
  152103. NULL,
  152104. &_vq_auxt__44un1__p7_1,
  152105. NULL,
  152106. 0
  152107. };
  152108. static long _vq_quantlist__44un1__p7_2[] = {
  152109. 6,
  152110. 5,
  152111. 7,
  152112. 4,
  152113. 8,
  152114. 3,
  152115. 9,
  152116. 2,
  152117. 10,
  152118. 1,
  152119. 11,
  152120. 0,
  152121. 12,
  152122. };
  152123. static long _vq_lengthlist__44un1__p7_2[] = {
  152124. 3, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9, 9, 8, 4, 5, 5,
  152125. 6, 6, 8, 8, 9, 8, 9, 9, 9, 9, 4, 5, 5, 7, 6, 8,
  152126. 8, 8, 8, 9, 8, 9, 8, 6, 7, 7, 7, 8, 8, 8, 9, 9,
  152127. 9, 9, 9, 9, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  152128. 9, 7, 8, 8, 8, 8, 9, 8, 9, 9,10, 9, 9,10, 7, 8,
  152129. 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 8, 9, 9, 9, 9,
  152130. 9, 9, 9, 9,10,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9,
  152131. 9, 9, 9,10,10, 9, 9, 9,10, 9, 9,10, 9, 9,10,10,
  152132. 10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10, 9,
  152133. 9, 9,10, 9, 9,10,10, 9,10,10,10,10, 9, 9, 9,10,
  152134. 9, 9, 9,10,10,10,10,10,10,
  152135. };
  152136. static float _vq_quantthresh__44un1__p7_2[] = {
  152137. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  152138. 2.5, 3.5, 4.5, 5.5,
  152139. };
  152140. static long _vq_quantmap__44un1__p7_2[] = {
  152141. 11, 9, 7, 5, 3, 1, 0, 2,
  152142. 4, 6, 8, 10, 12,
  152143. };
  152144. static encode_aux_threshmatch _vq_auxt__44un1__p7_2 = {
  152145. _vq_quantthresh__44un1__p7_2,
  152146. _vq_quantmap__44un1__p7_2,
  152147. 13,
  152148. 13
  152149. };
  152150. static static_codebook _44un1__p7_2 = {
  152151. 2, 169,
  152152. _vq_lengthlist__44un1__p7_2,
  152153. 1, -531103744, 1611661312, 4, 0,
  152154. _vq_quantlist__44un1__p7_2,
  152155. NULL,
  152156. &_vq_auxt__44un1__p7_2,
  152157. NULL,
  152158. 0
  152159. };
  152160. static long _huff_lengthlist__44un1__short[] = {
  152161. 12,12,14,12,14,14,14,14,12, 6, 6, 8, 9, 9,11,14,
  152162. 12, 4, 2, 6, 6, 7,11,14,13, 6, 5, 7, 8, 9,11,14,
  152163. 13, 8, 5, 8, 6, 8,12,14,12, 7, 7, 8, 8, 8,10,14,
  152164. 12, 6, 3, 4, 4, 4, 7,14,11, 7, 4, 6, 6, 6, 8,14,
  152165. };
  152166. static static_codebook _huff_book__44un1__short = {
  152167. 2, 64,
  152168. _huff_lengthlist__44un1__short,
  152169. 0, 0, 0, 0, 0,
  152170. NULL,
  152171. NULL,
  152172. NULL,
  152173. NULL,
  152174. 0
  152175. };
  152176. /*** End of inlined file: res_books_uncoupled.h ***/
  152177. /***** residue backends *********************************************/
  152178. static vorbis_info_residue0 _residue_44_low_un={
  152179. 0,-1, -1, 8,-1,
  152180. {0},
  152181. {-1},
  152182. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 28.5},
  152183. { -1, 25, -1, 45, -1, -1, -1}
  152184. };
  152185. static vorbis_info_residue0 _residue_44_mid_un={
  152186. 0,-1, -1, 10,-1,
  152187. /* 0 1 2 3 4 5 6 7 8 9 */
  152188. {0},
  152189. {-1},
  152190. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 4.5, 16.5, 60.5},
  152191. { -1, 30, -1, 50, -1, 80, -1, -1, -1}
  152192. };
  152193. static vorbis_info_residue0 _residue_44_hi_un={
  152194. 0,-1, -1, 10,-1,
  152195. /* 0 1 2 3 4 5 6 7 8 9 */
  152196. {0},
  152197. {-1},
  152198. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  152199. { -1, -1, -1, -1, -1, -1, -1, -1, -1}
  152200. };
  152201. /* mapping conventions:
  152202. only one submap (this would change for efficient 5.1 support for example)*/
  152203. /* Four psychoacoustic profiles are used, one for each blocktype */
  152204. static vorbis_info_mapping0 _map_nominal_u[2]={
  152205. {1, {0,0}, {0}, {0}, 0,{0},{0}},
  152206. {1, {0,0}, {1}, {1}, 0,{0},{0}}
  152207. };
  152208. static static_bookblock _resbook_44u_n1={
  152209. {
  152210. {0},
  152211. {0,0,&_44un1__p1_0},
  152212. {0,0,&_44un1__p2_0},
  152213. {0,0,&_44un1__p3_0},
  152214. {0,0,&_44un1__p4_0},
  152215. {0,0,&_44un1__p5_0},
  152216. {&_44un1__p6_0,&_44un1__p6_1},
  152217. {&_44un1__p7_0,&_44un1__p7_1,&_44un1__p7_2}
  152218. }
  152219. };
  152220. static static_bookblock _resbook_44u_0={
  152221. {
  152222. {0},
  152223. {0,0,&_44u0__p1_0},
  152224. {0,0,&_44u0__p2_0},
  152225. {0,0,&_44u0__p3_0},
  152226. {0,0,&_44u0__p4_0},
  152227. {0,0,&_44u0__p5_0},
  152228. {&_44u0__p6_0,&_44u0__p6_1},
  152229. {&_44u0__p7_0,&_44u0__p7_1,&_44u0__p7_2}
  152230. }
  152231. };
  152232. static static_bookblock _resbook_44u_1={
  152233. {
  152234. {0},
  152235. {0,0,&_44u1__p1_0},
  152236. {0,0,&_44u1__p2_0},
  152237. {0,0,&_44u1__p3_0},
  152238. {0,0,&_44u1__p4_0},
  152239. {0,0,&_44u1__p5_0},
  152240. {&_44u1__p6_0,&_44u1__p6_1},
  152241. {&_44u1__p7_0,&_44u1__p7_1,&_44u1__p7_2}
  152242. }
  152243. };
  152244. static static_bookblock _resbook_44u_2={
  152245. {
  152246. {0},
  152247. {0,0,&_44u2__p1_0},
  152248. {0,0,&_44u2__p2_0},
  152249. {0,0,&_44u2__p3_0},
  152250. {0,0,&_44u2__p4_0},
  152251. {0,0,&_44u2__p5_0},
  152252. {&_44u2__p6_0,&_44u2__p6_1},
  152253. {&_44u2__p7_0,&_44u2__p7_1,&_44u2__p7_2}
  152254. }
  152255. };
  152256. static static_bookblock _resbook_44u_3={
  152257. {
  152258. {0},
  152259. {0,0,&_44u3__p1_0},
  152260. {0,0,&_44u3__p2_0},
  152261. {0,0,&_44u3__p3_0},
  152262. {0,0,&_44u3__p4_0},
  152263. {0,0,&_44u3__p5_0},
  152264. {&_44u3__p6_0,&_44u3__p6_1},
  152265. {&_44u3__p7_0,&_44u3__p7_1,&_44u3__p7_2}
  152266. }
  152267. };
  152268. static static_bookblock _resbook_44u_4={
  152269. {
  152270. {0},
  152271. {0,0,&_44u4__p1_0},
  152272. {0,0,&_44u4__p2_0},
  152273. {0,0,&_44u4__p3_0},
  152274. {0,0,&_44u4__p4_0},
  152275. {0,0,&_44u4__p5_0},
  152276. {&_44u4__p6_0,&_44u4__p6_1},
  152277. {&_44u4__p7_0,&_44u4__p7_1,&_44u4__p7_2}
  152278. }
  152279. };
  152280. static static_bookblock _resbook_44u_5={
  152281. {
  152282. {0},
  152283. {0,0,&_44u5__p1_0},
  152284. {0,0,&_44u5__p2_0},
  152285. {0,0,&_44u5__p3_0},
  152286. {0,0,&_44u5__p4_0},
  152287. {0,0,&_44u5__p5_0},
  152288. {0,0,&_44u5__p6_0},
  152289. {&_44u5__p7_0,&_44u5__p7_1},
  152290. {&_44u5__p8_0,&_44u5__p8_1},
  152291. {&_44u5__p9_0,&_44u5__p9_1,&_44u5__p9_2}
  152292. }
  152293. };
  152294. static static_bookblock _resbook_44u_6={
  152295. {
  152296. {0},
  152297. {0,0,&_44u6__p1_0},
  152298. {0,0,&_44u6__p2_0},
  152299. {0,0,&_44u6__p3_0},
  152300. {0,0,&_44u6__p4_0},
  152301. {0,0,&_44u6__p5_0},
  152302. {0,0,&_44u6__p6_0},
  152303. {&_44u6__p7_0,&_44u6__p7_1},
  152304. {&_44u6__p8_0,&_44u6__p8_1},
  152305. {&_44u6__p9_0,&_44u6__p9_1,&_44u6__p9_2}
  152306. }
  152307. };
  152308. static static_bookblock _resbook_44u_7={
  152309. {
  152310. {0},
  152311. {0,0,&_44u7__p1_0},
  152312. {0,0,&_44u7__p2_0},
  152313. {0,0,&_44u7__p3_0},
  152314. {0,0,&_44u7__p4_0},
  152315. {0,0,&_44u7__p5_0},
  152316. {0,0,&_44u7__p6_0},
  152317. {&_44u7__p7_0,&_44u7__p7_1},
  152318. {&_44u7__p8_0,&_44u7__p8_1},
  152319. {&_44u7__p9_0,&_44u7__p9_1,&_44u7__p9_2}
  152320. }
  152321. };
  152322. static static_bookblock _resbook_44u_8={
  152323. {
  152324. {0},
  152325. {0,0,&_44u8_p1_0},
  152326. {0,0,&_44u8_p2_0},
  152327. {0,0,&_44u8_p3_0},
  152328. {0,0,&_44u8_p4_0},
  152329. {&_44u8_p5_0,&_44u8_p5_1},
  152330. {&_44u8_p6_0,&_44u8_p6_1},
  152331. {&_44u8_p7_0,&_44u8_p7_1},
  152332. {&_44u8_p8_0,&_44u8_p8_1},
  152333. {&_44u8_p9_0,&_44u8_p9_1,&_44u8_p9_2}
  152334. }
  152335. };
  152336. static static_bookblock _resbook_44u_9={
  152337. {
  152338. {0},
  152339. {0,0,&_44u9_p1_0},
  152340. {0,0,&_44u9_p2_0},
  152341. {0,0,&_44u9_p3_0},
  152342. {0,0,&_44u9_p4_0},
  152343. {&_44u9_p5_0,&_44u9_p5_1},
  152344. {&_44u9_p6_0,&_44u9_p6_1},
  152345. {&_44u9_p7_0,&_44u9_p7_1},
  152346. {&_44u9_p8_0,&_44u9_p8_1},
  152347. {&_44u9_p9_0,&_44u9_p9_1,&_44u9_p9_2}
  152348. }
  152349. };
  152350. static vorbis_residue_template _res_44u_n1[]={
  152351. {1,0, &_residue_44_low_un,
  152352. &_huff_book__44un1__short,&_huff_book__44un1__short,
  152353. &_resbook_44u_n1,&_resbook_44u_n1},
  152354. {1,0, &_residue_44_low_un,
  152355. &_huff_book__44un1__long,&_huff_book__44un1__long,
  152356. &_resbook_44u_n1,&_resbook_44u_n1}
  152357. };
  152358. static vorbis_residue_template _res_44u_0[]={
  152359. {1,0, &_residue_44_low_un,
  152360. &_huff_book__44u0__short,&_huff_book__44u0__short,
  152361. &_resbook_44u_0,&_resbook_44u_0},
  152362. {1,0, &_residue_44_low_un,
  152363. &_huff_book__44u0__long,&_huff_book__44u0__long,
  152364. &_resbook_44u_0,&_resbook_44u_0}
  152365. };
  152366. static vorbis_residue_template _res_44u_1[]={
  152367. {1,0, &_residue_44_low_un,
  152368. &_huff_book__44u1__short,&_huff_book__44u1__short,
  152369. &_resbook_44u_1,&_resbook_44u_1},
  152370. {1,0, &_residue_44_low_un,
  152371. &_huff_book__44u1__long,&_huff_book__44u1__long,
  152372. &_resbook_44u_1,&_resbook_44u_1}
  152373. };
  152374. static vorbis_residue_template _res_44u_2[]={
  152375. {1,0, &_residue_44_low_un,
  152376. &_huff_book__44u2__short,&_huff_book__44u2__short,
  152377. &_resbook_44u_2,&_resbook_44u_2},
  152378. {1,0, &_residue_44_low_un,
  152379. &_huff_book__44u2__long,&_huff_book__44u2__long,
  152380. &_resbook_44u_2,&_resbook_44u_2}
  152381. };
  152382. static vorbis_residue_template _res_44u_3[]={
  152383. {1,0, &_residue_44_low_un,
  152384. &_huff_book__44u3__short,&_huff_book__44u3__short,
  152385. &_resbook_44u_3,&_resbook_44u_3},
  152386. {1,0, &_residue_44_low_un,
  152387. &_huff_book__44u3__long,&_huff_book__44u3__long,
  152388. &_resbook_44u_3,&_resbook_44u_3}
  152389. };
  152390. static vorbis_residue_template _res_44u_4[]={
  152391. {1,0, &_residue_44_low_un,
  152392. &_huff_book__44u4__short,&_huff_book__44u4__short,
  152393. &_resbook_44u_4,&_resbook_44u_4},
  152394. {1,0, &_residue_44_low_un,
  152395. &_huff_book__44u4__long,&_huff_book__44u4__long,
  152396. &_resbook_44u_4,&_resbook_44u_4}
  152397. };
  152398. static vorbis_residue_template _res_44u_5[]={
  152399. {1,0, &_residue_44_mid_un,
  152400. &_huff_book__44u5__short,&_huff_book__44u5__short,
  152401. &_resbook_44u_5,&_resbook_44u_5},
  152402. {1,0, &_residue_44_mid_un,
  152403. &_huff_book__44u5__long,&_huff_book__44u5__long,
  152404. &_resbook_44u_5,&_resbook_44u_5}
  152405. };
  152406. static vorbis_residue_template _res_44u_6[]={
  152407. {1,0, &_residue_44_mid_un,
  152408. &_huff_book__44u6__short,&_huff_book__44u6__short,
  152409. &_resbook_44u_6,&_resbook_44u_6},
  152410. {1,0, &_residue_44_mid_un,
  152411. &_huff_book__44u6__long,&_huff_book__44u6__long,
  152412. &_resbook_44u_6,&_resbook_44u_6}
  152413. };
  152414. static vorbis_residue_template _res_44u_7[]={
  152415. {1,0, &_residue_44_mid_un,
  152416. &_huff_book__44u7__short,&_huff_book__44u7__short,
  152417. &_resbook_44u_7,&_resbook_44u_7},
  152418. {1,0, &_residue_44_mid_un,
  152419. &_huff_book__44u7__long,&_huff_book__44u7__long,
  152420. &_resbook_44u_7,&_resbook_44u_7}
  152421. };
  152422. static vorbis_residue_template _res_44u_8[]={
  152423. {1,0, &_residue_44_hi_un,
  152424. &_huff_book__44u8__short,&_huff_book__44u8__short,
  152425. &_resbook_44u_8,&_resbook_44u_8},
  152426. {1,0, &_residue_44_hi_un,
  152427. &_huff_book__44u8__long,&_huff_book__44u8__long,
  152428. &_resbook_44u_8,&_resbook_44u_8}
  152429. };
  152430. static vorbis_residue_template _res_44u_9[]={
  152431. {1,0, &_residue_44_hi_un,
  152432. &_huff_book__44u9__short,&_huff_book__44u9__short,
  152433. &_resbook_44u_9,&_resbook_44u_9},
  152434. {1,0, &_residue_44_hi_un,
  152435. &_huff_book__44u9__long,&_huff_book__44u9__long,
  152436. &_resbook_44u_9,&_resbook_44u_9}
  152437. };
  152438. static vorbis_mapping_template _mapres_template_44_uncoupled[]={
  152439. { _map_nominal_u, _res_44u_n1 }, /* -1 */
  152440. { _map_nominal_u, _res_44u_0 }, /* 0 */
  152441. { _map_nominal_u, _res_44u_1 }, /* 1 */
  152442. { _map_nominal_u, _res_44u_2 }, /* 2 */
  152443. { _map_nominal_u, _res_44u_3 }, /* 3 */
  152444. { _map_nominal_u, _res_44u_4 }, /* 4 */
  152445. { _map_nominal_u, _res_44u_5 }, /* 5 */
  152446. { _map_nominal_u, _res_44u_6 }, /* 6 */
  152447. { _map_nominal_u, _res_44u_7 }, /* 7 */
  152448. { _map_nominal_u, _res_44u_8 }, /* 8 */
  152449. { _map_nominal_u, _res_44u_9 }, /* 9 */
  152450. };
  152451. /*** End of inlined file: residue_44u.h ***/
  152452. static double rate_mapping_44_un[12]={
  152453. 32000.,48000.,60000.,70000.,80000.,86000.,
  152454. 96000.,110000.,120000.,140000.,160000.,240001.
  152455. };
  152456. ve_setup_data_template ve_setup_44_uncoupled={
  152457. 11,
  152458. rate_mapping_44_un,
  152459. quality_mapping_44,
  152460. -1,
  152461. 40000,
  152462. 50000,
  152463. blocksize_short_44,
  152464. blocksize_long_44,
  152465. _psy_tone_masteratt_44,
  152466. _psy_tone_0dB,
  152467. _psy_tone_suppress,
  152468. _vp_tonemask_adj_otherblock,
  152469. _vp_tonemask_adj_longblock,
  152470. _vp_tonemask_adj_otherblock,
  152471. _psy_noiseguards_44,
  152472. _psy_noisebias_impulse,
  152473. _psy_noisebias_padding,
  152474. _psy_noisebias_trans,
  152475. _psy_noisebias_long,
  152476. _psy_noise_suppress,
  152477. _psy_compand_44,
  152478. _psy_compand_short_mapping,
  152479. _psy_compand_long_mapping,
  152480. {_noise_start_short_44,_noise_start_long_44},
  152481. {_noise_part_short_44,_noise_part_long_44},
  152482. _noise_thresh_44,
  152483. _psy_ath_floater,
  152484. _psy_ath_abs,
  152485. _psy_lowpass_44,
  152486. _psy_global_44,
  152487. _global_mapping_44,
  152488. NULL,
  152489. _floor_books,
  152490. _floor,
  152491. _floor_short_mapping_44,
  152492. _floor_long_mapping_44,
  152493. _mapres_template_44_uncoupled
  152494. };
  152495. /*** End of inlined file: setup_44u.h ***/
  152496. /*** Start of inlined file: setup_32.h ***/
  152497. static double rate_mapping_32[12]={
  152498. 18000.,28000.,35000.,45000.,56000.,60000.,
  152499. 75000.,90000.,100000.,115000.,150000.,190000.,
  152500. };
  152501. static double rate_mapping_32_un[12]={
  152502. 30000.,42000.,52000.,64000.,72000.,78000.,
  152503. 86000.,92000.,110000.,120000.,140000.,190000.,
  152504. };
  152505. static double _psy_lowpass_32[12]={
  152506. 12.3,13.,13.,14.,15.,99.,99.,99.,99.,99.,99.,99.
  152507. };
  152508. ve_setup_data_template ve_setup_32_stereo={
  152509. 11,
  152510. rate_mapping_32,
  152511. quality_mapping_44,
  152512. 2,
  152513. 26000,
  152514. 40000,
  152515. blocksize_short_44,
  152516. blocksize_long_44,
  152517. _psy_tone_masteratt_44,
  152518. _psy_tone_0dB,
  152519. _psy_tone_suppress,
  152520. _vp_tonemask_adj_otherblock,
  152521. _vp_tonemask_adj_longblock,
  152522. _vp_tonemask_adj_otherblock,
  152523. _psy_noiseguards_44,
  152524. _psy_noisebias_impulse,
  152525. _psy_noisebias_padding,
  152526. _psy_noisebias_trans,
  152527. _psy_noisebias_long,
  152528. _psy_noise_suppress,
  152529. _psy_compand_44,
  152530. _psy_compand_short_mapping,
  152531. _psy_compand_long_mapping,
  152532. {_noise_start_short_44,_noise_start_long_44},
  152533. {_noise_part_short_44,_noise_part_long_44},
  152534. _noise_thresh_44,
  152535. _psy_ath_floater,
  152536. _psy_ath_abs,
  152537. _psy_lowpass_32,
  152538. _psy_global_44,
  152539. _global_mapping_44,
  152540. _psy_stereo_modes_44,
  152541. _floor_books,
  152542. _floor,
  152543. _floor_short_mapping_44,
  152544. _floor_long_mapping_44,
  152545. _mapres_template_44_stereo
  152546. };
  152547. ve_setup_data_template ve_setup_32_uncoupled={
  152548. 11,
  152549. rate_mapping_32_un,
  152550. quality_mapping_44,
  152551. -1,
  152552. 26000,
  152553. 40000,
  152554. blocksize_short_44,
  152555. blocksize_long_44,
  152556. _psy_tone_masteratt_44,
  152557. _psy_tone_0dB,
  152558. _psy_tone_suppress,
  152559. _vp_tonemask_adj_otherblock,
  152560. _vp_tonemask_adj_longblock,
  152561. _vp_tonemask_adj_otherblock,
  152562. _psy_noiseguards_44,
  152563. _psy_noisebias_impulse,
  152564. _psy_noisebias_padding,
  152565. _psy_noisebias_trans,
  152566. _psy_noisebias_long,
  152567. _psy_noise_suppress,
  152568. _psy_compand_44,
  152569. _psy_compand_short_mapping,
  152570. _psy_compand_long_mapping,
  152571. {_noise_start_short_44,_noise_start_long_44},
  152572. {_noise_part_short_44,_noise_part_long_44},
  152573. _noise_thresh_44,
  152574. _psy_ath_floater,
  152575. _psy_ath_abs,
  152576. _psy_lowpass_32,
  152577. _psy_global_44,
  152578. _global_mapping_44,
  152579. NULL,
  152580. _floor_books,
  152581. _floor,
  152582. _floor_short_mapping_44,
  152583. _floor_long_mapping_44,
  152584. _mapres_template_44_uncoupled
  152585. };
  152586. /*** End of inlined file: setup_32.h ***/
  152587. /*** Start of inlined file: setup_8.h ***/
  152588. /*** Start of inlined file: psych_8.h ***/
  152589. static att3 _psy_tone_masteratt_8[3]={
  152590. {{ 32, 25, 12}, 0, 0}, /* 0 */
  152591. {{ 30, 25, 12}, 0, 0}, /* 0 */
  152592. {{ 20, 0, -14}, 0, 0}, /* 0 */
  152593. };
  152594. static vp_adjblock _vp_tonemask_adj_8[3]={
  152595. /* adjust for mode zero */
  152596. /* 63 125 250 500 1 2 4 8 16 */
  152597. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  152598. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  152599. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 1 */
  152600. };
  152601. static noise3 _psy_noisebias_8[3]={
  152602. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  152603. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  152604. {-10,-10,-10,-10, -5, -5, -5, 0, 0, 4, 4, 4, 4, 4, 99, 99, 99},
  152605. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  152606. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  152607. {-10,-10,-10,-10,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  152608. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  152609. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  152610. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  152611. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  152612. };
  152613. /* stereo mode by base quality level */
  152614. static adj_stereo _psy_stereo_modes_8[3]={
  152615. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  152616. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  152617. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  152618. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  152619. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  152620. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  152621. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  152622. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  152623. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  152624. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  152625. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  152626. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  152627. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  152628. };
  152629. static noiseguard _psy_noiseguards_8[2]={
  152630. {10,10,-1},
  152631. {10,10,-1},
  152632. };
  152633. static compandblock _psy_compand_8[2]={
  152634. {{
  152635. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  152636. 8, 8, 9, 9,10,10,11, 11, /* 15dB */
  152637. 12,12,13,13,14,14,15, 15, /* 23dB */
  152638. 16,16,17,17,17,18,18, 19, /* 31dB */
  152639. 19,19,20,21,22,23,24, 25, /* 39dB */
  152640. }},
  152641. {{
  152642. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  152643. 7, 7, 6, 6, 5, 5, 4, 4, /* 15dB */
  152644. 3, 3, 3, 4, 5, 6, 7, 8, /* 23dB */
  152645. 9,10,11,12,13,14,15, 16, /* 31dB */
  152646. 17,18,19,20,21,22,23, 24, /* 39dB */
  152647. }},
  152648. };
  152649. static double _psy_lowpass_8[3]={3.,4.,4.};
  152650. static int _noise_start_8[2]={
  152651. 64,64,
  152652. };
  152653. static int _noise_part_8[2]={
  152654. 8,8,
  152655. };
  152656. static int _psy_ath_floater_8[3]={
  152657. -100,-100,-105,
  152658. };
  152659. static int _psy_ath_abs_8[3]={
  152660. -130,-130,-140,
  152661. };
  152662. /*** End of inlined file: psych_8.h ***/
  152663. /*** Start of inlined file: residue_8.h ***/
  152664. /***** residue backends *********************************************/
  152665. static static_bookblock _resbook_8s_0={
  152666. {
  152667. {0},{0,0,&_8c0_s_p1_0},{0,0,&_8c0_s_p2_0},{0,0,&_8c0_s_p3_0},
  152668. {0,0,&_8c0_s_p4_0},{0,0,&_8c0_s_p5_0},{0,0,&_8c0_s_p6_0},
  152669. {&_8c0_s_p7_0,&_8c0_s_p7_1},{&_8c0_s_p8_0,&_8c0_s_p8_1},
  152670. {&_8c0_s_p9_0,&_8c0_s_p9_1,&_8c0_s_p9_2}
  152671. }
  152672. };
  152673. static static_bookblock _resbook_8s_1={
  152674. {
  152675. {0},{0,0,&_8c1_s_p1_0},{0,0,&_8c1_s_p2_0},{0,0,&_8c1_s_p3_0},
  152676. {0,0,&_8c1_s_p4_0},{0,0,&_8c1_s_p5_0},{0,0,&_8c1_s_p6_0},
  152677. {&_8c1_s_p7_0,&_8c1_s_p7_1},{&_8c1_s_p8_0,&_8c1_s_p8_1},
  152678. {&_8c1_s_p9_0,&_8c1_s_p9_1,&_8c1_s_p9_2}
  152679. }
  152680. };
  152681. static vorbis_residue_template _res_8s_0[]={
  152682. {2,0, &_residue_44_mid,
  152683. &_huff_book__8c0_s_single,&_huff_book__8c0_s_single,
  152684. &_resbook_8s_0,&_resbook_8s_0},
  152685. };
  152686. static vorbis_residue_template _res_8s_1[]={
  152687. {2,0, &_residue_44_mid,
  152688. &_huff_book__8c1_s_single,&_huff_book__8c1_s_single,
  152689. &_resbook_8s_1,&_resbook_8s_1},
  152690. };
  152691. static vorbis_mapping_template _mapres_template_8_stereo[2]={
  152692. { _map_nominal, _res_8s_0 }, /* 0 */
  152693. { _map_nominal, _res_8s_1 }, /* 1 */
  152694. };
  152695. static static_bookblock _resbook_8u_0={
  152696. {
  152697. {0},
  152698. {0,0,&_8u0__p1_0},
  152699. {0,0,&_8u0__p2_0},
  152700. {0,0,&_8u0__p3_0},
  152701. {0,0,&_8u0__p4_0},
  152702. {0,0,&_8u0__p5_0},
  152703. {&_8u0__p6_0,&_8u0__p6_1},
  152704. {&_8u0__p7_0,&_8u0__p7_1,&_8u0__p7_2}
  152705. }
  152706. };
  152707. static static_bookblock _resbook_8u_1={
  152708. {
  152709. {0},
  152710. {0,0,&_8u1__p1_0},
  152711. {0,0,&_8u1__p2_0},
  152712. {0,0,&_8u1__p3_0},
  152713. {0,0,&_8u1__p4_0},
  152714. {0,0,&_8u1__p5_0},
  152715. {0,0,&_8u1__p6_0},
  152716. {&_8u1__p7_0,&_8u1__p7_1},
  152717. {&_8u1__p8_0,&_8u1__p8_1},
  152718. {&_8u1__p9_0,&_8u1__p9_1,&_8u1__p9_2}
  152719. }
  152720. };
  152721. static vorbis_residue_template _res_8u_0[]={
  152722. {1,0, &_residue_44_low_un,
  152723. &_huff_book__8u0__single,&_huff_book__8u0__single,
  152724. &_resbook_8u_0,&_resbook_8u_0},
  152725. };
  152726. static vorbis_residue_template _res_8u_1[]={
  152727. {1,0, &_residue_44_mid_un,
  152728. &_huff_book__8u1__single,&_huff_book__8u1__single,
  152729. &_resbook_8u_1,&_resbook_8u_1},
  152730. };
  152731. static vorbis_mapping_template _mapres_template_8_uncoupled[2]={
  152732. { _map_nominal_u, _res_8u_0 }, /* 0 */
  152733. { _map_nominal_u, _res_8u_1 }, /* 1 */
  152734. };
  152735. /*** End of inlined file: residue_8.h ***/
  152736. static int blocksize_8[2]={
  152737. 512,512
  152738. };
  152739. static int _floor_mapping_8[2]={
  152740. 6,6,
  152741. };
  152742. static double rate_mapping_8[3]={
  152743. 6000.,9000.,32000.,
  152744. };
  152745. static double rate_mapping_8_uncoupled[3]={
  152746. 8000.,14000.,42000.,
  152747. };
  152748. static double quality_mapping_8[3]={
  152749. -.1,.0,1.
  152750. };
  152751. static double _psy_compand_8_mapping[3]={ 0., 1., 1.};
  152752. static double _global_mapping_8[3]={ 1., 2., 3. };
  152753. ve_setup_data_template ve_setup_8_stereo={
  152754. 2,
  152755. rate_mapping_8,
  152756. quality_mapping_8,
  152757. 2,
  152758. 8000,
  152759. 9000,
  152760. blocksize_8,
  152761. blocksize_8,
  152762. _psy_tone_masteratt_8,
  152763. _psy_tone_0dB,
  152764. _psy_tone_suppress,
  152765. _vp_tonemask_adj_8,
  152766. NULL,
  152767. _vp_tonemask_adj_8,
  152768. _psy_noiseguards_8,
  152769. _psy_noisebias_8,
  152770. _psy_noisebias_8,
  152771. NULL,
  152772. NULL,
  152773. _psy_noise_suppress,
  152774. _psy_compand_8,
  152775. _psy_compand_8_mapping,
  152776. NULL,
  152777. {_noise_start_8,_noise_start_8},
  152778. {_noise_part_8,_noise_part_8},
  152779. _noise_thresh_5only,
  152780. _psy_ath_floater_8,
  152781. _psy_ath_abs_8,
  152782. _psy_lowpass_8,
  152783. _psy_global_44,
  152784. _global_mapping_8,
  152785. _psy_stereo_modes_8,
  152786. _floor_books,
  152787. _floor,
  152788. _floor_mapping_8,
  152789. NULL,
  152790. _mapres_template_8_stereo
  152791. };
  152792. ve_setup_data_template ve_setup_8_uncoupled={
  152793. 2,
  152794. rate_mapping_8_uncoupled,
  152795. quality_mapping_8,
  152796. -1,
  152797. 8000,
  152798. 9000,
  152799. blocksize_8,
  152800. blocksize_8,
  152801. _psy_tone_masteratt_8,
  152802. _psy_tone_0dB,
  152803. _psy_tone_suppress,
  152804. _vp_tonemask_adj_8,
  152805. NULL,
  152806. _vp_tonemask_adj_8,
  152807. _psy_noiseguards_8,
  152808. _psy_noisebias_8,
  152809. _psy_noisebias_8,
  152810. NULL,
  152811. NULL,
  152812. _psy_noise_suppress,
  152813. _psy_compand_8,
  152814. _psy_compand_8_mapping,
  152815. NULL,
  152816. {_noise_start_8,_noise_start_8},
  152817. {_noise_part_8,_noise_part_8},
  152818. _noise_thresh_5only,
  152819. _psy_ath_floater_8,
  152820. _psy_ath_abs_8,
  152821. _psy_lowpass_8,
  152822. _psy_global_44,
  152823. _global_mapping_8,
  152824. _psy_stereo_modes_8,
  152825. _floor_books,
  152826. _floor,
  152827. _floor_mapping_8,
  152828. NULL,
  152829. _mapres_template_8_uncoupled
  152830. };
  152831. /*** End of inlined file: setup_8.h ***/
  152832. /*** Start of inlined file: setup_11.h ***/
  152833. /*** Start of inlined file: psych_11.h ***/
  152834. static double _psy_lowpass_11[3]={4.5,5.5,30.,};
  152835. static att3 _psy_tone_masteratt_11[3]={
  152836. {{ 30, 25, 12}, 0, 0}, /* 0 */
  152837. {{ 30, 25, 12}, 0, 0}, /* 0 */
  152838. {{ 20, 0, -14}, 0, 0}, /* 0 */
  152839. };
  152840. static vp_adjblock _vp_tonemask_adj_11[3]={
  152841. /* adjust for mode zero */
  152842. /* 63 125 250 500 1 2 4 8 16 */
  152843. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 2, 0,99,99,99}}, /* 0 */
  152844. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 5, 0, 0,99,99,99}}, /* 1 */
  152845. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 2 */
  152846. };
  152847. static noise3 _psy_noisebias_11[3]={
  152848. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  152849. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  152850. {-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 4, 5, 5, 10, 99, 99, 99},
  152851. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  152852. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  152853. {-15,-15,-15,-15,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  152854. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  152855. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  152856. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  152857. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  152858. };
  152859. static double _noise_thresh_11[3]={ .3,.5,.5 };
  152860. /*** End of inlined file: psych_11.h ***/
  152861. static int blocksize_11[2]={
  152862. 512,512
  152863. };
  152864. static int _floor_mapping_11[2]={
  152865. 6,6,
  152866. };
  152867. static double rate_mapping_11[3]={
  152868. 8000.,13000.,44000.,
  152869. };
  152870. static double rate_mapping_11_uncoupled[3]={
  152871. 12000.,20000.,50000.,
  152872. };
  152873. static double quality_mapping_11[3]={
  152874. -.1,.0,1.
  152875. };
  152876. ve_setup_data_template ve_setup_11_stereo={
  152877. 2,
  152878. rate_mapping_11,
  152879. quality_mapping_11,
  152880. 2,
  152881. 9000,
  152882. 15000,
  152883. blocksize_11,
  152884. blocksize_11,
  152885. _psy_tone_masteratt_11,
  152886. _psy_tone_0dB,
  152887. _psy_tone_suppress,
  152888. _vp_tonemask_adj_11,
  152889. NULL,
  152890. _vp_tonemask_adj_11,
  152891. _psy_noiseguards_8,
  152892. _psy_noisebias_11,
  152893. _psy_noisebias_11,
  152894. NULL,
  152895. NULL,
  152896. _psy_noise_suppress,
  152897. _psy_compand_8,
  152898. _psy_compand_8_mapping,
  152899. NULL,
  152900. {_noise_start_8,_noise_start_8},
  152901. {_noise_part_8,_noise_part_8},
  152902. _noise_thresh_11,
  152903. _psy_ath_floater_8,
  152904. _psy_ath_abs_8,
  152905. _psy_lowpass_11,
  152906. _psy_global_44,
  152907. _global_mapping_8,
  152908. _psy_stereo_modes_8,
  152909. _floor_books,
  152910. _floor,
  152911. _floor_mapping_11,
  152912. NULL,
  152913. _mapres_template_8_stereo
  152914. };
  152915. ve_setup_data_template ve_setup_11_uncoupled={
  152916. 2,
  152917. rate_mapping_11_uncoupled,
  152918. quality_mapping_11,
  152919. -1,
  152920. 9000,
  152921. 15000,
  152922. blocksize_11,
  152923. blocksize_11,
  152924. _psy_tone_masteratt_11,
  152925. _psy_tone_0dB,
  152926. _psy_tone_suppress,
  152927. _vp_tonemask_adj_11,
  152928. NULL,
  152929. _vp_tonemask_adj_11,
  152930. _psy_noiseguards_8,
  152931. _psy_noisebias_11,
  152932. _psy_noisebias_11,
  152933. NULL,
  152934. NULL,
  152935. _psy_noise_suppress,
  152936. _psy_compand_8,
  152937. _psy_compand_8_mapping,
  152938. NULL,
  152939. {_noise_start_8,_noise_start_8},
  152940. {_noise_part_8,_noise_part_8},
  152941. _noise_thresh_11,
  152942. _psy_ath_floater_8,
  152943. _psy_ath_abs_8,
  152944. _psy_lowpass_11,
  152945. _psy_global_44,
  152946. _global_mapping_8,
  152947. _psy_stereo_modes_8,
  152948. _floor_books,
  152949. _floor,
  152950. _floor_mapping_11,
  152951. NULL,
  152952. _mapres_template_8_uncoupled
  152953. };
  152954. /*** End of inlined file: setup_11.h ***/
  152955. /*** Start of inlined file: setup_16.h ***/
  152956. /*** Start of inlined file: psych_16.h ***/
  152957. /* stereo mode by base quality level */
  152958. static adj_stereo _psy_stereo_modes_16[4]={
  152959. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  152960. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  152961. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  152962. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 4, 4},
  152963. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  152964. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  152965. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  152966. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 4, 4, 4, 4, 4},
  152967. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  152968. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  152969. { 5, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  152970. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  152971. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  152972. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  152973. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  152974. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8},
  152975. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  152976. };
  152977. static double _psy_lowpass_16[4]={6.5,8,30.,99.};
  152978. static att3 _psy_tone_masteratt_16[4]={
  152979. {{ 30, 25, 12}, 0, 0}, /* 0 */
  152980. {{ 25, 22, 12}, 0, 0}, /* 0 */
  152981. {{ 20, 12, 0}, 0, 0}, /* 0 */
  152982. {{ 15, 0, -14}, 0, 0}, /* 0 */
  152983. };
  152984. static vp_adjblock _vp_tonemask_adj_16[4]={
  152985. /* adjust for mode zero */
  152986. /* 63 125 250 500 1 2 4 8 16 */
  152987. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 0 */
  152988. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 1 */
  152989. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  152990. {{-30,-30,-30,-30,-30,-26,-20,-10, -5, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  152991. };
  152992. static noise3 _psy_noisebias_16_short[4]={
  152993. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  152994. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  152995. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  152996. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  152997. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  152998. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 4, 5, 6, 8, 8, 15},
  152999. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  153000. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  153001. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10, -8, 0, 0, 0, 0, 2, 5},
  153002. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153003. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  153004. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  153005. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153006. };
  153007. static noise3 _psy_noisebias_16_impulse[4]={
  153008. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153009. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  153010. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  153011. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  153012. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 4, 4, 4, 5, 5, 6, 8, 15},
  153013. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 0, 0, 0, 0, 4, 10},
  153014. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  153015. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 4, 10},
  153016. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10,-10,-10,-10,-10,-10, -7, -5},
  153017. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153018. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  153019. {-30,-30,-30,-30,-26,-22,-20,-18,-18,-18,-20,-20,-20,-20,-20,-20,-16},
  153020. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153021. };
  153022. static noise3 _psy_noisebias_16[4]={
  153023. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153024. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 8, 8, 10, 10, 10, 14, 20},
  153025. {-10,-10,-10,-10,-10, -5, -2, -2, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  153026. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  153027. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  153028. {-15,-15,-15,-15,-15,-10, -5, -5, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  153029. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  153030. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  153031. {-20,-20,-20,-20,-16,-12,-20,-10, -5, -5, 0, 0, 0, 0, 0, 2, 5},
  153032. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153033. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  153034. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  153035. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153036. };
  153037. static double _noise_thresh_16[4]={ .3,.5,.5,.5 };
  153038. static int _noise_start_16[3]={ 256,256,9999 };
  153039. static int _noise_part_16[4]={ 8,8,8,8 };
  153040. static int _psy_ath_floater_16[4]={
  153041. -100,-100,-100,-105,
  153042. };
  153043. static int _psy_ath_abs_16[4]={
  153044. -130,-130,-130,-140,
  153045. };
  153046. /*** End of inlined file: psych_16.h ***/
  153047. /*** Start of inlined file: residue_16.h ***/
  153048. /***** residue backends *********************************************/
  153049. static static_bookblock _resbook_16s_0={
  153050. {
  153051. {0},
  153052. {0,0,&_16c0_s_p1_0},
  153053. {0,0,&_16c0_s_p2_0},
  153054. {0,0,&_16c0_s_p3_0},
  153055. {0,0,&_16c0_s_p4_0},
  153056. {0,0,&_16c0_s_p5_0},
  153057. {0,0,&_16c0_s_p6_0},
  153058. {&_16c0_s_p7_0,&_16c0_s_p7_1},
  153059. {&_16c0_s_p8_0,&_16c0_s_p8_1},
  153060. {&_16c0_s_p9_0,&_16c0_s_p9_1,&_16c0_s_p9_2}
  153061. }
  153062. };
  153063. static static_bookblock _resbook_16s_1={
  153064. {
  153065. {0},
  153066. {0,0,&_16c1_s_p1_0},
  153067. {0,0,&_16c1_s_p2_0},
  153068. {0,0,&_16c1_s_p3_0},
  153069. {0,0,&_16c1_s_p4_0},
  153070. {0,0,&_16c1_s_p5_0},
  153071. {0,0,&_16c1_s_p6_0},
  153072. {&_16c1_s_p7_0,&_16c1_s_p7_1},
  153073. {&_16c1_s_p8_0,&_16c1_s_p8_1},
  153074. {&_16c1_s_p9_0,&_16c1_s_p9_1,&_16c1_s_p9_2}
  153075. }
  153076. };
  153077. static static_bookblock _resbook_16s_2={
  153078. {
  153079. {0},
  153080. {0,0,&_16c2_s_p1_0},
  153081. {0,0,&_16c2_s_p2_0},
  153082. {0,0,&_16c2_s_p3_0},
  153083. {0,0,&_16c2_s_p4_0},
  153084. {&_16c2_s_p5_0,&_16c2_s_p5_1},
  153085. {&_16c2_s_p6_0,&_16c2_s_p6_1},
  153086. {&_16c2_s_p7_0,&_16c2_s_p7_1},
  153087. {&_16c2_s_p8_0,&_16c2_s_p8_1},
  153088. {&_16c2_s_p9_0,&_16c2_s_p9_1,&_16c2_s_p9_2}
  153089. }
  153090. };
  153091. static vorbis_residue_template _res_16s_0[]={
  153092. {2,0, &_residue_44_mid,
  153093. &_huff_book__16c0_s_single,&_huff_book__16c0_s_single,
  153094. &_resbook_16s_0,&_resbook_16s_0},
  153095. };
  153096. static vorbis_residue_template _res_16s_1[]={
  153097. {2,0, &_residue_44_mid,
  153098. &_huff_book__16c1_s_short,&_huff_book__16c1_s_short,
  153099. &_resbook_16s_1,&_resbook_16s_1},
  153100. {2,0, &_residue_44_mid,
  153101. &_huff_book__16c1_s_long,&_huff_book__16c1_s_long,
  153102. &_resbook_16s_1,&_resbook_16s_1}
  153103. };
  153104. static vorbis_residue_template _res_16s_2[]={
  153105. {2,0, &_residue_44_high,
  153106. &_huff_book__16c2_s_short,&_huff_book__16c2_s_short,
  153107. &_resbook_16s_2,&_resbook_16s_2},
  153108. {2,0, &_residue_44_high,
  153109. &_huff_book__16c2_s_long,&_huff_book__16c2_s_long,
  153110. &_resbook_16s_2,&_resbook_16s_2}
  153111. };
  153112. static vorbis_mapping_template _mapres_template_16_stereo[3]={
  153113. { _map_nominal, _res_16s_0 }, /* 0 */
  153114. { _map_nominal, _res_16s_1 }, /* 1 */
  153115. { _map_nominal, _res_16s_2 }, /* 2 */
  153116. };
  153117. static static_bookblock _resbook_16u_0={
  153118. {
  153119. {0},
  153120. {0,0,&_16u0__p1_0},
  153121. {0,0,&_16u0__p2_0},
  153122. {0,0,&_16u0__p3_0},
  153123. {0,0,&_16u0__p4_0},
  153124. {0,0,&_16u0__p5_0},
  153125. {&_16u0__p6_0,&_16u0__p6_1},
  153126. {&_16u0__p7_0,&_16u0__p7_1,&_16u0__p7_2}
  153127. }
  153128. };
  153129. static static_bookblock _resbook_16u_1={
  153130. {
  153131. {0},
  153132. {0,0,&_16u1__p1_0},
  153133. {0,0,&_16u1__p2_0},
  153134. {0,0,&_16u1__p3_0},
  153135. {0,0,&_16u1__p4_0},
  153136. {0,0,&_16u1__p5_0},
  153137. {0,0,&_16u1__p6_0},
  153138. {&_16u1__p7_0,&_16u1__p7_1},
  153139. {&_16u1__p8_0,&_16u1__p8_1},
  153140. {&_16u1__p9_0,&_16u1__p9_1,&_16u1__p9_2}
  153141. }
  153142. };
  153143. static static_bookblock _resbook_16u_2={
  153144. {
  153145. {0},
  153146. {0,0,&_16u2_p1_0},
  153147. {0,0,&_16u2_p2_0},
  153148. {0,0,&_16u2_p3_0},
  153149. {0,0,&_16u2_p4_0},
  153150. {&_16u2_p5_0,&_16u2_p5_1},
  153151. {&_16u2_p6_0,&_16u2_p6_1},
  153152. {&_16u2_p7_0,&_16u2_p7_1},
  153153. {&_16u2_p8_0,&_16u2_p8_1},
  153154. {&_16u2_p9_0,&_16u2_p9_1,&_16u2_p9_2}
  153155. }
  153156. };
  153157. static vorbis_residue_template _res_16u_0[]={
  153158. {1,0, &_residue_44_low_un,
  153159. &_huff_book__16u0__single,&_huff_book__16u0__single,
  153160. &_resbook_16u_0,&_resbook_16u_0},
  153161. };
  153162. static vorbis_residue_template _res_16u_1[]={
  153163. {1,0, &_residue_44_mid_un,
  153164. &_huff_book__16u1__short,&_huff_book__16u1__short,
  153165. &_resbook_16u_1,&_resbook_16u_1},
  153166. {1,0, &_residue_44_mid_un,
  153167. &_huff_book__16u1__long,&_huff_book__16u1__long,
  153168. &_resbook_16u_1,&_resbook_16u_1}
  153169. };
  153170. static vorbis_residue_template _res_16u_2[]={
  153171. {1,0, &_residue_44_hi_un,
  153172. &_huff_book__16u2__short,&_huff_book__16u2__short,
  153173. &_resbook_16u_2,&_resbook_16u_2},
  153174. {1,0, &_residue_44_hi_un,
  153175. &_huff_book__16u2__long,&_huff_book__16u2__long,
  153176. &_resbook_16u_2,&_resbook_16u_2}
  153177. };
  153178. static vorbis_mapping_template _mapres_template_16_uncoupled[3]={
  153179. { _map_nominal_u, _res_16u_0 }, /* 0 */
  153180. { _map_nominal_u, _res_16u_1 }, /* 1 */
  153181. { _map_nominal_u, _res_16u_2 }, /* 2 */
  153182. };
  153183. /*** End of inlined file: residue_16.h ***/
  153184. static int blocksize_16_short[3]={
  153185. 1024,512,512
  153186. };
  153187. static int blocksize_16_long[3]={
  153188. 1024,1024,1024
  153189. };
  153190. static int _floor_mapping_16_short[3]={
  153191. 9,3,3
  153192. };
  153193. static int _floor_mapping_16[3]={
  153194. 9,9,9
  153195. };
  153196. static double rate_mapping_16[4]={
  153197. 12000.,20000.,44000.,86000.
  153198. };
  153199. static double rate_mapping_16_uncoupled[4]={
  153200. 16000.,28000.,64000.,100000.
  153201. };
  153202. static double _global_mapping_16[4]={ 1., 2., 3., 4. };
  153203. static double quality_mapping_16[4]={ -.1,.05,.5,1. };
  153204. static double _psy_compand_16_mapping[4]={ 0., .8, 1., 1.};
  153205. ve_setup_data_template ve_setup_16_stereo={
  153206. 3,
  153207. rate_mapping_16,
  153208. quality_mapping_16,
  153209. 2,
  153210. 15000,
  153211. 19000,
  153212. blocksize_16_short,
  153213. blocksize_16_long,
  153214. _psy_tone_masteratt_16,
  153215. _psy_tone_0dB,
  153216. _psy_tone_suppress,
  153217. _vp_tonemask_adj_16,
  153218. _vp_tonemask_adj_16,
  153219. _vp_tonemask_adj_16,
  153220. _psy_noiseguards_8,
  153221. _psy_noisebias_16_impulse,
  153222. _psy_noisebias_16_short,
  153223. _psy_noisebias_16_short,
  153224. _psy_noisebias_16,
  153225. _psy_noise_suppress,
  153226. _psy_compand_8,
  153227. _psy_compand_16_mapping,
  153228. _psy_compand_16_mapping,
  153229. {_noise_start_16,_noise_start_16},
  153230. { _noise_part_16, _noise_part_16},
  153231. _noise_thresh_16,
  153232. _psy_ath_floater_16,
  153233. _psy_ath_abs_16,
  153234. _psy_lowpass_16,
  153235. _psy_global_44,
  153236. _global_mapping_16,
  153237. _psy_stereo_modes_16,
  153238. _floor_books,
  153239. _floor,
  153240. _floor_mapping_16_short,
  153241. _floor_mapping_16,
  153242. _mapres_template_16_stereo
  153243. };
  153244. ve_setup_data_template ve_setup_16_uncoupled={
  153245. 3,
  153246. rate_mapping_16_uncoupled,
  153247. quality_mapping_16,
  153248. -1,
  153249. 15000,
  153250. 19000,
  153251. blocksize_16_short,
  153252. blocksize_16_long,
  153253. _psy_tone_masteratt_16,
  153254. _psy_tone_0dB,
  153255. _psy_tone_suppress,
  153256. _vp_tonemask_adj_16,
  153257. _vp_tonemask_adj_16,
  153258. _vp_tonemask_adj_16,
  153259. _psy_noiseguards_8,
  153260. _psy_noisebias_16_impulse,
  153261. _psy_noisebias_16_short,
  153262. _psy_noisebias_16_short,
  153263. _psy_noisebias_16,
  153264. _psy_noise_suppress,
  153265. _psy_compand_8,
  153266. _psy_compand_16_mapping,
  153267. _psy_compand_16_mapping,
  153268. {_noise_start_16,_noise_start_16},
  153269. { _noise_part_16, _noise_part_16},
  153270. _noise_thresh_16,
  153271. _psy_ath_floater_16,
  153272. _psy_ath_abs_16,
  153273. _psy_lowpass_16,
  153274. _psy_global_44,
  153275. _global_mapping_16,
  153276. _psy_stereo_modes_16,
  153277. _floor_books,
  153278. _floor,
  153279. _floor_mapping_16_short,
  153280. _floor_mapping_16,
  153281. _mapres_template_16_uncoupled
  153282. };
  153283. /*** End of inlined file: setup_16.h ***/
  153284. /*** Start of inlined file: setup_22.h ***/
  153285. static double rate_mapping_22[4]={
  153286. 15000.,20000.,44000.,86000.
  153287. };
  153288. static double rate_mapping_22_uncoupled[4]={
  153289. 16000.,28000.,50000.,90000.
  153290. };
  153291. static double _psy_lowpass_22[4]={9.5,11.,30.,99.};
  153292. ve_setup_data_template ve_setup_22_stereo={
  153293. 3,
  153294. rate_mapping_22,
  153295. quality_mapping_16,
  153296. 2,
  153297. 19000,
  153298. 26000,
  153299. blocksize_16_short,
  153300. blocksize_16_long,
  153301. _psy_tone_masteratt_16,
  153302. _psy_tone_0dB,
  153303. _psy_tone_suppress,
  153304. _vp_tonemask_adj_16,
  153305. _vp_tonemask_adj_16,
  153306. _vp_tonemask_adj_16,
  153307. _psy_noiseguards_8,
  153308. _psy_noisebias_16_impulse,
  153309. _psy_noisebias_16_short,
  153310. _psy_noisebias_16_short,
  153311. _psy_noisebias_16,
  153312. _psy_noise_suppress,
  153313. _psy_compand_8,
  153314. _psy_compand_8_mapping,
  153315. _psy_compand_8_mapping,
  153316. {_noise_start_16,_noise_start_16},
  153317. { _noise_part_16, _noise_part_16},
  153318. _noise_thresh_16,
  153319. _psy_ath_floater_16,
  153320. _psy_ath_abs_16,
  153321. _psy_lowpass_22,
  153322. _psy_global_44,
  153323. _global_mapping_16,
  153324. _psy_stereo_modes_16,
  153325. _floor_books,
  153326. _floor,
  153327. _floor_mapping_16_short,
  153328. _floor_mapping_16,
  153329. _mapres_template_16_stereo
  153330. };
  153331. ve_setup_data_template ve_setup_22_uncoupled={
  153332. 3,
  153333. rate_mapping_22_uncoupled,
  153334. quality_mapping_16,
  153335. -1,
  153336. 19000,
  153337. 26000,
  153338. blocksize_16_short,
  153339. blocksize_16_long,
  153340. _psy_tone_masteratt_16,
  153341. _psy_tone_0dB,
  153342. _psy_tone_suppress,
  153343. _vp_tonemask_adj_16,
  153344. _vp_tonemask_adj_16,
  153345. _vp_tonemask_adj_16,
  153346. _psy_noiseguards_8,
  153347. _psy_noisebias_16_impulse,
  153348. _psy_noisebias_16_short,
  153349. _psy_noisebias_16_short,
  153350. _psy_noisebias_16,
  153351. _psy_noise_suppress,
  153352. _psy_compand_8,
  153353. _psy_compand_8_mapping,
  153354. _psy_compand_8_mapping,
  153355. {_noise_start_16,_noise_start_16},
  153356. { _noise_part_16, _noise_part_16},
  153357. _noise_thresh_16,
  153358. _psy_ath_floater_16,
  153359. _psy_ath_abs_16,
  153360. _psy_lowpass_22,
  153361. _psy_global_44,
  153362. _global_mapping_16,
  153363. _psy_stereo_modes_16,
  153364. _floor_books,
  153365. _floor,
  153366. _floor_mapping_16_short,
  153367. _floor_mapping_16,
  153368. _mapres_template_16_uncoupled
  153369. };
  153370. /*** End of inlined file: setup_22.h ***/
  153371. /*** Start of inlined file: setup_X.h ***/
  153372. static double rate_mapping_X[12]={
  153373. -1.,-1.,-1.,-1.,-1.,-1.,
  153374. -1.,-1.,-1.,-1.,-1.,-1.
  153375. };
  153376. ve_setup_data_template ve_setup_X_stereo={
  153377. 11,
  153378. rate_mapping_X,
  153379. quality_mapping_44,
  153380. 2,
  153381. 50000,
  153382. 200000,
  153383. blocksize_short_44,
  153384. blocksize_long_44,
  153385. _psy_tone_masteratt_44,
  153386. _psy_tone_0dB,
  153387. _psy_tone_suppress,
  153388. _vp_tonemask_adj_otherblock,
  153389. _vp_tonemask_adj_longblock,
  153390. _vp_tonemask_adj_otherblock,
  153391. _psy_noiseguards_44,
  153392. _psy_noisebias_impulse,
  153393. _psy_noisebias_padding,
  153394. _psy_noisebias_trans,
  153395. _psy_noisebias_long,
  153396. _psy_noise_suppress,
  153397. _psy_compand_44,
  153398. _psy_compand_short_mapping,
  153399. _psy_compand_long_mapping,
  153400. {_noise_start_short_44,_noise_start_long_44},
  153401. {_noise_part_short_44,_noise_part_long_44},
  153402. _noise_thresh_44,
  153403. _psy_ath_floater,
  153404. _psy_ath_abs,
  153405. _psy_lowpass_44,
  153406. _psy_global_44,
  153407. _global_mapping_44,
  153408. _psy_stereo_modes_44,
  153409. _floor_books,
  153410. _floor,
  153411. _floor_short_mapping_44,
  153412. _floor_long_mapping_44,
  153413. _mapres_template_44_stereo
  153414. };
  153415. ve_setup_data_template ve_setup_X_uncoupled={
  153416. 11,
  153417. rate_mapping_X,
  153418. quality_mapping_44,
  153419. -1,
  153420. 50000,
  153421. 200000,
  153422. blocksize_short_44,
  153423. blocksize_long_44,
  153424. _psy_tone_masteratt_44,
  153425. _psy_tone_0dB,
  153426. _psy_tone_suppress,
  153427. _vp_tonemask_adj_otherblock,
  153428. _vp_tonemask_adj_longblock,
  153429. _vp_tonemask_adj_otherblock,
  153430. _psy_noiseguards_44,
  153431. _psy_noisebias_impulse,
  153432. _psy_noisebias_padding,
  153433. _psy_noisebias_trans,
  153434. _psy_noisebias_long,
  153435. _psy_noise_suppress,
  153436. _psy_compand_44,
  153437. _psy_compand_short_mapping,
  153438. _psy_compand_long_mapping,
  153439. {_noise_start_short_44,_noise_start_long_44},
  153440. {_noise_part_short_44,_noise_part_long_44},
  153441. _noise_thresh_44,
  153442. _psy_ath_floater,
  153443. _psy_ath_abs,
  153444. _psy_lowpass_44,
  153445. _psy_global_44,
  153446. _global_mapping_44,
  153447. NULL,
  153448. _floor_books,
  153449. _floor,
  153450. _floor_short_mapping_44,
  153451. _floor_long_mapping_44,
  153452. _mapres_template_44_uncoupled
  153453. };
  153454. ve_setup_data_template ve_setup_XX_stereo={
  153455. 2,
  153456. rate_mapping_X,
  153457. quality_mapping_8,
  153458. 2,
  153459. 0,
  153460. 8000,
  153461. blocksize_8,
  153462. blocksize_8,
  153463. _psy_tone_masteratt_8,
  153464. _psy_tone_0dB,
  153465. _psy_tone_suppress,
  153466. _vp_tonemask_adj_8,
  153467. NULL,
  153468. _vp_tonemask_adj_8,
  153469. _psy_noiseguards_8,
  153470. _psy_noisebias_8,
  153471. _psy_noisebias_8,
  153472. NULL,
  153473. NULL,
  153474. _psy_noise_suppress,
  153475. _psy_compand_8,
  153476. _psy_compand_8_mapping,
  153477. NULL,
  153478. {_noise_start_8,_noise_start_8},
  153479. {_noise_part_8,_noise_part_8},
  153480. _noise_thresh_5only,
  153481. _psy_ath_floater_8,
  153482. _psy_ath_abs_8,
  153483. _psy_lowpass_8,
  153484. _psy_global_44,
  153485. _global_mapping_8,
  153486. _psy_stereo_modes_8,
  153487. _floor_books,
  153488. _floor,
  153489. _floor_mapping_8,
  153490. NULL,
  153491. _mapres_template_8_stereo
  153492. };
  153493. ve_setup_data_template ve_setup_XX_uncoupled={
  153494. 2,
  153495. rate_mapping_X,
  153496. quality_mapping_8,
  153497. -1,
  153498. 0,
  153499. 8000,
  153500. blocksize_8,
  153501. blocksize_8,
  153502. _psy_tone_masteratt_8,
  153503. _psy_tone_0dB,
  153504. _psy_tone_suppress,
  153505. _vp_tonemask_adj_8,
  153506. NULL,
  153507. _vp_tonemask_adj_8,
  153508. _psy_noiseguards_8,
  153509. _psy_noisebias_8,
  153510. _psy_noisebias_8,
  153511. NULL,
  153512. NULL,
  153513. _psy_noise_suppress,
  153514. _psy_compand_8,
  153515. _psy_compand_8_mapping,
  153516. NULL,
  153517. {_noise_start_8,_noise_start_8},
  153518. {_noise_part_8,_noise_part_8},
  153519. _noise_thresh_5only,
  153520. _psy_ath_floater_8,
  153521. _psy_ath_abs_8,
  153522. _psy_lowpass_8,
  153523. _psy_global_44,
  153524. _global_mapping_8,
  153525. _psy_stereo_modes_8,
  153526. _floor_books,
  153527. _floor,
  153528. _floor_mapping_8,
  153529. NULL,
  153530. _mapres_template_8_uncoupled
  153531. };
  153532. /*** End of inlined file: setup_X.h ***/
  153533. static ve_setup_data_template *setup_list[]={
  153534. &ve_setup_44_stereo,
  153535. &ve_setup_44_uncoupled,
  153536. &ve_setup_32_stereo,
  153537. &ve_setup_32_uncoupled,
  153538. &ve_setup_22_stereo,
  153539. &ve_setup_22_uncoupled,
  153540. &ve_setup_16_stereo,
  153541. &ve_setup_16_uncoupled,
  153542. &ve_setup_11_stereo,
  153543. &ve_setup_11_uncoupled,
  153544. &ve_setup_8_stereo,
  153545. &ve_setup_8_uncoupled,
  153546. &ve_setup_X_stereo,
  153547. &ve_setup_X_uncoupled,
  153548. &ve_setup_XX_stereo,
  153549. &ve_setup_XX_uncoupled,
  153550. 0
  153551. };
  153552. static int vorbis_encode_toplevel_setup(vorbis_info *vi,int ch,long rate){
  153553. if(vi && vi->codec_setup){
  153554. vi->version=0;
  153555. vi->channels=ch;
  153556. vi->rate=rate;
  153557. return(0);
  153558. }
  153559. return(OV_EINVAL);
  153560. }
  153561. static void vorbis_encode_floor_setup(vorbis_info *vi,double s,int block,
  153562. static_codebook ***books,
  153563. vorbis_info_floor1 *in,
  153564. int *x){
  153565. int i,k,is=s;
  153566. vorbis_info_floor1 *f=(vorbis_info_floor1*) _ogg_calloc(1,sizeof(*f));
  153567. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  153568. memcpy(f,in+x[is],sizeof(*f));
  153569. /* fill in the lowpass field, even if it's temporary */
  153570. f->n=ci->blocksizes[block]>>1;
  153571. /* books */
  153572. {
  153573. int partitions=f->partitions;
  153574. int maxclass=-1;
  153575. int maxbook=-1;
  153576. for(i=0;i<partitions;i++)
  153577. if(f->partitionclass[i]>maxclass)maxclass=f->partitionclass[i];
  153578. for(i=0;i<=maxclass;i++){
  153579. if(f->class_book[i]>maxbook)maxbook=f->class_book[i];
  153580. f->class_book[i]+=ci->books;
  153581. for(k=0;k<(1<<f->class_subs[i]);k++){
  153582. if(f->class_subbook[i][k]>maxbook)maxbook=f->class_subbook[i][k];
  153583. if(f->class_subbook[i][k]>=0)f->class_subbook[i][k]+=ci->books;
  153584. }
  153585. }
  153586. for(i=0;i<=maxbook;i++)
  153587. ci->book_param[ci->books++]=books[x[is]][i];
  153588. }
  153589. /* for now, we're only using floor 1 */
  153590. ci->floor_type[ci->floors]=1;
  153591. ci->floor_param[ci->floors]=f;
  153592. ci->floors++;
  153593. return;
  153594. }
  153595. static void vorbis_encode_global_psych_setup(vorbis_info *vi,double s,
  153596. vorbis_info_psy_global *in,
  153597. double *x){
  153598. int i,is=s;
  153599. double ds=s-is;
  153600. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  153601. vorbis_info_psy_global *g=&ci->psy_g_param;
  153602. memcpy(g,in+(int)x[is],sizeof(*g));
  153603. ds=x[is]*(1.-ds)+x[is+1]*ds;
  153604. is=(int)ds;
  153605. ds-=is;
  153606. if(ds==0 && is>0){
  153607. is--;
  153608. ds=1.;
  153609. }
  153610. /* interpolate the trigger threshholds */
  153611. for(i=0;i<4;i++){
  153612. g->preecho_thresh[i]=in[is].preecho_thresh[i]*(1.-ds)+in[is+1].preecho_thresh[i]*ds;
  153613. g->postecho_thresh[i]=in[is].postecho_thresh[i]*(1.-ds)+in[is+1].postecho_thresh[i]*ds;
  153614. }
  153615. g->ampmax_att_per_sec=ci->hi.amplitude_track_dBpersec;
  153616. return;
  153617. }
  153618. static void vorbis_encode_global_stereo(vorbis_info *vi,
  153619. highlevel_encode_setup *hi,
  153620. adj_stereo *p){
  153621. float s=hi->stereo_point_setting;
  153622. int i,is=s;
  153623. double ds=s-is;
  153624. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  153625. vorbis_info_psy_global *g=&ci->psy_g_param;
  153626. if(p){
  153627. memcpy(g->coupling_prepointamp,p[is].pre,sizeof(*p[is].pre)*PACKETBLOBS);
  153628. memcpy(g->coupling_postpointamp,p[is].post,sizeof(*p[is].post)*PACKETBLOBS);
  153629. if(hi->managed){
  153630. /* interpolate the kHz threshholds */
  153631. for(i=0;i<PACKETBLOBS;i++){
  153632. float kHz=p[is].kHz[i]*(1.-ds)+p[is+1].kHz[i]*ds;
  153633. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  153634. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  153635. g->coupling_pkHz[i]=kHz;
  153636. kHz=p[is].lowpasskHz[i]*(1.-ds)+p[is+1].lowpasskHz[i]*ds;
  153637. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  153638. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  153639. }
  153640. }else{
  153641. float kHz=p[is].kHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].kHz[PACKETBLOBS/2]*ds;
  153642. for(i=0;i<PACKETBLOBS;i++){
  153643. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  153644. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  153645. g->coupling_pkHz[i]=kHz;
  153646. }
  153647. kHz=p[is].lowpasskHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].lowpasskHz[PACKETBLOBS/2]*ds;
  153648. for(i=0;i<PACKETBLOBS;i++){
  153649. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  153650. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  153651. }
  153652. }
  153653. }else{
  153654. for(i=0;i<PACKETBLOBS;i++){
  153655. g->sliding_lowpass[0][i]=ci->blocksizes[0];
  153656. g->sliding_lowpass[1][i]=ci->blocksizes[1];
  153657. }
  153658. }
  153659. return;
  153660. }
  153661. static void vorbis_encode_psyset_setup(vorbis_info *vi,double s,
  153662. int *nn_start,
  153663. int *nn_partition,
  153664. double *nn_thresh,
  153665. int block){
  153666. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  153667. vorbis_info_psy *p=ci->psy_param[block];
  153668. highlevel_encode_setup *hi=&ci->hi;
  153669. int is=s;
  153670. if(block>=ci->psys)
  153671. ci->psys=block+1;
  153672. if(!p){
  153673. p=(vorbis_info_psy*)_ogg_calloc(1,sizeof(*p));
  153674. ci->psy_param[block]=p;
  153675. }
  153676. memcpy(p,&_psy_info_template,sizeof(*p));
  153677. p->blockflag=block>>1;
  153678. if(hi->noise_normalize_p){
  153679. p->normal_channel_p=1;
  153680. p->normal_point_p=1;
  153681. p->normal_start=nn_start[is];
  153682. p->normal_partition=nn_partition[is];
  153683. p->normal_thresh=nn_thresh[is];
  153684. }
  153685. return;
  153686. }
  153687. static void vorbis_encode_tonemask_setup(vorbis_info *vi,double s,int block,
  153688. att3 *att,
  153689. int *max,
  153690. vp_adjblock *in){
  153691. int i,is=s;
  153692. double ds=s-is;
  153693. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  153694. vorbis_info_psy *p=ci->psy_param[block];
  153695. /* 0 and 2 are only used by bitmanagement, but there's no harm to always
  153696. filling the values in here */
  153697. p->tone_masteratt[0]=att[is].att[0]*(1.-ds)+att[is+1].att[0]*ds;
  153698. p->tone_masteratt[1]=att[is].att[1]*(1.-ds)+att[is+1].att[1]*ds;
  153699. p->tone_masteratt[2]=att[is].att[2]*(1.-ds)+att[is+1].att[2]*ds;
  153700. p->tone_centerboost=att[is].boost*(1.-ds)+att[is+1].boost*ds;
  153701. p->tone_decay=att[is].decay*(1.-ds)+att[is+1].decay*ds;
  153702. p->max_curve_dB=max[is]*(1.-ds)+max[is+1]*ds;
  153703. for(i=0;i<P_BANDS;i++)
  153704. p->toneatt[i]=in[is].block[i]*(1.-ds)+in[is+1].block[i]*ds;
  153705. return;
  153706. }
  153707. static void vorbis_encode_compand_setup(vorbis_info *vi,double s,int block,
  153708. compandblock *in, double *x){
  153709. int i,is=s;
  153710. double ds=s-is;
  153711. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  153712. vorbis_info_psy *p=ci->psy_param[block];
  153713. ds=x[is]*(1.-ds)+x[is+1]*ds;
  153714. is=(int)ds;
  153715. ds-=is;
  153716. if(ds==0 && is>0){
  153717. is--;
  153718. ds=1.;
  153719. }
  153720. /* interpolate the compander settings */
  153721. for(i=0;i<NOISE_COMPAND_LEVELS;i++)
  153722. p->noisecompand[i]=in[is].data[i]*(1.-ds)+in[is+1].data[i]*ds;
  153723. return;
  153724. }
  153725. static void vorbis_encode_peak_setup(vorbis_info *vi,double s,int block,
  153726. int *suppress){
  153727. int is=s;
  153728. double ds=s-is;
  153729. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  153730. vorbis_info_psy *p=ci->psy_param[block];
  153731. p->tone_abs_limit=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  153732. return;
  153733. }
  153734. static void vorbis_encode_noisebias_setup(vorbis_info *vi,double s,int block,
  153735. int *suppress,
  153736. noise3 *in,
  153737. noiseguard *guard,
  153738. double userbias){
  153739. int i,is=s,j;
  153740. double ds=s-is;
  153741. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  153742. vorbis_info_psy *p=ci->psy_param[block];
  153743. p->noisemaxsupp=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  153744. p->noisewindowlomin=guard[block].lo;
  153745. p->noisewindowhimin=guard[block].hi;
  153746. p->noisewindowfixed=guard[block].fixed;
  153747. for(j=0;j<P_NOISECURVES;j++)
  153748. for(i=0;i<P_BANDS;i++)
  153749. p->noiseoff[j][i]=in[is].data[j][i]*(1.-ds)+in[is+1].data[j][i]*ds;
  153750. /* impulse blocks may take a user specified bias to boost the
  153751. nominal/high noise encoding depth */
  153752. for(j=0;j<P_NOISECURVES;j++){
  153753. float min=p->noiseoff[j][0]+6; /* the lowest it can go */
  153754. for(i=0;i<P_BANDS;i++){
  153755. p->noiseoff[j][i]+=userbias;
  153756. if(p->noiseoff[j][i]<min)p->noiseoff[j][i]=min;
  153757. }
  153758. }
  153759. return;
  153760. }
  153761. static void vorbis_encode_ath_setup(vorbis_info *vi,int block){
  153762. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  153763. vorbis_info_psy *p=ci->psy_param[block];
  153764. p->ath_adjatt=ci->hi.ath_floating_dB;
  153765. p->ath_maxatt=ci->hi.ath_absolute_dB;
  153766. return;
  153767. }
  153768. static int book_dup_or_new(codec_setup_info *ci,static_codebook *book){
  153769. int i;
  153770. for(i=0;i<ci->books;i++)
  153771. if(ci->book_param[i]==book)return(i);
  153772. return(ci->books++);
  153773. }
  153774. static void vorbis_encode_blocksize_setup(vorbis_info *vi,double s,
  153775. int *shortb,int *longb){
  153776. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  153777. int is=s;
  153778. int blockshort=shortb[is];
  153779. int blocklong=longb[is];
  153780. ci->blocksizes[0]=blockshort;
  153781. ci->blocksizes[1]=blocklong;
  153782. }
  153783. static void vorbis_encode_residue_setup(vorbis_info *vi,
  153784. int number, int block,
  153785. vorbis_residue_template *res){
  153786. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  153787. int i,n;
  153788. vorbis_info_residue0 *r=(vorbis_info_residue0*)(ci->residue_param[number]=
  153789. (vorbis_info_residue0*)_ogg_malloc(sizeof(*r)));
  153790. memcpy(r,res->res,sizeof(*r));
  153791. if(ci->residues<=number)ci->residues=number+1;
  153792. switch(ci->blocksizes[block]){
  153793. case 64:case 128:case 256:
  153794. r->grouping=16;
  153795. break;
  153796. default:
  153797. r->grouping=32;
  153798. break;
  153799. }
  153800. ci->residue_type[number]=res->res_type;
  153801. /* to be adjusted by lowpass/pointlimit later */
  153802. n=r->end=ci->blocksizes[block]>>1;
  153803. if(res->res_type==2)
  153804. n=r->end*=vi->channels;
  153805. /* fill in all the books */
  153806. {
  153807. int booklist=0,k;
  153808. if(ci->hi.managed){
  153809. for(i=0;i<r->partitions;i++)
  153810. for(k=0;k<3;k++)
  153811. if(res->books_base_managed->books[i][k])
  153812. r->secondstages[i]|=(1<<k);
  153813. r->groupbook=book_dup_or_new(ci,res->book_aux_managed);
  153814. ci->book_param[r->groupbook]=res->book_aux_managed;
  153815. for(i=0;i<r->partitions;i++){
  153816. for(k=0;k<3;k++){
  153817. if(res->books_base_managed->books[i][k]){
  153818. int bookid=book_dup_or_new(ci,res->books_base_managed->books[i][k]);
  153819. r->booklist[booklist++]=bookid;
  153820. ci->book_param[bookid]=res->books_base_managed->books[i][k];
  153821. }
  153822. }
  153823. }
  153824. }else{
  153825. for(i=0;i<r->partitions;i++)
  153826. for(k=0;k<3;k++)
  153827. if(res->books_base->books[i][k])
  153828. r->secondstages[i]|=(1<<k);
  153829. r->groupbook=book_dup_or_new(ci,res->book_aux);
  153830. ci->book_param[r->groupbook]=res->book_aux;
  153831. for(i=0;i<r->partitions;i++){
  153832. for(k=0;k<3;k++){
  153833. if(res->books_base->books[i][k]){
  153834. int bookid=book_dup_or_new(ci,res->books_base->books[i][k]);
  153835. r->booklist[booklist++]=bookid;
  153836. ci->book_param[bookid]=res->books_base->books[i][k];
  153837. }
  153838. }
  153839. }
  153840. }
  153841. }
  153842. /* lowpass setup/pointlimit */
  153843. {
  153844. double freq=ci->hi.lowpass_kHz*1000.;
  153845. vorbis_info_floor1 *f=(vorbis_info_floor1*)ci->floor_param[block]; /* by convention */
  153846. double nyq=vi->rate/2.;
  153847. long blocksize=ci->blocksizes[block]>>1;
  153848. /* lowpass needs to be set in the floor and the residue. */
  153849. if(freq>nyq)freq=nyq;
  153850. /* in the floor, the granularity can be very fine; it doesn't alter
  153851. the encoding structure, only the samples used to fit the floor
  153852. approximation */
  153853. f->n=freq/nyq*blocksize;
  153854. /* this res may by limited by the maximum pointlimit of the mode,
  153855. not the lowpass. the floor is always lowpass limited. */
  153856. if(res->limit_type){
  153857. if(ci->hi.managed)
  153858. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS-1]*1000.;
  153859. else
  153860. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS/2]*1000.;
  153861. if(freq>nyq)freq=nyq;
  153862. }
  153863. /* in the residue, we're constrained, physically, by partition
  153864. boundaries. We still lowpass 'wherever', but we have to round up
  153865. here to next boundary, or the vorbis spec will round it *down* to
  153866. previous boundary in encode/decode */
  153867. if(ci->residue_type[block]==2)
  153868. r->end=(int)((freq/nyq*blocksize*2)/r->grouping+.9)* /* round up only if we're well past */
  153869. r->grouping;
  153870. else
  153871. r->end=(int)((freq/nyq*blocksize)/r->grouping+.9)* /* round up only if we're well past */
  153872. r->grouping;
  153873. }
  153874. }
  153875. /* we assume two maps in this encoder */
  153876. static void vorbis_encode_map_n_res_setup(vorbis_info *vi,double s,
  153877. vorbis_mapping_template *maps){
  153878. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  153879. int i,j,is=s,modes=2;
  153880. vorbis_info_mapping0 *map=maps[is].map;
  153881. vorbis_info_mode *mode=_mode_template;
  153882. vorbis_residue_template *res=maps[is].res;
  153883. if(ci->blocksizes[0]==ci->blocksizes[1])modes=1;
  153884. for(i=0;i<modes;i++){
  153885. ci->map_param[i]=_ogg_calloc(1,sizeof(*map));
  153886. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*mode));
  153887. memcpy(ci->mode_param[i],mode+i,sizeof(*_mode_template));
  153888. if(i>=ci->modes)ci->modes=i+1;
  153889. ci->map_type[i]=0;
  153890. memcpy(ci->map_param[i],map+i,sizeof(*map));
  153891. if(i>=ci->maps)ci->maps=i+1;
  153892. for(j=0;j<map[i].submaps;j++)
  153893. vorbis_encode_residue_setup(vi,map[i].residuesubmap[j],i
  153894. ,res+map[i].residuesubmap[j]);
  153895. }
  153896. }
  153897. static double setting_to_approx_bitrate(vorbis_info *vi){
  153898. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  153899. highlevel_encode_setup *hi=&ci->hi;
  153900. ve_setup_data_template *setup=(ve_setup_data_template *)hi->setup;
  153901. int is=hi->base_setting;
  153902. double ds=hi->base_setting-is;
  153903. int ch=vi->channels;
  153904. double *r=setup->rate_mapping;
  153905. if(r==NULL)
  153906. return(-1);
  153907. return((r[is]*(1.-ds)+r[is+1]*ds)*ch);
  153908. }
  153909. static void get_setup_template(vorbis_info *vi,
  153910. long ch,long srate,
  153911. double req,int q_or_bitrate){
  153912. int i=0,j;
  153913. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  153914. highlevel_encode_setup *hi=&ci->hi;
  153915. if(q_or_bitrate)req/=ch;
  153916. while(setup_list[i]){
  153917. if(setup_list[i]->coupling_restriction==-1 ||
  153918. setup_list[i]->coupling_restriction==ch){
  153919. if(srate>=setup_list[i]->samplerate_min_restriction &&
  153920. srate<=setup_list[i]->samplerate_max_restriction){
  153921. int mappings=setup_list[i]->mappings;
  153922. double *map=(q_or_bitrate?
  153923. setup_list[i]->rate_mapping:
  153924. setup_list[i]->quality_mapping);
  153925. /* the template matches. Does the requested quality mode
  153926. fall within this template's modes? */
  153927. if(req<map[0]){++i;continue;}
  153928. if(req>map[setup_list[i]->mappings]){++i;continue;}
  153929. for(j=0;j<mappings;j++)
  153930. if(req>=map[j] && req<map[j+1])break;
  153931. /* an all-points match */
  153932. hi->setup=setup_list[i];
  153933. if(j==mappings)
  153934. hi->base_setting=j-.001;
  153935. else{
  153936. float low=map[j];
  153937. float high=map[j+1];
  153938. float del=(req-low)/(high-low);
  153939. hi->base_setting=j+del;
  153940. }
  153941. return;
  153942. }
  153943. }
  153944. i++;
  153945. }
  153946. hi->setup=NULL;
  153947. }
  153948. /* encoders will need to use vorbis_info_init beforehand and call
  153949. vorbis_info clear when all done */
  153950. /* two interfaces; this, more detailed one, and later a convenience
  153951. layer on top */
  153952. /* the final setup call */
  153953. int vorbis_encode_setup_init(vorbis_info *vi){
  153954. int i0=0,singleblock=0;
  153955. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  153956. ve_setup_data_template *setup=NULL;
  153957. highlevel_encode_setup *hi=&ci->hi;
  153958. if(ci==NULL)return(OV_EINVAL);
  153959. if(!hi->impulse_block_p)i0=1;
  153960. /* too low/high an ATH floater is nonsensical, but doesn't break anything */
  153961. if(hi->ath_floating_dB>-80)hi->ath_floating_dB=-80;
  153962. if(hi->ath_floating_dB<-200)hi->ath_floating_dB=-200;
  153963. /* again, bound this to avoid the app shooting itself int he foot
  153964. too badly */
  153965. if(hi->amplitude_track_dBpersec>0.)hi->amplitude_track_dBpersec=0.;
  153966. if(hi->amplitude_track_dBpersec<-99999.)hi->amplitude_track_dBpersec=-99999.;
  153967. /* get the appropriate setup template; matches the fetch in previous
  153968. stages */
  153969. setup=(ve_setup_data_template *)hi->setup;
  153970. if(setup==NULL)return(OV_EINVAL);
  153971. hi->set_in_stone=1;
  153972. /* choose block sizes from configured sizes as well as paying
  153973. attention to long_block_p and short_block_p. If the configured
  153974. short and long blocks are the same length, we set long_block_p
  153975. and unset short_block_p */
  153976. vorbis_encode_blocksize_setup(vi,hi->base_setting,
  153977. setup->blocksize_short,
  153978. setup->blocksize_long);
  153979. if(ci->blocksizes[0]==ci->blocksizes[1])singleblock=1;
  153980. /* floor setup; choose proper floor params. Allocated on the floor
  153981. stack in order; if we alloc only long floor, it's 0 */
  153982. vorbis_encode_floor_setup(vi,hi->short_setting,0,
  153983. setup->floor_books,
  153984. setup->floor_params,
  153985. setup->floor_short_mapping);
  153986. if(!singleblock)
  153987. vorbis_encode_floor_setup(vi,hi->long_setting,1,
  153988. setup->floor_books,
  153989. setup->floor_params,
  153990. setup->floor_long_mapping);
  153991. /* setup of [mostly] short block detection and stereo*/
  153992. vorbis_encode_global_psych_setup(vi,hi->trigger_setting,
  153993. setup->global_params,
  153994. setup->global_mapping);
  153995. vorbis_encode_global_stereo(vi,hi,setup->stereo_modes);
  153996. /* basic psych setup and noise normalization */
  153997. vorbis_encode_psyset_setup(vi,hi->short_setting,
  153998. setup->psy_noise_normal_start[0],
  153999. setup->psy_noise_normal_partition[0],
  154000. setup->psy_noise_normal_thresh,
  154001. 0);
  154002. vorbis_encode_psyset_setup(vi,hi->short_setting,
  154003. setup->psy_noise_normal_start[0],
  154004. setup->psy_noise_normal_partition[0],
  154005. setup->psy_noise_normal_thresh,
  154006. 1);
  154007. if(!singleblock){
  154008. vorbis_encode_psyset_setup(vi,hi->long_setting,
  154009. setup->psy_noise_normal_start[1],
  154010. setup->psy_noise_normal_partition[1],
  154011. setup->psy_noise_normal_thresh,
  154012. 2);
  154013. vorbis_encode_psyset_setup(vi,hi->long_setting,
  154014. setup->psy_noise_normal_start[1],
  154015. setup->psy_noise_normal_partition[1],
  154016. setup->psy_noise_normal_thresh,
  154017. 3);
  154018. }
  154019. /* tone masking setup */
  154020. vorbis_encode_tonemask_setup(vi,hi->block[i0].tone_mask_setting,0,
  154021. setup->psy_tone_masteratt,
  154022. setup->psy_tone_0dB,
  154023. setup->psy_tone_adj_impulse);
  154024. vorbis_encode_tonemask_setup(vi,hi->block[1].tone_mask_setting,1,
  154025. setup->psy_tone_masteratt,
  154026. setup->psy_tone_0dB,
  154027. setup->psy_tone_adj_other);
  154028. if(!singleblock){
  154029. vorbis_encode_tonemask_setup(vi,hi->block[2].tone_mask_setting,2,
  154030. setup->psy_tone_masteratt,
  154031. setup->psy_tone_0dB,
  154032. setup->psy_tone_adj_other);
  154033. vorbis_encode_tonemask_setup(vi,hi->block[3].tone_mask_setting,3,
  154034. setup->psy_tone_masteratt,
  154035. setup->psy_tone_0dB,
  154036. setup->psy_tone_adj_long);
  154037. }
  154038. /* noise companding setup */
  154039. vorbis_encode_compand_setup(vi,hi->block[i0].noise_compand_setting,0,
  154040. setup->psy_noise_compand,
  154041. setup->psy_noise_compand_short_mapping);
  154042. vorbis_encode_compand_setup(vi,hi->block[1].noise_compand_setting,1,
  154043. setup->psy_noise_compand,
  154044. setup->psy_noise_compand_short_mapping);
  154045. if(!singleblock){
  154046. vorbis_encode_compand_setup(vi,hi->block[2].noise_compand_setting,2,
  154047. setup->psy_noise_compand,
  154048. setup->psy_noise_compand_long_mapping);
  154049. vorbis_encode_compand_setup(vi,hi->block[3].noise_compand_setting,3,
  154050. setup->psy_noise_compand,
  154051. setup->psy_noise_compand_long_mapping);
  154052. }
  154053. /* peak guarding setup */
  154054. vorbis_encode_peak_setup(vi,hi->block[i0].tone_peaklimit_setting,0,
  154055. setup->psy_tone_dBsuppress);
  154056. vorbis_encode_peak_setup(vi,hi->block[1].tone_peaklimit_setting,1,
  154057. setup->psy_tone_dBsuppress);
  154058. if(!singleblock){
  154059. vorbis_encode_peak_setup(vi,hi->block[2].tone_peaklimit_setting,2,
  154060. setup->psy_tone_dBsuppress);
  154061. vorbis_encode_peak_setup(vi,hi->block[3].tone_peaklimit_setting,3,
  154062. setup->psy_tone_dBsuppress);
  154063. }
  154064. /* noise bias setup */
  154065. vorbis_encode_noisebias_setup(vi,hi->block[i0].noise_bias_setting,0,
  154066. setup->psy_noise_dBsuppress,
  154067. setup->psy_noise_bias_impulse,
  154068. setup->psy_noiseguards,
  154069. (i0==0?hi->impulse_noisetune:0.));
  154070. vorbis_encode_noisebias_setup(vi,hi->block[1].noise_bias_setting,1,
  154071. setup->psy_noise_dBsuppress,
  154072. setup->psy_noise_bias_padding,
  154073. setup->psy_noiseguards,0.);
  154074. if(!singleblock){
  154075. vorbis_encode_noisebias_setup(vi,hi->block[2].noise_bias_setting,2,
  154076. setup->psy_noise_dBsuppress,
  154077. setup->psy_noise_bias_trans,
  154078. setup->psy_noiseguards,0.);
  154079. vorbis_encode_noisebias_setup(vi,hi->block[3].noise_bias_setting,3,
  154080. setup->psy_noise_dBsuppress,
  154081. setup->psy_noise_bias_long,
  154082. setup->psy_noiseguards,0.);
  154083. }
  154084. vorbis_encode_ath_setup(vi,0);
  154085. vorbis_encode_ath_setup(vi,1);
  154086. if(!singleblock){
  154087. vorbis_encode_ath_setup(vi,2);
  154088. vorbis_encode_ath_setup(vi,3);
  154089. }
  154090. vorbis_encode_map_n_res_setup(vi,hi->base_setting,setup->maps);
  154091. /* set bitrate readonlies and management */
  154092. if(hi->bitrate_av>0)
  154093. vi->bitrate_nominal=hi->bitrate_av;
  154094. else{
  154095. vi->bitrate_nominal=setting_to_approx_bitrate(vi);
  154096. }
  154097. vi->bitrate_lower=hi->bitrate_min;
  154098. vi->bitrate_upper=hi->bitrate_max;
  154099. if(hi->bitrate_av)
  154100. vi->bitrate_window=(double)hi->bitrate_reservoir/hi->bitrate_av;
  154101. else
  154102. vi->bitrate_window=0.;
  154103. if(hi->managed){
  154104. ci->bi.avg_rate=hi->bitrate_av;
  154105. ci->bi.min_rate=hi->bitrate_min;
  154106. ci->bi.max_rate=hi->bitrate_max;
  154107. ci->bi.reservoir_bits=hi->bitrate_reservoir;
  154108. ci->bi.reservoir_bias=
  154109. hi->bitrate_reservoir_bias;
  154110. ci->bi.slew_damp=hi->bitrate_av_damp;
  154111. }
  154112. return(0);
  154113. }
  154114. static int vorbis_encode_setup_setting(vorbis_info *vi,
  154115. long channels,
  154116. long rate){
  154117. int ret=0,i,is;
  154118. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154119. highlevel_encode_setup *hi=&ci->hi;
  154120. ve_setup_data_template *setup=(ve_setup_data_template*) hi->setup;
  154121. double ds;
  154122. ret=vorbis_encode_toplevel_setup(vi,channels,rate);
  154123. if(ret)return(ret);
  154124. is=hi->base_setting;
  154125. ds=hi->base_setting-is;
  154126. hi->short_setting=hi->base_setting;
  154127. hi->long_setting=hi->base_setting;
  154128. hi->managed=0;
  154129. hi->impulse_block_p=1;
  154130. hi->noise_normalize_p=1;
  154131. hi->stereo_point_setting=hi->base_setting;
  154132. hi->lowpass_kHz=
  154133. setup->psy_lowpass[is]*(1.-ds)+setup->psy_lowpass[is+1]*ds;
  154134. hi->ath_floating_dB=setup->psy_ath_float[is]*(1.-ds)+
  154135. setup->psy_ath_float[is+1]*ds;
  154136. hi->ath_absolute_dB=setup->psy_ath_abs[is]*(1.-ds)+
  154137. setup->psy_ath_abs[is+1]*ds;
  154138. hi->amplitude_track_dBpersec=-6.;
  154139. hi->trigger_setting=hi->base_setting;
  154140. for(i=0;i<4;i++){
  154141. hi->block[i].tone_mask_setting=hi->base_setting;
  154142. hi->block[i].tone_peaklimit_setting=hi->base_setting;
  154143. hi->block[i].noise_bias_setting=hi->base_setting;
  154144. hi->block[i].noise_compand_setting=hi->base_setting;
  154145. }
  154146. return(ret);
  154147. }
  154148. int vorbis_encode_setup_vbr(vorbis_info *vi,
  154149. long channels,
  154150. long rate,
  154151. float quality){
  154152. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154153. highlevel_encode_setup *hi=&ci->hi;
  154154. quality+=.0000001;
  154155. if(quality>=1.)quality=.9999;
  154156. get_setup_template(vi,channels,rate,quality,0);
  154157. if(!hi->setup)return OV_EIMPL;
  154158. return vorbis_encode_setup_setting(vi,channels,rate);
  154159. }
  154160. int vorbis_encode_init_vbr(vorbis_info *vi,
  154161. long channels,
  154162. long rate,
  154163. float base_quality /* 0. to 1. */
  154164. ){
  154165. int ret=0;
  154166. ret=vorbis_encode_setup_vbr(vi,channels,rate,base_quality);
  154167. if(ret){
  154168. vorbis_info_clear(vi);
  154169. return ret;
  154170. }
  154171. ret=vorbis_encode_setup_init(vi);
  154172. if(ret)
  154173. vorbis_info_clear(vi);
  154174. return(ret);
  154175. }
  154176. int vorbis_encode_setup_managed(vorbis_info *vi,
  154177. long channels,
  154178. long rate,
  154179. long max_bitrate,
  154180. long nominal_bitrate,
  154181. long min_bitrate){
  154182. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154183. highlevel_encode_setup *hi=&ci->hi;
  154184. double tnominal=nominal_bitrate;
  154185. int ret=0;
  154186. if(nominal_bitrate<=0.){
  154187. if(max_bitrate>0.){
  154188. if(min_bitrate>0.)
  154189. nominal_bitrate=(max_bitrate+min_bitrate)*.5;
  154190. else
  154191. nominal_bitrate=max_bitrate*.875;
  154192. }else{
  154193. if(min_bitrate>0.){
  154194. nominal_bitrate=min_bitrate;
  154195. }else{
  154196. return(OV_EINVAL);
  154197. }
  154198. }
  154199. }
  154200. get_setup_template(vi,channels,rate,nominal_bitrate,1);
  154201. if(!hi->setup)return OV_EIMPL;
  154202. ret=vorbis_encode_setup_setting(vi,channels,rate);
  154203. if(ret){
  154204. vorbis_info_clear(vi);
  154205. return ret;
  154206. }
  154207. /* initialize management with sane defaults */
  154208. hi->managed=1;
  154209. hi->bitrate_min=min_bitrate;
  154210. hi->bitrate_max=max_bitrate;
  154211. hi->bitrate_av=tnominal;
  154212. hi->bitrate_av_damp=1.5f; /* full range in no less than 1.5 second */
  154213. hi->bitrate_reservoir=nominal_bitrate*2;
  154214. hi->bitrate_reservoir_bias=.1; /* bias toward hoarding bits */
  154215. return(ret);
  154216. }
  154217. int vorbis_encode_init(vorbis_info *vi,
  154218. long channels,
  154219. long rate,
  154220. long max_bitrate,
  154221. long nominal_bitrate,
  154222. long min_bitrate){
  154223. int ret=vorbis_encode_setup_managed(vi,channels,rate,
  154224. max_bitrate,
  154225. nominal_bitrate,
  154226. min_bitrate);
  154227. if(ret){
  154228. vorbis_info_clear(vi);
  154229. return(ret);
  154230. }
  154231. ret=vorbis_encode_setup_init(vi);
  154232. if(ret)
  154233. vorbis_info_clear(vi);
  154234. return(ret);
  154235. }
  154236. int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg){
  154237. if(vi){
  154238. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154239. highlevel_encode_setup *hi=&ci->hi;
  154240. int setp=(number&0xf); /* a read request has a low nibble of 0 */
  154241. if(setp && hi->set_in_stone)return(OV_EINVAL);
  154242. switch(number){
  154243. /* now deprecated *****************/
  154244. case OV_ECTL_RATEMANAGE_GET:
  154245. {
  154246. struct ovectl_ratemanage_arg *ai=
  154247. (struct ovectl_ratemanage_arg *)arg;
  154248. ai->management_active=hi->managed;
  154249. ai->bitrate_hard_window=ai->bitrate_av_window=
  154250. (double)hi->bitrate_reservoir/vi->rate;
  154251. ai->bitrate_av_window_center=1.;
  154252. ai->bitrate_hard_min=hi->bitrate_min;
  154253. ai->bitrate_hard_max=hi->bitrate_max;
  154254. ai->bitrate_av_lo=hi->bitrate_av;
  154255. ai->bitrate_av_hi=hi->bitrate_av;
  154256. }
  154257. return(0);
  154258. /* now deprecated *****************/
  154259. case OV_ECTL_RATEMANAGE_SET:
  154260. {
  154261. struct ovectl_ratemanage_arg *ai=
  154262. (struct ovectl_ratemanage_arg *)arg;
  154263. if(ai==NULL){
  154264. hi->managed=0;
  154265. }else{
  154266. hi->managed=ai->management_active;
  154267. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_AVG,arg);
  154268. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_HARD,arg);
  154269. }
  154270. }
  154271. return 0;
  154272. /* now deprecated *****************/
  154273. case OV_ECTL_RATEMANAGE_AVG:
  154274. {
  154275. struct ovectl_ratemanage_arg *ai=
  154276. (struct ovectl_ratemanage_arg *)arg;
  154277. if(ai==NULL){
  154278. hi->bitrate_av=0;
  154279. }else{
  154280. hi->bitrate_av=(ai->bitrate_av_lo+ai->bitrate_av_hi)*.5;
  154281. }
  154282. }
  154283. return(0);
  154284. /* now deprecated *****************/
  154285. case OV_ECTL_RATEMANAGE_HARD:
  154286. {
  154287. struct ovectl_ratemanage_arg *ai=
  154288. (struct ovectl_ratemanage_arg *)arg;
  154289. if(ai==NULL){
  154290. hi->bitrate_min=0;
  154291. hi->bitrate_max=0;
  154292. }else{
  154293. hi->bitrate_min=ai->bitrate_hard_min;
  154294. hi->bitrate_max=ai->bitrate_hard_max;
  154295. hi->bitrate_reservoir=ai->bitrate_hard_window*
  154296. (hi->bitrate_max+hi->bitrate_min)*.5;
  154297. }
  154298. if(hi->bitrate_reservoir<128.)
  154299. hi->bitrate_reservoir=128.;
  154300. }
  154301. return(0);
  154302. /* replacement ratemanage interface */
  154303. case OV_ECTL_RATEMANAGE2_GET:
  154304. {
  154305. struct ovectl_ratemanage2_arg *ai=
  154306. (struct ovectl_ratemanage2_arg *)arg;
  154307. if(ai==NULL)return OV_EINVAL;
  154308. ai->management_active=hi->managed;
  154309. ai->bitrate_limit_min_kbps=hi->bitrate_min/1000;
  154310. ai->bitrate_limit_max_kbps=hi->bitrate_max/1000;
  154311. ai->bitrate_average_kbps=hi->bitrate_av/1000;
  154312. ai->bitrate_average_damping=hi->bitrate_av_damp;
  154313. ai->bitrate_limit_reservoir_bits=hi->bitrate_reservoir;
  154314. ai->bitrate_limit_reservoir_bias=hi->bitrate_reservoir_bias;
  154315. }
  154316. return (0);
  154317. case OV_ECTL_RATEMANAGE2_SET:
  154318. {
  154319. struct ovectl_ratemanage2_arg *ai=
  154320. (struct ovectl_ratemanage2_arg *)arg;
  154321. if(ai==NULL){
  154322. hi->managed=0;
  154323. }else{
  154324. /* sanity check; only catch invariant violations */
  154325. if(ai->bitrate_limit_min_kbps>0 &&
  154326. ai->bitrate_average_kbps>0 &&
  154327. ai->bitrate_limit_min_kbps>ai->bitrate_average_kbps)
  154328. return OV_EINVAL;
  154329. if(ai->bitrate_limit_max_kbps>0 &&
  154330. ai->bitrate_average_kbps>0 &&
  154331. ai->bitrate_limit_max_kbps<ai->bitrate_average_kbps)
  154332. return OV_EINVAL;
  154333. if(ai->bitrate_limit_min_kbps>0 &&
  154334. ai->bitrate_limit_max_kbps>0 &&
  154335. ai->bitrate_limit_min_kbps>ai->bitrate_limit_max_kbps)
  154336. return OV_EINVAL;
  154337. if(ai->bitrate_average_damping <= 0.)
  154338. return OV_EINVAL;
  154339. if(ai->bitrate_limit_reservoir_bits < 0)
  154340. return OV_EINVAL;
  154341. if(ai->bitrate_limit_reservoir_bias < 0.)
  154342. return OV_EINVAL;
  154343. if(ai->bitrate_limit_reservoir_bias > 1.)
  154344. return OV_EINVAL;
  154345. hi->managed=ai->management_active;
  154346. hi->bitrate_min=ai->bitrate_limit_min_kbps * 1000;
  154347. hi->bitrate_max=ai->bitrate_limit_max_kbps * 1000;
  154348. hi->bitrate_av=ai->bitrate_average_kbps * 1000;
  154349. hi->bitrate_av_damp=ai->bitrate_average_damping;
  154350. hi->bitrate_reservoir=ai->bitrate_limit_reservoir_bits;
  154351. hi->bitrate_reservoir_bias=ai->bitrate_limit_reservoir_bias;
  154352. }
  154353. }
  154354. return 0;
  154355. case OV_ECTL_LOWPASS_GET:
  154356. {
  154357. double *farg=(double *)arg;
  154358. *farg=hi->lowpass_kHz;
  154359. }
  154360. return(0);
  154361. case OV_ECTL_LOWPASS_SET:
  154362. {
  154363. double *farg=(double *)arg;
  154364. hi->lowpass_kHz=*farg;
  154365. if(hi->lowpass_kHz<2.)hi->lowpass_kHz=2.;
  154366. if(hi->lowpass_kHz>99.)hi->lowpass_kHz=99.;
  154367. }
  154368. return(0);
  154369. case OV_ECTL_IBLOCK_GET:
  154370. {
  154371. double *farg=(double *)arg;
  154372. *farg=hi->impulse_noisetune;
  154373. }
  154374. return(0);
  154375. case OV_ECTL_IBLOCK_SET:
  154376. {
  154377. double *farg=(double *)arg;
  154378. hi->impulse_noisetune=*farg;
  154379. if(hi->impulse_noisetune>0.)hi->impulse_noisetune=0.;
  154380. if(hi->impulse_noisetune<-15.)hi->impulse_noisetune=-15.;
  154381. }
  154382. return(0);
  154383. }
  154384. return(OV_EIMPL);
  154385. }
  154386. return(OV_EINVAL);
  154387. }
  154388. #endif
  154389. /*** End of inlined file: vorbisenc.c ***/
  154390. /*** Start of inlined file: vorbisfile.c ***/
  154391. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  154392. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  154393. // tasks..
  154394. #if JUCE_MSVC
  154395. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  154396. #endif
  154397. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  154398. #if JUCE_USE_OGGVORBIS
  154399. #include <stdlib.h>
  154400. #include <stdio.h>
  154401. #include <errno.h>
  154402. #include <string.h>
  154403. #include <math.h>
  154404. /* A 'chained bitstream' is a Vorbis bitstream that contains more than
  154405. one logical bitstream arranged end to end (the only form of Ogg
  154406. multiplexing allowed in a Vorbis bitstream; grouping [parallel
  154407. multiplexing] is not allowed in Vorbis) */
  154408. /* A Vorbis file can be played beginning to end (streamed) without
  154409. worrying ahead of time about chaining (see decoder_example.c). If
  154410. we have the whole file, however, and want random access
  154411. (seeking/scrubbing) or desire to know the total length/time of a
  154412. file, we need to account for the possibility of chaining. */
  154413. /* We can handle things a number of ways; we can determine the entire
  154414. bitstream structure right off the bat, or find pieces on demand.
  154415. This example determines and caches structure for the entire
  154416. bitstream, but builds a virtual decoder on the fly when moving
  154417. between links in the chain. */
  154418. /* There are also different ways to implement seeking. Enough
  154419. information exists in an Ogg bitstream to seek to
  154420. sample-granularity positions in the output. Or, one can seek by
  154421. picking some portion of the stream roughly in the desired area if
  154422. we only want coarse navigation through the stream. */
  154423. /*************************************************************************
  154424. * Many, many internal helpers. The intention is not to be confusing;
  154425. * rampant duplication and monolithic function implementation would be
  154426. * harder to understand anyway. The high level functions are last. Begin
  154427. * grokking near the end of the file */
  154428. /* read a little more data from the file/pipe into the ogg_sync framer
  154429. */
  154430. #define CHUNKSIZE 8500 /* a shade over 8k; anyone using pages well
  154431. over 8k gets what they deserve */
  154432. static long _get_data(OggVorbis_File *vf){
  154433. errno=0;
  154434. if(vf->datasource){
  154435. char *buffer=ogg_sync_buffer(&vf->oy,CHUNKSIZE);
  154436. long bytes=(vf->callbacks.read_func)(buffer,1,CHUNKSIZE,vf->datasource);
  154437. if(bytes>0)ogg_sync_wrote(&vf->oy,bytes);
  154438. if(bytes==0 && errno)return(-1);
  154439. return(bytes);
  154440. }else
  154441. return(0);
  154442. }
  154443. /* save a tiny smidge of verbosity to make the code more readable */
  154444. static void _seek_helper(OggVorbis_File *vf,ogg_int64_t offset){
  154445. if(vf->datasource){
  154446. (vf->callbacks.seek_func)(vf->datasource, offset, SEEK_SET);
  154447. vf->offset=offset;
  154448. ogg_sync_reset(&vf->oy);
  154449. }else{
  154450. /* shouldn't happen unless someone writes a broken callback */
  154451. return;
  154452. }
  154453. }
  154454. /* The read/seek functions track absolute position within the stream */
  154455. /* from the head of the stream, get the next page. boundary specifies
  154456. if the function is allowed to fetch more data from the stream (and
  154457. how much) or only use internally buffered data.
  154458. boundary: -1) unbounded search
  154459. 0) read no additional data; use cached only
  154460. n) search for a new page beginning for n bytes
  154461. return: <0) did not find a page (OV_FALSE, OV_EOF, OV_EREAD)
  154462. n) found a page at absolute offset n */
  154463. static ogg_int64_t _get_next_page(OggVorbis_File *vf,ogg_page *og,
  154464. ogg_int64_t boundary){
  154465. if(boundary>0)boundary+=vf->offset;
  154466. while(1){
  154467. long more;
  154468. if(boundary>0 && vf->offset>=boundary)return(OV_FALSE);
  154469. more=ogg_sync_pageseek(&vf->oy,og);
  154470. if(more<0){
  154471. /* skipped n bytes */
  154472. vf->offset-=more;
  154473. }else{
  154474. if(more==0){
  154475. /* send more paramedics */
  154476. if(!boundary)return(OV_FALSE);
  154477. {
  154478. long ret=_get_data(vf);
  154479. if(ret==0)return(OV_EOF);
  154480. if(ret<0)return(OV_EREAD);
  154481. }
  154482. }else{
  154483. /* got a page. Return the offset at the page beginning,
  154484. advance the internal offset past the page end */
  154485. ogg_int64_t ret=vf->offset;
  154486. vf->offset+=more;
  154487. return(ret);
  154488. }
  154489. }
  154490. }
  154491. }
  154492. /* find the latest page beginning before the current stream cursor
  154493. position. Much dirtier than the above as Ogg doesn't have any
  154494. backward search linkage. no 'readp' as it will certainly have to
  154495. read. */
  154496. /* returns offset or OV_EREAD, OV_FAULT */
  154497. static ogg_int64_t _get_prev_page(OggVorbis_File *vf,ogg_page *og){
  154498. ogg_int64_t begin=vf->offset;
  154499. ogg_int64_t end=begin;
  154500. ogg_int64_t ret;
  154501. ogg_int64_t offset=-1;
  154502. while(offset==-1){
  154503. begin-=CHUNKSIZE;
  154504. if(begin<0)
  154505. begin=0;
  154506. _seek_helper(vf,begin);
  154507. while(vf->offset<end){
  154508. ret=_get_next_page(vf,og,end-vf->offset);
  154509. if(ret==OV_EREAD)return(OV_EREAD);
  154510. if(ret<0){
  154511. break;
  154512. }else{
  154513. offset=ret;
  154514. }
  154515. }
  154516. }
  154517. /* we have the offset. Actually snork and hold the page now */
  154518. _seek_helper(vf,offset);
  154519. ret=_get_next_page(vf,og,CHUNKSIZE);
  154520. if(ret<0)
  154521. /* this shouldn't be possible */
  154522. return(OV_EFAULT);
  154523. return(offset);
  154524. }
  154525. /* finds each bitstream link one at a time using a bisection search
  154526. (has to begin by knowing the offset of the lb's initial page).
  154527. Recurses for each link so it can alloc the link storage after
  154528. finding them all, then unroll and fill the cache at the same time */
  154529. static int _bisect_forward_serialno(OggVorbis_File *vf,
  154530. ogg_int64_t begin,
  154531. ogg_int64_t searched,
  154532. ogg_int64_t end,
  154533. long currentno,
  154534. long m){
  154535. ogg_int64_t endsearched=end;
  154536. ogg_int64_t next=end;
  154537. ogg_page og;
  154538. ogg_int64_t ret;
  154539. /* the below guards against garbage seperating the last and
  154540. first pages of two links. */
  154541. while(searched<endsearched){
  154542. ogg_int64_t bisect;
  154543. if(endsearched-searched<CHUNKSIZE){
  154544. bisect=searched;
  154545. }else{
  154546. bisect=(searched+endsearched)/2;
  154547. }
  154548. _seek_helper(vf,bisect);
  154549. ret=_get_next_page(vf,&og,-1);
  154550. if(ret==OV_EREAD)return(OV_EREAD);
  154551. if(ret<0 || ogg_page_serialno(&og)!=currentno){
  154552. endsearched=bisect;
  154553. if(ret>=0)next=ret;
  154554. }else{
  154555. searched=ret+og.header_len+og.body_len;
  154556. }
  154557. }
  154558. _seek_helper(vf,next);
  154559. ret=_get_next_page(vf,&og,-1);
  154560. if(ret==OV_EREAD)return(OV_EREAD);
  154561. if(searched>=end || ret<0){
  154562. vf->links=m+1;
  154563. vf->offsets=(ogg_int64_t*)_ogg_malloc((vf->links+1)*sizeof(*vf->offsets));
  154564. vf->serialnos=(long*)_ogg_malloc(vf->links*sizeof(*vf->serialnos));
  154565. vf->offsets[m+1]=searched;
  154566. }else{
  154567. ret=_bisect_forward_serialno(vf,next,vf->offset,
  154568. end,ogg_page_serialno(&og),m+1);
  154569. if(ret==OV_EREAD)return(OV_EREAD);
  154570. }
  154571. vf->offsets[m]=begin;
  154572. vf->serialnos[m]=currentno;
  154573. return(0);
  154574. }
  154575. /* uses the local ogg_stream storage in vf; this is important for
  154576. non-streaming input sources */
  154577. static int _fetch_headers(OggVorbis_File *vf,vorbis_info *vi,vorbis_comment *vc,
  154578. long *serialno,ogg_page *og_ptr){
  154579. ogg_page og;
  154580. ogg_packet op;
  154581. int i,ret;
  154582. if(!og_ptr){
  154583. ogg_int64_t llret=_get_next_page(vf,&og,CHUNKSIZE);
  154584. if(llret==OV_EREAD)return(OV_EREAD);
  154585. if(llret<0)return OV_ENOTVORBIS;
  154586. og_ptr=&og;
  154587. }
  154588. ogg_stream_reset_serialno(&vf->os,ogg_page_serialno(og_ptr));
  154589. if(serialno)*serialno=vf->os.serialno;
  154590. vf->ready_state=STREAMSET;
  154591. /* extract the initial header from the first page and verify that the
  154592. Ogg bitstream is in fact Vorbis data */
  154593. vorbis_info_init(vi);
  154594. vorbis_comment_init(vc);
  154595. i=0;
  154596. while(i<3){
  154597. ogg_stream_pagein(&vf->os,og_ptr);
  154598. while(i<3){
  154599. int result=ogg_stream_packetout(&vf->os,&op);
  154600. if(result==0)break;
  154601. if(result==-1){
  154602. ret=OV_EBADHEADER;
  154603. goto bail_header;
  154604. }
  154605. if((ret=vorbis_synthesis_headerin(vi,vc,&op))){
  154606. goto bail_header;
  154607. }
  154608. i++;
  154609. }
  154610. if(i<3)
  154611. if(_get_next_page(vf,og_ptr,CHUNKSIZE)<0){
  154612. ret=OV_EBADHEADER;
  154613. goto bail_header;
  154614. }
  154615. }
  154616. return 0;
  154617. bail_header:
  154618. vorbis_info_clear(vi);
  154619. vorbis_comment_clear(vc);
  154620. vf->ready_state=OPENED;
  154621. return ret;
  154622. }
  154623. /* last step of the OggVorbis_File initialization; get all the
  154624. vorbis_info structs and PCM positions. Only called by the seekable
  154625. initialization (local stream storage is hacked slightly; pay
  154626. attention to how that's done) */
  154627. /* this is void and does not propogate errors up because we want to be
  154628. able to open and use damaged bitstreams as well as we can. Just
  154629. watch out for missing information for links in the OggVorbis_File
  154630. struct */
  154631. static void _prefetch_all_headers(OggVorbis_File *vf, ogg_int64_t dataoffset){
  154632. ogg_page og;
  154633. int i;
  154634. ogg_int64_t ret;
  154635. vf->vi=(vorbis_info*) _ogg_realloc(vf->vi,vf->links*sizeof(*vf->vi));
  154636. vf->vc=(vorbis_comment*) _ogg_realloc(vf->vc,vf->links*sizeof(*vf->vc));
  154637. vf->dataoffsets=(ogg_int64_t*) _ogg_malloc(vf->links*sizeof(*vf->dataoffsets));
  154638. vf->pcmlengths=(ogg_int64_t*) _ogg_malloc(vf->links*2*sizeof(*vf->pcmlengths));
  154639. for(i=0;i<vf->links;i++){
  154640. if(i==0){
  154641. /* we already grabbed the initial header earlier. Just set the offset */
  154642. vf->dataoffsets[i]=dataoffset;
  154643. _seek_helper(vf,dataoffset);
  154644. }else{
  154645. /* seek to the location of the initial header */
  154646. _seek_helper(vf,vf->offsets[i]);
  154647. if(_fetch_headers(vf,vf->vi+i,vf->vc+i,NULL,NULL)<0){
  154648. vf->dataoffsets[i]=-1;
  154649. }else{
  154650. vf->dataoffsets[i]=vf->offset;
  154651. }
  154652. }
  154653. /* fetch beginning PCM offset */
  154654. if(vf->dataoffsets[i]!=-1){
  154655. ogg_int64_t accumulated=0;
  154656. long lastblock=-1;
  154657. int result;
  154658. ogg_stream_reset_serialno(&vf->os,vf->serialnos[i]);
  154659. while(1){
  154660. ogg_packet op;
  154661. ret=_get_next_page(vf,&og,-1);
  154662. if(ret<0)
  154663. /* this should not be possible unless the file is
  154664. truncated/mangled */
  154665. break;
  154666. if(ogg_page_serialno(&og)!=vf->serialnos[i])
  154667. break;
  154668. /* count blocksizes of all frames in the page */
  154669. ogg_stream_pagein(&vf->os,&og);
  154670. while((result=ogg_stream_packetout(&vf->os,&op))){
  154671. if(result>0){ /* ignore holes */
  154672. long thisblock=vorbis_packet_blocksize(vf->vi+i,&op);
  154673. if(lastblock!=-1)
  154674. accumulated+=(lastblock+thisblock)>>2;
  154675. lastblock=thisblock;
  154676. }
  154677. }
  154678. if(ogg_page_granulepos(&og)!=-1){
  154679. /* pcm offset of last packet on the first audio page */
  154680. accumulated= ogg_page_granulepos(&og)-accumulated;
  154681. break;
  154682. }
  154683. }
  154684. /* less than zero? This is a stream with samples trimmed off
  154685. the beginning, a normal occurrence; set the offset to zero */
  154686. if(accumulated<0)accumulated=0;
  154687. vf->pcmlengths[i*2]=accumulated;
  154688. }
  154689. /* get the PCM length of this link. To do this,
  154690. get the last page of the stream */
  154691. {
  154692. ogg_int64_t end=vf->offsets[i+1];
  154693. _seek_helper(vf,end);
  154694. while(1){
  154695. ret=_get_prev_page(vf,&og);
  154696. if(ret<0){
  154697. /* this should not be possible */
  154698. vorbis_info_clear(vf->vi+i);
  154699. vorbis_comment_clear(vf->vc+i);
  154700. break;
  154701. }
  154702. if(ogg_page_granulepos(&og)!=-1){
  154703. vf->pcmlengths[i*2+1]=ogg_page_granulepos(&og)-vf->pcmlengths[i*2];
  154704. break;
  154705. }
  154706. vf->offset=ret;
  154707. }
  154708. }
  154709. }
  154710. }
  154711. static int _make_decode_ready(OggVorbis_File *vf){
  154712. if(vf->ready_state>STREAMSET)return 0;
  154713. if(vf->ready_state<STREAMSET)return OV_EFAULT;
  154714. if(vf->seekable){
  154715. if(vorbis_synthesis_init(&vf->vd,vf->vi+vf->current_link))
  154716. return OV_EBADLINK;
  154717. }else{
  154718. if(vorbis_synthesis_init(&vf->vd,vf->vi))
  154719. return OV_EBADLINK;
  154720. }
  154721. vorbis_block_init(&vf->vd,&vf->vb);
  154722. vf->ready_state=INITSET;
  154723. vf->bittrack=0.f;
  154724. vf->samptrack=0.f;
  154725. return 0;
  154726. }
  154727. static int _open_seekable2(OggVorbis_File *vf){
  154728. long serialno=vf->current_serialno;
  154729. ogg_int64_t dataoffset=vf->offset, end;
  154730. ogg_page og;
  154731. /* we're partially open and have a first link header state in
  154732. storage in vf */
  154733. /* we can seek, so set out learning all about this file */
  154734. (vf->callbacks.seek_func)(vf->datasource,0,SEEK_END);
  154735. vf->offset=vf->end=(vf->callbacks.tell_func)(vf->datasource);
  154736. /* We get the offset for the last page of the physical bitstream.
  154737. Most OggVorbis files will contain a single logical bitstream */
  154738. end=_get_prev_page(vf,&og);
  154739. if(end<0)return(end);
  154740. /* more than one logical bitstream? */
  154741. if(ogg_page_serialno(&og)!=serialno){
  154742. /* Chained bitstream. Bisect-search each logical bitstream
  154743. section. Do so based on serial number only */
  154744. if(_bisect_forward_serialno(vf,0,0,end+1,serialno,0)<0)return(OV_EREAD);
  154745. }else{
  154746. /* Only one logical bitstream */
  154747. if(_bisect_forward_serialno(vf,0,end,end+1,serialno,0))return(OV_EREAD);
  154748. }
  154749. /* the initial header memory is referenced by vf after; don't free it */
  154750. _prefetch_all_headers(vf,dataoffset);
  154751. return(ov_raw_seek(vf,0));
  154752. }
  154753. /* clear out the current logical bitstream decoder */
  154754. static void _decode_clear(OggVorbis_File *vf){
  154755. vorbis_dsp_clear(&vf->vd);
  154756. vorbis_block_clear(&vf->vb);
  154757. vf->ready_state=OPENED;
  154758. }
  154759. /* fetch and process a packet. Handles the case where we're at a
  154760. bitstream boundary and dumps the decoding machine. If the decoding
  154761. machine is unloaded, it loads it. It also keeps pcm_offset up to
  154762. date (seek and read both use this. seek uses a special hack with
  154763. readp).
  154764. return: <0) error, OV_HOLE (lost packet) or OV_EOF
  154765. 0) need more data (only if readp==0)
  154766. 1) got a packet
  154767. */
  154768. static int _fetch_and_process_packet(OggVorbis_File *vf,
  154769. ogg_packet *op_in,
  154770. int readp,
  154771. int spanp){
  154772. ogg_page og;
  154773. /* handle one packet. Try to fetch it from current stream state */
  154774. /* extract packets from page */
  154775. while(1){
  154776. /* process a packet if we can. If the machine isn't loaded,
  154777. neither is a page */
  154778. if(vf->ready_state==INITSET){
  154779. while(1) {
  154780. ogg_packet op;
  154781. ogg_packet *op_ptr=(op_in?op_in:&op);
  154782. int result=ogg_stream_packetout(&vf->os,op_ptr);
  154783. ogg_int64_t granulepos;
  154784. op_in=NULL;
  154785. if(result==-1)return(OV_HOLE); /* hole in the data. */
  154786. if(result>0){
  154787. /* got a packet. process it */
  154788. granulepos=op_ptr->granulepos;
  154789. if(!vorbis_synthesis(&vf->vb,op_ptr)){ /* lazy check for lazy
  154790. header handling. The
  154791. header packets aren't
  154792. audio, so if/when we
  154793. submit them,
  154794. vorbis_synthesis will
  154795. reject them */
  154796. /* suck in the synthesis data and track bitrate */
  154797. {
  154798. int oldsamples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  154799. /* for proper use of libvorbis within libvorbisfile,
  154800. oldsamples will always be zero. */
  154801. if(oldsamples)return(OV_EFAULT);
  154802. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  154803. vf->samptrack+=vorbis_synthesis_pcmout(&vf->vd,NULL)-oldsamples;
  154804. vf->bittrack+=op_ptr->bytes*8;
  154805. }
  154806. /* update the pcm offset. */
  154807. if(granulepos!=-1 && !op_ptr->e_o_s){
  154808. int link=(vf->seekable?vf->current_link:0);
  154809. int i,samples;
  154810. /* this packet has a pcm_offset on it (the last packet
  154811. completed on a page carries the offset) After processing
  154812. (above), we know the pcm position of the *last* sample
  154813. ready to be returned. Find the offset of the *first*
  154814. As an aside, this trick is inaccurate if we begin
  154815. reading anew right at the last page; the end-of-stream
  154816. granulepos declares the last frame in the stream, and the
  154817. last packet of the last page may be a partial frame.
  154818. So, we need a previous granulepos from an in-sequence page
  154819. to have a reference point. Thus the !op_ptr->e_o_s clause
  154820. above */
  154821. if(vf->seekable && link>0)
  154822. granulepos-=vf->pcmlengths[link*2];
  154823. if(granulepos<0)granulepos=0; /* actually, this
  154824. shouldn't be possible
  154825. here unless the stream
  154826. is very broken */
  154827. samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  154828. granulepos-=samples;
  154829. for(i=0;i<link;i++)
  154830. granulepos+=vf->pcmlengths[i*2+1];
  154831. vf->pcm_offset=granulepos;
  154832. }
  154833. return(1);
  154834. }
  154835. }
  154836. else
  154837. break;
  154838. }
  154839. }
  154840. if(vf->ready_state>=OPENED){
  154841. ogg_int64_t ret;
  154842. if(!readp)return(0);
  154843. if((ret=_get_next_page(vf,&og,-1))<0){
  154844. return(OV_EOF); /* eof.
  154845. leave unitialized */
  154846. }
  154847. /* bitrate tracking; add the header's bytes here, the body bytes
  154848. are done by packet above */
  154849. vf->bittrack+=og.header_len*8;
  154850. /* has our decoding just traversed a bitstream boundary? */
  154851. if(vf->ready_state==INITSET){
  154852. if(vf->current_serialno!=ogg_page_serialno(&og)){
  154853. if(!spanp)
  154854. return(OV_EOF);
  154855. _decode_clear(vf);
  154856. if(!vf->seekable){
  154857. vorbis_info_clear(vf->vi);
  154858. vorbis_comment_clear(vf->vc);
  154859. }
  154860. }
  154861. }
  154862. }
  154863. /* Do we need to load a new machine before submitting the page? */
  154864. /* This is different in the seekable and non-seekable cases.
  154865. In the seekable case, we already have all the header
  154866. information loaded and cached; we just initialize the machine
  154867. with it and continue on our merry way.
  154868. In the non-seekable (streaming) case, we'll only be at a
  154869. boundary if we just left the previous logical bitstream and
  154870. we're now nominally at the header of the next bitstream
  154871. */
  154872. if(vf->ready_state!=INITSET){
  154873. int link;
  154874. if(vf->ready_state<STREAMSET){
  154875. if(vf->seekable){
  154876. vf->current_serialno=ogg_page_serialno(&og);
  154877. /* match the serialno to bitstream section. We use this rather than
  154878. offset positions to avoid problems near logical bitstream
  154879. boundaries */
  154880. for(link=0;link<vf->links;link++)
  154881. if(vf->serialnos[link]==vf->current_serialno)break;
  154882. if(link==vf->links)return(OV_EBADLINK); /* sign of a bogus
  154883. stream. error out,
  154884. leave machine
  154885. uninitialized */
  154886. vf->current_link=link;
  154887. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  154888. vf->ready_state=STREAMSET;
  154889. }else{
  154890. /* we're streaming */
  154891. /* fetch the three header packets, build the info struct */
  154892. int ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,&og);
  154893. if(ret)return(ret);
  154894. vf->current_link++;
  154895. link=0;
  154896. }
  154897. }
  154898. {
  154899. int ret=_make_decode_ready(vf);
  154900. if(ret<0)return ret;
  154901. }
  154902. }
  154903. ogg_stream_pagein(&vf->os,&og);
  154904. }
  154905. }
  154906. /* if, eg, 64 bit stdio is configured by default, this will build with
  154907. fseek64 */
  154908. static int _fseek64_wrap(FILE *f,ogg_int64_t off,int whence){
  154909. if(f==NULL)return(-1);
  154910. return fseek(f,off,whence);
  154911. }
  154912. static int _ov_open1(void *f,OggVorbis_File *vf,char *initial,
  154913. long ibytes, ov_callbacks callbacks){
  154914. int offsettest=(f?callbacks.seek_func(f,0,SEEK_CUR):-1);
  154915. int ret;
  154916. memset(vf,0,sizeof(*vf));
  154917. vf->datasource=f;
  154918. vf->callbacks = callbacks;
  154919. /* init the framing state */
  154920. ogg_sync_init(&vf->oy);
  154921. /* perhaps some data was previously read into a buffer for testing
  154922. against other stream types. Allow initialization from this
  154923. previously read data (as we may be reading from a non-seekable
  154924. stream) */
  154925. if(initial){
  154926. char *buffer=ogg_sync_buffer(&vf->oy,ibytes);
  154927. memcpy(buffer,initial,ibytes);
  154928. ogg_sync_wrote(&vf->oy,ibytes);
  154929. }
  154930. /* can we seek? Stevens suggests the seek test was portable */
  154931. if(offsettest!=-1)vf->seekable=1;
  154932. /* No seeking yet; Set up a 'single' (current) logical bitstream
  154933. entry for partial open */
  154934. vf->links=1;
  154935. vf->vi=(vorbis_info*) _ogg_calloc(vf->links,sizeof(*vf->vi));
  154936. vf->vc=(vorbis_comment*) _ogg_calloc(vf->links,sizeof(*vf->vc));
  154937. ogg_stream_init(&vf->os,-1); /* fill in the serialno later */
  154938. /* Try to fetch the headers, maintaining all the storage */
  154939. if((ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,NULL))<0){
  154940. vf->datasource=NULL;
  154941. ov_clear(vf);
  154942. }else
  154943. vf->ready_state=PARTOPEN;
  154944. return(ret);
  154945. }
  154946. static int _ov_open2(OggVorbis_File *vf){
  154947. if(vf->ready_state != PARTOPEN) return OV_EINVAL;
  154948. vf->ready_state=OPENED;
  154949. if(vf->seekable){
  154950. int ret=_open_seekable2(vf);
  154951. if(ret){
  154952. vf->datasource=NULL;
  154953. ov_clear(vf);
  154954. }
  154955. return(ret);
  154956. }else
  154957. vf->ready_state=STREAMSET;
  154958. return 0;
  154959. }
  154960. /* clear out the OggVorbis_File struct */
  154961. int ov_clear(OggVorbis_File *vf){
  154962. if(vf){
  154963. vorbis_block_clear(&vf->vb);
  154964. vorbis_dsp_clear(&vf->vd);
  154965. ogg_stream_clear(&vf->os);
  154966. if(vf->vi && vf->links){
  154967. int i;
  154968. for(i=0;i<vf->links;i++){
  154969. vorbis_info_clear(vf->vi+i);
  154970. vorbis_comment_clear(vf->vc+i);
  154971. }
  154972. _ogg_free(vf->vi);
  154973. _ogg_free(vf->vc);
  154974. }
  154975. if(vf->dataoffsets)_ogg_free(vf->dataoffsets);
  154976. if(vf->pcmlengths)_ogg_free(vf->pcmlengths);
  154977. if(vf->serialnos)_ogg_free(vf->serialnos);
  154978. if(vf->offsets)_ogg_free(vf->offsets);
  154979. ogg_sync_clear(&vf->oy);
  154980. if(vf->datasource)(vf->callbacks.close_func)(vf->datasource);
  154981. memset(vf,0,sizeof(*vf));
  154982. }
  154983. #ifdef DEBUG_LEAKS
  154984. _VDBG_dump();
  154985. #endif
  154986. return(0);
  154987. }
  154988. /* inspects the OggVorbis file and finds/documents all the logical
  154989. bitstreams contained in it. Tries to be tolerant of logical
  154990. bitstream sections that are truncated/woogie.
  154991. return: -1) error
  154992. 0) OK
  154993. */
  154994. int ov_open_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  154995. ov_callbacks callbacks){
  154996. int ret=_ov_open1(f,vf,initial,ibytes,callbacks);
  154997. if(ret)return ret;
  154998. return _ov_open2(vf);
  154999. }
  155000. int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  155001. ov_callbacks callbacks = {
  155002. (size_t (*)(void *, size_t, size_t, void *)) fread,
  155003. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  155004. (int (*)(void *)) fclose,
  155005. (long (*)(void *)) ftell
  155006. };
  155007. return ov_open_callbacks((void *)f, vf, initial, ibytes, callbacks);
  155008. }
  155009. /* cheap hack for game usage where downsampling is desirable; there's
  155010. no need for SRC as we can just do it cheaply in libvorbis. */
  155011. int ov_halfrate(OggVorbis_File *vf,int flag){
  155012. int i;
  155013. if(vf->vi==NULL)return OV_EINVAL;
  155014. if(!vf->seekable)return OV_EINVAL;
  155015. if(vf->ready_state>=STREAMSET)
  155016. _decode_clear(vf); /* clear out stream state; later on libvorbis
  155017. will be able to swap this on the fly, but
  155018. for now dumping the decode machine is needed
  155019. to reinit the MDCT lookups. 1.1 libvorbis
  155020. is planned to be able to switch on the fly */
  155021. for(i=0;i<vf->links;i++){
  155022. if(vorbis_synthesis_halfrate(vf->vi+i,flag)){
  155023. ov_halfrate(vf,0);
  155024. return OV_EINVAL;
  155025. }
  155026. }
  155027. return 0;
  155028. }
  155029. int ov_halfrate_p(OggVorbis_File *vf){
  155030. if(vf->vi==NULL)return OV_EINVAL;
  155031. return vorbis_synthesis_halfrate_p(vf->vi);
  155032. }
  155033. /* Only partially open the vorbis file; test for Vorbisness, and load
  155034. the headers for the first chain. Do not seek (although test for
  155035. seekability). Use ov_test_open to finish opening the file, else
  155036. ov_clear to close/free it. Same return codes as open. */
  155037. int ov_test_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  155038. ov_callbacks callbacks)
  155039. {
  155040. return _ov_open1(f,vf,initial,ibytes,callbacks);
  155041. }
  155042. int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  155043. ov_callbacks callbacks = {
  155044. (size_t (*)(void *, size_t, size_t, void *)) fread,
  155045. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  155046. (int (*)(void *)) fclose,
  155047. (long (*)(void *)) ftell
  155048. };
  155049. return ov_test_callbacks((void *)f, vf, initial, ibytes, callbacks);
  155050. }
  155051. int ov_test_open(OggVorbis_File *vf){
  155052. if(vf->ready_state!=PARTOPEN)return(OV_EINVAL);
  155053. return _ov_open2(vf);
  155054. }
  155055. /* How many logical bitstreams in this physical bitstream? */
  155056. long ov_streams(OggVorbis_File *vf){
  155057. return vf->links;
  155058. }
  155059. /* Is the FILE * associated with vf seekable? */
  155060. long ov_seekable(OggVorbis_File *vf){
  155061. return vf->seekable;
  155062. }
  155063. /* returns the bitrate for a given logical bitstream or the entire
  155064. physical bitstream. If the file is open for random access, it will
  155065. find the *actual* average bitrate. If the file is streaming, it
  155066. returns the nominal bitrate (if set) else the average of the
  155067. upper/lower bounds (if set) else -1 (unset).
  155068. If you want the actual bitrate field settings, get them from the
  155069. vorbis_info structs */
  155070. long ov_bitrate(OggVorbis_File *vf,int i){
  155071. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155072. if(i>=vf->links)return(OV_EINVAL);
  155073. if(!vf->seekable && i!=0)return(ov_bitrate(vf,0));
  155074. if(i<0){
  155075. ogg_int64_t bits=0;
  155076. int i;
  155077. float br;
  155078. for(i=0;i<vf->links;i++)
  155079. bits+=(vf->offsets[i+1]-vf->dataoffsets[i])*8;
  155080. /* This once read: return(rint(bits/ov_time_total(vf,-1)));
  155081. * gcc 3.x on x86 miscompiled this at optimisation level 2 and above,
  155082. * so this is slightly transformed to make it work.
  155083. */
  155084. br = bits/ov_time_total(vf,-1);
  155085. return(rint(br));
  155086. }else{
  155087. if(vf->seekable){
  155088. /* return the actual bitrate */
  155089. return(rint((vf->offsets[i+1]-vf->dataoffsets[i])*8/ov_time_total(vf,i)));
  155090. }else{
  155091. /* return nominal if set */
  155092. if(vf->vi[i].bitrate_nominal>0){
  155093. return vf->vi[i].bitrate_nominal;
  155094. }else{
  155095. if(vf->vi[i].bitrate_upper>0){
  155096. if(vf->vi[i].bitrate_lower>0){
  155097. return (vf->vi[i].bitrate_upper+vf->vi[i].bitrate_lower)/2;
  155098. }else{
  155099. return vf->vi[i].bitrate_upper;
  155100. }
  155101. }
  155102. return(OV_FALSE);
  155103. }
  155104. }
  155105. }
  155106. }
  155107. /* returns the actual bitrate since last call. returns -1 if no
  155108. additional data to offer since last call (or at beginning of stream),
  155109. EINVAL if stream is only partially open
  155110. */
  155111. long ov_bitrate_instant(OggVorbis_File *vf){
  155112. int link=(vf->seekable?vf->current_link:0);
  155113. long ret;
  155114. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155115. if(vf->samptrack==0)return(OV_FALSE);
  155116. ret=vf->bittrack/vf->samptrack*vf->vi[link].rate+.5;
  155117. vf->bittrack=0.f;
  155118. vf->samptrack=0.f;
  155119. return(ret);
  155120. }
  155121. /* Guess */
  155122. long ov_serialnumber(OggVorbis_File *vf,int i){
  155123. if(i>=vf->links)return(ov_serialnumber(vf,vf->links-1));
  155124. if(!vf->seekable && i>=0)return(ov_serialnumber(vf,-1));
  155125. if(i<0){
  155126. return(vf->current_serialno);
  155127. }else{
  155128. return(vf->serialnos[i]);
  155129. }
  155130. }
  155131. /* returns: total raw (compressed) length of content if i==-1
  155132. raw (compressed) length of that logical bitstream for i==0 to n
  155133. OV_EINVAL if the stream is not seekable (we can't know the length)
  155134. or if stream is only partially open
  155135. */
  155136. ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i){
  155137. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155138. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  155139. if(i<0){
  155140. ogg_int64_t acc=0;
  155141. int i;
  155142. for(i=0;i<vf->links;i++)
  155143. acc+=ov_raw_total(vf,i);
  155144. return(acc);
  155145. }else{
  155146. return(vf->offsets[i+1]-vf->offsets[i]);
  155147. }
  155148. }
  155149. /* returns: total PCM length (samples) of content if i==-1 PCM length
  155150. (samples) of that logical bitstream for i==0 to n
  155151. OV_EINVAL if the stream is not seekable (we can't know the
  155152. length) or only partially open
  155153. */
  155154. ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i){
  155155. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155156. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  155157. if(i<0){
  155158. ogg_int64_t acc=0;
  155159. int i;
  155160. for(i=0;i<vf->links;i++)
  155161. acc+=ov_pcm_total(vf,i);
  155162. return(acc);
  155163. }else{
  155164. return(vf->pcmlengths[i*2+1]);
  155165. }
  155166. }
  155167. /* returns: total seconds of content if i==-1
  155168. seconds in that logical bitstream for i==0 to n
  155169. OV_EINVAL if the stream is not seekable (we can't know the
  155170. length) or only partially open
  155171. */
  155172. double ov_time_total(OggVorbis_File *vf,int i){
  155173. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155174. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  155175. if(i<0){
  155176. double acc=0;
  155177. int i;
  155178. for(i=0;i<vf->links;i++)
  155179. acc+=ov_time_total(vf,i);
  155180. return(acc);
  155181. }else{
  155182. return((double)(vf->pcmlengths[i*2+1])/vf->vi[i].rate);
  155183. }
  155184. }
  155185. /* seek to an offset relative to the *compressed* data. This also
  155186. scans packets to update the PCM cursor. It will cross a logical
  155187. bitstream boundary, but only if it can't get any packets out of the
  155188. tail of the bitstream we seek to (so no surprises).
  155189. returns zero on success, nonzero on failure */
  155190. int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos){
  155191. ogg_stream_state work_os;
  155192. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155193. if(!vf->seekable)
  155194. return(OV_ENOSEEK); /* don't dump machine if we can't seek */
  155195. if(pos<0 || pos>vf->end)return(OV_EINVAL);
  155196. /* don't yet clear out decoding machine (if it's initialized), in
  155197. the case we're in the same link. Restart the decode lapping, and
  155198. let _fetch_and_process_packet deal with a potential bitstream
  155199. boundary */
  155200. vf->pcm_offset=-1;
  155201. ogg_stream_reset_serialno(&vf->os,
  155202. vf->current_serialno); /* must set serialno */
  155203. vorbis_synthesis_restart(&vf->vd);
  155204. _seek_helper(vf,pos);
  155205. /* we need to make sure the pcm_offset is set, but we don't want to
  155206. advance the raw cursor past good packets just to get to the first
  155207. with a granulepos. That's not equivalent behavior to beginning
  155208. decoding as immediately after the seek position as possible.
  155209. So, a hack. We use two stream states; a local scratch state and
  155210. the shared vf->os stream state. We use the local state to
  155211. scan, and the shared state as a buffer for later decode.
  155212. Unfortuantely, on the last page we still advance to last packet
  155213. because the granulepos on the last page is not necessarily on a
  155214. packet boundary, and we need to make sure the granpos is
  155215. correct.
  155216. */
  155217. {
  155218. ogg_page og;
  155219. ogg_packet op;
  155220. int lastblock=0;
  155221. int accblock=0;
  155222. int thisblock;
  155223. int eosflag;
  155224. ogg_stream_init(&work_os,vf->current_serialno); /* get the memory ready */
  155225. ogg_stream_reset(&work_os); /* eliminate the spurious OV_HOLE
  155226. return from not necessarily
  155227. starting from the beginning */
  155228. while(1){
  155229. if(vf->ready_state>=STREAMSET){
  155230. /* snarf/scan a packet if we can */
  155231. int result=ogg_stream_packetout(&work_os,&op);
  155232. if(result>0){
  155233. if(vf->vi[vf->current_link].codec_setup){
  155234. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  155235. if(thisblock<0){
  155236. ogg_stream_packetout(&vf->os,NULL);
  155237. thisblock=0;
  155238. }else{
  155239. if(eosflag)
  155240. ogg_stream_packetout(&vf->os,NULL);
  155241. else
  155242. if(lastblock)accblock+=(lastblock+thisblock)>>2;
  155243. }
  155244. if(op.granulepos!=-1){
  155245. int i,link=vf->current_link;
  155246. ogg_int64_t granulepos=op.granulepos-vf->pcmlengths[link*2];
  155247. if(granulepos<0)granulepos=0;
  155248. for(i=0;i<link;i++)
  155249. granulepos+=vf->pcmlengths[i*2+1];
  155250. vf->pcm_offset=granulepos-accblock;
  155251. break;
  155252. }
  155253. lastblock=thisblock;
  155254. continue;
  155255. }else
  155256. ogg_stream_packetout(&vf->os,NULL);
  155257. }
  155258. }
  155259. if(!lastblock){
  155260. if(_get_next_page(vf,&og,-1)<0){
  155261. vf->pcm_offset=ov_pcm_total(vf,-1);
  155262. break;
  155263. }
  155264. }else{
  155265. /* huh? Bogus stream with packets but no granulepos */
  155266. vf->pcm_offset=-1;
  155267. break;
  155268. }
  155269. /* has our decoding just traversed a bitstream boundary? */
  155270. if(vf->ready_state>=STREAMSET)
  155271. if(vf->current_serialno!=ogg_page_serialno(&og)){
  155272. _decode_clear(vf); /* clear out stream state */
  155273. ogg_stream_clear(&work_os);
  155274. }
  155275. if(vf->ready_state<STREAMSET){
  155276. int link;
  155277. vf->current_serialno=ogg_page_serialno(&og);
  155278. for(link=0;link<vf->links;link++)
  155279. if(vf->serialnos[link]==vf->current_serialno)break;
  155280. if(link==vf->links)goto seek_error; /* sign of a bogus stream.
  155281. error out, leave
  155282. machine uninitialized */
  155283. vf->current_link=link;
  155284. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  155285. ogg_stream_reset_serialno(&work_os,vf->current_serialno);
  155286. vf->ready_state=STREAMSET;
  155287. }
  155288. ogg_stream_pagein(&vf->os,&og);
  155289. ogg_stream_pagein(&work_os,&og);
  155290. eosflag=ogg_page_eos(&og);
  155291. }
  155292. }
  155293. ogg_stream_clear(&work_os);
  155294. vf->bittrack=0.f;
  155295. vf->samptrack=0.f;
  155296. return(0);
  155297. seek_error:
  155298. /* dump the machine so we're in a known state */
  155299. vf->pcm_offset=-1;
  155300. ogg_stream_clear(&work_os);
  155301. _decode_clear(vf);
  155302. return OV_EBADLINK;
  155303. }
  155304. /* Page granularity seek (faster than sample granularity because we
  155305. don't do the last bit of decode to find a specific sample).
  155306. Seek to the last [granule marked] page preceeding the specified pos
  155307. location, such that decoding past the returned point will quickly
  155308. arrive at the requested position. */
  155309. int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos){
  155310. int link=-1;
  155311. ogg_int64_t result=0;
  155312. ogg_int64_t total=ov_pcm_total(vf,-1);
  155313. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155314. if(!vf->seekable)return(OV_ENOSEEK);
  155315. if(pos<0 || pos>total)return(OV_EINVAL);
  155316. /* which bitstream section does this pcm offset occur in? */
  155317. for(link=vf->links-1;link>=0;link--){
  155318. total-=vf->pcmlengths[link*2+1];
  155319. if(pos>=total)break;
  155320. }
  155321. /* search within the logical bitstream for the page with the highest
  155322. pcm_pos preceeding (or equal to) pos. There is a danger here;
  155323. missing pages or incorrect frame number information in the
  155324. bitstream could make our task impossible. Account for that (it
  155325. would be an error condition) */
  155326. /* new search algorithm by HB (Nicholas Vinen) */
  155327. {
  155328. ogg_int64_t end=vf->offsets[link+1];
  155329. ogg_int64_t begin=vf->offsets[link];
  155330. ogg_int64_t begintime = vf->pcmlengths[link*2];
  155331. ogg_int64_t endtime = vf->pcmlengths[link*2+1]+begintime;
  155332. ogg_int64_t target=pos-total+begintime;
  155333. ogg_int64_t best=begin;
  155334. ogg_page og;
  155335. while(begin<end){
  155336. ogg_int64_t bisect;
  155337. if(end-begin<CHUNKSIZE){
  155338. bisect=begin;
  155339. }else{
  155340. /* take a (pretty decent) guess. */
  155341. bisect=begin +
  155342. (target-begintime)*(end-begin)/(endtime-begintime) - CHUNKSIZE;
  155343. if(bisect<=begin)
  155344. bisect=begin+1;
  155345. }
  155346. _seek_helper(vf,bisect);
  155347. while(begin<end){
  155348. result=_get_next_page(vf,&og,end-vf->offset);
  155349. if(result==OV_EREAD) goto seek_error;
  155350. if(result<0){
  155351. if(bisect<=begin+1)
  155352. end=begin; /* found it */
  155353. else{
  155354. if(bisect==0) goto seek_error;
  155355. bisect-=CHUNKSIZE;
  155356. if(bisect<=begin)bisect=begin+1;
  155357. _seek_helper(vf,bisect);
  155358. }
  155359. }else{
  155360. ogg_int64_t granulepos=ogg_page_granulepos(&og);
  155361. if(granulepos==-1)continue;
  155362. if(granulepos<target){
  155363. best=result; /* raw offset of packet with granulepos */
  155364. begin=vf->offset; /* raw offset of next page */
  155365. begintime=granulepos;
  155366. if(target-begintime>44100)break;
  155367. bisect=begin; /* *not* begin + 1 */
  155368. }else{
  155369. if(bisect<=begin+1)
  155370. end=begin; /* found it */
  155371. else{
  155372. if(end==vf->offset){ /* we're pretty close - we'd be stuck in */
  155373. end=result;
  155374. bisect-=CHUNKSIZE; /* an endless loop otherwise. */
  155375. if(bisect<=begin)bisect=begin+1;
  155376. _seek_helper(vf,bisect);
  155377. }else{
  155378. end=result;
  155379. endtime=granulepos;
  155380. break;
  155381. }
  155382. }
  155383. }
  155384. }
  155385. }
  155386. }
  155387. /* found our page. seek to it, update pcm offset. Easier case than
  155388. raw_seek, don't keep packets preceeding granulepos. */
  155389. {
  155390. ogg_page og;
  155391. ogg_packet op;
  155392. /* seek */
  155393. _seek_helper(vf,best);
  155394. vf->pcm_offset=-1;
  155395. if(_get_next_page(vf,&og,-1)<0)return(OV_EOF); /* shouldn't happen */
  155396. if(link!=vf->current_link){
  155397. /* Different link; dump entire decode machine */
  155398. _decode_clear(vf);
  155399. vf->current_link=link;
  155400. vf->current_serialno=ogg_page_serialno(&og);
  155401. vf->ready_state=STREAMSET;
  155402. }else{
  155403. vorbis_synthesis_restart(&vf->vd);
  155404. }
  155405. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  155406. ogg_stream_pagein(&vf->os,&og);
  155407. /* pull out all but last packet; the one with granulepos */
  155408. while(1){
  155409. result=ogg_stream_packetpeek(&vf->os,&op);
  155410. if(result==0){
  155411. /* !!! the packet finishing this page originated on a
  155412. preceeding page. Keep fetching previous pages until we
  155413. get one with a granulepos or without the 'continued' flag
  155414. set. Then just use raw_seek for simplicity. */
  155415. _seek_helper(vf,best);
  155416. while(1){
  155417. result=_get_prev_page(vf,&og);
  155418. if(result<0) goto seek_error;
  155419. if(ogg_page_granulepos(&og)>-1 ||
  155420. !ogg_page_continued(&og)){
  155421. return ov_raw_seek(vf,result);
  155422. }
  155423. vf->offset=result;
  155424. }
  155425. }
  155426. if(result<0){
  155427. result = OV_EBADPACKET;
  155428. goto seek_error;
  155429. }
  155430. if(op.granulepos!=-1){
  155431. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  155432. if(vf->pcm_offset<0)vf->pcm_offset=0;
  155433. vf->pcm_offset+=total;
  155434. break;
  155435. }else
  155436. result=ogg_stream_packetout(&vf->os,NULL);
  155437. }
  155438. }
  155439. }
  155440. /* verify result */
  155441. if(vf->pcm_offset>pos || pos>ov_pcm_total(vf,-1)){
  155442. result=OV_EFAULT;
  155443. goto seek_error;
  155444. }
  155445. vf->bittrack=0.f;
  155446. vf->samptrack=0.f;
  155447. return(0);
  155448. seek_error:
  155449. /* dump machine so we're in a known state */
  155450. vf->pcm_offset=-1;
  155451. _decode_clear(vf);
  155452. return (int)result;
  155453. }
  155454. /* seek to a sample offset relative to the decompressed pcm stream
  155455. returns zero on success, nonzero on failure */
  155456. int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos){
  155457. int thisblock,lastblock=0;
  155458. int ret=ov_pcm_seek_page(vf,pos);
  155459. if(ret<0)return(ret);
  155460. if((ret=_make_decode_ready(vf)))return ret;
  155461. /* discard leading packets we don't need for the lapping of the
  155462. position we want; don't decode them */
  155463. while(1){
  155464. ogg_packet op;
  155465. ogg_page og;
  155466. int ret=ogg_stream_packetpeek(&vf->os,&op);
  155467. if(ret>0){
  155468. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  155469. if(thisblock<0){
  155470. ogg_stream_packetout(&vf->os,NULL);
  155471. continue; /* non audio packet */
  155472. }
  155473. if(lastblock)vf->pcm_offset+=(lastblock+thisblock)>>2;
  155474. if(vf->pcm_offset+((thisblock+
  155475. vorbis_info_blocksize(vf->vi,1))>>2)>=pos)break;
  155476. /* remove the packet from packet queue and track its granulepos */
  155477. ogg_stream_packetout(&vf->os,NULL);
  155478. vorbis_synthesis_trackonly(&vf->vb,&op); /* set up a vb with
  155479. only tracking, no
  155480. pcm_decode */
  155481. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  155482. /* end of logical stream case is hard, especially with exact
  155483. length positioning. */
  155484. if(op.granulepos>-1){
  155485. int i;
  155486. /* always believe the stream markers */
  155487. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  155488. if(vf->pcm_offset<0)vf->pcm_offset=0;
  155489. for(i=0;i<vf->current_link;i++)
  155490. vf->pcm_offset+=vf->pcmlengths[i*2+1];
  155491. }
  155492. lastblock=thisblock;
  155493. }else{
  155494. if(ret<0 && ret!=OV_HOLE)break;
  155495. /* suck in a new page */
  155496. if(_get_next_page(vf,&og,-1)<0)break;
  155497. if(vf->current_serialno!=ogg_page_serialno(&og))_decode_clear(vf);
  155498. if(vf->ready_state<STREAMSET){
  155499. int link;
  155500. vf->current_serialno=ogg_page_serialno(&og);
  155501. for(link=0;link<vf->links;link++)
  155502. if(vf->serialnos[link]==vf->current_serialno)break;
  155503. if(link==vf->links)return(OV_EBADLINK);
  155504. vf->current_link=link;
  155505. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  155506. vf->ready_state=STREAMSET;
  155507. ret=_make_decode_ready(vf);
  155508. if(ret)return ret;
  155509. lastblock=0;
  155510. }
  155511. ogg_stream_pagein(&vf->os,&og);
  155512. }
  155513. }
  155514. vf->bittrack=0.f;
  155515. vf->samptrack=0.f;
  155516. /* discard samples until we reach the desired position. Crossing a
  155517. logical bitstream boundary with abandon is OK. */
  155518. while(vf->pcm_offset<pos){
  155519. ogg_int64_t target=pos-vf->pcm_offset;
  155520. long samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  155521. if(samples>target)samples=target;
  155522. vorbis_synthesis_read(&vf->vd,samples);
  155523. vf->pcm_offset+=samples;
  155524. if(samples<target)
  155525. if(_fetch_and_process_packet(vf,NULL,1,1)<=0)
  155526. vf->pcm_offset=ov_pcm_total(vf,-1); /* eof */
  155527. }
  155528. return 0;
  155529. }
  155530. /* seek to a playback time relative to the decompressed pcm stream
  155531. returns zero on success, nonzero on failure */
  155532. int ov_time_seek(OggVorbis_File *vf,double seconds){
  155533. /* translate time to PCM position and call ov_pcm_seek */
  155534. int link=-1;
  155535. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  155536. double time_total=ov_time_total(vf,-1);
  155537. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155538. if(!vf->seekable)return(OV_ENOSEEK);
  155539. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  155540. /* which bitstream section does this time offset occur in? */
  155541. for(link=vf->links-1;link>=0;link--){
  155542. pcm_total-=vf->pcmlengths[link*2+1];
  155543. time_total-=ov_time_total(vf,link);
  155544. if(seconds>=time_total)break;
  155545. }
  155546. /* enough information to convert time offset to pcm offset */
  155547. {
  155548. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  155549. return(ov_pcm_seek(vf,target));
  155550. }
  155551. }
  155552. /* page-granularity version of ov_time_seek
  155553. returns zero on success, nonzero on failure */
  155554. int ov_time_seek_page(OggVorbis_File *vf,double seconds){
  155555. /* translate time to PCM position and call ov_pcm_seek */
  155556. int link=-1;
  155557. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  155558. double time_total=ov_time_total(vf,-1);
  155559. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155560. if(!vf->seekable)return(OV_ENOSEEK);
  155561. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  155562. /* which bitstream section does this time offset occur in? */
  155563. for(link=vf->links-1;link>=0;link--){
  155564. pcm_total-=vf->pcmlengths[link*2+1];
  155565. time_total-=ov_time_total(vf,link);
  155566. if(seconds>=time_total)break;
  155567. }
  155568. /* enough information to convert time offset to pcm offset */
  155569. {
  155570. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  155571. return(ov_pcm_seek_page(vf,target));
  155572. }
  155573. }
  155574. /* tell the current stream offset cursor. Note that seek followed by
  155575. tell will likely not give the set offset due to caching */
  155576. ogg_int64_t ov_raw_tell(OggVorbis_File *vf){
  155577. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155578. return(vf->offset);
  155579. }
  155580. /* return PCM offset (sample) of next PCM sample to be read */
  155581. ogg_int64_t ov_pcm_tell(OggVorbis_File *vf){
  155582. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155583. return(vf->pcm_offset);
  155584. }
  155585. /* return time offset (seconds) of next PCM sample to be read */
  155586. double ov_time_tell(OggVorbis_File *vf){
  155587. int link=0;
  155588. ogg_int64_t pcm_total=0;
  155589. double time_total=0.f;
  155590. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155591. if(vf->seekable){
  155592. pcm_total=ov_pcm_total(vf,-1);
  155593. time_total=ov_time_total(vf,-1);
  155594. /* which bitstream section does this time offset occur in? */
  155595. for(link=vf->links-1;link>=0;link--){
  155596. pcm_total-=vf->pcmlengths[link*2+1];
  155597. time_total-=ov_time_total(vf,link);
  155598. if(vf->pcm_offset>=pcm_total)break;
  155599. }
  155600. }
  155601. return((double)time_total+(double)(vf->pcm_offset-pcm_total)/vf->vi[link].rate);
  155602. }
  155603. /* link: -1) return the vorbis_info struct for the bitstream section
  155604. currently being decoded
  155605. 0-n) to request information for a specific bitstream section
  155606. In the case of a non-seekable bitstream, any call returns the
  155607. current bitstream. NULL in the case that the machine is not
  155608. initialized */
  155609. vorbis_info *ov_info(OggVorbis_File *vf,int link){
  155610. if(vf->seekable){
  155611. if(link<0)
  155612. if(vf->ready_state>=STREAMSET)
  155613. return vf->vi+vf->current_link;
  155614. else
  155615. return vf->vi;
  155616. else
  155617. if(link>=vf->links)
  155618. return NULL;
  155619. else
  155620. return vf->vi+link;
  155621. }else{
  155622. return vf->vi;
  155623. }
  155624. }
  155625. /* grr, strong typing, grr, no templates/inheritence, grr */
  155626. vorbis_comment *ov_comment(OggVorbis_File *vf,int link){
  155627. if(vf->seekable){
  155628. if(link<0)
  155629. if(vf->ready_state>=STREAMSET)
  155630. return vf->vc+vf->current_link;
  155631. else
  155632. return vf->vc;
  155633. else
  155634. if(link>=vf->links)
  155635. return NULL;
  155636. else
  155637. return vf->vc+link;
  155638. }else{
  155639. return vf->vc;
  155640. }
  155641. }
  155642. static int host_is_big_endian() {
  155643. ogg_int32_t pattern = 0xfeedface; /* deadbeef */
  155644. unsigned char *bytewise = (unsigned char *)&pattern;
  155645. if (bytewise[0] == 0xfe) return 1;
  155646. return 0;
  155647. }
  155648. /* up to this point, everything could more or less hide the multiple
  155649. logical bitstream nature of chaining from the toplevel application
  155650. if the toplevel application didn't particularly care. However, at
  155651. the point that we actually read audio back, the multiple-section
  155652. nature must surface: Multiple bitstream sections do not necessarily
  155653. have to have the same number of channels or sampling rate.
  155654. ov_read returns the sequential logical bitstream number currently
  155655. being decoded along with the PCM data in order that the toplevel
  155656. application can take action on channel/sample rate changes. This
  155657. number will be incremented even for streamed (non-seekable) streams
  155658. (for seekable streams, it represents the actual logical bitstream
  155659. index within the physical bitstream. Note that the accessor
  155660. functions above are aware of this dichotomy).
  155661. input values: buffer) a buffer to hold packed PCM data for return
  155662. length) the byte length requested to be placed into buffer
  155663. bigendianp) should the data be packed LSB first (0) or
  155664. MSB first (1)
  155665. word) word size for output. currently 1 (byte) or
  155666. 2 (16 bit short)
  155667. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  155668. 0) EOF
  155669. n) number of bytes of PCM actually returned. The
  155670. below works on a packet-by-packet basis, so the
  155671. return length is not related to the 'length' passed
  155672. in, just guaranteed to fit.
  155673. *section) set to the logical bitstream number */
  155674. long ov_read(OggVorbis_File *vf,char *buffer,int length,
  155675. int bigendianp,int word,int sgned,int *bitstream){
  155676. int i,j;
  155677. int host_endian = host_is_big_endian();
  155678. float **pcm;
  155679. long samples;
  155680. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155681. while(1){
  155682. if(vf->ready_state==INITSET){
  155683. samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  155684. if(samples)break;
  155685. }
  155686. /* suck in another packet */
  155687. {
  155688. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  155689. if(ret==OV_EOF)
  155690. return(0);
  155691. if(ret<=0)
  155692. return(ret);
  155693. }
  155694. }
  155695. if(samples>0){
  155696. /* yay! proceed to pack data into the byte buffer */
  155697. long channels=ov_info(vf,-1)->channels;
  155698. long bytespersample=word * channels;
  155699. vorbis_fpu_control fpu;
  155700. (void) fpu; // (to avoid a warning about it being unused)
  155701. if(samples>length/bytespersample)samples=length/bytespersample;
  155702. if(samples <= 0)
  155703. return OV_EINVAL;
  155704. /* a tight loop to pack each size */
  155705. {
  155706. int val;
  155707. if(word==1){
  155708. int off=(sgned?0:128);
  155709. vorbis_fpu_setround(&fpu);
  155710. for(j=0;j<samples;j++)
  155711. for(i=0;i<channels;i++){
  155712. val=vorbis_ftoi(pcm[i][j]*128.f);
  155713. if(val>127)val=127;
  155714. else if(val<-128)val=-128;
  155715. *buffer++=val+off;
  155716. }
  155717. vorbis_fpu_restore(fpu);
  155718. }else{
  155719. int off=(sgned?0:32768);
  155720. if(host_endian==bigendianp){
  155721. if(sgned){
  155722. vorbis_fpu_setround(&fpu);
  155723. for(i=0;i<channels;i++) { /* It's faster in this order */
  155724. float *src=pcm[i];
  155725. short *dest=((short *)buffer)+i;
  155726. for(j=0;j<samples;j++) {
  155727. val=vorbis_ftoi(src[j]*32768.f);
  155728. if(val>32767)val=32767;
  155729. else if(val<-32768)val=-32768;
  155730. *dest=val;
  155731. dest+=channels;
  155732. }
  155733. }
  155734. vorbis_fpu_restore(fpu);
  155735. }else{
  155736. vorbis_fpu_setround(&fpu);
  155737. for(i=0;i<channels;i++) {
  155738. float *src=pcm[i];
  155739. short *dest=((short *)buffer)+i;
  155740. for(j=0;j<samples;j++) {
  155741. val=vorbis_ftoi(src[j]*32768.f);
  155742. if(val>32767)val=32767;
  155743. else if(val<-32768)val=-32768;
  155744. *dest=val+off;
  155745. dest+=channels;
  155746. }
  155747. }
  155748. vorbis_fpu_restore(fpu);
  155749. }
  155750. }else if(bigendianp){
  155751. vorbis_fpu_setround(&fpu);
  155752. for(j=0;j<samples;j++)
  155753. for(i=0;i<channels;i++){
  155754. val=vorbis_ftoi(pcm[i][j]*32768.f);
  155755. if(val>32767)val=32767;
  155756. else if(val<-32768)val=-32768;
  155757. val+=off;
  155758. *buffer++=(val>>8);
  155759. *buffer++=(val&0xff);
  155760. }
  155761. vorbis_fpu_restore(fpu);
  155762. }else{
  155763. int val;
  155764. vorbis_fpu_setround(&fpu);
  155765. for(j=0;j<samples;j++)
  155766. for(i=0;i<channels;i++){
  155767. val=vorbis_ftoi(pcm[i][j]*32768.f);
  155768. if(val>32767)val=32767;
  155769. else if(val<-32768)val=-32768;
  155770. val+=off;
  155771. *buffer++=(val&0xff);
  155772. *buffer++=(val>>8);
  155773. }
  155774. vorbis_fpu_restore(fpu);
  155775. }
  155776. }
  155777. }
  155778. vorbis_synthesis_read(&vf->vd,samples);
  155779. vf->pcm_offset+=samples;
  155780. if(bitstream)*bitstream=vf->current_link;
  155781. return(samples*bytespersample);
  155782. }else{
  155783. return(samples);
  155784. }
  155785. }
  155786. /* input values: pcm_channels) a float vector per channel of output
  155787. length) the sample length being read by the app
  155788. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  155789. 0) EOF
  155790. n) number of samples of PCM actually returned. The
  155791. below works on a packet-by-packet basis, so the
  155792. return length is not related to the 'length' passed
  155793. in, just guaranteed to fit.
  155794. *section) set to the logical bitstream number */
  155795. long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int length,
  155796. int *bitstream){
  155797. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155798. while(1){
  155799. if(vf->ready_state==INITSET){
  155800. float **pcm;
  155801. long samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  155802. if(samples){
  155803. if(pcm_channels)*pcm_channels=pcm;
  155804. if(samples>length)samples=length;
  155805. vorbis_synthesis_read(&vf->vd,samples);
  155806. vf->pcm_offset+=samples;
  155807. if(bitstream)*bitstream=vf->current_link;
  155808. return samples;
  155809. }
  155810. }
  155811. /* suck in another packet */
  155812. {
  155813. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  155814. if(ret==OV_EOF)return(0);
  155815. if(ret<=0)return(ret);
  155816. }
  155817. }
  155818. }
  155819. extern float *vorbis_window(vorbis_dsp_state *v,int W);
  155820. extern void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,
  155821. ogg_int64_t off);
  155822. static void _ov_splice(float **pcm,float **lappcm,
  155823. int n1, int n2,
  155824. int ch1, int ch2,
  155825. float *w1, float *w2){
  155826. int i,j;
  155827. float *w=w1;
  155828. int n=n1;
  155829. if(n1>n2){
  155830. n=n2;
  155831. w=w2;
  155832. }
  155833. /* splice */
  155834. for(j=0;j<ch1 && j<ch2;j++){
  155835. float *s=lappcm[j];
  155836. float *d=pcm[j];
  155837. for(i=0;i<n;i++){
  155838. float wd=w[i]*w[i];
  155839. float ws=1.-wd;
  155840. d[i]=d[i]*wd + s[i]*ws;
  155841. }
  155842. }
  155843. /* window from zero */
  155844. for(;j<ch2;j++){
  155845. float *d=pcm[j];
  155846. for(i=0;i<n;i++){
  155847. float wd=w[i]*w[i];
  155848. d[i]=d[i]*wd;
  155849. }
  155850. }
  155851. }
  155852. /* make sure vf is INITSET */
  155853. static int _ov_initset(OggVorbis_File *vf){
  155854. while(1){
  155855. if(vf->ready_state==INITSET)break;
  155856. /* suck in another packet */
  155857. {
  155858. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  155859. if(ret<0 && ret!=OV_HOLE)return(ret);
  155860. }
  155861. }
  155862. return 0;
  155863. }
  155864. /* make sure vf is INITSET and that we have a primed buffer; if
  155865. we're crosslapping at a stream section boundary, this also makes
  155866. sure we're sanity checking against the right stream information */
  155867. static int _ov_initprime(OggVorbis_File *vf){
  155868. vorbis_dsp_state *vd=&vf->vd;
  155869. while(1){
  155870. if(vf->ready_state==INITSET)
  155871. if(vorbis_synthesis_pcmout(vd,NULL))break;
  155872. /* suck in another packet */
  155873. {
  155874. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  155875. if(ret<0 && ret!=OV_HOLE)return(ret);
  155876. }
  155877. }
  155878. return 0;
  155879. }
  155880. /* grab enough data for lapping from vf; this may be in the form of
  155881. unreturned, already-decoded pcm, remaining PCM we will need to
  155882. decode, or synthetic postextrapolation from last packets. */
  155883. static void _ov_getlap(OggVorbis_File *vf,vorbis_info *vi,vorbis_dsp_state *vd,
  155884. float **lappcm,int lapsize){
  155885. int lapcount=0,i;
  155886. float **pcm;
  155887. /* try first to decode the lapping data */
  155888. while(lapcount<lapsize){
  155889. int samples=vorbis_synthesis_pcmout(vd,&pcm);
  155890. if(samples){
  155891. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  155892. for(i=0;i<vi->channels;i++)
  155893. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  155894. lapcount+=samples;
  155895. vorbis_synthesis_read(vd,samples);
  155896. }else{
  155897. /* suck in another packet */
  155898. int ret=_fetch_and_process_packet(vf,NULL,1,0); /* do *not* span */
  155899. if(ret==OV_EOF)break;
  155900. }
  155901. }
  155902. if(lapcount<lapsize){
  155903. /* failed to get lapping data from normal decode; pry it from the
  155904. postextrapolation buffering, or the second half of the MDCT
  155905. from the last packet */
  155906. int samples=vorbis_synthesis_lapout(&vf->vd,&pcm);
  155907. if(samples==0){
  155908. for(i=0;i<vi->channels;i++)
  155909. memset(lappcm[i]+lapcount,0,sizeof(**pcm)*lapsize-lapcount);
  155910. lapcount=lapsize;
  155911. }else{
  155912. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  155913. for(i=0;i<vi->channels;i++)
  155914. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  155915. lapcount+=samples;
  155916. }
  155917. }
  155918. }
  155919. /* this sets up crosslapping of a sample by using trailing data from
  155920. sample 1 and lapping it into the windowing buffer of sample 2 */
  155921. int ov_crosslap(OggVorbis_File *vf1, OggVorbis_File *vf2){
  155922. vorbis_info *vi1,*vi2;
  155923. float **lappcm;
  155924. float **pcm;
  155925. float *w1,*w2;
  155926. int n1,n2,i,ret,hs1,hs2;
  155927. if(vf1==vf2)return(0); /* degenerate case */
  155928. if(vf1->ready_state<OPENED)return(OV_EINVAL);
  155929. if(vf2->ready_state<OPENED)return(OV_EINVAL);
  155930. /* the relevant overlap buffers must be pre-checked and pre-primed
  155931. before looking at settings in the event that priming would cross
  155932. a bitstream boundary. So, do it now */
  155933. ret=_ov_initset(vf1);
  155934. if(ret)return(ret);
  155935. ret=_ov_initprime(vf2);
  155936. if(ret)return(ret);
  155937. vi1=ov_info(vf1,-1);
  155938. vi2=ov_info(vf2,-1);
  155939. hs1=ov_halfrate_p(vf1);
  155940. hs2=ov_halfrate_p(vf2);
  155941. lappcm=(float**) alloca(sizeof(*lappcm)*vi1->channels);
  155942. n1=vorbis_info_blocksize(vi1,0)>>(1+hs1);
  155943. n2=vorbis_info_blocksize(vi2,0)>>(1+hs2);
  155944. w1=vorbis_window(&vf1->vd,0);
  155945. w2=vorbis_window(&vf2->vd,0);
  155946. for(i=0;i<vi1->channels;i++)
  155947. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  155948. _ov_getlap(vf1,vi1,&vf1->vd,lappcm,n1);
  155949. /* have a lapping buffer from vf1; now to splice it into the lapping
  155950. buffer of vf2 */
  155951. /* consolidate and expose the buffer. */
  155952. vorbis_synthesis_lapout(&vf2->vd,&pcm);
  155953. _analysis_output_always("pcmL",0,pcm[0],n1*2,0,0,0);
  155954. _analysis_output_always("pcmR",0,pcm[1],n1*2,0,0,0);
  155955. /* splice */
  155956. _ov_splice(pcm,lappcm,n1,n2,vi1->channels,vi2->channels,w1,w2);
  155957. /* done */
  155958. return(0);
  155959. }
  155960. static int _ov_64_seek_lap(OggVorbis_File *vf,ogg_int64_t pos,
  155961. int (*localseek)(OggVorbis_File *,ogg_int64_t)){
  155962. vorbis_info *vi;
  155963. float **lappcm;
  155964. float **pcm;
  155965. float *w1,*w2;
  155966. int n1,n2,ch1,ch2,hs;
  155967. int i,ret;
  155968. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155969. ret=_ov_initset(vf);
  155970. if(ret)return(ret);
  155971. vi=ov_info(vf,-1);
  155972. hs=ov_halfrate_p(vf);
  155973. ch1=vi->channels;
  155974. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  155975. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  155976. persistent; even if the decode state
  155977. from this link gets dumped, this
  155978. window array continues to exist */
  155979. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  155980. for(i=0;i<ch1;i++)
  155981. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  155982. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  155983. /* have lapping data; seek and prime the buffer */
  155984. ret=localseek(vf,pos);
  155985. if(ret)return ret;
  155986. ret=_ov_initprime(vf);
  155987. if(ret)return(ret);
  155988. /* Guard against cross-link changes; they're perfectly legal */
  155989. vi=ov_info(vf,-1);
  155990. ch2=vi->channels;
  155991. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  155992. w2=vorbis_window(&vf->vd,0);
  155993. /* consolidate and expose the buffer. */
  155994. vorbis_synthesis_lapout(&vf->vd,&pcm);
  155995. /* splice */
  155996. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  155997. /* done */
  155998. return(0);
  155999. }
  156000. int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  156001. return _ov_64_seek_lap(vf,pos,ov_raw_seek);
  156002. }
  156003. int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  156004. return _ov_64_seek_lap(vf,pos,ov_pcm_seek);
  156005. }
  156006. int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos){
  156007. return _ov_64_seek_lap(vf,pos,ov_pcm_seek_page);
  156008. }
  156009. static int _ov_d_seek_lap(OggVorbis_File *vf,double pos,
  156010. int (*localseek)(OggVorbis_File *,double)){
  156011. vorbis_info *vi;
  156012. float **lappcm;
  156013. float **pcm;
  156014. float *w1,*w2;
  156015. int n1,n2,ch1,ch2,hs;
  156016. int i,ret;
  156017. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156018. ret=_ov_initset(vf);
  156019. if(ret)return(ret);
  156020. vi=ov_info(vf,-1);
  156021. hs=ov_halfrate_p(vf);
  156022. ch1=vi->channels;
  156023. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  156024. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  156025. persistent; even if the decode state
  156026. from this link gets dumped, this
  156027. window array continues to exist */
  156028. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  156029. for(i=0;i<ch1;i++)
  156030. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  156031. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  156032. /* have lapping data; seek and prime the buffer */
  156033. ret=localseek(vf,pos);
  156034. if(ret)return ret;
  156035. ret=_ov_initprime(vf);
  156036. if(ret)return(ret);
  156037. /* Guard against cross-link changes; they're perfectly legal */
  156038. vi=ov_info(vf,-1);
  156039. ch2=vi->channels;
  156040. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  156041. w2=vorbis_window(&vf->vd,0);
  156042. /* consolidate and expose the buffer. */
  156043. vorbis_synthesis_lapout(&vf->vd,&pcm);
  156044. /* splice */
  156045. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  156046. /* done */
  156047. return(0);
  156048. }
  156049. int ov_time_seek_lap(OggVorbis_File *vf,double pos){
  156050. return _ov_d_seek_lap(vf,pos,ov_time_seek);
  156051. }
  156052. int ov_time_seek_page_lap(OggVorbis_File *vf,double pos){
  156053. return _ov_d_seek_lap(vf,pos,ov_time_seek_page);
  156054. }
  156055. #endif
  156056. /*** End of inlined file: vorbisfile.c ***/
  156057. /*** Start of inlined file: window.c ***/
  156058. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  156059. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  156060. // tasks..
  156061. #if JUCE_MSVC
  156062. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  156063. #endif
  156064. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  156065. #if JUCE_USE_OGGVORBIS
  156066. #include <stdlib.h>
  156067. #include <math.h>
  156068. static float vwin64[32] = {
  156069. 0.0009460463F, 0.0085006468F, 0.0235352254F, 0.0458950567F,
  156070. 0.0753351908F, 0.1115073077F, 0.1539457973F, 0.2020557475F,
  156071. 0.2551056759F, 0.3122276645F, 0.3724270287F, 0.4346027792F,
  156072. 0.4975789974F, 0.5601459521F, 0.6211085051F, 0.6793382689F,
  156073. 0.7338252629F, 0.7837245849F, 0.8283939355F, 0.8674186656F,
  156074. 0.9006222429F, 0.9280614787F, 0.9500073081F, 0.9669131782F,
  156075. 0.9793740220F, 0.9880792941F, 0.9937636139F, 0.9971582668F,
  156076. 0.9989462667F, 0.9997230082F, 0.9999638688F, 0.9999995525F,
  156077. };
  156078. static float vwin128[64] = {
  156079. 0.0002365472F, 0.0021280687F, 0.0059065254F, 0.0115626550F,
  156080. 0.0190823442F, 0.0284463735F, 0.0396300935F, 0.0526030430F,
  156081. 0.0673285281F, 0.0837631763F, 0.1018564887F, 0.1215504095F,
  156082. 0.1427789367F, 0.1654677960F, 0.1895342001F, 0.2148867160F,
  156083. 0.2414252576F, 0.2690412240F, 0.2976177952F, 0.3270303960F,
  156084. 0.3571473350F, 0.3878306189F, 0.4189369387F, 0.4503188188F,
  156085. 0.4818259135F, 0.5133064334F, 0.5446086751F, 0.5755826278F,
  156086. 0.6060816248F, 0.6359640047F, 0.6650947483F, 0.6933470543F,
  156087. 0.7206038179F, 0.7467589810F, 0.7717187213F, 0.7954024542F,
  156088. 0.8177436264F, 0.8386902831F, 0.8582053981F, 0.8762669622F,
  156089. 0.8928678298F, 0.9080153310F, 0.9217306608F, 0.9340480615F,
  156090. 0.9450138200F, 0.9546851041F, 0.9631286621F, 0.9704194171F,
  156091. 0.9766389810F, 0.9818741197F, 0.9862151938F, 0.9897546035F,
  156092. 0.9925852598F, 0.9947991032F, 0.9964856900F, 0.9977308602F,
  156093. 0.9986155015F, 0.9992144193F, 0.9995953200F, 0.9998179155F,
  156094. 0.9999331503F, 0.9999825563F, 0.9999977357F, 0.9999999720F,
  156095. };
  156096. static float vwin256[128] = {
  156097. 0.0000591390F, 0.0005321979F, 0.0014780301F, 0.0028960636F,
  156098. 0.0047854363F, 0.0071449926F, 0.0099732775F, 0.0132685298F,
  156099. 0.0170286741F, 0.0212513119F, 0.0259337111F, 0.0310727950F,
  156100. 0.0366651302F, 0.0427069140F, 0.0491939614F, 0.0561216907F,
  156101. 0.0634851102F, 0.0712788035F, 0.0794969160F, 0.0881331402F,
  156102. 0.0971807028F, 0.1066323515F, 0.1164803426F, 0.1267164297F,
  156103. 0.1373318534F, 0.1483173323F, 0.1596630553F, 0.1713586755F,
  156104. 0.1833933062F, 0.1957555184F, 0.2084333404F, 0.2214142599F,
  156105. 0.2346852280F, 0.2482326664F, 0.2620424757F, 0.2761000481F,
  156106. 0.2903902813F, 0.3048975959F, 0.3196059553F, 0.3344988887F,
  156107. 0.3495595160F, 0.3647705766F, 0.3801144597F, 0.3955732382F,
  156108. 0.4111287047F, 0.4267624093F, 0.4424557009F, 0.4581897696F,
  156109. 0.4739456913F, 0.4897044744F, 0.5054471075F, 0.5211546088F,
  156110. 0.5368080763F, 0.5523887395F, 0.5678780103F, 0.5832575361F,
  156111. 0.5985092508F, 0.6136154277F, 0.6285587300F, 0.6433222619F,
  156112. 0.6578896175F, 0.6722449294F, 0.6863729144F, 0.7002589187F,
  156113. 0.7138889597F, 0.7272497662F, 0.7403288154F, 0.7531143679F,
  156114. 0.7655954985F, 0.7777621249F, 0.7896050322F, 0.8011158947F,
  156115. 0.8122872932F, 0.8231127294F, 0.8335866365F, 0.8437043850F,
  156116. 0.8534622861F, 0.8628575905F, 0.8718884835F, 0.8805540765F,
  156117. 0.8888543947F, 0.8967903616F, 0.9043637797F, 0.9115773078F,
  156118. 0.9184344360F, 0.9249394562F, 0.9310974312F, 0.9369141608F,
  156119. 0.9423961446F, 0.9475505439F, 0.9523851406F, 0.9569082947F,
  156120. 0.9611289005F, 0.9650563408F, 0.9687004405F, 0.9720714191F,
  156121. 0.9751798427F, 0.9780365753F, 0.9806527301F, 0.9830396204F,
  156122. 0.9852087111F, 0.9871715701F, 0.9889398207F, 0.9905250941F,
  156123. 0.9919389832F, 0.9931929973F, 0.9942985174F, 0.9952667537F,
  156124. 0.9961087037F, 0.9968351119F, 0.9974564312F, 0.9979827858F,
  156125. 0.9984239359F, 0.9987892441F, 0.9990876435F, 0.9993276081F,
  156126. 0.9995171241F, 0.9996636648F, 0.9997741654F, 0.9998550016F,
  156127. 0.9999119692F, 0.9999502656F, 0.9999744742F, 0.9999885497F,
  156128. 0.9999958064F, 0.9999989077F, 0.9999998584F, 0.9999999983F,
  156129. };
  156130. static float vwin512[256] = {
  156131. 0.0000147849F, 0.0001330607F, 0.0003695946F, 0.0007243509F,
  156132. 0.0011972759F, 0.0017882983F, 0.0024973285F, 0.0033242588F,
  156133. 0.0042689632F, 0.0053312973F, 0.0065110982F, 0.0078081841F,
  156134. 0.0092223540F, 0.0107533880F, 0.0124010466F, 0.0141650703F,
  156135. 0.0160451800F, 0.0180410758F, 0.0201524373F, 0.0223789233F,
  156136. 0.0247201710F, 0.0271757958F, 0.0297453914F, 0.0324285286F,
  156137. 0.0352247556F, 0.0381335972F, 0.0411545545F, 0.0442871045F,
  156138. 0.0475306997F, 0.0508847676F, 0.0543487103F, 0.0579219038F,
  156139. 0.0616036982F, 0.0653934164F, 0.0692903546F, 0.0732937809F,
  156140. 0.0774029356F, 0.0816170305F, 0.0859352485F, 0.0903567428F,
  156141. 0.0948806375F, 0.0995060259F, 0.1042319712F, 0.1090575056F,
  156142. 0.1139816300F, 0.1190033137F, 0.1241214941F, 0.1293350764F,
  156143. 0.1346429333F, 0.1400439046F, 0.1455367974F, 0.1511203852F,
  156144. 0.1567934083F, 0.1625545735F, 0.1684025537F, 0.1743359881F,
  156145. 0.1803534820F, 0.1864536069F, 0.1926349000F, 0.1988958650F,
  156146. 0.2052349715F, 0.2116506555F, 0.2181413191F, 0.2247053313F,
  156147. 0.2313410275F, 0.2380467105F, 0.2448206500F, 0.2516610835F,
  156148. 0.2585662164F, 0.2655342226F, 0.2725632448F, 0.2796513950F,
  156149. 0.2867967551F, 0.2939973773F, 0.3012512852F, 0.3085564739F,
  156150. 0.3159109111F, 0.3233125375F, 0.3307592680F, 0.3382489922F,
  156151. 0.3457795756F, 0.3533488602F, 0.3609546657F, 0.3685947904F,
  156152. 0.3762670121F, 0.3839690896F, 0.3916987634F, 0.3994537572F,
  156153. 0.4072317788F, 0.4150305215F, 0.4228476653F, 0.4306808783F,
  156154. 0.4385278181F, 0.4463861329F, 0.4542534630F, 0.4621274424F,
  156155. 0.4700057001F, 0.4778858615F, 0.4857655502F, 0.4936423891F,
  156156. 0.5015140023F, 0.5093780165F, 0.5172320626F, 0.5250737772F,
  156157. 0.5329008043F, 0.5407107971F, 0.5485014192F, 0.5562703465F,
  156158. 0.5640152688F, 0.5717338914F, 0.5794239366F, 0.5870831457F,
  156159. 0.5947092801F, 0.6023001235F, 0.6098534829F, 0.6173671907F,
  156160. 0.6248391059F, 0.6322671161F, 0.6396491384F, 0.6469831217F,
  156161. 0.6542670475F, 0.6614989319F, 0.6686768267F, 0.6757988210F,
  156162. 0.6828630426F, 0.6898676592F, 0.6968108799F, 0.7036909564F,
  156163. 0.7105061843F, 0.7172549043F, 0.7239355032F, 0.7305464154F,
  156164. 0.7370861235F, 0.7435531598F, 0.7499461068F, 0.7562635986F,
  156165. 0.7625043214F, 0.7686670148F, 0.7747504721F, 0.7807535410F,
  156166. 0.7866751247F, 0.7925141825F, 0.7982697296F, 0.8039408387F,
  156167. 0.8095266395F, 0.8150263196F, 0.8204391248F, 0.8257643590F,
  156168. 0.8310013848F, 0.8361496236F, 0.8412085555F, 0.8461777194F,
  156169. 0.8510567129F, 0.8558451924F, 0.8605428730F, 0.8651495278F,
  156170. 0.8696649882F, 0.8740891432F, 0.8784219392F, 0.8826633797F,
  156171. 0.8868135244F, 0.8908724888F, 0.8948404441F, 0.8987176157F,
  156172. 0.9025042831F, 0.9062007791F, 0.9098074886F, 0.9133248482F,
  156173. 0.9167533451F, 0.9200935163F, 0.9233459472F, 0.9265112712F,
  156174. 0.9295901680F, 0.9325833632F, 0.9354916263F, 0.9383157705F,
  156175. 0.9410566504F, 0.9437151618F, 0.9462922398F, 0.9487888576F,
  156176. 0.9512060252F, 0.9535447882F, 0.9558062262F, 0.9579914516F,
  156177. 0.9601016078F, 0.9621378683F, 0.9641014348F, 0.9659935361F,
  156178. 0.9678154261F, 0.9695683830F, 0.9712537071F, 0.9728727198F,
  156179. 0.9744267618F, 0.9759171916F, 0.9773453842F, 0.9787127293F,
  156180. 0.9800206298F, 0.9812705006F, 0.9824637665F, 0.9836018613F,
  156181. 0.9846862258F, 0.9857183066F, 0.9866995544F, 0.9876314227F,
  156182. 0.9885153662F, 0.9893528393F, 0.9901452948F, 0.9908941823F,
  156183. 0.9916009470F, 0.9922670279F, 0.9928938570F, 0.9934828574F,
  156184. 0.9940354423F, 0.9945530133F, 0.9950369595F, 0.9954886562F,
  156185. 0.9959094633F, 0.9963007242F, 0.9966637649F, 0.9969998925F,
  156186. 0.9973103939F, 0.9975965351F, 0.9978595598F, 0.9981006885F,
  156187. 0.9983211172F, 0.9985220166F, 0.9987045311F, 0.9988697776F,
  156188. 0.9990188449F, 0.9991527924F, 0.9992726499F, 0.9993794157F,
  156189. 0.9994740570F, 0.9995575079F, 0.9996306699F, 0.9996944099F,
  156190. 0.9997495605F, 0.9997969190F, 0.9998372465F, 0.9998712678F,
  156191. 0.9998996704F, 0.9999231041F, 0.9999421807F, 0.9999574732F,
  156192. 0.9999695157F, 0.9999788026F, 0.9999857885F, 0.9999908879F,
  156193. 0.9999944746F, 0.9999968817F, 0.9999984010F, 0.9999992833F,
  156194. 0.9999997377F, 0.9999999317F, 0.9999999911F, 0.9999999999F,
  156195. };
  156196. static float vwin1024[512] = {
  156197. 0.0000036962F, 0.0000332659F, 0.0000924041F, 0.0001811086F,
  156198. 0.0002993761F, 0.0004472021F, 0.0006245811F, 0.0008315063F,
  156199. 0.0010679699F, 0.0013339631F, 0.0016294757F, 0.0019544965F,
  156200. 0.0023090133F, 0.0026930125F, 0.0031064797F, 0.0035493989F,
  156201. 0.0040217533F, 0.0045235250F, 0.0050546946F, 0.0056152418F,
  156202. 0.0062051451F, 0.0068243817F, 0.0074729278F, 0.0081507582F,
  156203. 0.0088578466F, 0.0095941655F, 0.0103596863F, 0.0111543789F,
  156204. 0.0119782122F, 0.0128311538F, 0.0137131701F, 0.0146242260F,
  156205. 0.0155642855F, 0.0165333111F, 0.0175312640F, 0.0185581042F,
  156206. 0.0196137903F, 0.0206982797F, 0.0218115284F, 0.0229534910F,
  156207. 0.0241241208F, 0.0253233698F, 0.0265511886F, 0.0278075263F,
  156208. 0.0290923308F, 0.0304055484F, 0.0317471241F, 0.0331170013F,
  156209. 0.0345151222F, 0.0359414274F, 0.0373958560F, 0.0388783456F,
  156210. 0.0403888325F, 0.0419272511F, 0.0434935347F, 0.0450876148F,
  156211. 0.0467094213F, 0.0483588828F, 0.0500359261F, 0.0517404765F,
  156212. 0.0534724575F, 0.0552317913F, 0.0570183983F, 0.0588321971F,
  156213. 0.0606731048F, 0.0625410369F, 0.0644359070F, 0.0663576272F,
  156214. 0.0683061077F, 0.0702812571F, 0.0722829821F, 0.0743111878F,
  156215. 0.0763657775F, 0.0784466526F, 0.0805537129F, 0.0826868561F,
  156216. 0.0848459782F, 0.0870309736F, 0.0892417345F, 0.0914781514F,
  156217. 0.0937401128F, 0.0960275056F, 0.0983402145F, 0.1006781223F,
  156218. 0.1030411101F, 0.1054290568F, 0.1078418397F, 0.1102793336F,
  156219. 0.1127414119F, 0.1152279457F, 0.1177388042F, 0.1202738544F,
  156220. 0.1228329618F, 0.1254159892F, 0.1280227980F, 0.1306532471F,
  156221. 0.1333071937F, 0.1359844927F, 0.1386849970F, 0.1414085575F,
  156222. 0.1441550230F, 0.1469242403F, 0.1497160539F, 0.1525303063F,
  156223. 0.1553668381F, 0.1582254875F, 0.1611060909F, 0.1640084822F,
  156224. 0.1669324936F, 0.1698779549F, 0.1728446939F, 0.1758325362F,
  156225. 0.1788413055F, 0.1818708232F, 0.1849209084F, 0.1879913785F,
  156226. 0.1910820485F, 0.1941927312F, 0.1973232376F, 0.2004733764F,
  156227. 0.2036429541F, 0.2068317752F, 0.2100396421F, 0.2132663552F,
  156228. 0.2165117125F, 0.2197755102F, 0.2230575422F, 0.2263576007F,
  156229. 0.2296754753F, 0.2330109540F, 0.2363638225F, 0.2397338646F,
  156230. 0.2431208619F, 0.2465245941F, 0.2499448389F, 0.2533813719F,
  156231. 0.2568339669F, 0.2603023956F, 0.2637864277F, 0.2672858312F,
  156232. 0.2708003718F, 0.2743298135F, 0.2778739186F, 0.2814324472F,
  156233. 0.2850051576F, 0.2885918065F, 0.2921921485F, 0.2958059366F,
  156234. 0.2994329219F, 0.3030728538F, 0.3067254799F, 0.3103905462F,
  156235. 0.3140677969F, 0.3177569747F, 0.3214578205F, 0.3251700736F,
  156236. 0.3288934718F, 0.3326277513F, 0.3363726468F, 0.3401278914F,
  156237. 0.3438932168F, 0.3476683533F, 0.3514530297F, 0.3552469734F,
  156238. 0.3590499106F, 0.3628615659F, 0.3666816630F, 0.3705099239F,
  156239. 0.3743460698F, 0.3781898204F, 0.3820408945F, 0.3858990095F,
  156240. 0.3897638820F, 0.3936352274F, 0.3975127601F, 0.4013961936F,
  156241. 0.4052852405F, 0.4091796123F, 0.4130790198F, 0.4169831732F,
  156242. 0.4208917815F, 0.4248045534F, 0.4287211965F, 0.4326414181F,
  156243. 0.4365649248F, 0.4404914225F, 0.4444206167F, 0.4483522125F,
  156244. 0.4522859146F, 0.4562214270F, 0.4601584538F, 0.4640966984F,
  156245. 0.4680358644F, 0.4719756548F, 0.4759157726F, 0.4798559209F,
  156246. 0.4837958024F, 0.4877351199F, 0.4916735765F, 0.4956108751F,
  156247. 0.4995467188F, 0.5034808109F, 0.5074128550F, 0.5113425550F,
  156248. 0.5152696149F, 0.5191937395F, 0.5231146336F, 0.5270320028F,
  156249. 0.5309455530F, 0.5348549910F, 0.5387600239F, 0.5426603597F,
  156250. 0.5465557070F, 0.5504457754F, 0.5543302752F, 0.5582089175F,
  156251. 0.5620814145F, 0.5659474793F, 0.5698068262F, 0.5736591704F,
  156252. 0.5775042283F, 0.5813417176F, 0.5851713571F, 0.5889928670F,
  156253. 0.5928059689F, 0.5966103856F, 0.6004058415F, 0.6041920626F,
  156254. 0.6079687761F, 0.6117357113F, 0.6154925986F, 0.6192391705F,
  156255. 0.6229751612F, 0.6267003064F, 0.6304143441F, 0.6341170137F,
  156256. 0.6378080569F, 0.6414872173F, 0.6451542405F, 0.6488088741F,
  156257. 0.6524508681F, 0.6560799742F, 0.6596959469F, 0.6632985424F,
  156258. 0.6668875197F, 0.6704626398F, 0.6740236662F, 0.6775703649F,
  156259. 0.6811025043F, 0.6846198554F, 0.6881221916F, 0.6916092892F,
  156260. 0.6950809269F, 0.6985368861F, 0.7019769510F, 0.7054009085F,
  156261. 0.7088085484F, 0.7121996632F, 0.7155740484F, 0.7189315023F,
  156262. 0.7222718263F, 0.7255948245F, 0.7289003043F, 0.7321880760F,
  156263. 0.7354579530F, 0.7387097518F, 0.7419432921F, 0.7451583966F,
  156264. 0.7483548915F, 0.7515326059F, 0.7546913723F, 0.7578310265F,
  156265. 0.7609514077F, 0.7640523581F, 0.7671337237F, 0.7701953535F,
  156266. 0.7732371001F, 0.7762588195F, 0.7792603711F, 0.7822416178F,
  156267. 0.7852024259F, 0.7881426654F, 0.7910622097F, 0.7939609356F,
  156268. 0.7968387237F, 0.7996954579F, 0.8025310261F, 0.8053453193F,
  156269. 0.8081382324F, 0.8109096638F, 0.8136595156F, 0.8163876936F,
  156270. 0.8190941071F, 0.8217786690F, 0.8244412960F, 0.8270819086F,
  156271. 0.8297004305F, 0.8322967896F, 0.8348709171F, 0.8374227481F,
  156272. 0.8399522213F, 0.8424592789F, 0.8449438672F, 0.8474059356F,
  156273. 0.8498454378F, 0.8522623306F, 0.8546565748F, 0.8570281348F,
  156274. 0.8593769787F, 0.8617030779F, 0.8640064080F, 0.8662869477F,
  156275. 0.8685446796F, 0.8707795899F, 0.8729916682F, 0.8751809079F,
  156276. 0.8773473059F, 0.8794908626F, 0.8816115819F, 0.8837094713F,
  156277. 0.8857845418F, 0.8878368079F, 0.8898662874F, 0.8918730019F,
  156278. 0.8938569760F, 0.8958182380F, 0.8977568194F, 0.8996727552F,
  156279. 0.9015660837F, 0.9034368465F, 0.9052850885F, 0.9071108577F,
  156280. 0.9089142057F, 0.9106951869F, 0.9124538591F, 0.9141902832F,
  156281. 0.9159045233F, 0.9175966464F, 0.9192667228F, 0.9209148257F,
  156282. 0.9225410313F, 0.9241454187F, 0.9257280701F, 0.9272890704F,
  156283. 0.9288285075F, 0.9303464720F, 0.9318430576F, 0.9333183603F,
  156284. 0.9347724792F, 0.9362055158F, 0.9376175745F, 0.9390087622F,
  156285. 0.9403791881F, 0.9417289644F, 0.9430582055F, 0.9443670283F,
  156286. 0.9456555521F, 0.9469238986F, 0.9481721917F, 0.9494005577F,
  156287. 0.9506091252F, 0.9517980248F, 0.9529673894F, 0.9541173540F,
  156288. 0.9552480557F, 0.9563596334F, 0.9574522282F, 0.9585259830F,
  156289. 0.9595810428F, 0.9606175542F, 0.9616356656F, 0.9626355274F,
  156290. 0.9636172915F, 0.9645811114F, 0.9655271425F, 0.9664555414F,
  156291. 0.9673664664F, 0.9682600774F, 0.9691365355F, 0.9699960034F,
  156292. 0.9708386448F, 0.9716646250F, 0.9724741103F, 0.9732672685F,
  156293. 0.9740442683F, 0.9748052795F, 0.9755504729F, 0.9762800205F,
  156294. 0.9769940950F, 0.9776928703F, 0.9783765210F, 0.9790452223F,
  156295. 0.9796991504F, 0.9803384823F, 0.9809633954F, 0.9815740679F,
  156296. 0.9821706784F, 0.9827534063F, 0.9833224312F, 0.9838779332F,
  156297. 0.9844200928F, 0.9849490910F, 0.9854651087F, 0.9859683274F,
  156298. 0.9864589286F, 0.9869370940F, 0.9874030054F, 0.9878568447F,
  156299. 0.9882987937F, 0.9887290343F, 0.9891477481F, 0.9895551169F,
  156300. 0.9899513220F, 0.9903365446F, 0.9907109658F, 0.9910747662F,
  156301. 0.9914281260F, 0.9917712252F, 0.9921042433F, 0.9924273593F,
  156302. 0.9927407516F, 0.9930445982F, 0.9933390763F, 0.9936243626F,
  156303. 0.9939006331F, 0.9941680631F, 0.9944268269F, 0.9946770982F,
  156304. 0.9949190498F, 0.9951528537F, 0.9953786808F, 0.9955967011F,
  156305. 0.9958070836F, 0.9960099963F, 0.9962056061F, 0.9963940787F,
  156306. 0.9965755786F, 0.9967502693F, 0.9969183129F, 0.9970798704F,
  156307. 0.9972351013F, 0.9973841640F, 0.9975272151F, 0.9976644103F,
  156308. 0.9977959036F, 0.9979218476F, 0.9980423932F, 0.9981576901F,
  156309. 0.9982678862F, 0.9983731278F, 0.9984735596F, 0.9985693247F,
  156310. 0.9986605645F, 0.9987474186F, 0.9988300248F, 0.9989085193F,
  156311. 0.9989830364F, 0.9990537085F, 0.9991206662F, 0.9991840382F,
  156312. 0.9992439513F, 0.9993005303F, 0.9993538982F, 0.9994041757F,
  156313. 0.9994514817F, 0.9994959330F, 0.9995376444F, 0.9995767286F,
  156314. 0.9996132960F, 0.9996474550F, 0.9996793121F, 0.9997089710F,
  156315. 0.9997365339F, 0.9997621003F, 0.9997857677F, 0.9998076311F,
  156316. 0.9998277836F, 0.9998463156F, 0.9998633155F, 0.9998788692F,
  156317. 0.9998930603F, 0.9999059701F, 0.9999176774F, 0.9999282586F,
  156318. 0.9999377880F, 0.9999463370F, 0.9999539749F, 0.9999607685F,
  156319. 0.9999667820F, 0.9999720773F, 0.9999767136F, 0.9999807479F,
  156320. 0.9999842344F, 0.9999872249F, 0.9999897688F, 0.9999919127F,
  156321. 0.9999937009F, 0.9999951749F, 0.9999963738F, 0.9999973342F,
  156322. 0.9999980900F, 0.9999986724F, 0.9999991103F, 0.9999994297F,
  156323. 0.9999996543F, 0.9999998049F, 0.9999999000F, 0.9999999552F,
  156324. 0.9999999836F, 0.9999999957F, 0.9999999994F, 1.0000000000F,
  156325. };
  156326. static float vwin2048[1024] = {
  156327. 0.0000009241F, 0.0000083165F, 0.0000231014F, 0.0000452785F,
  156328. 0.0000748476F, 0.0001118085F, 0.0001561608F, 0.0002079041F,
  156329. 0.0002670379F, 0.0003335617F, 0.0004074748F, 0.0004887765F,
  156330. 0.0005774661F, 0.0006735427F, 0.0007770054F, 0.0008878533F,
  156331. 0.0010060853F, 0.0011317002F, 0.0012646969F, 0.0014050742F,
  156332. 0.0015528307F, 0.0017079650F, 0.0018704756F, 0.0020403610F,
  156333. 0.0022176196F, 0.0024022497F, 0.0025942495F, 0.0027936173F,
  156334. 0.0030003511F, 0.0032144490F, 0.0034359088F, 0.0036647286F,
  156335. 0.0039009061F, 0.0041444391F, 0.0043953253F, 0.0046535621F,
  156336. 0.0049191472F, 0.0051920781F, 0.0054723520F, 0.0057599664F,
  156337. 0.0060549184F, 0.0063572052F, 0.0066668239F, 0.0069837715F,
  156338. 0.0073080449F, 0.0076396410F, 0.0079785566F, 0.0083247884F,
  156339. 0.0086783330F, 0.0090391871F, 0.0094073470F, 0.0097828092F,
  156340. 0.0101655700F, 0.0105556258F, 0.0109529726F, 0.0113576065F,
  156341. 0.0117695237F, 0.0121887200F, 0.0126151913F, 0.0130489335F,
  156342. 0.0134899422F, 0.0139382130F, 0.0143937415F, 0.0148565233F,
  156343. 0.0153265536F, 0.0158038279F, 0.0162883413F, 0.0167800889F,
  156344. 0.0172790660F, 0.0177852675F, 0.0182986882F, 0.0188193231F,
  156345. 0.0193471668F, 0.0198822141F, 0.0204244594F, 0.0209738974F,
  156346. 0.0215305225F, 0.0220943289F, 0.0226653109F, 0.0232434627F,
  156347. 0.0238287784F, 0.0244212519F, 0.0250208772F, 0.0256276481F,
  156348. 0.0262415582F, 0.0268626014F, 0.0274907711F, 0.0281260608F,
  156349. 0.0287684638F, 0.0294179736F, 0.0300745833F, 0.0307382859F,
  156350. 0.0314090747F, 0.0320869424F, 0.0327718819F, 0.0334638860F,
  156351. 0.0341629474F, 0.0348690586F, 0.0355822122F, 0.0363024004F,
  156352. 0.0370296157F, 0.0377638502F, 0.0385050960F, 0.0392533451F,
  156353. 0.0400085896F, 0.0407708211F, 0.0415400315F, 0.0423162123F,
  156354. 0.0430993552F, 0.0438894515F, 0.0446864926F, 0.0454904698F,
  156355. 0.0463013742F, 0.0471191969F, 0.0479439288F, 0.0487755607F,
  156356. 0.0496140836F, 0.0504594879F, 0.0513117642F, 0.0521709031F,
  156357. 0.0530368949F, 0.0539097297F, 0.0547893979F, 0.0556758894F,
  156358. 0.0565691941F, 0.0574693019F, 0.0583762026F, 0.0592898858F,
  156359. 0.0602103410F, 0.0611375576F, 0.0620715250F, 0.0630122324F,
  156360. 0.0639596688F, 0.0649138234F, 0.0658746848F, 0.0668422421F,
  156361. 0.0678164838F, 0.0687973985F, 0.0697849746F, 0.0707792005F,
  156362. 0.0717800645F, 0.0727875547F, 0.0738016591F, 0.0748223656F,
  156363. 0.0758496620F, 0.0768835359F, 0.0779239751F, 0.0789709668F,
  156364. 0.0800244985F, 0.0810845574F, 0.0821511306F, 0.0832242052F,
  156365. 0.0843037679F, 0.0853898056F, 0.0864823050F, 0.0875812525F,
  156366. 0.0886866347F, 0.0897984378F, 0.0909166480F, 0.0920412513F,
  156367. 0.0931722338F, 0.0943095813F, 0.0954532795F, 0.0966033140F,
  156368. 0.0977596702F, 0.0989223336F, 0.1000912894F, 0.1012665227F,
  156369. 0.1024480185F, 0.1036357616F, 0.1048297369F, 0.1060299290F,
  156370. 0.1072363224F, 0.1084489014F, 0.1096676504F, 0.1108925534F,
  156371. 0.1121235946F, 0.1133607577F, 0.1146040267F, 0.1158533850F,
  156372. 0.1171088163F, 0.1183703040F, 0.1196378312F, 0.1209113812F,
  156373. 0.1221909370F, 0.1234764815F, 0.1247679974F, 0.1260654674F,
  156374. 0.1273688740F, 0.1286781995F, 0.1299934263F, 0.1313145365F,
  156375. 0.1326415121F, 0.1339743349F, 0.1353129866F, 0.1366574490F,
  156376. 0.1380077035F, 0.1393637315F, 0.1407255141F, 0.1420930325F,
  156377. 0.1434662677F, 0.1448452004F, 0.1462298115F, 0.1476200814F,
  156378. 0.1490159906F, 0.1504175195F, 0.1518246482F, 0.1532373569F,
  156379. 0.1546556253F, 0.1560794333F, 0.1575087606F, 0.1589435866F,
  156380. 0.1603838909F, 0.1618296526F, 0.1632808509F, 0.1647374648F,
  156381. 0.1661994731F, 0.1676668546F, 0.1691395880F, 0.1706176516F,
  156382. 0.1721010238F, 0.1735896829F, 0.1750836068F, 0.1765827736F,
  156383. 0.1780871610F, 0.1795967468F, 0.1811115084F, 0.1826314234F,
  156384. 0.1841564689F, 0.1856866221F, 0.1872218600F, 0.1887621595F,
  156385. 0.1903074974F, 0.1918578503F, 0.1934131947F, 0.1949735068F,
  156386. 0.1965387630F, 0.1981089393F, 0.1996840117F, 0.2012639560F,
  156387. 0.2028487479F, 0.2044383630F, 0.2060327766F, 0.2076319642F,
  156388. 0.2092359007F, 0.2108445614F, 0.2124579211F, 0.2140759545F,
  156389. 0.2156986364F, 0.2173259411F, 0.2189578432F, 0.2205943168F,
  156390. 0.2222353361F, 0.2238808751F, 0.2255309076F, 0.2271854073F,
  156391. 0.2288443480F, 0.2305077030F, 0.2321754457F, 0.2338475493F,
  156392. 0.2355239869F, 0.2372047315F, 0.2388897560F, 0.2405790329F,
  156393. 0.2422725350F, 0.2439702347F, 0.2456721043F, 0.2473781159F,
  156394. 0.2490882418F, 0.2508024539F, 0.2525207240F, 0.2542430237F,
  156395. 0.2559693248F, 0.2576995986F, 0.2594338166F, 0.2611719498F,
  156396. 0.2629139695F, 0.2646598466F, 0.2664095520F, 0.2681630564F,
  156397. 0.2699203304F, 0.2716813445F, 0.2734460691F, 0.2752144744F,
  156398. 0.2769865307F, 0.2787622079F, 0.2805414760F, 0.2823243047F,
  156399. 0.2841106637F, 0.2859005227F, 0.2876938509F, 0.2894906179F,
  156400. 0.2912907928F, 0.2930943447F, 0.2949012426F, 0.2967114554F,
  156401. 0.2985249520F, 0.3003417009F, 0.3021616708F, 0.3039848301F,
  156402. 0.3058111471F, 0.3076405901F, 0.3094731273F, 0.3113087266F,
  156403. 0.3131473560F, 0.3149889833F, 0.3168335762F, 0.3186811024F,
  156404. 0.3205315294F, 0.3223848245F, 0.3242409552F, 0.3260998886F,
  156405. 0.3279615918F, 0.3298260319F, 0.3316931758F, 0.3335629903F,
  156406. 0.3354354423F, 0.3373104982F, 0.3391881247F, 0.3410682882F,
  156407. 0.3429509551F, 0.3448360917F, 0.3467236642F, 0.3486136387F,
  156408. 0.3505059811F, 0.3524006575F, 0.3542976336F, 0.3561968753F,
  156409. 0.3580983482F, 0.3600020179F, 0.3619078499F, 0.3638158096F,
  156410. 0.3657258625F, 0.3676379737F, 0.3695521086F, 0.3714682321F,
  156411. 0.3733863094F, 0.3753063055F, 0.3772281852F, 0.3791519134F,
  156412. 0.3810774548F, 0.3830047742F, 0.3849338362F, 0.3868646053F,
  156413. 0.3887970459F, 0.3907311227F, 0.3926667998F, 0.3946040417F,
  156414. 0.3965428125F, 0.3984830765F, 0.4004247978F, 0.4023679403F,
  156415. 0.4043124683F, 0.4062583455F, 0.4082055359F, 0.4101540034F,
  156416. 0.4121037117F, 0.4140546246F, 0.4160067058F, 0.4179599190F,
  156417. 0.4199142277F, 0.4218695956F, 0.4238259861F, 0.4257833627F,
  156418. 0.4277416888F, 0.4297009279F, 0.4316610433F, 0.4336219983F,
  156419. 0.4355837562F, 0.4375462803F, 0.4395095337F, 0.4414734797F,
  156420. 0.4434380815F, 0.4454033021F, 0.4473691046F, 0.4493354521F,
  156421. 0.4513023078F, 0.4532696345F, 0.4552373954F, 0.4572055533F,
  156422. 0.4591740713F, 0.4611429123F, 0.4631120393F, 0.4650814151F,
  156423. 0.4670510028F, 0.4690207650F, 0.4709906649F, 0.4729606651F,
  156424. 0.4749307287F, 0.4769008185F, 0.4788708972F, 0.4808409279F,
  156425. 0.4828108732F, 0.4847806962F, 0.4867503597F, 0.4887198264F,
  156426. 0.4906890593F, 0.4926580213F, 0.4946266753F, 0.4965949840F,
  156427. 0.4985629105F, 0.5005304176F, 0.5024974683F, 0.5044640255F,
  156428. 0.5064300522F, 0.5083955114F, 0.5103603659F, 0.5123245790F,
  156429. 0.5142881136F, 0.5162509328F, 0.5182129997F, 0.5201742774F,
  156430. 0.5221347290F, 0.5240943178F, 0.5260530070F, 0.5280107598F,
  156431. 0.5299675395F, 0.5319233095F, 0.5338780330F, 0.5358316736F,
  156432. 0.5377841946F, 0.5397355596F, 0.5416857320F, 0.5436346755F,
  156433. 0.5455823538F, 0.5475287304F, 0.5494737691F, 0.5514174337F,
  156434. 0.5533596881F, 0.5553004962F, 0.5572398218F, 0.5591776291F,
  156435. 0.5611138821F, 0.5630485449F, 0.5649815818F, 0.5669129570F,
  156436. 0.5688426349F, 0.5707705799F, 0.5726967564F, 0.5746211290F,
  156437. 0.5765436624F, 0.5784643212F, 0.5803830702F, 0.5822998743F,
  156438. 0.5842146984F, 0.5861275076F, 0.5880382669F, 0.5899469416F,
  156439. 0.5918534968F, 0.5937578981F, 0.5956601107F, 0.5975601004F,
  156440. 0.5994578326F, 0.6013532732F, 0.6032463880F, 0.6051371429F,
  156441. 0.6070255039F, 0.6089114372F, 0.6107949090F, 0.6126758856F,
  156442. 0.6145543334F, 0.6164302191F, 0.6183035092F, 0.6201741706F,
  156443. 0.6220421700F, 0.6239074745F, 0.6257700513F, 0.6276298674F,
  156444. 0.6294868903F, 0.6313410873F, 0.6331924262F, 0.6350408745F,
  156445. 0.6368864001F, 0.6387289710F, 0.6405685552F, 0.6424051209F,
  156446. 0.6442386364F, 0.6460690702F, 0.6478963910F, 0.6497205673F,
  156447. 0.6515415682F, 0.6533593625F, 0.6551739194F, 0.6569852082F,
  156448. 0.6587931984F, 0.6605978593F, 0.6623991609F, 0.6641970728F,
  156449. 0.6659915652F, 0.6677826081F, 0.6695701718F, 0.6713542268F,
  156450. 0.6731347437F, 0.6749116932F, 0.6766850461F, 0.6784547736F,
  156451. 0.6802208469F, 0.6819832374F, 0.6837419164F, 0.6854968559F,
  156452. 0.6872480275F, 0.6889954034F, 0.6907389556F, 0.6924786566F,
  156453. 0.6942144788F, 0.6959463950F, 0.6976743780F, 0.6993984008F,
  156454. 0.7011184365F, 0.7028344587F, 0.7045464407F, 0.7062543564F,
  156455. 0.7079581796F, 0.7096578844F, 0.7113534450F, 0.7130448359F,
  156456. 0.7147320316F, 0.7164150070F, 0.7180937371F, 0.7197681970F,
  156457. 0.7214383620F, 0.7231042077F, 0.7247657098F, 0.7264228443F,
  156458. 0.7280755871F, 0.7297239147F, 0.7313678035F, 0.7330072301F,
  156459. 0.7346421715F, 0.7362726046F, 0.7378985069F, 0.7395198556F,
  156460. 0.7411366285F, 0.7427488034F, 0.7443563584F, 0.7459592717F,
  156461. 0.7475575218F, 0.7491510873F, 0.7507399471F, 0.7523240803F,
  156462. 0.7539034661F, 0.7554780839F, 0.7570479136F, 0.7586129349F,
  156463. 0.7601731279F, 0.7617284730F, 0.7632789506F, 0.7648245416F,
  156464. 0.7663652267F, 0.7679009872F, 0.7694318044F, 0.7709576599F,
  156465. 0.7724785354F, 0.7739944130F, 0.7755052749F, 0.7770111035F,
  156466. 0.7785118815F, 0.7800075916F, 0.7814982170F, 0.7829837410F,
  156467. 0.7844641472F, 0.7859394191F, 0.7874095408F, 0.7888744965F,
  156468. 0.7903342706F, 0.7917888476F, 0.7932382124F, 0.7946823501F,
  156469. 0.7961212460F, 0.7975548855F, 0.7989832544F, 0.8004063386F,
  156470. 0.8018241244F, 0.8032365981F, 0.8046437463F, 0.8060455560F,
  156471. 0.8074420141F, 0.8088331080F, 0.8102188253F, 0.8115991536F,
  156472. 0.8129740810F, 0.8143435957F, 0.8157076861F, 0.8170663409F,
  156473. 0.8184195489F, 0.8197672994F, 0.8211095817F, 0.8224463853F,
  156474. 0.8237777001F, 0.8251035161F, 0.8264238235F, 0.8277386129F,
  156475. 0.8290478750F, 0.8303516008F, 0.8316497814F, 0.8329424083F,
  156476. 0.8342294731F, 0.8355109677F, 0.8367868841F, 0.8380572148F,
  156477. 0.8393219523F, 0.8405810893F, 0.8418346190F, 0.8430825345F,
  156478. 0.8443248294F, 0.8455614974F, 0.8467925323F, 0.8480179285F,
  156479. 0.8492376802F, 0.8504517822F, 0.8516602292F, 0.8528630164F,
  156480. 0.8540601391F, 0.8552515928F, 0.8564373733F, 0.8576174766F,
  156481. 0.8587918990F, 0.8599606368F, 0.8611236868F, 0.8622810460F,
  156482. 0.8634327113F, 0.8645786802F, 0.8657189504F, 0.8668535195F,
  156483. 0.8679823857F, 0.8691055472F, 0.8702230025F, 0.8713347503F,
  156484. 0.8724407896F, 0.8735411194F, 0.8746357394F, 0.8757246489F,
  156485. 0.8768078479F, 0.8778853364F, 0.8789571146F, 0.8800231832F,
  156486. 0.8810835427F, 0.8821381942F, 0.8831871387F, 0.8842303777F,
  156487. 0.8852679127F, 0.8862997456F, 0.8873258784F, 0.8883463132F,
  156488. 0.8893610527F, 0.8903700994F, 0.8913734562F, 0.8923711263F,
  156489. 0.8933631129F, 0.8943494196F, 0.8953300500F, 0.8963050083F,
  156490. 0.8972742985F, 0.8982379249F, 0.8991958922F, 0.9001482052F,
  156491. 0.9010948688F, 0.9020358883F, 0.9029712690F, 0.9039010165F,
  156492. 0.9048251367F, 0.9057436357F, 0.9066565195F, 0.9075637946F,
  156493. 0.9084654678F, 0.9093615456F, 0.9102520353F, 0.9111369440F,
  156494. 0.9120162792F, 0.9128900484F, 0.9137582595F, 0.9146209204F,
  156495. 0.9154780394F, 0.9163296248F, 0.9171756853F, 0.9180162296F,
  156496. 0.9188512667F, 0.9196808057F, 0.9205048559F, 0.9213234270F,
  156497. 0.9221365285F, 0.9229441704F, 0.9237463629F, 0.9245431160F,
  156498. 0.9253344404F, 0.9261203465F, 0.9269008453F, 0.9276759477F,
  156499. 0.9284456648F, 0.9292100080F, 0.9299689889F, 0.9307226190F,
  156500. 0.9314709103F, 0.9322138747F, 0.9329515245F, 0.9336838721F,
  156501. 0.9344109300F, 0.9351327108F, 0.9358492275F, 0.9365604931F,
  156502. 0.9372665208F, 0.9379673239F, 0.9386629160F, 0.9393533107F,
  156503. 0.9400385220F, 0.9407185637F, 0.9413934501F, 0.9420631954F,
  156504. 0.9427278141F, 0.9433873208F, 0.9440417304F, 0.9446910576F,
  156505. 0.9453353176F, 0.9459745255F, 0.9466086968F, 0.9472378469F,
  156506. 0.9478619915F, 0.9484811463F, 0.9490953274F, 0.9497045506F,
  156507. 0.9503088323F, 0.9509081888F, 0.9515026365F, 0.9520921921F,
  156508. 0.9526768723F, 0.9532566940F, 0.9538316742F, 0.9544018300F,
  156509. 0.9549671786F, 0.9555277375F, 0.9560835241F, 0.9566345562F,
  156510. 0.9571808513F, 0.9577224275F, 0.9582593027F, 0.9587914949F,
  156511. 0.9593190225F, 0.9598419038F, 0.9603601571F, 0.9608738012F,
  156512. 0.9613828546F, 0.9618873361F, 0.9623872646F, 0.9628826591F,
  156513. 0.9633735388F, 0.9638599227F, 0.9643418303F, 0.9648192808F,
  156514. 0.9652922939F, 0.9657608890F, 0.9662250860F, 0.9666849046F,
  156515. 0.9671403646F, 0.9675914861F, 0.9680382891F, 0.9684807937F,
  156516. 0.9689190202F, 0.9693529890F, 0.9697827203F, 0.9702082347F,
  156517. 0.9706295529F, 0.9710466953F, 0.9714596828F, 0.9718685362F,
  156518. 0.9722732762F, 0.9726739240F, 0.9730705005F, 0.9734630267F,
  156519. 0.9738515239F, 0.9742360134F, 0.9746165163F, 0.9749930540F,
  156520. 0.9753656481F, 0.9757343198F, 0.9760990909F, 0.9764599829F,
  156521. 0.9768170175F, 0.9771702164F, 0.9775196013F, 0.9778651941F,
  156522. 0.9782070167F, 0.9785450909F, 0.9788794388F, 0.9792100824F,
  156523. 0.9795370437F, 0.9798603449F, 0.9801800080F, 0.9804960554F,
  156524. 0.9808085092F, 0.9811173916F, 0.9814227251F, 0.9817245318F,
  156525. 0.9820228343F, 0.9823176549F, 0.9826090160F, 0.9828969402F,
  156526. 0.9831814498F, 0.9834625674F, 0.9837403156F, 0.9840147169F,
  156527. 0.9842857939F, 0.9845535692F, 0.9848180654F, 0.9850793052F,
  156528. 0.9853373113F, 0.9855921062F, 0.9858437127F, 0.9860921535F,
  156529. 0.9863374512F, 0.9865796287F, 0.9868187085F, 0.9870547136F,
  156530. 0.9872876664F, 0.9875175899F, 0.9877445067F, 0.9879684396F,
  156531. 0.9881894112F, 0.9884074444F, 0.9886225619F, 0.9888347863F,
  156532. 0.9890441404F, 0.9892506468F, 0.9894543284F, 0.9896552077F,
  156533. 0.9898533074F, 0.9900486502F, 0.9902412587F, 0.9904311555F,
  156534. 0.9906183633F, 0.9908029045F, 0.9909848019F, 0.9911640779F,
  156535. 0.9913407550F, 0.9915148557F, 0.9916864025F, 0.9918554179F,
  156536. 0.9920219241F, 0.9921859437F, 0.9923474989F, 0.9925066120F,
  156537. 0.9926633054F, 0.9928176012F, 0.9929695218F, 0.9931190891F,
  156538. 0.9932663254F, 0.9934112527F, 0.9935538932F, 0.9936942686F,
  156539. 0.9938324012F, 0.9939683126F, 0.9941020248F, 0.9942335597F,
  156540. 0.9943629388F, 0.9944901841F, 0.9946153170F, 0.9947383593F,
  156541. 0.9948593325F, 0.9949782579F, 0.9950951572F, 0.9952100516F,
  156542. 0.9953229625F, 0.9954339111F, 0.9955429186F, 0.9956500062F,
  156543. 0.9957551948F, 0.9958585056F, 0.9959599593F, 0.9960595769F,
  156544. 0.9961573792F, 0.9962533869F, 0.9963476206F, 0.9964401009F,
  156545. 0.9965308483F, 0.9966198833F, 0.9967072261F, 0.9967928971F,
  156546. 0.9968769164F, 0.9969593041F, 0.9970400804F, 0.9971192651F,
  156547. 0.9971968781F, 0.9972729391F, 0.9973474680F, 0.9974204842F,
  156548. 0.9974920074F, 0.9975620569F, 0.9976306521F, 0.9976978122F,
  156549. 0.9977635565F, 0.9978279039F, 0.9978908736F, 0.9979524842F,
  156550. 0.9980127547F, 0.9980717037F, 0.9981293499F, 0.9981857116F,
  156551. 0.9982408073F, 0.9982946554F, 0.9983472739F, 0.9983986810F,
  156552. 0.9984488947F, 0.9984979328F, 0.9985458132F, 0.9985925534F,
  156553. 0.9986381711F, 0.9986826838F, 0.9987261086F, 0.9987684630F,
  156554. 0.9988097640F, 0.9988500286F, 0.9988892738F, 0.9989275163F,
  156555. 0.9989647727F, 0.9990010597F, 0.9990363938F, 0.9990707911F,
  156556. 0.9991042679F, 0.9991368404F, 0.9991685244F, 0.9991993358F,
  156557. 0.9992292905F, 0.9992584038F, 0.9992866914F, 0.9993141686F,
  156558. 0.9993408506F, 0.9993667526F, 0.9993918895F, 0.9994162761F,
  156559. 0.9994399273F, 0.9994628576F, 0.9994850815F, 0.9995066133F,
  156560. 0.9995274672F, 0.9995476574F, 0.9995671978F, 0.9995861021F,
  156561. 0.9996043841F, 0.9996220573F, 0.9996391352F, 0.9996556310F,
  156562. 0.9996715579F, 0.9996869288F, 0.9997017568F, 0.9997160543F,
  156563. 0.9997298342F, 0.9997431088F, 0.9997558905F, 0.9997681914F,
  156564. 0.9997800236F, 0.9997913990F, 0.9998023292F, 0.9998128261F,
  156565. 0.9998229009F, 0.9998325650F, 0.9998418296F, 0.9998507058F,
  156566. 0.9998592044F, 0.9998673362F, 0.9998751117F, 0.9998825415F,
  156567. 0.9998896358F, 0.9998964047F, 0.9999028584F, 0.9999090066F,
  156568. 0.9999148590F, 0.9999204253F, 0.9999257148F, 0.9999307368F,
  156569. 0.9999355003F, 0.9999400144F, 0.9999442878F, 0.9999483293F,
  156570. 0.9999521472F, 0.9999557499F, 0.9999591457F, 0.9999623426F,
  156571. 0.9999653483F, 0.9999681708F, 0.9999708175F, 0.9999732959F,
  156572. 0.9999756132F, 0.9999777765F, 0.9999797928F, 0.9999816688F,
  156573. 0.9999834113F, 0.9999850266F, 0.9999865211F, 0.9999879009F,
  156574. 0.9999891721F, 0.9999903405F, 0.9999914118F, 0.9999923914F,
  156575. 0.9999932849F, 0.9999940972F, 0.9999948336F, 0.9999954989F,
  156576. 0.9999960978F, 0.9999966349F, 0.9999971146F, 0.9999975411F,
  156577. 0.9999979185F, 0.9999982507F, 0.9999985414F, 0.9999987944F,
  156578. 0.9999990129F, 0.9999992003F, 0.9999993596F, 0.9999994939F,
  156579. 0.9999996059F, 0.9999996981F, 0.9999997732F, 0.9999998333F,
  156580. 0.9999998805F, 0.9999999170F, 0.9999999444F, 0.9999999643F,
  156581. 0.9999999784F, 0.9999999878F, 0.9999999937F, 0.9999999972F,
  156582. 0.9999999990F, 0.9999999997F, 1.0000000000F, 1.0000000000F,
  156583. };
  156584. static float vwin4096[2048] = {
  156585. 0.0000002310F, 0.0000020791F, 0.0000057754F, 0.0000113197F,
  156586. 0.0000187121F, 0.0000279526F, 0.0000390412F, 0.0000519777F,
  156587. 0.0000667623F, 0.0000833949F, 0.0001018753F, 0.0001222036F,
  156588. 0.0001443798F, 0.0001684037F, 0.0001942754F, 0.0002219947F,
  156589. 0.0002515616F, 0.0002829761F, 0.0003162380F, 0.0003513472F,
  156590. 0.0003883038F, 0.0004271076F, 0.0004677584F, 0.0005102563F,
  156591. 0.0005546011F, 0.0006007928F, 0.0006488311F, 0.0006987160F,
  156592. 0.0007504474F, 0.0008040251F, 0.0008594490F, 0.0009167191F,
  156593. 0.0009758351F, 0.0010367969F, 0.0010996044F, 0.0011642574F,
  156594. 0.0012307558F, 0.0012990994F, 0.0013692880F, 0.0014413216F,
  156595. 0.0015151998F, 0.0015909226F, 0.0016684898F, 0.0017479011F,
  156596. 0.0018291565F, 0.0019122556F, 0.0019971983F, 0.0020839845F,
  156597. 0.0021726138F, 0.0022630861F, 0.0023554012F, 0.0024495588F,
  156598. 0.0025455588F, 0.0026434008F, 0.0027430847F, 0.0028446103F,
  156599. 0.0029479772F, 0.0030531853F, 0.0031602342F, 0.0032691238F,
  156600. 0.0033798538F, 0.0034924239F, 0.0036068338F, 0.0037230833F,
  156601. 0.0038411721F, 0.0039610999F, 0.0040828664F, 0.0042064714F,
  156602. 0.0043319145F, 0.0044591954F, 0.0045883139F, 0.0047192696F,
  156603. 0.0048520622F, 0.0049866914F, 0.0051231569F, 0.0052614583F,
  156604. 0.0054015953F, 0.0055435676F, 0.0056873748F, 0.0058330166F,
  156605. 0.0059804926F, 0.0061298026F, 0.0062809460F, 0.0064339226F,
  156606. 0.0065887320F, 0.0067453738F, 0.0069038476F, 0.0070641531F,
  156607. 0.0072262899F, 0.0073902575F, 0.0075560556F, 0.0077236838F,
  156608. 0.0078931417F, 0.0080644288F, 0.0082375447F, 0.0084124891F,
  156609. 0.0085892615F, 0.0087678614F, 0.0089482885F, 0.0091305422F,
  156610. 0.0093146223F, 0.0095005281F, 0.0096882592F, 0.0098778153F,
  156611. 0.0100691958F, 0.0102624002F, 0.0104574281F, 0.0106542791F,
  156612. 0.0108529525F, 0.0110534480F, 0.0112557651F, 0.0114599032F,
  156613. 0.0116658618F, 0.0118736405F, 0.0120832387F, 0.0122946560F,
  156614. 0.0125078917F, 0.0127229454F, 0.0129398166F, 0.0131585046F,
  156615. 0.0133790090F, 0.0136013292F, 0.0138254647F, 0.0140514149F,
  156616. 0.0142791792F, 0.0145087572F, 0.0147401481F, 0.0149733515F,
  156617. 0.0152083667F, 0.0154451932F, 0.0156838304F, 0.0159242777F,
  156618. 0.0161665345F, 0.0164106001F, 0.0166564741F, 0.0169041557F,
  156619. 0.0171536443F, 0.0174049393F, 0.0176580401F, 0.0179129461F,
  156620. 0.0181696565F, 0.0184281708F, 0.0186884883F, 0.0189506084F,
  156621. 0.0192145303F, 0.0194802535F, 0.0197477772F, 0.0200171008F,
  156622. 0.0202882236F, 0.0205611449F, 0.0208358639F, 0.0211123801F,
  156623. 0.0213906927F, 0.0216708011F, 0.0219527043F, 0.0222364019F,
  156624. 0.0225218930F, 0.0228091769F, 0.0230982529F, 0.0233891203F,
  156625. 0.0236817782F, 0.0239762259F, 0.0242724628F, 0.0245704880F,
  156626. 0.0248703007F, 0.0251719002F, 0.0254752858F, 0.0257804565F,
  156627. 0.0260874117F, 0.0263961506F, 0.0267066722F, 0.0270189760F,
  156628. 0.0273330609F, 0.0276489263F, 0.0279665712F, 0.0282859949F,
  156629. 0.0286071966F, 0.0289301753F, 0.0292549303F, 0.0295814607F,
  156630. 0.0299097656F, 0.0302398442F, 0.0305716957F, 0.0309053191F,
  156631. 0.0312407135F, 0.0315778782F, 0.0319168122F, 0.0322575145F,
  156632. 0.0325999844F, 0.0329442209F, 0.0332902231F, 0.0336379900F,
  156633. 0.0339875208F, 0.0343388146F, 0.0346918703F, 0.0350466871F,
  156634. 0.0354032640F, 0.0357616000F, 0.0361216943F, 0.0364835458F,
  156635. 0.0368471535F, 0.0372125166F, 0.0375796339F, 0.0379485046F,
  156636. 0.0383191276F, 0.0386915020F, 0.0390656267F, 0.0394415008F,
  156637. 0.0398191231F, 0.0401984927F, 0.0405796086F, 0.0409624698F,
  156638. 0.0413470751F, 0.0417334235F, 0.0421215141F, 0.0425113457F,
  156639. 0.0429029172F, 0.0432962277F, 0.0436912760F, 0.0440880610F,
  156640. 0.0444865817F, 0.0448868370F, 0.0452888257F, 0.0456925468F,
  156641. 0.0460979992F, 0.0465051816F, 0.0469140931F, 0.0473247325F,
  156642. 0.0477370986F, 0.0481511902F, 0.0485670064F, 0.0489845458F,
  156643. 0.0494038074F, 0.0498247899F, 0.0502474922F, 0.0506719131F,
  156644. 0.0510980514F, 0.0515259060F, 0.0519554756F, 0.0523867590F,
  156645. 0.0528197550F, 0.0532544624F, 0.0536908800F, 0.0541290066F,
  156646. 0.0545688408F, 0.0550103815F, 0.0554536274F, 0.0558985772F,
  156647. 0.0563452297F, 0.0567935837F, 0.0572436377F, 0.0576953907F,
  156648. 0.0581488412F, 0.0586039880F, 0.0590608297F, 0.0595193651F,
  156649. 0.0599795929F, 0.0604415117F, 0.0609051202F, 0.0613704170F,
  156650. 0.0618374009F, 0.0623060704F, 0.0627764243F, 0.0632484611F,
  156651. 0.0637221795F, 0.0641975781F, 0.0646746555F, 0.0651534104F,
  156652. 0.0656338413F, 0.0661159469F, 0.0665997257F, 0.0670851763F,
  156653. 0.0675722973F, 0.0680610873F, 0.0685515448F, 0.0690436684F,
  156654. 0.0695374567F, 0.0700329081F, 0.0705300213F, 0.0710287947F,
  156655. 0.0715292269F, 0.0720313163F, 0.0725350616F, 0.0730404612F,
  156656. 0.0735475136F, 0.0740562172F, 0.0745665707F, 0.0750785723F,
  156657. 0.0755922207F, 0.0761075143F, 0.0766244515F, 0.0771430307F,
  156658. 0.0776632505F, 0.0781851092F, 0.0787086052F, 0.0792337371F,
  156659. 0.0797605032F, 0.0802889018F, 0.0808189315F, 0.0813505905F,
  156660. 0.0818838773F, 0.0824187903F, 0.0829553277F, 0.0834934881F,
  156661. 0.0840332697F, 0.0845746708F, 0.0851176899F, 0.0856623252F,
  156662. 0.0862085751F, 0.0867564379F, 0.0873059119F, 0.0878569954F,
  156663. 0.0884096867F, 0.0889639840F, 0.0895198858F, 0.0900773902F,
  156664. 0.0906364955F, 0.0911972000F, 0.0917595019F, 0.0923233995F,
  156665. 0.0928888909F, 0.0934559745F, 0.0940246485F, 0.0945949110F,
  156666. 0.0951667604F, 0.0957401946F, 0.0963152121F, 0.0968918109F,
  156667. 0.0974699893F, 0.0980497454F, 0.0986310773F, 0.0992139832F,
  156668. 0.0997984614F, 0.1003845098F, 0.1009721267F, 0.1015613101F,
  156669. 0.1021520582F, 0.1027443692F, 0.1033382410F, 0.1039336718F,
  156670. 0.1045306597F, 0.1051292027F, 0.1057292990F, 0.1063309466F,
  156671. 0.1069341435F, 0.1075388878F, 0.1081451776F, 0.1087530108F,
  156672. 0.1093623856F, 0.1099732998F, 0.1105857516F, 0.1111997389F,
  156673. 0.1118152597F, 0.1124323121F, 0.1130508939F, 0.1136710032F,
  156674. 0.1142926379F, 0.1149157960F, 0.1155404755F, 0.1161666742F,
  156675. 0.1167943901F, 0.1174236211F, 0.1180543652F, 0.1186866202F,
  156676. 0.1193203841F, 0.1199556548F, 0.1205924300F, 0.1212307078F,
  156677. 0.1218704860F, 0.1225117624F, 0.1231545349F, 0.1237988013F,
  156678. 0.1244445596F, 0.1250918074F, 0.1257405427F, 0.1263907632F,
  156679. 0.1270424667F, 0.1276956512F, 0.1283503142F, 0.1290064537F,
  156680. 0.1296640674F, 0.1303231530F, 0.1309837084F, 0.1316457312F,
  156681. 0.1323092193F, 0.1329741703F, 0.1336405820F, 0.1343084520F,
  156682. 0.1349777782F, 0.1356485582F, 0.1363207897F, 0.1369944704F,
  156683. 0.1376695979F, 0.1383461700F, 0.1390241842F, 0.1397036384F,
  156684. 0.1403845300F, 0.1410668567F, 0.1417506162F, 0.1424358061F,
  156685. 0.1431224240F, 0.1438104674F, 0.1444999341F, 0.1451908216F,
  156686. 0.1458831274F, 0.1465768492F, 0.1472719844F, 0.1479685308F,
  156687. 0.1486664857F, 0.1493658468F, 0.1500666115F, 0.1507687775F,
  156688. 0.1514723422F, 0.1521773031F, 0.1528836577F, 0.1535914035F,
  156689. 0.1543005380F, 0.1550110587F, 0.1557229631F, 0.1564362485F,
  156690. 0.1571509124F, 0.1578669524F, 0.1585843657F, 0.1593031499F,
  156691. 0.1600233024F, 0.1607448205F, 0.1614677017F, 0.1621919433F,
  156692. 0.1629175428F, 0.1636444975F, 0.1643728047F, 0.1651024619F,
  156693. 0.1658334665F, 0.1665658156F, 0.1672995067F, 0.1680345371F,
  156694. 0.1687709041F, 0.1695086050F, 0.1702476372F, 0.1709879978F,
  156695. 0.1717296843F, 0.1724726938F, 0.1732170237F, 0.1739626711F,
  156696. 0.1747096335F, 0.1754579079F, 0.1762074916F, 0.1769583819F,
  156697. 0.1777105760F, 0.1784640710F, 0.1792188642F, 0.1799749529F,
  156698. 0.1807323340F, 0.1814910049F, 0.1822509628F, 0.1830122046F,
  156699. 0.1837747277F, 0.1845385292F, 0.1853036062F, 0.1860699558F,
  156700. 0.1868375751F, 0.1876064613F, 0.1883766114F, 0.1891480226F,
  156701. 0.1899206919F, 0.1906946164F, 0.1914697932F, 0.1922462194F,
  156702. 0.1930238919F, 0.1938028079F, 0.1945829643F, 0.1953643583F,
  156703. 0.1961469868F, 0.1969308468F, 0.1977159353F, 0.1985022494F,
  156704. 0.1992897859F, 0.2000785420F, 0.2008685145F, 0.2016597005F,
  156705. 0.2024520968F, 0.2032457005F, 0.2040405084F, 0.2048365175F,
  156706. 0.2056337247F, 0.2064321269F, 0.2072317211F, 0.2080325041F,
  156707. 0.2088344727F, 0.2096376240F, 0.2104419547F, 0.2112474618F,
  156708. 0.2120541420F, 0.2128619923F, 0.2136710094F, 0.2144811902F,
  156709. 0.2152925315F, 0.2161050301F, 0.2169186829F, 0.2177334866F,
  156710. 0.2185494381F, 0.2193665340F, 0.2201847712F, 0.2210041465F,
  156711. 0.2218246565F, 0.2226462981F, 0.2234690680F, 0.2242929629F,
  156712. 0.2251179796F, 0.2259441147F, 0.2267713650F, 0.2275997272F,
  156713. 0.2284291979F, 0.2292597739F, 0.2300914518F, 0.2309242283F,
  156714. 0.2317581001F, 0.2325930638F, 0.2334291160F, 0.2342662534F,
  156715. 0.2351044727F, 0.2359437703F, 0.2367841431F, 0.2376255875F,
  156716. 0.2384681001F, 0.2393116776F, 0.2401563165F, 0.2410020134F,
  156717. 0.2418487649F, 0.2426965675F, 0.2435454178F, 0.2443953122F,
  156718. 0.2452462474F, 0.2460982199F, 0.2469512262F, 0.2478052628F,
  156719. 0.2486603262F, 0.2495164129F, 0.2503735194F, 0.2512316421F,
  156720. 0.2520907776F, 0.2529509222F, 0.2538120726F, 0.2546742250F,
  156721. 0.2555373760F, 0.2564015219F, 0.2572666593F, 0.2581327845F,
  156722. 0.2589998939F, 0.2598679840F, 0.2607370510F, 0.2616070916F,
  156723. 0.2624781019F, 0.2633500783F, 0.2642230173F, 0.2650969152F,
  156724. 0.2659717684F, 0.2668475731F, 0.2677243257F, 0.2686020226F,
  156725. 0.2694806601F, 0.2703602344F, 0.2712407419F, 0.2721221789F,
  156726. 0.2730045417F, 0.2738878265F, 0.2747720297F, 0.2756571474F,
  156727. 0.2765431760F, 0.2774301117F, 0.2783179508F, 0.2792066895F,
  156728. 0.2800963240F, 0.2809868505F, 0.2818782654F, 0.2827705647F,
  156729. 0.2836637447F, 0.2845578016F, 0.2854527315F, 0.2863485307F,
  156730. 0.2872451953F, 0.2881427215F, 0.2890411055F, 0.2899403433F,
  156731. 0.2908404312F, 0.2917413654F, 0.2926431418F, 0.2935457567F,
  156732. 0.2944492061F, 0.2953534863F, 0.2962585932F, 0.2971645230F,
  156733. 0.2980712717F, 0.2989788356F, 0.2998872105F, 0.3007963927F,
  156734. 0.3017063781F, 0.3026171629F, 0.3035287430F, 0.3044411145F,
  156735. 0.3053542736F, 0.3062682161F, 0.3071829381F, 0.3080984356F,
  156736. 0.3090147047F, 0.3099317413F, 0.3108495414F, 0.3117681011F,
  156737. 0.3126874163F, 0.3136074830F, 0.3145282972F, 0.3154498548F,
  156738. 0.3163721517F, 0.3172951841F, 0.3182189477F, 0.3191434385F,
  156739. 0.3200686525F, 0.3209945856F, 0.3219212336F, 0.3228485927F,
  156740. 0.3237766585F, 0.3247054271F, 0.3256348943F, 0.3265650560F,
  156741. 0.3274959081F, 0.3284274465F, 0.3293596671F, 0.3302925657F,
  156742. 0.3312261382F, 0.3321603804F, 0.3330952882F, 0.3340308574F,
  156743. 0.3349670838F, 0.3359039634F, 0.3368414919F, 0.3377796651F,
  156744. 0.3387184789F, 0.3396579290F, 0.3405980113F, 0.3415387216F,
  156745. 0.3424800556F, 0.3434220091F, 0.3443645779F, 0.3453077578F,
  156746. 0.3462515446F, 0.3471959340F, 0.3481409217F, 0.3490865036F,
  156747. 0.3500326754F, 0.3509794328F, 0.3519267715F, 0.3528746873F,
  156748. 0.3538231759F, 0.3547722330F, 0.3557218544F, 0.3566720357F,
  156749. 0.3576227727F, 0.3585740610F, 0.3595258964F, 0.3604782745F,
  156750. 0.3614311910F, 0.3623846417F, 0.3633386221F, 0.3642931280F,
  156751. 0.3652481549F, 0.3662036987F, 0.3671597548F, 0.3681163191F,
  156752. 0.3690733870F, 0.3700309544F, 0.3709890167F, 0.3719475696F,
  156753. 0.3729066089F, 0.3738661299F, 0.3748261285F, 0.3757866002F,
  156754. 0.3767475406F, 0.3777089453F, 0.3786708100F, 0.3796331302F,
  156755. 0.3805959014F, 0.3815591194F, 0.3825227796F, 0.3834868777F,
  156756. 0.3844514093F, 0.3854163698F, 0.3863817549F, 0.3873475601F,
  156757. 0.3883137810F, 0.3892804131F, 0.3902474521F, 0.3912148933F,
  156758. 0.3921827325F, 0.3931509650F, 0.3941195865F, 0.3950885925F,
  156759. 0.3960579785F, 0.3970277400F, 0.3979978725F, 0.3989683716F,
  156760. 0.3999392328F, 0.4009104516F, 0.4018820234F, 0.4028539438F,
  156761. 0.4038262084F, 0.4047988125F, 0.4057717516F, 0.4067450214F,
  156762. 0.4077186172F, 0.4086925345F, 0.4096667688F, 0.4106413155F,
  156763. 0.4116161703F, 0.4125913284F, 0.4135667854F, 0.4145425368F,
  156764. 0.4155185780F, 0.4164949044F, 0.4174715116F, 0.4184483949F,
  156765. 0.4194255498F, 0.4204029718F, 0.4213806563F, 0.4223585987F,
  156766. 0.4233367946F, 0.4243152392F, 0.4252939281F, 0.4262728566F,
  156767. 0.4272520202F, 0.4282314144F, 0.4292110345F, 0.4301908760F,
  156768. 0.4311709343F, 0.4321512047F, 0.4331316828F, 0.4341123639F,
  156769. 0.4350932435F, 0.4360743168F, 0.4370555794F, 0.4380370267F,
  156770. 0.4390186540F, 0.4400004567F, 0.4409824303F, 0.4419645701F,
  156771. 0.4429468716F, 0.4439293300F, 0.4449119409F, 0.4458946996F,
  156772. 0.4468776014F, 0.4478606418F, 0.4488438162F, 0.4498271199F,
  156773. 0.4508105483F, 0.4517940967F, 0.4527777607F, 0.4537615355F,
  156774. 0.4547454165F, 0.4557293991F, 0.4567134786F, 0.4576976505F,
  156775. 0.4586819101F, 0.4596662527F, 0.4606506738F, 0.4616351687F,
  156776. 0.4626197328F, 0.4636043614F, 0.4645890499F, 0.4655737936F,
  156777. 0.4665585880F, 0.4675434284F, 0.4685283101F, 0.4695132286F,
  156778. 0.4704981791F, 0.4714831570F, 0.4724681577F, 0.4734531766F,
  156779. 0.4744382089F, 0.4754232501F, 0.4764082956F, 0.4773933406F,
  156780. 0.4783783806F, 0.4793634108F, 0.4803484267F, 0.4813334237F,
  156781. 0.4823183969F, 0.4833033419F, 0.4842882540F, 0.4852731285F,
  156782. 0.4862579608F, 0.4872427462F, 0.4882274802F, 0.4892121580F,
  156783. 0.4901967751F, 0.4911813267F, 0.4921658083F, 0.4931502151F,
  156784. 0.4941345427F, 0.4951187863F, 0.4961029412F, 0.4970870029F,
  156785. 0.4980709667F, 0.4990548280F, 0.5000385822F, 0.5010222245F,
  156786. 0.5020057505F, 0.5029891553F, 0.5039724345F, 0.5049555834F,
  156787. 0.5059385973F, 0.5069214716F, 0.5079042018F, 0.5088867831F,
  156788. 0.5098692110F, 0.5108514808F, 0.5118335879F, 0.5128155277F,
  156789. 0.5137972956F, 0.5147788869F, 0.5157602971F, 0.5167415215F,
  156790. 0.5177225555F, 0.5187033945F, 0.5196840339F, 0.5206644692F,
  156791. 0.5216446956F, 0.5226247086F, 0.5236045035F, 0.5245840759F,
  156792. 0.5255634211F, 0.5265425344F, 0.5275214114F, 0.5285000474F,
  156793. 0.5294784378F, 0.5304565781F, 0.5314344637F, 0.5324120899F,
  156794. 0.5333894522F, 0.5343665461F, 0.5353433670F, 0.5363199102F,
  156795. 0.5372961713F, 0.5382721457F, 0.5392478287F, 0.5402232159F,
  156796. 0.5411983027F, 0.5421730845F, 0.5431475569F, 0.5441217151F,
  156797. 0.5450955548F, 0.5460690714F, 0.5470422602F, 0.5480151169F,
  156798. 0.5489876368F, 0.5499598155F, 0.5509316484F, 0.5519031310F,
  156799. 0.5528742587F, 0.5538450271F, 0.5548154317F, 0.5557854680F,
  156800. 0.5567551314F, 0.5577244174F, 0.5586933216F, 0.5596618395F,
  156801. 0.5606299665F, 0.5615976983F, 0.5625650302F, 0.5635319580F,
  156802. 0.5644984770F, 0.5654645828F, 0.5664302709F, 0.5673955370F,
  156803. 0.5683603765F, 0.5693247850F, 0.5702887580F, 0.5712522912F,
  156804. 0.5722153800F, 0.5731780200F, 0.5741402069F, 0.5751019362F,
  156805. 0.5760632034F, 0.5770240042F, 0.5779843341F, 0.5789441889F,
  156806. 0.5799035639F, 0.5808624549F, 0.5818208575F, 0.5827787673F,
  156807. 0.5837361800F, 0.5846930910F, 0.5856494961F, 0.5866053910F,
  156808. 0.5875607712F, 0.5885156324F, 0.5894699703F, 0.5904237804F,
  156809. 0.5913770586F, 0.5923298004F, 0.5932820016F, 0.5942336578F,
  156810. 0.5951847646F, 0.5961353179F, 0.5970853132F, 0.5980347464F,
  156811. 0.5989836131F, 0.5999319090F, 0.6008796298F, 0.6018267713F,
  156812. 0.6027733292F, 0.6037192993F, 0.6046646773F, 0.6056094589F,
  156813. 0.6065536400F, 0.6074972162F, 0.6084401833F, 0.6093825372F,
  156814. 0.6103242736F, 0.6112653884F, 0.6122058772F, 0.6131457359F,
  156815. 0.6140849604F, 0.6150235464F, 0.6159614897F, 0.6168987862F,
  156816. 0.6178354318F, 0.6187714223F, 0.6197067535F, 0.6206414213F,
  156817. 0.6215754215F, 0.6225087501F, 0.6234414028F, 0.6243733757F,
  156818. 0.6253046646F, 0.6262352654F, 0.6271651739F, 0.6280943862F,
  156819. 0.6290228982F, 0.6299507057F, 0.6308778048F, 0.6318041913F,
  156820. 0.6327298612F, 0.6336548105F, 0.6345790352F, 0.6355025312F,
  156821. 0.6364252945F, 0.6373473211F, 0.6382686070F, 0.6391891483F,
  156822. 0.6401089409F, 0.6410279808F, 0.6419462642F, 0.6428637869F,
  156823. 0.6437805452F, 0.6446965350F, 0.6456117524F, 0.6465261935F,
  156824. 0.6474398544F, 0.6483527311F, 0.6492648197F, 0.6501761165F,
  156825. 0.6510866174F, 0.6519963186F, 0.6529052162F, 0.6538133064F,
  156826. 0.6547205854F, 0.6556270492F, 0.6565326941F, 0.6574375162F,
  156827. 0.6583415117F, 0.6592446769F, 0.6601470079F, 0.6610485009F,
  156828. 0.6619491521F, 0.6628489578F, 0.6637479143F, 0.6646460177F,
  156829. 0.6655432643F, 0.6664396505F, 0.6673351724F, 0.6682298264F,
  156830. 0.6691236087F, 0.6700165157F, 0.6709085436F, 0.6717996889F,
  156831. 0.6726899478F, 0.6735793167F, 0.6744677918F, 0.6753553697F,
  156832. 0.6762420466F, 0.6771278190F, 0.6780126832F, 0.6788966357F,
  156833. 0.6797796728F, 0.6806617909F, 0.6815429866F, 0.6824232562F,
  156834. 0.6833025961F, 0.6841810030F, 0.6850584731F, 0.6859350031F,
  156835. 0.6868105894F, 0.6876852284F, 0.6885589168F, 0.6894316510F,
  156836. 0.6903034275F, 0.6911742430F, 0.6920440939F, 0.6929129769F,
  156837. 0.6937808884F, 0.6946478251F, 0.6955137837F, 0.6963787606F,
  156838. 0.6972427525F, 0.6981057560F, 0.6989677678F, 0.6998287845F,
  156839. 0.7006888028F, 0.7015478194F, 0.7024058309F, 0.7032628340F,
  156840. 0.7041188254F, 0.7049738019F, 0.7058277601F, 0.7066806969F,
  156841. 0.7075326089F, 0.7083834929F, 0.7092333457F, 0.7100821640F,
  156842. 0.7109299447F, 0.7117766846F, 0.7126223804F, 0.7134670291F,
  156843. 0.7143106273F, 0.7151531721F, 0.7159946602F, 0.7168350885F,
  156844. 0.7176744539F, 0.7185127534F, 0.7193499837F, 0.7201861418F,
  156845. 0.7210212247F, 0.7218552293F, 0.7226881526F, 0.7235199914F,
  156846. 0.7243507428F, 0.7251804039F, 0.7260089715F, 0.7268364426F,
  156847. 0.7276628144F, 0.7284880839F, 0.7293122481F, 0.7301353040F,
  156848. 0.7309572487F, 0.7317780794F, 0.7325977930F, 0.7334163868F,
  156849. 0.7342338579F, 0.7350502033F, 0.7358654202F, 0.7366795059F,
  156850. 0.7374924573F, 0.7383042718F, 0.7391149465F, 0.7399244787F,
  156851. 0.7407328655F, 0.7415401041F, 0.7423461920F, 0.7431511261F,
  156852. 0.7439549040F, 0.7447575227F, 0.7455589797F, 0.7463592723F,
  156853. 0.7471583976F, 0.7479563532F, 0.7487531363F, 0.7495487443F,
  156854. 0.7503431745F, 0.7511364244F, 0.7519284913F, 0.7527193726F,
  156855. 0.7535090658F, 0.7542975683F, 0.7550848776F, 0.7558709910F,
  156856. 0.7566559062F, 0.7574396205F, 0.7582221314F, 0.7590034366F,
  156857. 0.7597835334F, 0.7605624194F, 0.7613400923F, 0.7621165495F,
  156858. 0.7628917886F, 0.7636658072F, 0.7644386030F, 0.7652101735F,
  156859. 0.7659805164F, 0.7667496292F, 0.7675175098F, 0.7682841556F,
  156860. 0.7690495645F, 0.7698137341F, 0.7705766622F, 0.7713383463F,
  156861. 0.7720987844F, 0.7728579741F, 0.7736159132F, 0.7743725994F,
  156862. 0.7751280306F, 0.7758822046F, 0.7766351192F, 0.7773867722F,
  156863. 0.7781371614F, 0.7788862848F, 0.7796341401F, 0.7803807253F,
  156864. 0.7811260383F, 0.7818700769F, 0.7826128392F, 0.7833543230F,
  156865. 0.7840945263F, 0.7848334471F, 0.7855710833F, 0.7863074330F,
  156866. 0.7870424941F, 0.7877762647F, 0.7885087428F, 0.7892399264F,
  156867. 0.7899698137F, 0.7906984026F, 0.7914256914F, 0.7921516780F,
  156868. 0.7928763607F, 0.7935997375F, 0.7943218065F, 0.7950425661F,
  156869. 0.7957620142F, 0.7964801492F, 0.7971969692F, 0.7979124724F,
  156870. 0.7986266570F, 0.7993395214F, 0.8000510638F, 0.8007612823F,
  156871. 0.8014701754F, 0.8021777413F, 0.8028839784F, 0.8035888849F,
  156872. 0.8042924592F, 0.8049946997F, 0.8056956048F, 0.8063951727F,
  156873. 0.8070934020F, 0.8077902910F, 0.8084858381F, 0.8091800419F,
  156874. 0.8098729007F, 0.8105644130F, 0.8112545774F, 0.8119433922F,
  156875. 0.8126308561F, 0.8133169676F, 0.8140017251F, 0.8146851272F,
  156876. 0.8153671726F, 0.8160478598F, 0.8167271874F, 0.8174051539F,
  156877. 0.8180817582F, 0.8187569986F, 0.8194308741F, 0.8201033831F,
  156878. 0.8207745244F, 0.8214442966F, 0.8221126986F, 0.8227797290F,
  156879. 0.8234453865F, 0.8241096700F, 0.8247725781F, 0.8254341097F,
  156880. 0.8260942636F, 0.8267530385F, 0.8274104334F, 0.8280664470F,
  156881. 0.8287210782F, 0.8293743259F, 0.8300261889F, 0.8306766662F,
  156882. 0.8313257566F, 0.8319734591F, 0.8326197727F, 0.8332646963F,
  156883. 0.8339082288F, 0.8345503692F, 0.8351911167F, 0.8358304700F,
  156884. 0.8364684284F, 0.8371049907F, 0.8377401562F, 0.8383739238F,
  156885. 0.8390062927F, 0.8396372618F, 0.8402668305F, 0.8408949977F,
  156886. 0.8415217626F, 0.8421471245F, 0.8427710823F, 0.8433936354F,
  156887. 0.8440147830F, 0.8446345242F, 0.8452528582F, 0.8458697844F,
  156888. 0.8464853020F, 0.8470994102F, 0.8477121084F, 0.8483233958F,
  156889. 0.8489332718F, 0.8495417356F, 0.8501487866F, 0.8507544243F,
  156890. 0.8513586479F, 0.8519614568F, 0.8525628505F, 0.8531628283F,
  156891. 0.8537613897F, 0.8543585341F, 0.8549542611F, 0.8555485699F,
  156892. 0.8561414603F, 0.8567329315F, 0.8573229832F, 0.8579116149F,
  156893. 0.8584988262F, 0.8590846165F, 0.8596689855F, 0.8602519327F,
  156894. 0.8608334577F, 0.8614135603F, 0.8619922399F, 0.8625694962F,
  156895. 0.8631453289F, 0.8637197377F, 0.8642927222F, 0.8648642821F,
  156896. 0.8654344172F, 0.8660031272F, 0.8665704118F, 0.8671362708F,
  156897. 0.8677007039F, 0.8682637109F, 0.8688252917F, 0.8693854460F,
  156898. 0.8699441737F, 0.8705014745F, 0.8710573485F, 0.8716117953F,
  156899. 0.8721648150F, 0.8727164073F, 0.8732665723F, 0.8738153098F,
  156900. 0.8743626197F, 0.8749085021F, 0.8754529569F, 0.8759959840F,
  156901. 0.8765375835F, 0.8770777553F, 0.8776164996F, 0.8781538162F,
  156902. 0.8786897054F, 0.8792241670F, 0.8797572013F, 0.8802888082F,
  156903. 0.8808189880F, 0.8813477407F, 0.8818750664F, 0.8824009653F,
  156904. 0.8829254375F, 0.8834484833F, 0.8839701028F, 0.8844902961F,
  156905. 0.8850090636F, 0.8855264054F, 0.8860423218F, 0.8865568131F,
  156906. 0.8870698794F, 0.8875815212F, 0.8880917386F, 0.8886005319F,
  156907. 0.8891079016F, 0.8896138479F, 0.8901183712F, 0.8906214719F,
  156908. 0.8911231503F, 0.8916234067F, 0.8921222417F, 0.8926196556F,
  156909. 0.8931156489F, 0.8936102219F, 0.8941033752F, 0.8945951092F,
  156910. 0.8950854244F, 0.8955743212F, 0.8960618003F, 0.8965478621F,
  156911. 0.8970325071F, 0.8975157359F, 0.8979975490F, 0.8984779471F,
  156912. 0.8989569307F, 0.8994345004F, 0.8999106568F, 0.9003854005F,
  156913. 0.9008587323F, 0.9013306526F, 0.9018011623F, 0.9022702619F,
  156914. 0.9027379521F, 0.9032042337F, 0.9036691074F, 0.9041325739F,
  156915. 0.9045946339F, 0.9050552882F, 0.9055145376F, 0.9059723828F,
  156916. 0.9064288246F, 0.9068838638F, 0.9073375013F, 0.9077897379F,
  156917. 0.9082405743F, 0.9086900115F, 0.9091380503F, 0.9095846917F,
  156918. 0.9100299364F, 0.9104737854F, 0.9109162397F, 0.9113573001F,
  156919. 0.9117969675F, 0.9122352430F, 0.9126721275F, 0.9131076219F,
  156920. 0.9135417273F, 0.9139744447F, 0.9144057750F, 0.9148357194F,
  156921. 0.9152642787F, 0.9156914542F, 0.9161172468F, 0.9165416576F,
  156922. 0.9169646877F, 0.9173863382F, 0.9178066102F, 0.9182255048F,
  156923. 0.9186430232F, 0.9190591665F, 0.9194739359F, 0.9198873324F,
  156924. 0.9202993574F, 0.9207100120F, 0.9211192973F, 0.9215272147F,
  156925. 0.9219337653F, 0.9223389504F, 0.9227427713F, 0.9231452290F,
  156926. 0.9235463251F, 0.9239460607F, 0.9243444371F, 0.9247414557F,
  156927. 0.9251371177F, 0.9255314245F, 0.9259243774F, 0.9263159778F,
  156928. 0.9267062270F, 0.9270951264F, 0.9274826774F, 0.9278688814F,
  156929. 0.9282537398F, 0.9286372540F, 0.9290194254F, 0.9294002555F,
  156930. 0.9297797458F, 0.9301578976F, 0.9305347125F, 0.9309101919F,
  156931. 0.9312843373F, 0.9316571503F, 0.9320286323F, 0.9323987849F,
  156932. 0.9327676097F, 0.9331351080F, 0.9335012816F, 0.9338661320F,
  156933. 0.9342296607F, 0.9345918694F, 0.9349527596F, 0.9353123330F,
  156934. 0.9356705911F, 0.9360275357F, 0.9363831683F, 0.9367374905F,
  156935. 0.9370905042F, 0.9374422108F, 0.9377926122F, 0.9381417099F,
  156936. 0.9384895057F, 0.9388360014F, 0.9391811985F, 0.9395250989F,
  156937. 0.9398677043F, 0.9402090165F, 0.9405490371F, 0.9408877680F,
  156938. 0.9412252110F, 0.9415613678F, 0.9418962402F, 0.9422298301F,
  156939. 0.9425621392F, 0.9428931695F, 0.9432229226F, 0.9435514005F,
  156940. 0.9438786050F, 0.9442045381F, 0.9445292014F, 0.9448525971F,
  156941. 0.9451747268F, 0.9454955926F, 0.9458151963F, 0.9461335399F,
  156942. 0.9464506253F, 0.9467664545F, 0.9470810293F, 0.9473943517F,
  156943. 0.9477064238F, 0.9480172474F, 0.9483268246F, 0.9486351573F,
  156944. 0.9489422475F, 0.9492480973F, 0.9495527087F, 0.9498560837F,
  156945. 0.9501582243F, 0.9504591325F, 0.9507588105F, 0.9510572603F,
  156946. 0.9513544839F, 0.9516504834F, 0.9519452609F, 0.9522388186F,
  156947. 0.9525311584F, 0.9528222826F, 0.9531121932F, 0.9534008923F,
  156948. 0.9536883821F, 0.9539746647F, 0.9542597424F, 0.9545436171F,
  156949. 0.9548262912F, 0.9551077667F, 0.9553880459F, 0.9556671309F,
  156950. 0.9559450239F, 0.9562217272F, 0.9564972429F, 0.9567715733F,
  156951. 0.9570447206F, 0.9573166871F, 0.9575874749F, 0.9578570863F,
  156952. 0.9581255236F, 0.9583927890F, 0.9586588849F, 0.9589238134F,
  156953. 0.9591875769F, 0.9594501777F, 0.9597116180F, 0.9599719003F,
  156954. 0.9602310267F, 0.9604889995F, 0.9607458213F, 0.9610014942F,
  156955. 0.9612560206F, 0.9615094028F, 0.9617616433F, 0.9620127443F,
  156956. 0.9622627083F, 0.9625115376F, 0.9627592345F, 0.9630058016F,
  156957. 0.9632512411F, 0.9634955555F, 0.9637387471F, 0.9639808185F,
  156958. 0.9642217720F, 0.9644616100F, 0.9647003349F, 0.9649379493F,
  156959. 0.9651744556F, 0.9654098561F, 0.9656441534F, 0.9658773499F,
  156960. 0.9661094480F, 0.9663404504F, 0.9665703593F, 0.9667991774F,
  156961. 0.9670269071F, 0.9672535509F, 0.9674791114F, 0.9677035909F,
  156962. 0.9679269921F, 0.9681493174F, 0.9683705694F, 0.9685907506F,
  156963. 0.9688098636F, 0.9690279108F, 0.9692448948F, 0.9694608182F,
  156964. 0.9696756836F, 0.9698894934F, 0.9701022503F, 0.9703139569F,
  156965. 0.9705246156F, 0.9707342291F, 0.9709428000F, 0.9711503309F,
  156966. 0.9713568243F, 0.9715622829F, 0.9717667093F, 0.9719701060F,
  156967. 0.9721724757F, 0.9723738210F, 0.9725741446F, 0.9727734490F,
  156968. 0.9729717369F, 0.9731690109F, 0.9733652737F, 0.9735605279F,
  156969. 0.9737547762F, 0.9739480212F, 0.9741402656F, 0.9743315120F,
  156970. 0.9745217631F, 0.9747110216F, 0.9748992901F, 0.9750865714F,
  156971. 0.9752728681F, 0.9754581829F, 0.9756425184F, 0.9758258775F,
  156972. 0.9760082627F, 0.9761896768F, 0.9763701224F, 0.9765496024F,
  156973. 0.9767281193F, 0.9769056760F, 0.9770822751F, 0.9772579193F,
  156974. 0.9774326114F, 0.9776063542F, 0.9777791502F, 0.9779510023F,
  156975. 0.9781219133F, 0.9782918858F, 0.9784609226F, 0.9786290264F,
  156976. 0.9787962000F, 0.9789624461F, 0.9791277676F, 0.9792921671F,
  156977. 0.9794556474F, 0.9796182113F, 0.9797798615F, 0.9799406009F,
  156978. 0.9801004321F, 0.9802593580F, 0.9804173813F, 0.9805745049F,
  156979. 0.9807307314F, 0.9808860637F, 0.9810405046F, 0.9811940568F,
  156980. 0.9813467232F, 0.9814985065F, 0.9816494095F, 0.9817994351F,
  156981. 0.9819485860F, 0.9820968650F, 0.9822442750F, 0.9823908186F,
  156982. 0.9825364988F, 0.9826813184F, 0.9828252801F, 0.9829683868F,
  156983. 0.9831106413F, 0.9832520463F, 0.9833926048F, 0.9835323195F,
  156984. 0.9836711932F, 0.9838092288F, 0.9839464291F, 0.9840827969F,
  156985. 0.9842183351F, 0.9843530464F, 0.9844869337F, 0.9846199998F,
  156986. 0.9847522475F, 0.9848836798F, 0.9850142993F, 0.9851441090F,
  156987. 0.9852731117F, 0.9854013101F, 0.9855287073F, 0.9856553058F,
  156988. 0.9857811087F, 0.9859061188F, 0.9860303388F, 0.9861537717F,
  156989. 0.9862764202F, 0.9863982872F, 0.9865193756F, 0.9866396882F,
  156990. 0.9867592277F, 0.9868779972F, 0.9869959993F, 0.9871132370F,
  156991. 0.9872297131F, 0.9873454304F, 0.9874603918F, 0.9875746001F,
  156992. 0.9876880581F, 0.9878007688F, 0.9879127348F, 0.9880239592F,
  156993. 0.9881344447F, 0.9882441941F, 0.9883532104F, 0.9884614962F,
  156994. 0.9885690546F, 0.9886758883F, 0.9887820001F, 0.9888873930F,
  156995. 0.9889920697F, 0.9890960331F, 0.9891992859F, 0.9893018312F,
  156996. 0.9894036716F, 0.9895048100F, 0.9896052493F, 0.9897049923F,
  156997. 0.9898040418F, 0.9899024006F, 0.9900000717F, 0.9900970577F,
  156998. 0.9901933616F, 0.9902889862F, 0.9903839343F, 0.9904782087F,
  156999. 0.9905718122F, 0.9906647477F, 0.9907570180F, 0.9908486259F,
  157000. 0.9909395742F, 0.9910298658F, 0.9911195034F, 0.9912084899F,
  157001. 0.9912968281F, 0.9913845208F, 0.9914715708F, 0.9915579810F,
  157002. 0.9916437540F, 0.9917288928F, 0.9918134001F, 0.9918972788F,
  157003. 0.9919805316F, 0.9920631613F, 0.9921451707F, 0.9922265626F,
  157004. 0.9923073399F, 0.9923875052F, 0.9924670615F, 0.9925460114F,
  157005. 0.9926243577F, 0.9927021033F, 0.9927792508F, 0.9928558032F,
  157006. 0.9929317631F, 0.9930071333F, 0.9930819167F, 0.9931561158F,
  157007. 0.9932297337F, 0.9933027728F, 0.9933752362F, 0.9934471264F,
  157008. 0.9935184462F, 0.9935891985F, 0.9936593859F, 0.9937290112F,
  157009. 0.9937980771F, 0.9938665864F, 0.9939345418F, 0.9940019460F,
  157010. 0.9940688018F, 0.9941351118F, 0.9942008789F, 0.9942661057F,
  157011. 0.9943307950F, 0.9943949494F, 0.9944585717F, 0.9945216645F,
  157012. 0.9945842307F, 0.9946462728F, 0.9947077936F, 0.9947687957F,
  157013. 0.9948292820F, 0.9948892550F, 0.9949487174F, 0.9950076719F,
  157014. 0.9950661212F, 0.9951240679F, 0.9951815148F, 0.9952384645F,
  157015. 0.9952949196F, 0.9953508828F, 0.9954063568F, 0.9954613442F,
  157016. 0.9955158476F, 0.9955698697F, 0.9956234132F, 0.9956764806F,
  157017. 0.9957290746F, 0.9957811978F, 0.9958328528F, 0.9958840423F,
  157018. 0.9959347688F, 0.9959850351F, 0.9960348435F, 0.9960841969F,
  157019. 0.9961330977F, 0.9961815486F, 0.9962295521F, 0.9962771108F,
  157020. 0.9963242274F, 0.9963709043F, 0.9964171441F, 0.9964629494F,
  157021. 0.9965083228F, 0.9965532668F, 0.9965977840F, 0.9966418768F,
  157022. 0.9966855479F, 0.9967287998F, 0.9967716350F, 0.9968140559F,
  157023. 0.9968560653F, 0.9968976655F, 0.9969388591F, 0.9969796485F,
  157024. 0.9970200363F, 0.9970600250F, 0.9970996170F, 0.9971388149F,
  157025. 0.9971776211F, 0.9972160380F, 0.9972540683F, 0.9972917142F,
  157026. 0.9973289783F, 0.9973658631F, 0.9974023709F, 0.9974385042F,
  157027. 0.9974742655F, 0.9975096571F, 0.9975446816F, 0.9975793413F,
  157028. 0.9976136386F, 0.9976475759F, 0.9976811557F, 0.9977143803F,
  157029. 0.9977472521F, 0.9977797736F, 0.9978119470F, 0.9978437748F,
  157030. 0.9978752593F, 0.9979064029F, 0.9979372079F, 0.9979676768F,
  157031. 0.9979978117F, 0.9980276151F, 0.9980570893F, 0.9980862367F,
  157032. 0.9981150595F, 0.9981435600F, 0.9981717406F, 0.9981996035F,
  157033. 0.9982271511F, 0.9982543856F, 0.9982813093F, 0.9983079246F,
  157034. 0.9983342336F, 0.9983602386F, 0.9983859418F, 0.9984113456F,
  157035. 0.9984364522F, 0.9984612638F, 0.9984857825F, 0.9985100108F,
  157036. 0.9985339507F, 0.9985576044F, 0.9985809743F, 0.9986040624F,
  157037. 0.9986268710F, 0.9986494022F, 0.9986716583F, 0.9986936413F,
  157038. 0.9987153535F, 0.9987367969F, 0.9987579738F, 0.9987788864F,
  157039. 0.9987995366F, 0.9988199267F, 0.9988400587F, 0.9988599348F,
  157040. 0.9988795572F, 0.9988989278F, 0.9989180487F, 0.9989369222F,
  157041. 0.9989555501F, 0.9989739347F, 0.9989920780F, 0.9990099820F,
  157042. 0.9990276487F, 0.9990450803F, 0.9990622787F, 0.9990792460F,
  157043. 0.9990959841F, 0.9991124952F, 0.9991287812F, 0.9991448440F,
  157044. 0.9991606858F, 0.9991763084F, 0.9991917139F, 0.9992069042F,
  157045. 0.9992218813F, 0.9992366471F, 0.9992512035F, 0.9992655525F,
  157046. 0.9992796961F, 0.9992936361F, 0.9993073744F, 0.9993209131F,
  157047. 0.9993342538F, 0.9993473987F, 0.9993603494F, 0.9993731080F,
  157048. 0.9993856762F, 0.9993980559F, 0.9994102490F, 0.9994222573F,
  157049. 0.9994340827F, 0.9994457269F, 0.9994571918F, 0.9994684793F,
  157050. 0.9994795910F, 0.9994905288F, 0.9995012945F, 0.9995118898F,
  157051. 0.9995223165F, 0.9995325765F, 0.9995426713F, 0.9995526029F,
  157052. 0.9995623728F, 0.9995719829F, 0.9995814349F, 0.9995907304F,
  157053. 0.9995998712F, 0.9996088590F, 0.9996176954F, 0.9996263821F,
  157054. 0.9996349208F, 0.9996433132F, 0.9996515609F, 0.9996596656F,
  157055. 0.9996676288F, 0.9996754522F, 0.9996831375F, 0.9996906862F,
  157056. 0.9996981000F, 0.9997053804F, 0.9997125290F, 0.9997195474F,
  157057. 0.9997264371F, 0.9997331998F, 0.9997398369F, 0.9997463500F,
  157058. 0.9997527406F, 0.9997590103F, 0.9997651606F, 0.9997711930F,
  157059. 0.9997771089F, 0.9997829098F, 0.9997885973F, 0.9997941728F,
  157060. 0.9997996378F, 0.9998049936F, 0.9998102419F, 0.9998153839F,
  157061. 0.9998204211F, 0.9998253550F, 0.9998301868F, 0.9998349182F,
  157062. 0.9998395503F, 0.9998440847F, 0.9998485226F, 0.9998528654F,
  157063. 0.9998571146F, 0.9998612713F, 0.9998653370F, 0.9998693130F,
  157064. 0.9998732007F, 0.9998770012F, 0.9998807159F, 0.9998843461F,
  157065. 0.9998878931F, 0.9998913581F, 0.9998947424F, 0.9998980473F,
  157066. 0.9999012740F, 0.9999044237F, 0.9999074976F, 0.9999104971F,
  157067. 0.9999134231F, 0.9999162771F, 0.9999190601F, 0.9999217733F,
  157068. 0.9999244179F, 0.9999269950F, 0.9999295058F, 0.9999319515F,
  157069. 0.9999343332F, 0.9999366519F, 0.9999389088F, 0.9999411050F,
  157070. 0.9999432416F, 0.9999453196F, 0.9999473402F, 0.9999493044F,
  157071. 0.9999512132F, 0.9999530677F, 0.9999548690F, 0.9999566180F,
  157072. 0.9999583157F, 0.9999599633F, 0.9999615616F, 0.9999631116F,
  157073. 0.9999646144F, 0.9999660709F, 0.9999674820F, 0.9999688487F,
  157074. 0.9999701719F, 0.9999714526F, 0.9999726917F, 0.9999738900F,
  157075. 0.9999750486F, 0.9999761682F, 0.9999772497F, 0.9999782941F,
  157076. 0.9999793021F, 0.9999802747F, 0.9999812126F, 0.9999821167F,
  157077. 0.9999829878F, 0.9999838268F, 0.9999846343F, 0.9999854113F,
  157078. 0.9999861584F, 0.9999868765F, 0.9999875664F, 0.9999882287F,
  157079. 0.9999888642F, 0.9999894736F, 0.9999900577F, 0.9999906172F,
  157080. 0.9999911528F, 0.9999916651F, 0.9999921548F, 0.9999926227F,
  157081. 0.9999930693F, 0.9999934954F, 0.9999939015F, 0.9999942883F,
  157082. 0.9999946564F, 0.9999950064F, 0.9999953390F, 0.9999956547F,
  157083. 0.9999959541F, 0.9999962377F, 0.9999965062F, 0.9999967601F,
  157084. 0.9999969998F, 0.9999972260F, 0.9999974392F, 0.9999976399F,
  157085. 0.9999978285F, 0.9999980056F, 0.9999981716F, 0.9999983271F,
  157086. 0.9999984724F, 0.9999986081F, 0.9999987345F, 0.9999988521F,
  157087. 0.9999989613F, 0.9999990625F, 0.9999991562F, 0.9999992426F,
  157088. 0.9999993223F, 0.9999993954F, 0.9999994625F, 0.9999995239F,
  157089. 0.9999995798F, 0.9999996307F, 0.9999996768F, 0.9999997184F,
  157090. 0.9999997559F, 0.9999997895F, 0.9999998195F, 0.9999998462F,
  157091. 0.9999998698F, 0.9999998906F, 0.9999999088F, 0.9999999246F,
  157092. 0.9999999383F, 0.9999999500F, 0.9999999600F, 0.9999999684F,
  157093. 0.9999999754F, 0.9999999811F, 0.9999999858F, 0.9999999896F,
  157094. 0.9999999925F, 0.9999999948F, 0.9999999965F, 0.9999999978F,
  157095. 0.9999999986F, 0.9999999992F, 0.9999999996F, 0.9999999998F,
  157096. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  157097. };
  157098. static float vwin8192[4096] = {
  157099. 0.0000000578F, 0.0000005198F, 0.0000014438F, 0.0000028299F,
  157100. 0.0000046780F, 0.0000069882F, 0.0000097604F, 0.0000129945F,
  157101. 0.0000166908F, 0.0000208490F, 0.0000254692F, 0.0000305515F,
  157102. 0.0000360958F, 0.0000421021F, 0.0000485704F, 0.0000555006F,
  157103. 0.0000628929F, 0.0000707472F, 0.0000790635F, 0.0000878417F,
  157104. 0.0000970820F, 0.0001067842F, 0.0001169483F, 0.0001275744F,
  157105. 0.0001386625F, 0.0001502126F, 0.0001622245F, 0.0001746984F,
  157106. 0.0001876343F, 0.0002010320F, 0.0002148917F, 0.0002292132F,
  157107. 0.0002439967F, 0.0002592421F, 0.0002749493F, 0.0002911184F,
  157108. 0.0003077493F, 0.0003248421F, 0.0003423967F, 0.0003604132F,
  157109. 0.0003788915F, 0.0003978316F, 0.0004172335F, 0.0004370971F,
  157110. 0.0004574226F, 0.0004782098F, 0.0004994587F, 0.0005211694F,
  157111. 0.0005433418F, 0.0005659759F, 0.0005890717F, 0.0006126292F,
  157112. 0.0006366484F, 0.0006611292F, 0.0006860716F, 0.0007114757F,
  157113. 0.0007373414F, 0.0007636687F, 0.0007904576F, 0.0008177080F,
  157114. 0.0008454200F, 0.0008735935F, 0.0009022285F, 0.0009313250F,
  157115. 0.0009608830F, 0.0009909025F, 0.0010213834F, 0.0010523257F,
  157116. 0.0010837295F, 0.0011155946F, 0.0011479211F, 0.0011807090F,
  157117. 0.0012139582F, 0.0012476687F, 0.0012818405F, 0.0013164736F,
  157118. 0.0013515679F, 0.0013871235F, 0.0014231402F, 0.0014596182F,
  157119. 0.0014965573F, 0.0015339576F, 0.0015718190F, 0.0016101415F,
  157120. 0.0016489251F, 0.0016881698F, 0.0017278754F, 0.0017680421F,
  157121. 0.0018086698F, 0.0018497584F, 0.0018913080F, 0.0019333185F,
  157122. 0.0019757898F, 0.0020187221F, 0.0020621151F, 0.0021059690F,
  157123. 0.0021502837F, 0.0021950591F, 0.0022402953F, 0.0022859921F,
  157124. 0.0023321497F, 0.0023787679F, 0.0024258467F, 0.0024733861F,
  157125. 0.0025213861F, 0.0025698466F, 0.0026187676F, 0.0026681491F,
  157126. 0.0027179911F, 0.0027682935F, 0.0028190562F, 0.0028702794F,
  157127. 0.0029219628F, 0.0029741066F, 0.0030267107F, 0.0030797749F,
  157128. 0.0031332994F, 0.0031872841F, 0.0032417289F, 0.0032966338F,
  157129. 0.0033519988F, 0.0034078238F, 0.0034641089F, 0.0035208539F,
  157130. 0.0035780589F, 0.0036357237F, 0.0036938485F, 0.0037524331F,
  157131. 0.0038114775F, 0.0038709817F, 0.0039309456F, 0.0039913692F,
  157132. 0.0040522524F, 0.0041135953F, 0.0041753978F, 0.0042376599F,
  157133. 0.0043003814F, 0.0043635624F, 0.0044272029F, 0.0044913028F,
  157134. 0.0045558620F, 0.0046208806F, 0.0046863585F, 0.0047522955F,
  157135. 0.0048186919F, 0.0048855473F, 0.0049528619F, 0.0050206356F,
  157136. 0.0050888684F, 0.0051575601F, 0.0052267108F, 0.0052963204F,
  157137. 0.0053663890F, 0.0054369163F, 0.0055079025F, 0.0055793474F,
  157138. 0.0056512510F, 0.0057236133F, 0.0057964342F, 0.0058697137F,
  157139. 0.0059434517F, 0.0060176482F, 0.0060923032F, 0.0061674166F,
  157140. 0.0062429883F, 0.0063190183F, 0.0063955066F, 0.0064724532F,
  157141. 0.0065498579F, 0.0066277207F, 0.0067060416F, 0.0067848205F,
  157142. 0.0068640575F, 0.0069437523F, 0.0070239051F, 0.0071045157F,
  157143. 0.0071855840F, 0.0072671102F, 0.0073490940F, 0.0074315355F,
  157144. 0.0075144345F, 0.0075977911F, 0.0076816052F, 0.0077658768F,
  157145. 0.0078506057F, 0.0079357920F, 0.0080214355F, 0.0081075363F,
  157146. 0.0081940943F, 0.0082811094F, 0.0083685816F, 0.0084565108F,
  157147. 0.0085448970F, 0.0086337401F, 0.0087230401F, 0.0088127969F,
  157148. 0.0089030104F, 0.0089936807F, 0.0090848076F, 0.0091763911F,
  157149. 0.0092684311F, 0.0093609276F, 0.0094538805F, 0.0095472898F,
  157150. 0.0096411554F, 0.0097354772F, 0.0098302552F, 0.0099254894F,
  157151. 0.0100211796F, 0.0101173259F, 0.0102139281F, 0.0103109863F,
  157152. 0.0104085002F, 0.0105064700F, 0.0106048955F, 0.0107037766F,
  157153. 0.0108031133F, 0.0109029056F, 0.0110031534F, 0.0111038565F,
  157154. 0.0112050151F, 0.0113066289F, 0.0114086980F, 0.0115112222F,
  157155. 0.0116142015F, 0.0117176359F, 0.0118215252F, 0.0119258695F,
  157156. 0.0120306686F, 0.0121359225F, 0.0122416312F, 0.0123477944F,
  157157. 0.0124544123F, 0.0125614847F, 0.0126690116F, 0.0127769928F,
  157158. 0.0128854284F, 0.0129943182F, 0.0131036623F, 0.0132134604F,
  157159. 0.0133237126F, 0.0134344188F, 0.0135455790F, 0.0136571929F,
  157160. 0.0137692607F, 0.0138817821F, 0.0139947572F, 0.0141081859F,
  157161. 0.0142220681F, 0.0143364037F, 0.0144511927F, 0.0145664350F,
  157162. 0.0146821304F, 0.0147982791F, 0.0149148808F, 0.0150319355F,
  157163. 0.0151494431F, 0.0152674036F, 0.0153858168F, 0.0155046828F,
  157164. 0.0156240014F, 0.0157437726F, 0.0158639962F, 0.0159846723F,
  157165. 0.0161058007F, 0.0162273814F, 0.0163494142F, 0.0164718991F,
  157166. 0.0165948361F, 0.0167182250F, 0.0168420658F, 0.0169663584F,
  157167. 0.0170911027F, 0.0172162987F, 0.0173419462F, 0.0174680452F,
  157168. 0.0175945956F, 0.0177215974F, 0.0178490504F, 0.0179769545F,
  157169. 0.0181053098F, 0.0182341160F, 0.0183633732F, 0.0184930812F,
  157170. 0.0186232399F, 0.0187538494F, 0.0188849094F, 0.0190164200F,
  157171. 0.0191483809F, 0.0192807923F, 0.0194136539F, 0.0195469656F,
  157172. 0.0196807275F, 0.0198149394F, 0.0199496012F, 0.0200847128F,
  157173. 0.0202202742F, 0.0203562853F, 0.0204927460F, 0.0206296561F,
  157174. 0.0207670157F, 0.0209048245F, 0.0210430826F, 0.0211817899F,
  157175. 0.0213209462F, 0.0214605515F, 0.0216006057F, 0.0217411086F,
  157176. 0.0218820603F, 0.0220234605F, 0.0221653093F, 0.0223076066F,
  157177. 0.0224503521F, 0.0225935459F, 0.0227371879F, 0.0228812779F,
  157178. 0.0230258160F, 0.0231708018F, 0.0233162355F, 0.0234621169F,
  157179. 0.0236084459F, 0.0237552224F, 0.0239024462F, 0.0240501175F,
  157180. 0.0241982359F, 0.0243468015F, 0.0244958141F, 0.0246452736F,
  157181. 0.0247951800F, 0.0249455331F, 0.0250963329F, 0.0252475792F,
  157182. 0.0253992720F, 0.0255514111F, 0.0257039965F, 0.0258570281F,
  157183. 0.0260105057F, 0.0261644293F, 0.0263187987F, 0.0264736139F,
  157184. 0.0266288747F, 0.0267845811F, 0.0269407330F, 0.0270973302F,
  157185. 0.0272543727F, 0.0274118604F, 0.0275697930F, 0.0277281707F,
  157186. 0.0278869932F, 0.0280462604F, 0.0282059723F, 0.0283661287F,
  157187. 0.0285267295F, 0.0286877747F, 0.0288492641F, 0.0290111976F,
  157188. 0.0291735751F, 0.0293363965F, 0.0294996617F, 0.0296633706F,
  157189. 0.0298275231F, 0.0299921190F, 0.0301571583F, 0.0303226409F,
  157190. 0.0304885667F, 0.0306549354F, 0.0308217472F, 0.0309890017F,
  157191. 0.0311566989F, 0.0313248388F, 0.0314934211F, 0.0316624459F,
  157192. 0.0318319128F, 0.0320018220F, 0.0321721732F, 0.0323429663F,
  157193. 0.0325142013F, 0.0326858779F, 0.0328579962F, 0.0330305559F,
  157194. 0.0332035570F, 0.0333769994F, 0.0335508829F, 0.0337252074F,
  157195. 0.0338999728F, 0.0340751790F, 0.0342508259F, 0.0344269134F,
  157196. 0.0346034412F, 0.0347804094F, 0.0349578178F, 0.0351356663F,
  157197. 0.0353139548F, 0.0354926831F, 0.0356718511F, 0.0358514588F,
  157198. 0.0360315059F, 0.0362119924F, 0.0363929182F, 0.0365742831F,
  157199. 0.0367560870F, 0.0369383297F, 0.0371210113F, 0.0373041315F,
  157200. 0.0374876902F, 0.0376716873F, 0.0378561226F, 0.0380409961F,
  157201. 0.0382263077F, 0.0384120571F, 0.0385982443F, 0.0387848691F,
  157202. 0.0389719315F, 0.0391594313F, 0.0393473683F, 0.0395357425F,
  157203. 0.0397245537F, 0.0399138017F, 0.0401034866F, 0.0402936080F,
  157204. 0.0404841660F, 0.0406751603F, 0.0408665909F, 0.0410584576F,
  157205. 0.0412507603F, 0.0414434988F, 0.0416366731F, 0.0418302829F,
  157206. 0.0420243282F, 0.0422188088F, 0.0424137246F, 0.0426090755F,
  157207. 0.0428048613F, 0.0430010819F, 0.0431977371F, 0.0433948269F,
  157208. 0.0435923511F, 0.0437903095F, 0.0439887020F, 0.0441875285F,
  157209. 0.0443867889F, 0.0445864830F, 0.0447866106F, 0.0449871717F,
  157210. 0.0451881661F, 0.0453895936F, 0.0455914542F, 0.0457937477F,
  157211. 0.0459964738F, 0.0461996326F, 0.0464032239F, 0.0466072475F,
  157212. 0.0468117032F, 0.0470165910F, 0.0472219107F, 0.0474276622F,
  157213. 0.0476338452F, 0.0478404597F, 0.0480475056F, 0.0482549827F,
  157214. 0.0484628907F, 0.0486712297F, 0.0488799994F, 0.0490891998F,
  157215. 0.0492988306F, 0.0495088917F, 0.0497193830F, 0.0499303043F,
  157216. 0.0501416554F, 0.0503534363F, 0.0505656468F, 0.0507782867F,
  157217. 0.0509913559F, 0.0512048542F, 0.0514187815F, 0.0516331376F,
  157218. 0.0518479225F, 0.0520631358F, 0.0522787775F, 0.0524948475F,
  157219. 0.0527113455F, 0.0529282715F, 0.0531456252F, 0.0533634066F,
  157220. 0.0535816154F, 0.0538002515F, 0.0540193148F, 0.0542388051F,
  157221. 0.0544587222F, 0.0546790660F, 0.0548998364F, 0.0551210331F,
  157222. 0.0553426561F, 0.0555647051F, 0.0557871801F, 0.0560100807F,
  157223. 0.0562334070F, 0.0564571587F, 0.0566813357F, 0.0569059378F,
  157224. 0.0571309649F, 0.0573564168F, 0.0575822933F, 0.0578085942F,
  157225. 0.0580353195F, 0.0582624689F, 0.0584900423F, 0.0587180396F,
  157226. 0.0589464605F, 0.0591753049F, 0.0594045726F, 0.0596342635F,
  157227. 0.0598643774F, 0.0600949141F, 0.0603258735F, 0.0605572555F,
  157228. 0.0607890597F, 0.0610212862F, 0.0612539346F, 0.0614870049F,
  157229. 0.0617204968F, 0.0619544103F, 0.0621887451F, 0.0624235010F,
  157230. 0.0626586780F, 0.0628942758F, 0.0631302942F, 0.0633667331F,
  157231. 0.0636035923F, 0.0638408717F, 0.0640785710F, 0.0643166901F,
  157232. 0.0645552288F, 0.0647941870F, 0.0650335645F, 0.0652733610F,
  157233. 0.0655135765F, 0.0657542108F, 0.0659952636F, 0.0662367348F,
  157234. 0.0664786242F, 0.0667209316F, 0.0669636570F, 0.0672068000F,
  157235. 0.0674503605F, 0.0676943384F, 0.0679387334F, 0.0681835454F,
  157236. 0.0684287742F, 0.0686744196F, 0.0689204814F, 0.0691669595F,
  157237. 0.0694138536F, 0.0696611637F, 0.0699088894F, 0.0701570307F,
  157238. 0.0704055873F, 0.0706545590F, 0.0709039458F, 0.0711537473F,
  157239. 0.0714039634F, 0.0716545939F, 0.0719056387F, 0.0721570975F,
  157240. 0.0724089702F, 0.0726612565F, 0.0729139563F, 0.0731670694F,
  157241. 0.0734205956F, 0.0736745347F, 0.0739288866F, 0.0741836510F,
  157242. 0.0744388277F, 0.0746944166F, 0.0749504175F, 0.0752068301F,
  157243. 0.0754636543F, 0.0757208899F, 0.0759785367F, 0.0762365946F,
  157244. 0.0764950632F, 0.0767539424F, 0.0770132320F, 0.0772729319F,
  157245. 0.0775330418F, 0.0777935616F, 0.0780544909F, 0.0783158298F,
  157246. 0.0785775778F, 0.0788397349F, 0.0791023009F, 0.0793652755F,
  157247. 0.0796286585F, 0.0798924498F, 0.0801566492F, 0.0804212564F,
  157248. 0.0806862712F, 0.0809516935F, 0.0812175231F, 0.0814837597F,
  157249. 0.0817504031F, 0.0820174532F, 0.0822849097F, 0.0825527724F,
  157250. 0.0828210412F, 0.0830897158F, 0.0833587960F, 0.0836282816F,
  157251. 0.0838981724F, 0.0841684682F, 0.0844391688F, 0.0847102740F,
  157252. 0.0849817835F, 0.0852536973F, 0.0855260150F, 0.0857987364F,
  157253. 0.0860718614F, 0.0863453897F, 0.0866193211F, 0.0868936554F,
  157254. 0.0871683924F, 0.0874435319F, 0.0877190737F, 0.0879950175F,
  157255. 0.0882713632F, 0.0885481105F, 0.0888252592F, 0.0891028091F,
  157256. 0.0893807600F, 0.0896591117F, 0.0899378639F, 0.0902170165F,
  157257. 0.0904965692F, 0.0907765218F, 0.0910568740F, 0.0913376258F,
  157258. 0.0916187767F, 0.0919003268F, 0.0921822756F, 0.0924646230F,
  157259. 0.0927473687F, 0.0930305126F, 0.0933140545F, 0.0935979940F,
  157260. 0.0938823310F, 0.0941670653F, 0.0944521966F, 0.0947377247F,
  157261. 0.0950236494F, 0.0953099704F, 0.0955966876F, 0.0958838007F,
  157262. 0.0961713094F, 0.0964592136F, 0.0967475131F, 0.0970362075F,
  157263. 0.0973252967F, 0.0976147805F, 0.0979046585F, 0.0981949307F,
  157264. 0.0984855967F, 0.0987766563F, 0.0990681093F, 0.0993599555F,
  157265. 0.0996521945F, 0.0999448263F, 0.1002378506F, 0.1005312671F,
  157266. 0.1008250755F, 0.1011192757F, 0.1014138675F, 0.1017088505F,
  157267. 0.1020042246F, 0.1022999895F, 0.1025961450F, 0.1028926909F,
  157268. 0.1031896268F, 0.1034869526F, 0.1037846680F, 0.1040827729F,
  157269. 0.1043812668F, 0.1046801497F, 0.1049794213F, 0.1052790813F,
  157270. 0.1055791294F, 0.1058795656F, 0.1061803894F, 0.1064816006F,
  157271. 0.1067831991F, 0.1070851846F, 0.1073875568F, 0.1076903155F,
  157272. 0.1079934604F, 0.1082969913F, 0.1086009079F, 0.1089052101F,
  157273. 0.1092098975F, 0.1095149699F, 0.1098204270F, 0.1101262687F,
  157274. 0.1104324946F, 0.1107391045F, 0.1110460982F, 0.1113534754F,
  157275. 0.1116612359F, 0.1119693793F, 0.1122779055F, 0.1125868142F,
  157276. 0.1128961052F, 0.1132057781F, 0.1135158328F, 0.1138262690F,
  157277. 0.1141370863F, 0.1144482847F, 0.1147598638F, 0.1150718233F,
  157278. 0.1153841631F, 0.1156968828F, 0.1160099822F, 0.1163234610F,
  157279. 0.1166373190F, 0.1169515559F, 0.1172661714F, 0.1175811654F,
  157280. 0.1178965374F, 0.1182122874F, 0.1185284149F, 0.1188449198F,
  157281. 0.1191618018F, 0.1194790606F, 0.1197966960F, 0.1201147076F,
  157282. 0.1204330953F, 0.1207518587F, 0.1210709976F, 0.1213905118F,
  157283. 0.1217104009F, 0.1220306647F, 0.1223513029F, 0.1226723153F,
  157284. 0.1229937016F, 0.1233154615F, 0.1236375948F, 0.1239601011F,
  157285. 0.1242829803F, 0.1246062319F, 0.1249298559F, 0.1252538518F,
  157286. 0.1255782195F, 0.1259029586F, 0.1262280689F, 0.1265535501F,
  157287. 0.1268794019F, 0.1272056241F, 0.1275322163F, 0.1278591784F,
  157288. 0.1281865099F, 0.1285142108F, 0.1288422805F, 0.1291707190F,
  157289. 0.1294995259F, 0.1298287009F, 0.1301582437F, 0.1304881542F,
  157290. 0.1308184319F, 0.1311490766F, 0.1314800881F, 0.1318114660F,
  157291. 0.1321432100F, 0.1324753200F, 0.1328077955F, 0.1331406364F,
  157292. 0.1334738422F, 0.1338074129F, 0.1341413479F, 0.1344756472F,
  157293. 0.1348103103F, 0.1351453370F, 0.1354807270F, 0.1358164801F,
  157294. 0.1361525959F, 0.1364890741F, 0.1368259145F, 0.1371631167F,
  157295. 0.1375006805F, 0.1378386056F, 0.1381768917F, 0.1385155384F,
  157296. 0.1388545456F, 0.1391939129F, 0.1395336400F, 0.1398737266F,
  157297. 0.1402141724F, 0.1405549772F, 0.1408961406F, 0.1412376623F,
  157298. 0.1415795421F, 0.1419217797F, 0.1422643746F, 0.1426073268F,
  157299. 0.1429506358F, 0.1432943013F, 0.1436383231F, 0.1439827008F,
  157300. 0.1443274342F, 0.1446725229F, 0.1450179667F, 0.1453637652F,
  157301. 0.1457099181F, 0.1460564252F, 0.1464032861F, 0.1467505006F,
  157302. 0.1470980682F, 0.1474459888F, 0.1477942620F, 0.1481428875F,
  157303. 0.1484918651F, 0.1488411942F, 0.1491908748F, 0.1495409065F,
  157304. 0.1498912889F, 0.1502420218F, 0.1505931048F, 0.1509445376F,
  157305. 0.1512963200F, 0.1516484516F, 0.1520009321F, 0.1523537612F,
  157306. 0.1527069385F, 0.1530604638F, 0.1534143368F, 0.1537685571F,
  157307. 0.1541231244F, 0.1544780384F, 0.1548332987F, 0.1551889052F,
  157308. 0.1555448574F, 0.1559011550F, 0.1562577978F, 0.1566147853F,
  157309. 0.1569721173F, 0.1573297935F, 0.1576878135F, 0.1580461771F,
  157310. 0.1584048838F, 0.1587639334F, 0.1591233255F, 0.1594830599F,
  157311. 0.1598431361F, 0.1602035540F, 0.1605643131F, 0.1609254131F,
  157312. 0.1612868537F, 0.1616486346F, 0.1620107555F, 0.1623732160F,
  157313. 0.1627360158F, 0.1630991545F, 0.1634626319F, 0.1638264476F,
  157314. 0.1641906013F, 0.1645550926F, 0.1649199212F, 0.1652850869F,
  157315. 0.1656505892F, 0.1660164278F, 0.1663826024F, 0.1667491127F,
  157316. 0.1671159583F, 0.1674831388F, 0.1678506541F, 0.1682185036F,
  157317. 0.1685866872F, 0.1689552044F, 0.1693240549F, 0.1696932384F,
  157318. 0.1700627545F, 0.1704326029F, 0.1708027833F, 0.1711732952F,
  157319. 0.1715441385F, 0.1719153127F, 0.1722868175F, 0.1726586526F,
  157320. 0.1730308176F, 0.1734033121F, 0.1737761359F, 0.1741492886F,
  157321. 0.1745227698F, 0.1748965792F, 0.1752707164F, 0.1756451812F,
  157322. 0.1760199731F, 0.1763950918F, 0.1767705370F, 0.1771463083F,
  157323. 0.1775224054F, 0.1778988279F, 0.1782755754F, 0.1786526477F,
  157324. 0.1790300444F, 0.1794077651F, 0.1797858094F, 0.1801641771F,
  157325. 0.1805428677F, 0.1809218810F, 0.1813012165F, 0.1816808739F,
  157326. 0.1820608528F, 0.1824411530F, 0.1828217739F, 0.1832027154F,
  157327. 0.1835839770F, 0.1839655584F, 0.1843474592F, 0.1847296790F,
  157328. 0.1851122175F, 0.1854950744F, 0.1858782492F, 0.1862617417F,
  157329. 0.1866455514F, 0.1870296780F, 0.1874141211F, 0.1877988804F,
  157330. 0.1881839555F, 0.1885693461F, 0.1889550517F, 0.1893410721F,
  157331. 0.1897274068F, 0.1901140555F, 0.1905010178F, 0.1908882933F,
  157332. 0.1912758818F, 0.1916637828F, 0.1920519959F, 0.1924405208F,
  157333. 0.1928293571F, 0.1932185044F, 0.1936079625F, 0.1939977308F,
  157334. 0.1943878091F, 0.1947781969F, 0.1951688939F, 0.1955598998F,
  157335. 0.1959512141F, 0.1963428364F, 0.1967347665F, 0.1971270038F,
  157336. 0.1975195482F, 0.1979123990F, 0.1983055561F, 0.1986990190F,
  157337. 0.1990927873F, 0.1994868607F, 0.1998812388F, 0.2002759212F,
  157338. 0.2006709075F, 0.2010661974F, 0.2014617904F, 0.2018576862F,
  157339. 0.2022538844F, 0.2026503847F, 0.2030471865F, 0.2034442897F,
  157340. 0.2038416937F, 0.2042393982F, 0.2046374028F, 0.2050357071F,
  157341. 0.2054343107F, 0.2058332133F, 0.2062324145F, 0.2066319138F,
  157342. 0.2070317110F, 0.2074318055F, 0.2078321970F, 0.2082328852F,
  157343. 0.2086338696F, 0.2090351498F, 0.2094367255F, 0.2098385962F,
  157344. 0.2102407617F, 0.2106432213F, 0.2110459749F, 0.2114490220F,
  157345. 0.2118523621F, 0.2122559950F, 0.2126599202F, 0.2130641373F,
  157346. 0.2134686459F, 0.2138734456F, 0.2142785361F, 0.2146839168F,
  157347. 0.2150895875F, 0.2154955478F, 0.2159017972F, 0.2163083353F,
  157348. 0.2167151617F, 0.2171222761F, 0.2175296780F, 0.2179373670F,
  157349. 0.2183453428F, 0.2187536049F, 0.2191621529F, 0.2195709864F,
  157350. 0.2199801051F, 0.2203895085F, 0.2207991961F, 0.2212091677F,
  157351. 0.2216194228F, 0.2220299610F, 0.2224407818F, 0.2228518850F,
  157352. 0.2232632699F, 0.2236749364F, 0.2240868839F, 0.2244991121F,
  157353. 0.2249116204F, 0.2253244086F, 0.2257374763F, 0.2261508229F,
  157354. 0.2265644481F, 0.2269783514F, 0.2273925326F, 0.2278069911F,
  157355. 0.2282217265F, 0.2286367384F, 0.2290520265F, 0.2294675902F,
  157356. 0.2298834292F, 0.2302995431F, 0.2307159314F, 0.2311325937F,
  157357. 0.2315495297F, 0.2319667388F, 0.2323842207F, 0.2328019749F,
  157358. 0.2332200011F, 0.2336382988F, 0.2340568675F, 0.2344757070F,
  157359. 0.2348948166F, 0.2353141961F, 0.2357338450F, 0.2361537629F,
  157360. 0.2365739493F, 0.2369944038F, 0.2374151261F, 0.2378361156F,
  157361. 0.2382573720F, 0.2386788948F, 0.2391006836F, 0.2395227380F,
  157362. 0.2399450575F, 0.2403676417F, 0.2407904902F, 0.2412136026F,
  157363. 0.2416369783F, 0.2420606171F, 0.2424845185F, 0.2429086820F,
  157364. 0.2433331072F, 0.2437577936F, 0.2441827409F, 0.2446079486F,
  157365. 0.2450334163F, 0.2454591435F, 0.2458851298F, 0.2463113747F,
  157366. 0.2467378779F, 0.2471646389F, 0.2475916573F, 0.2480189325F,
  157367. 0.2484464643F, 0.2488742521F, 0.2493022955F, 0.2497305940F,
  157368. 0.2501591473F, 0.2505879549F, 0.2510170163F, 0.2514463311F,
  157369. 0.2518758989F, 0.2523057193F, 0.2527357916F, 0.2531661157F,
  157370. 0.2535966909F, 0.2540275169F, 0.2544585931F, 0.2548899193F,
  157371. 0.2553214948F, 0.2557533193F, 0.2561853924F, 0.2566177135F,
  157372. 0.2570502822F, 0.2574830981F, 0.2579161608F, 0.2583494697F,
  157373. 0.2587830245F, 0.2592168246F, 0.2596508697F, 0.2600851593F,
  157374. 0.2605196929F, 0.2609544701F, 0.2613894904F, 0.2618247534F,
  157375. 0.2622602586F, 0.2626960055F, 0.2631319938F, 0.2635682230F,
  157376. 0.2640046925F, 0.2644414021F, 0.2648783511F, 0.2653155391F,
  157377. 0.2657529657F, 0.2661906305F, 0.2666285329F, 0.2670666725F,
  157378. 0.2675050489F, 0.2679436616F, 0.2683825101F, 0.2688215940F,
  157379. 0.2692609127F, 0.2697004660F, 0.2701402532F, 0.2705802739F,
  157380. 0.2710205278F, 0.2714610142F, 0.2719017327F, 0.2723426830F,
  157381. 0.2727838644F, 0.2732252766F, 0.2736669191F, 0.2741087914F,
  157382. 0.2745508930F, 0.2749932235F, 0.2754357824F, 0.2758785693F,
  157383. 0.2763215837F, 0.2767648251F, 0.2772082930F, 0.2776519870F,
  157384. 0.2780959066F, 0.2785400513F, 0.2789844207F, 0.2794290143F,
  157385. 0.2798738316F, 0.2803188722F, 0.2807641355F, 0.2812096211F,
  157386. 0.2816553286F, 0.2821012574F, 0.2825474071F, 0.2829937773F,
  157387. 0.2834403673F, 0.2838871768F, 0.2843342053F, 0.2847814523F,
  157388. 0.2852289174F, 0.2856765999F, 0.2861244996F, 0.2865726159F,
  157389. 0.2870209482F, 0.2874694962F, 0.2879182594F, 0.2883672372F,
  157390. 0.2888164293F, 0.2892658350F, 0.2897154540F, 0.2901652858F,
  157391. 0.2906153298F, 0.2910655856F, 0.2915160527F, 0.2919667306F,
  157392. 0.2924176189F, 0.2928687171F, 0.2933200246F, 0.2937715409F,
  157393. 0.2942232657F, 0.2946751984F, 0.2951273386F, 0.2955796856F,
  157394. 0.2960322391F, 0.2964849986F, 0.2969379636F, 0.2973911335F,
  157395. 0.2978445080F, 0.2982980864F, 0.2987518684F, 0.2992058534F,
  157396. 0.2996600409F, 0.3001144305F, 0.3005690217F, 0.3010238139F,
  157397. 0.3014788067F, 0.3019339995F, 0.3023893920F, 0.3028449835F,
  157398. 0.3033007736F, 0.3037567618F, 0.3042129477F, 0.3046693306F,
  157399. 0.3051259102F, 0.3055826859F, 0.3060396572F, 0.3064968236F,
  157400. 0.3069541847F, 0.3074117399F, 0.3078694887F, 0.3083274307F,
  157401. 0.3087855653F, 0.3092438920F, 0.3097024104F, 0.3101611199F,
  157402. 0.3106200200F, 0.3110791103F, 0.3115383902F, 0.3119978592F,
  157403. 0.3124575169F, 0.3129173627F, 0.3133773961F, 0.3138376166F,
  157404. 0.3142980238F, 0.3147586170F, 0.3152193959F, 0.3156803598F,
  157405. 0.3161415084F, 0.3166028410F, 0.3170643573F, 0.3175260566F,
  157406. 0.3179879384F, 0.3184500023F, 0.3189122478F, 0.3193746743F,
  157407. 0.3198372814F, 0.3203000685F, 0.3207630351F, 0.3212261807F,
  157408. 0.3216895048F, 0.3221530069F, 0.3226166865F, 0.3230805430F,
  157409. 0.3235445760F, 0.3240087849F, 0.3244731693F, 0.3249377285F,
  157410. 0.3254024622F, 0.3258673698F, 0.3263324507F, 0.3267977045F,
  157411. 0.3272631306F, 0.3277287286F, 0.3281944978F, 0.3286604379F,
  157412. 0.3291265482F, 0.3295928284F, 0.3300592777F, 0.3305258958F,
  157413. 0.3309926821F, 0.3314596361F, 0.3319267573F, 0.3323940451F,
  157414. 0.3328614990F, 0.3333291186F, 0.3337969033F, 0.3342648525F,
  157415. 0.3347329658F, 0.3352012427F, 0.3356696825F, 0.3361382849F,
  157416. 0.3366070492F, 0.3370759749F, 0.3375450616F, 0.3380143087F,
  157417. 0.3384837156F, 0.3389532819F, 0.3394230071F, 0.3398928905F,
  157418. 0.3403629317F, 0.3408331302F, 0.3413034854F, 0.3417739967F,
  157419. 0.3422446638F, 0.3427154860F, 0.3431864628F, 0.3436575938F,
  157420. 0.3441288782F, 0.3446003158F, 0.3450719058F, 0.3455436478F,
  157421. 0.3460155412F, 0.3464875856F, 0.3469597804F, 0.3474321250F,
  157422. 0.3479046189F, 0.3483772617F, 0.3488500527F, 0.3493229914F,
  157423. 0.3497960774F, 0.3502693100F, 0.3507426887F, 0.3512162131F,
  157424. 0.3516898825F, 0.3521636965F, 0.3526376545F, 0.3531117559F,
  157425. 0.3535860003F, 0.3540603870F, 0.3545349157F, 0.3550095856F,
  157426. 0.3554843964F, 0.3559593474F, 0.3564344381F, 0.3569096680F,
  157427. 0.3573850366F, 0.3578605432F, 0.3583361875F, 0.3588119687F,
  157428. 0.3592878865F, 0.3597639402F, 0.3602401293F, 0.3607164533F,
  157429. 0.3611929117F, 0.3616695038F, 0.3621462292F, 0.3626230873F,
  157430. 0.3631000776F, 0.3635771995F, 0.3640544525F, 0.3645318360F,
  157431. 0.3650093496F, 0.3654869926F, 0.3659647645F, 0.3664426648F,
  157432. 0.3669206930F, 0.3673988484F, 0.3678771306F, 0.3683555390F,
  157433. 0.3688340731F, 0.3693127322F, 0.3697915160F, 0.3702704237F,
  157434. 0.3707494549F, 0.3712286091F, 0.3717078857F, 0.3721872840F,
  157435. 0.3726668037F, 0.3731464441F, 0.3736262047F, 0.3741060850F,
  157436. 0.3745860843F, 0.3750662023F, 0.3755464382F, 0.3760267915F,
  157437. 0.3765072618F, 0.3769878484F, 0.3774685509F, 0.3779493686F,
  157438. 0.3784303010F, 0.3789113475F, 0.3793925076F, 0.3798737809F,
  157439. 0.3803551666F, 0.3808366642F, 0.3813182733F, 0.3817999932F,
  157440. 0.3822818234F, 0.3827637633F, 0.3832458124F, 0.3837279702F,
  157441. 0.3842102360F, 0.3846926093F, 0.3851750897F, 0.3856576764F,
  157442. 0.3861403690F, 0.3866231670F, 0.3871060696F, 0.3875890765F,
  157443. 0.3880721870F, 0.3885554007F, 0.3890387168F, 0.3895221349F,
  157444. 0.3900056544F, 0.3904892748F, 0.3909729955F, 0.3914568160F,
  157445. 0.3919407356F, 0.3924247539F, 0.3929088702F, 0.3933930841F,
  157446. 0.3938773949F, 0.3943618021F, 0.3948463052F, 0.3953309035F,
  157447. 0.3958155966F, 0.3963003838F, 0.3967852646F, 0.3972702385F,
  157448. 0.3977553048F, 0.3982404631F, 0.3987257127F, 0.3992110531F,
  157449. 0.3996964838F, 0.4001820041F, 0.4006676136F, 0.4011533116F,
  157450. 0.4016390976F, 0.4021249710F, 0.4026109313F, 0.4030969779F,
  157451. 0.4035831102F, 0.4040693277F, 0.4045556299F, 0.4050420160F,
  157452. 0.4055284857F, 0.4060150383F, 0.4065016732F, 0.4069883899F,
  157453. 0.4074751879F, 0.4079620665F, 0.4084490252F, 0.4089360635F,
  157454. 0.4094231807F, 0.4099103763F, 0.4103976498F, 0.4108850005F,
  157455. 0.4113724280F, 0.4118599315F, 0.4123475107F, 0.4128351648F,
  157456. 0.4133228934F, 0.4138106959F, 0.4142985716F, 0.4147865201F,
  157457. 0.4152745408F, 0.4157626330F, 0.4162507963F, 0.4167390301F,
  157458. 0.4172273337F, 0.4177157067F, 0.4182041484F, 0.4186926583F,
  157459. 0.4191812359F, 0.4196698805F, 0.4201585915F, 0.4206473685F,
  157460. 0.4211362108F, 0.4216251179F, 0.4221140892F, 0.4226031241F,
  157461. 0.4230922221F, 0.4235813826F, 0.4240706050F, 0.4245598887F,
  157462. 0.4250492332F, 0.4255386379F, 0.4260281022F, 0.4265176256F,
  157463. 0.4270072075F, 0.4274968473F, 0.4279865445F, 0.4284762984F,
  157464. 0.4289661086F, 0.4294559743F, 0.4299458951F, 0.4304358704F,
  157465. 0.4309258996F, 0.4314159822F, 0.4319061175F, 0.4323963050F,
  157466. 0.4328865441F, 0.4333768342F, 0.4338671749F, 0.4343575654F,
  157467. 0.4348480052F, 0.4353384938F, 0.4358290306F, 0.4363196149F,
  157468. 0.4368102463F, 0.4373009241F, 0.4377916478F, 0.4382824168F,
  157469. 0.4387732305F, 0.4392640884F, 0.4397549899F, 0.4402459343F,
  157470. 0.4407369212F, 0.4412279499F, 0.4417190198F, 0.4422101305F,
  157471. 0.4427012813F, 0.4431924717F, 0.4436837010F, 0.4441749686F,
  157472. 0.4446662742F, 0.4451576169F, 0.4456489963F, 0.4461404118F,
  157473. 0.4466318628F, 0.4471233487F, 0.4476148690F, 0.4481064230F,
  157474. 0.4485980103F, 0.4490896302F, 0.4495812821F, 0.4500729654F,
  157475. 0.4505646797F, 0.4510564243F, 0.4515481986F, 0.4520400021F,
  157476. 0.4525318341F, 0.4530236942F, 0.4535155816F, 0.4540074959F,
  157477. 0.4544994365F, 0.4549914028F, 0.4554833941F, 0.4559754100F,
  157478. 0.4564674499F, 0.4569595131F, 0.4574515991F, 0.4579437074F,
  157479. 0.4584358372F, 0.4589279881F, 0.4594201595F, 0.4599123508F,
  157480. 0.4604045615F, 0.4608967908F, 0.4613890383F, 0.4618813034F,
  157481. 0.4623735855F, 0.4628658841F, 0.4633581984F, 0.4638505281F,
  157482. 0.4643428724F, 0.4648352308F, 0.4653276028F, 0.4658199877F,
  157483. 0.4663123849F, 0.4668047940F, 0.4672972143F, 0.4677896451F,
  157484. 0.4682820861F, 0.4687745365F, 0.4692669958F, 0.4697594634F,
  157485. 0.4702519387F, 0.4707444211F, 0.4712369102F, 0.4717294052F,
  157486. 0.4722219056F, 0.4727144109F, 0.4732069204F, 0.4736994336F,
  157487. 0.4741919498F, 0.4746844686F, 0.4751769893F, 0.4756695113F,
  157488. 0.4761620341F, 0.4766545571F, 0.4771470797F, 0.4776396013F,
  157489. 0.4781321213F, 0.4786246392F, 0.4791171544F, 0.4796096663F,
  157490. 0.4801021744F, 0.4805946779F, 0.4810871765F, 0.4815796694F,
  157491. 0.4820721561F, 0.4825646360F, 0.4830571086F, 0.4835495732F,
  157492. 0.4840420293F, 0.4845344763F, 0.4850269136F, 0.4855193407F,
  157493. 0.4860117569F, 0.4865041617F, 0.4869965545F, 0.4874889347F,
  157494. 0.4879813018F, 0.4884736551F, 0.4889659941F, 0.4894583182F,
  157495. 0.4899506268F, 0.4904429193F, 0.4909351952F, 0.4914274538F,
  157496. 0.4919196947F, 0.4924119172F, 0.4929041207F, 0.4933963046F,
  157497. 0.4938884685F, 0.4943806116F, 0.4948727335F, 0.4953648335F,
  157498. 0.4958569110F, 0.4963489656F, 0.4968409965F, 0.4973330032F,
  157499. 0.4978249852F, 0.4983169419F, 0.4988088726F, 0.4993007768F,
  157500. 0.4997926539F, 0.5002845034F, 0.5007763247F, 0.5012681171F,
  157501. 0.5017598801F, 0.5022516132F, 0.5027433157F, 0.5032349871F,
  157502. 0.5037266268F, 0.5042182341F, 0.5047098086F, 0.5052013497F,
  157503. 0.5056928567F, 0.5061843292F, 0.5066757664F, 0.5071671679F,
  157504. 0.5076585330F, 0.5081498613F, 0.5086411520F, 0.5091324047F,
  157505. 0.5096236187F, 0.5101147934F, 0.5106059284F, 0.5110970230F,
  157506. 0.5115880766F, 0.5120790887F, 0.5125700587F, 0.5130609860F,
  157507. 0.5135518700F, 0.5140427102F, 0.5145335059F, 0.5150242566F,
  157508. 0.5155149618F, 0.5160056208F, 0.5164962331F, 0.5169867980F,
  157509. 0.5174773151F, 0.5179677837F, 0.5184582033F, 0.5189485733F,
  157510. 0.5194388931F, 0.5199291621F, 0.5204193798F, 0.5209095455F,
  157511. 0.5213996588F, 0.5218897190F, 0.5223797256F, 0.5228696779F,
  157512. 0.5233595755F, 0.5238494177F, 0.5243392039F, 0.5248289337F,
  157513. 0.5253186063F, 0.5258082213F, 0.5262977781F, 0.5267872760F,
  157514. 0.5272767146F, 0.5277660932F, 0.5282554112F, 0.5287446682F,
  157515. 0.5292338635F, 0.5297229965F, 0.5302120667F, 0.5307010736F,
  157516. 0.5311900164F, 0.5316788947F, 0.5321677079F, 0.5326564554F,
  157517. 0.5331451366F, 0.5336337511F, 0.5341222981F, 0.5346107771F,
  157518. 0.5350991876F, 0.5355875290F, 0.5360758007F, 0.5365640021F,
  157519. 0.5370521327F, 0.5375401920F, 0.5380281792F, 0.5385160939F,
  157520. 0.5390039355F, 0.5394917034F, 0.5399793971F, 0.5404670159F,
  157521. 0.5409545594F, 0.5414420269F, 0.5419294179F, 0.5424167318F,
  157522. 0.5429039680F, 0.5433911261F, 0.5438782053F, 0.5443652051F,
  157523. 0.5448521250F, 0.5453389644F, 0.5458257228F, 0.5463123995F,
  157524. 0.5467989940F, 0.5472855057F, 0.5477719341F, 0.5482582786F,
  157525. 0.5487445387F, 0.5492307137F, 0.5497168031F, 0.5502028063F,
  157526. 0.5506887228F, 0.5511745520F, 0.5516602934F, 0.5521459463F,
  157527. 0.5526315103F, 0.5531169847F, 0.5536023690F, 0.5540876626F,
  157528. 0.5545728649F, 0.5550579755F, 0.5555429937F, 0.5560279189F,
  157529. 0.5565127507F, 0.5569974884F, 0.5574821315F, 0.5579666794F,
  157530. 0.5584511316F, 0.5589354875F, 0.5594197465F, 0.5599039080F,
  157531. 0.5603879716F, 0.5608719367F, 0.5613558026F, 0.5618395689F,
  157532. 0.5623232350F, 0.5628068002F, 0.5632902642F, 0.5637736262F,
  157533. 0.5642568858F, 0.5647400423F, 0.5652230953F, 0.5657060442F,
  157534. 0.5661888883F, 0.5666716272F, 0.5671542603F, 0.5676367870F,
  157535. 0.5681192069F, 0.5686015192F, 0.5690837235F, 0.5695658192F,
  157536. 0.5700478058F, 0.5705296827F, 0.5710114494F, 0.5714931052F,
  157537. 0.5719746497F, 0.5724560822F, 0.5729374023F, 0.5734186094F,
  157538. 0.5738997029F, 0.5743806823F, 0.5748615470F, 0.5753422965F,
  157539. 0.5758229301F, 0.5763034475F, 0.5767838480F, 0.5772641310F,
  157540. 0.5777442960F, 0.5782243426F, 0.5787042700F, 0.5791840778F,
  157541. 0.5796637654F, 0.5801433322F, 0.5806227778F, 0.5811021016F,
  157542. 0.5815813029F, 0.5820603814F, 0.5825393363F, 0.5830181673F,
  157543. 0.5834968737F, 0.5839754549F, 0.5844539105F, 0.5849322399F,
  157544. 0.5854104425F, 0.5858885179F, 0.5863664653F, 0.5868442844F,
  157545. 0.5873219746F, 0.5877995353F, 0.5882769660F, 0.5887542661F,
  157546. 0.5892314351F, 0.5897084724F, 0.5901853776F, 0.5906621500F,
  157547. 0.5911387892F, 0.5916152945F, 0.5920916655F, 0.5925679016F,
  157548. 0.5930440022F, 0.5935199669F, 0.5939957950F, 0.5944714861F,
  157549. 0.5949470396F, 0.5954224550F, 0.5958977317F, 0.5963728692F,
  157550. 0.5968478669F, 0.5973227244F, 0.5977974411F, 0.5982720163F,
  157551. 0.5987464497F, 0.5992207407F, 0.5996948887F, 0.6001688932F,
  157552. 0.6006427537F, 0.6011164696F, 0.6015900405F, 0.6020634657F,
  157553. 0.6025367447F, 0.6030098770F, 0.6034828621F, 0.6039556995F,
  157554. 0.6044283885F, 0.6049009288F, 0.6053733196F, 0.6058455606F,
  157555. 0.6063176512F, 0.6067895909F, 0.6072613790F, 0.6077330152F,
  157556. 0.6082044989F, 0.6086758295F, 0.6091470065F, 0.6096180294F,
  157557. 0.6100888977F, 0.6105596108F, 0.6110301682F, 0.6115005694F,
  157558. 0.6119708139F, 0.6124409011F, 0.6129108305F, 0.6133806017F,
  157559. 0.6138502139F, 0.6143196669F, 0.6147889599F, 0.6152580926F,
  157560. 0.6157270643F, 0.6161958746F, 0.6166645230F, 0.6171330088F,
  157561. 0.6176013317F, 0.6180694910F, 0.6185374863F, 0.6190053171F,
  157562. 0.6194729827F, 0.6199404828F, 0.6204078167F, 0.6208749841F,
  157563. 0.6213419842F, 0.6218088168F, 0.6222754811F, 0.6227419768F,
  157564. 0.6232083032F, 0.6236744600F, 0.6241404465F, 0.6246062622F,
  157565. 0.6250719067F, 0.6255373795F, 0.6260026799F, 0.6264678076F,
  157566. 0.6269327619F, 0.6273975425F, 0.6278621487F, 0.6283265800F,
  157567. 0.6287908361F, 0.6292549163F, 0.6297188201F, 0.6301825471F,
  157568. 0.6306460966F, 0.6311094683F, 0.6315726617F, 0.6320356761F,
  157569. 0.6324985111F, 0.6329611662F, 0.6334236410F, 0.6338859348F,
  157570. 0.6343480472F, 0.6348099777F, 0.6352717257F, 0.6357332909F,
  157571. 0.6361946726F, 0.6366558704F, 0.6371168837F, 0.6375777122F,
  157572. 0.6380383552F, 0.6384988123F, 0.6389590830F, 0.6394191668F,
  157573. 0.6398790631F, 0.6403387716F, 0.6407982916F, 0.6412576228F,
  157574. 0.6417167645F, 0.6421757163F, 0.6426344778F, 0.6430930483F,
  157575. 0.6435514275F, 0.6440096149F, 0.6444676098F, 0.6449254119F,
  157576. 0.6453830207F, 0.6458404356F, 0.6462976562F, 0.6467546820F,
  157577. 0.6472115125F, 0.6476681472F, 0.6481245856F, 0.6485808273F,
  157578. 0.6490368717F, 0.6494927183F, 0.6499483667F, 0.6504038164F,
  157579. 0.6508590670F, 0.6513141178F, 0.6517689684F, 0.6522236185F,
  157580. 0.6526780673F, 0.6531323146F, 0.6535863598F, 0.6540402024F,
  157581. 0.6544938419F, 0.6549472779F, 0.6554005099F, 0.6558535373F,
  157582. 0.6563063598F, 0.6567589769F, 0.6572113880F, 0.6576635927F,
  157583. 0.6581155906F, 0.6585673810F, 0.6590189637F, 0.6594703380F,
  157584. 0.6599215035F, 0.6603724598F, 0.6608232064F, 0.6612737427F,
  157585. 0.6617240684F, 0.6621741829F, 0.6626240859F, 0.6630737767F,
  157586. 0.6635232550F, 0.6639725202F, 0.6644215720F, 0.6648704098F,
  157587. 0.6653190332F, 0.6657674417F, 0.6662156348F, 0.6666636121F,
  157588. 0.6671113731F, 0.6675589174F, 0.6680062445F, 0.6684533538F,
  157589. 0.6689002450F, 0.6693469177F, 0.6697933712F, 0.6702396052F,
  157590. 0.6706856193F, 0.6711314129F, 0.6715769855F, 0.6720223369F,
  157591. 0.6724674664F, 0.6729123736F, 0.6733570581F, 0.6738015194F,
  157592. 0.6742457570F, 0.6746897706F, 0.6751335596F, 0.6755771236F,
  157593. 0.6760204621F, 0.6764635747F, 0.6769064609F, 0.6773491204F,
  157594. 0.6777915525F, 0.6782337570F, 0.6786757332F, 0.6791174809F,
  157595. 0.6795589995F, 0.6800002886F, 0.6804413477F, 0.6808821765F,
  157596. 0.6813227743F, 0.6817631409F, 0.6822032758F, 0.6826431785F,
  157597. 0.6830828485F, 0.6835222855F, 0.6839614890F, 0.6844004585F,
  157598. 0.6848391936F, 0.6852776939F, 0.6857159589F, 0.6861539883F,
  157599. 0.6865917815F, 0.6870293381F, 0.6874666576F, 0.6879037398F,
  157600. 0.6883405840F, 0.6887771899F, 0.6892135571F, 0.6896496850F,
  157601. 0.6900855733F, 0.6905212216F, 0.6909566294F, 0.6913917963F,
  157602. 0.6918267218F, 0.6922614055F, 0.6926958471F, 0.6931300459F,
  157603. 0.6935640018F, 0.6939977141F, 0.6944311825F, 0.6948644066F,
  157604. 0.6952973859F, 0.6957301200F, 0.6961626085F, 0.6965948510F,
  157605. 0.6970268470F, 0.6974585961F, 0.6978900980F, 0.6983213521F,
  157606. 0.6987523580F, 0.6991831154F, 0.6996136238F, 0.7000438828F,
  157607. 0.7004738921F, 0.7009036510F, 0.7013331594F, 0.7017624166F,
  157608. 0.7021914224F, 0.7026201763F, 0.7030486779F, 0.7034769268F,
  157609. 0.7039049226F, 0.7043326648F, 0.7047601531F, 0.7051873870F,
  157610. 0.7056143662F, 0.7060410902F, 0.7064675586F, 0.7068937711F,
  157611. 0.7073197271F, 0.7077454264F, 0.7081708684F, 0.7085960529F,
  157612. 0.7090209793F, 0.7094456474F, 0.7098700566F, 0.7102942066F,
  157613. 0.7107180970F, 0.7111417274F, 0.7115650974F, 0.7119882066F,
  157614. 0.7124110545F, 0.7128336409F, 0.7132559653F, 0.7136780272F,
  157615. 0.7140998264F, 0.7145213624F, 0.7149426348F, 0.7153636433F,
  157616. 0.7157843874F, 0.7162048668F, 0.7166250810F, 0.7170450296F,
  157617. 0.7174647124F, 0.7178841289F, 0.7183032786F, 0.7187221613F,
  157618. 0.7191407765F, 0.7195591239F, 0.7199772030F, 0.7203950135F,
  157619. 0.7208125550F, 0.7212298271F, 0.7216468294F, 0.7220635616F,
  157620. 0.7224800233F, 0.7228962140F, 0.7233121335F, 0.7237277813F,
  157621. 0.7241431571F, 0.7245582604F, 0.7249730910F, 0.7253876484F,
  157622. 0.7258019322F, 0.7262159422F, 0.7266296778F, 0.7270431388F,
  157623. 0.7274563247F, 0.7278692353F, 0.7282818700F, 0.7286942287F,
  157624. 0.7291063108F, 0.7295181160F, 0.7299296440F, 0.7303408944F,
  157625. 0.7307518669F, 0.7311625609F, 0.7315729763F, 0.7319831126F,
  157626. 0.7323929695F, 0.7328025466F, 0.7332118435F, 0.7336208600F,
  157627. 0.7340295955F, 0.7344380499F, 0.7348462226F, 0.7352541134F,
  157628. 0.7356617220F, 0.7360690478F, 0.7364760907F, 0.7368828502F,
  157629. 0.7372893259F, 0.7376955176F, 0.7381014249F, 0.7385070475F,
  157630. 0.7389123849F, 0.7393174368F, 0.7397222029F, 0.7401266829F,
  157631. 0.7405308763F, 0.7409347829F, 0.7413384023F, 0.7417417341F,
  157632. 0.7421447780F, 0.7425475338F, 0.7429500009F, 0.7433521791F,
  157633. 0.7437540681F, 0.7441556674F, 0.7445569769F, 0.7449579960F,
  157634. 0.7453587245F, 0.7457591621F, 0.7461593084F, 0.7465591631F,
  157635. 0.7469587259F, 0.7473579963F, 0.7477569741F, 0.7481556590F,
  157636. 0.7485540506F, 0.7489521486F, 0.7493499526F, 0.7497474623F,
  157637. 0.7501446775F, 0.7505415977F, 0.7509382227F, 0.7513345521F,
  157638. 0.7517305856F, 0.7521263229F, 0.7525217636F, 0.7529169074F,
  157639. 0.7533117541F, 0.7537063032F, 0.7541005545F, 0.7544945076F,
  157640. 0.7548881623F, 0.7552815182F, 0.7556745749F, 0.7560673323F,
  157641. 0.7564597899F, 0.7568519474F, 0.7572438046F, 0.7576353611F,
  157642. 0.7580266166F, 0.7584175708F, 0.7588082235F, 0.7591985741F,
  157643. 0.7595886226F, 0.7599783685F, 0.7603678116F, 0.7607569515F,
  157644. 0.7611457879F, 0.7615343206F, 0.7619225493F, 0.7623104735F,
  157645. 0.7626980931F, 0.7630854078F, 0.7634724171F, 0.7638591209F,
  157646. 0.7642455188F, 0.7646316106F, 0.7650173959F, 0.7654028744F,
  157647. 0.7657880459F, 0.7661729100F, 0.7665574664F, 0.7669417150F,
  157648. 0.7673256553F, 0.7677092871F, 0.7680926100F, 0.7684756239F,
  157649. 0.7688583284F, 0.7692407232F, 0.7696228080F, 0.7700045826F,
  157650. 0.7703860467F, 0.7707671999F, 0.7711480420F, 0.7715285728F,
  157651. 0.7719087918F, 0.7722886989F, 0.7726682938F, 0.7730475762F,
  157652. 0.7734265458F, 0.7738052023F, 0.7741835454F, 0.7745615750F,
  157653. 0.7749392906F, 0.7753166921F, 0.7756937791F, 0.7760705514F,
  157654. 0.7764470087F, 0.7768231508F, 0.7771989773F, 0.7775744880F,
  157655. 0.7779496827F, 0.7783245610F, 0.7786991227F, 0.7790733676F,
  157656. 0.7794472953F, 0.7798209056F, 0.7801941982F, 0.7805671729F,
  157657. 0.7809398294F, 0.7813121675F, 0.7816841869F, 0.7820558873F,
  157658. 0.7824272684F, 0.7827983301F, 0.7831690720F, 0.7835394940F,
  157659. 0.7839095957F, 0.7842793768F, 0.7846488373F, 0.7850179767F,
  157660. 0.7853867948F, 0.7857552914F, 0.7861234663F, 0.7864913191F,
  157661. 0.7868588497F, 0.7872260578F, 0.7875929431F, 0.7879595055F,
  157662. 0.7883257445F, 0.7886916601F, 0.7890572520F, 0.7894225198F,
  157663. 0.7897874635F, 0.7901520827F, 0.7905163772F, 0.7908803468F,
  157664. 0.7912439912F, 0.7916073102F, 0.7919703035F, 0.7923329710F,
  157665. 0.7926953124F, 0.7930573274F, 0.7934190158F, 0.7937803774F,
  157666. 0.7941414120F, 0.7945021193F, 0.7948624991F, 0.7952225511F,
  157667. 0.7955822752F, 0.7959416711F, 0.7963007387F, 0.7966594775F,
  157668. 0.7970178875F, 0.7973759685F, 0.7977337201F, 0.7980911422F,
  157669. 0.7984482346F, 0.7988049970F, 0.7991614292F, 0.7995175310F,
  157670. 0.7998733022F, 0.8002287426F, 0.8005838519F, 0.8009386299F,
  157671. 0.8012930765F, 0.8016471914F, 0.8020009744F, 0.8023544253F,
  157672. 0.8027075438F, 0.8030603298F, 0.8034127831F, 0.8037649035F,
  157673. 0.8041166906F, 0.8044681445F, 0.8048192647F, 0.8051700512F,
  157674. 0.8055205038F, 0.8058706222F, 0.8062204062F, 0.8065698556F,
  157675. 0.8069189702F, 0.8072677499F, 0.8076161944F, 0.8079643036F,
  157676. 0.8083120772F, 0.8086595151F, 0.8090066170F, 0.8093533827F,
  157677. 0.8096998122F, 0.8100459051F, 0.8103916613F, 0.8107370806F,
  157678. 0.8110821628F, 0.8114269077F, 0.8117713151F, 0.8121153849F,
  157679. 0.8124591169F, 0.8128025108F, 0.8131455666F, 0.8134882839F,
  157680. 0.8138306627F, 0.8141727027F, 0.8145144038F, 0.8148557658F,
  157681. 0.8151967886F, 0.8155374718F, 0.8158778154F, 0.8162178192F,
  157682. 0.8165574830F, 0.8168968067F, 0.8172357900F, 0.8175744328F,
  157683. 0.8179127349F, 0.8182506962F, 0.8185883164F, 0.8189255955F,
  157684. 0.8192625332F, 0.8195991295F, 0.8199353840F, 0.8202712967F,
  157685. 0.8206068673F, 0.8209420958F, 0.8212769820F, 0.8216115256F,
  157686. 0.8219457266F, 0.8222795848F, 0.8226131000F, 0.8229462721F,
  157687. 0.8232791009F, 0.8236115863F, 0.8239437280F, 0.8242755260F,
  157688. 0.8246069801F, 0.8249380901F, 0.8252688559F, 0.8255992774F,
  157689. 0.8259293544F, 0.8262590867F, 0.8265884741F, 0.8269175167F,
  157690. 0.8272462141F, 0.8275745663F, 0.8279025732F, 0.8282302344F,
  157691. 0.8285575501F, 0.8288845199F, 0.8292111437F, 0.8295374215F,
  157692. 0.8298633530F, 0.8301889382F, 0.8305141768F, 0.8308390688F,
  157693. 0.8311636141F, 0.8314878124F, 0.8318116637F, 0.8321351678F,
  157694. 0.8324583246F, 0.8327811340F, 0.8331035957F, 0.8334257098F,
  157695. 0.8337474761F, 0.8340688944F, 0.8343899647F, 0.8347106867F,
  157696. 0.8350310605F, 0.8353510857F, 0.8356707624F, 0.8359900904F,
  157697. 0.8363090696F, 0.8366276999F, 0.8369459811F, 0.8372639131F,
  157698. 0.8375814958F, 0.8378987292F, 0.8382156130F, 0.8385321472F,
  157699. 0.8388483316F, 0.8391641662F, 0.8394796508F, 0.8397947853F,
  157700. 0.8401095697F, 0.8404240037F, 0.8407380873F, 0.8410518204F,
  157701. 0.8413652029F, 0.8416782347F, 0.8419909156F, 0.8423032456F,
  157702. 0.8426152245F, 0.8429268523F, 0.8432381289F, 0.8435490541F,
  157703. 0.8438596279F, 0.8441698502F, 0.8444797208F, 0.8447892396F,
  157704. 0.8450984067F, 0.8454072218F, 0.8457156849F, 0.8460237959F,
  157705. 0.8463315547F, 0.8466389612F, 0.8469460154F, 0.8472527170F,
  157706. 0.8475590661F, 0.8478650625F, 0.8481707063F, 0.8484759971F,
  157707. 0.8487809351F, 0.8490855201F, 0.8493897521F, 0.8496936308F,
  157708. 0.8499971564F, 0.8503003286F, 0.8506031474F, 0.8509056128F,
  157709. 0.8512077246F, 0.8515094828F, 0.8518108872F, 0.8521119379F,
  157710. 0.8524126348F, 0.8527129777F, 0.8530129666F, 0.8533126015F,
  157711. 0.8536118822F, 0.8539108087F, 0.8542093809F, 0.8545075988F,
  157712. 0.8548054623F, 0.8551029712F, 0.8554001257F, 0.8556969255F,
  157713. 0.8559933707F, 0.8562894611F, 0.8565851968F, 0.8568805775F,
  157714. 0.8571756034F, 0.8574702743F, 0.8577645902F, 0.8580585509F,
  157715. 0.8583521566F, 0.8586454070F, 0.8589383021F, 0.8592308420F,
  157716. 0.8595230265F, 0.8598148556F, 0.8601063292F, 0.8603974473F,
  157717. 0.8606882098F, 0.8609786167F, 0.8612686680F, 0.8615583636F,
  157718. 0.8618477034F, 0.8621366874F, 0.8624253156F, 0.8627135878F,
  157719. 0.8630015042F, 0.8632890646F, 0.8635762690F, 0.8638631173F,
  157720. 0.8641496096F, 0.8644357457F, 0.8647215257F, 0.8650069495F,
  157721. 0.8652920171F, 0.8655767283F, 0.8658610833F, 0.8661450820F,
  157722. 0.8664287243F, 0.8667120102F, 0.8669949397F, 0.8672775127F,
  157723. 0.8675597293F, 0.8678415894F, 0.8681230929F, 0.8684042398F,
  157724. 0.8686850302F, 0.8689654640F, 0.8692455412F, 0.8695252617F,
  157725. 0.8698046255F, 0.8700836327F, 0.8703622831F, 0.8706405768F,
  157726. 0.8709185138F, 0.8711960940F, 0.8714733174F, 0.8717501840F,
  157727. 0.8720266939F, 0.8723028469F, 0.8725786430F, 0.8728540824F,
  157728. 0.8731291648F, 0.8734038905F, 0.8736782592F, 0.8739522711F,
  157729. 0.8742259261F, 0.8744992242F, 0.8747721653F, 0.8750447496F,
  157730. 0.8753169770F, 0.8755888475F, 0.8758603611F, 0.8761315177F,
  157731. 0.8764023175F, 0.8766727603F, 0.8769428462F, 0.8772125752F,
  157732. 0.8774819474F, 0.8777509626F, 0.8780196209F, 0.8782879224F,
  157733. 0.8785558669F, 0.8788234546F, 0.8790906854F, 0.8793575594F,
  157734. 0.8796240765F, 0.8798902368F, 0.8801560403F, 0.8804214870F,
  157735. 0.8806865768F, 0.8809513099F, 0.8812156863F, 0.8814797059F,
  157736. 0.8817433687F, 0.8820066749F, 0.8822696243F, 0.8825322171F,
  157737. 0.8827944532F, 0.8830563327F, 0.8833178556F, 0.8835790219F,
  157738. 0.8838398316F, 0.8841002848F, 0.8843603815F, 0.8846201217F,
  157739. 0.8848795054F, 0.8851385327F, 0.8853972036F, 0.8856555182F,
  157740. 0.8859134764F, 0.8861710783F, 0.8864283239F, 0.8866852133F,
  157741. 0.8869417464F, 0.8871979234F, 0.8874537443F, 0.8877092090F,
  157742. 0.8879643177F, 0.8882190704F, 0.8884734671F, 0.8887275078F,
  157743. 0.8889811927F, 0.8892345216F, 0.8894874948F, 0.8897401122F,
  157744. 0.8899923738F, 0.8902442798F, 0.8904958301F, 0.8907470248F,
  157745. 0.8909978640F, 0.8912483477F, 0.8914984759F, 0.8917482487F,
  157746. 0.8919976662F, 0.8922467284F, 0.8924954353F, 0.8927437871F,
  157747. 0.8929917837F, 0.8932394252F, 0.8934867118F, 0.8937336433F,
  157748. 0.8939802199F, 0.8942264417F, 0.8944723087F, 0.8947178210F,
  157749. 0.8949629785F, 0.8952077815F, 0.8954522299F, 0.8956963239F,
  157750. 0.8959400634F, 0.8961834486F, 0.8964264795F, 0.8966691561F,
  157751. 0.8969114786F, 0.8971534470F, 0.8973950614F, 0.8976363219F,
  157752. 0.8978772284F, 0.8981177812F, 0.8983579802F, 0.8985978256F,
  157753. 0.8988373174F, 0.8990764556F, 0.8993152405F, 0.8995536720F,
  157754. 0.8997917502F, 0.9000294751F, 0.9002668470F, 0.9005038658F,
  157755. 0.9007405317F, 0.9009768446F, 0.9012128048F, 0.9014484123F,
  157756. 0.9016836671F, 0.9019185693F, 0.9021531191F, 0.9023873165F,
  157757. 0.9026211616F, 0.9028546546F, 0.9030877954F, 0.9033205841F,
  157758. 0.9035530210F, 0.9037851059F, 0.9040168392F, 0.9042482207F,
  157759. 0.9044792507F, 0.9047099293F, 0.9049402564F, 0.9051702323F,
  157760. 0.9053998569F, 0.9056291305F, 0.9058580531F, 0.9060866248F,
  157761. 0.9063148457F, 0.9065427159F, 0.9067702355F, 0.9069974046F,
  157762. 0.9072242233F, 0.9074506917F, 0.9076768100F, 0.9079025782F,
  157763. 0.9081279964F, 0.9083530647F, 0.9085777833F, 0.9088021523F,
  157764. 0.9090261717F, 0.9092498417F, 0.9094731623F, 0.9096961338F,
  157765. 0.9099187561F, 0.9101410295F, 0.9103629540F, 0.9105845297F,
  157766. 0.9108057568F, 0.9110266354F, 0.9112471656F, 0.9114673475F,
  157767. 0.9116871812F, 0.9119066668F, 0.9121258046F, 0.9123445945F,
  157768. 0.9125630367F, 0.9127811314F, 0.9129988786F, 0.9132162785F,
  157769. 0.9134333312F, 0.9136500368F, 0.9138663954F, 0.9140824073F,
  157770. 0.9142980724F, 0.9145133910F, 0.9147283632F, 0.9149429890F,
  157771. 0.9151572687F, 0.9153712023F, 0.9155847900F, 0.9157980319F,
  157772. 0.9160109282F, 0.9162234790F, 0.9164356844F, 0.9166475445F,
  157773. 0.9168590595F, 0.9170702296F, 0.9172810548F, 0.9174915354F,
  157774. 0.9177016714F, 0.9179114629F, 0.9181209102F, 0.9183300134F,
  157775. 0.9185387726F, 0.9187471879F, 0.9189552595F, 0.9191629876F,
  157776. 0.9193703723F, 0.9195774136F, 0.9197841119F, 0.9199904672F,
  157777. 0.9201964797F, 0.9204021495F, 0.9206074767F, 0.9208124616F,
  157778. 0.9210171043F, 0.9212214049F, 0.9214253636F, 0.9216289805F,
  157779. 0.9218322558F, 0.9220351896F, 0.9222377821F, 0.9224400335F,
  157780. 0.9226419439F, 0.9228435134F, 0.9230447423F, 0.9232456307F,
  157781. 0.9234461787F, 0.9236463865F, 0.9238462543F, 0.9240457822F,
  157782. 0.9242449704F, 0.9244438190F, 0.9246423282F, 0.9248404983F,
  157783. 0.9250383293F, 0.9252358214F, 0.9254329747F, 0.9256297896F,
  157784. 0.9258262660F, 0.9260224042F, 0.9262182044F, 0.9264136667F,
  157785. 0.9266087913F, 0.9268035783F, 0.9269980280F, 0.9271921405F,
  157786. 0.9273859160F, 0.9275793546F, 0.9277724566F, 0.9279652221F,
  157787. 0.9281576513F, 0.9283497443F, 0.9285415014F, 0.9287329227F,
  157788. 0.9289240084F, 0.9291147586F, 0.9293051737F, 0.9294952536F,
  157789. 0.9296849987F, 0.9298744091F, 0.9300634850F, 0.9302522266F,
  157790. 0.9304406340F, 0.9306287074F, 0.9308164471F, 0.9310038532F,
  157791. 0.9311909259F, 0.9313776654F, 0.9315640719F, 0.9317501455F,
  157792. 0.9319358865F, 0.9321212951F, 0.9323063713F, 0.9324911155F,
  157793. 0.9326755279F, 0.9328596085F, 0.9330433577F, 0.9332267756F,
  157794. 0.9334098623F, 0.9335926182F, 0.9337750434F, 0.9339571380F,
  157795. 0.9341389023F, 0.9343203366F, 0.9345014409F, 0.9346822155F,
  157796. 0.9348626606F, 0.9350427763F, 0.9352225630F, 0.9354020207F,
  157797. 0.9355811498F, 0.9357599503F, 0.9359384226F, 0.9361165667F,
  157798. 0.9362943830F, 0.9364718716F, 0.9366490327F, 0.9368258666F,
  157799. 0.9370023733F, 0.9371785533F, 0.9373544066F, 0.9375299335F,
  157800. 0.9377051341F, 0.9378800087F, 0.9380545576F, 0.9382287809F,
  157801. 0.9384026787F, 0.9385762515F, 0.9387494993F, 0.9389224223F,
  157802. 0.9390950209F, 0.9392672951F, 0.9394392453F, 0.9396108716F,
  157803. 0.9397821743F, 0.9399531536F, 0.9401238096F, 0.9402941427F,
  157804. 0.9404641530F, 0.9406338407F, 0.9408032061F, 0.9409722495F,
  157805. 0.9411409709F, 0.9413093707F, 0.9414774491F, 0.9416452062F,
  157806. 0.9418126424F, 0.9419797579F, 0.9421465528F, 0.9423130274F,
  157807. 0.9424791819F, 0.9426450166F, 0.9428105317F, 0.9429757274F,
  157808. 0.9431406039F, 0.9433051616F, 0.9434694005F, 0.9436333209F,
  157809. 0.9437969232F, 0.9439602074F, 0.9441231739F, 0.9442858229F,
  157810. 0.9444481545F, 0.9446101691F, 0.9447718669F, 0.9449332481F,
  157811. 0.9450943129F, 0.9452550617F, 0.9454154945F, 0.9455756118F,
  157812. 0.9457354136F, 0.9458949003F, 0.9460540721F, 0.9462129292F,
  157813. 0.9463714719F, 0.9465297003F, 0.9466876149F, 0.9468452157F,
  157814. 0.9470025031F, 0.9471594772F, 0.9473161384F, 0.9474724869F,
  157815. 0.9476285229F, 0.9477842466F, 0.9479396584F, 0.9480947585F,
  157816. 0.9482495470F, 0.9484040243F, 0.9485581906F, 0.9487120462F,
  157817. 0.9488655913F, 0.9490188262F, 0.9491717511F, 0.9493243662F,
  157818. 0.9494766718F, 0.9496286683F, 0.9497803557F, 0.9499317345F,
  157819. 0.9500828047F, 0.9502335668F, 0.9503840209F, 0.9505341673F,
  157820. 0.9506840062F, 0.9508335380F, 0.9509827629F, 0.9511316810F,
  157821. 0.9512802928F, 0.9514285984F, 0.9515765982F, 0.9517242923F,
  157822. 0.9518716810F, 0.9520187646F, 0.9521655434F, 0.9523120176F,
  157823. 0.9524581875F, 0.9526040534F, 0.9527496154F, 0.9528948739F,
  157824. 0.9530398292F, 0.9531844814F, 0.9533288310F, 0.9534728780F,
  157825. 0.9536166229F, 0.9537600659F, 0.9539032071F, 0.9540460470F,
  157826. 0.9541885858F, 0.9543308237F, 0.9544727611F, 0.9546143981F,
  157827. 0.9547557351F, 0.9548967723F, 0.9550375100F, 0.9551779485F,
  157828. 0.9553180881F, 0.9554579290F, 0.9555974714F, 0.9557367158F,
  157829. 0.9558756623F, 0.9560143112F, 0.9561526628F, 0.9562907174F,
  157830. 0.9564284752F, 0.9565659366F, 0.9567031017F, 0.9568399710F,
  157831. 0.9569765446F, 0.9571128229F, 0.9572488061F, 0.9573844944F,
  157832. 0.9575198883F, 0.9576549879F, 0.9577897936F, 0.9579243056F,
  157833. 0.9580585242F, 0.9581924497F, 0.9583260824F, 0.9584594226F,
  157834. 0.9585924705F, 0.9587252264F, 0.9588576906F, 0.9589898634F,
  157835. 0.9591217452F, 0.9592533360F, 0.9593846364F, 0.9595156465F,
  157836. 0.9596463666F, 0.9597767971F, 0.9599069382F, 0.9600367901F,
  157837. 0.9601663533F, 0.9602956279F, 0.9604246143F, 0.9605533128F,
  157838. 0.9606817236F, 0.9608098471F, 0.9609376835F, 0.9610652332F,
  157839. 0.9611924963F, 0.9613194733F, 0.9614461644F, 0.9615725699F,
  157840. 0.9616986901F, 0.9618245253F, 0.9619500757F, 0.9620753418F,
  157841. 0.9622003238F, 0.9623250219F, 0.9624494365F, 0.9625735679F,
  157842. 0.9626974163F, 0.9628209821F, 0.9629442656F, 0.9630672671F,
  157843. 0.9631899868F, 0.9633124251F, 0.9634345822F, 0.9635564585F,
  157844. 0.9636780543F, 0.9637993699F, 0.9639204056F, 0.9640411616F,
  157845. 0.9641616383F, 0.9642818359F, 0.9644017549F, 0.9645213955F,
  157846. 0.9646407579F, 0.9647598426F, 0.9648786497F, 0.9649971797F,
  157847. 0.9651154328F, 0.9652334092F, 0.9653511095F, 0.9654685337F,
  157848. 0.9655856823F, 0.9657025556F, 0.9658191538F, 0.9659354773F,
  157849. 0.9660515263F, 0.9661673013F, 0.9662828024F, 0.9663980300F,
  157850. 0.9665129845F, 0.9666276660F, 0.9667420750F, 0.9668562118F,
  157851. 0.9669700766F, 0.9670836698F, 0.9671969917F, 0.9673100425F,
  157852. 0.9674228227F, 0.9675353325F, 0.9676475722F, 0.9677595422F,
  157853. 0.9678712428F, 0.9679826742F, 0.9680938368F, 0.9682047309F,
  157854. 0.9683153569F, 0.9684257150F, 0.9685358056F, 0.9686456289F,
  157855. 0.9687551853F, 0.9688644752F, 0.9689734987F, 0.9690822564F,
  157856. 0.9691907483F, 0.9692989750F, 0.9694069367F, 0.9695146337F,
  157857. 0.9696220663F, 0.9697292349F, 0.9698361398F, 0.9699427813F,
  157858. 0.9700491597F, 0.9701552754F, 0.9702611286F, 0.9703667197F,
  157859. 0.9704720490F, 0.9705771169F, 0.9706819236F, 0.9707864695F,
  157860. 0.9708907549F, 0.9709947802F, 0.9710985456F, 0.9712020514F,
  157861. 0.9713052981F, 0.9714082859F, 0.9715110151F, 0.9716134862F,
  157862. 0.9717156993F, 0.9718176549F, 0.9719193532F, 0.9720207946F,
  157863. 0.9721219794F, 0.9722229080F, 0.9723235806F, 0.9724239976F,
  157864. 0.9725241593F, 0.9726240661F, 0.9727237183F, 0.9728231161F,
  157865. 0.9729222601F, 0.9730211503F, 0.9731197873F, 0.9732181713F,
  157866. 0.9733163027F, 0.9734141817F, 0.9735118088F, 0.9736091842F,
  157867. 0.9737063083F, 0.9738031814F, 0.9738998039F, 0.9739961760F,
  157868. 0.9740922981F, 0.9741881706F, 0.9742837938F, 0.9743791680F,
  157869. 0.9744742935F, 0.9745691707F, 0.9746637999F, 0.9747581814F,
  157870. 0.9748523157F, 0.9749462029F, 0.9750398435F, 0.9751332378F,
  157871. 0.9752263861F, 0.9753192887F, 0.9754119461F, 0.9755043585F,
  157872. 0.9755965262F, 0.9756884496F, 0.9757801291F, 0.9758715650F,
  157873. 0.9759627575F, 0.9760537071F, 0.9761444141F, 0.9762348789F,
  157874. 0.9763251016F, 0.9764150828F, 0.9765048228F, 0.9765943218F,
  157875. 0.9766835802F, 0.9767725984F, 0.9768613767F, 0.9769499154F,
  157876. 0.9770382149F, 0.9771262755F, 0.9772140976F, 0.9773016815F,
  157877. 0.9773890275F, 0.9774761360F, 0.9775630073F, 0.9776496418F,
  157878. 0.9777360398F, 0.9778222016F, 0.9779081277F, 0.9779938182F,
  157879. 0.9780792736F, 0.9781644943F, 0.9782494805F, 0.9783342326F,
  157880. 0.9784187509F, 0.9785030359F, 0.9785870877F, 0.9786709069F,
  157881. 0.9787544936F, 0.9788378484F, 0.9789209714F, 0.9790038631F,
  157882. 0.9790865238F, 0.9791689538F, 0.9792511535F, 0.9793331232F,
  157883. 0.9794148633F, 0.9794963742F, 0.9795776561F, 0.9796587094F,
  157884. 0.9797395345F, 0.9798201316F, 0.9799005013F, 0.9799806437F,
  157885. 0.9800605593F, 0.9801402483F, 0.9802197112F, 0.9802989483F,
  157886. 0.9803779600F, 0.9804567465F, 0.9805353082F, 0.9806136455F,
  157887. 0.9806917587F, 0.9807696482F, 0.9808473143F, 0.9809247574F,
  157888. 0.9810019778F, 0.9810789759F, 0.9811557519F, 0.9812323064F,
  157889. 0.9813086395F, 0.9813847517F, 0.9814606433F, 0.9815363147F,
  157890. 0.9816117662F, 0.9816869981F, 0.9817620108F, 0.9818368047F,
  157891. 0.9819113801F, 0.9819857374F, 0.9820598769F, 0.9821337989F,
  157892. 0.9822075038F, 0.9822809920F, 0.9823542638F, 0.9824273195F,
  157893. 0.9825001596F, 0.9825727843F, 0.9826451940F, 0.9827173891F,
  157894. 0.9827893700F, 0.9828611368F, 0.9829326901F, 0.9830040302F,
  157895. 0.9830751574F, 0.9831460720F, 0.9832167745F, 0.9832872652F,
  157896. 0.9833575444F, 0.9834276124F, 0.9834974697F, 0.9835671166F,
  157897. 0.9836365535F, 0.9837057806F, 0.9837747983F, 0.9838436071F,
  157898. 0.9839122072F, 0.9839805990F, 0.9840487829F, 0.9841167591F,
  157899. 0.9841845282F, 0.9842520903F, 0.9843194459F, 0.9843865953F,
  157900. 0.9844535389F, 0.9845202771F, 0.9845868101F, 0.9846531383F,
  157901. 0.9847192622F, 0.9847851820F, 0.9848508980F, 0.9849164108F,
  157902. 0.9849817205F, 0.9850468276F, 0.9851117324F, 0.9851764352F,
  157903. 0.9852409365F, 0.9853052366F, 0.9853693358F, 0.9854332344F,
  157904. 0.9854969330F, 0.9855604317F, 0.9856237309F, 0.9856868310F,
  157905. 0.9857497325F, 0.9858124355F, 0.9858749404F, 0.9859372477F,
  157906. 0.9859993577F, 0.9860612707F, 0.9861229871F, 0.9861845072F,
  157907. 0.9862458315F, 0.9863069601F, 0.9863678936F, 0.9864286322F,
  157908. 0.9864891764F, 0.9865495264F, 0.9866096826F, 0.9866696454F,
  157909. 0.9867294152F, 0.9867889922F, 0.9868483769F, 0.9869075695F,
  157910. 0.9869665706F, 0.9870253803F, 0.9870839991F, 0.9871424273F,
  157911. 0.9872006653F, 0.9872587135F, 0.9873165721F, 0.9873742415F,
  157912. 0.9874317222F, 0.9874890144F, 0.9875461185F, 0.9876030348F,
  157913. 0.9876597638F, 0.9877163057F, 0.9877726610F, 0.9878288300F,
  157914. 0.9878848130F, 0.9879406104F, 0.9879962225F, 0.9880516497F,
  157915. 0.9881068924F, 0.9881619509F, 0.9882168256F, 0.9882715168F,
  157916. 0.9883260249F, 0.9883803502F, 0.9884344931F, 0.9884884539F,
  157917. 0.9885422331F, 0.9885958309F, 0.9886492477F, 0.9887024838F,
  157918. 0.9887555397F, 0.9888084157F, 0.9888611120F, 0.9889136292F,
  157919. 0.9889659675F, 0.9890181273F, 0.9890701089F, 0.9891219128F,
  157920. 0.9891735392F, 0.9892249885F, 0.9892762610F, 0.9893273572F,
  157921. 0.9893782774F, 0.9894290219F, 0.9894795911F, 0.9895299853F,
  157922. 0.9895802049F, 0.9896302502F, 0.9896801217F, 0.9897298196F,
  157923. 0.9897793443F, 0.9898286961F, 0.9898778755F, 0.9899268828F,
  157924. 0.9899757183F, 0.9900243823F, 0.9900728753F, 0.9901211976F,
  157925. 0.9901693495F, 0.9902173314F, 0.9902651436F, 0.9903127865F,
  157926. 0.9903602605F, 0.9904075659F, 0.9904547031F, 0.9905016723F,
  157927. 0.9905484740F, 0.9905951086F, 0.9906415763F, 0.9906878775F,
  157928. 0.9907340126F, 0.9907799819F, 0.9908257858F, 0.9908714247F,
  157929. 0.9909168988F, 0.9909622086F, 0.9910073543F, 0.9910523364F,
  157930. 0.9910971552F, 0.9911418110F, 0.9911863042F, 0.9912306351F,
  157931. 0.9912748042F, 0.9913188117F, 0.9913626580F, 0.9914063435F,
  157932. 0.9914498684F, 0.9914932333F, 0.9915364383F, 0.9915794839F,
  157933. 0.9916223703F, 0.9916650981F, 0.9917076674F, 0.9917500787F,
  157934. 0.9917923323F, 0.9918344286F, 0.9918763679F, 0.9919181505F,
  157935. 0.9919597769F, 0.9920012473F, 0.9920425621F, 0.9920837217F,
  157936. 0.9921247263F, 0.9921655765F, 0.9922062724F, 0.9922468145F,
  157937. 0.9922872030F, 0.9923274385F, 0.9923675211F, 0.9924074513F,
  157938. 0.9924472294F, 0.9924868557F, 0.9925263306F, 0.9925656544F,
  157939. 0.9926048275F, 0.9926438503F, 0.9926827230F, 0.9927214461F,
  157940. 0.9927600199F, 0.9927984446F, 0.9928367208F, 0.9928748486F,
  157941. 0.9929128285F, 0.9929506608F, 0.9929883459F, 0.9930258841F,
  157942. 0.9930632757F, 0.9931005211F, 0.9931376207F, 0.9931745747F,
  157943. 0.9932113836F, 0.9932480476F, 0.9932845671F, 0.9933209425F,
  157944. 0.9933571742F, 0.9933932623F, 0.9934292074F, 0.9934650097F,
  157945. 0.9935006696F, 0.9935361874F, 0.9935715635F, 0.9936067982F,
  157946. 0.9936418919F, 0.9936768448F, 0.9937116574F, 0.9937463300F,
  157947. 0.9937808629F, 0.9938152565F, 0.9938495111F, 0.9938836271F,
  157948. 0.9939176047F, 0.9939514444F, 0.9939851465F, 0.9940187112F,
  157949. 0.9940521391F, 0.9940854303F, 0.9941185853F, 0.9941516044F,
  157950. 0.9941844879F, 0.9942172361F, 0.9942498495F, 0.9942823283F,
  157951. 0.9943146729F, 0.9943468836F, 0.9943789608F, 0.9944109047F,
  157952. 0.9944427158F, 0.9944743944F, 0.9945059408F, 0.9945373553F,
  157953. 0.9945686384F, 0.9945997902F, 0.9946308112F, 0.9946617017F,
  157954. 0.9946924621F, 0.9947230926F, 0.9947535937F, 0.9947839656F,
  157955. 0.9948142086F, 0.9948443232F, 0.9948743097F, 0.9949041683F,
  157956. 0.9949338995F, 0.9949635035F, 0.9949929807F, 0.9950223315F,
  157957. 0.9950515561F, 0.9950806549F, 0.9951096282F, 0.9951384764F,
  157958. 0.9951671998F, 0.9951957987F, 0.9952242735F, 0.9952526245F,
  157959. 0.9952808520F, 0.9953089564F, 0.9953369380F, 0.9953647971F,
  157960. 0.9953925340F, 0.9954201491F, 0.9954476428F, 0.9954750153F,
  157961. 0.9955022670F, 0.9955293981F, 0.9955564092F, 0.9955833003F,
  157962. 0.9956100720F, 0.9956367245F, 0.9956632582F, 0.9956896733F,
  157963. 0.9957159703F, 0.9957421494F, 0.9957682110F, 0.9957941553F,
  157964. 0.9958199828F, 0.9958456937F, 0.9958712884F, 0.9958967672F,
  157965. 0.9959221305F, 0.9959473784F, 0.9959725115F, 0.9959975300F,
  157966. 0.9960224342F, 0.9960472244F, 0.9960719011F, 0.9960964644F,
  157967. 0.9961209148F, 0.9961452525F, 0.9961694779F, 0.9961935913F,
  157968. 0.9962175930F, 0.9962414834F, 0.9962652627F, 0.9962889313F,
  157969. 0.9963124895F, 0.9963359377F, 0.9963592761F, 0.9963825051F,
  157970. 0.9964056250F, 0.9964286361F, 0.9964515387F, 0.9964743332F,
  157971. 0.9964970198F, 0.9965195990F, 0.9965420709F, 0.9965644360F,
  157972. 0.9965866946F, 0.9966088469F, 0.9966308932F, 0.9966528340F,
  157973. 0.9966746695F, 0.9966964001F, 0.9967180260F, 0.9967395475F,
  157974. 0.9967609651F, 0.9967822789F, 0.9968034894F, 0.9968245968F,
  157975. 0.9968456014F, 0.9968665036F, 0.9968873037F, 0.9969080019F,
  157976. 0.9969285987F, 0.9969490942F, 0.9969694889F, 0.9969897830F,
  157977. 0.9970099769F, 0.9970300708F, 0.9970500651F, 0.9970699601F,
  157978. 0.9970897561F, 0.9971094533F, 0.9971290522F, 0.9971485531F,
  157979. 0.9971679561F, 0.9971872617F, 0.9972064702F, 0.9972255818F,
  157980. 0.9972445968F, 0.9972635157F, 0.9972823386F, 0.9973010659F,
  157981. 0.9973196980F, 0.9973382350F, 0.9973566773F, 0.9973750253F,
  157982. 0.9973932791F, 0.9974114392F, 0.9974295059F, 0.9974474793F,
  157983. 0.9974653599F, 0.9974831480F, 0.9975008438F, 0.9975184476F,
  157984. 0.9975359598F, 0.9975533806F, 0.9975707104F, 0.9975879495F,
  157985. 0.9976050981F, 0.9976221566F, 0.9976391252F, 0.9976560043F,
  157986. 0.9976727941F, 0.9976894950F, 0.9977061073F, 0.9977226312F,
  157987. 0.9977390671F, 0.9977554152F, 0.9977716759F, 0.9977878495F,
  157988. 0.9978039361F, 0.9978199363F, 0.9978358501F, 0.9978516780F,
  157989. 0.9978674202F, 0.9978830771F, 0.9978986488F, 0.9979141358F,
  157990. 0.9979295383F, 0.9979448566F, 0.9979600909F, 0.9979752417F,
  157991. 0.9979903091F, 0.9980052936F, 0.9980201952F, 0.9980350145F,
  157992. 0.9980497515F, 0.9980644067F, 0.9980789804F, 0.9980934727F,
  157993. 0.9981078841F, 0.9981222147F, 0.9981364649F, 0.9981506350F,
  157994. 0.9981647253F, 0.9981787360F, 0.9981926674F, 0.9982065199F,
  157995. 0.9982202936F, 0.9982339890F, 0.9982476062F, 0.9982611456F,
  157996. 0.9982746074F, 0.9982879920F, 0.9983012996F, 0.9983145304F,
  157997. 0.9983276849F, 0.9983407632F, 0.9983537657F, 0.9983666926F,
  157998. 0.9983795442F, 0.9983923208F, 0.9984050226F, 0.9984176501F,
  157999. 0.9984302033F, 0.9984426827F, 0.9984550884F, 0.9984674208F,
  158000. 0.9984796802F, 0.9984918667F, 0.9985039808F, 0.9985160227F,
  158001. 0.9985279926F, 0.9985398909F, 0.9985517177F, 0.9985634734F,
  158002. 0.9985751583F, 0.9985867727F, 0.9985983167F, 0.9986097907F,
  158003. 0.9986211949F, 0.9986325297F, 0.9986437953F, 0.9986549919F,
  158004. 0.9986661199F, 0.9986771795F, 0.9986881710F, 0.9986990946F,
  158005. 0.9987099507F, 0.9987207394F, 0.9987314611F, 0.9987421161F,
  158006. 0.9987527045F, 0.9987632267F, 0.9987736829F, 0.9987840734F,
  158007. 0.9987943985F, 0.9988046584F, 0.9988148534F, 0.9988249838F,
  158008. 0.9988350498F, 0.9988450516F, 0.9988549897F, 0.9988648641F,
  158009. 0.9988746753F, 0.9988844233F, 0.9988941086F, 0.9989037313F,
  158010. 0.9989132918F, 0.9989227902F, 0.9989322269F, 0.9989416021F,
  158011. 0.9989509160F, 0.9989601690F, 0.9989693613F, 0.9989784931F,
  158012. 0.9989875647F, 0.9989965763F, 0.9990055283F, 0.9990144208F,
  158013. 0.9990232541F, 0.9990320286F, 0.9990407443F, 0.9990494016F,
  158014. 0.9990580008F, 0.9990665421F, 0.9990750257F, 0.9990834519F,
  158015. 0.9990918209F, 0.9991001331F, 0.9991083886F, 0.9991165877F,
  158016. 0.9991247307F, 0.9991328177F, 0.9991408491F, 0.9991488251F,
  158017. 0.9991567460F, 0.9991646119F, 0.9991724232F, 0.9991801801F,
  158018. 0.9991878828F, 0.9991955316F, 0.9992031267F, 0.9992106684F,
  158019. 0.9992181569F, 0.9992255925F, 0.9992329753F, 0.9992403057F,
  158020. 0.9992475839F, 0.9992548101F, 0.9992619846F, 0.9992691076F,
  158021. 0.9992761793F, 0.9992832001F, 0.9992901701F, 0.9992970895F,
  158022. 0.9993039587F, 0.9993107777F, 0.9993175470F, 0.9993242667F,
  158023. 0.9993309371F, 0.9993375583F, 0.9993441307F, 0.9993506545F,
  158024. 0.9993571298F, 0.9993635570F, 0.9993699362F, 0.9993762678F,
  158025. 0.9993825519F, 0.9993887887F, 0.9993949785F, 0.9994011216F,
  158026. 0.9994072181F, 0.9994132683F, 0.9994192725F, 0.9994252307F,
  158027. 0.9994311434F, 0.9994370107F, 0.9994428327F, 0.9994486099F,
  158028. 0.9994543423F, 0.9994600303F, 0.9994656739F, 0.9994712736F,
  158029. 0.9994768294F, 0.9994823417F, 0.9994878105F, 0.9994932363F,
  158030. 0.9994986191F, 0.9995039592F, 0.9995092568F, 0.9995145122F,
  158031. 0.9995197256F, 0.9995248971F, 0.9995300270F, 0.9995351156F,
  158032. 0.9995401630F, 0.9995451695F, 0.9995501352F, 0.9995550604F,
  158033. 0.9995599454F, 0.9995647903F, 0.9995695953F, 0.9995743607F,
  158034. 0.9995790866F, 0.9995837734F, 0.9995884211F, 0.9995930300F,
  158035. 0.9995976004F, 0.9996021324F, 0.9996066263F, 0.9996110822F,
  158036. 0.9996155004F, 0.9996198810F, 0.9996242244F, 0.9996285306F,
  158037. 0.9996327999F, 0.9996370326F, 0.9996412287F, 0.9996453886F,
  158038. 0.9996495125F, 0.9996536004F, 0.9996576527F, 0.9996616696F,
  158039. 0.9996656512F, 0.9996695977F, 0.9996735094F, 0.9996773865F,
  158040. 0.9996812291F, 0.9996850374F, 0.9996888118F, 0.9996925523F,
  158041. 0.9996962591F, 0.9996999325F, 0.9997035727F, 0.9997071798F,
  158042. 0.9997107541F, 0.9997142957F, 0.9997178049F, 0.9997212818F,
  158043. 0.9997247266F, 0.9997281396F, 0.9997315209F, 0.9997348708F,
  158044. 0.9997381893F, 0.9997414767F, 0.9997447333F, 0.9997479591F,
  158045. 0.9997511544F, 0.9997543194F, 0.9997574542F, 0.9997605591F,
  158046. 0.9997636342F, 0.9997666797F, 0.9997696958F, 0.9997726828F,
  158047. 0.9997756407F, 0.9997785698F, 0.9997814703F, 0.9997843423F,
  158048. 0.9997871860F, 0.9997900016F, 0.9997927894F, 0.9997955494F,
  158049. 0.9997982818F, 0.9998009869F, 0.9998036648F, 0.9998063157F,
  158050. 0.9998089398F, 0.9998115373F, 0.9998141082F, 0.9998166529F,
  158051. 0.9998191715F, 0.9998216642F, 0.9998241311F, 0.9998265724F,
  158052. 0.9998289884F, 0.9998313790F, 0.9998337447F, 0.9998360854F,
  158053. 0.9998384015F, 0.9998406930F, 0.9998429602F, 0.9998452031F,
  158054. 0.9998474221F, 0.9998496171F, 0.9998517885F, 0.9998539364F,
  158055. 0.9998560610F, 0.9998581624F, 0.9998602407F, 0.9998622962F,
  158056. 0.9998643291F, 0.9998663394F, 0.9998683274F, 0.9998702932F,
  158057. 0.9998722370F, 0.9998741589F, 0.9998760591F, 0.9998779378F,
  158058. 0.9998797952F, 0.9998816313F, 0.9998834464F, 0.9998852406F,
  158059. 0.9998870141F, 0.9998887670F, 0.9998904995F, 0.9998922117F,
  158060. 0.9998939039F, 0.9998955761F, 0.9998972285F, 0.9998988613F,
  158061. 0.9999004746F, 0.9999020686F, 0.9999036434F, 0.9999051992F,
  158062. 0.9999067362F, 0.9999082544F, 0.9999097541F, 0.9999112354F,
  158063. 0.9999126984F, 0.9999141433F, 0.9999155703F, 0.9999169794F,
  158064. 0.9999183709F, 0.9999197449F, 0.9999211014F, 0.9999224408F,
  158065. 0.9999237631F, 0.9999250684F, 0.9999263570F, 0.9999276289F,
  158066. 0.9999288843F, 0.9999301233F, 0.9999313461F, 0.9999325529F,
  158067. 0.9999337437F, 0.9999349187F, 0.9999360780F, 0.9999372218F,
  158068. 0.9999383503F, 0.9999394635F, 0.9999405616F, 0.9999416447F,
  158069. 0.9999427129F, 0.9999437665F, 0.9999448055F, 0.9999458301F,
  158070. 0.9999468404F, 0.9999478365F, 0.9999488185F, 0.9999497867F,
  158071. 0.9999507411F, 0.9999516819F, 0.9999526091F, 0.9999535230F,
  158072. 0.9999544236F, 0.9999553111F, 0.9999561856F, 0.9999570472F,
  158073. 0.9999578960F, 0.9999587323F, 0.9999595560F, 0.9999603674F,
  158074. 0.9999611666F, 0.9999619536F, 0.9999627286F, 0.9999634917F,
  158075. 0.9999642431F, 0.9999649828F, 0.9999657110F, 0.9999664278F,
  158076. 0.9999671334F, 0.9999678278F, 0.9999685111F, 0.9999691835F,
  158077. 0.9999698451F, 0.9999704960F, 0.9999711364F, 0.9999717662F,
  158078. 0.9999723858F, 0.9999729950F, 0.9999735942F, 0.9999741834F,
  158079. 0.9999747626F, 0.9999753321F, 0.9999758919F, 0.9999764421F,
  158080. 0.9999769828F, 0.9999775143F, 0.9999780364F, 0.9999785495F,
  158081. 0.9999790535F, 0.9999795485F, 0.9999800348F, 0.9999805124F,
  158082. 0.9999809813F, 0.9999814417F, 0.9999818938F, 0.9999823375F,
  158083. 0.9999827731F, 0.9999832005F, 0.9999836200F, 0.9999840316F,
  158084. 0.9999844353F, 0.9999848314F, 0.9999852199F, 0.9999856008F,
  158085. 0.9999859744F, 0.9999863407F, 0.9999866997F, 0.9999870516F,
  158086. 0.9999873965F, 0.9999877345F, 0.9999880656F, 0.9999883900F,
  158087. 0.9999887078F, 0.9999890190F, 0.9999893237F, 0.9999896220F,
  158088. 0.9999899140F, 0.9999901999F, 0.9999904796F, 0.9999907533F,
  158089. 0.9999910211F, 0.9999912830F, 0.9999915391F, 0.9999917896F,
  158090. 0.9999920345F, 0.9999922738F, 0.9999925077F, 0.9999927363F,
  158091. 0.9999929596F, 0.9999931777F, 0.9999933907F, 0.9999935987F,
  158092. 0.9999938018F, 0.9999940000F, 0.9999941934F, 0.9999943820F,
  158093. 0.9999945661F, 0.9999947456F, 0.9999949206F, 0.9999950912F,
  158094. 0.9999952575F, 0.9999954195F, 0.9999955773F, 0.9999957311F,
  158095. 0.9999958807F, 0.9999960265F, 0.9999961683F, 0.9999963063F,
  158096. 0.9999964405F, 0.9999965710F, 0.9999966979F, 0.9999968213F,
  158097. 0.9999969412F, 0.9999970576F, 0.9999971707F, 0.9999972805F,
  158098. 0.9999973871F, 0.9999974905F, 0.9999975909F, 0.9999976881F,
  158099. 0.9999977824F, 0.9999978738F, 0.9999979624F, 0.9999980481F,
  158100. 0.9999981311F, 0.9999982115F, 0.9999982892F, 0.9999983644F,
  158101. 0.9999984370F, 0.9999985072F, 0.9999985750F, 0.9999986405F,
  158102. 0.9999987037F, 0.9999987647F, 0.9999988235F, 0.9999988802F,
  158103. 0.9999989348F, 0.9999989873F, 0.9999990379F, 0.9999990866F,
  158104. 0.9999991334F, 0.9999991784F, 0.9999992217F, 0.9999992632F,
  158105. 0.9999993030F, 0.9999993411F, 0.9999993777F, 0.9999994128F,
  158106. 0.9999994463F, 0.9999994784F, 0.9999995091F, 0.9999995384F,
  158107. 0.9999995663F, 0.9999995930F, 0.9999996184F, 0.9999996426F,
  158108. 0.9999996657F, 0.9999996876F, 0.9999997084F, 0.9999997282F,
  158109. 0.9999997469F, 0.9999997647F, 0.9999997815F, 0.9999997973F,
  158110. 0.9999998123F, 0.9999998265F, 0.9999998398F, 0.9999998524F,
  158111. 0.9999998642F, 0.9999998753F, 0.9999998857F, 0.9999998954F,
  158112. 0.9999999045F, 0.9999999130F, 0.9999999209F, 0.9999999282F,
  158113. 0.9999999351F, 0.9999999414F, 0.9999999472F, 0.9999999526F,
  158114. 0.9999999576F, 0.9999999622F, 0.9999999664F, 0.9999999702F,
  158115. 0.9999999737F, 0.9999999769F, 0.9999999798F, 0.9999999824F,
  158116. 0.9999999847F, 0.9999999868F, 0.9999999887F, 0.9999999904F,
  158117. 0.9999999919F, 0.9999999932F, 0.9999999943F, 0.9999999953F,
  158118. 0.9999999961F, 0.9999999969F, 0.9999999975F, 0.9999999980F,
  158119. 0.9999999985F, 0.9999999988F, 0.9999999991F, 0.9999999993F,
  158120. 0.9999999995F, 0.9999999997F, 0.9999999998F, 0.9999999999F,
  158121. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  158122. 1.0000000000F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  158123. };
  158124. static float *vwin[8] = {
  158125. vwin64,
  158126. vwin128,
  158127. vwin256,
  158128. vwin512,
  158129. vwin1024,
  158130. vwin2048,
  158131. vwin4096,
  158132. vwin8192,
  158133. };
  158134. float *_vorbis_window_get(int n){
  158135. return vwin[n];
  158136. }
  158137. void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  158138. int lW,int W,int nW){
  158139. lW=(W?lW:0);
  158140. nW=(W?nW:0);
  158141. {
  158142. float *windowLW=vwin[winno[lW]];
  158143. float *windowNW=vwin[winno[nW]];
  158144. long n=blocksizes[W];
  158145. long ln=blocksizes[lW];
  158146. long rn=blocksizes[nW];
  158147. long leftbegin=n/4-ln/4;
  158148. long leftend=leftbegin+ln/2;
  158149. long rightbegin=n/2+n/4-rn/4;
  158150. long rightend=rightbegin+rn/2;
  158151. int i,p;
  158152. for(i=0;i<leftbegin;i++)
  158153. d[i]=0.f;
  158154. for(p=0;i<leftend;i++,p++)
  158155. d[i]*=windowLW[p];
  158156. for(i=rightbegin,p=rn/2-1;i<rightend;i++,p--)
  158157. d[i]*=windowNW[p];
  158158. for(;i<n;i++)
  158159. d[i]=0.f;
  158160. }
  158161. }
  158162. #endif
  158163. /*** End of inlined file: window.c ***/
  158164. #else
  158165. #include <vorbis/vorbisenc.h>
  158166. #include <vorbis/codec.h>
  158167. #include <vorbis/vorbisfile.h>
  158168. #endif
  158169. }
  158170. #undef max
  158171. #undef min
  158172. BEGIN_JUCE_NAMESPACE
  158173. static const char* const oggFormatName = "Ogg-Vorbis file";
  158174. static const char* const oggExtensions[] = { ".ogg", 0 };
  158175. class OggReader : public AudioFormatReader
  158176. {
  158177. OggVorbisNamespace::OggVorbis_File ovFile;
  158178. OggVorbisNamespace::ov_callbacks callbacks;
  158179. AudioSampleBuffer reservoir;
  158180. int reservoirStart, samplesInReservoir;
  158181. public:
  158182. OggReader (InputStream* const inp)
  158183. : AudioFormatReader (inp, TRANS (oggFormatName)),
  158184. reservoir (2, 4096),
  158185. reservoirStart (0),
  158186. samplesInReservoir (0)
  158187. {
  158188. using namespace OggVorbisNamespace;
  158189. sampleRate = 0;
  158190. usesFloatingPointData = true;
  158191. callbacks.read_func = &oggReadCallback;
  158192. callbacks.seek_func = &oggSeekCallback;
  158193. callbacks.close_func = &oggCloseCallback;
  158194. callbacks.tell_func = &oggTellCallback;
  158195. const int err = ov_open_callbacks (input, &ovFile, 0, 0, callbacks);
  158196. if (err == 0)
  158197. {
  158198. vorbis_info* info = ov_info (&ovFile, -1);
  158199. lengthInSamples = (uint32) ov_pcm_total (&ovFile, -1);
  158200. numChannels = info->channels;
  158201. bitsPerSample = 16;
  158202. sampleRate = info->rate;
  158203. reservoir.setSize (numChannels,
  158204. (int) jmin (lengthInSamples, (int64) reservoir.getNumSamples()));
  158205. }
  158206. }
  158207. ~OggReader()
  158208. {
  158209. OggVorbisNamespace::ov_clear (&ovFile);
  158210. }
  158211. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  158212. int64 startSampleInFile, int numSamples)
  158213. {
  158214. while (numSamples > 0)
  158215. {
  158216. const int numAvailable = reservoirStart + samplesInReservoir - startSampleInFile;
  158217. if (startSampleInFile >= reservoirStart && numAvailable > 0)
  158218. {
  158219. // got a few samples overlapping, so use them before seeking..
  158220. const int numToUse = jmin (numSamples, numAvailable);
  158221. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  158222. if (destSamples[i] != 0)
  158223. memcpy (destSamples[i] + startOffsetInDestBuffer,
  158224. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  158225. sizeof (float) * numToUse);
  158226. startSampleInFile += numToUse;
  158227. numSamples -= numToUse;
  158228. startOffsetInDestBuffer += numToUse;
  158229. if (numSamples == 0)
  158230. break;
  158231. }
  158232. if (startSampleInFile < reservoirStart
  158233. || startSampleInFile + numSamples > reservoirStart + samplesInReservoir)
  158234. {
  158235. // buffer miss, so refill the reservoir
  158236. int bitStream = 0;
  158237. reservoirStart = jmax (0, (int) startSampleInFile);
  158238. samplesInReservoir = reservoir.getNumSamples();
  158239. if (reservoirStart != (int) OggVorbisNamespace::ov_pcm_tell (&ovFile))
  158240. OggVorbisNamespace::ov_pcm_seek (&ovFile, reservoirStart);
  158241. int offset = 0;
  158242. int numToRead = samplesInReservoir;
  158243. while (numToRead > 0)
  158244. {
  158245. float** dataIn = 0;
  158246. const int samps = OggVorbisNamespace::ov_read_float (&ovFile, &dataIn, numToRead, &bitStream);
  158247. if (samps <= 0)
  158248. break;
  158249. jassert (samps <= numToRead);
  158250. for (int i = jmin ((int) numChannels, reservoir.getNumChannels()); --i >= 0;)
  158251. {
  158252. memcpy (reservoir.getSampleData (i, offset),
  158253. dataIn[i],
  158254. sizeof (float) * samps);
  158255. }
  158256. numToRead -= samps;
  158257. offset += samps;
  158258. }
  158259. if (numToRead > 0)
  158260. reservoir.clear (offset, numToRead);
  158261. }
  158262. }
  158263. if (numSamples > 0)
  158264. {
  158265. for (int i = numDestChannels; --i >= 0;)
  158266. if (destSamples[i] != 0)
  158267. zeromem (destSamples[i] + startOffsetInDestBuffer,
  158268. sizeof (int) * numSamples);
  158269. }
  158270. return true;
  158271. }
  158272. static size_t oggReadCallback (void* ptr, size_t size, size_t nmemb, void* datasource)
  158273. {
  158274. return (size_t) (static_cast <InputStream*> (datasource)->read (ptr, (int) (size * nmemb)) / size);
  158275. }
  158276. static int oggSeekCallback (void* datasource, OggVorbisNamespace::ogg_int64_t offset, int whence)
  158277. {
  158278. InputStream* const in = static_cast <InputStream*> (datasource);
  158279. if (whence == SEEK_CUR)
  158280. offset += in->getPosition();
  158281. else if (whence == SEEK_END)
  158282. offset += in->getTotalLength();
  158283. in->setPosition (offset);
  158284. return 0;
  158285. }
  158286. static int oggCloseCallback (void*)
  158287. {
  158288. return 0;
  158289. }
  158290. static long oggTellCallback (void* datasource)
  158291. {
  158292. return (long) static_cast <InputStream*> (datasource)->getPosition();
  158293. }
  158294. juce_UseDebuggingNewOperator
  158295. };
  158296. class OggWriter : public AudioFormatWriter
  158297. {
  158298. OggVorbisNamespace::ogg_stream_state os;
  158299. OggVorbisNamespace::ogg_page og;
  158300. OggVorbisNamespace::ogg_packet op;
  158301. OggVorbisNamespace::vorbis_info vi;
  158302. OggVorbisNamespace::vorbis_comment vc;
  158303. OggVorbisNamespace::vorbis_dsp_state vd;
  158304. OggVorbisNamespace::vorbis_block vb;
  158305. public:
  158306. bool ok;
  158307. OggWriter (OutputStream* const out,
  158308. const double sampleRate,
  158309. const int numChannels,
  158310. const int bitsPerSample,
  158311. const int qualityIndex)
  158312. : AudioFormatWriter (out, TRANS (oggFormatName),
  158313. sampleRate,
  158314. numChannels,
  158315. bitsPerSample)
  158316. {
  158317. using namespace OggVorbisNamespace;
  158318. ok = false;
  158319. vorbis_info_init (&vi);
  158320. if (vorbis_encode_init_vbr (&vi,
  158321. numChannels,
  158322. (int) sampleRate,
  158323. jlimit (0.0f, 1.0f, qualityIndex * 0.5f)) == 0)
  158324. {
  158325. vorbis_comment_init (&vc);
  158326. if (JUCEApplication::getInstance() != 0)
  158327. vorbis_comment_add_tag (&vc, "ENCODER", const_cast <char*> (JUCEApplication::getInstance()->getApplicationName().toUTF8()));
  158328. vorbis_analysis_init (&vd, &vi);
  158329. vorbis_block_init (&vd, &vb);
  158330. ogg_stream_init (&os, Random::getSystemRandom().nextInt());
  158331. ogg_packet header;
  158332. ogg_packet header_comm;
  158333. ogg_packet header_code;
  158334. vorbis_analysis_headerout (&vd, &vc, &header, &header_comm, &header_code);
  158335. ogg_stream_packetin (&os, &header);
  158336. ogg_stream_packetin (&os, &header_comm);
  158337. ogg_stream_packetin (&os, &header_code);
  158338. for (;;)
  158339. {
  158340. if (ogg_stream_flush (&os, &og) == 0)
  158341. break;
  158342. output->write (og.header, og.header_len);
  158343. output->write (og.body, og.body_len);
  158344. }
  158345. ok = true;
  158346. }
  158347. }
  158348. ~OggWriter()
  158349. {
  158350. using namespace OggVorbisNamespace;
  158351. if (ok)
  158352. {
  158353. // write a zero-length packet to show ogg that we're finished..
  158354. write (0, 0);
  158355. ogg_stream_clear (&os);
  158356. vorbis_block_clear (&vb);
  158357. vorbis_dsp_clear (&vd);
  158358. vorbis_comment_clear (&vc);
  158359. vorbis_info_clear (&vi);
  158360. output->flush();
  158361. }
  158362. else
  158363. {
  158364. vorbis_info_clear (&vi);
  158365. output = 0; // to stop the base class deleting this, as it needs to be returned
  158366. // to the caller of createWriter()
  158367. }
  158368. }
  158369. bool write (const int** samplesToWrite, int numSamples)
  158370. {
  158371. using namespace OggVorbisNamespace;
  158372. if (! ok)
  158373. return false;
  158374. if (numSamples > 0)
  158375. {
  158376. const double gain = 1.0 / 0x80000000u;
  158377. float** const vorbisBuffer = vorbis_analysis_buffer (&vd, numSamples);
  158378. for (int i = numChannels; --i >= 0;)
  158379. {
  158380. float* const dst = vorbisBuffer[i];
  158381. const int* const src = samplesToWrite [i];
  158382. if (src != 0 && dst != 0)
  158383. {
  158384. for (int j = 0; j < numSamples; ++j)
  158385. dst[j] = (float) (src[j] * gain);
  158386. }
  158387. }
  158388. }
  158389. vorbis_analysis_wrote (&vd, numSamples);
  158390. while (vorbis_analysis_blockout (&vd, &vb) == 1)
  158391. {
  158392. vorbis_analysis (&vb, 0);
  158393. vorbis_bitrate_addblock (&vb);
  158394. while (vorbis_bitrate_flushpacket (&vd, &op))
  158395. {
  158396. ogg_stream_packetin (&os, &op);
  158397. for (;;)
  158398. {
  158399. if (ogg_stream_pageout (&os, &og) == 0)
  158400. break;
  158401. output->write (og.header, og.header_len);
  158402. output->write (og.body, og.body_len);
  158403. if (ogg_page_eos (&og))
  158404. break;
  158405. }
  158406. }
  158407. }
  158408. return true;
  158409. }
  158410. juce_UseDebuggingNewOperator
  158411. };
  158412. OggVorbisAudioFormat::OggVorbisAudioFormat()
  158413. : AudioFormat (TRANS (oggFormatName), StringArray (oggExtensions))
  158414. {
  158415. }
  158416. OggVorbisAudioFormat::~OggVorbisAudioFormat()
  158417. {
  158418. }
  158419. const Array <int> OggVorbisAudioFormat::getPossibleSampleRates()
  158420. {
  158421. const int rates[] = { 22050, 32000, 44100, 48000, 0 };
  158422. return Array <int> (rates);
  158423. }
  158424. const Array <int> OggVorbisAudioFormat::getPossibleBitDepths()
  158425. {
  158426. Array <int> depths;
  158427. depths.add (32);
  158428. return depths;
  158429. }
  158430. bool OggVorbisAudioFormat::canDoStereo()
  158431. {
  158432. return true;
  158433. }
  158434. bool OggVorbisAudioFormat::canDoMono()
  158435. {
  158436. return true;
  158437. }
  158438. AudioFormatReader* OggVorbisAudioFormat::createReaderFor (InputStream* in,
  158439. const bool deleteStreamIfOpeningFails)
  158440. {
  158441. ScopedPointer <OggReader> r (new OggReader (in));
  158442. if (r->sampleRate != 0)
  158443. return r.release();
  158444. if (! deleteStreamIfOpeningFails)
  158445. r->input = 0;
  158446. return 0;
  158447. }
  158448. AudioFormatWriter* OggVorbisAudioFormat::createWriterFor (OutputStream* out,
  158449. double sampleRate,
  158450. unsigned int numChannels,
  158451. int bitsPerSample,
  158452. const StringPairArray& /*metadataValues*/,
  158453. int qualityOptionIndex)
  158454. {
  158455. ScopedPointer <OggWriter> w (new OggWriter (out,
  158456. sampleRate,
  158457. numChannels,
  158458. bitsPerSample,
  158459. qualityOptionIndex));
  158460. return w->ok ? w.release() : 0;
  158461. }
  158462. bool OggVorbisAudioFormat::isCompressed()
  158463. {
  158464. return true;
  158465. }
  158466. const StringArray OggVorbisAudioFormat::getQualityOptions()
  158467. {
  158468. StringArray s;
  158469. s.add ("Low Quality");
  158470. s.add ("Medium Quality");
  158471. s.add ("High Quality");
  158472. return s;
  158473. }
  158474. int OggVorbisAudioFormat::estimateOggFileQuality (const File& source)
  158475. {
  158476. FileInputStream* const in = source.createInputStream();
  158477. if (in != 0)
  158478. {
  158479. ScopedPointer <AudioFormatReader> r (createReaderFor (in, true));
  158480. if (r != 0)
  158481. {
  158482. const int64 numSamps = r->lengthInSamples;
  158483. r = 0;
  158484. const int64 fileNumSamps = source.getSize() / 4;
  158485. const double ratio = numSamps / (double) fileNumSamps;
  158486. if (ratio > 12.0)
  158487. return 0;
  158488. else if (ratio > 6.0)
  158489. return 1;
  158490. else
  158491. return 2;
  158492. }
  158493. }
  158494. return 1;
  158495. }
  158496. END_JUCE_NAMESPACE
  158497. #endif
  158498. /*** End of inlined file: juce_OggVorbisAudioFormat.cpp ***/
  158499. #endif
  158500. #if JUCE_BUILD_CORE && ! JUCE_ONLY_BUILD_CORE_LIBRARY // do these in the core section to help balance the sizes
  158501. /*** Start of inlined file: juce_JPEGLoader.cpp ***/
  158502. #if JUCE_MSVC
  158503. #pragma warning (push)
  158504. #endif
  158505. namespace jpeglibNamespace
  158506. {
  158507. #if JUCE_INCLUDE_JPEGLIB_CODE
  158508. #if JUCE_MINGW
  158509. typedef unsigned char boolean;
  158510. #endif
  158511. extern "C"
  158512. {
  158513. #define JPEG_INTERNALS
  158514. #undef FAR
  158515. /*** Start of inlined file: jpeglib.h ***/
  158516. #ifndef JPEGLIB_H
  158517. #define JPEGLIB_H
  158518. /*
  158519. * First we include the configuration files that record how this
  158520. * installation of the JPEG library is set up. jconfig.h can be
  158521. * generated automatically for many systems. jmorecfg.h contains
  158522. * manual configuration options that most people need not worry about.
  158523. */
  158524. #ifndef JCONFIG_INCLUDED /* in case jinclude.h already did */
  158525. /*** Start of inlined file: jconfig.h ***/
  158526. /* see jconfig.doc for explanations */
  158527. // disable all the warnings under MSVC
  158528. #ifdef _MSC_VER
  158529. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  158530. #endif
  158531. #ifdef __BORLANDC__
  158532. #pragma warn -8057
  158533. #pragma warn -8019
  158534. #pragma warn -8004
  158535. #pragma warn -8008
  158536. #endif
  158537. #define HAVE_PROTOTYPES
  158538. #define HAVE_UNSIGNED_CHAR
  158539. #define HAVE_UNSIGNED_SHORT
  158540. /* #define void char */
  158541. /* #define const */
  158542. #undef CHAR_IS_UNSIGNED
  158543. #define HAVE_STDDEF_H
  158544. #define HAVE_STDLIB_H
  158545. #undef NEED_BSD_STRINGS
  158546. #undef NEED_SYS_TYPES_H
  158547. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  158548. #undef NEED_SHORT_EXTERNAL_NAMES
  158549. #undef INCOMPLETE_TYPES_BROKEN
  158550. /* Define "boolean" as unsigned char, not int, per Windows custom */
  158551. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  158552. typedef unsigned char boolean;
  158553. #endif
  158554. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  158555. #ifdef JPEG_INTERNALS
  158556. #undef RIGHT_SHIFT_IS_UNSIGNED
  158557. #endif /* JPEG_INTERNALS */
  158558. #ifdef JPEG_CJPEG_DJPEG
  158559. #define BMP_SUPPORTED /* BMP image file format */
  158560. #define GIF_SUPPORTED /* GIF image file format */
  158561. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  158562. #undef RLE_SUPPORTED /* Utah RLE image file format */
  158563. #define TARGA_SUPPORTED /* Targa image file format */
  158564. #define TWO_FILE_COMMANDLINE /* optional */
  158565. #define USE_SETMODE /* Microsoft has setmode() */
  158566. #undef NEED_SIGNAL_CATCHER
  158567. #undef DONT_USE_B_MODE
  158568. #undef PROGRESS_REPORT /* optional */
  158569. #endif /* JPEG_CJPEG_DJPEG */
  158570. /*** End of inlined file: jconfig.h ***/
  158571. /* widely used configuration options */
  158572. #endif
  158573. /*** Start of inlined file: jmorecfg.h ***/
  158574. /*
  158575. * Define BITS_IN_JSAMPLE as either
  158576. * 8 for 8-bit sample values (the usual setting)
  158577. * 12 for 12-bit sample values
  158578. * Only 8 and 12 are legal data precisions for lossy JPEG according to the
  158579. * JPEG standard, and the IJG code does not support anything else!
  158580. * We do not support run-time selection of data precision, sorry.
  158581. */
  158582. #define BITS_IN_JSAMPLE 8 /* use 8 or 12 */
  158583. /*
  158584. * Maximum number of components (color channels) allowed in JPEG image.
  158585. * To meet the letter of the JPEG spec, set this to 255. However, darn
  158586. * few applications need more than 4 channels (maybe 5 for CMYK + alpha
  158587. * mask). We recommend 10 as a reasonable compromise; use 4 if you are
  158588. * really short on memory. (Each allowed component costs a hundred or so
  158589. * bytes of storage, whether actually used in an image or not.)
  158590. */
  158591. #define MAX_COMPONENTS 10 /* maximum number of image components */
  158592. /*
  158593. * Basic data types.
  158594. * You may need to change these if you have a machine with unusual data
  158595. * type sizes; for example, "char" not 8 bits, "short" not 16 bits,
  158596. * or "long" not 32 bits. We don't care whether "int" is 16 or 32 bits,
  158597. * but it had better be at least 16.
  158598. */
  158599. /* Representation of a single sample (pixel element value).
  158600. * We frequently allocate large arrays of these, so it's important to keep
  158601. * them small. But if you have memory to burn and access to char or short
  158602. * arrays is very slow on your hardware, you might want to change these.
  158603. */
  158604. #if BITS_IN_JSAMPLE == 8
  158605. /* JSAMPLE should be the smallest type that will hold the values 0..255.
  158606. * You can use a signed char by having GETJSAMPLE mask it with 0xFF.
  158607. */
  158608. #ifdef HAVE_UNSIGNED_CHAR
  158609. typedef unsigned char JSAMPLE;
  158610. #define GETJSAMPLE(value) ((int) (value))
  158611. #else /* not HAVE_UNSIGNED_CHAR */
  158612. typedef char JSAMPLE;
  158613. #ifdef CHAR_IS_UNSIGNED
  158614. #define GETJSAMPLE(value) ((int) (value))
  158615. #else
  158616. #define GETJSAMPLE(value) ((int) (value) & 0xFF)
  158617. #endif /* CHAR_IS_UNSIGNED */
  158618. #endif /* HAVE_UNSIGNED_CHAR */
  158619. #define MAXJSAMPLE 255
  158620. #define CENTERJSAMPLE 128
  158621. #endif /* BITS_IN_JSAMPLE == 8 */
  158622. #if BITS_IN_JSAMPLE == 12
  158623. /* JSAMPLE should be the smallest type that will hold the values 0..4095.
  158624. * On nearly all machines "short" will do nicely.
  158625. */
  158626. typedef short JSAMPLE;
  158627. #define GETJSAMPLE(value) ((int) (value))
  158628. #define MAXJSAMPLE 4095
  158629. #define CENTERJSAMPLE 2048
  158630. #endif /* BITS_IN_JSAMPLE == 12 */
  158631. /* Representation of a DCT frequency coefficient.
  158632. * This should be a signed value of at least 16 bits; "short" is usually OK.
  158633. * Again, we allocate large arrays of these, but you can change to int
  158634. * if you have memory to burn and "short" is really slow.
  158635. */
  158636. typedef short JCOEF;
  158637. /* Compressed datastreams are represented as arrays of JOCTET.
  158638. * These must be EXACTLY 8 bits wide, at least once they are written to
  158639. * external storage. Note that when using the stdio data source/destination
  158640. * managers, this is also the data type passed to fread/fwrite.
  158641. */
  158642. #ifdef HAVE_UNSIGNED_CHAR
  158643. typedef unsigned char JOCTET;
  158644. #define GETJOCTET(value) (value)
  158645. #else /* not HAVE_UNSIGNED_CHAR */
  158646. typedef char JOCTET;
  158647. #ifdef CHAR_IS_UNSIGNED
  158648. #define GETJOCTET(value) (value)
  158649. #else
  158650. #define GETJOCTET(value) ((value) & 0xFF)
  158651. #endif /* CHAR_IS_UNSIGNED */
  158652. #endif /* HAVE_UNSIGNED_CHAR */
  158653. /* These typedefs are used for various table entries and so forth.
  158654. * They must be at least as wide as specified; but making them too big
  158655. * won't cost a huge amount of memory, so we don't provide special
  158656. * extraction code like we did for JSAMPLE. (In other words, these
  158657. * typedefs live at a different point on the speed/space tradeoff curve.)
  158658. */
  158659. /* UINT8 must hold at least the values 0..255. */
  158660. #ifdef HAVE_UNSIGNED_CHAR
  158661. typedef unsigned char UINT8;
  158662. #else /* not HAVE_UNSIGNED_CHAR */
  158663. #ifdef CHAR_IS_UNSIGNED
  158664. typedef char UINT8;
  158665. #else /* not CHAR_IS_UNSIGNED */
  158666. typedef short UINT8;
  158667. #endif /* CHAR_IS_UNSIGNED */
  158668. #endif /* HAVE_UNSIGNED_CHAR */
  158669. /* UINT16 must hold at least the values 0..65535. */
  158670. #ifdef HAVE_UNSIGNED_SHORT
  158671. typedef unsigned short UINT16;
  158672. #else /* not HAVE_UNSIGNED_SHORT */
  158673. typedef unsigned int UINT16;
  158674. #endif /* HAVE_UNSIGNED_SHORT */
  158675. /* INT16 must hold at least the values -32768..32767. */
  158676. #ifndef XMD_H /* X11/xmd.h correctly defines INT16 */
  158677. typedef short INT16;
  158678. #endif
  158679. /* INT32 must hold at least signed 32-bit values. */
  158680. #ifndef XMD_H /* X11/xmd.h correctly defines INT32 */
  158681. typedef long INT32;
  158682. #endif
  158683. /* Datatype used for image dimensions. The JPEG standard only supports
  158684. * images up to 64K*64K due to 16-bit fields in SOF markers. Therefore
  158685. * "unsigned int" is sufficient on all machines. However, if you need to
  158686. * handle larger images and you don't mind deviating from the spec, you
  158687. * can change this datatype.
  158688. */
  158689. typedef unsigned int JDIMENSION;
  158690. #define JPEG_MAX_DIMENSION 65500L /* a tad under 64K to prevent overflows */
  158691. /* These macros are used in all function definitions and extern declarations.
  158692. * You could modify them if you need to change function linkage conventions;
  158693. * in particular, you'll need to do that to make the library a Windows DLL.
  158694. * Another application is to make all functions global for use with debuggers
  158695. * or code profilers that require it.
  158696. */
  158697. /* a function called through method pointers: */
  158698. #define METHODDEF(type) static type
  158699. /* a function used only in its module: */
  158700. #define LOCAL(type) static type
  158701. /* a function referenced thru EXTERNs: */
  158702. #define GLOBAL(type) type
  158703. /* a reference to a GLOBAL function: */
  158704. #define EXTERN(type) extern type
  158705. /* This macro is used to declare a "method", that is, a function pointer.
  158706. * We want to supply prototype parameters if the compiler can cope.
  158707. * Note that the arglist parameter must be parenthesized!
  158708. * Again, you can customize this if you need special linkage keywords.
  158709. */
  158710. #ifdef HAVE_PROTOTYPES
  158711. #define JMETHOD(type,methodname,arglist) type (*methodname) arglist
  158712. #else
  158713. #define JMETHOD(type,methodname,arglist) type (*methodname) ()
  158714. #endif
  158715. /* Here is the pseudo-keyword for declaring pointers that must be "far"
  158716. * on 80x86 machines. Most of the specialized coding for 80x86 is handled
  158717. * by just saying "FAR *" where such a pointer is needed. In a few places
  158718. * explicit coding is needed; see uses of the NEED_FAR_POINTERS symbol.
  158719. */
  158720. #ifdef NEED_FAR_POINTERS
  158721. #define FAR far
  158722. #else
  158723. #define FAR
  158724. #endif
  158725. /*
  158726. * On a few systems, type boolean and/or its values FALSE, TRUE may appear
  158727. * in standard header files. Or you may have conflicts with application-
  158728. * specific header files that you want to include together with these files.
  158729. * Defining HAVE_BOOLEAN before including jpeglib.h should make it work.
  158730. */
  158731. #ifndef HAVE_BOOLEAN
  158732. typedef int boolean;
  158733. #endif
  158734. #ifndef FALSE /* in case these macros already exist */
  158735. #define FALSE 0 /* values of boolean */
  158736. #endif
  158737. #ifndef TRUE
  158738. #define TRUE 1
  158739. #endif
  158740. /*
  158741. * The remaining options affect code selection within the JPEG library,
  158742. * but they don't need to be visible to most applications using the library.
  158743. * To minimize application namespace pollution, the symbols won't be
  158744. * defined unless JPEG_INTERNALS or JPEG_INTERNAL_OPTIONS has been defined.
  158745. */
  158746. #ifdef JPEG_INTERNALS
  158747. #define JPEG_INTERNAL_OPTIONS
  158748. #endif
  158749. #ifdef JPEG_INTERNAL_OPTIONS
  158750. /*
  158751. * These defines indicate whether to include various optional functions.
  158752. * Undefining some of these symbols will produce a smaller but less capable
  158753. * library. Note that you can leave certain source files out of the
  158754. * compilation/linking process if you've #undef'd the corresponding symbols.
  158755. * (You may HAVE to do that if your compiler doesn't like null source files.)
  158756. */
  158757. /* Arithmetic coding is unsupported for legal reasons. Complaints to IBM. */
  158758. /* Capability options common to encoder and decoder: */
  158759. #define DCT_ISLOW_SUPPORTED /* slow but accurate integer algorithm */
  158760. #define DCT_IFAST_SUPPORTED /* faster, less accurate integer method */
  158761. #define DCT_FLOAT_SUPPORTED /* floating-point: accurate, fast on fast HW */
  158762. /* Encoder capability options: */
  158763. #undef C_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  158764. #define C_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  158765. #define C_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  158766. #define ENTROPY_OPT_SUPPORTED /* Optimization of entropy coding parms? */
  158767. /* Note: if you selected 12-bit data precision, it is dangerous to turn off
  158768. * ENTROPY_OPT_SUPPORTED. The standard Huffman tables are only good for 8-bit
  158769. * precision, so jchuff.c normally uses entropy optimization to compute
  158770. * usable tables for higher precision. If you don't want to do optimization,
  158771. * you'll have to supply different default Huffman tables.
  158772. * The exact same statements apply for progressive JPEG: the default tables
  158773. * don't work for progressive mode. (This may get fixed, however.)
  158774. */
  158775. #define INPUT_SMOOTHING_SUPPORTED /* Input image smoothing option? */
  158776. /* Decoder capability options: */
  158777. #undef D_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  158778. #define D_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  158779. #define D_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  158780. #define SAVE_MARKERS_SUPPORTED /* jpeg_save_markers() needed? */
  158781. #define BLOCK_SMOOTHING_SUPPORTED /* Block smoothing? (Progressive only) */
  158782. #define IDCT_SCALING_SUPPORTED /* Output rescaling via IDCT? */
  158783. #undef UPSAMPLE_SCALING_SUPPORTED /* Output rescaling at upsample stage? */
  158784. #define UPSAMPLE_MERGING_SUPPORTED /* Fast path for sloppy upsampling? */
  158785. #define QUANT_1PASS_SUPPORTED /* 1-pass color quantization? */
  158786. #define QUANT_2PASS_SUPPORTED /* 2-pass color quantization? */
  158787. /* more capability options later, no doubt */
  158788. /*
  158789. * Ordering of RGB data in scanlines passed to or from the application.
  158790. * If your application wants to deal with data in the order B,G,R, just
  158791. * change these macros. You can also deal with formats such as R,G,B,X
  158792. * (one extra byte per pixel) by changing RGB_PIXELSIZE. Note that changing
  158793. * the offsets will also change the order in which colormap data is organized.
  158794. * RESTRICTIONS:
  158795. * 1. The sample applications cjpeg,djpeg do NOT support modified RGB formats.
  158796. * 2. These macros only affect RGB<=>YCbCr color conversion, so they are not
  158797. * useful if you are using JPEG color spaces other than YCbCr or grayscale.
  158798. * 3. The color quantizer modules will not behave desirably if RGB_PIXELSIZE
  158799. * is not 3 (they don't understand about dummy color components!). So you
  158800. * can't use color quantization if you change that value.
  158801. */
  158802. #define RGB_RED 0 /* Offset of Red in an RGB scanline element */
  158803. #define RGB_GREEN 1 /* Offset of Green */
  158804. #define RGB_BLUE 2 /* Offset of Blue */
  158805. #define RGB_PIXELSIZE 3 /* JSAMPLEs per RGB scanline element */
  158806. /* Definitions for speed-related optimizations. */
  158807. /* If your compiler supports inline functions, define INLINE
  158808. * as the inline keyword; otherwise define it as empty.
  158809. */
  158810. #ifndef INLINE
  158811. #ifdef __GNUC__ /* for instance, GNU C knows about inline */
  158812. #define INLINE __inline__
  158813. #endif
  158814. #ifndef INLINE
  158815. #define INLINE /* default is to define it as empty */
  158816. #endif
  158817. #endif
  158818. /* On some machines (notably 68000 series) "int" is 32 bits, but multiplying
  158819. * two 16-bit shorts is faster than multiplying two ints. Define MULTIPLIER
  158820. * as short on such a machine. MULTIPLIER must be at least 16 bits wide.
  158821. */
  158822. #ifndef MULTIPLIER
  158823. #define MULTIPLIER int /* type for fastest integer multiply */
  158824. #endif
  158825. /* FAST_FLOAT should be either float or double, whichever is done faster
  158826. * by your compiler. (Note that this type is only used in the floating point
  158827. * DCT routines, so it only matters if you've defined DCT_FLOAT_SUPPORTED.)
  158828. * Typically, float is faster in ANSI C compilers, while double is faster in
  158829. * pre-ANSI compilers (because they insist on converting to double anyway).
  158830. * The code below therefore chooses float if we have ANSI-style prototypes.
  158831. */
  158832. #ifndef FAST_FLOAT
  158833. #ifdef HAVE_PROTOTYPES
  158834. #define FAST_FLOAT float
  158835. #else
  158836. #define FAST_FLOAT double
  158837. #endif
  158838. #endif
  158839. #endif /* JPEG_INTERNAL_OPTIONS */
  158840. /*** End of inlined file: jmorecfg.h ***/
  158841. /* seldom changed options */
  158842. /* Version ID for the JPEG library.
  158843. * Might be useful for tests like "#if JPEG_LIB_VERSION >= 60".
  158844. */
  158845. #define JPEG_LIB_VERSION 62 /* Version 6b */
  158846. /* Various constants determining the sizes of things.
  158847. * All of these are specified by the JPEG standard, so don't change them
  158848. * if you want to be compatible.
  158849. */
  158850. #define DCTSIZE 8 /* The basic DCT block is 8x8 samples */
  158851. #define DCTSIZE2 64 /* DCTSIZE squared; # of elements in a block */
  158852. #define NUM_QUANT_TBLS 4 /* Quantization tables are numbered 0..3 */
  158853. #define NUM_HUFF_TBLS 4 /* Huffman tables are numbered 0..3 */
  158854. #define NUM_ARITH_TBLS 16 /* Arith-coding tables are numbered 0..15 */
  158855. #define MAX_COMPS_IN_SCAN 4 /* JPEG limit on # of components in one scan */
  158856. #define MAX_SAMP_FACTOR 4 /* JPEG limit on sampling factors */
  158857. /* Unfortunately, some bozo at Adobe saw no reason to be bound by the standard;
  158858. * the PostScript DCT filter can emit files with many more than 10 blocks/MCU.
  158859. * If you happen to run across such a file, you can up D_MAX_BLOCKS_IN_MCU
  158860. * to handle it. We even let you do this from the jconfig.h file. However,
  158861. * we strongly discourage changing C_MAX_BLOCKS_IN_MCU; just because Adobe
  158862. * sometimes emits noncompliant files doesn't mean you should too.
  158863. */
  158864. #define C_MAX_BLOCKS_IN_MCU 10 /* compressor's limit on blocks per MCU */
  158865. #ifndef D_MAX_BLOCKS_IN_MCU
  158866. #define D_MAX_BLOCKS_IN_MCU 10 /* decompressor's limit on blocks per MCU */
  158867. #endif
  158868. /* Data structures for images (arrays of samples and of DCT coefficients).
  158869. * On 80x86 machines, the image arrays are too big for near pointers,
  158870. * but the pointer arrays can fit in near memory.
  158871. */
  158872. typedef JSAMPLE FAR *JSAMPROW; /* ptr to one image row of pixel samples. */
  158873. typedef JSAMPROW *JSAMPARRAY; /* ptr to some rows (a 2-D sample array) */
  158874. typedef JSAMPARRAY *JSAMPIMAGE; /* a 3-D sample array: top index is color */
  158875. typedef JCOEF JBLOCK[DCTSIZE2]; /* one block of coefficients */
  158876. typedef JBLOCK FAR *JBLOCKROW; /* pointer to one row of coefficient blocks */
  158877. typedef JBLOCKROW *JBLOCKARRAY; /* a 2-D array of coefficient blocks */
  158878. typedef JBLOCKARRAY *JBLOCKIMAGE; /* a 3-D array of coefficient blocks */
  158879. typedef JCOEF FAR *JCOEFPTR; /* useful in a couple of places */
  158880. /* Types for JPEG compression parameters and working tables. */
  158881. /* DCT coefficient quantization tables. */
  158882. typedef struct {
  158883. /* This array gives the coefficient quantizers in natural array order
  158884. * (not the zigzag order in which they are stored in a JPEG DQT marker).
  158885. * CAUTION: IJG versions prior to v6a kept this array in zigzag order.
  158886. */
  158887. UINT16 quantval[DCTSIZE2]; /* quantization step for each coefficient */
  158888. /* This field is used only during compression. It's initialized FALSE when
  158889. * the table is created, and set TRUE when it's been output to the file.
  158890. * You could suppress output of a table by setting this to TRUE.
  158891. * (See jpeg_suppress_tables for an example.)
  158892. */
  158893. boolean sent_table; /* TRUE when table has been output */
  158894. } JQUANT_TBL;
  158895. /* Huffman coding tables. */
  158896. typedef struct {
  158897. /* These two fields directly represent the contents of a JPEG DHT marker */
  158898. UINT8 bits[17]; /* bits[k] = # of symbols with codes of */
  158899. /* length k bits; bits[0] is unused */
  158900. UINT8 huffval[256]; /* The symbols, in order of incr code length */
  158901. /* This field is used only during compression. It's initialized FALSE when
  158902. * the table is created, and set TRUE when it's been output to the file.
  158903. * You could suppress output of a table by setting this to TRUE.
  158904. * (See jpeg_suppress_tables for an example.)
  158905. */
  158906. boolean sent_table; /* TRUE when table has been output */
  158907. } JHUFF_TBL;
  158908. /* Basic info about one component (color channel). */
  158909. typedef struct {
  158910. /* These values are fixed over the whole image. */
  158911. /* For compression, they must be supplied by parameter setup; */
  158912. /* for decompression, they are read from the SOF marker. */
  158913. int component_id; /* identifier for this component (0..255) */
  158914. int component_index; /* its index in SOF or cinfo->comp_info[] */
  158915. int h_samp_factor; /* horizontal sampling factor (1..4) */
  158916. int v_samp_factor; /* vertical sampling factor (1..4) */
  158917. int quant_tbl_no; /* quantization table selector (0..3) */
  158918. /* These values may vary between scans. */
  158919. /* For compression, they must be supplied by parameter setup; */
  158920. /* for decompression, they are read from the SOS marker. */
  158921. /* The decompressor output side may not use these variables. */
  158922. int dc_tbl_no; /* DC entropy table selector (0..3) */
  158923. int ac_tbl_no; /* AC entropy table selector (0..3) */
  158924. /* Remaining fields should be treated as private by applications. */
  158925. /* These values are computed during compression or decompression startup: */
  158926. /* Component's size in DCT blocks.
  158927. * Any dummy blocks added to complete an MCU are not counted; therefore
  158928. * these values do not depend on whether a scan is interleaved or not.
  158929. */
  158930. JDIMENSION width_in_blocks;
  158931. JDIMENSION height_in_blocks;
  158932. /* Size of a DCT block in samples. Always DCTSIZE for compression.
  158933. * For decompression this is the size of the output from one DCT block,
  158934. * reflecting any scaling we choose to apply during the IDCT step.
  158935. * Values of 1,2,4,8 are likely to be supported. Note that different
  158936. * components may receive different IDCT scalings.
  158937. */
  158938. int DCT_scaled_size;
  158939. /* The downsampled dimensions are the component's actual, unpadded number
  158940. * of samples at the main buffer (preprocessing/compression interface), thus
  158941. * downsampled_width = ceil(image_width * Hi/Hmax)
  158942. * and similarly for height. For decompression, IDCT scaling is included, so
  158943. * downsampled_width = ceil(image_width * Hi/Hmax * DCT_scaled_size/DCTSIZE)
  158944. */
  158945. JDIMENSION downsampled_width; /* actual width in samples */
  158946. JDIMENSION downsampled_height; /* actual height in samples */
  158947. /* This flag is used only for decompression. In cases where some of the
  158948. * components will be ignored (eg grayscale output from YCbCr image),
  158949. * we can skip most computations for the unused components.
  158950. */
  158951. boolean component_needed; /* do we need the value of this component? */
  158952. /* These values are computed before starting a scan of the component. */
  158953. /* The decompressor output side may not use these variables. */
  158954. int MCU_width; /* number of blocks per MCU, horizontally */
  158955. int MCU_height; /* number of blocks per MCU, vertically */
  158956. int MCU_blocks; /* MCU_width * MCU_height */
  158957. int MCU_sample_width; /* MCU width in samples, MCU_width*DCT_scaled_size */
  158958. int last_col_width; /* # of non-dummy blocks across in last MCU */
  158959. int last_row_height; /* # of non-dummy blocks down in last MCU */
  158960. /* Saved quantization table for component; NULL if none yet saved.
  158961. * See jdinput.c comments about the need for this information.
  158962. * This field is currently used only for decompression.
  158963. */
  158964. JQUANT_TBL * quant_table;
  158965. /* Private per-component storage for DCT or IDCT subsystem. */
  158966. void * dct_table;
  158967. } jpeg_component_info;
  158968. /* The script for encoding a multiple-scan file is an array of these: */
  158969. typedef struct {
  158970. int comps_in_scan; /* number of components encoded in this scan */
  158971. int component_index[MAX_COMPS_IN_SCAN]; /* their SOF/comp_info[] indexes */
  158972. int Ss, Se; /* progressive JPEG spectral selection parms */
  158973. int Ah, Al; /* progressive JPEG successive approx. parms */
  158974. } jpeg_scan_info;
  158975. /* The decompressor can save APPn and COM markers in a list of these: */
  158976. typedef struct jpeg_marker_struct FAR * jpeg_saved_marker_ptr;
  158977. struct jpeg_marker_struct {
  158978. jpeg_saved_marker_ptr next; /* next in list, or NULL */
  158979. UINT8 marker; /* marker code: JPEG_COM, or JPEG_APP0+n */
  158980. unsigned int original_length; /* # bytes of data in the file */
  158981. unsigned int data_length; /* # bytes of data saved at data[] */
  158982. JOCTET FAR * data; /* the data contained in the marker */
  158983. /* the marker length word is not counted in data_length or original_length */
  158984. };
  158985. /* Known color spaces. */
  158986. typedef enum {
  158987. JCS_UNKNOWN, /* error/unspecified */
  158988. JCS_GRAYSCALE, /* monochrome */
  158989. JCS_RGB, /* red/green/blue */
  158990. JCS_YCbCr, /* Y/Cb/Cr (also known as YUV) */
  158991. JCS_CMYK, /* C/M/Y/K */
  158992. JCS_YCCK /* Y/Cb/Cr/K */
  158993. } J_COLOR_SPACE;
  158994. /* DCT/IDCT algorithm options. */
  158995. typedef enum {
  158996. JDCT_ISLOW, /* slow but accurate integer algorithm */
  158997. JDCT_IFAST, /* faster, less accurate integer method */
  158998. JDCT_FLOAT /* floating-point: accurate, fast on fast HW */
  158999. } J_DCT_METHOD;
  159000. #ifndef JDCT_DEFAULT /* may be overridden in jconfig.h */
  159001. #define JDCT_DEFAULT JDCT_ISLOW
  159002. #endif
  159003. #ifndef JDCT_FASTEST /* may be overridden in jconfig.h */
  159004. #define JDCT_FASTEST JDCT_IFAST
  159005. #endif
  159006. /* Dithering options for decompression. */
  159007. typedef enum {
  159008. JDITHER_NONE, /* no dithering */
  159009. JDITHER_ORDERED, /* simple ordered dither */
  159010. JDITHER_FS /* Floyd-Steinberg error diffusion dither */
  159011. } J_DITHER_MODE;
  159012. /* Common fields between JPEG compression and decompression master structs. */
  159013. #define jpeg_common_fields \
  159014. struct jpeg_error_mgr * err; /* Error handler module */\
  159015. struct jpeg_memory_mgr * mem; /* Memory manager module */\
  159016. struct jpeg_progress_mgr * progress; /* Progress monitor, or NULL if none */\
  159017. void * client_data; /* Available for use by application */\
  159018. boolean is_decompressor; /* So common code can tell which is which */\
  159019. int global_state /* For checking call sequence validity */
  159020. /* Routines that are to be used by both halves of the library are declared
  159021. * to receive a pointer to this structure. There are no actual instances of
  159022. * jpeg_common_struct, only of jpeg_compress_struct and jpeg_decompress_struct.
  159023. */
  159024. struct jpeg_common_struct {
  159025. jpeg_common_fields; /* Fields common to both master struct types */
  159026. /* Additional fields follow in an actual jpeg_compress_struct or
  159027. * jpeg_decompress_struct. All three structs must agree on these
  159028. * initial fields! (This would be a lot cleaner in C++.)
  159029. */
  159030. };
  159031. typedef struct jpeg_common_struct * j_common_ptr;
  159032. typedef struct jpeg_compress_struct * j_compress_ptr;
  159033. typedef struct jpeg_decompress_struct * j_decompress_ptr;
  159034. /* Master record for a compression instance */
  159035. struct jpeg_compress_struct {
  159036. jpeg_common_fields; /* Fields shared with jpeg_decompress_struct */
  159037. /* Destination for compressed data */
  159038. struct jpeg_destination_mgr * dest;
  159039. /* Description of source image --- these fields must be filled in by
  159040. * outer application before starting compression. in_color_space must
  159041. * be correct before you can even call jpeg_set_defaults().
  159042. */
  159043. JDIMENSION image_width; /* input image width */
  159044. JDIMENSION image_height; /* input image height */
  159045. int input_components; /* # of color components in input image */
  159046. J_COLOR_SPACE in_color_space; /* colorspace of input image */
  159047. double input_gamma; /* image gamma of input image */
  159048. /* Compression parameters --- these fields must be set before calling
  159049. * jpeg_start_compress(). We recommend calling jpeg_set_defaults() to
  159050. * initialize everything to reasonable defaults, then changing anything
  159051. * the application specifically wants to change. That way you won't get
  159052. * burnt when new parameters are added. Also note that there are several
  159053. * helper routines to simplify changing parameters.
  159054. */
  159055. int data_precision; /* bits of precision in image data */
  159056. int num_components; /* # of color components in JPEG image */
  159057. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  159058. jpeg_component_info * comp_info;
  159059. /* comp_info[i] describes component that appears i'th in SOF */
  159060. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  159061. /* ptrs to coefficient quantization tables, or NULL if not defined */
  159062. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  159063. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  159064. /* ptrs to Huffman coding tables, or NULL if not defined */
  159065. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  159066. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  159067. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  159068. int num_scans; /* # of entries in scan_info array */
  159069. const jpeg_scan_info * scan_info; /* script for multi-scan file, or NULL */
  159070. /* The default value of scan_info is NULL, which causes a single-scan
  159071. * sequential JPEG file to be emitted. To create a multi-scan file,
  159072. * set num_scans and scan_info to point to an array of scan definitions.
  159073. */
  159074. boolean raw_data_in; /* TRUE=caller supplies downsampled data */
  159075. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  159076. boolean optimize_coding; /* TRUE=optimize entropy encoding parms */
  159077. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  159078. int smoothing_factor; /* 1..100, or 0 for no input smoothing */
  159079. J_DCT_METHOD dct_method; /* DCT algorithm selector */
  159080. /* The restart interval can be specified in absolute MCUs by setting
  159081. * restart_interval, or in MCU rows by setting restart_in_rows
  159082. * (in which case the correct restart_interval will be figured
  159083. * for each scan).
  159084. */
  159085. unsigned int restart_interval; /* MCUs per restart, or 0 for no restart */
  159086. int restart_in_rows; /* if > 0, MCU rows per restart interval */
  159087. /* Parameters controlling emission of special markers. */
  159088. boolean write_JFIF_header; /* should a JFIF marker be written? */
  159089. UINT8 JFIF_major_version; /* What to write for the JFIF version number */
  159090. UINT8 JFIF_minor_version;
  159091. /* These three values are not used by the JPEG code, merely copied */
  159092. /* into the JFIF APP0 marker. density_unit can be 0 for unknown, */
  159093. /* 1 for dots/inch, or 2 for dots/cm. Note that the pixel aspect */
  159094. /* ratio is defined by X_density/Y_density even when density_unit=0. */
  159095. UINT8 density_unit; /* JFIF code for pixel size units */
  159096. UINT16 X_density; /* Horizontal pixel density */
  159097. UINT16 Y_density; /* Vertical pixel density */
  159098. boolean write_Adobe_marker; /* should an Adobe marker be written? */
  159099. /* State variable: index of next scanline to be written to
  159100. * jpeg_write_scanlines(). Application may use this to control its
  159101. * processing loop, e.g., "while (next_scanline < image_height)".
  159102. */
  159103. JDIMENSION next_scanline; /* 0 .. image_height-1 */
  159104. /* Remaining fields are known throughout compressor, but generally
  159105. * should not be touched by a surrounding application.
  159106. */
  159107. /*
  159108. * These fields are computed during compression startup
  159109. */
  159110. boolean progressive_mode; /* TRUE if scan script uses progressive mode */
  159111. int max_h_samp_factor; /* largest h_samp_factor */
  159112. int max_v_samp_factor; /* largest v_samp_factor */
  159113. JDIMENSION total_iMCU_rows; /* # of iMCU rows to be input to coef ctlr */
  159114. /* The coefficient controller receives data in units of MCU rows as defined
  159115. * for fully interleaved scans (whether the JPEG file is interleaved or not).
  159116. * There are v_samp_factor * DCTSIZE sample rows of each component in an
  159117. * "iMCU" (interleaved MCU) row.
  159118. */
  159119. /*
  159120. * These fields are valid during any one scan.
  159121. * They describe the components and MCUs actually appearing in the scan.
  159122. */
  159123. int comps_in_scan; /* # of JPEG components in this scan */
  159124. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  159125. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  159126. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  159127. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  159128. int blocks_in_MCU; /* # of DCT blocks per MCU */
  159129. int MCU_membership[C_MAX_BLOCKS_IN_MCU];
  159130. /* MCU_membership[i] is index in cur_comp_info of component owning */
  159131. /* i'th block in an MCU */
  159132. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  159133. /*
  159134. * Links to compression subobjects (methods and private variables of modules)
  159135. */
  159136. struct jpeg_comp_master * master;
  159137. struct jpeg_c_main_controller * main;
  159138. struct jpeg_c_prep_controller * prep;
  159139. struct jpeg_c_coef_controller * coef;
  159140. struct jpeg_marker_writer * marker;
  159141. struct jpeg_color_converter * cconvert;
  159142. struct jpeg_downsampler * downsample;
  159143. struct jpeg_forward_dct * fdct;
  159144. struct jpeg_entropy_encoder * entropy;
  159145. jpeg_scan_info * script_space; /* workspace for jpeg_simple_progression */
  159146. int script_space_size;
  159147. };
  159148. /* Master record for a decompression instance */
  159149. struct jpeg_decompress_struct {
  159150. jpeg_common_fields; /* Fields shared with jpeg_compress_struct */
  159151. /* Source of compressed data */
  159152. struct jpeg_source_mgr * src;
  159153. /* Basic description of image --- filled in by jpeg_read_header(). */
  159154. /* Application may inspect these values to decide how to process image. */
  159155. JDIMENSION image_width; /* nominal image width (from SOF marker) */
  159156. JDIMENSION image_height; /* nominal image height */
  159157. int num_components; /* # of color components in JPEG image */
  159158. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  159159. /* Decompression processing parameters --- these fields must be set before
  159160. * calling jpeg_start_decompress(). Note that jpeg_read_header() initializes
  159161. * them to default values.
  159162. */
  159163. J_COLOR_SPACE out_color_space; /* colorspace for output */
  159164. unsigned int scale_num, scale_denom; /* fraction by which to scale image */
  159165. double output_gamma; /* image gamma wanted in output */
  159166. boolean buffered_image; /* TRUE=multiple output passes */
  159167. boolean raw_data_out; /* TRUE=downsampled data wanted */
  159168. J_DCT_METHOD dct_method; /* IDCT algorithm selector */
  159169. boolean do_fancy_upsampling; /* TRUE=apply fancy upsampling */
  159170. boolean do_block_smoothing; /* TRUE=apply interblock smoothing */
  159171. boolean quantize_colors; /* TRUE=colormapped output wanted */
  159172. /* the following are ignored if not quantize_colors: */
  159173. J_DITHER_MODE dither_mode; /* type of color dithering to use */
  159174. boolean two_pass_quantize; /* TRUE=use two-pass color quantization */
  159175. int desired_number_of_colors; /* max # colors to use in created colormap */
  159176. /* these are significant only in buffered-image mode: */
  159177. boolean enable_1pass_quant; /* enable future use of 1-pass quantizer */
  159178. boolean enable_external_quant;/* enable future use of external colormap */
  159179. boolean enable_2pass_quant; /* enable future use of 2-pass quantizer */
  159180. /* Description of actual output image that will be returned to application.
  159181. * These fields are computed by jpeg_start_decompress().
  159182. * You can also use jpeg_calc_output_dimensions() to determine these values
  159183. * in advance of calling jpeg_start_decompress().
  159184. */
  159185. JDIMENSION output_width; /* scaled image width */
  159186. JDIMENSION output_height; /* scaled image height */
  159187. int out_color_components; /* # of color components in out_color_space */
  159188. int output_components; /* # of color components returned */
  159189. /* output_components is 1 (a colormap index) when quantizing colors;
  159190. * otherwise it equals out_color_components.
  159191. */
  159192. int rec_outbuf_height; /* min recommended height of scanline buffer */
  159193. /* If the buffer passed to jpeg_read_scanlines() is less than this many rows
  159194. * high, space and time will be wasted due to unnecessary data copying.
  159195. * Usually rec_outbuf_height will be 1 or 2, at most 4.
  159196. */
  159197. /* When quantizing colors, the output colormap is described by these fields.
  159198. * The application can supply a colormap by setting colormap non-NULL before
  159199. * calling jpeg_start_decompress; otherwise a colormap is created during
  159200. * jpeg_start_decompress or jpeg_start_output.
  159201. * The map has out_color_components rows and actual_number_of_colors columns.
  159202. */
  159203. int actual_number_of_colors; /* number of entries in use */
  159204. JSAMPARRAY colormap; /* The color map as a 2-D pixel array */
  159205. /* State variables: these variables indicate the progress of decompression.
  159206. * The application may examine these but must not modify them.
  159207. */
  159208. /* Row index of next scanline to be read from jpeg_read_scanlines().
  159209. * Application may use this to control its processing loop, e.g.,
  159210. * "while (output_scanline < output_height)".
  159211. */
  159212. JDIMENSION output_scanline; /* 0 .. output_height-1 */
  159213. /* Current input scan number and number of iMCU rows completed in scan.
  159214. * These indicate the progress of the decompressor input side.
  159215. */
  159216. int input_scan_number; /* Number of SOS markers seen so far */
  159217. JDIMENSION input_iMCU_row; /* Number of iMCU rows completed */
  159218. /* The "output scan number" is the notional scan being displayed by the
  159219. * output side. The decompressor will not allow output scan/row number
  159220. * to get ahead of input scan/row, but it can fall arbitrarily far behind.
  159221. */
  159222. int output_scan_number; /* Nominal scan number being displayed */
  159223. JDIMENSION output_iMCU_row; /* Number of iMCU rows read */
  159224. /* Current progression status. coef_bits[c][i] indicates the precision
  159225. * with which component c's DCT coefficient i (in zigzag order) is known.
  159226. * It is -1 when no data has yet been received, otherwise it is the point
  159227. * transform (shift) value for the most recent scan of the coefficient
  159228. * (thus, 0 at completion of the progression).
  159229. * This pointer is NULL when reading a non-progressive file.
  159230. */
  159231. int (*coef_bits)[DCTSIZE2]; /* -1 or current Al value for each coef */
  159232. /* Internal JPEG parameters --- the application usually need not look at
  159233. * these fields. Note that the decompressor output side may not use
  159234. * any parameters that can change between scans.
  159235. */
  159236. /* Quantization and Huffman tables are carried forward across input
  159237. * datastreams when processing abbreviated JPEG datastreams.
  159238. */
  159239. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  159240. /* ptrs to coefficient quantization tables, or NULL if not defined */
  159241. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  159242. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  159243. /* ptrs to Huffman coding tables, or NULL if not defined */
  159244. /* These parameters are never carried across datastreams, since they
  159245. * are given in SOF/SOS markers or defined to be reset by SOI.
  159246. */
  159247. int data_precision; /* bits of precision in image data */
  159248. jpeg_component_info * comp_info;
  159249. /* comp_info[i] describes component that appears i'th in SOF */
  159250. boolean progressive_mode; /* TRUE if SOFn specifies progressive mode */
  159251. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  159252. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  159253. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  159254. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  159255. unsigned int restart_interval; /* MCUs per restart interval, or 0 for no restart */
  159256. /* These fields record data obtained from optional markers recognized by
  159257. * the JPEG library.
  159258. */
  159259. boolean saw_JFIF_marker; /* TRUE iff a JFIF APP0 marker was found */
  159260. /* Data copied from JFIF marker; only valid if saw_JFIF_marker is TRUE: */
  159261. UINT8 JFIF_major_version; /* JFIF version number */
  159262. UINT8 JFIF_minor_version;
  159263. UINT8 density_unit; /* JFIF code for pixel size units */
  159264. UINT16 X_density; /* Horizontal pixel density */
  159265. UINT16 Y_density; /* Vertical pixel density */
  159266. boolean saw_Adobe_marker; /* TRUE iff an Adobe APP14 marker was found */
  159267. UINT8 Adobe_transform; /* Color transform code from Adobe marker */
  159268. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  159269. /* Aside from the specific data retained from APPn markers known to the
  159270. * library, the uninterpreted contents of any or all APPn and COM markers
  159271. * can be saved in a list for examination by the application.
  159272. */
  159273. jpeg_saved_marker_ptr marker_list; /* Head of list of saved markers */
  159274. /* Remaining fields are known throughout decompressor, but generally
  159275. * should not be touched by a surrounding application.
  159276. */
  159277. /*
  159278. * These fields are computed during decompression startup
  159279. */
  159280. int max_h_samp_factor; /* largest h_samp_factor */
  159281. int max_v_samp_factor; /* largest v_samp_factor */
  159282. int min_DCT_scaled_size; /* smallest DCT_scaled_size of any component */
  159283. JDIMENSION total_iMCU_rows; /* # of iMCU rows in image */
  159284. /* The coefficient controller's input and output progress is measured in
  159285. * units of "iMCU" (interleaved MCU) rows. These are the same as MCU rows
  159286. * in fully interleaved JPEG scans, but are used whether the scan is
  159287. * interleaved or not. We define an iMCU row as v_samp_factor DCT block
  159288. * rows of each component. Therefore, the IDCT output contains
  159289. * v_samp_factor*DCT_scaled_size sample rows of a component per iMCU row.
  159290. */
  159291. JSAMPLE * sample_range_limit; /* table for fast range-limiting */
  159292. /*
  159293. * These fields are valid during any one scan.
  159294. * They describe the components and MCUs actually appearing in the scan.
  159295. * Note that the decompressor output side must not use these fields.
  159296. */
  159297. int comps_in_scan; /* # of JPEG components in this scan */
  159298. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  159299. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  159300. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  159301. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  159302. int blocks_in_MCU; /* # of DCT blocks per MCU */
  159303. int MCU_membership[D_MAX_BLOCKS_IN_MCU];
  159304. /* MCU_membership[i] is index in cur_comp_info of component owning */
  159305. /* i'th block in an MCU */
  159306. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  159307. /* This field is shared between entropy decoder and marker parser.
  159308. * It is either zero or the code of a JPEG marker that has been
  159309. * read from the data source, but has not yet been processed.
  159310. */
  159311. int unread_marker;
  159312. /*
  159313. * Links to decompression subobjects (methods, private variables of modules)
  159314. */
  159315. struct jpeg_decomp_master * master;
  159316. struct jpeg_d_main_controller * main;
  159317. struct jpeg_d_coef_controller * coef;
  159318. struct jpeg_d_post_controller * post;
  159319. struct jpeg_input_controller * inputctl;
  159320. struct jpeg_marker_reader * marker;
  159321. struct jpeg_entropy_decoder * entropy;
  159322. struct jpeg_inverse_dct * idct;
  159323. struct jpeg_upsampler * upsample;
  159324. struct jpeg_color_deconverter * cconvert;
  159325. struct jpeg_color_quantizer * cquantize;
  159326. };
  159327. /* "Object" declarations for JPEG modules that may be supplied or called
  159328. * directly by the surrounding application.
  159329. * As with all objects in the JPEG library, these structs only define the
  159330. * publicly visible methods and state variables of a module. Additional
  159331. * private fields may exist after the public ones.
  159332. */
  159333. /* Error handler object */
  159334. struct jpeg_error_mgr {
  159335. /* Error exit handler: does not return to caller */
  159336. JMETHOD(void, error_exit, (j_common_ptr cinfo));
  159337. /* Conditionally emit a trace or warning message */
  159338. JMETHOD(void, emit_message, (j_common_ptr cinfo, int msg_level));
  159339. /* Routine that actually outputs a trace or error message */
  159340. JMETHOD(void, output_message, (j_common_ptr cinfo));
  159341. /* Format a message string for the most recent JPEG error or message */
  159342. JMETHOD(void, format_message, (j_common_ptr cinfo, char * buffer));
  159343. #define JMSG_LENGTH_MAX 200 /* recommended size of format_message buffer */
  159344. /* Reset error state variables at start of a new image */
  159345. JMETHOD(void, reset_error_mgr, (j_common_ptr cinfo));
  159346. /* The message ID code and any parameters are saved here.
  159347. * A message can have one string parameter or up to 8 int parameters.
  159348. */
  159349. int msg_code;
  159350. #define JMSG_STR_PARM_MAX 80
  159351. union {
  159352. int i[8];
  159353. char s[JMSG_STR_PARM_MAX];
  159354. } msg_parm;
  159355. /* Standard state variables for error facility */
  159356. int trace_level; /* max msg_level that will be displayed */
  159357. /* For recoverable corrupt-data errors, we emit a warning message,
  159358. * but keep going unless emit_message chooses to abort. emit_message
  159359. * should count warnings in num_warnings. The surrounding application
  159360. * can check for bad data by seeing if num_warnings is nonzero at the
  159361. * end of processing.
  159362. */
  159363. long num_warnings; /* number of corrupt-data warnings */
  159364. /* These fields point to the table(s) of error message strings.
  159365. * An application can change the table pointer to switch to a different
  159366. * message list (typically, to change the language in which errors are
  159367. * reported). Some applications may wish to add additional error codes
  159368. * that will be handled by the JPEG library error mechanism; the second
  159369. * table pointer is used for this purpose.
  159370. *
  159371. * First table includes all errors generated by JPEG library itself.
  159372. * Error code 0 is reserved for a "no such error string" message.
  159373. */
  159374. const char * const * jpeg_message_table; /* Library errors */
  159375. int last_jpeg_message; /* Table contains strings 0..last_jpeg_message */
  159376. /* Second table can be added by application (see cjpeg/djpeg for example).
  159377. * It contains strings numbered first_addon_message..last_addon_message.
  159378. */
  159379. const char * const * addon_message_table; /* Non-library errors */
  159380. int first_addon_message; /* code for first string in addon table */
  159381. int last_addon_message; /* code for last string in addon table */
  159382. };
  159383. /* Progress monitor object */
  159384. struct jpeg_progress_mgr {
  159385. JMETHOD(void, progress_monitor, (j_common_ptr cinfo));
  159386. long pass_counter; /* work units completed in this pass */
  159387. long pass_limit; /* total number of work units in this pass */
  159388. int completed_passes; /* passes completed so far */
  159389. int total_passes; /* total number of passes expected */
  159390. };
  159391. /* Data destination object for compression */
  159392. struct jpeg_destination_mgr {
  159393. JOCTET * next_output_byte; /* => next byte to write in buffer */
  159394. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  159395. JMETHOD(void, init_destination, (j_compress_ptr cinfo));
  159396. JMETHOD(boolean, empty_output_buffer, (j_compress_ptr cinfo));
  159397. JMETHOD(void, term_destination, (j_compress_ptr cinfo));
  159398. };
  159399. /* Data source object for decompression */
  159400. struct jpeg_source_mgr {
  159401. const JOCTET * next_input_byte; /* => next byte to read from buffer */
  159402. size_t bytes_in_buffer; /* # of bytes remaining in buffer */
  159403. JMETHOD(void, init_source, (j_decompress_ptr cinfo));
  159404. JMETHOD(boolean, fill_input_buffer, (j_decompress_ptr cinfo));
  159405. JMETHOD(void, skip_input_data, (j_decompress_ptr cinfo, long num_bytes));
  159406. JMETHOD(boolean, resync_to_restart, (j_decompress_ptr cinfo, int desired));
  159407. JMETHOD(void, term_source, (j_decompress_ptr cinfo));
  159408. };
  159409. /* Memory manager object.
  159410. * Allocates "small" objects (a few K total), "large" objects (tens of K),
  159411. * and "really big" objects (virtual arrays with backing store if needed).
  159412. * The memory manager does not allow individual objects to be freed; rather,
  159413. * each created object is assigned to a pool, and whole pools can be freed
  159414. * at once. This is faster and more convenient than remembering exactly what
  159415. * to free, especially where malloc()/free() are not too speedy.
  159416. * NB: alloc routines never return NULL. They exit to error_exit if not
  159417. * successful.
  159418. */
  159419. #define JPOOL_PERMANENT 0 /* lasts until master record is destroyed */
  159420. #define JPOOL_IMAGE 1 /* lasts until done with image/datastream */
  159421. #define JPOOL_NUMPOOLS 2
  159422. typedef struct jvirt_sarray_control * jvirt_sarray_ptr;
  159423. typedef struct jvirt_barray_control * jvirt_barray_ptr;
  159424. struct jpeg_memory_mgr {
  159425. /* Method pointers */
  159426. JMETHOD(void *, alloc_small, (j_common_ptr cinfo, int pool_id,
  159427. size_t sizeofobject));
  159428. JMETHOD(void FAR *, alloc_large, (j_common_ptr cinfo, int pool_id,
  159429. size_t sizeofobject));
  159430. JMETHOD(JSAMPARRAY, alloc_sarray, (j_common_ptr cinfo, int pool_id,
  159431. JDIMENSION samplesperrow,
  159432. JDIMENSION numrows));
  159433. JMETHOD(JBLOCKARRAY, alloc_barray, (j_common_ptr cinfo, int pool_id,
  159434. JDIMENSION blocksperrow,
  159435. JDIMENSION numrows));
  159436. JMETHOD(jvirt_sarray_ptr, request_virt_sarray, (j_common_ptr cinfo,
  159437. int pool_id,
  159438. boolean pre_zero,
  159439. JDIMENSION samplesperrow,
  159440. JDIMENSION numrows,
  159441. JDIMENSION maxaccess));
  159442. JMETHOD(jvirt_barray_ptr, request_virt_barray, (j_common_ptr cinfo,
  159443. int pool_id,
  159444. boolean pre_zero,
  159445. JDIMENSION blocksperrow,
  159446. JDIMENSION numrows,
  159447. JDIMENSION maxaccess));
  159448. JMETHOD(void, realize_virt_arrays, (j_common_ptr cinfo));
  159449. JMETHOD(JSAMPARRAY, access_virt_sarray, (j_common_ptr cinfo,
  159450. jvirt_sarray_ptr ptr,
  159451. JDIMENSION start_row,
  159452. JDIMENSION num_rows,
  159453. boolean writable));
  159454. JMETHOD(JBLOCKARRAY, access_virt_barray, (j_common_ptr cinfo,
  159455. jvirt_barray_ptr ptr,
  159456. JDIMENSION start_row,
  159457. JDIMENSION num_rows,
  159458. boolean writable));
  159459. JMETHOD(void, free_pool, (j_common_ptr cinfo, int pool_id));
  159460. JMETHOD(void, self_destruct, (j_common_ptr cinfo));
  159461. /* Limit on memory allocation for this JPEG object. (Note that this is
  159462. * merely advisory, not a guaranteed maximum; it only affects the space
  159463. * used for virtual-array buffers.) May be changed by outer application
  159464. * after creating the JPEG object.
  159465. */
  159466. long max_memory_to_use;
  159467. /* Maximum allocation request accepted by alloc_large. */
  159468. long max_alloc_chunk;
  159469. };
  159470. /* Routine signature for application-supplied marker processing methods.
  159471. * Need not pass marker code since it is stored in cinfo->unread_marker.
  159472. */
  159473. typedef JMETHOD(boolean, jpeg_marker_parser_method, (j_decompress_ptr cinfo));
  159474. /* Declarations for routines called by application.
  159475. * The JPP macro hides prototype parameters from compilers that can't cope.
  159476. * Note JPP requires double parentheses.
  159477. */
  159478. #ifdef HAVE_PROTOTYPES
  159479. #define JPP(arglist) arglist
  159480. #else
  159481. #define JPP(arglist) ()
  159482. #endif
  159483. /* Short forms of external names for systems with brain-damaged linkers.
  159484. * We shorten external names to be unique in the first six letters, which
  159485. * is good enough for all known systems.
  159486. * (If your compiler itself needs names to be unique in less than 15
  159487. * characters, you are out of luck. Get a better compiler.)
  159488. */
  159489. #ifdef NEED_SHORT_EXTERNAL_NAMES
  159490. #define jpeg_std_error jStdError
  159491. #define jpeg_CreateCompress jCreaCompress
  159492. #define jpeg_CreateDecompress jCreaDecompress
  159493. #define jpeg_destroy_compress jDestCompress
  159494. #define jpeg_destroy_decompress jDestDecompress
  159495. #define jpeg_stdio_dest jStdDest
  159496. #define jpeg_stdio_src jStdSrc
  159497. #define jpeg_set_defaults jSetDefaults
  159498. #define jpeg_set_colorspace jSetColorspace
  159499. #define jpeg_default_colorspace jDefColorspace
  159500. #define jpeg_set_quality jSetQuality
  159501. #define jpeg_set_linear_quality jSetLQuality
  159502. #define jpeg_add_quant_table jAddQuantTable
  159503. #define jpeg_quality_scaling jQualityScaling
  159504. #define jpeg_simple_progression jSimProgress
  159505. #define jpeg_suppress_tables jSuppressTables
  159506. #define jpeg_alloc_quant_table jAlcQTable
  159507. #define jpeg_alloc_huff_table jAlcHTable
  159508. #define jpeg_start_compress jStrtCompress
  159509. #define jpeg_write_scanlines jWrtScanlines
  159510. #define jpeg_finish_compress jFinCompress
  159511. #define jpeg_write_raw_data jWrtRawData
  159512. #define jpeg_write_marker jWrtMarker
  159513. #define jpeg_write_m_header jWrtMHeader
  159514. #define jpeg_write_m_byte jWrtMByte
  159515. #define jpeg_write_tables jWrtTables
  159516. #define jpeg_read_header jReadHeader
  159517. #define jpeg_start_decompress jStrtDecompress
  159518. #define jpeg_read_scanlines jReadScanlines
  159519. #define jpeg_finish_decompress jFinDecompress
  159520. #define jpeg_read_raw_data jReadRawData
  159521. #define jpeg_has_multiple_scans jHasMultScn
  159522. #define jpeg_start_output jStrtOutput
  159523. #define jpeg_finish_output jFinOutput
  159524. #define jpeg_input_complete jInComplete
  159525. #define jpeg_new_colormap jNewCMap
  159526. #define jpeg_consume_input jConsumeInput
  159527. #define jpeg_calc_output_dimensions jCalcDimensions
  159528. #define jpeg_save_markers jSaveMarkers
  159529. #define jpeg_set_marker_processor jSetMarker
  159530. #define jpeg_read_coefficients jReadCoefs
  159531. #define jpeg_write_coefficients jWrtCoefs
  159532. #define jpeg_copy_critical_parameters jCopyCrit
  159533. #define jpeg_abort_compress jAbrtCompress
  159534. #define jpeg_abort_decompress jAbrtDecompress
  159535. #define jpeg_abort jAbort
  159536. #define jpeg_destroy jDestroy
  159537. #define jpeg_resync_to_restart jResyncRestart
  159538. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  159539. /* Default error-management setup */
  159540. EXTERN(struct jpeg_error_mgr *) jpeg_std_error
  159541. JPP((struct jpeg_error_mgr * err));
  159542. /* Initialization of JPEG compression objects.
  159543. * jpeg_create_compress() and jpeg_create_decompress() are the exported
  159544. * names that applications should call. These expand to calls on
  159545. * jpeg_CreateCompress and jpeg_CreateDecompress with additional information
  159546. * passed for version mismatch checking.
  159547. * NB: you must set up the error-manager BEFORE calling jpeg_create_xxx.
  159548. */
  159549. #define jpeg_create_compress(cinfo) \
  159550. jpeg_CreateCompress((cinfo), JPEG_LIB_VERSION, \
  159551. (size_t) sizeof(struct jpeg_compress_struct))
  159552. #define jpeg_create_decompress(cinfo) \
  159553. jpeg_CreateDecompress((cinfo), JPEG_LIB_VERSION, \
  159554. (size_t) sizeof(struct jpeg_decompress_struct))
  159555. EXTERN(void) jpeg_CreateCompress JPP((j_compress_ptr cinfo,
  159556. int version, size_t structsize));
  159557. EXTERN(void) jpeg_CreateDecompress JPP((j_decompress_ptr cinfo,
  159558. int version, size_t structsize));
  159559. /* Destruction of JPEG compression objects */
  159560. EXTERN(void) jpeg_destroy_compress JPP((j_compress_ptr cinfo));
  159561. EXTERN(void) jpeg_destroy_decompress JPP((j_decompress_ptr cinfo));
  159562. /* Standard data source and destination managers: stdio streams. */
  159563. /* Caller is responsible for opening the file before and closing after. */
  159564. EXTERN(void) jpeg_stdio_dest JPP((j_compress_ptr cinfo, FILE * outfile));
  159565. EXTERN(void) jpeg_stdio_src JPP((j_decompress_ptr cinfo, FILE * infile));
  159566. /* Default parameter setup for compression */
  159567. EXTERN(void) jpeg_set_defaults JPP((j_compress_ptr cinfo));
  159568. /* Compression parameter setup aids */
  159569. EXTERN(void) jpeg_set_colorspace JPP((j_compress_ptr cinfo,
  159570. J_COLOR_SPACE colorspace));
  159571. EXTERN(void) jpeg_default_colorspace JPP((j_compress_ptr cinfo));
  159572. EXTERN(void) jpeg_set_quality JPP((j_compress_ptr cinfo, int quality,
  159573. boolean force_baseline));
  159574. EXTERN(void) jpeg_set_linear_quality JPP((j_compress_ptr cinfo,
  159575. int scale_factor,
  159576. boolean force_baseline));
  159577. EXTERN(void) jpeg_add_quant_table JPP((j_compress_ptr cinfo, int which_tbl,
  159578. const unsigned int *basic_table,
  159579. int scale_factor,
  159580. boolean force_baseline));
  159581. EXTERN(int) jpeg_quality_scaling JPP((int quality));
  159582. EXTERN(void) jpeg_simple_progression JPP((j_compress_ptr cinfo));
  159583. EXTERN(void) jpeg_suppress_tables JPP((j_compress_ptr cinfo,
  159584. boolean suppress));
  159585. EXTERN(JQUANT_TBL *) jpeg_alloc_quant_table JPP((j_common_ptr cinfo));
  159586. EXTERN(JHUFF_TBL *) jpeg_alloc_huff_table JPP((j_common_ptr cinfo));
  159587. /* Main entry points for compression */
  159588. EXTERN(void) jpeg_start_compress JPP((j_compress_ptr cinfo,
  159589. boolean write_all_tables));
  159590. EXTERN(JDIMENSION) jpeg_write_scanlines JPP((j_compress_ptr cinfo,
  159591. JSAMPARRAY scanlines,
  159592. JDIMENSION num_lines));
  159593. EXTERN(void) jpeg_finish_compress JPP((j_compress_ptr cinfo));
  159594. /* Replaces jpeg_write_scanlines when writing raw downsampled data. */
  159595. EXTERN(JDIMENSION) jpeg_write_raw_data JPP((j_compress_ptr cinfo,
  159596. JSAMPIMAGE data,
  159597. JDIMENSION num_lines));
  159598. /* Write a special marker. See libjpeg.doc concerning safe usage. */
  159599. EXTERN(void) jpeg_write_marker
  159600. JPP((j_compress_ptr cinfo, int marker,
  159601. const JOCTET * dataptr, unsigned int datalen));
  159602. /* Same, but piecemeal. */
  159603. EXTERN(void) jpeg_write_m_header
  159604. JPP((j_compress_ptr cinfo, int marker, unsigned int datalen));
  159605. EXTERN(void) jpeg_write_m_byte
  159606. JPP((j_compress_ptr cinfo, int val));
  159607. /* Alternate compression function: just write an abbreviated table file */
  159608. EXTERN(void) jpeg_write_tables JPP((j_compress_ptr cinfo));
  159609. /* Decompression startup: read start of JPEG datastream to see what's there */
  159610. EXTERN(int) jpeg_read_header JPP((j_decompress_ptr cinfo,
  159611. boolean require_image));
  159612. /* Return value is one of: */
  159613. #define JPEG_SUSPENDED 0 /* Suspended due to lack of input data */
  159614. #define JPEG_HEADER_OK 1 /* Found valid image datastream */
  159615. #define JPEG_HEADER_TABLES_ONLY 2 /* Found valid table-specs-only datastream */
  159616. /* If you pass require_image = TRUE (normal case), you need not check for
  159617. * a TABLES_ONLY return code; an abbreviated file will cause an error exit.
  159618. * JPEG_SUSPENDED is only possible if you use a data source module that can
  159619. * give a suspension return (the stdio source module doesn't).
  159620. */
  159621. /* Main entry points for decompression */
  159622. EXTERN(boolean) jpeg_start_decompress JPP((j_decompress_ptr cinfo));
  159623. EXTERN(JDIMENSION) jpeg_read_scanlines JPP((j_decompress_ptr cinfo,
  159624. JSAMPARRAY scanlines,
  159625. JDIMENSION max_lines));
  159626. EXTERN(boolean) jpeg_finish_decompress JPP((j_decompress_ptr cinfo));
  159627. /* Replaces jpeg_read_scanlines when reading raw downsampled data. */
  159628. EXTERN(JDIMENSION) jpeg_read_raw_data JPP((j_decompress_ptr cinfo,
  159629. JSAMPIMAGE data,
  159630. JDIMENSION max_lines));
  159631. /* Additional entry points for buffered-image mode. */
  159632. EXTERN(boolean) jpeg_has_multiple_scans JPP((j_decompress_ptr cinfo));
  159633. EXTERN(boolean) jpeg_start_output JPP((j_decompress_ptr cinfo,
  159634. int scan_number));
  159635. EXTERN(boolean) jpeg_finish_output JPP((j_decompress_ptr cinfo));
  159636. EXTERN(boolean) jpeg_input_complete JPP((j_decompress_ptr cinfo));
  159637. EXTERN(void) jpeg_new_colormap JPP((j_decompress_ptr cinfo));
  159638. EXTERN(int) jpeg_consume_input JPP((j_decompress_ptr cinfo));
  159639. /* Return value is one of: */
  159640. /* #define JPEG_SUSPENDED 0 Suspended due to lack of input data */
  159641. #define JPEG_REACHED_SOS 1 /* Reached start of new scan */
  159642. #define JPEG_REACHED_EOI 2 /* Reached end of image */
  159643. #define JPEG_ROW_COMPLETED 3 /* Completed one iMCU row */
  159644. #define JPEG_SCAN_COMPLETED 4 /* Completed last iMCU row of a scan */
  159645. /* Precalculate output dimensions for current decompression parameters. */
  159646. EXTERN(void) jpeg_calc_output_dimensions JPP((j_decompress_ptr cinfo));
  159647. /* Control saving of COM and APPn markers into marker_list. */
  159648. EXTERN(void) jpeg_save_markers
  159649. JPP((j_decompress_ptr cinfo, int marker_code,
  159650. unsigned int length_limit));
  159651. /* Install a special processing method for COM or APPn markers. */
  159652. EXTERN(void) jpeg_set_marker_processor
  159653. JPP((j_decompress_ptr cinfo, int marker_code,
  159654. jpeg_marker_parser_method routine));
  159655. /* Read or write raw DCT coefficients --- useful for lossless transcoding. */
  159656. EXTERN(jvirt_barray_ptr *) jpeg_read_coefficients JPP((j_decompress_ptr cinfo));
  159657. EXTERN(void) jpeg_write_coefficients JPP((j_compress_ptr cinfo,
  159658. jvirt_barray_ptr * coef_arrays));
  159659. EXTERN(void) jpeg_copy_critical_parameters JPP((j_decompress_ptr srcinfo,
  159660. j_compress_ptr dstinfo));
  159661. /* If you choose to abort compression or decompression before completing
  159662. * jpeg_finish_(de)compress, then you need to clean up to release memory,
  159663. * temporary files, etc. You can just call jpeg_destroy_(de)compress
  159664. * if you're done with the JPEG object, but if you want to clean it up and
  159665. * reuse it, call this:
  159666. */
  159667. EXTERN(void) jpeg_abort_compress JPP((j_compress_ptr cinfo));
  159668. EXTERN(void) jpeg_abort_decompress JPP((j_decompress_ptr cinfo));
  159669. /* Generic versions of jpeg_abort and jpeg_destroy that work on either
  159670. * flavor of JPEG object. These may be more convenient in some places.
  159671. */
  159672. EXTERN(void) jpeg_abort JPP((j_common_ptr cinfo));
  159673. EXTERN(void) jpeg_destroy JPP((j_common_ptr cinfo));
  159674. /* Default restart-marker-resync procedure for use by data source modules */
  159675. EXTERN(boolean) jpeg_resync_to_restart JPP((j_decompress_ptr cinfo,
  159676. int desired));
  159677. /* These marker codes are exported since applications and data source modules
  159678. * are likely to want to use them.
  159679. */
  159680. #define JPEG_RST0 0xD0 /* RST0 marker code */
  159681. #define JPEG_EOI 0xD9 /* EOI marker code */
  159682. #define JPEG_APP0 0xE0 /* APP0 marker code */
  159683. #define JPEG_COM 0xFE /* COM marker code */
  159684. /* If we have a brain-damaged compiler that emits warnings (or worse, errors)
  159685. * for structure definitions that are never filled in, keep it quiet by
  159686. * supplying dummy definitions for the various substructures.
  159687. */
  159688. #ifdef INCOMPLETE_TYPES_BROKEN
  159689. #ifndef JPEG_INTERNALS /* will be defined in jpegint.h */
  159690. struct jvirt_sarray_control { long dummy; };
  159691. struct jvirt_barray_control { long dummy; };
  159692. struct jpeg_comp_master { long dummy; };
  159693. struct jpeg_c_main_controller { long dummy; };
  159694. struct jpeg_c_prep_controller { long dummy; };
  159695. struct jpeg_c_coef_controller { long dummy; };
  159696. struct jpeg_marker_writer { long dummy; };
  159697. struct jpeg_color_converter { long dummy; };
  159698. struct jpeg_downsampler { long dummy; };
  159699. struct jpeg_forward_dct { long dummy; };
  159700. struct jpeg_entropy_encoder { long dummy; };
  159701. struct jpeg_decomp_master { long dummy; };
  159702. struct jpeg_d_main_controller { long dummy; };
  159703. struct jpeg_d_coef_controller { long dummy; };
  159704. struct jpeg_d_post_controller { long dummy; };
  159705. struct jpeg_input_controller { long dummy; };
  159706. struct jpeg_marker_reader { long dummy; };
  159707. struct jpeg_entropy_decoder { long dummy; };
  159708. struct jpeg_inverse_dct { long dummy; };
  159709. struct jpeg_upsampler { long dummy; };
  159710. struct jpeg_color_deconverter { long dummy; };
  159711. struct jpeg_color_quantizer { long dummy; };
  159712. #endif /* JPEG_INTERNALS */
  159713. #endif /* INCOMPLETE_TYPES_BROKEN */
  159714. /*
  159715. * The JPEG library modules define JPEG_INTERNALS before including this file.
  159716. * The internal structure declarations are read only when that is true.
  159717. * Applications using the library should not include jpegint.h, but may wish
  159718. * to include jerror.h.
  159719. */
  159720. #ifdef JPEG_INTERNALS
  159721. /*** Start of inlined file: jpegint.h ***/
  159722. /* Declarations for both compression & decompression */
  159723. typedef enum { /* Operating modes for buffer controllers */
  159724. JBUF_PASS_THRU, /* Plain stripwise operation */
  159725. /* Remaining modes require a full-image buffer to have been created */
  159726. JBUF_SAVE_SOURCE, /* Run source subobject only, save output */
  159727. JBUF_CRANK_DEST, /* Run dest subobject only, using saved data */
  159728. JBUF_SAVE_AND_PASS /* Run both subobjects, save output */
  159729. } J_BUF_MODE;
  159730. /* Values of global_state field (jdapi.c has some dependencies on ordering!) */
  159731. #define CSTATE_START 100 /* after create_compress */
  159732. #define CSTATE_SCANNING 101 /* start_compress done, write_scanlines OK */
  159733. #define CSTATE_RAW_OK 102 /* start_compress done, write_raw_data OK */
  159734. #define CSTATE_WRCOEFS 103 /* jpeg_write_coefficients done */
  159735. #define DSTATE_START 200 /* after create_decompress */
  159736. #define DSTATE_INHEADER 201 /* reading header markers, no SOS yet */
  159737. #define DSTATE_READY 202 /* found SOS, ready for start_decompress */
  159738. #define DSTATE_PRELOAD 203 /* reading multiscan file in start_decompress*/
  159739. #define DSTATE_PRESCAN 204 /* performing dummy pass for 2-pass quant */
  159740. #define DSTATE_SCANNING 205 /* start_decompress done, read_scanlines OK */
  159741. #define DSTATE_RAW_OK 206 /* start_decompress done, read_raw_data OK */
  159742. #define DSTATE_BUFIMAGE 207 /* expecting jpeg_start_output */
  159743. #define DSTATE_BUFPOST 208 /* looking for SOS/EOI in jpeg_finish_output */
  159744. #define DSTATE_RDCOEFS 209 /* reading file in jpeg_read_coefficients */
  159745. #define DSTATE_STOPPING 210 /* looking for EOI in jpeg_finish_decompress */
  159746. /* Declarations for compression modules */
  159747. /* Master control module */
  159748. struct jpeg_comp_master {
  159749. JMETHOD(void, prepare_for_pass, (j_compress_ptr cinfo));
  159750. JMETHOD(void, pass_startup, (j_compress_ptr cinfo));
  159751. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  159752. /* State variables made visible to other modules */
  159753. boolean call_pass_startup; /* True if pass_startup must be called */
  159754. boolean is_last_pass; /* True during last pass */
  159755. };
  159756. /* Main buffer control (downsampled-data buffer) */
  159757. struct jpeg_c_main_controller {
  159758. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  159759. JMETHOD(void, process_data, (j_compress_ptr cinfo,
  159760. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  159761. JDIMENSION in_rows_avail));
  159762. };
  159763. /* Compression preprocessing (downsampling input buffer control) */
  159764. struct jpeg_c_prep_controller {
  159765. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  159766. JMETHOD(void, pre_process_data, (j_compress_ptr cinfo,
  159767. JSAMPARRAY input_buf,
  159768. JDIMENSION *in_row_ctr,
  159769. JDIMENSION in_rows_avail,
  159770. JSAMPIMAGE output_buf,
  159771. JDIMENSION *out_row_group_ctr,
  159772. JDIMENSION out_row_groups_avail));
  159773. };
  159774. /* Coefficient buffer control */
  159775. struct jpeg_c_coef_controller {
  159776. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  159777. JMETHOD(boolean, compress_data, (j_compress_ptr cinfo,
  159778. JSAMPIMAGE input_buf));
  159779. };
  159780. /* Colorspace conversion */
  159781. struct jpeg_color_converter {
  159782. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  159783. JMETHOD(void, color_convert, (j_compress_ptr cinfo,
  159784. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  159785. JDIMENSION output_row, int num_rows));
  159786. };
  159787. /* Downsampling */
  159788. struct jpeg_downsampler {
  159789. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  159790. JMETHOD(void, downsample, (j_compress_ptr cinfo,
  159791. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  159792. JSAMPIMAGE output_buf,
  159793. JDIMENSION out_row_group_index));
  159794. boolean need_context_rows; /* TRUE if need rows above & below */
  159795. };
  159796. /* Forward DCT (also controls coefficient quantization) */
  159797. struct jpeg_forward_dct {
  159798. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  159799. /* perhaps this should be an array??? */
  159800. JMETHOD(void, forward_DCT, (j_compress_ptr cinfo,
  159801. jpeg_component_info * compptr,
  159802. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  159803. JDIMENSION start_row, JDIMENSION start_col,
  159804. JDIMENSION num_blocks));
  159805. };
  159806. /* Entropy encoding */
  159807. struct jpeg_entropy_encoder {
  159808. JMETHOD(void, start_pass, (j_compress_ptr cinfo, boolean gather_statistics));
  159809. JMETHOD(boolean, encode_mcu, (j_compress_ptr cinfo, JBLOCKROW *MCU_data));
  159810. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  159811. };
  159812. /* Marker writing */
  159813. struct jpeg_marker_writer {
  159814. JMETHOD(void, write_file_header, (j_compress_ptr cinfo));
  159815. JMETHOD(void, write_frame_header, (j_compress_ptr cinfo));
  159816. JMETHOD(void, write_scan_header, (j_compress_ptr cinfo));
  159817. JMETHOD(void, write_file_trailer, (j_compress_ptr cinfo));
  159818. JMETHOD(void, write_tables_only, (j_compress_ptr cinfo));
  159819. /* These routines are exported to allow insertion of extra markers */
  159820. /* Probably only COM and APPn markers should be written this way */
  159821. JMETHOD(void, write_marker_header, (j_compress_ptr cinfo, int marker,
  159822. unsigned int datalen));
  159823. JMETHOD(void, write_marker_byte, (j_compress_ptr cinfo, int val));
  159824. };
  159825. /* Declarations for decompression modules */
  159826. /* Master control module */
  159827. struct jpeg_decomp_master {
  159828. JMETHOD(void, prepare_for_output_pass, (j_decompress_ptr cinfo));
  159829. JMETHOD(void, finish_output_pass, (j_decompress_ptr cinfo));
  159830. /* State variables made visible to other modules */
  159831. boolean is_dummy_pass; /* True during 1st pass for 2-pass quant */
  159832. };
  159833. /* Input control module */
  159834. struct jpeg_input_controller {
  159835. JMETHOD(int, consume_input, (j_decompress_ptr cinfo));
  159836. JMETHOD(void, reset_input_controller, (j_decompress_ptr cinfo));
  159837. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  159838. JMETHOD(void, finish_input_pass, (j_decompress_ptr cinfo));
  159839. /* State variables made visible to other modules */
  159840. boolean has_multiple_scans; /* True if file has multiple scans */
  159841. boolean eoi_reached; /* True when EOI has been consumed */
  159842. };
  159843. /* Main buffer control (downsampled-data buffer) */
  159844. struct jpeg_d_main_controller {
  159845. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  159846. JMETHOD(void, process_data, (j_decompress_ptr cinfo,
  159847. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  159848. JDIMENSION out_rows_avail));
  159849. };
  159850. /* Coefficient buffer control */
  159851. struct jpeg_d_coef_controller {
  159852. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  159853. JMETHOD(int, consume_data, (j_decompress_ptr cinfo));
  159854. JMETHOD(void, start_output_pass, (j_decompress_ptr cinfo));
  159855. JMETHOD(int, decompress_data, (j_decompress_ptr cinfo,
  159856. JSAMPIMAGE output_buf));
  159857. /* Pointer to array of coefficient virtual arrays, or NULL if none */
  159858. jvirt_barray_ptr *coef_arrays;
  159859. };
  159860. /* Decompression postprocessing (color quantization buffer control) */
  159861. struct jpeg_d_post_controller {
  159862. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  159863. JMETHOD(void, post_process_data, (j_decompress_ptr cinfo,
  159864. JSAMPIMAGE input_buf,
  159865. JDIMENSION *in_row_group_ctr,
  159866. JDIMENSION in_row_groups_avail,
  159867. JSAMPARRAY output_buf,
  159868. JDIMENSION *out_row_ctr,
  159869. JDIMENSION out_rows_avail));
  159870. };
  159871. /* Marker reading & parsing */
  159872. struct jpeg_marker_reader {
  159873. JMETHOD(void, reset_marker_reader, (j_decompress_ptr cinfo));
  159874. /* Read markers until SOS or EOI.
  159875. * Returns same codes as are defined for jpeg_consume_input:
  159876. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  159877. */
  159878. JMETHOD(int, read_markers, (j_decompress_ptr cinfo));
  159879. /* Read a restart marker --- exported for use by entropy decoder only */
  159880. jpeg_marker_parser_method read_restart_marker;
  159881. /* State of marker reader --- nominally internal, but applications
  159882. * supplying COM or APPn handlers might like to know the state.
  159883. */
  159884. boolean saw_SOI; /* found SOI? */
  159885. boolean saw_SOF; /* found SOF? */
  159886. int next_restart_num; /* next restart number expected (0-7) */
  159887. unsigned int discarded_bytes; /* # of bytes skipped looking for a marker */
  159888. };
  159889. /* Entropy decoding */
  159890. struct jpeg_entropy_decoder {
  159891. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  159892. JMETHOD(boolean, decode_mcu, (j_decompress_ptr cinfo,
  159893. JBLOCKROW *MCU_data));
  159894. /* This is here to share code between baseline and progressive decoders; */
  159895. /* other modules probably should not use it */
  159896. boolean insufficient_data; /* set TRUE after emitting warning */
  159897. };
  159898. /* Inverse DCT (also performs dequantization) */
  159899. typedef JMETHOD(void, inverse_DCT_method_ptr,
  159900. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  159901. JCOEFPTR coef_block,
  159902. JSAMPARRAY output_buf, JDIMENSION output_col));
  159903. struct jpeg_inverse_dct {
  159904. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  159905. /* It is useful to allow each component to have a separate IDCT method. */
  159906. inverse_DCT_method_ptr inverse_DCT[MAX_COMPONENTS];
  159907. };
  159908. /* Upsampling (note that upsampler must also call color converter) */
  159909. struct jpeg_upsampler {
  159910. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  159911. JMETHOD(void, upsample, (j_decompress_ptr cinfo,
  159912. JSAMPIMAGE input_buf,
  159913. JDIMENSION *in_row_group_ctr,
  159914. JDIMENSION in_row_groups_avail,
  159915. JSAMPARRAY output_buf,
  159916. JDIMENSION *out_row_ctr,
  159917. JDIMENSION out_rows_avail));
  159918. boolean need_context_rows; /* TRUE if need rows above & below */
  159919. };
  159920. /* Colorspace conversion */
  159921. struct jpeg_color_deconverter {
  159922. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  159923. JMETHOD(void, color_convert, (j_decompress_ptr cinfo,
  159924. JSAMPIMAGE input_buf, JDIMENSION input_row,
  159925. JSAMPARRAY output_buf, int num_rows));
  159926. };
  159927. /* Color quantization or color precision reduction */
  159928. struct jpeg_color_quantizer {
  159929. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, boolean is_pre_scan));
  159930. JMETHOD(void, color_quantize, (j_decompress_ptr cinfo,
  159931. JSAMPARRAY input_buf, JSAMPARRAY output_buf,
  159932. int num_rows));
  159933. JMETHOD(void, finish_pass, (j_decompress_ptr cinfo));
  159934. JMETHOD(void, new_color_map, (j_decompress_ptr cinfo));
  159935. };
  159936. /* Miscellaneous useful macros */
  159937. #undef MAX
  159938. #define MAX(a,b) ((a) > (b) ? (a) : (b))
  159939. #undef MIN
  159940. #define MIN(a,b) ((a) < (b) ? (a) : (b))
  159941. /* We assume that right shift corresponds to signed division by 2 with
  159942. * rounding towards minus infinity. This is correct for typical "arithmetic
  159943. * shift" instructions that shift in copies of the sign bit. But some
  159944. * C compilers implement >> with an unsigned shift. For these machines you
  159945. * must define RIGHT_SHIFT_IS_UNSIGNED.
  159946. * RIGHT_SHIFT provides a proper signed right shift of an INT32 quantity.
  159947. * It is only applied with constant shift counts. SHIFT_TEMPS must be
  159948. * included in the variables of any routine using RIGHT_SHIFT.
  159949. */
  159950. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  159951. #define SHIFT_TEMPS INT32 shift_temp;
  159952. #define RIGHT_SHIFT(x,shft) \
  159953. ((shift_temp = (x)) < 0 ? \
  159954. (shift_temp >> (shft)) | ((~((INT32) 0)) << (32-(shft))) : \
  159955. (shift_temp >> (shft)))
  159956. #else
  159957. #define SHIFT_TEMPS
  159958. #define RIGHT_SHIFT(x,shft) ((x) >> (shft))
  159959. #endif
  159960. /* Short forms of external names for systems with brain-damaged linkers. */
  159961. #ifdef NEED_SHORT_EXTERNAL_NAMES
  159962. #define jinit_compress_master jICompress
  159963. #define jinit_c_master_control jICMaster
  159964. #define jinit_c_main_controller jICMainC
  159965. #define jinit_c_prep_controller jICPrepC
  159966. #define jinit_c_coef_controller jICCoefC
  159967. #define jinit_color_converter jICColor
  159968. #define jinit_downsampler jIDownsampler
  159969. #define jinit_forward_dct jIFDCT
  159970. #define jinit_huff_encoder jIHEncoder
  159971. #define jinit_phuff_encoder jIPHEncoder
  159972. #define jinit_marker_writer jIMWriter
  159973. #define jinit_master_decompress jIDMaster
  159974. #define jinit_d_main_controller jIDMainC
  159975. #define jinit_d_coef_controller jIDCoefC
  159976. #define jinit_d_post_controller jIDPostC
  159977. #define jinit_input_controller jIInCtlr
  159978. #define jinit_marker_reader jIMReader
  159979. #define jinit_huff_decoder jIHDecoder
  159980. #define jinit_phuff_decoder jIPHDecoder
  159981. #define jinit_inverse_dct jIIDCT
  159982. #define jinit_upsampler jIUpsampler
  159983. #define jinit_color_deconverter jIDColor
  159984. #define jinit_1pass_quantizer jI1Quant
  159985. #define jinit_2pass_quantizer jI2Quant
  159986. #define jinit_merged_upsampler jIMUpsampler
  159987. #define jinit_memory_mgr jIMemMgr
  159988. #define jdiv_round_up jDivRound
  159989. #define jround_up jRound
  159990. #define jcopy_sample_rows jCopySamples
  159991. #define jcopy_block_row jCopyBlocks
  159992. #define jzero_far jZeroFar
  159993. #define jpeg_zigzag_order jZIGTable
  159994. #define jpeg_natural_order jZAGTable
  159995. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  159996. /* Compression module initialization routines */
  159997. EXTERN(void) jinit_compress_master JPP((j_compress_ptr cinfo));
  159998. EXTERN(void) jinit_c_master_control JPP((j_compress_ptr cinfo,
  159999. boolean transcode_only));
  160000. EXTERN(void) jinit_c_main_controller JPP((j_compress_ptr cinfo,
  160001. boolean need_full_buffer));
  160002. EXTERN(void) jinit_c_prep_controller JPP((j_compress_ptr cinfo,
  160003. boolean need_full_buffer));
  160004. EXTERN(void) jinit_c_coef_controller JPP((j_compress_ptr cinfo,
  160005. boolean need_full_buffer));
  160006. EXTERN(void) jinit_color_converter JPP((j_compress_ptr cinfo));
  160007. EXTERN(void) jinit_downsampler JPP((j_compress_ptr cinfo));
  160008. EXTERN(void) jinit_forward_dct JPP((j_compress_ptr cinfo));
  160009. EXTERN(void) jinit_huff_encoder JPP((j_compress_ptr cinfo));
  160010. EXTERN(void) jinit_phuff_encoder JPP((j_compress_ptr cinfo));
  160011. EXTERN(void) jinit_marker_writer JPP((j_compress_ptr cinfo));
  160012. /* Decompression module initialization routines */
  160013. EXTERN(void) jinit_master_decompress JPP((j_decompress_ptr cinfo));
  160014. EXTERN(void) jinit_d_main_controller JPP((j_decompress_ptr cinfo,
  160015. boolean need_full_buffer));
  160016. EXTERN(void) jinit_d_coef_controller JPP((j_decompress_ptr cinfo,
  160017. boolean need_full_buffer));
  160018. EXTERN(void) jinit_d_post_controller JPP((j_decompress_ptr cinfo,
  160019. boolean need_full_buffer));
  160020. EXTERN(void) jinit_input_controller JPP((j_decompress_ptr cinfo));
  160021. EXTERN(void) jinit_marker_reader JPP((j_decompress_ptr cinfo));
  160022. EXTERN(void) jinit_huff_decoder JPP((j_decompress_ptr cinfo));
  160023. EXTERN(void) jinit_phuff_decoder JPP((j_decompress_ptr cinfo));
  160024. EXTERN(void) jinit_inverse_dct JPP((j_decompress_ptr cinfo));
  160025. EXTERN(void) jinit_upsampler JPP((j_decompress_ptr cinfo));
  160026. EXTERN(void) jinit_color_deconverter JPP((j_decompress_ptr cinfo));
  160027. EXTERN(void) jinit_1pass_quantizer JPP((j_decompress_ptr cinfo));
  160028. EXTERN(void) jinit_2pass_quantizer JPP((j_decompress_ptr cinfo));
  160029. EXTERN(void) jinit_merged_upsampler JPP((j_decompress_ptr cinfo));
  160030. /* Memory manager initialization */
  160031. EXTERN(void) jinit_memory_mgr JPP((j_common_ptr cinfo));
  160032. /* Utility routines in jutils.c */
  160033. EXTERN(long) jdiv_round_up JPP((long a, long b));
  160034. EXTERN(long) jround_up JPP((long a, long b));
  160035. EXTERN(void) jcopy_sample_rows JPP((JSAMPARRAY input_array, int source_row,
  160036. JSAMPARRAY output_array, int dest_row,
  160037. int num_rows, JDIMENSION num_cols));
  160038. EXTERN(void) jcopy_block_row JPP((JBLOCKROW input_row, JBLOCKROW output_row,
  160039. JDIMENSION num_blocks));
  160040. EXTERN(void) jzero_far JPP((void FAR * target, size_t bytestozero));
  160041. /* Constant tables in jutils.c */
  160042. #if 0 /* This table is not actually needed in v6a */
  160043. extern const int jpeg_zigzag_order[]; /* natural coef order to zigzag order */
  160044. #endif
  160045. extern const int jpeg_natural_order[]; /* zigzag coef order to natural order */
  160046. /* Suppress undefined-structure complaints if necessary. */
  160047. #ifdef INCOMPLETE_TYPES_BROKEN
  160048. #ifndef AM_MEMORY_MANAGER /* only jmemmgr.c defines these */
  160049. struct jvirt_sarray_control { long dummy; };
  160050. struct jvirt_barray_control { long dummy; };
  160051. #endif
  160052. #endif /* INCOMPLETE_TYPES_BROKEN */
  160053. /*** End of inlined file: jpegint.h ***/
  160054. /* fetch private declarations */
  160055. /*** Start of inlined file: jerror.h ***/
  160056. /*
  160057. * To define the enum list of message codes, include this file without
  160058. * defining macro JMESSAGE. To create a message string table, include it
  160059. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  160060. */
  160061. #ifndef JMESSAGE
  160062. #ifndef JERROR_H
  160063. /* First time through, define the enum list */
  160064. #define JMAKE_ENUM_LIST
  160065. #else
  160066. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  160067. #define JMESSAGE(code,string)
  160068. #endif /* JERROR_H */
  160069. #endif /* JMESSAGE */
  160070. #ifdef JMAKE_ENUM_LIST
  160071. typedef enum {
  160072. #define JMESSAGE(code,string) code ,
  160073. #endif /* JMAKE_ENUM_LIST */
  160074. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  160075. /* For maintenance convenience, list is alphabetical by message code name */
  160076. JMESSAGE(JERR_ARITH_NOTIMPL,
  160077. "Sorry, there are legal restrictions on arithmetic coding")
  160078. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  160079. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  160080. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  160081. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  160082. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  160083. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  160084. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  160085. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  160086. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  160087. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  160088. JMESSAGE(JERR_BAD_LIB_VERSION,
  160089. "Wrong JPEG library version: library is %d, caller expects %d")
  160090. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  160091. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  160092. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  160093. JMESSAGE(JERR_BAD_PROGRESSION,
  160094. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  160095. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  160096. "Invalid progressive parameters at scan script entry %d")
  160097. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  160098. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  160099. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  160100. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  160101. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  160102. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  160103. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  160104. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  160105. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  160106. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  160107. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  160108. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  160109. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  160110. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  160111. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  160112. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  160113. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  160114. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  160115. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  160116. JMESSAGE(JERR_FILE_READ, "Input file read error")
  160117. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  160118. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  160119. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  160120. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  160121. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  160122. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  160123. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  160124. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  160125. "Cannot transcode due to multiple use of quantization table %d")
  160126. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  160127. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  160128. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  160129. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  160130. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  160131. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  160132. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  160133. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  160134. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  160135. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  160136. JMESSAGE(JERR_QUANT_COMPONENTS,
  160137. "Cannot quantize more than %d color components")
  160138. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  160139. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  160140. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  160141. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  160142. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  160143. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  160144. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  160145. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  160146. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  160147. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  160148. JMESSAGE(JERR_TFILE_WRITE,
  160149. "Write failed on temporary file --- out of disk space?")
  160150. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  160151. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  160152. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  160153. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  160154. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  160155. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  160156. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  160157. JMESSAGE(JMSG_VERSION, JVERSION)
  160158. JMESSAGE(JTRC_16BIT_TABLES,
  160159. "Caution: quantization tables are too coarse for baseline JPEG")
  160160. JMESSAGE(JTRC_ADOBE,
  160161. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  160162. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  160163. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  160164. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  160165. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  160166. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  160167. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  160168. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  160169. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  160170. JMESSAGE(JTRC_EOI, "End Of Image")
  160171. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  160172. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  160173. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  160174. "Warning: thumbnail image size does not match data length %u")
  160175. JMESSAGE(JTRC_JFIF_EXTENSION,
  160176. "JFIF extension marker: type 0x%02x, length %u")
  160177. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  160178. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  160179. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  160180. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  160181. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  160182. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  160183. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  160184. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  160185. JMESSAGE(JTRC_RST, "RST%d")
  160186. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  160187. "Smoothing not supported with nonstandard sampling ratios")
  160188. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  160189. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  160190. JMESSAGE(JTRC_SOI, "Start of Image")
  160191. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  160192. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  160193. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  160194. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  160195. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  160196. JMESSAGE(JTRC_THUMB_JPEG,
  160197. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  160198. JMESSAGE(JTRC_THUMB_PALETTE,
  160199. "JFIF extension marker: palette thumbnail image, length %u")
  160200. JMESSAGE(JTRC_THUMB_RGB,
  160201. "JFIF extension marker: RGB thumbnail image, length %u")
  160202. JMESSAGE(JTRC_UNKNOWN_IDS,
  160203. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  160204. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  160205. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  160206. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  160207. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  160208. "Inconsistent progression sequence for component %d coefficient %d")
  160209. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  160210. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  160211. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  160212. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  160213. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  160214. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  160215. JMESSAGE(JWRN_MUST_RESYNC,
  160216. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  160217. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  160218. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  160219. #ifdef JMAKE_ENUM_LIST
  160220. JMSG_LASTMSGCODE
  160221. } J_MESSAGE_CODE;
  160222. #undef JMAKE_ENUM_LIST
  160223. #endif /* JMAKE_ENUM_LIST */
  160224. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  160225. #undef JMESSAGE
  160226. #ifndef JERROR_H
  160227. #define JERROR_H
  160228. /* Macros to simplify using the error and trace message stuff */
  160229. /* The first parameter is either type of cinfo pointer */
  160230. /* Fatal errors (print message and exit) */
  160231. #define ERREXIT(cinfo,code) \
  160232. ((cinfo)->err->msg_code = (code), \
  160233. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  160234. #define ERREXIT1(cinfo,code,p1) \
  160235. ((cinfo)->err->msg_code = (code), \
  160236. (cinfo)->err->msg_parm.i[0] = (p1), \
  160237. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  160238. #define ERREXIT2(cinfo,code,p1,p2) \
  160239. ((cinfo)->err->msg_code = (code), \
  160240. (cinfo)->err->msg_parm.i[0] = (p1), \
  160241. (cinfo)->err->msg_parm.i[1] = (p2), \
  160242. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  160243. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  160244. ((cinfo)->err->msg_code = (code), \
  160245. (cinfo)->err->msg_parm.i[0] = (p1), \
  160246. (cinfo)->err->msg_parm.i[1] = (p2), \
  160247. (cinfo)->err->msg_parm.i[2] = (p3), \
  160248. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  160249. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  160250. ((cinfo)->err->msg_code = (code), \
  160251. (cinfo)->err->msg_parm.i[0] = (p1), \
  160252. (cinfo)->err->msg_parm.i[1] = (p2), \
  160253. (cinfo)->err->msg_parm.i[2] = (p3), \
  160254. (cinfo)->err->msg_parm.i[3] = (p4), \
  160255. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  160256. #define ERREXITS(cinfo,code,str) \
  160257. ((cinfo)->err->msg_code = (code), \
  160258. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  160259. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  160260. #define MAKESTMT(stuff) do { stuff } while (0)
  160261. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  160262. #define WARNMS(cinfo,code) \
  160263. ((cinfo)->err->msg_code = (code), \
  160264. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  160265. #define WARNMS1(cinfo,code,p1) \
  160266. ((cinfo)->err->msg_code = (code), \
  160267. (cinfo)->err->msg_parm.i[0] = (p1), \
  160268. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  160269. #define WARNMS2(cinfo,code,p1,p2) \
  160270. ((cinfo)->err->msg_code = (code), \
  160271. (cinfo)->err->msg_parm.i[0] = (p1), \
  160272. (cinfo)->err->msg_parm.i[1] = (p2), \
  160273. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  160274. /* Informational/debugging messages */
  160275. #define TRACEMS(cinfo,lvl,code) \
  160276. ((cinfo)->err->msg_code = (code), \
  160277. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  160278. #define TRACEMS1(cinfo,lvl,code,p1) \
  160279. ((cinfo)->err->msg_code = (code), \
  160280. (cinfo)->err->msg_parm.i[0] = (p1), \
  160281. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  160282. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  160283. ((cinfo)->err->msg_code = (code), \
  160284. (cinfo)->err->msg_parm.i[0] = (p1), \
  160285. (cinfo)->err->msg_parm.i[1] = (p2), \
  160286. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  160287. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  160288. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  160289. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  160290. (cinfo)->err->msg_code = (code); \
  160291. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  160292. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  160293. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  160294. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  160295. (cinfo)->err->msg_code = (code); \
  160296. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  160297. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  160298. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  160299. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  160300. _mp[4] = (p5); \
  160301. (cinfo)->err->msg_code = (code); \
  160302. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  160303. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  160304. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  160305. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  160306. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  160307. (cinfo)->err->msg_code = (code); \
  160308. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  160309. #define TRACEMSS(cinfo,lvl,code,str) \
  160310. ((cinfo)->err->msg_code = (code), \
  160311. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  160312. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  160313. #endif /* JERROR_H */
  160314. /*** End of inlined file: jerror.h ***/
  160315. /* fetch error codes too */
  160316. #endif
  160317. #endif /* JPEGLIB_H */
  160318. /*** End of inlined file: jpeglib.h ***/
  160319. /*** Start of inlined file: jcapimin.c ***/
  160320. #define JPEG_INTERNALS
  160321. /*** Start of inlined file: jinclude.h ***/
  160322. /* Include auto-config file to find out which system include files we need. */
  160323. #ifndef __jinclude_h__
  160324. #define __jinclude_h__
  160325. /*** Start of inlined file: jconfig.h ***/
  160326. /* see jconfig.doc for explanations */
  160327. // disable all the warnings under MSVC
  160328. #ifdef _MSC_VER
  160329. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  160330. #endif
  160331. #ifdef __BORLANDC__
  160332. #pragma warn -8057
  160333. #pragma warn -8019
  160334. #pragma warn -8004
  160335. #pragma warn -8008
  160336. #endif
  160337. #define HAVE_PROTOTYPES
  160338. #define HAVE_UNSIGNED_CHAR
  160339. #define HAVE_UNSIGNED_SHORT
  160340. /* #define void char */
  160341. /* #define const */
  160342. #undef CHAR_IS_UNSIGNED
  160343. #define HAVE_STDDEF_H
  160344. #define HAVE_STDLIB_H
  160345. #undef NEED_BSD_STRINGS
  160346. #undef NEED_SYS_TYPES_H
  160347. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  160348. #undef NEED_SHORT_EXTERNAL_NAMES
  160349. #undef INCOMPLETE_TYPES_BROKEN
  160350. /* Define "boolean" as unsigned char, not int, per Windows custom */
  160351. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  160352. typedef unsigned char boolean;
  160353. #endif
  160354. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  160355. #ifdef JPEG_INTERNALS
  160356. #undef RIGHT_SHIFT_IS_UNSIGNED
  160357. #endif /* JPEG_INTERNALS */
  160358. #ifdef JPEG_CJPEG_DJPEG
  160359. #define BMP_SUPPORTED /* BMP image file format */
  160360. #define GIF_SUPPORTED /* GIF image file format */
  160361. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  160362. #undef RLE_SUPPORTED /* Utah RLE image file format */
  160363. #define TARGA_SUPPORTED /* Targa image file format */
  160364. #define TWO_FILE_COMMANDLINE /* optional */
  160365. #define USE_SETMODE /* Microsoft has setmode() */
  160366. #undef NEED_SIGNAL_CATCHER
  160367. #undef DONT_USE_B_MODE
  160368. #undef PROGRESS_REPORT /* optional */
  160369. #endif /* JPEG_CJPEG_DJPEG */
  160370. /*** End of inlined file: jconfig.h ***/
  160371. /* auto configuration options */
  160372. #define JCONFIG_INCLUDED /* so that jpeglib.h doesn't do it again */
  160373. /*
  160374. * We need the NULL macro and size_t typedef.
  160375. * On an ANSI-conforming system it is sufficient to include <stddef.h>.
  160376. * Otherwise, we get them from <stdlib.h> or <stdio.h>; we may have to
  160377. * pull in <sys/types.h> as well.
  160378. * Note that the core JPEG library does not require <stdio.h>;
  160379. * only the default error handler and data source/destination modules do.
  160380. * But we must pull it in because of the references to FILE in jpeglib.h.
  160381. * You can remove those references if you want to compile without <stdio.h>.
  160382. */
  160383. #ifdef HAVE_STDDEF_H
  160384. #include <stddef.h>
  160385. #endif
  160386. #ifdef HAVE_STDLIB_H
  160387. #include <stdlib.h>
  160388. #endif
  160389. #ifdef NEED_SYS_TYPES_H
  160390. #include <sys/types.h>
  160391. #endif
  160392. #include <stdio.h>
  160393. /*
  160394. * We need memory copying and zeroing functions, plus strncpy().
  160395. * ANSI and System V implementations declare these in <string.h>.
  160396. * BSD doesn't have the mem() functions, but it does have bcopy()/bzero().
  160397. * Some systems may declare memset and memcpy in <memory.h>.
  160398. *
  160399. * NOTE: we assume the size parameters to these functions are of type size_t.
  160400. * Change the casts in these macros if not!
  160401. */
  160402. #ifdef NEED_BSD_STRINGS
  160403. #include <strings.h>
  160404. #define MEMZERO(target,size) bzero((void *)(target), (size_t)(size))
  160405. #define MEMCOPY(dest,src,size) bcopy((const void *)(src), (void *)(dest), (size_t)(size))
  160406. #else /* not BSD, assume ANSI/SysV string lib */
  160407. #include <string.h>
  160408. #define MEMZERO(target,size) memset((void *)(target), 0, (size_t)(size))
  160409. #define MEMCOPY(dest,src,size) memcpy((void *)(dest), (const void *)(src), (size_t)(size))
  160410. #endif
  160411. /*
  160412. * In ANSI C, and indeed any rational implementation, size_t is also the
  160413. * type returned by sizeof(). However, it seems there are some irrational
  160414. * implementations out there, in which sizeof() returns an int even though
  160415. * size_t is defined as long or unsigned long. To ensure consistent results
  160416. * we always use this SIZEOF() macro in place of using sizeof() directly.
  160417. */
  160418. #define SIZEOF(object) ((size_t) sizeof(object))
  160419. /*
  160420. * The modules that use fread() and fwrite() always invoke them through
  160421. * these macros. On some systems you may need to twiddle the argument casts.
  160422. * CAUTION: argument order is different from underlying functions!
  160423. */
  160424. #define JFREAD(file,buf,sizeofbuf) \
  160425. ((size_t) fread((void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  160426. #define JFWRITE(file,buf,sizeofbuf) \
  160427. ((size_t) fwrite((const void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  160428. typedef enum { /* JPEG marker codes */
  160429. M_SOF0 = 0xc0,
  160430. M_SOF1 = 0xc1,
  160431. M_SOF2 = 0xc2,
  160432. M_SOF3 = 0xc3,
  160433. M_SOF5 = 0xc5,
  160434. M_SOF6 = 0xc6,
  160435. M_SOF7 = 0xc7,
  160436. M_JPG = 0xc8,
  160437. M_SOF9 = 0xc9,
  160438. M_SOF10 = 0xca,
  160439. M_SOF11 = 0xcb,
  160440. M_SOF13 = 0xcd,
  160441. M_SOF14 = 0xce,
  160442. M_SOF15 = 0xcf,
  160443. M_DHT = 0xc4,
  160444. M_DAC = 0xcc,
  160445. M_RST0 = 0xd0,
  160446. M_RST1 = 0xd1,
  160447. M_RST2 = 0xd2,
  160448. M_RST3 = 0xd3,
  160449. M_RST4 = 0xd4,
  160450. M_RST5 = 0xd5,
  160451. M_RST6 = 0xd6,
  160452. M_RST7 = 0xd7,
  160453. M_SOI = 0xd8,
  160454. M_EOI = 0xd9,
  160455. M_SOS = 0xda,
  160456. M_DQT = 0xdb,
  160457. M_DNL = 0xdc,
  160458. M_DRI = 0xdd,
  160459. M_DHP = 0xde,
  160460. M_EXP = 0xdf,
  160461. M_APP0 = 0xe0,
  160462. M_APP1 = 0xe1,
  160463. M_APP2 = 0xe2,
  160464. M_APP3 = 0xe3,
  160465. M_APP4 = 0xe4,
  160466. M_APP5 = 0xe5,
  160467. M_APP6 = 0xe6,
  160468. M_APP7 = 0xe7,
  160469. M_APP8 = 0xe8,
  160470. M_APP9 = 0xe9,
  160471. M_APP10 = 0xea,
  160472. M_APP11 = 0xeb,
  160473. M_APP12 = 0xec,
  160474. M_APP13 = 0xed,
  160475. M_APP14 = 0xee,
  160476. M_APP15 = 0xef,
  160477. M_JPG0 = 0xf0,
  160478. M_JPG13 = 0xfd,
  160479. M_COM = 0xfe,
  160480. M_TEM = 0x01,
  160481. M_ERROR = 0x100
  160482. } JPEG_MARKER;
  160483. /*
  160484. * Figure F.12: extend sign bit.
  160485. * On some machines, a shift and add will be faster than a table lookup.
  160486. */
  160487. #ifdef AVOID_TABLES
  160488. #define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))
  160489. #else
  160490. #define HUFF_EXTEND(x,s) ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
  160491. static const int extend_test[16] = /* entry n is 2**(n-1) */
  160492. { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
  160493. 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
  160494. static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
  160495. { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
  160496. ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
  160497. ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
  160498. ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
  160499. #endif /* AVOID_TABLES */
  160500. #endif
  160501. /*** End of inlined file: jinclude.h ***/
  160502. /*
  160503. * Initialization of a JPEG compression object.
  160504. * The error manager must already be set up (in case memory manager fails).
  160505. */
  160506. GLOBAL(void)
  160507. jpeg_CreateCompress (j_compress_ptr cinfo, int version, size_t structsize)
  160508. {
  160509. int i;
  160510. /* Guard against version mismatches between library and caller. */
  160511. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  160512. if (version != JPEG_LIB_VERSION)
  160513. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  160514. if (structsize != SIZEOF(struct jpeg_compress_struct))
  160515. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  160516. (int) SIZEOF(struct jpeg_compress_struct), (int) structsize);
  160517. /* For debugging purposes, we zero the whole master structure.
  160518. * But the application has already set the err pointer, and may have set
  160519. * client_data, so we have to save and restore those fields.
  160520. * Note: if application hasn't set client_data, tools like Purify may
  160521. * complain here.
  160522. */
  160523. {
  160524. struct jpeg_error_mgr * err = cinfo->err;
  160525. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  160526. MEMZERO(cinfo, SIZEOF(struct jpeg_compress_struct));
  160527. cinfo->err = err;
  160528. cinfo->client_data = client_data;
  160529. }
  160530. cinfo->is_decompressor = FALSE;
  160531. /* Initialize a memory manager instance for this object */
  160532. jinit_memory_mgr((j_common_ptr) cinfo);
  160533. /* Zero out pointers to permanent structures. */
  160534. cinfo->progress = NULL;
  160535. cinfo->dest = NULL;
  160536. cinfo->comp_info = NULL;
  160537. for (i = 0; i < NUM_QUANT_TBLS; i++)
  160538. cinfo->quant_tbl_ptrs[i] = NULL;
  160539. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  160540. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  160541. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  160542. }
  160543. cinfo->script_space = NULL;
  160544. cinfo->input_gamma = 1.0; /* in case application forgets */
  160545. /* OK, I'm ready */
  160546. cinfo->global_state = CSTATE_START;
  160547. }
  160548. /*
  160549. * Destruction of a JPEG compression object
  160550. */
  160551. GLOBAL(void)
  160552. jpeg_destroy_compress (j_compress_ptr cinfo)
  160553. {
  160554. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  160555. }
  160556. /*
  160557. * Abort processing of a JPEG compression operation,
  160558. * but don't destroy the object itself.
  160559. */
  160560. GLOBAL(void)
  160561. jpeg_abort_compress (j_compress_ptr cinfo)
  160562. {
  160563. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  160564. }
  160565. /*
  160566. * Forcibly suppress or un-suppress all quantization and Huffman tables.
  160567. * Marks all currently defined tables as already written (if suppress)
  160568. * or not written (if !suppress). This will control whether they get emitted
  160569. * by a subsequent jpeg_start_compress call.
  160570. *
  160571. * This routine is exported for use by applications that want to produce
  160572. * abbreviated JPEG datastreams. It logically belongs in jcparam.c, but
  160573. * since it is called by jpeg_start_compress, we put it here --- otherwise
  160574. * jcparam.o would be linked whether the application used it or not.
  160575. */
  160576. GLOBAL(void)
  160577. jpeg_suppress_tables (j_compress_ptr cinfo, boolean suppress)
  160578. {
  160579. int i;
  160580. JQUANT_TBL * qtbl;
  160581. JHUFF_TBL * htbl;
  160582. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  160583. if ((qtbl = cinfo->quant_tbl_ptrs[i]) != NULL)
  160584. qtbl->sent_table = suppress;
  160585. }
  160586. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  160587. if ((htbl = cinfo->dc_huff_tbl_ptrs[i]) != NULL)
  160588. htbl->sent_table = suppress;
  160589. if ((htbl = cinfo->ac_huff_tbl_ptrs[i]) != NULL)
  160590. htbl->sent_table = suppress;
  160591. }
  160592. }
  160593. /*
  160594. * Finish JPEG compression.
  160595. *
  160596. * If a multipass operating mode was selected, this may do a great deal of
  160597. * work including most of the actual output.
  160598. */
  160599. GLOBAL(void)
  160600. jpeg_finish_compress (j_compress_ptr cinfo)
  160601. {
  160602. JDIMENSION iMCU_row;
  160603. if (cinfo->global_state == CSTATE_SCANNING ||
  160604. cinfo->global_state == CSTATE_RAW_OK) {
  160605. /* Terminate first pass */
  160606. if (cinfo->next_scanline < cinfo->image_height)
  160607. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  160608. (*cinfo->master->finish_pass) (cinfo);
  160609. } else if (cinfo->global_state != CSTATE_WRCOEFS)
  160610. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  160611. /* Perform any remaining passes */
  160612. while (! cinfo->master->is_last_pass) {
  160613. (*cinfo->master->prepare_for_pass) (cinfo);
  160614. for (iMCU_row = 0; iMCU_row < cinfo->total_iMCU_rows; iMCU_row++) {
  160615. if (cinfo->progress != NULL) {
  160616. cinfo->progress->pass_counter = (long) iMCU_row;
  160617. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows;
  160618. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  160619. }
  160620. /* We bypass the main controller and invoke coef controller directly;
  160621. * all work is being done from the coefficient buffer.
  160622. */
  160623. if (! (*cinfo->coef->compress_data) (cinfo, (JSAMPIMAGE) NULL))
  160624. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  160625. }
  160626. (*cinfo->master->finish_pass) (cinfo);
  160627. }
  160628. /* Write EOI, do final cleanup */
  160629. (*cinfo->marker->write_file_trailer) (cinfo);
  160630. (*cinfo->dest->term_destination) (cinfo);
  160631. /* We can use jpeg_abort to release memory and reset global_state */
  160632. jpeg_abort((j_common_ptr) cinfo);
  160633. }
  160634. /*
  160635. * Write a special marker.
  160636. * This is only recommended for writing COM or APPn markers.
  160637. * Must be called after jpeg_start_compress() and before
  160638. * first call to jpeg_write_scanlines() or jpeg_write_raw_data().
  160639. */
  160640. GLOBAL(void)
  160641. jpeg_write_marker (j_compress_ptr cinfo, int marker,
  160642. const JOCTET *dataptr, unsigned int datalen)
  160643. {
  160644. JMETHOD(void, write_marker_byte, (j_compress_ptr info, int val));
  160645. if (cinfo->next_scanline != 0 ||
  160646. (cinfo->global_state != CSTATE_SCANNING &&
  160647. cinfo->global_state != CSTATE_RAW_OK &&
  160648. cinfo->global_state != CSTATE_WRCOEFS))
  160649. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  160650. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  160651. write_marker_byte = cinfo->marker->write_marker_byte; /* copy for speed */
  160652. while (datalen--) {
  160653. (*write_marker_byte) (cinfo, *dataptr);
  160654. dataptr++;
  160655. }
  160656. }
  160657. /* Same, but piecemeal. */
  160658. GLOBAL(void)
  160659. jpeg_write_m_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  160660. {
  160661. if (cinfo->next_scanline != 0 ||
  160662. (cinfo->global_state != CSTATE_SCANNING &&
  160663. cinfo->global_state != CSTATE_RAW_OK &&
  160664. cinfo->global_state != CSTATE_WRCOEFS))
  160665. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  160666. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  160667. }
  160668. GLOBAL(void)
  160669. jpeg_write_m_byte (j_compress_ptr cinfo, int val)
  160670. {
  160671. (*cinfo->marker->write_marker_byte) (cinfo, val);
  160672. }
  160673. /*
  160674. * Alternate compression function: just write an abbreviated table file.
  160675. * Before calling this, all parameters and a data destination must be set up.
  160676. *
  160677. * To produce a pair of files containing abbreviated tables and abbreviated
  160678. * image data, one would proceed as follows:
  160679. *
  160680. * initialize JPEG object
  160681. * set JPEG parameters
  160682. * set destination to table file
  160683. * jpeg_write_tables(cinfo);
  160684. * set destination to image file
  160685. * jpeg_start_compress(cinfo, FALSE);
  160686. * write data...
  160687. * jpeg_finish_compress(cinfo);
  160688. *
  160689. * jpeg_write_tables has the side effect of marking all tables written
  160690. * (same as jpeg_suppress_tables(..., TRUE)). Thus a subsequent start_compress
  160691. * will not re-emit the tables unless it is passed write_all_tables=TRUE.
  160692. */
  160693. GLOBAL(void)
  160694. jpeg_write_tables (j_compress_ptr cinfo)
  160695. {
  160696. if (cinfo->global_state != CSTATE_START)
  160697. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  160698. /* (Re)initialize error mgr and destination modules */
  160699. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  160700. (*cinfo->dest->init_destination) (cinfo);
  160701. /* Initialize the marker writer ... bit of a crock to do it here. */
  160702. jinit_marker_writer(cinfo);
  160703. /* Write them tables! */
  160704. (*cinfo->marker->write_tables_only) (cinfo);
  160705. /* And clean up. */
  160706. (*cinfo->dest->term_destination) (cinfo);
  160707. /*
  160708. * In library releases up through v6a, we called jpeg_abort() here to free
  160709. * any working memory allocated by the destination manager and marker
  160710. * writer. Some applications had a problem with that: they allocated space
  160711. * of their own from the library memory manager, and didn't want it to go
  160712. * away during write_tables. So now we do nothing. This will cause a
  160713. * memory leak if an app calls write_tables repeatedly without doing a full
  160714. * compression cycle or otherwise resetting the JPEG object. However, that
  160715. * seems less bad than unexpectedly freeing memory in the normal case.
  160716. * An app that prefers the old behavior can call jpeg_abort for itself after
  160717. * each call to jpeg_write_tables().
  160718. */
  160719. }
  160720. /*** End of inlined file: jcapimin.c ***/
  160721. /*** Start of inlined file: jcapistd.c ***/
  160722. #define JPEG_INTERNALS
  160723. /*
  160724. * Compression initialization.
  160725. * Before calling this, all parameters and a data destination must be set up.
  160726. *
  160727. * We require a write_all_tables parameter as a failsafe check when writing
  160728. * multiple datastreams from the same compression object. Since prior runs
  160729. * will have left all the tables marked sent_table=TRUE, a subsequent run
  160730. * would emit an abbreviated stream (no tables) by default. This may be what
  160731. * is wanted, but for safety's sake it should not be the default behavior:
  160732. * programmers should have to make a deliberate choice to emit abbreviated
  160733. * images. Therefore the documentation and examples should encourage people
  160734. * to pass write_all_tables=TRUE; then it will take active thought to do the
  160735. * wrong thing.
  160736. */
  160737. GLOBAL(void)
  160738. jpeg_start_compress (j_compress_ptr cinfo, boolean write_all_tables)
  160739. {
  160740. if (cinfo->global_state != CSTATE_START)
  160741. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  160742. if (write_all_tables)
  160743. jpeg_suppress_tables(cinfo, FALSE); /* mark all tables to be written */
  160744. /* (Re)initialize error mgr and destination modules */
  160745. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  160746. (*cinfo->dest->init_destination) (cinfo);
  160747. /* Perform master selection of active modules */
  160748. jinit_compress_master(cinfo);
  160749. /* Set up for the first pass */
  160750. (*cinfo->master->prepare_for_pass) (cinfo);
  160751. /* Ready for application to drive first pass through jpeg_write_scanlines
  160752. * or jpeg_write_raw_data.
  160753. */
  160754. cinfo->next_scanline = 0;
  160755. cinfo->global_state = (cinfo->raw_data_in ? CSTATE_RAW_OK : CSTATE_SCANNING);
  160756. }
  160757. /*
  160758. * Write some scanlines of data to the JPEG compressor.
  160759. *
  160760. * The return value will be the number of lines actually written.
  160761. * This should be less than the supplied num_lines only in case that
  160762. * the data destination module has requested suspension of the compressor,
  160763. * or if more than image_height scanlines are passed in.
  160764. *
  160765. * Note: we warn about excess calls to jpeg_write_scanlines() since
  160766. * this likely signals an application programmer error. However,
  160767. * excess scanlines passed in the last valid call are *silently* ignored,
  160768. * so that the application need not adjust num_lines for end-of-image
  160769. * when using a multiple-scanline buffer.
  160770. */
  160771. GLOBAL(JDIMENSION)
  160772. jpeg_write_scanlines (j_compress_ptr cinfo, JSAMPARRAY scanlines,
  160773. JDIMENSION num_lines)
  160774. {
  160775. JDIMENSION row_ctr, rows_left;
  160776. if (cinfo->global_state != CSTATE_SCANNING)
  160777. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  160778. if (cinfo->next_scanline >= cinfo->image_height)
  160779. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  160780. /* Call progress monitor hook if present */
  160781. if (cinfo->progress != NULL) {
  160782. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  160783. cinfo->progress->pass_limit = (long) cinfo->image_height;
  160784. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  160785. }
  160786. /* Give master control module another chance if this is first call to
  160787. * jpeg_write_scanlines. This lets output of the frame/scan headers be
  160788. * delayed so that application can write COM, etc, markers between
  160789. * jpeg_start_compress and jpeg_write_scanlines.
  160790. */
  160791. if (cinfo->master->call_pass_startup)
  160792. (*cinfo->master->pass_startup) (cinfo);
  160793. /* Ignore any extra scanlines at bottom of image. */
  160794. rows_left = cinfo->image_height - cinfo->next_scanline;
  160795. if (num_lines > rows_left)
  160796. num_lines = rows_left;
  160797. row_ctr = 0;
  160798. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, num_lines);
  160799. cinfo->next_scanline += row_ctr;
  160800. return row_ctr;
  160801. }
  160802. /*
  160803. * Alternate entry point to write raw data.
  160804. * Processes exactly one iMCU row per call, unless suspended.
  160805. */
  160806. GLOBAL(JDIMENSION)
  160807. jpeg_write_raw_data (j_compress_ptr cinfo, JSAMPIMAGE data,
  160808. JDIMENSION num_lines)
  160809. {
  160810. JDIMENSION lines_per_iMCU_row;
  160811. if (cinfo->global_state != CSTATE_RAW_OK)
  160812. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  160813. if (cinfo->next_scanline >= cinfo->image_height) {
  160814. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  160815. return 0;
  160816. }
  160817. /* Call progress monitor hook if present */
  160818. if (cinfo->progress != NULL) {
  160819. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  160820. cinfo->progress->pass_limit = (long) cinfo->image_height;
  160821. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  160822. }
  160823. /* Give master control module another chance if this is first call to
  160824. * jpeg_write_raw_data. This lets output of the frame/scan headers be
  160825. * delayed so that application can write COM, etc, markers between
  160826. * jpeg_start_compress and jpeg_write_raw_data.
  160827. */
  160828. if (cinfo->master->call_pass_startup)
  160829. (*cinfo->master->pass_startup) (cinfo);
  160830. /* Verify that at least one iMCU row has been passed. */
  160831. lines_per_iMCU_row = cinfo->max_v_samp_factor * DCTSIZE;
  160832. if (num_lines < lines_per_iMCU_row)
  160833. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  160834. /* Directly compress the row. */
  160835. if (! (*cinfo->coef->compress_data) (cinfo, data)) {
  160836. /* If compressor did not consume the whole row, suspend processing. */
  160837. return 0;
  160838. }
  160839. /* OK, we processed one iMCU row. */
  160840. cinfo->next_scanline += lines_per_iMCU_row;
  160841. return lines_per_iMCU_row;
  160842. }
  160843. /*** End of inlined file: jcapistd.c ***/
  160844. /*** Start of inlined file: jccoefct.c ***/
  160845. #define JPEG_INTERNALS
  160846. /* We use a full-image coefficient buffer when doing Huffman optimization,
  160847. * and also for writing multiple-scan JPEG files. In all cases, the DCT
  160848. * step is run during the first pass, and subsequent passes need only read
  160849. * the buffered coefficients.
  160850. */
  160851. #ifdef ENTROPY_OPT_SUPPORTED
  160852. #define FULL_COEF_BUFFER_SUPPORTED
  160853. #else
  160854. #ifdef C_MULTISCAN_FILES_SUPPORTED
  160855. #define FULL_COEF_BUFFER_SUPPORTED
  160856. #endif
  160857. #endif
  160858. /* Private buffer controller object */
  160859. typedef struct {
  160860. struct jpeg_c_coef_controller pub; /* public fields */
  160861. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  160862. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  160863. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  160864. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  160865. /* For single-pass compression, it's sufficient to buffer just one MCU
  160866. * (although this may prove a bit slow in practice). We allocate a
  160867. * workspace of C_MAX_BLOCKS_IN_MCU coefficient blocks, and reuse it for each
  160868. * MCU constructed and sent. (On 80x86, the workspace is FAR even though
  160869. * it's not really very big; this is to keep the module interfaces unchanged
  160870. * when a large coefficient buffer is necessary.)
  160871. * In multi-pass modes, this array points to the current MCU's blocks
  160872. * within the virtual arrays.
  160873. */
  160874. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  160875. /* In multi-pass modes, we need a virtual block array for each component. */
  160876. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  160877. } my_coef_controller;
  160878. typedef my_coef_controller * my_coef_ptr;
  160879. /* Forward declarations */
  160880. METHODDEF(boolean) compress_data
  160881. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  160882. #ifdef FULL_COEF_BUFFER_SUPPORTED
  160883. METHODDEF(boolean) compress_first_pass
  160884. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  160885. METHODDEF(boolean) compress_output
  160886. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  160887. #endif
  160888. LOCAL(void)
  160889. start_iMCU_row (j_compress_ptr cinfo)
  160890. /* Reset within-iMCU-row counters for a new row */
  160891. {
  160892. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  160893. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  160894. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  160895. * But at the bottom of the image, process only what's left.
  160896. */
  160897. if (cinfo->comps_in_scan > 1) {
  160898. coef->MCU_rows_per_iMCU_row = 1;
  160899. } else {
  160900. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  160901. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  160902. else
  160903. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  160904. }
  160905. coef->mcu_ctr = 0;
  160906. coef->MCU_vert_offset = 0;
  160907. }
  160908. /*
  160909. * Initialize for a processing pass.
  160910. */
  160911. METHODDEF(void)
  160912. start_pass_coef (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  160913. {
  160914. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  160915. coef->iMCU_row_num = 0;
  160916. start_iMCU_row(cinfo);
  160917. switch (pass_mode) {
  160918. case JBUF_PASS_THRU:
  160919. if (coef->whole_image[0] != NULL)
  160920. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  160921. coef->pub.compress_data = compress_data;
  160922. break;
  160923. #ifdef FULL_COEF_BUFFER_SUPPORTED
  160924. case JBUF_SAVE_AND_PASS:
  160925. if (coef->whole_image[0] == NULL)
  160926. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  160927. coef->pub.compress_data = compress_first_pass;
  160928. break;
  160929. case JBUF_CRANK_DEST:
  160930. if (coef->whole_image[0] == NULL)
  160931. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  160932. coef->pub.compress_data = compress_output;
  160933. break;
  160934. #endif
  160935. default:
  160936. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  160937. break;
  160938. }
  160939. }
  160940. /*
  160941. * Process some data in the single-pass case.
  160942. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  160943. * per call, ie, v_samp_factor block rows for each component in the image.
  160944. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  160945. *
  160946. * NB: input_buf contains a plane for each component in image,
  160947. * which we index according to the component's SOF position.
  160948. */
  160949. METHODDEF(boolean)
  160950. compress_data (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  160951. {
  160952. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  160953. JDIMENSION MCU_col_num; /* index of current MCU within row */
  160954. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  160955. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  160956. int blkn, bi, ci, yindex, yoffset, blockcnt;
  160957. JDIMENSION ypos, xpos;
  160958. jpeg_component_info *compptr;
  160959. /* Loop to write as much as one whole iMCU row */
  160960. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  160961. yoffset++) {
  160962. for (MCU_col_num = coef->mcu_ctr; MCU_col_num <= last_MCU_col;
  160963. MCU_col_num++) {
  160964. /* Determine where data comes from in input_buf and do the DCT thing.
  160965. * Each call on forward_DCT processes a horizontal row of DCT blocks
  160966. * as wide as an MCU; we rely on having allocated the MCU_buffer[] blocks
  160967. * sequentially. Dummy blocks at the right or bottom edge are filled in
  160968. * specially. The data in them does not matter for image reconstruction,
  160969. * so we fill them with values that will encode to the smallest amount of
  160970. * data, viz: all zeroes in the AC entries, DC entries equal to previous
  160971. * block's DC value. (Thanks to Thomas Kinsman for this idea.)
  160972. */
  160973. blkn = 0;
  160974. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  160975. compptr = cinfo->cur_comp_info[ci];
  160976. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  160977. : compptr->last_col_width;
  160978. xpos = MCU_col_num * compptr->MCU_sample_width;
  160979. ypos = yoffset * DCTSIZE; /* ypos == (yoffset+yindex) * DCTSIZE */
  160980. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  160981. if (coef->iMCU_row_num < last_iMCU_row ||
  160982. yoffset+yindex < compptr->last_row_height) {
  160983. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  160984. input_buf[compptr->component_index],
  160985. coef->MCU_buffer[blkn],
  160986. ypos, xpos, (JDIMENSION) blockcnt);
  160987. if (blockcnt < compptr->MCU_width) {
  160988. /* Create some dummy blocks at the right edge of the image. */
  160989. jzero_far((void FAR *) coef->MCU_buffer[blkn + blockcnt],
  160990. (compptr->MCU_width - blockcnt) * SIZEOF(JBLOCK));
  160991. for (bi = blockcnt; bi < compptr->MCU_width; bi++) {
  160992. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn+bi-1][0][0];
  160993. }
  160994. }
  160995. } else {
  160996. /* Create a row of dummy blocks at the bottom of the image. */
  160997. jzero_far((void FAR *) coef->MCU_buffer[blkn],
  160998. compptr->MCU_width * SIZEOF(JBLOCK));
  160999. for (bi = 0; bi < compptr->MCU_width; bi++) {
  161000. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn-1][0][0];
  161001. }
  161002. }
  161003. blkn += compptr->MCU_width;
  161004. ypos += DCTSIZE;
  161005. }
  161006. }
  161007. /* Try to write the MCU. In event of a suspension failure, we will
  161008. * re-DCT the MCU on restart (a bit inefficient, could be fixed...)
  161009. */
  161010. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  161011. /* Suspension forced; update state counters and exit */
  161012. coef->MCU_vert_offset = yoffset;
  161013. coef->mcu_ctr = MCU_col_num;
  161014. return FALSE;
  161015. }
  161016. }
  161017. /* Completed an MCU row, but perhaps not an iMCU row */
  161018. coef->mcu_ctr = 0;
  161019. }
  161020. /* Completed the iMCU row, advance counters for next one */
  161021. coef->iMCU_row_num++;
  161022. start_iMCU_row(cinfo);
  161023. return TRUE;
  161024. }
  161025. #ifdef FULL_COEF_BUFFER_SUPPORTED
  161026. /*
  161027. * Process some data in the first pass of a multi-pass case.
  161028. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  161029. * per call, ie, v_samp_factor block rows for each component in the image.
  161030. * This amount of data is read from the source buffer, DCT'd and quantized,
  161031. * and saved into the virtual arrays. We also generate suitable dummy blocks
  161032. * as needed at the right and lower edges. (The dummy blocks are constructed
  161033. * in the virtual arrays, which have been padded appropriately.) This makes
  161034. * it possible for subsequent passes not to worry about real vs. dummy blocks.
  161035. *
  161036. * We must also emit the data to the entropy encoder. This is conveniently
  161037. * done by calling compress_output() after we've loaded the current strip
  161038. * of the virtual arrays.
  161039. *
  161040. * NB: input_buf contains a plane for each component in image. All
  161041. * components are DCT'd and loaded into the virtual arrays in this pass.
  161042. * However, it may be that only a subset of the components are emitted to
  161043. * the entropy encoder during this first pass; be careful about looking
  161044. * at the scan-dependent variables (MCU dimensions, etc).
  161045. */
  161046. METHODDEF(boolean)
  161047. compress_first_pass (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  161048. {
  161049. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161050. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  161051. JDIMENSION blocks_across, MCUs_across, MCUindex;
  161052. int bi, ci, h_samp_factor, block_row, block_rows, ndummy;
  161053. JCOEF lastDC;
  161054. jpeg_component_info *compptr;
  161055. JBLOCKARRAY buffer;
  161056. JBLOCKROW thisblockrow, lastblockrow;
  161057. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  161058. ci++, compptr++) {
  161059. /* Align the virtual buffer for this component. */
  161060. buffer = (*cinfo->mem->access_virt_barray)
  161061. ((j_common_ptr) cinfo, coef->whole_image[ci],
  161062. coef->iMCU_row_num * compptr->v_samp_factor,
  161063. (JDIMENSION) compptr->v_samp_factor, TRUE);
  161064. /* Count non-dummy DCT block rows in this iMCU row. */
  161065. if (coef->iMCU_row_num < last_iMCU_row)
  161066. block_rows = compptr->v_samp_factor;
  161067. else {
  161068. /* NB: can't use last_row_height here, since may not be set! */
  161069. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  161070. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  161071. }
  161072. blocks_across = compptr->width_in_blocks;
  161073. h_samp_factor = compptr->h_samp_factor;
  161074. /* Count number of dummy blocks to be added at the right margin. */
  161075. ndummy = (int) (blocks_across % h_samp_factor);
  161076. if (ndummy > 0)
  161077. ndummy = h_samp_factor - ndummy;
  161078. /* Perform DCT for all non-dummy blocks in this iMCU row. Each call
  161079. * on forward_DCT processes a complete horizontal row of DCT blocks.
  161080. */
  161081. for (block_row = 0; block_row < block_rows; block_row++) {
  161082. thisblockrow = buffer[block_row];
  161083. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  161084. input_buf[ci], thisblockrow,
  161085. (JDIMENSION) (block_row * DCTSIZE),
  161086. (JDIMENSION) 0, blocks_across);
  161087. if (ndummy > 0) {
  161088. /* Create dummy blocks at the right edge of the image. */
  161089. thisblockrow += blocks_across; /* => first dummy block */
  161090. jzero_far((void FAR *) thisblockrow, ndummy * SIZEOF(JBLOCK));
  161091. lastDC = thisblockrow[-1][0];
  161092. for (bi = 0; bi < ndummy; bi++) {
  161093. thisblockrow[bi][0] = lastDC;
  161094. }
  161095. }
  161096. }
  161097. /* If at end of image, create dummy block rows as needed.
  161098. * The tricky part here is that within each MCU, we want the DC values
  161099. * of the dummy blocks to match the last real block's DC value.
  161100. * This squeezes a few more bytes out of the resulting file...
  161101. */
  161102. if (coef->iMCU_row_num == last_iMCU_row) {
  161103. blocks_across += ndummy; /* include lower right corner */
  161104. MCUs_across = blocks_across / h_samp_factor;
  161105. for (block_row = block_rows; block_row < compptr->v_samp_factor;
  161106. block_row++) {
  161107. thisblockrow = buffer[block_row];
  161108. lastblockrow = buffer[block_row-1];
  161109. jzero_far((void FAR *) thisblockrow,
  161110. (size_t) (blocks_across * SIZEOF(JBLOCK)));
  161111. for (MCUindex = 0; MCUindex < MCUs_across; MCUindex++) {
  161112. lastDC = lastblockrow[h_samp_factor-1][0];
  161113. for (bi = 0; bi < h_samp_factor; bi++) {
  161114. thisblockrow[bi][0] = lastDC;
  161115. }
  161116. thisblockrow += h_samp_factor; /* advance to next MCU in row */
  161117. lastblockrow += h_samp_factor;
  161118. }
  161119. }
  161120. }
  161121. }
  161122. /* NB: compress_output will increment iMCU_row_num if successful.
  161123. * A suspension return will result in redoing all the work above next time.
  161124. */
  161125. /* Emit data to the entropy encoder, sharing code with subsequent passes */
  161126. return compress_output(cinfo, input_buf);
  161127. }
  161128. /*
  161129. * Process some data in subsequent passes of a multi-pass case.
  161130. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  161131. * per call, ie, v_samp_factor block rows for each component in the scan.
  161132. * The data is obtained from the virtual arrays and fed to the entropy coder.
  161133. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  161134. *
  161135. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  161136. */
  161137. METHODDEF(boolean)
  161138. compress_output (j_compress_ptr cinfo, JSAMPIMAGE)
  161139. {
  161140. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161141. JDIMENSION MCU_col_num; /* index of current MCU within row */
  161142. int blkn, ci, xindex, yindex, yoffset;
  161143. JDIMENSION start_col;
  161144. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  161145. JBLOCKROW buffer_ptr;
  161146. jpeg_component_info *compptr;
  161147. /* Align the virtual buffers for the components used in this scan.
  161148. * NB: during first pass, this is safe only because the buffers will
  161149. * already be aligned properly, so jmemmgr.c won't need to do any I/O.
  161150. */
  161151. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  161152. compptr = cinfo->cur_comp_info[ci];
  161153. buffer[ci] = (*cinfo->mem->access_virt_barray)
  161154. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  161155. coef->iMCU_row_num * compptr->v_samp_factor,
  161156. (JDIMENSION) compptr->v_samp_factor, FALSE);
  161157. }
  161158. /* Loop to process one whole iMCU row */
  161159. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  161160. yoffset++) {
  161161. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  161162. MCU_col_num++) {
  161163. /* Construct list of pointers to DCT blocks belonging to this MCU */
  161164. blkn = 0; /* index of current DCT block within MCU */
  161165. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  161166. compptr = cinfo->cur_comp_info[ci];
  161167. start_col = MCU_col_num * compptr->MCU_width;
  161168. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  161169. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  161170. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  161171. coef->MCU_buffer[blkn++] = buffer_ptr++;
  161172. }
  161173. }
  161174. }
  161175. /* Try to write the MCU. */
  161176. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  161177. /* Suspension forced; update state counters and exit */
  161178. coef->MCU_vert_offset = yoffset;
  161179. coef->mcu_ctr = MCU_col_num;
  161180. return FALSE;
  161181. }
  161182. }
  161183. /* Completed an MCU row, but perhaps not an iMCU row */
  161184. coef->mcu_ctr = 0;
  161185. }
  161186. /* Completed the iMCU row, advance counters for next one */
  161187. coef->iMCU_row_num++;
  161188. start_iMCU_row(cinfo);
  161189. return TRUE;
  161190. }
  161191. #endif /* FULL_COEF_BUFFER_SUPPORTED */
  161192. /*
  161193. * Initialize coefficient buffer controller.
  161194. */
  161195. GLOBAL(void)
  161196. jinit_c_coef_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  161197. {
  161198. my_coef_ptr coef;
  161199. coef = (my_coef_ptr)
  161200. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161201. SIZEOF(my_coef_controller));
  161202. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  161203. coef->pub.start_pass = start_pass_coef;
  161204. /* Create the coefficient buffer. */
  161205. if (need_full_buffer) {
  161206. #ifdef FULL_COEF_BUFFER_SUPPORTED
  161207. /* Allocate a full-image virtual array for each component, */
  161208. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  161209. int ci;
  161210. jpeg_component_info *compptr;
  161211. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  161212. ci++, compptr++) {
  161213. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  161214. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  161215. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  161216. (long) compptr->h_samp_factor),
  161217. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  161218. (long) compptr->v_samp_factor),
  161219. (JDIMENSION) compptr->v_samp_factor);
  161220. }
  161221. #else
  161222. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161223. #endif
  161224. } else {
  161225. /* We only need a single-MCU buffer. */
  161226. JBLOCKROW buffer;
  161227. int i;
  161228. buffer = (JBLOCKROW)
  161229. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161230. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  161231. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  161232. coef->MCU_buffer[i] = buffer + i;
  161233. }
  161234. coef->whole_image[0] = NULL; /* flag for no virtual arrays */
  161235. }
  161236. }
  161237. /*** End of inlined file: jccoefct.c ***/
  161238. /*** Start of inlined file: jccolor.c ***/
  161239. #define JPEG_INTERNALS
  161240. /* Private subobject */
  161241. typedef struct {
  161242. struct jpeg_color_converter pub; /* public fields */
  161243. /* Private state for RGB->YCC conversion */
  161244. INT32 * rgb_ycc_tab; /* => table for RGB to YCbCr conversion */
  161245. } my_color_converter;
  161246. typedef my_color_converter * my_cconvert_ptr;
  161247. /**************** RGB -> YCbCr conversion: most common case **************/
  161248. /*
  161249. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  161250. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  161251. * The conversion equations to be implemented are therefore
  161252. * Y = 0.29900 * R + 0.58700 * G + 0.11400 * B
  161253. * Cb = -0.16874 * R - 0.33126 * G + 0.50000 * B + CENTERJSAMPLE
  161254. * Cr = 0.50000 * R - 0.41869 * G - 0.08131 * B + CENTERJSAMPLE
  161255. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  161256. * Note: older versions of the IJG code used a zero offset of MAXJSAMPLE/2,
  161257. * rather than CENTERJSAMPLE, for Cb and Cr. This gave equal positive and
  161258. * negative swings for Cb/Cr, but meant that grayscale values (Cb=Cr=0)
  161259. * were not represented exactly. Now we sacrifice exact representation of
  161260. * maximum red and maximum blue in order to get exact grayscales.
  161261. *
  161262. * To avoid floating-point arithmetic, we represent the fractional constants
  161263. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  161264. * the products by 2^16, with appropriate rounding, to get the correct answer.
  161265. *
  161266. * For even more speed, we avoid doing any multiplications in the inner loop
  161267. * by precalculating the constants times R,G,B for all possible values.
  161268. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  161269. * for 12-bit samples it is still acceptable. It's not very reasonable for
  161270. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  161271. * colorspace anyway.
  161272. * The CENTERJSAMPLE offsets and the rounding fudge-factor of 0.5 are included
  161273. * in the tables to save adding them separately in the inner loop.
  161274. */
  161275. #define SCALEBITS 16 /* speediest right-shift on some machines */
  161276. #define CBCR_OFFSET ((INT32) CENTERJSAMPLE << SCALEBITS)
  161277. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  161278. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  161279. /* We allocate one big table and divide it up into eight parts, instead of
  161280. * doing eight alloc_small requests. This lets us use a single table base
  161281. * address, which can be held in a register in the inner loops on many
  161282. * machines (more than can hold all eight addresses, anyway).
  161283. */
  161284. #define R_Y_OFF 0 /* offset to R => Y section */
  161285. #define G_Y_OFF (1*(MAXJSAMPLE+1)) /* offset to G => Y section */
  161286. #define B_Y_OFF (2*(MAXJSAMPLE+1)) /* etc. */
  161287. #define R_CB_OFF (3*(MAXJSAMPLE+1))
  161288. #define G_CB_OFF (4*(MAXJSAMPLE+1))
  161289. #define B_CB_OFF (5*(MAXJSAMPLE+1))
  161290. #define R_CR_OFF B_CB_OFF /* B=>Cb, R=>Cr are the same */
  161291. #define G_CR_OFF (6*(MAXJSAMPLE+1))
  161292. #define B_CR_OFF (7*(MAXJSAMPLE+1))
  161293. #define TABLE_SIZE (8*(MAXJSAMPLE+1))
  161294. /*
  161295. * Initialize for RGB->YCC colorspace conversion.
  161296. */
  161297. METHODDEF(void)
  161298. rgb_ycc_start (j_compress_ptr cinfo)
  161299. {
  161300. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  161301. INT32 * rgb_ycc_tab;
  161302. INT32 i;
  161303. /* Allocate and fill in the conversion tables. */
  161304. cconvert->rgb_ycc_tab = rgb_ycc_tab = (INT32 *)
  161305. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161306. (TABLE_SIZE * SIZEOF(INT32)));
  161307. for (i = 0; i <= MAXJSAMPLE; i++) {
  161308. rgb_ycc_tab[i+R_Y_OFF] = FIX(0.29900) * i;
  161309. rgb_ycc_tab[i+G_Y_OFF] = FIX(0.58700) * i;
  161310. rgb_ycc_tab[i+B_Y_OFF] = FIX(0.11400) * i + ONE_HALF;
  161311. rgb_ycc_tab[i+R_CB_OFF] = (-FIX(0.16874)) * i;
  161312. rgb_ycc_tab[i+G_CB_OFF] = (-FIX(0.33126)) * i;
  161313. /* We use a rounding fudge-factor of 0.5-epsilon for Cb and Cr.
  161314. * This ensures that the maximum output will round to MAXJSAMPLE
  161315. * not MAXJSAMPLE+1, and thus that we don't have to range-limit.
  161316. */
  161317. rgb_ycc_tab[i+B_CB_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  161318. /* B=>Cb and R=>Cr tables are the same
  161319. rgb_ycc_tab[i+R_CR_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  161320. */
  161321. rgb_ycc_tab[i+G_CR_OFF] = (-FIX(0.41869)) * i;
  161322. rgb_ycc_tab[i+B_CR_OFF] = (-FIX(0.08131)) * i;
  161323. }
  161324. }
  161325. /*
  161326. * Convert some rows of samples to the JPEG colorspace.
  161327. *
  161328. * Note that we change from the application's interleaved-pixel format
  161329. * to our internal noninterleaved, one-plane-per-component format.
  161330. * The input buffer is therefore three times as wide as the output buffer.
  161331. *
  161332. * A starting row offset is provided only for the output buffer. The caller
  161333. * can easily adjust the passed input_buf value to accommodate any row
  161334. * offset required on that side.
  161335. */
  161336. METHODDEF(void)
  161337. rgb_ycc_convert (j_compress_ptr cinfo,
  161338. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  161339. JDIMENSION output_row, int num_rows)
  161340. {
  161341. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  161342. register int r, g, b;
  161343. register INT32 * ctab = cconvert->rgb_ycc_tab;
  161344. register JSAMPROW inptr;
  161345. register JSAMPROW outptr0, outptr1, outptr2;
  161346. register JDIMENSION col;
  161347. JDIMENSION num_cols = cinfo->image_width;
  161348. while (--num_rows >= 0) {
  161349. inptr = *input_buf++;
  161350. outptr0 = output_buf[0][output_row];
  161351. outptr1 = output_buf[1][output_row];
  161352. outptr2 = output_buf[2][output_row];
  161353. output_row++;
  161354. for (col = 0; col < num_cols; col++) {
  161355. r = GETJSAMPLE(inptr[RGB_RED]);
  161356. g = GETJSAMPLE(inptr[RGB_GREEN]);
  161357. b = GETJSAMPLE(inptr[RGB_BLUE]);
  161358. inptr += RGB_PIXELSIZE;
  161359. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  161360. * must be too; we do not need an explicit range-limiting operation.
  161361. * Hence the value being shifted is never negative, and we don't
  161362. * need the general RIGHT_SHIFT macro.
  161363. */
  161364. /* Y */
  161365. outptr0[col] = (JSAMPLE)
  161366. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  161367. >> SCALEBITS);
  161368. /* Cb */
  161369. outptr1[col] = (JSAMPLE)
  161370. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  161371. >> SCALEBITS);
  161372. /* Cr */
  161373. outptr2[col] = (JSAMPLE)
  161374. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  161375. >> SCALEBITS);
  161376. }
  161377. }
  161378. }
  161379. /**************** Cases other than RGB -> YCbCr **************/
  161380. /*
  161381. * Convert some rows of samples to the JPEG colorspace.
  161382. * This version handles RGB->grayscale conversion, which is the same
  161383. * as the RGB->Y portion of RGB->YCbCr.
  161384. * We assume rgb_ycc_start has been called (we only use the Y tables).
  161385. */
  161386. METHODDEF(void)
  161387. rgb_gray_convert (j_compress_ptr cinfo,
  161388. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  161389. JDIMENSION output_row, int num_rows)
  161390. {
  161391. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  161392. register int r, g, b;
  161393. register INT32 * ctab = cconvert->rgb_ycc_tab;
  161394. register JSAMPROW inptr;
  161395. register JSAMPROW outptr;
  161396. register JDIMENSION col;
  161397. JDIMENSION num_cols = cinfo->image_width;
  161398. while (--num_rows >= 0) {
  161399. inptr = *input_buf++;
  161400. outptr = output_buf[0][output_row];
  161401. output_row++;
  161402. for (col = 0; col < num_cols; col++) {
  161403. r = GETJSAMPLE(inptr[RGB_RED]);
  161404. g = GETJSAMPLE(inptr[RGB_GREEN]);
  161405. b = GETJSAMPLE(inptr[RGB_BLUE]);
  161406. inptr += RGB_PIXELSIZE;
  161407. /* Y */
  161408. outptr[col] = (JSAMPLE)
  161409. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  161410. >> SCALEBITS);
  161411. }
  161412. }
  161413. }
  161414. /*
  161415. * Convert some rows of samples to the JPEG colorspace.
  161416. * This version handles Adobe-style CMYK->YCCK conversion,
  161417. * where we convert R=1-C, G=1-M, and B=1-Y to YCbCr using the same
  161418. * conversion as above, while passing K (black) unchanged.
  161419. * We assume rgb_ycc_start has been called.
  161420. */
  161421. METHODDEF(void)
  161422. cmyk_ycck_convert (j_compress_ptr cinfo,
  161423. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  161424. JDIMENSION output_row, int num_rows)
  161425. {
  161426. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  161427. register int r, g, b;
  161428. register INT32 * ctab = cconvert->rgb_ycc_tab;
  161429. register JSAMPROW inptr;
  161430. register JSAMPROW outptr0, outptr1, outptr2, outptr3;
  161431. register JDIMENSION col;
  161432. JDIMENSION num_cols = cinfo->image_width;
  161433. while (--num_rows >= 0) {
  161434. inptr = *input_buf++;
  161435. outptr0 = output_buf[0][output_row];
  161436. outptr1 = output_buf[1][output_row];
  161437. outptr2 = output_buf[2][output_row];
  161438. outptr3 = output_buf[3][output_row];
  161439. output_row++;
  161440. for (col = 0; col < num_cols; col++) {
  161441. r = MAXJSAMPLE - GETJSAMPLE(inptr[0]);
  161442. g = MAXJSAMPLE - GETJSAMPLE(inptr[1]);
  161443. b = MAXJSAMPLE - GETJSAMPLE(inptr[2]);
  161444. /* K passes through as-is */
  161445. outptr3[col] = inptr[3]; /* don't need GETJSAMPLE here */
  161446. inptr += 4;
  161447. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  161448. * must be too; we do not need an explicit range-limiting operation.
  161449. * Hence the value being shifted is never negative, and we don't
  161450. * need the general RIGHT_SHIFT macro.
  161451. */
  161452. /* Y */
  161453. outptr0[col] = (JSAMPLE)
  161454. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  161455. >> SCALEBITS);
  161456. /* Cb */
  161457. outptr1[col] = (JSAMPLE)
  161458. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  161459. >> SCALEBITS);
  161460. /* Cr */
  161461. outptr2[col] = (JSAMPLE)
  161462. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  161463. >> SCALEBITS);
  161464. }
  161465. }
  161466. }
  161467. /*
  161468. * Convert some rows of samples to the JPEG colorspace.
  161469. * This version handles grayscale output with no conversion.
  161470. * The source can be either plain grayscale or YCbCr (since Y == gray).
  161471. */
  161472. METHODDEF(void)
  161473. grayscale_convert (j_compress_ptr cinfo,
  161474. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  161475. JDIMENSION output_row, int num_rows)
  161476. {
  161477. register JSAMPROW inptr;
  161478. register JSAMPROW outptr;
  161479. register JDIMENSION col;
  161480. JDIMENSION num_cols = cinfo->image_width;
  161481. int instride = cinfo->input_components;
  161482. while (--num_rows >= 0) {
  161483. inptr = *input_buf++;
  161484. outptr = output_buf[0][output_row];
  161485. output_row++;
  161486. for (col = 0; col < num_cols; col++) {
  161487. outptr[col] = inptr[0]; /* don't need GETJSAMPLE() here */
  161488. inptr += instride;
  161489. }
  161490. }
  161491. }
  161492. /*
  161493. * Convert some rows of samples to the JPEG colorspace.
  161494. * This version handles multi-component colorspaces without conversion.
  161495. * We assume input_components == num_components.
  161496. */
  161497. METHODDEF(void)
  161498. null_convert (j_compress_ptr cinfo,
  161499. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  161500. JDIMENSION output_row, int num_rows)
  161501. {
  161502. register JSAMPROW inptr;
  161503. register JSAMPROW outptr;
  161504. register JDIMENSION col;
  161505. register int ci;
  161506. int nc = cinfo->num_components;
  161507. JDIMENSION num_cols = cinfo->image_width;
  161508. while (--num_rows >= 0) {
  161509. /* It seems fastest to make a separate pass for each component. */
  161510. for (ci = 0; ci < nc; ci++) {
  161511. inptr = *input_buf;
  161512. outptr = output_buf[ci][output_row];
  161513. for (col = 0; col < num_cols; col++) {
  161514. outptr[col] = inptr[ci]; /* don't need GETJSAMPLE() here */
  161515. inptr += nc;
  161516. }
  161517. }
  161518. input_buf++;
  161519. output_row++;
  161520. }
  161521. }
  161522. /*
  161523. * Empty method for start_pass.
  161524. */
  161525. METHODDEF(void)
  161526. null_method (j_compress_ptr)
  161527. {
  161528. /* no work needed */
  161529. }
  161530. /*
  161531. * Module initialization routine for input colorspace conversion.
  161532. */
  161533. GLOBAL(void)
  161534. jinit_color_converter (j_compress_ptr cinfo)
  161535. {
  161536. my_cconvert_ptr cconvert;
  161537. cconvert = (my_cconvert_ptr)
  161538. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161539. SIZEOF(my_color_converter));
  161540. cinfo->cconvert = (struct jpeg_color_converter *) cconvert;
  161541. /* set start_pass to null method until we find out differently */
  161542. cconvert->pub.start_pass = null_method;
  161543. /* Make sure input_components agrees with in_color_space */
  161544. switch (cinfo->in_color_space) {
  161545. case JCS_GRAYSCALE:
  161546. if (cinfo->input_components != 1)
  161547. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  161548. break;
  161549. case JCS_RGB:
  161550. #if RGB_PIXELSIZE != 3
  161551. if (cinfo->input_components != RGB_PIXELSIZE)
  161552. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  161553. break;
  161554. #endif /* else share code with YCbCr */
  161555. case JCS_YCbCr:
  161556. if (cinfo->input_components != 3)
  161557. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  161558. break;
  161559. case JCS_CMYK:
  161560. case JCS_YCCK:
  161561. if (cinfo->input_components != 4)
  161562. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  161563. break;
  161564. default: /* JCS_UNKNOWN can be anything */
  161565. if (cinfo->input_components < 1)
  161566. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  161567. break;
  161568. }
  161569. /* Check num_components, set conversion method based on requested space */
  161570. switch (cinfo->jpeg_color_space) {
  161571. case JCS_GRAYSCALE:
  161572. if (cinfo->num_components != 1)
  161573. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  161574. if (cinfo->in_color_space == JCS_GRAYSCALE)
  161575. cconvert->pub.color_convert = grayscale_convert;
  161576. else if (cinfo->in_color_space == JCS_RGB) {
  161577. cconvert->pub.start_pass = rgb_ycc_start;
  161578. cconvert->pub.color_convert = rgb_gray_convert;
  161579. } else if (cinfo->in_color_space == JCS_YCbCr)
  161580. cconvert->pub.color_convert = grayscale_convert;
  161581. else
  161582. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  161583. break;
  161584. case JCS_RGB:
  161585. if (cinfo->num_components != 3)
  161586. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  161587. if (cinfo->in_color_space == JCS_RGB && RGB_PIXELSIZE == 3)
  161588. cconvert->pub.color_convert = null_convert;
  161589. else
  161590. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  161591. break;
  161592. case JCS_YCbCr:
  161593. if (cinfo->num_components != 3)
  161594. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  161595. if (cinfo->in_color_space == JCS_RGB) {
  161596. cconvert->pub.start_pass = rgb_ycc_start;
  161597. cconvert->pub.color_convert = rgb_ycc_convert;
  161598. } else if (cinfo->in_color_space == JCS_YCbCr)
  161599. cconvert->pub.color_convert = null_convert;
  161600. else
  161601. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  161602. break;
  161603. case JCS_CMYK:
  161604. if (cinfo->num_components != 4)
  161605. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  161606. if (cinfo->in_color_space == JCS_CMYK)
  161607. cconvert->pub.color_convert = null_convert;
  161608. else
  161609. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  161610. break;
  161611. case JCS_YCCK:
  161612. if (cinfo->num_components != 4)
  161613. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  161614. if (cinfo->in_color_space == JCS_CMYK) {
  161615. cconvert->pub.start_pass = rgb_ycc_start;
  161616. cconvert->pub.color_convert = cmyk_ycck_convert;
  161617. } else if (cinfo->in_color_space == JCS_YCCK)
  161618. cconvert->pub.color_convert = null_convert;
  161619. else
  161620. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  161621. break;
  161622. default: /* allow null conversion of JCS_UNKNOWN */
  161623. if (cinfo->jpeg_color_space != cinfo->in_color_space ||
  161624. cinfo->num_components != cinfo->input_components)
  161625. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  161626. cconvert->pub.color_convert = null_convert;
  161627. break;
  161628. }
  161629. }
  161630. /*** End of inlined file: jccolor.c ***/
  161631. #undef FIX
  161632. /*** Start of inlined file: jcdctmgr.c ***/
  161633. #define JPEG_INTERNALS
  161634. /*** Start of inlined file: jdct.h ***/
  161635. /*
  161636. * A forward DCT routine is given a pointer to a work area of type DCTELEM[];
  161637. * the DCT is to be performed in-place in that buffer. Type DCTELEM is int
  161638. * for 8-bit samples, INT32 for 12-bit samples. (NOTE: Floating-point DCT
  161639. * implementations use an array of type FAST_FLOAT, instead.)
  161640. * The DCT inputs are expected to be signed (range +-CENTERJSAMPLE).
  161641. * The DCT outputs are returned scaled up by a factor of 8; they therefore
  161642. * have a range of +-8K for 8-bit data, +-128K for 12-bit data. This
  161643. * convention improves accuracy in integer implementations and saves some
  161644. * work in floating-point ones.
  161645. * Quantization of the output coefficients is done by jcdctmgr.c.
  161646. */
  161647. #ifndef __jdct_h__
  161648. #define __jdct_h__
  161649. #if BITS_IN_JSAMPLE == 8
  161650. typedef int DCTELEM; /* 16 or 32 bits is fine */
  161651. #else
  161652. typedef INT32 DCTELEM; /* must have 32 bits */
  161653. #endif
  161654. typedef JMETHOD(void, forward_DCT_method_ptr, (DCTELEM * data));
  161655. typedef JMETHOD(void, float_DCT_method_ptr, (FAST_FLOAT * data));
  161656. /*
  161657. * An inverse DCT routine is given a pointer to the input JBLOCK and a pointer
  161658. * to an output sample array. The routine must dequantize the input data as
  161659. * well as perform the IDCT; for dequantization, it uses the multiplier table
  161660. * pointed to by compptr->dct_table. The output data is to be placed into the
  161661. * sample array starting at a specified column. (Any row offset needed will
  161662. * be applied to the array pointer before it is passed to the IDCT code.)
  161663. * Note that the number of samples emitted by the IDCT routine is
  161664. * DCT_scaled_size * DCT_scaled_size.
  161665. */
  161666. /* typedef inverse_DCT_method_ptr is declared in jpegint.h */
  161667. /*
  161668. * Each IDCT routine has its own ideas about the best dct_table element type.
  161669. */
  161670. typedef MULTIPLIER ISLOW_MULT_TYPE; /* short or int, whichever is faster */
  161671. #if BITS_IN_JSAMPLE == 8
  161672. typedef MULTIPLIER IFAST_MULT_TYPE; /* 16 bits is OK, use short if faster */
  161673. #define IFAST_SCALE_BITS 2 /* fractional bits in scale factors */
  161674. #else
  161675. typedef INT32 IFAST_MULT_TYPE; /* need 32 bits for scaled quantizers */
  161676. #define IFAST_SCALE_BITS 13 /* fractional bits in scale factors */
  161677. #endif
  161678. typedef FAST_FLOAT FLOAT_MULT_TYPE; /* preferred floating type */
  161679. /*
  161680. * Each IDCT routine is responsible for range-limiting its results and
  161681. * converting them to unsigned form (0..MAXJSAMPLE). The raw outputs could
  161682. * be quite far out of range if the input data is corrupt, so a bulletproof
  161683. * range-limiting step is required. We use a mask-and-table-lookup method
  161684. * to do the combined operations quickly. See the comments with
  161685. * prepare_range_limit_table (in jdmaster.c) for more info.
  161686. */
  161687. #define IDCT_range_limit(cinfo) ((cinfo)->sample_range_limit + CENTERJSAMPLE)
  161688. #define RANGE_MASK (MAXJSAMPLE * 4 + 3) /* 2 bits wider than legal samples */
  161689. /* Short forms of external names for systems with brain-damaged linkers. */
  161690. #ifdef NEED_SHORT_EXTERNAL_NAMES
  161691. #define jpeg_fdct_islow jFDislow
  161692. #define jpeg_fdct_ifast jFDifast
  161693. #define jpeg_fdct_float jFDfloat
  161694. #define jpeg_idct_islow jRDislow
  161695. #define jpeg_idct_ifast jRDifast
  161696. #define jpeg_idct_float jRDfloat
  161697. #define jpeg_idct_4x4 jRD4x4
  161698. #define jpeg_idct_2x2 jRD2x2
  161699. #define jpeg_idct_1x1 jRD1x1
  161700. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  161701. /* Extern declarations for the forward and inverse DCT routines. */
  161702. EXTERN(void) jpeg_fdct_islow JPP((DCTELEM * data));
  161703. EXTERN(void) jpeg_fdct_ifast JPP((DCTELEM * data));
  161704. EXTERN(void) jpeg_fdct_float JPP((FAST_FLOAT * data));
  161705. EXTERN(void) jpeg_idct_islow
  161706. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  161707. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  161708. EXTERN(void) jpeg_idct_ifast
  161709. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  161710. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  161711. EXTERN(void) jpeg_idct_float
  161712. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  161713. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  161714. EXTERN(void) jpeg_idct_4x4
  161715. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  161716. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  161717. EXTERN(void) jpeg_idct_2x2
  161718. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  161719. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  161720. EXTERN(void) jpeg_idct_1x1
  161721. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  161722. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  161723. /*
  161724. * Macros for handling fixed-point arithmetic; these are used by many
  161725. * but not all of the DCT/IDCT modules.
  161726. *
  161727. * All values are expected to be of type INT32.
  161728. * Fractional constants are scaled left by CONST_BITS bits.
  161729. * CONST_BITS is defined within each module using these macros,
  161730. * and may differ from one module to the next.
  161731. */
  161732. #define ONE ((INT32) 1)
  161733. #define CONST_SCALE (ONE << CONST_BITS)
  161734. /* Convert a positive real constant to an integer scaled by CONST_SCALE.
  161735. * Caution: some C compilers fail to reduce "FIX(constant)" at compile time,
  161736. * thus causing a lot of useless floating-point operations at run time.
  161737. */
  161738. #define FIX(x) ((INT32) ((x) * CONST_SCALE + 0.5))
  161739. /* Descale and correctly round an INT32 value that's scaled by N bits.
  161740. * We assume RIGHT_SHIFT rounds towards minus infinity, so adding
  161741. * the fudge factor is correct for either sign of X.
  161742. */
  161743. #define DESCALE(x,n) RIGHT_SHIFT((x) + (ONE << ((n)-1)), n)
  161744. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  161745. * This macro is used only when the two inputs will actually be no more than
  161746. * 16 bits wide, so that a 16x16->32 bit multiply can be used instead of a
  161747. * full 32x32 multiply. This provides a useful speedup on many machines.
  161748. * Unfortunately there is no way to specify a 16x16->32 multiply portably
  161749. * in C, but some C compilers will do the right thing if you provide the
  161750. * correct combination of casts.
  161751. */
  161752. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  161753. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT16) (const)))
  161754. #endif
  161755. #ifdef SHORTxLCONST_32 /* known to work with Microsoft C 6.0 */
  161756. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT32) (const)))
  161757. #endif
  161758. #ifndef MULTIPLY16C16 /* default definition */
  161759. #define MULTIPLY16C16(var,const) ((var) * (const))
  161760. #endif
  161761. /* Same except both inputs are variables. */
  161762. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  161763. #define MULTIPLY16V16(var1,var2) (((INT16) (var1)) * ((INT16) (var2)))
  161764. #endif
  161765. #ifndef MULTIPLY16V16 /* default definition */
  161766. #define MULTIPLY16V16(var1,var2) ((var1) * (var2))
  161767. #endif
  161768. #endif
  161769. /*** End of inlined file: jdct.h ***/
  161770. /* Private declarations for DCT subsystem */
  161771. /* Private subobject for this module */
  161772. typedef struct {
  161773. struct jpeg_forward_dct pub; /* public fields */
  161774. /* Pointer to the DCT routine actually in use */
  161775. forward_DCT_method_ptr do_dct;
  161776. /* The actual post-DCT divisors --- not identical to the quant table
  161777. * entries, because of scaling (especially for an unnormalized DCT).
  161778. * Each table is given in normal array order.
  161779. */
  161780. DCTELEM * divisors[NUM_QUANT_TBLS];
  161781. #ifdef DCT_FLOAT_SUPPORTED
  161782. /* Same as above for the floating-point case. */
  161783. float_DCT_method_ptr do_float_dct;
  161784. FAST_FLOAT * float_divisors[NUM_QUANT_TBLS];
  161785. #endif
  161786. } my_fdct_controller;
  161787. typedef my_fdct_controller * my_fdct_ptr;
  161788. /*
  161789. * Initialize for a processing pass.
  161790. * Verify that all referenced Q-tables are present, and set up
  161791. * the divisor table for each one.
  161792. * In the current implementation, DCT of all components is done during
  161793. * the first pass, even if only some components will be output in the
  161794. * first scan. Hence all components should be examined here.
  161795. */
  161796. METHODDEF(void)
  161797. start_pass_fdctmgr (j_compress_ptr cinfo)
  161798. {
  161799. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  161800. int ci, qtblno, i;
  161801. jpeg_component_info *compptr;
  161802. JQUANT_TBL * qtbl;
  161803. DCTELEM * dtbl;
  161804. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  161805. ci++, compptr++) {
  161806. qtblno = compptr->quant_tbl_no;
  161807. /* Make sure specified quantization table is present */
  161808. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  161809. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  161810. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  161811. qtbl = cinfo->quant_tbl_ptrs[qtblno];
  161812. /* Compute divisors for this quant table */
  161813. /* We may do this more than once for same table, but it's not a big deal */
  161814. switch (cinfo->dct_method) {
  161815. #ifdef DCT_ISLOW_SUPPORTED
  161816. case JDCT_ISLOW:
  161817. /* For LL&M IDCT method, divisors are equal to raw quantization
  161818. * coefficients multiplied by 8 (to counteract scaling).
  161819. */
  161820. if (fdct->divisors[qtblno] == NULL) {
  161821. fdct->divisors[qtblno] = (DCTELEM *)
  161822. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161823. DCTSIZE2 * SIZEOF(DCTELEM));
  161824. }
  161825. dtbl = fdct->divisors[qtblno];
  161826. for (i = 0; i < DCTSIZE2; i++) {
  161827. dtbl[i] = ((DCTELEM) qtbl->quantval[i]) << 3;
  161828. }
  161829. break;
  161830. #endif
  161831. #ifdef DCT_IFAST_SUPPORTED
  161832. case JDCT_IFAST:
  161833. {
  161834. /* For AA&N IDCT method, divisors are equal to quantization
  161835. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  161836. * scalefactor[0] = 1
  161837. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  161838. * We apply a further scale factor of 8.
  161839. */
  161840. #define CONST_BITS 14
  161841. static const INT16 aanscales[DCTSIZE2] = {
  161842. /* precomputed values scaled up by 14 bits */
  161843. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  161844. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  161845. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  161846. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  161847. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  161848. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  161849. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  161850. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  161851. };
  161852. SHIFT_TEMPS
  161853. if (fdct->divisors[qtblno] == NULL) {
  161854. fdct->divisors[qtblno] = (DCTELEM *)
  161855. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161856. DCTSIZE2 * SIZEOF(DCTELEM));
  161857. }
  161858. dtbl = fdct->divisors[qtblno];
  161859. for (i = 0; i < DCTSIZE2; i++) {
  161860. dtbl[i] = (DCTELEM)
  161861. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  161862. (INT32) aanscales[i]),
  161863. CONST_BITS-3);
  161864. }
  161865. }
  161866. break;
  161867. #endif
  161868. #ifdef DCT_FLOAT_SUPPORTED
  161869. case JDCT_FLOAT:
  161870. {
  161871. /* For float AA&N IDCT method, divisors are equal to quantization
  161872. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  161873. * scalefactor[0] = 1
  161874. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  161875. * We apply a further scale factor of 8.
  161876. * What's actually stored is 1/divisor so that the inner loop can
  161877. * use a multiplication rather than a division.
  161878. */
  161879. FAST_FLOAT * fdtbl;
  161880. int row, col;
  161881. static const double aanscalefactor[DCTSIZE] = {
  161882. 1.0, 1.387039845, 1.306562965, 1.175875602,
  161883. 1.0, 0.785694958, 0.541196100, 0.275899379
  161884. };
  161885. if (fdct->float_divisors[qtblno] == NULL) {
  161886. fdct->float_divisors[qtblno] = (FAST_FLOAT *)
  161887. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161888. DCTSIZE2 * SIZEOF(FAST_FLOAT));
  161889. }
  161890. fdtbl = fdct->float_divisors[qtblno];
  161891. i = 0;
  161892. for (row = 0; row < DCTSIZE; row++) {
  161893. for (col = 0; col < DCTSIZE; col++) {
  161894. fdtbl[i] = (FAST_FLOAT)
  161895. (1.0 / (((double) qtbl->quantval[i] *
  161896. aanscalefactor[row] * aanscalefactor[col] * 8.0)));
  161897. i++;
  161898. }
  161899. }
  161900. }
  161901. break;
  161902. #endif
  161903. default:
  161904. ERREXIT(cinfo, JERR_NOT_COMPILED);
  161905. break;
  161906. }
  161907. }
  161908. }
  161909. /*
  161910. * Perform forward DCT on one or more blocks of a component.
  161911. *
  161912. * The input samples are taken from the sample_data[] array starting at
  161913. * position start_row/start_col, and moving to the right for any additional
  161914. * blocks. The quantized coefficients are returned in coef_blocks[].
  161915. */
  161916. METHODDEF(void)
  161917. forward_DCT (j_compress_ptr cinfo, jpeg_component_info * compptr,
  161918. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  161919. JDIMENSION start_row, JDIMENSION start_col,
  161920. JDIMENSION num_blocks)
  161921. /* This version is used for integer DCT implementations. */
  161922. {
  161923. /* This routine is heavily used, so it's worth coding it tightly. */
  161924. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  161925. forward_DCT_method_ptr do_dct = fdct->do_dct;
  161926. DCTELEM * divisors = fdct->divisors[compptr->quant_tbl_no];
  161927. DCTELEM workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  161928. JDIMENSION bi;
  161929. sample_data += start_row; /* fold in the vertical offset once */
  161930. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  161931. /* Load data into workspace, applying unsigned->signed conversion */
  161932. { register DCTELEM *workspaceptr;
  161933. register JSAMPROW elemptr;
  161934. register int elemr;
  161935. workspaceptr = workspace;
  161936. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  161937. elemptr = sample_data[elemr] + start_col;
  161938. #if DCTSIZE == 8 /* unroll the inner loop */
  161939. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  161940. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  161941. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  161942. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  161943. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  161944. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  161945. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  161946. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  161947. #else
  161948. { register int elemc;
  161949. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  161950. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  161951. }
  161952. }
  161953. #endif
  161954. }
  161955. }
  161956. /* Perform the DCT */
  161957. (*do_dct) (workspace);
  161958. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  161959. { register DCTELEM temp, qval;
  161960. register int i;
  161961. register JCOEFPTR output_ptr = coef_blocks[bi];
  161962. for (i = 0; i < DCTSIZE2; i++) {
  161963. qval = divisors[i];
  161964. temp = workspace[i];
  161965. /* Divide the coefficient value by qval, ensuring proper rounding.
  161966. * Since C does not specify the direction of rounding for negative
  161967. * quotients, we have to force the dividend positive for portability.
  161968. *
  161969. * In most files, at least half of the output values will be zero
  161970. * (at default quantization settings, more like three-quarters...)
  161971. * so we should ensure that this case is fast. On many machines,
  161972. * a comparison is enough cheaper than a divide to make a special test
  161973. * a win. Since both inputs will be nonnegative, we need only test
  161974. * for a < b to discover whether a/b is 0.
  161975. * If your machine's division is fast enough, define FAST_DIVIDE.
  161976. */
  161977. #ifdef FAST_DIVIDE
  161978. #define DIVIDE_BY(a,b) a /= b
  161979. #else
  161980. #define DIVIDE_BY(a,b) if (a >= b) a /= b; else a = 0
  161981. #endif
  161982. if (temp < 0) {
  161983. temp = -temp;
  161984. temp += qval>>1; /* for rounding */
  161985. DIVIDE_BY(temp, qval);
  161986. temp = -temp;
  161987. } else {
  161988. temp += qval>>1; /* for rounding */
  161989. DIVIDE_BY(temp, qval);
  161990. }
  161991. output_ptr[i] = (JCOEF) temp;
  161992. }
  161993. }
  161994. }
  161995. }
  161996. #ifdef DCT_FLOAT_SUPPORTED
  161997. METHODDEF(void)
  161998. forward_DCT_float (j_compress_ptr cinfo, jpeg_component_info * compptr,
  161999. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  162000. JDIMENSION start_row, JDIMENSION start_col,
  162001. JDIMENSION num_blocks)
  162002. /* This version is used for floating-point DCT implementations. */
  162003. {
  162004. /* This routine is heavily used, so it's worth coding it tightly. */
  162005. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  162006. float_DCT_method_ptr do_dct = fdct->do_float_dct;
  162007. FAST_FLOAT * divisors = fdct->float_divisors[compptr->quant_tbl_no];
  162008. FAST_FLOAT workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  162009. JDIMENSION bi;
  162010. sample_data += start_row; /* fold in the vertical offset once */
  162011. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  162012. /* Load data into workspace, applying unsigned->signed conversion */
  162013. { register FAST_FLOAT *workspaceptr;
  162014. register JSAMPROW elemptr;
  162015. register int elemr;
  162016. workspaceptr = workspace;
  162017. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  162018. elemptr = sample_data[elemr] + start_col;
  162019. #if DCTSIZE == 8 /* unroll the inner loop */
  162020. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162021. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162022. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162023. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162024. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162025. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162026. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162027. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162028. #else
  162029. { register int elemc;
  162030. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  162031. *workspaceptr++ = (FAST_FLOAT)
  162032. (GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162033. }
  162034. }
  162035. #endif
  162036. }
  162037. }
  162038. /* Perform the DCT */
  162039. (*do_dct) (workspace);
  162040. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  162041. { register FAST_FLOAT temp;
  162042. register int i;
  162043. register JCOEFPTR output_ptr = coef_blocks[bi];
  162044. for (i = 0; i < DCTSIZE2; i++) {
  162045. /* Apply the quantization and scaling factor */
  162046. temp = workspace[i] * divisors[i];
  162047. /* Round to nearest integer.
  162048. * Since C does not specify the direction of rounding for negative
  162049. * quotients, we have to force the dividend positive for portability.
  162050. * The maximum coefficient size is +-16K (for 12-bit data), so this
  162051. * code should work for either 16-bit or 32-bit ints.
  162052. */
  162053. output_ptr[i] = (JCOEF) ((int) (temp + (FAST_FLOAT) 16384.5) - 16384);
  162054. }
  162055. }
  162056. }
  162057. }
  162058. #endif /* DCT_FLOAT_SUPPORTED */
  162059. /*
  162060. * Initialize FDCT manager.
  162061. */
  162062. GLOBAL(void)
  162063. jinit_forward_dct (j_compress_ptr cinfo)
  162064. {
  162065. my_fdct_ptr fdct;
  162066. int i;
  162067. fdct = (my_fdct_ptr)
  162068. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162069. SIZEOF(my_fdct_controller));
  162070. cinfo->fdct = (struct jpeg_forward_dct *) fdct;
  162071. fdct->pub.start_pass = start_pass_fdctmgr;
  162072. switch (cinfo->dct_method) {
  162073. #ifdef DCT_ISLOW_SUPPORTED
  162074. case JDCT_ISLOW:
  162075. fdct->pub.forward_DCT = forward_DCT;
  162076. fdct->do_dct = jpeg_fdct_islow;
  162077. break;
  162078. #endif
  162079. #ifdef DCT_IFAST_SUPPORTED
  162080. case JDCT_IFAST:
  162081. fdct->pub.forward_DCT = forward_DCT;
  162082. fdct->do_dct = jpeg_fdct_ifast;
  162083. break;
  162084. #endif
  162085. #ifdef DCT_FLOAT_SUPPORTED
  162086. case JDCT_FLOAT:
  162087. fdct->pub.forward_DCT = forward_DCT_float;
  162088. fdct->do_float_dct = jpeg_fdct_float;
  162089. break;
  162090. #endif
  162091. default:
  162092. ERREXIT(cinfo, JERR_NOT_COMPILED);
  162093. break;
  162094. }
  162095. /* Mark divisor tables unallocated */
  162096. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  162097. fdct->divisors[i] = NULL;
  162098. #ifdef DCT_FLOAT_SUPPORTED
  162099. fdct->float_divisors[i] = NULL;
  162100. #endif
  162101. }
  162102. }
  162103. /*** End of inlined file: jcdctmgr.c ***/
  162104. #undef CONST_BITS
  162105. /*** Start of inlined file: jchuff.c ***/
  162106. #define JPEG_INTERNALS
  162107. /*** Start of inlined file: jchuff.h ***/
  162108. /* The legal range of a DCT coefficient is
  162109. * -1024 .. +1023 for 8-bit data;
  162110. * -16384 .. +16383 for 12-bit data.
  162111. * Hence the magnitude should always fit in 10 or 14 bits respectively.
  162112. */
  162113. #ifndef _jchuff_h_
  162114. #define _jchuff_h_
  162115. #if BITS_IN_JSAMPLE == 8
  162116. #define MAX_COEF_BITS 10
  162117. #else
  162118. #define MAX_COEF_BITS 14
  162119. #endif
  162120. /* Derived data constructed for each Huffman table */
  162121. typedef struct {
  162122. unsigned int ehufco[256]; /* code for each symbol */
  162123. char ehufsi[256]; /* length of code for each symbol */
  162124. /* If no code has been allocated for a symbol S, ehufsi[S] contains 0 */
  162125. } c_derived_tbl;
  162126. /* Short forms of external names for systems with brain-damaged linkers. */
  162127. #ifdef NEED_SHORT_EXTERNAL_NAMES
  162128. #define jpeg_make_c_derived_tbl jMkCDerived
  162129. #define jpeg_gen_optimal_table jGenOptTbl
  162130. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  162131. /* Expand a Huffman table definition into the derived format */
  162132. EXTERN(void) jpeg_make_c_derived_tbl
  162133. JPP((j_compress_ptr cinfo, boolean isDC, int tblno,
  162134. c_derived_tbl ** pdtbl));
  162135. /* Generate an optimal table definition given the specified counts */
  162136. EXTERN(void) jpeg_gen_optimal_table
  162137. JPP((j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[]));
  162138. #endif
  162139. /*** End of inlined file: jchuff.h ***/
  162140. /* Declarations shared with jcphuff.c */
  162141. /* Expanded entropy encoder object for Huffman encoding.
  162142. *
  162143. * The savable_state subrecord contains fields that change within an MCU,
  162144. * but must not be updated permanently until we complete the MCU.
  162145. */
  162146. typedef struct {
  162147. INT32 put_buffer; /* current bit-accumulation buffer */
  162148. int put_bits; /* # of bits now in it */
  162149. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  162150. } savable_state;
  162151. /* This macro is to work around compilers with missing or broken
  162152. * structure assignment. You'll need to fix this code if you have
  162153. * such a compiler and you change MAX_COMPS_IN_SCAN.
  162154. */
  162155. #ifndef NO_STRUCT_ASSIGN
  162156. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  162157. #else
  162158. #if MAX_COMPS_IN_SCAN == 4
  162159. #define ASSIGN_STATE(dest,src) \
  162160. ((dest).put_buffer = (src).put_buffer, \
  162161. (dest).put_bits = (src).put_bits, \
  162162. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  162163. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  162164. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  162165. (dest).last_dc_val[3] = (src).last_dc_val[3])
  162166. #endif
  162167. #endif
  162168. typedef struct {
  162169. struct jpeg_entropy_encoder pub; /* public fields */
  162170. savable_state saved; /* Bit buffer & DC state at start of MCU */
  162171. /* These fields are NOT loaded into local working state. */
  162172. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  162173. int next_restart_num; /* next restart number to write (0-7) */
  162174. /* Pointers to derived tables (these workspaces have image lifespan) */
  162175. c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  162176. c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  162177. #ifdef ENTROPY_OPT_SUPPORTED /* Statistics tables for optimization */
  162178. long * dc_count_ptrs[NUM_HUFF_TBLS];
  162179. long * ac_count_ptrs[NUM_HUFF_TBLS];
  162180. #endif
  162181. } huff_entropy_encoder;
  162182. typedef huff_entropy_encoder * huff_entropy_ptr;
  162183. /* Working state while writing an MCU.
  162184. * This struct contains all the fields that are needed by subroutines.
  162185. */
  162186. typedef struct {
  162187. JOCTET * next_output_byte; /* => next byte to write in buffer */
  162188. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  162189. savable_state cur; /* Current bit buffer & DC state */
  162190. j_compress_ptr cinfo; /* dump_buffer needs access to this */
  162191. } working_state;
  162192. /* Forward declarations */
  162193. METHODDEF(boolean) encode_mcu_huff JPP((j_compress_ptr cinfo,
  162194. JBLOCKROW *MCU_data));
  162195. METHODDEF(void) finish_pass_huff JPP((j_compress_ptr cinfo));
  162196. #ifdef ENTROPY_OPT_SUPPORTED
  162197. METHODDEF(boolean) encode_mcu_gather JPP((j_compress_ptr cinfo,
  162198. JBLOCKROW *MCU_data));
  162199. METHODDEF(void) finish_pass_gather JPP((j_compress_ptr cinfo));
  162200. #endif
  162201. /*
  162202. * Initialize for a Huffman-compressed scan.
  162203. * If gather_statistics is TRUE, we do not output anything during the scan,
  162204. * just count the Huffman symbols used and generate Huffman code tables.
  162205. */
  162206. METHODDEF(void)
  162207. start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
  162208. {
  162209. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  162210. int ci, dctbl, actbl;
  162211. jpeg_component_info * compptr;
  162212. if (gather_statistics) {
  162213. #ifdef ENTROPY_OPT_SUPPORTED
  162214. entropy->pub.encode_mcu = encode_mcu_gather;
  162215. entropy->pub.finish_pass = finish_pass_gather;
  162216. #else
  162217. ERREXIT(cinfo, JERR_NOT_COMPILED);
  162218. #endif
  162219. } else {
  162220. entropy->pub.encode_mcu = encode_mcu_huff;
  162221. entropy->pub.finish_pass = finish_pass_huff;
  162222. }
  162223. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162224. compptr = cinfo->cur_comp_info[ci];
  162225. dctbl = compptr->dc_tbl_no;
  162226. actbl = compptr->ac_tbl_no;
  162227. if (gather_statistics) {
  162228. #ifdef ENTROPY_OPT_SUPPORTED
  162229. /* Check for invalid table indexes */
  162230. /* (make_c_derived_tbl does this in the other path) */
  162231. if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS)
  162232. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
  162233. if (actbl < 0 || actbl >= NUM_HUFF_TBLS)
  162234. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
  162235. /* Allocate and zero the statistics tables */
  162236. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  162237. if (entropy->dc_count_ptrs[dctbl] == NULL)
  162238. entropy->dc_count_ptrs[dctbl] = (long *)
  162239. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162240. 257 * SIZEOF(long));
  162241. MEMZERO(entropy->dc_count_ptrs[dctbl], 257 * SIZEOF(long));
  162242. if (entropy->ac_count_ptrs[actbl] == NULL)
  162243. entropy->ac_count_ptrs[actbl] = (long *)
  162244. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162245. 257 * SIZEOF(long));
  162246. MEMZERO(entropy->ac_count_ptrs[actbl], 257 * SIZEOF(long));
  162247. #endif
  162248. } else {
  162249. /* Compute derived values for Huffman tables */
  162250. /* We may do this more than once for a table, but it's not expensive */
  162251. jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl,
  162252. & entropy->dc_derived_tbls[dctbl]);
  162253. jpeg_make_c_derived_tbl(cinfo, FALSE, actbl,
  162254. & entropy->ac_derived_tbls[actbl]);
  162255. }
  162256. /* Initialize DC predictions to 0 */
  162257. entropy->saved.last_dc_val[ci] = 0;
  162258. }
  162259. /* Initialize bit buffer to empty */
  162260. entropy->saved.put_buffer = 0;
  162261. entropy->saved.put_bits = 0;
  162262. /* Initialize restart stuff */
  162263. entropy->restarts_to_go = cinfo->restart_interval;
  162264. entropy->next_restart_num = 0;
  162265. }
  162266. /*
  162267. * Compute the derived values for a Huffman table.
  162268. * This routine also performs some validation checks on the table.
  162269. *
  162270. * Note this is also used by jcphuff.c.
  162271. */
  162272. GLOBAL(void)
  162273. jpeg_make_c_derived_tbl (j_compress_ptr cinfo, boolean isDC, int tblno,
  162274. c_derived_tbl ** pdtbl)
  162275. {
  162276. JHUFF_TBL *htbl;
  162277. c_derived_tbl *dtbl;
  162278. int p, i, l, lastp, si, maxsymbol;
  162279. char huffsize[257];
  162280. unsigned int huffcode[257];
  162281. unsigned int code;
  162282. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  162283. * paralleling the order of the symbols themselves in htbl->huffval[].
  162284. */
  162285. /* Find the input Huffman table */
  162286. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  162287. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  162288. htbl =
  162289. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  162290. if (htbl == NULL)
  162291. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  162292. /* Allocate a workspace if we haven't already done so. */
  162293. if (*pdtbl == NULL)
  162294. *pdtbl = (c_derived_tbl *)
  162295. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162296. SIZEOF(c_derived_tbl));
  162297. dtbl = *pdtbl;
  162298. /* Figure C.1: make table of Huffman code length for each symbol */
  162299. p = 0;
  162300. for (l = 1; l <= 16; l++) {
  162301. i = (int) htbl->bits[l];
  162302. if (i < 0 || p + i > 256) /* protect against table overrun */
  162303. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  162304. while (i--)
  162305. huffsize[p++] = (char) l;
  162306. }
  162307. huffsize[p] = 0;
  162308. lastp = p;
  162309. /* Figure C.2: generate the codes themselves */
  162310. /* We also validate that the counts represent a legal Huffman code tree. */
  162311. code = 0;
  162312. si = huffsize[0];
  162313. p = 0;
  162314. while (huffsize[p]) {
  162315. while (((int) huffsize[p]) == si) {
  162316. huffcode[p++] = code;
  162317. code++;
  162318. }
  162319. /* code is now 1 more than the last code used for codelength si; but
  162320. * it must still fit in si bits, since no code is allowed to be all ones.
  162321. */
  162322. if (((INT32) code) >= (((INT32) 1) << si))
  162323. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  162324. code <<= 1;
  162325. si++;
  162326. }
  162327. /* Figure C.3: generate encoding tables */
  162328. /* These are code and size indexed by symbol value */
  162329. /* Set all codeless symbols to have code length 0;
  162330. * this lets us detect duplicate VAL entries here, and later
  162331. * allows emit_bits to detect any attempt to emit such symbols.
  162332. */
  162333. MEMZERO(dtbl->ehufsi, SIZEOF(dtbl->ehufsi));
  162334. /* This is also a convenient place to check for out-of-range
  162335. * and duplicated VAL entries. We allow 0..255 for AC symbols
  162336. * but only 0..15 for DC. (We could constrain them further
  162337. * based on data depth and mode, but this seems enough.)
  162338. */
  162339. maxsymbol = isDC ? 15 : 255;
  162340. for (p = 0; p < lastp; p++) {
  162341. i = htbl->huffval[p];
  162342. if (i < 0 || i > maxsymbol || dtbl->ehufsi[i])
  162343. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  162344. dtbl->ehufco[i] = huffcode[p];
  162345. dtbl->ehufsi[i] = huffsize[p];
  162346. }
  162347. }
  162348. /* Outputting bytes to the file */
  162349. /* Emit a byte, taking 'action' if must suspend. */
  162350. #define emit_byte(state,val,action) \
  162351. { *(state)->next_output_byte++ = (JOCTET) (val); \
  162352. if (--(state)->free_in_buffer == 0) \
  162353. if (! dump_buffer(state)) \
  162354. { action; } }
  162355. LOCAL(boolean)
  162356. dump_buffer (working_state * state)
  162357. /* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
  162358. {
  162359. struct jpeg_destination_mgr * dest = state->cinfo->dest;
  162360. if (! (*dest->empty_output_buffer) (state->cinfo))
  162361. return FALSE;
  162362. /* After a successful buffer dump, must reset buffer pointers */
  162363. state->next_output_byte = dest->next_output_byte;
  162364. state->free_in_buffer = dest->free_in_buffer;
  162365. return TRUE;
  162366. }
  162367. /* Outputting bits to the file */
  162368. /* Only the right 24 bits of put_buffer are used; the valid bits are
  162369. * left-justified in this part. At most 16 bits can be passed to emit_bits
  162370. * in one call, and we never retain more than 7 bits in put_buffer
  162371. * between calls, so 24 bits are sufficient.
  162372. */
  162373. INLINE
  162374. LOCAL(boolean)
  162375. emit_bits (working_state * state, unsigned int code, int size)
  162376. /* Emit some bits; return TRUE if successful, FALSE if must suspend */
  162377. {
  162378. /* This routine is heavily used, so it's worth coding tightly. */
  162379. register INT32 put_buffer = (INT32) code;
  162380. register int put_bits = state->cur.put_bits;
  162381. /* if size is 0, caller used an invalid Huffman table entry */
  162382. if (size == 0)
  162383. ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE);
  162384. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  162385. put_bits += size; /* new number of bits in buffer */
  162386. put_buffer <<= 24 - put_bits; /* align incoming bits */
  162387. put_buffer |= state->cur.put_buffer; /* and merge with old buffer contents */
  162388. while (put_bits >= 8) {
  162389. int c = (int) ((put_buffer >> 16) & 0xFF);
  162390. emit_byte(state, c, return FALSE);
  162391. if (c == 0xFF) { /* need to stuff a zero byte? */
  162392. emit_byte(state, 0, return FALSE);
  162393. }
  162394. put_buffer <<= 8;
  162395. put_bits -= 8;
  162396. }
  162397. state->cur.put_buffer = put_buffer; /* update state variables */
  162398. state->cur.put_bits = put_bits;
  162399. return TRUE;
  162400. }
  162401. LOCAL(boolean)
  162402. flush_bits (working_state * state)
  162403. {
  162404. if (! emit_bits(state, 0x7F, 7)) /* fill any partial byte with ones */
  162405. return FALSE;
  162406. state->cur.put_buffer = 0; /* and reset bit-buffer to empty */
  162407. state->cur.put_bits = 0;
  162408. return TRUE;
  162409. }
  162410. /* Encode a single block's worth of coefficients */
  162411. LOCAL(boolean)
  162412. encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val,
  162413. c_derived_tbl *dctbl, c_derived_tbl *actbl)
  162414. {
  162415. register int temp, temp2;
  162416. register int nbits;
  162417. register int k, r, i;
  162418. /* Encode the DC coefficient difference per section F.1.2.1 */
  162419. temp = temp2 = block[0] - last_dc_val;
  162420. if (temp < 0) {
  162421. temp = -temp; /* temp is abs value of input */
  162422. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  162423. /* This code assumes we are on a two's complement machine */
  162424. temp2--;
  162425. }
  162426. /* Find the number of bits needed for the magnitude of the coefficient */
  162427. nbits = 0;
  162428. while (temp) {
  162429. nbits++;
  162430. temp >>= 1;
  162431. }
  162432. /* Check for out-of-range coefficient values.
  162433. * Since we're encoding a difference, the range limit is twice as much.
  162434. */
  162435. if (nbits > MAX_COEF_BITS+1)
  162436. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  162437. /* Emit the Huffman-coded symbol for the number of bits */
  162438. if (! emit_bits(state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits]))
  162439. return FALSE;
  162440. /* Emit that number of bits of the value, if positive, */
  162441. /* or the complement of its magnitude, if negative. */
  162442. if (nbits) /* emit_bits rejects calls with size 0 */
  162443. if (! emit_bits(state, (unsigned int) temp2, nbits))
  162444. return FALSE;
  162445. /* Encode the AC coefficients per section F.1.2.2 */
  162446. r = 0; /* r = run length of zeros */
  162447. for (k = 1; k < DCTSIZE2; k++) {
  162448. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  162449. r++;
  162450. } else {
  162451. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  162452. while (r > 15) {
  162453. if (! emit_bits(state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0]))
  162454. return FALSE;
  162455. r -= 16;
  162456. }
  162457. temp2 = temp;
  162458. if (temp < 0) {
  162459. temp = -temp; /* temp is abs value of input */
  162460. /* This code assumes we are on a two's complement machine */
  162461. temp2--;
  162462. }
  162463. /* Find the number of bits needed for the magnitude of the coefficient */
  162464. nbits = 1; /* there must be at least one 1 bit */
  162465. while ((temp >>= 1))
  162466. nbits++;
  162467. /* Check for out-of-range coefficient values */
  162468. if (nbits > MAX_COEF_BITS)
  162469. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  162470. /* Emit Huffman symbol for run length / number of bits */
  162471. i = (r << 4) + nbits;
  162472. if (! emit_bits(state, actbl->ehufco[i], actbl->ehufsi[i]))
  162473. return FALSE;
  162474. /* Emit that number of bits of the value, if positive, */
  162475. /* or the complement of its magnitude, if negative. */
  162476. if (! emit_bits(state, (unsigned int) temp2, nbits))
  162477. return FALSE;
  162478. r = 0;
  162479. }
  162480. }
  162481. /* If the last coef(s) were zero, emit an end-of-block code */
  162482. if (r > 0)
  162483. if (! emit_bits(state, actbl->ehufco[0], actbl->ehufsi[0]))
  162484. return FALSE;
  162485. return TRUE;
  162486. }
  162487. /*
  162488. * Emit a restart marker & resynchronize predictions.
  162489. */
  162490. LOCAL(boolean)
  162491. emit_restart (working_state * state, int restart_num)
  162492. {
  162493. int ci;
  162494. if (! flush_bits(state))
  162495. return FALSE;
  162496. emit_byte(state, 0xFF, return FALSE);
  162497. emit_byte(state, JPEG_RST0 + restart_num, return FALSE);
  162498. /* Re-initialize DC predictions to 0 */
  162499. for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
  162500. state->cur.last_dc_val[ci] = 0;
  162501. /* The restart counter is not updated until we successfully write the MCU. */
  162502. return TRUE;
  162503. }
  162504. /*
  162505. * Encode and output one MCU's worth of Huffman-compressed coefficients.
  162506. */
  162507. METHODDEF(boolean)
  162508. encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  162509. {
  162510. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  162511. working_state state;
  162512. int blkn, ci;
  162513. jpeg_component_info * compptr;
  162514. /* Load up working state */
  162515. state.next_output_byte = cinfo->dest->next_output_byte;
  162516. state.free_in_buffer = cinfo->dest->free_in_buffer;
  162517. ASSIGN_STATE(state.cur, entropy->saved);
  162518. state.cinfo = cinfo;
  162519. /* Emit restart marker if needed */
  162520. if (cinfo->restart_interval) {
  162521. if (entropy->restarts_to_go == 0)
  162522. if (! emit_restart(&state, entropy->next_restart_num))
  162523. return FALSE;
  162524. }
  162525. /* Encode the MCU data blocks */
  162526. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  162527. ci = cinfo->MCU_membership[blkn];
  162528. compptr = cinfo->cur_comp_info[ci];
  162529. if (! encode_one_block(&state,
  162530. MCU_data[blkn][0], state.cur.last_dc_val[ci],
  162531. entropy->dc_derived_tbls[compptr->dc_tbl_no],
  162532. entropy->ac_derived_tbls[compptr->ac_tbl_no]))
  162533. return FALSE;
  162534. /* Update last_dc_val */
  162535. state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
  162536. }
  162537. /* Completed MCU, so update state */
  162538. cinfo->dest->next_output_byte = state.next_output_byte;
  162539. cinfo->dest->free_in_buffer = state.free_in_buffer;
  162540. ASSIGN_STATE(entropy->saved, state.cur);
  162541. /* Update restart-interval state too */
  162542. if (cinfo->restart_interval) {
  162543. if (entropy->restarts_to_go == 0) {
  162544. entropy->restarts_to_go = cinfo->restart_interval;
  162545. entropy->next_restart_num++;
  162546. entropy->next_restart_num &= 7;
  162547. }
  162548. entropy->restarts_to_go--;
  162549. }
  162550. return TRUE;
  162551. }
  162552. /*
  162553. * Finish up at the end of a Huffman-compressed scan.
  162554. */
  162555. METHODDEF(void)
  162556. finish_pass_huff (j_compress_ptr cinfo)
  162557. {
  162558. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  162559. working_state state;
  162560. /* Load up working state ... flush_bits needs it */
  162561. state.next_output_byte = cinfo->dest->next_output_byte;
  162562. state.free_in_buffer = cinfo->dest->free_in_buffer;
  162563. ASSIGN_STATE(state.cur, entropy->saved);
  162564. state.cinfo = cinfo;
  162565. /* Flush out the last data */
  162566. if (! flush_bits(&state))
  162567. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  162568. /* Update state */
  162569. cinfo->dest->next_output_byte = state.next_output_byte;
  162570. cinfo->dest->free_in_buffer = state.free_in_buffer;
  162571. ASSIGN_STATE(entropy->saved, state.cur);
  162572. }
  162573. /*
  162574. * Huffman coding optimization.
  162575. *
  162576. * We first scan the supplied data and count the number of uses of each symbol
  162577. * that is to be Huffman-coded. (This process MUST agree with the code above.)
  162578. * Then we build a Huffman coding tree for the observed counts.
  162579. * Symbols which are not needed at all for the particular image are not
  162580. * assigned any code, which saves space in the DHT marker as well as in
  162581. * the compressed data.
  162582. */
  162583. #ifdef ENTROPY_OPT_SUPPORTED
  162584. /* Process a single block's worth of coefficients */
  162585. LOCAL(void)
  162586. htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,
  162587. long dc_counts[], long ac_counts[])
  162588. {
  162589. register int temp;
  162590. register int nbits;
  162591. register int k, r;
  162592. /* Encode the DC coefficient difference per section F.1.2.1 */
  162593. temp = block[0] - last_dc_val;
  162594. if (temp < 0)
  162595. temp = -temp;
  162596. /* Find the number of bits needed for the magnitude of the coefficient */
  162597. nbits = 0;
  162598. while (temp) {
  162599. nbits++;
  162600. temp >>= 1;
  162601. }
  162602. /* Check for out-of-range coefficient values.
  162603. * Since we're encoding a difference, the range limit is twice as much.
  162604. */
  162605. if (nbits > MAX_COEF_BITS+1)
  162606. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  162607. /* Count the Huffman symbol for the number of bits */
  162608. dc_counts[nbits]++;
  162609. /* Encode the AC coefficients per section F.1.2.2 */
  162610. r = 0; /* r = run length of zeros */
  162611. for (k = 1; k < DCTSIZE2; k++) {
  162612. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  162613. r++;
  162614. } else {
  162615. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  162616. while (r > 15) {
  162617. ac_counts[0xF0]++;
  162618. r -= 16;
  162619. }
  162620. /* Find the number of bits needed for the magnitude of the coefficient */
  162621. if (temp < 0)
  162622. temp = -temp;
  162623. /* Find the number of bits needed for the magnitude of the coefficient */
  162624. nbits = 1; /* there must be at least one 1 bit */
  162625. while ((temp >>= 1))
  162626. nbits++;
  162627. /* Check for out-of-range coefficient values */
  162628. if (nbits > MAX_COEF_BITS)
  162629. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  162630. /* Count Huffman symbol for run length / number of bits */
  162631. ac_counts[(r << 4) + nbits]++;
  162632. r = 0;
  162633. }
  162634. }
  162635. /* If the last coef(s) were zero, emit an end-of-block code */
  162636. if (r > 0)
  162637. ac_counts[0]++;
  162638. }
  162639. /*
  162640. * Trial-encode one MCU's worth of Huffman-compressed coefficients.
  162641. * No data is actually output, so no suspension return is possible.
  162642. */
  162643. METHODDEF(boolean)
  162644. encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  162645. {
  162646. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  162647. int blkn, ci;
  162648. jpeg_component_info * compptr;
  162649. /* Take care of restart intervals if needed */
  162650. if (cinfo->restart_interval) {
  162651. if (entropy->restarts_to_go == 0) {
  162652. /* Re-initialize DC predictions to 0 */
  162653. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  162654. entropy->saved.last_dc_val[ci] = 0;
  162655. /* Update restart state */
  162656. entropy->restarts_to_go = cinfo->restart_interval;
  162657. }
  162658. entropy->restarts_to_go--;
  162659. }
  162660. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  162661. ci = cinfo->MCU_membership[blkn];
  162662. compptr = cinfo->cur_comp_info[ci];
  162663. htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
  162664. entropy->dc_count_ptrs[compptr->dc_tbl_no],
  162665. entropy->ac_count_ptrs[compptr->ac_tbl_no]);
  162666. entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
  162667. }
  162668. return TRUE;
  162669. }
  162670. /*
  162671. * Generate the best Huffman code table for the given counts, fill htbl.
  162672. * Note this is also used by jcphuff.c.
  162673. *
  162674. * The JPEG standard requires that no symbol be assigned a codeword of all
  162675. * one bits (so that padding bits added at the end of a compressed segment
  162676. * can't look like a valid code). Because of the canonical ordering of
  162677. * codewords, this just means that there must be an unused slot in the
  162678. * longest codeword length category. Section K.2 of the JPEG spec suggests
  162679. * reserving such a slot by pretending that symbol 256 is a valid symbol
  162680. * with count 1. In theory that's not optimal; giving it count zero but
  162681. * including it in the symbol set anyway should give a better Huffman code.
  162682. * But the theoretically better code actually seems to come out worse in
  162683. * practice, because it produces more all-ones bytes (which incur stuffed
  162684. * zero bytes in the final file). In any case the difference is tiny.
  162685. *
  162686. * The JPEG standard requires Huffman codes to be no more than 16 bits long.
  162687. * If some symbols have a very small but nonzero probability, the Huffman tree
  162688. * must be adjusted to meet the code length restriction. We currently use
  162689. * the adjustment method suggested in JPEG section K.2. This method is *not*
  162690. * optimal; it may not choose the best possible limited-length code. But
  162691. * typically only very-low-frequency symbols will be given less-than-optimal
  162692. * lengths, so the code is almost optimal. Experimental comparisons against
  162693. * an optimal limited-length-code algorithm indicate that the difference is
  162694. * microscopic --- usually less than a hundredth of a percent of total size.
  162695. * So the extra complexity of an optimal algorithm doesn't seem worthwhile.
  162696. */
  162697. GLOBAL(void)
  162698. jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[])
  162699. {
  162700. #define MAX_CLEN 32 /* assumed maximum initial code length */
  162701. UINT8 bits[MAX_CLEN+1]; /* bits[k] = # of symbols with code length k */
  162702. int codesize[257]; /* codesize[k] = code length of symbol k */
  162703. int others[257]; /* next symbol in current branch of tree */
  162704. int c1, c2;
  162705. int p, i, j;
  162706. long v;
  162707. /* This algorithm is explained in section K.2 of the JPEG standard */
  162708. MEMZERO(bits, SIZEOF(bits));
  162709. MEMZERO(codesize, SIZEOF(codesize));
  162710. for (i = 0; i < 257; i++)
  162711. others[i] = -1; /* init links to empty */
  162712. freq[256] = 1; /* make sure 256 has a nonzero count */
  162713. /* Including the pseudo-symbol 256 in the Huffman procedure guarantees
  162714. * that no real symbol is given code-value of all ones, because 256
  162715. * will be placed last in the largest codeword category.
  162716. */
  162717. /* Huffman's basic algorithm to assign optimal code lengths to symbols */
  162718. for (;;) {
  162719. /* Find the smallest nonzero frequency, set c1 = its symbol */
  162720. /* In case of ties, take the larger symbol number */
  162721. c1 = -1;
  162722. v = 1000000000L;
  162723. for (i = 0; i <= 256; i++) {
  162724. if (freq[i] && freq[i] <= v) {
  162725. v = freq[i];
  162726. c1 = i;
  162727. }
  162728. }
  162729. /* Find the next smallest nonzero frequency, set c2 = its symbol */
  162730. /* In case of ties, take the larger symbol number */
  162731. c2 = -1;
  162732. v = 1000000000L;
  162733. for (i = 0; i <= 256; i++) {
  162734. if (freq[i] && freq[i] <= v && i != c1) {
  162735. v = freq[i];
  162736. c2 = i;
  162737. }
  162738. }
  162739. /* Done if we've merged everything into one frequency */
  162740. if (c2 < 0)
  162741. break;
  162742. /* Else merge the two counts/trees */
  162743. freq[c1] += freq[c2];
  162744. freq[c2] = 0;
  162745. /* Increment the codesize of everything in c1's tree branch */
  162746. codesize[c1]++;
  162747. while (others[c1] >= 0) {
  162748. c1 = others[c1];
  162749. codesize[c1]++;
  162750. }
  162751. others[c1] = c2; /* chain c2 onto c1's tree branch */
  162752. /* Increment the codesize of everything in c2's tree branch */
  162753. codesize[c2]++;
  162754. while (others[c2] >= 0) {
  162755. c2 = others[c2];
  162756. codesize[c2]++;
  162757. }
  162758. }
  162759. /* Now count the number of symbols of each code length */
  162760. for (i = 0; i <= 256; i++) {
  162761. if (codesize[i]) {
  162762. /* The JPEG standard seems to think that this can't happen, */
  162763. /* but I'm paranoid... */
  162764. if (codesize[i] > MAX_CLEN)
  162765. ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW);
  162766. bits[codesize[i]]++;
  162767. }
  162768. }
  162769. /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure
  162770. * Huffman procedure assigned any such lengths, we must adjust the coding.
  162771. * Here is what the JPEG spec says about how this next bit works:
  162772. * Since symbols are paired for the longest Huffman code, the symbols are
  162773. * removed from this length category two at a time. The prefix for the pair
  162774. * (which is one bit shorter) is allocated to one of the pair; then,
  162775. * skipping the BITS entry for that prefix length, a code word from the next
  162776. * shortest nonzero BITS entry is converted into a prefix for two code words
  162777. * one bit longer.
  162778. */
  162779. for (i = MAX_CLEN; i > 16; i--) {
  162780. while (bits[i] > 0) {
  162781. j = i - 2; /* find length of new prefix to be used */
  162782. while (bits[j] == 0)
  162783. j--;
  162784. bits[i] -= 2; /* remove two symbols */
  162785. bits[i-1]++; /* one goes in this length */
  162786. bits[j+1] += 2; /* two new symbols in this length */
  162787. bits[j]--; /* symbol of this length is now a prefix */
  162788. }
  162789. }
  162790. /* Remove the count for the pseudo-symbol 256 from the largest codelength */
  162791. while (bits[i] == 0) /* find largest codelength still in use */
  162792. i--;
  162793. bits[i]--;
  162794. /* Return final symbol counts (only for lengths 0..16) */
  162795. MEMCOPY(htbl->bits, bits, SIZEOF(htbl->bits));
  162796. /* Return a list of the symbols sorted by code length */
  162797. /* It's not real clear to me why we don't need to consider the codelength
  162798. * changes made above, but the JPEG spec seems to think this works.
  162799. */
  162800. p = 0;
  162801. for (i = 1; i <= MAX_CLEN; i++) {
  162802. for (j = 0; j <= 255; j++) {
  162803. if (codesize[j] == i) {
  162804. htbl->huffval[p] = (UINT8) j;
  162805. p++;
  162806. }
  162807. }
  162808. }
  162809. /* Set sent_table FALSE so updated table will be written to JPEG file. */
  162810. htbl->sent_table = FALSE;
  162811. }
  162812. /*
  162813. * Finish up a statistics-gathering pass and create the new Huffman tables.
  162814. */
  162815. METHODDEF(void)
  162816. finish_pass_gather (j_compress_ptr cinfo)
  162817. {
  162818. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  162819. int ci, dctbl, actbl;
  162820. jpeg_component_info * compptr;
  162821. JHUFF_TBL **htblptr;
  162822. boolean did_dc[NUM_HUFF_TBLS];
  162823. boolean did_ac[NUM_HUFF_TBLS];
  162824. /* It's important not to apply jpeg_gen_optimal_table more than once
  162825. * per table, because it clobbers the input frequency counts!
  162826. */
  162827. MEMZERO(did_dc, SIZEOF(did_dc));
  162828. MEMZERO(did_ac, SIZEOF(did_ac));
  162829. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162830. compptr = cinfo->cur_comp_info[ci];
  162831. dctbl = compptr->dc_tbl_no;
  162832. actbl = compptr->ac_tbl_no;
  162833. if (! did_dc[dctbl]) {
  162834. htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl];
  162835. if (*htblptr == NULL)
  162836. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  162837. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);
  162838. did_dc[dctbl] = TRUE;
  162839. }
  162840. if (! did_ac[actbl]) {
  162841. htblptr = & cinfo->ac_huff_tbl_ptrs[actbl];
  162842. if (*htblptr == NULL)
  162843. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  162844. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);
  162845. did_ac[actbl] = TRUE;
  162846. }
  162847. }
  162848. }
  162849. #endif /* ENTROPY_OPT_SUPPORTED */
  162850. /*
  162851. * Module initialization routine for Huffman entropy encoding.
  162852. */
  162853. GLOBAL(void)
  162854. jinit_huff_encoder (j_compress_ptr cinfo)
  162855. {
  162856. huff_entropy_ptr entropy;
  162857. int i;
  162858. entropy = (huff_entropy_ptr)
  162859. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162860. SIZEOF(huff_entropy_encoder));
  162861. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  162862. entropy->pub.start_pass = start_pass_huff;
  162863. /* Mark tables unallocated */
  162864. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  162865. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  162866. #ifdef ENTROPY_OPT_SUPPORTED
  162867. entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
  162868. #endif
  162869. }
  162870. }
  162871. /*** End of inlined file: jchuff.c ***/
  162872. #undef emit_byte
  162873. /*** Start of inlined file: jcinit.c ***/
  162874. #define JPEG_INTERNALS
  162875. /*
  162876. * Master selection of compression modules.
  162877. * This is done once at the start of processing an image. We determine
  162878. * which modules will be used and give them appropriate initialization calls.
  162879. */
  162880. GLOBAL(void)
  162881. jinit_compress_master (j_compress_ptr cinfo)
  162882. {
  162883. /* Initialize master control (includes parameter checking/processing) */
  162884. jinit_c_master_control(cinfo, FALSE /* full compression */);
  162885. /* Preprocessing */
  162886. if (! cinfo->raw_data_in) {
  162887. jinit_color_converter(cinfo);
  162888. jinit_downsampler(cinfo);
  162889. jinit_c_prep_controller(cinfo, FALSE /* never need full buffer here */);
  162890. }
  162891. /* Forward DCT */
  162892. jinit_forward_dct(cinfo);
  162893. /* Entropy encoding: either Huffman or arithmetic coding. */
  162894. if (cinfo->arith_code) {
  162895. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  162896. } else {
  162897. if (cinfo->progressive_mode) {
  162898. #ifdef C_PROGRESSIVE_SUPPORTED
  162899. jinit_phuff_encoder(cinfo);
  162900. #else
  162901. ERREXIT(cinfo, JERR_NOT_COMPILED);
  162902. #endif
  162903. } else
  162904. jinit_huff_encoder(cinfo);
  162905. }
  162906. /* Need a full-image coefficient buffer in any multi-pass mode. */
  162907. jinit_c_coef_controller(cinfo,
  162908. (boolean) (cinfo->num_scans > 1 || cinfo->optimize_coding));
  162909. jinit_c_main_controller(cinfo, FALSE /* never need full buffer here */);
  162910. jinit_marker_writer(cinfo);
  162911. /* We can now tell the memory manager to allocate virtual arrays. */
  162912. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  162913. /* Write the datastream header (SOI) immediately.
  162914. * Frame and scan headers are postponed till later.
  162915. * This lets application insert special markers after the SOI.
  162916. */
  162917. (*cinfo->marker->write_file_header) (cinfo);
  162918. }
  162919. /*** End of inlined file: jcinit.c ***/
  162920. /*** Start of inlined file: jcmainct.c ***/
  162921. #define JPEG_INTERNALS
  162922. /* Note: currently, there is no operating mode in which a full-image buffer
  162923. * is needed at this step. If there were, that mode could not be used with
  162924. * "raw data" input, since this module is bypassed in that case. However,
  162925. * we've left the code here for possible use in special applications.
  162926. */
  162927. #undef FULL_MAIN_BUFFER_SUPPORTED
  162928. /* Private buffer controller object */
  162929. typedef struct {
  162930. struct jpeg_c_main_controller pub; /* public fields */
  162931. JDIMENSION cur_iMCU_row; /* number of current iMCU row */
  162932. JDIMENSION rowgroup_ctr; /* counts row groups received in iMCU row */
  162933. boolean suspended; /* remember if we suspended output */
  162934. J_BUF_MODE pass_mode; /* current operating mode */
  162935. /* If using just a strip buffer, this points to the entire set of buffers
  162936. * (we allocate one for each component). In the full-image case, this
  162937. * points to the currently accessible strips of the virtual arrays.
  162938. */
  162939. JSAMPARRAY buffer[MAX_COMPONENTS];
  162940. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  162941. /* If using full-image storage, this array holds pointers to virtual-array
  162942. * control blocks for each component. Unused if not full-image storage.
  162943. */
  162944. jvirt_sarray_ptr whole_image[MAX_COMPONENTS];
  162945. #endif
  162946. } my_main_controller;
  162947. typedef my_main_controller * my_main_ptr;
  162948. /* Forward declarations */
  162949. METHODDEF(void) process_data_simple_main
  162950. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  162951. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  162952. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  162953. METHODDEF(void) process_data_buffer_main
  162954. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  162955. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  162956. #endif
  162957. /*
  162958. * Initialize for a processing pass.
  162959. */
  162960. METHODDEF(void)
  162961. start_pass_main (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  162962. {
  162963. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  162964. /* Do nothing in raw-data mode. */
  162965. if (cinfo->raw_data_in)
  162966. return;
  162967. main_->cur_iMCU_row = 0; /* initialize counters */
  162968. main_->rowgroup_ctr = 0;
  162969. main_->suspended = FALSE;
  162970. main_->pass_mode = pass_mode; /* save mode for use by process_data */
  162971. switch (pass_mode) {
  162972. case JBUF_PASS_THRU:
  162973. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  162974. if (main_->whole_image[0] != NULL)
  162975. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162976. #endif
  162977. main_->pub.process_data = process_data_simple_main;
  162978. break;
  162979. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  162980. case JBUF_SAVE_SOURCE:
  162981. case JBUF_CRANK_DEST:
  162982. case JBUF_SAVE_AND_PASS:
  162983. if (main_->whole_image[0] == NULL)
  162984. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162985. main_->pub.process_data = process_data_buffer_main;
  162986. break;
  162987. #endif
  162988. default:
  162989. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162990. break;
  162991. }
  162992. }
  162993. /*
  162994. * Process some data.
  162995. * This routine handles the simple pass-through mode,
  162996. * where we have only a strip buffer.
  162997. */
  162998. METHODDEF(void)
  162999. process_data_simple_main (j_compress_ptr cinfo,
  163000. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  163001. JDIMENSION in_rows_avail)
  163002. {
  163003. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  163004. while (main_->cur_iMCU_row < cinfo->total_iMCU_rows) {
  163005. /* Read input data if we haven't filled the main buffer yet */
  163006. if (main_->rowgroup_ctr < DCTSIZE)
  163007. (*cinfo->prep->pre_process_data) (cinfo,
  163008. input_buf, in_row_ctr, in_rows_avail,
  163009. main_->buffer, &main_->rowgroup_ctr,
  163010. (JDIMENSION) DCTSIZE);
  163011. /* If we don't have a full iMCU row buffered, return to application for
  163012. * more data. Note that preprocessor will always pad to fill the iMCU row
  163013. * at the bottom of the image.
  163014. */
  163015. if (main_->rowgroup_ctr != DCTSIZE)
  163016. return;
  163017. /* Send the completed row to the compressor */
  163018. if (! (*cinfo->coef->compress_data) (cinfo, main_->buffer)) {
  163019. /* If compressor did not consume the whole row, then we must need to
  163020. * suspend processing and return to the application. In this situation
  163021. * we pretend we didn't yet consume the last input row; otherwise, if
  163022. * it happened to be the last row of the image, the application would
  163023. * think we were done.
  163024. */
  163025. if (! main_->suspended) {
  163026. (*in_row_ctr)--;
  163027. main_->suspended = TRUE;
  163028. }
  163029. return;
  163030. }
  163031. /* We did finish the row. Undo our little suspension hack if a previous
  163032. * call suspended; then mark the main buffer empty.
  163033. */
  163034. if (main_->suspended) {
  163035. (*in_row_ctr)++;
  163036. main_->suspended = FALSE;
  163037. }
  163038. main_->rowgroup_ctr = 0;
  163039. main_->cur_iMCU_row++;
  163040. }
  163041. }
  163042. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163043. /*
  163044. * Process some data.
  163045. * This routine handles all of the modes that use a full-size buffer.
  163046. */
  163047. METHODDEF(void)
  163048. process_data_buffer_main (j_compress_ptr cinfo,
  163049. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  163050. JDIMENSION in_rows_avail)
  163051. {
  163052. my_main_ptr main = (my_main_ptr) cinfo->main;
  163053. int ci;
  163054. jpeg_component_info *compptr;
  163055. boolean writing = (main->pass_mode != JBUF_CRANK_DEST);
  163056. while (main->cur_iMCU_row < cinfo->total_iMCU_rows) {
  163057. /* Realign the virtual buffers if at the start of an iMCU row. */
  163058. if (main->rowgroup_ctr == 0) {
  163059. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163060. ci++, compptr++) {
  163061. main->buffer[ci] = (*cinfo->mem->access_virt_sarray)
  163062. ((j_common_ptr) cinfo, main->whole_image[ci],
  163063. main->cur_iMCU_row * (compptr->v_samp_factor * DCTSIZE),
  163064. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE), writing);
  163065. }
  163066. /* In a read pass, pretend we just read some source data. */
  163067. if (! writing) {
  163068. *in_row_ctr += cinfo->max_v_samp_factor * DCTSIZE;
  163069. main->rowgroup_ctr = DCTSIZE;
  163070. }
  163071. }
  163072. /* If a write pass, read input data until the current iMCU row is full. */
  163073. /* Note: preprocessor will pad if necessary to fill the last iMCU row. */
  163074. if (writing) {
  163075. (*cinfo->prep->pre_process_data) (cinfo,
  163076. input_buf, in_row_ctr, in_rows_avail,
  163077. main->buffer, &main->rowgroup_ctr,
  163078. (JDIMENSION) DCTSIZE);
  163079. /* Return to application if we need more data to fill the iMCU row. */
  163080. if (main->rowgroup_ctr < DCTSIZE)
  163081. return;
  163082. }
  163083. /* Emit data, unless this is a sink-only pass. */
  163084. if (main->pass_mode != JBUF_SAVE_SOURCE) {
  163085. if (! (*cinfo->coef->compress_data) (cinfo, main->buffer)) {
  163086. /* If compressor did not consume the whole row, then we must need to
  163087. * suspend processing and return to the application. In this situation
  163088. * we pretend we didn't yet consume the last input row; otherwise, if
  163089. * it happened to be the last row of the image, the application would
  163090. * think we were done.
  163091. */
  163092. if (! main->suspended) {
  163093. (*in_row_ctr)--;
  163094. main->suspended = TRUE;
  163095. }
  163096. return;
  163097. }
  163098. /* We did finish the row. Undo our little suspension hack if a previous
  163099. * call suspended; then mark the main buffer empty.
  163100. */
  163101. if (main->suspended) {
  163102. (*in_row_ctr)++;
  163103. main->suspended = FALSE;
  163104. }
  163105. }
  163106. /* If get here, we are done with this iMCU row. Mark buffer empty. */
  163107. main->rowgroup_ctr = 0;
  163108. main->cur_iMCU_row++;
  163109. }
  163110. }
  163111. #endif /* FULL_MAIN_BUFFER_SUPPORTED */
  163112. /*
  163113. * Initialize main buffer controller.
  163114. */
  163115. GLOBAL(void)
  163116. jinit_c_main_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  163117. {
  163118. my_main_ptr main_;
  163119. int ci;
  163120. jpeg_component_info *compptr;
  163121. main_ = (my_main_ptr)
  163122. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163123. SIZEOF(my_main_controller));
  163124. cinfo->main = (struct jpeg_c_main_controller *) main_;
  163125. main_->pub.start_pass = start_pass_main;
  163126. /* We don't need to create a buffer in raw-data mode. */
  163127. if (cinfo->raw_data_in)
  163128. return;
  163129. /* Create the buffer. It holds downsampled data, so each component
  163130. * may be of a different size.
  163131. */
  163132. if (need_full_buffer) {
  163133. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163134. /* Allocate a full-image virtual array for each component */
  163135. /* Note we pad the bottom to a multiple of the iMCU height */
  163136. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163137. ci++, compptr++) {
  163138. main->whole_image[ci] = (*cinfo->mem->request_virt_sarray)
  163139. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  163140. compptr->width_in_blocks * DCTSIZE,
  163141. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  163142. (long) compptr->v_samp_factor) * DCTSIZE,
  163143. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  163144. }
  163145. #else
  163146. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  163147. #endif
  163148. } else {
  163149. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163150. main_->whole_image[0] = NULL; /* flag for no virtual arrays */
  163151. #endif
  163152. /* Allocate a strip buffer for each component */
  163153. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163154. ci++, compptr++) {
  163155. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  163156. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163157. compptr->width_in_blocks * DCTSIZE,
  163158. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  163159. }
  163160. }
  163161. }
  163162. /*** End of inlined file: jcmainct.c ***/
  163163. /*** Start of inlined file: jcmarker.c ***/
  163164. #define JPEG_INTERNALS
  163165. /* Private state */
  163166. typedef struct {
  163167. struct jpeg_marker_writer pub; /* public fields */
  163168. unsigned int last_restart_interval; /* last DRI value emitted; 0 after SOI */
  163169. } my_marker_writer;
  163170. typedef my_marker_writer * my_marker_ptr;
  163171. /*
  163172. * Basic output routines.
  163173. *
  163174. * Note that we do not support suspension while writing a marker.
  163175. * Therefore, an application using suspension must ensure that there is
  163176. * enough buffer space for the initial markers (typ. 600-700 bytes) before
  163177. * calling jpeg_start_compress, and enough space to write the trailing EOI
  163178. * (a few bytes) before calling jpeg_finish_compress. Multipass compression
  163179. * modes are not supported at all with suspension, so those two are the only
  163180. * points where markers will be written.
  163181. */
  163182. LOCAL(void)
  163183. emit_byte (j_compress_ptr cinfo, int val)
  163184. /* Emit a byte */
  163185. {
  163186. struct jpeg_destination_mgr * dest = cinfo->dest;
  163187. *(dest->next_output_byte)++ = (JOCTET) val;
  163188. if (--dest->free_in_buffer == 0) {
  163189. if (! (*dest->empty_output_buffer) (cinfo))
  163190. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  163191. }
  163192. }
  163193. LOCAL(void)
  163194. emit_marker (j_compress_ptr cinfo, JPEG_MARKER mark)
  163195. /* Emit a marker code */
  163196. {
  163197. emit_byte(cinfo, 0xFF);
  163198. emit_byte(cinfo, (int) mark);
  163199. }
  163200. LOCAL(void)
  163201. emit_2bytes (j_compress_ptr cinfo, int value)
  163202. /* Emit a 2-byte integer; these are always MSB first in JPEG files */
  163203. {
  163204. emit_byte(cinfo, (value >> 8) & 0xFF);
  163205. emit_byte(cinfo, value & 0xFF);
  163206. }
  163207. /*
  163208. * Routines to write specific marker types.
  163209. */
  163210. LOCAL(int)
  163211. emit_dqt (j_compress_ptr cinfo, int index)
  163212. /* Emit a DQT marker */
  163213. /* Returns the precision used (0 = 8bits, 1 = 16bits) for baseline checking */
  163214. {
  163215. JQUANT_TBL * qtbl = cinfo->quant_tbl_ptrs[index];
  163216. int prec;
  163217. int i;
  163218. if (qtbl == NULL)
  163219. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, index);
  163220. prec = 0;
  163221. for (i = 0; i < DCTSIZE2; i++) {
  163222. if (qtbl->quantval[i] > 255)
  163223. prec = 1;
  163224. }
  163225. if (! qtbl->sent_table) {
  163226. emit_marker(cinfo, M_DQT);
  163227. emit_2bytes(cinfo, prec ? DCTSIZE2*2 + 1 + 2 : DCTSIZE2 + 1 + 2);
  163228. emit_byte(cinfo, index + (prec<<4));
  163229. for (i = 0; i < DCTSIZE2; i++) {
  163230. /* The table entries must be emitted in zigzag order. */
  163231. unsigned int qval = qtbl->quantval[jpeg_natural_order[i]];
  163232. if (prec)
  163233. emit_byte(cinfo, (int) (qval >> 8));
  163234. emit_byte(cinfo, (int) (qval & 0xFF));
  163235. }
  163236. qtbl->sent_table = TRUE;
  163237. }
  163238. return prec;
  163239. }
  163240. LOCAL(void)
  163241. emit_dht (j_compress_ptr cinfo, int index, boolean is_ac)
  163242. /* Emit a DHT marker */
  163243. {
  163244. JHUFF_TBL * htbl;
  163245. int length, i;
  163246. if (is_ac) {
  163247. htbl = cinfo->ac_huff_tbl_ptrs[index];
  163248. index += 0x10; /* output index has AC bit set */
  163249. } else {
  163250. htbl = cinfo->dc_huff_tbl_ptrs[index];
  163251. }
  163252. if (htbl == NULL)
  163253. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, index);
  163254. if (! htbl->sent_table) {
  163255. emit_marker(cinfo, M_DHT);
  163256. length = 0;
  163257. for (i = 1; i <= 16; i++)
  163258. length += htbl->bits[i];
  163259. emit_2bytes(cinfo, length + 2 + 1 + 16);
  163260. emit_byte(cinfo, index);
  163261. for (i = 1; i <= 16; i++)
  163262. emit_byte(cinfo, htbl->bits[i]);
  163263. for (i = 0; i < length; i++)
  163264. emit_byte(cinfo, htbl->huffval[i]);
  163265. htbl->sent_table = TRUE;
  163266. }
  163267. }
  163268. LOCAL(void)
  163269. emit_dac (j_compress_ptr)
  163270. /* Emit a DAC marker */
  163271. /* Since the useful info is so small, we want to emit all the tables in */
  163272. /* one DAC marker. Therefore this routine does its own scan of the table. */
  163273. {
  163274. #ifdef C_ARITH_CODING_SUPPORTED
  163275. char dc_in_use[NUM_ARITH_TBLS];
  163276. char ac_in_use[NUM_ARITH_TBLS];
  163277. int length, i;
  163278. jpeg_component_info *compptr;
  163279. for (i = 0; i < NUM_ARITH_TBLS; i++)
  163280. dc_in_use[i] = ac_in_use[i] = 0;
  163281. for (i = 0; i < cinfo->comps_in_scan; i++) {
  163282. compptr = cinfo->cur_comp_info[i];
  163283. dc_in_use[compptr->dc_tbl_no] = 1;
  163284. ac_in_use[compptr->ac_tbl_no] = 1;
  163285. }
  163286. length = 0;
  163287. for (i = 0; i < NUM_ARITH_TBLS; i++)
  163288. length += dc_in_use[i] + ac_in_use[i];
  163289. emit_marker(cinfo, M_DAC);
  163290. emit_2bytes(cinfo, length*2 + 2);
  163291. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  163292. if (dc_in_use[i]) {
  163293. emit_byte(cinfo, i);
  163294. emit_byte(cinfo, cinfo->arith_dc_L[i] + (cinfo->arith_dc_U[i]<<4));
  163295. }
  163296. if (ac_in_use[i]) {
  163297. emit_byte(cinfo, i + 0x10);
  163298. emit_byte(cinfo, cinfo->arith_ac_K[i]);
  163299. }
  163300. }
  163301. #endif /* C_ARITH_CODING_SUPPORTED */
  163302. }
  163303. LOCAL(void)
  163304. emit_dri (j_compress_ptr cinfo)
  163305. /* Emit a DRI marker */
  163306. {
  163307. emit_marker(cinfo, M_DRI);
  163308. emit_2bytes(cinfo, 4); /* fixed length */
  163309. emit_2bytes(cinfo, (int) cinfo->restart_interval);
  163310. }
  163311. LOCAL(void)
  163312. emit_sof (j_compress_ptr cinfo, JPEG_MARKER code)
  163313. /* Emit a SOF marker */
  163314. {
  163315. int ci;
  163316. jpeg_component_info *compptr;
  163317. emit_marker(cinfo, code);
  163318. emit_2bytes(cinfo, 3 * cinfo->num_components + 2 + 5 + 1); /* length */
  163319. /* Make sure image isn't bigger than SOF field can handle */
  163320. if ((long) cinfo->image_height > 65535L ||
  163321. (long) cinfo->image_width > 65535L)
  163322. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) 65535);
  163323. emit_byte(cinfo, cinfo->data_precision);
  163324. emit_2bytes(cinfo, (int) cinfo->image_height);
  163325. emit_2bytes(cinfo, (int) cinfo->image_width);
  163326. emit_byte(cinfo, cinfo->num_components);
  163327. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163328. ci++, compptr++) {
  163329. emit_byte(cinfo, compptr->component_id);
  163330. emit_byte(cinfo, (compptr->h_samp_factor << 4) + compptr->v_samp_factor);
  163331. emit_byte(cinfo, compptr->quant_tbl_no);
  163332. }
  163333. }
  163334. LOCAL(void)
  163335. emit_sos (j_compress_ptr cinfo)
  163336. /* Emit a SOS marker */
  163337. {
  163338. int i, td, ta;
  163339. jpeg_component_info *compptr;
  163340. emit_marker(cinfo, M_SOS);
  163341. emit_2bytes(cinfo, 2 * cinfo->comps_in_scan + 2 + 1 + 3); /* length */
  163342. emit_byte(cinfo, cinfo->comps_in_scan);
  163343. for (i = 0; i < cinfo->comps_in_scan; i++) {
  163344. compptr = cinfo->cur_comp_info[i];
  163345. emit_byte(cinfo, compptr->component_id);
  163346. td = compptr->dc_tbl_no;
  163347. ta = compptr->ac_tbl_no;
  163348. if (cinfo->progressive_mode) {
  163349. /* Progressive mode: only DC or only AC tables are used in one scan;
  163350. * furthermore, Huffman coding of DC refinement uses no table at all.
  163351. * We emit 0 for unused field(s); this is recommended by the P&M text
  163352. * but does not seem to be specified in the standard.
  163353. */
  163354. if (cinfo->Ss == 0) {
  163355. ta = 0; /* DC scan */
  163356. if (cinfo->Ah != 0 && !cinfo->arith_code)
  163357. td = 0; /* no DC table either */
  163358. } else {
  163359. td = 0; /* AC scan */
  163360. }
  163361. }
  163362. emit_byte(cinfo, (td << 4) + ta);
  163363. }
  163364. emit_byte(cinfo, cinfo->Ss);
  163365. emit_byte(cinfo, cinfo->Se);
  163366. emit_byte(cinfo, (cinfo->Ah << 4) + cinfo->Al);
  163367. }
  163368. LOCAL(void)
  163369. emit_jfif_app0 (j_compress_ptr cinfo)
  163370. /* Emit a JFIF-compliant APP0 marker */
  163371. {
  163372. /*
  163373. * Length of APP0 block (2 bytes)
  163374. * Block ID (4 bytes - ASCII "JFIF")
  163375. * Zero byte (1 byte to terminate the ID string)
  163376. * Version Major, Minor (2 bytes - major first)
  163377. * Units (1 byte - 0x00 = none, 0x01 = inch, 0x02 = cm)
  163378. * Xdpu (2 bytes - dots per unit horizontal)
  163379. * Ydpu (2 bytes - dots per unit vertical)
  163380. * Thumbnail X size (1 byte)
  163381. * Thumbnail Y size (1 byte)
  163382. */
  163383. emit_marker(cinfo, M_APP0);
  163384. emit_2bytes(cinfo, 2 + 4 + 1 + 2 + 1 + 2 + 2 + 1 + 1); /* length */
  163385. emit_byte(cinfo, 0x4A); /* Identifier: ASCII "JFIF" */
  163386. emit_byte(cinfo, 0x46);
  163387. emit_byte(cinfo, 0x49);
  163388. emit_byte(cinfo, 0x46);
  163389. emit_byte(cinfo, 0);
  163390. emit_byte(cinfo, cinfo->JFIF_major_version); /* Version fields */
  163391. emit_byte(cinfo, cinfo->JFIF_minor_version);
  163392. emit_byte(cinfo, cinfo->density_unit); /* Pixel size information */
  163393. emit_2bytes(cinfo, (int) cinfo->X_density);
  163394. emit_2bytes(cinfo, (int) cinfo->Y_density);
  163395. emit_byte(cinfo, 0); /* No thumbnail image */
  163396. emit_byte(cinfo, 0);
  163397. }
  163398. LOCAL(void)
  163399. emit_adobe_app14 (j_compress_ptr cinfo)
  163400. /* Emit an Adobe APP14 marker */
  163401. {
  163402. /*
  163403. * Length of APP14 block (2 bytes)
  163404. * Block ID (5 bytes - ASCII "Adobe")
  163405. * Version Number (2 bytes - currently 100)
  163406. * Flags0 (2 bytes - currently 0)
  163407. * Flags1 (2 bytes - currently 0)
  163408. * Color transform (1 byte)
  163409. *
  163410. * Although Adobe TN 5116 mentions Version = 101, all the Adobe files
  163411. * now in circulation seem to use Version = 100, so that's what we write.
  163412. *
  163413. * We write the color transform byte as 1 if the JPEG color space is
  163414. * YCbCr, 2 if it's YCCK, 0 otherwise. Adobe's definition has to do with
  163415. * whether the encoder performed a transformation, which is pretty useless.
  163416. */
  163417. emit_marker(cinfo, M_APP14);
  163418. emit_2bytes(cinfo, 2 + 5 + 2 + 2 + 2 + 1); /* length */
  163419. emit_byte(cinfo, 0x41); /* Identifier: ASCII "Adobe" */
  163420. emit_byte(cinfo, 0x64);
  163421. emit_byte(cinfo, 0x6F);
  163422. emit_byte(cinfo, 0x62);
  163423. emit_byte(cinfo, 0x65);
  163424. emit_2bytes(cinfo, 100); /* Version */
  163425. emit_2bytes(cinfo, 0); /* Flags0 */
  163426. emit_2bytes(cinfo, 0); /* Flags1 */
  163427. switch (cinfo->jpeg_color_space) {
  163428. case JCS_YCbCr:
  163429. emit_byte(cinfo, 1); /* Color transform = 1 */
  163430. break;
  163431. case JCS_YCCK:
  163432. emit_byte(cinfo, 2); /* Color transform = 2 */
  163433. break;
  163434. default:
  163435. emit_byte(cinfo, 0); /* Color transform = 0 */
  163436. break;
  163437. }
  163438. }
  163439. /*
  163440. * These routines allow writing an arbitrary marker with parameters.
  163441. * The only intended use is to emit COM or APPn markers after calling
  163442. * write_file_header and before calling write_frame_header.
  163443. * Other uses are not guaranteed to produce desirable results.
  163444. * Counting the parameter bytes properly is the caller's responsibility.
  163445. */
  163446. METHODDEF(void)
  163447. write_marker_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  163448. /* Emit an arbitrary marker header */
  163449. {
  163450. if (datalen > (unsigned int) 65533) /* safety check */
  163451. ERREXIT(cinfo, JERR_BAD_LENGTH);
  163452. emit_marker(cinfo, (JPEG_MARKER) marker);
  163453. emit_2bytes(cinfo, (int) (datalen + 2)); /* total length */
  163454. }
  163455. METHODDEF(void)
  163456. write_marker_byte (j_compress_ptr cinfo, int val)
  163457. /* Emit one byte of marker parameters following write_marker_header */
  163458. {
  163459. emit_byte(cinfo, val);
  163460. }
  163461. /*
  163462. * Write datastream header.
  163463. * This consists of an SOI and optional APPn markers.
  163464. * We recommend use of the JFIF marker, but not the Adobe marker,
  163465. * when using YCbCr or grayscale data. The JFIF marker should NOT
  163466. * be used for any other JPEG colorspace. The Adobe marker is helpful
  163467. * to distinguish RGB, CMYK, and YCCK colorspaces.
  163468. * Note that an application can write additional header markers after
  163469. * jpeg_start_compress returns.
  163470. */
  163471. METHODDEF(void)
  163472. write_file_header (j_compress_ptr cinfo)
  163473. {
  163474. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  163475. emit_marker(cinfo, M_SOI); /* first the SOI */
  163476. /* SOI is defined to reset restart interval to 0 */
  163477. marker->last_restart_interval = 0;
  163478. if (cinfo->write_JFIF_header) /* next an optional JFIF APP0 */
  163479. emit_jfif_app0(cinfo);
  163480. if (cinfo->write_Adobe_marker) /* next an optional Adobe APP14 */
  163481. emit_adobe_app14(cinfo);
  163482. }
  163483. /*
  163484. * Write frame header.
  163485. * This consists of DQT and SOFn markers.
  163486. * Note that we do not emit the SOF until we have emitted the DQT(s).
  163487. * This avoids compatibility problems with incorrect implementations that
  163488. * try to error-check the quant table numbers as soon as they see the SOF.
  163489. */
  163490. METHODDEF(void)
  163491. write_frame_header (j_compress_ptr cinfo)
  163492. {
  163493. int ci, prec;
  163494. boolean is_baseline;
  163495. jpeg_component_info *compptr;
  163496. /* Emit DQT for each quantization table.
  163497. * Note that emit_dqt() suppresses any duplicate tables.
  163498. */
  163499. prec = 0;
  163500. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163501. ci++, compptr++) {
  163502. prec += emit_dqt(cinfo, compptr->quant_tbl_no);
  163503. }
  163504. /* now prec is nonzero iff there are any 16-bit quant tables. */
  163505. /* Check for a non-baseline specification.
  163506. * Note we assume that Huffman table numbers won't be changed later.
  163507. */
  163508. if (cinfo->arith_code || cinfo->progressive_mode ||
  163509. cinfo->data_precision != 8) {
  163510. is_baseline = FALSE;
  163511. } else {
  163512. is_baseline = TRUE;
  163513. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163514. ci++, compptr++) {
  163515. if (compptr->dc_tbl_no > 1 || compptr->ac_tbl_no > 1)
  163516. is_baseline = FALSE;
  163517. }
  163518. if (prec && is_baseline) {
  163519. is_baseline = FALSE;
  163520. /* If it's baseline except for quantizer size, warn the user */
  163521. TRACEMS(cinfo, 0, JTRC_16BIT_TABLES);
  163522. }
  163523. }
  163524. /* Emit the proper SOF marker */
  163525. if (cinfo->arith_code) {
  163526. emit_sof(cinfo, M_SOF9); /* SOF code for arithmetic coding */
  163527. } else {
  163528. if (cinfo->progressive_mode)
  163529. emit_sof(cinfo, M_SOF2); /* SOF code for progressive Huffman */
  163530. else if (is_baseline)
  163531. emit_sof(cinfo, M_SOF0); /* SOF code for baseline implementation */
  163532. else
  163533. emit_sof(cinfo, M_SOF1); /* SOF code for non-baseline Huffman file */
  163534. }
  163535. }
  163536. /*
  163537. * Write scan header.
  163538. * This consists of DHT or DAC markers, optional DRI, and SOS.
  163539. * Compressed data will be written following the SOS.
  163540. */
  163541. METHODDEF(void)
  163542. write_scan_header (j_compress_ptr cinfo)
  163543. {
  163544. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  163545. int i;
  163546. jpeg_component_info *compptr;
  163547. if (cinfo->arith_code) {
  163548. /* Emit arith conditioning info. We may have some duplication
  163549. * if the file has multiple scans, but it's so small it's hardly
  163550. * worth worrying about.
  163551. */
  163552. emit_dac(cinfo);
  163553. } else {
  163554. /* Emit Huffman tables.
  163555. * Note that emit_dht() suppresses any duplicate tables.
  163556. */
  163557. for (i = 0; i < cinfo->comps_in_scan; i++) {
  163558. compptr = cinfo->cur_comp_info[i];
  163559. if (cinfo->progressive_mode) {
  163560. /* Progressive mode: only DC or only AC tables are used in one scan */
  163561. if (cinfo->Ss == 0) {
  163562. if (cinfo->Ah == 0) /* DC needs no table for refinement scan */
  163563. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  163564. } else {
  163565. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  163566. }
  163567. } else {
  163568. /* Sequential mode: need both DC and AC tables */
  163569. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  163570. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  163571. }
  163572. }
  163573. }
  163574. /* Emit DRI if required --- note that DRI value could change for each scan.
  163575. * We avoid wasting space with unnecessary DRIs, however.
  163576. */
  163577. if (cinfo->restart_interval != marker->last_restart_interval) {
  163578. emit_dri(cinfo);
  163579. marker->last_restart_interval = cinfo->restart_interval;
  163580. }
  163581. emit_sos(cinfo);
  163582. }
  163583. /*
  163584. * Write datastream trailer.
  163585. */
  163586. METHODDEF(void)
  163587. write_file_trailer (j_compress_ptr cinfo)
  163588. {
  163589. emit_marker(cinfo, M_EOI);
  163590. }
  163591. /*
  163592. * Write an abbreviated table-specification datastream.
  163593. * This consists of SOI, DQT and DHT tables, and EOI.
  163594. * Any table that is defined and not marked sent_table = TRUE will be
  163595. * emitted. Note that all tables will be marked sent_table = TRUE at exit.
  163596. */
  163597. METHODDEF(void)
  163598. write_tables_only (j_compress_ptr cinfo)
  163599. {
  163600. int i;
  163601. emit_marker(cinfo, M_SOI);
  163602. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  163603. if (cinfo->quant_tbl_ptrs[i] != NULL)
  163604. (void) emit_dqt(cinfo, i);
  163605. }
  163606. if (! cinfo->arith_code) {
  163607. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  163608. if (cinfo->dc_huff_tbl_ptrs[i] != NULL)
  163609. emit_dht(cinfo, i, FALSE);
  163610. if (cinfo->ac_huff_tbl_ptrs[i] != NULL)
  163611. emit_dht(cinfo, i, TRUE);
  163612. }
  163613. }
  163614. emit_marker(cinfo, M_EOI);
  163615. }
  163616. /*
  163617. * Initialize the marker writer module.
  163618. */
  163619. GLOBAL(void)
  163620. jinit_marker_writer (j_compress_ptr cinfo)
  163621. {
  163622. my_marker_ptr marker;
  163623. /* Create the subobject */
  163624. marker = (my_marker_ptr)
  163625. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163626. SIZEOF(my_marker_writer));
  163627. cinfo->marker = (struct jpeg_marker_writer *) marker;
  163628. /* Initialize method pointers */
  163629. marker->pub.write_file_header = write_file_header;
  163630. marker->pub.write_frame_header = write_frame_header;
  163631. marker->pub.write_scan_header = write_scan_header;
  163632. marker->pub.write_file_trailer = write_file_trailer;
  163633. marker->pub.write_tables_only = write_tables_only;
  163634. marker->pub.write_marker_header = write_marker_header;
  163635. marker->pub.write_marker_byte = write_marker_byte;
  163636. /* Initialize private state */
  163637. marker->last_restart_interval = 0;
  163638. }
  163639. /*** End of inlined file: jcmarker.c ***/
  163640. /*** Start of inlined file: jcmaster.c ***/
  163641. #define JPEG_INTERNALS
  163642. /* Private state */
  163643. typedef enum {
  163644. main_pass, /* input data, also do first output step */
  163645. huff_opt_pass, /* Huffman code optimization pass */
  163646. output_pass /* data output pass */
  163647. } c_pass_type;
  163648. typedef struct {
  163649. struct jpeg_comp_master pub; /* public fields */
  163650. c_pass_type pass_type; /* the type of the current pass */
  163651. int pass_number; /* # of passes completed */
  163652. int total_passes; /* total # of passes needed */
  163653. int scan_number; /* current index in scan_info[] */
  163654. } my_comp_master;
  163655. typedef my_comp_master * my_master_ptr;
  163656. /*
  163657. * Support routines that do various essential calculations.
  163658. */
  163659. LOCAL(void)
  163660. initial_setup (j_compress_ptr cinfo)
  163661. /* Do computations that are needed before master selection phase */
  163662. {
  163663. int ci;
  163664. jpeg_component_info *compptr;
  163665. long samplesperrow;
  163666. JDIMENSION jd_samplesperrow;
  163667. /* Sanity check on image dimensions */
  163668. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  163669. || cinfo->num_components <= 0 || cinfo->input_components <= 0)
  163670. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  163671. /* Make sure image isn't bigger than I can handle */
  163672. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  163673. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  163674. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  163675. /* Width of an input scanline must be representable as JDIMENSION. */
  163676. samplesperrow = (long) cinfo->image_width * (long) cinfo->input_components;
  163677. jd_samplesperrow = (JDIMENSION) samplesperrow;
  163678. if ((long) jd_samplesperrow != samplesperrow)
  163679. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  163680. /* For now, precision must match compiled-in value... */
  163681. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  163682. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  163683. /* Check that number of components won't exceed internal array sizes */
  163684. if (cinfo->num_components > MAX_COMPONENTS)
  163685. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  163686. MAX_COMPONENTS);
  163687. /* Compute maximum sampling factors; check factor validity */
  163688. cinfo->max_h_samp_factor = 1;
  163689. cinfo->max_v_samp_factor = 1;
  163690. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163691. ci++, compptr++) {
  163692. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  163693. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  163694. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  163695. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  163696. compptr->h_samp_factor);
  163697. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  163698. compptr->v_samp_factor);
  163699. }
  163700. /* Compute dimensions of components */
  163701. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163702. ci++, compptr++) {
  163703. /* Fill in the correct component_index value; don't rely on application */
  163704. compptr->component_index = ci;
  163705. /* For compression, we never do DCT scaling. */
  163706. compptr->DCT_scaled_size = DCTSIZE;
  163707. /* Size in DCT blocks */
  163708. compptr->width_in_blocks = (JDIMENSION)
  163709. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  163710. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  163711. compptr->height_in_blocks = (JDIMENSION)
  163712. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  163713. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  163714. /* Size in samples */
  163715. compptr->downsampled_width = (JDIMENSION)
  163716. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  163717. (long) cinfo->max_h_samp_factor);
  163718. compptr->downsampled_height = (JDIMENSION)
  163719. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  163720. (long) cinfo->max_v_samp_factor);
  163721. /* Mark component needed (this flag isn't actually used for compression) */
  163722. compptr->component_needed = TRUE;
  163723. }
  163724. /* Compute number of fully interleaved MCU rows (number of times that
  163725. * main controller will call coefficient controller).
  163726. */
  163727. cinfo->total_iMCU_rows = (JDIMENSION)
  163728. jdiv_round_up((long) cinfo->image_height,
  163729. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  163730. }
  163731. #ifdef C_MULTISCAN_FILES_SUPPORTED
  163732. LOCAL(void)
  163733. validate_script (j_compress_ptr cinfo)
  163734. /* Verify that the scan script in cinfo->scan_info[] is valid; also
  163735. * determine whether it uses progressive JPEG, and set cinfo->progressive_mode.
  163736. */
  163737. {
  163738. const jpeg_scan_info * scanptr;
  163739. int scanno, ncomps, ci, coefi, thisi;
  163740. int Ss, Se, Ah, Al;
  163741. boolean component_sent[MAX_COMPONENTS];
  163742. #ifdef C_PROGRESSIVE_SUPPORTED
  163743. int * last_bitpos_ptr;
  163744. int last_bitpos[MAX_COMPONENTS][DCTSIZE2];
  163745. /* -1 until that coefficient has been seen; then last Al for it */
  163746. #endif
  163747. if (cinfo->num_scans <= 0)
  163748. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, 0);
  163749. /* For sequential JPEG, all scans must have Ss=0, Se=DCTSIZE2-1;
  163750. * for progressive JPEG, no scan can have this.
  163751. */
  163752. scanptr = cinfo->scan_info;
  163753. if (scanptr->Ss != 0 || scanptr->Se != DCTSIZE2-1) {
  163754. #ifdef C_PROGRESSIVE_SUPPORTED
  163755. cinfo->progressive_mode = TRUE;
  163756. last_bitpos_ptr = & last_bitpos[0][0];
  163757. for (ci = 0; ci < cinfo->num_components; ci++)
  163758. for (coefi = 0; coefi < DCTSIZE2; coefi++)
  163759. *last_bitpos_ptr++ = -1;
  163760. #else
  163761. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163762. #endif
  163763. } else {
  163764. cinfo->progressive_mode = FALSE;
  163765. for (ci = 0; ci < cinfo->num_components; ci++)
  163766. component_sent[ci] = FALSE;
  163767. }
  163768. for (scanno = 1; scanno <= cinfo->num_scans; scanptr++, scanno++) {
  163769. /* Validate component indexes */
  163770. ncomps = scanptr->comps_in_scan;
  163771. if (ncomps <= 0 || ncomps > MAX_COMPS_IN_SCAN)
  163772. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, ncomps, MAX_COMPS_IN_SCAN);
  163773. for (ci = 0; ci < ncomps; ci++) {
  163774. thisi = scanptr->component_index[ci];
  163775. if (thisi < 0 || thisi >= cinfo->num_components)
  163776. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  163777. /* Components must appear in SOF order within each scan */
  163778. if (ci > 0 && thisi <= scanptr->component_index[ci-1])
  163779. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  163780. }
  163781. /* Validate progression parameters */
  163782. Ss = scanptr->Ss;
  163783. Se = scanptr->Se;
  163784. Ah = scanptr->Ah;
  163785. Al = scanptr->Al;
  163786. if (cinfo->progressive_mode) {
  163787. #ifdef C_PROGRESSIVE_SUPPORTED
  163788. /* The JPEG spec simply gives the ranges 0..13 for Ah and Al, but that
  163789. * seems wrong: the upper bound ought to depend on data precision.
  163790. * Perhaps they really meant 0..N+1 for N-bit precision.
  163791. * Here we allow 0..10 for 8-bit data; Al larger than 10 results in
  163792. * out-of-range reconstructed DC values during the first DC scan,
  163793. * which might cause problems for some decoders.
  163794. */
  163795. #if BITS_IN_JSAMPLE == 8
  163796. #define MAX_AH_AL 10
  163797. #else
  163798. #define MAX_AH_AL 13
  163799. #endif
  163800. if (Ss < 0 || Ss >= DCTSIZE2 || Se < Ss || Se >= DCTSIZE2 ||
  163801. Ah < 0 || Ah > MAX_AH_AL || Al < 0 || Al > MAX_AH_AL)
  163802. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  163803. if (Ss == 0) {
  163804. if (Se != 0) /* DC and AC together not OK */
  163805. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  163806. } else {
  163807. if (ncomps != 1) /* AC scans must be for only one component */
  163808. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  163809. }
  163810. for (ci = 0; ci < ncomps; ci++) {
  163811. last_bitpos_ptr = & last_bitpos[scanptr->component_index[ci]][0];
  163812. if (Ss != 0 && last_bitpos_ptr[0] < 0) /* AC without prior DC scan */
  163813. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  163814. for (coefi = Ss; coefi <= Se; coefi++) {
  163815. if (last_bitpos_ptr[coefi] < 0) {
  163816. /* first scan of this coefficient */
  163817. if (Ah != 0)
  163818. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  163819. } else {
  163820. /* not first scan */
  163821. if (Ah != last_bitpos_ptr[coefi] || Al != Ah-1)
  163822. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  163823. }
  163824. last_bitpos_ptr[coefi] = Al;
  163825. }
  163826. }
  163827. #endif
  163828. } else {
  163829. /* For sequential JPEG, all progression parameters must be these: */
  163830. if (Ss != 0 || Se != DCTSIZE2-1 || Ah != 0 || Al != 0)
  163831. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  163832. /* Make sure components are not sent twice */
  163833. for (ci = 0; ci < ncomps; ci++) {
  163834. thisi = scanptr->component_index[ci];
  163835. if (component_sent[thisi])
  163836. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  163837. component_sent[thisi] = TRUE;
  163838. }
  163839. }
  163840. }
  163841. /* Now verify that everything got sent. */
  163842. if (cinfo->progressive_mode) {
  163843. #ifdef C_PROGRESSIVE_SUPPORTED
  163844. /* For progressive mode, we only check that at least some DC data
  163845. * got sent for each component; the spec does not require that all bits
  163846. * of all coefficients be transmitted. Would it be wiser to enforce
  163847. * transmission of all coefficient bits??
  163848. */
  163849. for (ci = 0; ci < cinfo->num_components; ci++) {
  163850. if (last_bitpos[ci][0] < 0)
  163851. ERREXIT(cinfo, JERR_MISSING_DATA);
  163852. }
  163853. #endif
  163854. } else {
  163855. for (ci = 0; ci < cinfo->num_components; ci++) {
  163856. if (! component_sent[ci])
  163857. ERREXIT(cinfo, JERR_MISSING_DATA);
  163858. }
  163859. }
  163860. }
  163861. #endif /* C_MULTISCAN_FILES_SUPPORTED */
  163862. LOCAL(void)
  163863. select_scan_parameters (j_compress_ptr cinfo)
  163864. /* Set up the scan parameters for the current scan */
  163865. {
  163866. int ci;
  163867. #ifdef C_MULTISCAN_FILES_SUPPORTED
  163868. if (cinfo->scan_info != NULL) {
  163869. /* Prepare for current scan --- the script is already validated */
  163870. my_master_ptr master = (my_master_ptr) cinfo->master;
  163871. const jpeg_scan_info * scanptr = cinfo->scan_info + master->scan_number;
  163872. cinfo->comps_in_scan = scanptr->comps_in_scan;
  163873. for (ci = 0; ci < scanptr->comps_in_scan; ci++) {
  163874. cinfo->cur_comp_info[ci] =
  163875. &cinfo->comp_info[scanptr->component_index[ci]];
  163876. }
  163877. cinfo->Ss = scanptr->Ss;
  163878. cinfo->Se = scanptr->Se;
  163879. cinfo->Ah = scanptr->Ah;
  163880. cinfo->Al = scanptr->Al;
  163881. }
  163882. else
  163883. #endif
  163884. {
  163885. /* Prepare for single sequential-JPEG scan containing all components */
  163886. if (cinfo->num_components > MAX_COMPS_IN_SCAN)
  163887. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  163888. MAX_COMPS_IN_SCAN);
  163889. cinfo->comps_in_scan = cinfo->num_components;
  163890. for (ci = 0; ci < cinfo->num_components; ci++) {
  163891. cinfo->cur_comp_info[ci] = &cinfo->comp_info[ci];
  163892. }
  163893. cinfo->Ss = 0;
  163894. cinfo->Se = DCTSIZE2-1;
  163895. cinfo->Ah = 0;
  163896. cinfo->Al = 0;
  163897. }
  163898. }
  163899. LOCAL(void)
  163900. per_scan_setup (j_compress_ptr cinfo)
  163901. /* Do computations that are needed before processing a JPEG scan */
  163902. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] are already set */
  163903. {
  163904. int ci, mcublks, tmp;
  163905. jpeg_component_info *compptr;
  163906. if (cinfo->comps_in_scan == 1) {
  163907. /* Noninterleaved (single-component) scan */
  163908. compptr = cinfo->cur_comp_info[0];
  163909. /* Overall image size in MCUs */
  163910. cinfo->MCUs_per_row = compptr->width_in_blocks;
  163911. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  163912. /* For noninterleaved scan, always one block per MCU */
  163913. compptr->MCU_width = 1;
  163914. compptr->MCU_height = 1;
  163915. compptr->MCU_blocks = 1;
  163916. compptr->MCU_sample_width = DCTSIZE;
  163917. compptr->last_col_width = 1;
  163918. /* For noninterleaved scans, it is convenient to define last_row_height
  163919. * as the number of block rows present in the last iMCU row.
  163920. */
  163921. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  163922. if (tmp == 0) tmp = compptr->v_samp_factor;
  163923. compptr->last_row_height = tmp;
  163924. /* Prepare array describing MCU composition */
  163925. cinfo->blocks_in_MCU = 1;
  163926. cinfo->MCU_membership[0] = 0;
  163927. } else {
  163928. /* Interleaved (multi-component) scan */
  163929. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  163930. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  163931. MAX_COMPS_IN_SCAN);
  163932. /* Overall image size in MCUs */
  163933. cinfo->MCUs_per_row = (JDIMENSION)
  163934. jdiv_round_up((long) cinfo->image_width,
  163935. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  163936. cinfo->MCU_rows_in_scan = (JDIMENSION)
  163937. jdiv_round_up((long) cinfo->image_height,
  163938. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  163939. cinfo->blocks_in_MCU = 0;
  163940. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  163941. compptr = cinfo->cur_comp_info[ci];
  163942. /* Sampling factors give # of blocks of component in each MCU */
  163943. compptr->MCU_width = compptr->h_samp_factor;
  163944. compptr->MCU_height = compptr->v_samp_factor;
  163945. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  163946. compptr->MCU_sample_width = compptr->MCU_width * DCTSIZE;
  163947. /* Figure number of non-dummy blocks in last MCU column & row */
  163948. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  163949. if (tmp == 0) tmp = compptr->MCU_width;
  163950. compptr->last_col_width = tmp;
  163951. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  163952. if (tmp == 0) tmp = compptr->MCU_height;
  163953. compptr->last_row_height = tmp;
  163954. /* Prepare array describing MCU composition */
  163955. mcublks = compptr->MCU_blocks;
  163956. if (cinfo->blocks_in_MCU + mcublks > C_MAX_BLOCKS_IN_MCU)
  163957. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  163958. while (mcublks-- > 0) {
  163959. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  163960. }
  163961. }
  163962. }
  163963. /* Convert restart specified in rows to actual MCU count. */
  163964. /* Note that count must fit in 16 bits, so we provide limiting. */
  163965. if (cinfo->restart_in_rows > 0) {
  163966. long nominal = (long) cinfo->restart_in_rows * (long) cinfo->MCUs_per_row;
  163967. cinfo->restart_interval = (unsigned int) MIN(nominal, 65535L);
  163968. }
  163969. }
  163970. /*
  163971. * Per-pass setup.
  163972. * This is called at the beginning of each pass. We determine which modules
  163973. * will be active during this pass and give them appropriate start_pass calls.
  163974. * We also set is_last_pass to indicate whether any more passes will be
  163975. * required.
  163976. */
  163977. METHODDEF(void)
  163978. prepare_for_pass (j_compress_ptr cinfo)
  163979. {
  163980. my_master_ptr master = (my_master_ptr) cinfo->master;
  163981. switch (master->pass_type) {
  163982. case main_pass:
  163983. /* Initial pass: will collect input data, and do either Huffman
  163984. * optimization or data output for the first scan.
  163985. */
  163986. select_scan_parameters(cinfo);
  163987. per_scan_setup(cinfo);
  163988. if (! cinfo->raw_data_in) {
  163989. (*cinfo->cconvert->start_pass) (cinfo);
  163990. (*cinfo->downsample->start_pass) (cinfo);
  163991. (*cinfo->prep->start_pass) (cinfo, JBUF_PASS_THRU);
  163992. }
  163993. (*cinfo->fdct->start_pass) (cinfo);
  163994. (*cinfo->entropy->start_pass) (cinfo, cinfo->optimize_coding);
  163995. (*cinfo->coef->start_pass) (cinfo,
  163996. (master->total_passes > 1 ?
  163997. JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  163998. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  163999. if (cinfo->optimize_coding) {
  164000. /* No immediate data output; postpone writing frame/scan headers */
  164001. master->pub.call_pass_startup = FALSE;
  164002. } else {
  164003. /* Will write frame/scan headers at first jpeg_write_scanlines call */
  164004. master->pub.call_pass_startup = TRUE;
  164005. }
  164006. break;
  164007. #ifdef ENTROPY_OPT_SUPPORTED
  164008. case huff_opt_pass:
  164009. /* Do Huffman optimization for a scan after the first one. */
  164010. select_scan_parameters(cinfo);
  164011. per_scan_setup(cinfo);
  164012. if (cinfo->Ss != 0 || cinfo->Ah == 0 || cinfo->arith_code) {
  164013. (*cinfo->entropy->start_pass) (cinfo, TRUE);
  164014. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  164015. master->pub.call_pass_startup = FALSE;
  164016. break;
  164017. }
  164018. /* Special case: Huffman DC refinement scans need no Huffman table
  164019. * and therefore we can skip the optimization pass for them.
  164020. */
  164021. master->pass_type = output_pass;
  164022. master->pass_number++;
  164023. /*FALLTHROUGH*/
  164024. #endif
  164025. case output_pass:
  164026. /* Do a data-output pass. */
  164027. /* We need not repeat per-scan setup if prior optimization pass did it. */
  164028. if (! cinfo->optimize_coding) {
  164029. select_scan_parameters(cinfo);
  164030. per_scan_setup(cinfo);
  164031. }
  164032. (*cinfo->entropy->start_pass) (cinfo, FALSE);
  164033. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  164034. /* We emit frame/scan headers now */
  164035. if (master->scan_number == 0)
  164036. (*cinfo->marker->write_frame_header) (cinfo);
  164037. (*cinfo->marker->write_scan_header) (cinfo);
  164038. master->pub.call_pass_startup = FALSE;
  164039. break;
  164040. default:
  164041. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164042. }
  164043. master->pub.is_last_pass = (master->pass_number == master->total_passes-1);
  164044. /* Set up progress monitor's pass info if present */
  164045. if (cinfo->progress != NULL) {
  164046. cinfo->progress->completed_passes = master->pass_number;
  164047. cinfo->progress->total_passes = master->total_passes;
  164048. }
  164049. }
  164050. /*
  164051. * Special start-of-pass hook.
  164052. * This is called by jpeg_write_scanlines if call_pass_startup is TRUE.
  164053. * In single-pass processing, we need this hook because we don't want to
  164054. * write frame/scan headers during jpeg_start_compress; we want to let the
  164055. * application write COM markers etc. between jpeg_start_compress and the
  164056. * jpeg_write_scanlines loop.
  164057. * In multi-pass processing, this routine is not used.
  164058. */
  164059. METHODDEF(void)
  164060. pass_startup (j_compress_ptr cinfo)
  164061. {
  164062. cinfo->master->call_pass_startup = FALSE; /* reset flag so call only once */
  164063. (*cinfo->marker->write_frame_header) (cinfo);
  164064. (*cinfo->marker->write_scan_header) (cinfo);
  164065. }
  164066. /*
  164067. * Finish up at end of pass.
  164068. */
  164069. METHODDEF(void)
  164070. finish_pass_master (j_compress_ptr cinfo)
  164071. {
  164072. my_master_ptr master = (my_master_ptr) cinfo->master;
  164073. /* The entropy coder always needs an end-of-pass call,
  164074. * either to analyze statistics or to flush its output buffer.
  164075. */
  164076. (*cinfo->entropy->finish_pass) (cinfo);
  164077. /* Update state for next pass */
  164078. switch (master->pass_type) {
  164079. case main_pass:
  164080. /* next pass is either output of scan 0 (after optimization)
  164081. * or output of scan 1 (if no optimization).
  164082. */
  164083. master->pass_type = output_pass;
  164084. if (! cinfo->optimize_coding)
  164085. master->scan_number++;
  164086. break;
  164087. case huff_opt_pass:
  164088. /* next pass is always output of current scan */
  164089. master->pass_type = output_pass;
  164090. break;
  164091. case output_pass:
  164092. /* next pass is either optimization or output of next scan */
  164093. if (cinfo->optimize_coding)
  164094. master->pass_type = huff_opt_pass;
  164095. master->scan_number++;
  164096. break;
  164097. }
  164098. master->pass_number++;
  164099. }
  164100. /*
  164101. * Initialize master compression control.
  164102. */
  164103. GLOBAL(void)
  164104. jinit_c_master_control (j_compress_ptr cinfo, boolean transcode_only)
  164105. {
  164106. my_master_ptr master;
  164107. master = (my_master_ptr)
  164108. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164109. SIZEOF(my_comp_master));
  164110. cinfo->master = (struct jpeg_comp_master *) master;
  164111. master->pub.prepare_for_pass = prepare_for_pass;
  164112. master->pub.pass_startup = pass_startup;
  164113. master->pub.finish_pass = finish_pass_master;
  164114. master->pub.is_last_pass = FALSE;
  164115. /* Validate parameters, determine derived values */
  164116. initial_setup(cinfo);
  164117. if (cinfo->scan_info != NULL) {
  164118. #ifdef C_MULTISCAN_FILES_SUPPORTED
  164119. validate_script(cinfo);
  164120. #else
  164121. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164122. #endif
  164123. } else {
  164124. cinfo->progressive_mode = FALSE;
  164125. cinfo->num_scans = 1;
  164126. }
  164127. if (cinfo->progressive_mode) /* TEMPORARY HACK ??? */
  164128. cinfo->optimize_coding = TRUE; /* assume default tables no good for progressive mode */
  164129. /* Initialize my private state */
  164130. if (transcode_only) {
  164131. /* no main pass in transcoding */
  164132. if (cinfo->optimize_coding)
  164133. master->pass_type = huff_opt_pass;
  164134. else
  164135. master->pass_type = output_pass;
  164136. } else {
  164137. /* for normal compression, first pass is always this type: */
  164138. master->pass_type = main_pass;
  164139. }
  164140. master->scan_number = 0;
  164141. master->pass_number = 0;
  164142. if (cinfo->optimize_coding)
  164143. master->total_passes = cinfo->num_scans * 2;
  164144. else
  164145. master->total_passes = cinfo->num_scans;
  164146. }
  164147. /*** End of inlined file: jcmaster.c ***/
  164148. /*** Start of inlined file: jcomapi.c ***/
  164149. #define JPEG_INTERNALS
  164150. /*
  164151. * Abort processing of a JPEG compression or decompression operation,
  164152. * but don't destroy the object itself.
  164153. *
  164154. * For this, we merely clean up all the nonpermanent memory pools.
  164155. * Note that temp files (virtual arrays) are not allowed to belong to
  164156. * the permanent pool, so we will be able to close all temp files here.
  164157. * Closing a data source or destination, if necessary, is the application's
  164158. * responsibility.
  164159. */
  164160. GLOBAL(void)
  164161. jpeg_abort (j_common_ptr cinfo)
  164162. {
  164163. int pool;
  164164. /* Do nothing if called on a not-initialized or destroyed JPEG object. */
  164165. if (cinfo->mem == NULL)
  164166. return;
  164167. /* Releasing pools in reverse order might help avoid fragmentation
  164168. * with some (brain-damaged) malloc libraries.
  164169. */
  164170. for (pool = JPOOL_NUMPOOLS-1; pool > JPOOL_PERMANENT; pool--) {
  164171. (*cinfo->mem->free_pool) (cinfo, pool);
  164172. }
  164173. /* Reset overall state for possible reuse of object */
  164174. if (cinfo->is_decompressor) {
  164175. cinfo->global_state = DSTATE_START;
  164176. /* Try to keep application from accessing now-deleted marker list.
  164177. * A bit kludgy to do it here, but this is the most central place.
  164178. */
  164179. ((j_decompress_ptr) cinfo)->marker_list = NULL;
  164180. } else {
  164181. cinfo->global_state = CSTATE_START;
  164182. }
  164183. }
  164184. /*
  164185. * Destruction of a JPEG object.
  164186. *
  164187. * Everything gets deallocated except the master jpeg_compress_struct itself
  164188. * and the error manager struct. Both of these are supplied by the application
  164189. * and must be freed, if necessary, by the application. (Often they are on
  164190. * the stack and so don't need to be freed anyway.)
  164191. * Closing a data source or destination, if necessary, is the application's
  164192. * responsibility.
  164193. */
  164194. GLOBAL(void)
  164195. jpeg_destroy (j_common_ptr cinfo)
  164196. {
  164197. /* We need only tell the memory manager to release everything. */
  164198. /* NB: mem pointer is NULL if memory mgr failed to initialize. */
  164199. if (cinfo->mem != NULL)
  164200. (*cinfo->mem->self_destruct) (cinfo);
  164201. cinfo->mem = NULL; /* be safe if jpeg_destroy is called twice */
  164202. cinfo->global_state = 0; /* mark it destroyed */
  164203. }
  164204. /*
  164205. * Convenience routines for allocating quantization and Huffman tables.
  164206. * (Would jutils.c be a more reasonable place to put these?)
  164207. */
  164208. GLOBAL(JQUANT_TBL *)
  164209. jpeg_alloc_quant_table (j_common_ptr cinfo)
  164210. {
  164211. JQUANT_TBL *tbl;
  164212. tbl = (JQUANT_TBL *)
  164213. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JQUANT_TBL));
  164214. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  164215. return tbl;
  164216. }
  164217. GLOBAL(JHUFF_TBL *)
  164218. jpeg_alloc_huff_table (j_common_ptr cinfo)
  164219. {
  164220. JHUFF_TBL *tbl;
  164221. tbl = (JHUFF_TBL *)
  164222. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JHUFF_TBL));
  164223. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  164224. return tbl;
  164225. }
  164226. /*** End of inlined file: jcomapi.c ***/
  164227. /*** Start of inlined file: jcparam.c ***/
  164228. #define JPEG_INTERNALS
  164229. /*
  164230. * Quantization table setup routines
  164231. */
  164232. GLOBAL(void)
  164233. jpeg_add_quant_table (j_compress_ptr cinfo, int which_tbl,
  164234. const unsigned int *basic_table,
  164235. int scale_factor, boolean force_baseline)
  164236. /* Define a quantization table equal to the basic_table times
  164237. * a scale factor (given as a percentage).
  164238. * If force_baseline is TRUE, the computed quantization table entries
  164239. * are limited to 1..255 for JPEG baseline compatibility.
  164240. */
  164241. {
  164242. JQUANT_TBL ** qtblptr;
  164243. int i;
  164244. long temp;
  164245. /* Safety check to ensure start_compress not called yet. */
  164246. if (cinfo->global_state != CSTATE_START)
  164247. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  164248. if (which_tbl < 0 || which_tbl >= NUM_QUANT_TBLS)
  164249. ERREXIT1(cinfo, JERR_DQT_INDEX, which_tbl);
  164250. qtblptr = & cinfo->quant_tbl_ptrs[which_tbl];
  164251. if (*qtblptr == NULL)
  164252. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  164253. for (i = 0; i < DCTSIZE2; i++) {
  164254. temp = ((long) basic_table[i] * scale_factor + 50L) / 100L;
  164255. /* limit the values to the valid range */
  164256. if (temp <= 0L) temp = 1L;
  164257. if (temp > 32767L) temp = 32767L; /* max quantizer needed for 12 bits */
  164258. if (force_baseline && temp > 255L)
  164259. temp = 255L; /* limit to baseline range if requested */
  164260. (*qtblptr)->quantval[i] = (UINT16) temp;
  164261. }
  164262. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  164263. (*qtblptr)->sent_table = FALSE;
  164264. }
  164265. GLOBAL(void)
  164266. jpeg_set_linear_quality (j_compress_ptr cinfo, int scale_factor,
  164267. boolean force_baseline)
  164268. /* Set or change the 'quality' (quantization) setting, using default tables
  164269. * and a straight percentage-scaling quality scale. In most cases it's better
  164270. * to use jpeg_set_quality (below); this entry point is provided for
  164271. * applications that insist on a linear percentage scaling.
  164272. */
  164273. {
  164274. /* These are the sample quantization tables given in JPEG spec section K.1.
  164275. * The spec says that the values given produce "good" quality, and
  164276. * when divided by 2, "very good" quality.
  164277. */
  164278. static const unsigned int std_luminance_quant_tbl[DCTSIZE2] = {
  164279. 16, 11, 10, 16, 24, 40, 51, 61,
  164280. 12, 12, 14, 19, 26, 58, 60, 55,
  164281. 14, 13, 16, 24, 40, 57, 69, 56,
  164282. 14, 17, 22, 29, 51, 87, 80, 62,
  164283. 18, 22, 37, 56, 68, 109, 103, 77,
  164284. 24, 35, 55, 64, 81, 104, 113, 92,
  164285. 49, 64, 78, 87, 103, 121, 120, 101,
  164286. 72, 92, 95, 98, 112, 100, 103, 99
  164287. };
  164288. static const unsigned int std_chrominance_quant_tbl[DCTSIZE2] = {
  164289. 17, 18, 24, 47, 99, 99, 99, 99,
  164290. 18, 21, 26, 66, 99, 99, 99, 99,
  164291. 24, 26, 56, 99, 99, 99, 99, 99,
  164292. 47, 66, 99, 99, 99, 99, 99, 99,
  164293. 99, 99, 99, 99, 99, 99, 99, 99,
  164294. 99, 99, 99, 99, 99, 99, 99, 99,
  164295. 99, 99, 99, 99, 99, 99, 99, 99,
  164296. 99, 99, 99, 99, 99, 99, 99, 99
  164297. };
  164298. /* Set up two quantization tables using the specified scaling */
  164299. jpeg_add_quant_table(cinfo, 0, std_luminance_quant_tbl,
  164300. scale_factor, force_baseline);
  164301. jpeg_add_quant_table(cinfo, 1, std_chrominance_quant_tbl,
  164302. scale_factor, force_baseline);
  164303. }
  164304. GLOBAL(int)
  164305. jpeg_quality_scaling (int quality)
  164306. /* Convert a user-specified quality rating to a percentage scaling factor
  164307. * for an underlying quantization table, using our recommended scaling curve.
  164308. * The input 'quality' factor should be 0 (terrible) to 100 (very good).
  164309. */
  164310. {
  164311. /* Safety limit on quality factor. Convert 0 to 1 to avoid zero divide. */
  164312. if (quality <= 0) quality = 1;
  164313. if (quality > 100) quality = 100;
  164314. /* The basic table is used as-is (scaling 100) for a quality of 50.
  164315. * Qualities 50..100 are converted to scaling percentage 200 - 2*Q;
  164316. * note that at Q=100 the scaling is 0, which will cause jpeg_add_quant_table
  164317. * to make all the table entries 1 (hence, minimum quantization loss).
  164318. * Qualities 1..50 are converted to scaling percentage 5000/Q.
  164319. */
  164320. if (quality < 50)
  164321. quality = 5000 / quality;
  164322. else
  164323. quality = 200 - quality*2;
  164324. return quality;
  164325. }
  164326. GLOBAL(void)
  164327. jpeg_set_quality (j_compress_ptr cinfo, int quality, boolean force_baseline)
  164328. /* Set or change the 'quality' (quantization) setting, using default tables.
  164329. * This is the standard quality-adjusting entry point for typical user
  164330. * interfaces; only those who want detailed control over quantization tables
  164331. * would use the preceding three routines directly.
  164332. */
  164333. {
  164334. /* Convert user 0-100 rating to percentage scaling */
  164335. quality = jpeg_quality_scaling(quality);
  164336. /* Set up standard quality tables */
  164337. jpeg_set_linear_quality(cinfo, quality, force_baseline);
  164338. }
  164339. /*
  164340. * Huffman table setup routines
  164341. */
  164342. LOCAL(void)
  164343. add_huff_table (j_compress_ptr cinfo,
  164344. JHUFF_TBL **htblptr, const UINT8 *bits, const UINT8 *val)
  164345. /* Define a Huffman table */
  164346. {
  164347. int nsymbols, len;
  164348. if (*htblptr == NULL)
  164349. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  164350. /* Copy the number-of-symbols-of-each-code-length counts */
  164351. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  164352. /* Validate the counts. We do this here mainly so we can copy the right
  164353. * number of symbols from the val[] array, without risking marching off
  164354. * the end of memory. jchuff.c will do a more thorough test later.
  164355. */
  164356. nsymbols = 0;
  164357. for (len = 1; len <= 16; len++)
  164358. nsymbols += bits[len];
  164359. if (nsymbols < 1 || nsymbols > 256)
  164360. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  164361. MEMCOPY((*htblptr)->huffval, val, nsymbols * SIZEOF(UINT8));
  164362. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  164363. (*htblptr)->sent_table = FALSE;
  164364. }
  164365. LOCAL(void)
  164366. std_huff_tables (j_compress_ptr cinfo)
  164367. /* Set up the standard Huffman tables (cf. JPEG standard section K.3) */
  164368. /* IMPORTANT: these are only valid for 8-bit data precision! */
  164369. {
  164370. static const UINT8 bits_dc_luminance[17] =
  164371. { /* 0-base */ 0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 };
  164372. static const UINT8 val_dc_luminance[] =
  164373. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  164374. static const UINT8 bits_dc_chrominance[17] =
  164375. { /* 0-base */ 0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 };
  164376. static const UINT8 val_dc_chrominance[] =
  164377. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  164378. static const UINT8 bits_ac_luminance[17] =
  164379. { /* 0-base */ 0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d };
  164380. static const UINT8 val_ac_luminance[] =
  164381. { 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,
  164382. 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
  164383. 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08,
  164384. 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
  164385. 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16,
  164386. 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
  164387. 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
  164388. 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
  164389. 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
  164390. 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
  164391. 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
  164392. 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
  164393. 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
  164394. 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
  164395. 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
  164396. 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5,
  164397. 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4,
  164398. 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,
  164399. 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea,
  164400. 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  164401. 0xf9, 0xfa };
  164402. static const UINT8 bits_ac_chrominance[17] =
  164403. { /* 0-base */ 0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77 };
  164404. static const UINT8 val_ac_chrominance[] =
  164405. { 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21,
  164406. 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
  164407. 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91,
  164408. 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
  164409. 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34,
  164410. 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
  164411. 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38,
  164412. 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
  164413. 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
  164414. 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
  164415. 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
  164416. 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
  164417. 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96,
  164418. 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5,
  164419. 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4,
  164420. 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3,
  164421. 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2,
  164422. 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
  164423. 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9,
  164424. 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  164425. 0xf9, 0xfa };
  164426. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[0],
  164427. bits_dc_luminance, val_dc_luminance);
  164428. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[0],
  164429. bits_ac_luminance, val_ac_luminance);
  164430. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[1],
  164431. bits_dc_chrominance, val_dc_chrominance);
  164432. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[1],
  164433. bits_ac_chrominance, val_ac_chrominance);
  164434. }
  164435. /*
  164436. * Default parameter setup for compression.
  164437. *
  164438. * Applications that don't choose to use this routine must do their
  164439. * own setup of all these parameters. Alternately, you can call this
  164440. * to establish defaults and then alter parameters selectively. This
  164441. * is the recommended approach since, if we add any new parameters,
  164442. * your code will still work (they'll be set to reasonable defaults).
  164443. */
  164444. GLOBAL(void)
  164445. jpeg_set_defaults (j_compress_ptr cinfo)
  164446. {
  164447. int i;
  164448. /* Safety check to ensure start_compress not called yet. */
  164449. if (cinfo->global_state != CSTATE_START)
  164450. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  164451. /* Allocate comp_info array large enough for maximum component count.
  164452. * Array is made permanent in case application wants to compress
  164453. * multiple images at same param settings.
  164454. */
  164455. if (cinfo->comp_info == NULL)
  164456. cinfo->comp_info = (jpeg_component_info *)
  164457. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  164458. MAX_COMPONENTS * SIZEOF(jpeg_component_info));
  164459. /* Initialize everything not dependent on the color space */
  164460. cinfo->data_precision = BITS_IN_JSAMPLE;
  164461. /* Set up two quantization tables using default quality of 75 */
  164462. jpeg_set_quality(cinfo, 75, TRUE);
  164463. /* Set up two Huffman tables */
  164464. std_huff_tables(cinfo);
  164465. /* Initialize default arithmetic coding conditioning */
  164466. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  164467. cinfo->arith_dc_L[i] = 0;
  164468. cinfo->arith_dc_U[i] = 1;
  164469. cinfo->arith_ac_K[i] = 5;
  164470. }
  164471. /* Default is no multiple-scan output */
  164472. cinfo->scan_info = NULL;
  164473. cinfo->num_scans = 0;
  164474. /* Expect normal source image, not raw downsampled data */
  164475. cinfo->raw_data_in = FALSE;
  164476. /* Use Huffman coding, not arithmetic coding, by default */
  164477. cinfo->arith_code = FALSE;
  164478. /* By default, don't do extra passes to optimize entropy coding */
  164479. cinfo->optimize_coding = FALSE;
  164480. /* The standard Huffman tables are only valid for 8-bit data precision.
  164481. * If the precision is higher, force optimization on so that usable
  164482. * tables will be computed. This test can be removed if default tables
  164483. * are supplied that are valid for the desired precision.
  164484. */
  164485. if (cinfo->data_precision > 8)
  164486. cinfo->optimize_coding = TRUE;
  164487. /* By default, use the simpler non-cosited sampling alignment */
  164488. cinfo->CCIR601_sampling = FALSE;
  164489. /* No input smoothing */
  164490. cinfo->smoothing_factor = 0;
  164491. /* DCT algorithm preference */
  164492. cinfo->dct_method = JDCT_DEFAULT;
  164493. /* No restart markers */
  164494. cinfo->restart_interval = 0;
  164495. cinfo->restart_in_rows = 0;
  164496. /* Fill in default JFIF marker parameters. Note that whether the marker
  164497. * will actually be written is determined by jpeg_set_colorspace.
  164498. *
  164499. * By default, the library emits JFIF version code 1.01.
  164500. * An application that wants to emit JFIF 1.02 extension markers should set
  164501. * JFIF_minor_version to 2. We could probably get away with just defaulting
  164502. * to 1.02, but there may still be some decoders in use that will complain
  164503. * about that; saying 1.01 should minimize compatibility problems.
  164504. */
  164505. cinfo->JFIF_major_version = 1; /* Default JFIF version = 1.01 */
  164506. cinfo->JFIF_minor_version = 1;
  164507. cinfo->density_unit = 0; /* Pixel size is unknown by default */
  164508. cinfo->X_density = 1; /* Pixel aspect ratio is square by default */
  164509. cinfo->Y_density = 1;
  164510. /* Choose JPEG colorspace based on input space, set defaults accordingly */
  164511. jpeg_default_colorspace(cinfo);
  164512. }
  164513. /*
  164514. * Select an appropriate JPEG colorspace for in_color_space.
  164515. */
  164516. GLOBAL(void)
  164517. jpeg_default_colorspace (j_compress_ptr cinfo)
  164518. {
  164519. switch (cinfo->in_color_space) {
  164520. case JCS_GRAYSCALE:
  164521. jpeg_set_colorspace(cinfo, JCS_GRAYSCALE);
  164522. break;
  164523. case JCS_RGB:
  164524. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  164525. break;
  164526. case JCS_YCbCr:
  164527. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  164528. break;
  164529. case JCS_CMYK:
  164530. jpeg_set_colorspace(cinfo, JCS_CMYK); /* By default, no translation */
  164531. break;
  164532. case JCS_YCCK:
  164533. jpeg_set_colorspace(cinfo, JCS_YCCK);
  164534. break;
  164535. case JCS_UNKNOWN:
  164536. jpeg_set_colorspace(cinfo, JCS_UNKNOWN);
  164537. break;
  164538. default:
  164539. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  164540. }
  164541. }
  164542. /*
  164543. * Set the JPEG colorspace, and choose colorspace-dependent default values.
  164544. */
  164545. GLOBAL(void)
  164546. jpeg_set_colorspace (j_compress_ptr cinfo, J_COLOR_SPACE colorspace)
  164547. {
  164548. jpeg_component_info * compptr;
  164549. int ci;
  164550. #define SET_COMP(index,id,hsamp,vsamp,quant,dctbl,actbl) \
  164551. (compptr = &cinfo->comp_info[index], \
  164552. compptr->component_id = (id), \
  164553. compptr->h_samp_factor = (hsamp), \
  164554. compptr->v_samp_factor = (vsamp), \
  164555. compptr->quant_tbl_no = (quant), \
  164556. compptr->dc_tbl_no = (dctbl), \
  164557. compptr->ac_tbl_no = (actbl) )
  164558. /* Safety check to ensure start_compress not called yet. */
  164559. if (cinfo->global_state != CSTATE_START)
  164560. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  164561. /* For all colorspaces, we use Q and Huff tables 0 for luminance components,
  164562. * tables 1 for chrominance components.
  164563. */
  164564. cinfo->jpeg_color_space = colorspace;
  164565. cinfo->write_JFIF_header = FALSE; /* No marker for non-JFIF colorspaces */
  164566. cinfo->write_Adobe_marker = FALSE; /* write no Adobe marker by default */
  164567. switch (colorspace) {
  164568. case JCS_GRAYSCALE:
  164569. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  164570. cinfo->num_components = 1;
  164571. /* JFIF specifies component ID 1 */
  164572. SET_COMP(0, 1, 1,1, 0, 0,0);
  164573. break;
  164574. case JCS_RGB:
  164575. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag RGB */
  164576. cinfo->num_components = 3;
  164577. SET_COMP(0, 0x52 /* 'R' */, 1,1, 0, 0,0);
  164578. SET_COMP(1, 0x47 /* 'G' */, 1,1, 0, 0,0);
  164579. SET_COMP(2, 0x42 /* 'B' */, 1,1, 0, 0,0);
  164580. break;
  164581. case JCS_YCbCr:
  164582. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  164583. cinfo->num_components = 3;
  164584. /* JFIF specifies component IDs 1,2,3 */
  164585. /* We default to 2x2 subsamples of chrominance */
  164586. SET_COMP(0, 1, 2,2, 0, 0,0);
  164587. SET_COMP(1, 2, 1,1, 1, 1,1);
  164588. SET_COMP(2, 3, 1,1, 1, 1,1);
  164589. break;
  164590. case JCS_CMYK:
  164591. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag CMYK */
  164592. cinfo->num_components = 4;
  164593. SET_COMP(0, 0x43 /* 'C' */, 1,1, 0, 0,0);
  164594. SET_COMP(1, 0x4D /* 'M' */, 1,1, 0, 0,0);
  164595. SET_COMP(2, 0x59 /* 'Y' */, 1,1, 0, 0,0);
  164596. SET_COMP(3, 0x4B /* 'K' */, 1,1, 0, 0,0);
  164597. break;
  164598. case JCS_YCCK:
  164599. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag YCCK */
  164600. cinfo->num_components = 4;
  164601. SET_COMP(0, 1, 2,2, 0, 0,0);
  164602. SET_COMP(1, 2, 1,1, 1, 1,1);
  164603. SET_COMP(2, 3, 1,1, 1, 1,1);
  164604. SET_COMP(3, 4, 2,2, 0, 0,0);
  164605. break;
  164606. case JCS_UNKNOWN:
  164607. cinfo->num_components = cinfo->input_components;
  164608. if (cinfo->num_components < 1 || cinfo->num_components > MAX_COMPONENTS)
  164609. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  164610. MAX_COMPONENTS);
  164611. for (ci = 0; ci < cinfo->num_components; ci++) {
  164612. SET_COMP(ci, ci, 1,1, 0, 0,0);
  164613. }
  164614. break;
  164615. default:
  164616. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  164617. }
  164618. }
  164619. #ifdef C_PROGRESSIVE_SUPPORTED
  164620. LOCAL(jpeg_scan_info *)
  164621. fill_a_scan (jpeg_scan_info * scanptr, int ci,
  164622. int Ss, int Se, int Ah, int Al)
  164623. /* Support routine: generate one scan for specified component */
  164624. {
  164625. scanptr->comps_in_scan = 1;
  164626. scanptr->component_index[0] = ci;
  164627. scanptr->Ss = Ss;
  164628. scanptr->Se = Se;
  164629. scanptr->Ah = Ah;
  164630. scanptr->Al = Al;
  164631. scanptr++;
  164632. return scanptr;
  164633. }
  164634. LOCAL(jpeg_scan_info *)
  164635. fill_scans (jpeg_scan_info * scanptr, int ncomps,
  164636. int Ss, int Se, int Ah, int Al)
  164637. /* Support routine: generate one scan for each component */
  164638. {
  164639. int ci;
  164640. for (ci = 0; ci < ncomps; ci++) {
  164641. scanptr->comps_in_scan = 1;
  164642. scanptr->component_index[0] = ci;
  164643. scanptr->Ss = Ss;
  164644. scanptr->Se = Se;
  164645. scanptr->Ah = Ah;
  164646. scanptr->Al = Al;
  164647. scanptr++;
  164648. }
  164649. return scanptr;
  164650. }
  164651. LOCAL(jpeg_scan_info *)
  164652. fill_dc_scans (jpeg_scan_info * scanptr, int ncomps, int Ah, int Al)
  164653. /* Support routine: generate interleaved DC scan if possible, else N scans */
  164654. {
  164655. int ci;
  164656. if (ncomps <= MAX_COMPS_IN_SCAN) {
  164657. /* Single interleaved DC scan */
  164658. scanptr->comps_in_scan = ncomps;
  164659. for (ci = 0; ci < ncomps; ci++)
  164660. scanptr->component_index[ci] = ci;
  164661. scanptr->Ss = scanptr->Se = 0;
  164662. scanptr->Ah = Ah;
  164663. scanptr->Al = Al;
  164664. scanptr++;
  164665. } else {
  164666. /* Noninterleaved DC scan for each component */
  164667. scanptr = fill_scans(scanptr, ncomps, 0, 0, Ah, Al);
  164668. }
  164669. return scanptr;
  164670. }
  164671. /*
  164672. * Create a recommended progressive-JPEG script.
  164673. * cinfo->num_components and cinfo->jpeg_color_space must be correct.
  164674. */
  164675. GLOBAL(void)
  164676. jpeg_simple_progression (j_compress_ptr cinfo)
  164677. {
  164678. int ncomps = cinfo->num_components;
  164679. int nscans;
  164680. jpeg_scan_info * scanptr;
  164681. /* Safety check to ensure start_compress not called yet. */
  164682. if (cinfo->global_state != CSTATE_START)
  164683. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  164684. /* Figure space needed for script. Calculation must match code below! */
  164685. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  164686. /* Custom script for YCbCr color images. */
  164687. nscans = 10;
  164688. } else {
  164689. /* All-purpose script for other color spaces. */
  164690. if (ncomps > MAX_COMPS_IN_SCAN)
  164691. nscans = 6 * ncomps; /* 2 DC + 4 AC scans per component */
  164692. else
  164693. nscans = 2 + 4 * ncomps; /* 2 DC scans; 4 AC scans per component */
  164694. }
  164695. /* Allocate space for script.
  164696. * We need to put it in the permanent pool in case the application performs
  164697. * multiple compressions without changing the settings. To avoid a memory
  164698. * leak if jpeg_simple_progression is called repeatedly for the same JPEG
  164699. * object, we try to re-use previously allocated space, and we allocate
  164700. * enough space to handle YCbCr even if initially asked for grayscale.
  164701. */
  164702. if (cinfo->script_space == NULL || cinfo->script_space_size < nscans) {
  164703. cinfo->script_space_size = MAX(nscans, 10);
  164704. cinfo->script_space = (jpeg_scan_info *)
  164705. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  164706. cinfo->script_space_size * SIZEOF(jpeg_scan_info));
  164707. }
  164708. scanptr = cinfo->script_space;
  164709. cinfo->scan_info = scanptr;
  164710. cinfo->num_scans = nscans;
  164711. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  164712. /* Custom script for YCbCr color images. */
  164713. /* Initial DC scan */
  164714. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  164715. /* Initial AC scan: get some luma data out in a hurry */
  164716. scanptr = fill_a_scan(scanptr, 0, 1, 5, 0, 2);
  164717. /* Chroma data is too small to be worth expending many scans on */
  164718. scanptr = fill_a_scan(scanptr, 2, 1, 63, 0, 1);
  164719. scanptr = fill_a_scan(scanptr, 1, 1, 63, 0, 1);
  164720. /* Complete spectral selection for luma AC */
  164721. scanptr = fill_a_scan(scanptr, 0, 6, 63, 0, 2);
  164722. /* Refine next bit of luma AC */
  164723. scanptr = fill_a_scan(scanptr, 0, 1, 63, 2, 1);
  164724. /* Finish DC successive approximation */
  164725. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  164726. /* Finish AC successive approximation */
  164727. scanptr = fill_a_scan(scanptr, 2, 1, 63, 1, 0);
  164728. scanptr = fill_a_scan(scanptr, 1, 1, 63, 1, 0);
  164729. /* Luma bottom bit comes last since it's usually largest scan */
  164730. scanptr = fill_a_scan(scanptr, 0, 1, 63, 1, 0);
  164731. } else {
  164732. /* All-purpose script for other color spaces. */
  164733. /* Successive approximation first pass */
  164734. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  164735. scanptr = fill_scans(scanptr, ncomps, 1, 5, 0, 2);
  164736. scanptr = fill_scans(scanptr, ncomps, 6, 63, 0, 2);
  164737. /* Successive approximation second pass */
  164738. scanptr = fill_scans(scanptr, ncomps, 1, 63, 2, 1);
  164739. /* Successive approximation final pass */
  164740. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  164741. scanptr = fill_scans(scanptr, ncomps, 1, 63, 1, 0);
  164742. }
  164743. }
  164744. #endif /* C_PROGRESSIVE_SUPPORTED */
  164745. /*** End of inlined file: jcparam.c ***/
  164746. /*** Start of inlined file: jcphuff.c ***/
  164747. #define JPEG_INTERNALS
  164748. #ifdef C_PROGRESSIVE_SUPPORTED
  164749. /* Expanded entropy encoder object for progressive Huffman encoding. */
  164750. typedef struct {
  164751. struct jpeg_entropy_encoder pub; /* public fields */
  164752. /* Mode flag: TRUE for optimization, FALSE for actual data output */
  164753. boolean gather_statistics;
  164754. /* Bit-level coding status.
  164755. * next_output_byte/free_in_buffer are local copies of cinfo->dest fields.
  164756. */
  164757. JOCTET * next_output_byte; /* => next byte to write in buffer */
  164758. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  164759. INT32 put_buffer; /* current bit-accumulation buffer */
  164760. int put_bits; /* # of bits now in it */
  164761. j_compress_ptr cinfo; /* link to cinfo (needed for dump_buffer) */
  164762. /* Coding status for DC components */
  164763. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  164764. /* Coding status for AC components */
  164765. int ac_tbl_no; /* the table number of the single component */
  164766. unsigned int EOBRUN; /* run length of EOBs */
  164767. unsigned int BE; /* # of buffered correction bits before MCU */
  164768. char * bit_buffer; /* buffer for correction bits (1 per char) */
  164769. /* packing correction bits tightly would save some space but cost time... */
  164770. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  164771. int next_restart_num; /* next restart number to write (0-7) */
  164772. /* Pointers to derived tables (these workspaces have image lifespan).
  164773. * Since any one scan codes only DC or only AC, we only need one set
  164774. * of tables, not one for DC and one for AC.
  164775. */
  164776. c_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  164777. /* Statistics tables for optimization; again, one set is enough */
  164778. long * count_ptrs[NUM_HUFF_TBLS];
  164779. } phuff_entropy_encoder;
  164780. typedef phuff_entropy_encoder * phuff_entropy_ptr;
  164781. /* MAX_CORR_BITS is the number of bits the AC refinement correction-bit
  164782. * buffer can hold. Larger sizes may slightly improve compression, but
  164783. * 1000 is already well into the realm of overkill.
  164784. * The minimum safe size is 64 bits.
  164785. */
  164786. #define MAX_CORR_BITS 1000 /* Max # of correction bits I can buffer */
  164787. /* IRIGHT_SHIFT is like RIGHT_SHIFT, but works on int rather than INT32.
  164788. * We assume that int right shift is unsigned if INT32 right shift is,
  164789. * which should be safe.
  164790. */
  164791. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  164792. #define ISHIFT_TEMPS int ishift_temp;
  164793. #define IRIGHT_SHIFT(x,shft) \
  164794. ((ishift_temp = (x)) < 0 ? \
  164795. (ishift_temp >> (shft)) | ((~0) << (16-(shft))) : \
  164796. (ishift_temp >> (shft)))
  164797. #else
  164798. #define ISHIFT_TEMPS
  164799. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  164800. #endif
  164801. /* Forward declarations */
  164802. METHODDEF(boolean) encode_mcu_DC_first JPP((j_compress_ptr cinfo,
  164803. JBLOCKROW *MCU_data));
  164804. METHODDEF(boolean) encode_mcu_AC_first JPP((j_compress_ptr cinfo,
  164805. JBLOCKROW *MCU_data));
  164806. METHODDEF(boolean) encode_mcu_DC_refine JPP((j_compress_ptr cinfo,
  164807. JBLOCKROW *MCU_data));
  164808. METHODDEF(boolean) encode_mcu_AC_refine JPP((j_compress_ptr cinfo,
  164809. JBLOCKROW *MCU_data));
  164810. METHODDEF(void) finish_pass_phuff JPP((j_compress_ptr cinfo));
  164811. METHODDEF(void) finish_pass_gather_phuff JPP((j_compress_ptr cinfo));
  164812. /*
  164813. * Initialize for a Huffman-compressed scan using progressive JPEG.
  164814. */
  164815. METHODDEF(void)
  164816. start_pass_phuff (j_compress_ptr cinfo, boolean gather_statistics)
  164817. {
  164818. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  164819. boolean is_DC_band;
  164820. int ci, tbl;
  164821. jpeg_component_info * compptr;
  164822. entropy->cinfo = cinfo;
  164823. entropy->gather_statistics = gather_statistics;
  164824. is_DC_band = (cinfo->Ss == 0);
  164825. /* We assume jcmaster.c already validated the scan parameters. */
  164826. /* Select execution routines */
  164827. if (cinfo->Ah == 0) {
  164828. if (is_DC_band)
  164829. entropy->pub.encode_mcu = encode_mcu_DC_first;
  164830. else
  164831. entropy->pub.encode_mcu = encode_mcu_AC_first;
  164832. } else {
  164833. if (is_DC_band)
  164834. entropy->pub.encode_mcu = encode_mcu_DC_refine;
  164835. else {
  164836. entropy->pub.encode_mcu = encode_mcu_AC_refine;
  164837. /* AC refinement needs a correction bit buffer */
  164838. if (entropy->bit_buffer == NULL)
  164839. entropy->bit_buffer = (char *)
  164840. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164841. MAX_CORR_BITS * SIZEOF(char));
  164842. }
  164843. }
  164844. if (gather_statistics)
  164845. entropy->pub.finish_pass = finish_pass_gather_phuff;
  164846. else
  164847. entropy->pub.finish_pass = finish_pass_phuff;
  164848. /* Only DC coefficients may be interleaved, so cinfo->comps_in_scan = 1
  164849. * for AC coefficients.
  164850. */
  164851. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  164852. compptr = cinfo->cur_comp_info[ci];
  164853. /* Initialize DC predictions to 0 */
  164854. entropy->last_dc_val[ci] = 0;
  164855. /* Get table index */
  164856. if (is_DC_band) {
  164857. if (cinfo->Ah != 0) /* DC refinement needs no table */
  164858. continue;
  164859. tbl = compptr->dc_tbl_no;
  164860. } else {
  164861. entropy->ac_tbl_no = tbl = compptr->ac_tbl_no;
  164862. }
  164863. if (gather_statistics) {
  164864. /* Check for invalid table index */
  164865. /* (make_c_derived_tbl does this in the other path) */
  164866. if (tbl < 0 || tbl >= NUM_HUFF_TBLS)
  164867. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);
  164868. /* Allocate and zero the statistics tables */
  164869. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  164870. if (entropy->count_ptrs[tbl] == NULL)
  164871. entropy->count_ptrs[tbl] = (long *)
  164872. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164873. 257 * SIZEOF(long));
  164874. MEMZERO(entropy->count_ptrs[tbl], 257 * SIZEOF(long));
  164875. } else {
  164876. /* Compute derived values for Huffman table */
  164877. /* We may do this more than once for a table, but it's not expensive */
  164878. jpeg_make_c_derived_tbl(cinfo, is_DC_band, tbl,
  164879. & entropy->derived_tbls[tbl]);
  164880. }
  164881. }
  164882. /* Initialize AC stuff */
  164883. entropy->EOBRUN = 0;
  164884. entropy->BE = 0;
  164885. /* Initialize bit buffer to empty */
  164886. entropy->put_buffer = 0;
  164887. entropy->put_bits = 0;
  164888. /* Initialize restart stuff */
  164889. entropy->restarts_to_go = cinfo->restart_interval;
  164890. entropy->next_restart_num = 0;
  164891. }
  164892. /* Outputting bytes to the file.
  164893. * NB: these must be called only when actually outputting,
  164894. * that is, entropy->gather_statistics == FALSE.
  164895. */
  164896. /* Emit a byte */
  164897. #define emit_byte(entropy,val) \
  164898. { *(entropy)->next_output_byte++ = (JOCTET) (val); \
  164899. if (--(entropy)->free_in_buffer == 0) \
  164900. dump_buffer_p(entropy); }
  164901. LOCAL(void)
  164902. dump_buffer_p (phuff_entropy_ptr entropy)
  164903. /* Empty the output buffer; we do not support suspension in this module. */
  164904. {
  164905. struct jpeg_destination_mgr * dest = entropy->cinfo->dest;
  164906. if (! (*dest->empty_output_buffer) (entropy->cinfo))
  164907. ERREXIT(entropy->cinfo, JERR_CANT_SUSPEND);
  164908. /* After a successful buffer dump, must reset buffer pointers */
  164909. entropy->next_output_byte = dest->next_output_byte;
  164910. entropy->free_in_buffer = dest->free_in_buffer;
  164911. }
  164912. /* Outputting bits to the file */
  164913. /* Only the right 24 bits of put_buffer are used; the valid bits are
  164914. * left-justified in this part. At most 16 bits can be passed to emit_bits
  164915. * in one call, and we never retain more than 7 bits in put_buffer
  164916. * between calls, so 24 bits are sufficient.
  164917. */
  164918. INLINE
  164919. LOCAL(void)
  164920. emit_bits_p (phuff_entropy_ptr entropy, unsigned int code, int size)
  164921. /* Emit some bits, unless we are in gather mode */
  164922. {
  164923. /* This routine is heavily used, so it's worth coding tightly. */
  164924. register INT32 put_buffer = (INT32) code;
  164925. register int put_bits = entropy->put_bits;
  164926. /* if size is 0, caller used an invalid Huffman table entry */
  164927. if (size == 0)
  164928. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  164929. if (entropy->gather_statistics)
  164930. return; /* do nothing if we're only getting stats */
  164931. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  164932. put_bits += size; /* new number of bits in buffer */
  164933. put_buffer <<= 24 - put_bits; /* align incoming bits */
  164934. put_buffer |= entropy->put_buffer; /* and merge with old buffer contents */
  164935. while (put_bits >= 8) {
  164936. int c = (int) ((put_buffer >> 16) & 0xFF);
  164937. emit_byte(entropy, c);
  164938. if (c == 0xFF) { /* need to stuff a zero byte? */
  164939. emit_byte(entropy, 0);
  164940. }
  164941. put_buffer <<= 8;
  164942. put_bits -= 8;
  164943. }
  164944. entropy->put_buffer = put_buffer; /* update variables */
  164945. entropy->put_bits = put_bits;
  164946. }
  164947. LOCAL(void)
  164948. flush_bits_p (phuff_entropy_ptr entropy)
  164949. {
  164950. emit_bits_p(entropy, 0x7F, 7); /* fill any partial byte with ones */
  164951. entropy->put_buffer = 0; /* and reset bit-buffer to empty */
  164952. entropy->put_bits = 0;
  164953. }
  164954. /*
  164955. * Emit (or just count) a Huffman symbol.
  164956. */
  164957. INLINE
  164958. LOCAL(void)
  164959. emit_symbol (phuff_entropy_ptr entropy, int tbl_no, int symbol)
  164960. {
  164961. if (entropy->gather_statistics)
  164962. entropy->count_ptrs[tbl_no][symbol]++;
  164963. else {
  164964. c_derived_tbl * tbl = entropy->derived_tbls[tbl_no];
  164965. emit_bits_p(entropy, tbl->ehufco[symbol], tbl->ehufsi[symbol]);
  164966. }
  164967. }
  164968. /*
  164969. * Emit bits from a correction bit buffer.
  164970. */
  164971. LOCAL(void)
  164972. emit_buffered_bits (phuff_entropy_ptr entropy, char * bufstart,
  164973. unsigned int nbits)
  164974. {
  164975. if (entropy->gather_statistics)
  164976. return; /* no real work */
  164977. while (nbits > 0) {
  164978. emit_bits_p(entropy, (unsigned int) (*bufstart), 1);
  164979. bufstart++;
  164980. nbits--;
  164981. }
  164982. }
  164983. /*
  164984. * Emit any pending EOBRUN symbol.
  164985. */
  164986. LOCAL(void)
  164987. emit_eobrun (phuff_entropy_ptr entropy)
  164988. {
  164989. register int temp, nbits;
  164990. if (entropy->EOBRUN > 0) { /* if there is any pending EOBRUN */
  164991. temp = entropy->EOBRUN;
  164992. nbits = 0;
  164993. while ((temp >>= 1))
  164994. nbits++;
  164995. /* safety check: shouldn't happen given limited correction-bit buffer */
  164996. if (nbits > 14)
  164997. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  164998. emit_symbol(entropy, entropy->ac_tbl_no, nbits << 4);
  164999. if (nbits)
  165000. emit_bits_p(entropy, entropy->EOBRUN, nbits);
  165001. entropy->EOBRUN = 0;
  165002. /* Emit any buffered correction bits */
  165003. emit_buffered_bits(entropy, entropy->bit_buffer, entropy->BE);
  165004. entropy->BE = 0;
  165005. }
  165006. }
  165007. /*
  165008. * Emit a restart marker & resynchronize predictions.
  165009. */
  165010. LOCAL(void)
  165011. emit_restart_p (phuff_entropy_ptr entropy, int restart_num)
  165012. {
  165013. int ci;
  165014. emit_eobrun(entropy);
  165015. if (! entropy->gather_statistics) {
  165016. flush_bits_p(entropy);
  165017. emit_byte(entropy, 0xFF);
  165018. emit_byte(entropy, JPEG_RST0 + restart_num);
  165019. }
  165020. if (entropy->cinfo->Ss == 0) {
  165021. /* Re-initialize DC predictions to 0 */
  165022. for (ci = 0; ci < entropy->cinfo->comps_in_scan; ci++)
  165023. entropy->last_dc_val[ci] = 0;
  165024. } else {
  165025. /* Re-initialize all AC-related fields to 0 */
  165026. entropy->EOBRUN = 0;
  165027. entropy->BE = 0;
  165028. }
  165029. }
  165030. /*
  165031. * MCU encoding for DC initial scan (either spectral selection,
  165032. * or first pass of successive approximation).
  165033. */
  165034. METHODDEF(boolean)
  165035. encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  165036. {
  165037. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165038. register int temp, temp2;
  165039. register int nbits;
  165040. int blkn, ci;
  165041. int Al = cinfo->Al;
  165042. JBLOCKROW block;
  165043. jpeg_component_info * compptr;
  165044. ISHIFT_TEMPS
  165045. entropy->next_output_byte = cinfo->dest->next_output_byte;
  165046. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  165047. /* Emit restart marker if needed */
  165048. if (cinfo->restart_interval)
  165049. if (entropy->restarts_to_go == 0)
  165050. emit_restart_p(entropy, entropy->next_restart_num);
  165051. /* Encode the MCU data blocks */
  165052. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  165053. block = MCU_data[blkn];
  165054. ci = cinfo->MCU_membership[blkn];
  165055. compptr = cinfo->cur_comp_info[ci];
  165056. /* Compute the DC value after the required point transform by Al.
  165057. * This is simply an arithmetic right shift.
  165058. */
  165059. temp2 = IRIGHT_SHIFT((int) ((*block)[0]), Al);
  165060. /* DC differences are figured on the point-transformed values. */
  165061. temp = temp2 - entropy->last_dc_val[ci];
  165062. entropy->last_dc_val[ci] = temp2;
  165063. /* Encode the DC coefficient difference per section G.1.2.1 */
  165064. temp2 = temp;
  165065. if (temp < 0) {
  165066. temp = -temp; /* temp is abs value of input */
  165067. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  165068. /* This code assumes we are on a two's complement machine */
  165069. temp2--;
  165070. }
  165071. /* Find the number of bits needed for the magnitude of the coefficient */
  165072. nbits = 0;
  165073. while (temp) {
  165074. nbits++;
  165075. temp >>= 1;
  165076. }
  165077. /* Check for out-of-range coefficient values.
  165078. * Since we're encoding a difference, the range limit is twice as much.
  165079. */
  165080. if (nbits > MAX_COEF_BITS+1)
  165081. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  165082. /* Count/emit the Huffman-coded symbol for the number of bits */
  165083. emit_symbol(entropy, compptr->dc_tbl_no, nbits);
  165084. /* Emit that number of bits of the value, if positive, */
  165085. /* or the complement of its magnitude, if negative. */
  165086. if (nbits) /* emit_bits rejects calls with size 0 */
  165087. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  165088. }
  165089. cinfo->dest->next_output_byte = entropy->next_output_byte;
  165090. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  165091. /* Update restart-interval state too */
  165092. if (cinfo->restart_interval) {
  165093. if (entropy->restarts_to_go == 0) {
  165094. entropy->restarts_to_go = cinfo->restart_interval;
  165095. entropy->next_restart_num++;
  165096. entropy->next_restart_num &= 7;
  165097. }
  165098. entropy->restarts_to_go--;
  165099. }
  165100. return TRUE;
  165101. }
  165102. /*
  165103. * MCU encoding for AC initial scan (either spectral selection,
  165104. * or first pass of successive approximation).
  165105. */
  165106. METHODDEF(boolean)
  165107. encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  165108. {
  165109. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165110. register int temp, temp2;
  165111. register int nbits;
  165112. register int r, k;
  165113. int Se = cinfo->Se;
  165114. int Al = cinfo->Al;
  165115. JBLOCKROW block;
  165116. entropy->next_output_byte = cinfo->dest->next_output_byte;
  165117. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  165118. /* Emit restart marker if needed */
  165119. if (cinfo->restart_interval)
  165120. if (entropy->restarts_to_go == 0)
  165121. emit_restart_p(entropy, entropy->next_restart_num);
  165122. /* Encode the MCU data block */
  165123. block = MCU_data[0];
  165124. /* Encode the AC coefficients per section G.1.2.2, fig. G.3 */
  165125. r = 0; /* r = run length of zeros */
  165126. for (k = cinfo->Ss; k <= Se; k++) {
  165127. if ((temp = (*block)[jpeg_natural_order[k]]) == 0) {
  165128. r++;
  165129. continue;
  165130. }
  165131. /* We must apply the point transform by Al. For AC coefficients this
  165132. * is an integer division with rounding towards 0. To do this portably
  165133. * in C, we shift after obtaining the absolute value; so the code is
  165134. * interwoven with finding the abs value (temp) and output bits (temp2).
  165135. */
  165136. if (temp < 0) {
  165137. temp = -temp; /* temp is abs value of input */
  165138. temp >>= Al; /* apply the point transform */
  165139. /* For a negative coef, want temp2 = bitwise complement of abs(coef) */
  165140. temp2 = ~temp;
  165141. } else {
  165142. temp >>= Al; /* apply the point transform */
  165143. temp2 = temp;
  165144. }
  165145. /* Watch out for case that nonzero coef is zero after point transform */
  165146. if (temp == 0) {
  165147. r++;
  165148. continue;
  165149. }
  165150. /* Emit any pending EOBRUN */
  165151. if (entropy->EOBRUN > 0)
  165152. emit_eobrun(entropy);
  165153. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  165154. while (r > 15) {
  165155. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  165156. r -= 16;
  165157. }
  165158. /* Find the number of bits needed for the magnitude of the coefficient */
  165159. nbits = 1; /* there must be at least one 1 bit */
  165160. while ((temp >>= 1))
  165161. nbits++;
  165162. /* Check for out-of-range coefficient values */
  165163. if (nbits > MAX_COEF_BITS)
  165164. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  165165. /* Count/emit Huffman symbol for run length / number of bits */
  165166. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + nbits);
  165167. /* Emit that number of bits of the value, if positive, */
  165168. /* or the complement of its magnitude, if negative. */
  165169. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  165170. r = 0; /* reset zero run length */
  165171. }
  165172. if (r > 0) { /* If there are trailing zeroes, */
  165173. entropy->EOBRUN++; /* count an EOB */
  165174. if (entropy->EOBRUN == 0x7FFF)
  165175. emit_eobrun(entropy); /* force it out to avoid overflow */
  165176. }
  165177. cinfo->dest->next_output_byte = entropy->next_output_byte;
  165178. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  165179. /* Update restart-interval state too */
  165180. if (cinfo->restart_interval) {
  165181. if (entropy->restarts_to_go == 0) {
  165182. entropy->restarts_to_go = cinfo->restart_interval;
  165183. entropy->next_restart_num++;
  165184. entropy->next_restart_num &= 7;
  165185. }
  165186. entropy->restarts_to_go--;
  165187. }
  165188. return TRUE;
  165189. }
  165190. /*
  165191. * MCU encoding for DC successive approximation refinement scan.
  165192. * Note: we assume such scans can be multi-component, although the spec
  165193. * is not very clear on the point.
  165194. */
  165195. METHODDEF(boolean)
  165196. encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  165197. {
  165198. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165199. register int temp;
  165200. int blkn;
  165201. int Al = cinfo->Al;
  165202. JBLOCKROW block;
  165203. entropy->next_output_byte = cinfo->dest->next_output_byte;
  165204. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  165205. /* Emit restart marker if needed */
  165206. if (cinfo->restart_interval)
  165207. if (entropy->restarts_to_go == 0)
  165208. emit_restart_p(entropy, entropy->next_restart_num);
  165209. /* Encode the MCU data blocks */
  165210. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  165211. block = MCU_data[blkn];
  165212. /* We simply emit the Al'th bit of the DC coefficient value. */
  165213. temp = (*block)[0];
  165214. emit_bits_p(entropy, (unsigned int) (temp >> Al), 1);
  165215. }
  165216. cinfo->dest->next_output_byte = entropy->next_output_byte;
  165217. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  165218. /* Update restart-interval state too */
  165219. if (cinfo->restart_interval) {
  165220. if (entropy->restarts_to_go == 0) {
  165221. entropy->restarts_to_go = cinfo->restart_interval;
  165222. entropy->next_restart_num++;
  165223. entropy->next_restart_num &= 7;
  165224. }
  165225. entropy->restarts_to_go--;
  165226. }
  165227. return TRUE;
  165228. }
  165229. /*
  165230. * MCU encoding for AC successive approximation refinement scan.
  165231. */
  165232. METHODDEF(boolean)
  165233. encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  165234. {
  165235. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165236. register int temp;
  165237. register int r, k;
  165238. int EOB;
  165239. char *BR_buffer;
  165240. unsigned int BR;
  165241. int Se = cinfo->Se;
  165242. int Al = cinfo->Al;
  165243. JBLOCKROW block;
  165244. int absvalues[DCTSIZE2];
  165245. entropy->next_output_byte = cinfo->dest->next_output_byte;
  165246. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  165247. /* Emit restart marker if needed */
  165248. if (cinfo->restart_interval)
  165249. if (entropy->restarts_to_go == 0)
  165250. emit_restart_p(entropy, entropy->next_restart_num);
  165251. /* Encode the MCU data block */
  165252. block = MCU_data[0];
  165253. /* It is convenient to make a pre-pass to determine the transformed
  165254. * coefficients' absolute values and the EOB position.
  165255. */
  165256. EOB = 0;
  165257. for (k = cinfo->Ss; k <= Se; k++) {
  165258. temp = (*block)[jpeg_natural_order[k]];
  165259. /* We must apply the point transform by Al. For AC coefficients this
  165260. * is an integer division with rounding towards 0. To do this portably
  165261. * in C, we shift after obtaining the absolute value.
  165262. */
  165263. if (temp < 0)
  165264. temp = -temp; /* temp is abs value of input */
  165265. temp >>= Al; /* apply the point transform */
  165266. absvalues[k] = temp; /* save abs value for main pass */
  165267. if (temp == 1)
  165268. EOB = k; /* EOB = index of last newly-nonzero coef */
  165269. }
  165270. /* Encode the AC coefficients per section G.1.2.3, fig. G.7 */
  165271. r = 0; /* r = run length of zeros */
  165272. BR = 0; /* BR = count of buffered bits added now */
  165273. BR_buffer = entropy->bit_buffer + entropy->BE; /* Append bits to buffer */
  165274. for (k = cinfo->Ss; k <= Se; k++) {
  165275. if ((temp = absvalues[k]) == 0) {
  165276. r++;
  165277. continue;
  165278. }
  165279. /* Emit any required ZRLs, but not if they can be folded into EOB */
  165280. while (r > 15 && k <= EOB) {
  165281. /* emit any pending EOBRUN and the BE correction bits */
  165282. emit_eobrun(entropy);
  165283. /* Emit ZRL */
  165284. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  165285. r -= 16;
  165286. /* Emit buffered correction bits that must be associated with ZRL */
  165287. emit_buffered_bits(entropy, BR_buffer, BR);
  165288. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  165289. BR = 0;
  165290. }
  165291. /* If the coef was previously nonzero, it only needs a correction bit.
  165292. * NOTE: a straight translation of the spec's figure G.7 would suggest
  165293. * that we also need to test r > 15. But if r > 15, we can only get here
  165294. * if k > EOB, which implies that this coefficient is not 1.
  165295. */
  165296. if (temp > 1) {
  165297. /* The correction bit is the next bit of the absolute value. */
  165298. BR_buffer[BR++] = (char) (temp & 1);
  165299. continue;
  165300. }
  165301. /* Emit any pending EOBRUN and the BE correction bits */
  165302. emit_eobrun(entropy);
  165303. /* Count/emit Huffman symbol for run length / number of bits */
  165304. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + 1);
  165305. /* Emit output bit for newly-nonzero coef */
  165306. temp = ((*block)[jpeg_natural_order[k]] < 0) ? 0 : 1;
  165307. emit_bits_p(entropy, (unsigned int) temp, 1);
  165308. /* Emit buffered correction bits that must be associated with this code */
  165309. emit_buffered_bits(entropy, BR_buffer, BR);
  165310. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  165311. BR = 0;
  165312. r = 0; /* reset zero run length */
  165313. }
  165314. if (r > 0 || BR > 0) { /* If there are trailing zeroes, */
  165315. entropy->EOBRUN++; /* count an EOB */
  165316. entropy->BE += BR; /* concat my correction bits to older ones */
  165317. /* We force out the EOB if we risk either:
  165318. * 1. overflow of the EOB counter;
  165319. * 2. overflow of the correction bit buffer during the next MCU.
  165320. */
  165321. if (entropy->EOBRUN == 0x7FFF || entropy->BE > (MAX_CORR_BITS-DCTSIZE2+1))
  165322. emit_eobrun(entropy);
  165323. }
  165324. cinfo->dest->next_output_byte = entropy->next_output_byte;
  165325. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  165326. /* Update restart-interval state too */
  165327. if (cinfo->restart_interval) {
  165328. if (entropy->restarts_to_go == 0) {
  165329. entropy->restarts_to_go = cinfo->restart_interval;
  165330. entropy->next_restart_num++;
  165331. entropy->next_restart_num &= 7;
  165332. }
  165333. entropy->restarts_to_go--;
  165334. }
  165335. return TRUE;
  165336. }
  165337. /*
  165338. * Finish up at the end of a Huffman-compressed progressive scan.
  165339. */
  165340. METHODDEF(void)
  165341. finish_pass_phuff (j_compress_ptr cinfo)
  165342. {
  165343. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165344. entropy->next_output_byte = cinfo->dest->next_output_byte;
  165345. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  165346. /* Flush out any buffered data */
  165347. emit_eobrun(entropy);
  165348. flush_bits_p(entropy);
  165349. cinfo->dest->next_output_byte = entropy->next_output_byte;
  165350. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  165351. }
  165352. /*
  165353. * Finish up a statistics-gathering pass and create the new Huffman tables.
  165354. */
  165355. METHODDEF(void)
  165356. finish_pass_gather_phuff (j_compress_ptr cinfo)
  165357. {
  165358. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165359. boolean is_DC_band;
  165360. int ci, tbl;
  165361. jpeg_component_info * compptr;
  165362. JHUFF_TBL **htblptr;
  165363. boolean did[NUM_HUFF_TBLS];
  165364. /* Flush out buffered data (all we care about is counting the EOB symbol) */
  165365. emit_eobrun(entropy);
  165366. is_DC_band = (cinfo->Ss == 0);
  165367. /* It's important not to apply jpeg_gen_optimal_table more than once
  165368. * per table, because it clobbers the input frequency counts!
  165369. */
  165370. MEMZERO(did, SIZEOF(did));
  165371. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  165372. compptr = cinfo->cur_comp_info[ci];
  165373. if (is_DC_band) {
  165374. if (cinfo->Ah != 0) /* DC refinement needs no table */
  165375. continue;
  165376. tbl = compptr->dc_tbl_no;
  165377. } else {
  165378. tbl = compptr->ac_tbl_no;
  165379. }
  165380. if (! did[tbl]) {
  165381. if (is_DC_band)
  165382. htblptr = & cinfo->dc_huff_tbl_ptrs[tbl];
  165383. else
  165384. htblptr = & cinfo->ac_huff_tbl_ptrs[tbl];
  165385. if (*htblptr == NULL)
  165386. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  165387. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->count_ptrs[tbl]);
  165388. did[tbl] = TRUE;
  165389. }
  165390. }
  165391. }
  165392. /*
  165393. * Module initialization routine for progressive Huffman entropy encoding.
  165394. */
  165395. GLOBAL(void)
  165396. jinit_phuff_encoder (j_compress_ptr cinfo)
  165397. {
  165398. phuff_entropy_ptr entropy;
  165399. int i;
  165400. entropy = (phuff_entropy_ptr)
  165401. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165402. SIZEOF(phuff_entropy_encoder));
  165403. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  165404. entropy->pub.start_pass = start_pass_phuff;
  165405. /* Mark tables unallocated */
  165406. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  165407. entropy->derived_tbls[i] = NULL;
  165408. entropy->count_ptrs[i] = NULL;
  165409. }
  165410. entropy->bit_buffer = NULL; /* needed only in AC refinement scan */
  165411. }
  165412. #endif /* C_PROGRESSIVE_SUPPORTED */
  165413. /*** End of inlined file: jcphuff.c ***/
  165414. /*** Start of inlined file: jcprepct.c ***/
  165415. #define JPEG_INTERNALS
  165416. /* At present, jcsample.c can request context rows only for smoothing.
  165417. * In the future, we might also need context rows for CCIR601 sampling
  165418. * or other more-complex downsampling procedures. The code to support
  165419. * context rows should be compiled only if needed.
  165420. */
  165421. #ifdef INPUT_SMOOTHING_SUPPORTED
  165422. #define CONTEXT_ROWS_SUPPORTED
  165423. #endif
  165424. /*
  165425. * For the simple (no-context-row) case, we just need to buffer one
  165426. * row group's worth of pixels for the downsampling step. At the bottom of
  165427. * the image, we pad to a full row group by replicating the last pixel row.
  165428. * The downsampler's last output row is then replicated if needed to pad
  165429. * out to a full iMCU row.
  165430. *
  165431. * When providing context rows, we must buffer three row groups' worth of
  165432. * pixels. Three row groups are physically allocated, but the row pointer
  165433. * arrays are made five row groups high, with the extra pointers above and
  165434. * below "wrapping around" to point to the last and first real row groups.
  165435. * This allows the downsampler to access the proper context rows.
  165436. * At the top and bottom of the image, we create dummy context rows by
  165437. * copying the first or last real pixel row. This copying could be avoided
  165438. * by pointer hacking as is done in jdmainct.c, but it doesn't seem worth the
  165439. * trouble on the compression side.
  165440. */
  165441. /* Private buffer controller object */
  165442. typedef struct {
  165443. struct jpeg_c_prep_controller pub; /* public fields */
  165444. /* Downsampling input buffer. This buffer holds color-converted data
  165445. * until we have enough to do a downsample step.
  165446. */
  165447. JSAMPARRAY color_buf[MAX_COMPONENTS];
  165448. JDIMENSION rows_to_go; /* counts rows remaining in source image */
  165449. int next_buf_row; /* index of next row to store in color_buf */
  165450. #ifdef CONTEXT_ROWS_SUPPORTED /* only needed for context case */
  165451. int this_row_group; /* starting row index of group to process */
  165452. int next_buf_stop; /* downsample when we reach this index */
  165453. #endif
  165454. } my_prep_controller;
  165455. typedef my_prep_controller * my_prep_ptr;
  165456. /*
  165457. * Initialize for a processing pass.
  165458. */
  165459. METHODDEF(void)
  165460. start_pass_prep (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  165461. {
  165462. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  165463. if (pass_mode != JBUF_PASS_THRU)
  165464. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  165465. /* Initialize total-height counter for detecting bottom of image */
  165466. prep->rows_to_go = cinfo->image_height;
  165467. /* Mark the conversion buffer empty */
  165468. prep->next_buf_row = 0;
  165469. #ifdef CONTEXT_ROWS_SUPPORTED
  165470. /* Preset additional state variables for context mode.
  165471. * These aren't used in non-context mode, so we needn't test which mode.
  165472. */
  165473. prep->this_row_group = 0;
  165474. /* Set next_buf_stop to stop after two row groups have been read in. */
  165475. prep->next_buf_stop = 2 * cinfo->max_v_samp_factor;
  165476. #endif
  165477. }
  165478. /*
  165479. * Expand an image vertically from height input_rows to height output_rows,
  165480. * by duplicating the bottom row.
  165481. */
  165482. LOCAL(void)
  165483. expand_bottom_edge (JSAMPARRAY image_data, JDIMENSION num_cols,
  165484. int input_rows, int output_rows)
  165485. {
  165486. register int row;
  165487. for (row = input_rows; row < output_rows; row++) {
  165488. jcopy_sample_rows(image_data, input_rows-1, image_data, row,
  165489. 1, num_cols);
  165490. }
  165491. }
  165492. /*
  165493. * Process some data in the simple no-context case.
  165494. *
  165495. * Preprocessor output data is counted in "row groups". A row group
  165496. * is defined to be v_samp_factor sample rows of each component.
  165497. * Downsampling will produce this much data from each max_v_samp_factor
  165498. * input rows.
  165499. */
  165500. METHODDEF(void)
  165501. pre_process_data (j_compress_ptr cinfo,
  165502. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  165503. JDIMENSION in_rows_avail,
  165504. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  165505. JDIMENSION out_row_groups_avail)
  165506. {
  165507. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  165508. int numrows, ci;
  165509. JDIMENSION inrows;
  165510. jpeg_component_info * compptr;
  165511. while (*in_row_ctr < in_rows_avail &&
  165512. *out_row_group_ctr < out_row_groups_avail) {
  165513. /* Do color conversion to fill the conversion buffer. */
  165514. inrows = in_rows_avail - *in_row_ctr;
  165515. numrows = cinfo->max_v_samp_factor - prep->next_buf_row;
  165516. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  165517. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  165518. prep->color_buf,
  165519. (JDIMENSION) prep->next_buf_row,
  165520. numrows);
  165521. *in_row_ctr += numrows;
  165522. prep->next_buf_row += numrows;
  165523. prep->rows_to_go -= numrows;
  165524. /* If at bottom of image, pad to fill the conversion buffer. */
  165525. if (prep->rows_to_go == 0 &&
  165526. prep->next_buf_row < cinfo->max_v_samp_factor) {
  165527. for (ci = 0; ci < cinfo->num_components; ci++) {
  165528. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  165529. prep->next_buf_row, cinfo->max_v_samp_factor);
  165530. }
  165531. prep->next_buf_row = cinfo->max_v_samp_factor;
  165532. }
  165533. /* If we've filled the conversion buffer, empty it. */
  165534. if (prep->next_buf_row == cinfo->max_v_samp_factor) {
  165535. (*cinfo->downsample->downsample) (cinfo,
  165536. prep->color_buf, (JDIMENSION) 0,
  165537. output_buf, *out_row_group_ctr);
  165538. prep->next_buf_row = 0;
  165539. (*out_row_group_ctr)++;
  165540. }
  165541. /* If at bottom of image, pad the output to a full iMCU height.
  165542. * Note we assume the caller is providing a one-iMCU-height output buffer!
  165543. */
  165544. if (prep->rows_to_go == 0 &&
  165545. *out_row_group_ctr < out_row_groups_avail) {
  165546. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165547. ci++, compptr++) {
  165548. expand_bottom_edge(output_buf[ci],
  165549. compptr->width_in_blocks * DCTSIZE,
  165550. (int) (*out_row_group_ctr * compptr->v_samp_factor),
  165551. (int) (out_row_groups_avail * compptr->v_samp_factor));
  165552. }
  165553. *out_row_group_ctr = out_row_groups_avail;
  165554. break; /* can exit outer loop without test */
  165555. }
  165556. }
  165557. }
  165558. #ifdef CONTEXT_ROWS_SUPPORTED
  165559. /*
  165560. * Process some data in the context case.
  165561. */
  165562. METHODDEF(void)
  165563. pre_process_context (j_compress_ptr cinfo,
  165564. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  165565. JDIMENSION in_rows_avail,
  165566. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  165567. JDIMENSION out_row_groups_avail)
  165568. {
  165569. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  165570. int numrows, ci;
  165571. int buf_height = cinfo->max_v_samp_factor * 3;
  165572. JDIMENSION inrows;
  165573. while (*out_row_group_ctr < out_row_groups_avail) {
  165574. if (*in_row_ctr < in_rows_avail) {
  165575. /* Do color conversion to fill the conversion buffer. */
  165576. inrows = in_rows_avail - *in_row_ctr;
  165577. numrows = prep->next_buf_stop - prep->next_buf_row;
  165578. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  165579. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  165580. prep->color_buf,
  165581. (JDIMENSION) prep->next_buf_row,
  165582. numrows);
  165583. /* Pad at top of image, if first time through */
  165584. if (prep->rows_to_go == cinfo->image_height) {
  165585. for (ci = 0; ci < cinfo->num_components; ci++) {
  165586. int row;
  165587. for (row = 1; row <= cinfo->max_v_samp_factor; row++) {
  165588. jcopy_sample_rows(prep->color_buf[ci], 0,
  165589. prep->color_buf[ci], -row,
  165590. 1, cinfo->image_width);
  165591. }
  165592. }
  165593. }
  165594. *in_row_ctr += numrows;
  165595. prep->next_buf_row += numrows;
  165596. prep->rows_to_go -= numrows;
  165597. } else {
  165598. /* Return for more data, unless we are at the bottom of the image. */
  165599. if (prep->rows_to_go != 0)
  165600. break;
  165601. /* When at bottom of image, pad to fill the conversion buffer. */
  165602. if (prep->next_buf_row < prep->next_buf_stop) {
  165603. for (ci = 0; ci < cinfo->num_components; ci++) {
  165604. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  165605. prep->next_buf_row, prep->next_buf_stop);
  165606. }
  165607. prep->next_buf_row = prep->next_buf_stop;
  165608. }
  165609. }
  165610. /* If we've gotten enough data, downsample a row group. */
  165611. if (prep->next_buf_row == prep->next_buf_stop) {
  165612. (*cinfo->downsample->downsample) (cinfo,
  165613. prep->color_buf,
  165614. (JDIMENSION) prep->this_row_group,
  165615. output_buf, *out_row_group_ctr);
  165616. (*out_row_group_ctr)++;
  165617. /* Advance pointers with wraparound as necessary. */
  165618. prep->this_row_group += cinfo->max_v_samp_factor;
  165619. if (prep->this_row_group >= buf_height)
  165620. prep->this_row_group = 0;
  165621. if (prep->next_buf_row >= buf_height)
  165622. prep->next_buf_row = 0;
  165623. prep->next_buf_stop = prep->next_buf_row + cinfo->max_v_samp_factor;
  165624. }
  165625. }
  165626. }
  165627. /*
  165628. * Create the wrapped-around downsampling input buffer needed for context mode.
  165629. */
  165630. LOCAL(void)
  165631. create_context_buffer (j_compress_ptr cinfo)
  165632. {
  165633. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  165634. int rgroup_height = cinfo->max_v_samp_factor;
  165635. int ci, i;
  165636. jpeg_component_info * compptr;
  165637. JSAMPARRAY true_buffer, fake_buffer;
  165638. /* Grab enough space for fake row pointers for all the components;
  165639. * we need five row groups' worth of pointers for each component.
  165640. */
  165641. fake_buffer = (JSAMPARRAY)
  165642. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165643. (cinfo->num_components * 5 * rgroup_height) *
  165644. SIZEOF(JSAMPROW));
  165645. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165646. ci++, compptr++) {
  165647. /* Allocate the actual buffer space (3 row groups) for this component.
  165648. * We make the buffer wide enough to allow the downsampler to edge-expand
  165649. * horizontally within the buffer, if it so chooses.
  165650. */
  165651. true_buffer = (*cinfo->mem->alloc_sarray)
  165652. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165653. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  165654. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  165655. (JDIMENSION) (3 * rgroup_height));
  165656. /* Copy true buffer row pointers into the middle of the fake row array */
  165657. MEMCOPY(fake_buffer + rgroup_height, true_buffer,
  165658. 3 * rgroup_height * SIZEOF(JSAMPROW));
  165659. /* Fill in the above and below wraparound pointers */
  165660. for (i = 0; i < rgroup_height; i++) {
  165661. fake_buffer[i] = true_buffer[2 * rgroup_height + i];
  165662. fake_buffer[4 * rgroup_height + i] = true_buffer[i];
  165663. }
  165664. prep->color_buf[ci] = fake_buffer + rgroup_height;
  165665. fake_buffer += 5 * rgroup_height; /* point to space for next component */
  165666. }
  165667. }
  165668. #endif /* CONTEXT_ROWS_SUPPORTED */
  165669. /*
  165670. * Initialize preprocessing controller.
  165671. */
  165672. GLOBAL(void)
  165673. jinit_c_prep_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  165674. {
  165675. my_prep_ptr prep;
  165676. int ci;
  165677. jpeg_component_info * compptr;
  165678. if (need_full_buffer) /* safety check */
  165679. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  165680. prep = (my_prep_ptr)
  165681. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165682. SIZEOF(my_prep_controller));
  165683. cinfo->prep = (struct jpeg_c_prep_controller *) prep;
  165684. prep->pub.start_pass = start_pass_prep;
  165685. /* Allocate the color conversion buffer.
  165686. * We make the buffer wide enough to allow the downsampler to edge-expand
  165687. * horizontally within the buffer, if it so chooses.
  165688. */
  165689. if (cinfo->downsample->need_context_rows) {
  165690. /* Set up to provide context rows */
  165691. #ifdef CONTEXT_ROWS_SUPPORTED
  165692. prep->pub.pre_process_data = pre_process_context;
  165693. create_context_buffer(cinfo);
  165694. #else
  165695. ERREXIT(cinfo, JERR_NOT_COMPILED);
  165696. #endif
  165697. } else {
  165698. /* No context, just make it tall enough for one row group */
  165699. prep->pub.pre_process_data = pre_process_data;
  165700. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165701. ci++, compptr++) {
  165702. prep->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  165703. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165704. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  165705. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  165706. (JDIMENSION) cinfo->max_v_samp_factor);
  165707. }
  165708. }
  165709. }
  165710. /*** End of inlined file: jcprepct.c ***/
  165711. /*** Start of inlined file: jcsample.c ***/
  165712. #define JPEG_INTERNALS
  165713. /* Pointer to routine to downsample a single component */
  165714. typedef JMETHOD(void, downsample1_ptr,
  165715. (j_compress_ptr cinfo, jpeg_component_info * compptr,
  165716. JSAMPARRAY input_data, JSAMPARRAY output_data));
  165717. /* Private subobject */
  165718. typedef struct {
  165719. struct jpeg_downsampler pub; /* public fields */
  165720. /* Downsampling method pointers, one per component */
  165721. downsample1_ptr methods[MAX_COMPONENTS];
  165722. } my_downsampler;
  165723. typedef my_downsampler * my_downsample_ptr;
  165724. /*
  165725. * Initialize for a downsampling pass.
  165726. */
  165727. METHODDEF(void)
  165728. start_pass_downsample (j_compress_ptr)
  165729. {
  165730. /* no work for now */
  165731. }
  165732. /*
  165733. * Expand a component horizontally from width input_cols to width output_cols,
  165734. * by duplicating the rightmost samples.
  165735. */
  165736. LOCAL(void)
  165737. expand_right_edge (JSAMPARRAY image_data, int num_rows,
  165738. JDIMENSION input_cols, JDIMENSION output_cols)
  165739. {
  165740. register JSAMPROW ptr;
  165741. register JSAMPLE pixval;
  165742. register int count;
  165743. int row;
  165744. int numcols = (int) (output_cols - input_cols);
  165745. if (numcols > 0) {
  165746. for (row = 0; row < num_rows; row++) {
  165747. ptr = image_data[row] + input_cols;
  165748. pixval = ptr[-1]; /* don't need GETJSAMPLE() here */
  165749. for (count = numcols; count > 0; count--)
  165750. *ptr++ = pixval;
  165751. }
  165752. }
  165753. }
  165754. /*
  165755. * Do downsampling for a whole row group (all components).
  165756. *
  165757. * In this version we simply downsample each component independently.
  165758. */
  165759. METHODDEF(void)
  165760. sep_downsample (j_compress_ptr cinfo,
  165761. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  165762. JSAMPIMAGE output_buf, JDIMENSION out_row_group_index)
  165763. {
  165764. my_downsample_ptr downsample = (my_downsample_ptr) cinfo->downsample;
  165765. int ci;
  165766. jpeg_component_info * compptr;
  165767. JSAMPARRAY in_ptr, out_ptr;
  165768. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165769. ci++, compptr++) {
  165770. in_ptr = input_buf[ci] + in_row_index;
  165771. out_ptr = output_buf[ci] + (out_row_group_index * compptr->v_samp_factor);
  165772. (*downsample->methods[ci]) (cinfo, compptr, in_ptr, out_ptr);
  165773. }
  165774. }
  165775. /*
  165776. * Downsample pixel values of a single component.
  165777. * One row group is processed per call.
  165778. * This version handles arbitrary integral sampling ratios, without smoothing.
  165779. * Note that this version is not actually used for customary sampling ratios.
  165780. */
  165781. METHODDEF(void)
  165782. int_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  165783. JSAMPARRAY input_data, JSAMPARRAY output_data)
  165784. {
  165785. int inrow, outrow, h_expand, v_expand, numpix, numpix2, h, v;
  165786. JDIMENSION outcol, outcol_h; /* outcol_h == outcol*h_expand */
  165787. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  165788. JSAMPROW inptr, outptr;
  165789. INT32 outvalue;
  165790. h_expand = cinfo->max_h_samp_factor / compptr->h_samp_factor;
  165791. v_expand = cinfo->max_v_samp_factor / compptr->v_samp_factor;
  165792. numpix = h_expand * v_expand;
  165793. numpix2 = numpix/2;
  165794. /* Expand input data enough to let all the output samples be generated
  165795. * by the standard loop. Special-casing padded output would be more
  165796. * efficient.
  165797. */
  165798. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  165799. cinfo->image_width, output_cols * h_expand);
  165800. inrow = 0;
  165801. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  165802. outptr = output_data[outrow];
  165803. for (outcol = 0, outcol_h = 0; outcol < output_cols;
  165804. outcol++, outcol_h += h_expand) {
  165805. outvalue = 0;
  165806. for (v = 0; v < v_expand; v++) {
  165807. inptr = input_data[inrow+v] + outcol_h;
  165808. for (h = 0; h < h_expand; h++) {
  165809. outvalue += (INT32) GETJSAMPLE(*inptr++);
  165810. }
  165811. }
  165812. *outptr++ = (JSAMPLE) ((outvalue + numpix2) / numpix);
  165813. }
  165814. inrow += v_expand;
  165815. }
  165816. }
  165817. /*
  165818. * Downsample pixel values of a single component.
  165819. * This version handles the special case of a full-size component,
  165820. * without smoothing.
  165821. */
  165822. METHODDEF(void)
  165823. fullsize_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  165824. JSAMPARRAY input_data, JSAMPARRAY output_data)
  165825. {
  165826. /* Copy the data */
  165827. jcopy_sample_rows(input_data, 0, output_data, 0,
  165828. cinfo->max_v_samp_factor, cinfo->image_width);
  165829. /* Edge-expand */
  165830. expand_right_edge(output_data, cinfo->max_v_samp_factor,
  165831. cinfo->image_width, compptr->width_in_blocks * DCTSIZE);
  165832. }
  165833. /*
  165834. * Downsample pixel values of a single component.
  165835. * This version handles the common case of 2:1 horizontal and 1:1 vertical,
  165836. * without smoothing.
  165837. *
  165838. * A note about the "bias" calculations: when rounding fractional values to
  165839. * integer, we do not want to always round 0.5 up to the next integer.
  165840. * If we did that, we'd introduce a noticeable bias towards larger values.
  165841. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  165842. * alternate pixel locations (a simple ordered dither pattern).
  165843. */
  165844. METHODDEF(void)
  165845. h2v1_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  165846. JSAMPARRAY input_data, JSAMPARRAY output_data)
  165847. {
  165848. int outrow;
  165849. JDIMENSION outcol;
  165850. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  165851. register JSAMPROW inptr, outptr;
  165852. register int bias;
  165853. /* Expand input data enough to let all the output samples be generated
  165854. * by the standard loop. Special-casing padded output would be more
  165855. * efficient.
  165856. */
  165857. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  165858. cinfo->image_width, output_cols * 2);
  165859. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  165860. outptr = output_data[outrow];
  165861. inptr = input_data[outrow];
  165862. bias = 0; /* bias = 0,1,0,1,... for successive samples */
  165863. for (outcol = 0; outcol < output_cols; outcol++) {
  165864. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr) + GETJSAMPLE(inptr[1])
  165865. + bias) >> 1);
  165866. bias ^= 1; /* 0=>1, 1=>0 */
  165867. inptr += 2;
  165868. }
  165869. }
  165870. }
  165871. /*
  165872. * Downsample pixel values of a single component.
  165873. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  165874. * without smoothing.
  165875. */
  165876. METHODDEF(void)
  165877. h2v2_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  165878. JSAMPARRAY input_data, JSAMPARRAY output_data)
  165879. {
  165880. int inrow, outrow;
  165881. JDIMENSION outcol;
  165882. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  165883. register JSAMPROW inptr0, inptr1, outptr;
  165884. register int bias;
  165885. /* Expand input data enough to let all the output samples be generated
  165886. * by the standard loop. Special-casing padded output would be more
  165887. * efficient.
  165888. */
  165889. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  165890. cinfo->image_width, output_cols * 2);
  165891. inrow = 0;
  165892. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  165893. outptr = output_data[outrow];
  165894. inptr0 = input_data[inrow];
  165895. inptr1 = input_data[inrow+1];
  165896. bias = 1; /* bias = 1,2,1,2,... for successive samples */
  165897. for (outcol = 0; outcol < output_cols; outcol++) {
  165898. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  165899. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1])
  165900. + bias) >> 2);
  165901. bias ^= 3; /* 1=>2, 2=>1 */
  165902. inptr0 += 2; inptr1 += 2;
  165903. }
  165904. inrow += 2;
  165905. }
  165906. }
  165907. #ifdef INPUT_SMOOTHING_SUPPORTED
  165908. /*
  165909. * Downsample pixel values of a single component.
  165910. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  165911. * with smoothing. One row of context is required.
  165912. */
  165913. METHODDEF(void)
  165914. h2v2_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  165915. JSAMPARRAY input_data, JSAMPARRAY output_data)
  165916. {
  165917. int inrow, outrow;
  165918. JDIMENSION colctr;
  165919. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  165920. register JSAMPROW inptr0, inptr1, above_ptr, below_ptr, outptr;
  165921. INT32 membersum, neighsum, memberscale, neighscale;
  165922. /* Expand input data enough to let all the output samples be generated
  165923. * by the standard loop. Special-casing padded output would be more
  165924. * efficient.
  165925. */
  165926. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  165927. cinfo->image_width, output_cols * 2);
  165928. /* We don't bother to form the individual "smoothed" input pixel values;
  165929. * we can directly compute the output which is the average of the four
  165930. * smoothed values. Each of the four member pixels contributes a fraction
  165931. * (1-8*SF) to its own smoothed image and a fraction SF to each of the three
  165932. * other smoothed pixels, therefore a total fraction (1-5*SF)/4 to the final
  165933. * output. The four corner-adjacent neighbor pixels contribute a fraction
  165934. * SF to just one smoothed pixel, or SF/4 to the final output; while the
  165935. * eight edge-adjacent neighbors contribute SF to each of two smoothed
  165936. * pixels, or SF/2 overall. In order to use integer arithmetic, these
  165937. * factors are scaled by 2^16 = 65536.
  165938. * Also recall that SF = smoothing_factor / 1024.
  165939. */
  165940. memberscale = 16384 - cinfo->smoothing_factor * 80; /* scaled (1-5*SF)/4 */
  165941. neighscale = cinfo->smoothing_factor * 16; /* scaled SF/4 */
  165942. inrow = 0;
  165943. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  165944. outptr = output_data[outrow];
  165945. inptr0 = input_data[inrow];
  165946. inptr1 = input_data[inrow+1];
  165947. above_ptr = input_data[inrow-1];
  165948. below_ptr = input_data[inrow+2];
  165949. /* Special case for first column: pretend column -1 is same as column 0 */
  165950. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  165951. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  165952. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  165953. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  165954. GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[2]) +
  165955. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[2]);
  165956. neighsum += neighsum;
  165957. neighsum += GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[2]) +
  165958. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[2]);
  165959. membersum = membersum * memberscale + neighsum * neighscale;
  165960. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  165961. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  165962. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  165963. /* sum of pixels directly mapped to this output element */
  165964. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  165965. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  165966. /* sum of edge-neighbor pixels */
  165967. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  165968. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  165969. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[2]) +
  165970. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[2]);
  165971. /* The edge-neighbors count twice as much as corner-neighbors */
  165972. neighsum += neighsum;
  165973. /* Add in the corner-neighbors */
  165974. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[2]) +
  165975. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[2]);
  165976. /* form final output scaled up by 2^16 */
  165977. membersum = membersum * memberscale + neighsum * neighscale;
  165978. /* round, descale and output it */
  165979. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  165980. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  165981. }
  165982. /* Special case for last column */
  165983. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  165984. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  165985. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  165986. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  165987. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[1]) +
  165988. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[1]);
  165989. neighsum += neighsum;
  165990. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[1]) +
  165991. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[1]);
  165992. membersum = membersum * memberscale + neighsum * neighscale;
  165993. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  165994. inrow += 2;
  165995. }
  165996. }
  165997. /*
  165998. * Downsample pixel values of a single component.
  165999. * This version handles the special case of a full-size component,
  166000. * with smoothing. One row of context is required.
  166001. */
  166002. METHODDEF(void)
  166003. fullsize_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info *compptr,
  166004. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166005. {
  166006. int outrow;
  166007. JDIMENSION colctr;
  166008. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166009. register JSAMPROW inptr, above_ptr, below_ptr, outptr;
  166010. INT32 membersum, neighsum, memberscale, neighscale;
  166011. int colsum, lastcolsum, nextcolsum;
  166012. /* Expand input data enough to let all the output samples be generated
  166013. * by the standard loop. Special-casing padded output would be more
  166014. * efficient.
  166015. */
  166016. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  166017. cinfo->image_width, output_cols);
  166018. /* Each of the eight neighbor pixels contributes a fraction SF to the
  166019. * smoothed pixel, while the main pixel contributes (1-8*SF). In order
  166020. * to use integer arithmetic, these factors are multiplied by 2^16 = 65536.
  166021. * Also recall that SF = smoothing_factor / 1024.
  166022. */
  166023. memberscale = 65536L - cinfo->smoothing_factor * 512L; /* scaled 1-8*SF */
  166024. neighscale = cinfo->smoothing_factor * 64; /* scaled SF */
  166025. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166026. outptr = output_data[outrow];
  166027. inptr = input_data[outrow];
  166028. above_ptr = input_data[outrow-1];
  166029. below_ptr = input_data[outrow+1];
  166030. /* Special case for first column */
  166031. colsum = GETJSAMPLE(*above_ptr++) + GETJSAMPLE(*below_ptr++) +
  166032. GETJSAMPLE(*inptr);
  166033. membersum = GETJSAMPLE(*inptr++);
  166034. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  166035. GETJSAMPLE(*inptr);
  166036. neighsum = colsum + (colsum - membersum) + nextcolsum;
  166037. membersum = membersum * memberscale + neighsum * neighscale;
  166038. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  166039. lastcolsum = colsum; colsum = nextcolsum;
  166040. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  166041. membersum = GETJSAMPLE(*inptr++);
  166042. above_ptr++; below_ptr++;
  166043. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  166044. GETJSAMPLE(*inptr);
  166045. neighsum = lastcolsum + (colsum - membersum) + nextcolsum;
  166046. membersum = membersum * memberscale + neighsum * neighscale;
  166047. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  166048. lastcolsum = colsum; colsum = nextcolsum;
  166049. }
  166050. /* Special case for last column */
  166051. membersum = GETJSAMPLE(*inptr);
  166052. neighsum = lastcolsum + (colsum - membersum) + colsum;
  166053. membersum = membersum * memberscale + neighsum * neighscale;
  166054. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  166055. }
  166056. }
  166057. #endif /* INPUT_SMOOTHING_SUPPORTED */
  166058. /*
  166059. * Module initialization routine for downsampling.
  166060. * Note that we must select a routine for each component.
  166061. */
  166062. GLOBAL(void)
  166063. jinit_downsampler (j_compress_ptr cinfo)
  166064. {
  166065. my_downsample_ptr downsample;
  166066. int ci;
  166067. jpeg_component_info * compptr;
  166068. boolean smoothok = TRUE;
  166069. downsample = (my_downsample_ptr)
  166070. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166071. SIZEOF(my_downsampler));
  166072. cinfo->downsample = (struct jpeg_downsampler *) downsample;
  166073. downsample->pub.start_pass = start_pass_downsample;
  166074. downsample->pub.downsample = sep_downsample;
  166075. downsample->pub.need_context_rows = FALSE;
  166076. if (cinfo->CCIR601_sampling)
  166077. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  166078. /* Verify we can handle the sampling factors, and set up method pointers */
  166079. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166080. ci++, compptr++) {
  166081. if (compptr->h_samp_factor == cinfo->max_h_samp_factor &&
  166082. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  166083. #ifdef INPUT_SMOOTHING_SUPPORTED
  166084. if (cinfo->smoothing_factor) {
  166085. downsample->methods[ci] = fullsize_smooth_downsample;
  166086. downsample->pub.need_context_rows = TRUE;
  166087. } else
  166088. #endif
  166089. downsample->methods[ci] = fullsize_downsample;
  166090. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  166091. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  166092. smoothok = FALSE;
  166093. downsample->methods[ci] = h2v1_downsample;
  166094. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  166095. compptr->v_samp_factor * 2 == cinfo->max_v_samp_factor) {
  166096. #ifdef INPUT_SMOOTHING_SUPPORTED
  166097. if (cinfo->smoothing_factor) {
  166098. downsample->methods[ci] = h2v2_smooth_downsample;
  166099. downsample->pub.need_context_rows = TRUE;
  166100. } else
  166101. #endif
  166102. downsample->methods[ci] = h2v2_downsample;
  166103. } else if ((cinfo->max_h_samp_factor % compptr->h_samp_factor) == 0 &&
  166104. (cinfo->max_v_samp_factor % compptr->v_samp_factor) == 0) {
  166105. smoothok = FALSE;
  166106. downsample->methods[ci] = int_downsample;
  166107. } else
  166108. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  166109. }
  166110. #ifdef INPUT_SMOOTHING_SUPPORTED
  166111. if (cinfo->smoothing_factor && !smoothok)
  166112. TRACEMS(cinfo, 0, JTRC_SMOOTH_NOTIMPL);
  166113. #endif
  166114. }
  166115. /*** End of inlined file: jcsample.c ***/
  166116. /*** Start of inlined file: jctrans.c ***/
  166117. #define JPEG_INTERNALS
  166118. /* Forward declarations */
  166119. LOCAL(void) transencode_master_selection
  166120. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  166121. LOCAL(void) transencode_coef_controller
  166122. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  166123. /*
  166124. * Compression initialization for writing raw-coefficient data.
  166125. * Before calling this, all parameters and a data destination must be set up.
  166126. * Call jpeg_finish_compress() to actually write the data.
  166127. *
  166128. * The number of passed virtual arrays must match cinfo->num_components.
  166129. * Note that the virtual arrays need not be filled or even realized at
  166130. * the time write_coefficients is called; indeed, if the virtual arrays
  166131. * were requested from this compression object's memory manager, they
  166132. * typically will be realized during this routine and filled afterwards.
  166133. */
  166134. GLOBAL(void)
  166135. jpeg_write_coefficients (j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays)
  166136. {
  166137. if (cinfo->global_state != CSTATE_START)
  166138. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  166139. /* Mark all tables to be written */
  166140. jpeg_suppress_tables(cinfo, FALSE);
  166141. /* (Re)initialize error mgr and destination modules */
  166142. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  166143. (*cinfo->dest->init_destination) (cinfo);
  166144. /* Perform master selection of active modules */
  166145. transencode_master_selection(cinfo, coef_arrays);
  166146. /* Wait for jpeg_finish_compress() call */
  166147. cinfo->next_scanline = 0; /* so jpeg_write_marker works */
  166148. cinfo->global_state = CSTATE_WRCOEFS;
  166149. }
  166150. /*
  166151. * Initialize the compression object with default parameters,
  166152. * then copy from the source object all parameters needed for lossless
  166153. * transcoding. Parameters that can be varied without loss (such as
  166154. * scan script and Huffman optimization) are left in their default states.
  166155. */
  166156. GLOBAL(void)
  166157. jpeg_copy_critical_parameters (j_decompress_ptr srcinfo,
  166158. j_compress_ptr dstinfo)
  166159. {
  166160. JQUANT_TBL ** qtblptr;
  166161. jpeg_component_info *incomp, *outcomp;
  166162. JQUANT_TBL *c_quant, *slot_quant;
  166163. int tblno, ci, coefi;
  166164. /* Safety check to ensure start_compress not called yet. */
  166165. if (dstinfo->global_state != CSTATE_START)
  166166. ERREXIT1(dstinfo, JERR_BAD_STATE, dstinfo->global_state);
  166167. /* Copy fundamental image dimensions */
  166168. dstinfo->image_width = srcinfo->image_width;
  166169. dstinfo->image_height = srcinfo->image_height;
  166170. dstinfo->input_components = srcinfo->num_components;
  166171. dstinfo->in_color_space = srcinfo->jpeg_color_space;
  166172. /* Initialize all parameters to default values */
  166173. jpeg_set_defaults(dstinfo);
  166174. /* jpeg_set_defaults may choose wrong colorspace, eg YCbCr if input is RGB.
  166175. * Fix it to get the right header markers for the image colorspace.
  166176. */
  166177. jpeg_set_colorspace(dstinfo, srcinfo->jpeg_color_space);
  166178. dstinfo->data_precision = srcinfo->data_precision;
  166179. dstinfo->CCIR601_sampling = srcinfo->CCIR601_sampling;
  166180. /* Copy the source's quantization tables. */
  166181. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  166182. if (srcinfo->quant_tbl_ptrs[tblno] != NULL) {
  166183. qtblptr = & dstinfo->quant_tbl_ptrs[tblno];
  166184. if (*qtblptr == NULL)
  166185. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) dstinfo);
  166186. MEMCOPY((*qtblptr)->quantval,
  166187. srcinfo->quant_tbl_ptrs[tblno]->quantval,
  166188. SIZEOF((*qtblptr)->quantval));
  166189. (*qtblptr)->sent_table = FALSE;
  166190. }
  166191. }
  166192. /* Copy the source's per-component info.
  166193. * Note we assume jpeg_set_defaults has allocated the dest comp_info array.
  166194. */
  166195. dstinfo->num_components = srcinfo->num_components;
  166196. if (dstinfo->num_components < 1 || dstinfo->num_components > MAX_COMPONENTS)
  166197. ERREXIT2(dstinfo, JERR_COMPONENT_COUNT, dstinfo->num_components,
  166198. MAX_COMPONENTS);
  166199. for (ci = 0, incomp = srcinfo->comp_info, outcomp = dstinfo->comp_info;
  166200. ci < dstinfo->num_components; ci++, incomp++, outcomp++) {
  166201. outcomp->component_id = incomp->component_id;
  166202. outcomp->h_samp_factor = incomp->h_samp_factor;
  166203. outcomp->v_samp_factor = incomp->v_samp_factor;
  166204. outcomp->quant_tbl_no = incomp->quant_tbl_no;
  166205. /* Make sure saved quantization table for component matches the qtable
  166206. * slot. If not, the input file re-used this qtable slot.
  166207. * IJG encoder currently cannot duplicate this.
  166208. */
  166209. tblno = outcomp->quant_tbl_no;
  166210. if (tblno < 0 || tblno >= NUM_QUANT_TBLS ||
  166211. srcinfo->quant_tbl_ptrs[tblno] == NULL)
  166212. ERREXIT1(dstinfo, JERR_NO_QUANT_TABLE, tblno);
  166213. slot_quant = srcinfo->quant_tbl_ptrs[tblno];
  166214. c_quant = incomp->quant_table;
  166215. if (c_quant != NULL) {
  166216. for (coefi = 0; coefi < DCTSIZE2; coefi++) {
  166217. if (c_quant->quantval[coefi] != slot_quant->quantval[coefi])
  166218. ERREXIT1(dstinfo, JERR_MISMATCHED_QUANT_TABLE, tblno);
  166219. }
  166220. }
  166221. /* Note: we do not copy the source's Huffman table assignments;
  166222. * instead we rely on jpeg_set_colorspace to have made a suitable choice.
  166223. */
  166224. }
  166225. /* Also copy JFIF version and resolution information, if available.
  166226. * Strictly speaking this isn't "critical" info, but it's nearly
  166227. * always appropriate to copy it if available. In particular,
  166228. * if the application chooses to copy JFIF 1.02 extension markers from
  166229. * the source file, we need to copy the version to make sure we don't
  166230. * emit a file that has 1.02 extensions but a claimed version of 1.01.
  166231. * We will *not*, however, copy version info from mislabeled "2.01" files.
  166232. */
  166233. if (srcinfo->saw_JFIF_marker) {
  166234. if (srcinfo->JFIF_major_version == 1) {
  166235. dstinfo->JFIF_major_version = srcinfo->JFIF_major_version;
  166236. dstinfo->JFIF_minor_version = srcinfo->JFIF_minor_version;
  166237. }
  166238. dstinfo->density_unit = srcinfo->density_unit;
  166239. dstinfo->X_density = srcinfo->X_density;
  166240. dstinfo->Y_density = srcinfo->Y_density;
  166241. }
  166242. }
  166243. /*
  166244. * Master selection of compression modules for transcoding.
  166245. * This substitutes for jcinit.c's initialization of the full compressor.
  166246. */
  166247. LOCAL(void)
  166248. transencode_master_selection (j_compress_ptr cinfo,
  166249. jvirt_barray_ptr * coef_arrays)
  166250. {
  166251. /* Although we don't actually use input_components for transcoding,
  166252. * jcmaster.c's initial_setup will complain if input_components is 0.
  166253. */
  166254. cinfo->input_components = 1;
  166255. /* Initialize master control (includes parameter checking/processing) */
  166256. jinit_c_master_control(cinfo, TRUE /* transcode only */);
  166257. /* Entropy encoding: either Huffman or arithmetic coding. */
  166258. if (cinfo->arith_code) {
  166259. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  166260. } else {
  166261. if (cinfo->progressive_mode) {
  166262. #ifdef C_PROGRESSIVE_SUPPORTED
  166263. jinit_phuff_encoder(cinfo);
  166264. #else
  166265. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166266. #endif
  166267. } else
  166268. jinit_huff_encoder(cinfo);
  166269. }
  166270. /* We need a special coefficient buffer controller. */
  166271. transencode_coef_controller(cinfo, coef_arrays);
  166272. jinit_marker_writer(cinfo);
  166273. /* We can now tell the memory manager to allocate virtual arrays. */
  166274. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  166275. /* Write the datastream header (SOI, JFIF) immediately.
  166276. * Frame and scan headers are postponed till later.
  166277. * This lets application insert special markers after the SOI.
  166278. */
  166279. (*cinfo->marker->write_file_header) (cinfo);
  166280. }
  166281. /*
  166282. * The rest of this file is a special implementation of the coefficient
  166283. * buffer controller. This is similar to jccoefct.c, but it handles only
  166284. * output from presupplied virtual arrays. Furthermore, we generate any
  166285. * dummy padding blocks on-the-fly rather than expecting them to be present
  166286. * in the arrays.
  166287. */
  166288. /* Private buffer controller object */
  166289. typedef struct {
  166290. struct jpeg_c_coef_controller pub; /* public fields */
  166291. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  166292. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  166293. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  166294. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  166295. /* Virtual block array for each component. */
  166296. jvirt_barray_ptr * whole_image;
  166297. /* Workspace for constructing dummy blocks at right/bottom edges. */
  166298. JBLOCKROW dummy_buffer[C_MAX_BLOCKS_IN_MCU];
  166299. } my_coef_controller2;
  166300. typedef my_coef_controller2 * my_coef_ptr2;
  166301. LOCAL(void)
  166302. start_iMCU_row2 (j_compress_ptr cinfo)
  166303. /* Reset within-iMCU-row counters for a new row */
  166304. {
  166305. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  166306. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  166307. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  166308. * But at the bottom of the image, process only what's left.
  166309. */
  166310. if (cinfo->comps_in_scan > 1) {
  166311. coef->MCU_rows_per_iMCU_row = 1;
  166312. } else {
  166313. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  166314. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  166315. else
  166316. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  166317. }
  166318. coef->mcu_ctr = 0;
  166319. coef->MCU_vert_offset = 0;
  166320. }
  166321. /*
  166322. * Initialize for a processing pass.
  166323. */
  166324. METHODDEF(void)
  166325. start_pass_coef2 (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  166326. {
  166327. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  166328. if (pass_mode != JBUF_CRANK_DEST)
  166329. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166330. coef->iMCU_row_num = 0;
  166331. start_iMCU_row2(cinfo);
  166332. }
  166333. /*
  166334. * Process some data.
  166335. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  166336. * per call, ie, v_samp_factor block rows for each component in the scan.
  166337. * The data is obtained from the virtual arrays and fed to the entropy coder.
  166338. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  166339. *
  166340. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  166341. */
  166342. METHODDEF(boolean)
  166343. compress_output2 (j_compress_ptr cinfo, JSAMPIMAGE)
  166344. {
  166345. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  166346. JDIMENSION MCU_col_num; /* index of current MCU within row */
  166347. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  166348. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  166349. int blkn, ci, xindex, yindex, yoffset, blockcnt;
  166350. JDIMENSION start_col;
  166351. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  166352. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  166353. JBLOCKROW buffer_ptr;
  166354. jpeg_component_info *compptr;
  166355. /* Align the virtual buffers for the components used in this scan. */
  166356. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  166357. compptr = cinfo->cur_comp_info[ci];
  166358. buffer[ci] = (*cinfo->mem->access_virt_barray)
  166359. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  166360. coef->iMCU_row_num * compptr->v_samp_factor,
  166361. (JDIMENSION) compptr->v_samp_factor, FALSE);
  166362. }
  166363. /* Loop to process one whole iMCU row */
  166364. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  166365. yoffset++) {
  166366. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  166367. MCU_col_num++) {
  166368. /* Construct list of pointers to DCT blocks belonging to this MCU */
  166369. blkn = 0; /* index of current DCT block within MCU */
  166370. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  166371. compptr = cinfo->cur_comp_info[ci];
  166372. start_col = MCU_col_num * compptr->MCU_width;
  166373. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  166374. : compptr->last_col_width;
  166375. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  166376. if (coef->iMCU_row_num < last_iMCU_row ||
  166377. yindex+yoffset < compptr->last_row_height) {
  166378. /* Fill in pointers to real blocks in this row */
  166379. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  166380. for (xindex = 0; xindex < blockcnt; xindex++)
  166381. MCU_buffer[blkn++] = buffer_ptr++;
  166382. } else {
  166383. /* At bottom of image, need a whole row of dummy blocks */
  166384. xindex = 0;
  166385. }
  166386. /* Fill in any dummy blocks needed in this row.
  166387. * Dummy blocks are filled in the same way as in jccoefct.c:
  166388. * all zeroes in the AC entries, DC entries equal to previous
  166389. * block's DC value. The init routine has already zeroed the
  166390. * AC entries, so we need only set the DC entries correctly.
  166391. */
  166392. for (; xindex < compptr->MCU_width; xindex++) {
  166393. MCU_buffer[blkn] = coef->dummy_buffer[blkn];
  166394. MCU_buffer[blkn][0][0] = MCU_buffer[blkn-1][0][0];
  166395. blkn++;
  166396. }
  166397. }
  166398. }
  166399. /* Try to write the MCU. */
  166400. if (! (*cinfo->entropy->encode_mcu) (cinfo, MCU_buffer)) {
  166401. /* Suspension forced; update state counters and exit */
  166402. coef->MCU_vert_offset = yoffset;
  166403. coef->mcu_ctr = MCU_col_num;
  166404. return FALSE;
  166405. }
  166406. }
  166407. /* Completed an MCU row, but perhaps not an iMCU row */
  166408. coef->mcu_ctr = 0;
  166409. }
  166410. /* Completed the iMCU row, advance counters for next one */
  166411. coef->iMCU_row_num++;
  166412. start_iMCU_row2(cinfo);
  166413. return TRUE;
  166414. }
  166415. /*
  166416. * Initialize coefficient buffer controller.
  166417. *
  166418. * Each passed coefficient array must be the right size for that
  166419. * coefficient: width_in_blocks wide and height_in_blocks high,
  166420. * with unitheight at least v_samp_factor.
  166421. */
  166422. LOCAL(void)
  166423. transencode_coef_controller (j_compress_ptr cinfo,
  166424. jvirt_barray_ptr * coef_arrays)
  166425. {
  166426. my_coef_ptr2 coef;
  166427. JBLOCKROW buffer;
  166428. int i;
  166429. coef = (my_coef_ptr2)
  166430. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166431. SIZEOF(my_coef_controller2));
  166432. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  166433. coef->pub.start_pass = start_pass_coef2;
  166434. coef->pub.compress_data = compress_output2;
  166435. /* Save pointer to virtual arrays */
  166436. coef->whole_image = coef_arrays;
  166437. /* Allocate and pre-zero space for dummy DCT blocks. */
  166438. buffer = (JBLOCKROW)
  166439. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166440. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  166441. jzero_far((void FAR *) buffer, C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  166442. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  166443. coef->dummy_buffer[i] = buffer + i;
  166444. }
  166445. }
  166446. /*** End of inlined file: jctrans.c ***/
  166447. /*** Start of inlined file: jdapistd.c ***/
  166448. #define JPEG_INTERNALS
  166449. /* Forward declarations */
  166450. LOCAL(boolean) output_pass_setup JPP((j_decompress_ptr cinfo));
  166451. /*
  166452. * Decompression initialization.
  166453. * jpeg_read_header must be completed before calling this.
  166454. *
  166455. * If a multipass operating mode was selected, this will do all but the
  166456. * last pass, and thus may take a great deal of time.
  166457. *
  166458. * Returns FALSE if suspended. The return value need be inspected only if
  166459. * a suspending data source is used.
  166460. */
  166461. GLOBAL(boolean)
  166462. jpeg_start_decompress (j_decompress_ptr cinfo)
  166463. {
  166464. if (cinfo->global_state == DSTATE_READY) {
  166465. /* First call: initialize master control, select active modules */
  166466. jinit_master_decompress(cinfo);
  166467. if (cinfo->buffered_image) {
  166468. /* No more work here; expecting jpeg_start_output next */
  166469. cinfo->global_state = DSTATE_BUFIMAGE;
  166470. return TRUE;
  166471. }
  166472. cinfo->global_state = DSTATE_PRELOAD;
  166473. }
  166474. if (cinfo->global_state == DSTATE_PRELOAD) {
  166475. /* If file has multiple scans, absorb them all into the coef buffer */
  166476. if (cinfo->inputctl->has_multiple_scans) {
  166477. #ifdef D_MULTISCAN_FILES_SUPPORTED
  166478. for (;;) {
  166479. int retcode;
  166480. /* Call progress monitor hook if present */
  166481. if (cinfo->progress != NULL)
  166482. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  166483. /* Absorb some more input */
  166484. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  166485. if (retcode == JPEG_SUSPENDED)
  166486. return FALSE;
  166487. if (retcode == JPEG_REACHED_EOI)
  166488. break;
  166489. /* Advance progress counter if appropriate */
  166490. if (cinfo->progress != NULL &&
  166491. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  166492. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  166493. /* jdmaster underestimated number of scans; ratchet up one scan */
  166494. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  166495. }
  166496. }
  166497. }
  166498. #else
  166499. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166500. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  166501. }
  166502. cinfo->output_scan_number = cinfo->input_scan_number;
  166503. } else if (cinfo->global_state != DSTATE_PRESCAN)
  166504. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  166505. /* Perform any dummy output passes, and set up for the final pass */
  166506. return output_pass_setup(cinfo);
  166507. }
  166508. /*
  166509. * Set up for an output pass, and perform any dummy pass(es) needed.
  166510. * Common subroutine for jpeg_start_decompress and jpeg_start_output.
  166511. * Entry: global_state = DSTATE_PRESCAN only if previously suspended.
  166512. * Exit: If done, returns TRUE and sets global_state for proper output mode.
  166513. * If suspended, returns FALSE and sets global_state = DSTATE_PRESCAN.
  166514. */
  166515. LOCAL(boolean)
  166516. output_pass_setup (j_decompress_ptr cinfo)
  166517. {
  166518. if (cinfo->global_state != DSTATE_PRESCAN) {
  166519. /* First call: do pass setup */
  166520. (*cinfo->master->prepare_for_output_pass) (cinfo);
  166521. cinfo->output_scanline = 0;
  166522. cinfo->global_state = DSTATE_PRESCAN;
  166523. }
  166524. /* Loop over any required dummy passes */
  166525. while (cinfo->master->is_dummy_pass) {
  166526. #ifdef QUANT_2PASS_SUPPORTED
  166527. /* Crank through the dummy pass */
  166528. while (cinfo->output_scanline < cinfo->output_height) {
  166529. JDIMENSION last_scanline;
  166530. /* Call progress monitor hook if present */
  166531. if (cinfo->progress != NULL) {
  166532. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  166533. cinfo->progress->pass_limit = (long) cinfo->output_height;
  166534. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  166535. }
  166536. /* Process some data */
  166537. last_scanline = cinfo->output_scanline;
  166538. (*cinfo->main->process_data) (cinfo, (JSAMPARRAY) NULL,
  166539. &cinfo->output_scanline, (JDIMENSION) 0);
  166540. if (cinfo->output_scanline == last_scanline)
  166541. return FALSE; /* No progress made, must suspend */
  166542. }
  166543. /* Finish up dummy pass, and set up for another one */
  166544. (*cinfo->master->finish_output_pass) (cinfo);
  166545. (*cinfo->master->prepare_for_output_pass) (cinfo);
  166546. cinfo->output_scanline = 0;
  166547. #else
  166548. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166549. #endif /* QUANT_2PASS_SUPPORTED */
  166550. }
  166551. /* Ready for application to drive output pass through
  166552. * jpeg_read_scanlines or jpeg_read_raw_data.
  166553. */
  166554. cinfo->global_state = cinfo->raw_data_out ? DSTATE_RAW_OK : DSTATE_SCANNING;
  166555. return TRUE;
  166556. }
  166557. /*
  166558. * Read some scanlines of data from the JPEG decompressor.
  166559. *
  166560. * The return value will be the number of lines actually read.
  166561. * This may be less than the number requested in several cases,
  166562. * including bottom of image, data source suspension, and operating
  166563. * modes that emit multiple scanlines at a time.
  166564. *
  166565. * Note: we warn about excess calls to jpeg_read_scanlines() since
  166566. * this likely signals an application programmer error. However,
  166567. * an oversize buffer (max_lines > scanlines remaining) is not an error.
  166568. */
  166569. GLOBAL(JDIMENSION)
  166570. jpeg_read_scanlines (j_decompress_ptr cinfo, JSAMPARRAY scanlines,
  166571. JDIMENSION max_lines)
  166572. {
  166573. JDIMENSION row_ctr;
  166574. if (cinfo->global_state != DSTATE_SCANNING)
  166575. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  166576. if (cinfo->output_scanline >= cinfo->output_height) {
  166577. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  166578. return 0;
  166579. }
  166580. /* Call progress monitor hook if present */
  166581. if (cinfo->progress != NULL) {
  166582. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  166583. cinfo->progress->pass_limit = (long) cinfo->output_height;
  166584. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  166585. }
  166586. /* Process some data */
  166587. row_ctr = 0;
  166588. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, max_lines);
  166589. cinfo->output_scanline += row_ctr;
  166590. return row_ctr;
  166591. }
  166592. /*
  166593. * Alternate entry point to read raw data.
  166594. * Processes exactly one iMCU row per call, unless suspended.
  166595. */
  166596. GLOBAL(JDIMENSION)
  166597. jpeg_read_raw_data (j_decompress_ptr cinfo, JSAMPIMAGE data,
  166598. JDIMENSION max_lines)
  166599. {
  166600. JDIMENSION lines_per_iMCU_row;
  166601. if (cinfo->global_state != DSTATE_RAW_OK)
  166602. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  166603. if (cinfo->output_scanline >= cinfo->output_height) {
  166604. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  166605. return 0;
  166606. }
  166607. /* Call progress monitor hook if present */
  166608. if (cinfo->progress != NULL) {
  166609. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  166610. cinfo->progress->pass_limit = (long) cinfo->output_height;
  166611. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  166612. }
  166613. /* Verify that at least one iMCU row can be returned. */
  166614. lines_per_iMCU_row = cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size;
  166615. if (max_lines < lines_per_iMCU_row)
  166616. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  166617. /* Decompress directly into user's buffer. */
  166618. if (! (*cinfo->coef->decompress_data) (cinfo, data))
  166619. return 0; /* suspension forced, can do nothing more */
  166620. /* OK, we processed one iMCU row. */
  166621. cinfo->output_scanline += lines_per_iMCU_row;
  166622. return lines_per_iMCU_row;
  166623. }
  166624. /* Additional entry points for buffered-image mode. */
  166625. #ifdef D_MULTISCAN_FILES_SUPPORTED
  166626. /*
  166627. * Initialize for an output pass in buffered-image mode.
  166628. */
  166629. GLOBAL(boolean)
  166630. jpeg_start_output (j_decompress_ptr cinfo, int scan_number)
  166631. {
  166632. if (cinfo->global_state != DSTATE_BUFIMAGE &&
  166633. cinfo->global_state != DSTATE_PRESCAN)
  166634. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  166635. /* Limit scan number to valid range */
  166636. if (scan_number <= 0)
  166637. scan_number = 1;
  166638. if (cinfo->inputctl->eoi_reached &&
  166639. scan_number > cinfo->input_scan_number)
  166640. scan_number = cinfo->input_scan_number;
  166641. cinfo->output_scan_number = scan_number;
  166642. /* Perform any dummy output passes, and set up for the real pass */
  166643. return output_pass_setup(cinfo);
  166644. }
  166645. /*
  166646. * Finish up after an output pass in buffered-image mode.
  166647. *
  166648. * Returns FALSE if suspended. The return value need be inspected only if
  166649. * a suspending data source is used.
  166650. */
  166651. GLOBAL(boolean)
  166652. jpeg_finish_output (j_decompress_ptr cinfo)
  166653. {
  166654. if ((cinfo->global_state == DSTATE_SCANNING ||
  166655. cinfo->global_state == DSTATE_RAW_OK) && cinfo->buffered_image) {
  166656. /* Terminate this pass. */
  166657. /* We do not require the whole pass to have been completed. */
  166658. (*cinfo->master->finish_output_pass) (cinfo);
  166659. cinfo->global_state = DSTATE_BUFPOST;
  166660. } else if (cinfo->global_state != DSTATE_BUFPOST) {
  166661. /* BUFPOST = repeat call after a suspension, anything else is error */
  166662. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  166663. }
  166664. /* Read markers looking for SOS or EOI */
  166665. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  166666. ! cinfo->inputctl->eoi_reached) {
  166667. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  166668. return FALSE; /* Suspend, come back later */
  166669. }
  166670. cinfo->global_state = DSTATE_BUFIMAGE;
  166671. return TRUE;
  166672. }
  166673. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  166674. /*** End of inlined file: jdapistd.c ***/
  166675. /*** Start of inlined file: jdapimin.c ***/
  166676. #define JPEG_INTERNALS
  166677. /*
  166678. * Initialization of a JPEG decompression object.
  166679. * The error manager must already be set up (in case memory manager fails).
  166680. */
  166681. GLOBAL(void)
  166682. jpeg_CreateDecompress (j_decompress_ptr cinfo, int version, size_t structsize)
  166683. {
  166684. int i;
  166685. /* Guard against version mismatches between library and caller. */
  166686. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  166687. if (version != JPEG_LIB_VERSION)
  166688. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  166689. if (structsize != SIZEOF(struct jpeg_decompress_struct))
  166690. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  166691. (int) SIZEOF(struct jpeg_decompress_struct), (int) structsize);
  166692. /* For debugging purposes, we zero the whole master structure.
  166693. * But the application has already set the err pointer, and may have set
  166694. * client_data, so we have to save and restore those fields.
  166695. * Note: if application hasn't set client_data, tools like Purify may
  166696. * complain here.
  166697. */
  166698. {
  166699. struct jpeg_error_mgr * err = cinfo->err;
  166700. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  166701. MEMZERO(cinfo, SIZEOF(struct jpeg_decompress_struct));
  166702. cinfo->err = err;
  166703. cinfo->client_data = client_data;
  166704. }
  166705. cinfo->is_decompressor = TRUE;
  166706. /* Initialize a memory manager instance for this object */
  166707. jinit_memory_mgr((j_common_ptr) cinfo);
  166708. /* Zero out pointers to permanent structures. */
  166709. cinfo->progress = NULL;
  166710. cinfo->src = NULL;
  166711. for (i = 0; i < NUM_QUANT_TBLS; i++)
  166712. cinfo->quant_tbl_ptrs[i] = NULL;
  166713. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  166714. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  166715. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  166716. }
  166717. /* Initialize marker processor so application can override methods
  166718. * for COM, APPn markers before calling jpeg_read_header.
  166719. */
  166720. cinfo->marker_list = NULL;
  166721. jinit_marker_reader(cinfo);
  166722. /* And initialize the overall input controller. */
  166723. jinit_input_controller(cinfo);
  166724. /* OK, I'm ready */
  166725. cinfo->global_state = DSTATE_START;
  166726. }
  166727. /*
  166728. * Destruction of a JPEG decompression object
  166729. */
  166730. GLOBAL(void)
  166731. jpeg_destroy_decompress (j_decompress_ptr cinfo)
  166732. {
  166733. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  166734. }
  166735. /*
  166736. * Abort processing of a JPEG decompression operation,
  166737. * but don't destroy the object itself.
  166738. */
  166739. GLOBAL(void)
  166740. jpeg_abort_decompress (j_decompress_ptr cinfo)
  166741. {
  166742. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  166743. }
  166744. /*
  166745. * Set default decompression parameters.
  166746. */
  166747. LOCAL(void)
  166748. default_decompress_parms (j_decompress_ptr cinfo)
  166749. {
  166750. /* Guess the input colorspace, and set output colorspace accordingly. */
  166751. /* (Wish JPEG committee had provided a real way to specify this...) */
  166752. /* Note application may override our guesses. */
  166753. switch (cinfo->num_components) {
  166754. case 1:
  166755. cinfo->jpeg_color_space = JCS_GRAYSCALE;
  166756. cinfo->out_color_space = JCS_GRAYSCALE;
  166757. break;
  166758. case 3:
  166759. if (cinfo->saw_JFIF_marker) {
  166760. cinfo->jpeg_color_space = JCS_YCbCr; /* JFIF implies YCbCr */
  166761. } else if (cinfo->saw_Adobe_marker) {
  166762. switch (cinfo->Adobe_transform) {
  166763. case 0:
  166764. cinfo->jpeg_color_space = JCS_RGB;
  166765. break;
  166766. case 1:
  166767. cinfo->jpeg_color_space = JCS_YCbCr;
  166768. break;
  166769. default:
  166770. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  166771. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  166772. break;
  166773. }
  166774. } else {
  166775. /* Saw no special markers, try to guess from the component IDs */
  166776. int cid0 = cinfo->comp_info[0].component_id;
  166777. int cid1 = cinfo->comp_info[1].component_id;
  166778. int cid2 = cinfo->comp_info[2].component_id;
  166779. if (cid0 == 1 && cid1 == 2 && cid2 == 3)
  166780. cinfo->jpeg_color_space = JCS_YCbCr; /* assume JFIF w/out marker */
  166781. else if (cid0 == 82 && cid1 == 71 && cid2 == 66)
  166782. cinfo->jpeg_color_space = JCS_RGB; /* ASCII 'R', 'G', 'B' */
  166783. else {
  166784. TRACEMS3(cinfo, 1, JTRC_UNKNOWN_IDS, cid0, cid1, cid2);
  166785. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  166786. }
  166787. }
  166788. /* Always guess RGB is proper output colorspace. */
  166789. cinfo->out_color_space = JCS_RGB;
  166790. break;
  166791. case 4:
  166792. if (cinfo->saw_Adobe_marker) {
  166793. switch (cinfo->Adobe_transform) {
  166794. case 0:
  166795. cinfo->jpeg_color_space = JCS_CMYK;
  166796. break;
  166797. case 2:
  166798. cinfo->jpeg_color_space = JCS_YCCK;
  166799. break;
  166800. default:
  166801. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  166802. cinfo->jpeg_color_space = JCS_YCCK; /* assume it's YCCK */
  166803. break;
  166804. }
  166805. } else {
  166806. /* No special markers, assume straight CMYK. */
  166807. cinfo->jpeg_color_space = JCS_CMYK;
  166808. }
  166809. cinfo->out_color_space = JCS_CMYK;
  166810. break;
  166811. default:
  166812. cinfo->jpeg_color_space = JCS_UNKNOWN;
  166813. cinfo->out_color_space = JCS_UNKNOWN;
  166814. break;
  166815. }
  166816. /* Set defaults for other decompression parameters. */
  166817. cinfo->scale_num = 1; /* 1:1 scaling */
  166818. cinfo->scale_denom = 1;
  166819. cinfo->output_gamma = 1.0;
  166820. cinfo->buffered_image = FALSE;
  166821. cinfo->raw_data_out = FALSE;
  166822. cinfo->dct_method = JDCT_DEFAULT;
  166823. cinfo->do_fancy_upsampling = TRUE;
  166824. cinfo->do_block_smoothing = TRUE;
  166825. cinfo->quantize_colors = FALSE;
  166826. /* We set these in case application only sets quantize_colors. */
  166827. cinfo->dither_mode = JDITHER_FS;
  166828. #ifdef QUANT_2PASS_SUPPORTED
  166829. cinfo->two_pass_quantize = TRUE;
  166830. #else
  166831. cinfo->two_pass_quantize = FALSE;
  166832. #endif
  166833. cinfo->desired_number_of_colors = 256;
  166834. cinfo->colormap = NULL;
  166835. /* Initialize for no mode change in buffered-image mode. */
  166836. cinfo->enable_1pass_quant = FALSE;
  166837. cinfo->enable_external_quant = FALSE;
  166838. cinfo->enable_2pass_quant = FALSE;
  166839. }
  166840. /*
  166841. * Decompression startup: read start of JPEG datastream to see what's there.
  166842. * Need only initialize JPEG object and supply a data source before calling.
  166843. *
  166844. * This routine will read as far as the first SOS marker (ie, actual start of
  166845. * compressed data), and will save all tables and parameters in the JPEG
  166846. * object. It will also initialize the decompression parameters to default
  166847. * values, and finally return JPEG_HEADER_OK. On return, the application may
  166848. * adjust the decompression parameters and then call jpeg_start_decompress.
  166849. * (Or, if the application only wanted to determine the image parameters,
  166850. * the data need not be decompressed. In that case, call jpeg_abort or
  166851. * jpeg_destroy to release any temporary space.)
  166852. * If an abbreviated (tables only) datastream is presented, the routine will
  166853. * return JPEG_HEADER_TABLES_ONLY upon reaching EOI. The application may then
  166854. * re-use the JPEG object to read the abbreviated image datastream(s).
  166855. * It is unnecessary (but OK) to call jpeg_abort in this case.
  166856. * The JPEG_SUSPENDED return code only occurs if the data source module
  166857. * requests suspension of the decompressor. In this case the application
  166858. * should load more source data and then re-call jpeg_read_header to resume
  166859. * processing.
  166860. * If a non-suspending data source is used and require_image is TRUE, then the
  166861. * return code need not be inspected since only JPEG_HEADER_OK is possible.
  166862. *
  166863. * This routine is now just a front end to jpeg_consume_input, with some
  166864. * extra error checking.
  166865. */
  166866. GLOBAL(int)
  166867. jpeg_read_header (j_decompress_ptr cinfo, boolean require_image)
  166868. {
  166869. int retcode;
  166870. if (cinfo->global_state != DSTATE_START &&
  166871. cinfo->global_state != DSTATE_INHEADER)
  166872. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  166873. retcode = jpeg_consume_input(cinfo);
  166874. switch (retcode) {
  166875. case JPEG_REACHED_SOS:
  166876. retcode = JPEG_HEADER_OK;
  166877. break;
  166878. case JPEG_REACHED_EOI:
  166879. if (require_image) /* Complain if application wanted an image */
  166880. ERREXIT(cinfo, JERR_NO_IMAGE);
  166881. /* Reset to start state; it would be safer to require the application to
  166882. * call jpeg_abort, but we can't change it now for compatibility reasons.
  166883. * A side effect is to free any temporary memory (there shouldn't be any).
  166884. */
  166885. jpeg_abort((j_common_ptr) cinfo); /* sets state = DSTATE_START */
  166886. retcode = JPEG_HEADER_TABLES_ONLY;
  166887. break;
  166888. case JPEG_SUSPENDED:
  166889. /* no work */
  166890. break;
  166891. }
  166892. return retcode;
  166893. }
  166894. /*
  166895. * Consume data in advance of what the decompressor requires.
  166896. * This can be called at any time once the decompressor object has
  166897. * been created and a data source has been set up.
  166898. *
  166899. * This routine is essentially a state machine that handles a couple
  166900. * of critical state-transition actions, namely initial setup and
  166901. * transition from header scanning to ready-for-start_decompress.
  166902. * All the actual input is done via the input controller's consume_input
  166903. * method.
  166904. */
  166905. GLOBAL(int)
  166906. jpeg_consume_input (j_decompress_ptr cinfo)
  166907. {
  166908. int retcode = JPEG_SUSPENDED;
  166909. /* NB: every possible DSTATE value should be listed in this switch */
  166910. switch (cinfo->global_state) {
  166911. case DSTATE_START:
  166912. /* Start-of-datastream actions: reset appropriate modules */
  166913. (*cinfo->inputctl->reset_input_controller) (cinfo);
  166914. /* Initialize application's data source module */
  166915. (*cinfo->src->init_source) (cinfo);
  166916. cinfo->global_state = DSTATE_INHEADER;
  166917. /*FALLTHROUGH*/
  166918. case DSTATE_INHEADER:
  166919. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  166920. if (retcode == JPEG_REACHED_SOS) { /* Found SOS, prepare to decompress */
  166921. /* Set up default parameters based on header data */
  166922. default_decompress_parms(cinfo);
  166923. /* Set global state: ready for start_decompress */
  166924. cinfo->global_state = DSTATE_READY;
  166925. }
  166926. break;
  166927. case DSTATE_READY:
  166928. /* Can't advance past first SOS until start_decompress is called */
  166929. retcode = JPEG_REACHED_SOS;
  166930. break;
  166931. case DSTATE_PRELOAD:
  166932. case DSTATE_PRESCAN:
  166933. case DSTATE_SCANNING:
  166934. case DSTATE_RAW_OK:
  166935. case DSTATE_BUFIMAGE:
  166936. case DSTATE_BUFPOST:
  166937. case DSTATE_STOPPING:
  166938. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  166939. break;
  166940. default:
  166941. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  166942. }
  166943. return retcode;
  166944. }
  166945. /*
  166946. * Have we finished reading the input file?
  166947. */
  166948. GLOBAL(boolean)
  166949. jpeg_input_complete (j_decompress_ptr cinfo)
  166950. {
  166951. /* Check for valid jpeg object */
  166952. if (cinfo->global_state < DSTATE_START ||
  166953. cinfo->global_state > DSTATE_STOPPING)
  166954. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  166955. return cinfo->inputctl->eoi_reached;
  166956. }
  166957. /*
  166958. * Is there more than one scan?
  166959. */
  166960. GLOBAL(boolean)
  166961. jpeg_has_multiple_scans (j_decompress_ptr cinfo)
  166962. {
  166963. /* Only valid after jpeg_read_header completes */
  166964. if (cinfo->global_state < DSTATE_READY ||
  166965. cinfo->global_state > DSTATE_STOPPING)
  166966. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  166967. return cinfo->inputctl->has_multiple_scans;
  166968. }
  166969. /*
  166970. * Finish JPEG decompression.
  166971. *
  166972. * This will normally just verify the file trailer and release temp storage.
  166973. *
  166974. * Returns FALSE if suspended. The return value need be inspected only if
  166975. * a suspending data source is used.
  166976. */
  166977. GLOBAL(boolean)
  166978. jpeg_finish_decompress (j_decompress_ptr cinfo)
  166979. {
  166980. if ((cinfo->global_state == DSTATE_SCANNING ||
  166981. cinfo->global_state == DSTATE_RAW_OK) && ! cinfo->buffered_image) {
  166982. /* Terminate final pass of non-buffered mode */
  166983. if (cinfo->output_scanline < cinfo->output_height)
  166984. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  166985. (*cinfo->master->finish_output_pass) (cinfo);
  166986. cinfo->global_state = DSTATE_STOPPING;
  166987. } else if (cinfo->global_state == DSTATE_BUFIMAGE) {
  166988. /* Finishing after a buffered-image operation */
  166989. cinfo->global_state = DSTATE_STOPPING;
  166990. } else if (cinfo->global_state != DSTATE_STOPPING) {
  166991. /* STOPPING = repeat call after a suspension, anything else is error */
  166992. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  166993. }
  166994. /* Read until EOI */
  166995. while (! cinfo->inputctl->eoi_reached) {
  166996. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  166997. return FALSE; /* Suspend, come back later */
  166998. }
  166999. /* Do final cleanup */
  167000. (*cinfo->src->term_source) (cinfo);
  167001. /* We can use jpeg_abort to release memory and reset global_state */
  167002. jpeg_abort((j_common_ptr) cinfo);
  167003. return TRUE;
  167004. }
  167005. /*** End of inlined file: jdapimin.c ***/
  167006. /*** Start of inlined file: jdatasrc.c ***/
  167007. /* this is not a core library module, so it doesn't define JPEG_INTERNALS */
  167008. /*** Start of inlined file: jerror.h ***/
  167009. /*
  167010. * To define the enum list of message codes, include this file without
  167011. * defining macro JMESSAGE. To create a message string table, include it
  167012. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  167013. */
  167014. #ifndef JMESSAGE
  167015. #ifndef JERROR_H
  167016. /* First time through, define the enum list */
  167017. #define JMAKE_ENUM_LIST
  167018. #else
  167019. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  167020. #define JMESSAGE(code,string)
  167021. #endif /* JERROR_H */
  167022. #endif /* JMESSAGE */
  167023. #ifdef JMAKE_ENUM_LIST
  167024. typedef enum {
  167025. #define JMESSAGE(code,string) code ,
  167026. #endif /* JMAKE_ENUM_LIST */
  167027. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  167028. /* For maintenance convenience, list is alphabetical by message code name */
  167029. JMESSAGE(JERR_ARITH_NOTIMPL,
  167030. "Sorry, there are legal restrictions on arithmetic coding")
  167031. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  167032. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  167033. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  167034. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  167035. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  167036. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  167037. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  167038. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  167039. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  167040. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  167041. JMESSAGE(JERR_BAD_LIB_VERSION,
  167042. "Wrong JPEG library version: library is %d, caller expects %d")
  167043. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  167044. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  167045. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  167046. JMESSAGE(JERR_BAD_PROGRESSION,
  167047. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  167048. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  167049. "Invalid progressive parameters at scan script entry %d")
  167050. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  167051. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  167052. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  167053. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  167054. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  167055. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  167056. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  167057. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  167058. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  167059. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  167060. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  167061. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  167062. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  167063. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  167064. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  167065. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  167066. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  167067. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  167068. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  167069. JMESSAGE(JERR_FILE_READ, "Input file read error")
  167070. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  167071. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  167072. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  167073. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  167074. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  167075. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  167076. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  167077. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  167078. "Cannot transcode due to multiple use of quantization table %d")
  167079. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  167080. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  167081. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  167082. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  167083. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  167084. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  167085. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  167086. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  167087. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  167088. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  167089. JMESSAGE(JERR_QUANT_COMPONENTS,
  167090. "Cannot quantize more than %d color components")
  167091. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  167092. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  167093. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  167094. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  167095. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  167096. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  167097. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  167098. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  167099. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  167100. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  167101. JMESSAGE(JERR_TFILE_WRITE,
  167102. "Write failed on temporary file --- out of disk space?")
  167103. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  167104. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  167105. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  167106. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  167107. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  167108. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  167109. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  167110. JMESSAGE(JMSG_VERSION, JVERSION)
  167111. JMESSAGE(JTRC_16BIT_TABLES,
  167112. "Caution: quantization tables are too coarse for baseline JPEG")
  167113. JMESSAGE(JTRC_ADOBE,
  167114. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  167115. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  167116. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  167117. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  167118. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  167119. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  167120. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  167121. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  167122. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  167123. JMESSAGE(JTRC_EOI, "End Of Image")
  167124. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  167125. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  167126. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  167127. "Warning: thumbnail image size does not match data length %u")
  167128. JMESSAGE(JTRC_JFIF_EXTENSION,
  167129. "JFIF extension marker: type 0x%02x, length %u")
  167130. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  167131. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  167132. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  167133. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  167134. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  167135. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  167136. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  167137. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  167138. JMESSAGE(JTRC_RST, "RST%d")
  167139. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  167140. "Smoothing not supported with nonstandard sampling ratios")
  167141. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  167142. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  167143. JMESSAGE(JTRC_SOI, "Start of Image")
  167144. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  167145. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  167146. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  167147. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  167148. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  167149. JMESSAGE(JTRC_THUMB_JPEG,
  167150. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  167151. JMESSAGE(JTRC_THUMB_PALETTE,
  167152. "JFIF extension marker: palette thumbnail image, length %u")
  167153. JMESSAGE(JTRC_THUMB_RGB,
  167154. "JFIF extension marker: RGB thumbnail image, length %u")
  167155. JMESSAGE(JTRC_UNKNOWN_IDS,
  167156. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  167157. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  167158. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  167159. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  167160. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  167161. "Inconsistent progression sequence for component %d coefficient %d")
  167162. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  167163. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  167164. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  167165. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  167166. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  167167. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  167168. JMESSAGE(JWRN_MUST_RESYNC,
  167169. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  167170. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  167171. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  167172. #ifdef JMAKE_ENUM_LIST
  167173. JMSG_LASTMSGCODE
  167174. } J_MESSAGE_CODE;
  167175. #undef JMAKE_ENUM_LIST
  167176. #endif /* JMAKE_ENUM_LIST */
  167177. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  167178. #undef JMESSAGE
  167179. #ifndef JERROR_H
  167180. #define JERROR_H
  167181. /* Macros to simplify using the error and trace message stuff */
  167182. /* The first parameter is either type of cinfo pointer */
  167183. /* Fatal errors (print message and exit) */
  167184. #define ERREXIT(cinfo,code) \
  167185. ((cinfo)->err->msg_code = (code), \
  167186. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  167187. #define ERREXIT1(cinfo,code,p1) \
  167188. ((cinfo)->err->msg_code = (code), \
  167189. (cinfo)->err->msg_parm.i[0] = (p1), \
  167190. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  167191. #define ERREXIT2(cinfo,code,p1,p2) \
  167192. ((cinfo)->err->msg_code = (code), \
  167193. (cinfo)->err->msg_parm.i[0] = (p1), \
  167194. (cinfo)->err->msg_parm.i[1] = (p2), \
  167195. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  167196. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  167197. ((cinfo)->err->msg_code = (code), \
  167198. (cinfo)->err->msg_parm.i[0] = (p1), \
  167199. (cinfo)->err->msg_parm.i[1] = (p2), \
  167200. (cinfo)->err->msg_parm.i[2] = (p3), \
  167201. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  167202. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  167203. ((cinfo)->err->msg_code = (code), \
  167204. (cinfo)->err->msg_parm.i[0] = (p1), \
  167205. (cinfo)->err->msg_parm.i[1] = (p2), \
  167206. (cinfo)->err->msg_parm.i[2] = (p3), \
  167207. (cinfo)->err->msg_parm.i[3] = (p4), \
  167208. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  167209. #define ERREXITS(cinfo,code,str) \
  167210. ((cinfo)->err->msg_code = (code), \
  167211. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  167212. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  167213. #define MAKESTMT(stuff) do { stuff } while (0)
  167214. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  167215. #define WARNMS(cinfo,code) \
  167216. ((cinfo)->err->msg_code = (code), \
  167217. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  167218. #define WARNMS1(cinfo,code,p1) \
  167219. ((cinfo)->err->msg_code = (code), \
  167220. (cinfo)->err->msg_parm.i[0] = (p1), \
  167221. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  167222. #define WARNMS2(cinfo,code,p1,p2) \
  167223. ((cinfo)->err->msg_code = (code), \
  167224. (cinfo)->err->msg_parm.i[0] = (p1), \
  167225. (cinfo)->err->msg_parm.i[1] = (p2), \
  167226. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  167227. /* Informational/debugging messages */
  167228. #define TRACEMS(cinfo,lvl,code) \
  167229. ((cinfo)->err->msg_code = (code), \
  167230. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  167231. #define TRACEMS1(cinfo,lvl,code,p1) \
  167232. ((cinfo)->err->msg_code = (code), \
  167233. (cinfo)->err->msg_parm.i[0] = (p1), \
  167234. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  167235. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  167236. ((cinfo)->err->msg_code = (code), \
  167237. (cinfo)->err->msg_parm.i[0] = (p1), \
  167238. (cinfo)->err->msg_parm.i[1] = (p2), \
  167239. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  167240. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  167241. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  167242. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  167243. (cinfo)->err->msg_code = (code); \
  167244. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  167245. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  167246. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  167247. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  167248. (cinfo)->err->msg_code = (code); \
  167249. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  167250. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  167251. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  167252. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  167253. _mp[4] = (p5); \
  167254. (cinfo)->err->msg_code = (code); \
  167255. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  167256. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  167257. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  167258. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  167259. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  167260. (cinfo)->err->msg_code = (code); \
  167261. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  167262. #define TRACEMSS(cinfo,lvl,code,str) \
  167263. ((cinfo)->err->msg_code = (code), \
  167264. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  167265. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  167266. #endif /* JERROR_H */
  167267. /*** End of inlined file: jerror.h ***/
  167268. /* Expanded data source object for stdio input */
  167269. typedef struct {
  167270. struct jpeg_source_mgr pub; /* public fields */
  167271. FILE * infile; /* source stream */
  167272. JOCTET * buffer; /* start of buffer */
  167273. boolean start_of_file; /* have we gotten any data yet? */
  167274. } my_source_mgr;
  167275. typedef my_source_mgr * my_src_ptr;
  167276. #define INPUT_BUF_SIZE 4096 /* choose an efficiently fread'able size */
  167277. /*
  167278. * Initialize source --- called by jpeg_read_header
  167279. * before any data is actually read.
  167280. */
  167281. METHODDEF(void)
  167282. init_source (j_decompress_ptr cinfo)
  167283. {
  167284. my_src_ptr src = (my_src_ptr) cinfo->src;
  167285. /* We reset the empty-input-file flag for each image,
  167286. * but we don't clear the input buffer.
  167287. * This is correct behavior for reading a series of images from one source.
  167288. */
  167289. src->start_of_file = TRUE;
  167290. }
  167291. /*
  167292. * Fill the input buffer --- called whenever buffer is emptied.
  167293. *
  167294. * In typical applications, this should read fresh data into the buffer
  167295. * (ignoring the current state of next_input_byte & bytes_in_buffer),
  167296. * reset the pointer & count to the start of the buffer, and return TRUE
  167297. * indicating that the buffer has been reloaded. It is not necessary to
  167298. * fill the buffer entirely, only to obtain at least one more byte.
  167299. *
  167300. * There is no such thing as an EOF return. If the end of the file has been
  167301. * reached, the routine has a choice of ERREXIT() or inserting fake data into
  167302. * the buffer. In most cases, generating a warning message and inserting a
  167303. * fake EOI marker is the best course of action --- this will allow the
  167304. * decompressor to output however much of the image is there. However,
  167305. * the resulting error message is misleading if the real problem is an empty
  167306. * input file, so we handle that case specially.
  167307. *
  167308. * In applications that need to be able to suspend compression due to input
  167309. * not being available yet, a FALSE return indicates that no more data can be
  167310. * obtained right now, but more may be forthcoming later. In this situation,
  167311. * the decompressor will return to its caller (with an indication of the
  167312. * number of scanlines it has read, if any). The application should resume
  167313. * decompression after it has loaded more data into the input buffer. Note
  167314. * that there are substantial restrictions on the use of suspension --- see
  167315. * the documentation.
  167316. *
  167317. * When suspending, the decompressor will back up to a convenient restart point
  167318. * (typically the start of the current MCU). next_input_byte & bytes_in_buffer
  167319. * indicate where the restart point will be if the current call returns FALSE.
  167320. * Data beyond this point must be rescanned after resumption, so move it to
  167321. * the front of the buffer rather than discarding it.
  167322. */
  167323. METHODDEF(boolean)
  167324. fill_input_buffer (j_decompress_ptr cinfo)
  167325. {
  167326. my_src_ptr src = (my_src_ptr) cinfo->src;
  167327. size_t nbytes;
  167328. nbytes = JFREAD(src->infile, src->buffer, INPUT_BUF_SIZE);
  167329. if (nbytes <= 0) {
  167330. if (src->start_of_file) /* Treat empty input file as fatal error */
  167331. ERREXIT(cinfo, JERR_INPUT_EMPTY);
  167332. WARNMS(cinfo, JWRN_JPEG_EOF);
  167333. /* Insert a fake EOI marker */
  167334. src->buffer[0] = (JOCTET) 0xFF;
  167335. src->buffer[1] = (JOCTET) JPEG_EOI;
  167336. nbytes = 2;
  167337. }
  167338. src->pub.next_input_byte = src->buffer;
  167339. src->pub.bytes_in_buffer = nbytes;
  167340. src->start_of_file = FALSE;
  167341. return TRUE;
  167342. }
  167343. /*
  167344. * Skip data --- used to skip over a potentially large amount of
  167345. * uninteresting data (such as an APPn marker).
  167346. *
  167347. * Writers of suspendable-input applications must note that skip_input_data
  167348. * is not granted the right to give a suspension return. If the skip extends
  167349. * beyond the data currently in the buffer, the buffer can be marked empty so
  167350. * that the next read will cause a fill_input_buffer call that can suspend.
  167351. * Arranging for additional bytes to be discarded before reloading the input
  167352. * buffer is the application writer's problem.
  167353. */
  167354. METHODDEF(void)
  167355. skip_input_data (j_decompress_ptr cinfo, long num_bytes)
  167356. {
  167357. my_src_ptr src = (my_src_ptr) cinfo->src;
  167358. /* Just a dumb implementation for now. Could use fseek() except
  167359. * it doesn't work on pipes. Not clear that being smart is worth
  167360. * any trouble anyway --- large skips are infrequent.
  167361. */
  167362. if (num_bytes > 0) {
  167363. while (num_bytes > (long) src->pub.bytes_in_buffer) {
  167364. num_bytes -= (long) src->pub.bytes_in_buffer;
  167365. (void) fill_input_buffer(cinfo);
  167366. /* note we assume that fill_input_buffer will never return FALSE,
  167367. * so suspension need not be handled.
  167368. */
  167369. }
  167370. src->pub.next_input_byte += (size_t) num_bytes;
  167371. src->pub.bytes_in_buffer -= (size_t) num_bytes;
  167372. }
  167373. }
  167374. /*
  167375. * An additional method that can be provided by data source modules is the
  167376. * resync_to_restart method for error recovery in the presence of RST markers.
  167377. * For the moment, this source module just uses the default resync method
  167378. * provided by the JPEG library. That method assumes that no backtracking
  167379. * is possible.
  167380. */
  167381. /*
  167382. * Terminate source --- called by jpeg_finish_decompress
  167383. * after all data has been read. Often a no-op.
  167384. *
  167385. * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding
  167386. * application must deal with any cleanup that should happen even
  167387. * for error exit.
  167388. */
  167389. METHODDEF(void)
  167390. term_source (j_decompress_ptr)
  167391. {
  167392. /* no work necessary here */
  167393. }
  167394. /*
  167395. * Prepare for input from a stdio stream.
  167396. * The caller must have already opened the stream, and is responsible
  167397. * for closing it after finishing decompression.
  167398. */
  167399. GLOBAL(void)
  167400. jpeg_stdio_src (j_decompress_ptr cinfo, FILE * infile)
  167401. {
  167402. my_src_ptr src;
  167403. /* The source object and input buffer are made permanent so that a series
  167404. * of JPEG images can be read from the same file by calling jpeg_stdio_src
  167405. * only before the first one. (If we discarded the buffer at the end of
  167406. * one image, we'd likely lose the start of the next one.)
  167407. * This makes it unsafe to use this manager and a different source
  167408. * manager serially with the same JPEG object. Caveat programmer.
  167409. */
  167410. if (cinfo->src == NULL) { /* first time for this JPEG object? */
  167411. cinfo->src = (struct jpeg_source_mgr *)
  167412. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  167413. SIZEOF(my_source_mgr));
  167414. src = (my_src_ptr) cinfo->src;
  167415. src->buffer = (JOCTET *)
  167416. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  167417. INPUT_BUF_SIZE * SIZEOF(JOCTET));
  167418. }
  167419. src = (my_src_ptr) cinfo->src;
  167420. src->pub.init_source = init_source;
  167421. src->pub.fill_input_buffer = fill_input_buffer;
  167422. src->pub.skip_input_data = skip_input_data;
  167423. src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */
  167424. src->pub.term_source = term_source;
  167425. src->infile = infile;
  167426. src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */
  167427. src->pub.next_input_byte = NULL; /* until buffer loaded */
  167428. }
  167429. /*** End of inlined file: jdatasrc.c ***/
  167430. /*** Start of inlined file: jdcoefct.c ***/
  167431. #define JPEG_INTERNALS
  167432. /* Block smoothing is only applicable for progressive JPEG, so: */
  167433. #ifndef D_PROGRESSIVE_SUPPORTED
  167434. #undef BLOCK_SMOOTHING_SUPPORTED
  167435. #endif
  167436. /* Private buffer controller object */
  167437. typedef struct {
  167438. struct jpeg_d_coef_controller pub; /* public fields */
  167439. /* These variables keep track of the current location of the input side. */
  167440. /* cinfo->input_iMCU_row is also used for this. */
  167441. JDIMENSION MCU_ctr; /* counts MCUs processed in current row */
  167442. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  167443. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  167444. /* The output side's location is represented by cinfo->output_iMCU_row. */
  167445. /* In single-pass modes, it's sufficient to buffer just one MCU.
  167446. * We allocate a workspace of D_MAX_BLOCKS_IN_MCU coefficient blocks,
  167447. * and let the entropy decoder write into that workspace each time.
  167448. * (On 80x86, the workspace is FAR even though it's not really very big;
  167449. * this is to keep the module interfaces unchanged when a large coefficient
  167450. * buffer is necessary.)
  167451. * In multi-pass modes, this array points to the current MCU's blocks
  167452. * within the virtual arrays; it is used only by the input side.
  167453. */
  167454. JBLOCKROW MCU_buffer[D_MAX_BLOCKS_IN_MCU];
  167455. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167456. /* In multi-pass modes, we need a virtual block array for each component. */
  167457. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  167458. #endif
  167459. #ifdef BLOCK_SMOOTHING_SUPPORTED
  167460. /* When doing block smoothing, we latch coefficient Al values here */
  167461. int * coef_bits_latch;
  167462. #define SAVED_COEFS 6 /* we save coef_bits[0..5] */
  167463. #endif
  167464. } my_coef_controller3;
  167465. typedef my_coef_controller3 * my_coef_ptr3;
  167466. /* Forward declarations */
  167467. METHODDEF(int) decompress_onepass
  167468. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  167469. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167470. METHODDEF(int) decompress_data
  167471. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  167472. #endif
  167473. #ifdef BLOCK_SMOOTHING_SUPPORTED
  167474. LOCAL(boolean) smoothing_ok JPP((j_decompress_ptr cinfo));
  167475. METHODDEF(int) decompress_smooth_data
  167476. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  167477. #endif
  167478. LOCAL(void)
  167479. start_iMCU_row3 (j_decompress_ptr cinfo)
  167480. /* Reset within-iMCU-row counters for a new row (input side) */
  167481. {
  167482. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  167483. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  167484. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  167485. * But at the bottom of the image, process only what's left.
  167486. */
  167487. if (cinfo->comps_in_scan > 1) {
  167488. coef->MCU_rows_per_iMCU_row = 1;
  167489. } else {
  167490. if (cinfo->input_iMCU_row < (cinfo->total_iMCU_rows-1))
  167491. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  167492. else
  167493. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  167494. }
  167495. coef->MCU_ctr = 0;
  167496. coef->MCU_vert_offset = 0;
  167497. }
  167498. /*
  167499. * Initialize for an input processing pass.
  167500. */
  167501. METHODDEF(void)
  167502. start_input_pass (j_decompress_ptr cinfo)
  167503. {
  167504. cinfo->input_iMCU_row = 0;
  167505. start_iMCU_row3(cinfo);
  167506. }
  167507. /*
  167508. * Initialize for an output processing pass.
  167509. */
  167510. METHODDEF(void)
  167511. start_output_pass (j_decompress_ptr cinfo)
  167512. {
  167513. #ifdef BLOCK_SMOOTHING_SUPPORTED
  167514. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  167515. /* If multipass, check to see whether to use block smoothing on this pass */
  167516. if (coef->pub.coef_arrays != NULL) {
  167517. if (cinfo->do_block_smoothing && smoothing_ok(cinfo))
  167518. coef->pub.decompress_data = decompress_smooth_data;
  167519. else
  167520. coef->pub.decompress_data = decompress_data;
  167521. }
  167522. #endif
  167523. cinfo->output_iMCU_row = 0;
  167524. }
  167525. /*
  167526. * Decompress and return some data in the single-pass case.
  167527. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  167528. * Input and output must run in lockstep since we have only a one-MCU buffer.
  167529. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  167530. *
  167531. * NB: output_buf contains a plane for each component in image,
  167532. * which we index according to the component's SOF position.
  167533. */
  167534. METHODDEF(int)
  167535. decompress_onepass (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  167536. {
  167537. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  167538. JDIMENSION MCU_col_num; /* index of current MCU within row */
  167539. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  167540. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  167541. int blkn, ci, xindex, yindex, yoffset, useful_width;
  167542. JSAMPARRAY output_ptr;
  167543. JDIMENSION start_col, output_col;
  167544. jpeg_component_info *compptr;
  167545. inverse_DCT_method_ptr inverse_DCT;
  167546. /* Loop to process as much as one whole iMCU row */
  167547. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  167548. yoffset++) {
  167549. for (MCU_col_num = coef->MCU_ctr; MCU_col_num <= last_MCU_col;
  167550. MCU_col_num++) {
  167551. /* Try to fetch an MCU. Entropy decoder expects buffer to be zeroed. */
  167552. jzero_far((void FAR *) coef->MCU_buffer[0],
  167553. (size_t) (cinfo->blocks_in_MCU * SIZEOF(JBLOCK)));
  167554. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  167555. /* Suspension forced; update state counters and exit */
  167556. coef->MCU_vert_offset = yoffset;
  167557. coef->MCU_ctr = MCU_col_num;
  167558. return JPEG_SUSPENDED;
  167559. }
  167560. /* Determine where data should go in output_buf and do the IDCT thing.
  167561. * We skip dummy blocks at the right and bottom edges (but blkn gets
  167562. * incremented past them!). Note the inner loop relies on having
  167563. * allocated the MCU_buffer[] blocks sequentially.
  167564. */
  167565. blkn = 0; /* index of current DCT block within MCU */
  167566. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167567. compptr = cinfo->cur_comp_info[ci];
  167568. /* Don't bother to IDCT an uninteresting component. */
  167569. if (! compptr->component_needed) {
  167570. blkn += compptr->MCU_blocks;
  167571. continue;
  167572. }
  167573. inverse_DCT = cinfo->idct->inverse_DCT[compptr->component_index];
  167574. useful_width = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  167575. : compptr->last_col_width;
  167576. output_ptr = output_buf[compptr->component_index] +
  167577. yoffset * compptr->DCT_scaled_size;
  167578. start_col = MCU_col_num * compptr->MCU_sample_width;
  167579. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  167580. if (cinfo->input_iMCU_row < last_iMCU_row ||
  167581. yoffset+yindex < compptr->last_row_height) {
  167582. output_col = start_col;
  167583. for (xindex = 0; xindex < useful_width; xindex++) {
  167584. (*inverse_DCT) (cinfo, compptr,
  167585. (JCOEFPTR) coef->MCU_buffer[blkn+xindex],
  167586. output_ptr, output_col);
  167587. output_col += compptr->DCT_scaled_size;
  167588. }
  167589. }
  167590. blkn += compptr->MCU_width;
  167591. output_ptr += compptr->DCT_scaled_size;
  167592. }
  167593. }
  167594. }
  167595. /* Completed an MCU row, but perhaps not an iMCU row */
  167596. coef->MCU_ctr = 0;
  167597. }
  167598. /* Completed the iMCU row, advance counters for next one */
  167599. cinfo->output_iMCU_row++;
  167600. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  167601. start_iMCU_row3(cinfo);
  167602. return JPEG_ROW_COMPLETED;
  167603. }
  167604. /* Completed the scan */
  167605. (*cinfo->inputctl->finish_input_pass) (cinfo);
  167606. return JPEG_SCAN_COMPLETED;
  167607. }
  167608. /*
  167609. * Dummy consume-input routine for single-pass operation.
  167610. */
  167611. METHODDEF(int)
  167612. dummy_consume_data (j_decompress_ptr)
  167613. {
  167614. return JPEG_SUSPENDED; /* Always indicate nothing was done */
  167615. }
  167616. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167617. /*
  167618. * Consume input data and store it in the full-image coefficient buffer.
  167619. * We read as much as one fully interleaved MCU row ("iMCU" row) per call,
  167620. * ie, v_samp_factor block rows for each component in the scan.
  167621. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  167622. */
  167623. METHODDEF(int)
  167624. consume_data (j_decompress_ptr cinfo)
  167625. {
  167626. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  167627. JDIMENSION MCU_col_num; /* index of current MCU within row */
  167628. int blkn, ci, xindex, yindex, yoffset;
  167629. JDIMENSION start_col;
  167630. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  167631. JBLOCKROW buffer_ptr;
  167632. jpeg_component_info *compptr;
  167633. /* Align the virtual buffers for the components used in this scan. */
  167634. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167635. compptr = cinfo->cur_comp_info[ci];
  167636. buffer[ci] = (*cinfo->mem->access_virt_barray)
  167637. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  167638. cinfo->input_iMCU_row * compptr->v_samp_factor,
  167639. (JDIMENSION) compptr->v_samp_factor, TRUE);
  167640. /* Note: entropy decoder expects buffer to be zeroed,
  167641. * but this is handled automatically by the memory manager
  167642. * because we requested a pre-zeroed array.
  167643. */
  167644. }
  167645. /* Loop to process one whole iMCU row */
  167646. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  167647. yoffset++) {
  167648. for (MCU_col_num = coef->MCU_ctr; MCU_col_num < cinfo->MCUs_per_row;
  167649. MCU_col_num++) {
  167650. /* Construct list of pointers to DCT blocks belonging to this MCU */
  167651. blkn = 0; /* index of current DCT block within MCU */
  167652. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167653. compptr = cinfo->cur_comp_info[ci];
  167654. start_col = MCU_col_num * compptr->MCU_width;
  167655. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  167656. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  167657. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  167658. coef->MCU_buffer[blkn++] = buffer_ptr++;
  167659. }
  167660. }
  167661. }
  167662. /* Try to fetch the MCU. */
  167663. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  167664. /* Suspension forced; update state counters and exit */
  167665. coef->MCU_vert_offset = yoffset;
  167666. coef->MCU_ctr = MCU_col_num;
  167667. return JPEG_SUSPENDED;
  167668. }
  167669. }
  167670. /* Completed an MCU row, but perhaps not an iMCU row */
  167671. coef->MCU_ctr = 0;
  167672. }
  167673. /* Completed the iMCU row, advance counters for next one */
  167674. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  167675. start_iMCU_row3(cinfo);
  167676. return JPEG_ROW_COMPLETED;
  167677. }
  167678. /* Completed the scan */
  167679. (*cinfo->inputctl->finish_input_pass) (cinfo);
  167680. return JPEG_SCAN_COMPLETED;
  167681. }
  167682. /*
  167683. * Decompress and return some data in the multi-pass case.
  167684. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  167685. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  167686. *
  167687. * NB: output_buf contains a plane for each component in image.
  167688. */
  167689. METHODDEF(int)
  167690. decompress_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  167691. {
  167692. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  167693. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  167694. JDIMENSION block_num;
  167695. int ci, block_row, block_rows;
  167696. JBLOCKARRAY buffer;
  167697. JBLOCKROW buffer_ptr;
  167698. JSAMPARRAY output_ptr;
  167699. JDIMENSION output_col;
  167700. jpeg_component_info *compptr;
  167701. inverse_DCT_method_ptr inverse_DCT;
  167702. /* Force some input to be done if we are getting ahead of the input. */
  167703. while (cinfo->input_scan_number < cinfo->output_scan_number ||
  167704. (cinfo->input_scan_number == cinfo->output_scan_number &&
  167705. cinfo->input_iMCU_row <= cinfo->output_iMCU_row)) {
  167706. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  167707. return JPEG_SUSPENDED;
  167708. }
  167709. /* OK, output from the virtual arrays. */
  167710. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167711. ci++, compptr++) {
  167712. /* Don't bother to IDCT an uninteresting component. */
  167713. if (! compptr->component_needed)
  167714. continue;
  167715. /* Align the virtual buffer for this component. */
  167716. buffer = (*cinfo->mem->access_virt_barray)
  167717. ((j_common_ptr) cinfo, coef->whole_image[ci],
  167718. cinfo->output_iMCU_row * compptr->v_samp_factor,
  167719. (JDIMENSION) compptr->v_samp_factor, FALSE);
  167720. /* Count non-dummy DCT block rows in this iMCU row. */
  167721. if (cinfo->output_iMCU_row < last_iMCU_row)
  167722. block_rows = compptr->v_samp_factor;
  167723. else {
  167724. /* NB: can't use last_row_height here; it is input-side-dependent! */
  167725. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  167726. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  167727. }
  167728. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  167729. output_ptr = output_buf[ci];
  167730. /* Loop over all DCT blocks to be processed. */
  167731. for (block_row = 0; block_row < block_rows; block_row++) {
  167732. buffer_ptr = buffer[block_row];
  167733. output_col = 0;
  167734. for (block_num = 0; block_num < compptr->width_in_blocks; block_num++) {
  167735. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) buffer_ptr,
  167736. output_ptr, output_col);
  167737. buffer_ptr++;
  167738. output_col += compptr->DCT_scaled_size;
  167739. }
  167740. output_ptr += compptr->DCT_scaled_size;
  167741. }
  167742. }
  167743. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  167744. return JPEG_ROW_COMPLETED;
  167745. return JPEG_SCAN_COMPLETED;
  167746. }
  167747. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  167748. #ifdef BLOCK_SMOOTHING_SUPPORTED
  167749. /*
  167750. * This code applies interblock smoothing as described by section K.8
  167751. * of the JPEG standard: the first 5 AC coefficients are estimated from
  167752. * the DC values of a DCT block and its 8 neighboring blocks.
  167753. * We apply smoothing only for progressive JPEG decoding, and only if
  167754. * the coefficients it can estimate are not yet known to full precision.
  167755. */
  167756. /* Natural-order array positions of the first 5 zigzag-order coefficients */
  167757. #define Q01_POS 1
  167758. #define Q10_POS 8
  167759. #define Q20_POS 16
  167760. #define Q11_POS 9
  167761. #define Q02_POS 2
  167762. /*
  167763. * Determine whether block smoothing is applicable and safe.
  167764. * We also latch the current states of the coef_bits[] entries for the
  167765. * AC coefficients; otherwise, if the input side of the decompressor
  167766. * advances into a new scan, we might think the coefficients are known
  167767. * more accurately than they really are.
  167768. */
  167769. LOCAL(boolean)
  167770. smoothing_ok (j_decompress_ptr cinfo)
  167771. {
  167772. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  167773. boolean smoothing_useful = FALSE;
  167774. int ci, coefi;
  167775. jpeg_component_info *compptr;
  167776. JQUANT_TBL * qtable;
  167777. int * coef_bits;
  167778. int * coef_bits_latch;
  167779. if (! cinfo->progressive_mode || cinfo->coef_bits == NULL)
  167780. return FALSE;
  167781. /* Allocate latch area if not already done */
  167782. if (coef->coef_bits_latch == NULL)
  167783. coef->coef_bits_latch = (int *)
  167784. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167785. cinfo->num_components *
  167786. (SAVED_COEFS * SIZEOF(int)));
  167787. coef_bits_latch = coef->coef_bits_latch;
  167788. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167789. ci++, compptr++) {
  167790. /* All components' quantization values must already be latched. */
  167791. if ((qtable = compptr->quant_table) == NULL)
  167792. return FALSE;
  167793. /* Verify DC & first 5 AC quantizers are nonzero to avoid zero-divide. */
  167794. if (qtable->quantval[0] == 0 ||
  167795. qtable->quantval[Q01_POS] == 0 ||
  167796. qtable->quantval[Q10_POS] == 0 ||
  167797. qtable->quantval[Q20_POS] == 0 ||
  167798. qtable->quantval[Q11_POS] == 0 ||
  167799. qtable->quantval[Q02_POS] == 0)
  167800. return FALSE;
  167801. /* DC values must be at least partly known for all components. */
  167802. coef_bits = cinfo->coef_bits[ci];
  167803. if (coef_bits[0] < 0)
  167804. return FALSE;
  167805. /* Block smoothing is helpful if some AC coefficients remain inaccurate. */
  167806. for (coefi = 1; coefi <= 5; coefi++) {
  167807. coef_bits_latch[coefi] = coef_bits[coefi];
  167808. if (coef_bits[coefi] != 0)
  167809. smoothing_useful = TRUE;
  167810. }
  167811. coef_bits_latch += SAVED_COEFS;
  167812. }
  167813. return smoothing_useful;
  167814. }
  167815. /*
  167816. * Variant of decompress_data for use when doing block smoothing.
  167817. */
  167818. METHODDEF(int)
  167819. decompress_smooth_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  167820. {
  167821. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  167822. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  167823. JDIMENSION block_num, last_block_column;
  167824. int ci, block_row, block_rows, access_rows;
  167825. JBLOCKARRAY buffer;
  167826. JBLOCKROW buffer_ptr, prev_block_row, next_block_row;
  167827. JSAMPARRAY output_ptr;
  167828. JDIMENSION output_col;
  167829. jpeg_component_info *compptr;
  167830. inverse_DCT_method_ptr inverse_DCT;
  167831. boolean first_row, last_row;
  167832. JBLOCK workspace;
  167833. int *coef_bits;
  167834. JQUANT_TBL *quanttbl;
  167835. INT32 Q00,Q01,Q02,Q10,Q11,Q20, num;
  167836. int DC1,DC2,DC3,DC4,DC5,DC6,DC7,DC8,DC9;
  167837. int Al, pred;
  167838. /* Force some input to be done if we are getting ahead of the input. */
  167839. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  167840. ! cinfo->inputctl->eoi_reached) {
  167841. if (cinfo->input_scan_number == cinfo->output_scan_number) {
  167842. /* If input is working on current scan, we ordinarily want it to
  167843. * have completed the current row. But if input scan is DC,
  167844. * we want it to keep one row ahead so that next block row's DC
  167845. * values are up to date.
  167846. */
  167847. JDIMENSION delta = (cinfo->Ss == 0) ? 1 : 0;
  167848. if (cinfo->input_iMCU_row > cinfo->output_iMCU_row+delta)
  167849. break;
  167850. }
  167851. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  167852. return JPEG_SUSPENDED;
  167853. }
  167854. /* OK, output from the virtual arrays. */
  167855. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167856. ci++, compptr++) {
  167857. /* Don't bother to IDCT an uninteresting component. */
  167858. if (! compptr->component_needed)
  167859. continue;
  167860. /* Count non-dummy DCT block rows in this iMCU row. */
  167861. if (cinfo->output_iMCU_row < last_iMCU_row) {
  167862. block_rows = compptr->v_samp_factor;
  167863. access_rows = block_rows * 2; /* this and next iMCU row */
  167864. last_row = FALSE;
  167865. } else {
  167866. /* NB: can't use last_row_height here; it is input-side-dependent! */
  167867. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  167868. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  167869. access_rows = block_rows; /* this iMCU row only */
  167870. last_row = TRUE;
  167871. }
  167872. /* Align the virtual buffer for this component. */
  167873. if (cinfo->output_iMCU_row > 0) {
  167874. access_rows += compptr->v_samp_factor; /* prior iMCU row too */
  167875. buffer = (*cinfo->mem->access_virt_barray)
  167876. ((j_common_ptr) cinfo, coef->whole_image[ci],
  167877. (cinfo->output_iMCU_row - 1) * compptr->v_samp_factor,
  167878. (JDIMENSION) access_rows, FALSE);
  167879. buffer += compptr->v_samp_factor; /* point to current iMCU row */
  167880. first_row = FALSE;
  167881. } else {
  167882. buffer = (*cinfo->mem->access_virt_barray)
  167883. ((j_common_ptr) cinfo, coef->whole_image[ci],
  167884. (JDIMENSION) 0, (JDIMENSION) access_rows, FALSE);
  167885. first_row = TRUE;
  167886. }
  167887. /* Fetch component-dependent info */
  167888. coef_bits = coef->coef_bits_latch + (ci * SAVED_COEFS);
  167889. quanttbl = compptr->quant_table;
  167890. Q00 = quanttbl->quantval[0];
  167891. Q01 = quanttbl->quantval[Q01_POS];
  167892. Q10 = quanttbl->quantval[Q10_POS];
  167893. Q20 = quanttbl->quantval[Q20_POS];
  167894. Q11 = quanttbl->quantval[Q11_POS];
  167895. Q02 = quanttbl->quantval[Q02_POS];
  167896. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  167897. output_ptr = output_buf[ci];
  167898. /* Loop over all DCT blocks to be processed. */
  167899. for (block_row = 0; block_row < block_rows; block_row++) {
  167900. buffer_ptr = buffer[block_row];
  167901. if (first_row && block_row == 0)
  167902. prev_block_row = buffer_ptr;
  167903. else
  167904. prev_block_row = buffer[block_row-1];
  167905. if (last_row && block_row == block_rows-1)
  167906. next_block_row = buffer_ptr;
  167907. else
  167908. next_block_row = buffer[block_row+1];
  167909. /* We fetch the surrounding DC values using a sliding-register approach.
  167910. * Initialize all nine here so as to do the right thing on narrow pics.
  167911. */
  167912. DC1 = DC2 = DC3 = (int) prev_block_row[0][0];
  167913. DC4 = DC5 = DC6 = (int) buffer_ptr[0][0];
  167914. DC7 = DC8 = DC9 = (int) next_block_row[0][0];
  167915. output_col = 0;
  167916. last_block_column = compptr->width_in_blocks - 1;
  167917. for (block_num = 0; block_num <= last_block_column; block_num++) {
  167918. /* Fetch current DCT block into workspace so we can modify it. */
  167919. jcopy_block_row(buffer_ptr, (JBLOCKROW) workspace, (JDIMENSION) 1);
  167920. /* Update DC values */
  167921. if (block_num < last_block_column) {
  167922. DC3 = (int) prev_block_row[1][0];
  167923. DC6 = (int) buffer_ptr[1][0];
  167924. DC9 = (int) next_block_row[1][0];
  167925. }
  167926. /* Compute coefficient estimates per K.8.
  167927. * An estimate is applied only if coefficient is still zero,
  167928. * and is not known to be fully accurate.
  167929. */
  167930. /* AC01 */
  167931. if ((Al=coef_bits[1]) != 0 && workspace[1] == 0) {
  167932. num = 36 * Q00 * (DC4 - DC6);
  167933. if (num >= 0) {
  167934. pred = (int) (((Q01<<7) + num) / (Q01<<8));
  167935. if (Al > 0 && pred >= (1<<Al))
  167936. pred = (1<<Al)-1;
  167937. } else {
  167938. pred = (int) (((Q01<<7) - num) / (Q01<<8));
  167939. if (Al > 0 && pred >= (1<<Al))
  167940. pred = (1<<Al)-1;
  167941. pred = -pred;
  167942. }
  167943. workspace[1] = (JCOEF) pred;
  167944. }
  167945. /* AC10 */
  167946. if ((Al=coef_bits[2]) != 0 && workspace[8] == 0) {
  167947. num = 36 * Q00 * (DC2 - DC8);
  167948. if (num >= 0) {
  167949. pred = (int) (((Q10<<7) + num) / (Q10<<8));
  167950. if (Al > 0 && pred >= (1<<Al))
  167951. pred = (1<<Al)-1;
  167952. } else {
  167953. pred = (int) (((Q10<<7) - num) / (Q10<<8));
  167954. if (Al > 0 && pred >= (1<<Al))
  167955. pred = (1<<Al)-1;
  167956. pred = -pred;
  167957. }
  167958. workspace[8] = (JCOEF) pred;
  167959. }
  167960. /* AC20 */
  167961. if ((Al=coef_bits[3]) != 0 && workspace[16] == 0) {
  167962. num = 9 * Q00 * (DC2 + DC8 - 2*DC5);
  167963. if (num >= 0) {
  167964. pred = (int) (((Q20<<7) + num) / (Q20<<8));
  167965. if (Al > 0 && pred >= (1<<Al))
  167966. pred = (1<<Al)-1;
  167967. } else {
  167968. pred = (int) (((Q20<<7) - num) / (Q20<<8));
  167969. if (Al > 0 && pred >= (1<<Al))
  167970. pred = (1<<Al)-1;
  167971. pred = -pred;
  167972. }
  167973. workspace[16] = (JCOEF) pred;
  167974. }
  167975. /* AC11 */
  167976. if ((Al=coef_bits[4]) != 0 && workspace[9] == 0) {
  167977. num = 5 * Q00 * (DC1 - DC3 - DC7 + DC9);
  167978. if (num >= 0) {
  167979. pred = (int) (((Q11<<7) + num) / (Q11<<8));
  167980. if (Al > 0 && pred >= (1<<Al))
  167981. pred = (1<<Al)-1;
  167982. } else {
  167983. pred = (int) (((Q11<<7) - num) / (Q11<<8));
  167984. if (Al > 0 && pred >= (1<<Al))
  167985. pred = (1<<Al)-1;
  167986. pred = -pred;
  167987. }
  167988. workspace[9] = (JCOEF) pred;
  167989. }
  167990. /* AC02 */
  167991. if ((Al=coef_bits[5]) != 0 && workspace[2] == 0) {
  167992. num = 9 * Q00 * (DC4 + DC6 - 2*DC5);
  167993. if (num >= 0) {
  167994. pred = (int) (((Q02<<7) + num) / (Q02<<8));
  167995. if (Al > 0 && pred >= (1<<Al))
  167996. pred = (1<<Al)-1;
  167997. } else {
  167998. pred = (int) (((Q02<<7) - num) / (Q02<<8));
  167999. if (Al > 0 && pred >= (1<<Al))
  168000. pred = (1<<Al)-1;
  168001. pred = -pred;
  168002. }
  168003. workspace[2] = (JCOEF) pred;
  168004. }
  168005. /* OK, do the IDCT */
  168006. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) workspace,
  168007. output_ptr, output_col);
  168008. /* Advance for next column */
  168009. DC1 = DC2; DC2 = DC3;
  168010. DC4 = DC5; DC5 = DC6;
  168011. DC7 = DC8; DC8 = DC9;
  168012. buffer_ptr++, prev_block_row++, next_block_row++;
  168013. output_col += compptr->DCT_scaled_size;
  168014. }
  168015. output_ptr += compptr->DCT_scaled_size;
  168016. }
  168017. }
  168018. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  168019. return JPEG_ROW_COMPLETED;
  168020. return JPEG_SCAN_COMPLETED;
  168021. }
  168022. #endif /* BLOCK_SMOOTHING_SUPPORTED */
  168023. /*
  168024. * Initialize coefficient buffer controller.
  168025. */
  168026. GLOBAL(void)
  168027. jinit_d_coef_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  168028. {
  168029. my_coef_ptr3 coef;
  168030. coef = (my_coef_ptr3)
  168031. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168032. SIZEOF(my_coef_controller3));
  168033. cinfo->coef = (struct jpeg_d_coef_controller *) coef;
  168034. coef->pub.start_input_pass = start_input_pass;
  168035. coef->pub.start_output_pass = start_output_pass;
  168036. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168037. coef->coef_bits_latch = NULL;
  168038. #endif
  168039. /* Create the coefficient buffer. */
  168040. if (need_full_buffer) {
  168041. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168042. /* Allocate a full-image virtual array for each component, */
  168043. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  168044. /* Note we ask for a pre-zeroed array. */
  168045. int ci, access_rows;
  168046. jpeg_component_info *compptr;
  168047. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168048. ci++, compptr++) {
  168049. access_rows = compptr->v_samp_factor;
  168050. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168051. /* If block smoothing could be used, need a bigger window */
  168052. if (cinfo->progressive_mode)
  168053. access_rows *= 3;
  168054. #endif
  168055. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  168056. ((j_common_ptr) cinfo, JPOOL_IMAGE, TRUE,
  168057. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  168058. (long) compptr->h_samp_factor),
  168059. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  168060. (long) compptr->v_samp_factor),
  168061. (JDIMENSION) access_rows);
  168062. }
  168063. coef->pub.consume_data = consume_data;
  168064. coef->pub.decompress_data = decompress_data;
  168065. coef->pub.coef_arrays = coef->whole_image; /* link to virtual arrays */
  168066. #else
  168067. ERREXIT(cinfo, JERR_NOT_COMPILED);
  168068. #endif
  168069. } else {
  168070. /* We only need a single-MCU buffer. */
  168071. JBLOCKROW buffer;
  168072. int i;
  168073. buffer = (JBLOCKROW)
  168074. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168075. D_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  168076. for (i = 0; i < D_MAX_BLOCKS_IN_MCU; i++) {
  168077. coef->MCU_buffer[i] = buffer + i;
  168078. }
  168079. coef->pub.consume_data = dummy_consume_data;
  168080. coef->pub.decompress_data = decompress_onepass;
  168081. coef->pub.coef_arrays = NULL; /* flag for no virtual arrays */
  168082. }
  168083. }
  168084. /*** End of inlined file: jdcoefct.c ***/
  168085. #undef FIX
  168086. /*** Start of inlined file: jdcolor.c ***/
  168087. #define JPEG_INTERNALS
  168088. /* Private subobject */
  168089. typedef struct {
  168090. struct jpeg_color_deconverter pub; /* public fields */
  168091. /* Private state for YCC->RGB conversion */
  168092. int * Cr_r_tab; /* => table for Cr to R conversion */
  168093. int * Cb_b_tab; /* => table for Cb to B conversion */
  168094. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  168095. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  168096. } my_color_deconverter2;
  168097. typedef my_color_deconverter2 * my_cconvert_ptr2;
  168098. /**************** YCbCr -> RGB conversion: most common case **************/
  168099. /*
  168100. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  168101. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  168102. * The conversion equations to be implemented are therefore
  168103. * R = Y + 1.40200 * Cr
  168104. * G = Y - 0.34414 * Cb - 0.71414 * Cr
  168105. * B = Y + 1.77200 * Cb
  168106. * where Cb and Cr represent the incoming values less CENTERJSAMPLE.
  168107. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  168108. *
  168109. * To avoid floating-point arithmetic, we represent the fractional constants
  168110. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  168111. * the products by 2^16, with appropriate rounding, to get the correct answer.
  168112. * Notice that Y, being an integral input, does not contribute any fraction
  168113. * so it need not participate in the rounding.
  168114. *
  168115. * For even more speed, we avoid doing any multiplications in the inner loop
  168116. * by precalculating the constants times Cb and Cr for all possible values.
  168117. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  168118. * for 12-bit samples it is still acceptable. It's not very reasonable for
  168119. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  168120. * colorspace anyway.
  168121. * The Cr=>R and Cb=>B values can be rounded to integers in advance; the
  168122. * values for the G calculation are left scaled up, since we must add them
  168123. * together before rounding.
  168124. */
  168125. #define SCALEBITS 16 /* speediest right-shift on some machines */
  168126. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  168127. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  168128. /*
  168129. * Initialize tables for YCC->RGB colorspace conversion.
  168130. */
  168131. LOCAL(void)
  168132. build_ycc_rgb_table (j_decompress_ptr cinfo)
  168133. {
  168134. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  168135. int i;
  168136. INT32 x;
  168137. SHIFT_TEMPS
  168138. cconvert->Cr_r_tab = (int *)
  168139. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168140. (MAXJSAMPLE+1) * SIZEOF(int));
  168141. cconvert->Cb_b_tab = (int *)
  168142. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168143. (MAXJSAMPLE+1) * SIZEOF(int));
  168144. cconvert->Cr_g_tab = (INT32 *)
  168145. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168146. (MAXJSAMPLE+1) * SIZEOF(INT32));
  168147. cconvert->Cb_g_tab = (INT32 *)
  168148. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168149. (MAXJSAMPLE+1) * SIZEOF(INT32));
  168150. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  168151. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  168152. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  168153. /* Cr=>R value is nearest int to 1.40200 * x */
  168154. cconvert->Cr_r_tab[i] = (int)
  168155. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  168156. /* Cb=>B value is nearest int to 1.77200 * x */
  168157. cconvert->Cb_b_tab[i] = (int)
  168158. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  168159. /* Cr=>G value is scaled-up -0.71414 * x */
  168160. cconvert->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  168161. /* Cb=>G value is scaled-up -0.34414 * x */
  168162. /* We also add in ONE_HALF so that need not do it in inner loop */
  168163. cconvert->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  168164. }
  168165. }
  168166. /*
  168167. * Convert some rows of samples to the output colorspace.
  168168. *
  168169. * Note that we change from noninterleaved, one-plane-per-component format
  168170. * to interleaved-pixel format. The output buffer is therefore three times
  168171. * as wide as the input buffer.
  168172. * A starting row offset is provided only for the input buffer. The caller
  168173. * can easily adjust the passed output_buf value to accommodate any row
  168174. * offset required on that side.
  168175. */
  168176. METHODDEF(void)
  168177. ycc_rgb_convert (j_decompress_ptr cinfo,
  168178. JSAMPIMAGE input_buf, JDIMENSION input_row,
  168179. JSAMPARRAY output_buf, int num_rows)
  168180. {
  168181. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  168182. register int y, cb, cr;
  168183. register JSAMPROW outptr;
  168184. register JSAMPROW inptr0, inptr1, inptr2;
  168185. register JDIMENSION col;
  168186. JDIMENSION num_cols = cinfo->output_width;
  168187. /* copy these pointers into registers if possible */
  168188. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  168189. register int * Crrtab = cconvert->Cr_r_tab;
  168190. register int * Cbbtab = cconvert->Cb_b_tab;
  168191. register INT32 * Crgtab = cconvert->Cr_g_tab;
  168192. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  168193. SHIFT_TEMPS
  168194. while (--num_rows >= 0) {
  168195. inptr0 = input_buf[0][input_row];
  168196. inptr1 = input_buf[1][input_row];
  168197. inptr2 = input_buf[2][input_row];
  168198. input_row++;
  168199. outptr = *output_buf++;
  168200. for (col = 0; col < num_cols; col++) {
  168201. y = GETJSAMPLE(inptr0[col]);
  168202. cb = GETJSAMPLE(inptr1[col]);
  168203. cr = GETJSAMPLE(inptr2[col]);
  168204. /* Range-limiting is essential due to noise introduced by DCT losses. */
  168205. outptr[RGB_RED] = range_limit[y + Crrtab[cr]];
  168206. outptr[RGB_GREEN] = range_limit[y +
  168207. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  168208. SCALEBITS))];
  168209. outptr[RGB_BLUE] = range_limit[y + Cbbtab[cb]];
  168210. outptr += RGB_PIXELSIZE;
  168211. }
  168212. }
  168213. }
  168214. /**************** Cases other than YCbCr -> RGB **************/
  168215. /*
  168216. * Color conversion for no colorspace change: just copy the data,
  168217. * converting from separate-planes to interleaved representation.
  168218. */
  168219. METHODDEF(void)
  168220. null_convert2 (j_decompress_ptr cinfo,
  168221. JSAMPIMAGE input_buf, JDIMENSION input_row,
  168222. JSAMPARRAY output_buf, int num_rows)
  168223. {
  168224. register JSAMPROW inptr, outptr;
  168225. register JDIMENSION count;
  168226. register int num_components = cinfo->num_components;
  168227. JDIMENSION num_cols = cinfo->output_width;
  168228. int ci;
  168229. while (--num_rows >= 0) {
  168230. for (ci = 0; ci < num_components; ci++) {
  168231. inptr = input_buf[ci][input_row];
  168232. outptr = output_buf[0] + ci;
  168233. for (count = num_cols; count > 0; count--) {
  168234. *outptr = *inptr++; /* needn't bother with GETJSAMPLE() here */
  168235. outptr += num_components;
  168236. }
  168237. }
  168238. input_row++;
  168239. output_buf++;
  168240. }
  168241. }
  168242. /*
  168243. * Color conversion for grayscale: just copy the data.
  168244. * This also works for YCbCr -> grayscale conversion, in which
  168245. * we just copy the Y (luminance) component and ignore chrominance.
  168246. */
  168247. METHODDEF(void)
  168248. grayscale_convert2 (j_decompress_ptr cinfo,
  168249. JSAMPIMAGE input_buf, JDIMENSION input_row,
  168250. JSAMPARRAY output_buf, int num_rows)
  168251. {
  168252. jcopy_sample_rows(input_buf[0], (int) input_row, output_buf, 0,
  168253. num_rows, cinfo->output_width);
  168254. }
  168255. /*
  168256. * Convert grayscale to RGB: just duplicate the graylevel three times.
  168257. * This is provided to support applications that don't want to cope
  168258. * with grayscale as a separate case.
  168259. */
  168260. METHODDEF(void)
  168261. gray_rgb_convert (j_decompress_ptr cinfo,
  168262. JSAMPIMAGE input_buf, JDIMENSION input_row,
  168263. JSAMPARRAY output_buf, int num_rows)
  168264. {
  168265. register JSAMPROW inptr, outptr;
  168266. register JDIMENSION col;
  168267. JDIMENSION num_cols = cinfo->output_width;
  168268. while (--num_rows >= 0) {
  168269. inptr = input_buf[0][input_row++];
  168270. outptr = *output_buf++;
  168271. for (col = 0; col < num_cols; col++) {
  168272. /* We can dispense with GETJSAMPLE() here */
  168273. outptr[RGB_RED] = outptr[RGB_GREEN] = outptr[RGB_BLUE] = inptr[col];
  168274. outptr += RGB_PIXELSIZE;
  168275. }
  168276. }
  168277. }
  168278. /*
  168279. * Adobe-style YCCK->CMYK conversion.
  168280. * We convert YCbCr to R=1-C, G=1-M, and B=1-Y using the same
  168281. * conversion as above, while passing K (black) unchanged.
  168282. * We assume build_ycc_rgb_table has been called.
  168283. */
  168284. METHODDEF(void)
  168285. ycck_cmyk_convert (j_decompress_ptr cinfo,
  168286. JSAMPIMAGE input_buf, JDIMENSION input_row,
  168287. JSAMPARRAY output_buf, int num_rows)
  168288. {
  168289. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  168290. register int y, cb, cr;
  168291. register JSAMPROW outptr;
  168292. register JSAMPROW inptr0, inptr1, inptr2, inptr3;
  168293. register JDIMENSION col;
  168294. JDIMENSION num_cols = cinfo->output_width;
  168295. /* copy these pointers into registers if possible */
  168296. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  168297. register int * Crrtab = cconvert->Cr_r_tab;
  168298. register int * Cbbtab = cconvert->Cb_b_tab;
  168299. register INT32 * Crgtab = cconvert->Cr_g_tab;
  168300. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  168301. SHIFT_TEMPS
  168302. while (--num_rows >= 0) {
  168303. inptr0 = input_buf[0][input_row];
  168304. inptr1 = input_buf[1][input_row];
  168305. inptr2 = input_buf[2][input_row];
  168306. inptr3 = input_buf[3][input_row];
  168307. input_row++;
  168308. outptr = *output_buf++;
  168309. for (col = 0; col < num_cols; col++) {
  168310. y = GETJSAMPLE(inptr0[col]);
  168311. cb = GETJSAMPLE(inptr1[col]);
  168312. cr = GETJSAMPLE(inptr2[col]);
  168313. /* Range-limiting is essential due to noise introduced by DCT losses. */
  168314. outptr[0] = range_limit[MAXJSAMPLE - (y + Crrtab[cr])]; /* red */
  168315. outptr[1] = range_limit[MAXJSAMPLE - (y + /* green */
  168316. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  168317. SCALEBITS)))];
  168318. outptr[2] = range_limit[MAXJSAMPLE - (y + Cbbtab[cb])]; /* blue */
  168319. /* K passes through unchanged */
  168320. outptr[3] = inptr3[col]; /* don't need GETJSAMPLE here */
  168321. outptr += 4;
  168322. }
  168323. }
  168324. }
  168325. /*
  168326. * Empty method for start_pass.
  168327. */
  168328. METHODDEF(void)
  168329. start_pass_dcolor (j_decompress_ptr)
  168330. {
  168331. /* no work needed */
  168332. }
  168333. /*
  168334. * Module initialization routine for output colorspace conversion.
  168335. */
  168336. GLOBAL(void)
  168337. jinit_color_deconverter (j_decompress_ptr cinfo)
  168338. {
  168339. my_cconvert_ptr2 cconvert;
  168340. int ci;
  168341. cconvert = (my_cconvert_ptr2)
  168342. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168343. SIZEOF(my_color_deconverter2));
  168344. cinfo->cconvert = (struct jpeg_color_deconverter *) cconvert;
  168345. cconvert->pub.start_pass = start_pass_dcolor;
  168346. /* Make sure num_components agrees with jpeg_color_space */
  168347. switch (cinfo->jpeg_color_space) {
  168348. case JCS_GRAYSCALE:
  168349. if (cinfo->num_components != 1)
  168350. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  168351. break;
  168352. case JCS_RGB:
  168353. case JCS_YCbCr:
  168354. if (cinfo->num_components != 3)
  168355. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  168356. break;
  168357. case JCS_CMYK:
  168358. case JCS_YCCK:
  168359. if (cinfo->num_components != 4)
  168360. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  168361. break;
  168362. default: /* JCS_UNKNOWN can be anything */
  168363. if (cinfo->num_components < 1)
  168364. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  168365. break;
  168366. }
  168367. /* Set out_color_components and conversion method based on requested space.
  168368. * Also clear the component_needed flags for any unused components,
  168369. * so that earlier pipeline stages can avoid useless computation.
  168370. */
  168371. switch (cinfo->out_color_space) {
  168372. case JCS_GRAYSCALE:
  168373. cinfo->out_color_components = 1;
  168374. if (cinfo->jpeg_color_space == JCS_GRAYSCALE ||
  168375. cinfo->jpeg_color_space == JCS_YCbCr) {
  168376. cconvert->pub.color_convert = grayscale_convert2;
  168377. /* For color->grayscale conversion, only the Y (0) component is needed */
  168378. for (ci = 1; ci < cinfo->num_components; ci++)
  168379. cinfo->comp_info[ci].component_needed = FALSE;
  168380. } else
  168381. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  168382. break;
  168383. case JCS_RGB:
  168384. cinfo->out_color_components = RGB_PIXELSIZE;
  168385. if (cinfo->jpeg_color_space == JCS_YCbCr) {
  168386. cconvert->pub.color_convert = ycc_rgb_convert;
  168387. build_ycc_rgb_table(cinfo);
  168388. } else if (cinfo->jpeg_color_space == JCS_GRAYSCALE) {
  168389. cconvert->pub.color_convert = gray_rgb_convert;
  168390. } else if (cinfo->jpeg_color_space == JCS_RGB && RGB_PIXELSIZE == 3) {
  168391. cconvert->pub.color_convert = null_convert2;
  168392. } else
  168393. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  168394. break;
  168395. case JCS_CMYK:
  168396. cinfo->out_color_components = 4;
  168397. if (cinfo->jpeg_color_space == JCS_YCCK) {
  168398. cconvert->pub.color_convert = ycck_cmyk_convert;
  168399. build_ycc_rgb_table(cinfo);
  168400. } else if (cinfo->jpeg_color_space == JCS_CMYK) {
  168401. cconvert->pub.color_convert = null_convert2;
  168402. } else
  168403. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  168404. break;
  168405. default:
  168406. /* Permit null conversion to same output space */
  168407. if (cinfo->out_color_space == cinfo->jpeg_color_space) {
  168408. cinfo->out_color_components = cinfo->num_components;
  168409. cconvert->pub.color_convert = null_convert2;
  168410. } else /* unsupported non-null conversion */
  168411. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  168412. break;
  168413. }
  168414. if (cinfo->quantize_colors)
  168415. cinfo->output_components = 1; /* single colormapped output component */
  168416. else
  168417. cinfo->output_components = cinfo->out_color_components;
  168418. }
  168419. /*** End of inlined file: jdcolor.c ***/
  168420. #undef FIX
  168421. /*** Start of inlined file: jddctmgr.c ***/
  168422. #define JPEG_INTERNALS
  168423. /*
  168424. * The decompressor input side (jdinput.c) saves away the appropriate
  168425. * quantization table for each component at the start of the first scan
  168426. * involving that component. (This is necessary in order to correctly
  168427. * decode files that reuse Q-table slots.)
  168428. * When we are ready to make an output pass, the saved Q-table is converted
  168429. * to a multiplier table that will actually be used by the IDCT routine.
  168430. * The multiplier table contents are IDCT-method-dependent. To support
  168431. * application changes in IDCT method between scans, we can remake the
  168432. * multiplier tables if necessary.
  168433. * In buffered-image mode, the first output pass may occur before any data
  168434. * has been seen for some components, and thus before their Q-tables have
  168435. * been saved away. To handle this case, multiplier tables are preset
  168436. * to zeroes; the result of the IDCT will be a neutral gray level.
  168437. */
  168438. /* Private subobject for this module */
  168439. typedef struct {
  168440. struct jpeg_inverse_dct pub; /* public fields */
  168441. /* This array contains the IDCT method code that each multiplier table
  168442. * is currently set up for, or -1 if it's not yet set up.
  168443. * The actual multiplier tables are pointed to by dct_table in the
  168444. * per-component comp_info structures.
  168445. */
  168446. int cur_method[MAX_COMPONENTS];
  168447. } my_idct_controller;
  168448. typedef my_idct_controller * my_idct_ptr;
  168449. /* Allocated multiplier tables: big enough for any supported variant */
  168450. typedef union {
  168451. ISLOW_MULT_TYPE islow_array[DCTSIZE2];
  168452. #ifdef DCT_IFAST_SUPPORTED
  168453. IFAST_MULT_TYPE ifast_array[DCTSIZE2];
  168454. #endif
  168455. #ifdef DCT_FLOAT_SUPPORTED
  168456. FLOAT_MULT_TYPE float_array[DCTSIZE2];
  168457. #endif
  168458. } multiplier_table;
  168459. /* The current scaled-IDCT routines require ISLOW-style multiplier tables,
  168460. * so be sure to compile that code if either ISLOW or SCALING is requested.
  168461. */
  168462. #ifdef DCT_ISLOW_SUPPORTED
  168463. #define PROVIDE_ISLOW_TABLES
  168464. #else
  168465. #ifdef IDCT_SCALING_SUPPORTED
  168466. #define PROVIDE_ISLOW_TABLES
  168467. #endif
  168468. #endif
  168469. /*
  168470. * Prepare for an output pass.
  168471. * Here we select the proper IDCT routine for each component and build
  168472. * a matching multiplier table.
  168473. */
  168474. METHODDEF(void)
  168475. start_pass (j_decompress_ptr cinfo)
  168476. {
  168477. my_idct_ptr idct = (my_idct_ptr) cinfo->idct;
  168478. int ci, i;
  168479. jpeg_component_info *compptr;
  168480. int method = 0;
  168481. inverse_DCT_method_ptr method_ptr = NULL;
  168482. JQUANT_TBL * qtbl;
  168483. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168484. ci++, compptr++) {
  168485. /* Select the proper IDCT routine for this component's scaling */
  168486. switch (compptr->DCT_scaled_size) {
  168487. #ifdef IDCT_SCALING_SUPPORTED
  168488. case 1:
  168489. method_ptr = jpeg_idct_1x1;
  168490. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  168491. break;
  168492. case 2:
  168493. method_ptr = jpeg_idct_2x2;
  168494. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  168495. break;
  168496. case 4:
  168497. method_ptr = jpeg_idct_4x4;
  168498. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  168499. break;
  168500. #endif
  168501. case DCTSIZE:
  168502. switch (cinfo->dct_method) {
  168503. #ifdef DCT_ISLOW_SUPPORTED
  168504. case JDCT_ISLOW:
  168505. method_ptr = jpeg_idct_islow;
  168506. method = JDCT_ISLOW;
  168507. break;
  168508. #endif
  168509. #ifdef DCT_IFAST_SUPPORTED
  168510. case JDCT_IFAST:
  168511. method_ptr = jpeg_idct_ifast;
  168512. method = JDCT_IFAST;
  168513. break;
  168514. #endif
  168515. #ifdef DCT_FLOAT_SUPPORTED
  168516. case JDCT_FLOAT:
  168517. method_ptr = jpeg_idct_float;
  168518. method = JDCT_FLOAT;
  168519. break;
  168520. #endif
  168521. default:
  168522. ERREXIT(cinfo, JERR_NOT_COMPILED);
  168523. break;
  168524. }
  168525. break;
  168526. default:
  168527. ERREXIT1(cinfo, JERR_BAD_DCTSIZE, compptr->DCT_scaled_size);
  168528. break;
  168529. }
  168530. idct->pub.inverse_DCT[ci] = method_ptr;
  168531. /* Create multiplier table from quant table.
  168532. * However, we can skip this if the component is uninteresting
  168533. * or if we already built the table. Also, if no quant table
  168534. * has yet been saved for the component, we leave the
  168535. * multiplier table all-zero; we'll be reading zeroes from the
  168536. * coefficient controller's buffer anyway.
  168537. */
  168538. if (! compptr->component_needed || idct->cur_method[ci] == method)
  168539. continue;
  168540. qtbl = compptr->quant_table;
  168541. if (qtbl == NULL) /* happens if no data yet for component */
  168542. continue;
  168543. idct->cur_method[ci] = method;
  168544. switch (method) {
  168545. #ifdef PROVIDE_ISLOW_TABLES
  168546. case JDCT_ISLOW:
  168547. {
  168548. /* For LL&M IDCT method, multipliers are equal to raw quantization
  168549. * coefficients, but are stored as ints to ensure access efficiency.
  168550. */
  168551. ISLOW_MULT_TYPE * ismtbl = (ISLOW_MULT_TYPE *) compptr->dct_table;
  168552. for (i = 0; i < DCTSIZE2; i++) {
  168553. ismtbl[i] = (ISLOW_MULT_TYPE) qtbl->quantval[i];
  168554. }
  168555. }
  168556. break;
  168557. #endif
  168558. #ifdef DCT_IFAST_SUPPORTED
  168559. case JDCT_IFAST:
  168560. {
  168561. /* For AA&N IDCT method, multipliers are equal to quantization
  168562. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  168563. * scalefactor[0] = 1
  168564. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  168565. * For integer operation, the multiplier table is to be scaled by
  168566. * IFAST_SCALE_BITS.
  168567. */
  168568. IFAST_MULT_TYPE * ifmtbl = (IFAST_MULT_TYPE *) compptr->dct_table;
  168569. #define CONST_BITS 14
  168570. static const INT16 aanscales[DCTSIZE2] = {
  168571. /* precomputed values scaled up by 14 bits */
  168572. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  168573. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  168574. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  168575. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  168576. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  168577. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  168578. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  168579. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  168580. };
  168581. SHIFT_TEMPS
  168582. for (i = 0; i < DCTSIZE2; i++) {
  168583. ifmtbl[i] = (IFAST_MULT_TYPE)
  168584. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  168585. (INT32) aanscales[i]),
  168586. CONST_BITS-IFAST_SCALE_BITS);
  168587. }
  168588. }
  168589. break;
  168590. #endif
  168591. #ifdef DCT_FLOAT_SUPPORTED
  168592. case JDCT_FLOAT:
  168593. {
  168594. /* For float AA&N IDCT method, multipliers are equal to quantization
  168595. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  168596. * scalefactor[0] = 1
  168597. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  168598. */
  168599. FLOAT_MULT_TYPE * fmtbl = (FLOAT_MULT_TYPE *) compptr->dct_table;
  168600. int row, col;
  168601. static const double aanscalefactor[DCTSIZE] = {
  168602. 1.0, 1.387039845, 1.306562965, 1.175875602,
  168603. 1.0, 0.785694958, 0.541196100, 0.275899379
  168604. };
  168605. i = 0;
  168606. for (row = 0; row < DCTSIZE; row++) {
  168607. for (col = 0; col < DCTSIZE; col++) {
  168608. fmtbl[i] = (FLOAT_MULT_TYPE)
  168609. ((double) qtbl->quantval[i] *
  168610. aanscalefactor[row] * aanscalefactor[col]);
  168611. i++;
  168612. }
  168613. }
  168614. }
  168615. break;
  168616. #endif
  168617. default:
  168618. ERREXIT(cinfo, JERR_NOT_COMPILED);
  168619. break;
  168620. }
  168621. }
  168622. }
  168623. /*
  168624. * Initialize IDCT manager.
  168625. */
  168626. GLOBAL(void)
  168627. jinit_inverse_dct (j_decompress_ptr cinfo)
  168628. {
  168629. my_idct_ptr idct;
  168630. int ci;
  168631. jpeg_component_info *compptr;
  168632. idct = (my_idct_ptr)
  168633. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168634. SIZEOF(my_idct_controller));
  168635. cinfo->idct = (struct jpeg_inverse_dct *) idct;
  168636. idct->pub.start_pass = start_pass;
  168637. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168638. ci++, compptr++) {
  168639. /* Allocate and pre-zero a multiplier table for each component */
  168640. compptr->dct_table =
  168641. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168642. SIZEOF(multiplier_table));
  168643. MEMZERO(compptr->dct_table, SIZEOF(multiplier_table));
  168644. /* Mark multiplier table not yet set up for any method */
  168645. idct->cur_method[ci] = -1;
  168646. }
  168647. }
  168648. /*** End of inlined file: jddctmgr.c ***/
  168649. #undef CONST_BITS
  168650. #undef ASSIGN_STATE
  168651. /*** Start of inlined file: jdhuff.c ***/
  168652. #define JPEG_INTERNALS
  168653. /*** Start of inlined file: jdhuff.h ***/
  168654. /* Short forms of external names for systems with brain-damaged linkers. */
  168655. #ifndef __jdhuff_h__
  168656. #define __jdhuff_h__
  168657. #ifdef NEED_SHORT_EXTERNAL_NAMES
  168658. #define jpeg_make_d_derived_tbl jMkDDerived
  168659. #define jpeg_fill_bit_buffer jFilBitBuf
  168660. #define jpeg_huff_decode jHufDecode
  168661. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  168662. /* Derived data constructed for each Huffman table */
  168663. #define HUFF_LOOKAHEAD 8 /* # of bits of lookahead */
  168664. typedef struct {
  168665. /* Basic tables: (element [0] of each array is unused) */
  168666. INT32 maxcode[18]; /* largest code of length k (-1 if none) */
  168667. /* (maxcode[17] is a sentinel to ensure jpeg_huff_decode terminates) */
  168668. INT32 valoffset[17]; /* huffval[] offset for codes of length k */
  168669. /* valoffset[k] = huffval[] index of 1st symbol of code length k, less
  168670. * the smallest code of length k; so given a code of length k, the
  168671. * corresponding symbol is huffval[code + valoffset[k]]
  168672. */
  168673. /* Link to public Huffman table (needed only in jpeg_huff_decode) */
  168674. JHUFF_TBL *pub;
  168675. /* Lookahead tables: indexed by the next HUFF_LOOKAHEAD bits of
  168676. * the input data stream. If the next Huffman code is no more
  168677. * than HUFF_LOOKAHEAD bits long, we can obtain its length and
  168678. * the corresponding symbol directly from these tables.
  168679. */
  168680. int look_nbits[1<<HUFF_LOOKAHEAD]; /* # bits, or 0 if too long */
  168681. UINT8 look_sym[1<<HUFF_LOOKAHEAD]; /* symbol, or unused */
  168682. } d_derived_tbl;
  168683. /* Expand a Huffman table definition into the derived format */
  168684. EXTERN(void) jpeg_make_d_derived_tbl
  168685. JPP((j_decompress_ptr cinfo, boolean isDC, int tblno,
  168686. d_derived_tbl ** pdtbl));
  168687. /*
  168688. * Fetching the next N bits from the input stream is a time-critical operation
  168689. * for the Huffman decoders. We implement it with a combination of inline
  168690. * macros and out-of-line subroutines. Note that N (the number of bits
  168691. * demanded at one time) never exceeds 15 for JPEG use.
  168692. *
  168693. * We read source bytes into get_buffer and dole out bits as needed.
  168694. * If get_buffer already contains enough bits, they are fetched in-line
  168695. * by the macros CHECK_BIT_BUFFER and GET_BITS. When there aren't enough
  168696. * bits, jpeg_fill_bit_buffer is called; it will attempt to fill get_buffer
  168697. * as full as possible (not just to the number of bits needed; this
  168698. * prefetching reduces the overhead cost of calling jpeg_fill_bit_buffer).
  168699. * Note that jpeg_fill_bit_buffer may return FALSE to indicate suspension.
  168700. * On TRUE return, jpeg_fill_bit_buffer guarantees that get_buffer contains
  168701. * at least the requested number of bits --- dummy zeroes are inserted if
  168702. * necessary.
  168703. */
  168704. typedef INT32 bit_buf_type; /* type of bit-extraction buffer */
  168705. #define BIT_BUF_SIZE 32 /* size of buffer in bits */
  168706. /* If long is > 32 bits on your machine, and shifting/masking longs is
  168707. * reasonably fast, making bit_buf_type be long and setting BIT_BUF_SIZE
  168708. * appropriately should be a win. Unfortunately we can't define the size
  168709. * with something like #define BIT_BUF_SIZE (sizeof(bit_buf_type)*8)
  168710. * because not all machines measure sizeof in 8-bit bytes.
  168711. */
  168712. typedef struct { /* Bitreading state saved across MCUs */
  168713. bit_buf_type get_buffer; /* current bit-extraction buffer */
  168714. int bits_left; /* # of unused bits in it */
  168715. } bitread_perm_state;
  168716. typedef struct { /* Bitreading working state within an MCU */
  168717. /* Current data source location */
  168718. /* We need a copy, rather than munging the original, in case of suspension */
  168719. const JOCTET * next_input_byte; /* => next byte to read from source */
  168720. size_t bytes_in_buffer; /* # of bytes remaining in source buffer */
  168721. /* Bit input buffer --- note these values are kept in register variables,
  168722. * not in this struct, inside the inner loops.
  168723. */
  168724. bit_buf_type get_buffer; /* current bit-extraction buffer */
  168725. int bits_left; /* # of unused bits in it */
  168726. /* Pointer needed by jpeg_fill_bit_buffer. */
  168727. j_decompress_ptr cinfo; /* back link to decompress master record */
  168728. } bitread_working_state;
  168729. /* Macros to declare and load/save bitread local variables. */
  168730. #define BITREAD_STATE_VARS \
  168731. register bit_buf_type get_buffer; \
  168732. register int bits_left; \
  168733. bitread_working_state br_state
  168734. #define BITREAD_LOAD_STATE(cinfop,permstate) \
  168735. br_state.cinfo = cinfop; \
  168736. br_state.next_input_byte = cinfop->src->next_input_byte; \
  168737. br_state.bytes_in_buffer = cinfop->src->bytes_in_buffer; \
  168738. get_buffer = permstate.get_buffer; \
  168739. bits_left = permstate.bits_left;
  168740. #define BITREAD_SAVE_STATE(cinfop,permstate) \
  168741. cinfop->src->next_input_byte = br_state.next_input_byte; \
  168742. cinfop->src->bytes_in_buffer = br_state.bytes_in_buffer; \
  168743. permstate.get_buffer = get_buffer; \
  168744. permstate.bits_left = bits_left
  168745. /*
  168746. * These macros provide the in-line portion of bit fetching.
  168747. * Use CHECK_BIT_BUFFER to ensure there are N bits in get_buffer
  168748. * before using GET_BITS, PEEK_BITS, or DROP_BITS.
  168749. * The variables get_buffer and bits_left are assumed to be locals,
  168750. * but the state struct might not be (jpeg_huff_decode needs this).
  168751. * CHECK_BIT_BUFFER(state,n,action);
  168752. * Ensure there are N bits in get_buffer; if suspend, take action.
  168753. * val = GET_BITS(n);
  168754. * Fetch next N bits.
  168755. * val = PEEK_BITS(n);
  168756. * Fetch next N bits without removing them from the buffer.
  168757. * DROP_BITS(n);
  168758. * Discard next N bits.
  168759. * The value N should be a simple variable, not an expression, because it
  168760. * is evaluated multiple times.
  168761. */
  168762. #define CHECK_BIT_BUFFER(state,nbits,action) \
  168763. { if (bits_left < (nbits)) { \
  168764. if (! jpeg_fill_bit_buffer(&(state),get_buffer,bits_left,nbits)) \
  168765. { action; } \
  168766. get_buffer = (state).get_buffer; bits_left = (state).bits_left; } }
  168767. #define GET_BITS(nbits) \
  168768. (((int) (get_buffer >> (bits_left -= (nbits)))) & ((1<<(nbits))-1))
  168769. #define PEEK_BITS(nbits) \
  168770. (((int) (get_buffer >> (bits_left - (nbits)))) & ((1<<(nbits))-1))
  168771. #define DROP_BITS(nbits) \
  168772. (bits_left -= (nbits))
  168773. /* Load up the bit buffer to a depth of at least nbits */
  168774. EXTERN(boolean) jpeg_fill_bit_buffer
  168775. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  168776. register int bits_left, int nbits));
  168777. /*
  168778. * Code for extracting next Huffman-coded symbol from input bit stream.
  168779. * Again, this is time-critical and we make the main paths be macros.
  168780. *
  168781. * We use a lookahead table to process codes of up to HUFF_LOOKAHEAD bits
  168782. * without looping. Usually, more than 95% of the Huffman codes will be 8
  168783. * or fewer bits long. The few overlength codes are handled with a loop,
  168784. * which need not be inline code.
  168785. *
  168786. * Notes about the HUFF_DECODE macro:
  168787. * 1. Near the end of the data segment, we may fail to get enough bits
  168788. * for a lookahead. In that case, we do it the hard way.
  168789. * 2. If the lookahead table contains no entry, the next code must be
  168790. * more than HUFF_LOOKAHEAD bits long.
  168791. * 3. jpeg_huff_decode returns -1 if forced to suspend.
  168792. */
  168793. #define HUFF_DECODE(result,state,htbl,failaction,slowlabel) \
  168794. { register int nb, look; \
  168795. if (bits_left < HUFF_LOOKAHEAD) { \
  168796. if (! jpeg_fill_bit_buffer(&state,get_buffer,bits_left, 0)) {failaction;} \
  168797. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  168798. if (bits_left < HUFF_LOOKAHEAD) { \
  168799. nb = 1; goto slowlabel; \
  168800. } \
  168801. } \
  168802. look = PEEK_BITS(HUFF_LOOKAHEAD); \
  168803. if ((nb = htbl->look_nbits[look]) != 0) { \
  168804. DROP_BITS(nb); \
  168805. result = htbl->look_sym[look]; \
  168806. } else { \
  168807. nb = HUFF_LOOKAHEAD+1; \
  168808. slowlabel: \
  168809. if ((result=jpeg_huff_decode(&state,get_buffer,bits_left,htbl,nb)) < 0) \
  168810. { failaction; } \
  168811. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  168812. } \
  168813. }
  168814. /* Out-of-line case for Huffman code fetching */
  168815. EXTERN(int) jpeg_huff_decode
  168816. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  168817. register int bits_left, d_derived_tbl * htbl, int min_bits));
  168818. #endif
  168819. /*** End of inlined file: jdhuff.h ***/
  168820. /* Declarations shared with jdphuff.c */
  168821. /*
  168822. * Expanded entropy decoder object for Huffman decoding.
  168823. *
  168824. * The savable_state subrecord contains fields that change within an MCU,
  168825. * but must not be updated permanently until we complete the MCU.
  168826. */
  168827. typedef struct {
  168828. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  168829. } savable_state2;
  168830. /* This macro is to work around compilers with missing or broken
  168831. * structure assignment. You'll need to fix this code if you have
  168832. * such a compiler and you change MAX_COMPS_IN_SCAN.
  168833. */
  168834. #ifndef NO_STRUCT_ASSIGN
  168835. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  168836. #else
  168837. #if MAX_COMPS_IN_SCAN == 4
  168838. #define ASSIGN_STATE(dest,src) \
  168839. ((dest).last_dc_val[0] = (src).last_dc_val[0], \
  168840. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  168841. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  168842. (dest).last_dc_val[3] = (src).last_dc_val[3])
  168843. #endif
  168844. #endif
  168845. typedef struct {
  168846. struct jpeg_entropy_decoder pub; /* public fields */
  168847. /* These fields are loaded into local variables at start of each MCU.
  168848. * In case of suspension, we exit WITHOUT updating them.
  168849. */
  168850. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  168851. savable_state2 saved; /* Other state at start of MCU */
  168852. /* These fields are NOT loaded into local working state. */
  168853. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  168854. /* Pointers to derived tables (these workspaces have image lifespan) */
  168855. d_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  168856. d_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  168857. /* Precalculated info set up by start_pass for use in decode_mcu: */
  168858. /* Pointers to derived tables to be used for each block within an MCU */
  168859. d_derived_tbl * dc_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  168860. d_derived_tbl * ac_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  168861. /* Whether we care about the DC and AC coefficient values for each block */
  168862. boolean dc_needed[D_MAX_BLOCKS_IN_MCU];
  168863. boolean ac_needed[D_MAX_BLOCKS_IN_MCU];
  168864. } huff_entropy_decoder2;
  168865. typedef huff_entropy_decoder2 * huff_entropy_ptr2;
  168866. /*
  168867. * Initialize for a Huffman-compressed scan.
  168868. */
  168869. METHODDEF(void)
  168870. start_pass_huff_decoder (j_decompress_ptr cinfo)
  168871. {
  168872. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  168873. int ci, blkn, dctbl, actbl;
  168874. jpeg_component_info * compptr;
  168875. /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
  168876. * This ought to be an error condition, but we make it a warning because
  168877. * there are some baseline files out there with all zeroes in these bytes.
  168878. */
  168879. if (cinfo->Ss != 0 || cinfo->Se != DCTSIZE2-1 ||
  168880. cinfo->Ah != 0 || cinfo->Al != 0)
  168881. WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
  168882. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168883. compptr = cinfo->cur_comp_info[ci];
  168884. dctbl = compptr->dc_tbl_no;
  168885. actbl = compptr->ac_tbl_no;
  168886. /* Compute derived values for Huffman tables */
  168887. /* We may do this more than once for a table, but it's not expensive */
  168888. jpeg_make_d_derived_tbl(cinfo, TRUE, dctbl,
  168889. & entropy->dc_derived_tbls[dctbl]);
  168890. jpeg_make_d_derived_tbl(cinfo, FALSE, actbl,
  168891. & entropy->ac_derived_tbls[actbl]);
  168892. /* Initialize DC predictions to 0 */
  168893. entropy->saved.last_dc_val[ci] = 0;
  168894. }
  168895. /* Precalculate decoding info for each block in an MCU of this scan */
  168896. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  168897. ci = cinfo->MCU_membership[blkn];
  168898. compptr = cinfo->cur_comp_info[ci];
  168899. /* Precalculate which table to use for each block */
  168900. entropy->dc_cur_tbls[blkn] = entropy->dc_derived_tbls[compptr->dc_tbl_no];
  168901. entropy->ac_cur_tbls[blkn] = entropy->ac_derived_tbls[compptr->ac_tbl_no];
  168902. /* Decide whether we really care about the coefficient values */
  168903. if (compptr->component_needed) {
  168904. entropy->dc_needed[blkn] = TRUE;
  168905. /* we don't need the ACs if producing a 1/8th-size image */
  168906. entropy->ac_needed[blkn] = (compptr->DCT_scaled_size > 1);
  168907. } else {
  168908. entropy->dc_needed[blkn] = entropy->ac_needed[blkn] = FALSE;
  168909. }
  168910. }
  168911. /* Initialize bitread state variables */
  168912. entropy->bitstate.bits_left = 0;
  168913. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  168914. entropy->pub.insufficient_data = FALSE;
  168915. /* Initialize restart counter */
  168916. entropy->restarts_to_go = cinfo->restart_interval;
  168917. }
  168918. /*
  168919. * Compute the derived values for a Huffman table.
  168920. * This routine also performs some validation checks on the table.
  168921. *
  168922. * Note this is also used by jdphuff.c.
  168923. */
  168924. GLOBAL(void)
  168925. jpeg_make_d_derived_tbl (j_decompress_ptr cinfo, boolean isDC, int tblno,
  168926. d_derived_tbl ** pdtbl)
  168927. {
  168928. JHUFF_TBL *htbl;
  168929. d_derived_tbl *dtbl;
  168930. int p, i, l, si, numsymbols;
  168931. int lookbits, ctr;
  168932. char huffsize[257];
  168933. unsigned int huffcode[257];
  168934. unsigned int code;
  168935. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  168936. * paralleling the order of the symbols themselves in htbl->huffval[].
  168937. */
  168938. /* Find the input Huffman table */
  168939. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  168940. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  168941. htbl =
  168942. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  168943. if (htbl == NULL)
  168944. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  168945. /* Allocate a workspace if we haven't already done so. */
  168946. if (*pdtbl == NULL)
  168947. *pdtbl = (d_derived_tbl *)
  168948. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168949. SIZEOF(d_derived_tbl));
  168950. dtbl = *pdtbl;
  168951. dtbl->pub = htbl; /* fill in back link */
  168952. /* Figure C.1: make table of Huffman code length for each symbol */
  168953. p = 0;
  168954. for (l = 1; l <= 16; l++) {
  168955. i = (int) htbl->bits[l];
  168956. if (i < 0 || p + i > 256) /* protect against table overrun */
  168957. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  168958. while (i--)
  168959. huffsize[p++] = (char) l;
  168960. }
  168961. huffsize[p] = 0;
  168962. numsymbols = p;
  168963. /* Figure C.2: generate the codes themselves */
  168964. /* We also validate that the counts represent a legal Huffman code tree. */
  168965. code = 0;
  168966. si = huffsize[0];
  168967. p = 0;
  168968. while (huffsize[p]) {
  168969. while (((int) huffsize[p]) == si) {
  168970. huffcode[p++] = code;
  168971. code++;
  168972. }
  168973. /* code is now 1 more than the last code used for codelength si; but
  168974. * it must still fit in si bits, since no code is allowed to be all ones.
  168975. */
  168976. if (((INT32) code) >= (((INT32) 1) << si))
  168977. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  168978. code <<= 1;
  168979. si++;
  168980. }
  168981. /* Figure F.15: generate decoding tables for bit-sequential decoding */
  168982. p = 0;
  168983. for (l = 1; l <= 16; l++) {
  168984. if (htbl->bits[l]) {
  168985. /* valoffset[l] = huffval[] index of 1st symbol of code length l,
  168986. * minus the minimum code of length l
  168987. */
  168988. dtbl->valoffset[l] = (INT32) p - (INT32) huffcode[p];
  168989. p += htbl->bits[l];
  168990. dtbl->maxcode[l] = huffcode[p-1]; /* maximum code of length l */
  168991. } else {
  168992. dtbl->maxcode[l] = -1; /* -1 if no codes of this length */
  168993. }
  168994. }
  168995. dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates */
  168996. /* Compute lookahead tables to speed up decoding.
  168997. * First we set all the table entries to 0, indicating "too long";
  168998. * then we iterate through the Huffman codes that are short enough and
  168999. * fill in all the entries that correspond to bit sequences starting
  169000. * with that code.
  169001. */
  169002. MEMZERO(dtbl->look_nbits, SIZEOF(dtbl->look_nbits));
  169003. p = 0;
  169004. for (l = 1; l <= HUFF_LOOKAHEAD; l++) {
  169005. for (i = 1; i <= (int) htbl->bits[l]; i++, p++) {
  169006. /* l = current code's length, p = its index in huffcode[] & huffval[]. */
  169007. /* Generate left-justified code followed by all possible bit sequences */
  169008. lookbits = huffcode[p] << (HUFF_LOOKAHEAD-l);
  169009. for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) {
  169010. dtbl->look_nbits[lookbits] = l;
  169011. dtbl->look_sym[lookbits] = htbl->huffval[p];
  169012. lookbits++;
  169013. }
  169014. }
  169015. }
  169016. /* Validate symbols as being reasonable.
  169017. * For AC tables, we make no check, but accept all byte values 0..255.
  169018. * For DC tables, we require the symbols to be in range 0..15.
  169019. * (Tighter bounds could be applied depending on the data depth and mode,
  169020. * but this is sufficient to ensure safe decoding.)
  169021. */
  169022. if (isDC) {
  169023. for (i = 0; i < numsymbols; i++) {
  169024. int sym = htbl->huffval[i];
  169025. if (sym < 0 || sym > 15)
  169026. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  169027. }
  169028. }
  169029. }
  169030. /*
  169031. * Out-of-line code for bit fetching (shared with jdphuff.c).
  169032. * See jdhuff.h for info about usage.
  169033. * Note: current values of get_buffer and bits_left are passed as parameters,
  169034. * but are returned in the corresponding fields of the state struct.
  169035. *
  169036. * On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width
  169037. * of get_buffer to be used. (On machines with wider words, an even larger
  169038. * buffer could be used.) However, on some machines 32-bit shifts are
  169039. * quite slow and take time proportional to the number of places shifted.
  169040. * (This is true with most PC compilers, for instance.) In this case it may
  169041. * be a win to set MIN_GET_BITS to the minimum value of 15. This reduces the
  169042. * average shift distance at the cost of more calls to jpeg_fill_bit_buffer.
  169043. */
  169044. #ifdef SLOW_SHIFT_32
  169045. #define MIN_GET_BITS 15 /* minimum allowable value */
  169046. #else
  169047. #define MIN_GET_BITS (BIT_BUF_SIZE-7)
  169048. #endif
  169049. GLOBAL(boolean)
  169050. jpeg_fill_bit_buffer (bitread_working_state * state,
  169051. register bit_buf_type get_buffer, register int bits_left,
  169052. int nbits)
  169053. /* Load up the bit buffer to a depth of at least nbits */
  169054. {
  169055. /* Copy heavily used state fields into locals (hopefully registers) */
  169056. register const JOCTET * next_input_byte = state->next_input_byte;
  169057. register size_t bytes_in_buffer = state->bytes_in_buffer;
  169058. j_decompress_ptr cinfo = state->cinfo;
  169059. /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */
  169060. /* (It is assumed that no request will be for more than that many bits.) */
  169061. /* We fail to do so only if we hit a marker or are forced to suspend. */
  169062. if (cinfo->unread_marker == 0) { /* cannot advance past a marker */
  169063. while (bits_left < MIN_GET_BITS) {
  169064. register int c;
  169065. /* Attempt to read a byte */
  169066. if (bytes_in_buffer == 0) {
  169067. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  169068. return FALSE;
  169069. next_input_byte = cinfo->src->next_input_byte;
  169070. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  169071. }
  169072. bytes_in_buffer--;
  169073. c = GETJOCTET(*next_input_byte++);
  169074. /* If it's 0xFF, check and discard stuffed zero byte */
  169075. if (c == 0xFF) {
  169076. /* Loop here to discard any padding FF's on terminating marker,
  169077. * so that we can save a valid unread_marker value. NOTE: we will
  169078. * accept multiple FF's followed by a 0 as meaning a single FF data
  169079. * byte. This data pattern is not valid according to the standard.
  169080. */
  169081. do {
  169082. if (bytes_in_buffer == 0) {
  169083. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  169084. return FALSE;
  169085. next_input_byte = cinfo->src->next_input_byte;
  169086. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  169087. }
  169088. bytes_in_buffer--;
  169089. c = GETJOCTET(*next_input_byte++);
  169090. } while (c == 0xFF);
  169091. if (c == 0) {
  169092. /* Found FF/00, which represents an FF data byte */
  169093. c = 0xFF;
  169094. } else {
  169095. /* Oops, it's actually a marker indicating end of compressed data.
  169096. * Save the marker code for later use.
  169097. * Fine point: it might appear that we should save the marker into
  169098. * bitread working state, not straight into permanent state. But
  169099. * once we have hit a marker, we cannot need to suspend within the
  169100. * current MCU, because we will read no more bytes from the data
  169101. * source. So it is OK to update permanent state right away.
  169102. */
  169103. cinfo->unread_marker = c;
  169104. /* See if we need to insert some fake zero bits. */
  169105. goto no_more_bytes;
  169106. }
  169107. }
  169108. /* OK, load c into get_buffer */
  169109. get_buffer = (get_buffer << 8) | c;
  169110. bits_left += 8;
  169111. } /* end while */
  169112. } else {
  169113. no_more_bytes:
  169114. /* We get here if we've read the marker that terminates the compressed
  169115. * data segment. There should be enough bits in the buffer register
  169116. * to satisfy the request; if so, no problem.
  169117. */
  169118. if (nbits > bits_left) {
  169119. /* Uh-oh. Report corrupted data to user and stuff zeroes into
  169120. * the data stream, so that we can produce some kind of image.
  169121. * We use a nonvolatile flag to ensure that only one warning message
  169122. * appears per data segment.
  169123. */
  169124. if (! cinfo->entropy->insufficient_data) {
  169125. WARNMS(cinfo, JWRN_HIT_MARKER);
  169126. cinfo->entropy->insufficient_data = TRUE;
  169127. }
  169128. /* Fill the buffer with zero bits */
  169129. get_buffer <<= MIN_GET_BITS - bits_left;
  169130. bits_left = MIN_GET_BITS;
  169131. }
  169132. }
  169133. /* Unload the local registers */
  169134. state->next_input_byte = next_input_byte;
  169135. state->bytes_in_buffer = bytes_in_buffer;
  169136. state->get_buffer = get_buffer;
  169137. state->bits_left = bits_left;
  169138. return TRUE;
  169139. }
  169140. /*
  169141. * Out-of-line code for Huffman code decoding.
  169142. * See jdhuff.h for info about usage.
  169143. */
  169144. GLOBAL(int)
  169145. jpeg_huff_decode (bitread_working_state * state,
  169146. register bit_buf_type get_buffer, register int bits_left,
  169147. d_derived_tbl * htbl, int min_bits)
  169148. {
  169149. register int l = min_bits;
  169150. register INT32 code;
  169151. /* HUFF_DECODE has determined that the code is at least min_bits */
  169152. /* bits long, so fetch that many bits in one swoop. */
  169153. CHECK_BIT_BUFFER(*state, l, return -1);
  169154. code = GET_BITS(l);
  169155. /* Collect the rest of the Huffman code one bit at a time. */
  169156. /* This is per Figure F.16 in the JPEG spec. */
  169157. while (code > htbl->maxcode[l]) {
  169158. code <<= 1;
  169159. CHECK_BIT_BUFFER(*state, 1, return -1);
  169160. code |= GET_BITS(1);
  169161. l++;
  169162. }
  169163. /* Unload the local registers */
  169164. state->get_buffer = get_buffer;
  169165. state->bits_left = bits_left;
  169166. /* With garbage input we may reach the sentinel value l = 17. */
  169167. if (l > 16) {
  169168. WARNMS(state->cinfo, JWRN_HUFF_BAD_CODE);
  169169. return 0; /* fake a zero as the safest result */
  169170. }
  169171. return htbl->pub->huffval[ (int) (code + htbl->valoffset[l]) ];
  169172. }
  169173. /*
  169174. * Check for a restart marker & resynchronize decoder.
  169175. * Returns FALSE if must suspend.
  169176. */
  169177. LOCAL(boolean)
  169178. process_restart (j_decompress_ptr cinfo)
  169179. {
  169180. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  169181. int ci;
  169182. /* Throw away any unused bits remaining in bit buffer; */
  169183. /* include any full bytes in next_marker's count of discarded bytes */
  169184. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  169185. entropy->bitstate.bits_left = 0;
  169186. /* Advance past the RSTn marker */
  169187. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  169188. return FALSE;
  169189. /* Re-initialize DC predictions to 0 */
  169190. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  169191. entropy->saved.last_dc_val[ci] = 0;
  169192. /* Reset restart counter */
  169193. entropy->restarts_to_go = cinfo->restart_interval;
  169194. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  169195. * against a marker. In that case we will end up treating the next data
  169196. * segment as empty, and we can avoid producing bogus output pixels by
  169197. * leaving the flag set.
  169198. */
  169199. if (cinfo->unread_marker == 0)
  169200. entropy->pub.insufficient_data = FALSE;
  169201. return TRUE;
  169202. }
  169203. /*
  169204. * Decode and return one MCU's worth of Huffman-compressed coefficients.
  169205. * The coefficients are reordered from zigzag order into natural array order,
  169206. * but are not dequantized.
  169207. *
  169208. * The i'th block of the MCU is stored into the block pointed to by
  169209. * MCU_data[i]. WE ASSUME THIS AREA HAS BEEN ZEROED BY THE CALLER.
  169210. * (Wholesale zeroing is usually a little faster than retail...)
  169211. *
  169212. * Returns FALSE if data source requested suspension. In that case no
  169213. * changes have been made to permanent state. (Exception: some output
  169214. * coefficients may already have been assigned. This is harmless for
  169215. * this module, since we'll just re-assign them on the next call.)
  169216. */
  169217. METHODDEF(boolean)
  169218. decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  169219. {
  169220. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  169221. int blkn;
  169222. BITREAD_STATE_VARS;
  169223. savable_state2 state;
  169224. /* Process restart marker if needed; may have to suspend */
  169225. if (cinfo->restart_interval) {
  169226. if (entropy->restarts_to_go == 0)
  169227. if (! process_restart(cinfo))
  169228. return FALSE;
  169229. }
  169230. /* If we've run out of data, just leave the MCU set to zeroes.
  169231. * This way, we return uniform gray for the remainder of the segment.
  169232. */
  169233. if (! entropy->pub.insufficient_data) {
  169234. /* Load up working state */
  169235. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  169236. ASSIGN_STATE(state, entropy->saved);
  169237. /* Outer loop handles each block in the MCU */
  169238. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  169239. JBLOCKROW block = MCU_data[blkn];
  169240. d_derived_tbl * dctbl = entropy->dc_cur_tbls[blkn];
  169241. d_derived_tbl * actbl = entropy->ac_cur_tbls[blkn];
  169242. register int s, k, r;
  169243. /* Decode a single block's worth of coefficients */
  169244. /* Section F.2.2.1: decode the DC coefficient difference */
  169245. HUFF_DECODE(s, br_state, dctbl, return FALSE, label1);
  169246. if (s) {
  169247. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  169248. r = GET_BITS(s);
  169249. s = HUFF_EXTEND(r, s);
  169250. }
  169251. if (entropy->dc_needed[blkn]) {
  169252. /* Convert DC difference to actual value, update last_dc_val */
  169253. int ci = cinfo->MCU_membership[blkn];
  169254. s += state.last_dc_val[ci];
  169255. state.last_dc_val[ci] = s;
  169256. /* Output the DC coefficient (assumes jpeg_natural_order[0] = 0) */
  169257. (*block)[0] = (JCOEF) s;
  169258. }
  169259. if (entropy->ac_needed[blkn]) {
  169260. /* Section F.2.2.2: decode the AC coefficients */
  169261. /* Since zeroes are skipped, output area must be cleared beforehand */
  169262. for (k = 1; k < DCTSIZE2; k++) {
  169263. HUFF_DECODE(s, br_state, actbl, return FALSE, label2);
  169264. r = s >> 4;
  169265. s &= 15;
  169266. if (s) {
  169267. k += r;
  169268. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  169269. r = GET_BITS(s);
  169270. s = HUFF_EXTEND(r, s);
  169271. /* Output coefficient in natural (dezigzagged) order.
  169272. * Note: the extra entries in jpeg_natural_order[] will save us
  169273. * if k >= DCTSIZE2, which could happen if the data is corrupted.
  169274. */
  169275. (*block)[jpeg_natural_order[k]] = (JCOEF) s;
  169276. } else {
  169277. if (r != 15)
  169278. break;
  169279. k += 15;
  169280. }
  169281. }
  169282. } else {
  169283. /* Section F.2.2.2: decode the AC coefficients */
  169284. /* In this path we just discard the values */
  169285. for (k = 1; k < DCTSIZE2; k++) {
  169286. HUFF_DECODE(s, br_state, actbl, return FALSE, label3);
  169287. r = s >> 4;
  169288. s &= 15;
  169289. if (s) {
  169290. k += r;
  169291. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  169292. DROP_BITS(s);
  169293. } else {
  169294. if (r != 15)
  169295. break;
  169296. k += 15;
  169297. }
  169298. }
  169299. }
  169300. }
  169301. /* Completed MCU, so update state */
  169302. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  169303. ASSIGN_STATE(entropy->saved, state);
  169304. }
  169305. /* Account for restart interval (no-op if not using restarts) */
  169306. entropy->restarts_to_go--;
  169307. return TRUE;
  169308. }
  169309. /*
  169310. * Module initialization routine for Huffman entropy decoding.
  169311. */
  169312. GLOBAL(void)
  169313. jinit_huff_decoder (j_decompress_ptr cinfo)
  169314. {
  169315. huff_entropy_ptr2 entropy;
  169316. int i;
  169317. entropy = (huff_entropy_ptr2)
  169318. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169319. SIZEOF(huff_entropy_decoder2));
  169320. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  169321. entropy->pub.start_pass = start_pass_huff_decoder;
  169322. entropy->pub.decode_mcu = decode_mcu;
  169323. /* Mark tables unallocated */
  169324. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  169325. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  169326. }
  169327. }
  169328. /*** End of inlined file: jdhuff.c ***/
  169329. /*** Start of inlined file: jdinput.c ***/
  169330. #define JPEG_INTERNALS
  169331. /* Private state */
  169332. typedef struct {
  169333. struct jpeg_input_controller pub; /* public fields */
  169334. boolean inheaders; /* TRUE until first SOS is reached */
  169335. } my_input_controller;
  169336. typedef my_input_controller * my_inputctl_ptr;
  169337. /* Forward declarations */
  169338. METHODDEF(int) consume_markers JPP((j_decompress_ptr cinfo));
  169339. /*
  169340. * Routines to calculate various quantities related to the size of the image.
  169341. */
  169342. LOCAL(void)
  169343. initial_setup2 (j_decompress_ptr cinfo)
  169344. /* Called once, when first SOS marker is reached */
  169345. {
  169346. int ci;
  169347. jpeg_component_info *compptr;
  169348. /* Make sure image isn't bigger than I can handle */
  169349. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  169350. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  169351. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  169352. /* For now, precision must match compiled-in value... */
  169353. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  169354. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  169355. /* Check that number of components won't exceed internal array sizes */
  169356. if (cinfo->num_components > MAX_COMPONENTS)
  169357. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  169358. MAX_COMPONENTS);
  169359. /* Compute maximum sampling factors; check factor validity */
  169360. cinfo->max_h_samp_factor = 1;
  169361. cinfo->max_v_samp_factor = 1;
  169362. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169363. ci++, compptr++) {
  169364. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  169365. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  169366. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  169367. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  169368. compptr->h_samp_factor);
  169369. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  169370. compptr->v_samp_factor);
  169371. }
  169372. /* We initialize DCT_scaled_size and min_DCT_scaled_size to DCTSIZE.
  169373. * In the full decompressor, this will be overridden by jdmaster.c;
  169374. * but in the transcoder, jdmaster.c is not used, so we must do it here.
  169375. */
  169376. cinfo->min_DCT_scaled_size = DCTSIZE;
  169377. /* Compute dimensions of components */
  169378. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169379. ci++, compptr++) {
  169380. compptr->DCT_scaled_size = DCTSIZE;
  169381. /* Size in DCT blocks */
  169382. compptr->width_in_blocks = (JDIMENSION)
  169383. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  169384. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  169385. compptr->height_in_blocks = (JDIMENSION)
  169386. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  169387. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  169388. /* downsampled_width and downsampled_height will also be overridden by
  169389. * jdmaster.c if we are doing full decompression. The transcoder library
  169390. * doesn't use these values, but the calling application might.
  169391. */
  169392. /* Size in samples */
  169393. compptr->downsampled_width = (JDIMENSION)
  169394. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  169395. (long) cinfo->max_h_samp_factor);
  169396. compptr->downsampled_height = (JDIMENSION)
  169397. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  169398. (long) cinfo->max_v_samp_factor);
  169399. /* Mark component needed, until color conversion says otherwise */
  169400. compptr->component_needed = TRUE;
  169401. /* Mark no quantization table yet saved for component */
  169402. compptr->quant_table = NULL;
  169403. }
  169404. /* Compute number of fully interleaved MCU rows. */
  169405. cinfo->total_iMCU_rows = (JDIMENSION)
  169406. jdiv_round_up((long) cinfo->image_height,
  169407. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  169408. /* Decide whether file contains multiple scans */
  169409. if (cinfo->comps_in_scan < cinfo->num_components || cinfo->progressive_mode)
  169410. cinfo->inputctl->has_multiple_scans = TRUE;
  169411. else
  169412. cinfo->inputctl->has_multiple_scans = FALSE;
  169413. }
  169414. LOCAL(void)
  169415. per_scan_setup2 (j_decompress_ptr cinfo)
  169416. /* Do computations that are needed before processing a JPEG scan */
  169417. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] were set from SOS marker */
  169418. {
  169419. int ci, mcublks, tmp;
  169420. jpeg_component_info *compptr;
  169421. if (cinfo->comps_in_scan == 1) {
  169422. /* Noninterleaved (single-component) scan */
  169423. compptr = cinfo->cur_comp_info[0];
  169424. /* Overall image size in MCUs */
  169425. cinfo->MCUs_per_row = compptr->width_in_blocks;
  169426. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  169427. /* For noninterleaved scan, always one block per MCU */
  169428. compptr->MCU_width = 1;
  169429. compptr->MCU_height = 1;
  169430. compptr->MCU_blocks = 1;
  169431. compptr->MCU_sample_width = compptr->DCT_scaled_size;
  169432. compptr->last_col_width = 1;
  169433. /* For noninterleaved scans, it is convenient to define last_row_height
  169434. * as the number of block rows present in the last iMCU row.
  169435. */
  169436. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  169437. if (tmp == 0) tmp = compptr->v_samp_factor;
  169438. compptr->last_row_height = tmp;
  169439. /* Prepare array describing MCU composition */
  169440. cinfo->blocks_in_MCU = 1;
  169441. cinfo->MCU_membership[0] = 0;
  169442. } else {
  169443. /* Interleaved (multi-component) scan */
  169444. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  169445. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  169446. MAX_COMPS_IN_SCAN);
  169447. /* Overall image size in MCUs */
  169448. cinfo->MCUs_per_row = (JDIMENSION)
  169449. jdiv_round_up((long) cinfo->image_width,
  169450. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  169451. cinfo->MCU_rows_in_scan = (JDIMENSION)
  169452. jdiv_round_up((long) cinfo->image_height,
  169453. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  169454. cinfo->blocks_in_MCU = 0;
  169455. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  169456. compptr = cinfo->cur_comp_info[ci];
  169457. /* Sampling factors give # of blocks of component in each MCU */
  169458. compptr->MCU_width = compptr->h_samp_factor;
  169459. compptr->MCU_height = compptr->v_samp_factor;
  169460. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  169461. compptr->MCU_sample_width = compptr->MCU_width * compptr->DCT_scaled_size;
  169462. /* Figure number of non-dummy blocks in last MCU column & row */
  169463. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  169464. if (tmp == 0) tmp = compptr->MCU_width;
  169465. compptr->last_col_width = tmp;
  169466. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  169467. if (tmp == 0) tmp = compptr->MCU_height;
  169468. compptr->last_row_height = tmp;
  169469. /* Prepare array describing MCU composition */
  169470. mcublks = compptr->MCU_blocks;
  169471. if (cinfo->blocks_in_MCU + mcublks > D_MAX_BLOCKS_IN_MCU)
  169472. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  169473. while (mcublks-- > 0) {
  169474. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  169475. }
  169476. }
  169477. }
  169478. }
  169479. /*
  169480. * Save away a copy of the Q-table referenced by each component present
  169481. * in the current scan, unless already saved during a prior scan.
  169482. *
  169483. * In a multiple-scan JPEG file, the encoder could assign different components
  169484. * the same Q-table slot number, but change table definitions between scans
  169485. * so that each component uses a different Q-table. (The IJG encoder is not
  169486. * currently capable of doing this, but other encoders might.) Since we want
  169487. * to be able to dequantize all the components at the end of the file, this
  169488. * means that we have to save away the table actually used for each component.
  169489. * We do this by copying the table at the start of the first scan containing
  169490. * the component.
  169491. * The JPEG spec prohibits the encoder from changing the contents of a Q-table
  169492. * slot between scans of a component using that slot. If the encoder does so
  169493. * anyway, this decoder will simply use the Q-table values that were current
  169494. * at the start of the first scan for the component.
  169495. *
  169496. * The decompressor output side looks only at the saved quant tables,
  169497. * not at the current Q-table slots.
  169498. */
  169499. LOCAL(void)
  169500. latch_quant_tables (j_decompress_ptr cinfo)
  169501. {
  169502. int ci, qtblno;
  169503. jpeg_component_info *compptr;
  169504. JQUANT_TBL * qtbl;
  169505. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  169506. compptr = cinfo->cur_comp_info[ci];
  169507. /* No work if we already saved Q-table for this component */
  169508. if (compptr->quant_table != NULL)
  169509. continue;
  169510. /* Make sure specified quantization table is present */
  169511. qtblno = compptr->quant_tbl_no;
  169512. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  169513. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  169514. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  169515. /* OK, save away the quantization table */
  169516. qtbl = (JQUANT_TBL *)
  169517. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169518. SIZEOF(JQUANT_TBL));
  169519. MEMCOPY(qtbl, cinfo->quant_tbl_ptrs[qtblno], SIZEOF(JQUANT_TBL));
  169520. compptr->quant_table = qtbl;
  169521. }
  169522. }
  169523. /*
  169524. * Initialize the input modules to read a scan of compressed data.
  169525. * The first call to this is done by jdmaster.c after initializing
  169526. * the entire decompressor (during jpeg_start_decompress).
  169527. * Subsequent calls come from consume_markers, below.
  169528. */
  169529. METHODDEF(void)
  169530. start_input_pass2 (j_decompress_ptr cinfo)
  169531. {
  169532. per_scan_setup2(cinfo);
  169533. latch_quant_tables(cinfo);
  169534. (*cinfo->entropy->start_pass) (cinfo);
  169535. (*cinfo->coef->start_input_pass) (cinfo);
  169536. cinfo->inputctl->consume_input = cinfo->coef->consume_data;
  169537. }
  169538. /*
  169539. * Finish up after inputting a compressed-data scan.
  169540. * This is called by the coefficient controller after it's read all
  169541. * the expected data of the scan.
  169542. */
  169543. METHODDEF(void)
  169544. finish_input_pass (j_decompress_ptr cinfo)
  169545. {
  169546. cinfo->inputctl->consume_input = consume_markers;
  169547. }
  169548. /*
  169549. * Read JPEG markers before, between, or after compressed-data scans.
  169550. * Change state as necessary when a new scan is reached.
  169551. * Return value is JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  169552. *
  169553. * The consume_input method pointer points either here or to the
  169554. * coefficient controller's consume_data routine, depending on whether
  169555. * we are reading a compressed data segment or inter-segment markers.
  169556. */
  169557. METHODDEF(int)
  169558. consume_markers (j_decompress_ptr cinfo)
  169559. {
  169560. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  169561. int val;
  169562. if (inputctl->pub.eoi_reached) /* After hitting EOI, read no further */
  169563. return JPEG_REACHED_EOI;
  169564. val = (*cinfo->marker->read_markers) (cinfo);
  169565. switch (val) {
  169566. case JPEG_REACHED_SOS: /* Found SOS */
  169567. if (inputctl->inheaders) { /* 1st SOS */
  169568. initial_setup2(cinfo);
  169569. inputctl->inheaders = FALSE;
  169570. /* Note: start_input_pass must be called by jdmaster.c
  169571. * before any more input can be consumed. jdapimin.c is
  169572. * responsible for enforcing this sequencing.
  169573. */
  169574. } else { /* 2nd or later SOS marker */
  169575. if (! inputctl->pub.has_multiple_scans)
  169576. ERREXIT(cinfo, JERR_EOI_EXPECTED); /* Oops, I wasn't expecting this! */
  169577. start_input_pass2(cinfo);
  169578. }
  169579. break;
  169580. case JPEG_REACHED_EOI: /* Found EOI */
  169581. inputctl->pub.eoi_reached = TRUE;
  169582. if (inputctl->inheaders) { /* Tables-only datastream, apparently */
  169583. if (cinfo->marker->saw_SOF)
  169584. ERREXIT(cinfo, JERR_SOF_NO_SOS);
  169585. } else {
  169586. /* Prevent infinite loop in coef ctlr's decompress_data routine
  169587. * if user set output_scan_number larger than number of scans.
  169588. */
  169589. if (cinfo->output_scan_number > cinfo->input_scan_number)
  169590. cinfo->output_scan_number = cinfo->input_scan_number;
  169591. }
  169592. break;
  169593. case JPEG_SUSPENDED:
  169594. break;
  169595. }
  169596. return val;
  169597. }
  169598. /*
  169599. * Reset state to begin a fresh datastream.
  169600. */
  169601. METHODDEF(void)
  169602. reset_input_controller (j_decompress_ptr cinfo)
  169603. {
  169604. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  169605. inputctl->pub.consume_input = consume_markers;
  169606. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  169607. inputctl->pub.eoi_reached = FALSE;
  169608. inputctl->inheaders = TRUE;
  169609. /* Reset other modules */
  169610. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  169611. (*cinfo->marker->reset_marker_reader) (cinfo);
  169612. /* Reset progression state -- would be cleaner if entropy decoder did this */
  169613. cinfo->coef_bits = NULL;
  169614. }
  169615. /*
  169616. * Initialize the input controller module.
  169617. * This is called only once, when the decompression object is created.
  169618. */
  169619. GLOBAL(void)
  169620. jinit_input_controller (j_decompress_ptr cinfo)
  169621. {
  169622. my_inputctl_ptr inputctl;
  169623. /* Create subobject in permanent pool */
  169624. inputctl = (my_inputctl_ptr)
  169625. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  169626. SIZEOF(my_input_controller));
  169627. cinfo->inputctl = (struct jpeg_input_controller *) inputctl;
  169628. /* Initialize method pointers */
  169629. inputctl->pub.consume_input = consume_markers;
  169630. inputctl->pub.reset_input_controller = reset_input_controller;
  169631. inputctl->pub.start_input_pass = start_input_pass2;
  169632. inputctl->pub.finish_input_pass = finish_input_pass;
  169633. /* Initialize state: can't use reset_input_controller since we don't
  169634. * want to try to reset other modules yet.
  169635. */
  169636. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  169637. inputctl->pub.eoi_reached = FALSE;
  169638. inputctl->inheaders = TRUE;
  169639. }
  169640. /*** End of inlined file: jdinput.c ***/
  169641. /*** Start of inlined file: jdmainct.c ***/
  169642. #define JPEG_INTERNALS
  169643. /*
  169644. * In the current system design, the main buffer need never be a full-image
  169645. * buffer; any full-height buffers will be found inside the coefficient or
  169646. * postprocessing controllers. Nonetheless, the main controller is not
  169647. * trivial. Its responsibility is to provide context rows for upsampling/
  169648. * rescaling, and doing this in an efficient fashion is a bit tricky.
  169649. *
  169650. * Postprocessor input data is counted in "row groups". A row group
  169651. * is defined to be (v_samp_factor * DCT_scaled_size / min_DCT_scaled_size)
  169652. * sample rows of each component. (We require DCT_scaled_size values to be
  169653. * chosen such that these numbers are integers. In practice DCT_scaled_size
  169654. * values will likely be powers of two, so we actually have the stronger
  169655. * condition that DCT_scaled_size / min_DCT_scaled_size is an integer.)
  169656. * Upsampling will typically produce max_v_samp_factor pixel rows from each
  169657. * row group (times any additional scale factor that the upsampler is
  169658. * applying).
  169659. *
  169660. * The coefficient controller will deliver data to us one iMCU row at a time;
  169661. * each iMCU row contains v_samp_factor * DCT_scaled_size sample rows, or
  169662. * exactly min_DCT_scaled_size row groups. (This amount of data corresponds
  169663. * to one row of MCUs when the image is fully interleaved.) Note that the
  169664. * number of sample rows varies across components, but the number of row
  169665. * groups does not. Some garbage sample rows may be included in the last iMCU
  169666. * row at the bottom of the image.
  169667. *
  169668. * Depending on the vertical scaling algorithm used, the upsampler may need
  169669. * access to the sample row(s) above and below its current input row group.
  169670. * The upsampler is required to set need_context_rows TRUE at global selection
  169671. * time if so. When need_context_rows is FALSE, this controller can simply
  169672. * obtain one iMCU row at a time from the coefficient controller and dole it
  169673. * out as row groups to the postprocessor.
  169674. *
  169675. * When need_context_rows is TRUE, this controller guarantees that the buffer
  169676. * passed to postprocessing contains at least one row group's worth of samples
  169677. * above and below the row group(s) being processed. Note that the context
  169678. * rows "above" the first passed row group appear at negative row offsets in
  169679. * the passed buffer. At the top and bottom of the image, the required
  169680. * context rows are manufactured by duplicating the first or last real sample
  169681. * row; this avoids having special cases in the upsampling inner loops.
  169682. *
  169683. * The amount of context is fixed at one row group just because that's a
  169684. * convenient number for this controller to work with. The existing
  169685. * upsamplers really only need one sample row of context. An upsampler
  169686. * supporting arbitrary output rescaling might wish for more than one row
  169687. * group of context when shrinking the image; tough, we don't handle that.
  169688. * (This is justified by the assumption that downsizing will be handled mostly
  169689. * by adjusting the DCT_scaled_size values, so that the actual scale factor at
  169690. * the upsample step needn't be much less than one.)
  169691. *
  169692. * To provide the desired context, we have to retain the last two row groups
  169693. * of one iMCU row while reading in the next iMCU row. (The last row group
  169694. * can't be processed until we have another row group for its below-context,
  169695. * and so we have to save the next-to-last group too for its above-context.)
  169696. * We could do this most simply by copying data around in our buffer, but
  169697. * that'd be very slow. We can avoid copying any data by creating a rather
  169698. * strange pointer structure. Here's how it works. We allocate a workspace
  169699. * consisting of M+2 row groups (where M = min_DCT_scaled_size is the number
  169700. * of row groups per iMCU row). We create two sets of redundant pointers to
  169701. * the workspace. Labeling the physical row groups 0 to M+1, the synthesized
  169702. * pointer lists look like this:
  169703. * M+1 M-1
  169704. * master pointer --> 0 master pointer --> 0
  169705. * 1 1
  169706. * ... ...
  169707. * M-3 M-3
  169708. * M-2 M
  169709. * M-1 M+1
  169710. * M M-2
  169711. * M+1 M-1
  169712. * 0 0
  169713. * We read alternate iMCU rows using each master pointer; thus the last two
  169714. * row groups of the previous iMCU row remain un-overwritten in the workspace.
  169715. * The pointer lists are set up so that the required context rows appear to
  169716. * be adjacent to the proper places when we pass the pointer lists to the
  169717. * upsampler.
  169718. *
  169719. * The above pictures describe the normal state of the pointer lists.
  169720. * At top and bottom of the image, we diddle the pointer lists to duplicate
  169721. * the first or last sample row as necessary (this is cheaper than copying
  169722. * sample rows around).
  169723. *
  169724. * This scheme breaks down if M < 2, ie, min_DCT_scaled_size is 1. In that
  169725. * situation each iMCU row provides only one row group so the buffering logic
  169726. * must be different (eg, we must read two iMCU rows before we can emit the
  169727. * first row group). For now, we simply do not support providing context
  169728. * rows when min_DCT_scaled_size is 1. That combination seems unlikely to
  169729. * be worth providing --- if someone wants a 1/8th-size preview, they probably
  169730. * want it quick and dirty, so a context-free upsampler is sufficient.
  169731. */
  169732. /* Private buffer controller object */
  169733. typedef struct {
  169734. struct jpeg_d_main_controller pub; /* public fields */
  169735. /* Pointer to allocated workspace (M or M+2 row groups). */
  169736. JSAMPARRAY buffer[MAX_COMPONENTS];
  169737. boolean buffer_full; /* Have we gotten an iMCU row from decoder? */
  169738. JDIMENSION rowgroup_ctr; /* counts row groups output to postprocessor */
  169739. /* Remaining fields are only used in the context case. */
  169740. /* These are the master pointers to the funny-order pointer lists. */
  169741. JSAMPIMAGE xbuffer[2]; /* pointers to weird pointer lists */
  169742. int whichptr; /* indicates which pointer set is now in use */
  169743. int context_state; /* process_data state machine status */
  169744. JDIMENSION rowgroups_avail; /* row groups available to postprocessor */
  169745. JDIMENSION iMCU_row_ctr; /* counts iMCU rows to detect image top/bot */
  169746. } my_main_controller4;
  169747. typedef my_main_controller4 * my_main_ptr4;
  169748. /* context_state values: */
  169749. #define CTX_PREPARE_FOR_IMCU 0 /* need to prepare for MCU row */
  169750. #define CTX_PROCESS_IMCU 1 /* feeding iMCU to postprocessor */
  169751. #define CTX_POSTPONED_ROW 2 /* feeding postponed row group */
  169752. /* Forward declarations */
  169753. METHODDEF(void) process_data_simple_main2
  169754. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  169755. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  169756. METHODDEF(void) process_data_context_main
  169757. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  169758. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  169759. #ifdef QUANT_2PASS_SUPPORTED
  169760. METHODDEF(void) process_data_crank_post
  169761. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  169762. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  169763. #endif
  169764. LOCAL(void)
  169765. alloc_funny_pointers (j_decompress_ptr cinfo)
  169766. /* Allocate space for the funny pointer lists.
  169767. * This is done only once, not once per pass.
  169768. */
  169769. {
  169770. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  169771. int ci, rgroup;
  169772. int M = cinfo->min_DCT_scaled_size;
  169773. jpeg_component_info *compptr;
  169774. JSAMPARRAY xbuf;
  169775. /* Get top-level space for component array pointers.
  169776. * We alloc both arrays with one call to save a few cycles.
  169777. */
  169778. main_->xbuffer[0] = (JSAMPIMAGE)
  169779. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169780. cinfo->num_components * 2 * SIZEOF(JSAMPARRAY));
  169781. main_->xbuffer[1] = main_->xbuffer[0] + cinfo->num_components;
  169782. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169783. ci++, compptr++) {
  169784. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  169785. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  169786. /* Get space for pointer lists --- M+4 row groups in each list.
  169787. * We alloc both pointer lists with one call to save a few cycles.
  169788. */
  169789. xbuf = (JSAMPARRAY)
  169790. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169791. 2 * (rgroup * (M + 4)) * SIZEOF(JSAMPROW));
  169792. xbuf += rgroup; /* want one row group at negative offsets */
  169793. main_->xbuffer[0][ci] = xbuf;
  169794. xbuf += rgroup * (M + 4);
  169795. main_->xbuffer[1][ci] = xbuf;
  169796. }
  169797. }
  169798. LOCAL(void)
  169799. make_funny_pointers (j_decompress_ptr cinfo)
  169800. /* Create the funny pointer lists discussed in the comments above.
  169801. * The actual workspace is already allocated (in main->buffer),
  169802. * and the space for the pointer lists is allocated too.
  169803. * This routine just fills in the curiously ordered lists.
  169804. * This will be repeated at the beginning of each pass.
  169805. */
  169806. {
  169807. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  169808. int ci, i, rgroup;
  169809. int M = cinfo->min_DCT_scaled_size;
  169810. jpeg_component_info *compptr;
  169811. JSAMPARRAY buf, xbuf0, xbuf1;
  169812. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169813. ci++, compptr++) {
  169814. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  169815. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  169816. xbuf0 = main_->xbuffer[0][ci];
  169817. xbuf1 = main_->xbuffer[1][ci];
  169818. /* First copy the workspace pointers as-is */
  169819. buf = main_->buffer[ci];
  169820. for (i = 0; i < rgroup * (M + 2); i++) {
  169821. xbuf0[i] = xbuf1[i] = buf[i];
  169822. }
  169823. /* In the second list, put the last four row groups in swapped order */
  169824. for (i = 0; i < rgroup * 2; i++) {
  169825. xbuf1[rgroup*(M-2) + i] = buf[rgroup*M + i];
  169826. xbuf1[rgroup*M + i] = buf[rgroup*(M-2) + i];
  169827. }
  169828. /* The wraparound pointers at top and bottom will be filled later
  169829. * (see set_wraparound_pointers, below). Initially we want the "above"
  169830. * pointers to duplicate the first actual data line. This only needs
  169831. * to happen in xbuffer[0].
  169832. */
  169833. for (i = 0; i < rgroup; i++) {
  169834. xbuf0[i - rgroup] = xbuf0[0];
  169835. }
  169836. }
  169837. }
  169838. LOCAL(void)
  169839. set_wraparound_pointers (j_decompress_ptr cinfo)
  169840. /* Set up the "wraparound" pointers at top and bottom of the pointer lists.
  169841. * This changes the pointer list state from top-of-image to the normal state.
  169842. */
  169843. {
  169844. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  169845. int ci, i, rgroup;
  169846. int M = cinfo->min_DCT_scaled_size;
  169847. jpeg_component_info *compptr;
  169848. JSAMPARRAY xbuf0, xbuf1;
  169849. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169850. ci++, compptr++) {
  169851. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  169852. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  169853. xbuf0 = main_->xbuffer[0][ci];
  169854. xbuf1 = main_->xbuffer[1][ci];
  169855. for (i = 0; i < rgroup; i++) {
  169856. xbuf0[i - rgroup] = xbuf0[rgroup*(M+1) + i];
  169857. xbuf1[i - rgroup] = xbuf1[rgroup*(M+1) + i];
  169858. xbuf0[rgroup*(M+2) + i] = xbuf0[i];
  169859. xbuf1[rgroup*(M+2) + i] = xbuf1[i];
  169860. }
  169861. }
  169862. }
  169863. LOCAL(void)
  169864. set_bottom_pointers (j_decompress_ptr cinfo)
  169865. /* Change the pointer lists to duplicate the last sample row at the bottom
  169866. * of the image. whichptr indicates which xbuffer holds the final iMCU row.
  169867. * Also sets rowgroups_avail to indicate number of nondummy row groups in row.
  169868. */
  169869. {
  169870. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  169871. int ci, i, rgroup, iMCUheight, rows_left;
  169872. jpeg_component_info *compptr;
  169873. JSAMPARRAY xbuf;
  169874. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169875. ci++, compptr++) {
  169876. /* Count sample rows in one iMCU row and in one row group */
  169877. iMCUheight = compptr->v_samp_factor * compptr->DCT_scaled_size;
  169878. rgroup = iMCUheight / cinfo->min_DCT_scaled_size;
  169879. /* Count nondummy sample rows remaining for this component */
  169880. rows_left = (int) (compptr->downsampled_height % (JDIMENSION) iMCUheight);
  169881. if (rows_left == 0) rows_left = iMCUheight;
  169882. /* Count nondummy row groups. Should get same answer for each component,
  169883. * so we need only do it once.
  169884. */
  169885. if (ci == 0) {
  169886. main_->rowgroups_avail = (JDIMENSION) ((rows_left-1) / rgroup + 1);
  169887. }
  169888. /* Duplicate the last real sample row rgroup*2 times; this pads out the
  169889. * last partial rowgroup and ensures at least one full rowgroup of context.
  169890. */
  169891. xbuf = main_->xbuffer[main_->whichptr][ci];
  169892. for (i = 0; i < rgroup * 2; i++) {
  169893. xbuf[rows_left + i] = xbuf[rows_left-1];
  169894. }
  169895. }
  169896. }
  169897. /*
  169898. * Initialize for a processing pass.
  169899. */
  169900. METHODDEF(void)
  169901. start_pass_main2 (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  169902. {
  169903. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  169904. switch (pass_mode) {
  169905. case JBUF_PASS_THRU:
  169906. if (cinfo->upsample->need_context_rows) {
  169907. main_->pub.process_data = process_data_context_main;
  169908. make_funny_pointers(cinfo); /* Create the xbuffer[] lists */
  169909. main_->whichptr = 0; /* Read first iMCU row into xbuffer[0] */
  169910. main_->context_state = CTX_PREPARE_FOR_IMCU;
  169911. main_->iMCU_row_ctr = 0;
  169912. } else {
  169913. /* Simple case with no context needed */
  169914. main_->pub.process_data = process_data_simple_main2;
  169915. }
  169916. main_->buffer_full = FALSE; /* Mark buffer empty */
  169917. main_->rowgroup_ctr = 0;
  169918. break;
  169919. #ifdef QUANT_2PASS_SUPPORTED
  169920. case JBUF_CRANK_DEST:
  169921. /* For last pass of 2-pass quantization, just crank the postprocessor */
  169922. main_->pub.process_data = process_data_crank_post;
  169923. break;
  169924. #endif
  169925. default:
  169926. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  169927. break;
  169928. }
  169929. }
  169930. /*
  169931. * Process some data.
  169932. * This handles the simple case where no context is required.
  169933. */
  169934. METHODDEF(void)
  169935. process_data_simple_main2 (j_decompress_ptr cinfo,
  169936. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  169937. JDIMENSION out_rows_avail)
  169938. {
  169939. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  169940. JDIMENSION rowgroups_avail;
  169941. /* Read input data if we haven't filled the main buffer yet */
  169942. if (! main_->buffer_full) {
  169943. if (! (*cinfo->coef->decompress_data) (cinfo, main_->buffer))
  169944. return; /* suspension forced, can do nothing more */
  169945. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  169946. }
  169947. /* There are always min_DCT_scaled_size row groups in an iMCU row. */
  169948. rowgroups_avail = (JDIMENSION) cinfo->min_DCT_scaled_size;
  169949. /* Note: at the bottom of the image, we may pass extra garbage row groups
  169950. * to the postprocessor. The postprocessor has to check for bottom
  169951. * of image anyway (at row resolution), so no point in us doing it too.
  169952. */
  169953. /* Feed the postprocessor */
  169954. (*cinfo->post->post_process_data) (cinfo, main_->buffer,
  169955. &main_->rowgroup_ctr, rowgroups_avail,
  169956. output_buf, out_row_ctr, out_rows_avail);
  169957. /* Has postprocessor consumed all the data yet? If so, mark buffer empty */
  169958. if (main_->rowgroup_ctr >= rowgroups_avail) {
  169959. main_->buffer_full = FALSE;
  169960. main_->rowgroup_ctr = 0;
  169961. }
  169962. }
  169963. /*
  169964. * Process some data.
  169965. * This handles the case where context rows must be provided.
  169966. */
  169967. METHODDEF(void)
  169968. process_data_context_main (j_decompress_ptr cinfo,
  169969. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  169970. JDIMENSION out_rows_avail)
  169971. {
  169972. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  169973. /* Read input data if we haven't filled the main buffer yet */
  169974. if (! main_->buffer_full) {
  169975. if (! (*cinfo->coef->decompress_data) (cinfo,
  169976. main_->xbuffer[main_->whichptr]))
  169977. return; /* suspension forced, can do nothing more */
  169978. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  169979. main_->iMCU_row_ctr++; /* count rows received */
  169980. }
  169981. /* Postprocessor typically will not swallow all the input data it is handed
  169982. * in one call (due to filling the output buffer first). Must be prepared
  169983. * to exit and restart. This switch lets us keep track of how far we got.
  169984. * Note that each case falls through to the next on successful completion.
  169985. */
  169986. switch (main_->context_state) {
  169987. case CTX_POSTPONED_ROW:
  169988. /* Call postprocessor using previously set pointers for postponed row */
  169989. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  169990. &main_->rowgroup_ctr, main_->rowgroups_avail,
  169991. output_buf, out_row_ctr, out_rows_avail);
  169992. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  169993. return; /* Need to suspend */
  169994. main_->context_state = CTX_PREPARE_FOR_IMCU;
  169995. if (*out_row_ctr >= out_rows_avail)
  169996. return; /* Postprocessor exactly filled output buf */
  169997. /*FALLTHROUGH*/
  169998. case CTX_PREPARE_FOR_IMCU:
  169999. /* Prepare to process first M-1 row groups of this iMCU row */
  170000. main_->rowgroup_ctr = 0;
  170001. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size - 1);
  170002. /* Check for bottom of image: if so, tweak pointers to "duplicate"
  170003. * the last sample row, and adjust rowgroups_avail to ignore padding rows.
  170004. */
  170005. if (main_->iMCU_row_ctr == cinfo->total_iMCU_rows)
  170006. set_bottom_pointers(cinfo);
  170007. main_->context_state = CTX_PROCESS_IMCU;
  170008. /*FALLTHROUGH*/
  170009. case CTX_PROCESS_IMCU:
  170010. /* Call postprocessor using previously set pointers */
  170011. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  170012. &main_->rowgroup_ctr, main_->rowgroups_avail,
  170013. output_buf, out_row_ctr, out_rows_avail);
  170014. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  170015. return; /* Need to suspend */
  170016. /* After the first iMCU, change wraparound pointers to normal state */
  170017. if (main_->iMCU_row_ctr == 1)
  170018. set_wraparound_pointers(cinfo);
  170019. /* Prepare to load new iMCU row using other xbuffer list */
  170020. main_->whichptr ^= 1; /* 0=>1 or 1=>0 */
  170021. main_->buffer_full = FALSE;
  170022. /* Still need to process last row group of this iMCU row, */
  170023. /* which is saved at index M+1 of the other xbuffer */
  170024. main_->rowgroup_ctr = (JDIMENSION) (cinfo->min_DCT_scaled_size + 1);
  170025. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size + 2);
  170026. main_->context_state = CTX_POSTPONED_ROW;
  170027. }
  170028. }
  170029. /*
  170030. * Process some data.
  170031. * Final pass of two-pass quantization: just call the postprocessor.
  170032. * Source data will be the postprocessor controller's internal buffer.
  170033. */
  170034. #ifdef QUANT_2PASS_SUPPORTED
  170035. METHODDEF(void)
  170036. process_data_crank_post (j_decompress_ptr cinfo,
  170037. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170038. JDIMENSION out_rows_avail)
  170039. {
  170040. (*cinfo->post->post_process_data) (cinfo, (JSAMPIMAGE) NULL,
  170041. (JDIMENSION *) NULL, (JDIMENSION) 0,
  170042. output_buf, out_row_ctr, out_rows_avail);
  170043. }
  170044. #endif /* QUANT_2PASS_SUPPORTED */
  170045. /*
  170046. * Initialize main buffer controller.
  170047. */
  170048. GLOBAL(void)
  170049. jinit_d_main_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  170050. {
  170051. my_main_ptr4 main_;
  170052. int ci, rgroup, ngroups;
  170053. jpeg_component_info *compptr;
  170054. main_ = (my_main_ptr4)
  170055. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170056. SIZEOF(my_main_controller4));
  170057. cinfo->main = (struct jpeg_d_main_controller *) main_;
  170058. main_->pub.start_pass = start_pass_main2;
  170059. if (need_full_buffer) /* shouldn't happen */
  170060. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  170061. /* Allocate the workspace.
  170062. * ngroups is the number of row groups we need.
  170063. */
  170064. if (cinfo->upsample->need_context_rows) {
  170065. if (cinfo->min_DCT_scaled_size < 2) /* unsupported, see comments above */
  170066. ERREXIT(cinfo, JERR_NOTIMPL);
  170067. alloc_funny_pointers(cinfo); /* Alloc space for xbuffer[] lists */
  170068. ngroups = cinfo->min_DCT_scaled_size + 2;
  170069. } else {
  170070. ngroups = cinfo->min_DCT_scaled_size;
  170071. }
  170072. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170073. ci++, compptr++) {
  170074. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170075. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170076. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  170077. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170078. compptr->width_in_blocks * compptr->DCT_scaled_size,
  170079. (JDIMENSION) (rgroup * ngroups));
  170080. }
  170081. }
  170082. /*** End of inlined file: jdmainct.c ***/
  170083. /*** Start of inlined file: jdmarker.c ***/
  170084. #define JPEG_INTERNALS
  170085. /* Private state */
  170086. typedef struct {
  170087. struct jpeg_marker_reader pub; /* public fields */
  170088. /* Application-overridable marker processing methods */
  170089. jpeg_marker_parser_method process_COM;
  170090. jpeg_marker_parser_method process_APPn[16];
  170091. /* Limit on marker data length to save for each marker type */
  170092. unsigned int length_limit_COM;
  170093. unsigned int length_limit_APPn[16];
  170094. /* Status of COM/APPn marker saving */
  170095. jpeg_saved_marker_ptr cur_marker; /* NULL if not processing a marker */
  170096. unsigned int bytes_read; /* data bytes read so far in marker */
  170097. /* Note: cur_marker is not linked into marker_list until it's all read. */
  170098. } my_marker_reader;
  170099. typedef my_marker_reader * my_marker_ptr2;
  170100. /*
  170101. * Macros for fetching data from the data source module.
  170102. *
  170103. * At all times, cinfo->src->next_input_byte and ->bytes_in_buffer reflect
  170104. * the current restart point; we update them only when we have reached a
  170105. * suitable place to restart if a suspension occurs.
  170106. */
  170107. /* Declare and initialize local copies of input pointer/count */
  170108. #define INPUT_VARS(cinfo) \
  170109. struct jpeg_source_mgr * datasrc = (cinfo)->src; \
  170110. const JOCTET * next_input_byte = datasrc->next_input_byte; \
  170111. size_t bytes_in_buffer = datasrc->bytes_in_buffer
  170112. /* Unload the local copies --- do this only at a restart boundary */
  170113. #define INPUT_SYNC(cinfo) \
  170114. ( datasrc->next_input_byte = next_input_byte, \
  170115. datasrc->bytes_in_buffer = bytes_in_buffer )
  170116. /* Reload the local copies --- used only in MAKE_BYTE_AVAIL */
  170117. #define INPUT_RELOAD(cinfo) \
  170118. ( next_input_byte = datasrc->next_input_byte, \
  170119. bytes_in_buffer = datasrc->bytes_in_buffer )
  170120. /* Internal macro for INPUT_BYTE and INPUT_2BYTES: make a byte available.
  170121. * Note we do *not* do INPUT_SYNC before calling fill_input_buffer,
  170122. * but we must reload the local copies after a successful fill.
  170123. */
  170124. #define MAKE_BYTE_AVAIL(cinfo,action) \
  170125. if (bytes_in_buffer == 0) { \
  170126. if (! (*datasrc->fill_input_buffer) (cinfo)) \
  170127. { action; } \
  170128. INPUT_RELOAD(cinfo); \
  170129. }
  170130. /* Read a byte into variable V.
  170131. * If must suspend, take the specified action (typically "return FALSE").
  170132. */
  170133. #define INPUT_BYTE(cinfo,V,action) \
  170134. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  170135. bytes_in_buffer--; \
  170136. V = GETJOCTET(*next_input_byte++); )
  170137. /* As above, but read two bytes interpreted as an unsigned 16-bit integer.
  170138. * V should be declared unsigned int or perhaps INT32.
  170139. */
  170140. #define INPUT_2BYTES(cinfo,V,action) \
  170141. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  170142. bytes_in_buffer--; \
  170143. V = ((unsigned int) GETJOCTET(*next_input_byte++)) << 8; \
  170144. MAKE_BYTE_AVAIL(cinfo,action); \
  170145. bytes_in_buffer--; \
  170146. V += GETJOCTET(*next_input_byte++); )
  170147. /*
  170148. * Routines to process JPEG markers.
  170149. *
  170150. * Entry condition: JPEG marker itself has been read and its code saved
  170151. * in cinfo->unread_marker; input restart point is just after the marker.
  170152. *
  170153. * Exit: if return TRUE, have read and processed any parameters, and have
  170154. * updated the restart point to point after the parameters.
  170155. * If return FALSE, was forced to suspend before reaching end of
  170156. * marker parameters; restart point has not been moved. Same routine
  170157. * will be called again after application supplies more input data.
  170158. *
  170159. * This approach to suspension assumes that all of a marker's parameters
  170160. * can fit into a single input bufferload. This should hold for "normal"
  170161. * markers. Some COM/APPn markers might have large parameter segments
  170162. * that might not fit. If we are simply dropping such a marker, we use
  170163. * skip_input_data to get past it, and thereby put the problem on the
  170164. * source manager's shoulders. If we are saving the marker's contents
  170165. * into memory, we use a slightly different convention: when forced to
  170166. * suspend, the marker processor updates the restart point to the end of
  170167. * what it's consumed (ie, the end of the buffer) before returning FALSE.
  170168. * On resumption, cinfo->unread_marker still contains the marker code,
  170169. * but the data source will point to the next chunk of marker data.
  170170. * The marker processor must retain internal state to deal with this.
  170171. *
  170172. * Note that we don't bother to avoid duplicate trace messages if a
  170173. * suspension occurs within marker parameters. Other side effects
  170174. * require more care.
  170175. */
  170176. LOCAL(boolean)
  170177. get_soi (j_decompress_ptr cinfo)
  170178. /* Process an SOI marker */
  170179. {
  170180. int i;
  170181. TRACEMS(cinfo, 1, JTRC_SOI);
  170182. if (cinfo->marker->saw_SOI)
  170183. ERREXIT(cinfo, JERR_SOI_DUPLICATE);
  170184. /* Reset all parameters that are defined to be reset by SOI */
  170185. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  170186. cinfo->arith_dc_L[i] = 0;
  170187. cinfo->arith_dc_U[i] = 1;
  170188. cinfo->arith_ac_K[i] = 5;
  170189. }
  170190. cinfo->restart_interval = 0;
  170191. /* Set initial assumptions for colorspace etc */
  170192. cinfo->jpeg_color_space = JCS_UNKNOWN;
  170193. cinfo->CCIR601_sampling = FALSE; /* Assume non-CCIR sampling??? */
  170194. cinfo->saw_JFIF_marker = FALSE;
  170195. cinfo->JFIF_major_version = 1; /* set default JFIF APP0 values */
  170196. cinfo->JFIF_minor_version = 1;
  170197. cinfo->density_unit = 0;
  170198. cinfo->X_density = 1;
  170199. cinfo->Y_density = 1;
  170200. cinfo->saw_Adobe_marker = FALSE;
  170201. cinfo->Adobe_transform = 0;
  170202. cinfo->marker->saw_SOI = TRUE;
  170203. return TRUE;
  170204. }
  170205. LOCAL(boolean)
  170206. get_sof (j_decompress_ptr cinfo, boolean is_prog, boolean is_arith)
  170207. /* Process a SOFn marker */
  170208. {
  170209. INT32 length;
  170210. int c, ci;
  170211. jpeg_component_info * compptr;
  170212. INPUT_VARS(cinfo);
  170213. cinfo->progressive_mode = is_prog;
  170214. cinfo->arith_code = is_arith;
  170215. INPUT_2BYTES(cinfo, length, return FALSE);
  170216. INPUT_BYTE(cinfo, cinfo->data_precision, return FALSE);
  170217. INPUT_2BYTES(cinfo, cinfo->image_height, return FALSE);
  170218. INPUT_2BYTES(cinfo, cinfo->image_width, return FALSE);
  170219. INPUT_BYTE(cinfo, cinfo->num_components, return FALSE);
  170220. length -= 8;
  170221. TRACEMS4(cinfo, 1, JTRC_SOF, cinfo->unread_marker,
  170222. (int) cinfo->image_width, (int) cinfo->image_height,
  170223. cinfo->num_components);
  170224. if (cinfo->marker->saw_SOF)
  170225. ERREXIT(cinfo, JERR_SOF_DUPLICATE);
  170226. /* We don't support files in which the image height is initially specified */
  170227. /* as 0 and is later redefined by DNL. As long as we have to check that, */
  170228. /* might as well have a general sanity check. */
  170229. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  170230. || cinfo->num_components <= 0)
  170231. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  170232. if (length != (cinfo->num_components * 3))
  170233. ERREXIT(cinfo, JERR_BAD_LENGTH);
  170234. if (cinfo->comp_info == NULL) /* do only once, even if suspend */
  170235. cinfo->comp_info = (jpeg_component_info *) (*cinfo->mem->alloc_small)
  170236. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170237. cinfo->num_components * SIZEOF(jpeg_component_info));
  170238. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170239. ci++, compptr++) {
  170240. compptr->component_index = ci;
  170241. INPUT_BYTE(cinfo, compptr->component_id, return FALSE);
  170242. INPUT_BYTE(cinfo, c, return FALSE);
  170243. compptr->h_samp_factor = (c >> 4) & 15;
  170244. compptr->v_samp_factor = (c ) & 15;
  170245. INPUT_BYTE(cinfo, compptr->quant_tbl_no, return FALSE);
  170246. TRACEMS4(cinfo, 1, JTRC_SOF_COMPONENT,
  170247. compptr->component_id, compptr->h_samp_factor,
  170248. compptr->v_samp_factor, compptr->quant_tbl_no);
  170249. }
  170250. cinfo->marker->saw_SOF = TRUE;
  170251. INPUT_SYNC(cinfo);
  170252. return TRUE;
  170253. }
  170254. LOCAL(boolean)
  170255. get_sos (j_decompress_ptr cinfo)
  170256. /* Process a SOS marker */
  170257. {
  170258. INT32 length;
  170259. int i, ci, n, c, cc;
  170260. jpeg_component_info * compptr;
  170261. INPUT_VARS(cinfo);
  170262. if (! cinfo->marker->saw_SOF)
  170263. ERREXIT(cinfo, JERR_SOS_NO_SOF);
  170264. INPUT_2BYTES(cinfo, length, return FALSE);
  170265. INPUT_BYTE(cinfo, n, return FALSE); /* Number of components */
  170266. TRACEMS1(cinfo, 1, JTRC_SOS, n);
  170267. if (length != (n * 2 + 6) || n < 1 || n > MAX_COMPS_IN_SCAN)
  170268. ERREXIT(cinfo, JERR_BAD_LENGTH);
  170269. cinfo->comps_in_scan = n;
  170270. /* Collect the component-spec parameters */
  170271. for (i = 0; i < n; i++) {
  170272. INPUT_BYTE(cinfo, cc, return FALSE);
  170273. INPUT_BYTE(cinfo, c, return FALSE);
  170274. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170275. ci++, compptr++) {
  170276. if (cc == compptr->component_id)
  170277. goto id_found;
  170278. }
  170279. ERREXIT1(cinfo, JERR_BAD_COMPONENT_ID, cc);
  170280. id_found:
  170281. cinfo->cur_comp_info[i] = compptr;
  170282. compptr->dc_tbl_no = (c >> 4) & 15;
  170283. compptr->ac_tbl_no = (c ) & 15;
  170284. TRACEMS3(cinfo, 1, JTRC_SOS_COMPONENT, cc,
  170285. compptr->dc_tbl_no, compptr->ac_tbl_no);
  170286. }
  170287. /* Collect the additional scan parameters Ss, Se, Ah/Al. */
  170288. INPUT_BYTE(cinfo, c, return FALSE);
  170289. cinfo->Ss = c;
  170290. INPUT_BYTE(cinfo, c, return FALSE);
  170291. cinfo->Se = c;
  170292. INPUT_BYTE(cinfo, c, return FALSE);
  170293. cinfo->Ah = (c >> 4) & 15;
  170294. cinfo->Al = (c ) & 15;
  170295. TRACEMS4(cinfo, 1, JTRC_SOS_PARAMS, cinfo->Ss, cinfo->Se,
  170296. cinfo->Ah, cinfo->Al);
  170297. /* Prepare to scan data & restart markers */
  170298. cinfo->marker->next_restart_num = 0;
  170299. /* Count another SOS marker */
  170300. cinfo->input_scan_number++;
  170301. INPUT_SYNC(cinfo);
  170302. return TRUE;
  170303. }
  170304. #ifdef D_ARITH_CODING_SUPPORTED
  170305. LOCAL(boolean)
  170306. get_dac (j_decompress_ptr cinfo)
  170307. /* Process a DAC marker */
  170308. {
  170309. INT32 length;
  170310. int index, val;
  170311. INPUT_VARS(cinfo);
  170312. INPUT_2BYTES(cinfo, length, return FALSE);
  170313. length -= 2;
  170314. while (length > 0) {
  170315. INPUT_BYTE(cinfo, index, return FALSE);
  170316. INPUT_BYTE(cinfo, val, return FALSE);
  170317. length -= 2;
  170318. TRACEMS2(cinfo, 1, JTRC_DAC, index, val);
  170319. if (index < 0 || index >= (2*NUM_ARITH_TBLS))
  170320. ERREXIT1(cinfo, JERR_DAC_INDEX, index);
  170321. if (index >= NUM_ARITH_TBLS) { /* define AC table */
  170322. cinfo->arith_ac_K[index-NUM_ARITH_TBLS] = (UINT8) val;
  170323. } else { /* define DC table */
  170324. cinfo->arith_dc_L[index] = (UINT8) (val & 0x0F);
  170325. cinfo->arith_dc_U[index] = (UINT8) (val >> 4);
  170326. if (cinfo->arith_dc_L[index] > cinfo->arith_dc_U[index])
  170327. ERREXIT1(cinfo, JERR_DAC_VALUE, val);
  170328. }
  170329. }
  170330. if (length != 0)
  170331. ERREXIT(cinfo, JERR_BAD_LENGTH);
  170332. INPUT_SYNC(cinfo);
  170333. return TRUE;
  170334. }
  170335. #else /* ! D_ARITH_CODING_SUPPORTED */
  170336. #define get_dac(cinfo) skip_variable(cinfo)
  170337. #endif /* D_ARITH_CODING_SUPPORTED */
  170338. LOCAL(boolean)
  170339. get_dht (j_decompress_ptr cinfo)
  170340. /* Process a DHT marker */
  170341. {
  170342. INT32 length;
  170343. UINT8 bits[17];
  170344. UINT8 huffval[256];
  170345. int i, index, count;
  170346. JHUFF_TBL **htblptr;
  170347. INPUT_VARS(cinfo);
  170348. INPUT_2BYTES(cinfo, length, return FALSE);
  170349. length -= 2;
  170350. while (length > 16) {
  170351. INPUT_BYTE(cinfo, index, return FALSE);
  170352. TRACEMS1(cinfo, 1, JTRC_DHT, index);
  170353. bits[0] = 0;
  170354. count = 0;
  170355. for (i = 1; i <= 16; i++) {
  170356. INPUT_BYTE(cinfo, bits[i], return FALSE);
  170357. count += bits[i];
  170358. }
  170359. length -= 1 + 16;
  170360. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  170361. bits[1], bits[2], bits[3], bits[4],
  170362. bits[5], bits[6], bits[7], bits[8]);
  170363. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  170364. bits[9], bits[10], bits[11], bits[12],
  170365. bits[13], bits[14], bits[15], bits[16]);
  170366. /* Here we just do minimal validation of the counts to avoid walking
  170367. * off the end of our table space. jdhuff.c will check more carefully.
  170368. */
  170369. if (count > 256 || ((INT32) count) > length)
  170370. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  170371. for (i = 0; i < count; i++)
  170372. INPUT_BYTE(cinfo, huffval[i], return FALSE);
  170373. length -= count;
  170374. if (index & 0x10) { /* AC table definition */
  170375. index -= 0x10;
  170376. htblptr = &cinfo->ac_huff_tbl_ptrs[index];
  170377. } else { /* DC table definition */
  170378. htblptr = &cinfo->dc_huff_tbl_ptrs[index];
  170379. }
  170380. if (index < 0 || index >= NUM_HUFF_TBLS)
  170381. ERREXIT1(cinfo, JERR_DHT_INDEX, index);
  170382. if (*htblptr == NULL)
  170383. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  170384. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  170385. MEMCOPY((*htblptr)->huffval, huffval, SIZEOF((*htblptr)->huffval));
  170386. }
  170387. if (length != 0)
  170388. ERREXIT(cinfo, JERR_BAD_LENGTH);
  170389. INPUT_SYNC(cinfo);
  170390. return TRUE;
  170391. }
  170392. LOCAL(boolean)
  170393. get_dqt (j_decompress_ptr cinfo)
  170394. /* Process a DQT marker */
  170395. {
  170396. INT32 length;
  170397. int n, i, prec;
  170398. unsigned int tmp;
  170399. JQUANT_TBL *quant_ptr;
  170400. INPUT_VARS(cinfo);
  170401. INPUT_2BYTES(cinfo, length, return FALSE);
  170402. length -= 2;
  170403. while (length > 0) {
  170404. INPUT_BYTE(cinfo, n, return FALSE);
  170405. prec = n >> 4;
  170406. n &= 0x0F;
  170407. TRACEMS2(cinfo, 1, JTRC_DQT, n, prec);
  170408. if (n >= NUM_QUANT_TBLS)
  170409. ERREXIT1(cinfo, JERR_DQT_INDEX, n);
  170410. if (cinfo->quant_tbl_ptrs[n] == NULL)
  170411. cinfo->quant_tbl_ptrs[n] = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  170412. quant_ptr = cinfo->quant_tbl_ptrs[n];
  170413. for (i = 0; i < DCTSIZE2; i++) {
  170414. if (prec)
  170415. INPUT_2BYTES(cinfo, tmp, return FALSE);
  170416. else
  170417. INPUT_BYTE(cinfo, tmp, return FALSE);
  170418. /* We convert the zigzag-order table to natural array order. */
  170419. quant_ptr->quantval[jpeg_natural_order[i]] = (UINT16) tmp;
  170420. }
  170421. if (cinfo->err->trace_level >= 2) {
  170422. for (i = 0; i < DCTSIZE2; i += 8) {
  170423. TRACEMS8(cinfo, 2, JTRC_QUANTVALS,
  170424. quant_ptr->quantval[i], quant_ptr->quantval[i+1],
  170425. quant_ptr->quantval[i+2], quant_ptr->quantval[i+3],
  170426. quant_ptr->quantval[i+4], quant_ptr->quantval[i+5],
  170427. quant_ptr->quantval[i+6], quant_ptr->quantval[i+7]);
  170428. }
  170429. }
  170430. length -= DCTSIZE2+1;
  170431. if (prec) length -= DCTSIZE2;
  170432. }
  170433. if (length != 0)
  170434. ERREXIT(cinfo, JERR_BAD_LENGTH);
  170435. INPUT_SYNC(cinfo);
  170436. return TRUE;
  170437. }
  170438. LOCAL(boolean)
  170439. get_dri (j_decompress_ptr cinfo)
  170440. /* Process a DRI marker */
  170441. {
  170442. INT32 length;
  170443. unsigned int tmp;
  170444. INPUT_VARS(cinfo);
  170445. INPUT_2BYTES(cinfo, length, return FALSE);
  170446. if (length != 4)
  170447. ERREXIT(cinfo, JERR_BAD_LENGTH);
  170448. INPUT_2BYTES(cinfo, tmp, return FALSE);
  170449. TRACEMS1(cinfo, 1, JTRC_DRI, tmp);
  170450. cinfo->restart_interval = tmp;
  170451. INPUT_SYNC(cinfo);
  170452. return TRUE;
  170453. }
  170454. /*
  170455. * Routines for processing APPn and COM markers.
  170456. * These are either saved in memory or discarded, per application request.
  170457. * APP0 and APP14 are specially checked to see if they are
  170458. * JFIF and Adobe markers, respectively.
  170459. */
  170460. #define APP0_DATA_LEN 14 /* Length of interesting data in APP0 */
  170461. #define APP14_DATA_LEN 12 /* Length of interesting data in APP14 */
  170462. #define APPN_DATA_LEN 14 /* Must be the largest of the above!! */
  170463. LOCAL(void)
  170464. examine_app0 (j_decompress_ptr cinfo, JOCTET FAR * data,
  170465. unsigned int datalen, INT32 remaining)
  170466. /* Examine first few bytes from an APP0.
  170467. * Take appropriate action if it is a JFIF marker.
  170468. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  170469. */
  170470. {
  170471. INT32 totallen = (INT32) datalen + remaining;
  170472. if (datalen >= APP0_DATA_LEN &&
  170473. GETJOCTET(data[0]) == 0x4A &&
  170474. GETJOCTET(data[1]) == 0x46 &&
  170475. GETJOCTET(data[2]) == 0x49 &&
  170476. GETJOCTET(data[3]) == 0x46 &&
  170477. GETJOCTET(data[4]) == 0) {
  170478. /* Found JFIF APP0 marker: save info */
  170479. cinfo->saw_JFIF_marker = TRUE;
  170480. cinfo->JFIF_major_version = GETJOCTET(data[5]);
  170481. cinfo->JFIF_minor_version = GETJOCTET(data[6]);
  170482. cinfo->density_unit = GETJOCTET(data[7]);
  170483. cinfo->X_density = (GETJOCTET(data[8]) << 8) + GETJOCTET(data[9]);
  170484. cinfo->Y_density = (GETJOCTET(data[10]) << 8) + GETJOCTET(data[11]);
  170485. /* Check version.
  170486. * Major version must be 1, anything else signals an incompatible change.
  170487. * (We used to treat this as an error, but now it's a nonfatal warning,
  170488. * because some bozo at Hijaak couldn't read the spec.)
  170489. * Minor version should be 0..2, but process anyway if newer.
  170490. */
  170491. if (cinfo->JFIF_major_version != 1)
  170492. WARNMS2(cinfo, JWRN_JFIF_MAJOR,
  170493. cinfo->JFIF_major_version, cinfo->JFIF_minor_version);
  170494. /* Generate trace messages */
  170495. TRACEMS5(cinfo, 1, JTRC_JFIF,
  170496. cinfo->JFIF_major_version, cinfo->JFIF_minor_version,
  170497. cinfo->X_density, cinfo->Y_density, cinfo->density_unit);
  170498. /* Validate thumbnail dimensions and issue appropriate messages */
  170499. if (GETJOCTET(data[12]) | GETJOCTET(data[13]))
  170500. TRACEMS2(cinfo, 1, JTRC_JFIF_THUMBNAIL,
  170501. GETJOCTET(data[12]), GETJOCTET(data[13]));
  170502. totallen -= APP0_DATA_LEN;
  170503. if (totallen !=
  170504. ((INT32)GETJOCTET(data[12]) * (INT32)GETJOCTET(data[13]) * (INT32) 3))
  170505. TRACEMS1(cinfo, 1, JTRC_JFIF_BADTHUMBNAILSIZE, (int) totallen);
  170506. } else if (datalen >= 6 &&
  170507. GETJOCTET(data[0]) == 0x4A &&
  170508. GETJOCTET(data[1]) == 0x46 &&
  170509. GETJOCTET(data[2]) == 0x58 &&
  170510. GETJOCTET(data[3]) == 0x58 &&
  170511. GETJOCTET(data[4]) == 0) {
  170512. /* Found JFIF "JFXX" extension APP0 marker */
  170513. /* The library doesn't actually do anything with these,
  170514. * but we try to produce a helpful trace message.
  170515. */
  170516. switch (GETJOCTET(data[5])) {
  170517. case 0x10:
  170518. TRACEMS1(cinfo, 1, JTRC_THUMB_JPEG, (int) totallen);
  170519. break;
  170520. case 0x11:
  170521. TRACEMS1(cinfo, 1, JTRC_THUMB_PALETTE, (int) totallen);
  170522. break;
  170523. case 0x13:
  170524. TRACEMS1(cinfo, 1, JTRC_THUMB_RGB, (int) totallen);
  170525. break;
  170526. default:
  170527. TRACEMS2(cinfo, 1, JTRC_JFIF_EXTENSION,
  170528. GETJOCTET(data[5]), (int) totallen);
  170529. break;
  170530. }
  170531. } else {
  170532. /* Start of APP0 does not match "JFIF" or "JFXX", or too short */
  170533. TRACEMS1(cinfo, 1, JTRC_APP0, (int) totallen);
  170534. }
  170535. }
  170536. LOCAL(void)
  170537. examine_app14 (j_decompress_ptr cinfo, JOCTET FAR * data,
  170538. unsigned int datalen, INT32 remaining)
  170539. /* Examine first few bytes from an APP14.
  170540. * Take appropriate action if it is an Adobe marker.
  170541. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  170542. */
  170543. {
  170544. unsigned int version, flags0, flags1, transform;
  170545. if (datalen >= APP14_DATA_LEN &&
  170546. GETJOCTET(data[0]) == 0x41 &&
  170547. GETJOCTET(data[1]) == 0x64 &&
  170548. GETJOCTET(data[2]) == 0x6F &&
  170549. GETJOCTET(data[3]) == 0x62 &&
  170550. GETJOCTET(data[4]) == 0x65) {
  170551. /* Found Adobe APP14 marker */
  170552. version = (GETJOCTET(data[5]) << 8) + GETJOCTET(data[6]);
  170553. flags0 = (GETJOCTET(data[7]) << 8) + GETJOCTET(data[8]);
  170554. flags1 = (GETJOCTET(data[9]) << 8) + GETJOCTET(data[10]);
  170555. transform = GETJOCTET(data[11]);
  170556. TRACEMS4(cinfo, 1, JTRC_ADOBE, version, flags0, flags1, transform);
  170557. cinfo->saw_Adobe_marker = TRUE;
  170558. cinfo->Adobe_transform = (UINT8) transform;
  170559. } else {
  170560. /* Start of APP14 does not match "Adobe", or too short */
  170561. TRACEMS1(cinfo, 1, JTRC_APP14, (int) (datalen + remaining));
  170562. }
  170563. }
  170564. METHODDEF(boolean)
  170565. get_interesting_appn (j_decompress_ptr cinfo)
  170566. /* Process an APP0 or APP14 marker without saving it */
  170567. {
  170568. INT32 length;
  170569. JOCTET b[APPN_DATA_LEN];
  170570. unsigned int i, numtoread;
  170571. INPUT_VARS(cinfo);
  170572. INPUT_2BYTES(cinfo, length, return FALSE);
  170573. length -= 2;
  170574. /* get the interesting part of the marker data */
  170575. if (length >= APPN_DATA_LEN)
  170576. numtoread = APPN_DATA_LEN;
  170577. else if (length > 0)
  170578. numtoread = (unsigned int) length;
  170579. else
  170580. numtoread = 0;
  170581. for (i = 0; i < numtoread; i++)
  170582. INPUT_BYTE(cinfo, b[i], return FALSE);
  170583. length -= numtoread;
  170584. /* process it */
  170585. switch (cinfo->unread_marker) {
  170586. case M_APP0:
  170587. examine_app0(cinfo, (JOCTET FAR *) b, numtoread, length);
  170588. break;
  170589. case M_APP14:
  170590. examine_app14(cinfo, (JOCTET FAR *) b, numtoread, length);
  170591. break;
  170592. default:
  170593. /* can't get here unless jpeg_save_markers chooses wrong processor */
  170594. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  170595. break;
  170596. }
  170597. /* skip any remaining data -- could be lots */
  170598. INPUT_SYNC(cinfo);
  170599. if (length > 0)
  170600. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  170601. return TRUE;
  170602. }
  170603. #ifdef SAVE_MARKERS_SUPPORTED
  170604. METHODDEF(boolean)
  170605. save_marker (j_decompress_ptr cinfo)
  170606. /* Save an APPn or COM marker into the marker list */
  170607. {
  170608. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  170609. jpeg_saved_marker_ptr cur_marker = marker->cur_marker;
  170610. unsigned int bytes_read, data_length;
  170611. JOCTET FAR * data;
  170612. INT32 length = 0;
  170613. INPUT_VARS(cinfo);
  170614. if (cur_marker == NULL) {
  170615. /* begin reading a marker */
  170616. INPUT_2BYTES(cinfo, length, return FALSE);
  170617. length -= 2;
  170618. if (length >= 0) { /* watch out for bogus length word */
  170619. /* figure out how much we want to save */
  170620. unsigned int limit;
  170621. if (cinfo->unread_marker == (int) M_COM)
  170622. limit = marker->length_limit_COM;
  170623. else
  170624. limit = marker->length_limit_APPn[cinfo->unread_marker - (int) M_APP0];
  170625. if ((unsigned int) length < limit)
  170626. limit = (unsigned int) length;
  170627. /* allocate and initialize the marker item */
  170628. cur_marker = (jpeg_saved_marker_ptr)
  170629. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170630. SIZEOF(struct jpeg_marker_struct) + limit);
  170631. cur_marker->next = NULL;
  170632. cur_marker->marker = (UINT8) cinfo->unread_marker;
  170633. cur_marker->original_length = (unsigned int) length;
  170634. cur_marker->data_length = limit;
  170635. /* data area is just beyond the jpeg_marker_struct */
  170636. data = cur_marker->data = (JOCTET FAR *) (cur_marker + 1);
  170637. marker->cur_marker = cur_marker;
  170638. marker->bytes_read = 0;
  170639. bytes_read = 0;
  170640. data_length = limit;
  170641. } else {
  170642. /* deal with bogus length word */
  170643. bytes_read = data_length = 0;
  170644. data = NULL;
  170645. }
  170646. } else {
  170647. /* resume reading a marker */
  170648. bytes_read = marker->bytes_read;
  170649. data_length = cur_marker->data_length;
  170650. data = cur_marker->data + bytes_read;
  170651. }
  170652. while (bytes_read < data_length) {
  170653. INPUT_SYNC(cinfo); /* move the restart point to here */
  170654. marker->bytes_read = bytes_read;
  170655. /* If there's not at least one byte in buffer, suspend */
  170656. MAKE_BYTE_AVAIL(cinfo, return FALSE);
  170657. /* Copy bytes with reasonable rapidity */
  170658. while (bytes_read < data_length && bytes_in_buffer > 0) {
  170659. *data++ = *next_input_byte++;
  170660. bytes_in_buffer--;
  170661. bytes_read++;
  170662. }
  170663. }
  170664. /* Done reading what we want to read */
  170665. if (cur_marker != NULL) { /* will be NULL if bogus length word */
  170666. /* Add new marker to end of list */
  170667. if (cinfo->marker_list == NULL) {
  170668. cinfo->marker_list = cur_marker;
  170669. } else {
  170670. jpeg_saved_marker_ptr prev = cinfo->marker_list;
  170671. while (prev->next != NULL)
  170672. prev = prev->next;
  170673. prev->next = cur_marker;
  170674. }
  170675. /* Reset pointer & calc remaining data length */
  170676. data = cur_marker->data;
  170677. length = cur_marker->original_length - data_length;
  170678. }
  170679. /* Reset to initial state for next marker */
  170680. marker->cur_marker = NULL;
  170681. /* Process the marker if interesting; else just make a generic trace msg */
  170682. switch (cinfo->unread_marker) {
  170683. case M_APP0:
  170684. examine_app0(cinfo, data, data_length, length);
  170685. break;
  170686. case M_APP14:
  170687. examine_app14(cinfo, data, data_length, length);
  170688. break;
  170689. default:
  170690. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker,
  170691. (int) (data_length + length));
  170692. break;
  170693. }
  170694. /* skip any remaining data -- could be lots */
  170695. INPUT_SYNC(cinfo); /* do before skip_input_data */
  170696. if (length > 0)
  170697. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  170698. return TRUE;
  170699. }
  170700. #endif /* SAVE_MARKERS_SUPPORTED */
  170701. METHODDEF(boolean)
  170702. skip_variable (j_decompress_ptr cinfo)
  170703. /* Skip over an unknown or uninteresting variable-length marker */
  170704. {
  170705. INT32 length;
  170706. INPUT_VARS(cinfo);
  170707. INPUT_2BYTES(cinfo, length, return FALSE);
  170708. length -= 2;
  170709. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker, (int) length);
  170710. INPUT_SYNC(cinfo); /* do before skip_input_data */
  170711. if (length > 0)
  170712. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  170713. return TRUE;
  170714. }
  170715. /*
  170716. * Find the next JPEG marker, save it in cinfo->unread_marker.
  170717. * Returns FALSE if had to suspend before reaching a marker;
  170718. * in that case cinfo->unread_marker is unchanged.
  170719. *
  170720. * Note that the result might not be a valid marker code,
  170721. * but it will never be 0 or FF.
  170722. */
  170723. LOCAL(boolean)
  170724. next_marker (j_decompress_ptr cinfo)
  170725. {
  170726. int c;
  170727. INPUT_VARS(cinfo);
  170728. for (;;) {
  170729. INPUT_BYTE(cinfo, c, return FALSE);
  170730. /* Skip any non-FF bytes.
  170731. * This may look a bit inefficient, but it will not occur in a valid file.
  170732. * We sync after each discarded byte so that a suspending data source
  170733. * can discard the byte from its buffer.
  170734. */
  170735. while (c != 0xFF) {
  170736. cinfo->marker->discarded_bytes++;
  170737. INPUT_SYNC(cinfo);
  170738. INPUT_BYTE(cinfo, c, return FALSE);
  170739. }
  170740. /* This loop swallows any duplicate FF bytes. Extra FFs are legal as
  170741. * pad bytes, so don't count them in discarded_bytes. We assume there
  170742. * will not be so many consecutive FF bytes as to overflow a suspending
  170743. * data source's input buffer.
  170744. */
  170745. do {
  170746. INPUT_BYTE(cinfo, c, return FALSE);
  170747. } while (c == 0xFF);
  170748. if (c != 0)
  170749. break; /* found a valid marker, exit loop */
  170750. /* Reach here if we found a stuffed-zero data sequence (FF/00).
  170751. * Discard it and loop back to try again.
  170752. */
  170753. cinfo->marker->discarded_bytes += 2;
  170754. INPUT_SYNC(cinfo);
  170755. }
  170756. if (cinfo->marker->discarded_bytes != 0) {
  170757. WARNMS2(cinfo, JWRN_EXTRANEOUS_DATA, cinfo->marker->discarded_bytes, c);
  170758. cinfo->marker->discarded_bytes = 0;
  170759. }
  170760. cinfo->unread_marker = c;
  170761. INPUT_SYNC(cinfo);
  170762. return TRUE;
  170763. }
  170764. LOCAL(boolean)
  170765. first_marker (j_decompress_ptr cinfo)
  170766. /* Like next_marker, but used to obtain the initial SOI marker. */
  170767. /* For this marker, we do not allow preceding garbage or fill; otherwise,
  170768. * we might well scan an entire input file before realizing it ain't JPEG.
  170769. * If an application wants to process non-JFIF files, it must seek to the
  170770. * SOI before calling the JPEG library.
  170771. */
  170772. {
  170773. int c, c2;
  170774. INPUT_VARS(cinfo);
  170775. INPUT_BYTE(cinfo, c, return FALSE);
  170776. INPUT_BYTE(cinfo, c2, return FALSE);
  170777. if (c != 0xFF || c2 != (int) M_SOI)
  170778. ERREXIT2(cinfo, JERR_NO_SOI, c, c2);
  170779. cinfo->unread_marker = c2;
  170780. INPUT_SYNC(cinfo);
  170781. return TRUE;
  170782. }
  170783. /*
  170784. * Read markers until SOS or EOI.
  170785. *
  170786. * Returns same codes as are defined for jpeg_consume_input:
  170787. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  170788. */
  170789. METHODDEF(int)
  170790. read_markers (j_decompress_ptr cinfo)
  170791. {
  170792. /* Outer loop repeats once for each marker. */
  170793. for (;;) {
  170794. /* Collect the marker proper, unless we already did. */
  170795. /* NB: first_marker() enforces the requirement that SOI appear first. */
  170796. if (cinfo->unread_marker == 0) {
  170797. if (! cinfo->marker->saw_SOI) {
  170798. if (! first_marker(cinfo))
  170799. return JPEG_SUSPENDED;
  170800. } else {
  170801. if (! next_marker(cinfo))
  170802. return JPEG_SUSPENDED;
  170803. }
  170804. }
  170805. /* At this point cinfo->unread_marker contains the marker code and the
  170806. * input point is just past the marker proper, but before any parameters.
  170807. * A suspension will cause us to return with this state still true.
  170808. */
  170809. switch (cinfo->unread_marker) {
  170810. case M_SOI:
  170811. if (! get_soi(cinfo))
  170812. return JPEG_SUSPENDED;
  170813. break;
  170814. case M_SOF0: /* Baseline */
  170815. case M_SOF1: /* Extended sequential, Huffman */
  170816. if (! get_sof(cinfo, FALSE, FALSE))
  170817. return JPEG_SUSPENDED;
  170818. break;
  170819. case M_SOF2: /* Progressive, Huffman */
  170820. if (! get_sof(cinfo, TRUE, FALSE))
  170821. return JPEG_SUSPENDED;
  170822. break;
  170823. case M_SOF9: /* Extended sequential, arithmetic */
  170824. if (! get_sof(cinfo, FALSE, TRUE))
  170825. return JPEG_SUSPENDED;
  170826. break;
  170827. case M_SOF10: /* Progressive, arithmetic */
  170828. if (! get_sof(cinfo, TRUE, TRUE))
  170829. return JPEG_SUSPENDED;
  170830. break;
  170831. /* Currently unsupported SOFn types */
  170832. case M_SOF3: /* Lossless, Huffman */
  170833. case M_SOF5: /* Differential sequential, Huffman */
  170834. case M_SOF6: /* Differential progressive, Huffman */
  170835. case M_SOF7: /* Differential lossless, Huffman */
  170836. case M_JPG: /* Reserved for JPEG extensions */
  170837. case M_SOF11: /* Lossless, arithmetic */
  170838. case M_SOF13: /* Differential sequential, arithmetic */
  170839. case M_SOF14: /* Differential progressive, arithmetic */
  170840. case M_SOF15: /* Differential lossless, arithmetic */
  170841. ERREXIT1(cinfo, JERR_SOF_UNSUPPORTED, cinfo->unread_marker);
  170842. break;
  170843. case M_SOS:
  170844. if (! get_sos(cinfo))
  170845. return JPEG_SUSPENDED;
  170846. cinfo->unread_marker = 0; /* processed the marker */
  170847. return JPEG_REACHED_SOS;
  170848. case M_EOI:
  170849. TRACEMS(cinfo, 1, JTRC_EOI);
  170850. cinfo->unread_marker = 0; /* processed the marker */
  170851. return JPEG_REACHED_EOI;
  170852. case M_DAC:
  170853. if (! get_dac(cinfo))
  170854. return JPEG_SUSPENDED;
  170855. break;
  170856. case M_DHT:
  170857. if (! get_dht(cinfo))
  170858. return JPEG_SUSPENDED;
  170859. break;
  170860. case M_DQT:
  170861. if (! get_dqt(cinfo))
  170862. return JPEG_SUSPENDED;
  170863. break;
  170864. case M_DRI:
  170865. if (! get_dri(cinfo))
  170866. return JPEG_SUSPENDED;
  170867. break;
  170868. case M_APP0:
  170869. case M_APP1:
  170870. case M_APP2:
  170871. case M_APP3:
  170872. case M_APP4:
  170873. case M_APP5:
  170874. case M_APP6:
  170875. case M_APP7:
  170876. case M_APP8:
  170877. case M_APP9:
  170878. case M_APP10:
  170879. case M_APP11:
  170880. case M_APP12:
  170881. case M_APP13:
  170882. case M_APP14:
  170883. case M_APP15:
  170884. if (! (*((my_marker_ptr2) cinfo->marker)->process_APPn[
  170885. cinfo->unread_marker - (int) M_APP0]) (cinfo))
  170886. return JPEG_SUSPENDED;
  170887. break;
  170888. case M_COM:
  170889. if (! (*((my_marker_ptr2) cinfo->marker)->process_COM) (cinfo))
  170890. return JPEG_SUSPENDED;
  170891. break;
  170892. case M_RST0: /* these are all parameterless */
  170893. case M_RST1:
  170894. case M_RST2:
  170895. case M_RST3:
  170896. case M_RST4:
  170897. case M_RST5:
  170898. case M_RST6:
  170899. case M_RST7:
  170900. case M_TEM:
  170901. TRACEMS1(cinfo, 1, JTRC_PARMLESS_MARKER, cinfo->unread_marker);
  170902. break;
  170903. case M_DNL: /* Ignore DNL ... perhaps the wrong thing */
  170904. if (! skip_variable(cinfo))
  170905. return JPEG_SUSPENDED;
  170906. break;
  170907. default: /* must be DHP, EXP, JPGn, or RESn */
  170908. /* For now, we treat the reserved markers as fatal errors since they are
  170909. * likely to be used to signal incompatible JPEG Part 3 extensions.
  170910. * Once the JPEG 3 version-number marker is well defined, this code
  170911. * ought to change!
  170912. */
  170913. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  170914. break;
  170915. }
  170916. /* Successfully processed marker, so reset state variable */
  170917. cinfo->unread_marker = 0;
  170918. } /* end loop */
  170919. }
  170920. /*
  170921. * Read a restart marker, which is expected to appear next in the datastream;
  170922. * if the marker is not there, take appropriate recovery action.
  170923. * Returns FALSE if suspension is required.
  170924. *
  170925. * This is called by the entropy decoder after it has read an appropriate
  170926. * number of MCUs. cinfo->unread_marker may be nonzero if the entropy decoder
  170927. * has already read a marker from the data source. Under normal conditions
  170928. * cinfo->unread_marker will be reset to 0 before returning; if not reset,
  170929. * it holds a marker which the decoder will be unable to read past.
  170930. */
  170931. METHODDEF(boolean)
  170932. read_restart_marker (j_decompress_ptr cinfo)
  170933. {
  170934. /* Obtain a marker unless we already did. */
  170935. /* Note that next_marker will complain if it skips any data. */
  170936. if (cinfo->unread_marker == 0) {
  170937. if (! next_marker(cinfo))
  170938. return FALSE;
  170939. }
  170940. if (cinfo->unread_marker ==
  170941. ((int) M_RST0 + cinfo->marker->next_restart_num)) {
  170942. /* Normal case --- swallow the marker and let entropy decoder continue */
  170943. TRACEMS1(cinfo, 3, JTRC_RST, cinfo->marker->next_restart_num);
  170944. cinfo->unread_marker = 0;
  170945. } else {
  170946. /* Uh-oh, the restart markers have been messed up. */
  170947. /* Let the data source manager determine how to resync. */
  170948. if (! (*cinfo->src->resync_to_restart) (cinfo,
  170949. cinfo->marker->next_restart_num))
  170950. return FALSE;
  170951. }
  170952. /* Update next-restart state */
  170953. cinfo->marker->next_restart_num = (cinfo->marker->next_restart_num + 1) & 7;
  170954. return TRUE;
  170955. }
  170956. /*
  170957. * This is the default resync_to_restart method for data source managers
  170958. * to use if they don't have any better approach. Some data source managers
  170959. * may be able to back up, or may have additional knowledge about the data
  170960. * which permits a more intelligent recovery strategy; such managers would
  170961. * presumably supply their own resync method.
  170962. *
  170963. * read_restart_marker calls resync_to_restart if it finds a marker other than
  170964. * the restart marker it was expecting. (This code is *not* used unless
  170965. * a nonzero restart interval has been declared.) cinfo->unread_marker is
  170966. * the marker code actually found (might be anything, except 0 or FF).
  170967. * The desired restart marker number (0..7) is passed as a parameter.
  170968. * This routine is supposed to apply whatever error recovery strategy seems
  170969. * appropriate in order to position the input stream to the next data segment.
  170970. * Note that cinfo->unread_marker is treated as a marker appearing before
  170971. * the current data-source input point; usually it should be reset to zero
  170972. * before returning.
  170973. * Returns FALSE if suspension is required.
  170974. *
  170975. * This implementation is substantially constrained by wanting to treat the
  170976. * input as a data stream; this means we can't back up. Therefore, we have
  170977. * only the following actions to work with:
  170978. * 1. Simply discard the marker and let the entropy decoder resume at next
  170979. * byte of file.
  170980. * 2. Read forward until we find another marker, discarding intervening
  170981. * data. (In theory we could look ahead within the current bufferload,
  170982. * without having to discard data if we don't find the desired marker.
  170983. * This idea is not implemented here, in part because it makes behavior
  170984. * dependent on buffer size and chance buffer-boundary positions.)
  170985. * 3. Leave the marker unread (by failing to zero cinfo->unread_marker).
  170986. * This will cause the entropy decoder to process an empty data segment,
  170987. * inserting dummy zeroes, and then we will reprocess the marker.
  170988. *
  170989. * #2 is appropriate if we think the desired marker lies ahead, while #3 is
  170990. * appropriate if the found marker is a future restart marker (indicating
  170991. * that we have missed the desired restart marker, probably because it got
  170992. * corrupted).
  170993. * We apply #2 or #3 if the found marker is a restart marker no more than
  170994. * two counts behind or ahead of the expected one. We also apply #2 if the
  170995. * found marker is not a legal JPEG marker code (it's certainly bogus data).
  170996. * If the found marker is a restart marker more than 2 counts away, we do #1
  170997. * (too much risk that the marker is erroneous; with luck we will be able to
  170998. * resync at some future point).
  170999. * For any valid non-restart JPEG marker, we apply #3. This keeps us from
  171000. * overrunning the end of a scan. An implementation limited to single-scan
  171001. * files might find it better to apply #2 for markers other than EOI, since
  171002. * any other marker would have to be bogus data in that case.
  171003. */
  171004. GLOBAL(boolean)
  171005. jpeg_resync_to_restart (j_decompress_ptr cinfo, int desired)
  171006. {
  171007. int marker = cinfo->unread_marker;
  171008. int action = 1;
  171009. /* Always put up a warning. */
  171010. WARNMS2(cinfo, JWRN_MUST_RESYNC, marker, desired);
  171011. /* Outer loop handles repeated decision after scanning forward. */
  171012. for (;;) {
  171013. if (marker < (int) M_SOF0)
  171014. action = 2; /* invalid marker */
  171015. else if (marker < (int) M_RST0 || marker > (int) M_RST7)
  171016. action = 3; /* valid non-restart marker */
  171017. else {
  171018. if (marker == ((int) M_RST0 + ((desired+1) & 7)) ||
  171019. marker == ((int) M_RST0 + ((desired+2) & 7)))
  171020. action = 3; /* one of the next two expected restarts */
  171021. else if (marker == ((int) M_RST0 + ((desired-1) & 7)) ||
  171022. marker == ((int) M_RST0 + ((desired-2) & 7)))
  171023. action = 2; /* a prior restart, so advance */
  171024. else
  171025. action = 1; /* desired restart or too far away */
  171026. }
  171027. TRACEMS2(cinfo, 4, JTRC_RECOVERY_ACTION, marker, action);
  171028. switch (action) {
  171029. case 1:
  171030. /* Discard marker and let entropy decoder resume processing. */
  171031. cinfo->unread_marker = 0;
  171032. return TRUE;
  171033. case 2:
  171034. /* Scan to the next marker, and repeat the decision loop. */
  171035. if (! next_marker(cinfo))
  171036. return FALSE;
  171037. marker = cinfo->unread_marker;
  171038. break;
  171039. case 3:
  171040. /* Return without advancing past this marker. */
  171041. /* Entropy decoder will be forced to process an empty segment. */
  171042. return TRUE;
  171043. }
  171044. } /* end loop */
  171045. }
  171046. /*
  171047. * Reset marker processing state to begin a fresh datastream.
  171048. */
  171049. METHODDEF(void)
  171050. reset_marker_reader (j_decompress_ptr cinfo)
  171051. {
  171052. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  171053. cinfo->comp_info = NULL; /* until allocated by get_sof */
  171054. cinfo->input_scan_number = 0; /* no SOS seen yet */
  171055. cinfo->unread_marker = 0; /* no pending marker */
  171056. marker->pub.saw_SOI = FALSE; /* set internal state too */
  171057. marker->pub.saw_SOF = FALSE;
  171058. marker->pub.discarded_bytes = 0;
  171059. marker->cur_marker = NULL;
  171060. }
  171061. /*
  171062. * Initialize the marker reader module.
  171063. * This is called only once, when the decompression object is created.
  171064. */
  171065. GLOBAL(void)
  171066. jinit_marker_reader (j_decompress_ptr cinfo)
  171067. {
  171068. my_marker_ptr2 marker;
  171069. int i;
  171070. /* Create subobject in permanent pool */
  171071. marker = (my_marker_ptr2)
  171072. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  171073. SIZEOF(my_marker_reader));
  171074. cinfo->marker = (struct jpeg_marker_reader *) marker;
  171075. /* Initialize public method pointers */
  171076. marker->pub.reset_marker_reader = reset_marker_reader;
  171077. marker->pub.read_markers = read_markers;
  171078. marker->pub.read_restart_marker = read_restart_marker;
  171079. /* Initialize COM/APPn processing.
  171080. * By default, we examine and then discard APP0 and APP14,
  171081. * but simply discard COM and all other APPn.
  171082. */
  171083. marker->process_COM = skip_variable;
  171084. marker->length_limit_COM = 0;
  171085. for (i = 0; i < 16; i++) {
  171086. marker->process_APPn[i] = skip_variable;
  171087. marker->length_limit_APPn[i] = 0;
  171088. }
  171089. marker->process_APPn[0] = get_interesting_appn;
  171090. marker->process_APPn[14] = get_interesting_appn;
  171091. /* Reset marker processing state */
  171092. reset_marker_reader(cinfo);
  171093. }
  171094. /*
  171095. * Control saving of COM and APPn markers into marker_list.
  171096. */
  171097. #ifdef SAVE_MARKERS_SUPPORTED
  171098. GLOBAL(void)
  171099. jpeg_save_markers (j_decompress_ptr cinfo, int marker_code,
  171100. unsigned int length_limit)
  171101. {
  171102. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  171103. long maxlength;
  171104. jpeg_marker_parser_method processor;
  171105. /* Length limit mustn't be larger than what we can allocate
  171106. * (should only be a concern in a 16-bit environment).
  171107. */
  171108. maxlength = cinfo->mem->max_alloc_chunk - SIZEOF(struct jpeg_marker_struct);
  171109. if (((long) length_limit) > maxlength)
  171110. length_limit = (unsigned int) maxlength;
  171111. /* Choose processor routine to use.
  171112. * APP0/APP14 have special requirements.
  171113. */
  171114. if (length_limit) {
  171115. processor = save_marker;
  171116. /* If saving APP0/APP14, save at least enough for our internal use. */
  171117. if (marker_code == (int) M_APP0 && length_limit < APP0_DATA_LEN)
  171118. length_limit = APP0_DATA_LEN;
  171119. else if (marker_code == (int) M_APP14 && length_limit < APP14_DATA_LEN)
  171120. length_limit = APP14_DATA_LEN;
  171121. } else {
  171122. processor = skip_variable;
  171123. /* If discarding APP0/APP14, use our regular on-the-fly processor. */
  171124. if (marker_code == (int) M_APP0 || marker_code == (int) M_APP14)
  171125. processor = get_interesting_appn;
  171126. }
  171127. if (marker_code == (int) M_COM) {
  171128. marker->process_COM = processor;
  171129. marker->length_limit_COM = length_limit;
  171130. } else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15) {
  171131. marker->process_APPn[marker_code - (int) M_APP0] = processor;
  171132. marker->length_limit_APPn[marker_code - (int) M_APP0] = length_limit;
  171133. } else
  171134. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  171135. }
  171136. #endif /* SAVE_MARKERS_SUPPORTED */
  171137. /*
  171138. * Install a special processing method for COM or APPn markers.
  171139. */
  171140. GLOBAL(void)
  171141. jpeg_set_marker_processor (j_decompress_ptr cinfo, int marker_code,
  171142. jpeg_marker_parser_method routine)
  171143. {
  171144. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  171145. if (marker_code == (int) M_COM)
  171146. marker->process_COM = routine;
  171147. else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15)
  171148. marker->process_APPn[marker_code - (int) M_APP0] = routine;
  171149. else
  171150. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  171151. }
  171152. /*** End of inlined file: jdmarker.c ***/
  171153. /*** Start of inlined file: jdmaster.c ***/
  171154. #define JPEG_INTERNALS
  171155. /* Private state */
  171156. typedef struct {
  171157. struct jpeg_decomp_master pub; /* public fields */
  171158. int pass_number; /* # of passes completed */
  171159. boolean using_merged_upsample; /* TRUE if using merged upsample/cconvert */
  171160. /* Saved references to initialized quantizer modules,
  171161. * in case we need to switch modes.
  171162. */
  171163. struct jpeg_color_quantizer * quantizer_1pass;
  171164. struct jpeg_color_quantizer * quantizer_2pass;
  171165. } my_decomp_master;
  171166. typedef my_decomp_master * my_master_ptr6;
  171167. /*
  171168. * Determine whether merged upsample/color conversion should be used.
  171169. * CRUCIAL: this must match the actual capabilities of jdmerge.c!
  171170. */
  171171. LOCAL(boolean)
  171172. use_merged_upsample (j_decompress_ptr cinfo)
  171173. {
  171174. #ifdef UPSAMPLE_MERGING_SUPPORTED
  171175. /* Merging is the equivalent of plain box-filter upsampling */
  171176. if (cinfo->do_fancy_upsampling || cinfo->CCIR601_sampling)
  171177. return FALSE;
  171178. /* jdmerge.c only supports YCC=>RGB color conversion */
  171179. if (cinfo->jpeg_color_space != JCS_YCbCr || cinfo->num_components != 3 ||
  171180. cinfo->out_color_space != JCS_RGB ||
  171181. cinfo->out_color_components != RGB_PIXELSIZE)
  171182. return FALSE;
  171183. /* and it only handles 2h1v or 2h2v sampling ratios */
  171184. if (cinfo->comp_info[0].h_samp_factor != 2 ||
  171185. cinfo->comp_info[1].h_samp_factor != 1 ||
  171186. cinfo->comp_info[2].h_samp_factor != 1 ||
  171187. cinfo->comp_info[0].v_samp_factor > 2 ||
  171188. cinfo->comp_info[1].v_samp_factor != 1 ||
  171189. cinfo->comp_info[2].v_samp_factor != 1)
  171190. return FALSE;
  171191. /* furthermore, it doesn't work if we've scaled the IDCTs differently */
  171192. if (cinfo->comp_info[0].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  171193. cinfo->comp_info[1].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  171194. cinfo->comp_info[2].DCT_scaled_size != cinfo->min_DCT_scaled_size)
  171195. return FALSE;
  171196. /* ??? also need to test for upsample-time rescaling, when & if supported */
  171197. return TRUE; /* by golly, it'll work... */
  171198. #else
  171199. return FALSE;
  171200. #endif
  171201. }
  171202. /*
  171203. * Compute output image dimensions and related values.
  171204. * NOTE: this is exported for possible use by application.
  171205. * Hence it mustn't do anything that can't be done twice.
  171206. * Also note that it may be called before the master module is initialized!
  171207. */
  171208. GLOBAL(void)
  171209. jpeg_calc_output_dimensions (j_decompress_ptr cinfo)
  171210. /* Do computations that are needed before master selection phase */
  171211. {
  171212. #ifdef IDCT_SCALING_SUPPORTED
  171213. int ci;
  171214. jpeg_component_info *compptr;
  171215. #endif
  171216. /* Prevent application from calling me at wrong times */
  171217. if (cinfo->global_state != DSTATE_READY)
  171218. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  171219. #ifdef IDCT_SCALING_SUPPORTED
  171220. /* Compute actual output image dimensions and DCT scaling choices. */
  171221. if (cinfo->scale_num * 8 <= cinfo->scale_denom) {
  171222. /* Provide 1/8 scaling */
  171223. cinfo->output_width = (JDIMENSION)
  171224. jdiv_round_up((long) cinfo->image_width, 8L);
  171225. cinfo->output_height = (JDIMENSION)
  171226. jdiv_round_up((long) cinfo->image_height, 8L);
  171227. cinfo->min_DCT_scaled_size = 1;
  171228. } else if (cinfo->scale_num * 4 <= cinfo->scale_denom) {
  171229. /* Provide 1/4 scaling */
  171230. cinfo->output_width = (JDIMENSION)
  171231. jdiv_round_up((long) cinfo->image_width, 4L);
  171232. cinfo->output_height = (JDIMENSION)
  171233. jdiv_round_up((long) cinfo->image_height, 4L);
  171234. cinfo->min_DCT_scaled_size = 2;
  171235. } else if (cinfo->scale_num * 2 <= cinfo->scale_denom) {
  171236. /* Provide 1/2 scaling */
  171237. cinfo->output_width = (JDIMENSION)
  171238. jdiv_round_up((long) cinfo->image_width, 2L);
  171239. cinfo->output_height = (JDIMENSION)
  171240. jdiv_round_up((long) cinfo->image_height, 2L);
  171241. cinfo->min_DCT_scaled_size = 4;
  171242. } else {
  171243. /* Provide 1/1 scaling */
  171244. cinfo->output_width = cinfo->image_width;
  171245. cinfo->output_height = cinfo->image_height;
  171246. cinfo->min_DCT_scaled_size = DCTSIZE;
  171247. }
  171248. /* In selecting the actual DCT scaling for each component, we try to
  171249. * scale up the chroma components via IDCT scaling rather than upsampling.
  171250. * This saves time if the upsampler gets to use 1:1 scaling.
  171251. * Note this code assumes that the supported DCT scalings are powers of 2.
  171252. */
  171253. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171254. ci++, compptr++) {
  171255. int ssize = cinfo->min_DCT_scaled_size;
  171256. while (ssize < DCTSIZE &&
  171257. (compptr->h_samp_factor * ssize * 2 <=
  171258. cinfo->max_h_samp_factor * cinfo->min_DCT_scaled_size) &&
  171259. (compptr->v_samp_factor * ssize * 2 <=
  171260. cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size)) {
  171261. ssize = ssize * 2;
  171262. }
  171263. compptr->DCT_scaled_size = ssize;
  171264. }
  171265. /* Recompute downsampled dimensions of components;
  171266. * application needs to know these if using raw downsampled data.
  171267. */
  171268. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171269. ci++, compptr++) {
  171270. /* Size in samples, after IDCT scaling */
  171271. compptr->downsampled_width = (JDIMENSION)
  171272. jdiv_round_up((long) cinfo->image_width *
  171273. (long) (compptr->h_samp_factor * compptr->DCT_scaled_size),
  171274. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  171275. compptr->downsampled_height = (JDIMENSION)
  171276. jdiv_round_up((long) cinfo->image_height *
  171277. (long) (compptr->v_samp_factor * compptr->DCT_scaled_size),
  171278. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  171279. }
  171280. #else /* !IDCT_SCALING_SUPPORTED */
  171281. /* Hardwire it to "no scaling" */
  171282. cinfo->output_width = cinfo->image_width;
  171283. cinfo->output_height = cinfo->image_height;
  171284. /* jdinput.c has already initialized DCT_scaled_size to DCTSIZE,
  171285. * and has computed unscaled downsampled_width and downsampled_height.
  171286. */
  171287. #endif /* IDCT_SCALING_SUPPORTED */
  171288. /* Report number of components in selected colorspace. */
  171289. /* Probably this should be in the color conversion module... */
  171290. switch (cinfo->out_color_space) {
  171291. case JCS_GRAYSCALE:
  171292. cinfo->out_color_components = 1;
  171293. break;
  171294. case JCS_RGB:
  171295. #if RGB_PIXELSIZE != 3
  171296. cinfo->out_color_components = RGB_PIXELSIZE;
  171297. break;
  171298. #endif /* else share code with YCbCr */
  171299. case JCS_YCbCr:
  171300. cinfo->out_color_components = 3;
  171301. break;
  171302. case JCS_CMYK:
  171303. case JCS_YCCK:
  171304. cinfo->out_color_components = 4;
  171305. break;
  171306. default: /* else must be same colorspace as in file */
  171307. cinfo->out_color_components = cinfo->num_components;
  171308. break;
  171309. }
  171310. cinfo->output_components = (cinfo->quantize_colors ? 1 :
  171311. cinfo->out_color_components);
  171312. /* See if upsampler will want to emit more than one row at a time */
  171313. if (use_merged_upsample(cinfo))
  171314. cinfo->rec_outbuf_height = cinfo->max_v_samp_factor;
  171315. else
  171316. cinfo->rec_outbuf_height = 1;
  171317. }
  171318. /*
  171319. * Several decompression processes need to range-limit values to the range
  171320. * 0..MAXJSAMPLE; the input value may fall somewhat outside this range
  171321. * due to noise introduced by quantization, roundoff error, etc. These
  171322. * processes are inner loops and need to be as fast as possible. On most
  171323. * machines, particularly CPUs with pipelines or instruction prefetch,
  171324. * a (subscript-check-less) C table lookup
  171325. * x = sample_range_limit[x];
  171326. * is faster than explicit tests
  171327. * if (x < 0) x = 0;
  171328. * else if (x > MAXJSAMPLE) x = MAXJSAMPLE;
  171329. * These processes all use a common table prepared by the routine below.
  171330. *
  171331. * For most steps we can mathematically guarantee that the initial value
  171332. * of x is within MAXJSAMPLE+1 of the legal range, so a table running from
  171333. * -(MAXJSAMPLE+1) to 2*MAXJSAMPLE+1 is sufficient. But for the initial
  171334. * limiting step (just after the IDCT), a wildly out-of-range value is
  171335. * possible if the input data is corrupt. To avoid any chance of indexing
  171336. * off the end of memory and getting a bad-pointer trap, we perform the
  171337. * post-IDCT limiting thus:
  171338. * x = range_limit[x & MASK];
  171339. * where MASK is 2 bits wider than legal sample data, ie 10 bits for 8-bit
  171340. * samples. Under normal circumstances this is more than enough range and
  171341. * a correct output will be generated; with bogus input data the mask will
  171342. * cause wraparound, and we will safely generate a bogus-but-in-range output.
  171343. * For the post-IDCT step, we want to convert the data from signed to unsigned
  171344. * representation by adding CENTERJSAMPLE at the same time that we limit it.
  171345. * So the post-IDCT limiting table ends up looking like this:
  171346. * CENTERJSAMPLE,CENTERJSAMPLE+1,...,MAXJSAMPLE,
  171347. * MAXJSAMPLE (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  171348. * 0 (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  171349. * 0,1,...,CENTERJSAMPLE-1
  171350. * Negative inputs select values from the upper half of the table after
  171351. * masking.
  171352. *
  171353. * We can save some space by overlapping the start of the post-IDCT table
  171354. * with the simpler range limiting table. The post-IDCT table begins at
  171355. * sample_range_limit + CENTERJSAMPLE.
  171356. *
  171357. * Note that the table is allocated in near data space on PCs; it's small
  171358. * enough and used often enough to justify this.
  171359. */
  171360. LOCAL(void)
  171361. prepare_range_limit_table (j_decompress_ptr cinfo)
  171362. /* Allocate and fill in the sample_range_limit table */
  171363. {
  171364. JSAMPLE * table;
  171365. int i;
  171366. table = (JSAMPLE *)
  171367. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171368. (5 * (MAXJSAMPLE+1) + CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  171369. table += (MAXJSAMPLE+1); /* allow negative subscripts of simple table */
  171370. cinfo->sample_range_limit = table;
  171371. /* First segment of "simple" table: limit[x] = 0 for x < 0 */
  171372. MEMZERO(table - (MAXJSAMPLE+1), (MAXJSAMPLE+1) * SIZEOF(JSAMPLE));
  171373. /* Main part of "simple" table: limit[x] = x */
  171374. for (i = 0; i <= MAXJSAMPLE; i++)
  171375. table[i] = (JSAMPLE) i;
  171376. table += CENTERJSAMPLE; /* Point to where post-IDCT table starts */
  171377. /* End of simple table, rest of first half of post-IDCT table */
  171378. for (i = CENTERJSAMPLE; i < 2*(MAXJSAMPLE+1); i++)
  171379. table[i] = MAXJSAMPLE;
  171380. /* Second half of post-IDCT table */
  171381. MEMZERO(table + (2 * (MAXJSAMPLE+1)),
  171382. (2 * (MAXJSAMPLE+1) - CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  171383. MEMCOPY(table + (4 * (MAXJSAMPLE+1) - CENTERJSAMPLE),
  171384. cinfo->sample_range_limit, CENTERJSAMPLE * SIZEOF(JSAMPLE));
  171385. }
  171386. /*
  171387. * Master selection of decompression modules.
  171388. * This is done once at jpeg_start_decompress time. We determine
  171389. * which modules will be used and give them appropriate initialization calls.
  171390. * We also initialize the decompressor input side to begin consuming data.
  171391. *
  171392. * Since jpeg_read_header has finished, we know what is in the SOF
  171393. * and (first) SOS markers. We also have all the application parameter
  171394. * settings.
  171395. */
  171396. LOCAL(void)
  171397. master_selection (j_decompress_ptr cinfo)
  171398. {
  171399. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  171400. boolean use_c_buffer;
  171401. long samplesperrow;
  171402. JDIMENSION jd_samplesperrow;
  171403. /* Initialize dimensions and other stuff */
  171404. jpeg_calc_output_dimensions(cinfo);
  171405. prepare_range_limit_table(cinfo);
  171406. /* Width of an output scanline must be representable as JDIMENSION. */
  171407. samplesperrow = (long) cinfo->output_width * (long) cinfo->out_color_components;
  171408. jd_samplesperrow = (JDIMENSION) samplesperrow;
  171409. if ((long) jd_samplesperrow != samplesperrow)
  171410. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  171411. /* Initialize my private state */
  171412. master->pass_number = 0;
  171413. master->using_merged_upsample = use_merged_upsample(cinfo);
  171414. /* Color quantizer selection */
  171415. master->quantizer_1pass = NULL;
  171416. master->quantizer_2pass = NULL;
  171417. /* No mode changes if not using buffered-image mode. */
  171418. if (! cinfo->quantize_colors || ! cinfo->buffered_image) {
  171419. cinfo->enable_1pass_quant = FALSE;
  171420. cinfo->enable_external_quant = FALSE;
  171421. cinfo->enable_2pass_quant = FALSE;
  171422. }
  171423. if (cinfo->quantize_colors) {
  171424. if (cinfo->raw_data_out)
  171425. ERREXIT(cinfo, JERR_NOTIMPL);
  171426. /* 2-pass quantizer only works in 3-component color space. */
  171427. if (cinfo->out_color_components != 3) {
  171428. cinfo->enable_1pass_quant = TRUE;
  171429. cinfo->enable_external_quant = FALSE;
  171430. cinfo->enable_2pass_quant = FALSE;
  171431. cinfo->colormap = NULL;
  171432. } else if (cinfo->colormap != NULL) {
  171433. cinfo->enable_external_quant = TRUE;
  171434. } else if (cinfo->two_pass_quantize) {
  171435. cinfo->enable_2pass_quant = TRUE;
  171436. } else {
  171437. cinfo->enable_1pass_quant = TRUE;
  171438. }
  171439. if (cinfo->enable_1pass_quant) {
  171440. #ifdef QUANT_1PASS_SUPPORTED
  171441. jinit_1pass_quantizer(cinfo);
  171442. master->quantizer_1pass = cinfo->cquantize;
  171443. #else
  171444. ERREXIT(cinfo, JERR_NOT_COMPILED);
  171445. #endif
  171446. }
  171447. /* We use the 2-pass code to map to external colormaps. */
  171448. if (cinfo->enable_2pass_quant || cinfo->enable_external_quant) {
  171449. #ifdef QUANT_2PASS_SUPPORTED
  171450. jinit_2pass_quantizer(cinfo);
  171451. master->quantizer_2pass = cinfo->cquantize;
  171452. #else
  171453. ERREXIT(cinfo, JERR_NOT_COMPILED);
  171454. #endif
  171455. }
  171456. /* If both quantizers are initialized, the 2-pass one is left active;
  171457. * this is necessary for starting with quantization to an external map.
  171458. */
  171459. }
  171460. /* Post-processing: in particular, color conversion first */
  171461. if (! cinfo->raw_data_out) {
  171462. if (master->using_merged_upsample) {
  171463. #ifdef UPSAMPLE_MERGING_SUPPORTED
  171464. jinit_merged_upsampler(cinfo); /* does color conversion too */
  171465. #else
  171466. ERREXIT(cinfo, JERR_NOT_COMPILED);
  171467. #endif
  171468. } else {
  171469. jinit_color_deconverter(cinfo);
  171470. jinit_upsampler(cinfo);
  171471. }
  171472. jinit_d_post_controller(cinfo, cinfo->enable_2pass_quant);
  171473. }
  171474. /* Inverse DCT */
  171475. jinit_inverse_dct(cinfo);
  171476. /* Entropy decoding: either Huffman or arithmetic coding. */
  171477. if (cinfo->arith_code) {
  171478. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  171479. } else {
  171480. if (cinfo->progressive_mode) {
  171481. #ifdef D_PROGRESSIVE_SUPPORTED
  171482. jinit_phuff_decoder(cinfo);
  171483. #else
  171484. ERREXIT(cinfo, JERR_NOT_COMPILED);
  171485. #endif
  171486. } else
  171487. jinit_huff_decoder(cinfo);
  171488. }
  171489. /* Initialize principal buffer controllers. */
  171490. use_c_buffer = cinfo->inputctl->has_multiple_scans || cinfo->buffered_image;
  171491. jinit_d_coef_controller(cinfo, use_c_buffer);
  171492. if (! cinfo->raw_data_out)
  171493. jinit_d_main_controller(cinfo, FALSE /* never need full buffer here */);
  171494. /* We can now tell the memory manager to allocate virtual arrays. */
  171495. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  171496. /* Initialize input side of decompressor to consume first scan. */
  171497. (*cinfo->inputctl->start_input_pass) (cinfo);
  171498. #ifdef D_MULTISCAN_FILES_SUPPORTED
  171499. /* If jpeg_start_decompress will read the whole file, initialize
  171500. * progress monitoring appropriately. The input step is counted
  171501. * as one pass.
  171502. */
  171503. if (cinfo->progress != NULL && ! cinfo->buffered_image &&
  171504. cinfo->inputctl->has_multiple_scans) {
  171505. int nscans;
  171506. /* Estimate number of scans to set pass_limit. */
  171507. if (cinfo->progressive_mode) {
  171508. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  171509. nscans = 2 + 3 * cinfo->num_components;
  171510. } else {
  171511. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  171512. nscans = cinfo->num_components;
  171513. }
  171514. cinfo->progress->pass_counter = 0L;
  171515. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  171516. cinfo->progress->completed_passes = 0;
  171517. cinfo->progress->total_passes = (cinfo->enable_2pass_quant ? 3 : 2);
  171518. /* Count the input pass as done */
  171519. master->pass_number++;
  171520. }
  171521. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  171522. }
  171523. /*
  171524. * Per-pass setup.
  171525. * This is called at the beginning of each output pass. We determine which
  171526. * modules will be active during this pass and give them appropriate
  171527. * start_pass calls. We also set is_dummy_pass to indicate whether this
  171528. * is a "real" output pass or a dummy pass for color quantization.
  171529. * (In the latter case, jdapistd.c will crank the pass to completion.)
  171530. */
  171531. METHODDEF(void)
  171532. prepare_for_output_pass (j_decompress_ptr cinfo)
  171533. {
  171534. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  171535. if (master->pub.is_dummy_pass) {
  171536. #ifdef QUANT_2PASS_SUPPORTED
  171537. /* Final pass of 2-pass quantization */
  171538. master->pub.is_dummy_pass = FALSE;
  171539. (*cinfo->cquantize->start_pass) (cinfo, FALSE);
  171540. (*cinfo->post->start_pass) (cinfo, JBUF_CRANK_DEST);
  171541. (*cinfo->main->start_pass) (cinfo, JBUF_CRANK_DEST);
  171542. #else
  171543. ERREXIT(cinfo, JERR_NOT_COMPILED);
  171544. #endif /* QUANT_2PASS_SUPPORTED */
  171545. } else {
  171546. if (cinfo->quantize_colors && cinfo->colormap == NULL) {
  171547. /* Select new quantization method */
  171548. if (cinfo->two_pass_quantize && cinfo->enable_2pass_quant) {
  171549. cinfo->cquantize = master->quantizer_2pass;
  171550. master->pub.is_dummy_pass = TRUE;
  171551. } else if (cinfo->enable_1pass_quant) {
  171552. cinfo->cquantize = master->quantizer_1pass;
  171553. } else {
  171554. ERREXIT(cinfo, JERR_MODE_CHANGE);
  171555. }
  171556. }
  171557. (*cinfo->idct->start_pass) (cinfo);
  171558. (*cinfo->coef->start_output_pass) (cinfo);
  171559. if (! cinfo->raw_data_out) {
  171560. if (! master->using_merged_upsample)
  171561. (*cinfo->cconvert->start_pass) (cinfo);
  171562. (*cinfo->upsample->start_pass) (cinfo);
  171563. if (cinfo->quantize_colors)
  171564. (*cinfo->cquantize->start_pass) (cinfo, master->pub.is_dummy_pass);
  171565. (*cinfo->post->start_pass) (cinfo,
  171566. (master->pub.is_dummy_pass ? JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  171567. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  171568. }
  171569. }
  171570. /* Set up progress monitor's pass info if present */
  171571. if (cinfo->progress != NULL) {
  171572. cinfo->progress->completed_passes = master->pass_number;
  171573. cinfo->progress->total_passes = master->pass_number +
  171574. (master->pub.is_dummy_pass ? 2 : 1);
  171575. /* In buffered-image mode, we assume one more output pass if EOI not
  171576. * yet reached, but no more passes if EOI has been reached.
  171577. */
  171578. if (cinfo->buffered_image && ! cinfo->inputctl->eoi_reached) {
  171579. cinfo->progress->total_passes += (cinfo->enable_2pass_quant ? 2 : 1);
  171580. }
  171581. }
  171582. }
  171583. /*
  171584. * Finish up at end of an output pass.
  171585. */
  171586. METHODDEF(void)
  171587. finish_output_pass (j_decompress_ptr cinfo)
  171588. {
  171589. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  171590. if (cinfo->quantize_colors)
  171591. (*cinfo->cquantize->finish_pass) (cinfo);
  171592. master->pass_number++;
  171593. }
  171594. #ifdef D_MULTISCAN_FILES_SUPPORTED
  171595. /*
  171596. * Switch to a new external colormap between output passes.
  171597. */
  171598. GLOBAL(void)
  171599. jpeg_new_colormap (j_decompress_ptr cinfo)
  171600. {
  171601. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  171602. /* Prevent application from calling me at wrong times */
  171603. if (cinfo->global_state != DSTATE_BUFIMAGE)
  171604. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  171605. if (cinfo->quantize_colors && cinfo->enable_external_quant &&
  171606. cinfo->colormap != NULL) {
  171607. /* Select 2-pass quantizer for external colormap use */
  171608. cinfo->cquantize = master->quantizer_2pass;
  171609. /* Notify quantizer of colormap change */
  171610. (*cinfo->cquantize->new_color_map) (cinfo);
  171611. master->pub.is_dummy_pass = FALSE; /* just in case */
  171612. } else
  171613. ERREXIT(cinfo, JERR_MODE_CHANGE);
  171614. }
  171615. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  171616. /*
  171617. * Initialize master decompression control and select active modules.
  171618. * This is performed at the start of jpeg_start_decompress.
  171619. */
  171620. GLOBAL(void)
  171621. jinit_master_decompress (j_decompress_ptr cinfo)
  171622. {
  171623. my_master_ptr6 master;
  171624. master = (my_master_ptr6)
  171625. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171626. SIZEOF(my_decomp_master));
  171627. cinfo->master = (struct jpeg_decomp_master *) master;
  171628. master->pub.prepare_for_output_pass = prepare_for_output_pass;
  171629. master->pub.finish_output_pass = finish_output_pass;
  171630. master->pub.is_dummy_pass = FALSE;
  171631. master_selection(cinfo);
  171632. }
  171633. /*** End of inlined file: jdmaster.c ***/
  171634. #undef FIX
  171635. /*** Start of inlined file: jdmerge.c ***/
  171636. #define JPEG_INTERNALS
  171637. #ifdef UPSAMPLE_MERGING_SUPPORTED
  171638. /* Private subobject */
  171639. typedef struct {
  171640. struct jpeg_upsampler pub; /* public fields */
  171641. /* Pointer to routine to do actual upsampling/conversion of one row group */
  171642. JMETHOD(void, upmethod, (j_decompress_ptr cinfo,
  171643. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  171644. JSAMPARRAY output_buf));
  171645. /* Private state for YCC->RGB conversion */
  171646. int * Cr_r_tab; /* => table for Cr to R conversion */
  171647. int * Cb_b_tab; /* => table for Cb to B conversion */
  171648. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  171649. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  171650. /* For 2:1 vertical sampling, we produce two output rows at a time.
  171651. * We need a "spare" row buffer to hold the second output row if the
  171652. * application provides just a one-row buffer; we also use the spare
  171653. * to discard the dummy last row if the image height is odd.
  171654. */
  171655. JSAMPROW spare_row;
  171656. boolean spare_full; /* T if spare buffer is occupied */
  171657. JDIMENSION out_row_width; /* samples per output row */
  171658. JDIMENSION rows_to_go; /* counts rows remaining in image */
  171659. } my_upsampler;
  171660. typedef my_upsampler * my_upsample_ptr;
  171661. #define SCALEBITS 16 /* speediest right-shift on some machines */
  171662. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  171663. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  171664. /*
  171665. * Initialize tables for YCC->RGB colorspace conversion.
  171666. * This is taken directly from jdcolor.c; see that file for more info.
  171667. */
  171668. LOCAL(void)
  171669. build_ycc_rgb_table2 (j_decompress_ptr cinfo)
  171670. {
  171671. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  171672. int i;
  171673. INT32 x;
  171674. SHIFT_TEMPS
  171675. upsample->Cr_r_tab = (int *)
  171676. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171677. (MAXJSAMPLE+1) * SIZEOF(int));
  171678. upsample->Cb_b_tab = (int *)
  171679. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171680. (MAXJSAMPLE+1) * SIZEOF(int));
  171681. upsample->Cr_g_tab = (INT32 *)
  171682. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171683. (MAXJSAMPLE+1) * SIZEOF(INT32));
  171684. upsample->Cb_g_tab = (INT32 *)
  171685. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171686. (MAXJSAMPLE+1) * SIZEOF(INT32));
  171687. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  171688. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  171689. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  171690. /* Cr=>R value is nearest int to 1.40200 * x */
  171691. upsample->Cr_r_tab[i] = (int)
  171692. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  171693. /* Cb=>B value is nearest int to 1.77200 * x */
  171694. upsample->Cb_b_tab[i] = (int)
  171695. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  171696. /* Cr=>G value is scaled-up -0.71414 * x */
  171697. upsample->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  171698. /* Cb=>G value is scaled-up -0.34414 * x */
  171699. /* We also add in ONE_HALF so that need not do it in inner loop */
  171700. upsample->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  171701. }
  171702. }
  171703. /*
  171704. * Initialize for an upsampling pass.
  171705. */
  171706. METHODDEF(void)
  171707. start_pass_merged_upsample (j_decompress_ptr cinfo)
  171708. {
  171709. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  171710. /* Mark the spare buffer empty */
  171711. upsample->spare_full = FALSE;
  171712. /* Initialize total-height counter for detecting bottom of image */
  171713. upsample->rows_to_go = cinfo->output_height;
  171714. }
  171715. /*
  171716. * Control routine to do upsampling (and color conversion).
  171717. *
  171718. * The control routine just handles the row buffering considerations.
  171719. */
  171720. METHODDEF(void)
  171721. merged_2v_upsample (j_decompress_ptr cinfo,
  171722. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  171723. JDIMENSION,
  171724. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  171725. JDIMENSION out_rows_avail)
  171726. /* 2:1 vertical sampling case: may need a spare row. */
  171727. {
  171728. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  171729. JSAMPROW work_ptrs[2];
  171730. JDIMENSION num_rows; /* number of rows returned to caller */
  171731. if (upsample->spare_full) {
  171732. /* If we have a spare row saved from a previous cycle, just return it. */
  171733. jcopy_sample_rows(& upsample->spare_row, 0, output_buf + *out_row_ctr, 0,
  171734. 1, upsample->out_row_width);
  171735. num_rows = 1;
  171736. upsample->spare_full = FALSE;
  171737. } else {
  171738. /* Figure number of rows to return to caller. */
  171739. num_rows = 2;
  171740. /* Not more than the distance to the end of the image. */
  171741. if (num_rows > upsample->rows_to_go)
  171742. num_rows = upsample->rows_to_go;
  171743. /* And not more than what the client can accept: */
  171744. out_rows_avail -= *out_row_ctr;
  171745. if (num_rows > out_rows_avail)
  171746. num_rows = out_rows_avail;
  171747. /* Create output pointer array for upsampler. */
  171748. work_ptrs[0] = output_buf[*out_row_ctr];
  171749. if (num_rows > 1) {
  171750. work_ptrs[1] = output_buf[*out_row_ctr + 1];
  171751. } else {
  171752. work_ptrs[1] = upsample->spare_row;
  171753. upsample->spare_full = TRUE;
  171754. }
  171755. /* Now do the upsampling. */
  171756. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr, work_ptrs);
  171757. }
  171758. /* Adjust counts */
  171759. *out_row_ctr += num_rows;
  171760. upsample->rows_to_go -= num_rows;
  171761. /* When the buffer is emptied, declare this input row group consumed */
  171762. if (! upsample->spare_full)
  171763. (*in_row_group_ctr)++;
  171764. }
  171765. METHODDEF(void)
  171766. merged_1v_upsample (j_decompress_ptr cinfo,
  171767. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  171768. JDIMENSION,
  171769. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  171770. JDIMENSION)
  171771. /* 1:1 vertical sampling case: much easier, never need a spare row. */
  171772. {
  171773. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  171774. /* Just do the upsampling. */
  171775. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr,
  171776. output_buf + *out_row_ctr);
  171777. /* Adjust counts */
  171778. (*out_row_ctr)++;
  171779. (*in_row_group_ctr)++;
  171780. }
  171781. /*
  171782. * These are the routines invoked by the control routines to do
  171783. * the actual upsampling/conversion. One row group is processed per call.
  171784. *
  171785. * Note: since we may be writing directly into application-supplied buffers,
  171786. * we have to be honest about the output width; we can't assume the buffer
  171787. * has been rounded up to an even width.
  171788. */
  171789. /*
  171790. * Upsample and color convert for the case of 2:1 horizontal and 1:1 vertical.
  171791. */
  171792. METHODDEF(void)
  171793. h2v1_merged_upsample (j_decompress_ptr cinfo,
  171794. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  171795. JSAMPARRAY output_buf)
  171796. {
  171797. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  171798. register int y, cred, cgreen, cblue;
  171799. int cb, cr;
  171800. register JSAMPROW outptr;
  171801. JSAMPROW inptr0, inptr1, inptr2;
  171802. JDIMENSION col;
  171803. /* copy these pointers into registers if possible */
  171804. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  171805. int * Crrtab = upsample->Cr_r_tab;
  171806. int * Cbbtab = upsample->Cb_b_tab;
  171807. INT32 * Crgtab = upsample->Cr_g_tab;
  171808. INT32 * Cbgtab = upsample->Cb_g_tab;
  171809. SHIFT_TEMPS
  171810. inptr0 = input_buf[0][in_row_group_ctr];
  171811. inptr1 = input_buf[1][in_row_group_ctr];
  171812. inptr2 = input_buf[2][in_row_group_ctr];
  171813. outptr = output_buf[0];
  171814. /* Loop for each pair of output pixels */
  171815. for (col = cinfo->output_width >> 1; col > 0; col--) {
  171816. /* Do the chroma part of the calculation */
  171817. cb = GETJSAMPLE(*inptr1++);
  171818. cr = GETJSAMPLE(*inptr2++);
  171819. cred = Crrtab[cr];
  171820. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  171821. cblue = Cbbtab[cb];
  171822. /* Fetch 2 Y values and emit 2 pixels */
  171823. y = GETJSAMPLE(*inptr0++);
  171824. outptr[RGB_RED] = range_limit[y + cred];
  171825. outptr[RGB_GREEN] = range_limit[y + cgreen];
  171826. outptr[RGB_BLUE] = range_limit[y + cblue];
  171827. outptr += RGB_PIXELSIZE;
  171828. y = GETJSAMPLE(*inptr0++);
  171829. outptr[RGB_RED] = range_limit[y + cred];
  171830. outptr[RGB_GREEN] = range_limit[y + cgreen];
  171831. outptr[RGB_BLUE] = range_limit[y + cblue];
  171832. outptr += RGB_PIXELSIZE;
  171833. }
  171834. /* If image width is odd, do the last output column separately */
  171835. if (cinfo->output_width & 1) {
  171836. cb = GETJSAMPLE(*inptr1);
  171837. cr = GETJSAMPLE(*inptr2);
  171838. cred = Crrtab[cr];
  171839. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  171840. cblue = Cbbtab[cb];
  171841. y = GETJSAMPLE(*inptr0);
  171842. outptr[RGB_RED] = range_limit[y + cred];
  171843. outptr[RGB_GREEN] = range_limit[y + cgreen];
  171844. outptr[RGB_BLUE] = range_limit[y + cblue];
  171845. }
  171846. }
  171847. /*
  171848. * Upsample and color convert for the case of 2:1 horizontal and 2:1 vertical.
  171849. */
  171850. METHODDEF(void)
  171851. h2v2_merged_upsample (j_decompress_ptr cinfo,
  171852. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  171853. JSAMPARRAY output_buf)
  171854. {
  171855. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  171856. register int y, cred, cgreen, cblue;
  171857. int cb, cr;
  171858. register JSAMPROW outptr0, outptr1;
  171859. JSAMPROW inptr00, inptr01, inptr1, inptr2;
  171860. JDIMENSION col;
  171861. /* copy these pointers into registers if possible */
  171862. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  171863. int * Crrtab = upsample->Cr_r_tab;
  171864. int * Cbbtab = upsample->Cb_b_tab;
  171865. INT32 * Crgtab = upsample->Cr_g_tab;
  171866. INT32 * Cbgtab = upsample->Cb_g_tab;
  171867. SHIFT_TEMPS
  171868. inptr00 = input_buf[0][in_row_group_ctr*2];
  171869. inptr01 = input_buf[0][in_row_group_ctr*2 + 1];
  171870. inptr1 = input_buf[1][in_row_group_ctr];
  171871. inptr2 = input_buf[2][in_row_group_ctr];
  171872. outptr0 = output_buf[0];
  171873. outptr1 = output_buf[1];
  171874. /* Loop for each group of output pixels */
  171875. for (col = cinfo->output_width >> 1; col > 0; col--) {
  171876. /* Do the chroma part of the calculation */
  171877. cb = GETJSAMPLE(*inptr1++);
  171878. cr = GETJSAMPLE(*inptr2++);
  171879. cred = Crrtab[cr];
  171880. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  171881. cblue = Cbbtab[cb];
  171882. /* Fetch 4 Y values and emit 4 pixels */
  171883. y = GETJSAMPLE(*inptr00++);
  171884. outptr0[RGB_RED] = range_limit[y + cred];
  171885. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  171886. outptr0[RGB_BLUE] = range_limit[y + cblue];
  171887. outptr0 += RGB_PIXELSIZE;
  171888. y = GETJSAMPLE(*inptr00++);
  171889. outptr0[RGB_RED] = range_limit[y + cred];
  171890. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  171891. outptr0[RGB_BLUE] = range_limit[y + cblue];
  171892. outptr0 += RGB_PIXELSIZE;
  171893. y = GETJSAMPLE(*inptr01++);
  171894. outptr1[RGB_RED] = range_limit[y + cred];
  171895. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  171896. outptr1[RGB_BLUE] = range_limit[y + cblue];
  171897. outptr1 += RGB_PIXELSIZE;
  171898. y = GETJSAMPLE(*inptr01++);
  171899. outptr1[RGB_RED] = range_limit[y + cred];
  171900. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  171901. outptr1[RGB_BLUE] = range_limit[y + cblue];
  171902. outptr1 += RGB_PIXELSIZE;
  171903. }
  171904. /* If image width is odd, do the last output column separately */
  171905. if (cinfo->output_width & 1) {
  171906. cb = GETJSAMPLE(*inptr1);
  171907. cr = GETJSAMPLE(*inptr2);
  171908. cred = Crrtab[cr];
  171909. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  171910. cblue = Cbbtab[cb];
  171911. y = GETJSAMPLE(*inptr00);
  171912. outptr0[RGB_RED] = range_limit[y + cred];
  171913. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  171914. outptr0[RGB_BLUE] = range_limit[y + cblue];
  171915. y = GETJSAMPLE(*inptr01);
  171916. outptr1[RGB_RED] = range_limit[y + cred];
  171917. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  171918. outptr1[RGB_BLUE] = range_limit[y + cblue];
  171919. }
  171920. }
  171921. /*
  171922. * Module initialization routine for merged upsampling/color conversion.
  171923. *
  171924. * NB: this is called under the conditions determined by use_merged_upsample()
  171925. * in jdmaster.c. That routine MUST correspond to the actual capabilities
  171926. * of this module; no safety checks are made here.
  171927. */
  171928. GLOBAL(void)
  171929. jinit_merged_upsampler (j_decompress_ptr cinfo)
  171930. {
  171931. my_upsample_ptr upsample;
  171932. upsample = (my_upsample_ptr)
  171933. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171934. SIZEOF(my_upsampler));
  171935. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  171936. upsample->pub.start_pass = start_pass_merged_upsample;
  171937. upsample->pub.need_context_rows = FALSE;
  171938. upsample->out_row_width = cinfo->output_width * cinfo->out_color_components;
  171939. if (cinfo->max_v_samp_factor == 2) {
  171940. upsample->pub.upsample = merged_2v_upsample;
  171941. upsample->upmethod = h2v2_merged_upsample;
  171942. /* Allocate a spare row buffer */
  171943. upsample->spare_row = (JSAMPROW)
  171944. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171945. (size_t) (upsample->out_row_width * SIZEOF(JSAMPLE)));
  171946. } else {
  171947. upsample->pub.upsample = merged_1v_upsample;
  171948. upsample->upmethod = h2v1_merged_upsample;
  171949. /* No spare row needed */
  171950. upsample->spare_row = NULL;
  171951. }
  171952. build_ycc_rgb_table2(cinfo);
  171953. }
  171954. #endif /* UPSAMPLE_MERGING_SUPPORTED */
  171955. /*** End of inlined file: jdmerge.c ***/
  171956. #undef ASSIGN_STATE
  171957. /*** Start of inlined file: jdphuff.c ***/
  171958. #define JPEG_INTERNALS
  171959. #ifdef D_PROGRESSIVE_SUPPORTED
  171960. /*
  171961. * Expanded entropy decoder object for progressive Huffman decoding.
  171962. *
  171963. * The savable_state subrecord contains fields that change within an MCU,
  171964. * but must not be updated permanently until we complete the MCU.
  171965. */
  171966. typedef struct {
  171967. unsigned int EOBRUN; /* remaining EOBs in EOBRUN */
  171968. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  171969. } savable_state3;
  171970. /* This macro is to work around compilers with missing or broken
  171971. * structure assignment. You'll need to fix this code if you have
  171972. * such a compiler and you change MAX_COMPS_IN_SCAN.
  171973. */
  171974. #ifndef NO_STRUCT_ASSIGN
  171975. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  171976. #else
  171977. #if MAX_COMPS_IN_SCAN == 4
  171978. #define ASSIGN_STATE(dest,src) \
  171979. ((dest).EOBRUN = (src).EOBRUN, \
  171980. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  171981. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  171982. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  171983. (dest).last_dc_val[3] = (src).last_dc_val[3])
  171984. #endif
  171985. #endif
  171986. typedef struct {
  171987. struct jpeg_entropy_decoder pub; /* public fields */
  171988. /* These fields are loaded into local variables at start of each MCU.
  171989. * In case of suspension, we exit WITHOUT updating them.
  171990. */
  171991. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  171992. savable_state3 saved; /* Other state at start of MCU */
  171993. /* These fields are NOT loaded into local working state. */
  171994. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  171995. /* Pointers to derived tables (these workspaces have image lifespan) */
  171996. d_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  171997. d_derived_tbl * ac_derived_tbl; /* active table during an AC scan */
  171998. } phuff_entropy_decoder;
  171999. typedef phuff_entropy_decoder * phuff_entropy_ptr2;
  172000. /* Forward declarations */
  172001. METHODDEF(boolean) decode_mcu_DC_first JPP((j_decompress_ptr cinfo,
  172002. JBLOCKROW *MCU_data));
  172003. METHODDEF(boolean) decode_mcu_AC_first JPP((j_decompress_ptr cinfo,
  172004. JBLOCKROW *MCU_data));
  172005. METHODDEF(boolean) decode_mcu_DC_refine JPP((j_decompress_ptr cinfo,
  172006. JBLOCKROW *MCU_data));
  172007. METHODDEF(boolean) decode_mcu_AC_refine JPP((j_decompress_ptr cinfo,
  172008. JBLOCKROW *MCU_data));
  172009. /*
  172010. * Initialize for a Huffman-compressed scan.
  172011. */
  172012. METHODDEF(void)
  172013. start_pass_phuff_decoder (j_decompress_ptr cinfo)
  172014. {
  172015. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  172016. boolean is_DC_band, bad;
  172017. int ci, coefi, tbl;
  172018. int *coef_bit_ptr;
  172019. jpeg_component_info * compptr;
  172020. is_DC_band = (cinfo->Ss == 0);
  172021. /* Validate scan parameters */
  172022. bad = FALSE;
  172023. if (is_DC_band) {
  172024. if (cinfo->Se != 0)
  172025. bad = TRUE;
  172026. } else {
  172027. /* need not check Ss/Se < 0 since they came from unsigned bytes */
  172028. if (cinfo->Ss > cinfo->Se || cinfo->Se >= DCTSIZE2)
  172029. bad = TRUE;
  172030. /* AC scans may have only one component */
  172031. if (cinfo->comps_in_scan != 1)
  172032. bad = TRUE;
  172033. }
  172034. if (cinfo->Ah != 0) {
  172035. /* Successive approximation refinement scan: must have Al = Ah-1. */
  172036. if (cinfo->Al != cinfo->Ah-1)
  172037. bad = TRUE;
  172038. }
  172039. if (cinfo->Al > 13) /* need not check for < 0 */
  172040. bad = TRUE;
  172041. /* Arguably the maximum Al value should be less than 13 for 8-bit precision,
  172042. * but the spec doesn't say so, and we try to be liberal about what we
  172043. * accept. Note: large Al values could result in out-of-range DC
  172044. * coefficients during early scans, leading to bizarre displays due to
  172045. * overflows in the IDCT math. But we won't crash.
  172046. */
  172047. if (bad)
  172048. ERREXIT4(cinfo, JERR_BAD_PROGRESSION,
  172049. cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
  172050. /* Update progression status, and verify that scan order is legal.
  172051. * Note that inter-scan inconsistencies are treated as warnings
  172052. * not fatal errors ... not clear if this is right way to behave.
  172053. */
  172054. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  172055. int cindex = cinfo->cur_comp_info[ci]->component_index;
  172056. coef_bit_ptr = & cinfo->coef_bits[cindex][0];
  172057. if (!is_DC_band && coef_bit_ptr[0] < 0) /* AC without prior DC scan */
  172058. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
  172059. for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {
  172060. int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
  172061. if (cinfo->Ah != expected)
  172062. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
  172063. coef_bit_ptr[coefi] = cinfo->Al;
  172064. }
  172065. }
  172066. /* Select MCU decoding routine */
  172067. if (cinfo->Ah == 0) {
  172068. if (is_DC_band)
  172069. entropy->pub.decode_mcu = decode_mcu_DC_first;
  172070. else
  172071. entropy->pub.decode_mcu = decode_mcu_AC_first;
  172072. } else {
  172073. if (is_DC_band)
  172074. entropy->pub.decode_mcu = decode_mcu_DC_refine;
  172075. else
  172076. entropy->pub.decode_mcu = decode_mcu_AC_refine;
  172077. }
  172078. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  172079. compptr = cinfo->cur_comp_info[ci];
  172080. /* Make sure requested tables are present, and compute derived tables.
  172081. * We may build same derived table more than once, but it's not expensive.
  172082. */
  172083. if (is_DC_band) {
  172084. if (cinfo->Ah == 0) { /* DC refinement needs no table */
  172085. tbl = compptr->dc_tbl_no;
  172086. jpeg_make_d_derived_tbl(cinfo, TRUE, tbl,
  172087. & entropy->derived_tbls[tbl]);
  172088. }
  172089. } else {
  172090. tbl = compptr->ac_tbl_no;
  172091. jpeg_make_d_derived_tbl(cinfo, FALSE, tbl,
  172092. & entropy->derived_tbls[tbl]);
  172093. /* remember the single active table */
  172094. entropy->ac_derived_tbl = entropy->derived_tbls[tbl];
  172095. }
  172096. /* Initialize DC predictions to 0 */
  172097. entropy->saved.last_dc_val[ci] = 0;
  172098. }
  172099. /* Initialize bitread state variables */
  172100. entropy->bitstate.bits_left = 0;
  172101. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  172102. entropy->pub.insufficient_data = FALSE;
  172103. /* Initialize private state variables */
  172104. entropy->saved.EOBRUN = 0;
  172105. /* Initialize restart counter */
  172106. entropy->restarts_to_go = cinfo->restart_interval;
  172107. }
  172108. /*
  172109. * Check for a restart marker & resynchronize decoder.
  172110. * Returns FALSE if must suspend.
  172111. */
  172112. LOCAL(boolean)
  172113. process_restartp (j_decompress_ptr cinfo)
  172114. {
  172115. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  172116. int ci;
  172117. /* Throw away any unused bits remaining in bit buffer; */
  172118. /* include any full bytes in next_marker's count of discarded bytes */
  172119. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  172120. entropy->bitstate.bits_left = 0;
  172121. /* Advance past the RSTn marker */
  172122. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  172123. return FALSE;
  172124. /* Re-initialize DC predictions to 0 */
  172125. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  172126. entropy->saved.last_dc_val[ci] = 0;
  172127. /* Re-init EOB run count, too */
  172128. entropy->saved.EOBRUN = 0;
  172129. /* Reset restart counter */
  172130. entropy->restarts_to_go = cinfo->restart_interval;
  172131. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  172132. * against a marker. In that case we will end up treating the next data
  172133. * segment as empty, and we can avoid producing bogus output pixels by
  172134. * leaving the flag set.
  172135. */
  172136. if (cinfo->unread_marker == 0)
  172137. entropy->pub.insufficient_data = FALSE;
  172138. return TRUE;
  172139. }
  172140. /*
  172141. * Huffman MCU decoding.
  172142. * Each of these routines decodes and returns one MCU's worth of
  172143. * Huffman-compressed coefficients.
  172144. * The coefficients are reordered from zigzag order into natural array order,
  172145. * but are not dequantized.
  172146. *
  172147. * The i'th block of the MCU is stored into the block pointed to by
  172148. * MCU_data[i]. WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.
  172149. *
  172150. * We return FALSE if data source requested suspension. In that case no
  172151. * changes have been made to permanent state. (Exception: some output
  172152. * coefficients may already have been assigned. This is harmless for
  172153. * spectral selection, since we'll just re-assign them on the next call.
  172154. * Successive approximation AC refinement has to be more careful, however.)
  172155. */
  172156. /*
  172157. * MCU decoding for DC initial scan (either spectral selection,
  172158. * or first pass of successive approximation).
  172159. */
  172160. METHODDEF(boolean)
  172161. decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  172162. {
  172163. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  172164. int Al = cinfo->Al;
  172165. register int s, r;
  172166. int blkn, ci;
  172167. JBLOCKROW block;
  172168. BITREAD_STATE_VARS;
  172169. savable_state3 state;
  172170. d_derived_tbl * tbl;
  172171. jpeg_component_info * compptr;
  172172. /* Process restart marker if needed; may have to suspend */
  172173. if (cinfo->restart_interval) {
  172174. if (entropy->restarts_to_go == 0)
  172175. if (! process_restartp(cinfo))
  172176. return FALSE;
  172177. }
  172178. /* If we've run out of data, just leave the MCU set to zeroes.
  172179. * This way, we return uniform gray for the remainder of the segment.
  172180. */
  172181. if (! entropy->pub.insufficient_data) {
  172182. /* Load up working state */
  172183. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  172184. ASSIGN_STATE(state, entropy->saved);
  172185. /* Outer loop handles each block in the MCU */
  172186. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  172187. block = MCU_data[blkn];
  172188. ci = cinfo->MCU_membership[blkn];
  172189. compptr = cinfo->cur_comp_info[ci];
  172190. tbl = entropy->derived_tbls[compptr->dc_tbl_no];
  172191. /* Decode a single block's worth of coefficients */
  172192. /* Section F.2.2.1: decode the DC coefficient difference */
  172193. HUFF_DECODE(s, br_state, tbl, return FALSE, label1);
  172194. if (s) {
  172195. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  172196. r = GET_BITS(s);
  172197. s = HUFF_EXTEND(r, s);
  172198. }
  172199. /* Convert DC difference to actual value, update last_dc_val */
  172200. s += state.last_dc_val[ci];
  172201. state.last_dc_val[ci] = s;
  172202. /* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */
  172203. (*block)[0] = (JCOEF) (s << Al);
  172204. }
  172205. /* Completed MCU, so update state */
  172206. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  172207. ASSIGN_STATE(entropy->saved, state);
  172208. }
  172209. /* Account for restart interval (no-op if not using restarts) */
  172210. entropy->restarts_to_go--;
  172211. return TRUE;
  172212. }
  172213. /*
  172214. * MCU decoding for AC initial scan (either spectral selection,
  172215. * or first pass of successive approximation).
  172216. */
  172217. METHODDEF(boolean)
  172218. decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  172219. {
  172220. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  172221. int Se = cinfo->Se;
  172222. int Al = cinfo->Al;
  172223. register int s, k, r;
  172224. unsigned int EOBRUN;
  172225. JBLOCKROW block;
  172226. BITREAD_STATE_VARS;
  172227. d_derived_tbl * tbl;
  172228. /* Process restart marker if needed; may have to suspend */
  172229. if (cinfo->restart_interval) {
  172230. if (entropy->restarts_to_go == 0)
  172231. if (! process_restartp(cinfo))
  172232. return FALSE;
  172233. }
  172234. /* If we've run out of data, just leave the MCU set to zeroes.
  172235. * This way, we return uniform gray for the remainder of the segment.
  172236. */
  172237. if (! entropy->pub.insufficient_data) {
  172238. /* Load up working state.
  172239. * We can avoid loading/saving bitread state if in an EOB run.
  172240. */
  172241. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  172242. /* There is always only one block per MCU */
  172243. if (EOBRUN > 0) /* if it's a band of zeroes... */
  172244. EOBRUN--; /* ...process it now (we do nothing) */
  172245. else {
  172246. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  172247. block = MCU_data[0];
  172248. tbl = entropy->ac_derived_tbl;
  172249. for (k = cinfo->Ss; k <= Se; k++) {
  172250. HUFF_DECODE(s, br_state, tbl, return FALSE, label2);
  172251. r = s >> 4;
  172252. s &= 15;
  172253. if (s) {
  172254. k += r;
  172255. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  172256. r = GET_BITS(s);
  172257. s = HUFF_EXTEND(r, s);
  172258. /* Scale and output coefficient in natural (dezigzagged) order */
  172259. (*block)[jpeg_natural_order[k]] = (JCOEF) (s << Al);
  172260. } else {
  172261. if (r == 15) { /* ZRL */
  172262. k += 15; /* skip 15 zeroes in band */
  172263. } else { /* EOBr, run length is 2^r + appended bits */
  172264. EOBRUN = 1 << r;
  172265. if (r) { /* EOBr, r > 0 */
  172266. CHECK_BIT_BUFFER(br_state, r, return FALSE);
  172267. r = GET_BITS(r);
  172268. EOBRUN += r;
  172269. }
  172270. EOBRUN--; /* this band is processed at this moment */
  172271. break; /* force end-of-band */
  172272. }
  172273. }
  172274. }
  172275. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  172276. }
  172277. /* Completed MCU, so update state */
  172278. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  172279. }
  172280. /* Account for restart interval (no-op if not using restarts) */
  172281. entropy->restarts_to_go--;
  172282. return TRUE;
  172283. }
  172284. /*
  172285. * MCU decoding for DC successive approximation refinement scan.
  172286. * Note: we assume such scans can be multi-component, although the spec
  172287. * is not very clear on the point.
  172288. */
  172289. METHODDEF(boolean)
  172290. decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  172291. {
  172292. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  172293. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  172294. int blkn;
  172295. JBLOCKROW block;
  172296. BITREAD_STATE_VARS;
  172297. /* Process restart marker if needed; may have to suspend */
  172298. if (cinfo->restart_interval) {
  172299. if (entropy->restarts_to_go == 0)
  172300. if (! process_restartp(cinfo))
  172301. return FALSE;
  172302. }
  172303. /* Not worth the cycles to check insufficient_data here,
  172304. * since we will not change the data anyway if we read zeroes.
  172305. */
  172306. /* Load up working state */
  172307. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  172308. /* Outer loop handles each block in the MCU */
  172309. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  172310. block = MCU_data[blkn];
  172311. /* Encoded data is simply the next bit of the two's-complement DC value */
  172312. CHECK_BIT_BUFFER(br_state, 1, return FALSE);
  172313. if (GET_BITS(1))
  172314. (*block)[0] |= p1;
  172315. /* Note: since we use |=, repeating the assignment later is safe */
  172316. }
  172317. /* Completed MCU, so update state */
  172318. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  172319. /* Account for restart interval (no-op if not using restarts) */
  172320. entropy->restarts_to_go--;
  172321. return TRUE;
  172322. }
  172323. /*
  172324. * MCU decoding for AC successive approximation refinement scan.
  172325. */
  172326. METHODDEF(boolean)
  172327. decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  172328. {
  172329. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  172330. int Se = cinfo->Se;
  172331. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  172332. int m1 = (-1) << cinfo->Al; /* -1 in the bit position being coded */
  172333. register int s, k, r;
  172334. unsigned int EOBRUN;
  172335. JBLOCKROW block;
  172336. JCOEFPTR thiscoef;
  172337. BITREAD_STATE_VARS;
  172338. d_derived_tbl * tbl;
  172339. int num_newnz;
  172340. int newnz_pos[DCTSIZE2];
  172341. /* Process restart marker if needed; may have to suspend */
  172342. if (cinfo->restart_interval) {
  172343. if (entropy->restarts_to_go == 0)
  172344. if (! process_restartp(cinfo))
  172345. return FALSE;
  172346. }
  172347. /* If we've run out of data, don't modify the MCU.
  172348. */
  172349. if (! entropy->pub.insufficient_data) {
  172350. /* Load up working state */
  172351. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  172352. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  172353. /* There is always only one block per MCU */
  172354. block = MCU_data[0];
  172355. tbl = entropy->ac_derived_tbl;
  172356. /* If we are forced to suspend, we must undo the assignments to any newly
  172357. * nonzero coefficients in the block, because otherwise we'd get confused
  172358. * next time about which coefficients were already nonzero.
  172359. * But we need not undo addition of bits to already-nonzero coefficients;
  172360. * instead, we can test the current bit to see if we already did it.
  172361. */
  172362. num_newnz = 0;
  172363. /* initialize coefficient loop counter to start of band */
  172364. k = cinfo->Ss;
  172365. if (EOBRUN == 0) {
  172366. for (; k <= Se; k++) {
  172367. HUFF_DECODE(s, br_state, tbl, goto undoit, label3);
  172368. r = s >> 4;
  172369. s &= 15;
  172370. if (s) {
  172371. if (s != 1) /* size of new coef should always be 1 */
  172372. WARNMS(cinfo, JWRN_HUFF_BAD_CODE);
  172373. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  172374. if (GET_BITS(1))
  172375. s = p1; /* newly nonzero coef is positive */
  172376. else
  172377. s = m1; /* newly nonzero coef is negative */
  172378. } else {
  172379. if (r != 15) {
  172380. EOBRUN = 1 << r; /* EOBr, run length is 2^r + appended bits */
  172381. if (r) {
  172382. CHECK_BIT_BUFFER(br_state, r, goto undoit);
  172383. r = GET_BITS(r);
  172384. EOBRUN += r;
  172385. }
  172386. break; /* rest of block is handled by EOB logic */
  172387. }
  172388. /* note s = 0 for processing ZRL */
  172389. }
  172390. /* Advance over already-nonzero coefs and r still-zero coefs,
  172391. * appending correction bits to the nonzeroes. A correction bit is 1
  172392. * if the absolute value of the coefficient must be increased.
  172393. */
  172394. do {
  172395. thiscoef = *block + jpeg_natural_order[k];
  172396. if (*thiscoef != 0) {
  172397. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  172398. if (GET_BITS(1)) {
  172399. if ((*thiscoef & p1) == 0) { /* do nothing if already set it */
  172400. if (*thiscoef >= 0)
  172401. *thiscoef += p1;
  172402. else
  172403. *thiscoef += m1;
  172404. }
  172405. }
  172406. } else {
  172407. if (--r < 0)
  172408. break; /* reached target zero coefficient */
  172409. }
  172410. k++;
  172411. } while (k <= Se);
  172412. if (s) {
  172413. int pos = jpeg_natural_order[k];
  172414. /* Output newly nonzero coefficient */
  172415. (*block)[pos] = (JCOEF) s;
  172416. /* Remember its position in case we have to suspend */
  172417. newnz_pos[num_newnz++] = pos;
  172418. }
  172419. }
  172420. }
  172421. if (EOBRUN > 0) {
  172422. /* Scan any remaining coefficient positions after the end-of-band
  172423. * (the last newly nonzero coefficient, if any). Append a correction
  172424. * bit to each already-nonzero coefficient. A correction bit is 1
  172425. * if the absolute value of the coefficient must be increased.
  172426. */
  172427. for (; k <= Se; k++) {
  172428. thiscoef = *block + jpeg_natural_order[k];
  172429. if (*thiscoef != 0) {
  172430. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  172431. if (GET_BITS(1)) {
  172432. if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
  172433. if (*thiscoef >= 0)
  172434. *thiscoef += p1;
  172435. else
  172436. *thiscoef += m1;
  172437. }
  172438. }
  172439. }
  172440. }
  172441. /* Count one block completed in EOB run */
  172442. EOBRUN--;
  172443. }
  172444. /* Completed MCU, so update state */
  172445. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  172446. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  172447. }
  172448. /* Account for restart interval (no-op if not using restarts) */
  172449. entropy->restarts_to_go--;
  172450. return TRUE;
  172451. undoit:
  172452. /* Re-zero any output coefficients that we made newly nonzero */
  172453. while (num_newnz > 0)
  172454. (*block)[newnz_pos[--num_newnz]] = 0;
  172455. return FALSE;
  172456. }
  172457. /*
  172458. * Module initialization routine for progressive Huffman entropy decoding.
  172459. */
  172460. GLOBAL(void)
  172461. jinit_phuff_decoder (j_decompress_ptr cinfo)
  172462. {
  172463. phuff_entropy_ptr2 entropy;
  172464. int *coef_bit_ptr;
  172465. int ci, i;
  172466. entropy = (phuff_entropy_ptr2)
  172467. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172468. SIZEOF(phuff_entropy_decoder));
  172469. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  172470. entropy->pub.start_pass = start_pass_phuff_decoder;
  172471. /* Mark derived tables unallocated */
  172472. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  172473. entropy->derived_tbls[i] = NULL;
  172474. }
  172475. /* Create progression status table */
  172476. cinfo->coef_bits = (int (*)[DCTSIZE2])
  172477. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172478. cinfo->num_components*DCTSIZE2*SIZEOF(int));
  172479. coef_bit_ptr = & cinfo->coef_bits[0][0];
  172480. for (ci = 0; ci < cinfo->num_components; ci++)
  172481. for (i = 0; i < DCTSIZE2; i++)
  172482. *coef_bit_ptr++ = -1;
  172483. }
  172484. #endif /* D_PROGRESSIVE_SUPPORTED */
  172485. /*** End of inlined file: jdphuff.c ***/
  172486. /*** Start of inlined file: jdpostct.c ***/
  172487. #define JPEG_INTERNALS
  172488. /* Private buffer controller object */
  172489. typedef struct {
  172490. struct jpeg_d_post_controller pub; /* public fields */
  172491. /* Color quantization source buffer: this holds output data from
  172492. * the upsample/color conversion step to be passed to the quantizer.
  172493. * For two-pass color quantization, we need a full-image buffer;
  172494. * for one-pass operation, a strip buffer is sufficient.
  172495. */
  172496. jvirt_sarray_ptr whole_image; /* virtual array, or NULL if one-pass */
  172497. JSAMPARRAY buffer; /* strip buffer, or current strip of virtual */
  172498. JDIMENSION strip_height; /* buffer size in rows */
  172499. /* for two-pass mode only: */
  172500. JDIMENSION starting_row; /* row # of first row in current strip */
  172501. JDIMENSION next_row; /* index of next row to fill/empty in strip */
  172502. } my_post_controller;
  172503. typedef my_post_controller * my_post_ptr;
  172504. /* Forward declarations */
  172505. METHODDEF(void) post_process_1pass
  172506. JPP((j_decompress_ptr cinfo,
  172507. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172508. JDIMENSION in_row_groups_avail,
  172509. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172510. JDIMENSION out_rows_avail));
  172511. #ifdef QUANT_2PASS_SUPPORTED
  172512. METHODDEF(void) post_process_prepass
  172513. JPP((j_decompress_ptr cinfo,
  172514. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172515. JDIMENSION in_row_groups_avail,
  172516. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172517. JDIMENSION out_rows_avail));
  172518. METHODDEF(void) post_process_2pass
  172519. JPP((j_decompress_ptr cinfo,
  172520. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172521. JDIMENSION in_row_groups_avail,
  172522. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172523. JDIMENSION out_rows_avail));
  172524. #endif
  172525. /*
  172526. * Initialize for a processing pass.
  172527. */
  172528. METHODDEF(void)
  172529. start_pass_dpost (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  172530. {
  172531. my_post_ptr post = (my_post_ptr) cinfo->post;
  172532. switch (pass_mode) {
  172533. case JBUF_PASS_THRU:
  172534. if (cinfo->quantize_colors) {
  172535. /* Single-pass processing with color quantization. */
  172536. post->pub.post_process_data = post_process_1pass;
  172537. /* We could be doing buffered-image output before starting a 2-pass
  172538. * color quantization; in that case, jinit_d_post_controller did not
  172539. * allocate a strip buffer. Use the virtual-array buffer as workspace.
  172540. */
  172541. if (post->buffer == NULL) {
  172542. post->buffer = (*cinfo->mem->access_virt_sarray)
  172543. ((j_common_ptr) cinfo, post->whole_image,
  172544. (JDIMENSION) 0, post->strip_height, TRUE);
  172545. }
  172546. } else {
  172547. /* For single-pass processing without color quantization,
  172548. * I have no work to do; just call the upsampler directly.
  172549. */
  172550. post->pub.post_process_data = cinfo->upsample->upsample;
  172551. }
  172552. break;
  172553. #ifdef QUANT_2PASS_SUPPORTED
  172554. case JBUF_SAVE_AND_PASS:
  172555. /* First pass of 2-pass quantization */
  172556. if (post->whole_image == NULL)
  172557. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  172558. post->pub.post_process_data = post_process_prepass;
  172559. break;
  172560. case JBUF_CRANK_DEST:
  172561. /* Second pass of 2-pass quantization */
  172562. if (post->whole_image == NULL)
  172563. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  172564. post->pub.post_process_data = post_process_2pass;
  172565. break;
  172566. #endif /* QUANT_2PASS_SUPPORTED */
  172567. default:
  172568. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  172569. break;
  172570. }
  172571. post->starting_row = post->next_row = 0;
  172572. }
  172573. /*
  172574. * Process some data in the one-pass (strip buffer) case.
  172575. * This is used for color precision reduction as well as one-pass quantization.
  172576. */
  172577. METHODDEF(void)
  172578. post_process_1pass (j_decompress_ptr cinfo,
  172579. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172580. JDIMENSION in_row_groups_avail,
  172581. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172582. JDIMENSION out_rows_avail)
  172583. {
  172584. my_post_ptr post = (my_post_ptr) cinfo->post;
  172585. JDIMENSION num_rows, max_rows;
  172586. /* Fill the buffer, but not more than what we can dump out in one go. */
  172587. /* Note we rely on the upsampler to detect bottom of image. */
  172588. max_rows = out_rows_avail - *out_row_ctr;
  172589. if (max_rows > post->strip_height)
  172590. max_rows = post->strip_height;
  172591. num_rows = 0;
  172592. (*cinfo->upsample->upsample) (cinfo,
  172593. input_buf, in_row_group_ctr, in_row_groups_avail,
  172594. post->buffer, &num_rows, max_rows);
  172595. /* Quantize and emit data. */
  172596. (*cinfo->cquantize->color_quantize) (cinfo,
  172597. post->buffer, output_buf + *out_row_ctr, (int) num_rows);
  172598. *out_row_ctr += num_rows;
  172599. }
  172600. #ifdef QUANT_2PASS_SUPPORTED
  172601. /*
  172602. * Process some data in the first pass of 2-pass quantization.
  172603. */
  172604. METHODDEF(void)
  172605. post_process_prepass (j_decompress_ptr cinfo,
  172606. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172607. JDIMENSION in_row_groups_avail,
  172608. JSAMPARRAY, JDIMENSION *out_row_ctr,
  172609. JDIMENSION)
  172610. {
  172611. my_post_ptr post = (my_post_ptr) cinfo->post;
  172612. JDIMENSION old_next_row, num_rows;
  172613. /* Reposition virtual buffer if at start of strip. */
  172614. if (post->next_row == 0) {
  172615. post->buffer = (*cinfo->mem->access_virt_sarray)
  172616. ((j_common_ptr) cinfo, post->whole_image,
  172617. post->starting_row, post->strip_height, TRUE);
  172618. }
  172619. /* Upsample some data (up to a strip height's worth). */
  172620. old_next_row = post->next_row;
  172621. (*cinfo->upsample->upsample) (cinfo,
  172622. input_buf, in_row_group_ctr, in_row_groups_avail,
  172623. post->buffer, &post->next_row, post->strip_height);
  172624. /* Allow quantizer to scan new data. No data is emitted, */
  172625. /* but we advance out_row_ctr so outer loop can tell when we're done. */
  172626. if (post->next_row > old_next_row) {
  172627. num_rows = post->next_row - old_next_row;
  172628. (*cinfo->cquantize->color_quantize) (cinfo, post->buffer + old_next_row,
  172629. (JSAMPARRAY) NULL, (int) num_rows);
  172630. *out_row_ctr += num_rows;
  172631. }
  172632. /* Advance if we filled the strip. */
  172633. if (post->next_row >= post->strip_height) {
  172634. post->starting_row += post->strip_height;
  172635. post->next_row = 0;
  172636. }
  172637. }
  172638. /*
  172639. * Process some data in the second pass of 2-pass quantization.
  172640. */
  172641. METHODDEF(void)
  172642. post_process_2pass (j_decompress_ptr cinfo,
  172643. JSAMPIMAGE, JDIMENSION *,
  172644. JDIMENSION,
  172645. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172646. JDIMENSION out_rows_avail)
  172647. {
  172648. my_post_ptr post = (my_post_ptr) cinfo->post;
  172649. JDIMENSION num_rows, max_rows;
  172650. /* Reposition virtual buffer if at start of strip. */
  172651. if (post->next_row == 0) {
  172652. post->buffer = (*cinfo->mem->access_virt_sarray)
  172653. ((j_common_ptr) cinfo, post->whole_image,
  172654. post->starting_row, post->strip_height, FALSE);
  172655. }
  172656. /* Determine number of rows to emit. */
  172657. num_rows = post->strip_height - post->next_row; /* available in strip */
  172658. max_rows = out_rows_avail - *out_row_ctr; /* available in output area */
  172659. if (num_rows > max_rows)
  172660. num_rows = max_rows;
  172661. /* We have to check bottom of image here, can't depend on upsampler. */
  172662. max_rows = cinfo->output_height - post->starting_row;
  172663. if (num_rows > max_rows)
  172664. num_rows = max_rows;
  172665. /* Quantize and emit data. */
  172666. (*cinfo->cquantize->color_quantize) (cinfo,
  172667. post->buffer + post->next_row, output_buf + *out_row_ctr,
  172668. (int) num_rows);
  172669. *out_row_ctr += num_rows;
  172670. /* Advance if we filled the strip. */
  172671. post->next_row += num_rows;
  172672. if (post->next_row >= post->strip_height) {
  172673. post->starting_row += post->strip_height;
  172674. post->next_row = 0;
  172675. }
  172676. }
  172677. #endif /* QUANT_2PASS_SUPPORTED */
  172678. /*
  172679. * Initialize postprocessing controller.
  172680. */
  172681. GLOBAL(void)
  172682. jinit_d_post_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  172683. {
  172684. my_post_ptr post;
  172685. post = (my_post_ptr)
  172686. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172687. SIZEOF(my_post_controller));
  172688. cinfo->post = (struct jpeg_d_post_controller *) post;
  172689. post->pub.start_pass = start_pass_dpost;
  172690. post->whole_image = NULL; /* flag for no virtual arrays */
  172691. post->buffer = NULL; /* flag for no strip buffer */
  172692. /* Create the quantization buffer, if needed */
  172693. if (cinfo->quantize_colors) {
  172694. /* The buffer strip height is max_v_samp_factor, which is typically
  172695. * an efficient number of rows for upsampling to return.
  172696. * (In the presence of output rescaling, we might want to be smarter?)
  172697. */
  172698. post->strip_height = (JDIMENSION) cinfo->max_v_samp_factor;
  172699. if (need_full_buffer) {
  172700. /* Two-pass color quantization: need full-image storage. */
  172701. /* We round up the number of rows to a multiple of the strip height. */
  172702. #ifdef QUANT_2PASS_SUPPORTED
  172703. post->whole_image = (*cinfo->mem->request_virt_sarray)
  172704. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  172705. cinfo->output_width * cinfo->out_color_components,
  172706. (JDIMENSION) jround_up((long) cinfo->output_height,
  172707. (long) post->strip_height),
  172708. post->strip_height);
  172709. #else
  172710. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  172711. #endif /* QUANT_2PASS_SUPPORTED */
  172712. } else {
  172713. /* One-pass color quantization: just make a strip buffer. */
  172714. post->buffer = (*cinfo->mem->alloc_sarray)
  172715. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172716. cinfo->output_width * cinfo->out_color_components,
  172717. post->strip_height);
  172718. }
  172719. }
  172720. }
  172721. /*** End of inlined file: jdpostct.c ***/
  172722. #undef FIX
  172723. /*** Start of inlined file: jdsample.c ***/
  172724. #define JPEG_INTERNALS
  172725. /* Pointer to routine to upsample a single component */
  172726. typedef JMETHOD(void, upsample1_ptr,
  172727. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  172728. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr));
  172729. /* Private subobject */
  172730. typedef struct {
  172731. struct jpeg_upsampler pub; /* public fields */
  172732. /* Color conversion buffer. When using separate upsampling and color
  172733. * conversion steps, this buffer holds one upsampled row group until it
  172734. * has been color converted and output.
  172735. * Note: we do not allocate any storage for component(s) which are full-size,
  172736. * ie do not need rescaling. The corresponding entry of color_buf[] is
  172737. * simply set to point to the input data array, thereby avoiding copying.
  172738. */
  172739. JSAMPARRAY color_buf[MAX_COMPONENTS];
  172740. /* Per-component upsampling method pointers */
  172741. upsample1_ptr methods[MAX_COMPONENTS];
  172742. int next_row_out; /* counts rows emitted from color_buf */
  172743. JDIMENSION rows_to_go; /* counts rows remaining in image */
  172744. /* Height of an input row group for each component. */
  172745. int rowgroup_height[MAX_COMPONENTS];
  172746. /* These arrays save pixel expansion factors so that int_expand need not
  172747. * recompute them each time. They are unused for other upsampling methods.
  172748. */
  172749. UINT8 h_expand[MAX_COMPONENTS];
  172750. UINT8 v_expand[MAX_COMPONENTS];
  172751. } my_upsampler2;
  172752. typedef my_upsampler2 * my_upsample_ptr2;
  172753. /*
  172754. * Initialize for an upsampling pass.
  172755. */
  172756. METHODDEF(void)
  172757. start_pass_upsample (j_decompress_ptr cinfo)
  172758. {
  172759. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  172760. /* Mark the conversion buffer empty */
  172761. upsample->next_row_out = cinfo->max_v_samp_factor;
  172762. /* Initialize total-height counter for detecting bottom of image */
  172763. upsample->rows_to_go = cinfo->output_height;
  172764. }
  172765. /*
  172766. * Control routine to do upsampling (and color conversion).
  172767. *
  172768. * In this version we upsample each component independently.
  172769. * We upsample one row group into the conversion buffer, then apply
  172770. * color conversion a row at a time.
  172771. */
  172772. METHODDEF(void)
  172773. sep_upsample (j_decompress_ptr cinfo,
  172774. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172775. JDIMENSION,
  172776. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172777. JDIMENSION out_rows_avail)
  172778. {
  172779. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  172780. int ci;
  172781. jpeg_component_info * compptr;
  172782. JDIMENSION num_rows;
  172783. /* Fill the conversion buffer, if it's empty */
  172784. if (upsample->next_row_out >= cinfo->max_v_samp_factor) {
  172785. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  172786. ci++, compptr++) {
  172787. /* Invoke per-component upsample method. Notice we pass a POINTER
  172788. * to color_buf[ci], so that fullsize_upsample can change it.
  172789. */
  172790. (*upsample->methods[ci]) (cinfo, compptr,
  172791. input_buf[ci] + (*in_row_group_ctr * upsample->rowgroup_height[ci]),
  172792. upsample->color_buf + ci);
  172793. }
  172794. upsample->next_row_out = 0;
  172795. }
  172796. /* Color-convert and emit rows */
  172797. /* How many we have in the buffer: */
  172798. num_rows = (JDIMENSION) (cinfo->max_v_samp_factor - upsample->next_row_out);
  172799. /* Not more than the distance to the end of the image. Need this test
  172800. * in case the image height is not a multiple of max_v_samp_factor:
  172801. */
  172802. if (num_rows > upsample->rows_to_go)
  172803. num_rows = upsample->rows_to_go;
  172804. /* And not more than what the client can accept: */
  172805. out_rows_avail -= *out_row_ctr;
  172806. if (num_rows > out_rows_avail)
  172807. num_rows = out_rows_avail;
  172808. (*cinfo->cconvert->color_convert) (cinfo, upsample->color_buf,
  172809. (JDIMENSION) upsample->next_row_out,
  172810. output_buf + *out_row_ctr,
  172811. (int) num_rows);
  172812. /* Adjust counts */
  172813. *out_row_ctr += num_rows;
  172814. upsample->rows_to_go -= num_rows;
  172815. upsample->next_row_out += num_rows;
  172816. /* When the buffer is emptied, declare this input row group consumed */
  172817. if (upsample->next_row_out >= cinfo->max_v_samp_factor)
  172818. (*in_row_group_ctr)++;
  172819. }
  172820. /*
  172821. * These are the routines invoked by sep_upsample to upsample pixel values
  172822. * of a single component. One row group is processed per call.
  172823. */
  172824. /*
  172825. * For full-size components, we just make color_buf[ci] point at the
  172826. * input buffer, and thus avoid copying any data. Note that this is
  172827. * safe only because sep_upsample doesn't declare the input row group
  172828. * "consumed" until we are done color converting and emitting it.
  172829. */
  172830. METHODDEF(void)
  172831. fullsize_upsample (j_decompress_ptr, jpeg_component_info *,
  172832. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  172833. {
  172834. *output_data_ptr = input_data;
  172835. }
  172836. /*
  172837. * This is a no-op version used for "uninteresting" components.
  172838. * These components will not be referenced by color conversion.
  172839. */
  172840. METHODDEF(void)
  172841. noop_upsample (j_decompress_ptr, jpeg_component_info *,
  172842. JSAMPARRAY, JSAMPARRAY * output_data_ptr)
  172843. {
  172844. *output_data_ptr = NULL; /* safety check */
  172845. }
  172846. /*
  172847. * This version handles any integral sampling ratios.
  172848. * This is not used for typical JPEG files, so it need not be fast.
  172849. * Nor, for that matter, is it particularly accurate: the algorithm is
  172850. * simple replication of the input pixel onto the corresponding output
  172851. * pixels. The hi-falutin sampling literature refers to this as a
  172852. * "box filter". A box filter tends to introduce visible artifacts,
  172853. * so if you are actually going to use 3:1 or 4:1 sampling ratios
  172854. * you would be well advised to improve this code.
  172855. */
  172856. METHODDEF(void)
  172857. int_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  172858. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  172859. {
  172860. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  172861. JSAMPARRAY output_data = *output_data_ptr;
  172862. register JSAMPROW inptr, outptr;
  172863. register JSAMPLE invalue;
  172864. register int h;
  172865. JSAMPROW outend;
  172866. int h_expand, v_expand;
  172867. int inrow, outrow;
  172868. h_expand = upsample->h_expand[compptr->component_index];
  172869. v_expand = upsample->v_expand[compptr->component_index];
  172870. inrow = outrow = 0;
  172871. while (outrow < cinfo->max_v_samp_factor) {
  172872. /* Generate one output row with proper horizontal expansion */
  172873. inptr = input_data[inrow];
  172874. outptr = output_data[outrow];
  172875. outend = outptr + cinfo->output_width;
  172876. while (outptr < outend) {
  172877. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  172878. for (h = h_expand; h > 0; h--) {
  172879. *outptr++ = invalue;
  172880. }
  172881. }
  172882. /* Generate any additional output rows by duplicating the first one */
  172883. if (v_expand > 1) {
  172884. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  172885. v_expand-1, cinfo->output_width);
  172886. }
  172887. inrow++;
  172888. outrow += v_expand;
  172889. }
  172890. }
  172891. /*
  172892. * Fast processing for the common case of 2:1 horizontal and 1:1 vertical.
  172893. * It's still a box filter.
  172894. */
  172895. METHODDEF(void)
  172896. h2v1_upsample (j_decompress_ptr cinfo, jpeg_component_info *,
  172897. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  172898. {
  172899. JSAMPARRAY output_data = *output_data_ptr;
  172900. register JSAMPROW inptr, outptr;
  172901. register JSAMPLE invalue;
  172902. JSAMPROW outend;
  172903. int inrow;
  172904. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  172905. inptr = input_data[inrow];
  172906. outptr = output_data[inrow];
  172907. outend = outptr + cinfo->output_width;
  172908. while (outptr < outend) {
  172909. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  172910. *outptr++ = invalue;
  172911. *outptr++ = invalue;
  172912. }
  172913. }
  172914. }
  172915. /*
  172916. * Fast processing for the common case of 2:1 horizontal and 2:1 vertical.
  172917. * It's still a box filter.
  172918. */
  172919. METHODDEF(void)
  172920. h2v2_upsample (j_decompress_ptr cinfo, jpeg_component_info *,
  172921. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  172922. {
  172923. JSAMPARRAY output_data = *output_data_ptr;
  172924. register JSAMPROW inptr, outptr;
  172925. register JSAMPLE invalue;
  172926. JSAMPROW outend;
  172927. int inrow, outrow;
  172928. inrow = outrow = 0;
  172929. while (outrow < cinfo->max_v_samp_factor) {
  172930. inptr = input_data[inrow];
  172931. outptr = output_data[outrow];
  172932. outend = outptr + cinfo->output_width;
  172933. while (outptr < outend) {
  172934. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  172935. *outptr++ = invalue;
  172936. *outptr++ = invalue;
  172937. }
  172938. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  172939. 1, cinfo->output_width);
  172940. inrow++;
  172941. outrow += 2;
  172942. }
  172943. }
  172944. /*
  172945. * Fancy processing for the common case of 2:1 horizontal and 1:1 vertical.
  172946. *
  172947. * The upsampling algorithm is linear interpolation between pixel centers,
  172948. * also known as a "triangle filter". This is a good compromise between
  172949. * speed and visual quality. The centers of the output pixels are 1/4 and 3/4
  172950. * of the way between input pixel centers.
  172951. *
  172952. * A note about the "bias" calculations: when rounding fractional values to
  172953. * integer, we do not want to always round 0.5 up to the next integer.
  172954. * If we did that, we'd introduce a noticeable bias towards larger values.
  172955. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  172956. * alternate pixel locations (a simple ordered dither pattern).
  172957. */
  172958. METHODDEF(void)
  172959. h2v1_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  172960. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  172961. {
  172962. JSAMPARRAY output_data = *output_data_ptr;
  172963. register JSAMPROW inptr, outptr;
  172964. register int invalue;
  172965. register JDIMENSION colctr;
  172966. int inrow;
  172967. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  172968. inptr = input_data[inrow];
  172969. outptr = output_data[inrow];
  172970. /* Special case for first column */
  172971. invalue = GETJSAMPLE(*inptr++);
  172972. *outptr++ = (JSAMPLE) invalue;
  172973. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(*inptr) + 2) >> 2);
  172974. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  172975. /* General case: 3/4 * nearer pixel + 1/4 * further pixel */
  172976. invalue = GETJSAMPLE(*inptr++) * 3;
  172977. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(inptr[-2]) + 1) >> 2);
  172978. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(*inptr) + 2) >> 2);
  172979. }
  172980. /* Special case for last column */
  172981. invalue = GETJSAMPLE(*inptr);
  172982. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(inptr[-1]) + 1) >> 2);
  172983. *outptr++ = (JSAMPLE) invalue;
  172984. }
  172985. }
  172986. /*
  172987. * Fancy processing for the common case of 2:1 horizontal and 2:1 vertical.
  172988. * Again a triangle filter; see comments for h2v1 case, above.
  172989. *
  172990. * It is OK for us to reference the adjacent input rows because we demanded
  172991. * context from the main buffer controller (see initialization code).
  172992. */
  172993. METHODDEF(void)
  172994. h2v2_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  172995. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  172996. {
  172997. JSAMPARRAY output_data = *output_data_ptr;
  172998. register JSAMPROW inptr0, inptr1, outptr;
  172999. #if BITS_IN_JSAMPLE == 8
  173000. register int thiscolsum, lastcolsum, nextcolsum;
  173001. #else
  173002. register INT32 thiscolsum, lastcolsum, nextcolsum;
  173003. #endif
  173004. register JDIMENSION colctr;
  173005. int inrow, outrow, v;
  173006. inrow = outrow = 0;
  173007. while (outrow < cinfo->max_v_samp_factor) {
  173008. for (v = 0; v < 2; v++) {
  173009. /* inptr0 points to nearest input row, inptr1 points to next nearest */
  173010. inptr0 = input_data[inrow];
  173011. if (v == 0) /* next nearest is row above */
  173012. inptr1 = input_data[inrow-1];
  173013. else /* next nearest is row below */
  173014. inptr1 = input_data[inrow+1];
  173015. outptr = output_data[outrow++];
  173016. /* Special case for first column */
  173017. thiscolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  173018. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  173019. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 8) >> 4);
  173020. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  173021. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  173022. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  173023. /* General case: 3/4 * nearer pixel + 1/4 * further pixel in each */
  173024. /* dimension, thus 9/16, 3/16, 3/16, 1/16 overall */
  173025. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  173026. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  173027. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  173028. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  173029. }
  173030. /* Special case for last column */
  173031. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  173032. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 7) >> 4);
  173033. }
  173034. inrow++;
  173035. }
  173036. }
  173037. /*
  173038. * Module initialization routine for upsampling.
  173039. */
  173040. GLOBAL(void)
  173041. jinit_upsampler (j_decompress_ptr cinfo)
  173042. {
  173043. my_upsample_ptr2 upsample;
  173044. int ci;
  173045. jpeg_component_info * compptr;
  173046. boolean need_buffer, do_fancy;
  173047. int h_in_group, v_in_group, h_out_group, v_out_group;
  173048. upsample = (my_upsample_ptr2)
  173049. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173050. SIZEOF(my_upsampler2));
  173051. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  173052. upsample->pub.start_pass = start_pass_upsample;
  173053. upsample->pub.upsample = sep_upsample;
  173054. upsample->pub.need_context_rows = FALSE; /* until we find out differently */
  173055. if (cinfo->CCIR601_sampling) /* this isn't supported */
  173056. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  173057. /* jdmainct.c doesn't support context rows when min_DCT_scaled_size = 1,
  173058. * so don't ask for it.
  173059. */
  173060. do_fancy = cinfo->do_fancy_upsampling && cinfo->min_DCT_scaled_size > 1;
  173061. /* Verify we can handle the sampling factors, select per-component methods,
  173062. * and create storage as needed.
  173063. */
  173064. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  173065. ci++, compptr++) {
  173066. /* Compute size of an "input group" after IDCT scaling. This many samples
  173067. * are to be converted to max_h_samp_factor * max_v_samp_factor pixels.
  173068. */
  173069. h_in_group = (compptr->h_samp_factor * compptr->DCT_scaled_size) /
  173070. cinfo->min_DCT_scaled_size;
  173071. v_in_group = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  173072. cinfo->min_DCT_scaled_size;
  173073. h_out_group = cinfo->max_h_samp_factor;
  173074. v_out_group = cinfo->max_v_samp_factor;
  173075. upsample->rowgroup_height[ci] = v_in_group; /* save for use later */
  173076. need_buffer = TRUE;
  173077. if (! compptr->component_needed) {
  173078. /* Don't bother to upsample an uninteresting component. */
  173079. upsample->methods[ci] = noop_upsample;
  173080. need_buffer = FALSE;
  173081. } else if (h_in_group == h_out_group && v_in_group == v_out_group) {
  173082. /* Fullsize components can be processed without any work. */
  173083. upsample->methods[ci] = fullsize_upsample;
  173084. need_buffer = FALSE;
  173085. } else if (h_in_group * 2 == h_out_group &&
  173086. v_in_group == v_out_group) {
  173087. /* Special cases for 2h1v upsampling */
  173088. if (do_fancy && compptr->downsampled_width > 2)
  173089. upsample->methods[ci] = h2v1_fancy_upsample;
  173090. else
  173091. upsample->methods[ci] = h2v1_upsample;
  173092. } else if (h_in_group * 2 == h_out_group &&
  173093. v_in_group * 2 == v_out_group) {
  173094. /* Special cases for 2h2v upsampling */
  173095. if (do_fancy && compptr->downsampled_width > 2) {
  173096. upsample->methods[ci] = h2v2_fancy_upsample;
  173097. upsample->pub.need_context_rows = TRUE;
  173098. } else
  173099. upsample->methods[ci] = h2v2_upsample;
  173100. } else if ((h_out_group % h_in_group) == 0 &&
  173101. (v_out_group % v_in_group) == 0) {
  173102. /* Generic integral-factors upsampling method */
  173103. upsample->methods[ci] = int_upsample;
  173104. upsample->h_expand[ci] = (UINT8) (h_out_group / h_in_group);
  173105. upsample->v_expand[ci] = (UINT8) (v_out_group / v_in_group);
  173106. } else
  173107. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  173108. if (need_buffer) {
  173109. upsample->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  173110. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173111. (JDIMENSION) jround_up((long) cinfo->output_width,
  173112. (long) cinfo->max_h_samp_factor),
  173113. (JDIMENSION) cinfo->max_v_samp_factor);
  173114. }
  173115. }
  173116. }
  173117. /*** End of inlined file: jdsample.c ***/
  173118. /*** Start of inlined file: jdtrans.c ***/
  173119. #define JPEG_INTERNALS
  173120. /* Forward declarations */
  173121. LOCAL(void) transdecode_master_selection JPP((j_decompress_ptr cinfo));
  173122. /*
  173123. * Read the coefficient arrays from a JPEG file.
  173124. * jpeg_read_header must be completed before calling this.
  173125. *
  173126. * The entire image is read into a set of virtual coefficient-block arrays,
  173127. * one per component. The return value is a pointer to the array of
  173128. * virtual-array descriptors. These can be manipulated directly via the
  173129. * JPEG memory manager, or handed off to jpeg_write_coefficients().
  173130. * To release the memory occupied by the virtual arrays, call
  173131. * jpeg_finish_decompress() when done with the data.
  173132. *
  173133. * An alternative usage is to simply obtain access to the coefficient arrays
  173134. * during a buffered-image-mode decompression operation. This is allowed
  173135. * after any jpeg_finish_output() call. The arrays can be accessed until
  173136. * jpeg_finish_decompress() is called. (Note that any call to the library
  173137. * may reposition the arrays, so don't rely on access_virt_barray() results
  173138. * to stay valid across library calls.)
  173139. *
  173140. * Returns NULL if suspended. This case need be checked only if
  173141. * a suspending data source is used.
  173142. */
  173143. GLOBAL(jvirt_barray_ptr *)
  173144. jpeg_read_coefficients (j_decompress_ptr cinfo)
  173145. {
  173146. if (cinfo->global_state == DSTATE_READY) {
  173147. /* First call: initialize active modules */
  173148. transdecode_master_selection(cinfo);
  173149. cinfo->global_state = DSTATE_RDCOEFS;
  173150. }
  173151. if (cinfo->global_state == DSTATE_RDCOEFS) {
  173152. /* Absorb whole file into the coef buffer */
  173153. for (;;) {
  173154. int retcode;
  173155. /* Call progress monitor hook if present */
  173156. if (cinfo->progress != NULL)
  173157. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  173158. /* Absorb some more input */
  173159. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  173160. if (retcode == JPEG_SUSPENDED)
  173161. return NULL;
  173162. if (retcode == JPEG_REACHED_EOI)
  173163. break;
  173164. /* Advance progress counter if appropriate */
  173165. if (cinfo->progress != NULL &&
  173166. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  173167. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  173168. /* startup underestimated number of scans; ratchet up one scan */
  173169. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  173170. }
  173171. }
  173172. }
  173173. /* Set state so that jpeg_finish_decompress does the right thing */
  173174. cinfo->global_state = DSTATE_STOPPING;
  173175. }
  173176. /* At this point we should be in state DSTATE_STOPPING if being used
  173177. * standalone, or in state DSTATE_BUFIMAGE if being invoked to get access
  173178. * to the coefficients during a full buffered-image-mode decompression.
  173179. */
  173180. if ((cinfo->global_state == DSTATE_STOPPING ||
  173181. cinfo->global_state == DSTATE_BUFIMAGE) && cinfo->buffered_image) {
  173182. return cinfo->coef->coef_arrays;
  173183. }
  173184. /* Oops, improper usage */
  173185. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  173186. return NULL; /* keep compiler happy */
  173187. }
  173188. /*
  173189. * Master selection of decompression modules for transcoding.
  173190. * This substitutes for jdmaster.c's initialization of the full decompressor.
  173191. */
  173192. LOCAL(void)
  173193. transdecode_master_selection (j_decompress_ptr cinfo)
  173194. {
  173195. /* This is effectively a buffered-image operation. */
  173196. cinfo->buffered_image = TRUE;
  173197. /* Entropy decoding: either Huffman or arithmetic coding. */
  173198. if (cinfo->arith_code) {
  173199. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  173200. } else {
  173201. if (cinfo->progressive_mode) {
  173202. #ifdef D_PROGRESSIVE_SUPPORTED
  173203. jinit_phuff_decoder(cinfo);
  173204. #else
  173205. ERREXIT(cinfo, JERR_NOT_COMPILED);
  173206. #endif
  173207. } else
  173208. jinit_huff_decoder(cinfo);
  173209. }
  173210. /* Always get a full-image coefficient buffer. */
  173211. jinit_d_coef_controller(cinfo, TRUE);
  173212. /* We can now tell the memory manager to allocate virtual arrays. */
  173213. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  173214. /* Initialize input side of decompressor to consume first scan. */
  173215. (*cinfo->inputctl->start_input_pass) (cinfo);
  173216. /* Initialize progress monitoring. */
  173217. if (cinfo->progress != NULL) {
  173218. int nscans;
  173219. /* Estimate number of scans to set pass_limit. */
  173220. if (cinfo->progressive_mode) {
  173221. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  173222. nscans = 2 + 3 * cinfo->num_components;
  173223. } else if (cinfo->inputctl->has_multiple_scans) {
  173224. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  173225. nscans = cinfo->num_components;
  173226. } else {
  173227. nscans = 1;
  173228. }
  173229. cinfo->progress->pass_counter = 0L;
  173230. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  173231. cinfo->progress->completed_passes = 0;
  173232. cinfo->progress->total_passes = 1;
  173233. }
  173234. }
  173235. /*** End of inlined file: jdtrans.c ***/
  173236. /*** Start of inlined file: jfdctflt.c ***/
  173237. #define JPEG_INTERNALS
  173238. #ifdef DCT_FLOAT_SUPPORTED
  173239. /*
  173240. * This module is specialized to the case DCTSIZE = 8.
  173241. */
  173242. #if DCTSIZE != 8
  173243. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  173244. #endif
  173245. /*
  173246. * Perform the forward DCT on one block of samples.
  173247. */
  173248. GLOBAL(void)
  173249. jpeg_fdct_float (FAST_FLOAT * data)
  173250. {
  173251. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  173252. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  173253. FAST_FLOAT z1, z2, z3, z4, z5, z11, z13;
  173254. FAST_FLOAT *dataptr;
  173255. int ctr;
  173256. /* Pass 1: process rows. */
  173257. dataptr = data;
  173258. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  173259. tmp0 = dataptr[0] + dataptr[7];
  173260. tmp7 = dataptr[0] - dataptr[7];
  173261. tmp1 = dataptr[1] + dataptr[6];
  173262. tmp6 = dataptr[1] - dataptr[6];
  173263. tmp2 = dataptr[2] + dataptr[5];
  173264. tmp5 = dataptr[2] - dataptr[5];
  173265. tmp3 = dataptr[3] + dataptr[4];
  173266. tmp4 = dataptr[3] - dataptr[4];
  173267. /* Even part */
  173268. tmp10 = tmp0 + tmp3; /* phase 2 */
  173269. tmp13 = tmp0 - tmp3;
  173270. tmp11 = tmp1 + tmp2;
  173271. tmp12 = tmp1 - tmp2;
  173272. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  173273. dataptr[4] = tmp10 - tmp11;
  173274. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  173275. dataptr[2] = tmp13 + z1; /* phase 5 */
  173276. dataptr[6] = tmp13 - z1;
  173277. /* Odd part */
  173278. tmp10 = tmp4 + tmp5; /* phase 2 */
  173279. tmp11 = tmp5 + tmp6;
  173280. tmp12 = tmp6 + tmp7;
  173281. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  173282. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  173283. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  173284. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  173285. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  173286. z11 = tmp7 + z3; /* phase 5 */
  173287. z13 = tmp7 - z3;
  173288. dataptr[5] = z13 + z2; /* phase 6 */
  173289. dataptr[3] = z13 - z2;
  173290. dataptr[1] = z11 + z4;
  173291. dataptr[7] = z11 - z4;
  173292. dataptr += DCTSIZE; /* advance pointer to next row */
  173293. }
  173294. /* Pass 2: process columns. */
  173295. dataptr = data;
  173296. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  173297. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  173298. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  173299. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  173300. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  173301. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  173302. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  173303. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  173304. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  173305. /* Even part */
  173306. tmp10 = tmp0 + tmp3; /* phase 2 */
  173307. tmp13 = tmp0 - tmp3;
  173308. tmp11 = tmp1 + tmp2;
  173309. tmp12 = tmp1 - tmp2;
  173310. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  173311. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  173312. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  173313. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  173314. dataptr[DCTSIZE*6] = tmp13 - z1;
  173315. /* Odd part */
  173316. tmp10 = tmp4 + tmp5; /* phase 2 */
  173317. tmp11 = tmp5 + tmp6;
  173318. tmp12 = tmp6 + tmp7;
  173319. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  173320. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  173321. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  173322. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  173323. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  173324. z11 = tmp7 + z3; /* phase 5 */
  173325. z13 = tmp7 - z3;
  173326. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  173327. dataptr[DCTSIZE*3] = z13 - z2;
  173328. dataptr[DCTSIZE*1] = z11 + z4;
  173329. dataptr[DCTSIZE*7] = z11 - z4;
  173330. dataptr++; /* advance pointer to next column */
  173331. }
  173332. }
  173333. #endif /* DCT_FLOAT_SUPPORTED */
  173334. /*** End of inlined file: jfdctflt.c ***/
  173335. /*** Start of inlined file: jfdctint.c ***/
  173336. #define JPEG_INTERNALS
  173337. #ifdef DCT_ISLOW_SUPPORTED
  173338. /*
  173339. * This module is specialized to the case DCTSIZE = 8.
  173340. */
  173341. #if DCTSIZE != 8
  173342. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  173343. #endif
  173344. /*
  173345. * The poop on this scaling stuff is as follows:
  173346. *
  173347. * Each 1-D DCT step produces outputs which are a factor of sqrt(N)
  173348. * larger than the true DCT outputs. The final outputs are therefore
  173349. * a factor of N larger than desired; since N=8 this can be cured by
  173350. * a simple right shift at the end of the algorithm. The advantage of
  173351. * this arrangement is that we save two multiplications per 1-D DCT,
  173352. * because the y0 and y4 outputs need not be divided by sqrt(N).
  173353. * In the IJG code, this factor of 8 is removed by the quantization step
  173354. * (in jcdctmgr.c), NOT in this module.
  173355. *
  173356. * We have to do addition and subtraction of the integer inputs, which
  173357. * is no problem, and multiplication by fractional constants, which is
  173358. * a problem to do in integer arithmetic. We multiply all the constants
  173359. * by CONST_SCALE and convert them to integer constants (thus retaining
  173360. * CONST_BITS bits of precision in the constants). After doing a
  173361. * multiplication we have to divide the product by CONST_SCALE, with proper
  173362. * rounding, to produce the correct output. This division can be done
  173363. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  173364. * as long as possible so that partial sums can be added together with
  173365. * full fractional precision.
  173366. *
  173367. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  173368. * they are represented to better-than-integral precision. These outputs
  173369. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  173370. * with the recommended scaling. (For 12-bit sample data, the intermediate
  173371. * array is INT32 anyway.)
  173372. *
  173373. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  173374. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  173375. * shows that the values given below are the most effective.
  173376. */
  173377. #if BITS_IN_JSAMPLE == 8
  173378. #define CONST_BITS 13
  173379. #define PASS1_BITS 2
  173380. #else
  173381. #define CONST_BITS 13
  173382. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  173383. #endif
  173384. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  173385. * causing a lot of useless floating-point operations at run time.
  173386. * To get around this we use the following pre-calculated constants.
  173387. * If you change CONST_BITS you may want to add appropriate values.
  173388. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  173389. */
  173390. #if CONST_BITS == 13
  173391. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  173392. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  173393. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  173394. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  173395. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  173396. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  173397. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  173398. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  173399. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  173400. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  173401. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  173402. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  173403. #else
  173404. #define FIX_0_298631336 FIX(0.298631336)
  173405. #define FIX_0_390180644 FIX(0.390180644)
  173406. #define FIX_0_541196100 FIX(0.541196100)
  173407. #define FIX_0_765366865 FIX(0.765366865)
  173408. #define FIX_0_899976223 FIX(0.899976223)
  173409. #define FIX_1_175875602 FIX(1.175875602)
  173410. #define FIX_1_501321110 FIX(1.501321110)
  173411. #define FIX_1_847759065 FIX(1.847759065)
  173412. #define FIX_1_961570560 FIX(1.961570560)
  173413. #define FIX_2_053119869 FIX(2.053119869)
  173414. #define FIX_2_562915447 FIX(2.562915447)
  173415. #define FIX_3_072711026 FIX(3.072711026)
  173416. #endif
  173417. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  173418. * For 8-bit samples with the recommended scaling, all the variable
  173419. * and constant values involved are no more than 16 bits wide, so a
  173420. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  173421. * For 12-bit samples, a full 32-bit multiplication will be needed.
  173422. */
  173423. #if BITS_IN_JSAMPLE == 8
  173424. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  173425. #else
  173426. #define MULTIPLY(var,const) ((var) * (const))
  173427. #endif
  173428. /*
  173429. * Perform the forward DCT on one block of samples.
  173430. */
  173431. GLOBAL(void)
  173432. jpeg_fdct_islow (DCTELEM * data)
  173433. {
  173434. INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  173435. INT32 tmp10, tmp11, tmp12, tmp13;
  173436. INT32 z1, z2, z3, z4, z5;
  173437. DCTELEM *dataptr;
  173438. int ctr;
  173439. SHIFT_TEMPS
  173440. /* Pass 1: process rows. */
  173441. /* Note results are scaled up by sqrt(8) compared to a true DCT; */
  173442. /* furthermore, we scale the results by 2**PASS1_BITS. */
  173443. dataptr = data;
  173444. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  173445. tmp0 = dataptr[0] + dataptr[7];
  173446. tmp7 = dataptr[0] - dataptr[7];
  173447. tmp1 = dataptr[1] + dataptr[6];
  173448. tmp6 = dataptr[1] - dataptr[6];
  173449. tmp2 = dataptr[2] + dataptr[5];
  173450. tmp5 = dataptr[2] - dataptr[5];
  173451. tmp3 = dataptr[3] + dataptr[4];
  173452. tmp4 = dataptr[3] - dataptr[4];
  173453. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  173454. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  173455. */
  173456. tmp10 = tmp0 + tmp3;
  173457. tmp13 = tmp0 - tmp3;
  173458. tmp11 = tmp1 + tmp2;
  173459. tmp12 = tmp1 - tmp2;
  173460. dataptr[0] = (DCTELEM) ((tmp10 + tmp11) << PASS1_BITS);
  173461. dataptr[4] = (DCTELEM) ((tmp10 - tmp11) << PASS1_BITS);
  173462. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  173463. dataptr[2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  173464. CONST_BITS-PASS1_BITS);
  173465. dataptr[6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  173466. CONST_BITS-PASS1_BITS);
  173467. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  173468. * cK represents cos(K*pi/16).
  173469. * i0..i3 in the paper are tmp4..tmp7 here.
  173470. */
  173471. z1 = tmp4 + tmp7;
  173472. z2 = tmp5 + tmp6;
  173473. z3 = tmp4 + tmp6;
  173474. z4 = tmp5 + tmp7;
  173475. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  173476. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  173477. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  173478. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  173479. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  173480. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  173481. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  173482. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  173483. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  173484. z3 += z5;
  173485. z4 += z5;
  173486. dataptr[7] = (DCTELEM) DESCALE(tmp4 + z1 + z3, CONST_BITS-PASS1_BITS);
  173487. dataptr[5] = (DCTELEM) DESCALE(tmp5 + z2 + z4, CONST_BITS-PASS1_BITS);
  173488. dataptr[3] = (DCTELEM) DESCALE(tmp6 + z2 + z3, CONST_BITS-PASS1_BITS);
  173489. dataptr[1] = (DCTELEM) DESCALE(tmp7 + z1 + z4, CONST_BITS-PASS1_BITS);
  173490. dataptr += DCTSIZE; /* advance pointer to next row */
  173491. }
  173492. /* Pass 2: process columns.
  173493. * We remove the PASS1_BITS scaling, but leave the results scaled up
  173494. * by an overall factor of 8.
  173495. */
  173496. dataptr = data;
  173497. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  173498. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  173499. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  173500. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  173501. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  173502. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  173503. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  173504. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  173505. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  173506. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  173507. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  173508. */
  173509. tmp10 = tmp0 + tmp3;
  173510. tmp13 = tmp0 - tmp3;
  173511. tmp11 = tmp1 + tmp2;
  173512. tmp12 = tmp1 - tmp2;
  173513. dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(tmp10 + tmp11, PASS1_BITS);
  173514. dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(tmp10 - tmp11, PASS1_BITS);
  173515. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  173516. dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  173517. CONST_BITS+PASS1_BITS);
  173518. dataptr[DCTSIZE*6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  173519. CONST_BITS+PASS1_BITS);
  173520. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  173521. * cK represents cos(K*pi/16).
  173522. * i0..i3 in the paper are tmp4..tmp7 here.
  173523. */
  173524. z1 = tmp4 + tmp7;
  173525. z2 = tmp5 + tmp6;
  173526. z3 = tmp4 + tmp6;
  173527. z4 = tmp5 + tmp7;
  173528. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  173529. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  173530. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  173531. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  173532. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  173533. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  173534. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  173535. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  173536. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  173537. z3 += z5;
  173538. z4 += z5;
  173539. dataptr[DCTSIZE*7] = (DCTELEM) DESCALE(tmp4 + z1 + z3,
  173540. CONST_BITS+PASS1_BITS);
  173541. dataptr[DCTSIZE*5] = (DCTELEM) DESCALE(tmp5 + z2 + z4,
  173542. CONST_BITS+PASS1_BITS);
  173543. dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(tmp6 + z2 + z3,
  173544. CONST_BITS+PASS1_BITS);
  173545. dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(tmp7 + z1 + z4,
  173546. CONST_BITS+PASS1_BITS);
  173547. dataptr++; /* advance pointer to next column */
  173548. }
  173549. }
  173550. #endif /* DCT_ISLOW_SUPPORTED */
  173551. /*** End of inlined file: jfdctint.c ***/
  173552. #undef CONST_BITS
  173553. #undef MULTIPLY
  173554. #undef FIX_0_541196100
  173555. /*** Start of inlined file: jfdctfst.c ***/
  173556. #define JPEG_INTERNALS
  173557. #ifdef DCT_IFAST_SUPPORTED
  173558. /*
  173559. * This module is specialized to the case DCTSIZE = 8.
  173560. */
  173561. #if DCTSIZE != 8
  173562. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  173563. #endif
  173564. /* Scaling decisions are generally the same as in the LL&M algorithm;
  173565. * see jfdctint.c for more details. However, we choose to descale
  173566. * (right shift) multiplication products as soon as they are formed,
  173567. * rather than carrying additional fractional bits into subsequent additions.
  173568. * This compromises accuracy slightly, but it lets us save a few shifts.
  173569. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  173570. * everywhere except in the multiplications proper; this saves a good deal
  173571. * of work on 16-bit-int machines.
  173572. *
  173573. * Again to save a few shifts, the intermediate results between pass 1 and
  173574. * pass 2 are not upscaled, but are represented only to integral precision.
  173575. *
  173576. * A final compromise is to represent the multiplicative constants to only
  173577. * 8 fractional bits, rather than 13. This saves some shifting work on some
  173578. * machines, and may also reduce the cost of multiplication (since there
  173579. * are fewer one-bits in the constants).
  173580. */
  173581. #define CONST_BITS 8
  173582. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  173583. * causing a lot of useless floating-point operations at run time.
  173584. * To get around this we use the following pre-calculated constants.
  173585. * If you change CONST_BITS you may want to add appropriate values.
  173586. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  173587. */
  173588. #if CONST_BITS == 8
  173589. #define FIX_0_382683433 ((INT32) 98) /* FIX(0.382683433) */
  173590. #define FIX_0_541196100 ((INT32) 139) /* FIX(0.541196100) */
  173591. #define FIX_0_707106781 ((INT32) 181) /* FIX(0.707106781) */
  173592. #define FIX_1_306562965 ((INT32) 334) /* FIX(1.306562965) */
  173593. #else
  173594. #define FIX_0_382683433 FIX(0.382683433)
  173595. #define FIX_0_541196100 FIX(0.541196100)
  173596. #define FIX_0_707106781 FIX(0.707106781)
  173597. #define FIX_1_306562965 FIX(1.306562965)
  173598. #endif
  173599. /* We can gain a little more speed, with a further compromise in accuracy,
  173600. * by omitting the addition in a descaling shift. This yields an incorrectly
  173601. * rounded result half the time...
  173602. */
  173603. #ifndef USE_ACCURATE_ROUNDING
  173604. #undef DESCALE
  173605. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  173606. #endif
  173607. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  173608. * descale to yield a DCTELEM result.
  173609. */
  173610. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  173611. /*
  173612. * Perform the forward DCT on one block of samples.
  173613. */
  173614. GLOBAL(void)
  173615. jpeg_fdct_ifast (DCTELEM * data)
  173616. {
  173617. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  173618. DCTELEM tmp10, tmp11, tmp12, tmp13;
  173619. DCTELEM z1, z2, z3, z4, z5, z11, z13;
  173620. DCTELEM *dataptr;
  173621. int ctr;
  173622. SHIFT_TEMPS
  173623. /* Pass 1: process rows. */
  173624. dataptr = data;
  173625. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  173626. tmp0 = dataptr[0] + dataptr[7];
  173627. tmp7 = dataptr[0] - dataptr[7];
  173628. tmp1 = dataptr[1] + dataptr[6];
  173629. tmp6 = dataptr[1] - dataptr[6];
  173630. tmp2 = dataptr[2] + dataptr[5];
  173631. tmp5 = dataptr[2] - dataptr[5];
  173632. tmp3 = dataptr[3] + dataptr[4];
  173633. tmp4 = dataptr[3] - dataptr[4];
  173634. /* Even part */
  173635. tmp10 = tmp0 + tmp3; /* phase 2 */
  173636. tmp13 = tmp0 - tmp3;
  173637. tmp11 = tmp1 + tmp2;
  173638. tmp12 = tmp1 - tmp2;
  173639. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  173640. dataptr[4] = tmp10 - tmp11;
  173641. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  173642. dataptr[2] = tmp13 + z1; /* phase 5 */
  173643. dataptr[6] = tmp13 - z1;
  173644. /* Odd part */
  173645. tmp10 = tmp4 + tmp5; /* phase 2 */
  173646. tmp11 = tmp5 + tmp6;
  173647. tmp12 = tmp6 + tmp7;
  173648. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  173649. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  173650. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  173651. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  173652. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  173653. z11 = tmp7 + z3; /* phase 5 */
  173654. z13 = tmp7 - z3;
  173655. dataptr[5] = z13 + z2; /* phase 6 */
  173656. dataptr[3] = z13 - z2;
  173657. dataptr[1] = z11 + z4;
  173658. dataptr[7] = z11 - z4;
  173659. dataptr += DCTSIZE; /* advance pointer to next row */
  173660. }
  173661. /* Pass 2: process columns. */
  173662. dataptr = data;
  173663. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  173664. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  173665. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  173666. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  173667. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  173668. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  173669. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  173670. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  173671. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  173672. /* Even part */
  173673. tmp10 = tmp0 + tmp3; /* phase 2 */
  173674. tmp13 = tmp0 - tmp3;
  173675. tmp11 = tmp1 + tmp2;
  173676. tmp12 = tmp1 - tmp2;
  173677. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  173678. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  173679. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  173680. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  173681. dataptr[DCTSIZE*6] = tmp13 - z1;
  173682. /* Odd part */
  173683. tmp10 = tmp4 + tmp5; /* phase 2 */
  173684. tmp11 = tmp5 + tmp6;
  173685. tmp12 = tmp6 + tmp7;
  173686. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  173687. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  173688. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  173689. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  173690. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  173691. z11 = tmp7 + z3; /* phase 5 */
  173692. z13 = tmp7 - z3;
  173693. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  173694. dataptr[DCTSIZE*3] = z13 - z2;
  173695. dataptr[DCTSIZE*1] = z11 + z4;
  173696. dataptr[DCTSIZE*7] = z11 - z4;
  173697. dataptr++; /* advance pointer to next column */
  173698. }
  173699. }
  173700. #endif /* DCT_IFAST_SUPPORTED */
  173701. /*** End of inlined file: jfdctfst.c ***/
  173702. #undef FIX_0_541196100
  173703. /*** Start of inlined file: jidctflt.c ***/
  173704. #define JPEG_INTERNALS
  173705. #ifdef DCT_FLOAT_SUPPORTED
  173706. /*
  173707. * This module is specialized to the case DCTSIZE = 8.
  173708. */
  173709. #if DCTSIZE != 8
  173710. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  173711. #endif
  173712. /* Dequantize a coefficient by multiplying it by the multiplier-table
  173713. * entry; produce a float result.
  173714. */
  173715. #define DEQUANTIZE(coef,quantval) (((FAST_FLOAT) (coef)) * (quantval))
  173716. /*
  173717. * Perform dequantization and inverse DCT on one block of coefficients.
  173718. */
  173719. GLOBAL(void)
  173720. jpeg_idct_float (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173721. JCOEFPTR coef_block,
  173722. JSAMPARRAY output_buf, JDIMENSION output_col)
  173723. {
  173724. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  173725. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  173726. FAST_FLOAT z5, z10, z11, z12, z13;
  173727. JCOEFPTR inptr;
  173728. FLOAT_MULT_TYPE * quantptr;
  173729. FAST_FLOAT * wsptr;
  173730. JSAMPROW outptr;
  173731. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  173732. int ctr;
  173733. FAST_FLOAT workspace[DCTSIZE2]; /* buffers data between passes */
  173734. SHIFT_TEMPS
  173735. /* Pass 1: process columns from input, store into work array. */
  173736. inptr = coef_block;
  173737. quantptr = (FLOAT_MULT_TYPE *) compptr->dct_table;
  173738. wsptr = workspace;
  173739. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  173740. /* Due to quantization, we will usually find that many of the input
  173741. * coefficients are zero, especially the AC terms. We can exploit this
  173742. * by short-circuiting the IDCT calculation for any column in which all
  173743. * the AC terms are zero. In that case each output is equal to the
  173744. * DC coefficient (with scale factor as needed).
  173745. * With typical images and quantization tables, half or more of the
  173746. * column DCT calculations can be simplified this way.
  173747. */
  173748. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  173749. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  173750. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  173751. inptr[DCTSIZE*7] == 0) {
  173752. /* AC terms all zero */
  173753. FAST_FLOAT dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  173754. wsptr[DCTSIZE*0] = dcval;
  173755. wsptr[DCTSIZE*1] = dcval;
  173756. wsptr[DCTSIZE*2] = dcval;
  173757. wsptr[DCTSIZE*3] = dcval;
  173758. wsptr[DCTSIZE*4] = dcval;
  173759. wsptr[DCTSIZE*5] = dcval;
  173760. wsptr[DCTSIZE*6] = dcval;
  173761. wsptr[DCTSIZE*7] = dcval;
  173762. inptr++; /* advance pointers to next column */
  173763. quantptr++;
  173764. wsptr++;
  173765. continue;
  173766. }
  173767. /* Even part */
  173768. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  173769. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  173770. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  173771. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  173772. tmp10 = tmp0 + tmp2; /* phase 3 */
  173773. tmp11 = tmp0 - tmp2;
  173774. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  173775. tmp12 = (tmp1 - tmp3) * ((FAST_FLOAT) 1.414213562) - tmp13; /* 2*c4 */
  173776. tmp0 = tmp10 + tmp13; /* phase 2 */
  173777. tmp3 = tmp10 - tmp13;
  173778. tmp1 = tmp11 + tmp12;
  173779. tmp2 = tmp11 - tmp12;
  173780. /* Odd part */
  173781. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  173782. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  173783. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  173784. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  173785. z13 = tmp6 + tmp5; /* phase 6 */
  173786. z10 = tmp6 - tmp5;
  173787. z11 = tmp4 + tmp7;
  173788. z12 = tmp4 - tmp7;
  173789. tmp7 = z11 + z13; /* phase 5 */
  173790. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562); /* 2*c4 */
  173791. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  173792. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  173793. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  173794. tmp6 = tmp12 - tmp7; /* phase 2 */
  173795. tmp5 = tmp11 - tmp6;
  173796. tmp4 = tmp10 + tmp5;
  173797. wsptr[DCTSIZE*0] = tmp0 + tmp7;
  173798. wsptr[DCTSIZE*7] = tmp0 - tmp7;
  173799. wsptr[DCTSIZE*1] = tmp1 + tmp6;
  173800. wsptr[DCTSIZE*6] = tmp1 - tmp6;
  173801. wsptr[DCTSIZE*2] = tmp2 + tmp5;
  173802. wsptr[DCTSIZE*5] = tmp2 - tmp5;
  173803. wsptr[DCTSIZE*4] = tmp3 + tmp4;
  173804. wsptr[DCTSIZE*3] = tmp3 - tmp4;
  173805. inptr++; /* advance pointers to next column */
  173806. quantptr++;
  173807. wsptr++;
  173808. }
  173809. /* Pass 2: process rows from work array, store into output array. */
  173810. /* Note that we must descale the results by a factor of 8 == 2**3. */
  173811. wsptr = workspace;
  173812. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  173813. outptr = output_buf[ctr] + output_col;
  173814. /* Rows of zeroes can be exploited in the same way as we did with columns.
  173815. * However, the column calculation has created many nonzero AC terms, so
  173816. * the simplification applies less often (typically 5% to 10% of the time).
  173817. * And testing floats for zero is relatively expensive, so we don't bother.
  173818. */
  173819. /* Even part */
  173820. tmp10 = wsptr[0] + wsptr[4];
  173821. tmp11 = wsptr[0] - wsptr[4];
  173822. tmp13 = wsptr[2] + wsptr[6];
  173823. tmp12 = (wsptr[2] - wsptr[6]) * ((FAST_FLOAT) 1.414213562) - tmp13;
  173824. tmp0 = tmp10 + tmp13;
  173825. tmp3 = tmp10 - tmp13;
  173826. tmp1 = tmp11 + tmp12;
  173827. tmp2 = tmp11 - tmp12;
  173828. /* Odd part */
  173829. z13 = wsptr[5] + wsptr[3];
  173830. z10 = wsptr[5] - wsptr[3];
  173831. z11 = wsptr[1] + wsptr[7];
  173832. z12 = wsptr[1] - wsptr[7];
  173833. tmp7 = z11 + z13;
  173834. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562);
  173835. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  173836. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  173837. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  173838. tmp6 = tmp12 - tmp7;
  173839. tmp5 = tmp11 - tmp6;
  173840. tmp4 = tmp10 + tmp5;
  173841. /* Final output stage: scale down by a factor of 8 and range-limit */
  173842. outptr[0] = range_limit[(int) DESCALE((INT32) (tmp0 + tmp7), 3)
  173843. & RANGE_MASK];
  173844. outptr[7] = range_limit[(int) DESCALE((INT32) (tmp0 - tmp7), 3)
  173845. & RANGE_MASK];
  173846. outptr[1] = range_limit[(int) DESCALE((INT32) (tmp1 + tmp6), 3)
  173847. & RANGE_MASK];
  173848. outptr[6] = range_limit[(int) DESCALE((INT32) (tmp1 - tmp6), 3)
  173849. & RANGE_MASK];
  173850. outptr[2] = range_limit[(int) DESCALE((INT32) (tmp2 + tmp5), 3)
  173851. & RANGE_MASK];
  173852. outptr[5] = range_limit[(int) DESCALE((INT32) (tmp2 - tmp5), 3)
  173853. & RANGE_MASK];
  173854. outptr[4] = range_limit[(int) DESCALE((INT32) (tmp3 + tmp4), 3)
  173855. & RANGE_MASK];
  173856. outptr[3] = range_limit[(int) DESCALE((INT32) (tmp3 - tmp4), 3)
  173857. & RANGE_MASK];
  173858. wsptr += DCTSIZE; /* advance pointer to next row */
  173859. }
  173860. }
  173861. #endif /* DCT_FLOAT_SUPPORTED */
  173862. /*** End of inlined file: jidctflt.c ***/
  173863. #undef CONST_BITS
  173864. #undef FIX_1_847759065
  173865. #undef MULTIPLY
  173866. #undef DEQUANTIZE
  173867. #undef DESCALE
  173868. /*** Start of inlined file: jidctfst.c ***/
  173869. #define JPEG_INTERNALS
  173870. #ifdef DCT_IFAST_SUPPORTED
  173871. /*
  173872. * This module is specialized to the case DCTSIZE = 8.
  173873. */
  173874. #if DCTSIZE != 8
  173875. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  173876. #endif
  173877. /* Scaling decisions are generally the same as in the LL&M algorithm;
  173878. * see jidctint.c for more details. However, we choose to descale
  173879. * (right shift) multiplication products as soon as they are formed,
  173880. * rather than carrying additional fractional bits into subsequent additions.
  173881. * This compromises accuracy slightly, but it lets us save a few shifts.
  173882. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  173883. * everywhere except in the multiplications proper; this saves a good deal
  173884. * of work on 16-bit-int machines.
  173885. *
  173886. * The dequantized coefficients are not integers because the AA&N scaling
  173887. * factors have been incorporated. We represent them scaled up by PASS1_BITS,
  173888. * so that the first and second IDCT rounds have the same input scaling.
  173889. * For 8-bit JSAMPLEs, we choose IFAST_SCALE_BITS = PASS1_BITS so as to
  173890. * avoid a descaling shift; this compromises accuracy rather drastically
  173891. * for small quantization table entries, but it saves a lot of shifts.
  173892. * For 12-bit JSAMPLEs, there's no hope of using 16x16 multiplies anyway,
  173893. * so we use a much larger scaling factor to preserve accuracy.
  173894. *
  173895. * A final compromise is to represent the multiplicative constants to only
  173896. * 8 fractional bits, rather than 13. This saves some shifting work on some
  173897. * machines, and may also reduce the cost of multiplication (since there
  173898. * are fewer one-bits in the constants).
  173899. */
  173900. #if BITS_IN_JSAMPLE == 8
  173901. #define CONST_BITS 8
  173902. #define PASS1_BITS 2
  173903. #else
  173904. #define CONST_BITS 8
  173905. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  173906. #endif
  173907. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  173908. * causing a lot of useless floating-point operations at run time.
  173909. * To get around this we use the following pre-calculated constants.
  173910. * If you change CONST_BITS you may want to add appropriate values.
  173911. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  173912. */
  173913. #if CONST_BITS == 8
  173914. #define FIX_1_082392200 ((INT32) 277) /* FIX(1.082392200) */
  173915. #define FIX_1_414213562 ((INT32) 362) /* FIX(1.414213562) */
  173916. #define FIX_1_847759065 ((INT32) 473) /* FIX(1.847759065) */
  173917. #define FIX_2_613125930 ((INT32) 669) /* FIX(2.613125930) */
  173918. #else
  173919. #define FIX_1_082392200 FIX(1.082392200)
  173920. #define FIX_1_414213562 FIX(1.414213562)
  173921. #define FIX_1_847759065 FIX(1.847759065)
  173922. #define FIX_2_613125930 FIX(2.613125930)
  173923. #endif
  173924. /* We can gain a little more speed, with a further compromise in accuracy,
  173925. * by omitting the addition in a descaling shift. This yields an incorrectly
  173926. * rounded result half the time...
  173927. */
  173928. #ifndef USE_ACCURATE_ROUNDING
  173929. #undef DESCALE
  173930. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  173931. #endif
  173932. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  173933. * descale to yield a DCTELEM result.
  173934. */
  173935. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  173936. /* Dequantize a coefficient by multiplying it by the multiplier-table
  173937. * entry; produce a DCTELEM result. For 8-bit data a 16x16->16
  173938. * multiplication will do. For 12-bit data, the multiplier table is
  173939. * declared INT32, so a 32-bit multiply will be used.
  173940. */
  173941. #if BITS_IN_JSAMPLE == 8
  173942. #define DEQUANTIZE(coef,quantval) (((IFAST_MULT_TYPE) (coef)) * (quantval))
  173943. #else
  173944. #define DEQUANTIZE(coef,quantval) \
  173945. DESCALE((coef)*(quantval), IFAST_SCALE_BITS-PASS1_BITS)
  173946. #endif
  173947. /* Like DESCALE, but applies to a DCTELEM and produces an int.
  173948. * We assume that int right shift is unsigned if INT32 right shift is.
  173949. */
  173950. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  173951. #define ISHIFT_TEMPS DCTELEM ishift_temp;
  173952. #if BITS_IN_JSAMPLE == 8
  173953. #define DCTELEMBITS 16 /* DCTELEM may be 16 or 32 bits */
  173954. #else
  173955. #define DCTELEMBITS 32 /* DCTELEM must be 32 bits */
  173956. #endif
  173957. #define IRIGHT_SHIFT(x,shft) \
  173958. ((ishift_temp = (x)) < 0 ? \
  173959. (ishift_temp >> (shft)) | ((~((DCTELEM) 0)) << (DCTELEMBITS-(shft))) : \
  173960. (ishift_temp >> (shft)))
  173961. #else
  173962. #define ISHIFT_TEMPS
  173963. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  173964. #endif
  173965. #ifdef USE_ACCURATE_ROUNDING
  173966. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT((x) + (1 << ((n)-1)), n))
  173967. #else
  173968. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT(x, n))
  173969. #endif
  173970. /*
  173971. * Perform dequantization and inverse DCT on one block of coefficients.
  173972. */
  173973. GLOBAL(void)
  173974. jpeg_idct_ifast (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173975. JCOEFPTR coef_block,
  173976. JSAMPARRAY output_buf, JDIMENSION output_col)
  173977. {
  173978. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  173979. DCTELEM tmp10, tmp11, tmp12, tmp13;
  173980. DCTELEM z5, z10, z11, z12, z13;
  173981. JCOEFPTR inptr;
  173982. IFAST_MULT_TYPE * quantptr;
  173983. int * wsptr;
  173984. JSAMPROW outptr;
  173985. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  173986. int ctr;
  173987. int workspace[DCTSIZE2]; /* buffers data between passes */
  173988. SHIFT_TEMPS /* for DESCALE */
  173989. ISHIFT_TEMPS /* for IDESCALE */
  173990. /* Pass 1: process columns from input, store into work array. */
  173991. inptr = coef_block;
  173992. quantptr = (IFAST_MULT_TYPE *) compptr->dct_table;
  173993. wsptr = workspace;
  173994. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  173995. /* Due to quantization, we will usually find that many of the input
  173996. * coefficients are zero, especially the AC terms. We can exploit this
  173997. * by short-circuiting the IDCT calculation for any column in which all
  173998. * the AC terms are zero. In that case each output is equal to the
  173999. * DC coefficient (with scale factor as needed).
  174000. * With typical images and quantization tables, half or more of the
  174001. * column DCT calculations can be simplified this way.
  174002. */
  174003. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  174004. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  174005. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  174006. inptr[DCTSIZE*7] == 0) {
  174007. /* AC terms all zero */
  174008. int dcval = (int) DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174009. wsptr[DCTSIZE*0] = dcval;
  174010. wsptr[DCTSIZE*1] = dcval;
  174011. wsptr[DCTSIZE*2] = dcval;
  174012. wsptr[DCTSIZE*3] = dcval;
  174013. wsptr[DCTSIZE*4] = dcval;
  174014. wsptr[DCTSIZE*5] = dcval;
  174015. wsptr[DCTSIZE*6] = dcval;
  174016. wsptr[DCTSIZE*7] = dcval;
  174017. inptr++; /* advance pointers to next column */
  174018. quantptr++;
  174019. wsptr++;
  174020. continue;
  174021. }
  174022. /* Even part */
  174023. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174024. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  174025. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  174026. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  174027. tmp10 = tmp0 + tmp2; /* phase 3 */
  174028. tmp11 = tmp0 - tmp2;
  174029. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  174030. tmp12 = MULTIPLY(tmp1 - tmp3, FIX_1_414213562) - tmp13; /* 2*c4 */
  174031. tmp0 = tmp10 + tmp13; /* phase 2 */
  174032. tmp3 = tmp10 - tmp13;
  174033. tmp1 = tmp11 + tmp12;
  174034. tmp2 = tmp11 - tmp12;
  174035. /* Odd part */
  174036. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  174037. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  174038. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  174039. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  174040. z13 = tmp6 + tmp5; /* phase 6 */
  174041. z10 = tmp6 - tmp5;
  174042. z11 = tmp4 + tmp7;
  174043. z12 = tmp4 - tmp7;
  174044. tmp7 = z11 + z13; /* phase 5 */
  174045. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  174046. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  174047. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  174048. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  174049. tmp6 = tmp12 - tmp7; /* phase 2 */
  174050. tmp5 = tmp11 - tmp6;
  174051. tmp4 = tmp10 + tmp5;
  174052. wsptr[DCTSIZE*0] = (int) (tmp0 + tmp7);
  174053. wsptr[DCTSIZE*7] = (int) (tmp0 - tmp7);
  174054. wsptr[DCTSIZE*1] = (int) (tmp1 + tmp6);
  174055. wsptr[DCTSIZE*6] = (int) (tmp1 - tmp6);
  174056. wsptr[DCTSIZE*2] = (int) (tmp2 + tmp5);
  174057. wsptr[DCTSIZE*5] = (int) (tmp2 - tmp5);
  174058. wsptr[DCTSIZE*4] = (int) (tmp3 + tmp4);
  174059. wsptr[DCTSIZE*3] = (int) (tmp3 - tmp4);
  174060. inptr++; /* advance pointers to next column */
  174061. quantptr++;
  174062. wsptr++;
  174063. }
  174064. /* Pass 2: process rows from work array, store into output array. */
  174065. /* Note that we must descale the results by a factor of 8 == 2**3, */
  174066. /* and also undo the PASS1_BITS scaling. */
  174067. wsptr = workspace;
  174068. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  174069. outptr = output_buf[ctr] + output_col;
  174070. /* Rows of zeroes can be exploited in the same way as we did with columns.
  174071. * However, the column calculation has created many nonzero AC terms, so
  174072. * the simplification applies less often (typically 5% to 10% of the time).
  174073. * On machines with very fast multiplication, it's possible that the
  174074. * test takes more time than it's worth. In that case this section
  174075. * may be commented out.
  174076. */
  174077. #ifndef NO_ZERO_ROW_TEST
  174078. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  174079. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  174080. /* AC terms all zero */
  174081. JSAMPLE dcval = range_limit[IDESCALE(wsptr[0], PASS1_BITS+3)
  174082. & RANGE_MASK];
  174083. outptr[0] = dcval;
  174084. outptr[1] = dcval;
  174085. outptr[2] = dcval;
  174086. outptr[3] = dcval;
  174087. outptr[4] = dcval;
  174088. outptr[5] = dcval;
  174089. outptr[6] = dcval;
  174090. outptr[7] = dcval;
  174091. wsptr += DCTSIZE; /* advance pointer to next row */
  174092. continue;
  174093. }
  174094. #endif
  174095. /* Even part */
  174096. tmp10 = ((DCTELEM) wsptr[0] + (DCTELEM) wsptr[4]);
  174097. tmp11 = ((DCTELEM) wsptr[0] - (DCTELEM) wsptr[4]);
  174098. tmp13 = ((DCTELEM) wsptr[2] + (DCTELEM) wsptr[6]);
  174099. tmp12 = MULTIPLY((DCTELEM) wsptr[2] - (DCTELEM) wsptr[6], FIX_1_414213562)
  174100. - tmp13;
  174101. tmp0 = tmp10 + tmp13;
  174102. tmp3 = tmp10 - tmp13;
  174103. tmp1 = tmp11 + tmp12;
  174104. tmp2 = tmp11 - tmp12;
  174105. /* Odd part */
  174106. z13 = (DCTELEM) wsptr[5] + (DCTELEM) wsptr[3];
  174107. z10 = (DCTELEM) wsptr[5] - (DCTELEM) wsptr[3];
  174108. z11 = (DCTELEM) wsptr[1] + (DCTELEM) wsptr[7];
  174109. z12 = (DCTELEM) wsptr[1] - (DCTELEM) wsptr[7];
  174110. tmp7 = z11 + z13; /* phase 5 */
  174111. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  174112. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  174113. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  174114. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  174115. tmp6 = tmp12 - tmp7; /* phase 2 */
  174116. tmp5 = tmp11 - tmp6;
  174117. tmp4 = tmp10 + tmp5;
  174118. /* Final output stage: scale down by a factor of 8 and range-limit */
  174119. outptr[0] = range_limit[IDESCALE(tmp0 + tmp7, PASS1_BITS+3)
  174120. & RANGE_MASK];
  174121. outptr[7] = range_limit[IDESCALE(tmp0 - tmp7, PASS1_BITS+3)
  174122. & RANGE_MASK];
  174123. outptr[1] = range_limit[IDESCALE(tmp1 + tmp6, PASS1_BITS+3)
  174124. & RANGE_MASK];
  174125. outptr[6] = range_limit[IDESCALE(tmp1 - tmp6, PASS1_BITS+3)
  174126. & RANGE_MASK];
  174127. outptr[2] = range_limit[IDESCALE(tmp2 + tmp5, PASS1_BITS+3)
  174128. & RANGE_MASK];
  174129. outptr[5] = range_limit[IDESCALE(tmp2 - tmp5, PASS1_BITS+3)
  174130. & RANGE_MASK];
  174131. outptr[4] = range_limit[IDESCALE(tmp3 + tmp4, PASS1_BITS+3)
  174132. & RANGE_MASK];
  174133. outptr[3] = range_limit[IDESCALE(tmp3 - tmp4, PASS1_BITS+3)
  174134. & RANGE_MASK];
  174135. wsptr += DCTSIZE; /* advance pointer to next row */
  174136. }
  174137. }
  174138. #endif /* DCT_IFAST_SUPPORTED */
  174139. /*** End of inlined file: jidctfst.c ***/
  174140. #undef CONST_BITS
  174141. #undef FIX_1_847759065
  174142. #undef MULTIPLY
  174143. #undef DEQUANTIZE
  174144. /*** Start of inlined file: jidctint.c ***/
  174145. #define JPEG_INTERNALS
  174146. #ifdef DCT_ISLOW_SUPPORTED
  174147. /*
  174148. * This module is specialized to the case DCTSIZE = 8.
  174149. */
  174150. #if DCTSIZE != 8
  174151. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174152. #endif
  174153. /*
  174154. * The poop on this scaling stuff is as follows:
  174155. *
  174156. * Each 1-D IDCT step produces outputs which are a factor of sqrt(N)
  174157. * larger than the true IDCT outputs. The final outputs are therefore
  174158. * a factor of N larger than desired; since N=8 this can be cured by
  174159. * a simple right shift at the end of the algorithm. The advantage of
  174160. * this arrangement is that we save two multiplications per 1-D IDCT,
  174161. * because the y0 and y4 inputs need not be divided by sqrt(N).
  174162. *
  174163. * We have to do addition and subtraction of the integer inputs, which
  174164. * is no problem, and multiplication by fractional constants, which is
  174165. * a problem to do in integer arithmetic. We multiply all the constants
  174166. * by CONST_SCALE and convert them to integer constants (thus retaining
  174167. * CONST_BITS bits of precision in the constants). After doing a
  174168. * multiplication we have to divide the product by CONST_SCALE, with proper
  174169. * rounding, to produce the correct output. This division can be done
  174170. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  174171. * as long as possible so that partial sums can be added together with
  174172. * full fractional precision.
  174173. *
  174174. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  174175. * they are represented to better-than-integral precision. These outputs
  174176. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  174177. * with the recommended scaling. (To scale up 12-bit sample data further, an
  174178. * intermediate INT32 array would be needed.)
  174179. *
  174180. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  174181. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  174182. * shows that the values given below are the most effective.
  174183. */
  174184. #if BITS_IN_JSAMPLE == 8
  174185. #define CONST_BITS 13
  174186. #define PASS1_BITS 2
  174187. #else
  174188. #define CONST_BITS 13
  174189. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  174190. #endif
  174191. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174192. * causing a lot of useless floating-point operations at run time.
  174193. * To get around this we use the following pre-calculated constants.
  174194. * If you change CONST_BITS you may want to add appropriate values.
  174195. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174196. */
  174197. #if CONST_BITS == 13
  174198. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  174199. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  174200. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  174201. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  174202. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  174203. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  174204. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  174205. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  174206. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  174207. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  174208. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  174209. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  174210. #else
  174211. #define FIX_0_298631336 FIX(0.298631336)
  174212. #define FIX_0_390180644 FIX(0.390180644)
  174213. #define FIX_0_541196100 FIX(0.541196100)
  174214. #define FIX_0_765366865 FIX(0.765366865)
  174215. #define FIX_0_899976223 FIX(0.899976223)
  174216. #define FIX_1_175875602 FIX(1.175875602)
  174217. #define FIX_1_501321110 FIX(1.501321110)
  174218. #define FIX_1_847759065 FIX(1.847759065)
  174219. #define FIX_1_961570560 FIX(1.961570560)
  174220. #define FIX_2_053119869 FIX(2.053119869)
  174221. #define FIX_2_562915447 FIX(2.562915447)
  174222. #define FIX_3_072711026 FIX(3.072711026)
  174223. #endif
  174224. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  174225. * For 8-bit samples with the recommended scaling, all the variable
  174226. * and constant values involved are no more than 16 bits wide, so a
  174227. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  174228. * For 12-bit samples, a full 32-bit multiplication will be needed.
  174229. */
  174230. #if BITS_IN_JSAMPLE == 8
  174231. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  174232. #else
  174233. #define MULTIPLY(var,const) ((var) * (const))
  174234. #endif
  174235. /* Dequantize a coefficient by multiplying it by the multiplier-table
  174236. * entry; produce an int result. In this module, both inputs and result
  174237. * are 16 bits or less, so either int or short multiply will work.
  174238. */
  174239. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  174240. /*
  174241. * Perform dequantization and inverse DCT on one block of coefficients.
  174242. */
  174243. GLOBAL(void)
  174244. jpeg_idct_islow (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174245. JCOEFPTR coef_block,
  174246. JSAMPARRAY output_buf, JDIMENSION output_col)
  174247. {
  174248. INT32 tmp0, tmp1, tmp2, tmp3;
  174249. INT32 tmp10, tmp11, tmp12, tmp13;
  174250. INT32 z1, z2, z3, z4, z5;
  174251. JCOEFPTR inptr;
  174252. ISLOW_MULT_TYPE * quantptr;
  174253. int * wsptr;
  174254. JSAMPROW outptr;
  174255. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  174256. int ctr;
  174257. int workspace[DCTSIZE2]; /* buffers data between passes */
  174258. SHIFT_TEMPS
  174259. /* Pass 1: process columns from input, store into work array. */
  174260. /* Note results are scaled up by sqrt(8) compared to a true IDCT; */
  174261. /* furthermore, we scale the results by 2**PASS1_BITS. */
  174262. inptr = coef_block;
  174263. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  174264. wsptr = workspace;
  174265. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  174266. /* Due to quantization, we will usually find that many of the input
  174267. * coefficients are zero, especially the AC terms. We can exploit this
  174268. * by short-circuiting the IDCT calculation for any column in which all
  174269. * the AC terms are zero. In that case each output is equal to the
  174270. * DC coefficient (with scale factor as needed).
  174271. * With typical images and quantization tables, half or more of the
  174272. * column DCT calculations can be simplified this way.
  174273. */
  174274. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  174275. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  174276. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  174277. inptr[DCTSIZE*7] == 0) {
  174278. /* AC terms all zero */
  174279. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  174280. wsptr[DCTSIZE*0] = dcval;
  174281. wsptr[DCTSIZE*1] = dcval;
  174282. wsptr[DCTSIZE*2] = dcval;
  174283. wsptr[DCTSIZE*3] = dcval;
  174284. wsptr[DCTSIZE*4] = dcval;
  174285. wsptr[DCTSIZE*5] = dcval;
  174286. wsptr[DCTSIZE*6] = dcval;
  174287. wsptr[DCTSIZE*7] = dcval;
  174288. inptr++; /* advance pointers to next column */
  174289. quantptr++;
  174290. wsptr++;
  174291. continue;
  174292. }
  174293. /* Even part: reverse the even part of the forward DCT. */
  174294. /* The rotator is sqrt(2)*c(-6). */
  174295. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  174296. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  174297. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  174298. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  174299. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  174300. z2 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174301. z3 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  174302. tmp0 = (z2 + z3) << CONST_BITS;
  174303. tmp1 = (z2 - z3) << CONST_BITS;
  174304. tmp10 = tmp0 + tmp3;
  174305. tmp13 = tmp0 - tmp3;
  174306. tmp11 = tmp1 + tmp2;
  174307. tmp12 = tmp1 - tmp2;
  174308. /* Odd part per figure 8; the matrix is unitary and hence its
  174309. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  174310. */
  174311. tmp0 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  174312. tmp1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  174313. tmp2 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  174314. tmp3 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  174315. z1 = tmp0 + tmp3;
  174316. z2 = tmp1 + tmp2;
  174317. z3 = tmp0 + tmp2;
  174318. z4 = tmp1 + tmp3;
  174319. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  174320. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  174321. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  174322. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  174323. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  174324. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  174325. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  174326. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  174327. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  174328. z3 += z5;
  174329. z4 += z5;
  174330. tmp0 += z1 + z3;
  174331. tmp1 += z2 + z4;
  174332. tmp2 += z2 + z3;
  174333. tmp3 += z1 + z4;
  174334. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  174335. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp3, CONST_BITS-PASS1_BITS);
  174336. wsptr[DCTSIZE*7] = (int) DESCALE(tmp10 - tmp3, CONST_BITS-PASS1_BITS);
  174337. wsptr[DCTSIZE*1] = (int) DESCALE(tmp11 + tmp2, CONST_BITS-PASS1_BITS);
  174338. wsptr[DCTSIZE*6] = (int) DESCALE(tmp11 - tmp2, CONST_BITS-PASS1_BITS);
  174339. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 + tmp1, CONST_BITS-PASS1_BITS);
  174340. wsptr[DCTSIZE*5] = (int) DESCALE(tmp12 - tmp1, CONST_BITS-PASS1_BITS);
  174341. wsptr[DCTSIZE*3] = (int) DESCALE(tmp13 + tmp0, CONST_BITS-PASS1_BITS);
  174342. wsptr[DCTSIZE*4] = (int) DESCALE(tmp13 - tmp0, CONST_BITS-PASS1_BITS);
  174343. inptr++; /* advance pointers to next column */
  174344. quantptr++;
  174345. wsptr++;
  174346. }
  174347. /* Pass 2: process rows from work array, store into output array. */
  174348. /* Note that we must descale the results by a factor of 8 == 2**3, */
  174349. /* and also undo the PASS1_BITS scaling. */
  174350. wsptr = workspace;
  174351. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  174352. outptr = output_buf[ctr] + output_col;
  174353. /* Rows of zeroes can be exploited in the same way as we did with columns.
  174354. * However, the column calculation has created many nonzero AC terms, so
  174355. * the simplification applies less often (typically 5% to 10% of the time).
  174356. * On machines with very fast multiplication, it's possible that the
  174357. * test takes more time than it's worth. In that case this section
  174358. * may be commented out.
  174359. */
  174360. #ifndef NO_ZERO_ROW_TEST
  174361. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  174362. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  174363. /* AC terms all zero */
  174364. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  174365. & RANGE_MASK];
  174366. outptr[0] = dcval;
  174367. outptr[1] = dcval;
  174368. outptr[2] = dcval;
  174369. outptr[3] = dcval;
  174370. outptr[4] = dcval;
  174371. outptr[5] = dcval;
  174372. outptr[6] = dcval;
  174373. outptr[7] = dcval;
  174374. wsptr += DCTSIZE; /* advance pointer to next row */
  174375. continue;
  174376. }
  174377. #endif
  174378. /* Even part: reverse the even part of the forward DCT. */
  174379. /* The rotator is sqrt(2)*c(-6). */
  174380. z2 = (INT32) wsptr[2];
  174381. z3 = (INT32) wsptr[6];
  174382. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  174383. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  174384. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  174385. tmp0 = ((INT32) wsptr[0] + (INT32) wsptr[4]) << CONST_BITS;
  174386. tmp1 = ((INT32) wsptr[0] - (INT32) wsptr[4]) << CONST_BITS;
  174387. tmp10 = tmp0 + tmp3;
  174388. tmp13 = tmp0 - tmp3;
  174389. tmp11 = tmp1 + tmp2;
  174390. tmp12 = tmp1 - tmp2;
  174391. /* Odd part per figure 8; the matrix is unitary and hence its
  174392. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  174393. */
  174394. tmp0 = (INT32) wsptr[7];
  174395. tmp1 = (INT32) wsptr[5];
  174396. tmp2 = (INT32) wsptr[3];
  174397. tmp3 = (INT32) wsptr[1];
  174398. z1 = tmp0 + tmp3;
  174399. z2 = tmp1 + tmp2;
  174400. z3 = tmp0 + tmp2;
  174401. z4 = tmp1 + tmp3;
  174402. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  174403. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  174404. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  174405. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  174406. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  174407. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  174408. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  174409. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  174410. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  174411. z3 += z5;
  174412. z4 += z5;
  174413. tmp0 += z1 + z3;
  174414. tmp1 += z2 + z4;
  174415. tmp2 += z2 + z3;
  174416. tmp3 += z1 + z4;
  174417. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  174418. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp3,
  174419. CONST_BITS+PASS1_BITS+3)
  174420. & RANGE_MASK];
  174421. outptr[7] = range_limit[(int) DESCALE(tmp10 - tmp3,
  174422. CONST_BITS+PASS1_BITS+3)
  174423. & RANGE_MASK];
  174424. outptr[1] = range_limit[(int) DESCALE(tmp11 + tmp2,
  174425. CONST_BITS+PASS1_BITS+3)
  174426. & RANGE_MASK];
  174427. outptr[6] = range_limit[(int) DESCALE(tmp11 - tmp2,
  174428. CONST_BITS+PASS1_BITS+3)
  174429. & RANGE_MASK];
  174430. outptr[2] = range_limit[(int) DESCALE(tmp12 + tmp1,
  174431. CONST_BITS+PASS1_BITS+3)
  174432. & RANGE_MASK];
  174433. outptr[5] = range_limit[(int) DESCALE(tmp12 - tmp1,
  174434. CONST_BITS+PASS1_BITS+3)
  174435. & RANGE_MASK];
  174436. outptr[3] = range_limit[(int) DESCALE(tmp13 + tmp0,
  174437. CONST_BITS+PASS1_BITS+3)
  174438. & RANGE_MASK];
  174439. outptr[4] = range_limit[(int) DESCALE(tmp13 - tmp0,
  174440. CONST_BITS+PASS1_BITS+3)
  174441. & RANGE_MASK];
  174442. wsptr += DCTSIZE; /* advance pointer to next row */
  174443. }
  174444. }
  174445. #endif /* DCT_ISLOW_SUPPORTED */
  174446. /*** End of inlined file: jidctint.c ***/
  174447. /*** Start of inlined file: jidctred.c ***/
  174448. #define JPEG_INTERNALS
  174449. #ifdef IDCT_SCALING_SUPPORTED
  174450. /*
  174451. * This module is specialized to the case DCTSIZE = 8.
  174452. */
  174453. #if DCTSIZE != 8
  174454. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174455. #endif
  174456. /* Scaling is the same as in jidctint.c. */
  174457. #if BITS_IN_JSAMPLE == 8
  174458. #define CONST_BITS 13
  174459. #define PASS1_BITS 2
  174460. #else
  174461. #define CONST_BITS 13
  174462. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  174463. #endif
  174464. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174465. * causing a lot of useless floating-point operations at run time.
  174466. * To get around this we use the following pre-calculated constants.
  174467. * If you change CONST_BITS you may want to add appropriate values.
  174468. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174469. */
  174470. #if CONST_BITS == 13
  174471. #define FIX_0_211164243 ((INT32) 1730) /* FIX(0.211164243) */
  174472. #define FIX_0_509795579 ((INT32) 4176) /* FIX(0.509795579) */
  174473. #define FIX_0_601344887 ((INT32) 4926) /* FIX(0.601344887) */
  174474. #define FIX_0_720959822 ((INT32) 5906) /* FIX(0.720959822) */
  174475. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  174476. #define FIX_0_850430095 ((INT32) 6967) /* FIX(0.850430095) */
  174477. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  174478. #define FIX_1_061594337 ((INT32) 8697) /* FIX(1.061594337) */
  174479. #define FIX_1_272758580 ((INT32) 10426) /* FIX(1.272758580) */
  174480. #define FIX_1_451774981 ((INT32) 11893) /* FIX(1.451774981) */
  174481. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  174482. #define FIX_2_172734803 ((INT32) 17799) /* FIX(2.172734803) */
  174483. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  174484. #define FIX_3_624509785 ((INT32) 29692) /* FIX(3.624509785) */
  174485. #else
  174486. #define FIX_0_211164243 FIX(0.211164243)
  174487. #define FIX_0_509795579 FIX(0.509795579)
  174488. #define FIX_0_601344887 FIX(0.601344887)
  174489. #define FIX_0_720959822 FIX(0.720959822)
  174490. #define FIX_0_765366865 FIX(0.765366865)
  174491. #define FIX_0_850430095 FIX(0.850430095)
  174492. #define FIX_0_899976223 FIX(0.899976223)
  174493. #define FIX_1_061594337 FIX(1.061594337)
  174494. #define FIX_1_272758580 FIX(1.272758580)
  174495. #define FIX_1_451774981 FIX(1.451774981)
  174496. #define FIX_1_847759065 FIX(1.847759065)
  174497. #define FIX_2_172734803 FIX(2.172734803)
  174498. #define FIX_2_562915447 FIX(2.562915447)
  174499. #define FIX_3_624509785 FIX(3.624509785)
  174500. #endif
  174501. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  174502. * For 8-bit samples with the recommended scaling, all the variable
  174503. * and constant values involved are no more than 16 bits wide, so a
  174504. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  174505. * For 12-bit samples, a full 32-bit multiplication will be needed.
  174506. */
  174507. #if BITS_IN_JSAMPLE == 8
  174508. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  174509. #else
  174510. #define MULTIPLY(var,const) ((var) * (const))
  174511. #endif
  174512. /* Dequantize a coefficient by multiplying it by the multiplier-table
  174513. * entry; produce an int result. In this module, both inputs and result
  174514. * are 16 bits or less, so either int or short multiply will work.
  174515. */
  174516. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  174517. /*
  174518. * Perform dequantization and inverse DCT on one block of coefficients,
  174519. * producing a reduced-size 4x4 output block.
  174520. */
  174521. GLOBAL(void)
  174522. jpeg_idct_4x4 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174523. JCOEFPTR coef_block,
  174524. JSAMPARRAY output_buf, JDIMENSION output_col)
  174525. {
  174526. INT32 tmp0, tmp2, tmp10, tmp12;
  174527. INT32 z1, z2, z3, z4;
  174528. JCOEFPTR inptr;
  174529. ISLOW_MULT_TYPE * quantptr;
  174530. int * wsptr;
  174531. JSAMPROW outptr;
  174532. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  174533. int ctr;
  174534. int workspace[DCTSIZE*4]; /* buffers data between passes */
  174535. SHIFT_TEMPS
  174536. /* Pass 1: process columns from input, store into work array. */
  174537. inptr = coef_block;
  174538. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  174539. wsptr = workspace;
  174540. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  174541. /* Don't bother to process column 4, because second pass won't use it */
  174542. if (ctr == DCTSIZE-4)
  174543. continue;
  174544. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  174545. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*5] == 0 &&
  174546. inptr[DCTSIZE*6] == 0 && inptr[DCTSIZE*7] == 0) {
  174547. /* AC terms all zero; we need not examine term 4 for 4x4 output */
  174548. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  174549. wsptr[DCTSIZE*0] = dcval;
  174550. wsptr[DCTSIZE*1] = dcval;
  174551. wsptr[DCTSIZE*2] = dcval;
  174552. wsptr[DCTSIZE*3] = dcval;
  174553. continue;
  174554. }
  174555. /* Even part */
  174556. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174557. tmp0 <<= (CONST_BITS+1);
  174558. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  174559. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  174560. tmp2 = MULTIPLY(z2, FIX_1_847759065) + MULTIPLY(z3, - FIX_0_765366865);
  174561. tmp10 = tmp0 + tmp2;
  174562. tmp12 = tmp0 - tmp2;
  174563. /* Odd part */
  174564. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  174565. z2 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  174566. z3 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  174567. z4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  174568. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  174569. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  174570. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  174571. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  174572. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  174573. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  174574. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  174575. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  174576. /* Final output stage */
  174577. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp2, CONST_BITS-PASS1_BITS+1);
  174578. wsptr[DCTSIZE*3] = (int) DESCALE(tmp10 - tmp2, CONST_BITS-PASS1_BITS+1);
  174579. wsptr[DCTSIZE*1] = (int) DESCALE(tmp12 + tmp0, CONST_BITS-PASS1_BITS+1);
  174580. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 - tmp0, CONST_BITS-PASS1_BITS+1);
  174581. }
  174582. /* Pass 2: process 4 rows from work array, store into output array. */
  174583. wsptr = workspace;
  174584. for (ctr = 0; ctr < 4; ctr++) {
  174585. outptr = output_buf[ctr] + output_col;
  174586. /* It's not clear whether a zero row test is worthwhile here ... */
  174587. #ifndef NO_ZERO_ROW_TEST
  174588. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 &&
  174589. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  174590. /* AC terms all zero */
  174591. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  174592. & RANGE_MASK];
  174593. outptr[0] = dcval;
  174594. outptr[1] = dcval;
  174595. outptr[2] = dcval;
  174596. outptr[3] = dcval;
  174597. wsptr += DCTSIZE; /* advance pointer to next row */
  174598. continue;
  174599. }
  174600. #endif
  174601. /* Even part */
  174602. tmp0 = ((INT32) wsptr[0]) << (CONST_BITS+1);
  174603. tmp2 = MULTIPLY((INT32) wsptr[2], FIX_1_847759065)
  174604. + MULTIPLY((INT32) wsptr[6], - FIX_0_765366865);
  174605. tmp10 = tmp0 + tmp2;
  174606. tmp12 = tmp0 - tmp2;
  174607. /* Odd part */
  174608. z1 = (INT32) wsptr[7];
  174609. z2 = (INT32) wsptr[5];
  174610. z3 = (INT32) wsptr[3];
  174611. z4 = (INT32) wsptr[1];
  174612. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  174613. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  174614. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  174615. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  174616. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  174617. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  174618. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  174619. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  174620. /* Final output stage */
  174621. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp2,
  174622. CONST_BITS+PASS1_BITS+3+1)
  174623. & RANGE_MASK];
  174624. outptr[3] = range_limit[(int) DESCALE(tmp10 - tmp2,
  174625. CONST_BITS+PASS1_BITS+3+1)
  174626. & RANGE_MASK];
  174627. outptr[1] = range_limit[(int) DESCALE(tmp12 + tmp0,
  174628. CONST_BITS+PASS1_BITS+3+1)
  174629. & RANGE_MASK];
  174630. outptr[2] = range_limit[(int) DESCALE(tmp12 - tmp0,
  174631. CONST_BITS+PASS1_BITS+3+1)
  174632. & RANGE_MASK];
  174633. wsptr += DCTSIZE; /* advance pointer to next row */
  174634. }
  174635. }
  174636. /*
  174637. * Perform dequantization and inverse DCT on one block of coefficients,
  174638. * producing a reduced-size 2x2 output block.
  174639. */
  174640. GLOBAL(void)
  174641. jpeg_idct_2x2 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174642. JCOEFPTR coef_block,
  174643. JSAMPARRAY output_buf, JDIMENSION output_col)
  174644. {
  174645. INT32 tmp0, tmp10, z1;
  174646. JCOEFPTR inptr;
  174647. ISLOW_MULT_TYPE * quantptr;
  174648. int * wsptr;
  174649. JSAMPROW outptr;
  174650. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  174651. int ctr;
  174652. int workspace[DCTSIZE*2]; /* buffers data between passes */
  174653. SHIFT_TEMPS
  174654. /* Pass 1: process columns from input, store into work array. */
  174655. inptr = coef_block;
  174656. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  174657. wsptr = workspace;
  174658. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  174659. /* Don't bother to process columns 2,4,6 */
  174660. if (ctr == DCTSIZE-2 || ctr == DCTSIZE-4 || ctr == DCTSIZE-6)
  174661. continue;
  174662. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*3] == 0 &&
  174663. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*7] == 0) {
  174664. /* AC terms all zero; we need not examine terms 2,4,6 for 2x2 output */
  174665. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  174666. wsptr[DCTSIZE*0] = dcval;
  174667. wsptr[DCTSIZE*1] = dcval;
  174668. continue;
  174669. }
  174670. /* Even part */
  174671. z1 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174672. tmp10 = z1 << (CONST_BITS+2);
  174673. /* Odd part */
  174674. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  174675. tmp0 = MULTIPLY(z1, - FIX_0_720959822); /* sqrt(2) * (c7-c5+c3-c1) */
  174676. z1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  174677. tmp0 += MULTIPLY(z1, FIX_0_850430095); /* sqrt(2) * (-c1+c3+c5+c7) */
  174678. z1 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  174679. tmp0 += MULTIPLY(z1, - FIX_1_272758580); /* sqrt(2) * (-c1+c3-c5-c7) */
  174680. z1 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  174681. tmp0 += MULTIPLY(z1, FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  174682. /* Final output stage */
  174683. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp0, CONST_BITS-PASS1_BITS+2);
  174684. wsptr[DCTSIZE*1] = (int) DESCALE(tmp10 - tmp0, CONST_BITS-PASS1_BITS+2);
  174685. }
  174686. /* Pass 2: process 2 rows from work array, store into output array. */
  174687. wsptr = workspace;
  174688. for (ctr = 0; ctr < 2; ctr++) {
  174689. outptr = output_buf[ctr] + output_col;
  174690. /* It's not clear whether a zero row test is worthwhile here ... */
  174691. #ifndef NO_ZERO_ROW_TEST
  174692. if (wsptr[1] == 0 && wsptr[3] == 0 && wsptr[5] == 0 && wsptr[7] == 0) {
  174693. /* AC terms all zero */
  174694. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  174695. & RANGE_MASK];
  174696. outptr[0] = dcval;
  174697. outptr[1] = dcval;
  174698. wsptr += DCTSIZE; /* advance pointer to next row */
  174699. continue;
  174700. }
  174701. #endif
  174702. /* Even part */
  174703. tmp10 = ((INT32) wsptr[0]) << (CONST_BITS+2);
  174704. /* Odd part */
  174705. tmp0 = MULTIPLY((INT32) wsptr[7], - FIX_0_720959822) /* sqrt(2) * (c7-c5+c3-c1) */
  174706. + MULTIPLY((INT32) wsptr[5], FIX_0_850430095) /* sqrt(2) * (-c1+c3+c5+c7) */
  174707. + MULTIPLY((INT32) wsptr[3], - FIX_1_272758580) /* sqrt(2) * (-c1+c3-c5-c7) */
  174708. + MULTIPLY((INT32) wsptr[1], FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  174709. /* Final output stage */
  174710. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp0,
  174711. CONST_BITS+PASS1_BITS+3+2)
  174712. & RANGE_MASK];
  174713. outptr[1] = range_limit[(int) DESCALE(tmp10 - tmp0,
  174714. CONST_BITS+PASS1_BITS+3+2)
  174715. & RANGE_MASK];
  174716. wsptr += DCTSIZE; /* advance pointer to next row */
  174717. }
  174718. }
  174719. /*
  174720. * Perform dequantization and inverse DCT on one block of coefficients,
  174721. * producing a reduced-size 1x1 output block.
  174722. */
  174723. GLOBAL(void)
  174724. jpeg_idct_1x1 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174725. JCOEFPTR coef_block,
  174726. JSAMPARRAY output_buf, JDIMENSION output_col)
  174727. {
  174728. int dcval;
  174729. ISLOW_MULT_TYPE * quantptr;
  174730. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  174731. SHIFT_TEMPS
  174732. /* We hardly need an inverse DCT routine for this: just take the
  174733. * average pixel value, which is one-eighth of the DC coefficient.
  174734. */
  174735. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  174736. dcval = DEQUANTIZE(coef_block[0], quantptr[0]);
  174737. dcval = (int) DESCALE((INT32) dcval, 3);
  174738. output_buf[0][output_col] = range_limit[dcval & RANGE_MASK];
  174739. }
  174740. #endif /* IDCT_SCALING_SUPPORTED */
  174741. /*** End of inlined file: jidctred.c ***/
  174742. /*** Start of inlined file: jmemmgr.c ***/
  174743. #define JPEG_INTERNALS
  174744. #define AM_MEMORY_MANAGER /* we define jvirt_Xarray_control structs */
  174745. /*** Start of inlined file: jmemsys.h ***/
  174746. #ifndef __jmemsys_h__
  174747. #define __jmemsys_h__
  174748. /* Short forms of external names for systems with brain-damaged linkers. */
  174749. #ifdef NEED_SHORT_EXTERNAL_NAMES
  174750. #define jpeg_get_small jGetSmall
  174751. #define jpeg_free_small jFreeSmall
  174752. #define jpeg_get_large jGetLarge
  174753. #define jpeg_free_large jFreeLarge
  174754. #define jpeg_mem_available jMemAvail
  174755. #define jpeg_open_backing_store jOpenBackStore
  174756. #define jpeg_mem_init jMemInit
  174757. #define jpeg_mem_term jMemTerm
  174758. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  174759. /*
  174760. * These two functions are used to allocate and release small chunks of
  174761. * memory. (Typically the total amount requested through jpeg_get_small is
  174762. * no more than 20K or so; this will be requested in chunks of a few K each.)
  174763. * Behavior should be the same as for the standard library functions malloc
  174764. * and free; in particular, jpeg_get_small must return NULL on failure.
  174765. * On most systems, these ARE malloc and free. jpeg_free_small is passed the
  174766. * size of the object being freed, just in case it's needed.
  174767. * On an 80x86 machine using small-data memory model, these manage near heap.
  174768. */
  174769. EXTERN(void *) jpeg_get_small JPP((j_common_ptr cinfo, size_t sizeofobject));
  174770. EXTERN(void) jpeg_free_small JPP((j_common_ptr cinfo, void * object,
  174771. size_t sizeofobject));
  174772. /*
  174773. * These two functions are used to allocate and release large chunks of
  174774. * memory (up to the total free space designated by jpeg_mem_available).
  174775. * The interface is the same as above, except that on an 80x86 machine,
  174776. * far pointers are used. On most other machines these are identical to
  174777. * the jpeg_get/free_small routines; but we keep them separate anyway,
  174778. * in case a different allocation strategy is desirable for large chunks.
  174779. */
  174780. EXTERN(void FAR *) jpeg_get_large JPP((j_common_ptr cinfo,
  174781. size_t sizeofobject));
  174782. EXTERN(void) jpeg_free_large JPP((j_common_ptr cinfo, void FAR * object,
  174783. size_t sizeofobject));
  174784. /*
  174785. * The macro MAX_ALLOC_CHUNK designates the maximum number of bytes that may
  174786. * be requested in a single call to jpeg_get_large (and jpeg_get_small for that
  174787. * matter, but that case should never come into play). This macro is needed
  174788. * to model the 64Kb-segment-size limit of far addressing on 80x86 machines.
  174789. * On those machines, we expect that jconfig.h will provide a proper value.
  174790. * On machines with 32-bit flat address spaces, any large constant may be used.
  174791. *
  174792. * NB: jmemmgr.c expects that MAX_ALLOC_CHUNK will be representable as type
  174793. * size_t and will be a multiple of sizeof(align_type).
  174794. */
  174795. #ifndef MAX_ALLOC_CHUNK /* may be overridden in jconfig.h */
  174796. #define MAX_ALLOC_CHUNK 1000000000L
  174797. #endif
  174798. /*
  174799. * This routine computes the total space still available for allocation by
  174800. * jpeg_get_large. If more space than this is needed, backing store will be
  174801. * used. NOTE: any memory already allocated must not be counted.
  174802. *
  174803. * There is a minimum space requirement, corresponding to the minimum
  174804. * feasible buffer sizes; jmemmgr.c will request that much space even if
  174805. * jpeg_mem_available returns zero. The maximum space needed, enough to hold
  174806. * all working storage in memory, is also passed in case it is useful.
  174807. * Finally, the total space already allocated is passed. If no better
  174808. * method is available, cinfo->mem->max_memory_to_use - already_allocated
  174809. * is often a suitable calculation.
  174810. *
  174811. * It is OK for jpeg_mem_available to underestimate the space available
  174812. * (that'll just lead to more backing-store access than is really necessary).
  174813. * However, an overestimate will lead to failure. Hence it's wise to subtract
  174814. * a slop factor from the true available space. 5% should be enough.
  174815. *
  174816. * On machines with lots of virtual memory, any large constant may be returned.
  174817. * Conversely, zero may be returned to always use the minimum amount of memory.
  174818. */
  174819. EXTERN(long) jpeg_mem_available JPP((j_common_ptr cinfo,
  174820. long min_bytes_needed,
  174821. long max_bytes_needed,
  174822. long already_allocated));
  174823. /*
  174824. * This structure holds whatever state is needed to access a single
  174825. * backing-store object. The read/write/close method pointers are called
  174826. * by jmemmgr.c to manipulate the backing-store object; all other fields
  174827. * are private to the system-dependent backing store routines.
  174828. */
  174829. #define TEMP_NAME_LENGTH 64 /* max length of a temporary file's name */
  174830. #ifdef USE_MSDOS_MEMMGR /* DOS-specific junk */
  174831. typedef unsigned short XMSH; /* type of extended-memory handles */
  174832. typedef unsigned short EMSH; /* type of expanded-memory handles */
  174833. typedef union {
  174834. short file_handle; /* DOS file handle if it's a temp file */
  174835. XMSH xms_handle; /* handle if it's a chunk of XMS */
  174836. EMSH ems_handle; /* handle if it's a chunk of EMS */
  174837. } handle_union;
  174838. #endif /* USE_MSDOS_MEMMGR */
  174839. #ifdef USE_MAC_MEMMGR /* Mac-specific junk */
  174840. #include <Files.h>
  174841. #endif /* USE_MAC_MEMMGR */
  174842. //typedef struct backing_store_struct * backing_store_ptr;
  174843. typedef struct backing_store_struct {
  174844. /* Methods for reading/writing/closing this backing-store object */
  174845. JMETHOD(void, read_backing_store, (j_common_ptr cinfo,
  174846. struct backing_store_struct *info,
  174847. void FAR * buffer_address,
  174848. long file_offset, long byte_count));
  174849. JMETHOD(void, write_backing_store, (j_common_ptr cinfo,
  174850. struct backing_store_struct *info,
  174851. void FAR * buffer_address,
  174852. long file_offset, long byte_count));
  174853. JMETHOD(void, close_backing_store, (j_common_ptr cinfo,
  174854. struct backing_store_struct *info));
  174855. /* Private fields for system-dependent backing-store management */
  174856. #ifdef USE_MSDOS_MEMMGR
  174857. /* For the MS-DOS manager (jmemdos.c), we need: */
  174858. handle_union handle; /* reference to backing-store storage object */
  174859. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  174860. #else
  174861. #ifdef USE_MAC_MEMMGR
  174862. /* For the Mac manager (jmemmac.c), we need: */
  174863. short temp_file; /* file reference number to temp file */
  174864. FSSpec tempSpec; /* the FSSpec for the temp file */
  174865. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  174866. #else
  174867. /* For a typical implementation with temp files, we need: */
  174868. FILE * temp_file; /* stdio reference to temp file */
  174869. char temp_name[TEMP_NAME_LENGTH]; /* name of temp file */
  174870. #endif
  174871. #endif
  174872. } backing_store_info;
  174873. /*
  174874. * Initial opening of a backing-store object. This must fill in the
  174875. * read/write/close pointers in the object. The read/write routines
  174876. * may take an error exit if the specified maximum file size is exceeded.
  174877. * (If jpeg_mem_available always returns a large value, this routine can
  174878. * just take an error exit.)
  174879. */
  174880. EXTERN(void) jpeg_open_backing_store JPP((j_common_ptr cinfo,
  174881. struct backing_store_struct *info,
  174882. long total_bytes_needed));
  174883. /*
  174884. * These routines take care of any system-dependent initialization and
  174885. * cleanup required. jpeg_mem_init will be called before anything is
  174886. * allocated (and, therefore, nothing in cinfo is of use except the error
  174887. * manager pointer). It should return a suitable default value for
  174888. * max_memory_to_use; this may subsequently be overridden by the surrounding
  174889. * application. (Note that max_memory_to_use is only important if
  174890. * jpeg_mem_available chooses to consult it ... no one else will.)
  174891. * jpeg_mem_term may assume that all requested memory has been freed and that
  174892. * all opened backing-store objects have been closed.
  174893. */
  174894. EXTERN(long) jpeg_mem_init JPP((j_common_ptr cinfo));
  174895. EXTERN(void) jpeg_mem_term JPP((j_common_ptr cinfo));
  174896. #endif
  174897. /*** End of inlined file: jmemsys.h ***/
  174898. /* import the system-dependent declarations */
  174899. #ifndef NO_GETENV
  174900. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare getenv() */
  174901. extern char * getenv JPP((const char * name));
  174902. #endif
  174903. #endif
  174904. /*
  174905. * Some important notes:
  174906. * The allocation routines provided here must never return NULL.
  174907. * They should exit to error_exit if unsuccessful.
  174908. *
  174909. * It's not a good idea to try to merge the sarray and barray routines,
  174910. * even though they are textually almost the same, because samples are
  174911. * usually stored as bytes while coefficients are shorts or ints. Thus,
  174912. * in machines where byte pointers have a different representation from
  174913. * word pointers, the resulting machine code could not be the same.
  174914. */
  174915. /*
  174916. * Many machines require storage alignment: longs must start on 4-byte
  174917. * boundaries, doubles on 8-byte boundaries, etc. On such machines, malloc()
  174918. * always returns pointers that are multiples of the worst-case alignment
  174919. * requirement, and we had better do so too.
  174920. * There isn't any really portable way to determine the worst-case alignment
  174921. * requirement. This module assumes that the alignment requirement is
  174922. * multiples of sizeof(ALIGN_TYPE).
  174923. * By default, we define ALIGN_TYPE as double. This is necessary on some
  174924. * workstations (where doubles really do need 8-byte alignment) and will work
  174925. * fine on nearly everything. If your machine has lesser alignment needs,
  174926. * you can save a few bytes by making ALIGN_TYPE smaller.
  174927. * The only place I know of where this will NOT work is certain Macintosh
  174928. * 680x0 compilers that define double as a 10-byte IEEE extended float.
  174929. * Doing 10-byte alignment is counterproductive because longwords won't be
  174930. * aligned well. Put "#define ALIGN_TYPE long" in jconfig.h if you have
  174931. * such a compiler.
  174932. */
  174933. #ifndef ALIGN_TYPE /* so can override from jconfig.h */
  174934. #define ALIGN_TYPE double
  174935. #endif
  174936. /*
  174937. * We allocate objects from "pools", where each pool is gotten with a single
  174938. * request to jpeg_get_small() or jpeg_get_large(). There is no per-object
  174939. * overhead within a pool, except for alignment padding. Each pool has a
  174940. * header with a link to the next pool of the same class.
  174941. * Small and large pool headers are identical except that the latter's
  174942. * link pointer must be FAR on 80x86 machines.
  174943. * Notice that the "real" header fields are union'ed with a dummy ALIGN_TYPE
  174944. * field. This forces the compiler to make SIZEOF(small_pool_hdr) a multiple
  174945. * of the alignment requirement of ALIGN_TYPE.
  174946. */
  174947. typedef union small_pool_struct * small_pool_ptr;
  174948. typedef union small_pool_struct {
  174949. struct {
  174950. small_pool_ptr next; /* next in list of pools */
  174951. size_t bytes_used; /* how many bytes already used within pool */
  174952. size_t bytes_left; /* bytes still available in this pool */
  174953. } hdr;
  174954. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  174955. } small_pool_hdr;
  174956. typedef union large_pool_struct FAR * large_pool_ptr;
  174957. typedef union large_pool_struct {
  174958. struct {
  174959. large_pool_ptr next; /* next in list of pools */
  174960. size_t bytes_used; /* how many bytes already used within pool */
  174961. size_t bytes_left; /* bytes still available in this pool */
  174962. } hdr;
  174963. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  174964. } large_pool_hdr;
  174965. /*
  174966. * Here is the full definition of a memory manager object.
  174967. */
  174968. typedef struct {
  174969. struct jpeg_memory_mgr pub; /* public fields */
  174970. /* Each pool identifier (lifetime class) names a linked list of pools. */
  174971. small_pool_ptr small_list[JPOOL_NUMPOOLS];
  174972. large_pool_ptr large_list[JPOOL_NUMPOOLS];
  174973. /* Since we only have one lifetime class of virtual arrays, only one
  174974. * linked list is necessary (for each datatype). Note that the virtual
  174975. * array control blocks being linked together are actually stored somewhere
  174976. * in the small-pool list.
  174977. */
  174978. jvirt_sarray_ptr virt_sarray_list;
  174979. jvirt_barray_ptr virt_barray_list;
  174980. /* This counts total space obtained from jpeg_get_small/large */
  174981. long total_space_allocated;
  174982. /* alloc_sarray and alloc_barray set this value for use by virtual
  174983. * array routines.
  174984. */
  174985. JDIMENSION last_rowsperchunk; /* from most recent alloc_sarray/barray */
  174986. } my_memory_mgr;
  174987. typedef my_memory_mgr * my_mem_ptr;
  174988. /*
  174989. * The control blocks for virtual arrays.
  174990. * Note that these blocks are allocated in the "small" pool area.
  174991. * System-dependent info for the associated backing store (if any) is hidden
  174992. * inside the backing_store_info struct.
  174993. */
  174994. struct jvirt_sarray_control {
  174995. JSAMPARRAY mem_buffer; /* => the in-memory buffer */
  174996. JDIMENSION rows_in_array; /* total virtual array height */
  174997. JDIMENSION samplesperrow; /* width of array (and of memory buffer) */
  174998. JDIMENSION maxaccess; /* max rows accessed by access_virt_sarray */
  174999. JDIMENSION rows_in_mem; /* height of memory buffer */
  175000. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  175001. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  175002. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  175003. boolean pre_zero; /* pre-zero mode requested? */
  175004. boolean dirty; /* do current buffer contents need written? */
  175005. boolean b_s_open; /* is backing-store data valid? */
  175006. jvirt_sarray_ptr next; /* link to next virtual sarray control block */
  175007. backing_store_info b_s_info; /* System-dependent control info */
  175008. };
  175009. struct jvirt_barray_control {
  175010. JBLOCKARRAY mem_buffer; /* => the in-memory buffer */
  175011. JDIMENSION rows_in_array; /* total virtual array height */
  175012. JDIMENSION blocksperrow; /* width of array (and of memory buffer) */
  175013. JDIMENSION maxaccess; /* max rows accessed by access_virt_barray */
  175014. JDIMENSION rows_in_mem; /* height of memory buffer */
  175015. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  175016. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  175017. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  175018. boolean pre_zero; /* pre-zero mode requested? */
  175019. boolean dirty; /* do current buffer contents need written? */
  175020. boolean b_s_open; /* is backing-store data valid? */
  175021. jvirt_barray_ptr next; /* link to next virtual barray control block */
  175022. backing_store_info b_s_info; /* System-dependent control info */
  175023. };
  175024. #ifdef MEM_STATS /* optional extra stuff for statistics */
  175025. LOCAL(void)
  175026. print_mem_stats (j_common_ptr cinfo, int pool_id)
  175027. {
  175028. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175029. small_pool_ptr shdr_ptr;
  175030. large_pool_ptr lhdr_ptr;
  175031. /* Since this is only a debugging stub, we can cheat a little by using
  175032. * fprintf directly rather than going through the trace message code.
  175033. * This is helpful because message parm array can't handle longs.
  175034. */
  175035. fprintf(stderr, "Freeing pool %d, total space = %ld\n",
  175036. pool_id, mem->total_space_allocated);
  175037. for (lhdr_ptr = mem->large_list[pool_id]; lhdr_ptr != NULL;
  175038. lhdr_ptr = lhdr_ptr->hdr.next) {
  175039. fprintf(stderr, " Large chunk used %ld\n",
  175040. (long) lhdr_ptr->hdr.bytes_used);
  175041. }
  175042. for (shdr_ptr = mem->small_list[pool_id]; shdr_ptr != NULL;
  175043. shdr_ptr = shdr_ptr->hdr.next) {
  175044. fprintf(stderr, " Small chunk used %ld free %ld\n",
  175045. (long) shdr_ptr->hdr.bytes_used,
  175046. (long) shdr_ptr->hdr.bytes_left);
  175047. }
  175048. }
  175049. #endif /* MEM_STATS */
  175050. LOCAL(void)
  175051. out_of_memory (j_common_ptr cinfo, int which)
  175052. /* Report an out-of-memory error and stop execution */
  175053. /* If we compiled MEM_STATS support, report alloc requests before dying */
  175054. {
  175055. #ifdef MEM_STATS
  175056. cinfo->err->trace_level = 2; /* force self_destruct to report stats */
  175057. #endif
  175058. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, which);
  175059. }
  175060. /*
  175061. * Allocation of "small" objects.
  175062. *
  175063. * For these, we use pooled storage. When a new pool must be created,
  175064. * we try to get enough space for the current request plus a "slop" factor,
  175065. * where the slop will be the amount of leftover space in the new pool.
  175066. * The speed vs. space tradeoff is largely determined by the slop values.
  175067. * A different slop value is provided for each pool class (lifetime),
  175068. * and we also distinguish the first pool of a class from later ones.
  175069. * NOTE: the values given work fairly well on both 16- and 32-bit-int
  175070. * machines, but may be too small if longs are 64 bits or more.
  175071. */
  175072. static const size_t first_pool_slop[JPOOL_NUMPOOLS] =
  175073. {
  175074. 1600, /* first PERMANENT pool */
  175075. 16000 /* first IMAGE pool */
  175076. };
  175077. static const size_t extra_pool_slop[JPOOL_NUMPOOLS] =
  175078. {
  175079. 0, /* additional PERMANENT pools */
  175080. 5000 /* additional IMAGE pools */
  175081. };
  175082. #define MIN_SLOP 50 /* greater than 0 to avoid futile looping */
  175083. METHODDEF(void *)
  175084. alloc_small (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  175085. /* Allocate a "small" object */
  175086. {
  175087. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175088. small_pool_ptr hdr_ptr, prev_hdr_ptr;
  175089. char * data_ptr;
  175090. size_t odd_bytes, min_request, slop;
  175091. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  175092. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(small_pool_hdr)))
  175093. out_of_memory(cinfo, 1); /* request exceeds malloc's ability */
  175094. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  175095. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  175096. if (odd_bytes > 0)
  175097. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  175098. /* See if space is available in any existing pool */
  175099. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  175100. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  175101. prev_hdr_ptr = NULL;
  175102. hdr_ptr = mem->small_list[pool_id];
  175103. while (hdr_ptr != NULL) {
  175104. if (hdr_ptr->hdr.bytes_left >= sizeofobject)
  175105. break; /* found pool with enough space */
  175106. prev_hdr_ptr = hdr_ptr;
  175107. hdr_ptr = hdr_ptr->hdr.next;
  175108. }
  175109. /* Time to make a new pool? */
  175110. if (hdr_ptr == NULL) {
  175111. /* min_request is what we need now, slop is what will be leftover */
  175112. min_request = sizeofobject + SIZEOF(small_pool_hdr);
  175113. if (prev_hdr_ptr == NULL) /* first pool in class? */
  175114. slop = first_pool_slop[pool_id];
  175115. else
  175116. slop = extra_pool_slop[pool_id];
  175117. /* Don't ask for more than MAX_ALLOC_CHUNK */
  175118. if (slop > (size_t) (MAX_ALLOC_CHUNK-min_request))
  175119. slop = (size_t) (MAX_ALLOC_CHUNK-min_request);
  175120. /* Try to get space, if fail reduce slop and try again */
  175121. for (;;) {
  175122. hdr_ptr = (small_pool_ptr) jpeg_get_small(cinfo, min_request + slop);
  175123. if (hdr_ptr != NULL)
  175124. break;
  175125. slop /= 2;
  175126. if (slop < MIN_SLOP) /* give up when it gets real small */
  175127. out_of_memory(cinfo, 2); /* jpeg_get_small failed */
  175128. }
  175129. mem->total_space_allocated += min_request + slop;
  175130. /* Success, initialize the new pool header and add to end of list */
  175131. hdr_ptr->hdr.next = NULL;
  175132. hdr_ptr->hdr.bytes_used = 0;
  175133. hdr_ptr->hdr.bytes_left = sizeofobject + slop;
  175134. if (prev_hdr_ptr == NULL) /* first pool in class? */
  175135. mem->small_list[pool_id] = hdr_ptr;
  175136. else
  175137. prev_hdr_ptr->hdr.next = hdr_ptr;
  175138. }
  175139. /* OK, allocate the object from the current pool */
  175140. data_ptr = (char *) (hdr_ptr + 1); /* point to first data byte in pool */
  175141. data_ptr += hdr_ptr->hdr.bytes_used; /* point to place for object */
  175142. hdr_ptr->hdr.bytes_used += sizeofobject;
  175143. hdr_ptr->hdr.bytes_left -= sizeofobject;
  175144. return (void *) data_ptr;
  175145. }
  175146. /*
  175147. * Allocation of "large" objects.
  175148. *
  175149. * The external semantics of these are the same as "small" objects,
  175150. * except that FAR pointers are used on 80x86. However the pool
  175151. * management heuristics are quite different. We assume that each
  175152. * request is large enough that it may as well be passed directly to
  175153. * jpeg_get_large; the pool management just links everything together
  175154. * so that we can free it all on demand.
  175155. * Note: the major use of "large" objects is in JSAMPARRAY and JBLOCKARRAY
  175156. * structures. The routines that create these structures (see below)
  175157. * deliberately bunch rows together to ensure a large request size.
  175158. */
  175159. METHODDEF(void FAR *)
  175160. alloc_large (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  175161. /* Allocate a "large" object */
  175162. {
  175163. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175164. large_pool_ptr hdr_ptr;
  175165. size_t odd_bytes;
  175166. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  175167. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)))
  175168. out_of_memory(cinfo, 3); /* request exceeds malloc's ability */
  175169. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  175170. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  175171. if (odd_bytes > 0)
  175172. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  175173. /* Always make a new pool */
  175174. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  175175. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  175176. hdr_ptr = (large_pool_ptr) jpeg_get_large(cinfo, sizeofobject +
  175177. SIZEOF(large_pool_hdr));
  175178. if (hdr_ptr == NULL)
  175179. out_of_memory(cinfo, 4); /* jpeg_get_large failed */
  175180. mem->total_space_allocated += sizeofobject + SIZEOF(large_pool_hdr);
  175181. /* Success, initialize the new pool header and add to list */
  175182. hdr_ptr->hdr.next = mem->large_list[pool_id];
  175183. /* We maintain space counts in each pool header for statistical purposes,
  175184. * even though they are not needed for allocation.
  175185. */
  175186. hdr_ptr->hdr.bytes_used = sizeofobject;
  175187. hdr_ptr->hdr.bytes_left = 0;
  175188. mem->large_list[pool_id] = hdr_ptr;
  175189. return (void FAR *) (hdr_ptr + 1); /* point to first data byte in pool */
  175190. }
  175191. /*
  175192. * Creation of 2-D sample arrays.
  175193. * The pointers are in near heap, the samples themselves in FAR heap.
  175194. *
  175195. * To minimize allocation overhead and to allow I/O of large contiguous
  175196. * blocks, we allocate the sample rows in groups of as many rows as possible
  175197. * without exceeding MAX_ALLOC_CHUNK total bytes per allocation request.
  175198. * NB: the virtual array control routines, later in this file, know about
  175199. * this chunking of rows. The rowsperchunk value is left in the mem manager
  175200. * object so that it can be saved away if this sarray is the workspace for
  175201. * a virtual array.
  175202. */
  175203. METHODDEF(JSAMPARRAY)
  175204. alloc_sarray (j_common_ptr cinfo, int pool_id,
  175205. JDIMENSION samplesperrow, JDIMENSION numrows)
  175206. /* Allocate a 2-D sample array */
  175207. {
  175208. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175209. JSAMPARRAY result;
  175210. JSAMPROW workspace;
  175211. JDIMENSION rowsperchunk, currow, i;
  175212. long ltemp;
  175213. /* Calculate max # of rows allowed in one allocation chunk */
  175214. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  175215. ((long) samplesperrow * SIZEOF(JSAMPLE));
  175216. if (ltemp <= 0)
  175217. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  175218. if (ltemp < (long) numrows)
  175219. rowsperchunk = (JDIMENSION) ltemp;
  175220. else
  175221. rowsperchunk = numrows;
  175222. mem->last_rowsperchunk = rowsperchunk;
  175223. /* Get space for row pointers (small object) */
  175224. result = (JSAMPARRAY) alloc_small(cinfo, pool_id,
  175225. (size_t) (numrows * SIZEOF(JSAMPROW)));
  175226. /* Get the rows themselves (large objects) */
  175227. currow = 0;
  175228. while (currow < numrows) {
  175229. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  175230. workspace = (JSAMPROW) alloc_large(cinfo, pool_id,
  175231. (size_t) ((size_t) rowsperchunk * (size_t) samplesperrow
  175232. * SIZEOF(JSAMPLE)));
  175233. for (i = rowsperchunk; i > 0; i--) {
  175234. result[currow++] = workspace;
  175235. workspace += samplesperrow;
  175236. }
  175237. }
  175238. return result;
  175239. }
  175240. /*
  175241. * Creation of 2-D coefficient-block arrays.
  175242. * This is essentially the same as the code for sample arrays, above.
  175243. */
  175244. METHODDEF(JBLOCKARRAY)
  175245. alloc_barray (j_common_ptr cinfo, int pool_id,
  175246. JDIMENSION blocksperrow, JDIMENSION numrows)
  175247. /* Allocate a 2-D coefficient-block array */
  175248. {
  175249. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175250. JBLOCKARRAY result;
  175251. JBLOCKROW workspace;
  175252. JDIMENSION rowsperchunk, currow, i;
  175253. long ltemp;
  175254. /* Calculate max # of rows allowed in one allocation chunk */
  175255. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  175256. ((long) blocksperrow * SIZEOF(JBLOCK));
  175257. if (ltemp <= 0)
  175258. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  175259. if (ltemp < (long) numrows)
  175260. rowsperchunk = (JDIMENSION) ltemp;
  175261. else
  175262. rowsperchunk = numrows;
  175263. mem->last_rowsperchunk = rowsperchunk;
  175264. /* Get space for row pointers (small object) */
  175265. result = (JBLOCKARRAY) alloc_small(cinfo, pool_id,
  175266. (size_t) (numrows * SIZEOF(JBLOCKROW)));
  175267. /* Get the rows themselves (large objects) */
  175268. currow = 0;
  175269. while (currow < numrows) {
  175270. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  175271. workspace = (JBLOCKROW) alloc_large(cinfo, pool_id,
  175272. (size_t) ((size_t) rowsperchunk * (size_t) blocksperrow
  175273. * SIZEOF(JBLOCK)));
  175274. for (i = rowsperchunk; i > 0; i--) {
  175275. result[currow++] = workspace;
  175276. workspace += blocksperrow;
  175277. }
  175278. }
  175279. return result;
  175280. }
  175281. /*
  175282. * About virtual array management:
  175283. *
  175284. * The above "normal" array routines are only used to allocate strip buffers
  175285. * (as wide as the image, but just a few rows high). Full-image-sized buffers
  175286. * are handled as "virtual" arrays. The array is still accessed a strip at a
  175287. * time, but the memory manager must save the whole array for repeated
  175288. * accesses. The intended implementation is that there is a strip buffer in
  175289. * memory (as high as is possible given the desired memory limit), plus a
  175290. * backing file that holds the rest of the array.
  175291. *
  175292. * The request_virt_array routines are told the total size of the image and
  175293. * the maximum number of rows that will be accessed at once. The in-memory
  175294. * buffer must be at least as large as the maxaccess value.
  175295. *
  175296. * The request routines create control blocks but not the in-memory buffers.
  175297. * That is postponed until realize_virt_arrays is called. At that time the
  175298. * total amount of space needed is known (approximately, anyway), so free
  175299. * memory can be divided up fairly.
  175300. *
  175301. * The access_virt_array routines are responsible for making a specific strip
  175302. * area accessible (after reading or writing the backing file, if necessary).
  175303. * Note that the access routines are told whether the caller intends to modify
  175304. * the accessed strip; during a read-only pass this saves having to rewrite
  175305. * data to disk. The access routines are also responsible for pre-zeroing
  175306. * any newly accessed rows, if pre-zeroing was requested.
  175307. *
  175308. * In current usage, the access requests are usually for nonoverlapping
  175309. * strips; that is, successive access start_row numbers differ by exactly
  175310. * num_rows = maxaccess. This means we can get good performance with simple
  175311. * buffer dump/reload logic, by making the in-memory buffer be a multiple
  175312. * of the access height; then there will never be accesses across bufferload
  175313. * boundaries. The code will still work with overlapping access requests,
  175314. * but it doesn't handle bufferload overlaps very efficiently.
  175315. */
  175316. METHODDEF(jvirt_sarray_ptr)
  175317. request_virt_sarray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  175318. JDIMENSION samplesperrow, JDIMENSION numrows,
  175319. JDIMENSION maxaccess)
  175320. /* Request a virtual 2-D sample array */
  175321. {
  175322. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175323. jvirt_sarray_ptr result;
  175324. /* Only IMAGE-lifetime virtual arrays are currently supported */
  175325. if (pool_id != JPOOL_IMAGE)
  175326. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  175327. /* get control block */
  175328. result = (jvirt_sarray_ptr) alloc_small(cinfo, pool_id,
  175329. SIZEOF(struct jvirt_sarray_control));
  175330. result->mem_buffer = NULL; /* marks array not yet realized */
  175331. result->rows_in_array = numrows;
  175332. result->samplesperrow = samplesperrow;
  175333. result->maxaccess = maxaccess;
  175334. result->pre_zero = pre_zero;
  175335. result->b_s_open = FALSE; /* no associated backing-store object */
  175336. result->next = mem->virt_sarray_list; /* add to list of virtual arrays */
  175337. mem->virt_sarray_list = result;
  175338. return result;
  175339. }
  175340. METHODDEF(jvirt_barray_ptr)
  175341. request_virt_barray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  175342. JDIMENSION blocksperrow, JDIMENSION numrows,
  175343. JDIMENSION maxaccess)
  175344. /* Request a virtual 2-D coefficient-block array */
  175345. {
  175346. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175347. jvirt_barray_ptr result;
  175348. /* Only IMAGE-lifetime virtual arrays are currently supported */
  175349. if (pool_id != JPOOL_IMAGE)
  175350. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  175351. /* get control block */
  175352. result = (jvirt_barray_ptr) alloc_small(cinfo, pool_id,
  175353. SIZEOF(struct jvirt_barray_control));
  175354. result->mem_buffer = NULL; /* marks array not yet realized */
  175355. result->rows_in_array = numrows;
  175356. result->blocksperrow = blocksperrow;
  175357. result->maxaccess = maxaccess;
  175358. result->pre_zero = pre_zero;
  175359. result->b_s_open = FALSE; /* no associated backing-store object */
  175360. result->next = mem->virt_barray_list; /* add to list of virtual arrays */
  175361. mem->virt_barray_list = result;
  175362. return result;
  175363. }
  175364. METHODDEF(void)
  175365. realize_virt_arrays (j_common_ptr cinfo)
  175366. /* Allocate the in-memory buffers for any unrealized virtual arrays */
  175367. {
  175368. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175369. long space_per_minheight, maximum_space, avail_mem;
  175370. long minheights, max_minheights;
  175371. jvirt_sarray_ptr sptr;
  175372. jvirt_barray_ptr bptr;
  175373. /* Compute the minimum space needed (maxaccess rows in each buffer)
  175374. * and the maximum space needed (full image height in each buffer).
  175375. * These may be of use to the system-dependent jpeg_mem_available routine.
  175376. */
  175377. space_per_minheight = 0;
  175378. maximum_space = 0;
  175379. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  175380. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  175381. space_per_minheight += (long) sptr->maxaccess *
  175382. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  175383. maximum_space += (long) sptr->rows_in_array *
  175384. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  175385. }
  175386. }
  175387. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  175388. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  175389. space_per_minheight += (long) bptr->maxaccess *
  175390. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  175391. maximum_space += (long) bptr->rows_in_array *
  175392. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  175393. }
  175394. }
  175395. if (space_per_minheight <= 0)
  175396. return; /* no unrealized arrays, no work */
  175397. /* Determine amount of memory to actually use; this is system-dependent. */
  175398. avail_mem = jpeg_mem_available(cinfo, space_per_minheight, maximum_space,
  175399. mem->total_space_allocated);
  175400. /* If the maximum space needed is available, make all the buffers full
  175401. * height; otherwise parcel it out with the same number of minheights
  175402. * in each buffer.
  175403. */
  175404. if (avail_mem >= maximum_space)
  175405. max_minheights = 1000000000L;
  175406. else {
  175407. max_minheights = avail_mem / space_per_minheight;
  175408. /* If there doesn't seem to be enough space, try to get the minimum
  175409. * anyway. This allows a "stub" implementation of jpeg_mem_available().
  175410. */
  175411. if (max_minheights <= 0)
  175412. max_minheights = 1;
  175413. }
  175414. /* Allocate the in-memory buffers and initialize backing store as needed. */
  175415. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  175416. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  175417. minheights = ((long) sptr->rows_in_array - 1L) / sptr->maxaccess + 1L;
  175418. if (minheights <= max_minheights) {
  175419. /* This buffer fits in memory */
  175420. sptr->rows_in_mem = sptr->rows_in_array;
  175421. } else {
  175422. /* It doesn't fit in memory, create backing store. */
  175423. sptr->rows_in_mem = (JDIMENSION) (max_minheights * sptr->maxaccess);
  175424. jpeg_open_backing_store(cinfo, & sptr->b_s_info,
  175425. (long) sptr->rows_in_array *
  175426. (long) sptr->samplesperrow *
  175427. (long) SIZEOF(JSAMPLE));
  175428. sptr->b_s_open = TRUE;
  175429. }
  175430. sptr->mem_buffer = alloc_sarray(cinfo, JPOOL_IMAGE,
  175431. sptr->samplesperrow, sptr->rows_in_mem);
  175432. sptr->rowsperchunk = mem->last_rowsperchunk;
  175433. sptr->cur_start_row = 0;
  175434. sptr->first_undef_row = 0;
  175435. sptr->dirty = FALSE;
  175436. }
  175437. }
  175438. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  175439. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  175440. minheights = ((long) bptr->rows_in_array - 1L) / bptr->maxaccess + 1L;
  175441. if (minheights <= max_minheights) {
  175442. /* This buffer fits in memory */
  175443. bptr->rows_in_mem = bptr->rows_in_array;
  175444. } else {
  175445. /* It doesn't fit in memory, create backing store. */
  175446. bptr->rows_in_mem = (JDIMENSION) (max_minheights * bptr->maxaccess);
  175447. jpeg_open_backing_store(cinfo, & bptr->b_s_info,
  175448. (long) bptr->rows_in_array *
  175449. (long) bptr->blocksperrow *
  175450. (long) SIZEOF(JBLOCK));
  175451. bptr->b_s_open = TRUE;
  175452. }
  175453. bptr->mem_buffer = alloc_barray(cinfo, JPOOL_IMAGE,
  175454. bptr->blocksperrow, bptr->rows_in_mem);
  175455. bptr->rowsperchunk = mem->last_rowsperchunk;
  175456. bptr->cur_start_row = 0;
  175457. bptr->first_undef_row = 0;
  175458. bptr->dirty = FALSE;
  175459. }
  175460. }
  175461. }
  175462. LOCAL(void)
  175463. do_sarray_io (j_common_ptr cinfo, jvirt_sarray_ptr ptr, boolean writing)
  175464. /* Do backing store read or write of a virtual sample array */
  175465. {
  175466. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  175467. bytesperrow = (long) ptr->samplesperrow * SIZEOF(JSAMPLE);
  175468. file_offset = ptr->cur_start_row * bytesperrow;
  175469. /* Loop to read or write each allocation chunk in mem_buffer */
  175470. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  175471. /* One chunk, but check for short chunk at end of buffer */
  175472. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  175473. /* Transfer no more than is currently defined */
  175474. thisrow = (long) ptr->cur_start_row + i;
  175475. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  175476. /* Transfer no more than fits in file */
  175477. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  175478. if (rows <= 0) /* this chunk might be past end of file! */
  175479. break;
  175480. byte_count = rows * bytesperrow;
  175481. if (writing)
  175482. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  175483. (void FAR *) ptr->mem_buffer[i],
  175484. file_offset, byte_count);
  175485. else
  175486. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  175487. (void FAR *) ptr->mem_buffer[i],
  175488. file_offset, byte_count);
  175489. file_offset += byte_count;
  175490. }
  175491. }
  175492. LOCAL(void)
  175493. do_barray_io (j_common_ptr cinfo, jvirt_barray_ptr ptr, boolean writing)
  175494. /* Do backing store read or write of a virtual coefficient-block array */
  175495. {
  175496. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  175497. bytesperrow = (long) ptr->blocksperrow * SIZEOF(JBLOCK);
  175498. file_offset = ptr->cur_start_row * bytesperrow;
  175499. /* Loop to read or write each allocation chunk in mem_buffer */
  175500. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  175501. /* One chunk, but check for short chunk at end of buffer */
  175502. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  175503. /* Transfer no more than is currently defined */
  175504. thisrow = (long) ptr->cur_start_row + i;
  175505. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  175506. /* Transfer no more than fits in file */
  175507. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  175508. if (rows <= 0) /* this chunk might be past end of file! */
  175509. break;
  175510. byte_count = rows * bytesperrow;
  175511. if (writing)
  175512. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  175513. (void FAR *) ptr->mem_buffer[i],
  175514. file_offset, byte_count);
  175515. else
  175516. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  175517. (void FAR *) ptr->mem_buffer[i],
  175518. file_offset, byte_count);
  175519. file_offset += byte_count;
  175520. }
  175521. }
  175522. METHODDEF(JSAMPARRAY)
  175523. access_virt_sarray (j_common_ptr cinfo, jvirt_sarray_ptr ptr,
  175524. JDIMENSION start_row, JDIMENSION num_rows,
  175525. boolean writable)
  175526. /* Access the part of a virtual sample array starting at start_row */
  175527. /* and extending for num_rows rows. writable is true if */
  175528. /* caller intends to modify the accessed area. */
  175529. {
  175530. JDIMENSION end_row = start_row + num_rows;
  175531. JDIMENSION undef_row;
  175532. /* debugging check */
  175533. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  175534. ptr->mem_buffer == NULL)
  175535. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  175536. /* Make the desired part of the virtual array accessible */
  175537. if (start_row < ptr->cur_start_row ||
  175538. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  175539. if (! ptr->b_s_open)
  175540. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  175541. /* Flush old buffer contents if necessary */
  175542. if (ptr->dirty) {
  175543. do_sarray_io(cinfo, ptr, TRUE);
  175544. ptr->dirty = FALSE;
  175545. }
  175546. /* Decide what part of virtual array to access.
  175547. * Algorithm: if target address > current window, assume forward scan,
  175548. * load starting at target address. If target address < current window,
  175549. * assume backward scan, load so that target area is top of window.
  175550. * Note that when switching from forward write to forward read, will have
  175551. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  175552. */
  175553. if (start_row > ptr->cur_start_row) {
  175554. ptr->cur_start_row = start_row;
  175555. } else {
  175556. /* use long arithmetic here to avoid overflow & unsigned problems */
  175557. long ltemp;
  175558. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  175559. if (ltemp < 0)
  175560. ltemp = 0; /* don't fall off front end of file */
  175561. ptr->cur_start_row = (JDIMENSION) ltemp;
  175562. }
  175563. /* Read in the selected part of the array.
  175564. * During the initial write pass, we will do no actual read
  175565. * because the selected part is all undefined.
  175566. */
  175567. do_sarray_io(cinfo, ptr, FALSE);
  175568. }
  175569. /* Ensure the accessed part of the array is defined; prezero if needed.
  175570. * To improve locality of access, we only prezero the part of the array
  175571. * that the caller is about to access, not the entire in-memory array.
  175572. */
  175573. if (ptr->first_undef_row < end_row) {
  175574. if (ptr->first_undef_row < start_row) {
  175575. if (writable) /* writer skipped over a section of array */
  175576. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  175577. undef_row = start_row; /* but reader is allowed to read ahead */
  175578. } else {
  175579. undef_row = ptr->first_undef_row;
  175580. }
  175581. if (writable)
  175582. ptr->first_undef_row = end_row;
  175583. if (ptr->pre_zero) {
  175584. size_t bytesperrow = (size_t) ptr->samplesperrow * SIZEOF(JSAMPLE);
  175585. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  175586. end_row -= ptr->cur_start_row;
  175587. while (undef_row < end_row) {
  175588. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  175589. undef_row++;
  175590. }
  175591. } else {
  175592. if (! writable) /* reader looking at undefined data */
  175593. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  175594. }
  175595. }
  175596. /* Flag the buffer dirty if caller will write in it */
  175597. if (writable)
  175598. ptr->dirty = TRUE;
  175599. /* Return address of proper part of the buffer */
  175600. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  175601. }
  175602. METHODDEF(JBLOCKARRAY)
  175603. access_virt_barray (j_common_ptr cinfo, jvirt_barray_ptr ptr,
  175604. JDIMENSION start_row, JDIMENSION num_rows,
  175605. boolean writable)
  175606. /* Access the part of a virtual block array starting at start_row */
  175607. /* and extending for num_rows rows. writable is true if */
  175608. /* caller intends to modify the accessed area. */
  175609. {
  175610. JDIMENSION end_row = start_row + num_rows;
  175611. JDIMENSION undef_row;
  175612. /* debugging check */
  175613. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  175614. ptr->mem_buffer == NULL)
  175615. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  175616. /* Make the desired part of the virtual array accessible */
  175617. if (start_row < ptr->cur_start_row ||
  175618. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  175619. if (! ptr->b_s_open)
  175620. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  175621. /* Flush old buffer contents if necessary */
  175622. if (ptr->dirty) {
  175623. do_barray_io(cinfo, ptr, TRUE);
  175624. ptr->dirty = FALSE;
  175625. }
  175626. /* Decide what part of virtual array to access.
  175627. * Algorithm: if target address > current window, assume forward scan,
  175628. * load starting at target address. If target address < current window,
  175629. * assume backward scan, load so that target area is top of window.
  175630. * Note that when switching from forward write to forward read, will have
  175631. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  175632. */
  175633. if (start_row > ptr->cur_start_row) {
  175634. ptr->cur_start_row = start_row;
  175635. } else {
  175636. /* use long arithmetic here to avoid overflow & unsigned problems */
  175637. long ltemp;
  175638. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  175639. if (ltemp < 0)
  175640. ltemp = 0; /* don't fall off front end of file */
  175641. ptr->cur_start_row = (JDIMENSION) ltemp;
  175642. }
  175643. /* Read in the selected part of the array.
  175644. * During the initial write pass, we will do no actual read
  175645. * because the selected part is all undefined.
  175646. */
  175647. do_barray_io(cinfo, ptr, FALSE);
  175648. }
  175649. /* Ensure the accessed part of the array is defined; prezero if needed.
  175650. * To improve locality of access, we only prezero the part of the array
  175651. * that the caller is about to access, not the entire in-memory array.
  175652. */
  175653. if (ptr->first_undef_row < end_row) {
  175654. if (ptr->first_undef_row < start_row) {
  175655. if (writable) /* writer skipped over a section of array */
  175656. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  175657. undef_row = start_row; /* but reader is allowed to read ahead */
  175658. } else {
  175659. undef_row = ptr->first_undef_row;
  175660. }
  175661. if (writable)
  175662. ptr->first_undef_row = end_row;
  175663. if (ptr->pre_zero) {
  175664. size_t bytesperrow = (size_t) ptr->blocksperrow * SIZEOF(JBLOCK);
  175665. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  175666. end_row -= ptr->cur_start_row;
  175667. while (undef_row < end_row) {
  175668. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  175669. undef_row++;
  175670. }
  175671. } else {
  175672. if (! writable) /* reader looking at undefined data */
  175673. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  175674. }
  175675. }
  175676. /* Flag the buffer dirty if caller will write in it */
  175677. if (writable)
  175678. ptr->dirty = TRUE;
  175679. /* Return address of proper part of the buffer */
  175680. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  175681. }
  175682. /*
  175683. * Release all objects belonging to a specified pool.
  175684. */
  175685. METHODDEF(void)
  175686. free_pool (j_common_ptr cinfo, int pool_id)
  175687. {
  175688. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175689. small_pool_ptr shdr_ptr;
  175690. large_pool_ptr lhdr_ptr;
  175691. size_t space_freed;
  175692. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  175693. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  175694. #ifdef MEM_STATS
  175695. if (cinfo->err->trace_level > 1)
  175696. print_mem_stats(cinfo, pool_id); /* print pool's memory usage statistics */
  175697. #endif
  175698. /* If freeing IMAGE pool, close any virtual arrays first */
  175699. if (pool_id == JPOOL_IMAGE) {
  175700. jvirt_sarray_ptr sptr;
  175701. jvirt_barray_ptr bptr;
  175702. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  175703. if (sptr->b_s_open) { /* there may be no backing store */
  175704. sptr->b_s_open = FALSE; /* prevent recursive close if error */
  175705. (*sptr->b_s_info.close_backing_store) (cinfo, & sptr->b_s_info);
  175706. }
  175707. }
  175708. mem->virt_sarray_list = NULL;
  175709. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  175710. if (bptr->b_s_open) { /* there may be no backing store */
  175711. bptr->b_s_open = FALSE; /* prevent recursive close if error */
  175712. (*bptr->b_s_info.close_backing_store) (cinfo, & bptr->b_s_info);
  175713. }
  175714. }
  175715. mem->virt_barray_list = NULL;
  175716. }
  175717. /* Release large objects */
  175718. lhdr_ptr = mem->large_list[pool_id];
  175719. mem->large_list[pool_id] = NULL;
  175720. while (lhdr_ptr != NULL) {
  175721. large_pool_ptr next_lhdr_ptr = lhdr_ptr->hdr.next;
  175722. space_freed = lhdr_ptr->hdr.bytes_used +
  175723. lhdr_ptr->hdr.bytes_left +
  175724. SIZEOF(large_pool_hdr);
  175725. jpeg_free_large(cinfo, (void FAR *) lhdr_ptr, space_freed);
  175726. mem->total_space_allocated -= space_freed;
  175727. lhdr_ptr = next_lhdr_ptr;
  175728. }
  175729. /* Release small objects */
  175730. shdr_ptr = mem->small_list[pool_id];
  175731. mem->small_list[pool_id] = NULL;
  175732. while (shdr_ptr != NULL) {
  175733. small_pool_ptr next_shdr_ptr = shdr_ptr->hdr.next;
  175734. space_freed = shdr_ptr->hdr.bytes_used +
  175735. shdr_ptr->hdr.bytes_left +
  175736. SIZEOF(small_pool_hdr);
  175737. jpeg_free_small(cinfo, (void *) shdr_ptr, space_freed);
  175738. mem->total_space_allocated -= space_freed;
  175739. shdr_ptr = next_shdr_ptr;
  175740. }
  175741. }
  175742. /*
  175743. * Close up shop entirely.
  175744. * Note that this cannot be called unless cinfo->mem is non-NULL.
  175745. */
  175746. METHODDEF(void)
  175747. self_destruct (j_common_ptr cinfo)
  175748. {
  175749. int pool;
  175750. /* Close all backing store, release all memory.
  175751. * Releasing pools in reverse order might help avoid fragmentation
  175752. * with some (brain-damaged) malloc libraries.
  175753. */
  175754. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  175755. free_pool(cinfo, pool);
  175756. }
  175757. /* Release the memory manager control block too. */
  175758. jpeg_free_small(cinfo, (void *) cinfo->mem, SIZEOF(my_memory_mgr));
  175759. cinfo->mem = NULL; /* ensures I will be called only once */
  175760. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  175761. }
  175762. /*
  175763. * Memory manager initialization.
  175764. * When this is called, only the error manager pointer is valid in cinfo!
  175765. */
  175766. GLOBAL(void)
  175767. jinit_memory_mgr (j_common_ptr cinfo)
  175768. {
  175769. my_mem_ptr mem;
  175770. long max_to_use;
  175771. int pool;
  175772. size_t test_mac;
  175773. cinfo->mem = NULL; /* for safety if init fails */
  175774. /* Check for configuration errors.
  175775. * SIZEOF(ALIGN_TYPE) should be a power of 2; otherwise, it probably
  175776. * doesn't reflect any real hardware alignment requirement.
  175777. * The test is a little tricky: for X>0, X and X-1 have no one-bits
  175778. * in common if and only if X is a power of 2, ie has only one one-bit.
  175779. * Some compilers may give an "unreachable code" warning here; ignore it.
  175780. */
  175781. if ((SIZEOF(ALIGN_TYPE) & (SIZEOF(ALIGN_TYPE)-1)) != 0)
  175782. ERREXIT(cinfo, JERR_BAD_ALIGN_TYPE);
  175783. /* MAX_ALLOC_CHUNK must be representable as type size_t, and must be
  175784. * a multiple of SIZEOF(ALIGN_TYPE).
  175785. * Again, an "unreachable code" warning may be ignored here.
  175786. * But a "constant too large" warning means you need to fix MAX_ALLOC_CHUNK.
  175787. */
  175788. test_mac = (size_t) MAX_ALLOC_CHUNK;
  175789. if ((long) test_mac != MAX_ALLOC_CHUNK ||
  175790. (MAX_ALLOC_CHUNK % SIZEOF(ALIGN_TYPE)) != 0)
  175791. ERREXIT(cinfo, JERR_BAD_ALLOC_CHUNK);
  175792. max_to_use = jpeg_mem_init(cinfo); /* system-dependent initialization */
  175793. /* Attempt to allocate memory manager's control block */
  175794. mem = (my_mem_ptr) jpeg_get_small(cinfo, SIZEOF(my_memory_mgr));
  175795. if (mem == NULL) {
  175796. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  175797. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 0);
  175798. }
  175799. /* OK, fill in the method pointers */
  175800. mem->pub.alloc_small = alloc_small;
  175801. mem->pub.alloc_large = alloc_large;
  175802. mem->pub.alloc_sarray = alloc_sarray;
  175803. mem->pub.alloc_barray = alloc_barray;
  175804. mem->pub.request_virt_sarray = request_virt_sarray;
  175805. mem->pub.request_virt_barray = request_virt_barray;
  175806. mem->pub.realize_virt_arrays = realize_virt_arrays;
  175807. mem->pub.access_virt_sarray = access_virt_sarray;
  175808. mem->pub.access_virt_barray = access_virt_barray;
  175809. mem->pub.free_pool = free_pool;
  175810. mem->pub.self_destruct = self_destruct;
  175811. /* Make MAX_ALLOC_CHUNK accessible to other modules */
  175812. mem->pub.max_alloc_chunk = MAX_ALLOC_CHUNK;
  175813. /* Initialize working state */
  175814. mem->pub.max_memory_to_use = max_to_use;
  175815. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  175816. mem->small_list[pool] = NULL;
  175817. mem->large_list[pool] = NULL;
  175818. }
  175819. mem->virt_sarray_list = NULL;
  175820. mem->virt_barray_list = NULL;
  175821. mem->total_space_allocated = SIZEOF(my_memory_mgr);
  175822. /* Declare ourselves open for business */
  175823. cinfo->mem = & mem->pub;
  175824. /* Check for an environment variable JPEGMEM; if found, override the
  175825. * default max_memory setting from jpeg_mem_init. Note that the
  175826. * surrounding application may again override this value.
  175827. * If your system doesn't support getenv(), define NO_GETENV to disable
  175828. * this feature.
  175829. */
  175830. #ifndef NO_GETENV
  175831. { char * memenv;
  175832. if ((memenv = getenv("JPEGMEM")) != NULL) {
  175833. char ch = 'x';
  175834. if (sscanf(memenv, "%ld%c", &max_to_use, &ch) > 0) {
  175835. if (ch == 'm' || ch == 'M')
  175836. max_to_use *= 1000L;
  175837. mem->pub.max_memory_to_use = max_to_use * 1000L;
  175838. }
  175839. }
  175840. }
  175841. #endif
  175842. }
  175843. /*** End of inlined file: jmemmgr.c ***/
  175844. /*** Start of inlined file: jmemnobs.c ***/
  175845. #define JPEG_INTERNALS
  175846. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare malloc(),free() */
  175847. extern void * malloc JPP((size_t size));
  175848. extern void free JPP((void *ptr));
  175849. #endif
  175850. /*
  175851. * Memory allocation and freeing are controlled by the regular library
  175852. * routines malloc() and free().
  175853. */
  175854. GLOBAL(void *)
  175855. jpeg_get_small (j_common_ptr , size_t sizeofobject)
  175856. {
  175857. return (void *) malloc(sizeofobject);
  175858. }
  175859. GLOBAL(void)
  175860. jpeg_free_small (j_common_ptr , void * object, size_t)
  175861. {
  175862. free(object);
  175863. }
  175864. /*
  175865. * "Large" objects are treated the same as "small" ones.
  175866. * NB: although we include FAR keywords in the routine declarations,
  175867. * this file won't actually work in 80x86 small/medium model; at least,
  175868. * you probably won't be able to process useful-size images in only 64KB.
  175869. */
  175870. GLOBAL(void FAR *)
  175871. jpeg_get_large (j_common_ptr, size_t sizeofobject)
  175872. {
  175873. return (void FAR *) malloc(sizeofobject);
  175874. }
  175875. GLOBAL(void)
  175876. jpeg_free_large (j_common_ptr, void FAR * object, size_t)
  175877. {
  175878. free(object);
  175879. }
  175880. /*
  175881. * This routine computes the total memory space available for allocation.
  175882. * Here we always say, "we got all you want bud!"
  175883. */
  175884. GLOBAL(long)
  175885. jpeg_mem_available (j_common_ptr, long,
  175886. long max_bytes_needed, long)
  175887. {
  175888. return max_bytes_needed;
  175889. }
  175890. /*
  175891. * Backing store (temporary file) management.
  175892. * Since jpeg_mem_available always promised the moon,
  175893. * this should never be called and we can just error out.
  175894. */
  175895. GLOBAL(void)
  175896. jpeg_open_backing_store (j_common_ptr cinfo, struct backing_store_struct *,
  175897. long )
  175898. {
  175899. ERREXIT(cinfo, JERR_NO_BACKING_STORE);
  175900. }
  175901. /*
  175902. * These routines take care of any system-dependent initialization and
  175903. * cleanup required. Here, there isn't any.
  175904. */
  175905. GLOBAL(long)
  175906. jpeg_mem_init (j_common_ptr)
  175907. {
  175908. return 0; /* just set max_memory_to_use to 0 */
  175909. }
  175910. GLOBAL(void)
  175911. jpeg_mem_term (j_common_ptr)
  175912. {
  175913. /* no work */
  175914. }
  175915. /*** End of inlined file: jmemnobs.c ***/
  175916. /*** Start of inlined file: jquant1.c ***/
  175917. #define JPEG_INTERNALS
  175918. #ifdef QUANT_1PASS_SUPPORTED
  175919. /*
  175920. * The main purpose of 1-pass quantization is to provide a fast, if not very
  175921. * high quality, colormapped output capability. A 2-pass quantizer usually
  175922. * gives better visual quality; however, for quantized grayscale output this
  175923. * quantizer is perfectly adequate. Dithering is highly recommended with this
  175924. * quantizer, though you can turn it off if you really want to.
  175925. *
  175926. * In 1-pass quantization the colormap must be chosen in advance of seeing the
  175927. * image. We use a map consisting of all combinations of Ncolors[i] color
  175928. * values for the i'th component. The Ncolors[] values are chosen so that
  175929. * their product, the total number of colors, is no more than that requested.
  175930. * (In most cases, the product will be somewhat less.)
  175931. *
  175932. * Since the colormap is orthogonal, the representative value for each color
  175933. * component can be determined without considering the other components;
  175934. * then these indexes can be combined into a colormap index by a standard
  175935. * N-dimensional-array-subscript calculation. Most of the arithmetic involved
  175936. * can be precalculated and stored in the lookup table colorindex[].
  175937. * colorindex[i][j] maps pixel value j in component i to the nearest
  175938. * representative value (grid plane) for that component; this index is
  175939. * multiplied by the array stride for component i, so that the
  175940. * index of the colormap entry closest to a given pixel value is just
  175941. * sum( colorindex[component-number][pixel-component-value] )
  175942. * Aside from being fast, this scheme allows for variable spacing between
  175943. * representative values with no additional lookup cost.
  175944. *
  175945. * If gamma correction has been applied in color conversion, it might be wise
  175946. * to adjust the color grid spacing so that the representative colors are
  175947. * equidistant in linear space. At this writing, gamma correction is not
  175948. * implemented by jdcolor, so nothing is done here.
  175949. */
  175950. /* Declarations for ordered dithering.
  175951. *
  175952. * We use a standard 16x16 ordered dither array. The basic concept of ordered
  175953. * dithering is described in many references, for instance Dale Schumacher's
  175954. * chapter II.2 of Graphics Gems II (James Arvo, ed. Academic Press, 1991).
  175955. * In place of Schumacher's comparisons against a "threshold" value, we add a
  175956. * "dither" value to the input pixel and then round the result to the nearest
  175957. * output value. The dither value is equivalent to (0.5 - threshold) times
  175958. * the distance between output values. For ordered dithering, we assume that
  175959. * the output colors are equally spaced; if not, results will probably be
  175960. * worse, since the dither may be too much or too little at a given point.
  175961. *
  175962. * The normal calculation would be to form pixel value + dither, range-limit
  175963. * this to 0..MAXJSAMPLE, and then index into the colorindex table as usual.
  175964. * We can skip the separate range-limiting step by extending the colorindex
  175965. * table in both directions.
  175966. */
  175967. #define ODITHER_SIZE 16 /* dimension of dither matrix */
  175968. /* NB: if ODITHER_SIZE is not a power of 2, ODITHER_MASK uses will break */
  175969. #define ODITHER_CELLS (ODITHER_SIZE*ODITHER_SIZE) /* # cells in matrix */
  175970. #define ODITHER_MASK (ODITHER_SIZE-1) /* mask for wrapping around counters */
  175971. typedef int ODITHER_MATRIX[ODITHER_SIZE][ODITHER_SIZE];
  175972. typedef int (*ODITHER_MATRIX_PTR)[ODITHER_SIZE];
  175973. static const UINT8 base_dither_matrix[ODITHER_SIZE][ODITHER_SIZE] = {
  175974. /* Bayer's order-4 dither array. Generated by the code given in
  175975. * Stephen Hawley's article "Ordered Dithering" in Graphics Gems I.
  175976. * The values in this array must range from 0 to ODITHER_CELLS-1.
  175977. */
  175978. { 0,192, 48,240, 12,204, 60,252, 3,195, 51,243, 15,207, 63,255 },
  175979. { 128, 64,176,112,140, 76,188,124,131, 67,179,115,143, 79,191,127 },
  175980. { 32,224, 16,208, 44,236, 28,220, 35,227, 19,211, 47,239, 31,223 },
  175981. { 160, 96,144, 80,172,108,156, 92,163, 99,147, 83,175,111,159, 95 },
  175982. { 8,200, 56,248, 4,196, 52,244, 11,203, 59,251, 7,199, 55,247 },
  175983. { 136, 72,184,120,132, 68,180,116,139, 75,187,123,135, 71,183,119 },
  175984. { 40,232, 24,216, 36,228, 20,212, 43,235, 27,219, 39,231, 23,215 },
  175985. { 168,104,152, 88,164,100,148, 84,171,107,155, 91,167,103,151, 87 },
  175986. { 2,194, 50,242, 14,206, 62,254, 1,193, 49,241, 13,205, 61,253 },
  175987. { 130, 66,178,114,142, 78,190,126,129, 65,177,113,141, 77,189,125 },
  175988. { 34,226, 18,210, 46,238, 30,222, 33,225, 17,209, 45,237, 29,221 },
  175989. { 162, 98,146, 82,174,110,158, 94,161, 97,145, 81,173,109,157, 93 },
  175990. { 10,202, 58,250, 6,198, 54,246, 9,201, 57,249, 5,197, 53,245 },
  175991. { 138, 74,186,122,134, 70,182,118,137, 73,185,121,133, 69,181,117 },
  175992. { 42,234, 26,218, 38,230, 22,214, 41,233, 25,217, 37,229, 21,213 },
  175993. { 170,106,154, 90,166,102,150, 86,169,105,153, 89,165,101,149, 85 }
  175994. };
  175995. /* Declarations for Floyd-Steinberg dithering.
  175996. *
  175997. * Errors are accumulated into the array fserrors[], at a resolution of
  175998. * 1/16th of a pixel count. The error at a given pixel is propagated
  175999. * to its not-yet-processed neighbors using the standard F-S fractions,
  176000. * ... (here) 7/16
  176001. * 3/16 5/16 1/16
  176002. * We work left-to-right on even rows, right-to-left on odd rows.
  176003. *
  176004. * We can get away with a single array (holding one row's worth of errors)
  176005. * by using it to store the current row's errors at pixel columns not yet
  176006. * processed, but the next row's errors at columns already processed. We
  176007. * need only a few extra variables to hold the errors immediately around the
  176008. * current column. (If we are lucky, those variables are in registers, but
  176009. * even if not, they're probably cheaper to access than array elements are.)
  176010. *
  176011. * The fserrors[] array is indexed [component#][position].
  176012. * We provide (#columns + 2) entries per component; the extra entry at each
  176013. * end saves us from special-casing the first and last pixels.
  176014. *
  176015. * Note: on a wide image, we might not have enough room in a PC's near data
  176016. * segment to hold the error array; so it is allocated with alloc_large.
  176017. */
  176018. #if BITS_IN_JSAMPLE == 8
  176019. typedef INT16 FSERROR; /* 16 bits should be enough */
  176020. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  176021. #else
  176022. typedef INT32 FSERROR; /* may need more than 16 bits */
  176023. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  176024. #endif
  176025. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  176026. /* Private subobject */
  176027. #define MAX_Q_COMPS 4 /* max components I can handle */
  176028. typedef struct {
  176029. struct jpeg_color_quantizer pub; /* public fields */
  176030. /* Initially allocated colormap is saved here */
  176031. JSAMPARRAY sv_colormap; /* The color map as a 2-D pixel array */
  176032. int sv_actual; /* number of entries in use */
  176033. JSAMPARRAY colorindex; /* Precomputed mapping for speed */
  176034. /* colorindex[i][j] = index of color closest to pixel value j in component i,
  176035. * premultiplied as described above. Since colormap indexes must fit into
  176036. * JSAMPLEs, the entries of this array will too.
  176037. */
  176038. boolean is_padded; /* is the colorindex padded for odither? */
  176039. int Ncolors[MAX_Q_COMPS]; /* # of values alloced to each component */
  176040. /* Variables for ordered dithering */
  176041. int row_index; /* cur row's vertical index in dither matrix */
  176042. ODITHER_MATRIX_PTR odither[MAX_Q_COMPS]; /* one dither array per component */
  176043. /* Variables for Floyd-Steinberg dithering */
  176044. FSERRPTR fserrors[MAX_Q_COMPS]; /* accumulated errors */
  176045. boolean on_odd_row; /* flag to remember which row we are on */
  176046. } my_cquantizer;
  176047. typedef my_cquantizer * my_cquantize_ptr;
  176048. /*
  176049. * Policy-making subroutines for create_colormap and create_colorindex.
  176050. * These routines determine the colormap to be used. The rest of the module
  176051. * only assumes that the colormap is orthogonal.
  176052. *
  176053. * * select_ncolors decides how to divvy up the available colors
  176054. * among the components.
  176055. * * output_value defines the set of representative values for a component.
  176056. * * largest_input_value defines the mapping from input values to
  176057. * representative values for a component.
  176058. * Note that the latter two routines may impose different policies for
  176059. * different components, though this is not currently done.
  176060. */
  176061. LOCAL(int)
  176062. select_ncolors (j_decompress_ptr cinfo, int Ncolors[])
  176063. /* Determine allocation of desired colors to components, */
  176064. /* and fill in Ncolors[] array to indicate choice. */
  176065. /* Return value is total number of colors (product of Ncolors[] values). */
  176066. {
  176067. int nc = cinfo->out_color_components; /* number of color components */
  176068. int max_colors = cinfo->desired_number_of_colors;
  176069. int total_colors, iroot, i, j;
  176070. boolean changed;
  176071. long temp;
  176072. static const int RGB_order[3] = { RGB_GREEN, RGB_RED, RGB_BLUE };
  176073. /* We can allocate at least the nc'th root of max_colors per component. */
  176074. /* Compute floor(nc'th root of max_colors). */
  176075. iroot = 1;
  176076. do {
  176077. iroot++;
  176078. temp = iroot; /* set temp = iroot ** nc */
  176079. for (i = 1; i < nc; i++)
  176080. temp *= iroot;
  176081. } while (temp <= (long) max_colors); /* repeat till iroot exceeds root */
  176082. iroot--; /* now iroot = floor(root) */
  176083. /* Must have at least 2 color values per component */
  176084. if (iroot < 2)
  176085. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, (int) temp);
  176086. /* Initialize to iroot color values for each component */
  176087. total_colors = 1;
  176088. for (i = 0; i < nc; i++) {
  176089. Ncolors[i] = iroot;
  176090. total_colors *= iroot;
  176091. }
  176092. /* We may be able to increment the count for one or more components without
  176093. * exceeding max_colors, though we know not all can be incremented.
  176094. * Sometimes, the first component can be incremented more than once!
  176095. * (Example: for 16 colors, we start at 2*2*2, go to 3*2*2, then 4*2*2.)
  176096. * In RGB colorspace, try to increment G first, then R, then B.
  176097. */
  176098. do {
  176099. changed = FALSE;
  176100. for (i = 0; i < nc; i++) {
  176101. j = (cinfo->out_color_space == JCS_RGB ? RGB_order[i] : i);
  176102. /* calculate new total_colors if Ncolors[j] is incremented */
  176103. temp = total_colors / Ncolors[j];
  176104. temp *= Ncolors[j]+1; /* done in long arith to avoid oflo */
  176105. if (temp > (long) max_colors)
  176106. break; /* won't fit, done with this pass */
  176107. Ncolors[j]++; /* OK, apply the increment */
  176108. total_colors = (int) temp;
  176109. changed = TRUE;
  176110. }
  176111. } while (changed);
  176112. return total_colors;
  176113. }
  176114. LOCAL(int)
  176115. output_value (j_decompress_ptr, int, int j, int maxj)
  176116. /* Return j'th output value, where j will range from 0 to maxj */
  176117. /* The output values must fall in 0..MAXJSAMPLE in increasing order */
  176118. {
  176119. /* We always provide values 0 and MAXJSAMPLE for each component;
  176120. * any additional values are equally spaced between these limits.
  176121. * (Forcing the upper and lower values to the limits ensures that
  176122. * dithering can't produce a color outside the selected gamut.)
  176123. */
  176124. return (int) (((INT32) j * MAXJSAMPLE + maxj/2) / maxj);
  176125. }
  176126. LOCAL(int)
  176127. largest_input_value (j_decompress_ptr, int, int j, int maxj)
  176128. /* Return largest input value that should map to j'th output value */
  176129. /* Must have largest(j=0) >= 0, and largest(j=maxj) >= MAXJSAMPLE */
  176130. {
  176131. /* Breakpoints are halfway between values returned by output_value */
  176132. return (int) (((INT32) (2*j + 1) * MAXJSAMPLE + maxj) / (2*maxj));
  176133. }
  176134. /*
  176135. * Create the colormap.
  176136. */
  176137. LOCAL(void)
  176138. create_colormap (j_decompress_ptr cinfo)
  176139. {
  176140. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176141. JSAMPARRAY colormap; /* Created colormap */
  176142. int total_colors; /* Number of distinct output colors */
  176143. int i,j,k, nci, blksize, blkdist, ptr, val;
  176144. /* Select number of colors for each component */
  176145. total_colors = select_ncolors(cinfo, cquantize->Ncolors);
  176146. /* Report selected color counts */
  176147. if (cinfo->out_color_components == 3)
  176148. TRACEMS4(cinfo, 1, JTRC_QUANT_3_NCOLORS,
  176149. total_colors, cquantize->Ncolors[0],
  176150. cquantize->Ncolors[1], cquantize->Ncolors[2]);
  176151. else
  176152. TRACEMS1(cinfo, 1, JTRC_QUANT_NCOLORS, total_colors);
  176153. /* Allocate and fill in the colormap. */
  176154. /* The colors are ordered in the map in standard row-major order, */
  176155. /* i.e. rightmost (highest-indexed) color changes most rapidly. */
  176156. colormap = (*cinfo->mem->alloc_sarray)
  176157. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  176158. (JDIMENSION) total_colors, (JDIMENSION) cinfo->out_color_components);
  176159. /* blksize is number of adjacent repeated entries for a component */
  176160. /* blkdist is distance between groups of identical entries for a component */
  176161. blkdist = total_colors;
  176162. for (i = 0; i < cinfo->out_color_components; i++) {
  176163. /* fill in colormap entries for i'th color component */
  176164. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  176165. blksize = blkdist / nci;
  176166. for (j = 0; j < nci; j++) {
  176167. /* Compute j'th output value (out of nci) for component */
  176168. val = output_value(cinfo, i, j, nci-1);
  176169. /* Fill in all colormap entries that have this value of this component */
  176170. for (ptr = j * blksize; ptr < total_colors; ptr += blkdist) {
  176171. /* fill in blksize entries beginning at ptr */
  176172. for (k = 0; k < blksize; k++)
  176173. colormap[i][ptr+k] = (JSAMPLE) val;
  176174. }
  176175. }
  176176. blkdist = blksize; /* blksize of this color is blkdist of next */
  176177. }
  176178. /* Save the colormap in private storage,
  176179. * where it will survive color quantization mode changes.
  176180. */
  176181. cquantize->sv_colormap = colormap;
  176182. cquantize->sv_actual = total_colors;
  176183. }
  176184. /*
  176185. * Create the color index table.
  176186. */
  176187. LOCAL(void)
  176188. create_colorindex (j_decompress_ptr cinfo)
  176189. {
  176190. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176191. JSAMPROW indexptr;
  176192. int i,j,k, nci, blksize, val, pad;
  176193. /* For ordered dither, we pad the color index tables by MAXJSAMPLE in
  176194. * each direction (input index values can be -MAXJSAMPLE .. 2*MAXJSAMPLE).
  176195. * This is not necessary in the other dithering modes. However, we
  176196. * flag whether it was done in case user changes dithering mode.
  176197. */
  176198. if (cinfo->dither_mode == JDITHER_ORDERED) {
  176199. pad = MAXJSAMPLE*2;
  176200. cquantize->is_padded = TRUE;
  176201. } else {
  176202. pad = 0;
  176203. cquantize->is_padded = FALSE;
  176204. }
  176205. cquantize->colorindex = (*cinfo->mem->alloc_sarray)
  176206. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  176207. (JDIMENSION) (MAXJSAMPLE+1 + pad),
  176208. (JDIMENSION) cinfo->out_color_components);
  176209. /* blksize is number of adjacent repeated entries for a component */
  176210. blksize = cquantize->sv_actual;
  176211. for (i = 0; i < cinfo->out_color_components; i++) {
  176212. /* fill in colorindex entries for i'th color component */
  176213. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  176214. blksize = blksize / nci;
  176215. /* adjust colorindex pointers to provide padding at negative indexes. */
  176216. if (pad)
  176217. cquantize->colorindex[i] += MAXJSAMPLE;
  176218. /* in loop, val = index of current output value, */
  176219. /* and k = largest j that maps to current val */
  176220. indexptr = cquantize->colorindex[i];
  176221. val = 0;
  176222. k = largest_input_value(cinfo, i, 0, nci-1);
  176223. for (j = 0; j <= MAXJSAMPLE; j++) {
  176224. while (j > k) /* advance val if past boundary */
  176225. k = largest_input_value(cinfo, i, ++val, nci-1);
  176226. /* premultiply so that no multiplication needed in main processing */
  176227. indexptr[j] = (JSAMPLE) (val * blksize);
  176228. }
  176229. /* Pad at both ends if necessary */
  176230. if (pad)
  176231. for (j = 1; j <= MAXJSAMPLE; j++) {
  176232. indexptr[-j] = indexptr[0];
  176233. indexptr[MAXJSAMPLE+j] = indexptr[MAXJSAMPLE];
  176234. }
  176235. }
  176236. }
  176237. /*
  176238. * Create an ordered-dither array for a component having ncolors
  176239. * distinct output values.
  176240. */
  176241. LOCAL(ODITHER_MATRIX_PTR)
  176242. make_odither_array (j_decompress_ptr cinfo, int ncolors)
  176243. {
  176244. ODITHER_MATRIX_PTR odither;
  176245. int j,k;
  176246. INT32 num,den;
  176247. odither = (ODITHER_MATRIX_PTR)
  176248. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  176249. SIZEOF(ODITHER_MATRIX));
  176250. /* The inter-value distance for this color is MAXJSAMPLE/(ncolors-1).
  176251. * Hence the dither value for the matrix cell with fill order f
  176252. * (f=0..N-1) should be (N-1-2*f)/(2*N) * MAXJSAMPLE/(ncolors-1).
  176253. * On 16-bit-int machine, be careful to avoid overflow.
  176254. */
  176255. den = 2 * ODITHER_CELLS * ((INT32) (ncolors - 1));
  176256. for (j = 0; j < ODITHER_SIZE; j++) {
  176257. for (k = 0; k < ODITHER_SIZE; k++) {
  176258. num = ((INT32) (ODITHER_CELLS-1 - 2*((int)base_dither_matrix[j][k])))
  176259. * MAXJSAMPLE;
  176260. /* Ensure round towards zero despite C's lack of consistency
  176261. * about rounding negative values in integer division...
  176262. */
  176263. odither[j][k] = (int) (num<0 ? -((-num)/den) : num/den);
  176264. }
  176265. }
  176266. return odither;
  176267. }
  176268. /*
  176269. * Create the ordered-dither tables.
  176270. * Components having the same number of representative colors may
  176271. * share a dither table.
  176272. */
  176273. LOCAL(void)
  176274. create_odither_tables (j_decompress_ptr cinfo)
  176275. {
  176276. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176277. ODITHER_MATRIX_PTR odither;
  176278. int i, j, nci;
  176279. for (i = 0; i < cinfo->out_color_components; i++) {
  176280. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  176281. odither = NULL; /* search for matching prior component */
  176282. for (j = 0; j < i; j++) {
  176283. if (nci == cquantize->Ncolors[j]) {
  176284. odither = cquantize->odither[j];
  176285. break;
  176286. }
  176287. }
  176288. if (odither == NULL) /* need a new table? */
  176289. odither = make_odither_array(cinfo, nci);
  176290. cquantize->odither[i] = odither;
  176291. }
  176292. }
  176293. /*
  176294. * Map some rows of pixels to the output colormapped representation.
  176295. */
  176296. METHODDEF(void)
  176297. color_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  176298. JSAMPARRAY output_buf, int num_rows)
  176299. /* General case, no dithering */
  176300. {
  176301. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176302. JSAMPARRAY colorindex = cquantize->colorindex;
  176303. register int pixcode, ci;
  176304. register JSAMPROW ptrin, ptrout;
  176305. int row;
  176306. JDIMENSION col;
  176307. JDIMENSION width = cinfo->output_width;
  176308. register int nc = cinfo->out_color_components;
  176309. for (row = 0; row < num_rows; row++) {
  176310. ptrin = input_buf[row];
  176311. ptrout = output_buf[row];
  176312. for (col = width; col > 0; col--) {
  176313. pixcode = 0;
  176314. for (ci = 0; ci < nc; ci++) {
  176315. pixcode += GETJSAMPLE(colorindex[ci][GETJSAMPLE(*ptrin++)]);
  176316. }
  176317. *ptrout++ = (JSAMPLE) pixcode;
  176318. }
  176319. }
  176320. }
  176321. METHODDEF(void)
  176322. color_quantize3 (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  176323. JSAMPARRAY output_buf, int num_rows)
  176324. /* Fast path for out_color_components==3, no dithering */
  176325. {
  176326. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176327. register int pixcode;
  176328. register JSAMPROW ptrin, ptrout;
  176329. JSAMPROW colorindex0 = cquantize->colorindex[0];
  176330. JSAMPROW colorindex1 = cquantize->colorindex[1];
  176331. JSAMPROW colorindex2 = cquantize->colorindex[2];
  176332. int row;
  176333. JDIMENSION col;
  176334. JDIMENSION width = cinfo->output_width;
  176335. for (row = 0; row < num_rows; row++) {
  176336. ptrin = input_buf[row];
  176337. ptrout = output_buf[row];
  176338. for (col = width; col > 0; col--) {
  176339. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*ptrin++)]);
  176340. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*ptrin++)]);
  176341. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*ptrin++)]);
  176342. *ptrout++ = (JSAMPLE) pixcode;
  176343. }
  176344. }
  176345. }
  176346. METHODDEF(void)
  176347. quantize_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  176348. JSAMPARRAY output_buf, int num_rows)
  176349. /* General case, with ordered dithering */
  176350. {
  176351. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176352. register JSAMPROW input_ptr;
  176353. register JSAMPROW output_ptr;
  176354. JSAMPROW colorindex_ci;
  176355. int * dither; /* points to active row of dither matrix */
  176356. int row_index, col_index; /* current indexes into dither matrix */
  176357. int nc = cinfo->out_color_components;
  176358. int ci;
  176359. int row;
  176360. JDIMENSION col;
  176361. JDIMENSION width = cinfo->output_width;
  176362. for (row = 0; row < num_rows; row++) {
  176363. /* Initialize output values to 0 so can process components separately */
  176364. jzero_far((void FAR *) output_buf[row],
  176365. (size_t) (width * SIZEOF(JSAMPLE)));
  176366. row_index = cquantize->row_index;
  176367. for (ci = 0; ci < nc; ci++) {
  176368. input_ptr = input_buf[row] + ci;
  176369. output_ptr = output_buf[row];
  176370. colorindex_ci = cquantize->colorindex[ci];
  176371. dither = cquantize->odither[ci][row_index];
  176372. col_index = 0;
  176373. for (col = width; col > 0; col--) {
  176374. /* Form pixel value + dither, range-limit to 0..MAXJSAMPLE,
  176375. * select output value, accumulate into output code for this pixel.
  176376. * Range-limiting need not be done explicitly, as we have extended
  176377. * the colorindex table to produce the right answers for out-of-range
  176378. * inputs. The maximum dither is +- MAXJSAMPLE; this sets the
  176379. * required amount of padding.
  176380. */
  176381. *output_ptr += colorindex_ci[GETJSAMPLE(*input_ptr)+dither[col_index]];
  176382. input_ptr += nc;
  176383. output_ptr++;
  176384. col_index = (col_index + 1) & ODITHER_MASK;
  176385. }
  176386. }
  176387. /* Advance row index for next row */
  176388. row_index = (row_index + 1) & ODITHER_MASK;
  176389. cquantize->row_index = row_index;
  176390. }
  176391. }
  176392. METHODDEF(void)
  176393. quantize3_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  176394. JSAMPARRAY output_buf, int num_rows)
  176395. /* Fast path for out_color_components==3, with ordered dithering */
  176396. {
  176397. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176398. register int pixcode;
  176399. register JSAMPROW input_ptr;
  176400. register JSAMPROW output_ptr;
  176401. JSAMPROW colorindex0 = cquantize->colorindex[0];
  176402. JSAMPROW colorindex1 = cquantize->colorindex[1];
  176403. JSAMPROW colorindex2 = cquantize->colorindex[2];
  176404. int * dither0; /* points to active row of dither matrix */
  176405. int * dither1;
  176406. int * dither2;
  176407. int row_index, col_index; /* current indexes into dither matrix */
  176408. int row;
  176409. JDIMENSION col;
  176410. JDIMENSION width = cinfo->output_width;
  176411. for (row = 0; row < num_rows; row++) {
  176412. row_index = cquantize->row_index;
  176413. input_ptr = input_buf[row];
  176414. output_ptr = output_buf[row];
  176415. dither0 = cquantize->odither[0][row_index];
  176416. dither1 = cquantize->odither[1][row_index];
  176417. dither2 = cquantize->odither[2][row_index];
  176418. col_index = 0;
  176419. for (col = width; col > 0; col--) {
  176420. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*input_ptr++) +
  176421. dither0[col_index]]);
  176422. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*input_ptr++) +
  176423. dither1[col_index]]);
  176424. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*input_ptr++) +
  176425. dither2[col_index]]);
  176426. *output_ptr++ = (JSAMPLE) pixcode;
  176427. col_index = (col_index + 1) & ODITHER_MASK;
  176428. }
  176429. row_index = (row_index + 1) & ODITHER_MASK;
  176430. cquantize->row_index = row_index;
  176431. }
  176432. }
  176433. METHODDEF(void)
  176434. quantize_fs_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  176435. JSAMPARRAY output_buf, int num_rows)
  176436. /* General case, with Floyd-Steinberg dithering */
  176437. {
  176438. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176439. register LOCFSERROR cur; /* current error or pixel value */
  176440. LOCFSERROR belowerr; /* error for pixel below cur */
  176441. LOCFSERROR bpreverr; /* error for below/prev col */
  176442. LOCFSERROR bnexterr; /* error for below/next col */
  176443. LOCFSERROR delta;
  176444. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  176445. register JSAMPROW input_ptr;
  176446. register JSAMPROW output_ptr;
  176447. JSAMPROW colorindex_ci;
  176448. JSAMPROW colormap_ci;
  176449. int pixcode;
  176450. int nc = cinfo->out_color_components;
  176451. int dir; /* 1 for left-to-right, -1 for right-to-left */
  176452. int dirnc; /* dir * nc */
  176453. int ci;
  176454. int row;
  176455. JDIMENSION col;
  176456. JDIMENSION width = cinfo->output_width;
  176457. JSAMPLE *range_limit = cinfo->sample_range_limit;
  176458. SHIFT_TEMPS
  176459. for (row = 0; row < num_rows; row++) {
  176460. /* Initialize output values to 0 so can process components separately */
  176461. jzero_far((void FAR *) output_buf[row],
  176462. (size_t) (width * SIZEOF(JSAMPLE)));
  176463. for (ci = 0; ci < nc; ci++) {
  176464. input_ptr = input_buf[row] + ci;
  176465. output_ptr = output_buf[row];
  176466. if (cquantize->on_odd_row) {
  176467. /* work right to left in this row */
  176468. input_ptr += (width-1) * nc; /* so point to rightmost pixel */
  176469. output_ptr += width-1;
  176470. dir = -1;
  176471. dirnc = -nc;
  176472. errorptr = cquantize->fserrors[ci] + (width+1); /* => entry after last column */
  176473. } else {
  176474. /* work left to right in this row */
  176475. dir = 1;
  176476. dirnc = nc;
  176477. errorptr = cquantize->fserrors[ci]; /* => entry before first column */
  176478. }
  176479. colorindex_ci = cquantize->colorindex[ci];
  176480. colormap_ci = cquantize->sv_colormap[ci];
  176481. /* Preset error values: no error propagated to first pixel from left */
  176482. cur = 0;
  176483. /* and no error propagated to row below yet */
  176484. belowerr = bpreverr = 0;
  176485. for (col = width; col > 0; col--) {
  176486. /* cur holds the error propagated from the previous pixel on the
  176487. * current line. Add the error propagated from the previous line
  176488. * to form the complete error correction term for this pixel, and
  176489. * round the error term (which is expressed * 16) to an integer.
  176490. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  176491. * for either sign of the error value.
  176492. * Note: errorptr points to *previous* column's array entry.
  176493. */
  176494. cur = RIGHT_SHIFT(cur + errorptr[dir] + 8, 4);
  176495. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  176496. * The maximum error is +- MAXJSAMPLE; this sets the required size
  176497. * of the range_limit array.
  176498. */
  176499. cur += GETJSAMPLE(*input_ptr);
  176500. cur = GETJSAMPLE(range_limit[cur]);
  176501. /* Select output value, accumulate into output code for this pixel */
  176502. pixcode = GETJSAMPLE(colorindex_ci[cur]);
  176503. *output_ptr += (JSAMPLE) pixcode;
  176504. /* Compute actual representation error at this pixel */
  176505. /* Note: we can do this even though we don't have the final */
  176506. /* pixel code, because the colormap is orthogonal. */
  176507. cur -= GETJSAMPLE(colormap_ci[pixcode]);
  176508. /* Compute error fractions to be propagated to adjacent pixels.
  176509. * Add these into the running sums, and simultaneously shift the
  176510. * next-line error sums left by 1 column.
  176511. */
  176512. bnexterr = cur;
  176513. delta = cur * 2;
  176514. cur += delta; /* form error * 3 */
  176515. errorptr[0] = (FSERROR) (bpreverr + cur);
  176516. cur += delta; /* form error * 5 */
  176517. bpreverr = belowerr + cur;
  176518. belowerr = bnexterr;
  176519. cur += delta; /* form error * 7 */
  176520. /* At this point cur contains the 7/16 error value to be propagated
  176521. * to the next pixel on the current line, and all the errors for the
  176522. * next line have been shifted over. We are therefore ready to move on.
  176523. */
  176524. input_ptr += dirnc; /* advance input ptr to next column */
  176525. output_ptr += dir; /* advance output ptr to next column */
  176526. errorptr += dir; /* advance errorptr to current column */
  176527. }
  176528. /* Post-loop cleanup: we must unload the final error value into the
  176529. * final fserrors[] entry. Note we need not unload belowerr because
  176530. * it is for the dummy column before or after the actual array.
  176531. */
  176532. errorptr[0] = (FSERROR) bpreverr; /* unload prev err into array */
  176533. }
  176534. cquantize->on_odd_row = (cquantize->on_odd_row ? FALSE : TRUE);
  176535. }
  176536. }
  176537. /*
  176538. * Allocate workspace for Floyd-Steinberg errors.
  176539. */
  176540. LOCAL(void)
  176541. alloc_fs_workspace (j_decompress_ptr cinfo)
  176542. {
  176543. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176544. size_t arraysize;
  176545. int i;
  176546. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  176547. for (i = 0; i < cinfo->out_color_components; i++) {
  176548. cquantize->fserrors[i] = (FSERRPTR)
  176549. (*cinfo->mem->alloc_large)((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  176550. }
  176551. }
  176552. /*
  176553. * Initialize for one-pass color quantization.
  176554. */
  176555. METHODDEF(void)
  176556. start_pass_1_quant (j_decompress_ptr cinfo, boolean)
  176557. {
  176558. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176559. size_t arraysize;
  176560. int i;
  176561. /* Install my colormap. */
  176562. cinfo->colormap = cquantize->sv_colormap;
  176563. cinfo->actual_number_of_colors = cquantize->sv_actual;
  176564. /* Initialize for desired dithering mode. */
  176565. switch (cinfo->dither_mode) {
  176566. case JDITHER_NONE:
  176567. if (cinfo->out_color_components == 3)
  176568. cquantize->pub.color_quantize = color_quantize3;
  176569. else
  176570. cquantize->pub.color_quantize = color_quantize;
  176571. break;
  176572. case JDITHER_ORDERED:
  176573. if (cinfo->out_color_components == 3)
  176574. cquantize->pub.color_quantize = quantize3_ord_dither;
  176575. else
  176576. cquantize->pub.color_quantize = quantize_ord_dither;
  176577. cquantize->row_index = 0; /* initialize state for ordered dither */
  176578. /* If user changed to ordered dither from another mode,
  176579. * we must recreate the color index table with padding.
  176580. * This will cost extra space, but probably isn't very likely.
  176581. */
  176582. if (! cquantize->is_padded)
  176583. create_colorindex(cinfo);
  176584. /* Create ordered-dither tables if we didn't already. */
  176585. if (cquantize->odither[0] == NULL)
  176586. create_odither_tables(cinfo);
  176587. break;
  176588. case JDITHER_FS:
  176589. cquantize->pub.color_quantize = quantize_fs_dither;
  176590. cquantize->on_odd_row = FALSE; /* initialize state for F-S dither */
  176591. /* Allocate Floyd-Steinberg workspace if didn't already. */
  176592. if (cquantize->fserrors[0] == NULL)
  176593. alloc_fs_workspace(cinfo);
  176594. /* Initialize the propagated errors to zero. */
  176595. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  176596. for (i = 0; i < cinfo->out_color_components; i++)
  176597. jzero_far((void FAR *) cquantize->fserrors[i], arraysize);
  176598. break;
  176599. default:
  176600. ERREXIT(cinfo, JERR_NOT_COMPILED);
  176601. break;
  176602. }
  176603. }
  176604. /*
  176605. * Finish up at the end of the pass.
  176606. */
  176607. METHODDEF(void)
  176608. finish_pass_1_quant (j_decompress_ptr)
  176609. {
  176610. /* no work in 1-pass case */
  176611. }
  176612. /*
  176613. * Switch to a new external colormap between output passes.
  176614. * Shouldn't get to this module!
  176615. */
  176616. METHODDEF(void)
  176617. new_color_map_1_quant (j_decompress_ptr cinfo)
  176618. {
  176619. ERREXIT(cinfo, JERR_MODE_CHANGE);
  176620. }
  176621. /*
  176622. * Module initialization routine for 1-pass color quantization.
  176623. */
  176624. GLOBAL(void)
  176625. jinit_1pass_quantizer (j_decompress_ptr cinfo)
  176626. {
  176627. my_cquantize_ptr cquantize;
  176628. cquantize = (my_cquantize_ptr)
  176629. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  176630. SIZEOF(my_cquantizer));
  176631. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  176632. cquantize->pub.start_pass = start_pass_1_quant;
  176633. cquantize->pub.finish_pass = finish_pass_1_quant;
  176634. cquantize->pub.new_color_map = new_color_map_1_quant;
  176635. cquantize->fserrors[0] = NULL; /* Flag FS workspace not allocated */
  176636. cquantize->odither[0] = NULL; /* Also flag odither arrays not allocated */
  176637. /* Make sure my internal arrays won't overflow */
  176638. if (cinfo->out_color_components > MAX_Q_COMPS)
  176639. ERREXIT1(cinfo, JERR_QUANT_COMPONENTS, MAX_Q_COMPS);
  176640. /* Make sure colormap indexes can be represented by JSAMPLEs */
  176641. if (cinfo->desired_number_of_colors > (MAXJSAMPLE+1))
  176642. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXJSAMPLE+1);
  176643. /* Create the colormap and color index table. */
  176644. create_colormap(cinfo);
  176645. create_colorindex(cinfo);
  176646. /* Allocate Floyd-Steinberg workspace now if requested.
  176647. * We do this now since it is FAR storage and may affect the memory
  176648. * manager's space calculations. If the user changes to FS dither
  176649. * mode in a later pass, we will allocate the space then, and will
  176650. * possibly overrun the max_memory_to_use setting.
  176651. */
  176652. if (cinfo->dither_mode == JDITHER_FS)
  176653. alloc_fs_workspace(cinfo);
  176654. }
  176655. #endif /* QUANT_1PASS_SUPPORTED */
  176656. /*** End of inlined file: jquant1.c ***/
  176657. /*** Start of inlined file: jquant2.c ***/
  176658. #define JPEG_INTERNALS
  176659. #ifdef QUANT_2PASS_SUPPORTED
  176660. /*
  176661. * This module implements the well-known Heckbert paradigm for color
  176662. * quantization. Most of the ideas used here can be traced back to
  176663. * Heckbert's seminal paper
  176664. * Heckbert, Paul. "Color Image Quantization for Frame Buffer Display",
  176665. * Proc. SIGGRAPH '82, Computer Graphics v.16 #3 (July 1982), pp 297-304.
  176666. *
  176667. * In the first pass over the image, we accumulate a histogram showing the
  176668. * usage count of each possible color. To keep the histogram to a reasonable
  176669. * size, we reduce the precision of the input; typical practice is to retain
  176670. * 5 or 6 bits per color, so that 8 or 4 different input values are counted
  176671. * in the same histogram cell.
  176672. *
  176673. * Next, the color-selection step begins with a box representing the whole
  176674. * color space, and repeatedly splits the "largest" remaining box until we
  176675. * have as many boxes as desired colors. Then the mean color in each
  176676. * remaining box becomes one of the possible output colors.
  176677. *
  176678. * The second pass over the image maps each input pixel to the closest output
  176679. * color (optionally after applying a Floyd-Steinberg dithering correction).
  176680. * This mapping is logically trivial, but making it go fast enough requires
  176681. * considerable care.
  176682. *
  176683. * Heckbert-style quantizers vary a good deal in their policies for choosing
  176684. * the "largest" box and deciding where to cut it. The particular policies
  176685. * used here have proved out well in experimental comparisons, but better ones
  176686. * may yet be found.
  176687. *
  176688. * In earlier versions of the IJG code, this module quantized in YCbCr color
  176689. * space, processing the raw upsampled data without a color conversion step.
  176690. * This allowed the color conversion math to be done only once per colormap
  176691. * entry, not once per pixel. However, that optimization precluded other
  176692. * useful optimizations (such as merging color conversion with upsampling)
  176693. * and it also interfered with desired capabilities such as quantizing to an
  176694. * externally-supplied colormap. We have therefore abandoned that approach.
  176695. * The present code works in the post-conversion color space, typically RGB.
  176696. *
  176697. * To improve the visual quality of the results, we actually work in scaled
  176698. * RGB space, giving G distances more weight than R, and R in turn more than
  176699. * B. To do everything in integer math, we must use integer scale factors.
  176700. * The 2/3/1 scale factors used here correspond loosely to the relative
  176701. * weights of the colors in the NTSC grayscale equation.
  176702. * If you want to use this code to quantize a non-RGB color space, you'll
  176703. * probably need to change these scale factors.
  176704. */
  176705. #define R_SCALE 2 /* scale R distances by this much */
  176706. #define G_SCALE 3 /* scale G distances by this much */
  176707. #define B_SCALE 1 /* and B by this much */
  176708. /* Relabel R/G/B as components 0/1/2, respecting the RGB ordering defined
  176709. * in jmorecfg.h. As the code stands, it will do the right thing for R,G,B
  176710. * and B,G,R orders. If you define some other weird order in jmorecfg.h,
  176711. * you'll get compile errors until you extend this logic. In that case
  176712. * you'll probably want to tweak the histogram sizes too.
  176713. */
  176714. #if RGB_RED == 0
  176715. #define C0_SCALE R_SCALE
  176716. #endif
  176717. #if RGB_BLUE == 0
  176718. #define C0_SCALE B_SCALE
  176719. #endif
  176720. #if RGB_GREEN == 1
  176721. #define C1_SCALE G_SCALE
  176722. #endif
  176723. #if RGB_RED == 2
  176724. #define C2_SCALE R_SCALE
  176725. #endif
  176726. #if RGB_BLUE == 2
  176727. #define C2_SCALE B_SCALE
  176728. #endif
  176729. /*
  176730. * First we have the histogram data structure and routines for creating it.
  176731. *
  176732. * The number of bits of precision can be adjusted by changing these symbols.
  176733. * We recommend keeping 6 bits for G and 5 each for R and B.
  176734. * If you have plenty of memory and cycles, 6 bits all around gives marginally
  176735. * better results; if you are short of memory, 5 bits all around will save
  176736. * some space but degrade the results.
  176737. * To maintain a fully accurate histogram, we'd need to allocate a "long"
  176738. * (preferably unsigned long) for each cell. In practice this is overkill;
  176739. * we can get by with 16 bits per cell. Few of the cell counts will overflow,
  176740. * and clamping those that do overflow to the maximum value will give close-
  176741. * enough results. This reduces the recommended histogram size from 256Kb
  176742. * to 128Kb, which is a useful savings on PC-class machines.
  176743. * (In the second pass the histogram space is re-used for pixel mapping data;
  176744. * in that capacity, each cell must be able to store zero to the number of
  176745. * desired colors. 16 bits/cell is plenty for that too.)
  176746. * Since the JPEG code is intended to run in small memory model on 80x86
  176747. * machines, we can't just allocate the histogram in one chunk. Instead
  176748. * of a true 3-D array, we use a row of pointers to 2-D arrays. Each
  176749. * pointer corresponds to a C0 value (typically 2^5 = 32 pointers) and
  176750. * each 2-D array has 2^6*2^5 = 2048 or 2^6*2^6 = 4096 entries. Note that
  176751. * on 80x86 machines, the pointer row is in near memory but the actual
  176752. * arrays are in far memory (same arrangement as we use for image arrays).
  176753. */
  176754. #define MAXNUMCOLORS (MAXJSAMPLE+1) /* maximum size of colormap */
  176755. /* These will do the right thing for either R,G,B or B,G,R color order,
  176756. * but you may not like the results for other color orders.
  176757. */
  176758. #define HIST_C0_BITS 5 /* bits of precision in R/B histogram */
  176759. #define HIST_C1_BITS 6 /* bits of precision in G histogram */
  176760. #define HIST_C2_BITS 5 /* bits of precision in B/R histogram */
  176761. /* Number of elements along histogram axes. */
  176762. #define HIST_C0_ELEMS (1<<HIST_C0_BITS)
  176763. #define HIST_C1_ELEMS (1<<HIST_C1_BITS)
  176764. #define HIST_C2_ELEMS (1<<HIST_C2_BITS)
  176765. /* These are the amounts to shift an input value to get a histogram index. */
  176766. #define C0_SHIFT (BITS_IN_JSAMPLE-HIST_C0_BITS)
  176767. #define C1_SHIFT (BITS_IN_JSAMPLE-HIST_C1_BITS)
  176768. #define C2_SHIFT (BITS_IN_JSAMPLE-HIST_C2_BITS)
  176769. typedef UINT16 histcell; /* histogram cell; prefer an unsigned type */
  176770. typedef histcell FAR * histptr; /* for pointers to histogram cells */
  176771. typedef histcell hist1d[HIST_C2_ELEMS]; /* typedefs for the array */
  176772. typedef hist1d FAR * hist2d; /* type for the 2nd-level pointers */
  176773. typedef hist2d * hist3d; /* type for top-level pointer */
  176774. /* Declarations for Floyd-Steinberg dithering.
  176775. *
  176776. * Errors are accumulated into the array fserrors[], at a resolution of
  176777. * 1/16th of a pixel count. The error at a given pixel is propagated
  176778. * to its not-yet-processed neighbors using the standard F-S fractions,
  176779. * ... (here) 7/16
  176780. * 3/16 5/16 1/16
  176781. * We work left-to-right on even rows, right-to-left on odd rows.
  176782. *
  176783. * We can get away with a single array (holding one row's worth of errors)
  176784. * by using it to store the current row's errors at pixel columns not yet
  176785. * processed, but the next row's errors at columns already processed. We
  176786. * need only a few extra variables to hold the errors immediately around the
  176787. * current column. (If we are lucky, those variables are in registers, but
  176788. * even if not, they're probably cheaper to access than array elements are.)
  176789. *
  176790. * The fserrors[] array has (#columns + 2) entries; the extra entry at
  176791. * each end saves us from special-casing the first and last pixels.
  176792. * Each entry is three values long, one value for each color component.
  176793. *
  176794. * Note: on a wide image, we might not have enough room in a PC's near data
  176795. * segment to hold the error array; so it is allocated with alloc_large.
  176796. */
  176797. #if BITS_IN_JSAMPLE == 8
  176798. typedef INT16 FSERROR; /* 16 bits should be enough */
  176799. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  176800. #else
  176801. typedef INT32 FSERROR; /* may need more than 16 bits */
  176802. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  176803. #endif
  176804. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  176805. /* Private subobject */
  176806. typedef struct {
  176807. struct jpeg_color_quantizer pub; /* public fields */
  176808. /* Space for the eventually created colormap is stashed here */
  176809. JSAMPARRAY sv_colormap; /* colormap allocated at init time */
  176810. int desired; /* desired # of colors = size of colormap */
  176811. /* Variables for accumulating image statistics */
  176812. hist3d histogram; /* pointer to the histogram */
  176813. boolean needs_zeroed; /* TRUE if next pass must zero histogram */
  176814. /* Variables for Floyd-Steinberg dithering */
  176815. FSERRPTR fserrors; /* accumulated errors */
  176816. boolean on_odd_row; /* flag to remember which row we are on */
  176817. int * error_limiter; /* table for clamping the applied error */
  176818. } my_cquantizer2;
  176819. typedef my_cquantizer2 * my_cquantize_ptr2;
  176820. /*
  176821. * Prescan some rows of pixels.
  176822. * In this module the prescan simply updates the histogram, which has been
  176823. * initialized to zeroes by start_pass.
  176824. * An output_buf parameter is required by the method signature, but no data
  176825. * is actually output (in fact the buffer controller is probably passing a
  176826. * NULL pointer).
  176827. */
  176828. METHODDEF(void)
  176829. prescan_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  176830. JSAMPARRAY, int num_rows)
  176831. {
  176832. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  176833. register JSAMPROW ptr;
  176834. register histptr histp;
  176835. register hist3d histogram = cquantize->histogram;
  176836. int row;
  176837. JDIMENSION col;
  176838. JDIMENSION width = cinfo->output_width;
  176839. for (row = 0; row < num_rows; row++) {
  176840. ptr = input_buf[row];
  176841. for (col = width; col > 0; col--) {
  176842. /* get pixel value and index into the histogram */
  176843. histp = & histogram[GETJSAMPLE(ptr[0]) >> C0_SHIFT]
  176844. [GETJSAMPLE(ptr[1]) >> C1_SHIFT]
  176845. [GETJSAMPLE(ptr[2]) >> C2_SHIFT];
  176846. /* increment, check for overflow and undo increment if so. */
  176847. if (++(*histp) <= 0)
  176848. (*histp)--;
  176849. ptr += 3;
  176850. }
  176851. }
  176852. }
  176853. /*
  176854. * Next we have the really interesting routines: selection of a colormap
  176855. * given the completed histogram.
  176856. * These routines work with a list of "boxes", each representing a rectangular
  176857. * subset of the input color space (to histogram precision).
  176858. */
  176859. typedef struct {
  176860. /* The bounds of the box (inclusive); expressed as histogram indexes */
  176861. int c0min, c0max;
  176862. int c1min, c1max;
  176863. int c2min, c2max;
  176864. /* The volume (actually 2-norm) of the box */
  176865. INT32 volume;
  176866. /* The number of nonzero histogram cells within this box */
  176867. long colorcount;
  176868. } box;
  176869. typedef box * boxptr;
  176870. LOCAL(boxptr)
  176871. find_biggest_color_pop (boxptr boxlist, int numboxes)
  176872. /* Find the splittable box with the largest color population */
  176873. /* Returns NULL if no splittable boxes remain */
  176874. {
  176875. register boxptr boxp;
  176876. register int i;
  176877. register long maxc = 0;
  176878. boxptr which = NULL;
  176879. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  176880. if (boxp->colorcount > maxc && boxp->volume > 0) {
  176881. which = boxp;
  176882. maxc = boxp->colorcount;
  176883. }
  176884. }
  176885. return which;
  176886. }
  176887. LOCAL(boxptr)
  176888. find_biggest_volume (boxptr boxlist, int numboxes)
  176889. /* Find the splittable box with the largest (scaled) volume */
  176890. /* Returns NULL if no splittable boxes remain */
  176891. {
  176892. register boxptr boxp;
  176893. register int i;
  176894. register INT32 maxv = 0;
  176895. boxptr which = NULL;
  176896. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  176897. if (boxp->volume > maxv) {
  176898. which = boxp;
  176899. maxv = boxp->volume;
  176900. }
  176901. }
  176902. return which;
  176903. }
  176904. LOCAL(void)
  176905. update_box (j_decompress_ptr cinfo, boxptr boxp)
  176906. /* Shrink the min/max bounds of a box to enclose only nonzero elements, */
  176907. /* and recompute its volume and population */
  176908. {
  176909. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  176910. hist3d histogram = cquantize->histogram;
  176911. histptr histp;
  176912. int c0,c1,c2;
  176913. int c0min,c0max,c1min,c1max,c2min,c2max;
  176914. INT32 dist0,dist1,dist2;
  176915. long ccount;
  176916. c0min = boxp->c0min; c0max = boxp->c0max;
  176917. c1min = boxp->c1min; c1max = boxp->c1max;
  176918. c2min = boxp->c2min; c2max = boxp->c2max;
  176919. if (c0max > c0min)
  176920. for (c0 = c0min; c0 <= c0max; c0++)
  176921. for (c1 = c1min; c1 <= c1max; c1++) {
  176922. histp = & histogram[c0][c1][c2min];
  176923. for (c2 = c2min; c2 <= c2max; c2++)
  176924. if (*histp++ != 0) {
  176925. boxp->c0min = c0min = c0;
  176926. goto have_c0min;
  176927. }
  176928. }
  176929. have_c0min:
  176930. if (c0max > c0min)
  176931. for (c0 = c0max; c0 >= c0min; c0--)
  176932. for (c1 = c1min; c1 <= c1max; c1++) {
  176933. histp = & histogram[c0][c1][c2min];
  176934. for (c2 = c2min; c2 <= c2max; c2++)
  176935. if (*histp++ != 0) {
  176936. boxp->c0max = c0max = c0;
  176937. goto have_c0max;
  176938. }
  176939. }
  176940. have_c0max:
  176941. if (c1max > c1min)
  176942. for (c1 = c1min; c1 <= c1max; c1++)
  176943. for (c0 = c0min; c0 <= c0max; c0++) {
  176944. histp = & histogram[c0][c1][c2min];
  176945. for (c2 = c2min; c2 <= c2max; c2++)
  176946. if (*histp++ != 0) {
  176947. boxp->c1min = c1min = c1;
  176948. goto have_c1min;
  176949. }
  176950. }
  176951. have_c1min:
  176952. if (c1max > c1min)
  176953. for (c1 = c1max; c1 >= c1min; c1--)
  176954. for (c0 = c0min; c0 <= c0max; c0++) {
  176955. histp = & histogram[c0][c1][c2min];
  176956. for (c2 = c2min; c2 <= c2max; c2++)
  176957. if (*histp++ != 0) {
  176958. boxp->c1max = c1max = c1;
  176959. goto have_c1max;
  176960. }
  176961. }
  176962. have_c1max:
  176963. if (c2max > c2min)
  176964. for (c2 = c2min; c2 <= c2max; c2++)
  176965. for (c0 = c0min; c0 <= c0max; c0++) {
  176966. histp = & histogram[c0][c1min][c2];
  176967. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  176968. if (*histp != 0) {
  176969. boxp->c2min = c2min = c2;
  176970. goto have_c2min;
  176971. }
  176972. }
  176973. have_c2min:
  176974. if (c2max > c2min)
  176975. for (c2 = c2max; c2 >= c2min; c2--)
  176976. for (c0 = c0min; c0 <= c0max; c0++) {
  176977. histp = & histogram[c0][c1min][c2];
  176978. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  176979. if (*histp != 0) {
  176980. boxp->c2max = c2max = c2;
  176981. goto have_c2max;
  176982. }
  176983. }
  176984. have_c2max:
  176985. /* Update box volume.
  176986. * We use 2-norm rather than real volume here; this biases the method
  176987. * against making long narrow boxes, and it has the side benefit that
  176988. * a box is splittable iff norm > 0.
  176989. * Since the differences are expressed in histogram-cell units,
  176990. * we have to shift back to JSAMPLE units to get consistent distances;
  176991. * after which, we scale according to the selected distance scale factors.
  176992. */
  176993. dist0 = ((c0max - c0min) << C0_SHIFT) * C0_SCALE;
  176994. dist1 = ((c1max - c1min) << C1_SHIFT) * C1_SCALE;
  176995. dist2 = ((c2max - c2min) << C2_SHIFT) * C2_SCALE;
  176996. boxp->volume = dist0*dist0 + dist1*dist1 + dist2*dist2;
  176997. /* Now scan remaining volume of box and compute population */
  176998. ccount = 0;
  176999. for (c0 = c0min; c0 <= c0max; c0++)
  177000. for (c1 = c1min; c1 <= c1max; c1++) {
  177001. histp = & histogram[c0][c1][c2min];
  177002. for (c2 = c2min; c2 <= c2max; c2++, histp++)
  177003. if (*histp != 0) {
  177004. ccount++;
  177005. }
  177006. }
  177007. boxp->colorcount = ccount;
  177008. }
  177009. LOCAL(int)
  177010. median_cut (j_decompress_ptr cinfo, boxptr boxlist, int numboxes,
  177011. int desired_colors)
  177012. /* Repeatedly select and split the largest box until we have enough boxes */
  177013. {
  177014. int n,lb;
  177015. int c0,c1,c2,cmax;
  177016. register boxptr b1,b2;
  177017. while (numboxes < desired_colors) {
  177018. /* Select box to split.
  177019. * Current algorithm: by population for first half, then by volume.
  177020. */
  177021. if (numboxes*2 <= desired_colors) {
  177022. b1 = find_biggest_color_pop(boxlist, numboxes);
  177023. } else {
  177024. b1 = find_biggest_volume(boxlist, numboxes);
  177025. }
  177026. if (b1 == NULL) /* no splittable boxes left! */
  177027. break;
  177028. b2 = &boxlist[numboxes]; /* where new box will go */
  177029. /* Copy the color bounds to the new box. */
  177030. b2->c0max = b1->c0max; b2->c1max = b1->c1max; b2->c2max = b1->c2max;
  177031. b2->c0min = b1->c0min; b2->c1min = b1->c1min; b2->c2min = b1->c2min;
  177032. /* Choose which axis to split the box on.
  177033. * Current algorithm: longest scaled axis.
  177034. * See notes in update_box about scaling distances.
  177035. */
  177036. c0 = ((b1->c0max - b1->c0min) << C0_SHIFT) * C0_SCALE;
  177037. c1 = ((b1->c1max - b1->c1min) << C1_SHIFT) * C1_SCALE;
  177038. c2 = ((b1->c2max - b1->c2min) << C2_SHIFT) * C2_SCALE;
  177039. /* We want to break any ties in favor of green, then red, blue last.
  177040. * This code does the right thing for R,G,B or B,G,R color orders only.
  177041. */
  177042. #if RGB_RED == 0
  177043. cmax = c1; n = 1;
  177044. if (c0 > cmax) { cmax = c0; n = 0; }
  177045. if (c2 > cmax) { n = 2; }
  177046. #else
  177047. cmax = c1; n = 1;
  177048. if (c2 > cmax) { cmax = c2; n = 2; }
  177049. if (c0 > cmax) { n = 0; }
  177050. #endif
  177051. /* Choose split point along selected axis, and update box bounds.
  177052. * Current algorithm: split at halfway point.
  177053. * (Since the box has been shrunk to minimum volume,
  177054. * any split will produce two nonempty subboxes.)
  177055. * Note that lb value is max for lower box, so must be < old max.
  177056. */
  177057. switch (n) {
  177058. case 0:
  177059. lb = (b1->c0max + b1->c0min) / 2;
  177060. b1->c0max = lb;
  177061. b2->c0min = lb+1;
  177062. break;
  177063. case 1:
  177064. lb = (b1->c1max + b1->c1min) / 2;
  177065. b1->c1max = lb;
  177066. b2->c1min = lb+1;
  177067. break;
  177068. case 2:
  177069. lb = (b1->c2max + b1->c2min) / 2;
  177070. b1->c2max = lb;
  177071. b2->c2min = lb+1;
  177072. break;
  177073. }
  177074. /* Update stats for boxes */
  177075. update_box(cinfo, b1);
  177076. update_box(cinfo, b2);
  177077. numboxes++;
  177078. }
  177079. return numboxes;
  177080. }
  177081. LOCAL(void)
  177082. compute_color (j_decompress_ptr cinfo, boxptr boxp, int icolor)
  177083. /* Compute representative color for a box, put it in colormap[icolor] */
  177084. {
  177085. /* Current algorithm: mean weighted by pixels (not colors) */
  177086. /* Note it is important to get the rounding correct! */
  177087. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177088. hist3d histogram = cquantize->histogram;
  177089. histptr histp;
  177090. int c0,c1,c2;
  177091. int c0min,c0max,c1min,c1max,c2min,c2max;
  177092. long count;
  177093. long total = 0;
  177094. long c0total = 0;
  177095. long c1total = 0;
  177096. long c2total = 0;
  177097. c0min = boxp->c0min; c0max = boxp->c0max;
  177098. c1min = boxp->c1min; c1max = boxp->c1max;
  177099. c2min = boxp->c2min; c2max = boxp->c2max;
  177100. for (c0 = c0min; c0 <= c0max; c0++)
  177101. for (c1 = c1min; c1 <= c1max; c1++) {
  177102. histp = & histogram[c0][c1][c2min];
  177103. for (c2 = c2min; c2 <= c2max; c2++) {
  177104. if ((count = *histp++) != 0) {
  177105. total += count;
  177106. c0total += ((c0 << C0_SHIFT) + ((1<<C0_SHIFT)>>1)) * count;
  177107. c1total += ((c1 << C1_SHIFT) + ((1<<C1_SHIFT)>>1)) * count;
  177108. c2total += ((c2 << C2_SHIFT) + ((1<<C2_SHIFT)>>1)) * count;
  177109. }
  177110. }
  177111. }
  177112. cinfo->colormap[0][icolor] = (JSAMPLE) ((c0total + (total>>1)) / total);
  177113. cinfo->colormap[1][icolor] = (JSAMPLE) ((c1total + (total>>1)) / total);
  177114. cinfo->colormap[2][icolor] = (JSAMPLE) ((c2total + (total>>1)) / total);
  177115. }
  177116. LOCAL(void)
  177117. select_colors (j_decompress_ptr cinfo, int desired_colors)
  177118. /* Master routine for color selection */
  177119. {
  177120. boxptr boxlist;
  177121. int numboxes;
  177122. int i;
  177123. /* Allocate workspace for box list */
  177124. boxlist = (boxptr) (*cinfo->mem->alloc_small)
  177125. ((j_common_ptr) cinfo, JPOOL_IMAGE, desired_colors * SIZEOF(box));
  177126. /* Initialize one box containing whole space */
  177127. numboxes = 1;
  177128. boxlist[0].c0min = 0;
  177129. boxlist[0].c0max = MAXJSAMPLE >> C0_SHIFT;
  177130. boxlist[0].c1min = 0;
  177131. boxlist[0].c1max = MAXJSAMPLE >> C1_SHIFT;
  177132. boxlist[0].c2min = 0;
  177133. boxlist[0].c2max = MAXJSAMPLE >> C2_SHIFT;
  177134. /* Shrink it to actually-used volume and set its statistics */
  177135. update_box(cinfo, & boxlist[0]);
  177136. /* Perform median-cut to produce final box list */
  177137. numboxes = median_cut(cinfo, boxlist, numboxes, desired_colors);
  177138. /* Compute the representative color for each box, fill colormap */
  177139. for (i = 0; i < numboxes; i++)
  177140. compute_color(cinfo, & boxlist[i], i);
  177141. cinfo->actual_number_of_colors = numboxes;
  177142. TRACEMS1(cinfo, 1, JTRC_QUANT_SELECTED, numboxes);
  177143. }
  177144. /*
  177145. * These routines are concerned with the time-critical task of mapping input
  177146. * colors to the nearest color in the selected colormap.
  177147. *
  177148. * We re-use the histogram space as an "inverse color map", essentially a
  177149. * cache for the results of nearest-color searches. All colors within a
  177150. * histogram cell will be mapped to the same colormap entry, namely the one
  177151. * closest to the cell's center. This may not be quite the closest entry to
  177152. * the actual input color, but it's almost as good. A zero in the cache
  177153. * indicates we haven't found the nearest color for that cell yet; the array
  177154. * is cleared to zeroes before starting the mapping pass. When we find the
  177155. * nearest color for a cell, its colormap index plus one is recorded in the
  177156. * cache for future use. The pass2 scanning routines call fill_inverse_cmap
  177157. * when they need to use an unfilled entry in the cache.
  177158. *
  177159. * Our method of efficiently finding nearest colors is based on the "locally
  177160. * sorted search" idea described by Heckbert and on the incremental distance
  177161. * calculation described by Spencer W. Thomas in chapter III.1 of Graphics
  177162. * Gems II (James Arvo, ed. Academic Press, 1991). Thomas points out that
  177163. * the distances from a given colormap entry to each cell of the histogram can
  177164. * be computed quickly using an incremental method: the differences between
  177165. * distances to adjacent cells themselves differ by a constant. This allows a
  177166. * fairly fast implementation of the "brute force" approach of computing the
  177167. * distance from every colormap entry to every histogram cell. Unfortunately,
  177168. * it needs a work array to hold the best-distance-so-far for each histogram
  177169. * cell (because the inner loop has to be over cells, not colormap entries).
  177170. * The work array elements have to be INT32s, so the work array would need
  177171. * 256Kb at our recommended precision. This is not feasible in DOS machines.
  177172. *
  177173. * To get around these problems, we apply Thomas' method to compute the
  177174. * nearest colors for only the cells within a small subbox of the histogram.
  177175. * The work array need be only as big as the subbox, so the memory usage
  177176. * problem is solved. Furthermore, we need not fill subboxes that are never
  177177. * referenced in pass2; many images use only part of the color gamut, so a
  177178. * fair amount of work is saved. An additional advantage of this
  177179. * approach is that we can apply Heckbert's locality criterion to quickly
  177180. * eliminate colormap entries that are far away from the subbox; typically
  177181. * three-fourths of the colormap entries are rejected by Heckbert's criterion,
  177182. * and we need not compute their distances to individual cells in the subbox.
  177183. * The speed of this approach is heavily influenced by the subbox size: too
  177184. * small means too much overhead, too big loses because Heckbert's criterion
  177185. * can't eliminate as many colormap entries. Empirically the best subbox
  177186. * size seems to be about 1/512th of the histogram (1/8th in each direction).
  177187. *
  177188. * Thomas' article also describes a refined method which is asymptotically
  177189. * faster than the brute-force method, but it is also far more complex and
  177190. * cannot efficiently be applied to small subboxes. It is therefore not
  177191. * useful for programs intended to be portable to DOS machines. On machines
  177192. * with plenty of memory, filling the whole histogram in one shot with Thomas'
  177193. * refined method might be faster than the present code --- but then again,
  177194. * it might not be any faster, and it's certainly more complicated.
  177195. */
  177196. /* log2(histogram cells in update box) for each axis; this can be adjusted */
  177197. #define BOX_C0_LOG (HIST_C0_BITS-3)
  177198. #define BOX_C1_LOG (HIST_C1_BITS-3)
  177199. #define BOX_C2_LOG (HIST_C2_BITS-3)
  177200. #define BOX_C0_ELEMS (1<<BOX_C0_LOG) /* # of hist cells in update box */
  177201. #define BOX_C1_ELEMS (1<<BOX_C1_LOG)
  177202. #define BOX_C2_ELEMS (1<<BOX_C2_LOG)
  177203. #define BOX_C0_SHIFT (C0_SHIFT + BOX_C0_LOG)
  177204. #define BOX_C1_SHIFT (C1_SHIFT + BOX_C1_LOG)
  177205. #define BOX_C2_SHIFT (C2_SHIFT + BOX_C2_LOG)
  177206. /*
  177207. * The next three routines implement inverse colormap filling. They could
  177208. * all be folded into one big routine, but splitting them up this way saves
  177209. * some stack space (the mindist[] and bestdist[] arrays need not coexist)
  177210. * and may allow some compilers to produce better code by registerizing more
  177211. * inner-loop variables.
  177212. */
  177213. LOCAL(int)
  177214. find_nearby_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  177215. JSAMPLE colorlist[])
  177216. /* Locate the colormap entries close enough to an update box to be candidates
  177217. * for the nearest entry to some cell(s) in the update box. The update box
  177218. * is specified by the center coordinates of its first cell. The number of
  177219. * candidate colormap entries is returned, and their colormap indexes are
  177220. * placed in colorlist[].
  177221. * This routine uses Heckbert's "locally sorted search" criterion to select
  177222. * the colors that need further consideration.
  177223. */
  177224. {
  177225. int numcolors = cinfo->actual_number_of_colors;
  177226. int maxc0, maxc1, maxc2;
  177227. int centerc0, centerc1, centerc2;
  177228. int i, x, ncolors;
  177229. INT32 minmaxdist, min_dist, max_dist, tdist;
  177230. INT32 mindist[MAXNUMCOLORS]; /* min distance to colormap entry i */
  177231. /* Compute true coordinates of update box's upper corner and center.
  177232. * Actually we compute the coordinates of the center of the upper-corner
  177233. * histogram cell, which are the upper bounds of the volume we care about.
  177234. * Note that since ">>" rounds down, the "center" values may be closer to
  177235. * min than to max; hence comparisons to them must be "<=", not "<".
  177236. */
  177237. maxc0 = minc0 + ((1 << BOX_C0_SHIFT) - (1 << C0_SHIFT));
  177238. centerc0 = (minc0 + maxc0) >> 1;
  177239. maxc1 = minc1 + ((1 << BOX_C1_SHIFT) - (1 << C1_SHIFT));
  177240. centerc1 = (minc1 + maxc1) >> 1;
  177241. maxc2 = minc2 + ((1 << BOX_C2_SHIFT) - (1 << C2_SHIFT));
  177242. centerc2 = (minc2 + maxc2) >> 1;
  177243. /* For each color in colormap, find:
  177244. * 1. its minimum squared-distance to any point in the update box
  177245. * (zero if color is within update box);
  177246. * 2. its maximum squared-distance to any point in the update box.
  177247. * Both of these can be found by considering only the corners of the box.
  177248. * We save the minimum distance for each color in mindist[];
  177249. * only the smallest maximum distance is of interest.
  177250. */
  177251. minmaxdist = 0x7FFFFFFFL;
  177252. for (i = 0; i < numcolors; i++) {
  177253. /* We compute the squared-c0-distance term, then add in the other two. */
  177254. x = GETJSAMPLE(cinfo->colormap[0][i]);
  177255. if (x < minc0) {
  177256. tdist = (x - minc0) * C0_SCALE;
  177257. min_dist = tdist*tdist;
  177258. tdist = (x - maxc0) * C0_SCALE;
  177259. max_dist = tdist*tdist;
  177260. } else if (x > maxc0) {
  177261. tdist = (x - maxc0) * C0_SCALE;
  177262. min_dist = tdist*tdist;
  177263. tdist = (x - minc0) * C0_SCALE;
  177264. max_dist = tdist*tdist;
  177265. } else {
  177266. /* within cell range so no contribution to min_dist */
  177267. min_dist = 0;
  177268. if (x <= centerc0) {
  177269. tdist = (x - maxc0) * C0_SCALE;
  177270. max_dist = tdist*tdist;
  177271. } else {
  177272. tdist = (x - minc0) * C0_SCALE;
  177273. max_dist = tdist*tdist;
  177274. }
  177275. }
  177276. x = GETJSAMPLE(cinfo->colormap[1][i]);
  177277. if (x < minc1) {
  177278. tdist = (x - minc1) * C1_SCALE;
  177279. min_dist += tdist*tdist;
  177280. tdist = (x - maxc1) * C1_SCALE;
  177281. max_dist += tdist*tdist;
  177282. } else if (x > maxc1) {
  177283. tdist = (x - maxc1) * C1_SCALE;
  177284. min_dist += tdist*tdist;
  177285. tdist = (x - minc1) * C1_SCALE;
  177286. max_dist += tdist*tdist;
  177287. } else {
  177288. /* within cell range so no contribution to min_dist */
  177289. if (x <= centerc1) {
  177290. tdist = (x - maxc1) * C1_SCALE;
  177291. max_dist += tdist*tdist;
  177292. } else {
  177293. tdist = (x - minc1) * C1_SCALE;
  177294. max_dist += tdist*tdist;
  177295. }
  177296. }
  177297. x = GETJSAMPLE(cinfo->colormap[2][i]);
  177298. if (x < minc2) {
  177299. tdist = (x - minc2) * C2_SCALE;
  177300. min_dist += tdist*tdist;
  177301. tdist = (x - maxc2) * C2_SCALE;
  177302. max_dist += tdist*tdist;
  177303. } else if (x > maxc2) {
  177304. tdist = (x - maxc2) * C2_SCALE;
  177305. min_dist += tdist*tdist;
  177306. tdist = (x - minc2) * C2_SCALE;
  177307. max_dist += tdist*tdist;
  177308. } else {
  177309. /* within cell range so no contribution to min_dist */
  177310. if (x <= centerc2) {
  177311. tdist = (x - maxc2) * C2_SCALE;
  177312. max_dist += tdist*tdist;
  177313. } else {
  177314. tdist = (x - minc2) * C2_SCALE;
  177315. max_dist += tdist*tdist;
  177316. }
  177317. }
  177318. mindist[i] = min_dist; /* save away the results */
  177319. if (max_dist < minmaxdist)
  177320. minmaxdist = max_dist;
  177321. }
  177322. /* Now we know that no cell in the update box is more than minmaxdist
  177323. * away from some colormap entry. Therefore, only colors that are
  177324. * within minmaxdist of some part of the box need be considered.
  177325. */
  177326. ncolors = 0;
  177327. for (i = 0; i < numcolors; i++) {
  177328. if (mindist[i] <= minmaxdist)
  177329. colorlist[ncolors++] = (JSAMPLE) i;
  177330. }
  177331. return ncolors;
  177332. }
  177333. LOCAL(void)
  177334. find_best_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  177335. int numcolors, JSAMPLE colorlist[], JSAMPLE bestcolor[])
  177336. /* Find the closest colormap entry for each cell in the update box,
  177337. * given the list of candidate colors prepared by find_nearby_colors.
  177338. * Return the indexes of the closest entries in the bestcolor[] array.
  177339. * This routine uses Thomas' incremental distance calculation method to
  177340. * find the distance from a colormap entry to successive cells in the box.
  177341. */
  177342. {
  177343. int ic0, ic1, ic2;
  177344. int i, icolor;
  177345. register INT32 * bptr; /* pointer into bestdist[] array */
  177346. JSAMPLE * cptr; /* pointer into bestcolor[] array */
  177347. INT32 dist0, dist1; /* initial distance values */
  177348. register INT32 dist2; /* current distance in inner loop */
  177349. INT32 xx0, xx1; /* distance increments */
  177350. register INT32 xx2;
  177351. INT32 inc0, inc1, inc2; /* initial values for increments */
  177352. /* This array holds the distance to the nearest-so-far color for each cell */
  177353. INT32 bestdist[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  177354. /* Initialize best-distance for each cell of the update box */
  177355. bptr = bestdist;
  177356. for (i = BOX_C0_ELEMS*BOX_C1_ELEMS*BOX_C2_ELEMS-1; i >= 0; i--)
  177357. *bptr++ = 0x7FFFFFFFL;
  177358. /* For each color selected by find_nearby_colors,
  177359. * compute its distance to the center of each cell in the box.
  177360. * If that's less than best-so-far, update best distance and color number.
  177361. */
  177362. /* Nominal steps between cell centers ("x" in Thomas article) */
  177363. #define STEP_C0 ((1 << C0_SHIFT) * C0_SCALE)
  177364. #define STEP_C1 ((1 << C1_SHIFT) * C1_SCALE)
  177365. #define STEP_C2 ((1 << C2_SHIFT) * C2_SCALE)
  177366. for (i = 0; i < numcolors; i++) {
  177367. icolor = GETJSAMPLE(colorlist[i]);
  177368. /* Compute (square of) distance from minc0/c1/c2 to this color */
  177369. inc0 = (minc0 - GETJSAMPLE(cinfo->colormap[0][icolor])) * C0_SCALE;
  177370. dist0 = inc0*inc0;
  177371. inc1 = (minc1 - GETJSAMPLE(cinfo->colormap[1][icolor])) * C1_SCALE;
  177372. dist0 += inc1*inc1;
  177373. inc2 = (minc2 - GETJSAMPLE(cinfo->colormap[2][icolor])) * C2_SCALE;
  177374. dist0 += inc2*inc2;
  177375. /* Form the initial difference increments */
  177376. inc0 = inc0 * (2 * STEP_C0) + STEP_C0 * STEP_C0;
  177377. inc1 = inc1 * (2 * STEP_C1) + STEP_C1 * STEP_C1;
  177378. inc2 = inc2 * (2 * STEP_C2) + STEP_C2 * STEP_C2;
  177379. /* Now loop over all cells in box, updating distance per Thomas method */
  177380. bptr = bestdist;
  177381. cptr = bestcolor;
  177382. xx0 = inc0;
  177383. for (ic0 = BOX_C0_ELEMS-1; ic0 >= 0; ic0--) {
  177384. dist1 = dist0;
  177385. xx1 = inc1;
  177386. for (ic1 = BOX_C1_ELEMS-1; ic1 >= 0; ic1--) {
  177387. dist2 = dist1;
  177388. xx2 = inc2;
  177389. for (ic2 = BOX_C2_ELEMS-1; ic2 >= 0; ic2--) {
  177390. if (dist2 < *bptr) {
  177391. *bptr = dist2;
  177392. *cptr = (JSAMPLE) icolor;
  177393. }
  177394. dist2 += xx2;
  177395. xx2 += 2 * STEP_C2 * STEP_C2;
  177396. bptr++;
  177397. cptr++;
  177398. }
  177399. dist1 += xx1;
  177400. xx1 += 2 * STEP_C1 * STEP_C1;
  177401. }
  177402. dist0 += xx0;
  177403. xx0 += 2 * STEP_C0 * STEP_C0;
  177404. }
  177405. }
  177406. }
  177407. LOCAL(void)
  177408. fill_inverse_cmap (j_decompress_ptr cinfo, int c0, int c1, int c2)
  177409. /* Fill the inverse-colormap entries in the update box that contains */
  177410. /* histogram cell c0/c1/c2. (Only that one cell MUST be filled, but */
  177411. /* we can fill as many others as we wish.) */
  177412. {
  177413. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177414. hist3d histogram = cquantize->histogram;
  177415. int minc0, minc1, minc2; /* lower left corner of update box */
  177416. int ic0, ic1, ic2;
  177417. register JSAMPLE * cptr; /* pointer into bestcolor[] array */
  177418. register histptr cachep; /* pointer into main cache array */
  177419. /* This array lists the candidate colormap indexes. */
  177420. JSAMPLE colorlist[MAXNUMCOLORS];
  177421. int numcolors; /* number of candidate colors */
  177422. /* This array holds the actually closest colormap index for each cell. */
  177423. JSAMPLE bestcolor[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  177424. /* Convert cell coordinates to update box ID */
  177425. c0 >>= BOX_C0_LOG;
  177426. c1 >>= BOX_C1_LOG;
  177427. c2 >>= BOX_C2_LOG;
  177428. /* Compute true coordinates of update box's origin corner.
  177429. * Actually we compute the coordinates of the center of the corner
  177430. * histogram cell, which are the lower bounds of the volume we care about.
  177431. */
  177432. minc0 = (c0 << BOX_C0_SHIFT) + ((1 << C0_SHIFT) >> 1);
  177433. minc1 = (c1 << BOX_C1_SHIFT) + ((1 << C1_SHIFT) >> 1);
  177434. minc2 = (c2 << BOX_C2_SHIFT) + ((1 << C2_SHIFT) >> 1);
  177435. /* Determine which colormap entries are close enough to be candidates
  177436. * for the nearest entry to some cell in the update box.
  177437. */
  177438. numcolors = find_nearby_colors(cinfo, minc0, minc1, minc2, colorlist);
  177439. /* Determine the actually nearest colors. */
  177440. find_best_colors(cinfo, minc0, minc1, minc2, numcolors, colorlist,
  177441. bestcolor);
  177442. /* Save the best color numbers (plus 1) in the main cache array */
  177443. c0 <<= BOX_C0_LOG; /* convert ID back to base cell indexes */
  177444. c1 <<= BOX_C1_LOG;
  177445. c2 <<= BOX_C2_LOG;
  177446. cptr = bestcolor;
  177447. for (ic0 = 0; ic0 < BOX_C0_ELEMS; ic0++) {
  177448. for (ic1 = 0; ic1 < BOX_C1_ELEMS; ic1++) {
  177449. cachep = & histogram[c0+ic0][c1+ic1][c2];
  177450. for (ic2 = 0; ic2 < BOX_C2_ELEMS; ic2++) {
  177451. *cachep++ = (histcell) (GETJSAMPLE(*cptr++) + 1);
  177452. }
  177453. }
  177454. }
  177455. }
  177456. /*
  177457. * Map some rows of pixels to the output colormapped representation.
  177458. */
  177459. METHODDEF(void)
  177460. pass2_no_dither (j_decompress_ptr cinfo,
  177461. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  177462. /* This version performs no dithering */
  177463. {
  177464. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177465. hist3d histogram = cquantize->histogram;
  177466. register JSAMPROW inptr, outptr;
  177467. register histptr cachep;
  177468. register int c0, c1, c2;
  177469. int row;
  177470. JDIMENSION col;
  177471. JDIMENSION width = cinfo->output_width;
  177472. for (row = 0; row < num_rows; row++) {
  177473. inptr = input_buf[row];
  177474. outptr = output_buf[row];
  177475. for (col = width; col > 0; col--) {
  177476. /* get pixel value and index into the cache */
  177477. c0 = GETJSAMPLE(*inptr++) >> C0_SHIFT;
  177478. c1 = GETJSAMPLE(*inptr++) >> C1_SHIFT;
  177479. c2 = GETJSAMPLE(*inptr++) >> C2_SHIFT;
  177480. cachep = & histogram[c0][c1][c2];
  177481. /* If we have not seen this color before, find nearest colormap entry */
  177482. /* and update the cache */
  177483. if (*cachep == 0)
  177484. fill_inverse_cmap(cinfo, c0,c1,c2);
  177485. /* Now emit the colormap index for this cell */
  177486. *outptr++ = (JSAMPLE) (*cachep - 1);
  177487. }
  177488. }
  177489. }
  177490. METHODDEF(void)
  177491. pass2_fs_dither (j_decompress_ptr cinfo,
  177492. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  177493. /* This version performs Floyd-Steinberg dithering */
  177494. {
  177495. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177496. hist3d histogram = cquantize->histogram;
  177497. register LOCFSERROR cur0, cur1, cur2; /* current error or pixel value */
  177498. LOCFSERROR belowerr0, belowerr1, belowerr2; /* error for pixel below cur */
  177499. LOCFSERROR bpreverr0, bpreverr1, bpreverr2; /* error for below/prev col */
  177500. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  177501. JSAMPROW inptr; /* => current input pixel */
  177502. JSAMPROW outptr; /* => current output pixel */
  177503. histptr cachep;
  177504. int dir; /* +1 or -1 depending on direction */
  177505. int dir3; /* 3*dir, for advancing inptr & errorptr */
  177506. int row;
  177507. JDIMENSION col;
  177508. JDIMENSION width = cinfo->output_width;
  177509. JSAMPLE *range_limit = cinfo->sample_range_limit;
  177510. int *error_limit = cquantize->error_limiter;
  177511. JSAMPROW colormap0 = cinfo->colormap[0];
  177512. JSAMPROW colormap1 = cinfo->colormap[1];
  177513. JSAMPROW colormap2 = cinfo->colormap[2];
  177514. SHIFT_TEMPS
  177515. for (row = 0; row < num_rows; row++) {
  177516. inptr = input_buf[row];
  177517. outptr = output_buf[row];
  177518. if (cquantize->on_odd_row) {
  177519. /* work right to left in this row */
  177520. inptr += (width-1) * 3; /* so point to rightmost pixel */
  177521. outptr += width-1;
  177522. dir = -1;
  177523. dir3 = -3;
  177524. errorptr = cquantize->fserrors + (width+1)*3; /* => entry after last column */
  177525. cquantize->on_odd_row = FALSE; /* flip for next time */
  177526. } else {
  177527. /* work left to right in this row */
  177528. dir = 1;
  177529. dir3 = 3;
  177530. errorptr = cquantize->fserrors; /* => entry before first real column */
  177531. cquantize->on_odd_row = TRUE; /* flip for next time */
  177532. }
  177533. /* Preset error values: no error propagated to first pixel from left */
  177534. cur0 = cur1 = cur2 = 0;
  177535. /* and no error propagated to row below yet */
  177536. belowerr0 = belowerr1 = belowerr2 = 0;
  177537. bpreverr0 = bpreverr1 = bpreverr2 = 0;
  177538. for (col = width; col > 0; col--) {
  177539. /* curN holds the error propagated from the previous pixel on the
  177540. * current line. Add the error propagated from the previous line
  177541. * to form the complete error correction term for this pixel, and
  177542. * round the error term (which is expressed * 16) to an integer.
  177543. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  177544. * for either sign of the error value.
  177545. * Note: errorptr points to *previous* column's array entry.
  177546. */
  177547. cur0 = RIGHT_SHIFT(cur0 + errorptr[dir3+0] + 8, 4);
  177548. cur1 = RIGHT_SHIFT(cur1 + errorptr[dir3+1] + 8, 4);
  177549. cur2 = RIGHT_SHIFT(cur2 + errorptr[dir3+2] + 8, 4);
  177550. /* Limit the error using transfer function set by init_error_limit.
  177551. * See comments with init_error_limit for rationale.
  177552. */
  177553. cur0 = error_limit[cur0];
  177554. cur1 = error_limit[cur1];
  177555. cur2 = error_limit[cur2];
  177556. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  177557. * The maximum error is +- MAXJSAMPLE (or less with error limiting);
  177558. * this sets the required size of the range_limit array.
  177559. */
  177560. cur0 += GETJSAMPLE(inptr[0]);
  177561. cur1 += GETJSAMPLE(inptr[1]);
  177562. cur2 += GETJSAMPLE(inptr[2]);
  177563. cur0 = GETJSAMPLE(range_limit[cur0]);
  177564. cur1 = GETJSAMPLE(range_limit[cur1]);
  177565. cur2 = GETJSAMPLE(range_limit[cur2]);
  177566. /* Index into the cache with adjusted pixel value */
  177567. cachep = & histogram[cur0>>C0_SHIFT][cur1>>C1_SHIFT][cur2>>C2_SHIFT];
  177568. /* If we have not seen this color before, find nearest colormap */
  177569. /* entry and update the cache */
  177570. if (*cachep == 0)
  177571. fill_inverse_cmap(cinfo, cur0>>C0_SHIFT,cur1>>C1_SHIFT,cur2>>C2_SHIFT);
  177572. /* Now emit the colormap index for this cell */
  177573. { register int pixcode = *cachep - 1;
  177574. *outptr = (JSAMPLE) pixcode;
  177575. /* Compute representation error for this pixel */
  177576. cur0 -= GETJSAMPLE(colormap0[pixcode]);
  177577. cur1 -= GETJSAMPLE(colormap1[pixcode]);
  177578. cur2 -= GETJSAMPLE(colormap2[pixcode]);
  177579. }
  177580. /* Compute error fractions to be propagated to adjacent pixels.
  177581. * Add these into the running sums, and simultaneously shift the
  177582. * next-line error sums left by 1 column.
  177583. */
  177584. { register LOCFSERROR bnexterr, delta;
  177585. bnexterr = cur0; /* Process component 0 */
  177586. delta = cur0 * 2;
  177587. cur0 += delta; /* form error * 3 */
  177588. errorptr[0] = (FSERROR) (bpreverr0 + cur0);
  177589. cur0 += delta; /* form error * 5 */
  177590. bpreverr0 = belowerr0 + cur0;
  177591. belowerr0 = bnexterr;
  177592. cur0 += delta; /* form error * 7 */
  177593. bnexterr = cur1; /* Process component 1 */
  177594. delta = cur1 * 2;
  177595. cur1 += delta; /* form error * 3 */
  177596. errorptr[1] = (FSERROR) (bpreverr1 + cur1);
  177597. cur1 += delta; /* form error * 5 */
  177598. bpreverr1 = belowerr1 + cur1;
  177599. belowerr1 = bnexterr;
  177600. cur1 += delta; /* form error * 7 */
  177601. bnexterr = cur2; /* Process component 2 */
  177602. delta = cur2 * 2;
  177603. cur2 += delta; /* form error * 3 */
  177604. errorptr[2] = (FSERROR) (bpreverr2 + cur2);
  177605. cur2 += delta; /* form error * 5 */
  177606. bpreverr2 = belowerr2 + cur2;
  177607. belowerr2 = bnexterr;
  177608. cur2 += delta; /* form error * 7 */
  177609. }
  177610. /* At this point curN contains the 7/16 error value to be propagated
  177611. * to the next pixel on the current line, and all the errors for the
  177612. * next line have been shifted over. We are therefore ready to move on.
  177613. */
  177614. inptr += dir3; /* Advance pixel pointers to next column */
  177615. outptr += dir;
  177616. errorptr += dir3; /* advance errorptr to current column */
  177617. }
  177618. /* Post-loop cleanup: we must unload the final error values into the
  177619. * final fserrors[] entry. Note we need not unload belowerrN because
  177620. * it is for the dummy column before or after the actual array.
  177621. */
  177622. errorptr[0] = (FSERROR) bpreverr0; /* unload prev errs into array */
  177623. errorptr[1] = (FSERROR) bpreverr1;
  177624. errorptr[2] = (FSERROR) bpreverr2;
  177625. }
  177626. }
  177627. /*
  177628. * Initialize the error-limiting transfer function (lookup table).
  177629. * The raw F-S error computation can potentially compute error values of up to
  177630. * +- MAXJSAMPLE. But we want the maximum correction applied to a pixel to be
  177631. * much less, otherwise obviously wrong pixels will be created. (Typical
  177632. * effects include weird fringes at color-area boundaries, isolated bright
  177633. * pixels in a dark area, etc.) The standard advice for avoiding this problem
  177634. * is to ensure that the "corners" of the color cube are allocated as output
  177635. * colors; then repeated errors in the same direction cannot cause cascading
  177636. * error buildup. However, that only prevents the error from getting
  177637. * completely out of hand; Aaron Giles reports that error limiting improves
  177638. * the results even with corner colors allocated.
  177639. * A simple clamping of the error values to about +- MAXJSAMPLE/8 works pretty
  177640. * well, but the smoother transfer function used below is even better. Thanks
  177641. * to Aaron Giles for this idea.
  177642. */
  177643. LOCAL(void)
  177644. init_error_limit (j_decompress_ptr cinfo)
  177645. /* Allocate and fill in the error_limiter table */
  177646. {
  177647. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177648. int * table;
  177649. int in, out;
  177650. table = (int *) (*cinfo->mem->alloc_small)
  177651. ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE*2+1) * SIZEOF(int));
  177652. table += MAXJSAMPLE; /* so can index -MAXJSAMPLE .. +MAXJSAMPLE */
  177653. cquantize->error_limiter = table;
  177654. #define STEPSIZE ((MAXJSAMPLE+1)/16)
  177655. /* Map errors 1:1 up to +- MAXJSAMPLE/16 */
  177656. out = 0;
  177657. for (in = 0; in < STEPSIZE; in++, out++) {
  177658. table[in] = out; table[-in] = -out;
  177659. }
  177660. /* Map errors 1:2 up to +- 3*MAXJSAMPLE/16 */
  177661. for (; in < STEPSIZE*3; in++, out += (in&1) ? 0 : 1) {
  177662. table[in] = out; table[-in] = -out;
  177663. }
  177664. /* Clamp the rest to final out value (which is (MAXJSAMPLE+1)/8) */
  177665. for (; in <= MAXJSAMPLE; in++) {
  177666. table[in] = out; table[-in] = -out;
  177667. }
  177668. #undef STEPSIZE
  177669. }
  177670. /*
  177671. * Finish up at the end of each pass.
  177672. */
  177673. METHODDEF(void)
  177674. finish_pass1 (j_decompress_ptr cinfo)
  177675. {
  177676. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177677. /* Select the representative colors and fill in cinfo->colormap */
  177678. cinfo->colormap = cquantize->sv_colormap;
  177679. select_colors(cinfo, cquantize->desired);
  177680. /* Force next pass to zero the color index table */
  177681. cquantize->needs_zeroed = TRUE;
  177682. }
  177683. METHODDEF(void)
  177684. finish_pass2 (j_decompress_ptr)
  177685. {
  177686. /* no work */
  177687. }
  177688. /*
  177689. * Initialize for each processing pass.
  177690. */
  177691. METHODDEF(void)
  177692. start_pass_2_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
  177693. {
  177694. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177695. hist3d histogram = cquantize->histogram;
  177696. int i;
  177697. /* Only F-S dithering or no dithering is supported. */
  177698. /* If user asks for ordered dither, give him F-S. */
  177699. if (cinfo->dither_mode != JDITHER_NONE)
  177700. cinfo->dither_mode = JDITHER_FS;
  177701. if (is_pre_scan) {
  177702. /* Set up method pointers */
  177703. cquantize->pub.color_quantize = prescan_quantize;
  177704. cquantize->pub.finish_pass = finish_pass1;
  177705. cquantize->needs_zeroed = TRUE; /* Always zero histogram */
  177706. } else {
  177707. /* Set up method pointers */
  177708. if (cinfo->dither_mode == JDITHER_FS)
  177709. cquantize->pub.color_quantize = pass2_fs_dither;
  177710. else
  177711. cquantize->pub.color_quantize = pass2_no_dither;
  177712. cquantize->pub.finish_pass = finish_pass2;
  177713. /* Make sure color count is acceptable */
  177714. i = cinfo->actual_number_of_colors;
  177715. if (i < 1)
  177716. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 1);
  177717. if (i > MAXNUMCOLORS)
  177718. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  177719. if (cinfo->dither_mode == JDITHER_FS) {
  177720. size_t arraysize = (size_t) ((cinfo->output_width + 2) *
  177721. (3 * SIZEOF(FSERROR)));
  177722. /* Allocate Floyd-Steinberg workspace if we didn't already. */
  177723. if (cquantize->fserrors == NULL)
  177724. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  177725. ((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  177726. /* Initialize the propagated errors to zero. */
  177727. jzero_far((void FAR *) cquantize->fserrors, arraysize);
  177728. /* Make the error-limit table if we didn't already. */
  177729. if (cquantize->error_limiter == NULL)
  177730. init_error_limit(cinfo);
  177731. cquantize->on_odd_row = FALSE;
  177732. }
  177733. }
  177734. /* Zero the histogram or inverse color map, if necessary */
  177735. if (cquantize->needs_zeroed) {
  177736. for (i = 0; i < HIST_C0_ELEMS; i++) {
  177737. jzero_far((void FAR *) histogram[i],
  177738. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  177739. }
  177740. cquantize->needs_zeroed = FALSE;
  177741. }
  177742. }
  177743. /*
  177744. * Switch to a new external colormap between output passes.
  177745. */
  177746. METHODDEF(void)
  177747. new_color_map_2_quant (j_decompress_ptr cinfo)
  177748. {
  177749. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177750. /* Reset the inverse color map */
  177751. cquantize->needs_zeroed = TRUE;
  177752. }
  177753. /*
  177754. * Module initialization routine for 2-pass color quantization.
  177755. */
  177756. GLOBAL(void)
  177757. jinit_2pass_quantizer (j_decompress_ptr cinfo)
  177758. {
  177759. my_cquantize_ptr2 cquantize;
  177760. int i;
  177761. cquantize = (my_cquantize_ptr2)
  177762. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177763. SIZEOF(my_cquantizer2));
  177764. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  177765. cquantize->pub.start_pass = start_pass_2_quant;
  177766. cquantize->pub.new_color_map = new_color_map_2_quant;
  177767. cquantize->fserrors = NULL; /* flag optional arrays not allocated */
  177768. cquantize->error_limiter = NULL;
  177769. /* Make sure jdmaster didn't give me a case I can't handle */
  177770. if (cinfo->out_color_components != 3)
  177771. ERREXIT(cinfo, JERR_NOTIMPL);
  177772. /* Allocate the histogram/inverse colormap storage */
  177773. cquantize->histogram = (hist3d) (*cinfo->mem->alloc_small)
  177774. ((j_common_ptr) cinfo, JPOOL_IMAGE, HIST_C0_ELEMS * SIZEOF(hist2d));
  177775. for (i = 0; i < HIST_C0_ELEMS; i++) {
  177776. cquantize->histogram[i] = (hist2d) (*cinfo->mem->alloc_large)
  177777. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177778. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  177779. }
  177780. cquantize->needs_zeroed = TRUE; /* histogram is garbage now */
  177781. /* Allocate storage for the completed colormap, if required.
  177782. * We do this now since it is FAR storage and may affect
  177783. * the memory manager's space calculations.
  177784. */
  177785. if (cinfo->enable_2pass_quant) {
  177786. /* Make sure color count is acceptable */
  177787. int desired = cinfo->desired_number_of_colors;
  177788. /* Lower bound on # of colors ... somewhat arbitrary as long as > 0 */
  177789. if (desired < 8)
  177790. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 8);
  177791. /* Make sure colormap indexes can be represented by JSAMPLEs */
  177792. if (desired > MAXNUMCOLORS)
  177793. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  177794. cquantize->sv_colormap = (*cinfo->mem->alloc_sarray)
  177795. ((j_common_ptr) cinfo,JPOOL_IMAGE, (JDIMENSION) desired, (JDIMENSION) 3);
  177796. cquantize->desired = desired;
  177797. } else
  177798. cquantize->sv_colormap = NULL;
  177799. /* Only F-S dithering or no dithering is supported. */
  177800. /* If user asks for ordered dither, give him F-S. */
  177801. if (cinfo->dither_mode != JDITHER_NONE)
  177802. cinfo->dither_mode = JDITHER_FS;
  177803. /* Allocate Floyd-Steinberg workspace if necessary.
  177804. * This isn't really needed until pass 2, but again it is FAR storage.
  177805. * Although we will cope with a later change in dither_mode,
  177806. * we do not promise to honor max_memory_to_use if dither_mode changes.
  177807. */
  177808. if (cinfo->dither_mode == JDITHER_FS) {
  177809. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  177810. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177811. (size_t) ((cinfo->output_width + 2) * (3 * SIZEOF(FSERROR))));
  177812. /* Might as well create the error-limiting table too. */
  177813. init_error_limit(cinfo);
  177814. }
  177815. }
  177816. #endif /* QUANT_2PASS_SUPPORTED */
  177817. /*** End of inlined file: jquant2.c ***/
  177818. /*** Start of inlined file: jutils.c ***/
  177819. #define JPEG_INTERNALS
  177820. /*
  177821. * jpeg_zigzag_order[i] is the zigzag-order position of the i'th element
  177822. * of a DCT block read in natural order (left to right, top to bottom).
  177823. */
  177824. #if 0 /* This table is not actually needed in v6a */
  177825. const int jpeg_zigzag_order[DCTSIZE2] = {
  177826. 0, 1, 5, 6, 14, 15, 27, 28,
  177827. 2, 4, 7, 13, 16, 26, 29, 42,
  177828. 3, 8, 12, 17, 25, 30, 41, 43,
  177829. 9, 11, 18, 24, 31, 40, 44, 53,
  177830. 10, 19, 23, 32, 39, 45, 52, 54,
  177831. 20, 22, 33, 38, 46, 51, 55, 60,
  177832. 21, 34, 37, 47, 50, 56, 59, 61,
  177833. 35, 36, 48, 49, 57, 58, 62, 63
  177834. };
  177835. #endif
  177836. /*
  177837. * jpeg_natural_order[i] is the natural-order position of the i'th element
  177838. * of zigzag order.
  177839. *
  177840. * When reading corrupted data, the Huffman decoders could attempt
  177841. * to reference an entry beyond the end of this array (if the decoded
  177842. * zero run length reaches past the end of the block). To prevent
  177843. * wild stores without adding an inner-loop test, we put some extra
  177844. * "63"s after the real entries. This will cause the extra coefficient
  177845. * to be stored in location 63 of the block, not somewhere random.
  177846. * The worst case would be a run-length of 15, which means we need 16
  177847. * fake entries.
  177848. */
  177849. const int jpeg_natural_order[DCTSIZE2+16] = {
  177850. 0, 1, 8, 16, 9, 2, 3, 10,
  177851. 17, 24, 32, 25, 18, 11, 4, 5,
  177852. 12, 19, 26, 33, 40, 48, 41, 34,
  177853. 27, 20, 13, 6, 7, 14, 21, 28,
  177854. 35, 42, 49, 56, 57, 50, 43, 36,
  177855. 29, 22, 15, 23, 30, 37, 44, 51,
  177856. 58, 59, 52, 45, 38, 31, 39, 46,
  177857. 53, 60, 61, 54, 47, 55, 62, 63,
  177858. 63, 63, 63, 63, 63, 63, 63, 63, /* extra entries for safety in decoder */
  177859. 63, 63, 63, 63, 63, 63, 63, 63
  177860. };
  177861. /*
  177862. * Arithmetic utilities
  177863. */
  177864. GLOBAL(long)
  177865. jdiv_round_up (long a, long b)
  177866. /* Compute a/b rounded up to next integer, ie, ceil(a/b) */
  177867. /* Assumes a >= 0, b > 0 */
  177868. {
  177869. return (a + b - 1L) / b;
  177870. }
  177871. GLOBAL(long)
  177872. jround_up (long a, long b)
  177873. /* Compute a rounded up to next multiple of b, ie, ceil(a/b)*b */
  177874. /* Assumes a >= 0, b > 0 */
  177875. {
  177876. a += b - 1L;
  177877. return a - (a % b);
  177878. }
  177879. /* On normal machines we can apply MEMCOPY() and MEMZERO() to sample arrays
  177880. * and coefficient-block arrays. This won't work on 80x86 because the arrays
  177881. * are FAR and we're assuming a small-pointer memory model. However, some
  177882. * DOS compilers provide far-pointer versions of memcpy() and memset() even
  177883. * in the small-model libraries. These will be used if USE_FMEM is defined.
  177884. * Otherwise, the routines below do it the hard way. (The performance cost
  177885. * is not all that great, because these routines aren't very heavily used.)
  177886. */
  177887. #ifndef NEED_FAR_POINTERS /* normal case, same as regular macros */
  177888. #define FMEMCOPY(dest,src,size) MEMCOPY(dest,src,size)
  177889. #define FMEMZERO(target,size) MEMZERO(target,size)
  177890. #else /* 80x86 case, define if we can */
  177891. #ifdef USE_FMEM
  177892. #define FMEMCOPY(dest,src,size) _fmemcpy((void FAR *)(dest), (const void FAR *)(src), (size_t)(size))
  177893. #define FMEMZERO(target,size) _fmemset((void FAR *)(target), 0, (size_t)(size))
  177894. #endif
  177895. #endif
  177896. GLOBAL(void)
  177897. jcopy_sample_rows (JSAMPARRAY input_array, int source_row,
  177898. JSAMPARRAY output_array, int dest_row,
  177899. int num_rows, JDIMENSION num_cols)
  177900. /* Copy some rows of samples from one place to another.
  177901. * num_rows rows are copied from input_array[source_row++]
  177902. * to output_array[dest_row++]; these areas may overlap for duplication.
  177903. * The source and destination arrays must be at least as wide as num_cols.
  177904. */
  177905. {
  177906. register JSAMPROW inptr, outptr;
  177907. #ifdef FMEMCOPY
  177908. register size_t count = (size_t) (num_cols * SIZEOF(JSAMPLE));
  177909. #else
  177910. register JDIMENSION count;
  177911. #endif
  177912. register int row;
  177913. input_array += source_row;
  177914. output_array += dest_row;
  177915. for (row = num_rows; row > 0; row--) {
  177916. inptr = *input_array++;
  177917. outptr = *output_array++;
  177918. #ifdef FMEMCOPY
  177919. FMEMCOPY(outptr, inptr, count);
  177920. #else
  177921. for (count = num_cols; count > 0; count--)
  177922. *outptr++ = *inptr++; /* needn't bother with GETJSAMPLE() here */
  177923. #endif
  177924. }
  177925. }
  177926. GLOBAL(void)
  177927. jcopy_block_row (JBLOCKROW input_row, JBLOCKROW output_row,
  177928. JDIMENSION num_blocks)
  177929. /* Copy a row of coefficient blocks from one place to another. */
  177930. {
  177931. #ifdef FMEMCOPY
  177932. FMEMCOPY(output_row, input_row, num_blocks * (DCTSIZE2 * SIZEOF(JCOEF)));
  177933. #else
  177934. register JCOEFPTR inptr, outptr;
  177935. register long count;
  177936. inptr = (JCOEFPTR) input_row;
  177937. outptr = (JCOEFPTR) output_row;
  177938. for (count = (long) num_blocks * DCTSIZE2; count > 0; count--) {
  177939. *outptr++ = *inptr++;
  177940. }
  177941. #endif
  177942. }
  177943. GLOBAL(void)
  177944. jzero_far (void FAR * target, size_t bytestozero)
  177945. /* Zero out a chunk of FAR memory. */
  177946. /* This might be sample-array data, block-array data, or alloc_large data. */
  177947. {
  177948. #ifdef FMEMZERO
  177949. FMEMZERO(target, bytestozero);
  177950. #else
  177951. register char FAR * ptr = (char FAR *) target;
  177952. register size_t count;
  177953. for (count = bytestozero; count > 0; count--) {
  177954. *ptr++ = 0;
  177955. }
  177956. #endif
  177957. }
  177958. /*** End of inlined file: jutils.c ***/
  177959. /*** Start of inlined file: transupp.c ***/
  177960. /* Although this file really shouldn't have access to the library internals,
  177961. * it's helpful to let it call jround_up() and jcopy_block_row().
  177962. */
  177963. #define JPEG_INTERNALS
  177964. /*** Start of inlined file: transupp.h ***/
  177965. /* If you happen not to want the image transform support, disable it here */
  177966. #ifndef TRANSFORMS_SUPPORTED
  177967. #define TRANSFORMS_SUPPORTED 1 /* 0 disables transform code */
  177968. #endif
  177969. /* Short forms of external names for systems with brain-damaged linkers. */
  177970. #ifdef NEED_SHORT_EXTERNAL_NAMES
  177971. #define jtransform_request_workspace jTrRequest
  177972. #define jtransform_adjust_parameters jTrAdjust
  177973. #define jtransform_execute_transformation jTrExec
  177974. #define jcopy_markers_setup jCMrkSetup
  177975. #define jcopy_markers_execute jCMrkExec
  177976. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  177977. /*
  177978. * Codes for supported types of image transformations.
  177979. */
  177980. typedef enum {
  177981. JXFORM_NONE, /* no transformation */
  177982. JXFORM_FLIP_H, /* horizontal flip */
  177983. JXFORM_FLIP_V, /* vertical flip */
  177984. JXFORM_TRANSPOSE, /* transpose across UL-to-LR axis */
  177985. JXFORM_TRANSVERSE, /* transpose across UR-to-LL axis */
  177986. JXFORM_ROT_90, /* 90-degree clockwise rotation */
  177987. JXFORM_ROT_180, /* 180-degree rotation */
  177988. JXFORM_ROT_270 /* 270-degree clockwise (or 90 ccw) */
  177989. } JXFORM_CODE;
  177990. /*
  177991. * Although rotating and flipping data expressed as DCT coefficients is not
  177992. * hard, there is an asymmetry in the JPEG format specification for images
  177993. * whose dimensions aren't multiples of the iMCU size. The right and bottom
  177994. * image edges are padded out to the next iMCU boundary with junk data; but
  177995. * no padding is possible at the top and left edges. If we were to flip
  177996. * the whole image including the pad data, then pad garbage would become
  177997. * visible at the top and/or left, and real pixels would disappear into the
  177998. * pad margins --- perhaps permanently, since encoders & decoders may not
  177999. * bother to preserve DCT blocks that appear to be completely outside the
  178000. * nominal image area. So, we have to exclude any partial iMCUs from the
  178001. * basic transformation.
  178002. *
  178003. * Transpose is the only transformation that can handle partial iMCUs at the
  178004. * right and bottom edges completely cleanly. flip_h can flip partial iMCUs
  178005. * at the bottom, but leaves any partial iMCUs at the right edge untouched.
  178006. * Similarly flip_v leaves any partial iMCUs at the bottom edge untouched.
  178007. * The other transforms are defined as combinations of these basic transforms
  178008. * and process edge blocks in a way that preserves the equivalence.
  178009. *
  178010. * The "trim" option causes untransformable partial iMCUs to be dropped;
  178011. * this is not strictly lossless, but it usually gives the best-looking
  178012. * result for odd-size images. Note that when this option is active,
  178013. * the expected mathematical equivalences between the transforms may not hold.
  178014. * (For example, -rot 270 -trim trims only the bottom edge, but -rot 90 -trim
  178015. * followed by -rot 180 -trim trims both edges.)
  178016. *
  178017. * We also offer a "force to grayscale" option, which simply discards the
  178018. * chrominance channels of a YCbCr image. This is lossless in the sense that
  178019. * the luminance channel is preserved exactly. It's not the same kind of
  178020. * thing as the rotate/flip transformations, but it's convenient to handle it
  178021. * as part of this package, mainly because the transformation routines have to
  178022. * be aware of the option to know how many components to work on.
  178023. */
  178024. typedef struct {
  178025. /* Options: set by caller */
  178026. JXFORM_CODE transform; /* image transform operator */
  178027. boolean trim; /* if TRUE, trim partial MCUs as needed */
  178028. boolean force_grayscale; /* if TRUE, convert color image to grayscale */
  178029. /* Internal workspace: caller should not touch these */
  178030. int num_components; /* # of components in workspace */
  178031. jvirt_barray_ptr * workspace_coef_arrays; /* workspace for transformations */
  178032. } jpeg_transform_info;
  178033. #if TRANSFORMS_SUPPORTED
  178034. /* Request any required workspace */
  178035. EXTERN(void) jtransform_request_workspace
  178036. JPP((j_decompress_ptr srcinfo, jpeg_transform_info *info));
  178037. /* Adjust output image parameters */
  178038. EXTERN(jvirt_barray_ptr *) jtransform_adjust_parameters
  178039. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178040. jvirt_barray_ptr *src_coef_arrays,
  178041. jpeg_transform_info *info));
  178042. /* Execute the actual transformation, if any */
  178043. EXTERN(void) jtransform_execute_transformation
  178044. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178045. jvirt_barray_ptr *src_coef_arrays,
  178046. jpeg_transform_info *info));
  178047. #endif /* TRANSFORMS_SUPPORTED */
  178048. /*
  178049. * Support for copying optional markers from source to destination file.
  178050. */
  178051. typedef enum {
  178052. JCOPYOPT_NONE, /* copy no optional markers */
  178053. JCOPYOPT_COMMENTS, /* copy only comment (COM) markers */
  178054. JCOPYOPT_ALL /* copy all optional markers */
  178055. } JCOPY_OPTION;
  178056. #define JCOPYOPT_DEFAULT JCOPYOPT_COMMENTS /* recommended default */
  178057. /* Setup decompression object to save desired markers in memory */
  178058. EXTERN(void) jcopy_markers_setup
  178059. JPP((j_decompress_ptr srcinfo, JCOPY_OPTION option));
  178060. /* Copy markers saved in the given source object to the destination object */
  178061. EXTERN(void) jcopy_markers_execute
  178062. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178063. JCOPY_OPTION option));
  178064. /*** End of inlined file: transupp.h ***/
  178065. /* My own external interface */
  178066. #if TRANSFORMS_SUPPORTED
  178067. /*
  178068. * Lossless image transformation routines. These routines work on DCT
  178069. * coefficient arrays and thus do not require any lossy decompression
  178070. * or recompression of the image.
  178071. * Thanks to Guido Vollbeding for the initial design and code of this feature.
  178072. *
  178073. * Horizontal flipping is done in-place, using a single top-to-bottom
  178074. * pass through the virtual source array. It will thus be much the
  178075. * fastest option for images larger than main memory.
  178076. *
  178077. * The other routines require a set of destination virtual arrays, so they
  178078. * need twice as much memory as jpegtran normally does. The destination
  178079. * arrays are always written in normal scan order (top to bottom) because
  178080. * the virtual array manager expects this. The source arrays will be scanned
  178081. * in the corresponding order, which means multiple passes through the source
  178082. * arrays for most of the transforms. That could result in much thrashing
  178083. * if the image is larger than main memory.
  178084. *
  178085. * Some notes about the operating environment of the individual transform
  178086. * routines:
  178087. * 1. Both the source and destination virtual arrays are allocated from the
  178088. * source JPEG object, and therefore should be manipulated by calling the
  178089. * source's memory manager.
  178090. * 2. The destination's component count should be used. It may be smaller
  178091. * than the source's when forcing to grayscale.
  178092. * 3. Likewise the destination's sampling factors should be used. When
  178093. * forcing to grayscale the destination's sampling factors will be all 1,
  178094. * and we may as well take that as the effective iMCU size.
  178095. * 4. When "trim" is in effect, the destination's dimensions will be the
  178096. * trimmed values but the source's will be untrimmed.
  178097. * 5. All the routines assume that the source and destination buffers are
  178098. * padded out to a full iMCU boundary. This is true, although for the
  178099. * source buffer it is an undocumented property of jdcoefct.c.
  178100. * Notes 2,3,4 boil down to this: generally we should use the destination's
  178101. * dimensions and ignore the source's.
  178102. */
  178103. LOCAL(void)
  178104. do_flip_h (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178105. jvirt_barray_ptr *src_coef_arrays)
  178106. /* Horizontal flip; done in-place, so no separate dest array is required */
  178107. {
  178108. JDIMENSION MCU_cols, comp_width, blk_x, blk_y;
  178109. int ci, k, offset_y;
  178110. JBLOCKARRAY buffer;
  178111. JCOEFPTR ptr1, ptr2;
  178112. JCOEF temp1, temp2;
  178113. jpeg_component_info *compptr;
  178114. /* Horizontal mirroring of DCT blocks is accomplished by swapping
  178115. * pairs of blocks in-place. Within a DCT block, we perform horizontal
  178116. * mirroring by changing the signs of odd-numbered columns.
  178117. * Partial iMCUs at the right edge are left untouched.
  178118. */
  178119. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  178120. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178121. compptr = dstinfo->comp_info + ci;
  178122. comp_width = MCU_cols * compptr->h_samp_factor;
  178123. for (blk_y = 0; blk_y < compptr->height_in_blocks;
  178124. blk_y += compptr->v_samp_factor) {
  178125. buffer = (*srcinfo->mem->access_virt_barray)
  178126. ((j_common_ptr) srcinfo, src_coef_arrays[ci], blk_y,
  178127. (JDIMENSION) compptr->v_samp_factor, TRUE);
  178128. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  178129. for (blk_x = 0; blk_x * 2 < comp_width; blk_x++) {
  178130. ptr1 = buffer[offset_y][blk_x];
  178131. ptr2 = buffer[offset_y][comp_width - blk_x - 1];
  178132. /* this unrolled loop doesn't need to know which row it's on... */
  178133. for (k = 0; k < DCTSIZE2; k += 2) {
  178134. temp1 = *ptr1; /* swap even column */
  178135. temp2 = *ptr2;
  178136. *ptr1++ = temp2;
  178137. *ptr2++ = temp1;
  178138. temp1 = *ptr1; /* swap odd column with sign change */
  178139. temp2 = *ptr2;
  178140. *ptr1++ = -temp2;
  178141. *ptr2++ = -temp1;
  178142. }
  178143. }
  178144. }
  178145. }
  178146. }
  178147. }
  178148. LOCAL(void)
  178149. do_flip_v (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178150. jvirt_barray_ptr *src_coef_arrays,
  178151. jvirt_barray_ptr *dst_coef_arrays)
  178152. /* Vertical flip */
  178153. {
  178154. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  178155. int ci, i, j, offset_y;
  178156. JBLOCKARRAY src_buffer, dst_buffer;
  178157. JBLOCKROW src_row_ptr, dst_row_ptr;
  178158. JCOEFPTR src_ptr, dst_ptr;
  178159. jpeg_component_info *compptr;
  178160. /* We output into a separate array because we can't touch different
  178161. * rows of the source virtual array simultaneously. Otherwise, this
  178162. * is a pretty straightforward analog of horizontal flip.
  178163. * Within a DCT block, vertical mirroring is done by changing the signs
  178164. * of odd-numbered rows.
  178165. * Partial iMCUs at the bottom edge are copied verbatim.
  178166. */
  178167. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  178168. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178169. compptr = dstinfo->comp_info + ci;
  178170. comp_height = MCU_rows * compptr->v_samp_factor;
  178171. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  178172. dst_blk_y += compptr->v_samp_factor) {
  178173. dst_buffer = (*srcinfo->mem->access_virt_barray)
  178174. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  178175. (JDIMENSION) compptr->v_samp_factor, TRUE);
  178176. if (dst_blk_y < comp_height) {
  178177. /* Row is within the mirrorable area. */
  178178. src_buffer = (*srcinfo->mem->access_virt_barray)
  178179. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  178180. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  178181. (JDIMENSION) compptr->v_samp_factor, FALSE);
  178182. } else {
  178183. /* Bottom-edge blocks will be copied verbatim. */
  178184. src_buffer = (*srcinfo->mem->access_virt_barray)
  178185. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  178186. (JDIMENSION) compptr->v_samp_factor, FALSE);
  178187. }
  178188. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  178189. if (dst_blk_y < comp_height) {
  178190. /* Row is within the mirrorable area. */
  178191. dst_row_ptr = dst_buffer[offset_y];
  178192. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  178193. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  178194. dst_blk_x++) {
  178195. dst_ptr = dst_row_ptr[dst_blk_x];
  178196. src_ptr = src_row_ptr[dst_blk_x];
  178197. for (i = 0; i < DCTSIZE; i += 2) {
  178198. /* copy even row */
  178199. for (j = 0; j < DCTSIZE; j++)
  178200. *dst_ptr++ = *src_ptr++;
  178201. /* copy odd row with sign change */
  178202. for (j = 0; j < DCTSIZE; j++)
  178203. *dst_ptr++ = - *src_ptr++;
  178204. }
  178205. }
  178206. } else {
  178207. /* Just copy row verbatim. */
  178208. jcopy_block_row(src_buffer[offset_y], dst_buffer[offset_y],
  178209. compptr->width_in_blocks);
  178210. }
  178211. }
  178212. }
  178213. }
  178214. }
  178215. LOCAL(void)
  178216. do_transpose (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178217. jvirt_barray_ptr *src_coef_arrays,
  178218. jvirt_barray_ptr *dst_coef_arrays)
  178219. /* Transpose source into destination */
  178220. {
  178221. JDIMENSION dst_blk_x, dst_blk_y;
  178222. int ci, i, j, offset_x, offset_y;
  178223. JBLOCKARRAY src_buffer, dst_buffer;
  178224. JCOEFPTR src_ptr, dst_ptr;
  178225. jpeg_component_info *compptr;
  178226. /* Transposing pixels within a block just requires transposing the
  178227. * DCT coefficients.
  178228. * Partial iMCUs at the edges require no special treatment; we simply
  178229. * process all the available DCT blocks for every component.
  178230. */
  178231. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178232. compptr = dstinfo->comp_info + ci;
  178233. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  178234. dst_blk_y += compptr->v_samp_factor) {
  178235. dst_buffer = (*srcinfo->mem->access_virt_barray)
  178236. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  178237. (JDIMENSION) compptr->v_samp_factor, TRUE);
  178238. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  178239. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  178240. dst_blk_x += compptr->h_samp_factor) {
  178241. src_buffer = (*srcinfo->mem->access_virt_barray)
  178242. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  178243. (JDIMENSION) compptr->h_samp_factor, FALSE);
  178244. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  178245. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  178246. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  178247. for (i = 0; i < DCTSIZE; i++)
  178248. for (j = 0; j < DCTSIZE; j++)
  178249. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  178250. }
  178251. }
  178252. }
  178253. }
  178254. }
  178255. }
  178256. LOCAL(void)
  178257. do_rot_90 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178258. jvirt_barray_ptr *src_coef_arrays,
  178259. jvirt_barray_ptr *dst_coef_arrays)
  178260. /* 90 degree rotation is equivalent to
  178261. * 1. Transposing the image;
  178262. * 2. Horizontal mirroring.
  178263. * These two steps are merged into a single processing routine.
  178264. */
  178265. {
  178266. JDIMENSION MCU_cols, comp_width, dst_blk_x, dst_blk_y;
  178267. int ci, i, j, offset_x, offset_y;
  178268. JBLOCKARRAY src_buffer, dst_buffer;
  178269. JCOEFPTR src_ptr, dst_ptr;
  178270. jpeg_component_info *compptr;
  178271. /* Because of the horizontal mirror step, we can't process partial iMCUs
  178272. * at the (output) right edge properly. They just get transposed and
  178273. * not mirrored.
  178274. */
  178275. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  178276. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178277. compptr = dstinfo->comp_info + ci;
  178278. comp_width = MCU_cols * compptr->h_samp_factor;
  178279. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  178280. dst_blk_y += compptr->v_samp_factor) {
  178281. dst_buffer = (*srcinfo->mem->access_virt_barray)
  178282. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  178283. (JDIMENSION) compptr->v_samp_factor, TRUE);
  178284. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  178285. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  178286. dst_blk_x += compptr->h_samp_factor) {
  178287. src_buffer = (*srcinfo->mem->access_virt_barray)
  178288. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  178289. (JDIMENSION) compptr->h_samp_factor, FALSE);
  178290. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  178291. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  178292. if (dst_blk_x < comp_width) {
  178293. /* Block is within the mirrorable area. */
  178294. dst_ptr = dst_buffer[offset_y]
  178295. [comp_width - dst_blk_x - offset_x - 1];
  178296. for (i = 0; i < DCTSIZE; i++) {
  178297. for (j = 0; j < DCTSIZE; j++)
  178298. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  178299. i++;
  178300. for (j = 0; j < DCTSIZE; j++)
  178301. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  178302. }
  178303. } else {
  178304. /* Edge blocks are transposed but not mirrored. */
  178305. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  178306. for (i = 0; i < DCTSIZE; i++)
  178307. for (j = 0; j < DCTSIZE; j++)
  178308. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  178309. }
  178310. }
  178311. }
  178312. }
  178313. }
  178314. }
  178315. }
  178316. LOCAL(void)
  178317. do_rot_270 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178318. jvirt_barray_ptr *src_coef_arrays,
  178319. jvirt_barray_ptr *dst_coef_arrays)
  178320. /* 270 degree rotation is equivalent to
  178321. * 1. Horizontal mirroring;
  178322. * 2. Transposing the image.
  178323. * These two steps are merged into a single processing routine.
  178324. */
  178325. {
  178326. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  178327. int ci, i, j, offset_x, offset_y;
  178328. JBLOCKARRAY src_buffer, dst_buffer;
  178329. JCOEFPTR src_ptr, dst_ptr;
  178330. jpeg_component_info *compptr;
  178331. /* Because of the horizontal mirror step, we can't process partial iMCUs
  178332. * at the (output) bottom edge properly. They just get transposed and
  178333. * not mirrored.
  178334. */
  178335. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  178336. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178337. compptr = dstinfo->comp_info + ci;
  178338. comp_height = MCU_rows * compptr->v_samp_factor;
  178339. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  178340. dst_blk_y += compptr->v_samp_factor) {
  178341. dst_buffer = (*srcinfo->mem->access_virt_barray)
  178342. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  178343. (JDIMENSION) compptr->v_samp_factor, TRUE);
  178344. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  178345. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  178346. dst_blk_x += compptr->h_samp_factor) {
  178347. src_buffer = (*srcinfo->mem->access_virt_barray)
  178348. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  178349. (JDIMENSION) compptr->h_samp_factor, FALSE);
  178350. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  178351. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  178352. if (dst_blk_y < comp_height) {
  178353. /* Block is within the mirrorable area. */
  178354. src_ptr = src_buffer[offset_x]
  178355. [comp_height - dst_blk_y - offset_y - 1];
  178356. for (i = 0; i < DCTSIZE; i++) {
  178357. for (j = 0; j < DCTSIZE; j++) {
  178358. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  178359. j++;
  178360. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  178361. }
  178362. }
  178363. } else {
  178364. /* Edge blocks are transposed but not mirrored. */
  178365. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  178366. for (i = 0; i < DCTSIZE; i++)
  178367. for (j = 0; j < DCTSIZE; j++)
  178368. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  178369. }
  178370. }
  178371. }
  178372. }
  178373. }
  178374. }
  178375. }
  178376. LOCAL(void)
  178377. do_rot_180 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178378. jvirt_barray_ptr *src_coef_arrays,
  178379. jvirt_barray_ptr *dst_coef_arrays)
  178380. /* 180 degree rotation is equivalent to
  178381. * 1. Vertical mirroring;
  178382. * 2. Horizontal mirroring.
  178383. * These two steps are merged into a single processing routine.
  178384. */
  178385. {
  178386. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  178387. int ci, i, j, offset_y;
  178388. JBLOCKARRAY src_buffer, dst_buffer;
  178389. JBLOCKROW src_row_ptr, dst_row_ptr;
  178390. JCOEFPTR src_ptr, dst_ptr;
  178391. jpeg_component_info *compptr;
  178392. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  178393. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  178394. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178395. compptr = dstinfo->comp_info + ci;
  178396. comp_width = MCU_cols * compptr->h_samp_factor;
  178397. comp_height = MCU_rows * compptr->v_samp_factor;
  178398. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  178399. dst_blk_y += compptr->v_samp_factor) {
  178400. dst_buffer = (*srcinfo->mem->access_virt_barray)
  178401. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  178402. (JDIMENSION) compptr->v_samp_factor, TRUE);
  178403. if (dst_blk_y < comp_height) {
  178404. /* Row is within the vertically mirrorable area. */
  178405. src_buffer = (*srcinfo->mem->access_virt_barray)
  178406. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  178407. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  178408. (JDIMENSION) compptr->v_samp_factor, FALSE);
  178409. } else {
  178410. /* Bottom-edge rows are only mirrored horizontally. */
  178411. src_buffer = (*srcinfo->mem->access_virt_barray)
  178412. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  178413. (JDIMENSION) compptr->v_samp_factor, FALSE);
  178414. }
  178415. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  178416. if (dst_blk_y < comp_height) {
  178417. /* Row is within the mirrorable area. */
  178418. dst_row_ptr = dst_buffer[offset_y];
  178419. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  178420. /* Process the blocks that can be mirrored both ways. */
  178421. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  178422. dst_ptr = dst_row_ptr[dst_blk_x];
  178423. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  178424. for (i = 0; i < DCTSIZE; i += 2) {
  178425. /* For even row, negate every odd column. */
  178426. for (j = 0; j < DCTSIZE; j += 2) {
  178427. *dst_ptr++ = *src_ptr++;
  178428. *dst_ptr++ = - *src_ptr++;
  178429. }
  178430. /* For odd row, negate every even column. */
  178431. for (j = 0; j < DCTSIZE; j += 2) {
  178432. *dst_ptr++ = - *src_ptr++;
  178433. *dst_ptr++ = *src_ptr++;
  178434. }
  178435. }
  178436. }
  178437. /* Any remaining right-edge blocks are only mirrored vertically. */
  178438. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  178439. dst_ptr = dst_row_ptr[dst_blk_x];
  178440. src_ptr = src_row_ptr[dst_blk_x];
  178441. for (i = 0; i < DCTSIZE; i += 2) {
  178442. for (j = 0; j < DCTSIZE; j++)
  178443. *dst_ptr++ = *src_ptr++;
  178444. for (j = 0; j < DCTSIZE; j++)
  178445. *dst_ptr++ = - *src_ptr++;
  178446. }
  178447. }
  178448. } else {
  178449. /* Remaining rows are just mirrored horizontally. */
  178450. dst_row_ptr = dst_buffer[offset_y];
  178451. src_row_ptr = src_buffer[offset_y];
  178452. /* Process the blocks that can be mirrored. */
  178453. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  178454. dst_ptr = dst_row_ptr[dst_blk_x];
  178455. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  178456. for (i = 0; i < DCTSIZE2; i += 2) {
  178457. *dst_ptr++ = *src_ptr++;
  178458. *dst_ptr++ = - *src_ptr++;
  178459. }
  178460. }
  178461. /* Any remaining right-edge blocks are only copied. */
  178462. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  178463. dst_ptr = dst_row_ptr[dst_blk_x];
  178464. src_ptr = src_row_ptr[dst_blk_x];
  178465. for (i = 0; i < DCTSIZE2; i++)
  178466. *dst_ptr++ = *src_ptr++;
  178467. }
  178468. }
  178469. }
  178470. }
  178471. }
  178472. }
  178473. LOCAL(void)
  178474. do_transverse (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178475. jvirt_barray_ptr *src_coef_arrays,
  178476. jvirt_barray_ptr *dst_coef_arrays)
  178477. /* Transverse transpose is equivalent to
  178478. * 1. 180 degree rotation;
  178479. * 2. Transposition;
  178480. * or
  178481. * 1. Horizontal mirroring;
  178482. * 2. Transposition;
  178483. * 3. Horizontal mirroring.
  178484. * These steps are merged into a single processing routine.
  178485. */
  178486. {
  178487. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  178488. int ci, i, j, offset_x, offset_y;
  178489. JBLOCKARRAY src_buffer, dst_buffer;
  178490. JCOEFPTR src_ptr, dst_ptr;
  178491. jpeg_component_info *compptr;
  178492. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  178493. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  178494. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178495. compptr = dstinfo->comp_info + ci;
  178496. comp_width = MCU_cols * compptr->h_samp_factor;
  178497. comp_height = MCU_rows * compptr->v_samp_factor;
  178498. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  178499. dst_blk_y += compptr->v_samp_factor) {
  178500. dst_buffer = (*srcinfo->mem->access_virt_barray)
  178501. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  178502. (JDIMENSION) compptr->v_samp_factor, TRUE);
  178503. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  178504. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  178505. dst_blk_x += compptr->h_samp_factor) {
  178506. src_buffer = (*srcinfo->mem->access_virt_barray)
  178507. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  178508. (JDIMENSION) compptr->h_samp_factor, FALSE);
  178509. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  178510. if (dst_blk_y < comp_height) {
  178511. src_ptr = src_buffer[offset_x]
  178512. [comp_height - dst_blk_y - offset_y - 1];
  178513. if (dst_blk_x < comp_width) {
  178514. /* Block is within the mirrorable area. */
  178515. dst_ptr = dst_buffer[offset_y]
  178516. [comp_width - dst_blk_x - offset_x - 1];
  178517. for (i = 0; i < DCTSIZE; i++) {
  178518. for (j = 0; j < DCTSIZE; j++) {
  178519. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  178520. j++;
  178521. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  178522. }
  178523. i++;
  178524. for (j = 0; j < DCTSIZE; j++) {
  178525. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  178526. j++;
  178527. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  178528. }
  178529. }
  178530. } else {
  178531. /* Right-edge blocks are mirrored in y only */
  178532. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  178533. for (i = 0; i < DCTSIZE; i++) {
  178534. for (j = 0; j < DCTSIZE; j++) {
  178535. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  178536. j++;
  178537. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  178538. }
  178539. }
  178540. }
  178541. } else {
  178542. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  178543. if (dst_blk_x < comp_width) {
  178544. /* Bottom-edge blocks are mirrored in x only */
  178545. dst_ptr = dst_buffer[offset_y]
  178546. [comp_width - dst_blk_x - offset_x - 1];
  178547. for (i = 0; i < DCTSIZE; i++) {
  178548. for (j = 0; j < DCTSIZE; j++)
  178549. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  178550. i++;
  178551. for (j = 0; j < DCTSIZE; j++)
  178552. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  178553. }
  178554. } else {
  178555. /* At lower right corner, just transpose, no mirroring */
  178556. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  178557. for (i = 0; i < DCTSIZE; i++)
  178558. for (j = 0; j < DCTSIZE; j++)
  178559. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  178560. }
  178561. }
  178562. }
  178563. }
  178564. }
  178565. }
  178566. }
  178567. }
  178568. /* Request any required workspace.
  178569. *
  178570. * We allocate the workspace virtual arrays from the source decompression
  178571. * object, so that all the arrays (both the original data and the workspace)
  178572. * will be taken into account while making memory management decisions.
  178573. * Hence, this routine must be called after jpeg_read_header (which reads
  178574. * the image dimensions) and before jpeg_read_coefficients (which realizes
  178575. * the source's virtual arrays).
  178576. */
  178577. GLOBAL(void)
  178578. jtransform_request_workspace (j_decompress_ptr srcinfo,
  178579. jpeg_transform_info *info)
  178580. {
  178581. jvirt_barray_ptr *coef_arrays = NULL;
  178582. jpeg_component_info *compptr;
  178583. int ci;
  178584. if (info->force_grayscale &&
  178585. srcinfo->jpeg_color_space == JCS_YCbCr &&
  178586. srcinfo->num_components == 3) {
  178587. /* We'll only process the first component */
  178588. info->num_components = 1;
  178589. } else {
  178590. /* Process all the components */
  178591. info->num_components = srcinfo->num_components;
  178592. }
  178593. switch (info->transform) {
  178594. case JXFORM_NONE:
  178595. case JXFORM_FLIP_H:
  178596. /* Don't need a workspace array */
  178597. break;
  178598. case JXFORM_FLIP_V:
  178599. case JXFORM_ROT_180:
  178600. /* Need workspace arrays having same dimensions as source image.
  178601. * Note that we allocate arrays padded out to the next iMCU boundary,
  178602. * so that transform routines need not worry about missing edge blocks.
  178603. */
  178604. coef_arrays = (jvirt_barray_ptr *)
  178605. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  178606. SIZEOF(jvirt_barray_ptr) * info->num_components);
  178607. for (ci = 0; ci < info->num_components; ci++) {
  178608. compptr = srcinfo->comp_info + ci;
  178609. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  178610. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  178611. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  178612. (long) compptr->h_samp_factor),
  178613. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  178614. (long) compptr->v_samp_factor),
  178615. (JDIMENSION) compptr->v_samp_factor);
  178616. }
  178617. break;
  178618. case JXFORM_TRANSPOSE:
  178619. case JXFORM_TRANSVERSE:
  178620. case JXFORM_ROT_90:
  178621. case JXFORM_ROT_270:
  178622. /* Need workspace arrays having transposed dimensions.
  178623. * Note that we allocate arrays padded out to the next iMCU boundary,
  178624. * so that transform routines need not worry about missing edge blocks.
  178625. */
  178626. coef_arrays = (jvirt_barray_ptr *)
  178627. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  178628. SIZEOF(jvirt_barray_ptr) * info->num_components);
  178629. for (ci = 0; ci < info->num_components; ci++) {
  178630. compptr = srcinfo->comp_info + ci;
  178631. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  178632. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  178633. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  178634. (long) compptr->v_samp_factor),
  178635. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  178636. (long) compptr->h_samp_factor),
  178637. (JDIMENSION) compptr->h_samp_factor);
  178638. }
  178639. break;
  178640. }
  178641. info->workspace_coef_arrays = coef_arrays;
  178642. }
  178643. /* Transpose destination image parameters */
  178644. LOCAL(void)
  178645. transpose_critical_parameters (j_compress_ptr dstinfo)
  178646. {
  178647. int tblno, i, j, ci, itemp;
  178648. jpeg_component_info *compptr;
  178649. JQUANT_TBL *qtblptr;
  178650. JDIMENSION dtemp;
  178651. UINT16 qtemp;
  178652. /* Transpose basic image dimensions */
  178653. dtemp = dstinfo->image_width;
  178654. dstinfo->image_width = dstinfo->image_height;
  178655. dstinfo->image_height = dtemp;
  178656. /* Transpose sampling factors */
  178657. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178658. compptr = dstinfo->comp_info + ci;
  178659. itemp = compptr->h_samp_factor;
  178660. compptr->h_samp_factor = compptr->v_samp_factor;
  178661. compptr->v_samp_factor = itemp;
  178662. }
  178663. /* Transpose quantization tables */
  178664. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  178665. qtblptr = dstinfo->quant_tbl_ptrs[tblno];
  178666. if (qtblptr != NULL) {
  178667. for (i = 0; i < DCTSIZE; i++) {
  178668. for (j = 0; j < i; j++) {
  178669. qtemp = qtblptr->quantval[i*DCTSIZE+j];
  178670. qtblptr->quantval[i*DCTSIZE+j] = qtblptr->quantval[j*DCTSIZE+i];
  178671. qtblptr->quantval[j*DCTSIZE+i] = qtemp;
  178672. }
  178673. }
  178674. }
  178675. }
  178676. }
  178677. /* Trim off any partial iMCUs on the indicated destination edge */
  178678. LOCAL(void)
  178679. trim_right_edge (j_compress_ptr dstinfo)
  178680. {
  178681. int ci, max_h_samp_factor;
  178682. JDIMENSION MCU_cols;
  178683. /* We have to compute max_h_samp_factor ourselves,
  178684. * because it hasn't been set yet in the destination
  178685. * (and we don't want to use the source's value).
  178686. */
  178687. max_h_samp_factor = 1;
  178688. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178689. int h_samp_factor = dstinfo->comp_info[ci].h_samp_factor;
  178690. max_h_samp_factor = MAX(max_h_samp_factor, h_samp_factor);
  178691. }
  178692. MCU_cols = dstinfo->image_width / (max_h_samp_factor * DCTSIZE);
  178693. if (MCU_cols > 0) /* can't trim to 0 pixels */
  178694. dstinfo->image_width = MCU_cols * (max_h_samp_factor * DCTSIZE);
  178695. }
  178696. LOCAL(void)
  178697. trim_bottom_edge (j_compress_ptr dstinfo)
  178698. {
  178699. int ci, max_v_samp_factor;
  178700. JDIMENSION MCU_rows;
  178701. /* We have to compute max_v_samp_factor ourselves,
  178702. * because it hasn't been set yet in the destination
  178703. * (and we don't want to use the source's value).
  178704. */
  178705. max_v_samp_factor = 1;
  178706. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178707. int v_samp_factor = dstinfo->comp_info[ci].v_samp_factor;
  178708. max_v_samp_factor = MAX(max_v_samp_factor, v_samp_factor);
  178709. }
  178710. MCU_rows = dstinfo->image_height / (max_v_samp_factor * DCTSIZE);
  178711. if (MCU_rows > 0) /* can't trim to 0 pixels */
  178712. dstinfo->image_height = MCU_rows * (max_v_samp_factor * DCTSIZE);
  178713. }
  178714. /* Adjust output image parameters as needed.
  178715. *
  178716. * This must be called after jpeg_copy_critical_parameters()
  178717. * and before jpeg_write_coefficients().
  178718. *
  178719. * The return value is the set of virtual coefficient arrays to be written
  178720. * (either the ones allocated by jtransform_request_workspace, or the
  178721. * original source data arrays). The caller will need to pass this value
  178722. * to jpeg_write_coefficients().
  178723. */
  178724. GLOBAL(jvirt_barray_ptr *)
  178725. jtransform_adjust_parameters (j_decompress_ptr,
  178726. j_compress_ptr dstinfo,
  178727. jvirt_barray_ptr *src_coef_arrays,
  178728. jpeg_transform_info *info)
  178729. {
  178730. /* If force-to-grayscale is requested, adjust destination parameters */
  178731. if (info->force_grayscale) {
  178732. /* We use jpeg_set_colorspace to make sure subsidiary settings get fixed
  178733. * properly. Among other things, the target h_samp_factor & v_samp_factor
  178734. * will get set to 1, which typically won't match the source.
  178735. * In fact we do this even if the source is already grayscale; that
  178736. * provides an easy way of coercing a grayscale JPEG with funny sampling
  178737. * factors to the customary 1,1. (Some decoders fail on other factors.)
  178738. */
  178739. if ((dstinfo->jpeg_color_space == JCS_YCbCr &&
  178740. dstinfo->num_components == 3) ||
  178741. (dstinfo->jpeg_color_space == JCS_GRAYSCALE &&
  178742. dstinfo->num_components == 1)) {
  178743. /* We have to preserve the source's quantization table number. */
  178744. int sv_quant_tbl_no = dstinfo->comp_info[0].quant_tbl_no;
  178745. jpeg_set_colorspace(dstinfo, JCS_GRAYSCALE);
  178746. dstinfo->comp_info[0].quant_tbl_no = sv_quant_tbl_no;
  178747. } else {
  178748. /* Sorry, can't do it */
  178749. ERREXIT(dstinfo, JERR_CONVERSION_NOTIMPL);
  178750. }
  178751. }
  178752. /* Correct the destination's image dimensions etc if necessary */
  178753. switch (info->transform) {
  178754. case JXFORM_NONE:
  178755. /* Nothing to do */
  178756. break;
  178757. case JXFORM_FLIP_H:
  178758. if (info->trim)
  178759. trim_right_edge(dstinfo);
  178760. break;
  178761. case JXFORM_FLIP_V:
  178762. if (info->trim)
  178763. trim_bottom_edge(dstinfo);
  178764. break;
  178765. case JXFORM_TRANSPOSE:
  178766. transpose_critical_parameters(dstinfo);
  178767. /* transpose does NOT have to trim anything */
  178768. break;
  178769. case JXFORM_TRANSVERSE:
  178770. transpose_critical_parameters(dstinfo);
  178771. if (info->trim) {
  178772. trim_right_edge(dstinfo);
  178773. trim_bottom_edge(dstinfo);
  178774. }
  178775. break;
  178776. case JXFORM_ROT_90:
  178777. transpose_critical_parameters(dstinfo);
  178778. if (info->trim)
  178779. trim_right_edge(dstinfo);
  178780. break;
  178781. case JXFORM_ROT_180:
  178782. if (info->trim) {
  178783. trim_right_edge(dstinfo);
  178784. trim_bottom_edge(dstinfo);
  178785. }
  178786. break;
  178787. case JXFORM_ROT_270:
  178788. transpose_critical_parameters(dstinfo);
  178789. if (info->trim)
  178790. trim_bottom_edge(dstinfo);
  178791. break;
  178792. }
  178793. /* Return the appropriate output data set */
  178794. if (info->workspace_coef_arrays != NULL)
  178795. return info->workspace_coef_arrays;
  178796. return src_coef_arrays;
  178797. }
  178798. /* Execute the actual transformation, if any.
  178799. *
  178800. * This must be called *after* jpeg_write_coefficients, because it depends
  178801. * on jpeg_write_coefficients to have computed subsidiary values such as
  178802. * the per-component width and height fields in the destination object.
  178803. *
  178804. * Note that some transformations will modify the source data arrays!
  178805. */
  178806. GLOBAL(void)
  178807. jtransform_execute_transformation (j_decompress_ptr srcinfo,
  178808. j_compress_ptr dstinfo,
  178809. jvirt_barray_ptr *src_coef_arrays,
  178810. jpeg_transform_info *info)
  178811. {
  178812. jvirt_barray_ptr *dst_coef_arrays = info->workspace_coef_arrays;
  178813. switch (info->transform) {
  178814. case JXFORM_NONE:
  178815. break;
  178816. case JXFORM_FLIP_H:
  178817. do_flip_h(srcinfo, dstinfo, src_coef_arrays);
  178818. break;
  178819. case JXFORM_FLIP_V:
  178820. do_flip_v(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  178821. break;
  178822. case JXFORM_TRANSPOSE:
  178823. do_transpose(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  178824. break;
  178825. case JXFORM_TRANSVERSE:
  178826. do_transverse(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  178827. break;
  178828. case JXFORM_ROT_90:
  178829. do_rot_90(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  178830. break;
  178831. case JXFORM_ROT_180:
  178832. do_rot_180(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  178833. break;
  178834. case JXFORM_ROT_270:
  178835. do_rot_270(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  178836. break;
  178837. }
  178838. }
  178839. #endif /* TRANSFORMS_SUPPORTED */
  178840. /* Setup decompression object to save desired markers in memory.
  178841. * This must be called before jpeg_read_header() to have the desired effect.
  178842. */
  178843. GLOBAL(void)
  178844. jcopy_markers_setup (j_decompress_ptr srcinfo, JCOPY_OPTION option)
  178845. {
  178846. #ifdef SAVE_MARKERS_SUPPORTED
  178847. int m;
  178848. /* Save comments except under NONE option */
  178849. if (option != JCOPYOPT_NONE) {
  178850. jpeg_save_markers(srcinfo, JPEG_COM, 0xFFFF);
  178851. }
  178852. /* Save all types of APPn markers iff ALL option */
  178853. if (option == JCOPYOPT_ALL) {
  178854. for (m = 0; m < 16; m++)
  178855. jpeg_save_markers(srcinfo, JPEG_APP0 + m, 0xFFFF);
  178856. }
  178857. #endif /* SAVE_MARKERS_SUPPORTED */
  178858. }
  178859. /* Copy markers saved in the given source object to the destination object.
  178860. * This should be called just after jpeg_start_compress() or
  178861. * jpeg_write_coefficients().
  178862. * Note that those routines will have written the SOI, and also the
  178863. * JFIF APP0 or Adobe APP14 markers if selected.
  178864. */
  178865. GLOBAL(void)
  178866. jcopy_markers_execute (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178867. JCOPY_OPTION)
  178868. {
  178869. jpeg_saved_marker_ptr marker;
  178870. /* In the current implementation, we don't actually need to examine the
  178871. * option flag here; we just copy everything that got saved.
  178872. * But to avoid confusion, we do not output JFIF and Adobe APP14 markers
  178873. * if the encoder library already wrote one.
  178874. */
  178875. for (marker = srcinfo->marker_list; marker != NULL; marker = marker->next) {
  178876. if (dstinfo->write_JFIF_header &&
  178877. marker->marker == JPEG_APP0 &&
  178878. marker->data_length >= 5 &&
  178879. GETJOCTET(marker->data[0]) == 0x4A &&
  178880. GETJOCTET(marker->data[1]) == 0x46 &&
  178881. GETJOCTET(marker->data[2]) == 0x49 &&
  178882. GETJOCTET(marker->data[3]) == 0x46 &&
  178883. GETJOCTET(marker->data[4]) == 0)
  178884. continue; /* reject duplicate JFIF */
  178885. if (dstinfo->write_Adobe_marker &&
  178886. marker->marker == JPEG_APP0+14 &&
  178887. marker->data_length >= 5 &&
  178888. GETJOCTET(marker->data[0]) == 0x41 &&
  178889. GETJOCTET(marker->data[1]) == 0x64 &&
  178890. GETJOCTET(marker->data[2]) == 0x6F &&
  178891. GETJOCTET(marker->data[3]) == 0x62 &&
  178892. GETJOCTET(marker->data[4]) == 0x65)
  178893. continue; /* reject duplicate Adobe */
  178894. #ifdef NEED_FAR_POINTERS
  178895. /* We could use jpeg_write_marker if the data weren't FAR... */
  178896. {
  178897. unsigned int i;
  178898. jpeg_write_m_header(dstinfo, marker->marker, marker->data_length);
  178899. for (i = 0; i < marker->data_length; i++)
  178900. jpeg_write_m_byte(dstinfo, marker->data[i]);
  178901. }
  178902. #else
  178903. jpeg_write_marker(dstinfo, marker->marker,
  178904. marker->data, marker->data_length);
  178905. #endif
  178906. }
  178907. }
  178908. /*** End of inlined file: transupp.c ***/
  178909. }
  178910. #else
  178911. #define JPEG_INTERNALS
  178912. #undef FAR
  178913. #include <jpeglib.h>
  178914. #endif
  178915. }
  178916. #undef max
  178917. #undef min
  178918. #if JUCE_MSVC
  178919. #pragma warning (pop)
  178920. #endif
  178921. BEGIN_JUCE_NAMESPACE
  178922. namespace JPEGHelpers
  178923. {
  178924. using namespace jpeglibNamespace;
  178925. #if ! JUCE_MSVC
  178926. using jpeglibNamespace::boolean;
  178927. #endif
  178928. struct JPEGDecodingFailure {};
  178929. static void fatalErrorHandler (j_common_ptr)
  178930. {
  178931. throw JPEGDecodingFailure();
  178932. }
  178933. static void silentErrorCallback1 (j_common_ptr) {}
  178934. static void silentErrorCallback2 (j_common_ptr, int) {}
  178935. static void silentErrorCallback3 (j_common_ptr, char*) {}
  178936. static void setupSilentErrorHandler (struct jpeg_error_mgr& err)
  178937. {
  178938. zerostruct (err);
  178939. err.error_exit = fatalErrorHandler;
  178940. err.emit_message = silentErrorCallback2;
  178941. err.output_message = silentErrorCallback1;
  178942. err.format_message = silentErrorCallback3;
  178943. err.reset_error_mgr = silentErrorCallback1;
  178944. }
  178945. static void dummyCallback1 (j_decompress_ptr)
  178946. {
  178947. }
  178948. static void jpegSkip (j_decompress_ptr decompStruct, long num)
  178949. {
  178950. decompStruct->src->next_input_byte += num;
  178951. num = jmin (num, (long) decompStruct->src->bytes_in_buffer);
  178952. decompStruct->src->bytes_in_buffer -= num;
  178953. }
  178954. static boolean jpegFill (j_decompress_ptr)
  178955. {
  178956. return 0;
  178957. }
  178958. static const int jpegBufferSize = 512;
  178959. struct JuceJpegDest : public jpeg_destination_mgr
  178960. {
  178961. OutputStream* output;
  178962. char* buffer;
  178963. };
  178964. static void jpegWriteInit (j_compress_ptr)
  178965. {
  178966. }
  178967. static void jpegWriteTerminate (j_compress_ptr cinfo)
  178968. {
  178969. JuceJpegDest* const dest = static_cast <JuceJpegDest*> (cinfo->dest);
  178970. const size_t numToWrite = jpegBufferSize - dest->free_in_buffer;
  178971. dest->output->write (dest->buffer, (int) numToWrite);
  178972. }
  178973. static boolean jpegWriteFlush (j_compress_ptr cinfo)
  178974. {
  178975. JuceJpegDest* const dest = static_cast <JuceJpegDest*> (cinfo->dest);
  178976. const int numToWrite = jpegBufferSize;
  178977. dest->next_output_byte = reinterpret_cast <JOCTET*> (dest->buffer);
  178978. dest->free_in_buffer = jpegBufferSize;
  178979. return dest->output->write (dest->buffer, numToWrite);
  178980. }
  178981. }
  178982. JPEGImageFormat::JPEGImageFormat()
  178983. : quality (-1.0f)
  178984. {
  178985. }
  178986. JPEGImageFormat::~JPEGImageFormat() {}
  178987. void JPEGImageFormat::setQuality (const float newQuality)
  178988. {
  178989. quality = newQuality;
  178990. }
  178991. const String JPEGImageFormat::getFormatName()
  178992. {
  178993. return "JPEG";
  178994. }
  178995. bool JPEGImageFormat::canUnderstand (InputStream& in)
  178996. {
  178997. const int bytesNeeded = 10;
  178998. uint8 header [bytesNeeded];
  178999. if (in.read (header, bytesNeeded) == bytesNeeded)
  179000. {
  179001. return header[0] == 0xff
  179002. && header[1] == 0xd8
  179003. && header[2] == 0xff
  179004. && (header[3] == 0xe0 || header[3] == 0xe1);
  179005. }
  179006. return false;
  179007. }
  179008. const Image JPEGImageFormat::decodeImage (InputStream& in)
  179009. {
  179010. using namespace jpeglibNamespace;
  179011. using namespace JPEGHelpers;
  179012. MemoryBlock mb;
  179013. in.readIntoMemoryBlock (mb);
  179014. Image image;
  179015. if (mb.getSize() > 16)
  179016. {
  179017. struct jpeg_decompress_struct jpegDecompStruct;
  179018. struct jpeg_error_mgr jerr;
  179019. setupSilentErrorHandler (jerr);
  179020. jpegDecompStruct.err = &jerr;
  179021. jpeg_create_decompress (&jpegDecompStruct);
  179022. jpegDecompStruct.src = (jpeg_source_mgr*)(jpegDecompStruct.mem->alloc_small)
  179023. ((j_common_ptr)(&jpegDecompStruct), JPOOL_PERMANENT, sizeof (jpeg_source_mgr));
  179024. jpegDecompStruct.src->init_source = dummyCallback1;
  179025. jpegDecompStruct.src->fill_input_buffer = jpegFill;
  179026. jpegDecompStruct.src->skip_input_data = jpegSkip;
  179027. jpegDecompStruct.src->resync_to_restart = jpeg_resync_to_restart;
  179028. jpegDecompStruct.src->term_source = dummyCallback1;
  179029. jpegDecompStruct.src->next_input_byte = static_cast <const unsigned char*> (mb.getData());
  179030. jpegDecompStruct.src->bytes_in_buffer = mb.getSize();
  179031. try
  179032. {
  179033. jpeg_read_header (&jpegDecompStruct, TRUE);
  179034. jpeg_calc_output_dimensions (&jpegDecompStruct);
  179035. const int width = jpegDecompStruct.output_width;
  179036. const int height = jpegDecompStruct.output_height;
  179037. jpegDecompStruct.out_color_space = JCS_RGB;
  179038. JSAMPARRAY buffer
  179039. = (*jpegDecompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegDecompStruct,
  179040. JPOOL_IMAGE,
  179041. width * 3, 1);
  179042. if (jpeg_start_decompress (&jpegDecompStruct))
  179043. {
  179044. image = Image (Image::RGB, width, height, false);
  179045. const bool hasAlphaChan = image.hasAlphaChannel(); // (the native image creator may not give back what we expect)
  179046. const Image::BitmapData destData (image, 0, 0, width, height, true);
  179047. for (int y = 0; y < height; ++y)
  179048. {
  179049. jpeg_read_scanlines (&jpegDecompStruct, buffer, 1);
  179050. const uint8* src = *buffer;
  179051. uint8* dest = destData.getLinePointer (y);
  179052. if (hasAlphaChan)
  179053. {
  179054. for (int i = width; --i >= 0;)
  179055. {
  179056. ((PixelARGB*) dest)->setARGB (0xff, src[0], src[1], src[2]);
  179057. ((PixelARGB*) dest)->premultiply();
  179058. dest += destData.pixelStride;
  179059. src += 3;
  179060. }
  179061. }
  179062. else
  179063. {
  179064. for (int i = width; --i >= 0;)
  179065. {
  179066. ((PixelRGB*) dest)->setARGB (0xff, src[0], src[1], src[2]);
  179067. dest += destData.pixelStride;
  179068. src += 3;
  179069. }
  179070. }
  179071. }
  179072. jpeg_finish_decompress (&jpegDecompStruct);
  179073. in.setPosition (((char*) jpegDecompStruct.src->next_input_byte) - (char*) mb.getData());
  179074. }
  179075. jpeg_destroy_decompress (&jpegDecompStruct);
  179076. }
  179077. catch (...)
  179078. {}
  179079. }
  179080. return image;
  179081. }
  179082. bool JPEGImageFormat::writeImageToStream (const Image& image, OutputStream& out)
  179083. {
  179084. using namespace jpeglibNamespace;
  179085. using namespace JPEGHelpers;
  179086. if (image.hasAlphaChannel())
  179087. {
  179088. // this method could fill the background in white and still save the image..
  179089. jassertfalse;
  179090. return true;
  179091. }
  179092. struct jpeg_compress_struct jpegCompStruct;
  179093. struct jpeg_error_mgr jerr;
  179094. setupSilentErrorHandler (jerr);
  179095. jpegCompStruct.err = &jerr;
  179096. jpeg_create_compress (&jpegCompStruct);
  179097. JuceJpegDest dest;
  179098. jpegCompStruct.dest = &dest;
  179099. dest.output = &out;
  179100. HeapBlock <char> tempBuffer (jpegBufferSize);
  179101. dest.buffer = tempBuffer;
  179102. dest.next_output_byte = (JOCTET*) dest.buffer;
  179103. dest.free_in_buffer = jpegBufferSize;
  179104. dest.init_destination = jpegWriteInit;
  179105. dest.empty_output_buffer = jpegWriteFlush;
  179106. dest.term_destination = jpegWriteTerminate;
  179107. jpegCompStruct.image_width = image.getWidth();
  179108. jpegCompStruct.image_height = image.getHeight();
  179109. jpegCompStruct.input_components = 3;
  179110. jpegCompStruct.in_color_space = JCS_RGB;
  179111. jpegCompStruct.write_JFIF_header = 1;
  179112. jpegCompStruct.X_density = 72;
  179113. jpegCompStruct.Y_density = 72;
  179114. jpeg_set_defaults (&jpegCompStruct);
  179115. jpegCompStruct.dct_method = JDCT_FLOAT;
  179116. jpegCompStruct.optimize_coding = 1;
  179117. //jpegCompStruct.smoothing_factor = 10;
  179118. if (quality < 0.0f)
  179119. quality = 0.85f;
  179120. jpeg_set_quality (&jpegCompStruct, jlimit (0, 100, roundToInt (quality * 100.0f)), TRUE);
  179121. jpeg_start_compress (&jpegCompStruct, TRUE);
  179122. const int strideBytes = jpegCompStruct.image_width * jpegCompStruct.input_components;
  179123. JSAMPARRAY buffer = (*jpegCompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegCompStruct,
  179124. JPOOL_IMAGE, strideBytes, 1);
  179125. const Image::BitmapData srcData (image, 0, 0, jpegCompStruct.image_width, jpegCompStruct.image_height);
  179126. while (jpegCompStruct.next_scanline < jpegCompStruct.image_height)
  179127. {
  179128. const uint8* src = srcData.getLinePointer (jpegCompStruct.next_scanline);
  179129. uint8* dst = *buffer;
  179130. for (int i = jpegCompStruct.image_width; --i >= 0;)
  179131. {
  179132. *dst++ = ((const PixelRGB*) src)->getRed();
  179133. *dst++ = ((const PixelRGB*) src)->getGreen();
  179134. *dst++ = ((const PixelRGB*) src)->getBlue();
  179135. src += srcData.pixelStride;
  179136. }
  179137. jpeg_write_scanlines (&jpegCompStruct, buffer, 1);
  179138. }
  179139. jpeg_finish_compress (&jpegCompStruct);
  179140. jpeg_destroy_compress (&jpegCompStruct);
  179141. out.flush();
  179142. return true;
  179143. }
  179144. END_JUCE_NAMESPACE
  179145. /*** End of inlined file: juce_JPEGLoader.cpp ***/
  179146. /*** Start of inlined file: juce_PNGLoader.cpp ***/
  179147. #if JUCE_MSVC
  179148. #pragma warning (push)
  179149. #pragma warning (disable: 4390 4611)
  179150. #endif
  179151. namespace zlibNamespace
  179152. {
  179153. #if JUCE_INCLUDE_ZLIB_CODE
  179154. #undef OS_CODE
  179155. #undef fdopen
  179156. #undef OS_CODE
  179157. #else
  179158. #include <zlib.h>
  179159. #endif
  179160. }
  179161. namespace pnglibNamespace
  179162. {
  179163. using namespace zlibNamespace;
  179164. #if JUCE_INCLUDE_PNGLIB_CODE
  179165. #if _MSC_VER != 1310
  179166. using ::calloc; // (causes conflict in VS.NET 2003)
  179167. using ::malloc;
  179168. using ::free;
  179169. #endif
  179170. extern "C"
  179171. {
  179172. using ::abs;
  179173. #define PNG_INTERNAL
  179174. #define NO_DUMMY_DECL
  179175. #define PNG_SETJMP_NOT_SUPPORTED
  179176. /*** Start of inlined file: png.h ***/
  179177. /* png.h - header file for PNG reference library
  179178. *
  179179. * libpng version 1.2.21 - October 4, 2007
  179180. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  179181. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  179182. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  179183. *
  179184. * Authors and maintainers:
  179185. * libpng versions 0.71, May 1995, through 0.88, January 1996: Guy Schalnat
  179186. * libpng versions 0.89c, June 1996, through 0.96, May 1997: Andreas Dilger
  179187. * libpng versions 0.97, January 1998, through 1.2.21 - October 4, 2007: Glenn
  179188. * See also "Contributing Authors", below.
  179189. *
  179190. * Note about libpng version numbers:
  179191. *
  179192. * Due to various miscommunications, unforeseen code incompatibilities
  179193. * and occasional factors outside the authors' control, version numbering
  179194. * on the library has not always been consistent and straightforward.
  179195. * The following table summarizes matters since version 0.89c, which was
  179196. * the first widely used release:
  179197. *
  179198. * source png.h png.h shared-lib
  179199. * version string int version
  179200. * ------- ------ ----- ----------
  179201. * 0.89c "1.0 beta 3" 0.89 89 1.0.89
  179202. * 0.90 "1.0 beta 4" 0.90 90 0.90 [should have been 2.0.90]
  179203. * 0.95 "1.0 beta 5" 0.95 95 0.95 [should have been 2.0.95]
  179204. * 0.96 "1.0 beta 6" 0.96 96 0.96 [should have been 2.0.96]
  179205. * 0.97b "1.00.97 beta 7" 1.00.97 97 1.0.1 [should have been 2.0.97]
  179206. * 0.97c 0.97 97 2.0.97
  179207. * 0.98 0.98 98 2.0.98
  179208. * 0.99 0.99 98 2.0.99
  179209. * 0.99a-m 0.99 99 2.0.99
  179210. * 1.00 1.00 100 2.1.0 [100 should be 10000]
  179211. * 1.0.0 (from here on, the 100 2.1.0 [100 should be 10000]
  179212. * 1.0.1 png.h string is 10001 2.1.0
  179213. * 1.0.1a-e identical to the 10002 from here on, the shared library
  179214. * 1.0.2 source version) 10002 is 2.V where V is the source code
  179215. * 1.0.2a-b 10003 version, except as noted.
  179216. * 1.0.3 10003
  179217. * 1.0.3a-d 10004
  179218. * 1.0.4 10004
  179219. * 1.0.4a-f 10005
  179220. * 1.0.5 (+ 2 patches) 10005
  179221. * 1.0.5a-d 10006
  179222. * 1.0.5e-r 10100 (not source compatible)
  179223. * 1.0.5s-v 10006 (not binary compatible)
  179224. * 1.0.6 (+ 3 patches) 10006 (still binary incompatible)
  179225. * 1.0.6d-f 10007 (still binary incompatible)
  179226. * 1.0.6g 10007
  179227. * 1.0.6h 10007 10.6h (testing xy.z so-numbering)
  179228. * 1.0.6i 10007 10.6i
  179229. * 1.0.6j 10007 2.1.0.6j (incompatible with 1.0.0)
  179230. * 1.0.7beta11-14 DLLNUM 10007 2.1.0.7beta11-14 (binary compatible)
  179231. * 1.0.7beta15-18 1 10007 2.1.0.7beta15-18 (binary compatible)
  179232. * 1.0.7rc1-2 1 10007 2.1.0.7rc1-2 (binary compatible)
  179233. * 1.0.7 1 10007 (still compatible)
  179234. * 1.0.8beta1-4 1 10008 2.1.0.8beta1-4
  179235. * 1.0.8rc1 1 10008 2.1.0.8rc1
  179236. * 1.0.8 1 10008 2.1.0.8
  179237. * 1.0.9beta1-6 1 10009 2.1.0.9beta1-6
  179238. * 1.0.9rc1 1 10009 2.1.0.9rc1
  179239. * 1.0.9beta7-10 1 10009 2.1.0.9beta7-10
  179240. * 1.0.9rc2 1 10009 2.1.0.9rc2
  179241. * 1.0.9 1 10009 2.1.0.9
  179242. * 1.0.10beta1 1 10010 2.1.0.10beta1
  179243. * 1.0.10rc1 1 10010 2.1.0.10rc1
  179244. * 1.0.10 1 10010 2.1.0.10
  179245. * 1.0.11beta1-3 1 10011 2.1.0.11beta1-3
  179246. * 1.0.11rc1 1 10011 2.1.0.11rc1
  179247. * 1.0.11 1 10011 2.1.0.11
  179248. * 1.0.12beta1-2 2 10012 2.1.0.12beta1-2
  179249. * 1.0.12rc1 2 10012 2.1.0.12rc1
  179250. * 1.0.12 2 10012 2.1.0.12
  179251. * 1.1.0a-f - 10100 2.1.1.0a-f (branch abandoned)
  179252. * 1.2.0beta1-2 2 10200 2.1.2.0beta1-2
  179253. * 1.2.0beta3-5 3 10200 3.1.2.0beta3-5
  179254. * 1.2.0rc1 3 10200 3.1.2.0rc1
  179255. * 1.2.0 3 10200 3.1.2.0
  179256. * 1.2.1beta1-4 3 10201 3.1.2.1beta1-4
  179257. * 1.2.1rc1-2 3 10201 3.1.2.1rc1-2
  179258. * 1.2.1 3 10201 3.1.2.1
  179259. * 1.2.2beta1-6 12 10202 12.so.0.1.2.2beta1-6
  179260. * 1.0.13beta1 10 10013 10.so.0.1.0.13beta1
  179261. * 1.0.13rc1 10 10013 10.so.0.1.0.13rc1
  179262. * 1.2.2rc1 12 10202 12.so.0.1.2.2rc1
  179263. * 1.0.13 10 10013 10.so.0.1.0.13
  179264. * 1.2.2 12 10202 12.so.0.1.2.2
  179265. * 1.2.3rc1-6 12 10203 12.so.0.1.2.3rc1-6
  179266. * 1.2.3 12 10203 12.so.0.1.2.3
  179267. * 1.2.4beta1-3 13 10204 12.so.0.1.2.4beta1-3
  179268. * 1.0.14rc1 13 10014 10.so.0.1.0.14rc1
  179269. * 1.2.4rc1 13 10204 12.so.0.1.2.4rc1
  179270. * 1.0.14 10 10014 10.so.0.1.0.14
  179271. * 1.2.4 13 10204 12.so.0.1.2.4
  179272. * 1.2.5beta1-2 13 10205 12.so.0.1.2.5beta1-2
  179273. * 1.0.15rc1-3 10 10015 10.so.0.1.0.15rc1-3
  179274. * 1.2.5rc1-3 13 10205 12.so.0.1.2.5rc1-3
  179275. * 1.0.15 10 10015 10.so.0.1.0.15
  179276. * 1.2.5 13 10205 12.so.0.1.2.5
  179277. * 1.2.6beta1-4 13 10206 12.so.0.1.2.6beta1-4
  179278. * 1.0.16 10 10016 10.so.0.1.0.16
  179279. * 1.2.6 13 10206 12.so.0.1.2.6
  179280. * 1.2.7beta1-2 13 10207 12.so.0.1.2.7beta1-2
  179281. * 1.0.17rc1 10 10017 10.so.0.1.0.17rc1
  179282. * 1.2.7rc1 13 10207 12.so.0.1.2.7rc1
  179283. * 1.0.17 10 10017 10.so.0.1.0.17
  179284. * 1.2.7 13 10207 12.so.0.1.2.7
  179285. * 1.2.8beta1-5 13 10208 12.so.0.1.2.8beta1-5
  179286. * 1.0.18rc1-5 10 10018 10.so.0.1.0.18rc1-5
  179287. * 1.2.8rc1-5 13 10208 12.so.0.1.2.8rc1-5
  179288. * 1.0.18 10 10018 10.so.0.1.0.18
  179289. * 1.2.8 13 10208 12.so.0.1.2.8
  179290. * 1.2.9beta1-3 13 10209 12.so.0.1.2.9beta1-3
  179291. * 1.2.9beta4-11 13 10209 12.so.0.9[.0]
  179292. * 1.2.9rc1 13 10209 12.so.0.9[.0]
  179293. * 1.2.9 13 10209 12.so.0.9[.0]
  179294. * 1.2.10beta1-8 13 10210 12.so.0.10[.0]
  179295. * 1.2.10rc1-3 13 10210 12.so.0.10[.0]
  179296. * 1.2.10 13 10210 12.so.0.10[.0]
  179297. * 1.2.11beta1-4 13 10211 12.so.0.11[.0]
  179298. * 1.0.19rc1-5 10 10019 10.so.0.19[.0]
  179299. * 1.2.11rc1-5 13 10211 12.so.0.11[.0]
  179300. * 1.0.19 10 10019 10.so.0.19[.0]
  179301. * 1.2.11 13 10211 12.so.0.11[.0]
  179302. * 1.0.20 10 10020 10.so.0.20[.0]
  179303. * 1.2.12 13 10212 12.so.0.12[.0]
  179304. * 1.2.13beta1 13 10213 12.so.0.13[.0]
  179305. * 1.0.21 10 10021 10.so.0.21[.0]
  179306. * 1.2.13 13 10213 12.so.0.13[.0]
  179307. * 1.2.14beta1-2 13 10214 12.so.0.14[.0]
  179308. * 1.0.22rc1 10 10022 10.so.0.22[.0]
  179309. * 1.2.14rc1 13 10214 12.so.0.14[.0]
  179310. * 1.0.22 10 10022 10.so.0.22[.0]
  179311. * 1.2.14 13 10214 12.so.0.14[.0]
  179312. * 1.2.15beta1-6 13 10215 12.so.0.15[.0]
  179313. * 1.0.23rc1-5 10 10023 10.so.0.23[.0]
  179314. * 1.2.15rc1-5 13 10215 12.so.0.15[.0]
  179315. * 1.0.23 10 10023 10.so.0.23[.0]
  179316. * 1.2.15 13 10215 12.so.0.15[.0]
  179317. * 1.2.16beta1-2 13 10216 12.so.0.16[.0]
  179318. * 1.2.16rc1 13 10216 12.so.0.16[.0]
  179319. * 1.0.24 10 10024 10.so.0.24[.0]
  179320. * 1.2.16 13 10216 12.so.0.16[.0]
  179321. * 1.2.17beta1-2 13 10217 12.so.0.17[.0]
  179322. * 1.0.25rc1 10 10025 10.so.0.25[.0]
  179323. * 1.2.17rc1-3 13 10217 12.so.0.17[.0]
  179324. * 1.0.25 10 10025 10.so.0.25[.0]
  179325. * 1.2.17 13 10217 12.so.0.17[.0]
  179326. * 1.0.26 10 10026 10.so.0.26[.0]
  179327. * 1.2.18 13 10218 12.so.0.18[.0]
  179328. * 1.2.19beta1-31 13 10219 12.so.0.19[.0]
  179329. * 1.0.27rc1-6 10 10027 10.so.0.27[.0]
  179330. * 1.2.19rc1-6 13 10219 12.so.0.19[.0]
  179331. * 1.0.27 10 10027 10.so.0.27[.0]
  179332. * 1.2.19 13 10219 12.so.0.19[.0]
  179333. * 1.2.20beta01-04 13 10220 12.so.0.20[.0]
  179334. * 1.0.28rc1-6 10 10028 10.so.0.28[.0]
  179335. * 1.2.20rc1-6 13 10220 12.so.0.20[.0]
  179336. * 1.0.28 10 10028 10.so.0.28[.0]
  179337. * 1.2.20 13 10220 12.so.0.20[.0]
  179338. * 1.2.21beta1-2 13 10221 12.so.0.21[.0]
  179339. * 1.2.21rc1-3 13 10221 12.so.0.21[.0]
  179340. * 1.0.29 10 10029 10.so.0.29[.0]
  179341. * 1.2.21 13 10221 12.so.0.21[.0]
  179342. *
  179343. * Henceforth the source version will match the shared-library major
  179344. * and minor numbers; the shared-library major version number will be
  179345. * used for changes in backward compatibility, as it is intended. The
  179346. * PNG_LIBPNG_VER macro, which is not used within libpng but is available
  179347. * for applications, is an unsigned integer of the form xyyzz corresponding
  179348. * to the source version x.y.z (leading zeros in y and z). Beta versions
  179349. * were given the previous public release number plus a letter, until
  179350. * version 1.0.6j; from then on they were given the upcoming public
  179351. * release number plus "betaNN" or "rcN".
  179352. *
  179353. * Binary incompatibility exists only when applications make direct access
  179354. * to the info_ptr or png_ptr members through png.h, and the compiled
  179355. * application is loaded with a different version of the library.
  179356. *
  179357. * DLLNUM will change each time there are forward or backward changes
  179358. * in binary compatibility (e.g., when a new feature is added).
  179359. *
  179360. * See libpng.txt or libpng.3 for more information. The PNG specification
  179361. * is available as a W3C Recommendation and as an ISO Specification,
  179362. * <http://www.w3.org/TR/2003/REC-PNG-20031110/
  179363. */
  179364. /*
  179365. * COPYRIGHT NOTICE, DISCLAIMER, and LICENSE:
  179366. *
  179367. * If you modify libpng you may insert additional notices immediately following
  179368. * this sentence.
  179369. *
  179370. * libpng versions 1.2.6, August 15, 2004, through 1.2.21, October 4, 2007, are
  179371. * Copyright (c) 2004, 2006-2007 Glenn Randers-Pehrson, and are
  179372. * distributed according to the same disclaimer and license as libpng-1.2.5
  179373. * with the following individual added to the list of Contributing Authors:
  179374. *
  179375. * Cosmin Truta
  179376. *
  179377. * libpng versions 1.0.7, July 1, 2000, through 1.2.5, October 3, 2002, are
  179378. * Copyright (c) 2000-2002 Glenn Randers-Pehrson, and are
  179379. * distributed according to the same disclaimer and license as libpng-1.0.6
  179380. * with the following individuals added to the list of Contributing Authors:
  179381. *
  179382. * Simon-Pierre Cadieux
  179383. * Eric S. Raymond
  179384. * Gilles Vollant
  179385. *
  179386. * and with the following additions to the disclaimer:
  179387. *
  179388. * There is no warranty against interference with your enjoyment of the
  179389. * library or against infringement. There is no warranty that our
  179390. * efforts or the library will fulfill any of your particular purposes
  179391. * or needs. This library is provided with all faults, and the entire
  179392. * risk of satisfactory quality, performance, accuracy, and effort is with
  179393. * the user.
  179394. *
  179395. * libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are
  179396. * Copyright (c) 1998, 1999, 2000 Glenn Randers-Pehrson, and are
  179397. * distributed according to the same disclaimer and license as libpng-0.96,
  179398. * with the following individuals added to the list of Contributing Authors:
  179399. *
  179400. * Tom Lane
  179401. * Glenn Randers-Pehrson
  179402. * Willem van Schaik
  179403. *
  179404. * libpng versions 0.89, June 1996, through 0.96, May 1997, are
  179405. * Copyright (c) 1996, 1997 Andreas Dilger
  179406. * Distributed according to the same disclaimer and license as libpng-0.88,
  179407. * with the following individuals added to the list of Contributing Authors:
  179408. *
  179409. * John Bowler
  179410. * Kevin Bracey
  179411. * Sam Bushell
  179412. * Magnus Holmgren
  179413. * Greg Roelofs
  179414. * Tom Tanner
  179415. *
  179416. * libpng versions 0.5, May 1995, through 0.88, January 1996, are
  179417. * Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.
  179418. *
  179419. * For the purposes of this copyright and license, "Contributing Authors"
  179420. * is defined as the following set of individuals:
  179421. *
  179422. * Andreas Dilger
  179423. * Dave Martindale
  179424. * Guy Eric Schalnat
  179425. * Paul Schmidt
  179426. * Tim Wegner
  179427. *
  179428. * The PNG Reference Library is supplied "AS IS". The Contributing Authors
  179429. * and Group 42, Inc. disclaim all warranties, expressed or implied,
  179430. * including, without limitation, the warranties of merchantability and of
  179431. * fitness for any purpose. The Contributing Authors and Group 42, Inc.
  179432. * assume no liability for direct, indirect, incidental, special, exemplary,
  179433. * or consequential damages, which may result from the use of the PNG
  179434. * Reference Library, even if advised of the possibility of such damage.
  179435. *
  179436. * Permission is hereby granted to use, copy, modify, and distribute this
  179437. * source code, or portions hereof, for any purpose, without fee, subject
  179438. * to the following restrictions:
  179439. *
  179440. * 1. The origin of this source code must not be misrepresented.
  179441. *
  179442. * 2. Altered versions must be plainly marked as such and
  179443. * must not be misrepresented as being the original source.
  179444. *
  179445. * 3. This Copyright notice may not be removed or altered from
  179446. * any source or altered source distribution.
  179447. *
  179448. * The Contributing Authors and Group 42, Inc. specifically permit, without
  179449. * fee, and encourage the use of this source code as a component to
  179450. * supporting the PNG file format in commercial products. If you use this
  179451. * source code in a product, acknowledgment is not required but would be
  179452. * appreciated.
  179453. */
  179454. /*
  179455. * A "png_get_copyright" function is available, for convenient use in "about"
  179456. * boxes and the like:
  179457. *
  179458. * printf("%s",png_get_copyright(NULL));
  179459. *
  179460. * Also, the PNG logo (in PNG format, of course) is supplied in the
  179461. * files "pngbar.png" and "pngbar.jpg (88x31) and "pngnow.png" (98x31).
  179462. */
  179463. /*
  179464. * Libpng is OSI Certified Open Source Software. OSI Certified is a
  179465. * certification mark of the Open Source Initiative.
  179466. */
  179467. /*
  179468. * The contributing authors would like to thank all those who helped
  179469. * with testing, bug fixes, and patience. This wouldn't have been
  179470. * possible without all of you.
  179471. *
  179472. * Thanks to Frank J. T. Wojcik for helping with the documentation.
  179473. */
  179474. /*
  179475. * Y2K compliance in libpng:
  179476. * =========================
  179477. *
  179478. * October 4, 2007
  179479. *
  179480. * Since the PNG Development group is an ad-hoc body, we can't make
  179481. * an official declaration.
  179482. *
  179483. * This is your unofficial assurance that libpng from version 0.71 and
  179484. * upward through 1.2.21 are Y2K compliant. It is my belief that earlier
  179485. * versions were also Y2K compliant.
  179486. *
  179487. * Libpng only has three year fields. One is a 2-byte unsigned integer
  179488. * that will hold years up to 65535. The other two hold the date in text
  179489. * format, and will hold years up to 9999.
  179490. *
  179491. * The integer is
  179492. * "png_uint_16 year" in png_time_struct.
  179493. *
  179494. * The strings are
  179495. * "png_charp time_buffer" in png_struct and
  179496. * "near_time_buffer", which is a local character string in png.c.
  179497. *
  179498. * There are seven time-related functions:
  179499. * png.c: png_convert_to_rfc_1123() in png.c
  179500. * (formerly png_convert_to_rfc_1152() in error)
  179501. * png_convert_from_struct_tm() in pngwrite.c, called in pngwrite.c
  179502. * png_convert_from_time_t() in pngwrite.c
  179503. * png_get_tIME() in pngget.c
  179504. * png_handle_tIME() in pngrutil.c, called in pngread.c
  179505. * png_set_tIME() in pngset.c
  179506. * png_write_tIME() in pngwutil.c, called in pngwrite.c
  179507. *
  179508. * All handle dates properly in a Y2K environment. The
  179509. * png_convert_from_time_t() function calls gmtime() to convert from system
  179510. * clock time, which returns (year - 1900), which we properly convert to
  179511. * the full 4-digit year. There is a possibility that applications using
  179512. * libpng are not passing 4-digit years into the png_convert_to_rfc_1123()
  179513. * function, or that they are incorrectly passing only a 2-digit year
  179514. * instead of "year - 1900" into the png_convert_from_struct_tm() function,
  179515. * but this is not under our control. The libpng documentation has always
  179516. * stated that it works with 4-digit years, and the APIs have been
  179517. * documented as such.
  179518. *
  179519. * The tIME chunk itself is also Y2K compliant. It uses a 2-byte unsigned
  179520. * integer to hold the year, and can hold years as large as 65535.
  179521. *
  179522. * zlib, upon which libpng depends, is also Y2K compliant. It contains
  179523. * no date-related code.
  179524. *
  179525. * Glenn Randers-Pehrson
  179526. * libpng maintainer
  179527. * PNG Development Group
  179528. */
  179529. #ifndef PNG_H
  179530. #define PNG_H
  179531. /* This is not the place to learn how to use libpng. The file libpng.txt
  179532. * describes how to use libpng, and the file example.c summarizes it
  179533. * with some code on which to build. This file is useful for looking
  179534. * at the actual function definitions and structure components.
  179535. */
  179536. /* Version information for png.h - this should match the version in png.c */
  179537. #define PNG_LIBPNG_VER_STRING "1.2.21"
  179538. #define PNG_HEADER_VERSION_STRING \
  179539. " libpng version 1.2.21 - October 4, 2007\n"
  179540. #define PNG_LIBPNG_VER_SONUM 0
  179541. #define PNG_LIBPNG_VER_DLLNUM 13
  179542. /* These should match the first 3 components of PNG_LIBPNG_VER_STRING: */
  179543. #define PNG_LIBPNG_VER_MAJOR 1
  179544. #define PNG_LIBPNG_VER_MINOR 2
  179545. #define PNG_LIBPNG_VER_RELEASE 21
  179546. /* This should match the numeric part of the final component of
  179547. * PNG_LIBPNG_VER_STRING, omitting any leading zero: */
  179548. #define PNG_LIBPNG_VER_BUILD 0
  179549. /* Release Status */
  179550. #define PNG_LIBPNG_BUILD_ALPHA 1
  179551. #define PNG_LIBPNG_BUILD_BETA 2
  179552. #define PNG_LIBPNG_BUILD_RC 3
  179553. #define PNG_LIBPNG_BUILD_STABLE 4
  179554. #define PNG_LIBPNG_BUILD_RELEASE_STATUS_MASK 7
  179555. /* Release-Specific Flags */
  179556. #define PNG_LIBPNG_BUILD_PATCH 8 /* Can be OR'ed with
  179557. PNG_LIBPNG_BUILD_STABLE only */
  179558. #define PNG_LIBPNG_BUILD_PRIVATE 16 /* Cannot be OR'ed with
  179559. PNG_LIBPNG_BUILD_SPECIAL */
  179560. #define PNG_LIBPNG_BUILD_SPECIAL 32 /* Cannot be OR'ed with
  179561. PNG_LIBPNG_BUILD_PRIVATE */
  179562. #define PNG_LIBPNG_BUILD_BASE_TYPE PNG_LIBPNG_BUILD_STABLE
  179563. /* Careful here. At one time, Guy wanted to use 082, but that would be octal.
  179564. * We must not include leading zeros.
  179565. * Versions 0.7 through 1.0.0 were in the range 0 to 100 here (only
  179566. * version 1.0.0 was mis-numbered 100 instead of 10000). From
  179567. * version 1.0.1 it's xxyyzz, where x=major, y=minor, z=release */
  179568. #define PNG_LIBPNG_VER 10221 /* 1.2.21 */
  179569. #ifndef PNG_VERSION_INFO_ONLY
  179570. /* include the compression library's header */
  179571. #endif
  179572. /* include all user configurable info, including optional assembler routines */
  179573. /*** Start of inlined file: pngconf.h ***/
  179574. /* pngconf.h - machine configurable file for libpng
  179575. *
  179576. * libpng version 1.2.21 - October 4, 2007
  179577. * For conditions of distribution and use, see copyright notice in png.h
  179578. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  179579. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  179580. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  179581. */
  179582. /* Any machine specific code is near the front of this file, so if you
  179583. * are configuring libpng for a machine, you may want to read the section
  179584. * starting here down to where it starts to typedef png_color, png_text,
  179585. * and png_info.
  179586. */
  179587. #ifndef PNGCONF_H
  179588. #define PNGCONF_H
  179589. #define PNG_1_2_X
  179590. // These are some Juce config settings that should remove any unnecessary code bloat..
  179591. #define PNG_NO_STDIO 1
  179592. #define PNG_DEBUG 0
  179593. #define PNG_NO_WARNINGS 1
  179594. #define PNG_NO_ERROR_TEXT 1
  179595. #define PNG_NO_ERROR_NUMBERS 1
  179596. #define PNG_NO_USER_MEM 1
  179597. #define PNG_NO_READ_iCCP 1
  179598. #define PNG_NO_READ_UNKNOWN_CHUNKS 1
  179599. #define PNG_NO_READ_USER_CHUNKS 1
  179600. #define PNG_NO_READ_iTXt 1
  179601. #define PNG_NO_READ_sCAL 1
  179602. #define PNG_NO_READ_sPLT 1
  179603. #define png_error(a, b) png_err(a)
  179604. #define png_warning(a, b)
  179605. #define png_chunk_error(a, b) png_err(a)
  179606. #define png_chunk_warning(a, b)
  179607. /*
  179608. * PNG_USER_CONFIG has to be defined on the compiler command line. This
  179609. * includes the resource compiler for Windows DLL configurations.
  179610. */
  179611. #ifdef PNG_USER_CONFIG
  179612. # ifndef PNG_USER_PRIVATEBUILD
  179613. # define PNG_USER_PRIVATEBUILD
  179614. # endif
  179615. #include "pngusr.h"
  179616. #endif
  179617. /* PNG_CONFIGURE_LIBPNG is set by the "configure" script. */
  179618. #ifdef PNG_CONFIGURE_LIBPNG
  179619. #ifdef HAVE_CONFIG_H
  179620. #include "config.h"
  179621. #endif
  179622. #endif
  179623. /*
  179624. * Added at libpng-1.2.8
  179625. *
  179626. * If you create a private DLL you need to define in "pngusr.h" the followings:
  179627. * #define PNG_USER_PRIVATEBUILD <Describes by whom and why this version of
  179628. * the DLL was built>
  179629. * e.g. #define PNG_USER_PRIVATEBUILD "Build by MyCompany for xyz reasons."
  179630. * #define PNG_USER_DLLFNAME_POSTFIX <two-letter postfix that serve to
  179631. * distinguish your DLL from those of the official release. These
  179632. * correspond to the trailing letters that come after the version
  179633. * number and must match your private DLL name>
  179634. * e.g. // private DLL "libpng13gx.dll"
  179635. * #define PNG_USER_DLLFNAME_POSTFIX "gx"
  179636. *
  179637. * The following macros are also at your disposal if you want to complete the
  179638. * DLL VERSIONINFO structure.
  179639. * - PNG_USER_VERSIONINFO_COMMENTS
  179640. * - PNG_USER_VERSIONINFO_COMPANYNAME
  179641. * - PNG_USER_VERSIONINFO_LEGALTRADEMARKS
  179642. */
  179643. #ifdef __STDC__
  179644. #ifdef SPECIALBUILD
  179645. # pragma message("PNG_LIBPNG_SPECIALBUILD (and deprecated SPECIALBUILD)\
  179646. are now LIBPNG reserved macros. Use PNG_USER_PRIVATEBUILD instead.")
  179647. #endif
  179648. #ifdef PRIVATEBUILD
  179649. # pragma message("PRIVATEBUILD is deprecated.\
  179650. Use PNG_USER_PRIVATEBUILD instead.")
  179651. # define PNG_USER_PRIVATEBUILD PRIVATEBUILD
  179652. #endif
  179653. #endif /* __STDC__ */
  179654. #ifndef PNG_VERSION_INFO_ONLY
  179655. /* End of material added to libpng-1.2.8 */
  179656. /* Added at libpng-1.2.19, removed at libpng-1.2.20 because it caused trouble
  179657. Restored at libpng-1.2.21 */
  179658. # define PNG_WARN_UNINITIALIZED_ROW 1
  179659. /* End of material added at libpng-1.2.19/1.2.21 */
  179660. /* This is the size of the compression buffer, and thus the size of
  179661. * an IDAT chunk. Make this whatever size you feel is best for your
  179662. * machine. One of these will be allocated per png_struct. When this
  179663. * is full, it writes the data to the disk, and does some other
  179664. * calculations. Making this an extremely small size will slow
  179665. * the library down, but you may want to experiment to determine
  179666. * where it becomes significant, if you are concerned with memory
  179667. * usage. Note that zlib allocates at least 32Kb also. For readers,
  179668. * this describes the size of the buffer available to read the data in.
  179669. * Unless this gets smaller than the size of a row (compressed),
  179670. * it should not make much difference how big this is.
  179671. */
  179672. #ifndef PNG_ZBUF_SIZE
  179673. # define PNG_ZBUF_SIZE 8192
  179674. #endif
  179675. /* Enable if you want a write-only libpng */
  179676. #ifndef PNG_NO_READ_SUPPORTED
  179677. # define PNG_READ_SUPPORTED
  179678. #endif
  179679. /* Enable if you want a read-only libpng */
  179680. #ifndef PNG_NO_WRITE_SUPPORTED
  179681. # define PNG_WRITE_SUPPORTED
  179682. #endif
  179683. /* Enabled by default in 1.2.0. You can disable this if you don't need to
  179684. support PNGs that are embedded in MNG datastreams */
  179685. #if !defined(PNG_1_0_X) && !defined(PNG_NO_MNG_FEATURES)
  179686. # ifndef PNG_MNG_FEATURES_SUPPORTED
  179687. # define PNG_MNG_FEATURES_SUPPORTED
  179688. # endif
  179689. #endif
  179690. #ifndef PNG_NO_FLOATING_POINT_SUPPORTED
  179691. # ifndef PNG_FLOATING_POINT_SUPPORTED
  179692. # define PNG_FLOATING_POINT_SUPPORTED
  179693. # endif
  179694. #endif
  179695. /* If you are running on a machine where you cannot allocate more
  179696. * than 64K of memory at once, uncomment this. While libpng will not
  179697. * normally need that much memory in a chunk (unless you load up a very
  179698. * large file), zlib needs to know how big of a chunk it can use, and
  179699. * libpng thus makes sure to check any memory allocation to verify it
  179700. * will fit into memory.
  179701. #define PNG_MAX_MALLOC_64K
  179702. */
  179703. #if defined(MAXSEG_64K) && !defined(PNG_MAX_MALLOC_64K)
  179704. # define PNG_MAX_MALLOC_64K
  179705. #endif
  179706. /* Special munging to support doing things the 'cygwin' way:
  179707. * 'Normal' png-on-win32 defines/defaults:
  179708. * PNG_BUILD_DLL -- building dll
  179709. * PNG_USE_DLL -- building an application, linking to dll
  179710. * (no define) -- building static library, or building an
  179711. * application and linking to the static lib
  179712. * 'Cygwin' defines/defaults:
  179713. * PNG_BUILD_DLL -- (ignored) building the dll
  179714. * (no define) -- (ignored) building an application, linking to the dll
  179715. * PNG_STATIC -- (ignored) building the static lib, or building an
  179716. * application that links to the static lib.
  179717. * ALL_STATIC -- (ignored) building various static libs, or building an
  179718. * application that links to the static libs.
  179719. * Thus,
  179720. * a cygwin user should define either PNG_BUILD_DLL or PNG_STATIC, and
  179721. * this bit of #ifdefs will define the 'correct' config variables based on
  179722. * that. If a cygwin user *wants* to define 'PNG_USE_DLL' that's okay, but
  179723. * unnecessary.
  179724. *
  179725. * Also, the precedence order is:
  179726. * ALL_STATIC (since we can't #undef something outside our namespace)
  179727. * PNG_BUILD_DLL
  179728. * PNG_STATIC
  179729. * (nothing) == PNG_USE_DLL
  179730. *
  179731. * CYGWIN (2002-01-20): The preceding is now obsolete. With the advent
  179732. * of auto-import in binutils, we no longer need to worry about
  179733. * __declspec(dllexport) / __declspec(dllimport) and friends. Therefore,
  179734. * we don't need to worry about PNG_STATIC or ALL_STATIC when it comes
  179735. * to __declspec() stuff. However, we DO need to worry about
  179736. * PNG_BUILD_DLL and PNG_STATIC because those change some defaults
  179737. * such as CONSOLE_IO and whether GLOBAL_ARRAYS are allowed.
  179738. */
  179739. #if defined(__CYGWIN__)
  179740. # if defined(ALL_STATIC)
  179741. # if defined(PNG_BUILD_DLL)
  179742. # undef PNG_BUILD_DLL
  179743. # endif
  179744. # if defined(PNG_USE_DLL)
  179745. # undef PNG_USE_DLL
  179746. # endif
  179747. # if defined(PNG_DLL)
  179748. # undef PNG_DLL
  179749. # endif
  179750. # if !defined(PNG_STATIC)
  179751. # define PNG_STATIC
  179752. # endif
  179753. # else
  179754. # if defined (PNG_BUILD_DLL)
  179755. # if defined(PNG_STATIC)
  179756. # undef PNG_STATIC
  179757. # endif
  179758. # if defined(PNG_USE_DLL)
  179759. # undef PNG_USE_DLL
  179760. # endif
  179761. # if !defined(PNG_DLL)
  179762. # define PNG_DLL
  179763. # endif
  179764. # else
  179765. # if defined(PNG_STATIC)
  179766. # if defined(PNG_USE_DLL)
  179767. # undef PNG_USE_DLL
  179768. # endif
  179769. # if defined(PNG_DLL)
  179770. # undef PNG_DLL
  179771. # endif
  179772. # else
  179773. # if !defined(PNG_USE_DLL)
  179774. # define PNG_USE_DLL
  179775. # endif
  179776. # if !defined(PNG_DLL)
  179777. # define PNG_DLL
  179778. # endif
  179779. # endif
  179780. # endif
  179781. # endif
  179782. #endif
  179783. /* This protects us against compilers that run on a windowing system
  179784. * and thus don't have or would rather us not use the stdio types:
  179785. * stdin, stdout, and stderr. The only one currently used is stderr
  179786. * in png_error() and png_warning(). #defining PNG_NO_CONSOLE_IO will
  179787. * prevent these from being compiled and used. #defining PNG_NO_STDIO
  179788. * will also prevent these, plus will prevent the entire set of stdio
  179789. * macros and functions (FILE *, printf, etc.) from being compiled and used,
  179790. * unless (PNG_DEBUG > 0) has been #defined.
  179791. *
  179792. * #define PNG_NO_CONSOLE_IO
  179793. * #define PNG_NO_STDIO
  179794. */
  179795. #if defined(_WIN32_WCE)
  179796. # include <windows.h>
  179797. /* Console I/O functions are not supported on WindowsCE */
  179798. # define PNG_NO_CONSOLE_IO
  179799. # ifdef PNG_DEBUG
  179800. # undef PNG_DEBUG
  179801. # endif
  179802. #endif
  179803. #ifdef PNG_BUILD_DLL
  179804. # ifndef PNG_CONSOLE_IO_SUPPORTED
  179805. # ifndef PNG_NO_CONSOLE_IO
  179806. # define PNG_NO_CONSOLE_IO
  179807. # endif
  179808. # endif
  179809. #endif
  179810. # ifdef PNG_NO_STDIO
  179811. # ifndef PNG_NO_CONSOLE_IO
  179812. # define PNG_NO_CONSOLE_IO
  179813. # endif
  179814. # ifdef PNG_DEBUG
  179815. # if (PNG_DEBUG > 0)
  179816. # include <stdio.h>
  179817. # endif
  179818. # endif
  179819. # else
  179820. # if !defined(_WIN32_WCE)
  179821. /* "stdio.h" functions are not supported on WindowsCE */
  179822. # include <stdio.h>
  179823. # endif
  179824. # endif
  179825. /* This macro protects us against machines that don't have function
  179826. * prototypes (ie K&R style headers). If your compiler does not handle
  179827. * function prototypes, define this macro and use the included ansi2knr.
  179828. * I've always been able to use _NO_PROTO as the indicator, but you may
  179829. * need to drag the empty declaration out in front of here, or change the
  179830. * ifdef to suit your own needs.
  179831. */
  179832. #ifndef PNGARG
  179833. #ifdef OF /* zlib prototype munger */
  179834. # define PNGARG(arglist) OF(arglist)
  179835. #else
  179836. #ifdef _NO_PROTO
  179837. # define PNGARG(arglist) ()
  179838. # ifndef PNG_TYPECAST_NULL
  179839. # define PNG_TYPECAST_NULL
  179840. # endif
  179841. #else
  179842. # define PNGARG(arglist) arglist
  179843. #endif /* _NO_PROTO */
  179844. #endif /* OF */
  179845. #endif /* PNGARG */
  179846. /* Try to determine if we are compiling on a Mac. Note that testing for
  179847. * just __MWERKS__ is not good enough, because the Codewarrior is now used
  179848. * on non-Mac platforms.
  179849. */
  179850. #ifndef MACOS
  179851. # if (defined(__MWERKS__) && defined(macintosh)) || defined(applec) || \
  179852. defined(THINK_C) || defined(__SC__) || defined(TARGET_OS_MAC)
  179853. # define MACOS
  179854. # endif
  179855. #endif
  179856. /* enough people need this for various reasons to include it here */
  179857. #if !defined(MACOS) && !defined(RISCOS) && !defined(_WIN32_WCE)
  179858. # include <sys/types.h>
  179859. #endif
  179860. #if !defined(PNG_SETJMP_NOT_SUPPORTED) && !defined(PNG_NO_SETJMP_SUPPORTED)
  179861. # define PNG_SETJMP_SUPPORTED
  179862. #endif
  179863. #ifdef PNG_SETJMP_SUPPORTED
  179864. /* This is an attempt to force a single setjmp behaviour on Linux. If
  179865. * the X config stuff didn't define _BSD_SOURCE we wouldn't need this.
  179866. */
  179867. # ifdef __linux__
  179868. # ifdef _BSD_SOURCE
  179869. # define PNG_SAVE_BSD_SOURCE
  179870. # undef _BSD_SOURCE
  179871. # endif
  179872. # ifdef _SETJMP_H
  179873. /* If you encounter a compiler error here, see the explanation
  179874. * near the end of INSTALL.
  179875. */
  179876. __png.h__ already includes setjmp.h;
  179877. __dont__ include it again.;
  179878. # endif
  179879. # endif /* __linux__ */
  179880. /* include setjmp.h for error handling */
  179881. # include <setjmp.h>
  179882. # ifdef __linux__
  179883. # ifdef PNG_SAVE_BSD_SOURCE
  179884. # define _BSD_SOURCE
  179885. # undef PNG_SAVE_BSD_SOURCE
  179886. # endif
  179887. # endif /* __linux__ */
  179888. #endif /* PNG_SETJMP_SUPPORTED */
  179889. #ifdef BSD
  179890. #if ! JUCE_MAC
  179891. # include <strings.h>
  179892. #endif
  179893. #else
  179894. # include <string.h>
  179895. #endif
  179896. /* Other defines for things like memory and the like can go here. */
  179897. #ifdef PNG_INTERNAL
  179898. #include <stdlib.h>
  179899. /* The functions exported by PNG_EXTERN are PNG_INTERNAL functions, which
  179900. * aren't usually used outside the library (as far as I know), so it is
  179901. * debatable if they should be exported at all. In the future, when it is
  179902. * possible to have run-time registry of chunk-handling functions, some of
  179903. * these will be made available again.
  179904. #define PNG_EXTERN extern
  179905. */
  179906. #define PNG_EXTERN
  179907. /* Other defines specific to compilers can go here. Try to keep
  179908. * them inside an appropriate ifdef/endif pair for portability.
  179909. */
  179910. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  179911. # if defined(MACOS)
  179912. /* We need to check that <math.h> hasn't already been included earlier
  179913. * as it seems it doesn't agree with <fp.h>, yet we should really use
  179914. * <fp.h> if possible.
  179915. */
  179916. # if !defined(__MATH_H__) && !defined(__MATH_H) && !defined(__cmath__)
  179917. # include <fp.h>
  179918. # endif
  179919. # else
  179920. # include <math.h>
  179921. # endif
  179922. # if defined(_AMIGA) && defined(__SASC) && defined(_M68881)
  179923. /* Amiga SAS/C: We must include builtin FPU functions when compiling using
  179924. * MATH=68881
  179925. */
  179926. # include <m68881.h>
  179927. # endif
  179928. #endif
  179929. /* Codewarrior on NT has linking problems without this. */
  179930. #if (defined(__MWERKS__) && defined(WIN32)) || defined(__STDC__)
  179931. # define PNG_ALWAYS_EXTERN
  179932. #endif
  179933. /* This provides the non-ANSI (far) memory allocation routines. */
  179934. #if defined(__TURBOC__) && defined(__MSDOS__)
  179935. # include <mem.h>
  179936. # include <alloc.h>
  179937. #endif
  179938. /* I have no idea why is this necessary... */
  179939. #if defined(_MSC_VER) && (defined(WIN32) || defined(_Windows) || \
  179940. defined(_WINDOWS) || defined(_WIN32) || defined(__WIN32__))
  179941. # include <malloc.h>
  179942. #endif
  179943. /* This controls how fine the dithering gets. As this allocates
  179944. * a largish chunk of memory (32K), those who are not as concerned
  179945. * with dithering quality can decrease some or all of these.
  179946. */
  179947. #ifndef PNG_DITHER_RED_BITS
  179948. # define PNG_DITHER_RED_BITS 5
  179949. #endif
  179950. #ifndef PNG_DITHER_GREEN_BITS
  179951. # define PNG_DITHER_GREEN_BITS 5
  179952. #endif
  179953. #ifndef PNG_DITHER_BLUE_BITS
  179954. # define PNG_DITHER_BLUE_BITS 5
  179955. #endif
  179956. /* This controls how fine the gamma correction becomes when you
  179957. * are only interested in 8 bits anyway. Increasing this value
  179958. * results in more memory being used, and more pow() functions
  179959. * being called to fill in the gamma tables. Don't set this value
  179960. * less then 8, and even that may not work (I haven't tested it).
  179961. */
  179962. #ifndef PNG_MAX_GAMMA_8
  179963. # define PNG_MAX_GAMMA_8 11
  179964. #endif
  179965. /* This controls how much a difference in gamma we can tolerate before
  179966. * we actually start doing gamma conversion.
  179967. */
  179968. #ifndef PNG_GAMMA_THRESHOLD
  179969. # define PNG_GAMMA_THRESHOLD 0.05
  179970. #endif
  179971. #endif /* PNG_INTERNAL */
  179972. /* The following uses const char * instead of char * for error
  179973. * and warning message functions, so some compilers won't complain.
  179974. * If you do not want to use const, define PNG_NO_CONST here.
  179975. */
  179976. #ifndef PNG_NO_CONST
  179977. # define PNG_CONST const
  179978. #else
  179979. # define PNG_CONST
  179980. #endif
  179981. /* The following defines give you the ability to remove code from the
  179982. * library that you will not be using. I wish I could figure out how to
  179983. * automate this, but I can't do that without making it seriously hard
  179984. * on the users. So if you are not using an ability, change the #define
  179985. * to and #undef, and that part of the library will not be compiled. If
  179986. * your linker can't find a function, you may want to make sure the
  179987. * ability is defined here. Some of these depend upon some others being
  179988. * defined. I haven't figured out all the interactions here, so you may
  179989. * have to experiment awhile to get everything to compile. If you are
  179990. * creating or using a shared library, you probably shouldn't touch this,
  179991. * as it will affect the size of the structures, and this will cause bad
  179992. * things to happen if the library and/or application ever change.
  179993. */
  179994. /* Any features you will not be using can be undef'ed here */
  179995. /* GR-P, 0.96a: Set "*TRANSFORMS_SUPPORTED as default but allow user
  179996. * to turn it off with "*TRANSFORMS_NOT_SUPPORTED" or *PNG_NO_*_TRANSFORMS
  179997. * on the compile line, then pick and choose which ones to define without
  179998. * having to edit this file. It is safe to use the *TRANSFORMS_NOT_SUPPORTED
  179999. * if you only want to have a png-compliant reader/writer but don't need
  180000. * any of the extra transformations. This saves about 80 kbytes in a
  180001. * typical installation of the library. (PNG_NO_* form added in version
  180002. * 1.0.1c, for consistency)
  180003. */
  180004. /* The size of the png_text structure changed in libpng-1.0.6 when
  180005. * iTXt support was added. iTXt support was turned off by default through
  180006. * libpng-1.2.x, to support old apps that malloc the png_text structure
  180007. * instead of calling png_set_text() and letting libpng malloc it. It
  180008. * was turned on by default in libpng-1.3.0.
  180009. */
  180010. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  180011. # ifndef PNG_NO_iTXt_SUPPORTED
  180012. # define PNG_NO_iTXt_SUPPORTED
  180013. # endif
  180014. # ifndef PNG_NO_READ_iTXt
  180015. # define PNG_NO_READ_iTXt
  180016. # endif
  180017. # ifndef PNG_NO_WRITE_iTXt
  180018. # define PNG_NO_WRITE_iTXt
  180019. # endif
  180020. #endif
  180021. #if !defined(PNG_NO_iTXt_SUPPORTED)
  180022. # if !defined(PNG_READ_iTXt_SUPPORTED) && !defined(PNG_NO_READ_iTXt)
  180023. # define PNG_READ_iTXt
  180024. # endif
  180025. # if !defined(PNG_WRITE_iTXt_SUPPORTED) && !defined(PNG_NO_WRITE_iTXt)
  180026. # define PNG_WRITE_iTXt
  180027. # endif
  180028. #endif
  180029. /* The following support, added after version 1.0.0, can be turned off here en
  180030. * masse by defining PNG_LEGACY_SUPPORTED in case you need binary compatibility
  180031. * with old applications that require the length of png_struct and png_info
  180032. * to remain unchanged.
  180033. */
  180034. #ifdef PNG_LEGACY_SUPPORTED
  180035. # define PNG_NO_FREE_ME
  180036. # define PNG_NO_READ_UNKNOWN_CHUNKS
  180037. # define PNG_NO_WRITE_UNKNOWN_CHUNKS
  180038. # define PNG_NO_READ_USER_CHUNKS
  180039. # define PNG_NO_READ_iCCP
  180040. # define PNG_NO_WRITE_iCCP
  180041. # define PNG_NO_READ_iTXt
  180042. # define PNG_NO_WRITE_iTXt
  180043. # define PNG_NO_READ_sCAL
  180044. # define PNG_NO_WRITE_sCAL
  180045. # define PNG_NO_READ_sPLT
  180046. # define PNG_NO_WRITE_sPLT
  180047. # define PNG_NO_INFO_IMAGE
  180048. # define PNG_NO_READ_RGB_TO_GRAY
  180049. # define PNG_NO_READ_USER_TRANSFORM
  180050. # define PNG_NO_WRITE_USER_TRANSFORM
  180051. # define PNG_NO_USER_MEM
  180052. # define PNG_NO_READ_EMPTY_PLTE
  180053. # define PNG_NO_MNG_FEATURES
  180054. # define PNG_NO_FIXED_POINT_SUPPORTED
  180055. #endif
  180056. /* Ignore attempt to turn off both floating and fixed point support */
  180057. #if !defined(PNG_FLOATING_POINT_SUPPORTED) || \
  180058. !defined(PNG_NO_FIXED_POINT_SUPPORTED)
  180059. # define PNG_FIXED_POINT_SUPPORTED
  180060. #endif
  180061. #ifndef PNG_NO_FREE_ME
  180062. # define PNG_FREE_ME_SUPPORTED
  180063. #endif
  180064. #if defined(PNG_READ_SUPPORTED)
  180065. #if !defined(PNG_READ_TRANSFORMS_NOT_SUPPORTED) && \
  180066. !defined(PNG_NO_READ_TRANSFORMS)
  180067. # define PNG_READ_TRANSFORMS_SUPPORTED
  180068. #endif
  180069. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  180070. # ifndef PNG_NO_READ_EXPAND
  180071. # define PNG_READ_EXPAND_SUPPORTED
  180072. # endif
  180073. # ifndef PNG_NO_READ_SHIFT
  180074. # define PNG_READ_SHIFT_SUPPORTED
  180075. # endif
  180076. # ifndef PNG_NO_READ_PACK
  180077. # define PNG_READ_PACK_SUPPORTED
  180078. # endif
  180079. # ifndef PNG_NO_READ_BGR
  180080. # define PNG_READ_BGR_SUPPORTED
  180081. # endif
  180082. # ifndef PNG_NO_READ_SWAP
  180083. # define PNG_READ_SWAP_SUPPORTED
  180084. # endif
  180085. # ifndef PNG_NO_READ_PACKSWAP
  180086. # define PNG_READ_PACKSWAP_SUPPORTED
  180087. # endif
  180088. # ifndef PNG_NO_READ_INVERT
  180089. # define PNG_READ_INVERT_SUPPORTED
  180090. # endif
  180091. # ifndef PNG_NO_READ_DITHER
  180092. # define PNG_READ_DITHER_SUPPORTED
  180093. # endif
  180094. # ifndef PNG_NO_READ_BACKGROUND
  180095. # define PNG_READ_BACKGROUND_SUPPORTED
  180096. # endif
  180097. # ifndef PNG_NO_READ_16_TO_8
  180098. # define PNG_READ_16_TO_8_SUPPORTED
  180099. # endif
  180100. # ifndef PNG_NO_READ_FILLER
  180101. # define PNG_READ_FILLER_SUPPORTED
  180102. # endif
  180103. # ifndef PNG_NO_READ_GAMMA
  180104. # define PNG_READ_GAMMA_SUPPORTED
  180105. # endif
  180106. # ifndef PNG_NO_READ_GRAY_TO_RGB
  180107. # define PNG_READ_GRAY_TO_RGB_SUPPORTED
  180108. # endif
  180109. # ifndef PNG_NO_READ_SWAP_ALPHA
  180110. # define PNG_READ_SWAP_ALPHA_SUPPORTED
  180111. # endif
  180112. # ifndef PNG_NO_READ_INVERT_ALPHA
  180113. # define PNG_READ_INVERT_ALPHA_SUPPORTED
  180114. # endif
  180115. # ifndef PNG_NO_READ_STRIP_ALPHA
  180116. # define PNG_READ_STRIP_ALPHA_SUPPORTED
  180117. # endif
  180118. # ifndef PNG_NO_READ_USER_TRANSFORM
  180119. # define PNG_READ_USER_TRANSFORM_SUPPORTED
  180120. # endif
  180121. # ifndef PNG_NO_READ_RGB_TO_GRAY
  180122. # define PNG_READ_RGB_TO_GRAY_SUPPORTED
  180123. # endif
  180124. #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
  180125. #if !defined(PNG_NO_PROGRESSIVE_READ) && \
  180126. !defined(PNG_PROGRESSIVE_READ_SUPPORTED) /* if you don't do progressive */
  180127. # define PNG_PROGRESSIVE_READ_SUPPORTED /* reading. This is not talking */
  180128. #endif /* about interlacing capability! You'll */
  180129. /* still have interlacing unless you change the following line: */
  180130. #define PNG_READ_INTERLACING_SUPPORTED /* required in PNG-compliant decoders */
  180131. #ifndef PNG_NO_READ_COMPOSITE_NODIV
  180132. # ifndef PNG_NO_READ_COMPOSITED_NODIV /* libpng-1.0.x misspelling */
  180133. # define PNG_READ_COMPOSITE_NODIV_SUPPORTED /* well tested on Intel, SGI */
  180134. # endif
  180135. #endif
  180136. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  180137. /* Deprecated, will be removed from version 2.0.0.
  180138. Use PNG_MNG_FEATURES_SUPPORTED instead. */
  180139. #ifndef PNG_NO_READ_EMPTY_PLTE
  180140. # define PNG_READ_EMPTY_PLTE_SUPPORTED
  180141. #endif
  180142. #endif
  180143. #endif /* PNG_READ_SUPPORTED */
  180144. #if defined(PNG_WRITE_SUPPORTED)
  180145. # if !defined(PNG_WRITE_TRANSFORMS_NOT_SUPPORTED) && \
  180146. !defined(PNG_NO_WRITE_TRANSFORMS)
  180147. # define PNG_WRITE_TRANSFORMS_SUPPORTED
  180148. #endif
  180149. #ifdef PNG_WRITE_TRANSFORMS_SUPPORTED
  180150. # ifndef PNG_NO_WRITE_SHIFT
  180151. # define PNG_WRITE_SHIFT_SUPPORTED
  180152. # endif
  180153. # ifndef PNG_NO_WRITE_PACK
  180154. # define PNG_WRITE_PACK_SUPPORTED
  180155. # endif
  180156. # ifndef PNG_NO_WRITE_BGR
  180157. # define PNG_WRITE_BGR_SUPPORTED
  180158. # endif
  180159. # ifndef PNG_NO_WRITE_SWAP
  180160. # define PNG_WRITE_SWAP_SUPPORTED
  180161. # endif
  180162. # ifndef PNG_NO_WRITE_PACKSWAP
  180163. # define PNG_WRITE_PACKSWAP_SUPPORTED
  180164. # endif
  180165. # ifndef PNG_NO_WRITE_INVERT
  180166. # define PNG_WRITE_INVERT_SUPPORTED
  180167. # endif
  180168. # ifndef PNG_NO_WRITE_FILLER
  180169. # define PNG_WRITE_FILLER_SUPPORTED /* same as WRITE_STRIP_ALPHA */
  180170. # endif
  180171. # ifndef PNG_NO_WRITE_SWAP_ALPHA
  180172. # define PNG_WRITE_SWAP_ALPHA_SUPPORTED
  180173. # endif
  180174. # ifndef PNG_NO_WRITE_INVERT_ALPHA
  180175. # define PNG_WRITE_INVERT_ALPHA_SUPPORTED
  180176. # endif
  180177. # ifndef PNG_NO_WRITE_USER_TRANSFORM
  180178. # define PNG_WRITE_USER_TRANSFORM_SUPPORTED
  180179. # endif
  180180. #endif /* PNG_WRITE_TRANSFORMS_SUPPORTED */
  180181. #if !defined(PNG_NO_WRITE_INTERLACING_SUPPORTED) && \
  180182. !defined(PNG_WRITE_INTERLACING_SUPPORTED)
  180183. #define PNG_WRITE_INTERLACING_SUPPORTED /* not required for PNG-compliant
  180184. encoders, but can cause trouble
  180185. if left undefined */
  180186. #endif
  180187. #if !defined(PNG_NO_WRITE_WEIGHTED_FILTER) && \
  180188. !defined(PNG_WRITE_WEIGHTED_FILTER) && \
  180189. defined(PNG_FLOATING_POINT_SUPPORTED)
  180190. # define PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
  180191. #endif
  180192. #ifndef PNG_NO_WRITE_FLUSH
  180193. # define PNG_WRITE_FLUSH_SUPPORTED
  180194. #endif
  180195. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  180196. /* Deprecated, see PNG_MNG_FEATURES_SUPPORTED, above */
  180197. #ifndef PNG_NO_WRITE_EMPTY_PLTE
  180198. # define PNG_WRITE_EMPTY_PLTE_SUPPORTED
  180199. #endif
  180200. #endif
  180201. #endif /* PNG_WRITE_SUPPORTED */
  180202. #ifndef PNG_1_0_X
  180203. # ifndef PNG_NO_ERROR_NUMBERS
  180204. # define PNG_ERROR_NUMBERS_SUPPORTED
  180205. # endif
  180206. #endif /* PNG_1_0_X */
  180207. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  180208. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  180209. # ifndef PNG_NO_USER_TRANSFORM_PTR
  180210. # define PNG_USER_TRANSFORM_PTR_SUPPORTED
  180211. # endif
  180212. #endif
  180213. #ifndef PNG_NO_STDIO
  180214. # define PNG_TIME_RFC1123_SUPPORTED
  180215. #endif
  180216. /* This adds extra functions in pngget.c for accessing data from the
  180217. * info pointer (added in version 0.99)
  180218. * png_get_image_width()
  180219. * png_get_image_height()
  180220. * png_get_bit_depth()
  180221. * png_get_color_type()
  180222. * png_get_compression_type()
  180223. * png_get_filter_type()
  180224. * png_get_interlace_type()
  180225. * png_get_pixel_aspect_ratio()
  180226. * png_get_pixels_per_meter()
  180227. * png_get_x_offset_pixels()
  180228. * png_get_y_offset_pixels()
  180229. * png_get_x_offset_microns()
  180230. * png_get_y_offset_microns()
  180231. */
  180232. #if !defined(PNG_NO_EASY_ACCESS) && !defined(PNG_EASY_ACCESS_SUPPORTED)
  180233. # define PNG_EASY_ACCESS_SUPPORTED
  180234. #endif
  180235. /* PNG_ASSEMBLER_CODE was enabled by default in version 1.2.0
  180236. * and removed from version 1.2.20. The following will be removed
  180237. * from libpng-1.4.0
  180238. */
  180239. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_OPTIMIZED_CODE)
  180240. # ifndef PNG_OPTIMIZED_CODE_SUPPORTED
  180241. # define PNG_OPTIMIZED_CODE_SUPPORTED
  180242. # endif
  180243. #endif
  180244. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_ASSEMBLER_CODE)
  180245. # ifndef PNG_ASSEMBLER_CODE_SUPPORTED
  180246. # define PNG_ASSEMBLER_CODE_SUPPORTED
  180247. # endif
  180248. # if defined(__GNUC__) && defined(__x86_64__) && (__GNUC__ < 4)
  180249. /* work around 64-bit gcc compiler bugs in gcc-3.x */
  180250. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  180251. # define PNG_NO_MMX_CODE
  180252. # endif
  180253. # endif
  180254. # if defined(__APPLE__)
  180255. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  180256. # define PNG_NO_MMX_CODE
  180257. # endif
  180258. # endif
  180259. # if (defined(__MWERKS__) && ((__MWERKS__ < 0x0900) || macintosh))
  180260. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  180261. # define PNG_NO_MMX_CODE
  180262. # endif
  180263. # endif
  180264. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  180265. # define PNG_MMX_CODE_SUPPORTED
  180266. # endif
  180267. #endif
  180268. /* end of obsolete code to be removed from libpng-1.4.0 */
  180269. #if !defined(PNG_1_0_X)
  180270. #if !defined(PNG_NO_USER_MEM) && !defined(PNG_USER_MEM_SUPPORTED)
  180271. # define PNG_USER_MEM_SUPPORTED
  180272. #endif
  180273. #endif /* PNG_1_0_X */
  180274. /* Added at libpng-1.2.6 */
  180275. #if !defined(PNG_1_0_X)
  180276. #ifndef PNG_SET_USER_LIMITS_SUPPORTED
  180277. #if !defined(PNG_NO_SET_USER_LIMITS) && !defined(PNG_SET_USER_LIMITS_SUPPORTED)
  180278. # define PNG_SET_USER_LIMITS_SUPPORTED
  180279. #endif
  180280. #endif
  180281. #endif /* PNG_1_0_X */
  180282. /* Added at libpng-1.0.16 and 1.2.6. To accept all valid PNGS no matter
  180283. * how large, set these limits to 0x7fffffffL
  180284. */
  180285. #ifndef PNG_USER_WIDTH_MAX
  180286. # define PNG_USER_WIDTH_MAX 1000000L
  180287. #endif
  180288. #ifndef PNG_USER_HEIGHT_MAX
  180289. # define PNG_USER_HEIGHT_MAX 1000000L
  180290. #endif
  180291. /* These are currently experimental features, define them if you want */
  180292. /* very little testing */
  180293. /*
  180294. #ifdef PNG_READ_SUPPORTED
  180295. # ifndef PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  180296. # define PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  180297. # endif
  180298. #endif
  180299. */
  180300. /* This is only for PowerPC big-endian and 680x0 systems */
  180301. /* some testing */
  180302. /*
  180303. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  180304. # define PNG_READ_BIG_ENDIAN_SUPPORTED
  180305. #endif
  180306. */
  180307. /* Buggy compilers (e.g., gcc 2.7.2.2) need this */
  180308. /*
  180309. #define PNG_NO_POINTER_INDEXING
  180310. */
  180311. /* These functions are turned off by default, as they will be phased out. */
  180312. /*
  180313. #define PNG_USELESS_TESTS_SUPPORTED
  180314. #define PNG_CORRECT_PALETTE_SUPPORTED
  180315. */
  180316. /* Any chunks you are not interested in, you can undef here. The
  180317. * ones that allocate memory may be expecially important (hIST,
  180318. * tEXt, zTXt, tRNS, pCAL). Others will just save time and make png_info
  180319. * a bit smaller.
  180320. */
  180321. #if defined(PNG_READ_SUPPORTED) && \
  180322. !defined(PNG_READ_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  180323. !defined(PNG_NO_READ_ANCILLARY_CHUNKS)
  180324. # define PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  180325. #endif
  180326. #if defined(PNG_WRITE_SUPPORTED) && \
  180327. !defined(PNG_WRITE_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  180328. !defined(PNG_NO_WRITE_ANCILLARY_CHUNKS)
  180329. # define PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  180330. #endif
  180331. #ifdef PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  180332. #ifdef PNG_NO_READ_TEXT
  180333. # define PNG_NO_READ_iTXt
  180334. # define PNG_NO_READ_tEXt
  180335. # define PNG_NO_READ_zTXt
  180336. #endif
  180337. #ifndef PNG_NO_READ_bKGD
  180338. # define PNG_READ_bKGD_SUPPORTED
  180339. # define PNG_bKGD_SUPPORTED
  180340. #endif
  180341. #ifndef PNG_NO_READ_cHRM
  180342. # define PNG_READ_cHRM_SUPPORTED
  180343. # define PNG_cHRM_SUPPORTED
  180344. #endif
  180345. #ifndef PNG_NO_READ_gAMA
  180346. # define PNG_READ_gAMA_SUPPORTED
  180347. # define PNG_gAMA_SUPPORTED
  180348. #endif
  180349. #ifndef PNG_NO_READ_hIST
  180350. # define PNG_READ_hIST_SUPPORTED
  180351. # define PNG_hIST_SUPPORTED
  180352. #endif
  180353. #ifndef PNG_NO_READ_iCCP
  180354. # define PNG_READ_iCCP_SUPPORTED
  180355. # define PNG_iCCP_SUPPORTED
  180356. #endif
  180357. #ifndef PNG_NO_READ_iTXt
  180358. # ifndef PNG_READ_iTXt_SUPPORTED
  180359. # define PNG_READ_iTXt_SUPPORTED
  180360. # endif
  180361. # ifndef PNG_iTXt_SUPPORTED
  180362. # define PNG_iTXt_SUPPORTED
  180363. # endif
  180364. #endif
  180365. #ifndef PNG_NO_READ_oFFs
  180366. # define PNG_READ_oFFs_SUPPORTED
  180367. # define PNG_oFFs_SUPPORTED
  180368. #endif
  180369. #ifndef PNG_NO_READ_pCAL
  180370. # define PNG_READ_pCAL_SUPPORTED
  180371. # define PNG_pCAL_SUPPORTED
  180372. #endif
  180373. #ifndef PNG_NO_READ_sCAL
  180374. # define PNG_READ_sCAL_SUPPORTED
  180375. # define PNG_sCAL_SUPPORTED
  180376. #endif
  180377. #ifndef PNG_NO_READ_pHYs
  180378. # define PNG_READ_pHYs_SUPPORTED
  180379. # define PNG_pHYs_SUPPORTED
  180380. #endif
  180381. #ifndef PNG_NO_READ_sBIT
  180382. # define PNG_READ_sBIT_SUPPORTED
  180383. # define PNG_sBIT_SUPPORTED
  180384. #endif
  180385. #ifndef PNG_NO_READ_sPLT
  180386. # define PNG_READ_sPLT_SUPPORTED
  180387. # define PNG_sPLT_SUPPORTED
  180388. #endif
  180389. #ifndef PNG_NO_READ_sRGB
  180390. # define PNG_READ_sRGB_SUPPORTED
  180391. # define PNG_sRGB_SUPPORTED
  180392. #endif
  180393. #ifndef PNG_NO_READ_tEXt
  180394. # define PNG_READ_tEXt_SUPPORTED
  180395. # define PNG_tEXt_SUPPORTED
  180396. #endif
  180397. #ifndef PNG_NO_READ_tIME
  180398. # define PNG_READ_tIME_SUPPORTED
  180399. # define PNG_tIME_SUPPORTED
  180400. #endif
  180401. #ifndef PNG_NO_READ_tRNS
  180402. # define PNG_READ_tRNS_SUPPORTED
  180403. # define PNG_tRNS_SUPPORTED
  180404. #endif
  180405. #ifndef PNG_NO_READ_zTXt
  180406. # define PNG_READ_zTXt_SUPPORTED
  180407. # define PNG_zTXt_SUPPORTED
  180408. #endif
  180409. #ifndef PNG_NO_READ_UNKNOWN_CHUNKS
  180410. # define PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
  180411. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  180412. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  180413. # endif
  180414. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  180415. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  180416. # endif
  180417. #endif
  180418. #if !defined(PNG_NO_READ_USER_CHUNKS) && \
  180419. defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  180420. # define PNG_READ_USER_CHUNKS_SUPPORTED
  180421. # define PNG_USER_CHUNKS_SUPPORTED
  180422. # ifdef PNG_NO_READ_UNKNOWN_CHUNKS
  180423. # undef PNG_NO_READ_UNKNOWN_CHUNKS
  180424. # endif
  180425. # ifdef PNG_NO_HANDLE_AS_UNKNOWN
  180426. # undef PNG_NO_HANDLE_AS_UNKNOWN
  180427. # endif
  180428. #endif
  180429. #ifndef PNG_NO_READ_OPT_PLTE
  180430. # define PNG_READ_OPT_PLTE_SUPPORTED /* only affects support of the */
  180431. #endif /* optional PLTE chunk in RGB and RGBA images */
  180432. #if defined(PNG_READ_iTXt_SUPPORTED) || defined(PNG_READ_tEXt_SUPPORTED) || \
  180433. defined(PNG_READ_zTXt_SUPPORTED)
  180434. # define PNG_READ_TEXT_SUPPORTED
  180435. # define PNG_TEXT_SUPPORTED
  180436. #endif
  180437. #endif /* PNG_READ_ANCILLARY_CHUNKS_SUPPORTED */
  180438. #ifdef PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  180439. #ifdef PNG_NO_WRITE_TEXT
  180440. # define PNG_NO_WRITE_iTXt
  180441. # define PNG_NO_WRITE_tEXt
  180442. # define PNG_NO_WRITE_zTXt
  180443. #endif
  180444. #ifndef PNG_NO_WRITE_bKGD
  180445. # define PNG_WRITE_bKGD_SUPPORTED
  180446. # ifndef PNG_bKGD_SUPPORTED
  180447. # define PNG_bKGD_SUPPORTED
  180448. # endif
  180449. #endif
  180450. #ifndef PNG_NO_WRITE_cHRM
  180451. # define PNG_WRITE_cHRM_SUPPORTED
  180452. # ifndef PNG_cHRM_SUPPORTED
  180453. # define PNG_cHRM_SUPPORTED
  180454. # endif
  180455. #endif
  180456. #ifndef PNG_NO_WRITE_gAMA
  180457. # define PNG_WRITE_gAMA_SUPPORTED
  180458. # ifndef PNG_gAMA_SUPPORTED
  180459. # define PNG_gAMA_SUPPORTED
  180460. # endif
  180461. #endif
  180462. #ifndef PNG_NO_WRITE_hIST
  180463. # define PNG_WRITE_hIST_SUPPORTED
  180464. # ifndef PNG_hIST_SUPPORTED
  180465. # define PNG_hIST_SUPPORTED
  180466. # endif
  180467. #endif
  180468. #ifndef PNG_NO_WRITE_iCCP
  180469. # define PNG_WRITE_iCCP_SUPPORTED
  180470. # ifndef PNG_iCCP_SUPPORTED
  180471. # define PNG_iCCP_SUPPORTED
  180472. # endif
  180473. #endif
  180474. #ifndef PNG_NO_WRITE_iTXt
  180475. # ifndef PNG_WRITE_iTXt_SUPPORTED
  180476. # define PNG_WRITE_iTXt_SUPPORTED
  180477. # endif
  180478. # ifndef PNG_iTXt_SUPPORTED
  180479. # define PNG_iTXt_SUPPORTED
  180480. # endif
  180481. #endif
  180482. #ifndef PNG_NO_WRITE_oFFs
  180483. # define PNG_WRITE_oFFs_SUPPORTED
  180484. # ifndef PNG_oFFs_SUPPORTED
  180485. # define PNG_oFFs_SUPPORTED
  180486. # endif
  180487. #endif
  180488. #ifndef PNG_NO_WRITE_pCAL
  180489. # define PNG_WRITE_pCAL_SUPPORTED
  180490. # ifndef PNG_pCAL_SUPPORTED
  180491. # define PNG_pCAL_SUPPORTED
  180492. # endif
  180493. #endif
  180494. #ifndef PNG_NO_WRITE_sCAL
  180495. # define PNG_WRITE_sCAL_SUPPORTED
  180496. # ifndef PNG_sCAL_SUPPORTED
  180497. # define PNG_sCAL_SUPPORTED
  180498. # endif
  180499. #endif
  180500. #ifndef PNG_NO_WRITE_pHYs
  180501. # define PNG_WRITE_pHYs_SUPPORTED
  180502. # ifndef PNG_pHYs_SUPPORTED
  180503. # define PNG_pHYs_SUPPORTED
  180504. # endif
  180505. #endif
  180506. #ifndef PNG_NO_WRITE_sBIT
  180507. # define PNG_WRITE_sBIT_SUPPORTED
  180508. # ifndef PNG_sBIT_SUPPORTED
  180509. # define PNG_sBIT_SUPPORTED
  180510. # endif
  180511. #endif
  180512. #ifndef PNG_NO_WRITE_sPLT
  180513. # define PNG_WRITE_sPLT_SUPPORTED
  180514. # ifndef PNG_sPLT_SUPPORTED
  180515. # define PNG_sPLT_SUPPORTED
  180516. # endif
  180517. #endif
  180518. #ifndef PNG_NO_WRITE_sRGB
  180519. # define PNG_WRITE_sRGB_SUPPORTED
  180520. # ifndef PNG_sRGB_SUPPORTED
  180521. # define PNG_sRGB_SUPPORTED
  180522. # endif
  180523. #endif
  180524. #ifndef PNG_NO_WRITE_tEXt
  180525. # define PNG_WRITE_tEXt_SUPPORTED
  180526. # ifndef PNG_tEXt_SUPPORTED
  180527. # define PNG_tEXt_SUPPORTED
  180528. # endif
  180529. #endif
  180530. #ifndef PNG_NO_WRITE_tIME
  180531. # define PNG_WRITE_tIME_SUPPORTED
  180532. # ifndef PNG_tIME_SUPPORTED
  180533. # define PNG_tIME_SUPPORTED
  180534. # endif
  180535. #endif
  180536. #ifndef PNG_NO_WRITE_tRNS
  180537. # define PNG_WRITE_tRNS_SUPPORTED
  180538. # ifndef PNG_tRNS_SUPPORTED
  180539. # define PNG_tRNS_SUPPORTED
  180540. # endif
  180541. #endif
  180542. #ifndef PNG_NO_WRITE_zTXt
  180543. # define PNG_WRITE_zTXt_SUPPORTED
  180544. # ifndef PNG_zTXt_SUPPORTED
  180545. # define PNG_zTXt_SUPPORTED
  180546. # endif
  180547. #endif
  180548. #ifndef PNG_NO_WRITE_UNKNOWN_CHUNKS
  180549. # define PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
  180550. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  180551. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  180552. # endif
  180553. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  180554. # ifndef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  180555. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  180556. # endif
  180557. # endif
  180558. #endif
  180559. #if defined(PNG_WRITE_iTXt_SUPPORTED) || defined(PNG_WRITE_tEXt_SUPPORTED) || \
  180560. defined(PNG_WRITE_zTXt_SUPPORTED)
  180561. # define PNG_WRITE_TEXT_SUPPORTED
  180562. # ifndef PNG_TEXT_SUPPORTED
  180563. # define PNG_TEXT_SUPPORTED
  180564. # endif
  180565. #endif
  180566. #endif /* PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED */
  180567. /* Turn this off to disable png_read_png() and
  180568. * png_write_png() and leave the row_pointers member
  180569. * out of the info structure.
  180570. */
  180571. #ifndef PNG_NO_INFO_IMAGE
  180572. # define PNG_INFO_IMAGE_SUPPORTED
  180573. #endif
  180574. /* need the time information for reading tIME chunks */
  180575. #if defined(PNG_tIME_SUPPORTED)
  180576. # if !defined(_WIN32_WCE)
  180577. /* "time.h" functions are not supported on WindowsCE */
  180578. # include <time.h>
  180579. # endif
  180580. #endif
  180581. /* Some typedefs to get us started. These should be safe on most of the
  180582. * common platforms. The typedefs should be at least as large as the
  180583. * numbers suggest (a png_uint_32 must be at least 32 bits long), but they
  180584. * don't have to be exactly that size. Some compilers dislike passing
  180585. * unsigned shorts as function parameters, so you may be better off using
  180586. * unsigned int for png_uint_16. Likewise, for 64-bit systems, you may
  180587. * want to have unsigned int for png_uint_32 instead of unsigned long.
  180588. */
  180589. typedef unsigned long png_uint_32;
  180590. typedef long png_int_32;
  180591. typedef unsigned short png_uint_16;
  180592. typedef short png_int_16;
  180593. typedef unsigned char png_byte;
  180594. /* This is usually size_t. It is typedef'ed just in case you need it to
  180595. change (I'm not sure if you will or not, so I thought I'd be safe) */
  180596. #ifdef PNG_SIZE_T
  180597. typedef PNG_SIZE_T png_size_t;
  180598. # define png_sizeof(x) png_convert_size(sizeof (x))
  180599. #else
  180600. typedef size_t png_size_t;
  180601. # define png_sizeof(x) sizeof (x)
  180602. #endif
  180603. /* The following is needed for medium model support. It cannot be in the
  180604. * PNG_INTERNAL section. Needs modification for other compilers besides
  180605. * MSC. Model independent support declares all arrays and pointers to be
  180606. * large using the far keyword. The zlib version used must also support
  180607. * model independent data. As of version zlib 1.0.4, the necessary changes
  180608. * have been made in zlib. The USE_FAR_KEYWORD define triggers other
  180609. * changes that are needed. (Tim Wegner)
  180610. */
  180611. /* Separate compiler dependencies (problem here is that zlib.h always
  180612. defines FAR. (SJT) */
  180613. #ifdef __BORLANDC__
  180614. # if defined(__LARGE__) || defined(__HUGE__) || defined(__COMPACT__)
  180615. # define LDATA 1
  180616. # else
  180617. # define LDATA 0
  180618. # endif
  180619. /* GRR: why is Cygwin in here? Cygwin is not Borland C... */
  180620. # if !defined(__WIN32__) && !defined(__FLAT__) && !defined(__CYGWIN__)
  180621. # define PNG_MAX_MALLOC_64K
  180622. # if (LDATA != 1)
  180623. # ifndef FAR
  180624. # define FAR __far
  180625. # endif
  180626. # define USE_FAR_KEYWORD
  180627. # endif /* LDATA != 1 */
  180628. /* Possibly useful for moving data out of default segment.
  180629. * Uncomment it if you want. Could also define FARDATA as
  180630. * const if your compiler supports it. (SJT)
  180631. # define FARDATA FAR
  180632. */
  180633. # endif /* __WIN32__, __FLAT__, __CYGWIN__ */
  180634. #endif /* __BORLANDC__ */
  180635. /* Suggest testing for specific compiler first before testing for
  180636. * FAR. The Watcom compiler defines both __MEDIUM__ and M_I86MM,
  180637. * making reliance oncertain keywords suspect. (SJT)
  180638. */
  180639. /* MSC Medium model */
  180640. #if defined(FAR)
  180641. # if defined(M_I86MM)
  180642. # define USE_FAR_KEYWORD
  180643. # define FARDATA FAR
  180644. # include <dos.h>
  180645. # endif
  180646. #endif
  180647. /* SJT: default case */
  180648. #ifndef FAR
  180649. # define FAR
  180650. #endif
  180651. /* At this point FAR is always defined */
  180652. #ifndef FARDATA
  180653. # define FARDATA
  180654. #endif
  180655. /* Typedef for floating-point numbers that are converted
  180656. to fixed-point with a multiple of 100,000, e.g., int_gamma */
  180657. typedef png_int_32 png_fixed_point;
  180658. /* Add typedefs for pointers */
  180659. typedef void FAR * png_voidp;
  180660. typedef png_byte FAR * png_bytep;
  180661. typedef png_uint_32 FAR * png_uint_32p;
  180662. typedef png_int_32 FAR * png_int_32p;
  180663. typedef png_uint_16 FAR * png_uint_16p;
  180664. typedef png_int_16 FAR * png_int_16p;
  180665. typedef PNG_CONST char FAR * png_const_charp;
  180666. typedef char FAR * png_charp;
  180667. typedef png_fixed_point FAR * png_fixed_point_p;
  180668. #ifndef PNG_NO_STDIO
  180669. #if defined(_WIN32_WCE)
  180670. typedef HANDLE png_FILE_p;
  180671. #else
  180672. typedef FILE * png_FILE_p;
  180673. #endif
  180674. #endif
  180675. #ifdef PNG_FLOATING_POINT_SUPPORTED
  180676. typedef double FAR * png_doublep;
  180677. #endif
  180678. /* Pointers to pointers; i.e. arrays */
  180679. typedef png_byte FAR * FAR * png_bytepp;
  180680. typedef png_uint_32 FAR * FAR * png_uint_32pp;
  180681. typedef png_int_32 FAR * FAR * png_int_32pp;
  180682. typedef png_uint_16 FAR * FAR * png_uint_16pp;
  180683. typedef png_int_16 FAR * FAR * png_int_16pp;
  180684. typedef PNG_CONST char FAR * FAR * png_const_charpp;
  180685. typedef char FAR * FAR * png_charpp;
  180686. typedef png_fixed_point FAR * FAR * png_fixed_point_pp;
  180687. #ifdef PNG_FLOATING_POINT_SUPPORTED
  180688. typedef double FAR * FAR * png_doublepp;
  180689. #endif
  180690. /* Pointers to pointers to pointers; i.e., pointer to array */
  180691. typedef char FAR * FAR * FAR * png_charppp;
  180692. #if 0
  180693. /* SPC - Is this stuff deprecated? */
  180694. /* It'll be removed as of libpng-1.3.0 - GR-P */
  180695. /* libpng typedefs for types in zlib. If zlib changes
  180696. * or another compression library is used, then change these.
  180697. * Eliminates need to change all the source files.
  180698. */
  180699. typedef charf * png_zcharp;
  180700. typedef charf * FAR * png_zcharpp;
  180701. typedef z_stream FAR * png_zstreamp;
  180702. #endif /* (PNG_1_0_X) || defined(PNG_1_2_X) */
  180703. /*
  180704. * Define PNG_BUILD_DLL if the module being built is a Windows
  180705. * LIBPNG DLL.
  180706. *
  180707. * Define PNG_USE_DLL if you want to *link* to the Windows LIBPNG DLL.
  180708. * It is equivalent to Microsoft predefined macro _DLL that is
  180709. * automatically defined when you compile using the share
  180710. * version of the CRT (C Run-Time library)
  180711. *
  180712. * The cygwin mods make this behavior a little different:
  180713. * Define PNG_BUILD_DLL if you are building a dll for use with cygwin
  180714. * Define PNG_STATIC if you are building a static library for use with cygwin,
  180715. * -or- if you are building an application that you want to link to the
  180716. * static library.
  180717. * PNG_USE_DLL is defined by default (no user action needed) unless one of
  180718. * the other flags is defined.
  180719. */
  180720. #if !defined(PNG_DLL) && (defined(PNG_BUILD_DLL) || defined(PNG_USE_DLL))
  180721. # define PNG_DLL
  180722. #endif
  180723. /* If CYGWIN, then disallow GLOBAL ARRAYS unless building a static lib.
  180724. * When building a static lib, default to no GLOBAL ARRAYS, but allow
  180725. * command-line override
  180726. */
  180727. #if defined(__CYGWIN__)
  180728. # if !defined(PNG_STATIC)
  180729. # if defined(PNG_USE_GLOBAL_ARRAYS)
  180730. # undef PNG_USE_GLOBAL_ARRAYS
  180731. # endif
  180732. # if !defined(PNG_USE_LOCAL_ARRAYS)
  180733. # define PNG_USE_LOCAL_ARRAYS
  180734. # endif
  180735. # else
  180736. # if defined(PNG_USE_LOCAL_ARRAYS) || defined(PNG_NO_GLOBAL_ARRAYS)
  180737. # if defined(PNG_USE_GLOBAL_ARRAYS)
  180738. # undef PNG_USE_GLOBAL_ARRAYS
  180739. # endif
  180740. # endif
  180741. # endif
  180742. # if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  180743. # define PNG_USE_LOCAL_ARRAYS
  180744. # endif
  180745. #endif
  180746. /* Do not use global arrays (helps with building DLL's)
  180747. * They are no longer used in libpng itself, since version 1.0.5c,
  180748. * but might be required for some pre-1.0.5c applications.
  180749. */
  180750. #if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  180751. # if defined(PNG_NO_GLOBAL_ARRAYS) || \
  180752. (defined(__GNUC__) && defined(PNG_DLL)) || defined(_MSC_VER)
  180753. # define PNG_USE_LOCAL_ARRAYS
  180754. # else
  180755. # define PNG_USE_GLOBAL_ARRAYS
  180756. # endif
  180757. #endif
  180758. #if defined(__CYGWIN__)
  180759. # undef PNGAPI
  180760. # define PNGAPI __cdecl
  180761. # undef PNG_IMPEXP
  180762. # define PNG_IMPEXP
  180763. #endif
  180764. /* If you define PNGAPI, e.g., with compiler option "-DPNGAPI=__stdcall",
  180765. * you may get warnings regarding the linkage of png_zalloc and png_zfree.
  180766. * Don't ignore those warnings; you must also reset the default calling
  180767. * convention in your compiler to match your PNGAPI, and you must build
  180768. * zlib and your applications the same way you build libpng.
  180769. */
  180770. #if defined(__MINGW32__) && !defined(PNG_MODULEDEF)
  180771. # ifndef PNG_NO_MODULEDEF
  180772. # define PNG_NO_MODULEDEF
  180773. # endif
  180774. #endif
  180775. #if !defined(PNG_IMPEXP) && defined(PNG_BUILD_DLL) && !defined(PNG_NO_MODULEDEF)
  180776. # define PNG_IMPEXP
  180777. #endif
  180778. #if defined(PNG_DLL) || defined(_DLL) || defined(__DLL__ ) || \
  180779. (( defined(_Windows) || defined(_WINDOWS) || \
  180780. defined(WIN32) || defined(_WIN32) || defined(__WIN32__) ))
  180781. # ifndef PNGAPI
  180782. # if defined(__GNUC__) || (defined (_MSC_VER) && (_MSC_VER >= 800))
  180783. # define PNGAPI __cdecl
  180784. # else
  180785. # define PNGAPI _cdecl
  180786. # endif
  180787. # endif
  180788. # if !defined(PNG_IMPEXP) && (!defined(PNG_DLL) || \
  180789. 0 /* WINCOMPILER_WITH_NO_SUPPORT_FOR_DECLIMPEXP */)
  180790. # define PNG_IMPEXP
  180791. # endif
  180792. # if !defined(PNG_IMPEXP)
  180793. # define PNG_EXPORT_TYPE1(type,symbol) PNG_IMPEXP type PNGAPI symbol
  180794. # define PNG_EXPORT_TYPE2(type,symbol) type PNG_IMPEXP PNGAPI symbol
  180795. /* Borland/Microsoft */
  180796. # if defined(_MSC_VER) || defined(__BORLANDC__)
  180797. # if (_MSC_VER >= 800) || (__BORLANDC__ >= 0x500)
  180798. # define PNG_EXPORT PNG_EXPORT_TYPE1
  180799. # else
  180800. # define PNG_EXPORT PNG_EXPORT_TYPE2
  180801. # if defined(PNG_BUILD_DLL)
  180802. # define PNG_IMPEXP __export
  180803. # else
  180804. # define PNG_IMPEXP /*__import */ /* doesn't exist AFAIK in
  180805. VC++ */
  180806. # endif /* Exists in Borland C++ for
  180807. C++ classes (== huge) */
  180808. # endif
  180809. # endif
  180810. # if !defined(PNG_IMPEXP)
  180811. # if defined(PNG_BUILD_DLL)
  180812. # define PNG_IMPEXP __declspec(dllexport)
  180813. # else
  180814. # define PNG_IMPEXP __declspec(dllimport)
  180815. # endif
  180816. # endif
  180817. # endif /* PNG_IMPEXP */
  180818. #else /* !(DLL || non-cygwin WINDOWS) */
  180819. # if (defined(__IBMC__) || defined(__IBMCPP__)) && defined(__OS2__)
  180820. # ifndef PNGAPI
  180821. # define PNGAPI _System
  180822. # endif
  180823. # else
  180824. # if 0 /* ... other platforms, with other meanings */
  180825. # endif
  180826. # endif
  180827. #endif
  180828. #ifndef PNGAPI
  180829. # define PNGAPI
  180830. #endif
  180831. #ifndef PNG_IMPEXP
  180832. # define PNG_IMPEXP
  180833. #endif
  180834. #ifdef PNG_BUILDSYMS
  180835. # ifndef PNG_EXPORT
  180836. # define PNG_EXPORT(type,symbol) PNG_FUNCTION_EXPORT symbol END
  180837. # endif
  180838. # ifdef PNG_USE_GLOBAL_ARRAYS
  180839. # ifndef PNG_EXPORT_VAR
  180840. # define PNG_EXPORT_VAR(type) PNG_DATA_EXPORT
  180841. # endif
  180842. # endif
  180843. #endif
  180844. #ifndef PNG_EXPORT
  180845. # define PNG_EXPORT(type,symbol) PNG_IMPEXP type PNGAPI symbol
  180846. #endif
  180847. #ifdef PNG_USE_GLOBAL_ARRAYS
  180848. # ifndef PNG_EXPORT_VAR
  180849. # define PNG_EXPORT_VAR(type) extern PNG_IMPEXP type
  180850. # endif
  180851. #endif
  180852. /* User may want to use these so they are not in PNG_INTERNAL. Any library
  180853. * functions that are passed far data must be model independent.
  180854. */
  180855. #ifndef PNG_ABORT
  180856. # define PNG_ABORT() abort()
  180857. #endif
  180858. #ifdef PNG_SETJMP_SUPPORTED
  180859. # define png_jmpbuf(png_ptr) ((png_ptr)->jmpbuf)
  180860. #else
  180861. # define png_jmpbuf(png_ptr) \
  180862. (LIBPNG_WAS_COMPILED_WITH__PNG_SETJMP_NOT_SUPPORTED)
  180863. #endif
  180864. #if defined(USE_FAR_KEYWORD) /* memory model independent fns */
  180865. /* use this to make far-to-near assignments */
  180866. # define CHECK 1
  180867. # define NOCHECK 0
  180868. # define CVT_PTR(ptr) (png_far_to_near(png_ptr,ptr,CHECK))
  180869. # define CVT_PTR_NOCHECK(ptr) (png_far_to_near(png_ptr,ptr,NOCHECK))
  180870. # define png_snprintf _fsnprintf /* Added to v 1.2.19 */
  180871. # define png_strcpy _fstrcpy
  180872. # define png_strncpy _fstrncpy /* Added to v 1.2.6 */
  180873. # define png_strlen _fstrlen
  180874. # define png_memcmp _fmemcmp /* SJT: added */
  180875. # define png_memcpy _fmemcpy
  180876. # define png_memset _fmemset
  180877. #else /* use the usual functions */
  180878. # define CVT_PTR(ptr) (ptr)
  180879. # define CVT_PTR_NOCHECK(ptr) (ptr)
  180880. # ifndef PNG_NO_SNPRINTF
  180881. # ifdef _MSC_VER
  180882. # define png_snprintf _snprintf /* Added to v 1.2.19 */
  180883. # define png_snprintf2 _snprintf
  180884. # define png_snprintf6 _snprintf
  180885. # else
  180886. # define png_snprintf snprintf /* Added to v 1.2.19 */
  180887. # define png_snprintf2 snprintf
  180888. # define png_snprintf6 snprintf
  180889. # endif
  180890. # else
  180891. /* You don't have or don't want to use snprintf(). Caution: Using
  180892. * sprintf instead of snprintf exposes your application to accidental
  180893. * or malevolent buffer overflows. If you don't have snprintf()
  180894. * as a general rule you should provide one (you can get one from
  180895. * Portable OpenSSH). */
  180896. # define png_snprintf(s1,n,fmt,x1) sprintf(s1,fmt,x1)
  180897. # define png_snprintf2(s1,n,fmt,x1,x2) sprintf(s1,fmt,x1,x2)
  180898. # define png_snprintf6(s1,n,fmt,x1,x2,x3,x4,x5,x6) \
  180899. sprintf(s1,fmt,x1,x2,x3,x4,x5,x6)
  180900. # endif
  180901. # define png_strcpy strcpy
  180902. # define png_strncpy strncpy /* Added to v 1.2.6 */
  180903. # define png_strlen strlen
  180904. # define png_memcmp memcmp /* SJT: added */
  180905. # define png_memcpy memcpy
  180906. # define png_memset memset
  180907. #endif
  180908. /* End of memory model independent support */
  180909. /* Just a little check that someone hasn't tried to define something
  180910. * contradictory.
  180911. */
  180912. #if (PNG_ZBUF_SIZE > 65536L) && defined(PNG_MAX_MALLOC_64K)
  180913. # undef PNG_ZBUF_SIZE
  180914. # define PNG_ZBUF_SIZE 65536L
  180915. #endif
  180916. /* Added at libpng-1.2.8 */
  180917. #endif /* PNG_VERSION_INFO_ONLY */
  180918. #endif /* PNGCONF_H */
  180919. /*** End of inlined file: pngconf.h ***/
  180920. #ifdef _MSC_VER
  180921. #pragma warning (disable: 4996 4100)
  180922. #endif
  180923. /*
  180924. * Added at libpng-1.2.8 */
  180925. /* Ref MSDN: Private as priority over Special
  180926. * VS_FF_PRIVATEBUILD File *was not* built using standard release
  180927. * procedures. If this value is given, the StringFileInfo block must
  180928. * contain a PrivateBuild string.
  180929. *
  180930. * VS_FF_SPECIALBUILD File *was* built by the original company using
  180931. * standard release procedures but is a variation of the standard
  180932. * file of the same version number. If this value is given, the
  180933. * StringFileInfo block must contain a SpecialBuild string.
  180934. */
  180935. #if defined(PNG_USER_PRIVATEBUILD)
  180936. # define PNG_LIBPNG_BUILD_TYPE \
  180937. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_PRIVATE)
  180938. #else
  180939. # if defined(PNG_LIBPNG_SPECIALBUILD)
  180940. # define PNG_LIBPNG_BUILD_TYPE \
  180941. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_SPECIAL)
  180942. # else
  180943. # define PNG_LIBPNG_BUILD_TYPE (PNG_LIBPNG_BUILD_BASE_TYPE)
  180944. # endif
  180945. #endif
  180946. #ifndef PNG_VERSION_INFO_ONLY
  180947. /* Inhibit C++ name-mangling for libpng functions but not for system calls. */
  180948. #ifdef __cplusplus
  180949. extern "C" {
  180950. #endif /* __cplusplus */
  180951. /* This file is arranged in several sections. The first section contains
  180952. * structure and type definitions. The second section contains the external
  180953. * library functions, while the third has the internal library functions,
  180954. * which applications aren't expected to use directly.
  180955. */
  180956. #ifndef PNG_NO_TYPECAST_NULL
  180957. #define int_p_NULL (int *)NULL
  180958. #define png_bytep_NULL (png_bytep)NULL
  180959. #define png_bytepp_NULL (png_bytepp)NULL
  180960. #define png_doublep_NULL (png_doublep)NULL
  180961. #define png_error_ptr_NULL (png_error_ptr)NULL
  180962. #define png_flush_ptr_NULL (png_flush_ptr)NULL
  180963. #define png_free_ptr_NULL (png_free_ptr)NULL
  180964. #define png_infopp_NULL (png_infopp)NULL
  180965. #define png_malloc_ptr_NULL (png_malloc_ptr)NULL
  180966. #define png_read_status_ptr_NULL (png_read_status_ptr)NULL
  180967. #define png_rw_ptr_NULL (png_rw_ptr)NULL
  180968. #define png_structp_NULL (png_structp)NULL
  180969. #define png_uint_16p_NULL (png_uint_16p)NULL
  180970. #define png_voidp_NULL (png_voidp)NULL
  180971. #define png_write_status_ptr_NULL (png_write_status_ptr)NULL
  180972. #else
  180973. #define int_p_NULL NULL
  180974. #define png_bytep_NULL NULL
  180975. #define png_bytepp_NULL NULL
  180976. #define png_doublep_NULL NULL
  180977. #define png_error_ptr_NULL NULL
  180978. #define png_flush_ptr_NULL NULL
  180979. #define png_free_ptr_NULL NULL
  180980. #define png_infopp_NULL NULL
  180981. #define png_malloc_ptr_NULL NULL
  180982. #define png_read_status_ptr_NULL NULL
  180983. #define png_rw_ptr_NULL NULL
  180984. #define png_structp_NULL NULL
  180985. #define png_uint_16p_NULL NULL
  180986. #define png_voidp_NULL NULL
  180987. #define png_write_status_ptr_NULL NULL
  180988. #endif
  180989. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  180990. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  180991. /* Version information for C files, stored in png.c. This had better match
  180992. * the version above.
  180993. */
  180994. #ifdef PNG_USE_GLOBAL_ARRAYS
  180995. PNG_EXPORT_VAR (PNG_CONST char) png_libpng_ver[18];
  180996. /* need room for 99.99.99beta99z */
  180997. #else
  180998. #define png_libpng_ver png_get_header_ver(NULL)
  180999. #endif
  181000. #ifdef PNG_USE_GLOBAL_ARRAYS
  181001. /* This was removed in version 1.0.5c */
  181002. /* Structures to facilitate easy interlacing. See png.c for more details */
  181003. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_start[7];
  181004. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_inc[7];
  181005. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_ystart[7];
  181006. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_yinc[7];
  181007. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_mask[7];
  181008. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_dsp_mask[7];
  181009. /* This isn't currently used. If you need it, see png.c for more details.
  181010. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_height[7];
  181011. */
  181012. #endif
  181013. #endif /* PNG_NO_EXTERN */
  181014. /* Three color definitions. The order of the red, green, and blue, (and the
  181015. * exact size) is not important, although the size of the fields need to
  181016. * be png_byte or png_uint_16 (as defined below).
  181017. */
  181018. typedef struct png_color_struct
  181019. {
  181020. png_byte red;
  181021. png_byte green;
  181022. png_byte blue;
  181023. } png_color;
  181024. typedef png_color FAR * png_colorp;
  181025. typedef png_color FAR * FAR * png_colorpp;
  181026. typedef struct png_color_16_struct
  181027. {
  181028. png_byte index; /* used for palette files */
  181029. png_uint_16 red; /* for use in red green blue files */
  181030. png_uint_16 green;
  181031. png_uint_16 blue;
  181032. png_uint_16 gray; /* for use in grayscale files */
  181033. } png_color_16;
  181034. typedef png_color_16 FAR * png_color_16p;
  181035. typedef png_color_16 FAR * FAR * png_color_16pp;
  181036. typedef struct png_color_8_struct
  181037. {
  181038. png_byte red; /* for use in red green blue files */
  181039. png_byte green;
  181040. png_byte blue;
  181041. png_byte gray; /* for use in grayscale files */
  181042. png_byte alpha; /* for alpha channel files */
  181043. } png_color_8;
  181044. typedef png_color_8 FAR * png_color_8p;
  181045. typedef png_color_8 FAR * FAR * png_color_8pp;
  181046. /*
  181047. * The following two structures are used for the in-core representation
  181048. * of sPLT chunks.
  181049. */
  181050. typedef struct png_sPLT_entry_struct
  181051. {
  181052. png_uint_16 red;
  181053. png_uint_16 green;
  181054. png_uint_16 blue;
  181055. png_uint_16 alpha;
  181056. png_uint_16 frequency;
  181057. } png_sPLT_entry;
  181058. typedef png_sPLT_entry FAR * png_sPLT_entryp;
  181059. typedef png_sPLT_entry FAR * FAR * png_sPLT_entrypp;
  181060. /* When the depth of the sPLT palette is 8 bits, the color and alpha samples
  181061. * occupy the LSB of their respective members, and the MSB of each member
  181062. * is zero-filled. The frequency member always occupies the full 16 bits.
  181063. */
  181064. typedef struct png_sPLT_struct
  181065. {
  181066. png_charp name; /* palette name */
  181067. png_byte depth; /* depth of palette samples */
  181068. png_sPLT_entryp entries; /* palette entries */
  181069. png_int_32 nentries; /* number of palette entries */
  181070. } png_sPLT_t;
  181071. typedef png_sPLT_t FAR * png_sPLT_tp;
  181072. typedef png_sPLT_t FAR * FAR * png_sPLT_tpp;
  181073. #ifdef PNG_TEXT_SUPPORTED
  181074. /* png_text holds the contents of a text/ztxt/itxt chunk in a PNG file,
  181075. * and whether that contents is compressed or not. The "key" field
  181076. * points to a regular zero-terminated C string. The "text", "lang", and
  181077. * "lang_key" fields can be regular C strings, empty strings, or NULL pointers.
  181078. * However, the * structure returned by png_get_text() will always contain
  181079. * regular zero-terminated C strings (possibly empty), never NULL pointers,
  181080. * so they can be safely used in printf() and other string-handling functions.
  181081. */
  181082. typedef struct png_text_struct
  181083. {
  181084. int compression; /* compression value:
  181085. -1: tEXt, none
  181086. 0: zTXt, deflate
  181087. 1: iTXt, none
  181088. 2: iTXt, deflate */
  181089. png_charp key; /* keyword, 1-79 character description of "text" */
  181090. png_charp text; /* comment, may be an empty string (ie "")
  181091. or a NULL pointer */
  181092. png_size_t text_length; /* length of the text string */
  181093. #ifdef PNG_iTXt_SUPPORTED
  181094. png_size_t itxt_length; /* length of the itxt string */
  181095. png_charp lang; /* language code, 0-79 characters
  181096. or a NULL pointer */
  181097. png_charp lang_key; /* keyword translated UTF-8 string, 0 or more
  181098. chars or a NULL pointer */
  181099. #endif
  181100. } png_text;
  181101. typedef png_text FAR * png_textp;
  181102. typedef png_text FAR * FAR * png_textpp;
  181103. #endif
  181104. /* Supported compression types for text in PNG files (tEXt, and zTXt).
  181105. * The values of the PNG_TEXT_COMPRESSION_ defines should NOT be changed. */
  181106. #define PNG_TEXT_COMPRESSION_NONE_WR -3
  181107. #define PNG_TEXT_COMPRESSION_zTXt_WR -2
  181108. #define PNG_TEXT_COMPRESSION_NONE -1
  181109. #define PNG_TEXT_COMPRESSION_zTXt 0
  181110. #define PNG_ITXT_COMPRESSION_NONE 1
  181111. #define PNG_ITXT_COMPRESSION_zTXt 2
  181112. #define PNG_TEXT_COMPRESSION_LAST 3 /* Not a valid value */
  181113. /* png_time is a way to hold the time in an machine independent way.
  181114. * Two conversions are provided, both from time_t and struct tm. There
  181115. * is no portable way to convert to either of these structures, as far
  181116. * as I know. If you know of a portable way, send it to me. As a side
  181117. * note - PNG has always been Year 2000 compliant!
  181118. */
  181119. typedef struct png_time_struct
  181120. {
  181121. png_uint_16 year; /* full year, as in, 1995 */
  181122. png_byte month; /* month of year, 1 - 12 */
  181123. png_byte day; /* day of month, 1 - 31 */
  181124. png_byte hour; /* hour of day, 0 - 23 */
  181125. png_byte minute; /* minute of hour, 0 - 59 */
  181126. png_byte second; /* second of minute, 0 - 60 (for leap seconds) */
  181127. } png_time;
  181128. typedef png_time FAR * png_timep;
  181129. typedef png_time FAR * FAR * png_timepp;
  181130. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  181131. /* png_unknown_chunk is a structure to hold queued chunks for which there is
  181132. * no specific support. The idea is that we can use this to queue
  181133. * up private chunks for output even though the library doesn't actually
  181134. * know about their semantics.
  181135. */
  181136. typedef struct png_unknown_chunk_t
  181137. {
  181138. png_byte name[5];
  181139. png_byte *data;
  181140. png_size_t size;
  181141. /* libpng-using applications should NOT directly modify this byte. */
  181142. png_byte location; /* mode of operation at read time */
  181143. }
  181144. png_unknown_chunk;
  181145. typedef png_unknown_chunk FAR * png_unknown_chunkp;
  181146. typedef png_unknown_chunk FAR * FAR * png_unknown_chunkpp;
  181147. #endif
  181148. /* png_info is a structure that holds the information in a PNG file so
  181149. * that the application can find out the characteristics of the image.
  181150. * If you are reading the file, this structure will tell you what is
  181151. * in the PNG file. If you are writing the file, fill in the information
  181152. * you want to put into the PNG file, then call png_write_info().
  181153. * The names chosen should be very close to the PNG specification, so
  181154. * consult that document for information about the meaning of each field.
  181155. *
  181156. * With libpng < 0.95, it was only possible to directly set and read the
  181157. * the values in the png_info_struct, which meant that the contents and
  181158. * order of the values had to remain fixed. With libpng 0.95 and later,
  181159. * however, there are now functions that abstract the contents of
  181160. * png_info_struct from the application, so this makes it easier to use
  181161. * libpng with dynamic libraries, and even makes it possible to use
  181162. * libraries that don't have all of the libpng ancillary chunk-handing
  181163. * functionality.
  181164. *
  181165. * In any case, the order of the parameters in png_info_struct should NOT
  181166. * be changed for as long as possible to keep compatibility with applications
  181167. * that use the old direct-access method with png_info_struct.
  181168. *
  181169. * The following members may have allocated storage attached that should be
  181170. * cleaned up before the structure is discarded: palette, trans, text,
  181171. * pcal_purpose, pcal_units, pcal_params, hist, iccp_name, iccp_profile,
  181172. * splt_palettes, scal_unit, row_pointers, and unknowns. By default, these
  181173. * are automatically freed when the info structure is deallocated, if they were
  181174. * allocated internally by libpng. This behavior can be changed by means
  181175. * of the png_data_freer() function.
  181176. *
  181177. * More allocation details: all the chunk-reading functions that
  181178. * change these members go through the corresponding png_set_*
  181179. * functions. A function to clear these members is available: see
  181180. * png_free_data(). The png_set_* functions do not depend on being
  181181. * able to point info structure members to any of the storage they are
  181182. * passed (they make their own copies), EXCEPT that the png_set_text
  181183. * functions use the same storage passed to them in the text_ptr or
  181184. * itxt_ptr structure argument, and the png_set_rows and png_set_unknowns
  181185. * functions do not make their own copies.
  181186. */
  181187. typedef struct png_info_struct
  181188. {
  181189. /* the following are necessary for every PNG file */
  181190. png_uint_32 width; /* width of image in pixels (from IHDR) */
  181191. png_uint_32 height; /* height of image in pixels (from IHDR) */
  181192. png_uint_32 valid; /* valid chunk data (see PNG_INFO_ below) */
  181193. png_uint_32 rowbytes; /* bytes needed to hold an untransformed row */
  181194. png_colorp palette; /* array of color values (valid & PNG_INFO_PLTE) */
  181195. png_uint_16 num_palette; /* number of color entries in "palette" (PLTE) */
  181196. png_uint_16 num_trans; /* number of transparent palette color (tRNS) */
  181197. png_byte bit_depth; /* 1, 2, 4, 8, or 16 bits/channel (from IHDR) */
  181198. png_byte color_type; /* see PNG_COLOR_TYPE_ below (from IHDR) */
  181199. /* The following three should have been named *_method not *_type */
  181200. png_byte compression_type; /* must be PNG_COMPRESSION_TYPE_BASE (IHDR) */
  181201. png_byte filter_type; /* must be PNG_FILTER_TYPE_BASE (from IHDR) */
  181202. png_byte interlace_type; /* One of PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  181203. /* The following is informational only on read, and not used on writes. */
  181204. png_byte channels; /* number of data channels per pixel (1, 2, 3, 4) */
  181205. png_byte pixel_depth; /* number of bits per pixel */
  181206. png_byte spare_byte; /* to align the data, and for future use */
  181207. png_byte signature[8]; /* magic bytes read by libpng from start of file */
  181208. /* The rest of the data is optional. If you are reading, check the
  181209. * valid field to see if the information in these are valid. If you
  181210. * are writing, set the valid field to those chunks you want written,
  181211. * and initialize the appropriate fields below.
  181212. */
  181213. #if defined(PNG_gAMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  181214. /* The gAMA chunk describes the gamma characteristics of the system
  181215. * on which the image was created, normally in the range [1.0, 2.5].
  181216. * Data is valid if (valid & PNG_INFO_gAMA) is non-zero.
  181217. */
  181218. float gamma; /* gamma value of image, if (valid & PNG_INFO_gAMA) */
  181219. #endif
  181220. #if defined(PNG_sRGB_SUPPORTED)
  181221. /* GR-P, 0.96a */
  181222. /* Data valid if (valid & PNG_INFO_sRGB) non-zero. */
  181223. png_byte srgb_intent; /* sRGB rendering intent [0, 1, 2, or 3] */
  181224. #endif
  181225. #if defined(PNG_TEXT_SUPPORTED)
  181226. /* The tEXt, and zTXt chunks contain human-readable textual data in
  181227. * uncompressed, compressed, and optionally compressed forms, respectively.
  181228. * The data in "text" is an array of pointers to uncompressed,
  181229. * null-terminated C strings. Each chunk has a keyword that describes the
  181230. * textual data contained in that chunk. Keywords are not required to be
  181231. * unique, and the text string may be empty. Any number of text chunks may
  181232. * be in an image.
  181233. */
  181234. int num_text; /* number of comments read/to write */
  181235. int max_text; /* current size of text array */
  181236. png_textp text; /* array of comments read/to write */
  181237. #endif /* PNG_TEXT_SUPPORTED */
  181238. #if defined(PNG_tIME_SUPPORTED)
  181239. /* The tIME chunk holds the last time the displayed image data was
  181240. * modified. See the png_time struct for the contents of this struct.
  181241. */
  181242. png_time mod_time;
  181243. #endif
  181244. #if defined(PNG_sBIT_SUPPORTED)
  181245. /* The sBIT chunk specifies the number of significant high-order bits
  181246. * in the pixel data. Values are in the range [1, bit_depth], and are
  181247. * only specified for the channels in the pixel data. The contents of
  181248. * the low-order bits is not specified. Data is valid if
  181249. * (valid & PNG_INFO_sBIT) is non-zero.
  181250. */
  181251. png_color_8 sig_bit; /* significant bits in color channels */
  181252. #endif
  181253. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_EXPAND_SUPPORTED) || \
  181254. defined(PNG_READ_BACKGROUND_SUPPORTED)
  181255. /* The tRNS chunk supplies transparency data for paletted images and
  181256. * other image types that don't need a full alpha channel. There are
  181257. * "num_trans" transparency values for a paletted image, stored in the
  181258. * same order as the palette colors, starting from index 0. Values
  181259. * for the data are in the range [0, 255], ranging from fully transparent
  181260. * to fully opaque, respectively. For non-paletted images, there is a
  181261. * single color specified that should be treated as fully transparent.
  181262. * Data is valid if (valid & PNG_INFO_tRNS) is non-zero.
  181263. */
  181264. png_bytep trans; /* transparent values for paletted image */
  181265. png_color_16 trans_values; /* transparent color for non-palette image */
  181266. #endif
  181267. #if defined(PNG_bKGD_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  181268. /* The bKGD chunk gives the suggested image background color if the
  181269. * display program does not have its own background color and the image
  181270. * is needs to composited onto a background before display. The colors
  181271. * in "background" are normally in the same color space/depth as the
  181272. * pixel data. Data is valid if (valid & PNG_INFO_bKGD) is non-zero.
  181273. */
  181274. png_color_16 background;
  181275. #endif
  181276. #if defined(PNG_oFFs_SUPPORTED)
  181277. /* The oFFs chunk gives the offset in "offset_unit_type" units rightwards
  181278. * and downwards from the top-left corner of the display, page, or other
  181279. * application-specific co-ordinate space. See the PNG_OFFSET_ defines
  181280. * below for the unit types. Valid if (valid & PNG_INFO_oFFs) non-zero.
  181281. */
  181282. png_int_32 x_offset; /* x offset on page */
  181283. png_int_32 y_offset; /* y offset on page */
  181284. png_byte offset_unit_type; /* offset units type */
  181285. #endif
  181286. #if defined(PNG_pHYs_SUPPORTED)
  181287. /* The pHYs chunk gives the physical pixel density of the image for
  181288. * display or printing in "phys_unit_type" units (see PNG_RESOLUTION_
  181289. * defines below). Data is valid if (valid & PNG_INFO_pHYs) is non-zero.
  181290. */
  181291. png_uint_32 x_pixels_per_unit; /* horizontal pixel density */
  181292. png_uint_32 y_pixels_per_unit; /* vertical pixel density */
  181293. png_byte phys_unit_type; /* resolution type (see PNG_RESOLUTION_ below) */
  181294. #endif
  181295. #if defined(PNG_hIST_SUPPORTED)
  181296. /* The hIST chunk contains the relative frequency or importance of the
  181297. * various palette entries, so that a viewer can intelligently select a
  181298. * reduced-color palette, if required. Data is an array of "num_palette"
  181299. * values in the range [0,65535]. Data valid if (valid & PNG_INFO_hIST)
  181300. * is non-zero.
  181301. */
  181302. png_uint_16p hist;
  181303. #endif
  181304. #ifdef PNG_cHRM_SUPPORTED
  181305. /* The cHRM chunk describes the CIE color characteristics of the monitor
  181306. * on which the PNG was created. This data allows the viewer to do gamut
  181307. * mapping of the input image to ensure that the viewer sees the same
  181308. * colors in the image as the creator. Values are in the range
  181309. * [0.0, 0.8]. Data valid if (valid & PNG_INFO_cHRM) non-zero.
  181310. */
  181311. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181312. float x_white;
  181313. float y_white;
  181314. float x_red;
  181315. float y_red;
  181316. float x_green;
  181317. float y_green;
  181318. float x_blue;
  181319. float y_blue;
  181320. #endif
  181321. #endif
  181322. #if defined(PNG_pCAL_SUPPORTED)
  181323. /* The pCAL chunk describes a transformation between the stored pixel
  181324. * values and original physical data values used to create the image.
  181325. * The integer range [0, 2^bit_depth - 1] maps to the floating-point
  181326. * range given by [pcal_X0, pcal_X1], and are further transformed by a
  181327. * (possibly non-linear) transformation function given by "pcal_type"
  181328. * and "pcal_params" into "pcal_units". Please see the PNG_EQUATION_
  181329. * defines below, and the PNG-Group's PNG extensions document for a
  181330. * complete description of the transformations and how they should be
  181331. * implemented, and for a description of the ASCII parameter strings.
  181332. * Data values are valid if (valid & PNG_INFO_pCAL) non-zero.
  181333. */
  181334. png_charp pcal_purpose; /* pCAL chunk description string */
  181335. png_int_32 pcal_X0; /* minimum value */
  181336. png_int_32 pcal_X1; /* maximum value */
  181337. png_charp pcal_units; /* Latin-1 string giving physical units */
  181338. png_charpp pcal_params; /* ASCII strings containing parameter values */
  181339. png_byte pcal_type; /* equation type (see PNG_EQUATION_ below) */
  181340. png_byte pcal_nparams; /* number of parameters given in pcal_params */
  181341. #endif
  181342. /* New members added in libpng-1.0.6 */
  181343. #ifdef PNG_FREE_ME_SUPPORTED
  181344. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  181345. #endif
  181346. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  181347. /* storage for unknown chunks that the library doesn't recognize. */
  181348. png_unknown_chunkp unknown_chunks;
  181349. png_size_t unknown_chunks_num;
  181350. #endif
  181351. #if defined(PNG_iCCP_SUPPORTED)
  181352. /* iCCP chunk data. */
  181353. png_charp iccp_name; /* profile name */
  181354. png_charp iccp_profile; /* International Color Consortium profile data */
  181355. /* Note to maintainer: should be png_bytep */
  181356. png_uint_32 iccp_proflen; /* ICC profile data length */
  181357. png_byte iccp_compression; /* Always zero */
  181358. #endif
  181359. #if defined(PNG_sPLT_SUPPORTED)
  181360. /* data on sPLT chunks (there may be more than one). */
  181361. png_sPLT_tp splt_palettes;
  181362. png_uint_32 splt_palettes_num;
  181363. #endif
  181364. #if defined(PNG_sCAL_SUPPORTED)
  181365. /* The sCAL chunk describes the actual physical dimensions of the
  181366. * subject matter of the graphic. The chunk contains a unit specification
  181367. * a byte value, and two ASCII strings representing floating-point
  181368. * values. The values are width and height corresponsing to one pixel
  181369. * in the image. This external representation is converted to double
  181370. * here. Data values are valid if (valid & PNG_INFO_sCAL) is non-zero.
  181371. */
  181372. png_byte scal_unit; /* unit of physical scale */
  181373. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181374. double scal_pixel_width; /* width of one pixel */
  181375. double scal_pixel_height; /* height of one pixel */
  181376. #endif
  181377. #ifdef PNG_FIXED_POINT_SUPPORTED
  181378. png_charp scal_s_width; /* string containing height */
  181379. png_charp scal_s_height; /* string containing width */
  181380. #endif
  181381. #endif
  181382. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  181383. /* Memory has been allocated if (valid & PNG_ALLOCATED_INFO_ROWS) non-zero */
  181384. /* Data valid if (valid & PNG_INFO_IDAT) non-zero */
  181385. png_bytepp row_pointers; /* the image bits */
  181386. #endif
  181387. #if defined(PNG_FIXED_POINT_SUPPORTED) && defined(PNG_gAMA_SUPPORTED)
  181388. png_fixed_point int_gamma; /* gamma of image, if (valid & PNG_INFO_gAMA) */
  181389. #endif
  181390. #if defined(PNG_cHRM_SUPPORTED) && defined(PNG_FIXED_POINT_SUPPORTED)
  181391. png_fixed_point int_x_white;
  181392. png_fixed_point int_y_white;
  181393. png_fixed_point int_x_red;
  181394. png_fixed_point int_y_red;
  181395. png_fixed_point int_x_green;
  181396. png_fixed_point int_y_green;
  181397. png_fixed_point int_x_blue;
  181398. png_fixed_point int_y_blue;
  181399. #endif
  181400. } png_info;
  181401. typedef png_info FAR * png_infop;
  181402. typedef png_info FAR * FAR * png_infopp;
  181403. /* Maximum positive integer used in PNG is (2^31)-1 */
  181404. #define PNG_UINT_31_MAX ((png_uint_32)0x7fffffffL)
  181405. #define PNG_UINT_32_MAX ((png_uint_32)(-1))
  181406. #define PNG_SIZE_MAX ((png_size_t)(-1))
  181407. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  181408. /* PNG_MAX_UINT is deprecated; use PNG_UINT_31_MAX instead. */
  181409. #define PNG_MAX_UINT PNG_UINT_31_MAX
  181410. #endif
  181411. /* These describe the color_type field in png_info. */
  181412. /* color type masks */
  181413. #define PNG_COLOR_MASK_PALETTE 1
  181414. #define PNG_COLOR_MASK_COLOR 2
  181415. #define PNG_COLOR_MASK_ALPHA 4
  181416. /* color types. Note that not all combinations are legal */
  181417. #define PNG_COLOR_TYPE_GRAY 0
  181418. #define PNG_COLOR_TYPE_PALETTE (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_PALETTE)
  181419. #define PNG_COLOR_TYPE_RGB (PNG_COLOR_MASK_COLOR)
  181420. #define PNG_COLOR_TYPE_RGB_ALPHA (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_ALPHA)
  181421. #define PNG_COLOR_TYPE_GRAY_ALPHA (PNG_COLOR_MASK_ALPHA)
  181422. /* aliases */
  181423. #define PNG_COLOR_TYPE_RGBA PNG_COLOR_TYPE_RGB_ALPHA
  181424. #define PNG_COLOR_TYPE_GA PNG_COLOR_TYPE_GRAY_ALPHA
  181425. /* This is for compression type. PNG 1.0-1.2 only define the single type. */
  181426. #define PNG_COMPRESSION_TYPE_BASE 0 /* Deflate method 8, 32K window */
  181427. #define PNG_COMPRESSION_TYPE_DEFAULT PNG_COMPRESSION_TYPE_BASE
  181428. /* This is for filter type. PNG 1.0-1.2 only define the single type. */
  181429. #define PNG_FILTER_TYPE_BASE 0 /* Single row per-byte filtering */
  181430. #define PNG_INTRAPIXEL_DIFFERENCING 64 /* Used only in MNG datastreams */
  181431. #define PNG_FILTER_TYPE_DEFAULT PNG_FILTER_TYPE_BASE
  181432. /* These are for the interlacing type. These values should NOT be changed. */
  181433. #define PNG_INTERLACE_NONE 0 /* Non-interlaced image */
  181434. #define PNG_INTERLACE_ADAM7 1 /* Adam7 interlacing */
  181435. #define PNG_INTERLACE_LAST 2 /* Not a valid value */
  181436. /* These are for the oFFs chunk. These values should NOT be changed. */
  181437. #define PNG_OFFSET_PIXEL 0 /* Offset in pixels */
  181438. #define PNG_OFFSET_MICROMETER 1 /* Offset in micrometers (1/10^6 meter) */
  181439. #define PNG_OFFSET_LAST 2 /* Not a valid value */
  181440. /* These are for the pCAL chunk. These values should NOT be changed. */
  181441. #define PNG_EQUATION_LINEAR 0 /* Linear transformation */
  181442. #define PNG_EQUATION_BASE_E 1 /* Exponential base e transform */
  181443. #define PNG_EQUATION_ARBITRARY 2 /* Arbitrary base exponential transform */
  181444. #define PNG_EQUATION_HYPERBOLIC 3 /* Hyperbolic sine transformation */
  181445. #define PNG_EQUATION_LAST 4 /* Not a valid value */
  181446. /* These are for the sCAL chunk. These values should NOT be changed. */
  181447. #define PNG_SCALE_UNKNOWN 0 /* unknown unit (image scale) */
  181448. #define PNG_SCALE_METER 1 /* meters per pixel */
  181449. #define PNG_SCALE_RADIAN 2 /* radians per pixel */
  181450. #define PNG_SCALE_LAST 3 /* Not a valid value */
  181451. /* These are for the pHYs chunk. These values should NOT be changed. */
  181452. #define PNG_RESOLUTION_UNKNOWN 0 /* pixels/unknown unit (aspect ratio) */
  181453. #define PNG_RESOLUTION_METER 1 /* pixels/meter */
  181454. #define PNG_RESOLUTION_LAST 2 /* Not a valid value */
  181455. /* These are for the sRGB chunk. These values should NOT be changed. */
  181456. #define PNG_sRGB_INTENT_PERCEPTUAL 0
  181457. #define PNG_sRGB_INTENT_RELATIVE 1
  181458. #define PNG_sRGB_INTENT_SATURATION 2
  181459. #define PNG_sRGB_INTENT_ABSOLUTE 3
  181460. #define PNG_sRGB_INTENT_LAST 4 /* Not a valid value */
  181461. /* This is for text chunks */
  181462. #define PNG_KEYWORD_MAX_LENGTH 79
  181463. /* Maximum number of entries in PLTE/sPLT/tRNS arrays */
  181464. #define PNG_MAX_PALETTE_LENGTH 256
  181465. /* These determine if an ancillary chunk's data has been successfully read
  181466. * from the PNG header, or if the application has filled in the corresponding
  181467. * data in the info_struct to be written into the output file. The values
  181468. * of the PNG_INFO_<chunk> defines should NOT be changed.
  181469. */
  181470. #define PNG_INFO_gAMA 0x0001
  181471. #define PNG_INFO_sBIT 0x0002
  181472. #define PNG_INFO_cHRM 0x0004
  181473. #define PNG_INFO_PLTE 0x0008
  181474. #define PNG_INFO_tRNS 0x0010
  181475. #define PNG_INFO_bKGD 0x0020
  181476. #define PNG_INFO_hIST 0x0040
  181477. #define PNG_INFO_pHYs 0x0080
  181478. #define PNG_INFO_oFFs 0x0100
  181479. #define PNG_INFO_tIME 0x0200
  181480. #define PNG_INFO_pCAL 0x0400
  181481. #define PNG_INFO_sRGB 0x0800 /* GR-P, 0.96a */
  181482. #define PNG_INFO_iCCP 0x1000 /* ESR, 1.0.6 */
  181483. #define PNG_INFO_sPLT 0x2000 /* ESR, 1.0.6 */
  181484. #define PNG_INFO_sCAL 0x4000 /* ESR, 1.0.6 */
  181485. #define PNG_INFO_IDAT 0x8000L /* ESR, 1.0.6 */
  181486. /* This is used for the transformation routines, as some of them
  181487. * change these values for the row. It also should enable using
  181488. * the routines for other purposes.
  181489. */
  181490. typedef struct png_row_info_struct
  181491. {
  181492. png_uint_32 width; /* width of row */
  181493. png_uint_32 rowbytes; /* number of bytes in row */
  181494. png_byte color_type; /* color type of row */
  181495. png_byte bit_depth; /* bit depth of row */
  181496. png_byte channels; /* number of channels (1, 2, 3, or 4) */
  181497. png_byte pixel_depth; /* bits per pixel (depth * channels) */
  181498. } png_row_info;
  181499. typedef png_row_info FAR * png_row_infop;
  181500. typedef png_row_info FAR * FAR * png_row_infopp;
  181501. /* These are the function types for the I/O functions and for the functions
  181502. * that allow the user to override the default I/O functions with his or her
  181503. * own. The png_error_ptr type should match that of user-supplied warning
  181504. * and error functions, while the png_rw_ptr type should match that of the
  181505. * user read/write data functions.
  181506. */
  181507. typedef struct png_struct_def png_struct;
  181508. typedef png_struct FAR * png_structp;
  181509. typedef void (PNGAPI *png_error_ptr) PNGARG((png_structp, png_const_charp));
  181510. typedef void (PNGAPI *png_rw_ptr) PNGARG((png_structp, png_bytep, png_size_t));
  181511. typedef void (PNGAPI *png_flush_ptr) PNGARG((png_structp));
  181512. typedef void (PNGAPI *png_read_status_ptr) PNGARG((png_structp, png_uint_32,
  181513. int));
  181514. typedef void (PNGAPI *png_write_status_ptr) PNGARG((png_structp, png_uint_32,
  181515. int));
  181516. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  181517. typedef void (PNGAPI *png_progressive_info_ptr) PNGARG((png_structp, png_infop));
  181518. typedef void (PNGAPI *png_progressive_end_ptr) PNGARG((png_structp, png_infop));
  181519. typedef void (PNGAPI *png_progressive_row_ptr) PNGARG((png_structp, png_bytep,
  181520. png_uint_32, int));
  181521. #endif
  181522. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  181523. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  181524. defined(PNG_LEGACY_SUPPORTED)
  181525. typedef void (PNGAPI *png_user_transform_ptr) PNGARG((png_structp,
  181526. png_row_infop, png_bytep));
  181527. #endif
  181528. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  181529. typedef int (PNGAPI *png_user_chunk_ptr) PNGARG((png_structp, png_unknown_chunkp));
  181530. #endif
  181531. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  181532. typedef void (PNGAPI *png_unknown_chunk_ptr) PNGARG((png_structp));
  181533. #endif
  181534. /* Transform masks for the high-level interface */
  181535. #define PNG_TRANSFORM_IDENTITY 0x0000 /* read and write */
  181536. #define PNG_TRANSFORM_STRIP_16 0x0001 /* read only */
  181537. #define PNG_TRANSFORM_STRIP_ALPHA 0x0002 /* read only */
  181538. #define PNG_TRANSFORM_PACKING 0x0004 /* read and write */
  181539. #define PNG_TRANSFORM_PACKSWAP 0x0008 /* read and write */
  181540. #define PNG_TRANSFORM_EXPAND 0x0010 /* read only */
  181541. #define PNG_TRANSFORM_INVERT_MONO 0x0020 /* read and write */
  181542. #define PNG_TRANSFORM_SHIFT 0x0040 /* read and write */
  181543. #define PNG_TRANSFORM_BGR 0x0080 /* read and write */
  181544. #define PNG_TRANSFORM_SWAP_ALPHA 0x0100 /* read and write */
  181545. #define PNG_TRANSFORM_SWAP_ENDIAN 0x0200 /* read and write */
  181546. #define PNG_TRANSFORM_INVERT_ALPHA 0x0400 /* read and write */
  181547. #define PNG_TRANSFORM_STRIP_FILLER 0x0800 /* WRITE only */
  181548. /* Flags for MNG supported features */
  181549. #define PNG_FLAG_MNG_EMPTY_PLTE 0x01
  181550. #define PNG_FLAG_MNG_FILTER_64 0x04
  181551. #define PNG_ALL_MNG_FEATURES 0x05
  181552. typedef png_voidp (*png_malloc_ptr) PNGARG((png_structp, png_size_t));
  181553. typedef void (*png_free_ptr) PNGARG((png_structp, png_voidp));
  181554. /* The structure that holds the information to read and write PNG files.
  181555. * The only people who need to care about what is inside of this are the
  181556. * people who will be modifying the library for their own special needs.
  181557. * It should NOT be accessed directly by an application, except to store
  181558. * the jmp_buf.
  181559. */
  181560. struct png_struct_def
  181561. {
  181562. #ifdef PNG_SETJMP_SUPPORTED
  181563. jmp_buf jmpbuf; /* used in png_error */
  181564. #endif
  181565. png_error_ptr error_fn; /* function for printing errors and aborting */
  181566. png_error_ptr warning_fn; /* function for printing warnings */
  181567. png_voidp error_ptr; /* user supplied struct for error functions */
  181568. png_rw_ptr write_data_fn; /* function for writing output data */
  181569. png_rw_ptr read_data_fn; /* function for reading input data */
  181570. png_voidp io_ptr; /* ptr to application struct for I/O functions */
  181571. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  181572. png_user_transform_ptr read_user_transform_fn; /* user read transform */
  181573. #endif
  181574. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  181575. png_user_transform_ptr write_user_transform_fn; /* user write transform */
  181576. #endif
  181577. /* These were added in libpng-1.0.2 */
  181578. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  181579. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  181580. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  181581. png_voidp user_transform_ptr; /* user supplied struct for user transform */
  181582. png_byte user_transform_depth; /* bit depth of user transformed pixels */
  181583. png_byte user_transform_channels; /* channels in user transformed pixels */
  181584. #endif
  181585. #endif
  181586. png_uint_32 mode; /* tells us where we are in the PNG file */
  181587. png_uint_32 flags; /* flags indicating various things to libpng */
  181588. png_uint_32 transformations; /* which transformations to perform */
  181589. z_stream zstream; /* pointer to decompression structure (below) */
  181590. png_bytep zbuf; /* buffer for zlib */
  181591. png_size_t zbuf_size; /* size of zbuf */
  181592. int zlib_level; /* holds zlib compression level */
  181593. int zlib_method; /* holds zlib compression method */
  181594. int zlib_window_bits; /* holds zlib compression window bits */
  181595. int zlib_mem_level; /* holds zlib compression memory level */
  181596. int zlib_strategy; /* holds zlib compression strategy */
  181597. png_uint_32 width; /* width of image in pixels */
  181598. png_uint_32 height; /* height of image in pixels */
  181599. png_uint_32 num_rows; /* number of rows in current pass */
  181600. png_uint_32 usr_width; /* width of row at start of write */
  181601. png_uint_32 rowbytes; /* size of row in bytes */
  181602. png_uint_32 irowbytes; /* size of current interlaced row in bytes */
  181603. png_uint_32 iwidth; /* width of current interlaced row in pixels */
  181604. png_uint_32 row_number; /* current row in interlace pass */
  181605. png_bytep prev_row; /* buffer to save previous (unfiltered) row */
  181606. png_bytep row_buf; /* buffer to save current (unfiltered) row */
  181607. png_bytep sub_row; /* buffer to save "sub" row when filtering */
  181608. png_bytep up_row; /* buffer to save "up" row when filtering */
  181609. png_bytep avg_row; /* buffer to save "avg" row when filtering */
  181610. png_bytep paeth_row; /* buffer to save "Paeth" row when filtering */
  181611. png_row_info row_info; /* used for transformation routines */
  181612. png_uint_32 idat_size; /* current IDAT size for read */
  181613. png_uint_32 crc; /* current chunk CRC value */
  181614. png_colorp palette; /* palette from the input file */
  181615. png_uint_16 num_palette; /* number of color entries in palette */
  181616. png_uint_16 num_trans; /* number of transparency values */
  181617. png_byte chunk_name[5]; /* null-terminated name of current chunk */
  181618. png_byte compression; /* file compression type (always 0) */
  181619. png_byte filter; /* file filter type (always 0) */
  181620. png_byte interlaced; /* PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  181621. png_byte pass; /* current interlace pass (0 - 6) */
  181622. png_byte do_filter; /* row filter flags (see PNG_FILTER_ below ) */
  181623. png_byte color_type; /* color type of file */
  181624. png_byte bit_depth; /* bit depth of file */
  181625. png_byte usr_bit_depth; /* bit depth of users row */
  181626. png_byte pixel_depth; /* number of bits per pixel */
  181627. png_byte channels; /* number of channels in file */
  181628. png_byte usr_channels; /* channels at start of write */
  181629. png_byte sig_bytes; /* magic bytes read/written from start of file */
  181630. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  181631. #ifdef PNG_LEGACY_SUPPORTED
  181632. png_byte filler; /* filler byte for pixel expansion */
  181633. #else
  181634. png_uint_16 filler; /* filler bytes for pixel expansion */
  181635. #endif
  181636. #endif
  181637. #if defined(PNG_bKGD_SUPPORTED)
  181638. png_byte background_gamma_type;
  181639. # ifdef PNG_FLOATING_POINT_SUPPORTED
  181640. float background_gamma;
  181641. # endif
  181642. png_color_16 background; /* background color in screen gamma space */
  181643. #if defined(PNG_READ_GAMMA_SUPPORTED)
  181644. png_color_16 background_1; /* background normalized to gamma 1.0 */
  181645. #endif
  181646. #endif /* PNG_bKGD_SUPPORTED */
  181647. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  181648. png_flush_ptr output_flush_fn;/* Function for flushing output */
  181649. png_uint_32 flush_dist; /* how many rows apart to flush, 0 - no flush */
  181650. png_uint_32 flush_rows; /* number of rows written since last flush */
  181651. #endif
  181652. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  181653. int gamma_shift; /* number of "insignificant" bits 16-bit gamma */
  181654. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181655. float gamma; /* file gamma value */
  181656. float screen_gamma; /* screen gamma value (display_exponent) */
  181657. #endif
  181658. #endif
  181659. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  181660. png_bytep gamma_table; /* gamma table for 8-bit depth files */
  181661. png_bytep gamma_from_1; /* converts from 1.0 to screen */
  181662. png_bytep gamma_to_1; /* converts from file to 1.0 */
  181663. png_uint_16pp gamma_16_table; /* gamma table for 16-bit depth files */
  181664. png_uint_16pp gamma_16_from_1; /* converts from 1.0 to screen */
  181665. png_uint_16pp gamma_16_to_1; /* converts from file to 1.0 */
  181666. #endif
  181667. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_sBIT_SUPPORTED)
  181668. png_color_8 sig_bit; /* significant bits in each available channel */
  181669. #endif
  181670. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  181671. png_color_8 shift; /* shift for significant bit tranformation */
  181672. #endif
  181673. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) \
  181674. || defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  181675. png_bytep trans; /* transparency values for paletted files */
  181676. png_color_16 trans_values; /* transparency values for non-paletted files */
  181677. #endif
  181678. png_read_status_ptr read_row_fn; /* called after each row is decoded */
  181679. png_write_status_ptr write_row_fn; /* called after each row is encoded */
  181680. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  181681. png_progressive_info_ptr info_fn; /* called after header data fully read */
  181682. png_progressive_row_ptr row_fn; /* called after each prog. row is decoded */
  181683. png_progressive_end_ptr end_fn; /* called after image is complete */
  181684. png_bytep save_buffer_ptr; /* current location in save_buffer */
  181685. png_bytep save_buffer; /* buffer for previously read data */
  181686. png_bytep current_buffer_ptr; /* current location in current_buffer */
  181687. png_bytep current_buffer; /* buffer for recently used data */
  181688. png_uint_32 push_length; /* size of current input chunk */
  181689. png_uint_32 skip_length; /* bytes to skip in input data */
  181690. png_size_t save_buffer_size; /* amount of data now in save_buffer */
  181691. png_size_t save_buffer_max; /* total size of save_buffer */
  181692. png_size_t buffer_size; /* total amount of available input data */
  181693. png_size_t current_buffer_size; /* amount of data now in current_buffer */
  181694. int process_mode; /* what push library is currently doing */
  181695. int cur_palette; /* current push library palette index */
  181696. # if defined(PNG_TEXT_SUPPORTED)
  181697. png_size_t current_text_size; /* current size of text input data */
  181698. png_size_t current_text_left; /* how much text left to read in input */
  181699. png_charp current_text; /* current text chunk buffer */
  181700. png_charp current_text_ptr; /* current location in current_text */
  181701. # endif /* PNG_TEXT_SUPPORTED */
  181702. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  181703. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  181704. /* for the Borland special 64K segment handler */
  181705. png_bytepp offset_table_ptr;
  181706. png_bytep offset_table;
  181707. png_uint_16 offset_table_number;
  181708. png_uint_16 offset_table_count;
  181709. png_uint_16 offset_table_count_free;
  181710. #endif
  181711. #if defined(PNG_READ_DITHER_SUPPORTED)
  181712. png_bytep palette_lookup; /* lookup table for dithering */
  181713. png_bytep dither_index; /* index translation for palette files */
  181714. #endif
  181715. #if defined(PNG_READ_DITHER_SUPPORTED) || defined(PNG_hIST_SUPPORTED)
  181716. png_uint_16p hist; /* histogram */
  181717. #endif
  181718. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  181719. png_byte heuristic_method; /* heuristic for row filter selection */
  181720. png_byte num_prev_filters; /* number of weights for previous rows */
  181721. png_bytep prev_filters; /* filter type(s) of previous row(s) */
  181722. png_uint_16p filter_weights; /* weight(s) for previous line(s) */
  181723. png_uint_16p inv_filter_weights; /* 1/weight(s) for previous line(s) */
  181724. png_uint_16p filter_costs; /* relative filter calculation cost */
  181725. png_uint_16p inv_filter_costs; /* 1/relative filter calculation cost */
  181726. #endif
  181727. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  181728. png_charp time_buffer; /* String to hold RFC 1123 time text */
  181729. #endif
  181730. /* New members added in libpng-1.0.6 */
  181731. #ifdef PNG_FREE_ME_SUPPORTED
  181732. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  181733. #endif
  181734. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  181735. png_voidp user_chunk_ptr;
  181736. png_user_chunk_ptr read_user_chunk_fn; /* user read chunk handler */
  181737. #endif
  181738. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  181739. int num_chunk_list;
  181740. png_bytep chunk_list;
  181741. #endif
  181742. /* New members added in libpng-1.0.3 */
  181743. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  181744. png_byte rgb_to_gray_status;
  181745. /* These were changed from png_byte in libpng-1.0.6 */
  181746. png_uint_16 rgb_to_gray_red_coeff;
  181747. png_uint_16 rgb_to_gray_green_coeff;
  181748. png_uint_16 rgb_to_gray_blue_coeff;
  181749. #endif
  181750. /* New member added in libpng-1.0.4 (renamed in 1.0.9) */
  181751. #if defined(PNG_MNG_FEATURES_SUPPORTED) || \
  181752. defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  181753. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  181754. /* changed from png_byte to png_uint_32 at version 1.2.0 */
  181755. #ifdef PNG_1_0_X
  181756. png_byte mng_features_permitted;
  181757. #else
  181758. png_uint_32 mng_features_permitted;
  181759. #endif /* PNG_1_0_X */
  181760. #endif
  181761. /* New member added in libpng-1.0.7 */
  181762. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  181763. png_fixed_point int_gamma;
  181764. #endif
  181765. /* New member added in libpng-1.0.9, ifdef'ed out in 1.0.12, enabled in 1.2.0 */
  181766. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  181767. png_byte filter_type;
  181768. #endif
  181769. #if defined(PNG_1_0_X)
  181770. /* New member added in libpng-1.0.10, ifdef'ed out in 1.2.0 */
  181771. png_uint_32 row_buf_size;
  181772. #endif
  181773. /* New members added in libpng-1.2.0 */
  181774. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  181775. # if !defined(PNG_1_0_X)
  181776. # if defined(PNG_MMX_CODE_SUPPORTED)
  181777. png_byte mmx_bitdepth_threshold;
  181778. png_uint_32 mmx_rowbytes_threshold;
  181779. # endif
  181780. png_uint_32 asm_flags;
  181781. # endif
  181782. #endif
  181783. /* New members added in libpng-1.0.2 but first enabled by default in 1.2.0 */
  181784. #ifdef PNG_USER_MEM_SUPPORTED
  181785. png_voidp mem_ptr; /* user supplied struct for mem functions */
  181786. png_malloc_ptr malloc_fn; /* function for allocating memory */
  181787. png_free_ptr free_fn; /* function for freeing memory */
  181788. #endif
  181789. /* New member added in libpng-1.0.13 and 1.2.0 */
  181790. png_bytep big_row_buf; /* buffer to save current (unfiltered) row */
  181791. #if defined(PNG_READ_DITHER_SUPPORTED)
  181792. /* The following three members were added at version 1.0.14 and 1.2.4 */
  181793. png_bytep dither_sort; /* working sort array */
  181794. png_bytep index_to_palette; /* where the original index currently is */
  181795. /* in the palette */
  181796. png_bytep palette_to_index; /* which original index points to this */
  181797. /* palette color */
  181798. #endif
  181799. /* New members added in libpng-1.0.16 and 1.2.6 */
  181800. png_byte compression_type;
  181801. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  181802. png_uint_32 user_width_max;
  181803. png_uint_32 user_height_max;
  181804. #endif
  181805. /* New member added in libpng-1.0.25 and 1.2.17 */
  181806. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  181807. /* storage for unknown chunk that the library doesn't recognize. */
  181808. png_unknown_chunk unknown_chunk;
  181809. #endif
  181810. };
  181811. /* This triggers a compiler error in png.c, if png.c and png.h
  181812. * do not agree upon the version number.
  181813. */
  181814. typedef png_structp version_1_2_21;
  181815. typedef png_struct FAR * FAR * png_structpp;
  181816. /* Here are the function definitions most commonly used. This is not
  181817. * the place to find out how to use libpng. See libpng.txt for the
  181818. * full explanation, see example.c for the summary. This just provides
  181819. * a simple one line description of the use of each function.
  181820. */
  181821. /* Returns the version number of the library */
  181822. extern PNG_EXPORT(png_uint_32,png_access_version_number) PNGARG((void));
  181823. /* Tell lib we have already handled the first <num_bytes> magic bytes.
  181824. * Handling more than 8 bytes from the beginning of the file is an error.
  181825. */
  181826. extern PNG_EXPORT(void,png_set_sig_bytes) PNGARG((png_structp png_ptr,
  181827. int num_bytes));
  181828. /* Check sig[start] through sig[start + num_to_check - 1] to see if it's a
  181829. * PNG file. Returns zero if the supplied bytes match the 8-byte PNG
  181830. * signature, and non-zero otherwise. Having num_to_check == 0 or
  181831. * start > 7 will always fail (ie return non-zero).
  181832. */
  181833. extern PNG_EXPORT(int,png_sig_cmp) PNGARG((png_bytep sig, png_size_t start,
  181834. png_size_t num_to_check));
  181835. /* Simple signature checking function. This is the same as calling
  181836. * png_check_sig(sig, n) := !png_sig_cmp(sig, 0, n).
  181837. */
  181838. extern PNG_EXPORT(int,png_check_sig) PNGARG((png_bytep sig, int num));
  181839. /* Allocate and initialize png_ptr struct for reading, and any other memory. */
  181840. extern PNG_EXPORT(png_structp,png_create_read_struct)
  181841. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  181842. png_error_ptr error_fn, png_error_ptr warn_fn));
  181843. /* Allocate and initialize png_ptr struct for writing, and any other memory */
  181844. extern PNG_EXPORT(png_structp,png_create_write_struct)
  181845. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  181846. png_error_ptr error_fn, png_error_ptr warn_fn));
  181847. #ifdef PNG_WRITE_SUPPORTED
  181848. extern PNG_EXPORT(png_uint_32,png_get_compression_buffer_size)
  181849. PNGARG((png_structp png_ptr));
  181850. #endif
  181851. #ifdef PNG_WRITE_SUPPORTED
  181852. extern PNG_EXPORT(void,png_set_compression_buffer_size)
  181853. PNGARG((png_structp png_ptr, png_uint_32 size));
  181854. #endif
  181855. /* Reset the compression stream */
  181856. extern PNG_EXPORT(int,png_reset_zstream) PNGARG((png_structp png_ptr));
  181857. /* New functions added in libpng-1.0.2 (not enabled by default until 1.2.0) */
  181858. #ifdef PNG_USER_MEM_SUPPORTED
  181859. extern PNG_EXPORT(png_structp,png_create_read_struct_2)
  181860. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  181861. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  181862. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  181863. extern PNG_EXPORT(png_structp,png_create_write_struct_2)
  181864. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  181865. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  181866. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  181867. #endif
  181868. /* Write a PNG chunk - size, type, (optional) data, CRC. */
  181869. extern PNG_EXPORT(void,png_write_chunk) PNGARG((png_structp png_ptr,
  181870. png_bytep chunk_name, png_bytep data, png_size_t length));
  181871. /* Write the start of a PNG chunk - length and chunk name. */
  181872. extern PNG_EXPORT(void,png_write_chunk_start) PNGARG((png_structp png_ptr,
  181873. png_bytep chunk_name, png_uint_32 length));
  181874. /* Write the data of a PNG chunk started with png_write_chunk_start(). */
  181875. extern PNG_EXPORT(void,png_write_chunk_data) PNGARG((png_structp png_ptr,
  181876. png_bytep data, png_size_t length));
  181877. /* Finish a chunk started with png_write_chunk_start() (includes CRC). */
  181878. extern PNG_EXPORT(void,png_write_chunk_end) PNGARG((png_structp png_ptr));
  181879. /* Allocate and initialize the info structure */
  181880. extern PNG_EXPORT(png_infop,png_create_info_struct)
  181881. PNGARG((png_structp png_ptr));
  181882. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  181883. /* Initialize the info structure (old interface - DEPRECATED) */
  181884. extern PNG_EXPORT(void,png_info_init) PNGARG((png_infop info_ptr));
  181885. #undef png_info_init
  181886. #define png_info_init(info_ptr) png_info_init_3(&info_ptr,\
  181887. png_sizeof(png_info));
  181888. #endif
  181889. extern PNG_EXPORT(void,png_info_init_3) PNGARG((png_infopp info_ptr,
  181890. png_size_t png_info_struct_size));
  181891. /* Writes all the PNG information before the image. */
  181892. extern PNG_EXPORT(void,png_write_info_before_PLTE) PNGARG((png_structp png_ptr,
  181893. png_infop info_ptr));
  181894. extern PNG_EXPORT(void,png_write_info) PNGARG((png_structp png_ptr,
  181895. png_infop info_ptr));
  181896. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  181897. /* read the information before the actual image data. */
  181898. extern PNG_EXPORT(void,png_read_info) PNGARG((png_structp png_ptr,
  181899. png_infop info_ptr));
  181900. #endif
  181901. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  181902. extern PNG_EXPORT(png_charp,png_convert_to_rfc1123)
  181903. PNGARG((png_structp png_ptr, png_timep ptime));
  181904. #endif
  181905. #if !defined(_WIN32_WCE)
  181906. /* "time.h" functions are not supported on WindowsCE */
  181907. #if defined(PNG_WRITE_tIME_SUPPORTED)
  181908. /* convert from a struct tm to png_time */
  181909. extern PNG_EXPORT(void,png_convert_from_struct_tm) PNGARG((png_timep ptime,
  181910. struct tm FAR * ttime));
  181911. /* convert from time_t to png_time. Uses gmtime() */
  181912. extern PNG_EXPORT(void,png_convert_from_time_t) PNGARG((png_timep ptime,
  181913. time_t ttime));
  181914. #endif /* PNG_WRITE_tIME_SUPPORTED */
  181915. #endif /* _WIN32_WCE */
  181916. #if defined(PNG_READ_EXPAND_SUPPORTED)
  181917. /* Expand data to 24-bit RGB, or 8-bit grayscale, with alpha if available. */
  181918. extern PNG_EXPORT(void,png_set_expand) PNGARG((png_structp png_ptr));
  181919. #if !defined(PNG_1_0_X)
  181920. extern PNG_EXPORT(void,png_set_expand_gray_1_2_4_to_8) PNGARG((png_structp
  181921. png_ptr));
  181922. #endif
  181923. extern PNG_EXPORT(void,png_set_palette_to_rgb) PNGARG((png_structp png_ptr));
  181924. extern PNG_EXPORT(void,png_set_tRNS_to_alpha) PNGARG((png_structp png_ptr));
  181925. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  181926. /* Deprecated */
  181927. extern PNG_EXPORT(void,png_set_gray_1_2_4_to_8) PNGARG((png_structp png_ptr));
  181928. #endif
  181929. #endif
  181930. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  181931. /* Use blue, green, red order for pixels. */
  181932. extern PNG_EXPORT(void,png_set_bgr) PNGARG((png_structp png_ptr));
  181933. #endif
  181934. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  181935. /* Expand the grayscale to 24-bit RGB if necessary. */
  181936. extern PNG_EXPORT(void,png_set_gray_to_rgb) PNGARG((png_structp png_ptr));
  181937. #endif
  181938. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  181939. /* Reduce RGB to grayscale. */
  181940. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181941. extern PNG_EXPORT(void,png_set_rgb_to_gray) PNGARG((png_structp png_ptr,
  181942. int error_action, double red, double green ));
  181943. #endif
  181944. extern PNG_EXPORT(void,png_set_rgb_to_gray_fixed) PNGARG((png_structp png_ptr,
  181945. int error_action, png_fixed_point red, png_fixed_point green ));
  181946. extern PNG_EXPORT(png_byte,png_get_rgb_to_gray_status) PNGARG((png_structp
  181947. png_ptr));
  181948. #endif
  181949. extern PNG_EXPORT(void,png_build_grayscale_palette) PNGARG((int bit_depth,
  181950. png_colorp palette));
  181951. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  181952. extern PNG_EXPORT(void,png_set_strip_alpha) PNGARG((png_structp png_ptr));
  181953. #endif
  181954. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  181955. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  181956. extern PNG_EXPORT(void,png_set_swap_alpha) PNGARG((png_structp png_ptr));
  181957. #endif
  181958. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  181959. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  181960. extern PNG_EXPORT(void,png_set_invert_alpha) PNGARG((png_structp png_ptr));
  181961. #endif
  181962. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  181963. /* Add a filler byte to 8-bit Gray or 24-bit RGB images. */
  181964. extern PNG_EXPORT(void,png_set_filler) PNGARG((png_structp png_ptr,
  181965. png_uint_32 filler, int flags));
  181966. /* The values of the PNG_FILLER_ defines should NOT be changed */
  181967. #define PNG_FILLER_BEFORE 0
  181968. #define PNG_FILLER_AFTER 1
  181969. /* Add an alpha byte to 8-bit Gray or 24-bit RGB images. */
  181970. #if !defined(PNG_1_0_X)
  181971. extern PNG_EXPORT(void,png_set_add_alpha) PNGARG((png_structp png_ptr,
  181972. png_uint_32 filler, int flags));
  181973. #endif
  181974. #endif /* PNG_READ_FILLER_SUPPORTED || PNG_WRITE_FILLER_SUPPORTED */
  181975. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  181976. /* Swap bytes in 16-bit depth files. */
  181977. extern PNG_EXPORT(void,png_set_swap) PNGARG((png_structp png_ptr));
  181978. #endif
  181979. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  181980. /* Use 1 byte per pixel in 1, 2, or 4-bit depth files. */
  181981. extern PNG_EXPORT(void,png_set_packing) PNGARG((png_structp png_ptr));
  181982. #endif
  181983. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  181984. /* Swap packing order of pixels in bytes. */
  181985. extern PNG_EXPORT(void,png_set_packswap) PNGARG((png_structp png_ptr));
  181986. #endif
  181987. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  181988. /* Converts files to legal bit depths. */
  181989. extern PNG_EXPORT(void,png_set_shift) PNGARG((png_structp png_ptr,
  181990. png_color_8p true_bits));
  181991. #endif
  181992. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  181993. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  181994. /* Have the code handle the interlacing. Returns the number of passes. */
  181995. extern PNG_EXPORT(int,png_set_interlace_handling) PNGARG((png_structp png_ptr));
  181996. #endif
  181997. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  181998. /* Invert monochrome files */
  181999. extern PNG_EXPORT(void,png_set_invert_mono) PNGARG((png_structp png_ptr));
  182000. #endif
  182001. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  182002. /* Handle alpha and tRNS by replacing with a background color. */
  182003. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182004. extern PNG_EXPORT(void,png_set_background) PNGARG((png_structp png_ptr,
  182005. png_color_16p background_color, int background_gamma_code,
  182006. int need_expand, double background_gamma));
  182007. #endif
  182008. #define PNG_BACKGROUND_GAMMA_UNKNOWN 0
  182009. #define PNG_BACKGROUND_GAMMA_SCREEN 1
  182010. #define PNG_BACKGROUND_GAMMA_FILE 2
  182011. #define PNG_BACKGROUND_GAMMA_UNIQUE 3
  182012. #endif
  182013. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  182014. /* strip the second byte of information from a 16-bit depth file. */
  182015. extern PNG_EXPORT(void,png_set_strip_16) PNGARG((png_structp png_ptr));
  182016. #endif
  182017. #if defined(PNG_READ_DITHER_SUPPORTED)
  182018. /* Turn on dithering, and reduce the palette to the number of colors available. */
  182019. extern PNG_EXPORT(void,png_set_dither) PNGARG((png_structp png_ptr,
  182020. png_colorp palette, int num_palette, int maximum_colors,
  182021. png_uint_16p histogram, int full_dither));
  182022. #endif
  182023. #if defined(PNG_READ_GAMMA_SUPPORTED)
  182024. /* Handle gamma correction. Screen_gamma=(display_exponent) */
  182025. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182026. extern PNG_EXPORT(void,png_set_gamma) PNGARG((png_structp png_ptr,
  182027. double screen_gamma, double default_file_gamma));
  182028. #endif
  182029. #endif
  182030. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182031. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  182032. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  182033. /* Permit or disallow empty PLTE (0: not permitted, 1: permitted) */
  182034. /* Deprecated and will be removed. Use png_permit_mng_features() instead. */
  182035. extern PNG_EXPORT(void,png_permit_empty_plte) PNGARG((png_structp png_ptr,
  182036. int empty_plte_permitted));
  182037. #endif
  182038. #endif
  182039. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  182040. /* Set how many lines between output flushes - 0 for no flushing */
  182041. extern PNG_EXPORT(void,png_set_flush) PNGARG((png_structp png_ptr, int nrows));
  182042. /* Flush the current PNG output buffer */
  182043. extern PNG_EXPORT(void,png_write_flush) PNGARG((png_structp png_ptr));
  182044. #endif
  182045. /* optional update palette with requested transformations */
  182046. extern PNG_EXPORT(void,png_start_read_image) PNGARG((png_structp png_ptr));
  182047. /* optional call to update the users info structure */
  182048. extern PNG_EXPORT(void,png_read_update_info) PNGARG((png_structp png_ptr,
  182049. png_infop info_ptr));
  182050. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182051. /* read one or more rows of image data. */
  182052. extern PNG_EXPORT(void,png_read_rows) PNGARG((png_structp png_ptr,
  182053. png_bytepp row, png_bytepp display_row, png_uint_32 num_rows));
  182054. #endif
  182055. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182056. /* read a row of data. */
  182057. extern PNG_EXPORT(void,png_read_row) PNGARG((png_structp png_ptr,
  182058. png_bytep row,
  182059. png_bytep display_row));
  182060. #endif
  182061. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182062. /* read the whole image into memory at once. */
  182063. extern PNG_EXPORT(void,png_read_image) PNGARG((png_structp png_ptr,
  182064. png_bytepp image));
  182065. #endif
  182066. /* write a row of image data */
  182067. extern PNG_EXPORT(void,png_write_row) PNGARG((png_structp png_ptr,
  182068. png_bytep row));
  182069. /* write a few rows of image data */
  182070. extern PNG_EXPORT(void,png_write_rows) PNGARG((png_structp png_ptr,
  182071. png_bytepp row, png_uint_32 num_rows));
  182072. /* write the image data */
  182073. extern PNG_EXPORT(void,png_write_image) PNGARG((png_structp png_ptr,
  182074. png_bytepp image));
  182075. /* writes the end of the PNG file. */
  182076. extern PNG_EXPORT(void,png_write_end) PNGARG((png_structp png_ptr,
  182077. png_infop info_ptr));
  182078. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182079. /* read the end of the PNG file. */
  182080. extern PNG_EXPORT(void,png_read_end) PNGARG((png_structp png_ptr,
  182081. png_infop info_ptr));
  182082. #endif
  182083. /* free any memory associated with the png_info_struct */
  182084. extern PNG_EXPORT(void,png_destroy_info_struct) PNGARG((png_structp png_ptr,
  182085. png_infopp info_ptr_ptr));
  182086. /* free any memory associated with the png_struct and the png_info_structs */
  182087. extern PNG_EXPORT(void,png_destroy_read_struct) PNGARG((png_structpp
  182088. png_ptr_ptr, png_infopp info_ptr_ptr, png_infopp end_info_ptr_ptr));
  182089. /* free all memory used by the read (old method - NOT DLL EXPORTED) */
  182090. extern void png_read_destroy PNGARG((png_structp png_ptr, png_infop info_ptr,
  182091. png_infop end_info_ptr));
  182092. /* free any memory associated with the png_struct and the png_info_structs */
  182093. extern PNG_EXPORT(void,png_destroy_write_struct)
  182094. PNGARG((png_structpp png_ptr_ptr, png_infopp info_ptr_ptr));
  182095. /* free any memory used in png_ptr struct (old method - NOT DLL EXPORTED) */
  182096. extern void png_write_destroy PNGARG((png_structp png_ptr));
  182097. /* set the libpng method of handling chunk CRC errors */
  182098. extern PNG_EXPORT(void,png_set_crc_action) PNGARG((png_structp png_ptr,
  182099. int crit_action, int ancil_action));
  182100. /* Values for png_set_crc_action() to say how to handle CRC errors in
  182101. * ancillary and critical chunks, and whether to use the data contained
  182102. * therein. Note that it is impossible to "discard" data in a critical
  182103. * chunk. For versions prior to 0.90, the action was always error/quit,
  182104. * whereas in version 0.90 and later, the action for CRC errors in ancillary
  182105. * chunks is warn/discard. These values should NOT be changed.
  182106. *
  182107. * value action:critical action:ancillary
  182108. */
  182109. #define PNG_CRC_DEFAULT 0 /* error/quit warn/discard data */
  182110. #define PNG_CRC_ERROR_QUIT 1 /* error/quit error/quit */
  182111. #define PNG_CRC_WARN_DISCARD 2 /* (INVALID) warn/discard data */
  182112. #define PNG_CRC_WARN_USE 3 /* warn/use data warn/use data */
  182113. #define PNG_CRC_QUIET_USE 4 /* quiet/use data quiet/use data */
  182114. #define PNG_CRC_NO_CHANGE 5 /* use current value use current value */
  182115. /* These functions give the user control over the scan-line filtering in
  182116. * libpng and the compression methods used by zlib. These functions are
  182117. * mainly useful for testing, as the defaults should work with most users.
  182118. * Those users who are tight on memory or want faster performance at the
  182119. * expense of compression can modify them. See the compression library
  182120. * header file (zlib.h) for an explination of the compression functions.
  182121. */
  182122. /* set the filtering method(s) used by libpng. Currently, the only valid
  182123. * value for "method" is 0.
  182124. */
  182125. extern PNG_EXPORT(void,png_set_filter) PNGARG((png_structp png_ptr, int method,
  182126. int filters));
  182127. /* Flags for png_set_filter() to say which filters to use. The flags
  182128. * are chosen so that they don't conflict with real filter types
  182129. * below, in case they are supplied instead of the #defined constants.
  182130. * These values should NOT be changed.
  182131. */
  182132. #define PNG_NO_FILTERS 0x00
  182133. #define PNG_FILTER_NONE 0x08
  182134. #define PNG_FILTER_SUB 0x10
  182135. #define PNG_FILTER_UP 0x20
  182136. #define PNG_FILTER_AVG 0x40
  182137. #define PNG_FILTER_PAETH 0x80
  182138. #define PNG_ALL_FILTERS (PNG_FILTER_NONE | PNG_FILTER_SUB | PNG_FILTER_UP | \
  182139. PNG_FILTER_AVG | PNG_FILTER_PAETH)
  182140. /* Filter values (not flags) - used in pngwrite.c, pngwutil.c for now.
  182141. * These defines should NOT be changed.
  182142. */
  182143. #define PNG_FILTER_VALUE_NONE 0
  182144. #define PNG_FILTER_VALUE_SUB 1
  182145. #define PNG_FILTER_VALUE_UP 2
  182146. #define PNG_FILTER_VALUE_AVG 3
  182147. #define PNG_FILTER_VALUE_PAETH 4
  182148. #define PNG_FILTER_VALUE_LAST 5
  182149. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* EXPERIMENTAL */
  182150. /* The "heuristic_method" is given by one of the PNG_FILTER_HEURISTIC_
  182151. * defines, either the default (minimum-sum-of-absolute-differences), or
  182152. * the experimental method (weighted-minimum-sum-of-absolute-differences).
  182153. *
  182154. * Weights are factors >= 1.0, indicating how important it is to keep the
  182155. * filter type consistent between rows. Larger numbers mean the current
  182156. * filter is that many times as likely to be the same as the "num_weights"
  182157. * previous filters. This is cumulative for each previous row with a weight.
  182158. * There needs to be "num_weights" values in "filter_weights", or it can be
  182159. * NULL if the weights aren't being specified. Weights have no influence on
  182160. * the selection of the first row filter. Well chosen weights can (in theory)
  182161. * improve the compression for a given image.
  182162. *
  182163. * Costs are factors >= 1.0 indicating the relative decoding costs of a
  182164. * filter type. Higher costs indicate more decoding expense, and are
  182165. * therefore less likely to be selected over a filter with lower computational
  182166. * costs. There needs to be a value in "filter_costs" for each valid filter
  182167. * type (given by PNG_FILTER_VALUE_LAST), or it can be NULL if you aren't
  182168. * setting the costs. Costs try to improve the speed of decompression without
  182169. * unduly increasing the compressed image size.
  182170. *
  182171. * A negative weight or cost indicates the default value is to be used, and
  182172. * values in the range [0.0, 1.0) indicate the value is to remain unchanged.
  182173. * The default values for both weights and costs are currently 1.0, but may
  182174. * change if good general weighting/cost heuristics can be found. If both
  182175. * the weights and costs are set to 1.0, this degenerates the WEIGHTED method
  182176. * to the UNWEIGHTED method, but with added encoding time/computation.
  182177. */
  182178. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182179. extern PNG_EXPORT(void,png_set_filter_heuristics) PNGARG((png_structp png_ptr,
  182180. int heuristic_method, int num_weights, png_doublep filter_weights,
  182181. png_doublep filter_costs));
  182182. #endif
  182183. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  182184. /* Heuristic used for row filter selection. These defines should NOT be
  182185. * changed.
  182186. */
  182187. #define PNG_FILTER_HEURISTIC_DEFAULT 0 /* Currently "UNWEIGHTED" */
  182188. #define PNG_FILTER_HEURISTIC_UNWEIGHTED 1 /* Used by libpng < 0.95 */
  182189. #define PNG_FILTER_HEURISTIC_WEIGHTED 2 /* Experimental feature */
  182190. #define PNG_FILTER_HEURISTIC_LAST 3 /* Not a valid value */
  182191. /* Set the library compression level. Currently, valid values range from
  182192. * 0 - 9, corresponding directly to the zlib compression levels 0 - 9
  182193. * (0 - no compression, 9 - "maximal" compression). Note that tests have
  182194. * shown that zlib compression levels 3-6 usually perform as well as level 9
  182195. * for PNG images, and do considerably fewer caclulations. In the future,
  182196. * these values may not correspond directly to the zlib compression levels.
  182197. */
  182198. extern PNG_EXPORT(void,png_set_compression_level) PNGARG((png_structp png_ptr,
  182199. int level));
  182200. extern PNG_EXPORT(void,png_set_compression_mem_level)
  182201. PNGARG((png_structp png_ptr, int mem_level));
  182202. extern PNG_EXPORT(void,png_set_compression_strategy)
  182203. PNGARG((png_structp png_ptr, int strategy));
  182204. extern PNG_EXPORT(void,png_set_compression_window_bits)
  182205. PNGARG((png_structp png_ptr, int window_bits));
  182206. extern PNG_EXPORT(void,png_set_compression_method) PNGARG((png_structp png_ptr,
  182207. int method));
  182208. /* These next functions are called for input/output, memory, and error
  182209. * handling. They are in the file pngrio.c, pngwio.c, and pngerror.c,
  182210. * and call standard C I/O routines such as fread(), fwrite(), and
  182211. * fprintf(). These functions can be made to use other I/O routines
  182212. * at run time for those applications that need to handle I/O in a
  182213. * different manner by calling png_set_???_fn(). See libpng.txt for
  182214. * more information.
  182215. */
  182216. #if !defined(PNG_NO_STDIO)
  182217. /* Initialize the input/output for the PNG file to the default functions. */
  182218. extern PNG_EXPORT(void,png_init_io) PNGARG((png_structp png_ptr, png_FILE_p fp));
  182219. #endif
  182220. /* Replace the (error and abort), and warning functions with user
  182221. * supplied functions. If no messages are to be printed you must still
  182222. * write and use replacement functions. The replacement error_fn should
  182223. * still do a longjmp to the last setjmp location if you are using this
  182224. * method of error handling. If error_fn or warning_fn is NULL, the
  182225. * default function will be used.
  182226. */
  182227. extern PNG_EXPORT(void,png_set_error_fn) PNGARG((png_structp png_ptr,
  182228. png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warning_fn));
  182229. /* Return the user pointer associated with the error functions */
  182230. extern PNG_EXPORT(png_voidp,png_get_error_ptr) PNGARG((png_structp png_ptr));
  182231. /* Replace the default data output functions with a user supplied one(s).
  182232. * If buffered output is not used, then output_flush_fn can be set to NULL.
  182233. * If PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile time
  182234. * output_flush_fn will be ignored (and thus can be NULL).
  182235. */
  182236. extern PNG_EXPORT(void,png_set_write_fn) PNGARG((png_structp png_ptr,
  182237. png_voidp io_ptr, png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn));
  182238. /* Replace the default data input function with a user supplied one. */
  182239. extern PNG_EXPORT(void,png_set_read_fn) PNGARG((png_structp png_ptr,
  182240. png_voidp io_ptr, png_rw_ptr read_data_fn));
  182241. /* Return the user pointer associated with the I/O functions */
  182242. extern PNG_EXPORT(png_voidp,png_get_io_ptr) PNGARG((png_structp png_ptr));
  182243. extern PNG_EXPORT(void,png_set_read_status_fn) PNGARG((png_structp png_ptr,
  182244. png_read_status_ptr read_row_fn));
  182245. extern PNG_EXPORT(void,png_set_write_status_fn) PNGARG((png_structp png_ptr,
  182246. png_write_status_ptr write_row_fn));
  182247. #ifdef PNG_USER_MEM_SUPPORTED
  182248. /* Replace the default memory allocation functions with user supplied one(s). */
  182249. extern PNG_EXPORT(void,png_set_mem_fn) PNGARG((png_structp png_ptr,
  182250. png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  182251. /* Return the user pointer associated with the memory functions */
  182252. extern PNG_EXPORT(png_voidp,png_get_mem_ptr) PNGARG((png_structp png_ptr));
  182253. #endif
  182254. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182255. defined(PNG_LEGACY_SUPPORTED)
  182256. extern PNG_EXPORT(void,png_set_read_user_transform_fn) PNGARG((png_structp
  182257. png_ptr, png_user_transform_ptr read_user_transform_fn));
  182258. #endif
  182259. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  182260. defined(PNG_LEGACY_SUPPORTED)
  182261. extern PNG_EXPORT(void,png_set_write_user_transform_fn) PNGARG((png_structp
  182262. png_ptr, png_user_transform_ptr write_user_transform_fn));
  182263. #endif
  182264. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182265. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  182266. defined(PNG_LEGACY_SUPPORTED)
  182267. extern PNG_EXPORT(void,png_set_user_transform_info) PNGARG((png_structp
  182268. png_ptr, png_voidp user_transform_ptr, int user_transform_depth,
  182269. int user_transform_channels));
  182270. /* Return the user pointer associated with the user transform functions */
  182271. extern PNG_EXPORT(png_voidp,png_get_user_transform_ptr)
  182272. PNGARG((png_structp png_ptr));
  182273. #endif
  182274. #ifdef PNG_USER_CHUNKS_SUPPORTED
  182275. extern PNG_EXPORT(void,png_set_read_user_chunk_fn) PNGARG((png_structp png_ptr,
  182276. png_voidp user_chunk_ptr, png_user_chunk_ptr read_user_chunk_fn));
  182277. extern PNG_EXPORT(png_voidp,png_get_user_chunk_ptr) PNGARG((png_structp
  182278. png_ptr));
  182279. #endif
  182280. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  182281. /* Sets the function callbacks for the push reader, and a pointer to a
  182282. * user-defined structure available to the callback functions.
  182283. */
  182284. extern PNG_EXPORT(void,png_set_progressive_read_fn) PNGARG((png_structp png_ptr,
  182285. png_voidp progressive_ptr,
  182286. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  182287. png_progressive_end_ptr end_fn));
  182288. /* returns the user pointer associated with the push read functions */
  182289. extern PNG_EXPORT(png_voidp,png_get_progressive_ptr)
  182290. PNGARG((png_structp png_ptr));
  182291. /* function to be called when data becomes available */
  182292. extern PNG_EXPORT(void,png_process_data) PNGARG((png_structp png_ptr,
  182293. png_infop info_ptr, png_bytep buffer, png_size_t buffer_size));
  182294. /* function that combines rows. Not very much different than the
  182295. * png_combine_row() call. Is this even used?????
  182296. */
  182297. extern PNG_EXPORT(void,png_progressive_combine_row) PNGARG((png_structp png_ptr,
  182298. png_bytep old_row, png_bytep new_row));
  182299. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  182300. extern PNG_EXPORT(png_voidp,png_malloc) PNGARG((png_structp png_ptr,
  182301. png_uint_32 size));
  182302. #if defined(PNG_1_0_X)
  182303. # define png_malloc_warn png_malloc
  182304. #else
  182305. /* Added at libpng version 1.2.4 */
  182306. extern PNG_EXPORT(png_voidp,png_malloc_warn) PNGARG((png_structp png_ptr,
  182307. png_uint_32 size));
  182308. #endif
  182309. /* frees a pointer allocated by png_malloc() */
  182310. extern PNG_EXPORT(void,png_free) PNGARG((png_structp png_ptr, png_voidp ptr));
  182311. #if defined(PNG_1_0_X)
  182312. /* Function to allocate memory for zlib. */
  182313. extern PNG_EXPORT(voidpf,png_zalloc) PNGARG((voidpf png_ptr, uInt items,
  182314. uInt size));
  182315. /* Function to free memory for zlib */
  182316. extern PNG_EXPORT(void,png_zfree) PNGARG((voidpf png_ptr, voidpf ptr));
  182317. #endif
  182318. /* Free data that was allocated internally */
  182319. extern PNG_EXPORT(void,png_free_data) PNGARG((png_structp png_ptr,
  182320. png_infop info_ptr, png_uint_32 free_me, int num));
  182321. #ifdef PNG_FREE_ME_SUPPORTED
  182322. /* Reassign responsibility for freeing existing data, whether allocated
  182323. * by libpng or by the application */
  182324. extern PNG_EXPORT(void,png_data_freer) PNGARG((png_structp png_ptr,
  182325. png_infop info_ptr, int freer, png_uint_32 mask));
  182326. #endif
  182327. /* assignments for png_data_freer */
  182328. #define PNG_DESTROY_WILL_FREE_DATA 1
  182329. #define PNG_SET_WILL_FREE_DATA 1
  182330. #define PNG_USER_WILL_FREE_DATA 2
  182331. /* Flags for png_ptr->free_me and info_ptr->free_me */
  182332. #define PNG_FREE_HIST 0x0008
  182333. #define PNG_FREE_ICCP 0x0010
  182334. #define PNG_FREE_SPLT 0x0020
  182335. #define PNG_FREE_ROWS 0x0040
  182336. #define PNG_FREE_PCAL 0x0080
  182337. #define PNG_FREE_SCAL 0x0100
  182338. #define PNG_FREE_UNKN 0x0200
  182339. #define PNG_FREE_LIST 0x0400
  182340. #define PNG_FREE_PLTE 0x1000
  182341. #define PNG_FREE_TRNS 0x2000
  182342. #define PNG_FREE_TEXT 0x4000
  182343. #define PNG_FREE_ALL 0x7fff
  182344. #define PNG_FREE_MUL 0x4220 /* PNG_FREE_SPLT|PNG_FREE_TEXT|PNG_FREE_UNKN */
  182345. #ifdef PNG_USER_MEM_SUPPORTED
  182346. extern PNG_EXPORT(png_voidp,png_malloc_default) PNGARG((png_structp png_ptr,
  182347. png_uint_32 size));
  182348. extern PNG_EXPORT(void,png_free_default) PNGARG((png_structp png_ptr,
  182349. png_voidp ptr));
  182350. #endif
  182351. extern PNG_EXPORT(png_voidp,png_memcpy_check) PNGARG((png_structp png_ptr,
  182352. png_voidp s1, png_voidp s2, png_uint_32 size));
  182353. extern PNG_EXPORT(png_voidp,png_memset_check) PNGARG((png_structp png_ptr,
  182354. png_voidp s1, int value, png_uint_32 size));
  182355. #if defined(USE_FAR_KEYWORD) /* memory model conversion function */
  182356. extern void *png_far_to_near PNGARG((png_structp png_ptr,png_voidp ptr,
  182357. int check));
  182358. #endif /* USE_FAR_KEYWORD */
  182359. #ifndef PNG_NO_ERROR_TEXT
  182360. /* Fatal error in PNG image of libpng - can't continue */
  182361. extern PNG_EXPORT(void,png_error) PNGARG((png_structp png_ptr,
  182362. png_const_charp error_message));
  182363. /* The same, but the chunk name is prepended to the error string. */
  182364. extern PNG_EXPORT(void,png_chunk_error) PNGARG((png_structp png_ptr,
  182365. png_const_charp error_message));
  182366. #else
  182367. /* Fatal error in PNG image of libpng - can't continue */
  182368. extern PNG_EXPORT(void,png_err) PNGARG((png_structp png_ptr));
  182369. #endif
  182370. #ifndef PNG_NO_WARNINGS
  182371. /* Non-fatal error in libpng. Can continue, but may have a problem. */
  182372. extern PNG_EXPORT(void,png_warning) PNGARG((png_structp png_ptr,
  182373. png_const_charp warning_message));
  182374. #ifdef PNG_READ_SUPPORTED
  182375. /* Non-fatal error in libpng, chunk name is prepended to message. */
  182376. extern PNG_EXPORT(void,png_chunk_warning) PNGARG((png_structp png_ptr,
  182377. png_const_charp warning_message));
  182378. #endif /* PNG_READ_SUPPORTED */
  182379. #endif /* PNG_NO_WARNINGS */
  182380. /* The png_set_<chunk> functions are for storing values in the png_info_struct.
  182381. * Similarly, the png_get_<chunk> calls are used to read values from the
  182382. * png_info_struct, either storing the parameters in the passed variables, or
  182383. * setting pointers into the png_info_struct where the data is stored. The
  182384. * png_get_<chunk> functions return a non-zero value if the data was available
  182385. * in info_ptr, or return zero and do not change any of the parameters if the
  182386. * data was not available.
  182387. *
  182388. * These functions should be used instead of directly accessing png_info
  182389. * to avoid problems with future changes in the size and internal layout of
  182390. * png_info_struct.
  182391. */
  182392. /* Returns "flag" if chunk data is valid in info_ptr. */
  182393. extern PNG_EXPORT(png_uint_32,png_get_valid) PNGARG((png_structp png_ptr,
  182394. png_infop info_ptr, png_uint_32 flag));
  182395. /* Returns number of bytes needed to hold a transformed row. */
  182396. extern PNG_EXPORT(png_uint_32,png_get_rowbytes) PNGARG((png_structp png_ptr,
  182397. png_infop info_ptr));
  182398. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  182399. /* Returns row_pointers, which is an array of pointers to scanlines that was
  182400. returned from png_read_png(). */
  182401. extern PNG_EXPORT(png_bytepp,png_get_rows) PNGARG((png_structp png_ptr,
  182402. png_infop info_ptr));
  182403. /* Set row_pointers, which is an array of pointers to scanlines for use
  182404. by png_write_png(). */
  182405. extern PNG_EXPORT(void,png_set_rows) PNGARG((png_structp png_ptr,
  182406. png_infop info_ptr, png_bytepp row_pointers));
  182407. #endif
  182408. /* Returns number of color channels in image. */
  182409. extern PNG_EXPORT(png_byte,png_get_channels) PNGARG((png_structp png_ptr,
  182410. png_infop info_ptr));
  182411. #ifdef PNG_EASY_ACCESS_SUPPORTED
  182412. /* Returns image width in pixels. */
  182413. extern PNG_EXPORT(png_uint_32, png_get_image_width) PNGARG((png_structp
  182414. png_ptr, png_infop info_ptr));
  182415. /* Returns image height in pixels. */
  182416. extern PNG_EXPORT(png_uint_32, png_get_image_height) PNGARG((png_structp
  182417. png_ptr, png_infop info_ptr));
  182418. /* Returns image bit_depth. */
  182419. extern PNG_EXPORT(png_byte, png_get_bit_depth) PNGARG((png_structp
  182420. png_ptr, png_infop info_ptr));
  182421. /* Returns image color_type. */
  182422. extern PNG_EXPORT(png_byte, png_get_color_type) PNGARG((png_structp
  182423. png_ptr, png_infop info_ptr));
  182424. /* Returns image filter_type. */
  182425. extern PNG_EXPORT(png_byte, png_get_filter_type) PNGARG((png_structp
  182426. png_ptr, png_infop info_ptr));
  182427. /* Returns image interlace_type. */
  182428. extern PNG_EXPORT(png_byte, png_get_interlace_type) PNGARG((png_structp
  182429. png_ptr, png_infop info_ptr));
  182430. /* Returns image compression_type. */
  182431. extern PNG_EXPORT(png_byte, png_get_compression_type) PNGARG((png_structp
  182432. png_ptr, png_infop info_ptr));
  182433. /* Returns image resolution in pixels per meter, from pHYs chunk data. */
  182434. extern PNG_EXPORT(png_uint_32, png_get_pixels_per_meter) PNGARG((png_structp
  182435. png_ptr, png_infop info_ptr));
  182436. extern PNG_EXPORT(png_uint_32, png_get_x_pixels_per_meter) PNGARG((png_structp
  182437. png_ptr, png_infop info_ptr));
  182438. extern PNG_EXPORT(png_uint_32, png_get_y_pixels_per_meter) PNGARG((png_structp
  182439. png_ptr, png_infop info_ptr));
  182440. /* Returns pixel aspect ratio, computed from pHYs chunk data. */
  182441. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182442. extern PNG_EXPORT(float, png_get_pixel_aspect_ratio) PNGARG((png_structp
  182443. png_ptr, png_infop info_ptr));
  182444. #endif
  182445. /* Returns image x, y offset in pixels or microns, from oFFs chunk data. */
  182446. extern PNG_EXPORT(png_int_32, png_get_x_offset_pixels) PNGARG((png_structp
  182447. png_ptr, png_infop info_ptr));
  182448. extern PNG_EXPORT(png_int_32, png_get_y_offset_pixels) PNGARG((png_structp
  182449. png_ptr, png_infop info_ptr));
  182450. extern PNG_EXPORT(png_int_32, png_get_x_offset_microns) PNGARG((png_structp
  182451. png_ptr, png_infop info_ptr));
  182452. extern PNG_EXPORT(png_int_32, png_get_y_offset_microns) PNGARG((png_structp
  182453. png_ptr, png_infop info_ptr));
  182454. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  182455. /* Returns pointer to signature string read from PNG header */
  182456. extern PNG_EXPORT(png_bytep,png_get_signature) PNGARG((png_structp png_ptr,
  182457. png_infop info_ptr));
  182458. #if defined(PNG_bKGD_SUPPORTED)
  182459. extern PNG_EXPORT(png_uint_32,png_get_bKGD) PNGARG((png_structp png_ptr,
  182460. png_infop info_ptr, png_color_16p *background));
  182461. #endif
  182462. #if defined(PNG_bKGD_SUPPORTED)
  182463. extern PNG_EXPORT(void,png_set_bKGD) PNGARG((png_structp png_ptr,
  182464. png_infop info_ptr, png_color_16p background));
  182465. #endif
  182466. #if defined(PNG_cHRM_SUPPORTED)
  182467. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182468. extern PNG_EXPORT(png_uint_32,png_get_cHRM) PNGARG((png_structp png_ptr,
  182469. png_infop info_ptr, double *white_x, double *white_y, double *red_x,
  182470. double *red_y, double *green_x, double *green_y, double *blue_x,
  182471. double *blue_y));
  182472. #endif
  182473. #ifdef PNG_FIXED_POINT_SUPPORTED
  182474. extern PNG_EXPORT(png_uint_32,png_get_cHRM_fixed) PNGARG((png_structp png_ptr,
  182475. png_infop info_ptr, png_fixed_point *int_white_x, png_fixed_point
  182476. *int_white_y, png_fixed_point *int_red_x, png_fixed_point *int_red_y,
  182477. png_fixed_point *int_green_x, png_fixed_point *int_green_y, png_fixed_point
  182478. *int_blue_x, png_fixed_point *int_blue_y));
  182479. #endif
  182480. #endif
  182481. #if defined(PNG_cHRM_SUPPORTED)
  182482. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182483. extern PNG_EXPORT(void,png_set_cHRM) PNGARG((png_structp png_ptr,
  182484. png_infop info_ptr, double white_x, double white_y, double red_x,
  182485. double red_y, double green_x, double green_y, double blue_x, double blue_y));
  182486. #endif
  182487. #ifdef PNG_FIXED_POINT_SUPPORTED
  182488. extern PNG_EXPORT(void,png_set_cHRM_fixed) PNGARG((png_structp png_ptr,
  182489. png_infop info_ptr, png_fixed_point int_white_x, png_fixed_point int_white_y,
  182490. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  182491. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  182492. png_fixed_point int_blue_y));
  182493. #endif
  182494. #endif
  182495. #if defined(PNG_gAMA_SUPPORTED)
  182496. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182497. extern PNG_EXPORT(png_uint_32,png_get_gAMA) PNGARG((png_structp png_ptr,
  182498. png_infop info_ptr, double *file_gamma));
  182499. #endif
  182500. extern PNG_EXPORT(png_uint_32,png_get_gAMA_fixed) PNGARG((png_structp png_ptr,
  182501. png_infop info_ptr, png_fixed_point *int_file_gamma));
  182502. #endif
  182503. #if defined(PNG_gAMA_SUPPORTED)
  182504. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182505. extern PNG_EXPORT(void,png_set_gAMA) PNGARG((png_structp png_ptr,
  182506. png_infop info_ptr, double file_gamma));
  182507. #endif
  182508. extern PNG_EXPORT(void,png_set_gAMA_fixed) PNGARG((png_structp png_ptr,
  182509. png_infop info_ptr, png_fixed_point int_file_gamma));
  182510. #endif
  182511. #if defined(PNG_hIST_SUPPORTED)
  182512. extern PNG_EXPORT(png_uint_32,png_get_hIST) PNGARG((png_structp png_ptr,
  182513. png_infop info_ptr, png_uint_16p *hist));
  182514. #endif
  182515. #if defined(PNG_hIST_SUPPORTED)
  182516. extern PNG_EXPORT(void,png_set_hIST) PNGARG((png_structp png_ptr,
  182517. png_infop info_ptr, png_uint_16p hist));
  182518. #endif
  182519. extern PNG_EXPORT(png_uint_32,png_get_IHDR) PNGARG((png_structp png_ptr,
  182520. png_infop info_ptr, png_uint_32 *width, png_uint_32 *height,
  182521. int *bit_depth, int *color_type, int *interlace_method,
  182522. int *compression_method, int *filter_method));
  182523. extern PNG_EXPORT(void,png_set_IHDR) PNGARG((png_structp png_ptr,
  182524. png_infop info_ptr, png_uint_32 width, png_uint_32 height, int bit_depth,
  182525. int color_type, int interlace_method, int compression_method,
  182526. int filter_method));
  182527. #if defined(PNG_oFFs_SUPPORTED)
  182528. extern PNG_EXPORT(png_uint_32,png_get_oFFs) PNGARG((png_structp png_ptr,
  182529. png_infop info_ptr, png_int_32 *offset_x, png_int_32 *offset_y,
  182530. int *unit_type));
  182531. #endif
  182532. #if defined(PNG_oFFs_SUPPORTED)
  182533. extern PNG_EXPORT(void,png_set_oFFs) PNGARG((png_structp png_ptr,
  182534. png_infop info_ptr, png_int_32 offset_x, png_int_32 offset_y,
  182535. int unit_type));
  182536. #endif
  182537. #if defined(PNG_pCAL_SUPPORTED)
  182538. extern PNG_EXPORT(png_uint_32,png_get_pCAL) PNGARG((png_structp png_ptr,
  182539. png_infop info_ptr, png_charp *purpose, png_int_32 *X0, png_int_32 *X1,
  182540. int *type, int *nparams, png_charp *units, png_charpp *params));
  182541. #endif
  182542. #if defined(PNG_pCAL_SUPPORTED)
  182543. extern PNG_EXPORT(void,png_set_pCAL) PNGARG((png_structp png_ptr,
  182544. png_infop info_ptr, png_charp purpose, png_int_32 X0, png_int_32 X1,
  182545. int type, int nparams, png_charp units, png_charpp params));
  182546. #endif
  182547. #if defined(PNG_pHYs_SUPPORTED)
  182548. extern PNG_EXPORT(png_uint_32,png_get_pHYs) PNGARG((png_structp png_ptr,
  182549. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  182550. #endif
  182551. #if defined(PNG_pHYs_SUPPORTED)
  182552. extern PNG_EXPORT(void,png_set_pHYs) PNGARG((png_structp png_ptr,
  182553. png_infop info_ptr, png_uint_32 res_x, png_uint_32 res_y, int unit_type));
  182554. #endif
  182555. extern PNG_EXPORT(png_uint_32,png_get_PLTE) PNGARG((png_structp png_ptr,
  182556. png_infop info_ptr, png_colorp *palette, int *num_palette));
  182557. extern PNG_EXPORT(void,png_set_PLTE) PNGARG((png_structp png_ptr,
  182558. png_infop info_ptr, png_colorp palette, int num_palette));
  182559. #if defined(PNG_sBIT_SUPPORTED)
  182560. extern PNG_EXPORT(png_uint_32,png_get_sBIT) PNGARG((png_structp png_ptr,
  182561. png_infop info_ptr, png_color_8p *sig_bit));
  182562. #endif
  182563. #if defined(PNG_sBIT_SUPPORTED)
  182564. extern PNG_EXPORT(void,png_set_sBIT) PNGARG((png_structp png_ptr,
  182565. png_infop info_ptr, png_color_8p sig_bit));
  182566. #endif
  182567. #if defined(PNG_sRGB_SUPPORTED)
  182568. extern PNG_EXPORT(png_uint_32,png_get_sRGB) PNGARG((png_structp png_ptr,
  182569. png_infop info_ptr, int *intent));
  182570. #endif
  182571. #if defined(PNG_sRGB_SUPPORTED)
  182572. extern PNG_EXPORT(void,png_set_sRGB) PNGARG((png_structp png_ptr,
  182573. png_infop info_ptr, int intent));
  182574. extern PNG_EXPORT(void,png_set_sRGB_gAMA_and_cHRM) PNGARG((png_structp png_ptr,
  182575. png_infop info_ptr, int intent));
  182576. #endif
  182577. #if defined(PNG_iCCP_SUPPORTED)
  182578. extern PNG_EXPORT(png_uint_32,png_get_iCCP) PNGARG((png_structp png_ptr,
  182579. png_infop info_ptr, png_charpp name, int *compression_type,
  182580. png_charpp profile, png_uint_32 *proflen));
  182581. /* Note to maintainer: profile should be png_bytepp */
  182582. #endif
  182583. #if defined(PNG_iCCP_SUPPORTED)
  182584. extern PNG_EXPORT(void,png_set_iCCP) PNGARG((png_structp png_ptr,
  182585. png_infop info_ptr, png_charp name, int compression_type,
  182586. png_charp profile, png_uint_32 proflen));
  182587. /* Note to maintainer: profile should be png_bytep */
  182588. #endif
  182589. #if defined(PNG_sPLT_SUPPORTED)
  182590. extern PNG_EXPORT(png_uint_32,png_get_sPLT) PNGARG((png_structp png_ptr,
  182591. png_infop info_ptr, png_sPLT_tpp entries));
  182592. #endif
  182593. #if defined(PNG_sPLT_SUPPORTED)
  182594. extern PNG_EXPORT(void,png_set_sPLT) PNGARG((png_structp png_ptr,
  182595. png_infop info_ptr, png_sPLT_tp entries, int nentries));
  182596. #endif
  182597. #if defined(PNG_TEXT_SUPPORTED)
  182598. /* png_get_text also returns the number of text chunks in *num_text */
  182599. extern PNG_EXPORT(png_uint_32,png_get_text) PNGARG((png_structp png_ptr,
  182600. png_infop info_ptr, png_textp *text_ptr, int *num_text));
  182601. #endif
  182602. /*
  182603. * Note while png_set_text() will accept a structure whose text,
  182604. * language, and translated keywords are NULL pointers, the structure
  182605. * returned by png_get_text will always contain regular
  182606. * zero-terminated C strings. They might be empty strings but
  182607. * they will never be NULL pointers.
  182608. */
  182609. #if defined(PNG_TEXT_SUPPORTED)
  182610. extern PNG_EXPORT(void,png_set_text) PNGARG((png_structp png_ptr,
  182611. png_infop info_ptr, png_textp text_ptr, int num_text));
  182612. #endif
  182613. #if defined(PNG_tIME_SUPPORTED)
  182614. extern PNG_EXPORT(png_uint_32,png_get_tIME) PNGARG((png_structp png_ptr,
  182615. png_infop info_ptr, png_timep *mod_time));
  182616. #endif
  182617. #if defined(PNG_tIME_SUPPORTED)
  182618. extern PNG_EXPORT(void,png_set_tIME) PNGARG((png_structp png_ptr,
  182619. png_infop info_ptr, png_timep mod_time));
  182620. #endif
  182621. #if defined(PNG_tRNS_SUPPORTED)
  182622. extern PNG_EXPORT(png_uint_32,png_get_tRNS) PNGARG((png_structp png_ptr,
  182623. png_infop info_ptr, png_bytep *trans, int *num_trans,
  182624. png_color_16p *trans_values));
  182625. #endif
  182626. #if defined(PNG_tRNS_SUPPORTED)
  182627. extern PNG_EXPORT(void,png_set_tRNS) PNGARG((png_structp png_ptr,
  182628. png_infop info_ptr, png_bytep trans, int num_trans,
  182629. png_color_16p trans_values));
  182630. #endif
  182631. #if defined(PNG_tRNS_SUPPORTED)
  182632. #endif
  182633. #if defined(PNG_sCAL_SUPPORTED)
  182634. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182635. extern PNG_EXPORT(png_uint_32,png_get_sCAL) PNGARG((png_structp png_ptr,
  182636. png_infop info_ptr, int *unit, double *width, double *height));
  182637. #else
  182638. #ifdef PNG_FIXED_POINT_SUPPORTED
  182639. extern PNG_EXPORT(png_uint_32,png_get_sCAL_s) PNGARG((png_structp png_ptr,
  182640. png_infop info_ptr, int *unit, png_charpp swidth, png_charpp sheight));
  182641. #endif
  182642. #endif
  182643. #endif /* PNG_sCAL_SUPPORTED */
  182644. #if defined(PNG_sCAL_SUPPORTED)
  182645. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182646. extern PNG_EXPORT(void,png_set_sCAL) PNGARG((png_structp png_ptr,
  182647. png_infop info_ptr, int unit, double width, double height));
  182648. #else
  182649. #ifdef PNG_FIXED_POINT_SUPPORTED
  182650. extern PNG_EXPORT(void,png_set_sCAL_s) PNGARG((png_structp png_ptr,
  182651. png_infop info_ptr, int unit, png_charp swidth, png_charp sheight));
  182652. #endif
  182653. #endif
  182654. #endif /* PNG_sCAL_SUPPORTED || PNG_WRITE_sCAL_SUPPORTED */
  182655. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182656. /* provide a list of chunks and how they are to be handled, if the built-in
  182657. handling or default unknown chunk handling is not desired. Any chunks not
  182658. listed will be handled in the default manner. The IHDR and IEND chunks
  182659. must not be listed.
  182660. keep = 0: follow default behaviour
  182661. = 1: do not keep
  182662. = 2: keep only if safe-to-copy
  182663. = 3: keep even if unsafe-to-copy
  182664. */
  182665. extern PNG_EXPORT(void, png_set_keep_unknown_chunks) PNGARG((png_structp
  182666. png_ptr, int keep, png_bytep chunk_list, int num_chunks));
  182667. extern PNG_EXPORT(void, png_set_unknown_chunks) PNGARG((png_structp png_ptr,
  182668. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns));
  182669. extern PNG_EXPORT(void, png_set_unknown_chunk_location)
  182670. PNGARG((png_structp png_ptr, png_infop info_ptr, int chunk, int location));
  182671. extern PNG_EXPORT(png_uint_32,png_get_unknown_chunks) PNGARG((png_structp
  182672. png_ptr, png_infop info_ptr, png_unknown_chunkpp entries));
  182673. #endif
  182674. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  182675. PNG_EXPORT(int,png_handle_as_unknown) PNGARG((png_structp png_ptr, png_bytep
  182676. chunk_name));
  182677. #endif
  182678. /* Png_free_data() will turn off the "valid" flag for anything it frees.
  182679. If you need to turn it off for a chunk that your application has freed,
  182680. you can use png_set_invalid(png_ptr, info_ptr, PNG_INFO_CHNK); */
  182681. extern PNG_EXPORT(void, png_set_invalid) PNGARG((png_structp png_ptr,
  182682. png_infop info_ptr, int mask));
  182683. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  182684. /* The "params" pointer is currently not used and is for future expansion. */
  182685. extern PNG_EXPORT(void, png_read_png) PNGARG((png_structp png_ptr,
  182686. png_infop info_ptr,
  182687. int transforms,
  182688. png_voidp params));
  182689. extern PNG_EXPORT(void, png_write_png) PNGARG((png_structp png_ptr,
  182690. png_infop info_ptr,
  182691. int transforms,
  182692. png_voidp params));
  182693. #endif
  182694. /* Define PNG_DEBUG at compile time for debugging information. Higher
  182695. * numbers for PNG_DEBUG mean more debugging information. This has
  182696. * only been added since version 0.95 so it is not implemented throughout
  182697. * libpng yet, but more support will be added as needed.
  182698. */
  182699. #ifdef PNG_DEBUG
  182700. #if (PNG_DEBUG > 0)
  182701. #if !defined(PNG_DEBUG_FILE) && defined(_MSC_VER)
  182702. #include <crtdbg.h>
  182703. #if (PNG_DEBUG > 1)
  182704. #define png_debug(l,m) _RPT0(_CRT_WARN,m)
  182705. #define png_debug1(l,m,p1) _RPT1(_CRT_WARN,m,p1)
  182706. #define png_debug2(l,m,p1,p2) _RPT2(_CRT_WARN,m,p1,p2)
  182707. #endif
  182708. #else /* PNG_DEBUG_FILE || !_MSC_VER */
  182709. #ifndef PNG_DEBUG_FILE
  182710. #define PNG_DEBUG_FILE stderr
  182711. #endif /* PNG_DEBUG_FILE */
  182712. #if (PNG_DEBUG > 1)
  182713. #define png_debug(l,m) \
  182714. { \
  182715. int num_tabs=l; \
  182716. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  182717. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":"")))); \
  182718. }
  182719. #define png_debug1(l,m,p1) \
  182720. { \
  182721. int num_tabs=l; \
  182722. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  182723. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1); \
  182724. }
  182725. #define png_debug2(l,m,p1,p2) \
  182726. { \
  182727. int num_tabs=l; \
  182728. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  182729. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1,p2); \
  182730. }
  182731. #endif /* (PNG_DEBUG > 1) */
  182732. #endif /* _MSC_VER */
  182733. #endif /* (PNG_DEBUG > 0) */
  182734. #endif /* PNG_DEBUG */
  182735. #ifndef png_debug
  182736. #define png_debug(l, m)
  182737. #endif
  182738. #ifndef png_debug1
  182739. #define png_debug1(l, m, p1)
  182740. #endif
  182741. #ifndef png_debug2
  182742. #define png_debug2(l, m, p1, p2)
  182743. #endif
  182744. extern PNG_EXPORT(png_charp,png_get_copyright) PNGARG((png_structp png_ptr));
  182745. extern PNG_EXPORT(png_charp,png_get_header_ver) PNGARG((png_structp png_ptr));
  182746. extern PNG_EXPORT(png_charp,png_get_header_version) PNGARG((png_structp png_ptr));
  182747. extern PNG_EXPORT(png_charp,png_get_libpng_ver) PNGARG((png_structp png_ptr));
  182748. #ifdef PNG_MNG_FEATURES_SUPPORTED
  182749. extern PNG_EXPORT(png_uint_32,png_permit_mng_features) PNGARG((png_structp
  182750. png_ptr, png_uint_32 mng_features_permitted));
  182751. #endif
  182752. /* For use in png_set_keep_unknown, added to version 1.2.6 */
  182753. #define PNG_HANDLE_CHUNK_AS_DEFAULT 0
  182754. #define PNG_HANDLE_CHUNK_NEVER 1
  182755. #define PNG_HANDLE_CHUNK_IF_SAFE 2
  182756. #define PNG_HANDLE_CHUNK_ALWAYS 3
  182757. /* Added to version 1.2.0 */
  182758. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  182759. #if defined(PNG_MMX_CODE_SUPPORTED)
  182760. #define PNG_ASM_FLAG_MMX_SUPPORT_COMPILED 0x01 /* not user-settable */
  182761. #define PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU 0x02 /* not user-settable */
  182762. #define PNG_ASM_FLAG_MMX_READ_COMBINE_ROW 0x04
  182763. #define PNG_ASM_FLAG_MMX_READ_INTERLACE 0x08
  182764. #define PNG_ASM_FLAG_MMX_READ_FILTER_SUB 0x10
  182765. #define PNG_ASM_FLAG_MMX_READ_FILTER_UP 0x20
  182766. #define PNG_ASM_FLAG_MMX_READ_FILTER_AVG 0x40
  182767. #define PNG_ASM_FLAG_MMX_READ_FILTER_PAETH 0x80
  182768. #define PNG_ASM_FLAGS_INITIALIZED 0x80000000 /* not user-settable */
  182769. #define PNG_MMX_READ_FLAGS ( PNG_ASM_FLAG_MMX_READ_COMBINE_ROW \
  182770. | PNG_ASM_FLAG_MMX_READ_INTERLACE \
  182771. | PNG_ASM_FLAG_MMX_READ_FILTER_SUB \
  182772. | PNG_ASM_FLAG_MMX_READ_FILTER_UP \
  182773. | PNG_ASM_FLAG_MMX_READ_FILTER_AVG \
  182774. | PNG_ASM_FLAG_MMX_READ_FILTER_PAETH )
  182775. #define PNG_MMX_WRITE_FLAGS ( 0 )
  182776. #define PNG_MMX_FLAGS ( PNG_ASM_FLAG_MMX_SUPPORT_COMPILED \
  182777. | PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU \
  182778. | PNG_MMX_READ_FLAGS \
  182779. | PNG_MMX_WRITE_FLAGS )
  182780. #define PNG_SELECT_READ 1
  182781. #define PNG_SELECT_WRITE 2
  182782. #endif /* PNG_MMX_CODE_SUPPORTED */
  182783. #if !defined(PNG_1_0_X)
  182784. /* pngget.c */
  182785. extern PNG_EXPORT(png_uint_32,png_get_mmx_flagmask)
  182786. PNGARG((int flag_select, int *compilerID));
  182787. /* pngget.c */
  182788. extern PNG_EXPORT(png_uint_32,png_get_asm_flagmask)
  182789. PNGARG((int flag_select));
  182790. /* pngget.c */
  182791. extern PNG_EXPORT(png_uint_32,png_get_asm_flags)
  182792. PNGARG((png_structp png_ptr));
  182793. /* pngget.c */
  182794. extern PNG_EXPORT(png_byte,png_get_mmx_bitdepth_threshold)
  182795. PNGARG((png_structp png_ptr));
  182796. /* pngget.c */
  182797. extern PNG_EXPORT(png_uint_32,png_get_mmx_rowbytes_threshold)
  182798. PNGARG((png_structp png_ptr));
  182799. /* pngset.c */
  182800. extern PNG_EXPORT(void,png_set_asm_flags)
  182801. PNGARG((png_structp png_ptr, png_uint_32 asm_flags));
  182802. /* pngset.c */
  182803. extern PNG_EXPORT(void,png_set_mmx_thresholds)
  182804. PNGARG((png_structp png_ptr, png_byte mmx_bitdepth_threshold,
  182805. png_uint_32 mmx_rowbytes_threshold));
  182806. #endif /* PNG_1_0_X */
  182807. #if !defined(PNG_1_0_X)
  182808. /* png.c, pnggccrd.c, or pngvcrd.c */
  182809. extern PNG_EXPORT(int,png_mmx_support) PNGARG((void));
  182810. #endif /* PNG_ASSEMBLER_CODE_SUPPORTED */
  182811. /* Strip the prepended error numbers ("#nnn ") from error and warning
  182812. * messages before passing them to the error or warning handler. */
  182813. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  182814. extern PNG_EXPORT(void,png_set_strip_error_numbers) PNGARG((png_structp
  182815. png_ptr, png_uint_32 strip_mode));
  182816. #endif
  182817. #endif /* PNG_1_0_X */
  182818. /* Added at libpng-1.2.6 */
  182819. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  182820. extern PNG_EXPORT(void,png_set_user_limits) PNGARG((png_structp
  182821. png_ptr, png_uint_32 user_width_max, png_uint_32 user_height_max));
  182822. extern PNG_EXPORT(png_uint_32,png_get_user_width_max) PNGARG((png_structp
  182823. png_ptr));
  182824. extern PNG_EXPORT(png_uint_32,png_get_user_height_max) PNGARG((png_structp
  182825. png_ptr));
  182826. #endif
  182827. /* Maintainer: Put new public prototypes here ^, in libpng.3, and project defs */
  182828. #ifdef PNG_READ_COMPOSITE_NODIV_SUPPORTED
  182829. /* With these routines we avoid an integer divide, which will be slower on
  182830. * most machines. However, it does take more operations than the corresponding
  182831. * divide method, so it may be slower on a few RISC systems. There are two
  182832. * shifts (by 8 or 16 bits) and an addition, versus a single integer divide.
  182833. *
  182834. * Note that the rounding factors are NOT supposed to be the same! 128 and
  182835. * 32768 are correct for the NODIV code; 127 and 32767 are correct for the
  182836. * standard method.
  182837. *
  182838. * [Optimized code by Greg Roelofs and Mark Adler...blame us for bugs. :-) ]
  182839. */
  182840. /* fg and bg should be in `gamma 1.0' space; alpha is the opacity */
  182841. # define png_composite(composite, fg, alpha, bg) \
  182842. { png_uint_16 temp = (png_uint_16)((png_uint_16)(fg) * (png_uint_16)(alpha) \
  182843. + (png_uint_16)(bg)*(png_uint_16)(255 - \
  182844. (png_uint_16)(alpha)) + (png_uint_16)128); \
  182845. (composite) = (png_byte)((temp + (temp >> 8)) >> 8); }
  182846. # define png_composite_16(composite, fg, alpha, bg) \
  182847. { png_uint_32 temp = (png_uint_32)((png_uint_32)(fg) * (png_uint_32)(alpha) \
  182848. + (png_uint_32)(bg)*(png_uint_32)(65535L - \
  182849. (png_uint_32)(alpha)) + (png_uint_32)32768L); \
  182850. (composite) = (png_uint_16)((temp + (temp >> 16)) >> 16); }
  182851. #else /* standard method using integer division */
  182852. # define png_composite(composite, fg, alpha, bg) \
  182853. (composite) = (png_byte)(((png_uint_16)(fg) * (png_uint_16)(alpha) + \
  182854. (png_uint_16)(bg) * (png_uint_16)(255 - (png_uint_16)(alpha)) + \
  182855. (png_uint_16)127) / 255)
  182856. # define png_composite_16(composite, fg, alpha, bg) \
  182857. (composite) = (png_uint_16)(((png_uint_32)(fg) * (png_uint_32)(alpha) + \
  182858. (png_uint_32)(bg)*(png_uint_32)(65535L - (png_uint_32)(alpha)) + \
  182859. (png_uint_32)32767) / (png_uint_32)65535L)
  182860. #endif /* PNG_READ_COMPOSITE_NODIV_SUPPORTED */
  182861. /* Inline macros to do direct reads of bytes from the input buffer. These
  182862. * require that you are using an architecture that uses PNG byte ordering
  182863. * (MSB first) and supports unaligned data storage. I think that PowerPC
  182864. * in big-endian mode and 680x0 are the only ones that will support this.
  182865. * The x86 line of processors definitely do not. The png_get_int_32()
  182866. * routine also assumes we are using two's complement format for negative
  182867. * values, which is almost certainly true.
  182868. */
  182869. #if defined(PNG_READ_BIG_ENDIAN_SUPPORTED)
  182870. # define png_get_uint_32(buf) ( *((png_uint_32p) (buf)))
  182871. # define png_get_uint_16(buf) ( *((png_uint_16p) (buf)))
  182872. # define png_get_int_32(buf) ( *((png_int_32p) (buf)))
  182873. #else
  182874. extern PNG_EXPORT(png_uint_32,png_get_uint_32) PNGARG((png_bytep buf));
  182875. extern PNG_EXPORT(png_uint_16,png_get_uint_16) PNGARG((png_bytep buf));
  182876. extern PNG_EXPORT(png_int_32,png_get_int_32) PNGARG((png_bytep buf));
  182877. #endif /* !PNG_READ_BIG_ENDIAN_SUPPORTED */
  182878. extern PNG_EXPORT(png_uint_32,png_get_uint_31)
  182879. PNGARG((png_structp png_ptr, png_bytep buf));
  182880. /* No png_get_int_16 -- may be added if there's a real need for it. */
  182881. /* Place a 32-bit number into a buffer in PNG byte order (big-endian).
  182882. */
  182883. extern PNG_EXPORT(void,png_save_uint_32)
  182884. PNGARG((png_bytep buf, png_uint_32 i));
  182885. extern PNG_EXPORT(void,png_save_int_32)
  182886. PNGARG((png_bytep buf, png_int_32 i));
  182887. /* Place a 16-bit number into a buffer in PNG byte order.
  182888. * The parameter is declared unsigned int, not png_uint_16,
  182889. * just to avoid potential problems on pre-ANSI C compilers.
  182890. */
  182891. extern PNG_EXPORT(void,png_save_uint_16)
  182892. PNGARG((png_bytep buf, unsigned int i));
  182893. /* No png_save_int_16 -- may be added if there's a real need for it. */
  182894. /* ************************************************************************* */
  182895. /* These next functions are used internally in the code. They generally
  182896. * shouldn't be used unless you are writing code to add or replace some
  182897. * functionality in libpng. More information about most functions can
  182898. * be found in the files where the functions are located.
  182899. */
  182900. /* Various modes of operation, that are visible to applications because
  182901. * they are used for unknown chunk location.
  182902. */
  182903. #define PNG_HAVE_IHDR 0x01
  182904. #define PNG_HAVE_PLTE 0x02
  182905. #define PNG_HAVE_IDAT 0x04
  182906. #define PNG_AFTER_IDAT 0x08 /* Have complete zlib datastream */
  182907. #define PNG_HAVE_IEND 0x10
  182908. #if defined(PNG_INTERNAL)
  182909. /* More modes of operation. Note that after an init, mode is set to
  182910. * zero automatically when the structure is created.
  182911. */
  182912. #define PNG_HAVE_gAMA 0x20
  182913. #define PNG_HAVE_cHRM 0x40
  182914. #define PNG_HAVE_sRGB 0x80
  182915. #define PNG_HAVE_CHUNK_HEADER 0x100
  182916. #define PNG_WROTE_tIME 0x200
  182917. #define PNG_WROTE_INFO_BEFORE_PLTE 0x400
  182918. #define PNG_BACKGROUND_IS_GRAY 0x800
  182919. #define PNG_HAVE_PNG_SIGNATURE 0x1000
  182920. #define PNG_HAVE_CHUNK_AFTER_IDAT 0x2000 /* Have another chunk after IDAT */
  182921. /* flags for the transformations the PNG library does on the image data */
  182922. #define PNG_BGR 0x0001
  182923. #define PNG_INTERLACE 0x0002
  182924. #define PNG_PACK 0x0004
  182925. #define PNG_SHIFT 0x0008
  182926. #define PNG_SWAP_BYTES 0x0010
  182927. #define PNG_INVERT_MONO 0x0020
  182928. #define PNG_DITHER 0x0040
  182929. #define PNG_BACKGROUND 0x0080
  182930. #define PNG_BACKGROUND_EXPAND 0x0100
  182931. /* 0x0200 unused */
  182932. #define PNG_16_TO_8 0x0400
  182933. #define PNG_RGBA 0x0800
  182934. #define PNG_EXPAND 0x1000
  182935. #define PNG_GAMMA 0x2000
  182936. #define PNG_GRAY_TO_RGB 0x4000
  182937. #define PNG_FILLER 0x8000L
  182938. #define PNG_PACKSWAP 0x10000L
  182939. #define PNG_SWAP_ALPHA 0x20000L
  182940. #define PNG_STRIP_ALPHA 0x40000L
  182941. #define PNG_INVERT_ALPHA 0x80000L
  182942. #define PNG_USER_TRANSFORM 0x100000L
  182943. #define PNG_RGB_TO_GRAY_ERR 0x200000L
  182944. #define PNG_RGB_TO_GRAY_WARN 0x400000L
  182945. #define PNG_RGB_TO_GRAY 0x600000L /* two bits, RGB_TO_GRAY_ERR|WARN */
  182946. /* 0x800000L Unused */
  182947. #define PNG_ADD_ALPHA 0x1000000L /* Added to libpng-1.2.7 */
  182948. #define PNG_EXPAND_tRNS 0x2000000L /* Added to libpng-1.2.9 */
  182949. /* 0x4000000L unused */
  182950. /* 0x8000000L unused */
  182951. /* 0x10000000L unused */
  182952. /* 0x20000000L unused */
  182953. /* 0x40000000L unused */
  182954. /* flags for png_create_struct */
  182955. #define PNG_STRUCT_PNG 0x0001
  182956. #define PNG_STRUCT_INFO 0x0002
  182957. /* Scaling factor for filter heuristic weighting calculations */
  182958. #define PNG_WEIGHT_SHIFT 8
  182959. #define PNG_WEIGHT_FACTOR (1<<(PNG_WEIGHT_SHIFT))
  182960. #define PNG_COST_SHIFT 3
  182961. #define PNG_COST_FACTOR (1<<(PNG_COST_SHIFT))
  182962. /* flags for the png_ptr->flags rather than declaring a byte for each one */
  182963. #define PNG_FLAG_ZLIB_CUSTOM_STRATEGY 0x0001
  182964. #define PNG_FLAG_ZLIB_CUSTOM_LEVEL 0x0002
  182965. #define PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL 0x0004
  182966. #define PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS 0x0008
  182967. #define PNG_FLAG_ZLIB_CUSTOM_METHOD 0x0010
  182968. #define PNG_FLAG_ZLIB_FINISHED 0x0020
  182969. #define PNG_FLAG_ROW_INIT 0x0040
  182970. #define PNG_FLAG_FILLER_AFTER 0x0080
  182971. #define PNG_FLAG_CRC_ANCILLARY_USE 0x0100
  182972. #define PNG_FLAG_CRC_ANCILLARY_NOWARN 0x0200
  182973. #define PNG_FLAG_CRC_CRITICAL_USE 0x0400
  182974. #define PNG_FLAG_CRC_CRITICAL_IGNORE 0x0800
  182975. #define PNG_FLAG_FREE_PLTE 0x1000
  182976. #define PNG_FLAG_FREE_TRNS 0x2000
  182977. #define PNG_FLAG_FREE_HIST 0x4000
  182978. #define PNG_FLAG_KEEP_UNKNOWN_CHUNKS 0x8000L
  182979. #define PNG_FLAG_KEEP_UNSAFE_CHUNKS 0x10000L
  182980. #define PNG_FLAG_LIBRARY_MISMATCH 0x20000L
  182981. #define PNG_FLAG_STRIP_ERROR_NUMBERS 0x40000L
  182982. #define PNG_FLAG_STRIP_ERROR_TEXT 0x80000L
  182983. #define PNG_FLAG_MALLOC_NULL_MEM_OK 0x100000L
  182984. #define PNG_FLAG_ADD_ALPHA 0x200000L /* Added to libpng-1.2.8 */
  182985. #define PNG_FLAG_STRIP_ALPHA 0x400000L /* Added to libpng-1.2.8 */
  182986. /* 0x800000L unused */
  182987. /* 0x1000000L unused */
  182988. /* 0x2000000L unused */
  182989. /* 0x4000000L unused */
  182990. /* 0x8000000L unused */
  182991. /* 0x10000000L unused */
  182992. /* 0x20000000L unused */
  182993. /* 0x40000000L unused */
  182994. #define PNG_FLAG_CRC_ANCILLARY_MASK (PNG_FLAG_CRC_ANCILLARY_USE | \
  182995. PNG_FLAG_CRC_ANCILLARY_NOWARN)
  182996. #define PNG_FLAG_CRC_CRITICAL_MASK (PNG_FLAG_CRC_CRITICAL_USE | \
  182997. PNG_FLAG_CRC_CRITICAL_IGNORE)
  182998. #define PNG_FLAG_CRC_MASK (PNG_FLAG_CRC_ANCILLARY_MASK | \
  182999. PNG_FLAG_CRC_CRITICAL_MASK)
  183000. /* save typing and make code easier to understand */
  183001. #define PNG_COLOR_DIST(c1, c2) (abs((int)((c1).red) - (int)((c2).red)) + \
  183002. abs((int)((c1).green) - (int)((c2).green)) + \
  183003. abs((int)((c1).blue) - (int)((c2).blue)))
  183004. /* Added to libpng-1.2.6 JB */
  183005. #define PNG_ROWBYTES(pixel_bits, width) \
  183006. ((pixel_bits) >= 8 ? \
  183007. ((width) * (((png_uint_32)(pixel_bits)) >> 3)) : \
  183008. (( ((width) * ((png_uint_32)(pixel_bits))) + 7) >> 3) )
  183009. /* PNG_OUT_OF_RANGE returns true if value is outside the range
  183010. ideal-delta..ideal+delta. Each argument is evaluated twice.
  183011. "ideal" and "delta" should be constants, normally simple
  183012. integers, "value" a variable. Added to libpng-1.2.6 JB */
  183013. #define PNG_OUT_OF_RANGE(value, ideal, delta) \
  183014. ( (value) < (ideal)-(delta) || (value) > (ideal)+(delta) )
  183015. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  183016. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  183017. /* place to hold the signature string for a PNG file. */
  183018. #ifdef PNG_USE_GLOBAL_ARRAYS
  183019. PNG_EXPORT_VAR (PNG_CONST png_byte FARDATA) png_sig[8];
  183020. #else
  183021. #endif
  183022. #endif /* PNG_NO_EXTERN */
  183023. /* Constant strings for known chunk types. If you need to add a chunk,
  183024. * define the name here, and add an invocation of the macro in png.c and
  183025. * wherever it's needed.
  183026. */
  183027. #define PNG_IHDR png_byte png_IHDR[5] = { 73, 72, 68, 82, '\0'}
  183028. #define PNG_IDAT png_byte png_IDAT[5] = { 73, 68, 65, 84, '\0'}
  183029. #define PNG_IEND png_byte png_IEND[5] = { 73, 69, 78, 68, '\0'}
  183030. #define PNG_PLTE png_byte png_PLTE[5] = { 80, 76, 84, 69, '\0'}
  183031. #define PNG_bKGD png_byte png_bKGD[5] = { 98, 75, 71, 68, '\0'}
  183032. #define PNG_cHRM png_byte png_cHRM[5] = { 99, 72, 82, 77, '\0'}
  183033. #define PNG_gAMA png_byte png_gAMA[5] = {103, 65, 77, 65, '\0'}
  183034. #define PNG_hIST png_byte png_hIST[5] = {104, 73, 83, 84, '\0'}
  183035. #define PNG_iCCP png_byte png_iCCP[5] = {105, 67, 67, 80, '\0'}
  183036. #define PNG_iTXt png_byte png_iTXt[5] = {105, 84, 88, 116, '\0'}
  183037. #define PNG_oFFs png_byte png_oFFs[5] = {111, 70, 70, 115, '\0'}
  183038. #define PNG_pCAL png_byte png_pCAL[5] = {112, 67, 65, 76, '\0'}
  183039. #define PNG_sCAL png_byte png_sCAL[5] = {115, 67, 65, 76, '\0'}
  183040. #define PNG_pHYs png_byte png_pHYs[5] = {112, 72, 89, 115, '\0'}
  183041. #define PNG_sBIT png_byte png_sBIT[5] = {115, 66, 73, 84, '\0'}
  183042. #define PNG_sPLT png_byte png_sPLT[5] = {115, 80, 76, 84, '\0'}
  183043. #define PNG_sRGB png_byte png_sRGB[5] = {115, 82, 71, 66, '\0'}
  183044. #define PNG_tEXt png_byte png_tEXt[5] = {116, 69, 88, 116, '\0'}
  183045. #define PNG_tIME png_byte png_tIME[5] = {116, 73, 77, 69, '\0'}
  183046. #define PNG_tRNS png_byte png_tRNS[5] = {116, 82, 78, 83, '\0'}
  183047. #define PNG_zTXt png_byte png_zTXt[5] = {122, 84, 88, 116, '\0'}
  183048. #ifdef PNG_USE_GLOBAL_ARRAYS
  183049. PNG_EXPORT_VAR (png_byte FARDATA) png_IHDR[5];
  183050. PNG_EXPORT_VAR (png_byte FARDATA) png_IDAT[5];
  183051. PNG_EXPORT_VAR (png_byte FARDATA) png_IEND[5];
  183052. PNG_EXPORT_VAR (png_byte FARDATA) png_PLTE[5];
  183053. PNG_EXPORT_VAR (png_byte FARDATA) png_bKGD[5];
  183054. PNG_EXPORT_VAR (png_byte FARDATA) png_cHRM[5];
  183055. PNG_EXPORT_VAR (png_byte FARDATA) png_gAMA[5];
  183056. PNG_EXPORT_VAR (png_byte FARDATA) png_hIST[5];
  183057. PNG_EXPORT_VAR (png_byte FARDATA) png_iCCP[5];
  183058. PNG_EXPORT_VAR (png_byte FARDATA) png_iTXt[5];
  183059. PNG_EXPORT_VAR (png_byte FARDATA) png_oFFs[5];
  183060. PNG_EXPORT_VAR (png_byte FARDATA) png_pCAL[5];
  183061. PNG_EXPORT_VAR (png_byte FARDATA) png_sCAL[5];
  183062. PNG_EXPORT_VAR (png_byte FARDATA) png_pHYs[5];
  183063. PNG_EXPORT_VAR (png_byte FARDATA) png_sBIT[5];
  183064. PNG_EXPORT_VAR (png_byte FARDATA) png_sPLT[5];
  183065. PNG_EXPORT_VAR (png_byte FARDATA) png_sRGB[5];
  183066. PNG_EXPORT_VAR (png_byte FARDATA) png_tEXt[5];
  183067. PNG_EXPORT_VAR (png_byte FARDATA) png_tIME[5];
  183068. PNG_EXPORT_VAR (png_byte FARDATA) png_tRNS[5];
  183069. PNG_EXPORT_VAR (png_byte FARDATA) png_zTXt[5];
  183070. #endif /* PNG_USE_GLOBAL_ARRAYS */
  183071. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183072. /* Initialize png_ptr struct for reading, and allocate any other memory.
  183073. * (old interface - DEPRECATED - use png_create_read_struct instead).
  183074. */
  183075. extern PNG_EXPORT(void,png_read_init) PNGARG((png_structp png_ptr));
  183076. #undef png_read_init
  183077. #define png_read_init(png_ptr) png_read_init_3(&png_ptr, \
  183078. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  183079. #endif
  183080. extern PNG_EXPORT(void,png_read_init_3) PNGARG((png_structpp ptr_ptr,
  183081. png_const_charp user_png_ver, png_size_t png_struct_size));
  183082. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183083. extern PNG_EXPORT(void,png_read_init_2) PNGARG((png_structp png_ptr,
  183084. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  183085. png_info_size));
  183086. #endif
  183087. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183088. /* Initialize png_ptr struct for writing, and allocate any other memory.
  183089. * (old interface - DEPRECATED - use png_create_write_struct instead).
  183090. */
  183091. extern PNG_EXPORT(void,png_write_init) PNGARG((png_structp png_ptr));
  183092. #undef png_write_init
  183093. #define png_write_init(png_ptr) png_write_init_3(&png_ptr, \
  183094. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  183095. #endif
  183096. extern PNG_EXPORT(void,png_write_init_3) PNGARG((png_structpp ptr_ptr,
  183097. png_const_charp user_png_ver, png_size_t png_struct_size));
  183098. extern PNG_EXPORT(void,png_write_init_2) PNGARG((png_structp png_ptr,
  183099. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  183100. png_info_size));
  183101. /* Allocate memory for an internal libpng struct */
  183102. PNG_EXTERN png_voidp png_create_struct PNGARG((int type));
  183103. /* Free memory from internal libpng struct */
  183104. PNG_EXTERN void png_destroy_struct PNGARG((png_voidp struct_ptr));
  183105. PNG_EXTERN png_voidp png_create_struct_2 PNGARG((int type, png_malloc_ptr
  183106. malloc_fn, png_voidp mem_ptr));
  183107. PNG_EXTERN void png_destroy_struct_2 PNGARG((png_voidp struct_ptr,
  183108. png_free_ptr free_fn, png_voidp mem_ptr));
  183109. /* Free any memory that info_ptr points to and reset struct. */
  183110. PNG_EXTERN void png_info_destroy PNGARG((png_structp png_ptr,
  183111. png_infop info_ptr));
  183112. #ifndef PNG_1_0_X
  183113. /* Function to allocate memory for zlib. */
  183114. PNG_EXTERN voidpf png_zalloc PNGARG((voidpf png_ptr, uInt items, uInt size));
  183115. /* Function to free memory for zlib */
  183116. PNG_EXTERN void png_zfree PNGARG((voidpf png_ptr, voidpf ptr));
  183117. #ifdef PNG_SIZE_T
  183118. /* Function to convert a sizeof an item to png_sizeof item */
  183119. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  183120. #endif
  183121. /* Next four functions are used internally as callbacks. PNGAPI is required
  183122. * but not PNG_EXPORT. PNGAPI added at libpng version 1.2.3. */
  183123. PNG_EXTERN void PNGAPI png_default_read_data PNGARG((png_structp png_ptr,
  183124. png_bytep data, png_size_t length));
  183125. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  183126. PNG_EXTERN void PNGAPI png_push_fill_buffer PNGARG((png_structp png_ptr,
  183127. png_bytep buffer, png_size_t length));
  183128. #endif
  183129. PNG_EXTERN void PNGAPI png_default_write_data PNGARG((png_structp png_ptr,
  183130. png_bytep data, png_size_t length));
  183131. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  183132. #if !defined(PNG_NO_STDIO)
  183133. PNG_EXTERN void PNGAPI png_default_flush PNGARG((png_structp png_ptr));
  183134. #endif
  183135. #endif
  183136. #else /* PNG_1_0_X */
  183137. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  183138. PNG_EXTERN void png_push_fill_buffer PNGARG((png_structp png_ptr,
  183139. png_bytep buffer, png_size_t length));
  183140. #endif
  183141. #endif /* PNG_1_0_X */
  183142. /* Reset the CRC variable */
  183143. PNG_EXTERN void png_reset_crc PNGARG((png_structp png_ptr));
  183144. /* Write the "data" buffer to whatever output you are using. */
  183145. PNG_EXTERN void png_write_data PNGARG((png_structp png_ptr, png_bytep data,
  183146. png_size_t length));
  183147. /* Read data from whatever input you are using into the "data" buffer */
  183148. PNG_EXTERN void png_read_data PNGARG((png_structp png_ptr, png_bytep data,
  183149. png_size_t length));
  183150. /* Read bytes into buf, and update png_ptr->crc */
  183151. PNG_EXTERN void png_crc_read PNGARG((png_structp png_ptr, png_bytep buf,
  183152. png_size_t length));
  183153. /* Decompress data in a chunk that uses compression */
  183154. #if defined(PNG_zTXt_SUPPORTED) || defined(PNG_iTXt_SUPPORTED) || \
  183155. defined(PNG_iCCP_SUPPORTED) || defined(PNG_sPLT_SUPPORTED)
  183156. PNG_EXTERN png_charp png_decompress_chunk PNGARG((png_structp png_ptr,
  183157. int comp_type, png_charp chunkdata, png_size_t chunklength,
  183158. png_size_t prefix_length, png_size_t *data_length));
  183159. #endif
  183160. /* Read "skip" bytes, read the file crc, and (optionally) verify png_ptr->crc */
  183161. PNG_EXTERN int png_crc_finish PNGARG((png_structp png_ptr, png_uint_32 skip));
  183162. /* Read the CRC from the file and compare it to the libpng calculated CRC */
  183163. PNG_EXTERN int png_crc_error PNGARG((png_structp png_ptr));
  183164. /* Calculate the CRC over a section of data. Note that we are only
  183165. * passing a maximum of 64K on systems that have this as a memory limit,
  183166. * since this is the maximum buffer size we can specify.
  183167. */
  183168. PNG_EXTERN void png_calculate_crc PNGARG((png_structp png_ptr, png_bytep ptr,
  183169. png_size_t length));
  183170. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  183171. PNG_EXTERN void png_flush PNGARG((png_structp png_ptr));
  183172. #endif
  183173. /* simple function to write the signature */
  183174. PNG_EXTERN void png_write_sig PNGARG((png_structp png_ptr));
  183175. /* write various chunks */
  183176. /* Write the IHDR chunk, and update the png_struct with the necessary
  183177. * information.
  183178. */
  183179. PNG_EXTERN void png_write_IHDR PNGARG((png_structp png_ptr, png_uint_32 width,
  183180. png_uint_32 height,
  183181. int bit_depth, int color_type, int compression_method, int filter_method,
  183182. int interlace_method));
  183183. PNG_EXTERN void png_write_PLTE PNGARG((png_structp png_ptr, png_colorp palette,
  183184. png_uint_32 num_pal));
  183185. PNG_EXTERN void png_write_IDAT PNGARG((png_structp png_ptr, png_bytep data,
  183186. png_size_t length));
  183187. PNG_EXTERN void png_write_IEND PNGARG((png_structp png_ptr));
  183188. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  183189. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183190. PNG_EXTERN void png_write_gAMA PNGARG((png_structp png_ptr, double file_gamma));
  183191. #endif
  183192. #ifdef PNG_FIXED_POINT_SUPPORTED
  183193. PNG_EXTERN void png_write_gAMA_fixed PNGARG((png_structp png_ptr, png_fixed_point
  183194. file_gamma));
  183195. #endif
  183196. #endif
  183197. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  183198. PNG_EXTERN void png_write_sBIT PNGARG((png_structp png_ptr, png_color_8p sbit,
  183199. int color_type));
  183200. #endif
  183201. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  183202. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183203. PNG_EXTERN void png_write_cHRM PNGARG((png_structp png_ptr,
  183204. double white_x, double white_y,
  183205. double red_x, double red_y, double green_x, double green_y,
  183206. double blue_x, double blue_y));
  183207. #endif
  183208. #ifdef PNG_FIXED_POINT_SUPPORTED
  183209. PNG_EXTERN void png_write_cHRM_fixed PNGARG((png_structp png_ptr,
  183210. png_fixed_point int_white_x, png_fixed_point int_white_y,
  183211. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  183212. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  183213. png_fixed_point int_blue_y));
  183214. #endif
  183215. #endif
  183216. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  183217. PNG_EXTERN void png_write_sRGB PNGARG((png_structp png_ptr,
  183218. int intent));
  183219. #endif
  183220. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  183221. PNG_EXTERN void png_write_iCCP PNGARG((png_structp png_ptr,
  183222. png_charp name, int compression_type,
  183223. png_charp profile, int proflen));
  183224. /* Note to maintainer: profile should be png_bytep */
  183225. #endif
  183226. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  183227. PNG_EXTERN void png_write_sPLT PNGARG((png_structp png_ptr,
  183228. png_sPLT_tp palette));
  183229. #endif
  183230. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  183231. PNG_EXTERN void png_write_tRNS PNGARG((png_structp png_ptr, png_bytep trans,
  183232. png_color_16p values, int number, int color_type));
  183233. #endif
  183234. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  183235. PNG_EXTERN void png_write_bKGD PNGARG((png_structp png_ptr,
  183236. png_color_16p values, int color_type));
  183237. #endif
  183238. #if defined(PNG_WRITE_hIST_SUPPORTED)
  183239. PNG_EXTERN void png_write_hIST PNGARG((png_structp png_ptr, png_uint_16p hist,
  183240. int num_hist));
  183241. #endif
  183242. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  183243. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  183244. PNG_EXTERN png_size_t png_check_keyword PNGARG((png_structp png_ptr,
  183245. png_charp key, png_charpp new_key));
  183246. #endif
  183247. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  183248. PNG_EXTERN void png_write_tEXt PNGARG((png_structp png_ptr, png_charp key,
  183249. png_charp text, png_size_t text_len));
  183250. #endif
  183251. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  183252. PNG_EXTERN void png_write_zTXt PNGARG((png_structp png_ptr, png_charp key,
  183253. png_charp text, png_size_t text_len, int compression));
  183254. #endif
  183255. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  183256. PNG_EXTERN void png_write_iTXt PNGARG((png_structp png_ptr,
  183257. int compression, png_charp key, png_charp lang, png_charp lang_key,
  183258. png_charp text));
  183259. #endif
  183260. #if defined(PNG_TEXT_SUPPORTED) /* Added at version 1.0.14 and 1.2.4 */
  183261. PNG_EXTERN int png_set_text_2 PNGARG((png_structp png_ptr,
  183262. png_infop info_ptr, png_textp text_ptr, int num_text));
  183263. #endif
  183264. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  183265. PNG_EXTERN void png_write_oFFs PNGARG((png_structp png_ptr,
  183266. png_int_32 x_offset, png_int_32 y_offset, int unit_type));
  183267. #endif
  183268. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  183269. PNG_EXTERN void png_write_pCAL PNGARG((png_structp png_ptr, png_charp purpose,
  183270. png_int_32 X0, png_int_32 X1, int type, int nparams,
  183271. png_charp units, png_charpp params));
  183272. #endif
  183273. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  183274. PNG_EXTERN void png_write_pHYs PNGARG((png_structp png_ptr,
  183275. png_uint_32 x_pixels_per_unit, png_uint_32 y_pixels_per_unit,
  183276. int unit_type));
  183277. #endif
  183278. #if defined(PNG_WRITE_tIME_SUPPORTED)
  183279. PNG_EXTERN void png_write_tIME PNGARG((png_structp png_ptr,
  183280. png_timep mod_time));
  183281. #endif
  183282. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  183283. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  183284. PNG_EXTERN void png_write_sCAL PNGARG((png_structp png_ptr,
  183285. int unit, double width, double height));
  183286. #else
  183287. #ifdef PNG_FIXED_POINT_SUPPORTED
  183288. PNG_EXTERN void png_write_sCAL_s PNGARG((png_structp png_ptr,
  183289. int unit, png_charp width, png_charp height));
  183290. #endif
  183291. #endif
  183292. #endif
  183293. /* Called when finished processing a row of data */
  183294. PNG_EXTERN void png_write_finish_row PNGARG((png_structp png_ptr));
  183295. /* Internal use only. Called before first row of data */
  183296. PNG_EXTERN void png_write_start_row PNGARG((png_structp png_ptr));
  183297. #if defined(PNG_READ_GAMMA_SUPPORTED)
  183298. PNG_EXTERN void png_build_gamma_table PNGARG((png_structp png_ptr));
  183299. #endif
  183300. /* combine a row of data, dealing with alpha, etc. if requested */
  183301. PNG_EXTERN void png_combine_row PNGARG((png_structp png_ptr, png_bytep row,
  183302. int mask));
  183303. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  183304. /* expand an interlaced row */
  183305. /* OLD pre-1.0.9 interface:
  183306. PNG_EXTERN void png_do_read_interlace PNGARG((png_row_infop row_info,
  183307. png_bytep row, int pass, png_uint_32 transformations));
  183308. */
  183309. PNG_EXTERN void png_do_read_interlace PNGARG((png_structp png_ptr));
  183310. #endif
  183311. /* GRR TO DO (2.0 or whenever): simplify other internal calling interfaces */
  183312. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  183313. /* grab pixels out of a row for an interlaced pass */
  183314. PNG_EXTERN void png_do_write_interlace PNGARG((png_row_infop row_info,
  183315. png_bytep row, int pass));
  183316. #endif
  183317. /* unfilter a row */
  183318. PNG_EXTERN void png_read_filter_row PNGARG((png_structp png_ptr,
  183319. png_row_infop row_info, png_bytep row, png_bytep prev_row, int filter));
  183320. /* Choose the best filter to use and filter the row data */
  183321. PNG_EXTERN void png_write_find_filter PNGARG((png_structp png_ptr,
  183322. png_row_infop row_info));
  183323. /* Write out the filtered row. */
  183324. PNG_EXTERN void png_write_filtered_row PNGARG((png_structp png_ptr,
  183325. png_bytep filtered_row));
  183326. /* finish a row while reading, dealing with interlacing passes, etc. */
  183327. PNG_EXTERN void png_read_finish_row PNGARG((png_structp png_ptr));
  183328. /* initialize the row buffers, etc. */
  183329. PNG_EXTERN void png_read_start_row PNGARG((png_structp png_ptr));
  183330. /* optional call to update the users info structure */
  183331. PNG_EXTERN void png_read_transform_info PNGARG((png_structp png_ptr,
  183332. png_infop info_ptr));
  183333. /* these are the functions that do the transformations */
  183334. #if defined(PNG_READ_FILLER_SUPPORTED)
  183335. PNG_EXTERN void png_do_read_filler PNGARG((png_row_infop row_info,
  183336. png_bytep row, png_uint_32 filler, png_uint_32 flags));
  183337. #endif
  183338. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  183339. PNG_EXTERN void png_do_read_swap_alpha PNGARG((png_row_infop row_info,
  183340. png_bytep row));
  183341. #endif
  183342. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  183343. PNG_EXTERN void png_do_write_swap_alpha PNGARG((png_row_infop row_info,
  183344. png_bytep row));
  183345. #endif
  183346. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  183347. PNG_EXTERN void png_do_read_invert_alpha PNGARG((png_row_infop row_info,
  183348. png_bytep row));
  183349. #endif
  183350. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  183351. PNG_EXTERN void png_do_write_invert_alpha PNGARG((png_row_infop row_info,
  183352. png_bytep row));
  183353. #endif
  183354. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  183355. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  183356. PNG_EXTERN void png_do_strip_filler PNGARG((png_row_infop row_info,
  183357. png_bytep row, png_uint_32 flags));
  183358. #endif
  183359. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  183360. PNG_EXTERN void png_do_swap PNGARG((png_row_infop row_info, png_bytep row));
  183361. #endif
  183362. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  183363. PNG_EXTERN void png_do_packswap PNGARG((png_row_infop row_info, png_bytep row));
  183364. #endif
  183365. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  183366. PNG_EXTERN int png_do_rgb_to_gray PNGARG((png_structp png_ptr, png_row_infop
  183367. row_info, png_bytep row));
  183368. #endif
  183369. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  183370. PNG_EXTERN void png_do_gray_to_rgb PNGARG((png_row_infop row_info,
  183371. png_bytep row));
  183372. #endif
  183373. #if defined(PNG_READ_PACK_SUPPORTED)
  183374. PNG_EXTERN void png_do_unpack PNGARG((png_row_infop row_info, png_bytep row));
  183375. #endif
  183376. #if defined(PNG_READ_SHIFT_SUPPORTED)
  183377. PNG_EXTERN void png_do_unshift PNGARG((png_row_infop row_info, png_bytep row,
  183378. png_color_8p sig_bits));
  183379. #endif
  183380. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  183381. PNG_EXTERN void png_do_invert PNGARG((png_row_infop row_info, png_bytep row));
  183382. #endif
  183383. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  183384. PNG_EXTERN void png_do_chop PNGARG((png_row_infop row_info, png_bytep row));
  183385. #endif
  183386. #if defined(PNG_READ_DITHER_SUPPORTED)
  183387. PNG_EXTERN void png_do_dither PNGARG((png_row_infop row_info,
  183388. png_bytep row, png_bytep palette_lookup, png_bytep dither_lookup));
  183389. # if defined(PNG_CORRECT_PALETTE_SUPPORTED)
  183390. PNG_EXTERN void png_correct_palette PNGARG((png_structp png_ptr,
  183391. png_colorp palette, int num_palette));
  183392. # endif
  183393. #endif
  183394. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  183395. PNG_EXTERN void png_do_bgr PNGARG((png_row_infop row_info, png_bytep row));
  183396. #endif
  183397. #if defined(PNG_WRITE_PACK_SUPPORTED)
  183398. PNG_EXTERN void png_do_pack PNGARG((png_row_infop row_info,
  183399. png_bytep row, png_uint_32 bit_depth));
  183400. #endif
  183401. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  183402. PNG_EXTERN void png_do_shift PNGARG((png_row_infop row_info, png_bytep row,
  183403. png_color_8p bit_depth));
  183404. #endif
  183405. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  183406. #if defined(PNG_READ_GAMMA_SUPPORTED)
  183407. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  183408. png_color_16p trans_values, png_color_16p background,
  183409. png_color_16p background_1,
  183410. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  183411. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  183412. png_uint_16pp gamma_16_to_1, int gamma_shift));
  183413. #else
  183414. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  183415. png_color_16p trans_values, png_color_16p background));
  183416. #endif
  183417. #endif
  183418. #if defined(PNG_READ_GAMMA_SUPPORTED)
  183419. PNG_EXTERN void png_do_gamma PNGARG((png_row_infop row_info, png_bytep row,
  183420. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  183421. int gamma_shift));
  183422. #endif
  183423. #if defined(PNG_READ_EXPAND_SUPPORTED)
  183424. PNG_EXTERN void png_do_expand_palette PNGARG((png_row_infop row_info,
  183425. png_bytep row, png_colorp palette, png_bytep trans, int num_trans));
  183426. PNG_EXTERN void png_do_expand PNGARG((png_row_infop row_info,
  183427. png_bytep row, png_color_16p trans_value));
  183428. #endif
  183429. /* The following decodes the appropriate chunks, and does error correction,
  183430. * then calls the appropriate callback for the chunk if it is valid.
  183431. */
  183432. /* decode the IHDR chunk */
  183433. PNG_EXTERN void png_handle_IHDR PNGARG((png_structp png_ptr, png_infop info_ptr,
  183434. png_uint_32 length));
  183435. PNG_EXTERN void png_handle_PLTE PNGARG((png_structp png_ptr, png_infop info_ptr,
  183436. png_uint_32 length));
  183437. PNG_EXTERN void png_handle_IEND PNGARG((png_structp png_ptr, png_infop info_ptr,
  183438. png_uint_32 length));
  183439. #if defined(PNG_READ_bKGD_SUPPORTED)
  183440. PNG_EXTERN void png_handle_bKGD PNGARG((png_structp png_ptr, png_infop info_ptr,
  183441. png_uint_32 length));
  183442. #endif
  183443. #if defined(PNG_READ_cHRM_SUPPORTED)
  183444. PNG_EXTERN void png_handle_cHRM PNGARG((png_structp png_ptr, png_infop info_ptr,
  183445. png_uint_32 length));
  183446. #endif
  183447. #if defined(PNG_READ_gAMA_SUPPORTED)
  183448. PNG_EXTERN void png_handle_gAMA PNGARG((png_structp png_ptr, png_infop info_ptr,
  183449. png_uint_32 length));
  183450. #endif
  183451. #if defined(PNG_READ_hIST_SUPPORTED)
  183452. PNG_EXTERN void png_handle_hIST PNGARG((png_structp png_ptr, png_infop info_ptr,
  183453. png_uint_32 length));
  183454. #endif
  183455. #if defined(PNG_READ_iCCP_SUPPORTED)
  183456. extern void png_handle_iCCP PNGARG((png_structp png_ptr, png_infop info_ptr,
  183457. png_uint_32 length));
  183458. #endif /* PNG_READ_iCCP_SUPPORTED */
  183459. #if defined(PNG_READ_iTXt_SUPPORTED)
  183460. PNG_EXTERN void png_handle_iTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  183461. png_uint_32 length));
  183462. #endif
  183463. #if defined(PNG_READ_oFFs_SUPPORTED)
  183464. PNG_EXTERN void png_handle_oFFs PNGARG((png_structp png_ptr, png_infop info_ptr,
  183465. png_uint_32 length));
  183466. #endif
  183467. #if defined(PNG_READ_pCAL_SUPPORTED)
  183468. PNG_EXTERN void png_handle_pCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  183469. png_uint_32 length));
  183470. #endif
  183471. #if defined(PNG_READ_pHYs_SUPPORTED)
  183472. PNG_EXTERN void png_handle_pHYs PNGARG((png_structp png_ptr, png_infop info_ptr,
  183473. png_uint_32 length));
  183474. #endif
  183475. #if defined(PNG_READ_sBIT_SUPPORTED)
  183476. PNG_EXTERN void png_handle_sBIT PNGARG((png_structp png_ptr, png_infop info_ptr,
  183477. png_uint_32 length));
  183478. #endif
  183479. #if defined(PNG_READ_sCAL_SUPPORTED)
  183480. PNG_EXTERN void png_handle_sCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  183481. png_uint_32 length));
  183482. #endif
  183483. #if defined(PNG_READ_sPLT_SUPPORTED)
  183484. extern void png_handle_sPLT PNGARG((png_structp png_ptr, png_infop info_ptr,
  183485. png_uint_32 length));
  183486. #endif /* PNG_READ_sPLT_SUPPORTED */
  183487. #if defined(PNG_READ_sRGB_SUPPORTED)
  183488. PNG_EXTERN void png_handle_sRGB PNGARG((png_structp png_ptr, png_infop info_ptr,
  183489. png_uint_32 length));
  183490. #endif
  183491. #if defined(PNG_READ_tEXt_SUPPORTED)
  183492. PNG_EXTERN void png_handle_tEXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  183493. png_uint_32 length));
  183494. #endif
  183495. #if defined(PNG_READ_tIME_SUPPORTED)
  183496. PNG_EXTERN void png_handle_tIME PNGARG((png_structp png_ptr, png_infop info_ptr,
  183497. png_uint_32 length));
  183498. #endif
  183499. #if defined(PNG_READ_tRNS_SUPPORTED)
  183500. PNG_EXTERN void png_handle_tRNS PNGARG((png_structp png_ptr, png_infop info_ptr,
  183501. png_uint_32 length));
  183502. #endif
  183503. #if defined(PNG_READ_zTXt_SUPPORTED)
  183504. PNG_EXTERN void png_handle_zTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  183505. png_uint_32 length));
  183506. #endif
  183507. PNG_EXTERN void png_handle_unknown PNGARG((png_structp png_ptr,
  183508. png_infop info_ptr, png_uint_32 length));
  183509. PNG_EXTERN void png_check_chunk_name PNGARG((png_structp png_ptr,
  183510. png_bytep chunk_name));
  183511. /* handle the transformations for reading and writing */
  183512. PNG_EXTERN void png_do_read_transformations PNGARG((png_structp png_ptr));
  183513. PNG_EXTERN void png_do_write_transformations PNGARG((png_structp png_ptr));
  183514. PNG_EXTERN void png_init_read_transformations PNGARG((png_structp png_ptr));
  183515. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  183516. PNG_EXTERN void png_push_read_chunk PNGARG((png_structp png_ptr,
  183517. png_infop info_ptr));
  183518. PNG_EXTERN void png_push_read_sig PNGARG((png_structp png_ptr,
  183519. png_infop info_ptr));
  183520. PNG_EXTERN void png_push_check_crc PNGARG((png_structp png_ptr));
  183521. PNG_EXTERN void png_push_crc_skip PNGARG((png_structp png_ptr,
  183522. png_uint_32 length));
  183523. PNG_EXTERN void png_push_crc_finish PNGARG((png_structp png_ptr));
  183524. PNG_EXTERN void png_push_save_buffer PNGARG((png_structp png_ptr));
  183525. PNG_EXTERN void png_push_restore_buffer PNGARG((png_structp png_ptr,
  183526. png_bytep buffer, png_size_t buffer_length));
  183527. PNG_EXTERN void png_push_read_IDAT PNGARG((png_structp png_ptr));
  183528. PNG_EXTERN void png_process_IDAT_data PNGARG((png_structp png_ptr,
  183529. png_bytep buffer, png_size_t buffer_length));
  183530. PNG_EXTERN void png_push_process_row PNGARG((png_structp png_ptr));
  183531. PNG_EXTERN void png_push_handle_unknown PNGARG((png_structp png_ptr,
  183532. png_infop info_ptr, png_uint_32 length));
  183533. PNG_EXTERN void png_push_have_info PNGARG((png_structp png_ptr,
  183534. png_infop info_ptr));
  183535. PNG_EXTERN void png_push_have_end PNGARG((png_structp png_ptr,
  183536. png_infop info_ptr));
  183537. PNG_EXTERN void png_push_have_row PNGARG((png_structp png_ptr, png_bytep row));
  183538. PNG_EXTERN void png_push_read_end PNGARG((png_structp png_ptr,
  183539. png_infop info_ptr));
  183540. PNG_EXTERN void png_process_some_data PNGARG((png_structp png_ptr,
  183541. png_infop info_ptr));
  183542. PNG_EXTERN void png_read_push_finish_row PNGARG((png_structp png_ptr));
  183543. #if defined(PNG_READ_tEXt_SUPPORTED)
  183544. PNG_EXTERN void png_push_handle_tEXt PNGARG((png_structp png_ptr,
  183545. png_infop info_ptr, png_uint_32 length));
  183546. PNG_EXTERN void png_push_read_tEXt PNGARG((png_structp png_ptr,
  183547. png_infop info_ptr));
  183548. #endif
  183549. #if defined(PNG_READ_zTXt_SUPPORTED)
  183550. PNG_EXTERN void png_push_handle_zTXt PNGARG((png_structp png_ptr,
  183551. png_infop info_ptr, png_uint_32 length));
  183552. PNG_EXTERN void png_push_read_zTXt PNGARG((png_structp png_ptr,
  183553. png_infop info_ptr));
  183554. #endif
  183555. #if defined(PNG_READ_iTXt_SUPPORTED)
  183556. PNG_EXTERN void png_push_handle_iTXt PNGARG((png_structp png_ptr,
  183557. png_infop info_ptr, png_uint_32 length));
  183558. PNG_EXTERN void png_push_read_iTXt PNGARG((png_structp png_ptr,
  183559. png_infop info_ptr));
  183560. #endif
  183561. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  183562. #ifdef PNG_MNG_FEATURES_SUPPORTED
  183563. PNG_EXTERN void png_do_read_intrapixel PNGARG((png_row_infop row_info,
  183564. png_bytep row));
  183565. PNG_EXTERN void png_do_write_intrapixel PNGARG((png_row_infop row_info,
  183566. png_bytep row));
  183567. #endif
  183568. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  183569. #if defined(PNG_MMX_CODE_SUPPORTED)
  183570. /* png.c */ /* PRIVATE */
  183571. PNG_EXTERN void png_init_mmx_flags PNGARG((png_structp png_ptr));
  183572. #endif
  183573. #endif
  183574. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  183575. PNG_EXTERN png_uint_32 png_get_pixels_per_inch PNGARG((png_structp png_ptr,
  183576. png_infop info_ptr));
  183577. PNG_EXTERN png_uint_32 png_get_x_pixels_per_inch PNGARG((png_structp png_ptr,
  183578. png_infop info_ptr));
  183579. PNG_EXTERN png_uint_32 png_get_y_pixels_per_inch PNGARG((png_structp png_ptr,
  183580. png_infop info_ptr));
  183581. PNG_EXTERN float png_get_x_offset_inches PNGARG((png_structp png_ptr,
  183582. png_infop info_ptr));
  183583. PNG_EXTERN float png_get_y_offset_inches PNGARG((png_structp png_ptr,
  183584. png_infop info_ptr));
  183585. #if defined(PNG_pHYs_SUPPORTED)
  183586. PNG_EXTERN png_uint_32 png_get_pHYs_dpi PNGARG((png_structp png_ptr,
  183587. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  183588. #endif /* PNG_pHYs_SUPPORTED */
  183589. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  183590. /* Maintainer: Put new private prototypes here ^ and in libpngpf.3 */
  183591. #endif /* PNG_INTERNAL */
  183592. #ifdef __cplusplus
  183593. }
  183594. #endif
  183595. #endif /* PNG_VERSION_INFO_ONLY */
  183596. /* do not put anything past this line */
  183597. #endif /* PNG_H */
  183598. /*** End of inlined file: png.h ***/
  183599. #define PNG_NO_EXTERN
  183600. /*** Start of inlined file: png.c ***/
  183601. /* png.c - location for general purpose libpng functions
  183602. *
  183603. * Last changed in libpng 1.2.21 [October 4, 2007]
  183604. * For conditions of distribution and use, see copyright notice in png.h
  183605. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  183606. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  183607. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  183608. */
  183609. #define PNG_INTERNAL
  183610. #define PNG_NO_EXTERN
  183611. /* Generate a compiler error if there is an old png.h in the search path. */
  183612. typedef version_1_2_21 Your_png_h_is_not_version_1_2_21;
  183613. /* Version information for C files. This had better match the version
  183614. * string defined in png.h. */
  183615. #ifdef PNG_USE_GLOBAL_ARRAYS
  183616. /* png_libpng_ver was changed to a function in version 1.0.5c */
  183617. PNG_CONST char png_libpng_ver[18] = PNG_LIBPNG_VER_STRING;
  183618. #ifdef PNG_READ_SUPPORTED
  183619. /* png_sig was changed to a function in version 1.0.5c */
  183620. /* Place to hold the signature string for a PNG file. */
  183621. PNG_CONST png_byte FARDATA png_sig[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  183622. #endif /* PNG_READ_SUPPORTED */
  183623. /* Invoke global declarations for constant strings for known chunk types */
  183624. PNG_IHDR;
  183625. PNG_IDAT;
  183626. PNG_IEND;
  183627. PNG_PLTE;
  183628. PNG_bKGD;
  183629. PNG_cHRM;
  183630. PNG_gAMA;
  183631. PNG_hIST;
  183632. PNG_iCCP;
  183633. PNG_iTXt;
  183634. PNG_oFFs;
  183635. PNG_pCAL;
  183636. PNG_sCAL;
  183637. PNG_pHYs;
  183638. PNG_sBIT;
  183639. PNG_sPLT;
  183640. PNG_sRGB;
  183641. PNG_tEXt;
  183642. PNG_tIME;
  183643. PNG_tRNS;
  183644. PNG_zTXt;
  183645. #ifdef PNG_READ_SUPPORTED
  183646. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  183647. /* start of interlace block */
  183648. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  183649. /* offset to next interlace block */
  183650. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  183651. /* start of interlace block in the y direction */
  183652. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  183653. /* offset to next interlace block in the y direction */
  183654. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  183655. /* Height of interlace block. This is not currently used - if you need
  183656. * it, uncomment it here and in png.h
  183657. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  183658. */
  183659. /* Mask to determine which pixels are valid in a pass */
  183660. PNG_CONST int FARDATA png_pass_mask[] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  183661. /* Mask to determine which pixels to overwrite while displaying */
  183662. PNG_CONST int FARDATA png_pass_dsp_mask[]
  183663. = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  183664. #endif /* PNG_READ_SUPPORTED */
  183665. #endif /* PNG_USE_GLOBAL_ARRAYS */
  183666. /* Tells libpng that we have already handled the first "num_bytes" bytes
  183667. * of the PNG file signature. If the PNG data is embedded into another
  183668. * stream we can set num_bytes = 8 so that libpng will not attempt to read
  183669. * or write any of the magic bytes before it starts on the IHDR.
  183670. */
  183671. #ifdef PNG_READ_SUPPORTED
  183672. void PNGAPI
  183673. png_set_sig_bytes(png_structp png_ptr, int num_bytes)
  183674. {
  183675. if(png_ptr == NULL) return;
  183676. png_debug(1, "in png_set_sig_bytes\n");
  183677. if (num_bytes > 8)
  183678. png_error(png_ptr, "Too many bytes for PNG signature.");
  183679. png_ptr->sig_bytes = (png_byte)(num_bytes < 0 ? 0 : num_bytes);
  183680. }
  183681. /* Checks whether the supplied bytes match the PNG signature. We allow
  183682. * checking less than the full 8-byte signature so that those apps that
  183683. * already read the first few bytes of a file to determine the file type
  183684. * can simply check the remaining bytes for extra assurance. Returns
  183685. * an integer less than, equal to, or greater than zero if sig is found,
  183686. * respectively, to be less than, to match, or be greater than the correct
  183687. * PNG signature (this is the same behaviour as strcmp, memcmp, etc).
  183688. */
  183689. int PNGAPI
  183690. png_sig_cmp(png_bytep sig, png_size_t start, png_size_t num_to_check)
  183691. {
  183692. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  183693. if (num_to_check > 8)
  183694. num_to_check = 8;
  183695. else if (num_to_check < 1)
  183696. return (-1);
  183697. if (start > 7)
  183698. return (-1);
  183699. if (start + num_to_check > 8)
  183700. num_to_check = 8 - start;
  183701. return ((int)(png_memcmp(&sig[start], &png_signature[start], num_to_check)));
  183702. }
  183703. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  183704. /* (Obsolete) function to check signature bytes. It does not allow one
  183705. * to check a partial signature. This function might be removed in the
  183706. * future - use png_sig_cmp(). Returns true (nonzero) if the file is PNG.
  183707. */
  183708. int PNGAPI
  183709. png_check_sig(png_bytep sig, int num)
  183710. {
  183711. return ((int)!png_sig_cmp(sig, (png_size_t)0, (png_size_t)num));
  183712. }
  183713. #endif
  183714. #endif /* PNG_READ_SUPPORTED */
  183715. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  183716. /* Function to allocate memory for zlib and clear it to 0. */
  183717. #ifdef PNG_1_0_X
  183718. voidpf PNGAPI
  183719. #else
  183720. voidpf /* private */
  183721. #endif
  183722. png_zalloc(voidpf png_ptr, uInt items, uInt size)
  183723. {
  183724. png_voidp ptr;
  183725. png_structp p=(png_structp)png_ptr;
  183726. png_uint_32 save_flags=p->flags;
  183727. png_uint_32 num_bytes;
  183728. if(png_ptr == NULL) return (NULL);
  183729. if (items > PNG_UINT_32_MAX/size)
  183730. {
  183731. png_warning (p, "Potential overflow in png_zalloc()");
  183732. return (NULL);
  183733. }
  183734. num_bytes = (png_uint_32)items * size;
  183735. p->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  183736. ptr = (png_voidp)png_malloc((png_structp)png_ptr, num_bytes);
  183737. p->flags=save_flags;
  183738. #if defined(PNG_1_0_X) && !defined(PNG_NO_ZALLOC_ZERO)
  183739. if (ptr == NULL)
  183740. return ((voidpf)ptr);
  183741. if (num_bytes > (png_uint_32)0x8000L)
  183742. {
  183743. png_memset(ptr, 0, (png_size_t)0x8000L);
  183744. png_memset((png_bytep)ptr + (png_size_t)0x8000L, 0,
  183745. (png_size_t)(num_bytes - (png_uint_32)0x8000L));
  183746. }
  183747. else
  183748. {
  183749. png_memset(ptr, 0, (png_size_t)num_bytes);
  183750. }
  183751. #endif
  183752. return ((voidpf)ptr);
  183753. }
  183754. /* function to free memory for zlib */
  183755. #ifdef PNG_1_0_X
  183756. void PNGAPI
  183757. #else
  183758. void /* private */
  183759. #endif
  183760. png_zfree(voidpf png_ptr, voidpf ptr)
  183761. {
  183762. png_free((png_structp)png_ptr, (png_voidp)ptr);
  183763. }
  183764. /* Reset the CRC variable to 32 bits of 1's. Care must be taken
  183765. * in case CRC is > 32 bits to leave the top bits 0.
  183766. */
  183767. void /* PRIVATE */
  183768. png_reset_crc(png_structp png_ptr)
  183769. {
  183770. png_ptr->crc = crc32(0, Z_NULL, 0);
  183771. }
  183772. /* Calculate the CRC over a section of data. We can only pass as
  183773. * much data to this routine as the largest single buffer size. We
  183774. * also check that this data will actually be used before going to the
  183775. * trouble of calculating it.
  183776. */
  183777. void /* PRIVATE */
  183778. png_calculate_crc(png_structp png_ptr, png_bytep ptr, png_size_t length)
  183779. {
  183780. int need_crc = 1;
  183781. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  183782. {
  183783. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  183784. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  183785. need_crc = 0;
  183786. }
  183787. else /* critical */
  183788. {
  183789. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  183790. need_crc = 0;
  183791. }
  183792. if (need_crc)
  183793. png_ptr->crc = crc32(png_ptr->crc, ptr, (uInt)length);
  183794. }
  183795. /* Allocate the memory for an info_struct for the application. We don't
  183796. * really need the png_ptr, but it could potentially be useful in the
  183797. * future. This should be used in favour of malloc(png_sizeof(png_info))
  183798. * and png_info_init() so that applications that want to use a shared
  183799. * libpng don't have to be recompiled if png_info changes size.
  183800. */
  183801. png_infop PNGAPI
  183802. png_create_info_struct(png_structp png_ptr)
  183803. {
  183804. png_infop info_ptr;
  183805. png_debug(1, "in png_create_info_struct\n");
  183806. if(png_ptr == NULL) return (NULL);
  183807. #ifdef PNG_USER_MEM_SUPPORTED
  183808. info_ptr = (png_infop)png_create_struct_2(PNG_STRUCT_INFO,
  183809. png_ptr->malloc_fn, png_ptr->mem_ptr);
  183810. #else
  183811. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  183812. #endif
  183813. if (info_ptr != NULL)
  183814. png_info_init_3(&info_ptr, png_sizeof(png_info));
  183815. return (info_ptr);
  183816. }
  183817. /* This function frees the memory associated with a single info struct.
  183818. * Normally, one would use either png_destroy_read_struct() or
  183819. * png_destroy_write_struct() to free an info struct, but this may be
  183820. * useful for some applications.
  183821. */
  183822. void PNGAPI
  183823. png_destroy_info_struct(png_structp png_ptr, png_infopp info_ptr_ptr)
  183824. {
  183825. png_infop info_ptr = NULL;
  183826. if(png_ptr == NULL) return;
  183827. png_debug(1, "in png_destroy_info_struct\n");
  183828. if (info_ptr_ptr != NULL)
  183829. info_ptr = *info_ptr_ptr;
  183830. if (info_ptr != NULL)
  183831. {
  183832. png_info_destroy(png_ptr, info_ptr);
  183833. #ifdef PNG_USER_MEM_SUPPORTED
  183834. png_destroy_struct_2((png_voidp)info_ptr, png_ptr->free_fn,
  183835. png_ptr->mem_ptr);
  183836. #else
  183837. png_destroy_struct((png_voidp)info_ptr);
  183838. #endif
  183839. *info_ptr_ptr = NULL;
  183840. }
  183841. }
  183842. /* Initialize the info structure. This is now an internal function (0.89)
  183843. * and applications using it are urged to use png_create_info_struct()
  183844. * instead.
  183845. */
  183846. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  183847. #undef png_info_init
  183848. void PNGAPI
  183849. png_info_init(png_infop info_ptr)
  183850. {
  183851. /* We only come here via pre-1.0.12-compiled applications */
  183852. png_info_init_3(&info_ptr, 0);
  183853. }
  183854. #endif
  183855. void PNGAPI
  183856. png_info_init_3(png_infopp ptr_ptr, png_size_t png_info_struct_size)
  183857. {
  183858. png_infop info_ptr = *ptr_ptr;
  183859. if(info_ptr == NULL) return;
  183860. png_debug(1, "in png_info_init_3\n");
  183861. if(png_sizeof(png_info) > png_info_struct_size)
  183862. {
  183863. png_destroy_struct(info_ptr);
  183864. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  183865. *ptr_ptr = info_ptr;
  183866. }
  183867. /* set everything to 0 */
  183868. png_memset(info_ptr, 0, png_sizeof (png_info));
  183869. }
  183870. #ifdef PNG_FREE_ME_SUPPORTED
  183871. void PNGAPI
  183872. png_data_freer(png_structp png_ptr, png_infop info_ptr,
  183873. int freer, png_uint_32 mask)
  183874. {
  183875. png_debug(1, "in png_data_freer\n");
  183876. if (png_ptr == NULL || info_ptr == NULL)
  183877. return;
  183878. if(freer == PNG_DESTROY_WILL_FREE_DATA)
  183879. info_ptr->free_me |= mask;
  183880. else if(freer == PNG_USER_WILL_FREE_DATA)
  183881. info_ptr->free_me &= ~mask;
  183882. else
  183883. png_warning(png_ptr,
  183884. "Unknown freer parameter in png_data_freer.");
  183885. }
  183886. #endif
  183887. void PNGAPI
  183888. png_free_data(png_structp png_ptr, png_infop info_ptr, png_uint_32 mask,
  183889. int num)
  183890. {
  183891. png_debug(1, "in png_free_data\n");
  183892. if (png_ptr == NULL || info_ptr == NULL)
  183893. return;
  183894. #if defined(PNG_TEXT_SUPPORTED)
  183895. /* free text item num or (if num == -1) all text items */
  183896. #ifdef PNG_FREE_ME_SUPPORTED
  183897. if ((mask & PNG_FREE_TEXT) & info_ptr->free_me)
  183898. #else
  183899. if (mask & PNG_FREE_TEXT)
  183900. #endif
  183901. {
  183902. if (num != -1)
  183903. {
  183904. if (info_ptr->text && info_ptr->text[num].key)
  183905. {
  183906. png_free(png_ptr, info_ptr->text[num].key);
  183907. info_ptr->text[num].key = NULL;
  183908. }
  183909. }
  183910. else
  183911. {
  183912. int i;
  183913. for (i = 0; i < info_ptr->num_text; i++)
  183914. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, i);
  183915. png_free(png_ptr, info_ptr->text);
  183916. info_ptr->text = NULL;
  183917. info_ptr->num_text=0;
  183918. }
  183919. }
  183920. #endif
  183921. #if defined(PNG_tRNS_SUPPORTED)
  183922. /* free any tRNS entry */
  183923. #ifdef PNG_FREE_ME_SUPPORTED
  183924. if ((mask & PNG_FREE_TRNS) & info_ptr->free_me)
  183925. #else
  183926. if ((mask & PNG_FREE_TRNS) && (png_ptr->flags & PNG_FLAG_FREE_TRNS))
  183927. #endif
  183928. {
  183929. png_free(png_ptr, info_ptr->trans);
  183930. info_ptr->valid &= ~PNG_INFO_tRNS;
  183931. #ifndef PNG_FREE_ME_SUPPORTED
  183932. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  183933. #endif
  183934. info_ptr->trans = NULL;
  183935. }
  183936. #endif
  183937. #if defined(PNG_sCAL_SUPPORTED)
  183938. /* free any sCAL entry */
  183939. #ifdef PNG_FREE_ME_SUPPORTED
  183940. if ((mask & PNG_FREE_SCAL) & info_ptr->free_me)
  183941. #else
  183942. if (mask & PNG_FREE_SCAL)
  183943. #endif
  183944. {
  183945. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  183946. png_free(png_ptr, info_ptr->scal_s_width);
  183947. png_free(png_ptr, info_ptr->scal_s_height);
  183948. info_ptr->scal_s_width = NULL;
  183949. info_ptr->scal_s_height = NULL;
  183950. #endif
  183951. info_ptr->valid &= ~PNG_INFO_sCAL;
  183952. }
  183953. #endif
  183954. #if defined(PNG_pCAL_SUPPORTED)
  183955. /* free any pCAL entry */
  183956. #ifdef PNG_FREE_ME_SUPPORTED
  183957. if ((mask & PNG_FREE_PCAL) & info_ptr->free_me)
  183958. #else
  183959. if (mask & PNG_FREE_PCAL)
  183960. #endif
  183961. {
  183962. png_free(png_ptr, info_ptr->pcal_purpose);
  183963. png_free(png_ptr, info_ptr->pcal_units);
  183964. info_ptr->pcal_purpose = NULL;
  183965. info_ptr->pcal_units = NULL;
  183966. if (info_ptr->pcal_params != NULL)
  183967. {
  183968. int i;
  183969. for (i = 0; i < (int)info_ptr->pcal_nparams; i++)
  183970. {
  183971. png_free(png_ptr, info_ptr->pcal_params[i]);
  183972. info_ptr->pcal_params[i]=NULL;
  183973. }
  183974. png_free(png_ptr, info_ptr->pcal_params);
  183975. info_ptr->pcal_params = NULL;
  183976. }
  183977. info_ptr->valid &= ~PNG_INFO_pCAL;
  183978. }
  183979. #endif
  183980. #if defined(PNG_iCCP_SUPPORTED)
  183981. /* free any iCCP entry */
  183982. #ifdef PNG_FREE_ME_SUPPORTED
  183983. if ((mask & PNG_FREE_ICCP) & info_ptr->free_me)
  183984. #else
  183985. if (mask & PNG_FREE_ICCP)
  183986. #endif
  183987. {
  183988. png_free(png_ptr, info_ptr->iccp_name);
  183989. png_free(png_ptr, info_ptr->iccp_profile);
  183990. info_ptr->iccp_name = NULL;
  183991. info_ptr->iccp_profile = NULL;
  183992. info_ptr->valid &= ~PNG_INFO_iCCP;
  183993. }
  183994. #endif
  183995. #if defined(PNG_sPLT_SUPPORTED)
  183996. /* free a given sPLT entry, or (if num == -1) all sPLT entries */
  183997. #ifdef PNG_FREE_ME_SUPPORTED
  183998. if ((mask & PNG_FREE_SPLT) & info_ptr->free_me)
  183999. #else
  184000. if (mask & PNG_FREE_SPLT)
  184001. #endif
  184002. {
  184003. if (num != -1)
  184004. {
  184005. if(info_ptr->splt_palettes)
  184006. {
  184007. png_free(png_ptr, info_ptr->splt_palettes[num].name);
  184008. png_free(png_ptr, info_ptr->splt_palettes[num].entries);
  184009. info_ptr->splt_palettes[num].name = NULL;
  184010. info_ptr->splt_palettes[num].entries = NULL;
  184011. }
  184012. }
  184013. else
  184014. {
  184015. if(info_ptr->splt_palettes_num)
  184016. {
  184017. int i;
  184018. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  184019. png_free_data(png_ptr, info_ptr, PNG_FREE_SPLT, i);
  184020. png_free(png_ptr, info_ptr->splt_palettes);
  184021. info_ptr->splt_palettes = NULL;
  184022. info_ptr->splt_palettes_num = 0;
  184023. }
  184024. info_ptr->valid &= ~PNG_INFO_sPLT;
  184025. }
  184026. }
  184027. #endif
  184028. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  184029. if(png_ptr->unknown_chunk.data)
  184030. {
  184031. png_free(png_ptr, png_ptr->unknown_chunk.data);
  184032. png_ptr->unknown_chunk.data = NULL;
  184033. }
  184034. #ifdef PNG_FREE_ME_SUPPORTED
  184035. if ((mask & PNG_FREE_UNKN) & info_ptr->free_me)
  184036. #else
  184037. if (mask & PNG_FREE_UNKN)
  184038. #endif
  184039. {
  184040. if (num != -1)
  184041. {
  184042. if(info_ptr->unknown_chunks)
  184043. {
  184044. png_free(png_ptr, info_ptr->unknown_chunks[num].data);
  184045. info_ptr->unknown_chunks[num].data = NULL;
  184046. }
  184047. }
  184048. else
  184049. {
  184050. int i;
  184051. if(info_ptr->unknown_chunks_num)
  184052. {
  184053. for (i = 0; i < (int)info_ptr->unknown_chunks_num; i++)
  184054. png_free_data(png_ptr, info_ptr, PNG_FREE_UNKN, i);
  184055. png_free(png_ptr, info_ptr->unknown_chunks);
  184056. info_ptr->unknown_chunks = NULL;
  184057. info_ptr->unknown_chunks_num = 0;
  184058. }
  184059. }
  184060. }
  184061. #endif
  184062. #if defined(PNG_hIST_SUPPORTED)
  184063. /* free any hIST entry */
  184064. #ifdef PNG_FREE_ME_SUPPORTED
  184065. if ((mask & PNG_FREE_HIST) & info_ptr->free_me)
  184066. #else
  184067. if ((mask & PNG_FREE_HIST) && (png_ptr->flags & PNG_FLAG_FREE_HIST))
  184068. #endif
  184069. {
  184070. png_free(png_ptr, info_ptr->hist);
  184071. info_ptr->hist = NULL;
  184072. info_ptr->valid &= ~PNG_INFO_hIST;
  184073. #ifndef PNG_FREE_ME_SUPPORTED
  184074. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  184075. #endif
  184076. }
  184077. #endif
  184078. /* free any PLTE entry that was internally allocated */
  184079. #ifdef PNG_FREE_ME_SUPPORTED
  184080. if ((mask & PNG_FREE_PLTE) & info_ptr->free_me)
  184081. #else
  184082. if ((mask & PNG_FREE_PLTE) && (png_ptr->flags & PNG_FLAG_FREE_PLTE))
  184083. #endif
  184084. {
  184085. png_zfree(png_ptr, info_ptr->palette);
  184086. info_ptr->palette = NULL;
  184087. info_ptr->valid &= ~PNG_INFO_PLTE;
  184088. #ifndef PNG_FREE_ME_SUPPORTED
  184089. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  184090. #endif
  184091. info_ptr->num_palette = 0;
  184092. }
  184093. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  184094. /* free any image bits attached to the info structure */
  184095. #ifdef PNG_FREE_ME_SUPPORTED
  184096. if ((mask & PNG_FREE_ROWS) & info_ptr->free_me)
  184097. #else
  184098. if (mask & PNG_FREE_ROWS)
  184099. #endif
  184100. {
  184101. if(info_ptr->row_pointers)
  184102. {
  184103. int row;
  184104. for (row = 0; row < (int)info_ptr->height; row++)
  184105. {
  184106. png_free(png_ptr, info_ptr->row_pointers[row]);
  184107. info_ptr->row_pointers[row]=NULL;
  184108. }
  184109. png_free(png_ptr, info_ptr->row_pointers);
  184110. info_ptr->row_pointers=NULL;
  184111. }
  184112. info_ptr->valid &= ~PNG_INFO_IDAT;
  184113. }
  184114. #endif
  184115. #ifdef PNG_FREE_ME_SUPPORTED
  184116. if(num == -1)
  184117. info_ptr->free_me &= ~mask;
  184118. else
  184119. info_ptr->free_me &= ~(mask & ~PNG_FREE_MUL);
  184120. #endif
  184121. }
  184122. /* This is an internal routine to free any memory that the info struct is
  184123. * pointing to before re-using it or freeing the struct itself. Recall
  184124. * that png_free() checks for NULL pointers for us.
  184125. */
  184126. void /* PRIVATE */
  184127. png_info_destroy(png_structp png_ptr, png_infop info_ptr)
  184128. {
  184129. png_debug(1, "in png_info_destroy\n");
  184130. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  184131. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  184132. if (png_ptr->num_chunk_list)
  184133. {
  184134. png_free(png_ptr, png_ptr->chunk_list);
  184135. png_ptr->chunk_list=NULL;
  184136. png_ptr->num_chunk_list=0;
  184137. }
  184138. #endif
  184139. png_info_init_3(&info_ptr, png_sizeof(png_info));
  184140. }
  184141. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  184142. /* This function returns a pointer to the io_ptr associated with the user
  184143. * functions. The application should free any memory associated with this
  184144. * pointer before png_write_destroy() or png_read_destroy() are called.
  184145. */
  184146. png_voidp PNGAPI
  184147. png_get_io_ptr(png_structp png_ptr)
  184148. {
  184149. if(png_ptr == NULL) return (NULL);
  184150. return (png_ptr->io_ptr);
  184151. }
  184152. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184153. #if !defined(PNG_NO_STDIO)
  184154. /* Initialize the default input/output functions for the PNG file. If you
  184155. * use your own read or write routines, you can call either png_set_read_fn()
  184156. * or png_set_write_fn() instead of png_init_io(). If you have defined
  184157. * PNG_NO_STDIO, you must use a function of your own because "FILE *" isn't
  184158. * necessarily available.
  184159. */
  184160. void PNGAPI
  184161. png_init_io(png_structp png_ptr, png_FILE_p fp)
  184162. {
  184163. png_debug(1, "in png_init_io\n");
  184164. if(png_ptr == NULL) return;
  184165. png_ptr->io_ptr = (png_voidp)fp;
  184166. }
  184167. #endif
  184168. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  184169. /* Convert the supplied time into an RFC 1123 string suitable for use in
  184170. * a "Creation Time" or other text-based time string.
  184171. */
  184172. png_charp PNGAPI
  184173. png_convert_to_rfc1123(png_structp png_ptr, png_timep ptime)
  184174. {
  184175. static PNG_CONST char short_months[12][4] =
  184176. {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
  184177. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
  184178. if(png_ptr == NULL) return (NULL);
  184179. if (png_ptr->time_buffer == NULL)
  184180. {
  184181. png_ptr->time_buffer = (png_charp)png_malloc(png_ptr, (png_uint_32)(29*
  184182. png_sizeof(char)));
  184183. }
  184184. #if defined(_WIN32_WCE)
  184185. {
  184186. wchar_t time_buf[29];
  184187. wsprintf(time_buf, TEXT("%d %S %d %02d:%02d:%02d +0000"),
  184188. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  184189. ptime->year, ptime->hour % 24, ptime->minute % 60,
  184190. ptime->second % 61);
  184191. WideCharToMultiByte(CP_ACP, 0, time_buf, -1, png_ptr->time_buffer, 29,
  184192. NULL, NULL);
  184193. }
  184194. #else
  184195. #ifdef USE_FAR_KEYWORD
  184196. {
  184197. char near_time_buf[29];
  184198. png_snprintf6(near_time_buf,29,"%d %s %d %02d:%02d:%02d +0000",
  184199. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  184200. ptime->year, ptime->hour % 24, ptime->minute % 60,
  184201. ptime->second % 61);
  184202. png_memcpy(png_ptr->time_buffer, near_time_buf,
  184203. 29*png_sizeof(char));
  184204. }
  184205. #else
  184206. png_snprintf6(png_ptr->time_buffer,29,"%d %s %d %02d:%02d:%02d +0000",
  184207. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  184208. ptime->year, ptime->hour % 24, ptime->minute % 60,
  184209. ptime->second % 61);
  184210. #endif
  184211. #endif /* _WIN32_WCE */
  184212. return ((png_charp)png_ptr->time_buffer);
  184213. }
  184214. #endif /* PNG_TIME_RFC1123_SUPPORTED */
  184215. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  184216. png_charp PNGAPI
  184217. png_get_copyright(png_structp png_ptr)
  184218. {
  184219. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  184220. return ((png_charp) "\n libpng version 1.2.21 - October 4, 2007\n\
  184221. Copyright (c) 1998-2007 Glenn Randers-Pehrson\n\
  184222. Copyright (c) 1996-1997 Andreas Dilger\n\
  184223. Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.\n");
  184224. }
  184225. /* The following return the library version as a short string in the
  184226. * format 1.0.0 through 99.99.99zz. To get the version of *.h files
  184227. * used with your application, print out PNG_LIBPNG_VER_STRING, which
  184228. * is defined in png.h.
  184229. * Note: now there is no difference between png_get_libpng_ver() and
  184230. * png_get_header_ver(). Due to the version_nn_nn_nn typedef guard,
  184231. * it is guaranteed that png.c uses the correct version of png.h.
  184232. */
  184233. png_charp PNGAPI
  184234. png_get_libpng_ver(png_structp png_ptr)
  184235. {
  184236. /* Version of *.c files used when building libpng */
  184237. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  184238. return ((png_charp) PNG_LIBPNG_VER_STRING);
  184239. }
  184240. png_charp PNGAPI
  184241. png_get_header_ver(png_structp png_ptr)
  184242. {
  184243. /* Version of *.h files used when building libpng */
  184244. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  184245. return ((png_charp) PNG_LIBPNG_VER_STRING);
  184246. }
  184247. png_charp PNGAPI
  184248. png_get_header_version(png_structp png_ptr)
  184249. {
  184250. /* Returns longer string containing both version and date */
  184251. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  184252. return ((png_charp) PNG_HEADER_VERSION_STRING
  184253. #ifndef PNG_READ_SUPPORTED
  184254. " (NO READ SUPPORT)"
  184255. #endif
  184256. "\n");
  184257. }
  184258. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184259. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  184260. int PNGAPI
  184261. png_handle_as_unknown(png_structp png_ptr, png_bytep chunk_name)
  184262. {
  184263. /* check chunk_name and return "keep" value if it's on the list, else 0 */
  184264. int i;
  184265. png_bytep p;
  184266. if(png_ptr == NULL || chunk_name == NULL || png_ptr->num_chunk_list<=0)
  184267. return 0;
  184268. p=png_ptr->chunk_list+png_ptr->num_chunk_list*5-5;
  184269. for (i = png_ptr->num_chunk_list; i; i--, p-=5)
  184270. if (!png_memcmp(chunk_name, p, 4))
  184271. return ((int)*(p+4));
  184272. return 0;
  184273. }
  184274. #endif
  184275. /* This function, added to libpng-1.0.6g, is untested. */
  184276. int PNGAPI
  184277. png_reset_zstream(png_structp png_ptr)
  184278. {
  184279. if (png_ptr == NULL) return Z_STREAM_ERROR;
  184280. return (inflateReset(&png_ptr->zstream));
  184281. }
  184282. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  184283. /* This function was added to libpng-1.0.7 */
  184284. png_uint_32 PNGAPI
  184285. png_access_version_number(void)
  184286. {
  184287. /* Version of *.c files used when building libpng */
  184288. return((png_uint_32) PNG_LIBPNG_VER);
  184289. }
  184290. #if defined(PNG_READ_SUPPORTED) && defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  184291. #if !defined(PNG_1_0_X)
  184292. /* this function was added to libpng 1.2.0 */
  184293. int PNGAPI
  184294. png_mmx_support(void)
  184295. {
  184296. /* obsolete, to be removed from libpng-1.4.0 */
  184297. return -1;
  184298. }
  184299. #endif /* PNG_1_0_X */
  184300. #endif /* PNG_READ_SUPPORTED && PNG_ASSEMBLER_CODE_SUPPORTED */
  184301. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184302. #ifdef PNG_SIZE_T
  184303. /* Added at libpng version 1.2.6 */
  184304. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  184305. png_size_t PNGAPI
  184306. png_convert_size(size_t size)
  184307. {
  184308. if (size > (png_size_t)-1)
  184309. PNG_ABORT(); /* We haven't got access to png_ptr, so no png_error() */
  184310. return ((png_size_t)size);
  184311. }
  184312. #endif /* PNG_SIZE_T */
  184313. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  184314. /*** End of inlined file: png.c ***/
  184315. /*** Start of inlined file: pngerror.c ***/
  184316. /* pngerror.c - stub functions for i/o and memory allocation
  184317. *
  184318. * Last changed in libpng 1.2.20 October 4, 2007
  184319. * For conditions of distribution and use, see copyright notice in png.h
  184320. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  184321. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  184322. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  184323. *
  184324. * This file provides a location for all error handling. Users who
  184325. * need special error handling are expected to write replacement functions
  184326. * and use png_set_error_fn() to use those functions. See the instructions
  184327. * at each function.
  184328. */
  184329. #define PNG_INTERNAL
  184330. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184331. static void /* PRIVATE */
  184332. png_default_error PNGARG((png_structp png_ptr,
  184333. png_const_charp error_message));
  184334. #ifndef PNG_NO_WARNINGS
  184335. static void /* PRIVATE */
  184336. png_default_warning PNGARG((png_structp png_ptr,
  184337. png_const_charp warning_message));
  184338. #endif /* PNG_NO_WARNINGS */
  184339. /* This function is called whenever there is a fatal error. This function
  184340. * should not be changed. If there is a need to handle errors differently,
  184341. * you should supply a replacement error function and use png_set_error_fn()
  184342. * to replace the error function at run-time.
  184343. */
  184344. #ifndef PNG_NO_ERROR_TEXT
  184345. void PNGAPI
  184346. png_error(png_structp png_ptr, png_const_charp error_message)
  184347. {
  184348. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  184349. char msg[16];
  184350. if (png_ptr != NULL)
  184351. {
  184352. if (png_ptr->flags&
  184353. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  184354. {
  184355. if (*error_message == '#')
  184356. {
  184357. int offset;
  184358. for (offset=1; offset<15; offset++)
  184359. if (*(error_message+offset) == ' ')
  184360. break;
  184361. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  184362. {
  184363. int i;
  184364. for (i=0; i<offset-1; i++)
  184365. msg[i]=error_message[i+1];
  184366. msg[i]='\0';
  184367. error_message=msg;
  184368. }
  184369. else
  184370. error_message+=offset;
  184371. }
  184372. else
  184373. {
  184374. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  184375. {
  184376. msg[0]='0';
  184377. msg[1]='\0';
  184378. error_message=msg;
  184379. }
  184380. }
  184381. }
  184382. }
  184383. #endif
  184384. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  184385. (*(png_ptr->error_fn))(png_ptr, error_message);
  184386. /* If the custom handler doesn't exist, or if it returns,
  184387. use the default handler, which will not return. */
  184388. png_default_error(png_ptr, error_message);
  184389. }
  184390. #else
  184391. void PNGAPI
  184392. png_err(png_structp png_ptr)
  184393. {
  184394. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  184395. (*(png_ptr->error_fn))(png_ptr, '\0');
  184396. /* If the custom handler doesn't exist, or if it returns,
  184397. use the default handler, which will not return. */
  184398. png_default_error(png_ptr, '\0');
  184399. }
  184400. #endif /* PNG_NO_ERROR_TEXT */
  184401. #ifndef PNG_NO_WARNINGS
  184402. /* This function is called whenever there is a non-fatal error. This function
  184403. * should not be changed. If there is a need to handle warnings differently,
  184404. * you should supply a replacement warning function and use
  184405. * png_set_error_fn() to replace the warning function at run-time.
  184406. */
  184407. void PNGAPI
  184408. png_warning(png_structp png_ptr, png_const_charp warning_message)
  184409. {
  184410. int offset = 0;
  184411. if (png_ptr != NULL)
  184412. {
  184413. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  184414. if (png_ptr->flags&
  184415. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  184416. #endif
  184417. {
  184418. if (*warning_message == '#')
  184419. {
  184420. for (offset=1; offset<15; offset++)
  184421. if (*(warning_message+offset) == ' ')
  184422. break;
  184423. }
  184424. }
  184425. if (png_ptr != NULL && png_ptr->warning_fn != NULL)
  184426. (*(png_ptr->warning_fn))(png_ptr, warning_message+offset);
  184427. }
  184428. else
  184429. png_default_warning(png_ptr, warning_message+offset);
  184430. }
  184431. #endif /* PNG_NO_WARNINGS */
  184432. /* These utilities are used internally to build an error message that relates
  184433. * to the current chunk. The chunk name comes from png_ptr->chunk_name,
  184434. * this is used to prefix the message. The message is limited in length
  184435. * to 63 bytes, the name characters are output as hex digits wrapped in []
  184436. * if the character is invalid.
  184437. */
  184438. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  184439. /*static PNG_CONST char png_digit[16] = {
  184440. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  184441. 'A', 'B', 'C', 'D', 'E', 'F'
  184442. };*/
  184443. #if !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT)
  184444. static void /* PRIVATE */
  184445. png_format_buffer(png_structp png_ptr, png_charp buffer, png_const_charp
  184446. error_message)
  184447. {
  184448. int iout = 0, iin = 0;
  184449. while (iin < 4)
  184450. {
  184451. int c = png_ptr->chunk_name[iin++];
  184452. if (isnonalpha(c))
  184453. {
  184454. buffer[iout++] = '[';
  184455. buffer[iout++] = png_digit[(c & 0xf0) >> 4];
  184456. buffer[iout++] = png_digit[c & 0x0f];
  184457. buffer[iout++] = ']';
  184458. }
  184459. else
  184460. {
  184461. buffer[iout++] = (png_byte)c;
  184462. }
  184463. }
  184464. if (error_message == NULL)
  184465. buffer[iout] = 0;
  184466. else
  184467. {
  184468. buffer[iout++] = ':';
  184469. buffer[iout++] = ' ';
  184470. png_strncpy(buffer+iout, error_message, 63);
  184471. buffer[iout+63] = 0;
  184472. }
  184473. }
  184474. #ifdef PNG_READ_SUPPORTED
  184475. void PNGAPI
  184476. png_chunk_error(png_structp png_ptr, png_const_charp error_message)
  184477. {
  184478. char msg[18+64];
  184479. if (png_ptr == NULL)
  184480. png_error(png_ptr, error_message);
  184481. else
  184482. {
  184483. png_format_buffer(png_ptr, msg, error_message);
  184484. png_error(png_ptr, msg);
  184485. }
  184486. }
  184487. #endif /* PNG_READ_SUPPORTED */
  184488. #endif /* !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT) */
  184489. #ifndef PNG_NO_WARNINGS
  184490. void PNGAPI
  184491. png_chunk_warning(png_structp png_ptr, png_const_charp warning_message)
  184492. {
  184493. char msg[18+64];
  184494. if (png_ptr == NULL)
  184495. png_warning(png_ptr, warning_message);
  184496. else
  184497. {
  184498. png_format_buffer(png_ptr, msg, warning_message);
  184499. png_warning(png_ptr, msg);
  184500. }
  184501. }
  184502. #endif /* PNG_NO_WARNINGS */
  184503. /* This is the default error handling function. Note that replacements for
  184504. * this function MUST NOT RETURN, or the program will likely crash. This
  184505. * function is used by default, or if the program supplies NULL for the
  184506. * error function pointer in png_set_error_fn().
  184507. */
  184508. static void /* PRIVATE */
  184509. png_default_error(png_structp, png_const_charp error_message)
  184510. {
  184511. #ifndef PNG_NO_CONSOLE_IO
  184512. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  184513. if (*error_message == '#')
  184514. {
  184515. int offset;
  184516. char error_number[16];
  184517. for (offset=0; offset<15; offset++)
  184518. {
  184519. error_number[offset] = *(error_message+offset+1);
  184520. if (*(error_message+offset) == ' ')
  184521. break;
  184522. }
  184523. if((offset > 1) && (offset < 15))
  184524. {
  184525. error_number[offset-1]='\0';
  184526. fprintf(stderr, "libpng error no. %s: %s\n", error_number,
  184527. error_message+offset);
  184528. }
  184529. else
  184530. fprintf(stderr, "libpng error: %s, offset=%d\n", error_message,offset);
  184531. }
  184532. else
  184533. #endif
  184534. fprintf(stderr, "libpng error: %s\n", error_message);
  184535. #endif
  184536. #ifdef PNG_SETJMP_SUPPORTED
  184537. if (png_ptr)
  184538. {
  184539. # ifdef USE_FAR_KEYWORD
  184540. {
  184541. jmp_buf jmpbuf;
  184542. png_memcpy(jmpbuf, png_ptr->jmpbuf, png_sizeof(jmp_buf));
  184543. longjmp(jmpbuf, 1);
  184544. }
  184545. # else
  184546. longjmp(png_ptr->jmpbuf, 1);
  184547. # endif
  184548. }
  184549. #else
  184550. PNG_ABORT();
  184551. #endif
  184552. #ifdef PNG_NO_CONSOLE_IO
  184553. error_message = error_message; /* make compiler happy */
  184554. #endif
  184555. }
  184556. #ifndef PNG_NO_WARNINGS
  184557. /* This function is called when there is a warning, but the library thinks
  184558. * it can continue anyway. Replacement functions don't have to do anything
  184559. * here if you don't want them to. In the default configuration, png_ptr is
  184560. * not used, but it is passed in case it may be useful.
  184561. */
  184562. static void /* PRIVATE */
  184563. png_default_warning(png_structp png_ptr, png_const_charp warning_message)
  184564. {
  184565. #ifndef PNG_NO_CONSOLE_IO
  184566. # ifdef PNG_ERROR_NUMBERS_SUPPORTED
  184567. if (*warning_message == '#')
  184568. {
  184569. int offset;
  184570. char warning_number[16];
  184571. for (offset=0; offset<15; offset++)
  184572. {
  184573. warning_number[offset]=*(warning_message+offset+1);
  184574. if (*(warning_message+offset) == ' ')
  184575. break;
  184576. }
  184577. if((offset > 1) && (offset < 15))
  184578. {
  184579. warning_number[offset-1]='\0';
  184580. fprintf(stderr, "libpng warning no. %s: %s\n", warning_number,
  184581. warning_message+offset);
  184582. }
  184583. else
  184584. fprintf(stderr, "libpng warning: %s\n", warning_message);
  184585. }
  184586. else
  184587. # endif
  184588. fprintf(stderr, "libpng warning: %s\n", warning_message);
  184589. #else
  184590. warning_message = warning_message; /* make compiler happy */
  184591. #endif
  184592. png_ptr = png_ptr; /* make compiler happy */
  184593. }
  184594. #endif /* PNG_NO_WARNINGS */
  184595. /* This function is called when the application wants to use another method
  184596. * of handling errors and warnings. Note that the error function MUST NOT
  184597. * return to the calling routine or serious problems will occur. The return
  184598. * method used in the default routine calls longjmp(png_ptr->jmpbuf, 1)
  184599. */
  184600. void PNGAPI
  184601. png_set_error_fn(png_structp png_ptr, png_voidp error_ptr,
  184602. png_error_ptr error_fn, png_error_ptr warning_fn)
  184603. {
  184604. if (png_ptr == NULL)
  184605. return;
  184606. png_ptr->error_ptr = error_ptr;
  184607. png_ptr->error_fn = error_fn;
  184608. png_ptr->warning_fn = warning_fn;
  184609. }
  184610. /* This function returns a pointer to the error_ptr associated with the user
  184611. * functions. The application should free any memory associated with this
  184612. * pointer before png_write_destroy and png_read_destroy are called.
  184613. */
  184614. png_voidp PNGAPI
  184615. png_get_error_ptr(png_structp png_ptr)
  184616. {
  184617. if (png_ptr == NULL)
  184618. return NULL;
  184619. return ((png_voidp)png_ptr->error_ptr);
  184620. }
  184621. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  184622. void PNGAPI
  184623. png_set_strip_error_numbers(png_structp png_ptr, png_uint_32 strip_mode)
  184624. {
  184625. if(png_ptr != NULL)
  184626. {
  184627. png_ptr->flags &=
  184628. ((~(PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))&strip_mode);
  184629. }
  184630. }
  184631. #endif
  184632. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  184633. /*** End of inlined file: pngerror.c ***/
  184634. /*** Start of inlined file: pngget.c ***/
  184635. /* pngget.c - retrieval of values from info struct
  184636. *
  184637. * Last changed in libpng 1.2.15 January 5, 2007
  184638. * For conditions of distribution and use, see copyright notice in png.h
  184639. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  184640. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  184641. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  184642. */
  184643. #define PNG_INTERNAL
  184644. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184645. png_uint_32 PNGAPI
  184646. png_get_valid(png_structp png_ptr, png_infop info_ptr, png_uint_32 flag)
  184647. {
  184648. if (png_ptr != NULL && info_ptr != NULL)
  184649. return(info_ptr->valid & flag);
  184650. else
  184651. return(0);
  184652. }
  184653. png_uint_32 PNGAPI
  184654. png_get_rowbytes(png_structp png_ptr, png_infop info_ptr)
  184655. {
  184656. if (png_ptr != NULL && info_ptr != NULL)
  184657. return(info_ptr->rowbytes);
  184658. else
  184659. return(0);
  184660. }
  184661. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  184662. png_bytepp PNGAPI
  184663. png_get_rows(png_structp png_ptr, png_infop info_ptr)
  184664. {
  184665. if (png_ptr != NULL && info_ptr != NULL)
  184666. return(info_ptr->row_pointers);
  184667. else
  184668. return(0);
  184669. }
  184670. #endif
  184671. #ifdef PNG_EASY_ACCESS_SUPPORTED
  184672. /* easy access to info, added in libpng-0.99 */
  184673. png_uint_32 PNGAPI
  184674. png_get_image_width(png_structp png_ptr, png_infop info_ptr)
  184675. {
  184676. if (png_ptr != NULL && info_ptr != NULL)
  184677. {
  184678. return info_ptr->width;
  184679. }
  184680. return (0);
  184681. }
  184682. png_uint_32 PNGAPI
  184683. png_get_image_height(png_structp png_ptr, png_infop info_ptr)
  184684. {
  184685. if (png_ptr != NULL && info_ptr != NULL)
  184686. {
  184687. return info_ptr->height;
  184688. }
  184689. return (0);
  184690. }
  184691. png_byte PNGAPI
  184692. png_get_bit_depth(png_structp png_ptr, png_infop info_ptr)
  184693. {
  184694. if (png_ptr != NULL && info_ptr != NULL)
  184695. {
  184696. return info_ptr->bit_depth;
  184697. }
  184698. return (0);
  184699. }
  184700. png_byte PNGAPI
  184701. png_get_color_type(png_structp png_ptr, png_infop info_ptr)
  184702. {
  184703. if (png_ptr != NULL && info_ptr != NULL)
  184704. {
  184705. return info_ptr->color_type;
  184706. }
  184707. return (0);
  184708. }
  184709. png_byte PNGAPI
  184710. png_get_filter_type(png_structp png_ptr, png_infop info_ptr)
  184711. {
  184712. if (png_ptr != NULL && info_ptr != NULL)
  184713. {
  184714. return info_ptr->filter_type;
  184715. }
  184716. return (0);
  184717. }
  184718. png_byte PNGAPI
  184719. png_get_interlace_type(png_structp png_ptr, png_infop info_ptr)
  184720. {
  184721. if (png_ptr != NULL && info_ptr != NULL)
  184722. {
  184723. return info_ptr->interlace_type;
  184724. }
  184725. return (0);
  184726. }
  184727. png_byte PNGAPI
  184728. png_get_compression_type(png_structp png_ptr, png_infop info_ptr)
  184729. {
  184730. if (png_ptr != NULL && info_ptr != NULL)
  184731. {
  184732. return info_ptr->compression_type;
  184733. }
  184734. return (0);
  184735. }
  184736. png_uint_32 PNGAPI
  184737. png_get_x_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  184738. {
  184739. if (png_ptr != NULL && info_ptr != NULL)
  184740. #if defined(PNG_pHYs_SUPPORTED)
  184741. if (info_ptr->valid & PNG_INFO_pHYs)
  184742. {
  184743. png_debug1(1, "in %s retrieval function\n", "png_get_x_pixels_per_meter");
  184744. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  184745. return (0);
  184746. else return (info_ptr->x_pixels_per_unit);
  184747. }
  184748. #else
  184749. return (0);
  184750. #endif
  184751. return (0);
  184752. }
  184753. png_uint_32 PNGAPI
  184754. png_get_y_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  184755. {
  184756. if (png_ptr != NULL && info_ptr != NULL)
  184757. #if defined(PNG_pHYs_SUPPORTED)
  184758. if (info_ptr->valid & PNG_INFO_pHYs)
  184759. {
  184760. png_debug1(1, "in %s retrieval function\n", "png_get_y_pixels_per_meter");
  184761. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  184762. return (0);
  184763. else return (info_ptr->y_pixels_per_unit);
  184764. }
  184765. #else
  184766. return (0);
  184767. #endif
  184768. return (0);
  184769. }
  184770. png_uint_32 PNGAPI
  184771. png_get_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  184772. {
  184773. if (png_ptr != NULL && info_ptr != NULL)
  184774. #if defined(PNG_pHYs_SUPPORTED)
  184775. if (info_ptr->valid & PNG_INFO_pHYs)
  184776. {
  184777. png_debug1(1, "in %s retrieval function\n", "png_get_pixels_per_meter");
  184778. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER ||
  184779. info_ptr->x_pixels_per_unit != info_ptr->y_pixels_per_unit)
  184780. return (0);
  184781. else return (info_ptr->x_pixels_per_unit);
  184782. }
  184783. #else
  184784. return (0);
  184785. #endif
  184786. return (0);
  184787. }
  184788. #ifdef PNG_FLOATING_POINT_SUPPORTED
  184789. float PNGAPI
  184790. png_get_pixel_aspect_ratio(png_structp png_ptr, png_infop info_ptr)
  184791. {
  184792. if (png_ptr != NULL && info_ptr != NULL)
  184793. #if defined(PNG_pHYs_SUPPORTED)
  184794. if (info_ptr->valid & PNG_INFO_pHYs)
  184795. {
  184796. png_debug1(1, "in %s retrieval function\n", "png_get_aspect_ratio");
  184797. if (info_ptr->x_pixels_per_unit == 0)
  184798. return ((float)0.0);
  184799. else
  184800. return ((float)((float)info_ptr->y_pixels_per_unit
  184801. /(float)info_ptr->x_pixels_per_unit));
  184802. }
  184803. #else
  184804. return (0.0);
  184805. #endif
  184806. return ((float)0.0);
  184807. }
  184808. #endif
  184809. png_int_32 PNGAPI
  184810. png_get_x_offset_microns(png_structp png_ptr, png_infop info_ptr)
  184811. {
  184812. if (png_ptr != NULL && info_ptr != NULL)
  184813. #if defined(PNG_oFFs_SUPPORTED)
  184814. if (info_ptr->valid & PNG_INFO_oFFs)
  184815. {
  184816. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  184817. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  184818. return (0);
  184819. else return (info_ptr->x_offset);
  184820. }
  184821. #else
  184822. return (0);
  184823. #endif
  184824. return (0);
  184825. }
  184826. png_int_32 PNGAPI
  184827. png_get_y_offset_microns(png_structp png_ptr, png_infop info_ptr)
  184828. {
  184829. if (png_ptr != NULL && info_ptr != NULL)
  184830. #if defined(PNG_oFFs_SUPPORTED)
  184831. if (info_ptr->valid & PNG_INFO_oFFs)
  184832. {
  184833. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  184834. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  184835. return (0);
  184836. else return (info_ptr->y_offset);
  184837. }
  184838. #else
  184839. return (0);
  184840. #endif
  184841. return (0);
  184842. }
  184843. png_int_32 PNGAPI
  184844. png_get_x_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  184845. {
  184846. if (png_ptr != NULL && info_ptr != NULL)
  184847. #if defined(PNG_oFFs_SUPPORTED)
  184848. if (info_ptr->valid & PNG_INFO_oFFs)
  184849. {
  184850. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  184851. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  184852. return (0);
  184853. else return (info_ptr->x_offset);
  184854. }
  184855. #else
  184856. return (0);
  184857. #endif
  184858. return (0);
  184859. }
  184860. png_int_32 PNGAPI
  184861. png_get_y_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  184862. {
  184863. if (png_ptr != NULL && info_ptr != NULL)
  184864. #if defined(PNG_oFFs_SUPPORTED)
  184865. if (info_ptr->valid & PNG_INFO_oFFs)
  184866. {
  184867. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  184868. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  184869. return (0);
  184870. else return (info_ptr->y_offset);
  184871. }
  184872. #else
  184873. return (0);
  184874. #endif
  184875. return (0);
  184876. }
  184877. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  184878. png_uint_32 PNGAPI
  184879. png_get_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  184880. {
  184881. return ((png_uint_32)((float)png_get_pixels_per_meter(png_ptr, info_ptr)
  184882. *.0254 +.5));
  184883. }
  184884. png_uint_32 PNGAPI
  184885. png_get_x_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  184886. {
  184887. return ((png_uint_32)((float)png_get_x_pixels_per_meter(png_ptr, info_ptr)
  184888. *.0254 +.5));
  184889. }
  184890. png_uint_32 PNGAPI
  184891. png_get_y_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  184892. {
  184893. return ((png_uint_32)((float)png_get_y_pixels_per_meter(png_ptr, info_ptr)
  184894. *.0254 +.5));
  184895. }
  184896. float PNGAPI
  184897. png_get_x_offset_inches(png_structp png_ptr, png_infop info_ptr)
  184898. {
  184899. return ((float)png_get_x_offset_microns(png_ptr, info_ptr)
  184900. *.00003937);
  184901. }
  184902. float PNGAPI
  184903. png_get_y_offset_inches(png_structp png_ptr, png_infop info_ptr)
  184904. {
  184905. return ((float)png_get_y_offset_microns(png_ptr, info_ptr)
  184906. *.00003937);
  184907. }
  184908. #if defined(PNG_pHYs_SUPPORTED)
  184909. png_uint_32 PNGAPI
  184910. png_get_pHYs_dpi(png_structp png_ptr, png_infop info_ptr,
  184911. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  184912. {
  184913. png_uint_32 retval = 0;
  184914. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  184915. {
  184916. png_debug1(1, "in %s retrieval function\n", "pHYs");
  184917. if (res_x != NULL)
  184918. {
  184919. *res_x = info_ptr->x_pixels_per_unit;
  184920. retval |= PNG_INFO_pHYs;
  184921. }
  184922. if (res_y != NULL)
  184923. {
  184924. *res_y = info_ptr->y_pixels_per_unit;
  184925. retval |= PNG_INFO_pHYs;
  184926. }
  184927. if (unit_type != NULL)
  184928. {
  184929. *unit_type = (int)info_ptr->phys_unit_type;
  184930. retval |= PNG_INFO_pHYs;
  184931. if(*unit_type == 1)
  184932. {
  184933. if (res_x != NULL) *res_x = (png_uint_32)(*res_x * .0254 + .50);
  184934. if (res_y != NULL) *res_y = (png_uint_32)(*res_y * .0254 + .50);
  184935. }
  184936. }
  184937. }
  184938. return (retval);
  184939. }
  184940. #endif /* PNG_pHYs_SUPPORTED */
  184941. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  184942. /* png_get_channels really belongs in here, too, but it's been around longer */
  184943. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  184944. png_byte PNGAPI
  184945. png_get_channels(png_structp png_ptr, png_infop info_ptr)
  184946. {
  184947. if (png_ptr != NULL && info_ptr != NULL)
  184948. return(info_ptr->channels);
  184949. else
  184950. return (0);
  184951. }
  184952. png_bytep PNGAPI
  184953. png_get_signature(png_structp png_ptr, png_infop info_ptr)
  184954. {
  184955. if (png_ptr != NULL && info_ptr != NULL)
  184956. return(info_ptr->signature);
  184957. else
  184958. return (NULL);
  184959. }
  184960. #if defined(PNG_bKGD_SUPPORTED)
  184961. png_uint_32 PNGAPI
  184962. png_get_bKGD(png_structp png_ptr, png_infop info_ptr,
  184963. png_color_16p *background)
  184964. {
  184965. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD)
  184966. && background != NULL)
  184967. {
  184968. png_debug1(1, "in %s retrieval function\n", "bKGD");
  184969. *background = &(info_ptr->background);
  184970. return (PNG_INFO_bKGD);
  184971. }
  184972. return (0);
  184973. }
  184974. #endif
  184975. #if defined(PNG_cHRM_SUPPORTED)
  184976. #ifdef PNG_FLOATING_POINT_SUPPORTED
  184977. png_uint_32 PNGAPI
  184978. png_get_cHRM(png_structp png_ptr, png_infop info_ptr,
  184979. double *white_x, double *white_y, double *red_x, double *red_y,
  184980. double *green_x, double *green_y, double *blue_x, double *blue_y)
  184981. {
  184982. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  184983. {
  184984. png_debug1(1, "in %s retrieval function\n", "cHRM");
  184985. if (white_x != NULL)
  184986. *white_x = (double)info_ptr->x_white;
  184987. if (white_y != NULL)
  184988. *white_y = (double)info_ptr->y_white;
  184989. if (red_x != NULL)
  184990. *red_x = (double)info_ptr->x_red;
  184991. if (red_y != NULL)
  184992. *red_y = (double)info_ptr->y_red;
  184993. if (green_x != NULL)
  184994. *green_x = (double)info_ptr->x_green;
  184995. if (green_y != NULL)
  184996. *green_y = (double)info_ptr->y_green;
  184997. if (blue_x != NULL)
  184998. *blue_x = (double)info_ptr->x_blue;
  184999. if (blue_y != NULL)
  185000. *blue_y = (double)info_ptr->y_blue;
  185001. return (PNG_INFO_cHRM);
  185002. }
  185003. return (0);
  185004. }
  185005. #endif
  185006. #ifdef PNG_FIXED_POINT_SUPPORTED
  185007. png_uint_32 PNGAPI
  185008. png_get_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  185009. png_fixed_point *white_x, png_fixed_point *white_y, png_fixed_point *red_x,
  185010. png_fixed_point *red_y, png_fixed_point *green_x, png_fixed_point *green_y,
  185011. png_fixed_point *blue_x, png_fixed_point *blue_y)
  185012. {
  185013. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  185014. {
  185015. png_debug1(1, "in %s retrieval function\n", "cHRM");
  185016. if (white_x != NULL)
  185017. *white_x = info_ptr->int_x_white;
  185018. if (white_y != NULL)
  185019. *white_y = info_ptr->int_y_white;
  185020. if (red_x != NULL)
  185021. *red_x = info_ptr->int_x_red;
  185022. if (red_y != NULL)
  185023. *red_y = info_ptr->int_y_red;
  185024. if (green_x != NULL)
  185025. *green_x = info_ptr->int_x_green;
  185026. if (green_y != NULL)
  185027. *green_y = info_ptr->int_y_green;
  185028. if (blue_x != NULL)
  185029. *blue_x = info_ptr->int_x_blue;
  185030. if (blue_y != NULL)
  185031. *blue_y = info_ptr->int_y_blue;
  185032. return (PNG_INFO_cHRM);
  185033. }
  185034. return (0);
  185035. }
  185036. #endif
  185037. #endif
  185038. #if defined(PNG_gAMA_SUPPORTED)
  185039. #ifdef PNG_FLOATING_POINT_SUPPORTED
  185040. png_uint_32 PNGAPI
  185041. png_get_gAMA(png_structp png_ptr, png_infop info_ptr, double *file_gamma)
  185042. {
  185043. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  185044. && file_gamma != NULL)
  185045. {
  185046. png_debug1(1, "in %s retrieval function\n", "gAMA");
  185047. *file_gamma = (double)info_ptr->gamma;
  185048. return (PNG_INFO_gAMA);
  185049. }
  185050. return (0);
  185051. }
  185052. #endif
  185053. #ifdef PNG_FIXED_POINT_SUPPORTED
  185054. png_uint_32 PNGAPI
  185055. png_get_gAMA_fixed(png_structp png_ptr, png_infop info_ptr,
  185056. png_fixed_point *int_file_gamma)
  185057. {
  185058. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  185059. && int_file_gamma != NULL)
  185060. {
  185061. png_debug1(1, "in %s retrieval function\n", "gAMA");
  185062. *int_file_gamma = info_ptr->int_gamma;
  185063. return (PNG_INFO_gAMA);
  185064. }
  185065. return (0);
  185066. }
  185067. #endif
  185068. #endif
  185069. #if defined(PNG_sRGB_SUPPORTED)
  185070. png_uint_32 PNGAPI
  185071. png_get_sRGB(png_structp png_ptr, png_infop info_ptr, int *file_srgb_intent)
  185072. {
  185073. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB)
  185074. && file_srgb_intent != NULL)
  185075. {
  185076. png_debug1(1, "in %s retrieval function\n", "sRGB");
  185077. *file_srgb_intent = (int)info_ptr->srgb_intent;
  185078. return (PNG_INFO_sRGB);
  185079. }
  185080. return (0);
  185081. }
  185082. #endif
  185083. #if defined(PNG_iCCP_SUPPORTED)
  185084. png_uint_32 PNGAPI
  185085. png_get_iCCP(png_structp png_ptr, png_infop info_ptr,
  185086. png_charpp name, int *compression_type,
  185087. png_charpp profile, png_uint_32 *proflen)
  185088. {
  185089. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP)
  185090. && name != NULL && profile != NULL && proflen != NULL)
  185091. {
  185092. png_debug1(1, "in %s retrieval function\n", "iCCP");
  185093. *name = info_ptr->iccp_name;
  185094. *profile = info_ptr->iccp_profile;
  185095. /* compression_type is a dummy so the API won't have to change
  185096. if we introduce multiple compression types later. */
  185097. *proflen = (int)info_ptr->iccp_proflen;
  185098. *compression_type = (int)info_ptr->iccp_compression;
  185099. return (PNG_INFO_iCCP);
  185100. }
  185101. return (0);
  185102. }
  185103. #endif
  185104. #if defined(PNG_sPLT_SUPPORTED)
  185105. png_uint_32 PNGAPI
  185106. png_get_sPLT(png_structp png_ptr, png_infop info_ptr,
  185107. png_sPLT_tpp spalettes)
  185108. {
  185109. if (png_ptr != NULL && info_ptr != NULL && spalettes != NULL)
  185110. {
  185111. *spalettes = info_ptr->splt_palettes;
  185112. return ((png_uint_32)info_ptr->splt_palettes_num);
  185113. }
  185114. return (0);
  185115. }
  185116. #endif
  185117. #if defined(PNG_hIST_SUPPORTED)
  185118. png_uint_32 PNGAPI
  185119. png_get_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p *hist)
  185120. {
  185121. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST)
  185122. && hist != NULL)
  185123. {
  185124. png_debug1(1, "in %s retrieval function\n", "hIST");
  185125. *hist = info_ptr->hist;
  185126. return (PNG_INFO_hIST);
  185127. }
  185128. return (0);
  185129. }
  185130. #endif
  185131. png_uint_32 PNGAPI
  185132. png_get_IHDR(png_structp png_ptr, png_infop info_ptr,
  185133. png_uint_32 *width, png_uint_32 *height, int *bit_depth,
  185134. int *color_type, int *interlace_type, int *compression_type,
  185135. int *filter_type)
  185136. {
  185137. if (png_ptr != NULL && info_ptr != NULL && width != NULL && height != NULL &&
  185138. bit_depth != NULL && color_type != NULL)
  185139. {
  185140. png_debug1(1, "in %s retrieval function\n", "IHDR");
  185141. *width = info_ptr->width;
  185142. *height = info_ptr->height;
  185143. *bit_depth = info_ptr->bit_depth;
  185144. if (info_ptr->bit_depth < 1 || info_ptr->bit_depth > 16)
  185145. png_error(png_ptr, "Invalid bit depth");
  185146. *color_type = info_ptr->color_type;
  185147. if (info_ptr->color_type > 6)
  185148. png_error(png_ptr, "Invalid color type");
  185149. if (compression_type != NULL)
  185150. *compression_type = info_ptr->compression_type;
  185151. if (filter_type != NULL)
  185152. *filter_type = info_ptr->filter_type;
  185153. if (interlace_type != NULL)
  185154. *interlace_type = info_ptr->interlace_type;
  185155. /* check for potential overflow of rowbytes */
  185156. if (*width == 0 || *width > PNG_UINT_31_MAX)
  185157. png_error(png_ptr, "Invalid image width");
  185158. if (*height == 0 || *height > PNG_UINT_31_MAX)
  185159. png_error(png_ptr, "Invalid image height");
  185160. if (info_ptr->width > (PNG_UINT_32_MAX
  185161. >> 3) /* 8-byte RGBA pixels */
  185162. - 64 /* bigrowbuf hack */
  185163. - 1 /* filter byte */
  185164. - 7*8 /* rounding of width to multiple of 8 pixels */
  185165. - 8) /* extra max_pixel_depth pad */
  185166. {
  185167. png_warning(png_ptr,
  185168. "Width too large for libpng to process image data.");
  185169. }
  185170. return (1);
  185171. }
  185172. return (0);
  185173. }
  185174. #if defined(PNG_oFFs_SUPPORTED)
  185175. png_uint_32 PNGAPI
  185176. png_get_oFFs(png_structp png_ptr, png_infop info_ptr,
  185177. png_int_32 *offset_x, png_int_32 *offset_y, int *unit_type)
  185178. {
  185179. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs)
  185180. && offset_x != NULL && offset_y != NULL && unit_type != NULL)
  185181. {
  185182. png_debug1(1, "in %s retrieval function\n", "oFFs");
  185183. *offset_x = info_ptr->x_offset;
  185184. *offset_y = info_ptr->y_offset;
  185185. *unit_type = (int)info_ptr->offset_unit_type;
  185186. return (PNG_INFO_oFFs);
  185187. }
  185188. return (0);
  185189. }
  185190. #endif
  185191. #if defined(PNG_pCAL_SUPPORTED)
  185192. png_uint_32 PNGAPI
  185193. png_get_pCAL(png_structp png_ptr, png_infop info_ptr,
  185194. png_charp *purpose, png_int_32 *X0, png_int_32 *X1, int *type, int *nparams,
  185195. png_charp *units, png_charpp *params)
  185196. {
  185197. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL)
  185198. && purpose != NULL && X0 != NULL && X1 != NULL && type != NULL &&
  185199. nparams != NULL && units != NULL && params != NULL)
  185200. {
  185201. png_debug1(1, "in %s retrieval function\n", "pCAL");
  185202. *purpose = info_ptr->pcal_purpose;
  185203. *X0 = info_ptr->pcal_X0;
  185204. *X1 = info_ptr->pcal_X1;
  185205. *type = (int)info_ptr->pcal_type;
  185206. *nparams = (int)info_ptr->pcal_nparams;
  185207. *units = info_ptr->pcal_units;
  185208. *params = info_ptr->pcal_params;
  185209. return (PNG_INFO_pCAL);
  185210. }
  185211. return (0);
  185212. }
  185213. #endif
  185214. #if defined(PNG_sCAL_SUPPORTED)
  185215. #ifdef PNG_FLOATING_POINT_SUPPORTED
  185216. png_uint_32 PNGAPI
  185217. png_get_sCAL(png_structp png_ptr, png_infop info_ptr,
  185218. int *unit, double *width, double *height)
  185219. {
  185220. if (png_ptr != NULL && info_ptr != NULL &&
  185221. (info_ptr->valid & PNG_INFO_sCAL))
  185222. {
  185223. *unit = info_ptr->scal_unit;
  185224. *width = info_ptr->scal_pixel_width;
  185225. *height = info_ptr->scal_pixel_height;
  185226. return (PNG_INFO_sCAL);
  185227. }
  185228. return(0);
  185229. }
  185230. #else
  185231. #ifdef PNG_FIXED_POINT_SUPPORTED
  185232. png_uint_32 PNGAPI
  185233. png_get_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  185234. int *unit, png_charpp width, png_charpp height)
  185235. {
  185236. if (png_ptr != NULL && info_ptr != NULL &&
  185237. (info_ptr->valid & PNG_INFO_sCAL))
  185238. {
  185239. *unit = info_ptr->scal_unit;
  185240. *width = info_ptr->scal_s_width;
  185241. *height = info_ptr->scal_s_height;
  185242. return (PNG_INFO_sCAL);
  185243. }
  185244. return(0);
  185245. }
  185246. #endif
  185247. #endif
  185248. #endif
  185249. #if defined(PNG_pHYs_SUPPORTED)
  185250. png_uint_32 PNGAPI
  185251. png_get_pHYs(png_structp png_ptr, png_infop info_ptr,
  185252. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  185253. {
  185254. png_uint_32 retval = 0;
  185255. if (png_ptr != NULL && info_ptr != NULL &&
  185256. (info_ptr->valid & PNG_INFO_pHYs))
  185257. {
  185258. png_debug1(1, "in %s retrieval function\n", "pHYs");
  185259. if (res_x != NULL)
  185260. {
  185261. *res_x = info_ptr->x_pixels_per_unit;
  185262. retval |= PNG_INFO_pHYs;
  185263. }
  185264. if (res_y != NULL)
  185265. {
  185266. *res_y = info_ptr->y_pixels_per_unit;
  185267. retval |= PNG_INFO_pHYs;
  185268. }
  185269. if (unit_type != NULL)
  185270. {
  185271. *unit_type = (int)info_ptr->phys_unit_type;
  185272. retval |= PNG_INFO_pHYs;
  185273. }
  185274. }
  185275. return (retval);
  185276. }
  185277. #endif
  185278. png_uint_32 PNGAPI
  185279. png_get_PLTE(png_structp png_ptr, png_infop info_ptr, png_colorp *palette,
  185280. int *num_palette)
  185281. {
  185282. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_PLTE)
  185283. && palette != NULL)
  185284. {
  185285. png_debug1(1, "in %s retrieval function\n", "PLTE");
  185286. *palette = info_ptr->palette;
  185287. *num_palette = info_ptr->num_palette;
  185288. png_debug1(3, "num_palette = %d\n", *num_palette);
  185289. return (PNG_INFO_PLTE);
  185290. }
  185291. return (0);
  185292. }
  185293. #if defined(PNG_sBIT_SUPPORTED)
  185294. png_uint_32 PNGAPI
  185295. png_get_sBIT(png_structp png_ptr, png_infop info_ptr, png_color_8p *sig_bit)
  185296. {
  185297. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT)
  185298. && sig_bit != NULL)
  185299. {
  185300. png_debug1(1, "in %s retrieval function\n", "sBIT");
  185301. *sig_bit = &(info_ptr->sig_bit);
  185302. return (PNG_INFO_sBIT);
  185303. }
  185304. return (0);
  185305. }
  185306. #endif
  185307. #if defined(PNG_TEXT_SUPPORTED)
  185308. png_uint_32 PNGAPI
  185309. png_get_text(png_structp png_ptr, png_infop info_ptr, png_textp *text_ptr,
  185310. int *num_text)
  185311. {
  185312. if (png_ptr != NULL && info_ptr != NULL && info_ptr->num_text > 0)
  185313. {
  185314. png_debug1(1, "in %s retrieval function\n",
  185315. (png_ptr->chunk_name[0] == '\0' ? "text"
  185316. : (png_const_charp)png_ptr->chunk_name));
  185317. if (text_ptr != NULL)
  185318. *text_ptr = info_ptr->text;
  185319. if (num_text != NULL)
  185320. *num_text = info_ptr->num_text;
  185321. return ((png_uint_32)info_ptr->num_text);
  185322. }
  185323. if (num_text != NULL)
  185324. *num_text = 0;
  185325. return(0);
  185326. }
  185327. #endif
  185328. #if defined(PNG_tIME_SUPPORTED)
  185329. png_uint_32 PNGAPI
  185330. png_get_tIME(png_structp png_ptr, png_infop info_ptr, png_timep *mod_time)
  185331. {
  185332. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME)
  185333. && mod_time != NULL)
  185334. {
  185335. png_debug1(1, "in %s retrieval function\n", "tIME");
  185336. *mod_time = &(info_ptr->mod_time);
  185337. return (PNG_INFO_tIME);
  185338. }
  185339. return (0);
  185340. }
  185341. #endif
  185342. #if defined(PNG_tRNS_SUPPORTED)
  185343. png_uint_32 PNGAPI
  185344. png_get_tRNS(png_structp png_ptr, png_infop info_ptr,
  185345. png_bytep *trans, int *num_trans, png_color_16p *trans_values)
  185346. {
  185347. png_uint_32 retval = 0;
  185348. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  185349. {
  185350. png_debug1(1, "in %s retrieval function\n", "tRNS");
  185351. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  185352. {
  185353. if (trans != NULL)
  185354. {
  185355. *trans = info_ptr->trans;
  185356. retval |= PNG_INFO_tRNS;
  185357. }
  185358. if (trans_values != NULL)
  185359. *trans_values = &(info_ptr->trans_values);
  185360. }
  185361. else /* if (info_ptr->color_type != PNG_COLOR_TYPE_PALETTE) */
  185362. {
  185363. if (trans_values != NULL)
  185364. {
  185365. *trans_values = &(info_ptr->trans_values);
  185366. retval |= PNG_INFO_tRNS;
  185367. }
  185368. if(trans != NULL)
  185369. *trans = NULL;
  185370. }
  185371. if(num_trans != NULL)
  185372. {
  185373. *num_trans = info_ptr->num_trans;
  185374. retval |= PNG_INFO_tRNS;
  185375. }
  185376. }
  185377. return (retval);
  185378. }
  185379. #endif
  185380. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  185381. png_uint_32 PNGAPI
  185382. png_get_unknown_chunks(png_structp png_ptr, png_infop info_ptr,
  185383. png_unknown_chunkpp unknowns)
  185384. {
  185385. if (png_ptr != NULL && info_ptr != NULL && unknowns != NULL)
  185386. {
  185387. *unknowns = info_ptr->unknown_chunks;
  185388. return ((png_uint_32)info_ptr->unknown_chunks_num);
  185389. }
  185390. return (0);
  185391. }
  185392. #endif
  185393. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  185394. png_byte PNGAPI
  185395. png_get_rgb_to_gray_status (png_structp png_ptr)
  185396. {
  185397. return (png_byte)(png_ptr? png_ptr->rgb_to_gray_status : 0);
  185398. }
  185399. #endif
  185400. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  185401. png_voidp PNGAPI
  185402. png_get_user_chunk_ptr(png_structp png_ptr)
  185403. {
  185404. return (png_ptr? png_ptr->user_chunk_ptr : NULL);
  185405. }
  185406. #endif
  185407. #ifdef PNG_WRITE_SUPPORTED
  185408. png_uint_32 PNGAPI
  185409. png_get_compression_buffer_size(png_structp png_ptr)
  185410. {
  185411. return (png_uint_32)(png_ptr? png_ptr->zbuf_size : 0L);
  185412. }
  185413. #endif
  185414. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  185415. #ifndef PNG_1_0_X
  185416. /* this function was added to libpng 1.2.0 and should exist by default */
  185417. png_uint_32 PNGAPI
  185418. png_get_asm_flags (png_structp png_ptr)
  185419. {
  185420. /* obsolete, to be removed from libpng-1.4.0 */
  185421. return (png_ptr? 0L: 0L);
  185422. }
  185423. /* this function was added to libpng 1.2.0 and should exist by default */
  185424. png_uint_32 PNGAPI
  185425. png_get_asm_flagmask (int flag_select)
  185426. {
  185427. /* obsolete, to be removed from libpng-1.4.0 */
  185428. flag_select=flag_select;
  185429. return 0L;
  185430. }
  185431. /* GRR: could add this: && defined(PNG_MMX_CODE_SUPPORTED) */
  185432. /* this function was added to libpng 1.2.0 */
  185433. png_uint_32 PNGAPI
  185434. png_get_mmx_flagmask (int flag_select, int *compilerID)
  185435. {
  185436. /* obsolete, to be removed from libpng-1.4.0 */
  185437. flag_select=flag_select;
  185438. *compilerID = -1; /* unknown (i.e., no asm/MMX code compiled) */
  185439. return 0L;
  185440. }
  185441. /* this function was added to libpng 1.2.0 */
  185442. png_byte PNGAPI
  185443. png_get_mmx_bitdepth_threshold (png_structp png_ptr)
  185444. {
  185445. /* obsolete, to be removed from libpng-1.4.0 */
  185446. return (png_ptr? 0: 0);
  185447. }
  185448. /* this function was added to libpng 1.2.0 */
  185449. png_uint_32 PNGAPI
  185450. png_get_mmx_rowbytes_threshold (png_structp png_ptr)
  185451. {
  185452. /* obsolete, to be removed from libpng-1.4.0 */
  185453. return (png_ptr? 0L: 0L);
  185454. }
  185455. #endif /* ?PNG_1_0_X */
  185456. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  185457. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  185458. /* these functions were added to libpng 1.2.6 */
  185459. png_uint_32 PNGAPI
  185460. png_get_user_width_max (png_structp png_ptr)
  185461. {
  185462. return (png_ptr? png_ptr->user_width_max : 0);
  185463. }
  185464. png_uint_32 PNGAPI
  185465. png_get_user_height_max (png_structp png_ptr)
  185466. {
  185467. return (png_ptr? png_ptr->user_height_max : 0);
  185468. }
  185469. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  185470. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  185471. /*** End of inlined file: pngget.c ***/
  185472. /*** Start of inlined file: pngmem.c ***/
  185473. /* pngmem.c - stub functions for memory allocation
  185474. *
  185475. * Last changed in libpng 1.2.13 November 13, 2006
  185476. * For conditions of distribution and use, see copyright notice in png.h
  185477. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  185478. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  185479. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  185480. *
  185481. * This file provides a location for all memory allocation. Users who
  185482. * need special memory handling are expected to supply replacement
  185483. * functions for png_malloc() and png_free(), and to use
  185484. * png_create_read_struct_2() and png_create_write_struct_2() to
  185485. * identify the replacement functions.
  185486. */
  185487. #define PNG_INTERNAL
  185488. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185489. /* Borland DOS special memory handler */
  185490. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  185491. /* if you change this, be sure to change the one in png.h also */
  185492. /* Allocate memory for a png_struct. The malloc and memset can be replaced
  185493. by a single call to calloc() if this is thought to improve performance. */
  185494. png_voidp /* PRIVATE */
  185495. png_create_struct(int type)
  185496. {
  185497. #ifdef PNG_USER_MEM_SUPPORTED
  185498. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  185499. }
  185500. /* Alternate version of png_create_struct, for use with user-defined malloc. */
  185501. png_voidp /* PRIVATE */
  185502. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  185503. {
  185504. #endif /* PNG_USER_MEM_SUPPORTED */
  185505. png_size_t size;
  185506. png_voidp struct_ptr;
  185507. if (type == PNG_STRUCT_INFO)
  185508. size = png_sizeof(png_info);
  185509. else if (type == PNG_STRUCT_PNG)
  185510. size = png_sizeof(png_struct);
  185511. else
  185512. return (png_get_copyright(NULL));
  185513. #ifdef PNG_USER_MEM_SUPPORTED
  185514. if(malloc_fn != NULL)
  185515. {
  185516. png_struct dummy_struct;
  185517. png_structp png_ptr = &dummy_struct;
  185518. png_ptr->mem_ptr=mem_ptr;
  185519. struct_ptr = (*(malloc_fn))(png_ptr, (png_uint_32)size);
  185520. }
  185521. else
  185522. #endif /* PNG_USER_MEM_SUPPORTED */
  185523. struct_ptr = (png_voidp)farmalloc(size);
  185524. if (struct_ptr != NULL)
  185525. png_memset(struct_ptr, 0, size);
  185526. return (struct_ptr);
  185527. }
  185528. /* Free memory allocated by a png_create_struct() call */
  185529. void /* PRIVATE */
  185530. png_destroy_struct(png_voidp struct_ptr)
  185531. {
  185532. #ifdef PNG_USER_MEM_SUPPORTED
  185533. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  185534. }
  185535. /* Free memory allocated by a png_create_struct() call */
  185536. void /* PRIVATE */
  185537. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  185538. png_voidp mem_ptr)
  185539. {
  185540. #endif
  185541. if (struct_ptr != NULL)
  185542. {
  185543. #ifdef PNG_USER_MEM_SUPPORTED
  185544. if(free_fn != NULL)
  185545. {
  185546. png_struct dummy_struct;
  185547. png_structp png_ptr = &dummy_struct;
  185548. png_ptr->mem_ptr=mem_ptr;
  185549. (*(free_fn))(png_ptr, struct_ptr);
  185550. return;
  185551. }
  185552. #endif /* PNG_USER_MEM_SUPPORTED */
  185553. farfree (struct_ptr);
  185554. }
  185555. }
  185556. /* Allocate memory. For reasonable files, size should never exceed
  185557. * 64K. However, zlib may allocate more then 64K if you don't tell
  185558. * it not to. See zconf.h and png.h for more information. zlib does
  185559. * need to allocate exactly 64K, so whatever you call here must
  185560. * have the ability to do that.
  185561. *
  185562. * Borland seems to have a problem in DOS mode for exactly 64K.
  185563. * It gives you a segment with an offset of 8 (perhaps to store its
  185564. * memory stuff). zlib doesn't like this at all, so we have to
  185565. * detect and deal with it. This code should not be needed in
  185566. * Windows or OS/2 modes, and only in 16 bit mode. This code has
  185567. * been updated by Alexander Lehmann for version 0.89 to waste less
  185568. * memory.
  185569. *
  185570. * Note that we can't use png_size_t for the "size" declaration,
  185571. * since on some systems a png_size_t is a 16-bit quantity, and as a
  185572. * result, we would be truncating potentially larger memory requests
  185573. * (which should cause a fatal error) and introducing major problems.
  185574. */
  185575. png_voidp PNGAPI
  185576. png_malloc(png_structp png_ptr, png_uint_32 size)
  185577. {
  185578. png_voidp ret;
  185579. if (png_ptr == NULL || size == 0)
  185580. return (NULL);
  185581. #ifdef PNG_USER_MEM_SUPPORTED
  185582. if(png_ptr->malloc_fn != NULL)
  185583. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  185584. else
  185585. ret = (png_malloc_default(png_ptr, size));
  185586. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  185587. png_error(png_ptr, "Out of memory!");
  185588. return (ret);
  185589. }
  185590. png_voidp PNGAPI
  185591. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  185592. {
  185593. png_voidp ret;
  185594. #endif /* PNG_USER_MEM_SUPPORTED */
  185595. if (png_ptr == NULL || size == 0)
  185596. return (NULL);
  185597. #ifdef PNG_MAX_MALLOC_64K
  185598. if (size > (png_uint_32)65536L)
  185599. {
  185600. png_warning(png_ptr, "Cannot Allocate > 64K");
  185601. ret = NULL;
  185602. }
  185603. else
  185604. #endif
  185605. if (size != (size_t)size)
  185606. ret = NULL;
  185607. else if (size == (png_uint_32)65536L)
  185608. {
  185609. if (png_ptr->offset_table == NULL)
  185610. {
  185611. /* try to see if we need to do any of this fancy stuff */
  185612. ret = farmalloc(size);
  185613. if (ret == NULL || ((png_size_t)ret & 0xffff))
  185614. {
  185615. int num_blocks;
  185616. png_uint_32 total_size;
  185617. png_bytep table;
  185618. int i;
  185619. png_byte huge * hptr;
  185620. if (ret != NULL)
  185621. {
  185622. farfree(ret);
  185623. ret = NULL;
  185624. }
  185625. if(png_ptr->zlib_window_bits > 14)
  185626. num_blocks = (int)(1 << (png_ptr->zlib_window_bits - 14));
  185627. else
  185628. num_blocks = 1;
  185629. if (png_ptr->zlib_mem_level >= 7)
  185630. num_blocks += (int)(1 << (png_ptr->zlib_mem_level - 7));
  185631. else
  185632. num_blocks++;
  185633. total_size = ((png_uint_32)65536L) * (png_uint_32)num_blocks+16;
  185634. table = farmalloc(total_size);
  185635. if (table == NULL)
  185636. {
  185637. #ifndef PNG_USER_MEM_SUPPORTED
  185638. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  185639. png_error(png_ptr, "Out Of Memory."); /* Note "O" and "M" */
  185640. else
  185641. png_warning(png_ptr, "Out Of Memory.");
  185642. #endif
  185643. return (NULL);
  185644. }
  185645. if ((png_size_t)table & 0xfff0)
  185646. {
  185647. #ifndef PNG_USER_MEM_SUPPORTED
  185648. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  185649. png_error(png_ptr,
  185650. "Farmalloc didn't return normalized pointer");
  185651. else
  185652. png_warning(png_ptr,
  185653. "Farmalloc didn't return normalized pointer");
  185654. #endif
  185655. return (NULL);
  185656. }
  185657. png_ptr->offset_table = table;
  185658. png_ptr->offset_table_ptr = farmalloc(num_blocks *
  185659. png_sizeof (png_bytep));
  185660. if (png_ptr->offset_table_ptr == NULL)
  185661. {
  185662. #ifndef PNG_USER_MEM_SUPPORTED
  185663. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  185664. png_error(png_ptr, "Out Of memory."); /* Note "O" and "M" */
  185665. else
  185666. png_warning(png_ptr, "Out Of memory.");
  185667. #endif
  185668. return (NULL);
  185669. }
  185670. hptr = (png_byte huge *)table;
  185671. if ((png_size_t)hptr & 0xf)
  185672. {
  185673. hptr = (png_byte huge *)((long)(hptr) & 0xfffffff0L);
  185674. hptr = hptr + 16L; /* "hptr += 16L" fails on Turbo C++ 3.0 */
  185675. }
  185676. for (i = 0; i < num_blocks; i++)
  185677. {
  185678. png_ptr->offset_table_ptr[i] = (png_bytep)hptr;
  185679. hptr = hptr + (png_uint_32)65536L; /* "+=" fails on TC++3.0 */
  185680. }
  185681. png_ptr->offset_table_number = num_blocks;
  185682. png_ptr->offset_table_count = 0;
  185683. png_ptr->offset_table_count_free = 0;
  185684. }
  185685. }
  185686. if (png_ptr->offset_table_count >= png_ptr->offset_table_number)
  185687. {
  185688. #ifndef PNG_USER_MEM_SUPPORTED
  185689. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  185690. png_error(png_ptr, "Out of Memory."); /* Note "o" and "M" */
  185691. else
  185692. png_warning(png_ptr, "Out of Memory.");
  185693. #endif
  185694. return (NULL);
  185695. }
  185696. ret = png_ptr->offset_table_ptr[png_ptr->offset_table_count++];
  185697. }
  185698. else
  185699. ret = farmalloc(size);
  185700. #ifndef PNG_USER_MEM_SUPPORTED
  185701. if (ret == NULL)
  185702. {
  185703. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  185704. png_error(png_ptr, "Out of memory."); /* Note "o" and "m" */
  185705. else
  185706. png_warning(png_ptr, "Out of memory."); /* Note "o" and "m" */
  185707. }
  185708. #endif
  185709. return (ret);
  185710. }
  185711. /* free a pointer allocated by png_malloc(). In the default
  185712. configuration, png_ptr is not used, but is passed in case it
  185713. is needed. If ptr is NULL, return without taking any action. */
  185714. void PNGAPI
  185715. png_free(png_structp png_ptr, png_voidp ptr)
  185716. {
  185717. if (png_ptr == NULL || ptr == NULL)
  185718. return;
  185719. #ifdef PNG_USER_MEM_SUPPORTED
  185720. if (png_ptr->free_fn != NULL)
  185721. {
  185722. (*(png_ptr->free_fn))(png_ptr, ptr);
  185723. return;
  185724. }
  185725. else png_free_default(png_ptr, ptr);
  185726. }
  185727. void PNGAPI
  185728. png_free_default(png_structp png_ptr, png_voidp ptr)
  185729. {
  185730. #endif /* PNG_USER_MEM_SUPPORTED */
  185731. if(png_ptr == NULL) return;
  185732. if (png_ptr->offset_table != NULL)
  185733. {
  185734. int i;
  185735. for (i = 0; i < png_ptr->offset_table_count; i++)
  185736. {
  185737. if (ptr == png_ptr->offset_table_ptr[i])
  185738. {
  185739. ptr = NULL;
  185740. png_ptr->offset_table_count_free++;
  185741. break;
  185742. }
  185743. }
  185744. if (png_ptr->offset_table_count_free == png_ptr->offset_table_count)
  185745. {
  185746. farfree(png_ptr->offset_table);
  185747. farfree(png_ptr->offset_table_ptr);
  185748. png_ptr->offset_table = NULL;
  185749. png_ptr->offset_table_ptr = NULL;
  185750. }
  185751. }
  185752. if (ptr != NULL)
  185753. {
  185754. farfree(ptr);
  185755. }
  185756. }
  185757. #else /* Not the Borland DOS special memory handler */
  185758. /* Allocate memory for a png_struct or a png_info. The malloc and
  185759. memset can be replaced by a single call to calloc() if this is thought
  185760. to improve performance noticably. */
  185761. png_voidp /* PRIVATE */
  185762. png_create_struct(int type)
  185763. {
  185764. #ifdef PNG_USER_MEM_SUPPORTED
  185765. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  185766. }
  185767. /* Allocate memory for a png_struct or a png_info. The malloc and
  185768. memset can be replaced by a single call to calloc() if this is thought
  185769. to improve performance noticably. */
  185770. png_voidp /* PRIVATE */
  185771. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  185772. {
  185773. #endif /* PNG_USER_MEM_SUPPORTED */
  185774. png_size_t size;
  185775. png_voidp struct_ptr;
  185776. if (type == PNG_STRUCT_INFO)
  185777. size = png_sizeof(png_info);
  185778. else if (type == PNG_STRUCT_PNG)
  185779. size = png_sizeof(png_struct);
  185780. else
  185781. return (NULL);
  185782. #ifdef PNG_USER_MEM_SUPPORTED
  185783. if(malloc_fn != NULL)
  185784. {
  185785. png_struct dummy_struct;
  185786. png_structp png_ptr = &dummy_struct;
  185787. png_ptr->mem_ptr=mem_ptr;
  185788. struct_ptr = (*(malloc_fn))(png_ptr, size);
  185789. if (struct_ptr != NULL)
  185790. png_memset(struct_ptr, 0, size);
  185791. return (struct_ptr);
  185792. }
  185793. #endif /* PNG_USER_MEM_SUPPORTED */
  185794. #if defined(__TURBOC__) && !defined(__FLAT__)
  185795. struct_ptr = (png_voidp)farmalloc(size);
  185796. #else
  185797. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  185798. struct_ptr = (png_voidp)halloc(size,1);
  185799. # else
  185800. struct_ptr = (png_voidp)malloc(size);
  185801. # endif
  185802. #endif
  185803. if (struct_ptr != NULL)
  185804. png_memset(struct_ptr, 0, size);
  185805. return (struct_ptr);
  185806. }
  185807. /* Free memory allocated by a png_create_struct() call */
  185808. void /* PRIVATE */
  185809. png_destroy_struct(png_voidp struct_ptr)
  185810. {
  185811. #ifdef PNG_USER_MEM_SUPPORTED
  185812. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  185813. }
  185814. /* Free memory allocated by a png_create_struct() call */
  185815. void /* PRIVATE */
  185816. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  185817. png_voidp mem_ptr)
  185818. {
  185819. #endif /* PNG_USER_MEM_SUPPORTED */
  185820. if (struct_ptr != NULL)
  185821. {
  185822. #ifdef PNG_USER_MEM_SUPPORTED
  185823. if(free_fn != NULL)
  185824. {
  185825. png_struct dummy_struct;
  185826. png_structp png_ptr = &dummy_struct;
  185827. png_ptr->mem_ptr=mem_ptr;
  185828. (*(free_fn))(png_ptr, struct_ptr);
  185829. return;
  185830. }
  185831. #endif /* PNG_USER_MEM_SUPPORTED */
  185832. #if defined(__TURBOC__) && !defined(__FLAT__)
  185833. farfree(struct_ptr);
  185834. #else
  185835. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  185836. hfree(struct_ptr);
  185837. # else
  185838. free(struct_ptr);
  185839. # endif
  185840. #endif
  185841. }
  185842. }
  185843. /* Allocate memory. For reasonable files, size should never exceed
  185844. 64K. However, zlib may allocate more then 64K if you don't tell
  185845. it not to. See zconf.h and png.h for more information. zlib does
  185846. need to allocate exactly 64K, so whatever you call here must
  185847. have the ability to do that. */
  185848. png_voidp PNGAPI
  185849. png_malloc(png_structp png_ptr, png_uint_32 size)
  185850. {
  185851. png_voidp ret;
  185852. #ifdef PNG_USER_MEM_SUPPORTED
  185853. if (png_ptr == NULL || size == 0)
  185854. return (NULL);
  185855. if(png_ptr->malloc_fn != NULL)
  185856. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  185857. else
  185858. ret = (png_malloc_default(png_ptr, size));
  185859. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  185860. png_error(png_ptr, "Out of Memory!");
  185861. return (ret);
  185862. }
  185863. png_voidp PNGAPI
  185864. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  185865. {
  185866. png_voidp ret;
  185867. #endif /* PNG_USER_MEM_SUPPORTED */
  185868. if (png_ptr == NULL || size == 0)
  185869. return (NULL);
  185870. #ifdef PNG_MAX_MALLOC_64K
  185871. if (size > (png_uint_32)65536L)
  185872. {
  185873. #ifndef PNG_USER_MEM_SUPPORTED
  185874. if(png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  185875. png_error(png_ptr, "Cannot Allocate > 64K");
  185876. else
  185877. #endif
  185878. return NULL;
  185879. }
  185880. #endif
  185881. /* Check for overflow */
  185882. #if defined(__TURBOC__) && !defined(__FLAT__)
  185883. if (size != (unsigned long)size)
  185884. ret = NULL;
  185885. else
  185886. ret = farmalloc(size);
  185887. #else
  185888. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  185889. if (size != (unsigned long)size)
  185890. ret = NULL;
  185891. else
  185892. ret = halloc(size, 1);
  185893. # else
  185894. if (size != (size_t)size)
  185895. ret = NULL;
  185896. else
  185897. ret = malloc((size_t)size);
  185898. # endif
  185899. #endif
  185900. #ifndef PNG_USER_MEM_SUPPORTED
  185901. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  185902. png_error(png_ptr, "Out of Memory");
  185903. #endif
  185904. return (ret);
  185905. }
  185906. /* Free a pointer allocated by png_malloc(). If ptr is NULL, return
  185907. without taking any action. */
  185908. void PNGAPI
  185909. png_free(png_structp png_ptr, png_voidp ptr)
  185910. {
  185911. if (png_ptr == NULL || ptr == NULL)
  185912. return;
  185913. #ifdef PNG_USER_MEM_SUPPORTED
  185914. if (png_ptr->free_fn != NULL)
  185915. {
  185916. (*(png_ptr->free_fn))(png_ptr, ptr);
  185917. return;
  185918. }
  185919. else png_free_default(png_ptr, ptr);
  185920. }
  185921. void PNGAPI
  185922. png_free_default(png_structp png_ptr, png_voidp ptr)
  185923. {
  185924. if (png_ptr == NULL || ptr == NULL)
  185925. return;
  185926. #endif /* PNG_USER_MEM_SUPPORTED */
  185927. #if defined(__TURBOC__) && !defined(__FLAT__)
  185928. farfree(ptr);
  185929. #else
  185930. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  185931. hfree(ptr);
  185932. # else
  185933. free(ptr);
  185934. # endif
  185935. #endif
  185936. }
  185937. #endif /* Not Borland DOS special memory handler */
  185938. #if defined(PNG_1_0_X)
  185939. # define png_malloc_warn png_malloc
  185940. #else
  185941. /* This function was added at libpng version 1.2.3. The png_malloc_warn()
  185942. * function will set up png_malloc() to issue a png_warning and return NULL
  185943. * instead of issuing a png_error, if it fails to allocate the requested
  185944. * memory.
  185945. */
  185946. png_voidp PNGAPI
  185947. png_malloc_warn(png_structp png_ptr, png_uint_32 size)
  185948. {
  185949. png_voidp ptr;
  185950. png_uint_32 save_flags;
  185951. if(png_ptr == NULL) return (NULL);
  185952. save_flags=png_ptr->flags;
  185953. png_ptr->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  185954. ptr = (png_voidp)png_malloc((png_structp)png_ptr, size);
  185955. png_ptr->flags=save_flags;
  185956. return(ptr);
  185957. }
  185958. #endif
  185959. png_voidp PNGAPI
  185960. png_memcpy_check (png_structp png_ptr, png_voidp s1, png_voidp s2,
  185961. png_uint_32 length)
  185962. {
  185963. png_size_t size;
  185964. size = (png_size_t)length;
  185965. if ((png_uint_32)size != length)
  185966. png_error(png_ptr,"Overflow in png_memcpy_check.");
  185967. return(png_memcpy (s1, s2, size));
  185968. }
  185969. png_voidp PNGAPI
  185970. png_memset_check (png_structp png_ptr, png_voidp s1, int value,
  185971. png_uint_32 length)
  185972. {
  185973. png_size_t size;
  185974. size = (png_size_t)length;
  185975. if ((png_uint_32)size != length)
  185976. png_error(png_ptr,"Overflow in png_memset_check.");
  185977. return (png_memset (s1, value, size));
  185978. }
  185979. #ifdef PNG_USER_MEM_SUPPORTED
  185980. /* This function is called when the application wants to use another method
  185981. * of allocating and freeing memory.
  185982. */
  185983. void PNGAPI
  185984. png_set_mem_fn(png_structp png_ptr, png_voidp mem_ptr, png_malloc_ptr
  185985. malloc_fn, png_free_ptr free_fn)
  185986. {
  185987. if(png_ptr != NULL) {
  185988. png_ptr->mem_ptr = mem_ptr;
  185989. png_ptr->malloc_fn = malloc_fn;
  185990. png_ptr->free_fn = free_fn;
  185991. }
  185992. }
  185993. /* This function returns a pointer to the mem_ptr associated with the user
  185994. * functions. The application should free any memory associated with this
  185995. * pointer before png_write_destroy and png_read_destroy are called.
  185996. */
  185997. png_voidp PNGAPI
  185998. png_get_mem_ptr(png_structp png_ptr)
  185999. {
  186000. if(png_ptr == NULL) return (NULL);
  186001. return ((png_voidp)png_ptr->mem_ptr);
  186002. }
  186003. #endif /* PNG_USER_MEM_SUPPORTED */
  186004. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  186005. /*** End of inlined file: pngmem.c ***/
  186006. /*** Start of inlined file: pngread.c ***/
  186007. /* pngread.c - read a PNG file
  186008. *
  186009. * Last changed in libpng 1.2.20 September 7, 2007
  186010. * For conditions of distribution and use, see copyright notice in png.h
  186011. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  186012. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  186013. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  186014. *
  186015. * This file contains routines that an application calls directly to
  186016. * read a PNG file or stream.
  186017. */
  186018. #define PNG_INTERNAL
  186019. #if defined(PNG_READ_SUPPORTED)
  186020. /* Create a PNG structure for reading, and allocate any memory needed. */
  186021. png_structp PNGAPI
  186022. png_create_read_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  186023. png_error_ptr error_fn, png_error_ptr warn_fn)
  186024. {
  186025. #ifdef PNG_USER_MEM_SUPPORTED
  186026. return (png_create_read_struct_2(user_png_ver, error_ptr, error_fn,
  186027. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  186028. }
  186029. /* Alternate create PNG structure for reading, and allocate any memory needed. */
  186030. png_structp PNGAPI
  186031. png_create_read_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  186032. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  186033. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  186034. {
  186035. #endif /* PNG_USER_MEM_SUPPORTED */
  186036. png_structp png_ptr;
  186037. #ifdef PNG_SETJMP_SUPPORTED
  186038. #ifdef USE_FAR_KEYWORD
  186039. jmp_buf jmpbuf;
  186040. #endif
  186041. #endif
  186042. int i;
  186043. png_debug(1, "in png_create_read_struct\n");
  186044. #ifdef PNG_USER_MEM_SUPPORTED
  186045. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  186046. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  186047. #else
  186048. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  186049. #endif
  186050. if (png_ptr == NULL)
  186051. return (NULL);
  186052. /* added at libpng-1.2.6 */
  186053. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  186054. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  186055. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  186056. #endif
  186057. #ifdef PNG_SETJMP_SUPPORTED
  186058. #ifdef USE_FAR_KEYWORD
  186059. if (setjmp(jmpbuf))
  186060. #else
  186061. if (setjmp(png_ptr->jmpbuf))
  186062. #endif
  186063. {
  186064. png_free(png_ptr, png_ptr->zbuf);
  186065. png_ptr->zbuf=NULL;
  186066. #ifdef PNG_USER_MEM_SUPPORTED
  186067. png_destroy_struct_2((png_voidp)png_ptr,
  186068. (png_free_ptr)free_fn, (png_voidp)mem_ptr);
  186069. #else
  186070. png_destroy_struct((png_voidp)png_ptr);
  186071. #endif
  186072. return (NULL);
  186073. }
  186074. #ifdef USE_FAR_KEYWORD
  186075. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  186076. #endif
  186077. #endif
  186078. #ifdef PNG_USER_MEM_SUPPORTED
  186079. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  186080. #endif
  186081. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  186082. i=0;
  186083. do
  186084. {
  186085. if(user_png_ver[i] != png_libpng_ver[i])
  186086. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  186087. } while (png_libpng_ver[i++]);
  186088. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  186089. {
  186090. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  186091. * we must recompile any applications that use any older library version.
  186092. * For versions after libpng 1.0, we will be compatible, so we need
  186093. * only check the first digit.
  186094. */
  186095. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  186096. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  186097. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  186098. {
  186099. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  186100. char msg[80];
  186101. if (user_png_ver)
  186102. {
  186103. png_snprintf(msg, 80,
  186104. "Application was compiled with png.h from libpng-%.20s",
  186105. user_png_ver);
  186106. png_warning(png_ptr, msg);
  186107. }
  186108. png_snprintf(msg, 80,
  186109. "Application is running with png.c from libpng-%.20s",
  186110. png_libpng_ver);
  186111. png_warning(png_ptr, msg);
  186112. #endif
  186113. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  186114. png_ptr->flags=0;
  186115. #endif
  186116. png_error(png_ptr,
  186117. "Incompatible libpng version in application and library");
  186118. }
  186119. }
  186120. /* initialize zbuf - compression buffer */
  186121. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  186122. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  186123. (png_uint_32)png_ptr->zbuf_size);
  186124. png_ptr->zstream.zalloc = png_zalloc;
  186125. png_ptr->zstream.zfree = png_zfree;
  186126. png_ptr->zstream.opaque = (voidpf)png_ptr;
  186127. switch (inflateInit(&png_ptr->zstream))
  186128. {
  186129. case Z_OK: /* Do nothing */ break;
  186130. case Z_MEM_ERROR:
  186131. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory error"); break;
  186132. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version error"); break;
  186133. default: png_error(png_ptr, "Unknown zlib error");
  186134. }
  186135. png_ptr->zstream.next_out = png_ptr->zbuf;
  186136. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  186137. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  186138. #ifdef PNG_SETJMP_SUPPORTED
  186139. /* Applications that neglect to set up their own setjmp() and then encounter
  186140. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  186141. abort instead of returning. */
  186142. #ifdef USE_FAR_KEYWORD
  186143. if (setjmp(jmpbuf))
  186144. PNG_ABORT();
  186145. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  186146. #else
  186147. if (setjmp(png_ptr->jmpbuf))
  186148. PNG_ABORT();
  186149. #endif
  186150. #endif
  186151. return (png_ptr);
  186152. }
  186153. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  186154. /* Initialize PNG structure for reading, and allocate any memory needed.
  186155. This interface is deprecated in favour of the png_create_read_struct(),
  186156. and it will disappear as of libpng-1.3.0. */
  186157. #undef png_read_init
  186158. void PNGAPI
  186159. png_read_init(png_structp png_ptr)
  186160. {
  186161. /* We only come here via pre-1.0.7-compiled applications */
  186162. png_read_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  186163. }
  186164. void PNGAPI
  186165. png_read_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  186166. png_size_t png_struct_size, png_size_t png_info_size)
  186167. {
  186168. /* We only come here via pre-1.0.12-compiled applications */
  186169. if(png_ptr == NULL) return;
  186170. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  186171. if(png_sizeof(png_struct) > png_struct_size ||
  186172. png_sizeof(png_info) > png_info_size)
  186173. {
  186174. char msg[80];
  186175. png_ptr->warning_fn=NULL;
  186176. if (user_png_ver)
  186177. {
  186178. png_snprintf(msg, 80,
  186179. "Application was compiled with png.h from libpng-%.20s",
  186180. user_png_ver);
  186181. png_warning(png_ptr, msg);
  186182. }
  186183. png_snprintf(msg, 80,
  186184. "Application is running with png.c from libpng-%.20s",
  186185. png_libpng_ver);
  186186. png_warning(png_ptr, msg);
  186187. }
  186188. #endif
  186189. if(png_sizeof(png_struct) > png_struct_size)
  186190. {
  186191. png_ptr->error_fn=NULL;
  186192. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  186193. png_ptr->flags=0;
  186194. #endif
  186195. png_error(png_ptr,
  186196. "The png struct allocated by the application for reading is too small.");
  186197. }
  186198. if(png_sizeof(png_info) > png_info_size)
  186199. {
  186200. png_ptr->error_fn=NULL;
  186201. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  186202. png_ptr->flags=0;
  186203. #endif
  186204. png_error(png_ptr,
  186205. "The info struct allocated by application for reading is too small.");
  186206. }
  186207. png_read_init_3(&png_ptr, user_png_ver, png_struct_size);
  186208. }
  186209. #endif /* PNG_1_0_X || PNG_1_2_X */
  186210. void PNGAPI
  186211. png_read_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  186212. png_size_t png_struct_size)
  186213. {
  186214. #ifdef PNG_SETJMP_SUPPORTED
  186215. jmp_buf tmp_jmp; /* to save current jump buffer */
  186216. #endif
  186217. int i=0;
  186218. png_structp png_ptr=*ptr_ptr;
  186219. if(png_ptr == NULL) return;
  186220. do
  186221. {
  186222. if(user_png_ver[i] != png_libpng_ver[i])
  186223. {
  186224. #ifdef PNG_LEGACY_SUPPORTED
  186225. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  186226. #else
  186227. png_ptr->warning_fn=NULL;
  186228. png_warning(png_ptr,
  186229. "Application uses deprecated png_read_init() and should be recompiled.");
  186230. break;
  186231. #endif
  186232. }
  186233. } while (png_libpng_ver[i++]);
  186234. png_debug(1, "in png_read_init_3\n");
  186235. #ifdef PNG_SETJMP_SUPPORTED
  186236. /* save jump buffer and error functions */
  186237. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  186238. #endif
  186239. if(png_sizeof(png_struct) > png_struct_size)
  186240. {
  186241. png_destroy_struct(png_ptr);
  186242. *ptr_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  186243. png_ptr = *ptr_ptr;
  186244. }
  186245. /* reset all variables to 0 */
  186246. png_memset(png_ptr, 0, png_sizeof (png_struct));
  186247. #ifdef PNG_SETJMP_SUPPORTED
  186248. /* restore jump buffer */
  186249. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  186250. #endif
  186251. /* added at libpng-1.2.6 */
  186252. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  186253. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  186254. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  186255. #endif
  186256. /* initialize zbuf - compression buffer */
  186257. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  186258. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  186259. (png_uint_32)png_ptr->zbuf_size);
  186260. png_ptr->zstream.zalloc = png_zalloc;
  186261. png_ptr->zstream.zfree = png_zfree;
  186262. png_ptr->zstream.opaque = (voidpf)png_ptr;
  186263. switch (inflateInit(&png_ptr->zstream))
  186264. {
  186265. case Z_OK: /* Do nothing */ break;
  186266. case Z_MEM_ERROR:
  186267. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory"); break;
  186268. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version"); break;
  186269. default: png_error(png_ptr, "Unknown zlib error");
  186270. }
  186271. png_ptr->zstream.next_out = png_ptr->zbuf;
  186272. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  186273. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  186274. }
  186275. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  186276. /* Read the information before the actual image data. This has been
  186277. * changed in v0.90 to allow reading a file that already has the magic
  186278. * bytes read from the stream. You can tell libpng how many bytes have
  186279. * been read from the beginning of the stream (up to the maximum of 8)
  186280. * via png_set_sig_bytes(), and we will only check the remaining bytes
  186281. * here. The application can then have access to the signature bytes we
  186282. * read if it is determined that this isn't a valid PNG file.
  186283. */
  186284. void PNGAPI
  186285. png_read_info(png_structp png_ptr, png_infop info_ptr)
  186286. {
  186287. if(png_ptr == NULL) return;
  186288. png_debug(1, "in png_read_info\n");
  186289. /* If we haven't checked all of the PNG signature bytes, do so now. */
  186290. if (png_ptr->sig_bytes < 8)
  186291. {
  186292. png_size_t num_checked = png_ptr->sig_bytes,
  186293. num_to_check = 8 - num_checked;
  186294. png_read_data(png_ptr, &(info_ptr->signature[num_checked]), num_to_check);
  186295. png_ptr->sig_bytes = 8;
  186296. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  186297. {
  186298. if (num_checked < 4 &&
  186299. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  186300. png_error(png_ptr, "Not a PNG file");
  186301. else
  186302. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  186303. }
  186304. if (num_checked < 3)
  186305. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  186306. }
  186307. for(;;)
  186308. {
  186309. #ifdef PNG_USE_LOCAL_ARRAYS
  186310. PNG_CONST PNG_IHDR;
  186311. PNG_CONST PNG_IDAT;
  186312. PNG_CONST PNG_IEND;
  186313. PNG_CONST PNG_PLTE;
  186314. #if defined(PNG_READ_bKGD_SUPPORTED)
  186315. PNG_CONST PNG_bKGD;
  186316. #endif
  186317. #if defined(PNG_READ_cHRM_SUPPORTED)
  186318. PNG_CONST PNG_cHRM;
  186319. #endif
  186320. #if defined(PNG_READ_gAMA_SUPPORTED)
  186321. PNG_CONST PNG_gAMA;
  186322. #endif
  186323. #if defined(PNG_READ_hIST_SUPPORTED)
  186324. PNG_CONST PNG_hIST;
  186325. #endif
  186326. #if defined(PNG_READ_iCCP_SUPPORTED)
  186327. PNG_CONST PNG_iCCP;
  186328. #endif
  186329. #if defined(PNG_READ_iTXt_SUPPORTED)
  186330. PNG_CONST PNG_iTXt;
  186331. #endif
  186332. #if defined(PNG_READ_oFFs_SUPPORTED)
  186333. PNG_CONST PNG_oFFs;
  186334. #endif
  186335. #if defined(PNG_READ_pCAL_SUPPORTED)
  186336. PNG_CONST PNG_pCAL;
  186337. #endif
  186338. #if defined(PNG_READ_pHYs_SUPPORTED)
  186339. PNG_CONST PNG_pHYs;
  186340. #endif
  186341. #if defined(PNG_READ_sBIT_SUPPORTED)
  186342. PNG_CONST PNG_sBIT;
  186343. #endif
  186344. #if defined(PNG_READ_sCAL_SUPPORTED)
  186345. PNG_CONST PNG_sCAL;
  186346. #endif
  186347. #if defined(PNG_READ_sPLT_SUPPORTED)
  186348. PNG_CONST PNG_sPLT;
  186349. #endif
  186350. #if defined(PNG_READ_sRGB_SUPPORTED)
  186351. PNG_CONST PNG_sRGB;
  186352. #endif
  186353. #if defined(PNG_READ_tEXt_SUPPORTED)
  186354. PNG_CONST PNG_tEXt;
  186355. #endif
  186356. #if defined(PNG_READ_tIME_SUPPORTED)
  186357. PNG_CONST PNG_tIME;
  186358. #endif
  186359. #if defined(PNG_READ_tRNS_SUPPORTED)
  186360. PNG_CONST PNG_tRNS;
  186361. #endif
  186362. #if defined(PNG_READ_zTXt_SUPPORTED)
  186363. PNG_CONST PNG_zTXt;
  186364. #endif
  186365. #endif /* PNG_USE_LOCAL_ARRAYS */
  186366. png_byte chunk_length[4];
  186367. png_uint_32 length;
  186368. png_read_data(png_ptr, chunk_length, 4);
  186369. length = png_get_uint_31(png_ptr,chunk_length);
  186370. png_reset_crc(png_ptr);
  186371. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  186372. png_debug2(0, "Reading %s chunk, length=%lu.\n", png_ptr->chunk_name,
  186373. length);
  186374. /* This should be a binary subdivision search or a hash for
  186375. * matching the chunk name rather than a linear search.
  186376. */
  186377. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  186378. if(png_ptr->mode & PNG_AFTER_IDAT)
  186379. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  186380. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  186381. png_handle_IHDR(png_ptr, info_ptr, length);
  186382. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  186383. png_handle_IEND(png_ptr, info_ptr, length);
  186384. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  186385. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  186386. {
  186387. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  186388. png_ptr->mode |= PNG_HAVE_IDAT;
  186389. png_handle_unknown(png_ptr, info_ptr, length);
  186390. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  186391. png_ptr->mode |= PNG_HAVE_PLTE;
  186392. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  186393. {
  186394. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  186395. png_error(png_ptr, "Missing IHDR before IDAT");
  186396. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  186397. !(png_ptr->mode & PNG_HAVE_PLTE))
  186398. png_error(png_ptr, "Missing PLTE before IDAT");
  186399. break;
  186400. }
  186401. }
  186402. #endif
  186403. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  186404. png_handle_PLTE(png_ptr, info_ptr, length);
  186405. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  186406. {
  186407. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  186408. png_error(png_ptr, "Missing IHDR before IDAT");
  186409. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  186410. !(png_ptr->mode & PNG_HAVE_PLTE))
  186411. png_error(png_ptr, "Missing PLTE before IDAT");
  186412. png_ptr->idat_size = length;
  186413. png_ptr->mode |= PNG_HAVE_IDAT;
  186414. break;
  186415. }
  186416. #if defined(PNG_READ_bKGD_SUPPORTED)
  186417. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  186418. png_handle_bKGD(png_ptr, info_ptr, length);
  186419. #endif
  186420. #if defined(PNG_READ_cHRM_SUPPORTED)
  186421. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  186422. png_handle_cHRM(png_ptr, info_ptr, length);
  186423. #endif
  186424. #if defined(PNG_READ_gAMA_SUPPORTED)
  186425. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  186426. png_handle_gAMA(png_ptr, info_ptr, length);
  186427. #endif
  186428. #if defined(PNG_READ_hIST_SUPPORTED)
  186429. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  186430. png_handle_hIST(png_ptr, info_ptr, length);
  186431. #endif
  186432. #if defined(PNG_READ_oFFs_SUPPORTED)
  186433. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  186434. png_handle_oFFs(png_ptr, info_ptr, length);
  186435. #endif
  186436. #if defined(PNG_READ_pCAL_SUPPORTED)
  186437. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  186438. png_handle_pCAL(png_ptr, info_ptr, length);
  186439. #endif
  186440. #if defined(PNG_READ_sCAL_SUPPORTED)
  186441. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  186442. png_handle_sCAL(png_ptr, info_ptr, length);
  186443. #endif
  186444. #if defined(PNG_READ_pHYs_SUPPORTED)
  186445. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  186446. png_handle_pHYs(png_ptr, info_ptr, length);
  186447. #endif
  186448. #if defined(PNG_READ_sBIT_SUPPORTED)
  186449. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  186450. png_handle_sBIT(png_ptr, info_ptr, length);
  186451. #endif
  186452. #if defined(PNG_READ_sRGB_SUPPORTED)
  186453. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  186454. png_handle_sRGB(png_ptr, info_ptr, length);
  186455. #endif
  186456. #if defined(PNG_READ_iCCP_SUPPORTED)
  186457. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  186458. png_handle_iCCP(png_ptr, info_ptr, length);
  186459. #endif
  186460. #if defined(PNG_READ_sPLT_SUPPORTED)
  186461. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  186462. png_handle_sPLT(png_ptr, info_ptr, length);
  186463. #endif
  186464. #if defined(PNG_READ_tEXt_SUPPORTED)
  186465. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  186466. png_handle_tEXt(png_ptr, info_ptr, length);
  186467. #endif
  186468. #if defined(PNG_READ_tIME_SUPPORTED)
  186469. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  186470. png_handle_tIME(png_ptr, info_ptr, length);
  186471. #endif
  186472. #if defined(PNG_READ_tRNS_SUPPORTED)
  186473. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  186474. png_handle_tRNS(png_ptr, info_ptr, length);
  186475. #endif
  186476. #if defined(PNG_READ_zTXt_SUPPORTED)
  186477. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  186478. png_handle_zTXt(png_ptr, info_ptr, length);
  186479. #endif
  186480. #if defined(PNG_READ_iTXt_SUPPORTED)
  186481. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  186482. png_handle_iTXt(png_ptr, info_ptr, length);
  186483. #endif
  186484. else
  186485. png_handle_unknown(png_ptr, info_ptr, length);
  186486. }
  186487. }
  186488. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  186489. /* optional call to update the users info_ptr structure */
  186490. void PNGAPI
  186491. png_read_update_info(png_structp png_ptr, png_infop info_ptr)
  186492. {
  186493. png_debug(1, "in png_read_update_info\n");
  186494. if(png_ptr == NULL) return;
  186495. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  186496. png_read_start_row(png_ptr);
  186497. else
  186498. png_warning(png_ptr,
  186499. "Ignoring extra png_read_update_info() call; row buffer not reallocated");
  186500. png_read_transform_info(png_ptr, info_ptr);
  186501. }
  186502. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  186503. /* Initialize palette, background, etc, after transformations
  186504. * are set, but before any reading takes place. This allows
  186505. * the user to obtain a gamma-corrected palette, for example.
  186506. * If the user doesn't call this, we will do it ourselves.
  186507. */
  186508. void PNGAPI
  186509. png_start_read_image(png_structp png_ptr)
  186510. {
  186511. png_debug(1, "in png_start_read_image\n");
  186512. if(png_ptr == NULL) return;
  186513. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  186514. png_read_start_row(png_ptr);
  186515. }
  186516. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  186517. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  186518. void PNGAPI
  186519. png_read_row(png_structp png_ptr, png_bytep row, png_bytep dsp_row)
  186520. {
  186521. #ifdef PNG_USE_LOCAL_ARRAYS
  186522. PNG_CONST PNG_IDAT;
  186523. PNG_CONST int png_pass_dsp_mask[7] = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55,
  186524. 0xff};
  186525. PNG_CONST int png_pass_mask[7] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  186526. #endif
  186527. int ret;
  186528. if(png_ptr == NULL) return;
  186529. png_debug2(1, "in png_read_row (row %lu, pass %d)\n",
  186530. png_ptr->row_number, png_ptr->pass);
  186531. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  186532. png_read_start_row(png_ptr);
  186533. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  186534. {
  186535. /* check for transforms that have been set but were defined out */
  186536. #if defined(PNG_WRITE_INVERT_SUPPORTED) && !defined(PNG_READ_INVERT_SUPPORTED)
  186537. if (png_ptr->transformations & PNG_INVERT_MONO)
  186538. png_warning(png_ptr, "PNG_READ_INVERT_SUPPORTED is not defined.");
  186539. #endif
  186540. #if defined(PNG_WRITE_FILLER_SUPPORTED) && !defined(PNG_READ_FILLER_SUPPORTED)
  186541. if (png_ptr->transformations & PNG_FILLER)
  186542. png_warning(png_ptr, "PNG_READ_FILLER_SUPPORTED is not defined.");
  186543. #endif
  186544. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED) && !defined(PNG_READ_PACKSWAP_SUPPORTED)
  186545. if (png_ptr->transformations & PNG_PACKSWAP)
  186546. png_warning(png_ptr, "PNG_READ_PACKSWAP_SUPPORTED is not defined.");
  186547. #endif
  186548. #if defined(PNG_WRITE_PACK_SUPPORTED) && !defined(PNG_READ_PACK_SUPPORTED)
  186549. if (png_ptr->transformations & PNG_PACK)
  186550. png_warning(png_ptr, "PNG_READ_PACK_SUPPORTED is not defined.");
  186551. #endif
  186552. #if defined(PNG_WRITE_SHIFT_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED)
  186553. if (png_ptr->transformations & PNG_SHIFT)
  186554. png_warning(png_ptr, "PNG_READ_SHIFT_SUPPORTED is not defined.");
  186555. #endif
  186556. #if defined(PNG_WRITE_BGR_SUPPORTED) && !defined(PNG_READ_BGR_SUPPORTED)
  186557. if (png_ptr->transformations & PNG_BGR)
  186558. png_warning(png_ptr, "PNG_READ_BGR_SUPPORTED is not defined.");
  186559. #endif
  186560. #if defined(PNG_WRITE_SWAP_SUPPORTED) && !defined(PNG_READ_SWAP_SUPPORTED)
  186561. if (png_ptr->transformations & PNG_SWAP_BYTES)
  186562. png_warning(png_ptr, "PNG_READ_SWAP_SUPPORTED is not defined.");
  186563. #endif
  186564. }
  186565. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  186566. /* if interlaced and we do not need a new row, combine row and return */
  186567. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  186568. {
  186569. switch (png_ptr->pass)
  186570. {
  186571. case 0:
  186572. if (png_ptr->row_number & 0x07)
  186573. {
  186574. if (dsp_row != NULL)
  186575. png_combine_row(png_ptr, dsp_row,
  186576. png_pass_dsp_mask[png_ptr->pass]);
  186577. png_read_finish_row(png_ptr);
  186578. return;
  186579. }
  186580. break;
  186581. case 1:
  186582. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  186583. {
  186584. if (dsp_row != NULL)
  186585. png_combine_row(png_ptr, dsp_row,
  186586. png_pass_dsp_mask[png_ptr->pass]);
  186587. png_read_finish_row(png_ptr);
  186588. return;
  186589. }
  186590. break;
  186591. case 2:
  186592. if ((png_ptr->row_number & 0x07) != 4)
  186593. {
  186594. if (dsp_row != NULL && (png_ptr->row_number & 4))
  186595. png_combine_row(png_ptr, dsp_row,
  186596. png_pass_dsp_mask[png_ptr->pass]);
  186597. png_read_finish_row(png_ptr);
  186598. return;
  186599. }
  186600. break;
  186601. case 3:
  186602. if ((png_ptr->row_number & 3) || png_ptr->width < 3)
  186603. {
  186604. if (dsp_row != NULL)
  186605. png_combine_row(png_ptr, dsp_row,
  186606. png_pass_dsp_mask[png_ptr->pass]);
  186607. png_read_finish_row(png_ptr);
  186608. return;
  186609. }
  186610. break;
  186611. case 4:
  186612. if ((png_ptr->row_number & 3) != 2)
  186613. {
  186614. if (dsp_row != NULL && (png_ptr->row_number & 2))
  186615. png_combine_row(png_ptr, dsp_row,
  186616. png_pass_dsp_mask[png_ptr->pass]);
  186617. png_read_finish_row(png_ptr);
  186618. return;
  186619. }
  186620. break;
  186621. case 5:
  186622. if ((png_ptr->row_number & 1) || png_ptr->width < 2)
  186623. {
  186624. if (dsp_row != NULL)
  186625. png_combine_row(png_ptr, dsp_row,
  186626. png_pass_dsp_mask[png_ptr->pass]);
  186627. png_read_finish_row(png_ptr);
  186628. return;
  186629. }
  186630. break;
  186631. case 6:
  186632. if (!(png_ptr->row_number & 1))
  186633. {
  186634. png_read_finish_row(png_ptr);
  186635. return;
  186636. }
  186637. break;
  186638. }
  186639. }
  186640. #endif
  186641. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  186642. png_error(png_ptr, "Invalid attempt to read row data");
  186643. png_ptr->zstream.next_out = png_ptr->row_buf;
  186644. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  186645. do
  186646. {
  186647. if (!(png_ptr->zstream.avail_in))
  186648. {
  186649. while (!png_ptr->idat_size)
  186650. {
  186651. png_byte chunk_length[4];
  186652. png_crc_finish(png_ptr, 0);
  186653. png_read_data(png_ptr, chunk_length, 4);
  186654. png_ptr->idat_size = png_get_uint_31(png_ptr,chunk_length);
  186655. png_reset_crc(png_ptr);
  186656. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  186657. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  186658. png_error(png_ptr, "Not enough image data");
  186659. }
  186660. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  186661. png_ptr->zstream.next_in = png_ptr->zbuf;
  186662. if (png_ptr->zbuf_size > png_ptr->idat_size)
  186663. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  186664. png_crc_read(png_ptr, png_ptr->zbuf,
  186665. (png_size_t)png_ptr->zstream.avail_in);
  186666. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  186667. }
  186668. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  186669. if (ret == Z_STREAM_END)
  186670. {
  186671. if (png_ptr->zstream.avail_out || png_ptr->zstream.avail_in ||
  186672. png_ptr->idat_size)
  186673. png_error(png_ptr, "Extra compressed data");
  186674. png_ptr->mode |= PNG_AFTER_IDAT;
  186675. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  186676. break;
  186677. }
  186678. if (ret != Z_OK)
  186679. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  186680. "Decompression error");
  186681. } while (png_ptr->zstream.avail_out);
  186682. png_ptr->row_info.color_type = png_ptr->color_type;
  186683. png_ptr->row_info.width = png_ptr->iwidth;
  186684. png_ptr->row_info.channels = png_ptr->channels;
  186685. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  186686. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  186687. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  186688. png_ptr->row_info.width);
  186689. if(png_ptr->row_buf[0])
  186690. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  186691. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  186692. (int)(png_ptr->row_buf[0]));
  186693. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  186694. png_ptr->rowbytes + 1);
  186695. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  186696. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  186697. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  186698. {
  186699. /* Intrapixel differencing */
  186700. png_do_read_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  186701. }
  186702. #endif
  186703. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  186704. png_do_read_transformations(png_ptr);
  186705. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  186706. /* blow up interlaced rows to full size */
  186707. if (png_ptr->interlaced &&
  186708. (png_ptr->transformations & PNG_INTERLACE))
  186709. {
  186710. if (png_ptr->pass < 6)
  186711. /* old interface (pre-1.0.9):
  186712. png_do_read_interlace(&(png_ptr->row_info),
  186713. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  186714. */
  186715. png_do_read_interlace(png_ptr);
  186716. if (dsp_row != NULL)
  186717. png_combine_row(png_ptr, dsp_row,
  186718. png_pass_dsp_mask[png_ptr->pass]);
  186719. if (row != NULL)
  186720. png_combine_row(png_ptr, row,
  186721. png_pass_mask[png_ptr->pass]);
  186722. }
  186723. else
  186724. #endif
  186725. {
  186726. if (row != NULL)
  186727. png_combine_row(png_ptr, row, 0xff);
  186728. if (dsp_row != NULL)
  186729. png_combine_row(png_ptr, dsp_row, 0xff);
  186730. }
  186731. png_read_finish_row(png_ptr);
  186732. if (png_ptr->read_row_fn != NULL)
  186733. (*(png_ptr->read_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  186734. }
  186735. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  186736. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  186737. /* Read one or more rows of image data. If the image is interlaced,
  186738. * and png_set_interlace_handling() has been called, the rows need to
  186739. * contain the contents of the rows from the previous pass. If the
  186740. * image has alpha or transparency, and png_handle_alpha()[*] has been
  186741. * called, the rows contents must be initialized to the contents of the
  186742. * screen.
  186743. *
  186744. * "row" holds the actual image, and pixels are placed in it
  186745. * as they arrive. If the image is displayed after each pass, it will
  186746. * appear to "sparkle" in. "display_row" can be used to display a
  186747. * "chunky" progressive image, with finer detail added as it becomes
  186748. * available. If you do not want this "chunky" display, you may pass
  186749. * NULL for display_row. If you do not want the sparkle display, and
  186750. * you have not called png_handle_alpha(), you may pass NULL for rows.
  186751. * If you have called png_handle_alpha(), and the image has either an
  186752. * alpha channel or a transparency chunk, you must provide a buffer for
  186753. * rows. In this case, you do not have to provide a display_row buffer
  186754. * also, but you may. If the image is not interlaced, or if you have
  186755. * not called png_set_interlace_handling(), the display_row buffer will
  186756. * be ignored, so pass NULL to it.
  186757. *
  186758. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  186759. */
  186760. void PNGAPI
  186761. png_read_rows(png_structp png_ptr, png_bytepp row,
  186762. png_bytepp display_row, png_uint_32 num_rows)
  186763. {
  186764. png_uint_32 i;
  186765. png_bytepp rp;
  186766. png_bytepp dp;
  186767. png_debug(1, "in png_read_rows\n");
  186768. if(png_ptr == NULL) return;
  186769. rp = row;
  186770. dp = display_row;
  186771. if (rp != NULL && dp != NULL)
  186772. for (i = 0; i < num_rows; i++)
  186773. {
  186774. png_bytep rptr = *rp++;
  186775. png_bytep dptr = *dp++;
  186776. png_read_row(png_ptr, rptr, dptr);
  186777. }
  186778. else if(rp != NULL)
  186779. for (i = 0; i < num_rows; i++)
  186780. {
  186781. png_bytep rptr = *rp;
  186782. png_read_row(png_ptr, rptr, png_bytep_NULL);
  186783. rp++;
  186784. }
  186785. else if(dp != NULL)
  186786. for (i = 0; i < num_rows; i++)
  186787. {
  186788. png_bytep dptr = *dp;
  186789. png_read_row(png_ptr, png_bytep_NULL, dptr);
  186790. dp++;
  186791. }
  186792. }
  186793. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  186794. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  186795. /* Read the entire image. If the image has an alpha channel or a tRNS
  186796. * chunk, and you have called png_handle_alpha()[*], you will need to
  186797. * initialize the image to the current image that PNG will be overlaying.
  186798. * We set the num_rows again here, in case it was incorrectly set in
  186799. * png_read_start_row() by a call to png_read_update_info() or
  186800. * png_start_read_image() if png_set_interlace_handling() wasn't called
  186801. * prior to either of these functions like it should have been. You can
  186802. * only call this function once. If you desire to have an image for
  186803. * each pass of a interlaced image, use png_read_rows() instead.
  186804. *
  186805. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  186806. */
  186807. void PNGAPI
  186808. png_read_image(png_structp png_ptr, png_bytepp image)
  186809. {
  186810. png_uint_32 i,image_height;
  186811. int pass, j;
  186812. png_bytepp rp;
  186813. png_debug(1, "in png_read_image\n");
  186814. if(png_ptr == NULL) return;
  186815. #ifdef PNG_READ_INTERLACING_SUPPORTED
  186816. pass = png_set_interlace_handling(png_ptr);
  186817. #else
  186818. if (png_ptr->interlaced)
  186819. png_error(png_ptr,
  186820. "Cannot read interlaced image -- interlace handler disabled.");
  186821. pass = 1;
  186822. #endif
  186823. image_height=png_ptr->height;
  186824. png_ptr->num_rows = image_height; /* Make sure this is set correctly */
  186825. for (j = 0; j < pass; j++)
  186826. {
  186827. rp = image;
  186828. for (i = 0; i < image_height; i++)
  186829. {
  186830. png_read_row(png_ptr, *rp, png_bytep_NULL);
  186831. rp++;
  186832. }
  186833. }
  186834. }
  186835. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  186836. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  186837. /* Read the end of the PNG file. Will not read past the end of the
  186838. * file, will verify the end is accurate, and will read any comments
  186839. * or time information at the end of the file, if info is not NULL.
  186840. */
  186841. void PNGAPI
  186842. png_read_end(png_structp png_ptr, png_infop info_ptr)
  186843. {
  186844. png_byte chunk_length[4];
  186845. png_uint_32 length;
  186846. png_debug(1, "in png_read_end\n");
  186847. if(png_ptr == NULL) return;
  186848. png_crc_finish(png_ptr, 0); /* Finish off CRC from last IDAT chunk */
  186849. do
  186850. {
  186851. #ifdef PNG_USE_LOCAL_ARRAYS
  186852. PNG_CONST PNG_IHDR;
  186853. PNG_CONST PNG_IDAT;
  186854. PNG_CONST PNG_IEND;
  186855. PNG_CONST PNG_PLTE;
  186856. #if defined(PNG_READ_bKGD_SUPPORTED)
  186857. PNG_CONST PNG_bKGD;
  186858. #endif
  186859. #if defined(PNG_READ_cHRM_SUPPORTED)
  186860. PNG_CONST PNG_cHRM;
  186861. #endif
  186862. #if defined(PNG_READ_gAMA_SUPPORTED)
  186863. PNG_CONST PNG_gAMA;
  186864. #endif
  186865. #if defined(PNG_READ_hIST_SUPPORTED)
  186866. PNG_CONST PNG_hIST;
  186867. #endif
  186868. #if defined(PNG_READ_iCCP_SUPPORTED)
  186869. PNG_CONST PNG_iCCP;
  186870. #endif
  186871. #if defined(PNG_READ_iTXt_SUPPORTED)
  186872. PNG_CONST PNG_iTXt;
  186873. #endif
  186874. #if defined(PNG_READ_oFFs_SUPPORTED)
  186875. PNG_CONST PNG_oFFs;
  186876. #endif
  186877. #if defined(PNG_READ_pCAL_SUPPORTED)
  186878. PNG_CONST PNG_pCAL;
  186879. #endif
  186880. #if defined(PNG_READ_pHYs_SUPPORTED)
  186881. PNG_CONST PNG_pHYs;
  186882. #endif
  186883. #if defined(PNG_READ_sBIT_SUPPORTED)
  186884. PNG_CONST PNG_sBIT;
  186885. #endif
  186886. #if defined(PNG_READ_sCAL_SUPPORTED)
  186887. PNG_CONST PNG_sCAL;
  186888. #endif
  186889. #if defined(PNG_READ_sPLT_SUPPORTED)
  186890. PNG_CONST PNG_sPLT;
  186891. #endif
  186892. #if defined(PNG_READ_sRGB_SUPPORTED)
  186893. PNG_CONST PNG_sRGB;
  186894. #endif
  186895. #if defined(PNG_READ_tEXt_SUPPORTED)
  186896. PNG_CONST PNG_tEXt;
  186897. #endif
  186898. #if defined(PNG_READ_tIME_SUPPORTED)
  186899. PNG_CONST PNG_tIME;
  186900. #endif
  186901. #if defined(PNG_READ_tRNS_SUPPORTED)
  186902. PNG_CONST PNG_tRNS;
  186903. #endif
  186904. #if defined(PNG_READ_zTXt_SUPPORTED)
  186905. PNG_CONST PNG_zTXt;
  186906. #endif
  186907. #endif /* PNG_USE_LOCAL_ARRAYS */
  186908. png_read_data(png_ptr, chunk_length, 4);
  186909. length = png_get_uint_31(png_ptr,chunk_length);
  186910. png_reset_crc(png_ptr);
  186911. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  186912. png_debug1(0, "Reading %s chunk.\n", png_ptr->chunk_name);
  186913. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  186914. png_handle_IHDR(png_ptr, info_ptr, length);
  186915. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  186916. png_handle_IEND(png_ptr, info_ptr, length);
  186917. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  186918. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  186919. {
  186920. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  186921. {
  186922. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  186923. png_error(png_ptr, "Too many IDAT's found");
  186924. }
  186925. png_handle_unknown(png_ptr, info_ptr, length);
  186926. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  186927. png_ptr->mode |= PNG_HAVE_PLTE;
  186928. }
  186929. #endif
  186930. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  186931. {
  186932. /* Zero length IDATs are legal after the last IDAT has been
  186933. * read, but not after other chunks have been read.
  186934. */
  186935. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  186936. png_error(png_ptr, "Too many IDAT's found");
  186937. png_crc_finish(png_ptr, length);
  186938. }
  186939. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  186940. png_handle_PLTE(png_ptr, info_ptr, length);
  186941. #if defined(PNG_READ_bKGD_SUPPORTED)
  186942. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  186943. png_handle_bKGD(png_ptr, info_ptr, length);
  186944. #endif
  186945. #if defined(PNG_READ_cHRM_SUPPORTED)
  186946. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  186947. png_handle_cHRM(png_ptr, info_ptr, length);
  186948. #endif
  186949. #if defined(PNG_READ_gAMA_SUPPORTED)
  186950. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  186951. png_handle_gAMA(png_ptr, info_ptr, length);
  186952. #endif
  186953. #if defined(PNG_READ_hIST_SUPPORTED)
  186954. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  186955. png_handle_hIST(png_ptr, info_ptr, length);
  186956. #endif
  186957. #if defined(PNG_READ_oFFs_SUPPORTED)
  186958. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  186959. png_handle_oFFs(png_ptr, info_ptr, length);
  186960. #endif
  186961. #if defined(PNG_READ_pCAL_SUPPORTED)
  186962. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  186963. png_handle_pCAL(png_ptr, info_ptr, length);
  186964. #endif
  186965. #if defined(PNG_READ_sCAL_SUPPORTED)
  186966. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  186967. png_handle_sCAL(png_ptr, info_ptr, length);
  186968. #endif
  186969. #if defined(PNG_READ_pHYs_SUPPORTED)
  186970. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  186971. png_handle_pHYs(png_ptr, info_ptr, length);
  186972. #endif
  186973. #if defined(PNG_READ_sBIT_SUPPORTED)
  186974. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  186975. png_handle_sBIT(png_ptr, info_ptr, length);
  186976. #endif
  186977. #if defined(PNG_READ_sRGB_SUPPORTED)
  186978. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  186979. png_handle_sRGB(png_ptr, info_ptr, length);
  186980. #endif
  186981. #if defined(PNG_READ_iCCP_SUPPORTED)
  186982. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  186983. png_handle_iCCP(png_ptr, info_ptr, length);
  186984. #endif
  186985. #if defined(PNG_READ_sPLT_SUPPORTED)
  186986. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  186987. png_handle_sPLT(png_ptr, info_ptr, length);
  186988. #endif
  186989. #if defined(PNG_READ_tEXt_SUPPORTED)
  186990. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  186991. png_handle_tEXt(png_ptr, info_ptr, length);
  186992. #endif
  186993. #if defined(PNG_READ_tIME_SUPPORTED)
  186994. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  186995. png_handle_tIME(png_ptr, info_ptr, length);
  186996. #endif
  186997. #if defined(PNG_READ_tRNS_SUPPORTED)
  186998. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  186999. png_handle_tRNS(png_ptr, info_ptr, length);
  187000. #endif
  187001. #if defined(PNG_READ_zTXt_SUPPORTED)
  187002. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  187003. png_handle_zTXt(png_ptr, info_ptr, length);
  187004. #endif
  187005. #if defined(PNG_READ_iTXt_SUPPORTED)
  187006. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  187007. png_handle_iTXt(png_ptr, info_ptr, length);
  187008. #endif
  187009. else
  187010. png_handle_unknown(png_ptr, info_ptr, length);
  187011. } while (!(png_ptr->mode & PNG_HAVE_IEND));
  187012. }
  187013. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187014. /* free all memory used by the read */
  187015. void PNGAPI
  187016. png_destroy_read_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr,
  187017. png_infopp end_info_ptr_ptr)
  187018. {
  187019. png_structp png_ptr = NULL;
  187020. png_infop info_ptr = NULL, end_info_ptr = NULL;
  187021. #ifdef PNG_USER_MEM_SUPPORTED
  187022. png_free_ptr free_fn;
  187023. png_voidp mem_ptr;
  187024. #endif
  187025. png_debug(1, "in png_destroy_read_struct\n");
  187026. if (png_ptr_ptr != NULL)
  187027. png_ptr = *png_ptr_ptr;
  187028. if (info_ptr_ptr != NULL)
  187029. info_ptr = *info_ptr_ptr;
  187030. if (end_info_ptr_ptr != NULL)
  187031. end_info_ptr = *end_info_ptr_ptr;
  187032. #ifdef PNG_USER_MEM_SUPPORTED
  187033. free_fn = png_ptr->free_fn;
  187034. mem_ptr = png_ptr->mem_ptr;
  187035. #endif
  187036. png_read_destroy(png_ptr, info_ptr, end_info_ptr);
  187037. if (info_ptr != NULL)
  187038. {
  187039. #if defined(PNG_TEXT_SUPPORTED)
  187040. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, -1);
  187041. #endif
  187042. #ifdef PNG_USER_MEM_SUPPORTED
  187043. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  187044. (png_voidp)mem_ptr);
  187045. #else
  187046. png_destroy_struct((png_voidp)info_ptr);
  187047. #endif
  187048. *info_ptr_ptr = NULL;
  187049. }
  187050. if (end_info_ptr != NULL)
  187051. {
  187052. #if defined(PNG_READ_TEXT_SUPPORTED)
  187053. png_free_data(png_ptr, end_info_ptr, PNG_FREE_TEXT, -1);
  187054. #endif
  187055. #ifdef PNG_USER_MEM_SUPPORTED
  187056. png_destroy_struct_2((png_voidp)end_info_ptr, (png_free_ptr)free_fn,
  187057. (png_voidp)mem_ptr);
  187058. #else
  187059. png_destroy_struct((png_voidp)end_info_ptr);
  187060. #endif
  187061. *end_info_ptr_ptr = NULL;
  187062. }
  187063. if (png_ptr != NULL)
  187064. {
  187065. #ifdef PNG_USER_MEM_SUPPORTED
  187066. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  187067. (png_voidp)mem_ptr);
  187068. #else
  187069. png_destroy_struct((png_voidp)png_ptr);
  187070. #endif
  187071. *png_ptr_ptr = NULL;
  187072. }
  187073. }
  187074. /* free all memory used by the read (old method) */
  187075. void /* PRIVATE */
  187076. png_read_destroy(png_structp png_ptr, png_infop info_ptr, png_infop end_info_ptr)
  187077. {
  187078. #ifdef PNG_SETJMP_SUPPORTED
  187079. jmp_buf tmp_jmp;
  187080. #endif
  187081. png_error_ptr error_fn;
  187082. png_error_ptr warning_fn;
  187083. png_voidp error_ptr;
  187084. #ifdef PNG_USER_MEM_SUPPORTED
  187085. png_free_ptr free_fn;
  187086. #endif
  187087. png_debug(1, "in png_read_destroy\n");
  187088. if (info_ptr != NULL)
  187089. png_info_destroy(png_ptr, info_ptr);
  187090. if (end_info_ptr != NULL)
  187091. png_info_destroy(png_ptr, end_info_ptr);
  187092. png_free(png_ptr, png_ptr->zbuf);
  187093. png_free(png_ptr, png_ptr->big_row_buf);
  187094. png_free(png_ptr, png_ptr->prev_row);
  187095. #if defined(PNG_READ_DITHER_SUPPORTED)
  187096. png_free(png_ptr, png_ptr->palette_lookup);
  187097. png_free(png_ptr, png_ptr->dither_index);
  187098. #endif
  187099. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187100. png_free(png_ptr, png_ptr->gamma_table);
  187101. #endif
  187102. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  187103. png_free(png_ptr, png_ptr->gamma_from_1);
  187104. png_free(png_ptr, png_ptr->gamma_to_1);
  187105. #endif
  187106. #ifdef PNG_FREE_ME_SUPPORTED
  187107. if (png_ptr->free_me & PNG_FREE_PLTE)
  187108. png_zfree(png_ptr, png_ptr->palette);
  187109. png_ptr->free_me &= ~PNG_FREE_PLTE;
  187110. #else
  187111. if (png_ptr->flags & PNG_FLAG_FREE_PLTE)
  187112. png_zfree(png_ptr, png_ptr->palette);
  187113. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  187114. #endif
  187115. #if defined(PNG_tRNS_SUPPORTED) || \
  187116. defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  187117. #ifdef PNG_FREE_ME_SUPPORTED
  187118. if (png_ptr->free_me & PNG_FREE_TRNS)
  187119. png_free(png_ptr, png_ptr->trans);
  187120. png_ptr->free_me &= ~PNG_FREE_TRNS;
  187121. #else
  187122. if (png_ptr->flags & PNG_FLAG_FREE_TRNS)
  187123. png_free(png_ptr, png_ptr->trans);
  187124. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  187125. #endif
  187126. #endif
  187127. #if defined(PNG_READ_hIST_SUPPORTED)
  187128. #ifdef PNG_FREE_ME_SUPPORTED
  187129. if (png_ptr->free_me & PNG_FREE_HIST)
  187130. png_free(png_ptr, png_ptr->hist);
  187131. png_ptr->free_me &= ~PNG_FREE_HIST;
  187132. #else
  187133. if (png_ptr->flags & PNG_FLAG_FREE_HIST)
  187134. png_free(png_ptr, png_ptr->hist);
  187135. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  187136. #endif
  187137. #endif
  187138. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187139. if (png_ptr->gamma_16_table != NULL)
  187140. {
  187141. int i;
  187142. int istop = (1 << (8 - png_ptr->gamma_shift));
  187143. for (i = 0; i < istop; i++)
  187144. {
  187145. png_free(png_ptr, png_ptr->gamma_16_table[i]);
  187146. }
  187147. png_free(png_ptr, png_ptr->gamma_16_table);
  187148. }
  187149. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  187150. if (png_ptr->gamma_16_from_1 != NULL)
  187151. {
  187152. int i;
  187153. int istop = (1 << (8 - png_ptr->gamma_shift));
  187154. for (i = 0; i < istop; i++)
  187155. {
  187156. png_free(png_ptr, png_ptr->gamma_16_from_1[i]);
  187157. }
  187158. png_free(png_ptr, png_ptr->gamma_16_from_1);
  187159. }
  187160. if (png_ptr->gamma_16_to_1 != NULL)
  187161. {
  187162. int i;
  187163. int istop = (1 << (8 - png_ptr->gamma_shift));
  187164. for (i = 0; i < istop; i++)
  187165. {
  187166. png_free(png_ptr, png_ptr->gamma_16_to_1[i]);
  187167. }
  187168. png_free(png_ptr, png_ptr->gamma_16_to_1);
  187169. }
  187170. #endif
  187171. #endif
  187172. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  187173. png_free(png_ptr, png_ptr->time_buffer);
  187174. #endif
  187175. inflateEnd(&png_ptr->zstream);
  187176. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  187177. png_free(png_ptr, png_ptr->save_buffer);
  187178. #endif
  187179. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  187180. #ifdef PNG_TEXT_SUPPORTED
  187181. png_free(png_ptr, png_ptr->current_text);
  187182. #endif /* PNG_TEXT_SUPPORTED */
  187183. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  187184. /* Save the important info out of the png_struct, in case it is
  187185. * being used again.
  187186. */
  187187. #ifdef PNG_SETJMP_SUPPORTED
  187188. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  187189. #endif
  187190. error_fn = png_ptr->error_fn;
  187191. warning_fn = png_ptr->warning_fn;
  187192. error_ptr = png_ptr->error_ptr;
  187193. #ifdef PNG_USER_MEM_SUPPORTED
  187194. free_fn = png_ptr->free_fn;
  187195. #endif
  187196. png_memset(png_ptr, 0, png_sizeof (png_struct));
  187197. png_ptr->error_fn = error_fn;
  187198. png_ptr->warning_fn = warning_fn;
  187199. png_ptr->error_ptr = error_ptr;
  187200. #ifdef PNG_USER_MEM_SUPPORTED
  187201. png_ptr->free_fn = free_fn;
  187202. #endif
  187203. #ifdef PNG_SETJMP_SUPPORTED
  187204. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  187205. #endif
  187206. }
  187207. void PNGAPI
  187208. png_set_read_status_fn(png_structp png_ptr, png_read_status_ptr read_row_fn)
  187209. {
  187210. if(png_ptr == NULL) return;
  187211. png_ptr->read_row_fn = read_row_fn;
  187212. }
  187213. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187214. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  187215. void PNGAPI
  187216. png_read_png(png_structp png_ptr, png_infop info_ptr,
  187217. int transforms,
  187218. voidp params)
  187219. {
  187220. int row;
  187221. if(png_ptr == NULL) return;
  187222. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  187223. /* invert the alpha channel from opacity to transparency
  187224. */
  187225. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  187226. png_set_invert_alpha(png_ptr);
  187227. #endif
  187228. /* png_read_info() gives us all of the information from the
  187229. * PNG file before the first IDAT (image data chunk).
  187230. */
  187231. png_read_info(png_ptr, info_ptr);
  187232. if (info_ptr->height > PNG_UINT_32_MAX/png_sizeof(png_bytep))
  187233. png_error(png_ptr,"Image is too high to process with png_read_png()");
  187234. /* -------------- image transformations start here ------------------- */
  187235. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  187236. /* tell libpng to strip 16 bit/color files down to 8 bits per color
  187237. */
  187238. if (transforms & PNG_TRANSFORM_STRIP_16)
  187239. png_set_strip_16(png_ptr);
  187240. #endif
  187241. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  187242. /* Strip alpha bytes from the input data without combining with
  187243. * the background (not recommended).
  187244. */
  187245. if (transforms & PNG_TRANSFORM_STRIP_ALPHA)
  187246. png_set_strip_alpha(png_ptr);
  187247. #endif
  187248. #if defined(PNG_READ_PACK_SUPPORTED) && !defined(PNG_READ_EXPAND_SUPPORTED)
  187249. /* Extract multiple pixels with bit depths of 1, 2, or 4 from a single
  187250. * byte into separate bytes (useful for paletted and grayscale images).
  187251. */
  187252. if (transforms & PNG_TRANSFORM_PACKING)
  187253. png_set_packing(png_ptr);
  187254. #endif
  187255. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  187256. /* Change the order of packed pixels to least significant bit first
  187257. * (not useful if you are using png_set_packing).
  187258. */
  187259. if (transforms & PNG_TRANSFORM_PACKSWAP)
  187260. png_set_packswap(png_ptr);
  187261. #endif
  187262. #if defined(PNG_READ_EXPAND_SUPPORTED)
  187263. /* Expand paletted colors into true RGB triplets
  187264. * Expand grayscale images to full 8 bits from 1, 2, or 4 bits/pixel
  187265. * Expand paletted or RGB images with transparency to full alpha
  187266. * channels so the data will be available as RGBA quartets.
  187267. */
  187268. if (transforms & PNG_TRANSFORM_EXPAND)
  187269. if ((png_ptr->bit_depth < 8) ||
  187270. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) ||
  187271. (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)))
  187272. png_set_expand(png_ptr);
  187273. #endif
  187274. /* We don't handle background color or gamma transformation or dithering.
  187275. */
  187276. #if defined(PNG_READ_INVERT_SUPPORTED)
  187277. /* invert monochrome files to have 0 as white and 1 as black
  187278. */
  187279. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  187280. png_set_invert_mono(png_ptr);
  187281. #endif
  187282. #if defined(PNG_READ_SHIFT_SUPPORTED)
  187283. /* If you want to shift the pixel values from the range [0,255] or
  187284. * [0,65535] to the original [0,7] or [0,31], or whatever range the
  187285. * colors were originally in:
  187286. */
  187287. if ((transforms & PNG_TRANSFORM_SHIFT)
  187288. && png_get_valid(png_ptr, info_ptr, PNG_INFO_sBIT))
  187289. {
  187290. png_color_8p sig_bit;
  187291. png_get_sBIT(png_ptr, info_ptr, &sig_bit);
  187292. png_set_shift(png_ptr, sig_bit);
  187293. }
  187294. #endif
  187295. #if defined(PNG_READ_BGR_SUPPORTED)
  187296. /* flip the RGB pixels to BGR (or RGBA to BGRA)
  187297. */
  187298. if (transforms & PNG_TRANSFORM_BGR)
  187299. png_set_bgr(png_ptr);
  187300. #endif
  187301. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  187302. /* swap the RGBA or GA data to ARGB or AG (or BGRA to ABGR)
  187303. */
  187304. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  187305. png_set_swap_alpha(png_ptr);
  187306. #endif
  187307. #if defined(PNG_READ_SWAP_SUPPORTED)
  187308. /* swap bytes of 16 bit files to least significant byte first
  187309. */
  187310. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  187311. png_set_swap(png_ptr);
  187312. #endif
  187313. /* We don't handle adding filler bytes */
  187314. /* Optional call to gamma correct and add the background to the palette
  187315. * and update info structure. REQUIRED if you are expecting libpng to
  187316. * update the palette for you (i.e., you selected such a transform above).
  187317. */
  187318. png_read_update_info(png_ptr, info_ptr);
  187319. /* -------------- image transformations end here ------------------- */
  187320. #ifdef PNG_FREE_ME_SUPPORTED
  187321. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  187322. #endif
  187323. if(info_ptr->row_pointers == NULL)
  187324. {
  187325. info_ptr->row_pointers = (png_bytepp)png_malloc(png_ptr,
  187326. info_ptr->height * png_sizeof(png_bytep));
  187327. #ifdef PNG_FREE_ME_SUPPORTED
  187328. info_ptr->free_me |= PNG_FREE_ROWS;
  187329. #endif
  187330. for (row = 0; row < (int)info_ptr->height; row++)
  187331. {
  187332. info_ptr->row_pointers[row] = (png_bytep)png_malloc(png_ptr,
  187333. png_get_rowbytes(png_ptr, info_ptr));
  187334. }
  187335. }
  187336. png_read_image(png_ptr, info_ptr->row_pointers);
  187337. info_ptr->valid |= PNG_INFO_IDAT;
  187338. /* read rest of file, and get additional chunks in info_ptr - REQUIRED */
  187339. png_read_end(png_ptr, info_ptr);
  187340. transforms = transforms; /* quiet compiler warnings */
  187341. params = params;
  187342. }
  187343. #endif /* PNG_INFO_IMAGE_SUPPORTED */
  187344. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187345. #endif /* PNG_READ_SUPPORTED */
  187346. /*** End of inlined file: pngread.c ***/
  187347. /*** Start of inlined file: pngpread.c ***/
  187348. /* pngpread.c - read a png file in push mode
  187349. *
  187350. * Last changed in libpng 1.2.21 October 4, 2007
  187351. * For conditions of distribution and use, see copyright notice in png.h
  187352. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  187353. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  187354. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  187355. */
  187356. #define PNG_INTERNAL
  187357. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  187358. /* push model modes */
  187359. #define PNG_READ_SIG_MODE 0
  187360. #define PNG_READ_CHUNK_MODE 1
  187361. #define PNG_READ_IDAT_MODE 2
  187362. #define PNG_SKIP_MODE 3
  187363. #define PNG_READ_tEXt_MODE 4
  187364. #define PNG_READ_zTXt_MODE 5
  187365. #define PNG_READ_DONE_MODE 6
  187366. #define PNG_READ_iTXt_MODE 7
  187367. #define PNG_ERROR_MODE 8
  187368. void PNGAPI
  187369. png_process_data(png_structp png_ptr, png_infop info_ptr,
  187370. png_bytep buffer, png_size_t buffer_size)
  187371. {
  187372. if(png_ptr == NULL) return;
  187373. png_push_restore_buffer(png_ptr, buffer, buffer_size);
  187374. while (png_ptr->buffer_size)
  187375. {
  187376. png_process_some_data(png_ptr, info_ptr);
  187377. }
  187378. }
  187379. /* What we do with the incoming data depends on what we were previously
  187380. * doing before we ran out of data...
  187381. */
  187382. void /* PRIVATE */
  187383. png_process_some_data(png_structp png_ptr, png_infop info_ptr)
  187384. {
  187385. if(png_ptr == NULL) return;
  187386. switch (png_ptr->process_mode)
  187387. {
  187388. case PNG_READ_SIG_MODE:
  187389. {
  187390. png_push_read_sig(png_ptr, info_ptr);
  187391. break;
  187392. }
  187393. case PNG_READ_CHUNK_MODE:
  187394. {
  187395. png_push_read_chunk(png_ptr, info_ptr);
  187396. break;
  187397. }
  187398. case PNG_READ_IDAT_MODE:
  187399. {
  187400. png_push_read_IDAT(png_ptr);
  187401. break;
  187402. }
  187403. #if defined(PNG_READ_tEXt_SUPPORTED)
  187404. case PNG_READ_tEXt_MODE:
  187405. {
  187406. png_push_read_tEXt(png_ptr, info_ptr);
  187407. break;
  187408. }
  187409. #endif
  187410. #if defined(PNG_READ_zTXt_SUPPORTED)
  187411. case PNG_READ_zTXt_MODE:
  187412. {
  187413. png_push_read_zTXt(png_ptr, info_ptr);
  187414. break;
  187415. }
  187416. #endif
  187417. #if defined(PNG_READ_iTXt_SUPPORTED)
  187418. case PNG_READ_iTXt_MODE:
  187419. {
  187420. png_push_read_iTXt(png_ptr, info_ptr);
  187421. break;
  187422. }
  187423. #endif
  187424. case PNG_SKIP_MODE:
  187425. {
  187426. png_push_crc_finish(png_ptr);
  187427. break;
  187428. }
  187429. default:
  187430. {
  187431. png_ptr->buffer_size = 0;
  187432. break;
  187433. }
  187434. }
  187435. }
  187436. /* Read any remaining signature bytes from the stream and compare them with
  187437. * the correct PNG signature. It is possible that this routine is called
  187438. * with bytes already read from the signature, either because they have been
  187439. * checked by the calling application, or because of multiple calls to this
  187440. * routine.
  187441. */
  187442. void /* PRIVATE */
  187443. png_push_read_sig(png_structp png_ptr, png_infop info_ptr)
  187444. {
  187445. png_size_t num_checked = png_ptr->sig_bytes,
  187446. num_to_check = 8 - num_checked;
  187447. if (png_ptr->buffer_size < num_to_check)
  187448. {
  187449. num_to_check = png_ptr->buffer_size;
  187450. }
  187451. png_push_fill_buffer(png_ptr, &(info_ptr->signature[num_checked]),
  187452. num_to_check);
  187453. png_ptr->sig_bytes = (png_byte)(png_ptr->sig_bytes+num_to_check);
  187454. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  187455. {
  187456. if (num_checked < 4 &&
  187457. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  187458. png_error(png_ptr, "Not a PNG file");
  187459. else
  187460. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  187461. }
  187462. else
  187463. {
  187464. if (png_ptr->sig_bytes >= 8)
  187465. {
  187466. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  187467. }
  187468. }
  187469. }
  187470. void /* PRIVATE */
  187471. png_push_read_chunk(png_structp png_ptr, png_infop info_ptr)
  187472. {
  187473. #ifdef PNG_USE_LOCAL_ARRAYS
  187474. PNG_CONST PNG_IHDR;
  187475. PNG_CONST PNG_IDAT;
  187476. PNG_CONST PNG_IEND;
  187477. PNG_CONST PNG_PLTE;
  187478. #if defined(PNG_READ_bKGD_SUPPORTED)
  187479. PNG_CONST PNG_bKGD;
  187480. #endif
  187481. #if defined(PNG_READ_cHRM_SUPPORTED)
  187482. PNG_CONST PNG_cHRM;
  187483. #endif
  187484. #if defined(PNG_READ_gAMA_SUPPORTED)
  187485. PNG_CONST PNG_gAMA;
  187486. #endif
  187487. #if defined(PNG_READ_hIST_SUPPORTED)
  187488. PNG_CONST PNG_hIST;
  187489. #endif
  187490. #if defined(PNG_READ_iCCP_SUPPORTED)
  187491. PNG_CONST PNG_iCCP;
  187492. #endif
  187493. #if defined(PNG_READ_iTXt_SUPPORTED)
  187494. PNG_CONST PNG_iTXt;
  187495. #endif
  187496. #if defined(PNG_READ_oFFs_SUPPORTED)
  187497. PNG_CONST PNG_oFFs;
  187498. #endif
  187499. #if defined(PNG_READ_pCAL_SUPPORTED)
  187500. PNG_CONST PNG_pCAL;
  187501. #endif
  187502. #if defined(PNG_READ_pHYs_SUPPORTED)
  187503. PNG_CONST PNG_pHYs;
  187504. #endif
  187505. #if defined(PNG_READ_sBIT_SUPPORTED)
  187506. PNG_CONST PNG_sBIT;
  187507. #endif
  187508. #if defined(PNG_READ_sCAL_SUPPORTED)
  187509. PNG_CONST PNG_sCAL;
  187510. #endif
  187511. #if defined(PNG_READ_sRGB_SUPPORTED)
  187512. PNG_CONST PNG_sRGB;
  187513. #endif
  187514. #if defined(PNG_READ_sPLT_SUPPORTED)
  187515. PNG_CONST PNG_sPLT;
  187516. #endif
  187517. #if defined(PNG_READ_tEXt_SUPPORTED)
  187518. PNG_CONST PNG_tEXt;
  187519. #endif
  187520. #if defined(PNG_READ_tIME_SUPPORTED)
  187521. PNG_CONST PNG_tIME;
  187522. #endif
  187523. #if defined(PNG_READ_tRNS_SUPPORTED)
  187524. PNG_CONST PNG_tRNS;
  187525. #endif
  187526. #if defined(PNG_READ_zTXt_SUPPORTED)
  187527. PNG_CONST PNG_zTXt;
  187528. #endif
  187529. #endif /* PNG_USE_LOCAL_ARRAYS */
  187530. /* First we make sure we have enough data for the 4 byte chunk name
  187531. * and the 4 byte chunk length before proceeding with decoding the
  187532. * chunk data. To fully decode each of these chunks, we also make
  187533. * sure we have enough data in the buffer for the 4 byte CRC at the
  187534. * end of every chunk (except IDAT, which is handled separately).
  187535. */
  187536. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  187537. {
  187538. png_byte chunk_length[4];
  187539. if (png_ptr->buffer_size < 8)
  187540. {
  187541. png_push_save_buffer(png_ptr);
  187542. return;
  187543. }
  187544. png_push_fill_buffer(png_ptr, chunk_length, 4);
  187545. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  187546. png_reset_crc(png_ptr);
  187547. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187548. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  187549. }
  187550. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187551. if(png_ptr->mode & PNG_AFTER_IDAT)
  187552. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  187553. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  187554. {
  187555. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187556. {
  187557. png_push_save_buffer(png_ptr);
  187558. return;
  187559. }
  187560. png_handle_IHDR(png_ptr, info_ptr, png_ptr->push_length);
  187561. }
  187562. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  187563. {
  187564. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187565. {
  187566. png_push_save_buffer(png_ptr);
  187567. return;
  187568. }
  187569. png_handle_IEND(png_ptr, info_ptr, png_ptr->push_length);
  187570. png_ptr->process_mode = PNG_READ_DONE_MODE;
  187571. png_push_have_end(png_ptr, info_ptr);
  187572. }
  187573. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  187574. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  187575. {
  187576. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187577. {
  187578. png_push_save_buffer(png_ptr);
  187579. return;
  187580. }
  187581. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187582. png_ptr->mode |= PNG_HAVE_IDAT;
  187583. png_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  187584. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187585. png_ptr->mode |= PNG_HAVE_PLTE;
  187586. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187587. {
  187588. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  187589. png_error(png_ptr, "Missing IHDR before IDAT");
  187590. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  187591. !(png_ptr->mode & PNG_HAVE_PLTE))
  187592. png_error(png_ptr, "Missing PLTE before IDAT");
  187593. }
  187594. }
  187595. #endif
  187596. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187597. {
  187598. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187599. {
  187600. png_push_save_buffer(png_ptr);
  187601. return;
  187602. }
  187603. png_handle_PLTE(png_ptr, info_ptr, png_ptr->push_length);
  187604. }
  187605. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187606. {
  187607. /* If we reach an IDAT chunk, this means we have read all of the
  187608. * header chunks, and we can start reading the image (or if this
  187609. * is called after the image has been read - we have an error).
  187610. */
  187611. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  187612. png_error(png_ptr, "Missing IHDR before IDAT");
  187613. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  187614. !(png_ptr->mode & PNG_HAVE_PLTE))
  187615. png_error(png_ptr, "Missing PLTE before IDAT");
  187616. if (png_ptr->mode & PNG_HAVE_IDAT)
  187617. {
  187618. if (!(png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  187619. if (png_ptr->push_length == 0)
  187620. return;
  187621. if (png_ptr->mode & PNG_AFTER_IDAT)
  187622. png_error(png_ptr, "Too many IDAT's found");
  187623. }
  187624. png_ptr->idat_size = png_ptr->push_length;
  187625. png_ptr->mode |= PNG_HAVE_IDAT;
  187626. png_ptr->process_mode = PNG_READ_IDAT_MODE;
  187627. png_push_have_info(png_ptr, info_ptr);
  187628. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  187629. png_ptr->zstream.next_out = png_ptr->row_buf;
  187630. return;
  187631. }
  187632. #if defined(PNG_READ_gAMA_SUPPORTED)
  187633. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  187634. {
  187635. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187636. {
  187637. png_push_save_buffer(png_ptr);
  187638. return;
  187639. }
  187640. png_handle_gAMA(png_ptr, info_ptr, png_ptr->push_length);
  187641. }
  187642. #endif
  187643. #if defined(PNG_READ_sBIT_SUPPORTED)
  187644. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  187645. {
  187646. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187647. {
  187648. png_push_save_buffer(png_ptr);
  187649. return;
  187650. }
  187651. png_handle_sBIT(png_ptr, info_ptr, png_ptr->push_length);
  187652. }
  187653. #endif
  187654. #if defined(PNG_READ_cHRM_SUPPORTED)
  187655. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  187656. {
  187657. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187658. {
  187659. png_push_save_buffer(png_ptr);
  187660. return;
  187661. }
  187662. png_handle_cHRM(png_ptr, info_ptr, png_ptr->push_length);
  187663. }
  187664. #endif
  187665. #if defined(PNG_READ_sRGB_SUPPORTED)
  187666. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  187667. {
  187668. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187669. {
  187670. png_push_save_buffer(png_ptr);
  187671. return;
  187672. }
  187673. png_handle_sRGB(png_ptr, info_ptr, png_ptr->push_length);
  187674. }
  187675. #endif
  187676. #if defined(PNG_READ_iCCP_SUPPORTED)
  187677. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  187678. {
  187679. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187680. {
  187681. png_push_save_buffer(png_ptr);
  187682. return;
  187683. }
  187684. png_handle_iCCP(png_ptr, info_ptr, png_ptr->push_length);
  187685. }
  187686. #endif
  187687. #if defined(PNG_READ_sPLT_SUPPORTED)
  187688. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  187689. {
  187690. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187691. {
  187692. png_push_save_buffer(png_ptr);
  187693. return;
  187694. }
  187695. png_handle_sPLT(png_ptr, info_ptr, png_ptr->push_length);
  187696. }
  187697. #endif
  187698. #if defined(PNG_READ_tRNS_SUPPORTED)
  187699. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  187700. {
  187701. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187702. {
  187703. png_push_save_buffer(png_ptr);
  187704. return;
  187705. }
  187706. png_handle_tRNS(png_ptr, info_ptr, png_ptr->push_length);
  187707. }
  187708. #endif
  187709. #if defined(PNG_READ_bKGD_SUPPORTED)
  187710. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  187711. {
  187712. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187713. {
  187714. png_push_save_buffer(png_ptr);
  187715. return;
  187716. }
  187717. png_handle_bKGD(png_ptr, info_ptr, png_ptr->push_length);
  187718. }
  187719. #endif
  187720. #if defined(PNG_READ_hIST_SUPPORTED)
  187721. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  187722. {
  187723. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187724. {
  187725. png_push_save_buffer(png_ptr);
  187726. return;
  187727. }
  187728. png_handle_hIST(png_ptr, info_ptr, png_ptr->push_length);
  187729. }
  187730. #endif
  187731. #if defined(PNG_READ_pHYs_SUPPORTED)
  187732. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  187733. {
  187734. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187735. {
  187736. png_push_save_buffer(png_ptr);
  187737. return;
  187738. }
  187739. png_handle_pHYs(png_ptr, info_ptr, png_ptr->push_length);
  187740. }
  187741. #endif
  187742. #if defined(PNG_READ_oFFs_SUPPORTED)
  187743. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  187744. {
  187745. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187746. {
  187747. png_push_save_buffer(png_ptr);
  187748. return;
  187749. }
  187750. png_handle_oFFs(png_ptr, info_ptr, png_ptr->push_length);
  187751. }
  187752. #endif
  187753. #if defined(PNG_READ_pCAL_SUPPORTED)
  187754. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  187755. {
  187756. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187757. {
  187758. png_push_save_buffer(png_ptr);
  187759. return;
  187760. }
  187761. png_handle_pCAL(png_ptr, info_ptr, png_ptr->push_length);
  187762. }
  187763. #endif
  187764. #if defined(PNG_READ_sCAL_SUPPORTED)
  187765. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  187766. {
  187767. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187768. {
  187769. png_push_save_buffer(png_ptr);
  187770. return;
  187771. }
  187772. png_handle_sCAL(png_ptr, info_ptr, png_ptr->push_length);
  187773. }
  187774. #endif
  187775. #if defined(PNG_READ_tIME_SUPPORTED)
  187776. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  187777. {
  187778. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187779. {
  187780. png_push_save_buffer(png_ptr);
  187781. return;
  187782. }
  187783. png_handle_tIME(png_ptr, info_ptr, png_ptr->push_length);
  187784. }
  187785. #endif
  187786. #if defined(PNG_READ_tEXt_SUPPORTED)
  187787. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  187788. {
  187789. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187790. {
  187791. png_push_save_buffer(png_ptr);
  187792. return;
  187793. }
  187794. png_push_handle_tEXt(png_ptr, info_ptr, png_ptr->push_length);
  187795. }
  187796. #endif
  187797. #if defined(PNG_READ_zTXt_SUPPORTED)
  187798. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  187799. {
  187800. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187801. {
  187802. png_push_save_buffer(png_ptr);
  187803. return;
  187804. }
  187805. png_push_handle_zTXt(png_ptr, info_ptr, png_ptr->push_length);
  187806. }
  187807. #endif
  187808. #if defined(PNG_READ_iTXt_SUPPORTED)
  187809. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  187810. {
  187811. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187812. {
  187813. png_push_save_buffer(png_ptr);
  187814. return;
  187815. }
  187816. png_push_handle_iTXt(png_ptr, info_ptr, png_ptr->push_length);
  187817. }
  187818. #endif
  187819. else
  187820. {
  187821. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187822. {
  187823. png_push_save_buffer(png_ptr);
  187824. return;
  187825. }
  187826. png_push_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  187827. }
  187828. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  187829. }
  187830. void /* PRIVATE */
  187831. png_push_crc_skip(png_structp png_ptr, png_uint_32 skip)
  187832. {
  187833. png_ptr->process_mode = PNG_SKIP_MODE;
  187834. png_ptr->skip_length = skip;
  187835. }
  187836. void /* PRIVATE */
  187837. png_push_crc_finish(png_structp png_ptr)
  187838. {
  187839. if (png_ptr->skip_length && png_ptr->save_buffer_size)
  187840. {
  187841. png_size_t save_size;
  187842. if (png_ptr->skip_length < (png_uint_32)png_ptr->save_buffer_size)
  187843. save_size = (png_size_t)png_ptr->skip_length;
  187844. else
  187845. save_size = png_ptr->save_buffer_size;
  187846. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  187847. png_ptr->skip_length -= save_size;
  187848. png_ptr->buffer_size -= save_size;
  187849. png_ptr->save_buffer_size -= save_size;
  187850. png_ptr->save_buffer_ptr += save_size;
  187851. }
  187852. if (png_ptr->skip_length && png_ptr->current_buffer_size)
  187853. {
  187854. png_size_t save_size;
  187855. if (png_ptr->skip_length < (png_uint_32)png_ptr->current_buffer_size)
  187856. save_size = (png_size_t)png_ptr->skip_length;
  187857. else
  187858. save_size = png_ptr->current_buffer_size;
  187859. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  187860. png_ptr->skip_length -= save_size;
  187861. png_ptr->buffer_size -= save_size;
  187862. png_ptr->current_buffer_size -= save_size;
  187863. png_ptr->current_buffer_ptr += save_size;
  187864. }
  187865. if (!png_ptr->skip_length)
  187866. {
  187867. if (png_ptr->buffer_size < 4)
  187868. {
  187869. png_push_save_buffer(png_ptr);
  187870. return;
  187871. }
  187872. png_crc_finish(png_ptr, 0);
  187873. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  187874. }
  187875. }
  187876. void PNGAPI
  187877. png_push_fill_buffer(png_structp png_ptr, png_bytep buffer, png_size_t length)
  187878. {
  187879. png_bytep ptr;
  187880. if(png_ptr == NULL) return;
  187881. ptr = buffer;
  187882. if (png_ptr->save_buffer_size)
  187883. {
  187884. png_size_t save_size;
  187885. if (length < png_ptr->save_buffer_size)
  187886. save_size = length;
  187887. else
  187888. save_size = png_ptr->save_buffer_size;
  187889. png_memcpy(ptr, png_ptr->save_buffer_ptr, save_size);
  187890. length -= save_size;
  187891. ptr += save_size;
  187892. png_ptr->buffer_size -= save_size;
  187893. png_ptr->save_buffer_size -= save_size;
  187894. png_ptr->save_buffer_ptr += save_size;
  187895. }
  187896. if (length && png_ptr->current_buffer_size)
  187897. {
  187898. png_size_t save_size;
  187899. if (length < png_ptr->current_buffer_size)
  187900. save_size = length;
  187901. else
  187902. save_size = png_ptr->current_buffer_size;
  187903. png_memcpy(ptr, png_ptr->current_buffer_ptr, save_size);
  187904. png_ptr->buffer_size -= save_size;
  187905. png_ptr->current_buffer_size -= save_size;
  187906. png_ptr->current_buffer_ptr += save_size;
  187907. }
  187908. }
  187909. void /* PRIVATE */
  187910. png_push_save_buffer(png_structp png_ptr)
  187911. {
  187912. if (png_ptr->save_buffer_size)
  187913. {
  187914. if (png_ptr->save_buffer_ptr != png_ptr->save_buffer)
  187915. {
  187916. png_size_t i,istop;
  187917. png_bytep sp;
  187918. png_bytep dp;
  187919. istop = png_ptr->save_buffer_size;
  187920. for (i = 0, sp = png_ptr->save_buffer_ptr, dp = png_ptr->save_buffer;
  187921. i < istop; i++, sp++, dp++)
  187922. {
  187923. *dp = *sp;
  187924. }
  187925. }
  187926. }
  187927. if (png_ptr->save_buffer_size + png_ptr->current_buffer_size >
  187928. png_ptr->save_buffer_max)
  187929. {
  187930. png_size_t new_max;
  187931. png_bytep old_buffer;
  187932. if (png_ptr->save_buffer_size > PNG_SIZE_MAX -
  187933. (png_ptr->current_buffer_size + 256))
  187934. {
  187935. png_error(png_ptr, "Potential overflow of save_buffer");
  187936. }
  187937. new_max = png_ptr->save_buffer_size + png_ptr->current_buffer_size + 256;
  187938. old_buffer = png_ptr->save_buffer;
  187939. png_ptr->save_buffer = (png_bytep)png_malloc(png_ptr,
  187940. (png_uint_32)new_max);
  187941. png_memcpy(png_ptr->save_buffer, old_buffer, png_ptr->save_buffer_size);
  187942. png_free(png_ptr, old_buffer);
  187943. png_ptr->save_buffer_max = new_max;
  187944. }
  187945. if (png_ptr->current_buffer_size)
  187946. {
  187947. png_memcpy(png_ptr->save_buffer + png_ptr->save_buffer_size,
  187948. png_ptr->current_buffer_ptr, png_ptr->current_buffer_size);
  187949. png_ptr->save_buffer_size += png_ptr->current_buffer_size;
  187950. png_ptr->current_buffer_size = 0;
  187951. }
  187952. png_ptr->save_buffer_ptr = png_ptr->save_buffer;
  187953. png_ptr->buffer_size = 0;
  187954. }
  187955. void /* PRIVATE */
  187956. png_push_restore_buffer(png_structp png_ptr, png_bytep buffer,
  187957. png_size_t buffer_length)
  187958. {
  187959. png_ptr->current_buffer = buffer;
  187960. png_ptr->current_buffer_size = buffer_length;
  187961. png_ptr->buffer_size = buffer_length + png_ptr->save_buffer_size;
  187962. png_ptr->current_buffer_ptr = png_ptr->current_buffer;
  187963. }
  187964. void /* PRIVATE */
  187965. png_push_read_IDAT(png_structp png_ptr)
  187966. {
  187967. #ifdef PNG_USE_LOCAL_ARRAYS
  187968. PNG_CONST PNG_IDAT;
  187969. #endif
  187970. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  187971. {
  187972. png_byte chunk_length[4];
  187973. if (png_ptr->buffer_size < 8)
  187974. {
  187975. png_push_save_buffer(png_ptr);
  187976. return;
  187977. }
  187978. png_push_fill_buffer(png_ptr, chunk_length, 4);
  187979. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  187980. png_reset_crc(png_ptr);
  187981. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187982. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  187983. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187984. {
  187985. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  187986. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  187987. png_error(png_ptr, "Not enough compressed data");
  187988. return;
  187989. }
  187990. png_ptr->idat_size = png_ptr->push_length;
  187991. }
  187992. if (png_ptr->idat_size && png_ptr->save_buffer_size)
  187993. {
  187994. png_size_t save_size;
  187995. if (png_ptr->idat_size < (png_uint_32)png_ptr->save_buffer_size)
  187996. {
  187997. save_size = (png_size_t)png_ptr->idat_size;
  187998. /* check for overflow */
  187999. if((png_uint_32)save_size != png_ptr->idat_size)
  188000. png_error(png_ptr, "save_size overflowed in pngpread");
  188001. }
  188002. else
  188003. save_size = png_ptr->save_buffer_size;
  188004. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  188005. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  188006. png_process_IDAT_data(png_ptr, png_ptr->save_buffer_ptr, save_size);
  188007. png_ptr->idat_size -= save_size;
  188008. png_ptr->buffer_size -= save_size;
  188009. png_ptr->save_buffer_size -= save_size;
  188010. png_ptr->save_buffer_ptr += save_size;
  188011. }
  188012. if (png_ptr->idat_size && png_ptr->current_buffer_size)
  188013. {
  188014. png_size_t save_size;
  188015. if (png_ptr->idat_size < (png_uint_32)png_ptr->current_buffer_size)
  188016. {
  188017. save_size = (png_size_t)png_ptr->idat_size;
  188018. /* check for overflow */
  188019. if((png_uint_32)save_size != png_ptr->idat_size)
  188020. png_error(png_ptr, "save_size overflowed in pngpread");
  188021. }
  188022. else
  188023. save_size = png_ptr->current_buffer_size;
  188024. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  188025. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  188026. png_process_IDAT_data(png_ptr, png_ptr->current_buffer_ptr, save_size);
  188027. png_ptr->idat_size -= save_size;
  188028. png_ptr->buffer_size -= save_size;
  188029. png_ptr->current_buffer_size -= save_size;
  188030. png_ptr->current_buffer_ptr += save_size;
  188031. }
  188032. if (!png_ptr->idat_size)
  188033. {
  188034. if (png_ptr->buffer_size < 4)
  188035. {
  188036. png_push_save_buffer(png_ptr);
  188037. return;
  188038. }
  188039. png_crc_finish(png_ptr, 0);
  188040. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  188041. png_ptr->mode |= PNG_AFTER_IDAT;
  188042. }
  188043. }
  188044. void /* PRIVATE */
  188045. png_process_IDAT_data(png_structp png_ptr, png_bytep buffer,
  188046. png_size_t buffer_length)
  188047. {
  188048. int ret;
  188049. if ((png_ptr->flags & PNG_FLAG_ZLIB_FINISHED) && buffer_length)
  188050. png_error(png_ptr, "Extra compression data");
  188051. png_ptr->zstream.next_in = buffer;
  188052. png_ptr->zstream.avail_in = (uInt)buffer_length;
  188053. for(;;)
  188054. {
  188055. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  188056. if (ret != Z_OK)
  188057. {
  188058. if (ret == Z_STREAM_END)
  188059. {
  188060. if (png_ptr->zstream.avail_in)
  188061. png_error(png_ptr, "Extra compressed data");
  188062. if (!(png_ptr->zstream.avail_out))
  188063. {
  188064. png_push_process_row(png_ptr);
  188065. }
  188066. png_ptr->mode |= PNG_AFTER_IDAT;
  188067. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  188068. break;
  188069. }
  188070. else if (ret == Z_BUF_ERROR)
  188071. break;
  188072. else
  188073. png_error(png_ptr, "Decompression Error");
  188074. }
  188075. if (!(png_ptr->zstream.avail_out))
  188076. {
  188077. if ((
  188078. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  188079. png_ptr->interlaced && png_ptr->pass > 6) ||
  188080. (!png_ptr->interlaced &&
  188081. #endif
  188082. png_ptr->row_number == png_ptr->num_rows))
  188083. {
  188084. if (png_ptr->zstream.avail_in)
  188085. {
  188086. png_warning(png_ptr, "Too much data in IDAT chunks");
  188087. }
  188088. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  188089. break;
  188090. }
  188091. png_push_process_row(png_ptr);
  188092. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  188093. png_ptr->zstream.next_out = png_ptr->row_buf;
  188094. }
  188095. else
  188096. break;
  188097. }
  188098. }
  188099. void /* PRIVATE */
  188100. png_push_process_row(png_structp png_ptr)
  188101. {
  188102. png_ptr->row_info.color_type = png_ptr->color_type;
  188103. png_ptr->row_info.width = png_ptr->iwidth;
  188104. png_ptr->row_info.channels = png_ptr->channels;
  188105. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  188106. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  188107. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  188108. png_ptr->row_info.width);
  188109. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  188110. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  188111. (int)(png_ptr->row_buf[0]));
  188112. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  188113. png_ptr->rowbytes + 1);
  188114. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  188115. png_do_read_transformations(png_ptr);
  188116. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  188117. /* blow up interlaced rows to full size */
  188118. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  188119. {
  188120. if (png_ptr->pass < 6)
  188121. /* old interface (pre-1.0.9):
  188122. png_do_read_interlace(&(png_ptr->row_info),
  188123. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  188124. */
  188125. png_do_read_interlace(png_ptr);
  188126. switch (png_ptr->pass)
  188127. {
  188128. case 0:
  188129. {
  188130. int i;
  188131. for (i = 0; i < 8 && png_ptr->pass == 0; i++)
  188132. {
  188133. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188134. png_read_push_finish_row(png_ptr); /* updates png_ptr->pass */
  188135. }
  188136. if (png_ptr->pass == 2) /* pass 1 might be empty */
  188137. {
  188138. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  188139. {
  188140. png_push_have_row(png_ptr, png_bytep_NULL);
  188141. png_read_push_finish_row(png_ptr);
  188142. }
  188143. }
  188144. if (png_ptr->pass == 4 && png_ptr->height <= 4)
  188145. {
  188146. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  188147. {
  188148. png_push_have_row(png_ptr, png_bytep_NULL);
  188149. png_read_push_finish_row(png_ptr);
  188150. }
  188151. }
  188152. if (png_ptr->pass == 6 && png_ptr->height <= 4)
  188153. {
  188154. png_push_have_row(png_ptr, png_bytep_NULL);
  188155. png_read_push_finish_row(png_ptr);
  188156. }
  188157. break;
  188158. }
  188159. case 1:
  188160. {
  188161. int i;
  188162. for (i = 0; i < 8 && png_ptr->pass == 1; i++)
  188163. {
  188164. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188165. png_read_push_finish_row(png_ptr);
  188166. }
  188167. if (png_ptr->pass == 2) /* skip top 4 generated rows */
  188168. {
  188169. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  188170. {
  188171. png_push_have_row(png_ptr, png_bytep_NULL);
  188172. png_read_push_finish_row(png_ptr);
  188173. }
  188174. }
  188175. break;
  188176. }
  188177. case 2:
  188178. {
  188179. int i;
  188180. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  188181. {
  188182. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188183. png_read_push_finish_row(png_ptr);
  188184. }
  188185. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  188186. {
  188187. png_push_have_row(png_ptr, png_bytep_NULL);
  188188. png_read_push_finish_row(png_ptr);
  188189. }
  188190. if (png_ptr->pass == 4) /* pass 3 might be empty */
  188191. {
  188192. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  188193. {
  188194. png_push_have_row(png_ptr, png_bytep_NULL);
  188195. png_read_push_finish_row(png_ptr);
  188196. }
  188197. }
  188198. break;
  188199. }
  188200. case 3:
  188201. {
  188202. int i;
  188203. for (i = 0; i < 4 && png_ptr->pass == 3; i++)
  188204. {
  188205. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188206. png_read_push_finish_row(png_ptr);
  188207. }
  188208. if (png_ptr->pass == 4) /* skip top two generated rows */
  188209. {
  188210. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  188211. {
  188212. png_push_have_row(png_ptr, png_bytep_NULL);
  188213. png_read_push_finish_row(png_ptr);
  188214. }
  188215. }
  188216. break;
  188217. }
  188218. case 4:
  188219. {
  188220. int i;
  188221. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  188222. {
  188223. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188224. png_read_push_finish_row(png_ptr);
  188225. }
  188226. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  188227. {
  188228. png_push_have_row(png_ptr, png_bytep_NULL);
  188229. png_read_push_finish_row(png_ptr);
  188230. }
  188231. if (png_ptr->pass == 6) /* pass 5 might be empty */
  188232. {
  188233. png_push_have_row(png_ptr, png_bytep_NULL);
  188234. png_read_push_finish_row(png_ptr);
  188235. }
  188236. break;
  188237. }
  188238. case 5:
  188239. {
  188240. int i;
  188241. for (i = 0; i < 2 && png_ptr->pass == 5; i++)
  188242. {
  188243. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188244. png_read_push_finish_row(png_ptr);
  188245. }
  188246. if (png_ptr->pass == 6) /* skip top generated row */
  188247. {
  188248. png_push_have_row(png_ptr, png_bytep_NULL);
  188249. png_read_push_finish_row(png_ptr);
  188250. }
  188251. break;
  188252. }
  188253. case 6:
  188254. {
  188255. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188256. png_read_push_finish_row(png_ptr);
  188257. if (png_ptr->pass != 6)
  188258. break;
  188259. png_push_have_row(png_ptr, png_bytep_NULL);
  188260. png_read_push_finish_row(png_ptr);
  188261. }
  188262. }
  188263. }
  188264. else
  188265. #endif
  188266. {
  188267. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188268. png_read_push_finish_row(png_ptr);
  188269. }
  188270. }
  188271. void /* PRIVATE */
  188272. png_read_push_finish_row(png_structp png_ptr)
  188273. {
  188274. #ifdef PNG_USE_LOCAL_ARRAYS
  188275. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  188276. /* start of interlace block */
  188277. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  188278. /* offset to next interlace block */
  188279. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  188280. /* start of interlace block in the y direction */
  188281. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  188282. /* offset to next interlace block in the y direction */
  188283. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  188284. /* Height of interlace block. This is not currently used - if you need
  188285. * it, uncomment it here and in png.h
  188286. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  188287. */
  188288. #endif
  188289. png_ptr->row_number++;
  188290. if (png_ptr->row_number < png_ptr->num_rows)
  188291. return;
  188292. if (png_ptr->interlaced)
  188293. {
  188294. png_ptr->row_number = 0;
  188295. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  188296. png_ptr->rowbytes + 1);
  188297. do
  188298. {
  188299. png_ptr->pass++;
  188300. if ((png_ptr->pass == 1 && png_ptr->width < 5) ||
  188301. (png_ptr->pass == 3 && png_ptr->width < 3) ||
  188302. (png_ptr->pass == 5 && png_ptr->width < 2))
  188303. png_ptr->pass++;
  188304. if (png_ptr->pass > 7)
  188305. png_ptr->pass--;
  188306. if (png_ptr->pass >= 7)
  188307. break;
  188308. png_ptr->iwidth = (png_ptr->width +
  188309. png_pass_inc[png_ptr->pass] - 1 -
  188310. png_pass_start[png_ptr->pass]) /
  188311. png_pass_inc[png_ptr->pass];
  188312. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  188313. png_ptr->iwidth) + 1;
  188314. if (png_ptr->transformations & PNG_INTERLACE)
  188315. break;
  188316. png_ptr->num_rows = (png_ptr->height +
  188317. png_pass_yinc[png_ptr->pass] - 1 -
  188318. png_pass_ystart[png_ptr->pass]) /
  188319. png_pass_yinc[png_ptr->pass];
  188320. } while (png_ptr->iwidth == 0 || png_ptr->num_rows == 0);
  188321. }
  188322. }
  188323. #if defined(PNG_READ_tEXt_SUPPORTED)
  188324. void /* PRIVATE */
  188325. png_push_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  188326. length)
  188327. {
  188328. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  188329. {
  188330. png_error(png_ptr, "Out of place tEXt");
  188331. info_ptr = info_ptr; /* to quiet some compiler warnings */
  188332. }
  188333. #ifdef PNG_MAX_MALLOC_64K
  188334. png_ptr->skip_length = 0; /* This may not be necessary */
  188335. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  188336. {
  188337. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  188338. png_ptr->skip_length = length - (png_uint_32)65535L;
  188339. length = (png_uint_32)65535L;
  188340. }
  188341. #endif
  188342. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  188343. (png_uint_32)(length+1));
  188344. png_ptr->current_text[length] = '\0';
  188345. png_ptr->current_text_ptr = png_ptr->current_text;
  188346. png_ptr->current_text_size = (png_size_t)length;
  188347. png_ptr->current_text_left = (png_size_t)length;
  188348. png_ptr->process_mode = PNG_READ_tEXt_MODE;
  188349. }
  188350. void /* PRIVATE */
  188351. png_push_read_tEXt(png_structp png_ptr, png_infop info_ptr)
  188352. {
  188353. if (png_ptr->buffer_size && png_ptr->current_text_left)
  188354. {
  188355. png_size_t text_size;
  188356. if (png_ptr->buffer_size < png_ptr->current_text_left)
  188357. text_size = png_ptr->buffer_size;
  188358. else
  188359. text_size = png_ptr->current_text_left;
  188360. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  188361. png_ptr->current_text_left -= text_size;
  188362. png_ptr->current_text_ptr += text_size;
  188363. }
  188364. if (!(png_ptr->current_text_left))
  188365. {
  188366. png_textp text_ptr;
  188367. png_charp text;
  188368. png_charp key;
  188369. int ret;
  188370. if (png_ptr->buffer_size < 4)
  188371. {
  188372. png_push_save_buffer(png_ptr);
  188373. return;
  188374. }
  188375. png_push_crc_finish(png_ptr);
  188376. #if defined(PNG_MAX_MALLOC_64K)
  188377. if (png_ptr->skip_length)
  188378. return;
  188379. #endif
  188380. key = png_ptr->current_text;
  188381. for (text = key; *text; text++)
  188382. /* empty loop */ ;
  188383. if (text < key + png_ptr->current_text_size)
  188384. text++;
  188385. text_ptr = (png_textp)png_malloc(png_ptr,
  188386. (png_uint_32)png_sizeof(png_text));
  188387. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  188388. text_ptr->key = key;
  188389. #ifdef PNG_iTXt_SUPPORTED
  188390. text_ptr->lang = NULL;
  188391. text_ptr->lang_key = NULL;
  188392. #endif
  188393. text_ptr->text = text;
  188394. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  188395. png_free(png_ptr, key);
  188396. png_free(png_ptr, text_ptr);
  188397. png_ptr->current_text = NULL;
  188398. if (ret)
  188399. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  188400. }
  188401. }
  188402. #endif
  188403. #if defined(PNG_READ_zTXt_SUPPORTED)
  188404. void /* PRIVATE */
  188405. png_push_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  188406. length)
  188407. {
  188408. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  188409. {
  188410. png_error(png_ptr, "Out of place zTXt");
  188411. info_ptr = info_ptr; /* to quiet some compiler warnings */
  188412. }
  188413. #ifdef PNG_MAX_MALLOC_64K
  188414. /* We can't handle zTXt chunks > 64K, since we don't have enough space
  188415. * to be able to store the uncompressed data. Actually, the threshold
  188416. * is probably around 32K, but it isn't as definite as 64K is.
  188417. */
  188418. if (length > (png_uint_32)65535L)
  188419. {
  188420. png_warning(png_ptr, "zTXt chunk too large to fit in memory");
  188421. png_push_crc_skip(png_ptr, length);
  188422. return;
  188423. }
  188424. #endif
  188425. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  188426. (png_uint_32)(length+1));
  188427. png_ptr->current_text[length] = '\0';
  188428. png_ptr->current_text_ptr = png_ptr->current_text;
  188429. png_ptr->current_text_size = (png_size_t)length;
  188430. png_ptr->current_text_left = (png_size_t)length;
  188431. png_ptr->process_mode = PNG_READ_zTXt_MODE;
  188432. }
  188433. void /* PRIVATE */
  188434. png_push_read_zTXt(png_structp png_ptr, png_infop info_ptr)
  188435. {
  188436. if (png_ptr->buffer_size && png_ptr->current_text_left)
  188437. {
  188438. png_size_t text_size;
  188439. if (png_ptr->buffer_size < (png_uint_32)png_ptr->current_text_left)
  188440. text_size = png_ptr->buffer_size;
  188441. else
  188442. text_size = png_ptr->current_text_left;
  188443. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  188444. png_ptr->current_text_left -= text_size;
  188445. png_ptr->current_text_ptr += text_size;
  188446. }
  188447. if (!(png_ptr->current_text_left))
  188448. {
  188449. png_textp text_ptr;
  188450. png_charp text;
  188451. png_charp key;
  188452. int ret;
  188453. png_size_t text_size, key_size;
  188454. if (png_ptr->buffer_size < 4)
  188455. {
  188456. png_push_save_buffer(png_ptr);
  188457. return;
  188458. }
  188459. png_push_crc_finish(png_ptr);
  188460. key = png_ptr->current_text;
  188461. for (text = key; *text; text++)
  188462. /* empty loop */ ;
  188463. /* zTXt can't have zero text */
  188464. if (text >= key + png_ptr->current_text_size)
  188465. {
  188466. png_ptr->current_text = NULL;
  188467. png_free(png_ptr, key);
  188468. return;
  188469. }
  188470. text++;
  188471. if (*text != PNG_TEXT_COMPRESSION_zTXt) /* check compression byte */
  188472. {
  188473. png_ptr->current_text = NULL;
  188474. png_free(png_ptr, key);
  188475. return;
  188476. }
  188477. text++;
  188478. png_ptr->zstream.next_in = (png_bytep )text;
  188479. png_ptr->zstream.avail_in = (uInt)(png_ptr->current_text_size -
  188480. (text - key));
  188481. png_ptr->zstream.next_out = png_ptr->zbuf;
  188482. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  188483. key_size = text - key;
  188484. text_size = 0;
  188485. text = NULL;
  188486. ret = Z_STREAM_END;
  188487. while (png_ptr->zstream.avail_in)
  188488. {
  188489. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  188490. if (ret != Z_OK && ret != Z_STREAM_END)
  188491. {
  188492. inflateReset(&png_ptr->zstream);
  188493. png_ptr->zstream.avail_in = 0;
  188494. png_ptr->current_text = NULL;
  188495. png_free(png_ptr, key);
  188496. png_free(png_ptr, text);
  188497. return;
  188498. }
  188499. if (!(png_ptr->zstream.avail_out) || ret == Z_STREAM_END)
  188500. {
  188501. if (text == NULL)
  188502. {
  188503. text = (png_charp)png_malloc(png_ptr,
  188504. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  188505. + key_size + 1));
  188506. png_memcpy(text + key_size, png_ptr->zbuf,
  188507. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  188508. png_memcpy(text, key, key_size);
  188509. text_size = key_size + png_ptr->zbuf_size -
  188510. png_ptr->zstream.avail_out;
  188511. *(text + text_size) = '\0';
  188512. }
  188513. else
  188514. {
  188515. png_charp tmp;
  188516. tmp = text;
  188517. text = (png_charp)png_malloc(png_ptr, text_size +
  188518. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  188519. + 1));
  188520. png_memcpy(text, tmp, text_size);
  188521. png_free(png_ptr, tmp);
  188522. png_memcpy(text + text_size, png_ptr->zbuf,
  188523. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  188524. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  188525. *(text + text_size) = '\0';
  188526. }
  188527. if (ret != Z_STREAM_END)
  188528. {
  188529. png_ptr->zstream.next_out = png_ptr->zbuf;
  188530. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  188531. }
  188532. }
  188533. else
  188534. {
  188535. break;
  188536. }
  188537. if (ret == Z_STREAM_END)
  188538. break;
  188539. }
  188540. inflateReset(&png_ptr->zstream);
  188541. png_ptr->zstream.avail_in = 0;
  188542. if (ret != Z_STREAM_END)
  188543. {
  188544. png_ptr->current_text = NULL;
  188545. png_free(png_ptr, key);
  188546. png_free(png_ptr, text);
  188547. return;
  188548. }
  188549. png_ptr->current_text = NULL;
  188550. png_free(png_ptr, key);
  188551. key = text;
  188552. text += key_size;
  188553. text_ptr = (png_textp)png_malloc(png_ptr,
  188554. (png_uint_32)png_sizeof(png_text));
  188555. text_ptr->compression = PNG_TEXT_COMPRESSION_zTXt;
  188556. text_ptr->key = key;
  188557. #ifdef PNG_iTXt_SUPPORTED
  188558. text_ptr->lang = NULL;
  188559. text_ptr->lang_key = NULL;
  188560. #endif
  188561. text_ptr->text = text;
  188562. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  188563. png_free(png_ptr, key);
  188564. png_free(png_ptr, text_ptr);
  188565. if (ret)
  188566. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  188567. }
  188568. }
  188569. #endif
  188570. #if defined(PNG_READ_iTXt_SUPPORTED)
  188571. void /* PRIVATE */
  188572. png_push_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  188573. length)
  188574. {
  188575. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  188576. {
  188577. png_error(png_ptr, "Out of place iTXt");
  188578. info_ptr = info_ptr; /* to quiet some compiler warnings */
  188579. }
  188580. #ifdef PNG_MAX_MALLOC_64K
  188581. png_ptr->skip_length = 0; /* This may not be necessary */
  188582. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  188583. {
  188584. png_warning(png_ptr, "iTXt chunk too large to fit in memory");
  188585. png_ptr->skip_length = length - (png_uint_32)65535L;
  188586. length = (png_uint_32)65535L;
  188587. }
  188588. #endif
  188589. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  188590. (png_uint_32)(length+1));
  188591. png_ptr->current_text[length] = '\0';
  188592. png_ptr->current_text_ptr = png_ptr->current_text;
  188593. png_ptr->current_text_size = (png_size_t)length;
  188594. png_ptr->current_text_left = (png_size_t)length;
  188595. png_ptr->process_mode = PNG_READ_iTXt_MODE;
  188596. }
  188597. void /* PRIVATE */
  188598. png_push_read_iTXt(png_structp png_ptr, png_infop info_ptr)
  188599. {
  188600. if (png_ptr->buffer_size && png_ptr->current_text_left)
  188601. {
  188602. png_size_t text_size;
  188603. if (png_ptr->buffer_size < png_ptr->current_text_left)
  188604. text_size = png_ptr->buffer_size;
  188605. else
  188606. text_size = png_ptr->current_text_left;
  188607. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  188608. png_ptr->current_text_left -= text_size;
  188609. png_ptr->current_text_ptr += text_size;
  188610. }
  188611. if (!(png_ptr->current_text_left))
  188612. {
  188613. png_textp text_ptr;
  188614. png_charp key;
  188615. int comp_flag;
  188616. png_charp lang;
  188617. png_charp lang_key;
  188618. png_charp text;
  188619. int ret;
  188620. if (png_ptr->buffer_size < 4)
  188621. {
  188622. png_push_save_buffer(png_ptr);
  188623. return;
  188624. }
  188625. png_push_crc_finish(png_ptr);
  188626. #if defined(PNG_MAX_MALLOC_64K)
  188627. if (png_ptr->skip_length)
  188628. return;
  188629. #endif
  188630. key = png_ptr->current_text;
  188631. for (lang = key; *lang; lang++)
  188632. /* empty loop */ ;
  188633. if (lang < key + png_ptr->current_text_size - 3)
  188634. lang++;
  188635. comp_flag = *lang++;
  188636. lang++; /* skip comp_type, always zero */
  188637. for (lang_key = lang; *lang_key; lang_key++)
  188638. /* empty loop */ ;
  188639. lang_key++; /* skip NUL separator */
  188640. text=lang_key;
  188641. if (lang_key < key + png_ptr->current_text_size - 1)
  188642. {
  188643. for (; *text; text++)
  188644. /* empty loop */ ;
  188645. }
  188646. if (text < key + png_ptr->current_text_size)
  188647. text++;
  188648. text_ptr = (png_textp)png_malloc(png_ptr,
  188649. (png_uint_32)png_sizeof(png_text));
  188650. text_ptr->compression = comp_flag + 2;
  188651. text_ptr->key = key;
  188652. text_ptr->lang = lang;
  188653. text_ptr->lang_key = lang_key;
  188654. text_ptr->text = text;
  188655. text_ptr->text_length = 0;
  188656. text_ptr->itxt_length = png_strlen(text);
  188657. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  188658. png_ptr->current_text = NULL;
  188659. png_free(png_ptr, text_ptr);
  188660. if (ret)
  188661. png_warning(png_ptr, "Insufficient memory to store iTXt chunk.");
  188662. }
  188663. }
  188664. #endif
  188665. /* This function is called when we haven't found a handler for this
  188666. * chunk. If there isn't a problem with the chunk itself (ie a bad chunk
  188667. * name or a critical chunk), the chunk is (currently) silently ignored.
  188668. */
  188669. void /* PRIVATE */
  188670. png_push_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32
  188671. length)
  188672. {
  188673. png_uint_32 skip=0;
  188674. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  188675. if (!(png_ptr->chunk_name[0] & 0x20))
  188676. {
  188677. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  188678. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  188679. PNG_HANDLE_CHUNK_ALWAYS
  188680. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  188681. && png_ptr->read_user_chunk_fn == NULL
  188682. #endif
  188683. )
  188684. #endif
  188685. png_chunk_error(png_ptr, "unknown critical chunk");
  188686. info_ptr = info_ptr; /* to quiet some compiler warnings */
  188687. }
  188688. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  188689. if (png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS)
  188690. {
  188691. #ifdef PNG_MAX_MALLOC_64K
  188692. if (length > (png_uint_32)65535L)
  188693. {
  188694. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  188695. skip = length - (png_uint_32)65535L;
  188696. length = (png_uint_32)65535L;
  188697. }
  188698. #endif
  188699. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  188700. (png_charp)png_ptr->chunk_name, 5);
  188701. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  188702. png_ptr->unknown_chunk.size = (png_size_t)length;
  188703. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  188704. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  188705. if(png_ptr->read_user_chunk_fn != NULL)
  188706. {
  188707. /* callback to user unknown chunk handler */
  188708. int ret;
  188709. ret = (*(png_ptr->read_user_chunk_fn))
  188710. (png_ptr, &png_ptr->unknown_chunk);
  188711. if (ret < 0)
  188712. png_chunk_error(png_ptr, "error in user chunk");
  188713. if (ret == 0)
  188714. {
  188715. if (!(png_ptr->chunk_name[0] & 0x20))
  188716. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  188717. PNG_HANDLE_CHUNK_ALWAYS)
  188718. png_chunk_error(png_ptr, "unknown critical chunk");
  188719. png_set_unknown_chunks(png_ptr, info_ptr,
  188720. &png_ptr->unknown_chunk, 1);
  188721. }
  188722. }
  188723. #else
  188724. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  188725. #endif
  188726. png_free(png_ptr, png_ptr->unknown_chunk.data);
  188727. png_ptr->unknown_chunk.data = NULL;
  188728. }
  188729. else
  188730. #endif
  188731. skip=length;
  188732. png_push_crc_skip(png_ptr, skip);
  188733. }
  188734. void /* PRIVATE */
  188735. png_push_have_info(png_structp png_ptr, png_infop info_ptr)
  188736. {
  188737. if (png_ptr->info_fn != NULL)
  188738. (*(png_ptr->info_fn))(png_ptr, info_ptr);
  188739. }
  188740. void /* PRIVATE */
  188741. png_push_have_end(png_structp png_ptr, png_infop info_ptr)
  188742. {
  188743. if (png_ptr->end_fn != NULL)
  188744. (*(png_ptr->end_fn))(png_ptr, info_ptr);
  188745. }
  188746. void /* PRIVATE */
  188747. png_push_have_row(png_structp png_ptr, png_bytep row)
  188748. {
  188749. if (png_ptr->row_fn != NULL)
  188750. (*(png_ptr->row_fn))(png_ptr, row, png_ptr->row_number,
  188751. (int)png_ptr->pass);
  188752. }
  188753. void PNGAPI
  188754. png_progressive_combine_row (png_structp png_ptr,
  188755. png_bytep old_row, png_bytep new_row)
  188756. {
  188757. #ifdef PNG_USE_LOCAL_ARRAYS
  188758. PNG_CONST int FARDATA png_pass_dsp_mask[7] =
  188759. {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  188760. #endif
  188761. if(png_ptr == NULL) return;
  188762. if (new_row != NULL) /* new_row must == png_ptr->row_buf here. */
  188763. png_combine_row(png_ptr, old_row, png_pass_dsp_mask[png_ptr->pass]);
  188764. }
  188765. void PNGAPI
  188766. png_set_progressive_read_fn(png_structp png_ptr, png_voidp progressive_ptr,
  188767. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  188768. png_progressive_end_ptr end_fn)
  188769. {
  188770. if(png_ptr == NULL) return;
  188771. png_ptr->info_fn = info_fn;
  188772. png_ptr->row_fn = row_fn;
  188773. png_ptr->end_fn = end_fn;
  188774. png_set_read_fn(png_ptr, progressive_ptr, png_push_fill_buffer);
  188775. }
  188776. png_voidp PNGAPI
  188777. png_get_progressive_ptr(png_structp png_ptr)
  188778. {
  188779. if(png_ptr == NULL) return (NULL);
  188780. return png_ptr->io_ptr;
  188781. }
  188782. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  188783. /*** End of inlined file: pngpread.c ***/
  188784. /*** Start of inlined file: pngrio.c ***/
  188785. /* pngrio.c - functions for data input
  188786. *
  188787. * Last changed in libpng 1.2.13 November 13, 2006
  188788. * For conditions of distribution and use, see copyright notice in png.h
  188789. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  188790. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  188791. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  188792. *
  188793. * This file provides a location for all input. Users who need
  188794. * special handling are expected to write a function that has the same
  188795. * arguments as this and performs a similar function, but that possibly
  188796. * has a different input method. Note that you shouldn't change this
  188797. * function, but rather write a replacement function and then make
  188798. * libpng use it at run time with png_set_read_fn(...).
  188799. */
  188800. #define PNG_INTERNAL
  188801. #if defined(PNG_READ_SUPPORTED)
  188802. /* Read the data from whatever input you are using. The default routine
  188803. reads from a file pointer. Note that this routine sometimes gets called
  188804. with very small lengths, so you should implement some kind of simple
  188805. buffering if you are using unbuffered reads. This should never be asked
  188806. to read more then 64K on a 16 bit machine. */
  188807. void /* PRIVATE */
  188808. png_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  188809. {
  188810. png_debug1(4,"reading %d bytes\n", (int)length);
  188811. if (png_ptr->read_data_fn != NULL)
  188812. (*(png_ptr->read_data_fn))(png_ptr, data, length);
  188813. else
  188814. png_error(png_ptr, "Call to NULL read function");
  188815. }
  188816. #if !defined(PNG_NO_STDIO)
  188817. /* This is the function that does the actual reading of data. If you are
  188818. not reading from a standard C stream, you should create a replacement
  188819. read_data function and use it at run time with png_set_read_fn(), rather
  188820. than changing the library. */
  188821. #ifndef USE_FAR_KEYWORD
  188822. void PNGAPI
  188823. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  188824. {
  188825. png_size_t check;
  188826. if(png_ptr == NULL) return;
  188827. /* fread() returns 0 on error, so it is OK to store this in a png_size_t
  188828. * instead of an int, which is what fread() actually returns.
  188829. */
  188830. #if defined(_WIN32_WCE)
  188831. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  188832. check = 0;
  188833. #else
  188834. check = (png_size_t)fread(data, (png_size_t)1, length,
  188835. (png_FILE_p)png_ptr->io_ptr);
  188836. #endif
  188837. if (check != length)
  188838. png_error(png_ptr, "Read Error");
  188839. }
  188840. #else
  188841. /* this is the model-independent version. Since the standard I/O library
  188842. can't handle far buffers in the medium and small models, we have to copy
  188843. the data.
  188844. */
  188845. #define NEAR_BUF_SIZE 1024
  188846. #define MIN(a,b) (a <= b ? a : b)
  188847. static void PNGAPI
  188848. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  188849. {
  188850. int check;
  188851. png_byte *n_data;
  188852. png_FILE_p io_ptr;
  188853. if(png_ptr == NULL) return;
  188854. /* Check if data really is near. If so, use usual code. */
  188855. n_data = (png_byte *)CVT_PTR_NOCHECK(data);
  188856. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  188857. if ((png_bytep)n_data == data)
  188858. {
  188859. #if defined(_WIN32_WCE)
  188860. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  188861. check = 0;
  188862. #else
  188863. check = fread(n_data, 1, length, io_ptr);
  188864. #endif
  188865. }
  188866. else
  188867. {
  188868. png_byte buf[NEAR_BUF_SIZE];
  188869. png_size_t read, remaining, err;
  188870. check = 0;
  188871. remaining = length;
  188872. do
  188873. {
  188874. read = MIN(NEAR_BUF_SIZE, remaining);
  188875. #if defined(_WIN32_WCE)
  188876. if ( !ReadFile((HANDLE)(io_ptr), buf, read, &err, NULL) )
  188877. err = 0;
  188878. #else
  188879. err = fread(buf, (png_size_t)1, read, io_ptr);
  188880. #endif
  188881. png_memcpy(data, buf, read); /* copy far buffer to near buffer */
  188882. if(err != read)
  188883. break;
  188884. else
  188885. check += err;
  188886. data += read;
  188887. remaining -= read;
  188888. }
  188889. while (remaining != 0);
  188890. }
  188891. if ((png_uint_32)check != (png_uint_32)length)
  188892. png_error(png_ptr, "read Error");
  188893. }
  188894. #endif
  188895. #endif
  188896. /* This function allows the application to supply a new input function
  188897. for libpng if standard C streams aren't being used.
  188898. This function takes as its arguments:
  188899. png_ptr - pointer to a png input data structure
  188900. io_ptr - pointer to user supplied structure containing info about
  188901. the input functions. May be NULL.
  188902. read_data_fn - pointer to a new input function that takes as its
  188903. arguments a pointer to a png_struct, a pointer to
  188904. a location where input data can be stored, and a 32-bit
  188905. unsigned int that is the number of bytes to be read.
  188906. To exit and output any fatal error messages the new write
  188907. function should call png_error(png_ptr, "Error msg"). */
  188908. void PNGAPI
  188909. png_set_read_fn(png_structp png_ptr, png_voidp io_ptr,
  188910. png_rw_ptr read_data_fn)
  188911. {
  188912. if(png_ptr == NULL) return;
  188913. png_ptr->io_ptr = io_ptr;
  188914. #if !defined(PNG_NO_STDIO)
  188915. if (read_data_fn != NULL)
  188916. png_ptr->read_data_fn = read_data_fn;
  188917. else
  188918. png_ptr->read_data_fn = png_default_read_data;
  188919. #else
  188920. png_ptr->read_data_fn = read_data_fn;
  188921. #endif
  188922. /* It is an error to write to a read device */
  188923. if (png_ptr->write_data_fn != NULL)
  188924. {
  188925. png_ptr->write_data_fn = NULL;
  188926. png_warning(png_ptr,
  188927. "It's an error to set both read_data_fn and write_data_fn in the ");
  188928. png_warning(png_ptr,
  188929. "same structure. Resetting write_data_fn to NULL.");
  188930. }
  188931. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  188932. png_ptr->output_flush_fn = NULL;
  188933. #endif
  188934. }
  188935. #endif /* PNG_READ_SUPPORTED */
  188936. /*** End of inlined file: pngrio.c ***/
  188937. /*** Start of inlined file: pngrtran.c ***/
  188938. /* pngrtran.c - transforms the data in a row for PNG readers
  188939. *
  188940. * Last changed in libpng 1.2.21 [October 4, 2007]
  188941. * For conditions of distribution and use, see copyright notice in png.h
  188942. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  188943. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  188944. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  188945. *
  188946. * This file contains functions optionally called by an application
  188947. * in order to tell libpng how to handle data when reading a PNG.
  188948. * Transformations that are used in both reading and writing are
  188949. * in pngtrans.c.
  188950. */
  188951. #define PNG_INTERNAL
  188952. #if defined(PNG_READ_SUPPORTED)
  188953. /* Set the action on getting a CRC error for an ancillary or critical chunk. */
  188954. void PNGAPI
  188955. png_set_crc_action(png_structp png_ptr, int crit_action, int ancil_action)
  188956. {
  188957. png_debug(1, "in png_set_crc_action\n");
  188958. /* Tell libpng how we react to CRC errors in critical chunks */
  188959. if(png_ptr == NULL) return;
  188960. switch (crit_action)
  188961. {
  188962. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  188963. break;
  188964. case PNG_CRC_WARN_USE: /* warn/use data */
  188965. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  188966. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE;
  188967. break;
  188968. case PNG_CRC_QUIET_USE: /* quiet/use data */
  188969. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  188970. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE |
  188971. PNG_FLAG_CRC_CRITICAL_IGNORE;
  188972. break;
  188973. case PNG_CRC_WARN_DISCARD: /* not a valid action for critical data */
  188974. png_warning(png_ptr, "Can't discard critical data on CRC error.");
  188975. case PNG_CRC_ERROR_QUIT: /* error/quit */
  188976. case PNG_CRC_DEFAULT:
  188977. default:
  188978. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  188979. break;
  188980. }
  188981. switch (ancil_action)
  188982. {
  188983. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  188984. break;
  188985. case PNG_CRC_WARN_USE: /* warn/use data */
  188986. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  188987. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE;
  188988. break;
  188989. case PNG_CRC_QUIET_USE: /* quiet/use data */
  188990. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  188991. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE |
  188992. PNG_FLAG_CRC_ANCILLARY_NOWARN;
  188993. break;
  188994. case PNG_CRC_ERROR_QUIT: /* error/quit */
  188995. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  188996. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_NOWARN;
  188997. break;
  188998. case PNG_CRC_WARN_DISCARD: /* warn/discard data */
  188999. case PNG_CRC_DEFAULT:
  189000. default:
  189001. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  189002. break;
  189003. }
  189004. }
  189005. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  189006. defined(PNG_FLOATING_POINT_SUPPORTED)
  189007. /* handle alpha and tRNS via a background color */
  189008. void PNGAPI
  189009. png_set_background(png_structp png_ptr,
  189010. png_color_16p background_color, int background_gamma_code,
  189011. int need_expand, double background_gamma)
  189012. {
  189013. png_debug(1, "in png_set_background\n");
  189014. if(png_ptr == NULL) return;
  189015. if (background_gamma_code == PNG_BACKGROUND_GAMMA_UNKNOWN)
  189016. {
  189017. png_warning(png_ptr, "Application must supply a known background gamma");
  189018. return;
  189019. }
  189020. png_ptr->transformations |= PNG_BACKGROUND;
  189021. png_memcpy(&(png_ptr->background), background_color,
  189022. png_sizeof(png_color_16));
  189023. png_ptr->background_gamma = (float)background_gamma;
  189024. png_ptr->background_gamma_type = (png_byte)(background_gamma_code);
  189025. png_ptr->transformations |= (need_expand ? PNG_BACKGROUND_EXPAND : 0);
  189026. }
  189027. #endif
  189028. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  189029. /* strip 16 bit depth files to 8 bit depth */
  189030. void PNGAPI
  189031. png_set_strip_16(png_structp png_ptr)
  189032. {
  189033. png_debug(1, "in png_set_strip_16\n");
  189034. if(png_ptr == NULL) return;
  189035. png_ptr->transformations |= PNG_16_TO_8;
  189036. }
  189037. #endif
  189038. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  189039. void PNGAPI
  189040. png_set_strip_alpha(png_structp png_ptr)
  189041. {
  189042. png_debug(1, "in png_set_strip_alpha\n");
  189043. if(png_ptr == NULL) return;
  189044. png_ptr->flags |= PNG_FLAG_STRIP_ALPHA;
  189045. }
  189046. #endif
  189047. #if defined(PNG_READ_DITHER_SUPPORTED)
  189048. /* Dither file to 8 bit. Supply a palette, the current number
  189049. * of elements in the palette, the maximum number of elements
  189050. * allowed, and a histogram if possible. If the current number
  189051. * of colors is greater then the maximum number, the palette will be
  189052. * modified to fit in the maximum number. "full_dither" indicates
  189053. * whether we need a dithering cube set up for RGB images, or if we
  189054. * simply are reducing the number of colors in a paletted image.
  189055. */
  189056. typedef struct png_dsort_struct
  189057. {
  189058. struct png_dsort_struct FAR * next;
  189059. png_byte left;
  189060. png_byte right;
  189061. } png_dsort;
  189062. typedef png_dsort FAR * png_dsortp;
  189063. typedef png_dsort FAR * FAR * png_dsortpp;
  189064. void PNGAPI
  189065. png_set_dither(png_structp png_ptr, png_colorp palette,
  189066. int num_palette, int maximum_colors, png_uint_16p histogram,
  189067. int full_dither)
  189068. {
  189069. png_debug(1, "in png_set_dither\n");
  189070. if(png_ptr == NULL) return;
  189071. png_ptr->transformations |= PNG_DITHER;
  189072. if (!full_dither)
  189073. {
  189074. int i;
  189075. png_ptr->dither_index = (png_bytep)png_malloc(png_ptr,
  189076. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  189077. for (i = 0; i < num_palette; i++)
  189078. png_ptr->dither_index[i] = (png_byte)i;
  189079. }
  189080. if (num_palette > maximum_colors)
  189081. {
  189082. if (histogram != NULL)
  189083. {
  189084. /* This is easy enough, just throw out the least used colors.
  189085. Perhaps not the best solution, but good enough. */
  189086. int i;
  189087. /* initialize an array to sort colors */
  189088. png_ptr->dither_sort = (png_bytep)png_malloc(png_ptr,
  189089. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  189090. /* initialize the dither_sort array */
  189091. for (i = 0; i < num_palette; i++)
  189092. png_ptr->dither_sort[i] = (png_byte)i;
  189093. /* Find the least used palette entries by starting a
  189094. bubble sort, and running it until we have sorted
  189095. out enough colors. Note that we don't care about
  189096. sorting all the colors, just finding which are
  189097. least used. */
  189098. for (i = num_palette - 1; i >= maximum_colors; i--)
  189099. {
  189100. int done; /* to stop early if the list is pre-sorted */
  189101. int j;
  189102. done = 1;
  189103. for (j = 0; j < i; j++)
  189104. {
  189105. if (histogram[png_ptr->dither_sort[j]]
  189106. < histogram[png_ptr->dither_sort[j + 1]])
  189107. {
  189108. png_byte t;
  189109. t = png_ptr->dither_sort[j];
  189110. png_ptr->dither_sort[j] = png_ptr->dither_sort[j + 1];
  189111. png_ptr->dither_sort[j + 1] = t;
  189112. done = 0;
  189113. }
  189114. }
  189115. if (done)
  189116. break;
  189117. }
  189118. /* swap the palette around, and set up a table, if necessary */
  189119. if (full_dither)
  189120. {
  189121. int j = num_palette;
  189122. /* put all the useful colors within the max, but don't
  189123. move the others */
  189124. for (i = 0; i < maximum_colors; i++)
  189125. {
  189126. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  189127. {
  189128. do
  189129. j--;
  189130. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  189131. palette[i] = palette[j];
  189132. }
  189133. }
  189134. }
  189135. else
  189136. {
  189137. int j = num_palette;
  189138. /* move all the used colors inside the max limit, and
  189139. develop a translation table */
  189140. for (i = 0; i < maximum_colors; i++)
  189141. {
  189142. /* only move the colors we need to */
  189143. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  189144. {
  189145. png_color tmp_color;
  189146. do
  189147. j--;
  189148. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  189149. tmp_color = palette[j];
  189150. palette[j] = palette[i];
  189151. palette[i] = tmp_color;
  189152. /* indicate where the color went */
  189153. png_ptr->dither_index[j] = (png_byte)i;
  189154. png_ptr->dither_index[i] = (png_byte)j;
  189155. }
  189156. }
  189157. /* find closest color for those colors we are not using */
  189158. for (i = 0; i < num_palette; i++)
  189159. {
  189160. if ((int)png_ptr->dither_index[i] >= maximum_colors)
  189161. {
  189162. int min_d, k, min_k, d_index;
  189163. /* find the closest color to one we threw out */
  189164. d_index = png_ptr->dither_index[i];
  189165. min_d = PNG_COLOR_DIST(palette[d_index], palette[0]);
  189166. for (k = 1, min_k = 0; k < maximum_colors; k++)
  189167. {
  189168. int d;
  189169. d = PNG_COLOR_DIST(palette[d_index], palette[k]);
  189170. if (d < min_d)
  189171. {
  189172. min_d = d;
  189173. min_k = k;
  189174. }
  189175. }
  189176. /* point to closest color */
  189177. png_ptr->dither_index[i] = (png_byte)min_k;
  189178. }
  189179. }
  189180. }
  189181. png_free(png_ptr, png_ptr->dither_sort);
  189182. png_ptr->dither_sort=NULL;
  189183. }
  189184. else
  189185. {
  189186. /* This is much harder to do simply (and quickly). Perhaps
  189187. we need to go through a median cut routine, but those
  189188. don't always behave themselves with only a few colors
  189189. as input. So we will just find the closest two colors,
  189190. and throw out one of them (chosen somewhat randomly).
  189191. [We don't understand this at all, so if someone wants to
  189192. work on improving it, be our guest - AED, GRP]
  189193. */
  189194. int i;
  189195. int max_d;
  189196. int num_new_palette;
  189197. png_dsortp t;
  189198. png_dsortpp hash;
  189199. t=NULL;
  189200. /* initialize palette index arrays */
  189201. png_ptr->index_to_palette = (png_bytep)png_malloc(png_ptr,
  189202. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  189203. png_ptr->palette_to_index = (png_bytep)png_malloc(png_ptr,
  189204. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  189205. /* initialize the sort array */
  189206. for (i = 0; i < num_palette; i++)
  189207. {
  189208. png_ptr->index_to_palette[i] = (png_byte)i;
  189209. png_ptr->palette_to_index[i] = (png_byte)i;
  189210. }
  189211. hash = (png_dsortpp)png_malloc(png_ptr, (png_uint_32)(769 *
  189212. png_sizeof (png_dsortp)));
  189213. for (i = 0; i < 769; i++)
  189214. hash[i] = NULL;
  189215. /* png_memset(hash, 0, 769 * png_sizeof (png_dsortp)); */
  189216. num_new_palette = num_palette;
  189217. /* initial wild guess at how far apart the farthest pixel
  189218. pair we will be eliminating will be. Larger
  189219. numbers mean more areas will be allocated, Smaller
  189220. numbers run the risk of not saving enough data, and
  189221. having to do this all over again.
  189222. I have not done extensive checking on this number.
  189223. */
  189224. max_d = 96;
  189225. while (num_new_palette > maximum_colors)
  189226. {
  189227. for (i = 0; i < num_new_palette - 1; i++)
  189228. {
  189229. int j;
  189230. for (j = i + 1; j < num_new_palette; j++)
  189231. {
  189232. int d;
  189233. d = PNG_COLOR_DIST(palette[i], palette[j]);
  189234. if (d <= max_d)
  189235. {
  189236. t = (png_dsortp)png_malloc_warn(png_ptr,
  189237. (png_uint_32)(png_sizeof(png_dsort)));
  189238. if (t == NULL)
  189239. break;
  189240. t->next = hash[d];
  189241. t->left = (png_byte)i;
  189242. t->right = (png_byte)j;
  189243. hash[d] = t;
  189244. }
  189245. }
  189246. if (t == NULL)
  189247. break;
  189248. }
  189249. if (t != NULL)
  189250. for (i = 0; i <= max_d; i++)
  189251. {
  189252. if (hash[i] != NULL)
  189253. {
  189254. png_dsortp p;
  189255. for (p = hash[i]; p; p = p->next)
  189256. {
  189257. if ((int)png_ptr->index_to_palette[p->left]
  189258. < num_new_palette &&
  189259. (int)png_ptr->index_to_palette[p->right]
  189260. < num_new_palette)
  189261. {
  189262. int j, next_j;
  189263. if (num_new_palette & 0x01)
  189264. {
  189265. j = p->left;
  189266. next_j = p->right;
  189267. }
  189268. else
  189269. {
  189270. j = p->right;
  189271. next_j = p->left;
  189272. }
  189273. num_new_palette--;
  189274. palette[png_ptr->index_to_palette[j]]
  189275. = palette[num_new_palette];
  189276. if (!full_dither)
  189277. {
  189278. int k;
  189279. for (k = 0; k < num_palette; k++)
  189280. {
  189281. if (png_ptr->dither_index[k] ==
  189282. png_ptr->index_to_palette[j])
  189283. png_ptr->dither_index[k] =
  189284. png_ptr->index_to_palette[next_j];
  189285. if ((int)png_ptr->dither_index[k] ==
  189286. num_new_palette)
  189287. png_ptr->dither_index[k] =
  189288. png_ptr->index_to_palette[j];
  189289. }
  189290. }
  189291. png_ptr->index_to_palette[png_ptr->palette_to_index
  189292. [num_new_palette]] = png_ptr->index_to_palette[j];
  189293. png_ptr->palette_to_index[png_ptr->index_to_palette[j]]
  189294. = png_ptr->palette_to_index[num_new_palette];
  189295. png_ptr->index_to_palette[j] = (png_byte)num_new_palette;
  189296. png_ptr->palette_to_index[num_new_palette] = (png_byte)j;
  189297. }
  189298. if (num_new_palette <= maximum_colors)
  189299. break;
  189300. }
  189301. if (num_new_palette <= maximum_colors)
  189302. break;
  189303. }
  189304. }
  189305. for (i = 0; i < 769; i++)
  189306. {
  189307. if (hash[i] != NULL)
  189308. {
  189309. png_dsortp p = hash[i];
  189310. while (p)
  189311. {
  189312. t = p->next;
  189313. png_free(png_ptr, p);
  189314. p = t;
  189315. }
  189316. }
  189317. hash[i] = 0;
  189318. }
  189319. max_d += 96;
  189320. }
  189321. png_free(png_ptr, hash);
  189322. png_free(png_ptr, png_ptr->palette_to_index);
  189323. png_free(png_ptr, png_ptr->index_to_palette);
  189324. png_ptr->palette_to_index=NULL;
  189325. png_ptr->index_to_palette=NULL;
  189326. }
  189327. num_palette = maximum_colors;
  189328. }
  189329. if (png_ptr->palette == NULL)
  189330. {
  189331. png_ptr->palette = palette;
  189332. }
  189333. png_ptr->num_palette = (png_uint_16)num_palette;
  189334. if (full_dither)
  189335. {
  189336. int i;
  189337. png_bytep distance;
  189338. int total_bits = PNG_DITHER_RED_BITS + PNG_DITHER_GREEN_BITS +
  189339. PNG_DITHER_BLUE_BITS;
  189340. int num_red = (1 << PNG_DITHER_RED_BITS);
  189341. int num_green = (1 << PNG_DITHER_GREEN_BITS);
  189342. int num_blue = (1 << PNG_DITHER_BLUE_BITS);
  189343. png_size_t num_entries = ((png_size_t)1 << total_bits);
  189344. png_ptr->palette_lookup = (png_bytep )png_malloc(png_ptr,
  189345. (png_uint_32)(num_entries * png_sizeof (png_byte)));
  189346. png_memset(png_ptr->palette_lookup, 0, num_entries *
  189347. png_sizeof (png_byte));
  189348. distance = (png_bytep)png_malloc(png_ptr, (png_uint_32)(num_entries *
  189349. png_sizeof(png_byte)));
  189350. png_memset(distance, 0xff, num_entries * png_sizeof(png_byte));
  189351. for (i = 0; i < num_palette; i++)
  189352. {
  189353. int ir, ig, ib;
  189354. int r = (palette[i].red >> (8 - PNG_DITHER_RED_BITS));
  189355. int g = (palette[i].green >> (8 - PNG_DITHER_GREEN_BITS));
  189356. int b = (palette[i].blue >> (8 - PNG_DITHER_BLUE_BITS));
  189357. for (ir = 0; ir < num_red; ir++)
  189358. {
  189359. /* int dr = abs(ir - r); */
  189360. int dr = ((ir > r) ? ir - r : r - ir);
  189361. int index_r = (ir << (PNG_DITHER_BLUE_BITS + PNG_DITHER_GREEN_BITS));
  189362. for (ig = 0; ig < num_green; ig++)
  189363. {
  189364. /* int dg = abs(ig - g); */
  189365. int dg = ((ig > g) ? ig - g : g - ig);
  189366. int dt = dr + dg;
  189367. int dm = ((dr > dg) ? dr : dg);
  189368. int index_g = index_r | (ig << PNG_DITHER_BLUE_BITS);
  189369. for (ib = 0; ib < num_blue; ib++)
  189370. {
  189371. int d_index = index_g | ib;
  189372. /* int db = abs(ib - b); */
  189373. int db = ((ib > b) ? ib - b : b - ib);
  189374. int dmax = ((dm > db) ? dm : db);
  189375. int d = dmax + dt + db;
  189376. if (d < (int)distance[d_index])
  189377. {
  189378. distance[d_index] = (png_byte)d;
  189379. png_ptr->palette_lookup[d_index] = (png_byte)i;
  189380. }
  189381. }
  189382. }
  189383. }
  189384. }
  189385. png_free(png_ptr, distance);
  189386. }
  189387. }
  189388. #endif
  189389. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  189390. /* Transform the image from the file_gamma to the screen_gamma. We
  189391. * only do transformations on images where the file_gamma and screen_gamma
  189392. * are not close reciprocals, otherwise it slows things down slightly, and
  189393. * also needlessly introduces small errors.
  189394. *
  189395. * We will turn off gamma transformation later if no semitransparent entries
  189396. * are present in the tRNS array for palette images. We can't do it here
  189397. * because we don't necessarily have the tRNS chunk yet.
  189398. */
  189399. void PNGAPI
  189400. png_set_gamma(png_structp png_ptr, double scrn_gamma, double file_gamma)
  189401. {
  189402. png_debug(1, "in png_set_gamma\n");
  189403. if(png_ptr == NULL) return;
  189404. if ((fabs(scrn_gamma * file_gamma - 1.0) > PNG_GAMMA_THRESHOLD) ||
  189405. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA) ||
  189406. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE))
  189407. png_ptr->transformations |= PNG_GAMMA;
  189408. png_ptr->gamma = (float)file_gamma;
  189409. png_ptr->screen_gamma = (float)scrn_gamma;
  189410. }
  189411. #endif
  189412. #if defined(PNG_READ_EXPAND_SUPPORTED)
  189413. /* Expand paletted images to RGB, expand grayscale images of
  189414. * less than 8-bit depth to 8-bit depth, and expand tRNS chunks
  189415. * to alpha channels.
  189416. */
  189417. void PNGAPI
  189418. png_set_expand(png_structp png_ptr)
  189419. {
  189420. png_debug(1, "in png_set_expand\n");
  189421. if(png_ptr == NULL) return;
  189422. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  189423. #ifdef PNG_WARN_UNINITIALIZED_ROW
  189424. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  189425. #endif
  189426. }
  189427. /* GRR 19990627: the following three functions currently are identical
  189428. * to png_set_expand(). However, it is entirely reasonable that someone
  189429. * might wish to expand an indexed image to RGB but *not* expand a single,
  189430. * fully transparent palette entry to a full alpha channel--perhaps instead
  189431. * convert tRNS to the grayscale/RGB format (16-bit RGB value), or replace
  189432. * the transparent color with a particular RGB value, or drop tRNS entirely.
  189433. * IOW, a future version of the library may make the transformations flag
  189434. * a bit more fine-grained, with separate bits for each of these three
  189435. * functions.
  189436. *
  189437. * More to the point, these functions make it obvious what libpng will be
  189438. * doing, whereas "expand" can (and does) mean any number of things.
  189439. *
  189440. * GRP 20060307: In libpng-1.4.0, png_set_gray_1_2_4_to_8() was modified
  189441. * to expand only the sample depth but not to expand the tRNS to alpha.
  189442. */
  189443. /* Expand paletted images to RGB. */
  189444. void PNGAPI
  189445. png_set_palette_to_rgb(png_structp png_ptr)
  189446. {
  189447. png_debug(1, "in png_set_palette_to_rgb\n");
  189448. if(png_ptr == NULL) return;
  189449. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  189450. #ifdef PNG_WARN_UNINITIALIZED_ROW
  189451. png_ptr->flags &= !(PNG_FLAG_ROW_INIT);
  189452. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  189453. #endif
  189454. }
  189455. #if !defined(PNG_1_0_X)
  189456. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  189457. void PNGAPI
  189458. png_set_expand_gray_1_2_4_to_8(png_structp png_ptr)
  189459. {
  189460. png_debug(1, "in png_set_expand_gray_1_2_4_to_8\n");
  189461. if(png_ptr == NULL) return;
  189462. png_ptr->transformations |= PNG_EXPAND;
  189463. #ifdef PNG_WARN_UNINITIALIZED_ROW
  189464. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  189465. #endif
  189466. }
  189467. #endif
  189468. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  189469. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  189470. /* Deprecated as of libpng-1.2.9 */
  189471. void PNGAPI
  189472. png_set_gray_1_2_4_to_8(png_structp png_ptr)
  189473. {
  189474. png_debug(1, "in png_set_gray_1_2_4_to_8\n");
  189475. if(png_ptr == NULL) return;
  189476. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  189477. }
  189478. #endif
  189479. /* Expand tRNS chunks to alpha channels. */
  189480. void PNGAPI
  189481. png_set_tRNS_to_alpha(png_structp png_ptr)
  189482. {
  189483. png_debug(1, "in png_set_tRNS_to_alpha\n");
  189484. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  189485. #ifdef PNG_WARN_UNINITIALIZED_ROW
  189486. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  189487. #endif
  189488. }
  189489. #endif /* defined(PNG_READ_EXPAND_SUPPORTED) */
  189490. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  189491. void PNGAPI
  189492. png_set_gray_to_rgb(png_structp png_ptr)
  189493. {
  189494. png_debug(1, "in png_set_gray_to_rgb\n");
  189495. png_ptr->transformations |= PNG_GRAY_TO_RGB;
  189496. #ifdef PNG_WARN_UNINITIALIZED_ROW
  189497. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  189498. #endif
  189499. }
  189500. #endif
  189501. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  189502. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  189503. /* Convert a RGB image to a grayscale of the same width. This allows us,
  189504. * for example, to convert a 24 bpp RGB image into an 8 bpp grayscale image.
  189505. */
  189506. void PNGAPI
  189507. png_set_rgb_to_gray(png_structp png_ptr, int error_action, double red,
  189508. double green)
  189509. {
  189510. int red_fixed = (int)((float)red*100000.0 + 0.5);
  189511. int green_fixed = (int)((float)green*100000.0 + 0.5);
  189512. if(png_ptr == NULL) return;
  189513. png_set_rgb_to_gray_fixed(png_ptr, error_action, red_fixed, green_fixed);
  189514. }
  189515. #endif
  189516. void PNGAPI
  189517. png_set_rgb_to_gray_fixed(png_structp png_ptr, int error_action,
  189518. png_fixed_point red, png_fixed_point green)
  189519. {
  189520. png_debug(1, "in png_set_rgb_to_gray\n");
  189521. if(png_ptr == NULL) return;
  189522. switch(error_action)
  189523. {
  189524. case 1: png_ptr->transformations |= PNG_RGB_TO_GRAY;
  189525. break;
  189526. case 2: png_ptr->transformations |= PNG_RGB_TO_GRAY_WARN;
  189527. break;
  189528. case 3: png_ptr->transformations |= PNG_RGB_TO_GRAY_ERR;
  189529. }
  189530. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  189531. #if defined(PNG_READ_EXPAND_SUPPORTED)
  189532. png_ptr->transformations |= PNG_EXPAND;
  189533. #else
  189534. {
  189535. png_warning(png_ptr, "Cannot do RGB_TO_GRAY without EXPAND_SUPPORTED.");
  189536. png_ptr->transformations &= ~PNG_RGB_TO_GRAY;
  189537. }
  189538. #endif
  189539. {
  189540. png_uint_16 red_int, green_int;
  189541. if(red < 0 || green < 0)
  189542. {
  189543. red_int = 6968; /* .212671 * 32768 + .5 */
  189544. green_int = 23434; /* .715160 * 32768 + .5 */
  189545. }
  189546. else if(red + green < 100000L)
  189547. {
  189548. red_int = (png_uint_16)(((png_uint_32)red*32768L)/100000L);
  189549. green_int = (png_uint_16)(((png_uint_32)green*32768L)/100000L);
  189550. }
  189551. else
  189552. {
  189553. png_warning(png_ptr, "ignoring out of range rgb_to_gray coefficients");
  189554. red_int = 6968;
  189555. green_int = 23434;
  189556. }
  189557. png_ptr->rgb_to_gray_red_coeff = red_int;
  189558. png_ptr->rgb_to_gray_green_coeff = green_int;
  189559. png_ptr->rgb_to_gray_blue_coeff = (png_uint_16)(32768-red_int-green_int);
  189560. }
  189561. }
  189562. #endif
  189563. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  189564. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  189565. defined(PNG_LEGACY_SUPPORTED)
  189566. void PNGAPI
  189567. png_set_read_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  189568. read_user_transform_fn)
  189569. {
  189570. png_debug(1, "in png_set_read_user_transform_fn\n");
  189571. if(png_ptr == NULL) return;
  189572. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  189573. png_ptr->transformations |= PNG_USER_TRANSFORM;
  189574. png_ptr->read_user_transform_fn = read_user_transform_fn;
  189575. #endif
  189576. #ifdef PNG_LEGACY_SUPPORTED
  189577. if(read_user_transform_fn)
  189578. png_warning(png_ptr,
  189579. "This version of libpng does not support user transforms");
  189580. #endif
  189581. }
  189582. #endif
  189583. /* Initialize everything needed for the read. This includes modifying
  189584. * the palette.
  189585. */
  189586. void /* PRIVATE */
  189587. png_init_read_transformations(png_structp png_ptr)
  189588. {
  189589. png_debug(1, "in png_init_read_transformations\n");
  189590. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  189591. if(png_ptr != NULL)
  189592. #endif
  189593. {
  189594. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || defined(PNG_READ_SHIFT_SUPPORTED) \
  189595. || defined(PNG_READ_GAMMA_SUPPORTED)
  189596. int color_type = png_ptr->color_type;
  189597. #endif
  189598. #if defined(PNG_READ_EXPAND_SUPPORTED) && defined(PNG_READ_BACKGROUND_SUPPORTED)
  189599. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  189600. /* Detect gray background and attempt to enable optimization
  189601. * for gray --> RGB case */
  189602. /* Note: if PNG_BACKGROUND_EXPAND is set and color_type is either RGB or
  189603. * RGB_ALPHA (in which case need_expand is superfluous anyway), the
  189604. * background color might actually be gray yet not be flagged as such.
  189605. * This is not a problem for the current code, which uses
  189606. * PNG_BACKGROUND_IS_GRAY only to decide when to do the
  189607. * png_do_gray_to_rgb() transformation.
  189608. */
  189609. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  189610. !(color_type & PNG_COLOR_MASK_COLOR))
  189611. {
  189612. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  189613. } else if ((png_ptr->transformations & PNG_BACKGROUND) &&
  189614. !(png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  189615. (png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  189616. png_ptr->background.red == png_ptr->background.green &&
  189617. png_ptr->background.red == png_ptr->background.blue)
  189618. {
  189619. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  189620. png_ptr->background.gray = png_ptr->background.red;
  189621. }
  189622. #endif
  189623. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  189624. (png_ptr->transformations & PNG_EXPAND))
  189625. {
  189626. if (!(color_type & PNG_COLOR_MASK_COLOR)) /* i.e., GRAY or GRAY_ALPHA */
  189627. {
  189628. /* expand background and tRNS chunks */
  189629. switch (png_ptr->bit_depth)
  189630. {
  189631. case 1:
  189632. png_ptr->background.gray *= (png_uint_16)0xff;
  189633. png_ptr->background.red = png_ptr->background.green
  189634. = png_ptr->background.blue = png_ptr->background.gray;
  189635. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  189636. {
  189637. png_ptr->trans_values.gray *= (png_uint_16)0xff;
  189638. png_ptr->trans_values.red = png_ptr->trans_values.green
  189639. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  189640. }
  189641. break;
  189642. case 2:
  189643. png_ptr->background.gray *= (png_uint_16)0x55;
  189644. png_ptr->background.red = png_ptr->background.green
  189645. = png_ptr->background.blue = png_ptr->background.gray;
  189646. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  189647. {
  189648. png_ptr->trans_values.gray *= (png_uint_16)0x55;
  189649. png_ptr->trans_values.red = png_ptr->trans_values.green
  189650. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  189651. }
  189652. break;
  189653. case 4:
  189654. png_ptr->background.gray *= (png_uint_16)0x11;
  189655. png_ptr->background.red = png_ptr->background.green
  189656. = png_ptr->background.blue = png_ptr->background.gray;
  189657. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  189658. {
  189659. png_ptr->trans_values.gray *= (png_uint_16)0x11;
  189660. png_ptr->trans_values.red = png_ptr->trans_values.green
  189661. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  189662. }
  189663. break;
  189664. case 8:
  189665. case 16:
  189666. png_ptr->background.red = png_ptr->background.green
  189667. = png_ptr->background.blue = png_ptr->background.gray;
  189668. break;
  189669. }
  189670. }
  189671. else if (color_type == PNG_COLOR_TYPE_PALETTE)
  189672. {
  189673. png_ptr->background.red =
  189674. png_ptr->palette[png_ptr->background.index].red;
  189675. png_ptr->background.green =
  189676. png_ptr->palette[png_ptr->background.index].green;
  189677. png_ptr->background.blue =
  189678. png_ptr->palette[png_ptr->background.index].blue;
  189679. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  189680. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  189681. {
  189682. #if defined(PNG_READ_EXPAND_SUPPORTED)
  189683. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  189684. #endif
  189685. {
  189686. /* invert the alpha channel (in tRNS) unless the pixels are
  189687. going to be expanded, in which case leave it for later */
  189688. int i,istop;
  189689. istop=(int)png_ptr->num_trans;
  189690. for (i=0; i<istop; i++)
  189691. png_ptr->trans[i] = (png_byte)(255 - png_ptr->trans[i]);
  189692. }
  189693. }
  189694. #endif
  189695. }
  189696. }
  189697. #endif
  189698. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  189699. png_ptr->background_1 = png_ptr->background;
  189700. #endif
  189701. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  189702. if ((color_type == PNG_COLOR_TYPE_PALETTE && png_ptr->num_trans != 0)
  189703. && (fabs(png_ptr->screen_gamma * png_ptr->gamma - 1.0)
  189704. < PNG_GAMMA_THRESHOLD))
  189705. {
  189706. int i,k;
  189707. k=0;
  189708. for (i=0; i<png_ptr->num_trans; i++)
  189709. {
  189710. if (png_ptr->trans[i] != 0 && png_ptr->trans[i] != 0xff)
  189711. k=1; /* partial transparency is present */
  189712. }
  189713. if (k == 0)
  189714. png_ptr->transformations &= (~PNG_GAMMA);
  189715. }
  189716. if ((png_ptr->transformations & (PNG_GAMMA | PNG_RGB_TO_GRAY)) &&
  189717. png_ptr->gamma != 0.0)
  189718. {
  189719. png_build_gamma_table(png_ptr);
  189720. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  189721. if (png_ptr->transformations & PNG_BACKGROUND)
  189722. {
  189723. if (color_type == PNG_COLOR_TYPE_PALETTE)
  189724. {
  189725. /* could skip if no transparency and
  189726. */
  189727. png_color back, back_1;
  189728. png_colorp palette = png_ptr->palette;
  189729. int num_palette = png_ptr->num_palette;
  189730. int i;
  189731. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  189732. {
  189733. back.red = png_ptr->gamma_table[png_ptr->background.red];
  189734. back.green = png_ptr->gamma_table[png_ptr->background.green];
  189735. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  189736. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  189737. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  189738. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  189739. }
  189740. else
  189741. {
  189742. double g, gs;
  189743. switch (png_ptr->background_gamma_type)
  189744. {
  189745. case PNG_BACKGROUND_GAMMA_SCREEN:
  189746. g = (png_ptr->screen_gamma);
  189747. gs = 1.0;
  189748. break;
  189749. case PNG_BACKGROUND_GAMMA_FILE:
  189750. g = 1.0 / (png_ptr->gamma);
  189751. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  189752. break;
  189753. case PNG_BACKGROUND_GAMMA_UNIQUE:
  189754. g = 1.0 / (png_ptr->background_gamma);
  189755. gs = 1.0 / (png_ptr->background_gamma *
  189756. png_ptr->screen_gamma);
  189757. break;
  189758. default:
  189759. g = 1.0; /* back_1 */
  189760. gs = 1.0; /* back */
  189761. }
  189762. if ( fabs(gs - 1.0) < PNG_GAMMA_THRESHOLD)
  189763. {
  189764. back.red = (png_byte)png_ptr->background.red;
  189765. back.green = (png_byte)png_ptr->background.green;
  189766. back.blue = (png_byte)png_ptr->background.blue;
  189767. }
  189768. else
  189769. {
  189770. back.red = (png_byte)(pow(
  189771. (double)png_ptr->background.red/255, gs) * 255.0 + .5);
  189772. back.green = (png_byte)(pow(
  189773. (double)png_ptr->background.green/255, gs) * 255.0 + .5);
  189774. back.blue = (png_byte)(pow(
  189775. (double)png_ptr->background.blue/255, gs) * 255.0 + .5);
  189776. }
  189777. back_1.red = (png_byte)(pow(
  189778. (double)png_ptr->background.red/255, g) * 255.0 + .5);
  189779. back_1.green = (png_byte)(pow(
  189780. (double)png_ptr->background.green/255, g) * 255.0 + .5);
  189781. back_1.blue = (png_byte)(pow(
  189782. (double)png_ptr->background.blue/255, g) * 255.0 + .5);
  189783. }
  189784. for (i = 0; i < num_palette; i++)
  189785. {
  189786. if (i < (int)png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  189787. {
  189788. if (png_ptr->trans[i] == 0)
  189789. {
  189790. palette[i] = back;
  189791. }
  189792. else /* if (png_ptr->trans[i] != 0xff) */
  189793. {
  189794. png_byte v, w;
  189795. v = png_ptr->gamma_to_1[palette[i].red];
  189796. png_composite(w, v, png_ptr->trans[i], back_1.red);
  189797. palette[i].red = png_ptr->gamma_from_1[w];
  189798. v = png_ptr->gamma_to_1[palette[i].green];
  189799. png_composite(w, v, png_ptr->trans[i], back_1.green);
  189800. palette[i].green = png_ptr->gamma_from_1[w];
  189801. v = png_ptr->gamma_to_1[palette[i].blue];
  189802. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  189803. palette[i].blue = png_ptr->gamma_from_1[w];
  189804. }
  189805. }
  189806. else
  189807. {
  189808. palette[i].red = png_ptr->gamma_table[palette[i].red];
  189809. palette[i].green = png_ptr->gamma_table[palette[i].green];
  189810. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  189811. }
  189812. }
  189813. }
  189814. /* if (png_ptr->background_gamma_type!=PNG_BACKGROUND_GAMMA_UNKNOWN) */
  189815. else
  189816. /* color_type != PNG_COLOR_TYPE_PALETTE */
  189817. {
  189818. double m = (double)(((png_uint_32)1 << png_ptr->bit_depth) - 1);
  189819. double g = 1.0;
  189820. double gs = 1.0;
  189821. switch (png_ptr->background_gamma_type)
  189822. {
  189823. case PNG_BACKGROUND_GAMMA_SCREEN:
  189824. g = (png_ptr->screen_gamma);
  189825. gs = 1.0;
  189826. break;
  189827. case PNG_BACKGROUND_GAMMA_FILE:
  189828. g = 1.0 / (png_ptr->gamma);
  189829. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  189830. break;
  189831. case PNG_BACKGROUND_GAMMA_UNIQUE:
  189832. g = 1.0 / (png_ptr->background_gamma);
  189833. gs = 1.0 / (png_ptr->background_gamma *
  189834. png_ptr->screen_gamma);
  189835. break;
  189836. }
  189837. png_ptr->background_1.gray = (png_uint_16)(pow(
  189838. (double)png_ptr->background.gray / m, g) * m + .5);
  189839. png_ptr->background.gray = (png_uint_16)(pow(
  189840. (double)png_ptr->background.gray / m, gs) * m + .5);
  189841. if ((png_ptr->background.red != png_ptr->background.green) ||
  189842. (png_ptr->background.red != png_ptr->background.blue) ||
  189843. (png_ptr->background.red != png_ptr->background.gray))
  189844. {
  189845. /* RGB or RGBA with color background */
  189846. png_ptr->background_1.red = (png_uint_16)(pow(
  189847. (double)png_ptr->background.red / m, g) * m + .5);
  189848. png_ptr->background_1.green = (png_uint_16)(pow(
  189849. (double)png_ptr->background.green / m, g) * m + .5);
  189850. png_ptr->background_1.blue = (png_uint_16)(pow(
  189851. (double)png_ptr->background.blue / m, g) * m + .5);
  189852. png_ptr->background.red = (png_uint_16)(pow(
  189853. (double)png_ptr->background.red / m, gs) * m + .5);
  189854. png_ptr->background.green = (png_uint_16)(pow(
  189855. (double)png_ptr->background.green / m, gs) * m + .5);
  189856. png_ptr->background.blue = (png_uint_16)(pow(
  189857. (double)png_ptr->background.blue / m, gs) * m + .5);
  189858. }
  189859. else
  189860. {
  189861. /* GRAY, GRAY ALPHA, RGB, or RGBA with gray background */
  189862. png_ptr->background_1.red = png_ptr->background_1.green
  189863. = png_ptr->background_1.blue = png_ptr->background_1.gray;
  189864. png_ptr->background.red = png_ptr->background.green
  189865. = png_ptr->background.blue = png_ptr->background.gray;
  189866. }
  189867. }
  189868. }
  189869. else
  189870. /* transformation does not include PNG_BACKGROUND */
  189871. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  189872. if (color_type == PNG_COLOR_TYPE_PALETTE)
  189873. {
  189874. png_colorp palette = png_ptr->palette;
  189875. int num_palette = png_ptr->num_palette;
  189876. int i;
  189877. for (i = 0; i < num_palette; i++)
  189878. {
  189879. palette[i].red = png_ptr->gamma_table[palette[i].red];
  189880. palette[i].green = png_ptr->gamma_table[palette[i].green];
  189881. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  189882. }
  189883. }
  189884. }
  189885. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  189886. else
  189887. #endif
  189888. #endif /* PNG_READ_GAMMA_SUPPORTED && PNG_FLOATING_POINT_SUPPORTED */
  189889. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  189890. /* No GAMMA transformation */
  189891. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  189892. (color_type == PNG_COLOR_TYPE_PALETTE))
  189893. {
  189894. int i;
  189895. int istop = (int)png_ptr->num_trans;
  189896. png_color back;
  189897. png_colorp palette = png_ptr->palette;
  189898. back.red = (png_byte)png_ptr->background.red;
  189899. back.green = (png_byte)png_ptr->background.green;
  189900. back.blue = (png_byte)png_ptr->background.blue;
  189901. for (i = 0; i < istop; i++)
  189902. {
  189903. if (png_ptr->trans[i] == 0)
  189904. {
  189905. palette[i] = back;
  189906. }
  189907. else if (png_ptr->trans[i] != 0xff)
  189908. {
  189909. /* The png_composite() macro is defined in png.h */
  189910. png_composite(palette[i].red, palette[i].red,
  189911. png_ptr->trans[i], back.red);
  189912. png_composite(palette[i].green, palette[i].green,
  189913. png_ptr->trans[i], back.green);
  189914. png_composite(palette[i].blue, palette[i].blue,
  189915. png_ptr->trans[i], back.blue);
  189916. }
  189917. }
  189918. }
  189919. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  189920. #if defined(PNG_READ_SHIFT_SUPPORTED)
  189921. if ((png_ptr->transformations & PNG_SHIFT) &&
  189922. (color_type == PNG_COLOR_TYPE_PALETTE))
  189923. {
  189924. png_uint_16 i;
  189925. png_uint_16 istop = png_ptr->num_palette;
  189926. int sr = 8 - png_ptr->sig_bit.red;
  189927. int sg = 8 - png_ptr->sig_bit.green;
  189928. int sb = 8 - png_ptr->sig_bit.blue;
  189929. if (sr < 0 || sr > 8)
  189930. sr = 0;
  189931. if (sg < 0 || sg > 8)
  189932. sg = 0;
  189933. if (sb < 0 || sb > 8)
  189934. sb = 0;
  189935. for (i = 0; i < istop; i++)
  189936. {
  189937. png_ptr->palette[i].red >>= sr;
  189938. png_ptr->palette[i].green >>= sg;
  189939. png_ptr->palette[i].blue >>= sb;
  189940. }
  189941. }
  189942. #endif /* PNG_READ_SHIFT_SUPPORTED */
  189943. }
  189944. #if !defined(PNG_READ_GAMMA_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED) \
  189945. && !defined(PNG_READ_BACKGROUND_SUPPORTED)
  189946. if(png_ptr)
  189947. return;
  189948. #endif
  189949. }
  189950. /* Modify the info structure to reflect the transformations. The
  189951. * info should be updated so a PNG file could be written with it,
  189952. * assuming the transformations result in valid PNG data.
  189953. */
  189954. void /* PRIVATE */
  189955. png_read_transform_info(png_structp png_ptr, png_infop info_ptr)
  189956. {
  189957. png_debug(1, "in png_read_transform_info\n");
  189958. #if defined(PNG_READ_EXPAND_SUPPORTED)
  189959. if (png_ptr->transformations & PNG_EXPAND)
  189960. {
  189961. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  189962. {
  189963. if (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND_tRNS))
  189964. info_ptr->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  189965. else
  189966. info_ptr->color_type = PNG_COLOR_TYPE_RGB;
  189967. info_ptr->bit_depth = 8;
  189968. info_ptr->num_trans = 0;
  189969. }
  189970. else
  189971. {
  189972. if (png_ptr->num_trans)
  189973. {
  189974. if (png_ptr->transformations & PNG_EXPAND_tRNS)
  189975. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  189976. else
  189977. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  189978. }
  189979. if (info_ptr->bit_depth < 8)
  189980. info_ptr->bit_depth = 8;
  189981. info_ptr->num_trans = 0;
  189982. }
  189983. }
  189984. #endif
  189985. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  189986. if (png_ptr->transformations & PNG_BACKGROUND)
  189987. {
  189988. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  189989. info_ptr->num_trans = 0;
  189990. info_ptr->background = png_ptr->background;
  189991. }
  189992. #endif
  189993. #if defined(PNG_READ_GAMMA_SUPPORTED)
  189994. if (png_ptr->transformations & PNG_GAMMA)
  189995. {
  189996. #ifdef PNG_FLOATING_POINT_SUPPORTED
  189997. info_ptr->gamma = png_ptr->gamma;
  189998. #endif
  189999. #ifdef PNG_FIXED_POINT_SUPPORTED
  190000. info_ptr->int_gamma = png_ptr->int_gamma;
  190001. #endif
  190002. }
  190003. #endif
  190004. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  190005. if ((png_ptr->transformations & PNG_16_TO_8) && (info_ptr->bit_depth == 16))
  190006. info_ptr->bit_depth = 8;
  190007. #endif
  190008. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190009. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  190010. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  190011. #endif
  190012. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  190013. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  190014. info_ptr->color_type &= ~PNG_COLOR_MASK_COLOR;
  190015. #endif
  190016. #if defined(PNG_READ_DITHER_SUPPORTED)
  190017. if (png_ptr->transformations & PNG_DITHER)
  190018. {
  190019. if (((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  190020. (info_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)) &&
  190021. png_ptr->palette_lookup && info_ptr->bit_depth == 8)
  190022. {
  190023. info_ptr->color_type = PNG_COLOR_TYPE_PALETTE;
  190024. }
  190025. }
  190026. #endif
  190027. #if defined(PNG_READ_PACK_SUPPORTED)
  190028. if ((png_ptr->transformations & PNG_PACK) && (info_ptr->bit_depth < 8))
  190029. info_ptr->bit_depth = 8;
  190030. #endif
  190031. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190032. info_ptr->channels = 1;
  190033. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  190034. info_ptr->channels = 3;
  190035. else
  190036. info_ptr->channels = 1;
  190037. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  190038. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  190039. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  190040. #endif
  190041. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  190042. info_ptr->channels++;
  190043. #if defined(PNG_READ_FILLER_SUPPORTED)
  190044. /* STRIP_ALPHA and FILLER allowed: MASK_ALPHA bit stripped above */
  190045. if ((png_ptr->transformations & PNG_FILLER) &&
  190046. ((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  190047. (info_ptr->color_type == PNG_COLOR_TYPE_GRAY)))
  190048. {
  190049. info_ptr->channels++;
  190050. /* if adding a true alpha channel not just filler */
  190051. #if !defined(PNG_1_0_X)
  190052. if (png_ptr->transformations & PNG_ADD_ALPHA)
  190053. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  190054. #endif
  190055. }
  190056. #endif
  190057. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED) && \
  190058. defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  190059. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  190060. {
  190061. if(info_ptr->bit_depth < png_ptr->user_transform_depth)
  190062. info_ptr->bit_depth = png_ptr->user_transform_depth;
  190063. if(info_ptr->channels < png_ptr->user_transform_channels)
  190064. info_ptr->channels = png_ptr->user_transform_channels;
  190065. }
  190066. #endif
  190067. info_ptr->pixel_depth = (png_byte)(info_ptr->channels *
  190068. info_ptr->bit_depth);
  190069. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,info_ptr->width);
  190070. #if !defined(PNG_READ_EXPAND_SUPPORTED)
  190071. if(png_ptr)
  190072. return;
  190073. #endif
  190074. }
  190075. /* Transform the row. The order of transformations is significant,
  190076. * and is very touchy. If you add a transformation, take care to
  190077. * decide how it fits in with the other transformations here.
  190078. */
  190079. void /* PRIVATE */
  190080. png_do_read_transformations(png_structp png_ptr)
  190081. {
  190082. png_debug(1, "in png_do_read_transformations\n");
  190083. if (png_ptr->row_buf == NULL)
  190084. {
  190085. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  190086. char msg[50];
  190087. png_snprintf2(msg, 50,
  190088. "NULL row buffer for row %ld, pass %d", png_ptr->row_number,
  190089. png_ptr->pass);
  190090. png_error(png_ptr, msg);
  190091. #else
  190092. png_error(png_ptr, "NULL row buffer");
  190093. #endif
  190094. }
  190095. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190096. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  190097. /* Application has failed to call either png_read_start_image()
  190098. * or png_read_update_info() after setting transforms that expand
  190099. * pixels. This check added to libpng-1.2.19 */
  190100. #if (PNG_WARN_UNINITIALIZED_ROW==1)
  190101. png_error(png_ptr, "Uninitialized row");
  190102. #else
  190103. png_warning(png_ptr, "Uninitialized row");
  190104. #endif
  190105. #endif
  190106. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190107. if (png_ptr->transformations & PNG_EXPAND)
  190108. {
  190109. if (png_ptr->row_info.color_type == PNG_COLOR_TYPE_PALETTE)
  190110. {
  190111. png_do_expand_palette(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190112. png_ptr->palette, png_ptr->trans, png_ptr->num_trans);
  190113. }
  190114. else
  190115. {
  190116. if (png_ptr->num_trans &&
  190117. (png_ptr->transformations & PNG_EXPAND_tRNS))
  190118. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190119. &(png_ptr->trans_values));
  190120. else
  190121. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190122. NULL);
  190123. }
  190124. }
  190125. #endif
  190126. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  190127. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  190128. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190129. PNG_FLAG_FILLER_AFTER | (png_ptr->flags & PNG_FLAG_STRIP_ALPHA));
  190130. #endif
  190131. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  190132. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  190133. {
  190134. int rgb_error =
  190135. png_do_rgb_to_gray(png_ptr, &(png_ptr->row_info), png_ptr->row_buf + 1);
  190136. if(rgb_error)
  190137. {
  190138. png_ptr->rgb_to_gray_status=1;
  190139. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  190140. PNG_RGB_TO_GRAY_WARN)
  190141. png_warning(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  190142. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  190143. PNG_RGB_TO_GRAY_ERR)
  190144. png_error(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  190145. }
  190146. }
  190147. #endif
  190148. /*
  190149. From Andreas Dilger e-mail to png-implement, 26 March 1998:
  190150. In most cases, the "simple transparency" should be done prior to doing
  190151. gray-to-RGB, or you will have to test 3x as many bytes to check if a
  190152. pixel is transparent. You would also need to make sure that the
  190153. transparency information is upgraded to RGB.
  190154. To summarize, the current flow is:
  190155. - Gray + simple transparency -> compare 1 or 2 gray bytes and composite
  190156. with background "in place" if transparent,
  190157. convert to RGB if necessary
  190158. - Gray + alpha -> composite with gray background and remove alpha bytes,
  190159. convert to RGB if necessary
  190160. To support RGB backgrounds for gray images we need:
  190161. - Gray + simple transparency -> convert to RGB + simple transparency, compare
  190162. 3 or 6 bytes and composite with background
  190163. "in place" if transparent (3x compare/pixel
  190164. compared to doing composite with gray bkgrnd)
  190165. - Gray + alpha -> convert to RGB + alpha, composite with background and
  190166. remove alpha bytes (3x float operations/pixel
  190167. compared with composite on gray background)
  190168. Greg's change will do this. The reason it wasn't done before is for
  190169. performance, as this increases the per-pixel operations. If we would check
  190170. in advance if the background was gray or RGB, and position the gray-to-RGB
  190171. transform appropriately, then it would save a lot of work/time.
  190172. */
  190173. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190174. /* if gray -> RGB, do so now only if background is non-gray; else do later
  190175. * for performance reasons */
  190176. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  190177. !(png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  190178. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190179. #endif
  190180. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190181. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  190182. ((png_ptr->num_trans != 0 ) ||
  190183. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA)))
  190184. png_do_background(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190185. &(png_ptr->trans_values), &(png_ptr->background)
  190186. #if defined(PNG_READ_GAMMA_SUPPORTED)
  190187. , &(png_ptr->background_1),
  190188. png_ptr->gamma_table, png_ptr->gamma_from_1,
  190189. png_ptr->gamma_to_1, png_ptr->gamma_16_table,
  190190. png_ptr->gamma_16_from_1, png_ptr->gamma_16_to_1,
  190191. png_ptr->gamma_shift
  190192. #endif
  190193. );
  190194. #endif
  190195. #if defined(PNG_READ_GAMMA_SUPPORTED)
  190196. if ((png_ptr->transformations & PNG_GAMMA) &&
  190197. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190198. !((png_ptr->transformations & PNG_BACKGROUND) &&
  190199. ((png_ptr->num_trans != 0) ||
  190200. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA))) &&
  190201. #endif
  190202. (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE))
  190203. png_do_gamma(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190204. png_ptr->gamma_table, png_ptr->gamma_16_table,
  190205. png_ptr->gamma_shift);
  190206. #endif
  190207. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  190208. if (png_ptr->transformations & PNG_16_TO_8)
  190209. png_do_chop(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190210. #endif
  190211. #if defined(PNG_READ_DITHER_SUPPORTED)
  190212. if (png_ptr->transformations & PNG_DITHER)
  190213. {
  190214. png_do_dither((png_row_infop)&(png_ptr->row_info), png_ptr->row_buf + 1,
  190215. png_ptr->palette_lookup, png_ptr->dither_index);
  190216. if(png_ptr->row_info.rowbytes == (png_uint_32)0)
  190217. png_error(png_ptr, "png_do_dither returned rowbytes=0");
  190218. }
  190219. #endif
  190220. #if defined(PNG_READ_INVERT_SUPPORTED)
  190221. if (png_ptr->transformations & PNG_INVERT_MONO)
  190222. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190223. #endif
  190224. #if defined(PNG_READ_SHIFT_SUPPORTED)
  190225. if (png_ptr->transformations & PNG_SHIFT)
  190226. png_do_unshift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190227. &(png_ptr->shift));
  190228. #endif
  190229. #if defined(PNG_READ_PACK_SUPPORTED)
  190230. if (png_ptr->transformations & PNG_PACK)
  190231. png_do_unpack(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190232. #endif
  190233. #if defined(PNG_READ_BGR_SUPPORTED)
  190234. if (png_ptr->transformations & PNG_BGR)
  190235. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190236. #endif
  190237. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  190238. if (png_ptr->transformations & PNG_PACKSWAP)
  190239. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190240. #endif
  190241. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190242. /* if gray -> RGB, do so now only if we did not do so above */
  190243. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  190244. (png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  190245. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190246. #endif
  190247. #if defined(PNG_READ_FILLER_SUPPORTED)
  190248. if (png_ptr->transformations & PNG_FILLER)
  190249. png_do_read_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190250. (png_uint_32)png_ptr->filler, png_ptr->flags);
  190251. #endif
  190252. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  190253. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  190254. png_do_read_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190255. #endif
  190256. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  190257. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  190258. png_do_read_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190259. #endif
  190260. #if defined(PNG_READ_SWAP_SUPPORTED)
  190261. if (png_ptr->transformations & PNG_SWAP_BYTES)
  190262. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190263. #endif
  190264. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  190265. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  190266. {
  190267. if(png_ptr->read_user_transform_fn != NULL)
  190268. (*(png_ptr->read_user_transform_fn)) /* user read transform function */
  190269. (png_ptr, /* png_ptr */
  190270. &(png_ptr->row_info), /* row_info: */
  190271. /* png_uint_32 width; width of row */
  190272. /* png_uint_32 rowbytes; number of bytes in row */
  190273. /* png_byte color_type; color type of pixels */
  190274. /* png_byte bit_depth; bit depth of samples */
  190275. /* png_byte channels; number of channels (1-4) */
  190276. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  190277. png_ptr->row_buf + 1); /* start of pixel data for row */
  190278. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  190279. if(png_ptr->user_transform_depth)
  190280. png_ptr->row_info.bit_depth = png_ptr->user_transform_depth;
  190281. if(png_ptr->user_transform_channels)
  190282. png_ptr->row_info.channels = png_ptr->user_transform_channels;
  190283. #endif
  190284. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  190285. png_ptr->row_info.channels);
  190286. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  190287. png_ptr->row_info.width);
  190288. }
  190289. #endif
  190290. }
  190291. #if defined(PNG_READ_PACK_SUPPORTED)
  190292. /* Unpack pixels of 1, 2, or 4 bits per pixel into 1 byte per pixel,
  190293. * without changing the actual values. Thus, if you had a row with
  190294. * a bit depth of 1, you would end up with bytes that only contained
  190295. * the numbers 0 or 1. If you would rather they contain 0 and 255, use
  190296. * png_do_shift() after this.
  190297. */
  190298. void /* PRIVATE */
  190299. png_do_unpack(png_row_infop row_info, png_bytep row)
  190300. {
  190301. png_debug(1, "in png_do_unpack\n");
  190302. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190303. if (row != NULL && row_info != NULL && row_info->bit_depth < 8)
  190304. #else
  190305. if (row_info->bit_depth < 8)
  190306. #endif
  190307. {
  190308. png_uint_32 i;
  190309. png_uint_32 row_width=row_info->width;
  190310. switch (row_info->bit_depth)
  190311. {
  190312. case 1:
  190313. {
  190314. png_bytep sp = row + (png_size_t)((row_width - 1) >> 3);
  190315. png_bytep dp = row + (png_size_t)row_width - 1;
  190316. png_uint_32 shift = 7 - (int)((row_width + 7) & 0x07);
  190317. for (i = 0; i < row_width; i++)
  190318. {
  190319. *dp = (png_byte)((*sp >> shift) & 0x01);
  190320. if (shift == 7)
  190321. {
  190322. shift = 0;
  190323. sp--;
  190324. }
  190325. else
  190326. shift++;
  190327. dp--;
  190328. }
  190329. break;
  190330. }
  190331. case 2:
  190332. {
  190333. png_bytep sp = row + (png_size_t)((row_width - 1) >> 2);
  190334. png_bytep dp = row + (png_size_t)row_width - 1;
  190335. png_uint_32 shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  190336. for (i = 0; i < row_width; i++)
  190337. {
  190338. *dp = (png_byte)((*sp >> shift) & 0x03);
  190339. if (shift == 6)
  190340. {
  190341. shift = 0;
  190342. sp--;
  190343. }
  190344. else
  190345. shift += 2;
  190346. dp--;
  190347. }
  190348. break;
  190349. }
  190350. case 4:
  190351. {
  190352. png_bytep sp = row + (png_size_t)((row_width - 1) >> 1);
  190353. png_bytep dp = row + (png_size_t)row_width - 1;
  190354. png_uint_32 shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  190355. for (i = 0; i < row_width; i++)
  190356. {
  190357. *dp = (png_byte)((*sp >> shift) & 0x0f);
  190358. if (shift == 4)
  190359. {
  190360. shift = 0;
  190361. sp--;
  190362. }
  190363. else
  190364. shift = 4;
  190365. dp--;
  190366. }
  190367. break;
  190368. }
  190369. }
  190370. row_info->bit_depth = 8;
  190371. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  190372. row_info->rowbytes = row_width * row_info->channels;
  190373. }
  190374. }
  190375. #endif
  190376. #if defined(PNG_READ_SHIFT_SUPPORTED)
  190377. /* Reverse the effects of png_do_shift. This routine merely shifts the
  190378. * pixels back to their significant bits values. Thus, if you have
  190379. * a row of bit depth 8, but only 5 are significant, this will shift
  190380. * the values back to 0 through 31.
  190381. */
  190382. void /* PRIVATE */
  190383. png_do_unshift(png_row_infop row_info, png_bytep row, png_color_8p sig_bits)
  190384. {
  190385. png_debug(1, "in png_do_unshift\n");
  190386. if (
  190387. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190388. row != NULL && row_info != NULL && sig_bits != NULL &&
  190389. #endif
  190390. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  190391. {
  190392. int shift[4];
  190393. int channels = 0;
  190394. int c;
  190395. png_uint_16 value = 0;
  190396. png_uint_32 row_width = row_info->width;
  190397. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  190398. {
  190399. shift[channels++] = row_info->bit_depth - sig_bits->red;
  190400. shift[channels++] = row_info->bit_depth - sig_bits->green;
  190401. shift[channels++] = row_info->bit_depth - sig_bits->blue;
  190402. }
  190403. else
  190404. {
  190405. shift[channels++] = row_info->bit_depth - sig_bits->gray;
  190406. }
  190407. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  190408. {
  190409. shift[channels++] = row_info->bit_depth - sig_bits->alpha;
  190410. }
  190411. for (c = 0; c < channels; c++)
  190412. {
  190413. if (shift[c] <= 0)
  190414. shift[c] = 0;
  190415. else
  190416. value = 1;
  190417. }
  190418. if (!value)
  190419. return;
  190420. switch (row_info->bit_depth)
  190421. {
  190422. case 2:
  190423. {
  190424. png_bytep bp;
  190425. png_uint_32 i;
  190426. png_uint_32 istop = row_info->rowbytes;
  190427. for (bp = row, i = 0; i < istop; i++)
  190428. {
  190429. *bp >>= 1;
  190430. *bp++ &= 0x55;
  190431. }
  190432. break;
  190433. }
  190434. case 4:
  190435. {
  190436. png_bytep bp = row;
  190437. png_uint_32 i;
  190438. png_uint_32 istop = row_info->rowbytes;
  190439. png_byte mask = (png_byte)((((int)0xf0 >> shift[0]) & (int)0xf0) |
  190440. (png_byte)((int)0xf >> shift[0]));
  190441. for (i = 0; i < istop; i++)
  190442. {
  190443. *bp >>= shift[0];
  190444. *bp++ &= mask;
  190445. }
  190446. break;
  190447. }
  190448. case 8:
  190449. {
  190450. png_bytep bp = row;
  190451. png_uint_32 i;
  190452. png_uint_32 istop = row_width * channels;
  190453. for (i = 0; i < istop; i++)
  190454. {
  190455. *bp++ >>= shift[i%channels];
  190456. }
  190457. break;
  190458. }
  190459. case 16:
  190460. {
  190461. png_bytep bp = row;
  190462. png_uint_32 i;
  190463. png_uint_32 istop = channels * row_width;
  190464. for (i = 0; i < istop; i++)
  190465. {
  190466. value = (png_uint_16)((*bp << 8) + *(bp + 1));
  190467. value >>= shift[i%channels];
  190468. *bp++ = (png_byte)(value >> 8);
  190469. *bp++ = (png_byte)(value & 0xff);
  190470. }
  190471. break;
  190472. }
  190473. }
  190474. }
  190475. }
  190476. #endif
  190477. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  190478. /* chop rows of bit depth 16 down to 8 */
  190479. void /* PRIVATE */
  190480. png_do_chop(png_row_infop row_info, png_bytep row)
  190481. {
  190482. png_debug(1, "in png_do_chop\n");
  190483. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190484. if (row != NULL && row_info != NULL && row_info->bit_depth == 16)
  190485. #else
  190486. if (row_info->bit_depth == 16)
  190487. #endif
  190488. {
  190489. png_bytep sp = row;
  190490. png_bytep dp = row;
  190491. png_uint_32 i;
  190492. png_uint_32 istop = row_info->width * row_info->channels;
  190493. for (i = 0; i<istop; i++, sp += 2, dp++)
  190494. {
  190495. #if defined(PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED)
  190496. /* This does a more accurate scaling of the 16-bit color
  190497. * value, rather than a simple low-byte truncation.
  190498. *
  190499. * What the ideal calculation should be:
  190500. * *dp = (((((png_uint_32)(*sp) << 8) |
  190501. * (png_uint_32)(*(sp + 1))) * 255 + 127) / (png_uint_32)65535L;
  190502. *
  190503. * GRR: no, I think this is what it really should be:
  190504. * *dp = (((((png_uint_32)(*sp) << 8) |
  190505. * (png_uint_32)(*(sp + 1))) + 128L) / (png_uint_32)257L;
  190506. *
  190507. * GRR: here's the exact calculation with shifts:
  190508. * temp = (((png_uint_32)(*sp) << 8) | (png_uint_32)(*(sp + 1))) + 128L;
  190509. * *dp = (temp - (temp >> 8)) >> 8;
  190510. *
  190511. * Approximate calculation with shift/add instead of multiply/divide:
  190512. * *dp = ((((png_uint_32)(*sp) << 8) |
  190513. * (png_uint_32)((int)(*(sp + 1)) - *sp)) + 128) >> 8;
  190514. *
  190515. * What we actually do to avoid extra shifting and conversion:
  190516. */
  190517. *dp = *sp + ((((int)(*(sp + 1)) - *sp) > 128) ? 1 : 0);
  190518. #else
  190519. /* Simply discard the low order byte */
  190520. *dp = *sp;
  190521. #endif
  190522. }
  190523. row_info->bit_depth = 8;
  190524. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  190525. row_info->rowbytes = row_info->width * row_info->channels;
  190526. }
  190527. }
  190528. #endif
  190529. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  190530. void /* PRIVATE */
  190531. png_do_read_swap_alpha(png_row_infop row_info, png_bytep row)
  190532. {
  190533. png_debug(1, "in png_do_read_swap_alpha\n");
  190534. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190535. if (row != NULL && row_info != NULL)
  190536. #endif
  190537. {
  190538. png_uint_32 row_width = row_info->width;
  190539. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  190540. {
  190541. /* This converts from RGBA to ARGB */
  190542. if (row_info->bit_depth == 8)
  190543. {
  190544. png_bytep sp = row + row_info->rowbytes;
  190545. png_bytep dp = sp;
  190546. png_byte save;
  190547. png_uint_32 i;
  190548. for (i = 0; i < row_width; i++)
  190549. {
  190550. save = *(--sp);
  190551. *(--dp) = *(--sp);
  190552. *(--dp) = *(--sp);
  190553. *(--dp) = *(--sp);
  190554. *(--dp) = save;
  190555. }
  190556. }
  190557. /* This converts from RRGGBBAA to AARRGGBB */
  190558. else
  190559. {
  190560. png_bytep sp = row + row_info->rowbytes;
  190561. png_bytep dp = sp;
  190562. png_byte save[2];
  190563. png_uint_32 i;
  190564. for (i = 0; i < row_width; i++)
  190565. {
  190566. save[0] = *(--sp);
  190567. save[1] = *(--sp);
  190568. *(--dp) = *(--sp);
  190569. *(--dp) = *(--sp);
  190570. *(--dp) = *(--sp);
  190571. *(--dp) = *(--sp);
  190572. *(--dp) = *(--sp);
  190573. *(--dp) = *(--sp);
  190574. *(--dp) = save[0];
  190575. *(--dp) = save[1];
  190576. }
  190577. }
  190578. }
  190579. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  190580. {
  190581. /* This converts from GA to AG */
  190582. if (row_info->bit_depth == 8)
  190583. {
  190584. png_bytep sp = row + row_info->rowbytes;
  190585. png_bytep dp = sp;
  190586. png_byte save;
  190587. png_uint_32 i;
  190588. for (i = 0; i < row_width; i++)
  190589. {
  190590. save = *(--sp);
  190591. *(--dp) = *(--sp);
  190592. *(--dp) = save;
  190593. }
  190594. }
  190595. /* This converts from GGAA to AAGG */
  190596. else
  190597. {
  190598. png_bytep sp = row + row_info->rowbytes;
  190599. png_bytep dp = sp;
  190600. png_byte save[2];
  190601. png_uint_32 i;
  190602. for (i = 0; i < row_width; i++)
  190603. {
  190604. save[0] = *(--sp);
  190605. save[1] = *(--sp);
  190606. *(--dp) = *(--sp);
  190607. *(--dp) = *(--sp);
  190608. *(--dp) = save[0];
  190609. *(--dp) = save[1];
  190610. }
  190611. }
  190612. }
  190613. }
  190614. }
  190615. #endif
  190616. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  190617. void /* PRIVATE */
  190618. png_do_read_invert_alpha(png_row_infop row_info, png_bytep row)
  190619. {
  190620. png_debug(1, "in png_do_read_invert_alpha\n");
  190621. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190622. if (row != NULL && row_info != NULL)
  190623. #endif
  190624. {
  190625. png_uint_32 row_width = row_info->width;
  190626. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  190627. {
  190628. /* This inverts the alpha channel in RGBA */
  190629. if (row_info->bit_depth == 8)
  190630. {
  190631. png_bytep sp = row + row_info->rowbytes;
  190632. png_bytep dp = sp;
  190633. png_uint_32 i;
  190634. for (i = 0; i < row_width; i++)
  190635. {
  190636. *(--dp) = (png_byte)(255 - *(--sp));
  190637. /* This does nothing:
  190638. *(--dp) = *(--sp);
  190639. *(--dp) = *(--sp);
  190640. *(--dp) = *(--sp);
  190641. We can replace it with:
  190642. */
  190643. sp-=3;
  190644. dp=sp;
  190645. }
  190646. }
  190647. /* This inverts the alpha channel in RRGGBBAA */
  190648. else
  190649. {
  190650. png_bytep sp = row + row_info->rowbytes;
  190651. png_bytep dp = sp;
  190652. png_uint_32 i;
  190653. for (i = 0; i < row_width; i++)
  190654. {
  190655. *(--dp) = (png_byte)(255 - *(--sp));
  190656. *(--dp) = (png_byte)(255 - *(--sp));
  190657. /* This does nothing:
  190658. *(--dp) = *(--sp);
  190659. *(--dp) = *(--sp);
  190660. *(--dp) = *(--sp);
  190661. *(--dp) = *(--sp);
  190662. *(--dp) = *(--sp);
  190663. *(--dp) = *(--sp);
  190664. We can replace it with:
  190665. */
  190666. sp-=6;
  190667. dp=sp;
  190668. }
  190669. }
  190670. }
  190671. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  190672. {
  190673. /* This inverts the alpha channel in GA */
  190674. if (row_info->bit_depth == 8)
  190675. {
  190676. png_bytep sp = row + row_info->rowbytes;
  190677. png_bytep dp = sp;
  190678. png_uint_32 i;
  190679. for (i = 0; i < row_width; i++)
  190680. {
  190681. *(--dp) = (png_byte)(255 - *(--sp));
  190682. *(--dp) = *(--sp);
  190683. }
  190684. }
  190685. /* This inverts the alpha channel in GGAA */
  190686. else
  190687. {
  190688. png_bytep sp = row + row_info->rowbytes;
  190689. png_bytep dp = sp;
  190690. png_uint_32 i;
  190691. for (i = 0; i < row_width; i++)
  190692. {
  190693. *(--dp) = (png_byte)(255 - *(--sp));
  190694. *(--dp) = (png_byte)(255 - *(--sp));
  190695. /*
  190696. *(--dp) = *(--sp);
  190697. *(--dp) = *(--sp);
  190698. */
  190699. sp-=2;
  190700. dp=sp;
  190701. }
  190702. }
  190703. }
  190704. }
  190705. }
  190706. #endif
  190707. #if defined(PNG_READ_FILLER_SUPPORTED)
  190708. /* Add filler channel if we have RGB color */
  190709. void /* PRIVATE */
  190710. png_do_read_filler(png_row_infop row_info, png_bytep row,
  190711. png_uint_32 filler, png_uint_32 flags)
  190712. {
  190713. png_uint_32 i;
  190714. png_uint_32 row_width = row_info->width;
  190715. png_byte hi_filler = (png_byte)((filler>>8) & 0xff);
  190716. png_byte lo_filler = (png_byte)(filler & 0xff);
  190717. png_debug(1, "in png_do_read_filler\n");
  190718. if (
  190719. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190720. row != NULL && row_info != NULL &&
  190721. #endif
  190722. row_info->color_type == PNG_COLOR_TYPE_GRAY)
  190723. {
  190724. if(row_info->bit_depth == 8)
  190725. {
  190726. /* This changes the data from G to GX */
  190727. if (flags & PNG_FLAG_FILLER_AFTER)
  190728. {
  190729. png_bytep sp = row + (png_size_t)row_width;
  190730. png_bytep dp = sp + (png_size_t)row_width;
  190731. for (i = 1; i < row_width; i++)
  190732. {
  190733. *(--dp) = lo_filler;
  190734. *(--dp) = *(--sp);
  190735. }
  190736. *(--dp) = lo_filler;
  190737. row_info->channels = 2;
  190738. row_info->pixel_depth = 16;
  190739. row_info->rowbytes = row_width * 2;
  190740. }
  190741. /* This changes the data from G to XG */
  190742. else
  190743. {
  190744. png_bytep sp = row + (png_size_t)row_width;
  190745. png_bytep dp = sp + (png_size_t)row_width;
  190746. for (i = 0; i < row_width; i++)
  190747. {
  190748. *(--dp) = *(--sp);
  190749. *(--dp) = lo_filler;
  190750. }
  190751. row_info->channels = 2;
  190752. row_info->pixel_depth = 16;
  190753. row_info->rowbytes = row_width * 2;
  190754. }
  190755. }
  190756. else if(row_info->bit_depth == 16)
  190757. {
  190758. /* This changes the data from GG to GGXX */
  190759. if (flags & PNG_FLAG_FILLER_AFTER)
  190760. {
  190761. png_bytep sp = row + (png_size_t)row_width * 2;
  190762. png_bytep dp = sp + (png_size_t)row_width * 2;
  190763. for (i = 1; i < row_width; i++)
  190764. {
  190765. *(--dp) = hi_filler;
  190766. *(--dp) = lo_filler;
  190767. *(--dp) = *(--sp);
  190768. *(--dp) = *(--sp);
  190769. }
  190770. *(--dp) = hi_filler;
  190771. *(--dp) = lo_filler;
  190772. row_info->channels = 2;
  190773. row_info->pixel_depth = 32;
  190774. row_info->rowbytes = row_width * 4;
  190775. }
  190776. /* This changes the data from GG to XXGG */
  190777. else
  190778. {
  190779. png_bytep sp = row + (png_size_t)row_width * 2;
  190780. png_bytep dp = sp + (png_size_t)row_width * 2;
  190781. for (i = 0; i < row_width; i++)
  190782. {
  190783. *(--dp) = *(--sp);
  190784. *(--dp) = *(--sp);
  190785. *(--dp) = hi_filler;
  190786. *(--dp) = lo_filler;
  190787. }
  190788. row_info->channels = 2;
  190789. row_info->pixel_depth = 32;
  190790. row_info->rowbytes = row_width * 4;
  190791. }
  190792. }
  190793. } /* COLOR_TYPE == GRAY */
  190794. else if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  190795. {
  190796. if(row_info->bit_depth == 8)
  190797. {
  190798. /* This changes the data from RGB to RGBX */
  190799. if (flags & PNG_FLAG_FILLER_AFTER)
  190800. {
  190801. png_bytep sp = row + (png_size_t)row_width * 3;
  190802. png_bytep dp = sp + (png_size_t)row_width;
  190803. for (i = 1; i < row_width; i++)
  190804. {
  190805. *(--dp) = lo_filler;
  190806. *(--dp) = *(--sp);
  190807. *(--dp) = *(--sp);
  190808. *(--dp) = *(--sp);
  190809. }
  190810. *(--dp) = lo_filler;
  190811. row_info->channels = 4;
  190812. row_info->pixel_depth = 32;
  190813. row_info->rowbytes = row_width * 4;
  190814. }
  190815. /* This changes the data from RGB to XRGB */
  190816. else
  190817. {
  190818. png_bytep sp = row + (png_size_t)row_width * 3;
  190819. png_bytep dp = sp + (png_size_t)row_width;
  190820. for (i = 0; i < row_width; i++)
  190821. {
  190822. *(--dp) = *(--sp);
  190823. *(--dp) = *(--sp);
  190824. *(--dp) = *(--sp);
  190825. *(--dp) = lo_filler;
  190826. }
  190827. row_info->channels = 4;
  190828. row_info->pixel_depth = 32;
  190829. row_info->rowbytes = row_width * 4;
  190830. }
  190831. }
  190832. else if(row_info->bit_depth == 16)
  190833. {
  190834. /* This changes the data from RRGGBB to RRGGBBXX */
  190835. if (flags & PNG_FLAG_FILLER_AFTER)
  190836. {
  190837. png_bytep sp = row + (png_size_t)row_width * 6;
  190838. png_bytep dp = sp + (png_size_t)row_width * 2;
  190839. for (i = 1; i < row_width; i++)
  190840. {
  190841. *(--dp) = hi_filler;
  190842. *(--dp) = lo_filler;
  190843. *(--dp) = *(--sp);
  190844. *(--dp) = *(--sp);
  190845. *(--dp) = *(--sp);
  190846. *(--dp) = *(--sp);
  190847. *(--dp) = *(--sp);
  190848. *(--dp) = *(--sp);
  190849. }
  190850. *(--dp) = hi_filler;
  190851. *(--dp) = lo_filler;
  190852. row_info->channels = 4;
  190853. row_info->pixel_depth = 64;
  190854. row_info->rowbytes = row_width * 8;
  190855. }
  190856. /* This changes the data from RRGGBB to XXRRGGBB */
  190857. else
  190858. {
  190859. png_bytep sp = row + (png_size_t)row_width * 6;
  190860. png_bytep dp = sp + (png_size_t)row_width * 2;
  190861. for (i = 0; i < row_width; i++)
  190862. {
  190863. *(--dp) = *(--sp);
  190864. *(--dp) = *(--sp);
  190865. *(--dp) = *(--sp);
  190866. *(--dp) = *(--sp);
  190867. *(--dp) = *(--sp);
  190868. *(--dp) = *(--sp);
  190869. *(--dp) = hi_filler;
  190870. *(--dp) = lo_filler;
  190871. }
  190872. row_info->channels = 4;
  190873. row_info->pixel_depth = 64;
  190874. row_info->rowbytes = row_width * 8;
  190875. }
  190876. }
  190877. } /* COLOR_TYPE == RGB */
  190878. }
  190879. #endif
  190880. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190881. /* expand grayscale files to RGB, with or without alpha */
  190882. void /* PRIVATE */
  190883. png_do_gray_to_rgb(png_row_infop row_info, png_bytep row)
  190884. {
  190885. png_uint_32 i;
  190886. png_uint_32 row_width = row_info->width;
  190887. png_debug(1, "in png_do_gray_to_rgb\n");
  190888. if (row_info->bit_depth >= 8 &&
  190889. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190890. row != NULL && row_info != NULL &&
  190891. #endif
  190892. !(row_info->color_type & PNG_COLOR_MASK_COLOR))
  190893. {
  190894. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  190895. {
  190896. if (row_info->bit_depth == 8)
  190897. {
  190898. png_bytep sp = row + (png_size_t)row_width - 1;
  190899. png_bytep dp = sp + (png_size_t)row_width * 2;
  190900. for (i = 0; i < row_width; i++)
  190901. {
  190902. *(dp--) = *sp;
  190903. *(dp--) = *sp;
  190904. *(dp--) = *(sp--);
  190905. }
  190906. }
  190907. else
  190908. {
  190909. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  190910. png_bytep dp = sp + (png_size_t)row_width * 4;
  190911. for (i = 0; i < row_width; i++)
  190912. {
  190913. *(dp--) = *sp;
  190914. *(dp--) = *(sp - 1);
  190915. *(dp--) = *sp;
  190916. *(dp--) = *(sp - 1);
  190917. *(dp--) = *(sp--);
  190918. *(dp--) = *(sp--);
  190919. }
  190920. }
  190921. }
  190922. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  190923. {
  190924. if (row_info->bit_depth == 8)
  190925. {
  190926. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  190927. png_bytep dp = sp + (png_size_t)row_width * 2;
  190928. for (i = 0; i < row_width; i++)
  190929. {
  190930. *(dp--) = *(sp--);
  190931. *(dp--) = *sp;
  190932. *(dp--) = *sp;
  190933. *(dp--) = *(sp--);
  190934. }
  190935. }
  190936. else
  190937. {
  190938. png_bytep sp = row + (png_size_t)row_width * 4 - 1;
  190939. png_bytep dp = sp + (png_size_t)row_width * 4;
  190940. for (i = 0; i < row_width; i++)
  190941. {
  190942. *(dp--) = *(sp--);
  190943. *(dp--) = *(sp--);
  190944. *(dp--) = *sp;
  190945. *(dp--) = *(sp - 1);
  190946. *(dp--) = *sp;
  190947. *(dp--) = *(sp - 1);
  190948. *(dp--) = *(sp--);
  190949. *(dp--) = *(sp--);
  190950. }
  190951. }
  190952. }
  190953. row_info->channels += (png_byte)2;
  190954. row_info->color_type |= PNG_COLOR_MASK_COLOR;
  190955. row_info->pixel_depth = (png_byte)(row_info->channels *
  190956. row_info->bit_depth);
  190957. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  190958. }
  190959. }
  190960. #endif
  190961. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  190962. /* reduce RGB files to grayscale, with or without alpha
  190963. * using the equation given in Poynton's ColorFAQ at
  190964. * <http://www.inforamp.net/~poynton/>
  190965. * Copyright (c) 1998-01-04 Charles Poynton poynton at inforamp.net
  190966. *
  190967. * Y = 0.212671 * R + 0.715160 * G + 0.072169 * B
  190968. *
  190969. * We approximate this with
  190970. *
  190971. * Y = 0.21268 * R + 0.7151 * G + 0.07217 * B
  190972. *
  190973. * which can be expressed with integers as
  190974. *
  190975. * Y = (6969 * R + 23434 * G + 2365 * B)/32768
  190976. *
  190977. * The calculation is to be done in a linear colorspace.
  190978. *
  190979. * Other integer coefficents can be used via png_set_rgb_to_gray().
  190980. */
  190981. int /* PRIVATE */
  190982. png_do_rgb_to_gray(png_structp png_ptr, png_row_infop row_info, png_bytep row)
  190983. {
  190984. png_uint_32 i;
  190985. png_uint_32 row_width = row_info->width;
  190986. int rgb_error = 0;
  190987. png_debug(1, "in png_do_rgb_to_gray\n");
  190988. if (
  190989. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190990. row != NULL && row_info != NULL &&
  190991. #endif
  190992. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  190993. {
  190994. png_uint_32 rc = png_ptr->rgb_to_gray_red_coeff;
  190995. png_uint_32 gc = png_ptr->rgb_to_gray_green_coeff;
  190996. png_uint_32 bc = png_ptr->rgb_to_gray_blue_coeff;
  190997. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  190998. {
  190999. if (row_info->bit_depth == 8)
  191000. {
  191001. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  191002. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  191003. {
  191004. png_bytep sp = row;
  191005. png_bytep dp = row;
  191006. for (i = 0; i < row_width; i++)
  191007. {
  191008. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  191009. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  191010. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  191011. if(red != green || red != blue)
  191012. {
  191013. rgb_error |= 1;
  191014. *(dp++) = png_ptr->gamma_from_1[
  191015. (rc*red+gc*green+bc*blue)>>15];
  191016. }
  191017. else
  191018. *(dp++) = *(sp-1);
  191019. }
  191020. }
  191021. else
  191022. #endif
  191023. {
  191024. png_bytep sp = row;
  191025. png_bytep dp = row;
  191026. for (i = 0; i < row_width; i++)
  191027. {
  191028. png_byte red = *(sp++);
  191029. png_byte green = *(sp++);
  191030. png_byte blue = *(sp++);
  191031. if(red != green || red != blue)
  191032. {
  191033. rgb_error |= 1;
  191034. *(dp++) = (png_byte)((rc*red+gc*green+bc*blue)>>15);
  191035. }
  191036. else
  191037. *(dp++) = *(sp-1);
  191038. }
  191039. }
  191040. }
  191041. else /* RGB bit_depth == 16 */
  191042. {
  191043. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  191044. if (png_ptr->gamma_16_to_1 != NULL &&
  191045. png_ptr->gamma_16_from_1 != NULL)
  191046. {
  191047. png_bytep sp = row;
  191048. png_bytep dp = row;
  191049. for (i = 0; i < row_width; i++)
  191050. {
  191051. png_uint_16 red, green, blue, w;
  191052. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191053. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191054. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191055. if(red == green && red == blue)
  191056. w = red;
  191057. else
  191058. {
  191059. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  191060. png_ptr->gamma_shift][red>>8];
  191061. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  191062. png_ptr->gamma_shift][green>>8];
  191063. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  191064. png_ptr->gamma_shift][blue>>8];
  191065. png_uint_16 gray16 = (png_uint_16)((rc*red_1 + gc*green_1
  191066. + bc*blue_1)>>15);
  191067. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  191068. png_ptr->gamma_shift][gray16 >> 8];
  191069. rgb_error |= 1;
  191070. }
  191071. *(dp++) = (png_byte)((w>>8) & 0xff);
  191072. *(dp++) = (png_byte)(w & 0xff);
  191073. }
  191074. }
  191075. else
  191076. #endif
  191077. {
  191078. png_bytep sp = row;
  191079. png_bytep dp = row;
  191080. for (i = 0; i < row_width; i++)
  191081. {
  191082. png_uint_16 red, green, blue, gray16;
  191083. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191084. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191085. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191086. if(red != green || red != blue)
  191087. rgb_error |= 1;
  191088. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  191089. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  191090. *(dp++) = (png_byte)(gray16 & 0xff);
  191091. }
  191092. }
  191093. }
  191094. }
  191095. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191096. {
  191097. if (row_info->bit_depth == 8)
  191098. {
  191099. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  191100. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  191101. {
  191102. png_bytep sp = row;
  191103. png_bytep dp = row;
  191104. for (i = 0; i < row_width; i++)
  191105. {
  191106. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  191107. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  191108. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  191109. if(red != green || red != blue)
  191110. rgb_error |= 1;
  191111. *(dp++) = png_ptr->gamma_from_1
  191112. [(rc*red + gc*green + bc*blue)>>15];
  191113. *(dp++) = *(sp++); /* alpha */
  191114. }
  191115. }
  191116. else
  191117. #endif
  191118. {
  191119. png_bytep sp = row;
  191120. png_bytep dp = row;
  191121. for (i = 0; i < row_width; i++)
  191122. {
  191123. png_byte red = *(sp++);
  191124. png_byte green = *(sp++);
  191125. png_byte blue = *(sp++);
  191126. if(red != green || red != blue)
  191127. rgb_error |= 1;
  191128. *(dp++) = (png_byte)((rc*red + gc*green + bc*blue)>>15);
  191129. *(dp++) = *(sp++); /* alpha */
  191130. }
  191131. }
  191132. }
  191133. else /* RGBA bit_depth == 16 */
  191134. {
  191135. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  191136. if (png_ptr->gamma_16_to_1 != NULL &&
  191137. png_ptr->gamma_16_from_1 != NULL)
  191138. {
  191139. png_bytep sp = row;
  191140. png_bytep dp = row;
  191141. for (i = 0; i < row_width; i++)
  191142. {
  191143. png_uint_16 red, green, blue, w;
  191144. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191145. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191146. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191147. if(red == green && red == blue)
  191148. w = red;
  191149. else
  191150. {
  191151. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  191152. png_ptr->gamma_shift][red>>8];
  191153. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  191154. png_ptr->gamma_shift][green>>8];
  191155. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  191156. png_ptr->gamma_shift][blue>>8];
  191157. png_uint_16 gray16 = (png_uint_16)((rc * red_1
  191158. + gc * green_1 + bc * blue_1)>>15);
  191159. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  191160. png_ptr->gamma_shift][gray16 >> 8];
  191161. rgb_error |= 1;
  191162. }
  191163. *(dp++) = (png_byte)((w>>8) & 0xff);
  191164. *(dp++) = (png_byte)(w & 0xff);
  191165. *(dp++) = *(sp++); /* alpha */
  191166. *(dp++) = *(sp++);
  191167. }
  191168. }
  191169. else
  191170. #endif
  191171. {
  191172. png_bytep sp = row;
  191173. png_bytep dp = row;
  191174. for (i = 0; i < row_width; i++)
  191175. {
  191176. png_uint_16 red, green, blue, gray16;
  191177. red = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  191178. green = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  191179. blue = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  191180. if(red != green || red != blue)
  191181. rgb_error |= 1;
  191182. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  191183. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  191184. *(dp++) = (png_byte)(gray16 & 0xff);
  191185. *(dp++) = *(sp++); /* alpha */
  191186. *(dp++) = *(sp++);
  191187. }
  191188. }
  191189. }
  191190. }
  191191. row_info->channels -= (png_byte)2;
  191192. row_info->color_type &= ~PNG_COLOR_MASK_COLOR;
  191193. row_info->pixel_depth = (png_byte)(row_info->channels *
  191194. row_info->bit_depth);
  191195. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  191196. }
  191197. return rgb_error;
  191198. }
  191199. #endif
  191200. /* Build a grayscale palette. Palette is assumed to be 1 << bit_depth
  191201. * large of png_color. This lets grayscale images be treated as
  191202. * paletted. Most useful for gamma correction and simplification
  191203. * of code.
  191204. */
  191205. void PNGAPI
  191206. png_build_grayscale_palette(int bit_depth, png_colorp palette)
  191207. {
  191208. int num_palette;
  191209. int color_inc;
  191210. int i;
  191211. int v;
  191212. png_debug(1, "in png_do_build_grayscale_palette\n");
  191213. if (palette == NULL)
  191214. return;
  191215. switch (bit_depth)
  191216. {
  191217. case 1:
  191218. num_palette = 2;
  191219. color_inc = 0xff;
  191220. break;
  191221. case 2:
  191222. num_palette = 4;
  191223. color_inc = 0x55;
  191224. break;
  191225. case 4:
  191226. num_palette = 16;
  191227. color_inc = 0x11;
  191228. break;
  191229. case 8:
  191230. num_palette = 256;
  191231. color_inc = 1;
  191232. break;
  191233. default:
  191234. num_palette = 0;
  191235. color_inc = 0;
  191236. break;
  191237. }
  191238. for (i = 0, v = 0; i < num_palette; i++, v += color_inc)
  191239. {
  191240. palette[i].red = (png_byte)v;
  191241. palette[i].green = (png_byte)v;
  191242. palette[i].blue = (png_byte)v;
  191243. }
  191244. }
  191245. /* This function is currently unused. Do we really need it? */
  191246. #if defined(PNG_READ_DITHER_SUPPORTED) && defined(PNG_CORRECT_PALETTE_SUPPORTED)
  191247. void /* PRIVATE */
  191248. png_correct_palette(png_structp png_ptr, png_colorp palette,
  191249. int num_palette)
  191250. {
  191251. png_debug(1, "in png_correct_palette\n");
  191252. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  191253. defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  191254. if (png_ptr->transformations & (PNG_GAMMA | PNG_BACKGROUND))
  191255. {
  191256. png_color back, back_1;
  191257. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  191258. {
  191259. back.red = png_ptr->gamma_table[png_ptr->background.red];
  191260. back.green = png_ptr->gamma_table[png_ptr->background.green];
  191261. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  191262. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  191263. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  191264. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  191265. }
  191266. else
  191267. {
  191268. double g;
  191269. g = 1.0 / (png_ptr->background_gamma * png_ptr->screen_gamma);
  191270. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_SCREEN ||
  191271. fabs(g - 1.0) < PNG_GAMMA_THRESHOLD)
  191272. {
  191273. back.red = png_ptr->background.red;
  191274. back.green = png_ptr->background.green;
  191275. back.blue = png_ptr->background.blue;
  191276. }
  191277. else
  191278. {
  191279. back.red =
  191280. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  191281. 255.0 + 0.5);
  191282. back.green =
  191283. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  191284. 255.0 + 0.5);
  191285. back.blue =
  191286. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  191287. 255.0 + 0.5);
  191288. }
  191289. g = 1.0 / png_ptr->background_gamma;
  191290. back_1.red =
  191291. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  191292. 255.0 + 0.5);
  191293. back_1.green =
  191294. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  191295. 255.0 + 0.5);
  191296. back_1.blue =
  191297. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  191298. 255.0 + 0.5);
  191299. }
  191300. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  191301. {
  191302. png_uint_32 i;
  191303. for (i = 0; i < (png_uint_32)num_palette; i++)
  191304. {
  191305. if (i < png_ptr->num_trans && png_ptr->trans[i] == 0)
  191306. {
  191307. palette[i] = back;
  191308. }
  191309. else if (i < png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  191310. {
  191311. png_byte v, w;
  191312. v = png_ptr->gamma_to_1[png_ptr->palette[i].red];
  191313. png_composite(w, v, png_ptr->trans[i], back_1.red);
  191314. palette[i].red = png_ptr->gamma_from_1[w];
  191315. v = png_ptr->gamma_to_1[png_ptr->palette[i].green];
  191316. png_composite(w, v, png_ptr->trans[i], back_1.green);
  191317. palette[i].green = png_ptr->gamma_from_1[w];
  191318. v = png_ptr->gamma_to_1[png_ptr->palette[i].blue];
  191319. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  191320. palette[i].blue = png_ptr->gamma_from_1[w];
  191321. }
  191322. else
  191323. {
  191324. palette[i].red = png_ptr->gamma_table[palette[i].red];
  191325. palette[i].green = png_ptr->gamma_table[palette[i].green];
  191326. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  191327. }
  191328. }
  191329. }
  191330. else
  191331. {
  191332. int i;
  191333. for (i = 0; i < num_palette; i++)
  191334. {
  191335. if (palette[i].red == (png_byte)png_ptr->trans_values.gray)
  191336. {
  191337. palette[i] = back;
  191338. }
  191339. else
  191340. {
  191341. palette[i].red = png_ptr->gamma_table[palette[i].red];
  191342. palette[i].green = png_ptr->gamma_table[palette[i].green];
  191343. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  191344. }
  191345. }
  191346. }
  191347. }
  191348. else
  191349. #endif
  191350. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191351. if (png_ptr->transformations & PNG_GAMMA)
  191352. {
  191353. int i;
  191354. for (i = 0; i < num_palette; i++)
  191355. {
  191356. palette[i].red = png_ptr->gamma_table[palette[i].red];
  191357. palette[i].green = png_ptr->gamma_table[palette[i].green];
  191358. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  191359. }
  191360. }
  191361. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191362. else
  191363. #endif
  191364. #endif
  191365. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191366. if (png_ptr->transformations & PNG_BACKGROUND)
  191367. {
  191368. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  191369. {
  191370. png_color back;
  191371. back.red = (png_byte)png_ptr->background.red;
  191372. back.green = (png_byte)png_ptr->background.green;
  191373. back.blue = (png_byte)png_ptr->background.blue;
  191374. for (i = 0; i < (int)png_ptr->num_trans; i++)
  191375. {
  191376. if (png_ptr->trans[i] == 0)
  191377. {
  191378. palette[i].red = back.red;
  191379. palette[i].green = back.green;
  191380. palette[i].blue = back.blue;
  191381. }
  191382. else if (png_ptr->trans[i] != 0xff)
  191383. {
  191384. png_composite(palette[i].red, png_ptr->palette[i].red,
  191385. png_ptr->trans[i], back.red);
  191386. png_composite(palette[i].green, png_ptr->palette[i].green,
  191387. png_ptr->trans[i], back.green);
  191388. png_composite(palette[i].blue, png_ptr->palette[i].blue,
  191389. png_ptr->trans[i], back.blue);
  191390. }
  191391. }
  191392. }
  191393. else /* assume grayscale palette (what else could it be?) */
  191394. {
  191395. int i;
  191396. for (i = 0; i < num_palette; i++)
  191397. {
  191398. if (i == (png_byte)png_ptr->trans_values.gray)
  191399. {
  191400. palette[i].red = (png_byte)png_ptr->background.red;
  191401. palette[i].green = (png_byte)png_ptr->background.green;
  191402. palette[i].blue = (png_byte)png_ptr->background.blue;
  191403. }
  191404. }
  191405. }
  191406. }
  191407. #endif
  191408. }
  191409. #endif
  191410. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191411. /* Replace any alpha or transparency with the supplied background color.
  191412. * "background" is already in the screen gamma, while "background_1" is
  191413. * at a gamma of 1.0. Paletted files have already been taken care of.
  191414. */
  191415. void /* PRIVATE */
  191416. png_do_background(png_row_infop row_info, png_bytep row,
  191417. png_color_16p trans_values, png_color_16p background
  191418. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191419. , png_color_16p background_1,
  191420. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  191421. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  191422. png_uint_16pp gamma_16_to_1, int gamma_shift
  191423. #endif
  191424. )
  191425. {
  191426. png_bytep sp, dp;
  191427. png_uint_32 i;
  191428. png_uint_32 row_width=row_info->width;
  191429. int shift;
  191430. png_debug(1, "in png_do_background\n");
  191431. if (background != NULL &&
  191432. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191433. row != NULL && row_info != NULL &&
  191434. #endif
  191435. (!(row_info->color_type & PNG_COLOR_MASK_ALPHA) ||
  191436. (row_info->color_type != PNG_COLOR_TYPE_PALETTE && trans_values)))
  191437. {
  191438. switch (row_info->color_type)
  191439. {
  191440. case PNG_COLOR_TYPE_GRAY:
  191441. {
  191442. switch (row_info->bit_depth)
  191443. {
  191444. case 1:
  191445. {
  191446. sp = row;
  191447. shift = 7;
  191448. for (i = 0; i < row_width; i++)
  191449. {
  191450. if ((png_uint_16)((*sp >> shift) & 0x01)
  191451. == trans_values->gray)
  191452. {
  191453. *sp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  191454. *sp |= (png_byte)(background->gray << shift);
  191455. }
  191456. if (!shift)
  191457. {
  191458. shift = 7;
  191459. sp++;
  191460. }
  191461. else
  191462. shift--;
  191463. }
  191464. break;
  191465. }
  191466. case 2:
  191467. {
  191468. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191469. if (gamma_table != NULL)
  191470. {
  191471. sp = row;
  191472. shift = 6;
  191473. for (i = 0; i < row_width; i++)
  191474. {
  191475. if ((png_uint_16)((*sp >> shift) & 0x03)
  191476. == trans_values->gray)
  191477. {
  191478. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  191479. *sp |= (png_byte)(background->gray << shift);
  191480. }
  191481. else
  191482. {
  191483. png_byte p = (png_byte)((*sp >> shift) & 0x03);
  191484. png_byte g = (png_byte)((gamma_table [p | (p << 2) |
  191485. (p << 4) | (p << 6)] >> 6) & 0x03);
  191486. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  191487. *sp |= (png_byte)(g << shift);
  191488. }
  191489. if (!shift)
  191490. {
  191491. shift = 6;
  191492. sp++;
  191493. }
  191494. else
  191495. shift -= 2;
  191496. }
  191497. }
  191498. else
  191499. #endif
  191500. {
  191501. sp = row;
  191502. shift = 6;
  191503. for (i = 0; i < row_width; i++)
  191504. {
  191505. if ((png_uint_16)((*sp >> shift) & 0x03)
  191506. == trans_values->gray)
  191507. {
  191508. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  191509. *sp |= (png_byte)(background->gray << shift);
  191510. }
  191511. if (!shift)
  191512. {
  191513. shift = 6;
  191514. sp++;
  191515. }
  191516. else
  191517. shift -= 2;
  191518. }
  191519. }
  191520. break;
  191521. }
  191522. case 4:
  191523. {
  191524. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191525. if (gamma_table != NULL)
  191526. {
  191527. sp = row;
  191528. shift = 4;
  191529. for (i = 0; i < row_width; i++)
  191530. {
  191531. if ((png_uint_16)((*sp >> shift) & 0x0f)
  191532. == trans_values->gray)
  191533. {
  191534. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  191535. *sp |= (png_byte)(background->gray << shift);
  191536. }
  191537. else
  191538. {
  191539. png_byte p = (png_byte)((*sp >> shift) & 0x0f);
  191540. png_byte g = (png_byte)((gamma_table[p |
  191541. (p << 4)] >> 4) & 0x0f);
  191542. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  191543. *sp |= (png_byte)(g << shift);
  191544. }
  191545. if (!shift)
  191546. {
  191547. shift = 4;
  191548. sp++;
  191549. }
  191550. else
  191551. shift -= 4;
  191552. }
  191553. }
  191554. else
  191555. #endif
  191556. {
  191557. sp = row;
  191558. shift = 4;
  191559. for (i = 0; i < row_width; i++)
  191560. {
  191561. if ((png_uint_16)((*sp >> shift) & 0x0f)
  191562. == trans_values->gray)
  191563. {
  191564. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  191565. *sp |= (png_byte)(background->gray << shift);
  191566. }
  191567. if (!shift)
  191568. {
  191569. shift = 4;
  191570. sp++;
  191571. }
  191572. else
  191573. shift -= 4;
  191574. }
  191575. }
  191576. break;
  191577. }
  191578. case 8:
  191579. {
  191580. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191581. if (gamma_table != NULL)
  191582. {
  191583. sp = row;
  191584. for (i = 0; i < row_width; i++, sp++)
  191585. {
  191586. if (*sp == trans_values->gray)
  191587. {
  191588. *sp = (png_byte)background->gray;
  191589. }
  191590. else
  191591. {
  191592. *sp = gamma_table[*sp];
  191593. }
  191594. }
  191595. }
  191596. else
  191597. #endif
  191598. {
  191599. sp = row;
  191600. for (i = 0; i < row_width; i++, sp++)
  191601. {
  191602. if (*sp == trans_values->gray)
  191603. {
  191604. *sp = (png_byte)background->gray;
  191605. }
  191606. }
  191607. }
  191608. break;
  191609. }
  191610. case 16:
  191611. {
  191612. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191613. if (gamma_16 != NULL)
  191614. {
  191615. sp = row;
  191616. for (i = 0; i < row_width; i++, sp += 2)
  191617. {
  191618. png_uint_16 v;
  191619. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  191620. if (v == trans_values->gray)
  191621. {
  191622. /* background is already in screen gamma */
  191623. *sp = (png_byte)((background->gray >> 8) & 0xff);
  191624. *(sp + 1) = (png_byte)(background->gray & 0xff);
  191625. }
  191626. else
  191627. {
  191628. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  191629. *sp = (png_byte)((v >> 8) & 0xff);
  191630. *(sp + 1) = (png_byte)(v & 0xff);
  191631. }
  191632. }
  191633. }
  191634. else
  191635. #endif
  191636. {
  191637. sp = row;
  191638. for (i = 0; i < row_width; i++, sp += 2)
  191639. {
  191640. png_uint_16 v;
  191641. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  191642. if (v == trans_values->gray)
  191643. {
  191644. *sp = (png_byte)((background->gray >> 8) & 0xff);
  191645. *(sp + 1) = (png_byte)(background->gray & 0xff);
  191646. }
  191647. }
  191648. }
  191649. break;
  191650. }
  191651. }
  191652. break;
  191653. }
  191654. case PNG_COLOR_TYPE_RGB:
  191655. {
  191656. if (row_info->bit_depth == 8)
  191657. {
  191658. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191659. if (gamma_table != NULL)
  191660. {
  191661. sp = row;
  191662. for (i = 0; i < row_width; i++, sp += 3)
  191663. {
  191664. if (*sp == trans_values->red &&
  191665. *(sp + 1) == trans_values->green &&
  191666. *(sp + 2) == trans_values->blue)
  191667. {
  191668. *sp = (png_byte)background->red;
  191669. *(sp + 1) = (png_byte)background->green;
  191670. *(sp + 2) = (png_byte)background->blue;
  191671. }
  191672. else
  191673. {
  191674. *sp = gamma_table[*sp];
  191675. *(sp + 1) = gamma_table[*(sp + 1)];
  191676. *(sp + 2) = gamma_table[*(sp + 2)];
  191677. }
  191678. }
  191679. }
  191680. else
  191681. #endif
  191682. {
  191683. sp = row;
  191684. for (i = 0; i < row_width; i++, sp += 3)
  191685. {
  191686. if (*sp == trans_values->red &&
  191687. *(sp + 1) == trans_values->green &&
  191688. *(sp + 2) == trans_values->blue)
  191689. {
  191690. *sp = (png_byte)background->red;
  191691. *(sp + 1) = (png_byte)background->green;
  191692. *(sp + 2) = (png_byte)background->blue;
  191693. }
  191694. }
  191695. }
  191696. }
  191697. else /* if (row_info->bit_depth == 16) */
  191698. {
  191699. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191700. if (gamma_16 != NULL)
  191701. {
  191702. sp = row;
  191703. for (i = 0; i < row_width; i++, sp += 6)
  191704. {
  191705. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  191706. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  191707. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  191708. if (r == trans_values->red && g == trans_values->green &&
  191709. b == trans_values->blue)
  191710. {
  191711. /* background is already in screen gamma */
  191712. *sp = (png_byte)((background->red >> 8) & 0xff);
  191713. *(sp + 1) = (png_byte)(background->red & 0xff);
  191714. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  191715. *(sp + 3) = (png_byte)(background->green & 0xff);
  191716. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  191717. *(sp + 5) = (png_byte)(background->blue & 0xff);
  191718. }
  191719. else
  191720. {
  191721. png_uint_16 v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  191722. *sp = (png_byte)((v >> 8) & 0xff);
  191723. *(sp + 1) = (png_byte)(v & 0xff);
  191724. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  191725. *(sp + 2) = (png_byte)((v >> 8) & 0xff);
  191726. *(sp + 3) = (png_byte)(v & 0xff);
  191727. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  191728. *(sp + 4) = (png_byte)((v >> 8) & 0xff);
  191729. *(sp + 5) = (png_byte)(v & 0xff);
  191730. }
  191731. }
  191732. }
  191733. else
  191734. #endif
  191735. {
  191736. sp = row;
  191737. for (i = 0; i < row_width; i++, sp += 6)
  191738. {
  191739. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp+1));
  191740. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  191741. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  191742. if (r == trans_values->red && g == trans_values->green &&
  191743. b == trans_values->blue)
  191744. {
  191745. *sp = (png_byte)((background->red >> 8) & 0xff);
  191746. *(sp + 1) = (png_byte)(background->red & 0xff);
  191747. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  191748. *(sp + 3) = (png_byte)(background->green & 0xff);
  191749. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  191750. *(sp + 5) = (png_byte)(background->blue & 0xff);
  191751. }
  191752. }
  191753. }
  191754. }
  191755. break;
  191756. }
  191757. case PNG_COLOR_TYPE_GRAY_ALPHA:
  191758. {
  191759. if (row_info->bit_depth == 8)
  191760. {
  191761. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191762. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  191763. gamma_table != NULL)
  191764. {
  191765. sp = row;
  191766. dp = row;
  191767. for (i = 0; i < row_width; i++, sp += 2, dp++)
  191768. {
  191769. png_uint_16 a = *(sp + 1);
  191770. if (a == 0xff)
  191771. {
  191772. *dp = gamma_table[*sp];
  191773. }
  191774. else if (a == 0)
  191775. {
  191776. /* background is already in screen gamma */
  191777. *dp = (png_byte)background->gray;
  191778. }
  191779. else
  191780. {
  191781. png_byte v, w;
  191782. v = gamma_to_1[*sp];
  191783. png_composite(w, v, a, background_1->gray);
  191784. *dp = gamma_from_1[w];
  191785. }
  191786. }
  191787. }
  191788. else
  191789. #endif
  191790. {
  191791. sp = row;
  191792. dp = row;
  191793. for (i = 0; i < row_width; i++, sp += 2, dp++)
  191794. {
  191795. png_byte a = *(sp + 1);
  191796. if (a == 0xff)
  191797. {
  191798. *dp = *sp;
  191799. }
  191800. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191801. else if (a == 0)
  191802. {
  191803. *dp = (png_byte)background->gray;
  191804. }
  191805. else
  191806. {
  191807. png_composite(*dp, *sp, a, background_1->gray);
  191808. }
  191809. #else
  191810. *dp = (png_byte)background->gray;
  191811. #endif
  191812. }
  191813. }
  191814. }
  191815. else /* if (png_ptr->bit_depth == 16) */
  191816. {
  191817. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191818. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  191819. gamma_16_to_1 != NULL)
  191820. {
  191821. sp = row;
  191822. dp = row;
  191823. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  191824. {
  191825. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  191826. if (a == (png_uint_16)0xffff)
  191827. {
  191828. png_uint_16 v;
  191829. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  191830. *dp = (png_byte)((v >> 8) & 0xff);
  191831. *(dp + 1) = (png_byte)(v & 0xff);
  191832. }
  191833. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191834. else if (a == 0)
  191835. #else
  191836. else
  191837. #endif
  191838. {
  191839. /* background is already in screen gamma */
  191840. *dp = (png_byte)((background->gray >> 8) & 0xff);
  191841. *(dp + 1) = (png_byte)(background->gray & 0xff);
  191842. }
  191843. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191844. else
  191845. {
  191846. png_uint_16 g, v, w;
  191847. g = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  191848. png_composite_16(v, g, a, background_1->gray);
  191849. w = gamma_16_from_1[(v&0xff) >> gamma_shift][v >> 8];
  191850. *dp = (png_byte)((w >> 8) & 0xff);
  191851. *(dp + 1) = (png_byte)(w & 0xff);
  191852. }
  191853. #endif
  191854. }
  191855. }
  191856. else
  191857. #endif
  191858. {
  191859. sp = row;
  191860. dp = row;
  191861. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  191862. {
  191863. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  191864. if (a == (png_uint_16)0xffff)
  191865. {
  191866. png_memcpy(dp, sp, 2);
  191867. }
  191868. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191869. else if (a == 0)
  191870. #else
  191871. else
  191872. #endif
  191873. {
  191874. *dp = (png_byte)((background->gray >> 8) & 0xff);
  191875. *(dp + 1) = (png_byte)(background->gray & 0xff);
  191876. }
  191877. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191878. else
  191879. {
  191880. png_uint_16 g, v;
  191881. g = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  191882. png_composite_16(v, g, a, background_1->gray);
  191883. *dp = (png_byte)((v >> 8) & 0xff);
  191884. *(dp + 1) = (png_byte)(v & 0xff);
  191885. }
  191886. #endif
  191887. }
  191888. }
  191889. }
  191890. break;
  191891. }
  191892. case PNG_COLOR_TYPE_RGB_ALPHA:
  191893. {
  191894. if (row_info->bit_depth == 8)
  191895. {
  191896. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191897. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  191898. gamma_table != NULL)
  191899. {
  191900. sp = row;
  191901. dp = row;
  191902. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  191903. {
  191904. png_byte a = *(sp + 3);
  191905. if (a == 0xff)
  191906. {
  191907. *dp = gamma_table[*sp];
  191908. *(dp + 1) = gamma_table[*(sp + 1)];
  191909. *(dp + 2) = gamma_table[*(sp + 2)];
  191910. }
  191911. else if (a == 0)
  191912. {
  191913. /* background is already in screen gamma */
  191914. *dp = (png_byte)background->red;
  191915. *(dp + 1) = (png_byte)background->green;
  191916. *(dp + 2) = (png_byte)background->blue;
  191917. }
  191918. else
  191919. {
  191920. png_byte v, w;
  191921. v = gamma_to_1[*sp];
  191922. png_composite(w, v, a, background_1->red);
  191923. *dp = gamma_from_1[w];
  191924. v = gamma_to_1[*(sp + 1)];
  191925. png_composite(w, v, a, background_1->green);
  191926. *(dp + 1) = gamma_from_1[w];
  191927. v = gamma_to_1[*(sp + 2)];
  191928. png_composite(w, v, a, background_1->blue);
  191929. *(dp + 2) = gamma_from_1[w];
  191930. }
  191931. }
  191932. }
  191933. else
  191934. #endif
  191935. {
  191936. sp = row;
  191937. dp = row;
  191938. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  191939. {
  191940. png_byte a = *(sp + 3);
  191941. if (a == 0xff)
  191942. {
  191943. *dp = *sp;
  191944. *(dp + 1) = *(sp + 1);
  191945. *(dp + 2) = *(sp + 2);
  191946. }
  191947. else if (a == 0)
  191948. {
  191949. *dp = (png_byte)background->red;
  191950. *(dp + 1) = (png_byte)background->green;
  191951. *(dp + 2) = (png_byte)background->blue;
  191952. }
  191953. else
  191954. {
  191955. png_composite(*dp, *sp, a, background->red);
  191956. png_composite(*(dp + 1), *(sp + 1), a,
  191957. background->green);
  191958. png_composite(*(dp + 2), *(sp + 2), a,
  191959. background->blue);
  191960. }
  191961. }
  191962. }
  191963. }
  191964. else /* if (row_info->bit_depth == 16) */
  191965. {
  191966. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191967. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  191968. gamma_16_to_1 != NULL)
  191969. {
  191970. sp = row;
  191971. dp = row;
  191972. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  191973. {
  191974. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  191975. << 8) + (png_uint_16)(*(sp + 7)));
  191976. if (a == (png_uint_16)0xffff)
  191977. {
  191978. png_uint_16 v;
  191979. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  191980. *dp = (png_byte)((v >> 8) & 0xff);
  191981. *(dp + 1) = (png_byte)(v & 0xff);
  191982. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  191983. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  191984. *(dp + 3) = (png_byte)(v & 0xff);
  191985. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  191986. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  191987. *(dp + 5) = (png_byte)(v & 0xff);
  191988. }
  191989. else if (a == 0)
  191990. {
  191991. /* background is already in screen gamma */
  191992. *dp = (png_byte)((background->red >> 8) & 0xff);
  191993. *(dp + 1) = (png_byte)(background->red & 0xff);
  191994. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  191995. *(dp + 3) = (png_byte)(background->green & 0xff);
  191996. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  191997. *(dp + 5) = (png_byte)(background->blue & 0xff);
  191998. }
  191999. else
  192000. {
  192001. png_uint_16 v, w, x;
  192002. v = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  192003. png_composite_16(w, v, a, background_1->red);
  192004. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  192005. *dp = (png_byte)((x >> 8) & 0xff);
  192006. *(dp + 1) = (png_byte)(x & 0xff);
  192007. v = gamma_16_to_1[*(sp + 3) >> gamma_shift][*(sp + 2)];
  192008. png_composite_16(w, v, a, background_1->green);
  192009. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  192010. *(dp + 2) = (png_byte)((x >> 8) & 0xff);
  192011. *(dp + 3) = (png_byte)(x & 0xff);
  192012. v = gamma_16_to_1[*(sp + 5) >> gamma_shift][*(sp + 4)];
  192013. png_composite_16(w, v, a, background_1->blue);
  192014. x = gamma_16_from_1[(w & 0xff) >> gamma_shift][w >> 8];
  192015. *(dp + 4) = (png_byte)((x >> 8) & 0xff);
  192016. *(dp + 5) = (png_byte)(x & 0xff);
  192017. }
  192018. }
  192019. }
  192020. else
  192021. #endif
  192022. {
  192023. sp = row;
  192024. dp = row;
  192025. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  192026. {
  192027. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  192028. << 8) + (png_uint_16)(*(sp + 7)));
  192029. if (a == (png_uint_16)0xffff)
  192030. {
  192031. png_memcpy(dp, sp, 6);
  192032. }
  192033. else if (a == 0)
  192034. {
  192035. *dp = (png_byte)((background->red >> 8) & 0xff);
  192036. *(dp + 1) = (png_byte)(background->red & 0xff);
  192037. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192038. *(dp + 3) = (png_byte)(background->green & 0xff);
  192039. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192040. *(dp + 5) = (png_byte)(background->blue & 0xff);
  192041. }
  192042. else
  192043. {
  192044. png_uint_16 v;
  192045. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192046. png_uint_16 g = (png_uint_16)(((*(sp + 2)) << 8)
  192047. + *(sp + 3));
  192048. png_uint_16 b = (png_uint_16)(((*(sp + 4)) << 8)
  192049. + *(sp + 5));
  192050. png_composite_16(v, r, a, background->red);
  192051. *dp = (png_byte)((v >> 8) & 0xff);
  192052. *(dp + 1) = (png_byte)(v & 0xff);
  192053. png_composite_16(v, g, a, background->green);
  192054. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  192055. *(dp + 3) = (png_byte)(v & 0xff);
  192056. png_composite_16(v, b, a, background->blue);
  192057. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  192058. *(dp + 5) = (png_byte)(v & 0xff);
  192059. }
  192060. }
  192061. }
  192062. }
  192063. break;
  192064. }
  192065. }
  192066. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  192067. {
  192068. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  192069. row_info->channels--;
  192070. row_info->pixel_depth = (png_byte)(row_info->channels *
  192071. row_info->bit_depth);
  192072. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  192073. }
  192074. }
  192075. }
  192076. #endif
  192077. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192078. /* Gamma correct the image, avoiding the alpha channel. Make sure
  192079. * you do this after you deal with the transparency issue on grayscale
  192080. * or RGB images. If your bit depth is 8, use gamma_table, if it
  192081. * is 16, use gamma_16_table and gamma_shift. Build these with
  192082. * build_gamma_table().
  192083. */
  192084. void /* PRIVATE */
  192085. png_do_gamma(png_row_infop row_info, png_bytep row,
  192086. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  192087. int gamma_shift)
  192088. {
  192089. png_bytep sp;
  192090. png_uint_32 i;
  192091. png_uint_32 row_width=row_info->width;
  192092. png_debug(1, "in png_do_gamma\n");
  192093. if (
  192094. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192095. row != NULL && row_info != NULL &&
  192096. #endif
  192097. ((row_info->bit_depth <= 8 && gamma_table != NULL) ||
  192098. (row_info->bit_depth == 16 && gamma_16_table != NULL)))
  192099. {
  192100. switch (row_info->color_type)
  192101. {
  192102. case PNG_COLOR_TYPE_RGB:
  192103. {
  192104. if (row_info->bit_depth == 8)
  192105. {
  192106. sp = row;
  192107. for (i = 0; i < row_width; i++)
  192108. {
  192109. *sp = gamma_table[*sp];
  192110. sp++;
  192111. *sp = gamma_table[*sp];
  192112. sp++;
  192113. *sp = gamma_table[*sp];
  192114. sp++;
  192115. }
  192116. }
  192117. else /* if (row_info->bit_depth == 16) */
  192118. {
  192119. sp = row;
  192120. for (i = 0; i < row_width; i++)
  192121. {
  192122. png_uint_16 v;
  192123. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192124. *sp = (png_byte)((v >> 8) & 0xff);
  192125. *(sp + 1) = (png_byte)(v & 0xff);
  192126. sp += 2;
  192127. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192128. *sp = (png_byte)((v >> 8) & 0xff);
  192129. *(sp + 1) = (png_byte)(v & 0xff);
  192130. sp += 2;
  192131. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192132. *sp = (png_byte)((v >> 8) & 0xff);
  192133. *(sp + 1) = (png_byte)(v & 0xff);
  192134. sp += 2;
  192135. }
  192136. }
  192137. break;
  192138. }
  192139. case PNG_COLOR_TYPE_RGB_ALPHA:
  192140. {
  192141. if (row_info->bit_depth == 8)
  192142. {
  192143. sp = row;
  192144. for (i = 0; i < row_width; i++)
  192145. {
  192146. *sp = gamma_table[*sp];
  192147. sp++;
  192148. *sp = gamma_table[*sp];
  192149. sp++;
  192150. *sp = gamma_table[*sp];
  192151. sp++;
  192152. sp++;
  192153. }
  192154. }
  192155. else /* if (row_info->bit_depth == 16) */
  192156. {
  192157. sp = row;
  192158. for (i = 0; i < row_width; i++)
  192159. {
  192160. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192161. *sp = (png_byte)((v >> 8) & 0xff);
  192162. *(sp + 1) = (png_byte)(v & 0xff);
  192163. sp += 2;
  192164. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192165. *sp = (png_byte)((v >> 8) & 0xff);
  192166. *(sp + 1) = (png_byte)(v & 0xff);
  192167. sp += 2;
  192168. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192169. *sp = (png_byte)((v >> 8) & 0xff);
  192170. *(sp + 1) = (png_byte)(v & 0xff);
  192171. sp += 4;
  192172. }
  192173. }
  192174. break;
  192175. }
  192176. case PNG_COLOR_TYPE_GRAY_ALPHA:
  192177. {
  192178. if (row_info->bit_depth == 8)
  192179. {
  192180. sp = row;
  192181. for (i = 0; i < row_width; i++)
  192182. {
  192183. *sp = gamma_table[*sp];
  192184. sp += 2;
  192185. }
  192186. }
  192187. else /* if (row_info->bit_depth == 16) */
  192188. {
  192189. sp = row;
  192190. for (i = 0; i < row_width; i++)
  192191. {
  192192. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192193. *sp = (png_byte)((v >> 8) & 0xff);
  192194. *(sp + 1) = (png_byte)(v & 0xff);
  192195. sp += 4;
  192196. }
  192197. }
  192198. break;
  192199. }
  192200. case PNG_COLOR_TYPE_GRAY:
  192201. {
  192202. if (row_info->bit_depth == 2)
  192203. {
  192204. sp = row;
  192205. for (i = 0; i < row_width; i += 4)
  192206. {
  192207. int a = *sp & 0xc0;
  192208. int b = *sp & 0x30;
  192209. int c = *sp & 0x0c;
  192210. int d = *sp & 0x03;
  192211. *sp = (png_byte)(
  192212. ((((int)gamma_table[a|(a>>2)|(a>>4)|(a>>6)]) ) & 0xc0)|
  192213. ((((int)gamma_table[(b<<2)|b|(b>>2)|(b>>4)])>>2) & 0x30)|
  192214. ((((int)gamma_table[(c<<4)|(c<<2)|c|(c>>2)])>>4) & 0x0c)|
  192215. ((((int)gamma_table[(d<<6)|(d<<4)|(d<<2)|d])>>6) ));
  192216. sp++;
  192217. }
  192218. }
  192219. if (row_info->bit_depth == 4)
  192220. {
  192221. sp = row;
  192222. for (i = 0; i < row_width; i += 2)
  192223. {
  192224. int msb = *sp & 0xf0;
  192225. int lsb = *sp & 0x0f;
  192226. *sp = (png_byte)((((int)gamma_table[msb | (msb >> 4)]) & 0xf0)
  192227. | (((int)gamma_table[(lsb << 4) | lsb]) >> 4));
  192228. sp++;
  192229. }
  192230. }
  192231. else if (row_info->bit_depth == 8)
  192232. {
  192233. sp = row;
  192234. for (i = 0; i < row_width; i++)
  192235. {
  192236. *sp = gamma_table[*sp];
  192237. sp++;
  192238. }
  192239. }
  192240. else if (row_info->bit_depth == 16)
  192241. {
  192242. sp = row;
  192243. for (i = 0; i < row_width; i++)
  192244. {
  192245. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192246. *sp = (png_byte)((v >> 8) & 0xff);
  192247. *(sp + 1) = (png_byte)(v & 0xff);
  192248. sp += 2;
  192249. }
  192250. }
  192251. break;
  192252. }
  192253. }
  192254. }
  192255. }
  192256. #endif
  192257. #if defined(PNG_READ_EXPAND_SUPPORTED)
  192258. /* Expands a palette row to an RGB or RGBA row depending
  192259. * upon whether you supply trans and num_trans.
  192260. */
  192261. void /* PRIVATE */
  192262. png_do_expand_palette(png_row_infop row_info, png_bytep row,
  192263. png_colorp palette, png_bytep trans, int num_trans)
  192264. {
  192265. int shift, value;
  192266. png_bytep sp, dp;
  192267. png_uint_32 i;
  192268. png_uint_32 row_width=row_info->width;
  192269. png_debug(1, "in png_do_expand_palette\n");
  192270. if (
  192271. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192272. row != NULL && row_info != NULL &&
  192273. #endif
  192274. row_info->color_type == PNG_COLOR_TYPE_PALETTE)
  192275. {
  192276. if (row_info->bit_depth < 8)
  192277. {
  192278. switch (row_info->bit_depth)
  192279. {
  192280. case 1:
  192281. {
  192282. sp = row + (png_size_t)((row_width - 1) >> 3);
  192283. dp = row + (png_size_t)row_width - 1;
  192284. shift = 7 - (int)((row_width + 7) & 0x07);
  192285. for (i = 0; i < row_width; i++)
  192286. {
  192287. if ((*sp >> shift) & 0x01)
  192288. *dp = 1;
  192289. else
  192290. *dp = 0;
  192291. if (shift == 7)
  192292. {
  192293. shift = 0;
  192294. sp--;
  192295. }
  192296. else
  192297. shift++;
  192298. dp--;
  192299. }
  192300. break;
  192301. }
  192302. case 2:
  192303. {
  192304. sp = row + (png_size_t)((row_width - 1) >> 2);
  192305. dp = row + (png_size_t)row_width - 1;
  192306. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  192307. for (i = 0; i < row_width; i++)
  192308. {
  192309. value = (*sp >> shift) & 0x03;
  192310. *dp = (png_byte)value;
  192311. if (shift == 6)
  192312. {
  192313. shift = 0;
  192314. sp--;
  192315. }
  192316. else
  192317. shift += 2;
  192318. dp--;
  192319. }
  192320. break;
  192321. }
  192322. case 4:
  192323. {
  192324. sp = row + (png_size_t)((row_width - 1) >> 1);
  192325. dp = row + (png_size_t)row_width - 1;
  192326. shift = (int)((row_width & 0x01) << 2);
  192327. for (i = 0; i < row_width; i++)
  192328. {
  192329. value = (*sp >> shift) & 0x0f;
  192330. *dp = (png_byte)value;
  192331. if (shift == 4)
  192332. {
  192333. shift = 0;
  192334. sp--;
  192335. }
  192336. else
  192337. shift += 4;
  192338. dp--;
  192339. }
  192340. break;
  192341. }
  192342. }
  192343. row_info->bit_depth = 8;
  192344. row_info->pixel_depth = 8;
  192345. row_info->rowbytes = row_width;
  192346. }
  192347. switch (row_info->bit_depth)
  192348. {
  192349. case 8:
  192350. {
  192351. if (trans != NULL)
  192352. {
  192353. sp = row + (png_size_t)row_width - 1;
  192354. dp = row + (png_size_t)(row_width << 2) - 1;
  192355. for (i = 0; i < row_width; i++)
  192356. {
  192357. if ((int)(*sp) >= num_trans)
  192358. *dp-- = 0xff;
  192359. else
  192360. *dp-- = trans[*sp];
  192361. *dp-- = palette[*sp].blue;
  192362. *dp-- = palette[*sp].green;
  192363. *dp-- = palette[*sp].red;
  192364. sp--;
  192365. }
  192366. row_info->bit_depth = 8;
  192367. row_info->pixel_depth = 32;
  192368. row_info->rowbytes = row_width * 4;
  192369. row_info->color_type = 6;
  192370. row_info->channels = 4;
  192371. }
  192372. else
  192373. {
  192374. sp = row + (png_size_t)row_width - 1;
  192375. dp = row + (png_size_t)(row_width * 3) - 1;
  192376. for (i = 0; i < row_width; i++)
  192377. {
  192378. *dp-- = palette[*sp].blue;
  192379. *dp-- = palette[*sp].green;
  192380. *dp-- = palette[*sp].red;
  192381. sp--;
  192382. }
  192383. row_info->bit_depth = 8;
  192384. row_info->pixel_depth = 24;
  192385. row_info->rowbytes = row_width * 3;
  192386. row_info->color_type = 2;
  192387. row_info->channels = 3;
  192388. }
  192389. break;
  192390. }
  192391. }
  192392. }
  192393. }
  192394. /* If the bit depth < 8, it is expanded to 8. Also, if the already
  192395. * expanded transparency value is supplied, an alpha channel is built.
  192396. */
  192397. void /* PRIVATE */
  192398. png_do_expand(png_row_infop row_info, png_bytep row,
  192399. png_color_16p trans_value)
  192400. {
  192401. int shift, value;
  192402. png_bytep sp, dp;
  192403. png_uint_32 i;
  192404. png_uint_32 row_width=row_info->width;
  192405. png_debug(1, "in png_do_expand\n");
  192406. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192407. if (row != NULL && row_info != NULL)
  192408. #endif
  192409. {
  192410. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  192411. {
  192412. png_uint_16 gray = (png_uint_16)(trans_value ? trans_value->gray : 0);
  192413. if (row_info->bit_depth < 8)
  192414. {
  192415. switch (row_info->bit_depth)
  192416. {
  192417. case 1:
  192418. {
  192419. gray = (png_uint_16)((gray&0x01)*0xff);
  192420. sp = row + (png_size_t)((row_width - 1) >> 3);
  192421. dp = row + (png_size_t)row_width - 1;
  192422. shift = 7 - (int)((row_width + 7) & 0x07);
  192423. for (i = 0; i < row_width; i++)
  192424. {
  192425. if ((*sp >> shift) & 0x01)
  192426. *dp = 0xff;
  192427. else
  192428. *dp = 0;
  192429. if (shift == 7)
  192430. {
  192431. shift = 0;
  192432. sp--;
  192433. }
  192434. else
  192435. shift++;
  192436. dp--;
  192437. }
  192438. break;
  192439. }
  192440. case 2:
  192441. {
  192442. gray = (png_uint_16)((gray&0x03)*0x55);
  192443. sp = row + (png_size_t)((row_width - 1) >> 2);
  192444. dp = row + (png_size_t)row_width - 1;
  192445. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  192446. for (i = 0; i < row_width; i++)
  192447. {
  192448. value = (*sp >> shift) & 0x03;
  192449. *dp = (png_byte)(value | (value << 2) | (value << 4) |
  192450. (value << 6));
  192451. if (shift == 6)
  192452. {
  192453. shift = 0;
  192454. sp--;
  192455. }
  192456. else
  192457. shift += 2;
  192458. dp--;
  192459. }
  192460. break;
  192461. }
  192462. case 4:
  192463. {
  192464. gray = (png_uint_16)((gray&0x0f)*0x11);
  192465. sp = row + (png_size_t)((row_width - 1) >> 1);
  192466. dp = row + (png_size_t)row_width - 1;
  192467. shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  192468. for (i = 0; i < row_width; i++)
  192469. {
  192470. value = (*sp >> shift) & 0x0f;
  192471. *dp = (png_byte)(value | (value << 4));
  192472. if (shift == 4)
  192473. {
  192474. shift = 0;
  192475. sp--;
  192476. }
  192477. else
  192478. shift = 4;
  192479. dp--;
  192480. }
  192481. break;
  192482. }
  192483. }
  192484. row_info->bit_depth = 8;
  192485. row_info->pixel_depth = 8;
  192486. row_info->rowbytes = row_width;
  192487. }
  192488. if (trans_value != NULL)
  192489. {
  192490. if (row_info->bit_depth == 8)
  192491. {
  192492. gray = gray & 0xff;
  192493. sp = row + (png_size_t)row_width - 1;
  192494. dp = row + (png_size_t)(row_width << 1) - 1;
  192495. for (i = 0; i < row_width; i++)
  192496. {
  192497. if (*sp == gray)
  192498. *dp-- = 0;
  192499. else
  192500. *dp-- = 0xff;
  192501. *dp-- = *sp--;
  192502. }
  192503. }
  192504. else if (row_info->bit_depth == 16)
  192505. {
  192506. png_byte gray_high = (gray >> 8) & 0xff;
  192507. png_byte gray_low = gray & 0xff;
  192508. sp = row + row_info->rowbytes - 1;
  192509. dp = row + (row_info->rowbytes << 1) - 1;
  192510. for (i = 0; i < row_width; i++)
  192511. {
  192512. if (*(sp-1) == gray_high && *(sp) == gray_low)
  192513. {
  192514. *dp-- = 0;
  192515. *dp-- = 0;
  192516. }
  192517. else
  192518. {
  192519. *dp-- = 0xff;
  192520. *dp-- = 0xff;
  192521. }
  192522. *dp-- = *sp--;
  192523. *dp-- = *sp--;
  192524. }
  192525. }
  192526. row_info->color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
  192527. row_info->channels = 2;
  192528. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 1);
  192529. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  192530. row_width);
  192531. }
  192532. }
  192533. else if (row_info->color_type == PNG_COLOR_TYPE_RGB && trans_value)
  192534. {
  192535. if (row_info->bit_depth == 8)
  192536. {
  192537. png_byte red = trans_value->red & 0xff;
  192538. png_byte green = trans_value->green & 0xff;
  192539. png_byte blue = trans_value->blue & 0xff;
  192540. sp = row + (png_size_t)row_info->rowbytes - 1;
  192541. dp = row + (png_size_t)(row_width << 2) - 1;
  192542. for (i = 0; i < row_width; i++)
  192543. {
  192544. if (*(sp - 2) == red && *(sp - 1) == green && *(sp) == blue)
  192545. *dp-- = 0;
  192546. else
  192547. *dp-- = 0xff;
  192548. *dp-- = *sp--;
  192549. *dp-- = *sp--;
  192550. *dp-- = *sp--;
  192551. }
  192552. }
  192553. else if (row_info->bit_depth == 16)
  192554. {
  192555. png_byte red_high = (trans_value->red >> 8) & 0xff;
  192556. png_byte green_high = (trans_value->green >> 8) & 0xff;
  192557. png_byte blue_high = (trans_value->blue >> 8) & 0xff;
  192558. png_byte red_low = trans_value->red & 0xff;
  192559. png_byte green_low = trans_value->green & 0xff;
  192560. png_byte blue_low = trans_value->blue & 0xff;
  192561. sp = row + row_info->rowbytes - 1;
  192562. dp = row + (png_size_t)(row_width << 3) - 1;
  192563. for (i = 0; i < row_width; i++)
  192564. {
  192565. if (*(sp - 5) == red_high &&
  192566. *(sp - 4) == red_low &&
  192567. *(sp - 3) == green_high &&
  192568. *(sp - 2) == green_low &&
  192569. *(sp - 1) == blue_high &&
  192570. *(sp ) == blue_low)
  192571. {
  192572. *dp-- = 0;
  192573. *dp-- = 0;
  192574. }
  192575. else
  192576. {
  192577. *dp-- = 0xff;
  192578. *dp-- = 0xff;
  192579. }
  192580. *dp-- = *sp--;
  192581. *dp-- = *sp--;
  192582. *dp-- = *sp--;
  192583. *dp-- = *sp--;
  192584. *dp-- = *sp--;
  192585. *dp-- = *sp--;
  192586. }
  192587. }
  192588. row_info->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  192589. row_info->channels = 4;
  192590. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 2);
  192591. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  192592. }
  192593. }
  192594. }
  192595. #endif
  192596. #if defined(PNG_READ_DITHER_SUPPORTED)
  192597. void /* PRIVATE */
  192598. png_do_dither(png_row_infop row_info, png_bytep row,
  192599. png_bytep palette_lookup, png_bytep dither_lookup)
  192600. {
  192601. png_bytep sp, dp;
  192602. png_uint_32 i;
  192603. png_uint_32 row_width=row_info->width;
  192604. png_debug(1, "in png_do_dither\n");
  192605. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192606. if (row != NULL && row_info != NULL)
  192607. #endif
  192608. {
  192609. if (row_info->color_type == PNG_COLOR_TYPE_RGB &&
  192610. palette_lookup && row_info->bit_depth == 8)
  192611. {
  192612. int r, g, b, p;
  192613. sp = row;
  192614. dp = row;
  192615. for (i = 0; i < row_width; i++)
  192616. {
  192617. r = *sp++;
  192618. g = *sp++;
  192619. b = *sp++;
  192620. /* this looks real messy, but the compiler will reduce
  192621. it down to a reasonable formula. For example, with
  192622. 5 bits per color, we get:
  192623. p = (((r >> 3) & 0x1f) << 10) |
  192624. (((g >> 3) & 0x1f) << 5) |
  192625. ((b >> 3) & 0x1f);
  192626. */
  192627. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  192628. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  192629. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  192630. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  192631. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  192632. (PNG_DITHER_BLUE_BITS)) |
  192633. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  192634. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  192635. *dp++ = palette_lookup[p];
  192636. }
  192637. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  192638. row_info->channels = 1;
  192639. row_info->pixel_depth = row_info->bit_depth;
  192640. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  192641. }
  192642. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  192643. palette_lookup != NULL && row_info->bit_depth == 8)
  192644. {
  192645. int r, g, b, p;
  192646. sp = row;
  192647. dp = row;
  192648. for (i = 0; i < row_width; i++)
  192649. {
  192650. r = *sp++;
  192651. g = *sp++;
  192652. b = *sp++;
  192653. sp++;
  192654. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  192655. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  192656. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  192657. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  192658. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  192659. (PNG_DITHER_BLUE_BITS)) |
  192660. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  192661. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  192662. *dp++ = palette_lookup[p];
  192663. }
  192664. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  192665. row_info->channels = 1;
  192666. row_info->pixel_depth = row_info->bit_depth;
  192667. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  192668. }
  192669. else if (row_info->color_type == PNG_COLOR_TYPE_PALETTE &&
  192670. dither_lookup && row_info->bit_depth == 8)
  192671. {
  192672. sp = row;
  192673. for (i = 0; i < row_width; i++, sp++)
  192674. {
  192675. *sp = dither_lookup[*sp];
  192676. }
  192677. }
  192678. }
  192679. }
  192680. #endif
  192681. #ifdef PNG_FLOATING_POINT_SUPPORTED
  192682. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192683. static PNG_CONST int png_gamma_shift[] =
  192684. {0x10, 0x21, 0x42, 0x84, 0x110, 0x248, 0x550, 0xff0, 0x00};
  192685. /* We build the 8- or 16-bit gamma tables here. Note that for 16-bit
  192686. * tables, we don't make a full table if we are reducing to 8-bit in
  192687. * the future. Note also how the gamma_16 tables are segmented so that
  192688. * we don't need to allocate > 64K chunks for a full 16-bit table.
  192689. */
  192690. void /* PRIVATE */
  192691. png_build_gamma_table(png_structp png_ptr)
  192692. {
  192693. png_debug(1, "in png_build_gamma_table\n");
  192694. if (png_ptr->bit_depth <= 8)
  192695. {
  192696. int i;
  192697. double g;
  192698. if (png_ptr->screen_gamma > .000001)
  192699. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  192700. else
  192701. g = 1.0;
  192702. png_ptr->gamma_table = (png_bytep)png_malloc(png_ptr,
  192703. (png_uint_32)256);
  192704. for (i = 0; i < 256; i++)
  192705. {
  192706. png_ptr->gamma_table[i] = (png_byte)(pow((double)i / 255.0,
  192707. g) * 255.0 + .5);
  192708. }
  192709. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  192710. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  192711. if (png_ptr->transformations & ((PNG_BACKGROUND) | PNG_RGB_TO_GRAY))
  192712. {
  192713. g = 1.0 / (png_ptr->gamma);
  192714. png_ptr->gamma_to_1 = (png_bytep)png_malloc(png_ptr,
  192715. (png_uint_32)256);
  192716. for (i = 0; i < 256; i++)
  192717. {
  192718. png_ptr->gamma_to_1[i] = (png_byte)(pow((double)i / 255.0,
  192719. g) * 255.0 + .5);
  192720. }
  192721. png_ptr->gamma_from_1 = (png_bytep)png_malloc(png_ptr,
  192722. (png_uint_32)256);
  192723. if(png_ptr->screen_gamma > 0.000001)
  192724. g = 1.0 / png_ptr->screen_gamma;
  192725. else
  192726. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  192727. for (i = 0; i < 256; i++)
  192728. {
  192729. png_ptr->gamma_from_1[i] = (png_byte)(pow((double)i / 255.0,
  192730. g) * 255.0 + .5);
  192731. }
  192732. }
  192733. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  192734. }
  192735. else
  192736. {
  192737. double g;
  192738. int i, j, shift, num;
  192739. int sig_bit;
  192740. png_uint_32 ig;
  192741. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  192742. {
  192743. sig_bit = (int)png_ptr->sig_bit.red;
  192744. if ((int)png_ptr->sig_bit.green > sig_bit)
  192745. sig_bit = png_ptr->sig_bit.green;
  192746. if ((int)png_ptr->sig_bit.blue > sig_bit)
  192747. sig_bit = png_ptr->sig_bit.blue;
  192748. }
  192749. else
  192750. {
  192751. sig_bit = (int)png_ptr->sig_bit.gray;
  192752. }
  192753. if (sig_bit > 0)
  192754. shift = 16 - sig_bit;
  192755. else
  192756. shift = 0;
  192757. if (png_ptr->transformations & PNG_16_TO_8)
  192758. {
  192759. if (shift < (16 - PNG_MAX_GAMMA_8))
  192760. shift = (16 - PNG_MAX_GAMMA_8);
  192761. }
  192762. if (shift > 8)
  192763. shift = 8;
  192764. if (shift < 0)
  192765. shift = 0;
  192766. png_ptr->gamma_shift = (png_byte)shift;
  192767. num = (1 << (8 - shift));
  192768. if (png_ptr->screen_gamma > .000001)
  192769. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  192770. else
  192771. g = 1.0;
  192772. png_ptr->gamma_16_table = (png_uint_16pp)png_malloc(png_ptr,
  192773. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  192774. if (png_ptr->transformations & (PNG_16_TO_8 | PNG_BACKGROUND))
  192775. {
  192776. double fin, fout;
  192777. png_uint_32 last, max;
  192778. for (i = 0; i < num; i++)
  192779. {
  192780. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  192781. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  192782. }
  192783. g = 1.0 / g;
  192784. last = 0;
  192785. for (i = 0; i < 256; i++)
  192786. {
  192787. fout = ((double)i + 0.5) / 256.0;
  192788. fin = pow(fout, g);
  192789. max = (png_uint_32)(fin * (double)((png_uint_32)num << 8));
  192790. while (last <= max)
  192791. {
  192792. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  192793. [(int)(last >> (8 - shift))] = (png_uint_16)(
  192794. (png_uint_16)i | ((png_uint_16)i << 8));
  192795. last++;
  192796. }
  192797. }
  192798. while (last < ((png_uint_32)num << 8))
  192799. {
  192800. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  192801. [(int)(last >> (8 - shift))] = (png_uint_16)65535L;
  192802. last++;
  192803. }
  192804. }
  192805. else
  192806. {
  192807. for (i = 0; i < num; i++)
  192808. {
  192809. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  192810. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  192811. ig = (((png_uint_32)i * (png_uint_32)png_gamma_shift[shift]) >> 4);
  192812. for (j = 0; j < 256; j++)
  192813. {
  192814. png_ptr->gamma_16_table[i][j] =
  192815. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  192816. 65535.0, g) * 65535.0 + .5);
  192817. }
  192818. }
  192819. }
  192820. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  192821. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  192822. if (png_ptr->transformations & (PNG_BACKGROUND | PNG_RGB_TO_GRAY))
  192823. {
  192824. g = 1.0 / (png_ptr->gamma);
  192825. png_ptr->gamma_16_to_1 = (png_uint_16pp)png_malloc(png_ptr,
  192826. (png_uint_32)(num * png_sizeof (png_uint_16p )));
  192827. for (i = 0; i < num; i++)
  192828. {
  192829. png_ptr->gamma_16_to_1[i] = (png_uint_16p)png_malloc(png_ptr,
  192830. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  192831. ig = (((png_uint_32)i *
  192832. (png_uint_32)png_gamma_shift[shift]) >> 4);
  192833. for (j = 0; j < 256; j++)
  192834. {
  192835. png_ptr->gamma_16_to_1[i][j] =
  192836. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  192837. 65535.0, g) * 65535.0 + .5);
  192838. }
  192839. }
  192840. if(png_ptr->screen_gamma > 0.000001)
  192841. g = 1.0 / png_ptr->screen_gamma;
  192842. else
  192843. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  192844. png_ptr->gamma_16_from_1 = (png_uint_16pp)png_malloc(png_ptr,
  192845. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  192846. for (i = 0; i < num; i++)
  192847. {
  192848. png_ptr->gamma_16_from_1[i] = (png_uint_16p)png_malloc(png_ptr,
  192849. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  192850. ig = (((png_uint_32)i *
  192851. (png_uint_32)png_gamma_shift[shift]) >> 4);
  192852. for (j = 0; j < 256; j++)
  192853. {
  192854. png_ptr->gamma_16_from_1[i][j] =
  192855. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  192856. 65535.0, g) * 65535.0 + .5);
  192857. }
  192858. }
  192859. }
  192860. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  192861. }
  192862. }
  192863. #endif
  192864. /* To do: install integer version of png_build_gamma_table here */
  192865. #endif
  192866. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  192867. /* undoes intrapixel differencing */
  192868. void /* PRIVATE */
  192869. png_do_read_intrapixel(png_row_infop row_info, png_bytep row)
  192870. {
  192871. png_debug(1, "in png_do_read_intrapixel\n");
  192872. if (
  192873. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192874. row != NULL && row_info != NULL &&
  192875. #endif
  192876. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  192877. {
  192878. int bytes_per_pixel;
  192879. png_uint_32 row_width = row_info->width;
  192880. if (row_info->bit_depth == 8)
  192881. {
  192882. png_bytep rp;
  192883. png_uint_32 i;
  192884. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  192885. bytes_per_pixel = 3;
  192886. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  192887. bytes_per_pixel = 4;
  192888. else
  192889. return;
  192890. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  192891. {
  192892. *(rp) = (png_byte)((256 + *rp + *(rp+1))&0xff);
  192893. *(rp+2) = (png_byte)((256 + *(rp+2) + *(rp+1))&0xff);
  192894. }
  192895. }
  192896. else if (row_info->bit_depth == 16)
  192897. {
  192898. png_bytep rp;
  192899. png_uint_32 i;
  192900. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  192901. bytes_per_pixel = 6;
  192902. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  192903. bytes_per_pixel = 8;
  192904. else
  192905. return;
  192906. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  192907. {
  192908. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  192909. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  192910. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  192911. png_uint_32 red = (png_uint_32)((s0+s1+65536L) & 0xffffL);
  192912. png_uint_32 blue = (png_uint_32)((s2+s1+65536L) & 0xffffL);
  192913. *(rp ) = (png_byte)((red >> 8) & 0xff);
  192914. *(rp+1) = (png_byte)(red & 0xff);
  192915. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  192916. *(rp+5) = (png_byte)(blue & 0xff);
  192917. }
  192918. }
  192919. }
  192920. }
  192921. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  192922. #endif /* PNG_READ_SUPPORTED */
  192923. /*** End of inlined file: pngrtran.c ***/
  192924. /*** Start of inlined file: pngrutil.c ***/
  192925. /* pngrutil.c - utilities to read a PNG file
  192926. *
  192927. * Last changed in libpng 1.2.21 [October 4, 2007]
  192928. * For conditions of distribution and use, see copyright notice in png.h
  192929. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  192930. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  192931. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  192932. *
  192933. * This file contains routines that are only called from within
  192934. * libpng itself during the course of reading an image.
  192935. */
  192936. #define PNG_INTERNAL
  192937. #if defined(PNG_READ_SUPPORTED)
  192938. #if defined(_WIN32_WCE) && (_WIN32_WCE<0x500)
  192939. # define WIN32_WCE_OLD
  192940. #endif
  192941. #ifdef PNG_FLOATING_POINT_SUPPORTED
  192942. # if defined(WIN32_WCE_OLD)
  192943. /* strtod() function is not supported on WindowsCE */
  192944. __inline double png_strtod(png_structp png_ptr, PNG_CONST char *nptr, char **endptr)
  192945. {
  192946. double result = 0;
  192947. int len;
  192948. wchar_t *str, *end;
  192949. len = MultiByteToWideChar(CP_ACP, 0, nptr, -1, NULL, 0);
  192950. str = (wchar_t *)png_malloc(png_ptr, len * sizeof(wchar_t));
  192951. if ( NULL != str )
  192952. {
  192953. MultiByteToWideChar(CP_ACP, 0, nptr, -1, str, len);
  192954. result = wcstod(str, &end);
  192955. len = WideCharToMultiByte(CP_ACP, 0, end, -1, NULL, 0, NULL, NULL);
  192956. *endptr = (char *)nptr + (png_strlen(nptr) - len + 1);
  192957. png_free(png_ptr, str);
  192958. }
  192959. return result;
  192960. }
  192961. # else
  192962. # define png_strtod(p,a,b) strtod(a,b)
  192963. # endif
  192964. #endif
  192965. png_uint_32 PNGAPI
  192966. png_get_uint_31(png_structp png_ptr, png_bytep buf)
  192967. {
  192968. png_uint_32 i = png_get_uint_32(buf);
  192969. if (i > PNG_UINT_31_MAX)
  192970. png_error(png_ptr, "PNG unsigned integer out of range.");
  192971. return (i);
  192972. }
  192973. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  192974. /* Grab an unsigned 32-bit integer from a buffer in big-endian format. */
  192975. png_uint_32 PNGAPI
  192976. png_get_uint_32(png_bytep buf)
  192977. {
  192978. png_uint_32 i = ((png_uint_32)(*buf) << 24) +
  192979. ((png_uint_32)(*(buf + 1)) << 16) +
  192980. ((png_uint_32)(*(buf + 2)) << 8) +
  192981. (png_uint_32)(*(buf + 3));
  192982. return (i);
  192983. }
  192984. /* Grab a signed 32-bit integer from a buffer in big-endian format. The
  192985. * data is stored in the PNG file in two's complement format, and it is
  192986. * assumed that the machine format for signed integers is the same. */
  192987. png_int_32 PNGAPI
  192988. png_get_int_32(png_bytep buf)
  192989. {
  192990. png_int_32 i = ((png_int_32)(*buf) << 24) +
  192991. ((png_int_32)(*(buf + 1)) << 16) +
  192992. ((png_int_32)(*(buf + 2)) << 8) +
  192993. (png_int_32)(*(buf + 3));
  192994. return (i);
  192995. }
  192996. /* Grab an unsigned 16-bit integer from a buffer in big-endian format. */
  192997. png_uint_16 PNGAPI
  192998. png_get_uint_16(png_bytep buf)
  192999. {
  193000. png_uint_16 i = (png_uint_16)(((png_uint_16)(*buf) << 8) +
  193001. (png_uint_16)(*(buf + 1)));
  193002. return (i);
  193003. }
  193004. #endif /* PNG_READ_BIG_ENDIAN_SUPPORTED */
  193005. /* Read data, and (optionally) run it through the CRC. */
  193006. void /* PRIVATE */
  193007. png_crc_read(png_structp png_ptr, png_bytep buf, png_size_t length)
  193008. {
  193009. if(png_ptr == NULL) return;
  193010. png_read_data(png_ptr, buf, length);
  193011. png_calculate_crc(png_ptr, buf, length);
  193012. }
  193013. /* Optionally skip data and then check the CRC. Depending on whether we
  193014. are reading a ancillary or critical chunk, and how the program has set
  193015. things up, we may calculate the CRC on the data and print a message.
  193016. Returns '1' if there was a CRC error, '0' otherwise. */
  193017. int /* PRIVATE */
  193018. png_crc_finish(png_structp png_ptr, png_uint_32 skip)
  193019. {
  193020. png_size_t i;
  193021. png_size_t istop = png_ptr->zbuf_size;
  193022. for (i = (png_size_t)skip; i > istop; i -= istop)
  193023. {
  193024. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  193025. }
  193026. if (i)
  193027. {
  193028. png_crc_read(png_ptr, png_ptr->zbuf, i);
  193029. }
  193030. if (png_crc_error(png_ptr))
  193031. {
  193032. if (((png_ptr->chunk_name[0] & 0x20) && /* Ancillary */
  193033. !(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)) ||
  193034. (!(png_ptr->chunk_name[0] & 0x20) && /* Critical */
  193035. (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_USE)))
  193036. {
  193037. png_chunk_warning(png_ptr, "CRC error");
  193038. }
  193039. else
  193040. {
  193041. png_chunk_error(png_ptr, "CRC error");
  193042. }
  193043. return (1);
  193044. }
  193045. return (0);
  193046. }
  193047. /* Compare the CRC stored in the PNG file with that calculated by libpng from
  193048. the data it has read thus far. */
  193049. int /* PRIVATE */
  193050. png_crc_error(png_structp png_ptr)
  193051. {
  193052. png_byte crc_bytes[4];
  193053. png_uint_32 crc;
  193054. int need_crc = 1;
  193055. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  193056. {
  193057. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  193058. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  193059. need_crc = 0;
  193060. }
  193061. else /* critical */
  193062. {
  193063. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  193064. need_crc = 0;
  193065. }
  193066. png_read_data(png_ptr, crc_bytes, 4);
  193067. if (need_crc)
  193068. {
  193069. crc = png_get_uint_32(crc_bytes);
  193070. return ((int)(crc != png_ptr->crc));
  193071. }
  193072. else
  193073. return (0);
  193074. }
  193075. #if defined(PNG_READ_zTXt_SUPPORTED) || defined(PNG_READ_iTXt_SUPPORTED) || \
  193076. defined(PNG_READ_iCCP_SUPPORTED)
  193077. /*
  193078. * Decompress trailing data in a chunk. The assumption is that chunkdata
  193079. * points at an allocated area holding the contents of a chunk with a
  193080. * trailing compressed part. What we get back is an allocated area
  193081. * holding the original prefix part and an uncompressed version of the
  193082. * trailing part (the malloc area passed in is freed).
  193083. */
  193084. png_charp /* PRIVATE */
  193085. png_decompress_chunk(png_structp png_ptr, int comp_type,
  193086. png_charp chunkdata, png_size_t chunklength,
  193087. png_size_t prefix_size, png_size_t *newlength)
  193088. {
  193089. static PNG_CONST char msg[] = "Error decoding compressed text";
  193090. png_charp text;
  193091. png_size_t text_size;
  193092. if (comp_type == PNG_COMPRESSION_TYPE_BASE)
  193093. {
  193094. int ret = Z_OK;
  193095. png_ptr->zstream.next_in = (png_bytep)(chunkdata + prefix_size);
  193096. png_ptr->zstream.avail_in = (uInt)(chunklength - prefix_size);
  193097. png_ptr->zstream.next_out = png_ptr->zbuf;
  193098. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  193099. text_size = 0;
  193100. text = NULL;
  193101. while (png_ptr->zstream.avail_in)
  193102. {
  193103. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  193104. if (ret != Z_OK && ret != Z_STREAM_END)
  193105. {
  193106. if (png_ptr->zstream.msg != NULL)
  193107. png_warning(png_ptr, png_ptr->zstream.msg);
  193108. else
  193109. png_warning(png_ptr, msg);
  193110. inflateReset(&png_ptr->zstream);
  193111. png_ptr->zstream.avail_in = 0;
  193112. if (text == NULL)
  193113. {
  193114. text_size = prefix_size + png_sizeof(msg) + 1;
  193115. text = (png_charp)png_malloc_warn(png_ptr, text_size);
  193116. if (text == NULL)
  193117. {
  193118. png_free(png_ptr,chunkdata);
  193119. png_error(png_ptr,"Not enough memory to decompress chunk");
  193120. }
  193121. png_memcpy(text, chunkdata, prefix_size);
  193122. }
  193123. text[text_size - 1] = 0x00;
  193124. /* Copy what we can of the error message into the text chunk */
  193125. text_size = (png_size_t)(chunklength - (text - chunkdata) - 1);
  193126. text_size = png_sizeof(msg) > text_size ? text_size :
  193127. png_sizeof(msg);
  193128. png_memcpy(text + prefix_size, msg, text_size + 1);
  193129. break;
  193130. }
  193131. if (!png_ptr->zstream.avail_out || ret == Z_STREAM_END)
  193132. {
  193133. if (text == NULL)
  193134. {
  193135. text_size = prefix_size +
  193136. png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  193137. text = (png_charp)png_malloc_warn(png_ptr, text_size + 1);
  193138. if (text == NULL)
  193139. {
  193140. png_free(png_ptr,chunkdata);
  193141. png_error(png_ptr,"Not enough memory to decompress chunk.");
  193142. }
  193143. png_memcpy(text + prefix_size, png_ptr->zbuf,
  193144. text_size - prefix_size);
  193145. png_memcpy(text, chunkdata, prefix_size);
  193146. *(text + text_size) = 0x00;
  193147. }
  193148. else
  193149. {
  193150. png_charp tmp;
  193151. tmp = text;
  193152. text = (png_charp)png_malloc_warn(png_ptr,
  193153. (png_uint_32)(text_size +
  193154. png_ptr->zbuf_size - png_ptr->zstream.avail_out + 1));
  193155. if (text == NULL)
  193156. {
  193157. png_free(png_ptr, tmp);
  193158. png_free(png_ptr, chunkdata);
  193159. png_error(png_ptr,"Not enough memory to decompress chunk..");
  193160. }
  193161. png_memcpy(text, tmp, text_size);
  193162. png_free(png_ptr, tmp);
  193163. png_memcpy(text + text_size, png_ptr->zbuf,
  193164. (png_ptr->zbuf_size - png_ptr->zstream.avail_out));
  193165. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  193166. *(text + text_size) = 0x00;
  193167. }
  193168. if (ret == Z_STREAM_END)
  193169. break;
  193170. else
  193171. {
  193172. png_ptr->zstream.next_out = png_ptr->zbuf;
  193173. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  193174. }
  193175. }
  193176. }
  193177. if (ret != Z_STREAM_END)
  193178. {
  193179. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  193180. char umsg[52];
  193181. if (ret == Z_BUF_ERROR)
  193182. png_snprintf(umsg, 52,
  193183. "Buffer error in compressed datastream in %s chunk",
  193184. png_ptr->chunk_name);
  193185. else if (ret == Z_DATA_ERROR)
  193186. png_snprintf(umsg, 52,
  193187. "Data error in compressed datastream in %s chunk",
  193188. png_ptr->chunk_name);
  193189. else
  193190. png_snprintf(umsg, 52,
  193191. "Incomplete compressed datastream in %s chunk",
  193192. png_ptr->chunk_name);
  193193. png_warning(png_ptr, umsg);
  193194. #else
  193195. png_warning(png_ptr,
  193196. "Incomplete compressed datastream in chunk other than IDAT");
  193197. #endif
  193198. text_size=prefix_size;
  193199. if (text == NULL)
  193200. {
  193201. text = (png_charp)png_malloc_warn(png_ptr, text_size+1);
  193202. if (text == NULL)
  193203. {
  193204. png_free(png_ptr, chunkdata);
  193205. png_error(png_ptr,"Not enough memory for text.");
  193206. }
  193207. png_memcpy(text, chunkdata, prefix_size);
  193208. }
  193209. *(text + text_size) = 0x00;
  193210. }
  193211. inflateReset(&png_ptr->zstream);
  193212. png_ptr->zstream.avail_in = 0;
  193213. png_free(png_ptr, chunkdata);
  193214. chunkdata = text;
  193215. *newlength=text_size;
  193216. }
  193217. else /* if (comp_type != PNG_COMPRESSION_TYPE_BASE) */
  193218. {
  193219. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  193220. char umsg[50];
  193221. png_snprintf(umsg, 50,
  193222. "Unknown zTXt compression type %d", comp_type);
  193223. png_warning(png_ptr, umsg);
  193224. #else
  193225. png_warning(png_ptr, "Unknown zTXt compression type");
  193226. #endif
  193227. *(chunkdata + prefix_size) = 0x00;
  193228. *newlength=prefix_size;
  193229. }
  193230. return chunkdata;
  193231. }
  193232. #endif
  193233. /* read and check the IDHR chunk */
  193234. void /* PRIVATE */
  193235. png_handle_IHDR(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  193236. {
  193237. png_byte buf[13];
  193238. png_uint_32 width, height;
  193239. int bit_depth, color_type, compression_type, filter_type;
  193240. int interlace_type;
  193241. png_debug(1, "in png_handle_IHDR\n");
  193242. if (png_ptr->mode & PNG_HAVE_IHDR)
  193243. png_error(png_ptr, "Out of place IHDR");
  193244. /* check the length */
  193245. if (length != 13)
  193246. png_error(png_ptr, "Invalid IHDR chunk");
  193247. png_ptr->mode |= PNG_HAVE_IHDR;
  193248. png_crc_read(png_ptr, buf, 13);
  193249. png_crc_finish(png_ptr, 0);
  193250. width = png_get_uint_31(png_ptr, buf);
  193251. height = png_get_uint_31(png_ptr, buf + 4);
  193252. bit_depth = buf[8];
  193253. color_type = buf[9];
  193254. compression_type = buf[10];
  193255. filter_type = buf[11];
  193256. interlace_type = buf[12];
  193257. /* set internal variables */
  193258. png_ptr->width = width;
  193259. png_ptr->height = height;
  193260. png_ptr->bit_depth = (png_byte)bit_depth;
  193261. png_ptr->interlaced = (png_byte)interlace_type;
  193262. png_ptr->color_type = (png_byte)color_type;
  193263. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  193264. png_ptr->filter_type = (png_byte)filter_type;
  193265. #endif
  193266. png_ptr->compression_type = (png_byte)compression_type;
  193267. /* find number of channels */
  193268. switch (png_ptr->color_type)
  193269. {
  193270. case PNG_COLOR_TYPE_GRAY:
  193271. case PNG_COLOR_TYPE_PALETTE:
  193272. png_ptr->channels = 1;
  193273. break;
  193274. case PNG_COLOR_TYPE_RGB:
  193275. png_ptr->channels = 3;
  193276. break;
  193277. case PNG_COLOR_TYPE_GRAY_ALPHA:
  193278. png_ptr->channels = 2;
  193279. break;
  193280. case PNG_COLOR_TYPE_RGB_ALPHA:
  193281. png_ptr->channels = 4;
  193282. break;
  193283. }
  193284. /* set up other useful info */
  193285. png_ptr->pixel_depth = (png_byte)(png_ptr->bit_depth *
  193286. png_ptr->channels);
  193287. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->width);
  193288. png_debug1(3,"bit_depth = %d\n", png_ptr->bit_depth);
  193289. png_debug1(3,"channels = %d\n", png_ptr->channels);
  193290. png_debug1(3,"rowbytes = %lu\n", png_ptr->rowbytes);
  193291. png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth,
  193292. color_type, interlace_type, compression_type, filter_type);
  193293. }
  193294. /* read and check the palette */
  193295. void /* PRIVATE */
  193296. png_handle_PLTE(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  193297. {
  193298. png_color palette[PNG_MAX_PALETTE_LENGTH];
  193299. int num, i;
  193300. #ifndef PNG_NO_POINTER_INDEXING
  193301. png_colorp pal_ptr;
  193302. #endif
  193303. png_debug(1, "in png_handle_PLTE\n");
  193304. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  193305. png_error(png_ptr, "Missing IHDR before PLTE");
  193306. else if (png_ptr->mode & PNG_HAVE_IDAT)
  193307. {
  193308. png_warning(png_ptr, "Invalid PLTE after IDAT");
  193309. png_crc_finish(png_ptr, length);
  193310. return;
  193311. }
  193312. else if (png_ptr->mode & PNG_HAVE_PLTE)
  193313. png_error(png_ptr, "Duplicate PLTE chunk");
  193314. png_ptr->mode |= PNG_HAVE_PLTE;
  193315. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  193316. {
  193317. png_warning(png_ptr,
  193318. "Ignoring PLTE chunk in grayscale PNG");
  193319. png_crc_finish(png_ptr, length);
  193320. return;
  193321. }
  193322. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  193323. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  193324. {
  193325. png_crc_finish(png_ptr, length);
  193326. return;
  193327. }
  193328. #endif
  193329. if (length > 3*PNG_MAX_PALETTE_LENGTH || length % 3)
  193330. {
  193331. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  193332. {
  193333. png_warning(png_ptr, "Invalid palette chunk");
  193334. png_crc_finish(png_ptr, length);
  193335. return;
  193336. }
  193337. else
  193338. {
  193339. png_error(png_ptr, "Invalid palette chunk");
  193340. }
  193341. }
  193342. num = (int)length / 3;
  193343. #ifndef PNG_NO_POINTER_INDEXING
  193344. for (i = 0, pal_ptr = palette; i < num; i++, pal_ptr++)
  193345. {
  193346. png_byte buf[3];
  193347. png_crc_read(png_ptr, buf, 3);
  193348. pal_ptr->red = buf[0];
  193349. pal_ptr->green = buf[1];
  193350. pal_ptr->blue = buf[2];
  193351. }
  193352. #else
  193353. for (i = 0; i < num; i++)
  193354. {
  193355. png_byte buf[3];
  193356. png_crc_read(png_ptr, buf, 3);
  193357. /* don't depend upon png_color being any order */
  193358. palette[i].red = buf[0];
  193359. palette[i].green = buf[1];
  193360. palette[i].blue = buf[2];
  193361. }
  193362. #endif
  193363. /* If we actually NEED the PLTE chunk (ie for a paletted image), we do
  193364. whatever the normal CRC configuration tells us. However, if we
  193365. have an RGB image, the PLTE can be considered ancillary, so
  193366. we will act as though it is. */
  193367. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  193368. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  193369. #endif
  193370. {
  193371. png_crc_finish(png_ptr, 0);
  193372. }
  193373. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  193374. else if (png_crc_error(png_ptr)) /* Only if we have a CRC error */
  193375. {
  193376. /* If we don't want to use the data from an ancillary chunk,
  193377. we have two options: an error abort, or a warning and we
  193378. ignore the data in this chunk (which should be OK, since
  193379. it's considered ancillary for a RGB or RGBA image). */
  193380. if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_USE))
  193381. {
  193382. if (png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)
  193383. {
  193384. png_chunk_error(png_ptr, "CRC error");
  193385. }
  193386. else
  193387. {
  193388. png_chunk_warning(png_ptr, "CRC error");
  193389. return;
  193390. }
  193391. }
  193392. /* Otherwise, we (optionally) emit a warning and use the chunk. */
  193393. else if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN))
  193394. {
  193395. png_chunk_warning(png_ptr, "CRC error");
  193396. }
  193397. }
  193398. #endif
  193399. png_set_PLTE(png_ptr, info_ptr, palette, num);
  193400. #if defined(PNG_READ_tRNS_SUPPORTED)
  193401. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  193402. {
  193403. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  193404. {
  193405. if (png_ptr->num_trans > (png_uint_16)num)
  193406. {
  193407. png_warning(png_ptr, "Truncating incorrect tRNS chunk length");
  193408. png_ptr->num_trans = (png_uint_16)num;
  193409. }
  193410. if (info_ptr->num_trans > (png_uint_16)num)
  193411. {
  193412. png_warning(png_ptr, "Truncating incorrect info tRNS chunk length");
  193413. info_ptr->num_trans = (png_uint_16)num;
  193414. }
  193415. }
  193416. }
  193417. #endif
  193418. }
  193419. void /* PRIVATE */
  193420. png_handle_IEND(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  193421. {
  193422. png_debug(1, "in png_handle_IEND\n");
  193423. if (!(png_ptr->mode & PNG_HAVE_IHDR) || !(png_ptr->mode & PNG_HAVE_IDAT))
  193424. {
  193425. png_error(png_ptr, "No image in file");
  193426. }
  193427. png_ptr->mode |= (PNG_AFTER_IDAT | PNG_HAVE_IEND);
  193428. if (length != 0)
  193429. {
  193430. png_warning(png_ptr, "Incorrect IEND chunk length");
  193431. }
  193432. png_crc_finish(png_ptr, length);
  193433. info_ptr =info_ptr; /* quiet compiler warnings about unused info_ptr */
  193434. }
  193435. #if defined(PNG_READ_gAMA_SUPPORTED)
  193436. void /* PRIVATE */
  193437. png_handle_gAMA(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  193438. {
  193439. png_fixed_point igamma;
  193440. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193441. float file_gamma;
  193442. #endif
  193443. png_byte buf[4];
  193444. png_debug(1, "in png_handle_gAMA\n");
  193445. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  193446. png_error(png_ptr, "Missing IHDR before gAMA");
  193447. else if (png_ptr->mode & PNG_HAVE_IDAT)
  193448. {
  193449. png_warning(png_ptr, "Invalid gAMA after IDAT");
  193450. png_crc_finish(png_ptr, length);
  193451. return;
  193452. }
  193453. else if (png_ptr->mode & PNG_HAVE_PLTE)
  193454. /* Should be an error, but we can cope with it */
  193455. png_warning(png_ptr, "Out of place gAMA chunk");
  193456. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  193457. #if defined(PNG_READ_sRGB_SUPPORTED)
  193458. && !(info_ptr->valid & PNG_INFO_sRGB)
  193459. #endif
  193460. )
  193461. {
  193462. png_warning(png_ptr, "Duplicate gAMA chunk");
  193463. png_crc_finish(png_ptr, length);
  193464. return;
  193465. }
  193466. if (length != 4)
  193467. {
  193468. png_warning(png_ptr, "Incorrect gAMA chunk length");
  193469. png_crc_finish(png_ptr, length);
  193470. return;
  193471. }
  193472. png_crc_read(png_ptr, buf, 4);
  193473. if (png_crc_finish(png_ptr, 0))
  193474. return;
  193475. igamma = (png_fixed_point)png_get_uint_32(buf);
  193476. /* check for zero gamma */
  193477. if (igamma == 0)
  193478. {
  193479. png_warning(png_ptr,
  193480. "Ignoring gAMA chunk with gamma=0");
  193481. return;
  193482. }
  193483. #if defined(PNG_READ_sRGB_SUPPORTED)
  193484. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  193485. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  193486. {
  193487. png_warning(png_ptr,
  193488. "Ignoring incorrect gAMA value when sRGB is also present");
  193489. #ifndef PNG_NO_CONSOLE_IO
  193490. fprintf(stderr, "gamma = (%d/100000)\n", (int)igamma);
  193491. #endif
  193492. return;
  193493. }
  193494. #endif /* PNG_READ_sRGB_SUPPORTED */
  193495. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193496. file_gamma = (float)igamma / (float)100000.0;
  193497. # ifdef PNG_READ_GAMMA_SUPPORTED
  193498. png_ptr->gamma = file_gamma;
  193499. # endif
  193500. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  193501. #endif
  193502. #ifdef PNG_FIXED_POINT_SUPPORTED
  193503. png_set_gAMA_fixed(png_ptr, info_ptr, igamma);
  193504. #endif
  193505. }
  193506. #endif
  193507. #if defined(PNG_READ_sBIT_SUPPORTED)
  193508. void /* PRIVATE */
  193509. png_handle_sBIT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  193510. {
  193511. png_size_t truelen;
  193512. png_byte buf[4];
  193513. png_debug(1, "in png_handle_sBIT\n");
  193514. buf[0] = buf[1] = buf[2] = buf[3] = 0;
  193515. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  193516. png_error(png_ptr, "Missing IHDR before sBIT");
  193517. else if (png_ptr->mode & PNG_HAVE_IDAT)
  193518. {
  193519. png_warning(png_ptr, "Invalid sBIT after IDAT");
  193520. png_crc_finish(png_ptr, length);
  193521. return;
  193522. }
  193523. else if (png_ptr->mode & PNG_HAVE_PLTE)
  193524. {
  193525. /* Should be an error, but we can cope with it */
  193526. png_warning(png_ptr, "Out of place sBIT chunk");
  193527. }
  193528. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT))
  193529. {
  193530. png_warning(png_ptr, "Duplicate sBIT chunk");
  193531. png_crc_finish(png_ptr, length);
  193532. return;
  193533. }
  193534. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  193535. truelen = 3;
  193536. else
  193537. truelen = (png_size_t)png_ptr->channels;
  193538. if (length != truelen || length > 4)
  193539. {
  193540. png_warning(png_ptr, "Incorrect sBIT chunk length");
  193541. png_crc_finish(png_ptr, length);
  193542. return;
  193543. }
  193544. png_crc_read(png_ptr, buf, truelen);
  193545. if (png_crc_finish(png_ptr, 0))
  193546. return;
  193547. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  193548. {
  193549. png_ptr->sig_bit.red = buf[0];
  193550. png_ptr->sig_bit.green = buf[1];
  193551. png_ptr->sig_bit.blue = buf[2];
  193552. png_ptr->sig_bit.alpha = buf[3];
  193553. }
  193554. else
  193555. {
  193556. png_ptr->sig_bit.gray = buf[0];
  193557. png_ptr->sig_bit.red = buf[0];
  193558. png_ptr->sig_bit.green = buf[0];
  193559. png_ptr->sig_bit.blue = buf[0];
  193560. png_ptr->sig_bit.alpha = buf[1];
  193561. }
  193562. png_set_sBIT(png_ptr, info_ptr, &(png_ptr->sig_bit));
  193563. }
  193564. #endif
  193565. #if defined(PNG_READ_cHRM_SUPPORTED)
  193566. void /* PRIVATE */
  193567. png_handle_cHRM(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  193568. {
  193569. png_byte buf[4];
  193570. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193571. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  193572. #endif
  193573. png_fixed_point int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  193574. int_y_green, int_x_blue, int_y_blue;
  193575. png_uint_32 uint_x, uint_y;
  193576. png_debug(1, "in png_handle_cHRM\n");
  193577. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  193578. png_error(png_ptr, "Missing IHDR before cHRM");
  193579. else if (png_ptr->mode & PNG_HAVE_IDAT)
  193580. {
  193581. png_warning(png_ptr, "Invalid cHRM after IDAT");
  193582. png_crc_finish(png_ptr, length);
  193583. return;
  193584. }
  193585. else if (png_ptr->mode & PNG_HAVE_PLTE)
  193586. /* Should be an error, but we can cope with it */
  193587. png_warning(png_ptr, "Missing PLTE before cHRM");
  193588. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM)
  193589. #if defined(PNG_READ_sRGB_SUPPORTED)
  193590. && !(info_ptr->valid & PNG_INFO_sRGB)
  193591. #endif
  193592. )
  193593. {
  193594. png_warning(png_ptr, "Duplicate cHRM chunk");
  193595. png_crc_finish(png_ptr, length);
  193596. return;
  193597. }
  193598. if (length != 32)
  193599. {
  193600. png_warning(png_ptr, "Incorrect cHRM chunk length");
  193601. png_crc_finish(png_ptr, length);
  193602. return;
  193603. }
  193604. png_crc_read(png_ptr, buf, 4);
  193605. uint_x = png_get_uint_32(buf);
  193606. png_crc_read(png_ptr, buf, 4);
  193607. uint_y = png_get_uint_32(buf);
  193608. if (uint_x > 80000L || uint_y > 80000L ||
  193609. uint_x + uint_y > 100000L)
  193610. {
  193611. png_warning(png_ptr, "Invalid cHRM white point");
  193612. png_crc_finish(png_ptr, 24);
  193613. return;
  193614. }
  193615. int_x_white = (png_fixed_point)uint_x;
  193616. int_y_white = (png_fixed_point)uint_y;
  193617. png_crc_read(png_ptr, buf, 4);
  193618. uint_x = png_get_uint_32(buf);
  193619. png_crc_read(png_ptr, buf, 4);
  193620. uint_y = png_get_uint_32(buf);
  193621. if (uint_x + uint_y > 100000L)
  193622. {
  193623. png_warning(png_ptr, "Invalid cHRM red point");
  193624. png_crc_finish(png_ptr, 16);
  193625. return;
  193626. }
  193627. int_x_red = (png_fixed_point)uint_x;
  193628. int_y_red = (png_fixed_point)uint_y;
  193629. png_crc_read(png_ptr, buf, 4);
  193630. uint_x = png_get_uint_32(buf);
  193631. png_crc_read(png_ptr, buf, 4);
  193632. uint_y = png_get_uint_32(buf);
  193633. if (uint_x + uint_y > 100000L)
  193634. {
  193635. png_warning(png_ptr, "Invalid cHRM green point");
  193636. png_crc_finish(png_ptr, 8);
  193637. return;
  193638. }
  193639. int_x_green = (png_fixed_point)uint_x;
  193640. int_y_green = (png_fixed_point)uint_y;
  193641. png_crc_read(png_ptr, buf, 4);
  193642. uint_x = png_get_uint_32(buf);
  193643. png_crc_read(png_ptr, buf, 4);
  193644. uint_y = png_get_uint_32(buf);
  193645. if (uint_x + uint_y > 100000L)
  193646. {
  193647. png_warning(png_ptr, "Invalid cHRM blue point");
  193648. png_crc_finish(png_ptr, 0);
  193649. return;
  193650. }
  193651. int_x_blue = (png_fixed_point)uint_x;
  193652. int_y_blue = (png_fixed_point)uint_y;
  193653. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193654. white_x = (float)int_x_white / (float)100000.0;
  193655. white_y = (float)int_y_white / (float)100000.0;
  193656. red_x = (float)int_x_red / (float)100000.0;
  193657. red_y = (float)int_y_red / (float)100000.0;
  193658. green_x = (float)int_x_green / (float)100000.0;
  193659. green_y = (float)int_y_green / (float)100000.0;
  193660. blue_x = (float)int_x_blue / (float)100000.0;
  193661. blue_y = (float)int_y_blue / (float)100000.0;
  193662. #endif
  193663. #if defined(PNG_READ_sRGB_SUPPORTED)
  193664. if ((info_ptr != NULL) && (info_ptr->valid & PNG_INFO_sRGB))
  193665. {
  193666. if (PNG_OUT_OF_RANGE(int_x_white, 31270, 1000) ||
  193667. PNG_OUT_OF_RANGE(int_y_white, 32900, 1000) ||
  193668. PNG_OUT_OF_RANGE(int_x_red, 64000L, 1000) ||
  193669. PNG_OUT_OF_RANGE(int_y_red, 33000, 1000) ||
  193670. PNG_OUT_OF_RANGE(int_x_green, 30000, 1000) ||
  193671. PNG_OUT_OF_RANGE(int_y_green, 60000L, 1000) ||
  193672. PNG_OUT_OF_RANGE(int_x_blue, 15000, 1000) ||
  193673. PNG_OUT_OF_RANGE(int_y_blue, 6000, 1000))
  193674. {
  193675. png_warning(png_ptr,
  193676. "Ignoring incorrect cHRM value when sRGB is also present");
  193677. #ifndef PNG_NO_CONSOLE_IO
  193678. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193679. fprintf(stderr,"wx=%f, wy=%f, rx=%f, ry=%f\n",
  193680. white_x, white_y, red_x, red_y);
  193681. fprintf(stderr,"gx=%f, gy=%f, bx=%f, by=%f\n",
  193682. green_x, green_y, blue_x, blue_y);
  193683. #else
  193684. fprintf(stderr,"wx=%ld, wy=%ld, rx=%ld, ry=%ld\n",
  193685. int_x_white, int_y_white, int_x_red, int_y_red);
  193686. fprintf(stderr,"gx=%ld, gy=%ld, bx=%ld, by=%ld\n",
  193687. int_x_green, int_y_green, int_x_blue, int_y_blue);
  193688. #endif
  193689. #endif /* PNG_NO_CONSOLE_IO */
  193690. }
  193691. png_crc_finish(png_ptr, 0);
  193692. return;
  193693. }
  193694. #endif /* PNG_READ_sRGB_SUPPORTED */
  193695. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193696. png_set_cHRM(png_ptr, info_ptr,
  193697. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  193698. #endif
  193699. #ifdef PNG_FIXED_POINT_SUPPORTED
  193700. png_set_cHRM_fixed(png_ptr, info_ptr,
  193701. int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  193702. int_y_green, int_x_blue, int_y_blue);
  193703. #endif
  193704. if (png_crc_finish(png_ptr, 0))
  193705. return;
  193706. }
  193707. #endif
  193708. #if defined(PNG_READ_sRGB_SUPPORTED)
  193709. void /* PRIVATE */
  193710. png_handle_sRGB(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  193711. {
  193712. int intent;
  193713. png_byte buf[1];
  193714. png_debug(1, "in png_handle_sRGB\n");
  193715. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  193716. png_error(png_ptr, "Missing IHDR before sRGB");
  193717. else if (png_ptr->mode & PNG_HAVE_IDAT)
  193718. {
  193719. png_warning(png_ptr, "Invalid sRGB after IDAT");
  193720. png_crc_finish(png_ptr, length);
  193721. return;
  193722. }
  193723. else if (png_ptr->mode & PNG_HAVE_PLTE)
  193724. /* Should be an error, but we can cope with it */
  193725. png_warning(png_ptr, "Out of place sRGB chunk");
  193726. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  193727. {
  193728. png_warning(png_ptr, "Duplicate sRGB chunk");
  193729. png_crc_finish(png_ptr, length);
  193730. return;
  193731. }
  193732. if (length != 1)
  193733. {
  193734. png_warning(png_ptr, "Incorrect sRGB chunk length");
  193735. png_crc_finish(png_ptr, length);
  193736. return;
  193737. }
  193738. png_crc_read(png_ptr, buf, 1);
  193739. if (png_crc_finish(png_ptr, 0))
  193740. return;
  193741. intent = buf[0];
  193742. /* check for bad intent */
  193743. if (intent >= PNG_sRGB_INTENT_LAST)
  193744. {
  193745. png_warning(png_ptr, "Unknown sRGB intent");
  193746. return;
  193747. }
  193748. #if defined(PNG_READ_gAMA_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  193749. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA))
  193750. {
  193751. png_fixed_point igamma;
  193752. #ifdef PNG_FIXED_POINT_SUPPORTED
  193753. igamma=info_ptr->int_gamma;
  193754. #else
  193755. # ifdef PNG_FLOATING_POINT_SUPPORTED
  193756. igamma=(png_fixed_point)(info_ptr->gamma * 100000.);
  193757. # endif
  193758. #endif
  193759. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  193760. {
  193761. png_warning(png_ptr,
  193762. "Ignoring incorrect gAMA value when sRGB is also present");
  193763. #ifndef PNG_NO_CONSOLE_IO
  193764. # ifdef PNG_FIXED_POINT_SUPPORTED
  193765. fprintf(stderr,"incorrect gamma=(%d/100000)\n",(int)png_ptr->int_gamma);
  193766. # else
  193767. # ifdef PNG_FLOATING_POINT_SUPPORTED
  193768. fprintf(stderr,"incorrect gamma=%f\n",png_ptr->gamma);
  193769. # endif
  193770. # endif
  193771. #endif
  193772. }
  193773. }
  193774. #endif /* PNG_READ_gAMA_SUPPORTED */
  193775. #ifdef PNG_READ_cHRM_SUPPORTED
  193776. #ifdef PNG_FIXED_POINT_SUPPORTED
  193777. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  193778. if (PNG_OUT_OF_RANGE(info_ptr->int_x_white, 31270, 1000) ||
  193779. PNG_OUT_OF_RANGE(info_ptr->int_y_white, 32900, 1000) ||
  193780. PNG_OUT_OF_RANGE(info_ptr->int_x_red, 64000L, 1000) ||
  193781. PNG_OUT_OF_RANGE(info_ptr->int_y_red, 33000, 1000) ||
  193782. PNG_OUT_OF_RANGE(info_ptr->int_x_green, 30000, 1000) ||
  193783. PNG_OUT_OF_RANGE(info_ptr->int_y_green, 60000L, 1000) ||
  193784. PNG_OUT_OF_RANGE(info_ptr->int_x_blue, 15000, 1000) ||
  193785. PNG_OUT_OF_RANGE(info_ptr->int_y_blue, 6000, 1000))
  193786. {
  193787. png_warning(png_ptr,
  193788. "Ignoring incorrect cHRM value when sRGB is also present");
  193789. }
  193790. #endif /* PNG_FIXED_POINT_SUPPORTED */
  193791. #endif /* PNG_READ_cHRM_SUPPORTED */
  193792. png_set_sRGB_gAMA_and_cHRM(png_ptr, info_ptr, intent);
  193793. }
  193794. #endif /* PNG_READ_sRGB_SUPPORTED */
  193795. #if defined(PNG_READ_iCCP_SUPPORTED)
  193796. void /* PRIVATE */
  193797. png_handle_iCCP(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  193798. /* Note: this does not properly handle chunks that are > 64K under DOS */
  193799. {
  193800. png_charp chunkdata;
  193801. png_byte compression_type;
  193802. png_bytep pC;
  193803. png_charp profile;
  193804. png_uint_32 skip = 0;
  193805. png_uint_32 profile_size, profile_length;
  193806. png_size_t slength, prefix_length, data_length;
  193807. png_debug(1, "in png_handle_iCCP\n");
  193808. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  193809. png_error(png_ptr, "Missing IHDR before iCCP");
  193810. else if (png_ptr->mode & PNG_HAVE_IDAT)
  193811. {
  193812. png_warning(png_ptr, "Invalid iCCP after IDAT");
  193813. png_crc_finish(png_ptr, length);
  193814. return;
  193815. }
  193816. else if (png_ptr->mode & PNG_HAVE_PLTE)
  193817. /* Should be an error, but we can cope with it */
  193818. png_warning(png_ptr, "Out of place iCCP chunk");
  193819. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP))
  193820. {
  193821. png_warning(png_ptr, "Duplicate iCCP chunk");
  193822. png_crc_finish(png_ptr, length);
  193823. return;
  193824. }
  193825. #ifdef PNG_MAX_MALLOC_64K
  193826. if (length > (png_uint_32)65535L)
  193827. {
  193828. png_warning(png_ptr, "iCCP chunk too large to fit in memory");
  193829. skip = length - (png_uint_32)65535L;
  193830. length = (png_uint_32)65535L;
  193831. }
  193832. #endif
  193833. chunkdata = (png_charp)png_malloc(png_ptr, length + 1);
  193834. slength = (png_size_t)length;
  193835. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  193836. if (png_crc_finish(png_ptr, skip))
  193837. {
  193838. png_free(png_ptr, chunkdata);
  193839. return;
  193840. }
  193841. chunkdata[slength] = 0x00;
  193842. for (profile = chunkdata; *profile; profile++)
  193843. /* empty loop to find end of name */ ;
  193844. ++profile;
  193845. /* there should be at least one zero (the compression type byte)
  193846. following the separator, and we should be on it */
  193847. if ( profile >= chunkdata + slength - 1)
  193848. {
  193849. png_free(png_ptr, chunkdata);
  193850. png_warning(png_ptr, "Malformed iCCP chunk");
  193851. return;
  193852. }
  193853. /* compression_type should always be zero */
  193854. compression_type = *profile++;
  193855. if (compression_type)
  193856. {
  193857. png_warning(png_ptr, "Ignoring nonzero compression type in iCCP chunk");
  193858. compression_type=0x00; /* Reset it to zero (libpng-1.0.6 through 1.0.8
  193859. wrote nonzero) */
  193860. }
  193861. prefix_length = profile - chunkdata;
  193862. chunkdata = png_decompress_chunk(png_ptr, compression_type, chunkdata,
  193863. slength, prefix_length, &data_length);
  193864. profile_length = data_length - prefix_length;
  193865. if ( prefix_length > data_length || profile_length < 4)
  193866. {
  193867. png_free(png_ptr, chunkdata);
  193868. png_warning(png_ptr, "Profile size field missing from iCCP chunk");
  193869. return;
  193870. }
  193871. /* Check the profile_size recorded in the first 32 bits of the ICC profile */
  193872. pC = (png_bytep)(chunkdata+prefix_length);
  193873. profile_size = ((*(pC ))<<24) |
  193874. ((*(pC+1))<<16) |
  193875. ((*(pC+2))<< 8) |
  193876. ((*(pC+3)) );
  193877. if(profile_size < profile_length)
  193878. profile_length = profile_size;
  193879. if(profile_size > profile_length)
  193880. {
  193881. png_free(png_ptr, chunkdata);
  193882. png_warning(png_ptr, "Ignoring truncated iCCP profile.");
  193883. return;
  193884. }
  193885. png_set_iCCP(png_ptr, info_ptr, chunkdata, compression_type,
  193886. chunkdata + prefix_length, profile_length);
  193887. png_free(png_ptr, chunkdata);
  193888. }
  193889. #endif /* PNG_READ_iCCP_SUPPORTED */
  193890. #if defined(PNG_READ_sPLT_SUPPORTED)
  193891. void /* PRIVATE */
  193892. png_handle_sPLT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  193893. /* Note: this does not properly handle chunks that are > 64K under DOS */
  193894. {
  193895. png_bytep chunkdata;
  193896. png_bytep entry_start;
  193897. png_sPLT_t new_palette;
  193898. #ifdef PNG_NO_POINTER_INDEXING
  193899. png_sPLT_entryp pp;
  193900. #endif
  193901. int data_length, entry_size, i;
  193902. png_uint_32 skip = 0;
  193903. png_size_t slength;
  193904. png_debug(1, "in png_handle_sPLT\n");
  193905. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  193906. png_error(png_ptr, "Missing IHDR before sPLT");
  193907. else if (png_ptr->mode & PNG_HAVE_IDAT)
  193908. {
  193909. png_warning(png_ptr, "Invalid sPLT after IDAT");
  193910. png_crc_finish(png_ptr, length);
  193911. return;
  193912. }
  193913. #ifdef PNG_MAX_MALLOC_64K
  193914. if (length > (png_uint_32)65535L)
  193915. {
  193916. png_warning(png_ptr, "sPLT chunk too large to fit in memory");
  193917. skip = length - (png_uint_32)65535L;
  193918. length = (png_uint_32)65535L;
  193919. }
  193920. #endif
  193921. chunkdata = (png_bytep)png_malloc(png_ptr, length + 1);
  193922. slength = (png_size_t)length;
  193923. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  193924. if (png_crc_finish(png_ptr, skip))
  193925. {
  193926. png_free(png_ptr, chunkdata);
  193927. return;
  193928. }
  193929. chunkdata[slength] = 0x00;
  193930. for (entry_start = chunkdata; *entry_start; entry_start++)
  193931. /* empty loop to find end of name */ ;
  193932. ++entry_start;
  193933. /* a sample depth should follow the separator, and we should be on it */
  193934. if (entry_start > chunkdata + slength - 2)
  193935. {
  193936. png_free(png_ptr, chunkdata);
  193937. png_warning(png_ptr, "malformed sPLT chunk");
  193938. return;
  193939. }
  193940. new_palette.depth = *entry_start++;
  193941. entry_size = (new_palette.depth == 8 ? 6 : 10);
  193942. data_length = (slength - (entry_start - chunkdata));
  193943. /* integrity-check the data length */
  193944. if (data_length % entry_size)
  193945. {
  193946. png_free(png_ptr, chunkdata);
  193947. png_warning(png_ptr, "sPLT chunk has bad length");
  193948. return;
  193949. }
  193950. new_palette.nentries = (png_int_32) ( data_length / entry_size);
  193951. if ((png_uint_32) new_palette.nentries > (png_uint_32) (PNG_SIZE_MAX /
  193952. png_sizeof(png_sPLT_entry)))
  193953. {
  193954. png_warning(png_ptr, "sPLT chunk too long");
  193955. return;
  193956. }
  193957. new_palette.entries = (png_sPLT_entryp)png_malloc_warn(
  193958. png_ptr, new_palette.nentries * png_sizeof(png_sPLT_entry));
  193959. if (new_palette.entries == NULL)
  193960. {
  193961. png_warning(png_ptr, "sPLT chunk requires too much memory");
  193962. return;
  193963. }
  193964. #ifndef PNG_NO_POINTER_INDEXING
  193965. for (i = 0; i < new_palette.nentries; i++)
  193966. {
  193967. png_sPLT_entryp pp = new_palette.entries + i;
  193968. if (new_palette.depth == 8)
  193969. {
  193970. pp->red = *entry_start++;
  193971. pp->green = *entry_start++;
  193972. pp->blue = *entry_start++;
  193973. pp->alpha = *entry_start++;
  193974. }
  193975. else
  193976. {
  193977. pp->red = png_get_uint_16(entry_start); entry_start += 2;
  193978. pp->green = png_get_uint_16(entry_start); entry_start += 2;
  193979. pp->blue = png_get_uint_16(entry_start); entry_start += 2;
  193980. pp->alpha = png_get_uint_16(entry_start); entry_start += 2;
  193981. }
  193982. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  193983. }
  193984. #else
  193985. pp = new_palette.entries;
  193986. for (i = 0; i < new_palette.nentries; i++)
  193987. {
  193988. if (new_palette.depth == 8)
  193989. {
  193990. pp[i].red = *entry_start++;
  193991. pp[i].green = *entry_start++;
  193992. pp[i].blue = *entry_start++;
  193993. pp[i].alpha = *entry_start++;
  193994. }
  193995. else
  193996. {
  193997. pp[i].red = png_get_uint_16(entry_start); entry_start += 2;
  193998. pp[i].green = png_get_uint_16(entry_start); entry_start += 2;
  193999. pp[i].blue = png_get_uint_16(entry_start); entry_start += 2;
  194000. pp[i].alpha = png_get_uint_16(entry_start); entry_start += 2;
  194001. }
  194002. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  194003. }
  194004. #endif
  194005. /* discard all chunk data except the name and stash that */
  194006. new_palette.name = (png_charp)chunkdata;
  194007. png_set_sPLT(png_ptr, info_ptr, &new_palette, 1);
  194008. png_free(png_ptr, chunkdata);
  194009. png_free(png_ptr, new_palette.entries);
  194010. }
  194011. #endif /* PNG_READ_sPLT_SUPPORTED */
  194012. #if defined(PNG_READ_tRNS_SUPPORTED)
  194013. void /* PRIVATE */
  194014. png_handle_tRNS(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194015. {
  194016. png_byte readbuf[PNG_MAX_PALETTE_LENGTH];
  194017. int bit_mask;
  194018. png_debug(1, "in png_handle_tRNS\n");
  194019. /* For non-indexed color, mask off any bits in the tRNS value that
  194020. * exceed the bit depth. Some creators were writing extra bits there.
  194021. * This is not needed for indexed color. */
  194022. bit_mask = (1 << png_ptr->bit_depth) - 1;
  194023. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194024. png_error(png_ptr, "Missing IHDR before tRNS");
  194025. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194026. {
  194027. png_warning(png_ptr, "Invalid tRNS after IDAT");
  194028. png_crc_finish(png_ptr, length);
  194029. return;
  194030. }
  194031. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  194032. {
  194033. png_warning(png_ptr, "Duplicate tRNS chunk");
  194034. png_crc_finish(png_ptr, length);
  194035. return;
  194036. }
  194037. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  194038. {
  194039. png_byte buf[2];
  194040. if (length != 2)
  194041. {
  194042. png_warning(png_ptr, "Incorrect tRNS chunk length");
  194043. png_crc_finish(png_ptr, length);
  194044. return;
  194045. }
  194046. png_crc_read(png_ptr, buf, 2);
  194047. png_ptr->num_trans = 1;
  194048. png_ptr->trans_values.gray = png_get_uint_16(buf) & bit_mask;
  194049. }
  194050. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  194051. {
  194052. png_byte buf[6];
  194053. if (length != 6)
  194054. {
  194055. png_warning(png_ptr, "Incorrect tRNS chunk length");
  194056. png_crc_finish(png_ptr, length);
  194057. return;
  194058. }
  194059. png_crc_read(png_ptr, buf, (png_size_t)length);
  194060. png_ptr->num_trans = 1;
  194061. png_ptr->trans_values.red = png_get_uint_16(buf) & bit_mask;
  194062. png_ptr->trans_values.green = png_get_uint_16(buf + 2) & bit_mask;
  194063. png_ptr->trans_values.blue = png_get_uint_16(buf + 4) & bit_mask;
  194064. }
  194065. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194066. {
  194067. if (!(png_ptr->mode & PNG_HAVE_PLTE))
  194068. {
  194069. /* Should be an error, but we can cope with it. */
  194070. png_warning(png_ptr, "Missing PLTE before tRNS");
  194071. }
  194072. if (length > (png_uint_32)png_ptr->num_palette ||
  194073. length > PNG_MAX_PALETTE_LENGTH)
  194074. {
  194075. png_warning(png_ptr, "Incorrect tRNS chunk length");
  194076. png_crc_finish(png_ptr, length);
  194077. return;
  194078. }
  194079. if (length == 0)
  194080. {
  194081. png_warning(png_ptr, "Zero length tRNS chunk");
  194082. png_crc_finish(png_ptr, length);
  194083. return;
  194084. }
  194085. png_crc_read(png_ptr, readbuf, (png_size_t)length);
  194086. png_ptr->num_trans = (png_uint_16)length;
  194087. }
  194088. else
  194089. {
  194090. png_warning(png_ptr, "tRNS chunk not allowed with alpha channel");
  194091. png_crc_finish(png_ptr, length);
  194092. return;
  194093. }
  194094. if (png_crc_finish(png_ptr, 0))
  194095. {
  194096. png_ptr->num_trans = 0;
  194097. return;
  194098. }
  194099. png_set_tRNS(png_ptr, info_ptr, readbuf, png_ptr->num_trans,
  194100. &(png_ptr->trans_values));
  194101. }
  194102. #endif
  194103. #if defined(PNG_READ_bKGD_SUPPORTED)
  194104. void /* PRIVATE */
  194105. png_handle_bKGD(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194106. {
  194107. png_size_t truelen;
  194108. png_byte buf[6];
  194109. png_debug(1, "in png_handle_bKGD\n");
  194110. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194111. png_error(png_ptr, "Missing IHDR before bKGD");
  194112. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194113. {
  194114. png_warning(png_ptr, "Invalid bKGD after IDAT");
  194115. png_crc_finish(png_ptr, length);
  194116. return;
  194117. }
  194118. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  194119. !(png_ptr->mode & PNG_HAVE_PLTE))
  194120. {
  194121. png_warning(png_ptr, "Missing PLTE before bKGD");
  194122. png_crc_finish(png_ptr, length);
  194123. return;
  194124. }
  194125. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD))
  194126. {
  194127. png_warning(png_ptr, "Duplicate bKGD chunk");
  194128. png_crc_finish(png_ptr, length);
  194129. return;
  194130. }
  194131. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194132. truelen = 1;
  194133. else if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  194134. truelen = 6;
  194135. else
  194136. truelen = 2;
  194137. if (length != truelen)
  194138. {
  194139. png_warning(png_ptr, "Incorrect bKGD chunk length");
  194140. png_crc_finish(png_ptr, length);
  194141. return;
  194142. }
  194143. png_crc_read(png_ptr, buf, truelen);
  194144. if (png_crc_finish(png_ptr, 0))
  194145. return;
  194146. /* We convert the index value into RGB components so that we can allow
  194147. * arbitrary RGB values for background when we have transparency, and
  194148. * so it is easy to determine the RGB values of the background color
  194149. * from the info_ptr struct. */
  194150. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194151. {
  194152. png_ptr->background.index = buf[0];
  194153. if(info_ptr->num_palette)
  194154. {
  194155. if(buf[0] > info_ptr->num_palette)
  194156. {
  194157. png_warning(png_ptr, "Incorrect bKGD chunk index value");
  194158. return;
  194159. }
  194160. png_ptr->background.red =
  194161. (png_uint_16)png_ptr->palette[buf[0]].red;
  194162. png_ptr->background.green =
  194163. (png_uint_16)png_ptr->palette[buf[0]].green;
  194164. png_ptr->background.blue =
  194165. (png_uint_16)png_ptr->palette[buf[0]].blue;
  194166. }
  194167. }
  194168. else if (!(png_ptr->color_type & PNG_COLOR_MASK_COLOR)) /* GRAY */
  194169. {
  194170. png_ptr->background.red =
  194171. png_ptr->background.green =
  194172. png_ptr->background.blue =
  194173. png_ptr->background.gray = png_get_uint_16(buf);
  194174. }
  194175. else
  194176. {
  194177. png_ptr->background.red = png_get_uint_16(buf);
  194178. png_ptr->background.green = png_get_uint_16(buf + 2);
  194179. png_ptr->background.blue = png_get_uint_16(buf + 4);
  194180. }
  194181. png_set_bKGD(png_ptr, info_ptr, &(png_ptr->background));
  194182. }
  194183. #endif
  194184. #if defined(PNG_READ_hIST_SUPPORTED)
  194185. void /* PRIVATE */
  194186. png_handle_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194187. {
  194188. unsigned int num, i;
  194189. png_uint_16 readbuf[PNG_MAX_PALETTE_LENGTH];
  194190. png_debug(1, "in png_handle_hIST\n");
  194191. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194192. png_error(png_ptr, "Missing IHDR before hIST");
  194193. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194194. {
  194195. png_warning(png_ptr, "Invalid hIST after IDAT");
  194196. png_crc_finish(png_ptr, length);
  194197. return;
  194198. }
  194199. else if (!(png_ptr->mode & PNG_HAVE_PLTE))
  194200. {
  194201. png_warning(png_ptr, "Missing PLTE before hIST");
  194202. png_crc_finish(png_ptr, length);
  194203. return;
  194204. }
  194205. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST))
  194206. {
  194207. png_warning(png_ptr, "Duplicate hIST chunk");
  194208. png_crc_finish(png_ptr, length);
  194209. return;
  194210. }
  194211. num = length / 2 ;
  194212. if (num != (unsigned int) png_ptr->num_palette || num >
  194213. (unsigned int) PNG_MAX_PALETTE_LENGTH)
  194214. {
  194215. png_warning(png_ptr, "Incorrect hIST chunk length");
  194216. png_crc_finish(png_ptr, length);
  194217. return;
  194218. }
  194219. for (i = 0; i < num; i++)
  194220. {
  194221. png_byte buf[2];
  194222. png_crc_read(png_ptr, buf, 2);
  194223. readbuf[i] = png_get_uint_16(buf);
  194224. }
  194225. if (png_crc_finish(png_ptr, 0))
  194226. return;
  194227. png_set_hIST(png_ptr, info_ptr, readbuf);
  194228. }
  194229. #endif
  194230. #if defined(PNG_READ_pHYs_SUPPORTED)
  194231. void /* PRIVATE */
  194232. png_handle_pHYs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194233. {
  194234. png_byte buf[9];
  194235. png_uint_32 res_x, res_y;
  194236. int unit_type;
  194237. png_debug(1, "in png_handle_pHYs\n");
  194238. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194239. png_error(png_ptr, "Missing IHDR before pHYs");
  194240. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194241. {
  194242. png_warning(png_ptr, "Invalid pHYs after IDAT");
  194243. png_crc_finish(png_ptr, length);
  194244. return;
  194245. }
  194246. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  194247. {
  194248. png_warning(png_ptr, "Duplicate pHYs chunk");
  194249. png_crc_finish(png_ptr, length);
  194250. return;
  194251. }
  194252. if (length != 9)
  194253. {
  194254. png_warning(png_ptr, "Incorrect pHYs chunk length");
  194255. png_crc_finish(png_ptr, length);
  194256. return;
  194257. }
  194258. png_crc_read(png_ptr, buf, 9);
  194259. if (png_crc_finish(png_ptr, 0))
  194260. return;
  194261. res_x = png_get_uint_32(buf);
  194262. res_y = png_get_uint_32(buf + 4);
  194263. unit_type = buf[8];
  194264. png_set_pHYs(png_ptr, info_ptr, res_x, res_y, unit_type);
  194265. }
  194266. #endif
  194267. #if defined(PNG_READ_oFFs_SUPPORTED)
  194268. void /* PRIVATE */
  194269. png_handle_oFFs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194270. {
  194271. png_byte buf[9];
  194272. png_int_32 offset_x, offset_y;
  194273. int unit_type;
  194274. png_debug(1, "in png_handle_oFFs\n");
  194275. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194276. png_error(png_ptr, "Missing IHDR before oFFs");
  194277. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194278. {
  194279. png_warning(png_ptr, "Invalid oFFs after IDAT");
  194280. png_crc_finish(png_ptr, length);
  194281. return;
  194282. }
  194283. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs))
  194284. {
  194285. png_warning(png_ptr, "Duplicate oFFs chunk");
  194286. png_crc_finish(png_ptr, length);
  194287. return;
  194288. }
  194289. if (length != 9)
  194290. {
  194291. png_warning(png_ptr, "Incorrect oFFs chunk length");
  194292. png_crc_finish(png_ptr, length);
  194293. return;
  194294. }
  194295. png_crc_read(png_ptr, buf, 9);
  194296. if (png_crc_finish(png_ptr, 0))
  194297. return;
  194298. offset_x = png_get_int_32(buf);
  194299. offset_y = png_get_int_32(buf + 4);
  194300. unit_type = buf[8];
  194301. png_set_oFFs(png_ptr, info_ptr, offset_x, offset_y, unit_type);
  194302. }
  194303. #endif
  194304. #if defined(PNG_READ_pCAL_SUPPORTED)
  194305. /* read the pCAL chunk (described in the PNG Extensions document) */
  194306. void /* PRIVATE */
  194307. png_handle_pCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194308. {
  194309. png_charp purpose;
  194310. png_int_32 X0, X1;
  194311. png_byte type, nparams;
  194312. png_charp buf, units, endptr;
  194313. png_charpp params;
  194314. png_size_t slength;
  194315. int i;
  194316. png_debug(1, "in png_handle_pCAL\n");
  194317. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194318. png_error(png_ptr, "Missing IHDR before pCAL");
  194319. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194320. {
  194321. png_warning(png_ptr, "Invalid pCAL after IDAT");
  194322. png_crc_finish(png_ptr, length);
  194323. return;
  194324. }
  194325. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL))
  194326. {
  194327. png_warning(png_ptr, "Duplicate pCAL chunk");
  194328. png_crc_finish(png_ptr, length);
  194329. return;
  194330. }
  194331. png_debug1(2, "Allocating and reading pCAL chunk data (%lu bytes)\n",
  194332. length + 1);
  194333. purpose = (png_charp)png_malloc_warn(png_ptr, length + 1);
  194334. if (purpose == NULL)
  194335. {
  194336. png_warning(png_ptr, "No memory for pCAL purpose.");
  194337. return;
  194338. }
  194339. slength = (png_size_t)length;
  194340. png_crc_read(png_ptr, (png_bytep)purpose, slength);
  194341. if (png_crc_finish(png_ptr, 0))
  194342. {
  194343. png_free(png_ptr, purpose);
  194344. return;
  194345. }
  194346. purpose[slength] = 0x00; /* null terminate the last string */
  194347. png_debug(3, "Finding end of pCAL purpose string\n");
  194348. for (buf = purpose; *buf; buf++)
  194349. /* empty loop */ ;
  194350. endptr = purpose + slength;
  194351. /* We need to have at least 12 bytes after the purpose string
  194352. in order to get the parameter information. */
  194353. if (endptr <= buf + 12)
  194354. {
  194355. png_warning(png_ptr, "Invalid pCAL data");
  194356. png_free(png_ptr, purpose);
  194357. return;
  194358. }
  194359. png_debug(3, "Reading pCAL X0, X1, type, nparams, and units\n");
  194360. X0 = png_get_int_32((png_bytep)buf+1);
  194361. X1 = png_get_int_32((png_bytep)buf+5);
  194362. type = buf[9];
  194363. nparams = buf[10];
  194364. units = buf + 11;
  194365. png_debug(3, "Checking pCAL equation type and number of parameters\n");
  194366. /* Check that we have the right number of parameters for known
  194367. equation types. */
  194368. if ((type == PNG_EQUATION_LINEAR && nparams != 2) ||
  194369. (type == PNG_EQUATION_BASE_E && nparams != 3) ||
  194370. (type == PNG_EQUATION_ARBITRARY && nparams != 3) ||
  194371. (type == PNG_EQUATION_HYPERBOLIC && nparams != 4))
  194372. {
  194373. png_warning(png_ptr, "Invalid pCAL parameters for equation type");
  194374. png_free(png_ptr, purpose);
  194375. return;
  194376. }
  194377. else if (type >= PNG_EQUATION_LAST)
  194378. {
  194379. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  194380. }
  194381. for (buf = units; *buf; buf++)
  194382. /* Empty loop to move past the units string. */ ;
  194383. png_debug(3, "Allocating pCAL parameters array\n");
  194384. params = (png_charpp)png_malloc_warn(png_ptr, (png_uint_32)(nparams
  194385. *png_sizeof(png_charp))) ;
  194386. if (params == NULL)
  194387. {
  194388. png_free(png_ptr, purpose);
  194389. png_warning(png_ptr, "No memory for pCAL params.");
  194390. return;
  194391. }
  194392. /* Get pointers to the start of each parameter string. */
  194393. for (i = 0; i < (int)nparams; i++)
  194394. {
  194395. buf++; /* Skip the null string terminator from previous parameter. */
  194396. png_debug1(3, "Reading pCAL parameter %d\n", i);
  194397. for (params[i] = buf; buf <= endptr && *buf != 0x00; buf++)
  194398. /* Empty loop to move past each parameter string */ ;
  194399. /* Make sure we haven't run out of data yet */
  194400. if (buf > endptr)
  194401. {
  194402. png_warning(png_ptr, "Invalid pCAL data");
  194403. png_free(png_ptr, purpose);
  194404. png_free(png_ptr, params);
  194405. return;
  194406. }
  194407. }
  194408. png_set_pCAL(png_ptr, info_ptr, purpose, X0, X1, type, nparams,
  194409. units, params);
  194410. png_free(png_ptr, purpose);
  194411. png_free(png_ptr, params);
  194412. }
  194413. #endif
  194414. #if defined(PNG_READ_sCAL_SUPPORTED)
  194415. /* read the sCAL chunk */
  194416. void /* PRIVATE */
  194417. png_handle_sCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194418. {
  194419. png_charp buffer, ep;
  194420. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194421. double width, height;
  194422. png_charp vp;
  194423. #else
  194424. #ifdef PNG_FIXED_POINT_SUPPORTED
  194425. png_charp swidth, sheight;
  194426. #endif
  194427. #endif
  194428. png_size_t slength;
  194429. png_debug(1, "in png_handle_sCAL\n");
  194430. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194431. png_error(png_ptr, "Missing IHDR before sCAL");
  194432. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194433. {
  194434. png_warning(png_ptr, "Invalid sCAL after IDAT");
  194435. png_crc_finish(png_ptr, length);
  194436. return;
  194437. }
  194438. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sCAL))
  194439. {
  194440. png_warning(png_ptr, "Duplicate sCAL chunk");
  194441. png_crc_finish(png_ptr, length);
  194442. return;
  194443. }
  194444. png_debug1(2, "Allocating and reading sCAL chunk data (%lu bytes)\n",
  194445. length + 1);
  194446. buffer = (png_charp)png_malloc_warn(png_ptr, length + 1);
  194447. if (buffer == NULL)
  194448. {
  194449. png_warning(png_ptr, "Out of memory while processing sCAL chunk");
  194450. return;
  194451. }
  194452. slength = (png_size_t)length;
  194453. png_crc_read(png_ptr, (png_bytep)buffer, slength);
  194454. if (png_crc_finish(png_ptr, 0))
  194455. {
  194456. png_free(png_ptr, buffer);
  194457. return;
  194458. }
  194459. buffer[slength] = 0x00; /* null terminate the last string */
  194460. ep = buffer + 1; /* skip unit byte */
  194461. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194462. width = png_strtod(png_ptr, ep, &vp);
  194463. if (*vp)
  194464. {
  194465. png_warning(png_ptr, "malformed width string in sCAL chunk");
  194466. return;
  194467. }
  194468. #else
  194469. #ifdef PNG_FIXED_POINT_SUPPORTED
  194470. swidth = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  194471. if (swidth == NULL)
  194472. {
  194473. png_warning(png_ptr, "Out of memory while processing sCAL chunk width");
  194474. return;
  194475. }
  194476. png_memcpy(swidth, ep, (png_size_t)png_strlen(ep));
  194477. #endif
  194478. #endif
  194479. for (ep = buffer; *ep; ep++)
  194480. /* empty loop */ ;
  194481. ep++;
  194482. if (buffer + slength < ep)
  194483. {
  194484. png_warning(png_ptr, "Truncated sCAL chunk");
  194485. #if defined(PNG_FIXED_POINT_SUPPORTED) && \
  194486. !defined(PNG_FLOATING_POINT_SUPPORTED)
  194487. png_free(png_ptr, swidth);
  194488. #endif
  194489. png_free(png_ptr, buffer);
  194490. return;
  194491. }
  194492. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194493. height = png_strtod(png_ptr, ep, &vp);
  194494. if (*vp)
  194495. {
  194496. png_warning(png_ptr, "malformed height string in sCAL chunk");
  194497. return;
  194498. }
  194499. #else
  194500. #ifdef PNG_FIXED_POINT_SUPPORTED
  194501. sheight = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  194502. if (swidth == NULL)
  194503. {
  194504. png_warning(png_ptr, "Out of memory while processing sCAL chunk height");
  194505. return;
  194506. }
  194507. png_memcpy(sheight, ep, (png_size_t)png_strlen(ep));
  194508. #endif
  194509. #endif
  194510. if (buffer + slength < ep
  194511. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194512. || width <= 0. || height <= 0.
  194513. #endif
  194514. )
  194515. {
  194516. png_warning(png_ptr, "Invalid sCAL data");
  194517. png_free(png_ptr, buffer);
  194518. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  194519. png_free(png_ptr, swidth);
  194520. png_free(png_ptr, sheight);
  194521. #endif
  194522. return;
  194523. }
  194524. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194525. png_set_sCAL(png_ptr, info_ptr, buffer[0], width, height);
  194526. #else
  194527. #ifdef PNG_FIXED_POINT_SUPPORTED
  194528. png_set_sCAL_s(png_ptr, info_ptr, buffer[0], swidth, sheight);
  194529. #endif
  194530. #endif
  194531. png_free(png_ptr, buffer);
  194532. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  194533. png_free(png_ptr, swidth);
  194534. png_free(png_ptr, sheight);
  194535. #endif
  194536. }
  194537. #endif
  194538. #if defined(PNG_READ_tIME_SUPPORTED)
  194539. void /* PRIVATE */
  194540. png_handle_tIME(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194541. {
  194542. png_byte buf[7];
  194543. png_time mod_time;
  194544. png_debug(1, "in png_handle_tIME\n");
  194545. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194546. png_error(png_ptr, "Out of place tIME chunk");
  194547. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME))
  194548. {
  194549. png_warning(png_ptr, "Duplicate tIME chunk");
  194550. png_crc_finish(png_ptr, length);
  194551. return;
  194552. }
  194553. if (png_ptr->mode & PNG_HAVE_IDAT)
  194554. png_ptr->mode |= PNG_AFTER_IDAT;
  194555. if (length != 7)
  194556. {
  194557. png_warning(png_ptr, "Incorrect tIME chunk length");
  194558. png_crc_finish(png_ptr, length);
  194559. return;
  194560. }
  194561. png_crc_read(png_ptr, buf, 7);
  194562. if (png_crc_finish(png_ptr, 0))
  194563. return;
  194564. mod_time.second = buf[6];
  194565. mod_time.minute = buf[5];
  194566. mod_time.hour = buf[4];
  194567. mod_time.day = buf[3];
  194568. mod_time.month = buf[2];
  194569. mod_time.year = png_get_uint_16(buf);
  194570. png_set_tIME(png_ptr, info_ptr, &mod_time);
  194571. }
  194572. #endif
  194573. #if defined(PNG_READ_tEXt_SUPPORTED)
  194574. /* Note: this does not properly handle chunks that are > 64K under DOS */
  194575. void /* PRIVATE */
  194576. png_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194577. {
  194578. png_textp text_ptr;
  194579. png_charp key;
  194580. png_charp text;
  194581. png_uint_32 skip = 0;
  194582. png_size_t slength;
  194583. int ret;
  194584. png_debug(1, "in png_handle_tEXt\n");
  194585. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194586. png_error(png_ptr, "Missing IHDR before tEXt");
  194587. if (png_ptr->mode & PNG_HAVE_IDAT)
  194588. png_ptr->mode |= PNG_AFTER_IDAT;
  194589. #ifdef PNG_MAX_MALLOC_64K
  194590. if (length > (png_uint_32)65535L)
  194591. {
  194592. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  194593. skip = length - (png_uint_32)65535L;
  194594. length = (png_uint_32)65535L;
  194595. }
  194596. #endif
  194597. key = (png_charp)png_malloc_warn(png_ptr, length + 1);
  194598. if (key == NULL)
  194599. {
  194600. png_warning(png_ptr, "No memory to process text chunk.");
  194601. return;
  194602. }
  194603. slength = (png_size_t)length;
  194604. png_crc_read(png_ptr, (png_bytep)key, slength);
  194605. if (png_crc_finish(png_ptr, skip))
  194606. {
  194607. png_free(png_ptr, key);
  194608. return;
  194609. }
  194610. key[slength] = 0x00;
  194611. for (text = key; *text; text++)
  194612. /* empty loop to find end of key */ ;
  194613. if (text != key + slength)
  194614. text++;
  194615. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  194616. (png_uint_32)png_sizeof(png_text));
  194617. if (text_ptr == NULL)
  194618. {
  194619. png_warning(png_ptr, "Not enough memory to process text chunk.");
  194620. png_free(png_ptr, key);
  194621. return;
  194622. }
  194623. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  194624. text_ptr->key = key;
  194625. #ifdef PNG_iTXt_SUPPORTED
  194626. text_ptr->lang = NULL;
  194627. text_ptr->lang_key = NULL;
  194628. text_ptr->itxt_length = 0;
  194629. #endif
  194630. text_ptr->text = text;
  194631. text_ptr->text_length = png_strlen(text);
  194632. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  194633. png_free(png_ptr, key);
  194634. png_free(png_ptr, text_ptr);
  194635. if (ret)
  194636. png_warning(png_ptr, "Insufficient memory to process text chunk.");
  194637. }
  194638. #endif
  194639. #if defined(PNG_READ_zTXt_SUPPORTED)
  194640. /* note: this does not correctly handle chunks that are > 64K under DOS */
  194641. void /* PRIVATE */
  194642. png_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194643. {
  194644. png_textp text_ptr;
  194645. png_charp chunkdata;
  194646. png_charp text;
  194647. int comp_type;
  194648. int ret;
  194649. png_size_t slength, prefix_len, data_len;
  194650. png_debug(1, "in png_handle_zTXt\n");
  194651. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194652. png_error(png_ptr, "Missing IHDR before zTXt");
  194653. if (png_ptr->mode & PNG_HAVE_IDAT)
  194654. png_ptr->mode |= PNG_AFTER_IDAT;
  194655. #ifdef PNG_MAX_MALLOC_64K
  194656. /* We will no doubt have problems with chunks even half this size, but
  194657. there is no hard and fast rule to tell us where to stop. */
  194658. if (length > (png_uint_32)65535L)
  194659. {
  194660. png_warning(png_ptr,"zTXt chunk too large to fit in memory");
  194661. png_crc_finish(png_ptr, length);
  194662. return;
  194663. }
  194664. #endif
  194665. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  194666. if (chunkdata == NULL)
  194667. {
  194668. png_warning(png_ptr,"Out of memory processing zTXt chunk.");
  194669. return;
  194670. }
  194671. slength = (png_size_t)length;
  194672. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  194673. if (png_crc_finish(png_ptr, 0))
  194674. {
  194675. png_free(png_ptr, chunkdata);
  194676. return;
  194677. }
  194678. chunkdata[slength] = 0x00;
  194679. for (text = chunkdata; *text; text++)
  194680. /* empty loop */ ;
  194681. /* zTXt must have some text after the chunkdataword */
  194682. if (text >= chunkdata + slength - 2)
  194683. {
  194684. png_warning(png_ptr, "Truncated zTXt chunk");
  194685. png_free(png_ptr, chunkdata);
  194686. return;
  194687. }
  194688. else
  194689. {
  194690. comp_type = *(++text);
  194691. if (comp_type != PNG_TEXT_COMPRESSION_zTXt)
  194692. {
  194693. png_warning(png_ptr, "Unknown compression type in zTXt chunk");
  194694. comp_type = PNG_TEXT_COMPRESSION_zTXt;
  194695. }
  194696. text++; /* skip the compression_method byte */
  194697. }
  194698. prefix_len = text - chunkdata;
  194699. chunkdata = (png_charp)png_decompress_chunk(png_ptr, comp_type, chunkdata,
  194700. (png_size_t)length, prefix_len, &data_len);
  194701. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  194702. (png_uint_32)png_sizeof(png_text));
  194703. if (text_ptr == NULL)
  194704. {
  194705. png_warning(png_ptr,"Not enough memory to process zTXt chunk.");
  194706. png_free(png_ptr, chunkdata);
  194707. return;
  194708. }
  194709. text_ptr->compression = comp_type;
  194710. text_ptr->key = chunkdata;
  194711. #ifdef PNG_iTXt_SUPPORTED
  194712. text_ptr->lang = NULL;
  194713. text_ptr->lang_key = NULL;
  194714. text_ptr->itxt_length = 0;
  194715. #endif
  194716. text_ptr->text = chunkdata + prefix_len;
  194717. text_ptr->text_length = data_len;
  194718. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  194719. png_free(png_ptr, text_ptr);
  194720. png_free(png_ptr, chunkdata);
  194721. if (ret)
  194722. png_error(png_ptr, "Insufficient memory to store zTXt chunk.");
  194723. }
  194724. #endif
  194725. #if defined(PNG_READ_iTXt_SUPPORTED)
  194726. /* note: this does not correctly handle chunks that are > 64K under DOS */
  194727. void /* PRIVATE */
  194728. png_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194729. {
  194730. png_textp text_ptr;
  194731. png_charp chunkdata;
  194732. png_charp key, lang, text, lang_key;
  194733. int comp_flag;
  194734. int comp_type = 0;
  194735. int ret;
  194736. png_size_t slength, prefix_len, data_len;
  194737. png_debug(1, "in png_handle_iTXt\n");
  194738. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194739. png_error(png_ptr, "Missing IHDR before iTXt");
  194740. if (png_ptr->mode & PNG_HAVE_IDAT)
  194741. png_ptr->mode |= PNG_AFTER_IDAT;
  194742. #ifdef PNG_MAX_MALLOC_64K
  194743. /* We will no doubt have problems with chunks even half this size, but
  194744. there is no hard and fast rule to tell us where to stop. */
  194745. if (length > (png_uint_32)65535L)
  194746. {
  194747. png_warning(png_ptr,"iTXt chunk too large to fit in memory");
  194748. png_crc_finish(png_ptr, length);
  194749. return;
  194750. }
  194751. #endif
  194752. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  194753. if (chunkdata == NULL)
  194754. {
  194755. png_warning(png_ptr, "No memory to process iTXt chunk.");
  194756. return;
  194757. }
  194758. slength = (png_size_t)length;
  194759. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  194760. if (png_crc_finish(png_ptr, 0))
  194761. {
  194762. png_free(png_ptr, chunkdata);
  194763. return;
  194764. }
  194765. chunkdata[slength] = 0x00;
  194766. for (lang = chunkdata; *lang; lang++)
  194767. /* empty loop */ ;
  194768. lang++; /* skip NUL separator */
  194769. /* iTXt must have a language tag (possibly empty), two compression bytes,
  194770. translated keyword (possibly empty), and possibly some text after the
  194771. keyword */
  194772. if (lang >= chunkdata + slength - 3)
  194773. {
  194774. png_warning(png_ptr, "Truncated iTXt chunk");
  194775. png_free(png_ptr, chunkdata);
  194776. return;
  194777. }
  194778. else
  194779. {
  194780. comp_flag = *lang++;
  194781. comp_type = *lang++;
  194782. }
  194783. for (lang_key = lang; *lang_key; lang_key++)
  194784. /* empty loop */ ;
  194785. lang_key++; /* skip NUL separator */
  194786. if (lang_key >= chunkdata + slength)
  194787. {
  194788. png_warning(png_ptr, "Truncated iTXt chunk");
  194789. png_free(png_ptr, chunkdata);
  194790. return;
  194791. }
  194792. for (text = lang_key; *text; text++)
  194793. /* empty loop */ ;
  194794. text++; /* skip NUL separator */
  194795. if (text >= chunkdata + slength)
  194796. {
  194797. png_warning(png_ptr, "Malformed iTXt chunk");
  194798. png_free(png_ptr, chunkdata);
  194799. return;
  194800. }
  194801. prefix_len = text - chunkdata;
  194802. key=chunkdata;
  194803. if (comp_flag)
  194804. chunkdata = png_decompress_chunk(png_ptr, comp_type, chunkdata,
  194805. (size_t)length, prefix_len, &data_len);
  194806. else
  194807. data_len=png_strlen(chunkdata + prefix_len);
  194808. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  194809. (png_uint_32)png_sizeof(png_text));
  194810. if (text_ptr == NULL)
  194811. {
  194812. png_warning(png_ptr,"Not enough memory to process iTXt chunk.");
  194813. png_free(png_ptr, chunkdata);
  194814. return;
  194815. }
  194816. text_ptr->compression = (int)comp_flag + 1;
  194817. text_ptr->lang_key = chunkdata+(lang_key-key);
  194818. text_ptr->lang = chunkdata+(lang-key);
  194819. text_ptr->itxt_length = data_len;
  194820. text_ptr->text_length = 0;
  194821. text_ptr->key = chunkdata;
  194822. text_ptr->text = chunkdata + prefix_len;
  194823. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  194824. png_free(png_ptr, text_ptr);
  194825. png_free(png_ptr, chunkdata);
  194826. if (ret)
  194827. png_error(png_ptr, "Insufficient memory to store iTXt chunk.");
  194828. }
  194829. #endif
  194830. /* This function is called when we haven't found a handler for a
  194831. chunk. If there isn't a problem with the chunk itself (ie bad
  194832. chunk name, CRC, or a critical chunk), the chunk is silently ignored
  194833. -- unless the PNG_FLAG_UNKNOWN_CHUNKS_SUPPORTED flag is on in which
  194834. case it will be saved away to be written out later. */
  194835. void /* PRIVATE */
  194836. png_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194837. {
  194838. png_uint_32 skip = 0;
  194839. png_debug(1, "in png_handle_unknown\n");
  194840. if (png_ptr->mode & PNG_HAVE_IDAT)
  194841. {
  194842. #ifdef PNG_USE_LOCAL_ARRAYS
  194843. PNG_CONST PNG_IDAT;
  194844. #endif
  194845. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4)) /* not an IDAT */
  194846. png_ptr->mode |= PNG_AFTER_IDAT;
  194847. }
  194848. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  194849. if (!(png_ptr->chunk_name[0] & 0x20))
  194850. {
  194851. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  194852. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  194853. PNG_HANDLE_CHUNK_ALWAYS
  194854. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  194855. && png_ptr->read_user_chunk_fn == NULL
  194856. #endif
  194857. )
  194858. #endif
  194859. png_chunk_error(png_ptr, "unknown critical chunk");
  194860. }
  194861. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  194862. if ((png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS) ||
  194863. (png_ptr->read_user_chunk_fn != NULL))
  194864. {
  194865. #ifdef PNG_MAX_MALLOC_64K
  194866. if (length > (png_uint_32)65535L)
  194867. {
  194868. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  194869. skip = length - (png_uint_32)65535L;
  194870. length = (png_uint_32)65535L;
  194871. }
  194872. #endif
  194873. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  194874. (png_charp)png_ptr->chunk_name, 5);
  194875. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  194876. png_ptr->unknown_chunk.size = (png_size_t)length;
  194877. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  194878. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  194879. if(png_ptr->read_user_chunk_fn != NULL)
  194880. {
  194881. /* callback to user unknown chunk handler */
  194882. int ret;
  194883. ret = (*(png_ptr->read_user_chunk_fn))
  194884. (png_ptr, &png_ptr->unknown_chunk);
  194885. if (ret < 0)
  194886. png_chunk_error(png_ptr, "error in user chunk");
  194887. if (ret == 0)
  194888. {
  194889. if (!(png_ptr->chunk_name[0] & 0x20))
  194890. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  194891. PNG_HANDLE_CHUNK_ALWAYS)
  194892. png_chunk_error(png_ptr, "unknown critical chunk");
  194893. png_set_unknown_chunks(png_ptr, info_ptr,
  194894. &png_ptr->unknown_chunk, 1);
  194895. }
  194896. }
  194897. #else
  194898. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  194899. #endif
  194900. png_free(png_ptr, png_ptr->unknown_chunk.data);
  194901. png_ptr->unknown_chunk.data = NULL;
  194902. }
  194903. else
  194904. #endif
  194905. skip = length;
  194906. png_crc_finish(png_ptr, skip);
  194907. #if !defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  194908. info_ptr = info_ptr; /* quiet compiler warnings about unused info_ptr */
  194909. #endif
  194910. }
  194911. /* This function is called to verify that a chunk name is valid.
  194912. This function can't have the "critical chunk check" incorporated
  194913. into it, since in the future we will need to be able to call user
  194914. functions to handle unknown critical chunks after we check that
  194915. the chunk name itself is valid. */
  194916. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  194917. void /* PRIVATE */
  194918. png_check_chunk_name(png_structp png_ptr, png_bytep chunk_name)
  194919. {
  194920. png_debug(1, "in png_check_chunk_name\n");
  194921. if (isnonalpha(chunk_name[0]) || isnonalpha(chunk_name[1]) ||
  194922. isnonalpha(chunk_name[2]) || isnonalpha(chunk_name[3]))
  194923. {
  194924. png_chunk_error(png_ptr, "invalid chunk type");
  194925. }
  194926. }
  194927. /* Combines the row recently read in with the existing pixels in the
  194928. row. This routine takes care of alpha and transparency if requested.
  194929. This routine also handles the two methods of progressive display
  194930. of interlaced images, depending on the mask value.
  194931. The mask value describes which pixels are to be combined with
  194932. the row. The pattern always repeats every 8 pixels, so just 8
  194933. bits are needed. A one indicates the pixel is to be combined,
  194934. a zero indicates the pixel is to be skipped. This is in addition
  194935. to any alpha or transparency value associated with the pixel. If
  194936. you want all pixels to be combined, pass 0xff (255) in mask. */
  194937. void /* PRIVATE */
  194938. png_combine_row(png_structp png_ptr, png_bytep row, int mask)
  194939. {
  194940. png_debug(1,"in png_combine_row\n");
  194941. if (mask == 0xff)
  194942. {
  194943. png_memcpy(row, png_ptr->row_buf + 1,
  194944. PNG_ROWBYTES(png_ptr->row_info.pixel_depth, png_ptr->width));
  194945. }
  194946. else
  194947. {
  194948. switch (png_ptr->row_info.pixel_depth)
  194949. {
  194950. case 1:
  194951. {
  194952. png_bytep sp = png_ptr->row_buf + 1;
  194953. png_bytep dp = row;
  194954. int s_inc, s_start, s_end;
  194955. int m = 0x80;
  194956. int shift;
  194957. png_uint_32 i;
  194958. png_uint_32 row_width = png_ptr->width;
  194959. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  194960. if (png_ptr->transformations & PNG_PACKSWAP)
  194961. {
  194962. s_start = 0;
  194963. s_end = 7;
  194964. s_inc = 1;
  194965. }
  194966. else
  194967. #endif
  194968. {
  194969. s_start = 7;
  194970. s_end = 0;
  194971. s_inc = -1;
  194972. }
  194973. shift = s_start;
  194974. for (i = 0; i < row_width; i++)
  194975. {
  194976. if (m & mask)
  194977. {
  194978. int value;
  194979. value = (*sp >> shift) & 0x01;
  194980. *dp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  194981. *dp |= (png_byte)(value << shift);
  194982. }
  194983. if (shift == s_end)
  194984. {
  194985. shift = s_start;
  194986. sp++;
  194987. dp++;
  194988. }
  194989. else
  194990. shift += s_inc;
  194991. if (m == 1)
  194992. m = 0x80;
  194993. else
  194994. m >>= 1;
  194995. }
  194996. break;
  194997. }
  194998. case 2:
  194999. {
  195000. png_bytep sp = png_ptr->row_buf + 1;
  195001. png_bytep dp = row;
  195002. int s_start, s_end, s_inc;
  195003. int m = 0x80;
  195004. int shift;
  195005. png_uint_32 i;
  195006. png_uint_32 row_width = png_ptr->width;
  195007. int value;
  195008. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195009. if (png_ptr->transformations & PNG_PACKSWAP)
  195010. {
  195011. s_start = 0;
  195012. s_end = 6;
  195013. s_inc = 2;
  195014. }
  195015. else
  195016. #endif
  195017. {
  195018. s_start = 6;
  195019. s_end = 0;
  195020. s_inc = -2;
  195021. }
  195022. shift = s_start;
  195023. for (i = 0; i < row_width; i++)
  195024. {
  195025. if (m & mask)
  195026. {
  195027. value = (*sp >> shift) & 0x03;
  195028. *dp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  195029. *dp |= (png_byte)(value << shift);
  195030. }
  195031. if (shift == s_end)
  195032. {
  195033. shift = s_start;
  195034. sp++;
  195035. dp++;
  195036. }
  195037. else
  195038. shift += s_inc;
  195039. if (m == 1)
  195040. m = 0x80;
  195041. else
  195042. m >>= 1;
  195043. }
  195044. break;
  195045. }
  195046. case 4:
  195047. {
  195048. png_bytep sp = png_ptr->row_buf + 1;
  195049. png_bytep dp = row;
  195050. int s_start, s_end, s_inc;
  195051. int m = 0x80;
  195052. int shift;
  195053. png_uint_32 i;
  195054. png_uint_32 row_width = png_ptr->width;
  195055. int value;
  195056. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195057. if (png_ptr->transformations & PNG_PACKSWAP)
  195058. {
  195059. s_start = 0;
  195060. s_end = 4;
  195061. s_inc = 4;
  195062. }
  195063. else
  195064. #endif
  195065. {
  195066. s_start = 4;
  195067. s_end = 0;
  195068. s_inc = -4;
  195069. }
  195070. shift = s_start;
  195071. for (i = 0; i < row_width; i++)
  195072. {
  195073. if (m & mask)
  195074. {
  195075. value = (*sp >> shift) & 0xf;
  195076. *dp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  195077. *dp |= (png_byte)(value << shift);
  195078. }
  195079. if (shift == s_end)
  195080. {
  195081. shift = s_start;
  195082. sp++;
  195083. dp++;
  195084. }
  195085. else
  195086. shift += s_inc;
  195087. if (m == 1)
  195088. m = 0x80;
  195089. else
  195090. m >>= 1;
  195091. }
  195092. break;
  195093. }
  195094. default:
  195095. {
  195096. png_bytep sp = png_ptr->row_buf + 1;
  195097. png_bytep dp = row;
  195098. png_size_t pixel_bytes = (png_ptr->row_info.pixel_depth >> 3);
  195099. png_uint_32 i;
  195100. png_uint_32 row_width = png_ptr->width;
  195101. png_byte m = 0x80;
  195102. for (i = 0; i < row_width; i++)
  195103. {
  195104. if (m & mask)
  195105. {
  195106. png_memcpy(dp, sp, pixel_bytes);
  195107. }
  195108. sp += pixel_bytes;
  195109. dp += pixel_bytes;
  195110. if (m == 1)
  195111. m = 0x80;
  195112. else
  195113. m >>= 1;
  195114. }
  195115. break;
  195116. }
  195117. }
  195118. }
  195119. }
  195120. #ifdef PNG_READ_INTERLACING_SUPPORTED
  195121. /* OLD pre-1.0.9 interface:
  195122. void png_do_read_interlace(png_row_infop row_info, png_bytep row, int pass,
  195123. png_uint_32 transformations)
  195124. */
  195125. void /* PRIVATE */
  195126. png_do_read_interlace(png_structp png_ptr)
  195127. {
  195128. png_row_infop row_info = &(png_ptr->row_info);
  195129. png_bytep row = png_ptr->row_buf + 1;
  195130. int pass = png_ptr->pass;
  195131. png_uint_32 transformations = png_ptr->transformations;
  195132. #ifdef PNG_USE_LOCAL_ARRAYS
  195133. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  195134. /* offset to next interlace block */
  195135. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  195136. #endif
  195137. png_debug(1,"in png_do_read_interlace\n");
  195138. if (row != NULL && row_info != NULL)
  195139. {
  195140. png_uint_32 final_width;
  195141. final_width = row_info->width * png_pass_inc[pass];
  195142. switch (row_info->pixel_depth)
  195143. {
  195144. case 1:
  195145. {
  195146. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 3);
  195147. png_bytep dp = row + (png_size_t)((final_width - 1) >> 3);
  195148. int sshift, dshift;
  195149. int s_start, s_end, s_inc;
  195150. int jstop = png_pass_inc[pass];
  195151. png_byte v;
  195152. png_uint_32 i;
  195153. int j;
  195154. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195155. if (transformations & PNG_PACKSWAP)
  195156. {
  195157. sshift = (int)((row_info->width + 7) & 0x07);
  195158. dshift = (int)((final_width + 7) & 0x07);
  195159. s_start = 7;
  195160. s_end = 0;
  195161. s_inc = -1;
  195162. }
  195163. else
  195164. #endif
  195165. {
  195166. sshift = 7 - (int)((row_info->width + 7) & 0x07);
  195167. dshift = 7 - (int)((final_width + 7) & 0x07);
  195168. s_start = 0;
  195169. s_end = 7;
  195170. s_inc = 1;
  195171. }
  195172. for (i = 0; i < row_info->width; i++)
  195173. {
  195174. v = (png_byte)((*sp >> sshift) & 0x01);
  195175. for (j = 0; j < jstop; j++)
  195176. {
  195177. *dp &= (png_byte)((0x7f7f >> (7 - dshift)) & 0xff);
  195178. *dp |= (png_byte)(v << dshift);
  195179. if (dshift == s_end)
  195180. {
  195181. dshift = s_start;
  195182. dp--;
  195183. }
  195184. else
  195185. dshift += s_inc;
  195186. }
  195187. if (sshift == s_end)
  195188. {
  195189. sshift = s_start;
  195190. sp--;
  195191. }
  195192. else
  195193. sshift += s_inc;
  195194. }
  195195. break;
  195196. }
  195197. case 2:
  195198. {
  195199. png_bytep sp = row + (png_uint_32)((row_info->width - 1) >> 2);
  195200. png_bytep dp = row + (png_uint_32)((final_width - 1) >> 2);
  195201. int sshift, dshift;
  195202. int s_start, s_end, s_inc;
  195203. int jstop = png_pass_inc[pass];
  195204. png_uint_32 i;
  195205. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195206. if (transformations & PNG_PACKSWAP)
  195207. {
  195208. sshift = (int)(((row_info->width + 3) & 0x03) << 1);
  195209. dshift = (int)(((final_width + 3) & 0x03) << 1);
  195210. s_start = 6;
  195211. s_end = 0;
  195212. s_inc = -2;
  195213. }
  195214. else
  195215. #endif
  195216. {
  195217. sshift = (int)((3 - ((row_info->width + 3) & 0x03)) << 1);
  195218. dshift = (int)((3 - ((final_width + 3) & 0x03)) << 1);
  195219. s_start = 0;
  195220. s_end = 6;
  195221. s_inc = 2;
  195222. }
  195223. for (i = 0; i < row_info->width; i++)
  195224. {
  195225. png_byte v;
  195226. int j;
  195227. v = (png_byte)((*sp >> sshift) & 0x03);
  195228. for (j = 0; j < jstop; j++)
  195229. {
  195230. *dp &= (png_byte)((0x3f3f >> (6 - dshift)) & 0xff);
  195231. *dp |= (png_byte)(v << dshift);
  195232. if (dshift == s_end)
  195233. {
  195234. dshift = s_start;
  195235. dp--;
  195236. }
  195237. else
  195238. dshift += s_inc;
  195239. }
  195240. if (sshift == s_end)
  195241. {
  195242. sshift = s_start;
  195243. sp--;
  195244. }
  195245. else
  195246. sshift += s_inc;
  195247. }
  195248. break;
  195249. }
  195250. case 4:
  195251. {
  195252. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 1);
  195253. png_bytep dp = row + (png_size_t)((final_width - 1) >> 1);
  195254. int sshift, dshift;
  195255. int s_start, s_end, s_inc;
  195256. png_uint_32 i;
  195257. int jstop = png_pass_inc[pass];
  195258. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195259. if (transformations & PNG_PACKSWAP)
  195260. {
  195261. sshift = (int)(((row_info->width + 1) & 0x01) << 2);
  195262. dshift = (int)(((final_width + 1) & 0x01) << 2);
  195263. s_start = 4;
  195264. s_end = 0;
  195265. s_inc = -4;
  195266. }
  195267. else
  195268. #endif
  195269. {
  195270. sshift = (int)((1 - ((row_info->width + 1) & 0x01)) << 2);
  195271. dshift = (int)((1 - ((final_width + 1) & 0x01)) << 2);
  195272. s_start = 0;
  195273. s_end = 4;
  195274. s_inc = 4;
  195275. }
  195276. for (i = 0; i < row_info->width; i++)
  195277. {
  195278. png_byte v = (png_byte)((*sp >> sshift) & 0xf);
  195279. int j;
  195280. for (j = 0; j < jstop; j++)
  195281. {
  195282. *dp &= (png_byte)((0xf0f >> (4 - dshift)) & 0xff);
  195283. *dp |= (png_byte)(v << dshift);
  195284. if (dshift == s_end)
  195285. {
  195286. dshift = s_start;
  195287. dp--;
  195288. }
  195289. else
  195290. dshift += s_inc;
  195291. }
  195292. if (sshift == s_end)
  195293. {
  195294. sshift = s_start;
  195295. sp--;
  195296. }
  195297. else
  195298. sshift += s_inc;
  195299. }
  195300. break;
  195301. }
  195302. default:
  195303. {
  195304. png_size_t pixel_bytes = (row_info->pixel_depth >> 3);
  195305. png_bytep sp = row + (png_size_t)(row_info->width - 1) * pixel_bytes;
  195306. png_bytep dp = row + (png_size_t)(final_width - 1) * pixel_bytes;
  195307. int jstop = png_pass_inc[pass];
  195308. png_uint_32 i;
  195309. for (i = 0; i < row_info->width; i++)
  195310. {
  195311. png_byte v[8];
  195312. int j;
  195313. png_memcpy(v, sp, pixel_bytes);
  195314. for (j = 0; j < jstop; j++)
  195315. {
  195316. png_memcpy(dp, v, pixel_bytes);
  195317. dp -= pixel_bytes;
  195318. }
  195319. sp -= pixel_bytes;
  195320. }
  195321. break;
  195322. }
  195323. }
  195324. row_info->width = final_width;
  195325. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,final_width);
  195326. }
  195327. #if !defined(PNG_READ_PACKSWAP_SUPPORTED)
  195328. transformations = transformations; /* silence compiler warning */
  195329. #endif
  195330. }
  195331. #endif /* PNG_READ_INTERLACING_SUPPORTED */
  195332. void /* PRIVATE */
  195333. png_read_filter_row(png_structp, png_row_infop row_info, png_bytep row,
  195334. png_bytep prev_row, int filter)
  195335. {
  195336. png_debug(1, "in png_read_filter_row\n");
  195337. png_debug2(2,"row = %lu, filter = %d\n", png_ptr->row_number, filter);
  195338. switch (filter)
  195339. {
  195340. case PNG_FILTER_VALUE_NONE:
  195341. break;
  195342. case PNG_FILTER_VALUE_SUB:
  195343. {
  195344. png_uint_32 i;
  195345. png_uint_32 istop = row_info->rowbytes;
  195346. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  195347. png_bytep rp = row + bpp;
  195348. png_bytep lp = row;
  195349. for (i = bpp; i < istop; i++)
  195350. {
  195351. *rp = (png_byte)(((int)(*rp) + (int)(*lp++)) & 0xff);
  195352. rp++;
  195353. }
  195354. break;
  195355. }
  195356. case PNG_FILTER_VALUE_UP:
  195357. {
  195358. png_uint_32 i;
  195359. png_uint_32 istop = row_info->rowbytes;
  195360. png_bytep rp = row;
  195361. png_bytep pp = prev_row;
  195362. for (i = 0; i < istop; i++)
  195363. {
  195364. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  195365. rp++;
  195366. }
  195367. break;
  195368. }
  195369. case PNG_FILTER_VALUE_AVG:
  195370. {
  195371. png_uint_32 i;
  195372. png_bytep rp = row;
  195373. png_bytep pp = prev_row;
  195374. png_bytep lp = row;
  195375. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  195376. png_uint_32 istop = row_info->rowbytes - bpp;
  195377. for (i = 0; i < bpp; i++)
  195378. {
  195379. *rp = (png_byte)(((int)(*rp) +
  195380. ((int)(*pp++) / 2 )) & 0xff);
  195381. rp++;
  195382. }
  195383. for (i = 0; i < istop; i++)
  195384. {
  195385. *rp = (png_byte)(((int)(*rp) +
  195386. (int)(*pp++ + *lp++) / 2 ) & 0xff);
  195387. rp++;
  195388. }
  195389. break;
  195390. }
  195391. case PNG_FILTER_VALUE_PAETH:
  195392. {
  195393. png_uint_32 i;
  195394. png_bytep rp = row;
  195395. png_bytep pp = prev_row;
  195396. png_bytep lp = row;
  195397. png_bytep cp = prev_row;
  195398. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  195399. png_uint_32 istop=row_info->rowbytes - bpp;
  195400. for (i = 0; i < bpp; i++)
  195401. {
  195402. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  195403. rp++;
  195404. }
  195405. for (i = 0; i < istop; i++) /* use leftover rp,pp */
  195406. {
  195407. int a, b, c, pa, pb, pc, p;
  195408. a = *lp++;
  195409. b = *pp++;
  195410. c = *cp++;
  195411. p = b - c;
  195412. pc = a - c;
  195413. #ifdef PNG_USE_ABS
  195414. pa = abs(p);
  195415. pb = abs(pc);
  195416. pc = abs(p + pc);
  195417. #else
  195418. pa = p < 0 ? -p : p;
  195419. pb = pc < 0 ? -pc : pc;
  195420. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  195421. #endif
  195422. /*
  195423. if (pa <= pb && pa <= pc)
  195424. p = a;
  195425. else if (pb <= pc)
  195426. p = b;
  195427. else
  195428. p = c;
  195429. */
  195430. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  195431. *rp = (png_byte)(((int)(*rp) + p) & 0xff);
  195432. rp++;
  195433. }
  195434. break;
  195435. }
  195436. default:
  195437. png_warning(png_ptr, "Ignoring bad adaptive filter type");
  195438. *row=0;
  195439. break;
  195440. }
  195441. }
  195442. void /* PRIVATE */
  195443. png_read_finish_row(png_structp png_ptr)
  195444. {
  195445. #ifdef PNG_USE_LOCAL_ARRAYS
  195446. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  195447. /* start of interlace block */
  195448. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  195449. /* offset to next interlace block */
  195450. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  195451. /* start of interlace block in the y direction */
  195452. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  195453. /* offset to next interlace block in the y direction */
  195454. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  195455. #endif
  195456. png_debug(1, "in png_read_finish_row\n");
  195457. png_ptr->row_number++;
  195458. if (png_ptr->row_number < png_ptr->num_rows)
  195459. return;
  195460. if (png_ptr->interlaced)
  195461. {
  195462. png_ptr->row_number = 0;
  195463. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  195464. png_ptr->rowbytes + 1);
  195465. do
  195466. {
  195467. png_ptr->pass++;
  195468. if (png_ptr->pass >= 7)
  195469. break;
  195470. png_ptr->iwidth = (png_ptr->width +
  195471. png_pass_inc[png_ptr->pass] - 1 -
  195472. png_pass_start[png_ptr->pass]) /
  195473. png_pass_inc[png_ptr->pass];
  195474. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  195475. png_ptr->iwidth) + 1;
  195476. if (!(png_ptr->transformations & PNG_INTERLACE))
  195477. {
  195478. png_ptr->num_rows = (png_ptr->height +
  195479. png_pass_yinc[png_ptr->pass] - 1 -
  195480. png_pass_ystart[png_ptr->pass]) /
  195481. png_pass_yinc[png_ptr->pass];
  195482. if (!(png_ptr->num_rows))
  195483. continue;
  195484. }
  195485. else /* if (png_ptr->transformations & PNG_INTERLACE) */
  195486. break;
  195487. } while (png_ptr->iwidth == 0);
  195488. if (png_ptr->pass < 7)
  195489. return;
  195490. }
  195491. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  195492. {
  195493. #ifdef PNG_USE_LOCAL_ARRAYS
  195494. PNG_CONST PNG_IDAT;
  195495. #endif
  195496. char extra;
  195497. int ret;
  195498. png_ptr->zstream.next_out = (Bytef *)&extra;
  195499. png_ptr->zstream.avail_out = (uInt)1;
  195500. for(;;)
  195501. {
  195502. if (!(png_ptr->zstream.avail_in))
  195503. {
  195504. while (!png_ptr->idat_size)
  195505. {
  195506. png_byte chunk_length[4];
  195507. png_crc_finish(png_ptr, 0);
  195508. png_read_data(png_ptr, chunk_length, 4);
  195509. png_ptr->idat_size = png_get_uint_31(png_ptr, chunk_length);
  195510. png_reset_crc(png_ptr);
  195511. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  195512. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  195513. png_error(png_ptr, "Not enough image data");
  195514. }
  195515. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  195516. png_ptr->zstream.next_in = png_ptr->zbuf;
  195517. if (png_ptr->zbuf_size > png_ptr->idat_size)
  195518. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  195519. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zstream.avail_in);
  195520. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  195521. }
  195522. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  195523. if (ret == Z_STREAM_END)
  195524. {
  195525. if (!(png_ptr->zstream.avail_out) || png_ptr->zstream.avail_in ||
  195526. png_ptr->idat_size)
  195527. png_warning(png_ptr, "Extra compressed data");
  195528. png_ptr->mode |= PNG_AFTER_IDAT;
  195529. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  195530. break;
  195531. }
  195532. if (ret != Z_OK)
  195533. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  195534. "Decompression Error");
  195535. if (!(png_ptr->zstream.avail_out))
  195536. {
  195537. png_warning(png_ptr, "Extra compressed data.");
  195538. png_ptr->mode |= PNG_AFTER_IDAT;
  195539. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  195540. break;
  195541. }
  195542. }
  195543. png_ptr->zstream.avail_out = 0;
  195544. }
  195545. if (png_ptr->idat_size || png_ptr->zstream.avail_in)
  195546. png_warning(png_ptr, "Extra compression data");
  195547. inflateReset(&png_ptr->zstream);
  195548. png_ptr->mode |= PNG_AFTER_IDAT;
  195549. }
  195550. void /* PRIVATE */
  195551. png_read_start_row(png_structp png_ptr)
  195552. {
  195553. #ifdef PNG_USE_LOCAL_ARRAYS
  195554. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  195555. /* start of interlace block */
  195556. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  195557. /* offset to next interlace block */
  195558. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  195559. /* start of interlace block in the y direction */
  195560. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  195561. /* offset to next interlace block in the y direction */
  195562. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  195563. #endif
  195564. int max_pixel_depth;
  195565. png_uint_32 row_bytes;
  195566. png_debug(1, "in png_read_start_row\n");
  195567. png_ptr->zstream.avail_in = 0;
  195568. png_init_read_transformations(png_ptr);
  195569. if (png_ptr->interlaced)
  195570. {
  195571. if (!(png_ptr->transformations & PNG_INTERLACE))
  195572. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  195573. png_pass_ystart[0]) / png_pass_yinc[0];
  195574. else
  195575. png_ptr->num_rows = png_ptr->height;
  195576. png_ptr->iwidth = (png_ptr->width +
  195577. png_pass_inc[png_ptr->pass] - 1 -
  195578. png_pass_start[png_ptr->pass]) /
  195579. png_pass_inc[png_ptr->pass];
  195580. row_bytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->iwidth) + 1;
  195581. png_ptr->irowbytes = (png_size_t)row_bytes;
  195582. if((png_uint_32)png_ptr->irowbytes != row_bytes)
  195583. png_error(png_ptr, "Rowbytes overflow in png_read_start_row");
  195584. }
  195585. else
  195586. {
  195587. png_ptr->num_rows = png_ptr->height;
  195588. png_ptr->iwidth = png_ptr->width;
  195589. png_ptr->irowbytes = png_ptr->rowbytes + 1;
  195590. }
  195591. max_pixel_depth = png_ptr->pixel_depth;
  195592. #if defined(PNG_READ_PACK_SUPPORTED)
  195593. if ((png_ptr->transformations & PNG_PACK) && png_ptr->bit_depth < 8)
  195594. max_pixel_depth = 8;
  195595. #endif
  195596. #if defined(PNG_READ_EXPAND_SUPPORTED)
  195597. if (png_ptr->transformations & PNG_EXPAND)
  195598. {
  195599. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195600. {
  195601. if (png_ptr->num_trans)
  195602. max_pixel_depth = 32;
  195603. else
  195604. max_pixel_depth = 24;
  195605. }
  195606. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  195607. {
  195608. if (max_pixel_depth < 8)
  195609. max_pixel_depth = 8;
  195610. if (png_ptr->num_trans)
  195611. max_pixel_depth *= 2;
  195612. }
  195613. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  195614. {
  195615. if (png_ptr->num_trans)
  195616. {
  195617. max_pixel_depth *= 4;
  195618. max_pixel_depth /= 3;
  195619. }
  195620. }
  195621. }
  195622. #endif
  195623. #if defined(PNG_READ_FILLER_SUPPORTED)
  195624. if (png_ptr->transformations & (PNG_FILLER))
  195625. {
  195626. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195627. max_pixel_depth = 32;
  195628. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  195629. {
  195630. if (max_pixel_depth <= 8)
  195631. max_pixel_depth = 16;
  195632. else
  195633. max_pixel_depth = 32;
  195634. }
  195635. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  195636. {
  195637. if (max_pixel_depth <= 32)
  195638. max_pixel_depth = 32;
  195639. else
  195640. max_pixel_depth = 64;
  195641. }
  195642. }
  195643. #endif
  195644. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  195645. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  195646. {
  195647. if (
  195648. #if defined(PNG_READ_EXPAND_SUPPORTED)
  195649. (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND)) ||
  195650. #endif
  195651. #if defined(PNG_READ_FILLER_SUPPORTED)
  195652. (png_ptr->transformations & (PNG_FILLER)) ||
  195653. #endif
  195654. png_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  195655. {
  195656. if (max_pixel_depth <= 16)
  195657. max_pixel_depth = 32;
  195658. else
  195659. max_pixel_depth = 64;
  195660. }
  195661. else
  195662. {
  195663. if (max_pixel_depth <= 8)
  195664. {
  195665. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  195666. max_pixel_depth = 32;
  195667. else
  195668. max_pixel_depth = 24;
  195669. }
  195670. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  195671. max_pixel_depth = 64;
  195672. else
  195673. max_pixel_depth = 48;
  195674. }
  195675. }
  195676. #endif
  195677. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) && \
  195678. defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  195679. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  195680. {
  195681. int user_pixel_depth=png_ptr->user_transform_depth*
  195682. png_ptr->user_transform_channels;
  195683. if(user_pixel_depth > max_pixel_depth)
  195684. max_pixel_depth=user_pixel_depth;
  195685. }
  195686. #endif
  195687. /* align the width on the next larger 8 pixels. Mainly used
  195688. for interlacing */
  195689. row_bytes = ((png_ptr->width + 7) & ~((png_uint_32)7));
  195690. /* calculate the maximum bytes needed, adding a byte and a pixel
  195691. for safety's sake */
  195692. row_bytes = PNG_ROWBYTES(max_pixel_depth,row_bytes) +
  195693. 1 + ((max_pixel_depth + 7) >> 3);
  195694. #ifdef PNG_MAX_MALLOC_64K
  195695. if (row_bytes > (png_uint_32)65536L)
  195696. png_error(png_ptr, "This image requires a row greater than 64KB");
  195697. #endif
  195698. png_ptr->big_row_buf = (png_bytep)png_malloc(png_ptr, row_bytes+64);
  195699. png_ptr->row_buf = png_ptr->big_row_buf+32;
  195700. #ifdef PNG_MAX_MALLOC_64K
  195701. if ((png_uint_32)png_ptr->rowbytes + 1 > (png_uint_32)65536L)
  195702. png_error(png_ptr, "This image requires a row greater than 64KB");
  195703. #endif
  195704. if ((png_uint_32)png_ptr->rowbytes > (png_uint_32)(PNG_SIZE_MAX - 1))
  195705. png_error(png_ptr, "Row has too many bytes to allocate in memory.");
  195706. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)(
  195707. png_ptr->rowbytes + 1));
  195708. png_memset_check(png_ptr, png_ptr->prev_row, 0, png_ptr->rowbytes + 1);
  195709. png_debug1(3, "width = %lu,\n", png_ptr->width);
  195710. png_debug1(3, "height = %lu,\n", png_ptr->height);
  195711. png_debug1(3, "iwidth = %lu,\n", png_ptr->iwidth);
  195712. png_debug1(3, "num_rows = %lu\n", png_ptr->num_rows);
  195713. png_debug1(3, "rowbytes = %lu,\n", png_ptr->rowbytes);
  195714. png_debug1(3, "irowbytes = %lu,\n", png_ptr->irowbytes);
  195715. png_ptr->flags |= PNG_FLAG_ROW_INIT;
  195716. }
  195717. #endif /* PNG_READ_SUPPORTED */
  195718. /*** End of inlined file: pngrutil.c ***/
  195719. /*** Start of inlined file: pngset.c ***/
  195720. /* pngset.c - storage of image information into info struct
  195721. *
  195722. * Last changed in libpng 1.2.21 [October 4, 2007]
  195723. * For conditions of distribution and use, see copyright notice in png.h
  195724. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  195725. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  195726. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  195727. *
  195728. * The functions here are used during reads to store data from the file
  195729. * into the info struct, and during writes to store application data
  195730. * into the info struct for writing into the file. This abstracts the
  195731. * info struct and allows us to change the structure in the future.
  195732. */
  195733. #define PNG_INTERNAL
  195734. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  195735. #if defined(PNG_bKGD_SUPPORTED)
  195736. void PNGAPI
  195737. png_set_bKGD(png_structp png_ptr, png_infop info_ptr, png_color_16p background)
  195738. {
  195739. png_debug1(1, "in %s storage function\n", "bKGD");
  195740. if (png_ptr == NULL || info_ptr == NULL)
  195741. return;
  195742. png_memcpy(&(info_ptr->background), background, png_sizeof(png_color_16));
  195743. info_ptr->valid |= PNG_INFO_bKGD;
  195744. }
  195745. #endif
  195746. #if defined(PNG_cHRM_SUPPORTED)
  195747. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195748. void PNGAPI
  195749. png_set_cHRM(png_structp png_ptr, png_infop info_ptr,
  195750. double white_x, double white_y, double red_x, double red_y,
  195751. double green_x, double green_y, double blue_x, double blue_y)
  195752. {
  195753. png_debug1(1, "in %s storage function\n", "cHRM");
  195754. if (png_ptr == NULL || info_ptr == NULL)
  195755. return;
  195756. if (white_x < 0.0 || white_y < 0.0 ||
  195757. red_x < 0.0 || red_y < 0.0 ||
  195758. green_x < 0.0 || green_y < 0.0 ||
  195759. blue_x < 0.0 || blue_y < 0.0)
  195760. {
  195761. png_warning(png_ptr,
  195762. "Ignoring attempt to set negative chromaticity value");
  195763. return;
  195764. }
  195765. if (white_x > 21474.83 || white_y > 21474.83 ||
  195766. red_x > 21474.83 || red_y > 21474.83 ||
  195767. green_x > 21474.83 || green_y > 21474.83 ||
  195768. blue_x > 21474.83 || blue_y > 21474.83)
  195769. {
  195770. png_warning(png_ptr,
  195771. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  195772. return;
  195773. }
  195774. info_ptr->x_white = (float)white_x;
  195775. info_ptr->y_white = (float)white_y;
  195776. info_ptr->x_red = (float)red_x;
  195777. info_ptr->y_red = (float)red_y;
  195778. info_ptr->x_green = (float)green_x;
  195779. info_ptr->y_green = (float)green_y;
  195780. info_ptr->x_blue = (float)blue_x;
  195781. info_ptr->y_blue = (float)blue_y;
  195782. #ifdef PNG_FIXED_POINT_SUPPORTED
  195783. info_ptr->int_x_white = (png_fixed_point)(white_x*100000.+0.5);
  195784. info_ptr->int_y_white = (png_fixed_point)(white_y*100000.+0.5);
  195785. info_ptr->int_x_red = (png_fixed_point)( red_x*100000.+0.5);
  195786. info_ptr->int_y_red = (png_fixed_point)( red_y*100000.+0.5);
  195787. info_ptr->int_x_green = (png_fixed_point)(green_x*100000.+0.5);
  195788. info_ptr->int_y_green = (png_fixed_point)(green_y*100000.+0.5);
  195789. info_ptr->int_x_blue = (png_fixed_point)( blue_x*100000.+0.5);
  195790. info_ptr->int_y_blue = (png_fixed_point)( blue_y*100000.+0.5);
  195791. #endif
  195792. info_ptr->valid |= PNG_INFO_cHRM;
  195793. }
  195794. #endif
  195795. #ifdef PNG_FIXED_POINT_SUPPORTED
  195796. void PNGAPI
  195797. png_set_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  195798. png_fixed_point white_x, png_fixed_point white_y, png_fixed_point red_x,
  195799. png_fixed_point red_y, png_fixed_point green_x, png_fixed_point green_y,
  195800. png_fixed_point blue_x, png_fixed_point blue_y)
  195801. {
  195802. png_debug1(1, "in %s storage function\n", "cHRM");
  195803. if (png_ptr == NULL || info_ptr == NULL)
  195804. return;
  195805. if (white_x < 0 || white_y < 0 ||
  195806. red_x < 0 || red_y < 0 ||
  195807. green_x < 0 || green_y < 0 ||
  195808. blue_x < 0 || blue_y < 0)
  195809. {
  195810. png_warning(png_ptr,
  195811. "Ignoring attempt to set negative chromaticity value");
  195812. return;
  195813. }
  195814. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195815. if (white_x > (double) PNG_UINT_31_MAX ||
  195816. white_y > (double) PNG_UINT_31_MAX ||
  195817. red_x > (double) PNG_UINT_31_MAX ||
  195818. red_y > (double) PNG_UINT_31_MAX ||
  195819. green_x > (double) PNG_UINT_31_MAX ||
  195820. green_y > (double) PNG_UINT_31_MAX ||
  195821. blue_x > (double) PNG_UINT_31_MAX ||
  195822. blue_y > (double) PNG_UINT_31_MAX)
  195823. #else
  195824. if (white_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  195825. white_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  195826. red_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  195827. red_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  195828. green_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  195829. green_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  195830. blue_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  195831. blue_y > (png_fixed_point) PNG_UINT_31_MAX/100000L)
  195832. #endif
  195833. {
  195834. png_warning(png_ptr,
  195835. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  195836. return;
  195837. }
  195838. info_ptr->int_x_white = white_x;
  195839. info_ptr->int_y_white = white_y;
  195840. info_ptr->int_x_red = red_x;
  195841. info_ptr->int_y_red = red_y;
  195842. info_ptr->int_x_green = green_x;
  195843. info_ptr->int_y_green = green_y;
  195844. info_ptr->int_x_blue = blue_x;
  195845. info_ptr->int_y_blue = blue_y;
  195846. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195847. info_ptr->x_white = (float)(white_x/100000.);
  195848. info_ptr->y_white = (float)(white_y/100000.);
  195849. info_ptr->x_red = (float)( red_x/100000.);
  195850. info_ptr->y_red = (float)( red_y/100000.);
  195851. info_ptr->x_green = (float)(green_x/100000.);
  195852. info_ptr->y_green = (float)(green_y/100000.);
  195853. info_ptr->x_blue = (float)( blue_x/100000.);
  195854. info_ptr->y_blue = (float)( blue_y/100000.);
  195855. #endif
  195856. info_ptr->valid |= PNG_INFO_cHRM;
  195857. }
  195858. #endif
  195859. #endif
  195860. #if defined(PNG_gAMA_SUPPORTED)
  195861. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195862. void PNGAPI
  195863. png_set_gAMA(png_structp png_ptr, png_infop info_ptr, double file_gamma)
  195864. {
  195865. double gamma;
  195866. png_debug1(1, "in %s storage function\n", "gAMA");
  195867. if (png_ptr == NULL || info_ptr == NULL)
  195868. return;
  195869. /* Check for overflow */
  195870. if (file_gamma > 21474.83)
  195871. {
  195872. png_warning(png_ptr, "Limiting gamma to 21474.83");
  195873. gamma=21474.83;
  195874. }
  195875. else
  195876. gamma=file_gamma;
  195877. info_ptr->gamma = (float)gamma;
  195878. #ifdef PNG_FIXED_POINT_SUPPORTED
  195879. info_ptr->int_gamma = (int)(gamma*100000.+.5);
  195880. #endif
  195881. info_ptr->valid |= PNG_INFO_gAMA;
  195882. if(gamma == 0.0)
  195883. png_warning(png_ptr, "Setting gamma=0");
  195884. }
  195885. #endif
  195886. void PNGAPI
  195887. png_set_gAMA_fixed(png_structp png_ptr, png_infop info_ptr, png_fixed_point
  195888. int_gamma)
  195889. {
  195890. png_fixed_point gamma;
  195891. png_debug1(1, "in %s storage function\n", "gAMA");
  195892. if (png_ptr == NULL || info_ptr == NULL)
  195893. return;
  195894. if (int_gamma > (png_fixed_point) PNG_UINT_31_MAX)
  195895. {
  195896. png_warning(png_ptr, "Limiting gamma to 21474.83");
  195897. gamma=PNG_UINT_31_MAX;
  195898. }
  195899. else
  195900. {
  195901. if (int_gamma < 0)
  195902. {
  195903. png_warning(png_ptr, "Setting negative gamma to zero");
  195904. gamma=0;
  195905. }
  195906. else
  195907. gamma=int_gamma;
  195908. }
  195909. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195910. info_ptr->gamma = (float)(gamma/100000.);
  195911. #endif
  195912. #ifdef PNG_FIXED_POINT_SUPPORTED
  195913. info_ptr->int_gamma = gamma;
  195914. #endif
  195915. info_ptr->valid |= PNG_INFO_gAMA;
  195916. if(gamma == 0)
  195917. png_warning(png_ptr, "Setting gamma=0");
  195918. }
  195919. #endif
  195920. #if defined(PNG_hIST_SUPPORTED)
  195921. void PNGAPI
  195922. png_set_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p hist)
  195923. {
  195924. int i;
  195925. png_debug1(1, "in %s storage function\n", "hIST");
  195926. if (png_ptr == NULL || info_ptr == NULL)
  195927. return;
  195928. if (info_ptr->num_palette == 0 || info_ptr->num_palette
  195929. > PNG_MAX_PALETTE_LENGTH)
  195930. {
  195931. png_warning(png_ptr,
  195932. "Invalid palette size, hIST allocation skipped.");
  195933. return;
  195934. }
  195935. #ifdef PNG_FREE_ME_SUPPORTED
  195936. png_free_data(png_ptr, info_ptr, PNG_FREE_HIST, 0);
  195937. #endif
  195938. /* Changed from info->num_palette to PNG_MAX_PALETTE_LENGTH in version
  195939. 1.2.1 */
  195940. png_ptr->hist = (png_uint_16p)png_malloc_warn(png_ptr,
  195941. (png_uint_32)(PNG_MAX_PALETTE_LENGTH * png_sizeof (png_uint_16)));
  195942. if (png_ptr->hist == NULL)
  195943. {
  195944. png_warning(png_ptr, "Insufficient memory for hIST chunk data.");
  195945. return;
  195946. }
  195947. for (i = 0; i < info_ptr->num_palette; i++)
  195948. png_ptr->hist[i] = hist[i];
  195949. info_ptr->hist = png_ptr->hist;
  195950. info_ptr->valid |= PNG_INFO_hIST;
  195951. #ifdef PNG_FREE_ME_SUPPORTED
  195952. info_ptr->free_me |= PNG_FREE_HIST;
  195953. #else
  195954. png_ptr->flags |= PNG_FLAG_FREE_HIST;
  195955. #endif
  195956. }
  195957. #endif
  195958. void PNGAPI
  195959. png_set_IHDR(png_structp png_ptr, png_infop info_ptr,
  195960. png_uint_32 width, png_uint_32 height, int bit_depth,
  195961. int color_type, int interlace_type, int compression_type,
  195962. int filter_type)
  195963. {
  195964. png_debug1(1, "in %s storage function\n", "IHDR");
  195965. if (png_ptr == NULL || info_ptr == NULL)
  195966. return;
  195967. /* check for width and height valid values */
  195968. if (width == 0 || height == 0)
  195969. png_error(png_ptr, "Image width or height is zero in IHDR");
  195970. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  195971. if (width > png_ptr->user_width_max || height > png_ptr->user_height_max)
  195972. png_error(png_ptr, "image size exceeds user limits in IHDR");
  195973. #else
  195974. if (width > PNG_USER_WIDTH_MAX || height > PNG_USER_HEIGHT_MAX)
  195975. png_error(png_ptr, "image size exceeds user limits in IHDR");
  195976. #endif
  195977. if (width > PNG_UINT_31_MAX || height > PNG_UINT_31_MAX)
  195978. png_error(png_ptr, "Invalid image size in IHDR");
  195979. if ( width > (PNG_UINT_32_MAX
  195980. >> 3) /* 8-byte RGBA pixels */
  195981. - 64 /* bigrowbuf hack */
  195982. - 1 /* filter byte */
  195983. - 7*8 /* rounding of width to multiple of 8 pixels */
  195984. - 8) /* extra max_pixel_depth pad */
  195985. png_warning(png_ptr, "Width is too large for libpng to process pixels");
  195986. /* check other values */
  195987. if (bit_depth != 1 && bit_depth != 2 && bit_depth != 4 &&
  195988. bit_depth != 8 && bit_depth != 16)
  195989. png_error(png_ptr, "Invalid bit depth in IHDR");
  195990. if (color_type < 0 || color_type == 1 ||
  195991. color_type == 5 || color_type > 6)
  195992. png_error(png_ptr, "Invalid color type in IHDR");
  195993. if (((color_type == PNG_COLOR_TYPE_PALETTE) && bit_depth > 8) ||
  195994. ((color_type == PNG_COLOR_TYPE_RGB ||
  195995. color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||
  195996. color_type == PNG_COLOR_TYPE_RGB_ALPHA) && bit_depth < 8))
  195997. png_error(png_ptr, "Invalid color type/bit depth combination in IHDR");
  195998. if (interlace_type >= PNG_INTERLACE_LAST)
  195999. png_error(png_ptr, "Unknown interlace method in IHDR");
  196000. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  196001. png_error(png_ptr, "Unknown compression method in IHDR");
  196002. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  196003. /* Accept filter_method 64 (intrapixel differencing) only if
  196004. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  196005. * 2. Libpng did not read a PNG signature (this filter_method is only
  196006. * used in PNG datastreams that are embedded in MNG datastreams) and
  196007. * 3. The application called png_permit_mng_features with a mask that
  196008. * included PNG_FLAG_MNG_FILTER_64 and
  196009. * 4. The filter_method is 64 and
  196010. * 5. The color_type is RGB or RGBA
  196011. */
  196012. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&png_ptr->mng_features_permitted)
  196013. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  196014. if(filter_type != PNG_FILTER_TYPE_BASE)
  196015. {
  196016. if(!((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  196017. (filter_type == PNG_INTRAPIXEL_DIFFERENCING) &&
  196018. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  196019. (color_type == PNG_COLOR_TYPE_RGB ||
  196020. color_type == PNG_COLOR_TYPE_RGB_ALPHA)))
  196021. png_error(png_ptr, "Unknown filter method in IHDR");
  196022. if(png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)
  196023. png_warning(png_ptr, "Invalid filter method in IHDR");
  196024. }
  196025. #else
  196026. if(filter_type != PNG_FILTER_TYPE_BASE)
  196027. png_error(png_ptr, "Unknown filter method in IHDR");
  196028. #endif
  196029. info_ptr->width = width;
  196030. info_ptr->height = height;
  196031. info_ptr->bit_depth = (png_byte)bit_depth;
  196032. info_ptr->color_type =(png_byte) color_type;
  196033. info_ptr->compression_type = (png_byte)compression_type;
  196034. info_ptr->filter_type = (png_byte)filter_type;
  196035. info_ptr->interlace_type = (png_byte)interlace_type;
  196036. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196037. info_ptr->channels = 1;
  196038. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  196039. info_ptr->channels = 3;
  196040. else
  196041. info_ptr->channels = 1;
  196042. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  196043. info_ptr->channels++;
  196044. info_ptr->pixel_depth = (png_byte)(info_ptr->channels * info_ptr->bit_depth);
  196045. /* check for potential overflow */
  196046. if (width > (PNG_UINT_32_MAX
  196047. >> 3) /* 8-byte RGBA pixels */
  196048. - 64 /* bigrowbuf hack */
  196049. - 1 /* filter byte */
  196050. - 7*8 /* rounding of width to multiple of 8 pixels */
  196051. - 8) /* extra max_pixel_depth pad */
  196052. info_ptr->rowbytes = (png_size_t)0;
  196053. else
  196054. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,width);
  196055. }
  196056. #if defined(PNG_oFFs_SUPPORTED)
  196057. void PNGAPI
  196058. png_set_oFFs(png_structp png_ptr, png_infop info_ptr,
  196059. png_int_32 offset_x, png_int_32 offset_y, int unit_type)
  196060. {
  196061. png_debug1(1, "in %s storage function\n", "oFFs");
  196062. if (png_ptr == NULL || info_ptr == NULL)
  196063. return;
  196064. info_ptr->x_offset = offset_x;
  196065. info_ptr->y_offset = offset_y;
  196066. info_ptr->offset_unit_type = (png_byte)unit_type;
  196067. info_ptr->valid |= PNG_INFO_oFFs;
  196068. }
  196069. #endif
  196070. #if defined(PNG_pCAL_SUPPORTED)
  196071. void PNGAPI
  196072. png_set_pCAL(png_structp png_ptr, png_infop info_ptr,
  196073. png_charp purpose, png_int_32 X0, png_int_32 X1, int type, int nparams,
  196074. png_charp units, png_charpp params)
  196075. {
  196076. png_uint_32 length;
  196077. int i;
  196078. png_debug1(1, "in %s storage function\n", "pCAL");
  196079. if (png_ptr == NULL || info_ptr == NULL)
  196080. return;
  196081. length = png_strlen(purpose) + 1;
  196082. png_debug1(3, "allocating purpose for info (%lu bytes)\n", length);
  196083. info_ptr->pcal_purpose = (png_charp)png_malloc_warn(png_ptr, length);
  196084. if (info_ptr->pcal_purpose == NULL)
  196085. {
  196086. png_warning(png_ptr, "Insufficient memory for pCAL purpose.");
  196087. return;
  196088. }
  196089. png_memcpy(info_ptr->pcal_purpose, purpose, (png_size_t)length);
  196090. png_debug(3, "storing X0, X1, type, and nparams in info\n");
  196091. info_ptr->pcal_X0 = X0;
  196092. info_ptr->pcal_X1 = X1;
  196093. info_ptr->pcal_type = (png_byte)type;
  196094. info_ptr->pcal_nparams = (png_byte)nparams;
  196095. length = png_strlen(units) + 1;
  196096. png_debug1(3, "allocating units for info (%lu bytes)\n", length);
  196097. info_ptr->pcal_units = (png_charp)png_malloc_warn(png_ptr, length);
  196098. if (info_ptr->pcal_units == NULL)
  196099. {
  196100. png_warning(png_ptr, "Insufficient memory for pCAL units.");
  196101. return;
  196102. }
  196103. png_memcpy(info_ptr->pcal_units, units, (png_size_t)length);
  196104. info_ptr->pcal_params = (png_charpp)png_malloc_warn(png_ptr,
  196105. (png_uint_32)((nparams + 1) * png_sizeof(png_charp)));
  196106. if (info_ptr->pcal_params == NULL)
  196107. {
  196108. png_warning(png_ptr, "Insufficient memory for pCAL params.");
  196109. return;
  196110. }
  196111. info_ptr->pcal_params[nparams] = NULL;
  196112. for (i = 0; i < nparams; i++)
  196113. {
  196114. length = png_strlen(params[i]) + 1;
  196115. png_debug2(3, "allocating parameter %d for info (%lu bytes)\n", i, length);
  196116. info_ptr->pcal_params[i] = (png_charp)png_malloc_warn(png_ptr, length);
  196117. if (info_ptr->pcal_params[i] == NULL)
  196118. {
  196119. png_warning(png_ptr, "Insufficient memory for pCAL parameter.");
  196120. return;
  196121. }
  196122. png_memcpy(info_ptr->pcal_params[i], params[i], (png_size_t)length);
  196123. }
  196124. info_ptr->valid |= PNG_INFO_pCAL;
  196125. #ifdef PNG_FREE_ME_SUPPORTED
  196126. info_ptr->free_me |= PNG_FREE_PCAL;
  196127. #endif
  196128. }
  196129. #endif
  196130. #if defined(PNG_READ_sCAL_SUPPORTED) || defined(PNG_WRITE_sCAL_SUPPORTED)
  196131. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196132. void PNGAPI
  196133. png_set_sCAL(png_structp png_ptr, png_infop info_ptr,
  196134. int unit, double width, double height)
  196135. {
  196136. png_debug1(1, "in %s storage function\n", "sCAL");
  196137. if (png_ptr == NULL || info_ptr == NULL)
  196138. return;
  196139. info_ptr->scal_unit = (png_byte)unit;
  196140. info_ptr->scal_pixel_width = width;
  196141. info_ptr->scal_pixel_height = height;
  196142. info_ptr->valid |= PNG_INFO_sCAL;
  196143. }
  196144. #else
  196145. #ifdef PNG_FIXED_POINT_SUPPORTED
  196146. void PNGAPI
  196147. png_set_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  196148. int unit, png_charp swidth, png_charp sheight)
  196149. {
  196150. png_uint_32 length;
  196151. png_debug1(1, "in %s storage function\n", "sCAL");
  196152. if (png_ptr == NULL || info_ptr == NULL)
  196153. return;
  196154. info_ptr->scal_unit = (png_byte)unit;
  196155. length = png_strlen(swidth) + 1;
  196156. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  196157. info_ptr->scal_s_width = (png_charp)png_malloc_warn(png_ptr, length);
  196158. if (info_ptr->scal_s_width == NULL)
  196159. {
  196160. png_warning(png_ptr,
  196161. "Memory allocation failed while processing sCAL.");
  196162. }
  196163. png_memcpy(info_ptr->scal_s_width, swidth, (png_size_t)length);
  196164. length = png_strlen(sheight) + 1;
  196165. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  196166. info_ptr->scal_s_height = (png_charp)png_malloc_warn(png_ptr, length);
  196167. if (info_ptr->scal_s_height == NULL)
  196168. {
  196169. png_free (png_ptr, info_ptr->scal_s_width);
  196170. png_warning(png_ptr,
  196171. "Memory allocation failed while processing sCAL.");
  196172. }
  196173. png_memcpy(info_ptr->scal_s_height, sheight, (png_size_t)length);
  196174. info_ptr->valid |= PNG_INFO_sCAL;
  196175. #ifdef PNG_FREE_ME_SUPPORTED
  196176. info_ptr->free_me |= PNG_FREE_SCAL;
  196177. #endif
  196178. }
  196179. #endif
  196180. #endif
  196181. #endif
  196182. #if defined(PNG_pHYs_SUPPORTED)
  196183. void PNGAPI
  196184. png_set_pHYs(png_structp png_ptr, png_infop info_ptr,
  196185. png_uint_32 res_x, png_uint_32 res_y, int unit_type)
  196186. {
  196187. png_debug1(1, "in %s storage function\n", "pHYs");
  196188. if (png_ptr == NULL || info_ptr == NULL)
  196189. return;
  196190. info_ptr->x_pixels_per_unit = res_x;
  196191. info_ptr->y_pixels_per_unit = res_y;
  196192. info_ptr->phys_unit_type = (png_byte)unit_type;
  196193. info_ptr->valid |= PNG_INFO_pHYs;
  196194. }
  196195. #endif
  196196. void PNGAPI
  196197. png_set_PLTE(png_structp png_ptr, png_infop info_ptr,
  196198. png_colorp palette, int num_palette)
  196199. {
  196200. png_debug1(1, "in %s storage function\n", "PLTE");
  196201. if (png_ptr == NULL || info_ptr == NULL)
  196202. return;
  196203. if (num_palette < 0 || num_palette > PNG_MAX_PALETTE_LENGTH)
  196204. {
  196205. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196206. png_error(png_ptr, "Invalid palette length");
  196207. else
  196208. {
  196209. png_warning(png_ptr, "Invalid palette length");
  196210. return;
  196211. }
  196212. }
  196213. /*
  196214. * It may not actually be necessary to set png_ptr->palette here;
  196215. * we do it for backward compatibility with the way the png_handle_tRNS
  196216. * function used to do the allocation.
  196217. */
  196218. #ifdef PNG_FREE_ME_SUPPORTED
  196219. png_free_data(png_ptr, info_ptr, PNG_FREE_PLTE, 0);
  196220. #endif
  196221. /* Changed in libpng-1.2.1 to allocate PNG_MAX_PALETTE_LENGTH instead
  196222. of num_palette entries,
  196223. in case of an invalid PNG file that has too-large sample values. */
  196224. png_ptr->palette = (png_colorp)png_malloc(png_ptr,
  196225. PNG_MAX_PALETTE_LENGTH * png_sizeof(png_color));
  196226. png_memset(png_ptr->palette, 0, PNG_MAX_PALETTE_LENGTH *
  196227. png_sizeof(png_color));
  196228. png_memcpy(png_ptr->palette, palette, num_palette * png_sizeof (png_color));
  196229. info_ptr->palette = png_ptr->palette;
  196230. info_ptr->num_palette = png_ptr->num_palette = (png_uint_16)num_palette;
  196231. #ifdef PNG_FREE_ME_SUPPORTED
  196232. info_ptr->free_me |= PNG_FREE_PLTE;
  196233. #else
  196234. png_ptr->flags |= PNG_FLAG_FREE_PLTE;
  196235. #endif
  196236. info_ptr->valid |= PNG_INFO_PLTE;
  196237. }
  196238. #if defined(PNG_sBIT_SUPPORTED)
  196239. void PNGAPI
  196240. png_set_sBIT(png_structp png_ptr, png_infop info_ptr,
  196241. png_color_8p sig_bit)
  196242. {
  196243. png_debug1(1, "in %s storage function\n", "sBIT");
  196244. if (png_ptr == NULL || info_ptr == NULL)
  196245. return;
  196246. png_memcpy(&(info_ptr->sig_bit), sig_bit, png_sizeof (png_color_8));
  196247. info_ptr->valid |= PNG_INFO_sBIT;
  196248. }
  196249. #endif
  196250. #if defined(PNG_sRGB_SUPPORTED)
  196251. void PNGAPI
  196252. png_set_sRGB(png_structp png_ptr, png_infop info_ptr, int intent)
  196253. {
  196254. png_debug1(1, "in %s storage function\n", "sRGB");
  196255. if (png_ptr == NULL || info_ptr == NULL)
  196256. return;
  196257. info_ptr->srgb_intent = (png_byte)intent;
  196258. info_ptr->valid |= PNG_INFO_sRGB;
  196259. }
  196260. void PNGAPI
  196261. png_set_sRGB_gAMA_and_cHRM(png_structp png_ptr, png_infop info_ptr,
  196262. int intent)
  196263. {
  196264. #if defined(PNG_gAMA_SUPPORTED)
  196265. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196266. float file_gamma;
  196267. #endif
  196268. #ifdef PNG_FIXED_POINT_SUPPORTED
  196269. png_fixed_point int_file_gamma;
  196270. #endif
  196271. #endif
  196272. #if defined(PNG_cHRM_SUPPORTED)
  196273. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196274. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  196275. #endif
  196276. #ifdef PNG_FIXED_POINT_SUPPORTED
  196277. png_fixed_point int_white_x, int_white_y, int_red_x, int_red_y, int_green_x,
  196278. int_green_y, int_blue_x, int_blue_y;
  196279. #endif
  196280. #endif
  196281. png_debug1(1, "in %s storage function\n", "sRGB_gAMA_and_cHRM");
  196282. if (png_ptr == NULL || info_ptr == NULL)
  196283. return;
  196284. png_set_sRGB(png_ptr, info_ptr, intent);
  196285. #if defined(PNG_gAMA_SUPPORTED)
  196286. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196287. file_gamma = (float).45455;
  196288. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  196289. #endif
  196290. #ifdef PNG_FIXED_POINT_SUPPORTED
  196291. int_file_gamma = 45455L;
  196292. png_set_gAMA_fixed(png_ptr, info_ptr, int_file_gamma);
  196293. #endif
  196294. #endif
  196295. #if defined(PNG_cHRM_SUPPORTED)
  196296. #ifdef PNG_FIXED_POINT_SUPPORTED
  196297. int_white_x = 31270L;
  196298. int_white_y = 32900L;
  196299. int_red_x = 64000L;
  196300. int_red_y = 33000L;
  196301. int_green_x = 30000L;
  196302. int_green_y = 60000L;
  196303. int_blue_x = 15000L;
  196304. int_blue_y = 6000L;
  196305. png_set_cHRM_fixed(png_ptr, info_ptr,
  196306. int_white_x, int_white_y, int_red_x, int_red_y, int_green_x, int_green_y,
  196307. int_blue_x, int_blue_y);
  196308. #endif
  196309. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196310. white_x = (float).3127;
  196311. white_y = (float).3290;
  196312. red_x = (float).64;
  196313. red_y = (float).33;
  196314. green_x = (float).30;
  196315. green_y = (float).60;
  196316. blue_x = (float).15;
  196317. blue_y = (float).06;
  196318. png_set_cHRM(png_ptr, info_ptr,
  196319. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  196320. #endif
  196321. #endif
  196322. }
  196323. #endif
  196324. #if defined(PNG_iCCP_SUPPORTED)
  196325. void PNGAPI
  196326. png_set_iCCP(png_structp png_ptr, png_infop info_ptr,
  196327. png_charp name, int compression_type,
  196328. png_charp profile, png_uint_32 proflen)
  196329. {
  196330. png_charp new_iccp_name;
  196331. png_charp new_iccp_profile;
  196332. png_debug1(1, "in %s storage function\n", "iCCP");
  196333. if (png_ptr == NULL || info_ptr == NULL || name == NULL || profile == NULL)
  196334. return;
  196335. new_iccp_name = (png_charp)png_malloc_warn(png_ptr, png_strlen(name)+1);
  196336. if (new_iccp_name == NULL)
  196337. {
  196338. png_warning(png_ptr, "Insufficient memory to process iCCP chunk.");
  196339. return;
  196340. }
  196341. png_strncpy(new_iccp_name, name, png_strlen(name)+1);
  196342. new_iccp_profile = (png_charp)png_malloc_warn(png_ptr, proflen);
  196343. if (new_iccp_profile == NULL)
  196344. {
  196345. png_free (png_ptr, new_iccp_name);
  196346. png_warning(png_ptr, "Insufficient memory to process iCCP profile.");
  196347. return;
  196348. }
  196349. png_memcpy(new_iccp_profile, profile, (png_size_t)proflen);
  196350. png_free_data(png_ptr, info_ptr, PNG_FREE_ICCP, 0);
  196351. info_ptr->iccp_proflen = proflen;
  196352. info_ptr->iccp_name = new_iccp_name;
  196353. info_ptr->iccp_profile = new_iccp_profile;
  196354. /* Compression is always zero but is here so the API and info structure
  196355. * does not have to change if we introduce multiple compression types */
  196356. info_ptr->iccp_compression = (png_byte)compression_type;
  196357. #ifdef PNG_FREE_ME_SUPPORTED
  196358. info_ptr->free_me |= PNG_FREE_ICCP;
  196359. #endif
  196360. info_ptr->valid |= PNG_INFO_iCCP;
  196361. }
  196362. #endif
  196363. #if defined(PNG_TEXT_SUPPORTED)
  196364. void PNGAPI
  196365. png_set_text(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  196366. int num_text)
  196367. {
  196368. int ret;
  196369. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, num_text);
  196370. if (ret)
  196371. png_error(png_ptr, "Insufficient memory to store text");
  196372. }
  196373. int /* PRIVATE */
  196374. png_set_text_2(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  196375. int num_text)
  196376. {
  196377. int i;
  196378. png_debug1(1, "in %s storage function\n", (png_ptr->chunk_name[0] == '\0' ?
  196379. "text" : (png_const_charp)png_ptr->chunk_name));
  196380. if (png_ptr == NULL || info_ptr == NULL || num_text == 0)
  196381. return(0);
  196382. /* Make sure we have enough space in the "text" array in info_struct
  196383. * to hold all of the incoming text_ptr objects.
  196384. */
  196385. if (info_ptr->num_text + num_text > info_ptr->max_text)
  196386. {
  196387. if (info_ptr->text != NULL)
  196388. {
  196389. png_textp old_text;
  196390. int old_max;
  196391. old_max = info_ptr->max_text;
  196392. info_ptr->max_text = info_ptr->num_text + num_text + 8;
  196393. old_text = info_ptr->text;
  196394. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  196395. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  196396. if (info_ptr->text == NULL)
  196397. {
  196398. png_free(png_ptr, old_text);
  196399. return(1);
  196400. }
  196401. png_memcpy(info_ptr->text, old_text, (png_size_t)(old_max *
  196402. png_sizeof(png_text)));
  196403. png_free(png_ptr, old_text);
  196404. }
  196405. else
  196406. {
  196407. info_ptr->max_text = num_text + 8;
  196408. info_ptr->num_text = 0;
  196409. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  196410. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  196411. if (info_ptr->text == NULL)
  196412. return(1);
  196413. #ifdef PNG_FREE_ME_SUPPORTED
  196414. info_ptr->free_me |= PNG_FREE_TEXT;
  196415. #endif
  196416. }
  196417. png_debug1(3, "allocated %d entries for info_ptr->text\n",
  196418. info_ptr->max_text);
  196419. }
  196420. for (i = 0; i < num_text; i++)
  196421. {
  196422. png_size_t text_length,key_len;
  196423. png_size_t lang_len,lang_key_len;
  196424. png_textp textp = &(info_ptr->text[info_ptr->num_text]);
  196425. if (text_ptr[i].key == NULL)
  196426. continue;
  196427. key_len = png_strlen(text_ptr[i].key);
  196428. if(text_ptr[i].compression <= 0)
  196429. {
  196430. lang_len = 0;
  196431. lang_key_len = 0;
  196432. }
  196433. else
  196434. #ifdef PNG_iTXt_SUPPORTED
  196435. {
  196436. /* set iTXt data */
  196437. if (text_ptr[i].lang != NULL)
  196438. lang_len = png_strlen(text_ptr[i].lang);
  196439. else
  196440. lang_len = 0;
  196441. if (text_ptr[i].lang_key != NULL)
  196442. lang_key_len = png_strlen(text_ptr[i].lang_key);
  196443. else
  196444. lang_key_len = 0;
  196445. }
  196446. #else
  196447. {
  196448. png_warning(png_ptr, "iTXt chunk not supported.");
  196449. continue;
  196450. }
  196451. #endif
  196452. if (text_ptr[i].text == NULL || text_ptr[i].text[0] == '\0')
  196453. {
  196454. text_length = 0;
  196455. #ifdef PNG_iTXt_SUPPORTED
  196456. if(text_ptr[i].compression > 0)
  196457. textp->compression = PNG_ITXT_COMPRESSION_NONE;
  196458. else
  196459. #endif
  196460. textp->compression = PNG_TEXT_COMPRESSION_NONE;
  196461. }
  196462. else
  196463. {
  196464. text_length = png_strlen(text_ptr[i].text);
  196465. textp->compression = text_ptr[i].compression;
  196466. }
  196467. textp->key = (png_charp)png_malloc_warn(png_ptr,
  196468. (png_uint_32)(key_len + text_length + lang_len + lang_key_len + 4));
  196469. if (textp->key == NULL)
  196470. return(1);
  196471. png_debug2(2, "Allocated %lu bytes at %x in png_set_text\n",
  196472. (png_uint_32)(key_len + lang_len + lang_key_len + text_length + 4),
  196473. (int)textp->key);
  196474. png_memcpy(textp->key, text_ptr[i].key,
  196475. (png_size_t)(key_len));
  196476. *(textp->key+key_len) = '\0';
  196477. #ifdef PNG_iTXt_SUPPORTED
  196478. if (text_ptr[i].compression > 0)
  196479. {
  196480. textp->lang=textp->key + key_len + 1;
  196481. png_memcpy(textp->lang, text_ptr[i].lang, lang_len);
  196482. *(textp->lang+lang_len) = '\0';
  196483. textp->lang_key=textp->lang + lang_len + 1;
  196484. png_memcpy(textp->lang_key, text_ptr[i].lang_key, lang_key_len);
  196485. *(textp->lang_key+lang_key_len) = '\0';
  196486. textp->text=textp->lang_key + lang_key_len + 1;
  196487. }
  196488. else
  196489. #endif
  196490. {
  196491. #ifdef PNG_iTXt_SUPPORTED
  196492. textp->lang=NULL;
  196493. textp->lang_key=NULL;
  196494. #endif
  196495. textp->text=textp->key + key_len + 1;
  196496. }
  196497. if(text_length)
  196498. png_memcpy(textp->text, text_ptr[i].text,
  196499. (png_size_t)(text_length));
  196500. *(textp->text+text_length) = '\0';
  196501. #ifdef PNG_iTXt_SUPPORTED
  196502. if(textp->compression > 0)
  196503. {
  196504. textp->text_length = 0;
  196505. textp->itxt_length = text_length;
  196506. }
  196507. else
  196508. #endif
  196509. {
  196510. textp->text_length = text_length;
  196511. #ifdef PNG_iTXt_SUPPORTED
  196512. textp->itxt_length = 0;
  196513. #endif
  196514. }
  196515. info_ptr->num_text++;
  196516. png_debug1(3, "transferred text chunk %d\n", info_ptr->num_text);
  196517. }
  196518. return(0);
  196519. }
  196520. #endif
  196521. #if defined(PNG_tIME_SUPPORTED)
  196522. void PNGAPI
  196523. png_set_tIME(png_structp png_ptr, png_infop info_ptr, png_timep mod_time)
  196524. {
  196525. png_debug1(1, "in %s storage function\n", "tIME");
  196526. if (png_ptr == NULL || info_ptr == NULL ||
  196527. (png_ptr->mode & PNG_WROTE_tIME))
  196528. return;
  196529. png_memcpy(&(info_ptr->mod_time), mod_time, png_sizeof (png_time));
  196530. info_ptr->valid |= PNG_INFO_tIME;
  196531. }
  196532. #endif
  196533. #if defined(PNG_tRNS_SUPPORTED)
  196534. void PNGAPI
  196535. png_set_tRNS(png_structp png_ptr, png_infop info_ptr,
  196536. png_bytep trans, int num_trans, png_color_16p trans_values)
  196537. {
  196538. png_debug1(1, "in %s storage function\n", "tRNS");
  196539. if (png_ptr == NULL || info_ptr == NULL)
  196540. return;
  196541. if (trans != NULL)
  196542. {
  196543. /*
  196544. * It may not actually be necessary to set png_ptr->trans here;
  196545. * we do it for backward compatibility with the way the png_handle_tRNS
  196546. * function used to do the allocation.
  196547. */
  196548. #ifdef PNG_FREE_ME_SUPPORTED
  196549. png_free_data(png_ptr, info_ptr, PNG_FREE_TRNS, 0);
  196550. #endif
  196551. /* Changed from num_trans to PNG_MAX_PALETTE_LENGTH in version 1.2.1 */
  196552. png_ptr->trans = info_ptr->trans = (png_bytep)png_malloc(png_ptr,
  196553. (png_uint_32)PNG_MAX_PALETTE_LENGTH);
  196554. if (num_trans <= PNG_MAX_PALETTE_LENGTH)
  196555. png_memcpy(info_ptr->trans, trans, (png_size_t)num_trans);
  196556. #ifdef PNG_FREE_ME_SUPPORTED
  196557. info_ptr->free_me |= PNG_FREE_TRNS;
  196558. #else
  196559. png_ptr->flags |= PNG_FLAG_FREE_TRNS;
  196560. #endif
  196561. }
  196562. if (trans_values != NULL)
  196563. {
  196564. png_memcpy(&(info_ptr->trans_values), trans_values,
  196565. png_sizeof(png_color_16));
  196566. if (num_trans == 0)
  196567. num_trans = 1;
  196568. }
  196569. info_ptr->num_trans = (png_uint_16)num_trans;
  196570. info_ptr->valid |= PNG_INFO_tRNS;
  196571. }
  196572. #endif
  196573. #if defined(PNG_sPLT_SUPPORTED)
  196574. void PNGAPI
  196575. png_set_sPLT(png_structp png_ptr,
  196576. png_infop info_ptr, png_sPLT_tp entries, int nentries)
  196577. {
  196578. png_sPLT_tp np;
  196579. int i;
  196580. if (png_ptr == NULL || info_ptr == NULL)
  196581. return;
  196582. np = (png_sPLT_tp)png_malloc_warn(png_ptr,
  196583. (info_ptr->splt_palettes_num + nentries) * png_sizeof(png_sPLT_t));
  196584. if (np == NULL)
  196585. {
  196586. png_warning(png_ptr, "No memory for sPLT palettes.");
  196587. return;
  196588. }
  196589. png_memcpy(np, info_ptr->splt_palettes,
  196590. info_ptr->splt_palettes_num * png_sizeof(png_sPLT_t));
  196591. png_free(png_ptr, info_ptr->splt_palettes);
  196592. info_ptr->splt_palettes=NULL;
  196593. for (i = 0; i < nentries; i++)
  196594. {
  196595. png_sPLT_tp to = np + info_ptr->splt_palettes_num + i;
  196596. png_sPLT_tp from = entries + i;
  196597. to->name = (png_charp)png_malloc_warn(png_ptr,
  196598. png_strlen(from->name) + 1);
  196599. if (to->name == NULL)
  196600. {
  196601. png_warning(png_ptr,
  196602. "Out of memory while processing sPLT chunk");
  196603. }
  196604. /* TODO: use png_malloc_warn */
  196605. png_strncpy(to->name, from->name, png_strlen(from->name)+1);
  196606. to->entries = (png_sPLT_entryp)png_malloc_warn(png_ptr,
  196607. from->nentries * png_sizeof(png_sPLT_entry));
  196608. /* TODO: use png_malloc_warn */
  196609. png_memcpy(to->entries, from->entries,
  196610. from->nentries * png_sizeof(png_sPLT_entry));
  196611. if (to->entries == NULL)
  196612. {
  196613. png_warning(png_ptr,
  196614. "Out of memory while processing sPLT chunk");
  196615. png_free(png_ptr,to->name);
  196616. to->name = NULL;
  196617. }
  196618. to->nentries = from->nentries;
  196619. to->depth = from->depth;
  196620. }
  196621. info_ptr->splt_palettes = np;
  196622. info_ptr->splt_palettes_num += nentries;
  196623. info_ptr->valid |= PNG_INFO_sPLT;
  196624. #ifdef PNG_FREE_ME_SUPPORTED
  196625. info_ptr->free_me |= PNG_FREE_SPLT;
  196626. #endif
  196627. }
  196628. #endif /* PNG_sPLT_SUPPORTED */
  196629. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  196630. void PNGAPI
  196631. png_set_unknown_chunks(png_structp png_ptr,
  196632. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns)
  196633. {
  196634. png_unknown_chunkp np;
  196635. int i;
  196636. if (png_ptr == NULL || info_ptr == NULL || num_unknowns == 0)
  196637. return;
  196638. np = (png_unknown_chunkp)png_malloc_warn(png_ptr,
  196639. (info_ptr->unknown_chunks_num + num_unknowns) *
  196640. png_sizeof(png_unknown_chunk));
  196641. if (np == NULL)
  196642. {
  196643. png_warning(png_ptr,
  196644. "Out of memory while processing unknown chunk.");
  196645. return;
  196646. }
  196647. png_memcpy(np, info_ptr->unknown_chunks,
  196648. info_ptr->unknown_chunks_num * png_sizeof(png_unknown_chunk));
  196649. png_free(png_ptr, info_ptr->unknown_chunks);
  196650. info_ptr->unknown_chunks=NULL;
  196651. for (i = 0; i < num_unknowns; i++)
  196652. {
  196653. png_unknown_chunkp to = np + info_ptr->unknown_chunks_num + i;
  196654. png_unknown_chunkp from = unknowns + i;
  196655. png_strncpy((png_charp)to->name, (png_charp)from->name, 5);
  196656. to->data = (png_bytep)png_malloc_warn(png_ptr, from->size);
  196657. if (to->data == NULL)
  196658. {
  196659. png_warning(png_ptr,
  196660. "Out of memory while processing unknown chunk.");
  196661. }
  196662. else
  196663. {
  196664. png_memcpy(to->data, from->data, from->size);
  196665. to->size = from->size;
  196666. /* note our location in the read or write sequence */
  196667. to->location = (png_byte)(png_ptr->mode & 0xff);
  196668. }
  196669. }
  196670. info_ptr->unknown_chunks = np;
  196671. info_ptr->unknown_chunks_num += num_unknowns;
  196672. #ifdef PNG_FREE_ME_SUPPORTED
  196673. info_ptr->free_me |= PNG_FREE_UNKN;
  196674. #endif
  196675. }
  196676. void PNGAPI
  196677. png_set_unknown_chunk_location(png_structp png_ptr, png_infop info_ptr,
  196678. int chunk, int location)
  196679. {
  196680. if(png_ptr != NULL && info_ptr != NULL && chunk >= 0 && chunk <
  196681. (int)info_ptr->unknown_chunks_num)
  196682. info_ptr->unknown_chunks[chunk].location = (png_byte)location;
  196683. }
  196684. #endif
  196685. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  196686. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  196687. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  196688. void PNGAPI
  196689. png_permit_empty_plte (png_structp png_ptr, int empty_plte_permitted)
  196690. {
  196691. /* This function is deprecated in favor of png_permit_mng_features()
  196692. and will be removed from libpng-1.3.0 */
  196693. png_debug(1, "in png_permit_empty_plte, DEPRECATED.\n");
  196694. if (png_ptr == NULL)
  196695. return;
  196696. png_ptr->mng_features_permitted = (png_byte)
  196697. ((png_ptr->mng_features_permitted & (~(PNG_FLAG_MNG_EMPTY_PLTE))) |
  196698. ((empty_plte_permitted & PNG_FLAG_MNG_EMPTY_PLTE)));
  196699. }
  196700. #endif
  196701. #endif
  196702. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  196703. png_uint_32 PNGAPI
  196704. png_permit_mng_features (png_structp png_ptr, png_uint_32 mng_features)
  196705. {
  196706. png_debug(1, "in png_permit_mng_features\n");
  196707. if (png_ptr == NULL)
  196708. return (png_uint_32)0;
  196709. png_ptr->mng_features_permitted =
  196710. (png_byte)(mng_features & PNG_ALL_MNG_FEATURES);
  196711. return (png_uint_32)png_ptr->mng_features_permitted;
  196712. }
  196713. #endif
  196714. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  196715. void PNGAPI
  196716. png_set_keep_unknown_chunks(png_structp png_ptr, int keep, png_bytep
  196717. chunk_list, int num_chunks)
  196718. {
  196719. png_bytep new_list, p;
  196720. int i, old_num_chunks;
  196721. if (png_ptr == NULL)
  196722. return;
  196723. if (num_chunks == 0)
  196724. {
  196725. if(keep == PNG_HANDLE_CHUNK_ALWAYS || keep == PNG_HANDLE_CHUNK_IF_SAFE)
  196726. png_ptr->flags |= PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  196727. else
  196728. png_ptr->flags &= ~PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  196729. if(keep == PNG_HANDLE_CHUNK_ALWAYS)
  196730. png_ptr->flags |= PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  196731. else
  196732. png_ptr->flags &= ~PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  196733. return;
  196734. }
  196735. if (chunk_list == NULL)
  196736. return;
  196737. old_num_chunks=png_ptr->num_chunk_list;
  196738. new_list=(png_bytep)png_malloc(png_ptr,
  196739. (png_uint_32)(5*(num_chunks+old_num_chunks)));
  196740. if(png_ptr->chunk_list != NULL)
  196741. {
  196742. png_memcpy(new_list, png_ptr->chunk_list,
  196743. (png_size_t)(5*old_num_chunks));
  196744. png_free(png_ptr, png_ptr->chunk_list);
  196745. png_ptr->chunk_list=NULL;
  196746. }
  196747. png_memcpy(new_list+5*old_num_chunks, chunk_list,
  196748. (png_size_t)(5*num_chunks));
  196749. for (p=new_list+5*old_num_chunks+4, i=0; i<num_chunks; i++, p+=5)
  196750. *p=(png_byte)keep;
  196751. png_ptr->num_chunk_list=old_num_chunks+num_chunks;
  196752. png_ptr->chunk_list=new_list;
  196753. #ifdef PNG_FREE_ME_SUPPORTED
  196754. png_ptr->free_me |= PNG_FREE_LIST;
  196755. #endif
  196756. }
  196757. #endif
  196758. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  196759. void PNGAPI
  196760. png_set_read_user_chunk_fn(png_structp png_ptr, png_voidp user_chunk_ptr,
  196761. png_user_chunk_ptr read_user_chunk_fn)
  196762. {
  196763. png_debug(1, "in png_set_read_user_chunk_fn\n");
  196764. if (png_ptr == NULL)
  196765. return;
  196766. png_ptr->read_user_chunk_fn = read_user_chunk_fn;
  196767. png_ptr->user_chunk_ptr = user_chunk_ptr;
  196768. }
  196769. #endif
  196770. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  196771. void PNGAPI
  196772. png_set_rows(png_structp png_ptr, png_infop info_ptr, png_bytepp row_pointers)
  196773. {
  196774. png_debug1(1, "in %s storage function\n", "rows");
  196775. if (png_ptr == NULL || info_ptr == NULL)
  196776. return;
  196777. if(info_ptr->row_pointers && (info_ptr->row_pointers != row_pointers))
  196778. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  196779. info_ptr->row_pointers = row_pointers;
  196780. if(row_pointers)
  196781. info_ptr->valid |= PNG_INFO_IDAT;
  196782. }
  196783. #endif
  196784. #ifdef PNG_WRITE_SUPPORTED
  196785. void PNGAPI
  196786. png_set_compression_buffer_size(png_structp png_ptr, png_uint_32 size)
  196787. {
  196788. if (png_ptr == NULL)
  196789. return;
  196790. if(png_ptr->zbuf)
  196791. png_free(png_ptr, png_ptr->zbuf);
  196792. png_ptr->zbuf_size = (png_size_t)size;
  196793. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr, size);
  196794. png_ptr->zstream.next_out = png_ptr->zbuf;
  196795. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  196796. }
  196797. #endif
  196798. void PNGAPI
  196799. png_set_invalid(png_structp png_ptr, png_infop info_ptr, int mask)
  196800. {
  196801. if (png_ptr && info_ptr)
  196802. info_ptr->valid &= ~(mask);
  196803. }
  196804. #ifndef PNG_1_0_X
  196805. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  196806. /* function was added to libpng 1.2.0 and should always exist by default */
  196807. void PNGAPI
  196808. png_set_asm_flags (png_structp png_ptr, png_uint_32)
  196809. {
  196810. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  196811. if (png_ptr != NULL)
  196812. png_ptr->asm_flags = 0;
  196813. }
  196814. /* this function was added to libpng 1.2.0 */
  196815. void PNGAPI
  196816. png_set_mmx_thresholds (png_structp png_ptr,
  196817. png_byte,
  196818. png_uint_32)
  196819. {
  196820. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  196821. if (png_ptr == NULL)
  196822. return;
  196823. }
  196824. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  196825. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  196826. /* this function was added to libpng 1.2.6 */
  196827. void PNGAPI
  196828. png_set_user_limits (png_structp png_ptr, png_uint_32 user_width_max,
  196829. png_uint_32 user_height_max)
  196830. {
  196831. /* Images with dimensions larger than these limits will be
  196832. * rejected by png_set_IHDR(). To accept any PNG datastream
  196833. * regardless of dimensions, set both limits to 0x7ffffffL.
  196834. */
  196835. if(png_ptr == NULL) return;
  196836. png_ptr->user_width_max = user_width_max;
  196837. png_ptr->user_height_max = user_height_max;
  196838. }
  196839. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  196840. #endif /* ?PNG_1_0_X */
  196841. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  196842. /*** End of inlined file: pngset.c ***/
  196843. /*** Start of inlined file: pngtrans.c ***/
  196844. /* pngtrans.c - transforms the data in a row (used by both readers and writers)
  196845. *
  196846. * Last changed in libpng 1.2.17 May 15, 2007
  196847. * For conditions of distribution and use, see copyright notice in png.h
  196848. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  196849. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  196850. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  196851. */
  196852. #define PNG_INTERNAL
  196853. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  196854. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  196855. /* turn on BGR-to-RGB mapping */
  196856. void PNGAPI
  196857. png_set_bgr(png_structp png_ptr)
  196858. {
  196859. png_debug(1, "in png_set_bgr\n");
  196860. if(png_ptr == NULL) return;
  196861. png_ptr->transformations |= PNG_BGR;
  196862. }
  196863. #endif
  196864. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  196865. /* turn on 16 bit byte swapping */
  196866. void PNGAPI
  196867. png_set_swap(png_structp png_ptr)
  196868. {
  196869. png_debug(1, "in png_set_swap\n");
  196870. if(png_ptr == NULL) return;
  196871. if (png_ptr->bit_depth == 16)
  196872. png_ptr->transformations |= PNG_SWAP_BYTES;
  196873. }
  196874. #endif
  196875. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  196876. /* turn on pixel packing */
  196877. void PNGAPI
  196878. png_set_packing(png_structp png_ptr)
  196879. {
  196880. png_debug(1, "in png_set_packing\n");
  196881. if(png_ptr == NULL) return;
  196882. if (png_ptr->bit_depth < 8)
  196883. {
  196884. png_ptr->transformations |= PNG_PACK;
  196885. png_ptr->usr_bit_depth = 8;
  196886. }
  196887. }
  196888. #endif
  196889. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  196890. /* turn on packed pixel swapping */
  196891. void PNGAPI
  196892. png_set_packswap(png_structp png_ptr)
  196893. {
  196894. png_debug(1, "in png_set_packswap\n");
  196895. if(png_ptr == NULL) return;
  196896. if (png_ptr->bit_depth < 8)
  196897. png_ptr->transformations |= PNG_PACKSWAP;
  196898. }
  196899. #endif
  196900. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  196901. void PNGAPI
  196902. png_set_shift(png_structp png_ptr, png_color_8p true_bits)
  196903. {
  196904. png_debug(1, "in png_set_shift\n");
  196905. if(png_ptr == NULL) return;
  196906. png_ptr->transformations |= PNG_SHIFT;
  196907. png_ptr->shift = *true_bits;
  196908. }
  196909. #endif
  196910. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  196911. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  196912. int PNGAPI
  196913. png_set_interlace_handling(png_structp png_ptr)
  196914. {
  196915. png_debug(1, "in png_set_interlace handling\n");
  196916. if (png_ptr && png_ptr->interlaced)
  196917. {
  196918. png_ptr->transformations |= PNG_INTERLACE;
  196919. return (7);
  196920. }
  196921. return (1);
  196922. }
  196923. #endif
  196924. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  196925. /* Add a filler byte on read, or remove a filler or alpha byte on write.
  196926. * The filler type has changed in v0.95 to allow future 2-byte fillers
  196927. * for 48-bit input data, as well as to avoid problems with some compilers
  196928. * that don't like bytes as parameters.
  196929. */
  196930. void PNGAPI
  196931. png_set_filler(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  196932. {
  196933. png_debug(1, "in png_set_filler\n");
  196934. if(png_ptr == NULL) return;
  196935. png_ptr->transformations |= PNG_FILLER;
  196936. png_ptr->filler = (png_byte)filler;
  196937. if (filler_loc == PNG_FILLER_AFTER)
  196938. png_ptr->flags |= PNG_FLAG_FILLER_AFTER;
  196939. else
  196940. png_ptr->flags &= ~PNG_FLAG_FILLER_AFTER;
  196941. /* This should probably go in the "do_read_filler" routine.
  196942. * I attempted to do that in libpng-1.0.1a but that caused problems
  196943. * so I restored it in libpng-1.0.2a
  196944. */
  196945. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  196946. {
  196947. png_ptr->usr_channels = 4;
  196948. }
  196949. /* Also I added this in libpng-1.0.2a (what happens when we expand
  196950. * a less-than-8-bit grayscale to GA? */
  196951. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY && png_ptr->bit_depth >= 8)
  196952. {
  196953. png_ptr->usr_channels = 2;
  196954. }
  196955. }
  196956. #if !defined(PNG_1_0_X)
  196957. /* Added to libpng-1.2.7 */
  196958. void PNGAPI
  196959. png_set_add_alpha(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  196960. {
  196961. png_debug(1, "in png_set_add_alpha\n");
  196962. if(png_ptr == NULL) return;
  196963. png_set_filler(png_ptr, filler, filler_loc);
  196964. png_ptr->transformations |= PNG_ADD_ALPHA;
  196965. }
  196966. #endif
  196967. #endif
  196968. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  196969. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  196970. void PNGAPI
  196971. png_set_swap_alpha(png_structp png_ptr)
  196972. {
  196973. png_debug(1, "in png_set_swap_alpha\n");
  196974. if(png_ptr == NULL) return;
  196975. png_ptr->transformations |= PNG_SWAP_ALPHA;
  196976. }
  196977. #endif
  196978. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  196979. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  196980. void PNGAPI
  196981. png_set_invert_alpha(png_structp png_ptr)
  196982. {
  196983. png_debug(1, "in png_set_invert_alpha\n");
  196984. if(png_ptr == NULL) return;
  196985. png_ptr->transformations |= PNG_INVERT_ALPHA;
  196986. }
  196987. #endif
  196988. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  196989. void PNGAPI
  196990. png_set_invert_mono(png_structp png_ptr)
  196991. {
  196992. png_debug(1, "in png_set_invert_mono\n");
  196993. if(png_ptr == NULL) return;
  196994. png_ptr->transformations |= PNG_INVERT_MONO;
  196995. }
  196996. /* invert monochrome grayscale data */
  196997. void /* PRIVATE */
  196998. png_do_invert(png_row_infop row_info, png_bytep row)
  196999. {
  197000. png_debug(1, "in png_do_invert\n");
  197001. /* This test removed from libpng version 1.0.13 and 1.2.0:
  197002. * if (row_info->bit_depth == 1 &&
  197003. */
  197004. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197005. if (row == NULL || row_info == NULL)
  197006. return;
  197007. #endif
  197008. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  197009. {
  197010. png_bytep rp = row;
  197011. png_uint_32 i;
  197012. png_uint_32 istop = row_info->rowbytes;
  197013. for (i = 0; i < istop; i++)
  197014. {
  197015. *rp = (png_byte)(~(*rp));
  197016. rp++;
  197017. }
  197018. }
  197019. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  197020. row_info->bit_depth == 8)
  197021. {
  197022. png_bytep rp = row;
  197023. png_uint_32 i;
  197024. png_uint_32 istop = row_info->rowbytes;
  197025. for (i = 0; i < istop; i+=2)
  197026. {
  197027. *rp = (png_byte)(~(*rp));
  197028. rp+=2;
  197029. }
  197030. }
  197031. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  197032. row_info->bit_depth == 16)
  197033. {
  197034. png_bytep rp = row;
  197035. png_uint_32 i;
  197036. png_uint_32 istop = row_info->rowbytes;
  197037. for (i = 0; i < istop; i+=4)
  197038. {
  197039. *rp = (png_byte)(~(*rp));
  197040. *(rp+1) = (png_byte)(~(*(rp+1)));
  197041. rp+=4;
  197042. }
  197043. }
  197044. }
  197045. #endif
  197046. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  197047. /* swaps byte order on 16 bit depth images */
  197048. void /* PRIVATE */
  197049. png_do_swap(png_row_infop row_info, png_bytep row)
  197050. {
  197051. png_debug(1, "in png_do_swap\n");
  197052. if (
  197053. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197054. row != NULL && row_info != NULL &&
  197055. #endif
  197056. row_info->bit_depth == 16)
  197057. {
  197058. png_bytep rp = row;
  197059. png_uint_32 i;
  197060. png_uint_32 istop= row_info->width * row_info->channels;
  197061. for (i = 0; i < istop; i++, rp += 2)
  197062. {
  197063. png_byte t = *rp;
  197064. *rp = *(rp + 1);
  197065. *(rp + 1) = t;
  197066. }
  197067. }
  197068. }
  197069. #endif
  197070. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  197071. static PNG_CONST png_byte onebppswaptable[256] = {
  197072. 0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0,
  197073. 0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0,
  197074. 0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8,
  197075. 0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8,
  197076. 0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4,
  197077. 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4,
  197078. 0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC,
  197079. 0x1C, 0x9C, 0x5C, 0xDC, 0x3C, 0xBC, 0x7C, 0xFC,
  197080. 0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2,
  197081. 0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2,
  197082. 0x0A, 0x8A, 0x4A, 0xCA, 0x2A, 0xAA, 0x6A, 0xEA,
  197083. 0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA,
  197084. 0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6,
  197085. 0x16, 0x96, 0x56, 0xD6, 0x36, 0xB6, 0x76, 0xF6,
  197086. 0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE,
  197087. 0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE,
  197088. 0x01, 0x81, 0x41, 0xC1, 0x21, 0xA1, 0x61, 0xE1,
  197089. 0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1,
  197090. 0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9,
  197091. 0x19, 0x99, 0x59, 0xD9, 0x39, 0xB9, 0x79, 0xF9,
  197092. 0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5,
  197093. 0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5,
  197094. 0x0D, 0x8D, 0x4D, 0xCD, 0x2D, 0xAD, 0x6D, 0xED,
  197095. 0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD,
  197096. 0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3,
  197097. 0x13, 0x93, 0x53, 0xD3, 0x33, 0xB3, 0x73, 0xF3,
  197098. 0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB,
  197099. 0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB,
  197100. 0x07, 0x87, 0x47, 0xC7, 0x27, 0xA7, 0x67, 0xE7,
  197101. 0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7,
  197102. 0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF,
  197103. 0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F, 0xFF
  197104. };
  197105. static PNG_CONST png_byte twobppswaptable[256] = {
  197106. 0x00, 0x40, 0x80, 0xC0, 0x10, 0x50, 0x90, 0xD0,
  197107. 0x20, 0x60, 0xA0, 0xE0, 0x30, 0x70, 0xB0, 0xF0,
  197108. 0x04, 0x44, 0x84, 0xC4, 0x14, 0x54, 0x94, 0xD4,
  197109. 0x24, 0x64, 0xA4, 0xE4, 0x34, 0x74, 0xB4, 0xF4,
  197110. 0x08, 0x48, 0x88, 0xC8, 0x18, 0x58, 0x98, 0xD8,
  197111. 0x28, 0x68, 0xA8, 0xE8, 0x38, 0x78, 0xB8, 0xF8,
  197112. 0x0C, 0x4C, 0x8C, 0xCC, 0x1C, 0x5C, 0x9C, 0xDC,
  197113. 0x2C, 0x6C, 0xAC, 0xEC, 0x3C, 0x7C, 0xBC, 0xFC,
  197114. 0x01, 0x41, 0x81, 0xC1, 0x11, 0x51, 0x91, 0xD1,
  197115. 0x21, 0x61, 0xA1, 0xE1, 0x31, 0x71, 0xB1, 0xF1,
  197116. 0x05, 0x45, 0x85, 0xC5, 0x15, 0x55, 0x95, 0xD5,
  197117. 0x25, 0x65, 0xA5, 0xE5, 0x35, 0x75, 0xB5, 0xF5,
  197118. 0x09, 0x49, 0x89, 0xC9, 0x19, 0x59, 0x99, 0xD9,
  197119. 0x29, 0x69, 0xA9, 0xE9, 0x39, 0x79, 0xB9, 0xF9,
  197120. 0x0D, 0x4D, 0x8D, 0xCD, 0x1D, 0x5D, 0x9D, 0xDD,
  197121. 0x2D, 0x6D, 0xAD, 0xED, 0x3D, 0x7D, 0xBD, 0xFD,
  197122. 0x02, 0x42, 0x82, 0xC2, 0x12, 0x52, 0x92, 0xD2,
  197123. 0x22, 0x62, 0xA2, 0xE2, 0x32, 0x72, 0xB2, 0xF2,
  197124. 0x06, 0x46, 0x86, 0xC6, 0x16, 0x56, 0x96, 0xD6,
  197125. 0x26, 0x66, 0xA6, 0xE6, 0x36, 0x76, 0xB6, 0xF6,
  197126. 0x0A, 0x4A, 0x8A, 0xCA, 0x1A, 0x5A, 0x9A, 0xDA,
  197127. 0x2A, 0x6A, 0xAA, 0xEA, 0x3A, 0x7A, 0xBA, 0xFA,
  197128. 0x0E, 0x4E, 0x8E, 0xCE, 0x1E, 0x5E, 0x9E, 0xDE,
  197129. 0x2E, 0x6E, 0xAE, 0xEE, 0x3E, 0x7E, 0xBE, 0xFE,
  197130. 0x03, 0x43, 0x83, 0xC3, 0x13, 0x53, 0x93, 0xD3,
  197131. 0x23, 0x63, 0xA3, 0xE3, 0x33, 0x73, 0xB3, 0xF3,
  197132. 0x07, 0x47, 0x87, 0xC7, 0x17, 0x57, 0x97, 0xD7,
  197133. 0x27, 0x67, 0xA7, 0xE7, 0x37, 0x77, 0xB7, 0xF7,
  197134. 0x0B, 0x4B, 0x8B, 0xCB, 0x1B, 0x5B, 0x9B, 0xDB,
  197135. 0x2B, 0x6B, 0xAB, 0xEB, 0x3B, 0x7B, 0xBB, 0xFB,
  197136. 0x0F, 0x4F, 0x8F, 0xCF, 0x1F, 0x5F, 0x9F, 0xDF,
  197137. 0x2F, 0x6F, 0xAF, 0xEF, 0x3F, 0x7F, 0xBF, 0xFF
  197138. };
  197139. static PNG_CONST png_byte fourbppswaptable[256] = {
  197140. 0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70,
  197141. 0x80, 0x90, 0xA0, 0xB0, 0xC0, 0xD0, 0xE0, 0xF0,
  197142. 0x01, 0x11, 0x21, 0x31, 0x41, 0x51, 0x61, 0x71,
  197143. 0x81, 0x91, 0xA1, 0xB1, 0xC1, 0xD1, 0xE1, 0xF1,
  197144. 0x02, 0x12, 0x22, 0x32, 0x42, 0x52, 0x62, 0x72,
  197145. 0x82, 0x92, 0xA2, 0xB2, 0xC2, 0xD2, 0xE2, 0xF2,
  197146. 0x03, 0x13, 0x23, 0x33, 0x43, 0x53, 0x63, 0x73,
  197147. 0x83, 0x93, 0xA3, 0xB3, 0xC3, 0xD3, 0xE3, 0xF3,
  197148. 0x04, 0x14, 0x24, 0x34, 0x44, 0x54, 0x64, 0x74,
  197149. 0x84, 0x94, 0xA4, 0xB4, 0xC4, 0xD4, 0xE4, 0xF4,
  197150. 0x05, 0x15, 0x25, 0x35, 0x45, 0x55, 0x65, 0x75,
  197151. 0x85, 0x95, 0xA5, 0xB5, 0xC5, 0xD5, 0xE5, 0xF5,
  197152. 0x06, 0x16, 0x26, 0x36, 0x46, 0x56, 0x66, 0x76,
  197153. 0x86, 0x96, 0xA6, 0xB6, 0xC6, 0xD6, 0xE6, 0xF6,
  197154. 0x07, 0x17, 0x27, 0x37, 0x47, 0x57, 0x67, 0x77,
  197155. 0x87, 0x97, 0xA7, 0xB7, 0xC7, 0xD7, 0xE7, 0xF7,
  197156. 0x08, 0x18, 0x28, 0x38, 0x48, 0x58, 0x68, 0x78,
  197157. 0x88, 0x98, 0xA8, 0xB8, 0xC8, 0xD8, 0xE8, 0xF8,
  197158. 0x09, 0x19, 0x29, 0x39, 0x49, 0x59, 0x69, 0x79,
  197159. 0x89, 0x99, 0xA9, 0xB9, 0xC9, 0xD9, 0xE9, 0xF9,
  197160. 0x0A, 0x1A, 0x2A, 0x3A, 0x4A, 0x5A, 0x6A, 0x7A,
  197161. 0x8A, 0x9A, 0xAA, 0xBA, 0xCA, 0xDA, 0xEA, 0xFA,
  197162. 0x0B, 0x1B, 0x2B, 0x3B, 0x4B, 0x5B, 0x6B, 0x7B,
  197163. 0x8B, 0x9B, 0xAB, 0xBB, 0xCB, 0xDB, 0xEB, 0xFB,
  197164. 0x0C, 0x1C, 0x2C, 0x3C, 0x4C, 0x5C, 0x6C, 0x7C,
  197165. 0x8C, 0x9C, 0xAC, 0xBC, 0xCC, 0xDC, 0xEC, 0xFC,
  197166. 0x0D, 0x1D, 0x2D, 0x3D, 0x4D, 0x5D, 0x6D, 0x7D,
  197167. 0x8D, 0x9D, 0xAD, 0xBD, 0xCD, 0xDD, 0xED, 0xFD,
  197168. 0x0E, 0x1E, 0x2E, 0x3E, 0x4E, 0x5E, 0x6E, 0x7E,
  197169. 0x8E, 0x9E, 0xAE, 0xBE, 0xCE, 0xDE, 0xEE, 0xFE,
  197170. 0x0F, 0x1F, 0x2F, 0x3F, 0x4F, 0x5F, 0x6F, 0x7F,
  197171. 0x8F, 0x9F, 0xAF, 0xBF, 0xCF, 0xDF, 0xEF, 0xFF
  197172. };
  197173. /* swaps pixel packing order within bytes */
  197174. void /* PRIVATE */
  197175. png_do_packswap(png_row_infop row_info, png_bytep row)
  197176. {
  197177. png_debug(1, "in png_do_packswap\n");
  197178. if (
  197179. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197180. row != NULL && row_info != NULL &&
  197181. #endif
  197182. row_info->bit_depth < 8)
  197183. {
  197184. png_bytep rp, end, table;
  197185. end = row + row_info->rowbytes;
  197186. if (row_info->bit_depth == 1)
  197187. table = (png_bytep)onebppswaptable;
  197188. else if (row_info->bit_depth == 2)
  197189. table = (png_bytep)twobppswaptable;
  197190. else if (row_info->bit_depth == 4)
  197191. table = (png_bytep)fourbppswaptable;
  197192. else
  197193. return;
  197194. for (rp = row; rp < end; rp++)
  197195. *rp = table[*rp];
  197196. }
  197197. }
  197198. #endif /* PNG_READ_PACKSWAP_SUPPORTED or PNG_WRITE_PACKSWAP_SUPPORTED */
  197199. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  197200. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  197201. /* remove filler or alpha byte(s) */
  197202. void /* PRIVATE */
  197203. png_do_strip_filler(png_row_infop row_info, png_bytep row, png_uint_32 flags)
  197204. {
  197205. png_debug(1, "in png_do_strip_filler\n");
  197206. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197207. if (row != NULL && row_info != NULL)
  197208. #endif
  197209. {
  197210. png_bytep sp=row;
  197211. png_bytep dp=row;
  197212. png_uint_32 row_width=row_info->width;
  197213. png_uint_32 i;
  197214. if ((row_info->color_type == PNG_COLOR_TYPE_RGB ||
  197215. (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  197216. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  197217. row_info->channels == 4)
  197218. {
  197219. if (row_info->bit_depth == 8)
  197220. {
  197221. /* This converts from RGBX or RGBA to RGB */
  197222. if (flags & PNG_FLAG_FILLER_AFTER)
  197223. {
  197224. dp+=3; sp+=4;
  197225. for (i = 1; i < row_width; i++)
  197226. {
  197227. *dp++ = *sp++;
  197228. *dp++ = *sp++;
  197229. *dp++ = *sp++;
  197230. sp++;
  197231. }
  197232. }
  197233. /* This converts from XRGB or ARGB to RGB */
  197234. else
  197235. {
  197236. for (i = 0; i < row_width; i++)
  197237. {
  197238. sp++;
  197239. *dp++ = *sp++;
  197240. *dp++ = *sp++;
  197241. *dp++ = *sp++;
  197242. }
  197243. }
  197244. row_info->pixel_depth = 24;
  197245. row_info->rowbytes = row_width * 3;
  197246. }
  197247. else /* if (row_info->bit_depth == 16) */
  197248. {
  197249. if (flags & PNG_FLAG_FILLER_AFTER)
  197250. {
  197251. /* This converts from RRGGBBXX or RRGGBBAA to RRGGBB */
  197252. sp += 8; dp += 6;
  197253. for (i = 1; i < row_width; i++)
  197254. {
  197255. /* This could be (although png_memcpy is probably slower):
  197256. png_memcpy(dp, sp, 6);
  197257. sp += 8;
  197258. dp += 6;
  197259. */
  197260. *dp++ = *sp++;
  197261. *dp++ = *sp++;
  197262. *dp++ = *sp++;
  197263. *dp++ = *sp++;
  197264. *dp++ = *sp++;
  197265. *dp++ = *sp++;
  197266. sp += 2;
  197267. }
  197268. }
  197269. else
  197270. {
  197271. /* This converts from XXRRGGBB or AARRGGBB to RRGGBB */
  197272. for (i = 0; i < row_width; i++)
  197273. {
  197274. /* This could be (although png_memcpy is probably slower):
  197275. png_memcpy(dp, sp, 6);
  197276. sp += 8;
  197277. dp += 6;
  197278. */
  197279. sp+=2;
  197280. *dp++ = *sp++;
  197281. *dp++ = *sp++;
  197282. *dp++ = *sp++;
  197283. *dp++ = *sp++;
  197284. *dp++ = *sp++;
  197285. *dp++ = *sp++;
  197286. }
  197287. }
  197288. row_info->pixel_depth = 48;
  197289. row_info->rowbytes = row_width * 6;
  197290. }
  197291. row_info->channels = 3;
  197292. }
  197293. else if ((row_info->color_type == PNG_COLOR_TYPE_GRAY ||
  197294. (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  197295. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  197296. row_info->channels == 2)
  197297. {
  197298. if (row_info->bit_depth == 8)
  197299. {
  197300. /* This converts from GX or GA to G */
  197301. if (flags & PNG_FLAG_FILLER_AFTER)
  197302. {
  197303. for (i = 0; i < row_width; i++)
  197304. {
  197305. *dp++ = *sp++;
  197306. sp++;
  197307. }
  197308. }
  197309. /* This converts from XG or AG to G */
  197310. else
  197311. {
  197312. for (i = 0; i < row_width; i++)
  197313. {
  197314. sp++;
  197315. *dp++ = *sp++;
  197316. }
  197317. }
  197318. row_info->pixel_depth = 8;
  197319. row_info->rowbytes = row_width;
  197320. }
  197321. else /* if (row_info->bit_depth == 16) */
  197322. {
  197323. if (flags & PNG_FLAG_FILLER_AFTER)
  197324. {
  197325. /* This converts from GGXX or GGAA to GG */
  197326. sp += 4; dp += 2;
  197327. for (i = 1; i < row_width; i++)
  197328. {
  197329. *dp++ = *sp++;
  197330. *dp++ = *sp++;
  197331. sp += 2;
  197332. }
  197333. }
  197334. else
  197335. {
  197336. /* This converts from XXGG or AAGG to GG */
  197337. for (i = 0; i < row_width; i++)
  197338. {
  197339. sp += 2;
  197340. *dp++ = *sp++;
  197341. *dp++ = *sp++;
  197342. }
  197343. }
  197344. row_info->pixel_depth = 16;
  197345. row_info->rowbytes = row_width * 2;
  197346. }
  197347. row_info->channels = 1;
  197348. }
  197349. if (flags & PNG_FLAG_STRIP_ALPHA)
  197350. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  197351. }
  197352. }
  197353. #endif
  197354. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  197355. /* swaps red and blue bytes within a pixel */
  197356. void /* PRIVATE */
  197357. png_do_bgr(png_row_infop row_info, png_bytep row)
  197358. {
  197359. png_debug(1, "in png_do_bgr\n");
  197360. if (
  197361. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197362. row != NULL && row_info != NULL &&
  197363. #endif
  197364. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  197365. {
  197366. png_uint_32 row_width = row_info->width;
  197367. if (row_info->bit_depth == 8)
  197368. {
  197369. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  197370. {
  197371. png_bytep rp;
  197372. png_uint_32 i;
  197373. for (i = 0, rp = row; i < row_width; i++, rp += 3)
  197374. {
  197375. png_byte save = *rp;
  197376. *rp = *(rp + 2);
  197377. *(rp + 2) = save;
  197378. }
  197379. }
  197380. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  197381. {
  197382. png_bytep rp;
  197383. png_uint_32 i;
  197384. for (i = 0, rp = row; i < row_width; i++, rp += 4)
  197385. {
  197386. png_byte save = *rp;
  197387. *rp = *(rp + 2);
  197388. *(rp + 2) = save;
  197389. }
  197390. }
  197391. }
  197392. else if (row_info->bit_depth == 16)
  197393. {
  197394. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  197395. {
  197396. png_bytep rp;
  197397. png_uint_32 i;
  197398. for (i = 0, rp = row; i < row_width; i++, rp += 6)
  197399. {
  197400. png_byte save = *rp;
  197401. *rp = *(rp + 4);
  197402. *(rp + 4) = save;
  197403. save = *(rp + 1);
  197404. *(rp + 1) = *(rp + 5);
  197405. *(rp + 5) = save;
  197406. }
  197407. }
  197408. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  197409. {
  197410. png_bytep rp;
  197411. png_uint_32 i;
  197412. for (i = 0, rp = row; i < row_width; i++, rp += 8)
  197413. {
  197414. png_byte save = *rp;
  197415. *rp = *(rp + 4);
  197416. *(rp + 4) = save;
  197417. save = *(rp + 1);
  197418. *(rp + 1) = *(rp + 5);
  197419. *(rp + 5) = save;
  197420. }
  197421. }
  197422. }
  197423. }
  197424. }
  197425. #endif /* PNG_READ_BGR_SUPPORTED or PNG_WRITE_BGR_SUPPORTED */
  197426. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  197427. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  197428. defined(PNG_LEGACY_SUPPORTED)
  197429. void PNGAPI
  197430. png_set_user_transform_info(png_structp png_ptr, png_voidp
  197431. user_transform_ptr, int user_transform_depth, int user_transform_channels)
  197432. {
  197433. png_debug(1, "in png_set_user_transform_info\n");
  197434. if(png_ptr == NULL) return;
  197435. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  197436. png_ptr->user_transform_ptr = user_transform_ptr;
  197437. png_ptr->user_transform_depth = (png_byte)user_transform_depth;
  197438. png_ptr->user_transform_channels = (png_byte)user_transform_channels;
  197439. #else
  197440. if(user_transform_ptr || user_transform_depth || user_transform_channels)
  197441. png_warning(png_ptr,
  197442. "This version of libpng does not support user transform info");
  197443. #endif
  197444. }
  197445. #endif
  197446. /* This function returns a pointer to the user_transform_ptr associated with
  197447. * the user transform functions. The application should free any memory
  197448. * associated with this pointer before png_write_destroy and png_read_destroy
  197449. * are called.
  197450. */
  197451. png_voidp PNGAPI
  197452. png_get_user_transform_ptr(png_structp png_ptr)
  197453. {
  197454. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  197455. if (png_ptr == NULL) return (NULL);
  197456. return ((png_voidp)png_ptr->user_transform_ptr);
  197457. #else
  197458. return (NULL);
  197459. #endif
  197460. }
  197461. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  197462. /*** End of inlined file: pngtrans.c ***/
  197463. /*** Start of inlined file: pngwio.c ***/
  197464. /* pngwio.c - functions for data output
  197465. *
  197466. * Last changed in libpng 1.2.13 November 13, 2006
  197467. * For conditions of distribution and use, see copyright notice in png.h
  197468. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  197469. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  197470. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  197471. *
  197472. * This file provides a location for all output. Users who need
  197473. * special handling are expected to write functions that have the same
  197474. * arguments as these and perform similar functions, but that possibly
  197475. * use different output methods. Note that you shouldn't change these
  197476. * functions, but rather write replacement functions and then change
  197477. * them at run time with png_set_write_fn(...).
  197478. */
  197479. #define PNG_INTERNAL
  197480. #ifdef PNG_WRITE_SUPPORTED
  197481. /* Write the data to whatever output you are using. The default routine
  197482. writes to a file pointer. Note that this routine sometimes gets called
  197483. with very small lengths, so you should implement some kind of simple
  197484. buffering if you are using unbuffered writes. This should never be asked
  197485. to write more than 64K on a 16 bit machine. */
  197486. void /* PRIVATE */
  197487. png_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  197488. {
  197489. if (png_ptr->write_data_fn != NULL )
  197490. (*(png_ptr->write_data_fn))(png_ptr, data, length);
  197491. else
  197492. png_error(png_ptr, "Call to NULL write function");
  197493. }
  197494. #if !defined(PNG_NO_STDIO)
  197495. /* This is the function that does the actual writing of data. If you are
  197496. not writing to a standard C stream, you should create a replacement
  197497. write_data function and use it at run time with png_set_write_fn(), rather
  197498. than changing the library. */
  197499. #ifndef USE_FAR_KEYWORD
  197500. void PNGAPI
  197501. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  197502. {
  197503. png_uint_32 check;
  197504. if(png_ptr == NULL) return;
  197505. #if defined(_WIN32_WCE)
  197506. if ( !WriteFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  197507. check = 0;
  197508. #else
  197509. check = fwrite(data, 1, length, (png_FILE_p)(png_ptr->io_ptr));
  197510. #endif
  197511. if (check != length)
  197512. png_error(png_ptr, "Write Error");
  197513. }
  197514. #else
  197515. /* this is the model-independent version. Since the standard I/O library
  197516. can't handle far buffers in the medium and small models, we have to copy
  197517. the data.
  197518. */
  197519. #define NEAR_BUF_SIZE 1024
  197520. #define MIN(a,b) (a <= b ? a : b)
  197521. void PNGAPI
  197522. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  197523. {
  197524. png_uint_32 check;
  197525. png_byte *near_data; /* Needs to be "png_byte *" instead of "png_bytep" */
  197526. png_FILE_p io_ptr;
  197527. if(png_ptr == NULL) return;
  197528. /* Check if data really is near. If so, use usual code. */
  197529. near_data = (png_byte *)CVT_PTR_NOCHECK(data);
  197530. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  197531. if ((png_bytep)near_data == data)
  197532. {
  197533. #if defined(_WIN32_WCE)
  197534. if ( !WriteFile(io_ptr, near_data, length, &check, NULL) )
  197535. check = 0;
  197536. #else
  197537. check = fwrite(near_data, 1, length, io_ptr);
  197538. #endif
  197539. }
  197540. else
  197541. {
  197542. png_byte buf[NEAR_BUF_SIZE];
  197543. png_size_t written, remaining, err;
  197544. check = 0;
  197545. remaining = length;
  197546. do
  197547. {
  197548. written = MIN(NEAR_BUF_SIZE, remaining);
  197549. png_memcpy(buf, data, written); /* copy far buffer to near buffer */
  197550. #if defined(_WIN32_WCE)
  197551. if ( !WriteFile(io_ptr, buf, written, &err, NULL) )
  197552. err = 0;
  197553. #else
  197554. err = fwrite(buf, 1, written, io_ptr);
  197555. #endif
  197556. if (err != written)
  197557. break;
  197558. else
  197559. check += err;
  197560. data += written;
  197561. remaining -= written;
  197562. }
  197563. while (remaining != 0);
  197564. }
  197565. if (check != length)
  197566. png_error(png_ptr, "Write Error");
  197567. }
  197568. #endif
  197569. #endif
  197570. /* This function is called to output any data pending writing (normally
  197571. to disk). After png_flush is called, there should be no data pending
  197572. writing in any buffers. */
  197573. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  197574. void /* PRIVATE */
  197575. png_flush(png_structp png_ptr)
  197576. {
  197577. if (png_ptr->output_flush_fn != NULL)
  197578. (*(png_ptr->output_flush_fn))(png_ptr);
  197579. }
  197580. #if !defined(PNG_NO_STDIO)
  197581. void PNGAPI
  197582. png_default_flush(png_structp png_ptr)
  197583. {
  197584. #if !defined(_WIN32_WCE)
  197585. png_FILE_p io_ptr;
  197586. #endif
  197587. if(png_ptr == NULL) return;
  197588. #if !defined(_WIN32_WCE)
  197589. io_ptr = (png_FILE_p)CVT_PTR((png_ptr->io_ptr));
  197590. if (io_ptr != NULL)
  197591. fflush(io_ptr);
  197592. #endif
  197593. }
  197594. #endif
  197595. #endif
  197596. /* This function allows the application to supply new output functions for
  197597. libpng if standard C streams aren't being used.
  197598. This function takes as its arguments:
  197599. png_ptr - pointer to a png output data structure
  197600. io_ptr - pointer to user supplied structure containing info about
  197601. the output functions. May be NULL.
  197602. write_data_fn - pointer to a new output function that takes as its
  197603. arguments a pointer to a png_struct, a pointer to
  197604. data to be written, and a 32-bit unsigned int that is
  197605. the number of bytes to be written. The new write
  197606. function should call png_error(png_ptr, "Error msg")
  197607. to exit and output any fatal error messages.
  197608. flush_data_fn - pointer to a new flush function that takes as its
  197609. arguments a pointer to a png_struct. After a call to
  197610. the flush function, there should be no data in any buffers
  197611. or pending transmission. If the output method doesn't do
  197612. any buffering of ouput, a function prototype must still be
  197613. supplied although it doesn't have to do anything. If
  197614. PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile
  197615. time, output_flush_fn will be ignored, although it must be
  197616. supplied for compatibility. */
  197617. void PNGAPI
  197618. png_set_write_fn(png_structp png_ptr, png_voidp io_ptr,
  197619. png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn)
  197620. {
  197621. if(png_ptr == NULL) return;
  197622. png_ptr->io_ptr = io_ptr;
  197623. #if !defined(PNG_NO_STDIO)
  197624. if (write_data_fn != NULL)
  197625. png_ptr->write_data_fn = write_data_fn;
  197626. else
  197627. png_ptr->write_data_fn = png_default_write_data;
  197628. #else
  197629. png_ptr->write_data_fn = write_data_fn;
  197630. #endif
  197631. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  197632. #if !defined(PNG_NO_STDIO)
  197633. if (output_flush_fn != NULL)
  197634. png_ptr->output_flush_fn = output_flush_fn;
  197635. else
  197636. png_ptr->output_flush_fn = png_default_flush;
  197637. #else
  197638. png_ptr->output_flush_fn = output_flush_fn;
  197639. #endif
  197640. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  197641. /* It is an error to read while writing a png file */
  197642. if (png_ptr->read_data_fn != NULL)
  197643. {
  197644. png_ptr->read_data_fn = NULL;
  197645. png_warning(png_ptr,
  197646. "Attempted to set both read_data_fn and write_data_fn in");
  197647. png_warning(png_ptr,
  197648. "the same structure. Resetting read_data_fn to NULL.");
  197649. }
  197650. }
  197651. #if defined(USE_FAR_KEYWORD)
  197652. #if defined(_MSC_VER)
  197653. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  197654. {
  197655. void *near_ptr;
  197656. void FAR *far_ptr;
  197657. FP_OFF(near_ptr) = FP_OFF(ptr);
  197658. far_ptr = (void FAR *)near_ptr;
  197659. if(check != 0)
  197660. if(FP_SEG(ptr) != FP_SEG(far_ptr))
  197661. png_error(png_ptr,"segment lost in conversion");
  197662. return(near_ptr);
  197663. }
  197664. # else
  197665. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  197666. {
  197667. void *near_ptr;
  197668. void FAR *far_ptr;
  197669. near_ptr = (void FAR *)ptr;
  197670. far_ptr = (void FAR *)near_ptr;
  197671. if(check != 0)
  197672. if(far_ptr != ptr)
  197673. png_error(png_ptr,"segment lost in conversion");
  197674. return(near_ptr);
  197675. }
  197676. # endif
  197677. # endif
  197678. #endif /* PNG_WRITE_SUPPORTED */
  197679. /*** End of inlined file: pngwio.c ***/
  197680. /*** Start of inlined file: pngwrite.c ***/
  197681. /* pngwrite.c - general routines to write a PNG file
  197682. *
  197683. * Last changed in libpng 1.2.15 January 5, 2007
  197684. * For conditions of distribution and use, see copyright notice in png.h
  197685. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  197686. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  197687. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  197688. */
  197689. /* get internal access to png.h */
  197690. #define PNG_INTERNAL
  197691. #ifdef PNG_WRITE_SUPPORTED
  197692. /* Writes all the PNG information. This is the suggested way to use the
  197693. * library. If you have a new chunk to add, make a function to write it,
  197694. * and put it in the correct location here. If you want the chunk written
  197695. * after the image data, put it in png_write_end(). I strongly encourage
  197696. * you to supply a PNG_INFO_ flag, and check info_ptr->valid before writing
  197697. * the chunk, as that will keep the code from breaking if you want to just
  197698. * write a plain PNG file. If you have long comments, I suggest writing
  197699. * them in png_write_end(), and compressing them.
  197700. */
  197701. void PNGAPI
  197702. png_write_info_before_PLTE(png_structp png_ptr, png_infop info_ptr)
  197703. {
  197704. png_debug(1, "in png_write_info_before_PLTE\n");
  197705. if (png_ptr == NULL || info_ptr == NULL)
  197706. return;
  197707. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  197708. {
  197709. png_write_sig(png_ptr); /* write PNG signature */
  197710. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  197711. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&(png_ptr->mng_features_permitted))
  197712. {
  197713. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  197714. png_ptr->mng_features_permitted=0;
  197715. }
  197716. #endif
  197717. /* write IHDR information. */
  197718. png_write_IHDR(png_ptr, info_ptr->width, info_ptr->height,
  197719. info_ptr->bit_depth, info_ptr->color_type, info_ptr->compression_type,
  197720. info_ptr->filter_type,
  197721. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  197722. info_ptr->interlace_type);
  197723. #else
  197724. 0);
  197725. #endif
  197726. /* the rest of these check to see if the valid field has the appropriate
  197727. flag set, and if it does, writes the chunk. */
  197728. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  197729. if (info_ptr->valid & PNG_INFO_gAMA)
  197730. {
  197731. # ifdef PNG_FLOATING_POINT_SUPPORTED
  197732. png_write_gAMA(png_ptr, info_ptr->gamma);
  197733. #else
  197734. #ifdef PNG_FIXED_POINT_SUPPORTED
  197735. png_write_gAMA_fixed(png_ptr, info_ptr->int_gamma);
  197736. # endif
  197737. #endif
  197738. }
  197739. #endif
  197740. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  197741. if (info_ptr->valid & PNG_INFO_sRGB)
  197742. png_write_sRGB(png_ptr, (int)info_ptr->srgb_intent);
  197743. #endif
  197744. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  197745. if (info_ptr->valid & PNG_INFO_iCCP)
  197746. png_write_iCCP(png_ptr, info_ptr->iccp_name, PNG_COMPRESSION_TYPE_BASE,
  197747. info_ptr->iccp_profile, (int)info_ptr->iccp_proflen);
  197748. #endif
  197749. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  197750. if (info_ptr->valid & PNG_INFO_sBIT)
  197751. png_write_sBIT(png_ptr, &(info_ptr->sig_bit), info_ptr->color_type);
  197752. #endif
  197753. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  197754. if (info_ptr->valid & PNG_INFO_cHRM)
  197755. {
  197756. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197757. png_write_cHRM(png_ptr,
  197758. info_ptr->x_white, info_ptr->y_white,
  197759. info_ptr->x_red, info_ptr->y_red,
  197760. info_ptr->x_green, info_ptr->y_green,
  197761. info_ptr->x_blue, info_ptr->y_blue);
  197762. #else
  197763. # ifdef PNG_FIXED_POINT_SUPPORTED
  197764. png_write_cHRM_fixed(png_ptr,
  197765. info_ptr->int_x_white, info_ptr->int_y_white,
  197766. info_ptr->int_x_red, info_ptr->int_y_red,
  197767. info_ptr->int_x_green, info_ptr->int_y_green,
  197768. info_ptr->int_x_blue, info_ptr->int_y_blue);
  197769. # endif
  197770. #endif
  197771. }
  197772. #endif
  197773. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  197774. if (info_ptr->unknown_chunks_num)
  197775. {
  197776. png_unknown_chunk *up;
  197777. png_debug(5, "writing extra chunks\n");
  197778. for (up = info_ptr->unknown_chunks;
  197779. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  197780. up++)
  197781. {
  197782. int keep=png_handle_as_unknown(png_ptr, up->name);
  197783. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  197784. up->location && !(up->location & PNG_HAVE_PLTE) &&
  197785. !(up->location & PNG_HAVE_IDAT) &&
  197786. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  197787. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  197788. {
  197789. png_write_chunk(png_ptr, up->name, up->data, up->size);
  197790. }
  197791. }
  197792. }
  197793. #endif
  197794. png_ptr->mode |= PNG_WROTE_INFO_BEFORE_PLTE;
  197795. }
  197796. }
  197797. void PNGAPI
  197798. png_write_info(png_structp png_ptr, png_infop info_ptr)
  197799. {
  197800. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  197801. int i;
  197802. #endif
  197803. png_debug(1, "in png_write_info\n");
  197804. if (png_ptr == NULL || info_ptr == NULL)
  197805. return;
  197806. png_write_info_before_PLTE(png_ptr, info_ptr);
  197807. if (info_ptr->valid & PNG_INFO_PLTE)
  197808. png_write_PLTE(png_ptr, info_ptr->palette,
  197809. (png_uint_32)info_ptr->num_palette);
  197810. else if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  197811. png_error(png_ptr, "Valid palette required for paletted images");
  197812. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  197813. if (info_ptr->valid & PNG_INFO_tRNS)
  197814. {
  197815. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  197816. /* invert the alpha channel (in tRNS) */
  197817. if ((png_ptr->transformations & PNG_INVERT_ALPHA) &&
  197818. info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  197819. {
  197820. int j;
  197821. for (j=0; j<(int)info_ptr->num_trans; j++)
  197822. info_ptr->trans[j] = (png_byte)(255 - info_ptr->trans[j]);
  197823. }
  197824. #endif
  197825. png_write_tRNS(png_ptr, info_ptr->trans, &(info_ptr->trans_values),
  197826. info_ptr->num_trans, info_ptr->color_type);
  197827. }
  197828. #endif
  197829. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  197830. if (info_ptr->valid & PNG_INFO_bKGD)
  197831. png_write_bKGD(png_ptr, &(info_ptr->background), info_ptr->color_type);
  197832. #endif
  197833. #if defined(PNG_WRITE_hIST_SUPPORTED)
  197834. if (info_ptr->valid & PNG_INFO_hIST)
  197835. png_write_hIST(png_ptr, info_ptr->hist, info_ptr->num_palette);
  197836. #endif
  197837. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  197838. if (info_ptr->valid & PNG_INFO_oFFs)
  197839. png_write_oFFs(png_ptr, info_ptr->x_offset, info_ptr->y_offset,
  197840. info_ptr->offset_unit_type);
  197841. #endif
  197842. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  197843. if (info_ptr->valid & PNG_INFO_pCAL)
  197844. png_write_pCAL(png_ptr, info_ptr->pcal_purpose, info_ptr->pcal_X0,
  197845. info_ptr->pcal_X1, info_ptr->pcal_type, info_ptr->pcal_nparams,
  197846. info_ptr->pcal_units, info_ptr->pcal_params);
  197847. #endif
  197848. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  197849. if (info_ptr->valid & PNG_INFO_sCAL)
  197850. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  197851. png_write_sCAL(png_ptr, (int)info_ptr->scal_unit,
  197852. info_ptr->scal_pixel_width, info_ptr->scal_pixel_height);
  197853. #else
  197854. #ifdef PNG_FIXED_POINT_SUPPORTED
  197855. png_write_sCAL_s(png_ptr, (int)info_ptr->scal_unit,
  197856. info_ptr->scal_s_width, info_ptr->scal_s_height);
  197857. #else
  197858. png_warning(png_ptr,
  197859. "png_write_sCAL not supported; sCAL chunk not written.");
  197860. #endif
  197861. #endif
  197862. #endif
  197863. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  197864. if (info_ptr->valid & PNG_INFO_pHYs)
  197865. png_write_pHYs(png_ptr, info_ptr->x_pixels_per_unit,
  197866. info_ptr->y_pixels_per_unit, info_ptr->phys_unit_type);
  197867. #endif
  197868. #if defined(PNG_WRITE_tIME_SUPPORTED)
  197869. if (info_ptr->valid & PNG_INFO_tIME)
  197870. {
  197871. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  197872. png_ptr->mode |= PNG_WROTE_tIME;
  197873. }
  197874. #endif
  197875. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  197876. if (info_ptr->valid & PNG_INFO_sPLT)
  197877. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  197878. png_write_sPLT(png_ptr, info_ptr->splt_palettes + i);
  197879. #endif
  197880. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  197881. /* Check to see if we need to write text chunks */
  197882. for (i = 0; i < info_ptr->num_text; i++)
  197883. {
  197884. png_debug2(2, "Writing header text chunk %d, type %d\n", i,
  197885. info_ptr->text[i].compression);
  197886. /* an internationalized chunk? */
  197887. if (info_ptr->text[i].compression > 0)
  197888. {
  197889. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  197890. /* write international chunk */
  197891. png_write_iTXt(png_ptr,
  197892. info_ptr->text[i].compression,
  197893. info_ptr->text[i].key,
  197894. info_ptr->text[i].lang,
  197895. info_ptr->text[i].lang_key,
  197896. info_ptr->text[i].text);
  197897. #else
  197898. png_warning(png_ptr, "Unable to write international text");
  197899. #endif
  197900. /* Mark this chunk as written */
  197901. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  197902. }
  197903. /* If we want a compressed text chunk */
  197904. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_zTXt)
  197905. {
  197906. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  197907. /* write compressed chunk */
  197908. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  197909. info_ptr->text[i].text, 0,
  197910. info_ptr->text[i].compression);
  197911. #else
  197912. png_warning(png_ptr, "Unable to write compressed text");
  197913. #endif
  197914. /* Mark this chunk as written */
  197915. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  197916. }
  197917. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  197918. {
  197919. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  197920. /* write uncompressed chunk */
  197921. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  197922. info_ptr->text[i].text,
  197923. 0);
  197924. #else
  197925. png_warning(png_ptr, "Unable to write uncompressed text");
  197926. #endif
  197927. /* Mark this chunk as written */
  197928. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  197929. }
  197930. }
  197931. #endif
  197932. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  197933. if (info_ptr->unknown_chunks_num)
  197934. {
  197935. png_unknown_chunk *up;
  197936. png_debug(5, "writing extra chunks\n");
  197937. for (up = info_ptr->unknown_chunks;
  197938. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  197939. up++)
  197940. {
  197941. int keep=png_handle_as_unknown(png_ptr, up->name);
  197942. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  197943. up->location && (up->location & PNG_HAVE_PLTE) &&
  197944. !(up->location & PNG_HAVE_IDAT) &&
  197945. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  197946. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  197947. {
  197948. png_write_chunk(png_ptr, up->name, up->data, up->size);
  197949. }
  197950. }
  197951. }
  197952. #endif
  197953. }
  197954. /* Writes the end of the PNG file. If you don't want to write comments or
  197955. * time information, you can pass NULL for info. If you already wrote these
  197956. * in png_write_info(), do not write them again here. If you have long
  197957. * comments, I suggest writing them here, and compressing them.
  197958. */
  197959. void PNGAPI
  197960. png_write_end(png_structp png_ptr, png_infop info_ptr)
  197961. {
  197962. png_debug(1, "in png_write_end\n");
  197963. if (png_ptr == NULL)
  197964. return;
  197965. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  197966. png_error(png_ptr, "No IDATs written into file");
  197967. /* see if user wants us to write information chunks */
  197968. if (info_ptr != NULL)
  197969. {
  197970. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  197971. int i; /* local index variable */
  197972. #endif
  197973. #if defined(PNG_WRITE_tIME_SUPPORTED)
  197974. /* check to see if user has supplied a time chunk */
  197975. if ((info_ptr->valid & PNG_INFO_tIME) &&
  197976. !(png_ptr->mode & PNG_WROTE_tIME))
  197977. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  197978. #endif
  197979. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  197980. /* loop through comment chunks */
  197981. for (i = 0; i < info_ptr->num_text; i++)
  197982. {
  197983. png_debug2(2, "Writing trailer text chunk %d, type %d\n", i,
  197984. info_ptr->text[i].compression);
  197985. /* an internationalized chunk? */
  197986. if (info_ptr->text[i].compression > 0)
  197987. {
  197988. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  197989. /* write international chunk */
  197990. png_write_iTXt(png_ptr,
  197991. info_ptr->text[i].compression,
  197992. info_ptr->text[i].key,
  197993. info_ptr->text[i].lang,
  197994. info_ptr->text[i].lang_key,
  197995. info_ptr->text[i].text);
  197996. #else
  197997. png_warning(png_ptr, "Unable to write international text");
  197998. #endif
  197999. /* Mark this chunk as written */
  198000. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  198001. }
  198002. else if (info_ptr->text[i].compression >= PNG_TEXT_COMPRESSION_zTXt)
  198003. {
  198004. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  198005. /* write compressed chunk */
  198006. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  198007. info_ptr->text[i].text, 0,
  198008. info_ptr->text[i].compression);
  198009. #else
  198010. png_warning(png_ptr, "Unable to write compressed text");
  198011. #endif
  198012. /* Mark this chunk as written */
  198013. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  198014. }
  198015. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  198016. {
  198017. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  198018. /* write uncompressed chunk */
  198019. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  198020. info_ptr->text[i].text, 0);
  198021. #else
  198022. png_warning(png_ptr, "Unable to write uncompressed text");
  198023. #endif
  198024. /* Mark this chunk as written */
  198025. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  198026. }
  198027. }
  198028. #endif
  198029. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  198030. if (info_ptr->unknown_chunks_num)
  198031. {
  198032. png_unknown_chunk *up;
  198033. png_debug(5, "writing extra chunks\n");
  198034. for (up = info_ptr->unknown_chunks;
  198035. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  198036. up++)
  198037. {
  198038. int keep=png_handle_as_unknown(png_ptr, up->name);
  198039. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  198040. up->location && (up->location & PNG_AFTER_IDAT) &&
  198041. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  198042. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  198043. {
  198044. png_write_chunk(png_ptr, up->name, up->data, up->size);
  198045. }
  198046. }
  198047. }
  198048. #endif
  198049. }
  198050. png_ptr->mode |= PNG_AFTER_IDAT;
  198051. /* write end of PNG file */
  198052. png_write_IEND(png_ptr);
  198053. }
  198054. #if defined(PNG_WRITE_tIME_SUPPORTED)
  198055. #if !defined(_WIN32_WCE)
  198056. /* "time.h" functions are not supported on WindowsCE */
  198057. void PNGAPI
  198058. png_convert_from_struct_tm(png_timep ptime, struct tm FAR * ttime)
  198059. {
  198060. png_debug(1, "in png_convert_from_struct_tm\n");
  198061. ptime->year = (png_uint_16)(1900 + ttime->tm_year);
  198062. ptime->month = (png_byte)(ttime->tm_mon + 1);
  198063. ptime->day = (png_byte)ttime->tm_mday;
  198064. ptime->hour = (png_byte)ttime->tm_hour;
  198065. ptime->minute = (png_byte)ttime->tm_min;
  198066. ptime->second = (png_byte)ttime->tm_sec;
  198067. }
  198068. void PNGAPI
  198069. png_convert_from_time_t(png_timep ptime, time_t ttime)
  198070. {
  198071. struct tm *tbuf;
  198072. png_debug(1, "in png_convert_from_time_t\n");
  198073. tbuf = gmtime(&ttime);
  198074. png_convert_from_struct_tm(ptime, tbuf);
  198075. }
  198076. #endif
  198077. #endif
  198078. /* Initialize png_ptr structure, and allocate any memory needed */
  198079. png_structp PNGAPI
  198080. png_create_write_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  198081. png_error_ptr error_fn, png_error_ptr warn_fn)
  198082. {
  198083. #ifdef PNG_USER_MEM_SUPPORTED
  198084. return (png_create_write_struct_2(user_png_ver, error_ptr, error_fn,
  198085. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  198086. }
  198087. /* Alternate initialize png_ptr structure, and allocate any memory needed */
  198088. png_structp PNGAPI
  198089. png_create_write_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  198090. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  198091. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  198092. {
  198093. #endif /* PNG_USER_MEM_SUPPORTED */
  198094. png_structp png_ptr;
  198095. #ifdef PNG_SETJMP_SUPPORTED
  198096. #ifdef USE_FAR_KEYWORD
  198097. jmp_buf jmpbuf;
  198098. #endif
  198099. #endif
  198100. int i;
  198101. png_debug(1, "in png_create_write_struct\n");
  198102. #ifdef PNG_USER_MEM_SUPPORTED
  198103. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  198104. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  198105. #else
  198106. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  198107. #endif /* PNG_USER_MEM_SUPPORTED */
  198108. if (png_ptr == NULL)
  198109. return (NULL);
  198110. /* added at libpng-1.2.6 */
  198111. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  198112. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  198113. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  198114. #endif
  198115. #ifdef PNG_SETJMP_SUPPORTED
  198116. #ifdef USE_FAR_KEYWORD
  198117. if (setjmp(jmpbuf))
  198118. #else
  198119. if (setjmp(png_ptr->jmpbuf))
  198120. #endif
  198121. {
  198122. png_free(png_ptr, png_ptr->zbuf);
  198123. png_ptr->zbuf=NULL;
  198124. png_destroy_struct(png_ptr);
  198125. return (NULL);
  198126. }
  198127. #ifdef USE_FAR_KEYWORD
  198128. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  198129. #endif
  198130. #endif
  198131. #ifdef PNG_USER_MEM_SUPPORTED
  198132. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  198133. #endif /* PNG_USER_MEM_SUPPORTED */
  198134. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  198135. i=0;
  198136. do
  198137. {
  198138. if(user_png_ver[i] != png_libpng_ver[i])
  198139. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  198140. } while (png_libpng_ver[i++]);
  198141. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  198142. {
  198143. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  198144. * we must recompile any applications that use any older library version.
  198145. * For versions after libpng 1.0, we will be compatible, so we need
  198146. * only check the first digit.
  198147. */
  198148. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  198149. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  198150. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  198151. {
  198152. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  198153. char msg[80];
  198154. if (user_png_ver)
  198155. {
  198156. png_snprintf(msg, 80,
  198157. "Application was compiled with png.h from libpng-%.20s",
  198158. user_png_ver);
  198159. png_warning(png_ptr, msg);
  198160. }
  198161. png_snprintf(msg, 80,
  198162. "Application is running with png.c from libpng-%.20s",
  198163. png_libpng_ver);
  198164. png_warning(png_ptr, msg);
  198165. #endif
  198166. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  198167. png_ptr->flags=0;
  198168. #endif
  198169. png_error(png_ptr,
  198170. "Incompatible libpng version in application and library");
  198171. }
  198172. }
  198173. /* initialize zbuf - compression buffer */
  198174. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  198175. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  198176. (png_uint_32)png_ptr->zbuf_size);
  198177. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  198178. png_flush_ptr_NULL);
  198179. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  198180. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  198181. 1, png_doublep_NULL, png_doublep_NULL);
  198182. #endif
  198183. #ifdef PNG_SETJMP_SUPPORTED
  198184. /* Applications that neglect to set up their own setjmp() and then encounter
  198185. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  198186. abort instead of returning. */
  198187. #ifdef USE_FAR_KEYWORD
  198188. if (setjmp(jmpbuf))
  198189. PNG_ABORT();
  198190. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  198191. #else
  198192. if (setjmp(png_ptr->jmpbuf))
  198193. PNG_ABORT();
  198194. #endif
  198195. #endif
  198196. return (png_ptr);
  198197. }
  198198. /* Initialize png_ptr structure, and allocate any memory needed */
  198199. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  198200. /* Deprecated. */
  198201. #undef png_write_init
  198202. void PNGAPI
  198203. png_write_init(png_structp png_ptr)
  198204. {
  198205. /* We only come here via pre-1.0.7-compiled applications */
  198206. png_write_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  198207. }
  198208. void PNGAPI
  198209. png_write_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  198210. png_size_t png_struct_size, png_size_t png_info_size)
  198211. {
  198212. /* We only come here via pre-1.0.12-compiled applications */
  198213. if(png_ptr == NULL) return;
  198214. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  198215. if(png_sizeof(png_struct) > png_struct_size ||
  198216. png_sizeof(png_info) > png_info_size)
  198217. {
  198218. char msg[80];
  198219. png_ptr->warning_fn=NULL;
  198220. if (user_png_ver)
  198221. {
  198222. png_snprintf(msg, 80,
  198223. "Application was compiled with png.h from libpng-%.20s",
  198224. user_png_ver);
  198225. png_warning(png_ptr, msg);
  198226. }
  198227. png_snprintf(msg, 80,
  198228. "Application is running with png.c from libpng-%.20s",
  198229. png_libpng_ver);
  198230. png_warning(png_ptr, msg);
  198231. }
  198232. #endif
  198233. if(png_sizeof(png_struct) > png_struct_size)
  198234. {
  198235. png_ptr->error_fn=NULL;
  198236. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  198237. png_ptr->flags=0;
  198238. #endif
  198239. png_error(png_ptr,
  198240. "The png struct allocated by the application for writing is too small.");
  198241. }
  198242. if(png_sizeof(png_info) > png_info_size)
  198243. {
  198244. png_ptr->error_fn=NULL;
  198245. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  198246. png_ptr->flags=0;
  198247. #endif
  198248. png_error(png_ptr,
  198249. "The info struct allocated by the application for writing is too small.");
  198250. }
  198251. png_write_init_3(&png_ptr, user_png_ver, png_struct_size);
  198252. }
  198253. #endif /* PNG_1_0_X || PNG_1_2_X */
  198254. void PNGAPI
  198255. png_write_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  198256. png_size_t png_struct_size)
  198257. {
  198258. png_structp png_ptr=*ptr_ptr;
  198259. #ifdef PNG_SETJMP_SUPPORTED
  198260. jmp_buf tmp_jmp; /* to save current jump buffer */
  198261. #endif
  198262. int i = 0;
  198263. if (png_ptr == NULL)
  198264. return;
  198265. do
  198266. {
  198267. if (user_png_ver[i] != png_libpng_ver[i])
  198268. {
  198269. #ifdef PNG_LEGACY_SUPPORTED
  198270. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  198271. #else
  198272. png_ptr->warning_fn=NULL;
  198273. png_warning(png_ptr,
  198274. "Application uses deprecated png_write_init() and should be recompiled.");
  198275. break;
  198276. #endif
  198277. }
  198278. } while (png_libpng_ver[i++]);
  198279. png_debug(1, "in png_write_init_3\n");
  198280. #ifdef PNG_SETJMP_SUPPORTED
  198281. /* save jump buffer and error functions */
  198282. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  198283. #endif
  198284. if (png_sizeof(png_struct) > png_struct_size)
  198285. {
  198286. png_destroy_struct(png_ptr);
  198287. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  198288. *ptr_ptr = png_ptr;
  198289. }
  198290. /* reset all variables to 0 */
  198291. png_memset(png_ptr, 0, png_sizeof (png_struct));
  198292. /* added at libpng-1.2.6 */
  198293. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  198294. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  198295. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  198296. #endif
  198297. #ifdef PNG_SETJMP_SUPPORTED
  198298. /* restore jump buffer */
  198299. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  198300. #endif
  198301. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  198302. png_flush_ptr_NULL);
  198303. /* initialize zbuf - compression buffer */
  198304. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  198305. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  198306. (png_uint_32)png_ptr->zbuf_size);
  198307. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  198308. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  198309. 1, png_doublep_NULL, png_doublep_NULL);
  198310. #endif
  198311. }
  198312. /* Write a few rows of image data. If the image is interlaced,
  198313. * either you will have to write the 7 sub images, or, if you
  198314. * have called png_set_interlace_handling(), you will have to
  198315. * "write" the image seven times.
  198316. */
  198317. void PNGAPI
  198318. png_write_rows(png_structp png_ptr, png_bytepp row,
  198319. png_uint_32 num_rows)
  198320. {
  198321. png_uint_32 i; /* row counter */
  198322. png_bytepp rp; /* row pointer */
  198323. png_debug(1, "in png_write_rows\n");
  198324. if (png_ptr == NULL)
  198325. return;
  198326. /* loop through the rows */
  198327. for (i = 0, rp = row; i < num_rows; i++, rp++)
  198328. {
  198329. png_write_row(png_ptr, *rp);
  198330. }
  198331. }
  198332. /* Write the image. You only need to call this function once, even
  198333. * if you are writing an interlaced image.
  198334. */
  198335. void PNGAPI
  198336. png_write_image(png_structp png_ptr, png_bytepp image)
  198337. {
  198338. png_uint_32 i; /* row index */
  198339. int pass, num_pass; /* pass variables */
  198340. png_bytepp rp; /* points to current row */
  198341. if (png_ptr == NULL)
  198342. return;
  198343. png_debug(1, "in png_write_image\n");
  198344. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  198345. /* intialize interlace handling. If image is not interlaced,
  198346. this will set pass to 1 */
  198347. num_pass = png_set_interlace_handling(png_ptr);
  198348. #else
  198349. num_pass = 1;
  198350. #endif
  198351. /* loop through passes */
  198352. for (pass = 0; pass < num_pass; pass++)
  198353. {
  198354. /* loop through image */
  198355. for (i = 0, rp = image; i < png_ptr->height; i++, rp++)
  198356. {
  198357. png_write_row(png_ptr, *rp);
  198358. }
  198359. }
  198360. }
  198361. /* called by user to write a row of image data */
  198362. void PNGAPI
  198363. png_write_row(png_structp png_ptr, png_bytep row)
  198364. {
  198365. if (png_ptr == NULL)
  198366. return;
  198367. png_debug2(1, "in png_write_row (row %ld, pass %d)\n",
  198368. png_ptr->row_number, png_ptr->pass);
  198369. /* initialize transformations and other stuff if first time */
  198370. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  198371. {
  198372. /* make sure we wrote the header info */
  198373. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  198374. png_error(png_ptr,
  198375. "png_write_info was never called before png_write_row.");
  198376. /* check for transforms that have been set but were defined out */
  198377. #if !defined(PNG_WRITE_INVERT_SUPPORTED) && defined(PNG_READ_INVERT_SUPPORTED)
  198378. if (png_ptr->transformations & PNG_INVERT_MONO)
  198379. png_warning(png_ptr, "PNG_WRITE_INVERT_SUPPORTED is not defined.");
  198380. #endif
  198381. #if !defined(PNG_WRITE_FILLER_SUPPORTED) && defined(PNG_READ_FILLER_SUPPORTED)
  198382. if (png_ptr->transformations & PNG_FILLER)
  198383. png_warning(png_ptr, "PNG_WRITE_FILLER_SUPPORTED is not defined.");
  198384. #endif
  198385. #if !defined(PNG_WRITE_PACKSWAP_SUPPORTED) && defined(PNG_READ_PACKSWAP_SUPPORTED)
  198386. if (png_ptr->transformations & PNG_PACKSWAP)
  198387. png_warning(png_ptr, "PNG_WRITE_PACKSWAP_SUPPORTED is not defined.");
  198388. #endif
  198389. #if !defined(PNG_WRITE_PACK_SUPPORTED) && defined(PNG_READ_PACK_SUPPORTED)
  198390. if (png_ptr->transformations & PNG_PACK)
  198391. png_warning(png_ptr, "PNG_WRITE_PACK_SUPPORTED is not defined.");
  198392. #endif
  198393. #if !defined(PNG_WRITE_SHIFT_SUPPORTED) && defined(PNG_READ_SHIFT_SUPPORTED)
  198394. if (png_ptr->transformations & PNG_SHIFT)
  198395. png_warning(png_ptr, "PNG_WRITE_SHIFT_SUPPORTED is not defined.");
  198396. #endif
  198397. #if !defined(PNG_WRITE_BGR_SUPPORTED) && defined(PNG_READ_BGR_SUPPORTED)
  198398. if (png_ptr->transformations & PNG_BGR)
  198399. png_warning(png_ptr, "PNG_WRITE_BGR_SUPPORTED is not defined.");
  198400. #endif
  198401. #if !defined(PNG_WRITE_SWAP_SUPPORTED) && defined(PNG_READ_SWAP_SUPPORTED)
  198402. if (png_ptr->transformations & PNG_SWAP_BYTES)
  198403. png_warning(png_ptr, "PNG_WRITE_SWAP_SUPPORTED is not defined.");
  198404. #endif
  198405. png_write_start_row(png_ptr);
  198406. }
  198407. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  198408. /* if interlaced and not interested in row, return */
  198409. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  198410. {
  198411. switch (png_ptr->pass)
  198412. {
  198413. case 0:
  198414. if (png_ptr->row_number & 0x07)
  198415. {
  198416. png_write_finish_row(png_ptr);
  198417. return;
  198418. }
  198419. break;
  198420. case 1:
  198421. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  198422. {
  198423. png_write_finish_row(png_ptr);
  198424. return;
  198425. }
  198426. break;
  198427. case 2:
  198428. if ((png_ptr->row_number & 0x07) != 4)
  198429. {
  198430. png_write_finish_row(png_ptr);
  198431. return;
  198432. }
  198433. break;
  198434. case 3:
  198435. if ((png_ptr->row_number & 0x03) || png_ptr->width < 3)
  198436. {
  198437. png_write_finish_row(png_ptr);
  198438. return;
  198439. }
  198440. break;
  198441. case 4:
  198442. if ((png_ptr->row_number & 0x03) != 2)
  198443. {
  198444. png_write_finish_row(png_ptr);
  198445. return;
  198446. }
  198447. break;
  198448. case 5:
  198449. if ((png_ptr->row_number & 0x01) || png_ptr->width < 2)
  198450. {
  198451. png_write_finish_row(png_ptr);
  198452. return;
  198453. }
  198454. break;
  198455. case 6:
  198456. if (!(png_ptr->row_number & 0x01))
  198457. {
  198458. png_write_finish_row(png_ptr);
  198459. return;
  198460. }
  198461. break;
  198462. }
  198463. }
  198464. #endif
  198465. /* set up row info for transformations */
  198466. png_ptr->row_info.color_type = png_ptr->color_type;
  198467. png_ptr->row_info.width = png_ptr->usr_width;
  198468. png_ptr->row_info.channels = png_ptr->usr_channels;
  198469. png_ptr->row_info.bit_depth = png_ptr->usr_bit_depth;
  198470. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  198471. png_ptr->row_info.channels);
  198472. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  198473. png_ptr->row_info.width);
  198474. png_debug1(3, "row_info->color_type = %d\n", png_ptr->row_info.color_type);
  198475. png_debug1(3, "row_info->width = %lu\n", png_ptr->row_info.width);
  198476. png_debug1(3, "row_info->channels = %d\n", png_ptr->row_info.channels);
  198477. png_debug1(3, "row_info->bit_depth = %d\n", png_ptr->row_info.bit_depth);
  198478. png_debug1(3, "row_info->pixel_depth = %d\n", png_ptr->row_info.pixel_depth);
  198479. png_debug1(3, "row_info->rowbytes = %lu\n", png_ptr->row_info.rowbytes);
  198480. /* Copy user's row into buffer, leaving room for filter byte. */
  198481. png_memcpy_check(png_ptr, png_ptr->row_buf + 1, row,
  198482. png_ptr->row_info.rowbytes);
  198483. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  198484. /* handle interlacing */
  198485. if (png_ptr->interlaced && png_ptr->pass < 6 &&
  198486. (png_ptr->transformations & PNG_INTERLACE))
  198487. {
  198488. png_do_write_interlace(&(png_ptr->row_info),
  198489. png_ptr->row_buf + 1, png_ptr->pass);
  198490. /* this should always get caught above, but still ... */
  198491. if (!(png_ptr->row_info.width))
  198492. {
  198493. png_write_finish_row(png_ptr);
  198494. return;
  198495. }
  198496. }
  198497. #endif
  198498. /* handle other transformations */
  198499. if (png_ptr->transformations)
  198500. png_do_write_transformations(png_ptr);
  198501. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  198502. /* Write filter_method 64 (intrapixel differencing) only if
  198503. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  198504. * 2. Libpng did not write a PNG signature (this filter_method is only
  198505. * used in PNG datastreams that are embedded in MNG datastreams) and
  198506. * 3. The application called png_permit_mng_features with a mask that
  198507. * included PNG_FLAG_MNG_FILTER_64 and
  198508. * 4. The filter_method is 64 and
  198509. * 5. The color_type is RGB or RGBA
  198510. */
  198511. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  198512. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  198513. {
  198514. /* Intrapixel differencing */
  198515. png_do_write_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  198516. }
  198517. #endif
  198518. /* Find a filter if necessary, filter the row and write it out. */
  198519. png_write_find_filter(png_ptr, &(png_ptr->row_info));
  198520. if (png_ptr->write_row_fn != NULL)
  198521. (*(png_ptr->write_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  198522. }
  198523. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  198524. /* Set the automatic flush interval or 0 to turn flushing off */
  198525. void PNGAPI
  198526. png_set_flush(png_structp png_ptr, int nrows)
  198527. {
  198528. png_debug(1, "in png_set_flush\n");
  198529. if (png_ptr == NULL)
  198530. return;
  198531. png_ptr->flush_dist = (nrows < 0 ? 0 : nrows);
  198532. }
  198533. /* flush the current output buffers now */
  198534. void PNGAPI
  198535. png_write_flush(png_structp png_ptr)
  198536. {
  198537. int wrote_IDAT;
  198538. png_debug(1, "in png_write_flush\n");
  198539. if (png_ptr == NULL)
  198540. return;
  198541. /* We have already written out all of the data */
  198542. if (png_ptr->row_number >= png_ptr->num_rows)
  198543. return;
  198544. do
  198545. {
  198546. int ret;
  198547. /* compress the data */
  198548. ret = deflate(&png_ptr->zstream, Z_SYNC_FLUSH);
  198549. wrote_IDAT = 0;
  198550. /* check for compression errors */
  198551. if (ret != Z_OK)
  198552. {
  198553. if (png_ptr->zstream.msg != NULL)
  198554. png_error(png_ptr, png_ptr->zstream.msg);
  198555. else
  198556. png_error(png_ptr, "zlib error");
  198557. }
  198558. if (!(png_ptr->zstream.avail_out))
  198559. {
  198560. /* write the IDAT and reset the zlib output buffer */
  198561. png_write_IDAT(png_ptr, png_ptr->zbuf,
  198562. png_ptr->zbuf_size);
  198563. png_ptr->zstream.next_out = png_ptr->zbuf;
  198564. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  198565. wrote_IDAT = 1;
  198566. }
  198567. } while(wrote_IDAT == 1);
  198568. /* If there is any data left to be output, write it into a new IDAT */
  198569. if (png_ptr->zbuf_size != png_ptr->zstream.avail_out)
  198570. {
  198571. /* write the IDAT and reset the zlib output buffer */
  198572. png_write_IDAT(png_ptr, png_ptr->zbuf,
  198573. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  198574. png_ptr->zstream.next_out = png_ptr->zbuf;
  198575. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  198576. }
  198577. png_ptr->flush_rows = 0;
  198578. png_flush(png_ptr);
  198579. }
  198580. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  198581. /* free all memory used by the write */
  198582. void PNGAPI
  198583. png_destroy_write_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr)
  198584. {
  198585. png_structp png_ptr = NULL;
  198586. png_infop info_ptr = NULL;
  198587. #ifdef PNG_USER_MEM_SUPPORTED
  198588. png_free_ptr free_fn = NULL;
  198589. png_voidp mem_ptr = NULL;
  198590. #endif
  198591. png_debug(1, "in png_destroy_write_struct\n");
  198592. if (png_ptr_ptr != NULL)
  198593. {
  198594. png_ptr = *png_ptr_ptr;
  198595. #ifdef PNG_USER_MEM_SUPPORTED
  198596. free_fn = png_ptr->free_fn;
  198597. mem_ptr = png_ptr->mem_ptr;
  198598. #endif
  198599. }
  198600. if (info_ptr_ptr != NULL)
  198601. info_ptr = *info_ptr_ptr;
  198602. if (info_ptr != NULL)
  198603. {
  198604. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  198605. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  198606. if (png_ptr->num_chunk_list)
  198607. {
  198608. png_free(png_ptr, png_ptr->chunk_list);
  198609. png_ptr->chunk_list=NULL;
  198610. png_ptr->num_chunk_list=0;
  198611. }
  198612. #endif
  198613. #ifdef PNG_USER_MEM_SUPPORTED
  198614. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  198615. (png_voidp)mem_ptr);
  198616. #else
  198617. png_destroy_struct((png_voidp)info_ptr);
  198618. #endif
  198619. *info_ptr_ptr = NULL;
  198620. }
  198621. if (png_ptr != NULL)
  198622. {
  198623. png_write_destroy(png_ptr);
  198624. #ifdef PNG_USER_MEM_SUPPORTED
  198625. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  198626. (png_voidp)mem_ptr);
  198627. #else
  198628. png_destroy_struct((png_voidp)png_ptr);
  198629. #endif
  198630. *png_ptr_ptr = NULL;
  198631. }
  198632. }
  198633. /* Free any memory used in png_ptr struct (old method) */
  198634. void /* PRIVATE */
  198635. png_write_destroy(png_structp png_ptr)
  198636. {
  198637. #ifdef PNG_SETJMP_SUPPORTED
  198638. jmp_buf tmp_jmp; /* save jump buffer */
  198639. #endif
  198640. png_error_ptr error_fn;
  198641. png_error_ptr warning_fn;
  198642. png_voidp error_ptr;
  198643. #ifdef PNG_USER_MEM_SUPPORTED
  198644. png_free_ptr free_fn;
  198645. #endif
  198646. png_debug(1, "in png_write_destroy\n");
  198647. /* free any memory zlib uses */
  198648. deflateEnd(&png_ptr->zstream);
  198649. /* free our memory. png_free checks NULL for us. */
  198650. png_free(png_ptr, png_ptr->zbuf);
  198651. png_free(png_ptr, png_ptr->row_buf);
  198652. png_free(png_ptr, png_ptr->prev_row);
  198653. png_free(png_ptr, png_ptr->sub_row);
  198654. png_free(png_ptr, png_ptr->up_row);
  198655. png_free(png_ptr, png_ptr->avg_row);
  198656. png_free(png_ptr, png_ptr->paeth_row);
  198657. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  198658. png_free(png_ptr, png_ptr->time_buffer);
  198659. #endif
  198660. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  198661. png_free(png_ptr, png_ptr->prev_filters);
  198662. png_free(png_ptr, png_ptr->filter_weights);
  198663. png_free(png_ptr, png_ptr->inv_filter_weights);
  198664. png_free(png_ptr, png_ptr->filter_costs);
  198665. png_free(png_ptr, png_ptr->inv_filter_costs);
  198666. #endif
  198667. #ifdef PNG_SETJMP_SUPPORTED
  198668. /* reset structure */
  198669. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  198670. #endif
  198671. error_fn = png_ptr->error_fn;
  198672. warning_fn = png_ptr->warning_fn;
  198673. error_ptr = png_ptr->error_ptr;
  198674. #ifdef PNG_USER_MEM_SUPPORTED
  198675. free_fn = png_ptr->free_fn;
  198676. #endif
  198677. png_memset(png_ptr, 0, png_sizeof (png_struct));
  198678. png_ptr->error_fn = error_fn;
  198679. png_ptr->warning_fn = warning_fn;
  198680. png_ptr->error_ptr = error_ptr;
  198681. #ifdef PNG_USER_MEM_SUPPORTED
  198682. png_ptr->free_fn = free_fn;
  198683. #endif
  198684. #ifdef PNG_SETJMP_SUPPORTED
  198685. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  198686. #endif
  198687. }
  198688. /* Allow the application to select one or more row filters to use. */
  198689. void PNGAPI
  198690. png_set_filter(png_structp png_ptr, int method, int filters)
  198691. {
  198692. png_debug(1, "in png_set_filter\n");
  198693. if (png_ptr == NULL)
  198694. return;
  198695. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  198696. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  198697. (method == PNG_INTRAPIXEL_DIFFERENCING))
  198698. method = PNG_FILTER_TYPE_BASE;
  198699. #endif
  198700. if (method == PNG_FILTER_TYPE_BASE)
  198701. {
  198702. switch (filters & (PNG_ALL_FILTERS | 0x07))
  198703. {
  198704. #ifndef PNG_NO_WRITE_FILTER
  198705. case 5:
  198706. case 6:
  198707. case 7: png_warning(png_ptr, "Unknown row filter for method 0");
  198708. #endif /* PNG_NO_WRITE_FILTER */
  198709. case PNG_FILTER_VALUE_NONE:
  198710. png_ptr->do_filter=PNG_FILTER_NONE; break;
  198711. #ifndef PNG_NO_WRITE_FILTER
  198712. case PNG_FILTER_VALUE_SUB:
  198713. png_ptr->do_filter=PNG_FILTER_SUB; break;
  198714. case PNG_FILTER_VALUE_UP:
  198715. png_ptr->do_filter=PNG_FILTER_UP; break;
  198716. case PNG_FILTER_VALUE_AVG:
  198717. png_ptr->do_filter=PNG_FILTER_AVG; break;
  198718. case PNG_FILTER_VALUE_PAETH:
  198719. png_ptr->do_filter=PNG_FILTER_PAETH; break;
  198720. default: png_ptr->do_filter = (png_byte)filters; break;
  198721. #else
  198722. default: png_warning(png_ptr, "Unknown row filter for method 0");
  198723. #endif /* PNG_NO_WRITE_FILTER */
  198724. }
  198725. /* If we have allocated the row_buf, this means we have already started
  198726. * with the image and we should have allocated all of the filter buffers
  198727. * that have been selected. If prev_row isn't already allocated, then
  198728. * it is too late to start using the filters that need it, since we
  198729. * will be missing the data in the previous row. If an application
  198730. * wants to start and stop using particular filters during compression,
  198731. * it should start out with all of the filters, and then add and
  198732. * remove them after the start of compression.
  198733. */
  198734. if (png_ptr->row_buf != NULL)
  198735. {
  198736. #ifndef PNG_NO_WRITE_FILTER
  198737. if ((png_ptr->do_filter & PNG_FILTER_SUB) && png_ptr->sub_row == NULL)
  198738. {
  198739. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  198740. (png_ptr->rowbytes + 1));
  198741. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  198742. }
  198743. if ((png_ptr->do_filter & PNG_FILTER_UP) && png_ptr->up_row == NULL)
  198744. {
  198745. if (png_ptr->prev_row == NULL)
  198746. {
  198747. png_warning(png_ptr, "Can't add Up filter after starting");
  198748. png_ptr->do_filter &= ~PNG_FILTER_UP;
  198749. }
  198750. else
  198751. {
  198752. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  198753. (png_ptr->rowbytes + 1));
  198754. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  198755. }
  198756. }
  198757. if ((png_ptr->do_filter & PNG_FILTER_AVG) && png_ptr->avg_row == NULL)
  198758. {
  198759. if (png_ptr->prev_row == NULL)
  198760. {
  198761. png_warning(png_ptr, "Can't add Average filter after starting");
  198762. png_ptr->do_filter &= ~PNG_FILTER_AVG;
  198763. }
  198764. else
  198765. {
  198766. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  198767. (png_ptr->rowbytes + 1));
  198768. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  198769. }
  198770. }
  198771. if ((png_ptr->do_filter & PNG_FILTER_PAETH) &&
  198772. png_ptr->paeth_row == NULL)
  198773. {
  198774. if (png_ptr->prev_row == NULL)
  198775. {
  198776. png_warning(png_ptr, "Can't add Paeth filter after starting");
  198777. png_ptr->do_filter &= (png_byte)(~PNG_FILTER_PAETH);
  198778. }
  198779. else
  198780. {
  198781. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  198782. (png_ptr->rowbytes + 1));
  198783. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  198784. }
  198785. }
  198786. if (png_ptr->do_filter == PNG_NO_FILTERS)
  198787. #endif /* PNG_NO_WRITE_FILTER */
  198788. png_ptr->do_filter = PNG_FILTER_NONE;
  198789. }
  198790. }
  198791. else
  198792. png_error(png_ptr, "Unknown custom filter method");
  198793. }
  198794. /* This allows us to influence the way in which libpng chooses the "best"
  198795. * filter for the current scanline. While the "minimum-sum-of-absolute-
  198796. * differences metric is relatively fast and effective, there is some
  198797. * question as to whether it can be improved upon by trying to keep the
  198798. * filtered data going to zlib more consistent, hopefully resulting in
  198799. * better compression.
  198800. */
  198801. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* GRR 970116 */
  198802. void PNGAPI
  198803. png_set_filter_heuristics(png_structp png_ptr, int heuristic_method,
  198804. int num_weights, png_doublep filter_weights,
  198805. png_doublep filter_costs)
  198806. {
  198807. int i;
  198808. png_debug(1, "in png_set_filter_heuristics\n");
  198809. if (png_ptr == NULL)
  198810. return;
  198811. if (heuristic_method >= PNG_FILTER_HEURISTIC_LAST)
  198812. {
  198813. png_warning(png_ptr, "Unknown filter heuristic method");
  198814. return;
  198815. }
  198816. if (heuristic_method == PNG_FILTER_HEURISTIC_DEFAULT)
  198817. {
  198818. heuristic_method = PNG_FILTER_HEURISTIC_UNWEIGHTED;
  198819. }
  198820. if (num_weights < 0 || filter_weights == NULL ||
  198821. heuristic_method == PNG_FILTER_HEURISTIC_UNWEIGHTED)
  198822. {
  198823. num_weights = 0;
  198824. }
  198825. png_ptr->num_prev_filters = (png_byte)num_weights;
  198826. png_ptr->heuristic_method = (png_byte)heuristic_method;
  198827. if (num_weights > 0)
  198828. {
  198829. if (png_ptr->prev_filters == NULL)
  198830. {
  198831. png_ptr->prev_filters = (png_bytep)png_malloc(png_ptr,
  198832. (png_uint_32)(png_sizeof(png_byte) * num_weights));
  198833. /* To make sure that the weighting starts out fairly */
  198834. for (i = 0; i < num_weights; i++)
  198835. {
  198836. png_ptr->prev_filters[i] = 255;
  198837. }
  198838. }
  198839. if (png_ptr->filter_weights == NULL)
  198840. {
  198841. png_ptr->filter_weights = (png_uint_16p)png_malloc(png_ptr,
  198842. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  198843. png_ptr->inv_filter_weights = (png_uint_16p)png_malloc(png_ptr,
  198844. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  198845. for (i = 0; i < num_weights; i++)
  198846. {
  198847. png_ptr->inv_filter_weights[i] =
  198848. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  198849. }
  198850. }
  198851. for (i = 0; i < num_weights; i++)
  198852. {
  198853. if (filter_weights[i] < 0.0)
  198854. {
  198855. png_ptr->inv_filter_weights[i] =
  198856. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  198857. }
  198858. else
  198859. {
  198860. png_ptr->inv_filter_weights[i] =
  198861. (png_uint_16)((double)PNG_WEIGHT_FACTOR*filter_weights[i]+0.5);
  198862. png_ptr->filter_weights[i] =
  198863. (png_uint_16)((double)PNG_WEIGHT_FACTOR/filter_weights[i]+0.5);
  198864. }
  198865. }
  198866. }
  198867. /* If, in the future, there are other filter methods, this would
  198868. * need to be based on png_ptr->filter.
  198869. */
  198870. if (png_ptr->filter_costs == NULL)
  198871. {
  198872. png_ptr->filter_costs = (png_uint_16p)png_malloc(png_ptr,
  198873. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  198874. png_ptr->inv_filter_costs = (png_uint_16p)png_malloc(png_ptr,
  198875. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  198876. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  198877. {
  198878. png_ptr->inv_filter_costs[i] =
  198879. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  198880. }
  198881. }
  198882. /* Here is where we set the relative costs of the different filters. We
  198883. * should take the desired compression level into account when setting
  198884. * the costs, so that Paeth, for instance, has a high relative cost at low
  198885. * compression levels, while it has a lower relative cost at higher
  198886. * compression settings. The filter types are in order of increasing
  198887. * relative cost, so it would be possible to do this with an algorithm.
  198888. */
  198889. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  198890. {
  198891. if (filter_costs == NULL || filter_costs[i] < 0.0)
  198892. {
  198893. png_ptr->inv_filter_costs[i] =
  198894. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  198895. }
  198896. else if (filter_costs[i] >= 1.0)
  198897. {
  198898. png_ptr->inv_filter_costs[i] =
  198899. (png_uint_16)((double)PNG_COST_FACTOR / filter_costs[i] + 0.5);
  198900. png_ptr->filter_costs[i] =
  198901. (png_uint_16)((double)PNG_COST_FACTOR * filter_costs[i] + 0.5);
  198902. }
  198903. }
  198904. }
  198905. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  198906. void PNGAPI
  198907. png_set_compression_level(png_structp png_ptr, int level)
  198908. {
  198909. png_debug(1, "in png_set_compression_level\n");
  198910. if (png_ptr == NULL)
  198911. return;
  198912. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_LEVEL;
  198913. png_ptr->zlib_level = level;
  198914. }
  198915. void PNGAPI
  198916. png_set_compression_mem_level(png_structp png_ptr, int mem_level)
  198917. {
  198918. png_debug(1, "in png_set_compression_mem_level\n");
  198919. if (png_ptr == NULL)
  198920. return;
  198921. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL;
  198922. png_ptr->zlib_mem_level = mem_level;
  198923. }
  198924. void PNGAPI
  198925. png_set_compression_strategy(png_structp png_ptr, int strategy)
  198926. {
  198927. png_debug(1, "in png_set_compression_strategy\n");
  198928. if (png_ptr == NULL)
  198929. return;
  198930. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_STRATEGY;
  198931. png_ptr->zlib_strategy = strategy;
  198932. }
  198933. void PNGAPI
  198934. png_set_compression_window_bits(png_structp png_ptr, int window_bits)
  198935. {
  198936. if (png_ptr == NULL)
  198937. return;
  198938. if (window_bits > 15)
  198939. png_warning(png_ptr, "Only compression windows <= 32k supported by PNG");
  198940. else if (window_bits < 8)
  198941. png_warning(png_ptr, "Only compression windows >= 256 supported by PNG");
  198942. #ifndef WBITS_8_OK
  198943. /* avoid libpng bug with 256-byte windows */
  198944. if (window_bits == 8)
  198945. {
  198946. png_warning(png_ptr, "Compression window is being reset to 512");
  198947. window_bits=9;
  198948. }
  198949. #endif
  198950. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS;
  198951. png_ptr->zlib_window_bits = window_bits;
  198952. }
  198953. void PNGAPI
  198954. png_set_compression_method(png_structp png_ptr, int method)
  198955. {
  198956. png_debug(1, "in png_set_compression_method\n");
  198957. if (png_ptr == NULL)
  198958. return;
  198959. if (method != 8)
  198960. png_warning(png_ptr, "Only compression method 8 is supported by PNG");
  198961. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_METHOD;
  198962. png_ptr->zlib_method = method;
  198963. }
  198964. void PNGAPI
  198965. png_set_write_status_fn(png_structp png_ptr, png_write_status_ptr write_row_fn)
  198966. {
  198967. if (png_ptr == NULL)
  198968. return;
  198969. png_ptr->write_row_fn = write_row_fn;
  198970. }
  198971. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  198972. void PNGAPI
  198973. png_set_write_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  198974. write_user_transform_fn)
  198975. {
  198976. png_debug(1, "in png_set_write_user_transform_fn\n");
  198977. if (png_ptr == NULL)
  198978. return;
  198979. png_ptr->transformations |= PNG_USER_TRANSFORM;
  198980. png_ptr->write_user_transform_fn = write_user_transform_fn;
  198981. }
  198982. #endif
  198983. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  198984. void PNGAPI
  198985. png_write_png(png_structp png_ptr, png_infop info_ptr,
  198986. int transforms, voidp params)
  198987. {
  198988. if (png_ptr == NULL || info_ptr == NULL)
  198989. return;
  198990. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  198991. /* invert the alpha channel from opacity to transparency */
  198992. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  198993. png_set_invert_alpha(png_ptr);
  198994. #endif
  198995. /* Write the file header information. */
  198996. png_write_info(png_ptr, info_ptr);
  198997. /* ------ these transformations don't touch the info structure ------- */
  198998. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  198999. /* invert monochrome pixels */
  199000. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  199001. png_set_invert_mono(png_ptr);
  199002. #endif
  199003. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  199004. /* Shift the pixels up to a legal bit depth and fill in
  199005. * as appropriate to correctly scale the image.
  199006. */
  199007. if ((transforms & PNG_TRANSFORM_SHIFT)
  199008. && (info_ptr->valid & PNG_INFO_sBIT))
  199009. png_set_shift(png_ptr, &info_ptr->sig_bit);
  199010. #endif
  199011. #if defined(PNG_WRITE_PACK_SUPPORTED)
  199012. /* pack pixels into bytes */
  199013. if (transforms & PNG_TRANSFORM_PACKING)
  199014. png_set_packing(png_ptr);
  199015. #endif
  199016. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  199017. /* swap location of alpha bytes from ARGB to RGBA */
  199018. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  199019. png_set_swap_alpha(png_ptr);
  199020. #endif
  199021. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  199022. /* Get rid of filler (OR ALPHA) bytes, pack XRGB/RGBX/ARGB/RGBA into
  199023. * RGB (4 channels -> 3 channels). The second parameter is not used.
  199024. */
  199025. if (transforms & PNG_TRANSFORM_STRIP_FILLER)
  199026. png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
  199027. #endif
  199028. #if defined(PNG_WRITE_BGR_SUPPORTED)
  199029. /* flip BGR pixels to RGB */
  199030. if (transforms & PNG_TRANSFORM_BGR)
  199031. png_set_bgr(png_ptr);
  199032. #endif
  199033. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  199034. /* swap bytes of 16-bit files to most significant byte first */
  199035. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  199036. png_set_swap(png_ptr);
  199037. #endif
  199038. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  199039. /* swap bits of 1, 2, 4 bit packed pixel formats */
  199040. if (transforms & PNG_TRANSFORM_PACKSWAP)
  199041. png_set_packswap(png_ptr);
  199042. #endif
  199043. /* ----------------------- end of transformations ------------------- */
  199044. /* write the bits */
  199045. if (info_ptr->valid & PNG_INFO_IDAT)
  199046. png_write_image(png_ptr, info_ptr->row_pointers);
  199047. /* It is REQUIRED to call this to finish writing the rest of the file */
  199048. png_write_end(png_ptr, info_ptr);
  199049. transforms = transforms; /* quiet compiler warnings */
  199050. params = params;
  199051. }
  199052. #endif
  199053. #endif /* PNG_WRITE_SUPPORTED */
  199054. /*** End of inlined file: pngwrite.c ***/
  199055. /*** Start of inlined file: pngwtran.c ***/
  199056. /* pngwtran.c - transforms the data in a row for PNG writers
  199057. *
  199058. * Last changed in libpng 1.2.9 April 14, 2006
  199059. * For conditions of distribution and use, see copyright notice in png.h
  199060. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  199061. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  199062. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  199063. */
  199064. #define PNG_INTERNAL
  199065. #ifdef PNG_WRITE_SUPPORTED
  199066. /* Transform the data according to the user's wishes. The order of
  199067. * transformations is significant.
  199068. */
  199069. void /* PRIVATE */
  199070. png_do_write_transformations(png_structp png_ptr)
  199071. {
  199072. png_debug(1, "in png_do_write_transformations\n");
  199073. if (png_ptr == NULL)
  199074. return;
  199075. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  199076. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  199077. if(png_ptr->write_user_transform_fn != NULL)
  199078. (*(png_ptr->write_user_transform_fn)) /* user write transform function */
  199079. (png_ptr, /* png_ptr */
  199080. &(png_ptr->row_info), /* row_info: */
  199081. /* png_uint_32 width; width of row */
  199082. /* png_uint_32 rowbytes; number of bytes in row */
  199083. /* png_byte color_type; color type of pixels */
  199084. /* png_byte bit_depth; bit depth of samples */
  199085. /* png_byte channels; number of channels (1-4) */
  199086. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  199087. png_ptr->row_buf + 1); /* start of pixel data for row */
  199088. #endif
  199089. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  199090. if (png_ptr->transformations & PNG_FILLER)
  199091. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  199092. png_ptr->flags);
  199093. #endif
  199094. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  199095. if (png_ptr->transformations & PNG_PACKSWAP)
  199096. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199097. #endif
  199098. #if defined(PNG_WRITE_PACK_SUPPORTED)
  199099. if (png_ptr->transformations & PNG_PACK)
  199100. png_do_pack(&(png_ptr->row_info), png_ptr->row_buf + 1,
  199101. (png_uint_32)png_ptr->bit_depth);
  199102. #endif
  199103. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  199104. if (png_ptr->transformations & PNG_SWAP_BYTES)
  199105. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199106. #endif
  199107. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  199108. if (png_ptr->transformations & PNG_SHIFT)
  199109. png_do_shift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  199110. &(png_ptr->shift));
  199111. #endif
  199112. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  199113. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  199114. png_do_write_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199115. #endif
  199116. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  199117. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  199118. png_do_write_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199119. #endif
  199120. #if defined(PNG_WRITE_BGR_SUPPORTED)
  199121. if (png_ptr->transformations & PNG_BGR)
  199122. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199123. #endif
  199124. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  199125. if (png_ptr->transformations & PNG_INVERT_MONO)
  199126. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199127. #endif
  199128. }
  199129. #if defined(PNG_WRITE_PACK_SUPPORTED)
  199130. /* Pack pixels into bytes. Pass the true bit depth in bit_depth. The
  199131. * row_info bit depth should be 8 (one pixel per byte). The channels
  199132. * should be 1 (this only happens on grayscale and paletted images).
  199133. */
  199134. void /* PRIVATE */
  199135. png_do_pack(png_row_infop row_info, png_bytep row, png_uint_32 bit_depth)
  199136. {
  199137. png_debug(1, "in png_do_pack\n");
  199138. if (row_info->bit_depth == 8 &&
  199139. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  199140. row != NULL && row_info != NULL &&
  199141. #endif
  199142. row_info->channels == 1)
  199143. {
  199144. switch ((int)bit_depth)
  199145. {
  199146. case 1:
  199147. {
  199148. png_bytep sp, dp;
  199149. int mask, v;
  199150. png_uint_32 i;
  199151. png_uint_32 row_width = row_info->width;
  199152. sp = row;
  199153. dp = row;
  199154. mask = 0x80;
  199155. v = 0;
  199156. for (i = 0; i < row_width; i++)
  199157. {
  199158. if (*sp != 0)
  199159. v |= mask;
  199160. sp++;
  199161. if (mask > 1)
  199162. mask >>= 1;
  199163. else
  199164. {
  199165. mask = 0x80;
  199166. *dp = (png_byte)v;
  199167. dp++;
  199168. v = 0;
  199169. }
  199170. }
  199171. if (mask != 0x80)
  199172. *dp = (png_byte)v;
  199173. break;
  199174. }
  199175. case 2:
  199176. {
  199177. png_bytep sp, dp;
  199178. int shift, v;
  199179. png_uint_32 i;
  199180. png_uint_32 row_width = row_info->width;
  199181. sp = row;
  199182. dp = row;
  199183. shift = 6;
  199184. v = 0;
  199185. for (i = 0; i < row_width; i++)
  199186. {
  199187. png_byte value;
  199188. value = (png_byte)(*sp & 0x03);
  199189. v |= (value << shift);
  199190. if (shift == 0)
  199191. {
  199192. shift = 6;
  199193. *dp = (png_byte)v;
  199194. dp++;
  199195. v = 0;
  199196. }
  199197. else
  199198. shift -= 2;
  199199. sp++;
  199200. }
  199201. if (shift != 6)
  199202. *dp = (png_byte)v;
  199203. break;
  199204. }
  199205. case 4:
  199206. {
  199207. png_bytep sp, dp;
  199208. int shift, v;
  199209. png_uint_32 i;
  199210. png_uint_32 row_width = row_info->width;
  199211. sp = row;
  199212. dp = row;
  199213. shift = 4;
  199214. v = 0;
  199215. for (i = 0; i < row_width; i++)
  199216. {
  199217. png_byte value;
  199218. value = (png_byte)(*sp & 0x0f);
  199219. v |= (value << shift);
  199220. if (shift == 0)
  199221. {
  199222. shift = 4;
  199223. *dp = (png_byte)v;
  199224. dp++;
  199225. v = 0;
  199226. }
  199227. else
  199228. shift -= 4;
  199229. sp++;
  199230. }
  199231. if (shift != 4)
  199232. *dp = (png_byte)v;
  199233. break;
  199234. }
  199235. }
  199236. row_info->bit_depth = (png_byte)bit_depth;
  199237. row_info->pixel_depth = (png_byte)(bit_depth * row_info->channels);
  199238. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  199239. row_info->width);
  199240. }
  199241. }
  199242. #endif
  199243. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  199244. /* Shift pixel values to take advantage of whole range. Pass the
  199245. * true number of bits in bit_depth. The row should be packed
  199246. * according to row_info->bit_depth. Thus, if you had a row of
  199247. * bit depth 4, but the pixels only had values from 0 to 7, you
  199248. * would pass 3 as bit_depth, and this routine would translate the
  199249. * data to 0 to 15.
  199250. */
  199251. void /* PRIVATE */
  199252. png_do_shift(png_row_infop row_info, png_bytep row, png_color_8p bit_depth)
  199253. {
  199254. png_debug(1, "in png_do_shift\n");
  199255. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  199256. if (row != NULL && row_info != NULL &&
  199257. #else
  199258. if (
  199259. #endif
  199260. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  199261. {
  199262. int shift_start[4], shift_dec[4];
  199263. int channels = 0;
  199264. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  199265. {
  199266. shift_start[channels] = row_info->bit_depth - bit_depth->red;
  199267. shift_dec[channels] = bit_depth->red;
  199268. channels++;
  199269. shift_start[channels] = row_info->bit_depth - bit_depth->green;
  199270. shift_dec[channels] = bit_depth->green;
  199271. channels++;
  199272. shift_start[channels] = row_info->bit_depth - bit_depth->blue;
  199273. shift_dec[channels] = bit_depth->blue;
  199274. channels++;
  199275. }
  199276. else
  199277. {
  199278. shift_start[channels] = row_info->bit_depth - bit_depth->gray;
  199279. shift_dec[channels] = bit_depth->gray;
  199280. channels++;
  199281. }
  199282. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  199283. {
  199284. shift_start[channels] = row_info->bit_depth - bit_depth->alpha;
  199285. shift_dec[channels] = bit_depth->alpha;
  199286. channels++;
  199287. }
  199288. /* with low row depths, could only be grayscale, so one channel */
  199289. if (row_info->bit_depth < 8)
  199290. {
  199291. png_bytep bp = row;
  199292. png_uint_32 i;
  199293. png_byte mask;
  199294. png_uint_32 row_bytes = row_info->rowbytes;
  199295. if (bit_depth->gray == 1 && row_info->bit_depth == 2)
  199296. mask = 0x55;
  199297. else if (row_info->bit_depth == 4 && bit_depth->gray == 3)
  199298. mask = 0x11;
  199299. else
  199300. mask = 0xff;
  199301. for (i = 0; i < row_bytes; i++, bp++)
  199302. {
  199303. png_uint_16 v;
  199304. int j;
  199305. v = *bp;
  199306. *bp = 0;
  199307. for (j = shift_start[0]; j > -shift_dec[0]; j -= shift_dec[0])
  199308. {
  199309. if (j > 0)
  199310. *bp |= (png_byte)((v << j) & 0xff);
  199311. else
  199312. *bp |= (png_byte)((v >> (-j)) & mask);
  199313. }
  199314. }
  199315. }
  199316. else if (row_info->bit_depth == 8)
  199317. {
  199318. png_bytep bp = row;
  199319. png_uint_32 i;
  199320. png_uint_32 istop = channels * row_info->width;
  199321. for (i = 0; i < istop; i++, bp++)
  199322. {
  199323. png_uint_16 v;
  199324. int j;
  199325. int c = (int)(i%channels);
  199326. v = *bp;
  199327. *bp = 0;
  199328. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  199329. {
  199330. if (j > 0)
  199331. *bp |= (png_byte)((v << j) & 0xff);
  199332. else
  199333. *bp |= (png_byte)((v >> (-j)) & 0xff);
  199334. }
  199335. }
  199336. }
  199337. else
  199338. {
  199339. png_bytep bp;
  199340. png_uint_32 i;
  199341. png_uint_32 istop = channels * row_info->width;
  199342. for (bp = row, i = 0; i < istop; i++)
  199343. {
  199344. int c = (int)(i%channels);
  199345. png_uint_16 value, v;
  199346. int j;
  199347. v = (png_uint_16)(((png_uint_16)(*bp) << 8) + *(bp + 1));
  199348. value = 0;
  199349. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  199350. {
  199351. if (j > 0)
  199352. value |= (png_uint_16)((v << j) & (png_uint_16)0xffff);
  199353. else
  199354. value |= (png_uint_16)((v >> (-j)) & (png_uint_16)0xffff);
  199355. }
  199356. *bp++ = (png_byte)(value >> 8);
  199357. *bp++ = (png_byte)(value & 0xff);
  199358. }
  199359. }
  199360. }
  199361. }
  199362. #endif
  199363. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  199364. void /* PRIVATE */
  199365. png_do_write_swap_alpha(png_row_infop row_info, png_bytep row)
  199366. {
  199367. png_debug(1, "in png_do_write_swap_alpha\n");
  199368. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  199369. if (row != NULL && row_info != NULL)
  199370. #endif
  199371. {
  199372. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  199373. {
  199374. /* This converts from ARGB to RGBA */
  199375. if (row_info->bit_depth == 8)
  199376. {
  199377. png_bytep sp, dp;
  199378. png_uint_32 i;
  199379. png_uint_32 row_width = row_info->width;
  199380. for (i = 0, sp = dp = row; i < row_width; i++)
  199381. {
  199382. png_byte save = *(sp++);
  199383. *(dp++) = *(sp++);
  199384. *(dp++) = *(sp++);
  199385. *(dp++) = *(sp++);
  199386. *(dp++) = save;
  199387. }
  199388. }
  199389. /* This converts from AARRGGBB to RRGGBBAA */
  199390. else
  199391. {
  199392. png_bytep sp, dp;
  199393. png_uint_32 i;
  199394. png_uint_32 row_width = row_info->width;
  199395. for (i = 0, sp = dp = row; i < row_width; i++)
  199396. {
  199397. png_byte save[2];
  199398. save[0] = *(sp++);
  199399. save[1] = *(sp++);
  199400. *(dp++) = *(sp++);
  199401. *(dp++) = *(sp++);
  199402. *(dp++) = *(sp++);
  199403. *(dp++) = *(sp++);
  199404. *(dp++) = *(sp++);
  199405. *(dp++) = *(sp++);
  199406. *(dp++) = save[0];
  199407. *(dp++) = save[1];
  199408. }
  199409. }
  199410. }
  199411. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  199412. {
  199413. /* This converts from AG to GA */
  199414. if (row_info->bit_depth == 8)
  199415. {
  199416. png_bytep sp, dp;
  199417. png_uint_32 i;
  199418. png_uint_32 row_width = row_info->width;
  199419. for (i = 0, sp = dp = row; i < row_width; i++)
  199420. {
  199421. png_byte save = *(sp++);
  199422. *(dp++) = *(sp++);
  199423. *(dp++) = save;
  199424. }
  199425. }
  199426. /* This converts from AAGG to GGAA */
  199427. else
  199428. {
  199429. png_bytep sp, dp;
  199430. png_uint_32 i;
  199431. png_uint_32 row_width = row_info->width;
  199432. for (i = 0, sp = dp = row; i < row_width; i++)
  199433. {
  199434. png_byte save[2];
  199435. save[0] = *(sp++);
  199436. save[1] = *(sp++);
  199437. *(dp++) = *(sp++);
  199438. *(dp++) = *(sp++);
  199439. *(dp++) = save[0];
  199440. *(dp++) = save[1];
  199441. }
  199442. }
  199443. }
  199444. }
  199445. }
  199446. #endif
  199447. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  199448. void /* PRIVATE */
  199449. png_do_write_invert_alpha(png_row_infop row_info, png_bytep row)
  199450. {
  199451. png_debug(1, "in png_do_write_invert_alpha\n");
  199452. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  199453. if (row != NULL && row_info != NULL)
  199454. #endif
  199455. {
  199456. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  199457. {
  199458. /* This inverts the alpha channel in RGBA */
  199459. if (row_info->bit_depth == 8)
  199460. {
  199461. png_bytep sp, dp;
  199462. png_uint_32 i;
  199463. png_uint_32 row_width = row_info->width;
  199464. for (i = 0, sp = dp = row; i < row_width; i++)
  199465. {
  199466. /* does nothing
  199467. *(dp++) = *(sp++);
  199468. *(dp++) = *(sp++);
  199469. *(dp++) = *(sp++);
  199470. */
  199471. sp+=3; dp = sp;
  199472. *(dp++) = (png_byte)(255 - *(sp++));
  199473. }
  199474. }
  199475. /* This inverts the alpha channel in RRGGBBAA */
  199476. else
  199477. {
  199478. png_bytep sp, dp;
  199479. png_uint_32 i;
  199480. png_uint_32 row_width = row_info->width;
  199481. for (i = 0, sp = dp = row; i < row_width; i++)
  199482. {
  199483. /* does nothing
  199484. *(dp++) = *(sp++);
  199485. *(dp++) = *(sp++);
  199486. *(dp++) = *(sp++);
  199487. *(dp++) = *(sp++);
  199488. *(dp++) = *(sp++);
  199489. *(dp++) = *(sp++);
  199490. */
  199491. sp+=6; dp = sp;
  199492. *(dp++) = (png_byte)(255 - *(sp++));
  199493. *(dp++) = (png_byte)(255 - *(sp++));
  199494. }
  199495. }
  199496. }
  199497. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  199498. {
  199499. /* This inverts the alpha channel in GA */
  199500. if (row_info->bit_depth == 8)
  199501. {
  199502. png_bytep sp, dp;
  199503. png_uint_32 i;
  199504. png_uint_32 row_width = row_info->width;
  199505. for (i = 0, sp = dp = row; i < row_width; i++)
  199506. {
  199507. *(dp++) = *(sp++);
  199508. *(dp++) = (png_byte)(255 - *(sp++));
  199509. }
  199510. }
  199511. /* This inverts the alpha channel in GGAA */
  199512. else
  199513. {
  199514. png_bytep sp, dp;
  199515. png_uint_32 i;
  199516. png_uint_32 row_width = row_info->width;
  199517. for (i = 0, sp = dp = row; i < row_width; i++)
  199518. {
  199519. /* does nothing
  199520. *(dp++) = *(sp++);
  199521. *(dp++) = *(sp++);
  199522. */
  199523. sp+=2; dp = sp;
  199524. *(dp++) = (png_byte)(255 - *(sp++));
  199525. *(dp++) = (png_byte)(255 - *(sp++));
  199526. }
  199527. }
  199528. }
  199529. }
  199530. }
  199531. #endif
  199532. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  199533. /* undoes intrapixel differencing */
  199534. void /* PRIVATE */
  199535. png_do_write_intrapixel(png_row_infop row_info, png_bytep row)
  199536. {
  199537. png_debug(1, "in png_do_write_intrapixel\n");
  199538. if (
  199539. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  199540. row != NULL && row_info != NULL &&
  199541. #endif
  199542. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  199543. {
  199544. int bytes_per_pixel;
  199545. png_uint_32 row_width = row_info->width;
  199546. if (row_info->bit_depth == 8)
  199547. {
  199548. png_bytep rp;
  199549. png_uint_32 i;
  199550. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  199551. bytes_per_pixel = 3;
  199552. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  199553. bytes_per_pixel = 4;
  199554. else
  199555. return;
  199556. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  199557. {
  199558. *(rp) = (png_byte)((*rp - *(rp+1))&0xff);
  199559. *(rp+2) = (png_byte)((*(rp+2) - *(rp+1))&0xff);
  199560. }
  199561. }
  199562. else if (row_info->bit_depth == 16)
  199563. {
  199564. png_bytep rp;
  199565. png_uint_32 i;
  199566. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  199567. bytes_per_pixel = 6;
  199568. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  199569. bytes_per_pixel = 8;
  199570. else
  199571. return;
  199572. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  199573. {
  199574. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  199575. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  199576. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  199577. png_uint_32 red = (png_uint_32)((s0-s1) & 0xffffL);
  199578. png_uint_32 blue = (png_uint_32)((s2-s1) & 0xffffL);
  199579. *(rp ) = (png_byte)((red >> 8) & 0xff);
  199580. *(rp+1) = (png_byte)(red & 0xff);
  199581. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  199582. *(rp+5) = (png_byte)(blue & 0xff);
  199583. }
  199584. }
  199585. }
  199586. }
  199587. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  199588. #endif /* PNG_WRITE_SUPPORTED */
  199589. /*** End of inlined file: pngwtran.c ***/
  199590. /*** Start of inlined file: pngwutil.c ***/
  199591. /* pngwutil.c - utilities to write a PNG file
  199592. *
  199593. * Last changed in libpng 1.2.20 Septhember 3, 2007
  199594. * For conditions of distribution and use, see copyright notice in png.h
  199595. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  199596. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  199597. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  199598. */
  199599. #define PNG_INTERNAL
  199600. #ifdef PNG_WRITE_SUPPORTED
  199601. /* Place a 32-bit number into a buffer in PNG byte order. We work
  199602. * with unsigned numbers for convenience, although one supported
  199603. * ancillary chunk uses signed (two's complement) numbers.
  199604. */
  199605. void PNGAPI
  199606. png_save_uint_32(png_bytep buf, png_uint_32 i)
  199607. {
  199608. buf[0] = (png_byte)((i >> 24) & 0xff);
  199609. buf[1] = (png_byte)((i >> 16) & 0xff);
  199610. buf[2] = (png_byte)((i >> 8) & 0xff);
  199611. buf[3] = (png_byte)(i & 0xff);
  199612. }
  199613. /* The png_save_int_32 function assumes integers are stored in two's
  199614. * complement format. If this isn't the case, then this routine needs to
  199615. * be modified to write data in two's complement format.
  199616. */
  199617. void PNGAPI
  199618. png_save_int_32(png_bytep buf, png_int_32 i)
  199619. {
  199620. buf[0] = (png_byte)((i >> 24) & 0xff);
  199621. buf[1] = (png_byte)((i >> 16) & 0xff);
  199622. buf[2] = (png_byte)((i >> 8) & 0xff);
  199623. buf[3] = (png_byte)(i & 0xff);
  199624. }
  199625. /* Place a 16-bit number into a buffer in PNG byte order.
  199626. * The parameter is declared unsigned int, not png_uint_16,
  199627. * just to avoid potential problems on pre-ANSI C compilers.
  199628. */
  199629. void PNGAPI
  199630. png_save_uint_16(png_bytep buf, unsigned int i)
  199631. {
  199632. buf[0] = (png_byte)((i >> 8) & 0xff);
  199633. buf[1] = (png_byte)(i & 0xff);
  199634. }
  199635. /* Write a PNG chunk all at once. The type is an array of ASCII characters
  199636. * representing the chunk name. The array must be at least 4 bytes in
  199637. * length, and does not need to be null terminated. To be safe, pass the
  199638. * pre-defined chunk names here, and if you need a new one, define it
  199639. * where the others are defined. The length is the length of the data.
  199640. * All the data must be present. If that is not possible, use the
  199641. * png_write_chunk_start(), png_write_chunk_data(), and png_write_chunk_end()
  199642. * functions instead.
  199643. */
  199644. void PNGAPI
  199645. png_write_chunk(png_structp png_ptr, png_bytep chunk_name,
  199646. png_bytep data, png_size_t length)
  199647. {
  199648. if(png_ptr == NULL) return;
  199649. png_write_chunk_start(png_ptr, chunk_name, (png_uint_32)length);
  199650. png_write_chunk_data(png_ptr, data, length);
  199651. png_write_chunk_end(png_ptr);
  199652. }
  199653. /* Write the start of a PNG chunk. The type is the chunk type.
  199654. * The total_length is the sum of the lengths of all the data you will be
  199655. * passing in png_write_chunk_data().
  199656. */
  199657. void PNGAPI
  199658. png_write_chunk_start(png_structp png_ptr, png_bytep chunk_name,
  199659. png_uint_32 length)
  199660. {
  199661. png_byte buf[4];
  199662. png_debug2(0, "Writing %s chunk (%lu bytes)\n", chunk_name, length);
  199663. if(png_ptr == NULL) return;
  199664. /* write the length */
  199665. png_save_uint_32(buf, length);
  199666. png_write_data(png_ptr, buf, (png_size_t)4);
  199667. /* write the chunk name */
  199668. png_write_data(png_ptr, chunk_name, (png_size_t)4);
  199669. /* reset the crc and run it over the chunk name */
  199670. png_reset_crc(png_ptr);
  199671. png_calculate_crc(png_ptr, chunk_name, (png_size_t)4);
  199672. }
  199673. /* Write the data of a PNG chunk started with png_write_chunk_start().
  199674. * Note that multiple calls to this function are allowed, and that the
  199675. * sum of the lengths from these calls *must* add up to the total_length
  199676. * given to png_write_chunk_start().
  199677. */
  199678. void PNGAPI
  199679. png_write_chunk_data(png_structp png_ptr, png_bytep data, png_size_t length)
  199680. {
  199681. /* write the data, and run the CRC over it */
  199682. if(png_ptr == NULL) return;
  199683. if (data != NULL && length > 0)
  199684. {
  199685. png_calculate_crc(png_ptr, data, length);
  199686. png_write_data(png_ptr, data, length);
  199687. }
  199688. }
  199689. /* Finish a chunk started with png_write_chunk_start(). */
  199690. void PNGAPI
  199691. png_write_chunk_end(png_structp png_ptr)
  199692. {
  199693. png_byte buf[4];
  199694. if(png_ptr == NULL) return;
  199695. /* write the crc */
  199696. png_save_uint_32(buf, png_ptr->crc);
  199697. png_write_data(png_ptr, buf, (png_size_t)4);
  199698. }
  199699. /* Simple function to write the signature. If we have already written
  199700. * the magic bytes of the signature, or more likely, the PNG stream is
  199701. * being embedded into another stream and doesn't need its own signature,
  199702. * we should call png_set_sig_bytes() to tell libpng how many of the
  199703. * bytes have already been written.
  199704. */
  199705. void /* PRIVATE */
  199706. png_write_sig(png_structp png_ptr)
  199707. {
  199708. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  199709. /* write the rest of the 8 byte signature */
  199710. png_write_data(png_ptr, &png_signature[png_ptr->sig_bytes],
  199711. (png_size_t)8 - png_ptr->sig_bytes);
  199712. if(png_ptr->sig_bytes < 3)
  199713. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  199714. }
  199715. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_iCCP_SUPPORTED)
  199716. /*
  199717. * This pair of functions encapsulates the operation of (a) compressing a
  199718. * text string, and (b) issuing it later as a series of chunk data writes.
  199719. * The compression_state structure is shared context for these functions
  199720. * set up by the caller in order to make the whole mess thread-safe.
  199721. */
  199722. typedef struct
  199723. {
  199724. char *input; /* the uncompressed input data */
  199725. int input_len; /* its length */
  199726. int num_output_ptr; /* number of output pointers used */
  199727. int max_output_ptr; /* size of output_ptr */
  199728. png_charpp output_ptr; /* array of pointers to output */
  199729. } compression_state;
  199730. /* compress given text into storage in the png_ptr structure */
  199731. static int /* PRIVATE */
  199732. png_text_compress(png_structp png_ptr,
  199733. png_charp text, png_size_t text_len, int compression,
  199734. compression_state *comp)
  199735. {
  199736. int ret;
  199737. comp->num_output_ptr = 0;
  199738. comp->max_output_ptr = 0;
  199739. comp->output_ptr = NULL;
  199740. comp->input = NULL;
  199741. comp->input_len = 0;
  199742. /* we may just want to pass the text right through */
  199743. if (compression == PNG_TEXT_COMPRESSION_NONE)
  199744. {
  199745. comp->input = text;
  199746. comp->input_len = text_len;
  199747. return((int)text_len);
  199748. }
  199749. if (compression >= PNG_TEXT_COMPRESSION_LAST)
  199750. {
  199751. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  199752. char msg[50];
  199753. png_snprintf(msg, 50, "Unknown compression type %d", compression);
  199754. png_warning(png_ptr, msg);
  199755. #else
  199756. png_warning(png_ptr, "Unknown compression type");
  199757. #endif
  199758. }
  199759. /* We can't write the chunk until we find out how much data we have,
  199760. * which means we need to run the compressor first and save the
  199761. * output. This shouldn't be a problem, as the vast majority of
  199762. * comments should be reasonable, but we will set up an array of
  199763. * malloc'd pointers to be sure.
  199764. *
  199765. * If we knew the application was well behaved, we could simplify this
  199766. * greatly by assuming we can always malloc an output buffer large
  199767. * enough to hold the compressed text ((1001 * text_len / 1000) + 12)
  199768. * and malloc this directly. The only time this would be a bad idea is
  199769. * if we can't malloc more than 64K and we have 64K of random input
  199770. * data, or if the input string is incredibly large (although this
  199771. * wouldn't cause a failure, just a slowdown due to swapping).
  199772. */
  199773. /* set up the compression buffers */
  199774. png_ptr->zstream.avail_in = (uInt)text_len;
  199775. png_ptr->zstream.next_in = (Bytef *)text;
  199776. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  199777. png_ptr->zstream.next_out = (Bytef *)png_ptr->zbuf;
  199778. /* this is the same compression loop as in png_write_row() */
  199779. do
  199780. {
  199781. /* compress the data */
  199782. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  199783. if (ret != Z_OK)
  199784. {
  199785. /* error */
  199786. if (png_ptr->zstream.msg != NULL)
  199787. png_error(png_ptr, png_ptr->zstream.msg);
  199788. else
  199789. png_error(png_ptr, "zlib error");
  199790. }
  199791. /* check to see if we need more room */
  199792. if (!(png_ptr->zstream.avail_out))
  199793. {
  199794. /* make sure the output array has room */
  199795. if (comp->num_output_ptr >= comp->max_output_ptr)
  199796. {
  199797. int old_max;
  199798. old_max = comp->max_output_ptr;
  199799. comp->max_output_ptr = comp->num_output_ptr + 4;
  199800. if (comp->output_ptr != NULL)
  199801. {
  199802. png_charpp old_ptr;
  199803. old_ptr = comp->output_ptr;
  199804. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  199805. (png_uint_32)(comp->max_output_ptr *
  199806. png_sizeof (png_charpp)));
  199807. png_memcpy(comp->output_ptr, old_ptr, old_max
  199808. * png_sizeof (png_charp));
  199809. png_free(png_ptr, old_ptr);
  199810. }
  199811. else
  199812. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  199813. (png_uint_32)(comp->max_output_ptr *
  199814. png_sizeof (png_charp)));
  199815. }
  199816. /* save the data */
  199817. comp->output_ptr[comp->num_output_ptr] = (png_charp)png_malloc(png_ptr,
  199818. (png_uint_32)png_ptr->zbuf_size);
  199819. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  199820. png_ptr->zbuf_size);
  199821. comp->num_output_ptr++;
  199822. /* and reset the buffer */
  199823. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  199824. png_ptr->zstream.next_out = png_ptr->zbuf;
  199825. }
  199826. /* continue until we don't have any more to compress */
  199827. } while (png_ptr->zstream.avail_in);
  199828. /* finish the compression */
  199829. do
  199830. {
  199831. /* tell zlib we are finished */
  199832. ret = deflate(&png_ptr->zstream, Z_FINISH);
  199833. if (ret == Z_OK)
  199834. {
  199835. /* check to see if we need more room */
  199836. if (!(png_ptr->zstream.avail_out))
  199837. {
  199838. /* check to make sure our output array has room */
  199839. if (comp->num_output_ptr >= comp->max_output_ptr)
  199840. {
  199841. int old_max;
  199842. old_max = comp->max_output_ptr;
  199843. comp->max_output_ptr = comp->num_output_ptr + 4;
  199844. if (comp->output_ptr != NULL)
  199845. {
  199846. png_charpp old_ptr;
  199847. old_ptr = comp->output_ptr;
  199848. /* This could be optimized to realloc() */
  199849. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  199850. (png_uint_32)(comp->max_output_ptr *
  199851. png_sizeof (png_charpp)));
  199852. png_memcpy(comp->output_ptr, old_ptr,
  199853. old_max * png_sizeof (png_charp));
  199854. png_free(png_ptr, old_ptr);
  199855. }
  199856. else
  199857. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  199858. (png_uint_32)(comp->max_output_ptr *
  199859. png_sizeof (png_charp)));
  199860. }
  199861. /* save off the data */
  199862. comp->output_ptr[comp->num_output_ptr] =
  199863. (png_charp)png_malloc(png_ptr, (png_uint_32)png_ptr->zbuf_size);
  199864. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  199865. png_ptr->zbuf_size);
  199866. comp->num_output_ptr++;
  199867. /* and reset the buffer pointers */
  199868. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  199869. png_ptr->zstream.next_out = png_ptr->zbuf;
  199870. }
  199871. }
  199872. else if (ret != Z_STREAM_END)
  199873. {
  199874. /* we got an error */
  199875. if (png_ptr->zstream.msg != NULL)
  199876. png_error(png_ptr, png_ptr->zstream.msg);
  199877. else
  199878. png_error(png_ptr, "zlib error");
  199879. }
  199880. } while (ret != Z_STREAM_END);
  199881. /* text length is number of buffers plus last buffer */
  199882. text_len = png_ptr->zbuf_size * comp->num_output_ptr;
  199883. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  199884. text_len += png_ptr->zbuf_size - (png_size_t)png_ptr->zstream.avail_out;
  199885. return((int)text_len);
  199886. }
  199887. /* ship the compressed text out via chunk writes */
  199888. static void /* PRIVATE */
  199889. png_write_compressed_data_out(png_structp png_ptr, compression_state *comp)
  199890. {
  199891. int i;
  199892. /* handle the no-compression case */
  199893. if (comp->input)
  199894. {
  199895. png_write_chunk_data(png_ptr, (png_bytep)comp->input,
  199896. (png_size_t)comp->input_len);
  199897. return;
  199898. }
  199899. /* write saved output buffers, if any */
  199900. for (i = 0; i < comp->num_output_ptr; i++)
  199901. {
  199902. png_write_chunk_data(png_ptr,(png_bytep)comp->output_ptr[i],
  199903. png_ptr->zbuf_size);
  199904. png_free(png_ptr, comp->output_ptr[i]);
  199905. comp->output_ptr[i]=NULL;
  199906. }
  199907. if (comp->max_output_ptr != 0)
  199908. png_free(png_ptr, comp->output_ptr);
  199909. comp->output_ptr=NULL;
  199910. /* write anything left in zbuf */
  199911. if (png_ptr->zstream.avail_out < (png_uint_32)png_ptr->zbuf_size)
  199912. png_write_chunk_data(png_ptr, png_ptr->zbuf,
  199913. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  199914. /* reset zlib for another zTXt/iTXt or image data */
  199915. deflateReset(&png_ptr->zstream);
  199916. png_ptr->zstream.data_type = Z_BINARY;
  199917. }
  199918. #endif
  199919. /* Write the IHDR chunk, and update the png_struct with the necessary
  199920. * information. Note that the rest of this code depends upon this
  199921. * information being correct.
  199922. */
  199923. void /* PRIVATE */
  199924. png_write_IHDR(png_structp png_ptr, png_uint_32 width, png_uint_32 height,
  199925. int bit_depth, int color_type, int compression_type, int filter_type,
  199926. int interlace_type)
  199927. {
  199928. #ifdef PNG_USE_LOCAL_ARRAYS
  199929. PNG_IHDR;
  199930. #endif
  199931. png_byte buf[13]; /* buffer to store the IHDR info */
  199932. png_debug(1, "in png_write_IHDR\n");
  199933. /* Check that we have valid input data from the application info */
  199934. switch (color_type)
  199935. {
  199936. case PNG_COLOR_TYPE_GRAY:
  199937. switch (bit_depth)
  199938. {
  199939. case 1:
  199940. case 2:
  199941. case 4:
  199942. case 8:
  199943. case 16: png_ptr->channels = 1; break;
  199944. default: png_error(png_ptr,"Invalid bit depth for grayscale image");
  199945. }
  199946. break;
  199947. case PNG_COLOR_TYPE_RGB:
  199948. if (bit_depth != 8 && bit_depth != 16)
  199949. png_error(png_ptr, "Invalid bit depth for RGB image");
  199950. png_ptr->channels = 3;
  199951. break;
  199952. case PNG_COLOR_TYPE_PALETTE:
  199953. switch (bit_depth)
  199954. {
  199955. case 1:
  199956. case 2:
  199957. case 4:
  199958. case 8: png_ptr->channels = 1; break;
  199959. default: png_error(png_ptr, "Invalid bit depth for paletted image");
  199960. }
  199961. break;
  199962. case PNG_COLOR_TYPE_GRAY_ALPHA:
  199963. if (bit_depth != 8 && bit_depth != 16)
  199964. png_error(png_ptr, "Invalid bit depth for grayscale+alpha image");
  199965. png_ptr->channels = 2;
  199966. break;
  199967. case PNG_COLOR_TYPE_RGB_ALPHA:
  199968. if (bit_depth != 8 && bit_depth != 16)
  199969. png_error(png_ptr, "Invalid bit depth for RGBA image");
  199970. png_ptr->channels = 4;
  199971. break;
  199972. default:
  199973. png_error(png_ptr, "Invalid image color type specified");
  199974. }
  199975. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  199976. {
  199977. png_warning(png_ptr, "Invalid compression type specified");
  199978. compression_type = PNG_COMPRESSION_TYPE_BASE;
  199979. }
  199980. /* Write filter_method 64 (intrapixel differencing) only if
  199981. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  199982. * 2. Libpng did not write a PNG signature (this filter_method is only
  199983. * used in PNG datastreams that are embedded in MNG datastreams) and
  199984. * 3. The application called png_permit_mng_features with a mask that
  199985. * included PNG_FLAG_MNG_FILTER_64 and
  199986. * 4. The filter_method is 64 and
  199987. * 5. The color_type is RGB or RGBA
  199988. */
  199989. if (
  199990. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  199991. !((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  199992. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  199993. (color_type == PNG_COLOR_TYPE_RGB ||
  199994. color_type == PNG_COLOR_TYPE_RGB_ALPHA) &&
  199995. (filter_type == PNG_INTRAPIXEL_DIFFERENCING)) &&
  199996. #endif
  199997. filter_type != PNG_FILTER_TYPE_BASE)
  199998. {
  199999. png_warning(png_ptr, "Invalid filter type specified");
  200000. filter_type = PNG_FILTER_TYPE_BASE;
  200001. }
  200002. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  200003. if (interlace_type != PNG_INTERLACE_NONE &&
  200004. interlace_type != PNG_INTERLACE_ADAM7)
  200005. {
  200006. png_warning(png_ptr, "Invalid interlace type specified");
  200007. interlace_type = PNG_INTERLACE_ADAM7;
  200008. }
  200009. #else
  200010. interlace_type=PNG_INTERLACE_NONE;
  200011. #endif
  200012. /* save off the relevent information */
  200013. png_ptr->bit_depth = (png_byte)bit_depth;
  200014. png_ptr->color_type = (png_byte)color_type;
  200015. png_ptr->interlaced = (png_byte)interlace_type;
  200016. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200017. png_ptr->filter_type = (png_byte)filter_type;
  200018. #endif
  200019. png_ptr->compression_type = (png_byte)compression_type;
  200020. png_ptr->width = width;
  200021. png_ptr->height = height;
  200022. png_ptr->pixel_depth = (png_byte)(bit_depth * png_ptr->channels);
  200023. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, width);
  200024. /* set the usr info, so any transformations can modify it */
  200025. png_ptr->usr_width = png_ptr->width;
  200026. png_ptr->usr_bit_depth = png_ptr->bit_depth;
  200027. png_ptr->usr_channels = png_ptr->channels;
  200028. /* pack the header information into the buffer */
  200029. png_save_uint_32(buf, width);
  200030. png_save_uint_32(buf + 4, height);
  200031. buf[8] = (png_byte)bit_depth;
  200032. buf[9] = (png_byte)color_type;
  200033. buf[10] = (png_byte)compression_type;
  200034. buf[11] = (png_byte)filter_type;
  200035. buf[12] = (png_byte)interlace_type;
  200036. /* write the chunk */
  200037. png_write_chunk(png_ptr, png_IHDR, buf, (png_size_t)13);
  200038. /* initialize zlib with PNG info */
  200039. png_ptr->zstream.zalloc = png_zalloc;
  200040. png_ptr->zstream.zfree = png_zfree;
  200041. png_ptr->zstream.opaque = (voidpf)png_ptr;
  200042. if (!(png_ptr->do_filter))
  200043. {
  200044. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE ||
  200045. png_ptr->bit_depth < 8)
  200046. png_ptr->do_filter = PNG_FILTER_NONE;
  200047. else
  200048. png_ptr->do_filter = PNG_ALL_FILTERS;
  200049. }
  200050. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_STRATEGY))
  200051. {
  200052. if (png_ptr->do_filter != PNG_FILTER_NONE)
  200053. png_ptr->zlib_strategy = Z_FILTERED;
  200054. else
  200055. png_ptr->zlib_strategy = Z_DEFAULT_STRATEGY;
  200056. }
  200057. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_LEVEL))
  200058. png_ptr->zlib_level = Z_DEFAULT_COMPRESSION;
  200059. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL))
  200060. png_ptr->zlib_mem_level = 8;
  200061. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS))
  200062. png_ptr->zlib_window_bits = 15;
  200063. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_METHOD))
  200064. png_ptr->zlib_method = 8;
  200065. if (deflateInit2(&png_ptr->zstream, png_ptr->zlib_level,
  200066. png_ptr->zlib_method, png_ptr->zlib_window_bits,
  200067. png_ptr->zlib_mem_level, png_ptr->zlib_strategy) != Z_OK)
  200068. png_error(png_ptr, "zlib failed to initialize compressor");
  200069. png_ptr->zstream.next_out = png_ptr->zbuf;
  200070. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200071. /* libpng is not interested in zstream.data_type */
  200072. /* set it to a predefined value, to avoid its evaluation inside zlib */
  200073. png_ptr->zstream.data_type = Z_BINARY;
  200074. png_ptr->mode = PNG_HAVE_IHDR;
  200075. }
  200076. /* write the palette. We are careful not to trust png_color to be in the
  200077. * correct order for PNG, so people can redefine it to any convenient
  200078. * structure.
  200079. */
  200080. void /* PRIVATE */
  200081. png_write_PLTE(png_structp png_ptr, png_colorp palette, png_uint_32 num_pal)
  200082. {
  200083. #ifdef PNG_USE_LOCAL_ARRAYS
  200084. PNG_PLTE;
  200085. #endif
  200086. png_uint_32 i;
  200087. png_colorp pal_ptr;
  200088. png_byte buf[3];
  200089. png_debug(1, "in png_write_PLTE\n");
  200090. if ((
  200091. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200092. !(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) &&
  200093. #endif
  200094. num_pal == 0) || num_pal > 256)
  200095. {
  200096. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  200097. {
  200098. png_error(png_ptr, "Invalid number of colors in palette");
  200099. }
  200100. else
  200101. {
  200102. png_warning(png_ptr, "Invalid number of colors in palette");
  200103. return;
  200104. }
  200105. }
  200106. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  200107. {
  200108. png_warning(png_ptr,
  200109. "Ignoring request to write a PLTE chunk in grayscale PNG");
  200110. return;
  200111. }
  200112. png_ptr->num_palette = (png_uint_16)num_pal;
  200113. png_debug1(3, "num_palette = %d\n", png_ptr->num_palette);
  200114. png_write_chunk_start(png_ptr, png_PLTE, num_pal * 3);
  200115. #ifndef PNG_NO_POINTER_INDEXING
  200116. for (i = 0, pal_ptr = palette; i < num_pal; i++, pal_ptr++)
  200117. {
  200118. buf[0] = pal_ptr->red;
  200119. buf[1] = pal_ptr->green;
  200120. buf[2] = pal_ptr->blue;
  200121. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  200122. }
  200123. #else
  200124. /* This is a little slower but some buggy compilers need to do this instead */
  200125. pal_ptr=palette;
  200126. for (i = 0; i < num_pal; i++)
  200127. {
  200128. buf[0] = pal_ptr[i].red;
  200129. buf[1] = pal_ptr[i].green;
  200130. buf[2] = pal_ptr[i].blue;
  200131. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  200132. }
  200133. #endif
  200134. png_write_chunk_end(png_ptr);
  200135. png_ptr->mode |= PNG_HAVE_PLTE;
  200136. }
  200137. /* write an IDAT chunk */
  200138. void /* PRIVATE */
  200139. png_write_IDAT(png_structp png_ptr, png_bytep data, png_size_t length)
  200140. {
  200141. #ifdef PNG_USE_LOCAL_ARRAYS
  200142. PNG_IDAT;
  200143. #endif
  200144. png_debug(1, "in png_write_IDAT\n");
  200145. /* Optimize the CMF field in the zlib stream. */
  200146. /* This hack of the zlib stream is compliant to the stream specification. */
  200147. if (!(png_ptr->mode & PNG_HAVE_IDAT) &&
  200148. png_ptr->compression_type == PNG_COMPRESSION_TYPE_BASE)
  200149. {
  200150. unsigned int z_cmf = data[0]; /* zlib compression method and flags */
  200151. if ((z_cmf & 0x0f) == 8 && (z_cmf & 0xf0) <= 0x70)
  200152. {
  200153. /* Avoid memory underflows and multiplication overflows. */
  200154. /* The conditions below are practically always satisfied;
  200155. however, they still must be checked. */
  200156. if (length >= 2 &&
  200157. png_ptr->height < 16384 && png_ptr->width < 16384)
  200158. {
  200159. png_uint_32 uncompressed_idat_size = png_ptr->height *
  200160. ((png_ptr->width *
  200161. png_ptr->channels * png_ptr->bit_depth + 15) >> 3);
  200162. unsigned int z_cinfo = z_cmf >> 4;
  200163. unsigned int half_z_window_size = 1 << (z_cinfo + 7);
  200164. while (uncompressed_idat_size <= half_z_window_size &&
  200165. half_z_window_size >= 256)
  200166. {
  200167. z_cinfo--;
  200168. half_z_window_size >>= 1;
  200169. }
  200170. z_cmf = (z_cmf & 0x0f) | (z_cinfo << 4);
  200171. if (data[0] != (png_byte)z_cmf)
  200172. {
  200173. data[0] = (png_byte)z_cmf;
  200174. data[1] &= 0xe0;
  200175. data[1] += (png_byte)(0x1f - ((z_cmf << 8) + data[1]) % 0x1f);
  200176. }
  200177. }
  200178. }
  200179. else
  200180. png_error(png_ptr,
  200181. "Invalid zlib compression method or flags in IDAT");
  200182. }
  200183. png_write_chunk(png_ptr, png_IDAT, data, length);
  200184. png_ptr->mode |= PNG_HAVE_IDAT;
  200185. }
  200186. /* write an IEND chunk */
  200187. void /* PRIVATE */
  200188. png_write_IEND(png_structp png_ptr)
  200189. {
  200190. #ifdef PNG_USE_LOCAL_ARRAYS
  200191. PNG_IEND;
  200192. #endif
  200193. png_debug(1, "in png_write_IEND\n");
  200194. png_write_chunk(png_ptr, png_IEND, png_bytep_NULL,
  200195. (png_size_t)0);
  200196. png_ptr->mode |= PNG_HAVE_IEND;
  200197. }
  200198. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  200199. /* write a gAMA chunk */
  200200. #ifdef PNG_FLOATING_POINT_SUPPORTED
  200201. void /* PRIVATE */
  200202. png_write_gAMA(png_structp png_ptr, double file_gamma)
  200203. {
  200204. #ifdef PNG_USE_LOCAL_ARRAYS
  200205. PNG_gAMA;
  200206. #endif
  200207. png_uint_32 igamma;
  200208. png_byte buf[4];
  200209. png_debug(1, "in png_write_gAMA\n");
  200210. /* file_gamma is saved in 1/100,000ths */
  200211. igamma = (png_uint_32)(file_gamma * 100000.0 + 0.5);
  200212. png_save_uint_32(buf, igamma);
  200213. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  200214. }
  200215. #endif
  200216. #ifdef PNG_FIXED_POINT_SUPPORTED
  200217. void /* PRIVATE */
  200218. png_write_gAMA_fixed(png_structp png_ptr, png_fixed_point file_gamma)
  200219. {
  200220. #ifdef PNG_USE_LOCAL_ARRAYS
  200221. PNG_gAMA;
  200222. #endif
  200223. png_byte buf[4];
  200224. png_debug(1, "in png_write_gAMA\n");
  200225. /* file_gamma is saved in 1/100,000ths */
  200226. png_save_uint_32(buf, (png_uint_32)file_gamma);
  200227. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  200228. }
  200229. #endif
  200230. #endif
  200231. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  200232. /* write a sRGB chunk */
  200233. void /* PRIVATE */
  200234. png_write_sRGB(png_structp png_ptr, int srgb_intent)
  200235. {
  200236. #ifdef PNG_USE_LOCAL_ARRAYS
  200237. PNG_sRGB;
  200238. #endif
  200239. png_byte buf[1];
  200240. png_debug(1, "in png_write_sRGB\n");
  200241. if(srgb_intent >= PNG_sRGB_INTENT_LAST)
  200242. png_warning(png_ptr,
  200243. "Invalid sRGB rendering intent specified");
  200244. buf[0]=(png_byte)srgb_intent;
  200245. png_write_chunk(png_ptr, png_sRGB, buf, (png_size_t)1);
  200246. }
  200247. #endif
  200248. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  200249. /* write an iCCP chunk */
  200250. void /* PRIVATE */
  200251. png_write_iCCP(png_structp png_ptr, png_charp name, int compression_type,
  200252. png_charp profile, int profile_len)
  200253. {
  200254. #ifdef PNG_USE_LOCAL_ARRAYS
  200255. PNG_iCCP;
  200256. #endif
  200257. png_size_t name_len;
  200258. png_charp new_name;
  200259. compression_state comp;
  200260. int embedded_profile_len = 0;
  200261. png_debug(1, "in png_write_iCCP\n");
  200262. comp.num_output_ptr = 0;
  200263. comp.max_output_ptr = 0;
  200264. comp.output_ptr = NULL;
  200265. comp.input = NULL;
  200266. comp.input_len = 0;
  200267. if (name == NULL || (name_len = png_check_keyword(png_ptr, name,
  200268. &new_name)) == 0)
  200269. {
  200270. png_warning(png_ptr, "Empty keyword in iCCP chunk");
  200271. return;
  200272. }
  200273. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  200274. png_warning(png_ptr, "Unknown compression type in iCCP chunk");
  200275. if (profile == NULL)
  200276. profile_len = 0;
  200277. if (profile_len > 3)
  200278. embedded_profile_len =
  200279. ((*( (png_bytep)profile ))<<24) |
  200280. ((*( (png_bytep)profile+1))<<16) |
  200281. ((*( (png_bytep)profile+2))<< 8) |
  200282. ((*( (png_bytep)profile+3)) );
  200283. if (profile_len < embedded_profile_len)
  200284. {
  200285. png_warning(png_ptr,
  200286. "Embedded profile length too large in iCCP chunk");
  200287. return;
  200288. }
  200289. if (profile_len > embedded_profile_len)
  200290. {
  200291. png_warning(png_ptr,
  200292. "Truncating profile to actual length in iCCP chunk");
  200293. profile_len = embedded_profile_len;
  200294. }
  200295. if (profile_len)
  200296. profile_len = png_text_compress(png_ptr, profile, (png_size_t)profile_len,
  200297. PNG_COMPRESSION_TYPE_BASE, &comp);
  200298. /* make sure we include the NULL after the name and the compression type */
  200299. png_write_chunk_start(png_ptr, png_iCCP,
  200300. (png_uint_32)name_len+profile_len+2);
  200301. new_name[name_len+1]=0x00;
  200302. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 2);
  200303. if (profile_len)
  200304. png_write_compressed_data_out(png_ptr, &comp);
  200305. png_write_chunk_end(png_ptr);
  200306. png_free(png_ptr, new_name);
  200307. }
  200308. #endif
  200309. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  200310. /* write a sPLT chunk */
  200311. void /* PRIVATE */
  200312. png_write_sPLT(png_structp png_ptr, png_sPLT_tp spalette)
  200313. {
  200314. #ifdef PNG_USE_LOCAL_ARRAYS
  200315. PNG_sPLT;
  200316. #endif
  200317. png_size_t name_len;
  200318. png_charp new_name;
  200319. png_byte entrybuf[10];
  200320. int entry_size = (spalette->depth == 8 ? 6 : 10);
  200321. int palette_size = entry_size * spalette->nentries;
  200322. png_sPLT_entryp ep;
  200323. #ifdef PNG_NO_POINTER_INDEXING
  200324. int i;
  200325. #endif
  200326. png_debug(1, "in png_write_sPLT\n");
  200327. if (spalette->name == NULL || (name_len = png_check_keyword(png_ptr,
  200328. spalette->name, &new_name))==0)
  200329. {
  200330. png_warning(png_ptr, "Empty keyword in sPLT chunk");
  200331. return;
  200332. }
  200333. /* make sure we include the NULL after the name */
  200334. png_write_chunk_start(png_ptr, png_sPLT,
  200335. (png_uint_32)(name_len + 2 + palette_size));
  200336. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 1);
  200337. png_write_chunk_data(png_ptr, (png_bytep)&spalette->depth, 1);
  200338. /* loop through each palette entry, writing appropriately */
  200339. #ifndef PNG_NO_POINTER_INDEXING
  200340. for (ep = spalette->entries; ep<spalette->entries+spalette->nentries; ep++)
  200341. {
  200342. if (spalette->depth == 8)
  200343. {
  200344. entrybuf[0] = (png_byte)ep->red;
  200345. entrybuf[1] = (png_byte)ep->green;
  200346. entrybuf[2] = (png_byte)ep->blue;
  200347. entrybuf[3] = (png_byte)ep->alpha;
  200348. png_save_uint_16(entrybuf + 4, ep->frequency);
  200349. }
  200350. else
  200351. {
  200352. png_save_uint_16(entrybuf + 0, ep->red);
  200353. png_save_uint_16(entrybuf + 2, ep->green);
  200354. png_save_uint_16(entrybuf + 4, ep->blue);
  200355. png_save_uint_16(entrybuf + 6, ep->alpha);
  200356. png_save_uint_16(entrybuf + 8, ep->frequency);
  200357. }
  200358. png_write_chunk_data(png_ptr, entrybuf, (png_size_t)entry_size);
  200359. }
  200360. #else
  200361. ep=spalette->entries;
  200362. for (i=0; i>spalette->nentries; i++)
  200363. {
  200364. if (spalette->depth == 8)
  200365. {
  200366. entrybuf[0] = (png_byte)ep[i].red;
  200367. entrybuf[1] = (png_byte)ep[i].green;
  200368. entrybuf[2] = (png_byte)ep[i].blue;
  200369. entrybuf[3] = (png_byte)ep[i].alpha;
  200370. png_save_uint_16(entrybuf + 4, ep[i].frequency);
  200371. }
  200372. else
  200373. {
  200374. png_save_uint_16(entrybuf + 0, ep[i].red);
  200375. png_save_uint_16(entrybuf + 2, ep[i].green);
  200376. png_save_uint_16(entrybuf + 4, ep[i].blue);
  200377. png_save_uint_16(entrybuf + 6, ep[i].alpha);
  200378. png_save_uint_16(entrybuf + 8, ep[i].frequency);
  200379. }
  200380. png_write_chunk_data(png_ptr, entrybuf, entry_size);
  200381. }
  200382. #endif
  200383. png_write_chunk_end(png_ptr);
  200384. png_free(png_ptr, new_name);
  200385. }
  200386. #endif
  200387. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  200388. /* write the sBIT chunk */
  200389. void /* PRIVATE */
  200390. png_write_sBIT(png_structp png_ptr, png_color_8p sbit, int color_type)
  200391. {
  200392. #ifdef PNG_USE_LOCAL_ARRAYS
  200393. PNG_sBIT;
  200394. #endif
  200395. png_byte buf[4];
  200396. png_size_t size;
  200397. png_debug(1, "in png_write_sBIT\n");
  200398. /* make sure we don't depend upon the order of PNG_COLOR_8 */
  200399. if (color_type & PNG_COLOR_MASK_COLOR)
  200400. {
  200401. png_byte maxbits;
  200402. maxbits = (png_byte)(color_type==PNG_COLOR_TYPE_PALETTE ? 8 :
  200403. png_ptr->usr_bit_depth);
  200404. if (sbit->red == 0 || sbit->red > maxbits ||
  200405. sbit->green == 0 || sbit->green > maxbits ||
  200406. sbit->blue == 0 || sbit->blue > maxbits)
  200407. {
  200408. png_warning(png_ptr, "Invalid sBIT depth specified");
  200409. return;
  200410. }
  200411. buf[0] = sbit->red;
  200412. buf[1] = sbit->green;
  200413. buf[2] = sbit->blue;
  200414. size = 3;
  200415. }
  200416. else
  200417. {
  200418. if (sbit->gray == 0 || sbit->gray > png_ptr->usr_bit_depth)
  200419. {
  200420. png_warning(png_ptr, "Invalid sBIT depth specified");
  200421. return;
  200422. }
  200423. buf[0] = sbit->gray;
  200424. size = 1;
  200425. }
  200426. if (color_type & PNG_COLOR_MASK_ALPHA)
  200427. {
  200428. if (sbit->alpha == 0 || sbit->alpha > png_ptr->usr_bit_depth)
  200429. {
  200430. png_warning(png_ptr, "Invalid sBIT depth specified");
  200431. return;
  200432. }
  200433. buf[size++] = sbit->alpha;
  200434. }
  200435. png_write_chunk(png_ptr, png_sBIT, buf, size);
  200436. }
  200437. #endif
  200438. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  200439. /* write the cHRM chunk */
  200440. #ifdef PNG_FLOATING_POINT_SUPPORTED
  200441. void /* PRIVATE */
  200442. png_write_cHRM(png_structp png_ptr, double white_x, double white_y,
  200443. double red_x, double red_y, double green_x, double green_y,
  200444. double blue_x, double blue_y)
  200445. {
  200446. #ifdef PNG_USE_LOCAL_ARRAYS
  200447. PNG_cHRM;
  200448. #endif
  200449. png_byte buf[32];
  200450. png_uint_32 itemp;
  200451. png_debug(1, "in png_write_cHRM\n");
  200452. /* each value is saved in 1/100,000ths */
  200453. if (white_x < 0 || white_x > 0.8 || white_y < 0 || white_y > 0.8 ||
  200454. white_x + white_y > 1.0)
  200455. {
  200456. png_warning(png_ptr, "Invalid cHRM white point specified");
  200457. #if !defined(PNG_NO_CONSOLE_IO)
  200458. fprintf(stderr,"white_x=%f, white_y=%f\n",white_x, white_y);
  200459. #endif
  200460. return;
  200461. }
  200462. itemp = (png_uint_32)(white_x * 100000.0 + 0.5);
  200463. png_save_uint_32(buf, itemp);
  200464. itemp = (png_uint_32)(white_y * 100000.0 + 0.5);
  200465. png_save_uint_32(buf + 4, itemp);
  200466. if (red_x < 0 || red_y < 0 || red_x + red_y > 1.0)
  200467. {
  200468. png_warning(png_ptr, "Invalid cHRM red point specified");
  200469. return;
  200470. }
  200471. itemp = (png_uint_32)(red_x * 100000.0 + 0.5);
  200472. png_save_uint_32(buf + 8, itemp);
  200473. itemp = (png_uint_32)(red_y * 100000.0 + 0.5);
  200474. png_save_uint_32(buf + 12, itemp);
  200475. if (green_x < 0 || green_y < 0 || green_x + green_y > 1.0)
  200476. {
  200477. png_warning(png_ptr, "Invalid cHRM green point specified");
  200478. return;
  200479. }
  200480. itemp = (png_uint_32)(green_x * 100000.0 + 0.5);
  200481. png_save_uint_32(buf + 16, itemp);
  200482. itemp = (png_uint_32)(green_y * 100000.0 + 0.5);
  200483. png_save_uint_32(buf + 20, itemp);
  200484. if (blue_x < 0 || blue_y < 0 || blue_x + blue_y > 1.0)
  200485. {
  200486. png_warning(png_ptr, "Invalid cHRM blue point specified");
  200487. return;
  200488. }
  200489. itemp = (png_uint_32)(blue_x * 100000.0 + 0.5);
  200490. png_save_uint_32(buf + 24, itemp);
  200491. itemp = (png_uint_32)(blue_y * 100000.0 + 0.5);
  200492. png_save_uint_32(buf + 28, itemp);
  200493. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  200494. }
  200495. #endif
  200496. #ifdef PNG_FIXED_POINT_SUPPORTED
  200497. void /* PRIVATE */
  200498. png_write_cHRM_fixed(png_structp png_ptr, png_fixed_point white_x,
  200499. png_fixed_point white_y, png_fixed_point red_x, png_fixed_point red_y,
  200500. png_fixed_point green_x, png_fixed_point green_y, png_fixed_point blue_x,
  200501. png_fixed_point blue_y)
  200502. {
  200503. #ifdef PNG_USE_LOCAL_ARRAYS
  200504. PNG_cHRM;
  200505. #endif
  200506. png_byte buf[32];
  200507. png_debug(1, "in png_write_cHRM\n");
  200508. /* each value is saved in 1/100,000ths */
  200509. if (white_x > 80000L || white_y > 80000L || white_x + white_y > 100000L)
  200510. {
  200511. png_warning(png_ptr, "Invalid fixed cHRM white point specified");
  200512. #if !defined(PNG_NO_CONSOLE_IO)
  200513. fprintf(stderr,"white_x=%ld, white_y=%ld\n",white_x, white_y);
  200514. #endif
  200515. return;
  200516. }
  200517. png_save_uint_32(buf, (png_uint_32)white_x);
  200518. png_save_uint_32(buf + 4, (png_uint_32)white_y);
  200519. if (red_x + red_y > 100000L)
  200520. {
  200521. png_warning(png_ptr, "Invalid cHRM fixed red point specified");
  200522. return;
  200523. }
  200524. png_save_uint_32(buf + 8, (png_uint_32)red_x);
  200525. png_save_uint_32(buf + 12, (png_uint_32)red_y);
  200526. if (green_x + green_y > 100000L)
  200527. {
  200528. png_warning(png_ptr, "Invalid fixed cHRM green point specified");
  200529. return;
  200530. }
  200531. png_save_uint_32(buf + 16, (png_uint_32)green_x);
  200532. png_save_uint_32(buf + 20, (png_uint_32)green_y);
  200533. if (blue_x + blue_y > 100000L)
  200534. {
  200535. png_warning(png_ptr, "Invalid fixed cHRM blue point specified");
  200536. return;
  200537. }
  200538. png_save_uint_32(buf + 24, (png_uint_32)blue_x);
  200539. png_save_uint_32(buf + 28, (png_uint_32)blue_y);
  200540. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  200541. }
  200542. #endif
  200543. #endif
  200544. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  200545. /* write the tRNS chunk */
  200546. void /* PRIVATE */
  200547. png_write_tRNS(png_structp png_ptr, png_bytep trans, png_color_16p tran,
  200548. int num_trans, int color_type)
  200549. {
  200550. #ifdef PNG_USE_LOCAL_ARRAYS
  200551. PNG_tRNS;
  200552. #endif
  200553. png_byte buf[6];
  200554. png_debug(1, "in png_write_tRNS\n");
  200555. if (color_type == PNG_COLOR_TYPE_PALETTE)
  200556. {
  200557. if (num_trans <= 0 || num_trans > (int)png_ptr->num_palette)
  200558. {
  200559. png_warning(png_ptr,"Invalid number of transparent colors specified");
  200560. return;
  200561. }
  200562. /* write the chunk out as it is */
  200563. png_write_chunk(png_ptr, png_tRNS, trans, (png_size_t)num_trans);
  200564. }
  200565. else if (color_type == PNG_COLOR_TYPE_GRAY)
  200566. {
  200567. /* one 16 bit value */
  200568. if(tran->gray >= (1 << png_ptr->bit_depth))
  200569. {
  200570. png_warning(png_ptr,
  200571. "Ignoring attempt to write tRNS chunk out-of-range for bit_depth");
  200572. return;
  200573. }
  200574. png_save_uint_16(buf, tran->gray);
  200575. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)2);
  200576. }
  200577. else if (color_type == PNG_COLOR_TYPE_RGB)
  200578. {
  200579. /* three 16 bit values */
  200580. png_save_uint_16(buf, tran->red);
  200581. png_save_uint_16(buf + 2, tran->green);
  200582. png_save_uint_16(buf + 4, tran->blue);
  200583. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  200584. {
  200585. png_warning(png_ptr,
  200586. "Ignoring attempt to write 16-bit tRNS chunk when bit_depth is 8");
  200587. return;
  200588. }
  200589. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)6);
  200590. }
  200591. else
  200592. {
  200593. png_warning(png_ptr, "Can't write tRNS with an alpha channel");
  200594. }
  200595. }
  200596. #endif
  200597. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  200598. /* write the background chunk */
  200599. void /* PRIVATE */
  200600. png_write_bKGD(png_structp png_ptr, png_color_16p back, int color_type)
  200601. {
  200602. #ifdef PNG_USE_LOCAL_ARRAYS
  200603. PNG_bKGD;
  200604. #endif
  200605. png_byte buf[6];
  200606. png_debug(1, "in png_write_bKGD\n");
  200607. if (color_type == PNG_COLOR_TYPE_PALETTE)
  200608. {
  200609. if (
  200610. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200611. (png_ptr->num_palette ||
  200612. (!(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE))) &&
  200613. #endif
  200614. back->index > png_ptr->num_palette)
  200615. {
  200616. png_warning(png_ptr, "Invalid background palette index");
  200617. return;
  200618. }
  200619. buf[0] = back->index;
  200620. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)1);
  200621. }
  200622. else if (color_type & PNG_COLOR_MASK_COLOR)
  200623. {
  200624. png_save_uint_16(buf, back->red);
  200625. png_save_uint_16(buf + 2, back->green);
  200626. png_save_uint_16(buf + 4, back->blue);
  200627. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  200628. {
  200629. png_warning(png_ptr,
  200630. "Ignoring attempt to write 16-bit bKGD chunk when bit_depth is 8");
  200631. return;
  200632. }
  200633. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)6);
  200634. }
  200635. else
  200636. {
  200637. if(back->gray >= (1 << png_ptr->bit_depth))
  200638. {
  200639. png_warning(png_ptr,
  200640. "Ignoring attempt to write bKGD chunk out-of-range for bit_depth");
  200641. return;
  200642. }
  200643. png_save_uint_16(buf, back->gray);
  200644. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)2);
  200645. }
  200646. }
  200647. #endif
  200648. #if defined(PNG_WRITE_hIST_SUPPORTED)
  200649. /* write the histogram */
  200650. void /* PRIVATE */
  200651. png_write_hIST(png_structp png_ptr, png_uint_16p hist, int num_hist)
  200652. {
  200653. #ifdef PNG_USE_LOCAL_ARRAYS
  200654. PNG_hIST;
  200655. #endif
  200656. int i;
  200657. png_byte buf[3];
  200658. png_debug(1, "in png_write_hIST\n");
  200659. if (num_hist > (int)png_ptr->num_palette)
  200660. {
  200661. png_debug2(3, "num_hist = %d, num_palette = %d\n", num_hist,
  200662. png_ptr->num_palette);
  200663. png_warning(png_ptr, "Invalid number of histogram entries specified");
  200664. return;
  200665. }
  200666. png_write_chunk_start(png_ptr, png_hIST, (png_uint_32)(num_hist * 2));
  200667. for (i = 0; i < num_hist; i++)
  200668. {
  200669. png_save_uint_16(buf, hist[i]);
  200670. png_write_chunk_data(png_ptr, buf, (png_size_t)2);
  200671. }
  200672. png_write_chunk_end(png_ptr);
  200673. }
  200674. #endif
  200675. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  200676. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  200677. /* Check that the tEXt or zTXt keyword is valid per PNG 1.0 specification,
  200678. * and if invalid, correct the keyword rather than discarding the entire
  200679. * chunk. The PNG 1.0 specification requires keywords 1-79 characters in
  200680. * length, forbids leading or trailing whitespace, multiple internal spaces,
  200681. * and the non-break space (0x80) from ISO 8859-1. Returns keyword length.
  200682. *
  200683. * The new_key is allocated to hold the corrected keyword and must be freed
  200684. * by the calling routine. This avoids problems with trying to write to
  200685. * static keywords without having to have duplicate copies of the strings.
  200686. */
  200687. png_size_t /* PRIVATE */
  200688. png_check_keyword(png_structp png_ptr, png_charp key, png_charpp new_key)
  200689. {
  200690. png_size_t key_len;
  200691. png_charp kp, dp;
  200692. int kflag;
  200693. int kwarn=0;
  200694. png_debug(1, "in png_check_keyword\n");
  200695. *new_key = NULL;
  200696. if (key == NULL || (key_len = png_strlen(key)) == 0)
  200697. {
  200698. png_warning(png_ptr, "zero length keyword");
  200699. return ((png_size_t)0);
  200700. }
  200701. png_debug1(2, "Keyword to be checked is '%s'\n", key);
  200702. *new_key = (png_charp)png_malloc_warn(png_ptr, (png_uint_32)(key_len + 2));
  200703. if (*new_key == NULL)
  200704. {
  200705. png_warning(png_ptr, "Out of memory while procesing keyword");
  200706. return ((png_size_t)0);
  200707. }
  200708. /* Replace non-printing characters with a blank and print a warning */
  200709. for (kp = key, dp = *new_key; *kp != '\0'; kp++, dp++)
  200710. {
  200711. if ((png_byte)*kp < 0x20 ||
  200712. ((png_byte)*kp > 0x7E && (png_byte)*kp < 0xA1))
  200713. {
  200714. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  200715. char msg[40];
  200716. png_snprintf(msg, 40,
  200717. "invalid keyword character 0x%02X", (png_byte)*kp);
  200718. png_warning(png_ptr, msg);
  200719. #else
  200720. png_warning(png_ptr, "invalid character in keyword");
  200721. #endif
  200722. *dp = ' ';
  200723. }
  200724. else
  200725. {
  200726. *dp = *kp;
  200727. }
  200728. }
  200729. *dp = '\0';
  200730. /* Remove any trailing white space. */
  200731. kp = *new_key + key_len - 1;
  200732. if (*kp == ' ')
  200733. {
  200734. png_warning(png_ptr, "trailing spaces removed from keyword");
  200735. while (*kp == ' ')
  200736. {
  200737. *(kp--) = '\0';
  200738. key_len--;
  200739. }
  200740. }
  200741. /* Remove any leading white space. */
  200742. kp = *new_key;
  200743. if (*kp == ' ')
  200744. {
  200745. png_warning(png_ptr, "leading spaces removed from keyword");
  200746. while (*kp == ' ')
  200747. {
  200748. kp++;
  200749. key_len--;
  200750. }
  200751. }
  200752. png_debug1(2, "Checking for multiple internal spaces in '%s'\n", kp);
  200753. /* Remove multiple internal spaces. */
  200754. for (kflag = 0, dp = *new_key; *kp != '\0'; kp++)
  200755. {
  200756. if (*kp == ' ' && kflag == 0)
  200757. {
  200758. *(dp++) = *kp;
  200759. kflag = 1;
  200760. }
  200761. else if (*kp == ' ')
  200762. {
  200763. key_len--;
  200764. kwarn=1;
  200765. }
  200766. else
  200767. {
  200768. *(dp++) = *kp;
  200769. kflag = 0;
  200770. }
  200771. }
  200772. *dp = '\0';
  200773. if(kwarn)
  200774. png_warning(png_ptr, "extra interior spaces removed from keyword");
  200775. if (key_len == 0)
  200776. {
  200777. png_free(png_ptr, *new_key);
  200778. *new_key=NULL;
  200779. png_warning(png_ptr, "Zero length keyword");
  200780. }
  200781. if (key_len > 79)
  200782. {
  200783. png_warning(png_ptr, "keyword length must be 1 - 79 characters");
  200784. new_key[79] = '\0';
  200785. key_len = 79;
  200786. }
  200787. return (key_len);
  200788. }
  200789. #endif
  200790. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  200791. /* write a tEXt chunk */
  200792. void /* PRIVATE */
  200793. png_write_tEXt(png_structp png_ptr, png_charp key, png_charp text,
  200794. png_size_t text_len)
  200795. {
  200796. #ifdef PNG_USE_LOCAL_ARRAYS
  200797. PNG_tEXt;
  200798. #endif
  200799. png_size_t key_len;
  200800. png_charp new_key;
  200801. png_debug(1, "in png_write_tEXt\n");
  200802. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  200803. {
  200804. png_warning(png_ptr, "Empty keyword in tEXt chunk");
  200805. return;
  200806. }
  200807. if (text == NULL || *text == '\0')
  200808. text_len = 0;
  200809. else
  200810. text_len = png_strlen(text);
  200811. /* make sure we include the 0 after the key */
  200812. png_write_chunk_start(png_ptr, png_tEXt, (png_uint_32)key_len+text_len+1);
  200813. /*
  200814. * We leave it to the application to meet PNG-1.0 requirements on the
  200815. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  200816. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  200817. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  200818. */
  200819. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  200820. if (text_len)
  200821. png_write_chunk_data(png_ptr, (png_bytep)text, text_len);
  200822. png_write_chunk_end(png_ptr);
  200823. png_free(png_ptr, new_key);
  200824. }
  200825. #endif
  200826. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  200827. /* write a compressed text chunk */
  200828. void /* PRIVATE */
  200829. png_write_zTXt(png_structp png_ptr, png_charp key, png_charp text,
  200830. png_size_t text_len, int compression)
  200831. {
  200832. #ifdef PNG_USE_LOCAL_ARRAYS
  200833. PNG_zTXt;
  200834. #endif
  200835. png_size_t key_len;
  200836. char buf[1];
  200837. png_charp new_key;
  200838. compression_state comp;
  200839. png_debug(1, "in png_write_zTXt\n");
  200840. comp.num_output_ptr = 0;
  200841. comp.max_output_ptr = 0;
  200842. comp.output_ptr = NULL;
  200843. comp.input = NULL;
  200844. comp.input_len = 0;
  200845. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  200846. {
  200847. png_warning(png_ptr, "Empty keyword in zTXt chunk");
  200848. return;
  200849. }
  200850. if (text == NULL || *text == '\0' || compression==PNG_TEXT_COMPRESSION_NONE)
  200851. {
  200852. png_write_tEXt(png_ptr, new_key, text, (png_size_t)0);
  200853. png_free(png_ptr, new_key);
  200854. return;
  200855. }
  200856. text_len = png_strlen(text);
  200857. /* compute the compressed data; do it now for the length */
  200858. text_len = png_text_compress(png_ptr, text, text_len, compression,
  200859. &comp);
  200860. /* write start of chunk */
  200861. png_write_chunk_start(png_ptr, png_zTXt, (png_uint_32)
  200862. (key_len+text_len+2));
  200863. /* write key */
  200864. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  200865. png_free(png_ptr, new_key);
  200866. buf[0] = (png_byte)compression;
  200867. /* write compression */
  200868. png_write_chunk_data(png_ptr, (png_bytep)buf, (png_size_t)1);
  200869. /* write the compressed data */
  200870. png_write_compressed_data_out(png_ptr, &comp);
  200871. /* close the chunk */
  200872. png_write_chunk_end(png_ptr);
  200873. }
  200874. #endif
  200875. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  200876. /* write an iTXt chunk */
  200877. void /* PRIVATE */
  200878. png_write_iTXt(png_structp png_ptr, int compression, png_charp key,
  200879. png_charp lang, png_charp lang_key, png_charp text)
  200880. {
  200881. #ifdef PNG_USE_LOCAL_ARRAYS
  200882. PNG_iTXt;
  200883. #endif
  200884. png_size_t lang_len, key_len, lang_key_len, text_len;
  200885. png_charp new_lang, new_key;
  200886. png_byte cbuf[2];
  200887. compression_state comp;
  200888. png_debug(1, "in png_write_iTXt\n");
  200889. comp.num_output_ptr = 0;
  200890. comp.max_output_ptr = 0;
  200891. comp.output_ptr = NULL;
  200892. comp.input = NULL;
  200893. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  200894. {
  200895. png_warning(png_ptr, "Empty keyword in iTXt chunk");
  200896. return;
  200897. }
  200898. if (lang == NULL || (lang_len = png_check_keyword(png_ptr, lang, &new_lang))==0)
  200899. {
  200900. png_warning(png_ptr, "Empty language field in iTXt chunk");
  200901. new_lang = NULL;
  200902. lang_len = 0;
  200903. }
  200904. if (lang_key == NULL)
  200905. lang_key_len = 0;
  200906. else
  200907. lang_key_len = png_strlen(lang_key);
  200908. if (text == NULL)
  200909. text_len = 0;
  200910. else
  200911. text_len = png_strlen(text);
  200912. /* compute the compressed data; do it now for the length */
  200913. text_len = png_text_compress(png_ptr, text, text_len, compression-2,
  200914. &comp);
  200915. /* make sure we include the compression flag, the compression byte,
  200916. * and the NULs after the key, lang, and lang_key parts */
  200917. png_write_chunk_start(png_ptr, png_iTXt,
  200918. (png_uint_32)(
  200919. 5 /* comp byte, comp flag, terminators for key, lang and lang_key */
  200920. + key_len
  200921. + lang_len
  200922. + lang_key_len
  200923. + text_len));
  200924. /*
  200925. * We leave it to the application to meet PNG-1.0 requirements on the
  200926. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  200927. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  200928. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  200929. */
  200930. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  200931. /* set the compression flag */
  200932. if (compression == PNG_ITXT_COMPRESSION_NONE || \
  200933. compression == PNG_TEXT_COMPRESSION_NONE)
  200934. cbuf[0] = 0;
  200935. else /* compression == PNG_ITXT_COMPRESSION_zTXt */
  200936. cbuf[0] = 1;
  200937. /* set the compression method */
  200938. cbuf[1] = 0;
  200939. png_write_chunk_data(png_ptr, cbuf, 2);
  200940. cbuf[0] = 0;
  200941. png_write_chunk_data(png_ptr, (new_lang ? (png_bytep)new_lang : cbuf), lang_len + 1);
  200942. png_write_chunk_data(png_ptr, (lang_key ? (png_bytep)lang_key : cbuf), lang_key_len + 1);
  200943. png_write_compressed_data_out(png_ptr, &comp);
  200944. png_write_chunk_end(png_ptr);
  200945. png_free(png_ptr, new_key);
  200946. if (new_lang)
  200947. png_free(png_ptr, new_lang);
  200948. }
  200949. #endif
  200950. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  200951. /* write the oFFs chunk */
  200952. void /* PRIVATE */
  200953. png_write_oFFs(png_structp png_ptr, png_int_32 x_offset, png_int_32 y_offset,
  200954. int unit_type)
  200955. {
  200956. #ifdef PNG_USE_LOCAL_ARRAYS
  200957. PNG_oFFs;
  200958. #endif
  200959. png_byte buf[9];
  200960. png_debug(1, "in png_write_oFFs\n");
  200961. if (unit_type >= PNG_OFFSET_LAST)
  200962. png_warning(png_ptr, "Unrecognized unit type for oFFs chunk");
  200963. png_save_int_32(buf, x_offset);
  200964. png_save_int_32(buf + 4, y_offset);
  200965. buf[8] = (png_byte)unit_type;
  200966. png_write_chunk(png_ptr, png_oFFs, buf, (png_size_t)9);
  200967. }
  200968. #endif
  200969. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  200970. /* write the pCAL chunk (described in the PNG extensions document) */
  200971. void /* PRIVATE */
  200972. png_write_pCAL(png_structp png_ptr, png_charp purpose, png_int_32 X0,
  200973. png_int_32 X1, int type, int nparams, png_charp units, png_charpp params)
  200974. {
  200975. #ifdef PNG_USE_LOCAL_ARRAYS
  200976. PNG_pCAL;
  200977. #endif
  200978. png_size_t purpose_len, units_len, total_len;
  200979. png_uint_32p params_len;
  200980. png_byte buf[10];
  200981. png_charp new_purpose;
  200982. int i;
  200983. png_debug1(1, "in png_write_pCAL (%d parameters)\n", nparams);
  200984. if (type >= PNG_EQUATION_LAST)
  200985. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  200986. purpose_len = png_check_keyword(png_ptr, purpose, &new_purpose) + 1;
  200987. png_debug1(3, "pCAL purpose length = %d\n", (int)purpose_len);
  200988. units_len = png_strlen(units) + (nparams == 0 ? 0 : 1);
  200989. png_debug1(3, "pCAL units length = %d\n", (int)units_len);
  200990. total_len = purpose_len + units_len + 10;
  200991. params_len = (png_uint_32p)png_malloc(png_ptr, (png_uint_32)(nparams
  200992. *png_sizeof(png_uint_32)));
  200993. /* Find the length of each parameter, making sure we don't count the
  200994. null terminator for the last parameter. */
  200995. for (i = 0; i < nparams; i++)
  200996. {
  200997. params_len[i] = png_strlen(params[i]) + (i == nparams - 1 ? 0 : 1);
  200998. png_debug2(3, "pCAL parameter %d length = %lu\n", i, params_len[i]);
  200999. total_len += (png_size_t)params_len[i];
  201000. }
  201001. png_debug1(3, "pCAL total length = %d\n", (int)total_len);
  201002. png_write_chunk_start(png_ptr, png_pCAL, (png_uint_32)total_len);
  201003. png_write_chunk_data(png_ptr, (png_bytep)new_purpose, purpose_len);
  201004. png_save_int_32(buf, X0);
  201005. png_save_int_32(buf + 4, X1);
  201006. buf[8] = (png_byte)type;
  201007. buf[9] = (png_byte)nparams;
  201008. png_write_chunk_data(png_ptr, buf, (png_size_t)10);
  201009. png_write_chunk_data(png_ptr, (png_bytep)units, (png_size_t)units_len);
  201010. png_free(png_ptr, new_purpose);
  201011. for (i = 0; i < nparams; i++)
  201012. {
  201013. png_write_chunk_data(png_ptr, (png_bytep)params[i],
  201014. (png_size_t)params_len[i]);
  201015. }
  201016. png_free(png_ptr, params_len);
  201017. png_write_chunk_end(png_ptr);
  201018. }
  201019. #endif
  201020. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  201021. /* write the sCAL chunk */
  201022. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  201023. void /* PRIVATE */
  201024. png_write_sCAL(png_structp png_ptr, int unit, double width, double height)
  201025. {
  201026. #ifdef PNG_USE_LOCAL_ARRAYS
  201027. PNG_sCAL;
  201028. #endif
  201029. char buf[64];
  201030. png_size_t total_len;
  201031. png_debug(1, "in png_write_sCAL\n");
  201032. buf[0] = (char)unit;
  201033. #if defined(_WIN32_WCE)
  201034. /* sprintf() function is not supported on WindowsCE */
  201035. {
  201036. wchar_t wc_buf[32];
  201037. size_t wc_len;
  201038. swprintf(wc_buf, TEXT("%12.12e"), width);
  201039. wc_len = wcslen(wc_buf);
  201040. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + 1, wc_len, NULL, NULL);
  201041. total_len = wc_len + 2;
  201042. swprintf(wc_buf, TEXT("%12.12e"), height);
  201043. wc_len = wcslen(wc_buf);
  201044. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + total_len, wc_len,
  201045. NULL, NULL);
  201046. total_len += wc_len;
  201047. }
  201048. #else
  201049. png_snprintf(buf + 1, 63, "%12.12e", width);
  201050. total_len = 1 + png_strlen(buf + 1) + 1;
  201051. png_snprintf(buf + total_len, 64-total_len, "%12.12e", height);
  201052. total_len += png_strlen(buf + total_len);
  201053. #endif
  201054. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  201055. png_write_chunk(png_ptr, png_sCAL, (png_bytep)buf, total_len);
  201056. }
  201057. #else
  201058. #ifdef PNG_FIXED_POINT_SUPPORTED
  201059. void /* PRIVATE */
  201060. png_write_sCAL_s(png_structp png_ptr, int unit, png_charp width,
  201061. png_charp height)
  201062. {
  201063. #ifdef PNG_USE_LOCAL_ARRAYS
  201064. PNG_sCAL;
  201065. #endif
  201066. png_byte buf[64];
  201067. png_size_t wlen, hlen, total_len;
  201068. png_debug(1, "in png_write_sCAL_s\n");
  201069. wlen = png_strlen(width);
  201070. hlen = png_strlen(height);
  201071. total_len = wlen + hlen + 2;
  201072. if (total_len > 64)
  201073. {
  201074. png_warning(png_ptr, "Can't write sCAL (buffer too small)");
  201075. return;
  201076. }
  201077. buf[0] = (png_byte)unit;
  201078. png_memcpy(buf + 1, width, wlen + 1); /* append the '\0' here */
  201079. png_memcpy(buf + wlen + 2, height, hlen); /* do NOT append the '\0' here */
  201080. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  201081. png_write_chunk(png_ptr, png_sCAL, buf, total_len);
  201082. }
  201083. #endif
  201084. #endif
  201085. #endif
  201086. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  201087. /* write the pHYs chunk */
  201088. void /* PRIVATE */
  201089. png_write_pHYs(png_structp png_ptr, png_uint_32 x_pixels_per_unit,
  201090. png_uint_32 y_pixels_per_unit,
  201091. int unit_type)
  201092. {
  201093. #ifdef PNG_USE_LOCAL_ARRAYS
  201094. PNG_pHYs;
  201095. #endif
  201096. png_byte buf[9];
  201097. png_debug(1, "in png_write_pHYs\n");
  201098. if (unit_type >= PNG_RESOLUTION_LAST)
  201099. png_warning(png_ptr, "Unrecognized unit type for pHYs chunk");
  201100. png_save_uint_32(buf, x_pixels_per_unit);
  201101. png_save_uint_32(buf + 4, y_pixels_per_unit);
  201102. buf[8] = (png_byte)unit_type;
  201103. png_write_chunk(png_ptr, png_pHYs, buf, (png_size_t)9);
  201104. }
  201105. #endif
  201106. #if defined(PNG_WRITE_tIME_SUPPORTED)
  201107. /* Write the tIME chunk. Use either png_convert_from_struct_tm()
  201108. * or png_convert_from_time_t(), or fill in the structure yourself.
  201109. */
  201110. void /* PRIVATE */
  201111. png_write_tIME(png_structp png_ptr, png_timep mod_time)
  201112. {
  201113. #ifdef PNG_USE_LOCAL_ARRAYS
  201114. PNG_tIME;
  201115. #endif
  201116. png_byte buf[7];
  201117. png_debug(1, "in png_write_tIME\n");
  201118. if (mod_time->month > 12 || mod_time->month < 1 ||
  201119. mod_time->day > 31 || mod_time->day < 1 ||
  201120. mod_time->hour > 23 || mod_time->second > 60)
  201121. {
  201122. png_warning(png_ptr, "Invalid time specified for tIME chunk");
  201123. return;
  201124. }
  201125. png_save_uint_16(buf, mod_time->year);
  201126. buf[2] = mod_time->month;
  201127. buf[3] = mod_time->day;
  201128. buf[4] = mod_time->hour;
  201129. buf[5] = mod_time->minute;
  201130. buf[6] = mod_time->second;
  201131. png_write_chunk(png_ptr, png_tIME, buf, (png_size_t)7);
  201132. }
  201133. #endif
  201134. /* initializes the row writing capability of libpng */
  201135. void /* PRIVATE */
  201136. png_write_start_row(png_structp png_ptr)
  201137. {
  201138. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  201139. #ifdef PNG_USE_LOCAL_ARRAYS
  201140. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  201141. /* start of interlace block */
  201142. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  201143. /* offset to next interlace block */
  201144. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  201145. /* start of interlace block in the y direction */
  201146. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  201147. /* offset to next interlace block in the y direction */
  201148. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  201149. #endif
  201150. #endif
  201151. png_size_t buf_size;
  201152. png_debug(1, "in png_write_start_row\n");
  201153. buf_size = (png_size_t)(PNG_ROWBYTES(
  201154. png_ptr->usr_channels*png_ptr->usr_bit_depth,png_ptr->width)+1);
  201155. /* set up row buffer */
  201156. png_ptr->row_buf = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  201157. png_ptr->row_buf[0] = PNG_FILTER_VALUE_NONE;
  201158. #ifndef PNG_NO_WRITE_FILTERING
  201159. /* set up filtering buffer, if using this filter */
  201160. if (png_ptr->do_filter & PNG_FILTER_SUB)
  201161. {
  201162. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  201163. (png_ptr->rowbytes + 1));
  201164. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  201165. }
  201166. /* We only need to keep the previous row if we are using one of these. */
  201167. if (png_ptr->do_filter & (PNG_FILTER_AVG | PNG_FILTER_UP | PNG_FILTER_PAETH))
  201168. {
  201169. /* set up previous row buffer */
  201170. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  201171. png_memset(png_ptr->prev_row, 0, buf_size);
  201172. if (png_ptr->do_filter & PNG_FILTER_UP)
  201173. {
  201174. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  201175. (png_ptr->rowbytes + 1));
  201176. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  201177. }
  201178. if (png_ptr->do_filter & PNG_FILTER_AVG)
  201179. {
  201180. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  201181. (png_ptr->rowbytes + 1));
  201182. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  201183. }
  201184. if (png_ptr->do_filter & PNG_FILTER_PAETH)
  201185. {
  201186. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  201187. (png_ptr->rowbytes + 1));
  201188. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  201189. }
  201190. #endif /* PNG_NO_WRITE_FILTERING */
  201191. }
  201192. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  201193. /* if interlaced, we need to set up width and height of pass */
  201194. if (png_ptr->interlaced)
  201195. {
  201196. if (!(png_ptr->transformations & PNG_INTERLACE))
  201197. {
  201198. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  201199. png_pass_ystart[0]) / png_pass_yinc[0];
  201200. png_ptr->usr_width = (png_ptr->width + png_pass_inc[0] - 1 -
  201201. png_pass_start[0]) / png_pass_inc[0];
  201202. }
  201203. else
  201204. {
  201205. png_ptr->num_rows = png_ptr->height;
  201206. png_ptr->usr_width = png_ptr->width;
  201207. }
  201208. }
  201209. else
  201210. #endif
  201211. {
  201212. png_ptr->num_rows = png_ptr->height;
  201213. png_ptr->usr_width = png_ptr->width;
  201214. }
  201215. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  201216. png_ptr->zstream.next_out = png_ptr->zbuf;
  201217. }
  201218. /* Internal use only. Called when finished processing a row of data. */
  201219. void /* PRIVATE */
  201220. png_write_finish_row(png_structp png_ptr)
  201221. {
  201222. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  201223. #ifdef PNG_USE_LOCAL_ARRAYS
  201224. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  201225. /* start of interlace block */
  201226. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  201227. /* offset to next interlace block */
  201228. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  201229. /* start of interlace block in the y direction */
  201230. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  201231. /* offset to next interlace block in the y direction */
  201232. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  201233. #endif
  201234. #endif
  201235. int ret;
  201236. png_debug(1, "in png_write_finish_row\n");
  201237. /* next row */
  201238. png_ptr->row_number++;
  201239. /* see if we are done */
  201240. if (png_ptr->row_number < png_ptr->num_rows)
  201241. return;
  201242. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  201243. /* if interlaced, go to next pass */
  201244. if (png_ptr->interlaced)
  201245. {
  201246. png_ptr->row_number = 0;
  201247. if (png_ptr->transformations & PNG_INTERLACE)
  201248. {
  201249. png_ptr->pass++;
  201250. }
  201251. else
  201252. {
  201253. /* loop until we find a non-zero width or height pass */
  201254. do
  201255. {
  201256. png_ptr->pass++;
  201257. if (png_ptr->pass >= 7)
  201258. break;
  201259. png_ptr->usr_width = (png_ptr->width +
  201260. png_pass_inc[png_ptr->pass] - 1 -
  201261. png_pass_start[png_ptr->pass]) /
  201262. png_pass_inc[png_ptr->pass];
  201263. png_ptr->num_rows = (png_ptr->height +
  201264. png_pass_yinc[png_ptr->pass] - 1 -
  201265. png_pass_ystart[png_ptr->pass]) /
  201266. png_pass_yinc[png_ptr->pass];
  201267. if (png_ptr->transformations & PNG_INTERLACE)
  201268. break;
  201269. } while (png_ptr->usr_width == 0 || png_ptr->num_rows == 0);
  201270. }
  201271. /* reset the row above the image for the next pass */
  201272. if (png_ptr->pass < 7)
  201273. {
  201274. if (png_ptr->prev_row != NULL)
  201275. png_memset(png_ptr->prev_row, 0,
  201276. (png_size_t)(PNG_ROWBYTES(png_ptr->usr_channels*
  201277. png_ptr->usr_bit_depth,png_ptr->width))+1);
  201278. return;
  201279. }
  201280. }
  201281. #endif
  201282. /* if we get here, we've just written the last row, so we need
  201283. to flush the compressor */
  201284. do
  201285. {
  201286. /* tell the compressor we are done */
  201287. ret = deflate(&png_ptr->zstream, Z_FINISH);
  201288. /* check for an error */
  201289. if (ret == Z_OK)
  201290. {
  201291. /* check to see if we need more room */
  201292. if (!(png_ptr->zstream.avail_out))
  201293. {
  201294. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  201295. png_ptr->zstream.next_out = png_ptr->zbuf;
  201296. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  201297. }
  201298. }
  201299. else if (ret != Z_STREAM_END)
  201300. {
  201301. if (png_ptr->zstream.msg != NULL)
  201302. png_error(png_ptr, png_ptr->zstream.msg);
  201303. else
  201304. png_error(png_ptr, "zlib error");
  201305. }
  201306. } while (ret != Z_STREAM_END);
  201307. /* write any extra space */
  201308. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  201309. {
  201310. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size -
  201311. png_ptr->zstream.avail_out);
  201312. }
  201313. deflateReset(&png_ptr->zstream);
  201314. png_ptr->zstream.data_type = Z_BINARY;
  201315. }
  201316. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  201317. /* Pick out the correct pixels for the interlace pass.
  201318. * The basic idea here is to go through the row with a source
  201319. * pointer and a destination pointer (sp and dp), and copy the
  201320. * correct pixels for the pass. As the row gets compacted,
  201321. * sp will always be >= dp, so we should never overwrite anything.
  201322. * See the default: case for the easiest code to understand.
  201323. */
  201324. void /* PRIVATE */
  201325. png_do_write_interlace(png_row_infop row_info, png_bytep row, int pass)
  201326. {
  201327. #ifdef PNG_USE_LOCAL_ARRAYS
  201328. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  201329. /* start of interlace block */
  201330. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  201331. /* offset to next interlace block */
  201332. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  201333. #endif
  201334. png_debug(1, "in png_do_write_interlace\n");
  201335. /* we don't have to do anything on the last pass (6) */
  201336. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  201337. if (row != NULL && row_info != NULL && pass < 6)
  201338. #else
  201339. if (pass < 6)
  201340. #endif
  201341. {
  201342. /* each pixel depth is handled separately */
  201343. switch (row_info->pixel_depth)
  201344. {
  201345. case 1:
  201346. {
  201347. png_bytep sp;
  201348. png_bytep dp;
  201349. int shift;
  201350. int d;
  201351. int value;
  201352. png_uint_32 i;
  201353. png_uint_32 row_width = row_info->width;
  201354. dp = row;
  201355. d = 0;
  201356. shift = 7;
  201357. for (i = png_pass_start[pass]; i < row_width;
  201358. i += png_pass_inc[pass])
  201359. {
  201360. sp = row + (png_size_t)(i >> 3);
  201361. value = (int)(*sp >> (7 - (int)(i & 0x07))) & 0x01;
  201362. d |= (value << shift);
  201363. if (shift == 0)
  201364. {
  201365. shift = 7;
  201366. *dp++ = (png_byte)d;
  201367. d = 0;
  201368. }
  201369. else
  201370. shift--;
  201371. }
  201372. if (shift != 7)
  201373. *dp = (png_byte)d;
  201374. break;
  201375. }
  201376. case 2:
  201377. {
  201378. png_bytep sp;
  201379. png_bytep dp;
  201380. int shift;
  201381. int d;
  201382. int value;
  201383. png_uint_32 i;
  201384. png_uint_32 row_width = row_info->width;
  201385. dp = row;
  201386. shift = 6;
  201387. d = 0;
  201388. for (i = png_pass_start[pass]; i < row_width;
  201389. i += png_pass_inc[pass])
  201390. {
  201391. sp = row + (png_size_t)(i >> 2);
  201392. value = (*sp >> ((3 - (int)(i & 0x03)) << 1)) & 0x03;
  201393. d |= (value << shift);
  201394. if (shift == 0)
  201395. {
  201396. shift = 6;
  201397. *dp++ = (png_byte)d;
  201398. d = 0;
  201399. }
  201400. else
  201401. shift -= 2;
  201402. }
  201403. if (shift != 6)
  201404. *dp = (png_byte)d;
  201405. break;
  201406. }
  201407. case 4:
  201408. {
  201409. png_bytep sp;
  201410. png_bytep dp;
  201411. int shift;
  201412. int d;
  201413. int value;
  201414. png_uint_32 i;
  201415. png_uint_32 row_width = row_info->width;
  201416. dp = row;
  201417. shift = 4;
  201418. d = 0;
  201419. for (i = png_pass_start[pass]; i < row_width;
  201420. i += png_pass_inc[pass])
  201421. {
  201422. sp = row + (png_size_t)(i >> 1);
  201423. value = (*sp >> ((1 - (int)(i & 0x01)) << 2)) & 0x0f;
  201424. d |= (value << shift);
  201425. if (shift == 0)
  201426. {
  201427. shift = 4;
  201428. *dp++ = (png_byte)d;
  201429. d = 0;
  201430. }
  201431. else
  201432. shift -= 4;
  201433. }
  201434. if (shift != 4)
  201435. *dp = (png_byte)d;
  201436. break;
  201437. }
  201438. default:
  201439. {
  201440. png_bytep sp;
  201441. png_bytep dp;
  201442. png_uint_32 i;
  201443. png_uint_32 row_width = row_info->width;
  201444. png_size_t pixel_bytes;
  201445. /* start at the beginning */
  201446. dp = row;
  201447. /* find out how many bytes each pixel takes up */
  201448. pixel_bytes = (row_info->pixel_depth >> 3);
  201449. /* loop through the row, only looking at the pixels that
  201450. matter */
  201451. for (i = png_pass_start[pass]; i < row_width;
  201452. i += png_pass_inc[pass])
  201453. {
  201454. /* find out where the original pixel is */
  201455. sp = row + (png_size_t)i * pixel_bytes;
  201456. /* move the pixel */
  201457. if (dp != sp)
  201458. png_memcpy(dp, sp, pixel_bytes);
  201459. /* next pixel */
  201460. dp += pixel_bytes;
  201461. }
  201462. break;
  201463. }
  201464. }
  201465. /* set new row width */
  201466. row_info->width = (row_info->width +
  201467. png_pass_inc[pass] - 1 -
  201468. png_pass_start[pass]) /
  201469. png_pass_inc[pass];
  201470. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  201471. row_info->width);
  201472. }
  201473. }
  201474. #endif
  201475. /* This filters the row, chooses which filter to use, if it has not already
  201476. * been specified by the application, and then writes the row out with the
  201477. * chosen filter.
  201478. */
  201479. #define PNG_MAXSUM (((png_uint_32)(-1)) >> 1)
  201480. #define PNG_HISHIFT 10
  201481. #define PNG_LOMASK ((png_uint_32)0xffffL)
  201482. #define PNG_HIMASK ((png_uint_32)(~PNG_LOMASK >> PNG_HISHIFT))
  201483. void /* PRIVATE */
  201484. png_write_find_filter(png_structp png_ptr, png_row_infop row_info)
  201485. {
  201486. png_bytep best_row;
  201487. #ifndef PNG_NO_WRITE_FILTER
  201488. png_bytep prev_row, row_buf;
  201489. png_uint_32 mins, bpp;
  201490. png_byte filter_to_do = png_ptr->do_filter;
  201491. png_uint_32 row_bytes = row_info->rowbytes;
  201492. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  201493. int num_p_filters = (int)png_ptr->num_prev_filters;
  201494. #endif
  201495. png_debug(1, "in png_write_find_filter\n");
  201496. /* find out how many bytes offset each pixel is */
  201497. bpp = (row_info->pixel_depth + 7) >> 3;
  201498. prev_row = png_ptr->prev_row;
  201499. #endif
  201500. best_row = png_ptr->row_buf;
  201501. #ifndef PNG_NO_WRITE_FILTER
  201502. row_buf = best_row;
  201503. mins = PNG_MAXSUM;
  201504. /* The prediction method we use is to find which method provides the
  201505. * smallest value when summing the absolute values of the distances
  201506. * from zero, using anything >= 128 as negative numbers. This is known
  201507. * as the "minimum sum of absolute differences" heuristic. Other
  201508. * heuristics are the "weighted minimum sum of absolute differences"
  201509. * (experimental and can in theory improve compression), and the "zlib
  201510. * predictive" method (not implemented yet), which does test compressions
  201511. * of lines using different filter methods, and then chooses the
  201512. * (series of) filter(s) that give minimum compressed data size (VERY
  201513. * computationally expensive).
  201514. *
  201515. * GRR 980525: consider also
  201516. * (1) minimum sum of absolute differences from running average (i.e.,
  201517. * keep running sum of non-absolute differences & count of bytes)
  201518. * [track dispersion, too? restart average if dispersion too large?]
  201519. * (1b) minimum sum of absolute differences from sliding average, probably
  201520. * with window size <= deflate window (usually 32K)
  201521. * (2) minimum sum of squared differences from zero or running average
  201522. * (i.e., ~ root-mean-square approach)
  201523. */
  201524. /* We don't need to test the 'no filter' case if this is the only filter
  201525. * that has been chosen, as it doesn't actually do anything to the data.
  201526. */
  201527. if ((filter_to_do & PNG_FILTER_NONE) &&
  201528. filter_to_do != PNG_FILTER_NONE)
  201529. {
  201530. png_bytep rp;
  201531. png_uint_32 sum = 0;
  201532. png_uint_32 i;
  201533. int v;
  201534. for (i = 0, rp = row_buf + 1; i < row_bytes; i++, rp++)
  201535. {
  201536. v = *rp;
  201537. sum += (v < 128) ? v : 256 - v;
  201538. }
  201539. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  201540. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  201541. {
  201542. png_uint_32 sumhi, sumlo;
  201543. int j;
  201544. sumlo = sum & PNG_LOMASK;
  201545. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK; /* Gives us some footroom */
  201546. /* Reduce the sum if we match any of the previous rows */
  201547. for (j = 0; j < num_p_filters; j++)
  201548. {
  201549. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  201550. {
  201551. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  201552. PNG_WEIGHT_SHIFT;
  201553. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  201554. PNG_WEIGHT_SHIFT;
  201555. }
  201556. }
  201557. /* Factor in the cost of this filter (this is here for completeness,
  201558. * but it makes no sense to have a "cost" for the NONE filter, as
  201559. * it has the minimum possible computational cost - none).
  201560. */
  201561. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  201562. PNG_COST_SHIFT;
  201563. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  201564. PNG_COST_SHIFT;
  201565. if (sumhi > PNG_HIMASK)
  201566. sum = PNG_MAXSUM;
  201567. else
  201568. sum = (sumhi << PNG_HISHIFT) + sumlo;
  201569. }
  201570. #endif
  201571. mins = sum;
  201572. }
  201573. /* sub filter */
  201574. if (filter_to_do == PNG_FILTER_SUB)
  201575. /* it's the only filter so no testing is needed */
  201576. {
  201577. png_bytep rp, lp, dp;
  201578. png_uint_32 i;
  201579. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  201580. i++, rp++, dp++)
  201581. {
  201582. *dp = *rp;
  201583. }
  201584. for (lp = row_buf + 1; i < row_bytes;
  201585. i++, rp++, lp++, dp++)
  201586. {
  201587. *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  201588. }
  201589. best_row = png_ptr->sub_row;
  201590. }
  201591. else if (filter_to_do & PNG_FILTER_SUB)
  201592. {
  201593. png_bytep rp, dp, lp;
  201594. png_uint_32 sum = 0, lmins = mins;
  201595. png_uint_32 i;
  201596. int v;
  201597. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  201598. /* We temporarily increase the "minimum sum" by the factor we
  201599. * would reduce the sum of this filter, so that we can do the
  201600. * early exit comparison without scaling the sum each time.
  201601. */
  201602. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  201603. {
  201604. int j;
  201605. png_uint_32 lmhi, lmlo;
  201606. lmlo = lmins & PNG_LOMASK;
  201607. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  201608. for (j = 0; j < num_p_filters; j++)
  201609. {
  201610. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  201611. {
  201612. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  201613. PNG_WEIGHT_SHIFT;
  201614. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  201615. PNG_WEIGHT_SHIFT;
  201616. }
  201617. }
  201618. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  201619. PNG_COST_SHIFT;
  201620. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  201621. PNG_COST_SHIFT;
  201622. if (lmhi > PNG_HIMASK)
  201623. lmins = PNG_MAXSUM;
  201624. else
  201625. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  201626. }
  201627. #endif
  201628. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  201629. i++, rp++, dp++)
  201630. {
  201631. v = *dp = *rp;
  201632. sum += (v < 128) ? v : 256 - v;
  201633. }
  201634. for (lp = row_buf + 1; i < row_bytes;
  201635. i++, rp++, lp++, dp++)
  201636. {
  201637. v = *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  201638. sum += (v < 128) ? v : 256 - v;
  201639. if (sum > lmins) /* We are already worse, don't continue. */
  201640. break;
  201641. }
  201642. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  201643. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  201644. {
  201645. int j;
  201646. png_uint_32 sumhi, sumlo;
  201647. sumlo = sum & PNG_LOMASK;
  201648. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  201649. for (j = 0; j < num_p_filters; j++)
  201650. {
  201651. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  201652. {
  201653. sumlo = (sumlo * png_ptr->inv_filter_weights[j]) >>
  201654. PNG_WEIGHT_SHIFT;
  201655. sumhi = (sumhi * png_ptr->inv_filter_weights[j]) >>
  201656. PNG_WEIGHT_SHIFT;
  201657. }
  201658. }
  201659. sumlo = (sumlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  201660. PNG_COST_SHIFT;
  201661. sumhi = (sumhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  201662. PNG_COST_SHIFT;
  201663. if (sumhi > PNG_HIMASK)
  201664. sum = PNG_MAXSUM;
  201665. else
  201666. sum = (sumhi << PNG_HISHIFT) + sumlo;
  201667. }
  201668. #endif
  201669. if (sum < mins)
  201670. {
  201671. mins = sum;
  201672. best_row = png_ptr->sub_row;
  201673. }
  201674. }
  201675. /* up filter */
  201676. if (filter_to_do == PNG_FILTER_UP)
  201677. {
  201678. png_bytep rp, dp, pp;
  201679. png_uint_32 i;
  201680. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  201681. pp = prev_row + 1; i < row_bytes;
  201682. i++, rp++, pp++, dp++)
  201683. {
  201684. *dp = (png_byte)(((int)*rp - (int)*pp) & 0xff);
  201685. }
  201686. best_row = png_ptr->up_row;
  201687. }
  201688. else if (filter_to_do & PNG_FILTER_UP)
  201689. {
  201690. png_bytep rp, dp, pp;
  201691. png_uint_32 sum = 0, lmins = mins;
  201692. png_uint_32 i;
  201693. int v;
  201694. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  201695. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  201696. {
  201697. int j;
  201698. png_uint_32 lmhi, lmlo;
  201699. lmlo = lmins & PNG_LOMASK;
  201700. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  201701. for (j = 0; j < num_p_filters; j++)
  201702. {
  201703. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  201704. {
  201705. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  201706. PNG_WEIGHT_SHIFT;
  201707. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  201708. PNG_WEIGHT_SHIFT;
  201709. }
  201710. }
  201711. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  201712. PNG_COST_SHIFT;
  201713. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  201714. PNG_COST_SHIFT;
  201715. if (lmhi > PNG_HIMASK)
  201716. lmins = PNG_MAXSUM;
  201717. else
  201718. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  201719. }
  201720. #endif
  201721. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  201722. pp = prev_row + 1; i < row_bytes; i++)
  201723. {
  201724. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  201725. sum += (v < 128) ? v : 256 - v;
  201726. if (sum > lmins) /* We are already worse, don't continue. */
  201727. break;
  201728. }
  201729. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  201730. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  201731. {
  201732. int j;
  201733. png_uint_32 sumhi, sumlo;
  201734. sumlo = sum & PNG_LOMASK;
  201735. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  201736. for (j = 0; j < num_p_filters; j++)
  201737. {
  201738. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  201739. {
  201740. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  201741. PNG_WEIGHT_SHIFT;
  201742. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  201743. PNG_WEIGHT_SHIFT;
  201744. }
  201745. }
  201746. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  201747. PNG_COST_SHIFT;
  201748. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  201749. PNG_COST_SHIFT;
  201750. if (sumhi > PNG_HIMASK)
  201751. sum = PNG_MAXSUM;
  201752. else
  201753. sum = (sumhi << PNG_HISHIFT) + sumlo;
  201754. }
  201755. #endif
  201756. if (sum < mins)
  201757. {
  201758. mins = sum;
  201759. best_row = png_ptr->up_row;
  201760. }
  201761. }
  201762. /* avg filter */
  201763. if (filter_to_do == PNG_FILTER_AVG)
  201764. {
  201765. png_bytep rp, dp, pp, lp;
  201766. png_uint_32 i;
  201767. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  201768. pp = prev_row + 1; i < bpp; i++)
  201769. {
  201770. *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  201771. }
  201772. for (lp = row_buf + 1; i < row_bytes; i++)
  201773. {
  201774. *dp++ = (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2))
  201775. & 0xff);
  201776. }
  201777. best_row = png_ptr->avg_row;
  201778. }
  201779. else if (filter_to_do & PNG_FILTER_AVG)
  201780. {
  201781. png_bytep rp, dp, pp, lp;
  201782. png_uint_32 sum = 0, lmins = mins;
  201783. png_uint_32 i;
  201784. int v;
  201785. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  201786. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  201787. {
  201788. int j;
  201789. png_uint_32 lmhi, lmlo;
  201790. lmlo = lmins & PNG_LOMASK;
  201791. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  201792. for (j = 0; j < num_p_filters; j++)
  201793. {
  201794. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_AVG)
  201795. {
  201796. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  201797. PNG_WEIGHT_SHIFT;
  201798. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  201799. PNG_WEIGHT_SHIFT;
  201800. }
  201801. }
  201802. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  201803. PNG_COST_SHIFT;
  201804. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  201805. PNG_COST_SHIFT;
  201806. if (lmhi > PNG_HIMASK)
  201807. lmins = PNG_MAXSUM;
  201808. else
  201809. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  201810. }
  201811. #endif
  201812. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  201813. pp = prev_row + 1; i < bpp; i++)
  201814. {
  201815. v = *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  201816. sum += (v < 128) ? v : 256 - v;
  201817. }
  201818. for (lp = row_buf + 1; i < row_bytes; i++)
  201819. {
  201820. v = *dp++ =
  201821. (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2)) & 0xff);
  201822. sum += (v < 128) ? v : 256 - v;
  201823. if (sum > lmins) /* We are already worse, don't continue. */
  201824. break;
  201825. }
  201826. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  201827. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  201828. {
  201829. int j;
  201830. png_uint_32 sumhi, sumlo;
  201831. sumlo = sum & PNG_LOMASK;
  201832. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  201833. for (j = 0; j < num_p_filters; j++)
  201834. {
  201835. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  201836. {
  201837. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  201838. PNG_WEIGHT_SHIFT;
  201839. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  201840. PNG_WEIGHT_SHIFT;
  201841. }
  201842. }
  201843. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  201844. PNG_COST_SHIFT;
  201845. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  201846. PNG_COST_SHIFT;
  201847. if (sumhi > PNG_HIMASK)
  201848. sum = PNG_MAXSUM;
  201849. else
  201850. sum = (sumhi << PNG_HISHIFT) + sumlo;
  201851. }
  201852. #endif
  201853. if (sum < mins)
  201854. {
  201855. mins = sum;
  201856. best_row = png_ptr->avg_row;
  201857. }
  201858. }
  201859. /* Paeth filter */
  201860. if (filter_to_do == PNG_FILTER_PAETH)
  201861. {
  201862. png_bytep rp, dp, pp, cp, lp;
  201863. png_uint_32 i;
  201864. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  201865. pp = prev_row + 1; i < bpp; i++)
  201866. {
  201867. *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  201868. }
  201869. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  201870. {
  201871. int a, b, c, pa, pb, pc, p;
  201872. b = *pp++;
  201873. c = *cp++;
  201874. a = *lp++;
  201875. p = b - c;
  201876. pc = a - c;
  201877. #ifdef PNG_USE_ABS
  201878. pa = abs(p);
  201879. pb = abs(pc);
  201880. pc = abs(p + pc);
  201881. #else
  201882. pa = p < 0 ? -p : p;
  201883. pb = pc < 0 ? -pc : pc;
  201884. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  201885. #endif
  201886. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  201887. *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  201888. }
  201889. best_row = png_ptr->paeth_row;
  201890. }
  201891. else if (filter_to_do & PNG_FILTER_PAETH)
  201892. {
  201893. png_bytep rp, dp, pp, cp, lp;
  201894. png_uint_32 sum = 0, lmins = mins;
  201895. png_uint_32 i;
  201896. int v;
  201897. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  201898. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  201899. {
  201900. int j;
  201901. png_uint_32 lmhi, lmlo;
  201902. lmlo = lmins & PNG_LOMASK;
  201903. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  201904. for (j = 0; j < num_p_filters; j++)
  201905. {
  201906. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  201907. {
  201908. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  201909. PNG_WEIGHT_SHIFT;
  201910. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  201911. PNG_WEIGHT_SHIFT;
  201912. }
  201913. }
  201914. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  201915. PNG_COST_SHIFT;
  201916. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  201917. PNG_COST_SHIFT;
  201918. if (lmhi > PNG_HIMASK)
  201919. lmins = PNG_MAXSUM;
  201920. else
  201921. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  201922. }
  201923. #endif
  201924. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  201925. pp = prev_row + 1; i < bpp; i++)
  201926. {
  201927. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  201928. sum += (v < 128) ? v : 256 - v;
  201929. }
  201930. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  201931. {
  201932. int a, b, c, pa, pb, pc, p;
  201933. b = *pp++;
  201934. c = *cp++;
  201935. a = *lp++;
  201936. #ifndef PNG_SLOW_PAETH
  201937. p = b - c;
  201938. pc = a - c;
  201939. #ifdef PNG_USE_ABS
  201940. pa = abs(p);
  201941. pb = abs(pc);
  201942. pc = abs(p + pc);
  201943. #else
  201944. pa = p < 0 ? -p : p;
  201945. pb = pc < 0 ? -pc : pc;
  201946. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  201947. #endif
  201948. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  201949. #else /* PNG_SLOW_PAETH */
  201950. p = a + b - c;
  201951. pa = abs(p - a);
  201952. pb = abs(p - b);
  201953. pc = abs(p - c);
  201954. if (pa <= pb && pa <= pc)
  201955. p = a;
  201956. else if (pb <= pc)
  201957. p = b;
  201958. else
  201959. p = c;
  201960. #endif /* PNG_SLOW_PAETH */
  201961. v = *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  201962. sum += (v < 128) ? v : 256 - v;
  201963. if (sum > lmins) /* We are already worse, don't continue. */
  201964. break;
  201965. }
  201966. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  201967. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  201968. {
  201969. int j;
  201970. png_uint_32 sumhi, sumlo;
  201971. sumlo = sum & PNG_LOMASK;
  201972. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  201973. for (j = 0; j < num_p_filters; j++)
  201974. {
  201975. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  201976. {
  201977. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  201978. PNG_WEIGHT_SHIFT;
  201979. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  201980. PNG_WEIGHT_SHIFT;
  201981. }
  201982. }
  201983. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  201984. PNG_COST_SHIFT;
  201985. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  201986. PNG_COST_SHIFT;
  201987. if (sumhi > PNG_HIMASK)
  201988. sum = PNG_MAXSUM;
  201989. else
  201990. sum = (sumhi << PNG_HISHIFT) + sumlo;
  201991. }
  201992. #endif
  201993. if (sum < mins)
  201994. {
  201995. best_row = png_ptr->paeth_row;
  201996. }
  201997. }
  201998. #endif /* PNG_NO_WRITE_FILTER */
  201999. /* Do the actual writing of the filtered row data from the chosen filter. */
  202000. png_write_filtered_row(png_ptr, best_row);
  202001. #ifndef PNG_NO_WRITE_FILTER
  202002. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202003. /* Save the type of filter we picked this time for future calculations */
  202004. if (png_ptr->num_prev_filters > 0)
  202005. {
  202006. int j;
  202007. for (j = 1; j < num_p_filters; j++)
  202008. {
  202009. png_ptr->prev_filters[j] = png_ptr->prev_filters[j - 1];
  202010. }
  202011. png_ptr->prev_filters[j] = best_row[0];
  202012. }
  202013. #endif
  202014. #endif /* PNG_NO_WRITE_FILTER */
  202015. }
  202016. /* Do the actual writing of a previously filtered row. */
  202017. void /* PRIVATE */
  202018. png_write_filtered_row(png_structp png_ptr, png_bytep filtered_row)
  202019. {
  202020. png_debug(1, "in png_write_filtered_row\n");
  202021. png_debug1(2, "filter = %d\n", filtered_row[0]);
  202022. /* set up the zlib input buffer */
  202023. png_ptr->zstream.next_in = filtered_row;
  202024. png_ptr->zstream.avail_in = (uInt)png_ptr->row_info.rowbytes + 1;
  202025. /* repeat until we have compressed all the data */
  202026. do
  202027. {
  202028. int ret; /* return of zlib */
  202029. /* compress the data */
  202030. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  202031. /* check for compression errors */
  202032. if (ret != Z_OK)
  202033. {
  202034. if (png_ptr->zstream.msg != NULL)
  202035. png_error(png_ptr, png_ptr->zstream.msg);
  202036. else
  202037. png_error(png_ptr, "zlib error");
  202038. }
  202039. /* see if it is time to write another IDAT */
  202040. if (!(png_ptr->zstream.avail_out))
  202041. {
  202042. /* write the IDAT and reset the zlib output buffer */
  202043. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  202044. png_ptr->zstream.next_out = png_ptr->zbuf;
  202045. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  202046. }
  202047. /* repeat until all data has been compressed */
  202048. } while (png_ptr->zstream.avail_in);
  202049. /* swap the current and previous rows */
  202050. if (png_ptr->prev_row != NULL)
  202051. {
  202052. png_bytep tptr;
  202053. tptr = png_ptr->prev_row;
  202054. png_ptr->prev_row = png_ptr->row_buf;
  202055. png_ptr->row_buf = tptr;
  202056. }
  202057. /* finish row - updates counters and flushes zlib if last row */
  202058. png_write_finish_row(png_ptr);
  202059. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  202060. png_ptr->flush_rows++;
  202061. if (png_ptr->flush_dist > 0 &&
  202062. png_ptr->flush_rows >= png_ptr->flush_dist)
  202063. {
  202064. png_write_flush(png_ptr);
  202065. }
  202066. #endif
  202067. }
  202068. #endif /* PNG_WRITE_SUPPORTED */
  202069. /*** End of inlined file: pngwutil.c ***/
  202070. }
  202071. #else
  202072. extern "C"
  202073. {
  202074. #include <png.h>
  202075. #include <pngconf.h>
  202076. }
  202077. #endif
  202078. }
  202079. #undef max
  202080. #undef min
  202081. #if JUCE_MSVC
  202082. #pragma warning (pop)
  202083. #endif
  202084. BEGIN_JUCE_NAMESPACE
  202085. using ::calloc;
  202086. using ::malloc;
  202087. using ::free;
  202088. namespace PNGHelpers
  202089. {
  202090. using namespace pnglibNamespace;
  202091. static void readCallback (png_structp png, png_bytep data, png_size_t length)
  202092. {
  202093. static_cast<InputStream*> (png_get_io_ptr (png))->read (data, (int) length);
  202094. }
  202095. static void writeDataCallback (png_structp png, png_bytep data, png_size_t length)
  202096. {
  202097. static_cast<OutputStream*> (png_get_io_ptr (png))->write (data, (int) length);
  202098. }
  202099. struct PNGErrorStruct {};
  202100. static void errorCallback (png_structp, png_const_charp)
  202101. {
  202102. throw PNGErrorStruct();
  202103. }
  202104. }
  202105. PNGImageFormat::PNGImageFormat() {}
  202106. PNGImageFormat::~PNGImageFormat() {}
  202107. const String PNGImageFormat::getFormatName()
  202108. {
  202109. return "PNG";
  202110. }
  202111. bool PNGImageFormat::canUnderstand (InputStream& in)
  202112. {
  202113. const int bytesNeeded = 4;
  202114. char header [bytesNeeded];
  202115. return in.read (header, bytesNeeded) == bytesNeeded
  202116. && header[1] == 'P'
  202117. && header[2] == 'N'
  202118. && header[3] == 'G';
  202119. }
  202120. const Image PNGImageFormat::decodeImage (InputStream& in)
  202121. {
  202122. using namespace pnglibNamespace;
  202123. Image image;
  202124. png_structp pngReadStruct;
  202125. png_infop pngInfoStruct;
  202126. pngReadStruct = png_create_read_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  202127. if (pngReadStruct != 0)
  202128. {
  202129. pngInfoStruct = png_create_info_struct (pngReadStruct);
  202130. if (pngInfoStruct == 0)
  202131. {
  202132. png_destroy_read_struct (&pngReadStruct, 0, 0);
  202133. return Image();
  202134. }
  202135. png_set_error_fn (pngReadStruct, 0, PNGHelpers::errorCallback, PNGHelpers::errorCallback );
  202136. // read the header..
  202137. png_set_read_fn (pngReadStruct, &in, PNGHelpers::readCallback);
  202138. png_uint_32 width, height;
  202139. int bitDepth, colorType, interlaceType;
  202140. png_read_info (pngReadStruct, pngInfoStruct);
  202141. png_get_IHDR (pngReadStruct, pngInfoStruct,
  202142. &width, &height,
  202143. &bitDepth, &colorType,
  202144. &interlaceType, 0, 0);
  202145. if (bitDepth == 16)
  202146. png_set_strip_16 (pngReadStruct);
  202147. if (colorType == PNG_COLOR_TYPE_PALETTE)
  202148. png_set_expand (pngReadStruct);
  202149. if (bitDepth < 8)
  202150. png_set_expand (pngReadStruct);
  202151. if (png_get_valid (pngReadStruct, pngInfoStruct, PNG_INFO_tRNS))
  202152. png_set_expand (pngReadStruct);
  202153. if (colorType == PNG_COLOR_TYPE_GRAY || colorType == PNG_COLOR_TYPE_GRAY_ALPHA)
  202154. png_set_gray_to_rgb (pngReadStruct);
  202155. png_set_add_alpha (pngReadStruct, 0xff, PNG_FILLER_AFTER);
  202156. bool hasAlphaChan = (colorType & PNG_COLOR_MASK_ALPHA) != 0
  202157. || pngInfoStruct->num_trans > 0;
  202158. // Load the image into a temp buffer in the pnglib format..
  202159. HeapBlock <uint8> tempBuffer (height * (width << 2));
  202160. {
  202161. HeapBlock <png_bytep> rows (height);
  202162. for (int y = (int) height; --y >= 0;)
  202163. rows[y] = (png_bytep) (tempBuffer + (width << 2) * y);
  202164. png_read_image (pngReadStruct, rows);
  202165. png_read_end (pngReadStruct, pngInfoStruct);
  202166. }
  202167. png_destroy_read_struct (&pngReadStruct, &pngInfoStruct, 0);
  202168. // now convert the data to a juce image format..
  202169. image = Image (hasAlphaChan ? Image::ARGB : Image::RGB,
  202170. (int) width, (int) height, hasAlphaChan);
  202171. hasAlphaChan = image.hasAlphaChannel(); // (the native image creator may not give back what we expect)
  202172. const Image::BitmapData destData (image, 0, 0, (int) width, (int) height, true);
  202173. uint8* srcRow = tempBuffer;
  202174. uint8* destRow = destData.data;
  202175. for (int y = 0; y < (int) height; ++y)
  202176. {
  202177. const uint8* src = srcRow;
  202178. srcRow += (width << 2);
  202179. uint8* dest = destRow;
  202180. destRow += destData.lineStride;
  202181. if (hasAlphaChan)
  202182. {
  202183. for (int i = (int) width; --i >= 0;)
  202184. {
  202185. ((PixelARGB*) dest)->setARGB (src[3], src[0], src[1], src[2]);
  202186. ((PixelARGB*) dest)->premultiply();
  202187. dest += destData.pixelStride;
  202188. src += 4;
  202189. }
  202190. }
  202191. else
  202192. {
  202193. for (int i = (int) width; --i >= 0;)
  202194. {
  202195. ((PixelRGB*) dest)->setARGB (0, src[0], src[1], src[2]);
  202196. dest += destData.pixelStride;
  202197. src += 4;
  202198. }
  202199. }
  202200. }
  202201. }
  202202. return image;
  202203. }
  202204. bool PNGImageFormat::writeImageToStream (const Image& image, OutputStream& out)
  202205. {
  202206. using namespace pnglibNamespace;
  202207. const int width = image.getWidth();
  202208. const int height = image.getHeight();
  202209. png_structp pngWriteStruct = png_create_write_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  202210. if (pngWriteStruct == 0)
  202211. return false;
  202212. png_infop pngInfoStruct = png_create_info_struct (pngWriteStruct);
  202213. if (pngInfoStruct == 0)
  202214. {
  202215. png_destroy_write_struct (&pngWriteStruct, (png_infopp) 0);
  202216. return false;
  202217. }
  202218. png_set_write_fn (pngWriteStruct, &out, PNGHelpers::writeDataCallback, 0);
  202219. png_set_IHDR (pngWriteStruct, pngInfoStruct, width, height, 8,
  202220. image.hasAlphaChannel() ? PNG_COLOR_TYPE_RGB_ALPHA
  202221. : PNG_COLOR_TYPE_RGB,
  202222. PNG_INTERLACE_NONE,
  202223. PNG_COMPRESSION_TYPE_BASE,
  202224. PNG_FILTER_TYPE_BASE);
  202225. HeapBlock <uint8> rowData (width * 4);
  202226. png_color_8 sig_bit;
  202227. sig_bit.red = 8;
  202228. sig_bit.green = 8;
  202229. sig_bit.blue = 8;
  202230. sig_bit.alpha = 8;
  202231. png_set_sBIT (pngWriteStruct, pngInfoStruct, &sig_bit);
  202232. png_write_info (pngWriteStruct, pngInfoStruct);
  202233. png_set_shift (pngWriteStruct, &sig_bit);
  202234. png_set_packing (pngWriteStruct);
  202235. const Image::BitmapData srcData (image, 0, 0, width, height);
  202236. for (int y = 0; y < height; ++y)
  202237. {
  202238. uint8* dst = rowData;
  202239. const uint8* src = srcData.getLinePointer (y);
  202240. if (image.hasAlphaChannel())
  202241. {
  202242. for (int i = width; --i >= 0;)
  202243. {
  202244. PixelARGB p (*(const PixelARGB*) src);
  202245. p.unpremultiply();
  202246. *dst++ = p.getRed();
  202247. *dst++ = p.getGreen();
  202248. *dst++ = p.getBlue();
  202249. *dst++ = p.getAlpha();
  202250. src += srcData.pixelStride;
  202251. }
  202252. }
  202253. else
  202254. {
  202255. for (int i = width; --i >= 0;)
  202256. {
  202257. *dst++ = ((const PixelRGB*) src)->getRed();
  202258. *dst++ = ((const PixelRGB*) src)->getGreen();
  202259. *dst++ = ((const PixelRGB*) src)->getBlue();
  202260. src += srcData.pixelStride;
  202261. }
  202262. }
  202263. png_write_rows (pngWriteStruct, &rowData, 1);
  202264. }
  202265. png_write_end (pngWriteStruct, pngInfoStruct);
  202266. png_destroy_write_struct (&pngWriteStruct, &pngInfoStruct);
  202267. out.flush();
  202268. return true;
  202269. }
  202270. END_JUCE_NAMESPACE
  202271. /*** End of inlined file: juce_PNGLoader.cpp ***/
  202272. #endif
  202273. //==============================================================================
  202274. #if JUCE_BUILD_NATIVE
  202275. #if JUCE_WINDOWS
  202276. /*** Start of inlined file: juce_win32_NativeCode.cpp ***/
  202277. /*
  202278. This file wraps together all the win32-specific code, so that
  202279. we can include all the native headers just once, and compile all our
  202280. platform-specific stuff in one big lump, keeping it out of the way of
  202281. the rest of the codebase.
  202282. */
  202283. #if JUCE_WINDOWS
  202284. BEGIN_JUCE_NAMESPACE
  202285. #define JUCE_INCLUDED_FILE 1
  202286. // Now include the actual code files..
  202287. /*** Start of inlined file: juce_win32_DynamicLibraryLoader.cpp ***/
  202288. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  202289. // compiled on its own).
  202290. #if JUCE_INCLUDED_FILE
  202291. /*** Start of inlined file: juce_win32_DynamicLibraryLoader.h ***/
  202292. #ifndef __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  202293. #define __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  202294. #ifndef DOXYGEN
  202295. // use with DynamicLibraryLoader to simplify importing functions
  202296. //
  202297. // functionName: function to import
  202298. // localFunctionName: name you want to use to actually call it (must be different)
  202299. // returnType: the return type
  202300. // object: the DynamicLibraryLoader to use
  202301. // params: list of params (bracketed)
  202302. //
  202303. #define DynamicLibraryImport(functionName, localFunctionName, returnType, object, params) \
  202304. typedef returnType (WINAPI *type##localFunctionName) params; \
  202305. type##localFunctionName localFunctionName \
  202306. = (type##localFunctionName)object.findProcAddress (#functionName);
  202307. // loads and unloads a DLL automatically
  202308. class JUCE_API DynamicLibraryLoader
  202309. {
  202310. public:
  202311. DynamicLibraryLoader (const String& name);
  202312. ~DynamicLibraryLoader();
  202313. void* findProcAddress (const String& functionName);
  202314. private:
  202315. void* libHandle;
  202316. };
  202317. #endif
  202318. #endif // __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  202319. /*** End of inlined file: juce_win32_DynamicLibraryLoader.h ***/
  202320. DynamicLibraryLoader::DynamicLibraryLoader (const String& name)
  202321. {
  202322. libHandle = LoadLibrary (name);
  202323. }
  202324. DynamicLibraryLoader::~DynamicLibraryLoader()
  202325. {
  202326. FreeLibrary ((HMODULE) libHandle);
  202327. }
  202328. void* DynamicLibraryLoader::findProcAddress (const String& functionName)
  202329. {
  202330. return GetProcAddress ((HMODULE) libHandle, functionName.toCString());
  202331. }
  202332. #endif
  202333. /*** End of inlined file: juce_win32_DynamicLibraryLoader.cpp ***/
  202334. /*** Start of inlined file: juce_win32_SystemStats.cpp ***/
  202335. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  202336. // compiled on its own).
  202337. #if JUCE_INCLUDED_FILE
  202338. extern void juce_initialiseThreadEvents();
  202339. void Logger::outputDebugString (const String& text)
  202340. {
  202341. OutputDebugString (text + "\n");
  202342. }
  202343. static int64 hiResTicksPerSecond;
  202344. static double hiResTicksScaleFactor;
  202345. #if JUCE_USE_INTRINSICS
  202346. // CPU info functions using intrinsics...
  202347. #pragma intrinsic (__cpuid)
  202348. #pragma intrinsic (__rdtsc)
  202349. const String SystemStats::getCpuVendor()
  202350. {
  202351. int info [4];
  202352. __cpuid (info, 0);
  202353. char v [12];
  202354. memcpy (v, info + 1, 4);
  202355. memcpy (v + 4, info + 3, 4);
  202356. memcpy (v + 8, info + 2, 4);
  202357. return String (v, 12);
  202358. }
  202359. #else
  202360. // CPU info functions using old fashioned inline asm...
  202361. static void juce_getCpuVendor (char* const v)
  202362. {
  202363. int vendor[4];
  202364. zeromem (vendor, 16);
  202365. #ifdef JUCE_64BIT
  202366. #else
  202367. #ifndef __MINGW32__
  202368. __try
  202369. #endif
  202370. {
  202371. #if JUCE_GCC
  202372. unsigned int dummy = 0;
  202373. __asm__ ("cpuid" : "=a" (dummy), "=b" (vendor[0]), "=c" (vendor[2]),"=d" (vendor[1]) : "a" (0));
  202374. #else
  202375. __asm
  202376. {
  202377. mov eax, 0
  202378. cpuid
  202379. mov [vendor], ebx
  202380. mov [vendor + 4], edx
  202381. mov [vendor + 8], ecx
  202382. }
  202383. #endif
  202384. }
  202385. #ifndef __MINGW32__
  202386. __except (EXCEPTION_EXECUTE_HANDLER)
  202387. {
  202388. *v = 0;
  202389. }
  202390. #endif
  202391. #endif
  202392. memcpy (v, vendor, 16);
  202393. }
  202394. const String SystemStats::getCpuVendor()
  202395. {
  202396. char v [16];
  202397. juce_getCpuVendor (v);
  202398. return String (v, 16);
  202399. }
  202400. #endif
  202401. struct CPUFlags
  202402. {
  202403. bool hasMMX : 1;
  202404. bool hasSSE : 1;
  202405. bool hasSSE2 : 1;
  202406. bool has3DNow : 1;
  202407. };
  202408. static CPUFlags cpuFlags;
  202409. bool SystemStats::hasMMX()
  202410. {
  202411. return cpuFlags.hasMMX;
  202412. }
  202413. bool SystemStats::hasSSE()
  202414. {
  202415. return cpuFlags.hasSSE;
  202416. }
  202417. bool SystemStats::hasSSE2()
  202418. {
  202419. return cpuFlags.hasSSE2;
  202420. }
  202421. bool SystemStats::has3DNow()
  202422. {
  202423. return cpuFlags.has3DNow;
  202424. }
  202425. void SystemStats::initialiseStats()
  202426. {
  202427. juce_initialiseThreadEvents();
  202428. cpuFlags.hasMMX = IsProcessorFeaturePresent (PF_MMX_INSTRUCTIONS_AVAILABLE) != 0;
  202429. cpuFlags.hasSSE = IsProcessorFeaturePresent (PF_XMMI_INSTRUCTIONS_AVAILABLE) != 0;
  202430. cpuFlags.hasSSE2 = IsProcessorFeaturePresent (PF_XMMI64_INSTRUCTIONS_AVAILABLE) != 0;
  202431. #ifdef PF_AMD3D_INSTRUCTIONS_AVAILABLE
  202432. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_AMD3D_INSTRUCTIONS_AVAILABLE) != 0;
  202433. #else
  202434. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_3DNOW_INSTRUCTIONS_AVAILABLE) != 0;
  202435. #endif
  202436. LARGE_INTEGER f;
  202437. QueryPerformanceFrequency (&f);
  202438. hiResTicksPerSecond = f.QuadPart;
  202439. hiResTicksScaleFactor = 1000.0 / hiResTicksPerSecond;
  202440. String s (SystemStats::getJUCEVersion());
  202441. #if JUCE_DEBUG
  202442. const MMRESULT res = timeBeginPeriod (1);
  202443. jassert (res == TIMERR_NOERROR);
  202444. #else
  202445. timeBeginPeriod (1);
  202446. #endif
  202447. #if JUCE_DEBUG && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  202448. _CrtSetDbgFlag (_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
  202449. #endif
  202450. }
  202451. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  202452. {
  202453. OSVERSIONINFO info;
  202454. info.dwOSVersionInfoSize = sizeof (info);
  202455. GetVersionEx (&info);
  202456. if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
  202457. {
  202458. switch (info.dwMajorVersion)
  202459. {
  202460. case 5: return (info.dwMinorVersion == 0) ? Win2000 : WinXP;
  202461. case 6: return (info.dwMinorVersion == 0) ? WinVista : Windows7;
  202462. default: jassertfalse; break; // !! not a supported OS!
  202463. }
  202464. }
  202465. else if (info.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
  202466. {
  202467. jassert (info.dwMinorVersion != 0); // !! still running on Windows 95??
  202468. return Win98;
  202469. }
  202470. return UnknownOS;
  202471. }
  202472. const String SystemStats::getOperatingSystemName()
  202473. {
  202474. const char* name = "Unknown OS";
  202475. switch (getOperatingSystemType())
  202476. {
  202477. case Windows7: name = "Windows 7"; break;
  202478. case WinVista: name = "Windows Vista"; break;
  202479. case WinXP: name = "Windows XP"; break;
  202480. case Win2000: name = "Windows 2000"; break;
  202481. case Win98: name = "Windows 98"; break;
  202482. default: jassertfalse; break; // !! new type of OS?
  202483. }
  202484. return name;
  202485. }
  202486. bool SystemStats::isOperatingSystem64Bit()
  202487. {
  202488. #ifdef _WIN64
  202489. return true;
  202490. #else
  202491. typedef BOOL (WINAPI* LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
  202492. LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress (GetModuleHandle (L"kernel32"), "IsWow64Process");
  202493. BOOL isWow64 = FALSE;
  202494. return (fnIsWow64Process != 0)
  202495. && fnIsWow64Process (GetCurrentProcess(), &isWow64)
  202496. && (isWow64 != FALSE);
  202497. #endif
  202498. }
  202499. int SystemStats::getMemorySizeInMegabytes()
  202500. {
  202501. MEMORYSTATUSEX mem;
  202502. mem.dwLength = sizeof (mem);
  202503. GlobalMemoryStatusEx (&mem);
  202504. return (int) (mem.ullTotalPhys / (1024 * 1024)) + 1;
  202505. }
  202506. int SystemStats::getNumCpus()
  202507. {
  202508. SYSTEM_INFO systemInfo;
  202509. GetSystemInfo (&systemInfo);
  202510. return systemInfo.dwNumberOfProcessors;
  202511. }
  202512. uint32 juce_millisecondsSinceStartup() throw()
  202513. {
  202514. return (uint32) GetTickCount();
  202515. }
  202516. int64 Time::getHighResolutionTicks() throw()
  202517. {
  202518. LARGE_INTEGER ticks;
  202519. QueryPerformanceCounter (&ticks);
  202520. const int64 mainCounterAsHiResTicks = (GetTickCount() * hiResTicksPerSecond) / 1000;
  202521. const int64 newOffset = mainCounterAsHiResTicks - ticks.QuadPart;
  202522. // fix for a very obscure PCI hardware bug that can make the counter
  202523. // sometimes jump forwards by a few seconds..
  202524. static int64 hiResTicksOffset = 0;
  202525. const int64 offsetDrift = abs64 (newOffset - hiResTicksOffset);
  202526. if (offsetDrift > (hiResTicksPerSecond >> 1))
  202527. hiResTicksOffset = newOffset;
  202528. return ticks.QuadPart + hiResTicksOffset;
  202529. }
  202530. double Time::getMillisecondCounterHiRes() throw()
  202531. {
  202532. return getHighResolutionTicks() * hiResTicksScaleFactor;
  202533. }
  202534. int64 Time::getHighResolutionTicksPerSecond() throw()
  202535. {
  202536. return hiResTicksPerSecond;
  202537. }
  202538. static int64 juce_getClockCycleCounter() throw()
  202539. {
  202540. #if JUCE_USE_INTRINSICS
  202541. // MS intrinsics version...
  202542. return __rdtsc();
  202543. #elif JUCE_GCC
  202544. // GNU inline asm version...
  202545. unsigned int hi = 0, lo = 0;
  202546. __asm__ __volatile__ (
  202547. "xor %%eax, %%eax \n\
  202548. xor %%edx, %%edx \n\
  202549. rdtsc \n\
  202550. movl %%eax, %[lo] \n\
  202551. movl %%edx, %[hi]"
  202552. :
  202553. : [hi] "m" (hi),
  202554. [lo] "m" (lo)
  202555. : "cc", "eax", "ebx", "ecx", "edx", "memory");
  202556. return (int64) ((((uint64) hi) << 32) | lo);
  202557. #else
  202558. // MSVC inline asm version...
  202559. unsigned int hi = 0, lo = 0;
  202560. __asm
  202561. {
  202562. xor eax, eax
  202563. xor edx, edx
  202564. rdtsc
  202565. mov lo, eax
  202566. mov hi, edx
  202567. }
  202568. return (int64) ((((uint64) hi) << 32) | lo);
  202569. #endif
  202570. }
  202571. int SystemStats::getCpuSpeedInMegaherz()
  202572. {
  202573. const int64 cycles = juce_getClockCycleCounter();
  202574. const uint32 millis = Time::getMillisecondCounter();
  202575. int lastResult = 0;
  202576. for (;;)
  202577. {
  202578. int n = 1000000;
  202579. while (--n > 0) {}
  202580. const uint32 millisElapsed = Time::getMillisecondCounter() - millis;
  202581. const int64 cyclesNow = juce_getClockCycleCounter();
  202582. if (millisElapsed > 80)
  202583. {
  202584. const int newResult = (int) (((cyclesNow - cycles) / millisElapsed) / 1000);
  202585. if (millisElapsed > 500 || (lastResult == newResult && newResult > 100))
  202586. return newResult;
  202587. lastResult = newResult;
  202588. }
  202589. }
  202590. }
  202591. bool Time::setSystemTimeToThisTime() const
  202592. {
  202593. SYSTEMTIME st;
  202594. st.wDayOfWeek = 0;
  202595. st.wYear = (WORD) getYear();
  202596. st.wMonth = (WORD) (getMonth() + 1);
  202597. st.wDay = (WORD) getDayOfMonth();
  202598. st.wHour = (WORD) getHours();
  202599. st.wMinute = (WORD) getMinutes();
  202600. st.wSecond = (WORD) getSeconds();
  202601. st.wMilliseconds = (WORD) (millisSinceEpoch % 1000);
  202602. // do this twice because of daylight saving conversion problems - the
  202603. // first one sets it up, the second one kicks it in.
  202604. return SetLocalTime (&st) != 0
  202605. && SetLocalTime (&st) != 0;
  202606. }
  202607. int SystemStats::getPageSize()
  202608. {
  202609. SYSTEM_INFO systemInfo;
  202610. GetSystemInfo (&systemInfo);
  202611. return systemInfo.dwPageSize;
  202612. }
  202613. const String SystemStats::getLogonName()
  202614. {
  202615. TCHAR text [256];
  202616. DWORD len = numElementsInArray (text) - 2;
  202617. zerostruct (text);
  202618. GetUserName (text, &len);
  202619. return String (text, len);
  202620. }
  202621. const String SystemStats::getFullUserName()
  202622. {
  202623. return getLogonName();
  202624. }
  202625. #endif
  202626. /*** End of inlined file: juce_win32_SystemStats.cpp ***/
  202627. /*** Start of inlined file: juce_win32_Threads.cpp ***/
  202628. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  202629. // compiled on its own).
  202630. #if JUCE_INCLUDED_FILE
  202631. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  202632. extern HWND juce_messageWindowHandle;
  202633. #endif
  202634. #if ! JUCE_USE_INTRINSICS
  202635. // In newer compilers, the inline versions of these are used (in juce_Atomic.h), but in
  202636. // older ones we have to actually call the ops as win32 functions..
  202637. long juce_InterlockedExchange (volatile long* a, long b) throw() { return InterlockedExchange (a, b); }
  202638. long juce_InterlockedIncrement (volatile long* a) throw() { return InterlockedIncrement (a); }
  202639. long juce_InterlockedDecrement (volatile long* a) throw() { return InterlockedDecrement (a); }
  202640. long juce_InterlockedExchangeAdd (volatile long* a, long b) throw() { return InterlockedExchangeAdd (a, b); }
  202641. long juce_InterlockedCompareExchange (volatile long* a, long b, long c) throw() { return InterlockedCompareExchange (a, b, c); }
  202642. __int64 juce_InterlockedCompareExchange64 (volatile __int64* value, __int64 newValue, __int64 valueToCompare) throw()
  202643. {
  202644. jassertfalse; // This operation isn't available in old MS compiler versions!
  202645. __int64 oldValue = *value;
  202646. if (oldValue == valueToCompare)
  202647. *value = newValue;
  202648. return oldValue;
  202649. }
  202650. #endif
  202651. CriticalSection::CriticalSection() throw()
  202652. {
  202653. // (just to check the MS haven't changed this structure and broken things...)
  202654. #if _MSC_VER >= 1400
  202655. static_jassert (sizeof (CRITICAL_SECTION) <= sizeof (internal));
  202656. #else
  202657. static_jassert (sizeof (CRITICAL_SECTION) <= 24);
  202658. #endif
  202659. InitializeCriticalSection ((CRITICAL_SECTION*) internal);
  202660. }
  202661. CriticalSection::~CriticalSection() throw()
  202662. {
  202663. DeleteCriticalSection ((CRITICAL_SECTION*) internal);
  202664. }
  202665. void CriticalSection::enter() const throw()
  202666. {
  202667. EnterCriticalSection ((CRITICAL_SECTION*) internal);
  202668. }
  202669. bool CriticalSection::tryEnter() const throw()
  202670. {
  202671. return TryEnterCriticalSection ((CRITICAL_SECTION*) internal) != FALSE;
  202672. }
  202673. void CriticalSection::exit() const throw()
  202674. {
  202675. LeaveCriticalSection ((CRITICAL_SECTION*) internal);
  202676. }
  202677. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  202678. : internal (CreateEvent (0, manualReset ? TRUE : FALSE, FALSE, 0))
  202679. {
  202680. }
  202681. WaitableEvent::~WaitableEvent() throw()
  202682. {
  202683. CloseHandle (internal);
  202684. }
  202685. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  202686. {
  202687. return WaitForSingleObject (internal, timeOutMillisecs) == WAIT_OBJECT_0;
  202688. }
  202689. void WaitableEvent::signal() const throw()
  202690. {
  202691. SetEvent (internal);
  202692. }
  202693. void WaitableEvent::reset() const throw()
  202694. {
  202695. ResetEvent (internal);
  202696. }
  202697. void JUCE_API juce_threadEntryPoint (void*);
  202698. static unsigned int __stdcall threadEntryProc (void* userData)
  202699. {
  202700. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  202701. AttachThreadInput (GetWindowThreadProcessId (juce_messageWindowHandle, 0),
  202702. GetCurrentThreadId(), TRUE);
  202703. #endif
  202704. juce_threadEntryPoint (userData);
  202705. _endthreadex (0);
  202706. return 0;
  202707. }
  202708. void juce_CloseThreadHandle (void* handle)
  202709. {
  202710. CloseHandle ((HANDLE) handle);
  202711. }
  202712. void* juce_createThread (void* userData)
  202713. {
  202714. unsigned int threadId;
  202715. return (void*) _beginthreadex (0, 0, &threadEntryProc, userData, 0, &threadId);
  202716. }
  202717. void juce_killThread (void* handle)
  202718. {
  202719. if (handle != 0)
  202720. {
  202721. #if JUCE_DEBUG
  202722. OutputDebugString (_T("** Warning - Forced thread termination **\n"));
  202723. #endif
  202724. TerminateThread (handle, 0);
  202725. }
  202726. }
  202727. void juce_setCurrentThreadName (const String& name)
  202728. {
  202729. #if JUCE_DEBUG && JUCE_MSVC
  202730. struct
  202731. {
  202732. DWORD dwType;
  202733. LPCSTR szName;
  202734. DWORD dwThreadID;
  202735. DWORD dwFlags;
  202736. } info;
  202737. info.dwType = 0x1000;
  202738. info.szName = name.toCString();
  202739. info.dwThreadID = GetCurrentThreadId();
  202740. info.dwFlags = 0;
  202741. __try
  202742. {
  202743. RaiseException (0x406d1388 /*MS_VC_EXCEPTION*/, 0, sizeof (info) / sizeof (ULONG_PTR), (ULONG_PTR*) &info);
  202744. }
  202745. __except (EXCEPTION_CONTINUE_EXECUTION)
  202746. {}
  202747. #else
  202748. (void) name;
  202749. #endif
  202750. }
  202751. Thread::ThreadID Thread::getCurrentThreadId()
  202752. {
  202753. return (ThreadID) (pointer_sized_int) GetCurrentThreadId();
  202754. }
  202755. // priority 1 to 10 where 5=normal, 1=low
  202756. bool juce_setThreadPriority (void* threadHandle, int priority)
  202757. {
  202758. int pri = THREAD_PRIORITY_TIME_CRITICAL;
  202759. if (priority < 1)
  202760. pri = THREAD_PRIORITY_IDLE;
  202761. else if (priority < 2)
  202762. pri = THREAD_PRIORITY_LOWEST;
  202763. else if (priority < 5)
  202764. pri = THREAD_PRIORITY_BELOW_NORMAL;
  202765. else if (priority < 7)
  202766. pri = THREAD_PRIORITY_NORMAL;
  202767. else if (priority < 9)
  202768. pri = THREAD_PRIORITY_ABOVE_NORMAL;
  202769. else if (priority < 10)
  202770. pri = THREAD_PRIORITY_HIGHEST;
  202771. if (threadHandle == 0)
  202772. threadHandle = GetCurrentThread();
  202773. return SetThreadPriority (threadHandle, pri) != FALSE;
  202774. }
  202775. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  202776. {
  202777. SetThreadAffinityMask (GetCurrentThread(), affinityMask);
  202778. }
  202779. static HANDLE sleepEvent = 0;
  202780. void juce_initialiseThreadEvents()
  202781. {
  202782. if (sleepEvent == 0)
  202783. #if JUCE_DEBUG
  202784. sleepEvent = CreateEvent (0, 0, 0, _T("Juce Sleep Event"));
  202785. #else
  202786. sleepEvent = CreateEvent (0, 0, 0, 0);
  202787. #endif
  202788. }
  202789. void Thread::yield()
  202790. {
  202791. Sleep (0);
  202792. }
  202793. void JUCE_CALLTYPE Thread::sleep (const int millisecs)
  202794. {
  202795. if (millisecs >= 10)
  202796. {
  202797. Sleep (millisecs);
  202798. }
  202799. else
  202800. {
  202801. jassert (sleepEvent != 0);
  202802. // unlike Sleep() this is guaranteed to return to the current thread after
  202803. // the time expires, so we'll use this for short waits, which are more likely
  202804. // to need to be accurate
  202805. WaitForSingleObject (sleepEvent, millisecs);
  202806. }
  202807. }
  202808. static int lastProcessPriority = -1;
  202809. // called by WindowDriver because Windows does wierd things to process priority
  202810. // when you swap apps, and this forces an update when the app is brought to the front.
  202811. void juce_repeatLastProcessPriority()
  202812. {
  202813. if (lastProcessPriority >= 0) // (avoid changing this if it's not been explicitly set by the app..)
  202814. {
  202815. DWORD p;
  202816. switch (lastProcessPriority)
  202817. {
  202818. case Process::LowPriority: p = IDLE_PRIORITY_CLASS; break;
  202819. case Process::NormalPriority: p = NORMAL_PRIORITY_CLASS; break;
  202820. case Process::HighPriority: p = HIGH_PRIORITY_CLASS; break;
  202821. case Process::RealtimePriority: p = REALTIME_PRIORITY_CLASS; break;
  202822. default: jassertfalse; return; // bad priority value
  202823. }
  202824. SetPriorityClass (GetCurrentProcess(), p);
  202825. }
  202826. }
  202827. void Process::setPriority (ProcessPriority prior)
  202828. {
  202829. if (lastProcessPriority != (int) prior)
  202830. {
  202831. lastProcessPriority = (int) prior;
  202832. juce_repeatLastProcessPriority();
  202833. }
  202834. }
  202835. bool JUCE_PUBLIC_FUNCTION juce_isRunningUnderDebugger()
  202836. {
  202837. return IsDebuggerPresent() != FALSE;
  202838. }
  202839. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  202840. {
  202841. return juce_isRunningUnderDebugger();
  202842. }
  202843. void Process::raisePrivilege()
  202844. {
  202845. jassertfalse; // xxx not implemented
  202846. }
  202847. void Process::lowerPrivilege()
  202848. {
  202849. jassertfalse; // xxx not implemented
  202850. }
  202851. void Process::terminate()
  202852. {
  202853. #if JUCE_DEBUG && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  202854. _CrtDumpMemoryLeaks();
  202855. #endif
  202856. // bullet in the head in case there's a problem shutting down..
  202857. ExitProcess (0);
  202858. }
  202859. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  202860. {
  202861. void* result = 0;
  202862. JUCE_TRY
  202863. {
  202864. result = LoadLibrary (name);
  202865. }
  202866. JUCE_CATCH_ALL
  202867. return result;
  202868. }
  202869. void PlatformUtilities::freeDynamicLibrary (void* h)
  202870. {
  202871. JUCE_TRY
  202872. {
  202873. if (h != 0)
  202874. FreeLibrary ((HMODULE) h);
  202875. }
  202876. JUCE_CATCH_ALL
  202877. }
  202878. void* PlatformUtilities::getProcedureEntryPoint (void* h, const String& name)
  202879. {
  202880. return (h != 0) ? GetProcAddress ((HMODULE) h, name.toCString()) : 0;
  202881. }
  202882. class InterProcessLock::Pimpl
  202883. {
  202884. public:
  202885. Pimpl (const String& name, const int timeOutMillisecs)
  202886. : handle (0), refCount (1)
  202887. {
  202888. handle = CreateMutex (0, TRUE, "Global\\" + name.replaceCharacter ('\\','/'));
  202889. if (handle != 0 && GetLastError() == ERROR_ALREADY_EXISTS)
  202890. {
  202891. if (timeOutMillisecs == 0)
  202892. {
  202893. close();
  202894. return;
  202895. }
  202896. switch (WaitForSingleObject (handle, timeOutMillisecs < 0 ? INFINITE : timeOutMillisecs))
  202897. {
  202898. case WAIT_OBJECT_0:
  202899. case WAIT_ABANDONED:
  202900. break;
  202901. case WAIT_TIMEOUT:
  202902. default:
  202903. close();
  202904. break;
  202905. }
  202906. }
  202907. }
  202908. ~Pimpl()
  202909. {
  202910. close();
  202911. }
  202912. void close()
  202913. {
  202914. if (handle != 0)
  202915. {
  202916. ReleaseMutex (handle);
  202917. CloseHandle (handle);
  202918. handle = 0;
  202919. }
  202920. }
  202921. HANDLE handle;
  202922. int refCount;
  202923. };
  202924. InterProcessLock::InterProcessLock (const String& name_)
  202925. : name (name_)
  202926. {
  202927. }
  202928. InterProcessLock::~InterProcessLock()
  202929. {
  202930. }
  202931. bool InterProcessLock::enter (const int timeOutMillisecs)
  202932. {
  202933. const ScopedLock sl (lock);
  202934. if (pimpl == 0)
  202935. {
  202936. pimpl = new Pimpl (name, timeOutMillisecs);
  202937. if (pimpl->handle == 0)
  202938. pimpl = 0;
  202939. }
  202940. else
  202941. {
  202942. pimpl->refCount++;
  202943. }
  202944. return pimpl != 0;
  202945. }
  202946. void InterProcessLock::exit()
  202947. {
  202948. const ScopedLock sl (lock);
  202949. // Trying to release the lock too many times!
  202950. jassert (pimpl != 0);
  202951. if (pimpl != 0 && --(pimpl->refCount) == 0)
  202952. pimpl = 0;
  202953. }
  202954. #endif
  202955. /*** End of inlined file: juce_win32_Threads.cpp ***/
  202956. /*** Start of inlined file: juce_win32_Files.cpp ***/
  202957. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  202958. // compiled on its own).
  202959. #if JUCE_INCLUDED_FILE
  202960. #ifndef CSIDL_MYMUSIC
  202961. #define CSIDL_MYMUSIC 0x000d
  202962. #endif
  202963. #ifndef CSIDL_MYVIDEO
  202964. #define CSIDL_MYVIDEO 0x000e
  202965. #endif
  202966. #ifndef INVALID_FILE_ATTRIBUTES
  202967. #define INVALID_FILE_ATTRIBUTES ((DWORD) -1)
  202968. #endif
  202969. const juce_wchar File::separator = '\\';
  202970. const String File::separatorString ("\\");
  202971. bool File::exists() const
  202972. {
  202973. return fullPath.isNotEmpty()
  202974. && GetFileAttributes (fullPath) != INVALID_FILE_ATTRIBUTES;
  202975. }
  202976. bool File::existsAsFile() const
  202977. {
  202978. return fullPath.isNotEmpty()
  202979. && (GetFileAttributes (fullPath) & FILE_ATTRIBUTE_DIRECTORY) == 0;
  202980. }
  202981. bool File::isDirectory() const
  202982. {
  202983. const DWORD attr = GetFileAttributes (fullPath);
  202984. return ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) && (attr != INVALID_FILE_ATTRIBUTES);
  202985. }
  202986. bool File::hasWriteAccess() const
  202987. {
  202988. if (exists())
  202989. return (GetFileAttributes (fullPath) & FILE_ATTRIBUTE_READONLY) == 0;
  202990. // on windows, it seems that even read-only directories can still be written into,
  202991. // so checking the parent directory's permissions would return the wrong result..
  202992. return true;
  202993. }
  202994. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  202995. {
  202996. DWORD attr = GetFileAttributes (fullPath);
  202997. if (attr == INVALID_FILE_ATTRIBUTES)
  202998. return false;
  202999. if (shouldBeReadOnly == ((attr & FILE_ATTRIBUTE_READONLY) != 0))
  203000. return true;
  203001. if (shouldBeReadOnly)
  203002. attr |= FILE_ATTRIBUTE_READONLY;
  203003. else
  203004. attr &= ~FILE_ATTRIBUTE_READONLY;
  203005. return SetFileAttributes (fullPath, attr) != FALSE;
  203006. }
  203007. bool File::isHidden() const
  203008. {
  203009. return (GetFileAttributes (getFullPathName()) & FILE_ATTRIBUTE_HIDDEN) != 0;
  203010. }
  203011. bool File::deleteFile() const
  203012. {
  203013. if (! exists())
  203014. return true;
  203015. else if (isDirectory())
  203016. return RemoveDirectory (fullPath) != 0;
  203017. else
  203018. return DeleteFile (fullPath) != 0;
  203019. }
  203020. bool File::moveToTrash() const
  203021. {
  203022. if (! exists())
  203023. return true;
  203024. SHFILEOPSTRUCT fos;
  203025. zerostruct (fos);
  203026. // The string we pass in must be double null terminated..
  203027. String doubleNullTermPath (getFullPathName() + " ");
  203028. TCHAR* const p = const_cast <TCHAR*> (static_cast <const TCHAR*> (doubleNullTermPath));
  203029. p [getFullPathName().length()] = 0;
  203030. fos.wFunc = FO_DELETE;
  203031. fos.pFrom = p;
  203032. fos.fFlags = FOF_ALLOWUNDO | FOF_NOERRORUI | FOF_SILENT | FOF_NOCONFIRMATION
  203033. | FOF_NOCONFIRMMKDIR | FOF_RENAMEONCOLLISION;
  203034. return SHFileOperation (&fos) == 0;
  203035. }
  203036. bool File::copyInternal (const File& dest) const
  203037. {
  203038. return CopyFile (fullPath, dest.getFullPathName(), false) != 0;
  203039. }
  203040. bool File::moveInternal (const File& dest) const
  203041. {
  203042. return MoveFile (fullPath, dest.getFullPathName()) != 0;
  203043. }
  203044. void File::createDirectoryInternal (const String& fileName) const
  203045. {
  203046. CreateDirectory (fileName, 0);
  203047. }
  203048. // return 0 if not possible
  203049. void* juce_fileOpen (const File& file, bool forWriting)
  203050. {
  203051. HANDLE h;
  203052. if (forWriting)
  203053. {
  203054. h = CreateFile (file.getFullPathName(), GENERIC_WRITE, FILE_SHARE_READ, 0,
  203055. OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  203056. if (h != INVALID_HANDLE_VALUE)
  203057. SetFilePointer (h, 0, 0, FILE_END);
  203058. else
  203059. h = 0;
  203060. }
  203061. else
  203062. {
  203063. h = CreateFile (file.getFullPathName(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
  203064. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, 0);
  203065. if (h == INVALID_HANDLE_VALUE)
  203066. h = 0;
  203067. }
  203068. return h;
  203069. }
  203070. void juce_fileClose (void* handle)
  203071. {
  203072. CloseHandle (handle);
  203073. }
  203074. int juce_fileRead (void* handle, void* buffer, int size)
  203075. {
  203076. DWORD num = 0;
  203077. ReadFile ((HANDLE) handle, buffer, size, &num, 0);
  203078. return (int) num;
  203079. }
  203080. int juce_fileWrite (void* handle, const void* buffer, int size)
  203081. {
  203082. DWORD num;
  203083. WriteFile ((HANDLE) handle, buffer, size, &num, 0);
  203084. return (int) num;
  203085. }
  203086. int64 juce_fileSetPosition (void* handle, int64 pos)
  203087. {
  203088. LARGE_INTEGER li;
  203089. li.QuadPart = pos;
  203090. li.LowPart = SetFilePointer ((HANDLE) handle, li.LowPart, &li.HighPart, FILE_BEGIN); // (returns -1 if it fails)
  203091. return li.QuadPart;
  203092. }
  203093. int64 FileOutputStream::getPositionInternal() const
  203094. {
  203095. if (fileHandle == 0)
  203096. return -1;
  203097. LARGE_INTEGER li;
  203098. li.QuadPart = 0;
  203099. li.LowPart = SetFilePointer ((HANDLE) fileHandle, 0, &li.HighPart, FILE_CURRENT); // (returns -1 if it fails)
  203100. return jmax ((int64) 0, li.QuadPart);
  203101. }
  203102. void FileOutputStream::flushInternal()
  203103. {
  203104. if (fileHandle != 0)
  203105. FlushFileBuffers ((HANDLE) fileHandle);
  203106. }
  203107. int64 File::getSize() const
  203108. {
  203109. WIN32_FILE_ATTRIBUTE_DATA attributes;
  203110. if (GetFileAttributesEx (fullPath, GetFileExInfoStandard, &attributes))
  203111. return (((int64) attributes.nFileSizeHigh) << 32) | attributes.nFileSizeLow;
  203112. return 0;
  203113. }
  203114. static int64 fileTimeToTime (const FILETIME* const ft)
  203115. {
  203116. static_jassert (sizeof (ULARGE_INTEGER) == sizeof (FILETIME)); // tell me if this fails!
  203117. return (reinterpret_cast<const ULARGE_INTEGER*> (ft)->QuadPart - literal64bit (116444736000000000)) / 10000;
  203118. }
  203119. static void timeToFileTime (const int64 time, FILETIME* const ft)
  203120. {
  203121. reinterpret_cast<ULARGE_INTEGER*> (ft)->QuadPart = time * 10000 + literal64bit (116444736000000000);
  203122. }
  203123. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  203124. {
  203125. WIN32_FILE_ATTRIBUTE_DATA attributes;
  203126. if (GetFileAttributesEx (fullPath, GetFileExInfoStandard, &attributes))
  203127. {
  203128. modificationTime = fileTimeToTime (&attributes.ftLastWriteTime);
  203129. creationTime = fileTimeToTime (&attributes.ftCreationTime);
  203130. accessTime = fileTimeToTime (&attributes.ftLastAccessTime);
  203131. }
  203132. else
  203133. {
  203134. creationTime = accessTime = modificationTime = 0;
  203135. }
  203136. }
  203137. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 creationTime) const
  203138. {
  203139. void* const h = juce_fileOpen (fullPath, true);
  203140. bool ok = false;
  203141. if (h != 0)
  203142. {
  203143. FILETIME m, a, c;
  203144. timeToFileTime (modificationTime, &m);
  203145. timeToFileTime (accessTime, &a);
  203146. timeToFileTime (creationTime, &c);
  203147. ok = SetFileTime ((HANDLE) h,
  203148. creationTime > 0 ? &c : 0,
  203149. accessTime > 0 ? &a : 0,
  203150. modificationTime > 0 ? &m : 0) != 0;
  203151. juce_fileClose (h);
  203152. }
  203153. return ok;
  203154. }
  203155. void File::findFileSystemRoots (Array<File>& destArray)
  203156. {
  203157. TCHAR buffer [2048];
  203158. buffer[0] = 0;
  203159. buffer[1] = 0;
  203160. GetLogicalDriveStrings (2048, buffer);
  203161. const TCHAR* n = buffer;
  203162. StringArray roots;
  203163. while (*n != 0)
  203164. {
  203165. roots.add (String (n));
  203166. while (*n++ != 0)
  203167. {}
  203168. }
  203169. roots.sort (true);
  203170. for (int i = 0; i < roots.size(); ++i)
  203171. destArray.add (roots [i]);
  203172. }
  203173. static const String getDriveFromPath (const String& path)
  203174. {
  203175. if (path.isNotEmpty() && path[1] == ':')
  203176. return path.substring (0, 2) + '\\';
  203177. return path;
  203178. }
  203179. const String File::getVolumeLabel() const
  203180. {
  203181. TCHAR dest[64];
  203182. if (! GetVolumeInformation (getDriveFromPath (getFullPathName()), dest,
  203183. numElementsInArray (dest), 0, 0, 0, 0, 0))
  203184. dest[0] = 0;
  203185. return dest;
  203186. }
  203187. int File::getVolumeSerialNumber() const
  203188. {
  203189. TCHAR dest[64];
  203190. DWORD serialNum;
  203191. if (! GetVolumeInformation (getDriveFromPath (getFullPathName()), dest,
  203192. numElementsInArray (dest), &serialNum, 0, 0, 0, 0))
  203193. return 0;
  203194. return (int) serialNum;
  203195. }
  203196. static int64 getDiskSpaceInfo (const String& path, const bool total)
  203197. {
  203198. ULARGE_INTEGER spc, tot, totFree;
  203199. if (GetDiskFreeSpaceEx (getDriveFromPath (path), &spc, &tot, &totFree))
  203200. return total ? (int64) tot.QuadPart
  203201. : (int64) spc.QuadPart;
  203202. return 0;
  203203. }
  203204. int64 File::getBytesFreeOnVolume() const
  203205. {
  203206. return getDiskSpaceInfo (getFullPathName(), false);
  203207. }
  203208. int64 File::getVolumeTotalSize() const
  203209. {
  203210. return getDiskSpaceInfo (getFullPathName(), true);
  203211. }
  203212. static unsigned int getWindowsDriveType (const String& path)
  203213. {
  203214. return GetDriveType (getDriveFromPath (path));
  203215. }
  203216. bool File::isOnCDRomDrive() const
  203217. {
  203218. return getWindowsDriveType (getFullPathName()) == DRIVE_CDROM;
  203219. }
  203220. bool File::isOnHardDisk() const
  203221. {
  203222. if (fullPath.isEmpty())
  203223. return false;
  203224. const unsigned int n = getWindowsDriveType (getFullPathName());
  203225. if (fullPath.toLowerCase()[0] <= 'b' && fullPath[1] == ':')
  203226. return n != DRIVE_REMOVABLE;
  203227. else
  203228. return n != DRIVE_CDROM && n != DRIVE_REMOTE;
  203229. }
  203230. bool File::isOnRemovableDrive() const
  203231. {
  203232. if (fullPath.isEmpty())
  203233. return false;
  203234. const unsigned int n = getWindowsDriveType (getFullPathName());
  203235. return n == DRIVE_CDROM
  203236. || n == DRIVE_REMOTE
  203237. || n == DRIVE_REMOVABLE
  203238. || n == DRIVE_RAMDISK;
  203239. }
  203240. static const File juce_getSpecialFolderPath (int type)
  203241. {
  203242. WCHAR path [MAX_PATH + 256];
  203243. if (SHGetSpecialFolderPath (0, path, type, FALSE))
  203244. return File (String (path));
  203245. return File::nonexistent;
  203246. }
  203247. const File JUCE_CALLTYPE File::getSpecialLocation (const SpecialLocationType type)
  203248. {
  203249. int csidlType = 0;
  203250. switch (type)
  203251. {
  203252. case userHomeDirectory: csidlType = CSIDL_PROFILE; break;
  203253. case userDocumentsDirectory: csidlType = CSIDL_PERSONAL; break;
  203254. case userDesktopDirectory: csidlType = CSIDL_DESKTOP; break;
  203255. case userApplicationDataDirectory: csidlType = CSIDL_APPDATA; break;
  203256. case commonApplicationDataDirectory: csidlType = CSIDL_COMMON_APPDATA; break;
  203257. case globalApplicationsDirectory: csidlType = CSIDL_PROGRAM_FILES; break;
  203258. case userMusicDirectory: csidlType = CSIDL_MYMUSIC; break;
  203259. case userMoviesDirectory: csidlType = CSIDL_MYVIDEO; break;
  203260. case tempDirectory:
  203261. {
  203262. WCHAR dest [2048];
  203263. dest[0] = 0;
  203264. GetTempPath (numElementsInArray (dest), dest);
  203265. return File (String (dest));
  203266. }
  203267. case invokedExecutableFile:
  203268. case currentExecutableFile:
  203269. case currentApplicationFile:
  203270. {
  203271. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  203272. WCHAR dest [MAX_PATH + 256];
  203273. dest[0] = 0;
  203274. GetModuleFileName (moduleHandle, dest, numElementsInArray (dest));
  203275. return File (String (dest));
  203276. }
  203277. break;
  203278. default:
  203279. jassertfalse; // unknown type?
  203280. return File::nonexistent;
  203281. }
  203282. return juce_getSpecialFolderPath (csidlType);
  203283. }
  203284. const File File::getCurrentWorkingDirectory()
  203285. {
  203286. WCHAR dest [MAX_PATH + 256];
  203287. dest[0] = 0;
  203288. GetCurrentDirectory (numElementsInArray (dest), dest);
  203289. return File (String (dest));
  203290. }
  203291. bool File::setAsCurrentWorkingDirectory() const
  203292. {
  203293. return SetCurrentDirectory (getFullPathName()) != FALSE;
  203294. }
  203295. const String File::getVersion() const
  203296. {
  203297. String result;
  203298. DWORD handle = 0;
  203299. DWORD bufferSize = GetFileVersionInfoSize (getFullPathName(), &handle);
  203300. HeapBlock<char> buffer;
  203301. buffer.calloc (bufferSize);
  203302. if (GetFileVersionInfo (getFullPathName(), 0, bufferSize, buffer))
  203303. {
  203304. VS_FIXEDFILEINFO* vffi;
  203305. UINT len = 0;
  203306. if (VerQueryValue (buffer, (LPTSTR) _T("\\"), (LPVOID*) &vffi, &len))
  203307. {
  203308. result << (int) HIWORD (vffi->dwFileVersionMS) << '.'
  203309. << (int) LOWORD (vffi->dwFileVersionMS) << '.'
  203310. << (int) HIWORD (vffi->dwFileVersionLS) << '.'
  203311. << (int) LOWORD (vffi->dwFileVersionLS);
  203312. }
  203313. }
  203314. return result;
  203315. }
  203316. const File File::getLinkedTarget() const
  203317. {
  203318. File result (*this);
  203319. String p (getFullPathName());
  203320. if (! exists())
  203321. p += ".lnk";
  203322. else if (getFileExtension() != ".lnk")
  203323. return result;
  203324. ComSmartPtr <IShellLink> shellLink;
  203325. if (SUCCEEDED (shellLink.CoCreateInstance (CLSID_ShellLink)))
  203326. {
  203327. ComSmartPtr <IPersistFile> persistFile;
  203328. if (SUCCEEDED (shellLink->QueryInterface (IID_IPersistFile, (LPVOID*) &persistFile)))
  203329. {
  203330. if (SUCCEEDED (persistFile->Load ((const WCHAR*) p, STGM_READ))
  203331. && SUCCEEDED (shellLink->Resolve (0, SLR_ANY_MATCH | SLR_NO_UI)))
  203332. {
  203333. WIN32_FIND_DATA winFindData;
  203334. WCHAR resolvedPath [MAX_PATH];
  203335. if (SUCCEEDED (shellLink->GetPath (resolvedPath, MAX_PATH, &winFindData, SLGP_UNCPRIORITY)))
  203336. result = File (resolvedPath);
  203337. }
  203338. }
  203339. }
  203340. return result;
  203341. }
  203342. class DirectoryIterator::NativeIterator::Pimpl
  203343. {
  203344. public:
  203345. Pimpl (const File& directory, const String& wildCard)
  203346. : directoryWithWildCard (File::addTrailingSeparator (directory.getFullPathName()) + wildCard),
  203347. handle (INVALID_HANDLE_VALUE)
  203348. {
  203349. }
  203350. ~Pimpl()
  203351. {
  203352. if (handle != INVALID_HANDLE_VALUE)
  203353. FindClose (handle);
  203354. }
  203355. bool next (String& filenameFound,
  203356. bool* const isDir, bool* const isHidden, int64* const fileSize,
  203357. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  203358. {
  203359. WIN32_FIND_DATA findData;
  203360. if (handle == INVALID_HANDLE_VALUE)
  203361. {
  203362. handle = FindFirstFile (directoryWithWildCard, &findData);
  203363. if (handle == INVALID_HANDLE_VALUE)
  203364. return false;
  203365. }
  203366. else
  203367. {
  203368. if (FindNextFile (handle, &findData) == 0)
  203369. return false;
  203370. }
  203371. filenameFound = findData.cFileName;
  203372. if (isDir != 0) *isDir = ((findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0);
  203373. if (isHidden != 0) *isHidden = ((findData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) != 0);
  203374. if (fileSize != 0) *fileSize = findData.nFileSizeLow + (((int64) findData.nFileSizeHigh) << 32);
  203375. if (modTime != 0) *modTime = fileTimeToTime (&findData.ftLastWriteTime);
  203376. if (creationTime != 0) *creationTime = fileTimeToTime (&findData.ftCreationTime);
  203377. if (isReadOnly != 0) *isReadOnly = ((findData.dwFileAttributes & FILE_ATTRIBUTE_READONLY) != 0);
  203378. return true;
  203379. }
  203380. juce_UseDebuggingNewOperator
  203381. private:
  203382. const String directoryWithWildCard;
  203383. HANDLE handle;
  203384. Pimpl (const Pimpl&);
  203385. Pimpl& operator= (const Pimpl&);
  203386. };
  203387. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  203388. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  203389. {
  203390. }
  203391. DirectoryIterator::NativeIterator::~NativeIterator()
  203392. {
  203393. }
  203394. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  203395. bool* const isDir, bool* const isHidden, int64* const fileSize,
  203396. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  203397. {
  203398. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  203399. }
  203400. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  203401. {
  203402. HINSTANCE hInstance = 0;
  203403. JUCE_TRY
  203404. {
  203405. hInstance = ShellExecute (0, 0, fileName, parameters, 0, SW_SHOWDEFAULT);
  203406. }
  203407. JUCE_CATCH_ALL
  203408. return hInstance > (HINSTANCE) 32;
  203409. }
  203410. void File::revealToUser() const
  203411. {
  203412. if (isDirectory())
  203413. startAsProcess();
  203414. else if (getParentDirectory().exists())
  203415. getParentDirectory().startAsProcess();
  203416. }
  203417. class NamedPipeInternal
  203418. {
  203419. public:
  203420. NamedPipeInternal (const String& file, const bool isPipe_)
  203421. : pipeH (0),
  203422. cancelEvent (0),
  203423. connected (false),
  203424. isPipe (isPipe_)
  203425. {
  203426. cancelEvent = CreateEvent (0, FALSE, FALSE, 0);
  203427. pipeH = isPipe ? CreateNamedPipe (file, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, 0,
  203428. PIPE_UNLIMITED_INSTANCES, 4096, 4096, 0, 0)
  203429. : CreateFile (file, GENERIC_READ | GENERIC_WRITE, 0, 0,
  203430. OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
  203431. }
  203432. ~NamedPipeInternal()
  203433. {
  203434. disconnectPipe();
  203435. if (pipeH != 0)
  203436. CloseHandle (pipeH);
  203437. CloseHandle (cancelEvent);
  203438. }
  203439. bool connect (const int timeOutMs)
  203440. {
  203441. if (! isPipe)
  203442. return true;
  203443. if (! connected)
  203444. {
  203445. OVERLAPPED over;
  203446. zerostruct (over);
  203447. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  203448. if (ConnectNamedPipe (pipeH, &over))
  203449. {
  203450. connected = false; // yes, you read that right. In overlapped mode it should always return 0.
  203451. }
  203452. else
  203453. {
  203454. const int err = GetLastError();
  203455. if (err == ERROR_IO_PENDING || err == ERROR_PIPE_LISTENING)
  203456. {
  203457. HANDLE handles[] = { over.hEvent, cancelEvent };
  203458. if (WaitForMultipleObjects (2, handles, FALSE,
  203459. timeOutMs >= 0 ? timeOutMs : INFINITE) == WAIT_OBJECT_0)
  203460. connected = true;
  203461. }
  203462. else if (err == ERROR_PIPE_CONNECTED)
  203463. {
  203464. connected = true;
  203465. }
  203466. }
  203467. CloseHandle (over.hEvent);
  203468. }
  203469. return connected;
  203470. }
  203471. void disconnectPipe()
  203472. {
  203473. if (connected)
  203474. {
  203475. DisconnectNamedPipe (pipeH);
  203476. connected = false;
  203477. }
  203478. }
  203479. HANDLE pipeH;
  203480. HANDLE cancelEvent;
  203481. bool connected, isPipe;
  203482. };
  203483. void NamedPipe::close()
  203484. {
  203485. cancelPendingReads();
  203486. const ScopedLock sl (lock);
  203487. delete static_cast<NamedPipeInternal*> (internal);
  203488. internal = 0;
  203489. }
  203490. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  203491. {
  203492. close();
  203493. ScopedPointer<NamedPipeInternal> intern (new NamedPipeInternal ("\\\\.\\pipe\\" + pipeName, createPipe));
  203494. if (intern->pipeH != INVALID_HANDLE_VALUE)
  203495. {
  203496. internal = intern.release();
  203497. return true;
  203498. }
  203499. return false;
  203500. }
  203501. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds)
  203502. {
  203503. const ScopedLock sl (lock);
  203504. int bytesRead = -1;
  203505. bool waitAgain = true;
  203506. while (waitAgain && internal != 0)
  203507. {
  203508. NamedPipeInternal* const intern = static_cast<NamedPipeInternal*> (internal);
  203509. waitAgain = false;
  203510. if (! intern->connect (timeOutMilliseconds))
  203511. break;
  203512. if (maxBytesToRead <= 0)
  203513. return 0;
  203514. OVERLAPPED over;
  203515. zerostruct (over);
  203516. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  203517. unsigned long numRead;
  203518. if (ReadFile (intern->pipeH, destBuffer, maxBytesToRead, &numRead, &over))
  203519. {
  203520. bytesRead = (int) numRead;
  203521. }
  203522. else if (GetLastError() == ERROR_IO_PENDING)
  203523. {
  203524. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  203525. DWORD waitResult = WaitForMultipleObjects (2, handles, FALSE,
  203526. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  203527. : INFINITE);
  203528. if (waitResult != WAIT_OBJECT_0)
  203529. {
  203530. // if the operation timed out, let's cancel it...
  203531. CancelIo (intern->pipeH);
  203532. WaitForSingleObject (over.hEvent, INFINITE); // makes sure cancel is complete
  203533. }
  203534. if (GetOverlappedResult (intern->pipeH, &over, &numRead, FALSE))
  203535. {
  203536. bytesRead = (int) numRead;
  203537. }
  203538. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->isPipe)
  203539. {
  203540. intern->disconnectPipe();
  203541. waitAgain = true;
  203542. }
  203543. }
  203544. else
  203545. {
  203546. waitAgain = internal != 0;
  203547. Sleep (5);
  203548. }
  203549. CloseHandle (over.hEvent);
  203550. }
  203551. return bytesRead;
  203552. }
  203553. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  203554. {
  203555. int bytesWritten = -1;
  203556. NamedPipeInternal* const intern = static_cast<NamedPipeInternal*> (internal);
  203557. if (intern != 0 && intern->connect (timeOutMilliseconds))
  203558. {
  203559. if (numBytesToWrite <= 0)
  203560. return 0;
  203561. OVERLAPPED over;
  203562. zerostruct (over);
  203563. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  203564. unsigned long numWritten;
  203565. if (WriteFile (intern->pipeH, sourceBuffer, numBytesToWrite, &numWritten, &over))
  203566. {
  203567. bytesWritten = (int) numWritten;
  203568. }
  203569. else if (GetLastError() == ERROR_IO_PENDING)
  203570. {
  203571. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  203572. DWORD waitResult;
  203573. waitResult = WaitForMultipleObjects (2, handles, FALSE,
  203574. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  203575. : INFINITE);
  203576. if (waitResult != WAIT_OBJECT_0)
  203577. {
  203578. CancelIo (intern->pipeH);
  203579. WaitForSingleObject (over.hEvent, INFINITE);
  203580. }
  203581. if (GetOverlappedResult (intern->pipeH, &over, &numWritten, FALSE))
  203582. {
  203583. bytesWritten = (int) numWritten;
  203584. }
  203585. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->isPipe)
  203586. {
  203587. intern->disconnectPipe();
  203588. }
  203589. }
  203590. CloseHandle (over.hEvent);
  203591. }
  203592. return bytesWritten;
  203593. }
  203594. void NamedPipe::cancelPendingReads()
  203595. {
  203596. if (internal != 0)
  203597. SetEvent (static_cast<NamedPipeInternal*> (internal)->cancelEvent);
  203598. }
  203599. #endif
  203600. /*** End of inlined file: juce_win32_Files.cpp ***/
  203601. /*** Start of inlined file: juce_win32_Network.cpp ***/
  203602. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203603. // compiled on its own).
  203604. #if JUCE_INCLUDED_FILE
  203605. #ifndef INTERNET_FLAG_NEED_FILE
  203606. #define INTERNET_FLAG_NEED_FILE 0x00000010
  203607. #endif
  203608. #ifndef INTERNET_OPTION_DISABLE_AUTODIAL
  203609. #define INTERNET_OPTION_DISABLE_AUTODIAL 70
  203610. #endif
  203611. struct ConnectionAndRequestStruct
  203612. {
  203613. HINTERNET connection, request;
  203614. };
  203615. static HINTERNET sessionHandle = 0;
  203616. #ifndef WORKAROUND_TIMEOUT_BUG
  203617. //#define WORKAROUND_TIMEOUT_BUG 1
  203618. #endif
  203619. #if WORKAROUND_TIMEOUT_BUG
  203620. // Required because of a Microsoft bug in setting a timeout
  203621. class InternetConnectThread : public Thread
  203622. {
  203623. public:
  203624. InternetConnectThread (URL_COMPONENTS& uc_, HINTERNET& connection_, const bool isFtp_)
  203625. : Thread ("Internet"), uc (uc_), connection (connection_), isFtp (isFtp_)
  203626. {
  203627. startThread();
  203628. }
  203629. ~InternetConnectThread()
  203630. {
  203631. stopThread (60000);
  203632. }
  203633. void run()
  203634. {
  203635. connection = InternetConnect (sessionHandle, uc.lpszHostName,
  203636. uc.nPort, _T(""), _T(""),
  203637. isFtp ? INTERNET_SERVICE_FTP
  203638. : INTERNET_SERVICE_HTTP,
  203639. 0, 0);
  203640. notify();
  203641. }
  203642. juce_UseDebuggingNewOperator
  203643. private:
  203644. URL_COMPONENTS& uc;
  203645. HINTERNET& connection;
  203646. const bool isFtp;
  203647. InternetConnectThread (const InternetConnectThread&);
  203648. InternetConnectThread& operator= (const InternetConnectThread&);
  203649. };
  203650. #endif
  203651. void* juce_openInternetFile (const String& url,
  203652. const String& headers,
  203653. const MemoryBlock& postData,
  203654. const bool isPost,
  203655. URL::OpenStreamProgressCallback* callback,
  203656. void* callbackContext,
  203657. int timeOutMs)
  203658. {
  203659. if (sessionHandle == 0)
  203660. sessionHandle = InternetOpen (_T("juce"),
  203661. INTERNET_OPEN_TYPE_PRECONFIG,
  203662. 0, 0, 0);
  203663. if (sessionHandle != 0)
  203664. {
  203665. // break up the url..
  203666. TCHAR file[1024], server[1024];
  203667. URL_COMPONENTS uc;
  203668. zerostruct (uc);
  203669. uc.dwStructSize = sizeof (uc);
  203670. uc.dwUrlPathLength = sizeof (file);
  203671. uc.dwHostNameLength = sizeof (server);
  203672. uc.lpszUrlPath = file;
  203673. uc.lpszHostName = server;
  203674. if (InternetCrackUrl (url, 0, 0, &uc))
  203675. {
  203676. int disable = 1;
  203677. InternetSetOption (sessionHandle, INTERNET_OPTION_DISABLE_AUTODIAL, &disable, sizeof (disable));
  203678. if (timeOutMs == 0)
  203679. timeOutMs = 30000;
  203680. else if (timeOutMs < 0)
  203681. timeOutMs = -1;
  203682. InternetSetOption (sessionHandle, INTERNET_OPTION_CONNECT_TIMEOUT, &timeOutMs, sizeof (timeOutMs));
  203683. const bool isFtp = url.startsWithIgnoreCase ("ftp:");
  203684. #if WORKAROUND_TIMEOUT_BUG
  203685. HINTERNET connection = 0;
  203686. {
  203687. InternetConnectThread connectThread (uc, connection, isFtp);
  203688. connectThread.wait (timeOutMs);
  203689. if (connection == 0)
  203690. {
  203691. InternetCloseHandle (sessionHandle);
  203692. sessionHandle = 0;
  203693. }
  203694. }
  203695. #else
  203696. HINTERNET connection = InternetConnect (sessionHandle,
  203697. uc.lpszHostName,
  203698. uc.nPort,
  203699. _T(""), _T(""),
  203700. isFtp ? INTERNET_SERVICE_FTP
  203701. : INTERNET_SERVICE_HTTP,
  203702. 0, 0);
  203703. #endif
  203704. if (connection != 0)
  203705. {
  203706. if (isFtp)
  203707. {
  203708. HINTERNET request = FtpOpenFile (connection,
  203709. uc.lpszUrlPath,
  203710. GENERIC_READ,
  203711. FTP_TRANSFER_TYPE_BINARY | INTERNET_FLAG_NEED_FILE,
  203712. 0);
  203713. ConnectionAndRequestStruct* const result = new ConnectionAndRequestStruct();
  203714. result->connection = connection;
  203715. result->request = request;
  203716. return result;
  203717. }
  203718. else
  203719. {
  203720. const TCHAR* mimeTypes[] = { _T("*/*"), 0 };
  203721. DWORD flags = INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_NO_COOKIES;
  203722. if (url.startsWithIgnoreCase ("https:"))
  203723. flags |= INTERNET_FLAG_SECURE; // (this flag only seems necessary if the OS is running IE6 -
  203724. // IE7 seems to automatically work out when it's https)
  203725. HINTERNET request = HttpOpenRequest (connection,
  203726. isPost ? _T("POST")
  203727. : _T("GET"),
  203728. uc.lpszUrlPath,
  203729. 0, 0, mimeTypes, flags, 0);
  203730. if (request != 0)
  203731. {
  203732. INTERNET_BUFFERS buffers;
  203733. zerostruct (buffers);
  203734. buffers.dwStructSize = sizeof (INTERNET_BUFFERS);
  203735. buffers.lpcszHeader = (LPCTSTR) headers;
  203736. buffers.dwHeadersLength = headers.length();
  203737. buffers.dwBufferTotal = (DWORD) postData.getSize();
  203738. ConnectionAndRequestStruct* result = 0;
  203739. if (HttpSendRequestEx (request, &buffers, 0, HSR_INITIATE, 0))
  203740. {
  203741. int bytesSent = 0;
  203742. for (;;)
  203743. {
  203744. const int bytesToDo = jmin (1024, (int) postData.getSize() - bytesSent);
  203745. DWORD bytesDone = 0;
  203746. if (bytesToDo > 0
  203747. && ! InternetWriteFile (request,
  203748. static_cast <const char*> (postData.getData()) + bytesSent,
  203749. bytesToDo, &bytesDone))
  203750. {
  203751. break;
  203752. }
  203753. if (bytesToDo == 0 || (int) bytesDone < bytesToDo)
  203754. {
  203755. result = new ConnectionAndRequestStruct();
  203756. result->connection = connection;
  203757. result->request = request;
  203758. if (! HttpEndRequest (request, 0, 0, 0))
  203759. break;
  203760. return result;
  203761. }
  203762. bytesSent += bytesDone;
  203763. if (callback != 0 && ! callback (callbackContext, bytesSent, postData.getSize()))
  203764. break;
  203765. }
  203766. }
  203767. InternetCloseHandle (request);
  203768. }
  203769. InternetCloseHandle (connection);
  203770. }
  203771. }
  203772. }
  203773. }
  203774. return 0;
  203775. }
  203776. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  203777. {
  203778. DWORD bytesRead = 0;
  203779. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  203780. if (crs != 0)
  203781. InternetReadFile (crs->request,
  203782. buffer, bytesToRead,
  203783. &bytesRead);
  203784. return bytesRead;
  203785. }
  203786. int juce_seekInInternetFile (void* handle, int newPosition)
  203787. {
  203788. if (handle != 0)
  203789. {
  203790. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  203791. return InternetSetFilePointer (crs->request, newPosition, 0, FILE_BEGIN, 0);
  203792. }
  203793. return -1;
  203794. }
  203795. int64 juce_getInternetFileContentLength (void* handle)
  203796. {
  203797. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  203798. if (crs != 0)
  203799. {
  203800. DWORD index = 0, result = 0, size = sizeof (result);
  203801. if (HttpQueryInfo (crs->request, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, &result, &size, &index))
  203802. return (int64) result;
  203803. }
  203804. return -1;
  203805. }
  203806. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers)
  203807. {
  203808. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  203809. if (crs != 0)
  203810. {
  203811. DWORD bufferSizeBytes = 4096;
  203812. for (;;)
  203813. {
  203814. HeapBlock<char> buffer ((size_t) bufferSizeBytes);
  203815. if (HttpQueryInfo (crs->request, HTTP_QUERY_RAW_HEADERS_CRLF, buffer.getData(), &bufferSizeBytes, 0))
  203816. {
  203817. StringArray headersArray;
  203818. headersArray.addLines (reinterpret_cast <const WCHAR*> (buffer.getData()));
  203819. for (int i = 0; i < headersArray.size(); ++i)
  203820. {
  203821. const String& header = headersArray[i];
  203822. const String key (header.upToFirstOccurrenceOf ("; ", false, false));
  203823. const String value (header.fromFirstOccurrenceOf ("; ", false, false));
  203824. const String previousValue (headers [key]);
  203825. headers.set (key, previousValue.isEmpty() ? value : (previousValue + "," + value));
  203826. }
  203827. break;
  203828. }
  203829. if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
  203830. break;
  203831. }
  203832. }
  203833. }
  203834. void juce_closeInternetFile (void* handle)
  203835. {
  203836. if (handle != 0)
  203837. {
  203838. ScopedPointer <ConnectionAndRequestStruct> crs (static_cast <ConnectionAndRequestStruct*> (handle));
  203839. InternetCloseHandle (crs->request);
  203840. InternetCloseHandle (crs->connection);
  203841. }
  203842. }
  203843. static int getMACAddressViaGetAdaptersInfo (int64* addresses, int maxNum, const bool littleEndian) throw()
  203844. {
  203845. int numFound = 0;
  203846. DynamicLibraryLoader dll ("iphlpapi.dll");
  203847. DynamicLibraryImport (GetAdaptersInfo, getAdaptersInfo, DWORD, dll, (PIP_ADAPTER_INFO, PULONG))
  203848. if (getAdaptersInfo != 0)
  203849. {
  203850. ULONG len = sizeof (IP_ADAPTER_INFO);
  203851. MemoryBlock mb;
  203852. PIP_ADAPTER_INFO adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  203853. if (getAdaptersInfo (adapterInfo, &len) == ERROR_BUFFER_OVERFLOW)
  203854. {
  203855. mb.setSize (len);
  203856. adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  203857. }
  203858. if (getAdaptersInfo (adapterInfo, &len) == NO_ERROR)
  203859. {
  203860. PIP_ADAPTER_INFO adapter = adapterInfo;
  203861. while (adapter != 0)
  203862. {
  203863. int64 mac = 0;
  203864. for (unsigned int i = 0; i < adapter->AddressLength; ++i)
  203865. mac = (mac << 8) | adapter->Address[i];
  203866. if (littleEndian)
  203867. mac = (int64) ByteOrder::swap ((uint64) mac);
  203868. if (numFound < maxNum && mac != 0)
  203869. addresses [numFound++] = mac;
  203870. adapter = adapter->Next;
  203871. }
  203872. }
  203873. }
  203874. return numFound;
  203875. }
  203876. static int getMACAddressesViaNetBios (int64* addresses, int maxNum, const bool littleEndian) throw()
  203877. {
  203878. int numFound = 0;
  203879. DynamicLibraryLoader dll ("netapi32.dll");
  203880. DynamicLibraryImport (Netbios, NetbiosCall, UCHAR, dll, (PNCB))
  203881. if (NetbiosCall != 0)
  203882. {
  203883. NCB ncb;
  203884. zerostruct (ncb);
  203885. struct ASTAT
  203886. {
  203887. ADAPTER_STATUS adapt;
  203888. NAME_BUFFER NameBuff [30];
  203889. };
  203890. ASTAT astat;
  203891. zeromem (&astat, sizeof (astat)); // (can't use zerostruct here in VC6)
  203892. LANA_ENUM enums;
  203893. zerostruct (enums);
  203894. ncb.ncb_command = NCBENUM;
  203895. ncb.ncb_buffer = (unsigned char*) &enums;
  203896. ncb.ncb_length = sizeof (LANA_ENUM);
  203897. NetbiosCall (&ncb);
  203898. for (int i = 0; i < enums.length; ++i)
  203899. {
  203900. zerostruct (ncb);
  203901. ncb.ncb_command = NCBRESET;
  203902. ncb.ncb_lana_num = enums.lana[i];
  203903. if (NetbiosCall (&ncb) == 0)
  203904. {
  203905. zerostruct (ncb);
  203906. memcpy (ncb.ncb_callname, "* ", NCBNAMSZ);
  203907. ncb.ncb_command = NCBASTAT;
  203908. ncb.ncb_lana_num = enums.lana[i];
  203909. ncb.ncb_buffer = (unsigned char*) &astat;
  203910. ncb.ncb_length = sizeof (ASTAT);
  203911. if (NetbiosCall (&ncb) == 0)
  203912. {
  203913. if (astat.adapt.adapter_type == 0xfe)
  203914. {
  203915. uint64 mac = 0;
  203916. for (int i = 6; --i >= 0;)
  203917. mac = (mac << 8) | astat.adapt.adapter_address [littleEndian ? i : (5 - i)];
  203918. if (numFound < maxNum && mac != 0)
  203919. addresses [numFound++] = mac;
  203920. }
  203921. }
  203922. }
  203923. }
  203924. }
  203925. return numFound;
  203926. }
  203927. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian)
  203928. {
  203929. int numFound = getMACAddressViaGetAdaptersInfo (addresses, maxNum, littleEndian);
  203930. if (numFound == 0)
  203931. numFound = getMACAddressesViaNetBios (addresses, maxNum, littleEndian);
  203932. return numFound;
  203933. }
  203934. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  203935. const String& emailSubject,
  203936. const String& bodyText,
  203937. const StringArray& filesToAttach)
  203938. {
  203939. HMODULE h = LoadLibraryA ("MAPI32.dll");
  203940. typedef ULONG (WINAPI *MAPISendMailType) (LHANDLE, ULONG, lpMapiMessage, ::FLAGS, ULONG);
  203941. MAPISendMailType mapiSendMail = (MAPISendMailType) GetProcAddress (h, "MAPISendMail");
  203942. bool ok = false;
  203943. if (mapiSendMail != 0)
  203944. {
  203945. MapiMessage message;
  203946. zerostruct (message);
  203947. message.lpszSubject = (LPSTR) emailSubject.toCString();
  203948. message.lpszNoteText = (LPSTR) bodyText.toCString();
  203949. MapiRecipDesc recip;
  203950. zerostruct (recip);
  203951. recip.ulRecipClass = MAPI_TO;
  203952. String targetEmailAddress_ (targetEmailAddress);
  203953. if (targetEmailAddress_.isEmpty())
  203954. targetEmailAddress_ = " "; // (Windows Mail can't deal with a blank address)
  203955. recip.lpszName = (LPSTR) targetEmailAddress_.toCString();
  203956. message.nRecipCount = 1;
  203957. message.lpRecips = &recip;
  203958. HeapBlock <MapiFileDesc> files;
  203959. files.calloc (filesToAttach.size());
  203960. message.nFileCount = filesToAttach.size();
  203961. message.lpFiles = files;
  203962. for (int i = 0; i < filesToAttach.size(); ++i)
  203963. {
  203964. files[i].nPosition = (ULONG) -1;
  203965. files[i].lpszPathName = (LPSTR) filesToAttach[i].toCString();
  203966. }
  203967. ok = (mapiSendMail (0, 0, &message, MAPI_DIALOG | MAPI_LOGON_UI, 0) == SUCCESS_SUCCESS);
  203968. }
  203969. FreeLibrary (h);
  203970. return ok;
  203971. }
  203972. #endif
  203973. /*** End of inlined file: juce_win32_Network.cpp ***/
  203974. /*** Start of inlined file: juce_win32_PlatformUtils.cpp ***/
  203975. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203976. // compiled on its own).
  203977. #if JUCE_INCLUDED_FILE
  203978. static HKEY findKeyForPath (String name,
  203979. const bool createForWriting,
  203980. String& valueName)
  203981. {
  203982. HKEY rootKey = 0;
  203983. if (name.startsWithIgnoreCase ("HKEY_CURRENT_USER\\"))
  203984. rootKey = HKEY_CURRENT_USER;
  203985. else if (name.startsWithIgnoreCase ("HKEY_LOCAL_MACHINE\\"))
  203986. rootKey = HKEY_LOCAL_MACHINE;
  203987. else if (name.startsWithIgnoreCase ("HKEY_CLASSES_ROOT\\"))
  203988. rootKey = HKEY_CLASSES_ROOT;
  203989. if (rootKey != 0)
  203990. {
  203991. name = name.substring (name.indexOfChar ('\\') + 1);
  203992. const int lastSlash = name.lastIndexOfChar ('\\');
  203993. valueName = name.substring (lastSlash + 1);
  203994. name = name.substring (0, lastSlash);
  203995. HKEY key;
  203996. DWORD result;
  203997. if (createForWriting)
  203998. {
  203999. if (RegCreateKeyEx (rootKey, name, 0, 0, REG_OPTION_NON_VOLATILE,
  204000. (KEY_WRITE | KEY_QUERY_VALUE), 0, &key, &result) == ERROR_SUCCESS)
  204001. return key;
  204002. }
  204003. else
  204004. {
  204005. if (RegOpenKeyEx (rootKey, name, 0, KEY_READ, &key) == ERROR_SUCCESS)
  204006. return key;
  204007. }
  204008. }
  204009. return 0;
  204010. }
  204011. const String PlatformUtilities::getRegistryValue (const String& regValuePath,
  204012. const String& defaultValue)
  204013. {
  204014. String valueName, result (defaultValue);
  204015. HKEY k = findKeyForPath (regValuePath, false, valueName);
  204016. if (k != 0)
  204017. {
  204018. WCHAR buffer [2048];
  204019. unsigned long bufferSize = sizeof (buffer);
  204020. DWORD type = REG_SZ;
  204021. if (RegQueryValueEx (k, valueName, 0, &type, (LPBYTE) buffer, &bufferSize) == ERROR_SUCCESS)
  204022. {
  204023. if (type == REG_SZ)
  204024. result = buffer;
  204025. else if (type == REG_DWORD)
  204026. result = String ((int) *(DWORD*) buffer);
  204027. }
  204028. RegCloseKey (k);
  204029. }
  204030. return result;
  204031. }
  204032. void PlatformUtilities::setRegistryValue (const String& regValuePath,
  204033. const String& value)
  204034. {
  204035. String valueName;
  204036. HKEY k = findKeyForPath (regValuePath, true, valueName);
  204037. if (k != 0)
  204038. {
  204039. RegSetValueEx (k, valueName, 0, REG_SZ,
  204040. (const BYTE*) (const WCHAR*) value,
  204041. sizeof (WCHAR) * (value.length() + 1));
  204042. RegCloseKey (k);
  204043. }
  204044. }
  204045. bool PlatformUtilities::registryValueExists (const String& regValuePath)
  204046. {
  204047. bool exists = false;
  204048. String valueName;
  204049. HKEY k = findKeyForPath (regValuePath, false, valueName);
  204050. if (k != 0)
  204051. {
  204052. unsigned char buffer [2048];
  204053. unsigned long bufferSize = sizeof (buffer);
  204054. DWORD type = 0;
  204055. if (RegQueryValueEx (k, valueName, 0, &type, buffer, &bufferSize) == ERROR_SUCCESS)
  204056. exists = true;
  204057. RegCloseKey (k);
  204058. }
  204059. return exists;
  204060. }
  204061. void PlatformUtilities::deleteRegistryValue (const String& regValuePath)
  204062. {
  204063. String valueName;
  204064. HKEY k = findKeyForPath (regValuePath, true, valueName);
  204065. if (k != 0)
  204066. {
  204067. RegDeleteValue (k, valueName);
  204068. RegCloseKey (k);
  204069. }
  204070. }
  204071. void PlatformUtilities::deleteRegistryKey (const String& regKeyPath)
  204072. {
  204073. String valueName;
  204074. HKEY k = findKeyForPath (regKeyPath, true, valueName);
  204075. if (k != 0)
  204076. {
  204077. RegDeleteKey (k, valueName);
  204078. RegCloseKey (k);
  204079. }
  204080. }
  204081. void PlatformUtilities::registerFileAssociation (const String& fileExtension,
  204082. const String& symbolicDescription,
  204083. const String& fullDescription,
  204084. const File& targetExecutable,
  204085. int iconResourceNumber)
  204086. {
  204087. setRegistryValue ("HKEY_CLASSES_ROOT\\" + fileExtension + "\\", symbolicDescription);
  204088. const String key ("HKEY_CLASSES_ROOT\\" + symbolicDescription);
  204089. if (iconResourceNumber != 0)
  204090. setRegistryValue (key + "\\DefaultIcon\\",
  204091. targetExecutable.getFullPathName() + "," + String (-iconResourceNumber));
  204092. setRegistryValue (key + "\\", fullDescription);
  204093. setRegistryValue (key + "\\shell\\open\\command\\",
  204094. targetExecutable.getFullPathName() + " %1");
  204095. }
  204096. bool juce_IsRunningInWine()
  204097. {
  204098. HKEY key;
  204099. if (RegOpenKeyEx (HKEY_CURRENT_USER, _T("Software\\Wine"), 0, KEY_READ, &key) == ERROR_SUCCESS)
  204100. {
  204101. RegCloseKey (key);
  204102. return true;
  204103. }
  204104. return false;
  204105. }
  204106. const String JUCE_CALLTYPE PlatformUtilities::getCurrentCommandLineParams()
  204107. {
  204108. String s (::GetCommandLineW());
  204109. StringArray tokens;
  204110. tokens.addTokens (s, true); // tokenise so that we can remove the initial filename argument
  204111. return tokens.joinIntoString (" ", 1);
  204112. }
  204113. static void* currentModuleHandle = 0;
  204114. void* PlatformUtilities::getCurrentModuleInstanceHandle() throw()
  204115. {
  204116. if (currentModuleHandle == 0)
  204117. currentModuleHandle = GetModuleHandle (0);
  204118. return currentModuleHandle;
  204119. }
  204120. void PlatformUtilities::setCurrentModuleInstanceHandle (void* const newHandle) throw()
  204121. {
  204122. currentModuleHandle = newHandle;
  204123. }
  204124. void PlatformUtilities::fpuReset()
  204125. {
  204126. #if JUCE_MSVC
  204127. _clearfp();
  204128. #endif
  204129. }
  204130. void PlatformUtilities::beep()
  204131. {
  204132. MessageBeep (MB_OK);
  204133. }
  204134. #endif
  204135. /*** End of inlined file: juce_win32_PlatformUtils.cpp ***/
  204136. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  204137. /*** Start of inlined file: juce_win32_Messaging.cpp ***/
  204138. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204139. // compiled on its own).
  204140. #if JUCE_INCLUDED_FILE
  204141. static const unsigned int specialId = WM_APP + 0x4400;
  204142. static const unsigned int broadcastId = WM_APP + 0x4403;
  204143. static const unsigned int specialCallbackId = WM_APP + 0x4402;
  204144. static const TCHAR* const messageWindowName = _T("JUCEWindow");
  204145. HWND juce_messageWindowHandle = 0;
  204146. extern long improbableWindowNumber; // defined in windowing.cpp
  204147. #ifndef WM_APPCOMMAND
  204148. #define WM_APPCOMMAND 0x0319
  204149. #endif
  204150. static LRESULT CALLBACK juce_MessageWndProc (HWND h,
  204151. const UINT message,
  204152. const WPARAM wParam,
  204153. const LPARAM lParam) throw()
  204154. {
  204155. JUCE_TRY
  204156. {
  204157. if (h == juce_messageWindowHandle)
  204158. {
  204159. if (message == specialCallbackId)
  204160. {
  204161. MessageCallbackFunction* const func = (MessageCallbackFunction*) wParam;
  204162. return (LRESULT) (*func) ((void*) lParam);
  204163. }
  204164. else if (message == specialId)
  204165. {
  204166. // these are trapped early in the dispatch call, but must also be checked
  204167. // here in case there are windows modal dialog boxes doing their own
  204168. // dispatch loop and not calling our version
  204169. MessageManager::getInstance()->deliverMessage ((void*) lParam);
  204170. return 0;
  204171. }
  204172. else if (message == broadcastId)
  204173. {
  204174. const ScopedPointer <String> messageString ((String*) lParam);
  204175. MessageManager::getInstance()->deliverBroadcastMessage (*messageString);
  204176. return 0;
  204177. }
  204178. else if (message == WM_COPYDATA && ((const COPYDATASTRUCT*) lParam)->dwData == broadcastId)
  204179. {
  204180. const String messageString ((const juce_wchar*) ((const COPYDATASTRUCT*) lParam)->lpData,
  204181. ((const COPYDATASTRUCT*) lParam)->cbData / sizeof (juce_wchar));
  204182. PostMessage (juce_messageWindowHandle, broadcastId, 0, (LPARAM) new String (messageString));
  204183. return 0;
  204184. }
  204185. }
  204186. }
  204187. JUCE_CATCH_EXCEPTION
  204188. return DefWindowProc (h, message, wParam, lParam);
  204189. }
  204190. static bool isEventBlockedByModalComps (MSG& m)
  204191. {
  204192. if (Component::getNumCurrentlyModalComponents() == 0
  204193. || GetWindowLong (m.hwnd, GWLP_USERDATA) == improbableWindowNumber)
  204194. return false;
  204195. switch (m.message)
  204196. {
  204197. case WM_MOUSEMOVE:
  204198. case WM_NCMOUSEMOVE:
  204199. case 0x020A: /* WM_MOUSEWHEEL */
  204200. case 0x020E: /* WM_MOUSEHWHEEL */
  204201. case WM_KEYUP:
  204202. case WM_SYSKEYUP:
  204203. case WM_CHAR:
  204204. case WM_APPCOMMAND:
  204205. case WM_LBUTTONUP:
  204206. case WM_MBUTTONUP:
  204207. case WM_RBUTTONUP:
  204208. case WM_MOUSEACTIVATE:
  204209. case WM_NCMOUSEHOVER:
  204210. case WM_MOUSEHOVER:
  204211. return true;
  204212. case WM_NCLBUTTONDOWN:
  204213. case WM_NCLBUTTONDBLCLK:
  204214. case WM_NCRBUTTONDOWN:
  204215. case WM_NCRBUTTONDBLCLK:
  204216. case WM_NCMBUTTONDOWN:
  204217. case WM_NCMBUTTONDBLCLK:
  204218. case WM_LBUTTONDOWN:
  204219. case WM_LBUTTONDBLCLK:
  204220. case WM_MBUTTONDOWN:
  204221. case WM_MBUTTONDBLCLK:
  204222. case WM_RBUTTONDOWN:
  204223. case WM_RBUTTONDBLCLK:
  204224. case WM_KEYDOWN:
  204225. case WM_SYSKEYDOWN:
  204226. {
  204227. Component* const modal = Component::getCurrentlyModalComponent (0);
  204228. if (modal != 0)
  204229. modal->inputAttemptWhenModal();
  204230. return true;
  204231. }
  204232. default:
  204233. break;
  204234. }
  204235. return false;
  204236. }
  204237. bool juce_dispatchNextMessageOnSystemQueue (const bool returnIfNoPendingMessages)
  204238. {
  204239. MSG m;
  204240. if (returnIfNoPendingMessages && ! PeekMessage (&m, (HWND) 0, 0, 0, 0))
  204241. return false;
  204242. if (GetMessage (&m, (HWND) 0, 0, 0) >= 0)
  204243. {
  204244. if (m.message == specialId && m.hwnd == juce_messageWindowHandle)
  204245. {
  204246. MessageManager::getInstance()->deliverMessage ((void*) m.lParam);
  204247. }
  204248. else if (m.message == WM_QUIT)
  204249. {
  204250. if (JUCEApplication::getInstance())
  204251. JUCEApplication::getInstance()->systemRequestedQuit();
  204252. }
  204253. else if (! isEventBlockedByModalComps (m))
  204254. {
  204255. if ((m.message == WM_LBUTTONDOWN || m.message == WM_RBUTTONDOWN)
  204256. && GetWindowLong (m.hwnd, GWLP_USERDATA) != improbableWindowNumber)
  204257. {
  204258. // if it's someone else's window being clicked on, and the focus is
  204259. // currently on a juce window, pass the kb focus over..
  204260. HWND currentFocus = GetFocus();
  204261. if (currentFocus == 0 || GetWindowLong (currentFocus, GWLP_USERDATA) == improbableWindowNumber)
  204262. SetFocus (m.hwnd);
  204263. }
  204264. TranslateMessage (&m);
  204265. DispatchMessage (&m);
  204266. }
  204267. }
  204268. return true;
  204269. }
  204270. bool juce_postMessageToSystemQueue (void* message)
  204271. {
  204272. return PostMessage (juce_messageWindowHandle, specialId, 0, (LPARAM) message) != 0;
  204273. }
  204274. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  204275. void* userData)
  204276. {
  204277. if (MessageManager::getInstance()->isThisTheMessageThread())
  204278. {
  204279. return (*callback) (userData);
  204280. }
  204281. else
  204282. {
  204283. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  204284. // deadlock because the message manager is blocked from running, and can't
  204285. // call your function..
  204286. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  204287. return (void*) SendMessage (juce_messageWindowHandle,
  204288. specialCallbackId,
  204289. (WPARAM) callback,
  204290. (LPARAM) userData);
  204291. }
  204292. }
  204293. static BOOL CALLBACK BroadcastEnumWindowProc (HWND hwnd, LPARAM lParam)
  204294. {
  204295. if (hwnd != juce_messageWindowHandle)
  204296. reinterpret_cast <Array<void*>*> (lParam)->add ((void*) hwnd);
  204297. return TRUE;
  204298. }
  204299. void MessageManager::broadcastMessage (const String& value) throw()
  204300. {
  204301. Array<void*> windows;
  204302. EnumWindows (&BroadcastEnumWindowProc, (LPARAM) &windows);
  204303. const String localCopy (value);
  204304. COPYDATASTRUCT data;
  204305. data.dwData = broadcastId;
  204306. data.cbData = (localCopy.length() + 1) * sizeof (juce_wchar);
  204307. data.lpData = (void*) static_cast <const juce_wchar*> (localCopy);
  204308. for (int i = windows.size(); --i >= 0;)
  204309. {
  204310. HWND hwnd = (HWND) windows.getUnchecked(i);
  204311. TCHAR windowName [64]; // no need to read longer strings than this
  204312. GetWindowText (hwnd, windowName, 64);
  204313. windowName [63] = 0;
  204314. if (String (windowName) == messageWindowName)
  204315. {
  204316. DWORD_PTR result;
  204317. SendMessageTimeout (hwnd, WM_COPYDATA,
  204318. (WPARAM) juce_messageWindowHandle,
  204319. (LPARAM) &data,
  204320. SMTO_BLOCK | SMTO_ABORTIFHUNG,
  204321. 8000,
  204322. &result);
  204323. }
  204324. }
  204325. }
  204326. static const String getMessageWindowClassName()
  204327. {
  204328. // this name has to be different for each app/dll instance because otherwise
  204329. // poor old Win32 can get a bit confused (even despite it not being a process-global
  204330. // window class).
  204331. static int number = 0;
  204332. if (number == 0)
  204333. number = 0x7fffffff & (int) Time::getHighResolutionTicks();
  204334. return "JUCEcs_" + String (number);
  204335. }
  204336. void MessageManager::doPlatformSpecificInitialisation()
  204337. {
  204338. OleInitialize (0);
  204339. const String className (getMessageWindowClassName());
  204340. HMODULE hmod = (HMODULE) PlatformUtilities::getCurrentModuleInstanceHandle();
  204341. WNDCLASSEX wc;
  204342. zerostruct (wc);
  204343. wc.cbSize = sizeof (wc);
  204344. wc.lpfnWndProc = (WNDPROC) juce_MessageWndProc;
  204345. wc.cbWndExtra = 4;
  204346. wc.hInstance = hmod;
  204347. wc.lpszClassName = className;
  204348. RegisterClassEx (&wc);
  204349. juce_messageWindowHandle = CreateWindow (wc.lpszClassName,
  204350. messageWindowName,
  204351. 0, 0, 0, 0, 0, 0, 0,
  204352. hmod, 0);
  204353. }
  204354. void MessageManager::doPlatformSpecificShutdown()
  204355. {
  204356. DestroyWindow (juce_messageWindowHandle);
  204357. UnregisterClass (getMessageWindowClassName(), 0);
  204358. OleUninitialize();
  204359. }
  204360. #endif
  204361. /*** End of inlined file: juce_win32_Messaging.cpp ***/
  204362. /*** Start of inlined file: juce_win32_Windowing.cpp ***/
  204363. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204364. // compiled on its own).
  204365. #if JUCE_INCLUDED_FILE
  204366. #undef GetSystemMetrics // multimon overrides this for some reason and causes a mess..
  204367. // these are in the windows SDK, but need to be repeated here for GCC..
  204368. #ifndef GET_APPCOMMAND_LPARAM
  204369. #define FAPPCOMMAND_MASK 0xF000
  204370. #define GET_APPCOMMAND_LPARAM(lParam) ((short) (HIWORD (lParam) & ~FAPPCOMMAND_MASK))
  204371. #define APPCOMMAND_MEDIA_NEXTTRACK 11
  204372. #define APPCOMMAND_MEDIA_PREVIOUSTRACK 12
  204373. #define APPCOMMAND_MEDIA_STOP 13
  204374. #define APPCOMMAND_MEDIA_PLAY_PAUSE 14
  204375. #define WM_APPCOMMAND 0x0319
  204376. #endif
  204377. extern void juce_repeatLastProcessPriority(); // in juce_win32_Threads.cpp
  204378. extern void juce_CheckCurrentlyFocusedTopLevelWindow(); // in juce_TopLevelWindow.cpp
  204379. extern bool juce_IsRunningInWine();
  204380. #ifndef ULW_ALPHA
  204381. #define ULW_ALPHA 0x00000002
  204382. #endif
  204383. #ifndef AC_SRC_ALPHA
  204384. #define AC_SRC_ALPHA 0x01
  204385. #endif
  204386. static HPALETTE palette = 0;
  204387. static bool createPaletteIfNeeded = true;
  204388. static bool shouldDeactivateTitleBar = true;
  204389. static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY) throw();
  204390. #define WM_TRAYNOTIFY WM_USER + 100
  204391. using ::abs;
  204392. typedef BOOL (WINAPI* UpdateLayeredWinFunc) (HWND, HDC, POINT*, SIZE*, HDC, POINT*, COLORREF, BLENDFUNCTION*, DWORD);
  204393. static UpdateLayeredWinFunc updateLayeredWindow = 0;
  204394. bool Desktop::canUseSemiTransparentWindows() throw()
  204395. {
  204396. if (updateLayeredWindow == 0)
  204397. {
  204398. if (! juce_IsRunningInWine())
  204399. {
  204400. HMODULE user32Mod = GetModuleHandle (_T("user32.dll"));
  204401. updateLayeredWindow = (UpdateLayeredWinFunc) GetProcAddress (user32Mod, "UpdateLayeredWindow");
  204402. }
  204403. }
  204404. return updateLayeredWindow != 0;
  204405. }
  204406. const int extendedKeyModifier = 0x10000;
  204407. const int KeyPress::spaceKey = VK_SPACE;
  204408. const int KeyPress::returnKey = VK_RETURN;
  204409. const int KeyPress::escapeKey = VK_ESCAPE;
  204410. const int KeyPress::backspaceKey = VK_BACK;
  204411. const int KeyPress::deleteKey = VK_DELETE | extendedKeyModifier;
  204412. const int KeyPress::insertKey = VK_INSERT | extendedKeyModifier;
  204413. const int KeyPress::tabKey = VK_TAB;
  204414. const int KeyPress::leftKey = VK_LEFT | extendedKeyModifier;
  204415. const int KeyPress::rightKey = VK_RIGHT | extendedKeyModifier;
  204416. const int KeyPress::upKey = VK_UP | extendedKeyModifier;
  204417. const int KeyPress::downKey = VK_DOWN | extendedKeyModifier;
  204418. const int KeyPress::homeKey = VK_HOME | extendedKeyModifier;
  204419. const int KeyPress::endKey = VK_END | extendedKeyModifier;
  204420. const int KeyPress::pageUpKey = VK_PRIOR | extendedKeyModifier;
  204421. const int KeyPress::pageDownKey = VK_NEXT | extendedKeyModifier;
  204422. const int KeyPress::F1Key = VK_F1 | extendedKeyModifier;
  204423. const int KeyPress::F2Key = VK_F2 | extendedKeyModifier;
  204424. const int KeyPress::F3Key = VK_F3 | extendedKeyModifier;
  204425. const int KeyPress::F4Key = VK_F4 | extendedKeyModifier;
  204426. const int KeyPress::F5Key = VK_F5 | extendedKeyModifier;
  204427. const int KeyPress::F6Key = VK_F6 | extendedKeyModifier;
  204428. const int KeyPress::F7Key = VK_F7 | extendedKeyModifier;
  204429. const int KeyPress::F8Key = VK_F8 | extendedKeyModifier;
  204430. const int KeyPress::F9Key = VK_F9 | extendedKeyModifier;
  204431. const int KeyPress::F10Key = VK_F10 | extendedKeyModifier;
  204432. const int KeyPress::F11Key = VK_F11 | extendedKeyModifier;
  204433. const int KeyPress::F12Key = VK_F12 | extendedKeyModifier;
  204434. const int KeyPress::F13Key = VK_F13 | extendedKeyModifier;
  204435. const int KeyPress::F14Key = VK_F14 | extendedKeyModifier;
  204436. const int KeyPress::F15Key = VK_F15 | extendedKeyModifier;
  204437. const int KeyPress::F16Key = VK_F16 | extendedKeyModifier;
  204438. const int KeyPress::numberPad0 = VK_NUMPAD0 | extendedKeyModifier;
  204439. const int KeyPress::numberPad1 = VK_NUMPAD1 | extendedKeyModifier;
  204440. const int KeyPress::numberPad2 = VK_NUMPAD2 | extendedKeyModifier;
  204441. const int KeyPress::numberPad3 = VK_NUMPAD3 | extendedKeyModifier;
  204442. const int KeyPress::numberPad4 = VK_NUMPAD4 | extendedKeyModifier;
  204443. const int KeyPress::numberPad5 = VK_NUMPAD5 | extendedKeyModifier;
  204444. const int KeyPress::numberPad6 = VK_NUMPAD6 | extendedKeyModifier;
  204445. const int KeyPress::numberPad7 = VK_NUMPAD7 | extendedKeyModifier;
  204446. const int KeyPress::numberPad8 = VK_NUMPAD8 | extendedKeyModifier;
  204447. const int KeyPress::numberPad9 = VK_NUMPAD9 | extendedKeyModifier;
  204448. const int KeyPress::numberPadAdd = VK_ADD | extendedKeyModifier;
  204449. const int KeyPress::numberPadSubtract = VK_SUBTRACT | extendedKeyModifier;
  204450. const int KeyPress::numberPadMultiply = VK_MULTIPLY | extendedKeyModifier;
  204451. const int KeyPress::numberPadDivide = VK_DIVIDE | extendedKeyModifier;
  204452. const int KeyPress::numberPadSeparator = VK_SEPARATOR | extendedKeyModifier;
  204453. const int KeyPress::numberPadDecimalPoint = VK_DECIMAL | extendedKeyModifier;
  204454. const int KeyPress::numberPadEquals = 0x92 /*VK_OEM_NEC_EQUAL*/ | extendedKeyModifier;
  204455. const int KeyPress::numberPadDelete = VK_DELETE | extendedKeyModifier;
  204456. const int KeyPress::playKey = 0x30000;
  204457. const int KeyPress::stopKey = 0x30001;
  204458. const int KeyPress::fastForwardKey = 0x30002;
  204459. const int KeyPress::rewindKey = 0x30003;
  204460. class WindowsBitmapImage : public Image::SharedImage
  204461. {
  204462. public:
  204463. HBITMAP hBitmap;
  204464. BITMAPV4HEADER bitmapInfo;
  204465. HDC hdc;
  204466. unsigned char* bitmapData;
  204467. WindowsBitmapImage (const Image::PixelFormat format_,
  204468. const int w, const int h, const bool clearImage)
  204469. : Image::SharedImage (format_, w, h)
  204470. {
  204471. jassert (format_ == Image::RGB || format_ == Image::ARGB);
  204472. pixelStride = (format_ == Image::RGB) ? 3 : 4;
  204473. zerostruct (bitmapInfo);
  204474. bitmapInfo.bV4Size = sizeof (BITMAPV4HEADER);
  204475. bitmapInfo.bV4Width = w;
  204476. bitmapInfo.bV4Height = h;
  204477. bitmapInfo.bV4Planes = 1;
  204478. bitmapInfo.bV4CSType = 1;
  204479. bitmapInfo.bV4BitCount = (unsigned short) (pixelStride * 8);
  204480. if (format_ == Image::ARGB)
  204481. {
  204482. bitmapInfo.bV4AlphaMask = 0xff000000;
  204483. bitmapInfo.bV4RedMask = 0xff0000;
  204484. bitmapInfo.bV4GreenMask = 0xff00;
  204485. bitmapInfo.bV4BlueMask = 0xff;
  204486. bitmapInfo.bV4V4Compression = BI_BITFIELDS;
  204487. }
  204488. else
  204489. {
  204490. bitmapInfo.bV4V4Compression = BI_RGB;
  204491. }
  204492. lineStride = -((w * pixelStride + 3) & ~3);
  204493. HDC dc = GetDC (0);
  204494. hdc = CreateCompatibleDC (dc);
  204495. ReleaseDC (0, dc);
  204496. SetMapMode (hdc, MM_TEXT);
  204497. hBitmap = CreateDIBSection (hdc,
  204498. (BITMAPINFO*) &(bitmapInfo),
  204499. DIB_RGB_COLORS,
  204500. (void**) &bitmapData,
  204501. 0, 0);
  204502. SelectObject (hdc, hBitmap);
  204503. if (format_ == Image::ARGB && clearImage)
  204504. zeromem (bitmapData, abs (h * lineStride));
  204505. imageData = bitmapData - (lineStride * (h - 1));
  204506. }
  204507. ~WindowsBitmapImage()
  204508. {
  204509. DeleteDC (hdc);
  204510. DeleteObject (hBitmap);
  204511. }
  204512. Image::ImageType getType() const { return Image::NativeImage; }
  204513. LowLevelGraphicsContext* createLowLevelContext()
  204514. {
  204515. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  204516. }
  204517. SharedImage* clone()
  204518. {
  204519. WindowsBitmapImage* im = new WindowsBitmapImage (format, width, height, false);
  204520. for (int i = 0; i < height; ++i)
  204521. memcpy (im->imageData + i * lineStride, imageData + i * lineStride, lineStride);
  204522. return im;
  204523. }
  204524. void blitToWindow (HWND hwnd, HDC dc, const bool transparent,
  204525. const int x, const int y,
  204526. const RectangleList& maskedRegion) throw()
  204527. {
  204528. static HDRAWDIB hdd = 0;
  204529. static bool needToCreateDrawDib = true;
  204530. if (needToCreateDrawDib)
  204531. {
  204532. needToCreateDrawDib = false;
  204533. HDC dc = GetDC (0);
  204534. const int n = GetDeviceCaps (dc, BITSPIXEL);
  204535. ReleaseDC (0, dc);
  204536. // only open if we're not palettised
  204537. if (n > 8)
  204538. hdd = DrawDibOpen();
  204539. }
  204540. if (createPaletteIfNeeded)
  204541. {
  204542. HDC dc = GetDC (0);
  204543. const int n = GetDeviceCaps (dc, BITSPIXEL);
  204544. ReleaseDC (0, dc);
  204545. if (n <= 8)
  204546. palette = CreateHalftonePalette (dc);
  204547. createPaletteIfNeeded = false;
  204548. }
  204549. if (palette != 0)
  204550. {
  204551. SelectPalette (dc, palette, FALSE);
  204552. RealizePalette (dc);
  204553. SetStretchBltMode (dc, HALFTONE);
  204554. }
  204555. SetMapMode (dc, MM_TEXT);
  204556. if (transparent)
  204557. {
  204558. POINT p, pos;
  204559. SIZE size;
  204560. RECT windowBounds;
  204561. GetWindowRect (hwnd, &windowBounds);
  204562. p.x = -x;
  204563. p.y = -y;
  204564. pos.x = windowBounds.left;
  204565. pos.y = windowBounds.top;
  204566. size.cx = windowBounds.right - windowBounds.left;
  204567. size.cy = windowBounds.bottom - windowBounds.top;
  204568. BLENDFUNCTION bf;
  204569. bf.AlphaFormat = AC_SRC_ALPHA;
  204570. bf.BlendFlags = 0;
  204571. bf.BlendOp = AC_SRC_OVER;
  204572. bf.SourceConstantAlpha = 0xff;
  204573. if (! maskedRegion.isEmpty())
  204574. {
  204575. for (RectangleList::Iterator i (maskedRegion); i.next();)
  204576. {
  204577. const Rectangle<int>& r = *i.getRectangle();
  204578. ExcludeClipRect (hdc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  204579. }
  204580. }
  204581. updateLayeredWindow (hwnd, 0, &pos, &size, hdc, &p, 0, &bf, ULW_ALPHA);
  204582. }
  204583. else
  204584. {
  204585. int savedDC = 0;
  204586. if (! maskedRegion.isEmpty())
  204587. {
  204588. savedDC = SaveDC (dc);
  204589. for (RectangleList::Iterator i (maskedRegion); i.next();)
  204590. {
  204591. const Rectangle<int>& r = *i.getRectangle();
  204592. ExcludeClipRect (dc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  204593. }
  204594. }
  204595. if (hdd == 0)
  204596. {
  204597. StretchDIBits (dc,
  204598. x, y, width, height,
  204599. 0, 0, width, height,
  204600. bitmapData, (const BITMAPINFO*) &bitmapInfo,
  204601. DIB_RGB_COLORS, SRCCOPY);
  204602. }
  204603. else
  204604. {
  204605. DrawDibDraw (hdd, dc, x, y, -1, -1,
  204606. (BITMAPINFOHEADER*) &bitmapInfo, bitmapData,
  204607. 0, 0, width, height, 0);
  204608. }
  204609. if (! maskedRegion.isEmpty())
  204610. RestoreDC (dc, savedDC);
  204611. }
  204612. }
  204613. juce_UseDebuggingNewOperator
  204614. private:
  204615. WindowsBitmapImage (const WindowsBitmapImage&);
  204616. WindowsBitmapImage& operator= (const WindowsBitmapImage&);
  204617. };
  204618. long improbableWindowNumber = 0xf965aa01; // also referenced by messaging.cpp
  204619. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  204620. {
  204621. SHORT k = (SHORT) keyCode;
  204622. if ((keyCode & extendedKeyModifier) == 0
  204623. && (k >= (SHORT) 'a' && k <= (SHORT) 'z'))
  204624. k += (SHORT) 'A' - (SHORT) 'a';
  204625. const SHORT translatedValues[] = { (SHORT) ',', VK_OEM_COMMA,
  204626. (SHORT) '+', VK_OEM_PLUS,
  204627. (SHORT) '-', VK_OEM_MINUS,
  204628. (SHORT) '.', VK_OEM_PERIOD,
  204629. (SHORT) ';', VK_OEM_1,
  204630. (SHORT) ':', VK_OEM_1,
  204631. (SHORT) '/', VK_OEM_2,
  204632. (SHORT) '?', VK_OEM_2,
  204633. (SHORT) '[', VK_OEM_4,
  204634. (SHORT) ']', VK_OEM_6 };
  204635. for (int i = 0; i < numElementsInArray (translatedValues); i += 2)
  204636. if (k == translatedValues [i])
  204637. k = translatedValues [i + 1];
  204638. return (GetKeyState (k) & 0x8000) != 0;
  204639. }
  204640. static void* callFunctionIfNotLocked (MessageCallbackFunction* callback, void* userData)
  204641. {
  204642. if (MessageManager::getInstance()->currentThreadHasLockedMessageManager())
  204643. return callback (userData);
  204644. else
  204645. return MessageManager::getInstance()->callFunctionOnMessageThread (callback, userData);
  204646. }
  204647. class Win32ComponentPeer : public ComponentPeer
  204648. {
  204649. public:
  204650. Win32ComponentPeer (Component* const component,
  204651. const int windowStyleFlags)
  204652. : ComponentPeer (component, windowStyleFlags),
  204653. dontRepaint (false),
  204654. fullScreen (false),
  204655. isDragging (false),
  204656. isMouseOver (false),
  204657. hasCreatedCaret (false),
  204658. currentWindowIcon (0),
  204659. taskBarIcon (0),
  204660. dropTarget (0)
  204661. {
  204662. callFunctionIfNotLocked (&createWindowCallback, this);
  204663. setTitle (component->getName());
  204664. if ((windowStyleFlags & windowHasDropShadow) != 0
  204665. && Desktop::canUseSemiTransparentWindows())
  204666. {
  204667. shadower = component->getLookAndFeel().createDropShadowerForComponent (component);
  204668. if (shadower != 0)
  204669. shadower->setOwner (component);
  204670. }
  204671. else
  204672. {
  204673. shadower = 0;
  204674. }
  204675. }
  204676. ~Win32ComponentPeer()
  204677. {
  204678. setTaskBarIcon (Image());
  204679. deleteAndZero (shadower);
  204680. // do this before the next bit to avoid messages arriving for this window
  204681. // before it's destroyed
  204682. SetWindowLongPtr (hwnd, GWLP_USERDATA, 0);
  204683. callFunctionIfNotLocked (&destroyWindowCallback, (void*) hwnd);
  204684. if (currentWindowIcon != 0)
  204685. DestroyIcon (currentWindowIcon);
  204686. if (dropTarget != 0)
  204687. {
  204688. dropTarget->Release();
  204689. dropTarget = 0;
  204690. }
  204691. }
  204692. void* getNativeHandle() const
  204693. {
  204694. return hwnd;
  204695. }
  204696. void setVisible (bool shouldBeVisible)
  204697. {
  204698. ShowWindow (hwnd, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  204699. if (shouldBeVisible)
  204700. InvalidateRect (hwnd, 0, 0);
  204701. else
  204702. lastPaintTime = 0;
  204703. }
  204704. void setTitle (const String& title)
  204705. {
  204706. SetWindowText (hwnd, title);
  204707. }
  204708. void setPosition (int x, int y)
  204709. {
  204710. offsetWithinParent (x, y);
  204711. SetWindowPos (hwnd, 0,
  204712. x - windowBorder.getLeft(),
  204713. y - windowBorder.getTop(),
  204714. 0, 0,
  204715. SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  204716. }
  204717. void repaintNowIfTransparent()
  204718. {
  204719. if (isTransparent() && lastPaintTime > 0 && Time::getMillisecondCounter() > lastPaintTime + 30)
  204720. handlePaintMessage();
  204721. }
  204722. void updateBorderSize()
  204723. {
  204724. WINDOWINFO info;
  204725. info.cbSize = sizeof (info);
  204726. if (GetWindowInfo (hwnd, &info))
  204727. {
  204728. windowBorder = BorderSize (info.rcClient.top - info.rcWindow.top,
  204729. info.rcClient.left - info.rcWindow.left,
  204730. info.rcWindow.bottom - info.rcClient.bottom,
  204731. info.rcWindow.right - info.rcClient.right);
  204732. }
  204733. }
  204734. void setSize (int w, int h)
  204735. {
  204736. SetWindowPos (hwnd, 0, 0, 0,
  204737. w + windowBorder.getLeftAndRight(),
  204738. h + windowBorder.getTopAndBottom(),
  204739. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  204740. updateBorderSize();
  204741. repaintNowIfTransparent();
  204742. }
  204743. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  204744. {
  204745. fullScreen = isNowFullScreen;
  204746. offsetWithinParent (x, y);
  204747. SetWindowPos (hwnd, 0,
  204748. x - windowBorder.getLeft(),
  204749. y - windowBorder.getTop(),
  204750. w + windowBorder.getLeftAndRight(),
  204751. h + windowBorder.getTopAndBottom(),
  204752. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  204753. updateBorderSize();
  204754. repaintNowIfTransparent();
  204755. }
  204756. const Rectangle<int> getBounds() const
  204757. {
  204758. RECT r;
  204759. GetWindowRect (hwnd, &r);
  204760. Rectangle<int> bounds (r.left, r.top, r.right - r.left, r.bottom - r.top);
  204761. HWND parentH = GetParent (hwnd);
  204762. if (parentH != 0)
  204763. {
  204764. GetWindowRect (parentH, &r);
  204765. bounds.translate (-r.left, -r.top);
  204766. }
  204767. return windowBorder.subtractedFrom (bounds);
  204768. }
  204769. const Point<int> getScreenPosition() const
  204770. {
  204771. RECT r;
  204772. GetWindowRect (hwnd, &r);
  204773. return Point<int> (r.left + windowBorder.getLeft(),
  204774. r.top + windowBorder.getTop());
  204775. }
  204776. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition)
  204777. {
  204778. return relativePosition + getScreenPosition();
  204779. }
  204780. const Point<int> globalPositionToRelative (const Point<int>& screenPosition)
  204781. {
  204782. return screenPosition - getScreenPosition();
  204783. }
  204784. void setMinimised (bool shouldBeMinimised)
  204785. {
  204786. if (shouldBeMinimised != isMinimised())
  204787. ShowWindow (hwnd, shouldBeMinimised ? SW_MINIMIZE : SW_SHOWNORMAL);
  204788. }
  204789. bool isMinimised() const
  204790. {
  204791. WINDOWPLACEMENT wp;
  204792. wp.length = sizeof (WINDOWPLACEMENT);
  204793. GetWindowPlacement (hwnd, &wp);
  204794. return wp.showCmd == SW_SHOWMINIMIZED;
  204795. }
  204796. void setFullScreen (bool shouldBeFullScreen)
  204797. {
  204798. setMinimised (false);
  204799. if (fullScreen != shouldBeFullScreen)
  204800. {
  204801. fullScreen = shouldBeFullScreen;
  204802. const Component::SafePointer<Component> deletionChecker (component);
  204803. if (! fullScreen)
  204804. {
  204805. const Rectangle<int> boundsCopy (lastNonFullscreenBounds);
  204806. if (hasTitleBar())
  204807. ShowWindow (hwnd, SW_SHOWNORMAL);
  204808. if (! boundsCopy.isEmpty())
  204809. {
  204810. setBounds (boundsCopy.getX(),
  204811. boundsCopy.getY(),
  204812. boundsCopy.getWidth(),
  204813. boundsCopy.getHeight(),
  204814. false);
  204815. }
  204816. }
  204817. else
  204818. {
  204819. if (hasTitleBar())
  204820. ShowWindow (hwnd, SW_SHOWMAXIMIZED);
  204821. else
  204822. SendMessageW (hwnd, WM_SETTINGCHANGE, 0, 0);
  204823. }
  204824. if (deletionChecker != 0)
  204825. handleMovedOrResized();
  204826. }
  204827. }
  204828. bool isFullScreen() const
  204829. {
  204830. if (! hasTitleBar())
  204831. return fullScreen;
  204832. WINDOWPLACEMENT wp;
  204833. wp.length = sizeof (wp);
  204834. GetWindowPlacement (hwnd, &wp);
  204835. return wp.showCmd == SW_SHOWMAXIMIZED;
  204836. }
  204837. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  204838. {
  204839. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  204840. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  204841. return false;
  204842. RECT r;
  204843. GetWindowRect (hwnd, &r);
  204844. POINT p;
  204845. p.x = position.getX() + r.left + windowBorder.getLeft();
  204846. p.y = position.getY() + r.top + windowBorder.getTop();
  204847. HWND w = WindowFromPoint (p);
  204848. return w == hwnd || (trueIfInAChildWindow && (IsChild (hwnd, w) != 0));
  204849. }
  204850. const BorderSize getFrameSize() const
  204851. {
  204852. return windowBorder;
  204853. }
  204854. bool setAlwaysOnTop (bool alwaysOnTop)
  204855. {
  204856. const bool oldDeactivate = shouldDeactivateTitleBar;
  204857. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  204858. SetWindowPos (hwnd, alwaysOnTop ? HWND_TOPMOST : HWND_NOTOPMOST,
  204859. 0, 0, 0, 0,
  204860. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  204861. shouldDeactivateTitleBar = oldDeactivate;
  204862. if (shadower != 0)
  204863. shadower->componentBroughtToFront (*component);
  204864. return true;
  204865. }
  204866. void toFront (bool makeActive)
  204867. {
  204868. setMinimised (false);
  204869. const bool oldDeactivate = shouldDeactivateTitleBar;
  204870. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  204871. callFunctionIfNotLocked (makeActive ? &toFrontCallback1 : &toFrontCallback2, hwnd);
  204872. shouldDeactivateTitleBar = oldDeactivate;
  204873. if (! makeActive)
  204874. {
  204875. // in this case a broughttofront call won't have occured, so do it now..
  204876. handleBroughtToFront();
  204877. }
  204878. }
  204879. void toBehind (ComponentPeer* other)
  204880. {
  204881. Win32ComponentPeer* const otherPeer = dynamic_cast <Win32ComponentPeer*> (other);
  204882. jassert (otherPeer != 0); // wrong type of window?
  204883. if (otherPeer != 0)
  204884. {
  204885. setMinimised (false);
  204886. // must be careful not to try to put a topmost window behind a normal one, or win32
  204887. // promotes the normal one to be topmost!
  204888. if (getComponent()->isAlwaysOnTop() == otherPeer->getComponent()->isAlwaysOnTop())
  204889. SetWindowPos (hwnd, otherPeer->hwnd, 0, 0, 0, 0,
  204890. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  204891. else if (otherPeer->getComponent()->isAlwaysOnTop())
  204892. SetWindowPos (hwnd, HWND_TOP, 0, 0, 0, 0,
  204893. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  204894. }
  204895. }
  204896. bool isFocused() const
  204897. {
  204898. return callFunctionIfNotLocked (&getFocusCallback, 0) == (void*) hwnd;
  204899. }
  204900. void grabFocus()
  204901. {
  204902. const bool oldDeactivate = shouldDeactivateTitleBar;
  204903. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  204904. callFunctionIfNotLocked (&setFocusCallback, hwnd);
  204905. shouldDeactivateTitleBar = oldDeactivate;
  204906. }
  204907. void textInputRequired (const Point<int>&)
  204908. {
  204909. if (! hasCreatedCaret)
  204910. {
  204911. hasCreatedCaret = true;
  204912. CreateCaret (hwnd, (HBITMAP) 1, 0, 0);
  204913. }
  204914. ShowCaret (hwnd);
  204915. SetCaretPos (0, 0);
  204916. }
  204917. void repaint (const Rectangle<int>& area)
  204918. {
  204919. const RECT r = { area.getX(), area.getY(), area.getRight(), area.getBottom() };
  204920. InvalidateRect (hwnd, &r, FALSE);
  204921. }
  204922. void performAnyPendingRepaintsNow()
  204923. {
  204924. MSG m;
  204925. if (component->isVisible() && PeekMessage (&m, hwnd, WM_PAINT, WM_PAINT, PM_REMOVE))
  204926. DispatchMessage (&m);
  204927. }
  204928. static Win32ComponentPeer* getOwnerOfWindow (HWND h) throw()
  204929. {
  204930. if (h != 0 && GetWindowLongPtr (h, GWLP_USERDATA) == improbableWindowNumber)
  204931. return (Win32ComponentPeer*) (pointer_sized_int) GetWindowLongPtr (h, 8);
  204932. return 0;
  204933. }
  204934. void setTaskBarIcon (const Image& image)
  204935. {
  204936. if (image.isValid())
  204937. {
  204938. HICON hicon = createHICONFromImage (image, TRUE, 0, 0);
  204939. if (taskBarIcon == 0)
  204940. {
  204941. taskBarIcon = new NOTIFYICONDATA();
  204942. taskBarIcon->cbSize = sizeof (NOTIFYICONDATA);
  204943. taskBarIcon->hWnd = (HWND) hwnd;
  204944. taskBarIcon->uID = (int) (pointer_sized_int) hwnd;
  204945. taskBarIcon->uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  204946. taskBarIcon->uCallbackMessage = WM_TRAYNOTIFY;
  204947. taskBarIcon->hIcon = hicon;
  204948. taskBarIcon->szTip[0] = 0;
  204949. Shell_NotifyIcon (NIM_ADD, taskBarIcon);
  204950. }
  204951. else
  204952. {
  204953. HICON oldIcon = taskBarIcon->hIcon;
  204954. taskBarIcon->hIcon = hicon;
  204955. taskBarIcon->uFlags = NIF_ICON;
  204956. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  204957. DestroyIcon (oldIcon);
  204958. }
  204959. DestroyIcon (hicon);
  204960. }
  204961. else if (taskBarIcon != 0)
  204962. {
  204963. taskBarIcon->uFlags = 0;
  204964. Shell_NotifyIcon (NIM_DELETE, taskBarIcon);
  204965. DestroyIcon (taskBarIcon->hIcon);
  204966. deleteAndZero (taskBarIcon);
  204967. }
  204968. }
  204969. void setTaskBarIconToolTip (const String& toolTip) const
  204970. {
  204971. if (taskBarIcon != 0)
  204972. {
  204973. taskBarIcon->uFlags = NIF_TIP;
  204974. toolTip.copyToUnicode (taskBarIcon->szTip, sizeof (taskBarIcon->szTip) - 1);
  204975. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  204976. }
  204977. }
  204978. bool isInside (HWND h) const
  204979. {
  204980. return GetAncestor (hwnd, GA_ROOT) == h;
  204981. }
  204982. static void updateKeyModifiers() throw()
  204983. {
  204984. int keyMods = 0;
  204985. if (GetKeyState (VK_SHIFT) & 0x8000) keyMods |= ModifierKeys::shiftModifier;
  204986. if (GetKeyState (VK_CONTROL) & 0x8000) keyMods |= ModifierKeys::ctrlModifier;
  204987. if (GetKeyState (VK_MENU) & 0x8000) keyMods |= ModifierKeys::altModifier;
  204988. if (GetKeyState (VK_RMENU) & 0x8000) keyMods &= ~(ModifierKeys::ctrlModifier | ModifierKeys::altModifier);
  204989. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  204990. }
  204991. static void updateModifiersFromWParam (const WPARAM wParam)
  204992. {
  204993. int mouseMods = 0;
  204994. if (wParam & MK_LBUTTON) mouseMods |= ModifierKeys::leftButtonModifier;
  204995. if (wParam & MK_RBUTTON) mouseMods |= ModifierKeys::rightButtonModifier;
  204996. if (wParam & MK_MBUTTON) mouseMods |= ModifierKeys::middleButtonModifier;
  204997. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  204998. updateKeyModifiers();
  204999. }
  205000. static int64 getMouseEventTime()
  205001. {
  205002. static int64 eventTimeOffset = 0;
  205003. static DWORD lastMessageTime = 0;
  205004. const DWORD thisMessageTime = GetMessageTime();
  205005. if (thisMessageTime < lastMessageTime || lastMessageTime == 0)
  205006. {
  205007. lastMessageTime = thisMessageTime;
  205008. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  205009. }
  205010. return eventTimeOffset + thisMessageTime;
  205011. }
  205012. juce_UseDebuggingNewOperator
  205013. bool dontRepaint;
  205014. static ModifierKeys currentModifiers;
  205015. static ModifierKeys modifiersAtLastCallback;
  205016. private:
  205017. HWND hwnd;
  205018. DropShadower* shadower;
  205019. bool fullScreen, isDragging, isMouseOver, hasCreatedCaret;
  205020. BorderSize windowBorder;
  205021. HICON currentWindowIcon;
  205022. NOTIFYICONDATA* taskBarIcon;
  205023. IDropTarget* dropTarget;
  205024. class TemporaryImage : public Timer
  205025. {
  205026. public:
  205027. TemporaryImage() {}
  205028. ~TemporaryImage() {}
  205029. const Image& getImage (const bool transparent, const int w, const int h)
  205030. {
  205031. const Image::PixelFormat format = transparent ? Image::ARGB : Image::RGB;
  205032. if ((! image.isValid()) || image.getWidth() < w || image.getHeight() < h || image.getFormat() != format)
  205033. image = Image (new WindowsBitmapImage (format, (w + 31) & ~31, (h + 31) & ~31, false));
  205034. startTimer (3000);
  205035. return image;
  205036. }
  205037. void timerCallback()
  205038. {
  205039. stopTimer();
  205040. image = Image();
  205041. }
  205042. private:
  205043. Image image;
  205044. TemporaryImage (const TemporaryImage&);
  205045. TemporaryImage& operator= (const TemporaryImage&);
  205046. };
  205047. TemporaryImage offscreenImageGenerator;
  205048. class WindowClassHolder : public DeletedAtShutdown
  205049. {
  205050. public:
  205051. WindowClassHolder()
  205052. : windowClassName ("JUCE_")
  205053. {
  205054. // this name has to be different for each app/dll instance because otherwise
  205055. // poor old Win32 can get a bit confused (even despite it not being a process-global
  205056. // window class).
  205057. windowClassName << (int) (Time::currentTimeMillis() & 0x7fffffff);
  205058. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  205059. TCHAR moduleFile [1024];
  205060. moduleFile[0] = 0;
  205061. GetModuleFileName (moduleHandle, moduleFile, 1024);
  205062. WORD iconNum = 0;
  205063. WNDCLASSEX wcex;
  205064. wcex.cbSize = sizeof (wcex);
  205065. wcex.style = CS_OWNDC;
  205066. wcex.lpfnWndProc = (WNDPROC) windowProc;
  205067. wcex.lpszClassName = windowClassName;
  205068. wcex.cbClsExtra = 0;
  205069. wcex.cbWndExtra = 32;
  205070. wcex.hInstance = moduleHandle;
  205071. wcex.hIcon = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  205072. iconNum = 1;
  205073. wcex.hIconSm = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  205074. wcex.hCursor = 0;
  205075. wcex.hbrBackground = 0;
  205076. wcex.lpszMenuName = 0;
  205077. RegisterClassEx (&wcex);
  205078. }
  205079. ~WindowClassHolder()
  205080. {
  205081. if (ComponentPeer::getNumPeers() == 0)
  205082. UnregisterClass (windowClassName, (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle());
  205083. clearSingletonInstance();
  205084. }
  205085. String windowClassName;
  205086. juce_DeclareSingleton_SingleThreaded_Minimal (WindowClassHolder);
  205087. };
  205088. static void* createWindowCallback (void* userData)
  205089. {
  205090. static_cast <Win32ComponentPeer*> (userData)->createWindow();
  205091. return 0;
  205092. }
  205093. void createWindow()
  205094. {
  205095. DWORD exstyle = WS_EX_ACCEPTFILES;
  205096. DWORD type = WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
  205097. if (hasTitleBar())
  205098. {
  205099. type |= WS_OVERLAPPED;
  205100. if ((styleFlags & windowHasCloseButton) != 0)
  205101. {
  205102. type |= WS_SYSMENU;
  205103. }
  205104. else
  205105. {
  205106. // annoyingly, windows won't let you have a min/max button without a close button
  205107. jassert ((styleFlags & (windowHasMinimiseButton | windowHasMaximiseButton)) == 0);
  205108. }
  205109. if ((styleFlags & windowIsResizable) != 0)
  205110. type |= WS_THICKFRAME;
  205111. }
  205112. else
  205113. {
  205114. type |= WS_POPUP | WS_SYSMENU;
  205115. }
  205116. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  205117. exstyle |= WS_EX_TOOLWINDOW;
  205118. else
  205119. exstyle |= WS_EX_APPWINDOW;
  205120. if ((styleFlags & windowHasMinimiseButton) != 0)
  205121. type |= WS_MINIMIZEBOX;
  205122. if ((styleFlags & windowHasMaximiseButton) != 0)
  205123. type |= WS_MAXIMIZEBOX;
  205124. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  205125. exstyle |= WS_EX_TRANSPARENT;
  205126. if ((styleFlags & windowIsSemiTransparent) != 0
  205127. && Desktop::canUseSemiTransparentWindows())
  205128. exstyle |= WS_EX_LAYERED;
  205129. hwnd = CreateWindowEx (exstyle, WindowClassHolder::getInstance()->windowClassName, L"", type, 0, 0, 0, 0, 0, 0, 0, 0);
  205130. if (hwnd != 0)
  205131. {
  205132. SetWindowLongPtr (hwnd, 0, 0);
  205133. SetWindowLongPtr (hwnd, 8, (LONG_PTR) this);
  205134. SetWindowLongPtr (hwnd, GWLP_USERDATA, improbableWindowNumber);
  205135. if (dropTarget == 0)
  205136. dropTarget = new JuceDropTarget (this);
  205137. RegisterDragDrop (hwnd, dropTarget);
  205138. updateBorderSize();
  205139. // Calling this function here is (for some reason) necessary to make Windows
  205140. // correctly enable the menu items that we specify in the wm_initmenu message.
  205141. GetSystemMenu (hwnd, false);
  205142. }
  205143. else
  205144. {
  205145. jassertfalse;
  205146. }
  205147. }
  205148. static void* destroyWindowCallback (void* handle)
  205149. {
  205150. RevokeDragDrop ((HWND) handle);
  205151. DestroyWindow ((HWND) handle);
  205152. return 0;
  205153. }
  205154. static void* toFrontCallback1 (void* h)
  205155. {
  205156. SetForegroundWindow ((HWND) h);
  205157. return 0;
  205158. }
  205159. static void* toFrontCallback2 (void* h)
  205160. {
  205161. SetWindowPos ((HWND) h, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  205162. return 0;
  205163. }
  205164. static void* setFocusCallback (void* h)
  205165. {
  205166. SetFocus ((HWND) h);
  205167. return 0;
  205168. }
  205169. static void* getFocusCallback (void*)
  205170. {
  205171. return GetFocus();
  205172. }
  205173. void offsetWithinParent (int& x, int& y) const
  205174. {
  205175. if (isTransparent())
  205176. {
  205177. HWND parentHwnd = GetParent (hwnd);
  205178. if (parentHwnd != 0)
  205179. {
  205180. RECT parentRect;
  205181. GetWindowRect (parentHwnd, &parentRect);
  205182. x += parentRect.left;
  205183. y += parentRect.top;
  205184. }
  205185. }
  205186. }
  205187. bool isTransparent() const
  205188. {
  205189. return (GetWindowLong (hwnd, GWL_EXSTYLE) & WS_EX_LAYERED) != 0;
  205190. }
  205191. inline bool hasTitleBar() const throw() { return (styleFlags & windowHasTitleBar) != 0; }
  205192. void setIcon (const Image& newIcon)
  205193. {
  205194. HICON hicon = createHICONFromImage (newIcon, TRUE, 0, 0);
  205195. if (hicon != 0)
  205196. {
  205197. SendMessage (hwnd, WM_SETICON, ICON_BIG, (LPARAM) hicon);
  205198. SendMessage (hwnd, WM_SETICON, ICON_SMALL, (LPARAM) hicon);
  205199. if (currentWindowIcon != 0)
  205200. DestroyIcon (currentWindowIcon);
  205201. currentWindowIcon = hicon;
  205202. }
  205203. }
  205204. void handlePaintMessage()
  205205. {
  205206. HRGN rgn = CreateRectRgn (0, 0, 0, 0);
  205207. const int regionType = GetUpdateRgn (hwnd, rgn, false);
  205208. PAINTSTRUCT paintStruct;
  205209. HDC dc = BeginPaint (hwnd, &paintStruct); // Note this can immediately generate a WM_NCPAINT
  205210. // message and become re-entrant, but that's OK
  205211. // if something in a paint handler calls, e.g. a message box, this can become reentrant and
  205212. // corrupt the image it's using to paint into, so do a check here.
  205213. static bool reentrant = false;
  205214. if (reentrant)
  205215. {
  205216. DeleteObject (rgn);
  205217. EndPaint (hwnd, &paintStruct);
  205218. return;
  205219. }
  205220. reentrant = true;
  205221. // this is the rectangle to update..
  205222. int x = paintStruct.rcPaint.left;
  205223. int y = paintStruct.rcPaint.top;
  205224. int w = paintStruct.rcPaint.right - x;
  205225. int h = paintStruct.rcPaint.bottom - y;
  205226. const bool transparent = isTransparent();
  205227. if (transparent)
  205228. {
  205229. // it's not possible to have a transparent window with a title bar at the moment!
  205230. jassert (! hasTitleBar());
  205231. RECT r;
  205232. GetWindowRect (hwnd, &r);
  205233. x = y = 0;
  205234. w = r.right - r.left;
  205235. h = r.bottom - r.top;
  205236. }
  205237. if (w > 0 && h > 0)
  205238. {
  205239. clearMaskedRegion();
  205240. Image offscreenImage (offscreenImageGenerator.getImage (transparent, w, h));
  205241. RectangleList contextClip;
  205242. const Rectangle<int> clipBounds (0, 0, w, h);
  205243. bool needToPaintAll = true;
  205244. if (regionType == COMPLEXREGION && ! transparent)
  205245. {
  205246. HRGN clipRgn = CreateRectRgnIndirect (&paintStruct.rcPaint);
  205247. CombineRgn (rgn, rgn, clipRgn, RGN_AND);
  205248. DeleteObject (clipRgn);
  205249. char rgnData [8192];
  205250. const DWORD res = GetRegionData (rgn, sizeof (rgnData), (RGNDATA*) rgnData);
  205251. if (res > 0 && res <= sizeof (rgnData))
  205252. {
  205253. const RGNDATAHEADER* const hdr = &(((const RGNDATA*) rgnData)->rdh);
  205254. if (hdr->iType == RDH_RECTANGLES
  205255. && hdr->rcBound.right - hdr->rcBound.left >= w
  205256. && hdr->rcBound.bottom - hdr->rcBound.top >= h)
  205257. {
  205258. needToPaintAll = false;
  205259. const RECT* rects = (const RECT*) (rgnData + sizeof (RGNDATAHEADER));
  205260. int num = ((RGNDATA*) rgnData)->rdh.nCount;
  205261. while (--num >= 0)
  205262. {
  205263. if (rects->right <= x + w && rects->bottom <= y + h)
  205264. {
  205265. // (need to move this one pixel to the left because of a win32 bug)
  205266. const int cx = jmax (x, (int) rects->left - 1);
  205267. contextClip.addWithoutMerging (Rectangle<int> (cx - x, rects->top - y, rects->right - cx, rects->bottom - rects->top)
  205268. .getIntersection (clipBounds));
  205269. }
  205270. else
  205271. {
  205272. needToPaintAll = true;
  205273. break;
  205274. }
  205275. ++rects;
  205276. }
  205277. }
  205278. }
  205279. }
  205280. if (needToPaintAll)
  205281. {
  205282. contextClip.clear();
  205283. contextClip.addWithoutMerging (Rectangle<int> (0, 0, w, h));
  205284. }
  205285. if (transparent)
  205286. {
  205287. RectangleList::Iterator i (contextClip);
  205288. while (i.next())
  205289. offscreenImage.clear (*i.getRectangle());
  205290. }
  205291. // if the component's not opaque, this won't draw properly unless the platform can support this
  205292. jassert (Desktop::canUseSemiTransparentWindows() || component->isOpaque());
  205293. updateCurrentModifiers();
  205294. LowLevelGraphicsSoftwareRenderer context (offscreenImage, -x, -y, contextClip);
  205295. handlePaint (context);
  205296. if (! dontRepaint)
  205297. static_cast <WindowsBitmapImage*> (offscreenImage.getSharedImage())
  205298. ->blitToWindow (hwnd, dc, transparent, x, y, maskedRegion);
  205299. }
  205300. DeleteObject (rgn);
  205301. EndPaint (hwnd, &paintStruct);
  205302. reentrant = false;
  205303. #ifndef JUCE_GCC //xxx should add this fn for gcc..
  205304. _fpreset(); // because some graphics cards can unmask FP exceptions
  205305. #endif
  205306. lastPaintTime = Time::getMillisecondCounter();
  205307. }
  205308. void doMouseEvent (const Point<int>& position)
  205309. {
  205310. handleMouseEvent (0, position, currentModifiers, getMouseEventTime());
  205311. }
  205312. void doMouseMove (const Point<int>& position)
  205313. {
  205314. if (! isMouseOver)
  205315. {
  205316. isMouseOver = true;
  205317. updateKeyModifiers();
  205318. TRACKMOUSEEVENT tme;
  205319. tme.cbSize = sizeof (tme);
  205320. tme.dwFlags = TME_LEAVE;
  205321. tme.hwndTrack = hwnd;
  205322. tme.dwHoverTime = 0;
  205323. if (! TrackMouseEvent (&tme))
  205324. jassertfalse;
  205325. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  205326. }
  205327. else if (! isDragging)
  205328. {
  205329. if (! contains (position, false))
  205330. return;
  205331. }
  205332. // (Throttling the incoming queue of mouse-events seems to still be required in XP..)
  205333. static uint32 lastMouseTime = 0;
  205334. const uint32 now = Time::getMillisecondCounter();
  205335. const int maxMouseMovesPerSecond = 60;
  205336. if (now > lastMouseTime + 1000 / maxMouseMovesPerSecond)
  205337. {
  205338. lastMouseTime = now;
  205339. doMouseEvent (position);
  205340. }
  205341. }
  205342. void doMouseDown (const Point<int>& position, const WPARAM wParam)
  205343. {
  205344. if (GetCapture() != hwnd)
  205345. SetCapture (hwnd);
  205346. doMouseMove (position);
  205347. updateModifiersFromWParam (wParam);
  205348. isDragging = true;
  205349. doMouseEvent (position);
  205350. }
  205351. void doMouseUp (const Point<int>& position, const WPARAM wParam)
  205352. {
  205353. updateModifiersFromWParam (wParam);
  205354. isDragging = false;
  205355. // release the mouse capture if the user has released all buttons
  205356. if ((wParam & (MK_LBUTTON | MK_RBUTTON | MK_MBUTTON)) == 0 && hwnd == GetCapture())
  205357. ReleaseCapture();
  205358. doMouseEvent (position);
  205359. }
  205360. void doCaptureChanged()
  205361. {
  205362. if (isDragging)
  205363. doMouseUp (getCurrentMousePos(), (WPARAM) 0);
  205364. }
  205365. void doMouseExit()
  205366. {
  205367. isMouseOver = false;
  205368. doMouseEvent (getCurrentMousePos());
  205369. }
  205370. void doMouseWheel (const Point<int>& position, const WPARAM wParam, const bool isVertical)
  205371. {
  205372. updateKeyModifiers();
  205373. const float amount = jlimit (-1000.0f, 1000.0f, 0.75f * (short) HIWORD (wParam));
  205374. handleMouseWheel (0, position, getMouseEventTime(),
  205375. isVertical ? 0.0f : amount,
  205376. isVertical ? amount : 0.0f);
  205377. }
  205378. void sendModifierKeyChangeIfNeeded()
  205379. {
  205380. if (modifiersAtLastCallback != currentModifiers)
  205381. {
  205382. modifiersAtLastCallback = currentModifiers;
  205383. handleModifierKeysChange();
  205384. }
  205385. }
  205386. bool doKeyUp (const WPARAM key)
  205387. {
  205388. updateKeyModifiers();
  205389. switch (key)
  205390. {
  205391. case VK_SHIFT:
  205392. case VK_CONTROL:
  205393. case VK_MENU:
  205394. case VK_CAPITAL:
  205395. case VK_LWIN:
  205396. case VK_RWIN:
  205397. case VK_APPS:
  205398. case VK_NUMLOCK:
  205399. case VK_SCROLL:
  205400. case VK_LSHIFT:
  205401. case VK_RSHIFT:
  205402. case VK_LCONTROL:
  205403. case VK_LMENU:
  205404. case VK_RCONTROL:
  205405. case VK_RMENU:
  205406. sendModifierKeyChangeIfNeeded();
  205407. }
  205408. return handleKeyUpOrDown (false)
  205409. || Component::getCurrentlyModalComponent() != 0;
  205410. }
  205411. bool doKeyDown (const WPARAM key)
  205412. {
  205413. updateKeyModifiers();
  205414. bool used = false;
  205415. switch (key)
  205416. {
  205417. case VK_SHIFT:
  205418. case VK_LSHIFT:
  205419. case VK_RSHIFT:
  205420. case VK_CONTROL:
  205421. case VK_LCONTROL:
  205422. case VK_RCONTROL:
  205423. case VK_MENU:
  205424. case VK_LMENU:
  205425. case VK_RMENU:
  205426. case VK_LWIN:
  205427. case VK_RWIN:
  205428. case VK_CAPITAL:
  205429. case VK_NUMLOCK:
  205430. case VK_SCROLL:
  205431. case VK_APPS:
  205432. sendModifierKeyChangeIfNeeded();
  205433. break;
  205434. case VK_LEFT:
  205435. case VK_RIGHT:
  205436. case VK_UP:
  205437. case VK_DOWN:
  205438. case VK_PRIOR:
  205439. case VK_NEXT:
  205440. case VK_HOME:
  205441. case VK_END:
  205442. case VK_DELETE:
  205443. case VK_INSERT:
  205444. case VK_F1:
  205445. case VK_F2:
  205446. case VK_F3:
  205447. case VK_F4:
  205448. case VK_F5:
  205449. case VK_F6:
  205450. case VK_F7:
  205451. case VK_F8:
  205452. case VK_F9:
  205453. case VK_F10:
  205454. case VK_F11:
  205455. case VK_F12:
  205456. case VK_F13:
  205457. case VK_F14:
  205458. case VK_F15:
  205459. case VK_F16:
  205460. used = handleKeyUpOrDown (true);
  205461. used = handleKeyPress (extendedKeyModifier | (int) key, 0) || used;
  205462. break;
  205463. case VK_ADD:
  205464. case VK_SUBTRACT:
  205465. case VK_MULTIPLY:
  205466. case VK_DIVIDE:
  205467. case VK_SEPARATOR:
  205468. case VK_DECIMAL:
  205469. used = handleKeyUpOrDown (true);
  205470. break;
  205471. default:
  205472. used = handleKeyUpOrDown (true);
  205473. {
  205474. MSG msg;
  205475. if (! PeekMessage (&msg, hwnd, WM_CHAR, WM_DEADCHAR, PM_NOREMOVE))
  205476. {
  205477. // if there isn't a WM_CHAR or WM_DEADCHAR message pending, we need to
  205478. // manually generate the key-press event that matches this key-down.
  205479. const UINT keyChar = MapVirtualKey (key, 2);
  205480. used = handleKeyPress ((int) LOWORD (keyChar), 0) || used;
  205481. }
  205482. }
  205483. break;
  205484. }
  205485. if (Component::getCurrentlyModalComponent() != 0)
  205486. used = true;
  205487. return used;
  205488. }
  205489. bool doKeyChar (int key, const LPARAM flags)
  205490. {
  205491. updateKeyModifiers();
  205492. juce_wchar textChar = (juce_wchar) key;
  205493. const int virtualScanCode = (flags >> 16) & 0xff;
  205494. if (key >= '0' && key <= '9')
  205495. {
  205496. switch (virtualScanCode) // check for a numeric keypad scan-code
  205497. {
  205498. case 0x52:
  205499. case 0x4f:
  205500. case 0x50:
  205501. case 0x51:
  205502. case 0x4b:
  205503. case 0x4c:
  205504. case 0x4d:
  205505. case 0x47:
  205506. case 0x48:
  205507. case 0x49:
  205508. key = (key - '0') + KeyPress::numberPad0;
  205509. break;
  205510. default:
  205511. break;
  205512. }
  205513. }
  205514. else
  205515. {
  205516. // convert the scan code to an unmodified character code..
  205517. const UINT virtualKey = MapVirtualKey (virtualScanCode, 1);
  205518. UINT keyChar = MapVirtualKey (virtualKey, 2);
  205519. keyChar = LOWORD (keyChar);
  205520. if (keyChar != 0)
  205521. key = (int) keyChar;
  205522. // avoid sending junk text characters for some control-key combinations
  205523. if (textChar < ' ' && currentModifiers.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::altModifier))
  205524. textChar = 0;
  205525. }
  205526. return handleKeyPress (key, textChar);
  205527. }
  205528. bool doAppCommand (const LPARAM lParam)
  205529. {
  205530. int key = 0;
  205531. switch (GET_APPCOMMAND_LPARAM (lParam))
  205532. {
  205533. case APPCOMMAND_MEDIA_PLAY_PAUSE:
  205534. key = KeyPress::playKey;
  205535. break;
  205536. case APPCOMMAND_MEDIA_STOP:
  205537. key = KeyPress::stopKey;
  205538. break;
  205539. case APPCOMMAND_MEDIA_NEXTTRACK:
  205540. key = KeyPress::fastForwardKey;
  205541. break;
  205542. case APPCOMMAND_MEDIA_PREVIOUSTRACK:
  205543. key = KeyPress::rewindKey;
  205544. break;
  205545. }
  205546. if (key != 0)
  205547. {
  205548. updateKeyModifiers();
  205549. if (hwnd == GetActiveWindow())
  205550. {
  205551. handleKeyPress (key, 0);
  205552. return true;
  205553. }
  205554. }
  205555. return false;
  205556. }
  205557. class JuceDropTarget : public ComBaseClassHelper <IDropTarget>
  205558. {
  205559. public:
  205560. JuceDropTarget (Win32ComponentPeer* const owner_)
  205561. : owner (owner_)
  205562. {
  205563. }
  205564. ~JuceDropTarget() {}
  205565. HRESULT __stdcall DragEnter (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  205566. {
  205567. updateFileList (pDataObject);
  205568. owner->handleFileDragMove (files, owner->globalPositionToRelative (Point<int> (mousePos.x, mousePos.y)));
  205569. *pdwEffect = DROPEFFECT_COPY;
  205570. return S_OK;
  205571. }
  205572. HRESULT __stdcall DragLeave()
  205573. {
  205574. owner->handleFileDragExit (files);
  205575. return S_OK;
  205576. }
  205577. HRESULT __stdcall DragOver (DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  205578. {
  205579. owner->handleFileDragMove (files, owner->globalPositionToRelative (Point<int> (mousePos.x, mousePos.y)));
  205580. *pdwEffect = DROPEFFECT_COPY;
  205581. return S_OK;
  205582. }
  205583. HRESULT __stdcall Drop (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  205584. {
  205585. updateFileList (pDataObject);
  205586. owner->handleFileDragDrop (files, owner->globalPositionToRelative (Point<int> (mousePos.x, mousePos.y)));
  205587. *pdwEffect = DROPEFFECT_COPY;
  205588. return S_OK;
  205589. }
  205590. private:
  205591. Win32ComponentPeer* const owner;
  205592. StringArray files;
  205593. void updateFileList (IDataObject* const pDataObject)
  205594. {
  205595. files.clear();
  205596. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  205597. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  205598. if (pDataObject->GetData (&format, &medium) == S_OK)
  205599. {
  205600. const SIZE_T totalLen = GlobalSize (medium.hGlobal);
  205601. const LPDROPFILES pDropFiles = (const LPDROPFILES) GlobalLock (medium.hGlobal);
  205602. unsigned int i = 0;
  205603. if (pDropFiles->fWide)
  205604. {
  205605. const WCHAR* const fname = (WCHAR*) (((const char*) pDropFiles) + sizeof (DROPFILES));
  205606. for (;;)
  205607. {
  205608. unsigned int len = 0;
  205609. while (i + len < totalLen && fname [i + len] != 0)
  205610. ++len;
  205611. if (len == 0)
  205612. break;
  205613. files.add (String (fname + i, len));
  205614. i += len + 1;
  205615. }
  205616. }
  205617. else
  205618. {
  205619. const char* const fname = ((const char*) pDropFiles) + sizeof (DROPFILES);
  205620. for (;;)
  205621. {
  205622. unsigned int len = 0;
  205623. while (i + len < totalLen && fname [i + len] != 0)
  205624. ++len;
  205625. if (len == 0)
  205626. break;
  205627. files.add (String (fname + i, len));
  205628. i += len + 1;
  205629. }
  205630. }
  205631. GlobalUnlock (medium.hGlobal);
  205632. }
  205633. }
  205634. JuceDropTarget (const JuceDropTarget&);
  205635. JuceDropTarget& operator= (const JuceDropTarget&);
  205636. };
  205637. void doSettingChange()
  205638. {
  205639. Desktop::getInstance().refreshMonitorSizes();
  205640. if (fullScreen && ! isMinimised())
  205641. {
  205642. const Rectangle<int> r (component->getParentMonitorArea());
  205643. SetWindowPos (hwnd, 0,
  205644. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  205645. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOSENDCHANGING);
  205646. }
  205647. }
  205648. public:
  205649. static LRESULT CALLBACK windowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  205650. {
  205651. Win32ComponentPeer* const peer = getOwnerOfWindow (h);
  205652. if (peer != 0)
  205653. return peer->peerWindowProc (h, message, wParam, lParam);
  205654. return DefWindowProcW (h, message, wParam, lParam);
  205655. }
  205656. private:
  205657. static const Point<int> getPointFromLParam (LPARAM lParam) throw()
  205658. {
  205659. return Point<int> (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam));
  205660. }
  205661. const Point<int> getCurrentMousePos() throw()
  205662. {
  205663. RECT wr;
  205664. GetWindowRect (hwnd, &wr);
  205665. const DWORD mp = GetMessagePos();
  205666. return Point<int> (GET_X_LPARAM (mp) - wr.left - windowBorder.getLeft(),
  205667. GET_Y_LPARAM (mp) - wr.top - windowBorder.getTop());
  205668. }
  205669. LRESULT peerWindowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  205670. {
  205671. if (isValidPeer (this))
  205672. {
  205673. switch (message)
  205674. {
  205675. case WM_NCHITTEST:
  205676. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  205677. return HTTRANSPARENT;
  205678. if (hasTitleBar())
  205679. break;
  205680. return HTCLIENT;
  205681. case WM_PAINT:
  205682. handlePaintMessage();
  205683. return 0;
  205684. case WM_NCPAINT:
  205685. if (wParam != 1)
  205686. handlePaintMessage();
  205687. if (hasTitleBar())
  205688. break;
  205689. return 0;
  205690. case WM_ERASEBKGND:
  205691. case WM_NCCALCSIZE:
  205692. if (hasTitleBar())
  205693. break;
  205694. return 1;
  205695. case WM_MOUSEMOVE:
  205696. doMouseMove (getPointFromLParam (lParam));
  205697. return 0;
  205698. case WM_MOUSELEAVE:
  205699. doMouseExit();
  205700. return 0;
  205701. case WM_LBUTTONDOWN:
  205702. case WM_MBUTTONDOWN:
  205703. case WM_RBUTTONDOWN:
  205704. doMouseDown (getPointFromLParam (lParam), wParam);
  205705. return 0;
  205706. case WM_LBUTTONUP:
  205707. case WM_MBUTTONUP:
  205708. case WM_RBUTTONUP:
  205709. doMouseUp (getPointFromLParam (lParam), wParam);
  205710. return 0;
  205711. case WM_CAPTURECHANGED:
  205712. doCaptureChanged();
  205713. return 0;
  205714. case WM_NCMOUSEMOVE:
  205715. if (hasTitleBar())
  205716. break;
  205717. return 0;
  205718. case 0x020A: /* WM_MOUSEWHEEL */
  205719. doMouseWheel (getCurrentMousePos(), wParam, true);
  205720. return 0;
  205721. case 0x020E: /* WM_MOUSEHWHEEL */
  205722. doMouseWheel (getCurrentMousePos(), wParam, false);
  205723. return 0;
  205724. case WM_WINDOWPOSCHANGING:
  205725. if ((styleFlags & (windowHasTitleBar | windowIsResizable)) == (windowHasTitleBar | windowIsResizable))
  205726. {
  205727. WINDOWPOS* const wp = (WINDOWPOS*) lParam;
  205728. if ((wp->flags & (SWP_NOMOVE | SWP_NOSIZE)) != (SWP_NOMOVE | SWP_NOSIZE))
  205729. {
  205730. if (constrainer != 0)
  205731. {
  205732. const Rectangle<int> current (component->getX() - windowBorder.getLeft(),
  205733. component->getY() - windowBorder.getTop(),
  205734. component->getWidth() + windowBorder.getLeftAndRight(),
  205735. component->getHeight() + windowBorder.getTopAndBottom());
  205736. Rectangle<int> pos (wp->x, wp->y, wp->cx, wp->cy);
  205737. constrainer->checkBounds (pos, current,
  205738. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  205739. pos.getY() != current.getY() && pos.getBottom() == current.getBottom(),
  205740. pos.getX() != current.getX() && pos.getRight() == current.getRight(),
  205741. pos.getY() == current.getY() && pos.getBottom() != current.getBottom(),
  205742. pos.getX() == current.getX() && pos.getRight() != current.getRight());
  205743. wp->x = pos.getX();
  205744. wp->y = pos.getY();
  205745. wp->cx = pos.getWidth();
  205746. wp->cy = pos.getHeight();
  205747. }
  205748. }
  205749. }
  205750. return 0;
  205751. case WM_WINDOWPOSCHANGED:
  205752. handleMovedOrResized();
  205753. if (dontRepaint)
  205754. break; // needed for non-accelerated openGL windows to draw themselves correctly..
  205755. return 0;
  205756. case WM_KEYDOWN:
  205757. case WM_SYSKEYDOWN:
  205758. if (doKeyDown (wParam))
  205759. return 0;
  205760. break;
  205761. case WM_KEYUP:
  205762. case WM_SYSKEYUP:
  205763. if (doKeyUp (wParam))
  205764. return 0;
  205765. break;
  205766. case WM_CHAR:
  205767. if (doKeyChar ((int) wParam, lParam))
  205768. return 0;
  205769. break;
  205770. case WM_APPCOMMAND:
  205771. if (doAppCommand (lParam))
  205772. return TRUE;
  205773. break;
  205774. case WM_SETFOCUS:
  205775. updateKeyModifiers();
  205776. handleFocusGain();
  205777. break;
  205778. case WM_KILLFOCUS:
  205779. if (hasCreatedCaret)
  205780. {
  205781. hasCreatedCaret = false;
  205782. DestroyCaret();
  205783. }
  205784. handleFocusLoss();
  205785. break;
  205786. case WM_ACTIVATEAPP:
  205787. // Windows does weird things to process priority when you swap apps,
  205788. // so this forces an update when the app is brought to the front
  205789. if (wParam != FALSE)
  205790. juce_repeatLastProcessPriority();
  205791. else
  205792. Desktop::getInstance().setKioskModeComponent (0); // turn kiosk mode off if we lose focus
  205793. juce_CheckCurrentlyFocusedTopLevelWindow();
  205794. modifiersAtLastCallback = -1;
  205795. return 0;
  205796. case WM_ACTIVATE:
  205797. if (LOWORD (wParam) == WA_ACTIVE || LOWORD (wParam) == WA_CLICKACTIVE)
  205798. {
  205799. modifiersAtLastCallback = -1;
  205800. updateKeyModifiers();
  205801. if (isMinimised())
  205802. {
  205803. component->repaint();
  205804. handleMovedOrResized();
  205805. if (! ComponentPeer::isValidPeer (this))
  205806. return 0;
  205807. }
  205808. if (LOWORD (wParam) == WA_CLICKACTIVE
  205809. && component->isCurrentlyBlockedByAnotherModalComponent())
  205810. {
  205811. const Point<int> mousePos (component->getMouseXYRelative());
  205812. Component* const underMouse = component->getComponentAt (mousePos.getX(), mousePos.getY());
  205813. if (underMouse != 0 && underMouse->isCurrentlyBlockedByAnotherModalComponent())
  205814. Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  205815. return 0;
  205816. }
  205817. handleBroughtToFront();
  205818. if (component->isCurrentlyBlockedByAnotherModalComponent())
  205819. Component::getCurrentlyModalComponent()->toFront (true);
  205820. return 0;
  205821. }
  205822. break;
  205823. case WM_NCACTIVATE:
  205824. // while a temporary window is being shown, prevent Windows from deactivating the
  205825. // title bars of our main windows.
  205826. if (wParam == 0 && ! shouldDeactivateTitleBar)
  205827. wParam = TRUE; // change this and let it get passed to the DefWindowProc.
  205828. break;
  205829. case WM_MOUSEACTIVATE:
  205830. if (! component->getMouseClickGrabsKeyboardFocus())
  205831. return MA_NOACTIVATE;
  205832. break;
  205833. case WM_SHOWWINDOW:
  205834. if (wParam != 0)
  205835. handleBroughtToFront();
  205836. break;
  205837. case WM_CLOSE:
  205838. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  205839. handleUserClosingWindow();
  205840. return 0;
  205841. case WM_QUERYENDSESSION:
  205842. if (JUCEApplication::getInstance() != 0)
  205843. {
  205844. JUCEApplication::getInstance()->systemRequestedQuit();
  205845. return MessageManager::getInstance()->hasStopMessageBeenSent();
  205846. }
  205847. return TRUE;
  205848. case WM_TRAYNOTIFY:
  205849. if (component->isCurrentlyBlockedByAnotherModalComponent())
  205850. {
  205851. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN
  205852. || lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  205853. {
  205854. Component* const current = Component::getCurrentlyModalComponent();
  205855. if (current != 0)
  205856. current->inputAttemptWhenModal();
  205857. }
  205858. }
  205859. else
  205860. {
  205861. ModifierKeys eventMods (ModifierKeys::getCurrentModifiersRealtime());
  205862. if (lParam == WM_LBUTTONDOWN || lParam == WM_LBUTTONDBLCLK)
  205863. eventMods = eventMods.withFlags (ModifierKeys::leftButtonModifier);
  205864. else if (lParam == WM_RBUTTONDOWN || lParam == WM_RBUTTONDBLCLK)
  205865. eventMods = eventMods.withFlags (ModifierKeys::rightButtonModifier);
  205866. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  205867. eventMods = eventMods.withoutMouseButtons();
  205868. const MouseEvent e (Desktop::getInstance().getMainMouseSource(),
  205869. Point<int>(), eventMods, component, component, getMouseEventTime(),
  205870. Point<int>(), getMouseEventTime(), 1, false);
  205871. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN)
  205872. {
  205873. SetFocus (hwnd);
  205874. SetForegroundWindow (hwnd);
  205875. component->mouseDown (e);
  205876. }
  205877. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  205878. {
  205879. component->mouseUp (e);
  205880. }
  205881. else if (lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  205882. {
  205883. component->mouseDoubleClick (e);
  205884. }
  205885. else if (lParam == WM_MOUSEMOVE)
  205886. {
  205887. component->mouseMove (e);
  205888. }
  205889. }
  205890. break;
  205891. case WM_SYNCPAINT:
  205892. return 0;
  205893. case WM_PALETTECHANGED:
  205894. InvalidateRect (h, 0, 0);
  205895. break;
  205896. case WM_DISPLAYCHANGE:
  205897. InvalidateRect (h, 0, 0);
  205898. createPaletteIfNeeded = true;
  205899. // intentional fall-through...
  205900. case WM_SETTINGCHANGE: // note the fall-through in the previous case!
  205901. doSettingChange();
  205902. break;
  205903. case WM_INITMENU:
  205904. if (! hasTitleBar())
  205905. {
  205906. if (isFullScreen())
  205907. {
  205908. EnableMenuItem ((HMENU) wParam, SC_RESTORE, MF_BYCOMMAND | MF_ENABLED);
  205909. EnableMenuItem ((HMENU) wParam, SC_MOVE, MF_BYCOMMAND | MF_GRAYED);
  205910. }
  205911. else if (! isMinimised())
  205912. {
  205913. EnableMenuItem ((HMENU) wParam, SC_MAXIMIZE, MF_BYCOMMAND | MF_GRAYED);
  205914. }
  205915. }
  205916. break;
  205917. case WM_SYSCOMMAND:
  205918. switch (wParam & 0xfff0)
  205919. {
  205920. case SC_CLOSE:
  205921. if (sendInputAttemptWhenModalMessage())
  205922. return 0;
  205923. if (hasTitleBar())
  205924. {
  205925. PostMessage (h, WM_CLOSE, 0, 0);
  205926. return 0;
  205927. }
  205928. break;
  205929. case SC_KEYMENU:
  205930. // (NB mustn't call sendInputAttemptWhenModalMessage() here because of very
  205931. // obscure situations that can arise if a modal loop is started from an alt-key
  205932. // keypress).
  205933. if (hasTitleBar() && h == GetCapture())
  205934. ReleaseCapture();
  205935. break;
  205936. case SC_MAXIMIZE:
  205937. if (sendInputAttemptWhenModalMessage())
  205938. return 0;
  205939. setFullScreen (true);
  205940. return 0;
  205941. case SC_MINIMIZE:
  205942. if (sendInputAttemptWhenModalMessage())
  205943. return 0;
  205944. if (! hasTitleBar())
  205945. {
  205946. setMinimised (true);
  205947. return 0;
  205948. }
  205949. break;
  205950. case SC_RESTORE:
  205951. if (sendInputAttemptWhenModalMessage())
  205952. return 0;
  205953. if (hasTitleBar())
  205954. {
  205955. if (isFullScreen())
  205956. {
  205957. setFullScreen (false);
  205958. return 0;
  205959. }
  205960. }
  205961. else
  205962. {
  205963. if (isMinimised())
  205964. setMinimised (false);
  205965. else if (isFullScreen())
  205966. setFullScreen (false);
  205967. return 0;
  205968. }
  205969. break;
  205970. }
  205971. break;
  205972. case WM_NCLBUTTONDOWN:
  205973. case WM_NCRBUTTONDOWN:
  205974. case WM_NCMBUTTONDOWN:
  205975. sendInputAttemptWhenModalMessage();
  205976. break;
  205977. //case WM_IME_STARTCOMPOSITION;
  205978. // return 0;
  205979. case WM_GETDLGCODE:
  205980. return DLGC_WANTALLKEYS;
  205981. default:
  205982. break;
  205983. }
  205984. }
  205985. return DefWindowProcW (h, message, wParam, lParam);
  205986. }
  205987. bool sendInputAttemptWhenModalMessage()
  205988. {
  205989. if (component->isCurrentlyBlockedByAnotherModalComponent())
  205990. {
  205991. Component* const current = Component::getCurrentlyModalComponent();
  205992. if (current != 0)
  205993. current->inputAttemptWhenModal();
  205994. return true;
  205995. }
  205996. return false;
  205997. }
  205998. Win32ComponentPeer (const Win32ComponentPeer&);
  205999. Win32ComponentPeer& operator= (const Win32ComponentPeer&);
  206000. };
  206001. ModifierKeys Win32ComponentPeer::currentModifiers;
  206002. ModifierKeys Win32ComponentPeer::modifiersAtLastCallback;
  206003. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  206004. {
  206005. return new Win32ComponentPeer (this, styleFlags);
  206006. }
  206007. juce_ImplementSingleton_SingleThreaded (Win32ComponentPeer::WindowClassHolder);
  206008. void ModifierKeys::updateCurrentModifiers() throw()
  206009. {
  206010. currentModifiers = Win32ComponentPeer::currentModifiers;
  206011. }
  206012. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  206013. {
  206014. Win32ComponentPeer::updateKeyModifiers();
  206015. int keyMods = 0;
  206016. if ((GetKeyState (VK_LBUTTON) & 0x8000) != 0) keyMods |= ModifierKeys::leftButtonModifier;
  206017. if ((GetKeyState (VK_RBUTTON) & 0x8000) != 0) keyMods |= ModifierKeys::rightButtonModifier;
  206018. if ((GetKeyState (VK_MBUTTON) & 0x8000) != 0) keyMods |= ModifierKeys::middleButtonModifier;
  206019. Win32ComponentPeer::currentModifiers
  206020. = Win32ComponentPeer::currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  206021. return Win32ComponentPeer::currentModifiers;
  206022. }
  206023. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  206024. {
  206025. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  206026. if (wp != 0)
  206027. wp->setTaskBarIcon (newImage);
  206028. }
  206029. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  206030. {
  206031. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  206032. if (wp != 0)
  206033. wp->setTaskBarIconToolTip (tooltip);
  206034. }
  206035. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw()
  206036. {
  206037. DWORD val = GetWindowLong (h, styleType);
  206038. if (bitIsSet)
  206039. val |= feature;
  206040. else
  206041. val &= ~feature;
  206042. SetWindowLongPtr (h, styleType, val);
  206043. SetWindowPos (h, 0, 0, 0, 0, 0,
  206044. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER
  206045. | SWP_NOOWNERZORDER | SWP_FRAMECHANGED | SWP_NOSENDCHANGING);
  206046. }
  206047. bool Process::isForegroundProcess()
  206048. {
  206049. HWND fg = GetForegroundWindow();
  206050. if (fg == 0)
  206051. return true;
  206052. // when running as a plugin in IE8, the browser UI runs in a different process to the plugin, so
  206053. // process ID isn't a reliable way to check if the foreground window belongs to us - instead, we
  206054. // have to see if any of our windows are children of the foreground window
  206055. fg = GetAncestor (fg, GA_ROOT);
  206056. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  206057. {
  206058. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (ComponentPeer::getPeer (i));
  206059. if (wp != 0 && wp->isInside (fg))
  206060. return true;
  206061. }
  206062. return false;
  206063. }
  206064. bool AlertWindow::showNativeDialogBox (const String& title,
  206065. const String& bodyText,
  206066. bool isOkCancel)
  206067. {
  206068. return MessageBox (0, bodyText, title,
  206069. MB_SETFOREGROUND | (isOkCancel ? MB_OKCANCEL
  206070. : MB_OK)) == IDOK;
  206071. }
  206072. void Desktop::createMouseInputSources()
  206073. {
  206074. mouseSources.add (new MouseInputSource (0, true));
  206075. }
  206076. const Point<int> Desktop::getMousePosition()
  206077. {
  206078. POINT mousePos;
  206079. GetCursorPos (&mousePos);
  206080. return Point<int> (mousePos.x, mousePos.y);
  206081. }
  206082. void Desktop::setMousePosition (const Point<int>& newPosition)
  206083. {
  206084. SetCursorPos (newPosition.getX(), newPosition.getY());
  206085. }
  206086. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  206087. {
  206088. return createSoftwareImage (format, width, height, clearImage);
  206089. }
  206090. class ScreenSaverDefeater : public Timer,
  206091. public DeletedAtShutdown
  206092. {
  206093. public:
  206094. ScreenSaverDefeater()
  206095. {
  206096. startTimer (10000);
  206097. timerCallback();
  206098. }
  206099. ~ScreenSaverDefeater() {}
  206100. void timerCallback()
  206101. {
  206102. if (Process::isForegroundProcess())
  206103. {
  206104. // simulate a shift key getting pressed..
  206105. INPUT input[2];
  206106. input[0].type = INPUT_KEYBOARD;
  206107. input[0].ki.wVk = VK_SHIFT;
  206108. input[0].ki.dwFlags = 0;
  206109. input[0].ki.dwExtraInfo = 0;
  206110. input[1].type = INPUT_KEYBOARD;
  206111. input[1].ki.wVk = VK_SHIFT;
  206112. input[1].ki.dwFlags = KEYEVENTF_KEYUP;
  206113. input[1].ki.dwExtraInfo = 0;
  206114. SendInput (2, input, sizeof (INPUT));
  206115. }
  206116. }
  206117. };
  206118. static ScreenSaverDefeater* screenSaverDefeater = 0;
  206119. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  206120. {
  206121. if (isEnabled)
  206122. deleteAndZero (screenSaverDefeater);
  206123. else if (screenSaverDefeater == 0)
  206124. screenSaverDefeater = new ScreenSaverDefeater();
  206125. }
  206126. bool Desktop::isScreenSaverEnabled()
  206127. {
  206128. return screenSaverDefeater == 0;
  206129. }
  206130. /* (The code below is the "correct" way to disable the screen saver, but it
  206131. completely fails on winXP when the saver is password-protected...)
  206132. static bool juce_screenSaverEnabled = true;
  206133. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  206134. {
  206135. juce_screenSaverEnabled = isEnabled;
  206136. SetThreadExecutionState (isEnabled ? ES_CONTINUOUS
  206137. : (ES_DISPLAY_REQUIRED | ES_CONTINUOUS));
  206138. }
  206139. bool Desktop::isScreenSaverEnabled() throw()
  206140. {
  206141. return juce_screenSaverEnabled;
  206142. }
  206143. */
  206144. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool /*allowMenusAndBars*/)
  206145. {
  206146. if (enableOrDisable)
  206147. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  206148. }
  206149. static BOOL CALLBACK enumMonitorsProc (HMONITOR, HDC, LPRECT r, LPARAM userInfo)
  206150. {
  206151. Array <Rectangle<int> >* const monitorCoords = (Array <Rectangle<int> >*) userInfo;
  206152. monitorCoords->add (Rectangle<int> (r->left, r->top, r->right - r->left, r->bottom - r->top));
  206153. return TRUE;
  206154. }
  206155. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  206156. {
  206157. EnumDisplayMonitors (0, 0, &enumMonitorsProc, (LPARAM) &monitorCoords);
  206158. // make sure the first in the list is the main monitor
  206159. for (int i = 1; i < monitorCoords.size(); ++i)
  206160. if (monitorCoords[i].getX() == 0 && monitorCoords[i].getY() == 0)
  206161. monitorCoords.swap (i, 0);
  206162. if (monitorCoords.size() == 0)
  206163. {
  206164. RECT r;
  206165. GetWindowRect (GetDesktopWindow(), &r);
  206166. monitorCoords.add (Rectangle<int> (r.left, r.top, r.right - r.left, r.bottom - r.top));
  206167. }
  206168. if (clipToWorkArea)
  206169. {
  206170. // clip the main monitor to the active non-taskbar area
  206171. RECT r;
  206172. SystemParametersInfo (SPI_GETWORKAREA, 0, &r, 0);
  206173. Rectangle<int>& screen = monitorCoords.getReference (0);
  206174. screen.setPosition (jmax (screen.getX(), (int) r.left),
  206175. jmax (screen.getY(), (int) r.top));
  206176. screen.setSize (jmin (screen.getRight(), (int) r.right) - screen.getX(),
  206177. jmin (screen.getBottom(), (int) r.bottom) - screen.getY());
  206178. }
  206179. }
  206180. static const Image createImageFromHBITMAP (HBITMAP bitmap) throw()
  206181. {
  206182. Image im;
  206183. if (bitmap != 0)
  206184. {
  206185. BITMAP bm;
  206186. if (GetObject (bitmap, sizeof (BITMAP), &bm)
  206187. && bm.bmWidth > 0 && bm.bmHeight > 0)
  206188. {
  206189. HDC tempDC = GetDC (0);
  206190. HDC dc = CreateCompatibleDC (tempDC);
  206191. ReleaseDC (0, tempDC);
  206192. SelectObject (dc, bitmap);
  206193. im = Image (Image::ARGB, bm.bmWidth, bm.bmHeight, true);
  206194. Image::BitmapData imageData (im, 0, 0, bm.bmWidth, bm.bmHeight, true);
  206195. for (int y = bm.bmHeight; --y >= 0;)
  206196. {
  206197. for (int x = bm.bmWidth; --x >= 0;)
  206198. {
  206199. COLORREF col = GetPixel (dc, x, y);
  206200. imageData.setPixelColour (x, y, Colour ((uint8) GetRValue (col),
  206201. (uint8) GetGValue (col),
  206202. (uint8) GetBValue (col)));
  206203. }
  206204. }
  206205. DeleteDC (dc);
  206206. }
  206207. }
  206208. return im;
  206209. }
  206210. static const Image createImageFromHICON (HICON icon) throw()
  206211. {
  206212. ICONINFO info;
  206213. if (GetIconInfo (icon, &info))
  206214. {
  206215. Image mask (createImageFromHBITMAP (info.hbmMask));
  206216. Image image (createImageFromHBITMAP (info.hbmColor));
  206217. if (mask.isValid() && image.isValid())
  206218. {
  206219. for (int y = image.getHeight(); --y >= 0;)
  206220. {
  206221. for (int x = image.getWidth(); --x >= 0;)
  206222. {
  206223. const float brightness = mask.getPixelAt (x, y).getBrightness();
  206224. if (brightness > 0.0f)
  206225. image.multiplyAlphaAt (x, y, 1.0f - brightness);
  206226. }
  206227. }
  206228. return image;
  206229. }
  206230. }
  206231. return Image();
  206232. }
  206233. static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY) throw()
  206234. {
  206235. WindowsBitmapImage* nativeBitmap = new WindowsBitmapImage (Image::ARGB, image.getWidth(), image.getHeight(), true);
  206236. Image bitmap (nativeBitmap);
  206237. {
  206238. Graphics g (bitmap);
  206239. g.drawImageAt (image, 0, 0);
  206240. }
  206241. HBITMAP mask = CreateBitmap (image.getWidth(), image.getHeight(), 1, 1, 0);
  206242. ICONINFO info;
  206243. info.fIcon = isIcon;
  206244. info.xHotspot = hotspotX;
  206245. info.yHotspot = hotspotY;
  206246. info.hbmMask = mask;
  206247. info.hbmColor = nativeBitmap->hBitmap;
  206248. HICON hi = CreateIconIndirect (&info);
  206249. DeleteObject (mask);
  206250. return hi;
  206251. }
  206252. const Image juce_createIconForFile (const File& file)
  206253. {
  206254. Image image;
  206255. WCHAR filename [1024];
  206256. file.getFullPathName().copyToUnicode (filename, 1023);
  206257. WORD iconNum = 0;
  206258. HICON icon = ExtractAssociatedIcon ((HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(),
  206259. filename, &iconNum);
  206260. if (icon != 0)
  206261. {
  206262. image = createImageFromHICON (icon);
  206263. DestroyIcon (icon);
  206264. }
  206265. return image;
  206266. }
  206267. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  206268. {
  206269. const int maxW = GetSystemMetrics (SM_CXCURSOR);
  206270. const int maxH = GetSystemMetrics (SM_CYCURSOR);
  206271. Image im (image);
  206272. if (im.getWidth() > maxW || im.getHeight() > maxH)
  206273. {
  206274. im = im.rescaled (maxW, maxH);
  206275. hotspotX = (hotspotX * maxW) / image.getWidth();
  206276. hotspotY = (hotspotY * maxH) / image.getHeight();
  206277. }
  206278. return createHICONFromImage (im, FALSE, hotspotX, hotspotY);
  206279. }
  206280. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard)
  206281. {
  206282. if (cursorHandle != 0 && ! isStandard)
  206283. DestroyCursor ((HCURSOR) cursorHandle);
  206284. }
  206285. void* MouseCursor::createStandardMouseCursor (const MouseCursor::StandardCursorType type)
  206286. {
  206287. LPCTSTR cursorName = IDC_ARROW;
  206288. switch (type)
  206289. {
  206290. case NormalCursor: break;
  206291. case NoCursor: return 0;
  206292. case WaitCursor: cursorName = IDC_WAIT; break;
  206293. case IBeamCursor: cursorName = IDC_IBEAM; break;
  206294. case PointingHandCursor: cursorName = MAKEINTRESOURCE(32649); break;
  206295. case CrosshairCursor: cursorName = IDC_CROSS; break;
  206296. case CopyingCursor: break; // can't seem to find one of these in the win32 list..
  206297. case LeftRightResizeCursor:
  206298. case LeftEdgeResizeCursor:
  206299. case RightEdgeResizeCursor: cursorName = IDC_SIZEWE; break;
  206300. case UpDownResizeCursor:
  206301. case TopEdgeResizeCursor:
  206302. case BottomEdgeResizeCursor: cursorName = IDC_SIZENS; break;
  206303. case TopLeftCornerResizeCursor:
  206304. case BottomRightCornerResizeCursor: cursorName = IDC_SIZENWSE; break;
  206305. case TopRightCornerResizeCursor:
  206306. case BottomLeftCornerResizeCursor: cursorName = IDC_SIZENESW; break;
  206307. case UpDownLeftRightResizeCursor: cursorName = IDC_SIZEALL; break;
  206308. case DraggingHandCursor:
  206309. {
  206310. static void* dragHandCursor = 0;
  206311. if (dragHandCursor == 0)
  206312. {
  206313. static const unsigned char dragHandData[] =
  206314. { 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,
  206315. 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,
  206316. 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 };
  206317. dragHandCursor = createMouseCursorFromImage (ImageFileFormat::loadFrom (dragHandData, sizeof (dragHandData)), 8, 7);
  206318. }
  206319. return dragHandCursor;
  206320. }
  206321. default:
  206322. jassertfalse; break;
  206323. }
  206324. HCURSOR cursorH = LoadCursor (0, cursorName);
  206325. if (cursorH == 0)
  206326. cursorH = LoadCursor (0, IDC_ARROW);
  206327. return cursorH;
  206328. }
  206329. void MouseCursor::showInWindow (ComponentPeer*) const
  206330. {
  206331. SetCursor ((HCURSOR) getHandle());
  206332. }
  206333. void MouseCursor::showInAllWindows() const
  206334. {
  206335. showInWindow (0);
  206336. }
  206337. class JuceDropSource : public ComBaseClassHelper <IDropSource>
  206338. {
  206339. public:
  206340. JuceDropSource() {}
  206341. ~JuceDropSource() {}
  206342. HRESULT __stdcall QueryContinueDrag (BOOL escapePressed, DWORD keys)
  206343. {
  206344. if (escapePressed)
  206345. return DRAGDROP_S_CANCEL;
  206346. if ((keys & (MK_LBUTTON | MK_RBUTTON)) == 0)
  206347. return DRAGDROP_S_DROP;
  206348. return S_OK;
  206349. }
  206350. HRESULT __stdcall GiveFeedback (DWORD)
  206351. {
  206352. return DRAGDROP_S_USEDEFAULTCURSORS;
  206353. }
  206354. };
  206355. class JuceEnumFormatEtc : public ComBaseClassHelper <IEnumFORMATETC>
  206356. {
  206357. public:
  206358. JuceEnumFormatEtc (const FORMATETC* const format_)
  206359. : format (format_),
  206360. index (0)
  206361. {
  206362. }
  206363. ~JuceEnumFormatEtc() {}
  206364. HRESULT __stdcall Clone (IEnumFORMATETC** result)
  206365. {
  206366. if (result == 0)
  206367. return E_POINTER;
  206368. JuceEnumFormatEtc* const newOne = new JuceEnumFormatEtc (format);
  206369. newOne->index = index;
  206370. *result = newOne;
  206371. return S_OK;
  206372. }
  206373. HRESULT __stdcall Next (ULONG celt, LPFORMATETC lpFormatEtc, ULONG* pceltFetched)
  206374. {
  206375. if (pceltFetched != 0)
  206376. *pceltFetched = 0;
  206377. else if (celt != 1)
  206378. return S_FALSE;
  206379. if (index == 0 && celt > 0 && lpFormatEtc != 0)
  206380. {
  206381. copyFormatEtc (lpFormatEtc [0], *format);
  206382. ++index;
  206383. if (pceltFetched != 0)
  206384. *pceltFetched = 1;
  206385. return S_OK;
  206386. }
  206387. return S_FALSE;
  206388. }
  206389. HRESULT __stdcall Skip (ULONG celt)
  206390. {
  206391. if (index + (int) celt >= 1)
  206392. return S_FALSE;
  206393. index += celt;
  206394. return S_OK;
  206395. }
  206396. HRESULT __stdcall Reset()
  206397. {
  206398. index = 0;
  206399. return S_OK;
  206400. }
  206401. private:
  206402. const FORMATETC* const format;
  206403. int index;
  206404. static void copyFormatEtc (FORMATETC& dest, const FORMATETC& source)
  206405. {
  206406. dest = source;
  206407. if (source.ptd != 0)
  206408. {
  206409. dest.ptd = (DVTARGETDEVICE*) CoTaskMemAlloc (sizeof (DVTARGETDEVICE));
  206410. *(dest.ptd) = *(source.ptd);
  206411. }
  206412. }
  206413. JuceEnumFormatEtc (const JuceEnumFormatEtc&);
  206414. JuceEnumFormatEtc& operator= (const JuceEnumFormatEtc&);
  206415. };
  206416. class JuceDataObject : public ComBaseClassHelper <IDataObject>
  206417. {
  206418. JuceDropSource* const dropSource;
  206419. const FORMATETC* const format;
  206420. const STGMEDIUM* const medium;
  206421. JuceDataObject (const JuceDataObject&);
  206422. JuceDataObject& operator= (const JuceDataObject&);
  206423. public:
  206424. JuceDataObject (JuceDropSource* const dropSource_,
  206425. const FORMATETC* const format_,
  206426. const STGMEDIUM* const medium_)
  206427. : dropSource (dropSource_),
  206428. format (format_),
  206429. medium (medium_)
  206430. {
  206431. }
  206432. virtual ~JuceDataObject()
  206433. {
  206434. jassert (refCount == 0);
  206435. }
  206436. HRESULT __stdcall GetData (FORMATETC __RPC_FAR* pFormatEtc, STGMEDIUM __RPC_FAR* pMedium)
  206437. {
  206438. if ((pFormatEtc->tymed & format->tymed) != 0
  206439. && pFormatEtc->cfFormat == format->cfFormat
  206440. && pFormatEtc->dwAspect == format->dwAspect)
  206441. {
  206442. pMedium->tymed = format->tymed;
  206443. pMedium->pUnkForRelease = 0;
  206444. if (format->tymed == TYMED_HGLOBAL)
  206445. {
  206446. const SIZE_T len = GlobalSize (medium->hGlobal);
  206447. void* const src = GlobalLock (medium->hGlobal);
  206448. void* const dst = GlobalAlloc (GMEM_FIXED, len);
  206449. memcpy (dst, src, len);
  206450. GlobalUnlock (medium->hGlobal);
  206451. pMedium->hGlobal = dst;
  206452. return S_OK;
  206453. }
  206454. }
  206455. return DV_E_FORMATETC;
  206456. }
  206457. HRESULT __stdcall QueryGetData (FORMATETC __RPC_FAR* f)
  206458. {
  206459. if (f == 0)
  206460. return E_INVALIDARG;
  206461. if (f->tymed == format->tymed
  206462. && f->cfFormat == format->cfFormat
  206463. && f->dwAspect == format->dwAspect)
  206464. return S_OK;
  206465. return DV_E_FORMATETC;
  206466. }
  206467. HRESULT __stdcall GetCanonicalFormatEtc (FORMATETC __RPC_FAR*, FORMATETC __RPC_FAR* pFormatEtcOut)
  206468. {
  206469. pFormatEtcOut->ptd = 0;
  206470. return E_NOTIMPL;
  206471. }
  206472. HRESULT __stdcall EnumFormatEtc (DWORD direction, IEnumFORMATETC __RPC_FAR *__RPC_FAR *result)
  206473. {
  206474. if (result == 0)
  206475. return E_POINTER;
  206476. if (direction == DATADIR_GET)
  206477. {
  206478. *result = new JuceEnumFormatEtc (format);
  206479. return S_OK;
  206480. }
  206481. *result = 0;
  206482. return E_NOTIMPL;
  206483. }
  206484. HRESULT __stdcall GetDataHere (FORMATETC __RPC_FAR*, STGMEDIUM __RPC_FAR*) { return DATA_E_FORMATETC; }
  206485. HRESULT __stdcall SetData (FORMATETC __RPC_FAR*, STGMEDIUM __RPC_FAR*, BOOL) { return E_NOTIMPL; }
  206486. HRESULT __stdcall DAdvise (FORMATETC __RPC_FAR*, DWORD, IAdviseSink __RPC_FAR*, DWORD __RPC_FAR*) { return OLE_E_ADVISENOTSUPPORTED; }
  206487. HRESULT __stdcall DUnadvise (DWORD) { return E_NOTIMPL; }
  206488. HRESULT __stdcall EnumDAdvise (IEnumSTATDATA __RPC_FAR *__RPC_FAR *) { return OLE_E_ADVISENOTSUPPORTED; }
  206489. };
  206490. static HDROP createHDrop (const StringArray& fileNames) throw()
  206491. {
  206492. int totalChars = 0;
  206493. for (int i = fileNames.size(); --i >= 0;)
  206494. totalChars += fileNames[i].length() + 1;
  206495. HDROP hDrop = (HDROP) GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT,
  206496. sizeof (DROPFILES)
  206497. + sizeof (WCHAR) * (totalChars + 2));
  206498. if (hDrop != 0)
  206499. {
  206500. LPDROPFILES pDropFiles = (LPDROPFILES) GlobalLock (hDrop);
  206501. pDropFiles->pFiles = sizeof (DROPFILES);
  206502. pDropFiles->fWide = true;
  206503. WCHAR* fname = (WCHAR*) (((char*) pDropFiles) + sizeof (DROPFILES));
  206504. for (int i = 0; i < fileNames.size(); ++i)
  206505. {
  206506. fileNames[i].copyToUnicode (fname, 2048);
  206507. fname += fileNames[i].length() + 1;
  206508. }
  206509. *fname = 0;
  206510. GlobalUnlock (hDrop);
  206511. }
  206512. return hDrop;
  206513. }
  206514. static bool performDragDrop (FORMATETC* const format, STGMEDIUM* const medium, const DWORD whatToDo) throw()
  206515. {
  206516. JuceDropSource* const source = new JuceDropSource();
  206517. JuceDataObject* const data = new JuceDataObject (source, format, medium);
  206518. DWORD effect;
  206519. const HRESULT res = DoDragDrop (data, source, whatToDo, &effect);
  206520. data->Release();
  206521. source->Release();
  206522. return res == DRAGDROP_S_DROP;
  206523. }
  206524. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMove)
  206525. {
  206526. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  206527. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  206528. medium.hGlobal = createHDrop (files);
  206529. return performDragDrop (&format, &medium, canMove ? (DROPEFFECT_COPY | DROPEFFECT_MOVE)
  206530. : DROPEFFECT_COPY);
  206531. }
  206532. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  206533. {
  206534. FORMATETC format = { CF_TEXT, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  206535. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  206536. const int numChars = text.length();
  206537. medium.hGlobal = GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT, (numChars + 2) * sizeof (WCHAR));
  206538. WCHAR* const data = static_cast <WCHAR*> (GlobalLock (medium.hGlobal));
  206539. text.copyToUnicode (data, numChars + 1);
  206540. format.cfFormat = CF_UNICODETEXT;
  206541. GlobalUnlock (medium.hGlobal);
  206542. return performDragDrop (&format, &medium, DROPEFFECT_COPY | DROPEFFECT_MOVE);
  206543. }
  206544. #endif
  206545. /*** End of inlined file: juce_win32_Windowing.cpp ***/
  206546. /*** Start of inlined file: juce_win32_Fonts.cpp ***/
  206547. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  206548. // compiled on its own).
  206549. #if JUCE_INCLUDED_FILE
  206550. static int CALLBACK wfontEnum2 (ENUMLOGFONTEXW* lpelfe,
  206551. NEWTEXTMETRICEXW*,
  206552. int type,
  206553. LPARAM lParam)
  206554. {
  206555. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  206556. {
  206557. const String fontName (lpelfe->elfLogFont.lfFaceName);
  206558. ((StringArray*) lParam)->addIfNotAlreadyThere (fontName.removeCharacters ("@"));
  206559. }
  206560. return 1;
  206561. }
  206562. static int CALLBACK wfontEnum1 (ENUMLOGFONTEXW* lpelfe,
  206563. NEWTEXTMETRICEXW*,
  206564. int type,
  206565. LPARAM lParam)
  206566. {
  206567. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  206568. {
  206569. LOGFONTW lf;
  206570. zerostruct (lf);
  206571. lf.lfWeight = FW_DONTCARE;
  206572. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  206573. lf.lfQuality = DEFAULT_QUALITY;
  206574. lf.lfCharSet = DEFAULT_CHARSET;
  206575. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  206576. lf.lfPitchAndFamily = FF_DONTCARE;
  206577. const String fontName (lpelfe->elfLogFont.lfFaceName);
  206578. fontName.copyToUnicode (lf.lfFaceName, LF_FACESIZE - 1);
  206579. HDC dc = CreateCompatibleDC (0);
  206580. EnumFontFamiliesEx (dc, &lf,
  206581. (FONTENUMPROCW) &wfontEnum2,
  206582. lParam, 0);
  206583. DeleteDC (dc);
  206584. }
  206585. return 1;
  206586. }
  206587. const StringArray Font::findAllTypefaceNames()
  206588. {
  206589. StringArray results;
  206590. HDC dc = CreateCompatibleDC (0);
  206591. {
  206592. LOGFONTW lf;
  206593. zerostruct (lf);
  206594. lf.lfWeight = FW_DONTCARE;
  206595. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  206596. lf.lfQuality = DEFAULT_QUALITY;
  206597. lf.lfCharSet = DEFAULT_CHARSET;
  206598. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  206599. lf.lfPitchAndFamily = FF_DONTCARE;
  206600. lf.lfFaceName[0] = 0;
  206601. EnumFontFamiliesEx (dc, &lf,
  206602. (FONTENUMPROCW) &wfontEnum1,
  206603. (LPARAM) &results, 0);
  206604. }
  206605. DeleteDC (dc);
  206606. results.sort (true);
  206607. return results;
  206608. }
  206609. extern bool juce_IsRunningInWine();
  206610. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  206611. {
  206612. if (juce_IsRunningInWine())
  206613. {
  206614. // If we're running in Wine, then use fonts that might be available on Linux..
  206615. defaultSans = "Bitstream Vera Sans";
  206616. defaultSerif = "Bitstream Vera Serif";
  206617. defaultFixed = "Bitstream Vera Sans Mono";
  206618. }
  206619. else
  206620. {
  206621. defaultSans = "Verdana";
  206622. defaultSerif = "Times";
  206623. defaultFixed = "Lucida Console";
  206624. }
  206625. }
  206626. class FontDCHolder : private DeletedAtShutdown
  206627. {
  206628. public:
  206629. FontDCHolder()
  206630. : dc (0), numKPs (0), size (0),
  206631. bold (false), italic (false)
  206632. {
  206633. }
  206634. ~FontDCHolder()
  206635. {
  206636. if (dc != 0)
  206637. {
  206638. DeleteDC (dc);
  206639. DeleteObject (fontH);
  206640. }
  206641. clearSingletonInstance();
  206642. }
  206643. juce_DeclareSingleton_SingleThreaded_Minimal (FontDCHolder);
  206644. HDC loadFont (const String& fontName_, const bool bold_, const bool italic_, const int size_)
  206645. {
  206646. if (fontName != fontName_ || bold != bold_ || italic != italic_ || size != size_)
  206647. {
  206648. fontName = fontName_;
  206649. bold = bold_;
  206650. italic = italic_;
  206651. size = size_;
  206652. if (dc != 0)
  206653. {
  206654. DeleteDC (dc);
  206655. DeleteObject (fontH);
  206656. kps.free();
  206657. }
  206658. fontH = 0;
  206659. dc = CreateCompatibleDC (0);
  206660. SetMapperFlags (dc, 0);
  206661. SetMapMode (dc, MM_TEXT);
  206662. LOGFONTW lfw;
  206663. zerostruct (lfw);
  206664. lfw.lfCharSet = DEFAULT_CHARSET;
  206665. lfw.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  206666. lfw.lfOutPrecision = OUT_OUTLINE_PRECIS;
  206667. lfw.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
  206668. lfw.lfQuality = PROOF_QUALITY;
  206669. lfw.lfItalic = (BYTE) (italic ? TRUE : FALSE);
  206670. lfw.lfWeight = bold ? FW_BOLD : FW_NORMAL;
  206671. fontName.copyToUnicode (lfw.lfFaceName, LF_FACESIZE - 1);
  206672. lfw.lfHeight = size > 0 ? size : -256;
  206673. HFONT standardSizedFont = CreateFontIndirect (&lfw);
  206674. if (standardSizedFont != 0)
  206675. {
  206676. if (SelectObject (dc, standardSizedFont) != 0)
  206677. {
  206678. fontH = standardSizedFont;
  206679. if (size == 0)
  206680. {
  206681. OUTLINETEXTMETRIC otm;
  206682. if (GetOutlineTextMetrics (dc, sizeof (otm), &otm) != 0)
  206683. {
  206684. lfw.lfHeight = -(int) otm.otmEMSquare;
  206685. fontH = CreateFontIndirect (&lfw);
  206686. SelectObject (dc, fontH);
  206687. DeleteObject (standardSizedFont);
  206688. }
  206689. }
  206690. }
  206691. else
  206692. {
  206693. jassertfalse;
  206694. }
  206695. }
  206696. else
  206697. {
  206698. jassertfalse;
  206699. }
  206700. }
  206701. return dc;
  206702. }
  206703. KERNINGPAIR* getKerningPairs (int& numKPs_)
  206704. {
  206705. if (kps == 0)
  206706. {
  206707. numKPs = GetKerningPairs (dc, 0, 0);
  206708. kps.calloc (numKPs);
  206709. GetKerningPairs (dc, numKPs, kps);
  206710. }
  206711. numKPs_ = numKPs;
  206712. return kps;
  206713. }
  206714. private:
  206715. HFONT fontH;
  206716. HDC dc;
  206717. String fontName;
  206718. HeapBlock <KERNINGPAIR> kps;
  206719. int numKPs, size;
  206720. bool bold, italic;
  206721. FontDCHolder (const FontDCHolder&);
  206722. FontDCHolder& operator= (const FontDCHolder&);
  206723. };
  206724. juce_ImplementSingleton_SingleThreaded (FontDCHolder);
  206725. class WindowsTypeface : public CustomTypeface
  206726. {
  206727. public:
  206728. WindowsTypeface (const Font& font)
  206729. {
  206730. HDC dc = FontDCHolder::getInstance()->loadFont (font.getTypefaceName(),
  206731. font.isBold(), font.isItalic(), 0);
  206732. TEXTMETRIC tm;
  206733. tm.tmAscent = tm.tmHeight = 1;
  206734. tm.tmDefaultChar = 0;
  206735. GetTextMetrics (dc, &tm);
  206736. setCharacteristics (font.getTypefaceName(),
  206737. tm.tmAscent / (float) tm.tmHeight,
  206738. font.isBold(), font.isItalic(),
  206739. tm.tmDefaultChar);
  206740. }
  206741. bool loadGlyphIfPossible (juce_wchar character)
  206742. {
  206743. HDC dc = FontDCHolder::getInstance()->loadFont (name, isBold, isItalic, 0);
  206744. GLYPHMETRICS gm;
  206745. {
  206746. const WCHAR charToTest[] = { (WCHAR) character, 0 };
  206747. WORD index = 0;
  206748. if (GetGlyphIndices (dc, charToTest, 1, &index, GGI_MARK_NONEXISTING_GLYPHS) != GDI_ERROR
  206749. && index == 0xffff)
  206750. {
  206751. return false;
  206752. }
  206753. }
  206754. Path glyphPath;
  206755. TEXTMETRIC tm;
  206756. if (! GetTextMetrics (dc, &tm))
  206757. {
  206758. addGlyph (character, glyphPath, 0);
  206759. return true;
  206760. }
  206761. const float height = (float) tm.tmHeight;
  206762. static const MAT2 identityMatrix = { { 0, 1 }, { 0, 0 }, { 0, 0 }, { 0, 1 } };
  206763. const int bufSize = GetGlyphOutline (dc, character, GGO_NATIVE,
  206764. &gm, 0, 0, &identityMatrix);
  206765. if (bufSize > 0)
  206766. {
  206767. HeapBlock<char> data (bufSize);
  206768. GetGlyphOutline (dc, character, GGO_NATIVE, &gm,
  206769. bufSize, data, &identityMatrix);
  206770. const TTPOLYGONHEADER* pheader = reinterpret_cast<TTPOLYGONHEADER*> (data.getData());
  206771. const float scaleX = 1.0f / height;
  206772. const float scaleY = -1.0f / height;
  206773. while ((char*) pheader < data + bufSize)
  206774. {
  206775. float x = scaleX * pheader->pfxStart.x.value;
  206776. float y = scaleY * pheader->pfxStart.y.value;
  206777. glyphPath.startNewSubPath (x, y);
  206778. const TTPOLYCURVE* curve = (const TTPOLYCURVE*) ((const char*) pheader + sizeof (TTPOLYGONHEADER));
  206779. const char* const curveEnd = ((const char*) pheader) + pheader->cb;
  206780. while ((const char*) curve < curveEnd)
  206781. {
  206782. if (curve->wType == TT_PRIM_LINE)
  206783. {
  206784. for (int i = 0; i < curve->cpfx; ++i)
  206785. {
  206786. x = scaleX * curve->apfx[i].x.value;
  206787. y = scaleY * curve->apfx[i].y.value;
  206788. glyphPath.lineTo (x, y);
  206789. }
  206790. }
  206791. else if (curve->wType == TT_PRIM_QSPLINE)
  206792. {
  206793. for (int i = 0; i < curve->cpfx - 1; ++i)
  206794. {
  206795. const float x2 = scaleX * curve->apfx[i].x.value;
  206796. const float y2 = scaleY * curve->apfx[i].y.value;
  206797. float x3, y3;
  206798. if (i < curve->cpfx - 2)
  206799. {
  206800. x3 = 0.5f * (x2 + scaleX * curve->apfx[i + 1].x.value);
  206801. y3 = 0.5f * (y2 + scaleY * curve->apfx[i + 1].y.value);
  206802. }
  206803. else
  206804. {
  206805. x3 = scaleX * curve->apfx[i + 1].x.value;
  206806. y3 = scaleY * curve->apfx[i + 1].y.value;
  206807. }
  206808. glyphPath.quadraticTo (x2, y2, x3, y3);
  206809. x = x3;
  206810. y = y3;
  206811. }
  206812. }
  206813. curve = (const TTPOLYCURVE*) &(curve->apfx [curve->cpfx]);
  206814. }
  206815. pheader = (const TTPOLYGONHEADER*) curve;
  206816. glyphPath.closeSubPath();
  206817. }
  206818. }
  206819. addGlyph (character, glyphPath, gm.gmCellIncX / height);
  206820. int numKPs;
  206821. const KERNINGPAIR* const kps = FontDCHolder::getInstance()->getKerningPairs (numKPs);
  206822. for (int i = 0; i < numKPs; ++i)
  206823. {
  206824. if (kps[i].wFirst == character)
  206825. addKerningPair (kps[i].wFirst, kps[i].wSecond,
  206826. kps[i].iKernAmount / height);
  206827. }
  206828. return true;
  206829. }
  206830. juce_UseDebuggingNewOperator
  206831. };
  206832. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  206833. {
  206834. return new WindowsTypeface (font);
  206835. }
  206836. #endif
  206837. /*** End of inlined file: juce_win32_Fonts.cpp ***/
  206838. /*** Start of inlined file: juce_win32_FileChooser.cpp ***/
  206839. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  206840. // compiled on its own).
  206841. #if JUCE_INCLUDED_FILE
  206842. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw();
  206843. namespace FileChooserHelpers
  206844. {
  206845. static const void* defaultDirPath = 0;
  206846. static String returnedString; // need this to get non-existent pathnames from the directory chooser
  206847. static Component* currentExtraFileWin = 0;
  206848. static bool areThereAnyAlwaysOnTopWindows()
  206849. {
  206850. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  206851. {
  206852. Component* c = Desktop::getInstance().getComponent (i);
  206853. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  206854. return true;
  206855. }
  206856. return false;
  206857. }
  206858. static int CALLBACK browseCallbackProc (HWND hWnd, UINT msg, LPARAM lParam, LPARAM /*lpData*/)
  206859. {
  206860. if (msg == BFFM_INITIALIZED)
  206861. SendMessage (hWnd, BFFM_SETSELECTIONW, TRUE, (LPARAM) defaultDirPath);
  206862. else if (msg == BFFM_VALIDATEFAILEDW)
  206863. returnedString = (LPCWSTR) lParam;
  206864. else if (msg == BFFM_VALIDATEFAILEDA)
  206865. returnedString = (const char*) lParam;
  206866. return 0;
  206867. }
  206868. static UINT_PTR CALLBACK openCallback (HWND hdlg, UINT uiMsg, WPARAM /*wParam*/, LPARAM lParam)
  206869. {
  206870. if (currentExtraFileWin != 0)
  206871. {
  206872. if (uiMsg == WM_INITDIALOG)
  206873. {
  206874. HWND dialogH = GetParent (hdlg);
  206875. jassert (dialogH != 0);
  206876. if (dialogH == 0)
  206877. dialogH = hdlg;
  206878. RECT r, cr;
  206879. GetWindowRect (dialogH, &r);
  206880. GetClientRect (dialogH, &cr);
  206881. SetWindowPos (dialogH, 0,
  206882. r.left, r.top,
  206883. currentExtraFileWin->getWidth() + jmax (150, (int) (r.right - r.left)),
  206884. jmax (150, (int) (r.bottom - r.top)),
  206885. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  206886. currentExtraFileWin->setBounds (cr.right, cr.top, currentExtraFileWin->getWidth(), cr.bottom - cr.top);
  206887. currentExtraFileWin->getChildComponent(0)->setBounds (0, 0, currentExtraFileWin->getWidth(), currentExtraFileWin->getHeight());
  206888. SetParent ((HWND) currentExtraFileWin->getWindowHandle(), (HWND) dialogH);
  206889. juce_setWindowStyleBit ((HWND)currentExtraFileWin->getWindowHandle(), GWL_STYLE, WS_CHILD, (dialogH != 0));
  206890. juce_setWindowStyleBit ((HWND)currentExtraFileWin->getWindowHandle(), GWL_STYLE, WS_POPUP, (dialogH == 0));
  206891. }
  206892. else if (uiMsg == WM_NOTIFY)
  206893. {
  206894. LPOFNOTIFY ofn = (LPOFNOTIFY) lParam;
  206895. if (ofn->hdr.code == CDN_SELCHANGE)
  206896. {
  206897. FilePreviewComponent* comp = (FilePreviewComponent*) currentExtraFileWin->getChildComponent(0);
  206898. if (comp != 0)
  206899. {
  206900. TCHAR path [MAX_PATH * 2];
  206901. path[0] = 0;
  206902. CommDlg_OpenSave_GetFilePath (GetParent (hdlg), (LPARAM) &path, MAX_PATH);
  206903. const String fn ((const WCHAR*) path);
  206904. comp->selectedFileChanged (File (fn));
  206905. }
  206906. }
  206907. }
  206908. }
  206909. return 0;
  206910. }
  206911. class FPComponentHolder : public Component
  206912. {
  206913. public:
  206914. FPComponentHolder()
  206915. {
  206916. setVisible (true);
  206917. setOpaque (true);
  206918. }
  206919. ~FPComponentHolder()
  206920. {
  206921. }
  206922. void paint (Graphics& g)
  206923. {
  206924. g.fillAll (Colours::lightgrey);
  206925. }
  206926. private:
  206927. FPComponentHolder (const FPComponentHolder&);
  206928. FPComponentHolder& operator= (const FPComponentHolder&);
  206929. };
  206930. }
  206931. void FileChooser::showPlatformDialog (Array<File>& results,
  206932. const String& title,
  206933. const File& currentFileOrDirectory,
  206934. const String& filter,
  206935. bool selectsDirectory,
  206936. bool /*selectsFiles*/,
  206937. bool isSaveDialogue,
  206938. bool warnAboutOverwritingExistingFiles,
  206939. bool selectMultipleFiles,
  206940. FilePreviewComponent* extraInfoComponent)
  206941. {
  206942. using namespace FileChooserHelpers;
  206943. const int numCharsAvailable = 32768;
  206944. MemoryBlock filenameSpace ((numCharsAvailable + 1) * sizeof (WCHAR), true);
  206945. WCHAR* const fname = (WCHAR*) filenameSpace.getData();
  206946. int fnameIdx = 0;
  206947. JUCE_TRY
  206948. {
  206949. // use a modal window as the parent for this dialog box
  206950. // to block input from other app windows
  206951. const Rectangle<int> mainMon (Desktop::getInstance().getMainMonitorArea());
  206952. Component w (String::empty);
  206953. w.setBounds (mainMon.getX() + mainMon.getWidth() / 4,
  206954. mainMon.getY() + mainMon.getHeight() / 4,
  206955. 0, 0);
  206956. w.setOpaque (true);
  206957. w.setAlwaysOnTop (areThereAnyAlwaysOnTopWindows());
  206958. w.addToDesktop (0);
  206959. if (extraInfoComponent == 0)
  206960. w.enterModalState();
  206961. String initialDir;
  206962. if (currentFileOrDirectory.isDirectory())
  206963. {
  206964. initialDir = currentFileOrDirectory.getFullPathName();
  206965. }
  206966. else
  206967. {
  206968. currentFileOrDirectory.getFileName().copyToUnicode (fname, numCharsAvailable);
  206969. initialDir = currentFileOrDirectory.getParentDirectory().getFullPathName();
  206970. }
  206971. if (currentExtraFileWin->isValidComponent())
  206972. {
  206973. jassertfalse;
  206974. return;
  206975. }
  206976. if (selectsDirectory)
  206977. {
  206978. LPITEMIDLIST list = 0;
  206979. filenameSpace.fillWith (0);
  206980. {
  206981. BROWSEINFO bi;
  206982. zerostruct (bi);
  206983. bi.hwndOwner = (HWND) w.getWindowHandle();
  206984. bi.pszDisplayName = fname;
  206985. bi.lpszTitle = title;
  206986. bi.lpfn = browseCallbackProc;
  206987. #ifdef BIF_USENEWUI
  206988. bi.ulFlags = BIF_USENEWUI | BIF_VALIDATE;
  206989. #else
  206990. bi.ulFlags = 0x50;
  206991. #endif
  206992. defaultDirPath = (const WCHAR*) initialDir;
  206993. list = SHBrowseForFolder (&bi);
  206994. if (! SHGetPathFromIDListW (list, fname))
  206995. {
  206996. fname[0] = 0;
  206997. returnedString = String::empty;
  206998. }
  206999. }
  207000. LPMALLOC al;
  207001. if (list != 0 && SUCCEEDED (SHGetMalloc (&al)))
  207002. al->Free (list);
  207003. defaultDirPath = 0;
  207004. if (returnedString.isNotEmpty())
  207005. {
  207006. const String stringFName (fname);
  207007. results.add (File (stringFName).getSiblingFile (returnedString));
  207008. returnedString = String::empty;
  207009. return;
  207010. }
  207011. }
  207012. else
  207013. {
  207014. DWORD flags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR | OFN_HIDEREADONLY;
  207015. if (warnAboutOverwritingExistingFiles)
  207016. flags |= OFN_OVERWRITEPROMPT;
  207017. if (selectMultipleFiles)
  207018. flags |= OFN_ALLOWMULTISELECT;
  207019. if (extraInfoComponent != 0)
  207020. {
  207021. flags |= OFN_ENABLEHOOK;
  207022. currentExtraFileWin = new FPComponentHolder();
  207023. currentExtraFileWin->addAndMakeVisible (extraInfoComponent);
  207024. currentExtraFileWin->setSize (jlimit (20, 800, extraInfoComponent->getWidth()),
  207025. extraInfoComponent->getHeight());
  207026. currentExtraFileWin->addToDesktop (0);
  207027. currentExtraFileWin->enterModalState();
  207028. }
  207029. {
  207030. WCHAR filters [1024];
  207031. zeromem (filters, sizeof (filters));
  207032. filter.copyToUnicode (filters, 1024);
  207033. filter.copyToUnicode (filters + filter.length() + 1,
  207034. 1022 - filter.length());
  207035. OPENFILENAMEW of;
  207036. zerostruct (of);
  207037. #ifdef OPENFILENAME_SIZE_VERSION_400W
  207038. of.lStructSize = OPENFILENAME_SIZE_VERSION_400W;
  207039. #else
  207040. of.lStructSize = sizeof (of);
  207041. #endif
  207042. of.hwndOwner = (HWND) w.getWindowHandle();
  207043. of.lpstrFilter = filters;
  207044. of.nFilterIndex = 1;
  207045. of.lpstrFile = fname;
  207046. of.nMaxFile = numCharsAvailable;
  207047. of.lpstrInitialDir = initialDir;
  207048. of.lpstrTitle = title;
  207049. of.Flags = flags;
  207050. if (extraInfoComponent != 0)
  207051. of.lpfnHook = &openCallback;
  207052. if (isSaveDialogue)
  207053. {
  207054. if (! GetSaveFileName (&of))
  207055. fname[0] = 0;
  207056. else
  207057. fnameIdx = of.nFileOffset;
  207058. }
  207059. else
  207060. {
  207061. if (! GetOpenFileName (&of))
  207062. fname[0] = 0;
  207063. else
  207064. fnameIdx = of.nFileOffset;
  207065. }
  207066. }
  207067. }
  207068. }
  207069. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  207070. catch (...)
  207071. {
  207072. fname[0] = 0;
  207073. }
  207074. #endif
  207075. deleteAndZero (currentExtraFileWin);
  207076. const WCHAR* const files = fname;
  207077. if (selectMultipleFiles && fnameIdx > 0 && files [fnameIdx - 1] == 0)
  207078. {
  207079. const WCHAR* filename = files + fnameIdx;
  207080. while (*filename != 0)
  207081. {
  207082. const String filepath (String (files) + "\\" + String (filename));
  207083. results.add (File (filepath));
  207084. filename += CharacterFunctions::length (filename) + 1;
  207085. }
  207086. }
  207087. else if (files[0] != 0)
  207088. {
  207089. results.add (File (files));
  207090. }
  207091. }
  207092. #endif
  207093. /*** End of inlined file: juce_win32_FileChooser.cpp ***/
  207094. /*** Start of inlined file: juce_win32_Misc.cpp ***/
  207095. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  207096. // compiled on its own).
  207097. #if JUCE_INCLUDED_FILE
  207098. void SystemClipboard::copyTextToClipboard (const String& text)
  207099. {
  207100. if (OpenClipboard (0) != 0)
  207101. {
  207102. if (EmptyClipboard() != 0)
  207103. {
  207104. const int len = text.length();
  207105. if (len > 0)
  207106. {
  207107. HGLOBAL bufH = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE,
  207108. (len + 1) * sizeof (wchar_t));
  207109. if (bufH != 0)
  207110. {
  207111. WCHAR* const data = static_cast <WCHAR*> (GlobalLock (bufH));
  207112. text.copyToUnicode (data, len);
  207113. GlobalUnlock (bufH);
  207114. SetClipboardData (CF_UNICODETEXT, bufH);
  207115. }
  207116. }
  207117. }
  207118. CloseClipboard();
  207119. }
  207120. }
  207121. const String SystemClipboard::getTextFromClipboard()
  207122. {
  207123. String result;
  207124. if (OpenClipboard (0) != 0)
  207125. {
  207126. HANDLE bufH = GetClipboardData (CF_UNICODETEXT);
  207127. if (bufH != 0)
  207128. {
  207129. const wchar_t* const data = (const wchar_t*) GlobalLock (bufH);
  207130. if (data != 0)
  207131. {
  207132. result = String (data, (int) (GlobalSize (bufH) / sizeof (wchar_t)));
  207133. GlobalUnlock (bufH);
  207134. }
  207135. }
  207136. CloseClipboard();
  207137. }
  207138. return result;
  207139. }
  207140. #endif
  207141. /*** End of inlined file: juce_win32_Misc.cpp ***/
  207142. /*** Start of inlined file: juce_win32_ActiveXComponent.cpp ***/
  207143. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  207144. // compiled on its own).
  207145. #if JUCE_INCLUDED_FILE
  207146. namespace ActiveXHelpers
  207147. {
  207148. class JuceIStorage : public ComBaseClassHelper <IStorage>
  207149. {
  207150. public:
  207151. JuceIStorage() {}
  207152. ~JuceIStorage() {}
  207153. HRESULT __stdcall CreateStream (const WCHAR*, DWORD, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  207154. HRESULT __stdcall OpenStream (const WCHAR*, void*, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  207155. HRESULT __stdcall CreateStorage (const WCHAR*, DWORD, DWORD, DWORD, IStorage**) { return E_NOTIMPL; }
  207156. HRESULT __stdcall OpenStorage (const WCHAR*, IStorage*, DWORD, SNB, DWORD, IStorage**) { return E_NOTIMPL; }
  207157. HRESULT __stdcall CopyTo (DWORD, IID const*, SNB, IStorage*) { return E_NOTIMPL; }
  207158. HRESULT __stdcall MoveElementTo (const OLECHAR*,IStorage*, const OLECHAR*, DWORD) { return E_NOTIMPL; }
  207159. HRESULT __stdcall Commit (DWORD) { return E_NOTIMPL; }
  207160. HRESULT __stdcall Revert() { return E_NOTIMPL; }
  207161. HRESULT __stdcall EnumElements (DWORD, void*, DWORD, IEnumSTATSTG**) { return E_NOTIMPL; }
  207162. HRESULT __stdcall DestroyElement (const OLECHAR*) { return E_NOTIMPL; }
  207163. HRESULT __stdcall RenameElement (const WCHAR*, const WCHAR*) { return E_NOTIMPL; }
  207164. HRESULT __stdcall SetElementTimes (const WCHAR*, FILETIME const*, FILETIME const*, FILETIME const*) { return E_NOTIMPL; }
  207165. HRESULT __stdcall SetClass (REFCLSID) { return S_OK; }
  207166. HRESULT __stdcall SetStateBits (DWORD, DWORD) { return E_NOTIMPL; }
  207167. HRESULT __stdcall Stat (STATSTG*, DWORD) { return E_NOTIMPL; }
  207168. juce_UseDebuggingNewOperator
  207169. };
  207170. class JuceOleInPlaceFrame : public ComBaseClassHelper <IOleInPlaceFrame>
  207171. {
  207172. HWND window;
  207173. public:
  207174. JuceOleInPlaceFrame (HWND window_) : window (window_) {}
  207175. ~JuceOleInPlaceFrame() {}
  207176. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  207177. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  207178. HRESULT __stdcall GetBorder (LPRECT) { return E_NOTIMPL; }
  207179. HRESULT __stdcall RequestBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  207180. HRESULT __stdcall SetBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  207181. HRESULT __stdcall SetActiveObject (IOleInPlaceActiveObject*, LPCOLESTR) { return S_OK; }
  207182. HRESULT __stdcall InsertMenus (HMENU, LPOLEMENUGROUPWIDTHS) { return E_NOTIMPL; }
  207183. HRESULT __stdcall SetMenu (HMENU, HOLEMENU, HWND) { return S_OK; }
  207184. HRESULT __stdcall RemoveMenus (HMENU) { return E_NOTIMPL; }
  207185. HRESULT __stdcall SetStatusText (LPCOLESTR) { return S_OK; }
  207186. HRESULT __stdcall EnableModeless (BOOL) { return S_OK; }
  207187. HRESULT __stdcall TranslateAccelerator(LPMSG, WORD) { return E_NOTIMPL; }
  207188. juce_UseDebuggingNewOperator
  207189. };
  207190. class JuceIOleInPlaceSite : public ComBaseClassHelper <IOleInPlaceSite>
  207191. {
  207192. HWND window;
  207193. JuceOleInPlaceFrame* frame;
  207194. public:
  207195. JuceIOleInPlaceSite (HWND window_)
  207196. : window (window_),
  207197. frame (new JuceOleInPlaceFrame (window))
  207198. {}
  207199. ~JuceIOleInPlaceSite()
  207200. {
  207201. frame->Release();
  207202. }
  207203. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  207204. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  207205. HRESULT __stdcall CanInPlaceActivate() { return S_OK; }
  207206. HRESULT __stdcall OnInPlaceActivate() { return S_OK; }
  207207. HRESULT __stdcall OnUIActivate() { return S_OK; }
  207208. HRESULT __stdcall GetWindowContext (LPOLEINPLACEFRAME* lplpFrame, LPOLEINPLACEUIWINDOW* lplpDoc, LPRECT, LPRECT, LPOLEINPLACEFRAMEINFO lpFrameInfo)
  207209. {
  207210. *lplpFrame = frame;
  207211. *lplpDoc = 0;
  207212. lpFrameInfo->fMDIApp = FALSE;
  207213. lpFrameInfo->hwndFrame = window;
  207214. lpFrameInfo->haccel = 0;
  207215. lpFrameInfo->cAccelEntries = 0;
  207216. return S_OK;
  207217. }
  207218. HRESULT __stdcall Scroll (SIZE) { return E_NOTIMPL; }
  207219. HRESULT __stdcall OnUIDeactivate (BOOL) { return S_OK; }
  207220. HRESULT __stdcall OnInPlaceDeactivate() { return S_OK; }
  207221. HRESULT __stdcall DiscardUndoState() { return E_NOTIMPL; }
  207222. HRESULT __stdcall DeactivateAndUndo() { return E_NOTIMPL; }
  207223. HRESULT __stdcall OnPosRectChange (LPCRECT) { return S_OK; }
  207224. juce_UseDebuggingNewOperator
  207225. };
  207226. class JuceIOleClientSite : public ComBaseClassHelper <IOleClientSite>
  207227. {
  207228. JuceIOleInPlaceSite* inplaceSite;
  207229. public:
  207230. JuceIOleClientSite (HWND window)
  207231. : inplaceSite (new JuceIOleInPlaceSite (window))
  207232. {}
  207233. ~JuceIOleClientSite()
  207234. {
  207235. inplaceSite->Release();
  207236. }
  207237. HRESULT __stdcall QueryInterface (REFIID type, void __RPC_FAR* __RPC_FAR* result)
  207238. {
  207239. if (type == IID_IOleInPlaceSite)
  207240. {
  207241. inplaceSite->AddRef();
  207242. *result = static_cast <IOleInPlaceSite*> (inplaceSite);
  207243. return S_OK;
  207244. }
  207245. return ComBaseClassHelper <IOleClientSite>::QueryInterface (type, result);
  207246. }
  207247. HRESULT __stdcall SaveObject() { return E_NOTIMPL; }
  207248. HRESULT __stdcall GetMoniker (DWORD, DWORD, IMoniker**) { return E_NOTIMPL; }
  207249. HRESULT __stdcall GetContainer (LPOLECONTAINER* ppContainer) { *ppContainer = 0; return E_NOINTERFACE; }
  207250. HRESULT __stdcall ShowObject() { return S_OK; }
  207251. HRESULT __stdcall OnShowWindow (BOOL) { return E_NOTIMPL; }
  207252. HRESULT __stdcall RequestNewObjectLayout() { return E_NOTIMPL; }
  207253. juce_UseDebuggingNewOperator
  207254. };
  207255. static Array<ActiveXControlComponent*> activeXComps;
  207256. static HWND getHWND (const ActiveXControlComponent* const component)
  207257. {
  207258. HWND hwnd = 0;
  207259. const IID iid = IID_IOleWindow;
  207260. IOleWindow* const window = (IOleWindow*) component->queryInterface (&iid);
  207261. if (window != 0)
  207262. {
  207263. window->GetWindow (&hwnd);
  207264. window->Release();
  207265. }
  207266. return hwnd;
  207267. }
  207268. static void offerActiveXMouseEventToPeer (ComponentPeer* const peer, HWND hwnd, UINT message, LPARAM lParam)
  207269. {
  207270. RECT activeXRect, peerRect;
  207271. GetWindowRect (hwnd, &activeXRect);
  207272. GetWindowRect ((HWND) peer->getNativeHandle(), &peerRect);
  207273. const Point<int> mousePos (GET_X_LPARAM (lParam) + activeXRect.left - peerRect.left,
  207274. GET_Y_LPARAM (lParam) + activeXRect.top - peerRect.top);
  207275. const int64 mouseEventTime = Win32ComponentPeer::getMouseEventTime();
  207276. ModifierKeys::getCurrentModifiersRealtime(); // to update the mouse button flags
  207277. switch (message)
  207278. {
  207279. case WM_MOUSEMOVE:
  207280. case WM_LBUTTONDOWN:
  207281. case WM_MBUTTONDOWN:
  207282. case WM_RBUTTONDOWN:
  207283. case WM_LBUTTONUP:
  207284. case WM_MBUTTONUP:
  207285. case WM_RBUTTONUP:
  207286. peer->handleMouseEvent (0, mousePos, Win32ComponentPeer::currentModifiers, mouseEventTime);
  207287. break;
  207288. default:
  207289. break;
  207290. }
  207291. }
  207292. }
  207293. class ActiveXControlComponent::Pimpl : public ComponentMovementWatcher
  207294. {
  207295. ActiveXControlComponent* const owner;
  207296. bool wasShowing;
  207297. public:
  207298. HWND controlHWND;
  207299. IStorage* storage;
  207300. IOleClientSite* clientSite;
  207301. IOleObject* control;
  207302. Pimpl (HWND hwnd, ActiveXControlComponent* const owner_)
  207303. : ComponentMovementWatcher (owner_),
  207304. owner (owner_),
  207305. wasShowing (owner_ != 0 && owner_->isShowing()),
  207306. controlHWND (0),
  207307. storage (new ActiveXHelpers::JuceIStorage()),
  207308. clientSite (new ActiveXHelpers::JuceIOleClientSite (hwnd)),
  207309. control (0)
  207310. {
  207311. }
  207312. ~Pimpl()
  207313. {
  207314. if (control != 0)
  207315. {
  207316. control->Close (OLECLOSE_NOSAVE);
  207317. control->Release();
  207318. }
  207319. clientSite->Release();
  207320. storage->Release();
  207321. }
  207322. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  207323. {
  207324. Component* const topComp = owner->getTopLevelComponent();
  207325. if (topComp->getPeer() != 0)
  207326. {
  207327. const Point<int> pos (owner->relativePositionToOtherComponent (topComp, Point<int>()));
  207328. owner->setControlBounds (Rectangle<int> (pos.getX(), pos.getY(), owner->getWidth(), owner->getHeight()));
  207329. }
  207330. }
  207331. void componentPeerChanged()
  207332. {
  207333. const bool isShowingNow = owner->isShowing();
  207334. if (wasShowing != isShowingNow)
  207335. {
  207336. wasShowing = isShowingNow;
  207337. owner->setControlVisible (isShowingNow);
  207338. }
  207339. componentMovedOrResized (true, true);
  207340. }
  207341. void componentVisibilityChanged (Component&)
  207342. {
  207343. componentPeerChanged();
  207344. }
  207345. // intercepts events going to an activeX control, so we can sneakily use the mouse events
  207346. static LRESULT CALLBACK activeXHookWndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
  207347. {
  207348. for (int i = ActiveXHelpers::activeXComps.size(); --i >= 0;)
  207349. {
  207350. const ActiveXControlComponent* const ax = ActiveXHelpers::activeXComps.getUnchecked(i);
  207351. if (ax->control != 0 && ax->control->controlHWND == hwnd)
  207352. {
  207353. switch (message)
  207354. {
  207355. case WM_MOUSEMOVE:
  207356. case WM_LBUTTONDOWN:
  207357. case WM_MBUTTONDOWN:
  207358. case WM_RBUTTONDOWN:
  207359. case WM_LBUTTONUP:
  207360. case WM_MBUTTONUP:
  207361. case WM_RBUTTONUP:
  207362. case WM_LBUTTONDBLCLK:
  207363. case WM_MBUTTONDBLCLK:
  207364. case WM_RBUTTONDBLCLK:
  207365. if (ax->isShowing())
  207366. {
  207367. ComponentPeer* const peer = ax->getPeer();
  207368. if (peer != 0)
  207369. {
  207370. ActiveXHelpers::offerActiveXMouseEventToPeer (peer, hwnd, message, lParam);
  207371. if (! ax->areMouseEventsAllowed())
  207372. return 0;
  207373. }
  207374. }
  207375. break;
  207376. default:
  207377. break;
  207378. }
  207379. return CallWindowProc ((WNDPROC) ax->originalWndProc, hwnd, message, wParam, lParam);
  207380. }
  207381. }
  207382. return DefWindowProc (hwnd, message, wParam, lParam);
  207383. }
  207384. };
  207385. ActiveXControlComponent::ActiveXControlComponent()
  207386. : originalWndProc (0),
  207387. mouseEventsAllowed (true)
  207388. {
  207389. ActiveXHelpers::activeXComps.add (this);
  207390. }
  207391. ActiveXControlComponent::~ActiveXControlComponent()
  207392. {
  207393. deleteControl();
  207394. ActiveXHelpers::activeXComps.removeValue (this);
  207395. }
  207396. void ActiveXControlComponent::paint (Graphics& g)
  207397. {
  207398. if (control == 0)
  207399. g.fillAll (Colours::lightgrey);
  207400. }
  207401. bool ActiveXControlComponent::createControl (const void* controlIID)
  207402. {
  207403. deleteControl();
  207404. ComponentPeer* const peer = getPeer();
  207405. // the component must have already been added to a real window when you call this!
  207406. jassert (dynamic_cast <Win32ComponentPeer*> (peer) != 0);
  207407. if (dynamic_cast <Win32ComponentPeer*> (peer) != 0)
  207408. {
  207409. const Point<int> pos (relativePositionToOtherComponent (getTopLevelComponent(), Point<int>()));
  207410. HWND hwnd = (HWND) peer->getNativeHandle();
  207411. ScopedPointer<Pimpl> newControl (new Pimpl (hwnd, this));
  207412. HRESULT hr;
  207413. if ((hr = OleCreate (*(const IID*) controlIID, IID_IOleObject, 1 /*OLERENDER_DRAW*/, 0,
  207414. newControl->clientSite, newControl->storage,
  207415. (void**) &(newControl->control))) == S_OK)
  207416. {
  207417. newControl->control->SetHostNames (L"Juce", 0);
  207418. if (OleSetContainedObject (newControl->control, TRUE) == S_OK)
  207419. {
  207420. RECT rect;
  207421. rect.left = pos.getX();
  207422. rect.top = pos.getY();
  207423. rect.right = pos.getX() + getWidth();
  207424. rect.bottom = pos.getY() + getHeight();
  207425. if (newControl->control->DoVerb (OLEIVERB_SHOW, 0, newControl->clientSite, 0, hwnd, &rect) == S_OK)
  207426. {
  207427. control = newControl;
  207428. setControlBounds (Rectangle<int> (pos.getX(), pos.getY(), getWidth(), getHeight()));
  207429. control->controlHWND = ActiveXHelpers::getHWND (this);
  207430. if (control->controlHWND != 0)
  207431. {
  207432. originalWndProc = (void*) (pointer_sized_int) GetWindowLongPtr ((HWND) control->controlHWND, GWLP_WNDPROC);
  207433. SetWindowLongPtr ((HWND) control->controlHWND, GWLP_WNDPROC, (LONG_PTR) Pimpl::activeXHookWndProc);
  207434. }
  207435. return true;
  207436. }
  207437. }
  207438. }
  207439. }
  207440. return false;
  207441. }
  207442. void ActiveXControlComponent::deleteControl()
  207443. {
  207444. control = 0;
  207445. originalWndProc = 0;
  207446. }
  207447. void* ActiveXControlComponent::queryInterface (const void* iid) const
  207448. {
  207449. void* result = 0;
  207450. if (control != 0 && control->control != 0
  207451. && SUCCEEDED (control->control->QueryInterface (*(const IID*) iid, &result)))
  207452. return result;
  207453. return 0;
  207454. }
  207455. void ActiveXControlComponent::setControlBounds (const Rectangle<int>& newBounds) const
  207456. {
  207457. if (control->controlHWND != 0)
  207458. MoveWindow (control->controlHWND, newBounds.getX(), newBounds.getY(), newBounds.getWidth(), newBounds.getHeight(), TRUE);
  207459. }
  207460. void ActiveXControlComponent::setControlVisible (const bool shouldBeVisible) const
  207461. {
  207462. if (control->controlHWND != 0)
  207463. ShowWindow (control->controlHWND, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  207464. }
  207465. void ActiveXControlComponent::setMouseEventsAllowed (const bool eventsCanReachControl)
  207466. {
  207467. mouseEventsAllowed = eventsCanReachControl;
  207468. }
  207469. #endif
  207470. /*** End of inlined file: juce_win32_ActiveXComponent.cpp ***/
  207471. /*** Start of inlined file: juce_win32_QuickTimeMovieComponent.cpp ***/
  207472. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  207473. // compiled on its own).
  207474. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  207475. using namespace QTOLibrary;
  207476. using namespace QTOControlLib;
  207477. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  207478. static bool isQTAvailable = false;
  207479. class QuickTimeMovieComponent::Pimpl
  207480. {
  207481. public:
  207482. Pimpl() : dataHandle (0)
  207483. {
  207484. }
  207485. ~Pimpl()
  207486. {
  207487. clearHandle();
  207488. }
  207489. void clearHandle()
  207490. {
  207491. if (dataHandle != 0)
  207492. {
  207493. DisposeHandle (dataHandle);
  207494. dataHandle = 0;
  207495. }
  207496. }
  207497. IQTControlPtr qtControl;
  207498. IQTMoviePtr qtMovie;
  207499. Handle dataHandle;
  207500. };
  207501. QuickTimeMovieComponent::QuickTimeMovieComponent()
  207502. : movieLoaded (false),
  207503. controllerVisible (true)
  207504. {
  207505. pimpl = new Pimpl();
  207506. setMouseEventsAllowed (false);
  207507. }
  207508. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  207509. {
  207510. closeMovie();
  207511. pimpl->qtControl = 0;
  207512. deleteControl();
  207513. pimpl = 0;
  207514. }
  207515. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  207516. {
  207517. if (! isQTAvailable)
  207518. isQTAvailable = (InitializeQTML (0) == noErr) && (EnterMovies() == noErr);
  207519. return isQTAvailable;
  207520. }
  207521. void QuickTimeMovieComponent::createControlIfNeeded()
  207522. {
  207523. if (isShowing() && ! isControlCreated())
  207524. {
  207525. const IID qtIID = __uuidof (QTControl);
  207526. if (createControl (&qtIID))
  207527. {
  207528. const IID qtInterfaceIID = __uuidof (IQTControl);
  207529. pimpl->qtControl = (IQTControl*) queryInterface (&qtInterfaceIID);
  207530. if (pimpl->qtControl != 0)
  207531. {
  207532. pimpl->qtControl->Release(); // it has one ref too many at this point
  207533. pimpl->qtControl->QuickTimeInitialize();
  207534. pimpl->qtControl->PutSizing (qtMovieFitsControl);
  207535. if (movieFile != File::nonexistent)
  207536. loadMovie (movieFile, controllerVisible);
  207537. }
  207538. }
  207539. }
  207540. }
  207541. bool QuickTimeMovieComponent::isControlCreated() const
  207542. {
  207543. return isControlOpen();
  207544. }
  207545. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  207546. const bool isControllerVisible)
  207547. {
  207548. const ScopedPointer<InputStream> movieStreamDeleter (movieStream);
  207549. movieFile = File::nonexistent;
  207550. movieLoaded = false;
  207551. pimpl->qtMovie = 0;
  207552. controllerVisible = isControllerVisible;
  207553. createControlIfNeeded();
  207554. if (isControlCreated())
  207555. {
  207556. if (pimpl->qtControl != 0)
  207557. {
  207558. pimpl->qtControl->Put_MovieHandle (0);
  207559. pimpl->clearHandle();
  207560. Movie movie;
  207561. if (juce_OpenQuickTimeMovieFromStream (movieStream, movie, pimpl->dataHandle))
  207562. {
  207563. pimpl->qtControl->Put_MovieHandle ((long) (pointer_sized_int) movie);
  207564. pimpl->qtMovie = pimpl->qtControl->GetMovie();
  207565. if (pimpl->qtMovie != 0)
  207566. pimpl->qtMovie->PutMovieControllerType (isControllerVisible ? qtMovieControllerTypeStandard
  207567. : qtMovieControllerTypeNone);
  207568. }
  207569. if (movie == 0)
  207570. pimpl->clearHandle();
  207571. }
  207572. movieLoaded = (pimpl->qtMovie != 0);
  207573. }
  207574. else
  207575. {
  207576. // You're trying to open a movie when the control hasn't yet been created, probably because
  207577. // you've not yet added this component to a Window and made the whole component hierarchy visible.
  207578. jassertfalse;
  207579. }
  207580. return movieLoaded;
  207581. }
  207582. void QuickTimeMovieComponent::closeMovie()
  207583. {
  207584. stop();
  207585. movieFile = File::nonexistent;
  207586. movieLoaded = false;
  207587. pimpl->qtMovie = 0;
  207588. if (pimpl->qtControl != 0)
  207589. pimpl->qtControl->Put_MovieHandle (0);
  207590. pimpl->clearHandle();
  207591. }
  207592. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  207593. {
  207594. return movieFile;
  207595. }
  207596. bool QuickTimeMovieComponent::isMovieOpen() const
  207597. {
  207598. return movieLoaded;
  207599. }
  207600. double QuickTimeMovieComponent::getMovieDuration() const
  207601. {
  207602. if (pimpl->qtMovie != 0)
  207603. return pimpl->qtMovie->GetDuration() / (double) pimpl->qtMovie->GetTimeScale();
  207604. return 0.0;
  207605. }
  207606. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  207607. {
  207608. if (pimpl->qtMovie != 0)
  207609. {
  207610. struct QTRECT r = pimpl->qtMovie->GetNaturalRect();
  207611. width = r.right - r.left;
  207612. height = r.bottom - r.top;
  207613. }
  207614. else
  207615. {
  207616. width = height = 0;
  207617. }
  207618. }
  207619. void QuickTimeMovieComponent::play()
  207620. {
  207621. if (pimpl->qtMovie != 0)
  207622. pimpl->qtMovie->Play();
  207623. }
  207624. void QuickTimeMovieComponent::stop()
  207625. {
  207626. if (pimpl->qtMovie != 0)
  207627. pimpl->qtMovie->Stop();
  207628. }
  207629. bool QuickTimeMovieComponent::isPlaying() const
  207630. {
  207631. return pimpl->qtMovie != 0 && pimpl->qtMovie->GetRate() != 0.0f;
  207632. }
  207633. void QuickTimeMovieComponent::setPosition (const double seconds)
  207634. {
  207635. if (pimpl->qtMovie != 0)
  207636. pimpl->qtMovie->PutTime ((long) (seconds * pimpl->qtMovie->GetTimeScale()));
  207637. }
  207638. double QuickTimeMovieComponent::getPosition() const
  207639. {
  207640. if (pimpl->qtMovie != 0)
  207641. return pimpl->qtMovie->GetTime() / (double) pimpl->qtMovie->GetTimeScale();
  207642. return 0.0;
  207643. }
  207644. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  207645. {
  207646. if (pimpl->qtMovie != 0)
  207647. pimpl->qtMovie->PutRate (newSpeed);
  207648. }
  207649. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  207650. {
  207651. if (pimpl->qtMovie != 0)
  207652. {
  207653. pimpl->qtMovie->PutAudioVolume (newVolume);
  207654. pimpl->qtMovie->PutAudioMute (newVolume <= 0);
  207655. }
  207656. }
  207657. float QuickTimeMovieComponent::getMovieVolume() const
  207658. {
  207659. if (pimpl->qtMovie != 0)
  207660. return pimpl->qtMovie->GetAudioVolume();
  207661. return 0.0f;
  207662. }
  207663. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  207664. {
  207665. if (pimpl->qtMovie != 0)
  207666. pimpl->qtMovie->PutLoop (shouldLoop);
  207667. }
  207668. bool QuickTimeMovieComponent::isLooping() const
  207669. {
  207670. return pimpl->qtMovie != 0 && pimpl->qtMovie->GetLoop();
  207671. }
  207672. bool QuickTimeMovieComponent::isControllerVisible() const
  207673. {
  207674. return controllerVisible;
  207675. }
  207676. void QuickTimeMovieComponent::parentHierarchyChanged()
  207677. {
  207678. createControlIfNeeded();
  207679. QTCompBaseClass::parentHierarchyChanged();
  207680. }
  207681. void QuickTimeMovieComponent::visibilityChanged()
  207682. {
  207683. createControlIfNeeded();
  207684. QTCompBaseClass::visibilityChanged();
  207685. }
  207686. void QuickTimeMovieComponent::paint (Graphics& g)
  207687. {
  207688. if (! isControlCreated())
  207689. g.fillAll (Colours::black);
  207690. }
  207691. static Handle createHandleDataRef (Handle dataHandle, const char* fileName)
  207692. {
  207693. Handle dataRef = 0;
  207694. OSStatus err = PtrToHand (&dataHandle, &dataRef, sizeof (Handle));
  207695. if (err == noErr)
  207696. {
  207697. Str255 suffix;
  207698. CharacterFunctions::copy ((char*) suffix, fileName, 128);
  207699. StringPtr name = suffix;
  207700. err = PtrAndHand (name, dataRef, name[0] + 1);
  207701. if (err == noErr)
  207702. {
  207703. long atoms[3];
  207704. atoms[0] = EndianU32_NtoB (3 * sizeof (long));
  207705. atoms[1] = EndianU32_NtoB (kDataRefExtensionMacOSFileType);
  207706. atoms[2] = EndianU32_NtoB (MovieFileType);
  207707. err = PtrAndHand (atoms, dataRef, 3 * sizeof (long));
  207708. if (err == noErr)
  207709. return dataRef;
  207710. }
  207711. DisposeHandle (dataRef);
  207712. }
  207713. return 0;
  207714. }
  207715. static CFStringRef juceStringToCFString (const String& s)
  207716. {
  207717. const int len = s.length();
  207718. const juce_wchar* const t = s;
  207719. HeapBlock <UniChar> temp (len + 2);
  207720. for (int i = 0; i <= len; ++i)
  207721. temp[i] = t[i];
  207722. return CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  207723. }
  207724. static bool openMovie (QTNewMoviePropertyElement* props, int prop, Movie& movie)
  207725. {
  207726. Boolean trueBool = true;
  207727. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  207728. props[prop].propID = kQTMovieInstantiationPropertyID_DontResolveDataRefs;
  207729. props[prop].propValueSize = sizeof (trueBool);
  207730. props[prop].propValueAddress = &trueBool;
  207731. ++prop;
  207732. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  207733. props[prop].propID = kQTMovieInstantiationPropertyID_AsyncOK;
  207734. props[prop].propValueSize = sizeof (trueBool);
  207735. props[prop].propValueAddress = &trueBool;
  207736. ++prop;
  207737. Boolean isActive = true;
  207738. props[prop].propClass = kQTPropertyClass_NewMovieProperty;
  207739. props[prop].propID = kQTNewMoviePropertyID_Active;
  207740. props[prop].propValueSize = sizeof (isActive);
  207741. props[prop].propValueAddress = &isActive;
  207742. ++prop;
  207743. MacSetPort (0);
  207744. jassert (prop <= 5);
  207745. OSStatus err = NewMovieFromProperties (prop, props, 0, 0, &movie);
  207746. return err == noErr;
  207747. }
  207748. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle)
  207749. {
  207750. if (input == 0)
  207751. return false;
  207752. dataHandle = 0;
  207753. bool ok = false;
  207754. QTNewMoviePropertyElement props[5];
  207755. zeromem (props, sizeof (props));
  207756. int prop = 0;
  207757. DataReferenceRecord dr;
  207758. props[prop].propClass = kQTPropertyClass_DataLocation;
  207759. props[prop].propID = kQTDataLocationPropertyID_DataReference;
  207760. props[prop].propValueSize = sizeof (dr);
  207761. props[prop].propValueAddress = &dr;
  207762. ++prop;
  207763. FileInputStream* const fin = dynamic_cast <FileInputStream*> (input);
  207764. if (fin != 0)
  207765. {
  207766. CFStringRef filePath = juceStringToCFString (fin->getFile().getFullPathName());
  207767. QTNewDataReferenceFromFullPathCFString (filePath, (QTPathStyle) kQTNativeDefaultPathStyle, 0,
  207768. &dr.dataRef, &dr.dataRefType);
  207769. ok = openMovie (props, prop, movie);
  207770. DisposeHandle (dr.dataRef);
  207771. CFRelease (filePath);
  207772. }
  207773. else
  207774. {
  207775. // sanity-check because this currently needs to load the whole stream into memory..
  207776. jassert (input->getTotalLength() < 50 * 1024 * 1024);
  207777. dataHandle = NewHandle ((Size) input->getTotalLength());
  207778. HLock (dataHandle);
  207779. // read the entire stream into memory - this is a pain, but can't get it to work
  207780. // properly using a custom callback to supply the data.
  207781. input->read (*dataHandle, (int) input->getTotalLength());
  207782. HUnlock (dataHandle);
  207783. // different types to get QT to try. (We should really be a bit smarter here by
  207784. // working out in advance which one the stream contains, rather than just trying
  207785. // each one)
  207786. const char* const suffixesToTry[] = { "\04.mov", "\04.mp3",
  207787. "\04.avi", "\04.m4a" };
  207788. for (int i = 0; i < numElementsInArray (suffixesToTry) && ! ok; ++i)
  207789. {
  207790. /* // this fails for some bizarre reason - it can be bodged to work with
  207791. // movies, but can't seem to do it for other file types..
  207792. QTNewMovieUserProcRecord procInfo;
  207793. procInfo.getMovieUserProc = NewGetMovieUPP (readMovieStreamProc);
  207794. procInfo.getMovieUserProcRefcon = this;
  207795. procInfo.defaultDataRef.dataRef = dataRef;
  207796. procInfo.defaultDataRef.dataRefType = HandleDataHandlerSubType;
  207797. props[prop].propClass = kQTPropertyClass_DataLocation;
  207798. props[prop].propID = kQTDataLocationPropertyID_MovieUserProc;
  207799. props[prop].propValueSize = sizeof (procInfo);
  207800. props[prop].propValueAddress = (void*) &procInfo;
  207801. ++prop; */
  207802. dr.dataRef = createHandleDataRef (dataHandle, suffixesToTry [i]);
  207803. dr.dataRefType = HandleDataHandlerSubType;
  207804. ok = openMovie (props, prop, movie);
  207805. DisposeHandle (dr.dataRef);
  207806. }
  207807. }
  207808. return ok;
  207809. }
  207810. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  207811. const bool isControllerVisible)
  207812. {
  207813. const bool ok = loadMovie (static_cast <InputStream*> (movieFile_.createInputStream()), isControllerVisible);
  207814. movieFile = movieFile_;
  207815. return ok;
  207816. }
  207817. bool QuickTimeMovieComponent::loadMovie (const URL& movieURL,
  207818. const bool isControllerVisible)
  207819. {
  207820. return loadMovie (static_cast <InputStream*> (movieURL.createInputStream (false)), isControllerVisible);
  207821. }
  207822. void QuickTimeMovieComponent::goToStart()
  207823. {
  207824. setPosition (0.0);
  207825. }
  207826. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  207827. const RectanglePlacement& placement)
  207828. {
  207829. int normalWidth, normalHeight;
  207830. getMovieNormalSize (normalWidth, normalHeight);
  207831. if (normalWidth > 0 && normalHeight > 0 && ! spaceToFitWithin.isEmpty())
  207832. {
  207833. double x = 0.0, y = 0.0, w = normalWidth, h = normalHeight;
  207834. placement.applyTo (x, y, w, h,
  207835. spaceToFitWithin.getX(), spaceToFitWithin.getY(),
  207836. spaceToFitWithin.getWidth(), spaceToFitWithin.getHeight());
  207837. if (w > 0 && h > 0)
  207838. {
  207839. setBounds (roundToInt (x), roundToInt (y),
  207840. roundToInt (w), roundToInt (h));
  207841. }
  207842. }
  207843. else
  207844. {
  207845. setBounds (spaceToFitWithin);
  207846. }
  207847. }
  207848. #endif
  207849. /*** End of inlined file: juce_win32_QuickTimeMovieComponent.cpp ***/
  207850. /*** Start of inlined file: juce_win32_WebBrowserComponent.cpp ***/
  207851. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  207852. // compiled on its own).
  207853. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  207854. class WebBrowserComponentInternal : public ActiveXControlComponent
  207855. {
  207856. public:
  207857. WebBrowserComponentInternal()
  207858. : browser (0),
  207859. connectionPoint (0),
  207860. adviseCookie (0)
  207861. {
  207862. }
  207863. ~WebBrowserComponentInternal()
  207864. {
  207865. if (connectionPoint != 0)
  207866. connectionPoint->Unadvise (adviseCookie);
  207867. if (browser != 0)
  207868. browser->Release();
  207869. }
  207870. void createBrowser()
  207871. {
  207872. createControl (&CLSID_WebBrowser);
  207873. browser = (IWebBrowser2*) queryInterface (&IID_IWebBrowser2);
  207874. IConnectionPointContainer* connectionPointContainer = (IConnectionPointContainer*) queryInterface (&IID_IConnectionPointContainer);
  207875. if (connectionPointContainer != 0)
  207876. {
  207877. connectionPointContainer->FindConnectionPoint (DIID_DWebBrowserEvents2,
  207878. &connectionPoint);
  207879. if (connectionPoint != 0)
  207880. {
  207881. WebBrowserComponent* const owner = dynamic_cast <WebBrowserComponent*> (getParentComponent());
  207882. jassert (owner != 0);
  207883. EventHandler* handler = new EventHandler (owner);
  207884. connectionPoint->Advise (handler, &adviseCookie);
  207885. handler->Release();
  207886. }
  207887. }
  207888. }
  207889. void goToURL (const String& url,
  207890. const StringArray* headers,
  207891. const MemoryBlock* postData)
  207892. {
  207893. if (browser != 0)
  207894. {
  207895. LPSAFEARRAY sa = 0;
  207896. VARIANT flags, frame, postDataVar, headersVar; // (_variant_t isn't available in all compilers)
  207897. VariantInit (&flags);
  207898. VariantInit (&frame);
  207899. VariantInit (&postDataVar);
  207900. VariantInit (&headersVar);
  207901. if (headers != 0)
  207902. {
  207903. V_VT (&headersVar) = VT_BSTR;
  207904. V_BSTR (&headersVar) = SysAllocString ((const OLECHAR*) headers->joinIntoString ("\r\n"));
  207905. }
  207906. if (postData != 0 && postData->getSize() > 0)
  207907. {
  207908. LPSAFEARRAY sa = SafeArrayCreateVector (VT_UI1, 0, postData->getSize());
  207909. if (sa != 0)
  207910. {
  207911. void* data = 0;
  207912. SafeArrayAccessData (sa, &data);
  207913. jassert (data != 0);
  207914. if (data != 0)
  207915. {
  207916. postData->copyTo (data, 0, postData->getSize());
  207917. SafeArrayUnaccessData (sa);
  207918. VARIANT postDataVar2;
  207919. VariantInit (&postDataVar2);
  207920. V_VT (&postDataVar2) = VT_ARRAY | VT_UI1;
  207921. V_ARRAY (&postDataVar2) = sa;
  207922. postDataVar = postDataVar2;
  207923. }
  207924. }
  207925. }
  207926. browser->Navigate ((BSTR) (const OLECHAR*) url,
  207927. &flags, &frame,
  207928. &postDataVar, &headersVar);
  207929. if (sa != 0)
  207930. SafeArrayDestroy (sa);
  207931. VariantClear (&flags);
  207932. VariantClear (&frame);
  207933. VariantClear (&postDataVar);
  207934. VariantClear (&headersVar);
  207935. }
  207936. }
  207937. IWebBrowser2* browser;
  207938. juce_UseDebuggingNewOperator
  207939. private:
  207940. IConnectionPoint* connectionPoint;
  207941. DWORD adviseCookie;
  207942. class EventHandler : public ComBaseClassHelper <IDispatch>,
  207943. public ComponentMovementWatcher
  207944. {
  207945. public:
  207946. EventHandler (WebBrowserComponent* owner_)
  207947. : ComponentMovementWatcher (owner_),
  207948. owner (owner_)
  207949. {
  207950. }
  207951. ~EventHandler()
  207952. {
  207953. }
  207954. HRESULT __stdcall GetTypeInfoCount (UINT __RPC_FAR*) { return E_NOTIMPL; }
  207955. HRESULT __stdcall GetTypeInfo (UINT, LCID, ITypeInfo __RPC_FAR *__RPC_FAR*) { return E_NOTIMPL; }
  207956. HRESULT __stdcall GetIDsOfNames (REFIID, LPOLESTR __RPC_FAR*, UINT, LCID, DISPID __RPC_FAR*) { return E_NOTIMPL; }
  207957. HRESULT __stdcall Invoke (DISPID dispIdMember, REFIID /*riid*/, LCID /*lcid*/,
  207958. WORD /*wFlags*/, DISPPARAMS __RPC_FAR* pDispParams,
  207959. VARIANT __RPC_FAR* /*pVarResult*/, EXCEPINFO __RPC_FAR* /*pExcepInfo*/,
  207960. UINT __RPC_FAR* /*puArgErr*/)
  207961. {
  207962. switch (dispIdMember)
  207963. {
  207964. case DISPID_BEFORENAVIGATE2:
  207965. {
  207966. VARIANT* const vurl = pDispParams->rgvarg[5].pvarVal;
  207967. String url;
  207968. if ((vurl->vt & VT_BYREF) != 0)
  207969. url = *vurl->pbstrVal;
  207970. else
  207971. url = vurl->bstrVal;
  207972. *pDispParams->rgvarg->pboolVal
  207973. = owner->pageAboutToLoad (url) ? VARIANT_FALSE
  207974. : VARIANT_TRUE;
  207975. return S_OK;
  207976. }
  207977. default:
  207978. break;
  207979. }
  207980. return E_NOTIMPL;
  207981. }
  207982. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/) {}
  207983. void componentPeerChanged() {}
  207984. void componentVisibilityChanged (Component&)
  207985. {
  207986. owner->visibilityChanged();
  207987. }
  207988. juce_UseDebuggingNewOperator
  207989. private:
  207990. WebBrowserComponent* const owner;
  207991. EventHandler (const EventHandler&);
  207992. EventHandler& operator= (const EventHandler&);
  207993. };
  207994. };
  207995. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  207996. : browser (0),
  207997. blankPageShown (false),
  207998. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  207999. {
  208000. setOpaque (true);
  208001. addAndMakeVisible (browser = new WebBrowserComponentInternal());
  208002. }
  208003. WebBrowserComponent::~WebBrowserComponent()
  208004. {
  208005. delete browser;
  208006. }
  208007. void WebBrowserComponent::goToURL (const String& url,
  208008. const StringArray* headers,
  208009. const MemoryBlock* postData)
  208010. {
  208011. lastURL = url;
  208012. lastHeaders.clear();
  208013. if (headers != 0)
  208014. lastHeaders = *headers;
  208015. lastPostData.setSize (0);
  208016. if (postData != 0)
  208017. lastPostData = *postData;
  208018. blankPageShown = false;
  208019. browser->goToURL (url, headers, postData);
  208020. }
  208021. void WebBrowserComponent::stop()
  208022. {
  208023. if (browser->browser != 0)
  208024. browser->browser->Stop();
  208025. }
  208026. void WebBrowserComponent::goBack()
  208027. {
  208028. lastURL = String::empty;
  208029. blankPageShown = false;
  208030. if (browser->browser != 0)
  208031. browser->browser->GoBack();
  208032. }
  208033. void WebBrowserComponent::goForward()
  208034. {
  208035. lastURL = String::empty;
  208036. if (browser->browser != 0)
  208037. browser->browser->GoForward();
  208038. }
  208039. void WebBrowserComponent::refresh()
  208040. {
  208041. if (browser->browser != 0)
  208042. browser->browser->Refresh();
  208043. }
  208044. void WebBrowserComponent::paint (Graphics& g)
  208045. {
  208046. if (browser->browser == 0)
  208047. g.fillAll (Colours::white);
  208048. }
  208049. void WebBrowserComponent::checkWindowAssociation()
  208050. {
  208051. if (isShowing())
  208052. {
  208053. if (browser->browser == 0 && getPeer() != 0)
  208054. {
  208055. browser->createBrowser();
  208056. reloadLastURL();
  208057. }
  208058. else
  208059. {
  208060. if (blankPageShown)
  208061. goBack();
  208062. }
  208063. }
  208064. else
  208065. {
  208066. if (browser != 0 && unloadPageWhenBrowserIsHidden && ! blankPageShown)
  208067. {
  208068. // when the component becomes invisible, some stuff like flash
  208069. // carries on playing audio, so we need to force it onto a blank
  208070. // page to avoid this..
  208071. blankPageShown = true;
  208072. browser->goToURL ("about:blank", 0, 0);
  208073. }
  208074. }
  208075. }
  208076. void WebBrowserComponent::reloadLastURL()
  208077. {
  208078. if (lastURL.isNotEmpty())
  208079. {
  208080. goToURL (lastURL, &lastHeaders, &lastPostData);
  208081. lastURL = String::empty;
  208082. }
  208083. }
  208084. void WebBrowserComponent::parentHierarchyChanged()
  208085. {
  208086. checkWindowAssociation();
  208087. }
  208088. void WebBrowserComponent::resized()
  208089. {
  208090. browser->setSize (getWidth(), getHeight());
  208091. }
  208092. void WebBrowserComponent::visibilityChanged()
  208093. {
  208094. checkWindowAssociation();
  208095. }
  208096. bool WebBrowserComponent::pageAboutToLoad (const String&)
  208097. {
  208098. return true;
  208099. }
  208100. #endif
  208101. /*** End of inlined file: juce_win32_WebBrowserComponent.cpp ***/
  208102. /*** Start of inlined file: juce_win32_OpenGLComponent.cpp ***/
  208103. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  208104. // compiled on its own).
  208105. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  208106. #define WGL_EXT_FUNCTION_INIT(extType, extFunc) \
  208107. ((extFunc = (extType) wglGetProcAddress (#extFunc)) != 0)
  208108. typedef const char* (WINAPI* PFNWGLGETEXTENSIONSSTRINGARBPROC) (HDC hdc);
  208109. typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBIVARBPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);
  208110. typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATARBPROC) (HDC hdc, const int* piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
  208111. typedef BOOL (WINAPI * PFNWGLSWAPINTERVALEXTPROC) (int interval);
  208112. typedef int (WINAPI * PFNWGLGETSWAPINTERVALEXTPROC) (void);
  208113. #define WGL_NUMBER_PIXEL_FORMATS_ARB 0x2000
  208114. #define WGL_DRAW_TO_WINDOW_ARB 0x2001
  208115. #define WGL_ACCELERATION_ARB 0x2003
  208116. #define WGL_SWAP_METHOD_ARB 0x2007
  208117. #define WGL_SUPPORT_OPENGL_ARB 0x2010
  208118. #define WGL_PIXEL_TYPE_ARB 0x2013
  208119. #define WGL_DOUBLE_BUFFER_ARB 0x2011
  208120. #define WGL_COLOR_BITS_ARB 0x2014
  208121. #define WGL_RED_BITS_ARB 0x2015
  208122. #define WGL_GREEN_BITS_ARB 0x2017
  208123. #define WGL_BLUE_BITS_ARB 0x2019
  208124. #define WGL_ALPHA_BITS_ARB 0x201B
  208125. #define WGL_DEPTH_BITS_ARB 0x2022
  208126. #define WGL_STENCIL_BITS_ARB 0x2023
  208127. #define WGL_FULL_ACCELERATION_ARB 0x2027
  208128. #define WGL_ACCUM_RED_BITS_ARB 0x201E
  208129. #define WGL_ACCUM_GREEN_BITS_ARB 0x201F
  208130. #define WGL_ACCUM_BLUE_BITS_ARB 0x2020
  208131. #define WGL_ACCUM_ALPHA_BITS_ARB 0x2021
  208132. #define WGL_STEREO_ARB 0x2012
  208133. #define WGL_SAMPLE_BUFFERS_ARB 0x2041
  208134. #define WGL_SAMPLES_ARB 0x2042
  208135. #define WGL_TYPE_RGBA_ARB 0x202B
  208136. static void getWglExtensions (HDC dc, StringArray& result) throw()
  208137. {
  208138. PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringARB = 0;
  208139. if (WGL_EXT_FUNCTION_INIT (PFNWGLGETEXTENSIONSSTRINGARBPROC, wglGetExtensionsStringARB))
  208140. result.addTokens (String (wglGetExtensionsStringARB (dc)), false);
  208141. else
  208142. jassertfalse; // If this fails, it may be because you didn't activate the openGL context
  208143. }
  208144. class WindowedGLContext : public OpenGLContext
  208145. {
  208146. public:
  208147. WindowedGLContext (Component* const component_,
  208148. HGLRC contextToShareWith,
  208149. const OpenGLPixelFormat& pixelFormat)
  208150. : renderContext (0),
  208151. nativeWindow (0),
  208152. dc (0),
  208153. component (component_)
  208154. {
  208155. jassert (component != 0);
  208156. createNativeWindow();
  208157. // Use a default pixel format that should be supported everywhere
  208158. PIXELFORMATDESCRIPTOR pfd;
  208159. zerostruct (pfd);
  208160. pfd.nSize = sizeof (pfd);
  208161. pfd.nVersion = 1;
  208162. pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
  208163. pfd.iPixelType = PFD_TYPE_RGBA;
  208164. pfd.cColorBits = 24;
  208165. pfd.cDepthBits = 16;
  208166. const int format = ChoosePixelFormat (dc, &pfd);
  208167. if (format != 0)
  208168. SetPixelFormat (dc, format, &pfd);
  208169. renderContext = wglCreateContext (dc);
  208170. makeActive();
  208171. setPixelFormat (pixelFormat);
  208172. if (contextToShareWith != 0 && renderContext != 0)
  208173. wglShareLists (contextToShareWith, renderContext);
  208174. }
  208175. ~WindowedGLContext()
  208176. {
  208177. makeInactive();
  208178. wglDeleteContext (renderContext);
  208179. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  208180. delete nativeWindow;
  208181. }
  208182. bool makeActive() const throw()
  208183. {
  208184. jassert (renderContext != 0);
  208185. return wglMakeCurrent (dc, renderContext) != 0;
  208186. }
  208187. bool makeInactive() const throw()
  208188. {
  208189. return (! isActive()) || (wglMakeCurrent (0, 0) != 0);
  208190. }
  208191. bool isActive() const throw()
  208192. {
  208193. return wglGetCurrentContext() == renderContext;
  208194. }
  208195. const OpenGLPixelFormat getPixelFormat() const
  208196. {
  208197. OpenGLPixelFormat pf;
  208198. makeActive();
  208199. StringArray availableExtensions;
  208200. getWglExtensions (dc, availableExtensions);
  208201. fillInPixelFormatDetails (GetPixelFormat (dc), pf, availableExtensions);
  208202. return pf;
  208203. }
  208204. void* getRawContext() const throw()
  208205. {
  208206. return renderContext;
  208207. }
  208208. bool setPixelFormat (const OpenGLPixelFormat& pixelFormat)
  208209. {
  208210. makeActive();
  208211. PIXELFORMATDESCRIPTOR pfd;
  208212. zerostruct (pfd);
  208213. pfd.nSize = sizeof (pfd);
  208214. pfd.nVersion = 1;
  208215. pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER;
  208216. pfd.iPixelType = PFD_TYPE_RGBA;
  208217. pfd.iLayerType = PFD_MAIN_PLANE;
  208218. pfd.cColorBits = (BYTE) (pixelFormat.redBits + pixelFormat.greenBits + pixelFormat.blueBits);
  208219. pfd.cRedBits = (BYTE) pixelFormat.redBits;
  208220. pfd.cGreenBits = (BYTE) pixelFormat.greenBits;
  208221. pfd.cBlueBits = (BYTE) pixelFormat.blueBits;
  208222. pfd.cAlphaBits = (BYTE) pixelFormat.alphaBits;
  208223. pfd.cDepthBits = (BYTE) pixelFormat.depthBufferBits;
  208224. pfd.cStencilBits = (BYTE) pixelFormat.stencilBufferBits;
  208225. pfd.cAccumBits = (BYTE) (pixelFormat.accumulationBufferRedBits + pixelFormat.accumulationBufferGreenBits
  208226. + pixelFormat.accumulationBufferBlueBits + pixelFormat.accumulationBufferAlphaBits);
  208227. pfd.cAccumRedBits = (BYTE) pixelFormat.accumulationBufferRedBits;
  208228. pfd.cAccumGreenBits = (BYTE) pixelFormat.accumulationBufferGreenBits;
  208229. pfd.cAccumBlueBits = (BYTE) pixelFormat.accumulationBufferBlueBits;
  208230. pfd.cAccumAlphaBits = (BYTE) pixelFormat.accumulationBufferAlphaBits;
  208231. int format = 0;
  208232. PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = 0;
  208233. StringArray availableExtensions;
  208234. getWglExtensions (dc, availableExtensions);
  208235. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  208236. && WGL_EXT_FUNCTION_INIT (PFNWGLCHOOSEPIXELFORMATARBPROC, wglChoosePixelFormatARB))
  208237. {
  208238. int attributes[64];
  208239. int n = 0;
  208240. attributes[n++] = WGL_DRAW_TO_WINDOW_ARB;
  208241. attributes[n++] = GL_TRUE;
  208242. attributes[n++] = WGL_SUPPORT_OPENGL_ARB;
  208243. attributes[n++] = GL_TRUE;
  208244. attributes[n++] = WGL_ACCELERATION_ARB;
  208245. attributes[n++] = WGL_FULL_ACCELERATION_ARB;
  208246. attributes[n++] = WGL_DOUBLE_BUFFER_ARB;
  208247. attributes[n++] = GL_TRUE;
  208248. attributes[n++] = WGL_PIXEL_TYPE_ARB;
  208249. attributes[n++] = WGL_TYPE_RGBA_ARB;
  208250. attributes[n++] = WGL_COLOR_BITS_ARB;
  208251. attributes[n++] = pfd.cColorBits;
  208252. attributes[n++] = WGL_RED_BITS_ARB;
  208253. attributes[n++] = pixelFormat.redBits;
  208254. attributes[n++] = WGL_GREEN_BITS_ARB;
  208255. attributes[n++] = pixelFormat.greenBits;
  208256. attributes[n++] = WGL_BLUE_BITS_ARB;
  208257. attributes[n++] = pixelFormat.blueBits;
  208258. attributes[n++] = WGL_ALPHA_BITS_ARB;
  208259. attributes[n++] = pixelFormat.alphaBits;
  208260. attributes[n++] = WGL_DEPTH_BITS_ARB;
  208261. attributes[n++] = pixelFormat.depthBufferBits;
  208262. if (pixelFormat.stencilBufferBits > 0)
  208263. {
  208264. attributes[n++] = WGL_STENCIL_BITS_ARB;
  208265. attributes[n++] = pixelFormat.stencilBufferBits;
  208266. }
  208267. attributes[n++] = WGL_ACCUM_RED_BITS_ARB;
  208268. attributes[n++] = pixelFormat.accumulationBufferRedBits;
  208269. attributes[n++] = WGL_ACCUM_GREEN_BITS_ARB;
  208270. attributes[n++] = pixelFormat.accumulationBufferGreenBits;
  208271. attributes[n++] = WGL_ACCUM_BLUE_BITS_ARB;
  208272. attributes[n++] = pixelFormat.accumulationBufferBlueBits;
  208273. attributes[n++] = WGL_ACCUM_ALPHA_BITS_ARB;
  208274. attributes[n++] = pixelFormat.accumulationBufferAlphaBits;
  208275. if (availableExtensions.contains ("WGL_ARB_multisample")
  208276. && pixelFormat.fullSceneAntiAliasingNumSamples > 0)
  208277. {
  208278. attributes[n++] = WGL_SAMPLE_BUFFERS_ARB;
  208279. attributes[n++] = 1;
  208280. attributes[n++] = WGL_SAMPLES_ARB;
  208281. attributes[n++] = pixelFormat.fullSceneAntiAliasingNumSamples;
  208282. }
  208283. attributes[n++] = 0;
  208284. UINT formatsCount;
  208285. const BOOL ok = wglChoosePixelFormatARB (dc, attributes, 0, 1, &format, &formatsCount);
  208286. (void) ok;
  208287. jassert (ok);
  208288. }
  208289. else
  208290. {
  208291. format = ChoosePixelFormat (dc, &pfd);
  208292. }
  208293. if (format != 0)
  208294. {
  208295. makeInactive();
  208296. // win32 can't change the pixel format of a window, so need to delete the
  208297. // old one and create a new one..
  208298. jassert (nativeWindow != 0);
  208299. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  208300. delete nativeWindow;
  208301. createNativeWindow();
  208302. if (SetPixelFormat (dc, format, &pfd))
  208303. {
  208304. wglDeleteContext (renderContext);
  208305. renderContext = wglCreateContext (dc);
  208306. jassert (renderContext != 0);
  208307. return renderContext != 0;
  208308. }
  208309. }
  208310. return false;
  208311. }
  208312. void updateWindowPosition (int x, int y, int w, int h, int)
  208313. {
  208314. SetWindowPos ((HWND) nativeWindow->getNativeHandle(), 0,
  208315. x, y, w, h,
  208316. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  208317. }
  208318. void repaint()
  208319. {
  208320. nativeWindow->repaint (nativeWindow->getBounds().withPosition (Point<int>()));
  208321. }
  208322. void swapBuffers()
  208323. {
  208324. SwapBuffers (dc);
  208325. }
  208326. bool setSwapInterval (int numFramesPerSwap)
  208327. {
  208328. makeActive();
  208329. StringArray availableExtensions;
  208330. getWglExtensions (dc, availableExtensions);
  208331. PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = 0;
  208332. return availableExtensions.contains ("WGL_EXT_swap_control")
  208333. && WGL_EXT_FUNCTION_INIT (PFNWGLSWAPINTERVALEXTPROC, wglSwapIntervalEXT)
  208334. && wglSwapIntervalEXT (numFramesPerSwap) != FALSE;
  208335. }
  208336. int getSwapInterval() const
  208337. {
  208338. makeActive();
  208339. StringArray availableExtensions;
  208340. getWglExtensions (dc, availableExtensions);
  208341. PFNWGLGETSWAPINTERVALEXTPROC wglGetSwapIntervalEXT = 0;
  208342. if (availableExtensions.contains ("WGL_EXT_swap_control")
  208343. && WGL_EXT_FUNCTION_INIT (PFNWGLGETSWAPINTERVALEXTPROC, wglGetSwapIntervalEXT))
  208344. return wglGetSwapIntervalEXT();
  208345. return 0;
  208346. }
  208347. void findAlternativeOpenGLPixelFormats (OwnedArray <OpenGLPixelFormat>& results)
  208348. {
  208349. jassert (isActive());
  208350. StringArray availableExtensions;
  208351. getWglExtensions (dc, availableExtensions);
  208352. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  208353. int numTypes = 0;
  208354. if (availableExtensions.contains("WGL_ARB_pixel_format")
  208355. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  208356. {
  208357. int attributes = WGL_NUMBER_PIXEL_FORMATS_ARB;
  208358. if (! wglGetPixelFormatAttribivARB (dc, 1, 0, 1, &attributes, &numTypes))
  208359. jassertfalse;
  208360. }
  208361. else
  208362. {
  208363. numTypes = DescribePixelFormat (dc, 0, 0, 0);
  208364. }
  208365. OpenGLPixelFormat pf;
  208366. for (int i = 0; i < numTypes; ++i)
  208367. {
  208368. if (fillInPixelFormatDetails (i + 1, pf, availableExtensions))
  208369. {
  208370. bool alreadyListed = false;
  208371. for (int j = results.size(); --j >= 0;)
  208372. if (pf == *results.getUnchecked(j))
  208373. alreadyListed = true;
  208374. if (! alreadyListed)
  208375. results.add (new OpenGLPixelFormat (pf));
  208376. }
  208377. }
  208378. }
  208379. void* getNativeWindowHandle() const
  208380. {
  208381. return nativeWindow != 0 ? nativeWindow->getNativeHandle() : 0;
  208382. }
  208383. juce_UseDebuggingNewOperator
  208384. HGLRC renderContext;
  208385. private:
  208386. Win32ComponentPeer* nativeWindow;
  208387. Component* const component;
  208388. HDC dc;
  208389. void createNativeWindow()
  208390. {
  208391. nativeWindow = new Win32ComponentPeer (component, 0);
  208392. nativeWindow->dontRepaint = true;
  208393. nativeWindow->setVisible (true);
  208394. HWND hwnd = (HWND) nativeWindow->getNativeHandle();
  208395. Win32ComponentPeer* const peer = dynamic_cast <Win32ComponentPeer*> (component->getTopLevelComponent()->getPeer());
  208396. if (peer != 0)
  208397. {
  208398. SetParent (hwnd, (HWND) peer->getNativeHandle());
  208399. juce_setWindowStyleBit (hwnd, GWL_STYLE, WS_CHILD, true);
  208400. juce_setWindowStyleBit (hwnd, GWL_STYLE, WS_POPUP, false);
  208401. }
  208402. dc = GetDC (hwnd);
  208403. }
  208404. bool fillInPixelFormatDetails (const int pixelFormatIndex,
  208405. OpenGLPixelFormat& result,
  208406. const StringArray& availableExtensions) const throw()
  208407. {
  208408. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  208409. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  208410. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  208411. {
  208412. int attributes[32];
  208413. int numAttributes = 0;
  208414. attributes[numAttributes++] = WGL_DRAW_TO_WINDOW_ARB;
  208415. attributes[numAttributes++] = WGL_SUPPORT_OPENGL_ARB;
  208416. attributes[numAttributes++] = WGL_ACCELERATION_ARB;
  208417. attributes[numAttributes++] = WGL_DOUBLE_BUFFER_ARB;
  208418. attributes[numAttributes++] = WGL_PIXEL_TYPE_ARB;
  208419. attributes[numAttributes++] = WGL_RED_BITS_ARB;
  208420. attributes[numAttributes++] = WGL_GREEN_BITS_ARB;
  208421. attributes[numAttributes++] = WGL_BLUE_BITS_ARB;
  208422. attributes[numAttributes++] = WGL_ALPHA_BITS_ARB;
  208423. attributes[numAttributes++] = WGL_DEPTH_BITS_ARB;
  208424. attributes[numAttributes++] = WGL_STENCIL_BITS_ARB;
  208425. attributes[numAttributes++] = WGL_ACCUM_RED_BITS_ARB;
  208426. attributes[numAttributes++] = WGL_ACCUM_GREEN_BITS_ARB;
  208427. attributes[numAttributes++] = WGL_ACCUM_BLUE_BITS_ARB;
  208428. attributes[numAttributes++] = WGL_ACCUM_ALPHA_BITS_ARB;
  208429. if (availableExtensions.contains ("WGL_ARB_multisample"))
  208430. attributes[numAttributes++] = WGL_SAMPLES_ARB;
  208431. int values[32];
  208432. zeromem (values, sizeof (values));
  208433. if (wglGetPixelFormatAttribivARB (dc, pixelFormatIndex, 0, numAttributes, attributes, values))
  208434. {
  208435. int n = 0;
  208436. bool isValidFormat = (values[n++] == GL_TRUE); // WGL_DRAW_TO_WINDOW_ARB
  208437. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_SUPPORT_OPENGL_ARB
  208438. isValidFormat = (values[n++] == WGL_FULL_ACCELERATION_ARB) && isValidFormat; // WGL_ACCELERATION_ARB
  208439. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_DOUBLE_BUFFER_ARB:
  208440. isValidFormat = (values[n++] == WGL_TYPE_RGBA_ARB) && isValidFormat; // WGL_PIXEL_TYPE_ARB
  208441. result.redBits = values[n++]; // WGL_RED_BITS_ARB
  208442. result.greenBits = values[n++]; // WGL_GREEN_BITS_ARB
  208443. result.blueBits = values[n++]; // WGL_BLUE_BITS_ARB
  208444. result.alphaBits = values[n++]; // WGL_ALPHA_BITS_ARB
  208445. result.depthBufferBits = values[n++]; // WGL_DEPTH_BITS_ARB
  208446. result.stencilBufferBits = values[n++]; // WGL_STENCIL_BITS_ARB
  208447. result.accumulationBufferRedBits = values[n++]; // WGL_ACCUM_RED_BITS_ARB
  208448. result.accumulationBufferGreenBits = values[n++]; // WGL_ACCUM_GREEN_BITS_ARB
  208449. result.accumulationBufferBlueBits = values[n++]; // WGL_ACCUM_BLUE_BITS_ARB
  208450. result.accumulationBufferAlphaBits = values[n++]; // WGL_ACCUM_ALPHA_BITS_ARB
  208451. result.fullSceneAntiAliasingNumSamples = (uint8) values[n++]; // WGL_SAMPLES_ARB
  208452. return isValidFormat;
  208453. }
  208454. else
  208455. {
  208456. jassertfalse;
  208457. }
  208458. }
  208459. else
  208460. {
  208461. PIXELFORMATDESCRIPTOR pfd;
  208462. if (DescribePixelFormat (dc, pixelFormatIndex, sizeof (pfd), &pfd))
  208463. {
  208464. result.redBits = pfd.cRedBits;
  208465. result.greenBits = pfd.cGreenBits;
  208466. result.blueBits = pfd.cBlueBits;
  208467. result.alphaBits = pfd.cAlphaBits;
  208468. result.depthBufferBits = pfd.cDepthBits;
  208469. result.stencilBufferBits = pfd.cStencilBits;
  208470. result.accumulationBufferRedBits = pfd.cAccumRedBits;
  208471. result.accumulationBufferGreenBits = pfd.cAccumGreenBits;
  208472. result.accumulationBufferBlueBits = pfd.cAccumBlueBits;
  208473. result.accumulationBufferAlphaBits = pfd.cAccumAlphaBits;
  208474. result.fullSceneAntiAliasingNumSamples = 0;
  208475. return true;
  208476. }
  208477. else
  208478. {
  208479. jassertfalse;
  208480. }
  208481. }
  208482. return false;
  208483. }
  208484. WindowedGLContext (const WindowedGLContext&);
  208485. WindowedGLContext& operator= (const WindowedGLContext&);
  208486. };
  208487. OpenGLContext* OpenGLComponent::createContext()
  208488. {
  208489. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this,
  208490. contextToShareListsWith != 0 ? (HGLRC) contextToShareListsWith->getRawContext() : 0,
  208491. preferredPixelFormat));
  208492. return (c->renderContext != 0) ? c.release() : 0;
  208493. }
  208494. void* OpenGLComponent::getNativeWindowHandle() const
  208495. {
  208496. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle() : 0;
  208497. }
  208498. void juce_glViewport (const int w, const int h)
  208499. {
  208500. glViewport (0, 0, w, h);
  208501. }
  208502. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  208503. OwnedArray <OpenGLPixelFormat>& results)
  208504. {
  208505. Component tempComp;
  208506. {
  208507. WindowedGLContext wc (component, 0, OpenGLPixelFormat (8, 8, 16, 0));
  208508. wc.makeActive();
  208509. wc.findAlternativeOpenGLPixelFormats (results);
  208510. }
  208511. }
  208512. #endif
  208513. /*** End of inlined file: juce_win32_OpenGLComponent.cpp ***/
  208514. /*** Start of inlined file: juce_win32_AudioCDReader.cpp ***/
  208515. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  208516. // compiled on its own).
  208517. #if JUCE_INCLUDED_FILE
  208518. #if JUCE_USE_CDREADER
  208519. namespace CDReaderHelpers
  208520. {
  208521. //***************************************************************************
  208522. // %%% TARGET STATUS VALUES %%%
  208523. //***************************************************************************
  208524. #define STATUS_GOOD 0x00 // Status Good
  208525. #define STATUS_CHKCOND 0x02 // Check Condition
  208526. #define STATUS_CONDMET 0x04 // Condition Met
  208527. #define STATUS_BUSY 0x08 // Busy
  208528. #define STATUS_INTERM 0x10 // Intermediate
  208529. #define STATUS_INTCDMET 0x14 // Intermediate-condition met
  208530. #define STATUS_RESCONF 0x18 // Reservation conflict
  208531. #define STATUS_COMTERM 0x22 // Command Terminated
  208532. #define STATUS_QFULL 0x28 // Queue full
  208533. //***************************************************************************
  208534. // %%% SCSI MISCELLANEOUS EQUATES %%%
  208535. //***************************************************************************
  208536. #define MAXLUN 7 // Maximum Logical Unit Id
  208537. #define MAXTARG 7 // Maximum Target Id
  208538. #define MAX_SCSI_LUNS 64 // Maximum Number of SCSI LUNs
  208539. #define MAX_NUM_HA 8 // Maximum Number of SCSI HA's
  208540. //***************************************************************************
  208541. // %%% Commands for all Device Types %%%
  208542. //***************************************************************************
  208543. #define SCSI_CHANGE_DEF 0x40 // Change Definition (Optional)
  208544. #define SCSI_COMPARE 0x39 // Compare (O)
  208545. #define SCSI_COPY 0x18 // Copy (O)
  208546. #define SCSI_COP_VERIFY 0x3A // Copy and Verify (O)
  208547. #define SCSI_INQUIRY 0x12 // Inquiry (MANDATORY)
  208548. #define SCSI_LOG_SELECT 0x4C // Log Select (O)
  208549. #define SCSI_LOG_SENSE 0x4D // Log Sense (O)
  208550. #define SCSI_MODE_SEL6 0x15 // Mode Select 6-byte (Device Specific)
  208551. #define SCSI_MODE_SEL10 0x55 // Mode Select 10-byte (Device Specific)
  208552. #define SCSI_MODE_SEN6 0x1A // Mode Sense 6-byte (Device Specific)
  208553. #define SCSI_MODE_SEN10 0x5A // Mode Sense 10-byte (Device Specific)
  208554. #define SCSI_READ_BUFF 0x3C // Read Buffer (O)
  208555. #define SCSI_REQ_SENSE 0x03 // Request Sense (MANDATORY)
  208556. #define SCSI_SEND_DIAG 0x1D // Send Diagnostic (O)
  208557. #define SCSI_TST_U_RDY 0x00 // Test Unit Ready (MANDATORY)
  208558. #define SCSI_WRITE_BUFF 0x3B // Write Buffer (O)
  208559. //***************************************************************************
  208560. // %%% Commands Unique to Direct Access Devices %%%
  208561. //***************************************************************************
  208562. #define SCSI_COMPARE 0x39 // Compare (O)
  208563. #define SCSI_FORMAT 0x04 // Format Unit (MANDATORY)
  208564. #define SCSI_LCK_UN_CAC 0x36 // Lock Unlock Cache (O)
  208565. #define SCSI_PREFETCH 0x34 // Prefetch (O)
  208566. #define SCSI_MED_REMOVL 0x1E // Prevent/Allow medium Removal (O)
  208567. #define SCSI_READ6 0x08 // Read 6-byte (MANDATORY)
  208568. #define SCSI_READ10 0x28 // Read 10-byte (MANDATORY)
  208569. #define SCSI_RD_CAPAC 0x25 // Read Capacity (MANDATORY)
  208570. #define SCSI_RD_DEFECT 0x37 // Read Defect Data (O)
  208571. #define SCSI_READ_LONG 0x3E // Read Long (O)
  208572. #define SCSI_REASS_BLK 0x07 // Reassign Blocks (O)
  208573. #define SCSI_RCV_DIAG 0x1C // Receive Diagnostic Results (O)
  208574. #define SCSI_RELEASE 0x17 // Release Unit (MANDATORY)
  208575. #define SCSI_REZERO 0x01 // Rezero Unit (O)
  208576. #define SCSI_SRCH_DAT_E 0x31 // Search Data Equal (O)
  208577. #define SCSI_SRCH_DAT_H 0x30 // Search Data High (O)
  208578. #define SCSI_SRCH_DAT_L 0x32 // Search Data Low (O)
  208579. #define SCSI_SEEK6 0x0B // Seek 6-Byte (O)
  208580. #define SCSI_SEEK10 0x2B // Seek 10-Byte (O)
  208581. #define SCSI_SEND_DIAG 0x1D // Send Diagnostics (MANDATORY)
  208582. #define SCSI_SET_LIMIT 0x33 // Set Limits (O)
  208583. #define SCSI_START_STP 0x1B // Start/Stop Unit (O)
  208584. #define SCSI_SYNC_CACHE 0x35 // Synchronize Cache (O)
  208585. #define SCSI_VERIFY 0x2F // Verify (O)
  208586. #define SCSI_WRITE6 0x0A // Write 6-Byte (MANDATORY)
  208587. #define SCSI_WRITE10 0x2A // Write 10-Byte (MANDATORY)
  208588. #define SCSI_WRT_VERIFY 0x2E // Write and Verify (O)
  208589. #define SCSI_WRITE_LONG 0x3F // Write Long (O)
  208590. #define SCSI_WRITE_SAME 0x41 // Write Same (O)
  208591. //***************************************************************************
  208592. // %%% Commands Unique to Sequential Access Devices %%%
  208593. //***************************************************************************
  208594. #define SCSI_ERASE 0x19 // Erase (MANDATORY)
  208595. #define SCSI_LOAD_UN 0x1b // Load/Unload (O)
  208596. #define SCSI_LOCATE 0x2B // Locate (O)
  208597. #define SCSI_RD_BLK_LIM 0x05 // Read Block Limits (MANDATORY)
  208598. #define SCSI_READ_POS 0x34 // Read Position (O)
  208599. #define SCSI_READ_REV 0x0F // Read Reverse (O)
  208600. #define SCSI_REC_BF_DAT 0x14 // Recover Buffer Data (O)
  208601. #define SCSI_RESERVE 0x16 // Reserve Unit (MANDATORY)
  208602. #define SCSI_REWIND 0x01 // Rewind (MANDATORY)
  208603. #define SCSI_SPACE 0x11 // Space (MANDATORY)
  208604. #define SCSI_VERIFY_T 0x13 // Verify (Tape) (O)
  208605. #define SCSI_WRT_FILE 0x10 // Write Filemarks (MANDATORY)
  208606. //***************************************************************************
  208607. // %%% Commands Unique to Printer Devices %%%
  208608. //***************************************************************************
  208609. #define SCSI_PRINT 0x0A // Print (MANDATORY)
  208610. #define SCSI_SLEW_PNT 0x0B // Slew and Print (O)
  208611. #define SCSI_STOP_PNT 0x1B // Stop Print (O)
  208612. #define SCSI_SYNC_BUFF 0x10 // Synchronize Buffer (O)
  208613. //***************************************************************************
  208614. // %%% Commands Unique to Processor Devices %%%
  208615. //***************************************************************************
  208616. #define SCSI_RECEIVE 0x08 // Receive (O)
  208617. #define SCSI_SEND 0x0A // Send (O)
  208618. //***************************************************************************
  208619. // %%% Commands Unique to Write-Once Devices %%%
  208620. //***************************************************************************
  208621. #define SCSI_MEDIUM_SCN 0x38 // Medium Scan (O)
  208622. #define SCSI_SRCHDATE10 0x31 // Search Data Equal 10-Byte (O)
  208623. #define SCSI_SRCHDATE12 0xB1 // Search Data Equal 12-Byte (O)
  208624. #define SCSI_SRCHDATH10 0x30 // Search Data High 10-Byte (O)
  208625. #define SCSI_SRCHDATH12 0xB0 // Search Data High 12-Byte (O)
  208626. #define SCSI_SRCHDATL10 0x32 // Search Data Low 10-Byte (O)
  208627. #define SCSI_SRCHDATL12 0xB2 // Search Data Low 12-Byte (O)
  208628. #define SCSI_SET_LIM_10 0x33 // Set Limits 10-Byte (O)
  208629. #define SCSI_SET_LIM_12 0xB3 // Set Limits 10-Byte (O)
  208630. #define SCSI_VERIFY10 0x2F // Verify 10-Byte (O)
  208631. #define SCSI_VERIFY12 0xAF // Verify 12-Byte (O)
  208632. #define SCSI_WRITE12 0xAA // Write 12-Byte (O)
  208633. #define SCSI_WRT_VER10 0x2E // Write and Verify 10-Byte (O)
  208634. #define SCSI_WRT_VER12 0xAE // Write and Verify 12-Byte (O)
  208635. //***************************************************************************
  208636. // %%% Commands Unique to CD-ROM Devices %%%
  208637. //***************************************************************************
  208638. #define SCSI_PLAYAUD_10 0x45 // Play Audio 10-Byte (O)
  208639. #define SCSI_PLAYAUD_12 0xA5 // Play Audio 12-Byte 12-Byte (O)
  208640. #define SCSI_PLAYAUDMSF 0x47 // Play Audio MSF (O)
  208641. #define SCSI_PLAYA_TKIN 0x48 // Play Audio Track/Index (O)
  208642. #define SCSI_PLYTKREL10 0x49 // Play Track Relative 10-Byte (O)
  208643. #define SCSI_PLYTKREL12 0xA9 // Play Track Relative 12-Byte (O)
  208644. #define SCSI_READCDCAP 0x25 // Read CD-ROM Capacity (MANDATORY)
  208645. #define SCSI_READHEADER 0x44 // Read Header (O)
  208646. #define SCSI_SUBCHANNEL 0x42 // Read Subchannel (O)
  208647. #define SCSI_READ_TOC 0x43 // Read TOC (O)
  208648. //***************************************************************************
  208649. // %%% Commands Unique to Scanner Devices %%%
  208650. //***************************************************************************
  208651. #define SCSI_GETDBSTAT 0x34 // Get Data Buffer Status (O)
  208652. #define SCSI_GETWINDOW 0x25 // Get Window (O)
  208653. #define SCSI_OBJECTPOS 0x31 // Object Postion (O)
  208654. #define SCSI_SCAN 0x1B // Scan (O)
  208655. #define SCSI_SETWINDOW 0x24 // Set Window (MANDATORY)
  208656. //***************************************************************************
  208657. // %%% Commands Unique to Optical Memory Devices %%%
  208658. //***************************************************************************
  208659. #define SCSI_UpdateBlk 0x3D // Update Block (O)
  208660. //***************************************************************************
  208661. // %%% Commands Unique to Medium Changer Devices %%%
  208662. //***************************************************************************
  208663. #define SCSI_EXCHMEDIUM 0xA6 // Exchange Medium (O)
  208664. #define SCSI_INITELSTAT 0x07 // Initialize Element Status (O)
  208665. #define SCSI_POSTOELEM 0x2B // Position to Element (O)
  208666. #define SCSI_REQ_VE_ADD 0xB5 // Request Volume Element Address (O)
  208667. #define SCSI_SENDVOLTAG 0xB6 // Send Volume Tag (O)
  208668. //***************************************************************************
  208669. // %%% Commands Unique to Communication Devices %%%
  208670. //***************************************************************************
  208671. #define SCSI_GET_MSG_6 0x08 // Get Message 6-Byte (MANDATORY)
  208672. #define SCSI_GET_MSG_10 0x28 // Get Message 10-Byte (O)
  208673. #define SCSI_GET_MSG_12 0xA8 // Get Message 12-Byte (O)
  208674. #define SCSI_SND_MSG_6 0x0A // Send Message 6-Byte (MANDATORY)
  208675. #define SCSI_SND_MSG_10 0x2A // Send Message 10-Byte (O)
  208676. #define SCSI_SND_MSG_12 0xAA // Send Message 12-Byte (O)
  208677. //***************************************************************************
  208678. // %%% Request Sense Data Format %%%
  208679. //***************************************************************************
  208680. typedef struct {
  208681. BYTE ErrorCode; // Error Code (70H or 71H)
  208682. BYTE SegmentNum; // Number of current segment descriptor
  208683. BYTE SenseKey; // Sense Key(See bit definitions too)
  208684. BYTE InfoByte0; // Information MSB
  208685. BYTE InfoByte1; // Information MID
  208686. BYTE InfoByte2; // Information MID
  208687. BYTE InfoByte3; // Information LSB
  208688. BYTE AddSenLen; // Additional Sense Length
  208689. BYTE ComSpecInf0; // Command Specific Information MSB
  208690. BYTE ComSpecInf1; // Command Specific Information MID
  208691. BYTE ComSpecInf2; // Command Specific Information MID
  208692. BYTE ComSpecInf3; // Command Specific Information LSB
  208693. BYTE AddSenseCode; // Additional Sense Code
  208694. BYTE AddSenQual; // Additional Sense Code Qualifier
  208695. BYTE FieldRepUCode; // Field Replaceable Unit Code
  208696. BYTE SenKeySpec15; // Sense Key Specific 15th byte
  208697. BYTE SenKeySpec16; // Sense Key Specific 16th byte
  208698. BYTE SenKeySpec17; // Sense Key Specific 17th byte
  208699. BYTE AddSenseBytes; // Additional Sense Bytes
  208700. } SENSE_DATA_FMT;
  208701. //***************************************************************************
  208702. // %%% REQUEST SENSE ERROR CODE %%%
  208703. //***************************************************************************
  208704. #define SERROR_CURRENT 0x70 // Current Errors
  208705. #define SERROR_DEFERED 0x71 // Deferred Errors
  208706. //***************************************************************************
  208707. // %%% REQUEST SENSE BIT DEFINITIONS %%%
  208708. //***************************************************************************
  208709. #define SENSE_VALID 0x80 // Byte 0 Bit 7
  208710. #define SENSE_FILEMRK 0x80 // Byte 2 Bit 7
  208711. #define SENSE_EOM 0x40 // Byte 2 Bit 6
  208712. #define SENSE_ILI 0x20 // Byte 2 Bit 5
  208713. //***************************************************************************
  208714. // %%% REQUEST SENSE SENSE KEY DEFINITIONS %%%
  208715. //***************************************************************************
  208716. #define KEY_NOSENSE 0x00 // No Sense
  208717. #define KEY_RECERROR 0x01 // Recovered Error
  208718. #define KEY_NOTREADY 0x02 // Not Ready
  208719. #define KEY_MEDIUMERR 0x03 // Medium Error
  208720. #define KEY_HARDERROR 0x04 // Hardware Error
  208721. #define KEY_ILLGLREQ 0x05 // Illegal Request
  208722. #define KEY_UNITATT 0x06 // Unit Attention
  208723. #define KEY_DATAPROT 0x07 // Data Protect
  208724. #define KEY_BLANKCHK 0x08 // Blank Check
  208725. #define KEY_VENDSPEC 0x09 // Vendor Specific
  208726. #define KEY_COPYABORT 0x0A // Copy Abort
  208727. #define KEY_EQUAL 0x0C // Equal (Search)
  208728. #define KEY_VOLOVRFLW 0x0D // Volume Overflow
  208729. #define KEY_MISCOMP 0x0E // Miscompare (Search)
  208730. #define KEY_RESERVED 0x0F // Reserved
  208731. //***************************************************************************
  208732. // %%% PERIPHERAL DEVICE TYPE DEFINITIONS %%%
  208733. //***************************************************************************
  208734. #define DTYPE_DASD 0x00 // Disk Device
  208735. #define DTYPE_SEQD 0x01 // Tape Device
  208736. #define DTYPE_PRNT 0x02 // Printer
  208737. #define DTYPE_PROC 0x03 // Processor
  208738. #define DTYPE_WORM 0x04 // Write-once read-multiple
  208739. #define DTYPE_CROM 0x05 // CD-ROM device
  208740. #define DTYPE_SCAN 0x06 // Scanner device
  208741. #define DTYPE_OPTI 0x07 // Optical memory device
  208742. #define DTYPE_JUKE 0x08 // Medium Changer device
  208743. #define DTYPE_COMM 0x09 // Communications device
  208744. #define DTYPE_RESL 0x0A // Reserved (low)
  208745. #define DTYPE_RESH 0x1E // Reserved (high)
  208746. #define DTYPE_UNKNOWN 0x1F // Unknown or no device type
  208747. //***************************************************************************
  208748. // %%% ANSI APPROVED VERSION DEFINITIONS %%%
  208749. //***************************************************************************
  208750. #define ANSI_MAYBE 0x0 // Device may or may not be ANSI approved stand
  208751. #define ANSI_SCSI1 0x1 // Device complies to ANSI X3.131-1986 (SCSI-1)
  208752. #define ANSI_SCSI2 0x2 // Device complies to SCSI-2
  208753. #define ANSI_RESLO 0x3 // Reserved (low)
  208754. #define ANSI_RESHI 0x7 // Reserved (high)
  208755. typedef struct
  208756. {
  208757. USHORT Length;
  208758. UCHAR ScsiStatus;
  208759. UCHAR PathId;
  208760. UCHAR TargetId;
  208761. UCHAR Lun;
  208762. UCHAR CdbLength;
  208763. UCHAR SenseInfoLength;
  208764. UCHAR DataIn;
  208765. ULONG DataTransferLength;
  208766. ULONG TimeOutValue;
  208767. ULONG DataBufferOffset;
  208768. ULONG SenseInfoOffset;
  208769. UCHAR Cdb[16];
  208770. } SCSI_PASS_THROUGH, *PSCSI_PASS_THROUGH;
  208771. typedef struct
  208772. {
  208773. USHORT Length;
  208774. UCHAR ScsiStatus;
  208775. UCHAR PathId;
  208776. UCHAR TargetId;
  208777. UCHAR Lun;
  208778. UCHAR CdbLength;
  208779. UCHAR SenseInfoLength;
  208780. UCHAR DataIn;
  208781. ULONG DataTransferLength;
  208782. ULONG TimeOutValue;
  208783. PVOID DataBuffer;
  208784. ULONG SenseInfoOffset;
  208785. UCHAR Cdb[16];
  208786. } SCSI_PASS_THROUGH_DIRECT, *PSCSI_PASS_THROUGH_DIRECT;
  208787. typedef struct
  208788. {
  208789. SCSI_PASS_THROUGH_DIRECT spt;
  208790. ULONG Filler;
  208791. UCHAR ucSenseBuf[32];
  208792. } SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, *PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER;
  208793. typedef struct
  208794. {
  208795. ULONG Length;
  208796. UCHAR PortNumber;
  208797. UCHAR PathId;
  208798. UCHAR TargetId;
  208799. UCHAR Lun;
  208800. } SCSI_ADDRESS, *PSCSI_ADDRESS;
  208801. #define METHOD_BUFFERED 0
  208802. #define METHOD_IN_DIRECT 1
  208803. #define METHOD_OUT_DIRECT 2
  208804. #define METHOD_NEITHER 3
  208805. #define FILE_ANY_ACCESS 0
  208806. #ifndef FILE_READ_ACCESS
  208807. #define FILE_READ_ACCESS (0x0001)
  208808. #endif
  208809. #ifndef FILE_WRITE_ACCESS
  208810. #define FILE_WRITE_ACCESS (0x0002)
  208811. #endif
  208812. #define IOCTL_SCSI_BASE 0x00000004
  208813. #define SCSI_IOCTL_DATA_OUT 0
  208814. #define SCSI_IOCTL_DATA_IN 1
  208815. #define SCSI_IOCTL_DATA_UNSPECIFIED 2
  208816. #define CTL_CODE2( DevType, Function, Method, Access ) ( \
  208817. ((DevType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method) \
  208818. )
  208819. #define IOCTL_SCSI_PASS_THROUGH CTL_CODE2( IOCTL_SCSI_BASE, 0x0401, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  208820. #define IOCTL_SCSI_GET_CAPABILITIES CTL_CODE2( IOCTL_SCSI_BASE, 0x0404, METHOD_BUFFERED, FILE_ANY_ACCESS)
  208821. #define IOCTL_SCSI_PASS_THROUGH_DIRECT CTL_CODE2( IOCTL_SCSI_BASE, 0x0405, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  208822. #define IOCTL_SCSI_GET_ADDRESS CTL_CODE2( IOCTL_SCSI_BASE, 0x0406, METHOD_BUFFERED, FILE_ANY_ACCESS )
  208823. #define SENSE_LEN 14
  208824. #define SRB_DIR_SCSI 0x00
  208825. #define SRB_POSTING 0x01
  208826. #define SRB_ENABLE_RESIDUAL_COUNT 0x04
  208827. #define SRB_DIR_IN 0x08
  208828. #define SRB_DIR_OUT 0x10
  208829. #define SRB_EVENT_NOTIFY 0x40
  208830. #define RESIDUAL_COUNT_SUPPORTED 0x02
  208831. #define MAX_SRB_TIMEOUT 1080001u
  208832. #define DEFAULT_SRB_TIMEOUT 1080001u
  208833. #define SC_HA_INQUIRY 0x00
  208834. #define SC_GET_DEV_TYPE 0x01
  208835. #define SC_EXEC_SCSI_CMD 0x02
  208836. #define SC_ABORT_SRB 0x03
  208837. #define SC_RESET_DEV 0x04
  208838. #define SC_SET_HA_PARMS 0x05
  208839. #define SC_GET_DISK_INFO 0x06
  208840. #define SC_RESCAN_SCSI_BUS 0x07
  208841. #define SC_GETSET_TIMEOUTS 0x08
  208842. #define SS_PENDING 0x00
  208843. #define SS_COMP 0x01
  208844. #define SS_ABORTED 0x02
  208845. #define SS_ABORT_FAIL 0x03
  208846. #define SS_ERR 0x04
  208847. #define SS_INVALID_CMD 0x80
  208848. #define SS_INVALID_HA 0x81
  208849. #define SS_NO_DEVICE 0x82
  208850. #define SS_INVALID_SRB 0xE0
  208851. #define SS_OLD_MANAGER 0xE1
  208852. #define SS_BUFFER_ALIGN 0xE1
  208853. #define SS_ILLEGAL_MODE 0xE2
  208854. #define SS_NO_ASPI 0xE3
  208855. #define SS_FAILED_INIT 0xE4
  208856. #define SS_ASPI_IS_BUSY 0xE5
  208857. #define SS_BUFFER_TO_BIG 0xE6
  208858. #define SS_BUFFER_TOO_BIG 0xE6
  208859. #define SS_MISMATCHED_COMPONENTS 0xE7
  208860. #define SS_NO_ADAPTERS 0xE8
  208861. #define SS_INSUFFICIENT_RESOURCES 0xE9
  208862. #define SS_ASPI_IS_SHUTDOWN 0xEA
  208863. #define SS_BAD_INSTALL 0xEB
  208864. #define HASTAT_OK 0x00
  208865. #define HASTAT_SEL_TO 0x11
  208866. #define HASTAT_DO_DU 0x12
  208867. #define HASTAT_BUS_FREE 0x13
  208868. #define HASTAT_PHASE_ERR 0x14
  208869. #define HASTAT_TIMEOUT 0x09
  208870. #define HASTAT_COMMAND_TIMEOUT 0x0B
  208871. #define HASTAT_MESSAGE_REJECT 0x0D
  208872. #define HASTAT_BUS_RESET 0x0E
  208873. #define HASTAT_PARITY_ERROR 0x0F
  208874. #define HASTAT_REQUEST_SENSE_FAILED 0x10
  208875. #define PACKED
  208876. #pragma pack(1)
  208877. typedef struct
  208878. {
  208879. BYTE SRB_Cmd;
  208880. BYTE SRB_Status;
  208881. BYTE SRB_HaID;
  208882. BYTE SRB_Flags;
  208883. DWORD SRB_Hdr_Rsvd;
  208884. BYTE HA_Count;
  208885. BYTE HA_SCSI_ID;
  208886. BYTE HA_ManagerId[16];
  208887. BYTE HA_Identifier[16];
  208888. BYTE HA_Unique[16];
  208889. WORD HA_Rsvd1;
  208890. BYTE pad[20];
  208891. } PACKED SRB_HAInquiry, *PSRB_HAInquiry, FAR *LPSRB_HAInquiry;
  208892. typedef struct
  208893. {
  208894. BYTE SRB_Cmd;
  208895. BYTE SRB_Status;
  208896. BYTE SRB_HaID;
  208897. BYTE SRB_Flags;
  208898. DWORD SRB_Hdr_Rsvd;
  208899. BYTE SRB_Target;
  208900. BYTE SRB_Lun;
  208901. BYTE SRB_DeviceType;
  208902. BYTE SRB_Rsvd1;
  208903. BYTE pad[68];
  208904. } PACKED SRB_GDEVBlock, *PSRB_GDEVBlock, FAR *LPSRB_GDEVBlock;
  208905. typedef struct
  208906. {
  208907. BYTE SRB_Cmd;
  208908. BYTE SRB_Status;
  208909. BYTE SRB_HaID;
  208910. BYTE SRB_Flags;
  208911. DWORD SRB_Hdr_Rsvd;
  208912. BYTE SRB_Target;
  208913. BYTE SRB_Lun;
  208914. WORD SRB_Rsvd1;
  208915. DWORD SRB_BufLen;
  208916. BYTE FAR *SRB_BufPointer;
  208917. BYTE SRB_SenseLen;
  208918. BYTE SRB_CDBLen;
  208919. BYTE SRB_HaStat;
  208920. BYTE SRB_TargStat;
  208921. VOID FAR *SRB_PostProc;
  208922. BYTE SRB_Rsvd2[20];
  208923. BYTE CDBByte[16];
  208924. BYTE SenseArea[SENSE_LEN+2];
  208925. } PACKED SRB_ExecSCSICmd, *PSRB_ExecSCSICmd, FAR *LPSRB_ExecSCSICmd;
  208926. typedef struct
  208927. {
  208928. BYTE SRB_Cmd;
  208929. BYTE SRB_Status;
  208930. BYTE SRB_HaId;
  208931. BYTE SRB_Flags;
  208932. DWORD SRB_Hdr_Rsvd;
  208933. } PACKED SRB, *PSRB, FAR *LPSRB;
  208934. #pragma pack()
  208935. struct CDDeviceInfo
  208936. {
  208937. char vendor[9];
  208938. char productId[17];
  208939. char rev[5];
  208940. char vendorSpec[21];
  208941. BYTE ha;
  208942. BYTE tgt;
  208943. BYTE lun;
  208944. char scsiDriveLetter; // will be 0 if not using scsi
  208945. };
  208946. class CDReadBuffer
  208947. {
  208948. public:
  208949. int startFrame;
  208950. int numFrames;
  208951. int dataStartOffset;
  208952. int dataLength;
  208953. int bufferSize;
  208954. HeapBlock<BYTE> buffer;
  208955. int index;
  208956. bool wantsIndex;
  208957. CDReadBuffer (const int numberOfFrames)
  208958. : startFrame (0),
  208959. numFrames (0),
  208960. dataStartOffset (0),
  208961. dataLength (0),
  208962. bufferSize (2352 * numberOfFrames),
  208963. buffer (bufferSize),
  208964. index (0),
  208965. wantsIndex (false)
  208966. {
  208967. }
  208968. bool isZero() const throw()
  208969. {
  208970. BYTE* p = buffer + dataStartOffset;
  208971. for (int i = dataLength; --i >= 0;)
  208972. if (*p++ != 0)
  208973. return false;
  208974. return true;
  208975. }
  208976. };
  208977. class CDDeviceHandle;
  208978. class CDController
  208979. {
  208980. public:
  208981. CDController();
  208982. virtual ~CDController();
  208983. virtual bool read (CDReadBuffer* t) = 0;
  208984. virtual void shutDown();
  208985. bool readAudio (CDReadBuffer* t, CDReadBuffer* overlapBuffer = 0);
  208986. int getLastIndex();
  208987. public:
  208988. bool initialised;
  208989. CDDeviceHandle* deviceInfo;
  208990. int framesToCheck, framesOverlap;
  208991. void prepare (SRB_ExecSCSICmd& s);
  208992. void perform (SRB_ExecSCSICmd& s);
  208993. void setPaused (bool paused);
  208994. };
  208995. #pragma pack(1)
  208996. struct TOCTRACK
  208997. {
  208998. BYTE rsvd;
  208999. BYTE ADR;
  209000. BYTE trackNumber;
  209001. BYTE rsvd2;
  209002. BYTE addr[4];
  209003. };
  209004. struct TOC
  209005. {
  209006. WORD tocLen;
  209007. BYTE firstTrack;
  209008. BYTE lastTrack;
  209009. TOCTRACK tracks[100];
  209010. };
  209011. #pragma pack()
  209012. enum
  209013. {
  209014. READTYPE_ANY = 0,
  209015. READTYPE_ATAPI1 = 1,
  209016. READTYPE_ATAPI2 = 2,
  209017. READTYPE_READ6 = 3,
  209018. READTYPE_READ10 = 4,
  209019. READTYPE_READ_D8 = 5,
  209020. READTYPE_READ_D4 = 6,
  209021. READTYPE_READ_D4_1 = 7,
  209022. READTYPE_READ10_2 = 8
  209023. };
  209024. class CDDeviceHandle
  209025. {
  209026. public:
  209027. CDDeviceHandle (const CDDeviceInfo* const device)
  209028. : scsiHandle (0),
  209029. readType (READTYPE_ANY),
  209030. controller (0)
  209031. {
  209032. memcpy (&info, device, sizeof (info));
  209033. }
  209034. ~CDDeviceHandle()
  209035. {
  209036. if (controller != 0)
  209037. {
  209038. controller->shutDown();
  209039. controller = 0;
  209040. }
  209041. if (scsiHandle != 0)
  209042. CloseHandle (scsiHandle);
  209043. }
  209044. bool readTOC (TOC* lpToc, bool useMSF);
  209045. bool readAudio (CDReadBuffer* buffer, CDReadBuffer* overlapBuffer = 0);
  209046. void openDrawer (bool shouldBeOpen);
  209047. CDDeviceInfo info;
  209048. HANDLE scsiHandle;
  209049. BYTE readType;
  209050. private:
  209051. ScopedPointer<CDController> controller;
  209052. bool testController (const int readType,
  209053. CDController* const newController,
  209054. CDReadBuffer* const bufferToUse);
  209055. };
  209056. DWORD (*fGetASPI32SupportInfo)(void);
  209057. DWORD (*fSendASPI32Command)(LPSRB);
  209058. static HINSTANCE winAspiLib = 0;
  209059. static bool usingScsi = false;
  209060. static bool initialised = false;
  209061. static bool InitialiseCDRipper()
  209062. {
  209063. if (! initialised)
  209064. {
  209065. initialised = true;
  209066. OSVERSIONINFO info;
  209067. info.dwOSVersionInfoSize = sizeof (info);
  209068. GetVersionEx (&info);
  209069. usingScsi = (info.dwPlatformId == VER_PLATFORM_WIN32_NT) && (info.dwMajorVersion > 4);
  209070. if (! usingScsi)
  209071. {
  209072. fGetASPI32SupportInfo = 0;
  209073. fSendASPI32Command = 0;
  209074. winAspiLib = LoadLibrary (_T("WNASPI32.DLL"));
  209075. if (winAspiLib != 0)
  209076. {
  209077. fGetASPI32SupportInfo = (DWORD(*)(void)) GetProcAddress (winAspiLib, "GetASPI32SupportInfo");
  209078. fSendASPI32Command = (DWORD(*)(LPSRB)) GetProcAddress (winAspiLib, "SendASPI32Command");
  209079. if (fGetASPI32SupportInfo == 0 || fSendASPI32Command == 0)
  209080. return false;
  209081. }
  209082. else
  209083. {
  209084. usingScsi = true;
  209085. }
  209086. }
  209087. }
  209088. return true;
  209089. }
  209090. static void DeinitialiseCDRipper()
  209091. {
  209092. if (winAspiLib != 0)
  209093. {
  209094. fGetASPI32SupportInfo = 0;
  209095. fSendASPI32Command = 0;
  209096. FreeLibrary (winAspiLib);
  209097. winAspiLib = 0;
  209098. }
  209099. initialised = false;
  209100. }
  209101. static HANDLE CreateSCSIDeviceHandle (char driveLetter)
  209102. {
  209103. TCHAR devicePath[] = { '\\', '\\', '.', '\\', driveLetter, ':', 0, 0 };
  209104. OSVERSIONINFO info;
  209105. info.dwOSVersionInfoSize = sizeof (info);
  209106. GetVersionEx (&info);
  209107. DWORD flags = GENERIC_READ;
  209108. if ((info.dwPlatformId == VER_PLATFORM_WIN32_NT) && (info.dwMajorVersion > 4))
  209109. flags = GENERIC_READ | GENERIC_WRITE;
  209110. HANDLE h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  209111. if (h == INVALID_HANDLE_VALUE)
  209112. {
  209113. flags ^= GENERIC_WRITE;
  209114. h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  209115. }
  209116. return h;
  209117. }
  209118. static DWORD performScsiPassThroughCommand (const LPSRB_ExecSCSICmd srb,
  209119. const char driveLetter,
  209120. HANDLE& deviceHandle,
  209121. const bool retryOnFailure = true)
  209122. {
  209123. SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER s;
  209124. zerostruct (s);
  209125. s.spt.Length = sizeof (SCSI_PASS_THROUGH);
  209126. s.spt.CdbLength = srb->SRB_CDBLen;
  209127. s.spt.DataIn = (BYTE) ((srb->SRB_Flags & SRB_DIR_IN)
  209128. ? SCSI_IOCTL_DATA_IN
  209129. : ((srb->SRB_Flags & SRB_DIR_OUT)
  209130. ? SCSI_IOCTL_DATA_OUT
  209131. : SCSI_IOCTL_DATA_UNSPECIFIED));
  209132. s.spt.DataTransferLength = srb->SRB_BufLen;
  209133. s.spt.TimeOutValue = 5;
  209134. s.spt.DataBuffer = srb->SRB_BufPointer;
  209135. s.spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  209136. memcpy (s.spt.Cdb, srb->CDBByte, srb->SRB_CDBLen);
  209137. srb->SRB_Status = SS_ERR;
  209138. srb->SRB_TargStat = 0x0004;
  209139. DWORD bytesReturned = 0;
  209140. if (DeviceIoControl (deviceHandle, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  209141. &s, sizeof (s),
  209142. &s, sizeof (s),
  209143. &bytesReturned, 0) != 0)
  209144. {
  209145. srb->SRB_Status = SS_COMP;
  209146. }
  209147. else if (retryOnFailure)
  209148. {
  209149. const DWORD error = GetLastError();
  209150. if ((error == ERROR_MEDIA_CHANGED) || (error == ERROR_INVALID_HANDLE))
  209151. {
  209152. if (error != ERROR_INVALID_HANDLE)
  209153. CloseHandle (deviceHandle);
  209154. deviceHandle = CreateSCSIDeviceHandle (driveLetter);
  209155. return performScsiPassThroughCommand (srb, driveLetter, deviceHandle, false);
  209156. }
  209157. }
  209158. return srb->SRB_Status;
  209159. }
  209160. // Controller types..
  209161. class ControllerType1 : public CDController
  209162. {
  209163. public:
  209164. ControllerType1() {}
  209165. ~ControllerType1() {}
  209166. bool read (CDReadBuffer* rb)
  209167. {
  209168. if (rb->numFrames * 2352 > rb->bufferSize)
  209169. return false;
  209170. SRB_ExecSCSICmd s;
  209171. prepare (s);
  209172. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  209173. s.SRB_BufLen = rb->bufferSize;
  209174. s.SRB_BufPointer = rb->buffer;
  209175. s.SRB_CDBLen = 12;
  209176. s.CDBByte[0] = 0xBE;
  209177. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  209178. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  209179. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  209180. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  209181. s.CDBByte[9] = (BYTE)((deviceInfo->readType == READTYPE_ATAPI1) ? 0x10 : 0xF0);
  209182. perform (s);
  209183. if (s.SRB_Status != SS_COMP)
  209184. return false;
  209185. rb->dataLength = rb->numFrames * 2352;
  209186. rb->dataStartOffset = 0;
  209187. return true;
  209188. }
  209189. };
  209190. class ControllerType2 : public CDController
  209191. {
  209192. public:
  209193. ControllerType2() {}
  209194. ~ControllerType2() {}
  209195. void shutDown()
  209196. {
  209197. if (initialised)
  209198. {
  209199. BYTE bufPointer[] = { 0, 0, 0, 8, 83, 0, 0, 0, 0, 0, 8, 0 };
  209200. SRB_ExecSCSICmd s;
  209201. prepare (s);
  209202. s.SRB_Flags = SRB_EVENT_NOTIFY | SRB_ENABLE_RESIDUAL_COUNT;
  209203. s.SRB_BufLen = 0x0C;
  209204. s.SRB_BufPointer = bufPointer;
  209205. s.SRB_CDBLen = 6;
  209206. s.CDBByte[0] = 0x15;
  209207. s.CDBByte[4] = 0x0C;
  209208. perform (s);
  209209. }
  209210. }
  209211. bool init()
  209212. {
  209213. SRB_ExecSCSICmd s;
  209214. s.SRB_Status = SS_ERR;
  209215. if (deviceInfo->readType == READTYPE_READ10_2)
  209216. {
  209217. BYTE bufPointer1[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 35, 6, 0, 0, 0, 0, 0, 128 };
  209218. BYTE bufPointer2[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 1, 6, 32, 7, 0, 0, 0, 0 };
  209219. for (int i = 0; i < 2; ++i)
  209220. {
  209221. prepare (s);
  209222. s.SRB_Flags = SRB_EVENT_NOTIFY;
  209223. s.SRB_BufLen = 0x14;
  209224. s.SRB_BufPointer = (i == 0) ? bufPointer1 : bufPointer2;
  209225. s.SRB_CDBLen = 6;
  209226. s.CDBByte[0] = 0x15;
  209227. s.CDBByte[1] = 0x10;
  209228. s.CDBByte[4] = 0x14;
  209229. perform (s);
  209230. if (s.SRB_Status != SS_COMP)
  209231. return false;
  209232. }
  209233. }
  209234. else
  209235. {
  209236. BYTE bufPointer[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48 };
  209237. prepare (s);
  209238. s.SRB_Flags = SRB_EVENT_NOTIFY;
  209239. s.SRB_BufLen = 0x0C;
  209240. s.SRB_BufPointer = bufPointer;
  209241. s.SRB_CDBLen = 6;
  209242. s.CDBByte[0] = 0x15;
  209243. s.CDBByte[4] = 0x0C;
  209244. perform (s);
  209245. }
  209246. return s.SRB_Status == SS_COMP;
  209247. }
  209248. bool read (CDReadBuffer* rb)
  209249. {
  209250. if (rb->numFrames * 2352 > rb->bufferSize)
  209251. return false;
  209252. if (!initialised)
  209253. {
  209254. initialised = init();
  209255. if (!initialised)
  209256. return false;
  209257. }
  209258. SRB_ExecSCSICmd s;
  209259. prepare (s);
  209260. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  209261. s.SRB_BufLen = rb->bufferSize;
  209262. s.SRB_BufPointer = rb->buffer;
  209263. s.SRB_CDBLen = 10;
  209264. s.CDBByte[0] = 0x28;
  209265. s.CDBByte[1] = (BYTE)(deviceInfo->info.lun << 5);
  209266. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  209267. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  209268. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  209269. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  209270. perform (s);
  209271. if (s.SRB_Status != SS_COMP)
  209272. return false;
  209273. rb->dataLength = rb->numFrames * 2352;
  209274. rb->dataStartOffset = 0;
  209275. return true;
  209276. }
  209277. };
  209278. class ControllerType3 : public CDController
  209279. {
  209280. public:
  209281. ControllerType3() {}
  209282. ~ControllerType3() {}
  209283. bool read (CDReadBuffer* rb)
  209284. {
  209285. if (rb->numFrames * 2352 > rb->bufferSize)
  209286. return false;
  209287. if (!initialised)
  209288. {
  209289. setPaused (false);
  209290. initialised = true;
  209291. }
  209292. SRB_ExecSCSICmd s;
  209293. prepare (s);
  209294. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  209295. s.SRB_BufLen = rb->numFrames * 2352;
  209296. s.SRB_BufPointer = rb->buffer;
  209297. s.SRB_CDBLen = 12;
  209298. s.CDBByte[0] = 0xD8;
  209299. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  209300. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  209301. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  209302. s.CDBByte[9] = (BYTE)(rb->numFrames & 0xFF);
  209303. perform (s);
  209304. if (s.SRB_Status != SS_COMP)
  209305. return false;
  209306. rb->dataLength = rb->numFrames * 2352;
  209307. rb->dataStartOffset = 0;
  209308. return true;
  209309. }
  209310. };
  209311. class ControllerType4 : public CDController
  209312. {
  209313. public:
  209314. ControllerType4() {}
  209315. ~ControllerType4() {}
  209316. bool selectD4Mode()
  209317. {
  209318. BYTE bufPointer[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 48 };
  209319. SRB_ExecSCSICmd s;
  209320. prepare (s);
  209321. s.SRB_Flags = SRB_EVENT_NOTIFY;
  209322. s.SRB_CDBLen = 6;
  209323. s.SRB_BufLen = 12;
  209324. s.SRB_BufPointer = bufPointer;
  209325. s.CDBByte[0] = 0x15;
  209326. s.CDBByte[1] = 0x10;
  209327. s.CDBByte[4] = 0x08;
  209328. perform (s);
  209329. return s.SRB_Status == SS_COMP;
  209330. }
  209331. bool read (CDReadBuffer* rb)
  209332. {
  209333. if (rb->numFrames * 2352 > rb->bufferSize)
  209334. return false;
  209335. if (!initialised)
  209336. {
  209337. setPaused (true);
  209338. if (deviceInfo->readType == READTYPE_READ_D4_1)
  209339. selectD4Mode();
  209340. initialised = true;
  209341. }
  209342. SRB_ExecSCSICmd s;
  209343. prepare (s);
  209344. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  209345. s.SRB_BufLen = rb->bufferSize;
  209346. s.SRB_BufPointer = rb->buffer;
  209347. s.SRB_CDBLen = 10;
  209348. s.CDBByte[0] = 0xD4;
  209349. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  209350. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  209351. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  209352. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  209353. perform (s);
  209354. if (s.SRB_Status != SS_COMP)
  209355. return false;
  209356. rb->dataLength = rb->numFrames * 2352;
  209357. rb->dataStartOffset = 0;
  209358. return true;
  209359. }
  209360. };
  209361. CDController::CDController() : initialised (false)
  209362. {
  209363. }
  209364. CDController::~CDController()
  209365. {
  209366. }
  209367. void CDController::prepare (SRB_ExecSCSICmd& s)
  209368. {
  209369. zerostruct (s);
  209370. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  209371. s.SRB_HaID = deviceInfo->info.ha;
  209372. s.SRB_Target = deviceInfo->info.tgt;
  209373. s.SRB_Lun = deviceInfo->info.lun;
  209374. s.SRB_SenseLen = SENSE_LEN;
  209375. }
  209376. void CDController::perform (SRB_ExecSCSICmd& s)
  209377. {
  209378. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  209379. s.SRB_PostProc = event;
  209380. ResetEvent (event);
  209381. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s,
  209382. deviceInfo->info.scsiDriveLetter,
  209383. deviceInfo->scsiHandle)
  209384. : fSendASPI32Command ((LPSRB)&s);
  209385. if (status == SS_PENDING)
  209386. WaitForSingleObject (event, 4000);
  209387. CloseHandle (event);
  209388. }
  209389. void CDController::setPaused (bool paused)
  209390. {
  209391. SRB_ExecSCSICmd s;
  209392. prepare (s);
  209393. s.SRB_Flags = SRB_EVENT_NOTIFY;
  209394. s.SRB_CDBLen = 10;
  209395. s.CDBByte[0] = 0x4B;
  209396. s.CDBByte[8] = (BYTE) (paused ? 0 : 1);
  209397. perform (s);
  209398. }
  209399. void CDController::shutDown()
  209400. {
  209401. }
  209402. bool CDController::readAudio (CDReadBuffer* rb, CDReadBuffer* overlapBuffer)
  209403. {
  209404. if (overlapBuffer != 0)
  209405. {
  209406. const bool canDoJitter = (overlapBuffer->bufferSize >= 2352 * framesToCheck);
  209407. const bool doJitter = canDoJitter && ! overlapBuffer->isZero();
  209408. if (doJitter
  209409. && overlapBuffer->startFrame > 0
  209410. && overlapBuffer->numFrames > 0
  209411. && overlapBuffer->dataLength > 0)
  209412. {
  209413. const int numFrames = rb->numFrames;
  209414. if (overlapBuffer->startFrame == (rb->startFrame - framesToCheck))
  209415. {
  209416. rb->startFrame -= framesOverlap;
  209417. if (framesToCheck < framesOverlap
  209418. && numFrames + framesOverlap <= rb->bufferSize / 2352)
  209419. rb->numFrames += framesOverlap;
  209420. }
  209421. else
  209422. {
  209423. overlapBuffer->dataLength = 0;
  209424. overlapBuffer->startFrame = 0;
  209425. overlapBuffer->numFrames = 0;
  209426. }
  209427. }
  209428. if (! read (rb))
  209429. return false;
  209430. if (doJitter)
  209431. {
  209432. const int checkLen = framesToCheck * 2352;
  209433. const int maxToCheck = rb->dataLength - checkLen;
  209434. if (overlapBuffer->dataLength == 0 || overlapBuffer->isZero())
  209435. return true;
  209436. BYTE* const p = overlapBuffer->buffer + overlapBuffer->dataStartOffset;
  209437. bool found = false;
  209438. for (int i = 0; i < maxToCheck; ++i)
  209439. {
  209440. if (memcmp (p, rb->buffer + i, checkLen) == 0)
  209441. {
  209442. i += checkLen;
  209443. rb->dataStartOffset = i;
  209444. rb->dataLength -= i;
  209445. rb->startFrame = overlapBuffer->startFrame + framesToCheck;
  209446. found = true;
  209447. break;
  209448. }
  209449. }
  209450. rb->numFrames = rb->dataLength / 2352;
  209451. rb->dataLength = 2352 * rb->numFrames;
  209452. if (!found)
  209453. return false;
  209454. }
  209455. if (canDoJitter)
  209456. {
  209457. memcpy (overlapBuffer->buffer,
  209458. rb->buffer + rb->dataStartOffset + 2352 * (rb->numFrames - framesToCheck),
  209459. 2352 * framesToCheck);
  209460. overlapBuffer->startFrame = rb->startFrame + rb->numFrames - framesToCheck;
  209461. overlapBuffer->numFrames = framesToCheck;
  209462. overlapBuffer->dataLength = 2352 * framesToCheck;
  209463. overlapBuffer->dataStartOffset = 0;
  209464. }
  209465. else
  209466. {
  209467. overlapBuffer->startFrame = 0;
  209468. overlapBuffer->numFrames = 0;
  209469. overlapBuffer->dataLength = 0;
  209470. }
  209471. return true;
  209472. }
  209473. else
  209474. {
  209475. return read (rb);
  209476. }
  209477. }
  209478. int CDController::getLastIndex()
  209479. {
  209480. char qdata[100];
  209481. SRB_ExecSCSICmd s;
  209482. prepare (s);
  209483. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  209484. s.SRB_BufLen = sizeof (qdata);
  209485. s.SRB_BufPointer = (BYTE*)qdata;
  209486. s.SRB_CDBLen = 12;
  209487. s.CDBByte[0] = 0x42;
  209488. s.CDBByte[1] = (BYTE)(deviceInfo->info.lun << 5);
  209489. s.CDBByte[2] = 64;
  209490. s.CDBByte[3] = 1; // get current position
  209491. s.CDBByte[7] = 0;
  209492. s.CDBByte[8] = (BYTE)sizeof (qdata);
  209493. perform (s);
  209494. if (s.SRB_Status == SS_COMP)
  209495. return qdata[7];
  209496. return 0;
  209497. }
  209498. bool CDDeviceHandle::readTOC (TOC* lpToc, bool useMSF)
  209499. {
  209500. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  209501. SRB_ExecSCSICmd s;
  209502. zerostruct (s);
  209503. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  209504. s.SRB_HaID = info.ha;
  209505. s.SRB_Target = info.tgt;
  209506. s.SRB_Lun = info.lun;
  209507. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  209508. s.SRB_BufLen = 0x324;
  209509. s.SRB_BufPointer = (BYTE*)lpToc;
  209510. s.SRB_SenseLen = 0x0E;
  209511. s.SRB_CDBLen = 0x0A;
  209512. s.SRB_PostProc = event;
  209513. s.CDBByte[0] = 0x43;
  209514. s.CDBByte[1] = (BYTE)(useMSF ? 0x02 : 0x00);
  209515. s.CDBByte[7] = 0x03;
  209516. s.CDBByte[8] = 0x24;
  209517. ResetEvent (event);
  209518. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s, info.scsiDriveLetter, scsiHandle)
  209519. : fSendASPI32Command ((LPSRB)&s);
  209520. if (status == SS_PENDING)
  209521. WaitForSingleObject (event, 4000);
  209522. CloseHandle (event);
  209523. return (s.SRB_Status == SS_COMP);
  209524. }
  209525. bool CDDeviceHandle::readAudio (CDReadBuffer* const buffer,
  209526. CDReadBuffer* const overlapBuffer)
  209527. {
  209528. if (controller == 0)
  209529. {
  209530. testController (READTYPE_ATAPI2, new ControllerType1(), buffer)
  209531. || testController (READTYPE_ATAPI1, new ControllerType1(), buffer)
  209532. || testController (READTYPE_READ10_2, new ControllerType2(), buffer)
  209533. || testController (READTYPE_READ10, new ControllerType2(), buffer)
  209534. || testController (READTYPE_READ_D8, new ControllerType3(), buffer)
  209535. || testController (READTYPE_READ_D4, new ControllerType4(), buffer)
  209536. || testController (READTYPE_READ_D4_1, new ControllerType4(), buffer);
  209537. }
  209538. buffer->index = 0;
  209539. if ((controller != 0)
  209540. && controller->readAudio (buffer, overlapBuffer))
  209541. {
  209542. if (buffer->wantsIndex)
  209543. buffer->index = controller->getLastIndex();
  209544. return true;
  209545. }
  209546. return false;
  209547. }
  209548. void CDDeviceHandle::openDrawer (bool shouldBeOpen)
  209549. {
  209550. if (shouldBeOpen)
  209551. {
  209552. if (controller != 0)
  209553. {
  209554. controller->shutDown();
  209555. controller = 0;
  209556. }
  209557. if (scsiHandle != 0)
  209558. {
  209559. CloseHandle (scsiHandle);
  209560. scsiHandle = 0;
  209561. }
  209562. }
  209563. SRB_ExecSCSICmd s;
  209564. zerostruct (s);
  209565. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  209566. s.SRB_HaID = info.ha;
  209567. s.SRB_Target = info.tgt;
  209568. s.SRB_Lun = info.lun;
  209569. s.SRB_SenseLen = SENSE_LEN;
  209570. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  209571. s.SRB_BufLen = 0;
  209572. s.SRB_BufPointer = 0;
  209573. s.SRB_CDBLen = 12;
  209574. s.CDBByte[0] = 0x1b;
  209575. s.CDBByte[1] = (BYTE)(info.lun << 5);
  209576. s.CDBByte[4] = (BYTE)((shouldBeOpen) ? 2 : 3);
  209577. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  209578. s.SRB_PostProc = event;
  209579. ResetEvent (event);
  209580. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s, info.scsiDriveLetter, scsiHandle)
  209581. : fSendASPI32Command ((LPSRB)&s);
  209582. if (status == SS_PENDING)
  209583. WaitForSingleObject (event, 4000);
  209584. CloseHandle (event);
  209585. }
  209586. bool CDDeviceHandle::testController (const int type,
  209587. CDController* const newController,
  209588. CDReadBuffer* const rb)
  209589. {
  209590. controller = newController;
  209591. readType = (BYTE)type;
  209592. controller->deviceInfo = this;
  209593. controller->framesToCheck = 1;
  209594. controller->framesOverlap = 3;
  209595. bool passed = false;
  209596. memset (rb->buffer, 0xcd, rb->bufferSize);
  209597. if (controller->read (rb))
  209598. {
  209599. passed = true;
  209600. int* p = (int*) (rb->buffer + rb->dataStartOffset);
  209601. int wrong = 0;
  209602. for (int i = rb->dataLength / 4; --i >= 0;)
  209603. {
  209604. if (*p++ == (int) 0xcdcdcdcd)
  209605. {
  209606. if (++wrong == 4)
  209607. {
  209608. passed = false;
  209609. break;
  209610. }
  209611. }
  209612. else
  209613. {
  209614. wrong = 0;
  209615. }
  209616. }
  209617. }
  209618. if (! passed)
  209619. {
  209620. controller->shutDown();
  209621. controller = 0;
  209622. }
  209623. return passed;
  209624. }
  209625. static void GetAspiDeviceInfo (CDDeviceInfo* dev, BYTE ha, BYTE tgt, BYTE lun)
  209626. {
  209627. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  209628. const int bufSize = 128;
  209629. BYTE buffer[bufSize];
  209630. zeromem (buffer, bufSize);
  209631. SRB_ExecSCSICmd s;
  209632. zerostruct (s);
  209633. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  209634. s.SRB_HaID = ha;
  209635. s.SRB_Target = tgt;
  209636. s.SRB_Lun = lun;
  209637. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  209638. s.SRB_BufLen = bufSize;
  209639. s.SRB_BufPointer = buffer;
  209640. s.SRB_SenseLen = SENSE_LEN;
  209641. s.SRB_CDBLen = 6;
  209642. s.SRB_PostProc = event;
  209643. s.CDBByte[0] = SCSI_INQUIRY;
  209644. s.CDBByte[4] = 100;
  209645. ResetEvent (event);
  209646. if (fSendASPI32Command ((LPSRB)&s) == SS_PENDING)
  209647. WaitForSingleObject (event, 4000);
  209648. CloseHandle (event);
  209649. if (s.SRB_Status == SS_COMP)
  209650. {
  209651. memcpy (dev->vendor, &buffer[8], 8);
  209652. memcpy (dev->productId, &buffer[16], 16);
  209653. memcpy (dev->rev, &buffer[32], 4);
  209654. memcpy (dev->vendorSpec, &buffer[36], 20);
  209655. }
  209656. }
  209657. static int FindCDDevices (CDDeviceInfo* const list,
  209658. int maxItems)
  209659. {
  209660. int count = 0;
  209661. if (usingScsi)
  209662. {
  209663. for (char driveLetter = 'b'; driveLetter <= 'z'; ++driveLetter)
  209664. {
  209665. TCHAR drivePath[8];
  209666. drivePath[0] = driveLetter;
  209667. drivePath[1] = ':';
  209668. drivePath[2] = '\\';
  209669. drivePath[3] = 0;
  209670. if (GetDriveType (drivePath) == DRIVE_CDROM)
  209671. {
  209672. HANDLE h = CreateSCSIDeviceHandle (driveLetter);
  209673. if (h != INVALID_HANDLE_VALUE)
  209674. {
  209675. BYTE buffer[100], passThroughStruct[1024];
  209676. zeromem (buffer, sizeof (buffer));
  209677. zeromem (passThroughStruct, sizeof (passThroughStruct));
  209678. PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER p = (PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER)passThroughStruct;
  209679. p->spt.Length = sizeof (SCSI_PASS_THROUGH);
  209680. p->spt.CdbLength = 6;
  209681. p->spt.SenseInfoLength = 24;
  209682. p->spt.DataIn = SCSI_IOCTL_DATA_IN;
  209683. p->spt.DataTransferLength = 100;
  209684. p->spt.TimeOutValue = 2;
  209685. p->spt.DataBuffer = buffer;
  209686. p->spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  209687. p->spt.Cdb[0] = 0x12;
  209688. p->spt.Cdb[4] = 100;
  209689. DWORD bytesReturned = 0;
  209690. if (DeviceIoControl (h, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  209691. p, sizeof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER),
  209692. p, sizeof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER),
  209693. &bytesReturned, 0) != 0)
  209694. {
  209695. zeromem (&list[count], sizeof (CDDeviceInfo));
  209696. list[count].scsiDriveLetter = driveLetter;
  209697. memcpy (list[count].vendor, &buffer[8], 8);
  209698. memcpy (list[count].productId, &buffer[16], 16);
  209699. memcpy (list[count].rev, &buffer[32], 4);
  209700. memcpy (list[count].vendorSpec, &buffer[36], 20);
  209701. zeromem (passThroughStruct, sizeof (passThroughStruct));
  209702. PSCSI_ADDRESS scsiAddr = (PSCSI_ADDRESS)passThroughStruct;
  209703. scsiAddr->Length = sizeof (SCSI_ADDRESS);
  209704. if (DeviceIoControl (h, IOCTL_SCSI_GET_ADDRESS,
  209705. 0, 0, scsiAddr, sizeof (SCSI_ADDRESS),
  209706. &bytesReturned, 0) != 0)
  209707. {
  209708. list[count].ha = scsiAddr->PortNumber;
  209709. list[count].tgt = scsiAddr->TargetId;
  209710. list[count].lun = scsiAddr->Lun;
  209711. ++count;
  209712. }
  209713. }
  209714. CloseHandle (h);
  209715. }
  209716. }
  209717. }
  209718. }
  209719. else
  209720. {
  209721. const DWORD d = fGetASPI32SupportInfo();
  209722. BYTE status = HIBYTE (LOWORD (d));
  209723. if (status != SS_COMP || status == SS_NO_ADAPTERS)
  209724. return 0;
  209725. const int numAdapters = LOBYTE (LOWORD (d));
  209726. for (BYTE ha = 0; ha < numAdapters; ++ha)
  209727. {
  209728. SRB_HAInquiry s;
  209729. zerostruct (s);
  209730. s.SRB_Cmd = SC_HA_INQUIRY;
  209731. s.SRB_HaID = ha;
  209732. fSendASPI32Command ((LPSRB)&s);
  209733. if (s.SRB_Status == SS_COMP)
  209734. {
  209735. maxItems = (int)s.HA_Unique[3];
  209736. if (maxItems == 0)
  209737. maxItems = 8;
  209738. for (BYTE tgt = 0; tgt < maxItems; ++tgt)
  209739. {
  209740. for (BYTE lun = 0; lun < 8; ++lun)
  209741. {
  209742. SRB_GDEVBlock sb;
  209743. zerostruct (sb);
  209744. sb.SRB_Cmd = SC_GET_DEV_TYPE;
  209745. sb.SRB_HaID = ha;
  209746. sb.SRB_Target = tgt;
  209747. sb.SRB_Lun = lun;
  209748. fSendASPI32Command ((LPSRB) &sb);
  209749. if (sb.SRB_Status == SS_COMP
  209750. && sb.SRB_DeviceType == DTYPE_CROM)
  209751. {
  209752. zeromem (&list[count], sizeof (CDDeviceInfo));
  209753. list[count].ha = ha;
  209754. list[count].tgt = tgt;
  209755. list[count].lun = lun;
  209756. GetAspiDeviceInfo (&(list[count]), ha, tgt, lun);
  209757. ++count;
  209758. }
  209759. }
  209760. }
  209761. }
  209762. }
  209763. }
  209764. return count;
  209765. }
  209766. static int ripperUsers = 0;
  209767. static bool initialisedOk = false;
  209768. class DeinitialiseTimer : private Timer,
  209769. private DeletedAtShutdown
  209770. {
  209771. DeinitialiseTimer (const DeinitialiseTimer&);
  209772. DeinitialiseTimer& operator= (const DeinitialiseTimer&);
  209773. public:
  209774. DeinitialiseTimer()
  209775. {
  209776. startTimer (4000);
  209777. }
  209778. ~DeinitialiseTimer()
  209779. {
  209780. if (--ripperUsers == 0)
  209781. DeinitialiseCDRipper();
  209782. }
  209783. void timerCallback()
  209784. {
  209785. delete this;
  209786. }
  209787. juce_UseDebuggingNewOperator
  209788. };
  209789. static void incUserCount()
  209790. {
  209791. if (ripperUsers++ == 0)
  209792. initialisedOk = InitialiseCDRipper();
  209793. }
  209794. static void decUserCount()
  209795. {
  209796. new DeinitialiseTimer();
  209797. }
  209798. struct CDDeviceWrapper
  209799. {
  209800. ScopedPointer<CDDeviceHandle> cdH;
  209801. ScopedPointer<CDReadBuffer> overlapBuffer;
  209802. bool jitter;
  209803. };
  209804. static int getAddressOf (const TOCTRACK* const t)
  209805. {
  209806. return (((DWORD)t->addr[0]) << 24) + (((DWORD)t->addr[1]) << 16) +
  209807. (((DWORD)t->addr[2]) << 8) + ((DWORD)t->addr[3]);
  209808. }
  209809. static int getMSFAddressOf (const TOCTRACK* const t)
  209810. {
  209811. return 60 * t->addr[1] + t->addr[2];
  209812. }
  209813. static const int samplesPerFrame = 44100 / 75;
  209814. static const int bytesPerFrame = samplesPerFrame * 4;
  209815. static CDDeviceHandle* openHandle (const CDDeviceInfo* const device)
  209816. {
  209817. SRB_GDEVBlock s;
  209818. zerostruct (s);
  209819. s.SRB_Cmd = SC_GET_DEV_TYPE;
  209820. s.SRB_HaID = device->ha;
  209821. s.SRB_Target = device->tgt;
  209822. s.SRB_Lun = device->lun;
  209823. if (usingScsi)
  209824. {
  209825. HANDLE h = CreateSCSIDeviceHandle (device->scsiDriveLetter);
  209826. if (h != INVALID_HANDLE_VALUE)
  209827. {
  209828. CDDeviceHandle* cdh = new CDDeviceHandle (device);
  209829. cdh->scsiHandle = h;
  209830. return cdh;
  209831. }
  209832. }
  209833. else
  209834. {
  209835. if (fSendASPI32Command ((LPSRB)&s) == SS_COMP
  209836. && s.SRB_DeviceType == DTYPE_CROM)
  209837. {
  209838. return new CDDeviceHandle (device);
  209839. }
  209840. }
  209841. return 0;
  209842. }
  209843. }
  209844. const StringArray AudioCDReader::getAvailableCDNames()
  209845. {
  209846. using namespace CDReaderHelpers;
  209847. StringArray results;
  209848. incUserCount();
  209849. if (initialisedOk)
  209850. {
  209851. CDDeviceInfo list[8];
  209852. const int num = FindCDDevices (list, 8);
  209853. decUserCount();
  209854. for (int i = 0; i < num; ++i)
  209855. {
  209856. String s;
  209857. if (list[i].scsiDriveLetter > 0)
  209858. s << String::charToString (list[i].scsiDriveLetter).toUpperCase() << ": ";
  209859. s << String (list[i].vendor).trim()
  209860. << ' ' << String (list[i].productId).trim()
  209861. << ' ' << String (list[i].rev).trim();
  209862. results.add (s);
  209863. }
  209864. }
  209865. return results;
  209866. }
  209867. AudioCDReader* AudioCDReader::createReaderForCD (const int deviceIndex)
  209868. {
  209869. using namespace CDReaderHelpers;
  209870. incUserCount();
  209871. if (initialisedOk)
  209872. {
  209873. CDDeviceInfo list[8];
  209874. const int num = FindCDDevices (list, 8);
  209875. if (((unsigned int) deviceIndex) < (unsigned int) num)
  209876. {
  209877. CDDeviceHandle* const handle = openHandle (&(list[deviceIndex]));
  209878. if (handle != 0)
  209879. {
  209880. CDDeviceWrapper* const d = new CDDeviceWrapper();
  209881. d->cdH = handle;
  209882. d->overlapBuffer = new CDReadBuffer(3);
  209883. return new AudioCDReader (d);
  209884. }
  209885. }
  209886. }
  209887. decUserCount();
  209888. return 0;
  209889. }
  209890. AudioCDReader::AudioCDReader (void* handle_)
  209891. : AudioFormatReader (0, "CD Audio"),
  209892. handle (handle_),
  209893. indexingEnabled (false),
  209894. lastIndex (0),
  209895. firstFrameInBuffer (0),
  209896. samplesInBuffer (0)
  209897. {
  209898. using namespace CDReaderHelpers;
  209899. jassert (handle_ != 0);
  209900. refreshTrackLengths();
  209901. sampleRate = 44100.0;
  209902. bitsPerSample = 16;
  209903. lengthInSamples = getPositionOfTrackStart (numTracks);
  209904. numChannels = 2;
  209905. usesFloatingPointData = false;
  209906. buffer.setSize (4 * bytesPerFrame, true);
  209907. }
  209908. AudioCDReader::~AudioCDReader()
  209909. {
  209910. using namespace CDReaderHelpers;
  209911. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  209912. delete device;
  209913. decUserCount();
  209914. }
  209915. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  209916. int64 startSampleInFile, int numSamples)
  209917. {
  209918. using namespace CDReaderHelpers;
  209919. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  209920. bool ok = true;
  209921. while (numSamples > 0)
  209922. {
  209923. const int bufferStartSample = firstFrameInBuffer * samplesPerFrame;
  209924. const int bufferEndSample = bufferStartSample + samplesInBuffer;
  209925. if (startSampleInFile >= bufferStartSample
  209926. && startSampleInFile < bufferEndSample)
  209927. {
  209928. const int toDo = (int) jmin ((int64) numSamples, bufferEndSample - startSampleInFile);
  209929. int* const l = destSamples[0] + startOffsetInDestBuffer;
  209930. int* const r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  209931. const short* src = (const short*) buffer.getData();
  209932. src += 2 * (startSampleInFile - bufferStartSample);
  209933. for (int i = 0; i < toDo; ++i)
  209934. {
  209935. l[i] = src [i << 1] << 16;
  209936. if (r != 0)
  209937. r[i] = src [(i << 1) + 1] << 16;
  209938. }
  209939. startOffsetInDestBuffer += toDo;
  209940. startSampleInFile += toDo;
  209941. numSamples -= toDo;
  209942. }
  209943. else
  209944. {
  209945. const int framesInBuffer = buffer.getSize() / bytesPerFrame;
  209946. const int frameNeeded = (int) (startSampleInFile / samplesPerFrame);
  209947. if (firstFrameInBuffer + framesInBuffer != frameNeeded)
  209948. {
  209949. device->overlapBuffer->dataLength = 0;
  209950. device->overlapBuffer->startFrame = 0;
  209951. device->overlapBuffer->numFrames = 0;
  209952. device->jitter = false;
  209953. }
  209954. firstFrameInBuffer = frameNeeded;
  209955. lastIndex = 0;
  209956. CDReadBuffer readBuffer (framesInBuffer + 4);
  209957. readBuffer.wantsIndex = indexingEnabled;
  209958. int i;
  209959. for (i = 5; --i >= 0;)
  209960. {
  209961. readBuffer.startFrame = frameNeeded;
  209962. readBuffer.numFrames = framesInBuffer;
  209963. if (device->cdH->readAudio (&readBuffer, (device->jitter) ? device->overlapBuffer : 0))
  209964. break;
  209965. else
  209966. device->overlapBuffer->dataLength = 0;
  209967. }
  209968. if (i >= 0)
  209969. {
  209970. memcpy ((char*) buffer.getData(),
  209971. readBuffer.buffer + readBuffer.dataStartOffset,
  209972. readBuffer.dataLength);
  209973. samplesInBuffer = readBuffer.dataLength >> 2;
  209974. lastIndex = readBuffer.index;
  209975. }
  209976. else
  209977. {
  209978. int* l = destSamples[0] + startOffsetInDestBuffer;
  209979. int* r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  209980. while (--numSamples >= 0)
  209981. {
  209982. *l++ = 0;
  209983. if (r != 0)
  209984. *r++ = 0;
  209985. }
  209986. // sometimes the read fails for just the very last couple of blocks, so
  209987. // we'll ignore and errors in the last half-second of the disk..
  209988. ok = startSampleInFile > (trackStarts [numTracks] - 20000);
  209989. break;
  209990. }
  209991. }
  209992. }
  209993. return ok;
  209994. }
  209995. bool AudioCDReader::isCDStillPresent() const
  209996. {
  209997. using namespace CDReaderHelpers;
  209998. TOC toc;
  209999. zerostruct (toc);
  210000. return ((CDDeviceWrapper*) handle)->cdH->readTOC (&toc, false);
  210001. }
  210002. int AudioCDReader::getNumTracks() const
  210003. {
  210004. return numTracks;
  210005. }
  210006. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  210007. {
  210008. using namespace CDReaderHelpers;
  210009. return (trackNum >= 0 && trackNum <= numTracks) ? trackStarts [trackNum] * samplesPerFrame
  210010. : 0;
  210011. }
  210012. void AudioCDReader::refreshTrackLengths()
  210013. {
  210014. using namespace CDReaderHelpers;
  210015. zeromem (trackStarts, sizeof (trackStarts));
  210016. zeromem (audioTracks, sizeof (audioTracks));
  210017. TOC toc;
  210018. zerostruct (toc);
  210019. if (((CDDeviceWrapper*)handle)->cdH->readTOC (&toc, false))
  210020. {
  210021. numTracks = 1 + toc.lastTrack - toc.firstTrack;
  210022. for (int i = 0; i <= numTracks; ++i)
  210023. {
  210024. trackStarts[i] = getAddressOf (&toc.tracks[i]);
  210025. audioTracks[i] = ((toc.tracks[i].ADR & 4) == 0);
  210026. }
  210027. }
  210028. else
  210029. {
  210030. numTracks = 0;
  210031. }
  210032. }
  210033. bool AudioCDReader::isTrackAudio (int trackNum) const
  210034. {
  210035. return (trackNum >= 0 && trackNum <= numTracks) ? audioTracks [trackNum]
  210036. : false;
  210037. }
  210038. void AudioCDReader::enableIndexScanning (bool b)
  210039. {
  210040. indexingEnabled = b;
  210041. }
  210042. int AudioCDReader::getLastIndex() const
  210043. {
  210044. return lastIndex;
  210045. }
  210046. const int framesPerIndexRead = 4;
  210047. int AudioCDReader::getIndexAt (int samplePos)
  210048. {
  210049. using namespace CDReaderHelpers;
  210050. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  210051. const int frameNeeded = samplePos / samplesPerFrame;
  210052. device->overlapBuffer->dataLength = 0;
  210053. device->overlapBuffer->startFrame = 0;
  210054. device->overlapBuffer->numFrames = 0;
  210055. device->jitter = false;
  210056. firstFrameInBuffer = 0;
  210057. lastIndex = 0;
  210058. CDReadBuffer readBuffer (4 + framesPerIndexRead);
  210059. readBuffer.wantsIndex = true;
  210060. int i;
  210061. for (i = 5; --i >= 0;)
  210062. {
  210063. readBuffer.startFrame = frameNeeded;
  210064. readBuffer.numFrames = framesPerIndexRead;
  210065. if (device->cdH->readAudio (&readBuffer, (false) ? device->overlapBuffer : 0))
  210066. break;
  210067. }
  210068. if (i >= 0)
  210069. return readBuffer.index;
  210070. return -1;
  210071. }
  210072. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  210073. {
  210074. using namespace CDReaderHelpers;
  210075. Array <int> indexes;
  210076. const int trackStart = getPositionOfTrackStart (trackNumber);
  210077. const int trackEnd = getPositionOfTrackStart (trackNumber + 1);
  210078. bool needToScan = true;
  210079. if (trackEnd - trackStart > 20 * 44100)
  210080. {
  210081. // check the end of the track for indexes before scanning the whole thing
  210082. needToScan = false;
  210083. int pos = jmax (trackStart, trackEnd - 44100 * 5);
  210084. bool seenAnIndex = false;
  210085. while (pos <= trackEnd - samplesPerFrame)
  210086. {
  210087. const int index = getIndexAt (pos);
  210088. if (index == 0)
  210089. {
  210090. // lead-out, so skip back a bit if we've not found any indexes yet..
  210091. if (seenAnIndex)
  210092. break;
  210093. pos -= 44100 * 5;
  210094. if (pos < trackStart)
  210095. break;
  210096. }
  210097. else
  210098. {
  210099. if (index > 0)
  210100. seenAnIndex = true;
  210101. if (index > 1)
  210102. {
  210103. needToScan = true;
  210104. break;
  210105. }
  210106. pos += samplesPerFrame * framesPerIndexRead;
  210107. }
  210108. }
  210109. }
  210110. if (needToScan)
  210111. {
  210112. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  210113. int pos = trackStart;
  210114. int last = -1;
  210115. while (pos < trackEnd - samplesPerFrame * 10)
  210116. {
  210117. const int frameNeeded = pos / samplesPerFrame;
  210118. device->overlapBuffer->dataLength = 0;
  210119. device->overlapBuffer->startFrame = 0;
  210120. device->overlapBuffer->numFrames = 0;
  210121. device->jitter = false;
  210122. firstFrameInBuffer = 0;
  210123. CDReadBuffer readBuffer (4);
  210124. readBuffer.wantsIndex = true;
  210125. int i;
  210126. for (i = 5; --i >= 0;)
  210127. {
  210128. readBuffer.startFrame = frameNeeded;
  210129. readBuffer.numFrames = framesPerIndexRead;
  210130. if (device->cdH->readAudio (&readBuffer, (false) ? device->overlapBuffer : 0))
  210131. break;
  210132. }
  210133. if (i < 0)
  210134. break;
  210135. if (readBuffer.index > last && readBuffer.index > 1)
  210136. {
  210137. last = readBuffer.index;
  210138. indexes.add (pos);
  210139. }
  210140. pos += samplesPerFrame * framesPerIndexRead;
  210141. }
  210142. indexes.removeValue (trackStart);
  210143. }
  210144. return indexes;
  210145. }
  210146. int AudioCDReader::getCDDBId()
  210147. {
  210148. using namespace CDReaderHelpers;
  210149. refreshTrackLengths();
  210150. if (numTracks > 0)
  210151. {
  210152. TOC toc;
  210153. zerostruct (toc);
  210154. if (((CDDeviceWrapper*) handle)->cdH->readTOC (&toc, true))
  210155. {
  210156. int n = 0;
  210157. for (int i = numTracks; --i >= 0;)
  210158. {
  210159. int j = getMSFAddressOf (&toc.tracks[i]);
  210160. while (j > 0)
  210161. {
  210162. n += (j % 10);
  210163. j /= 10;
  210164. }
  210165. }
  210166. if (n != 0)
  210167. {
  210168. const int t = getMSFAddressOf (&toc.tracks[numTracks])
  210169. - getMSFAddressOf (&toc.tracks[0]);
  210170. return ((n % 0xff) << 24) | (t << 8) | numTracks;
  210171. }
  210172. }
  210173. }
  210174. return 0;
  210175. }
  210176. void AudioCDReader::ejectDisk()
  210177. {
  210178. using namespace CDReaderHelpers;
  210179. ((CDDeviceWrapper*) handle)->cdH->openDrawer (true);
  210180. }
  210181. #endif
  210182. #if JUCE_USE_CDBURNER
  210183. static IDiscRecorder* enumCDBurners (StringArray* list, int indexToOpen, IDiscMaster** master)
  210184. {
  210185. CoInitialize (0);
  210186. IDiscMaster* dm;
  210187. IDiscRecorder* result = 0;
  210188. if (SUCCEEDED (CoCreateInstance (CLSID_MSDiscMasterObj, 0,
  210189. CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER,
  210190. IID_IDiscMaster,
  210191. (void**) &dm)))
  210192. {
  210193. if (SUCCEEDED (dm->Open()))
  210194. {
  210195. IEnumDiscRecorders* drEnum = 0;
  210196. if (SUCCEEDED (dm->EnumDiscRecorders (&drEnum)))
  210197. {
  210198. IDiscRecorder* dr = 0;
  210199. DWORD dummy;
  210200. int index = 0;
  210201. while (drEnum->Next (1, &dr, &dummy) == S_OK)
  210202. {
  210203. if (indexToOpen == index)
  210204. {
  210205. result = dr;
  210206. break;
  210207. }
  210208. else if (list != 0)
  210209. {
  210210. BSTR path;
  210211. if (SUCCEEDED (dr->GetPath (&path)))
  210212. list->add ((const WCHAR*) path);
  210213. }
  210214. ++index;
  210215. dr->Release();
  210216. }
  210217. drEnum->Release();
  210218. }
  210219. if (master == 0)
  210220. dm->Close();
  210221. }
  210222. if (master != 0)
  210223. *master = dm;
  210224. else
  210225. dm->Release();
  210226. }
  210227. return result;
  210228. }
  210229. class AudioCDBurner::Pimpl : public ComBaseClassHelper <IDiscMasterProgressEvents>,
  210230. public Timer
  210231. {
  210232. public:
  210233. Pimpl (AudioCDBurner& owner_, IDiscMaster* discMaster_, IDiscRecorder* discRecorder_)
  210234. : owner (owner_), discMaster (discMaster_), discRecorder (discRecorder_), redbook (0),
  210235. listener (0), progress (0), shouldCancel (false)
  210236. {
  210237. HRESULT hr = discMaster->SetActiveDiscMasterFormat (IID_IRedbookDiscMaster, (void**) &redbook);
  210238. jassert (SUCCEEDED (hr));
  210239. hr = discMaster->SetActiveDiscRecorder (discRecorder);
  210240. //jassert (SUCCEEDED (hr));
  210241. lastState = getDiskState();
  210242. startTimer (2000);
  210243. }
  210244. ~Pimpl() {}
  210245. void releaseObjects()
  210246. {
  210247. discRecorder->Close();
  210248. if (redbook != 0)
  210249. redbook->Release();
  210250. discRecorder->Release();
  210251. discMaster->Release();
  210252. Release();
  210253. }
  210254. HRESULT __stdcall QueryCancel (boolean* pbCancel)
  210255. {
  210256. if (listener != 0 && ! shouldCancel)
  210257. shouldCancel = listener->audioCDBurnProgress (progress);
  210258. *pbCancel = shouldCancel;
  210259. return S_OK;
  210260. }
  210261. HRESULT __stdcall NotifyBlockProgress (long nCompleted, long nTotal)
  210262. {
  210263. progress = nCompleted / (float) nTotal;
  210264. shouldCancel = listener != 0 && listener->audioCDBurnProgress (progress);
  210265. return E_NOTIMPL;
  210266. }
  210267. HRESULT __stdcall NotifyPnPActivity (void) { return E_NOTIMPL; }
  210268. HRESULT __stdcall NotifyAddProgress (long /*nCompletedSteps*/, long /*nTotalSteps*/) { return E_NOTIMPL; }
  210269. HRESULT __stdcall NotifyTrackProgress (long /*nCurrentTrack*/, long /*nTotalTracks*/) { return E_NOTIMPL; }
  210270. HRESULT __stdcall NotifyPreparingBurn (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  210271. HRESULT __stdcall NotifyClosingDisc (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  210272. HRESULT __stdcall NotifyBurnComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  210273. HRESULT __stdcall NotifyEraseComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  210274. class ScopedDiscOpener
  210275. {
  210276. public:
  210277. ScopedDiscOpener (Pimpl& p) : pimpl (p) { pimpl.discRecorder->OpenExclusive(); }
  210278. ~ScopedDiscOpener() { pimpl.discRecorder->Close(); }
  210279. private:
  210280. Pimpl& pimpl;
  210281. ScopedDiscOpener (const ScopedDiscOpener&);
  210282. ScopedDiscOpener& operator= (const ScopedDiscOpener&);
  210283. };
  210284. DiskState getDiskState()
  210285. {
  210286. const ScopedDiscOpener opener (*this);
  210287. long type, flags;
  210288. HRESULT hr = discRecorder->QueryMediaType (&type, &flags);
  210289. if (FAILED (hr))
  210290. return unknown;
  210291. if (type != 0 && (flags & MEDIA_WRITABLE) != 0)
  210292. return writableDiskPresent;
  210293. if (type == 0)
  210294. return noDisc;
  210295. else
  210296. return readOnlyDiskPresent;
  210297. }
  210298. int getIntProperty (const LPOLESTR name, const int defaultReturn) const
  210299. {
  210300. ComSmartPtr<IPropertyStorage> prop;
  210301. if (FAILED (discRecorder->GetRecorderProperties (&prop)))
  210302. return defaultReturn;
  210303. PROPSPEC iPropSpec;
  210304. iPropSpec.ulKind = PRSPEC_LPWSTR;
  210305. iPropSpec.lpwstr = name;
  210306. PROPVARIANT iPropVariant;
  210307. return FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant))
  210308. ? defaultReturn : (int) iPropVariant.lVal;
  210309. }
  210310. bool setIntProperty (const LPOLESTR name, const int value) const
  210311. {
  210312. ComSmartPtr<IPropertyStorage> prop;
  210313. if (FAILED (discRecorder->GetRecorderProperties (&prop)))
  210314. return false;
  210315. PROPSPEC iPropSpec;
  210316. iPropSpec.ulKind = PRSPEC_LPWSTR;
  210317. iPropSpec.lpwstr = name;
  210318. PROPVARIANT iPropVariant;
  210319. if (FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant)))
  210320. return false;
  210321. iPropVariant.lVal = (long) value;
  210322. return SUCCEEDED (prop->WriteMultiple (1, &iPropSpec, &iPropVariant, iPropVariant.vt))
  210323. && SUCCEEDED (discRecorder->SetRecorderProperties (prop));
  210324. }
  210325. void timerCallback()
  210326. {
  210327. const DiskState state = getDiskState();
  210328. if (state != lastState)
  210329. {
  210330. lastState = state;
  210331. owner.sendChangeMessage (&owner);
  210332. }
  210333. }
  210334. AudioCDBurner& owner;
  210335. DiskState lastState;
  210336. IDiscMaster* discMaster;
  210337. IDiscRecorder* discRecorder;
  210338. IRedbookDiscMaster* redbook;
  210339. AudioCDBurner::BurnProgressListener* listener;
  210340. float progress;
  210341. bool shouldCancel;
  210342. };
  210343. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  210344. {
  210345. IDiscMaster* discMaster = 0;
  210346. IDiscRecorder* discRecorder = enumCDBurners (0, deviceIndex, &discMaster);
  210347. if (discRecorder != 0)
  210348. pimpl = new Pimpl (*this, discMaster, discRecorder);
  210349. }
  210350. AudioCDBurner::~AudioCDBurner()
  210351. {
  210352. if (pimpl != 0)
  210353. pimpl.release()->releaseObjects();
  210354. }
  210355. const StringArray AudioCDBurner::findAvailableDevices()
  210356. {
  210357. StringArray devs;
  210358. enumCDBurners (&devs, -1, 0);
  210359. return devs;
  210360. }
  210361. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  210362. {
  210363. ScopedPointer<AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  210364. if (b->pimpl == 0)
  210365. b = 0;
  210366. return b.release();
  210367. }
  210368. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  210369. {
  210370. return pimpl->getDiskState();
  210371. }
  210372. bool AudioCDBurner::isDiskPresent() const
  210373. {
  210374. return getDiskState() == writableDiskPresent;
  210375. }
  210376. bool AudioCDBurner::openTray()
  210377. {
  210378. const Pimpl::ScopedDiscOpener opener (*pimpl);
  210379. return SUCCEEDED (pimpl->discRecorder->Eject());
  210380. }
  210381. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  210382. {
  210383. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  210384. DiskState oldState = getDiskState();
  210385. DiskState newState = oldState;
  210386. while (newState == oldState && Time::currentTimeMillis() < timeout)
  210387. {
  210388. newState = getDiskState();
  210389. Thread::sleep (jmin (250, (int) (timeout - Time::currentTimeMillis())));
  210390. }
  210391. return newState;
  210392. }
  210393. const Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  210394. {
  210395. Array<int> results;
  210396. const int maxSpeed = pimpl->getIntProperty (L"MaxWriteSpeed", 1);
  210397. const int speeds[] = { 1, 2, 4, 8, 12, 16, 20, 24, 32, 40, 64, 80 };
  210398. for (int i = 0; i < numElementsInArray (speeds); ++i)
  210399. if (speeds[i] <= maxSpeed)
  210400. results.add (speeds[i]);
  210401. results.addIfNotAlreadyThere (maxSpeed);
  210402. return results;
  210403. }
  210404. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  210405. {
  210406. if (pimpl->getIntProperty (L"BufferUnderrunFreeCapable", 0) == 0)
  210407. return false;
  210408. pimpl->setIntProperty (L"EnableBufferUnderrunFree", shouldBeEnabled ? -1 : 0);
  210409. return pimpl->getIntProperty (L"EnableBufferUnderrunFree", 0) != 0;
  210410. }
  210411. int AudioCDBurner::getNumAvailableAudioBlocks() const
  210412. {
  210413. long blocksFree = 0;
  210414. pimpl->redbook->GetAvailableAudioTrackBlocks (&blocksFree);
  210415. return blocksFree;
  210416. }
  210417. const String AudioCDBurner::burn (AudioCDBurner::BurnProgressListener* listener, bool ejectDiscAfterwards,
  210418. bool performFakeBurnForTesting, int writeSpeed)
  210419. {
  210420. pimpl->setIntProperty (L"WriteSpeed", writeSpeed > 0 ? writeSpeed : -1);
  210421. pimpl->listener = listener;
  210422. pimpl->progress = 0;
  210423. pimpl->shouldCancel = false;
  210424. UINT_PTR cookie;
  210425. HRESULT hr = pimpl->discMaster->ProgressAdvise ((AudioCDBurner::Pimpl*) pimpl, &cookie);
  210426. hr = pimpl->discMaster->RecordDisc (performFakeBurnForTesting,
  210427. ejectDiscAfterwards);
  210428. String error;
  210429. if (hr != S_OK)
  210430. {
  210431. const char* e = "Couldn't open or write to the CD device";
  210432. if (hr == IMAPI_E_USERABORT)
  210433. e = "User cancelled the write operation";
  210434. else if (hr == IMAPI_E_MEDIUM_NOTPRESENT || hr == IMAPI_E_TRACKOPEN)
  210435. e = "No Disk present";
  210436. error = e;
  210437. }
  210438. pimpl->discMaster->ProgressUnadvise (cookie);
  210439. pimpl->listener = 0;
  210440. return error;
  210441. }
  210442. bool AudioCDBurner::addAudioTrack (AudioSource* audioSource, int numSamples)
  210443. {
  210444. if (audioSource == 0)
  210445. return false;
  210446. ScopedPointer<AudioSource> source (audioSource);
  210447. long bytesPerBlock;
  210448. HRESULT hr = pimpl->redbook->GetAudioBlockSize (&bytesPerBlock);
  210449. const int samplesPerBlock = bytesPerBlock / 4;
  210450. bool ok = true;
  210451. hr = pimpl->redbook->CreateAudioTrack ((long) numSamples / (bytesPerBlock * 4));
  210452. HeapBlock <byte> buffer (bytesPerBlock);
  210453. AudioSampleBuffer sourceBuffer (2, samplesPerBlock);
  210454. int samplesDone = 0;
  210455. source->prepareToPlay (samplesPerBlock, 44100.0);
  210456. while (ok)
  210457. {
  210458. {
  210459. AudioSourceChannelInfo info;
  210460. info.buffer = &sourceBuffer;
  210461. info.numSamples = samplesPerBlock;
  210462. info.startSample = 0;
  210463. sourceBuffer.clear();
  210464. source->getNextAudioBlock (info);
  210465. }
  210466. zeromem (buffer, bytesPerBlock);
  210467. AudioDataConverters::convertFloatToInt16LE (sourceBuffer.getSampleData (0, 0),
  210468. buffer, samplesPerBlock, 4);
  210469. AudioDataConverters::convertFloatToInt16LE (sourceBuffer.getSampleData (1, 0),
  210470. buffer + 2, samplesPerBlock, 4);
  210471. hr = pimpl->redbook->AddAudioTrackBlocks (buffer, bytesPerBlock);
  210472. if (FAILED (hr))
  210473. ok = false;
  210474. samplesDone += samplesPerBlock;
  210475. if (samplesDone >= numSamples)
  210476. break;
  210477. }
  210478. hr = pimpl->redbook->CloseAudioTrack();
  210479. return ok && hr == S_OK;
  210480. }
  210481. #endif
  210482. #endif
  210483. /*** End of inlined file: juce_win32_AudioCDReader.cpp ***/
  210484. /*** Start of inlined file: juce_win32_Midi.cpp ***/
  210485. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  210486. // compiled on its own).
  210487. #if JUCE_INCLUDED_FILE
  210488. using ::free;
  210489. namespace MidiConstants
  210490. {
  210491. static const int midiBufferSize = 1024 * 10;
  210492. static const int numInHeaders = 32;
  210493. static const int inBufferSize = 256;
  210494. }
  210495. class MidiInThread : public Thread
  210496. {
  210497. public:
  210498. MidiInThread (MidiInput* const input_,
  210499. MidiInputCallback* const callback_)
  210500. : Thread ("Juce Midi"),
  210501. hIn (0),
  210502. input (input_),
  210503. callback (callback_),
  210504. isStarted (false),
  210505. startTime (0),
  210506. pendingLength(0)
  210507. {
  210508. for (int i = MidiConstants::numInHeaders; --i >= 0;)
  210509. {
  210510. zeromem (&hdr[i], sizeof (MIDIHDR));
  210511. hdr[i].lpData = inData[i];
  210512. hdr[i].dwBufferLength = MidiConstants::inBufferSize;
  210513. }
  210514. };
  210515. ~MidiInThread()
  210516. {
  210517. stop();
  210518. if (hIn != 0)
  210519. {
  210520. int count = 5;
  210521. while (--count >= 0)
  210522. {
  210523. if (midiInClose (hIn) == MMSYSERR_NOERROR)
  210524. break;
  210525. Sleep (20);
  210526. }
  210527. }
  210528. }
  210529. void handle (const uint32 message, const uint32 timeStamp)
  210530. {
  210531. const int byte = message & 0xff;
  210532. if (byte < 0x80)
  210533. return;
  210534. const int numBytes = MidiMessage::getMessageLengthFromFirstByte ((uint8) byte);
  210535. const double time = timeStampToTime (timeStamp);
  210536. {
  210537. const ScopedLock sl (lock);
  210538. if (pendingLength < MidiConstants::midiBufferSize - 12)
  210539. {
  210540. char* const p = pending + pendingLength;
  210541. *(double*) p = time;
  210542. *(uint32*) (p + 8) = numBytes;
  210543. *(uint32*) (p + 12) = message;
  210544. pendingLength += 12 + numBytes;
  210545. }
  210546. else
  210547. {
  210548. jassertfalse; // midi buffer overflow! You might need to increase the size..
  210549. }
  210550. }
  210551. notify();
  210552. }
  210553. void handleSysEx (MIDIHDR* const hdr, const uint32 timeStamp)
  210554. {
  210555. const int num = hdr->dwBytesRecorded;
  210556. if (num > 0)
  210557. {
  210558. const double time = timeStampToTime (timeStamp);
  210559. {
  210560. const ScopedLock sl (lock);
  210561. if (pendingLength < MidiConstants::midiBufferSize - (8 + num))
  210562. {
  210563. char* const p = pending + pendingLength;
  210564. *(double*) p = time;
  210565. *(uint32*) (p + 8) = num;
  210566. memcpy (p + 12, hdr->lpData, num);
  210567. pendingLength += 12 + num;
  210568. }
  210569. else
  210570. {
  210571. jassertfalse; // midi buffer overflow! You might need to increase the size..
  210572. }
  210573. }
  210574. notify();
  210575. }
  210576. }
  210577. void writeBlock (const int i)
  210578. {
  210579. hdr[i].dwBytesRecorded = 0;
  210580. MMRESULT res = midiInPrepareHeader (hIn, &hdr[i], sizeof (MIDIHDR));
  210581. jassert (res == MMSYSERR_NOERROR);
  210582. res = midiInAddBuffer (hIn, &hdr[i], sizeof (MIDIHDR));
  210583. jassert (res == MMSYSERR_NOERROR);
  210584. }
  210585. void run()
  210586. {
  210587. MemoryBlock pendingCopy (64);
  210588. while (! threadShouldExit())
  210589. {
  210590. for (int i = 0; i < MidiConstants::numInHeaders; ++i)
  210591. {
  210592. if ((hdr[i].dwFlags & WHDR_DONE) != 0)
  210593. {
  210594. MMRESULT res = midiInUnprepareHeader (hIn, &hdr[i], sizeof (MIDIHDR));
  210595. (void) res;
  210596. jassert (res == MMSYSERR_NOERROR);
  210597. writeBlock (i);
  210598. }
  210599. }
  210600. int len;
  210601. {
  210602. const ScopedLock sl (lock);
  210603. len = pendingLength;
  210604. if (len > 0)
  210605. {
  210606. pendingCopy.ensureSize (len);
  210607. pendingCopy.copyFrom (pending, 0, len);
  210608. pendingLength = 0;
  210609. }
  210610. }
  210611. //xxx needs to figure out if blocks are broken up or not
  210612. if (len == 0)
  210613. {
  210614. wait (500);
  210615. }
  210616. else
  210617. {
  210618. const char* p = (const char*) pendingCopy.getData();
  210619. while (len > 0)
  210620. {
  210621. const double time = *(const double*) p;
  210622. const int messageLen = *(const int*) (p + 8);
  210623. const MidiMessage message ((const uint8*) (p + 12), messageLen, time);
  210624. callback->handleIncomingMidiMessage (input, message);
  210625. p += 12 + messageLen;
  210626. len -= 12 + messageLen;
  210627. }
  210628. }
  210629. }
  210630. }
  210631. void start()
  210632. {
  210633. jassert (hIn != 0);
  210634. if (hIn != 0 && ! isStarted)
  210635. {
  210636. stop();
  210637. activeMidiThreads.addIfNotAlreadyThere (this);
  210638. int i;
  210639. for (i = 0; i < MidiConstants::numInHeaders; ++i)
  210640. writeBlock (i);
  210641. startTime = Time::getMillisecondCounter();
  210642. MMRESULT res = midiInStart (hIn);
  210643. jassert (res == MMSYSERR_NOERROR);
  210644. if (res == MMSYSERR_NOERROR)
  210645. {
  210646. isStarted = true;
  210647. pendingLength = 0;
  210648. startThread (6);
  210649. }
  210650. }
  210651. }
  210652. void stop()
  210653. {
  210654. if (isStarted)
  210655. {
  210656. stopThread (5000);
  210657. midiInReset (hIn);
  210658. midiInStop (hIn);
  210659. activeMidiThreads.removeValue (this);
  210660. { const ScopedLock sl (lock); }
  210661. for (int i = MidiConstants::numInHeaders; --i >= 0;)
  210662. {
  210663. if ((hdr[i].dwFlags & WHDR_DONE) != 0)
  210664. {
  210665. int c = 10;
  210666. while (--c >= 0 && midiInUnprepareHeader (hIn, &hdr[i], sizeof (MIDIHDR)) == MIDIERR_STILLPLAYING)
  210667. Sleep (20);
  210668. jassert (c >= 0);
  210669. }
  210670. }
  210671. isStarted = false;
  210672. pendingLength = 0;
  210673. }
  210674. }
  210675. static void CALLBACK midiInCallback (HMIDIIN, UINT uMsg, DWORD_PTR dwInstance, DWORD_PTR midiMessage, DWORD_PTR timeStamp)
  210676. {
  210677. MidiInThread* const thread = reinterpret_cast <MidiInThread*> (dwInstance);
  210678. if (thread != 0 && activeMidiThreads.contains (thread))
  210679. {
  210680. if (uMsg == MIM_DATA)
  210681. thread->handle ((uint32) midiMessage, (uint32) timeStamp);
  210682. else if (uMsg == MIM_LONGDATA)
  210683. thread->handleSysEx ((MIDIHDR*) midiMessage, (uint32) timeStamp);
  210684. }
  210685. }
  210686. juce_UseDebuggingNewOperator
  210687. HMIDIIN hIn;
  210688. private:
  210689. static Array <void*, CriticalSection> activeMidiThreads;
  210690. MidiInput* input;
  210691. MidiInputCallback* callback;
  210692. bool isStarted;
  210693. uint32 startTime;
  210694. CriticalSection lock;
  210695. MIDIHDR hdr [MidiConstants::numInHeaders];
  210696. char inData [MidiConstants::numInHeaders] [MidiConstants::inBufferSize];
  210697. int pendingLength;
  210698. char pending [MidiConstants::midiBufferSize];
  210699. double timeStampToTime (uint32 timeStamp)
  210700. {
  210701. timeStamp += startTime;
  210702. const uint32 now = Time::getMillisecondCounter();
  210703. if (timeStamp > now)
  210704. {
  210705. if (timeStamp > now + 2)
  210706. --startTime;
  210707. timeStamp = now;
  210708. }
  210709. return 0.001 * timeStamp;
  210710. }
  210711. MidiInThread (const MidiInThread&);
  210712. MidiInThread& operator= (const MidiInThread&);
  210713. };
  210714. Array <void*, CriticalSection> MidiInThread::activeMidiThreads;
  210715. const StringArray MidiInput::getDevices()
  210716. {
  210717. StringArray s;
  210718. const int num = midiInGetNumDevs();
  210719. for (int i = 0; i < num; ++i)
  210720. {
  210721. MIDIINCAPS mc;
  210722. zerostruct (mc);
  210723. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  210724. s.add (String (mc.szPname, sizeof (mc.szPname)));
  210725. }
  210726. return s;
  210727. }
  210728. int MidiInput::getDefaultDeviceIndex()
  210729. {
  210730. return 0;
  210731. }
  210732. MidiInput* MidiInput::openDevice (const int index, MidiInputCallback* const callback)
  210733. {
  210734. if (callback == 0)
  210735. return 0;
  210736. UINT deviceId = MIDI_MAPPER;
  210737. int n = 0;
  210738. String name;
  210739. const int num = midiInGetNumDevs();
  210740. for (int i = 0; i < num; ++i)
  210741. {
  210742. MIDIINCAPS mc;
  210743. zerostruct (mc);
  210744. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  210745. {
  210746. if (index == n)
  210747. {
  210748. deviceId = i;
  210749. name = String (mc.szPname, sizeof (mc.szPname));
  210750. break;
  210751. }
  210752. ++n;
  210753. }
  210754. }
  210755. ScopedPointer <MidiInput> in (new MidiInput (name));
  210756. ScopedPointer <MidiInThread> thread (new MidiInThread (in, callback));
  210757. HMIDIIN h;
  210758. HRESULT err = midiInOpen (&h, deviceId,
  210759. (DWORD_PTR) &MidiInThread::midiInCallback,
  210760. (DWORD_PTR) (MidiInThread*) thread,
  210761. CALLBACK_FUNCTION);
  210762. if (err == MMSYSERR_NOERROR)
  210763. {
  210764. thread->hIn = h;
  210765. in->internal = thread.release();
  210766. return in.release();
  210767. }
  210768. return 0;
  210769. }
  210770. MidiInput::MidiInput (const String& name_)
  210771. : name (name_),
  210772. internal (0)
  210773. {
  210774. }
  210775. MidiInput::~MidiInput()
  210776. {
  210777. delete static_cast <MidiInThread*> (internal);
  210778. }
  210779. void MidiInput::start()
  210780. {
  210781. static_cast <MidiInThread*> (internal)->start();
  210782. }
  210783. void MidiInput::stop()
  210784. {
  210785. static_cast <MidiInThread*> (internal)->stop();
  210786. }
  210787. struct MidiOutHandle
  210788. {
  210789. int refCount;
  210790. UINT deviceId;
  210791. HMIDIOUT handle;
  210792. static Array<MidiOutHandle*> activeHandles;
  210793. juce_UseDebuggingNewOperator
  210794. };
  210795. Array<MidiOutHandle*> MidiOutHandle::activeHandles;
  210796. const StringArray MidiOutput::getDevices()
  210797. {
  210798. StringArray s;
  210799. const int num = midiOutGetNumDevs();
  210800. for (int i = 0; i < num; ++i)
  210801. {
  210802. MIDIOUTCAPS mc;
  210803. zerostruct (mc);
  210804. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  210805. s.add (String (mc.szPname, sizeof (mc.szPname)));
  210806. }
  210807. return s;
  210808. }
  210809. int MidiOutput::getDefaultDeviceIndex()
  210810. {
  210811. const int num = midiOutGetNumDevs();
  210812. int n = 0;
  210813. for (int i = 0; i < num; ++i)
  210814. {
  210815. MIDIOUTCAPS mc;
  210816. zerostruct (mc);
  210817. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  210818. {
  210819. if ((mc.wTechnology & MOD_MAPPER) != 0)
  210820. return n;
  210821. ++n;
  210822. }
  210823. }
  210824. return 0;
  210825. }
  210826. MidiOutput* MidiOutput::openDevice (int index)
  210827. {
  210828. UINT deviceId = MIDI_MAPPER;
  210829. const int num = midiOutGetNumDevs();
  210830. int i, n = 0;
  210831. for (i = 0; i < num; ++i)
  210832. {
  210833. MIDIOUTCAPS mc;
  210834. zerostruct (mc);
  210835. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  210836. {
  210837. // use the microsoft sw synth as a default - best not to allow deviceId
  210838. // to be MIDI_MAPPER, or else device sharing breaks
  210839. if (String (mc.szPname, sizeof (mc.szPname)).containsIgnoreCase ("microsoft"))
  210840. deviceId = i;
  210841. if (index == n)
  210842. {
  210843. deviceId = i;
  210844. break;
  210845. }
  210846. ++n;
  210847. }
  210848. }
  210849. for (i = MidiOutHandle::activeHandles.size(); --i >= 0;)
  210850. {
  210851. MidiOutHandle* const han = MidiOutHandle::activeHandles.getUnchecked(i);
  210852. if (han != 0 && han->deviceId == deviceId)
  210853. {
  210854. han->refCount++;
  210855. MidiOutput* const out = new MidiOutput();
  210856. out->internal = han;
  210857. return out;
  210858. }
  210859. }
  210860. for (i = 4; --i >= 0;)
  210861. {
  210862. HMIDIOUT h = 0;
  210863. MMRESULT res = midiOutOpen (&h, deviceId, 0, 0, CALLBACK_NULL);
  210864. if (res == MMSYSERR_NOERROR)
  210865. {
  210866. MidiOutHandle* const han = new MidiOutHandle();
  210867. han->deviceId = deviceId;
  210868. han->refCount = 1;
  210869. han->handle = h;
  210870. MidiOutHandle::activeHandles.add (han);
  210871. MidiOutput* const out = new MidiOutput();
  210872. out->internal = han;
  210873. return out;
  210874. }
  210875. else if (res == MMSYSERR_ALLOCATED)
  210876. {
  210877. Sleep (100);
  210878. }
  210879. else
  210880. {
  210881. break;
  210882. }
  210883. }
  210884. return 0;
  210885. }
  210886. MidiOutput::~MidiOutput()
  210887. {
  210888. MidiOutHandle* const h = static_cast <MidiOutHandle*> (internal);
  210889. if (MidiOutHandle::activeHandles.contains (h) && --(h->refCount) == 0)
  210890. {
  210891. midiOutClose (h->handle);
  210892. MidiOutHandle::activeHandles.removeValue (h);
  210893. delete h;
  210894. }
  210895. }
  210896. void MidiOutput::reset()
  210897. {
  210898. const MidiOutHandle* const h = static_cast <const MidiOutHandle*> (internal);
  210899. midiOutReset (h->handle);
  210900. }
  210901. bool MidiOutput::getVolume (float& leftVol,
  210902. float& rightVol)
  210903. {
  210904. const MidiOutHandle* const handle = static_cast <const MidiOutHandle*> (internal);
  210905. DWORD n;
  210906. if (midiOutGetVolume (handle->handle, &n) == MMSYSERR_NOERROR)
  210907. {
  210908. const unsigned short* const nn = (const unsigned short*) &n;
  210909. rightVol = nn[0] / (float) 0xffff;
  210910. leftVol = nn[1] / (float) 0xffff;
  210911. return true;
  210912. }
  210913. else
  210914. {
  210915. rightVol = leftVol = 1.0f;
  210916. return false;
  210917. }
  210918. }
  210919. void MidiOutput::setVolume (float leftVol,
  210920. float rightVol)
  210921. {
  210922. const MidiOutHandle* const handle = static_cast <MidiOutHandle*> (internal);
  210923. DWORD n;
  210924. unsigned short* const nn = (unsigned short*) &n;
  210925. nn[0] = (unsigned short) jlimit (0, 0xffff, (int) (rightVol * 0xffff));
  210926. nn[1] = (unsigned short) jlimit (0, 0xffff, (int) (leftVol * 0xffff));
  210927. midiOutSetVolume (handle->handle, n);
  210928. }
  210929. void MidiOutput::sendMessageNow (const MidiMessage& message)
  210930. {
  210931. const MidiOutHandle* const handle = static_cast <const MidiOutHandle*> (internal);
  210932. if (message.getRawDataSize() > 3
  210933. || message.isSysEx())
  210934. {
  210935. MIDIHDR h;
  210936. zerostruct (h);
  210937. h.lpData = (char*) message.getRawData();
  210938. h.dwBufferLength = message.getRawDataSize();
  210939. h.dwBytesRecorded = message.getRawDataSize();
  210940. if (midiOutPrepareHeader (handle->handle, &h, sizeof (MIDIHDR)) == MMSYSERR_NOERROR)
  210941. {
  210942. MMRESULT res = midiOutLongMsg (handle->handle, &h, sizeof (MIDIHDR));
  210943. if (res == MMSYSERR_NOERROR)
  210944. {
  210945. while ((h.dwFlags & MHDR_DONE) == 0)
  210946. Sleep (1);
  210947. int count = 500; // 1 sec timeout
  210948. while (--count >= 0)
  210949. {
  210950. res = midiOutUnprepareHeader (handle->handle, &h, sizeof (MIDIHDR));
  210951. if (res == MIDIERR_STILLPLAYING)
  210952. Sleep (2);
  210953. else
  210954. break;
  210955. }
  210956. }
  210957. }
  210958. }
  210959. else
  210960. {
  210961. midiOutShortMsg (handle->handle,
  210962. *(unsigned int*) message.getRawData());
  210963. }
  210964. }
  210965. #endif
  210966. /*** End of inlined file: juce_win32_Midi.cpp ***/
  210967. /*** Start of inlined file: juce_win32_ASIO.cpp ***/
  210968. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  210969. // compiled on its own).
  210970. #if JUCE_INCLUDED_FILE && JUCE_ASIO
  210971. #undef WINDOWS
  210972. // #define ASIO_DEBUGGING
  210973. #ifdef ASIO_DEBUGGING
  210974. #define log(a) { Logger::writeToLog (a); DBG (a) }
  210975. #else
  210976. #define log(a) {}
  210977. #endif
  210978. #ifdef ASIO_DEBUGGING
  210979. static void logError (const String& context, long error)
  210980. {
  210981. String err ("unknown error");
  210982. if (error == ASE_NotPresent)
  210983. err = "Not Present";
  210984. else if (error == ASE_HWMalfunction)
  210985. err = "Hardware Malfunction";
  210986. else if (error == ASE_InvalidParameter)
  210987. err = "Invalid Parameter";
  210988. else if (error == ASE_InvalidMode)
  210989. err = "Invalid Mode";
  210990. else if (error == ASE_SPNotAdvancing)
  210991. err = "Sample position not advancing";
  210992. else if (error == ASE_NoClock)
  210993. err = "No Clock";
  210994. else if (error == ASE_NoMemory)
  210995. err = "Out of memory";
  210996. log ("!!error: " + context + " - " + err);
  210997. }
  210998. #else
  210999. #define logError(a, b) {}
  211000. #endif
  211001. class ASIOAudioIODevice;
  211002. static ASIOAudioIODevice* volatile currentASIODev[3] = { 0, 0, 0 };
  211003. static const int maxASIOChannels = 160;
  211004. class JUCE_API ASIOAudioIODevice : public AudioIODevice,
  211005. private Timer
  211006. {
  211007. public:
  211008. Component ourWindow;
  211009. ASIOAudioIODevice (const String& name_, const CLSID classId_, const int slotNumber,
  211010. const String& optionalDllForDirectLoading_)
  211011. : AudioIODevice (name_, "ASIO"),
  211012. asioObject (0),
  211013. classId (classId_),
  211014. optionalDllForDirectLoading (optionalDllForDirectLoading_),
  211015. currentBitDepth (16),
  211016. currentSampleRate (0),
  211017. isOpen_ (false),
  211018. isStarted (false),
  211019. postOutput (true),
  211020. insideControlPanelModalLoop (false),
  211021. shouldUsePreferredSize (false)
  211022. {
  211023. name = name_;
  211024. ourWindow.addToDesktop (0);
  211025. windowHandle = ourWindow.getWindowHandle();
  211026. jassert (currentASIODev [slotNumber] == 0);
  211027. currentASIODev [slotNumber] = this;
  211028. openDevice();
  211029. }
  211030. ~ASIOAudioIODevice()
  211031. {
  211032. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  211033. if (currentASIODev[i] == this)
  211034. currentASIODev[i] = 0;
  211035. close();
  211036. log ("ASIO - exiting");
  211037. removeCurrentDriver();
  211038. }
  211039. void updateSampleRates()
  211040. {
  211041. // find a list of sample rates..
  211042. const double possibleSampleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  211043. sampleRates.clear();
  211044. if (asioObject != 0)
  211045. {
  211046. for (int index = 0; index < numElementsInArray (possibleSampleRates); ++index)
  211047. {
  211048. const long err = asioObject->canSampleRate (possibleSampleRates[index]);
  211049. if (err == 0)
  211050. {
  211051. sampleRates.add ((int) possibleSampleRates[index]);
  211052. log ("rate: " + String ((int) possibleSampleRates[index]));
  211053. }
  211054. else if (err != ASE_NoClock)
  211055. {
  211056. logError ("CanSampleRate", err);
  211057. }
  211058. }
  211059. if (sampleRates.size() == 0)
  211060. {
  211061. double cr = 0;
  211062. const long err = asioObject->getSampleRate (&cr);
  211063. log ("No sample rates supported - current rate: " + String ((int) cr));
  211064. if (err == 0)
  211065. sampleRates.add ((int) cr);
  211066. }
  211067. }
  211068. }
  211069. const StringArray getOutputChannelNames()
  211070. {
  211071. return outputChannelNames;
  211072. }
  211073. const StringArray getInputChannelNames()
  211074. {
  211075. return inputChannelNames;
  211076. }
  211077. int getNumSampleRates()
  211078. {
  211079. return sampleRates.size();
  211080. }
  211081. double getSampleRate (int index)
  211082. {
  211083. return sampleRates [index];
  211084. }
  211085. int getNumBufferSizesAvailable()
  211086. {
  211087. return bufferSizes.size();
  211088. }
  211089. int getBufferSizeSamples (int index)
  211090. {
  211091. return bufferSizes [index];
  211092. }
  211093. int getDefaultBufferSize()
  211094. {
  211095. return preferredSize;
  211096. }
  211097. const String open (const BigInteger& inputChannels,
  211098. const BigInteger& outputChannels,
  211099. double sr,
  211100. int bufferSizeSamples)
  211101. {
  211102. close();
  211103. currentCallback = 0;
  211104. if (bufferSizeSamples <= 0)
  211105. shouldUsePreferredSize = true;
  211106. if (asioObject == 0 || ! isASIOOpen)
  211107. {
  211108. log ("Warning: device not open");
  211109. const String err (openDevice());
  211110. if (asioObject == 0 || ! isASIOOpen)
  211111. return err;
  211112. }
  211113. isStarted = false;
  211114. bufferIndex = -1;
  211115. long err = 0;
  211116. long newPreferredSize = 0;
  211117. // if the preferred size has just changed, assume it's a control panel thing and use it as the new value.
  211118. minSize = 0;
  211119. maxSize = 0;
  211120. newPreferredSize = 0;
  211121. granularity = 0;
  211122. if (asioObject->getBufferSize (&minSize, &maxSize, &newPreferredSize, &granularity) == 0)
  211123. {
  211124. if (preferredSize != 0 && newPreferredSize != 0 && newPreferredSize != preferredSize)
  211125. shouldUsePreferredSize = true;
  211126. preferredSize = newPreferredSize;
  211127. }
  211128. // unfortunate workaround for certain manufacturers whose drivers crash horribly if you make
  211129. // dynamic changes to the buffer size...
  211130. shouldUsePreferredSize = shouldUsePreferredSize
  211131. || getName().containsIgnoreCase ("Digidesign");
  211132. if (shouldUsePreferredSize)
  211133. {
  211134. log ("Using preferred size for buffer..");
  211135. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  211136. {
  211137. bufferSizeSamples = preferredSize;
  211138. }
  211139. else
  211140. {
  211141. bufferSizeSamples = 1024;
  211142. logError ("GetBufferSize1", err);
  211143. }
  211144. shouldUsePreferredSize = false;
  211145. }
  211146. int sampleRate = roundDoubleToInt (sr);
  211147. currentSampleRate = sampleRate;
  211148. currentBlockSizeSamples = bufferSizeSamples;
  211149. currentChansOut.clear();
  211150. currentChansIn.clear();
  211151. zeromem (inBuffers, sizeof (inBuffers));
  211152. zeromem (outBuffers, sizeof (outBuffers));
  211153. updateSampleRates();
  211154. if (sampleRate == 0 || (sampleRates.size() > 0 && ! sampleRates.contains (sampleRate)))
  211155. sampleRate = sampleRates[0];
  211156. jassert (sampleRate != 0);
  211157. if (sampleRate == 0)
  211158. sampleRate = 44100;
  211159. long numSources = 32;
  211160. ASIOClockSource clocks[32];
  211161. zeromem (clocks, sizeof (clocks));
  211162. asioObject->getClockSources (clocks, &numSources);
  211163. bool isSourceSet = false;
  211164. // careful not to remove this loop because it does more than just logging!
  211165. int i;
  211166. for (i = 0; i < numSources; ++i)
  211167. {
  211168. String s ("clock: ");
  211169. s += clocks[i].name;
  211170. if (clocks[i].isCurrentSource)
  211171. {
  211172. isSourceSet = true;
  211173. s << " (cur)";
  211174. }
  211175. log (s);
  211176. }
  211177. if (numSources > 1 && ! isSourceSet)
  211178. {
  211179. log ("setting clock source");
  211180. asioObject->setClockSource (clocks[0].index);
  211181. Thread::sleep (20);
  211182. }
  211183. else
  211184. {
  211185. if (numSources == 0)
  211186. {
  211187. log ("ASIO - no clock sources!");
  211188. }
  211189. }
  211190. double cr = 0;
  211191. err = asioObject->getSampleRate (&cr);
  211192. if (err == 0)
  211193. {
  211194. currentSampleRate = cr;
  211195. }
  211196. else
  211197. {
  211198. logError ("GetSampleRate", err);
  211199. currentSampleRate = 0;
  211200. }
  211201. error = String::empty;
  211202. needToReset = false;
  211203. isReSync = false;
  211204. err = 0;
  211205. bool buffersCreated = false;
  211206. if (currentSampleRate != sampleRate)
  211207. {
  211208. log ("ASIO samplerate: " + String (currentSampleRate) + " to " + String (sampleRate));
  211209. err = asioObject->setSampleRate (sampleRate);
  211210. if (err == ASE_NoClock && numSources > 0)
  211211. {
  211212. log ("trying to set a clock source..");
  211213. Thread::sleep (10);
  211214. err = asioObject->setClockSource (clocks[0].index);
  211215. if (err != 0)
  211216. {
  211217. logError ("SetClock", err);
  211218. }
  211219. Thread::sleep (10);
  211220. err = asioObject->setSampleRate (sampleRate);
  211221. }
  211222. }
  211223. if (err == 0)
  211224. {
  211225. currentSampleRate = sampleRate;
  211226. if (needToReset)
  211227. {
  211228. if (isReSync)
  211229. {
  211230. log ("Resync request");
  211231. }
  211232. log ("! Resetting ASIO after sample rate change");
  211233. removeCurrentDriver();
  211234. loadDriver();
  211235. const String error (initDriver());
  211236. if (error.isNotEmpty())
  211237. {
  211238. log ("ASIOInit: " + error);
  211239. }
  211240. needToReset = false;
  211241. isReSync = false;
  211242. }
  211243. numActiveInputChans = 0;
  211244. numActiveOutputChans = 0;
  211245. ASIOBufferInfo* info = bufferInfos;
  211246. int i;
  211247. for (i = 0; i < totalNumInputChans; ++i)
  211248. {
  211249. if (inputChannels[i])
  211250. {
  211251. currentChansIn.setBit (i);
  211252. info->isInput = 1;
  211253. info->channelNum = i;
  211254. info->buffers[0] = info->buffers[1] = 0;
  211255. ++info;
  211256. ++numActiveInputChans;
  211257. }
  211258. }
  211259. for (i = 0; i < totalNumOutputChans; ++i)
  211260. {
  211261. if (outputChannels[i])
  211262. {
  211263. currentChansOut.setBit (i);
  211264. info->isInput = 0;
  211265. info->channelNum = i;
  211266. info->buffers[0] = info->buffers[1] = 0;
  211267. ++info;
  211268. ++numActiveOutputChans;
  211269. }
  211270. }
  211271. const int totalBuffers = numActiveInputChans + numActiveOutputChans;
  211272. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  211273. if (currentASIODev[0] == this)
  211274. {
  211275. callbacks.bufferSwitch = &bufferSwitchCallback0;
  211276. callbacks.asioMessage = &asioMessagesCallback0;
  211277. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  211278. }
  211279. else if (currentASIODev[1] == this)
  211280. {
  211281. callbacks.bufferSwitch = &bufferSwitchCallback1;
  211282. callbacks.asioMessage = &asioMessagesCallback1;
  211283. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  211284. }
  211285. else if (currentASIODev[2] == this)
  211286. {
  211287. callbacks.bufferSwitch = &bufferSwitchCallback2;
  211288. callbacks.asioMessage = &asioMessagesCallback2;
  211289. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  211290. }
  211291. else
  211292. {
  211293. jassertfalse;
  211294. }
  211295. log ("disposing buffers");
  211296. err = asioObject->disposeBuffers();
  211297. log ("creating buffers: " + String (totalBuffers) + ", " + String (currentBlockSizeSamples));
  211298. err = asioObject->createBuffers (bufferInfos,
  211299. totalBuffers,
  211300. currentBlockSizeSamples,
  211301. &callbacks);
  211302. if (err != 0)
  211303. {
  211304. currentBlockSizeSamples = preferredSize;
  211305. logError ("create buffers 2", err);
  211306. asioObject->disposeBuffers();
  211307. err = asioObject->createBuffers (bufferInfos,
  211308. totalBuffers,
  211309. currentBlockSizeSamples,
  211310. &callbacks);
  211311. }
  211312. if (err == 0)
  211313. {
  211314. buffersCreated = true;
  211315. tempBuffer.calloc (totalBuffers * currentBlockSizeSamples + 32);
  211316. int n = 0;
  211317. Array <int> types;
  211318. currentBitDepth = 16;
  211319. for (i = 0; i < jmin ((int) totalNumInputChans, maxASIOChannels); ++i)
  211320. {
  211321. if (inputChannels[i])
  211322. {
  211323. inBuffers[n] = tempBuffer + (currentBlockSizeSamples * n);
  211324. ASIOChannelInfo channelInfo;
  211325. zerostruct (channelInfo);
  211326. channelInfo.channel = i;
  211327. channelInfo.isInput = 1;
  211328. asioObject->getChannelInfo (&channelInfo);
  211329. types.addIfNotAlreadyThere (channelInfo.type);
  211330. typeToFormatParameters (channelInfo.type,
  211331. inputChannelBitDepths[n],
  211332. inputChannelBytesPerSample[n],
  211333. inputChannelIsFloat[n],
  211334. inputChannelLittleEndian[n]);
  211335. currentBitDepth = jmax (currentBitDepth, inputChannelBitDepths[n]);
  211336. ++n;
  211337. }
  211338. }
  211339. jassert (numActiveInputChans == n);
  211340. n = 0;
  211341. for (i = 0; i < jmin ((int) totalNumOutputChans, maxASIOChannels); ++i)
  211342. {
  211343. if (outputChannels[i])
  211344. {
  211345. outBuffers[n] = tempBuffer + (currentBlockSizeSamples * (numActiveInputChans + n));
  211346. ASIOChannelInfo channelInfo;
  211347. zerostruct (channelInfo);
  211348. channelInfo.channel = i;
  211349. channelInfo.isInput = 0;
  211350. asioObject->getChannelInfo (&channelInfo);
  211351. types.addIfNotAlreadyThere (channelInfo.type);
  211352. typeToFormatParameters (channelInfo.type,
  211353. outputChannelBitDepths[n],
  211354. outputChannelBytesPerSample[n],
  211355. outputChannelIsFloat[n],
  211356. outputChannelLittleEndian[n]);
  211357. currentBitDepth = jmax (currentBitDepth, outputChannelBitDepths[n]);
  211358. ++n;
  211359. }
  211360. }
  211361. jassert (numActiveOutputChans == n);
  211362. for (i = types.size(); --i >= 0;)
  211363. {
  211364. log ("channel format: " + String (types[i]));
  211365. }
  211366. jassert (n <= totalBuffers);
  211367. for (i = 0; i < numActiveOutputChans; ++i)
  211368. {
  211369. const int size = currentBlockSizeSamples * (outputChannelBitDepths[i] >> 3);
  211370. if (bufferInfos [numActiveInputChans + i].buffers[0] == 0
  211371. || bufferInfos [numActiveInputChans + i].buffers[1] == 0)
  211372. {
  211373. log ("!! Null buffers");
  211374. }
  211375. else
  211376. {
  211377. zeromem (bufferInfos[numActiveInputChans + i].buffers[0], size);
  211378. zeromem (bufferInfos[numActiveInputChans + i].buffers[1], size);
  211379. }
  211380. }
  211381. inputLatency = outputLatency = 0;
  211382. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  211383. {
  211384. log ("ASIO - no latencies");
  211385. }
  211386. else
  211387. {
  211388. log ("ASIO latencies: " + String ((int) outputLatency) + ", " + String ((int) inputLatency));
  211389. }
  211390. isOpen_ = true;
  211391. log ("starting ASIO");
  211392. calledback = false;
  211393. err = asioObject->start();
  211394. if (err != 0)
  211395. {
  211396. isOpen_ = false;
  211397. log ("ASIO - stop on failure");
  211398. Thread::sleep (10);
  211399. asioObject->stop();
  211400. error = "Can't start device";
  211401. Thread::sleep (10);
  211402. }
  211403. else
  211404. {
  211405. int count = 300;
  211406. while (--count > 0 && ! calledback)
  211407. Thread::sleep (10);
  211408. isStarted = true;
  211409. if (! calledback)
  211410. {
  211411. error = "Device didn't start correctly";
  211412. log ("ASIO didn't callback - stopping..");
  211413. asioObject->stop();
  211414. }
  211415. }
  211416. }
  211417. else
  211418. {
  211419. error = "Can't create i/o buffers";
  211420. }
  211421. }
  211422. else
  211423. {
  211424. error = "Can't set sample rate: ";
  211425. error << sampleRate;
  211426. }
  211427. if (error.isNotEmpty())
  211428. {
  211429. logError (error, err);
  211430. if (asioObject != 0 && buffersCreated)
  211431. asioObject->disposeBuffers();
  211432. Thread::sleep (20);
  211433. isStarted = false;
  211434. isOpen_ = false;
  211435. const String errorCopy (error);
  211436. close(); // (this resets the error string)
  211437. error = errorCopy;
  211438. }
  211439. needToReset = false;
  211440. isReSync = false;
  211441. return error;
  211442. }
  211443. void close()
  211444. {
  211445. error = String::empty;
  211446. stopTimer();
  211447. stop();
  211448. if (isASIOOpen && isOpen_)
  211449. {
  211450. const ScopedLock sl (callbackLock);
  211451. isOpen_ = false;
  211452. isStarted = false;
  211453. needToReset = false;
  211454. isReSync = false;
  211455. log ("ASIO - stopping");
  211456. if (asioObject != 0)
  211457. {
  211458. Thread::sleep (20);
  211459. asioObject->stop();
  211460. Thread::sleep (10);
  211461. asioObject->disposeBuffers();
  211462. }
  211463. Thread::sleep (10);
  211464. }
  211465. }
  211466. bool isOpen()
  211467. {
  211468. return isOpen_ || insideControlPanelModalLoop;
  211469. }
  211470. int getCurrentBufferSizeSamples()
  211471. {
  211472. return currentBlockSizeSamples;
  211473. }
  211474. double getCurrentSampleRate()
  211475. {
  211476. return currentSampleRate;
  211477. }
  211478. const BigInteger getActiveOutputChannels() const
  211479. {
  211480. return currentChansOut;
  211481. }
  211482. const BigInteger getActiveInputChannels() const
  211483. {
  211484. return currentChansIn;
  211485. }
  211486. int getCurrentBitDepth()
  211487. {
  211488. return currentBitDepth;
  211489. }
  211490. int getOutputLatencyInSamples()
  211491. {
  211492. return outputLatency + currentBlockSizeSamples / 4;
  211493. }
  211494. int getInputLatencyInSamples()
  211495. {
  211496. return inputLatency + currentBlockSizeSamples / 4;
  211497. }
  211498. void start (AudioIODeviceCallback* callback)
  211499. {
  211500. if (callback != 0)
  211501. {
  211502. callback->audioDeviceAboutToStart (this);
  211503. const ScopedLock sl (callbackLock);
  211504. currentCallback = callback;
  211505. }
  211506. }
  211507. void stop()
  211508. {
  211509. AudioIODeviceCallback* const lastCallback = currentCallback;
  211510. {
  211511. const ScopedLock sl (callbackLock);
  211512. currentCallback = 0;
  211513. }
  211514. if (lastCallback != 0)
  211515. lastCallback->audioDeviceStopped();
  211516. }
  211517. bool isPlaying()
  211518. {
  211519. return isASIOOpen && (currentCallback != 0);
  211520. }
  211521. const String getLastError()
  211522. {
  211523. return error;
  211524. }
  211525. bool hasControlPanel() const
  211526. {
  211527. return true;
  211528. }
  211529. bool showControlPanel()
  211530. {
  211531. log ("ASIO - showing control panel");
  211532. Component modalWindow (String::empty);
  211533. modalWindow.setOpaque (true);
  211534. modalWindow.addToDesktop (0);
  211535. modalWindow.enterModalState();
  211536. bool done = false;
  211537. JUCE_TRY
  211538. {
  211539. // are there are devices that need to be closed before showing their control panel?
  211540. // close();
  211541. insideControlPanelModalLoop = true;
  211542. const uint32 started = Time::getMillisecondCounter();
  211543. if (asioObject != 0)
  211544. {
  211545. asioObject->controlPanel();
  211546. const int spent = (int) Time::getMillisecondCounter() - (int) started;
  211547. log ("spent: " + String (spent));
  211548. if (spent > 300)
  211549. {
  211550. shouldUsePreferredSize = true;
  211551. done = true;
  211552. }
  211553. }
  211554. }
  211555. JUCE_CATCH_ALL
  211556. insideControlPanelModalLoop = false;
  211557. return done;
  211558. }
  211559. void resetRequest() throw()
  211560. {
  211561. needToReset = true;
  211562. }
  211563. void resyncRequest() throw()
  211564. {
  211565. needToReset = true;
  211566. isReSync = true;
  211567. }
  211568. void timerCallback()
  211569. {
  211570. if (! insideControlPanelModalLoop)
  211571. {
  211572. stopTimer();
  211573. // used to cause a reset
  211574. log ("! ASIO restart request!");
  211575. if (isOpen_)
  211576. {
  211577. AudioIODeviceCallback* const oldCallback = currentCallback;
  211578. close();
  211579. open (BigInteger (currentChansIn), BigInteger (currentChansOut),
  211580. currentSampleRate, currentBlockSizeSamples);
  211581. if (oldCallback != 0)
  211582. start (oldCallback);
  211583. }
  211584. }
  211585. else
  211586. {
  211587. startTimer (100);
  211588. }
  211589. }
  211590. juce_UseDebuggingNewOperator
  211591. private:
  211592. IASIO* volatile asioObject;
  211593. ASIOCallbacks callbacks;
  211594. void* windowHandle;
  211595. CLSID classId;
  211596. const String optionalDllForDirectLoading;
  211597. String error;
  211598. long totalNumInputChans, totalNumOutputChans;
  211599. StringArray inputChannelNames, outputChannelNames;
  211600. Array<int> sampleRates, bufferSizes;
  211601. long inputLatency, outputLatency;
  211602. long minSize, maxSize, preferredSize, granularity;
  211603. int volatile currentBlockSizeSamples;
  211604. int volatile currentBitDepth;
  211605. double volatile currentSampleRate;
  211606. BigInteger currentChansOut, currentChansIn;
  211607. AudioIODeviceCallback* volatile currentCallback;
  211608. CriticalSection callbackLock;
  211609. ASIOBufferInfo bufferInfos [maxASIOChannels];
  211610. float* inBuffers [maxASIOChannels];
  211611. float* outBuffers [maxASIOChannels];
  211612. int inputChannelBitDepths [maxASIOChannels];
  211613. int outputChannelBitDepths [maxASIOChannels];
  211614. int inputChannelBytesPerSample [maxASIOChannels];
  211615. int outputChannelBytesPerSample [maxASIOChannels];
  211616. bool inputChannelIsFloat [maxASIOChannels];
  211617. bool outputChannelIsFloat [maxASIOChannels];
  211618. bool inputChannelLittleEndian [maxASIOChannels];
  211619. bool outputChannelLittleEndian [maxASIOChannels];
  211620. WaitableEvent event1;
  211621. HeapBlock <float> tempBuffer;
  211622. int volatile bufferIndex, numActiveInputChans, numActiveOutputChans;
  211623. bool isOpen_, isStarted;
  211624. bool volatile isASIOOpen;
  211625. bool volatile calledback;
  211626. bool volatile littleEndian, postOutput, needToReset, isReSync;
  211627. bool volatile insideControlPanelModalLoop;
  211628. bool volatile shouldUsePreferredSize;
  211629. void removeCurrentDriver()
  211630. {
  211631. if (asioObject != 0)
  211632. {
  211633. asioObject->Release();
  211634. asioObject = 0;
  211635. }
  211636. }
  211637. bool loadDriver()
  211638. {
  211639. removeCurrentDriver();
  211640. JUCE_TRY
  211641. {
  211642. if (CoCreateInstance (classId, 0, CLSCTX_INPROC_SERVER,
  211643. classId, (void**) &asioObject) == S_OK)
  211644. {
  211645. return true;
  211646. }
  211647. // If a class isn't registered but we have a path for it, we can fallback to
  211648. // doing a direct load of the COM object (only available via the juce_createASIOAudioIODeviceForGUID function).
  211649. if (optionalDllForDirectLoading.isNotEmpty())
  211650. {
  211651. HMODULE h = LoadLibrary (optionalDllForDirectLoading);
  211652. if (h != 0)
  211653. {
  211654. typedef HRESULT (CALLBACK* DllGetClassObjectFunc) (REFCLSID clsid, REFIID iid, LPVOID* ppv);
  211655. DllGetClassObjectFunc dllGetClassObject = (DllGetClassObjectFunc) GetProcAddress (h, "DllGetClassObject");
  211656. if (dllGetClassObject != 0)
  211657. {
  211658. IClassFactory* classFactory = 0;
  211659. HRESULT hr = dllGetClassObject (classId, IID_IClassFactory, (void**) &classFactory);
  211660. if (classFactory != 0)
  211661. {
  211662. hr = classFactory->CreateInstance (0, classId, (void**) &asioObject);
  211663. classFactory->Release();
  211664. }
  211665. return asioObject != 0;
  211666. }
  211667. }
  211668. }
  211669. }
  211670. JUCE_CATCH_ALL
  211671. asioObject = 0;
  211672. return false;
  211673. }
  211674. const String initDriver()
  211675. {
  211676. if (asioObject != 0)
  211677. {
  211678. char buffer [256];
  211679. zeromem (buffer, sizeof (buffer));
  211680. if (! asioObject->init (windowHandle))
  211681. {
  211682. asioObject->getErrorMessage (buffer);
  211683. return String (buffer, sizeof (buffer) - 1);
  211684. }
  211685. // just in case any daft drivers expect this to be called..
  211686. asioObject->getDriverName (buffer);
  211687. return String::empty;
  211688. }
  211689. return "No Driver";
  211690. }
  211691. const String openDevice()
  211692. {
  211693. // use this in case the driver starts opening dialog boxes..
  211694. Component modalWindow (String::empty);
  211695. modalWindow.setOpaque (true);
  211696. modalWindow.addToDesktop (0);
  211697. modalWindow.enterModalState();
  211698. // open the device and get its info..
  211699. log ("opening ASIO device: " + getName());
  211700. needToReset = false;
  211701. isReSync = false;
  211702. outputChannelNames.clear();
  211703. inputChannelNames.clear();
  211704. bufferSizes.clear();
  211705. sampleRates.clear();
  211706. isASIOOpen = false;
  211707. isOpen_ = false;
  211708. totalNumInputChans = 0;
  211709. totalNumOutputChans = 0;
  211710. numActiveInputChans = 0;
  211711. numActiveOutputChans = 0;
  211712. currentCallback = 0;
  211713. error = String::empty;
  211714. if (getName().isEmpty())
  211715. return error;
  211716. long err = 0;
  211717. if (loadDriver())
  211718. {
  211719. if ((error = initDriver()).isEmpty())
  211720. {
  211721. numActiveInputChans = 0;
  211722. numActiveOutputChans = 0;
  211723. totalNumInputChans = 0;
  211724. totalNumOutputChans = 0;
  211725. if (asioObject != 0
  211726. && (err = asioObject->getChannels (&totalNumInputChans, &totalNumOutputChans)) == 0)
  211727. {
  211728. log (String ((int) totalNumInputChans) + " in, " + String ((int) totalNumOutputChans) + " out");
  211729. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  211730. {
  211731. // find a list of buffer sizes..
  211732. log (String ((int) minSize) + " " + String ((int) maxSize) + " " + String ((int) preferredSize) + " " + String ((int) granularity));
  211733. if (granularity >= 0)
  211734. {
  211735. granularity = jmax (1, (int) granularity);
  211736. for (int i = jmax ((int) minSize, (int) granularity); i < jmin (6400, (int) maxSize); i += granularity)
  211737. bufferSizes.addIfNotAlreadyThere (granularity * (i / granularity));
  211738. }
  211739. else if (granularity < 0)
  211740. {
  211741. for (int i = 0; i < 18; ++i)
  211742. {
  211743. const int s = (1 << i);
  211744. if (s >= minSize && s <= maxSize)
  211745. bufferSizes.add (s);
  211746. }
  211747. }
  211748. if (! bufferSizes.contains (preferredSize))
  211749. bufferSizes.insert (0, preferredSize);
  211750. double currentRate = 0;
  211751. asioObject->getSampleRate (&currentRate);
  211752. if (currentRate <= 0.0 || currentRate > 192001.0)
  211753. {
  211754. log ("setting sample rate");
  211755. err = asioObject->setSampleRate (44100.0);
  211756. if (err != 0)
  211757. {
  211758. logError ("setting sample rate", err);
  211759. }
  211760. asioObject->getSampleRate (&currentRate);
  211761. }
  211762. currentSampleRate = currentRate;
  211763. postOutput = (asioObject->outputReady() == 0);
  211764. if (postOutput)
  211765. {
  211766. log ("ASIO outputReady = ok");
  211767. }
  211768. updateSampleRates();
  211769. // ..because cubase does it at this point
  211770. inputLatency = outputLatency = 0;
  211771. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  211772. {
  211773. log ("ASIO - no latencies");
  211774. }
  211775. log ("latencies: " + String ((int) inputLatency) + ", " + String ((int) outputLatency));
  211776. // create some dummy buffers now.. because cubase does..
  211777. numActiveInputChans = 0;
  211778. numActiveOutputChans = 0;
  211779. ASIOBufferInfo* info = bufferInfos;
  211780. int i, numChans = 0;
  211781. for (i = 0; i < jmin (2, (int) totalNumInputChans); ++i)
  211782. {
  211783. info->isInput = 1;
  211784. info->channelNum = i;
  211785. info->buffers[0] = info->buffers[1] = 0;
  211786. ++info;
  211787. ++numChans;
  211788. }
  211789. const int outputBufferIndex = numChans;
  211790. for (i = 0; i < jmin (2, (int) totalNumOutputChans); ++i)
  211791. {
  211792. info->isInput = 0;
  211793. info->channelNum = i;
  211794. info->buffers[0] = info->buffers[1] = 0;
  211795. ++info;
  211796. ++numChans;
  211797. }
  211798. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  211799. if (currentASIODev[0] == this)
  211800. {
  211801. callbacks.bufferSwitch = &bufferSwitchCallback0;
  211802. callbacks.asioMessage = &asioMessagesCallback0;
  211803. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  211804. }
  211805. else if (currentASIODev[1] == this)
  211806. {
  211807. callbacks.bufferSwitch = &bufferSwitchCallback1;
  211808. callbacks.asioMessage = &asioMessagesCallback1;
  211809. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  211810. }
  211811. else if (currentASIODev[2] == this)
  211812. {
  211813. callbacks.bufferSwitch = &bufferSwitchCallback2;
  211814. callbacks.asioMessage = &asioMessagesCallback2;
  211815. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  211816. }
  211817. else
  211818. {
  211819. jassertfalse;
  211820. }
  211821. log ("creating buffers (dummy): " + String (numChans) + ", " + String ((int) preferredSize));
  211822. if (preferredSize > 0)
  211823. {
  211824. err = asioObject->createBuffers (bufferInfos, numChans, preferredSize, &callbacks);
  211825. if (err != 0)
  211826. {
  211827. logError ("dummy buffers", err);
  211828. }
  211829. }
  211830. long newInps = 0, newOuts = 0;
  211831. asioObject->getChannels (&newInps, &newOuts);
  211832. if (totalNumInputChans != newInps || totalNumOutputChans != newOuts)
  211833. {
  211834. totalNumInputChans = newInps;
  211835. totalNumOutputChans = newOuts;
  211836. log (String ((int) totalNumInputChans) + " in; " + String ((int) totalNumOutputChans) + " out");
  211837. }
  211838. updateSampleRates();
  211839. ASIOChannelInfo channelInfo;
  211840. channelInfo.type = 0;
  211841. for (i = 0; i < totalNumInputChans; ++i)
  211842. {
  211843. zerostruct (channelInfo);
  211844. channelInfo.channel = i;
  211845. channelInfo.isInput = 1;
  211846. asioObject->getChannelInfo (&channelInfo);
  211847. inputChannelNames.add (String (channelInfo.name));
  211848. }
  211849. for (i = 0; i < totalNumOutputChans; ++i)
  211850. {
  211851. zerostruct (channelInfo);
  211852. channelInfo.channel = i;
  211853. channelInfo.isInput = 0;
  211854. asioObject->getChannelInfo (&channelInfo);
  211855. outputChannelNames.add (String (channelInfo.name));
  211856. typeToFormatParameters (channelInfo.type,
  211857. outputChannelBitDepths[i],
  211858. outputChannelBytesPerSample[i],
  211859. outputChannelIsFloat[i],
  211860. outputChannelLittleEndian[i]);
  211861. if (i < 2)
  211862. {
  211863. // clear the channels that are used with the dummy stuff
  211864. const int bytesPerBuffer = preferredSize * (outputChannelBitDepths[i] >> 3);
  211865. zeromem (bufferInfos [outputBufferIndex + i].buffers[0], bytesPerBuffer);
  211866. zeromem (bufferInfos [outputBufferIndex + i].buffers[1], bytesPerBuffer);
  211867. }
  211868. }
  211869. outputChannelNames.trim();
  211870. inputChannelNames.trim();
  211871. outputChannelNames.appendNumbersToDuplicates (false, true);
  211872. inputChannelNames.appendNumbersToDuplicates (false, true);
  211873. // start and stop because cubase does it..
  211874. asioObject->getLatencies (&inputLatency, &outputLatency);
  211875. if ((err = asioObject->start()) != 0)
  211876. {
  211877. // ignore an error here, as it might start later after setting other stuff up
  211878. logError ("ASIO start", err);
  211879. }
  211880. Thread::sleep (100);
  211881. asioObject->stop();
  211882. }
  211883. else
  211884. {
  211885. error = "Can't detect buffer sizes";
  211886. }
  211887. }
  211888. else
  211889. {
  211890. error = "Can't detect asio channels";
  211891. }
  211892. }
  211893. }
  211894. else
  211895. {
  211896. error = "No such device";
  211897. }
  211898. if (error.isNotEmpty())
  211899. {
  211900. logError (error, err);
  211901. if (asioObject != 0)
  211902. asioObject->disposeBuffers();
  211903. removeCurrentDriver();
  211904. isASIOOpen = false;
  211905. }
  211906. else
  211907. {
  211908. isASIOOpen = true;
  211909. log ("ASIO device open");
  211910. }
  211911. isOpen_ = false;
  211912. needToReset = false;
  211913. isReSync = false;
  211914. return error;
  211915. }
  211916. void callback (const long index)
  211917. {
  211918. if (isStarted)
  211919. {
  211920. bufferIndex = index;
  211921. processBuffer();
  211922. }
  211923. else
  211924. {
  211925. if (postOutput && (asioObject != 0))
  211926. asioObject->outputReady();
  211927. }
  211928. calledback = true;
  211929. }
  211930. void processBuffer()
  211931. {
  211932. const ASIOBufferInfo* const infos = bufferInfos;
  211933. const int bi = bufferIndex;
  211934. const ScopedLock sl (callbackLock);
  211935. if (needToReset)
  211936. {
  211937. needToReset = false;
  211938. if (isReSync)
  211939. {
  211940. log ("! ASIO resync");
  211941. isReSync = false;
  211942. }
  211943. else
  211944. {
  211945. startTimer (20);
  211946. }
  211947. }
  211948. if (bi >= 0)
  211949. {
  211950. const int samps = currentBlockSizeSamples;
  211951. if (currentCallback != 0)
  211952. {
  211953. int i;
  211954. for (i = 0; i < numActiveInputChans; ++i)
  211955. {
  211956. float* const dst = inBuffers[i];
  211957. jassert (dst != 0);
  211958. const char* const src = (const char*) (infos[i].buffers[bi]);
  211959. if (inputChannelIsFloat[i])
  211960. {
  211961. memcpy (dst, src, samps * sizeof (float));
  211962. }
  211963. else
  211964. {
  211965. jassert (dst == tempBuffer + (samps * i));
  211966. switch (inputChannelBitDepths[i])
  211967. {
  211968. case 16:
  211969. convertInt16ToFloat (src, dst, inputChannelBytesPerSample[i],
  211970. samps, inputChannelLittleEndian[i]);
  211971. break;
  211972. case 24:
  211973. convertInt24ToFloat (src, dst, inputChannelBytesPerSample[i],
  211974. samps, inputChannelLittleEndian[i]);
  211975. break;
  211976. case 32:
  211977. convertInt32ToFloat (src, dst, inputChannelBytesPerSample[i],
  211978. samps, inputChannelLittleEndian[i]);
  211979. break;
  211980. case 64:
  211981. jassertfalse;
  211982. break;
  211983. }
  211984. }
  211985. }
  211986. currentCallback->audioDeviceIOCallback ((const float**) inBuffers,
  211987. numActiveInputChans,
  211988. outBuffers,
  211989. numActiveOutputChans,
  211990. samps);
  211991. for (i = 0; i < numActiveOutputChans; ++i)
  211992. {
  211993. float* const src = outBuffers[i];
  211994. jassert (src != 0);
  211995. char* const dst = (char*) (infos [numActiveInputChans + i].buffers[bi]);
  211996. if (outputChannelIsFloat[i])
  211997. {
  211998. memcpy (dst, src, samps * sizeof (float));
  211999. }
  212000. else
  212001. {
  212002. jassert (src == tempBuffer + (samps * (numActiveInputChans + i)));
  212003. switch (outputChannelBitDepths[i])
  212004. {
  212005. case 16:
  212006. convertFloatToInt16 (src, dst, outputChannelBytesPerSample[i],
  212007. samps, outputChannelLittleEndian[i]);
  212008. break;
  212009. case 24:
  212010. convertFloatToInt24 (src, dst, outputChannelBytesPerSample[i],
  212011. samps, outputChannelLittleEndian[i]);
  212012. break;
  212013. case 32:
  212014. convertFloatToInt32 (src, dst, outputChannelBytesPerSample[i],
  212015. samps, outputChannelLittleEndian[i]);
  212016. break;
  212017. case 64:
  212018. jassertfalse;
  212019. break;
  212020. }
  212021. }
  212022. }
  212023. }
  212024. else
  212025. {
  212026. for (int i = 0; i < numActiveOutputChans; ++i)
  212027. {
  212028. const int bytesPerBuffer = samps * (outputChannelBitDepths[i] >> 3);
  212029. zeromem (infos[numActiveInputChans + i].buffers[bi], bytesPerBuffer);
  212030. }
  212031. }
  212032. }
  212033. if (postOutput)
  212034. asioObject->outputReady();
  212035. }
  212036. static ASIOTime* bufferSwitchTimeInfoCallback0 (ASIOTime*, long index, long)
  212037. {
  212038. if (currentASIODev[0] != 0)
  212039. currentASIODev[0]->callback (index);
  212040. return 0;
  212041. }
  212042. static ASIOTime* bufferSwitchTimeInfoCallback1 (ASIOTime*, long index, long)
  212043. {
  212044. if (currentASIODev[1] != 0)
  212045. currentASIODev[1]->callback (index);
  212046. return 0;
  212047. }
  212048. static ASIOTime* bufferSwitchTimeInfoCallback2 (ASIOTime*, long index, long)
  212049. {
  212050. if (currentASIODev[2] != 0)
  212051. currentASIODev[2]->callback (index);
  212052. return 0;
  212053. }
  212054. static void bufferSwitchCallback0 (long index, long)
  212055. {
  212056. if (currentASIODev[0] != 0)
  212057. currentASIODev[0]->callback (index);
  212058. }
  212059. static void bufferSwitchCallback1 (long index, long)
  212060. {
  212061. if (currentASIODev[1] != 0)
  212062. currentASIODev[1]->callback (index);
  212063. }
  212064. static void bufferSwitchCallback2 (long index, long)
  212065. {
  212066. if (currentASIODev[2] != 0)
  212067. currentASIODev[2]->callback (index);
  212068. }
  212069. static long asioMessagesCallback0 (long selector, long value, void*, double*)
  212070. {
  212071. return asioMessagesCallback (selector, value, 0);
  212072. }
  212073. static long asioMessagesCallback1 (long selector, long value, void*, double*)
  212074. {
  212075. return asioMessagesCallback (selector, value, 1);
  212076. }
  212077. static long asioMessagesCallback2 (long selector, long value, void*, double*)
  212078. {
  212079. return asioMessagesCallback (selector, value, 2);
  212080. }
  212081. static long asioMessagesCallback (long selector, long value, const int deviceIndex)
  212082. {
  212083. switch (selector)
  212084. {
  212085. case kAsioSelectorSupported:
  212086. if (value == kAsioResetRequest
  212087. || value == kAsioEngineVersion
  212088. || value == kAsioResyncRequest
  212089. || value == kAsioLatenciesChanged
  212090. || value == kAsioSupportsInputMonitor)
  212091. return 1;
  212092. break;
  212093. case kAsioBufferSizeChange:
  212094. break;
  212095. case kAsioResetRequest:
  212096. if (currentASIODev[deviceIndex] != 0)
  212097. currentASIODev[deviceIndex]->resetRequest();
  212098. return 1;
  212099. case kAsioResyncRequest:
  212100. if (currentASIODev[deviceIndex] != 0)
  212101. currentASIODev[deviceIndex]->resyncRequest();
  212102. return 1;
  212103. case kAsioLatenciesChanged:
  212104. return 1;
  212105. case kAsioEngineVersion:
  212106. return 2;
  212107. case kAsioSupportsTimeInfo:
  212108. case kAsioSupportsTimeCode:
  212109. return 0;
  212110. }
  212111. return 0;
  212112. }
  212113. static void sampleRateChangedCallback (ASIOSampleRate) throw()
  212114. {
  212115. }
  212116. static void convertInt16ToFloat (const char* src,
  212117. float* dest,
  212118. const int srcStrideBytes,
  212119. int numSamples,
  212120. const bool littleEndian) throw()
  212121. {
  212122. const double g = 1.0 / 32768.0;
  212123. if (littleEndian)
  212124. {
  212125. while (--numSamples >= 0)
  212126. {
  212127. *dest++ = (float) (g * (short) ByteOrder::littleEndianShort (src));
  212128. src += srcStrideBytes;
  212129. }
  212130. }
  212131. else
  212132. {
  212133. while (--numSamples >= 0)
  212134. {
  212135. *dest++ = (float) (g * (short) ByteOrder::bigEndianShort (src));
  212136. src += srcStrideBytes;
  212137. }
  212138. }
  212139. }
  212140. static void convertFloatToInt16 (const float* src,
  212141. char* dest,
  212142. const int dstStrideBytes,
  212143. int numSamples,
  212144. const bool littleEndian) throw()
  212145. {
  212146. const double maxVal = (double) 0x7fff;
  212147. if (littleEndian)
  212148. {
  212149. while (--numSamples >= 0)
  212150. {
  212151. *(uint16*) dest = ByteOrder::swapIfBigEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  212152. dest += dstStrideBytes;
  212153. }
  212154. }
  212155. else
  212156. {
  212157. while (--numSamples >= 0)
  212158. {
  212159. *(uint16*) dest = ByteOrder::swapIfLittleEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  212160. dest += dstStrideBytes;
  212161. }
  212162. }
  212163. }
  212164. static void convertInt24ToFloat (const char* src,
  212165. float* dest,
  212166. const int srcStrideBytes,
  212167. int numSamples,
  212168. const bool littleEndian) throw()
  212169. {
  212170. const double g = 1.0 / 0x7fffff;
  212171. if (littleEndian)
  212172. {
  212173. while (--numSamples >= 0)
  212174. {
  212175. *dest++ = (float) (g * ByteOrder::littleEndian24Bit (src));
  212176. src += srcStrideBytes;
  212177. }
  212178. }
  212179. else
  212180. {
  212181. while (--numSamples >= 0)
  212182. {
  212183. *dest++ = (float) (g * ByteOrder::bigEndian24Bit (src));
  212184. src += srcStrideBytes;
  212185. }
  212186. }
  212187. }
  212188. static void convertFloatToInt24 (const float* src,
  212189. char* dest,
  212190. const int dstStrideBytes,
  212191. int numSamples,
  212192. const bool littleEndian) throw()
  212193. {
  212194. const double maxVal = (double) 0x7fffff;
  212195. if (littleEndian)
  212196. {
  212197. while (--numSamples >= 0)
  212198. {
  212199. ByteOrder::littleEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  212200. dest += dstStrideBytes;
  212201. }
  212202. }
  212203. else
  212204. {
  212205. while (--numSamples >= 0)
  212206. {
  212207. ByteOrder::bigEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  212208. dest += dstStrideBytes;
  212209. }
  212210. }
  212211. }
  212212. static void convertInt32ToFloat (const char* src,
  212213. float* dest,
  212214. const int srcStrideBytes,
  212215. int numSamples,
  212216. const bool littleEndian) throw()
  212217. {
  212218. const double g = 1.0 / 0x7fffffff;
  212219. if (littleEndian)
  212220. {
  212221. while (--numSamples >= 0)
  212222. {
  212223. *dest++ = (float) (g * (int) ByteOrder::littleEndianInt (src));
  212224. src += srcStrideBytes;
  212225. }
  212226. }
  212227. else
  212228. {
  212229. while (--numSamples >= 0)
  212230. {
  212231. *dest++ = (float) (g * (int) ByteOrder::bigEndianInt (src));
  212232. src += srcStrideBytes;
  212233. }
  212234. }
  212235. }
  212236. static void convertFloatToInt32 (const float* src,
  212237. char* dest,
  212238. const int dstStrideBytes,
  212239. int numSamples,
  212240. const bool littleEndian) throw()
  212241. {
  212242. const double maxVal = (double) 0x7fffffff;
  212243. if (littleEndian)
  212244. {
  212245. while (--numSamples >= 0)
  212246. {
  212247. *(uint32*) dest = ByteOrder::swapIfBigEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  212248. dest += dstStrideBytes;
  212249. }
  212250. }
  212251. else
  212252. {
  212253. while (--numSamples >= 0)
  212254. {
  212255. *(uint32*) dest = ByteOrder::swapIfLittleEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  212256. dest += dstStrideBytes;
  212257. }
  212258. }
  212259. }
  212260. static void typeToFormatParameters (const long type,
  212261. int& bitDepth,
  212262. int& byteStride,
  212263. bool& formatIsFloat,
  212264. bool& littleEndian) throw()
  212265. {
  212266. bitDepth = 0;
  212267. littleEndian = false;
  212268. formatIsFloat = false;
  212269. switch (type)
  212270. {
  212271. case ASIOSTInt16MSB:
  212272. case ASIOSTInt16LSB:
  212273. case ASIOSTInt32MSB16:
  212274. case ASIOSTInt32LSB16:
  212275. bitDepth = 16; break;
  212276. case ASIOSTFloat32MSB:
  212277. case ASIOSTFloat32LSB:
  212278. formatIsFloat = true;
  212279. bitDepth = 32; break;
  212280. case ASIOSTInt32MSB:
  212281. case ASIOSTInt32LSB:
  212282. bitDepth = 32; break;
  212283. case ASIOSTInt24MSB:
  212284. case ASIOSTInt24LSB:
  212285. case ASIOSTInt32MSB24:
  212286. case ASIOSTInt32LSB24:
  212287. case ASIOSTInt32MSB18:
  212288. case ASIOSTInt32MSB20:
  212289. case ASIOSTInt32LSB18:
  212290. case ASIOSTInt32LSB20:
  212291. bitDepth = 24; break;
  212292. case ASIOSTFloat64MSB:
  212293. case ASIOSTFloat64LSB:
  212294. default:
  212295. bitDepth = 64;
  212296. break;
  212297. }
  212298. switch (type)
  212299. {
  212300. case ASIOSTInt16MSB:
  212301. case ASIOSTInt32MSB16:
  212302. case ASIOSTFloat32MSB:
  212303. case ASIOSTFloat64MSB:
  212304. case ASIOSTInt32MSB:
  212305. case ASIOSTInt32MSB18:
  212306. case ASIOSTInt32MSB20:
  212307. case ASIOSTInt32MSB24:
  212308. case ASIOSTInt24MSB:
  212309. littleEndian = false; break;
  212310. case ASIOSTInt16LSB:
  212311. case ASIOSTInt32LSB16:
  212312. case ASIOSTFloat32LSB:
  212313. case ASIOSTFloat64LSB:
  212314. case ASIOSTInt32LSB:
  212315. case ASIOSTInt32LSB18:
  212316. case ASIOSTInt32LSB20:
  212317. case ASIOSTInt32LSB24:
  212318. case ASIOSTInt24LSB:
  212319. littleEndian = true; break;
  212320. default:
  212321. break;
  212322. }
  212323. switch (type)
  212324. {
  212325. case ASIOSTInt16LSB:
  212326. case ASIOSTInt16MSB:
  212327. byteStride = 2; break;
  212328. case ASIOSTInt24LSB:
  212329. case ASIOSTInt24MSB:
  212330. byteStride = 3; break;
  212331. case ASIOSTInt32MSB16:
  212332. case ASIOSTInt32LSB16:
  212333. case ASIOSTInt32MSB:
  212334. case ASIOSTInt32MSB18:
  212335. case ASIOSTInt32MSB20:
  212336. case ASIOSTInt32MSB24:
  212337. case ASIOSTInt32LSB:
  212338. case ASIOSTInt32LSB18:
  212339. case ASIOSTInt32LSB20:
  212340. case ASIOSTInt32LSB24:
  212341. case ASIOSTFloat32LSB:
  212342. case ASIOSTFloat32MSB:
  212343. byteStride = 4; break;
  212344. case ASIOSTFloat64MSB:
  212345. case ASIOSTFloat64LSB:
  212346. byteStride = 8; break;
  212347. default:
  212348. break;
  212349. }
  212350. }
  212351. };
  212352. class ASIOAudioIODeviceType : public AudioIODeviceType
  212353. {
  212354. public:
  212355. ASIOAudioIODeviceType()
  212356. : AudioIODeviceType ("ASIO"),
  212357. hasScanned (false)
  212358. {
  212359. CoInitialize (0);
  212360. }
  212361. ~ASIOAudioIODeviceType()
  212362. {
  212363. }
  212364. void scanForDevices()
  212365. {
  212366. hasScanned = true;
  212367. deviceNames.clear();
  212368. classIds.clear();
  212369. HKEY hk = 0;
  212370. int index = 0;
  212371. if (RegOpenKeyA (HKEY_LOCAL_MACHINE, "software\\asio", &hk) == ERROR_SUCCESS)
  212372. {
  212373. for (;;)
  212374. {
  212375. char name [256];
  212376. if (RegEnumKeyA (hk, index++, name, 256) == ERROR_SUCCESS)
  212377. {
  212378. addDriverInfo (name, hk);
  212379. }
  212380. else
  212381. {
  212382. break;
  212383. }
  212384. }
  212385. RegCloseKey (hk);
  212386. }
  212387. }
  212388. const StringArray getDeviceNames (bool /*wantInputNames*/) const
  212389. {
  212390. jassert (hasScanned); // need to call scanForDevices() before doing this
  212391. return deviceNames;
  212392. }
  212393. int getDefaultDeviceIndex (bool) const
  212394. {
  212395. jassert (hasScanned); // need to call scanForDevices() before doing this
  212396. for (int i = deviceNames.size(); --i >= 0;)
  212397. if (deviceNames[i].containsIgnoreCase ("asio4all"))
  212398. return i; // asio4all is a safe choice for a default..
  212399. #if JUCE_DEBUG
  212400. if (deviceNames.size() > 1 && deviceNames[0].containsIgnoreCase ("digidesign"))
  212401. return 1; // (the digi m-box driver crashes the app when you run
  212402. // it in the debugger, which can be a bit annoying)
  212403. #endif
  212404. return 0;
  212405. }
  212406. static int findFreeSlot()
  212407. {
  212408. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  212409. if (currentASIODev[i] == 0)
  212410. return i;
  212411. jassertfalse; // unfortunately you can only have a finite number
  212412. // of ASIO devices open at the same time..
  212413. return -1;
  212414. }
  212415. int getIndexOfDevice (AudioIODevice* d, bool /*asInput*/) const
  212416. {
  212417. jassert (hasScanned); // need to call scanForDevices() before doing this
  212418. return d == 0 ? -1 : deviceNames.indexOf (d->getName());
  212419. }
  212420. bool hasSeparateInputsAndOutputs() const { return false; }
  212421. AudioIODevice* createDevice (const String& outputDeviceName,
  212422. const String& inputDeviceName)
  212423. {
  212424. // ASIO can't open two different devices for input and output - they must be the same one.
  212425. jassert (inputDeviceName == outputDeviceName || outputDeviceName.isEmpty() || inputDeviceName.isEmpty());
  212426. jassert (hasScanned); // need to call scanForDevices() before doing this
  212427. const int index = deviceNames.indexOf (outputDeviceName.isNotEmpty() ? outputDeviceName
  212428. : inputDeviceName);
  212429. if (index >= 0)
  212430. {
  212431. const int freeSlot = findFreeSlot();
  212432. if (freeSlot >= 0)
  212433. return new ASIOAudioIODevice (outputDeviceName, *(classIds [index]), freeSlot, String::empty);
  212434. }
  212435. return 0;
  212436. }
  212437. juce_UseDebuggingNewOperator
  212438. private:
  212439. StringArray deviceNames;
  212440. OwnedArray <CLSID> classIds;
  212441. bool hasScanned;
  212442. static bool checkClassIsOk (const String& classId)
  212443. {
  212444. HKEY hk = 0;
  212445. bool ok = false;
  212446. if (RegOpenKey (HKEY_CLASSES_ROOT, _T("clsid"), &hk) == ERROR_SUCCESS)
  212447. {
  212448. int index = 0;
  212449. for (;;)
  212450. {
  212451. WCHAR buf [512];
  212452. if (RegEnumKey (hk, index++, buf, 512) == ERROR_SUCCESS)
  212453. {
  212454. if (classId.equalsIgnoreCase (buf))
  212455. {
  212456. HKEY subKey, pathKey;
  212457. if (RegOpenKeyEx (hk, buf, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  212458. {
  212459. if (RegOpenKeyEx (subKey, _T("InprocServer32"), 0, KEY_READ, &pathKey) == ERROR_SUCCESS)
  212460. {
  212461. WCHAR pathName [1024];
  212462. DWORD dtype = REG_SZ;
  212463. DWORD dsize = sizeof (pathName);
  212464. if (RegQueryValueEx (pathKey, 0, 0, &dtype, (LPBYTE) pathName, &dsize) == ERROR_SUCCESS)
  212465. ok = File (pathName).exists();
  212466. RegCloseKey (pathKey);
  212467. }
  212468. RegCloseKey (subKey);
  212469. }
  212470. break;
  212471. }
  212472. }
  212473. else
  212474. {
  212475. break;
  212476. }
  212477. }
  212478. RegCloseKey (hk);
  212479. }
  212480. return ok;
  212481. }
  212482. void addDriverInfo (const String& keyName, HKEY hk)
  212483. {
  212484. HKEY subKey;
  212485. if (RegOpenKeyEx (hk, keyName, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  212486. {
  212487. WCHAR buf [256];
  212488. zerostruct (buf);
  212489. DWORD dtype = REG_SZ;
  212490. DWORD dsize = sizeof (buf);
  212491. if (RegQueryValueEx (subKey, _T("clsid"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  212492. {
  212493. if (dsize > 0 && checkClassIsOk (buf))
  212494. {
  212495. CLSID classId;
  212496. if (CLSIDFromString ((LPOLESTR) buf, &classId) == S_OK)
  212497. {
  212498. dtype = REG_SZ;
  212499. dsize = sizeof (buf);
  212500. String deviceName;
  212501. if (RegQueryValueEx (subKey, _T("description"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  212502. deviceName = buf;
  212503. else
  212504. deviceName = keyName;
  212505. log ("found " + deviceName);
  212506. deviceNames.add (deviceName);
  212507. classIds.add (new CLSID (classId));
  212508. }
  212509. }
  212510. RegCloseKey (subKey);
  212511. }
  212512. }
  212513. }
  212514. ASIOAudioIODeviceType (const ASIOAudioIODeviceType&);
  212515. ASIOAudioIODeviceType& operator= (const ASIOAudioIODeviceType&);
  212516. };
  212517. AudioIODeviceType* juce_createAudioIODeviceType_ASIO()
  212518. {
  212519. return new ASIOAudioIODeviceType();
  212520. }
  212521. AudioIODevice* juce_createASIOAudioIODeviceForGUID (const String& name,
  212522. void* guid,
  212523. const String& optionalDllForDirectLoading)
  212524. {
  212525. const int freeSlot = ASIOAudioIODeviceType::findFreeSlot();
  212526. if (freeSlot < 0)
  212527. return 0;
  212528. return new ASIOAudioIODevice (name, *(CLSID*) guid, freeSlot, optionalDllForDirectLoading);
  212529. }
  212530. #undef log
  212531. #endif
  212532. /*** End of inlined file: juce_win32_ASIO.cpp ***/
  212533. /*** Start of inlined file: juce_win32_DirectSound.cpp ***/
  212534. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  212535. // compiled on its own).
  212536. #if JUCE_INCLUDED_FILE && JUCE_DIRECTSOUND
  212537. END_JUCE_NAMESPACE
  212538. extern "C"
  212539. {
  212540. // Declare just the minimum number of interfaces for the DSound objects that we need..
  212541. typedef struct typeDSBUFFERDESC
  212542. {
  212543. DWORD dwSize;
  212544. DWORD dwFlags;
  212545. DWORD dwBufferBytes;
  212546. DWORD dwReserved;
  212547. LPWAVEFORMATEX lpwfxFormat;
  212548. GUID guid3DAlgorithm;
  212549. } DSBUFFERDESC;
  212550. struct IDirectSoundBuffer;
  212551. #undef INTERFACE
  212552. #define INTERFACE IDirectSound
  212553. DECLARE_INTERFACE_(IDirectSound, IUnknown)
  212554. {
  212555. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  212556. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  212557. STDMETHOD_(ULONG,Release) (THIS) PURE;
  212558. STDMETHOD(CreateSoundBuffer) (THIS_ DSBUFFERDESC*, IDirectSoundBuffer**, LPUNKNOWN) PURE;
  212559. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  212560. STDMETHOD(DuplicateSoundBuffer) (THIS_ IDirectSoundBuffer*, IDirectSoundBuffer**) PURE;
  212561. STDMETHOD(SetCooperativeLevel) (THIS_ HWND, DWORD) PURE;
  212562. STDMETHOD(Compact) (THIS) PURE;
  212563. STDMETHOD(GetSpeakerConfig) (THIS_ LPDWORD) PURE;
  212564. STDMETHOD(SetSpeakerConfig) (THIS_ DWORD) PURE;
  212565. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  212566. };
  212567. #undef INTERFACE
  212568. #define INTERFACE IDirectSoundBuffer
  212569. DECLARE_INTERFACE_(IDirectSoundBuffer, IUnknown)
  212570. {
  212571. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  212572. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  212573. STDMETHOD_(ULONG,Release) (THIS) PURE;
  212574. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  212575. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  212576. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  212577. STDMETHOD(GetVolume) (THIS_ LPLONG) PURE;
  212578. STDMETHOD(GetPan) (THIS_ LPLONG) PURE;
  212579. STDMETHOD(GetFrequency) (THIS_ LPDWORD) PURE;
  212580. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  212581. STDMETHOD(Initialize) (THIS_ IDirectSound*, DSBUFFERDESC*) PURE;
  212582. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  212583. STDMETHOD(Play) (THIS_ DWORD, DWORD, DWORD) PURE;
  212584. STDMETHOD(SetCurrentPosition) (THIS_ DWORD) PURE;
  212585. STDMETHOD(SetFormat) (THIS_ const WAVEFORMATEX*) PURE;
  212586. STDMETHOD(SetVolume) (THIS_ LONG) PURE;
  212587. STDMETHOD(SetPan) (THIS_ LONG) PURE;
  212588. STDMETHOD(SetFrequency) (THIS_ DWORD) PURE;
  212589. STDMETHOD(Stop) (THIS) PURE;
  212590. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  212591. STDMETHOD(Restore) (THIS) PURE;
  212592. };
  212593. typedef struct typeDSCBUFFERDESC
  212594. {
  212595. DWORD dwSize;
  212596. DWORD dwFlags;
  212597. DWORD dwBufferBytes;
  212598. DWORD dwReserved;
  212599. LPWAVEFORMATEX lpwfxFormat;
  212600. } DSCBUFFERDESC;
  212601. struct IDirectSoundCaptureBuffer;
  212602. #undef INTERFACE
  212603. #define INTERFACE IDirectSoundCapture
  212604. DECLARE_INTERFACE_(IDirectSoundCapture, IUnknown)
  212605. {
  212606. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  212607. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  212608. STDMETHOD_(ULONG,Release) (THIS) PURE;
  212609. STDMETHOD(CreateCaptureBuffer) (THIS_ DSCBUFFERDESC*, IDirectSoundCaptureBuffer**, LPUNKNOWN) PURE;
  212610. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  212611. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  212612. };
  212613. #undef INTERFACE
  212614. #define INTERFACE IDirectSoundCaptureBuffer
  212615. DECLARE_INTERFACE_(IDirectSoundCaptureBuffer, IUnknown)
  212616. {
  212617. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  212618. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  212619. STDMETHOD_(ULONG,Release) (THIS) PURE;
  212620. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  212621. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  212622. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  212623. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  212624. STDMETHOD(Initialize) (THIS_ IDirectSoundCapture*, DSCBUFFERDESC*) PURE;
  212625. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  212626. STDMETHOD(Start) (THIS_ DWORD) PURE;
  212627. STDMETHOD(Stop) (THIS) PURE;
  212628. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  212629. };
  212630. };
  212631. BEGIN_JUCE_NAMESPACE
  212632. static const String getDSErrorMessage (HRESULT hr)
  212633. {
  212634. const char* result = 0;
  212635. switch (hr)
  212636. {
  212637. case MAKE_HRESULT(1, 0x878, 10):
  212638. result = "Device already allocated";
  212639. break;
  212640. case MAKE_HRESULT(1, 0x878, 30):
  212641. result = "Control unavailable";
  212642. break;
  212643. case E_INVALIDARG:
  212644. result = "Invalid parameter";
  212645. break;
  212646. case MAKE_HRESULT(1, 0x878, 50):
  212647. result = "Invalid call";
  212648. break;
  212649. case E_FAIL:
  212650. result = "Generic error";
  212651. break;
  212652. case MAKE_HRESULT(1, 0x878, 70):
  212653. result = "Priority level error";
  212654. break;
  212655. case E_OUTOFMEMORY:
  212656. result = "Out of memory";
  212657. break;
  212658. case MAKE_HRESULT(1, 0x878, 100):
  212659. result = "Bad format";
  212660. break;
  212661. case E_NOTIMPL:
  212662. result = "Unsupported function";
  212663. break;
  212664. case MAKE_HRESULT(1, 0x878, 120):
  212665. result = "No driver";
  212666. break;
  212667. case MAKE_HRESULT(1, 0x878, 130):
  212668. result = "Already initialised";
  212669. break;
  212670. case CLASS_E_NOAGGREGATION:
  212671. result = "No aggregation";
  212672. break;
  212673. case MAKE_HRESULT(1, 0x878, 150):
  212674. result = "Buffer lost";
  212675. break;
  212676. case MAKE_HRESULT(1, 0x878, 160):
  212677. result = "Another app has priority";
  212678. break;
  212679. case MAKE_HRESULT(1, 0x878, 170):
  212680. result = "Uninitialised";
  212681. break;
  212682. case E_NOINTERFACE:
  212683. result = "No interface";
  212684. break;
  212685. case S_OK:
  212686. result = "No error";
  212687. break;
  212688. default:
  212689. return "Unknown error: " + String ((int) hr);
  212690. }
  212691. return result;
  212692. }
  212693. #define DS_DEBUGGING 1
  212694. #ifdef DS_DEBUGGING
  212695. #define CATCH JUCE_CATCH_EXCEPTION
  212696. #undef log
  212697. #define log(a) Logger::writeToLog(a);
  212698. #undef logError
  212699. #define logError(a) logDSError(a, __LINE__);
  212700. static void logDSError (HRESULT hr, int lineNum)
  212701. {
  212702. if (hr != S_OK)
  212703. {
  212704. String error ("DS error at line ");
  212705. error << lineNum << " - " << getDSErrorMessage (hr);
  212706. log (error);
  212707. }
  212708. }
  212709. #else
  212710. #define CATCH JUCE_CATCH_ALL
  212711. #define log(a)
  212712. #define logError(a)
  212713. #endif
  212714. #define DSOUND_FUNCTION(functionName, params) \
  212715. typedef HRESULT (WINAPI *type##functionName) params; \
  212716. static type##functionName ds##functionName = 0;
  212717. #define DSOUND_FUNCTION_LOAD(functionName) \
  212718. ds##functionName = (type##functionName) GetProcAddress (h, #functionName); \
  212719. jassert (ds##functionName != 0);
  212720. typedef BOOL (CALLBACK *LPDSENUMCALLBACKW) (LPGUID, LPCWSTR, LPCWSTR, LPVOID);
  212721. typedef BOOL (CALLBACK *LPDSENUMCALLBACKA) (LPGUID, LPCSTR, LPCSTR, LPVOID);
  212722. DSOUND_FUNCTION (DirectSoundCreate, (const GUID*, IDirectSound**, LPUNKNOWN))
  212723. DSOUND_FUNCTION (DirectSoundCaptureCreate, (const GUID*, IDirectSoundCapture**, LPUNKNOWN))
  212724. DSOUND_FUNCTION (DirectSoundEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  212725. DSOUND_FUNCTION (DirectSoundCaptureEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  212726. static void initialiseDSoundFunctions()
  212727. {
  212728. if (dsDirectSoundCreate == 0)
  212729. {
  212730. HMODULE h = LoadLibraryA ("dsound.dll");
  212731. DSOUND_FUNCTION_LOAD (DirectSoundCreate)
  212732. DSOUND_FUNCTION_LOAD (DirectSoundCaptureCreate)
  212733. DSOUND_FUNCTION_LOAD (DirectSoundEnumerateW)
  212734. DSOUND_FUNCTION_LOAD (DirectSoundCaptureEnumerateW)
  212735. }
  212736. }
  212737. class DSoundInternalOutChannel
  212738. {
  212739. String name;
  212740. LPGUID guid;
  212741. int sampleRate, bufferSizeSamples;
  212742. float* leftBuffer;
  212743. float* rightBuffer;
  212744. IDirectSound* pDirectSound;
  212745. IDirectSoundBuffer* pOutputBuffer;
  212746. DWORD writeOffset;
  212747. int totalBytesPerBuffer;
  212748. int bytesPerBuffer;
  212749. unsigned int lastPlayCursor;
  212750. public:
  212751. int bitDepth;
  212752. bool doneFlag;
  212753. DSoundInternalOutChannel (const String& name_,
  212754. LPGUID guid_,
  212755. int rate,
  212756. int bufferSize,
  212757. float* left,
  212758. float* right)
  212759. : name (name_),
  212760. guid (guid_),
  212761. sampleRate (rate),
  212762. bufferSizeSamples (bufferSize),
  212763. leftBuffer (left),
  212764. rightBuffer (right),
  212765. pDirectSound (0),
  212766. pOutputBuffer (0),
  212767. bitDepth (16)
  212768. {
  212769. }
  212770. ~DSoundInternalOutChannel()
  212771. {
  212772. close();
  212773. }
  212774. void close()
  212775. {
  212776. HRESULT hr;
  212777. if (pOutputBuffer != 0)
  212778. {
  212779. JUCE_TRY
  212780. {
  212781. log ("closing dsound out: " + name);
  212782. hr = pOutputBuffer->Stop();
  212783. logError (hr);
  212784. }
  212785. CATCH
  212786. JUCE_TRY
  212787. {
  212788. hr = pOutputBuffer->Release();
  212789. logError (hr);
  212790. }
  212791. CATCH
  212792. pOutputBuffer = 0;
  212793. }
  212794. if (pDirectSound != 0)
  212795. {
  212796. JUCE_TRY
  212797. {
  212798. hr = pDirectSound->Release();
  212799. logError (hr);
  212800. }
  212801. CATCH
  212802. pDirectSound = 0;
  212803. }
  212804. }
  212805. const String open()
  212806. {
  212807. log ("opening dsound out device: " + name + " rate=" + String (sampleRate)
  212808. + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  212809. pDirectSound = 0;
  212810. pOutputBuffer = 0;
  212811. writeOffset = 0;
  212812. String error;
  212813. HRESULT hr = E_NOINTERFACE;
  212814. if (dsDirectSoundCreate != 0)
  212815. hr = dsDirectSoundCreate (guid, &pDirectSound, 0);
  212816. if (hr == S_OK)
  212817. {
  212818. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  212819. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  212820. const int numChannels = 2;
  212821. hr = pDirectSound->SetCooperativeLevel (GetDesktopWindow(), 2 /* DSSCL_PRIORITY */);
  212822. logError (hr);
  212823. if (hr == S_OK)
  212824. {
  212825. IDirectSoundBuffer* pPrimaryBuffer;
  212826. DSBUFFERDESC primaryDesc;
  212827. zerostruct (primaryDesc);
  212828. primaryDesc.dwSize = sizeof (DSBUFFERDESC);
  212829. primaryDesc.dwFlags = 1 /* DSBCAPS_PRIMARYBUFFER */;
  212830. primaryDesc.dwBufferBytes = 0;
  212831. primaryDesc.lpwfxFormat = 0;
  212832. log ("opening dsound out step 2");
  212833. hr = pDirectSound->CreateSoundBuffer (&primaryDesc, &pPrimaryBuffer, 0);
  212834. logError (hr);
  212835. if (hr == S_OK)
  212836. {
  212837. WAVEFORMATEX wfFormat;
  212838. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  212839. wfFormat.nChannels = (unsigned short) numChannels;
  212840. wfFormat.nSamplesPerSec = sampleRate;
  212841. wfFormat.wBitsPerSample = (unsigned short) bitDepth;
  212842. wfFormat.nBlockAlign = (unsigned short) (wfFormat.nChannels * wfFormat.wBitsPerSample / 8);
  212843. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  212844. wfFormat.cbSize = 0;
  212845. hr = pPrimaryBuffer->SetFormat (&wfFormat);
  212846. logError (hr);
  212847. if (hr == S_OK)
  212848. {
  212849. DSBUFFERDESC secondaryDesc;
  212850. zerostruct (secondaryDesc);
  212851. secondaryDesc.dwSize = sizeof (DSBUFFERDESC);
  212852. secondaryDesc.dwFlags = 0x8000 /* DSBCAPS_GLOBALFOCUS */
  212853. | 0x10000 /* DSBCAPS_GETCURRENTPOSITION2 */;
  212854. secondaryDesc.dwBufferBytes = totalBytesPerBuffer;
  212855. secondaryDesc.lpwfxFormat = &wfFormat;
  212856. hr = pDirectSound->CreateSoundBuffer (&secondaryDesc, &pOutputBuffer, 0);
  212857. logError (hr);
  212858. if (hr == S_OK)
  212859. {
  212860. log ("opening dsound out step 3");
  212861. DWORD dwDataLen;
  212862. unsigned char* pDSBuffData;
  212863. hr = pOutputBuffer->Lock (0, totalBytesPerBuffer,
  212864. (LPVOID*) &pDSBuffData, &dwDataLen, 0, 0, 0);
  212865. logError (hr);
  212866. if (hr == S_OK)
  212867. {
  212868. zeromem (pDSBuffData, dwDataLen);
  212869. hr = pOutputBuffer->Unlock (pDSBuffData, dwDataLen, 0, 0);
  212870. if (hr == S_OK)
  212871. {
  212872. hr = pOutputBuffer->SetCurrentPosition (0);
  212873. if (hr == S_OK)
  212874. {
  212875. hr = pOutputBuffer->Play (0, 0, 1 /* DSBPLAY_LOOPING */);
  212876. if (hr == S_OK)
  212877. return String::empty;
  212878. }
  212879. }
  212880. }
  212881. }
  212882. }
  212883. }
  212884. }
  212885. }
  212886. error = getDSErrorMessage (hr);
  212887. close();
  212888. return error;
  212889. }
  212890. void synchronisePosition()
  212891. {
  212892. if (pOutputBuffer != 0)
  212893. {
  212894. DWORD playCursor;
  212895. pOutputBuffer->GetCurrentPosition (&playCursor, &writeOffset);
  212896. }
  212897. }
  212898. bool service()
  212899. {
  212900. if (pOutputBuffer == 0)
  212901. return true;
  212902. DWORD playCursor, writeCursor;
  212903. for (;;)
  212904. {
  212905. HRESULT hr = pOutputBuffer->GetCurrentPosition (&playCursor, &writeCursor);
  212906. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  212907. {
  212908. pOutputBuffer->Restore();
  212909. continue;
  212910. }
  212911. if (hr == S_OK)
  212912. break;
  212913. logError (hr);
  212914. jassertfalse;
  212915. return true;
  212916. }
  212917. int playWriteGap = writeCursor - playCursor;
  212918. if (playWriteGap < 0)
  212919. playWriteGap += totalBytesPerBuffer;
  212920. int bytesEmpty = playCursor - writeOffset;
  212921. if (bytesEmpty < 0)
  212922. bytesEmpty += totalBytesPerBuffer;
  212923. if (bytesEmpty > (totalBytesPerBuffer - playWriteGap))
  212924. {
  212925. writeOffset = writeCursor;
  212926. bytesEmpty = totalBytesPerBuffer - playWriteGap;
  212927. }
  212928. if (bytesEmpty >= bytesPerBuffer)
  212929. {
  212930. LPBYTE lpbuf1 = 0;
  212931. LPBYTE lpbuf2 = 0;
  212932. DWORD dwSize1 = 0;
  212933. DWORD dwSize2 = 0;
  212934. HRESULT hr = pOutputBuffer->Lock (writeOffset,
  212935. bytesPerBuffer,
  212936. (void**) &lpbuf1, &dwSize1,
  212937. (void**) &lpbuf2, &dwSize2, 0);
  212938. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  212939. {
  212940. pOutputBuffer->Restore();
  212941. hr = pOutputBuffer->Lock (writeOffset,
  212942. bytesPerBuffer,
  212943. (void**) &lpbuf1, &dwSize1,
  212944. (void**) &lpbuf2, &dwSize2, 0);
  212945. }
  212946. if (hr == S_OK)
  212947. {
  212948. if (bitDepth == 16)
  212949. {
  212950. const float gainL = 32767.0f;
  212951. const float gainR = 32767.0f;
  212952. int* dest = (int*)lpbuf1;
  212953. const float* left = leftBuffer;
  212954. const float* right = rightBuffer;
  212955. int samples1 = dwSize1 >> 2;
  212956. int samples2 = dwSize2 >> 2;
  212957. if (left == 0)
  212958. {
  212959. while (--samples1 >= 0)
  212960. {
  212961. int r = roundToInt (gainR * *right++);
  212962. if (r < -32768)
  212963. r = -32768;
  212964. else if (r > 32767)
  212965. r = 32767;
  212966. *dest++ = (r << 16);
  212967. }
  212968. dest = (int*)lpbuf2;
  212969. while (--samples2 >= 0)
  212970. {
  212971. int r = roundToInt (gainR * *right++);
  212972. if (r < -32768)
  212973. r = -32768;
  212974. else if (r > 32767)
  212975. r = 32767;
  212976. *dest++ = (r << 16);
  212977. }
  212978. }
  212979. else if (right == 0)
  212980. {
  212981. while (--samples1 >= 0)
  212982. {
  212983. int l = roundToInt (gainL * *left++);
  212984. if (l < -32768)
  212985. l = -32768;
  212986. else if (l > 32767)
  212987. l = 32767;
  212988. l &= 0xffff;
  212989. *dest++ = l;
  212990. }
  212991. dest = (int*)lpbuf2;
  212992. while (--samples2 >= 0)
  212993. {
  212994. int l = roundToInt (gainL * *left++);
  212995. if (l < -32768)
  212996. l = -32768;
  212997. else if (l > 32767)
  212998. l = 32767;
  212999. l &= 0xffff;
  213000. *dest++ = l;
  213001. }
  213002. }
  213003. else
  213004. {
  213005. while (--samples1 >= 0)
  213006. {
  213007. int l = roundToInt (gainL * *left++);
  213008. if (l < -32768)
  213009. l = -32768;
  213010. else if (l > 32767)
  213011. l = 32767;
  213012. l &= 0xffff;
  213013. int r = roundToInt (gainR * *right++);
  213014. if (r < -32768)
  213015. r = -32768;
  213016. else if (r > 32767)
  213017. r = 32767;
  213018. *dest++ = (r << 16) | l;
  213019. }
  213020. dest = (int*)lpbuf2;
  213021. while (--samples2 >= 0)
  213022. {
  213023. int l = roundToInt (gainL * *left++);
  213024. if (l < -32768)
  213025. l = -32768;
  213026. else if (l > 32767)
  213027. l = 32767;
  213028. l &= 0xffff;
  213029. int r = roundToInt (gainR * *right++);
  213030. if (r < -32768)
  213031. r = -32768;
  213032. else if (r > 32767)
  213033. r = 32767;
  213034. *dest++ = (r << 16) | l;
  213035. }
  213036. }
  213037. }
  213038. else
  213039. {
  213040. jassertfalse;
  213041. }
  213042. writeOffset = (writeOffset + dwSize1 + dwSize2) % totalBytesPerBuffer;
  213043. pOutputBuffer->Unlock (lpbuf1, dwSize1, lpbuf2, dwSize2);
  213044. }
  213045. else
  213046. {
  213047. jassertfalse;
  213048. logError (hr);
  213049. }
  213050. bytesEmpty -= bytesPerBuffer;
  213051. return true;
  213052. }
  213053. else
  213054. {
  213055. return false;
  213056. }
  213057. }
  213058. };
  213059. struct DSoundInternalInChannel
  213060. {
  213061. String name;
  213062. LPGUID guid;
  213063. int sampleRate, bufferSizeSamples;
  213064. float* leftBuffer;
  213065. float* rightBuffer;
  213066. IDirectSound* pDirectSound;
  213067. IDirectSoundCapture* pDirectSoundCapture;
  213068. IDirectSoundCaptureBuffer* pInputBuffer;
  213069. public:
  213070. unsigned int readOffset;
  213071. int bytesPerBuffer, totalBytesPerBuffer;
  213072. int bitDepth;
  213073. bool doneFlag;
  213074. DSoundInternalInChannel (const String& name_,
  213075. LPGUID guid_,
  213076. int rate,
  213077. int bufferSize,
  213078. float* left,
  213079. float* right)
  213080. : name (name_),
  213081. guid (guid_),
  213082. sampleRate (rate),
  213083. bufferSizeSamples (bufferSize),
  213084. leftBuffer (left),
  213085. rightBuffer (right),
  213086. pDirectSound (0),
  213087. pDirectSoundCapture (0),
  213088. pInputBuffer (0),
  213089. bitDepth (16)
  213090. {
  213091. }
  213092. ~DSoundInternalInChannel()
  213093. {
  213094. close();
  213095. }
  213096. void close()
  213097. {
  213098. HRESULT hr;
  213099. if (pInputBuffer != 0)
  213100. {
  213101. JUCE_TRY
  213102. {
  213103. log ("closing dsound in: " + name);
  213104. hr = pInputBuffer->Stop();
  213105. logError (hr);
  213106. }
  213107. CATCH
  213108. JUCE_TRY
  213109. {
  213110. hr = pInputBuffer->Release();
  213111. logError (hr);
  213112. }
  213113. CATCH
  213114. pInputBuffer = 0;
  213115. }
  213116. if (pDirectSoundCapture != 0)
  213117. {
  213118. JUCE_TRY
  213119. {
  213120. hr = pDirectSoundCapture->Release();
  213121. logError (hr);
  213122. }
  213123. CATCH
  213124. pDirectSoundCapture = 0;
  213125. }
  213126. if (pDirectSound != 0)
  213127. {
  213128. JUCE_TRY
  213129. {
  213130. hr = pDirectSound->Release();
  213131. logError (hr);
  213132. }
  213133. CATCH
  213134. pDirectSound = 0;
  213135. }
  213136. }
  213137. const String open()
  213138. {
  213139. log ("opening dsound in device: " + name
  213140. + " rate=" + String (sampleRate) + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  213141. pDirectSound = 0;
  213142. pDirectSoundCapture = 0;
  213143. pInputBuffer = 0;
  213144. readOffset = 0;
  213145. totalBytesPerBuffer = 0;
  213146. String error;
  213147. HRESULT hr = E_NOINTERFACE;
  213148. if (dsDirectSoundCaptureCreate != 0)
  213149. hr = dsDirectSoundCaptureCreate (guid, &pDirectSoundCapture, 0);
  213150. logError (hr);
  213151. if (hr == S_OK)
  213152. {
  213153. const int numChannels = 2;
  213154. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  213155. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  213156. WAVEFORMATEX wfFormat;
  213157. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  213158. wfFormat.nChannels = (unsigned short)numChannels;
  213159. wfFormat.nSamplesPerSec = sampleRate;
  213160. wfFormat.wBitsPerSample = (unsigned short)bitDepth;
  213161. wfFormat.nBlockAlign = (unsigned short)(wfFormat.nChannels * (wfFormat.wBitsPerSample / 8));
  213162. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  213163. wfFormat.cbSize = 0;
  213164. DSCBUFFERDESC captureDesc;
  213165. zerostruct (captureDesc);
  213166. captureDesc.dwSize = sizeof (DSCBUFFERDESC);
  213167. captureDesc.dwFlags = 0;
  213168. captureDesc.dwBufferBytes = totalBytesPerBuffer;
  213169. captureDesc.lpwfxFormat = &wfFormat;
  213170. log ("opening dsound in step 2");
  213171. hr = pDirectSoundCapture->CreateCaptureBuffer (&captureDesc, &pInputBuffer, 0);
  213172. logError (hr);
  213173. if (hr == S_OK)
  213174. {
  213175. hr = pInputBuffer->Start (1 /* DSCBSTART_LOOPING */);
  213176. logError (hr);
  213177. if (hr == S_OK)
  213178. return String::empty;
  213179. }
  213180. }
  213181. error = getDSErrorMessage (hr);
  213182. close();
  213183. return error;
  213184. }
  213185. void synchronisePosition()
  213186. {
  213187. if (pInputBuffer != 0)
  213188. {
  213189. DWORD capturePos;
  213190. pInputBuffer->GetCurrentPosition (&capturePos, (DWORD*)&readOffset);
  213191. }
  213192. }
  213193. bool service()
  213194. {
  213195. if (pInputBuffer == 0)
  213196. return true;
  213197. DWORD capturePos, readPos;
  213198. HRESULT hr = pInputBuffer->GetCurrentPosition (&capturePos, &readPos);
  213199. logError (hr);
  213200. if (hr != S_OK)
  213201. return true;
  213202. int bytesFilled = readPos - readOffset;
  213203. if (bytesFilled < 0)
  213204. bytesFilled += totalBytesPerBuffer;
  213205. if (bytesFilled >= bytesPerBuffer)
  213206. {
  213207. LPBYTE lpbuf1 = 0;
  213208. LPBYTE lpbuf2 = 0;
  213209. DWORD dwsize1 = 0;
  213210. DWORD dwsize2 = 0;
  213211. HRESULT hr = pInputBuffer->Lock (readOffset,
  213212. bytesPerBuffer,
  213213. (void**) &lpbuf1, &dwsize1,
  213214. (void**) &lpbuf2, &dwsize2, 0);
  213215. if (hr == S_OK)
  213216. {
  213217. if (bitDepth == 16)
  213218. {
  213219. const float g = 1.0f / 32768.0f;
  213220. float* destL = leftBuffer;
  213221. float* destR = rightBuffer;
  213222. int samples1 = dwsize1 >> 2;
  213223. int samples2 = dwsize2 >> 2;
  213224. const short* src = (const short*)lpbuf1;
  213225. if (destL == 0)
  213226. {
  213227. while (--samples1 >= 0)
  213228. {
  213229. ++src;
  213230. *destR++ = *src++ * g;
  213231. }
  213232. src = (const short*)lpbuf2;
  213233. while (--samples2 >= 0)
  213234. {
  213235. ++src;
  213236. *destR++ = *src++ * g;
  213237. }
  213238. }
  213239. else if (destR == 0)
  213240. {
  213241. while (--samples1 >= 0)
  213242. {
  213243. *destL++ = *src++ * g;
  213244. ++src;
  213245. }
  213246. src = (const short*)lpbuf2;
  213247. while (--samples2 >= 0)
  213248. {
  213249. *destL++ = *src++ * g;
  213250. ++src;
  213251. }
  213252. }
  213253. else
  213254. {
  213255. while (--samples1 >= 0)
  213256. {
  213257. *destL++ = *src++ * g;
  213258. *destR++ = *src++ * g;
  213259. }
  213260. src = (const short*)lpbuf2;
  213261. while (--samples2 >= 0)
  213262. {
  213263. *destL++ = *src++ * g;
  213264. *destR++ = *src++ * g;
  213265. }
  213266. }
  213267. }
  213268. else
  213269. {
  213270. jassertfalse;
  213271. }
  213272. readOffset = (readOffset + dwsize1 + dwsize2) % totalBytesPerBuffer;
  213273. pInputBuffer->Unlock (lpbuf1, dwsize1, lpbuf2, dwsize2);
  213274. }
  213275. else
  213276. {
  213277. logError (hr);
  213278. jassertfalse;
  213279. }
  213280. bytesFilled -= bytesPerBuffer;
  213281. return true;
  213282. }
  213283. else
  213284. {
  213285. return false;
  213286. }
  213287. }
  213288. };
  213289. class DSoundAudioIODevice : public AudioIODevice,
  213290. public Thread
  213291. {
  213292. public:
  213293. DSoundAudioIODevice (const String& deviceName,
  213294. const int outputDeviceIndex_,
  213295. const int inputDeviceIndex_)
  213296. : AudioIODevice (deviceName, "DirectSound"),
  213297. Thread ("Juce DSound"),
  213298. isOpen_ (false),
  213299. isStarted (false),
  213300. outputDeviceIndex (outputDeviceIndex_),
  213301. inputDeviceIndex (inputDeviceIndex_),
  213302. totalSamplesOut (0),
  213303. sampleRate (0.0),
  213304. inputBuffers (1, 1),
  213305. outputBuffers (1, 1),
  213306. callback (0),
  213307. bufferSizeSamples (0)
  213308. {
  213309. if (outputDeviceIndex_ >= 0)
  213310. {
  213311. outChannels.add (TRANS("Left"));
  213312. outChannels.add (TRANS("Right"));
  213313. }
  213314. if (inputDeviceIndex_ >= 0)
  213315. {
  213316. inChannels.add (TRANS("Left"));
  213317. inChannels.add (TRANS("Right"));
  213318. }
  213319. }
  213320. ~DSoundAudioIODevice()
  213321. {
  213322. close();
  213323. }
  213324. const StringArray getOutputChannelNames()
  213325. {
  213326. return outChannels;
  213327. }
  213328. const StringArray getInputChannelNames()
  213329. {
  213330. return inChannels;
  213331. }
  213332. int getNumSampleRates()
  213333. {
  213334. return 4;
  213335. }
  213336. double getSampleRate (int index)
  213337. {
  213338. const double samps[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  213339. return samps [jlimit (0, 3, index)];
  213340. }
  213341. int getNumBufferSizesAvailable()
  213342. {
  213343. return 50;
  213344. }
  213345. int getBufferSizeSamples (int index)
  213346. {
  213347. int n = 64;
  213348. for (int i = 0; i < index; ++i)
  213349. n += (n < 512) ? 32
  213350. : ((n < 1024) ? 64
  213351. : ((n < 2048) ? 128 : 256));
  213352. return n;
  213353. }
  213354. int getDefaultBufferSize()
  213355. {
  213356. return 2560;
  213357. }
  213358. const String open (const BigInteger& inputChannels,
  213359. const BigInteger& outputChannels,
  213360. double sampleRate,
  213361. int bufferSizeSamples)
  213362. {
  213363. lastError = openDevice (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  213364. isOpen_ = lastError.isEmpty();
  213365. return lastError;
  213366. }
  213367. void close()
  213368. {
  213369. stop();
  213370. if (isOpen_)
  213371. {
  213372. closeDevice();
  213373. isOpen_ = false;
  213374. }
  213375. }
  213376. bool isOpen()
  213377. {
  213378. return isOpen_ && isThreadRunning();
  213379. }
  213380. int getCurrentBufferSizeSamples()
  213381. {
  213382. return bufferSizeSamples;
  213383. }
  213384. double getCurrentSampleRate()
  213385. {
  213386. return sampleRate;
  213387. }
  213388. int getCurrentBitDepth()
  213389. {
  213390. int i, bits = 256;
  213391. for (i = inChans.size(); --i >= 0;)
  213392. bits = jmin (bits, inChans[i]->bitDepth);
  213393. for (i = outChans.size(); --i >= 0;)
  213394. bits = jmin (bits, outChans[i]->bitDepth);
  213395. if (bits > 32)
  213396. bits = 16;
  213397. return bits;
  213398. }
  213399. const BigInteger getActiveOutputChannels() const
  213400. {
  213401. return enabledOutputs;
  213402. }
  213403. const BigInteger getActiveInputChannels() const
  213404. {
  213405. return enabledInputs;
  213406. }
  213407. int getOutputLatencyInSamples()
  213408. {
  213409. return (int) (getCurrentBufferSizeSamples() * 1.5);
  213410. }
  213411. int getInputLatencyInSamples()
  213412. {
  213413. return getOutputLatencyInSamples();
  213414. }
  213415. void start (AudioIODeviceCallback* call)
  213416. {
  213417. if (isOpen_ && call != 0 && ! isStarted)
  213418. {
  213419. if (! isThreadRunning())
  213420. {
  213421. // something gone wrong and the thread's stopped..
  213422. isOpen_ = false;
  213423. return;
  213424. }
  213425. call->audioDeviceAboutToStart (this);
  213426. const ScopedLock sl (startStopLock);
  213427. callback = call;
  213428. isStarted = true;
  213429. }
  213430. }
  213431. void stop()
  213432. {
  213433. if (isStarted)
  213434. {
  213435. AudioIODeviceCallback* const callbackLocal = callback;
  213436. {
  213437. const ScopedLock sl (startStopLock);
  213438. isStarted = false;
  213439. }
  213440. if (callbackLocal != 0)
  213441. callbackLocal->audioDeviceStopped();
  213442. }
  213443. }
  213444. bool isPlaying()
  213445. {
  213446. return isStarted && isOpen_ && isThreadRunning();
  213447. }
  213448. const String getLastError()
  213449. {
  213450. return lastError;
  213451. }
  213452. juce_UseDebuggingNewOperator
  213453. StringArray inChannels, outChannels;
  213454. int outputDeviceIndex, inputDeviceIndex;
  213455. private:
  213456. bool isOpen_;
  213457. bool isStarted;
  213458. String lastError;
  213459. OwnedArray <DSoundInternalInChannel> inChans;
  213460. OwnedArray <DSoundInternalOutChannel> outChans;
  213461. WaitableEvent startEvent;
  213462. int bufferSizeSamples;
  213463. int volatile totalSamplesOut;
  213464. int64 volatile lastBlockTime;
  213465. double sampleRate;
  213466. BigInteger enabledInputs, enabledOutputs;
  213467. AudioSampleBuffer inputBuffers, outputBuffers;
  213468. AudioIODeviceCallback* callback;
  213469. CriticalSection startStopLock;
  213470. DSoundAudioIODevice (const DSoundAudioIODevice&);
  213471. DSoundAudioIODevice& operator= (const DSoundAudioIODevice&);
  213472. const String openDevice (const BigInteger& inputChannels,
  213473. const BigInteger& outputChannels,
  213474. double sampleRate_,
  213475. int bufferSizeSamples_);
  213476. void closeDevice()
  213477. {
  213478. isStarted = false;
  213479. stopThread (5000);
  213480. inChans.clear();
  213481. outChans.clear();
  213482. inputBuffers.setSize (1, 1);
  213483. outputBuffers.setSize (1, 1);
  213484. }
  213485. void resync()
  213486. {
  213487. if (! threadShouldExit())
  213488. {
  213489. sleep (5);
  213490. int i;
  213491. for (i = 0; i < outChans.size(); ++i)
  213492. outChans.getUnchecked(i)->synchronisePosition();
  213493. for (i = 0; i < inChans.size(); ++i)
  213494. inChans.getUnchecked(i)->synchronisePosition();
  213495. }
  213496. }
  213497. public:
  213498. void run()
  213499. {
  213500. while (! threadShouldExit())
  213501. {
  213502. if (wait (100))
  213503. break;
  213504. }
  213505. const int latencyMs = (int) (bufferSizeSamples * 1000.0 / sampleRate);
  213506. const int maxTimeMS = jmax (5, 3 * latencyMs);
  213507. while (! threadShouldExit())
  213508. {
  213509. int numToDo = 0;
  213510. uint32 startTime = Time::getMillisecondCounter();
  213511. int i;
  213512. for (i = inChans.size(); --i >= 0;)
  213513. {
  213514. inChans.getUnchecked(i)->doneFlag = false;
  213515. ++numToDo;
  213516. }
  213517. for (i = outChans.size(); --i >= 0;)
  213518. {
  213519. outChans.getUnchecked(i)->doneFlag = false;
  213520. ++numToDo;
  213521. }
  213522. if (numToDo > 0)
  213523. {
  213524. const int maxCount = 3;
  213525. int count = maxCount;
  213526. for (;;)
  213527. {
  213528. for (i = inChans.size(); --i >= 0;)
  213529. {
  213530. DSoundInternalInChannel* const in = inChans.getUnchecked(i);
  213531. if ((! in->doneFlag) && in->service())
  213532. {
  213533. in->doneFlag = true;
  213534. --numToDo;
  213535. }
  213536. }
  213537. for (i = outChans.size(); --i >= 0;)
  213538. {
  213539. DSoundInternalOutChannel* const out = outChans.getUnchecked(i);
  213540. if ((! out->doneFlag) && out->service())
  213541. {
  213542. out->doneFlag = true;
  213543. --numToDo;
  213544. }
  213545. }
  213546. if (numToDo <= 0)
  213547. break;
  213548. if (Time::getMillisecondCounter() > startTime + maxTimeMS)
  213549. {
  213550. resync();
  213551. break;
  213552. }
  213553. if (--count <= 0)
  213554. {
  213555. Sleep (1);
  213556. count = maxCount;
  213557. }
  213558. if (threadShouldExit())
  213559. return;
  213560. }
  213561. }
  213562. else
  213563. {
  213564. sleep (1);
  213565. }
  213566. const ScopedLock sl (startStopLock);
  213567. if (isStarted)
  213568. {
  213569. JUCE_TRY
  213570. {
  213571. callback->audioDeviceIOCallback (const_cast <const float**> (inputBuffers.getArrayOfChannels()),
  213572. inputBuffers.getNumChannels(),
  213573. outputBuffers.getArrayOfChannels(),
  213574. outputBuffers.getNumChannels(),
  213575. bufferSizeSamples);
  213576. }
  213577. JUCE_CATCH_EXCEPTION
  213578. totalSamplesOut += bufferSizeSamples;
  213579. }
  213580. else
  213581. {
  213582. outputBuffers.clear();
  213583. totalSamplesOut = 0;
  213584. sleep (1);
  213585. }
  213586. }
  213587. }
  213588. };
  213589. class DSoundAudioIODeviceType : public AudioIODeviceType
  213590. {
  213591. public:
  213592. DSoundAudioIODeviceType()
  213593. : AudioIODeviceType ("DirectSound"),
  213594. hasScanned (false)
  213595. {
  213596. initialiseDSoundFunctions();
  213597. }
  213598. ~DSoundAudioIODeviceType()
  213599. {
  213600. }
  213601. void scanForDevices()
  213602. {
  213603. hasScanned = true;
  213604. outputDeviceNames.clear();
  213605. outputGuids.clear();
  213606. inputDeviceNames.clear();
  213607. inputGuids.clear();
  213608. if (dsDirectSoundEnumerateW != 0)
  213609. {
  213610. dsDirectSoundEnumerateW (outputEnumProcW, this);
  213611. dsDirectSoundCaptureEnumerateW (inputEnumProcW, this);
  213612. }
  213613. }
  213614. const StringArray getDeviceNames (bool wantInputNames) const
  213615. {
  213616. jassert (hasScanned); // need to call scanForDevices() before doing this
  213617. return wantInputNames ? inputDeviceNames
  213618. : outputDeviceNames;
  213619. }
  213620. int getDefaultDeviceIndex (bool /*forInput*/) const
  213621. {
  213622. jassert (hasScanned); // need to call scanForDevices() before doing this
  213623. return 0;
  213624. }
  213625. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  213626. {
  213627. jassert (hasScanned); // need to call scanForDevices() before doing this
  213628. DSoundAudioIODevice* const d = dynamic_cast <DSoundAudioIODevice*> (device);
  213629. if (d == 0)
  213630. return -1;
  213631. return asInput ? d->inputDeviceIndex
  213632. : d->outputDeviceIndex;
  213633. }
  213634. bool hasSeparateInputsAndOutputs() const { return true; }
  213635. AudioIODevice* createDevice (const String& outputDeviceName,
  213636. const String& inputDeviceName)
  213637. {
  213638. jassert (hasScanned); // need to call scanForDevices() before doing this
  213639. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  213640. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  213641. if (outputIndex >= 0 || inputIndex >= 0)
  213642. return new DSoundAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  213643. : inputDeviceName,
  213644. outputIndex, inputIndex);
  213645. return 0;
  213646. }
  213647. juce_UseDebuggingNewOperator
  213648. StringArray outputDeviceNames;
  213649. OwnedArray <GUID> outputGuids;
  213650. StringArray inputDeviceNames;
  213651. OwnedArray <GUID> inputGuids;
  213652. private:
  213653. bool hasScanned;
  213654. BOOL outputEnumProc (LPGUID lpGUID, String desc)
  213655. {
  213656. desc = desc.trim();
  213657. if (desc.isNotEmpty())
  213658. {
  213659. const String origDesc (desc);
  213660. int n = 2;
  213661. while (outputDeviceNames.contains (desc))
  213662. desc = origDesc + " (" + String (n++) + ")";
  213663. outputDeviceNames.add (desc);
  213664. if (lpGUID != 0)
  213665. outputGuids.add (new GUID (*lpGUID));
  213666. else
  213667. outputGuids.add (0);
  213668. }
  213669. return TRUE;
  213670. }
  213671. static BOOL CALLBACK outputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  213672. {
  213673. return ((DSoundAudioIODeviceType*) object)
  213674. ->outputEnumProc (lpGUID, String (description));
  213675. }
  213676. static BOOL CALLBACK outputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  213677. {
  213678. return ((DSoundAudioIODeviceType*) object)
  213679. ->outputEnumProc (lpGUID, String (description));
  213680. }
  213681. BOOL CALLBACK inputEnumProc (LPGUID lpGUID, String desc)
  213682. {
  213683. desc = desc.trim();
  213684. if (desc.isNotEmpty())
  213685. {
  213686. const String origDesc (desc);
  213687. int n = 2;
  213688. while (inputDeviceNames.contains (desc))
  213689. desc = origDesc + " (" + String (n++) + ")";
  213690. inputDeviceNames.add (desc);
  213691. if (lpGUID != 0)
  213692. inputGuids.add (new GUID (*lpGUID));
  213693. else
  213694. inputGuids.add (0);
  213695. }
  213696. return TRUE;
  213697. }
  213698. static BOOL CALLBACK inputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  213699. {
  213700. return ((DSoundAudioIODeviceType*) object)
  213701. ->inputEnumProc (lpGUID, String (description));
  213702. }
  213703. static BOOL CALLBACK inputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  213704. {
  213705. return ((DSoundAudioIODeviceType*) object)
  213706. ->inputEnumProc (lpGUID, String (description));
  213707. }
  213708. DSoundAudioIODeviceType (const DSoundAudioIODeviceType&);
  213709. DSoundAudioIODeviceType& operator= (const DSoundAudioIODeviceType&);
  213710. };
  213711. const String DSoundAudioIODevice::openDevice (const BigInteger& inputChannels,
  213712. const BigInteger& outputChannels,
  213713. double sampleRate_,
  213714. int bufferSizeSamples_)
  213715. {
  213716. closeDevice();
  213717. totalSamplesOut = 0;
  213718. sampleRate = sampleRate_;
  213719. if (bufferSizeSamples_ <= 0)
  213720. bufferSizeSamples_ = 960; // use as a default size if none is set.
  213721. bufferSizeSamples = bufferSizeSamples_ & ~7;
  213722. DSoundAudioIODeviceType dlh;
  213723. dlh.scanForDevices();
  213724. enabledInputs = inputChannels;
  213725. enabledInputs.setRange (inChannels.size(),
  213726. enabledInputs.getHighestBit() + 1 - inChannels.size(),
  213727. false);
  213728. inputBuffers.setSize (jmax (1, enabledInputs.countNumberOfSetBits()), bufferSizeSamples);
  213729. int i, numIns = 0;
  213730. for (i = 0; i <= enabledInputs.getHighestBit(); i += 2)
  213731. {
  213732. float* left = 0;
  213733. if (enabledInputs[i])
  213734. left = inputBuffers.getSampleData (numIns++);
  213735. float* right = 0;
  213736. if (enabledInputs[i + 1])
  213737. right = inputBuffers.getSampleData (numIns++);
  213738. if (left != 0 || right != 0)
  213739. inChans.add (new DSoundInternalInChannel (dlh.inputDeviceNames [inputDeviceIndex],
  213740. dlh.inputGuids [inputDeviceIndex],
  213741. (int) sampleRate, bufferSizeSamples,
  213742. left, right));
  213743. }
  213744. enabledOutputs = outputChannels;
  213745. enabledOutputs.setRange (outChannels.size(),
  213746. enabledOutputs.getHighestBit() + 1 - outChannels.size(),
  213747. false);
  213748. outputBuffers.setSize (jmax (1, enabledOutputs.countNumberOfSetBits()), bufferSizeSamples);
  213749. int numOuts = 0;
  213750. for (i = 0; i <= enabledOutputs.getHighestBit(); i += 2)
  213751. {
  213752. float* left = 0;
  213753. if (enabledOutputs[i])
  213754. left = outputBuffers.getSampleData (numOuts++);
  213755. float* right = 0;
  213756. if (enabledOutputs[i + 1])
  213757. right = outputBuffers.getSampleData (numOuts++);
  213758. if (left != 0 || right != 0)
  213759. outChans.add (new DSoundInternalOutChannel (dlh.outputDeviceNames[outputDeviceIndex],
  213760. dlh.outputGuids [outputDeviceIndex],
  213761. (int) sampleRate, bufferSizeSamples,
  213762. left, right));
  213763. }
  213764. String error;
  213765. // boost our priority while opening the devices to try to get better sync between them
  213766. const int oldThreadPri = GetThreadPriority (GetCurrentThread());
  213767. const int oldProcPri = GetPriorityClass (GetCurrentProcess());
  213768. SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  213769. SetPriorityClass (GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
  213770. for (i = 0; i < outChans.size(); ++i)
  213771. {
  213772. error = outChans[i]->open();
  213773. if (error.isNotEmpty())
  213774. {
  213775. error = "Error opening " + dlh.outputDeviceNames[i] + ": \"" + error + "\"";
  213776. break;
  213777. }
  213778. }
  213779. if (error.isEmpty())
  213780. {
  213781. for (i = 0; i < inChans.size(); ++i)
  213782. {
  213783. error = inChans[i]->open();
  213784. if (error.isNotEmpty())
  213785. {
  213786. error = "Error opening " + dlh.inputDeviceNames[i] + ": \"" + error + "\"";
  213787. break;
  213788. }
  213789. }
  213790. }
  213791. if (error.isEmpty())
  213792. {
  213793. totalSamplesOut = 0;
  213794. for (i = 0; i < outChans.size(); ++i)
  213795. outChans.getUnchecked(i)->synchronisePosition();
  213796. for (i = 0; i < inChans.size(); ++i)
  213797. inChans.getUnchecked(i)->synchronisePosition();
  213798. startThread (9);
  213799. sleep (10);
  213800. notify();
  213801. }
  213802. else
  213803. {
  213804. log (error);
  213805. }
  213806. SetThreadPriority (GetCurrentThread(), oldThreadPri);
  213807. SetPriorityClass (GetCurrentProcess(), oldProcPri);
  213808. return error;
  213809. }
  213810. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound()
  213811. {
  213812. return new DSoundAudioIODeviceType();
  213813. }
  213814. #undef log
  213815. #endif
  213816. /*** End of inlined file: juce_win32_DirectSound.cpp ***/
  213817. /*** Start of inlined file: juce_win32_WASAPI.cpp ***/
  213818. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  213819. // compiled on its own).
  213820. #if JUCE_INCLUDED_FILE && JUCE_WASAPI
  213821. #if 1
  213822. const String getAudioErrorDesc (HRESULT hr)
  213823. {
  213824. const char* e = 0;
  213825. switch (hr)
  213826. {
  213827. case E_POINTER: e = "E_POINTER"; break;
  213828. case E_INVALIDARG: e = "E_INVALIDARG"; break;
  213829. case AUDCLNT_E_NOT_INITIALIZED: e = "AUDCLNT_E_NOT_INITIALIZED"; break;
  213830. case AUDCLNT_E_ALREADY_INITIALIZED: e = "AUDCLNT_E_ALREADY_INITIALIZED"; break;
  213831. case AUDCLNT_E_WRONG_ENDPOINT_TYPE: e = "AUDCLNT_E_WRONG_ENDPOINT_TYPE"; break;
  213832. case AUDCLNT_E_DEVICE_INVALIDATED: e = "AUDCLNT_E_DEVICE_INVALIDATED"; break;
  213833. case AUDCLNT_E_NOT_STOPPED: e = "AUDCLNT_E_NOT_STOPPED"; break;
  213834. case AUDCLNT_E_BUFFER_TOO_LARGE: e = "AUDCLNT_E_BUFFER_TOO_LARGE"; break;
  213835. case AUDCLNT_E_OUT_OF_ORDER: e = "AUDCLNT_E_OUT_OF_ORDER"; break;
  213836. case AUDCLNT_E_UNSUPPORTED_FORMAT: e = "AUDCLNT_E_UNSUPPORTED_FORMAT"; break;
  213837. case AUDCLNT_E_INVALID_SIZE: e = "AUDCLNT_E_INVALID_SIZE"; break;
  213838. case AUDCLNT_E_DEVICE_IN_USE: e = "AUDCLNT_E_DEVICE_IN_USE"; break;
  213839. case AUDCLNT_E_BUFFER_OPERATION_PENDING: e = "AUDCLNT_E_BUFFER_OPERATION_PENDING"; break;
  213840. case AUDCLNT_E_THREAD_NOT_REGISTERED: e = "AUDCLNT_E_THREAD_NOT_REGISTERED"; break;
  213841. case AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED: e = "AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED"; break;
  213842. case AUDCLNT_E_ENDPOINT_CREATE_FAILED: e = "AUDCLNT_E_ENDPOINT_CREATE_FAILED"; break;
  213843. case AUDCLNT_E_SERVICE_NOT_RUNNING: e = "AUDCLNT_E_SERVICE_NOT_RUNNING"; break;
  213844. case AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED: e = "AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED"; break;
  213845. case AUDCLNT_E_EXCLUSIVE_MODE_ONLY: e = "AUDCLNT_E_EXCLUSIVE_MODE_ONLY"; break;
  213846. case AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL: e = "AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL"; break;
  213847. case AUDCLNT_E_EVENTHANDLE_NOT_SET: e = "AUDCLNT_E_EVENTHANDLE_NOT_SET"; break;
  213848. case AUDCLNT_E_INCORRECT_BUFFER_SIZE: e = "AUDCLNT_E_INCORRECT_BUFFER_SIZE"; break;
  213849. case AUDCLNT_E_BUFFER_SIZE_ERROR: e = "AUDCLNT_E_BUFFER_SIZE_ERROR"; break;
  213850. case AUDCLNT_S_BUFFER_EMPTY: e = "AUDCLNT_S_BUFFER_EMPTY"; break;
  213851. case AUDCLNT_S_THREAD_ALREADY_REGISTERED: e = "AUDCLNT_S_THREAD_ALREADY_REGISTERED"; break;
  213852. default: return String::toHexString ((int) hr);
  213853. }
  213854. return e;
  213855. }
  213856. #define logFailure(hr) { if (FAILED (hr)) { DBG ("WASAPI FAIL! " + getAudioErrorDesc (hr)); jassertfalse; } }
  213857. #define OK(a) wasapi_checkResult(a)
  213858. static bool wasapi_checkResult (HRESULT hr)
  213859. {
  213860. logFailure (hr);
  213861. return SUCCEEDED (hr);
  213862. }
  213863. #else
  213864. #define logFailure(hr) {}
  213865. #define OK(a) SUCCEEDED(a)
  213866. #endif
  213867. static const String wasapi_getDeviceID (IMMDevice* const device)
  213868. {
  213869. String s;
  213870. WCHAR* deviceId = 0;
  213871. if (OK (device->GetId (&deviceId)))
  213872. {
  213873. s = String (deviceId);
  213874. CoTaskMemFree (deviceId);
  213875. }
  213876. return s;
  213877. }
  213878. static EDataFlow wasapi_getDataFlow (IMMDevice* const device)
  213879. {
  213880. EDataFlow flow = eRender;
  213881. ComSmartPtr <IMMEndpoint> endPoint;
  213882. if (OK (device->QueryInterface (__uuidof (IMMEndpoint), (void**) &endPoint)))
  213883. (void) OK (endPoint->GetDataFlow (&flow));
  213884. return flow;
  213885. }
  213886. static int wasapi_refTimeToSamples (const REFERENCE_TIME& t, const double sampleRate) throw()
  213887. {
  213888. return roundDoubleToInt (sampleRate * ((double) t) * 0.0000001);
  213889. }
  213890. static void wasapi_copyWavFormat (WAVEFORMATEXTENSIBLE& dest, const WAVEFORMATEX* const src) throw()
  213891. {
  213892. memcpy (&dest, src, src->wFormatTag == WAVE_FORMAT_EXTENSIBLE ? sizeof (WAVEFORMATEXTENSIBLE)
  213893. : sizeof (WAVEFORMATEX));
  213894. }
  213895. class WASAPIDeviceBase
  213896. {
  213897. public:
  213898. WASAPIDeviceBase (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  213899. : device (device_),
  213900. sampleRate (0),
  213901. numChannels (0),
  213902. actualNumChannels (0),
  213903. defaultSampleRate (0),
  213904. minBufferSize (0),
  213905. defaultBufferSize (0),
  213906. latencySamples (0),
  213907. useExclusiveMode (useExclusiveMode_)
  213908. {
  213909. clientEvent = CreateEvent (0, false, false, _T("JuceWASAPI"));
  213910. ComSmartPtr <IAudioClient> tempClient (createClient());
  213911. if (tempClient == 0)
  213912. return;
  213913. REFERENCE_TIME defaultPeriod, minPeriod;
  213914. if (! OK (tempClient->GetDevicePeriod (&defaultPeriod, &minPeriod)))
  213915. return;
  213916. WAVEFORMATEX* mixFormat = 0;
  213917. if (! OK (tempClient->GetMixFormat (&mixFormat)))
  213918. return;
  213919. WAVEFORMATEXTENSIBLE format;
  213920. wasapi_copyWavFormat (format, mixFormat);
  213921. CoTaskMemFree (mixFormat);
  213922. actualNumChannels = numChannels = format.Format.nChannels;
  213923. defaultSampleRate = format.Format.nSamplesPerSec;
  213924. minBufferSize = wasapi_refTimeToSamples (minPeriod, defaultSampleRate);
  213925. defaultBufferSize = wasapi_refTimeToSamples (defaultPeriod, defaultSampleRate);
  213926. rates.addUsingDefaultSort (defaultSampleRate);
  213927. static const double ratesToTest[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  213928. for (int i = 0; i < numElementsInArray (ratesToTest); ++i)
  213929. {
  213930. if (ratesToTest[i] == defaultSampleRate)
  213931. continue;
  213932. format.Format.nSamplesPerSec = roundDoubleToInt (ratesToTest[i]);
  213933. if (SUCCEEDED (tempClient->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  213934. (WAVEFORMATEX*) &format, 0)))
  213935. if (! rates.contains (ratesToTest[i]))
  213936. rates.addUsingDefaultSort (ratesToTest[i]);
  213937. }
  213938. }
  213939. ~WASAPIDeviceBase()
  213940. {
  213941. device = 0;
  213942. CloseHandle (clientEvent);
  213943. }
  213944. bool isOk() const throw() { return defaultBufferSize > 0 && defaultSampleRate > 0; }
  213945. bool openClient (const double newSampleRate, const BigInteger& newChannels)
  213946. {
  213947. sampleRate = newSampleRate;
  213948. channels = newChannels;
  213949. channels.setRange (actualNumChannels, channels.getHighestBit() + 1 - actualNumChannels, false);
  213950. numChannels = channels.getHighestBit() + 1;
  213951. if (numChannels == 0)
  213952. return true;
  213953. client = createClient();
  213954. if (client != 0
  213955. && (tryInitialisingWithFormat (true, 4) || tryInitialisingWithFormat (false, 4)
  213956. || tryInitialisingWithFormat (false, 3) || tryInitialisingWithFormat (false, 2)))
  213957. {
  213958. channelMaps.clear();
  213959. for (int i = 0; i <= channels.getHighestBit(); ++i)
  213960. if (channels[i])
  213961. channelMaps.add (i);
  213962. REFERENCE_TIME latency;
  213963. if (OK (client->GetStreamLatency (&latency)))
  213964. latencySamples = wasapi_refTimeToSamples (latency, sampleRate);
  213965. (void) OK (client->GetBufferSize (&actualBufferSize));
  213966. return OK (client->SetEventHandle (clientEvent));
  213967. }
  213968. return false;
  213969. }
  213970. void closeClient()
  213971. {
  213972. if (client != 0)
  213973. client->Stop();
  213974. client = 0;
  213975. ResetEvent (clientEvent);
  213976. }
  213977. ComSmartPtr <IMMDevice> device;
  213978. ComSmartPtr <IAudioClient> client;
  213979. double sampleRate, defaultSampleRate;
  213980. int numChannels, actualNumChannels;
  213981. int minBufferSize, defaultBufferSize, latencySamples;
  213982. const bool useExclusiveMode;
  213983. Array <double> rates;
  213984. HANDLE clientEvent;
  213985. BigInteger channels;
  213986. AudioDataConverters::DataFormat dataFormat;
  213987. Array <int> channelMaps;
  213988. UINT32 actualBufferSize;
  213989. int bytesPerSample;
  213990. private:
  213991. const ComSmartPtr <IAudioClient> createClient()
  213992. {
  213993. ComSmartPtr <IAudioClient> client;
  213994. if (device != 0)
  213995. {
  213996. HRESULT hr = device->Activate (__uuidof (IAudioClient), CLSCTX_INPROC_SERVER, 0, (void**) &client);
  213997. logFailure (hr);
  213998. }
  213999. return client;
  214000. }
  214001. bool tryInitialisingWithFormat (const bool useFloat, const int bytesPerSampleToTry)
  214002. {
  214003. WAVEFORMATEXTENSIBLE format;
  214004. zerostruct (format);
  214005. if (numChannels <= 2 && bytesPerSampleToTry <= 2)
  214006. {
  214007. format.Format.wFormatTag = WAVE_FORMAT_PCM;
  214008. }
  214009. else
  214010. {
  214011. format.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
  214012. format.Format.cbSize = sizeof (WAVEFORMATEXTENSIBLE) - sizeof (WAVEFORMATEX);
  214013. }
  214014. format.Format.nSamplesPerSec = roundDoubleToInt (sampleRate);
  214015. format.Format.nChannels = (WORD) numChannels;
  214016. format.Format.wBitsPerSample = (WORD) (8 * bytesPerSampleToTry);
  214017. format.Format.nAvgBytesPerSec = (DWORD) (format.Format.nSamplesPerSec * numChannels * bytesPerSampleToTry);
  214018. format.Format.nBlockAlign = (WORD) (numChannels * bytesPerSampleToTry);
  214019. format.SubFormat = useFloat ? KSDATAFORMAT_SUBTYPE_IEEE_FLOAT : KSDATAFORMAT_SUBTYPE_PCM;
  214020. format.Samples.wValidBitsPerSample = format.Format.wBitsPerSample;
  214021. switch (numChannels)
  214022. {
  214023. case 1: format.dwChannelMask = SPEAKER_FRONT_CENTER; break;
  214024. case 2: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT; break;
  214025. case 4: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  214026. case 6: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  214027. 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;
  214028. default: break;
  214029. }
  214030. WAVEFORMATEXTENSIBLE* nearestFormat = 0;
  214031. HRESULT hr = client->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  214032. (WAVEFORMATEX*) &format, useExclusiveMode ? 0 : (WAVEFORMATEX**) &nearestFormat);
  214033. logFailure (hr);
  214034. if (hr == S_FALSE && format.Format.nSamplesPerSec == nearestFormat->Format.nSamplesPerSec)
  214035. {
  214036. wasapi_copyWavFormat (format, (WAVEFORMATEX*) nearestFormat);
  214037. hr = S_OK;
  214038. }
  214039. CoTaskMemFree (nearestFormat);
  214040. REFERENCE_TIME defaultPeriod = 0, minPeriod = 0;
  214041. if (useExclusiveMode)
  214042. OK (client->GetDevicePeriod (&defaultPeriod, &minPeriod));
  214043. GUID session;
  214044. if (hr == S_OK
  214045. && OK (client->Initialize (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  214046. AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
  214047. defaultPeriod, defaultPeriod, (WAVEFORMATEX*) &format, &session)))
  214048. {
  214049. actualNumChannels = format.Format.nChannels;
  214050. const bool isFloat = format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE && format.SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
  214051. bytesPerSample = format.Format.wBitsPerSample / 8;
  214052. dataFormat = isFloat ? AudioDataConverters::float32LE
  214053. : (bytesPerSample == 4 ? AudioDataConverters::int32LE
  214054. : ((bytesPerSample == 3 ? AudioDataConverters::int24LE
  214055. : AudioDataConverters::int16LE)));
  214056. return true;
  214057. }
  214058. return false;
  214059. }
  214060. WASAPIDeviceBase (const WASAPIDeviceBase&);
  214061. WASAPIDeviceBase& operator= (const WASAPIDeviceBase&);
  214062. };
  214063. class WASAPIInputDevice : public WASAPIDeviceBase
  214064. {
  214065. public:
  214066. WASAPIInputDevice (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  214067. : WASAPIDeviceBase (device_, useExclusiveMode_),
  214068. reservoir (1, 1)
  214069. {
  214070. }
  214071. ~WASAPIInputDevice()
  214072. {
  214073. close();
  214074. }
  214075. bool open (const double newSampleRate, const BigInteger& newChannels)
  214076. {
  214077. reservoirSize = 0;
  214078. reservoirCapacity = 16384;
  214079. reservoir.setSize (actualNumChannels * reservoirCapacity * sizeof (float));
  214080. return openClient (newSampleRate, newChannels)
  214081. && (numChannels == 0 || OK (client->GetService (__uuidof (IAudioCaptureClient), (void**) &captureClient)));
  214082. }
  214083. void close()
  214084. {
  214085. closeClient();
  214086. captureClient = 0;
  214087. reservoir.setSize (0);
  214088. }
  214089. void copyBuffers (float** destBuffers, int numDestBuffers, int bufferSize, Thread& thread)
  214090. {
  214091. if (numChannels <= 0)
  214092. return;
  214093. int offset = 0;
  214094. while (bufferSize > 0)
  214095. {
  214096. if (reservoirSize > 0) // There's stuff in the reservoir, so use that...
  214097. {
  214098. const int samplesToDo = jmin (bufferSize, (int) reservoirSize);
  214099. for (int i = 0; i < numDestBuffers; ++i)
  214100. {
  214101. float* const dest = destBuffers[i] + offset;
  214102. const int srcChan = channelMaps.getUnchecked(i);
  214103. switch (dataFormat)
  214104. {
  214105. case AudioDataConverters::float32LE:
  214106. AudioDataConverters::convertFloat32LEToFloat (((uint8*) reservoir.getData()) + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  214107. break;
  214108. case AudioDataConverters::int32LE:
  214109. AudioDataConverters::convertInt32LEToFloat (((uint8*) reservoir.getData()) + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  214110. break;
  214111. case AudioDataConverters::int24LE:
  214112. AudioDataConverters::convertInt24LEToFloat (((uint8*) reservoir.getData()) + 3 * srcChan, dest, samplesToDo, 3 * actualNumChannels);
  214113. break;
  214114. case AudioDataConverters::int16LE:
  214115. AudioDataConverters::convertInt16LEToFloat (((uint8*) reservoir.getData()) + 2 * srcChan, dest, samplesToDo, 2 * actualNumChannels);
  214116. break;
  214117. default: jassertfalse; break;
  214118. }
  214119. }
  214120. bufferSize -= samplesToDo;
  214121. offset += samplesToDo;
  214122. reservoirSize -= samplesToDo;
  214123. }
  214124. else
  214125. {
  214126. UINT32 packetLength = 0;
  214127. if (! OK (captureClient->GetNextPacketSize (&packetLength)))
  214128. break;
  214129. if (packetLength == 0)
  214130. {
  214131. if (thread.threadShouldExit())
  214132. break;
  214133. Thread::sleep (1);
  214134. continue;
  214135. }
  214136. uint8* inputData = 0;
  214137. UINT32 numSamplesAvailable;
  214138. DWORD flags;
  214139. if (OK (captureClient->GetBuffer (&inputData, &numSamplesAvailable, &flags, 0, 0)))
  214140. {
  214141. const int samplesToDo = jmin (bufferSize, (int) numSamplesAvailable);
  214142. for (int i = 0; i < numDestBuffers; ++i)
  214143. {
  214144. float* const dest = destBuffers[i] + offset;
  214145. const int srcChan = channelMaps.getUnchecked(i);
  214146. switch (dataFormat)
  214147. {
  214148. case AudioDataConverters::float32LE:
  214149. AudioDataConverters::convertFloat32LEToFloat (inputData + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  214150. break;
  214151. case AudioDataConverters::int32LE:
  214152. AudioDataConverters::convertInt32LEToFloat (inputData + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  214153. break;
  214154. case AudioDataConverters::int24LE:
  214155. AudioDataConverters::convertInt24LEToFloat (inputData + 3 * srcChan, dest, samplesToDo, 3 * actualNumChannels);
  214156. break;
  214157. case AudioDataConverters::int16LE:
  214158. AudioDataConverters::convertInt16LEToFloat (inputData + 2 * srcChan, dest, samplesToDo, 2 * actualNumChannels);
  214159. break;
  214160. default: jassertfalse; break;
  214161. }
  214162. }
  214163. bufferSize -= samplesToDo;
  214164. offset += samplesToDo;
  214165. if (samplesToDo < (int) numSamplesAvailable)
  214166. {
  214167. reservoirSize = jmin ((int) (numSamplesAvailable - samplesToDo), reservoirCapacity);
  214168. memcpy ((uint8*) reservoir.getData(), inputData + bytesPerSample * actualNumChannels * samplesToDo,
  214169. bytesPerSample * actualNumChannels * reservoirSize);
  214170. }
  214171. captureClient->ReleaseBuffer (numSamplesAvailable);
  214172. }
  214173. }
  214174. }
  214175. }
  214176. ComSmartPtr <IAudioCaptureClient> captureClient;
  214177. MemoryBlock reservoir;
  214178. int reservoirSize, reservoirCapacity;
  214179. private:
  214180. WASAPIInputDevice (const WASAPIInputDevice&);
  214181. WASAPIInputDevice& operator= (const WASAPIInputDevice&);
  214182. };
  214183. class WASAPIOutputDevice : public WASAPIDeviceBase
  214184. {
  214185. public:
  214186. WASAPIOutputDevice (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  214187. : WASAPIDeviceBase (device_, useExclusiveMode_)
  214188. {
  214189. }
  214190. ~WASAPIOutputDevice()
  214191. {
  214192. close();
  214193. }
  214194. bool open (const double newSampleRate, const BigInteger& newChannels)
  214195. {
  214196. return openClient (newSampleRate, newChannels)
  214197. && (numChannels == 0 || OK (client->GetService (__uuidof (IAudioRenderClient), (void**) &renderClient)));
  214198. }
  214199. void close()
  214200. {
  214201. closeClient();
  214202. renderClient = 0;
  214203. }
  214204. void copyBuffers (const float** const srcBuffers, const int numSrcBuffers, int bufferSize, Thread& thread)
  214205. {
  214206. if (numChannels <= 0)
  214207. return;
  214208. int offset = 0;
  214209. while (bufferSize > 0)
  214210. {
  214211. UINT32 padding = 0;
  214212. if (! OK (client->GetCurrentPadding (&padding)))
  214213. return;
  214214. int samplesToDo = useExclusiveMode ? bufferSize
  214215. : jmin ((int) (actualBufferSize - padding), bufferSize);
  214216. if (samplesToDo <= 0)
  214217. {
  214218. if (thread.threadShouldExit())
  214219. break;
  214220. Thread::sleep (0);
  214221. continue;
  214222. }
  214223. uint8* outputData = 0;
  214224. if (OK (renderClient->GetBuffer (samplesToDo, &outputData)))
  214225. {
  214226. for (int i = 0; i < numSrcBuffers; ++i)
  214227. {
  214228. const float* const source = srcBuffers[i] + offset;
  214229. const int destChan = channelMaps.getUnchecked(i);
  214230. switch (dataFormat)
  214231. {
  214232. case AudioDataConverters::float32LE:
  214233. AudioDataConverters::convertFloatToFloat32LE (source, outputData + 4 * destChan, samplesToDo, 4 * actualNumChannels);
  214234. break;
  214235. case AudioDataConverters::int32LE:
  214236. AudioDataConverters::convertFloatToInt32LE (source, outputData + 4 * destChan, samplesToDo, 4 * actualNumChannels);
  214237. break;
  214238. case AudioDataConverters::int24LE:
  214239. AudioDataConverters::convertFloatToInt24LE (source, outputData + 3 * destChan, samplesToDo, 3 * actualNumChannels);
  214240. break;
  214241. case AudioDataConverters::int16LE:
  214242. AudioDataConverters::convertFloatToInt16LE (source, outputData + 2 * destChan, samplesToDo, 2 * actualNumChannels);
  214243. break;
  214244. default: jassertfalse; break;
  214245. }
  214246. }
  214247. renderClient->ReleaseBuffer (samplesToDo, 0);
  214248. offset += samplesToDo;
  214249. bufferSize -= samplesToDo;
  214250. }
  214251. }
  214252. }
  214253. ComSmartPtr <IAudioRenderClient> renderClient;
  214254. private:
  214255. WASAPIOutputDevice (const WASAPIOutputDevice&);
  214256. WASAPIOutputDevice& operator= (const WASAPIOutputDevice&);
  214257. };
  214258. class WASAPIAudioIODevice : public AudioIODevice,
  214259. public Thread
  214260. {
  214261. public:
  214262. WASAPIAudioIODevice (const String& deviceName,
  214263. const String& outputDeviceId_,
  214264. const String& inputDeviceId_,
  214265. const bool useExclusiveMode_)
  214266. : AudioIODevice (deviceName, "Windows Audio"),
  214267. Thread ("Juce WASAPI"),
  214268. isOpen_ (false),
  214269. isStarted (false),
  214270. outputDevice (0),
  214271. outputDeviceId (outputDeviceId_),
  214272. inputDevice (0),
  214273. inputDeviceId (inputDeviceId_),
  214274. useExclusiveMode (useExclusiveMode_),
  214275. currentBufferSizeSamples (0),
  214276. currentSampleRate (0),
  214277. callback (0)
  214278. {
  214279. }
  214280. ~WASAPIAudioIODevice()
  214281. {
  214282. close();
  214283. deleteAndZero (inputDevice);
  214284. deleteAndZero (outputDevice);
  214285. }
  214286. bool initialise()
  214287. {
  214288. double defaultSampleRateIn = 0, defaultSampleRateOut = 0;
  214289. int minBufferSizeIn = 0, defaultBufferSizeIn = 0, minBufferSizeOut = 0, defaultBufferSizeOut = 0;
  214290. latencyIn = latencyOut = 0;
  214291. Array <double> ratesIn, ratesOut;
  214292. if (createDevices())
  214293. {
  214294. jassert (inputDevice != 0 || outputDevice != 0);
  214295. if (inputDevice != 0 && outputDevice != 0)
  214296. {
  214297. defaultSampleRate = jmin (inputDevice->defaultSampleRate, outputDevice->defaultSampleRate);
  214298. minBufferSize = jmin (inputDevice->minBufferSize, outputDevice->minBufferSize);
  214299. defaultBufferSize = jmax (inputDevice->defaultBufferSize, outputDevice->defaultBufferSize);
  214300. sampleRates = inputDevice->rates;
  214301. sampleRates.removeValuesNotIn (outputDevice->rates);
  214302. }
  214303. else
  214304. {
  214305. WASAPIDeviceBase* const d = inputDevice != 0 ? (WASAPIDeviceBase*) inputDevice : (WASAPIDeviceBase*) outputDevice;
  214306. defaultSampleRate = d->defaultSampleRate;
  214307. minBufferSize = d->minBufferSize;
  214308. defaultBufferSize = d->defaultBufferSize;
  214309. sampleRates = d->rates;
  214310. }
  214311. bufferSizes.addUsingDefaultSort (defaultBufferSize);
  214312. if (minBufferSize != defaultBufferSize)
  214313. bufferSizes.addUsingDefaultSort (minBufferSize);
  214314. int n = 64;
  214315. for (int i = 0; i < 40; ++i)
  214316. {
  214317. if (n >= minBufferSize && n <= 2048 && ! bufferSizes.contains (n))
  214318. bufferSizes.addUsingDefaultSort (n);
  214319. n += (n < 512) ? 32 : (n < 1024 ? 64 : 128);
  214320. }
  214321. return true;
  214322. }
  214323. return false;
  214324. }
  214325. const StringArray getOutputChannelNames()
  214326. {
  214327. StringArray outChannels;
  214328. if (outputDevice != 0)
  214329. for (int i = 1; i <= outputDevice->actualNumChannels; ++i)
  214330. outChannels.add ("Output channel " + String (i));
  214331. return outChannels;
  214332. }
  214333. const StringArray getInputChannelNames()
  214334. {
  214335. StringArray inChannels;
  214336. if (inputDevice != 0)
  214337. for (int i = 1; i <= inputDevice->actualNumChannels; ++i)
  214338. inChannels.add ("Input channel " + String (i));
  214339. return inChannels;
  214340. }
  214341. int getNumSampleRates() { return sampleRates.size(); }
  214342. double getSampleRate (int index) { return sampleRates [index]; }
  214343. int getNumBufferSizesAvailable() { return bufferSizes.size(); }
  214344. int getBufferSizeSamples (int index) { return bufferSizes [index]; }
  214345. int getDefaultBufferSize() { return defaultBufferSize; }
  214346. int getCurrentBufferSizeSamples() { return currentBufferSizeSamples; }
  214347. double getCurrentSampleRate() { return currentSampleRate; }
  214348. int getCurrentBitDepth() { return 32; }
  214349. int getOutputLatencyInSamples() { return latencyOut; }
  214350. int getInputLatencyInSamples() { return latencyIn; }
  214351. const BigInteger getActiveOutputChannels() const { return outputDevice != 0 ? outputDevice->channels : BigInteger(); }
  214352. const BigInteger getActiveInputChannels() const { return inputDevice != 0 ? inputDevice->channels : BigInteger(); }
  214353. const String getLastError() { return lastError; }
  214354. const String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  214355. double sampleRate, int bufferSizeSamples)
  214356. {
  214357. close();
  214358. lastError = String::empty;
  214359. if (sampleRates.size() == 0 && inputDevice != 0 && outputDevice != 0)
  214360. {
  214361. lastError = "The input and output devices don't share a common sample rate!";
  214362. return lastError;
  214363. }
  214364. currentBufferSizeSamples = bufferSizeSamples <= 0 ? defaultBufferSize : jmax (bufferSizeSamples, minBufferSize);
  214365. currentSampleRate = sampleRate > 0 ? sampleRate : defaultSampleRate;
  214366. if (inputDevice != 0 && ! inputDevice->open (currentSampleRate, inputChannels))
  214367. {
  214368. lastError = "Couldn't open the input device!";
  214369. return lastError;
  214370. }
  214371. if (outputDevice != 0 && ! outputDevice->open (currentSampleRate, outputChannels))
  214372. {
  214373. close();
  214374. lastError = "Couldn't open the output device!";
  214375. return lastError;
  214376. }
  214377. if (inputDevice != 0)
  214378. ResetEvent (inputDevice->clientEvent);
  214379. if (outputDevice != 0)
  214380. ResetEvent (outputDevice->clientEvent);
  214381. startThread (8);
  214382. Thread::sleep (5);
  214383. if (inputDevice != 0 && inputDevice->client != 0)
  214384. {
  214385. latencyIn = inputDevice->latencySamples + inputDevice->actualBufferSize + inputDevice->minBufferSize;
  214386. HRESULT hr = inputDevice->client->Start();
  214387. logFailure (hr); //xxx handle this
  214388. }
  214389. if (outputDevice != 0 && outputDevice->client != 0)
  214390. {
  214391. latencyOut = outputDevice->latencySamples + outputDevice->actualBufferSize + outputDevice->minBufferSize;
  214392. HRESULT hr = outputDevice->client->Start();
  214393. logFailure (hr); //xxx handle this
  214394. }
  214395. isOpen_ = true;
  214396. return lastError;
  214397. }
  214398. void close()
  214399. {
  214400. stop();
  214401. if (inputDevice != 0)
  214402. SetEvent (inputDevice->clientEvent);
  214403. if (outputDevice != 0)
  214404. SetEvent (outputDevice->clientEvent);
  214405. stopThread (5000);
  214406. if (inputDevice != 0)
  214407. inputDevice->close();
  214408. if (outputDevice != 0)
  214409. outputDevice->close();
  214410. isOpen_ = false;
  214411. }
  214412. bool isOpen() { return isOpen_ && isThreadRunning(); }
  214413. bool isPlaying() { return isStarted && isOpen_ && isThreadRunning(); }
  214414. void start (AudioIODeviceCallback* call)
  214415. {
  214416. if (isOpen_ && call != 0 && ! isStarted)
  214417. {
  214418. if (! isThreadRunning())
  214419. {
  214420. // something's gone wrong and the thread's stopped..
  214421. isOpen_ = false;
  214422. return;
  214423. }
  214424. call->audioDeviceAboutToStart (this);
  214425. const ScopedLock sl (startStopLock);
  214426. callback = call;
  214427. isStarted = true;
  214428. }
  214429. }
  214430. void stop()
  214431. {
  214432. if (isStarted)
  214433. {
  214434. AudioIODeviceCallback* const callbackLocal = callback;
  214435. {
  214436. const ScopedLock sl (startStopLock);
  214437. isStarted = false;
  214438. }
  214439. if (callbackLocal != 0)
  214440. callbackLocal->audioDeviceStopped();
  214441. }
  214442. }
  214443. void setMMThreadPriority()
  214444. {
  214445. DynamicLibraryLoader dll ("avrt.dll");
  214446. DynamicLibraryImport (AvSetMmThreadCharacteristics, avSetMmThreadCharacteristics, HANDLE, dll, (LPCTSTR, LPDWORD))
  214447. DynamicLibraryImport (AvSetMmThreadPriority, avSetMmThreadPriority, HANDLE, dll, (HANDLE, AVRT_PRIORITY))
  214448. if (avSetMmThreadCharacteristics != 0 && avSetMmThreadPriority != 0)
  214449. {
  214450. DWORD dummy = 0;
  214451. HANDLE h = avSetMmThreadCharacteristics (_T("Pro Audio"), &dummy);
  214452. if (h != 0)
  214453. avSetMmThreadPriority (h, AVRT_PRIORITY_NORMAL);
  214454. }
  214455. }
  214456. void run()
  214457. {
  214458. setMMThreadPriority();
  214459. const int bufferSize = currentBufferSizeSamples;
  214460. HANDLE events[2];
  214461. int numEvents = 0;
  214462. if (inputDevice != 0)
  214463. events [numEvents++] = inputDevice->clientEvent;
  214464. if (outputDevice != 0)
  214465. events [numEvents++] = outputDevice->clientEvent;
  214466. const int numInputBuffers = getActiveInputChannels().countNumberOfSetBits();
  214467. const int numOutputBuffers = getActiveOutputChannels().countNumberOfSetBits();
  214468. AudioSampleBuffer ins (jmax (1, numInputBuffers), bufferSize + 32);
  214469. AudioSampleBuffer outs (jmax (1, numOutputBuffers), bufferSize + 32);
  214470. float** const inputBuffers = ins.getArrayOfChannels();
  214471. float** const outputBuffers = outs.getArrayOfChannels();
  214472. ins.clear();
  214473. while (! threadShouldExit())
  214474. {
  214475. const DWORD result = useExclusiveMode ? WaitForSingleObject (inputDevice->clientEvent, 1000)
  214476. : WaitForMultipleObjects (numEvents, events, true, 1000);
  214477. if (result == WAIT_TIMEOUT)
  214478. continue;
  214479. if (threadShouldExit())
  214480. break;
  214481. if (inputDevice != 0)
  214482. inputDevice->copyBuffers (inputBuffers, numInputBuffers, bufferSize, *this);
  214483. // Make the callback..
  214484. {
  214485. const ScopedLock sl (startStopLock);
  214486. if (isStarted)
  214487. {
  214488. JUCE_TRY
  214489. {
  214490. callback->audioDeviceIOCallback ((const float**) inputBuffers,
  214491. numInputBuffers,
  214492. outputBuffers,
  214493. numOutputBuffers,
  214494. bufferSize);
  214495. }
  214496. JUCE_CATCH_EXCEPTION
  214497. }
  214498. else
  214499. {
  214500. outs.clear();
  214501. }
  214502. }
  214503. if (useExclusiveMode && WaitForSingleObject (outputDevice->clientEvent, 1000) == WAIT_TIMEOUT)
  214504. continue;
  214505. if (outputDevice != 0)
  214506. outputDevice->copyBuffers ((const float**) outputBuffers, numOutputBuffers, bufferSize, *this);
  214507. }
  214508. }
  214509. juce_UseDebuggingNewOperator
  214510. String outputDeviceId, inputDeviceId;
  214511. String lastError;
  214512. private:
  214513. // Device stats...
  214514. WASAPIInputDevice* inputDevice;
  214515. WASAPIOutputDevice* outputDevice;
  214516. const bool useExclusiveMode;
  214517. double defaultSampleRate;
  214518. int minBufferSize, defaultBufferSize;
  214519. int latencyIn, latencyOut;
  214520. Array <double> sampleRates;
  214521. Array <int> bufferSizes;
  214522. // Active state...
  214523. bool isOpen_, isStarted;
  214524. int currentBufferSizeSamples;
  214525. double currentSampleRate;
  214526. AudioIODeviceCallback* callback;
  214527. CriticalSection startStopLock;
  214528. bool createDevices()
  214529. {
  214530. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  214531. if (! OK (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  214532. return false;
  214533. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  214534. if (! OK (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, &deviceCollection)))
  214535. return false;
  214536. UINT32 numDevices = 0;
  214537. if (! OK (deviceCollection->GetCount (&numDevices)))
  214538. return false;
  214539. for (UINT32 i = 0; i < numDevices; ++i)
  214540. {
  214541. ComSmartPtr <IMMDevice> device;
  214542. if (! OK (deviceCollection->Item (i, &device)))
  214543. continue;
  214544. const String deviceId (wasapi_getDeviceID (device));
  214545. if (deviceId.isEmpty())
  214546. continue;
  214547. const EDataFlow flow = wasapi_getDataFlow (device);
  214548. if (deviceId == inputDeviceId && flow == eCapture)
  214549. inputDevice = new WASAPIInputDevice (device, useExclusiveMode);
  214550. else if (deviceId == outputDeviceId && flow == eRender)
  214551. outputDevice = new WASAPIOutputDevice (device, useExclusiveMode);
  214552. }
  214553. return (outputDeviceId.isEmpty() || (outputDevice != 0 && outputDevice->isOk()))
  214554. && (inputDeviceId.isEmpty() || (inputDevice != 0 && inputDevice->isOk()));
  214555. }
  214556. WASAPIAudioIODevice (const WASAPIAudioIODevice&);
  214557. WASAPIAudioIODevice& operator= (const WASAPIAudioIODevice&);
  214558. };
  214559. class WASAPIAudioIODeviceType : public AudioIODeviceType
  214560. {
  214561. public:
  214562. WASAPIAudioIODeviceType()
  214563. : AudioIODeviceType ("Windows Audio"),
  214564. hasScanned (false)
  214565. {
  214566. }
  214567. ~WASAPIAudioIODeviceType()
  214568. {
  214569. }
  214570. void scanForDevices()
  214571. {
  214572. hasScanned = true;
  214573. outputDeviceNames.clear();
  214574. inputDeviceNames.clear();
  214575. outputDeviceIds.clear();
  214576. inputDeviceIds.clear();
  214577. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  214578. if (! OK (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  214579. return;
  214580. const String defaultRenderer = getDefaultEndpoint (enumerator, false);
  214581. const String defaultCapture = getDefaultEndpoint (enumerator, true);
  214582. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  214583. UINT32 numDevices = 0;
  214584. if (! (OK (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, &deviceCollection))
  214585. && OK (deviceCollection->GetCount (&numDevices))))
  214586. return;
  214587. for (UINT32 i = 0; i < numDevices; ++i)
  214588. {
  214589. ComSmartPtr <IMMDevice> device;
  214590. if (! OK (deviceCollection->Item (i, &device)))
  214591. continue;
  214592. const String deviceId (wasapi_getDeviceID (device));
  214593. DWORD state = 0;
  214594. if (! OK (device->GetState (&state)))
  214595. continue;
  214596. if (state != DEVICE_STATE_ACTIVE)
  214597. continue;
  214598. String name;
  214599. {
  214600. ComSmartPtr <IPropertyStore> properties;
  214601. if (! OK (device->OpenPropertyStore (STGM_READ, &properties)))
  214602. continue;
  214603. PROPVARIANT value;
  214604. PropVariantInit (&value);
  214605. if (OK (properties->GetValue (PKEY_Device_FriendlyName, &value)))
  214606. name = value.pwszVal;
  214607. PropVariantClear (&value);
  214608. }
  214609. const EDataFlow flow = wasapi_getDataFlow (device);
  214610. if (flow == eRender)
  214611. {
  214612. const int index = (deviceId == defaultRenderer) ? 0 : -1;
  214613. outputDeviceIds.insert (index, deviceId);
  214614. outputDeviceNames.insert (index, name);
  214615. }
  214616. else if (flow == eCapture)
  214617. {
  214618. const int index = (deviceId == defaultCapture) ? 0 : -1;
  214619. inputDeviceIds.insert (index, deviceId);
  214620. inputDeviceNames.insert (index, name);
  214621. }
  214622. }
  214623. inputDeviceNames.appendNumbersToDuplicates (false, false);
  214624. outputDeviceNames.appendNumbersToDuplicates (false, false);
  214625. }
  214626. const StringArray getDeviceNames (bool wantInputNames) const
  214627. {
  214628. jassert (hasScanned); // need to call scanForDevices() before doing this
  214629. return wantInputNames ? inputDeviceNames
  214630. : outputDeviceNames;
  214631. }
  214632. int getDefaultDeviceIndex (bool /*forInput*/) const
  214633. {
  214634. jassert (hasScanned); // need to call scanForDevices() before doing this
  214635. return 0;
  214636. }
  214637. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  214638. {
  214639. jassert (hasScanned); // need to call scanForDevices() before doing this
  214640. WASAPIAudioIODevice* const d = dynamic_cast <WASAPIAudioIODevice*> (device);
  214641. return d == 0 ? -1 : (asInput ? inputDeviceIds.indexOf (d->inputDeviceId)
  214642. : outputDeviceIds.indexOf (d->outputDeviceId));
  214643. }
  214644. bool hasSeparateInputsAndOutputs() const { return true; }
  214645. AudioIODevice* createDevice (const String& outputDeviceName,
  214646. const String& inputDeviceName)
  214647. {
  214648. jassert (hasScanned); // need to call scanForDevices() before doing this
  214649. const bool useExclusiveMode = false;
  214650. ScopedPointer<WASAPIAudioIODevice> device;
  214651. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  214652. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  214653. if (outputIndex >= 0 || inputIndex >= 0)
  214654. {
  214655. device = new WASAPIAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  214656. : inputDeviceName,
  214657. outputDeviceIds [outputIndex],
  214658. inputDeviceIds [inputIndex],
  214659. useExclusiveMode);
  214660. if (! device->initialise())
  214661. device = 0;
  214662. }
  214663. return device.release();
  214664. }
  214665. juce_UseDebuggingNewOperator
  214666. StringArray outputDeviceNames, outputDeviceIds;
  214667. StringArray inputDeviceNames, inputDeviceIds;
  214668. private:
  214669. bool hasScanned;
  214670. static const String getDefaultEndpoint (IMMDeviceEnumerator* const enumerator, const bool forCapture)
  214671. {
  214672. String s;
  214673. IMMDevice* dev = 0;
  214674. if (OK (enumerator->GetDefaultAudioEndpoint (forCapture ? eCapture : eRender,
  214675. eMultimedia, &dev)))
  214676. {
  214677. WCHAR* deviceId = 0;
  214678. if (OK (dev->GetId (&deviceId)))
  214679. {
  214680. s = String (deviceId);
  214681. CoTaskMemFree (deviceId);
  214682. }
  214683. dev->Release();
  214684. }
  214685. return s;
  214686. }
  214687. WASAPIAudioIODeviceType (const WASAPIAudioIODeviceType&);
  214688. WASAPIAudioIODeviceType& operator= (const WASAPIAudioIODeviceType&);
  214689. };
  214690. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI()
  214691. {
  214692. return new WASAPIAudioIODeviceType();
  214693. }
  214694. #undef logFailure
  214695. #undef OK
  214696. #endif
  214697. /*** End of inlined file: juce_win32_WASAPI.cpp ***/
  214698. /*** Start of inlined file: juce_win32_CameraDevice.cpp ***/
  214699. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  214700. // compiled on its own).
  214701. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  214702. class DShowCameraDeviceInteral : public ChangeBroadcaster
  214703. {
  214704. public:
  214705. DShowCameraDeviceInteral (CameraDevice* const owner_,
  214706. const ComSmartPtr <ICaptureGraphBuilder2>& captureGraphBuilder_,
  214707. const ComSmartPtr <IBaseFilter>& filter_,
  214708. int minWidth, int minHeight,
  214709. int maxWidth, int maxHeight)
  214710. : owner (owner_),
  214711. captureGraphBuilder (captureGraphBuilder_),
  214712. filter (filter_),
  214713. ok (false),
  214714. imageNeedsFlipping (false),
  214715. width (0),
  214716. height (0),
  214717. activeUsers (0),
  214718. recordNextFrameTime (false)
  214719. {
  214720. HRESULT hr = graphBuilder.CoCreateInstance (CLSID_FilterGraph);
  214721. if (FAILED (hr))
  214722. return;
  214723. hr = captureGraphBuilder->SetFiltergraph (graphBuilder);
  214724. if (FAILED (hr))
  214725. return;
  214726. hr = graphBuilder->QueryInterface (IID_IMediaControl, (void**) &mediaControl);
  214727. if (FAILED (hr))
  214728. return;
  214729. {
  214730. ComSmartPtr <IAMStreamConfig> streamConfig;
  214731. hr = captureGraphBuilder->FindInterface (&PIN_CATEGORY_CAPTURE, 0, filter,
  214732. IID_IAMStreamConfig, (void**) &streamConfig);
  214733. if (streamConfig != 0)
  214734. {
  214735. getVideoSizes (streamConfig);
  214736. if (! selectVideoSize (streamConfig, minWidth, minHeight, maxWidth, maxHeight))
  214737. return;
  214738. }
  214739. }
  214740. hr = graphBuilder->AddFilter (filter, _T("Video Capture"));
  214741. if (FAILED (hr))
  214742. return;
  214743. hr = smartTee.CoCreateInstance (CLSID_SmartTee);
  214744. if (FAILED (hr))
  214745. return;
  214746. hr = graphBuilder->AddFilter (smartTee, _T("Smart Tee"));
  214747. if (FAILED (hr))
  214748. return;
  214749. if (! connectFilters (filter, smartTee))
  214750. return;
  214751. ComSmartPtr <IBaseFilter> sampleGrabberBase;
  214752. hr = sampleGrabberBase.CoCreateInstance (CLSID_SampleGrabber);
  214753. if (FAILED (hr))
  214754. return;
  214755. hr = sampleGrabberBase->QueryInterface (IID_ISampleGrabber, (void**) &sampleGrabber);
  214756. if (FAILED (hr))
  214757. return;
  214758. AM_MEDIA_TYPE mt;
  214759. zerostruct (mt);
  214760. mt.majortype = MEDIATYPE_Video;
  214761. mt.subtype = MEDIASUBTYPE_RGB24;
  214762. mt.formattype = FORMAT_VideoInfo;
  214763. sampleGrabber->SetMediaType (&mt);
  214764. callback = new GrabberCallback (*this);
  214765. sampleGrabber->SetCallback (callback, 1);
  214766. hr = graphBuilder->AddFilter (sampleGrabberBase, _T("Sample Grabber"));
  214767. if (FAILED (hr))
  214768. return;
  214769. ComSmartPtr <IPin> grabberInputPin;
  214770. if (! (getPin (smartTee, PINDIR_OUTPUT, &smartTeeCaptureOutputPin, "capture")
  214771. && getPin (smartTee, PINDIR_OUTPUT, &smartTeePreviewOutputPin, "preview")
  214772. && getPin (sampleGrabberBase, PINDIR_INPUT, &grabberInputPin)))
  214773. return;
  214774. hr = graphBuilder->Connect (smartTeePreviewOutputPin, grabberInputPin);
  214775. if (FAILED (hr))
  214776. return;
  214777. zerostruct (mt);
  214778. hr = sampleGrabber->GetConnectedMediaType (&mt);
  214779. VIDEOINFOHEADER* pVih = (VIDEOINFOHEADER*) (mt.pbFormat);
  214780. width = pVih->bmiHeader.biWidth;
  214781. height = pVih->bmiHeader.biHeight;
  214782. ComSmartPtr <IBaseFilter> nullFilter;
  214783. hr = nullFilter.CoCreateInstance (CLSID_NullRenderer);
  214784. hr = graphBuilder->AddFilter (nullFilter, _T("Null Renderer"));
  214785. if (connectFilters (sampleGrabberBase, nullFilter)
  214786. && addGraphToRot())
  214787. {
  214788. activeImage = Image (Image::RGB, width, height, true);
  214789. loadingImage = Image (Image::RGB, width, height, true);
  214790. ok = true;
  214791. }
  214792. }
  214793. ~DShowCameraDeviceInteral()
  214794. {
  214795. if (mediaControl != 0)
  214796. mediaControl->Stop();
  214797. removeGraphFromRot();
  214798. for (int i = viewerComps.size(); --i >= 0;)
  214799. viewerComps.getUnchecked(i)->ownerDeleted();
  214800. callback = 0;
  214801. graphBuilder = 0;
  214802. sampleGrabber = 0;
  214803. mediaControl = 0;
  214804. filter = 0;
  214805. captureGraphBuilder = 0;
  214806. smartTee = 0;
  214807. smartTeePreviewOutputPin = 0;
  214808. smartTeeCaptureOutputPin = 0;
  214809. asfWriter = 0;
  214810. }
  214811. void addUser()
  214812. {
  214813. if (ok && activeUsers++ == 0)
  214814. mediaControl->Run();
  214815. }
  214816. void removeUser()
  214817. {
  214818. if (ok && --activeUsers == 0)
  214819. mediaControl->Stop();
  214820. }
  214821. void handleFrame (double /*time*/, BYTE* buffer, long /*bufferSize*/)
  214822. {
  214823. if (recordNextFrameTime)
  214824. {
  214825. const double defaultCameraLatency = 0.1;
  214826. firstRecordedTime = Time::getCurrentTime() - RelativeTime (defaultCameraLatency);
  214827. recordNextFrameTime = false;
  214828. ComSmartPtr <IPin> pin;
  214829. if (getPin (filter, PINDIR_OUTPUT, &pin))
  214830. {
  214831. ComSmartPtr <IAMPushSource> pushSource;
  214832. HRESULT hr = pin->QueryInterface (IID_IAMPushSource, (void**) &pushSource);
  214833. if (pushSource != 0)
  214834. {
  214835. REFERENCE_TIME latency = 0;
  214836. hr = pushSource->GetLatency (&latency);
  214837. firstRecordedTime = firstRecordedTime - RelativeTime ((double) latency);
  214838. }
  214839. }
  214840. }
  214841. {
  214842. const int lineStride = width * 3;
  214843. const ScopedLock sl (imageSwapLock);
  214844. {
  214845. const Image::BitmapData destData (loadingImage, 0, 0, width, height, true);
  214846. for (int i = 0; i < height; ++i)
  214847. memcpy (destData.getLinePointer ((height - 1) - i),
  214848. buffer + lineStride * i,
  214849. lineStride);
  214850. }
  214851. imageNeedsFlipping = true;
  214852. }
  214853. if (listeners.size() > 0)
  214854. callListeners (loadingImage);
  214855. sendChangeMessage (this);
  214856. }
  214857. void drawCurrentImage (Graphics& g, int x, int y, int w, int h)
  214858. {
  214859. if (imageNeedsFlipping)
  214860. {
  214861. const ScopedLock sl (imageSwapLock);
  214862. swapVariables (loadingImage, activeImage);
  214863. imageNeedsFlipping = false;
  214864. }
  214865. RectanglePlacement rp (RectanglePlacement::centred);
  214866. double dx = 0, dy = 0, dw = width, dh = height;
  214867. rp.applyTo (dx, dy, dw, dh, x, y, w, h);
  214868. const int rx = roundToInt (dx), ry = roundToInt (dy);
  214869. const int rw = roundToInt (dw), rh = roundToInt (dh);
  214870. g.saveState();
  214871. g.excludeClipRegion (Rectangle<int> (rx, ry, rw, rh));
  214872. g.fillAll (Colours::black);
  214873. g.restoreState();
  214874. g.drawImage (activeImage, rx, ry, rw, rh, 0, 0, width, height);
  214875. }
  214876. bool createFileCaptureFilter (const File& file)
  214877. {
  214878. removeFileCaptureFilter();
  214879. file.deleteFile();
  214880. mediaControl->Stop();
  214881. firstRecordedTime = Time();
  214882. recordNextFrameTime = true;
  214883. HRESULT hr = asfWriter.CoCreateInstance (CLSID_WMAsfWriter);
  214884. if (SUCCEEDED (hr))
  214885. {
  214886. ComSmartPtr <IFileSinkFilter> fileSink;
  214887. hr = asfWriter->QueryInterface (IID_IFileSinkFilter, (void**) &fileSink);
  214888. if (SUCCEEDED (hr))
  214889. {
  214890. hr = fileSink->SetFileName (file.getFullPathName(), 0);
  214891. if (SUCCEEDED (hr))
  214892. {
  214893. hr = graphBuilder->AddFilter (asfWriter, _T("AsfWriter"));
  214894. if (SUCCEEDED (hr))
  214895. {
  214896. ComSmartPtr <IConfigAsfWriter> asfConfig;
  214897. hr = asfWriter->QueryInterface (IID_IConfigAsfWriter, (void**) &asfConfig);
  214898. asfConfig->SetIndexMode (true);
  214899. ComSmartPtr <IWMProfileManager> profileManager;
  214900. hr = WMCreateProfileManager (&profileManager);
  214901. // This gibberish is the DirectShow profile for a video-only wmv file.
  214902. String prof ("<profile version=\"589824\" storageformat=\"1\" name=\"Quality\" description=\"Quality type for output.\"><streamconfig "
  214903. "majortype=\"{73646976-0000-0010-8000-00AA00389B71}\" streamnumber=\"1\" streamname=\"Video Stream\" inputname=\"Video409\" bitrate=\"894960\" "
  214904. "bufferwindow=\"0\" reliabletransport=\"1\" decodercomplexity=\"AU\" rfc1766langid=\"en-us\"><videomediaprops maxkeyframespacing=\"50000000\" quality=\"90\"/>"
  214905. "<wmmediatype subtype=\"{33564D57-0000-0010-8000-00AA00389B71}\" bfixedsizesamples=\"0\" btemporalcompression=\"1\" lsamplesize=\"0\"> <videoinfoheader "
  214906. "dwbitrate=\"894960\" dwbiterrorrate=\"0\" avgtimeperframe=\"100000\"><rcsource left=\"0\" top=\"0\" right=\"$WIDTH\" bottom=\"$HEIGHT\"/> <rctarget "
  214907. "left=\"0\" top=\"0\" right=\"$WIDTH\" bottom=\"$HEIGHT\"/> <bitmapinfoheader biwidth=\"$WIDTH\" biheight=\"$HEIGHT\" biplanes=\"1\" bibitcount=\"24\" "
  214908. "bicompression=\"WMV3\" bisizeimage=\"0\" bixpelspermeter=\"0\" biypelspermeter=\"0\" biclrused=\"0\" biclrimportant=\"0\"/> "
  214909. "</videoinfoheader></wmmediatype></streamconfig></profile>");
  214910. prof = prof.replace ("$WIDTH", String (width))
  214911. .replace ("$HEIGHT", String (height));
  214912. ComSmartPtr <IWMProfile> currentProfile;
  214913. hr = profileManager->LoadProfileByData ((const WCHAR*) prof, &currentProfile);
  214914. hr = asfConfig->ConfigureFilterUsingProfile (currentProfile);
  214915. if (SUCCEEDED (hr))
  214916. {
  214917. ComSmartPtr <IPin> asfWriterInputPin;
  214918. if (getPin (asfWriter, PINDIR_INPUT, &asfWriterInputPin, "Video Input 01"))
  214919. {
  214920. hr = graphBuilder->Connect (smartTeeCaptureOutputPin, asfWriterInputPin);
  214921. if (SUCCEEDED (hr)
  214922. && ok && activeUsers > 0
  214923. && SUCCEEDED (mediaControl->Run()))
  214924. {
  214925. return true;
  214926. }
  214927. }
  214928. }
  214929. }
  214930. }
  214931. }
  214932. }
  214933. removeFileCaptureFilter();
  214934. if (ok && activeUsers > 0)
  214935. mediaControl->Run();
  214936. return false;
  214937. }
  214938. void removeFileCaptureFilter()
  214939. {
  214940. mediaControl->Stop();
  214941. if (asfWriter != 0)
  214942. {
  214943. graphBuilder->RemoveFilter (asfWriter);
  214944. asfWriter = 0;
  214945. }
  214946. if (ok && activeUsers > 0)
  214947. mediaControl->Run();
  214948. }
  214949. void addListener (CameraImageListener* listenerToAdd)
  214950. {
  214951. const ScopedLock sl (listenerLock);
  214952. if (listeners.size() == 0)
  214953. addUser();
  214954. listeners.addIfNotAlreadyThere (listenerToAdd);
  214955. }
  214956. void removeListener (CameraImageListener* listenerToRemove)
  214957. {
  214958. const ScopedLock sl (listenerLock);
  214959. listeners.removeValue (listenerToRemove);
  214960. if (listeners.size() == 0)
  214961. removeUser();
  214962. }
  214963. void callListeners (const Image& image)
  214964. {
  214965. const ScopedLock sl (listenerLock);
  214966. for (int i = listeners.size(); --i >= 0;)
  214967. {
  214968. CameraImageListener* const l = listeners[i];
  214969. if (l != 0)
  214970. l->imageReceived (image);
  214971. }
  214972. }
  214973. class DShowCaptureViewerComp : public Component,
  214974. public ChangeListener
  214975. {
  214976. public:
  214977. DShowCaptureViewerComp (DShowCameraDeviceInteral* const owner_)
  214978. : owner (owner_)
  214979. {
  214980. setOpaque (true);
  214981. owner->addChangeListener (this);
  214982. owner->addUser();
  214983. owner->viewerComps.add (this);
  214984. setSize (owner_->width, owner_->height);
  214985. }
  214986. ~DShowCaptureViewerComp()
  214987. {
  214988. if (owner != 0)
  214989. {
  214990. owner->viewerComps.removeValue (this);
  214991. owner->removeUser();
  214992. owner->removeChangeListener (this);
  214993. }
  214994. }
  214995. void ownerDeleted()
  214996. {
  214997. owner = 0;
  214998. }
  214999. void paint (Graphics& g)
  215000. {
  215001. g.setColour (Colours::black);
  215002. g.setImageResamplingQuality (Graphics::lowResamplingQuality);
  215003. if (owner != 0)
  215004. owner->drawCurrentImage (g, 0, 0, getWidth(), getHeight());
  215005. else
  215006. g.fillAll (Colours::black);
  215007. }
  215008. void changeListenerCallback (void*)
  215009. {
  215010. repaint();
  215011. }
  215012. private:
  215013. DShowCameraDeviceInteral* owner;
  215014. };
  215015. bool ok;
  215016. int width, height;
  215017. Time firstRecordedTime;
  215018. Array <DShowCaptureViewerComp*> viewerComps;
  215019. private:
  215020. CameraDevice* const owner;
  215021. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  215022. ComSmartPtr <IBaseFilter> filter;
  215023. ComSmartPtr <IBaseFilter> smartTee;
  215024. ComSmartPtr <IGraphBuilder> graphBuilder;
  215025. ComSmartPtr <ISampleGrabber> sampleGrabber;
  215026. ComSmartPtr <IMediaControl> mediaControl;
  215027. ComSmartPtr <IPin> smartTeePreviewOutputPin;
  215028. ComSmartPtr <IPin> smartTeeCaptureOutputPin;
  215029. ComSmartPtr <IBaseFilter> asfWriter;
  215030. int activeUsers;
  215031. Array <int> widths, heights;
  215032. DWORD graphRegistrationID;
  215033. CriticalSection imageSwapLock;
  215034. bool imageNeedsFlipping;
  215035. Image loadingImage;
  215036. Image activeImage;
  215037. bool recordNextFrameTime;
  215038. void getVideoSizes (IAMStreamConfig* const streamConfig)
  215039. {
  215040. widths.clear();
  215041. heights.clear();
  215042. int count = 0, size = 0;
  215043. streamConfig->GetNumberOfCapabilities (&count, &size);
  215044. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  215045. {
  215046. for (int i = 0; i < count; ++i)
  215047. {
  215048. VIDEO_STREAM_CONFIG_CAPS scc;
  215049. AM_MEDIA_TYPE* config;
  215050. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  215051. if (SUCCEEDED (hr))
  215052. {
  215053. const int w = scc.InputSize.cx;
  215054. const int h = scc.InputSize.cy;
  215055. bool duplicate = false;
  215056. for (int j = widths.size(); --j >= 0;)
  215057. {
  215058. if (w == widths.getUnchecked (j) && h == heights.getUnchecked (j))
  215059. {
  215060. duplicate = true;
  215061. break;
  215062. }
  215063. }
  215064. if (! duplicate)
  215065. {
  215066. DBG ("Camera capture size: " + String (w) + ", " + String (h));
  215067. widths.add (w);
  215068. heights.add (h);
  215069. }
  215070. deleteMediaType (config);
  215071. }
  215072. }
  215073. }
  215074. }
  215075. bool selectVideoSize (IAMStreamConfig* const streamConfig,
  215076. const int minWidth, const int minHeight,
  215077. const int maxWidth, const int maxHeight)
  215078. {
  215079. int count = 0, size = 0, bestArea = 0, bestIndex = -1;
  215080. streamConfig->GetNumberOfCapabilities (&count, &size);
  215081. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  215082. {
  215083. AM_MEDIA_TYPE* config;
  215084. VIDEO_STREAM_CONFIG_CAPS scc;
  215085. for (int i = 0; i < count; ++i)
  215086. {
  215087. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  215088. if (SUCCEEDED (hr))
  215089. {
  215090. if (scc.InputSize.cx >= minWidth
  215091. && scc.InputSize.cy >= minHeight
  215092. && scc.InputSize.cx <= maxWidth
  215093. && scc.InputSize.cy <= maxHeight)
  215094. {
  215095. int area = scc.InputSize.cx * scc.InputSize.cy;
  215096. if (area > bestArea)
  215097. {
  215098. bestIndex = i;
  215099. bestArea = area;
  215100. }
  215101. }
  215102. deleteMediaType (config);
  215103. }
  215104. }
  215105. if (bestIndex >= 0)
  215106. {
  215107. HRESULT hr = streamConfig->GetStreamCaps (bestIndex, &config, (BYTE*) &scc);
  215108. hr = streamConfig->SetFormat (config);
  215109. deleteMediaType (config);
  215110. return SUCCEEDED (hr);
  215111. }
  215112. }
  215113. return false;
  215114. }
  215115. static bool getPin (IBaseFilter* filter, const PIN_DIRECTION wantedDirection, IPin** result, const char* pinName = 0)
  215116. {
  215117. ComSmartPtr <IEnumPins> enumerator;
  215118. ComSmartPtr <IPin> pin;
  215119. filter->EnumPins (&enumerator);
  215120. while (enumerator->Next (1, &pin, 0) == S_OK)
  215121. {
  215122. PIN_DIRECTION dir;
  215123. pin->QueryDirection (&dir);
  215124. if (wantedDirection == dir)
  215125. {
  215126. PIN_INFO info;
  215127. zerostruct (info);
  215128. pin->QueryPinInfo (&info);
  215129. if (pinName == 0 || String (pinName).equalsIgnoreCase (String (info.achName)))
  215130. {
  215131. pin->AddRef();
  215132. *result = pin;
  215133. return true;
  215134. }
  215135. }
  215136. }
  215137. return false;
  215138. }
  215139. bool connectFilters (IBaseFilter* const first, IBaseFilter* const second) const
  215140. {
  215141. ComSmartPtr <IPin> in, out;
  215142. return getPin (first, PINDIR_OUTPUT, &out)
  215143. && getPin (second, PINDIR_INPUT, &in)
  215144. && SUCCEEDED (graphBuilder->Connect (out, in));
  215145. }
  215146. bool addGraphToRot()
  215147. {
  215148. ComSmartPtr <IRunningObjectTable> rot;
  215149. if (FAILED (GetRunningObjectTable (0, &rot)))
  215150. return false;
  215151. ComSmartPtr <IMoniker> moniker;
  215152. WCHAR buffer[128];
  215153. HRESULT hr = CreateItemMoniker (_T("!"), buffer, &moniker);
  215154. if (FAILED (hr))
  215155. return false;
  215156. graphRegistrationID = 0;
  215157. return SUCCEEDED (rot->Register (0, graphBuilder, moniker, &graphRegistrationID));
  215158. }
  215159. void removeGraphFromRot()
  215160. {
  215161. ComSmartPtr <IRunningObjectTable> rot;
  215162. if (SUCCEEDED (GetRunningObjectTable (0, &rot)))
  215163. rot->Revoke (graphRegistrationID);
  215164. }
  215165. static void deleteMediaType (AM_MEDIA_TYPE* const pmt)
  215166. {
  215167. if (pmt->cbFormat != 0)
  215168. CoTaskMemFree ((PVOID) pmt->pbFormat);
  215169. if (pmt->pUnk != 0)
  215170. pmt->pUnk->Release();
  215171. CoTaskMemFree (pmt);
  215172. }
  215173. class GrabberCallback : public ComBaseClassHelper <ISampleGrabberCB>
  215174. {
  215175. public:
  215176. GrabberCallback (DShowCameraDeviceInteral& owner_)
  215177. : owner (owner_)
  215178. {
  215179. }
  215180. STDMETHODIMP SampleCB (double /*SampleTime*/, IMediaSample* /*pSample*/)
  215181. {
  215182. return E_FAIL;
  215183. }
  215184. STDMETHODIMP BufferCB (double time, BYTE* buffer, long bufferSize)
  215185. {
  215186. owner.handleFrame (time, buffer, bufferSize);
  215187. return S_OK;
  215188. }
  215189. private:
  215190. DShowCameraDeviceInteral& owner;
  215191. GrabberCallback (const GrabberCallback&);
  215192. GrabberCallback& operator= (const GrabberCallback&);
  215193. };
  215194. ComSmartPtr <GrabberCallback> callback;
  215195. Array <CameraImageListener*> listeners;
  215196. CriticalSection listenerLock;
  215197. DShowCameraDeviceInteral (const DShowCameraDeviceInteral&);
  215198. DShowCameraDeviceInteral& operator= (const DShowCameraDeviceInteral&);
  215199. };
  215200. CameraDevice::CameraDevice (const String& name_, int /*index*/)
  215201. : name (name_)
  215202. {
  215203. isRecording = false;
  215204. }
  215205. CameraDevice::~CameraDevice()
  215206. {
  215207. stopRecording();
  215208. delete static_cast <DShowCameraDeviceInteral*> (internal);
  215209. internal = 0;
  215210. }
  215211. Component* CameraDevice::createViewerComponent()
  215212. {
  215213. return new DShowCameraDeviceInteral::DShowCaptureViewerComp (static_cast <DShowCameraDeviceInteral*> (internal));
  215214. }
  215215. const String CameraDevice::getFileExtension()
  215216. {
  215217. return ".wmv";
  215218. }
  215219. void CameraDevice::startRecordingToFile (const File& file, int quality)
  215220. {
  215221. stopRecording();
  215222. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  215223. d->addUser();
  215224. isRecording = d->createFileCaptureFilter (file);
  215225. }
  215226. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  215227. {
  215228. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  215229. return d->firstRecordedTime;
  215230. }
  215231. void CameraDevice::stopRecording()
  215232. {
  215233. if (isRecording)
  215234. {
  215235. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  215236. d->removeFileCaptureFilter();
  215237. d->removeUser();
  215238. isRecording = false;
  215239. }
  215240. }
  215241. void CameraDevice::addListener (CameraImageListener* listenerToAdd)
  215242. {
  215243. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  215244. if (listenerToAdd != 0)
  215245. d->addListener (listenerToAdd);
  215246. }
  215247. void CameraDevice::removeListener (CameraImageListener* listenerToRemove)
  215248. {
  215249. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  215250. if (listenerToRemove != 0)
  215251. d->removeListener (listenerToRemove);
  215252. }
  215253. static ComSmartPtr <IBaseFilter> enumerateCameras (StringArray* const names,
  215254. const int deviceIndexToOpen,
  215255. String& name)
  215256. {
  215257. int index = 0;
  215258. ComSmartPtr <IBaseFilter> result;
  215259. ComSmartPtr <ICreateDevEnum> pDevEnum;
  215260. HRESULT hr = pDevEnum.CoCreateInstance (CLSID_SystemDeviceEnum);
  215261. if (SUCCEEDED (hr))
  215262. {
  215263. ComSmartPtr <IEnumMoniker> enumerator;
  215264. hr = pDevEnum->CreateClassEnumerator (CLSID_VideoInputDeviceCategory, &enumerator, 0);
  215265. if (SUCCEEDED (hr) && enumerator != 0)
  215266. {
  215267. ComSmartPtr <IBaseFilter> captureFilter;
  215268. ComSmartPtr <IMoniker> moniker;
  215269. ULONG fetched;
  215270. while (enumerator->Next (1, &moniker, &fetched) == S_OK)
  215271. {
  215272. hr = moniker->BindToObject (0, 0, IID_IBaseFilter, (void**) &captureFilter);
  215273. if (SUCCEEDED (hr))
  215274. {
  215275. ComSmartPtr <IPropertyBag> propertyBag;
  215276. hr = moniker->BindToStorage (0, 0, IID_IPropertyBag, (void**) &propertyBag);
  215277. if (SUCCEEDED (hr))
  215278. {
  215279. VARIANT var;
  215280. var.vt = VT_BSTR;
  215281. hr = propertyBag->Read (_T("FriendlyName"), &var, 0);
  215282. propertyBag = 0;
  215283. if (SUCCEEDED (hr))
  215284. {
  215285. if (names != 0)
  215286. names->add (var.bstrVal);
  215287. if (index == deviceIndexToOpen)
  215288. {
  215289. name = var.bstrVal;
  215290. result = captureFilter;
  215291. captureFilter = 0;
  215292. break;
  215293. }
  215294. ++index;
  215295. }
  215296. moniker = 0;
  215297. }
  215298. captureFilter = 0;
  215299. }
  215300. }
  215301. }
  215302. }
  215303. return result;
  215304. }
  215305. const StringArray CameraDevice::getAvailableDevices()
  215306. {
  215307. StringArray devs;
  215308. String dummy;
  215309. enumerateCameras (&devs, -1, dummy);
  215310. return devs;
  215311. }
  215312. CameraDevice* CameraDevice::openDevice (int index,
  215313. int minWidth, int minHeight,
  215314. int maxWidth, int maxHeight)
  215315. {
  215316. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  215317. HRESULT hr = captureGraphBuilder.CoCreateInstance (CLSID_CaptureGraphBuilder2);
  215318. if (SUCCEEDED (hr))
  215319. {
  215320. String name;
  215321. const ComSmartPtr <IBaseFilter> filter (enumerateCameras (0, index, name));
  215322. if (filter != 0)
  215323. {
  215324. ScopedPointer <CameraDevice> cam (new CameraDevice (name, index));
  215325. DShowCameraDeviceInteral* const intern
  215326. = new DShowCameraDeviceInteral (cam, captureGraphBuilder, filter,
  215327. minWidth, minHeight, maxWidth, maxHeight);
  215328. cam->internal = intern;
  215329. if (intern->ok)
  215330. return cam.release();
  215331. }
  215332. }
  215333. return 0;
  215334. }
  215335. #endif
  215336. /*** End of inlined file: juce_win32_CameraDevice.cpp ***/
  215337. #endif
  215338. // Auto-link the other win32 libs that are needed by library calls..
  215339. #if (JUCE_AMALGAMATED_TEMPLATE || defined (JUCE_DLL_BUILD)) && JUCE_MSVC && ! DONT_AUTOLINK_TO_WIN32_LIBRARIES
  215340. /*** Start of inlined file: juce_win32_AutoLinkLibraries.h ***/
  215341. // Auto-links to various win32 libs that are needed by library calls..
  215342. #pragma comment(lib, "kernel32.lib")
  215343. #pragma comment(lib, "user32.lib")
  215344. #pragma comment(lib, "shell32.lib")
  215345. #pragma comment(lib, "gdi32.lib")
  215346. #pragma comment(lib, "vfw32.lib")
  215347. #pragma comment(lib, "comdlg32.lib")
  215348. #pragma comment(lib, "winmm.lib")
  215349. #pragma comment(lib, "wininet.lib")
  215350. #pragma comment(lib, "ole32.lib")
  215351. #pragma comment(lib, "oleaut32.lib")
  215352. #pragma comment(lib, "advapi32.lib")
  215353. #pragma comment(lib, "ws2_32.lib")
  215354. #pragma comment(lib, "comsupp.lib")
  215355. #pragma comment(lib, "version.lib")
  215356. #if JUCE_OPENGL
  215357. #pragma comment(lib, "OpenGL32.Lib")
  215358. #pragma comment(lib, "GlU32.Lib")
  215359. #endif
  215360. #if JUCE_QUICKTIME
  215361. #pragma comment (lib, "QTMLClient.lib")
  215362. #endif
  215363. #if JUCE_USE_CAMERA
  215364. #pragma comment (lib, "Strmiids.lib")
  215365. #pragma comment (lib, "wmvcore.lib")
  215366. #endif
  215367. /*** End of inlined file: juce_win32_AutoLinkLibraries.h ***/
  215368. #endif
  215369. END_JUCE_NAMESPACE
  215370. #endif
  215371. /*** End of inlined file: juce_win32_NativeCode.cpp ***/
  215372. #endif
  215373. #if JUCE_LINUX
  215374. /*** Start of inlined file: juce_linux_NativeCode.cpp ***/
  215375. /*
  215376. This file wraps together all the mac-specific code, so that
  215377. we can include all the native headers just once, and compile all our
  215378. platform-specific stuff in one big lump, keeping it out of the way of
  215379. the rest of the codebase.
  215380. */
  215381. #if JUCE_LINUX
  215382. BEGIN_JUCE_NAMESPACE
  215383. #define JUCE_INCLUDED_FILE 1
  215384. // Now include the actual code files..
  215385. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  215386. /*
  215387. This file contains posix routines that are common to both the Linux and Mac builds.
  215388. It gets included directly in the cpp files for these platforms.
  215389. */
  215390. CriticalSection::CriticalSection() throw()
  215391. {
  215392. pthread_mutexattr_t atts;
  215393. pthread_mutexattr_init (&atts);
  215394. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  215395. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  215396. pthread_mutex_init (&internal, &atts);
  215397. }
  215398. CriticalSection::~CriticalSection() throw()
  215399. {
  215400. pthread_mutex_destroy (&internal);
  215401. }
  215402. void CriticalSection::enter() const throw()
  215403. {
  215404. pthread_mutex_lock (&internal);
  215405. }
  215406. bool CriticalSection::tryEnter() const throw()
  215407. {
  215408. return pthread_mutex_trylock (&internal) == 0;
  215409. }
  215410. void CriticalSection::exit() const throw()
  215411. {
  215412. pthread_mutex_unlock (&internal);
  215413. }
  215414. class WaitableEventImpl
  215415. {
  215416. public:
  215417. WaitableEventImpl (const bool manualReset_)
  215418. : triggered (false),
  215419. manualReset (manualReset_)
  215420. {
  215421. pthread_cond_init (&condition, 0);
  215422. pthread_mutexattr_t atts;
  215423. pthread_mutexattr_init (&atts);
  215424. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  215425. pthread_mutex_init (&mutex, &atts);
  215426. }
  215427. ~WaitableEventImpl()
  215428. {
  215429. pthread_cond_destroy (&condition);
  215430. pthread_mutex_destroy (&mutex);
  215431. }
  215432. bool wait (const int timeOutMillisecs) throw()
  215433. {
  215434. pthread_mutex_lock (&mutex);
  215435. if (! triggered)
  215436. {
  215437. if (timeOutMillisecs < 0)
  215438. {
  215439. do
  215440. {
  215441. pthread_cond_wait (&condition, &mutex);
  215442. }
  215443. while (! triggered);
  215444. }
  215445. else
  215446. {
  215447. struct timeval now;
  215448. gettimeofday (&now, 0);
  215449. struct timespec time;
  215450. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  215451. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  215452. if (time.tv_nsec >= 1000000000)
  215453. {
  215454. time.tv_nsec -= 1000000000;
  215455. time.tv_sec++;
  215456. }
  215457. do
  215458. {
  215459. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  215460. {
  215461. pthread_mutex_unlock (&mutex);
  215462. return false;
  215463. }
  215464. }
  215465. while (! triggered);
  215466. }
  215467. }
  215468. if (! manualReset)
  215469. triggered = false;
  215470. pthread_mutex_unlock (&mutex);
  215471. return true;
  215472. }
  215473. void signal() throw()
  215474. {
  215475. pthread_mutex_lock (&mutex);
  215476. triggered = true;
  215477. pthread_cond_broadcast (&condition);
  215478. pthread_mutex_unlock (&mutex);
  215479. }
  215480. void reset() throw()
  215481. {
  215482. pthread_mutex_lock (&mutex);
  215483. triggered = false;
  215484. pthread_mutex_unlock (&mutex);
  215485. }
  215486. private:
  215487. pthread_cond_t condition;
  215488. pthread_mutex_t mutex;
  215489. bool triggered;
  215490. const bool manualReset;
  215491. WaitableEventImpl (const WaitableEventImpl&);
  215492. WaitableEventImpl& operator= (const WaitableEventImpl&);
  215493. };
  215494. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  215495. : internal (new WaitableEventImpl (manualReset))
  215496. {
  215497. }
  215498. WaitableEvent::~WaitableEvent() throw()
  215499. {
  215500. delete static_cast <WaitableEventImpl*> (internal);
  215501. }
  215502. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  215503. {
  215504. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  215505. }
  215506. void WaitableEvent::signal() const throw()
  215507. {
  215508. static_cast <WaitableEventImpl*> (internal)->signal();
  215509. }
  215510. void WaitableEvent::reset() const throw()
  215511. {
  215512. static_cast <WaitableEventImpl*> (internal)->reset();
  215513. }
  215514. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  215515. {
  215516. struct timespec time;
  215517. time.tv_sec = millisecs / 1000;
  215518. time.tv_nsec = (millisecs % 1000) * 1000000;
  215519. nanosleep (&time, 0);
  215520. }
  215521. const juce_wchar File::separator = '/';
  215522. const String File::separatorString ("/");
  215523. const File File::getCurrentWorkingDirectory()
  215524. {
  215525. HeapBlock<char> heapBuffer;
  215526. char localBuffer [1024];
  215527. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  215528. int bufferSize = 4096;
  215529. while (cwd == 0 && errno == ERANGE)
  215530. {
  215531. heapBuffer.malloc (bufferSize);
  215532. cwd = getcwd (heapBuffer, bufferSize - 1);
  215533. bufferSize += 1024;
  215534. }
  215535. return File (String::fromUTF8 (cwd));
  215536. }
  215537. bool File::setAsCurrentWorkingDirectory() const
  215538. {
  215539. return chdir (getFullPathName().toUTF8()) == 0;
  215540. }
  215541. static bool juce_stat (const String& fileName, struct stat& info)
  215542. {
  215543. return fileName.isNotEmpty()
  215544. && (stat (fileName.toUTF8(), &info) == 0);
  215545. }
  215546. bool File::isDirectory() const
  215547. {
  215548. struct stat info;
  215549. return fullPath.isEmpty()
  215550. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  215551. }
  215552. bool File::exists() const
  215553. {
  215554. return fullPath.isNotEmpty()
  215555. && access (fullPath.toUTF8(), F_OK) == 0;
  215556. }
  215557. bool File::existsAsFile() const
  215558. {
  215559. return exists() && ! isDirectory();
  215560. }
  215561. int64 File::getSize() const
  215562. {
  215563. struct stat info;
  215564. return juce_stat (fullPath, info) ? info.st_size : 0;
  215565. }
  215566. bool File::hasWriteAccess() const
  215567. {
  215568. if (exists())
  215569. return access (fullPath.toUTF8(), W_OK) == 0;
  215570. if ((! isDirectory()) && fullPath.containsChar (separator))
  215571. return getParentDirectory().hasWriteAccess();
  215572. return false;
  215573. }
  215574. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  215575. {
  215576. struct stat info;
  215577. const int res = stat (fullPath.toUTF8(), &info);
  215578. if (res != 0)
  215579. return false;
  215580. info.st_mode &= 0777; // Just permissions
  215581. if (shouldBeReadOnly)
  215582. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  215583. else
  215584. // Give everybody write permission?
  215585. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  215586. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  215587. }
  215588. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  215589. {
  215590. modificationTime = 0;
  215591. accessTime = 0;
  215592. creationTime = 0;
  215593. struct stat info;
  215594. const int res = stat (fullPath.toUTF8(), &info);
  215595. if (res == 0)
  215596. {
  215597. modificationTime = (int64) info.st_mtime * 1000;
  215598. accessTime = (int64) info.st_atime * 1000;
  215599. creationTime = (int64) info.st_ctime * 1000;
  215600. }
  215601. }
  215602. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  215603. {
  215604. struct utimbuf times;
  215605. times.actime = (time_t) (accessTime / 1000);
  215606. times.modtime = (time_t) (modificationTime / 1000);
  215607. return utime (fullPath.toUTF8(), &times) == 0;
  215608. }
  215609. bool File::deleteFile() const
  215610. {
  215611. if (! exists())
  215612. return true;
  215613. else if (isDirectory())
  215614. return rmdir (fullPath.toUTF8()) == 0;
  215615. else
  215616. return remove (fullPath.toUTF8()) == 0;
  215617. }
  215618. bool File::moveInternal (const File& dest) const
  215619. {
  215620. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  215621. return true;
  215622. if (hasWriteAccess() && copyInternal (dest))
  215623. {
  215624. if (deleteFile())
  215625. return true;
  215626. dest.deleteFile();
  215627. }
  215628. return false;
  215629. }
  215630. void File::createDirectoryInternal (const String& fileName) const
  215631. {
  215632. mkdir (fileName.toUTF8(), 0777);
  215633. }
  215634. void* juce_fileOpen (const File& file, bool forWriting)
  215635. {
  215636. int flags = O_RDONLY;
  215637. if (forWriting)
  215638. {
  215639. if (file.exists())
  215640. {
  215641. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  215642. if (f != -1)
  215643. lseek (f, 0, SEEK_END);
  215644. return (void*) f;
  215645. }
  215646. else
  215647. {
  215648. flags = O_RDWR + O_CREAT;
  215649. }
  215650. }
  215651. return (void*) open (file.getFullPathName().toUTF8(), flags, 00644);
  215652. }
  215653. void juce_fileClose (void* handle)
  215654. {
  215655. if (handle != 0)
  215656. close ((int) (pointer_sized_int) handle);
  215657. }
  215658. int juce_fileRead (void* handle, void* buffer, int size)
  215659. {
  215660. if (handle != 0)
  215661. return jmax (0, (int) read ((int) (pointer_sized_int) handle, buffer, size));
  215662. return 0;
  215663. }
  215664. int juce_fileWrite (void* handle, const void* buffer, int size)
  215665. {
  215666. if (handle != 0)
  215667. return (int) write ((int) (pointer_sized_int) handle, buffer, size);
  215668. return 0;
  215669. }
  215670. int64 juce_fileSetPosition (void* handle, int64 pos)
  215671. {
  215672. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  215673. return pos;
  215674. return -1;
  215675. }
  215676. int64 FileOutputStream::getPositionInternal() const
  215677. {
  215678. if (fileHandle != 0)
  215679. return lseek ((int) (pointer_sized_int) fileHandle, 0, SEEK_CUR);
  215680. return -1;
  215681. }
  215682. void FileOutputStream::flushInternal()
  215683. {
  215684. if (fileHandle != 0)
  215685. fsync ((int) (pointer_sized_int) fileHandle);
  215686. }
  215687. const File juce_getExecutableFile()
  215688. {
  215689. Dl_info exeInfo;
  215690. dladdr ((const void*) juce_getExecutableFile, &exeInfo);
  215691. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  215692. }
  215693. // if this file doesn't exist, find a parent of it that does..
  215694. static bool juce_doStatFS (File f, struct statfs& result)
  215695. {
  215696. for (int i = 5; --i >= 0;)
  215697. {
  215698. if (f.exists())
  215699. break;
  215700. f = f.getParentDirectory();
  215701. }
  215702. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  215703. }
  215704. int64 File::getBytesFreeOnVolume() const
  215705. {
  215706. struct statfs buf;
  215707. if (juce_doStatFS (*this, buf))
  215708. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  215709. return 0;
  215710. }
  215711. int64 File::getVolumeTotalSize() const
  215712. {
  215713. struct statfs buf;
  215714. if (juce_doStatFS (*this, buf))
  215715. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  215716. return 0;
  215717. }
  215718. const String File::getVolumeLabel() const
  215719. {
  215720. #if JUCE_MAC
  215721. struct VolAttrBuf
  215722. {
  215723. u_int32_t length;
  215724. attrreference_t mountPointRef;
  215725. char mountPointSpace [MAXPATHLEN];
  215726. } attrBuf;
  215727. struct attrlist attrList;
  215728. zerostruct (attrList);
  215729. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  215730. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  215731. File f (*this);
  215732. for (;;)
  215733. {
  215734. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  215735. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  215736. (int) attrBuf.mountPointRef.attr_length);
  215737. const File parent (f.getParentDirectory());
  215738. if (f == parent)
  215739. break;
  215740. f = parent;
  215741. }
  215742. #endif
  215743. return String::empty;
  215744. }
  215745. int File::getVolumeSerialNumber() const
  215746. {
  215747. return 0; // xxx
  215748. }
  215749. void juce_runSystemCommand (const String& command)
  215750. {
  215751. int result = system (command.toUTF8());
  215752. (void) result;
  215753. }
  215754. const String juce_getOutputFromCommand (const String& command)
  215755. {
  215756. // slight bodge here, as we just pipe the output into a temp file and read it...
  215757. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  215758. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  215759. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  215760. String result (tempFile.loadFileAsString());
  215761. tempFile.deleteFile();
  215762. return result;
  215763. }
  215764. class InterProcessLock::Pimpl
  215765. {
  215766. public:
  215767. Pimpl (const String& name, const int timeOutMillisecs)
  215768. : handle (0), refCount (1)
  215769. {
  215770. #if JUCE_MAC
  215771. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  215772. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  215773. #else
  215774. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  215775. #endif
  215776. temp.create();
  215777. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  215778. if (handle != 0)
  215779. {
  215780. struct flock fl;
  215781. zerostruct (fl);
  215782. fl.l_whence = SEEK_SET;
  215783. fl.l_type = F_WRLCK;
  215784. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  215785. for (;;)
  215786. {
  215787. const int result = fcntl (handle, F_SETLK, &fl);
  215788. if (result >= 0)
  215789. return;
  215790. if (errno != EINTR)
  215791. {
  215792. if (timeOutMillisecs == 0
  215793. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  215794. break;
  215795. Thread::sleep (10);
  215796. }
  215797. }
  215798. }
  215799. closeFile();
  215800. }
  215801. ~Pimpl()
  215802. {
  215803. closeFile();
  215804. }
  215805. void closeFile()
  215806. {
  215807. if (handle != 0)
  215808. {
  215809. struct flock fl;
  215810. zerostruct (fl);
  215811. fl.l_whence = SEEK_SET;
  215812. fl.l_type = F_UNLCK;
  215813. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  215814. {}
  215815. close (handle);
  215816. handle = 0;
  215817. }
  215818. }
  215819. int handle, refCount;
  215820. };
  215821. InterProcessLock::InterProcessLock (const String& name_)
  215822. : name (name_)
  215823. {
  215824. }
  215825. InterProcessLock::~InterProcessLock()
  215826. {
  215827. }
  215828. bool InterProcessLock::enter (const int timeOutMillisecs)
  215829. {
  215830. const ScopedLock sl (lock);
  215831. if (pimpl == 0)
  215832. {
  215833. pimpl = new Pimpl (name, timeOutMillisecs);
  215834. if (pimpl->handle == 0)
  215835. pimpl = 0;
  215836. }
  215837. else
  215838. {
  215839. pimpl->refCount++;
  215840. }
  215841. return pimpl != 0;
  215842. }
  215843. void InterProcessLock::exit()
  215844. {
  215845. const ScopedLock sl (lock);
  215846. // Trying to release the lock too many times!
  215847. jassert (pimpl != 0);
  215848. if (pimpl != 0 && --(pimpl->refCount) == 0)
  215849. pimpl = 0;
  215850. }
  215851. /*** End of inlined file: juce_posix_SharedCode.h ***/
  215852. /*** Start of inlined file: juce_linux_Files.cpp ***/
  215853. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  215854. // compiled on its own).
  215855. #if JUCE_INCLUDED_FILE
  215856. static const short U_ISOFS_SUPER_MAGIC = 0x9660; // linux/iso_fs.h
  215857. static const short U_MSDOS_SUPER_MAGIC = 0x4d44; // linux/msdos_fs.h
  215858. static const short U_NFS_SUPER_MAGIC = 0x6969; // linux/nfs_fs.h
  215859. static const short U_SMB_SUPER_MAGIC = 0x517B; // linux/smb_fs.h
  215860. bool File::copyInternal (const File& dest) const
  215861. {
  215862. FileInputStream in (*this);
  215863. if (dest.deleteFile())
  215864. {
  215865. {
  215866. FileOutputStream out (dest);
  215867. if (out.failedToOpen())
  215868. return false;
  215869. if (out.writeFromInputStream (in, -1) == getSize())
  215870. return true;
  215871. }
  215872. dest.deleteFile();
  215873. }
  215874. return false;
  215875. }
  215876. void File::findFileSystemRoots (Array<File>& destArray)
  215877. {
  215878. destArray.add (File ("/"));
  215879. }
  215880. bool File::isOnCDRomDrive() const
  215881. {
  215882. struct statfs buf;
  215883. return statfs (getFullPathName().toUTF8(), &buf) == 0
  215884. && buf.f_type == U_ISOFS_SUPER_MAGIC;
  215885. }
  215886. bool File::isOnHardDisk() const
  215887. {
  215888. struct statfs buf;
  215889. if (statfs (getFullPathName().toUTF8(), &buf) == 0)
  215890. {
  215891. switch (buf.f_type)
  215892. {
  215893. case U_ISOFS_SUPER_MAGIC: // CD-ROM
  215894. case U_MSDOS_SUPER_MAGIC: // Probably floppy (but could be mounted FAT filesystem)
  215895. case U_NFS_SUPER_MAGIC: // Network NFS
  215896. case U_SMB_SUPER_MAGIC: // Network Samba
  215897. return false;
  215898. default:
  215899. // Assume anything else is a hard-disk (but note it could
  215900. // be a RAM disk. There isn't a good way of determining
  215901. // this for sure)
  215902. return true;
  215903. }
  215904. }
  215905. // Assume so if this fails for some reason
  215906. return true;
  215907. }
  215908. bool File::isOnRemovableDrive() const
  215909. {
  215910. jassertfalse; // xxx not implemented for linux!
  215911. return false;
  215912. }
  215913. bool File::isHidden() const
  215914. {
  215915. return getFileName().startsWithChar ('.');
  215916. }
  215917. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  215918. const File File::getSpecialLocation (const SpecialLocationType type)
  215919. {
  215920. switch (type)
  215921. {
  215922. case userHomeDirectory:
  215923. {
  215924. const char* homeDir = getenv ("HOME");
  215925. if (homeDir == 0)
  215926. {
  215927. struct passwd* const pw = getpwuid (getuid());
  215928. if (pw != 0)
  215929. homeDir = pw->pw_dir;
  215930. }
  215931. return File (String::fromUTF8 (homeDir));
  215932. }
  215933. case userDocumentsDirectory:
  215934. case userMusicDirectory:
  215935. case userMoviesDirectory:
  215936. case userApplicationDataDirectory:
  215937. return File ("~");
  215938. case userDesktopDirectory:
  215939. return File ("~/Desktop");
  215940. case commonApplicationDataDirectory:
  215941. return File ("/var");
  215942. case globalApplicationsDirectory:
  215943. return File ("/usr");
  215944. case tempDirectory:
  215945. {
  215946. File tmp ("/var/tmp");
  215947. if (! tmp.isDirectory())
  215948. {
  215949. tmp = "/tmp";
  215950. if (! tmp.isDirectory())
  215951. tmp = File::getCurrentWorkingDirectory();
  215952. }
  215953. return tmp;
  215954. }
  215955. case invokedExecutableFile:
  215956. if (juce_Argv0 != 0)
  215957. return File (String::fromUTF8 (juce_Argv0));
  215958. // deliberate fall-through...
  215959. case currentExecutableFile:
  215960. case currentApplicationFile:
  215961. return juce_getExecutableFile();
  215962. default:
  215963. jassertfalse; // unknown type?
  215964. break;
  215965. }
  215966. return File::nonexistent;
  215967. }
  215968. const String File::getVersion() const
  215969. {
  215970. return String::empty; // xxx not yet implemented
  215971. }
  215972. const File File::getLinkedTarget() const
  215973. {
  215974. char buffer [4096];
  215975. size_t numChars = readlink (getFullPathName().toUTF8(),
  215976. buffer, sizeof (buffer));
  215977. if (numChars > 0 && numChars <= sizeof (buffer))
  215978. return File (String::fromUTF8 (buffer, (int) numChars));
  215979. return *this;
  215980. }
  215981. bool File::moveToTrash() const
  215982. {
  215983. if (! exists())
  215984. return true;
  215985. File trashCan ("~/.Trash");
  215986. if (! trashCan.isDirectory())
  215987. trashCan = "~/.local/share/Trash/files";
  215988. if (! trashCan.isDirectory())
  215989. return false;
  215990. return moveFileTo (trashCan.getNonexistentChildFile (getFileNameWithoutExtension(),
  215991. getFileExtension()));
  215992. }
  215993. class DirectoryIterator::NativeIterator::Pimpl
  215994. {
  215995. public:
  215996. Pimpl (const File& directory, const String& wildCard_)
  215997. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  215998. wildCard (wildCard_),
  215999. dir (opendir (directory.getFullPathName().toUTF8()))
  216000. {
  216001. if (wildCard == "*.*")
  216002. wildCard = "*";
  216003. wildcardUTF8 = wildCard.toUTF8();
  216004. }
  216005. ~Pimpl()
  216006. {
  216007. if (dir != 0)
  216008. closedir (dir);
  216009. }
  216010. bool next (String& filenameFound,
  216011. bool* const isDir, bool* const isHidden, int64* const fileSize,
  216012. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  216013. {
  216014. if (dir == 0)
  216015. return false;
  216016. for (;;)
  216017. {
  216018. struct dirent* const de = readdir (dir);
  216019. if (de == 0)
  216020. return false;
  216021. if (fnmatch (wildcardUTF8, de->d_name, FNM_CASEFOLD) == 0)
  216022. {
  216023. filenameFound = String::fromUTF8 (de->d_name);
  216024. const String path (parentDir + filenameFound);
  216025. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  216026. {
  216027. struct stat info;
  216028. const bool statOk = juce_stat (path, info);
  216029. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  216030. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  216031. if (modTime != 0) *modTime = statOk ? (int64) info.st_mtime * 1000 : 0;
  216032. if (creationTime != 0) *creationTime = statOk ? (int64) info.st_ctime * 1000 : 0;
  216033. }
  216034. if (isHidden != 0)
  216035. *isHidden = filenameFound.startsWithChar ('.');
  216036. if (isReadOnly != 0)
  216037. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  216038. return true;
  216039. }
  216040. }
  216041. }
  216042. private:
  216043. String parentDir, wildCard;
  216044. const char* wildcardUTF8;
  216045. DIR* dir;
  216046. Pimpl (const Pimpl&);
  216047. Pimpl& operator= (const Pimpl&);
  216048. };
  216049. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  216050. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  216051. {
  216052. }
  216053. DirectoryIterator::NativeIterator::~NativeIterator()
  216054. {
  216055. }
  216056. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  216057. bool* const isDir, bool* const isHidden, int64* const fileSize,
  216058. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  216059. {
  216060. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  216061. }
  216062. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  216063. {
  216064. String cmdString (fileName.replace (" ", "\\ ",false));
  216065. cmdString << " " << parameters;
  216066. if (URL::isProbablyAWebsiteURL (fileName)
  216067. || cmdString.startsWithIgnoreCase ("file:")
  216068. || URL::isProbablyAnEmailAddress (fileName))
  216069. {
  216070. // create a command that tries to launch a bunch of likely browsers
  216071. const char* const browserNames[] = { "xdg-open", "/etc/alternatives/x-www-browser", "firefox", "mozilla", "konqueror", "opera" };
  216072. StringArray cmdLines;
  216073. for (int i = 0; i < numElementsInArray (browserNames); ++i)
  216074. cmdLines.add (String (browserNames[i]) + " " + cmdString.trim().quoted());
  216075. cmdString = cmdLines.joinIntoString (" || ");
  216076. }
  216077. const char* const argv[4] = { "/bin/sh", "-c", cmdString.toUTF8(), 0 };
  216078. const int cpid = fork();
  216079. if (cpid == 0)
  216080. {
  216081. setsid();
  216082. // Child process
  216083. execve (argv[0], (char**) argv, environ);
  216084. exit (0);
  216085. }
  216086. return cpid >= 0;
  216087. }
  216088. void File::revealToUser() const
  216089. {
  216090. if (isDirectory())
  216091. startAsProcess();
  216092. else if (getParentDirectory().exists())
  216093. getParentDirectory().startAsProcess();
  216094. }
  216095. #endif
  216096. /*** End of inlined file: juce_linux_Files.cpp ***/
  216097. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  216098. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  216099. // compiled on its own).
  216100. #if JUCE_INCLUDED_FILE
  216101. struct NamedPipeInternal
  216102. {
  216103. String pipeInName, pipeOutName;
  216104. int pipeIn, pipeOut;
  216105. bool volatile createdPipe, blocked, stopReadOperation;
  216106. static void signalHandler (int) {}
  216107. };
  216108. void NamedPipe::cancelPendingReads()
  216109. {
  216110. while (internal != 0 && ((NamedPipeInternal*) internal)->blocked)
  216111. {
  216112. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  216113. intern->stopReadOperation = true;
  216114. char buffer [1] = { 0 };
  216115. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  216116. (void) bytesWritten;
  216117. int timeout = 2000;
  216118. while (intern->blocked && --timeout >= 0)
  216119. Thread::sleep (2);
  216120. intern->stopReadOperation = false;
  216121. }
  216122. }
  216123. void NamedPipe::close()
  216124. {
  216125. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  216126. if (intern != 0)
  216127. {
  216128. internal = 0;
  216129. if (intern->pipeIn != -1)
  216130. ::close (intern->pipeIn);
  216131. if (intern->pipeOut != -1)
  216132. ::close (intern->pipeOut);
  216133. if (intern->createdPipe)
  216134. {
  216135. unlink (intern->pipeInName.toUTF8());
  216136. unlink (intern->pipeOutName.toUTF8());
  216137. }
  216138. delete intern;
  216139. }
  216140. }
  216141. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  216142. {
  216143. close();
  216144. NamedPipeInternal* const intern = new NamedPipeInternal();
  216145. internal = intern;
  216146. intern->createdPipe = createPipe;
  216147. intern->blocked = false;
  216148. intern->stopReadOperation = false;
  216149. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  216150. siginterrupt (SIGPIPE, 1);
  216151. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  216152. intern->pipeInName = pipePath + "_in";
  216153. intern->pipeOutName = pipePath + "_out";
  216154. intern->pipeIn = -1;
  216155. intern->pipeOut = -1;
  216156. if (createPipe)
  216157. {
  216158. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  216159. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  216160. {
  216161. delete intern;
  216162. internal = 0;
  216163. return false;
  216164. }
  216165. }
  216166. return true;
  216167. }
  216168. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  216169. {
  216170. int bytesRead = -1;
  216171. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  216172. if (intern != 0)
  216173. {
  216174. intern->blocked = true;
  216175. if (intern->pipeIn == -1)
  216176. {
  216177. if (intern->createdPipe)
  216178. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  216179. else
  216180. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  216181. if (intern->pipeIn == -1)
  216182. {
  216183. intern->blocked = false;
  216184. return -1;
  216185. }
  216186. }
  216187. bytesRead = 0;
  216188. char* p = (char*) destBuffer;
  216189. while (bytesRead < maxBytesToRead)
  216190. {
  216191. const int bytesThisTime = maxBytesToRead - bytesRead;
  216192. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  216193. if (numRead <= 0 || intern->stopReadOperation)
  216194. {
  216195. bytesRead = -1;
  216196. break;
  216197. }
  216198. bytesRead += numRead;
  216199. p += bytesRead;
  216200. }
  216201. intern->blocked = false;
  216202. }
  216203. return bytesRead;
  216204. }
  216205. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  216206. {
  216207. int bytesWritten = -1;
  216208. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  216209. if (intern != 0)
  216210. {
  216211. if (intern->pipeOut == -1)
  216212. {
  216213. if (intern->createdPipe)
  216214. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  216215. else
  216216. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  216217. if (intern->pipeOut == -1)
  216218. {
  216219. return -1;
  216220. }
  216221. }
  216222. const char* p = (const char*) sourceBuffer;
  216223. bytesWritten = 0;
  216224. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  216225. while (bytesWritten < numBytesToWrite
  216226. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  216227. {
  216228. const int bytesThisTime = numBytesToWrite - bytesWritten;
  216229. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  216230. if (numWritten <= 0)
  216231. {
  216232. bytesWritten = -1;
  216233. break;
  216234. }
  216235. bytesWritten += numWritten;
  216236. p += bytesWritten;
  216237. }
  216238. }
  216239. return bytesWritten;
  216240. }
  216241. #endif
  216242. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  216243. /*** Start of inlined file: juce_linux_Network.cpp ***/
  216244. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  216245. // compiled on its own).
  216246. #if JUCE_INCLUDED_FILE
  216247. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian)
  216248. {
  216249. int numResults = 0;
  216250. const int s = socket (AF_INET, SOCK_DGRAM, 0);
  216251. if (s != -1)
  216252. {
  216253. char buf [1024];
  216254. struct ifconf ifc;
  216255. ifc.ifc_len = sizeof (buf);
  216256. ifc.ifc_buf = buf;
  216257. ioctl (s, SIOCGIFCONF, &ifc);
  216258. for (unsigned int i = 0; i < ifc.ifc_len / sizeof (struct ifreq); ++i)
  216259. {
  216260. struct ifreq ifr;
  216261. strcpy (ifr.ifr_name, ifc.ifc_req[i].ifr_name);
  216262. if (ioctl (s, SIOCGIFFLAGS, &ifr) == 0
  216263. && (ifr.ifr_flags & IFF_LOOPBACK) == 0
  216264. && ioctl (s, SIOCGIFHWADDR, &ifr) == 0
  216265. && numResults < maxNum)
  216266. {
  216267. int64 a = 0;
  216268. for (int j = 6; --j >= 0;)
  216269. a = (a << 8) | (uint8) ifr.ifr_hwaddr.sa_data [littleEndian ? j : (5 - j)];
  216270. *addresses++ = a;
  216271. ++numResults;
  216272. }
  216273. }
  216274. close (s);
  216275. }
  216276. return numResults;
  216277. }
  216278. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  216279. const String& emailSubject,
  216280. const String& bodyText,
  216281. const StringArray& filesToAttach)
  216282. {
  216283. jassertfalse; // xxx todo
  216284. return false;
  216285. }
  216286. /** A HTTP input stream that uses sockets.
  216287. */
  216288. class JUCE_HTTPSocketStream
  216289. {
  216290. public:
  216291. JUCE_HTTPSocketStream()
  216292. : readPosition (0),
  216293. socketHandle (-1),
  216294. levelsOfRedirection (0),
  216295. timeoutSeconds (15)
  216296. {
  216297. }
  216298. ~JUCE_HTTPSocketStream()
  216299. {
  216300. closeSocket();
  216301. }
  216302. bool open (const String& url,
  216303. const String& headers,
  216304. const MemoryBlock& postData,
  216305. const bool isPost,
  216306. URL::OpenStreamProgressCallback* callback,
  216307. void* callbackContext,
  216308. int timeOutMs)
  216309. {
  216310. closeSocket();
  216311. uint32 timeOutTime = Time::getMillisecondCounter();
  216312. if (timeOutMs == 0)
  216313. timeOutTime += 60000;
  216314. else if (timeOutMs < 0)
  216315. timeOutTime = 0xffffffff;
  216316. else
  216317. timeOutTime += timeOutMs;
  216318. String hostName, hostPath;
  216319. int hostPort;
  216320. if (! decomposeURL (url, hostName, hostPath, hostPort))
  216321. return false;
  216322. const struct hostent* host = 0;
  216323. int port = 0;
  216324. String proxyName, proxyPath;
  216325. int proxyPort = 0;
  216326. String proxyURL (getenv ("http_proxy"));
  216327. if (proxyURL.startsWithIgnoreCase ("http://"))
  216328. {
  216329. if (! decomposeURL (proxyURL, proxyName, proxyPath, proxyPort))
  216330. return false;
  216331. host = gethostbyname (proxyName.toUTF8());
  216332. port = proxyPort;
  216333. }
  216334. else
  216335. {
  216336. host = gethostbyname (hostName.toUTF8());
  216337. port = hostPort;
  216338. }
  216339. if (host == 0)
  216340. return false;
  216341. struct sockaddr_in address;
  216342. zerostruct (address);
  216343. memcpy (&address.sin_addr, host->h_addr, host->h_length);
  216344. address.sin_family = host->h_addrtype;
  216345. address.sin_port = htons (port);
  216346. socketHandle = socket (host->h_addrtype, SOCK_STREAM, 0);
  216347. if (socketHandle == -1)
  216348. return false;
  216349. int receiveBufferSize = 16384;
  216350. setsockopt (socketHandle, SOL_SOCKET, SO_RCVBUF, (char*) &receiveBufferSize, sizeof (receiveBufferSize));
  216351. setsockopt (socketHandle, SOL_SOCKET, SO_KEEPALIVE, 0, 0);
  216352. #if JUCE_MAC
  216353. setsockopt (socketHandle, SOL_SOCKET, SO_NOSIGPIPE, 0, 0);
  216354. #endif
  216355. if (connect (socketHandle, (struct sockaddr*) &address, sizeof (address)) == -1)
  216356. {
  216357. closeSocket();
  216358. return false;
  216359. }
  216360. const MemoryBlock requestHeader (createRequestHeader (hostName, hostPort,
  216361. proxyName, proxyPort,
  216362. hostPath, url,
  216363. headers, postData,
  216364. isPost));
  216365. size_t totalHeaderSent = 0;
  216366. while (totalHeaderSent < requestHeader.getSize())
  216367. {
  216368. if (Time::getMillisecondCounter() > timeOutTime)
  216369. {
  216370. closeSocket();
  216371. return false;
  216372. }
  216373. const int numToSend = jmin (1024, (int) (requestHeader.getSize() - totalHeaderSent));
  216374. if (send (socketHandle,
  216375. ((const char*) requestHeader.getData()) + totalHeaderSent,
  216376. numToSend, 0)
  216377. != numToSend)
  216378. {
  216379. closeSocket();
  216380. return false;
  216381. }
  216382. totalHeaderSent += numToSend;
  216383. if (callback != 0 && ! callback (callbackContext, totalHeaderSent, requestHeader.getSize()))
  216384. {
  216385. closeSocket();
  216386. return false;
  216387. }
  216388. }
  216389. const String responseHeader (readResponse (timeOutTime));
  216390. if (responseHeader.isNotEmpty())
  216391. {
  216392. //DBG (responseHeader);
  216393. headerLines.clear();
  216394. headerLines.addLines (responseHeader);
  216395. const int statusCode = responseHeader.fromFirstOccurrenceOf (" ", false, false)
  216396. .substring (0, 3).getIntValue();
  216397. //int contentLength = findHeaderItem (lines, "Content-Length:").getIntValue();
  216398. //bool isChunked = findHeaderItem (lines, "Transfer-Encoding:").equalsIgnoreCase ("chunked");
  216399. String location (findHeaderItem (headerLines, "Location:"));
  216400. if (statusCode >= 300 && statusCode < 400
  216401. && location.isNotEmpty())
  216402. {
  216403. if (! location.startsWithIgnoreCase ("http://"))
  216404. location = "http://" + location;
  216405. if (levelsOfRedirection++ < 3)
  216406. return open (location, headers, postData, isPost, callback, callbackContext, timeOutMs);
  216407. }
  216408. else
  216409. {
  216410. levelsOfRedirection = 0;
  216411. return true;
  216412. }
  216413. }
  216414. closeSocket();
  216415. return false;
  216416. }
  216417. int read (void* buffer, int bytesToRead)
  216418. {
  216419. fd_set readbits;
  216420. FD_ZERO (&readbits);
  216421. FD_SET (socketHandle, &readbits);
  216422. struct timeval tv;
  216423. tv.tv_sec = timeoutSeconds;
  216424. tv.tv_usec = 0;
  216425. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  216426. return 0; // (timeout)
  216427. const int bytesRead = jmax (0, (int) recv (socketHandle, buffer, bytesToRead, MSG_WAITALL));
  216428. readPosition += bytesRead;
  216429. return bytesRead;
  216430. }
  216431. int readPosition;
  216432. StringArray headerLines;
  216433. juce_UseDebuggingNewOperator
  216434. private:
  216435. int socketHandle, levelsOfRedirection;
  216436. const int timeoutSeconds;
  216437. void closeSocket()
  216438. {
  216439. if (socketHandle >= 0)
  216440. close (socketHandle);
  216441. socketHandle = -1;
  216442. }
  216443. const MemoryBlock createRequestHeader (const String& hostName,
  216444. const int hostPort,
  216445. const String& proxyName,
  216446. const int proxyPort,
  216447. const String& hostPath,
  216448. const String& originalURL,
  216449. const String& headers,
  216450. const MemoryBlock& postData,
  216451. const bool isPost)
  216452. {
  216453. String header (isPost ? "POST " : "GET ");
  216454. if (proxyName.isEmpty())
  216455. {
  216456. header << hostPath << " HTTP/1.0\r\nHost: "
  216457. << hostName << ':' << hostPort;
  216458. }
  216459. else
  216460. {
  216461. header << originalURL << " HTTP/1.0\r\nHost: "
  216462. << proxyName << ':' << proxyPort;
  216463. }
  216464. header << "\r\nUser-Agent: JUCE/"
  216465. << JUCE_MAJOR_VERSION << '.' << JUCE_MINOR_VERSION
  216466. << "\r\nConnection: Close\r\nContent-Length: "
  216467. << postData.getSize() << "\r\n"
  216468. << headers << "\r\n";
  216469. MemoryBlock mb;
  216470. mb.append (header.toUTF8(), (int) strlen (header.toUTF8()));
  216471. mb.append (postData.getData(), postData.getSize());
  216472. return mb;
  216473. }
  216474. const String readResponse (const uint32 timeOutTime)
  216475. {
  216476. int bytesRead = 0, numConsecutiveLFs = 0;
  216477. MemoryBlock buffer (1024, true);
  216478. while (numConsecutiveLFs < 2 && bytesRead < 32768
  216479. && Time::getMillisecondCounter() <= timeOutTime)
  216480. {
  216481. fd_set readbits;
  216482. FD_ZERO (&readbits);
  216483. FD_SET (socketHandle, &readbits);
  216484. struct timeval tv;
  216485. tv.tv_sec = timeoutSeconds;
  216486. tv.tv_usec = 0;
  216487. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  216488. return String::empty; // (timeout)
  216489. buffer.ensureSize (bytesRead + 8, true);
  216490. char* const dest = (char*) buffer.getData() + bytesRead;
  216491. if (recv (socketHandle, dest, 1, 0) == -1)
  216492. return String::empty;
  216493. const char lastByte = *dest;
  216494. ++bytesRead;
  216495. if (lastByte == '\n')
  216496. ++numConsecutiveLFs;
  216497. else if (lastByte != '\r')
  216498. numConsecutiveLFs = 0;
  216499. }
  216500. const String header (String::fromUTF8 ((const char*) buffer.getData()));
  216501. if (header.startsWithIgnoreCase ("HTTP/"))
  216502. return header.trimEnd();
  216503. return String::empty;
  216504. }
  216505. static bool decomposeURL (const String& url,
  216506. String& host, String& path, int& port)
  216507. {
  216508. if (! url.startsWithIgnoreCase ("http://"))
  216509. return false;
  216510. const int nextSlash = url.indexOfChar (7, '/');
  216511. int nextColon = url.indexOfChar (7, ':');
  216512. if (nextColon > nextSlash && nextSlash > 0)
  216513. nextColon = -1;
  216514. if (nextColon >= 0)
  216515. {
  216516. host = url.substring (7, nextColon);
  216517. if (nextSlash >= 0)
  216518. port = url.substring (nextColon + 1, nextSlash).getIntValue();
  216519. else
  216520. port = url.substring (nextColon + 1).getIntValue();
  216521. }
  216522. else
  216523. {
  216524. port = 80;
  216525. if (nextSlash >= 0)
  216526. host = url.substring (7, nextSlash);
  216527. else
  216528. host = url.substring (7);
  216529. }
  216530. if (nextSlash >= 0)
  216531. path = url.substring (nextSlash);
  216532. else
  216533. path = "/";
  216534. return true;
  216535. }
  216536. static const String findHeaderItem (const StringArray& lines, const String& itemName)
  216537. {
  216538. for (int i = 0; i < lines.size(); ++i)
  216539. if (lines[i].startsWithIgnoreCase (itemName))
  216540. return lines[i].substring (itemName.length()).trim();
  216541. return String::empty;
  216542. }
  216543. };
  216544. void* juce_openInternetFile (const String& url,
  216545. const String& headers,
  216546. const MemoryBlock& postData,
  216547. const bool isPost,
  216548. URL::OpenStreamProgressCallback* callback,
  216549. void* callbackContext,
  216550. int timeOutMs)
  216551. {
  216552. ScopedPointer<JUCE_HTTPSocketStream> s (new JUCE_HTTPSocketStream());
  216553. if (s->open (url, headers, postData, isPost, callback, callbackContext, timeOutMs))
  216554. return s.release();
  216555. return 0;
  216556. }
  216557. void juce_closeInternetFile (void* handle)
  216558. {
  216559. delete static_cast <JUCE_HTTPSocketStream*> (handle);
  216560. }
  216561. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  216562. {
  216563. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  216564. return s != 0 ? s->read (buffer, bytesToRead) : 0;
  216565. }
  216566. int64 juce_getInternetFileContentLength (void* handle)
  216567. {
  216568. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  216569. if (s != 0)
  216570. {
  216571. //xxx todo
  216572. jassertfalse
  216573. }
  216574. return -1;
  216575. }
  216576. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers)
  216577. {
  216578. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  216579. if (s != 0)
  216580. {
  216581. for (int i = 0; i < s->headerLines.size(); ++i)
  216582. {
  216583. const String& headersEntry = s->headerLines[i];
  216584. const String key (headersEntry.upToFirstOccurrenceOf ("; ", false, false));
  216585. const String value (headersEntry.fromFirstOccurrenceOf ("; ", false, false));
  216586. const String previousValue (headers [key]);
  216587. headers.set (key, previousValue.isEmpty() ? value : (previousValue + "," + value));
  216588. }
  216589. }
  216590. }
  216591. int juce_seekInInternetFile (void* handle, int newPosition)
  216592. {
  216593. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  216594. return s != 0 ? s->readPosition : 0;
  216595. }
  216596. #endif
  216597. /*** End of inlined file: juce_linux_Network.cpp ***/
  216598. /*** Start of inlined file: juce_linux_SystemStats.cpp ***/
  216599. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  216600. // compiled on its own).
  216601. #if JUCE_INCLUDED_FILE
  216602. void Logger::outputDebugString (const String& text)
  216603. {
  216604. std::cerr << text << std::endl;
  216605. }
  216606. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  216607. {
  216608. return Linux;
  216609. }
  216610. const String SystemStats::getOperatingSystemName()
  216611. {
  216612. return "Linux";
  216613. }
  216614. bool SystemStats::isOperatingSystem64Bit()
  216615. {
  216616. #if JUCE_64BIT
  216617. return true;
  216618. #else
  216619. //xxx not sure how to find this out?..
  216620. return false;
  216621. #endif
  216622. }
  216623. static const String juce_getCpuInfo (const char* const key)
  216624. {
  216625. StringArray lines;
  216626. lines.addLines (File ("/proc/cpuinfo").loadFileAsString());
  216627. for (int i = lines.size(); --i >= 0;) // (NB - it's important that this runs in reverse order)
  216628. if (lines[i].startsWithIgnoreCase (key))
  216629. return lines[i].fromFirstOccurrenceOf (":", false, false).trim();
  216630. return String::empty;
  216631. }
  216632. bool SystemStats::hasMMX() { return juce_getCpuInfo ("flags").contains ("mmx"); }
  216633. bool SystemStats::hasSSE() { return juce_getCpuInfo ("flags").contains ("sse"); }
  216634. bool SystemStats::hasSSE2() { return juce_getCpuInfo ("flags").contains ("sse2"); }
  216635. bool SystemStats::has3DNow() { return juce_getCpuInfo ("flags").contains ("3dnow"); }
  216636. const String SystemStats::getCpuVendor()
  216637. {
  216638. return juce_getCpuInfo ("vendor_id");
  216639. }
  216640. int SystemStats::getCpuSpeedInMegaherz()
  216641. {
  216642. return roundToInt (juce_getCpuInfo ("cpu MHz").getFloatValue());
  216643. }
  216644. int SystemStats::getMemorySizeInMegabytes()
  216645. {
  216646. struct sysinfo sysi;
  216647. if (sysinfo (&sysi) == 0)
  216648. return (sysi.totalram * sysi.mem_unit / (1024 * 1024));
  216649. return 0;
  216650. }
  216651. int SystemStats::getPageSize()
  216652. {
  216653. return sysconf (_SC_PAGESIZE);
  216654. }
  216655. int SystemStats::getNumCpus()
  216656. {
  216657. return juce_getCpuInfo ("processor").getIntValue() + 1;
  216658. }
  216659. const String SystemStats::getLogonName()
  216660. {
  216661. const char* user = getenv ("USER");
  216662. if (user == 0)
  216663. {
  216664. struct passwd* const pw = getpwuid (getuid());
  216665. if (pw != 0)
  216666. user = pw->pw_name;
  216667. }
  216668. return String::fromUTF8 (user);
  216669. }
  216670. const String SystemStats::getFullUserName()
  216671. {
  216672. return getLogonName();
  216673. }
  216674. void SystemStats::initialiseStats()
  216675. {
  216676. }
  216677. void PlatformUtilities::fpuReset()
  216678. {
  216679. }
  216680. static bool juce_getTimeSinceStartup (timeval* const t) throw()
  216681. {
  216682. if (gettimeofday (t, 0) != 0)
  216683. return false;
  216684. static unsigned int calibrate = 0;
  216685. static bool calibrated = false;
  216686. if (! calibrated)
  216687. {
  216688. calibrated = true;
  216689. struct sysinfo sysi;
  216690. if (sysinfo (&sysi) == 0)
  216691. calibrate = t->tv_sec - sysi.uptime; // Safe to assume system was not brought up earlier than 1970!
  216692. }
  216693. t->tv_sec -= calibrate;
  216694. return true;
  216695. }
  216696. uint32 juce_millisecondsSinceStartup() throw()
  216697. {
  216698. timeval t;
  216699. if (juce_getTimeSinceStartup (&t))
  216700. return (uint32) (t.tv_sec * 1000 + (t.tv_usec / 1000));
  216701. return 0;
  216702. }
  216703. int64 Time::getHighResolutionTicks() throw()
  216704. {
  216705. timeval t;
  216706. if (juce_getTimeSinceStartup (&t))
  216707. return ((int64) t.tv_sec * (int64) 1000000) + (int64) t.tv_usec;
  216708. return 0;
  216709. }
  216710. int64 Time::getHighResolutionTicksPerSecond() throw()
  216711. {
  216712. return 1000000; // (microseconds)
  216713. }
  216714. double Time::getMillisecondCounterHiRes() throw()
  216715. {
  216716. return getHighResolutionTicks() * 0.001;
  216717. }
  216718. bool Time::setSystemTimeToThisTime() const
  216719. {
  216720. timeval t;
  216721. t.tv_sec = millisSinceEpoch % 1000000;
  216722. t.tv_usec = millisSinceEpoch - t.tv_sec;
  216723. return settimeofday (&t, 0) ? false : true;
  216724. }
  216725. #endif
  216726. /*** End of inlined file: juce_linux_SystemStats.cpp ***/
  216727. /*** Start of inlined file: juce_linux_Threads.cpp ***/
  216728. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  216729. // compiled on its own).
  216730. #if JUCE_INCLUDED_FILE
  216731. /*
  216732. Note that a lot of methods that you'd expect to find in this file actually
  216733. live in juce_posix_SharedCode.h!
  216734. */
  216735. void JUCE_API juce_threadEntryPoint (void*);
  216736. void* threadEntryProc (void* value)
  216737. {
  216738. juce_threadEntryPoint (value);
  216739. return 0;
  216740. }
  216741. void* juce_createThread (void* userData)
  216742. {
  216743. pthread_t handle = 0;
  216744. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  216745. {
  216746. pthread_detach (handle);
  216747. return (void*) handle;
  216748. }
  216749. return 0;
  216750. }
  216751. void juce_killThread (void* handle)
  216752. {
  216753. if (handle != 0)
  216754. pthread_cancel ((pthread_t) handle);
  216755. }
  216756. void juce_setCurrentThreadName (const String& /*name*/)
  216757. {
  216758. }
  216759. Thread::ThreadID Thread::getCurrentThreadId()
  216760. {
  216761. return (ThreadID) pthread_self();
  216762. }
  216763. /* This is all a bit non-ideal... the trouble is that on Linux you
  216764. need to call setpriority to affect the dynamic priority for
  216765. non-realtime processes, but this requires the pid, which is not
  216766. accessible from the pthread_t. We could get it by calling getpid
  216767. once each thread has started, but then we would need a list of
  216768. running threads etc etc.
  216769. Also there is no such thing as IDLE priority on Linux.
  216770. For the moment, map idle, low and normal process priorities to
  216771. SCHED_OTHER, with the thread priority ignored for these classes.
  216772. Map high priority processes to the lower half of the SCHED_RR
  216773. range, and realtime to the upper half.
  216774. priority 1 to 10 where 5=normal, 1=low. If the handle is 0, sets the
  216775. priority of the current thread
  216776. */
  216777. bool juce_setThreadPriority (void* handle, int priority)
  216778. {
  216779. struct sched_param param;
  216780. int policy;
  216781. if (handle == 0)
  216782. handle = (void*) pthread_self();
  216783. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) == 0
  216784. && policy != SCHED_OTHER)
  216785. {
  216786. int minp = sched_get_priority_min (policy);
  216787. int maxp = sched_get_priority_max (policy);
  216788. int pri = ((maxp - minp) / 2) * (priority - 1) / 9;
  216789. if (param.sched_priority >= (minp + (maxp - minp) / 2))
  216790. param.sched_priority = minp + ((maxp - minp) / 2) + pri; // (realtime)
  216791. else
  216792. param.sched_priority = minp + pri; // (high)
  216793. param.sched_priority = jlimit (1, 127, 1 + (priority * 126) / 11);
  216794. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  216795. }
  216796. return false;
  216797. }
  216798. /* Remove this macro if you're having problems compiling the cpu affinity
  216799. calls (the API for these has changed about quite a bit in various Linux
  216800. versions, and a lot of distros seem to ship with obsolete versions)
  216801. */
  216802. #if defined (CPU_ISSET) && ! defined (SUPPORT_AFFINITIES)
  216803. #define SUPPORT_AFFINITIES 1
  216804. #endif
  216805. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  216806. {
  216807. #if SUPPORT_AFFINITIES
  216808. cpu_set_t affinity;
  216809. CPU_ZERO (&affinity);
  216810. for (int i = 0; i < 32; ++i)
  216811. if ((affinityMask & (1 << i)) != 0)
  216812. CPU_SET (i, &affinity);
  216813. /*
  216814. N.B. If this line causes a compile error, then you've probably not got the latest
  216815. version of glibc installed.
  216816. If you don't want to update your copy of glibc and don't care about cpu affinities,
  216817. then you can just disable all this stuff by setting the SUPPORT_AFFINITIES macro to 0.
  216818. */
  216819. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  216820. sched_yield();
  216821. #else
  216822. /* affinities aren't supported because either the appropriate header files weren't found,
  216823. or the SUPPORT_AFFINITIES macro was turned off
  216824. */
  216825. jassertfalse;
  216826. #endif
  216827. }
  216828. void Thread::yield()
  216829. {
  216830. sched_yield();
  216831. }
  216832. // sets the process to 0=low priority, 1=normal, 2=high, 3=realtime
  216833. void Process::setPriority (ProcessPriority prior)
  216834. {
  216835. struct sched_param param;
  216836. int policy, maxp, minp;
  216837. const int p = (int) prior;
  216838. if (p <= 1)
  216839. policy = SCHED_OTHER;
  216840. else
  216841. policy = SCHED_RR;
  216842. minp = sched_get_priority_min (policy);
  216843. maxp = sched_get_priority_max (policy);
  216844. if (p < 2)
  216845. param.sched_priority = 0;
  216846. else if (p == 2 )
  216847. // Set to middle of lower realtime priority range
  216848. param.sched_priority = minp + (maxp - minp) / 4;
  216849. else
  216850. // Set to middle of higher realtime priority range
  216851. param.sched_priority = minp + (3 * (maxp - minp) / 4);
  216852. pthread_setschedparam (pthread_self(), policy, &param);
  216853. }
  216854. void Process::terminate()
  216855. {
  216856. exit (0);
  216857. }
  216858. bool JUCE_PUBLIC_FUNCTION juce_isRunningUnderDebugger()
  216859. {
  216860. static char testResult = 0;
  216861. if (testResult == 0)
  216862. {
  216863. testResult = (char) ptrace (PT_TRACE_ME, 0, 0, 0);
  216864. if (testResult >= 0)
  216865. {
  216866. ptrace (PT_DETACH, 0, (caddr_t) 1, 0);
  216867. testResult = 1;
  216868. }
  216869. }
  216870. return testResult < 0;
  216871. }
  216872. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  216873. {
  216874. return juce_isRunningUnderDebugger();
  216875. }
  216876. void Process::raisePrivilege()
  216877. {
  216878. // If running suid root, change effective user
  216879. // to root
  216880. if (geteuid() != 0 && getuid() == 0)
  216881. {
  216882. setreuid (geteuid(), getuid());
  216883. setregid (getegid(), getgid());
  216884. }
  216885. }
  216886. void Process::lowerPrivilege()
  216887. {
  216888. // If runing suid root, change effective user
  216889. // back to real user
  216890. if (geteuid() == 0 && getuid() != 0)
  216891. {
  216892. setreuid (geteuid(), getuid());
  216893. setregid (getegid(), getgid());
  216894. }
  216895. }
  216896. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  216897. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  216898. {
  216899. return dlopen (name.toUTF8(), RTLD_LOCAL | RTLD_NOW);
  216900. }
  216901. void PlatformUtilities::freeDynamicLibrary (void* handle)
  216902. {
  216903. dlclose(handle);
  216904. }
  216905. void* PlatformUtilities::getProcedureEntryPoint (void* libraryHandle, const String& procedureName)
  216906. {
  216907. return dlsym (libraryHandle, procedureName.toCString());
  216908. }
  216909. #endif
  216910. #endif
  216911. /*** End of inlined file: juce_linux_Threads.cpp ***/
  216912. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  216913. /*** Start of inlined file: juce_linux_Clipboard.cpp ***/
  216914. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  216915. // compiled on its own).
  216916. #if JUCE_INCLUDED_FILE
  216917. #if JUCE_DEBUG
  216918. #define JUCE_DEBUG_XERRORS 1
  216919. #endif
  216920. extern Display* display;
  216921. extern Window juce_messageWindowHandle;
  216922. namespace ClipboardHelpers
  216923. {
  216924. static String localClipboardContent;
  216925. static Atom atom_UTF8_STRING;
  216926. static Atom atom_CLIPBOARD;
  216927. static Atom atom_TARGETS;
  216928. static void initSelectionAtoms()
  216929. {
  216930. static bool isInitialised = false;
  216931. if (! isInitialised)
  216932. {
  216933. atom_UTF8_STRING = XInternAtom (display, "UTF8_STRING", False);
  216934. atom_CLIPBOARD = XInternAtom (display, "CLIPBOARD", False);
  216935. atom_TARGETS = XInternAtom (display, "TARGETS", False);
  216936. }
  216937. }
  216938. // Read the content of a window property as either a locale-dependent string or an utf8 string
  216939. // works only for strings shorter than 1000000 bytes
  216940. static String readWindowProperty (Window window, Atom prop, Atom fmt)
  216941. {
  216942. String returnData;
  216943. char* clipData;
  216944. Atom actualType;
  216945. int actualFormat;
  216946. unsigned long numItems, bytesLeft;
  216947. if (XGetWindowProperty (display, window, prop,
  216948. 0L /* offset */, 1000000 /* length (max) */, False,
  216949. AnyPropertyType /* format */,
  216950. &actualType, &actualFormat, &numItems, &bytesLeft,
  216951. (unsigned char**) &clipData) == Success)
  216952. {
  216953. if (actualType == atom_UTF8_STRING && actualFormat == 8)
  216954. returnData = String::fromUTF8 (clipData, numItems);
  216955. else if (actualType == XA_STRING && actualFormat == 8)
  216956. returnData = String (clipData, numItems);
  216957. if (clipData != 0)
  216958. XFree (clipData);
  216959. jassert (bytesLeft == 0 || numItems == 1000000);
  216960. }
  216961. XDeleteProperty (display, window, prop);
  216962. return returnData;
  216963. }
  216964. // Send a SelectionRequest to the window owning the selection and waits for its answer (with a timeout) */
  216965. static bool requestSelectionContent (String& selectionContent, Atom selection, Atom requestedFormat)
  216966. {
  216967. Atom property_name = XInternAtom (display, "JUCE_SEL", false);
  216968. // The selection owner will be asked to set the JUCE_SEL property on the
  216969. // juce_messageWindowHandle with the selection content
  216970. XConvertSelection (display, selection, requestedFormat, property_name,
  216971. juce_messageWindowHandle, CurrentTime);
  216972. int count = 50; // will wait at most for 200 ms
  216973. while (--count >= 0)
  216974. {
  216975. XEvent event;
  216976. if (XCheckTypedWindowEvent (display, juce_messageWindowHandle, SelectionNotify, &event))
  216977. {
  216978. if (event.xselection.property == property_name)
  216979. {
  216980. jassert (event.xselection.requestor == juce_messageWindowHandle);
  216981. selectionContent = readWindowProperty (event.xselection.requestor,
  216982. event.xselection.property,
  216983. requestedFormat);
  216984. return true;
  216985. }
  216986. else
  216987. {
  216988. return false; // the format we asked for was denied.. (event.xselection.property == None)
  216989. }
  216990. }
  216991. // not very elegant.. we could do a select() or something like that...
  216992. // however clipboard content requesting is inherently slow on x11, it
  216993. // often takes 50ms or more so...
  216994. Thread::sleep (4);
  216995. }
  216996. return false;
  216997. }
  216998. }
  216999. // Called from the event loop in juce_linux_Messaging in response to SelectionRequest events
  217000. void juce_handleSelectionRequest (XSelectionRequestEvent &evt)
  217001. {
  217002. ClipboardHelpers::initSelectionAtoms();
  217003. // the selection content is sent to the target window as a window property
  217004. XSelectionEvent reply;
  217005. reply.type = SelectionNotify;
  217006. reply.display = evt.display;
  217007. reply.requestor = evt.requestor;
  217008. reply.selection = evt.selection;
  217009. reply.target = evt.target;
  217010. reply.property = None; // == "fail"
  217011. reply.time = evt.time;
  217012. HeapBlock <char> data;
  217013. int propertyFormat = 0, numDataItems = 0;
  217014. if (evt.selection == XA_PRIMARY || evt.selection == ClipboardHelpers::atom_CLIPBOARD)
  217015. {
  217016. if (evt.target == XA_STRING)
  217017. {
  217018. // format data according to system locale
  217019. numDataItems = ClipboardHelpers::localClipboardContent.getNumBytesAsCString() + 1;
  217020. data.calloc (numDataItems + 1);
  217021. ClipboardHelpers::localClipboardContent.copyToCString (data, numDataItems);
  217022. propertyFormat = 8; // bits/item
  217023. }
  217024. else if (evt.target == ClipboardHelpers::atom_UTF8_STRING)
  217025. {
  217026. // translate to utf8
  217027. numDataItems = ClipboardHelpers::localClipboardContent.getNumBytesAsUTF8() + 1;
  217028. data.calloc (numDataItems + 1);
  217029. ClipboardHelpers::localClipboardContent.copyToUTF8 (data, numDataItems);
  217030. propertyFormat = 8; // bits/item
  217031. }
  217032. else if (evt.target == ClipboardHelpers::atom_TARGETS)
  217033. {
  217034. // another application wants to know what we are able to send
  217035. numDataItems = 2;
  217036. propertyFormat = 32; // atoms are 32-bit
  217037. data.calloc (numDataItems * 4);
  217038. Atom* atoms = reinterpret_cast<Atom*> (data.getData());
  217039. atoms[0] = ClipboardHelpers::atom_UTF8_STRING;
  217040. atoms[1] = XA_STRING;
  217041. }
  217042. }
  217043. else
  217044. {
  217045. DBG ("requested unsupported clipboard");
  217046. }
  217047. if (data != 0)
  217048. {
  217049. const int maxReasonableSelectionSize = 1000000;
  217050. // for very big chunks of data, we should use the "INCR" protocol , which is a pain in the *ss
  217051. if (evt.property != None && numDataItems < maxReasonableSelectionSize)
  217052. {
  217053. XChangeProperty (evt.display, evt.requestor,
  217054. evt.property, evt.target,
  217055. propertyFormat /* 8 or 32 */, PropModeReplace,
  217056. reinterpret_cast<const unsigned char*> (data.getData()), numDataItems);
  217057. reply.property = evt.property; // " == success"
  217058. }
  217059. }
  217060. XSendEvent (evt.display, evt.requestor, 0, NoEventMask, (XEvent*) &reply);
  217061. }
  217062. void SystemClipboard::copyTextToClipboard (const String& clipText)
  217063. {
  217064. ClipboardHelpers::initSelectionAtoms();
  217065. ClipboardHelpers::localClipboardContent = clipText;
  217066. XSetSelectionOwner (display, XA_PRIMARY, juce_messageWindowHandle, CurrentTime);
  217067. XSetSelectionOwner (display, ClipboardHelpers::atom_CLIPBOARD, juce_messageWindowHandle, CurrentTime);
  217068. }
  217069. const String SystemClipboard::getTextFromClipboard()
  217070. {
  217071. ClipboardHelpers::initSelectionAtoms();
  217072. /* 1) try to read from the "CLIPBOARD" selection first (the "high
  217073. level" clipboard that is supposed to be filled by ctrl-C
  217074. etc). When a clipboard manager is running, the content of this
  217075. selection is preserved even when the original selection owner
  217076. exits.
  217077. 2) and then try to read from "PRIMARY" selection (the "legacy" selection
  217078. filled by good old x11 apps such as xterm)
  217079. */
  217080. String content;
  217081. Atom selection = XA_PRIMARY;
  217082. Window selectionOwner = None;
  217083. if ((selectionOwner = XGetSelectionOwner (display, selection)) == None)
  217084. {
  217085. selection = ClipboardHelpers::atom_CLIPBOARD;
  217086. selectionOwner = XGetSelectionOwner (display, selection);
  217087. }
  217088. if (selectionOwner != None)
  217089. {
  217090. if (selectionOwner == juce_messageWindowHandle)
  217091. {
  217092. content = ClipboardHelpers::localClipboardContent;
  217093. }
  217094. else
  217095. {
  217096. // first try: we want an utf8 string
  217097. bool ok = ClipboardHelpers::requestSelectionContent (content, selection, ClipboardHelpers::atom_UTF8_STRING);
  217098. if (! ok)
  217099. {
  217100. // second chance, ask for a good old locale-dependent string ..
  217101. ok = ClipboardHelpers::requestSelectionContent (content, selection, XA_STRING);
  217102. }
  217103. }
  217104. }
  217105. return content;
  217106. }
  217107. #endif
  217108. /*** End of inlined file: juce_linux_Clipboard.cpp ***/
  217109. /*** Start of inlined file: juce_linux_Messaging.cpp ***/
  217110. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217111. // compiled on its own).
  217112. #if JUCE_INCLUDED_FILE
  217113. #if JUCE_DEBUG && ! defined (JUCE_DEBUG_XERRORS)
  217114. #define JUCE_DEBUG_XERRORS 1
  217115. #endif
  217116. Display* display = 0;
  217117. Window juce_messageWindowHandle = None;
  217118. XContext windowHandleXContext; // This is referenced from Windowing.cpp
  217119. extern void juce_windowMessageReceive (XEvent* event); // Defined in Windowing.cpp
  217120. extern void juce_handleSelectionRequest (XSelectionRequestEvent &evt); // Defined in Clipboard.cpp
  217121. ScopedXLock::ScopedXLock() { XLockDisplay (display); }
  217122. ScopedXLock::~ScopedXLock() { XUnlockDisplay (display); }
  217123. class InternalMessageQueue
  217124. {
  217125. public:
  217126. InternalMessageQueue()
  217127. : bytesInSocket (0),
  217128. totalEventCount (0)
  217129. {
  217130. int ret = ::socketpair (AF_LOCAL, SOCK_STREAM, 0, fd);
  217131. (void) ret; jassert (ret == 0);
  217132. //setNonBlocking (fd[0]);
  217133. //setNonBlocking (fd[1]);
  217134. }
  217135. ~InternalMessageQueue()
  217136. {
  217137. close (fd[0]);
  217138. close (fd[1]);
  217139. clearSingletonInstance();
  217140. }
  217141. void postMessage (Message* msg)
  217142. {
  217143. const int maxBytesInSocketQueue = 128;
  217144. ScopedLock sl (lock);
  217145. queue.add (msg);
  217146. if (bytesInSocket < maxBytesInSocketQueue)
  217147. {
  217148. ++bytesInSocket;
  217149. ScopedUnlock ul (lock);
  217150. const unsigned char x = 0xff;
  217151. size_t bytesWritten = write (fd[0], &x, 1);
  217152. (void) bytesWritten;
  217153. }
  217154. }
  217155. bool isEmpty() const
  217156. {
  217157. ScopedLock sl (lock);
  217158. return queue.size() == 0;
  217159. }
  217160. bool dispatchNextEvent()
  217161. {
  217162. // This alternates between giving priority to XEvents or internal messages,
  217163. // to keep everything running smoothly..
  217164. if ((++totalEventCount & 1) != 0)
  217165. return dispatchNextXEvent() || dispatchNextInternalMessage();
  217166. else
  217167. return dispatchNextInternalMessage() || dispatchNextXEvent();
  217168. }
  217169. // Wait for an event (either XEvent, or an internal Message)
  217170. bool sleepUntilEvent (const int timeoutMs)
  217171. {
  217172. if (! isEmpty())
  217173. return true;
  217174. if (display != 0)
  217175. {
  217176. ScopedXLock xlock;
  217177. if (XPending (display))
  217178. return true;
  217179. }
  217180. struct timeval tv;
  217181. tv.tv_sec = 0;
  217182. tv.tv_usec = timeoutMs * 1000;
  217183. int fd0 = getWaitHandle();
  217184. int fdmax = fd0;
  217185. fd_set readset;
  217186. FD_ZERO (&readset);
  217187. FD_SET (fd0, &readset);
  217188. if (display != 0)
  217189. {
  217190. ScopedXLock xlock;
  217191. int fd1 = XConnectionNumber (display);
  217192. FD_SET (fd1, &readset);
  217193. fdmax = jmax (fd0, fd1);
  217194. }
  217195. const int ret = select (fdmax + 1, &readset, 0, 0, &tv);
  217196. return (ret > 0); // ret <= 0 if error or timeout
  217197. }
  217198. struct MessageThreadFuncCall
  217199. {
  217200. enum { uniqueID = 0x73774623 };
  217201. MessageCallbackFunction* func;
  217202. void* parameter;
  217203. void* result;
  217204. CriticalSection lock;
  217205. WaitableEvent event;
  217206. };
  217207. juce_DeclareSingleton_SingleThreaded_Minimal (InternalMessageQueue);
  217208. private:
  217209. CriticalSection lock;
  217210. OwnedArray <Message> queue;
  217211. int fd[2];
  217212. int bytesInSocket;
  217213. int totalEventCount;
  217214. int getWaitHandle() const throw() { return fd[1]; }
  217215. static bool setNonBlocking (int handle)
  217216. {
  217217. int socketFlags = fcntl (handle, F_GETFL, 0);
  217218. if (socketFlags == -1)
  217219. return false;
  217220. socketFlags |= O_NONBLOCK;
  217221. return fcntl (handle, F_SETFL, socketFlags) == 0;
  217222. }
  217223. static bool dispatchNextXEvent()
  217224. {
  217225. if (display == 0)
  217226. return false;
  217227. XEvent evt;
  217228. {
  217229. ScopedXLock xlock;
  217230. if (! XPending (display))
  217231. return false;
  217232. XNextEvent (display, &evt);
  217233. }
  217234. if (evt.type == SelectionRequest && evt.xany.window == juce_messageWindowHandle)
  217235. juce_handleSelectionRequest (evt.xselectionrequest);
  217236. else if (evt.xany.window != juce_messageWindowHandle)
  217237. juce_windowMessageReceive (&evt);
  217238. return true;
  217239. }
  217240. Message* popNextMessage()
  217241. {
  217242. ScopedLock sl (lock);
  217243. if (bytesInSocket > 0)
  217244. {
  217245. --bytesInSocket;
  217246. ScopedUnlock ul (lock);
  217247. unsigned char x;
  217248. size_t numBytes = read (fd[1], &x, 1);
  217249. (void) numBytes;
  217250. }
  217251. Message* m = queue[0];
  217252. queue.remove (0, false /* deleteObject */);
  217253. return m;
  217254. }
  217255. bool dispatchNextInternalMessage()
  217256. {
  217257. ScopedPointer <Message> msg (popNextMessage());
  217258. if (msg == 0)
  217259. return false;
  217260. if (msg->intParameter1 == MessageThreadFuncCall::uniqueID)
  217261. {
  217262. // Handle callback message
  217263. MessageThreadFuncCall* const call = (MessageThreadFuncCall*) msg->pointerParameter;
  217264. call->result = (*(call->func)) (call->parameter);
  217265. call->event.signal();
  217266. }
  217267. else
  217268. {
  217269. // Handle "normal" messages
  217270. MessageManager::getInstance()->deliverMessage (msg.release());
  217271. }
  217272. return true;
  217273. }
  217274. };
  217275. juce_ImplementSingleton_SingleThreaded (InternalMessageQueue);
  217276. namespace LinuxErrorHandling
  217277. {
  217278. static bool errorOccurred = false;
  217279. static bool keyboardBreakOccurred = false;
  217280. static XErrorHandler oldErrorHandler = (XErrorHandler) 0;
  217281. static XIOErrorHandler oldIOErrorHandler = (XIOErrorHandler) 0;
  217282. // Usually happens when client-server connection is broken
  217283. static int ioErrorHandler (Display* display)
  217284. {
  217285. DBG ("ERROR: connection to X server broken.. terminating.");
  217286. errorOccurred = true;
  217287. if (JUCEApplication::getInstance() != 0)
  217288. MessageManager::getInstance()->stopDispatchLoop();
  217289. return 0;
  217290. }
  217291. // A protocol error has occurred
  217292. static int juce_XErrorHandler (Display* display, XErrorEvent* event)
  217293. {
  217294. #if JUCE_DEBUG_XERRORS
  217295. char errorStr[64] = { 0 };
  217296. char requestStr[64] = { 0 };
  217297. XGetErrorText (display, event->error_code, errorStr, 64);
  217298. XGetErrorDatabaseText (display, "XRequest", String (event->request_code).toCString(), "Unknown", requestStr, 64);
  217299. DBG ("ERROR: X returned " + String (errorStr) + " for operation " + String (requestStr));
  217300. #endif
  217301. return 0;
  217302. }
  217303. static void installXErrorHandlers()
  217304. {
  217305. oldIOErrorHandler = XSetIOErrorHandler (ioErrorHandler);
  217306. oldErrorHandler = XSetErrorHandler (juce_XErrorHandler);
  217307. }
  217308. static void removeXErrorHandlers()
  217309. {
  217310. XSetIOErrorHandler (oldIOErrorHandler);
  217311. oldIOErrorHandler = 0;
  217312. XSetErrorHandler (oldErrorHandler);
  217313. oldErrorHandler = 0;
  217314. }
  217315. static void keyboardBreakSignalHandler (int sig)
  217316. {
  217317. if (sig == SIGINT)
  217318. keyboardBreakOccurred = true;
  217319. }
  217320. static void installKeyboardBreakHandler()
  217321. {
  217322. struct sigaction saction;
  217323. sigset_t maskSet;
  217324. sigemptyset (&maskSet);
  217325. saction.sa_handler = keyboardBreakSignalHandler;
  217326. saction.sa_mask = maskSet;
  217327. saction.sa_flags = 0;
  217328. sigaction (SIGINT, &saction, 0);
  217329. }
  217330. }
  217331. void MessageManager::doPlatformSpecificInitialisation()
  217332. {
  217333. // Initialise xlib for multiple thread support
  217334. static bool initThreadCalled = false;
  217335. if (! initThreadCalled)
  217336. {
  217337. if (! XInitThreads())
  217338. {
  217339. // This is fatal! Print error and closedown
  217340. Logger::outputDebugString ("Failed to initialise xlib thread support.");
  217341. if (JUCEApplication::getInstance() != 0)
  217342. Process::terminate();
  217343. return;
  217344. }
  217345. initThreadCalled = true;
  217346. }
  217347. LinuxErrorHandling::installXErrorHandlers();
  217348. LinuxErrorHandling::installKeyboardBreakHandler();
  217349. // Create the internal message queue
  217350. InternalMessageQueue::getInstance();
  217351. // Try to connect to a display
  217352. String displayName (getenv ("DISPLAY"));
  217353. if (displayName.isEmpty())
  217354. displayName = ":0.0";
  217355. display = XOpenDisplay (displayName.toCString());
  217356. if (display != 0) // This is not fatal! we can run headless.
  217357. {
  217358. // Create a context to store user data associated with Windows we create in WindowDriver
  217359. windowHandleXContext = XUniqueContext();
  217360. // We're only interested in client messages for this window, which are always sent
  217361. XSetWindowAttributes swa;
  217362. swa.event_mask = NoEventMask;
  217363. // Create our message window (this will never be mapped)
  217364. const int screen = DefaultScreen (display);
  217365. juce_messageWindowHandle = XCreateWindow (display, RootWindow (display, screen),
  217366. 0, 0, 1, 1, 0, 0, InputOnly,
  217367. DefaultVisual (display, screen),
  217368. CWEventMask, &swa);
  217369. }
  217370. }
  217371. void MessageManager::doPlatformSpecificShutdown()
  217372. {
  217373. InternalMessageQueue::deleteInstance();
  217374. if (display != 0 && ! LinuxErrorHandling::errorOccurred)
  217375. {
  217376. XDestroyWindow (display, juce_messageWindowHandle);
  217377. XCloseDisplay (display);
  217378. juce_messageWindowHandle = 0;
  217379. display = 0;
  217380. LinuxErrorHandling::removeXErrorHandlers();
  217381. }
  217382. }
  217383. bool juce_postMessageToSystemQueue (void* message)
  217384. {
  217385. if (LinuxErrorHandling::errorOccurred)
  217386. return false;
  217387. InternalMessageQueue::getInstanceWithoutCreating()->postMessage ((Message*) message);
  217388. return true;
  217389. }
  217390. void MessageManager::broadcastMessage (const String& value) throw()
  217391. {
  217392. /* TODO */
  217393. }
  217394. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* func,
  217395. void* parameter)
  217396. {
  217397. if (LinuxErrorHandling::errorOccurred)
  217398. return 0;
  217399. if (isThisTheMessageThread())
  217400. return func (parameter);
  217401. InternalMessageQueue::MessageThreadFuncCall messageCallContext;
  217402. messageCallContext.func = func;
  217403. messageCallContext.parameter = parameter;
  217404. InternalMessageQueue::getInstanceWithoutCreating()
  217405. ->postMessage (new Message (InternalMessageQueue::MessageThreadFuncCall::uniqueID,
  217406. 0, 0, &messageCallContext));
  217407. // Wait for it to complete before continuing
  217408. messageCallContext.event.wait();
  217409. return messageCallContext.result;
  217410. }
  217411. // this function expects that it will NEVER be called simultaneously for two concurrent threads
  217412. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages)
  217413. {
  217414. while (! LinuxErrorHandling::errorOccurred)
  217415. {
  217416. if (LinuxErrorHandling::keyboardBreakOccurred)
  217417. {
  217418. LinuxErrorHandling::errorOccurred = true;
  217419. if (JUCEApplication::getInstance() != 0)
  217420. Process::terminate();
  217421. break;
  217422. }
  217423. if (InternalMessageQueue::getInstanceWithoutCreating()->dispatchNextEvent())
  217424. return true;
  217425. if (returnIfNoPendingMessages)
  217426. break;
  217427. InternalMessageQueue::getInstanceWithoutCreating()->sleepUntilEvent (2000);
  217428. }
  217429. return false;
  217430. }
  217431. #endif
  217432. /*** End of inlined file: juce_linux_Messaging.cpp ***/
  217433. /*** Start of inlined file: juce_linux_Fonts.cpp ***/
  217434. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217435. // compiled on its own).
  217436. #if JUCE_INCLUDED_FILE
  217437. class FreeTypeFontFace
  217438. {
  217439. public:
  217440. enum FontStyle
  217441. {
  217442. Plain = 0,
  217443. Bold = 1,
  217444. Italic = 2
  217445. };
  217446. FreeTypeFontFace (const String& familyName)
  217447. : hasSerif (false),
  217448. monospaced (false)
  217449. {
  217450. family = familyName;
  217451. }
  217452. void setFileName (const String& name, const int faceIndex, FontStyle style)
  217453. {
  217454. if (names [(int) style].fileName.isEmpty())
  217455. {
  217456. names [(int) style].fileName = name;
  217457. names [(int) style].faceIndex = faceIndex;
  217458. }
  217459. }
  217460. const String& getFamilyName() const throw() { return family; }
  217461. const String& getFileName (const int style, int& faceIndex) const throw()
  217462. {
  217463. faceIndex = names[style].faceIndex;
  217464. return names[style].fileName;
  217465. }
  217466. void setMonospaced (bool mono) throw() { monospaced = mono; }
  217467. bool getMonospaced() const throw() { return monospaced; }
  217468. void setSerif (const bool serif) throw() { hasSerif = serif; }
  217469. bool getSerif() const throw() { return hasSerif; }
  217470. private:
  217471. String family;
  217472. struct FontNameIndex
  217473. {
  217474. String fileName;
  217475. int faceIndex;
  217476. };
  217477. FontNameIndex names[4];
  217478. bool hasSerif, monospaced;
  217479. };
  217480. class FreeTypeInterface : public DeletedAtShutdown
  217481. {
  217482. public:
  217483. FreeTypeInterface()
  217484. : ftLib (0),
  217485. lastFace (0),
  217486. lastBold (false),
  217487. lastItalic (false)
  217488. {
  217489. if (FT_Init_FreeType (&ftLib) != 0)
  217490. {
  217491. ftLib = 0;
  217492. DBG ("Failed to initialize FreeType");
  217493. }
  217494. StringArray fontDirs;
  217495. fontDirs.addTokens (String::fromUTF8 (getenv ("JUCE_FONT_PATH")), ";,", String::empty);
  217496. fontDirs.removeEmptyStrings (true);
  217497. if (fontDirs.size() == 0)
  217498. {
  217499. XmlDocument fontsConfig (File ("/etc/fonts/fonts.conf"));
  217500. const ScopedPointer<XmlElement> fontsInfo (fontsConfig.getDocumentElement());
  217501. if (fontsInfo != 0)
  217502. {
  217503. forEachXmlChildElementWithTagName (*fontsInfo, e, "dir")
  217504. {
  217505. fontDirs.add (e->getAllSubText().trim());
  217506. }
  217507. }
  217508. }
  217509. if (fontDirs.size() == 0)
  217510. fontDirs.add ("/usr/X11R6/lib/X11/fonts");
  217511. for (int i = 0; i < fontDirs.size(); ++i)
  217512. enumerateFaces (fontDirs[i]);
  217513. }
  217514. ~FreeTypeInterface()
  217515. {
  217516. if (lastFace != 0)
  217517. FT_Done_Face (lastFace);
  217518. if (ftLib != 0)
  217519. FT_Done_FreeType (ftLib);
  217520. clearSingletonInstance();
  217521. }
  217522. FreeTypeFontFace* findOrCreate (const String& familyName, const bool create = false)
  217523. {
  217524. for (int i = 0; i < faces.size(); i++)
  217525. if (faces[i]->getFamilyName() == familyName)
  217526. return faces[i];
  217527. if (! create)
  217528. return 0;
  217529. FreeTypeFontFace* newFace = new FreeTypeFontFace (familyName);
  217530. faces.add (newFace);
  217531. return newFace;
  217532. }
  217533. // Enumerate all font faces available in a given directory
  217534. void enumerateFaces (const String& path)
  217535. {
  217536. File dirPath (path);
  217537. if (path.isEmpty() || ! dirPath.isDirectory())
  217538. return;
  217539. DirectoryIterator di (dirPath, true);
  217540. while (di.next())
  217541. {
  217542. File possible (di.getFile());
  217543. if (possible.hasFileExtension ("ttf")
  217544. || possible.hasFileExtension ("pfb")
  217545. || possible.hasFileExtension ("pcf"))
  217546. {
  217547. FT_Face face;
  217548. int faceIndex = 0;
  217549. int numFaces = 0;
  217550. do
  217551. {
  217552. if (FT_New_Face (ftLib, possible.getFullPathName().toUTF8(),
  217553. faceIndex, &face) == 0)
  217554. {
  217555. if (faceIndex == 0)
  217556. numFaces = face->num_faces;
  217557. if ((face->face_flags & FT_FACE_FLAG_SCALABLE) != 0)
  217558. {
  217559. FreeTypeFontFace* const newFace = findOrCreate (face->family_name, true);
  217560. int style = (int) FreeTypeFontFace::Plain;
  217561. if ((face->style_flags & FT_STYLE_FLAG_BOLD) != 0)
  217562. style |= (int) FreeTypeFontFace::Bold;
  217563. if ((face->style_flags & FT_STYLE_FLAG_ITALIC) != 0)
  217564. style |= (int) FreeTypeFontFace::Italic;
  217565. newFace->setFileName (possible.getFullPathName(), faceIndex, (FreeTypeFontFace::FontStyle) style);
  217566. newFace->setMonospaced ((face->face_flags & FT_FACE_FLAG_FIXED_WIDTH) != 0);
  217567. // Surely there must be a better way to do this?
  217568. const String name (face->family_name);
  217569. newFace->setSerif (! (name.containsIgnoreCase ("Sans")
  217570. || name.containsIgnoreCase ("Verdana")
  217571. || name.containsIgnoreCase ("Arial")));
  217572. }
  217573. FT_Done_Face (face);
  217574. }
  217575. ++faceIndex;
  217576. }
  217577. while (faceIndex < numFaces);
  217578. }
  217579. }
  217580. }
  217581. // Create a FreeType face object for a given font
  217582. FT_Face createFT_Face (const String& fontName, const bool bold, const bool italic)
  217583. {
  217584. FT_Face face = 0;
  217585. if (fontName == lastFontName && bold == lastBold && italic == lastItalic)
  217586. {
  217587. face = lastFace;
  217588. }
  217589. else
  217590. {
  217591. if (lastFace != 0)
  217592. {
  217593. FT_Done_Face (lastFace);
  217594. lastFace = 0;
  217595. }
  217596. lastFontName = fontName;
  217597. lastBold = bold;
  217598. lastItalic = italic;
  217599. FreeTypeFontFace* const ftFace = findOrCreate (fontName);
  217600. if (ftFace != 0)
  217601. {
  217602. int style = (int) FreeTypeFontFace::Plain;
  217603. if (bold)
  217604. style |= (int) FreeTypeFontFace::Bold;
  217605. if (italic)
  217606. style |= (int) FreeTypeFontFace::Italic;
  217607. int faceIndex;
  217608. String fileName (ftFace->getFileName (style, faceIndex));
  217609. if (fileName.isEmpty())
  217610. {
  217611. style ^= (int) FreeTypeFontFace::Bold;
  217612. fileName = ftFace->getFileName (style, faceIndex);
  217613. if (fileName.isEmpty())
  217614. {
  217615. style ^= (int) FreeTypeFontFace::Bold;
  217616. style ^= (int) FreeTypeFontFace::Italic;
  217617. fileName = ftFace->getFileName (style, faceIndex);
  217618. if (! fileName.length())
  217619. {
  217620. style ^= (int) FreeTypeFontFace::Bold;
  217621. fileName = ftFace->getFileName (style, faceIndex);
  217622. }
  217623. }
  217624. }
  217625. if (! FT_New_Face (ftLib, fileName.toUTF8(), faceIndex, &lastFace))
  217626. {
  217627. face = lastFace;
  217628. // If there isn't a unicode charmap then select the first one.
  217629. if (FT_Select_Charmap (face, ft_encoding_unicode))
  217630. FT_Set_Charmap (face, face->charmaps[0]);
  217631. }
  217632. }
  217633. }
  217634. return face;
  217635. }
  217636. bool addGlyph (FT_Face face, CustomTypeface& dest, uint32 character)
  217637. {
  217638. const unsigned int glyphIndex = FT_Get_Char_Index (face, character);
  217639. const float height = (float) (face->ascender - face->descender);
  217640. const float scaleX = 1.0f / height;
  217641. const float scaleY = -1.0f / height;
  217642. Path destShape;
  217643. if (FT_Load_Glyph (face, glyphIndex, FT_LOAD_NO_SCALE | FT_LOAD_NO_BITMAP | FT_LOAD_IGNORE_TRANSFORM) != 0
  217644. || face->glyph->format != ft_glyph_format_outline)
  217645. {
  217646. return false;
  217647. }
  217648. const FT_Outline* const outline = &face->glyph->outline;
  217649. const short* const contours = outline->contours;
  217650. const char* const tags = outline->tags;
  217651. FT_Vector* const points = outline->points;
  217652. for (int c = 0; c < outline->n_contours; c++)
  217653. {
  217654. const int startPoint = (c == 0) ? 0 : contours [c - 1] + 1;
  217655. const int endPoint = contours[c];
  217656. for (int p = startPoint; p <= endPoint; p++)
  217657. {
  217658. const float x = scaleX * points[p].x;
  217659. const float y = scaleY * points[p].y;
  217660. if (p == startPoint)
  217661. {
  217662. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  217663. {
  217664. float x2 = scaleX * points [endPoint].x;
  217665. float y2 = scaleY * points [endPoint].y;
  217666. if (FT_CURVE_TAG (tags[endPoint]) != FT_Curve_Tag_On)
  217667. {
  217668. x2 = (x + x2) * 0.5f;
  217669. y2 = (y + y2) * 0.5f;
  217670. }
  217671. destShape.startNewSubPath (x2, y2);
  217672. }
  217673. else
  217674. {
  217675. destShape.startNewSubPath (x, y);
  217676. }
  217677. }
  217678. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_On)
  217679. {
  217680. if (p != startPoint)
  217681. destShape.lineTo (x, y);
  217682. }
  217683. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  217684. {
  217685. const int nextIndex = (p == endPoint) ? startPoint : p + 1;
  217686. float x2 = scaleX * points [nextIndex].x;
  217687. float y2 = scaleY * points [nextIndex].y;
  217688. if (FT_CURVE_TAG (tags [nextIndex]) == FT_Curve_Tag_Conic)
  217689. {
  217690. x2 = (x + x2) * 0.5f;
  217691. y2 = (y + y2) * 0.5f;
  217692. }
  217693. else
  217694. {
  217695. ++p;
  217696. }
  217697. destShape.quadraticTo (x, y, x2, y2);
  217698. }
  217699. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Cubic)
  217700. {
  217701. if (p >= endPoint)
  217702. return false;
  217703. const int next1 = p + 1;
  217704. const int next2 = (p == (endPoint - 1)) ? startPoint : p + 2;
  217705. const float x2 = scaleX * points [next1].x;
  217706. const float y2 = scaleY * points [next1].y;
  217707. const float x3 = scaleX * points [next2].x;
  217708. const float y3 = scaleY * points [next2].y;
  217709. if (FT_CURVE_TAG (tags[next1]) != FT_Curve_Tag_Cubic
  217710. || FT_CURVE_TAG (tags[next2]) != FT_Curve_Tag_On)
  217711. return false;
  217712. destShape.cubicTo (x, y, x2, y2, x3, y3);
  217713. p += 2;
  217714. }
  217715. }
  217716. destShape.closeSubPath();
  217717. }
  217718. dest.addGlyph (character, destShape, face->glyph->metrics.horiAdvance / height);
  217719. if ((face->face_flags & FT_FACE_FLAG_KERNING) != 0)
  217720. addKerning (face, dest, character, glyphIndex);
  217721. return true;
  217722. }
  217723. void addKerning (FT_Face face, CustomTypeface& dest, const uint32 character, const uint32 glyphIndex)
  217724. {
  217725. const float height = (float) (face->ascender - face->descender);
  217726. uint32 rightGlyphIndex;
  217727. uint32 rightCharCode = FT_Get_First_Char (face, &rightGlyphIndex);
  217728. while (rightGlyphIndex != 0)
  217729. {
  217730. FT_Vector kerning;
  217731. if (FT_Get_Kerning (face, glyphIndex, rightGlyphIndex, ft_kerning_unscaled, &kerning) == 0)
  217732. {
  217733. if (kerning.x != 0)
  217734. dest.addKerningPair (character, rightCharCode, kerning.x / height);
  217735. }
  217736. rightCharCode = FT_Get_Next_Char (face, rightCharCode, &rightGlyphIndex);
  217737. }
  217738. }
  217739. // Add a glyph to a font
  217740. bool addGlyphToFont (const uint32 character, const String& fontName,
  217741. bool bold, bool italic, CustomTypeface& dest)
  217742. {
  217743. FT_Face face = createFT_Face (fontName, bold, italic);
  217744. return face != 0 && addGlyph (face, dest, character);
  217745. }
  217746. void getFamilyNames (StringArray& familyNames) const
  217747. {
  217748. for (int i = 0; i < faces.size(); i++)
  217749. familyNames.add (faces[i]->getFamilyName());
  217750. }
  217751. void getMonospacedNames (StringArray& monoSpaced) const
  217752. {
  217753. for (int i = 0; i < faces.size(); i++)
  217754. if (faces[i]->getMonospaced())
  217755. monoSpaced.add (faces[i]->getFamilyName());
  217756. }
  217757. void getSerifNames (StringArray& serif) const
  217758. {
  217759. for (int i = 0; i < faces.size(); i++)
  217760. if (faces[i]->getSerif())
  217761. serif.add (faces[i]->getFamilyName());
  217762. }
  217763. void getSansSerifNames (StringArray& sansSerif) const
  217764. {
  217765. for (int i = 0; i < faces.size(); i++)
  217766. if (! faces[i]->getSerif())
  217767. sansSerif.add (faces[i]->getFamilyName());
  217768. }
  217769. juce_DeclareSingleton_SingleThreaded_Minimal (FreeTypeInterface)
  217770. private:
  217771. FT_Library ftLib;
  217772. FT_Face lastFace;
  217773. String lastFontName;
  217774. bool lastBold, lastItalic;
  217775. OwnedArray<FreeTypeFontFace> faces;
  217776. };
  217777. juce_ImplementSingleton_SingleThreaded (FreeTypeInterface)
  217778. class FreetypeTypeface : public CustomTypeface
  217779. {
  217780. public:
  217781. FreetypeTypeface (const Font& font)
  217782. {
  217783. FT_Face face = FreeTypeInterface::getInstance()
  217784. ->createFT_Face (font.getTypefaceName(), font.isBold(), font.isItalic());
  217785. if (face == 0)
  217786. {
  217787. #if JUCE_DEBUG
  217788. String msg ("Failed to create typeface: ");
  217789. msg << font.getTypefaceName() << " " << (font.isBold() ? 'B' : ' ') << (font.isItalic() ? 'I' : ' ');
  217790. DBG (msg);
  217791. #endif
  217792. }
  217793. else
  217794. {
  217795. setCharacteristics (font.getTypefaceName(),
  217796. face->ascender / (float) (face->ascender - face->descender),
  217797. font.isBold(), font.isItalic(),
  217798. L' ');
  217799. }
  217800. }
  217801. bool loadGlyphIfPossible (juce_wchar character)
  217802. {
  217803. return FreeTypeInterface::getInstance()
  217804. ->addGlyphToFont (character, name, isBold, isItalic, *this);
  217805. }
  217806. };
  217807. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  217808. {
  217809. return new FreetypeTypeface (font);
  217810. }
  217811. const StringArray Font::findAllTypefaceNames()
  217812. {
  217813. StringArray s;
  217814. FreeTypeInterface::getInstance()->getFamilyNames (s);
  217815. s.sort (true);
  217816. return s;
  217817. }
  217818. static const String pickBestFont (const StringArray& names,
  217819. const char* const choicesString)
  217820. {
  217821. StringArray choices;
  217822. choices.addTokens (String (choicesString), ",", String::empty);
  217823. choices.trim();
  217824. choices.removeEmptyStrings();
  217825. int i, j;
  217826. for (j = 0; j < choices.size(); ++j)
  217827. if (names.contains (choices[j], true))
  217828. return choices[j];
  217829. for (j = 0; j < choices.size(); ++j)
  217830. for (i = 0; i < names.size(); i++)
  217831. if (names[i].startsWithIgnoreCase (choices[j]))
  217832. return names[i];
  217833. for (j = 0; j < choices.size(); ++j)
  217834. for (i = 0; i < names.size(); i++)
  217835. if (names[i].containsIgnoreCase (choices[j]))
  217836. return names[i];
  217837. return names[0];
  217838. }
  217839. static const String linux_getDefaultSansSerifFontName()
  217840. {
  217841. StringArray allFonts;
  217842. FreeTypeInterface::getInstance()->getSansSerifNames (allFonts);
  217843. return pickBestFont (allFonts, "Verdana, Bitstream Vera Sans, Luxi Sans, Sans");
  217844. }
  217845. static const String linux_getDefaultSerifFontName()
  217846. {
  217847. StringArray allFonts;
  217848. FreeTypeInterface::getInstance()->getSerifNames (allFonts);
  217849. return pickBestFont (allFonts, "Bitstream Vera Serif, Times, Nimbus Roman, Serif");
  217850. }
  217851. static const String linux_getDefaultMonospacedFontName()
  217852. {
  217853. StringArray allFonts;
  217854. FreeTypeInterface::getInstance()->getMonospacedNames (allFonts);
  217855. return pickBestFont (allFonts, "Bitstream Vera Sans Mono, Courier, Sans Mono, Mono");
  217856. }
  217857. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  217858. {
  217859. defaultSans = linux_getDefaultSansSerifFontName();
  217860. defaultSerif = linux_getDefaultSerifFontName();
  217861. defaultFixed = linux_getDefaultMonospacedFontName();
  217862. }
  217863. #endif
  217864. /*** End of inlined file: juce_linux_Fonts.cpp ***/
  217865. /*** Start of inlined file: juce_linux_Windowing.cpp ***/
  217866. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217867. // compiled on its own).
  217868. #if JUCE_INCLUDED_FILE
  217869. // These are defined in juce_linux_Messaging.cpp
  217870. extern Display* display;
  217871. extern XContext windowHandleXContext;
  217872. namespace Atoms
  217873. {
  217874. enum ProtocolItems
  217875. {
  217876. TAKE_FOCUS = 0,
  217877. DELETE_WINDOW = 1,
  217878. PING = 2
  217879. };
  217880. static Atom Protocols, ProtocolList[3], ChangeState, State,
  217881. ActiveWin, Pid, WindowType, WindowState,
  217882. XdndAware, XdndEnter, XdndLeave, XdndPosition, XdndStatus,
  217883. XdndDrop, XdndFinished, XdndSelection, XdndTypeList, XdndActionList,
  217884. XdndActionDescription, XdndActionCopy,
  217885. allowedActions[5],
  217886. allowedMimeTypes[2];
  217887. const unsigned long DndVersion = 3;
  217888. static void initialiseAtoms()
  217889. {
  217890. static bool atomsInitialised = false;
  217891. if (! atomsInitialised)
  217892. {
  217893. atomsInitialised = true;
  217894. Protocols = XInternAtom (display, "WM_PROTOCOLS", True);
  217895. ProtocolList [TAKE_FOCUS] = XInternAtom (display, "WM_TAKE_FOCUS", True);
  217896. ProtocolList [DELETE_WINDOW] = XInternAtom (display, "WM_DELETE_WINDOW", True);
  217897. ProtocolList [PING] = XInternAtom (display, "_NET_WM_PING", True);
  217898. ChangeState = XInternAtom (display, "WM_CHANGE_STATE", True);
  217899. State = XInternAtom (display, "WM_STATE", True);
  217900. ActiveWin = XInternAtom (display, "_NET_ACTIVE_WINDOW", False);
  217901. Pid = XInternAtom (display, "_NET_WM_PID", False);
  217902. WindowType = XInternAtom (display, "_NET_WM_WINDOW_TYPE", True);
  217903. WindowState = XInternAtom (display, "_NET_WM_STATE", True);
  217904. XdndAware = XInternAtom (display, "XdndAware", False);
  217905. XdndEnter = XInternAtom (display, "XdndEnter", False);
  217906. XdndLeave = XInternAtom (display, "XdndLeave", False);
  217907. XdndPosition = XInternAtom (display, "XdndPosition", False);
  217908. XdndStatus = XInternAtom (display, "XdndStatus", False);
  217909. XdndDrop = XInternAtom (display, "XdndDrop", False);
  217910. XdndFinished = XInternAtom (display, "XdndFinished", False);
  217911. XdndSelection = XInternAtom (display, "XdndSelection", False);
  217912. XdndTypeList = XInternAtom (display, "XdndTypeList", False);
  217913. XdndActionList = XInternAtom (display, "XdndActionList", False);
  217914. XdndActionCopy = XInternAtom (display, "XdndActionCopy", False);
  217915. XdndActionDescription = XInternAtom (display, "XdndActionDescription", False);
  217916. allowedMimeTypes[0] = XInternAtom (display, "text/plain", False);
  217917. allowedMimeTypes[1] = XInternAtom (display, "text/uri-list", False);
  217918. allowedActions[0] = XInternAtom (display, "XdndActionMove", False);
  217919. allowedActions[1] = XdndActionCopy;
  217920. allowedActions[2] = XInternAtom (display, "XdndActionLink", False);
  217921. allowedActions[3] = XInternAtom (display, "XdndActionAsk", False);
  217922. allowedActions[4] = XInternAtom (display, "XdndActionPrivate", False);
  217923. }
  217924. }
  217925. }
  217926. namespace Keys
  217927. {
  217928. enum MouseButtons
  217929. {
  217930. NoButton = 0,
  217931. LeftButton = 1,
  217932. MiddleButton = 2,
  217933. RightButton = 3,
  217934. WheelUp = 4,
  217935. WheelDown = 5
  217936. };
  217937. static int AltMask = 0;
  217938. static int NumLockMask = 0;
  217939. static bool numLock = false;
  217940. static bool capsLock = false;
  217941. static char keyStates [32];
  217942. static const int extendedKeyModifier = 0x10000000;
  217943. }
  217944. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  217945. {
  217946. int keysym;
  217947. if (keyCode & Keys::extendedKeyModifier)
  217948. {
  217949. keysym = 0xff00 | (keyCode & 0xff);
  217950. }
  217951. else
  217952. {
  217953. keysym = keyCode;
  217954. if (keysym == (XK_Tab & 0xff)
  217955. || keysym == (XK_Return & 0xff)
  217956. || keysym == (XK_Escape & 0xff)
  217957. || keysym == (XK_BackSpace & 0xff))
  217958. {
  217959. keysym |= 0xff00;
  217960. }
  217961. }
  217962. ScopedXLock xlock;
  217963. const int keycode = XKeysymToKeycode (display, keysym);
  217964. const int keybyte = keycode >> 3;
  217965. const int keybit = (1 << (keycode & 7));
  217966. return (Keys::keyStates [keybyte] & keybit) != 0;
  217967. }
  217968. #if JUCE_USE_XSHM
  217969. namespace XSHMHelpers
  217970. {
  217971. static int trappedErrorCode = 0;
  217972. extern "C" int errorTrapHandler (Display*, XErrorEvent* err)
  217973. {
  217974. trappedErrorCode = err->error_code;
  217975. return 0;
  217976. }
  217977. static bool isShmAvailable() throw()
  217978. {
  217979. static bool isChecked = false;
  217980. static bool isAvailable = false;
  217981. if (! isChecked)
  217982. {
  217983. isChecked = true;
  217984. int major, minor;
  217985. Bool pixmaps;
  217986. ScopedXLock xlock;
  217987. if (XShmQueryVersion (display, &major, &minor, &pixmaps))
  217988. {
  217989. trappedErrorCode = 0;
  217990. XErrorHandler oldHandler = XSetErrorHandler (errorTrapHandler);
  217991. XShmSegmentInfo segmentInfo;
  217992. zerostruct (segmentInfo);
  217993. XImage* xImage = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  217994. 24, ZPixmap, 0, &segmentInfo, 50, 50);
  217995. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  217996. xImage->bytes_per_line * xImage->height,
  217997. IPC_CREAT | 0777)) >= 0)
  217998. {
  217999. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  218000. if (segmentInfo.shmaddr != (void*) -1)
  218001. {
  218002. segmentInfo.readOnly = False;
  218003. xImage->data = segmentInfo.shmaddr;
  218004. XSync (display, False);
  218005. if (XShmAttach (display, &segmentInfo) != 0)
  218006. {
  218007. XSync (display, False);
  218008. XShmDetach (display, &segmentInfo);
  218009. isAvailable = true;
  218010. }
  218011. }
  218012. XFlush (display);
  218013. XDestroyImage (xImage);
  218014. shmdt (segmentInfo.shmaddr);
  218015. }
  218016. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  218017. XSetErrorHandler (oldHandler);
  218018. if (trappedErrorCode != 0)
  218019. isAvailable = false;
  218020. }
  218021. }
  218022. return isAvailable;
  218023. }
  218024. }
  218025. #endif
  218026. #if JUCE_USE_XRENDER
  218027. namespace XRender
  218028. {
  218029. typedef Status (*tXRenderQueryVersion) (Display*, int*, int*);
  218030. typedef XRenderPictFormat* (*tXrenderFindStandardFormat) (Display*, int);
  218031. typedef XRenderPictFormat* (*tXRenderFindFormat) (Display*, unsigned long, XRenderPictFormat*, int);
  218032. typedef XRenderPictFormat* (*tXRenderFindVisualFormat) (Display*, Visual*);
  218033. static tXRenderQueryVersion xRenderQueryVersion = 0;
  218034. static tXrenderFindStandardFormat xRenderFindStandardFormat = 0;
  218035. static tXRenderFindFormat xRenderFindFormat = 0;
  218036. static tXRenderFindVisualFormat xRenderFindVisualFormat = 0;
  218037. static bool isAvailable()
  218038. {
  218039. static bool hasLoaded = false;
  218040. if (! hasLoaded)
  218041. {
  218042. ScopedXLock xlock;
  218043. hasLoaded = true;
  218044. void* h = dlopen ("libXrender.so", RTLD_GLOBAL | RTLD_NOW);
  218045. if (h != 0)
  218046. {
  218047. xRenderQueryVersion = (tXRenderQueryVersion) dlsym (h, "XRenderQueryVersion");
  218048. xRenderFindStandardFormat = (tXrenderFindStandardFormat) dlsym (h, "XrenderFindStandardFormat");
  218049. xRenderFindFormat = (tXRenderFindFormat) dlsym (h, "XRenderFindFormat");
  218050. xRenderFindVisualFormat = (tXRenderFindVisualFormat) dlsym (h, "XRenderFindVisualFormat");
  218051. }
  218052. if (xRenderQueryVersion != 0
  218053. && xRenderFindStandardFormat != 0
  218054. && xRenderFindFormat != 0
  218055. && xRenderFindVisualFormat != 0)
  218056. {
  218057. int major, minor;
  218058. if (xRenderQueryVersion (display, &major, &minor))
  218059. return true;
  218060. }
  218061. xRenderQueryVersion = 0;
  218062. }
  218063. return xRenderQueryVersion != 0;
  218064. }
  218065. static XRenderPictFormat* findPictureFormat()
  218066. {
  218067. ScopedXLock xlock;
  218068. XRenderPictFormat* pictFormat = 0;
  218069. if (isAvailable())
  218070. {
  218071. pictFormat = xRenderFindStandardFormat (display, PictStandardARGB32);
  218072. if (pictFormat == 0)
  218073. {
  218074. XRenderPictFormat desiredFormat;
  218075. desiredFormat.type = PictTypeDirect;
  218076. desiredFormat.depth = 32;
  218077. desiredFormat.direct.alphaMask = 0xff;
  218078. desiredFormat.direct.redMask = 0xff;
  218079. desiredFormat.direct.greenMask = 0xff;
  218080. desiredFormat.direct.blueMask = 0xff;
  218081. desiredFormat.direct.alpha = 24;
  218082. desiredFormat.direct.red = 16;
  218083. desiredFormat.direct.green = 8;
  218084. desiredFormat.direct.blue = 0;
  218085. pictFormat = xRenderFindFormat (display,
  218086. PictFormatType | PictFormatDepth
  218087. | PictFormatRedMask | PictFormatRed
  218088. | PictFormatGreenMask | PictFormatGreen
  218089. | PictFormatBlueMask | PictFormatBlue
  218090. | PictFormatAlphaMask | PictFormatAlpha,
  218091. &desiredFormat,
  218092. 0);
  218093. }
  218094. }
  218095. return pictFormat;
  218096. }
  218097. }
  218098. #endif
  218099. namespace Visuals
  218100. {
  218101. static Visual* findVisualWithDepth (const int desiredDepth) throw()
  218102. {
  218103. ScopedXLock xlock;
  218104. Visual* visual = 0;
  218105. int numVisuals = 0;
  218106. long desiredMask = VisualNoMask;
  218107. XVisualInfo desiredVisual;
  218108. desiredVisual.screen = DefaultScreen (display);
  218109. desiredVisual.depth = desiredDepth;
  218110. desiredMask = VisualScreenMask | VisualDepthMask;
  218111. if (desiredDepth == 32)
  218112. {
  218113. desiredVisual.c_class = TrueColor;
  218114. desiredVisual.red_mask = 0x00FF0000;
  218115. desiredVisual.green_mask = 0x0000FF00;
  218116. desiredVisual.blue_mask = 0x000000FF;
  218117. desiredVisual.bits_per_rgb = 8;
  218118. desiredMask |= VisualClassMask;
  218119. desiredMask |= VisualRedMaskMask;
  218120. desiredMask |= VisualGreenMaskMask;
  218121. desiredMask |= VisualBlueMaskMask;
  218122. desiredMask |= VisualBitsPerRGBMask;
  218123. }
  218124. XVisualInfo* xvinfos = XGetVisualInfo (display,
  218125. desiredMask,
  218126. &desiredVisual,
  218127. &numVisuals);
  218128. if (xvinfos != 0)
  218129. {
  218130. for (int i = 0; i < numVisuals; i++)
  218131. {
  218132. if (xvinfos[i].depth == desiredDepth)
  218133. {
  218134. visual = xvinfos[i].visual;
  218135. break;
  218136. }
  218137. }
  218138. XFree (xvinfos);
  218139. }
  218140. return visual;
  218141. }
  218142. static Visual* findVisualFormat (const int desiredDepth, int& matchedDepth) throw()
  218143. {
  218144. Visual* visual = 0;
  218145. if (desiredDepth == 32)
  218146. {
  218147. #if JUCE_USE_XSHM
  218148. if (XSHMHelpers::isShmAvailable())
  218149. {
  218150. #if JUCE_USE_XRENDER
  218151. if (XRender::isAvailable())
  218152. {
  218153. XRenderPictFormat* pictFormat = XRender::findPictureFormat();
  218154. if (pictFormat != 0)
  218155. {
  218156. int numVisuals = 0;
  218157. XVisualInfo desiredVisual;
  218158. desiredVisual.screen = DefaultScreen (display);
  218159. desiredVisual.depth = 32;
  218160. desiredVisual.bits_per_rgb = 8;
  218161. XVisualInfo* xvinfos = XGetVisualInfo (display,
  218162. VisualScreenMask | VisualDepthMask | VisualBitsPerRGBMask,
  218163. &desiredVisual, &numVisuals);
  218164. if (xvinfos != 0)
  218165. {
  218166. for (int i = 0; i < numVisuals; ++i)
  218167. {
  218168. XRenderPictFormat* pictVisualFormat = XRender::xRenderFindVisualFormat (display, xvinfos[i].visual);
  218169. if (pictVisualFormat != 0
  218170. && pictVisualFormat->type == PictTypeDirect
  218171. && pictVisualFormat->direct.alphaMask)
  218172. {
  218173. visual = xvinfos[i].visual;
  218174. matchedDepth = 32;
  218175. break;
  218176. }
  218177. }
  218178. XFree (xvinfos);
  218179. }
  218180. }
  218181. }
  218182. #endif
  218183. if (visual == 0)
  218184. {
  218185. visual = findVisualWithDepth (32);
  218186. if (visual != 0)
  218187. matchedDepth = 32;
  218188. }
  218189. }
  218190. #endif
  218191. }
  218192. if (visual == 0 && desiredDepth >= 24)
  218193. {
  218194. visual = findVisualWithDepth (24);
  218195. if (visual != 0)
  218196. matchedDepth = 24;
  218197. }
  218198. if (visual == 0 && desiredDepth >= 16)
  218199. {
  218200. visual = findVisualWithDepth (16);
  218201. if (visual != 0)
  218202. matchedDepth = 16;
  218203. }
  218204. return visual;
  218205. }
  218206. }
  218207. class XBitmapImage : public Image::SharedImage
  218208. {
  218209. public:
  218210. XBitmapImage (const Image::PixelFormat format_, const int w, const int h,
  218211. const bool clearImage, const int imageDepth_, Visual* visual)
  218212. : Image::SharedImage (format_, w, h),
  218213. imageDepth (imageDepth_),
  218214. gc (None)
  218215. {
  218216. jassert (format_ == Image::RGB || format_ == Image::ARGB);
  218217. pixelStride = (format_ == Image::RGB) ? 3 : 4;
  218218. lineStride = ((w * pixelStride + 3) & ~3);
  218219. ScopedXLock xlock;
  218220. #if JUCE_USE_XSHM
  218221. usingXShm = false;
  218222. if ((imageDepth > 16) && XSHMHelpers::isShmAvailable())
  218223. {
  218224. zerostruct (segmentInfo);
  218225. segmentInfo.shmid = -1;
  218226. segmentInfo.shmaddr = (char *) -1;
  218227. segmentInfo.readOnly = False;
  218228. xImage = XShmCreateImage (display, visual, imageDepth, ZPixmap, 0, &segmentInfo, w, h);
  218229. if (xImage != 0)
  218230. {
  218231. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  218232. xImage->bytes_per_line * xImage->height,
  218233. IPC_CREAT | 0777)) >= 0)
  218234. {
  218235. if (segmentInfo.shmid != -1)
  218236. {
  218237. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  218238. if (segmentInfo.shmaddr != (void*) -1)
  218239. {
  218240. segmentInfo.readOnly = False;
  218241. xImage->data = segmentInfo.shmaddr;
  218242. imageData = (uint8*) segmentInfo.shmaddr;
  218243. if (XShmAttach (display, &segmentInfo) != 0)
  218244. usingXShm = true;
  218245. else
  218246. jassertfalse;
  218247. }
  218248. else
  218249. {
  218250. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  218251. }
  218252. }
  218253. }
  218254. }
  218255. }
  218256. if (! usingXShm)
  218257. #endif
  218258. {
  218259. imageDataAllocated.malloc (lineStride * h);
  218260. imageData = imageDataAllocated;
  218261. if (format_ == Image::ARGB && clearImage)
  218262. zeromem (imageData, h * lineStride);
  218263. xImage = (XImage*) juce_calloc (sizeof (XImage));
  218264. xImage->width = w;
  218265. xImage->height = h;
  218266. xImage->xoffset = 0;
  218267. xImage->format = ZPixmap;
  218268. xImage->data = (char*) imageData;
  218269. xImage->byte_order = ImageByteOrder (display);
  218270. xImage->bitmap_unit = BitmapUnit (display);
  218271. xImage->bitmap_bit_order = BitmapBitOrder (display);
  218272. xImage->bitmap_pad = 32;
  218273. xImage->depth = pixelStride * 8;
  218274. xImage->bytes_per_line = lineStride;
  218275. xImage->bits_per_pixel = pixelStride * 8;
  218276. xImage->red_mask = 0x00FF0000;
  218277. xImage->green_mask = 0x0000FF00;
  218278. xImage->blue_mask = 0x000000FF;
  218279. if (imageDepth == 16)
  218280. {
  218281. const int pixelStride = 2;
  218282. const int lineStride = ((w * pixelStride + 3) & ~3);
  218283. imageData16Bit.malloc (lineStride * h);
  218284. xImage->data = imageData16Bit;
  218285. xImage->bitmap_pad = 16;
  218286. xImage->depth = pixelStride * 8;
  218287. xImage->bytes_per_line = lineStride;
  218288. xImage->bits_per_pixel = pixelStride * 8;
  218289. xImage->red_mask = visual->red_mask;
  218290. xImage->green_mask = visual->green_mask;
  218291. xImage->blue_mask = visual->blue_mask;
  218292. }
  218293. if (! XInitImage (xImage))
  218294. jassertfalse;
  218295. }
  218296. }
  218297. ~XBitmapImage()
  218298. {
  218299. ScopedXLock xlock;
  218300. if (gc != None)
  218301. XFreeGC (display, gc);
  218302. #if JUCE_USE_XSHM
  218303. if (usingXShm)
  218304. {
  218305. XShmDetach (display, &segmentInfo);
  218306. XFlush (display);
  218307. XDestroyImage (xImage);
  218308. shmdt (segmentInfo.shmaddr);
  218309. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  218310. }
  218311. else
  218312. #endif
  218313. {
  218314. xImage->data = 0;
  218315. XDestroyImage (xImage);
  218316. }
  218317. }
  218318. Image::ImageType getType() const { return Image::NativeImage; }
  218319. LowLevelGraphicsContext* createLowLevelContext()
  218320. {
  218321. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  218322. }
  218323. SharedImage* clone()
  218324. {
  218325. jassertfalse;
  218326. return 0;
  218327. }
  218328. void blitToWindow (Window window, int dx, int dy, int dw, int dh, int sx, int sy)
  218329. {
  218330. ScopedXLock xlock;
  218331. if (gc == None)
  218332. {
  218333. XGCValues gcvalues;
  218334. gcvalues.foreground = None;
  218335. gcvalues.background = None;
  218336. gcvalues.function = GXcopy;
  218337. gcvalues.plane_mask = AllPlanes;
  218338. gcvalues.clip_mask = None;
  218339. gcvalues.graphics_exposures = False;
  218340. gc = XCreateGC (display, window,
  218341. GCBackground | GCForeground | GCFunction | GCPlaneMask | GCClipMask | GCGraphicsExposures,
  218342. &gcvalues);
  218343. }
  218344. if (imageDepth == 16)
  218345. {
  218346. const uint32 rMask = xImage->red_mask;
  218347. const uint32 rShiftL = jmax (0, getShiftNeeded (rMask));
  218348. const uint32 rShiftR = jmax (0, -getShiftNeeded (rMask));
  218349. const uint32 gMask = xImage->green_mask;
  218350. const uint32 gShiftL = jmax (0, getShiftNeeded (gMask));
  218351. const uint32 gShiftR = jmax (0, -getShiftNeeded (gMask));
  218352. const uint32 bMask = xImage->blue_mask;
  218353. const uint32 bShiftL = jmax (0, getShiftNeeded (bMask));
  218354. const uint32 bShiftR = jmax (0, -getShiftNeeded (bMask));
  218355. const Image::BitmapData srcData (Image (this), 0, 0, width, height);
  218356. for (int y = sy; y < sy + dh; ++y)
  218357. {
  218358. const uint8* p = srcData.getPixelPointer (sx, y);
  218359. for (int x = sx; x < sx + dw; ++x)
  218360. {
  218361. const PixelRGB* const pixel = (const PixelRGB*) p;
  218362. p += srcData.pixelStride;
  218363. XPutPixel (xImage, x, y,
  218364. (((((uint32) pixel->getRed()) << rShiftL) >> rShiftR) & rMask)
  218365. | (((((uint32) pixel->getGreen()) << gShiftL) >> gShiftR) & gMask)
  218366. | (((((uint32) pixel->getBlue()) << bShiftL) >> bShiftR) & bMask));
  218367. }
  218368. }
  218369. }
  218370. // blit results to screen.
  218371. #if JUCE_USE_XSHM
  218372. if (usingXShm)
  218373. XShmPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh, True);
  218374. else
  218375. #endif
  218376. XPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh);
  218377. }
  218378. juce_UseDebuggingNewOperator
  218379. private:
  218380. XImage* xImage;
  218381. const int imageDepth;
  218382. HeapBlock <uint8> imageDataAllocated;
  218383. HeapBlock <char> imageData16Bit;
  218384. GC gc;
  218385. #if JUCE_USE_XSHM
  218386. XShmSegmentInfo segmentInfo;
  218387. bool usingXShm;
  218388. #endif
  218389. static int getShiftNeeded (const uint32 mask) throw()
  218390. {
  218391. for (int i = 32; --i >= 0;)
  218392. if (((mask >> i) & 1) != 0)
  218393. return i - 7;
  218394. jassertfalse;
  218395. return 0;
  218396. }
  218397. };
  218398. class LinuxComponentPeer : public ComponentPeer
  218399. {
  218400. public:
  218401. LinuxComponentPeer (Component* const component, const int windowStyleFlags)
  218402. : ComponentPeer (component, windowStyleFlags),
  218403. windowH (0),
  218404. parentWindow (0),
  218405. wx (0),
  218406. wy (0),
  218407. ww (0),
  218408. wh (0),
  218409. fullScreen (false),
  218410. mapped (false),
  218411. visual (0),
  218412. depth (0)
  218413. {
  218414. // it's dangerous to create a window on a thread other than the message thread..
  218415. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  218416. repainter = new LinuxRepaintManager (this);
  218417. createWindow();
  218418. setTitle (component->getName());
  218419. }
  218420. ~LinuxComponentPeer()
  218421. {
  218422. // it's dangerous to delete a window on a thread other than the message thread..
  218423. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  218424. deleteIconPixmaps();
  218425. destroyWindow();
  218426. windowH = 0;
  218427. }
  218428. void* getNativeHandle() const
  218429. {
  218430. return (void*) windowH;
  218431. }
  218432. static LinuxComponentPeer* getPeerFor (Window windowHandle) throw()
  218433. {
  218434. XPointer peer = 0;
  218435. ScopedXLock xlock;
  218436. if (! XFindContext (display, (XID) windowHandle, windowHandleXContext, &peer))
  218437. {
  218438. if (peer != 0 && ! ComponentPeer::isValidPeer ((LinuxComponentPeer*) peer))
  218439. peer = 0;
  218440. }
  218441. return (LinuxComponentPeer*) peer;
  218442. }
  218443. void setVisible (bool shouldBeVisible)
  218444. {
  218445. ScopedXLock xlock;
  218446. if (shouldBeVisible)
  218447. XMapWindow (display, windowH);
  218448. else
  218449. XUnmapWindow (display, windowH);
  218450. }
  218451. void setTitle (const String& title)
  218452. {
  218453. setWindowTitle (windowH, title);
  218454. }
  218455. void setPosition (int x, int y)
  218456. {
  218457. setBounds (x, y, ww, wh, false);
  218458. }
  218459. void setSize (int w, int h)
  218460. {
  218461. setBounds (wx, wy, w, h, false);
  218462. }
  218463. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  218464. {
  218465. fullScreen = isNowFullScreen;
  218466. if (windowH != 0)
  218467. {
  218468. Component::SafePointer<Component> deletionChecker (component);
  218469. wx = x;
  218470. wy = y;
  218471. ww = jmax (1, w);
  218472. wh = jmax (1, h);
  218473. ScopedXLock xlock;
  218474. // Make sure the Window manager does what we want
  218475. XSizeHints* hints = XAllocSizeHints();
  218476. hints->flags = USSize | USPosition;
  218477. hints->width = ww;
  218478. hints->height = wh;
  218479. hints->x = wx;
  218480. hints->y = wy;
  218481. if ((getStyleFlags() & (windowHasTitleBar | windowIsResizable)) == windowHasTitleBar)
  218482. {
  218483. hints->min_width = hints->max_width = hints->width;
  218484. hints->min_height = hints->max_height = hints->height;
  218485. hints->flags |= PMinSize | PMaxSize;
  218486. }
  218487. XSetWMNormalHints (display, windowH, hints);
  218488. XFree (hints);
  218489. XMoveResizeWindow (display, windowH,
  218490. wx - windowBorder.getLeft(),
  218491. wy - windowBorder.getTop(), ww, wh);
  218492. if (deletionChecker != 0)
  218493. {
  218494. updateBorderSize();
  218495. handleMovedOrResized();
  218496. }
  218497. }
  218498. }
  218499. const Rectangle<int> getBounds() const { return Rectangle<int> (wx, wy, ww, wh); }
  218500. const Point<int> getScreenPosition() const { return Point<int> (wx, wy); }
  218501. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition)
  218502. {
  218503. return relativePosition + getScreenPosition();
  218504. }
  218505. const Point<int> globalPositionToRelative (const Point<int>& screenPosition)
  218506. {
  218507. return screenPosition - getScreenPosition();
  218508. }
  218509. void setMinimised (bool shouldBeMinimised)
  218510. {
  218511. if (shouldBeMinimised)
  218512. {
  218513. Window root = RootWindow (display, DefaultScreen (display));
  218514. XClientMessageEvent clientMsg;
  218515. clientMsg.display = display;
  218516. clientMsg.window = windowH;
  218517. clientMsg.type = ClientMessage;
  218518. clientMsg.format = 32;
  218519. clientMsg.message_type = Atoms::ChangeState;
  218520. clientMsg.data.l[0] = IconicState;
  218521. ScopedXLock xlock;
  218522. XSendEvent (display, root, false, SubstructureRedirectMask | SubstructureNotifyMask, (XEvent*) &clientMsg);
  218523. }
  218524. else
  218525. {
  218526. setVisible (true);
  218527. }
  218528. }
  218529. bool isMinimised() const
  218530. {
  218531. bool minimised = false;
  218532. unsigned char* stateProp;
  218533. unsigned long nitems, bytesLeft;
  218534. Atom actualType;
  218535. int actualFormat;
  218536. ScopedXLock xlock;
  218537. if (XGetWindowProperty (display, windowH, Atoms::State, 0, 64, False,
  218538. Atoms::State, &actualType, &actualFormat, &nitems, &bytesLeft,
  218539. &stateProp) == Success
  218540. && actualType == Atoms::State
  218541. && actualFormat == 32
  218542. && nitems > 0)
  218543. {
  218544. if (((unsigned long*) stateProp)[0] == IconicState)
  218545. minimised = true;
  218546. XFree (stateProp);
  218547. }
  218548. return minimised;
  218549. }
  218550. void setFullScreen (const bool shouldBeFullScreen)
  218551. {
  218552. Rectangle<int> r (lastNonFullscreenBounds); // (get a copy of this before de-minimising)
  218553. setMinimised (false);
  218554. if (fullScreen != shouldBeFullScreen)
  218555. {
  218556. if (shouldBeFullScreen)
  218557. r = Desktop::getInstance().getMainMonitorArea();
  218558. if (! r.isEmpty())
  218559. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  218560. getComponent()->repaint();
  218561. }
  218562. }
  218563. bool isFullScreen() const
  218564. {
  218565. return fullScreen;
  218566. }
  218567. bool isChildWindowOf (Window possibleParent) const
  218568. {
  218569. Window* windowList = 0;
  218570. uint32 windowListSize = 0;
  218571. Window parent, root;
  218572. ScopedXLock xlock;
  218573. if (XQueryTree (display, windowH, &root, &parent, &windowList, &windowListSize) != 0)
  218574. {
  218575. if (windowList != 0)
  218576. XFree (windowList);
  218577. return parent == possibleParent;
  218578. }
  218579. return false;
  218580. }
  218581. bool isFrontWindow() const
  218582. {
  218583. Window* windowList = 0;
  218584. uint32 windowListSize = 0;
  218585. bool result = false;
  218586. ScopedXLock xlock;
  218587. Window parent, root = RootWindow (display, DefaultScreen (display));
  218588. if (XQueryTree (display, root, &root, &parent, &windowList, &windowListSize) != 0)
  218589. {
  218590. for (int i = windowListSize; --i >= 0;)
  218591. {
  218592. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (windowList[i]);
  218593. if (peer != 0)
  218594. {
  218595. result = (peer == this);
  218596. break;
  218597. }
  218598. }
  218599. }
  218600. if (windowList != 0)
  218601. XFree (windowList);
  218602. return result;
  218603. }
  218604. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  218605. {
  218606. int x = position.getX();
  218607. int y = position.getY();
  218608. if (((unsigned int) x) >= (unsigned int) ww
  218609. || ((unsigned int) y) >= (unsigned int) wh)
  218610. return false;
  218611. bool inFront = false;
  218612. for (int i = 0; i < Desktop::getInstance().getNumComponents(); ++i)
  218613. {
  218614. Component* const c = Desktop::getInstance().getComponent (i);
  218615. if (inFront)
  218616. {
  218617. if (c->contains (x + wx - c->getScreenX(),
  218618. y + wy - c->getScreenY()))
  218619. {
  218620. return false;
  218621. }
  218622. }
  218623. else if (c == getComponent())
  218624. {
  218625. inFront = true;
  218626. }
  218627. }
  218628. if (trueIfInAChildWindow)
  218629. return true;
  218630. ::Window root, child;
  218631. unsigned int bw, depth;
  218632. int wx, wy, w, h;
  218633. ScopedXLock xlock;
  218634. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  218635. &wx, &wy, (unsigned int*) &w, (unsigned int*) &h,
  218636. &bw, &depth))
  218637. {
  218638. return false;
  218639. }
  218640. if (! XTranslateCoordinates (display, windowH, windowH, x, y, &wx, &wy, &child))
  218641. return false;
  218642. return child == None;
  218643. }
  218644. const BorderSize getFrameSize() const
  218645. {
  218646. return BorderSize();
  218647. }
  218648. bool setAlwaysOnTop (bool alwaysOnTop)
  218649. {
  218650. return false;
  218651. }
  218652. void toFront (bool makeActive)
  218653. {
  218654. if (makeActive)
  218655. {
  218656. setVisible (true);
  218657. grabFocus();
  218658. }
  218659. XEvent ev;
  218660. ev.xclient.type = ClientMessage;
  218661. ev.xclient.serial = 0;
  218662. ev.xclient.send_event = True;
  218663. ev.xclient.message_type = Atoms::ActiveWin;
  218664. ev.xclient.window = windowH;
  218665. ev.xclient.format = 32;
  218666. ev.xclient.data.l[0] = 2;
  218667. ev.xclient.data.l[1] = CurrentTime;
  218668. ev.xclient.data.l[2] = 0;
  218669. ev.xclient.data.l[3] = 0;
  218670. ev.xclient.data.l[4] = 0;
  218671. {
  218672. ScopedXLock xlock;
  218673. XSendEvent (display, RootWindow (display, DefaultScreen (display)),
  218674. False, SubstructureRedirectMask | SubstructureNotifyMask, &ev);
  218675. XWindowAttributes attr;
  218676. XGetWindowAttributes (display, windowH, &attr);
  218677. if (component->isAlwaysOnTop())
  218678. XRaiseWindow (display, windowH);
  218679. XSync (display, False);
  218680. }
  218681. handleBroughtToFront();
  218682. }
  218683. void toBehind (ComponentPeer* other)
  218684. {
  218685. LinuxComponentPeer* const otherPeer = dynamic_cast <LinuxComponentPeer*> (other);
  218686. jassert (otherPeer != 0); // wrong type of window?
  218687. if (otherPeer != 0)
  218688. {
  218689. setMinimised (false);
  218690. Window newStack[] = { otherPeer->windowH, windowH };
  218691. ScopedXLock xlock;
  218692. XRestackWindows (display, newStack, 2);
  218693. }
  218694. }
  218695. bool isFocused() const
  218696. {
  218697. int revert = 0;
  218698. Window focusedWindow = 0;
  218699. ScopedXLock xlock;
  218700. XGetInputFocus (display, &focusedWindow, &revert);
  218701. return focusedWindow == windowH;
  218702. }
  218703. void grabFocus()
  218704. {
  218705. XWindowAttributes atts;
  218706. ScopedXLock xlock;
  218707. if (windowH != 0
  218708. && XGetWindowAttributes (display, windowH, &atts)
  218709. && atts.map_state == IsViewable
  218710. && ! isFocused())
  218711. {
  218712. XSetInputFocus (display, windowH, RevertToParent, CurrentTime);
  218713. isActiveApplication = true;
  218714. }
  218715. }
  218716. void textInputRequired (const Point<int>&)
  218717. {
  218718. }
  218719. void repaint (const Rectangle<int>& area)
  218720. {
  218721. repainter->repaint (area.getIntersection (getComponent()->getLocalBounds()));
  218722. }
  218723. void performAnyPendingRepaintsNow()
  218724. {
  218725. repainter->performAnyPendingRepaintsNow();
  218726. }
  218727. static Pixmap juce_createColourPixmapFromImage (Display* display, const Image& image)
  218728. {
  218729. ScopedXLock xlock;
  218730. const int width = image.getWidth();
  218731. const int height = image.getHeight();
  218732. HeapBlock <char> colour (width * height);
  218733. int index = 0;
  218734. for (int y = 0; y < height; ++y)
  218735. for (int x = 0; x < width; ++x)
  218736. colour[index++] = static_cast<char> (image.getPixelAt (x, y).getARGB());
  218737. XImage* ximage = XCreateImage (display, CopyFromParent, 24, ZPixmap,
  218738. 0, colour.getData(),
  218739. width, height, 32, 0);
  218740. Pixmap pixmap = XCreatePixmap (display, DefaultRootWindow (display),
  218741. width, height, 24);
  218742. GC gc = XCreateGC (display, pixmap, 0, 0);
  218743. XPutImage (display, pixmap, gc, ximage, 0, 0, 0, 0, width, height);
  218744. XFreeGC (display, gc);
  218745. return pixmap;
  218746. }
  218747. static Pixmap juce_createMaskPixmapFromImage (Display* display, const Image& image)
  218748. {
  218749. ScopedXLock xlock;
  218750. const int width = image.getWidth();
  218751. const int height = image.getHeight();
  218752. const int stride = (width + 7) >> 3;
  218753. HeapBlock <char> mask;
  218754. mask.calloc (stride * height);
  218755. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  218756. for (int y = 0; y < height; ++y)
  218757. {
  218758. for (int x = 0; x < width; ++x)
  218759. {
  218760. const char bit = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  218761. const int offset = y * stride + (x >> 3);
  218762. if (image.getPixelAt (x, y).getAlpha() >= 128)
  218763. mask[offset] |= bit;
  218764. }
  218765. }
  218766. return XCreatePixmapFromBitmapData (display, DefaultRootWindow (display),
  218767. mask.getData(), width, height, 1, 0, 1);
  218768. }
  218769. void setIcon (const Image& newIcon)
  218770. {
  218771. const int dataSize = newIcon.getWidth() * newIcon.getHeight() + 2;
  218772. HeapBlock <unsigned long> data (dataSize);
  218773. int index = 0;
  218774. data[index++] = newIcon.getWidth();
  218775. data[index++] = newIcon.getHeight();
  218776. for (int y = 0; y < newIcon.getHeight(); ++y)
  218777. for (int x = 0; x < newIcon.getWidth(); ++x)
  218778. data[index++] = newIcon.getPixelAt (x, y).getARGB();
  218779. ScopedXLock xlock;
  218780. XChangeProperty (display, windowH,
  218781. XInternAtom (display, "_NET_WM_ICON", False),
  218782. XA_CARDINAL, 32, PropModeReplace,
  218783. reinterpret_cast<unsigned char*> (data.getData()), dataSize);
  218784. deleteIconPixmaps();
  218785. XWMHints* wmHints = XGetWMHints (display, windowH);
  218786. if (wmHints == 0)
  218787. wmHints = XAllocWMHints();
  218788. wmHints->flags |= IconPixmapHint | IconMaskHint;
  218789. wmHints->icon_pixmap = juce_createColourPixmapFromImage (display, newIcon);
  218790. wmHints->icon_mask = juce_createMaskPixmapFromImage (display, newIcon);
  218791. XSetWMHints (display, windowH, wmHints);
  218792. XFree (wmHints);
  218793. XSync (display, False);
  218794. }
  218795. void deleteIconPixmaps()
  218796. {
  218797. ScopedXLock xlock;
  218798. XWMHints* wmHints = XGetWMHints (display, windowH);
  218799. if (wmHints != 0)
  218800. {
  218801. if ((wmHints->flags & IconPixmapHint) != 0)
  218802. {
  218803. wmHints->flags &= ~IconPixmapHint;
  218804. XFreePixmap (display, wmHints->icon_pixmap);
  218805. }
  218806. if ((wmHints->flags & IconMaskHint) != 0)
  218807. {
  218808. wmHints->flags &= ~IconMaskHint;
  218809. XFreePixmap (display, wmHints->icon_mask);
  218810. }
  218811. XSetWMHints (display, windowH, wmHints);
  218812. XFree (wmHints);
  218813. }
  218814. }
  218815. void handleWindowMessage (XEvent* event)
  218816. {
  218817. switch (event->xany.type)
  218818. {
  218819. case 2: // 'KeyPress'
  218820. {
  218821. ScopedXLock xlock;
  218822. XKeyEvent* const keyEvent = (XKeyEvent*) &event->xkey;
  218823. updateKeyStates (keyEvent->keycode, true);
  218824. char utf8 [64];
  218825. zeromem (utf8, sizeof (utf8));
  218826. KeySym sym;
  218827. {
  218828. const char* oldLocale = ::setlocale (LC_ALL, 0);
  218829. ::setlocale (LC_ALL, "");
  218830. XLookupString (keyEvent, utf8, sizeof (utf8), &sym, 0);
  218831. ::setlocale (LC_ALL, oldLocale);
  218832. }
  218833. const juce_wchar unicodeChar = String::fromUTF8 (utf8, sizeof (utf8) - 1) [0];
  218834. int keyCode = (int) unicodeChar;
  218835. if (keyCode < 0x20)
  218836. keyCode = XKeycodeToKeysym (display, keyEvent->keycode, currentModifiers.isShiftDown() ? 1 : 0);
  218837. const ModifierKeys oldMods (currentModifiers);
  218838. bool keyPressed = false;
  218839. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, true);
  218840. if ((sym & 0xff00) == 0xff00)
  218841. {
  218842. // Translate keypad
  218843. if (sym == XK_KP_Divide)
  218844. keyCode = XK_slash;
  218845. else if (sym == XK_KP_Multiply)
  218846. keyCode = XK_asterisk;
  218847. else if (sym == XK_KP_Subtract)
  218848. keyCode = XK_hyphen;
  218849. else if (sym == XK_KP_Add)
  218850. keyCode = XK_plus;
  218851. else if (sym == XK_KP_Enter)
  218852. keyCode = XK_Return;
  218853. else if (sym == XK_KP_Decimal)
  218854. keyCode = Keys::numLock ? XK_period : XK_Delete;
  218855. else if (sym == XK_KP_0)
  218856. keyCode = Keys::numLock ? XK_0 : XK_Insert;
  218857. else if (sym == XK_KP_1)
  218858. keyCode = Keys::numLock ? XK_1 : XK_End;
  218859. else if (sym == XK_KP_2)
  218860. keyCode = Keys::numLock ? XK_2 : XK_Down;
  218861. else if (sym == XK_KP_3)
  218862. keyCode = Keys::numLock ? XK_3 : XK_Page_Down;
  218863. else if (sym == XK_KP_4)
  218864. keyCode = Keys::numLock ? XK_4 : XK_Left;
  218865. else if (sym == XK_KP_5)
  218866. keyCode = XK_5;
  218867. else if (sym == XK_KP_6)
  218868. keyCode = Keys::numLock ? XK_6 : XK_Right;
  218869. else if (sym == XK_KP_7)
  218870. keyCode = Keys::numLock ? XK_7 : XK_Home;
  218871. else if (sym == XK_KP_8)
  218872. keyCode = Keys::numLock ? XK_8 : XK_Up;
  218873. else if (sym == XK_KP_9)
  218874. keyCode = Keys::numLock ? XK_9 : XK_Page_Up;
  218875. switch (sym)
  218876. {
  218877. case XK_Left:
  218878. case XK_Right:
  218879. case XK_Up:
  218880. case XK_Down:
  218881. case XK_Page_Up:
  218882. case XK_Page_Down:
  218883. case XK_End:
  218884. case XK_Home:
  218885. case XK_Delete:
  218886. case XK_Insert:
  218887. keyPressed = true;
  218888. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  218889. break;
  218890. case XK_Tab:
  218891. case XK_Return:
  218892. case XK_Escape:
  218893. case XK_BackSpace:
  218894. keyPressed = true;
  218895. keyCode &= 0xff;
  218896. break;
  218897. default:
  218898. {
  218899. if (sym >= XK_F1 && sym <= XK_F16)
  218900. {
  218901. keyPressed = true;
  218902. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  218903. }
  218904. break;
  218905. }
  218906. }
  218907. }
  218908. if (utf8[0] != 0 || ((sym & 0xff00) == 0 && sym >= 8))
  218909. keyPressed = true;
  218910. if (oldMods != currentModifiers)
  218911. handleModifierKeysChange();
  218912. if (keyDownChange)
  218913. handleKeyUpOrDown (true);
  218914. if (keyPressed)
  218915. handleKeyPress (keyCode, unicodeChar);
  218916. break;
  218917. }
  218918. case KeyRelease:
  218919. {
  218920. const XKeyEvent* const keyEvent = (const XKeyEvent*) &event->xkey;
  218921. updateKeyStates (keyEvent->keycode, false);
  218922. ScopedXLock xlock;
  218923. KeySym sym = XKeycodeToKeysym (display, keyEvent->keycode, 0);
  218924. const ModifierKeys oldMods (currentModifiers);
  218925. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, false);
  218926. if (oldMods != currentModifiers)
  218927. handleModifierKeysChange();
  218928. if (keyDownChange)
  218929. handleKeyUpOrDown (false);
  218930. break;
  218931. }
  218932. case ButtonPress:
  218933. {
  218934. const XButtonPressedEvent* const buttonPressEvent = (const XButtonPressedEvent*) &event->xbutton;
  218935. updateKeyModifiers (buttonPressEvent->state);
  218936. bool buttonMsg = false;
  218937. const int map = pointerMap [buttonPressEvent->button - Button1];
  218938. if (map == Keys::WheelUp || map == Keys::WheelDown)
  218939. {
  218940. handleMouseWheel (0, Point<int> (buttonPressEvent->x, buttonPressEvent->y),
  218941. getEventTime (buttonPressEvent->time), 0, map == Keys::WheelDown ? -84.0f : 84.0f);
  218942. }
  218943. if (map == Keys::LeftButton)
  218944. {
  218945. currentModifiers = currentModifiers.withFlags (ModifierKeys::leftButtonModifier);
  218946. buttonMsg = true;
  218947. }
  218948. else if (map == Keys::RightButton)
  218949. {
  218950. currentModifiers = currentModifiers.withFlags (ModifierKeys::rightButtonModifier);
  218951. buttonMsg = true;
  218952. }
  218953. else if (map == Keys::MiddleButton)
  218954. {
  218955. currentModifiers = currentModifiers.withFlags (ModifierKeys::middleButtonModifier);
  218956. buttonMsg = true;
  218957. }
  218958. if (buttonMsg)
  218959. {
  218960. toFront (true);
  218961. handleMouseEvent (0, Point<int> (buttonPressEvent->x, buttonPressEvent->y), currentModifiers,
  218962. getEventTime (buttonPressEvent->time));
  218963. }
  218964. clearLastMousePos();
  218965. break;
  218966. }
  218967. case ButtonRelease:
  218968. {
  218969. const XButtonReleasedEvent* const buttonRelEvent = (const XButtonReleasedEvent*) &event->xbutton;
  218970. updateKeyModifiers (buttonRelEvent->state);
  218971. const int map = pointerMap [buttonRelEvent->button - Button1];
  218972. if (map == Keys::LeftButton)
  218973. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::leftButtonModifier);
  218974. else if (map == Keys::RightButton)
  218975. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::rightButtonModifier);
  218976. else if (map == Keys::MiddleButton)
  218977. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::middleButtonModifier);
  218978. handleMouseEvent (0, Point<int> (buttonRelEvent->x, buttonRelEvent->y), currentModifiers,
  218979. getEventTime (buttonRelEvent->time));
  218980. clearLastMousePos();
  218981. break;
  218982. }
  218983. case MotionNotify:
  218984. {
  218985. const XPointerMovedEvent* const movedEvent = (const XPointerMovedEvent*) &event->xmotion;
  218986. updateKeyModifiers (movedEvent->state);
  218987. const Point<int> mousePos (Desktop::getMousePosition());
  218988. if (lastMousePos != mousePos)
  218989. {
  218990. lastMousePos = mousePos;
  218991. if (parentWindow != 0 && (styleFlags & windowHasTitleBar) == 0)
  218992. {
  218993. Window wRoot = 0, wParent = 0;
  218994. {
  218995. ScopedXLock xlock;
  218996. unsigned int numChildren;
  218997. Window* wChild = 0;
  218998. XQueryTree (display, windowH, &wRoot, &wParent, &wChild, &numChildren);
  218999. }
  219000. if (wParent != 0
  219001. && wParent != windowH
  219002. && wParent != wRoot)
  219003. {
  219004. parentWindow = wParent;
  219005. updateBounds();
  219006. }
  219007. else
  219008. {
  219009. parentWindow = 0;
  219010. }
  219011. }
  219012. handleMouseEvent (0, mousePos - getScreenPosition(), currentModifiers, getEventTime (movedEvent->time));
  219013. }
  219014. break;
  219015. }
  219016. case EnterNotify:
  219017. {
  219018. clearLastMousePos();
  219019. const XEnterWindowEvent* const enterEvent = (const XEnterWindowEvent*) &event->xcrossing;
  219020. if (! currentModifiers.isAnyMouseButtonDown())
  219021. {
  219022. updateKeyModifiers (enterEvent->state);
  219023. handleMouseEvent (0, Point<int> (enterEvent->x, enterEvent->y), currentModifiers, getEventTime (enterEvent->time));
  219024. }
  219025. break;
  219026. }
  219027. case LeaveNotify:
  219028. {
  219029. const XLeaveWindowEvent* const leaveEvent = (const XLeaveWindowEvent*) &event->xcrossing;
  219030. // Suppress the normal leave if we've got a pointer grab, or if
  219031. // it's a bogus one caused by clicking a mouse button when running
  219032. // in a Window manager
  219033. if (((! currentModifiers.isAnyMouseButtonDown()) && leaveEvent->mode == NotifyNormal)
  219034. || leaveEvent->mode == NotifyUngrab)
  219035. {
  219036. updateKeyModifiers (leaveEvent->state);
  219037. handleMouseEvent (0, Point<int> (leaveEvent->x, leaveEvent->y), currentModifiers, getEventTime (leaveEvent->time));
  219038. }
  219039. break;
  219040. }
  219041. case FocusIn:
  219042. {
  219043. isActiveApplication = true;
  219044. if (isFocused())
  219045. handleFocusGain();
  219046. break;
  219047. }
  219048. case FocusOut:
  219049. {
  219050. isActiveApplication = false;
  219051. if (! isFocused())
  219052. handleFocusLoss();
  219053. break;
  219054. }
  219055. case Expose:
  219056. {
  219057. // Batch together all pending expose events
  219058. XExposeEvent* exposeEvent = (XExposeEvent*) &event->xexpose;
  219059. XEvent nextEvent;
  219060. ScopedXLock xlock;
  219061. if (exposeEvent->window != windowH)
  219062. {
  219063. Window child;
  219064. XTranslateCoordinates (display, exposeEvent->window, windowH,
  219065. exposeEvent->x, exposeEvent->y, &exposeEvent->x, &exposeEvent->y,
  219066. &child);
  219067. }
  219068. repaint (Rectangle<int> (exposeEvent->x, exposeEvent->y,
  219069. exposeEvent->width, exposeEvent->height));
  219070. while (XEventsQueued (display, QueuedAfterFlush) > 0)
  219071. {
  219072. XPeekEvent (display, (XEvent*) &nextEvent);
  219073. if (nextEvent.type != Expose || nextEvent.xany.window != event->xany.window)
  219074. break;
  219075. XNextEvent (display, (XEvent*) &nextEvent);
  219076. XExposeEvent* nextExposeEvent = (XExposeEvent*) &nextEvent.xexpose;
  219077. repaint (Rectangle<int> (nextExposeEvent->x, nextExposeEvent->y,
  219078. nextExposeEvent->width, nextExposeEvent->height));
  219079. }
  219080. break;
  219081. }
  219082. case CirculateNotify:
  219083. case CreateNotify:
  219084. case DestroyNotify:
  219085. // Think we can ignore these
  219086. break;
  219087. case ConfigureNotify:
  219088. {
  219089. updateBounds();
  219090. updateBorderSize();
  219091. handleMovedOrResized();
  219092. // if the native title bar is dragged, need to tell any active menus, etc.
  219093. if ((styleFlags & windowHasTitleBar) != 0
  219094. && component->isCurrentlyBlockedByAnotherModalComponent())
  219095. {
  219096. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  219097. if (currentModalComp != 0)
  219098. currentModalComp->inputAttemptWhenModal();
  219099. }
  219100. XConfigureEvent* const confEvent = (XConfigureEvent*) &event->xconfigure;
  219101. if (confEvent->window == windowH
  219102. && confEvent->above != 0
  219103. && isFrontWindow())
  219104. {
  219105. handleBroughtToFront();
  219106. }
  219107. break;
  219108. }
  219109. case ReparentNotify:
  219110. {
  219111. parentWindow = 0;
  219112. Window wRoot = 0;
  219113. Window* wChild = 0;
  219114. unsigned int numChildren;
  219115. {
  219116. ScopedXLock xlock;
  219117. XQueryTree (display, windowH, &wRoot, &parentWindow, &wChild, &numChildren);
  219118. }
  219119. if (parentWindow == windowH || parentWindow == wRoot)
  219120. parentWindow = 0;
  219121. updateBounds();
  219122. updateBorderSize();
  219123. handleMovedOrResized();
  219124. break;
  219125. }
  219126. case GravityNotify:
  219127. {
  219128. updateBounds();
  219129. updateBorderSize();
  219130. handleMovedOrResized();
  219131. break;
  219132. }
  219133. case MapNotify:
  219134. mapped = true;
  219135. handleBroughtToFront();
  219136. break;
  219137. case UnmapNotify:
  219138. mapped = false;
  219139. break;
  219140. case MappingNotify:
  219141. {
  219142. XMappingEvent* mappingEvent = (XMappingEvent*) &event->xmapping;
  219143. if (mappingEvent->request != MappingPointer)
  219144. {
  219145. // Deal with modifier/keyboard mapping
  219146. ScopedXLock xlock;
  219147. XRefreshKeyboardMapping (mappingEvent);
  219148. updateModifierMappings();
  219149. }
  219150. break;
  219151. }
  219152. case ClientMessage:
  219153. {
  219154. const XClientMessageEvent* const clientMsg = (const XClientMessageEvent*) &event->xclient;
  219155. if (clientMsg->message_type == Atoms::Protocols && clientMsg->format == 32)
  219156. {
  219157. const Atom atom = (Atom) clientMsg->data.l[0];
  219158. if (atom == Atoms::ProtocolList [Atoms::PING])
  219159. {
  219160. Window root = RootWindow (display, DefaultScreen (display));
  219161. event->xclient.window = root;
  219162. XSendEvent (display, root, False, NoEventMask, event);
  219163. XFlush (display);
  219164. }
  219165. else if (atom == Atoms::ProtocolList [Atoms::TAKE_FOCUS])
  219166. {
  219167. XWindowAttributes atts;
  219168. ScopedXLock xlock;
  219169. if (clientMsg->window != 0
  219170. && XGetWindowAttributes (display, clientMsg->window, &atts))
  219171. {
  219172. if (atts.map_state == IsViewable)
  219173. XSetInputFocus (display, clientMsg->window, RevertToParent, clientMsg->data.l[1]);
  219174. }
  219175. }
  219176. else if (atom == Atoms::ProtocolList [Atoms::DELETE_WINDOW])
  219177. {
  219178. handleUserClosingWindow();
  219179. }
  219180. }
  219181. else if (clientMsg->message_type == Atoms::XdndEnter)
  219182. {
  219183. handleDragAndDropEnter (clientMsg);
  219184. }
  219185. else if (clientMsg->message_type == Atoms::XdndLeave)
  219186. {
  219187. resetDragAndDrop();
  219188. }
  219189. else if (clientMsg->message_type == Atoms::XdndPosition)
  219190. {
  219191. handleDragAndDropPosition (clientMsg);
  219192. }
  219193. else if (clientMsg->message_type == Atoms::XdndDrop)
  219194. {
  219195. handleDragAndDropDrop (clientMsg);
  219196. }
  219197. else if (clientMsg->message_type == Atoms::XdndStatus)
  219198. {
  219199. handleDragAndDropStatus (clientMsg);
  219200. }
  219201. else if (clientMsg->message_type == Atoms::XdndFinished)
  219202. {
  219203. resetDragAndDrop();
  219204. }
  219205. break;
  219206. }
  219207. case SelectionNotify:
  219208. handleDragAndDropSelection (event);
  219209. break;
  219210. case SelectionClear:
  219211. case SelectionRequest:
  219212. break;
  219213. default:
  219214. #if JUCE_USE_XSHM
  219215. {
  219216. ScopedXLock xlock;
  219217. if (event->xany.type == XShmGetEventBase (display))
  219218. repainter->notifyPaintCompleted();
  219219. }
  219220. #endif
  219221. break;
  219222. }
  219223. }
  219224. void showMouseCursor (Cursor cursor) throw()
  219225. {
  219226. ScopedXLock xlock;
  219227. XDefineCursor (display, windowH, cursor);
  219228. }
  219229. void setTaskBarIcon (const Image& image)
  219230. {
  219231. ScopedXLock xlock;
  219232. taskbarImage = image;
  219233. Screen* const screen = XDefaultScreenOfDisplay (display);
  219234. const int screenNumber = XScreenNumberOfScreen (screen);
  219235. String screenAtom ("_NET_SYSTEM_TRAY_S");
  219236. screenAtom << screenNumber;
  219237. Atom selectionAtom = XInternAtom (display, screenAtom.toUTF8(), false);
  219238. XGrabServer (display);
  219239. Window managerWin = XGetSelectionOwner (display, selectionAtom);
  219240. if (managerWin != None)
  219241. XSelectInput (display, managerWin, StructureNotifyMask);
  219242. XUngrabServer (display);
  219243. XFlush (display);
  219244. if (managerWin != None)
  219245. {
  219246. XEvent ev;
  219247. zerostruct (ev);
  219248. ev.xclient.type = ClientMessage;
  219249. ev.xclient.window = managerWin;
  219250. ev.xclient.message_type = XInternAtom (display, "_NET_SYSTEM_TRAY_OPCODE", False);
  219251. ev.xclient.format = 32;
  219252. ev.xclient.data.l[0] = CurrentTime;
  219253. ev.xclient.data.l[1] = 0 /*SYSTEM_TRAY_REQUEST_DOCK*/;
  219254. ev.xclient.data.l[2] = windowH;
  219255. ev.xclient.data.l[3] = 0;
  219256. ev.xclient.data.l[4] = 0;
  219257. XSendEvent (display, managerWin, False, NoEventMask, &ev);
  219258. XSync (display, False);
  219259. }
  219260. // For older KDE's ...
  219261. long atomData = 1;
  219262. Atom trayAtom = XInternAtom (display, "KWM_DOCKWINDOW", false);
  219263. XChangeProperty (display, windowH, trayAtom, trayAtom, 32, PropModeReplace, (unsigned char*) &atomData, 1);
  219264. // For more recent KDE's...
  219265. trayAtom = XInternAtom (display, "_KDE_NET_WM_SYSTEM_TRAY_WINDOW_FOR", false);
  219266. XChangeProperty (display, windowH, trayAtom, XA_WINDOW, 32, PropModeReplace, (unsigned char*) &windowH, 1);
  219267. // a minimum size must be specified for GNOME and Xfce, otherwise the icon is displayed with a width of 1
  219268. XSizeHints* hints = XAllocSizeHints();
  219269. hints->flags = PMinSize;
  219270. hints->min_width = 22;
  219271. hints->min_height = 22;
  219272. XSetWMNormalHints (display, windowH, hints);
  219273. XFree (hints);
  219274. }
  219275. const Image& getTaskbarIcon() const throw() { return taskbarImage; }
  219276. juce_UseDebuggingNewOperator
  219277. bool dontRepaint;
  219278. static ModifierKeys currentModifiers;
  219279. static bool isActiveApplication;
  219280. private:
  219281. class LinuxRepaintManager : public Timer
  219282. {
  219283. public:
  219284. LinuxRepaintManager (LinuxComponentPeer* const peer_)
  219285. : peer (peer_),
  219286. lastTimeImageUsed (0)
  219287. {
  219288. #if JUCE_USE_XSHM
  219289. shmCompletedDrawing = true;
  219290. useARGBImagesForRendering = XSHMHelpers::isShmAvailable();
  219291. if (useARGBImagesForRendering)
  219292. {
  219293. ScopedXLock xlock;
  219294. XShmSegmentInfo segmentinfo;
  219295. XImage* const testImage
  219296. = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  219297. 24, ZPixmap, 0, &segmentinfo, 64, 64);
  219298. useARGBImagesForRendering = (testImage->bits_per_pixel == 32);
  219299. XDestroyImage (testImage);
  219300. }
  219301. #endif
  219302. }
  219303. ~LinuxRepaintManager()
  219304. {
  219305. }
  219306. void timerCallback()
  219307. {
  219308. #if JUCE_USE_XSHM
  219309. if (! shmCompletedDrawing)
  219310. return;
  219311. #endif
  219312. if (! regionsNeedingRepaint.isEmpty())
  219313. {
  219314. stopTimer();
  219315. performAnyPendingRepaintsNow();
  219316. }
  219317. else if (Time::getApproximateMillisecondCounter() > lastTimeImageUsed + 3000)
  219318. {
  219319. stopTimer();
  219320. image = Image();
  219321. }
  219322. }
  219323. void repaint (const Rectangle<int>& area)
  219324. {
  219325. if (! isTimerRunning())
  219326. startTimer (repaintTimerPeriod);
  219327. regionsNeedingRepaint.add (area);
  219328. }
  219329. void performAnyPendingRepaintsNow()
  219330. {
  219331. #if JUCE_USE_XSHM
  219332. if (! shmCompletedDrawing)
  219333. {
  219334. startTimer (repaintTimerPeriod);
  219335. return;
  219336. }
  219337. #endif
  219338. peer->clearMaskedRegion();
  219339. RectangleList originalRepaintRegion (regionsNeedingRepaint);
  219340. regionsNeedingRepaint.clear();
  219341. const Rectangle<int> totalArea (originalRepaintRegion.getBounds());
  219342. if (! totalArea.isEmpty())
  219343. {
  219344. if (image.isNull() || image.getWidth() < totalArea.getWidth()
  219345. || image.getHeight() < totalArea.getHeight())
  219346. {
  219347. #if JUCE_USE_XSHM
  219348. image = Image (new XBitmapImage (useARGBImagesForRendering ? Image::ARGB
  219349. : Image::RGB,
  219350. #else
  219351. image = Image (new XBitmapImage (Image::RGB,
  219352. #endif
  219353. (totalArea.getWidth() + 31) & ~31,
  219354. (totalArea.getHeight() + 31) & ~31,
  219355. false, peer->depth, peer->visual));
  219356. }
  219357. startTimer (repaintTimerPeriod);
  219358. RectangleList adjustedList (originalRepaintRegion);
  219359. adjustedList.offsetAll (-totalArea.getX(), -totalArea.getY());
  219360. LowLevelGraphicsSoftwareRenderer context (image, -totalArea.getX(), -totalArea.getY(), adjustedList);
  219361. if (peer->depth == 32)
  219362. {
  219363. RectangleList::Iterator i (originalRepaintRegion);
  219364. while (i.next())
  219365. image.clear (*i.getRectangle() - totalArea.getPosition());
  219366. }
  219367. peer->handlePaint (context);
  219368. if (! peer->maskedRegion.isEmpty())
  219369. originalRepaintRegion.subtract (peer->maskedRegion);
  219370. for (RectangleList::Iterator i (originalRepaintRegion); i.next();)
  219371. {
  219372. #if JUCE_USE_XSHM
  219373. shmCompletedDrawing = false;
  219374. #endif
  219375. const Rectangle<int>& r = *i.getRectangle();
  219376. static_cast<XBitmapImage*> (image.getSharedImage())
  219377. ->blitToWindow (peer->windowH,
  219378. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  219379. r.getX() - totalArea.getX(), r.getY() - totalArea.getY());
  219380. }
  219381. }
  219382. lastTimeImageUsed = Time::getApproximateMillisecondCounter();
  219383. startTimer (repaintTimerPeriod);
  219384. }
  219385. #if JUCE_USE_XSHM
  219386. void notifyPaintCompleted() { shmCompletedDrawing = true; }
  219387. #endif
  219388. private:
  219389. enum { repaintTimerPeriod = 1000 / 100 };
  219390. LinuxComponentPeer* const peer;
  219391. Image image;
  219392. uint32 lastTimeImageUsed;
  219393. RectangleList regionsNeedingRepaint;
  219394. #if JUCE_USE_XSHM
  219395. bool useARGBImagesForRendering, shmCompletedDrawing;
  219396. #endif
  219397. LinuxRepaintManager (const LinuxRepaintManager&);
  219398. LinuxRepaintManager& operator= (const LinuxRepaintManager&);
  219399. };
  219400. ScopedPointer <LinuxRepaintManager> repainter;
  219401. friend class LinuxRepaintManager;
  219402. Window windowH, parentWindow;
  219403. int wx, wy, ww, wh;
  219404. Image taskbarImage;
  219405. bool fullScreen, mapped;
  219406. Visual* visual;
  219407. int depth;
  219408. BorderSize windowBorder;
  219409. struct MotifWmHints
  219410. {
  219411. unsigned long flags;
  219412. unsigned long functions;
  219413. unsigned long decorations;
  219414. long input_mode;
  219415. unsigned long status;
  219416. };
  219417. static void updateKeyStates (const int keycode, const bool press) throw()
  219418. {
  219419. const int keybyte = keycode >> 3;
  219420. const int keybit = (1 << (keycode & 7));
  219421. if (press)
  219422. Keys::keyStates [keybyte] |= keybit;
  219423. else
  219424. Keys::keyStates [keybyte] &= ~keybit;
  219425. }
  219426. static void updateKeyModifiers (const int status) throw()
  219427. {
  219428. int keyMods = 0;
  219429. if (status & ShiftMask) keyMods |= ModifierKeys::shiftModifier;
  219430. if (status & ControlMask) keyMods |= ModifierKeys::ctrlModifier;
  219431. if (status & Keys::AltMask) keyMods |= ModifierKeys::altModifier;
  219432. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  219433. Keys::numLock = ((status & Keys::NumLockMask) != 0);
  219434. Keys::capsLock = ((status & LockMask) != 0);
  219435. }
  219436. static bool updateKeyModifiersFromSym (KeySym sym, const bool press) throw()
  219437. {
  219438. int modifier = 0;
  219439. bool isModifier = true;
  219440. switch (sym)
  219441. {
  219442. case XK_Shift_L:
  219443. case XK_Shift_R:
  219444. modifier = ModifierKeys::shiftModifier;
  219445. break;
  219446. case XK_Control_L:
  219447. case XK_Control_R:
  219448. modifier = ModifierKeys::ctrlModifier;
  219449. break;
  219450. case XK_Alt_L:
  219451. case XK_Alt_R:
  219452. modifier = ModifierKeys::altModifier;
  219453. break;
  219454. case XK_Num_Lock:
  219455. if (press)
  219456. Keys::numLock = ! Keys::numLock;
  219457. break;
  219458. case XK_Caps_Lock:
  219459. if (press)
  219460. Keys::capsLock = ! Keys::capsLock;
  219461. break;
  219462. case XK_Scroll_Lock:
  219463. break;
  219464. default:
  219465. isModifier = false;
  219466. break;
  219467. }
  219468. if (modifier != 0)
  219469. {
  219470. if (press)
  219471. currentModifiers = currentModifiers.withFlags (modifier);
  219472. else
  219473. currentModifiers = currentModifiers.withoutFlags (modifier);
  219474. }
  219475. return isModifier;
  219476. }
  219477. // Alt and Num lock are not defined by standard X
  219478. // modifier constants: check what they're mapped to
  219479. static void updateModifierMappings() throw()
  219480. {
  219481. ScopedXLock xlock;
  219482. const int altLeftCode = XKeysymToKeycode (display, XK_Alt_L);
  219483. const int numLockCode = XKeysymToKeycode (display, XK_Num_Lock);
  219484. Keys::AltMask = 0;
  219485. Keys::NumLockMask = 0;
  219486. XModifierKeymap* mapping = XGetModifierMapping (display);
  219487. if (mapping)
  219488. {
  219489. for (int i = 0; i < 8; i++)
  219490. {
  219491. if (mapping->modifiermap [i << 1] == altLeftCode)
  219492. Keys::AltMask = 1 << i;
  219493. else if (mapping->modifiermap [i << 1] == numLockCode)
  219494. Keys::NumLockMask = 1 << i;
  219495. }
  219496. XFreeModifiermap (mapping);
  219497. }
  219498. }
  219499. void removeWindowDecorations (Window wndH)
  219500. {
  219501. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  219502. if (hints != None)
  219503. {
  219504. MotifWmHints motifHints;
  219505. zerostruct (motifHints);
  219506. motifHints.flags = 2; /* MWM_HINTS_DECORATIONS */
  219507. motifHints.decorations = 0;
  219508. ScopedXLock xlock;
  219509. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  219510. (unsigned char*) &motifHints, 4);
  219511. }
  219512. hints = XInternAtom (display, "_WIN_HINTS", True);
  219513. if (hints != None)
  219514. {
  219515. long gnomeHints = 0;
  219516. ScopedXLock xlock;
  219517. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  219518. (unsigned char*) &gnomeHints, 1);
  219519. }
  219520. hints = XInternAtom (display, "KWM_WIN_DECORATION", True);
  219521. if (hints != None)
  219522. {
  219523. long kwmHints = 2; /*KDE_tinyDecoration*/
  219524. ScopedXLock xlock;
  219525. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  219526. (unsigned char*) &kwmHints, 1);
  219527. }
  219528. }
  219529. void addWindowButtons (Window wndH)
  219530. {
  219531. ScopedXLock xlock;
  219532. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  219533. if (hints != None)
  219534. {
  219535. MotifWmHints motifHints;
  219536. zerostruct (motifHints);
  219537. motifHints.flags = 1 | 2; /* MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS */
  219538. motifHints.decorations = 2 /* MWM_DECOR_BORDER */ | 8 /* MWM_DECOR_TITLE */ | 16; /* MWM_DECOR_MENU */
  219539. motifHints.functions = 4 /* MWM_FUNC_MOVE */;
  219540. if ((styleFlags & windowHasCloseButton) != 0)
  219541. motifHints.functions |= 32; /* MWM_FUNC_CLOSE */
  219542. if ((styleFlags & windowHasMinimiseButton) != 0)
  219543. {
  219544. motifHints.functions |= 8; /* MWM_FUNC_MINIMIZE */
  219545. motifHints.decorations |= 0x20; /* MWM_DECOR_MINIMIZE */
  219546. }
  219547. if ((styleFlags & windowHasMaximiseButton) != 0)
  219548. {
  219549. motifHints.functions |= 0x10; /* MWM_FUNC_MAXIMIZE */
  219550. motifHints.decorations |= 0x40; /* MWM_DECOR_MAXIMIZE */
  219551. }
  219552. if ((styleFlags & windowIsResizable) != 0)
  219553. {
  219554. motifHints.functions |= 2; /* MWM_FUNC_RESIZE */
  219555. motifHints.decorations |= 0x4; /* MWM_DECOR_RESIZEH */
  219556. }
  219557. XChangeProperty (display, wndH, hints, hints, 32, 0, (unsigned char*) &motifHints, 5);
  219558. }
  219559. hints = XInternAtom (display, "_NET_WM_ALLOWED_ACTIONS", True);
  219560. if (hints != None)
  219561. {
  219562. int netHints [6];
  219563. int num = 0;
  219564. if ((styleFlags & windowIsResizable) != 0)
  219565. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_RESIZE", True);
  219566. if ((styleFlags & windowHasMaximiseButton) != 0)
  219567. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_FULLSCREEN", True);
  219568. if ((styleFlags & windowHasMinimiseButton) != 0)
  219569. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_MINIMIZE", True);
  219570. if ((styleFlags & windowHasCloseButton) != 0)
  219571. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_CLOSE", True);
  219572. XChangeProperty (display, wndH, hints, XA_ATOM, 32, PropModeReplace, (unsigned char*) &netHints, num);
  219573. }
  219574. }
  219575. void setWindowType()
  219576. {
  219577. int netHints [2];
  219578. int numHints = 0;
  219579. if ((styleFlags & windowIsTemporary) != 0
  219580. || ((styleFlags & windowHasDropShadow) == 0 && Desktop::canUseSemiTransparentWindows()))
  219581. netHints [numHints++] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_COMBO", True);
  219582. else
  219583. netHints [numHints++] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_NORMAL", True);
  219584. netHints[numHints++] = XInternAtom (display, "_KDE_NET_WM_WINDOW_TYPE_OVERRIDE", True);
  219585. XChangeProperty (display, windowH, Atoms::WindowType, XA_ATOM, 32, PropModeReplace,
  219586. (unsigned char*) &netHints, numHints);
  219587. numHints = 0;
  219588. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  219589. netHints [numHints++] = XInternAtom (display, "_NET_WM_STATE_SKIP_TASKBAR", True);
  219590. if (component->isAlwaysOnTop())
  219591. netHints [numHints++] = XInternAtom (display, "_NET_WM_STATE_ABOVE", True);
  219592. if (numHints > 0)
  219593. XChangeProperty (display, windowH, Atoms::WindowState, XA_ATOM, 32, PropModeReplace,
  219594. (unsigned char*) &netHints, numHints);
  219595. }
  219596. void createWindow()
  219597. {
  219598. ScopedXLock xlock;
  219599. Atoms::initialiseAtoms();
  219600. resetDragAndDrop();
  219601. // Get defaults for various properties
  219602. const int screen = DefaultScreen (display);
  219603. Window root = RootWindow (display, screen);
  219604. // Try to obtain a 32-bit visual or fallback to 24 or 16
  219605. visual = Visuals::findVisualFormat ((styleFlags & windowIsSemiTransparent) ? 32 : 24, depth);
  219606. if (visual == 0)
  219607. {
  219608. Logger::outputDebugString ("ERROR: System doesn't support 32, 24 or 16 bit RGB display.\n");
  219609. Process::terminate();
  219610. }
  219611. // Create and install a colormap suitable fr our visual
  219612. Colormap colormap = XCreateColormap (display, root, visual, AllocNone);
  219613. XInstallColormap (display, colormap);
  219614. // Set up the window attributes
  219615. XSetWindowAttributes swa;
  219616. swa.border_pixel = 0;
  219617. swa.background_pixmap = None;
  219618. swa.colormap = colormap;
  219619. swa.event_mask = getAllEventsMask();
  219620. windowH = XCreateWindow (display, root,
  219621. 0, 0, 1, 1,
  219622. 0, depth, InputOutput, visual,
  219623. CWBorderPixel | CWColormap | CWBackPixmap | CWEventMask,
  219624. &swa);
  219625. XGrabButton (display, AnyButton, AnyModifier, windowH, False,
  219626. ButtonPressMask | ButtonReleaseMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask,
  219627. GrabModeAsync, GrabModeAsync, None, None);
  219628. // Set the window context to identify the window handle object
  219629. if (XSaveContext (display, (XID) windowH, windowHandleXContext, (XPointer) this))
  219630. {
  219631. // Failed
  219632. jassertfalse;
  219633. Logger::outputDebugString ("Failed to create context information for window.\n");
  219634. XDestroyWindow (display, windowH);
  219635. windowH = 0;
  219636. return;
  219637. }
  219638. // Set window manager hints
  219639. XWMHints* wmHints = XAllocWMHints();
  219640. wmHints->flags = InputHint | StateHint;
  219641. wmHints->input = True; // Locally active input model
  219642. wmHints->initial_state = NormalState;
  219643. XSetWMHints (display, windowH, wmHints);
  219644. XFree (wmHints);
  219645. // Set the window type
  219646. setWindowType();
  219647. // Define decoration
  219648. if ((styleFlags & windowHasTitleBar) == 0)
  219649. removeWindowDecorations (windowH);
  219650. else
  219651. addWindowButtons (windowH);
  219652. // Set window name
  219653. setWindowTitle (windowH, getComponent()->getName());
  219654. // Associate the PID, allowing to be shut down when something goes wrong
  219655. unsigned long pid = getpid();
  219656. XChangeProperty (display, windowH, Atoms::Pid, XA_CARDINAL, 32, PropModeReplace,
  219657. (unsigned char*) &pid, 1);
  219658. // Set window manager protocols
  219659. XChangeProperty (display, windowH, Atoms::Protocols, XA_ATOM, 32, PropModeReplace,
  219660. (unsigned char*) Atoms::ProtocolList, 2);
  219661. // Set drag and drop flags
  219662. XChangeProperty (display, windowH, Atoms::XdndTypeList, XA_ATOM, 32, PropModeReplace,
  219663. (const unsigned char*) Atoms::allowedMimeTypes, numElementsInArray (Atoms::allowedMimeTypes));
  219664. XChangeProperty (display, windowH, Atoms::XdndActionList, XA_ATOM, 32, PropModeReplace,
  219665. (const unsigned char*) Atoms::allowedActions, numElementsInArray (Atoms::allowedActions));
  219666. XChangeProperty (display, windowH, Atoms::XdndActionDescription, XA_STRING, 8, PropModeReplace,
  219667. (const unsigned char*) "", 0);
  219668. unsigned long dndVersion = Atoms::DndVersion;
  219669. XChangeProperty (display, windowH, Atoms::XdndAware, XA_ATOM, 32, PropModeReplace,
  219670. (const unsigned char*) &dndVersion, 1);
  219671. // Initialise the pointer and keyboard mapping
  219672. // This is not the same as the logical pointer mapping the X server uses:
  219673. // we don't mess with this.
  219674. static bool mappingInitialised = false;
  219675. if (! mappingInitialised)
  219676. {
  219677. mappingInitialised = true;
  219678. const int numButtons = XGetPointerMapping (display, 0, 0);
  219679. if (numButtons == 2)
  219680. {
  219681. pointerMap[0] = Keys::LeftButton;
  219682. pointerMap[1] = Keys::RightButton;
  219683. pointerMap[2] = pointerMap[3] = pointerMap[4] = Keys::NoButton;
  219684. }
  219685. else if (numButtons >= 3)
  219686. {
  219687. pointerMap[0] = Keys::LeftButton;
  219688. pointerMap[1] = Keys::MiddleButton;
  219689. pointerMap[2] = Keys::RightButton;
  219690. if (numButtons >= 5)
  219691. {
  219692. pointerMap[3] = Keys::WheelUp;
  219693. pointerMap[4] = Keys::WheelDown;
  219694. }
  219695. }
  219696. updateModifierMappings();
  219697. }
  219698. }
  219699. void destroyWindow()
  219700. {
  219701. ScopedXLock xlock;
  219702. XPointer handlePointer;
  219703. if (! XFindContext (display, (XID) windowH, windowHandleXContext, &handlePointer))
  219704. XDeleteContext (display, (XID) windowH, windowHandleXContext);
  219705. XDestroyWindow (display, windowH);
  219706. // Wait for it to complete and then remove any events for this
  219707. // window from the event queue.
  219708. XSync (display, false);
  219709. XEvent event;
  219710. while (XCheckWindowEvent (display, windowH, getAllEventsMask(), &event) == True)
  219711. {}
  219712. }
  219713. static int getAllEventsMask() throw()
  219714. {
  219715. return NoEventMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask
  219716. | EnterWindowMask | LeaveWindowMask | PointerMotionMask | KeymapStateMask
  219717. | ExposureMask | StructureNotifyMask | FocusChangeMask;
  219718. }
  219719. static int64 getEventTime (::Time t)
  219720. {
  219721. static int64 eventTimeOffset = 0x12345678;
  219722. const int64 thisMessageTime = t;
  219723. if (eventTimeOffset == 0x12345678)
  219724. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  219725. return eventTimeOffset + thisMessageTime;
  219726. }
  219727. static void setWindowTitle (Window xwin, const String& title)
  219728. {
  219729. XTextProperty nameProperty;
  219730. char* strings[] = { const_cast <char*> (title.toUTF8()) };
  219731. ScopedXLock xlock;
  219732. if (XStringListToTextProperty (strings, 1, &nameProperty))
  219733. {
  219734. XSetWMName (display, xwin, &nameProperty);
  219735. XSetWMIconName (display, xwin, &nameProperty);
  219736. XFree (nameProperty.value);
  219737. }
  219738. }
  219739. void updateBorderSize()
  219740. {
  219741. if ((styleFlags & windowHasTitleBar) == 0)
  219742. {
  219743. windowBorder = BorderSize (0);
  219744. }
  219745. else if (windowBorder.getTopAndBottom() == 0 && windowBorder.getLeftAndRight() == 0)
  219746. {
  219747. ScopedXLock xlock;
  219748. Atom hints = XInternAtom (display, "_NET_FRAME_EXTENTS", True);
  219749. if (hints != None)
  219750. {
  219751. unsigned char* data = 0;
  219752. unsigned long nitems, bytesLeft;
  219753. Atom actualType;
  219754. int actualFormat;
  219755. if (XGetWindowProperty (display, windowH, hints, 0, 4, False,
  219756. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  219757. &data) == Success)
  219758. {
  219759. const unsigned long* const sizes = (const unsigned long*) data;
  219760. if (actualFormat == 32)
  219761. windowBorder = BorderSize ((int) sizes[2], (int) sizes[0],
  219762. (int) sizes[3], (int) sizes[1]);
  219763. XFree (data);
  219764. }
  219765. }
  219766. }
  219767. }
  219768. void updateBounds()
  219769. {
  219770. jassert (windowH != 0);
  219771. if (windowH != 0)
  219772. {
  219773. Window root, child;
  219774. unsigned int bw, depth;
  219775. ScopedXLock xlock;
  219776. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  219777. &wx, &wy, (unsigned int*) &ww, (unsigned int*) &wh,
  219778. &bw, &depth))
  219779. {
  219780. wx = wy = ww = wh = 0;
  219781. }
  219782. else if (! XTranslateCoordinates (display, windowH, root, 0, 0, &wx, &wy, &child))
  219783. {
  219784. wx = wy = 0;
  219785. }
  219786. }
  219787. }
  219788. void resetDragAndDrop()
  219789. {
  219790. dragAndDropFiles.clear();
  219791. lastDropPos = Point<int> (-1, -1);
  219792. dragAndDropCurrentMimeType = 0;
  219793. dragAndDropSourceWindow = 0;
  219794. srcMimeTypeAtomList.clear();
  219795. }
  219796. void sendDragAndDropMessage (XClientMessageEvent& msg)
  219797. {
  219798. msg.type = ClientMessage;
  219799. msg.display = display;
  219800. msg.window = dragAndDropSourceWindow;
  219801. msg.format = 32;
  219802. msg.data.l[0] = windowH;
  219803. ScopedXLock xlock;
  219804. XSendEvent (display, dragAndDropSourceWindow, False, 0, (XEvent*) &msg);
  219805. }
  219806. void sendDragAndDropStatus (const bool acceptDrop, Atom dropAction)
  219807. {
  219808. XClientMessageEvent msg;
  219809. zerostruct (msg);
  219810. msg.message_type = Atoms::XdndStatus;
  219811. msg.data.l[1] = (acceptDrop ? 1 : 0) | 2; // 2 indicates that we want to receive position messages
  219812. msg.data.l[4] = dropAction;
  219813. sendDragAndDropMessage (msg);
  219814. }
  219815. void sendDragAndDropLeave()
  219816. {
  219817. XClientMessageEvent msg;
  219818. zerostruct (msg);
  219819. msg.message_type = Atoms::XdndLeave;
  219820. sendDragAndDropMessage (msg);
  219821. }
  219822. void sendDragAndDropFinish()
  219823. {
  219824. XClientMessageEvent msg;
  219825. zerostruct (msg);
  219826. msg.message_type = Atoms::XdndFinished;
  219827. sendDragAndDropMessage (msg);
  219828. }
  219829. void handleDragAndDropStatus (const XClientMessageEvent* const clientMsg)
  219830. {
  219831. if ((clientMsg->data.l[1] & 1) == 0)
  219832. {
  219833. sendDragAndDropLeave();
  219834. if (dragAndDropFiles.size() > 0)
  219835. handleFileDragExit (dragAndDropFiles);
  219836. dragAndDropFiles.clear();
  219837. }
  219838. }
  219839. void handleDragAndDropPosition (const XClientMessageEvent* const clientMsg)
  219840. {
  219841. if (dragAndDropSourceWindow == 0)
  219842. return;
  219843. dragAndDropSourceWindow = clientMsg->data.l[0];
  219844. Point<int> dropPos ((int) clientMsg->data.l[2] >> 16,
  219845. (int) clientMsg->data.l[2] & 0xffff);
  219846. dropPos -= getScreenPosition();
  219847. if (lastDropPos != dropPos)
  219848. {
  219849. lastDropPos = dropPos;
  219850. dragAndDropTimestamp = clientMsg->data.l[3];
  219851. Atom targetAction = Atoms::XdndActionCopy;
  219852. for (int i = numElementsInArray (Atoms::allowedActions); --i >= 0;)
  219853. {
  219854. if ((Atom) clientMsg->data.l[4] == Atoms::allowedActions[i])
  219855. {
  219856. targetAction = Atoms::allowedActions[i];
  219857. break;
  219858. }
  219859. }
  219860. sendDragAndDropStatus (true, targetAction);
  219861. if (dragAndDropFiles.size() == 0)
  219862. updateDraggedFileList (clientMsg);
  219863. if (dragAndDropFiles.size() > 0)
  219864. handleFileDragMove (dragAndDropFiles, dropPos);
  219865. }
  219866. }
  219867. void handleDragAndDropDrop (const XClientMessageEvent* const clientMsg)
  219868. {
  219869. if (dragAndDropFiles.size() == 0)
  219870. updateDraggedFileList (clientMsg);
  219871. const StringArray files (dragAndDropFiles);
  219872. const Point<int> lastPos (lastDropPos);
  219873. sendDragAndDropFinish();
  219874. resetDragAndDrop();
  219875. if (files.size() > 0)
  219876. handleFileDragDrop (files, lastPos);
  219877. }
  219878. void handleDragAndDropEnter (const XClientMessageEvent* const clientMsg)
  219879. {
  219880. dragAndDropFiles.clear();
  219881. srcMimeTypeAtomList.clear();
  219882. dragAndDropCurrentMimeType = 0;
  219883. const unsigned long dndCurrentVersion = static_cast <unsigned long> (clientMsg->data.l[1] & 0xff000000) >> 24;
  219884. if (dndCurrentVersion < 3 || dndCurrentVersion > Atoms::DndVersion)
  219885. {
  219886. dragAndDropSourceWindow = 0;
  219887. return;
  219888. }
  219889. dragAndDropSourceWindow = clientMsg->data.l[0];
  219890. if ((clientMsg->data.l[1] & 1) != 0)
  219891. {
  219892. Atom actual;
  219893. int format;
  219894. unsigned long count = 0, remaining = 0;
  219895. unsigned char* data = 0;
  219896. ScopedXLock xlock;
  219897. XGetWindowProperty (display, dragAndDropSourceWindow, Atoms::XdndTypeList,
  219898. 0, 0x8000000L, False, XA_ATOM, &actual, &format,
  219899. &count, &remaining, &data);
  219900. if (data != 0)
  219901. {
  219902. if (actual == XA_ATOM && format == 32 && count != 0)
  219903. {
  219904. const unsigned long* const types = (const unsigned long*) data;
  219905. for (unsigned int i = 0; i < count; ++i)
  219906. if (types[i] != None)
  219907. srcMimeTypeAtomList.add (types[i]);
  219908. }
  219909. XFree (data);
  219910. }
  219911. }
  219912. if (srcMimeTypeAtomList.size() == 0)
  219913. {
  219914. for (int i = 2; i < 5; ++i)
  219915. if (clientMsg->data.l[i] != None)
  219916. srcMimeTypeAtomList.add (clientMsg->data.l[i]);
  219917. if (srcMimeTypeAtomList.size() == 0)
  219918. {
  219919. dragAndDropSourceWindow = 0;
  219920. return;
  219921. }
  219922. }
  219923. for (int i = 0; i < srcMimeTypeAtomList.size() && dragAndDropCurrentMimeType == 0; ++i)
  219924. for (int j = 0; j < numElementsInArray (Atoms::allowedMimeTypes); ++j)
  219925. if (srcMimeTypeAtomList[i] == Atoms::allowedMimeTypes[j])
  219926. dragAndDropCurrentMimeType = Atoms::allowedMimeTypes[j];
  219927. handleDragAndDropPosition (clientMsg);
  219928. }
  219929. void handleDragAndDropSelection (const XEvent* const evt)
  219930. {
  219931. dragAndDropFiles.clear();
  219932. if (evt->xselection.property != 0)
  219933. {
  219934. StringArray lines;
  219935. {
  219936. MemoryBlock dropData;
  219937. for (;;)
  219938. {
  219939. Atom actual;
  219940. uint8* data = 0;
  219941. unsigned long count = 0, remaining = 0;
  219942. int format = 0;
  219943. ScopedXLock xlock;
  219944. if (XGetWindowProperty (display, evt->xany.window, evt->xselection.property,
  219945. dropData.getSize() / 4, 65536, 1, AnyPropertyType, &actual,
  219946. &format, &count, &remaining, &data) == Success)
  219947. {
  219948. dropData.append (data, count * format / 8);
  219949. XFree (data);
  219950. if (remaining == 0)
  219951. break;
  219952. }
  219953. else
  219954. {
  219955. XFree (data);
  219956. break;
  219957. }
  219958. }
  219959. lines.addLines (dropData.toString());
  219960. }
  219961. for (int i = 0; i < lines.size(); ++i)
  219962. dragAndDropFiles.add (URL::removeEscapeChars (lines[i].fromFirstOccurrenceOf ("file://", false, true)));
  219963. dragAndDropFiles.trim();
  219964. dragAndDropFiles.removeEmptyStrings();
  219965. }
  219966. }
  219967. void updateDraggedFileList (const XClientMessageEvent* const clientMsg)
  219968. {
  219969. dragAndDropFiles.clear();
  219970. if (dragAndDropSourceWindow != None
  219971. && dragAndDropCurrentMimeType != 0)
  219972. {
  219973. dragAndDropTimestamp = clientMsg->data.l[2];
  219974. ScopedXLock xlock;
  219975. XConvertSelection (display,
  219976. Atoms::XdndSelection,
  219977. dragAndDropCurrentMimeType,
  219978. XInternAtom (display, "JXSelectionWindowProperty", 0),
  219979. windowH,
  219980. dragAndDropTimestamp);
  219981. }
  219982. }
  219983. StringArray dragAndDropFiles;
  219984. int dragAndDropTimestamp;
  219985. Point<int> lastDropPos;
  219986. Atom dragAndDropCurrentMimeType;
  219987. Window dragAndDropSourceWindow;
  219988. Array <Atom> srcMimeTypeAtomList;
  219989. static int pointerMap[5];
  219990. static Point<int> lastMousePos;
  219991. static void clearLastMousePos() throw()
  219992. {
  219993. lastMousePos = Point<int> (0x100000, 0x100000);
  219994. }
  219995. };
  219996. ModifierKeys LinuxComponentPeer::currentModifiers;
  219997. bool LinuxComponentPeer::isActiveApplication = false;
  219998. int LinuxComponentPeer::pointerMap[5];
  219999. Point<int> LinuxComponentPeer::lastMousePos;
  220000. bool Process::isForegroundProcess()
  220001. {
  220002. return LinuxComponentPeer::isActiveApplication;
  220003. }
  220004. void ModifierKeys::updateCurrentModifiers() throw()
  220005. {
  220006. currentModifiers = LinuxComponentPeer::currentModifiers;
  220007. }
  220008. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  220009. {
  220010. Window root, child;
  220011. int x, y, winx, winy;
  220012. unsigned int mask;
  220013. int mouseMods = 0;
  220014. ScopedXLock xlock;
  220015. if (XQueryPointer (display, RootWindow (display, DefaultScreen (display)),
  220016. &root, &child, &x, &y, &winx, &winy, &mask) != False)
  220017. {
  220018. if ((mask & Button1Mask) != 0) mouseMods |= ModifierKeys::leftButtonModifier;
  220019. if ((mask & Button2Mask) != 0) mouseMods |= ModifierKeys::middleButtonModifier;
  220020. if ((mask & Button3Mask) != 0) mouseMods |= ModifierKeys::rightButtonModifier;
  220021. }
  220022. LinuxComponentPeer::currentModifiers = LinuxComponentPeer::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  220023. return LinuxComponentPeer::currentModifiers;
  220024. }
  220025. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  220026. {
  220027. if (enableOrDisable)
  220028. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  220029. }
  220030. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  220031. {
  220032. return new LinuxComponentPeer (this, styleFlags);
  220033. }
  220034. // (this callback is hooked up in the messaging code)
  220035. void juce_windowMessageReceive (XEvent* event)
  220036. {
  220037. if (event->xany.window != None)
  220038. {
  220039. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (event->xany.window);
  220040. if (ComponentPeer::isValidPeer (peer))
  220041. peer->handleWindowMessage (event);
  220042. }
  220043. else
  220044. {
  220045. switch (event->xany.type)
  220046. {
  220047. case KeymapNotify:
  220048. {
  220049. const XKeymapEvent* const keymapEvent = (const XKeymapEvent*) &event->xkeymap;
  220050. memcpy (Keys::keyStates, keymapEvent->key_vector, 32);
  220051. break;
  220052. }
  220053. default:
  220054. break;
  220055. }
  220056. }
  220057. }
  220058. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool /*clipToWorkArea*/)
  220059. {
  220060. if (display == 0)
  220061. return;
  220062. #if JUCE_USE_XINERAMA
  220063. int major_opcode, first_event, first_error;
  220064. ScopedXLock xlock;
  220065. if (XQueryExtension (display, "XINERAMA", &major_opcode, &first_event, &first_error))
  220066. {
  220067. typedef Bool (*tXineramaIsActive) (Display*);
  220068. typedef XineramaScreenInfo* (*tXineramaQueryScreens) (Display*, int*);
  220069. static tXineramaIsActive xXineramaIsActive = 0;
  220070. static tXineramaQueryScreens xXineramaQueryScreens = 0;
  220071. if (xXineramaIsActive == 0 || xXineramaQueryScreens == 0)
  220072. {
  220073. void* h = dlopen ("libXinerama.so", RTLD_GLOBAL | RTLD_NOW);
  220074. if (h == 0)
  220075. h = dlopen ("libXinerama.so.1", RTLD_GLOBAL | RTLD_NOW);
  220076. if (h != 0)
  220077. {
  220078. xXineramaIsActive = (tXineramaIsActive) dlsym (h, "XineramaIsActive");
  220079. xXineramaQueryScreens = (tXineramaQueryScreens) dlsym (h, "XineramaQueryScreens");
  220080. }
  220081. }
  220082. if (xXineramaIsActive != 0
  220083. && xXineramaQueryScreens != 0
  220084. && xXineramaIsActive (display))
  220085. {
  220086. int numMonitors = 0;
  220087. XineramaScreenInfo* const screens = xXineramaQueryScreens (display, &numMonitors);
  220088. if (screens != 0)
  220089. {
  220090. for (int i = numMonitors; --i >= 0;)
  220091. {
  220092. int index = screens[i].screen_number;
  220093. if (index >= 0)
  220094. {
  220095. while (monitorCoords.size() < index)
  220096. monitorCoords.add (Rectangle<int>());
  220097. monitorCoords.set (index, Rectangle<int> (screens[i].x_org,
  220098. screens[i].y_org,
  220099. screens[i].width,
  220100. screens[i].height));
  220101. }
  220102. }
  220103. XFree (screens);
  220104. }
  220105. }
  220106. }
  220107. if (monitorCoords.size() == 0)
  220108. #endif
  220109. {
  220110. Atom hints = XInternAtom (display, "_NET_WORKAREA", True);
  220111. if (hints != None)
  220112. {
  220113. const int numMonitors = ScreenCount (display);
  220114. for (int i = 0; i < numMonitors; ++i)
  220115. {
  220116. Window root = RootWindow (display, i);
  220117. unsigned long nitems, bytesLeft;
  220118. Atom actualType;
  220119. int actualFormat;
  220120. unsigned char* data = 0;
  220121. if (XGetWindowProperty (display, root, hints, 0, 4, False,
  220122. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  220123. &data) == Success)
  220124. {
  220125. const long* const position = (const long*) data;
  220126. if (actualType == XA_CARDINAL && actualFormat == 32 && nitems == 4)
  220127. monitorCoords.add (Rectangle<int> (position[0], position[1],
  220128. position[2], position[3]));
  220129. XFree (data);
  220130. }
  220131. }
  220132. }
  220133. if (monitorCoords.size() == 0)
  220134. {
  220135. monitorCoords.add (Rectangle<int> (0, 0,
  220136. DisplayWidth (display, DefaultScreen (display)),
  220137. DisplayHeight (display, DefaultScreen (display))));
  220138. }
  220139. }
  220140. }
  220141. void Desktop::createMouseInputSources()
  220142. {
  220143. mouseSources.add (new MouseInputSource (0, true));
  220144. }
  220145. bool Desktop::canUseSemiTransparentWindows() throw()
  220146. {
  220147. int matchedDepth = 0;
  220148. const int desiredDepth = 32;
  220149. return Visuals::findVisualFormat (desiredDepth, matchedDepth) != 0
  220150. && (matchedDepth == desiredDepth);
  220151. }
  220152. const Point<int> Desktop::getMousePosition()
  220153. {
  220154. Window root, child;
  220155. int x, y, winx, winy;
  220156. unsigned int mask;
  220157. ScopedXLock xlock;
  220158. if (XQueryPointer (display,
  220159. RootWindow (display, DefaultScreen (display)),
  220160. &root, &child,
  220161. &x, &y, &winx, &winy, &mask) == False)
  220162. {
  220163. // Pointer not on the default screen
  220164. x = y = -1;
  220165. }
  220166. return Point<int> (x, y);
  220167. }
  220168. void Desktop::setMousePosition (const Point<int>& newPosition)
  220169. {
  220170. ScopedXLock xlock;
  220171. Window root = RootWindow (display, DefaultScreen (display));
  220172. XWarpPointer (display, None, root, 0, 0, 0, 0, newPosition.getX(), newPosition.getY());
  220173. }
  220174. static bool screenSaverAllowed = true;
  220175. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  220176. {
  220177. if (screenSaverAllowed != isEnabled)
  220178. {
  220179. screenSaverAllowed = isEnabled;
  220180. typedef void (*tXScreenSaverSuspend) (Display*, Bool);
  220181. static tXScreenSaverSuspend xScreenSaverSuspend = 0;
  220182. if (xScreenSaverSuspend == 0)
  220183. {
  220184. void* h = dlopen ("libXss.so", RTLD_GLOBAL | RTLD_NOW);
  220185. if (h != 0)
  220186. xScreenSaverSuspend = (tXScreenSaverSuspend) dlsym (h, "XScreenSaverSuspend");
  220187. }
  220188. ScopedXLock xlock;
  220189. if (xScreenSaverSuspend != 0)
  220190. xScreenSaverSuspend (display, ! isEnabled);
  220191. }
  220192. }
  220193. bool Desktop::isScreenSaverEnabled()
  220194. {
  220195. return screenSaverAllowed;
  220196. }
  220197. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  220198. {
  220199. ScopedXLock xlock;
  220200. const unsigned int imageW = image.getWidth();
  220201. const unsigned int imageH = image.getHeight();
  220202. #if JUCE_USE_XCURSOR
  220203. {
  220204. typedef XcursorBool (*tXcursorSupportsARGB) (Display*);
  220205. typedef XcursorImage* (*tXcursorImageCreate) (int, int);
  220206. typedef void (*tXcursorImageDestroy) (XcursorImage*);
  220207. typedef Cursor (*tXcursorImageLoadCursor) (Display*, const XcursorImage*);
  220208. static tXcursorSupportsARGB xXcursorSupportsARGB = 0;
  220209. static tXcursorImageCreate xXcursorImageCreate = 0;
  220210. static tXcursorImageDestroy xXcursorImageDestroy = 0;
  220211. static tXcursorImageLoadCursor xXcursorImageLoadCursor = 0;
  220212. static bool hasBeenLoaded = false;
  220213. if (! hasBeenLoaded)
  220214. {
  220215. hasBeenLoaded = true;
  220216. void* h = dlopen ("libXcursor.so", RTLD_GLOBAL | RTLD_NOW);
  220217. if (h != 0)
  220218. {
  220219. xXcursorSupportsARGB = (tXcursorSupportsARGB) dlsym (h, "XcursorSupportsARGB");
  220220. xXcursorImageCreate = (tXcursorImageCreate) dlsym (h, "XcursorImageCreate");
  220221. xXcursorImageLoadCursor = (tXcursorImageLoadCursor) dlsym (h, "XcursorImageLoadCursor");
  220222. xXcursorImageDestroy = (tXcursorImageDestroy) dlsym (h, "XcursorImageDestroy");
  220223. if (xXcursorSupportsARGB == 0 || xXcursorImageCreate == 0
  220224. || xXcursorImageLoadCursor == 0 || xXcursorImageDestroy == 0
  220225. || ! xXcursorSupportsARGB (display))
  220226. xXcursorSupportsARGB = 0;
  220227. }
  220228. }
  220229. if (xXcursorSupportsARGB != 0)
  220230. {
  220231. XcursorImage* xcImage = xXcursorImageCreate (imageW, imageH);
  220232. if (xcImage != 0)
  220233. {
  220234. xcImage->xhot = hotspotX;
  220235. xcImage->yhot = hotspotY;
  220236. XcursorPixel* dest = xcImage->pixels;
  220237. for (int y = 0; y < (int) imageH; ++y)
  220238. for (int x = 0; x < (int) imageW; ++x)
  220239. *dest++ = image.getPixelAt (x, y).getARGB();
  220240. void* result = (void*) xXcursorImageLoadCursor (display, xcImage);
  220241. xXcursorImageDestroy (xcImage);
  220242. if (result != 0)
  220243. return result;
  220244. }
  220245. }
  220246. }
  220247. #endif
  220248. Window root = RootWindow (display, DefaultScreen (display));
  220249. unsigned int cursorW, cursorH;
  220250. if (! XQueryBestCursor (display, root, imageW, imageH, &cursorW, &cursorH))
  220251. return 0;
  220252. Image im (Image::ARGB, cursorW, cursorH, true);
  220253. {
  220254. Graphics g (im);
  220255. if (imageW > cursorW || imageH > cursorH)
  220256. {
  220257. hotspotX = (hotspotX * cursorW) / imageW;
  220258. hotspotY = (hotspotY * cursorH) / imageH;
  220259. g.drawImageWithin (image, 0, 0, imageW, imageH,
  220260. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  220261. false);
  220262. }
  220263. else
  220264. {
  220265. g.drawImageAt (image, 0, 0);
  220266. }
  220267. }
  220268. const int stride = (cursorW + 7) >> 3;
  220269. HeapBlock <char> maskPlane, sourcePlane;
  220270. maskPlane.calloc (stride * cursorH);
  220271. sourcePlane.calloc (stride * cursorH);
  220272. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  220273. for (int y = cursorH; --y >= 0;)
  220274. {
  220275. for (int x = cursorW; --x >= 0;)
  220276. {
  220277. const char mask = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  220278. const int offset = y * stride + (x >> 3);
  220279. const Colour c (im.getPixelAt (x, y));
  220280. if (c.getAlpha() >= 128)
  220281. maskPlane[offset] |= mask;
  220282. if (c.getBrightness() >= 0.5f)
  220283. sourcePlane[offset] |= mask;
  220284. }
  220285. }
  220286. Pixmap sourcePixmap = XCreatePixmapFromBitmapData (display, root, sourcePlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  220287. Pixmap maskPixmap = XCreatePixmapFromBitmapData (display, root, maskPlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  220288. XColor white, black;
  220289. black.red = black.green = black.blue = 0;
  220290. white.red = white.green = white.blue = 0xffff;
  220291. void* result = (void*) XCreatePixmapCursor (display, sourcePixmap, maskPixmap, &white, &black, hotspotX, hotspotY);
  220292. XFreePixmap (display, sourcePixmap);
  220293. XFreePixmap (display, maskPixmap);
  220294. return result;
  220295. }
  220296. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool)
  220297. {
  220298. ScopedXLock xlock;
  220299. if (cursorHandle != 0)
  220300. XFreeCursor (display, (Cursor) cursorHandle);
  220301. }
  220302. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  220303. {
  220304. unsigned int shape;
  220305. switch (type)
  220306. {
  220307. case NormalCursor: return None; // Use parent cursor
  220308. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 16, 16, true), 0, 0);
  220309. case WaitCursor: shape = XC_watch; break;
  220310. case IBeamCursor: shape = XC_xterm; break;
  220311. case PointingHandCursor: shape = XC_hand2; break;
  220312. case LeftRightResizeCursor: shape = XC_sb_h_double_arrow; break;
  220313. case UpDownResizeCursor: shape = XC_sb_v_double_arrow; break;
  220314. case UpDownLeftRightResizeCursor: shape = XC_fleur; break;
  220315. case TopEdgeResizeCursor: shape = XC_top_side; break;
  220316. case BottomEdgeResizeCursor: shape = XC_bottom_side; break;
  220317. case LeftEdgeResizeCursor: shape = XC_left_side; break;
  220318. case RightEdgeResizeCursor: shape = XC_right_side; break;
  220319. case TopLeftCornerResizeCursor: shape = XC_top_left_corner; break;
  220320. case TopRightCornerResizeCursor: shape = XC_top_right_corner; break;
  220321. case BottomLeftCornerResizeCursor: shape = XC_bottom_left_corner; break;
  220322. case BottomRightCornerResizeCursor: shape = XC_bottom_right_corner; break;
  220323. case CrosshairCursor: shape = XC_crosshair; break;
  220324. case DraggingHandCursor:
  220325. {
  220326. static unsigned char dragHandData[] = { 71,73,70,56,57,97,16,0,16,0,145,2,0,0,0,0,255,255,255,0,
  220327. 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,
  220328. 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 };
  220329. const int dragHandDataSize = 99;
  220330. return createMouseCursorFromImage (ImageFileFormat::loadFrom (dragHandData, dragHandDataSize), 8, 7);
  220331. }
  220332. case CopyingCursor:
  220333. {
  220334. static unsigned char copyCursorData[] = { 71,73,70,56,57,97,21,0,21,0,145,0,0,0,0,0,255,255,255,0,
  220335. 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,
  220336. 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,
  220337. 252,114,147,74,83,5,50,68,147,208,217,16,71,149,252,124,5,0,59,0,0 };
  220338. const int copyCursorSize = 119;
  220339. return createMouseCursorFromImage (ImageFileFormat::loadFrom (copyCursorData, copyCursorSize), 1, 3);
  220340. }
  220341. default:
  220342. jassertfalse;
  220343. return None;
  220344. }
  220345. ScopedXLock xlock;
  220346. return (void*) XCreateFontCursor (display, shape);
  220347. }
  220348. void MouseCursor::showInWindow (ComponentPeer* peer) const
  220349. {
  220350. LinuxComponentPeer* const lp = dynamic_cast <LinuxComponentPeer*> (peer);
  220351. if (lp != 0)
  220352. lp->showMouseCursor ((Cursor) getHandle());
  220353. }
  220354. void MouseCursor::showInAllWindows() const
  220355. {
  220356. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  220357. showInWindow (ComponentPeer::getPeer (i));
  220358. }
  220359. const Image juce_createIconForFile (const File& file)
  220360. {
  220361. return Image();
  220362. }
  220363. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  220364. {
  220365. return createSoftwareImage (format, width, height, clearImage);
  220366. }
  220367. #if JUCE_OPENGL
  220368. class WindowedGLContext : public OpenGLContext
  220369. {
  220370. public:
  220371. WindowedGLContext (Component* const component,
  220372. const OpenGLPixelFormat& pixelFormat_,
  220373. GLXContext sharedContext)
  220374. : renderContext (0),
  220375. embeddedWindow (0),
  220376. pixelFormat (pixelFormat_)
  220377. {
  220378. jassert (component != 0);
  220379. LinuxComponentPeer* const peer = dynamic_cast <LinuxComponentPeer*> (component->getTopLevelComponent()->getPeer());
  220380. if (peer == 0)
  220381. return;
  220382. ScopedXLock xlock;
  220383. XSync (display, False);
  220384. GLint attribs [64];
  220385. int n = 0;
  220386. attribs[n++] = GLX_RGBA;
  220387. attribs[n++] = GLX_DOUBLEBUFFER;
  220388. attribs[n++] = GLX_RED_SIZE;
  220389. attribs[n++] = pixelFormat.redBits;
  220390. attribs[n++] = GLX_GREEN_SIZE;
  220391. attribs[n++] = pixelFormat.greenBits;
  220392. attribs[n++] = GLX_BLUE_SIZE;
  220393. attribs[n++] = pixelFormat.blueBits;
  220394. attribs[n++] = GLX_ALPHA_SIZE;
  220395. attribs[n++] = pixelFormat.alphaBits;
  220396. attribs[n++] = GLX_DEPTH_SIZE;
  220397. attribs[n++] = pixelFormat.depthBufferBits;
  220398. attribs[n++] = GLX_STENCIL_SIZE;
  220399. attribs[n++] = pixelFormat.stencilBufferBits;
  220400. attribs[n++] = GLX_ACCUM_RED_SIZE;
  220401. attribs[n++] = pixelFormat.accumulationBufferRedBits;
  220402. attribs[n++] = GLX_ACCUM_GREEN_SIZE;
  220403. attribs[n++] = pixelFormat.accumulationBufferGreenBits;
  220404. attribs[n++] = GLX_ACCUM_BLUE_SIZE;
  220405. attribs[n++] = pixelFormat.accumulationBufferBlueBits;
  220406. attribs[n++] = GLX_ACCUM_ALPHA_SIZE;
  220407. attribs[n++] = pixelFormat.accumulationBufferAlphaBits;
  220408. // xxx not sure how to do fullSceneAntiAliasingNumSamples on linux..
  220409. attribs[n++] = None;
  220410. XVisualInfo* const bestVisual = glXChooseVisual (display, DefaultScreen (display), attribs);
  220411. if (bestVisual == 0)
  220412. return;
  220413. renderContext = glXCreateContext (display, bestVisual, sharedContext, GL_TRUE);
  220414. Window windowH = (Window) peer->getNativeHandle();
  220415. Colormap colourMap = XCreateColormap (display, windowH, bestVisual->visual, AllocNone);
  220416. XSetWindowAttributes swa;
  220417. swa.colormap = colourMap;
  220418. swa.border_pixel = 0;
  220419. swa.event_mask = ExposureMask | StructureNotifyMask;
  220420. embeddedWindow = XCreateWindow (display, windowH,
  220421. 0, 0, 1, 1, 0,
  220422. bestVisual->depth,
  220423. InputOutput,
  220424. bestVisual->visual,
  220425. CWBorderPixel | CWColormap | CWEventMask,
  220426. &swa);
  220427. XSaveContext (display, (XID) embeddedWindow, windowHandleXContext, (XPointer) peer);
  220428. XMapWindow (display, embeddedWindow);
  220429. XFreeColormap (display, colourMap);
  220430. XFree (bestVisual);
  220431. XSync (display, False);
  220432. }
  220433. ~WindowedGLContext()
  220434. {
  220435. makeInactive();
  220436. ScopedXLock xlock;
  220437. glXDestroyContext (display, renderContext);
  220438. XUnmapWindow (display, embeddedWindow);
  220439. XDestroyWindow (display, embeddedWindow);
  220440. }
  220441. bool makeActive() const throw()
  220442. {
  220443. jassert (renderContext != 0);
  220444. ScopedXLock xlock;
  220445. return glXMakeCurrent (display, embeddedWindow, renderContext)
  220446. && XSync (display, False);
  220447. }
  220448. bool makeInactive() const throw()
  220449. {
  220450. ScopedXLock xlock;
  220451. return (! isActive()) || glXMakeCurrent (display, None, 0);
  220452. }
  220453. bool isActive() const throw()
  220454. {
  220455. ScopedXLock xlock;
  220456. return glXGetCurrentContext() == renderContext;
  220457. }
  220458. const OpenGLPixelFormat getPixelFormat() const
  220459. {
  220460. return pixelFormat;
  220461. }
  220462. void* getRawContext() const throw()
  220463. {
  220464. return renderContext;
  220465. }
  220466. void updateWindowPosition (int x, int y, int w, int h, int)
  220467. {
  220468. ScopedXLock xlock;
  220469. XMoveResizeWindow (display, embeddedWindow,
  220470. x, y, jmax (1, w), jmax (1, h));
  220471. }
  220472. void swapBuffers()
  220473. {
  220474. ScopedXLock xlock;
  220475. glXSwapBuffers (display, embeddedWindow);
  220476. }
  220477. bool setSwapInterval (const int numFramesPerSwap)
  220478. {
  220479. // xxx needs doing..
  220480. return false;
  220481. }
  220482. int getSwapInterval() const
  220483. {
  220484. // xxx needs doing..
  220485. return 0;
  220486. }
  220487. void repaint()
  220488. {
  220489. }
  220490. juce_UseDebuggingNewOperator
  220491. GLXContext renderContext;
  220492. private:
  220493. Window embeddedWindow;
  220494. OpenGLPixelFormat pixelFormat;
  220495. WindowedGLContext (const WindowedGLContext&);
  220496. WindowedGLContext& operator= (const WindowedGLContext&);
  220497. };
  220498. OpenGLContext* OpenGLComponent::createContext()
  220499. {
  220500. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  220501. contextToShareListsWith != 0 ? (GLXContext) contextToShareListsWith->getRawContext() : 0));
  220502. return (c->renderContext != 0) ? c.release() : 0;
  220503. }
  220504. void juce_glViewport (const int w, const int h)
  220505. {
  220506. glViewport (0, 0, w, h);
  220507. }
  220508. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  220509. OwnedArray <OpenGLPixelFormat>& results)
  220510. {
  220511. results.add (new OpenGLPixelFormat()); // xxx
  220512. }
  220513. #endif
  220514. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  220515. {
  220516. jassertfalse; // not implemented!
  220517. return false;
  220518. }
  220519. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  220520. {
  220521. jassertfalse; // not implemented!
  220522. return false;
  220523. }
  220524. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  220525. {
  220526. if (! isOnDesktop ())
  220527. addToDesktop (0);
  220528. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  220529. if (wp != 0)
  220530. {
  220531. wp->setTaskBarIcon (newImage);
  220532. setVisible (true);
  220533. toFront (false);
  220534. repaint();
  220535. }
  220536. }
  220537. void SystemTrayIconComponent::paint (Graphics& g)
  220538. {
  220539. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  220540. if (wp != 0)
  220541. {
  220542. g.drawImageWithin (wp->getTaskbarIcon(), 0, 0, getWidth(), getHeight(),
  220543. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  220544. false);
  220545. }
  220546. }
  220547. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  220548. {
  220549. // xxx not yet implemented!
  220550. }
  220551. void PlatformUtilities::beep()
  220552. {
  220553. std::cout << "\a" << std::flush;
  220554. }
  220555. bool AlertWindow::showNativeDialogBox (const String& title,
  220556. const String& bodyText,
  220557. bool isOkCancel)
  220558. {
  220559. // use a non-native one for the time being..
  220560. if (isOkCancel)
  220561. return AlertWindow::showOkCancelBox (AlertWindow::NoIcon, title, bodyText);
  220562. else
  220563. AlertWindow::showMessageBox (AlertWindow::NoIcon, title, bodyText);
  220564. return true;
  220565. }
  220566. const int KeyPress::spaceKey = XK_space & 0xff;
  220567. const int KeyPress::returnKey = XK_Return & 0xff;
  220568. const int KeyPress::escapeKey = XK_Escape & 0xff;
  220569. const int KeyPress::backspaceKey = XK_BackSpace & 0xff;
  220570. const int KeyPress::leftKey = (XK_Left & 0xff) | Keys::extendedKeyModifier;
  220571. const int KeyPress::rightKey = (XK_Right & 0xff) | Keys::extendedKeyModifier;
  220572. const int KeyPress::upKey = (XK_Up & 0xff) | Keys::extendedKeyModifier;
  220573. const int KeyPress::downKey = (XK_Down & 0xff) | Keys::extendedKeyModifier;
  220574. const int KeyPress::pageUpKey = (XK_Page_Up & 0xff) | Keys::extendedKeyModifier;
  220575. const int KeyPress::pageDownKey = (XK_Page_Down & 0xff) | Keys::extendedKeyModifier;
  220576. const int KeyPress::endKey = (XK_End & 0xff) | Keys::extendedKeyModifier;
  220577. const int KeyPress::homeKey = (XK_Home & 0xff) | Keys::extendedKeyModifier;
  220578. const int KeyPress::insertKey = (XK_Insert & 0xff) | Keys::extendedKeyModifier;
  220579. const int KeyPress::deleteKey = (XK_Delete & 0xff) | Keys::extendedKeyModifier;
  220580. const int KeyPress::tabKey = XK_Tab & 0xff;
  220581. const int KeyPress::F1Key = (XK_F1 & 0xff) | Keys::extendedKeyModifier;
  220582. const int KeyPress::F2Key = (XK_F2 & 0xff) | Keys::extendedKeyModifier;
  220583. const int KeyPress::F3Key = (XK_F3 & 0xff) | Keys::extendedKeyModifier;
  220584. const int KeyPress::F4Key = (XK_F4 & 0xff) | Keys::extendedKeyModifier;
  220585. const int KeyPress::F5Key = (XK_F5 & 0xff) | Keys::extendedKeyModifier;
  220586. const int KeyPress::F6Key = (XK_F6 & 0xff) | Keys::extendedKeyModifier;
  220587. const int KeyPress::F7Key = (XK_F7 & 0xff) | Keys::extendedKeyModifier;
  220588. const int KeyPress::F8Key = (XK_F8 & 0xff) | Keys::extendedKeyModifier;
  220589. const int KeyPress::F9Key = (XK_F9 & 0xff) | Keys::extendedKeyModifier;
  220590. const int KeyPress::F10Key = (XK_F10 & 0xff) | Keys::extendedKeyModifier;
  220591. const int KeyPress::F11Key = (XK_F11 & 0xff) | Keys::extendedKeyModifier;
  220592. const int KeyPress::F12Key = (XK_F12 & 0xff) | Keys::extendedKeyModifier;
  220593. const int KeyPress::F13Key = (XK_F13 & 0xff) | Keys::extendedKeyModifier;
  220594. const int KeyPress::F14Key = (XK_F14 & 0xff) | Keys::extendedKeyModifier;
  220595. const int KeyPress::F15Key = (XK_F15 & 0xff) | Keys::extendedKeyModifier;
  220596. const int KeyPress::F16Key = (XK_F16 & 0xff) | Keys::extendedKeyModifier;
  220597. const int KeyPress::numberPad0 = (XK_KP_0 & 0xff) | Keys::extendedKeyModifier;
  220598. const int KeyPress::numberPad1 = (XK_KP_1 & 0xff) | Keys::extendedKeyModifier;
  220599. const int KeyPress::numberPad2 = (XK_KP_2 & 0xff) | Keys::extendedKeyModifier;
  220600. const int KeyPress::numberPad3 = (XK_KP_3 & 0xff) | Keys::extendedKeyModifier;
  220601. const int KeyPress::numberPad4 = (XK_KP_4 & 0xff) | Keys::extendedKeyModifier;
  220602. const int KeyPress::numberPad5 = (XK_KP_5 & 0xff) | Keys::extendedKeyModifier;
  220603. const int KeyPress::numberPad6 = (XK_KP_6 & 0xff) | Keys::extendedKeyModifier;
  220604. const int KeyPress::numberPad7 = (XK_KP_7 & 0xff)| Keys::extendedKeyModifier;
  220605. const int KeyPress::numberPad8 = (XK_KP_8 & 0xff)| Keys::extendedKeyModifier;
  220606. const int KeyPress::numberPad9 = (XK_KP_9 & 0xff)| Keys::extendedKeyModifier;
  220607. const int KeyPress::numberPadAdd = (XK_KP_Add & 0xff)| Keys::extendedKeyModifier;
  220608. const int KeyPress::numberPadSubtract = (XK_KP_Subtract & 0xff)| Keys::extendedKeyModifier;
  220609. const int KeyPress::numberPadMultiply = (XK_KP_Multiply & 0xff)| Keys::extendedKeyModifier;
  220610. const int KeyPress::numberPadDivide = (XK_KP_Divide & 0xff)| Keys::extendedKeyModifier;
  220611. const int KeyPress::numberPadSeparator = (XK_KP_Separator & 0xff)| Keys::extendedKeyModifier;
  220612. const int KeyPress::numberPadDecimalPoint = (XK_KP_Decimal & 0xff)| Keys::extendedKeyModifier;
  220613. const int KeyPress::numberPadEquals = (XK_KP_Equal & 0xff)| Keys::extendedKeyModifier;
  220614. const int KeyPress::numberPadDelete = (XK_KP_Delete & 0xff)| Keys::extendedKeyModifier;
  220615. const int KeyPress::playKey = (0xffeeff00) | Keys::extendedKeyModifier;
  220616. const int KeyPress::stopKey = (0xffeeff01) | Keys::extendedKeyModifier;
  220617. const int KeyPress::fastForwardKey = (0xffeeff02) | Keys::extendedKeyModifier;
  220618. const int KeyPress::rewindKey = (0xffeeff03) | Keys::extendedKeyModifier;
  220619. #endif
  220620. /*** End of inlined file: juce_linux_Windowing.cpp ***/
  220621. /*** Start of inlined file: juce_linux_Audio.cpp ***/
  220622. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  220623. // compiled on its own).
  220624. #if JUCE_INCLUDED_FILE && JUCE_ALSA
  220625. static const int maxNumChans = 64;
  220626. static void getDeviceSampleRates (snd_pcm_t* handle, Array <int>& rates)
  220627. {
  220628. const int ratesToTry[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  220629. snd_pcm_hw_params_t* hwParams;
  220630. snd_pcm_hw_params_alloca (&hwParams);
  220631. for (int i = 0; ratesToTry[i] != 0; ++i)
  220632. {
  220633. if (snd_pcm_hw_params_any (handle, hwParams) >= 0
  220634. && snd_pcm_hw_params_test_rate (handle, hwParams, ratesToTry[i], 0) == 0)
  220635. {
  220636. rates.addIfNotAlreadyThere (ratesToTry[i]);
  220637. }
  220638. }
  220639. }
  220640. static void getDeviceNumChannels (snd_pcm_t* handle, unsigned int* minChans, unsigned int* maxChans)
  220641. {
  220642. snd_pcm_hw_params_t *params;
  220643. snd_pcm_hw_params_alloca (&params);
  220644. if (snd_pcm_hw_params_any (handle, params) >= 0)
  220645. {
  220646. snd_pcm_hw_params_get_channels_min (params, minChans);
  220647. snd_pcm_hw_params_get_channels_max (params, maxChans);
  220648. }
  220649. }
  220650. static void getDeviceProperties (const String& deviceID,
  220651. unsigned int& minChansOut,
  220652. unsigned int& maxChansOut,
  220653. unsigned int& minChansIn,
  220654. unsigned int& maxChansIn,
  220655. Array <int>& rates)
  220656. {
  220657. if (deviceID.isEmpty())
  220658. return;
  220659. snd_ctl_t* handle;
  220660. if (snd_ctl_open (&handle, deviceID.upToLastOccurrenceOf (",", false, false).toUTF8(), SND_CTL_NONBLOCK) >= 0)
  220661. {
  220662. snd_pcm_info_t* info;
  220663. snd_pcm_info_alloca (&info);
  220664. snd_pcm_info_set_stream (info, SND_PCM_STREAM_PLAYBACK);
  220665. snd_pcm_info_set_device (info, deviceID.fromLastOccurrenceOf (",", false, false).getIntValue());
  220666. snd_pcm_info_set_subdevice (info, 0);
  220667. if (snd_ctl_pcm_info (handle, info) >= 0)
  220668. {
  220669. snd_pcm_t* pcmHandle;
  220670. if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_PLAYBACK, SND_PCM_ASYNC | SND_PCM_NONBLOCK ) >= 0)
  220671. {
  220672. getDeviceNumChannels (pcmHandle, &minChansOut, &maxChansOut);
  220673. getDeviceSampleRates (pcmHandle, rates);
  220674. snd_pcm_close (pcmHandle);
  220675. }
  220676. }
  220677. snd_pcm_info_set_stream (info, SND_PCM_STREAM_CAPTURE);
  220678. if (snd_ctl_pcm_info (handle, info) >= 0)
  220679. {
  220680. snd_pcm_t* pcmHandle;
  220681. if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_CAPTURE, SND_PCM_ASYNC | SND_PCM_NONBLOCK ) >= 0)
  220682. {
  220683. getDeviceNumChannels (pcmHandle, &minChansIn, &maxChansIn);
  220684. if (rates.size() == 0)
  220685. getDeviceSampleRates (pcmHandle, rates);
  220686. snd_pcm_close (pcmHandle);
  220687. }
  220688. }
  220689. snd_ctl_close (handle);
  220690. }
  220691. }
  220692. class ALSADevice
  220693. {
  220694. public:
  220695. ALSADevice (const String& deviceID,
  220696. const bool forInput)
  220697. : handle (0),
  220698. bitDepth (16),
  220699. numChannelsRunning (0),
  220700. isInput (forInput),
  220701. sampleFormat (AudioDataConverters::int16LE)
  220702. {
  220703. failed (snd_pcm_open (&handle, deviceID.toUTF8(),
  220704. forInput ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK,
  220705. SND_PCM_ASYNC));
  220706. }
  220707. ~ALSADevice()
  220708. {
  220709. if (handle != 0)
  220710. snd_pcm_close (handle);
  220711. }
  220712. bool setParameters (unsigned int sampleRate, int numChannels, int bufferSize)
  220713. {
  220714. if (handle == 0)
  220715. return false;
  220716. snd_pcm_hw_params_t* hwParams;
  220717. snd_pcm_hw_params_alloca (&hwParams);
  220718. if (failed (snd_pcm_hw_params_any (handle, hwParams)))
  220719. return false;
  220720. if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_NONINTERLEAVED) >= 0)
  220721. isInterleaved = false;
  220722. else if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_INTERLEAVED) >= 0)
  220723. isInterleaved = true;
  220724. else
  220725. {
  220726. jassertfalse;
  220727. return false;
  220728. }
  220729. const int formatsToTry[] = { SND_PCM_FORMAT_FLOAT_LE, 32, AudioDataConverters::float32LE,
  220730. SND_PCM_FORMAT_FLOAT_BE, 32, AudioDataConverters::float32BE,
  220731. SND_PCM_FORMAT_S32_LE, 32, AudioDataConverters::int32LE,
  220732. SND_PCM_FORMAT_S32_BE, 32, AudioDataConverters::int32BE,
  220733. SND_PCM_FORMAT_S24_3LE, 24, AudioDataConverters::int24LE,
  220734. SND_PCM_FORMAT_S24_3BE, 24, AudioDataConverters::int24BE,
  220735. SND_PCM_FORMAT_S16_LE, 16, AudioDataConverters::int16LE,
  220736. SND_PCM_FORMAT_S16_BE, 16, AudioDataConverters::int16BE };
  220737. bitDepth = 0;
  220738. for (int i = 0; i < numElementsInArray (formatsToTry); i += 3)
  220739. {
  220740. if (snd_pcm_hw_params_set_format (handle, hwParams, (_snd_pcm_format) formatsToTry [i]) >= 0)
  220741. {
  220742. bitDepth = formatsToTry [i + 1];
  220743. sampleFormat = (AudioDataConverters::DataFormat) formatsToTry [i + 2];
  220744. break;
  220745. }
  220746. }
  220747. if (bitDepth == 0)
  220748. {
  220749. error = "device doesn't support a compatible PCM format";
  220750. DBG ("ALSA error: " + error + "\n");
  220751. return false;
  220752. }
  220753. int dir = 0;
  220754. unsigned int periods = 4;
  220755. snd_pcm_uframes_t samplesPerPeriod = bufferSize;
  220756. if (failed (snd_pcm_hw_params_set_rate_near (handle, hwParams, &sampleRate, 0))
  220757. || failed (snd_pcm_hw_params_set_channels (handle, hwParams, numChannels))
  220758. || failed (snd_pcm_hw_params_set_periods_near (handle, hwParams, &periods, &dir))
  220759. || failed (snd_pcm_hw_params_set_period_size_near (handle, hwParams, &samplesPerPeriod, &dir))
  220760. || failed (snd_pcm_hw_params (handle, hwParams)))
  220761. {
  220762. return false;
  220763. }
  220764. snd_pcm_sw_params_t* swParams;
  220765. snd_pcm_sw_params_alloca (&swParams);
  220766. snd_pcm_uframes_t boundary;
  220767. if (failed (snd_pcm_sw_params_current (handle, swParams))
  220768. || failed (snd_pcm_sw_params_get_boundary (swParams, &boundary))
  220769. || failed (snd_pcm_sw_params_set_silence_threshold (handle, swParams, 0))
  220770. || failed (snd_pcm_sw_params_set_silence_size (handle, swParams, boundary))
  220771. || failed (snd_pcm_sw_params_set_start_threshold (handle, swParams, samplesPerPeriod))
  220772. || failed (snd_pcm_sw_params_set_stop_threshold (handle, swParams, boundary))
  220773. || failed (snd_pcm_sw_params (handle, swParams)))
  220774. {
  220775. return false;
  220776. }
  220777. /*
  220778. #if JUCE_DEBUG
  220779. // enable this to dump the config of the devices that get opened
  220780. snd_output_t* out;
  220781. snd_output_stdio_attach (&out, stderr, 0);
  220782. snd_pcm_hw_params_dump (hwParams, out);
  220783. snd_pcm_sw_params_dump (swParams, out);
  220784. #endif
  220785. */
  220786. numChannelsRunning = numChannels;
  220787. return true;
  220788. }
  220789. bool write (AudioSampleBuffer& outputChannelBuffer, const int numSamples)
  220790. {
  220791. jassert (numChannelsRunning <= outputChannelBuffer.getNumChannels());
  220792. float** const data = outputChannelBuffer.getArrayOfChannels();
  220793. if (isInterleaved)
  220794. {
  220795. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  220796. float* interleaved = static_cast <float*> (scratch.getData());
  220797. AudioDataConverters::interleaveSamples ((const float**) data, interleaved, numSamples, numChannelsRunning);
  220798. AudioDataConverters::convertFloatToFormat (sampleFormat, interleaved, interleaved, numSamples * numChannelsRunning);
  220799. snd_pcm_sframes_t num = snd_pcm_writei (handle, interleaved, numSamples);
  220800. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  220801. return false;
  220802. }
  220803. else
  220804. {
  220805. for (int i = 0; i < numChannelsRunning; ++i)
  220806. if (data[i] != 0)
  220807. AudioDataConverters::convertFloatToFormat (sampleFormat, data[i], data[i], numSamples);
  220808. snd_pcm_sframes_t num = snd_pcm_writen (handle, (void**) data, numSamples);
  220809. if (failed (num))
  220810. {
  220811. if (num == -EPIPE)
  220812. {
  220813. if (failed (snd_pcm_prepare (handle)))
  220814. return false;
  220815. }
  220816. else if (num != -ESTRPIPE)
  220817. return false;
  220818. }
  220819. }
  220820. return true;
  220821. }
  220822. bool read (AudioSampleBuffer& inputChannelBuffer, const int numSamples)
  220823. {
  220824. jassert (numChannelsRunning <= inputChannelBuffer.getNumChannels());
  220825. float** const data = inputChannelBuffer.getArrayOfChannels();
  220826. if (isInterleaved)
  220827. {
  220828. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  220829. float* interleaved = static_cast <float*> (scratch.getData());
  220830. snd_pcm_sframes_t num = snd_pcm_readi (handle, interleaved, numSamples);
  220831. if (failed (num))
  220832. {
  220833. if (num == -EPIPE)
  220834. {
  220835. if (failed (snd_pcm_prepare (handle)))
  220836. return false;
  220837. }
  220838. else if (num != -ESTRPIPE)
  220839. return false;
  220840. }
  220841. AudioDataConverters::convertFormatToFloat (sampleFormat, interleaved, interleaved, numSamples * numChannelsRunning);
  220842. AudioDataConverters::deinterleaveSamples (interleaved, data, numSamples, numChannelsRunning);
  220843. }
  220844. else
  220845. {
  220846. snd_pcm_sframes_t num = snd_pcm_readn (handle, (void**) data, numSamples);
  220847. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  220848. return false;
  220849. for (int i = 0; i < numChannelsRunning; ++i)
  220850. if (data[i] != 0)
  220851. AudioDataConverters::convertFormatToFloat (sampleFormat, data[i], data[i], numSamples);
  220852. }
  220853. return true;
  220854. }
  220855. juce_UseDebuggingNewOperator
  220856. snd_pcm_t* handle;
  220857. String error;
  220858. int bitDepth, numChannelsRunning;
  220859. private:
  220860. const bool isInput;
  220861. bool isInterleaved;
  220862. MemoryBlock scratch;
  220863. AudioDataConverters::DataFormat sampleFormat;
  220864. bool failed (const int errorNum)
  220865. {
  220866. if (errorNum >= 0)
  220867. return false;
  220868. error = snd_strerror (errorNum);
  220869. DBG ("ALSA error: " + error + "\n");
  220870. return true;
  220871. }
  220872. };
  220873. class ALSAThread : public Thread
  220874. {
  220875. public:
  220876. ALSAThread (const String& inputId_,
  220877. const String& outputId_)
  220878. : Thread ("Juce ALSA"),
  220879. sampleRate (0),
  220880. bufferSize (0),
  220881. callback (0),
  220882. inputId (inputId_),
  220883. outputId (outputId_),
  220884. outputDevice (0),
  220885. inputDevice (0),
  220886. numCallbacks (0),
  220887. inputChannelBuffer (1, 1),
  220888. outputChannelBuffer (1, 1)
  220889. {
  220890. initialiseRatesAndChannels();
  220891. }
  220892. ~ALSAThread()
  220893. {
  220894. close();
  220895. }
  220896. void open (BigInteger inputChannels,
  220897. BigInteger outputChannels,
  220898. const double sampleRate_,
  220899. const int bufferSize_)
  220900. {
  220901. close();
  220902. error = String::empty;
  220903. sampleRate = sampleRate_;
  220904. bufferSize = bufferSize_;
  220905. inputChannelBuffer.setSize (jmax ((int) minChansIn, inputChannels.getHighestBit()) + 1, bufferSize);
  220906. inputChannelBuffer.clear();
  220907. inputChannelDataForCallback.clear();
  220908. currentInputChans.clear();
  220909. if (inputChannels.getHighestBit() >= 0)
  220910. {
  220911. for (int i = 0; i <= jmax (inputChannels.getHighestBit(), (int) minChansIn); ++i)
  220912. {
  220913. if (inputChannels[i])
  220914. {
  220915. inputChannelDataForCallback.add (inputChannelBuffer.getSampleData (i));
  220916. currentInputChans.setBit (i);
  220917. }
  220918. }
  220919. }
  220920. outputChannelBuffer.setSize (jmax ((int) minChansOut, outputChannels.getHighestBit()) + 1, bufferSize);
  220921. outputChannelBuffer.clear();
  220922. outputChannelDataForCallback.clear();
  220923. currentOutputChans.clear();
  220924. if (outputChannels.getHighestBit() >= 0)
  220925. {
  220926. for (int i = 0; i <= jmax (outputChannels.getHighestBit(), (int) minChansOut); ++i)
  220927. {
  220928. if (outputChannels[i])
  220929. {
  220930. outputChannelDataForCallback.add (outputChannelBuffer.getSampleData (i));
  220931. currentOutputChans.setBit (i);
  220932. }
  220933. }
  220934. }
  220935. if (outputChannelDataForCallback.size() > 0 && outputId.isNotEmpty())
  220936. {
  220937. outputDevice = new ALSADevice (outputId, false);
  220938. if (outputDevice->error.isNotEmpty())
  220939. {
  220940. error = outputDevice->error;
  220941. deleteAndZero (outputDevice);
  220942. return;
  220943. }
  220944. currentOutputChans.setRange (0, minChansOut, true);
  220945. if (! outputDevice->setParameters ((unsigned int) sampleRate,
  220946. jlimit ((int) minChansOut, (int) maxChansOut, currentOutputChans.getHighestBit() + 1),
  220947. bufferSize))
  220948. {
  220949. error = outputDevice->error;
  220950. deleteAndZero (outputDevice);
  220951. return;
  220952. }
  220953. }
  220954. if (inputChannelDataForCallback.size() > 0 && inputId.isNotEmpty())
  220955. {
  220956. inputDevice = new ALSADevice (inputId, true);
  220957. if (inputDevice->error.isNotEmpty())
  220958. {
  220959. error = inputDevice->error;
  220960. deleteAndZero (inputDevice);
  220961. return;
  220962. }
  220963. currentInputChans.setRange (0, minChansIn, true);
  220964. if (! inputDevice->setParameters ((unsigned int) sampleRate,
  220965. jlimit ((int) minChansIn, (int) maxChansIn, currentInputChans.getHighestBit() + 1),
  220966. bufferSize))
  220967. {
  220968. error = inputDevice->error;
  220969. deleteAndZero (inputDevice);
  220970. return;
  220971. }
  220972. }
  220973. if (outputDevice == 0 && inputDevice == 0)
  220974. {
  220975. error = "no channels";
  220976. return;
  220977. }
  220978. if (outputDevice != 0 && inputDevice != 0)
  220979. {
  220980. snd_pcm_link (outputDevice->handle, inputDevice->handle);
  220981. }
  220982. if (inputDevice != 0 && failed (snd_pcm_prepare (inputDevice->handle)))
  220983. return;
  220984. if (outputDevice != 0 && failed (snd_pcm_prepare (outputDevice->handle)))
  220985. return;
  220986. startThread (9);
  220987. int count = 1000;
  220988. while (numCallbacks == 0)
  220989. {
  220990. sleep (5);
  220991. if (--count < 0 || ! isThreadRunning())
  220992. {
  220993. error = "device didn't start";
  220994. break;
  220995. }
  220996. }
  220997. }
  220998. void close()
  220999. {
  221000. stopThread (6000);
  221001. deleteAndZero (inputDevice);
  221002. deleteAndZero (outputDevice);
  221003. inputChannelBuffer.setSize (1, 1);
  221004. outputChannelBuffer.setSize (1, 1);
  221005. numCallbacks = 0;
  221006. }
  221007. void setCallback (AudioIODeviceCallback* const newCallback) throw()
  221008. {
  221009. const ScopedLock sl (callbackLock);
  221010. callback = newCallback;
  221011. }
  221012. void run()
  221013. {
  221014. while (! threadShouldExit())
  221015. {
  221016. if (inputDevice != 0)
  221017. {
  221018. if (! inputDevice->read (inputChannelBuffer, bufferSize))
  221019. {
  221020. DBG ("ALSA: read failure");
  221021. break;
  221022. }
  221023. }
  221024. if (threadShouldExit())
  221025. break;
  221026. {
  221027. const ScopedLock sl (callbackLock);
  221028. ++numCallbacks;
  221029. if (callback != 0)
  221030. {
  221031. callback->audioDeviceIOCallback ((const float**) inputChannelDataForCallback.getRawDataPointer(),
  221032. inputChannelDataForCallback.size(),
  221033. outputChannelDataForCallback.getRawDataPointer(),
  221034. outputChannelDataForCallback.size(),
  221035. bufferSize);
  221036. }
  221037. else
  221038. {
  221039. for (int i = 0; i < outputChannelDataForCallback.size(); ++i)
  221040. zeromem (outputChannelDataForCallback[i], sizeof (float) * bufferSize);
  221041. }
  221042. }
  221043. if (outputDevice != 0)
  221044. {
  221045. failed (snd_pcm_wait (outputDevice->handle, 2000));
  221046. if (threadShouldExit())
  221047. break;
  221048. failed (snd_pcm_avail_update (outputDevice->handle));
  221049. if (! outputDevice->write (outputChannelBuffer, bufferSize))
  221050. {
  221051. DBG ("ALSA: write failure");
  221052. break;
  221053. }
  221054. }
  221055. }
  221056. }
  221057. int getBitDepth() const throw()
  221058. {
  221059. if (outputDevice != 0)
  221060. return outputDevice->bitDepth;
  221061. if (inputDevice != 0)
  221062. return inputDevice->bitDepth;
  221063. return 16;
  221064. }
  221065. juce_UseDebuggingNewOperator
  221066. String error;
  221067. double sampleRate;
  221068. int bufferSize;
  221069. BigInteger currentInputChans, currentOutputChans;
  221070. Array <int> sampleRates;
  221071. StringArray channelNamesOut, channelNamesIn;
  221072. AudioIODeviceCallback* callback;
  221073. private:
  221074. const String inputId, outputId;
  221075. ALSADevice* outputDevice;
  221076. ALSADevice* inputDevice;
  221077. int numCallbacks;
  221078. CriticalSection callbackLock;
  221079. AudioSampleBuffer inputChannelBuffer, outputChannelBuffer;
  221080. Array<float*> inputChannelDataForCallback, outputChannelDataForCallback;
  221081. unsigned int minChansOut, maxChansOut;
  221082. unsigned int minChansIn, maxChansIn;
  221083. bool failed (const int errorNum)
  221084. {
  221085. if (errorNum >= 0)
  221086. return false;
  221087. error = snd_strerror (errorNum);
  221088. DBG ("ALSA error: " + error + "\n");
  221089. return true;
  221090. }
  221091. void initialiseRatesAndChannels()
  221092. {
  221093. sampleRates.clear();
  221094. channelNamesOut.clear();
  221095. channelNamesIn.clear();
  221096. minChansOut = 0;
  221097. maxChansOut = 0;
  221098. minChansIn = 0;
  221099. maxChansIn = 0;
  221100. unsigned int dummy = 0;
  221101. getDeviceProperties (inputId, dummy, dummy, minChansIn, maxChansIn, sampleRates);
  221102. getDeviceProperties (outputId, minChansOut, maxChansOut, dummy, dummy, sampleRates);
  221103. unsigned int i;
  221104. for (i = 0; i < maxChansOut; ++i)
  221105. channelNamesOut.add ("channel " + String ((int) i + 1));
  221106. for (i = 0; i < maxChansIn; ++i)
  221107. channelNamesIn.add ("channel " + String ((int) i + 1));
  221108. }
  221109. };
  221110. class ALSAAudioIODevice : public AudioIODevice
  221111. {
  221112. public:
  221113. ALSAAudioIODevice (const String& deviceName,
  221114. const String& inputId_,
  221115. const String& outputId_)
  221116. : AudioIODevice (deviceName, "ALSA"),
  221117. inputId (inputId_),
  221118. outputId (outputId_),
  221119. isOpen_ (false),
  221120. isStarted (false),
  221121. internal (new ALSAThread (inputId_, outputId_))
  221122. {
  221123. }
  221124. ~ALSAAudioIODevice()
  221125. {
  221126. }
  221127. const StringArray getOutputChannelNames()
  221128. {
  221129. return internal->channelNamesOut;
  221130. }
  221131. const StringArray getInputChannelNames()
  221132. {
  221133. return internal->channelNamesIn;
  221134. }
  221135. int getNumSampleRates()
  221136. {
  221137. return internal->sampleRates.size();
  221138. }
  221139. double getSampleRate (int index)
  221140. {
  221141. return internal->sampleRates [index];
  221142. }
  221143. int getNumBufferSizesAvailable()
  221144. {
  221145. return 50;
  221146. }
  221147. int getBufferSizeSamples (int index)
  221148. {
  221149. int n = 16;
  221150. for (int i = 0; i < index; ++i)
  221151. n += n < 64 ? 16
  221152. : (n < 512 ? 32
  221153. : (n < 1024 ? 64
  221154. : (n < 2048 ? 128 : 256)));
  221155. return n;
  221156. }
  221157. int getDefaultBufferSize()
  221158. {
  221159. return 512;
  221160. }
  221161. const String open (const BigInteger& inputChannels,
  221162. const BigInteger& outputChannels,
  221163. double sampleRate,
  221164. int bufferSizeSamples)
  221165. {
  221166. close();
  221167. if (bufferSizeSamples <= 0)
  221168. bufferSizeSamples = getDefaultBufferSize();
  221169. if (sampleRate <= 0)
  221170. {
  221171. for (int i = 0; i < getNumSampleRates(); ++i)
  221172. {
  221173. if (getSampleRate (i) >= 44100)
  221174. {
  221175. sampleRate = getSampleRate (i);
  221176. break;
  221177. }
  221178. }
  221179. }
  221180. internal->open (inputChannels, outputChannels,
  221181. sampleRate, bufferSizeSamples);
  221182. isOpen_ = internal->error.isEmpty();
  221183. return internal->error;
  221184. }
  221185. void close()
  221186. {
  221187. stop();
  221188. internal->close();
  221189. isOpen_ = false;
  221190. }
  221191. bool isOpen()
  221192. {
  221193. return isOpen_;
  221194. }
  221195. int getCurrentBufferSizeSamples()
  221196. {
  221197. return internal->bufferSize;
  221198. }
  221199. double getCurrentSampleRate()
  221200. {
  221201. return internal->sampleRate;
  221202. }
  221203. int getCurrentBitDepth()
  221204. {
  221205. return internal->getBitDepth();
  221206. }
  221207. const BigInteger getActiveOutputChannels() const
  221208. {
  221209. return internal->currentOutputChans;
  221210. }
  221211. const BigInteger getActiveInputChannels() const
  221212. {
  221213. return internal->currentInputChans;
  221214. }
  221215. int getOutputLatencyInSamples()
  221216. {
  221217. return 0;
  221218. }
  221219. int getInputLatencyInSamples()
  221220. {
  221221. return 0;
  221222. }
  221223. void start (AudioIODeviceCallback* callback)
  221224. {
  221225. if (! isOpen_)
  221226. callback = 0;
  221227. internal->setCallback (callback);
  221228. if (callback != 0)
  221229. callback->audioDeviceAboutToStart (this);
  221230. isStarted = (callback != 0);
  221231. }
  221232. void stop()
  221233. {
  221234. AudioIODeviceCallback* const oldCallback = internal->callback;
  221235. start (0);
  221236. if (oldCallback != 0)
  221237. oldCallback->audioDeviceStopped();
  221238. }
  221239. bool isPlaying()
  221240. {
  221241. return isStarted && internal->error.isEmpty();
  221242. }
  221243. const String getLastError()
  221244. {
  221245. return internal->error;
  221246. }
  221247. String inputId, outputId;
  221248. private:
  221249. bool isOpen_, isStarted;
  221250. ScopedPointer<ALSAThread> internal;
  221251. };
  221252. class ALSAAudioIODeviceType : public AudioIODeviceType
  221253. {
  221254. public:
  221255. ALSAAudioIODeviceType()
  221256. : AudioIODeviceType ("ALSA"),
  221257. hasScanned (false)
  221258. {
  221259. }
  221260. ~ALSAAudioIODeviceType()
  221261. {
  221262. }
  221263. void scanForDevices()
  221264. {
  221265. if (hasScanned)
  221266. return;
  221267. hasScanned = true;
  221268. inputNames.clear();
  221269. inputIds.clear();
  221270. outputNames.clear();
  221271. outputIds.clear();
  221272. snd_ctl_t* handle;
  221273. snd_ctl_card_info_t* info;
  221274. snd_ctl_card_info_alloca (&info);
  221275. int cardNum = -1;
  221276. while (outputIds.size() + inputIds.size() <= 32)
  221277. {
  221278. snd_card_next (&cardNum);
  221279. if (cardNum < 0)
  221280. break;
  221281. if (snd_ctl_open (&handle, ("hw:" + String (cardNum)).toUTF8(), SND_CTL_NONBLOCK) >= 0)
  221282. {
  221283. if (snd_ctl_card_info (handle, info) >= 0)
  221284. {
  221285. String cardId (snd_ctl_card_info_get_id (info));
  221286. if (cardId.removeCharacters ("0123456789").isEmpty())
  221287. cardId = String (cardNum);
  221288. int device = -1;
  221289. for (;;)
  221290. {
  221291. if (snd_ctl_pcm_next_device (handle, &device) < 0 || device < 0)
  221292. break;
  221293. String id, name;
  221294. id << "hw:" << cardId << ',' << device;
  221295. bool isInput, isOutput;
  221296. if (testDevice (id, isInput, isOutput))
  221297. {
  221298. name << snd_ctl_card_info_get_name (info);
  221299. if (name.isEmpty())
  221300. name = id;
  221301. if (isInput)
  221302. {
  221303. inputNames.add (name);
  221304. inputIds.add (id);
  221305. }
  221306. if (isOutput)
  221307. {
  221308. outputNames.add (name);
  221309. outputIds.add (id);
  221310. }
  221311. }
  221312. }
  221313. }
  221314. snd_ctl_close (handle);
  221315. }
  221316. }
  221317. inputNames.appendNumbersToDuplicates (false, true);
  221318. outputNames.appendNumbersToDuplicates (false, true);
  221319. }
  221320. const StringArray getDeviceNames (bool wantInputNames) const
  221321. {
  221322. jassert (hasScanned); // need to call scanForDevices() before doing this
  221323. return wantInputNames ? inputNames : outputNames;
  221324. }
  221325. int getDefaultDeviceIndex (bool forInput) const
  221326. {
  221327. jassert (hasScanned); // need to call scanForDevices() before doing this
  221328. return 0;
  221329. }
  221330. bool hasSeparateInputsAndOutputs() const { return true; }
  221331. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  221332. {
  221333. jassert (hasScanned); // need to call scanForDevices() before doing this
  221334. ALSAAudioIODevice* d = dynamic_cast <ALSAAudioIODevice*> (device);
  221335. if (d == 0)
  221336. return -1;
  221337. return asInput ? inputIds.indexOf (d->inputId)
  221338. : outputIds.indexOf (d->outputId);
  221339. }
  221340. AudioIODevice* createDevice (const String& outputDeviceName,
  221341. const String& inputDeviceName)
  221342. {
  221343. jassert (hasScanned); // need to call scanForDevices() before doing this
  221344. const int inputIndex = inputNames.indexOf (inputDeviceName);
  221345. const int outputIndex = outputNames.indexOf (outputDeviceName);
  221346. String deviceName (outputIndex >= 0 ? outputDeviceName
  221347. : inputDeviceName);
  221348. if (inputIndex >= 0 || outputIndex >= 0)
  221349. return new ALSAAudioIODevice (deviceName,
  221350. inputIds [inputIndex],
  221351. outputIds [outputIndex]);
  221352. return 0;
  221353. }
  221354. juce_UseDebuggingNewOperator
  221355. private:
  221356. StringArray inputNames, outputNames, inputIds, outputIds;
  221357. bool hasScanned;
  221358. static bool testDevice (const String& id, bool& isInput, bool& isOutput)
  221359. {
  221360. unsigned int minChansOut = 0, maxChansOut = 0;
  221361. unsigned int minChansIn = 0, maxChansIn = 0;
  221362. Array <int> rates;
  221363. getDeviceProperties (id, minChansOut, maxChansOut, minChansIn, maxChansIn, rates);
  221364. DBG ("ALSA device: " + id
  221365. + " outs=" + String ((int) minChansOut) + "-" + String ((int) maxChansOut)
  221366. + " ins=" + String ((int) minChansIn) + "-" + String ((int) maxChansIn)
  221367. + " rates=" + String (rates.size()));
  221368. isInput = maxChansIn > 0;
  221369. isOutput = maxChansOut > 0;
  221370. return (isInput || isOutput) && rates.size() > 0;
  221371. }
  221372. ALSAAudioIODeviceType (const ALSAAudioIODeviceType&);
  221373. ALSAAudioIODeviceType& operator= (const ALSAAudioIODeviceType&);
  221374. };
  221375. AudioIODeviceType* juce_createAudioIODeviceType_ALSA()
  221376. {
  221377. return new ALSAAudioIODeviceType();
  221378. }
  221379. #endif
  221380. /*** End of inlined file: juce_linux_Audio.cpp ***/
  221381. /*** Start of inlined file: juce_linux_JackAudio.cpp ***/
  221382. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  221383. // compiled on its own).
  221384. #ifdef JUCE_INCLUDED_FILE
  221385. #if JUCE_JACK
  221386. static void* juce_libjack_handle = 0;
  221387. void* juce_load_jack_function (const char* const name)
  221388. {
  221389. if (juce_libjack_handle == 0)
  221390. return 0;
  221391. return dlsym (juce_libjack_handle, name);
  221392. }
  221393. #define JUCE_DECL_JACK_FUNCTION(return_type, fn_name, argument_types, arguments) \
  221394. typedef return_type (*fn_name##_ptr_t)argument_types; \
  221395. return_type fn_name argument_types { \
  221396. static fn_name##_ptr_t fn = 0; \
  221397. if (fn == 0) { fn = (fn_name##_ptr_t)juce_load_jack_function(#fn_name); } \
  221398. if (fn) return (*fn)arguments; \
  221399. else return 0; \
  221400. }
  221401. #define JUCE_DECL_VOID_JACK_FUNCTION(fn_name, argument_types, arguments) \
  221402. typedef void (*fn_name##_ptr_t)argument_types; \
  221403. void fn_name argument_types { \
  221404. static fn_name##_ptr_t fn = 0; \
  221405. if (fn == 0) { fn = (fn_name##_ptr_t)juce_load_jack_function(#fn_name); } \
  221406. if (fn) (*fn)arguments; \
  221407. }
  221408. 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));
  221409. JUCE_DECL_JACK_FUNCTION (int, jack_client_close, (jack_client_t *client), (client));
  221410. JUCE_DECL_JACK_FUNCTION (int, jack_activate, (jack_client_t* client), (client));
  221411. JUCE_DECL_JACK_FUNCTION (int, jack_deactivate, (jack_client_t* client), (client));
  221412. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_buffer_size, (jack_client_t* client), (client));
  221413. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_sample_rate, (jack_client_t* client), (client));
  221414. JUCE_DECL_VOID_JACK_FUNCTION (jack_on_shutdown, (jack_client_t* client, void (*function)(void* arg), void* arg), (client, function, arg));
  221415. JUCE_DECL_JACK_FUNCTION (void* , jack_port_get_buffer, (jack_port_t* port, jack_nframes_t nframes), (port, nframes));
  221416. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_port_get_total_latency, (jack_client_t* client, jack_port_t* port), (client, port));
  221417. 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));
  221418. JUCE_DECL_VOID_JACK_FUNCTION (jack_set_error_function, (void (*func)(const char*)), (func));
  221419. JUCE_DECL_JACK_FUNCTION (int, jack_set_process_callback, (jack_client_t* client, JackProcessCallback process_callback, void* arg), (client, process_callback, arg));
  221420. 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));
  221421. JUCE_DECL_JACK_FUNCTION (int, jack_connect, (jack_client_t* client, const char* source_port, const char* destination_port), (client, source_port, destination_port));
  221422. JUCE_DECL_JACK_FUNCTION (const char*, jack_port_name, (const jack_port_t* port), (port));
  221423. JUCE_DECL_JACK_FUNCTION (int, jack_set_port_connect_callback, (jack_client_t* client, JackPortConnectCallback connect_callback, void* arg), (client, connect_callback, arg));
  221424. JUCE_DECL_JACK_FUNCTION (jack_port_t* , jack_port_by_id, (jack_client_t* client, jack_port_id_t port_id), (client, port_id));
  221425. JUCE_DECL_JACK_FUNCTION (int, jack_port_connected, (const jack_port_t* port), (port));
  221426. JUCE_DECL_JACK_FUNCTION (int, jack_port_connected_to, (const jack_port_t* port, const char* port_name), (port, port_name));
  221427. #if JUCE_DEBUG
  221428. #define JACK_LOGGING_ENABLED 1
  221429. #endif
  221430. #if JACK_LOGGING_ENABLED
  221431. static void jack_Log (const String& s)
  221432. {
  221433. std::cerr << s << std::endl;
  221434. }
  221435. static void dumpJackErrorMessage (const jack_status_t status)
  221436. {
  221437. if (status & JackServerFailed || status & JackServerError)
  221438. jack_Log ("Unable to connect to JACK server");
  221439. if (status & JackVersionError)
  221440. jack_Log ("Client's protocol version does not match");
  221441. if (status & JackInvalidOption)
  221442. jack_Log ("The operation contained an invalid or unsupported option");
  221443. if (status & JackNameNotUnique)
  221444. jack_Log ("The desired client name was not unique");
  221445. if (status & JackNoSuchClient)
  221446. jack_Log ("Requested client does not exist");
  221447. if (status & JackInitFailure)
  221448. jack_Log ("Unable to initialize client");
  221449. }
  221450. #else
  221451. #define dumpJackErrorMessage(a) {}
  221452. #define jack_Log(...) {}
  221453. #endif
  221454. #ifndef JUCE_JACK_CLIENT_NAME
  221455. #define JUCE_JACK_CLIENT_NAME "JuceJack"
  221456. #endif
  221457. class JackAudioIODevice : public AudioIODevice
  221458. {
  221459. public:
  221460. JackAudioIODevice (const String& deviceName,
  221461. const String& inputId_,
  221462. const String& outputId_)
  221463. : AudioIODevice (deviceName, "JACK"),
  221464. inputId (inputId_),
  221465. outputId (outputId_),
  221466. isOpen_ (false),
  221467. callback (0),
  221468. totalNumberOfInputChannels (0),
  221469. totalNumberOfOutputChannels (0)
  221470. {
  221471. jassert (deviceName.isNotEmpty());
  221472. jack_status_t status;
  221473. client = JUCE_NAMESPACE::jack_client_open (JUCE_JACK_CLIENT_NAME, JackNoStartServer, &status);
  221474. if (client == 0)
  221475. {
  221476. dumpJackErrorMessage (status);
  221477. }
  221478. else
  221479. {
  221480. JUCE_NAMESPACE::jack_set_error_function (errorCallback);
  221481. // open input ports
  221482. const StringArray inputChannels (getInputChannelNames());
  221483. for (int i = 0; i < inputChannels.size(); i++)
  221484. {
  221485. String inputName;
  221486. inputName << "in_" << ++totalNumberOfInputChannels;
  221487. inputPorts.add (JUCE_NAMESPACE::jack_port_register (client, inputName.toUTF8(),
  221488. JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0));
  221489. }
  221490. // open output ports
  221491. const StringArray outputChannels (getOutputChannelNames());
  221492. for (int i = 0; i < outputChannels.size (); i++)
  221493. {
  221494. String outputName;
  221495. outputName << "out_" << ++totalNumberOfOutputChannels;
  221496. outputPorts.add (JUCE_NAMESPACE::jack_port_register (client, outputName.toUTF8(),
  221497. JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0));
  221498. }
  221499. inChans.calloc (totalNumberOfInputChannels + 2);
  221500. outChans.calloc (totalNumberOfOutputChannels + 2);
  221501. }
  221502. }
  221503. ~JackAudioIODevice()
  221504. {
  221505. close();
  221506. if (client != 0)
  221507. {
  221508. JUCE_NAMESPACE::jack_client_close (client);
  221509. client = 0;
  221510. }
  221511. }
  221512. const StringArray getChannelNames (bool forInput) const
  221513. {
  221514. StringArray names;
  221515. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */
  221516. forInput ? JackPortIsInput : JackPortIsOutput);
  221517. if (ports != 0)
  221518. {
  221519. int j = 0;
  221520. while (ports[j] != 0)
  221521. {
  221522. const String portName (ports [j++]);
  221523. if (portName.upToFirstOccurrenceOf (":", false, false) == getName())
  221524. names.add (portName.fromFirstOccurrenceOf (":", false, false));
  221525. }
  221526. free (ports);
  221527. }
  221528. return names;
  221529. }
  221530. const StringArray getOutputChannelNames() { return getChannelNames (false); }
  221531. const StringArray getInputChannelNames() { return getChannelNames (true); }
  221532. int getNumSampleRates() { return client != 0 ? 1 : 0; }
  221533. double getSampleRate (int index) { return client != 0 ? JUCE_NAMESPACE::jack_get_sample_rate (client) : 0; }
  221534. int getNumBufferSizesAvailable() { return client != 0 ? 1 : 0; }
  221535. int getBufferSizeSamples (int index) { return getDefaultBufferSize(); }
  221536. int getDefaultBufferSize() { return client != 0 ? JUCE_NAMESPACE::jack_get_buffer_size (client) : 0; }
  221537. const String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  221538. double sampleRate, int bufferSizeSamples)
  221539. {
  221540. if (client == 0)
  221541. {
  221542. lastError = "No JACK client running";
  221543. return lastError;
  221544. }
  221545. lastError = String::empty;
  221546. close();
  221547. JUCE_NAMESPACE::jack_set_process_callback (client, processCallback, this);
  221548. JUCE_NAMESPACE::jack_on_shutdown (client, shutdownCallback, this);
  221549. JUCE_NAMESPACE::jack_activate (client);
  221550. isOpen_ = true;
  221551. if (! inputChannels.isZero())
  221552. {
  221553. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsOutput);
  221554. if (ports != 0)
  221555. {
  221556. const int numInputChannels = inputChannels.getHighestBit() + 1;
  221557. for (int i = 0; i < numInputChannels; ++i)
  221558. {
  221559. const String portName (ports[i]);
  221560. if (inputChannels[i] && portName.upToFirstOccurrenceOf (":", false, false) == getName())
  221561. {
  221562. int error = JUCE_NAMESPACE::jack_connect (client, ports[i], JUCE_NAMESPACE::jack_port_name ((jack_port_t*) inputPorts[i]));
  221563. if (error != 0)
  221564. jack_Log ("Cannot connect input port " + String (i) + " (" + String (ports[i]) + "), error " + String (error));
  221565. }
  221566. }
  221567. free (ports);
  221568. }
  221569. }
  221570. if (! outputChannels.isZero())
  221571. {
  221572. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsInput);
  221573. if (ports != 0)
  221574. {
  221575. const int numOutputChannels = outputChannels.getHighestBit() + 1;
  221576. for (int i = 0; i < numOutputChannels; ++i)
  221577. {
  221578. const String portName (ports[i]);
  221579. if (outputChannels[i] && portName.upToFirstOccurrenceOf (":", false, false) == getName())
  221580. {
  221581. int error = JUCE_NAMESPACE::jack_connect (client, JUCE_NAMESPACE::jack_port_name ((jack_port_t*) outputPorts[i]), ports[i]);
  221582. if (error != 0)
  221583. jack_Log ("Cannot connect output port " + String (i) + " (" + String (ports[i]) + "), error " + String (error));
  221584. }
  221585. }
  221586. free (ports);
  221587. }
  221588. }
  221589. return lastError;
  221590. }
  221591. void close()
  221592. {
  221593. stop();
  221594. if (client != 0)
  221595. {
  221596. JUCE_NAMESPACE::jack_deactivate (client);
  221597. JUCE_NAMESPACE::jack_set_process_callback (client, processCallback, 0);
  221598. JUCE_NAMESPACE::jack_on_shutdown (client, shutdownCallback, 0);
  221599. }
  221600. isOpen_ = false;
  221601. }
  221602. void start (AudioIODeviceCallback* newCallback)
  221603. {
  221604. if (isOpen_ && newCallback != callback)
  221605. {
  221606. if (newCallback != 0)
  221607. newCallback->audioDeviceAboutToStart (this);
  221608. AudioIODeviceCallback* const oldCallback = callback;
  221609. {
  221610. const ScopedLock sl (callbackLock);
  221611. callback = newCallback;
  221612. }
  221613. if (oldCallback != 0)
  221614. oldCallback->audioDeviceStopped();
  221615. }
  221616. }
  221617. void stop()
  221618. {
  221619. start (0);
  221620. }
  221621. bool isOpen() { return isOpen_; }
  221622. bool isPlaying() { return callback != 0; }
  221623. int getCurrentBufferSizeSamples() { return getBufferSizeSamples (0); }
  221624. double getCurrentSampleRate() { return getSampleRate (0); }
  221625. int getCurrentBitDepth() { return 32; }
  221626. const String getLastError() { return lastError; }
  221627. const BigInteger getActiveOutputChannels() const
  221628. {
  221629. BigInteger outputBits;
  221630. for (int i = 0; i < outputPorts.size(); i++)
  221631. if (JUCE_NAMESPACE::jack_port_connected ((jack_port_t*) outputPorts [i]))
  221632. outputBits.setBit (i);
  221633. return outputBits;
  221634. }
  221635. const BigInteger getActiveInputChannels() const
  221636. {
  221637. BigInteger inputBits;
  221638. for (int i = 0; i < inputPorts.size(); i++)
  221639. if (JUCE_NAMESPACE::jack_port_connected ((jack_port_t*) inputPorts [i]))
  221640. inputBits.setBit (i);
  221641. return inputBits;
  221642. }
  221643. int getOutputLatencyInSamples()
  221644. {
  221645. int latency = 0;
  221646. for (int i = 0; i < outputPorts.size(); i++)
  221647. latency = jmax (latency, (int) JUCE_NAMESPACE::jack_port_get_total_latency (client, (jack_port_t*) outputPorts [i]));
  221648. return latency;
  221649. }
  221650. int getInputLatencyInSamples()
  221651. {
  221652. int latency = 0;
  221653. for (int i = 0; i < inputPorts.size(); i++)
  221654. latency = jmax (latency, (int) JUCE_NAMESPACE::jack_port_get_total_latency (client, (jack_port_t*) inputPorts [i]));
  221655. return latency;
  221656. }
  221657. String inputId, outputId;
  221658. private:
  221659. void process (const int numSamples)
  221660. {
  221661. int i, numActiveInChans = 0, numActiveOutChans = 0;
  221662. for (i = 0; i < totalNumberOfInputChannels; ++i)
  221663. {
  221664. jack_default_audio_sample_t* in
  221665. = (jack_default_audio_sample_t*) JUCE_NAMESPACE::jack_port_get_buffer ((jack_port_t*) inputPorts.getUnchecked(i), numSamples);
  221666. if (in != 0)
  221667. inChans [numActiveInChans++] = (float*) in;
  221668. }
  221669. for (i = 0; i < totalNumberOfOutputChannels; ++i)
  221670. {
  221671. jack_default_audio_sample_t* out
  221672. = (jack_default_audio_sample_t*) JUCE_NAMESPACE::jack_port_get_buffer ((jack_port_t*) outputPorts.getUnchecked(i), numSamples);
  221673. if (out != 0)
  221674. outChans [numActiveOutChans++] = (float*) out;
  221675. }
  221676. const ScopedLock sl (callbackLock);
  221677. if (callback != 0)
  221678. {
  221679. callback->audioDeviceIOCallback (const_cast<const float**> (inChans.getData()), numActiveInChans,
  221680. outChans, numActiveOutChans, numSamples);
  221681. }
  221682. else
  221683. {
  221684. for (i = 0; i < numActiveOutChans; ++i)
  221685. zeromem (outChans[i], sizeof (float) * numSamples);
  221686. }
  221687. }
  221688. static int processCallback (jack_nframes_t nframes, void* callbackArgument)
  221689. {
  221690. if (callbackArgument != 0)
  221691. ((JackAudioIODevice*) callbackArgument)->process (nframes);
  221692. return 0;
  221693. }
  221694. static void threadInitCallback (void* callbackArgument)
  221695. {
  221696. jack_Log ("JackAudioIODevice::initialise");
  221697. }
  221698. static void shutdownCallback (void* callbackArgument)
  221699. {
  221700. jack_Log ("JackAudioIODevice::shutdown");
  221701. JackAudioIODevice* device = (JackAudioIODevice*) callbackArgument;
  221702. if (device != 0)
  221703. {
  221704. device->client = 0;
  221705. device->close();
  221706. }
  221707. }
  221708. static void errorCallback (const char* msg)
  221709. {
  221710. jack_Log ("JackAudioIODevice::errorCallback " + String (msg));
  221711. }
  221712. bool isOpen_;
  221713. jack_client_t* client;
  221714. String lastError;
  221715. AudioIODeviceCallback* callback;
  221716. CriticalSection callbackLock;
  221717. HeapBlock <float*> inChans, outChans;
  221718. int totalNumberOfInputChannels;
  221719. int totalNumberOfOutputChannels;
  221720. Array<void*> inputPorts, outputPorts;
  221721. };
  221722. class JackAudioIODeviceType : public AudioIODeviceType
  221723. {
  221724. public:
  221725. JackAudioIODeviceType()
  221726. : AudioIODeviceType ("JACK"),
  221727. hasScanned (false)
  221728. {
  221729. }
  221730. ~JackAudioIODeviceType()
  221731. {
  221732. }
  221733. void scanForDevices()
  221734. {
  221735. hasScanned = true;
  221736. inputNames.clear();
  221737. inputIds.clear();
  221738. outputNames.clear();
  221739. outputIds.clear();
  221740. if (juce_libjack_handle == 0)
  221741. {
  221742. juce_libjack_handle = dlopen ("libjack.so", RTLD_LAZY);
  221743. if (juce_libjack_handle == 0)
  221744. return;
  221745. }
  221746. // open a dummy client
  221747. jack_status_t status;
  221748. jack_client_t* client = JUCE_NAMESPACE::jack_client_open ("JuceJackDummy", JackNoStartServer, &status);
  221749. if (client == 0)
  221750. {
  221751. dumpJackErrorMessage (status);
  221752. }
  221753. else
  221754. {
  221755. // scan for output devices
  221756. const char** ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsOutput);
  221757. if (ports != 0)
  221758. {
  221759. int j = 0;
  221760. while (ports[j] != 0)
  221761. {
  221762. String clientName (ports[j]);
  221763. clientName = clientName.upToFirstOccurrenceOf (":", false, false);
  221764. if (clientName != String (JUCE_JACK_CLIENT_NAME)
  221765. && ! inputNames.contains (clientName))
  221766. {
  221767. inputNames.add (clientName);
  221768. inputIds.add (ports [j]);
  221769. }
  221770. ++j;
  221771. }
  221772. free (ports);
  221773. }
  221774. // scan for input devices
  221775. ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsInput);
  221776. if (ports != 0)
  221777. {
  221778. int j = 0;
  221779. while (ports[j] != 0)
  221780. {
  221781. String clientName (ports[j]);
  221782. clientName = clientName.upToFirstOccurrenceOf (":", false, false);
  221783. if (clientName != String (JUCE_JACK_CLIENT_NAME)
  221784. && ! outputNames.contains (clientName))
  221785. {
  221786. outputNames.add (clientName);
  221787. outputIds.add (ports [j]);
  221788. }
  221789. ++j;
  221790. }
  221791. free (ports);
  221792. }
  221793. JUCE_NAMESPACE::jack_client_close (client);
  221794. }
  221795. }
  221796. const StringArray getDeviceNames (bool wantInputNames) const
  221797. {
  221798. jassert (hasScanned); // need to call scanForDevices() before doing this
  221799. return wantInputNames ? inputNames : outputNames;
  221800. }
  221801. int getDefaultDeviceIndex (bool forInput) const
  221802. {
  221803. jassert (hasScanned); // need to call scanForDevices() before doing this
  221804. return 0;
  221805. }
  221806. bool hasSeparateInputsAndOutputs() const { return true; }
  221807. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  221808. {
  221809. jassert (hasScanned); // need to call scanForDevices() before doing this
  221810. JackAudioIODevice* d = dynamic_cast <JackAudioIODevice*> (device);
  221811. if (d == 0)
  221812. return -1;
  221813. return asInput ? inputIds.indexOf (d->inputId)
  221814. : outputIds.indexOf (d->outputId);
  221815. }
  221816. AudioIODevice* createDevice (const String& outputDeviceName,
  221817. const String& inputDeviceName)
  221818. {
  221819. jassert (hasScanned); // need to call scanForDevices() before doing this
  221820. const int inputIndex = inputNames.indexOf (inputDeviceName);
  221821. const int outputIndex = outputNames.indexOf (outputDeviceName);
  221822. if (inputIndex >= 0 || outputIndex >= 0)
  221823. return new JackAudioIODevice (outputIndex >= 0 ? outputDeviceName
  221824. : inputDeviceName,
  221825. inputIds [inputIndex],
  221826. outputIds [outputIndex]);
  221827. return 0;
  221828. }
  221829. juce_UseDebuggingNewOperator
  221830. private:
  221831. StringArray inputNames, outputNames, inputIds, outputIds;
  221832. bool hasScanned;
  221833. JackAudioIODeviceType (const JackAudioIODeviceType&);
  221834. JackAudioIODeviceType& operator= (const JackAudioIODeviceType&);
  221835. };
  221836. AudioIODeviceType* juce_createAudioIODeviceType_JACK()
  221837. {
  221838. return new JackAudioIODeviceType();
  221839. }
  221840. #else // if JACK is turned off..
  221841. AudioIODeviceType* juce_createAudioIODeviceType_JACK() { return 0; }
  221842. #endif
  221843. #endif
  221844. /*** End of inlined file: juce_linux_JackAudio.cpp ***/
  221845. /*** Start of inlined file: juce_linux_Midi.cpp ***/
  221846. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  221847. // compiled on its own).
  221848. #if JUCE_INCLUDED_FILE
  221849. #if JUCE_ALSA
  221850. static snd_seq_t* iterateDevices (const bool forInput,
  221851. StringArray& deviceNamesFound,
  221852. const int deviceIndexToOpen)
  221853. {
  221854. snd_seq_t* returnedHandle = 0;
  221855. snd_seq_t* seqHandle;
  221856. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  221857. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  221858. {
  221859. snd_seq_system_info_t* systemInfo;
  221860. snd_seq_client_info_t* clientInfo;
  221861. if (snd_seq_system_info_malloc (&systemInfo) == 0)
  221862. {
  221863. if (snd_seq_system_info (seqHandle, systemInfo) == 0
  221864. && snd_seq_client_info_malloc (&clientInfo) == 0)
  221865. {
  221866. int numClients = snd_seq_system_info_get_cur_clients (systemInfo);
  221867. while (--numClients >= 0 && returnedHandle == 0)
  221868. {
  221869. if (snd_seq_query_next_client (seqHandle, clientInfo) == 0)
  221870. {
  221871. snd_seq_port_info_t* portInfo;
  221872. if (snd_seq_port_info_malloc (&portInfo) == 0)
  221873. {
  221874. int numPorts = snd_seq_client_info_get_num_ports (clientInfo);
  221875. const int client = snd_seq_client_info_get_client (clientInfo);
  221876. snd_seq_port_info_set_client (portInfo, client);
  221877. snd_seq_port_info_set_port (portInfo, -1);
  221878. while (--numPorts >= 0)
  221879. {
  221880. if (snd_seq_query_next_port (seqHandle, portInfo) == 0
  221881. && (snd_seq_port_info_get_capability (portInfo)
  221882. & (forInput ? SND_SEQ_PORT_CAP_READ
  221883. : SND_SEQ_PORT_CAP_WRITE)) != 0)
  221884. {
  221885. deviceNamesFound.add (snd_seq_client_info_get_name (clientInfo));
  221886. if (deviceNamesFound.size() == deviceIndexToOpen + 1)
  221887. {
  221888. const int sourcePort = snd_seq_port_info_get_port (portInfo);
  221889. const int sourceClient = snd_seq_client_info_get_client (clientInfo);
  221890. if (sourcePort != -1)
  221891. {
  221892. snd_seq_set_client_name (seqHandle,
  221893. forInput ? "Juce Midi Input"
  221894. : "Juce Midi Output");
  221895. const int portId
  221896. = snd_seq_create_simple_port (seqHandle,
  221897. forInput ? "Juce Midi In Port"
  221898. : "Juce Midi Out Port",
  221899. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  221900. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  221901. SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  221902. snd_seq_connect_from (seqHandle, portId, sourceClient, sourcePort);
  221903. returnedHandle = seqHandle;
  221904. }
  221905. }
  221906. }
  221907. }
  221908. snd_seq_port_info_free (portInfo);
  221909. }
  221910. }
  221911. }
  221912. snd_seq_client_info_free (clientInfo);
  221913. }
  221914. snd_seq_system_info_free (systemInfo);
  221915. }
  221916. if (returnedHandle == 0)
  221917. snd_seq_close (seqHandle);
  221918. }
  221919. deviceNamesFound.appendNumbersToDuplicates (true, true);
  221920. return returnedHandle;
  221921. }
  221922. static snd_seq_t* createDevice (const bool forInput,
  221923. const String& deviceNameToOpen)
  221924. {
  221925. snd_seq_t* seqHandle = 0;
  221926. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  221927. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  221928. {
  221929. snd_seq_set_client_name (seqHandle,
  221930. (deviceNameToOpen + (forInput ? " Input" : " Output")).toCString());
  221931. const int portId
  221932. = snd_seq_create_simple_port (seqHandle,
  221933. forInput ? "in"
  221934. : "out",
  221935. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  221936. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  221937. forInput ? SND_SEQ_PORT_TYPE_APPLICATION
  221938. : SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  221939. if (portId < 0)
  221940. {
  221941. snd_seq_close (seqHandle);
  221942. seqHandle = 0;
  221943. }
  221944. }
  221945. return seqHandle;
  221946. }
  221947. class MidiOutputDevice
  221948. {
  221949. public:
  221950. MidiOutputDevice (MidiOutput* const midiOutput_,
  221951. snd_seq_t* const seqHandle_)
  221952. :
  221953. midiOutput (midiOutput_),
  221954. seqHandle (seqHandle_),
  221955. maxEventSize (16 * 1024)
  221956. {
  221957. jassert (seqHandle != 0 && midiOutput != 0);
  221958. snd_midi_event_new (maxEventSize, &midiParser);
  221959. }
  221960. ~MidiOutputDevice()
  221961. {
  221962. snd_midi_event_free (midiParser);
  221963. snd_seq_close (seqHandle);
  221964. }
  221965. void sendMessageNow (const MidiMessage& message)
  221966. {
  221967. if (message.getRawDataSize() > maxEventSize)
  221968. {
  221969. maxEventSize = message.getRawDataSize();
  221970. snd_midi_event_free (midiParser);
  221971. snd_midi_event_new (maxEventSize, &midiParser);
  221972. }
  221973. snd_seq_event_t event;
  221974. snd_seq_ev_clear (&event);
  221975. snd_midi_event_encode (midiParser,
  221976. message.getRawData(),
  221977. message.getRawDataSize(),
  221978. &event);
  221979. snd_midi_event_reset_encode (midiParser);
  221980. snd_seq_ev_set_source (&event, 0);
  221981. snd_seq_ev_set_subs (&event);
  221982. snd_seq_ev_set_direct (&event);
  221983. snd_seq_event_output (seqHandle, &event);
  221984. snd_seq_drain_output (seqHandle);
  221985. }
  221986. juce_UseDebuggingNewOperator
  221987. private:
  221988. MidiOutput* const midiOutput;
  221989. snd_seq_t* const seqHandle;
  221990. snd_midi_event_t* midiParser;
  221991. int maxEventSize;
  221992. };
  221993. const StringArray MidiOutput::getDevices()
  221994. {
  221995. StringArray devices;
  221996. iterateDevices (false, devices, -1);
  221997. return devices;
  221998. }
  221999. int MidiOutput::getDefaultDeviceIndex()
  222000. {
  222001. return 0;
  222002. }
  222003. MidiOutput* MidiOutput::openDevice (int deviceIndex)
  222004. {
  222005. MidiOutput* newDevice = 0;
  222006. StringArray devices;
  222007. snd_seq_t* const handle = iterateDevices (false, devices, deviceIndex);
  222008. if (handle != 0)
  222009. {
  222010. newDevice = new MidiOutput();
  222011. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  222012. }
  222013. return newDevice;
  222014. }
  222015. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  222016. {
  222017. MidiOutput* newDevice = 0;
  222018. snd_seq_t* const handle = createDevice (false, deviceName);
  222019. if (handle != 0)
  222020. {
  222021. newDevice = new MidiOutput();
  222022. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  222023. }
  222024. return newDevice;
  222025. }
  222026. MidiOutput::~MidiOutput()
  222027. {
  222028. MidiOutputDevice* const device = (MidiOutputDevice*) internal;
  222029. delete device;
  222030. }
  222031. void MidiOutput::reset()
  222032. {
  222033. }
  222034. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  222035. {
  222036. return false;
  222037. }
  222038. void MidiOutput::setVolume (float leftVol, float rightVol)
  222039. {
  222040. }
  222041. void MidiOutput::sendMessageNow (const MidiMessage& message)
  222042. {
  222043. ((MidiOutputDevice*) internal)->sendMessageNow (message);
  222044. }
  222045. class MidiInputThread : public Thread
  222046. {
  222047. public:
  222048. MidiInputThread (MidiInput* const midiInput_,
  222049. snd_seq_t* const seqHandle_,
  222050. MidiInputCallback* const callback_)
  222051. : Thread ("Juce MIDI Input"),
  222052. midiInput (midiInput_),
  222053. seqHandle (seqHandle_),
  222054. callback (callback_)
  222055. {
  222056. jassert (seqHandle != 0 && callback != 0 && midiInput != 0);
  222057. }
  222058. ~MidiInputThread()
  222059. {
  222060. snd_seq_close (seqHandle);
  222061. }
  222062. void run()
  222063. {
  222064. const int maxEventSize = 16 * 1024;
  222065. snd_midi_event_t* midiParser;
  222066. if (snd_midi_event_new (maxEventSize, &midiParser) >= 0)
  222067. {
  222068. HeapBlock <uint8> buffer (maxEventSize);
  222069. const int numPfds = snd_seq_poll_descriptors_count (seqHandle, POLLIN);
  222070. struct pollfd* const pfd = (struct pollfd*) alloca (numPfds * sizeof (struct pollfd));
  222071. snd_seq_poll_descriptors (seqHandle, pfd, numPfds, POLLIN);
  222072. while (! threadShouldExit())
  222073. {
  222074. if (poll (pfd, numPfds, 500) > 0)
  222075. {
  222076. snd_seq_event_t* inputEvent = 0;
  222077. snd_seq_nonblock (seqHandle, 1);
  222078. do
  222079. {
  222080. if (snd_seq_event_input (seqHandle, &inputEvent) >= 0)
  222081. {
  222082. // xxx what about SYSEXes that are too big for the buffer?
  222083. const int numBytes = snd_midi_event_decode (midiParser, buffer, maxEventSize, inputEvent);
  222084. snd_midi_event_reset_decode (midiParser);
  222085. if (numBytes > 0)
  222086. {
  222087. const MidiMessage message ((const uint8*) buffer,
  222088. numBytes,
  222089. Time::getMillisecondCounter() * 0.001);
  222090. callback->handleIncomingMidiMessage (midiInput, message);
  222091. }
  222092. snd_seq_free_event (inputEvent);
  222093. }
  222094. }
  222095. while (snd_seq_event_input_pending (seqHandle, 0) > 0);
  222096. snd_seq_free_event (inputEvent);
  222097. }
  222098. }
  222099. snd_midi_event_free (midiParser);
  222100. }
  222101. };
  222102. juce_UseDebuggingNewOperator
  222103. private:
  222104. MidiInput* const midiInput;
  222105. snd_seq_t* const seqHandle;
  222106. MidiInputCallback* const callback;
  222107. };
  222108. MidiInput::MidiInput (const String& name_)
  222109. : name (name_),
  222110. internal (0)
  222111. {
  222112. }
  222113. MidiInput::~MidiInput()
  222114. {
  222115. stop();
  222116. MidiInputThread* const thread = (MidiInputThread*) internal;
  222117. delete thread;
  222118. }
  222119. void MidiInput::start()
  222120. {
  222121. ((MidiInputThread*) internal)->startThread();
  222122. }
  222123. void MidiInput::stop()
  222124. {
  222125. ((MidiInputThread*) internal)->stopThread (3000);
  222126. }
  222127. int MidiInput::getDefaultDeviceIndex()
  222128. {
  222129. return 0;
  222130. }
  222131. const StringArray MidiInput::getDevices()
  222132. {
  222133. StringArray devices;
  222134. iterateDevices (true, devices, -1);
  222135. return devices;
  222136. }
  222137. MidiInput* MidiInput::openDevice (int deviceIndex, MidiInputCallback* callback)
  222138. {
  222139. MidiInput* newDevice = 0;
  222140. StringArray devices;
  222141. snd_seq_t* const handle = iterateDevices (true, devices, deviceIndex);
  222142. if (handle != 0)
  222143. {
  222144. newDevice = new MidiInput (devices [deviceIndex]);
  222145. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  222146. }
  222147. return newDevice;
  222148. }
  222149. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  222150. {
  222151. MidiInput* newDevice = 0;
  222152. snd_seq_t* const handle = createDevice (true, deviceName);
  222153. if (handle != 0)
  222154. {
  222155. newDevice = new MidiInput (deviceName);
  222156. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  222157. }
  222158. return newDevice;
  222159. }
  222160. #else
  222161. // (These are just stub functions if ALSA is unavailable...)
  222162. const StringArray MidiOutput::getDevices() { return StringArray(); }
  222163. int MidiOutput::getDefaultDeviceIndex() { return 0; }
  222164. MidiOutput* MidiOutput::openDevice (int) { return 0; }
  222165. MidiOutput* MidiOutput::createNewDevice (const String&) { return 0; }
  222166. MidiOutput::~MidiOutput() {}
  222167. void MidiOutput::reset() {}
  222168. bool MidiOutput::getVolume (float&, float&) { return false; }
  222169. void MidiOutput::setVolume (float, float) {}
  222170. void MidiOutput::sendMessageNow (const MidiMessage&) {}
  222171. MidiInput::MidiInput (const String& name_) : name (name_), internal (0) {}
  222172. MidiInput::~MidiInput() {}
  222173. void MidiInput::start() {}
  222174. void MidiInput::stop() {}
  222175. int MidiInput::getDefaultDeviceIndex() { return 0; }
  222176. const StringArray MidiInput::getDevices() { return StringArray(); }
  222177. MidiInput* MidiInput::openDevice (int, MidiInputCallback*) { return 0; }
  222178. MidiInput* MidiInput::createNewDevice (const String&, MidiInputCallback*) { return 0; }
  222179. #endif
  222180. #endif
  222181. /*** End of inlined file: juce_linux_Midi.cpp ***/
  222182. /*** Start of inlined file: juce_linux_AudioCDReader.cpp ***/
  222183. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  222184. // compiled on its own).
  222185. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  222186. AudioCDReader::AudioCDReader()
  222187. : AudioFormatReader (0, "CD Audio")
  222188. {
  222189. }
  222190. const StringArray AudioCDReader::getAvailableCDNames()
  222191. {
  222192. StringArray names;
  222193. return names;
  222194. }
  222195. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  222196. {
  222197. return 0;
  222198. }
  222199. AudioCDReader::~AudioCDReader()
  222200. {
  222201. }
  222202. void AudioCDReader::refreshTrackLengths()
  222203. {
  222204. }
  222205. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  222206. int64 startSampleInFile, int numSamples)
  222207. {
  222208. return false;
  222209. }
  222210. bool AudioCDReader::isCDStillPresent() const
  222211. {
  222212. return false;
  222213. }
  222214. int AudioCDReader::getNumTracks() const
  222215. {
  222216. return 0;
  222217. }
  222218. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  222219. {
  222220. return 0;
  222221. }
  222222. bool AudioCDReader::isTrackAudio (int trackNum) const
  222223. {
  222224. return false;
  222225. }
  222226. void AudioCDReader::enableIndexScanning (bool b)
  222227. {
  222228. }
  222229. int AudioCDReader::getLastIndex() const
  222230. {
  222231. return 0;
  222232. }
  222233. const Array<int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  222234. {
  222235. return Array<int>();
  222236. }
  222237. int AudioCDReader::getCDDBId()
  222238. {
  222239. return 0;
  222240. }
  222241. #endif
  222242. /*** End of inlined file: juce_linux_AudioCDReader.cpp ***/
  222243. /*** Start of inlined file: juce_linux_FileChooser.cpp ***/
  222244. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  222245. // compiled on its own).
  222246. #if JUCE_INCLUDED_FILE
  222247. void FileChooser::showPlatformDialog (Array<File>& results,
  222248. const String& title,
  222249. const File& file,
  222250. const String& filters,
  222251. bool isDirectory,
  222252. bool selectsFiles,
  222253. bool isSave,
  222254. bool warnAboutOverwritingExistingFiles,
  222255. bool selectMultipleFiles,
  222256. FilePreviewComponent* previewComponent)
  222257. {
  222258. const String separator (":");
  222259. String command ("zenity --file-selection");
  222260. if (title.isNotEmpty())
  222261. command << " --title=\"" << title << "\"";
  222262. if (file != File::nonexistent)
  222263. command << " --filename=\"" << file.getFullPathName () << "\"";
  222264. if (isDirectory)
  222265. command << " --directory";
  222266. if (isSave)
  222267. command << " --save";
  222268. if (selectMultipleFiles)
  222269. command << " --multiple --separator=\"" << separator << "\"";
  222270. command << " 2>&1";
  222271. MemoryOutputStream result;
  222272. int status = -1;
  222273. FILE* stream = popen (command.toUTF8(), "r");
  222274. if (stream != 0)
  222275. {
  222276. for (;;)
  222277. {
  222278. char buffer [1024];
  222279. const int bytesRead = fread (buffer, 1, sizeof (buffer), stream);
  222280. if (bytesRead <= 0)
  222281. break;
  222282. result.write (buffer, bytesRead);
  222283. }
  222284. status = pclose (stream);
  222285. }
  222286. if (status == 0)
  222287. {
  222288. StringArray tokens;
  222289. if (selectMultipleFiles)
  222290. tokens.addTokens (result.toUTF8(), separator, String::empty);
  222291. else
  222292. tokens.add (result.toUTF8());
  222293. for (int i = 0; i < tokens.size(); i++)
  222294. results.add (File (tokens[i]));
  222295. return;
  222296. }
  222297. //xxx ain't got one!
  222298. jassertfalse;
  222299. }
  222300. #endif
  222301. /*** End of inlined file: juce_linux_FileChooser.cpp ***/
  222302. /*** Start of inlined file: juce_linux_WebBrowserComponent.cpp ***/
  222303. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  222304. // compiled on its own).
  222305. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  222306. /*
  222307. Sorry.. This class isn't implemented on Linux!
  222308. */
  222309. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  222310. : browser (0),
  222311. blankPageShown (false),
  222312. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  222313. {
  222314. setOpaque (true);
  222315. }
  222316. WebBrowserComponent::~WebBrowserComponent()
  222317. {
  222318. }
  222319. void WebBrowserComponent::goToURL (const String& url,
  222320. const StringArray* headers,
  222321. const MemoryBlock* postData)
  222322. {
  222323. lastURL = url;
  222324. lastHeaders.clear();
  222325. if (headers != 0)
  222326. lastHeaders = *headers;
  222327. lastPostData.setSize (0);
  222328. if (postData != 0)
  222329. lastPostData = *postData;
  222330. blankPageShown = false;
  222331. }
  222332. void WebBrowserComponent::stop()
  222333. {
  222334. }
  222335. void WebBrowserComponent::goBack()
  222336. {
  222337. lastURL = String::empty;
  222338. blankPageShown = false;
  222339. }
  222340. void WebBrowserComponent::goForward()
  222341. {
  222342. lastURL = String::empty;
  222343. }
  222344. void WebBrowserComponent::refresh()
  222345. {
  222346. }
  222347. void WebBrowserComponent::paint (Graphics& g)
  222348. {
  222349. g.fillAll (Colours::white);
  222350. }
  222351. void WebBrowserComponent::checkWindowAssociation()
  222352. {
  222353. }
  222354. void WebBrowserComponent::reloadLastURL()
  222355. {
  222356. if (lastURL.isNotEmpty())
  222357. {
  222358. goToURL (lastURL, &lastHeaders, &lastPostData);
  222359. lastURL = String::empty;
  222360. }
  222361. }
  222362. void WebBrowserComponent::parentHierarchyChanged()
  222363. {
  222364. checkWindowAssociation();
  222365. }
  222366. void WebBrowserComponent::resized()
  222367. {
  222368. }
  222369. void WebBrowserComponent::visibilityChanged()
  222370. {
  222371. checkWindowAssociation();
  222372. }
  222373. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  222374. {
  222375. return true;
  222376. }
  222377. #endif
  222378. /*** End of inlined file: juce_linux_WebBrowserComponent.cpp ***/
  222379. #endif
  222380. END_JUCE_NAMESPACE
  222381. #endif
  222382. /*** End of inlined file: juce_linux_NativeCode.cpp ***/
  222383. #endif
  222384. #if JUCE_MAC || JUCE_IPHONE
  222385. /*** Start of inlined file: juce_mac_NativeCode.mm ***/
  222386. /*
  222387. This file wraps together all the mac-specific code, so that
  222388. we can include all the native headers just once, and compile all our
  222389. platform-specific stuff in one big lump, keeping it out of the way of
  222390. the rest of the codebase.
  222391. */
  222392. #if JUCE_MAC || JUCE_IPHONE
  222393. BEGIN_JUCE_NAMESPACE
  222394. #undef Point
  222395. #define JUCE_INCLUDED_FILE 1
  222396. // Now include the actual code files..
  222397. /*** Start of inlined file: juce_mac_ObjCSuffix.h ***/
  222398. /** This suffix is used for naming all Obj-C classes that are used inside juce.
  222399. Because of the flat naming structure used by Obj-C, you can get horrible situations where
  222400. two DLLs are loaded into a host, each of which uses classes with the same names, and these get
  222401. cross-linked so that when you make a call to a class that you thought was private, it ends up
  222402. actually calling into a similarly named class in the other module's address space.
  222403. By changing this macro to a unique value, you ensure that all the obj-C classes in your app
  222404. have unique names, and should avoid this problem.
  222405. If you're using the amalgamated version, you can just set this macro to something unique before
  222406. you include juce_amalgamated.cpp.
  222407. */
  222408. #ifndef JUCE_ObjCExtraSuffix
  222409. #define JUCE_ObjCExtraSuffix 3
  222410. #endif
  222411. #define appendMacro1(a, b, c, d, e) a ## _ ## b ## _ ## c ## _ ## d ## _ ## e
  222412. #define appendMacro2(a, b, c, d, e) appendMacro1(a, b, c, d, e)
  222413. #define MakeObjCClassName(rootName) appendMacro2 (rootName, JUCE_MAJOR_VERSION, JUCE_MINOR_VERSION, JUCE_BUILDNUMBER, JUCE_ObjCExtraSuffix)
  222414. /*** End of inlined file: juce_mac_ObjCSuffix.h ***/
  222415. /*** Start of inlined file: juce_mac_Strings.mm ***/
  222416. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  222417. // compiled on its own).
  222418. #if JUCE_INCLUDED_FILE
  222419. static const String nsStringToJuce (NSString* s)
  222420. {
  222421. return String::fromUTF8 ([s UTF8String]);
  222422. }
  222423. static NSString* juceStringToNS (const String& s)
  222424. {
  222425. return [NSString stringWithUTF8String: s.toUTF8()];
  222426. }
  222427. static const String convertUTF16ToString (const UniChar* utf16)
  222428. {
  222429. String s;
  222430. while (*utf16 != 0)
  222431. s += (juce_wchar) *utf16++;
  222432. return s;
  222433. }
  222434. const String PlatformUtilities::cfStringToJuceString (CFStringRef cfString)
  222435. {
  222436. String result;
  222437. if (cfString != 0)
  222438. {
  222439. CFRange range = { 0, CFStringGetLength (cfString) };
  222440. HeapBlock <UniChar> u (range.length + 1);
  222441. CFStringGetCharacters (cfString, range, u);
  222442. u[range.length] = 0;
  222443. result = convertUTF16ToString (u);
  222444. }
  222445. return result;
  222446. }
  222447. CFStringRef PlatformUtilities::juceStringToCFString (const String& s)
  222448. {
  222449. const int len = s.length();
  222450. HeapBlock <UniChar> temp (len + 2);
  222451. for (int i = 0; i <= len; ++i)
  222452. temp[i] = s[i];
  222453. return CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  222454. }
  222455. const String PlatformUtilities::convertToPrecomposedUnicode (const String& s)
  222456. {
  222457. #if JUCE_IPHONE
  222458. const ScopedAutoReleasePool pool;
  222459. return nsStringToJuce ([juceStringToNS (s) precomposedStringWithCanonicalMapping]);
  222460. #else
  222461. UnicodeMapping map;
  222462. map.unicodeEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  222463. kUnicodeNoSubset,
  222464. kTextEncodingDefaultFormat);
  222465. map.otherEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  222466. kUnicodeCanonicalCompVariant,
  222467. kTextEncodingDefaultFormat);
  222468. map.mappingVersion = kUnicodeUseLatestMapping;
  222469. UnicodeToTextInfo conversionInfo = 0;
  222470. String result;
  222471. if (CreateUnicodeToTextInfo (&map, &conversionInfo) == noErr)
  222472. {
  222473. const int len = s.length();
  222474. HeapBlock <UniChar> tempIn, tempOut;
  222475. tempIn.calloc (len + 2);
  222476. tempOut.calloc (len + 2);
  222477. for (int i = 0; i <= len; ++i)
  222478. tempIn[i] = s[i];
  222479. ByteCount bytesRead = 0;
  222480. ByteCount outputBufferSize = 0;
  222481. if (ConvertFromUnicodeToText (conversionInfo,
  222482. len * sizeof (UniChar), tempIn,
  222483. kUnicodeDefaultDirectionMask,
  222484. 0, 0, 0, 0,
  222485. len * sizeof (UniChar), &bytesRead,
  222486. &outputBufferSize, tempOut) == noErr)
  222487. {
  222488. result.preallocateStorage (bytesRead / sizeof (UniChar) + 2);
  222489. juce_wchar* t = result;
  222490. unsigned int i;
  222491. for (i = 0; i < bytesRead / sizeof (UniChar); ++i)
  222492. t[i] = (juce_wchar) tempOut[i];
  222493. t[i] = 0;
  222494. }
  222495. DisposeUnicodeToTextInfo (&conversionInfo);
  222496. }
  222497. return result;
  222498. #endif
  222499. }
  222500. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  222501. void SystemClipboard::copyTextToClipboard (const String& text)
  222502. {
  222503. #if JUCE_IPHONE
  222504. [[UIPasteboard generalPasteboard] setValue: juceStringToNS (text)
  222505. forPasteboardType: @"public.text"];
  222506. #else
  222507. [[NSPasteboard generalPasteboard] declareTypes: [NSArray arrayWithObject: NSStringPboardType]
  222508. owner: nil];
  222509. [[NSPasteboard generalPasteboard] setString: juceStringToNS (text)
  222510. forType: NSStringPboardType];
  222511. #endif
  222512. }
  222513. const String SystemClipboard::getTextFromClipboard()
  222514. {
  222515. #if JUCE_IPHONE
  222516. NSString* text = [[UIPasteboard generalPasteboard] valueForPasteboardType: @"public.text"];
  222517. #else
  222518. NSString* text = [[NSPasteboard generalPasteboard] stringForType: NSStringPboardType];
  222519. #endif
  222520. return text == 0 ? String::empty
  222521. : nsStringToJuce (text);
  222522. }
  222523. #endif
  222524. #endif
  222525. /*** End of inlined file: juce_mac_Strings.mm ***/
  222526. /*** Start of inlined file: juce_mac_SystemStats.mm ***/
  222527. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  222528. // compiled on its own).
  222529. #if JUCE_INCLUDED_FILE
  222530. namespace SystemStatsHelpers
  222531. {
  222532. static int64 highResTimerFrequency = 0;
  222533. static double highResTimerToMillisecRatio = 0;
  222534. #if JUCE_INTEL
  222535. static void juce_getCpuVendor (char* const v) throw()
  222536. {
  222537. int vendor[4];
  222538. zerostruct (vendor);
  222539. int dummy = 0;
  222540. asm ("mov %%ebx, %%esi \n\t"
  222541. "cpuid \n\t"
  222542. "xchg %%esi, %%ebx"
  222543. : "=a" (dummy), "=S" (vendor[0]), "=c" (vendor[2]), "=d" (vendor[1]) : "a" (0));
  222544. memcpy (v, vendor, 16);
  222545. }
  222546. static unsigned int getCPUIDWord (unsigned int& familyModel, unsigned int& extFeatures)
  222547. {
  222548. unsigned int cpu = 0;
  222549. unsigned int ext = 0;
  222550. unsigned int family = 0;
  222551. unsigned int dummy = 0;
  222552. asm ("mov %%ebx, %%esi \n\t"
  222553. "cpuid \n\t"
  222554. "xchg %%esi, %%ebx"
  222555. : "=a" (family), "=S" (ext), "=c" (dummy), "=d" (cpu) : "a" (1));
  222556. familyModel = family;
  222557. extFeatures = ext;
  222558. return cpu;
  222559. }
  222560. struct CPUFlags
  222561. {
  222562. bool hasMMX : 1;
  222563. bool hasSSE : 1;
  222564. bool hasSSE2 : 1;
  222565. bool has3DNow : 1;
  222566. };
  222567. static CPUFlags cpuFlags;
  222568. #endif
  222569. }
  222570. void SystemStats::initialiseStats()
  222571. {
  222572. using namespace SystemStatsHelpers;
  222573. static bool initialised = false;
  222574. if (! initialised)
  222575. {
  222576. initialised = true;
  222577. #if JUCE_MAC
  222578. // extremely annoying: adding this line stops the apple menu items from working. Of
  222579. // course, not adding it means that carbon windows (e.g. in plugins) won't get
  222580. // any events.
  222581. //NSApplicationLoad();
  222582. [NSApplication sharedApplication];
  222583. #endif
  222584. #if JUCE_INTEL
  222585. {
  222586. unsigned int familyModel, extFeatures;
  222587. const unsigned int features = getCPUIDWord (familyModel, extFeatures);
  222588. cpuFlags.hasMMX = ((features & (1 << 23)) != 0);
  222589. cpuFlags.hasSSE = ((features & (1 << 25)) != 0);
  222590. cpuFlags.hasSSE2 = ((features & (1 << 26)) != 0);
  222591. cpuFlags.has3DNow = ((extFeatures & (1 << 31)) != 0);
  222592. }
  222593. #endif
  222594. mach_timebase_info_data_t timebase;
  222595. (void) mach_timebase_info (&timebase);
  222596. highResTimerFrequency = (int64) (1.0e9 * timebase.denom / timebase.numer);
  222597. highResTimerToMillisecRatio = timebase.numer / (1.0e6 * timebase.denom);
  222598. String s (SystemStats::getJUCEVersion());
  222599. rlimit lim;
  222600. getrlimit (RLIMIT_NOFILE, &lim);
  222601. lim.rlim_cur = lim.rlim_max = RLIM_INFINITY;
  222602. setrlimit (RLIMIT_NOFILE, &lim);
  222603. }
  222604. }
  222605. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  222606. {
  222607. return MacOSX;
  222608. }
  222609. const String SystemStats::getOperatingSystemName()
  222610. {
  222611. return "Mac OS X";
  222612. }
  222613. bool SystemStats::isOperatingSystem64Bit()
  222614. {
  222615. #if JUCE_64BIT
  222616. return true;
  222617. #else
  222618. //xxx not sure how to find this out?..
  222619. return false;
  222620. #endif
  222621. }
  222622. int SystemStats::getMemorySizeInMegabytes()
  222623. {
  222624. uint64 mem = 0;
  222625. size_t memSize = sizeof (mem);
  222626. int mib[] = { CTL_HW, HW_MEMSIZE };
  222627. sysctl (mib, 2, &mem, &memSize, 0, 0);
  222628. return (int) (mem / (1024 * 1024));
  222629. }
  222630. bool SystemStats::hasMMX()
  222631. {
  222632. #if JUCE_INTEL
  222633. return SystemStatsHelpers::cpuFlags.hasMMX;
  222634. #else
  222635. return false;
  222636. #endif
  222637. }
  222638. bool SystemStats::hasSSE()
  222639. {
  222640. #if JUCE_INTEL
  222641. return SystemStatsHelpers::cpuFlags.hasSSE;
  222642. #else
  222643. return false;
  222644. #endif
  222645. }
  222646. bool SystemStats::hasSSE2()
  222647. {
  222648. #if JUCE_INTEL
  222649. return SystemStatsHelpers::cpuFlags.hasSSE2;
  222650. #else
  222651. return false;
  222652. #endif
  222653. }
  222654. bool SystemStats::has3DNow()
  222655. {
  222656. #if JUCE_INTEL
  222657. return SystemStatsHelpers::cpuFlags.has3DNow;
  222658. #else
  222659. return false;
  222660. #endif
  222661. }
  222662. const String SystemStats::getCpuVendor()
  222663. {
  222664. #if JUCE_INTEL
  222665. char v [16];
  222666. SystemStatsHelpers::juce_getCpuVendor (v);
  222667. return String (v, 16);
  222668. #else
  222669. return String::empty;
  222670. #endif
  222671. }
  222672. int SystemStats::getCpuSpeedInMegaherz()
  222673. {
  222674. uint64 speedHz = 0;
  222675. size_t speedSize = sizeof (speedHz);
  222676. int mib[] = { CTL_HW, HW_CPU_FREQ };
  222677. sysctl (mib, 2, &speedHz, &speedSize, 0, 0);
  222678. #if JUCE_BIG_ENDIAN
  222679. if (speedSize == 4)
  222680. speedHz >>= 32;
  222681. #endif
  222682. return (int) (speedHz / 1000000);
  222683. }
  222684. int SystemStats::getNumCpus()
  222685. {
  222686. #if JUCE_IPHONE || (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5)
  222687. return (int) [[NSProcessInfo processInfo] activeProcessorCount];
  222688. #else
  222689. return MPProcessors();
  222690. #endif
  222691. }
  222692. const String SystemStats::getLogonName()
  222693. {
  222694. return nsStringToJuce (NSUserName());
  222695. }
  222696. const String SystemStats::getFullUserName()
  222697. {
  222698. return nsStringToJuce (NSFullUserName());
  222699. }
  222700. uint32 juce_millisecondsSinceStartup() throw()
  222701. {
  222702. return (uint32) (mach_absolute_time() * SystemStatsHelpers::highResTimerToMillisecRatio);
  222703. }
  222704. double Time::getMillisecondCounterHiRes() throw()
  222705. {
  222706. return mach_absolute_time() * SystemStatsHelpers::highResTimerToMillisecRatio;
  222707. }
  222708. int64 Time::getHighResolutionTicks() throw()
  222709. {
  222710. return (int64) mach_absolute_time();
  222711. }
  222712. int64 Time::getHighResolutionTicksPerSecond() throw()
  222713. {
  222714. return SystemStatsHelpers::highResTimerFrequency;
  222715. }
  222716. bool Time::setSystemTimeToThisTime() const
  222717. {
  222718. jassertfalse;
  222719. return false;
  222720. }
  222721. int SystemStats::getPageSize()
  222722. {
  222723. return (int) NSPageSize();
  222724. }
  222725. void PlatformUtilities::fpuReset()
  222726. {
  222727. }
  222728. #endif
  222729. /*** End of inlined file: juce_mac_SystemStats.mm ***/
  222730. /*** Start of inlined file: juce_mac_Network.mm ***/
  222731. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  222732. // compiled on its own).
  222733. #if JUCE_INCLUDED_FILE
  222734. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian)
  222735. {
  222736. #ifndef IFT_ETHER
  222737. #define IFT_ETHER 6
  222738. #endif
  222739. ifaddrs* addrs = 0;
  222740. int numResults = 0;
  222741. if (getifaddrs (&addrs) == 0)
  222742. {
  222743. const ifaddrs* cursor = addrs;
  222744. while (cursor != 0 && numResults < maxNum)
  222745. {
  222746. sockaddr_storage* sto = (sockaddr_storage*) cursor->ifa_addr;
  222747. if (sto->ss_family == AF_LINK)
  222748. {
  222749. const sockaddr_dl* const sadd = (const sockaddr_dl*) cursor->ifa_addr;
  222750. if (sadd->sdl_type == IFT_ETHER)
  222751. {
  222752. const uint8* const addr = ((const uint8*) sadd->sdl_data) + sadd->sdl_nlen;
  222753. uint64 a = 0;
  222754. for (int i = 6; --i >= 0;)
  222755. a = (a << 8) | addr [littleEndian ? i : (5 - i)];
  222756. *addresses++ = (int64) a;
  222757. ++numResults;
  222758. }
  222759. }
  222760. cursor = cursor->ifa_next;
  222761. }
  222762. freeifaddrs (addrs);
  222763. }
  222764. return numResults;
  222765. }
  222766. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  222767. const String& emailSubject,
  222768. const String& bodyText,
  222769. const StringArray& filesToAttach)
  222770. {
  222771. #if JUCE_IPHONE
  222772. //xxx probably need to use MFMailComposeViewController
  222773. jassertfalse;
  222774. return false;
  222775. #else
  222776. const ScopedAutoReleasePool pool;
  222777. String script;
  222778. script << "tell application \"Mail\"\r\n"
  222779. "set newMessage to make new outgoing message with properties {subject:\""
  222780. << emailSubject.replace ("\"", "\\\"")
  222781. << "\", content:\""
  222782. << bodyText.replace ("\"", "\\\"")
  222783. << "\" & return & return}\r\n"
  222784. "tell newMessage\r\n"
  222785. "set visible to true\r\n"
  222786. "set sender to \"sdfsdfsdfewf\"\r\n"
  222787. "make new to recipient at end of to recipients with properties {address:\""
  222788. << targetEmailAddress
  222789. << "\"}\r\n";
  222790. for (int i = 0; i < filesToAttach.size(); ++i)
  222791. {
  222792. script << "tell content\r\n"
  222793. "make new attachment with properties {file name:\""
  222794. << filesToAttach[i].replace ("\"", "\\\"")
  222795. << "\"} at after the last paragraph\r\n"
  222796. "end tell\r\n";
  222797. }
  222798. script << "end tell\r\n"
  222799. "end tell\r\n";
  222800. NSAppleScript* s = [[NSAppleScript alloc]
  222801. initWithSource: juceStringToNS (script)];
  222802. NSDictionary* error = 0;
  222803. const bool ok = [s executeAndReturnError: &error] != nil;
  222804. [s release];
  222805. return ok;
  222806. #endif
  222807. }
  222808. END_JUCE_NAMESPACE
  222809. using namespace JUCE_NAMESPACE;
  222810. #define JuceURLConnection MakeObjCClassName(JuceURLConnection)
  222811. @interface JuceURLConnection : NSObject
  222812. {
  222813. @public
  222814. NSURLRequest* request;
  222815. NSURLConnection* connection;
  222816. NSMutableData* data;
  222817. Thread* runLoopThread;
  222818. bool initialised, hasFailed, hasFinished;
  222819. int position;
  222820. int64 contentLength;
  222821. NSDictionary* headers;
  222822. NSLock* dataLock;
  222823. }
  222824. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req withCallback: (URL::OpenStreamProgressCallback*) callback withContext: (void*) context;
  222825. - (void) dealloc;
  222826. - (void) connection: (NSURLConnection*) connection didReceiveResponse: (NSURLResponse*) response;
  222827. - (void) connection: (NSURLConnection*) connection didFailWithError: (NSError*) error;
  222828. - (void) connection: (NSURLConnection*) connection didReceiveData: (NSData*) data;
  222829. - (void) connectionDidFinishLoading: (NSURLConnection*) connection;
  222830. - (BOOL) isOpen;
  222831. - (int) read: (char*) dest numBytes: (int) num;
  222832. - (int) readPosition;
  222833. - (void) stop;
  222834. - (void) createConnection;
  222835. @end
  222836. class JuceURLConnectionMessageThread : public Thread
  222837. {
  222838. JuceURLConnection* owner;
  222839. public:
  222840. JuceURLConnectionMessageThread (JuceURLConnection* owner_)
  222841. : Thread ("http connection"),
  222842. owner (owner_)
  222843. {
  222844. }
  222845. ~JuceURLConnectionMessageThread()
  222846. {
  222847. stopThread (10000);
  222848. }
  222849. void run()
  222850. {
  222851. [owner createConnection];
  222852. while (! threadShouldExit())
  222853. {
  222854. const ScopedAutoReleasePool pool;
  222855. [[NSRunLoop currentRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  222856. }
  222857. }
  222858. };
  222859. @implementation JuceURLConnection
  222860. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req
  222861. withCallback: (URL::OpenStreamProgressCallback*) callback
  222862. withContext: (void*) context;
  222863. {
  222864. [super init];
  222865. request = req;
  222866. [request retain];
  222867. data = [[NSMutableData data] retain];
  222868. dataLock = [[NSLock alloc] init];
  222869. connection = 0;
  222870. initialised = false;
  222871. hasFailed = false;
  222872. hasFinished = false;
  222873. contentLength = -1;
  222874. headers = 0;
  222875. runLoopThread = new JuceURLConnectionMessageThread (self);
  222876. runLoopThread->startThread();
  222877. while (runLoopThread->isThreadRunning() && ! initialised)
  222878. {
  222879. if (callback != 0)
  222880. callback (context, -1, (int) [[request HTTPBody] length]);
  222881. Thread::sleep (1);
  222882. }
  222883. return self;
  222884. }
  222885. - (void) dealloc
  222886. {
  222887. [self stop];
  222888. deleteAndZero (runLoopThread);
  222889. [connection release];
  222890. [data release];
  222891. [dataLock release];
  222892. [request release];
  222893. [headers release];
  222894. [super dealloc];
  222895. }
  222896. - (void) createConnection
  222897. {
  222898. NSInteger oldRetainCount = [self retainCount];
  222899. connection = [[NSURLConnection alloc] initWithRequest: request
  222900. delegate: self];
  222901. if (oldRetainCount == [self retainCount])
  222902. [self retain]; // newer SDK should already retain this, but there were problems in older versions..
  222903. if (connection == nil)
  222904. runLoopThread->signalThreadShouldExit();
  222905. }
  222906. - (void) connection: (NSURLConnection*) conn didReceiveResponse: (NSURLResponse*) response
  222907. {
  222908. (void) conn;
  222909. [dataLock lock];
  222910. [data setLength: 0];
  222911. [dataLock unlock];
  222912. initialised = true;
  222913. contentLength = [response expectedContentLength];
  222914. [headers release];
  222915. headers = 0;
  222916. if ([response isKindOfClass: [NSHTTPURLResponse class]])
  222917. headers = [[((NSHTTPURLResponse*) response) allHeaderFields] retain];
  222918. }
  222919. - (void) connection: (NSURLConnection*) conn didFailWithError: (NSError*) error
  222920. {
  222921. (void) conn;
  222922. DBG (nsStringToJuce ([error description]));
  222923. hasFailed = true;
  222924. initialised = true;
  222925. if (runLoopThread != 0)
  222926. runLoopThread->signalThreadShouldExit();
  222927. }
  222928. - (void) connection: (NSURLConnection*) conn didReceiveData: (NSData*) newData
  222929. {
  222930. (void) conn;
  222931. [dataLock lock];
  222932. [data appendData: newData];
  222933. [dataLock unlock];
  222934. initialised = true;
  222935. }
  222936. - (void) connectionDidFinishLoading: (NSURLConnection*) conn
  222937. {
  222938. (void) conn;
  222939. hasFinished = true;
  222940. initialised = true;
  222941. if (runLoopThread != 0)
  222942. runLoopThread->signalThreadShouldExit();
  222943. }
  222944. - (BOOL) isOpen
  222945. {
  222946. return connection != 0 && ! hasFailed;
  222947. }
  222948. - (int) readPosition
  222949. {
  222950. return position;
  222951. }
  222952. - (int) read: (char*) dest numBytes: (int) numNeeded
  222953. {
  222954. int numDone = 0;
  222955. while (numNeeded > 0)
  222956. {
  222957. int available = jmin (numNeeded, (int) [data length]);
  222958. if (available > 0)
  222959. {
  222960. [dataLock lock];
  222961. [data getBytes: dest length: available];
  222962. [data replaceBytesInRange: NSMakeRange (0, available) withBytes: nil length: 0];
  222963. [dataLock unlock];
  222964. numDone += available;
  222965. numNeeded -= available;
  222966. dest += available;
  222967. }
  222968. else
  222969. {
  222970. if (hasFailed || hasFinished)
  222971. break;
  222972. Thread::sleep (1);
  222973. }
  222974. }
  222975. position += numDone;
  222976. return numDone;
  222977. }
  222978. - (void) stop
  222979. {
  222980. [connection cancel];
  222981. if (runLoopThread != 0)
  222982. runLoopThread->stopThread (10000);
  222983. }
  222984. @end
  222985. BEGIN_JUCE_NAMESPACE
  222986. void* juce_openInternetFile (const String& url,
  222987. const String& headers,
  222988. const MemoryBlock& postData,
  222989. const bool isPost,
  222990. URL::OpenStreamProgressCallback* callback,
  222991. void* callbackContext,
  222992. int timeOutMs)
  222993. {
  222994. const ScopedAutoReleasePool pool;
  222995. NSMutableURLRequest* req = [NSMutableURLRequest
  222996. requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  222997. cachePolicy: NSURLRequestUseProtocolCachePolicy
  222998. timeoutInterval: timeOutMs <= 0 ? 60.0 : (timeOutMs / 1000.0)];
  222999. if (req == nil)
  223000. return 0;
  223001. [req setHTTPMethod: isPost ? @"POST" : @"GET"];
  223002. //[req setCachePolicy: NSURLRequestReloadIgnoringLocalAndRemoteCacheData];
  223003. StringArray headerLines;
  223004. headerLines.addLines (headers);
  223005. headerLines.removeEmptyStrings (true);
  223006. for (int i = 0; i < headerLines.size(); ++i)
  223007. {
  223008. const String key (headerLines[i].upToFirstOccurrenceOf (":", false, false).trim());
  223009. const String value (headerLines[i].fromFirstOccurrenceOf (":", false, false).trim());
  223010. if (key.isNotEmpty() && value.isNotEmpty())
  223011. [req addValue: juceStringToNS (value) forHTTPHeaderField: juceStringToNS (key)];
  223012. }
  223013. if (isPost && postData.getSize() > 0)
  223014. {
  223015. [req setHTTPBody: [NSData dataWithBytes: postData.getData()
  223016. length: postData.getSize()]];
  223017. }
  223018. JuceURLConnection* const s = [[JuceURLConnection alloc] initWithRequest: req
  223019. withCallback: callback
  223020. withContext: callbackContext];
  223021. if ([s isOpen])
  223022. return s;
  223023. [s release];
  223024. return 0;
  223025. }
  223026. void juce_closeInternetFile (void* handle)
  223027. {
  223028. JuceURLConnection* const s = (JuceURLConnection*) handle;
  223029. if (s != 0)
  223030. {
  223031. const ScopedAutoReleasePool pool;
  223032. [s stop];
  223033. [s release];
  223034. }
  223035. }
  223036. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  223037. {
  223038. JuceURLConnection* const s = (JuceURLConnection*) handle;
  223039. if (s != 0)
  223040. {
  223041. const ScopedAutoReleasePool pool;
  223042. return [s read: (char*) buffer numBytes: bytesToRead];
  223043. }
  223044. return 0;
  223045. }
  223046. int64 juce_getInternetFileContentLength (void* handle)
  223047. {
  223048. JuceURLConnection* const s = (JuceURLConnection*) handle;
  223049. if (s != 0)
  223050. return s->contentLength;
  223051. return -1;
  223052. }
  223053. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers)
  223054. {
  223055. JuceURLConnection* const s = (JuceURLConnection*) handle;
  223056. if (s != 0 && s->headers != 0)
  223057. {
  223058. NSEnumerator* enumerator = [s->headers keyEnumerator];
  223059. NSString* key;
  223060. while ((key = [enumerator nextObject]) != nil)
  223061. headers.set (nsStringToJuce (key),
  223062. nsStringToJuce ((NSString*) [s->headers objectForKey: key]));
  223063. }
  223064. }
  223065. int juce_seekInInternetFile (void* handle, int /*newPosition*/)
  223066. {
  223067. JuceURLConnection* const s = (JuceURLConnection*) handle;
  223068. if (s != 0)
  223069. return [s readPosition];
  223070. return 0;
  223071. }
  223072. #endif
  223073. /*** End of inlined file: juce_mac_Network.mm ***/
  223074. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  223075. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223076. // compiled on its own).
  223077. #if JUCE_INCLUDED_FILE
  223078. struct NamedPipeInternal
  223079. {
  223080. String pipeInName, pipeOutName;
  223081. int pipeIn, pipeOut;
  223082. bool volatile createdPipe, blocked, stopReadOperation;
  223083. static void signalHandler (int) {}
  223084. };
  223085. void NamedPipe::cancelPendingReads()
  223086. {
  223087. while (internal != 0 && ((NamedPipeInternal*) internal)->blocked)
  223088. {
  223089. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  223090. intern->stopReadOperation = true;
  223091. char buffer [1] = { 0 };
  223092. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  223093. (void) bytesWritten;
  223094. int timeout = 2000;
  223095. while (intern->blocked && --timeout >= 0)
  223096. Thread::sleep (2);
  223097. intern->stopReadOperation = false;
  223098. }
  223099. }
  223100. void NamedPipe::close()
  223101. {
  223102. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  223103. if (intern != 0)
  223104. {
  223105. internal = 0;
  223106. if (intern->pipeIn != -1)
  223107. ::close (intern->pipeIn);
  223108. if (intern->pipeOut != -1)
  223109. ::close (intern->pipeOut);
  223110. if (intern->createdPipe)
  223111. {
  223112. unlink (intern->pipeInName.toUTF8());
  223113. unlink (intern->pipeOutName.toUTF8());
  223114. }
  223115. delete intern;
  223116. }
  223117. }
  223118. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  223119. {
  223120. close();
  223121. NamedPipeInternal* const intern = new NamedPipeInternal();
  223122. internal = intern;
  223123. intern->createdPipe = createPipe;
  223124. intern->blocked = false;
  223125. intern->stopReadOperation = false;
  223126. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  223127. siginterrupt (SIGPIPE, 1);
  223128. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  223129. intern->pipeInName = pipePath + "_in";
  223130. intern->pipeOutName = pipePath + "_out";
  223131. intern->pipeIn = -1;
  223132. intern->pipeOut = -1;
  223133. if (createPipe)
  223134. {
  223135. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  223136. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  223137. {
  223138. delete intern;
  223139. internal = 0;
  223140. return false;
  223141. }
  223142. }
  223143. return true;
  223144. }
  223145. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  223146. {
  223147. int bytesRead = -1;
  223148. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  223149. if (intern != 0)
  223150. {
  223151. intern->blocked = true;
  223152. if (intern->pipeIn == -1)
  223153. {
  223154. if (intern->createdPipe)
  223155. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  223156. else
  223157. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  223158. if (intern->pipeIn == -1)
  223159. {
  223160. intern->blocked = false;
  223161. return -1;
  223162. }
  223163. }
  223164. bytesRead = 0;
  223165. char* p = (char*) destBuffer;
  223166. while (bytesRead < maxBytesToRead)
  223167. {
  223168. const int bytesThisTime = maxBytesToRead - bytesRead;
  223169. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  223170. if (numRead <= 0 || intern->stopReadOperation)
  223171. {
  223172. bytesRead = -1;
  223173. break;
  223174. }
  223175. bytesRead += numRead;
  223176. p += bytesRead;
  223177. }
  223178. intern->blocked = false;
  223179. }
  223180. return bytesRead;
  223181. }
  223182. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  223183. {
  223184. int bytesWritten = -1;
  223185. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  223186. if (intern != 0)
  223187. {
  223188. if (intern->pipeOut == -1)
  223189. {
  223190. if (intern->createdPipe)
  223191. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  223192. else
  223193. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  223194. if (intern->pipeOut == -1)
  223195. {
  223196. return -1;
  223197. }
  223198. }
  223199. const char* p = (const char*) sourceBuffer;
  223200. bytesWritten = 0;
  223201. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  223202. while (bytesWritten < numBytesToWrite
  223203. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  223204. {
  223205. const int bytesThisTime = numBytesToWrite - bytesWritten;
  223206. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  223207. if (numWritten <= 0)
  223208. {
  223209. bytesWritten = -1;
  223210. break;
  223211. }
  223212. bytesWritten += numWritten;
  223213. p += bytesWritten;
  223214. }
  223215. }
  223216. return bytesWritten;
  223217. }
  223218. #endif
  223219. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  223220. /*** Start of inlined file: juce_mac_Threads.mm ***/
  223221. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223222. // compiled on its own).
  223223. #if JUCE_INCLUDED_FILE
  223224. /*
  223225. Note that a lot of methods that you'd expect to find in this file actually
  223226. live in juce_posix_SharedCode.h!
  223227. */
  223228. void JUCE_API juce_threadEntryPoint (void*);
  223229. void* threadEntryProc (void* userData)
  223230. {
  223231. const ScopedAutoReleasePool pool;
  223232. juce_threadEntryPoint (userData);
  223233. return 0;
  223234. }
  223235. void* juce_createThread (void* userData)
  223236. {
  223237. pthread_t handle = 0;
  223238. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  223239. {
  223240. pthread_detach (handle);
  223241. return (void*) handle;
  223242. }
  223243. return 0;
  223244. }
  223245. void juce_killThread (void* handle)
  223246. {
  223247. if (handle != 0)
  223248. pthread_cancel ((pthread_t) handle);
  223249. }
  223250. void juce_setCurrentThreadName (const String& /*name*/)
  223251. {
  223252. }
  223253. bool juce_setThreadPriority (void* handle, int priority)
  223254. {
  223255. if (handle == 0)
  223256. handle = (void*) pthread_self();
  223257. struct sched_param param;
  223258. int policy;
  223259. pthread_getschedparam ((pthread_t) handle, &policy, &param);
  223260. param.sched_priority = jlimit (1, 127, 1 + (priority * 126) / 11);
  223261. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  223262. }
  223263. Thread::ThreadID Thread::getCurrentThreadId()
  223264. {
  223265. return static_cast <ThreadID> (pthread_self());
  223266. }
  223267. void Thread::yield()
  223268. {
  223269. sched_yield();
  223270. }
  223271. void Thread::setCurrentThreadAffinityMask (const uint32 /*affinityMask*/)
  223272. {
  223273. // xxx
  223274. jassertfalse;
  223275. }
  223276. bool Process::isForegroundProcess()
  223277. {
  223278. #if JUCE_MAC
  223279. return [NSApp isActive];
  223280. #else
  223281. return true; // xxx change this if more than one app is ever possible on the iPhone!
  223282. #endif
  223283. }
  223284. void Process::raisePrivilege()
  223285. {
  223286. jassertfalse;
  223287. }
  223288. void Process::lowerPrivilege()
  223289. {
  223290. jassertfalse;
  223291. }
  223292. void Process::terminate()
  223293. {
  223294. exit (0);
  223295. }
  223296. void Process::setPriority (ProcessPriority)
  223297. {
  223298. // xxx
  223299. }
  223300. #endif
  223301. /*** End of inlined file: juce_mac_Threads.mm ***/
  223302. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  223303. /*
  223304. This file contains posix routines that are common to both the Linux and Mac builds.
  223305. It gets included directly in the cpp files for these platforms.
  223306. */
  223307. CriticalSection::CriticalSection() throw()
  223308. {
  223309. pthread_mutexattr_t atts;
  223310. pthread_mutexattr_init (&atts);
  223311. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  223312. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  223313. pthread_mutex_init (&internal, &atts);
  223314. }
  223315. CriticalSection::~CriticalSection() throw()
  223316. {
  223317. pthread_mutex_destroy (&internal);
  223318. }
  223319. void CriticalSection::enter() const throw()
  223320. {
  223321. pthread_mutex_lock (&internal);
  223322. }
  223323. bool CriticalSection::tryEnter() const throw()
  223324. {
  223325. return pthread_mutex_trylock (&internal) == 0;
  223326. }
  223327. void CriticalSection::exit() const throw()
  223328. {
  223329. pthread_mutex_unlock (&internal);
  223330. }
  223331. class WaitableEventImpl
  223332. {
  223333. public:
  223334. WaitableEventImpl (const bool manualReset_)
  223335. : triggered (false),
  223336. manualReset (manualReset_)
  223337. {
  223338. pthread_cond_init (&condition, 0);
  223339. pthread_mutexattr_t atts;
  223340. pthread_mutexattr_init (&atts);
  223341. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  223342. pthread_mutex_init (&mutex, &atts);
  223343. }
  223344. ~WaitableEventImpl()
  223345. {
  223346. pthread_cond_destroy (&condition);
  223347. pthread_mutex_destroy (&mutex);
  223348. }
  223349. bool wait (const int timeOutMillisecs) throw()
  223350. {
  223351. pthread_mutex_lock (&mutex);
  223352. if (! triggered)
  223353. {
  223354. if (timeOutMillisecs < 0)
  223355. {
  223356. do
  223357. {
  223358. pthread_cond_wait (&condition, &mutex);
  223359. }
  223360. while (! triggered);
  223361. }
  223362. else
  223363. {
  223364. struct timeval now;
  223365. gettimeofday (&now, 0);
  223366. struct timespec time;
  223367. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  223368. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  223369. if (time.tv_nsec >= 1000000000)
  223370. {
  223371. time.tv_nsec -= 1000000000;
  223372. time.tv_sec++;
  223373. }
  223374. do
  223375. {
  223376. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  223377. {
  223378. pthread_mutex_unlock (&mutex);
  223379. return false;
  223380. }
  223381. }
  223382. while (! triggered);
  223383. }
  223384. }
  223385. if (! manualReset)
  223386. triggered = false;
  223387. pthread_mutex_unlock (&mutex);
  223388. return true;
  223389. }
  223390. void signal() throw()
  223391. {
  223392. pthread_mutex_lock (&mutex);
  223393. triggered = true;
  223394. pthread_cond_broadcast (&condition);
  223395. pthread_mutex_unlock (&mutex);
  223396. }
  223397. void reset() throw()
  223398. {
  223399. pthread_mutex_lock (&mutex);
  223400. triggered = false;
  223401. pthread_mutex_unlock (&mutex);
  223402. }
  223403. private:
  223404. pthread_cond_t condition;
  223405. pthread_mutex_t mutex;
  223406. bool triggered;
  223407. const bool manualReset;
  223408. WaitableEventImpl (const WaitableEventImpl&);
  223409. WaitableEventImpl& operator= (const WaitableEventImpl&);
  223410. };
  223411. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  223412. : internal (new WaitableEventImpl (manualReset))
  223413. {
  223414. }
  223415. WaitableEvent::~WaitableEvent() throw()
  223416. {
  223417. delete static_cast <WaitableEventImpl*> (internal);
  223418. }
  223419. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  223420. {
  223421. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  223422. }
  223423. void WaitableEvent::signal() const throw()
  223424. {
  223425. static_cast <WaitableEventImpl*> (internal)->signal();
  223426. }
  223427. void WaitableEvent::reset() const throw()
  223428. {
  223429. static_cast <WaitableEventImpl*> (internal)->reset();
  223430. }
  223431. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  223432. {
  223433. struct timespec time;
  223434. time.tv_sec = millisecs / 1000;
  223435. time.tv_nsec = (millisecs % 1000) * 1000000;
  223436. nanosleep (&time, 0);
  223437. }
  223438. const juce_wchar File::separator = '/';
  223439. const String File::separatorString ("/");
  223440. const File File::getCurrentWorkingDirectory()
  223441. {
  223442. HeapBlock<char> heapBuffer;
  223443. char localBuffer [1024];
  223444. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  223445. int bufferSize = 4096;
  223446. while (cwd == 0 && errno == ERANGE)
  223447. {
  223448. heapBuffer.malloc (bufferSize);
  223449. cwd = getcwd (heapBuffer, bufferSize - 1);
  223450. bufferSize += 1024;
  223451. }
  223452. return File (String::fromUTF8 (cwd));
  223453. }
  223454. bool File::setAsCurrentWorkingDirectory() const
  223455. {
  223456. return chdir (getFullPathName().toUTF8()) == 0;
  223457. }
  223458. static bool juce_stat (const String& fileName, struct stat& info)
  223459. {
  223460. return fileName.isNotEmpty()
  223461. && (stat (fileName.toUTF8(), &info) == 0);
  223462. }
  223463. bool File::isDirectory() const
  223464. {
  223465. struct stat info;
  223466. return fullPath.isEmpty()
  223467. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  223468. }
  223469. bool File::exists() const
  223470. {
  223471. return fullPath.isNotEmpty()
  223472. && access (fullPath.toUTF8(), F_OK) == 0;
  223473. }
  223474. bool File::existsAsFile() const
  223475. {
  223476. return exists() && ! isDirectory();
  223477. }
  223478. int64 File::getSize() const
  223479. {
  223480. struct stat info;
  223481. return juce_stat (fullPath, info) ? info.st_size : 0;
  223482. }
  223483. bool File::hasWriteAccess() const
  223484. {
  223485. if (exists())
  223486. return access (fullPath.toUTF8(), W_OK) == 0;
  223487. if ((! isDirectory()) && fullPath.containsChar (separator))
  223488. return getParentDirectory().hasWriteAccess();
  223489. return false;
  223490. }
  223491. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  223492. {
  223493. struct stat info;
  223494. const int res = stat (fullPath.toUTF8(), &info);
  223495. if (res != 0)
  223496. return false;
  223497. info.st_mode &= 0777; // Just permissions
  223498. if (shouldBeReadOnly)
  223499. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  223500. else
  223501. // Give everybody write permission?
  223502. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  223503. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  223504. }
  223505. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  223506. {
  223507. modificationTime = 0;
  223508. accessTime = 0;
  223509. creationTime = 0;
  223510. struct stat info;
  223511. const int res = stat (fullPath.toUTF8(), &info);
  223512. if (res == 0)
  223513. {
  223514. modificationTime = (int64) info.st_mtime * 1000;
  223515. accessTime = (int64) info.st_atime * 1000;
  223516. creationTime = (int64) info.st_ctime * 1000;
  223517. }
  223518. }
  223519. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  223520. {
  223521. struct utimbuf times;
  223522. times.actime = (time_t) (accessTime / 1000);
  223523. times.modtime = (time_t) (modificationTime / 1000);
  223524. return utime (fullPath.toUTF8(), &times) == 0;
  223525. }
  223526. bool File::deleteFile() const
  223527. {
  223528. if (! exists())
  223529. return true;
  223530. else if (isDirectory())
  223531. return rmdir (fullPath.toUTF8()) == 0;
  223532. else
  223533. return remove (fullPath.toUTF8()) == 0;
  223534. }
  223535. bool File::moveInternal (const File& dest) const
  223536. {
  223537. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  223538. return true;
  223539. if (hasWriteAccess() && copyInternal (dest))
  223540. {
  223541. if (deleteFile())
  223542. return true;
  223543. dest.deleteFile();
  223544. }
  223545. return false;
  223546. }
  223547. void File::createDirectoryInternal (const String& fileName) const
  223548. {
  223549. mkdir (fileName.toUTF8(), 0777);
  223550. }
  223551. void* juce_fileOpen (const File& file, bool forWriting)
  223552. {
  223553. int flags = O_RDONLY;
  223554. if (forWriting)
  223555. {
  223556. if (file.exists())
  223557. {
  223558. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  223559. if (f != -1)
  223560. lseek (f, 0, SEEK_END);
  223561. return (void*) f;
  223562. }
  223563. else
  223564. {
  223565. flags = O_RDWR + O_CREAT;
  223566. }
  223567. }
  223568. return (void*) open (file.getFullPathName().toUTF8(), flags, 00644);
  223569. }
  223570. void juce_fileClose (void* handle)
  223571. {
  223572. if (handle != 0)
  223573. close ((int) (pointer_sized_int) handle);
  223574. }
  223575. int juce_fileRead (void* handle, void* buffer, int size)
  223576. {
  223577. if (handle != 0)
  223578. return jmax (0, (int) read ((int) (pointer_sized_int) handle, buffer, size));
  223579. return 0;
  223580. }
  223581. int juce_fileWrite (void* handle, const void* buffer, int size)
  223582. {
  223583. if (handle != 0)
  223584. return (int) write ((int) (pointer_sized_int) handle, buffer, size);
  223585. return 0;
  223586. }
  223587. int64 juce_fileSetPosition (void* handle, int64 pos)
  223588. {
  223589. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  223590. return pos;
  223591. return -1;
  223592. }
  223593. int64 FileOutputStream::getPositionInternal() const
  223594. {
  223595. if (fileHandle != 0)
  223596. return lseek ((int) (pointer_sized_int) fileHandle, 0, SEEK_CUR);
  223597. return -1;
  223598. }
  223599. void FileOutputStream::flushInternal()
  223600. {
  223601. if (fileHandle != 0)
  223602. fsync ((int) (pointer_sized_int) fileHandle);
  223603. }
  223604. const File juce_getExecutableFile()
  223605. {
  223606. Dl_info exeInfo;
  223607. dladdr ((const void*) juce_getExecutableFile, &exeInfo);
  223608. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  223609. }
  223610. // if this file doesn't exist, find a parent of it that does..
  223611. static bool juce_doStatFS (File f, struct statfs& result)
  223612. {
  223613. for (int i = 5; --i >= 0;)
  223614. {
  223615. if (f.exists())
  223616. break;
  223617. f = f.getParentDirectory();
  223618. }
  223619. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  223620. }
  223621. int64 File::getBytesFreeOnVolume() const
  223622. {
  223623. struct statfs buf;
  223624. if (juce_doStatFS (*this, buf))
  223625. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  223626. return 0;
  223627. }
  223628. int64 File::getVolumeTotalSize() const
  223629. {
  223630. struct statfs buf;
  223631. if (juce_doStatFS (*this, buf))
  223632. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  223633. return 0;
  223634. }
  223635. const String File::getVolumeLabel() const
  223636. {
  223637. #if JUCE_MAC
  223638. struct VolAttrBuf
  223639. {
  223640. u_int32_t length;
  223641. attrreference_t mountPointRef;
  223642. char mountPointSpace [MAXPATHLEN];
  223643. } attrBuf;
  223644. struct attrlist attrList;
  223645. zerostruct (attrList);
  223646. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  223647. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  223648. File f (*this);
  223649. for (;;)
  223650. {
  223651. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  223652. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  223653. (int) attrBuf.mountPointRef.attr_length);
  223654. const File parent (f.getParentDirectory());
  223655. if (f == parent)
  223656. break;
  223657. f = parent;
  223658. }
  223659. #endif
  223660. return String::empty;
  223661. }
  223662. int File::getVolumeSerialNumber() const
  223663. {
  223664. return 0; // xxx
  223665. }
  223666. void juce_runSystemCommand (const String& command)
  223667. {
  223668. int result = system (command.toUTF8());
  223669. (void) result;
  223670. }
  223671. const String juce_getOutputFromCommand (const String& command)
  223672. {
  223673. // slight bodge here, as we just pipe the output into a temp file and read it...
  223674. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  223675. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  223676. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  223677. String result (tempFile.loadFileAsString());
  223678. tempFile.deleteFile();
  223679. return result;
  223680. }
  223681. class InterProcessLock::Pimpl
  223682. {
  223683. public:
  223684. Pimpl (const String& name, const int timeOutMillisecs)
  223685. : handle (0), refCount (1)
  223686. {
  223687. #if JUCE_MAC
  223688. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  223689. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  223690. #else
  223691. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  223692. #endif
  223693. temp.create();
  223694. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  223695. if (handle != 0)
  223696. {
  223697. struct flock fl;
  223698. zerostruct (fl);
  223699. fl.l_whence = SEEK_SET;
  223700. fl.l_type = F_WRLCK;
  223701. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  223702. for (;;)
  223703. {
  223704. const int result = fcntl (handle, F_SETLK, &fl);
  223705. if (result >= 0)
  223706. return;
  223707. if (errno != EINTR)
  223708. {
  223709. if (timeOutMillisecs == 0
  223710. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  223711. break;
  223712. Thread::sleep (10);
  223713. }
  223714. }
  223715. }
  223716. closeFile();
  223717. }
  223718. ~Pimpl()
  223719. {
  223720. closeFile();
  223721. }
  223722. void closeFile()
  223723. {
  223724. if (handle != 0)
  223725. {
  223726. struct flock fl;
  223727. zerostruct (fl);
  223728. fl.l_whence = SEEK_SET;
  223729. fl.l_type = F_UNLCK;
  223730. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  223731. {}
  223732. close (handle);
  223733. handle = 0;
  223734. }
  223735. }
  223736. int handle, refCount;
  223737. };
  223738. InterProcessLock::InterProcessLock (const String& name_)
  223739. : name (name_)
  223740. {
  223741. }
  223742. InterProcessLock::~InterProcessLock()
  223743. {
  223744. }
  223745. bool InterProcessLock::enter (const int timeOutMillisecs)
  223746. {
  223747. const ScopedLock sl (lock);
  223748. if (pimpl == 0)
  223749. {
  223750. pimpl = new Pimpl (name, timeOutMillisecs);
  223751. if (pimpl->handle == 0)
  223752. pimpl = 0;
  223753. }
  223754. else
  223755. {
  223756. pimpl->refCount++;
  223757. }
  223758. return pimpl != 0;
  223759. }
  223760. void InterProcessLock::exit()
  223761. {
  223762. const ScopedLock sl (lock);
  223763. // Trying to release the lock too many times!
  223764. jassert (pimpl != 0);
  223765. if (pimpl != 0 && --(pimpl->refCount) == 0)
  223766. pimpl = 0;
  223767. }
  223768. /*** End of inlined file: juce_posix_SharedCode.h ***/
  223769. /*** Start of inlined file: juce_mac_Files.mm ***/
  223770. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223771. // compiled on its own).
  223772. #if JUCE_INCLUDED_FILE
  223773. /*
  223774. Note that a lot of methods that you'd expect to find in this file actually
  223775. live in juce_posix_SharedCode.h!
  223776. */
  223777. bool File::copyInternal (const File& dest) const
  223778. {
  223779. const ScopedAutoReleasePool pool;
  223780. NSFileManager* fm = [NSFileManager defaultManager];
  223781. return [fm fileExistsAtPath: juceStringToNS (fullPath)]
  223782. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  223783. && [fm copyItemAtPath: juceStringToNS (fullPath)
  223784. toPath: juceStringToNS (dest.getFullPathName())
  223785. error: nil];
  223786. #else
  223787. && [fm copyPath: juceStringToNS (fullPath)
  223788. toPath: juceStringToNS (dest.getFullPathName())
  223789. handler: nil];
  223790. #endif
  223791. }
  223792. void File::findFileSystemRoots (Array<File>& destArray)
  223793. {
  223794. destArray.add (File ("/"));
  223795. }
  223796. static bool isFileOnDriveType (const File& f, const char* const* types)
  223797. {
  223798. struct statfs buf;
  223799. if (juce_doStatFS (f, buf))
  223800. {
  223801. const String type (buf.f_fstypename);
  223802. while (*types != 0)
  223803. if (type.equalsIgnoreCase (*types++))
  223804. return true;
  223805. }
  223806. return false;
  223807. }
  223808. bool File::isOnCDRomDrive() const
  223809. {
  223810. const char* const cdTypes[] = { "cd9660", "cdfs", "cddafs", "udf", 0 };
  223811. return isFileOnDriveType (*this, cdTypes);
  223812. }
  223813. bool File::isOnHardDisk() const
  223814. {
  223815. const char* const nonHDTypes[] = { "nfs", "smbfs", "ramfs", 0 };
  223816. return ! (isOnCDRomDrive() || isFileOnDriveType (*this, nonHDTypes));
  223817. }
  223818. bool File::isOnRemovableDrive() const
  223819. {
  223820. #if JUCE_IPHONE
  223821. return false; // xxx is this possible?
  223822. #else
  223823. const ScopedAutoReleasePool pool;
  223824. BOOL removable = false;
  223825. [[NSWorkspace sharedWorkspace]
  223826. getFileSystemInfoForPath: juceStringToNS (getFullPathName())
  223827. isRemovable: &removable
  223828. isWritable: nil
  223829. isUnmountable: nil
  223830. description: nil
  223831. type: nil];
  223832. return removable;
  223833. #endif
  223834. }
  223835. static bool juce_isHiddenFile (const String& path)
  223836. {
  223837. #if JUCE_IPHONE
  223838. return File (path).getFileName().startsWithChar ('.');
  223839. #else
  223840. FSRef ref;
  223841. if (! PlatformUtilities::makeFSRefFromPath (&ref, path))
  223842. return false;
  223843. FSCatalogInfo info;
  223844. FSGetCatalogInfo (&ref, kFSCatInfoNodeFlags | kFSCatInfoFinderInfo, &info, 0, 0, 0);
  223845. if ((info.nodeFlags & kFSNodeIsDirectoryBit) != 0)
  223846. return (((FolderInfo*) &info.finderInfo)->finderFlags & kIsInvisible) != 0;
  223847. return (((FileInfo*) &info.finderInfo)->finderFlags & kIsInvisible) != 0;
  223848. #endif
  223849. }
  223850. bool File::isHidden() const
  223851. {
  223852. return juce_isHiddenFile (getFullPathName());
  223853. }
  223854. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  223855. const File File::getSpecialLocation (const SpecialLocationType type)
  223856. {
  223857. const ScopedAutoReleasePool pool;
  223858. String resultPath;
  223859. switch (type)
  223860. {
  223861. case userHomeDirectory:
  223862. resultPath = nsStringToJuce (NSHomeDirectory());
  223863. break;
  223864. case userDocumentsDirectory:
  223865. resultPath = "~/Documents";
  223866. break;
  223867. case userDesktopDirectory:
  223868. resultPath = "~/Desktop";
  223869. break;
  223870. case userApplicationDataDirectory:
  223871. resultPath = "~/Library";
  223872. break;
  223873. case commonApplicationDataDirectory:
  223874. resultPath = "/Library";
  223875. break;
  223876. case globalApplicationsDirectory:
  223877. resultPath = "/Applications";
  223878. break;
  223879. case userMusicDirectory:
  223880. resultPath = "~/Music";
  223881. break;
  223882. case userMoviesDirectory:
  223883. resultPath = "~/Movies";
  223884. break;
  223885. case tempDirectory:
  223886. {
  223887. File tmp ("~/Library/Caches/" + juce_getExecutableFile().getFileNameWithoutExtension());
  223888. tmp.createDirectory();
  223889. return tmp.getFullPathName();
  223890. }
  223891. case invokedExecutableFile:
  223892. if (juce_Argv0 != 0)
  223893. return File (String::fromUTF8 (juce_Argv0));
  223894. // deliberate fall-through...
  223895. case currentExecutableFile:
  223896. return juce_getExecutableFile();
  223897. case currentApplicationFile:
  223898. {
  223899. const File exe (juce_getExecutableFile());
  223900. const File parent (exe.getParentDirectory());
  223901. return parent.getFullPathName().endsWithIgnoreCase ("Contents/MacOS")
  223902. ? parent.getParentDirectory().getParentDirectory()
  223903. : exe;
  223904. }
  223905. default:
  223906. jassertfalse; // unknown type?
  223907. break;
  223908. }
  223909. if (resultPath.isNotEmpty())
  223910. return File (PlatformUtilities::convertToPrecomposedUnicode (resultPath));
  223911. return File::nonexistent;
  223912. }
  223913. const String File::getVersion() const
  223914. {
  223915. const ScopedAutoReleasePool pool;
  223916. String result;
  223917. NSBundle* bundle = [NSBundle bundleWithPath: juceStringToNS (getFullPathName())];
  223918. if (bundle != 0)
  223919. {
  223920. NSDictionary* info = [bundle infoDictionary];
  223921. if (info != 0)
  223922. {
  223923. NSString* name = [info valueForKey: @"CFBundleShortVersionString"];
  223924. if (name != nil)
  223925. result = nsStringToJuce (name);
  223926. }
  223927. }
  223928. return result;
  223929. }
  223930. const File File::getLinkedTarget() const
  223931. {
  223932. #if JUCE_IPHONE || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
  223933. NSString* dest = [[NSFileManager defaultManager] destinationOfSymbolicLinkAtPath: juceStringToNS (getFullPathName()) error: nil];
  223934. #else
  223935. NSString* dest = [[NSFileManager defaultManager] pathContentOfSymbolicLinkAtPath: juceStringToNS (getFullPathName())];
  223936. #endif
  223937. if (dest != nil)
  223938. return File (nsStringToJuce (dest));
  223939. return *this;
  223940. }
  223941. bool File::moveToTrash() const
  223942. {
  223943. if (! exists())
  223944. return true;
  223945. #if JUCE_IPHONE
  223946. return deleteFile(); //xxx is there a trashcan on the iPhone?
  223947. #else
  223948. const ScopedAutoReleasePool pool;
  223949. NSString* p = juceStringToNS (getFullPathName());
  223950. return [[NSWorkspace sharedWorkspace]
  223951. performFileOperation: NSWorkspaceRecycleOperation
  223952. source: [p stringByDeletingLastPathComponent]
  223953. destination: @""
  223954. files: [NSArray arrayWithObject: [p lastPathComponent]]
  223955. tag: nil ];
  223956. #endif
  223957. }
  223958. class DirectoryIterator::NativeIterator::Pimpl
  223959. {
  223960. public:
  223961. Pimpl (const File& directory, const String& wildCard_)
  223962. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  223963. wildCard (wildCard_),
  223964. enumerator (0)
  223965. {
  223966. ScopedAutoReleasePool pool;
  223967. enumerator = [[[NSFileManager defaultManager] enumeratorAtPath: juceStringToNS (directory.getFullPathName())] retain];
  223968. wildcardUTF8 = wildCard.toUTF8();
  223969. }
  223970. ~Pimpl()
  223971. {
  223972. [enumerator release];
  223973. }
  223974. bool next (String& filenameFound,
  223975. bool* const isDir, bool* const isHidden, int64* const fileSize,
  223976. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  223977. {
  223978. ScopedAutoReleasePool pool;
  223979. for (;;)
  223980. {
  223981. NSString* file;
  223982. if (enumerator == 0 || (file = [enumerator nextObject]) == 0)
  223983. return false;
  223984. [enumerator skipDescendents];
  223985. filenameFound = nsStringToJuce (file);
  223986. if (fnmatch (wildcardUTF8, filenameFound.toUTF8(), FNM_CASEFOLD) != 0)
  223987. continue;
  223988. const String path (parentDir + filenameFound);
  223989. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  223990. {
  223991. struct stat info;
  223992. const bool statOk = juce_stat (path, info);
  223993. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  223994. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  223995. if (modTime != 0) *modTime = statOk ? (int64) info.st_mtime * 1000 : 0;
  223996. if (creationTime != 0) *creationTime = statOk ? (int64) info.st_ctime * 1000 : 0;
  223997. }
  223998. if (isHidden != 0)
  223999. *isHidden = juce_isHiddenFile (path);
  224000. if (isReadOnly != 0)
  224001. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  224002. return true;
  224003. }
  224004. }
  224005. private:
  224006. String parentDir, wildCard;
  224007. const char* wildcardUTF8;
  224008. NSDirectoryEnumerator* enumerator;
  224009. Pimpl (const Pimpl&);
  224010. Pimpl& operator= (const Pimpl&);
  224011. };
  224012. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  224013. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  224014. {
  224015. }
  224016. DirectoryIterator::NativeIterator::~NativeIterator()
  224017. {
  224018. }
  224019. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  224020. bool* const isDir, bool* const isHidden, int64* const fileSize,
  224021. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  224022. {
  224023. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  224024. }
  224025. bool juce_launchExecutable (const String& pathAndArguments)
  224026. {
  224027. const char* const argv[4] = { "/bin/sh", "-c", pathAndArguments.toUTF8(), 0 };
  224028. const int cpid = fork();
  224029. if (cpid == 0)
  224030. {
  224031. // Child process
  224032. if (execve (argv[0], (char**) argv, 0) < 0)
  224033. exit (0);
  224034. }
  224035. else
  224036. {
  224037. if (cpid < 0)
  224038. return false;
  224039. }
  224040. return true;
  224041. }
  224042. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  224043. {
  224044. #if JUCE_IPHONE
  224045. return [[UIApplication sharedApplication] openURL: [NSURL fileURLWithPath: juceStringToNS (fileName)]];
  224046. #else
  224047. const ScopedAutoReleasePool pool;
  224048. if (parameters.isEmpty())
  224049. {
  224050. return [[NSWorkspace sharedWorkspace] openFile: juceStringToNS (fileName)]
  224051. || [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: juceStringToNS (fileName)]];
  224052. }
  224053. bool ok = false;
  224054. FSRef ref;
  224055. if (PlatformUtilities::makeFSRefFromPath (&ref, fileName))
  224056. {
  224057. if (PlatformUtilities::isBundle (fileName))
  224058. {
  224059. NSMutableArray* urls = [NSMutableArray array];
  224060. StringArray docs;
  224061. docs.addTokens (parameters, true);
  224062. for (int i = 0; i < docs.size(); ++i)
  224063. [urls addObject: juceStringToNS (docs[i])];
  224064. ok = [[NSWorkspace sharedWorkspace] openURLs: urls
  224065. withAppBundleIdentifier: [[NSBundle bundleWithPath: juceStringToNS (fileName)] bundleIdentifier]
  224066. options: 0
  224067. additionalEventParamDescriptor: nil
  224068. launchIdentifiers: nil];
  224069. }
  224070. else
  224071. {
  224072. ok = juce_launchExecutable ("\"" + fileName + "\" " + parameters);
  224073. }
  224074. }
  224075. return ok;
  224076. #endif
  224077. }
  224078. void File::revealToUser() const
  224079. {
  224080. #if ! JUCE_IPHONE
  224081. if (exists())
  224082. [[NSWorkspace sharedWorkspace] selectFile: juceStringToNS (getFullPathName()) inFileViewerRootedAtPath: @""];
  224083. else if (getParentDirectory().exists())
  224084. getParentDirectory().revealToUser();
  224085. #endif
  224086. }
  224087. #if ! JUCE_IPHONE
  224088. bool PlatformUtilities::makeFSRefFromPath (FSRef* destFSRef, const String& path)
  224089. {
  224090. return FSPathMakeRef ((const UInt8*) path.toUTF8(), destFSRef, 0) == noErr;
  224091. }
  224092. const String PlatformUtilities::makePathFromFSRef (FSRef* file)
  224093. {
  224094. char path [2048];
  224095. zerostruct (path);
  224096. if (FSRefMakePath (file, (UInt8*) path, sizeof (path) - 1) == noErr)
  224097. return PlatformUtilities::convertToPrecomposedUnicode (String::fromUTF8 (path));
  224098. return String::empty;
  224099. }
  224100. #endif
  224101. OSType PlatformUtilities::getTypeOfFile (const String& filename)
  224102. {
  224103. const ScopedAutoReleasePool pool;
  224104. #if JUCE_IPHONE || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
  224105. NSDictionary* fileDict = [[NSFileManager defaultManager] attributesOfItemAtPath: juceStringToNS (filename) error: nil];
  224106. #else
  224107. NSDictionary* fileDict = [[NSFileManager defaultManager] fileAttributesAtPath: juceStringToNS (filename) traverseLink: NO];
  224108. #endif
  224109. //return (OSType) [fileDict objectForKey: NSFileHFSTypeCode];
  224110. return [fileDict fileHFSTypeCode];
  224111. }
  224112. bool PlatformUtilities::isBundle (const String& filename)
  224113. {
  224114. #if JUCE_IPHONE
  224115. return false; // xxx can't find a sensible way to do this without trying to open the bundle..
  224116. #else
  224117. const ScopedAutoReleasePool pool;
  224118. return [[NSWorkspace sharedWorkspace] isFilePackageAtPath: juceStringToNS (filename)];
  224119. #endif
  224120. }
  224121. #endif
  224122. /*** End of inlined file: juce_mac_Files.mm ***/
  224123. #if JUCE_IPHONE
  224124. /*** Start of inlined file: juce_iphone_MiscUtilities.mm ***/
  224125. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224126. // compiled on its own).
  224127. #if JUCE_INCLUDED_FILE
  224128. static JUCEApplication* juce_intialisingApp;
  224129. END_JUCE_NAMESPACE
  224130. @interface JuceAppStartupDelegate : NSObject <UIApplicationDelegate>
  224131. {
  224132. }
  224133. - (void) applicationDidFinishLaunching: (UIApplication*) application;
  224134. - (void) applicationWillResignActive: (UIApplication*) application;
  224135. @end
  224136. @implementation JuceAppStartupDelegate
  224137. - (void) applicationDidFinishLaunching: (UIApplication*) application
  224138. {
  224139. String dummy;
  224140. if (! juce_intialisingApp->initialiseApp (dummy))
  224141. exit (0);
  224142. }
  224143. - (void) applicationWillResignActive: (UIApplication*) application
  224144. {
  224145. JUCEApplication::shutdownAppAndClearUp();
  224146. }
  224147. @end
  224148. BEGIN_JUCE_NAMESPACE
  224149. int juce_IPhoneMain (int argc, const char* argv[], JUCEApplication* app)
  224150. {
  224151. juce_intialisingApp = app;
  224152. return UIApplicationMain (argc, const_cast<char**> (argv), nil, @"JuceAppStartupDelegate");
  224153. }
  224154. ScopedAutoReleasePool::ScopedAutoReleasePool()
  224155. {
  224156. pool = [[NSAutoreleasePool alloc] init];
  224157. }
  224158. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  224159. {
  224160. [((NSAutoreleasePool*) pool) release];
  224161. }
  224162. void PlatformUtilities::beep()
  224163. {
  224164. //xxx
  224165. //AudioServicesPlaySystemSound ();
  224166. }
  224167. void PlatformUtilities::addItemToDock (const File& file)
  224168. {
  224169. }
  224170. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  224171. END_JUCE_NAMESPACE
  224172. @interface JuceAlertBoxDelegate : NSObject
  224173. {
  224174. @public
  224175. bool clickedOk;
  224176. }
  224177. - (void) alertView: (UIAlertView*) alertView clickedButtonAtIndex: (NSInteger) buttonIndex;
  224178. @end
  224179. @implementation JuceAlertBoxDelegate
  224180. - (void) alertView: (UIAlertView*) alertView clickedButtonAtIndex: (NSInteger) buttonIndex
  224181. {
  224182. clickedOk = (buttonIndex == 0);
  224183. alertView.hidden = true;
  224184. }
  224185. @end
  224186. BEGIN_JUCE_NAMESPACE
  224187. // (This function is used directly by other bits of code)
  224188. bool juce_iPhoneShowModalAlert (const String& title,
  224189. const String& bodyText,
  224190. NSString* okButtonText,
  224191. NSString* cancelButtonText)
  224192. {
  224193. const ScopedAutoReleasePool pool;
  224194. JuceAlertBoxDelegate* callback = [[JuceAlertBoxDelegate alloc] init];
  224195. UIAlertView* alert = [[UIAlertView alloc] initWithTitle: juceStringToNS (title)
  224196. message: juceStringToNS (bodyText)
  224197. delegate: callback
  224198. cancelButtonTitle: okButtonText
  224199. otherButtonTitles: cancelButtonText, nil];
  224200. [alert retain];
  224201. [alert show];
  224202. while (! alert.hidden && alert.superview != nil)
  224203. [[NSRunLoop mainRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  224204. const bool result = callback->clickedOk;
  224205. [alert release];
  224206. [callback release];
  224207. return result;
  224208. }
  224209. bool AlertWindow::showNativeDialogBox (const String& title,
  224210. const String& bodyText,
  224211. bool isOkCancel)
  224212. {
  224213. return juce_iPhoneShowModalAlert (title, bodyText,
  224214. @"OK",
  224215. isOkCancel ? @"Cancel" : nil);
  224216. }
  224217. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  224218. {
  224219. jassertfalse; // no such thing on the iphone!
  224220. return false;
  224221. }
  224222. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  224223. {
  224224. jassertfalse; // no such thing on the iphone!
  224225. return false;
  224226. }
  224227. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  224228. {
  224229. [[UIApplication sharedApplication] setIdleTimerDisabled: ! isEnabled];
  224230. }
  224231. bool Desktop::isScreenSaverEnabled()
  224232. {
  224233. return ! [[UIApplication sharedApplication] isIdleTimerDisabled];
  224234. }
  224235. void juce_updateMultiMonitorInfo (Array <Rectangle <int> >& monitorCoords, const bool clipToWorkArea)
  224236. {
  224237. const ScopedAutoReleasePool pool;
  224238. monitorCoords.clear();
  224239. CGRect r = clipToWorkArea ? [[UIScreen mainScreen] applicationFrame]
  224240. : [[UIScreen mainScreen] bounds];
  224241. monitorCoords.add (Rectangle<int> ((int) r.origin.x,
  224242. (int) r.origin.y,
  224243. (int) r.size.width,
  224244. (int) r.size.height));
  224245. }
  224246. #endif
  224247. #endif
  224248. /*** End of inlined file: juce_iphone_MiscUtilities.mm ***/
  224249. #else
  224250. /*** Start of inlined file: juce_mac_MiscUtilities.mm ***/
  224251. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224252. // compiled on its own).
  224253. #if JUCE_INCLUDED_FILE
  224254. ScopedAutoReleasePool::ScopedAutoReleasePool()
  224255. {
  224256. pool = [[NSAutoreleasePool alloc] init];
  224257. }
  224258. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  224259. {
  224260. [((NSAutoreleasePool*) pool) release];
  224261. }
  224262. void PlatformUtilities::beep()
  224263. {
  224264. NSBeep();
  224265. }
  224266. void PlatformUtilities::addItemToDock (const File& file)
  224267. {
  224268. // check that it's not already there...
  224269. if (! juce_getOutputFromCommand ("defaults read com.apple.dock persistent-apps")
  224270. .containsIgnoreCase (file.getFullPathName()))
  224271. {
  224272. 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>"
  224273. + file.getFullPathName() + "</string><key>_CFURLStringType</key><integer>0</integer></dict></dict></dict>\"");
  224274. juce_runSystemCommand ("osascript -e \"tell application \\\"Dock\\\" to quit\"");
  224275. }
  224276. }
  224277. int PlatformUtilities::getOSXMinorVersionNumber()
  224278. {
  224279. SInt32 versionMinor = 0;
  224280. OSErr err = Gestalt (gestaltSystemVersionMinor, &versionMinor);
  224281. (void) err;
  224282. jassert (err == noErr);
  224283. return (int) versionMinor;
  224284. }
  224285. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  224286. bool AlertWindow::showNativeDialogBox (const String& title,
  224287. const String& bodyText,
  224288. bool isOkCancel)
  224289. {
  224290. const ScopedAutoReleasePool pool;
  224291. return NSRunAlertPanel (juceStringToNS (title),
  224292. juceStringToNS (bodyText),
  224293. @"Ok",
  224294. isOkCancel ? @"Cancel" : nil,
  224295. nil) == NSAlertDefaultReturn;
  224296. }
  224297. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool /*canMoveFiles*/)
  224298. {
  224299. if (files.size() == 0)
  224300. return false;
  224301. MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource(0);
  224302. if (draggingSource == 0)
  224303. {
  224304. jassertfalse; // This method must be called in response to a component's mouseDown or mouseDrag event!
  224305. return false;
  224306. }
  224307. Component* sourceComp = draggingSource->getComponentUnderMouse();
  224308. if (sourceComp == 0)
  224309. {
  224310. jassertfalse; // This method must be called in response to a component's mouseDown or mouseDrag event!
  224311. return false;
  224312. }
  224313. const ScopedAutoReleasePool pool;
  224314. NSView* view = (NSView*) sourceComp->getWindowHandle();
  224315. if (view == 0)
  224316. return false;
  224317. NSPasteboard* pboard = [NSPasteboard pasteboardWithName: NSDragPboard];
  224318. [pboard declareTypes: [NSArray arrayWithObject: NSFilenamesPboardType]
  224319. owner: nil];
  224320. NSMutableArray* filesArray = [NSMutableArray arrayWithCapacity: 4];
  224321. for (int i = 0; i < files.size(); ++i)
  224322. [filesArray addObject: juceStringToNS (files[i])];
  224323. [pboard setPropertyList: filesArray
  224324. forType: NSFilenamesPboardType];
  224325. NSPoint dragPosition = [view convertPoint: [[[view window] currentEvent] locationInWindow]
  224326. fromView: nil];
  224327. dragPosition.x -= 16;
  224328. dragPosition.y -= 16;
  224329. [view dragImage: [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (files[0])]
  224330. at: dragPosition
  224331. offset: NSMakeSize (0, 0)
  224332. event: [[view window] currentEvent]
  224333. pasteboard: pboard
  224334. source: view
  224335. slideBack: YES];
  224336. return true;
  224337. }
  224338. bool DragAndDropContainer::performExternalDragDropOfText (const String& /*text*/)
  224339. {
  224340. jassertfalse; // not implemented!
  224341. return false;
  224342. }
  224343. bool Desktop::canUseSemiTransparentWindows() throw()
  224344. {
  224345. return true;
  224346. }
  224347. const Point<int> Desktop::getMousePosition()
  224348. {
  224349. const ScopedAutoReleasePool pool;
  224350. const NSPoint p ([NSEvent mouseLocation]);
  224351. return Point<int> (roundToInt (p.x), roundToInt ([[[NSScreen screens] objectAtIndex: 0] frame].size.height - p.y));
  224352. }
  224353. void Desktop::setMousePosition (const Point<int>& newPosition)
  224354. {
  224355. // this rubbish needs to be done around the warp call, to avoid causing a
  224356. // bizarre glitch..
  224357. CGAssociateMouseAndMouseCursorPosition (false);
  224358. CGWarpMouseCursorPosition (CGPointMake (newPosition.getX(), newPosition.getY()));
  224359. CGAssociateMouseAndMouseCursorPosition (true);
  224360. }
  224361. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  224362. class ScreenSaverDefeater : public Timer,
  224363. public DeletedAtShutdown
  224364. {
  224365. public:
  224366. ScreenSaverDefeater()
  224367. {
  224368. startTimer (10000);
  224369. timerCallback();
  224370. }
  224371. ~ScreenSaverDefeater() {}
  224372. void timerCallback()
  224373. {
  224374. if (Process::isForegroundProcess())
  224375. UpdateSystemActivity (UsrActivity);
  224376. }
  224377. };
  224378. static ScreenSaverDefeater* screenSaverDefeater = 0;
  224379. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  224380. {
  224381. if (isEnabled)
  224382. deleteAndZero (screenSaverDefeater);
  224383. else if (screenSaverDefeater == 0)
  224384. screenSaverDefeater = new ScreenSaverDefeater();
  224385. }
  224386. bool Desktop::isScreenSaverEnabled()
  224387. {
  224388. return screenSaverDefeater == 0;
  224389. }
  224390. #else
  224391. static IOPMAssertionID screenSaverDisablerID = 0;
  224392. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  224393. {
  224394. if (isEnabled)
  224395. {
  224396. if (screenSaverDisablerID != 0)
  224397. {
  224398. IOPMAssertionRelease (screenSaverDisablerID);
  224399. screenSaverDisablerID = 0;
  224400. }
  224401. }
  224402. else
  224403. {
  224404. if (screenSaverDisablerID == 0)
  224405. {
  224406. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  224407. IOPMAssertionCreateWithName (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  224408. CFSTR ("Juce"), &screenSaverDisablerID);
  224409. #else
  224410. IOPMAssertionCreate (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  224411. &screenSaverDisablerID);
  224412. #endif
  224413. }
  224414. }
  224415. }
  224416. bool Desktop::isScreenSaverEnabled()
  224417. {
  224418. return screenSaverDisablerID == 0;
  224419. }
  224420. #endif
  224421. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  224422. {
  224423. const ScopedAutoReleasePool pool;
  224424. monitorCoords.clear();
  224425. NSArray* screens = [NSScreen screens];
  224426. const CGFloat mainScreenBottom = [[[NSScreen screens] objectAtIndex: 0] frame].size.height;
  224427. for (unsigned int i = 0; i < [screens count]; ++i)
  224428. {
  224429. NSScreen* s = (NSScreen*) [screens objectAtIndex: i];
  224430. NSRect r = clipToWorkArea ? [s visibleFrame]
  224431. : [s frame];
  224432. monitorCoords.add (Rectangle<int> ((int) r.origin.x,
  224433. (int) (mainScreenBottom - (r.origin.y + r.size.height)),
  224434. (int) r.size.width,
  224435. (int) r.size.height));
  224436. }
  224437. jassert (monitorCoords.size() > 0);
  224438. }
  224439. #endif
  224440. #endif
  224441. /*** End of inlined file: juce_mac_MiscUtilities.mm ***/
  224442. #endif
  224443. /*** Start of inlined file: juce_mac_Debugging.mm ***/
  224444. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224445. // compiled on its own).
  224446. #if JUCE_INCLUDED_FILE
  224447. void Logger::outputDebugString (const String& text)
  224448. {
  224449. std::cerr << text << std::endl;
  224450. }
  224451. bool JUCE_PUBLIC_FUNCTION juce_isRunningUnderDebugger()
  224452. {
  224453. static char testResult = 0;
  224454. if (testResult == 0)
  224455. {
  224456. struct kinfo_proc info;
  224457. int m[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid() };
  224458. size_t sz = sizeof (info);
  224459. sysctl (m, 4, &info, &sz, 0, 0);
  224460. testResult = ((info.kp_proc.p_flag & P_TRACED) != 0) ? 1 : -1;
  224461. }
  224462. return testResult > 0;
  224463. }
  224464. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  224465. {
  224466. return juce_isRunningUnderDebugger();
  224467. }
  224468. #endif
  224469. /*** End of inlined file: juce_mac_Debugging.mm ***/
  224470. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  224471. #if JUCE_IPHONE
  224472. /*** Start of inlined file: juce_mac_Fonts.mm ***/
  224473. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224474. // compiled on its own).
  224475. #if JUCE_INCLUDED_FILE
  224476. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  224477. #define SUPPORT_10_4_FONTS 1
  224478. #define NEW_CGFONT_FUNCTIONS_UNAVAILABLE (CGFontCreateWithFontName == 0)
  224479. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  224480. #define SUPPORT_ONLY_10_4_FONTS 1
  224481. #endif
  224482. END_JUCE_NAMESPACE
  224483. @interface NSFont (PrivateHack)
  224484. - (NSGlyph) _defaultGlyphForChar: (unichar) theChar;
  224485. @end
  224486. BEGIN_JUCE_NAMESPACE
  224487. #endif
  224488. class MacTypeface : public Typeface
  224489. {
  224490. public:
  224491. MacTypeface (const Font& font)
  224492. : Typeface (font.getTypefaceName())
  224493. {
  224494. const ScopedAutoReleasePool pool;
  224495. renderingTransform = CGAffineTransformIdentity;
  224496. bool needsItalicTransform = false;
  224497. #if JUCE_IPHONE
  224498. NSString* fontName = juceStringToNS (font.getTypefaceName());
  224499. if (font.isItalic() || font.isBold())
  224500. {
  224501. NSArray* familyFonts = [UIFont fontNamesForFamilyName: juceStringToNS (font.getTypefaceName())];
  224502. for (NSString* i in familyFonts)
  224503. {
  224504. const String fn (nsStringToJuce (i));
  224505. const String afterDash (fn.fromFirstOccurrenceOf ("-", false, false));
  224506. const bool probablyBold = afterDash.containsIgnoreCase ("bold") || fn.endsWithIgnoreCase ("bold");
  224507. const bool probablyItalic = afterDash.containsIgnoreCase ("oblique")
  224508. || afterDash.containsIgnoreCase ("italic")
  224509. || fn.endsWithIgnoreCase ("oblique")
  224510. || fn.endsWithIgnoreCase ("italic");
  224511. if (probablyBold == font.isBold()
  224512. && probablyItalic == font.isItalic())
  224513. {
  224514. fontName = i;
  224515. needsItalicTransform = false;
  224516. break;
  224517. }
  224518. else if (probablyBold && (! probablyItalic) && probablyBold == font.isBold())
  224519. {
  224520. fontName = i;
  224521. needsItalicTransform = true; // not ideal, so carry on in case we find a better one
  224522. }
  224523. }
  224524. if (needsItalicTransform)
  224525. renderingTransform.c = 0.15f;
  224526. }
  224527. fontRef = CGFontCreateWithFontName ((CFStringRef) fontName);
  224528. const int ascender = abs (CGFontGetAscent (fontRef));
  224529. const float totalHeight = ascender + abs (CGFontGetDescent (fontRef));
  224530. ascent = ascender / totalHeight;
  224531. unitsToHeightScaleFactor = 1.0f / totalHeight;
  224532. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / totalHeight;
  224533. #else
  224534. nsFont = [NSFont fontWithName: juceStringToNS (font.getTypefaceName()) size: 1024];
  224535. if (font.isItalic())
  224536. {
  224537. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: nsFont
  224538. toHaveTrait: NSItalicFontMask];
  224539. if (newFont == nsFont)
  224540. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  224541. nsFont = newFont;
  224542. }
  224543. if (font.isBold())
  224544. nsFont = [[NSFontManager sharedFontManager] convertFont: nsFont toHaveTrait: NSBoldFontMask];
  224545. [nsFont retain];
  224546. ascent = std::abs ((float) [nsFont ascender]);
  224547. float totalSize = ascent + std::abs ((float) [nsFont descender]);
  224548. ascent /= totalSize;
  224549. pathTransform = AffineTransform::identity.scale (1.0f / totalSize, 1.0f / totalSize);
  224550. if (needsItalicTransform)
  224551. {
  224552. pathTransform = pathTransform.sheared (-0.15f, 0.0f);
  224553. renderingTransform.c = 0.15f;
  224554. }
  224555. #if SUPPORT_ONLY_10_4_FONTS
  224556. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  224557. if (atsFont == 0)
  224558. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  224559. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  224560. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  224561. unitsToHeightScaleFactor = 1.0f / totalHeight;
  224562. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  224563. #else
  224564. #if SUPPORT_10_4_FONTS
  224565. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  224566. {
  224567. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  224568. if (atsFont == 0)
  224569. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  224570. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  224571. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  224572. unitsToHeightScaleFactor = 1.0f / totalHeight;
  224573. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  224574. }
  224575. else
  224576. #endif
  224577. {
  224578. fontRef = CGFontCreateWithFontName ((CFStringRef) [nsFont fontName]);
  224579. const int totalHeight = abs (CGFontGetAscent (fontRef)) + abs (CGFontGetDescent (fontRef));
  224580. unitsToHeightScaleFactor = 1.0f / totalHeight;
  224581. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / (float) totalHeight;
  224582. }
  224583. #endif
  224584. #endif
  224585. }
  224586. ~MacTypeface()
  224587. {
  224588. #if ! JUCE_IPHONE
  224589. [nsFont release];
  224590. #endif
  224591. if (fontRef != 0)
  224592. CGFontRelease (fontRef);
  224593. }
  224594. float getAscent() const
  224595. {
  224596. return ascent;
  224597. }
  224598. float getDescent() const
  224599. {
  224600. return 1.0f - ascent;
  224601. }
  224602. float getStringWidth (const String& text)
  224603. {
  224604. if (fontRef == 0 || text.isEmpty())
  224605. return 0;
  224606. const int length = text.length();
  224607. HeapBlock <CGGlyph> glyphs;
  224608. createGlyphsForString (text, length, glyphs);
  224609. float x = 0;
  224610. #if SUPPORT_ONLY_10_4_FONTS
  224611. HeapBlock <NSSize> advances (length);
  224612. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  224613. for (int i = 0; i < length; ++i)
  224614. x += advances[i].width;
  224615. #else
  224616. #if SUPPORT_10_4_FONTS
  224617. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  224618. {
  224619. HeapBlock <NSSize> advances (length);
  224620. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast<NSGlyph*> (glyphs.getData()) count: length];
  224621. for (int i = 0; i < length; ++i)
  224622. x += advances[i].width;
  224623. }
  224624. else
  224625. #endif
  224626. {
  224627. HeapBlock <int> advances (length);
  224628. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  224629. for (int i = 0; i < length; ++i)
  224630. x += advances[i];
  224631. }
  224632. #endif
  224633. return x * unitsToHeightScaleFactor;
  224634. }
  224635. void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
  224636. {
  224637. xOffsets.add (0);
  224638. if (fontRef == 0 || text.isEmpty())
  224639. return;
  224640. const int length = text.length();
  224641. HeapBlock <CGGlyph> glyphs;
  224642. createGlyphsForString (text, length, glyphs);
  224643. #if SUPPORT_ONLY_10_4_FONTS
  224644. HeapBlock <NSSize> advances (length);
  224645. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  224646. int x = 0;
  224647. for (int i = 0; i < length; ++i)
  224648. {
  224649. x += advances[i].width;
  224650. xOffsets.add (x * unitsToHeightScaleFactor);
  224651. resultGlyphs.add (reinterpret_cast <NSGlyph*> (glyphs.getData())[i]);
  224652. }
  224653. #else
  224654. #if SUPPORT_10_4_FONTS
  224655. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  224656. {
  224657. HeapBlock <NSSize> advances (length);
  224658. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  224659. [nsFont getAdvancements: advances forGlyphs: nsGlyphs count: length];
  224660. float x = 0;
  224661. for (int i = 0; i < length; ++i)
  224662. {
  224663. x += advances[i].width;
  224664. xOffsets.add (x * unitsToHeightScaleFactor);
  224665. resultGlyphs.add (nsGlyphs[i]);
  224666. }
  224667. }
  224668. else
  224669. #endif
  224670. {
  224671. HeapBlock <int> advances (length);
  224672. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  224673. {
  224674. int x = 0;
  224675. for (int i = 0; i < length; ++i)
  224676. {
  224677. x += advances [i];
  224678. xOffsets.add (x * unitsToHeightScaleFactor);
  224679. resultGlyphs.add (glyphs[i]);
  224680. }
  224681. }
  224682. }
  224683. #endif
  224684. }
  224685. bool getOutlineForGlyph (int glyphNumber, Path& path)
  224686. {
  224687. #if JUCE_IPHONE
  224688. return false;
  224689. #else
  224690. if (nsFont == 0)
  224691. return false;
  224692. // we might need to apply a transform to the path, so it mustn't have anything else in it
  224693. jassert (path.isEmpty());
  224694. const ScopedAutoReleasePool pool;
  224695. NSBezierPath* bez = [NSBezierPath bezierPath];
  224696. [bez moveToPoint: NSMakePoint (0, 0)];
  224697. [bez appendBezierPathWithGlyph: (NSGlyph) glyphNumber
  224698. inFont: nsFont];
  224699. for (int i = 0; i < [bez elementCount]; ++i)
  224700. {
  224701. NSPoint p[3];
  224702. switch ([bez elementAtIndex: i associatedPoints: p])
  224703. {
  224704. case NSMoveToBezierPathElement:
  224705. path.startNewSubPath ((float) p[0].x, (float) -p[0].y);
  224706. break;
  224707. case NSLineToBezierPathElement:
  224708. path.lineTo ((float) p[0].x, (float) -p[0].y);
  224709. break;
  224710. case NSCurveToBezierPathElement:
  224711. 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);
  224712. break;
  224713. case NSClosePathBezierPathElement:
  224714. path.closeSubPath();
  224715. break;
  224716. default:
  224717. jassertfalse;
  224718. break;
  224719. }
  224720. }
  224721. path.applyTransform (pathTransform);
  224722. return true;
  224723. #endif
  224724. }
  224725. juce_UseDebuggingNewOperator
  224726. CGFontRef fontRef;
  224727. float fontHeightToCGSizeFactor;
  224728. CGAffineTransform renderingTransform;
  224729. private:
  224730. float ascent, unitsToHeightScaleFactor;
  224731. #if JUCE_IPHONE
  224732. #else
  224733. NSFont* nsFont;
  224734. AffineTransform pathTransform;
  224735. #endif
  224736. void createGlyphsForString (const juce_wchar* const text, const int length, HeapBlock <CGGlyph>& glyphs)
  224737. {
  224738. #if SUPPORT_10_4_FONTS
  224739. #if ! SUPPORT_ONLY_10_4_FONTS
  224740. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  224741. #endif
  224742. {
  224743. glyphs.malloc (sizeof (NSGlyph) * length, 1);
  224744. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  224745. for (int i = 0; i < length; ++i)
  224746. nsGlyphs[i] = (NSGlyph) [nsFont _defaultGlyphForChar: text[i]];
  224747. return;
  224748. }
  224749. #endif
  224750. #if ! SUPPORT_ONLY_10_4_FONTS
  224751. if (charToGlyphMapper == 0)
  224752. charToGlyphMapper = new CharToGlyphMapper (fontRef);
  224753. glyphs.malloc (length);
  224754. for (int i = 0; i < length; ++i)
  224755. glyphs[i] = (CGGlyph) charToGlyphMapper->getGlyphForCharacter (text[i]);
  224756. #endif
  224757. }
  224758. #if ! SUPPORT_ONLY_10_4_FONTS
  224759. // Reads a CGFontRef's character map table to convert unicode into glyph numbers
  224760. class CharToGlyphMapper
  224761. {
  224762. public:
  224763. CharToGlyphMapper (CGFontRef fontRef)
  224764. : segCount (0), endCode (0), startCode (0), idDelta (0),
  224765. idRangeOffset (0), glyphIndexes (0)
  224766. {
  224767. CFDataRef cmapTable = CGFontCopyTableForTag (fontRef, 'cmap');
  224768. if (cmapTable != 0)
  224769. {
  224770. const int numSubtables = getValue16 (cmapTable, 2);
  224771. for (int i = 0; i < numSubtables; ++i)
  224772. {
  224773. if (getValue16 (cmapTable, i * 8 + 4) == 0) // check for platform ID of 0
  224774. {
  224775. const int offset = getValue32 (cmapTable, i * 8 + 8);
  224776. if (getValue16 (cmapTable, offset) == 4) // check that it's format 4..
  224777. {
  224778. const int length = getValue16 (cmapTable, offset + 2);
  224779. const int segCountX2 = getValue16 (cmapTable, offset + 6);
  224780. segCount = segCountX2 / 2;
  224781. const int endCodeOffset = offset + 14;
  224782. const int startCodeOffset = endCodeOffset + 2 + segCountX2;
  224783. const int idDeltaOffset = startCodeOffset + segCountX2;
  224784. const int idRangeOffsetOffset = idDeltaOffset + segCountX2;
  224785. const int glyphIndexesOffset = idRangeOffsetOffset + segCountX2;
  224786. endCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + endCodeOffset, segCountX2);
  224787. startCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + startCodeOffset, segCountX2);
  224788. idDelta = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idDeltaOffset, segCountX2);
  224789. idRangeOffset = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idRangeOffsetOffset, segCountX2);
  224790. glyphIndexes = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + glyphIndexesOffset, offset + length - glyphIndexesOffset);
  224791. }
  224792. break;
  224793. }
  224794. }
  224795. CFRelease (cmapTable);
  224796. }
  224797. }
  224798. ~CharToGlyphMapper()
  224799. {
  224800. if (endCode != 0)
  224801. {
  224802. CFRelease (endCode);
  224803. CFRelease (startCode);
  224804. CFRelease (idDelta);
  224805. CFRelease (idRangeOffset);
  224806. CFRelease (glyphIndexes);
  224807. }
  224808. }
  224809. int getGlyphForCharacter (const juce_wchar c) const
  224810. {
  224811. for (int i = 0; i < segCount; ++i)
  224812. {
  224813. if (getValue16 (endCode, i * 2) >= c)
  224814. {
  224815. const int start = getValue16 (startCode, i * 2);
  224816. if (start > c)
  224817. break;
  224818. const int delta = getValue16 (idDelta, i * 2);
  224819. const int rangeOffset = getValue16 (idRangeOffset, i * 2);
  224820. if (rangeOffset == 0)
  224821. return delta + c;
  224822. else
  224823. return getValue16 (glyphIndexes, 2 * ((rangeOffset / 2) + (c - start) - (segCount - i)));
  224824. }
  224825. }
  224826. // If we failed to find it "properly", this dodgy fall-back seems to do the trick for most fonts!
  224827. return jmax (-1, c - 29);
  224828. }
  224829. private:
  224830. int segCount;
  224831. CFDataRef endCode, startCode, idDelta, idRangeOffset, glyphIndexes;
  224832. static uint16 getValue16 (CFDataRef data, const int index)
  224833. {
  224834. return CFSwapInt16BigToHost (*(UInt16*) (CFDataGetBytePtr (data) + index));
  224835. }
  224836. static uint32 getValue32 (CFDataRef data, const int index)
  224837. {
  224838. return CFSwapInt32BigToHost (*(UInt32*) (CFDataGetBytePtr (data) + index));
  224839. }
  224840. };
  224841. ScopedPointer <CharToGlyphMapper> charToGlyphMapper;
  224842. #endif
  224843. MacTypeface (const MacTypeface&);
  224844. MacTypeface& operator= (const MacTypeface&);
  224845. };
  224846. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  224847. {
  224848. return new MacTypeface (font);
  224849. }
  224850. const StringArray Font::findAllTypefaceNames()
  224851. {
  224852. StringArray names;
  224853. const ScopedAutoReleasePool pool;
  224854. #if JUCE_IPHONE
  224855. NSArray* fonts = [UIFont familyNames];
  224856. #else
  224857. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  224858. #endif
  224859. for (unsigned int i = 0; i < [fonts count]; ++i)
  224860. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  224861. names.sort (true);
  224862. return names;
  224863. }
  224864. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  224865. {
  224866. #if JUCE_IPHONE
  224867. defaultSans = "Helvetica";
  224868. defaultSerif = "Times New Roman";
  224869. defaultFixed = "Courier New";
  224870. #else
  224871. defaultSans = "Lucida Grande";
  224872. defaultSerif = "Times New Roman";
  224873. defaultFixed = "Monaco";
  224874. #endif
  224875. }
  224876. #endif
  224877. /*** End of inlined file: juce_mac_Fonts.mm ***/
  224878. /*** Start of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  224879. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224880. // compiled on its own).
  224881. #if JUCE_INCLUDED_FILE
  224882. class CoreGraphicsImage : public Image::SharedImage
  224883. {
  224884. public:
  224885. CoreGraphicsImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  224886. : Image::SharedImage (format_, width_, height_)
  224887. {
  224888. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  224889. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  224890. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  224891. imageData = imageDataAllocated;
  224892. CGColorSpaceRef colourSpace = (format == Image::SingleChannel) ? CGColorSpaceCreateDeviceGray()
  224893. : CGColorSpaceCreateDeviceRGB();
  224894. context = CGBitmapContextCreate (imageData, width, height, 8, lineStride,
  224895. colourSpace, getCGImageFlags (format_));
  224896. CGColorSpaceRelease (colourSpace);
  224897. }
  224898. ~CoreGraphicsImage()
  224899. {
  224900. CGContextRelease (context);
  224901. }
  224902. Image::ImageType getType() const { return Image::NativeImage; }
  224903. LowLevelGraphicsContext* createLowLevelContext();
  224904. SharedImage* clone()
  224905. {
  224906. CoreGraphicsImage* im = new CoreGraphicsImage (format, width, height, false);
  224907. memcpy (im->imageData, imageData, lineStride * height);
  224908. return im;
  224909. }
  224910. static CGImageRef createImage (const Image& juceImage, const bool forAlpha, CGColorSpaceRef colourSpace)
  224911. {
  224912. const CoreGraphicsImage* nativeImage = dynamic_cast <const CoreGraphicsImage*> (juceImage.getSharedImage());
  224913. if (nativeImage != 0 && (juceImage.getFormat() == Image::SingleChannel || ! forAlpha))
  224914. {
  224915. return CGBitmapContextCreateImage (nativeImage->context);
  224916. }
  224917. else
  224918. {
  224919. const Image::BitmapData srcData (juceImage, 0, 0, juceImage.getWidth(), juceImage.getHeight());
  224920. CGDataProviderRef provider = CGDataProviderCreateWithData (0, srcData.data, srcData.lineStride * srcData.height, 0);
  224921. CGImageRef imageRef = CGImageCreate (srcData.width, srcData.height,
  224922. 8, srcData.pixelStride * 8, srcData.lineStride,
  224923. colourSpace, getCGImageFlags (juceImage.getFormat()), provider,
  224924. 0, true, kCGRenderingIntentDefault);
  224925. CGDataProviderRelease (provider);
  224926. return imageRef;
  224927. }
  224928. }
  224929. #if JUCE_MAC
  224930. static NSImage* createNSImage (const Image& image)
  224931. {
  224932. const ScopedAutoReleasePool pool;
  224933. NSImage* im = [[NSImage alloc] init];
  224934. [im setSize: NSMakeSize (image.getWidth(), image.getHeight())];
  224935. [im lockFocus];
  224936. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  224937. CGImageRef imageRef = createImage (image, false, colourSpace);
  224938. CGColorSpaceRelease (colourSpace);
  224939. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  224940. CGContextDrawImage (cg, CGRectMake (0, 0, image.getWidth(), image.getHeight()), imageRef);
  224941. CGImageRelease (imageRef);
  224942. [im unlockFocus];
  224943. return im;
  224944. }
  224945. #endif
  224946. CGContextRef context;
  224947. HeapBlock<uint8> imageDataAllocated;
  224948. private:
  224949. static CGBitmapInfo getCGImageFlags (const Image::PixelFormat& format)
  224950. {
  224951. #if JUCE_BIG_ENDIAN
  224952. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big) : kCGBitmapByteOrderDefault;
  224953. #else
  224954. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little) : kCGBitmapByteOrderDefault;
  224955. #endif
  224956. }
  224957. };
  224958. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  224959. {
  224960. #if USE_COREGRAPHICS_RENDERING
  224961. return new CoreGraphicsImage (format == RGB ? ARGB : format, width, height, clearImage);
  224962. #else
  224963. return createSoftwareImage (format, width, height, clearImage);
  224964. #endif
  224965. }
  224966. class CoreGraphicsContext : public LowLevelGraphicsContext
  224967. {
  224968. public:
  224969. CoreGraphicsContext (CGContextRef context_, const float flipHeight_)
  224970. : context (context_),
  224971. flipHeight (flipHeight_),
  224972. state (new SavedState()),
  224973. numGradientLookupEntries (0),
  224974. lastClipRectIsValid (false)
  224975. {
  224976. CGContextRetain (context);
  224977. CGContextSaveGState(context);
  224978. CGContextSetShouldSmoothFonts (context, true);
  224979. CGContextSetShouldAntialias (context, true);
  224980. CGContextSetBlendMode (context, kCGBlendModeNormal);
  224981. rgbColourSpace = CGColorSpaceCreateDeviceRGB();
  224982. greyColourSpace = CGColorSpaceCreateDeviceGray();
  224983. gradientCallbacks.version = 0;
  224984. gradientCallbacks.evaluate = gradientCallback;
  224985. gradientCallbacks.releaseInfo = 0;
  224986. setFont (Font());
  224987. }
  224988. ~CoreGraphicsContext()
  224989. {
  224990. CGContextRestoreGState (context);
  224991. CGContextRelease (context);
  224992. CGColorSpaceRelease (rgbColourSpace);
  224993. CGColorSpaceRelease (greyColourSpace);
  224994. }
  224995. bool isVectorDevice() const { return false; }
  224996. void setOrigin (int x, int y)
  224997. {
  224998. CGContextTranslateCTM (context, x, -y);
  224999. if (lastClipRectIsValid)
  225000. lastClipRect.translate (-x, -y);
  225001. }
  225002. bool clipToRectangle (const Rectangle<int>& r)
  225003. {
  225004. CGContextClipToRect (context, CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()));
  225005. if (lastClipRectIsValid)
  225006. {
  225007. lastClipRect = lastClipRect.getIntersection (r);
  225008. return ! lastClipRect.isEmpty();
  225009. }
  225010. return ! isClipEmpty();
  225011. }
  225012. bool clipToRectangleList (const RectangleList& clipRegion)
  225013. {
  225014. if (clipRegion.isEmpty())
  225015. {
  225016. CGContextClipToRect (context, CGRectMake (0, 0, 0, 0));
  225017. lastClipRectIsValid = true;
  225018. lastClipRect = Rectangle<int>();
  225019. return false;
  225020. }
  225021. else
  225022. {
  225023. const int numRects = clipRegion.getNumRectangles();
  225024. HeapBlock <CGRect> rects (numRects);
  225025. for (int i = 0; i < numRects; ++i)
  225026. {
  225027. const Rectangle<int>& r = clipRegion.getRectangle(i);
  225028. rects[i] = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  225029. }
  225030. CGContextClipToRects (context, rects, numRects);
  225031. lastClipRectIsValid = false;
  225032. return ! isClipEmpty();
  225033. }
  225034. }
  225035. void excludeClipRectangle (const Rectangle<int>& r)
  225036. {
  225037. RectangleList remaining (getClipBounds());
  225038. remaining.subtract (r);
  225039. clipToRectangleList (remaining);
  225040. lastClipRectIsValid = false;
  225041. }
  225042. void clipToPath (const Path& path, const AffineTransform& transform)
  225043. {
  225044. createPath (path, transform);
  225045. CGContextClip (context);
  225046. lastClipRectIsValid = false;
  225047. }
  225048. void clipToImageAlpha (const Image& sourceImage, const Rectangle<int>& srcClip, const AffineTransform& transform)
  225049. {
  225050. if (! transform.isSingularity())
  225051. {
  225052. Image singleChannelImage (sourceImage);
  225053. if (sourceImage.getFormat() != Image::SingleChannel)
  225054. singleChannelImage = sourceImage.convertedToFormat (Image::SingleChannel);
  225055. CGImageRef image = CoreGraphicsImage::createImage (singleChannelImage, true, greyColourSpace);
  225056. if (srcClip != sourceImage.getBounds())
  225057. {
  225058. CGImageRef fullImage = image;
  225059. image = CGImageCreateWithImageInRect (fullImage, CGRectMake (srcClip.getX(), srcClip.getY(),
  225060. srcClip.getWidth(), srcClip.getHeight()));
  225061. CGImageRelease (fullImage);
  225062. }
  225063. flip();
  225064. AffineTransform t (AffineTransform::scale (1.0f, -1.0f).translated (0, srcClip.getHeight()).followedBy (transform));
  225065. applyTransform (t);
  225066. CGRect r = CGRectMake (0, 0, srcClip.getWidth(), srcClip.getHeight());
  225067. CGContextClipToMask (context, r, image);
  225068. applyTransform (t.inverted());
  225069. flip();
  225070. CGImageRelease (image);
  225071. lastClipRectIsValid = false;
  225072. }
  225073. }
  225074. bool clipRegionIntersects (const Rectangle<int>& r)
  225075. {
  225076. return getClipBounds().intersects (r);
  225077. }
  225078. const Rectangle<int> getClipBounds() const
  225079. {
  225080. if (! lastClipRectIsValid)
  225081. {
  225082. CGRect bounds = CGRectIntegral (CGContextGetClipBoundingBox (context));
  225083. lastClipRectIsValid = true;
  225084. lastClipRect.setBounds (roundToInt (bounds.origin.x),
  225085. roundToInt (flipHeight - (bounds.origin.y + bounds.size.height)),
  225086. roundToInt (bounds.size.width),
  225087. roundToInt (bounds.size.height));
  225088. }
  225089. return lastClipRect;
  225090. }
  225091. bool isClipEmpty() const
  225092. {
  225093. return getClipBounds().isEmpty();
  225094. }
  225095. void saveState()
  225096. {
  225097. CGContextSaveGState (context);
  225098. stateStack.add (new SavedState (*state));
  225099. }
  225100. void restoreState()
  225101. {
  225102. CGContextRestoreGState (context);
  225103. SavedState* const top = stateStack.getLast();
  225104. if (top != 0)
  225105. {
  225106. state = top;
  225107. stateStack.removeLast (1, false);
  225108. lastClipRectIsValid = false;
  225109. }
  225110. else
  225111. {
  225112. jassertfalse; // trying to pop with an empty stack!
  225113. }
  225114. }
  225115. void setFill (const FillType& fillType)
  225116. {
  225117. state->fillType = fillType;
  225118. if (fillType.isColour())
  225119. {
  225120. CGContextSetRGBFillColor (context, fillType.colour.getFloatRed(), fillType.colour.getFloatGreen(),
  225121. fillType.colour.getFloatBlue(), fillType.colour.getFloatAlpha());
  225122. CGContextSetAlpha (context, 1.0f);
  225123. }
  225124. }
  225125. void setOpacity (float newOpacity)
  225126. {
  225127. state->fillType.setOpacity (newOpacity);
  225128. setFill (state->fillType);
  225129. }
  225130. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  225131. {
  225132. CGContextSetInterpolationQuality (context, quality == Graphics::lowResamplingQuality
  225133. ? kCGInterpolationLow
  225134. : kCGInterpolationHigh);
  225135. }
  225136. void fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  225137. {
  225138. CGRect cgRect = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  225139. if (replaceExistingContents)
  225140. {
  225141. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  225142. CGContextClearRect (context, cgRect);
  225143. #else
  225144. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  225145. if (CGContextDrawLinearGradient == 0) // (just a way of checking whether we're running in 10.5 or later)
  225146. CGContextClearRect (context, cgRect);
  225147. else
  225148. #endif
  225149. CGContextSetBlendMode (context, kCGBlendModeCopy);
  225150. #endif
  225151. fillRect (r, false);
  225152. CGContextSetBlendMode (context, kCGBlendModeNormal);
  225153. }
  225154. else
  225155. {
  225156. if (state->fillType.isColour())
  225157. {
  225158. CGContextFillRect (context, cgRect);
  225159. }
  225160. else if (state->fillType.isGradient())
  225161. {
  225162. CGContextSaveGState (context);
  225163. CGContextClipToRect (context, cgRect);
  225164. drawGradient();
  225165. CGContextRestoreGState (context);
  225166. }
  225167. else
  225168. {
  225169. CGContextSaveGState (context);
  225170. CGContextClipToRect (context, cgRect);
  225171. drawImage (state->fillType.image, state->fillType.image.getBounds(), state->fillType.transform, true);
  225172. CGContextRestoreGState (context);
  225173. }
  225174. }
  225175. }
  225176. void fillPath (const Path& path, const AffineTransform& transform)
  225177. {
  225178. CGContextSaveGState (context);
  225179. if (state->fillType.isColour())
  225180. {
  225181. flip();
  225182. applyTransform (transform);
  225183. createPath (path);
  225184. if (path.isUsingNonZeroWinding())
  225185. CGContextFillPath (context);
  225186. else
  225187. CGContextEOFillPath (context);
  225188. }
  225189. else
  225190. {
  225191. createPath (path, transform);
  225192. if (path.isUsingNonZeroWinding())
  225193. CGContextClip (context);
  225194. else
  225195. CGContextEOClip (context);
  225196. if (state->fillType.isGradient())
  225197. drawGradient();
  225198. else
  225199. drawImage (state->fillType.image, state->fillType.image.getBounds(), state->fillType.transform, true);
  225200. }
  225201. CGContextRestoreGState (context);
  225202. }
  225203. void drawImage (const Image& sourceImage, const Rectangle<int>& srcClip,
  225204. const AffineTransform& transform, const bool fillEntireClipAsTiles)
  225205. {
  225206. jassert (sourceImage.getBounds().contains (srcClip));
  225207. CGImageRef fullImage = CoreGraphicsImage::createImage (sourceImage, false, rgbColourSpace);
  225208. CGImageRef image = fullImage;
  225209. if (srcClip != sourceImage.getBounds())
  225210. {
  225211. image = CGImageCreateWithImageInRect (fullImage, CGRectMake (srcClip.getX(), srcClip.getY(),
  225212. srcClip.getWidth(), srcClip.getHeight()));
  225213. CGImageRelease (fullImage);
  225214. }
  225215. CGContextSaveGState (context);
  225216. CGContextSetAlpha (context, state->fillType.getOpacity());
  225217. flip();
  225218. applyTransform (AffineTransform::scale (1.0f, -1.0f).translated (0, srcClip.getHeight()).followedBy (transform));
  225219. CGRect imageRect = CGRectMake (0, 0, srcClip.getWidth(), srcClip.getHeight());
  225220. if (fillEntireClipAsTiles)
  225221. {
  225222. #if JUCE_IPHONE
  225223. CGContextDrawTiledImage (context, imageRect, image);
  225224. #else
  225225. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  225226. // There's a bug in CGContextDrawTiledImage that makes it incredibly slow
  225227. // if it's doing a transformation - it's quicker to just draw lots of images manually
  225228. if (CGContextDrawTiledImage != 0 && transform.isOnlyTranslation())
  225229. CGContextDrawTiledImage (context, imageRect, image);
  225230. else
  225231. #endif
  225232. {
  225233. // Fallback to manually doing a tiled fill on 10.4
  225234. CGRect clip = CGRectIntegral (CGContextGetClipBoundingBox (context));
  225235. const int iw = srcClip.getWidth();
  225236. const int ih = srcClip.getHeight();
  225237. int x = 0, y = 0;
  225238. while (x > clip.origin.x) x -= iw;
  225239. while (y > clip.origin.y) y -= ih;
  225240. const int right = (int) (clip.origin.x + clip.size.width);
  225241. const int bottom = (int) (clip.origin.y + clip.size.height);
  225242. while (y < bottom)
  225243. {
  225244. for (int x2 = x; x2 < right; x2 += iw)
  225245. CGContextDrawImage (context, CGRectMake (x2, y, iw, ih), image);
  225246. y += ih;
  225247. }
  225248. }
  225249. #endif
  225250. }
  225251. else
  225252. {
  225253. CGContextDrawImage (context, imageRect, image);
  225254. }
  225255. CGImageRelease (image); // (This causes a memory bug in iPhone sim 3.0 - try upgrading to a later version if you hit this)
  225256. CGContextRestoreGState (context);
  225257. }
  225258. void drawLine (const Line<float>& line)
  225259. {
  225260. CGContextSetLineCap (context, kCGLineCapSquare);
  225261. CGContextSetLineWidth (context, 1.0f);
  225262. CGContextSetRGBStrokeColor (context,
  225263. state->fillType.colour.getFloatRed(), state->fillType.colour.getFloatGreen(),
  225264. state->fillType.colour.getFloatBlue(), state->fillType.colour.getFloatAlpha());
  225265. CGPoint cgLine[] = { { (CGFloat) line.getStartX(), flipHeight - (CGFloat) line.getStartY() },
  225266. { (CGFloat) line.getEndX(), flipHeight - (CGFloat) line.getEndY() } };
  225267. CGContextStrokeLineSegments (context, cgLine, 1);
  225268. }
  225269. void drawVerticalLine (const int x, float top, float bottom)
  225270. {
  225271. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  225272. CGContextFillRect (context, CGRectMake (x, flipHeight - bottom, 1.0f, bottom - top));
  225273. #else
  225274. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  225275. // the x co-ord slightly to trick it..
  225276. CGContextFillRect (context, CGRectMake (x + 1.0f / 256.0f, flipHeight - bottom, 1.0f + 1.0f / 256.0f, bottom - top));
  225277. #endif
  225278. }
  225279. void drawHorizontalLine (const int y, float left, float right)
  225280. {
  225281. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  225282. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + 1.0f), right - left, 1.0f));
  225283. #else
  225284. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  225285. // the x co-ord slightly to trick it..
  225286. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + (1.0f + 1.0f / 256.0f)), right - left, 1.0f + 1.0f / 256.0f));
  225287. #endif
  225288. }
  225289. void setFont (const Font& newFont)
  225290. {
  225291. if (state->font != newFont)
  225292. {
  225293. state->fontRef = 0;
  225294. state->font = newFont;
  225295. MacTypeface* mf = dynamic_cast <MacTypeface*> (state->font.getTypeface());
  225296. if (mf != 0)
  225297. {
  225298. state->fontRef = mf->fontRef;
  225299. CGContextSetFont (context, state->fontRef);
  225300. CGContextSetFontSize (context, state->font.getHeight() * mf->fontHeightToCGSizeFactor);
  225301. state->fontTransform = mf->renderingTransform;
  225302. state->fontTransform.a *= state->font.getHorizontalScale();
  225303. CGContextSetTextMatrix (context, state->fontTransform);
  225304. }
  225305. }
  225306. }
  225307. const Font getFont()
  225308. {
  225309. return state->font;
  225310. }
  225311. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  225312. {
  225313. if (state->fontRef != 0 && state->fillType.isColour())
  225314. {
  225315. if (transform.isOnlyTranslation())
  225316. {
  225317. CGContextSetTextMatrix (context, state->fontTransform); // have to set this each time, as it's not saved as part of the state
  225318. CGGlyph g = glyphNumber;
  225319. CGContextShowGlyphsAtPoint (context, transform.getTranslationX(),
  225320. flipHeight - roundToInt (transform.getTranslationY()), &g, 1);
  225321. }
  225322. else
  225323. {
  225324. CGContextSaveGState (context);
  225325. flip();
  225326. applyTransform (transform);
  225327. CGAffineTransform t = state->fontTransform;
  225328. t.d = -t.d;
  225329. CGContextSetTextMatrix (context, t);
  225330. CGGlyph g = glyphNumber;
  225331. CGContextShowGlyphsAtPoint (context, 0, 0, &g, 1);
  225332. CGContextRestoreGState (context);
  225333. }
  225334. }
  225335. else
  225336. {
  225337. Path p;
  225338. Font& f = state->font;
  225339. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  225340. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight())
  225341. .followedBy (transform));
  225342. }
  225343. }
  225344. private:
  225345. CGContextRef context;
  225346. const CGFloat flipHeight;
  225347. CGColorSpaceRef rgbColourSpace, greyColourSpace;
  225348. CGFunctionCallbacks gradientCallbacks;
  225349. mutable Rectangle<int> lastClipRect;
  225350. mutable bool lastClipRectIsValid;
  225351. struct SavedState
  225352. {
  225353. SavedState()
  225354. : font (1.0f), fontRef (0), fontTransform (CGAffineTransformIdentity)
  225355. {
  225356. }
  225357. SavedState (const SavedState& other)
  225358. : fillType (other.fillType), font (other.font), fontRef (other.fontRef),
  225359. fontTransform (other.fontTransform)
  225360. {
  225361. }
  225362. ~SavedState()
  225363. {
  225364. }
  225365. FillType fillType;
  225366. Font font;
  225367. CGFontRef fontRef;
  225368. CGAffineTransform fontTransform;
  225369. };
  225370. ScopedPointer <SavedState> state;
  225371. OwnedArray <SavedState> stateStack;
  225372. HeapBlock <PixelARGB> gradientLookupTable;
  225373. int numGradientLookupEntries;
  225374. static void gradientCallback (void* info, const CGFloat* inData, CGFloat* outData)
  225375. {
  225376. const CoreGraphicsContext* const g = static_cast <const CoreGraphicsContext*> (info);
  225377. const int index = roundToInt (g->numGradientLookupEntries * inData[0]);
  225378. PixelARGB colour (g->gradientLookupTable [jlimit (0, g->numGradientLookupEntries, index)]);
  225379. colour.unpremultiply();
  225380. outData[0] = colour.getRed() / 255.0f;
  225381. outData[1] = colour.getGreen() / 255.0f;
  225382. outData[2] = colour.getBlue() / 255.0f;
  225383. outData[3] = colour.getAlpha() / 255.0f;
  225384. }
  225385. CGShadingRef createGradient (const AffineTransform& transform, ColourGradient gradient)
  225386. {
  225387. numGradientLookupEntries = gradient.createLookupTable (transform, gradientLookupTable);
  225388. --numGradientLookupEntries;
  225389. CGShadingRef result = 0;
  225390. CGFunctionRef function = CGFunctionCreate (this, 1, 0, 4, 0, &gradientCallbacks);
  225391. CGPoint p1 (CGPointMake (gradient.point1.getX(), gradient.point1.getY()));
  225392. if (gradient.isRadial)
  225393. {
  225394. result = CGShadingCreateRadial (rgbColourSpace, p1, 0,
  225395. p1, gradient.point1.getDistanceFrom (gradient.point2),
  225396. function, true, true);
  225397. }
  225398. else
  225399. {
  225400. result = CGShadingCreateAxial (rgbColourSpace, p1,
  225401. CGPointMake (gradient.point2.getX(), gradient.point2.getY()),
  225402. function, true, true);
  225403. }
  225404. CGFunctionRelease (function);
  225405. return result;
  225406. }
  225407. void drawGradient()
  225408. {
  225409. flip();
  225410. applyTransform (state->fillType.transform);
  225411. CGContextSetInterpolationQuality (context, kCGInterpolationDefault); // (This is required for 10.4, where there's a crash if
  225412. // you draw a gradient with high quality interp enabled).
  225413. CGShadingRef shading = createGradient (state->fillType.transform, *(state->fillType.gradient));
  225414. CGContextSetAlpha (context, state->fillType.getOpacity());
  225415. CGContextDrawShading (context, shading);
  225416. CGShadingRelease (shading);
  225417. }
  225418. void createPath (const Path& path) const
  225419. {
  225420. CGContextBeginPath (context);
  225421. Path::Iterator i (path);
  225422. while (i.next())
  225423. {
  225424. switch (i.elementType)
  225425. {
  225426. case Path::Iterator::startNewSubPath: CGContextMoveToPoint (context, i.x1, i.y1); break;
  225427. case Path::Iterator::lineTo: CGContextAddLineToPoint (context, i.x1, i.y1); break;
  225428. case Path::Iterator::quadraticTo: CGContextAddQuadCurveToPoint (context, i.x1, i.y1, i.x2, i.y2); break;
  225429. case Path::Iterator::cubicTo: CGContextAddCurveToPoint (context, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3); break;
  225430. case Path::Iterator::closePath: CGContextClosePath (context); break;
  225431. default: jassertfalse; break;
  225432. }
  225433. }
  225434. }
  225435. void createPath (const Path& path, const AffineTransform& transform) const
  225436. {
  225437. CGContextBeginPath (context);
  225438. Path::Iterator i (path);
  225439. while (i.next())
  225440. {
  225441. switch (i.elementType)
  225442. {
  225443. case Path::Iterator::startNewSubPath:
  225444. transform.transformPoint (i.x1, i.y1);
  225445. CGContextMoveToPoint (context, i.x1, flipHeight - i.y1);
  225446. break;
  225447. case Path::Iterator::lineTo:
  225448. transform.transformPoint (i.x1, i.y1);
  225449. CGContextAddLineToPoint (context, i.x1, flipHeight - i.y1);
  225450. break;
  225451. case Path::Iterator::quadraticTo:
  225452. transform.transformPoint (i.x1, i.y1);
  225453. transform.transformPoint (i.x2, i.y2);
  225454. CGContextAddQuadCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2);
  225455. break;
  225456. case Path::Iterator::cubicTo:
  225457. transform.transformPoint (i.x1, i.y1);
  225458. transform.transformPoint (i.x2, i.y2);
  225459. transform.transformPoint (i.x3, i.y3);
  225460. CGContextAddCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2, i.x3, flipHeight - i.y3);
  225461. break;
  225462. case Path::Iterator::closePath:
  225463. CGContextClosePath (context); break;
  225464. default:
  225465. jassertfalse;
  225466. break;
  225467. }
  225468. }
  225469. }
  225470. void flip() const
  225471. {
  225472. CGContextConcatCTM (context, CGAffineTransformMake (1, 0, 0, -1, 0, flipHeight));
  225473. }
  225474. void applyTransform (const AffineTransform& transform) const
  225475. {
  225476. CGAffineTransform t;
  225477. t.a = transform.mat00;
  225478. t.b = transform.mat10;
  225479. t.c = transform.mat01;
  225480. t.d = transform.mat11;
  225481. t.tx = transform.mat02;
  225482. t.ty = transform.mat12;
  225483. CGContextConcatCTM (context, t);
  225484. }
  225485. CoreGraphicsContext (const CoreGraphicsContext&);
  225486. CoreGraphicsContext& operator= (const CoreGraphicsContext&);
  225487. };
  225488. LowLevelGraphicsContext* CoreGraphicsImage::createLowLevelContext()
  225489. {
  225490. return new CoreGraphicsContext (context, height);
  225491. }
  225492. #endif
  225493. /*** End of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  225494. /*** Start of inlined file: juce_iphone_UIViewComponentPeer.mm ***/
  225495. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225496. // compiled on its own).
  225497. #if JUCE_INCLUDED_FILE
  225498. class UIViewComponentPeer;
  225499. END_JUCE_NAMESPACE
  225500. #define JuceUIView MakeObjCClassName(JuceUIView)
  225501. @interface JuceUIView : UIView <UITextFieldDelegate>
  225502. {
  225503. @public
  225504. UIViewComponentPeer* owner;
  225505. UITextField *hiddenTextField;
  225506. }
  225507. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner withFrame: (CGRect) frame;
  225508. - (void) dealloc;
  225509. - (void) drawRect: (CGRect) r;
  225510. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event;
  225511. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event;
  225512. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event;
  225513. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event;
  225514. - (BOOL) becomeFirstResponder;
  225515. - (BOOL) resignFirstResponder;
  225516. - (BOOL) canBecomeFirstResponder;
  225517. - (void) asyncRepaint: (id) rect;
  225518. - (BOOL) textField: (UITextField*) textField shouldChangeCharactersInRange: (NSRange) range replacementString: (NSString*) string;
  225519. - (BOOL) textFieldShouldClear: (UITextField*) textField;
  225520. - (BOOL) textFieldShouldReturn: (UITextField*) textField;
  225521. @end
  225522. #define JuceUIWindow MakeObjCClassName(JuceUIWindow)
  225523. @interface JuceUIWindow : UIWindow
  225524. {
  225525. @private
  225526. UIViewComponentPeer* owner;
  225527. bool isZooming;
  225528. }
  225529. - (void) setOwner: (UIViewComponentPeer*) owner;
  225530. - (void) becomeKeyWindow;
  225531. @end
  225532. BEGIN_JUCE_NAMESPACE
  225533. class UIViewComponentPeer : public ComponentPeer,
  225534. public FocusChangeListener
  225535. {
  225536. public:
  225537. UIViewComponentPeer (Component* const component,
  225538. const int windowStyleFlags,
  225539. UIView* viewToAttachTo);
  225540. ~UIViewComponentPeer();
  225541. void* getNativeHandle() const;
  225542. void setVisible (bool shouldBeVisible);
  225543. void setTitle (const String& title);
  225544. void setPosition (int x, int y);
  225545. void setSize (int w, int h);
  225546. void setBounds (int x, int y, int w, int h, bool isNowFullScreen);
  225547. const Rectangle<int> getBounds() const;
  225548. const Rectangle<int> getBounds (const bool global) const;
  225549. const Point<int> getScreenPosition() const;
  225550. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition);
  225551. const Point<int> globalPositionToRelative (const Point<int>& screenPosition);
  225552. void setMinimised (bool shouldBeMinimised);
  225553. bool isMinimised() const;
  225554. void setFullScreen (bool shouldBeFullScreen);
  225555. bool isFullScreen() const;
  225556. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const;
  225557. const BorderSize getFrameSize() const;
  225558. bool setAlwaysOnTop (bool alwaysOnTop);
  225559. void toFront (bool makeActiveWindow);
  225560. void toBehind (ComponentPeer* other);
  225561. void setIcon (const Image& newIcon);
  225562. virtual void drawRect (CGRect r);
  225563. virtual bool canBecomeKeyWindow();
  225564. virtual bool windowShouldClose();
  225565. virtual void redirectMovedOrResized();
  225566. virtual CGRect constrainRect (CGRect r);
  225567. virtual void viewFocusGain();
  225568. virtual void viewFocusLoss();
  225569. bool isFocused() const;
  225570. void grabFocus();
  225571. void textInputRequired (const Point<int>& position);
  225572. virtual BOOL textFieldReplaceCharacters (const Range<int>& range, const String& text);
  225573. virtual BOOL textFieldShouldClear();
  225574. virtual BOOL textFieldShouldReturn();
  225575. void updateHiddenTextContent (TextInputTarget* target);
  225576. void globalFocusChanged (Component*);
  225577. void handleTouches (UIEvent* e, bool isDown, bool isUp, bool isCancel);
  225578. void repaint (const Rectangle<int>& area);
  225579. void performAnyPendingRepaintsNow();
  225580. juce_UseDebuggingNewOperator
  225581. UIWindow* window;
  225582. JuceUIView* view;
  225583. bool isSharedWindow, fullScreen, insideDrawRect;
  225584. static ModifierKeys currentModifiers;
  225585. static int64 getMouseTime (UIEvent* e)
  225586. {
  225587. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  225588. + (int64) ([e timestamp] * 1000.0);
  225589. }
  225590. Array <UITouch*> currentTouches;
  225591. };
  225592. END_JUCE_NAMESPACE
  225593. @implementation JuceUIView
  225594. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner_
  225595. withFrame: (CGRect) frame
  225596. {
  225597. [super initWithFrame: frame];
  225598. owner = owner_;
  225599. hiddenTextField = [[UITextField alloc] initWithFrame: CGRectMake (0, 0, 0, 0)];
  225600. [self addSubview: hiddenTextField];
  225601. hiddenTextField.delegate = self;
  225602. return self;
  225603. }
  225604. - (void) dealloc
  225605. {
  225606. [hiddenTextField removeFromSuperview];
  225607. [hiddenTextField release];
  225608. [super dealloc];
  225609. }
  225610. - (void) drawRect: (CGRect) r
  225611. {
  225612. if (owner != 0)
  225613. owner->drawRect (r);
  225614. }
  225615. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  225616. {
  225617. return false;
  225618. }
  225619. ModifierKeys UIViewComponentPeer::currentModifiers;
  225620. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  225621. {
  225622. return UIViewComponentPeer::currentModifiers;
  225623. }
  225624. void ModifierKeys::updateCurrentModifiers() throw()
  225625. {
  225626. currentModifiers = UIViewComponentPeer::currentModifiers;
  225627. }
  225628. JUCE_NAMESPACE::Point<int> juce_lastMousePos;
  225629. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event
  225630. {
  225631. if (owner != 0)
  225632. owner->handleTouches (event, true, false, false);
  225633. }
  225634. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event
  225635. {
  225636. if (owner != 0)
  225637. owner->handleTouches (event, false, false, false);
  225638. }
  225639. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event
  225640. {
  225641. if (owner != 0)
  225642. owner->handleTouches (event, false, true, false);
  225643. }
  225644. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event
  225645. {
  225646. if (owner != 0)
  225647. owner->handleTouches (event, false, true, true);
  225648. [self touchesEnded: touches withEvent: event];
  225649. }
  225650. - (BOOL) becomeFirstResponder
  225651. {
  225652. if (owner != 0)
  225653. owner->viewFocusGain();
  225654. return true;
  225655. }
  225656. - (BOOL) resignFirstResponder
  225657. {
  225658. if (owner != 0)
  225659. owner->viewFocusLoss();
  225660. return true;
  225661. }
  225662. - (BOOL) canBecomeFirstResponder
  225663. {
  225664. return owner != 0 && owner->canBecomeKeyWindow();
  225665. }
  225666. - (void) asyncRepaint: (id) rect
  225667. {
  225668. CGRect* r = (CGRect*) [((NSData*) rect) bytes];
  225669. [self setNeedsDisplayInRect: *r];
  225670. }
  225671. - (BOOL) textField: (UITextField*) textField shouldChangeCharactersInRange: (NSRange) range replacementString: (NSString*) text
  225672. {
  225673. return owner->textFieldReplaceCharacters (Range<int> (range.location, range.location + range.length),
  225674. nsStringToJuce (text));
  225675. }
  225676. - (BOOL) textFieldShouldClear: (UITextField*) textField
  225677. {
  225678. return owner->textFieldShouldClear();
  225679. }
  225680. - (BOOL) textFieldShouldReturn: (UITextField*) textField
  225681. {
  225682. return owner->textFieldShouldReturn();
  225683. }
  225684. @end
  225685. @implementation JuceUIWindow
  225686. - (void) setOwner: (UIViewComponentPeer*) owner_
  225687. {
  225688. owner = owner_;
  225689. isZooming = false;
  225690. }
  225691. - (void) becomeKeyWindow
  225692. {
  225693. [super becomeKeyWindow];
  225694. if (owner != 0)
  225695. owner->grabFocus();
  225696. }
  225697. @end
  225698. BEGIN_JUCE_NAMESPACE
  225699. UIViewComponentPeer::UIViewComponentPeer (Component* const component,
  225700. const int windowStyleFlags,
  225701. UIView* viewToAttachTo)
  225702. : ComponentPeer (component, windowStyleFlags),
  225703. window (0),
  225704. view (0),
  225705. isSharedWindow (viewToAttachTo != 0),
  225706. fullScreen (false),
  225707. insideDrawRect (false)
  225708. {
  225709. CGRect r = CGRectMake (0, 0, (float) component->getWidth(), (float) component->getHeight());
  225710. view = [[JuceUIView alloc] initWithOwner: this withFrame: r];
  225711. if (isSharedWindow)
  225712. {
  225713. window = [viewToAttachTo window];
  225714. [viewToAttachTo addSubview: view];
  225715. setVisible (component->isVisible());
  225716. }
  225717. else
  225718. {
  225719. r.origin.x = (float) component->getX();
  225720. r.origin.y = (float) component->getY();
  225721. r.origin.y = [[UIScreen mainScreen] bounds].size.height - (r.origin.y + r.size.height);
  225722. window = [[JuceUIWindow alloc] init];
  225723. window.frame = r;
  225724. window.opaque = component->isOpaque();
  225725. view.opaque = component->isOpaque();
  225726. window.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  225727. view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  225728. [((JuceUIWindow*) window) setOwner: this];
  225729. if (component->isAlwaysOnTop())
  225730. window.windowLevel = UIWindowLevelAlert;
  225731. [window addSubview: view];
  225732. view.frame = CGRectMake (0, 0, r.size.width, r.size.height);
  225733. view.hidden = ! component->isVisible();
  225734. window.hidden = ! component->isVisible();
  225735. view.multipleTouchEnabled = YES;
  225736. }
  225737. setTitle (component->getName());
  225738. Desktop::getInstance().addFocusChangeListener (this);
  225739. }
  225740. UIViewComponentPeer::~UIViewComponentPeer()
  225741. {
  225742. Desktop::getInstance().removeFocusChangeListener (this);
  225743. view->owner = 0;
  225744. [view removeFromSuperview];
  225745. [view release];
  225746. if (! isSharedWindow)
  225747. {
  225748. [((JuceUIWindow*) window) setOwner: 0];
  225749. [window release];
  225750. }
  225751. }
  225752. void* UIViewComponentPeer::getNativeHandle() const
  225753. {
  225754. return view;
  225755. }
  225756. void UIViewComponentPeer::setVisible (bool shouldBeVisible)
  225757. {
  225758. view.hidden = ! shouldBeVisible;
  225759. if (! isSharedWindow)
  225760. window.hidden = ! shouldBeVisible;
  225761. }
  225762. void UIViewComponentPeer::setTitle (const String& title)
  225763. {
  225764. // xxx is this possible?
  225765. }
  225766. void UIViewComponentPeer::setPosition (int x, int y)
  225767. {
  225768. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  225769. }
  225770. void UIViewComponentPeer::setSize (int w, int h)
  225771. {
  225772. setBounds (component->getX(), component->getY(), w, h, false);
  225773. }
  225774. void UIViewComponentPeer::setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  225775. {
  225776. fullScreen = isNowFullScreen;
  225777. w = jmax (0, w);
  225778. h = jmax (0, h);
  225779. CGRect r;
  225780. r.origin.x = (float) x;
  225781. r.origin.y = (float) y;
  225782. r.size.width = (float) w;
  225783. r.size.height = (float) h;
  225784. if (isSharedWindow)
  225785. {
  225786. //r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  225787. if ([view frame].size.width != r.size.width
  225788. || [view frame].size.height != r.size.height)
  225789. [view setNeedsDisplay];
  225790. view.frame = r;
  225791. }
  225792. else
  225793. {
  225794. window.frame = r;
  225795. view.frame = CGRectMake (0, 0, r.size.width, r.size.height);
  225796. }
  225797. }
  225798. const Rectangle<int> UIViewComponentPeer::getBounds (const bool global) const
  225799. {
  225800. CGRect r = [view frame];
  225801. if (global && [view window] != 0)
  225802. {
  225803. r = [view convertRect: r toView: nil];
  225804. CGRect wr = [[view window] frame];
  225805. r.origin.x += wr.origin.x;
  225806. r.origin.y += wr.origin.y;
  225807. }
  225808. return Rectangle<int> ((int) r.origin.x, (int) r.origin.y,
  225809. (int) r.size.width, (int) r.size.height);
  225810. }
  225811. const Rectangle<int> UIViewComponentPeer::getBounds() const
  225812. {
  225813. return getBounds (! isSharedWindow);
  225814. }
  225815. const Point<int> UIViewComponentPeer::getScreenPosition() const
  225816. {
  225817. return getBounds (true).getPosition();
  225818. }
  225819. const Point<int> UIViewComponentPeer::relativePositionToGlobal (const Point<int>& relativePosition)
  225820. {
  225821. return relativePosition + getScreenPosition();
  225822. }
  225823. const Point<int> UIViewComponentPeer::globalPositionToRelative (const Point<int>& screenPosition)
  225824. {
  225825. return screenPosition - getScreenPosition();
  225826. }
  225827. CGRect UIViewComponentPeer::constrainRect (CGRect r)
  225828. {
  225829. if (constrainer != 0)
  225830. {
  225831. CGRect current = [window frame];
  225832. current.origin.y = [[UIScreen mainScreen] bounds].size.height - current.origin.y - current.size.height;
  225833. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.origin.y - r.size.height;
  225834. Rectangle<int> pos ((int) r.origin.x, (int) r.origin.y,
  225835. (int) r.size.width, (int) r.size.height);
  225836. Rectangle<int> original ((int) current.origin.x, (int) current.origin.y,
  225837. (int) current.size.width, (int) current.size.height);
  225838. constrainer->checkBounds (pos, original,
  225839. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  225840. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  225841. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  225842. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  225843. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  225844. r.origin.x = pos.getX();
  225845. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.size.height - pos.getY();
  225846. r.size.width = pos.getWidth();
  225847. r.size.height = pos.getHeight();
  225848. }
  225849. return r;
  225850. }
  225851. void UIViewComponentPeer::setMinimised (bool shouldBeMinimised)
  225852. {
  225853. // xxx
  225854. }
  225855. bool UIViewComponentPeer::isMinimised() const
  225856. {
  225857. return false;
  225858. }
  225859. void UIViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  225860. {
  225861. if (! isSharedWindow)
  225862. {
  225863. Rectangle<int> r (lastNonFullscreenBounds);
  225864. setMinimised (false);
  225865. if (fullScreen != shouldBeFullScreen)
  225866. {
  225867. if (shouldBeFullScreen)
  225868. r = Desktop::getInstance().getMainMonitorArea();
  225869. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  225870. if (r != getComponent()->getBounds() && ! r.isEmpty())
  225871. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  225872. }
  225873. }
  225874. }
  225875. bool UIViewComponentPeer::isFullScreen() const
  225876. {
  225877. return fullScreen;
  225878. }
  225879. bool UIViewComponentPeer::contains (const Point<int>& position, bool trueIfInAChildWindow) const
  225880. {
  225881. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  225882. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  225883. return false;
  225884. CGPoint p;
  225885. p.x = (float) position.getX();
  225886. p.y = (float) position.getY();
  225887. UIView* v = [view hitTest: p withEvent: nil];
  225888. if (trueIfInAChildWindow)
  225889. return v != nil;
  225890. return v == view;
  225891. }
  225892. const BorderSize UIViewComponentPeer::getFrameSize() const
  225893. {
  225894. BorderSize b;
  225895. if (! isSharedWindow)
  225896. {
  225897. CGRect v = [view convertRect: [view frame] toView: nil];
  225898. CGRect w = [window frame];
  225899. b.setTop ((int) (w.size.height - (v.origin.y + v.size.height)));
  225900. b.setBottom ((int) v.origin.y);
  225901. b.setLeft ((int) v.origin.x);
  225902. b.setRight ((int) (w.size.width - (v.origin.x + v.size.width)));
  225903. }
  225904. return b;
  225905. }
  225906. bool UIViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  225907. {
  225908. if (! isSharedWindow)
  225909. window.windowLevel = alwaysOnTop ? UIWindowLevelAlert : UIWindowLevelNormal;
  225910. return true;
  225911. }
  225912. void UIViewComponentPeer::toFront (bool makeActiveWindow)
  225913. {
  225914. if (isSharedWindow)
  225915. [[view superview] bringSubviewToFront: view];
  225916. if (window != 0 && component->isVisible())
  225917. [window makeKeyAndVisible];
  225918. }
  225919. void UIViewComponentPeer::toBehind (ComponentPeer* other)
  225920. {
  225921. UIViewComponentPeer* const otherPeer = dynamic_cast <UIViewComponentPeer*> (other);
  225922. jassert (otherPeer != 0); // wrong type of window?
  225923. if (otherPeer != 0)
  225924. {
  225925. if (isSharedWindow)
  225926. {
  225927. [[view superview] insertSubview: view belowSubview: otherPeer->view];
  225928. }
  225929. else
  225930. {
  225931. jassertfalse; // don't know how to do this
  225932. }
  225933. }
  225934. }
  225935. void UIViewComponentPeer::setIcon (const Image& /*newIcon*/)
  225936. {
  225937. // to do..
  225938. }
  225939. void UIViewComponentPeer::handleTouches (UIEvent* event, const bool isDown, const bool isUp, bool isCancel)
  225940. {
  225941. NSArray* touches = [[event touchesForView: view] allObjects];
  225942. for (unsigned int i = 0; i < [touches count]; ++i)
  225943. {
  225944. UITouch* touch = [touches objectAtIndex: i];
  225945. CGPoint p = [touch locationInView: view];
  225946. const Point<int> pos ((int) p.x, (int) p.y);
  225947. juce_lastMousePos = pos + getScreenPosition();
  225948. const int64 time = getMouseTime (event);
  225949. int touchIndex = currentTouches.indexOf (touch);
  225950. if (touchIndex < 0)
  225951. {
  225952. touchIndex = currentTouches.size();
  225953. currentTouches.add (touch);
  225954. }
  225955. if (isDown)
  225956. {
  225957. currentModifiers = currentModifiers.withoutMouseButtons();
  225958. handleMouseEvent (touchIndex, pos, currentModifiers, time);
  225959. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
  225960. }
  225961. else if (isUp)
  225962. {
  225963. currentModifiers = currentModifiers.withoutMouseButtons();
  225964. currentTouches.remove (touchIndex);
  225965. }
  225966. if (isCancel)
  225967. currentTouches.clear();
  225968. handleMouseEvent (touchIndex, pos, currentModifiers, time);
  225969. }
  225970. }
  225971. static UIViewComponentPeer* currentlyFocusedPeer = 0;
  225972. void UIViewComponentPeer::viewFocusGain()
  225973. {
  225974. if (currentlyFocusedPeer != this)
  225975. {
  225976. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  225977. currentlyFocusedPeer->handleFocusLoss();
  225978. currentlyFocusedPeer = this;
  225979. handleFocusGain();
  225980. }
  225981. }
  225982. void UIViewComponentPeer::viewFocusLoss()
  225983. {
  225984. if (currentlyFocusedPeer == this)
  225985. {
  225986. currentlyFocusedPeer = 0;
  225987. handleFocusLoss();
  225988. }
  225989. }
  225990. void juce_HandleProcessFocusChange()
  225991. {
  225992. if (UIViewComponentPeer::isValidPeer (currentlyFocusedPeer))
  225993. {
  225994. if (Process::isForegroundProcess())
  225995. {
  225996. currentlyFocusedPeer->handleFocusGain();
  225997. ComponentPeer::bringModalComponentToFront();
  225998. }
  225999. else
  226000. {
  226001. currentlyFocusedPeer->handleFocusLoss();
  226002. // turn kiosk mode off if we lose focus..
  226003. Desktop::getInstance().setKioskModeComponent (0);
  226004. }
  226005. }
  226006. }
  226007. bool UIViewComponentPeer::isFocused() const
  226008. {
  226009. return isSharedWindow ? this == currentlyFocusedPeer
  226010. : (window != 0 && [window isKeyWindow]);
  226011. }
  226012. void UIViewComponentPeer::grabFocus()
  226013. {
  226014. if (window != 0)
  226015. {
  226016. [window makeKeyWindow];
  226017. viewFocusGain();
  226018. }
  226019. }
  226020. void UIViewComponentPeer::textInputRequired (const Point<int>&)
  226021. {
  226022. }
  226023. void UIViewComponentPeer::updateHiddenTextContent (TextInputTarget* target)
  226024. {
  226025. view->hiddenTextField.text = juceStringToNS (target->getTextInRange (Range<int> (0, target->getHighlightedRegion().getStart())));
  226026. }
  226027. BOOL UIViewComponentPeer::textFieldReplaceCharacters (const Range<int>& range, const String& text)
  226028. {
  226029. TextInputTarget* const target = findCurrentTextInputTarget();
  226030. if (target != 0)
  226031. {
  226032. const Range<int> currentSelection (target->getHighlightedRegion());
  226033. if (range.getLength() == 1 && text.isEmpty()) // (detect backspace)
  226034. if (currentSelection.isEmpty())
  226035. target->setHighlightedRegion (currentSelection.withStart (currentSelection.getStart() - 1));
  226036. target->insertTextAtCaret (text);
  226037. updateHiddenTextContent (target);
  226038. }
  226039. return NO;
  226040. }
  226041. BOOL UIViewComponentPeer::textFieldShouldClear()
  226042. {
  226043. TextInputTarget* const target = findCurrentTextInputTarget();
  226044. if (target != 0)
  226045. {
  226046. target->setHighlightedRegion (Range<int> (0, std::numeric_limits<int>::max()));
  226047. target->insertTextAtCaret (String::empty);
  226048. updateHiddenTextContent (target);
  226049. }
  226050. return YES;
  226051. }
  226052. BOOL UIViewComponentPeer::textFieldShouldReturn()
  226053. {
  226054. TextInputTarget* const target = findCurrentTextInputTarget();
  226055. if (target != 0)
  226056. {
  226057. target->insertTextAtCaret ("\n");
  226058. updateHiddenTextContent (target);
  226059. }
  226060. return YES;
  226061. }
  226062. void UIViewComponentPeer::globalFocusChanged (Component*)
  226063. {
  226064. TextInputTarget* const target = findCurrentTextInputTarget();
  226065. if (target != 0)
  226066. {
  226067. Component* comp = dynamic_cast<Component*> (target);
  226068. Point<int> pos (comp->relativePositionToOtherComponent (component, Point<int>()));
  226069. view->hiddenTextField.frame = CGRectMake (pos.getX(), pos.getY(), 0, 0);
  226070. updateHiddenTextContent (target);
  226071. [view->hiddenTextField becomeFirstResponder];
  226072. }
  226073. else
  226074. {
  226075. [view->hiddenTextField resignFirstResponder];
  226076. }
  226077. }
  226078. void UIViewComponentPeer::drawRect (CGRect r)
  226079. {
  226080. if (r.size.width < 1.0f || r.size.height < 1.0f)
  226081. return;
  226082. CGContextRef cg = UIGraphicsGetCurrentContext();
  226083. if (! component->isOpaque())
  226084. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  226085. CGContextConcatCTM (cg, CGAffineTransformMake (1, 0, 0, -1, 0, view.bounds.size.height));
  226086. CoreGraphicsContext g (cg, view.bounds.size.height);
  226087. insideDrawRect = true;
  226088. handlePaint (g);
  226089. insideDrawRect = false;
  226090. }
  226091. bool UIViewComponentPeer::canBecomeKeyWindow()
  226092. {
  226093. return (getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowIgnoresKeyPresses) == 0;
  226094. }
  226095. bool UIViewComponentPeer::windowShouldClose()
  226096. {
  226097. if (! isValidPeer (this))
  226098. return YES;
  226099. handleUserClosingWindow();
  226100. return NO;
  226101. }
  226102. void UIViewComponentPeer::redirectMovedOrResized()
  226103. {
  226104. handleMovedOrResized();
  226105. }
  226106. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  226107. {
  226108. }
  226109. class AsyncRepaintMessage : public CallbackMessage
  226110. {
  226111. public:
  226112. UIViewComponentPeer* const peer;
  226113. const Rectangle<int> rect;
  226114. AsyncRepaintMessage (UIViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  226115. : peer (peer_), rect (rect_)
  226116. {
  226117. }
  226118. void messageCallback()
  226119. {
  226120. if (ComponentPeer::isValidPeer (peer))
  226121. peer->repaint (rect);
  226122. }
  226123. };
  226124. void UIViewComponentPeer::repaint (const Rectangle<int>& area)
  226125. {
  226126. if (insideDrawRect || ! MessageManager::getInstance()->isThisTheMessageThread())
  226127. {
  226128. (new AsyncRepaintMessage (this, area))->post();
  226129. }
  226130. else
  226131. {
  226132. [view setNeedsDisplayInRect: CGRectMake ((float) area.getX(), (float) area.getY(),
  226133. (float) area.getWidth(), (float) area.getHeight())];
  226134. }
  226135. }
  226136. void UIViewComponentPeer::performAnyPendingRepaintsNow()
  226137. {
  226138. }
  226139. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  226140. {
  226141. return new UIViewComponentPeer (this, styleFlags, (UIView*) windowToAttachTo);
  226142. }
  226143. const Image juce_createIconForFile (const File& file)
  226144. {
  226145. return Image();
  226146. }
  226147. void Desktop::createMouseInputSources()
  226148. {
  226149. for (int i = 0; i < 10; ++i)
  226150. mouseSources.add (new MouseInputSource (i, false));
  226151. }
  226152. bool Desktop::canUseSemiTransparentWindows() throw()
  226153. {
  226154. return true;
  226155. }
  226156. const Point<int> Desktop::getMousePosition()
  226157. {
  226158. return juce_lastMousePos;
  226159. }
  226160. void Desktop::setMousePosition (const Point<int>&)
  226161. {
  226162. }
  226163. const int KeyPress::spaceKey = ' ';
  226164. const int KeyPress::returnKey = 0x0d;
  226165. const int KeyPress::escapeKey = 0x1b;
  226166. const int KeyPress::backspaceKey = 0x7f;
  226167. const int KeyPress::leftKey = 0x1000;
  226168. const int KeyPress::rightKey = 0x1001;
  226169. const int KeyPress::upKey = 0x1002;
  226170. const int KeyPress::downKey = 0x1003;
  226171. const int KeyPress::pageUpKey = 0x1004;
  226172. const int KeyPress::pageDownKey = 0x1005;
  226173. const int KeyPress::endKey = 0x1006;
  226174. const int KeyPress::homeKey = 0x1007;
  226175. const int KeyPress::deleteKey = 0x1008;
  226176. const int KeyPress::insertKey = -1;
  226177. const int KeyPress::tabKey = 9;
  226178. const int KeyPress::F1Key = 0x2001;
  226179. const int KeyPress::F2Key = 0x2002;
  226180. const int KeyPress::F3Key = 0x2003;
  226181. const int KeyPress::F4Key = 0x2004;
  226182. const int KeyPress::F5Key = 0x2005;
  226183. const int KeyPress::F6Key = 0x2006;
  226184. const int KeyPress::F7Key = 0x2007;
  226185. const int KeyPress::F8Key = 0x2008;
  226186. const int KeyPress::F9Key = 0x2009;
  226187. const int KeyPress::F10Key = 0x200a;
  226188. const int KeyPress::F11Key = 0x200b;
  226189. const int KeyPress::F12Key = 0x200c;
  226190. const int KeyPress::F13Key = 0x200d;
  226191. const int KeyPress::F14Key = 0x200e;
  226192. const int KeyPress::F15Key = 0x200f;
  226193. const int KeyPress::F16Key = 0x2010;
  226194. const int KeyPress::numberPad0 = 0x30020;
  226195. const int KeyPress::numberPad1 = 0x30021;
  226196. const int KeyPress::numberPad2 = 0x30022;
  226197. const int KeyPress::numberPad3 = 0x30023;
  226198. const int KeyPress::numberPad4 = 0x30024;
  226199. const int KeyPress::numberPad5 = 0x30025;
  226200. const int KeyPress::numberPad6 = 0x30026;
  226201. const int KeyPress::numberPad7 = 0x30027;
  226202. const int KeyPress::numberPad8 = 0x30028;
  226203. const int KeyPress::numberPad9 = 0x30029;
  226204. const int KeyPress::numberPadAdd = 0x3002a;
  226205. const int KeyPress::numberPadSubtract = 0x3002b;
  226206. const int KeyPress::numberPadMultiply = 0x3002c;
  226207. const int KeyPress::numberPadDivide = 0x3002d;
  226208. const int KeyPress::numberPadSeparator = 0x3002e;
  226209. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  226210. const int KeyPress::numberPadEquals = 0x30030;
  226211. const int KeyPress::numberPadDelete = 0x30031;
  226212. const int KeyPress::playKey = 0x30000;
  226213. const int KeyPress::stopKey = 0x30001;
  226214. const int KeyPress::fastForwardKey = 0x30002;
  226215. const int KeyPress::rewindKey = 0x30003;
  226216. #endif
  226217. /*** End of inlined file: juce_iphone_UIViewComponentPeer.mm ***/
  226218. /*** Start of inlined file: juce_iphone_MessageManager.mm ***/
  226219. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226220. // compiled on its own).
  226221. #if JUCE_INCLUDED_FILE
  226222. struct CallbackMessagePayload
  226223. {
  226224. MessageCallbackFunction* function;
  226225. void* parameter;
  226226. void* volatile result;
  226227. bool volatile hasBeenExecuted;
  226228. };
  226229. END_JUCE_NAMESPACE
  226230. @interface JuceCustomMessageHandler : NSObject
  226231. {
  226232. }
  226233. - (void) performCallback: (id) info;
  226234. @end
  226235. @implementation JuceCustomMessageHandler
  226236. - (void) performCallback: (id) info
  226237. {
  226238. if ([info isKindOfClass: [NSData class]])
  226239. {
  226240. JUCE_NAMESPACE::CallbackMessagePayload* pl = (JUCE_NAMESPACE::CallbackMessagePayload*) [((NSData*) info) bytes];
  226241. if (pl != 0)
  226242. {
  226243. pl->result = (*pl->function) (pl->parameter);
  226244. pl->hasBeenExecuted = true;
  226245. }
  226246. }
  226247. else
  226248. {
  226249. jassertfalse; // should never get here!
  226250. }
  226251. }
  226252. @end
  226253. BEGIN_JUCE_NAMESPACE
  226254. void MessageManager::runDispatchLoop()
  226255. {
  226256. jassert (isThisTheMessageThread()); // must only be called by the message thread
  226257. runDispatchLoopUntil (-1);
  226258. }
  226259. void MessageManager::stopDispatchLoop()
  226260. {
  226261. exit (0); // iPhone apps get no mercy..
  226262. }
  226263. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  226264. {
  226265. const ScopedAutoReleasePool pool;
  226266. jassert (isThisTheMessageThread()); // must only be called by the message thread
  226267. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  226268. NSDate* endDate = [NSDate dateWithTimeIntervalSinceNow: millisecondsToRunFor * 0.001];
  226269. while (! quitMessagePosted)
  226270. {
  226271. const ScopedAutoReleasePool pool;
  226272. [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode
  226273. beforeDate: endDate];
  226274. if (millisecondsToRunFor >= 0 && Time::getMillisecondCounter() >= endTime)
  226275. break;
  226276. }
  226277. return ! quitMessagePosted;
  226278. }
  226279. static CFRunLoopRef runLoop = 0;
  226280. static CFRunLoopSourceRef runLoopSource = 0;
  226281. static Array <void*, CriticalSection>* pendingMessages = 0;
  226282. static JuceCustomMessageHandler* juceCustomMessageHandler = 0;
  226283. static void runLoopSourceCallback (void*)
  226284. {
  226285. if (pendingMessages != 0)
  226286. {
  226287. int numDispatched = 0;
  226288. do
  226289. {
  226290. void* const nextMessage = pendingMessages->remove (0);
  226291. if (nextMessage == 0)
  226292. return;
  226293. const ScopedAutoReleasePool pool;
  226294. MessageManager::getInstance()->deliverMessage (nextMessage);
  226295. } while (++numDispatched <= 4);
  226296. CFRunLoopSourceSignal (runLoopSource);
  226297. CFRunLoopWakeUp (runLoop);
  226298. }
  226299. }
  226300. void MessageManager::doPlatformSpecificInitialisation()
  226301. {
  226302. pendingMessages = new Array <void*, CriticalSection>();
  226303. runLoop = CFRunLoopGetCurrent();
  226304. CFRunLoopSourceContext sourceContext;
  226305. zerostruct (sourceContext);
  226306. sourceContext.perform = runLoopSourceCallback;
  226307. runLoopSource = CFRunLoopSourceCreate (kCFAllocatorDefault, 1, &sourceContext);
  226308. CFRunLoopAddSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  226309. if (juceCustomMessageHandler == 0)
  226310. juceCustomMessageHandler = [[JuceCustomMessageHandler alloc] init];
  226311. }
  226312. void MessageManager::doPlatformSpecificShutdown()
  226313. {
  226314. CFRunLoopSourceInvalidate (runLoopSource);
  226315. CFRelease (runLoopSource);
  226316. runLoopSource = 0;
  226317. if (pendingMessages != 0)
  226318. {
  226319. while (pendingMessages->size() > 0)
  226320. delete ((Message*) pendingMessages->remove(0));
  226321. deleteAndZero (pendingMessages);
  226322. }
  226323. if (juceCustomMessageHandler != 0)
  226324. {
  226325. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceCustomMessageHandler];
  226326. [juceCustomMessageHandler release];
  226327. juceCustomMessageHandler = 0;
  226328. }
  226329. }
  226330. bool juce_postMessageToSystemQueue (void* message)
  226331. {
  226332. if (pendingMessages != 0)
  226333. {
  226334. pendingMessages->add (message);
  226335. CFRunLoopSourceSignal (runLoopSource);
  226336. CFRunLoopWakeUp (runLoop);
  226337. }
  226338. return true;
  226339. }
  226340. void MessageManager::broadcastMessage (const String& value) throw()
  226341. {
  226342. }
  226343. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  226344. void* data)
  226345. {
  226346. if (isThisTheMessageThread())
  226347. {
  226348. return (*callback) (data);
  226349. }
  226350. else
  226351. {
  226352. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  226353. // deadlock because the message manager is blocked from running, so can never
  226354. // call your function..
  226355. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  226356. const ScopedAutoReleasePool pool;
  226357. CallbackMessagePayload cmp;
  226358. cmp.function = callback;
  226359. cmp.parameter = data;
  226360. cmp.result = 0;
  226361. cmp.hasBeenExecuted = false;
  226362. [juceCustomMessageHandler performSelectorOnMainThread: @selector (performCallback:)
  226363. withObject: [NSData dataWithBytesNoCopy: &cmp
  226364. length: sizeof (cmp)
  226365. freeWhenDone: NO]
  226366. waitUntilDone: YES];
  226367. return cmp.result;
  226368. }
  226369. }
  226370. #endif
  226371. /*** End of inlined file: juce_iphone_MessageManager.mm ***/
  226372. /*** Start of inlined file: juce_mac_FileChooser.mm ***/
  226373. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226374. // compiled on its own).
  226375. #if JUCE_INCLUDED_FILE
  226376. #if JUCE_MAC
  226377. END_JUCE_NAMESPACE
  226378. using namespace JUCE_NAMESPACE;
  226379. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  226380. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  226381. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  226382. #else
  226383. @interface JuceFileChooserDelegate : NSObject
  226384. #endif
  226385. {
  226386. StringArray* filters;
  226387. }
  226388. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  226389. - (void) dealloc;
  226390. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  226391. @end
  226392. @implementation JuceFileChooserDelegate
  226393. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  226394. {
  226395. [super init];
  226396. filters = filters_;
  226397. return self;
  226398. }
  226399. - (void) dealloc
  226400. {
  226401. delete filters;
  226402. [super dealloc];
  226403. }
  226404. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  226405. {
  226406. (void) sender;
  226407. const File f (nsStringToJuce (filename));
  226408. for (int i = filters->size(); --i >= 0;)
  226409. if (f.getFileName().matchesWildcard ((*filters)[i], true))
  226410. return true;
  226411. return f.isDirectory();
  226412. }
  226413. @end
  226414. BEGIN_JUCE_NAMESPACE
  226415. void FileChooser::showPlatformDialog (Array<File>& results,
  226416. const String& title,
  226417. const File& currentFileOrDirectory,
  226418. const String& filter,
  226419. bool selectsDirectory,
  226420. bool selectsFiles,
  226421. bool isSaveDialogue,
  226422. bool warnAboutOverwritingExistingFiles,
  226423. bool selectMultipleFiles,
  226424. FilePreviewComponent* extraInfoComponent)
  226425. {
  226426. const ScopedAutoReleasePool pool;
  226427. StringArray* filters = new StringArray();
  226428. filters->addTokens (filter.replaceCharacters (",:", ";;"), ";", String::empty);
  226429. filters->trim();
  226430. filters->removeEmptyStrings();
  226431. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  226432. [delegate autorelease];
  226433. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  226434. : [NSOpenPanel openPanel];
  226435. [panel setTitle: juceStringToNS (title)];
  226436. if (! isSaveDialogue)
  226437. {
  226438. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  226439. [openPanel setCanChooseDirectories: selectsDirectory];
  226440. [openPanel setCanChooseFiles: selectsFiles];
  226441. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  226442. }
  226443. [panel setDelegate: delegate];
  226444. if (isSaveDialogue || selectsDirectory)
  226445. [panel setCanCreateDirectories: YES];
  226446. String directory, filename;
  226447. if (currentFileOrDirectory.isDirectory())
  226448. {
  226449. directory = currentFileOrDirectory.getFullPathName();
  226450. }
  226451. else
  226452. {
  226453. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  226454. filename = currentFileOrDirectory.getFileName();
  226455. }
  226456. if ([panel runModalForDirectory: juceStringToNS (directory)
  226457. file: juceStringToNS (filename)]
  226458. == NSOKButton)
  226459. {
  226460. if (isSaveDialogue)
  226461. {
  226462. results.add (File (nsStringToJuce ([panel filename])));
  226463. }
  226464. else
  226465. {
  226466. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  226467. NSArray* urls = [openPanel filenames];
  226468. for (unsigned int i = 0; i < [urls count]; ++i)
  226469. {
  226470. NSString* f = [urls objectAtIndex: i];
  226471. results.add (File (nsStringToJuce (f)));
  226472. }
  226473. }
  226474. }
  226475. [panel setDelegate: nil];
  226476. }
  226477. #else
  226478. void FileChooser::showPlatformDialog (Array<File>& results,
  226479. const String& title,
  226480. const File& currentFileOrDirectory,
  226481. const String& filter,
  226482. bool selectsDirectory,
  226483. bool selectsFiles,
  226484. bool isSaveDialogue,
  226485. bool warnAboutOverwritingExistingFiles,
  226486. bool selectMultipleFiles,
  226487. FilePreviewComponent* extraInfoComponent)
  226488. {
  226489. const ScopedAutoReleasePool pool;
  226490. jassertfalse; //xxx to do
  226491. }
  226492. #endif
  226493. #endif
  226494. /*** End of inlined file: juce_mac_FileChooser.mm ***/
  226495. /*** Start of inlined file: juce_mac_OpenGLComponent.mm ***/
  226496. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226497. // compiled on its own).
  226498. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  226499. #if JUCE_MAC
  226500. END_JUCE_NAMESPACE
  226501. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  226502. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  226503. {
  226504. CriticalSection* contextLock;
  226505. bool needsUpdate;
  226506. }
  226507. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  226508. - (bool) makeActive;
  226509. - (void) makeInactive;
  226510. - (void) reshape;
  226511. @end
  226512. @implementation ThreadSafeNSOpenGLView
  226513. - (id) initWithFrame: (NSRect) frameRect
  226514. pixelFormat: (NSOpenGLPixelFormat*) format
  226515. {
  226516. contextLock = new CriticalSection();
  226517. self = [super initWithFrame: frameRect pixelFormat: format];
  226518. if (self != nil)
  226519. [[NSNotificationCenter defaultCenter] addObserver: self
  226520. selector: @selector (_surfaceNeedsUpdate:)
  226521. name: NSViewGlobalFrameDidChangeNotification
  226522. object: self];
  226523. return self;
  226524. }
  226525. - (void) dealloc
  226526. {
  226527. [[NSNotificationCenter defaultCenter] removeObserver: self];
  226528. delete contextLock;
  226529. [super dealloc];
  226530. }
  226531. - (bool) makeActive
  226532. {
  226533. const ScopedLock sl (*contextLock);
  226534. if ([self openGLContext] == 0)
  226535. return false;
  226536. [[self openGLContext] makeCurrentContext];
  226537. if (needsUpdate)
  226538. {
  226539. [super update];
  226540. needsUpdate = false;
  226541. }
  226542. return true;
  226543. }
  226544. - (void) makeInactive
  226545. {
  226546. const ScopedLock sl (*contextLock);
  226547. [NSOpenGLContext clearCurrentContext];
  226548. }
  226549. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  226550. {
  226551. const ScopedLock sl (*contextLock);
  226552. needsUpdate = true;
  226553. }
  226554. - (void) update
  226555. {
  226556. const ScopedLock sl (*contextLock);
  226557. needsUpdate = true;
  226558. }
  226559. - (void) reshape
  226560. {
  226561. const ScopedLock sl (*contextLock);
  226562. needsUpdate = true;
  226563. }
  226564. @end
  226565. BEGIN_JUCE_NAMESPACE
  226566. class WindowedGLContext : public OpenGLContext
  226567. {
  226568. public:
  226569. WindowedGLContext (Component* const component,
  226570. const OpenGLPixelFormat& pixelFormat_,
  226571. NSOpenGLContext* sharedContext)
  226572. : renderContext (0),
  226573. pixelFormat (pixelFormat_)
  226574. {
  226575. jassert (component != 0);
  226576. NSOpenGLPixelFormatAttribute attribs [64];
  226577. int n = 0;
  226578. attribs[n++] = NSOpenGLPFADoubleBuffer;
  226579. attribs[n++] = NSOpenGLPFAAccelerated;
  226580. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  226581. attribs[n++] = NSOpenGLPFAColorSize;
  226582. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  226583. pixelFormat.greenBits,
  226584. pixelFormat.blueBits);
  226585. attribs[n++] = NSOpenGLPFAAlphaSize;
  226586. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  226587. attribs[n++] = NSOpenGLPFADepthSize;
  226588. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  226589. attribs[n++] = NSOpenGLPFAStencilSize;
  226590. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  226591. attribs[n++] = NSOpenGLPFAAccumSize;
  226592. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  226593. pixelFormat.accumulationBufferGreenBits,
  226594. pixelFormat.accumulationBufferBlueBits,
  226595. pixelFormat.accumulationBufferAlphaBits);
  226596. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  226597. attribs[n++] = NSOpenGLPFASampleBuffers;
  226598. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  226599. attribs[n++] = NSOpenGLPFAClosestPolicy;
  226600. attribs[n++] = NSOpenGLPFANoRecovery;
  226601. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  226602. NSOpenGLPixelFormat* format
  226603. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  226604. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  226605. pixelFormat: format];
  226606. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  226607. shareContext: sharedContext] autorelease];
  226608. const GLint swapInterval = 1;
  226609. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  226610. [view setOpenGLContext: renderContext];
  226611. [renderContext setView: view];
  226612. [format release];
  226613. viewHolder = new NSViewComponentInternal (view, component);
  226614. }
  226615. ~WindowedGLContext()
  226616. {
  226617. makeInactive();
  226618. [renderContext clearDrawable];
  226619. viewHolder = 0;
  226620. }
  226621. bool makeActive() const throw()
  226622. {
  226623. jassert (renderContext != 0);
  226624. [view makeActive];
  226625. return isActive();
  226626. }
  226627. bool makeInactive() const throw()
  226628. {
  226629. [view makeInactive];
  226630. return true;
  226631. }
  226632. bool isActive() const throw()
  226633. {
  226634. return [NSOpenGLContext currentContext] == renderContext;
  226635. }
  226636. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  226637. void* getRawContext() const throw() { return renderContext; }
  226638. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  226639. {
  226640. }
  226641. void swapBuffers()
  226642. {
  226643. [renderContext flushBuffer];
  226644. }
  226645. bool setSwapInterval (const int numFramesPerSwap)
  226646. {
  226647. [renderContext setValues: (const GLint*) &numFramesPerSwap
  226648. forParameter: NSOpenGLCPSwapInterval];
  226649. return true;
  226650. }
  226651. int getSwapInterval() const
  226652. {
  226653. GLint numFrames = 0;
  226654. [renderContext getValues: &numFrames
  226655. forParameter: NSOpenGLCPSwapInterval];
  226656. return numFrames;
  226657. }
  226658. void repaint()
  226659. {
  226660. // we need to invalidate the juce view that holds this gl view, to make it
  226661. // cause a repaint callback
  226662. NSView* v = (NSView*) viewHolder->view;
  226663. NSRect r = [v frame];
  226664. // bit of a bodge here.. if we only invalidate the area of the gl component,
  226665. // it's completely covered by the NSOpenGLView, so the OS throws away the
  226666. // repaint message, thus never causing our paint() callback, and never repainting
  226667. // the comp. So invalidating just a little bit around the edge helps..
  226668. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  226669. }
  226670. void* getNativeWindowHandle() const { return viewHolder->view; }
  226671. juce_UseDebuggingNewOperator
  226672. NSOpenGLContext* renderContext;
  226673. ThreadSafeNSOpenGLView* view;
  226674. private:
  226675. OpenGLPixelFormat pixelFormat;
  226676. ScopedPointer <NSViewComponentInternal> viewHolder;
  226677. WindowedGLContext (const WindowedGLContext&);
  226678. WindowedGLContext& operator= (const WindowedGLContext&);
  226679. };
  226680. OpenGLContext* OpenGLComponent::createContext()
  226681. {
  226682. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  226683. contextToShareListsWith != 0 ? (NSOpenGLContext*) contextToShareListsWith->getRawContext() : 0));
  226684. return (c->renderContext != 0) ? c.release() : 0;
  226685. }
  226686. void* OpenGLComponent::getNativeWindowHandle() const
  226687. {
  226688. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle()
  226689. : 0;
  226690. }
  226691. void juce_glViewport (const int w, const int h)
  226692. {
  226693. glViewport (0, 0, w, h);
  226694. }
  226695. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  226696. OwnedArray <OpenGLPixelFormat>& results)
  226697. {
  226698. /* GLint attribs [64];
  226699. int n = 0;
  226700. attribs[n++] = AGL_RGBA;
  226701. attribs[n++] = AGL_DOUBLEBUFFER;
  226702. attribs[n++] = AGL_ACCELERATED;
  226703. attribs[n++] = AGL_NO_RECOVERY;
  226704. attribs[n++] = AGL_NONE;
  226705. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  226706. while (p != 0)
  226707. {
  226708. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  226709. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  226710. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  226711. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  226712. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  226713. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  226714. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  226715. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  226716. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  226717. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  226718. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  226719. results.add (pf);
  226720. p = aglNextPixelFormat (p);
  226721. }*/
  226722. //jassertfalse //xxx can't see how you do this in cocoa!
  226723. }
  226724. #else
  226725. END_JUCE_NAMESPACE
  226726. @interface JuceGLView : UIView
  226727. {
  226728. }
  226729. + (Class) layerClass;
  226730. @end
  226731. @implementation JuceGLView
  226732. + (Class) layerClass
  226733. {
  226734. return [CAEAGLLayer class];
  226735. }
  226736. @end
  226737. BEGIN_JUCE_NAMESPACE
  226738. class GLESContext : public OpenGLContext
  226739. {
  226740. public:
  226741. GLESContext (UIViewComponentPeer* peer,
  226742. Component* const component_,
  226743. const OpenGLPixelFormat& pixelFormat_,
  226744. const GLESContext* const sharedContext,
  226745. NSUInteger apiType)
  226746. : component (component_), pixelFormat (pixelFormat_), glLayer (0), context (0),
  226747. useDepthBuffer (pixelFormat_.depthBufferBits > 0), frameBufferHandle (0), colorBufferHandle (0),
  226748. depthBufferHandle (0), lastWidth (0), lastHeight (0)
  226749. {
  226750. view = [[JuceGLView alloc] initWithFrame: CGRectMake (0, 0, 64, 64)];
  226751. view.opaque = YES;
  226752. view.hidden = NO;
  226753. view.backgroundColor = [UIColor blackColor];
  226754. view.userInteractionEnabled = NO;
  226755. glLayer = (CAEAGLLayer*) [view layer];
  226756. [peer->view addSubview: view];
  226757. if (sharedContext != 0)
  226758. context = [[EAGLContext alloc] initWithAPI: apiType
  226759. sharegroup: [sharedContext->context sharegroup]];
  226760. else
  226761. context = [[EAGLContext alloc] initWithAPI: apiType];
  226762. createGLBuffers();
  226763. }
  226764. ~GLESContext()
  226765. {
  226766. makeInactive();
  226767. [context release];
  226768. [view removeFromSuperview];
  226769. [view release];
  226770. freeGLBuffers();
  226771. }
  226772. bool makeActive() const throw()
  226773. {
  226774. jassert (context != 0);
  226775. [EAGLContext setCurrentContext: context];
  226776. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  226777. return true;
  226778. }
  226779. void swapBuffers()
  226780. {
  226781. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  226782. [context presentRenderbuffer: GL_RENDERBUFFER_OES];
  226783. }
  226784. bool makeInactive() const throw()
  226785. {
  226786. return [EAGLContext setCurrentContext: nil];
  226787. }
  226788. bool isActive() const throw()
  226789. {
  226790. return [EAGLContext currentContext] == context;
  226791. }
  226792. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  226793. void* getRawContext() const throw() { return glLayer; }
  226794. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  226795. {
  226796. view.frame = CGRectMake ((CGFloat) x, (CGFloat) y, (CGFloat) w, (CGFloat) h);
  226797. if (lastWidth != w || lastHeight != h)
  226798. {
  226799. lastWidth = w;
  226800. lastHeight = h;
  226801. freeGLBuffers();
  226802. createGLBuffers();
  226803. }
  226804. }
  226805. bool setSwapInterval (const int numFramesPerSwap)
  226806. {
  226807. numFrames = numFramesPerSwap;
  226808. return true;
  226809. }
  226810. int getSwapInterval() const
  226811. {
  226812. return numFrames;
  226813. }
  226814. void repaint()
  226815. {
  226816. }
  226817. void createGLBuffers()
  226818. {
  226819. makeActive();
  226820. glGenFramebuffersOES (1, &frameBufferHandle);
  226821. glGenRenderbuffersOES (1, &colorBufferHandle);
  226822. glGenRenderbuffersOES (1, &depthBufferHandle);
  226823. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  226824. [context renderbufferStorage: GL_RENDERBUFFER_OES fromDrawable: glLayer];
  226825. GLint width, height;
  226826. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &width);
  226827. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &height);
  226828. if (useDepthBuffer)
  226829. {
  226830. glBindRenderbufferOES (GL_RENDERBUFFER_OES, depthBufferHandle);
  226831. glRenderbufferStorageOES (GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height);
  226832. }
  226833. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  226834. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  226835. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorBufferHandle);
  226836. if (useDepthBuffer)
  226837. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBufferHandle);
  226838. jassert (glCheckFramebufferStatusOES (GL_FRAMEBUFFER_OES) == GL_FRAMEBUFFER_COMPLETE_OES);
  226839. }
  226840. void freeGLBuffers()
  226841. {
  226842. if (frameBufferHandle != 0)
  226843. {
  226844. glDeleteFramebuffersOES (1, &frameBufferHandle);
  226845. frameBufferHandle = 0;
  226846. }
  226847. if (colorBufferHandle != 0)
  226848. {
  226849. glDeleteRenderbuffersOES (1, &colorBufferHandle);
  226850. colorBufferHandle = 0;
  226851. }
  226852. if (depthBufferHandle != 0)
  226853. {
  226854. glDeleteRenderbuffersOES (1, &depthBufferHandle);
  226855. depthBufferHandle = 0;
  226856. }
  226857. }
  226858. juce_UseDebuggingNewOperator
  226859. private:
  226860. Component::SafePointer<Component> component;
  226861. OpenGLPixelFormat pixelFormat;
  226862. JuceGLView* view;
  226863. CAEAGLLayer* glLayer;
  226864. EAGLContext* context;
  226865. bool useDepthBuffer;
  226866. GLuint frameBufferHandle, colorBufferHandle, depthBufferHandle;
  226867. int numFrames;
  226868. int lastWidth, lastHeight;
  226869. GLESContext (const GLESContext&);
  226870. GLESContext& operator= (const GLESContext&);
  226871. };
  226872. OpenGLContext* OpenGLComponent::createContext()
  226873. {
  226874. ScopedAutoReleasePool pool;
  226875. UIViewComponentPeer* peer = dynamic_cast <UIViewComponentPeer*> (getPeer());
  226876. if (peer != 0)
  226877. return new GLESContext (peer, this, preferredPixelFormat,
  226878. dynamic_cast <const GLESContext*> (contextToShareListsWith),
  226879. type == openGLES2 ? kEAGLRenderingAPIOpenGLES2 : kEAGLRenderingAPIOpenGLES1);
  226880. return 0;
  226881. }
  226882. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  226883. OwnedArray <OpenGLPixelFormat>& /*results*/)
  226884. {
  226885. }
  226886. void juce_glViewport (const int w, const int h)
  226887. {
  226888. glViewport (0, 0, w, h);
  226889. }
  226890. #endif
  226891. #endif
  226892. /*** End of inlined file: juce_mac_OpenGLComponent.mm ***/
  226893. /*** Start of inlined file: juce_mac_MouseCursor.mm ***/
  226894. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226895. // compiled on its own).
  226896. #if JUCE_INCLUDED_FILE
  226897. #if JUCE_MAC
  226898. namespace MouseCursorHelpers
  226899. {
  226900. static void* createFromImage (const Image& image, float hotspotX, float hotspotY)
  226901. {
  226902. NSImage* im = CoreGraphicsImage::createNSImage (image);
  226903. NSCursor* c = [[NSCursor alloc] initWithImage: im
  226904. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  226905. [im release];
  226906. return c;
  226907. }
  226908. static void* fromWebKitFile (const char* filename, float hx, float hy)
  226909. {
  226910. FileInputStream fileStream (String ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources/") + filename);
  226911. BufferedInputStream buf (&fileStream, 4096, false);
  226912. PNGImageFormat pngFormat;
  226913. Image im (pngFormat.decodeImage (buf));
  226914. if (im.isValid())
  226915. return createFromImage (im, hx * im.getWidth(), hy * im.getHeight());
  226916. jassertfalse;
  226917. return 0;
  226918. }
  226919. }
  226920. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  226921. {
  226922. return MouseCursorHelpers::createFromImage (image, (float) hotspotX, (float) hotspotY);
  226923. }
  226924. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  226925. {
  226926. const ScopedAutoReleasePool pool;
  226927. NSCursor* c = 0;
  226928. switch (type)
  226929. {
  226930. case NormalCursor: c = [NSCursor arrowCursor]; break;
  226931. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 8, 8, true), 0, 0);
  226932. case DraggingHandCursor: c = [NSCursor openHandCursor]; break;
  226933. case WaitCursor: c = [NSCursor arrowCursor]; break; // avoid this on the mac, let the OS provide the beachball
  226934. case IBeamCursor: c = [NSCursor IBeamCursor]; break;
  226935. case PointingHandCursor: c = [NSCursor pointingHandCursor]; break;
  226936. case LeftRightResizeCursor: c = [NSCursor resizeLeftRightCursor]; break;
  226937. case LeftEdgeResizeCursor: c = [NSCursor resizeLeftCursor]; break;
  226938. case RightEdgeResizeCursor: c = [NSCursor resizeRightCursor]; break;
  226939. case CrosshairCursor: c = [NSCursor crosshairCursor]; break;
  226940. case CopyingCursor: return MouseCursorHelpers::fromWebKitFile ("copyCursor.png", 0, 0);
  226941. case UpDownResizeCursor:
  226942. case TopEdgeResizeCursor:
  226943. case BottomEdgeResizeCursor:
  226944. return MouseCursorHelpers::fromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  226945. case TopLeftCornerResizeCursor:
  226946. case BottomRightCornerResizeCursor:
  226947. return MouseCursorHelpers::fromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  226948. case TopRightCornerResizeCursor:
  226949. case BottomLeftCornerResizeCursor:
  226950. return MouseCursorHelpers::fromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  226951. case UpDownLeftRightResizeCursor:
  226952. return MouseCursorHelpers::fromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  226953. default:
  226954. jassertfalse;
  226955. break;
  226956. }
  226957. [c retain];
  226958. return c;
  226959. }
  226960. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool /*isStandard*/)
  226961. {
  226962. [((NSCursor*) cursorHandle) release];
  226963. }
  226964. void MouseCursor::showInAllWindows() const
  226965. {
  226966. showInWindow (0);
  226967. }
  226968. void MouseCursor::showInWindow (ComponentPeer*) const
  226969. {
  226970. [((NSCursor*) getHandle()) set];
  226971. }
  226972. #else
  226973. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) { return 0; }
  226974. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type) { return 0; }
  226975. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard) {}
  226976. void MouseCursor::showInAllWindows() const {}
  226977. void MouseCursor::showInWindow (ComponentPeer*) const {}
  226978. #endif
  226979. #endif
  226980. /*** End of inlined file: juce_mac_MouseCursor.mm ***/
  226981. /*** Start of inlined file: juce_mac_WebBrowserComponent.mm ***/
  226982. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226983. // compiled on its own).
  226984. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  226985. #if JUCE_MAC
  226986. END_JUCE_NAMESPACE
  226987. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  226988. @interface DownloadClickDetector : NSObject
  226989. {
  226990. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  226991. }
  226992. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  226993. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  226994. request: (NSURLRequest*) request
  226995. frame: (WebFrame*) frame
  226996. decisionListener: (id<WebPolicyDecisionListener>) listener;
  226997. @end
  226998. @implementation DownloadClickDetector
  226999. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  227000. {
  227001. [super init];
  227002. ownerComponent = ownerComponent_;
  227003. return self;
  227004. }
  227005. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  227006. request: (NSURLRequest*) request
  227007. frame: (WebFrame*) frame
  227008. decisionListener: (id <WebPolicyDecisionListener>) listener
  227009. {
  227010. (void) sender;
  227011. (void) request;
  227012. (void) frame;
  227013. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  227014. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  227015. [listener use];
  227016. else
  227017. [listener ignore];
  227018. }
  227019. @end
  227020. BEGIN_JUCE_NAMESPACE
  227021. class WebBrowserComponentInternal : public NSViewComponent
  227022. {
  227023. public:
  227024. WebBrowserComponentInternal (WebBrowserComponent* owner)
  227025. {
  227026. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  227027. frameName: @""
  227028. groupName: @""];
  227029. setView (webView);
  227030. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  227031. [webView setPolicyDelegate: clickListener];
  227032. }
  227033. ~WebBrowserComponentInternal()
  227034. {
  227035. [webView setPolicyDelegate: nil];
  227036. [clickListener release];
  227037. setView (0);
  227038. }
  227039. void goToURL (const String& url,
  227040. const StringArray* headers,
  227041. const MemoryBlock* postData)
  227042. {
  227043. NSMutableURLRequest* r
  227044. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  227045. cachePolicy: NSURLRequestUseProtocolCachePolicy
  227046. timeoutInterval: 30.0];
  227047. if (postData != 0 && postData->getSize() > 0)
  227048. {
  227049. [r setHTTPMethod: @"POST"];
  227050. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  227051. length: postData->getSize()]];
  227052. }
  227053. if (headers != 0)
  227054. {
  227055. for (int i = 0; i < headers->size(); ++i)
  227056. {
  227057. const String headerName ((*headers)[i].upToFirstOccurrenceOf (":", false, false).trim());
  227058. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (":", false, false).trim());
  227059. [r setValue: juceStringToNS (headerValue)
  227060. forHTTPHeaderField: juceStringToNS (headerName)];
  227061. }
  227062. }
  227063. stop();
  227064. [[webView mainFrame] loadRequest: r];
  227065. }
  227066. void goBack()
  227067. {
  227068. [webView goBack];
  227069. }
  227070. void goForward()
  227071. {
  227072. [webView goForward];
  227073. }
  227074. void stop()
  227075. {
  227076. [webView stopLoading: nil];
  227077. }
  227078. void refresh()
  227079. {
  227080. [webView reload: nil];
  227081. }
  227082. private:
  227083. WebView* webView;
  227084. DownloadClickDetector* clickListener;
  227085. };
  227086. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  227087. : browser (0),
  227088. blankPageShown (false),
  227089. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  227090. {
  227091. setOpaque (true);
  227092. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  227093. }
  227094. WebBrowserComponent::~WebBrowserComponent()
  227095. {
  227096. deleteAndZero (browser);
  227097. }
  227098. void WebBrowserComponent::goToURL (const String& url,
  227099. const StringArray* headers,
  227100. const MemoryBlock* postData)
  227101. {
  227102. lastURL = url;
  227103. lastHeaders.clear();
  227104. if (headers != 0)
  227105. lastHeaders = *headers;
  227106. lastPostData.setSize (0);
  227107. if (postData != 0)
  227108. lastPostData = *postData;
  227109. blankPageShown = false;
  227110. browser->goToURL (url, headers, postData);
  227111. }
  227112. void WebBrowserComponent::stop()
  227113. {
  227114. browser->stop();
  227115. }
  227116. void WebBrowserComponent::goBack()
  227117. {
  227118. lastURL = String::empty;
  227119. blankPageShown = false;
  227120. browser->goBack();
  227121. }
  227122. void WebBrowserComponent::goForward()
  227123. {
  227124. lastURL = String::empty;
  227125. browser->goForward();
  227126. }
  227127. void WebBrowserComponent::refresh()
  227128. {
  227129. browser->refresh();
  227130. }
  227131. void WebBrowserComponent::paint (Graphics&)
  227132. {
  227133. }
  227134. void WebBrowserComponent::checkWindowAssociation()
  227135. {
  227136. if (isShowing())
  227137. {
  227138. if (blankPageShown)
  227139. goBack();
  227140. }
  227141. else
  227142. {
  227143. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  227144. {
  227145. // when the component becomes invisible, some stuff like flash
  227146. // carries on playing audio, so we need to force it onto a blank
  227147. // page to avoid this, (and send it back when it's made visible again).
  227148. blankPageShown = true;
  227149. browser->goToURL ("about:blank", 0, 0);
  227150. }
  227151. }
  227152. }
  227153. void WebBrowserComponent::reloadLastURL()
  227154. {
  227155. if (lastURL.isNotEmpty())
  227156. {
  227157. goToURL (lastURL, &lastHeaders, &lastPostData);
  227158. lastURL = String::empty;
  227159. }
  227160. }
  227161. void WebBrowserComponent::parentHierarchyChanged()
  227162. {
  227163. checkWindowAssociation();
  227164. }
  227165. void WebBrowserComponent::resized()
  227166. {
  227167. browser->setSize (getWidth(), getHeight());
  227168. }
  227169. void WebBrowserComponent::visibilityChanged()
  227170. {
  227171. checkWindowAssociation();
  227172. }
  227173. bool WebBrowserComponent::pageAboutToLoad (const String&)
  227174. {
  227175. return true;
  227176. }
  227177. #else
  227178. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  227179. {
  227180. }
  227181. WebBrowserComponent::~WebBrowserComponent()
  227182. {
  227183. }
  227184. void WebBrowserComponent::goToURL (const String& url,
  227185. const StringArray* headers,
  227186. const MemoryBlock* postData)
  227187. {
  227188. }
  227189. void WebBrowserComponent::stop()
  227190. {
  227191. }
  227192. void WebBrowserComponent::goBack()
  227193. {
  227194. }
  227195. void WebBrowserComponent::goForward()
  227196. {
  227197. }
  227198. void WebBrowserComponent::refresh()
  227199. {
  227200. }
  227201. void WebBrowserComponent::paint (Graphics& g)
  227202. {
  227203. }
  227204. void WebBrowserComponent::checkWindowAssociation()
  227205. {
  227206. }
  227207. void WebBrowserComponent::reloadLastURL()
  227208. {
  227209. }
  227210. void WebBrowserComponent::parentHierarchyChanged()
  227211. {
  227212. }
  227213. void WebBrowserComponent::resized()
  227214. {
  227215. }
  227216. void WebBrowserComponent::visibilityChanged()
  227217. {
  227218. }
  227219. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  227220. {
  227221. return true;
  227222. }
  227223. #endif
  227224. #endif
  227225. /*** End of inlined file: juce_mac_WebBrowserComponent.mm ***/
  227226. /*** Start of inlined file: juce_iphone_Audio.cpp ***/
  227227. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227228. // compiled on its own).
  227229. #if JUCE_INCLUDED_FILE
  227230. class IPhoneAudioIODevice : public AudioIODevice
  227231. {
  227232. public:
  227233. IPhoneAudioIODevice (const String& deviceName)
  227234. : AudioIODevice (deviceName, "Audio"),
  227235. audioUnit (0),
  227236. isRunning (false),
  227237. callback (0),
  227238. actualBufferSize (0),
  227239. floatData (1, 2)
  227240. {
  227241. numInputChannels = 2;
  227242. numOutputChannels = 2;
  227243. preferredBufferSize = 0;
  227244. AudioSessionInitialize (0, 0, interruptionListenerStatic, this);
  227245. updateDeviceInfo();
  227246. }
  227247. ~IPhoneAudioIODevice()
  227248. {
  227249. close();
  227250. }
  227251. const StringArray getOutputChannelNames()
  227252. {
  227253. StringArray s;
  227254. s.add ("Left");
  227255. s.add ("Right");
  227256. return s;
  227257. }
  227258. const StringArray getInputChannelNames()
  227259. {
  227260. StringArray s;
  227261. if (audioInputIsAvailable)
  227262. {
  227263. s.add ("Left");
  227264. s.add ("Right");
  227265. }
  227266. return s;
  227267. }
  227268. int getNumSampleRates()
  227269. {
  227270. return 1;
  227271. }
  227272. double getSampleRate (int index)
  227273. {
  227274. return sampleRate;
  227275. }
  227276. int getNumBufferSizesAvailable()
  227277. {
  227278. return 1;
  227279. }
  227280. int getBufferSizeSamples (int index)
  227281. {
  227282. return getDefaultBufferSize();
  227283. }
  227284. int getDefaultBufferSize()
  227285. {
  227286. return 1024;
  227287. }
  227288. const String open (const BigInteger& inputChannels,
  227289. const BigInteger& outputChannels,
  227290. double sampleRate,
  227291. int bufferSize)
  227292. {
  227293. close();
  227294. lastError = String::empty;
  227295. preferredBufferSize = (bufferSize <= 0) ? getDefaultBufferSize() : bufferSize;
  227296. // xxx set up channel mapping
  227297. activeOutputChans = outputChannels;
  227298. activeOutputChans.setRange (2, activeOutputChans.getHighestBit(), false);
  227299. numOutputChannels = activeOutputChans.countNumberOfSetBits();
  227300. monoOutputChannelNumber = activeOutputChans.findNextSetBit (0);
  227301. activeInputChans = inputChannels;
  227302. activeInputChans.setRange (2, activeInputChans.getHighestBit(), false);
  227303. numInputChannels = activeInputChans.countNumberOfSetBits();
  227304. monoInputChannelNumber = activeInputChans.findNextSetBit (0);
  227305. AudioSessionSetActive (true);
  227306. UInt32 audioCategory = kAudioSessionCategory_PlayAndRecord;
  227307. AudioSessionSetProperty (kAudioSessionProperty_AudioCategory, sizeof (audioCategory), &audioCategory);
  227308. AudioSessionAddPropertyListener (kAudioSessionProperty_AudioRouteChange, propertyChangedStatic, this);
  227309. fixAudioRouteIfSetToReceiver();
  227310. updateDeviceInfo();
  227311. Float32 bufferDuration = preferredBufferSize / sampleRate;
  227312. AudioSessionSetProperty (kAudioSessionProperty_PreferredHardwareIOBufferDuration, sizeof (bufferDuration), &bufferDuration);
  227313. actualBufferSize = preferredBufferSize;
  227314. prepareFloatBuffers();
  227315. isRunning = true;
  227316. propertyChanged (0, 0, 0); // creates and starts the AU
  227317. lastError = audioUnit != 0 ? "" : "Couldn't open the device";
  227318. return lastError;
  227319. }
  227320. void close()
  227321. {
  227322. if (isRunning)
  227323. {
  227324. isRunning = false;
  227325. AudioSessionSetActive (false);
  227326. if (audioUnit != 0)
  227327. {
  227328. AudioComponentInstanceDispose (audioUnit);
  227329. audioUnit = 0;
  227330. }
  227331. }
  227332. }
  227333. bool isOpen()
  227334. {
  227335. return isRunning;
  227336. }
  227337. int getCurrentBufferSizeSamples()
  227338. {
  227339. return actualBufferSize;
  227340. }
  227341. double getCurrentSampleRate()
  227342. {
  227343. return sampleRate;
  227344. }
  227345. int getCurrentBitDepth()
  227346. {
  227347. return 16;
  227348. }
  227349. const BigInteger getActiveOutputChannels() const
  227350. {
  227351. return activeOutputChans;
  227352. }
  227353. const BigInteger getActiveInputChannels() const
  227354. {
  227355. return activeInputChans;
  227356. }
  227357. int getOutputLatencyInSamples()
  227358. {
  227359. return 0; //xxx
  227360. }
  227361. int getInputLatencyInSamples()
  227362. {
  227363. return 0; //xxx
  227364. }
  227365. void start (AudioIODeviceCallback* callback_)
  227366. {
  227367. if (isRunning && callback != callback_)
  227368. {
  227369. if (callback_ != 0)
  227370. callback_->audioDeviceAboutToStart (this);
  227371. const ScopedLock sl (callbackLock);
  227372. callback = callback_;
  227373. }
  227374. }
  227375. void stop()
  227376. {
  227377. if (isRunning)
  227378. {
  227379. AudioIODeviceCallback* lastCallback;
  227380. {
  227381. const ScopedLock sl (callbackLock);
  227382. lastCallback = callback;
  227383. callback = 0;
  227384. }
  227385. if (lastCallback != 0)
  227386. lastCallback->audioDeviceStopped();
  227387. }
  227388. }
  227389. bool isPlaying()
  227390. {
  227391. return isRunning && callback != 0;
  227392. }
  227393. const String getLastError()
  227394. {
  227395. return lastError;
  227396. }
  227397. private:
  227398. CriticalSection callbackLock;
  227399. Float64 sampleRate;
  227400. int numInputChannels, numOutputChannels;
  227401. int preferredBufferSize;
  227402. int actualBufferSize;
  227403. bool isRunning;
  227404. String lastError;
  227405. AudioStreamBasicDescription format;
  227406. AudioUnit audioUnit;
  227407. UInt32 audioInputIsAvailable;
  227408. AudioIODeviceCallback* callback;
  227409. BigInteger activeOutputChans, activeInputChans;
  227410. AudioSampleBuffer floatData;
  227411. float* inputChannels[3];
  227412. float* outputChannels[3];
  227413. bool monoInputChannelNumber, monoOutputChannelNumber;
  227414. void prepareFloatBuffers()
  227415. {
  227416. floatData.setSize (numInputChannels + numOutputChannels, actualBufferSize);
  227417. zerostruct (inputChannels);
  227418. zerostruct (outputChannels);
  227419. for (int i = 0; i < numInputChannels; ++i)
  227420. inputChannels[i] = floatData.getSampleData (i);
  227421. for (int i = 0; i < numOutputChannels; ++i)
  227422. outputChannels[i] = floatData.getSampleData (i + numInputChannels);
  227423. }
  227424. OSStatus process (AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp,
  227425. UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData)
  227426. {
  227427. OSStatus err = noErr;
  227428. if (audioInputIsAvailable)
  227429. err = AudioUnitRender (audioUnit, ioActionFlags, inTimeStamp, 1, inNumberFrames, ioData);
  227430. const ScopedLock sl (callbackLock);
  227431. if (callback != 0)
  227432. {
  227433. if (audioInputIsAvailable && numInputChannels > 0)
  227434. {
  227435. short* shortData = (short*) ioData->mBuffers[0].mData;
  227436. if (numInputChannels >= 2)
  227437. {
  227438. for (UInt32 i = 0; i < inNumberFrames; ++i)
  227439. {
  227440. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  227441. inputChannels[1][i] = *shortData++ * (1.0f / 32768.0f);
  227442. }
  227443. }
  227444. else
  227445. {
  227446. if (monoInputChannelNumber > 0)
  227447. ++shortData;
  227448. for (UInt32 i = 0; i < inNumberFrames; ++i)
  227449. {
  227450. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  227451. ++shortData;
  227452. }
  227453. }
  227454. }
  227455. else
  227456. {
  227457. for (int i = numInputChannels; --i >= 0;)
  227458. zeromem (inputChannels[i], sizeof (float) * inNumberFrames);
  227459. }
  227460. callback->audioDeviceIOCallback ((const float**) inputChannels, numInputChannels,
  227461. outputChannels, numOutputChannels,
  227462. (int) inNumberFrames);
  227463. short* shortData = (short*) ioData->mBuffers[0].mData;
  227464. int n = 0;
  227465. if (numOutputChannels >= 2)
  227466. {
  227467. for (UInt32 i = 0; i < inNumberFrames; ++i)
  227468. {
  227469. shortData [n++] = (short) (outputChannels[0][i] * 32767.0f);
  227470. shortData [n++] = (short) (outputChannels[1][i] * 32767.0f);
  227471. }
  227472. }
  227473. else if (numOutputChannels == 1)
  227474. {
  227475. for (UInt32 i = 0; i < inNumberFrames; ++i)
  227476. {
  227477. const short s = (short) (outputChannels[monoOutputChannelNumber][i] * 32767.0f);
  227478. shortData [n++] = s;
  227479. shortData [n++] = s;
  227480. }
  227481. }
  227482. else
  227483. {
  227484. zeromem (ioData->mBuffers[0].mData, 2 * sizeof (short) * inNumberFrames);
  227485. }
  227486. }
  227487. else
  227488. {
  227489. zeromem (ioData->mBuffers[0].mData, 2 * sizeof (short) * inNumberFrames);
  227490. }
  227491. return err;
  227492. }
  227493. void updateDeviceInfo()
  227494. {
  227495. UInt32 size = sizeof (sampleRate);
  227496. AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareSampleRate, &size, &sampleRate);
  227497. size = sizeof (audioInputIsAvailable);
  227498. AudioSessionGetProperty (kAudioSessionProperty_AudioInputAvailable, &size, &audioInputIsAvailable);
  227499. }
  227500. void propertyChanged (AudioSessionPropertyID inID, UInt32 inDataSize, const void* inPropertyValue)
  227501. {
  227502. if (! isRunning)
  227503. return;
  227504. if (inPropertyValue != 0)
  227505. {
  227506. CFDictionaryRef routeChangeDictionary = (CFDictionaryRef) inPropertyValue;
  227507. CFNumberRef routeChangeReasonRef = (CFNumberRef) CFDictionaryGetValue (routeChangeDictionary,
  227508. CFSTR (kAudioSession_AudioRouteChangeKey_Reason));
  227509. SInt32 routeChangeReason;
  227510. CFNumberGetValue (routeChangeReasonRef, kCFNumberSInt32Type, &routeChangeReason);
  227511. if (routeChangeReason == kAudioSessionRouteChangeReason_OldDeviceUnavailable)
  227512. fixAudioRouteIfSetToReceiver();
  227513. }
  227514. updateDeviceInfo();
  227515. createAudioUnit();
  227516. AudioSessionSetActive (true);
  227517. if (audioUnit != 0)
  227518. {
  227519. UInt32 formatSize = sizeof (format);
  227520. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, &formatSize);
  227521. Float32 bufferDuration = preferredBufferSize / sampleRate;
  227522. UInt32 bufferDurationSize = sizeof (bufferDuration);
  227523. AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareIOBufferDuration, &bufferDurationSize, &bufferDurationSize);
  227524. actualBufferSize = (int) (sampleRate * bufferDuration + 0.5);
  227525. AudioOutputUnitStart (audioUnit);
  227526. }
  227527. }
  227528. void interruptionListener (UInt32 inInterruption)
  227529. {
  227530. /*if (inInterruption == kAudioSessionBeginInterruption)
  227531. {
  227532. isRunning = false;
  227533. AudioOutputUnitStop (audioUnit);
  227534. if (juce_iPhoneShowModalAlert ("Audio Interrupted",
  227535. "This could have been interrupted by another application or by unplugging a headset",
  227536. @"Resume",
  227537. @"Cancel"))
  227538. {
  227539. isRunning = true;
  227540. propertyChanged (0, 0, 0);
  227541. }
  227542. }*/
  227543. if (inInterruption == kAudioSessionEndInterruption)
  227544. {
  227545. isRunning = true;
  227546. AudioSessionSetActive (true);
  227547. AudioOutputUnitStart (audioUnit);
  227548. }
  227549. }
  227550. static OSStatus processStatic (void* inRefCon, AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp,
  227551. UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData)
  227552. {
  227553. return ((IPhoneAudioIODevice*) inRefCon)->process (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  227554. }
  227555. static void propertyChangedStatic (void* inClientData, AudioSessionPropertyID inID, UInt32 inDataSize, const void* inPropertyValue)
  227556. {
  227557. ((IPhoneAudioIODevice*) inClientData)->propertyChanged (inID, inDataSize, inPropertyValue);
  227558. }
  227559. static void interruptionListenerStatic (void* inClientData, UInt32 inInterruption)
  227560. {
  227561. ((IPhoneAudioIODevice*) inClientData)->interruptionListener (inInterruption);
  227562. }
  227563. void resetFormat (const int numChannels)
  227564. {
  227565. memset (&format, 0, sizeof (format));
  227566. format.mFormatID = kAudioFormatLinearPCM;
  227567. format.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked;
  227568. format.mBitsPerChannel = 8 * sizeof (short);
  227569. format.mChannelsPerFrame = 2;
  227570. format.mFramesPerPacket = 1;
  227571. format.mBytesPerFrame = format.mBytesPerPacket = 2 * sizeof (short);
  227572. }
  227573. bool createAudioUnit()
  227574. {
  227575. if (audioUnit != 0)
  227576. {
  227577. AudioComponentInstanceDispose (audioUnit);
  227578. audioUnit = 0;
  227579. }
  227580. resetFormat (2);
  227581. AudioComponentDescription desc;
  227582. desc.componentType = kAudioUnitType_Output;
  227583. desc.componentSubType = kAudioUnitSubType_RemoteIO;
  227584. desc.componentManufacturer = kAudioUnitManufacturer_Apple;
  227585. desc.componentFlags = 0;
  227586. desc.componentFlagsMask = 0;
  227587. AudioComponent comp = AudioComponentFindNext (0, &desc);
  227588. AudioComponentInstanceNew (comp, &audioUnit);
  227589. if (audioUnit == 0)
  227590. return false;
  227591. const UInt32 one = 1;
  227592. AudioUnitSetProperty (audioUnit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, 1, &one, sizeof (one));
  227593. AudioChannelLayout layout;
  227594. layout.mChannelBitmap = 0;
  227595. layout.mNumberChannelDescriptions = 0;
  227596. layout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  227597. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Input, 0, &layout, sizeof (layout));
  227598. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Output, 0, &layout, sizeof (layout));
  227599. AURenderCallbackStruct inputProc;
  227600. inputProc.inputProc = processStatic;
  227601. inputProc.inputProcRefCon = this;
  227602. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &inputProc, sizeof (inputProc));
  227603. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &format, sizeof (format));
  227604. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, sizeof (format));
  227605. AudioUnitInitialize (audioUnit);
  227606. return true;
  227607. }
  227608. // If the routing is set to go through the receiver (i.e. the speaker, but quiet), this re-routes it
  227609. // to make it loud. Needed because by default when using an input + output, the output is kept quiet.
  227610. static void fixAudioRouteIfSetToReceiver()
  227611. {
  227612. CFStringRef audioRoute = 0;
  227613. UInt32 propertySize = sizeof (audioRoute);
  227614. if (AudioSessionGetProperty (kAudioSessionProperty_AudioRoute, &propertySize, &audioRoute) == noErr)
  227615. {
  227616. NSString* route = (NSString*) audioRoute;
  227617. //DBG ("audio route: " + nsStringToJuce (route));
  227618. if ([route hasPrefix: @"Receiver"])
  227619. {
  227620. UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
  227621. AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute, sizeof (audioRouteOverride), &audioRouteOverride);
  227622. }
  227623. CFRelease (audioRoute);
  227624. }
  227625. }
  227626. IPhoneAudioIODevice (const IPhoneAudioIODevice&);
  227627. IPhoneAudioIODevice& operator= (const IPhoneAudioIODevice&);
  227628. };
  227629. class IPhoneAudioIODeviceType : public AudioIODeviceType
  227630. {
  227631. public:
  227632. IPhoneAudioIODeviceType()
  227633. : AudioIODeviceType ("iPhone Audio")
  227634. {
  227635. }
  227636. ~IPhoneAudioIODeviceType()
  227637. {
  227638. }
  227639. void scanForDevices()
  227640. {
  227641. }
  227642. const StringArray getDeviceNames (bool wantInputNames) const
  227643. {
  227644. StringArray s;
  227645. s.add ("iPhone Audio");
  227646. return s;
  227647. }
  227648. int getDefaultDeviceIndex (bool forInput) const
  227649. {
  227650. return 0;
  227651. }
  227652. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  227653. {
  227654. return device != 0 ? 0 : -1;
  227655. }
  227656. bool hasSeparateInputsAndOutputs() const { return false; }
  227657. AudioIODevice* createDevice (const String& outputDeviceName,
  227658. const String& inputDeviceName)
  227659. {
  227660. if (outputDeviceName.isNotEmpty() || inputDeviceName.isNotEmpty())
  227661. {
  227662. return new IPhoneAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  227663. : inputDeviceName);
  227664. }
  227665. return 0;
  227666. }
  227667. juce_UseDebuggingNewOperator
  227668. private:
  227669. IPhoneAudioIODeviceType (const IPhoneAudioIODeviceType&);
  227670. IPhoneAudioIODeviceType& operator= (const IPhoneAudioIODeviceType&);
  227671. };
  227672. AudioIODeviceType* juce_createAudioIODeviceType_iPhoneAudio()
  227673. {
  227674. return new IPhoneAudioIODeviceType();
  227675. }
  227676. #endif
  227677. /*** End of inlined file: juce_iphone_Audio.cpp ***/
  227678. /*** Start of inlined file: juce_mac_CoreMidi.cpp ***/
  227679. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227680. // compiled on its own).
  227681. #if JUCE_INCLUDED_FILE
  227682. #if JUCE_MAC
  227683. #undef log
  227684. #define log(a) Logger::writeToLog(a)
  227685. static bool logAnyErrorsMidi (const OSStatus err, const int lineNum)
  227686. {
  227687. if (err == noErr)
  227688. return true;
  227689. log ("CoreMidi error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  227690. jassertfalse;
  227691. return false;
  227692. }
  227693. #undef OK
  227694. #define OK(a) logAnyErrorsMidi(a, __LINE__)
  227695. static const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  227696. {
  227697. String result;
  227698. CFStringRef str = 0;
  227699. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  227700. if (str != 0)
  227701. {
  227702. result = PlatformUtilities::cfStringToJuceString (str);
  227703. CFRelease (str);
  227704. str = 0;
  227705. }
  227706. MIDIEntityRef entity = 0;
  227707. MIDIEndpointGetEntity (endpoint, &entity);
  227708. if (entity == 0)
  227709. return result; // probably virtual
  227710. if (result.isEmpty())
  227711. {
  227712. // endpoint name has zero length - try the entity
  227713. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  227714. if (str != 0)
  227715. {
  227716. result += PlatformUtilities::cfStringToJuceString (str);
  227717. CFRelease (str);
  227718. str = 0;
  227719. }
  227720. }
  227721. // now consider the device's name
  227722. MIDIDeviceRef device = 0;
  227723. MIDIEntityGetDevice (entity, &device);
  227724. if (device == 0)
  227725. return result;
  227726. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  227727. if (str != 0)
  227728. {
  227729. const String s (PlatformUtilities::cfStringToJuceString (str));
  227730. CFRelease (str);
  227731. // if an external device has only one entity, throw away
  227732. // the endpoint name and just use the device name
  227733. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  227734. {
  227735. result = s;
  227736. }
  227737. else if (! result.startsWithIgnoreCase (s))
  227738. {
  227739. // prepend the device name to the entity name
  227740. result = (s + " " + result).trimEnd();
  227741. }
  227742. }
  227743. return result;
  227744. }
  227745. static const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  227746. {
  227747. String result;
  227748. // Does the endpoint have connections?
  227749. CFDataRef connections = 0;
  227750. int numConnections = 0;
  227751. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  227752. if (connections != 0)
  227753. {
  227754. numConnections = (int) (CFDataGetLength (connections) / sizeof (MIDIUniqueID));
  227755. if (numConnections > 0)
  227756. {
  227757. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  227758. for (int i = 0; i < numConnections; ++i, ++pid)
  227759. {
  227760. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  227761. MIDIObjectRef connObject;
  227762. MIDIObjectType connObjectType;
  227763. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  227764. if (err == noErr)
  227765. {
  227766. String s;
  227767. if (connObjectType == kMIDIObjectType_ExternalSource
  227768. || connObjectType == kMIDIObjectType_ExternalDestination)
  227769. {
  227770. // Connected to an external device's endpoint (10.3 and later).
  227771. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  227772. }
  227773. else
  227774. {
  227775. // Connected to an external device (10.2) (or something else, catch-all)
  227776. CFStringRef str = 0;
  227777. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  227778. if (str != 0)
  227779. {
  227780. s = PlatformUtilities::cfStringToJuceString (str);
  227781. CFRelease (str);
  227782. }
  227783. }
  227784. if (s.isNotEmpty())
  227785. {
  227786. if (result.isNotEmpty())
  227787. result += ", ";
  227788. result += s;
  227789. }
  227790. }
  227791. }
  227792. }
  227793. CFRelease (connections);
  227794. }
  227795. if (result.isNotEmpty())
  227796. return result;
  227797. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  227798. return getEndpointName (endpoint, false);
  227799. }
  227800. const StringArray MidiOutput::getDevices()
  227801. {
  227802. StringArray s;
  227803. const ItemCount num = MIDIGetNumberOfDestinations();
  227804. for (ItemCount i = 0; i < num; ++i)
  227805. {
  227806. MIDIEndpointRef dest = MIDIGetDestination (i);
  227807. if (dest != 0)
  227808. {
  227809. String name (getConnectedEndpointName (dest));
  227810. if (name.isEmpty())
  227811. name = "<error>";
  227812. s.add (name);
  227813. }
  227814. else
  227815. {
  227816. s.add ("<error>");
  227817. }
  227818. }
  227819. return s;
  227820. }
  227821. int MidiOutput::getDefaultDeviceIndex()
  227822. {
  227823. return 0;
  227824. }
  227825. static MIDIClientRef globalMidiClient;
  227826. static bool hasGlobalClientBeenCreated = false;
  227827. static bool makeSureClientExists()
  227828. {
  227829. if (! hasGlobalClientBeenCreated)
  227830. {
  227831. String name ("JUCE");
  227832. if (JUCEApplication::getInstance() != 0)
  227833. name = JUCEApplication::getInstance()->getApplicationName();
  227834. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  227835. hasGlobalClientBeenCreated = OK (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  227836. CFRelease (appName);
  227837. }
  227838. return hasGlobalClientBeenCreated;
  227839. }
  227840. class MidiPortAndEndpoint
  227841. {
  227842. public:
  227843. MidiPortAndEndpoint (MIDIPortRef port_, MIDIEndpointRef endPoint_)
  227844. : port (port_), endPoint (endPoint_)
  227845. {
  227846. }
  227847. ~MidiPortAndEndpoint()
  227848. {
  227849. if (port != 0)
  227850. MIDIPortDispose (port);
  227851. if (port == 0 && endPoint != 0) // if port == 0, it means we created the endpoint, so it's safe to delete it
  227852. MIDIEndpointDispose (endPoint);
  227853. }
  227854. MIDIPortRef port;
  227855. MIDIEndpointRef endPoint;
  227856. };
  227857. MidiOutput* MidiOutput::openDevice (int index)
  227858. {
  227859. MidiOutput* mo = 0;
  227860. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfDestinations())
  227861. {
  227862. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  227863. CFStringRef pname;
  227864. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  227865. {
  227866. log ("CoreMidi - opening out: " + PlatformUtilities::cfStringToJuceString (pname));
  227867. if (makeSureClientExists())
  227868. {
  227869. MIDIPortRef port;
  227870. if (OK (MIDIOutputPortCreate (globalMidiClient, pname, &port)))
  227871. {
  227872. mo = new MidiOutput();
  227873. mo->internal = new MidiPortAndEndpoint (port, endPoint);
  227874. }
  227875. }
  227876. CFRelease (pname);
  227877. }
  227878. }
  227879. return mo;
  227880. }
  227881. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  227882. {
  227883. MidiOutput* mo = 0;
  227884. if (makeSureClientExists())
  227885. {
  227886. MIDIEndpointRef endPoint;
  227887. CFStringRef name = PlatformUtilities::juceStringToCFString (deviceName);
  227888. if (OK (MIDISourceCreate (globalMidiClient, name, &endPoint)))
  227889. {
  227890. mo = new MidiOutput();
  227891. mo->internal = new MidiPortAndEndpoint (0, endPoint);
  227892. }
  227893. CFRelease (name);
  227894. }
  227895. return mo;
  227896. }
  227897. MidiOutput::~MidiOutput()
  227898. {
  227899. delete (MidiPortAndEndpoint*) internal;
  227900. }
  227901. void MidiOutput::reset()
  227902. {
  227903. }
  227904. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  227905. {
  227906. return false;
  227907. }
  227908. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  227909. {
  227910. }
  227911. void MidiOutput::sendMessageNow (const MidiMessage& message)
  227912. {
  227913. MidiPortAndEndpoint* const mpe = (MidiPortAndEndpoint*) internal;
  227914. if (message.isSysEx())
  227915. {
  227916. const int maxPacketSize = 256;
  227917. int pos = 0, bytesLeft = message.getRawDataSize();
  227918. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  227919. HeapBlock <MIDIPacketList> packets;
  227920. packets.malloc (32 * numPackets + message.getRawDataSize(), 1);
  227921. packets->numPackets = numPackets;
  227922. MIDIPacket* p = packets->packet;
  227923. for (int i = 0; i < numPackets; ++i)
  227924. {
  227925. p->timeStamp = 0;
  227926. p->length = jmin (maxPacketSize, bytesLeft);
  227927. memcpy (p->data, message.getRawData() + pos, p->length);
  227928. pos += p->length;
  227929. bytesLeft -= p->length;
  227930. p = MIDIPacketNext (p);
  227931. }
  227932. if (mpe->port != 0)
  227933. MIDISend (mpe->port, mpe->endPoint, packets);
  227934. else
  227935. MIDIReceived (mpe->endPoint, packets);
  227936. }
  227937. else
  227938. {
  227939. MIDIPacketList packets;
  227940. packets.numPackets = 1;
  227941. packets.packet[0].timeStamp = 0;
  227942. packets.packet[0].length = message.getRawDataSize();
  227943. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  227944. if (mpe->port != 0)
  227945. MIDISend (mpe->port, mpe->endPoint, &packets);
  227946. else
  227947. MIDIReceived (mpe->endPoint, &packets);
  227948. }
  227949. }
  227950. const StringArray MidiInput::getDevices()
  227951. {
  227952. StringArray s;
  227953. const ItemCount num = MIDIGetNumberOfSources();
  227954. for (ItemCount i = 0; i < num; ++i)
  227955. {
  227956. MIDIEndpointRef source = MIDIGetSource (i);
  227957. if (source != 0)
  227958. {
  227959. String name (getConnectedEndpointName (source));
  227960. if (name.isEmpty())
  227961. name = "<error>";
  227962. s.add (name);
  227963. }
  227964. else
  227965. {
  227966. s.add ("<error>");
  227967. }
  227968. }
  227969. return s;
  227970. }
  227971. int MidiInput::getDefaultDeviceIndex()
  227972. {
  227973. return 0;
  227974. }
  227975. struct MidiPortAndCallback
  227976. {
  227977. MidiInput* input;
  227978. MidiPortAndEndpoint* portAndEndpoint;
  227979. MidiInputCallback* callback;
  227980. MemoryBlock pendingData;
  227981. int pendingBytes;
  227982. double pendingDataTime;
  227983. bool active;
  227984. void processSysex (const uint8*& d, int& size, const double time)
  227985. {
  227986. if (*d == 0xf0)
  227987. {
  227988. pendingBytes = 0;
  227989. pendingDataTime = time;
  227990. }
  227991. pendingData.ensureSize (pendingBytes + size, false);
  227992. uint8* totalMessage = (uint8*) pendingData.getData();
  227993. uint8* dest = totalMessage + pendingBytes;
  227994. while (size > 0)
  227995. {
  227996. if (pendingBytes > 0 && *d >= 0x80)
  227997. {
  227998. if (*d >= 0xfa || *d == 0xf8)
  227999. {
  228000. callback->handleIncomingMidiMessage (input, MidiMessage (*d, time));
  228001. ++d;
  228002. --size;
  228003. }
  228004. else
  228005. {
  228006. if (*d == 0xf7)
  228007. {
  228008. *dest++ = *d++;
  228009. pendingBytes++;
  228010. --size;
  228011. }
  228012. break;
  228013. }
  228014. }
  228015. else
  228016. {
  228017. *dest++ = *d++;
  228018. pendingBytes++;
  228019. --size;
  228020. }
  228021. }
  228022. if (totalMessage [pendingBytes - 1] == 0xf7)
  228023. {
  228024. callback->handleIncomingMidiMessage (input, MidiMessage (totalMessage, pendingBytes, pendingDataTime));
  228025. pendingBytes = 0;
  228026. }
  228027. else
  228028. {
  228029. callback->handlePartialSysexMessage (input, totalMessage, pendingBytes, pendingDataTime);
  228030. }
  228031. }
  228032. };
  228033. namespace CoreMidiCallbacks
  228034. {
  228035. static CriticalSection callbackLock;
  228036. static Array<void*> activeCallbacks;
  228037. }
  228038. static void midiInputProc (const MIDIPacketList* pktlist,
  228039. void* readProcRefCon,
  228040. void* /*srcConnRefCon*/)
  228041. {
  228042. double time = Time::getMillisecondCounterHiRes() * 0.001;
  228043. const double originalTime = time;
  228044. MidiPortAndCallback* const mpc = (MidiPortAndCallback*) readProcRefCon;
  228045. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  228046. if (CoreMidiCallbacks::activeCallbacks.contains (mpc) && mpc->active)
  228047. {
  228048. const MIDIPacket* packet = &pktlist->packet[0];
  228049. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  228050. {
  228051. const uint8* d = (const uint8*) (packet->data);
  228052. int size = packet->length;
  228053. while (size > 0)
  228054. {
  228055. time = originalTime;
  228056. if (mpc->pendingBytes > 0 || d[0] == 0xf0)
  228057. {
  228058. mpc->processSysex (d, size, time);
  228059. }
  228060. else
  228061. {
  228062. int used = 0;
  228063. const MidiMessage m (d, size, used, 0, time);
  228064. if (used <= 0)
  228065. {
  228066. jassertfalse; // malformed midi message
  228067. break;
  228068. }
  228069. else
  228070. {
  228071. mpc->callback->handleIncomingMidiMessage (mpc->input, m);
  228072. }
  228073. size -= used;
  228074. d += used;
  228075. }
  228076. }
  228077. packet = MIDIPacketNext (packet);
  228078. }
  228079. }
  228080. }
  228081. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  228082. {
  228083. MidiInput* mi = 0;
  228084. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfSources())
  228085. {
  228086. MIDIEndpointRef endPoint = MIDIGetSource (index);
  228087. if (endPoint != 0)
  228088. {
  228089. CFStringRef pname;
  228090. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  228091. {
  228092. log ("CoreMidi - opening inp: " + PlatformUtilities::cfStringToJuceString (pname));
  228093. if (makeSureClientExists())
  228094. {
  228095. MIDIPortRef port;
  228096. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback());
  228097. mpc->active = false;
  228098. if (OK (MIDIInputPortCreate (globalMidiClient, pname, midiInputProc, mpc, &port)))
  228099. {
  228100. if (OK (MIDIPortConnectSource (port, endPoint, 0)))
  228101. {
  228102. mpc->portAndEndpoint = new MidiPortAndEndpoint (port, endPoint);
  228103. mpc->callback = callback;
  228104. mpc->pendingBytes = 0;
  228105. mpc->pendingData.ensureSize (128);
  228106. mi = new MidiInput (getDevices() [index]);
  228107. mpc->input = mi;
  228108. mi->internal = mpc;
  228109. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  228110. CoreMidiCallbacks::activeCallbacks.add (mpc.release());
  228111. }
  228112. else
  228113. {
  228114. OK (MIDIPortDispose (port));
  228115. }
  228116. }
  228117. }
  228118. }
  228119. CFRelease (pname);
  228120. }
  228121. }
  228122. return mi;
  228123. }
  228124. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  228125. {
  228126. MidiInput* mi = 0;
  228127. if (makeSureClientExists())
  228128. {
  228129. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback());
  228130. mpc->active = false;
  228131. MIDIEndpointRef endPoint;
  228132. CFStringRef name = PlatformUtilities::juceStringToCFString(deviceName);
  228133. if (OK (MIDIDestinationCreate (globalMidiClient, name, midiInputProc, mpc, &endPoint)))
  228134. {
  228135. mpc->portAndEndpoint = new MidiPortAndEndpoint (0, endPoint);
  228136. mpc->callback = callback;
  228137. mpc->pendingBytes = 0;
  228138. mpc->pendingData.ensureSize (128);
  228139. mi = new MidiInput (deviceName);
  228140. mpc->input = mi;
  228141. mi->internal = mpc;
  228142. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  228143. CoreMidiCallbacks::activeCallbacks.add (mpc.release());
  228144. }
  228145. CFRelease (name);
  228146. }
  228147. return mi;
  228148. }
  228149. MidiInput::MidiInput (const String& name_)
  228150. : name (name_)
  228151. {
  228152. }
  228153. MidiInput::~MidiInput()
  228154. {
  228155. MidiPortAndCallback* const mpc = (MidiPortAndCallback*) internal;
  228156. mpc->active = false;
  228157. {
  228158. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  228159. CoreMidiCallbacks::activeCallbacks.removeValue (mpc);
  228160. }
  228161. if (mpc->portAndEndpoint->port != 0)
  228162. OK (MIDIPortDisconnectSource (mpc->portAndEndpoint->port, mpc->portAndEndpoint->endPoint));
  228163. delete mpc->portAndEndpoint;
  228164. delete mpc;
  228165. }
  228166. void MidiInput::start()
  228167. {
  228168. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  228169. ((MidiPortAndCallback*) internal)->active = true;
  228170. }
  228171. void MidiInput::stop()
  228172. {
  228173. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  228174. ((MidiPortAndCallback*) internal)->active = false;
  228175. }
  228176. #undef log
  228177. #else
  228178. MidiOutput::~MidiOutput()
  228179. {
  228180. }
  228181. void MidiOutput::reset()
  228182. {
  228183. }
  228184. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  228185. {
  228186. return false;
  228187. }
  228188. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  228189. {
  228190. }
  228191. void MidiOutput::sendMessageNow (const MidiMessage& message)
  228192. {
  228193. }
  228194. const StringArray MidiOutput::getDevices()
  228195. {
  228196. return StringArray();
  228197. }
  228198. MidiOutput* MidiOutput::openDevice (int index)
  228199. {
  228200. return 0;
  228201. }
  228202. const StringArray MidiInput::getDevices()
  228203. {
  228204. return StringArray();
  228205. }
  228206. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  228207. {
  228208. return 0;
  228209. }
  228210. #endif
  228211. #endif
  228212. /*** End of inlined file: juce_mac_CoreMidi.cpp ***/
  228213. #else
  228214. /*** Start of inlined file: juce_mac_Fonts.mm ***/
  228215. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228216. // compiled on its own).
  228217. #if JUCE_INCLUDED_FILE
  228218. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  228219. #define SUPPORT_10_4_FONTS 1
  228220. #define NEW_CGFONT_FUNCTIONS_UNAVAILABLE (CGFontCreateWithFontName == 0)
  228221. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  228222. #define SUPPORT_ONLY_10_4_FONTS 1
  228223. #endif
  228224. END_JUCE_NAMESPACE
  228225. @interface NSFont (PrivateHack)
  228226. - (NSGlyph) _defaultGlyphForChar: (unichar) theChar;
  228227. @end
  228228. BEGIN_JUCE_NAMESPACE
  228229. #endif
  228230. class MacTypeface : public Typeface
  228231. {
  228232. public:
  228233. MacTypeface (const Font& font)
  228234. : Typeface (font.getTypefaceName())
  228235. {
  228236. const ScopedAutoReleasePool pool;
  228237. renderingTransform = CGAffineTransformIdentity;
  228238. bool needsItalicTransform = false;
  228239. #if JUCE_IPHONE
  228240. NSString* fontName = juceStringToNS (font.getTypefaceName());
  228241. if (font.isItalic() || font.isBold())
  228242. {
  228243. NSArray* familyFonts = [UIFont fontNamesForFamilyName: juceStringToNS (font.getTypefaceName())];
  228244. for (NSString* i in familyFonts)
  228245. {
  228246. const String fn (nsStringToJuce (i));
  228247. const String afterDash (fn.fromFirstOccurrenceOf ("-", false, false));
  228248. const bool probablyBold = afterDash.containsIgnoreCase ("bold") || fn.endsWithIgnoreCase ("bold");
  228249. const bool probablyItalic = afterDash.containsIgnoreCase ("oblique")
  228250. || afterDash.containsIgnoreCase ("italic")
  228251. || fn.endsWithIgnoreCase ("oblique")
  228252. || fn.endsWithIgnoreCase ("italic");
  228253. if (probablyBold == font.isBold()
  228254. && probablyItalic == font.isItalic())
  228255. {
  228256. fontName = i;
  228257. needsItalicTransform = false;
  228258. break;
  228259. }
  228260. else if (probablyBold && (! probablyItalic) && probablyBold == font.isBold())
  228261. {
  228262. fontName = i;
  228263. needsItalicTransform = true; // not ideal, so carry on in case we find a better one
  228264. }
  228265. }
  228266. if (needsItalicTransform)
  228267. renderingTransform.c = 0.15f;
  228268. }
  228269. fontRef = CGFontCreateWithFontName ((CFStringRef) fontName);
  228270. const int ascender = abs (CGFontGetAscent (fontRef));
  228271. const float totalHeight = ascender + abs (CGFontGetDescent (fontRef));
  228272. ascent = ascender / totalHeight;
  228273. unitsToHeightScaleFactor = 1.0f / totalHeight;
  228274. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / totalHeight;
  228275. #else
  228276. nsFont = [NSFont fontWithName: juceStringToNS (font.getTypefaceName()) size: 1024];
  228277. if (font.isItalic())
  228278. {
  228279. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: nsFont
  228280. toHaveTrait: NSItalicFontMask];
  228281. if (newFont == nsFont)
  228282. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  228283. nsFont = newFont;
  228284. }
  228285. if (font.isBold())
  228286. nsFont = [[NSFontManager sharedFontManager] convertFont: nsFont toHaveTrait: NSBoldFontMask];
  228287. [nsFont retain];
  228288. ascent = std::abs ((float) [nsFont ascender]);
  228289. float totalSize = ascent + std::abs ((float) [nsFont descender]);
  228290. ascent /= totalSize;
  228291. pathTransform = AffineTransform::identity.scale (1.0f / totalSize, 1.0f / totalSize);
  228292. if (needsItalicTransform)
  228293. {
  228294. pathTransform = pathTransform.sheared (-0.15f, 0.0f);
  228295. renderingTransform.c = 0.15f;
  228296. }
  228297. #if SUPPORT_ONLY_10_4_FONTS
  228298. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  228299. if (atsFont == 0)
  228300. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  228301. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  228302. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  228303. unitsToHeightScaleFactor = 1.0f / totalHeight;
  228304. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  228305. #else
  228306. #if SUPPORT_10_4_FONTS
  228307. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  228308. {
  228309. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  228310. if (atsFont == 0)
  228311. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  228312. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  228313. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  228314. unitsToHeightScaleFactor = 1.0f / totalHeight;
  228315. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  228316. }
  228317. else
  228318. #endif
  228319. {
  228320. fontRef = CGFontCreateWithFontName ((CFStringRef) [nsFont fontName]);
  228321. const int totalHeight = abs (CGFontGetAscent (fontRef)) + abs (CGFontGetDescent (fontRef));
  228322. unitsToHeightScaleFactor = 1.0f / totalHeight;
  228323. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / (float) totalHeight;
  228324. }
  228325. #endif
  228326. #endif
  228327. }
  228328. ~MacTypeface()
  228329. {
  228330. #if ! JUCE_IPHONE
  228331. [nsFont release];
  228332. #endif
  228333. if (fontRef != 0)
  228334. CGFontRelease (fontRef);
  228335. }
  228336. float getAscent() const
  228337. {
  228338. return ascent;
  228339. }
  228340. float getDescent() const
  228341. {
  228342. return 1.0f - ascent;
  228343. }
  228344. float getStringWidth (const String& text)
  228345. {
  228346. if (fontRef == 0 || text.isEmpty())
  228347. return 0;
  228348. const int length = text.length();
  228349. HeapBlock <CGGlyph> glyphs;
  228350. createGlyphsForString (text, length, glyphs);
  228351. float x = 0;
  228352. #if SUPPORT_ONLY_10_4_FONTS
  228353. HeapBlock <NSSize> advances (length);
  228354. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  228355. for (int i = 0; i < length; ++i)
  228356. x += advances[i].width;
  228357. #else
  228358. #if SUPPORT_10_4_FONTS
  228359. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  228360. {
  228361. HeapBlock <NSSize> advances (length);
  228362. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast<NSGlyph*> (glyphs.getData()) count: length];
  228363. for (int i = 0; i < length; ++i)
  228364. x += advances[i].width;
  228365. }
  228366. else
  228367. #endif
  228368. {
  228369. HeapBlock <int> advances (length);
  228370. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  228371. for (int i = 0; i < length; ++i)
  228372. x += advances[i];
  228373. }
  228374. #endif
  228375. return x * unitsToHeightScaleFactor;
  228376. }
  228377. void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
  228378. {
  228379. xOffsets.add (0);
  228380. if (fontRef == 0 || text.isEmpty())
  228381. return;
  228382. const int length = text.length();
  228383. HeapBlock <CGGlyph> glyphs;
  228384. createGlyphsForString (text, length, glyphs);
  228385. #if SUPPORT_ONLY_10_4_FONTS
  228386. HeapBlock <NSSize> advances (length);
  228387. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  228388. int x = 0;
  228389. for (int i = 0; i < length; ++i)
  228390. {
  228391. x += advances[i].width;
  228392. xOffsets.add (x * unitsToHeightScaleFactor);
  228393. resultGlyphs.add (reinterpret_cast <NSGlyph*> (glyphs.getData())[i]);
  228394. }
  228395. #else
  228396. #if SUPPORT_10_4_FONTS
  228397. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  228398. {
  228399. HeapBlock <NSSize> advances (length);
  228400. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  228401. [nsFont getAdvancements: advances forGlyphs: nsGlyphs count: length];
  228402. float x = 0;
  228403. for (int i = 0; i < length; ++i)
  228404. {
  228405. x += advances[i].width;
  228406. xOffsets.add (x * unitsToHeightScaleFactor);
  228407. resultGlyphs.add (nsGlyphs[i]);
  228408. }
  228409. }
  228410. else
  228411. #endif
  228412. {
  228413. HeapBlock <int> advances (length);
  228414. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  228415. {
  228416. int x = 0;
  228417. for (int i = 0; i < length; ++i)
  228418. {
  228419. x += advances [i];
  228420. xOffsets.add (x * unitsToHeightScaleFactor);
  228421. resultGlyphs.add (glyphs[i]);
  228422. }
  228423. }
  228424. }
  228425. #endif
  228426. }
  228427. bool getOutlineForGlyph (int glyphNumber, Path& path)
  228428. {
  228429. #if JUCE_IPHONE
  228430. return false;
  228431. #else
  228432. if (nsFont == 0)
  228433. return false;
  228434. // we might need to apply a transform to the path, so it mustn't have anything else in it
  228435. jassert (path.isEmpty());
  228436. const ScopedAutoReleasePool pool;
  228437. NSBezierPath* bez = [NSBezierPath bezierPath];
  228438. [bez moveToPoint: NSMakePoint (0, 0)];
  228439. [bez appendBezierPathWithGlyph: (NSGlyph) glyphNumber
  228440. inFont: nsFont];
  228441. for (int i = 0; i < [bez elementCount]; ++i)
  228442. {
  228443. NSPoint p[3];
  228444. switch ([bez elementAtIndex: i associatedPoints: p])
  228445. {
  228446. case NSMoveToBezierPathElement:
  228447. path.startNewSubPath ((float) p[0].x, (float) -p[0].y);
  228448. break;
  228449. case NSLineToBezierPathElement:
  228450. path.lineTo ((float) p[0].x, (float) -p[0].y);
  228451. break;
  228452. case NSCurveToBezierPathElement:
  228453. 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);
  228454. break;
  228455. case NSClosePathBezierPathElement:
  228456. path.closeSubPath();
  228457. break;
  228458. default:
  228459. jassertfalse;
  228460. break;
  228461. }
  228462. }
  228463. path.applyTransform (pathTransform);
  228464. return true;
  228465. #endif
  228466. }
  228467. juce_UseDebuggingNewOperator
  228468. CGFontRef fontRef;
  228469. float fontHeightToCGSizeFactor;
  228470. CGAffineTransform renderingTransform;
  228471. private:
  228472. float ascent, unitsToHeightScaleFactor;
  228473. #if JUCE_IPHONE
  228474. #else
  228475. NSFont* nsFont;
  228476. AffineTransform pathTransform;
  228477. #endif
  228478. void createGlyphsForString (const juce_wchar* const text, const int length, HeapBlock <CGGlyph>& glyphs)
  228479. {
  228480. #if SUPPORT_10_4_FONTS
  228481. #if ! SUPPORT_ONLY_10_4_FONTS
  228482. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  228483. #endif
  228484. {
  228485. glyphs.malloc (sizeof (NSGlyph) * length, 1);
  228486. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  228487. for (int i = 0; i < length; ++i)
  228488. nsGlyphs[i] = (NSGlyph) [nsFont _defaultGlyphForChar: text[i]];
  228489. return;
  228490. }
  228491. #endif
  228492. #if ! SUPPORT_ONLY_10_4_FONTS
  228493. if (charToGlyphMapper == 0)
  228494. charToGlyphMapper = new CharToGlyphMapper (fontRef);
  228495. glyphs.malloc (length);
  228496. for (int i = 0; i < length; ++i)
  228497. glyphs[i] = (CGGlyph) charToGlyphMapper->getGlyphForCharacter (text[i]);
  228498. #endif
  228499. }
  228500. #if ! SUPPORT_ONLY_10_4_FONTS
  228501. // Reads a CGFontRef's character map table to convert unicode into glyph numbers
  228502. class CharToGlyphMapper
  228503. {
  228504. public:
  228505. CharToGlyphMapper (CGFontRef fontRef)
  228506. : segCount (0), endCode (0), startCode (0), idDelta (0),
  228507. idRangeOffset (0), glyphIndexes (0)
  228508. {
  228509. CFDataRef cmapTable = CGFontCopyTableForTag (fontRef, 'cmap');
  228510. if (cmapTable != 0)
  228511. {
  228512. const int numSubtables = getValue16 (cmapTable, 2);
  228513. for (int i = 0; i < numSubtables; ++i)
  228514. {
  228515. if (getValue16 (cmapTable, i * 8 + 4) == 0) // check for platform ID of 0
  228516. {
  228517. const int offset = getValue32 (cmapTable, i * 8 + 8);
  228518. if (getValue16 (cmapTable, offset) == 4) // check that it's format 4..
  228519. {
  228520. const int length = getValue16 (cmapTable, offset + 2);
  228521. const int segCountX2 = getValue16 (cmapTable, offset + 6);
  228522. segCount = segCountX2 / 2;
  228523. const int endCodeOffset = offset + 14;
  228524. const int startCodeOffset = endCodeOffset + 2 + segCountX2;
  228525. const int idDeltaOffset = startCodeOffset + segCountX2;
  228526. const int idRangeOffsetOffset = idDeltaOffset + segCountX2;
  228527. const int glyphIndexesOffset = idRangeOffsetOffset + segCountX2;
  228528. endCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + endCodeOffset, segCountX2);
  228529. startCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + startCodeOffset, segCountX2);
  228530. idDelta = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idDeltaOffset, segCountX2);
  228531. idRangeOffset = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idRangeOffsetOffset, segCountX2);
  228532. glyphIndexes = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + glyphIndexesOffset, offset + length - glyphIndexesOffset);
  228533. }
  228534. break;
  228535. }
  228536. }
  228537. CFRelease (cmapTable);
  228538. }
  228539. }
  228540. ~CharToGlyphMapper()
  228541. {
  228542. if (endCode != 0)
  228543. {
  228544. CFRelease (endCode);
  228545. CFRelease (startCode);
  228546. CFRelease (idDelta);
  228547. CFRelease (idRangeOffset);
  228548. CFRelease (glyphIndexes);
  228549. }
  228550. }
  228551. int getGlyphForCharacter (const juce_wchar c) const
  228552. {
  228553. for (int i = 0; i < segCount; ++i)
  228554. {
  228555. if (getValue16 (endCode, i * 2) >= c)
  228556. {
  228557. const int start = getValue16 (startCode, i * 2);
  228558. if (start > c)
  228559. break;
  228560. const int delta = getValue16 (idDelta, i * 2);
  228561. const int rangeOffset = getValue16 (idRangeOffset, i * 2);
  228562. if (rangeOffset == 0)
  228563. return delta + c;
  228564. else
  228565. return getValue16 (glyphIndexes, 2 * ((rangeOffset / 2) + (c - start) - (segCount - i)));
  228566. }
  228567. }
  228568. // If we failed to find it "properly", this dodgy fall-back seems to do the trick for most fonts!
  228569. return jmax (-1, c - 29);
  228570. }
  228571. private:
  228572. int segCount;
  228573. CFDataRef endCode, startCode, idDelta, idRangeOffset, glyphIndexes;
  228574. static uint16 getValue16 (CFDataRef data, const int index)
  228575. {
  228576. return CFSwapInt16BigToHost (*(UInt16*) (CFDataGetBytePtr (data) + index));
  228577. }
  228578. static uint32 getValue32 (CFDataRef data, const int index)
  228579. {
  228580. return CFSwapInt32BigToHost (*(UInt32*) (CFDataGetBytePtr (data) + index));
  228581. }
  228582. };
  228583. ScopedPointer <CharToGlyphMapper> charToGlyphMapper;
  228584. #endif
  228585. MacTypeface (const MacTypeface&);
  228586. MacTypeface& operator= (const MacTypeface&);
  228587. };
  228588. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  228589. {
  228590. return new MacTypeface (font);
  228591. }
  228592. const StringArray Font::findAllTypefaceNames()
  228593. {
  228594. StringArray names;
  228595. const ScopedAutoReleasePool pool;
  228596. #if JUCE_IPHONE
  228597. NSArray* fonts = [UIFont familyNames];
  228598. #else
  228599. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  228600. #endif
  228601. for (unsigned int i = 0; i < [fonts count]; ++i)
  228602. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  228603. names.sort (true);
  228604. return names;
  228605. }
  228606. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  228607. {
  228608. #if JUCE_IPHONE
  228609. defaultSans = "Helvetica";
  228610. defaultSerif = "Times New Roman";
  228611. defaultFixed = "Courier New";
  228612. #else
  228613. defaultSans = "Lucida Grande";
  228614. defaultSerif = "Times New Roman";
  228615. defaultFixed = "Monaco";
  228616. #endif
  228617. }
  228618. #endif
  228619. /*** End of inlined file: juce_mac_Fonts.mm ***/
  228620. // (must go before juce_mac_CoreGraphicsContext.mm)
  228621. /*** Start of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  228622. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228623. // compiled on its own).
  228624. #if JUCE_INCLUDED_FILE
  228625. class CoreGraphicsImage : public Image::SharedImage
  228626. {
  228627. public:
  228628. CoreGraphicsImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  228629. : Image::SharedImage (format_, width_, height_)
  228630. {
  228631. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  228632. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  228633. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  228634. imageData = imageDataAllocated;
  228635. CGColorSpaceRef colourSpace = (format == Image::SingleChannel) ? CGColorSpaceCreateDeviceGray()
  228636. : CGColorSpaceCreateDeviceRGB();
  228637. context = CGBitmapContextCreate (imageData, width, height, 8, lineStride,
  228638. colourSpace, getCGImageFlags (format_));
  228639. CGColorSpaceRelease (colourSpace);
  228640. }
  228641. ~CoreGraphicsImage()
  228642. {
  228643. CGContextRelease (context);
  228644. }
  228645. Image::ImageType getType() const { return Image::NativeImage; }
  228646. LowLevelGraphicsContext* createLowLevelContext();
  228647. SharedImage* clone()
  228648. {
  228649. CoreGraphicsImage* im = new CoreGraphicsImage (format, width, height, false);
  228650. memcpy (im->imageData, imageData, lineStride * height);
  228651. return im;
  228652. }
  228653. static CGImageRef createImage (const Image& juceImage, const bool forAlpha, CGColorSpaceRef colourSpace)
  228654. {
  228655. const CoreGraphicsImage* nativeImage = dynamic_cast <const CoreGraphicsImage*> (juceImage.getSharedImage());
  228656. if (nativeImage != 0 && (juceImage.getFormat() == Image::SingleChannel || ! forAlpha))
  228657. {
  228658. return CGBitmapContextCreateImage (nativeImage->context);
  228659. }
  228660. else
  228661. {
  228662. const Image::BitmapData srcData (juceImage, 0, 0, juceImage.getWidth(), juceImage.getHeight());
  228663. CGDataProviderRef provider = CGDataProviderCreateWithData (0, srcData.data, srcData.lineStride * srcData.height, 0);
  228664. CGImageRef imageRef = CGImageCreate (srcData.width, srcData.height,
  228665. 8, srcData.pixelStride * 8, srcData.lineStride,
  228666. colourSpace, getCGImageFlags (juceImage.getFormat()), provider,
  228667. 0, true, kCGRenderingIntentDefault);
  228668. CGDataProviderRelease (provider);
  228669. return imageRef;
  228670. }
  228671. }
  228672. #if JUCE_MAC
  228673. static NSImage* createNSImage (const Image& image)
  228674. {
  228675. const ScopedAutoReleasePool pool;
  228676. NSImage* im = [[NSImage alloc] init];
  228677. [im setSize: NSMakeSize (image.getWidth(), image.getHeight())];
  228678. [im lockFocus];
  228679. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  228680. CGImageRef imageRef = createImage (image, false, colourSpace);
  228681. CGColorSpaceRelease (colourSpace);
  228682. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  228683. CGContextDrawImage (cg, CGRectMake (0, 0, image.getWidth(), image.getHeight()), imageRef);
  228684. CGImageRelease (imageRef);
  228685. [im unlockFocus];
  228686. return im;
  228687. }
  228688. #endif
  228689. CGContextRef context;
  228690. HeapBlock<uint8> imageDataAllocated;
  228691. private:
  228692. static CGBitmapInfo getCGImageFlags (const Image::PixelFormat& format)
  228693. {
  228694. #if JUCE_BIG_ENDIAN
  228695. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big) : kCGBitmapByteOrderDefault;
  228696. #else
  228697. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little) : kCGBitmapByteOrderDefault;
  228698. #endif
  228699. }
  228700. };
  228701. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  228702. {
  228703. #if USE_COREGRAPHICS_RENDERING
  228704. return new CoreGraphicsImage (format == RGB ? ARGB : format, width, height, clearImage);
  228705. #else
  228706. return createSoftwareImage (format, width, height, clearImage);
  228707. #endif
  228708. }
  228709. class CoreGraphicsContext : public LowLevelGraphicsContext
  228710. {
  228711. public:
  228712. CoreGraphicsContext (CGContextRef context_, const float flipHeight_)
  228713. : context (context_),
  228714. flipHeight (flipHeight_),
  228715. state (new SavedState()),
  228716. numGradientLookupEntries (0),
  228717. lastClipRectIsValid (false)
  228718. {
  228719. CGContextRetain (context);
  228720. CGContextSaveGState(context);
  228721. CGContextSetShouldSmoothFonts (context, true);
  228722. CGContextSetShouldAntialias (context, true);
  228723. CGContextSetBlendMode (context, kCGBlendModeNormal);
  228724. rgbColourSpace = CGColorSpaceCreateDeviceRGB();
  228725. greyColourSpace = CGColorSpaceCreateDeviceGray();
  228726. gradientCallbacks.version = 0;
  228727. gradientCallbacks.evaluate = gradientCallback;
  228728. gradientCallbacks.releaseInfo = 0;
  228729. setFont (Font());
  228730. }
  228731. ~CoreGraphicsContext()
  228732. {
  228733. CGContextRestoreGState (context);
  228734. CGContextRelease (context);
  228735. CGColorSpaceRelease (rgbColourSpace);
  228736. CGColorSpaceRelease (greyColourSpace);
  228737. }
  228738. bool isVectorDevice() const { return false; }
  228739. void setOrigin (int x, int y)
  228740. {
  228741. CGContextTranslateCTM (context, x, -y);
  228742. if (lastClipRectIsValid)
  228743. lastClipRect.translate (-x, -y);
  228744. }
  228745. bool clipToRectangle (const Rectangle<int>& r)
  228746. {
  228747. CGContextClipToRect (context, CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()));
  228748. if (lastClipRectIsValid)
  228749. {
  228750. lastClipRect = lastClipRect.getIntersection (r);
  228751. return ! lastClipRect.isEmpty();
  228752. }
  228753. return ! isClipEmpty();
  228754. }
  228755. bool clipToRectangleList (const RectangleList& clipRegion)
  228756. {
  228757. if (clipRegion.isEmpty())
  228758. {
  228759. CGContextClipToRect (context, CGRectMake (0, 0, 0, 0));
  228760. lastClipRectIsValid = true;
  228761. lastClipRect = Rectangle<int>();
  228762. return false;
  228763. }
  228764. else
  228765. {
  228766. const int numRects = clipRegion.getNumRectangles();
  228767. HeapBlock <CGRect> rects (numRects);
  228768. for (int i = 0; i < numRects; ++i)
  228769. {
  228770. const Rectangle<int>& r = clipRegion.getRectangle(i);
  228771. rects[i] = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  228772. }
  228773. CGContextClipToRects (context, rects, numRects);
  228774. lastClipRectIsValid = false;
  228775. return ! isClipEmpty();
  228776. }
  228777. }
  228778. void excludeClipRectangle (const Rectangle<int>& r)
  228779. {
  228780. RectangleList remaining (getClipBounds());
  228781. remaining.subtract (r);
  228782. clipToRectangleList (remaining);
  228783. lastClipRectIsValid = false;
  228784. }
  228785. void clipToPath (const Path& path, const AffineTransform& transform)
  228786. {
  228787. createPath (path, transform);
  228788. CGContextClip (context);
  228789. lastClipRectIsValid = false;
  228790. }
  228791. void clipToImageAlpha (const Image& sourceImage, const Rectangle<int>& srcClip, const AffineTransform& transform)
  228792. {
  228793. if (! transform.isSingularity())
  228794. {
  228795. Image singleChannelImage (sourceImage);
  228796. if (sourceImage.getFormat() != Image::SingleChannel)
  228797. singleChannelImage = sourceImage.convertedToFormat (Image::SingleChannel);
  228798. CGImageRef image = CoreGraphicsImage::createImage (singleChannelImage, true, greyColourSpace);
  228799. if (srcClip != sourceImage.getBounds())
  228800. {
  228801. CGImageRef fullImage = image;
  228802. image = CGImageCreateWithImageInRect (fullImage, CGRectMake (srcClip.getX(), srcClip.getY(),
  228803. srcClip.getWidth(), srcClip.getHeight()));
  228804. CGImageRelease (fullImage);
  228805. }
  228806. flip();
  228807. AffineTransform t (AffineTransform::scale (1.0f, -1.0f).translated (0, srcClip.getHeight()).followedBy (transform));
  228808. applyTransform (t);
  228809. CGRect r = CGRectMake (0, 0, srcClip.getWidth(), srcClip.getHeight());
  228810. CGContextClipToMask (context, r, image);
  228811. applyTransform (t.inverted());
  228812. flip();
  228813. CGImageRelease (image);
  228814. lastClipRectIsValid = false;
  228815. }
  228816. }
  228817. bool clipRegionIntersects (const Rectangle<int>& r)
  228818. {
  228819. return getClipBounds().intersects (r);
  228820. }
  228821. const Rectangle<int> getClipBounds() const
  228822. {
  228823. if (! lastClipRectIsValid)
  228824. {
  228825. CGRect bounds = CGRectIntegral (CGContextGetClipBoundingBox (context));
  228826. lastClipRectIsValid = true;
  228827. lastClipRect.setBounds (roundToInt (bounds.origin.x),
  228828. roundToInt (flipHeight - (bounds.origin.y + bounds.size.height)),
  228829. roundToInt (bounds.size.width),
  228830. roundToInt (bounds.size.height));
  228831. }
  228832. return lastClipRect;
  228833. }
  228834. bool isClipEmpty() const
  228835. {
  228836. return getClipBounds().isEmpty();
  228837. }
  228838. void saveState()
  228839. {
  228840. CGContextSaveGState (context);
  228841. stateStack.add (new SavedState (*state));
  228842. }
  228843. void restoreState()
  228844. {
  228845. CGContextRestoreGState (context);
  228846. SavedState* const top = stateStack.getLast();
  228847. if (top != 0)
  228848. {
  228849. state = top;
  228850. stateStack.removeLast (1, false);
  228851. lastClipRectIsValid = false;
  228852. }
  228853. else
  228854. {
  228855. jassertfalse; // trying to pop with an empty stack!
  228856. }
  228857. }
  228858. void setFill (const FillType& fillType)
  228859. {
  228860. state->fillType = fillType;
  228861. if (fillType.isColour())
  228862. {
  228863. CGContextSetRGBFillColor (context, fillType.colour.getFloatRed(), fillType.colour.getFloatGreen(),
  228864. fillType.colour.getFloatBlue(), fillType.colour.getFloatAlpha());
  228865. CGContextSetAlpha (context, 1.0f);
  228866. }
  228867. }
  228868. void setOpacity (float newOpacity)
  228869. {
  228870. state->fillType.setOpacity (newOpacity);
  228871. setFill (state->fillType);
  228872. }
  228873. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  228874. {
  228875. CGContextSetInterpolationQuality (context, quality == Graphics::lowResamplingQuality
  228876. ? kCGInterpolationLow
  228877. : kCGInterpolationHigh);
  228878. }
  228879. void fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  228880. {
  228881. CGRect cgRect = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  228882. if (replaceExistingContents)
  228883. {
  228884. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  228885. CGContextClearRect (context, cgRect);
  228886. #else
  228887. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  228888. if (CGContextDrawLinearGradient == 0) // (just a way of checking whether we're running in 10.5 or later)
  228889. CGContextClearRect (context, cgRect);
  228890. else
  228891. #endif
  228892. CGContextSetBlendMode (context, kCGBlendModeCopy);
  228893. #endif
  228894. fillRect (r, false);
  228895. CGContextSetBlendMode (context, kCGBlendModeNormal);
  228896. }
  228897. else
  228898. {
  228899. if (state->fillType.isColour())
  228900. {
  228901. CGContextFillRect (context, cgRect);
  228902. }
  228903. else if (state->fillType.isGradient())
  228904. {
  228905. CGContextSaveGState (context);
  228906. CGContextClipToRect (context, cgRect);
  228907. drawGradient();
  228908. CGContextRestoreGState (context);
  228909. }
  228910. else
  228911. {
  228912. CGContextSaveGState (context);
  228913. CGContextClipToRect (context, cgRect);
  228914. drawImage (state->fillType.image, state->fillType.image.getBounds(), state->fillType.transform, true);
  228915. CGContextRestoreGState (context);
  228916. }
  228917. }
  228918. }
  228919. void fillPath (const Path& path, const AffineTransform& transform)
  228920. {
  228921. CGContextSaveGState (context);
  228922. if (state->fillType.isColour())
  228923. {
  228924. flip();
  228925. applyTransform (transform);
  228926. createPath (path);
  228927. if (path.isUsingNonZeroWinding())
  228928. CGContextFillPath (context);
  228929. else
  228930. CGContextEOFillPath (context);
  228931. }
  228932. else
  228933. {
  228934. createPath (path, transform);
  228935. if (path.isUsingNonZeroWinding())
  228936. CGContextClip (context);
  228937. else
  228938. CGContextEOClip (context);
  228939. if (state->fillType.isGradient())
  228940. drawGradient();
  228941. else
  228942. drawImage (state->fillType.image, state->fillType.image.getBounds(), state->fillType.transform, true);
  228943. }
  228944. CGContextRestoreGState (context);
  228945. }
  228946. void drawImage (const Image& sourceImage, const Rectangle<int>& srcClip,
  228947. const AffineTransform& transform, const bool fillEntireClipAsTiles)
  228948. {
  228949. jassert (sourceImage.getBounds().contains (srcClip));
  228950. CGImageRef fullImage = CoreGraphicsImage::createImage (sourceImage, false, rgbColourSpace);
  228951. CGImageRef image = fullImage;
  228952. if (srcClip != sourceImage.getBounds())
  228953. {
  228954. image = CGImageCreateWithImageInRect (fullImage, CGRectMake (srcClip.getX(), srcClip.getY(),
  228955. srcClip.getWidth(), srcClip.getHeight()));
  228956. CGImageRelease (fullImage);
  228957. }
  228958. CGContextSaveGState (context);
  228959. CGContextSetAlpha (context, state->fillType.getOpacity());
  228960. flip();
  228961. applyTransform (AffineTransform::scale (1.0f, -1.0f).translated (0, srcClip.getHeight()).followedBy (transform));
  228962. CGRect imageRect = CGRectMake (0, 0, srcClip.getWidth(), srcClip.getHeight());
  228963. if (fillEntireClipAsTiles)
  228964. {
  228965. #if JUCE_IPHONE
  228966. CGContextDrawTiledImage (context, imageRect, image);
  228967. #else
  228968. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  228969. // There's a bug in CGContextDrawTiledImage that makes it incredibly slow
  228970. // if it's doing a transformation - it's quicker to just draw lots of images manually
  228971. if (CGContextDrawTiledImage != 0 && transform.isOnlyTranslation())
  228972. CGContextDrawTiledImage (context, imageRect, image);
  228973. else
  228974. #endif
  228975. {
  228976. // Fallback to manually doing a tiled fill on 10.4
  228977. CGRect clip = CGRectIntegral (CGContextGetClipBoundingBox (context));
  228978. const int iw = srcClip.getWidth();
  228979. const int ih = srcClip.getHeight();
  228980. int x = 0, y = 0;
  228981. while (x > clip.origin.x) x -= iw;
  228982. while (y > clip.origin.y) y -= ih;
  228983. const int right = (int) (clip.origin.x + clip.size.width);
  228984. const int bottom = (int) (clip.origin.y + clip.size.height);
  228985. while (y < bottom)
  228986. {
  228987. for (int x2 = x; x2 < right; x2 += iw)
  228988. CGContextDrawImage (context, CGRectMake (x2, y, iw, ih), image);
  228989. y += ih;
  228990. }
  228991. }
  228992. #endif
  228993. }
  228994. else
  228995. {
  228996. CGContextDrawImage (context, imageRect, image);
  228997. }
  228998. CGImageRelease (image); // (This causes a memory bug in iPhone sim 3.0 - try upgrading to a later version if you hit this)
  228999. CGContextRestoreGState (context);
  229000. }
  229001. void drawLine (const Line<float>& line)
  229002. {
  229003. CGContextSetLineCap (context, kCGLineCapSquare);
  229004. CGContextSetLineWidth (context, 1.0f);
  229005. CGContextSetRGBStrokeColor (context,
  229006. state->fillType.colour.getFloatRed(), state->fillType.colour.getFloatGreen(),
  229007. state->fillType.colour.getFloatBlue(), state->fillType.colour.getFloatAlpha());
  229008. CGPoint cgLine[] = { { (CGFloat) line.getStartX(), flipHeight - (CGFloat) line.getStartY() },
  229009. { (CGFloat) line.getEndX(), flipHeight - (CGFloat) line.getEndY() } };
  229010. CGContextStrokeLineSegments (context, cgLine, 1);
  229011. }
  229012. void drawVerticalLine (const int x, float top, float bottom)
  229013. {
  229014. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  229015. CGContextFillRect (context, CGRectMake (x, flipHeight - bottom, 1.0f, bottom - top));
  229016. #else
  229017. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  229018. // the x co-ord slightly to trick it..
  229019. CGContextFillRect (context, CGRectMake (x + 1.0f / 256.0f, flipHeight - bottom, 1.0f + 1.0f / 256.0f, bottom - top));
  229020. #endif
  229021. }
  229022. void drawHorizontalLine (const int y, float left, float right)
  229023. {
  229024. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  229025. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + 1.0f), right - left, 1.0f));
  229026. #else
  229027. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  229028. // the x co-ord slightly to trick it..
  229029. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + (1.0f + 1.0f / 256.0f)), right - left, 1.0f + 1.0f / 256.0f));
  229030. #endif
  229031. }
  229032. void setFont (const Font& newFont)
  229033. {
  229034. if (state->font != newFont)
  229035. {
  229036. state->fontRef = 0;
  229037. state->font = newFont;
  229038. MacTypeface* mf = dynamic_cast <MacTypeface*> (state->font.getTypeface());
  229039. if (mf != 0)
  229040. {
  229041. state->fontRef = mf->fontRef;
  229042. CGContextSetFont (context, state->fontRef);
  229043. CGContextSetFontSize (context, state->font.getHeight() * mf->fontHeightToCGSizeFactor);
  229044. state->fontTransform = mf->renderingTransform;
  229045. state->fontTransform.a *= state->font.getHorizontalScale();
  229046. CGContextSetTextMatrix (context, state->fontTransform);
  229047. }
  229048. }
  229049. }
  229050. const Font getFont()
  229051. {
  229052. return state->font;
  229053. }
  229054. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  229055. {
  229056. if (state->fontRef != 0 && state->fillType.isColour())
  229057. {
  229058. if (transform.isOnlyTranslation())
  229059. {
  229060. CGContextSetTextMatrix (context, state->fontTransform); // have to set this each time, as it's not saved as part of the state
  229061. CGGlyph g = glyphNumber;
  229062. CGContextShowGlyphsAtPoint (context, transform.getTranslationX(),
  229063. flipHeight - roundToInt (transform.getTranslationY()), &g, 1);
  229064. }
  229065. else
  229066. {
  229067. CGContextSaveGState (context);
  229068. flip();
  229069. applyTransform (transform);
  229070. CGAffineTransform t = state->fontTransform;
  229071. t.d = -t.d;
  229072. CGContextSetTextMatrix (context, t);
  229073. CGGlyph g = glyphNumber;
  229074. CGContextShowGlyphsAtPoint (context, 0, 0, &g, 1);
  229075. CGContextRestoreGState (context);
  229076. }
  229077. }
  229078. else
  229079. {
  229080. Path p;
  229081. Font& f = state->font;
  229082. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  229083. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight())
  229084. .followedBy (transform));
  229085. }
  229086. }
  229087. private:
  229088. CGContextRef context;
  229089. const CGFloat flipHeight;
  229090. CGColorSpaceRef rgbColourSpace, greyColourSpace;
  229091. CGFunctionCallbacks gradientCallbacks;
  229092. mutable Rectangle<int> lastClipRect;
  229093. mutable bool lastClipRectIsValid;
  229094. struct SavedState
  229095. {
  229096. SavedState()
  229097. : font (1.0f), fontRef (0), fontTransform (CGAffineTransformIdentity)
  229098. {
  229099. }
  229100. SavedState (const SavedState& other)
  229101. : fillType (other.fillType), font (other.font), fontRef (other.fontRef),
  229102. fontTransform (other.fontTransform)
  229103. {
  229104. }
  229105. ~SavedState()
  229106. {
  229107. }
  229108. FillType fillType;
  229109. Font font;
  229110. CGFontRef fontRef;
  229111. CGAffineTransform fontTransform;
  229112. };
  229113. ScopedPointer <SavedState> state;
  229114. OwnedArray <SavedState> stateStack;
  229115. HeapBlock <PixelARGB> gradientLookupTable;
  229116. int numGradientLookupEntries;
  229117. static void gradientCallback (void* info, const CGFloat* inData, CGFloat* outData)
  229118. {
  229119. const CoreGraphicsContext* const g = static_cast <const CoreGraphicsContext*> (info);
  229120. const int index = roundToInt (g->numGradientLookupEntries * inData[0]);
  229121. PixelARGB colour (g->gradientLookupTable [jlimit (0, g->numGradientLookupEntries, index)]);
  229122. colour.unpremultiply();
  229123. outData[0] = colour.getRed() / 255.0f;
  229124. outData[1] = colour.getGreen() / 255.0f;
  229125. outData[2] = colour.getBlue() / 255.0f;
  229126. outData[3] = colour.getAlpha() / 255.0f;
  229127. }
  229128. CGShadingRef createGradient (const AffineTransform& transform, ColourGradient gradient)
  229129. {
  229130. numGradientLookupEntries = gradient.createLookupTable (transform, gradientLookupTable);
  229131. --numGradientLookupEntries;
  229132. CGShadingRef result = 0;
  229133. CGFunctionRef function = CGFunctionCreate (this, 1, 0, 4, 0, &gradientCallbacks);
  229134. CGPoint p1 (CGPointMake (gradient.point1.getX(), gradient.point1.getY()));
  229135. if (gradient.isRadial)
  229136. {
  229137. result = CGShadingCreateRadial (rgbColourSpace, p1, 0,
  229138. p1, gradient.point1.getDistanceFrom (gradient.point2),
  229139. function, true, true);
  229140. }
  229141. else
  229142. {
  229143. result = CGShadingCreateAxial (rgbColourSpace, p1,
  229144. CGPointMake (gradient.point2.getX(), gradient.point2.getY()),
  229145. function, true, true);
  229146. }
  229147. CGFunctionRelease (function);
  229148. return result;
  229149. }
  229150. void drawGradient()
  229151. {
  229152. flip();
  229153. applyTransform (state->fillType.transform);
  229154. CGContextSetInterpolationQuality (context, kCGInterpolationDefault); // (This is required for 10.4, where there's a crash if
  229155. // you draw a gradient with high quality interp enabled).
  229156. CGShadingRef shading = createGradient (state->fillType.transform, *(state->fillType.gradient));
  229157. CGContextSetAlpha (context, state->fillType.getOpacity());
  229158. CGContextDrawShading (context, shading);
  229159. CGShadingRelease (shading);
  229160. }
  229161. void createPath (const Path& path) const
  229162. {
  229163. CGContextBeginPath (context);
  229164. Path::Iterator i (path);
  229165. while (i.next())
  229166. {
  229167. switch (i.elementType)
  229168. {
  229169. case Path::Iterator::startNewSubPath: CGContextMoveToPoint (context, i.x1, i.y1); break;
  229170. case Path::Iterator::lineTo: CGContextAddLineToPoint (context, i.x1, i.y1); break;
  229171. case Path::Iterator::quadraticTo: CGContextAddQuadCurveToPoint (context, i.x1, i.y1, i.x2, i.y2); break;
  229172. case Path::Iterator::cubicTo: CGContextAddCurveToPoint (context, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3); break;
  229173. case Path::Iterator::closePath: CGContextClosePath (context); break;
  229174. default: jassertfalse; break;
  229175. }
  229176. }
  229177. }
  229178. void createPath (const Path& path, const AffineTransform& transform) const
  229179. {
  229180. CGContextBeginPath (context);
  229181. Path::Iterator i (path);
  229182. while (i.next())
  229183. {
  229184. switch (i.elementType)
  229185. {
  229186. case Path::Iterator::startNewSubPath:
  229187. transform.transformPoint (i.x1, i.y1);
  229188. CGContextMoveToPoint (context, i.x1, flipHeight - i.y1);
  229189. break;
  229190. case Path::Iterator::lineTo:
  229191. transform.transformPoint (i.x1, i.y1);
  229192. CGContextAddLineToPoint (context, i.x1, flipHeight - i.y1);
  229193. break;
  229194. case Path::Iterator::quadraticTo:
  229195. transform.transformPoint (i.x1, i.y1);
  229196. transform.transformPoint (i.x2, i.y2);
  229197. CGContextAddQuadCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2);
  229198. break;
  229199. case Path::Iterator::cubicTo:
  229200. transform.transformPoint (i.x1, i.y1);
  229201. transform.transformPoint (i.x2, i.y2);
  229202. transform.transformPoint (i.x3, i.y3);
  229203. CGContextAddCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2, i.x3, flipHeight - i.y3);
  229204. break;
  229205. case Path::Iterator::closePath:
  229206. CGContextClosePath (context); break;
  229207. default:
  229208. jassertfalse;
  229209. break;
  229210. }
  229211. }
  229212. }
  229213. void flip() const
  229214. {
  229215. CGContextConcatCTM (context, CGAffineTransformMake (1, 0, 0, -1, 0, flipHeight));
  229216. }
  229217. void applyTransform (const AffineTransform& transform) const
  229218. {
  229219. CGAffineTransform t;
  229220. t.a = transform.mat00;
  229221. t.b = transform.mat10;
  229222. t.c = transform.mat01;
  229223. t.d = transform.mat11;
  229224. t.tx = transform.mat02;
  229225. t.ty = transform.mat12;
  229226. CGContextConcatCTM (context, t);
  229227. }
  229228. CoreGraphicsContext (const CoreGraphicsContext&);
  229229. CoreGraphicsContext& operator= (const CoreGraphicsContext&);
  229230. };
  229231. LowLevelGraphicsContext* CoreGraphicsImage::createLowLevelContext()
  229232. {
  229233. return new CoreGraphicsContext (context, height);
  229234. }
  229235. #endif
  229236. /*** End of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  229237. /*** Start of inlined file: juce_mac_NSViewComponentPeer.mm ***/
  229238. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229239. // compiled on its own).
  229240. #if JUCE_INCLUDED_FILE
  229241. class NSViewComponentPeer;
  229242. END_JUCE_NAMESPACE
  229243. #define JuceNSView MakeObjCClassName(JuceNSView)
  229244. @interface JuceNSView : NSView<NSTextInput>
  229245. {
  229246. @public
  229247. NSViewComponentPeer* owner;
  229248. NSNotificationCenter* notificationCenter;
  229249. String* stringBeingComposed;
  229250. bool textWasInserted;
  229251. }
  229252. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner withFrame: (NSRect) frame;
  229253. - (void) dealloc;
  229254. - (BOOL) isOpaque;
  229255. - (void) drawRect: (NSRect) r;
  229256. - (void) mouseDown: (NSEvent*) ev;
  229257. - (void) asyncMouseDown: (NSEvent*) ev;
  229258. - (void) mouseUp: (NSEvent*) ev;
  229259. - (void) asyncMouseUp: (NSEvent*) ev;
  229260. - (void) mouseDragged: (NSEvent*) ev;
  229261. - (void) mouseMoved: (NSEvent*) ev;
  229262. - (void) mouseEntered: (NSEvent*) ev;
  229263. - (void) mouseExited: (NSEvent*) ev;
  229264. - (void) rightMouseDown: (NSEvent*) ev;
  229265. - (void) rightMouseDragged: (NSEvent*) ev;
  229266. - (void) rightMouseUp: (NSEvent*) ev;
  229267. - (void) otherMouseDown: (NSEvent*) ev;
  229268. - (void) otherMouseDragged: (NSEvent*) ev;
  229269. - (void) otherMouseUp: (NSEvent*) ev;
  229270. - (void) scrollWheel: (NSEvent*) ev;
  229271. - (BOOL) acceptsFirstMouse: (NSEvent*) ev;
  229272. - (void) frameChanged: (NSNotification*) n;
  229273. - (void) viewDidMoveToWindow;
  229274. - (void) keyDown: (NSEvent*) ev;
  229275. - (void) keyUp: (NSEvent*) ev;
  229276. // NSTextInput Methods
  229277. - (void) insertText: (id) aString;
  229278. - (void) doCommandBySelector: (SEL) aSelector;
  229279. - (void) setMarkedText: (id) aString selectedRange: (NSRange) selRange;
  229280. - (void) unmarkText;
  229281. - (BOOL) hasMarkedText;
  229282. - (long) conversationIdentifier;
  229283. - (NSAttributedString*) attributedSubstringFromRange: (NSRange) theRange;
  229284. - (NSRange) markedRange;
  229285. - (NSRange) selectedRange;
  229286. - (NSRect) firstRectForCharacterRange: (NSRange) theRange;
  229287. - (unsigned int) characterIndexForPoint: (NSPoint) thePoint;
  229288. - (NSArray*) validAttributesForMarkedText;
  229289. - (void) flagsChanged: (NSEvent*) ev;
  229290. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  229291. - (BOOL) performKeyEquivalent: (NSEvent*) ev;
  229292. #endif
  229293. - (BOOL) becomeFirstResponder;
  229294. - (BOOL) resignFirstResponder;
  229295. - (BOOL) acceptsFirstResponder;
  229296. - (void) asyncRepaint: (id) rect;
  229297. - (NSArray*) getSupportedDragTypes;
  229298. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender;
  229299. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender;
  229300. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender;
  229301. - (void) draggingEnded: (id <NSDraggingInfo>) sender;
  229302. - (void) draggingExited: (id <NSDraggingInfo>) sender;
  229303. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender;
  229304. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender;
  229305. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender;
  229306. @end
  229307. #define JuceNSWindow MakeObjCClassName(JuceNSWindow)
  229308. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  229309. @interface JuceNSWindow : NSWindow <NSWindowDelegate>
  229310. #else
  229311. @interface JuceNSWindow : NSWindow
  229312. #endif
  229313. {
  229314. @private
  229315. NSViewComponentPeer* owner;
  229316. bool isZooming;
  229317. }
  229318. - (void) setOwner: (NSViewComponentPeer*) owner;
  229319. - (BOOL) canBecomeKeyWindow;
  229320. - (void) becomeKeyWindow;
  229321. - (BOOL) windowShouldClose: (id) window;
  229322. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen;
  229323. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize;
  229324. - (void) zoom: (id) sender;
  229325. @end
  229326. BEGIN_JUCE_NAMESPACE
  229327. class NSViewComponentPeer : public ComponentPeer
  229328. {
  229329. public:
  229330. NSViewComponentPeer (Component* const component,
  229331. const int windowStyleFlags,
  229332. NSView* viewToAttachTo);
  229333. ~NSViewComponentPeer();
  229334. void* getNativeHandle() const;
  229335. void setVisible (bool shouldBeVisible);
  229336. void setTitle (const String& title);
  229337. void setPosition (int x, int y);
  229338. void setSize (int w, int h);
  229339. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen);
  229340. const Rectangle<int> getBounds (const bool global) const;
  229341. const Rectangle<int> getBounds() const;
  229342. const Point<int> getScreenPosition() const;
  229343. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition);
  229344. const Point<int> globalPositionToRelative (const Point<int>& screenPosition);
  229345. void setMinimised (bool shouldBeMinimised);
  229346. bool isMinimised() const;
  229347. void setFullScreen (bool shouldBeFullScreen);
  229348. bool isFullScreen() const;
  229349. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const;
  229350. const BorderSize getFrameSize() const;
  229351. bool setAlwaysOnTop (bool alwaysOnTop);
  229352. void toFront (bool makeActiveWindow);
  229353. void toBehind (ComponentPeer* other);
  229354. void setIcon (const Image& newIcon);
  229355. const StringArray getAvailableRenderingEngines() throw();
  229356. int getCurrentRenderingEngine() throw();
  229357. void setCurrentRenderingEngine (int index) throw();
  229358. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  229359. for example having more than one juce plugin loaded into a host, then when a
  229360. method is called, the actual code that runs might actually be in a different module
  229361. than the one you expect... So any calls to library functions or statics that are
  229362. made inside obj-c methods will probably end up getting executed in a different DLL's
  229363. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  229364. To work around this insanity, I'm only allowing obj-c methods to make calls to
  229365. virtual methods of an object that's known to live inside the right module's space.
  229366. */
  229367. virtual void redirectMouseDown (NSEvent* ev);
  229368. virtual void redirectMouseUp (NSEvent* ev);
  229369. virtual void redirectMouseDrag (NSEvent* ev);
  229370. virtual void redirectMouseMove (NSEvent* ev);
  229371. virtual void redirectMouseEnter (NSEvent* ev);
  229372. virtual void redirectMouseExit (NSEvent* ev);
  229373. virtual void redirectMouseWheel (NSEvent* ev);
  229374. void sendMouseEvent (NSEvent* ev);
  229375. bool handleKeyEvent (NSEvent* ev, bool isKeyDown);
  229376. virtual bool redirectKeyDown (NSEvent* ev);
  229377. virtual bool redirectKeyUp (NSEvent* ev);
  229378. virtual void redirectModKeyChange (NSEvent* ev);
  229379. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  229380. virtual bool redirectPerformKeyEquivalent (NSEvent* ev);
  229381. #endif
  229382. virtual BOOL sendDragCallback (int type, id <NSDraggingInfo> sender);
  229383. virtual bool isOpaque();
  229384. virtual void drawRect (NSRect r);
  229385. virtual bool canBecomeKeyWindow();
  229386. virtual bool windowShouldClose();
  229387. virtual void redirectMovedOrResized();
  229388. virtual void viewMovedToWindow();
  229389. virtual NSRect constrainRect (NSRect r);
  229390. static void showArrowCursorIfNeeded();
  229391. static void updateModifiers (NSEvent* e);
  229392. static void updateKeysDown (NSEvent* ev, bool isKeyDown);
  229393. static int getKeyCodeFromEvent (NSEvent* ev)
  229394. {
  229395. const String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  229396. int keyCode = unmodified[0];
  229397. if (keyCode == 0x19) // (backwards-tab)
  229398. keyCode = '\t';
  229399. else if (keyCode == 0x03) // (enter)
  229400. keyCode = '\r';
  229401. return keyCode;
  229402. }
  229403. static int64 getMouseTime (NSEvent* e)
  229404. {
  229405. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  229406. + (int64) ([e timestamp] * 1000.0);
  229407. }
  229408. static const Point<int> getMousePos (NSEvent* e, NSView* view)
  229409. {
  229410. NSPoint p = [view convertPoint: [e locationInWindow] fromView: nil];
  229411. return Point<int> (roundToInt (p.x), roundToInt ([view frame].size.height - p.y));
  229412. }
  229413. static int getModifierForButtonNumber (const NSInteger num)
  229414. {
  229415. return num == 0 ? ModifierKeys::leftButtonModifier
  229416. : (num == 1 ? ModifierKeys::rightButtonModifier
  229417. : (num == 2 ? ModifierKeys::middleButtonModifier : 0));
  229418. }
  229419. virtual void viewFocusGain();
  229420. virtual void viewFocusLoss();
  229421. bool isFocused() const;
  229422. void grabFocus();
  229423. void textInputRequired (const Point<int>& position);
  229424. void repaint (const Rectangle<int>& area);
  229425. void performAnyPendingRepaintsNow();
  229426. juce_UseDebuggingNewOperator
  229427. NSWindow* window;
  229428. JuceNSView* view;
  229429. bool isSharedWindow, fullScreen, insideDrawRect, usingCoreGraphics, recursiveToFrontCall;
  229430. static ModifierKeys currentModifiers;
  229431. static ComponentPeer* currentlyFocusedPeer;
  229432. static Array<int> keysCurrentlyDown;
  229433. };
  229434. END_JUCE_NAMESPACE
  229435. @implementation JuceNSView
  229436. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner_
  229437. withFrame: (NSRect) frame
  229438. {
  229439. [super initWithFrame: frame];
  229440. owner = owner_;
  229441. stringBeingComposed = 0;
  229442. textWasInserted = false;
  229443. notificationCenter = [NSNotificationCenter defaultCenter];
  229444. [notificationCenter addObserver: self
  229445. selector: @selector (frameChanged:)
  229446. name: NSViewFrameDidChangeNotification
  229447. object: self];
  229448. if (! owner_->isSharedWindow)
  229449. {
  229450. [notificationCenter addObserver: self
  229451. selector: @selector (frameChanged:)
  229452. name: NSWindowDidMoveNotification
  229453. object: owner_->window];
  229454. }
  229455. [self registerForDraggedTypes: [self getSupportedDragTypes]];
  229456. return self;
  229457. }
  229458. - (void) dealloc
  229459. {
  229460. [notificationCenter removeObserver: self];
  229461. delete stringBeingComposed;
  229462. [super dealloc];
  229463. }
  229464. - (void) drawRect: (NSRect) r
  229465. {
  229466. if (owner != 0)
  229467. owner->drawRect (r);
  229468. }
  229469. - (BOOL) isOpaque
  229470. {
  229471. return owner == 0 || owner->isOpaque();
  229472. }
  229473. - (void) mouseDown: (NSEvent*) ev
  229474. {
  229475. // In some host situations, the host will stop modal loops from working
  229476. // correctly if they're called from a mouse event, so we'll trigger
  229477. // the event asynchronously..
  229478. if (JUCEApplication::getInstance() == 0)
  229479. [self performSelectorOnMainThread: @selector (asyncMouseDown:)
  229480. withObject: ev
  229481. waitUntilDone: NO];
  229482. else
  229483. [self asyncMouseDown: ev];
  229484. }
  229485. - (void) asyncMouseDown: (NSEvent*) ev
  229486. {
  229487. if (owner != 0)
  229488. owner->redirectMouseDown (ev);
  229489. }
  229490. - (void) mouseUp: (NSEvent*) ev
  229491. {
  229492. // In some host situations, the host will stop modal loops from working
  229493. // correctly if they're called from a mouse event, so we'll trigger
  229494. // the event asynchronously..
  229495. if (JUCEApplication::getInstance() == 0)
  229496. [self performSelectorOnMainThread: @selector (asyncMouseUp:)
  229497. withObject: ev
  229498. waitUntilDone: NO];
  229499. else
  229500. [self asyncMouseUp: ev];
  229501. }
  229502. - (void) asyncMouseUp: (NSEvent*) ev
  229503. {
  229504. if (owner != 0)
  229505. owner->redirectMouseUp (ev);
  229506. }
  229507. - (void) mouseDragged: (NSEvent*) ev
  229508. {
  229509. if (owner != 0)
  229510. owner->redirectMouseDrag (ev);
  229511. }
  229512. - (void) mouseMoved: (NSEvent*) ev
  229513. {
  229514. if (owner != 0)
  229515. owner->redirectMouseMove (ev);
  229516. }
  229517. - (void) mouseEntered: (NSEvent*) ev
  229518. {
  229519. if (owner != 0)
  229520. owner->redirectMouseEnter (ev);
  229521. }
  229522. - (void) mouseExited: (NSEvent*) ev
  229523. {
  229524. if (owner != 0)
  229525. owner->redirectMouseExit (ev);
  229526. }
  229527. - (void) rightMouseDown: (NSEvent*) ev
  229528. {
  229529. [self mouseDown: ev];
  229530. }
  229531. - (void) rightMouseDragged: (NSEvent*) ev
  229532. {
  229533. [self mouseDragged: ev];
  229534. }
  229535. - (void) rightMouseUp: (NSEvent*) ev
  229536. {
  229537. [self mouseUp: ev];
  229538. }
  229539. - (void) otherMouseDown: (NSEvent*) ev
  229540. {
  229541. [self mouseDown: ev];
  229542. }
  229543. - (void) otherMouseDragged: (NSEvent*) ev
  229544. {
  229545. [self mouseDragged: ev];
  229546. }
  229547. - (void) otherMouseUp: (NSEvent*) ev
  229548. {
  229549. [self mouseUp: ev];
  229550. }
  229551. - (void) scrollWheel: (NSEvent*) ev
  229552. {
  229553. if (owner != 0)
  229554. owner->redirectMouseWheel (ev);
  229555. }
  229556. - (BOOL) acceptsFirstMouse: (NSEvent*) ev
  229557. {
  229558. (void) ev;
  229559. return YES;
  229560. }
  229561. - (void) frameChanged: (NSNotification*) n
  229562. {
  229563. (void) n;
  229564. if (owner != 0)
  229565. owner->redirectMovedOrResized();
  229566. }
  229567. - (void) viewDidMoveToWindow
  229568. {
  229569. if (owner != 0)
  229570. owner->viewMovedToWindow();
  229571. }
  229572. - (void) asyncRepaint: (id) rect
  229573. {
  229574. NSRect* r = (NSRect*) [((NSData*) rect) bytes];
  229575. [self setNeedsDisplayInRect: *r];
  229576. }
  229577. - (void) keyDown: (NSEvent*) ev
  229578. {
  229579. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  229580. textWasInserted = false;
  229581. if (target != 0)
  229582. [self interpretKeyEvents: [NSArray arrayWithObject: ev]];
  229583. else
  229584. deleteAndZero (stringBeingComposed);
  229585. if ((! textWasInserted) && (owner == 0 || ! owner->redirectKeyDown (ev)))
  229586. [super keyDown: ev];
  229587. }
  229588. - (void) keyUp: (NSEvent*) ev
  229589. {
  229590. if (owner == 0 || ! owner->redirectKeyUp (ev))
  229591. [super keyUp: ev];
  229592. }
  229593. - (void) insertText: (id) aString
  229594. {
  229595. // This commits multi-byte text when return is pressed, or after every keypress for western keyboards
  229596. if ([aString length] > 0)
  229597. {
  229598. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  229599. if (target != 0)
  229600. {
  229601. target->insertTextAtCaret (nsStringToJuce ([aString isKindOfClass: [NSAttributedString class]] ? [aString string] : aString));
  229602. textWasInserted = true;
  229603. }
  229604. }
  229605. deleteAndZero (stringBeingComposed);
  229606. }
  229607. - (void) doCommandBySelector: (SEL) aSelector
  229608. {
  229609. (void) aSelector;
  229610. }
  229611. - (void) setMarkedText: (id) aString selectedRange: (NSRange) selectionRange
  229612. {
  229613. (void) selectionRange;
  229614. if (stringBeingComposed == 0)
  229615. stringBeingComposed = new String();
  229616. *stringBeingComposed = nsStringToJuce ([aString isKindOfClass:[NSAttributedString class]] ? [aString string] : aString);
  229617. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  229618. if (target != 0)
  229619. {
  229620. const Range<int> currentHighlight (target->getHighlightedRegion());
  229621. target->insertTextAtCaret (*stringBeingComposed);
  229622. target->setHighlightedRegion (currentHighlight.withLength (stringBeingComposed->length()));
  229623. textWasInserted = true;
  229624. }
  229625. }
  229626. - (void) unmarkText
  229627. {
  229628. if (stringBeingComposed != 0)
  229629. {
  229630. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  229631. if (target != 0)
  229632. {
  229633. target->insertTextAtCaret (*stringBeingComposed);
  229634. textWasInserted = true;
  229635. }
  229636. }
  229637. deleteAndZero (stringBeingComposed);
  229638. }
  229639. - (BOOL) hasMarkedText
  229640. {
  229641. return stringBeingComposed != 0;
  229642. }
  229643. - (long) conversationIdentifier
  229644. {
  229645. return (long) (pointer_sized_int) self;
  229646. }
  229647. - (NSAttributedString*) attributedSubstringFromRange: (NSRange) theRange
  229648. {
  229649. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  229650. if (target != 0)
  229651. {
  229652. const Range<int> r ((int) theRange.location,
  229653. (int) (theRange.location + theRange.length));
  229654. return [[[NSAttributedString alloc] initWithString: juceStringToNS (target->getTextInRange (r))] autorelease];
  229655. }
  229656. return nil;
  229657. }
  229658. - (NSRange) markedRange
  229659. {
  229660. return stringBeingComposed != 0 ? NSMakeRange (0, stringBeingComposed->length())
  229661. : NSMakeRange (NSNotFound, 0);
  229662. }
  229663. - (NSRange) selectedRange
  229664. {
  229665. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  229666. if (target != 0)
  229667. {
  229668. const Range<int> highlight (target->getHighlightedRegion());
  229669. if (! highlight.isEmpty())
  229670. return NSMakeRange (highlight.getStart(), highlight.getLength());
  229671. }
  229672. return NSMakeRange (NSNotFound, 0);
  229673. }
  229674. - (NSRect) firstRectForCharacterRange: (NSRange) theRange
  229675. {
  229676. (void) theRange;
  229677. JUCE_NAMESPACE::Component* const comp = dynamic_cast <JUCE_NAMESPACE::Component*> (owner->findCurrentTextInputTarget());
  229678. if (comp == 0)
  229679. return NSMakeRect (0, 0, 0, 0);
  229680. const Rectangle<int> bounds (comp->getScreenBounds());
  229681. return NSMakeRect (bounds.getX(),
  229682. [[[NSScreen screens] objectAtIndex: 0] frame].size.height - bounds.getY(),
  229683. bounds.getWidth(),
  229684. bounds.getHeight());
  229685. }
  229686. - (unsigned int) characterIndexForPoint: (NSPoint) thePoint
  229687. {
  229688. (void) thePoint;
  229689. return NSNotFound;
  229690. }
  229691. - (NSArray*) validAttributesForMarkedText
  229692. {
  229693. return [NSArray array];
  229694. }
  229695. - (void) flagsChanged: (NSEvent*) ev
  229696. {
  229697. if (owner != 0)
  229698. owner->redirectModKeyChange (ev);
  229699. }
  229700. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  229701. - (BOOL) performKeyEquivalent: (NSEvent*) ev
  229702. {
  229703. if (owner != 0 && owner->redirectPerformKeyEquivalent (ev))
  229704. return true;
  229705. return [super performKeyEquivalent: ev];
  229706. }
  229707. #endif
  229708. - (BOOL) becomeFirstResponder
  229709. {
  229710. if (owner != 0)
  229711. owner->viewFocusGain();
  229712. return true;
  229713. }
  229714. - (BOOL) resignFirstResponder
  229715. {
  229716. if (owner != 0)
  229717. owner->viewFocusLoss();
  229718. return true;
  229719. }
  229720. - (BOOL) acceptsFirstResponder
  229721. {
  229722. return owner != 0 && owner->canBecomeKeyWindow();
  229723. }
  229724. - (NSArray*) getSupportedDragTypes
  229725. {
  229726. return [NSArray arrayWithObjects: NSFilenamesPboardType, /*NSFilesPromisePboardType, NSStringPboardType,*/ nil];
  229727. }
  229728. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender
  229729. {
  229730. return owner != 0 && owner->sendDragCallback (type, sender);
  229731. }
  229732. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender
  229733. {
  229734. if ([self sendDragCallback: 0 sender: sender])
  229735. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  229736. else
  229737. return NSDragOperationNone;
  229738. }
  229739. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender
  229740. {
  229741. if ([self sendDragCallback: 0 sender: sender])
  229742. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  229743. else
  229744. return NSDragOperationNone;
  229745. }
  229746. - (void) draggingEnded: (id <NSDraggingInfo>) sender
  229747. {
  229748. [self sendDragCallback: 1 sender: sender];
  229749. }
  229750. - (void) draggingExited: (id <NSDraggingInfo>) sender
  229751. {
  229752. [self sendDragCallback: 1 sender: sender];
  229753. }
  229754. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender
  229755. {
  229756. (void) sender;
  229757. return YES;
  229758. }
  229759. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender
  229760. {
  229761. return [self sendDragCallback: 2 sender: sender];
  229762. }
  229763. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender
  229764. {
  229765. (void) sender;
  229766. }
  229767. @end
  229768. @implementation JuceNSWindow
  229769. - (void) setOwner: (NSViewComponentPeer*) owner_
  229770. {
  229771. owner = owner_;
  229772. isZooming = false;
  229773. }
  229774. - (BOOL) canBecomeKeyWindow
  229775. {
  229776. return owner != 0 && owner->canBecomeKeyWindow();
  229777. }
  229778. - (void) becomeKeyWindow
  229779. {
  229780. [super becomeKeyWindow];
  229781. if (owner != 0)
  229782. owner->grabFocus();
  229783. }
  229784. - (BOOL) windowShouldClose: (id) window
  229785. {
  229786. (void) window;
  229787. return owner == 0 || owner->windowShouldClose();
  229788. }
  229789. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen
  229790. {
  229791. (void) screen;
  229792. if (owner != 0)
  229793. frameRect = owner->constrainRect (frameRect);
  229794. return frameRect;
  229795. }
  229796. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize
  229797. {
  229798. (void) window;
  229799. if (isZooming)
  229800. return proposedFrameSize;
  229801. NSRect frameRect = [self frame];
  229802. frameRect.origin.y -= proposedFrameSize.height - frameRect.size.height;
  229803. frameRect.size = proposedFrameSize;
  229804. if (owner != 0)
  229805. frameRect = owner->constrainRect (frameRect);
  229806. if (JUCE_NAMESPACE::Component::getCurrentlyModalComponent() != 0
  229807. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  229808. && (owner->getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowHasTitleBar) != 0)
  229809. JUCE_NAMESPACE::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  229810. return frameRect.size;
  229811. }
  229812. - (void) zoom: (id) sender
  229813. {
  229814. isZooming = true;
  229815. [super zoom: sender];
  229816. isZooming = false;
  229817. }
  229818. - (void) windowWillMove: (NSNotification*) notification
  229819. {
  229820. (void) notification;
  229821. if (JUCE_NAMESPACE::Component::getCurrentlyModalComponent() != 0
  229822. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  229823. && (owner->getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowHasTitleBar) != 0)
  229824. JUCE_NAMESPACE::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  229825. }
  229826. @end
  229827. BEGIN_JUCE_NAMESPACE
  229828. ModifierKeys NSViewComponentPeer::currentModifiers;
  229829. ComponentPeer* NSViewComponentPeer::currentlyFocusedPeer = 0;
  229830. Array<int> NSViewComponentPeer::keysCurrentlyDown;
  229831. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  229832. {
  229833. if (NSViewComponentPeer::keysCurrentlyDown.contains (keyCode))
  229834. return true;
  229835. if (keyCode >= 'A' && keyCode <= 'Z'
  229836. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toLowerCase ((juce_wchar) keyCode)))
  229837. return true;
  229838. if (keyCode >= 'a' && keyCode <= 'z'
  229839. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode)))
  229840. return true;
  229841. return false;
  229842. }
  229843. void NSViewComponentPeer::updateModifiers (NSEvent* e)
  229844. {
  229845. int m = 0;
  229846. if (([e modifierFlags] & NSShiftKeyMask) != 0) m |= ModifierKeys::shiftModifier;
  229847. if (([e modifierFlags] & NSControlKeyMask) != 0) m |= ModifierKeys::ctrlModifier;
  229848. if (([e modifierFlags] & NSAlternateKeyMask) != 0) m |= ModifierKeys::altModifier;
  229849. if (([e modifierFlags] & NSCommandKeyMask) != 0) m |= ModifierKeys::commandModifier;
  229850. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (m);
  229851. }
  229852. void NSViewComponentPeer::updateKeysDown (NSEvent* ev, bool isKeyDown)
  229853. {
  229854. updateModifiers (ev);
  229855. int keyCode = getKeyCodeFromEvent (ev);
  229856. if (keyCode != 0)
  229857. {
  229858. if (isKeyDown)
  229859. keysCurrentlyDown.addIfNotAlreadyThere (keyCode);
  229860. else
  229861. keysCurrentlyDown.removeValue (keyCode);
  229862. }
  229863. }
  229864. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  229865. {
  229866. return NSViewComponentPeer::currentModifiers;
  229867. }
  229868. void ModifierKeys::updateCurrentModifiers() throw()
  229869. {
  229870. currentModifiers = NSViewComponentPeer::currentModifiers;
  229871. }
  229872. NSViewComponentPeer::NSViewComponentPeer (Component* const component_,
  229873. const int windowStyleFlags,
  229874. NSView* viewToAttachTo)
  229875. : ComponentPeer (component_, windowStyleFlags),
  229876. window (0),
  229877. view (0),
  229878. isSharedWindow (viewToAttachTo != 0),
  229879. fullScreen (false),
  229880. insideDrawRect (false),
  229881. #if USE_COREGRAPHICS_RENDERING
  229882. usingCoreGraphics (true),
  229883. #else
  229884. usingCoreGraphics (false),
  229885. #endif
  229886. recursiveToFrontCall (false)
  229887. {
  229888. NSRect r;
  229889. r.origin.x = 0;
  229890. r.origin.y = 0;
  229891. r.size.width = (float) component->getWidth();
  229892. r.size.height = (float) component->getHeight();
  229893. view = [[JuceNSView alloc] initWithOwner: this withFrame: r];
  229894. [view setPostsFrameChangedNotifications: YES];
  229895. if (isSharedWindow)
  229896. {
  229897. window = [viewToAttachTo window];
  229898. [viewToAttachTo addSubview: view];
  229899. setVisible (component->isVisible());
  229900. }
  229901. else
  229902. {
  229903. r.origin.x = (float) component->getX();
  229904. r.origin.y = (float) component->getY();
  229905. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  229906. unsigned int style = 0;
  229907. if ((windowStyleFlags & windowHasTitleBar) == 0)
  229908. style = NSBorderlessWindowMask;
  229909. else
  229910. style = NSTitledWindowMask;
  229911. if ((windowStyleFlags & windowHasMinimiseButton) != 0)
  229912. style |= NSMiniaturizableWindowMask;
  229913. if ((windowStyleFlags & windowHasCloseButton) != 0)
  229914. style |= NSClosableWindowMask;
  229915. if ((windowStyleFlags & windowIsResizable) != 0)
  229916. style |= NSResizableWindowMask;
  229917. window = [[JuceNSWindow alloc] initWithContentRect: r
  229918. styleMask: style
  229919. backing: NSBackingStoreBuffered
  229920. defer: YES];
  229921. [((JuceNSWindow*) window) setOwner: this];
  229922. [window orderOut: nil];
  229923. [window setDelegate: (JuceNSWindow*) window];
  229924. [window setOpaque: component->isOpaque()];
  229925. [window setHasShadow: ((windowStyleFlags & windowHasDropShadow) != 0)];
  229926. if (component->isAlwaysOnTop())
  229927. [window setLevel: NSFloatingWindowLevel];
  229928. [window setContentView: view];
  229929. [window setAutodisplay: YES];
  229930. [window setAcceptsMouseMovedEvents: YES];
  229931. // We'll both retain and also release this on closing because plugin hosts can unexpectedly
  229932. // close the window for us, and also tend to get cause trouble if setReleasedWhenClosed is NO.
  229933. [window setReleasedWhenClosed: YES];
  229934. [window retain];
  229935. [window setExcludedFromWindowsMenu: (windowStyleFlags & windowIsTemporary) != 0];
  229936. [window setIgnoresMouseEvents: (windowStyleFlags & windowIgnoresMouseClicks) != 0];
  229937. }
  229938. setTitle (component->getName());
  229939. }
  229940. NSViewComponentPeer::~NSViewComponentPeer()
  229941. {
  229942. view->owner = 0;
  229943. [view removeFromSuperview];
  229944. [view release];
  229945. if (! isSharedWindow)
  229946. {
  229947. [((JuceNSWindow*) window) setOwner: 0];
  229948. [window close];
  229949. [window release];
  229950. }
  229951. }
  229952. void* NSViewComponentPeer::getNativeHandle() const
  229953. {
  229954. return view;
  229955. }
  229956. void NSViewComponentPeer::setVisible (bool shouldBeVisible)
  229957. {
  229958. if (isSharedWindow)
  229959. {
  229960. [view setHidden: ! shouldBeVisible];
  229961. }
  229962. else
  229963. {
  229964. if (shouldBeVisible)
  229965. {
  229966. [window orderFront: nil];
  229967. handleBroughtToFront();
  229968. }
  229969. else
  229970. {
  229971. [window orderOut: nil];
  229972. }
  229973. }
  229974. }
  229975. void NSViewComponentPeer::setTitle (const String& title)
  229976. {
  229977. const ScopedAutoReleasePool pool;
  229978. if (! isSharedWindow)
  229979. [window setTitle: juceStringToNS (title)];
  229980. }
  229981. void NSViewComponentPeer::setPosition (int x, int y)
  229982. {
  229983. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  229984. }
  229985. void NSViewComponentPeer::setSize (int w, int h)
  229986. {
  229987. setBounds (component->getX(), component->getY(), w, h, false);
  229988. }
  229989. void NSViewComponentPeer::setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  229990. {
  229991. fullScreen = isNowFullScreen;
  229992. w = jmax (0, w);
  229993. h = jmax (0, h);
  229994. NSRect r;
  229995. r.origin.x = (float) x;
  229996. r.origin.y = (float) y;
  229997. r.size.width = (float) w;
  229998. r.size.height = (float) h;
  229999. if (isSharedWindow)
  230000. {
  230001. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  230002. if ([view frame].size.width != r.size.width
  230003. || [view frame].size.height != r.size.height)
  230004. [view setNeedsDisplay: true];
  230005. [view setFrame: r];
  230006. }
  230007. else
  230008. {
  230009. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  230010. [window setFrame: [window frameRectForContentRect: r]
  230011. display: true];
  230012. }
  230013. }
  230014. const Rectangle<int> NSViewComponentPeer::getBounds (const bool global) const
  230015. {
  230016. NSRect r = [view frame];
  230017. if (global && [view window] != 0)
  230018. {
  230019. r = [view convertRect: r toView: nil];
  230020. NSRect wr = [[view window] frame];
  230021. r.origin.x += wr.origin.x;
  230022. r.origin.y += wr.origin.y;
  230023. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  230024. }
  230025. else
  230026. {
  230027. r.origin.y = [[view superview] frame].size.height - r.origin.y - r.size.height;
  230028. }
  230029. return Rectangle<int> ((int) r.origin.x, (int) r.origin.y, (int) r.size.width, (int) r.size.height);
  230030. }
  230031. const Rectangle<int> NSViewComponentPeer::getBounds() const
  230032. {
  230033. return getBounds (! isSharedWindow);
  230034. }
  230035. const Point<int> NSViewComponentPeer::getScreenPosition() const
  230036. {
  230037. return getBounds (true).getPosition();
  230038. }
  230039. const Point<int> NSViewComponentPeer::relativePositionToGlobal (const Point<int>& relativePosition)
  230040. {
  230041. return relativePosition + getScreenPosition();
  230042. }
  230043. const Point<int> NSViewComponentPeer::globalPositionToRelative (const Point<int>& screenPosition)
  230044. {
  230045. return screenPosition - getScreenPosition();
  230046. }
  230047. NSRect NSViewComponentPeer::constrainRect (NSRect r)
  230048. {
  230049. if (constrainer != 0)
  230050. {
  230051. NSRect current = [window frame];
  230052. current.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - current.origin.y - current.size.height;
  230053. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  230054. Rectangle<int> pos ((int) r.origin.x, (int) r.origin.y,
  230055. (int) r.size.width, (int) r.size.height);
  230056. Rectangle<int> original ((int) current.origin.x, (int) current.origin.y,
  230057. (int) current.size.width, (int) current.size.height);
  230058. constrainer->checkBounds (pos, original,
  230059. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  230060. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  230061. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  230062. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  230063. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  230064. r.origin.x = pos.getX();
  230065. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.size.height - pos.getY();
  230066. r.size.width = pos.getWidth();
  230067. r.size.height = pos.getHeight();
  230068. }
  230069. return r;
  230070. }
  230071. void NSViewComponentPeer::setMinimised (bool shouldBeMinimised)
  230072. {
  230073. if (! isSharedWindow)
  230074. {
  230075. if (shouldBeMinimised)
  230076. [window miniaturize: nil];
  230077. else
  230078. [window deminiaturize: nil];
  230079. }
  230080. }
  230081. bool NSViewComponentPeer::isMinimised() const
  230082. {
  230083. return window != 0 && [window isMiniaturized];
  230084. }
  230085. void NSViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  230086. {
  230087. if (! isSharedWindow)
  230088. {
  230089. Rectangle<int> r (lastNonFullscreenBounds);
  230090. setMinimised (false);
  230091. if (fullScreen != shouldBeFullScreen)
  230092. {
  230093. if (shouldBeFullScreen && (getStyleFlags() & windowHasTitleBar) != 0)
  230094. {
  230095. fullScreen = true;
  230096. [window performZoom: nil];
  230097. }
  230098. else
  230099. {
  230100. if (shouldBeFullScreen)
  230101. r = Desktop::getInstance().getMainMonitorArea();
  230102. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  230103. if (r != getComponent()->getBounds() && ! r.isEmpty())
  230104. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  230105. }
  230106. }
  230107. }
  230108. }
  230109. bool NSViewComponentPeer::isFullScreen() const
  230110. {
  230111. return fullScreen;
  230112. }
  230113. bool NSViewComponentPeer::contains (const Point<int>& position, bool trueIfInAChildWindow) const
  230114. {
  230115. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  230116. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  230117. return false;
  230118. NSPoint p;
  230119. p.x = (float) position.getX();
  230120. p.y = (float) position.getY();
  230121. NSView* v = [view hitTest: p];
  230122. if (trueIfInAChildWindow)
  230123. return v != nil;
  230124. return v == view;
  230125. }
  230126. const BorderSize NSViewComponentPeer::getFrameSize() const
  230127. {
  230128. BorderSize b;
  230129. if (! isSharedWindow)
  230130. {
  230131. NSRect v = [view convertRect: [view frame] toView: nil];
  230132. NSRect w = [window frame];
  230133. b.setTop ((int) (w.size.height - (v.origin.y + v.size.height)));
  230134. b.setBottom ((int) v.origin.y);
  230135. b.setLeft ((int) v.origin.x);
  230136. b.setRight ((int) (w.size.width - (v.origin.x + v.size.width)));
  230137. }
  230138. return b;
  230139. }
  230140. bool NSViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  230141. {
  230142. if (! isSharedWindow)
  230143. {
  230144. [window setLevel: alwaysOnTop ? NSFloatingWindowLevel
  230145. : NSNormalWindowLevel];
  230146. }
  230147. return true;
  230148. }
  230149. void NSViewComponentPeer::toFront (bool makeActiveWindow)
  230150. {
  230151. if (isSharedWindow)
  230152. {
  230153. [[view superview] addSubview: view
  230154. positioned: NSWindowAbove
  230155. relativeTo: nil];
  230156. }
  230157. if (window != 0 && component->isVisible())
  230158. {
  230159. if (makeActiveWindow)
  230160. [window makeKeyAndOrderFront: nil];
  230161. else
  230162. [window orderFront: nil];
  230163. if (! recursiveToFrontCall)
  230164. {
  230165. recursiveToFrontCall = true;
  230166. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  230167. handleBroughtToFront();
  230168. recursiveToFrontCall = false;
  230169. }
  230170. }
  230171. }
  230172. void NSViewComponentPeer::toBehind (ComponentPeer* other)
  230173. {
  230174. NSViewComponentPeer* const otherPeer = dynamic_cast <NSViewComponentPeer*> (other);
  230175. jassert (otherPeer != 0); // wrong type of window?
  230176. if (otherPeer != 0)
  230177. {
  230178. if (isSharedWindow)
  230179. {
  230180. [[view superview] addSubview: view
  230181. positioned: NSWindowBelow
  230182. relativeTo: otherPeer->view];
  230183. }
  230184. else
  230185. {
  230186. [window orderWindow: NSWindowBelow
  230187. relativeTo: otherPeer->window != 0 ? [otherPeer->window windowNumber]
  230188. : nil ];
  230189. }
  230190. }
  230191. }
  230192. void NSViewComponentPeer::setIcon (const Image& /*newIcon*/)
  230193. {
  230194. // to do..
  230195. }
  230196. void NSViewComponentPeer::viewFocusGain()
  230197. {
  230198. if (currentlyFocusedPeer != this)
  230199. {
  230200. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  230201. currentlyFocusedPeer->handleFocusLoss();
  230202. currentlyFocusedPeer = this;
  230203. handleFocusGain();
  230204. }
  230205. }
  230206. void NSViewComponentPeer::viewFocusLoss()
  230207. {
  230208. if (currentlyFocusedPeer == this)
  230209. {
  230210. currentlyFocusedPeer = 0;
  230211. handleFocusLoss();
  230212. }
  230213. }
  230214. void juce_HandleProcessFocusChange()
  230215. {
  230216. NSViewComponentPeer::keysCurrentlyDown.clear();
  230217. if (NSViewComponentPeer::isValidPeer (NSViewComponentPeer::currentlyFocusedPeer))
  230218. {
  230219. if (Process::isForegroundProcess())
  230220. {
  230221. NSViewComponentPeer::currentlyFocusedPeer->handleFocusGain();
  230222. ComponentPeer::bringModalComponentToFront();
  230223. }
  230224. else
  230225. {
  230226. NSViewComponentPeer::currentlyFocusedPeer->handleFocusLoss();
  230227. // turn kiosk mode off if we lose focus..
  230228. Desktop::getInstance().setKioskModeComponent (0);
  230229. }
  230230. }
  230231. }
  230232. bool NSViewComponentPeer::isFocused() const
  230233. {
  230234. return isSharedWindow ? this == currentlyFocusedPeer
  230235. : (window != 0 && [window isKeyWindow]);
  230236. }
  230237. void NSViewComponentPeer::grabFocus()
  230238. {
  230239. if (window != 0)
  230240. {
  230241. [window makeKeyWindow];
  230242. [window makeFirstResponder: view];
  230243. viewFocusGain();
  230244. }
  230245. }
  230246. void NSViewComponentPeer::textInputRequired (const Point<int>&)
  230247. {
  230248. }
  230249. bool NSViewComponentPeer::handleKeyEvent (NSEvent* ev, bool isKeyDown)
  230250. {
  230251. String unicode (nsStringToJuce ([ev characters]));
  230252. String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  230253. int keyCode = getKeyCodeFromEvent (ev);
  230254. //DBG ("unicode: " + unicode + " " + String::toHexString ((int) unicode[0]));
  230255. //DBG ("unmodified: " + unmodified + " " + String::toHexString ((int) unmodified[0]));
  230256. if (unicode.isNotEmpty() || keyCode != 0)
  230257. {
  230258. if (isKeyDown)
  230259. {
  230260. bool used = false;
  230261. while (unicode.length() > 0)
  230262. {
  230263. juce_wchar textCharacter = unicode[0];
  230264. unicode = unicode.substring (1);
  230265. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  230266. textCharacter = 0;
  230267. used = handleKeyUpOrDown (true) || used;
  230268. used = handleKeyPress (keyCode, textCharacter) || used;
  230269. }
  230270. return used;
  230271. }
  230272. else
  230273. {
  230274. if (handleKeyUpOrDown (false))
  230275. return true;
  230276. }
  230277. }
  230278. return false;
  230279. }
  230280. bool NSViewComponentPeer::redirectKeyDown (NSEvent* ev)
  230281. {
  230282. updateKeysDown (ev, true);
  230283. bool used = handleKeyEvent (ev, true);
  230284. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  230285. {
  230286. // for command keys, the key-up event is thrown away, so simulate one..
  230287. updateKeysDown (ev, false);
  230288. used = (isValidPeer (this) && handleKeyEvent (ev, false)) || used;
  230289. }
  230290. // (If we're running modally, don't allow unused keystrokes to be passed
  230291. // along to other blocked views..)
  230292. if (Component::getCurrentlyModalComponent() != 0)
  230293. used = true;
  230294. return used;
  230295. }
  230296. bool NSViewComponentPeer::redirectKeyUp (NSEvent* ev)
  230297. {
  230298. updateKeysDown (ev, false);
  230299. return handleKeyEvent (ev, false)
  230300. || Component::getCurrentlyModalComponent() != 0;
  230301. }
  230302. void NSViewComponentPeer::redirectModKeyChange (NSEvent* ev)
  230303. {
  230304. keysCurrentlyDown.clear();
  230305. handleKeyUpOrDown (true);
  230306. updateModifiers (ev);
  230307. handleModifierKeysChange();
  230308. }
  230309. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  230310. bool NSViewComponentPeer::redirectPerformKeyEquivalent (NSEvent* ev)
  230311. {
  230312. if ([ev type] == NSKeyDown)
  230313. return redirectKeyDown (ev);
  230314. else if ([ev type] == NSKeyUp)
  230315. return redirectKeyUp (ev);
  230316. return false;
  230317. }
  230318. #endif
  230319. void NSViewComponentPeer::sendMouseEvent (NSEvent* ev)
  230320. {
  230321. updateModifiers (ev);
  230322. handleMouseEvent (0, getMousePos (ev, view), currentModifiers, getMouseTime (ev));
  230323. }
  230324. void NSViewComponentPeer::redirectMouseDown (NSEvent* ev)
  230325. {
  230326. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  230327. sendMouseEvent (ev);
  230328. }
  230329. void NSViewComponentPeer::redirectMouseUp (NSEvent* ev)
  230330. {
  230331. currentModifiers = currentModifiers.withoutFlags (getModifierForButtonNumber ([ev buttonNumber]));
  230332. sendMouseEvent (ev);
  230333. showArrowCursorIfNeeded();
  230334. }
  230335. void NSViewComponentPeer::redirectMouseDrag (NSEvent* ev)
  230336. {
  230337. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  230338. sendMouseEvent (ev);
  230339. }
  230340. void NSViewComponentPeer::redirectMouseMove (NSEvent* ev)
  230341. {
  230342. currentModifiers = currentModifiers.withoutMouseButtons();
  230343. sendMouseEvent (ev);
  230344. showArrowCursorIfNeeded();
  230345. }
  230346. void NSViewComponentPeer::redirectMouseEnter (NSEvent* ev)
  230347. {
  230348. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  230349. currentModifiers = currentModifiers.withoutMouseButtons();
  230350. sendMouseEvent (ev);
  230351. }
  230352. void NSViewComponentPeer::redirectMouseExit (NSEvent* ev)
  230353. {
  230354. currentModifiers = currentModifiers.withoutMouseButtons();
  230355. sendMouseEvent (ev);
  230356. }
  230357. void NSViewComponentPeer::redirectMouseWheel (NSEvent* ev)
  230358. {
  230359. updateModifiers (ev);
  230360. handleMouseWheel (0, getMousePos (ev, view), getMouseTime (ev),
  230361. [ev deltaX] * 10.0f, [ev deltaY] * 10.0f);
  230362. }
  230363. void NSViewComponentPeer::showArrowCursorIfNeeded()
  230364. {
  230365. MouseInputSource& mouse = Desktop::getInstance().getMainMouseSource();
  230366. if (mouse.getComponentUnderMouse() == 0
  230367. && Desktop::getInstance().findComponentAt (mouse.getScreenPosition()) == 0)
  230368. {
  230369. [[NSCursor arrowCursor] set];
  230370. }
  230371. }
  230372. BOOL NSViewComponentPeer::sendDragCallback (int type, id <NSDraggingInfo> sender)
  230373. {
  230374. NSString* bestType
  230375. = [[sender draggingPasteboard] availableTypeFromArray: [view getSupportedDragTypes]];
  230376. if (bestType == nil)
  230377. return false;
  230378. NSPoint p = [view convertPoint: [sender draggingLocation] fromView: nil];
  230379. const Point<int> pos ((int) p.x, (int) ([view frame].size.height - p.y));
  230380. StringArray files;
  230381. id list = [[sender draggingPasteboard] propertyListForType: bestType];
  230382. if (list == nil)
  230383. return false;
  230384. if ([list isKindOfClass: [NSArray class]])
  230385. {
  230386. NSArray* items = (NSArray*) list;
  230387. for (unsigned int i = 0; i < [items count]; ++i)
  230388. files.add (nsStringToJuce ((NSString*) [items objectAtIndex: i]));
  230389. }
  230390. if (files.size() == 0)
  230391. return false;
  230392. if (type == 0)
  230393. handleFileDragMove (files, pos);
  230394. else if (type == 1)
  230395. handleFileDragExit (files);
  230396. else if (type == 2)
  230397. handleFileDragDrop (files, pos);
  230398. return true;
  230399. }
  230400. bool NSViewComponentPeer::isOpaque()
  230401. {
  230402. return component == 0 || component->isOpaque();
  230403. }
  230404. void NSViewComponentPeer::drawRect (NSRect r)
  230405. {
  230406. if (r.size.width < 1.0f || r.size.height < 1.0f)
  230407. return;
  230408. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  230409. if (! component->isOpaque())
  230410. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  230411. #if USE_COREGRAPHICS_RENDERING
  230412. if (usingCoreGraphics)
  230413. {
  230414. CoreGraphicsContext context (cg, (float) [view frame].size.height);
  230415. insideDrawRect = true;
  230416. handlePaint (context);
  230417. insideDrawRect = false;
  230418. }
  230419. else
  230420. #endif
  230421. {
  230422. Image temp (getComponent()->isOpaque() ? Image::RGB : Image::ARGB,
  230423. (int) (r.size.width + 0.5f),
  230424. (int) (r.size.height + 0.5f),
  230425. ! getComponent()->isOpaque());
  230426. const int xOffset = -roundToInt (r.origin.x);
  230427. const int yOffset = -roundToInt ([view frame].size.height - (r.origin.y + r.size.height));
  230428. const NSRect* rects = 0;
  230429. NSInteger numRects = 0;
  230430. [view getRectsBeingDrawn: &rects count: &numRects];
  230431. const Rectangle<int> clipBounds (temp.getBounds());
  230432. RectangleList clip;
  230433. for (int i = 0; i < numRects; ++i)
  230434. {
  230435. clip.addWithoutMerging (clipBounds.getIntersection (Rectangle<int> (roundToInt (rects[i].origin.x) + xOffset,
  230436. roundToInt ([view frame].size.height - (rects[i].origin.y + rects[i].size.height)) + yOffset,
  230437. roundToInt (rects[i].size.width),
  230438. roundToInt (rects[i].size.height))));
  230439. }
  230440. if (! clip.isEmpty())
  230441. {
  230442. LowLevelGraphicsSoftwareRenderer context (temp, xOffset, yOffset, clip);
  230443. insideDrawRect = true;
  230444. handlePaint (context);
  230445. insideDrawRect = false;
  230446. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  230447. CGImageRef image = CoreGraphicsImage::createImage (temp, false, colourSpace);
  230448. CGColorSpaceRelease (colourSpace);
  230449. CGContextDrawImage (cg, CGRectMake (r.origin.x, r.origin.y, temp.getWidth(), temp.getHeight()), image);
  230450. CGImageRelease (image);
  230451. }
  230452. }
  230453. }
  230454. const StringArray NSViewComponentPeer::getAvailableRenderingEngines() throw()
  230455. {
  230456. StringArray s;
  230457. s.add ("Software Renderer");
  230458. #if USE_COREGRAPHICS_RENDERING
  230459. s.add ("CoreGraphics Renderer");
  230460. #endif
  230461. return s;
  230462. }
  230463. int NSViewComponentPeer::getCurrentRenderingEngine() throw()
  230464. {
  230465. return usingCoreGraphics ? 1 : 0;
  230466. }
  230467. void NSViewComponentPeer::setCurrentRenderingEngine (int index) throw()
  230468. {
  230469. #if USE_COREGRAPHICS_RENDERING
  230470. if (usingCoreGraphics != (index > 0))
  230471. {
  230472. usingCoreGraphics = index > 0;
  230473. [view setNeedsDisplay: true];
  230474. }
  230475. #endif
  230476. }
  230477. bool NSViewComponentPeer::canBecomeKeyWindow()
  230478. {
  230479. return (getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowIgnoresKeyPresses) == 0;
  230480. }
  230481. bool NSViewComponentPeer::windowShouldClose()
  230482. {
  230483. if (! isValidPeer (this))
  230484. return YES;
  230485. handleUserClosingWindow();
  230486. return NO;
  230487. }
  230488. void NSViewComponentPeer::redirectMovedOrResized()
  230489. {
  230490. handleMovedOrResized();
  230491. }
  230492. void NSViewComponentPeer::viewMovedToWindow()
  230493. {
  230494. if (isSharedWindow)
  230495. window = [view window];
  230496. }
  230497. void Desktop::createMouseInputSources()
  230498. {
  230499. mouseSources.add (new MouseInputSource (0, true));
  230500. }
  230501. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  230502. {
  230503. // Very annoyingly, this function has to use the old SetSystemUIMode function,
  230504. // which is in Carbon.framework. But, because there's no Cocoa equivalent, it
  230505. // is apparently still available in 64-bit apps..
  230506. if (enableOrDisable)
  230507. {
  230508. SetSystemUIMode (kUIModeAllSuppressed, allowMenusAndBars ? kUIOptionAutoShowMenuBar : 0);
  230509. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  230510. }
  230511. else
  230512. {
  230513. SetSystemUIMode (kUIModeNormal, 0);
  230514. }
  230515. }
  230516. class AsyncRepaintMessage : public CallbackMessage
  230517. {
  230518. public:
  230519. NSViewComponentPeer* const peer;
  230520. const Rectangle<int> rect;
  230521. AsyncRepaintMessage (NSViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  230522. : peer (peer_), rect (rect_)
  230523. {
  230524. }
  230525. void messageCallback()
  230526. {
  230527. if (ComponentPeer::isValidPeer (peer))
  230528. peer->repaint (rect);
  230529. }
  230530. };
  230531. void NSViewComponentPeer::repaint (const Rectangle<int>& area)
  230532. {
  230533. if (insideDrawRect)
  230534. {
  230535. (new AsyncRepaintMessage (this, area))->post();
  230536. }
  230537. else
  230538. {
  230539. [view setNeedsDisplayInRect: NSMakeRect ((float) area.getX(), [view frame].size.height - (float) area.getBottom(),
  230540. (float) area.getWidth(), (float) area.getHeight())];
  230541. }
  230542. }
  230543. void NSViewComponentPeer::performAnyPendingRepaintsNow()
  230544. {
  230545. [view displayIfNeeded];
  230546. }
  230547. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  230548. {
  230549. return new NSViewComponentPeer (this, styleFlags, (NSView*) windowToAttachTo);
  230550. }
  230551. const Image juce_createIconForFile (const File& file)
  230552. {
  230553. const ScopedAutoReleasePool pool;
  230554. NSImage* image = [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (file.getFullPathName())];
  230555. CoreGraphicsImage* result = new CoreGraphicsImage (Image::ARGB, (int) [image size].width, (int) [image size].height, true);
  230556. [NSGraphicsContext saveGraphicsState];
  230557. [NSGraphicsContext setCurrentContext: [NSGraphicsContext graphicsContextWithGraphicsPort: result->context flipped: false]];
  230558. [image drawAtPoint: NSMakePoint (0, 0)
  230559. fromRect: NSMakeRect (0, 0, [image size].width, [image size].height)
  230560. operation: NSCompositeSourceOver fraction: 1.0f];
  230561. [[NSGraphicsContext currentContext] flushGraphics];
  230562. [NSGraphicsContext restoreGraphicsState];
  230563. return Image (result);
  230564. }
  230565. const int KeyPress::spaceKey = ' ';
  230566. const int KeyPress::returnKey = 0x0d;
  230567. const int KeyPress::escapeKey = 0x1b;
  230568. const int KeyPress::backspaceKey = 0x7f;
  230569. const int KeyPress::leftKey = NSLeftArrowFunctionKey;
  230570. const int KeyPress::rightKey = NSRightArrowFunctionKey;
  230571. const int KeyPress::upKey = NSUpArrowFunctionKey;
  230572. const int KeyPress::downKey = NSDownArrowFunctionKey;
  230573. const int KeyPress::pageUpKey = NSPageUpFunctionKey;
  230574. const int KeyPress::pageDownKey = NSPageDownFunctionKey;
  230575. const int KeyPress::endKey = NSEndFunctionKey;
  230576. const int KeyPress::homeKey = NSHomeFunctionKey;
  230577. const int KeyPress::deleteKey = NSDeleteFunctionKey;
  230578. const int KeyPress::insertKey = -1;
  230579. const int KeyPress::tabKey = 9;
  230580. const int KeyPress::F1Key = NSF1FunctionKey;
  230581. const int KeyPress::F2Key = NSF2FunctionKey;
  230582. const int KeyPress::F3Key = NSF3FunctionKey;
  230583. const int KeyPress::F4Key = NSF4FunctionKey;
  230584. const int KeyPress::F5Key = NSF5FunctionKey;
  230585. const int KeyPress::F6Key = NSF6FunctionKey;
  230586. const int KeyPress::F7Key = NSF7FunctionKey;
  230587. const int KeyPress::F8Key = NSF8FunctionKey;
  230588. const int KeyPress::F9Key = NSF9FunctionKey;
  230589. const int KeyPress::F10Key = NSF10FunctionKey;
  230590. const int KeyPress::F11Key = NSF1FunctionKey;
  230591. const int KeyPress::F12Key = NSF12FunctionKey;
  230592. const int KeyPress::F13Key = NSF13FunctionKey;
  230593. const int KeyPress::F14Key = NSF14FunctionKey;
  230594. const int KeyPress::F15Key = NSF15FunctionKey;
  230595. const int KeyPress::F16Key = NSF16FunctionKey;
  230596. const int KeyPress::numberPad0 = 0x30020;
  230597. const int KeyPress::numberPad1 = 0x30021;
  230598. const int KeyPress::numberPad2 = 0x30022;
  230599. const int KeyPress::numberPad3 = 0x30023;
  230600. const int KeyPress::numberPad4 = 0x30024;
  230601. const int KeyPress::numberPad5 = 0x30025;
  230602. const int KeyPress::numberPad6 = 0x30026;
  230603. const int KeyPress::numberPad7 = 0x30027;
  230604. const int KeyPress::numberPad8 = 0x30028;
  230605. const int KeyPress::numberPad9 = 0x30029;
  230606. const int KeyPress::numberPadAdd = 0x3002a;
  230607. const int KeyPress::numberPadSubtract = 0x3002b;
  230608. const int KeyPress::numberPadMultiply = 0x3002c;
  230609. const int KeyPress::numberPadDivide = 0x3002d;
  230610. const int KeyPress::numberPadSeparator = 0x3002e;
  230611. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  230612. const int KeyPress::numberPadEquals = 0x30030;
  230613. const int KeyPress::numberPadDelete = 0x30031;
  230614. const int KeyPress::playKey = 0x30000;
  230615. const int KeyPress::stopKey = 0x30001;
  230616. const int KeyPress::fastForwardKey = 0x30002;
  230617. const int KeyPress::rewindKey = 0x30003;
  230618. #endif
  230619. /*** End of inlined file: juce_mac_NSViewComponentPeer.mm ***/
  230620. /*** Start of inlined file: juce_mac_MouseCursor.mm ***/
  230621. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  230622. // compiled on its own).
  230623. #if JUCE_INCLUDED_FILE
  230624. #if JUCE_MAC
  230625. namespace MouseCursorHelpers
  230626. {
  230627. static void* createFromImage (const Image& image, float hotspotX, float hotspotY)
  230628. {
  230629. NSImage* im = CoreGraphicsImage::createNSImage (image);
  230630. NSCursor* c = [[NSCursor alloc] initWithImage: im
  230631. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  230632. [im release];
  230633. return c;
  230634. }
  230635. static void* fromWebKitFile (const char* filename, float hx, float hy)
  230636. {
  230637. FileInputStream fileStream (String ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources/") + filename);
  230638. BufferedInputStream buf (&fileStream, 4096, false);
  230639. PNGImageFormat pngFormat;
  230640. Image im (pngFormat.decodeImage (buf));
  230641. if (im.isValid())
  230642. return createFromImage (im, hx * im.getWidth(), hy * im.getHeight());
  230643. jassertfalse;
  230644. return 0;
  230645. }
  230646. }
  230647. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  230648. {
  230649. return MouseCursorHelpers::createFromImage (image, (float) hotspotX, (float) hotspotY);
  230650. }
  230651. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  230652. {
  230653. const ScopedAutoReleasePool pool;
  230654. NSCursor* c = 0;
  230655. switch (type)
  230656. {
  230657. case NormalCursor: c = [NSCursor arrowCursor]; break;
  230658. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 8, 8, true), 0, 0);
  230659. case DraggingHandCursor: c = [NSCursor openHandCursor]; break;
  230660. case WaitCursor: c = [NSCursor arrowCursor]; break; // avoid this on the mac, let the OS provide the beachball
  230661. case IBeamCursor: c = [NSCursor IBeamCursor]; break;
  230662. case PointingHandCursor: c = [NSCursor pointingHandCursor]; break;
  230663. case LeftRightResizeCursor: c = [NSCursor resizeLeftRightCursor]; break;
  230664. case LeftEdgeResizeCursor: c = [NSCursor resizeLeftCursor]; break;
  230665. case RightEdgeResizeCursor: c = [NSCursor resizeRightCursor]; break;
  230666. case CrosshairCursor: c = [NSCursor crosshairCursor]; break;
  230667. case CopyingCursor: return MouseCursorHelpers::fromWebKitFile ("copyCursor.png", 0, 0);
  230668. case UpDownResizeCursor:
  230669. case TopEdgeResizeCursor:
  230670. case BottomEdgeResizeCursor:
  230671. return MouseCursorHelpers::fromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  230672. case TopLeftCornerResizeCursor:
  230673. case BottomRightCornerResizeCursor:
  230674. return MouseCursorHelpers::fromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  230675. case TopRightCornerResizeCursor:
  230676. case BottomLeftCornerResizeCursor:
  230677. return MouseCursorHelpers::fromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  230678. case UpDownLeftRightResizeCursor:
  230679. return MouseCursorHelpers::fromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  230680. default:
  230681. jassertfalse;
  230682. break;
  230683. }
  230684. [c retain];
  230685. return c;
  230686. }
  230687. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool /*isStandard*/)
  230688. {
  230689. [((NSCursor*) cursorHandle) release];
  230690. }
  230691. void MouseCursor::showInAllWindows() const
  230692. {
  230693. showInWindow (0);
  230694. }
  230695. void MouseCursor::showInWindow (ComponentPeer*) const
  230696. {
  230697. [((NSCursor*) getHandle()) set];
  230698. }
  230699. #else
  230700. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) { return 0; }
  230701. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type) { return 0; }
  230702. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard) {}
  230703. void MouseCursor::showInAllWindows() const {}
  230704. void MouseCursor::showInWindow (ComponentPeer*) const {}
  230705. #endif
  230706. #endif
  230707. /*** End of inlined file: juce_mac_MouseCursor.mm ***/
  230708. /*** Start of inlined file: juce_mac_NSViewComponent.mm ***/
  230709. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  230710. // compiled on its own).
  230711. #if JUCE_INCLUDED_FILE
  230712. class NSViewComponentInternal : public ComponentMovementWatcher
  230713. {
  230714. Component* const owner;
  230715. NSViewComponentPeer* currentPeer;
  230716. bool wasShowing;
  230717. public:
  230718. NSView* const view;
  230719. NSViewComponentInternal (NSView* const view_, Component* const owner_)
  230720. : ComponentMovementWatcher (owner_),
  230721. owner (owner_),
  230722. currentPeer (0),
  230723. wasShowing (false),
  230724. view (view_)
  230725. {
  230726. [view_ retain];
  230727. if (owner_->isShowing())
  230728. componentPeerChanged();
  230729. }
  230730. ~NSViewComponentInternal()
  230731. {
  230732. [view removeFromSuperview];
  230733. [view release];
  230734. }
  230735. void componentMovedOrResized (Component& comp, bool wasMoved, bool wasResized)
  230736. {
  230737. ComponentMovementWatcher::componentMovedOrResized (comp, wasMoved, wasResized);
  230738. // The ComponentMovementWatcher version of this method avoids calling
  230739. // us when the top-level comp is resized, but for an NSView we need to know this
  230740. // because with inverted co-ords, we need to update the position even if the
  230741. // top-left pos hasn't changed
  230742. if (comp.isOnDesktop() && wasResized)
  230743. componentMovedOrResized (wasMoved, wasResized);
  230744. }
  230745. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  230746. {
  230747. Component* const topComp = owner->getTopLevelComponent();
  230748. if (topComp->getPeer() != 0)
  230749. {
  230750. const Point<int> pos (owner->relativePositionToOtherComponent (topComp, Point<int>()));
  230751. NSRect r;
  230752. r.origin.x = (float) pos.getX();
  230753. r.origin.y = (float) pos.getY();
  230754. r.size.width = (float) owner->getWidth();
  230755. r.size.height = (float) owner->getHeight();
  230756. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  230757. [view setFrame: r];
  230758. }
  230759. }
  230760. void componentPeerChanged()
  230761. {
  230762. NSViewComponentPeer* const peer = dynamic_cast <NSViewComponentPeer*> (owner->getPeer());
  230763. if (currentPeer != peer)
  230764. {
  230765. [view removeFromSuperview];
  230766. currentPeer = peer;
  230767. if (peer != 0)
  230768. {
  230769. [peer->view addSubview: view];
  230770. componentMovedOrResized (false, false);
  230771. }
  230772. }
  230773. [view setHidden: ! owner->isShowing()];
  230774. }
  230775. void componentVisibilityChanged (Component&)
  230776. {
  230777. componentPeerChanged();
  230778. }
  230779. juce_UseDebuggingNewOperator
  230780. private:
  230781. NSViewComponentInternal (const NSViewComponentInternal&);
  230782. NSViewComponentInternal& operator= (const NSViewComponentInternal&);
  230783. };
  230784. NSViewComponent::NSViewComponent()
  230785. {
  230786. }
  230787. NSViewComponent::~NSViewComponent()
  230788. {
  230789. }
  230790. void NSViewComponent::setView (void* view)
  230791. {
  230792. if (view != getView())
  230793. {
  230794. if (view != 0)
  230795. info = new NSViewComponentInternal ((NSView*) view, this);
  230796. else
  230797. info = 0;
  230798. }
  230799. }
  230800. void* NSViewComponent::getView() const
  230801. {
  230802. return info == 0 ? 0 : info->view;
  230803. }
  230804. void NSViewComponent::paint (Graphics&)
  230805. {
  230806. }
  230807. #endif
  230808. /*** End of inlined file: juce_mac_NSViewComponent.mm ***/
  230809. /*** Start of inlined file: juce_mac_AppleRemote.mm ***/
  230810. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  230811. // compiled on its own).
  230812. #if JUCE_INCLUDED_FILE
  230813. AppleRemoteDevice::AppleRemoteDevice()
  230814. : device (0),
  230815. queue (0),
  230816. remoteId (0)
  230817. {
  230818. }
  230819. AppleRemoteDevice::~AppleRemoteDevice()
  230820. {
  230821. stop();
  230822. }
  230823. static io_object_t getAppleRemoteDevice()
  230824. {
  230825. CFMutableDictionaryRef dict = IOServiceMatching ("AppleIRController");
  230826. io_iterator_t iter = 0;
  230827. io_object_t iod = 0;
  230828. if (IOServiceGetMatchingServices (kIOMasterPortDefault, dict, &iter) == kIOReturnSuccess
  230829. && iter != 0)
  230830. {
  230831. iod = IOIteratorNext (iter);
  230832. }
  230833. IOObjectRelease (iter);
  230834. return iod;
  230835. }
  230836. static bool createAppleRemoteInterface (io_object_t iod, void** device)
  230837. {
  230838. jassert (*device == 0);
  230839. io_name_t classname;
  230840. if (IOObjectGetClass (iod, classname) == kIOReturnSuccess)
  230841. {
  230842. IOCFPlugInInterface** cfPlugInInterface = 0;
  230843. SInt32 score = 0;
  230844. if (IOCreatePlugInInterfaceForService (iod,
  230845. kIOHIDDeviceUserClientTypeID,
  230846. kIOCFPlugInInterfaceID,
  230847. &cfPlugInInterface,
  230848. &score) == kIOReturnSuccess)
  230849. {
  230850. HRESULT hr = (*cfPlugInInterface)->QueryInterface (cfPlugInInterface,
  230851. CFUUIDGetUUIDBytes (kIOHIDDeviceInterfaceID),
  230852. device);
  230853. (void) hr;
  230854. (*cfPlugInInterface)->Release (cfPlugInInterface);
  230855. }
  230856. }
  230857. return *device != 0;
  230858. }
  230859. bool AppleRemoteDevice::start (const bool inExclusiveMode)
  230860. {
  230861. if (queue != 0)
  230862. return true;
  230863. stop();
  230864. bool result = false;
  230865. io_object_t iod = getAppleRemoteDevice();
  230866. if (iod != 0)
  230867. {
  230868. if (createAppleRemoteInterface (iod, &device) && open (inExclusiveMode))
  230869. result = true;
  230870. else
  230871. stop();
  230872. IOObjectRelease (iod);
  230873. }
  230874. return result;
  230875. }
  230876. void AppleRemoteDevice::stop()
  230877. {
  230878. if (queue != 0)
  230879. {
  230880. (*(IOHIDQueueInterface**) queue)->stop ((IOHIDQueueInterface**) queue);
  230881. (*(IOHIDQueueInterface**) queue)->dispose ((IOHIDQueueInterface**) queue);
  230882. (*(IOHIDQueueInterface**) queue)->Release ((IOHIDQueueInterface**) queue);
  230883. queue = 0;
  230884. }
  230885. if (device != 0)
  230886. {
  230887. (*(IOHIDDeviceInterface**) device)->close ((IOHIDDeviceInterface**) device);
  230888. (*(IOHIDDeviceInterface**) device)->Release ((IOHIDDeviceInterface**) device);
  230889. device = 0;
  230890. }
  230891. }
  230892. bool AppleRemoteDevice::isActive() const
  230893. {
  230894. return queue != 0;
  230895. }
  230896. static void appleRemoteQueueCallback (void* const target, const IOReturn result, void*, void*)
  230897. {
  230898. if (result == kIOReturnSuccess)
  230899. ((AppleRemoteDevice*) target)->handleCallbackInternal();
  230900. }
  230901. bool AppleRemoteDevice::open (const bool openInExclusiveMode)
  230902. {
  230903. Array <int> cookies;
  230904. CFArrayRef elements;
  230905. IOHIDDeviceInterface122** const device122 = (IOHIDDeviceInterface122**) device;
  230906. if ((*device122)->copyMatchingElements (device122, 0, &elements) != kIOReturnSuccess)
  230907. return false;
  230908. for (int i = 0; i < CFArrayGetCount (elements); ++i)
  230909. {
  230910. CFDictionaryRef element = (CFDictionaryRef) CFArrayGetValueAtIndex (elements, i);
  230911. // get the cookie
  230912. CFTypeRef object = CFDictionaryGetValue (element, CFSTR (kIOHIDElementCookieKey));
  230913. if (object == 0 || CFGetTypeID (object) != CFNumberGetTypeID())
  230914. continue;
  230915. long number;
  230916. if (! CFNumberGetValue ((CFNumberRef) object, kCFNumberLongType, &number))
  230917. continue;
  230918. cookies.add ((int) number);
  230919. }
  230920. CFRelease (elements);
  230921. if ((*(IOHIDDeviceInterface**) device)
  230922. ->open ((IOHIDDeviceInterface**) device,
  230923. openInExclusiveMode ? kIOHIDOptionsTypeSeizeDevice
  230924. : kIOHIDOptionsTypeNone) == KERN_SUCCESS)
  230925. {
  230926. queue = (*(IOHIDDeviceInterface**) device)->allocQueue ((IOHIDDeviceInterface**) device);
  230927. if (queue != 0)
  230928. {
  230929. (*(IOHIDQueueInterface**) queue)->create ((IOHIDQueueInterface**) queue, 0, 12);
  230930. for (int i = 0; i < cookies.size(); ++i)
  230931. {
  230932. IOHIDElementCookie cookie = (IOHIDElementCookie) cookies.getUnchecked(i);
  230933. (*(IOHIDQueueInterface**) queue)->addElement ((IOHIDQueueInterface**) queue, cookie, 0);
  230934. }
  230935. CFRunLoopSourceRef eventSource;
  230936. if ((*(IOHIDQueueInterface**) queue)
  230937. ->createAsyncEventSource ((IOHIDQueueInterface**) queue, &eventSource) == KERN_SUCCESS)
  230938. {
  230939. if ((*(IOHIDQueueInterface**) queue)->setEventCallout ((IOHIDQueueInterface**) queue,
  230940. appleRemoteQueueCallback, this, 0) == KERN_SUCCESS)
  230941. {
  230942. CFRunLoopAddSource (CFRunLoopGetCurrent(), eventSource, kCFRunLoopDefaultMode);
  230943. (*(IOHIDQueueInterface**) queue)->start ((IOHIDQueueInterface**) queue);
  230944. return true;
  230945. }
  230946. }
  230947. }
  230948. }
  230949. return false;
  230950. }
  230951. void AppleRemoteDevice::handleCallbackInternal()
  230952. {
  230953. int totalValues = 0;
  230954. AbsoluteTime nullTime = { 0, 0 };
  230955. char cookies [12];
  230956. int numCookies = 0;
  230957. while (numCookies < numElementsInArray (cookies))
  230958. {
  230959. IOHIDEventStruct e;
  230960. if ((*(IOHIDQueueInterface**) queue)->getNextEvent ((IOHIDQueueInterface**) queue, &e, nullTime, 0) != kIOReturnSuccess)
  230961. break;
  230962. if ((int) e.elementCookie == 19)
  230963. {
  230964. remoteId = e.value;
  230965. buttonPressed (switched, false);
  230966. }
  230967. else
  230968. {
  230969. totalValues += e.value;
  230970. cookies [numCookies++] = (char) (pointer_sized_int) e.elementCookie;
  230971. }
  230972. }
  230973. cookies [numCookies++] = 0;
  230974. //DBG (String::toHexString ((uint8*) cookies, numCookies, 1) + " " + String (totalValues));
  230975. static const char buttonPatterns[] =
  230976. {
  230977. 0x1f, 0x14, 0x12, 0x1f, 0x14, 0x12, 0,
  230978. 0x1f, 0x15, 0x12, 0x1f, 0x15, 0x12, 0,
  230979. 0x1f, 0x1d, 0x1c, 0x12, 0,
  230980. 0x1f, 0x1e, 0x1c, 0x12, 0,
  230981. 0x1f, 0x16, 0x12, 0x1f, 0x16, 0x12, 0,
  230982. 0x1f, 0x17, 0x12, 0x1f, 0x17, 0x12, 0,
  230983. 0x1f, 0x12, 0x04, 0x02, 0,
  230984. 0x1f, 0x12, 0x03, 0x02, 0,
  230985. 0x1f, 0x12, 0x1f, 0x12, 0,
  230986. 0x23, 0x1f, 0x12, 0x23, 0x1f, 0x12, 0,
  230987. 19, 0
  230988. };
  230989. int buttonNum = (int) menuButton;
  230990. int i = 0;
  230991. while (i < numElementsInArray (buttonPatterns))
  230992. {
  230993. if (strcmp (cookies, buttonPatterns + i) == 0)
  230994. {
  230995. buttonPressed ((ButtonType) buttonNum, totalValues > 0);
  230996. break;
  230997. }
  230998. i += (int) strlen (buttonPatterns + i) + 1;
  230999. ++buttonNum;
  231000. }
  231001. }
  231002. #endif
  231003. /*** End of inlined file: juce_mac_AppleRemote.mm ***/
  231004. /*** Start of inlined file: juce_mac_OpenGLComponent.mm ***/
  231005. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  231006. // compiled on its own).
  231007. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  231008. #if JUCE_MAC
  231009. END_JUCE_NAMESPACE
  231010. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  231011. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  231012. {
  231013. CriticalSection* contextLock;
  231014. bool needsUpdate;
  231015. }
  231016. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  231017. - (bool) makeActive;
  231018. - (void) makeInactive;
  231019. - (void) reshape;
  231020. @end
  231021. @implementation ThreadSafeNSOpenGLView
  231022. - (id) initWithFrame: (NSRect) frameRect
  231023. pixelFormat: (NSOpenGLPixelFormat*) format
  231024. {
  231025. contextLock = new CriticalSection();
  231026. self = [super initWithFrame: frameRect pixelFormat: format];
  231027. if (self != nil)
  231028. [[NSNotificationCenter defaultCenter] addObserver: self
  231029. selector: @selector (_surfaceNeedsUpdate:)
  231030. name: NSViewGlobalFrameDidChangeNotification
  231031. object: self];
  231032. return self;
  231033. }
  231034. - (void) dealloc
  231035. {
  231036. [[NSNotificationCenter defaultCenter] removeObserver: self];
  231037. delete contextLock;
  231038. [super dealloc];
  231039. }
  231040. - (bool) makeActive
  231041. {
  231042. const ScopedLock sl (*contextLock);
  231043. if ([self openGLContext] == 0)
  231044. return false;
  231045. [[self openGLContext] makeCurrentContext];
  231046. if (needsUpdate)
  231047. {
  231048. [super update];
  231049. needsUpdate = false;
  231050. }
  231051. return true;
  231052. }
  231053. - (void) makeInactive
  231054. {
  231055. const ScopedLock sl (*contextLock);
  231056. [NSOpenGLContext clearCurrentContext];
  231057. }
  231058. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  231059. {
  231060. const ScopedLock sl (*contextLock);
  231061. needsUpdate = true;
  231062. }
  231063. - (void) update
  231064. {
  231065. const ScopedLock sl (*contextLock);
  231066. needsUpdate = true;
  231067. }
  231068. - (void) reshape
  231069. {
  231070. const ScopedLock sl (*contextLock);
  231071. needsUpdate = true;
  231072. }
  231073. @end
  231074. BEGIN_JUCE_NAMESPACE
  231075. class WindowedGLContext : public OpenGLContext
  231076. {
  231077. public:
  231078. WindowedGLContext (Component* const component,
  231079. const OpenGLPixelFormat& pixelFormat_,
  231080. NSOpenGLContext* sharedContext)
  231081. : renderContext (0),
  231082. pixelFormat (pixelFormat_)
  231083. {
  231084. jassert (component != 0);
  231085. NSOpenGLPixelFormatAttribute attribs [64];
  231086. int n = 0;
  231087. attribs[n++] = NSOpenGLPFADoubleBuffer;
  231088. attribs[n++] = NSOpenGLPFAAccelerated;
  231089. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  231090. attribs[n++] = NSOpenGLPFAColorSize;
  231091. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  231092. pixelFormat.greenBits,
  231093. pixelFormat.blueBits);
  231094. attribs[n++] = NSOpenGLPFAAlphaSize;
  231095. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  231096. attribs[n++] = NSOpenGLPFADepthSize;
  231097. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  231098. attribs[n++] = NSOpenGLPFAStencilSize;
  231099. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  231100. attribs[n++] = NSOpenGLPFAAccumSize;
  231101. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  231102. pixelFormat.accumulationBufferGreenBits,
  231103. pixelFormat.accumulationBufferBlueBits,
  231104. pixelFormat.accumulationBufferAlphaBits);
  231105. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  231106. attribs[n++] = NSOpenGLPFASampleBuffers;
  231107. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  231108. attribs[n++] = NSOpenGLPFAClosestPolicy;
  231109. attribs[n++] = NSOpenGLPFANoRecovery;
  231110. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  231111. NSOpenGLPixelFormat* format
  231112. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  231113. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  231114. pixelFormat: format];
  231115. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  231116. shareContext: sharedContext] autorelease];
  231117. const GLint swapInterval = 1;
  231118. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  231119. [view setOpenGLContext: renderContext];
  231120. [renderContext setView: view];
  231121. [format release];
  231122. viewHolder = new NSViewComponentInternal (view, component);
  231123. }
  231124. ~WindowedGLContext()
  231125. {
  231126. makeInactive();
  231127. [renderContext clearDrawable];
  231128. viewHolder = 0;
  231129. }
  231130. bool makeActive() const throw()
  231131. {
  231132. jassert (renderContext != 0);
  231133. [view makeActive];
  231134. return isActive();
  231135. }
  231136. bool makeInactive() const throw()
  231137. {
  231138. [view makeInactive];
  231139. return true;
  231140. }
  231141. bool isActive() const throw()
  231142. {
  231143. return [NSOpenGLContext currentContext] == renderContext;
  231144. }
  231145. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  231146. void* getRawContext() const throw() { return renderContext; }
  231147. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  231148. {
  231149. }
  231150. void swapBuffers()
  231151. {
  231152. [renderContext flushBuffer];
  231153. }
  231154. bool setSwapInterval (const int numFramesPerSwap)
  231155. {
  231156. [renderContext setValues: (const GLint*) &numFramesPerSwap
  231157. forParameter: NSOpenGLCPSwapInterval];
  231158. return true;
  231159. }
  231160. int getSwapInterval() const
  231161. {
  231162. GLint numFrames = 0;
  231163. [renderContext getValues: &numFrames
  231164. forParameter: NSOpenGLCPSwapInterval];
  231165. return numFrames;
  231166. }
  231167. void repaint()
  231168. {
  231169. // we need to invalidate the juce view that holds this gl view, to make it
  231170. // cause a repaint callback
  231171. NSView* v = (NSView*) viewHolder->view;
  231172. NSRect r = [v frame];
  231173. // bit of a bodge here.. if we only invalidate the area of the gl component,
  231174. // it's completely covered by the NSOpenGLView, so the OS throws away the
  231175. // repaint message, thus never causing our paint() callback, and never repainting
  231176. // the comp. So invalidating just a little bit around the edge helps..
  231177. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  231178. }
  231179. void* getNativeWindowHandle() const { return viewHolder->view; }
  231180. juce_UseDebuggingNewOperator
  231181. NSOpenGLContext* renderContext;
  231182. ThreadSafeNSOpenGLView* view;
  231183. private:
  231184. OpenGLPixelFormat pixelFormat;
  231185. ScopedPointer <NSViewComponentInternal> viewHolder;
  231186. WindowedGLContext (const WindowedGLContext&);
  231187. WindowedGLContext& operator= (const WindowedGLContext&);
  231188. };
  231189. OpenGLContext* OpenGLComponent::createContext()
  231190. {
  231191. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  231192. contextToShareListsWith != 0 ? (NSOpenGLContext*) contextToShareListsWith->getRawContext() : 0));
  231193. return (c->renderContext != 0) ? c.release() : 0;
  231194. }
  231195. void* OpenGLComponent::getNativeWindowHandle() const
  231196. {
  231197. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle()
  231198. : 0;
  231199. }
  231200. void juce_glViewport (const int w, const int h)
  231201. {
  231202. glViewport (0, 0, w, h);
  231203. }
  231204. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  231205. OwnedArray <OpenGLPixelFormat>& results)
  231206. {
  231207. /* GLint attribs [64];
  231208. int n = 0;
  231209. attribs[n++] = AGL_RGBA;
  231210. attribs[n++] = AGL_DOUBLEBUFFER;
  231211. attribs[n++] = AGL_ACCELERATED;
  231212. attribs[n++] = AGL_NO_RECOVERY;
  231213. attribs[n++] = AGL_NONE;
  231214. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  231215. while (p != 0)
  231216. {
  231217. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  231218. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  231219. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  231220. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  231221. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  231222. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  231223. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  231224. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  231225. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  231226. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  231227. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  231228. results.add (pf);
  231229. p = aglNextPixelFormat (p);
  231230. }*/
  231231. //jassertfalse //xxx can't see how you do this in cocoa!
  231232. }
  231233. #else
  231234. END_JUCE_NAMESPACE
  231235. @interface JuceGLView : UIView
  231236. {
  231237. }
  231238. + (Class) layerClass;
  231239. @end
  231240. @implementation JuceGLView
  231241. + (Class) layerClass
  231242. {
  231243. return [CAEAGLLayer class];
  231244. }
  231245. @end
  231246. BEGIN_JUCE_NAMESPACE
  231247. class GLESContext : public OpenGLContext
  231248. {
  231249. public:
  231250. GLESContext (UIViewComponentPeer* peer,
  231251. Component* const component_,
  231252. const OpenGLPixelFormat& pixelFormat_,
  231253. const GLESContext* const sharedContext,
  231254. NSUInteger apiType)
  231255. : component (component_), pixelFormat (pixelFormat_), glLayer (0), context (0),
  231256. useDepthBuffer (pixelFormat_.depthBufferBits > 0), frameBufferHandle (0), colorBufferHandle (0),
  231257. depthBufferHandle (0), lastWidth (0), lastHeight (0)
  231258. {
  231259. view = [[JuceGLView alloc] initWithFrame: CGRectMake (0, 0, 64, 64)];
  231260. view.opaque = YES;
  231261. view.hidden = NO;
  231262. view.backgroundColor = [UIColor blackColor];
  231263. view.userInteractionEnabled = NO;
  231264. glLayer = (CAEAGLLayer*) [view layer];
  231265. [peer->view addSubview: view];
  231266. if (sharedContext != 0)
  231267. context = [[EAGLContext alloc] initWithAPI: apiType
  231268. sharegroup: [sharedContext->context sharegroup]];
  231269. else
  231270. context = [[EAGLContext alloc] initWithAPI: apiType];
  231271. createGLBuffers();
  231272. }
  231273. ~GLESContext()
  231274. {
  231275. makeInactive();
  231276. [context release];
  231277. [view removeFromSuperview];
  231278. [view release];
  231279. freeGLBuffers();
  231280. }
  231281. bool makeActive() const throw()
  231282. {
  231283. jassert (context != 0);
  231284. [EAGLContext setCurrentContext: context];
  231285. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  231286. return true;
  231287. }
  231288. void swapBuffers()
  231289. {
  231290. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  231291. [context presentRenderbuffer: GL_RENDERBUFFER_OES];
  231292. }
  231293. bool makeInactive() const throw()
  231294. {
  231295. return [EAGLContext setCurrentContext: nil];
  231296. }
  231297. bool isActive() const throw()
  231298. {
  231299. return [EAGLContext currentContext] == context;
  231300. }
  231301. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  231302. void* getRawContext() const throw() { return glLayer; }
  231303. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  231304. {
  231305. view.frame = CGRectMake ((CGFloat) x, (CGFloat) y, (CGFloat) w, (CGFloat) h);
  231306. if (lastWidth != w || lastHeight != h)
  231307. {
  231308. lastWidth = w;
  231309. lastHeight = h;
  231310. freeGLBuffers();
  231311. createGLBuffers();
  231312. }
  231313. }
  231314. bool setSwapInterval (const int numFramesPerSwap)
  231315. {
  231316. numFrames = numFramesPerSwap;
  231317. return true;
  231318. }
  231319. int getSwapInterval() const
  231320. {
  231321. return numFrames;
  231322. }
  231323. void repaint()
  231324. {
  231325. }
  231326. void createGLBuffers()
  231327. {
  231328. makeActive();
  231329. glGenFramebuffersOES (1, &frameBufferHandle);
  231330. glGenRenderbuffersOES (1, &colorBufferHandle);
  231331. glGenRenderbuffersOES (1, &depthBufferHandle);
  231332. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  231333. [context renderbufferStorage: GL_RENDERBUFFER_OES fromDrawable: glLayer];
  231334. GLint width, height;
  231335. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &width);
  231336. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &height);
  231337. if (useDepthBuffer)
  231338. {
  231339. glBindRenderbufferOES (GL_RENDERBUFFER_OES, depthBufferHandle);
  231340. glRenderbufferStorageOES (GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height);
  231341. }
  231342. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  231343. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  231344. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorBufferHandle);
  231345. if (useDepthBuffer)
  231346. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBufferHandle);
  231347. jassert (glCheckFramebufferStatusOES (GL_FRAMEBUFFER_OES) == GL_FRAMEBUFFER_COMPLETE_OES);
  231348. }
  231349. void freeGLBuffers()
  231350. {
  231351. if (frameBufferHandle != 0)
  231352. {
  231353. glDeleteFramebuffersOES (1, &frameBufferHandle);
  231354. frameBufferHandle = 0;
  231355. }
  231356. if (colorBufferHandle != 0)
  231357. {
  231358. glDeleteRenderbuffersOES (1, &colorBufferHandle);
  231359. colorBufferHandle = 0;
  231360. }
  231361. if (depthBufferHandle != 0)
  231362. {
  231363. glDeleteRenderbuffersOES (1, &depthBufferHandle);
  231364. depthBufferHandle = 0;
  231365. }
  231366. }
  231367. juce_UseDebuggingNewOperator
  231368. private:
  231369. Component::SafePointer<Component> component;
  231370. OpenGLPixelFormat pixelFormat;
  231371. JuceGLView* view;
  231372. CAEAGLLayer* glLayer;
  231373. EAGLContext* context;
  231374. bool useDepthBuffer;
  231375. GLuint frameBufferHandle, colorBufferHandle, depthBufferHandle;
  231376. int numFrames;
  231377. int lastWidth, lastHeight;
  231378. GLESContext (const GLESContext&);
  231379. GLESContext& operator= (const GLESContext&);
  231380. };
  231381. OpenGLContext* OpenGLComponent::createContext()
  231382. {
  231383. ScopedAutoReleasePool pool;
  231384. UIViewComponentPeer* peer = dynamic_cast <UIViewComponentPeer*> (getPeer());
  231385. if (peer != 0)
  231386. return new GLESContext (peer, this, preferredPixelFormat,
  231387. dynamic_cast <const GLESContext*> (contextToShareListsWith),
  231388. type == openGLES2 ? kEAGLRenderingAPIOpenGLES2 : kEAGLRenderingAPIOpenGLES1);
  231389. return 0;
  231390. }
  231391. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  231392. OwnedArray <OpenGLPixelFormat>& /*results*/)
  231393. {
  231394. }
  231395. void juce_glViewport (const int w, const int h)
  231396. {
  231397. glViewport (0, 0, w, h);
  231398. }
  231399. #endif
  231400. #endif
  231401. /*** End of inlined file: juce_mac_OpenGLComponent.mm ***/
  231402. /*** Start of inlined file: juce_mac_MainMenu.mm ***/
  231403. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  231404. // compiled on its own).
  231405. #if JUCE_INCLUDED_FILE
  231406. class JuceMainMenuHandler;
  231407. END_JUCE_NAMESPACE
  231408. using namespace JUCE_NAMESPACE;
  231409. #define JuceMenuCallback MakeObjCClassName(JuceMenuCallback)
  231410. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  231411. @interface JuceMenuCallback : NSObject <NSMenuDelegate>
  231412. #else
  231413. @interface JuceMenuCallback : NSObject
  231414. #endif
  231415. {
  231416. JuceMainMenuHandler* owner;
  231417. }
  231418. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_;
  231419. - (void) dealloc;
  231420. - (void) menuItemInvoked: (id) menu;
  231421. - (void) menuNeedsUpdate: (NSMenu*) menu;
  231422. @end
  231423. BEGIN_JUCE_NAMESPACE
  231424. class JuceMainMenuHandler : private MenuBarModelListener,
  231425. private DeletedAtShutdown
  231426. {
  231427. public:
  231428. static JuceMainMenuHandler* instance;
  231429. JuceMainMenuHandler()
  231430. : currentModel (0),
  231431. lastUpdateTime (0)
  231432. {
  231433. callback = [[JuceMenuCallback alloc] initWithOwner: this];
  231434. }
  231435. ~JuceMainMenuHandler()
  231436. {
  231437. setMenu (0);
  231438. jassert (instance == this);
  231439. instance = 0;
  231440. [callback release];
  231441. }
  231442. void setMenu (MenuBarModel* const newMenuBarModel)
  231443. {
  231444. if (currentModel != newMenuBarModel)
  231445. {
  231446. if (currentModel != 0)
  231447. currentModel->removeListener (this);
  231448. currentModel = newMenuBarModel;
  231449. if (currentModel != 0)
  231450. currentModel->addListener (this);
  231451. menuBarItemsChanged (0);
  231452. }
  231453. }
  231454. void addSubMenu (NSMenu* parent, const PopupMenu& child,
  231455. const String& name, const int menuId, const int tag)
  231456. {
  231457. NSMenuItem* item = [parent addItemWithTitle: juceStringToNS (name)
  231458. action: nil
  231459. keyEquivalent: @""];
  231460. [item setTag: tag];
  231461. NSMenu* sub = createMenu (child, name, menuId, tag);
  231462. [parent setSubmenu: sub forItem: item];
  231463. [sub setAutoenablesItems: false];
  231464. [sub release];
  231465. }
  231466. void updateSubMenu (NSMenuItem* parentItem, const PopupMenu& menuToCopy,
  231467. const String& name, const int menuId, const int tag)
  231468. {
  231469. [parentItem setTag: tag];
  231470. NSMenu* menu = [parentItem submenu];
  231471. [menu setTitle: juceStringToNS (name)];
  231472. while ([menu numberOfItems] > 0)
  231473. [menu removeItemAtIndex: 0];
  231474. PopupMenu::MenuItemIterator iter (menuToCopy);
  231475. while (iter.next())
  231476. addMenuItem (iter, menu, menuId, tag);
  231477. [menu setAutoenablesItems: false];
  231478. [menu update];
  231479. }
  231480. void menuBarItemsChanged (MenuBarModel*)
  231481. {
  231482. lastUpdateTime = Time::getMillisecondCounter();
  231483. StringArray menuNames;
  231484. if (currentModel != 0)
  231485. menuNames = currentModel->getMenuBarNames();
  231486. NSMenu* menuBar = [NSApp mainMenu];
  231487. while ([menuBar numberOfItems] > 1 + menuNames.size())
  231488. [menuBar removeItemAtIndex: [menuBar numberOfItems] - 1];
  231489. int menuId = 1;
  231490. for (int i = 0; i < menuNames.size(); ++i)
  231491. {
  231492. const PopupMenu menu (currentModel->getMenuForIndex (i, menuNames [i]));
  231493. if (i >= [menuBar numberOfItems] - 1)
  231494. addSubMenu (menuBar, menu, menuNames[i], menuId, i);
  231495. else
  231496. updateSubMenu ([menuBar itemAtIndex: 1 + i], menu, menuNames[i], menuId, i);
  231497. }
  231498. }
  231499. static void flashMenuBar (NSMenu* menu)
  231500. {
  231501. if ([[menu title] isEqualToString: @"Apple"])
  231502. return;
  231503. [menu retain];
  231504. const unichar f35Key = NSF35FunctionKey;
  231505. NSString* f35String = [NSString stringWithCharacters: &f35Key length: 1];
  231506. NSMenuItem* item = [[NSMenuItem alloc] initWithTitle: @"x"
  231507. action: nil
  231508. keyEquivalent: f35String];
  231509. [item setTarget: nil];
  231510. [menu insertItem: item atIndex: [menu numberOfItems]];
  231511. [item release];
  231512. if ([menu indexOfItem: item] >= 0)
  231513. {
  231514. NSEvent* f35Event = [NSEvent keyEventWithType: NSKeyDown
  231515. location: NSZeroPoint
  231516. modifierFlags: NSCommandKeyMask
  231517. timestamp: 0
  231518. windowNumber: 0
  231519. context: [NSGraphicsContext currentContext]
  231520. characters: f35String
  231521. charactersIgnoringModifiers: f35String
  231522. isARepeat: NO
  231523. keyCode: 0];
  231524. [menu performKeyEquivalent: f35Event];
  231525. if ([menu indexOfItem: item] >= 0)
  231526. [menu removeItem: item]; // (this throws if the item isn't actually in the menu)
  231527. }
  231528. [menu release];
  231529. }
  231530. static NSMenuItem* findMenuItem (NSMenu* const menu, const ApplicationCommandTarget::InvocationInfo& info)
  231531. {
  231532. for (NSInteger i = [menu numberOfItems]; --i >= 0;)
  231533. {
  231534. NSMenuItem* m = [menu itemAtIndex: i];
  231535. if ([m tag] == info.commandID)
  231536. return m;
  231537. if ([m submenu] != 0)
  231538. {
  231539. NSMenuItem* found = findMenuItem ([m submenu], info);
  231540. if (found != 0)
  231541. return found;
  231542. }
  231543. }
  231544. return 0;
  231545. }
  231546. void menuCommandInvoked (MenuBarModel*, const ApplicationCommandTarget::InvocationInfo& info)
  231547. {
  231548. NSMenuItem* item = findMenuItem ([NSApp mainMenu], info);
  231549. if (item != 0)
  231550. flashMenuBar ([item menu]);
  231551. }
  231552. void updateMenus()
  231553. {
  231554. if (Time::getMillisecondCounter() > lastUpdateTime + 500)
  231555. menuBarItemsChanged (0);
  231556. }
  231557. void invoke (const int commandId, ApplicationCommandManager* const commandManager, const int topLevelIndex) const
  231558. {
  231559. if (currentModel != 0)
  231560. {
  231561. if (commandManager != 0)
  231562. {
  231563. ApplicationCommandTarget::InvocationInfo info (commandId);
  231564. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  231565. commandManager->invoke (info, true);
  231566. }
  231567. currentModel->menuItemSelected (commandId, topLevelIndex);
  231568. }
  231569. }
  231570. MenuBarModel* currentModel;
  231571. uint32 lastUpdateTime;
  231572. void addMenuItem (PopupMenu::MenuItemIterator& iter, NSMenu* menuToAddTo,
  231573. const int topLevelMenuId, const int topLevelIndex)
  231574. {
  231575. NSString* text = juceStringToNS (iter.itemName.upToFirstOccurrenceOf ("<end>", false, true));
  231576. if (text == 0)
  231577. text = @"";
  231578. if (iter.isSeparator)
  231579. {
  231580. [menuToAddTo addItem: [NSMenuItem separatorItem]];
  231581. }
  231582. else if (iter.isSectionHeader)
  231583. {
  231584. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  231585. action: nil
  231586. keyEquivalent: @""];
  231587. [item setEnabled: false];
  231588. }
  231589. else if (iter.subMenu != 0)
  231590. {
  231591. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  231592. action: nil
  231593. keyEquivalent: @""];
  231594. [item setTag: iter.itemId];
  231595. [item setEnabled: iter.isEnabled];
  231596. NSMenu* sub = createMenu (*iter.subMenu, iter.itemName, topLevelMenuId, topLevelIndex);
  231597. [sub setDelegate: nil];
  231598. [menuToAddTo setSubmenu: sub forItem: item];
  231599. [sub release];
  231600. }
  231601. else
  231602. {
  231603. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  231604. action: @selector (menuItemInvoked:)
  231605. keyEquivalent: @""];
  231606. [item setTag: iter.itemId];
  231607. [item setEnabled: iter.isEnabled];
  231608. [item setState: iter.isTicked ? NSOnState : NSOffState];
  231609. [item setTarget: (id) callback];
  231610. NSMutableArray* info = [NSMutableArray arrayWithObject: [NSNumber numberWithUnsignedLongLong: (pointer_sized_int) (void*) iter.commandManager]];
  231611. [info addObject: [NSNumber numberWithInt: topLevelIndex]];
  231612. [item setRepresentedObject: info];
  231613. if (iter.commandManager != 0)
  231614. {
  231615. const Array <KeyPress> keyPresses (iter.commandManager->getKeyMappings()
  231616. ->getKeyPressesAssignedToCommand (iter.itemId));
  231617. if (keyPresses.size() > 0)
  231618. {
  231619. const KeyPress& kp = keyPresses.getReference(0);
  231620. if (kp.getKeyCode() != KeyPress::backspaceKey
  231621. && kp.getKeyCode() != KeyPress::deleteKey) // (adding these is annoying because it flashes the menu bar
  231622. // every time you press the key while editing text)
  231623. {
  231624. juce_wchar key = kp.getTextCharacter();
  231625. if (kp.getKeyCode() == KeyPress::backspaceKey)
  231626. key = NSBackspaceCharacter;
  231627. else if (kp.getKeyCode() == KeyPress::deleteKey)
  231628. key = NSDeleteCharacter;
  231629. else if (key == 0)
  231630. key = (juce_wchar) kp.getKeyCode();
  231631. unsigned int mods = 0;
  231632. if (kp.getModifiers().isShiftDown())
  231633. mods |= NSShiftKeyMask;
  231634. if (kp.getModifiers().isCtrlDown())
  231635. mods |= NSControlKeyMask;
  231636. if (kp.getModifiers().isAltDown())
  231637. mods |= NSAlternateKeyMask;
  231638. if (kp.getModifiers().isCommandDown())
  231639. mods |= NSCommandKeyMask;
  231640. [item setKeyEquivalent: juceStringToNS (String::charToString (key))];
  231641. [item setKeyEquivalentModifierMask: mods];
  231642. }
  231643. }
  231644. }
  231645. }
  231646. }
  231647. JuceMenuCallback* callback;
  231648. private:
  231649. NSMenu* createMenu (const PopupMenu menu,
  231650. const String& menuName,
  231651. const int topLevelMenuId,
  231652. const int topLevelIndex)
  231653. {
  231654. NSMenu* m = [[NSMenu alloc] initWithTitle: juceStringToNS (menuName)];
  231655. [m setAutoenablesItems: false];
  231656. [m setDelegate: callback];
  231657. PopupMenu::MenuItemIterator iter (menu);
  231658. while (iter.next())
  231659. addMenuItem (iter, m, topLevelMenuId, topLevelIndex);
  231660. [m update];
  231661. return m;
  231662. }
  231663. };
  231664. JuceMainMenuHandler* JuceMainMenuHandler::instance = 0;
  231665. END_JUCE_NAMESPACE
  231666. @implementation JuceMenuCallback
  231667. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_
  231668. {
  231669. [super init];
  231670. owner = owner_;
  231671. return self;
  231672. }
  231673. - (void) dealloc
  231674. {
  231675. [super dealloc];
  231676. }
  231677. - (void) menuItemInvoked: (id) menu
  231678. {
  231679. NSMenuItem* item = (NSMenuItem*) menu;
  231680. if ([[item representedObject] isKindOfClass: [NSArray class]])
  231681. {
  231682. // 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
  231683. // our own components, which may have wanted to intercept it. So, rather than dispatching directly, we'll feed it back
  231684. // into the focused component and let it trigger the menu item indirectly.
  231685. NSEvent* e = [NSApp currentEvent];
  231686. if ([e type] == NSKeyDown || [e type] == NSKeyUp)
  231687. {
  231688. if (JUCE_NAMESPACE::Component::getCurrentlyFocusedComponent() != 0)
  231689. {
  231690. JUCE_NAMESPACE::NSViewComponentPeer* peer = dynamic_cast <JUCE_NAMESPACE::NSViewComponentPeer*> (JUCE_NAMESPACE::Component::getCurrentlyFocusedComponent()->getPeer());
  231691. if (peer != 0)
  231692. {
  231693. if ([e type] == NSKeyDown)
  231694. peer->redirectKeyDown (e);
  231695. else
  231696. peer->redirectKeyUp (e);
  231697. return;
  231698. }
  231699. }
  231700. }
  231701. NSArray* info = (NSArray*) [item representedObject];
  231702. owner->invoke ((int) [item tag],
  231703. (ApplicationCommandManager*) (pointer_sized_int)
  231704. [((NSNumber*) [info objectAtIndex: 0]) unsignedLongLongValue],
  231705. (int) [((NSNumber*) [info objectAtIndex: 1]) intValue]);
  231706. }
  231707. }
  231708. - (void) menuNeedsUpdate: (NSMenu*) menu;
  231709. {
  231710. (void) menu;
  231711. if (JuceMainMenuHandler::instance != 0)
  231712. JuceMainMenuHandler::instance->updateMenus();
  231713. }
  231714. @end
  231715. BEGIN_JUCE_NAMESPACE
  231716. static NSMenu* createStandardAppMenu (NSMenu* menu, const String& appName,
  231717. const PopupMenu* extraItems)
  231718. {
  231719. if (extraItems != 0 && JuceMainMenuHandler::instance != 0 && extraItems->getNumItems() > 0)
  231720. {
  231721. PopupMenu::MenuItemIterator iter (*extraItems);
  231722. while (iter.next())
  231723. JuceMainMenuHandler::instance->addMenuItem (iter, menu, 0, -1);
  231724. [menu addItem: [NSMenuItem separatorItem]];
  231725. }
  231726. NSMenuItem* item;
  231727. // Services...
  231728. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Services", nil)
  231729. action: nil keyEquivalent: @""];
  231730. [menu addItem: item];
  231731. [item release];
  231732. NSMenu* servicesMenu = [[NSMenu alloc] initWithTitle: @"Services"];
  231733. [menu setSubmenu: servicesMenu forItem: item];
  231734. [NSApp setServicesMenu: servicesMenu];
  231735. [servicesMenu release];
  231736. [menu addItem: [NSMenuItem separatorItem]];
  231737. // Hide + Show stuff...
  231738. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Hide " + appName)
  231739. action: @selector (hide:) keyEquivalent: @"h"];
  231740. [item setTarget: NSApp];
  231741. [menu addItem: item];
  231742. [item release];
  231743. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Hide Others", nil)
  231744. action: @selector (hideOtherApplications:) keyEquivalent: @"h"];
  231745. [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
  231746. [item setTarget: NSApp];
  231747. [menu addItem: item];
  231748. [item release];
  231749. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Show All", nil)
  231750. action: @selector (unhideAllApplications:) keyEquivalent: @""];
  231751. [item setTarget: NSApp];
  231752. [menu addItem: item];
  231753. [item release];
  231754. [menu addItem: [NSMenuItem separatorItem]];
  231755. // Quit item....
  231756. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Quit " + appName)
  231757. action: @selector (terminate:) keyEquivalent: @"q"];
  231758. [item setTarget: NSApp];
  231759. [menu addItem: item];
  231760. [item release];
  231761. return menu;
  231762. }
  231763. // Since our app has no NIB, this initialises a standard app menu...
  231764. static void rebuildMainMenu (const PopupMenu* extraItems)
  231765. {
  231766. // this can't be used in a plugin!
  231767. jassert (JUCEApplication::getInstance() != 0);
  231768. if (JUCEApplication::getInstance() != 0)
  231769. {
  231770. const ScopedAutoReleasePool pool;
  231771. NSMenu* mainMenu = [[NSMenu alloc] initWithTitle: @"MainMenu"];
  231772. NSMenuItem* item = [mainMenu addItemWithTitle: @"Apple" action: nil keyEquivalent: @""];
  231773. NSMenu* appMenu = [[NSMenu alloc] initWithTitle: @"Apple"];
  231774. [NSApp performSelector: @selector (setAppleMenu:) withObject: appMenu];
  231775. [mainMenu setSubmenu: appMenu forItem: item];
  231776. [NSApp setMainMenu: mainMenu];
  231777. createStandardAppMenu (appMenu, JUCEApplication::getInstance()->getApplicationName(), extraItems);
  231778. [appMenu release];
  231779. [mainMenu release];
  231780. }
  231781. }
  231782. void MenuBarModel::setMacMainMenu (MenuBarModel* newMenuBarModel,
  231783. const PopupMenu* extraAppleMenuItems)
  231784. {
  231785. if (getMacMainMenu() != newMenuBarModel)
  231786. {
  231787. const ScopedAutoReleasePool pool;
  231788. if (newMenuBarModel == 0)
  231789. {
  231790. delete JuceMainMenuHandler::instance;
  231791. jassert (JuceMainMenuHandler::instance == 0); // should be zeroed in the destructor
  231792. jassert (extraAppleMenuItems == 0); // you can't specify some extra items without also supplying a model
  231793. extraAppleMenuItems = 0;
  231794. }
  231795. else
  231796. {
  231797. if (JuceMainMenuHandler::instance == 0)
  231798. JuceMainMenuHandler::instance = new JuceMainMenuHandler();
  231799. JuceMainMenuHandler::instance->setMenu (newMenuBarModel);
  231800. }
  231801. }
  231802. rebuildMainMenu (extraAppleMenuItems);
  231803. if (newMenuBarModel != 0)
  231804. newMenuBarModel->menuItemsChanged();
  231805. }
  231806. MenuBarModel* MenuBarModel::getMacMainMenu()
  231807. {
  231808. return JuceMainMenuHandler::instance != 0
  231809. ? JuceMainMenuHandler::instance->currentModel : 0;
  231810. }
  231811. void initialiseMainMenu()
  231812. {
  231813. if (JUCEApplication::getInstance() != 0) // only needed in an app
  231814. rebuildMainMenu (0);
  231815. }
  231816. #endif
  231817. /*** End of inlined file: juce_mac_MainMenu.mm ***/
  231818. /*** Start of inlined file: juce_mac_FileChooser.mm ***/
  231819. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  231820. // compiled on its own).
  231821. #if JUCE_INCLUDED_FILE
  231822. #if JUCE_MAC
  231823. END_JUCE_NAMESPACE
  231824. using namespace JUCE_NAMESPACE;
  231825. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  231826. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  231827. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  231828. #else
  231829. @interface JuceFileChooserDelegate : NSObject
  231830. #endif
  231831. {
  231832. StringArray* filters;
  231833. }
  231834. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  231835. - (void) dealloc;
  231836. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  231837. @end
  231838. @implementation JuceFileChooserDelegate
  231839. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  231840. {
  231841. [super init];
  231842. filters = filters_;
  231843. return self;
  231844. }
  231845. - (void) dealloc
  231846. {
  231847. delete filters;
  231848. [super dealloc];
  231849. }
  231850. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  231851. {
  231852. (void) sender;
  231853. const File f (nsStringToJuce (filename));
  231854. for (int i = filters->size(); --i >= 0;)
  231855. if (f.getFileName().matchesWildcard ((*filters)[i], true))
  231856. return true;
  231857. return f.isDirectory();
  231858. }
  231859. @end
  231860. BEGIN_JUCE_NAMESPACE
  231861. void FileChooser::showPlatformDialog (Array<File>& results,
  231862. const String& title,
  231863. const File& currentFileOrDirectory,
  231864. const String& filter,
  231865. bool selectsDirectory,
  231866. bool selectsFiles,
  231867. bool isSaveDialogue,
  231868. bool warnAboutOverwritingExistingFiles,
  231869. bool selectMultipleFiles,
  231870. FilePreviewComponent* extraInfoComponent)
  231871. {
  231872. const ScopedAutoReleasePool pool;
  231873. StringArray* filters = new StringArray();
  231874. filters->addTokens (filter.replaceCharacters (",:", ";;"), ";", String::empty);
  231875. filters->trim();
  231876. filters->removeEmptyStrings();
  231877. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  231878. [delegate autorelease];
  231879. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  231880. : [NSOpenPanel openPanel];
  231881. [panel setTitle: juceStringToNS (title)];
  231882. if (! isSaveDialogue)
  231883. {
  231884. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  231885. [openPanel setCanChooseDirectories: selectsDirectory];
  231886. [openPanel setCanChooseFiles: selectsFiles];
  231887. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  231888. }
  231889. [panel setDelegate: delegate];
  231890. if (isSaveDialogue || selectsDirectory)
  231891. [panel setCanCreateDirectories: YES];
  231892. String directory, filename;
  231893. if (currentFileOrDirectory.isDirectory())
  231894. {
  231895. directory = currentFileOrDirectory.getFullPathName();
  231896. }
  231897. else
  231898. {
  231899. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  231900. filename = currentFileOrDirectory.getFileName();
  231901. }
  231902. if ([panel runModalForDirectory: juceStringToNS (directory)
  231903. file: juceStringToNS (filename)]
  231904. == NSOKButton)
  231905. {
  231906. if (isSaveDialogue)
  231907. {
  231908. results.add (File (nsStringToJuce ([panel filename])));
  231909. }
  231910. else
  231911. {
  231912. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  231913. NSArray* urls = [openPanel filenames];
  231914. for (unsigned int i = 0; i < [urls count]; ++i)
  231915. {
  231916. NSString* f = [urls objectAtIndex: i];
  231917. results.add (File (nsStringToJuce (f)));
  231918. }
  231919. }
  231920. }
  231921. [panel setDelegate: nil];
  231922. }
  231923. #else
  231924. void FileChooser::showPlatformDialog (Array<File>& results,
  231925. const String& title,
  231926. const File& currentFileOrDirectory,
  231927. const String& filter,
  231928. bool selectsDirectory,
  231929. bool selectsFiles,
  231930. bool isSaveDialogue,
  231931. bool warnAboutOverwritingExistingFiles,
  231932. bool selectMultipleFiles,
  231933. FilePreviewComponent* extraInfoComponent)
  231934. {
  231935. const ScopedAutoReleasePool pool;
  231936. jassertfalse; //xxx to do
  231937. }
  231938. #endif
  231939. #endif
  231940. /*** End of inlined file: juce_mac_FileChooser.mm ***/
  231941. /*** Start of inlined file: juce_mac_QuickTimeMovieComponent.mm ***/
  231942. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  231943. // compiled on its own).
  231944. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  231945. END_JUCE_NAMESPACE
  231946. #define NonInterceptingQTMovieView MakeObjCClassName(NonInterceptingQTMovieView)
  231947. @interface NonInterceptingQTMovieView : QTMovieView
  231948. {
  231949. }
  231950. - (id) initWithFrame: (NSRect) frame;
  231951. - (BOOL) acceptsFirstMouse: (NSEvent*) theEvent;
  231952. - (NSView*) hitTest: (NSPoint) p;
  231953. @end
  231954. @implementation NonInterceptingQTMovieView
  231955. - (id) initWithFrame: (NSRect) frame
  231956. {
  231957. self = [super initWithFrame: frame];
  231958. [self setNextResponder: [self superview]];
  231959. return self;
  231960. }
  231961. - (void) dealloc
  231962. {
  231963. [super dealloc];
  231964. }
  231965. - (NSView*) hitTest: (NSPoint) point
  231966. {
  231967. return [self isControllerVisible] ? [super hitTest: point] : nil;
  231968. }
  231969. - (BOOL) acceptsFirstMouse: (NSEvent*) theEvent
  231970. {
  231971. return YES;
  231972. }
  231973. @end
  231974. BEGIN_JUCE_NAMESPACE
  231975. #define theMovie (static_cast <QTMovie*> (movie))
  231976. QuickTimeMovieComponent::QuickTimeMovieComponent()
  231977. : movie (0)
  231978. {
  231979. setOpaque (true);
  231980. setVisible (true);
  231981. QTMovieView* view = [[NonInterceptingQTMovieView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)];
  231982. setView (view);
  231983. [view release];
  231984. }
  231985. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  231986. {
  231987. closeMovie();
  231988. setView (0);
  231989. }
  231990. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  231991. {
  231992. return true;
  231993. }
  231994. static QTMovie* openMovieFromStream (InputStream* movieStream, File& movieFile)
  231995. {
  231996. // unfortunately, QTMovie objects can only be created on the main thread..
  231997. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  231998. QTMovie* movie = 0;
  231999. FileInputStream* const fin = dynamic_cast <FileInputStream*> (movieStream);
  232000. if (fin != 0)
  232001. {
  232002. movieFile = fin->getFile();
  232003. movie = [QTMovie movieWithFile: juceStringToNS (movieFile.getFullPathName())
  232004. error: nil];
  232005. }
  232006. else
  232007. {
  232008. MemoryBlock temp;
  232009. movieStream->readIntoMemoryBlock (temp);
  232010. const char* const suffixesToTry[] = { ".mov", ".mp3", ".avi", ".m4a" };
  232011. for (int i = 0; i < numElementsInArray (suffixesToTry); ++i)
  232012. {
  232013. movie = [QTMovie movieWithDataReference: [QTDataReference dataReferenceWithReferenceToData: [NSData dataWithBytes: temp.getData()
  232014. length: temp.getSize()]
  232015. name: [NSString stringWithUTF8String: suffixesToTry[i]]
  232016. MIMEType: @""]
  232017. error: nil];
  232018. if (movie != 0)
  232019. break;
  232020. }
  232021. }
  232022. return movie;
  232023. }
  232024. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  232025. const bool isControllerVisible_)
  232026. {
  232027. return loadMovie ((InputStream*) movieFile_.createInputStream(), isControllerVisible_);
  232028. }
  232029. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  232030. const bool controllerVisible_)
  232031. {
  232032. closeMovie();
  232033. if (getPeer() == 0)
  232034. {
  232035. // To open a movie, this component must be visible inside a functioning window, so that
  232036. // the QT control can be assigned to the window.
  232037. jassertfalse;
  232038. return false;
  232039. }
  232040. movie = openMovieFromStream (movieStream, movieFile);
  232041. [theMovie retain];
  232042. QTMovieView* view = (QTMovieView*) getView();
  232043. [view setMovie: theMovie];
  232044. [view setControllerVisible: controllerVisible_];
  232045. setLooping (looping);
  232046. return movie != nil;
  232047. }
  232048. bool QuickTimeMovieComponent::loadMovie (const URL& movieURL,
  232049. const bool isControllerVisible_)
  232050. {
  232051. // unfortunately, QTMovie objects can only be created on the main thread..
  232052. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  232053. closeMovie();
  232054. if (getPeer() == 0)
  232055. {
  232056. // To open a movie, this component must be visible inside a functioning window, so that
  232057. // the QT control can be assigned to the window.
  232058. jassertfalse;
  232059. return false;
  232060. }
  232061. NSURL* url = [NSURL URLWithString: juceStringToNS (movieURL.toString (true))];
  232062. NSError* err;
  232063. if ([QTMovie canInitWithURL: url])
  232064. movie = [QTMovie movieWithURL: url error: &err];
  232065. [theMovie retain];
  232066. QTMovieView* view = (QTMovieView*) getView();
  232067. [view setMovie: theMovie];
  232068. [view setControllerVisible: controllerVisible];
  232069. setLooping (looping);
  232070. return movie != nil;
  232071. }
  232072. void QuickTimeMovieComponent::closeMovie()
  232073. {
  232074. stop();
  232075. QTMovieView* view = (QTMovieView*) getView();
  232076. [view setMovie: nil];
  232077. [theMovie release];
  232078. movie = 0;
  232079. movieFile = File::nonexistent;
  232080. }
  232081. bool QuickTimeMovieComponent::isMovieOpen() const
  232082. {
  232083. return movie != nil;
  232084. }
  232085. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  232086. {
  232087. return movieFile;
  232088. }
  232089. void QuickTimeMovieComponent::play()
  232090. {
  232091. [theMovie play];
  232092. }
  232093. void QuickTimeMovieComponent::stop()
  232094. {
  232095. [theMovie stop];
  232096. }
  232097. bool QuickTimeMovieComponent::isPlaying() const
  232098. {
  232099. return movie != 0 && [theMovie rate] != 0;
  232100. }
  232101. void QuickTimeMovieComponent::setPosition (const double seconds)
  232102. {
  232103. if (movie != 0)
  232104. {
  232105. QTTime t;
  232106. t.timeValue = (uint64) (100000.0 * seconds);
  232107. t.timeScale = 100000;
  232108. t.flags = 0;
  232109. [theMovie setCurrentTime: t];
  232110. }
  232111. }
  232112. double QuickTimeMovieComponent::getPosition() const
  232113. {
  232114. if (movie == 0)
  232115. return 0.0;
  232116. QTTime t = [theMovie currentTime];
  232117. return t.timeValue / (double) t.timeScale;
  232118. }
  232119. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  232120. {
  232121. [theMovie setRate: newSpeed];
  232122. }
  232123. double QuickTimeMovieComponent::getMovieDuration() const
  232124. {
  232125. if (movie == 0)
  232126. return 0.0;
  232127. QTTime t = [theMovie duration];
  232128. return t.timeValue / (double) t.timeScale;
  232129. }
  232130. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  232131. {
  232132. looping = shouldLoop;
  232133. [theMovie setAttribute: [NSNumber numberWithBool: shouldLoop]
  232134. forKey: QTMovieLoopsAttribute];
  232135. }
  232136. bool QuickTimeMovieComponent::isLooping() const
  232137. {
  232138. return looping;
  232139. }
  232140. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  232141. {
  232142. [theMovie setVolume: newVolume];
  232143. }
  232144. float QuickTimeMovieComponent::getMovieVolume() const
  232145. {
  232146. return movie != 0 ? [theMovie volume] : 0.0f;
  232147. }
  232148. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  232149. {
  232150. width = 0;
  232151. height = 0;
  232152. if (movie != 0)
  232153. {
  232154. NSSize s = [[theMovie attributeForKey: QTMovieNaturalSizeAttribute] sizeValue];
  232155. width = (int) s.width;
  232156. height = (int) s.height;
  232157. }
  232158. }
  232159. void QuickTimeMovieComponent::paint (Graphics& g)
  232160. {
  232161. if (movie == 0)
  232162. g.fillAll (Colours::black);
  232163. }
  232164. bool QuickTimeMovieComponent::isControllerVisible() const
  232165. {
  232166. return controllerVisible;
  232167. }
  232168. void QuickTimeMovieComponent::goToStart()
  232169. {
  232170. setPosition (0.0);
  232171. }
  232172. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  232173. const RectanglePlacement& placement)
  232174. {
  232175. int normalWidth, normalHeight;
  232176. getMovieNormalSize (normalWidth, normalHeight);
  232177. if (normalWidth > 0 && normalHeight > 0 && ! spaceToFitWithin.isEmpty())
  232178. {
  232179. double x = 0.0, y = 0.0, w = normalWidth, h = normalHeight;
  232180. placement.applyTo (x, y, w, h,
  232181. spaceToFitWithin.getX(), spaceToFitWithin.getY(),
  232182. spaceToFitWithin.getWidth(), spaceToFitWithin.getHeight());
  232183. if (w > 0 && h > 0)
  232184. {
  232185. setBounds (roundToInt (x), roundToInt (y),
  232186. roundToInt (w), roundToInt (h));
  232187. }
  232188. }
  232189. else
  232190. {
  232191. setBounds (spaceToFitWithin);
  232192. }
  232193. }
  232194. #if ! (JUCE_MAC && JUCE_64BIT)
  232195. bool juce_OpenQuickTimeMovieFromStream (InputStream* movieStream, Movie& result, Handle& dataHandle)
  232196. {
  232197. if (movieStream == 0)
  232198. return false;
  232199. File file;
  232200. QTMovie* movie = openMovieFromStream (movieStream, file);
  232201. if (movie != nil)
  232202. result = [movie quickTimeMovie];
  232203. return movie != nil;
  232204. }
  232205. #endif
  232206. #endif
  232207. /*** End of inlined file: juce_mac_QuickTimeMovieComponent.mm ***/
  232208. /*** Start of inlined file: juce_mac_AudioCDBurner.mm ***/
  232209. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232210. // compiled on its own).
  232211. #if JUCE_INCLUDED_FILE && JUCE_USE_CDBURNER
  232212. const int kilobytesPerSecond1x = 176;
  232213. END_JUCE_NAMESPACE
  232214. #define OpenDiskDevice MakeObjCClassName(OpenDiskDevice)
  232215. @interface OpenDiskDevice : NSObject
  232216. {
  232217. @public
  232218. DRDevice* device;
  232219. NSMutableArray* tracks;
  232220. bool underrunProtection;
  232221. }
  232222. - (OpenDiskDevice*) initWithDRDevice: (DRDevice*) device;
  232223. - (void) dealloc;
  232224. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) numSamples_;
  232225. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  232226. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting speed: (int) burnSpeed;
  232227. @end
  232228. #define AudioTrackProducer MakeObjCClassName(AudioTrackProducer)
  232229. @interface AudioTrackProducer : NSObject
  232230. {
  232231. JUCE_NAMESPACE::AudioSource* source;
  232232. int readPosition, lengthInFrames;
  232233. }
  232234. - (AudioTrackProducer*) init: (int) lengthInFrames;
  232235. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) lengthInSamples;
  232236. - (void) dealloc;
  232237. - (void) setupTrackProperties: (DRTrack*) track;
  232238. - (void) cleanupTrackAfterBurn: (DRTrack*) track;
  232239. - (BOOL) cleanupTrackAfterVerification:(DRTrack*)track;
  232240. - (uint64_t) estimateLengthOfTrack:(DRTrack*)track;
  232241. - (BOOL) prepareTrack:(DRTrack*)track forBurn:(DRBurn*)burn
  232242. toMedia:(NSDictionary*)mediaInfo;
  232243. - (BOOL) prepareTrackForVerification:(DRTrack*)track;
  232244. - (uint32_t) produceDataForTrack:(DRTrack*)track intoBuffer:(char*)buffer
  232245. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  232246. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  232247. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  232248. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  232249. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  232250. ioFlags:(uint32_t*)flags;
  232251. - (BOOL) verifyDataForTrack:(DRTrack*)track inBuffer:(const char*)buffer
  232252. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  232253. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  232254. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  232255. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  232256. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  232257. ioFlags:(uint32_t*)flags;
  232258. @end
  232259. @implementation OpenDiskDevice
  232260. - (OpenDiskDevice*) initWithDRDevice: (DRDevice*) device_
  232261. {
  232262. [super init];
  232263. device = device_;
  232264. tracks = [[NSMutableArray alloc] init];
  232265. underrunProtection = true;
  232266. return self;
  232267. }
  232268. - (void) dealloc
  232269. {
  232270. [tracks release];
  232271. [super dealloc];
  232272. }
  232273. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) numSamples_
  232274. {
  232275. AudioTrackProducer* p = [[AudioTrackProducer alloc] initWithAudioSource: source_ numSamples: numSamples_];
  232276. DRTrack* t = [[DRTrack alloc] initWithProducer: p];
  232277. [p setupTrackProperties: t];
  232278. [tracks addObject: t];
  232279. [t release];
  232280. [p release];
  232281. }
  232282. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  232283. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting speed: (int) burnSpeed
  232284. {
  232285. DRBurn* burn = [DRBurn burnForDevice: device];
  232286. if (! [device acquireExclusiveAccess])
  232287. {
  232288. *error = "Couldn't open or write to the CD device";
  232289. return;
  232290. }
  232291. [device acquireMediaReservation];
  232292. NSMutableDictionary* d = [[burn properties] mutableCopy];
  232293. [d autorelease];
  232294. [d setObject: [NSNumber numberWithBool: peformFakeBurnForTesting] forKey: DRBurnTestingKey];
  232295. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnVerifyDiscKey];
  232296. [d setObject: (shouldEject ? DRBurnCompletionActionEject : DRBurnCompletionActionMount) forKey: DRBurnCompletionActionKey];
  232297. if (burnSpeed > 0)
  232298. [d setObject: [NSNumber numberWithFloat: burnSpeed * JUCE_NAMESPACE::kilobytesPerSecond1x] forKey: DRBurnRequestedSpeedKey];
  232299. if (! underrunProtection)
  232300. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnUnderrunProtectionKey];
  232301. [burn setProperties: d];
  232302. [burn writeLayout: tracks];
  232303. for (;;)
  232304. {
  232305. JUCE_NAMESPACE::Thread::sleep (300);
  232306. float progress = [[[burn status] objectForKey: DRStatusPercentCompleteKey] floatValue];
  232307. if (listener != 0 && listener->audioCDBurnProgress (progress))
  232308. {
  232309. [burn abort];
  232310. *error = "User cancelled the write operation";
  232311. break;
  232312. }
  232313. if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateFailed])
  232314. {
  232315. *error = "Write operation failed";
  232316. break;
  232317. }
  232318. else if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateDone])
  232319. {
  232320. break;
  232321. }
  232322. NSString* err = (NSString*) [[[burn status] objectForKey: DRErrorStatusKey]
  232323. objectForKey: DRErrorStatusErrorStringKey];
  232324. if ([err length] > 0)
  232325. {
  232326. *error = JUCE_NAMESPACE::String::fromUTF8 ([err UTF8String]);
  232327. break;
  232328. }
  232329. }
  232330. [device releaseMediaReservation];
  232331. [device releaseExclusiveAccess];
  232332. }
  232333. @end
  232334. @implementation AudioTrackProducer
  232335. - (AudioTrackProducer*) init: (int) lengthInFrames_
  232336. {
  232337. lengthInFrames = lengthInFrames_;
  232338. readPosition = 0;
  232339. return self;
  232340. }
  232341. - (void) setupTrackProperties: (DRTrack*) track
  232342. {
  232343. NSMutableDictionary* p = [[track properties] mutableCopy];
  232344. [p setObject:[DRMSF msfWithFrames: lengthInFrames] forKey: DRTrackLengthKey];
  232345. [p setObject:[NSNumber numberWithUnsignedShort:2352] forKey: DRBlockSizeKey];
  232346. [p setObject:[NSNumber numberWithInt:0] forKey: DRDataFormKey];
  232347. [p setObject:[NSNumber numberWithInt:0] forKey: DRBlockTypeKey];
  232348. [p setObject:[NSNumber numberWithInt:0] forKey: DRTrackModeKey];
  232349. [p setObject:[NSNumber numberWithInt:0] forKey: DRSessionFormatKey];
  232350. [track setProperties: p];
  232351. [p release];
  232352. }
  232353. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) lengthInSamples
  232354. {
  232355. AudioTrackProducer* s = [self init: (lengthInSamples + 587) / 588];
  232356. if (s != nil)
  232357. s->source = source_;
  232358. return s;
  232359. }
  232360. - (void) dealloc
  232361. {
  232362. if (source != 0)
  232363. {
  232364. source->releaseResources();
  232365. delete source;
  232366. }
  232367. [super dealloc];
  232368. }
  232369. - (void) cleanupTrackAfterBurn: (DRTrack*) track
  232370. {
  232371. }
  232372. - (BOOL) cleanupTrackAfterVerification: (DRTrack*) track
  232373. {
  232374. return true;
  232375. }
  232376. - (uint64_t) estimateLengthOfTrack: (DRTrack*) track
  232377. {
  232378. return lengthInFrames;
  232379. }
  232380. - (BOOL) prepareTrack: (DRTrack*) track forBurn: (DRBurn*) burn
  232381. toMedia: (NSDictionary*) mediaInfo
  232382. {
  232383. if (source != 0)
  232384. source->prepareToPlay (44100 / 75, 44100);
  232385. readPosition = 0;
  232386. return true;
  232387. }
  232388. - (BOOL) prepareTrackForVerification: (DRTrack*) track
  232389. {
  232390. if (source != 0)
  232391. source->prepareToPlay (44100 / 75, 44100);
  232392. return true;
  232393. }
  232394. - (uint32_t) produceDataForTrack: (DRTrack*) track intoBuffer: (char*) buffer
  232395. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  232396. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  232397. {
  232398. if (source != 0)
  232399. {
  232400. const int numSamples = JUCE_NAMESPACE::jmin ((int) bufferLength / 4, (lengthInFrames * (44100 / 75)) - readPosition);
  232401. if (numSamples > 0)
  232402. {
  232403. JUCE_NAMESPACE::AudioSampleBuffer tempBuffer (2, numSamples);
  232404. JUCE_NAMESPACE::AudioSourceChannelInfo info;
  232405. info.buffer = &tempBuffer;
  232406. info.startSample = 0;
  232407. info.numSamples = numSamples;
  232408. source->getNextAudioBlock (info);
  232409. JUCE_NAMESPACE::AudioDataConverters::convertFloatToInt16LE (tempBuffer.getSampleData (0),
  232410. buffer, numSamples, 4);
  232411. JUCE_NAMESPACE::AudioDataConverters::convertFloatToInt16LE (tempBuffer.getSampleData (1),
  232412. buffer + 2, numSamples, 4);
  232413. readPosition += numSamples;
  232414. }
  232415. return numSamples * 4;
  232416. }
  232417. return 0;
  232418. }
  232419. - (uint32_t) producePreGapForTrack: (DRTrack*) track
  232420. intoBuffer: (char*) buffer length: (uint32_t) bufferLength
  232421. atAddress: (uint64_t) address blockSize: (uint32_t) blockSize
  232422. ioFlags: (uint32_t*) flags
  232423. {
  232424. zeromem (buffer, bufferLength);
  232425. return bufferLength;
  232426. }
  232427. - (BOOL) verifyDataForTrack: (DRTrack*) track inBuffer: (const char*) buffer
  232428. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  232429. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  232430. {
  232431. return true;
  232432. }
  232433. @end
  232434. BEGIN_JUCE_NAMESPACE
  232435. class AudioCDBurner::Pimpl : public Timer
  232436. {
  232437. public:
  232438. Pimpl (AudioCDBurner& owner_, const int deviceIndex)
  232439. : device (0), owner (owner_)
  232440. {
  232441. DRDevice* dev = [[DRDevice devices] objectAtIndex: deviceIndex];
  232442. if (dev != 0)
  232443. {
  232444. device = [[OpenDiskDevice alloc] initWithDRDevice: dev];
  232445. lastState = getDiskState();
  232446. startTimer (1000);
  232447. }
  232448. }
  232449. ~Pimpl()
  232450. {
  232451. stopTimer();
  232452. [device release];
  232453. }
  232454. void timerCallback()
  232455. {
  232456. const DiskState state = getDiskState();
  232457. if (state != lastState)
  232458. {
  232459. lastState = state;
  232460. owner.sendChangeMessage (&owner);
  232461. }
  232462. }
  232463. DiskState getDiskState() const
  232464. {
  232465. if ([device->device isValid])
  232466. {
  232467. NSDictionary* status = [device->device status];
  232468. NSString* state = [status objectForKey: DRDeviceMediaStateKey];
  232469. if ([state isEqualTo: DRDeviceMediaStateNone])
  232470. {
  232471. if ([[status objectForKey: DRDeviceIsTrayOpenKey] boolValue])
  232472. return trayOpen;
  232473. return noDisc;
  232474. }
  232475. if ([state isEqualTo: DRDeviceMediaStateMediaPresent])
  232476. {
  232477. if ([[[status objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceMediaBlocksFreeKey] intValue] > 0)
  232478. return writableDiskPresent;
  232479. else
  232480. return readOnlyDiskPresent;
  232481. }
  232482. }
  232483. return unknown;
  232484. }
  232485. bool openTray() { return [device->device isValid] && [device->device ejectMedia]; }
  232486. const Array<int> getAvailableWriteSpeeds() const
  232487. {
  232488. Array<int> results;
  232489. if ([device->device isValid])
  232490. {
  232491. NSArray* speeds = [[[device->device status] objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceBurnSpeedsKey];
  232492. for (unsigned int i = 0; i < [speeds count]; ++i)
  232493. {
  232494. const int kbPerSec = [[speeds objectAtIndex: i] intValue];
  232495. results.add (kbPerSec / kilobytesPerSecond1x);
  232496. }
  232497. }
  232498. return results;
  232499. }
  232500. bool setBufferUnderrunProtection (const bool shouldBeEnabled)
  232501. {
  232502. if ([device->device isValid])
  232503. {
  232504. device->underrunProtection = shouldBeEnabled;
  232505. return shouldBeEnabled && [[[device->device status] objectForKey: DRDeviceCanUnderrunProtectCDKey] boolValue];
  232506. }
  232507. return false;
  232508. }
  232509. int getNumAvailableAudioBlocks() const
  232510. {
  232511. return [[[[device->device status] objectForKey: DRDeviceMediaInfoKey]
  232512. objectForKey: DRDeviceMediaBlocksFreeKey] intValue];
  232513. }
  232514. OpenDiskDevice* device;
  232515. private:
  232516. DiskState lastState;
  232517. AudioCDBurner& owner;
  232518. };
  232519. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  232520. {
  232521. pimpl = new Pimpl (*this, deviceIndex);
  232522. }
  232523. AudioCDBurner::~AudioCDBurner()
  232524. {
  232525. }
  232526. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  232527. {
  232528. ScopedPointer <AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  232529. if (b->pimpl->device == 0)
  232530. b = 0;
  232531. return b.release();
  232532. }
  232533. static NSArray* findDiskBurnerDevices()
  232534. {
  232535. NSMutableArray* results = [NSMutableArray array];
  232536. NSArray* devs = [DRDevice devices];
  232537. if (devs != 0)
  232538. {
  232539. int num = [devs count];
  232540. int i;
  232541. for (i = 0; i < num; ++i)
  232542. {
  232543. NSDictionary* dic = [[devs objectAtIndex: i] info];
  232544. NSString* name = [dic valueForKey: DRDeviceProductNameKey];
  232545. if (name != nil)
  232546. [results addObject: name];
  232547. }
  232548. }
  232549. return results;
  232550. }
  232551. const StringArray AudioCDBurner::findAvailableDevices()
  232552. {
  232553. NSArray* names = findDiskBurnerDevices();
  232554. StringArray s;
  232555. for (unsigned int i = 0; i < [names count]; ++i)
  232556. s.add (String::fromUTF8 ([[names objectAtIndex: i] UTF8String]));
  232557. return s;
  232558. }
  232559. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  232560. {
  232561. return pimpl->getDiskState();
  232562. }
  232563. bool AudioCDBurner::isDiskPresent() const
  232564. {
  232565. return getDiskState() == writableDiskPresent;
  232566. }
  232567. bool AudioCDBurner::openTray()
  232568. {
  232569. return pimpl->openTray();
  232570. }
  232571. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  232572. {
  232573. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  232574. DiskState oldState = getDiskState();
  232575. DiskState newState = oldState;
  232576. while (newState == oldState && Time::currentTimeMillis() < timeout)
  232577. {
  232578. newState = getDiskState();
  232579. Thread::sleep (100);
  232580. }
  232581. return newState;
  232582. }
  232583. const Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  232584. {
  232585. return pimpl->getAvailableWriteSpeeds();
  232586. }
  232587. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  232588. {
  232589. return pimpl->setBufferUnderrunProtection (shouldBeEnabled);
  232590. }
  232591. int AudioCDBurner::getNumAvailableAudioBlocks() const
  232592. {
  232593. return pimpl->getNumAvailableAudioBlocks();
  232594. }
  232595. bool AudioCDBurner::addAudioTrack (AudioSource* source, int numSamps)
  232596. {
  232597. if ([pimpl->device->device isValid])
  232598. {
  232599. [pimpl->device addSourceTrack: source numSamples: numSamps];
  232600. return true;
  232601. }
  232602. return false;
  232603. }
  232604. const String AudioCDBurner::burn (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener* listener,
  232605. bool ejectDiscAfterwards,
  232606. bool performFakeBurnForTesting,
  232607. int writeSpeed)
  232608. {
  232609. String error ("Couldn't open or write to the CD device");
  232610. if ([pimpl->device->device isValid])
  232611. {
  232612. error = String::empty;
  232613. [pimpl->device burn: listener
  232614. errorString: &error
  232615. ejectAfterwards: ejectDiscAfterwards
  232616. isFake: performFakeBurnForTesting
  232617. speed: writeSpeed];
  232618. }
  232619. return error;
  232620. }
  232621. #endif
  232622. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  232623. void AudioCDReader::ejectDisk()
  232624. {
  232625. const ScopedAutoReleasePool p;
  232626. [[NSWorkspace sharedWorkspace] unmountAndEjectDeviceAtPath: juceStringToNS (volumeDir.getFullPathName())];
  232627. }
  232628. #endif
  232629. /*** End of inlined file: juce_mac_AudioCDBurner.mm ***/
  232630. /*** Start of inlined file: juce_mac_AudioCDReader.mm ***/
  232631. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232632. // compiled on its own).
  232633. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  232634. static void juce_findCDs (Array<File>& cds)
  232635. {
  232636. File volumes ("/Volumes");
  232637. volumes.findChildFiles (cds, File::findDirectories, false);
  232638. for (int i = cds.size(); --i >= 0;)
  232639. if (! cds.getReference(i).getChildFile (".TOC.plist").exists())
  232640. cds.remove (i);
  232641. }
  232642. const StringArray AudioCDReader::getAvailableCDNames()
  232643. {
  232644. Array<File> cds;
  232645. juce_findCDs (cds);
  232646. StringArray names;
  232647. for (int i = 0; i < cds.size(); ++i)
  232648. names.add (cds.getReference(i).getFileName());
  232649. return names;
  232650. }
  232651. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  232652. {
  232653. Array<File> cds;
  232654. juce_findCDs (cds);
  232655. if (cds[index].exists())
  232656. return new AudioCDReader (cds[index]);
  232657. return 0;
  232658. }
  232659. AudioCDReader::AudioCDReader (const File& volume)
  232660. : AudioFormatReader (0, "CD Audio"),
  232661. volumeDir (volume),
  232662. currentReaderTrack (-1),
  232663. reader (0)
  232664. {
  232665. sampleRate = 44100.0;
  232666. bitsPerSample = 16;
  232667. numChannels = 2;
  232668. usesFloatingPointData = false;
  232669. refreshTrackLengths();
  232670. }
  232671. AudioCDReader::~AudioCDReader()
  232672. {
  232673. }
  232674. static int juce_getCDTrackNumber (const File& file)
  232675. {
  232676. return file.getFileName()
  232677. .initialSectionContainingOnly ("0123456789")
  232678. .getIntValue();
  232679. }
  232680. int AudioCDReader::compareElements (const File& first, const File& second)
  232681. {
  232682. const int firstTrack = juce_getCDTrackNumber (first);
  232683. const int secondTrack = juce_getCDTrackNumber (second);
  232684. jassert (firstTrack > 0 && secondTrack > 0);
  232685. return firstTrack - secondTrack;
  232686. }
  232687. void AudioCDReader::refreshTrackLengths()
  232688. {
  232689. tracks.clear();
  232690. trackStartSamples.clear();
  232691. volumeDir.findChildFiles (tracks, File::findFiles | File::ignoreHiddenFiles, false, "*.aiff");
  232692. tracks.sort (*this);
  232693. AiffAudioFormat format;
  232694. int sample = 0;
  232695. for (int i = 0; i < tracks.size(); ++i)
  232696. {
  232697. trackStartSamples.add (sample);
  232698. FileInputStream* const in = tracks.getReference(i).createInputStream();
  232699. if (in != 0)
  232700. {
  232701. ScopedPointer <AudioFormatReader> r (format.createReaderFor (in, true));
  232702. if (r != 0)
  232703. sample += (int) r->lengthInSamples;
  232704. }
  232705. }
  232706. trackStartSamples.add (sample);
  232707. lengthInSamples = sample;
  232708. }
  232709. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  232710. int64 startSampleInFile, int numSamples)
  232711. {
  232712. while (numSamples > 0)
  232713. {
  232714. int track = -1;
  232715. for (int i = 0; i < trackStartSamples.size() - 1; ++i)
  232716. {
  232717. if (startSampleInFile < trackStartSamples.getUnchecked (i + 1))
  232718. {
  232719. track = i;
  232720. break;
  232721. }
  232722. }
  232723. if (track < 0)
  232724. return false;
  232725. if (track != currentReaderTrack)
  232726. {
  232727. reader = 0;
  232728. FileInputStream* const in = tracks [track].createInputStream();
  232729. if (in != 0)
  232730. {
  232731. BufferedInputStream* const bin = new BufferedInputStream (in, 65536, true);
  232732. AiffAudioFormat format;
  232733. reader = format.createReaderFor (bin, true);
  232734. if (reader == 0)
  232735. currentReaderTrack = -1;
  232736. else
  232737. currentReaderTrack = track;
  232738. }
  232739. }
  232740. if (reader == 0)
  232741. return false;
  232742. const int startPos = (int) (startSampleInFile - trackStartSamples.getUnchecked (track));
  232743. const int numAvailable = (int) jmin ((int64) numSamples, reader->lengthInSamples - startPos);
  232744. reader->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer, startPos, numAvailable);
  232745. numSamples -= numAvailable;
  232746. startSampleInFile += numAvailable;
  232747. }
  232748. return true;
  232749. }
  232750. bool AudioCDReader::isCDStillPresent() const
  232751. {
  232752. return volumeDir.exists();
  232753. }
  232754. int AudioCDReader::getNumTracks() const
  232755. {
  232756. return tracks.size();
  232757. }
  232758. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  232759. {
  232760. return trackStartSamples [trackNum];
  232761. }
  232762. bool AudioCDReader::isTrackAudio (int trackNum) const
  232763. {
  232764. return tracks [trackNum] != File::nonexistent;
  232765. }
  232766. void AudioCDReader::enableIndexScanning (bool b)
  232767. {
  232768. // any way to do this on a Mac??
  232769. }
  232770. int AudioCDReader::getLastIndex() const
  232771. {
  232772. return 0;
  232773. }
  232774. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  232775. {
  232776. return Array <int>();
  232777. }
  232778. int AudioCDReader::getCDDBId()
  232779. {
  232780. return 0; //xxx
  232781. }
  232782. #endif
  232783. /*** End of inlined file: juce_mac_AudioCDReader.mm ***/
  232784. /*** Start of inlined file: juce_mac_MessageManager.mm ***/
  232785. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232786. // compiled on its own).
  232787. #if JUCE_INCLUDED_FILE
  232788. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  232789. for example having more than one juce plugin loaded into a host, then when a
  232790. method is called, the actual code that runs might actually be in a different module
  232791. than the one you expect... So any calls to library functions or statics that are
  232792. made inside obj-c methods will probably end up getting executed in a different DLL's
  232793. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  232794. To work around this insanity, I'm only allowing obj-c methods to make calls to
  232795. virtual methods of an object that's known to live inside the right module's space.
  232796. */
  232797. class AppDelegateRedirector
  232798. {
  232799. public:
  232800. AppDelegateRedirector()
  232801. {
  232802. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_4
  232803. runLoop = CFRunLoopGetMain();
  232804. #else
  232805. runLoop = CFRunLoopGetCurrent();
  232806. #endif
  232807. CFRunLoopSourceContext sourceContext;
  232808. zerostruct (sourceContext);
  232809. sourceContext.info = this;
  232810. sourceContext.perform = runLoopSourceCallback;
  232811. runLoopSource = CFRunLoopSourceCreate (kCFAllocatorDefault, 1, &sourceContext);
  232812. CFRunLoopAddSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  232813. }
  232814. virtual ~AppDelegateRedirector()
  232815. {
  232816. CFRunLoopRemoveSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  232817. CFRunLoopSourceInvalidate (runLoopSource);
  232818. CFRelease (runLoopSource);
  232819. while (messages.size() > 0)
  232820. delete static_cast <Message*> (messages.remove(0));
  232821. }
  232822. virtual NSApplicationTerminateReply shouldTerminate()
  232823. {
  232824. if (JUCEApplication::getInstance() != 0)
  232825. {
  232826. JUCEApplication::getInstance()->systemRequestedQuit();
  232827. return NSTerminateCancel;
  232828. }
  232829. return NSTerminateNow;
  232830. }
  232831. virtual BOOL openFile (const NSString* filename)
  232832. {
  232833. if (JUCEApplication::getInstance() != 0)
  232834. {
  232835. JUCEApplication::getInstance()->anotherInstanceStarted (nsStringToJuce (filename));
  232836. return YES;
  232837. }
  232838. return NO;
  232839. }
  232840. virtual void openFiles (NSArray* filenames)
  232841. {
  232842. StringArray files;
  232843. for (unsigned int i = 0; i < [filenames count]; ++i)
  232844. {
  232845. String filename (nsStringToJuce ((NSString*) [filenames objectAtIndex: i]));
  232846. if (filename.containsChar (' '))
  232847. filename = filename.quoted('"');
  232848. files.add (filename);
  232849. }
  232850. if (files.size() > 0 && JUCEApplication::getInstance() != 0)
  232851. {
  232852. JUCEApplication::getInstance()->anotherInstanceStarted (files.joinIntoString (" "));
  232853. }
  232854. }
  232855. virtual void focusChanged()
  232856. {
  232857. juce_HandleProcessFocusChange();
  232858. }
  232859. struct CallbackMessagePayload
  232860. {
  232861. MessageCallbackFunction* function;
  232862. void* parameter;
  232863. void* volatile result;
  232864. bool volatile hasBeenExecuted;
  232865. };
  232866. virtual void performCallback (CallbackMessagePayload* pl)
  232867. {
  232868. pl->result = (*pl->function) (pl->parameter);
  232869. pl->hasBeenExecuted = true;
  232870. }
  232871. virtual void deleteSelf()
  232872. {
  232873. delete this;
  232874. }
  232875. void postMessage (void* m)
  232876. {
  232877. messages.add (m);
  232878. CFRunLoopSourceSignal (runLoopSource);
  232879. CFRunLoopWakeUp (runLoop);
  232880. }
  232881. private:
  232882. CFRunLoopRef runLoop;
  232883. CFRunLoopSourceRef runLoopSource;
  232884. Array <void*, CriticalSection> messages;
  232885. void runLoopCallback()
  232886. {
  232887. int numDispatched = 0;
  232888. do
  232889. {
  232890. void* const nextMessage = messages.remove (0);
  232891. if (nextMessage == 0)
  232892. return;
  232893. const ScopedAutoReleasePool pool;
  232894. MessageManager::getInstance()->deliverMessage (nextMessage);
  232895. } while (++numDispatched <= 4);
  232896. CFRunLoopSourceSignal (runLoopSource);
  232897. CFRunLoopWakeUp (runLoop);
  232898. }
  232899. static void runLoopSourceCallback (void* info)
  232900. {
  232901. static_cast <AppDelegateRedirector*> (info)->runLoopCallback();
  232902. }
  232903. };
  232904. END_JUCE_NAMESPACE
  232905. using namespace JUCE_NAMESPACE;
  232906. #define JuceAppDelegate MakeObjCClassName(JuceAppDelegate)
  232907. @interface JuceAppDelegate : NSObject
  232908. {
  232909. @private
  232910. id oldDelegate;
  232911. @public
  232912. AppDelegateRedirector* redirector;
  232913. }
  232914. - (JuceAppDelegate*) init;
  232915. - (void) dealloc;
  232916. - (BOOL) application: (NSApplication*) theApplication openFile: (NSString*) filename;
  232917. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames;
  232918. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app;
  232919. - (void) applicationDidBecomeActive: (NSNotification*) aNotification;
  232920. - (void) applicationDidResignActive: (NSNotification*) aNotification;
  232921. - (void) applicationWillUnhide: (NSNotification*) aNotification;
  232922. - (void) performCallback: (id) info;
  232923. - (void) dummyMethod;
  232924. @end
  232925. @implementation JuceAppDelegate
  232926. - (JuceAppDelegate*) init
  232927. {
  232928. [super init];
  232929. redirector = new AppDelegateRedirector();
  232930. NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
  232931. if (JUCEApplication::getInstance() != 0)
  232932. {
  232933. oldDelegate = [NSApp delegate];
  232934. [NSApp setDelegate: self];
  232935. }
  232936. else
  232937. {
  232938. oldDelegate = 0;
  232939. [center addObserver: self selector: @selector (applicationDidResignActive:)
  232940. name: NSApplicationDidResignActiveNotification object: NSApp];
  232941. [center addObserver: self selector: @selector (applicationDidBecomeActive:)
  232942. name: NSApplicationDidBecomeActiveNotification object: NSApp];
  232943. [center addObserver: self selector: @selector (applicationWillUnhide:)
  232944. name: NSApplicationWillUnhideNotification object: NSApp];
  232945. }
  232946. return self;
  232947. }
  232948. - (void) dealloc
  232949. {
  232950. if (oldDelegate != 0)
  232951. [NSApp setDelegate: oldDelegate];
  232952. redirector->deleteSelf();
  232953. [super dealloc];
  232954. }
  232955. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app
  232956. {
  232957. (void) app;
  232958. return redirector->shouldTerminate();
  232959. }
  232960. - (BOOL) application: (NSApplication*) app openFile: (NSString*) filename
  232961. {
  232962. (void) app;
  232963. return redirector->openFile (filename);
  232964. }
  232965. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames
  232966. {
  232967. (void) sender;
  232968. return redirector->openFiles (filenames);
  232969. }
  232970. - (void) applicationDidBecomeActive: (NSNotification*) notification
  232971. {
  232972. (void) notification;
  232973. redirector->focusChanged();
  232974. }
  232975. - (void) applicationDidResignActive: (NSNotification*) notification
  232976. {
  232977. (void) notification;
  232978. redirector->focusChanged();
  232979. }
  232980. - (void) applicationWillUnhide: (NSNotification*) notification
  232981. {
  232982. (void) notification;
  232983. redirector->focusChanged();
  232984. }
  232985. - (void) performCallback: (id) info
  232986. {
  232987. if ([info isKindOfClass: [NSData class]])
  232988. {
  232989. AppDelegateRedirector::CallbackMessagePayload* pl
  232990. = (AppDelegateRedirector::CallbackMessagePayload*) [((NSData*) info) bytes];
  232991. if (pl != 0)
  232992. redirector->performCallback (pl);
  232993. }
  232994. else
  232995. {
  232996. jassertfalse; // should never get here!
  232997. }
  232998. }
  232999. - (void) dummyMethod {} // (used as a way of running a dummy thread)
  233000. @end
  233001. BEGIN_JUCE_NAMESPACE
  233002. static JuceAppDelegate* juceAppDelegate = 0;
  233003. void MessageManager::runDispatchLoop()
  233004. {
  233005. if (! quitMessagePosted) // check that the quit message wasn't already posted..
  233006. {
  233007. const ScopedAutoReleasePool pool;
  233008. // must only be called by the message thread!
  233009. jassert (isThisTheMessageThread());
  233010. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  233011. @try
  233012. {
  233013. [NSApp run];
  233014. }
  233015. @catch (NSException* e)
  233016. {
  233017. // An AppKit exception will kill the app, but at least this provides a chance to log it.,
  233018. std::runtime_error ex (std::string ("NSException: ") + [[e name] UTF8String] + ", Reason:" + [[e reason] UTF8String]);
  233019. JUCEApplication::sendUnhandledException (&ex, __FILE__, __LINE__);
  233020. }
  233021. @finally
  233022. {
  233023. }
  233024. #else
  233025. [NSApp run];
  233026. #endif
  233027. }
  233028. }
  233029. void MessageManager::stopDispatchLoop()
  233030. {
  233031. quitMessagePosted = true;
  233032. [NSApp stop: nil];
  233033. [NSApp activateIgnoringOtherApps: YES]; // (if the app is inactive, it sits there and ignores the quit request until the next time it gets activated)
  233034. [NSEvent startPeriodicEventsAfterDelay: 0 withPeriod: 0.1];
  233035. }
  233036. static bool isEventBlockedByModalComps (NSEvent* e)
  233037. {
  233038. if (Component::getNumCurrentlyModalComponents() == 0)
  233039. return false;
  233040. NSWindow* const w = [e window];
  233041. if (w == 0 || [w worksWhenModal])
  233042. return false;
  233043. bool isKey = false, isInputAttempt = false;
  233044. switch ([e type])
  233045. {
  233046. case NSKeyDown:
  233047. case NSKeyUp:
  233048. isKey = isInputAttempt = true;
  233049. break;
  233050. case NSLeftMouseDown:
  233051. case NSRightMouseDown:
  233052. case NSOtherMouseDown:
  233053. isInputAttempt = true;
  233054. break;
  233055. case NSLeftMouseDragged:
  233056. case NSRightMouseDragged:
  233057. case NSLeftMouseUp:
  233058. case NSRightMouseUp:
  233059. case NSOtherMouseUp:
  233060. case NSOtherMouseDragged:
  233061. if (Desktop::getInstance().getDraggingMouseSource(0) != 0)
  233062. return false;
  233063. break;
  233064. case NSMouseMoved:
  233065. case NSMouseEntered:
  233066. case NSMouseExited:
  233067. case NSCursorUpdate:
  233068. case NSScrollWheel:
  233069. case NSTabletPoint:
  233070. case NSTabletProximity:
  233071. break;
  233072. default:
  233073. return false;
  233074. }
  233075. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  233076. {
  233077. ComponentPeer* const peer = ComponentPeer::getPeer (i);
  233078. NSView* const compView = (NSView*) peer->getNativeHandle();
  233079. if ([compView window] == w)
  233080. {
  233081. if (isKey)
  233082. {
  233083. if (compView == [w firstResponder])
  233084. return false;
  233085. }
  233086. else
  233087. {
  233088. if (NSPointInRect ([compView convertPoint: [e locationInWindow] fromView: nil],
  233089. [compView bounds]))
  233090. return false;
  233091. }
  233092. }
  233093. }
  233094. if (isInputAttempt)
  233095. {
  233096. if (! [NSApp isActive])
  233097. [NSApp activateIgnoringOtherApps: YES];
  233098. Component* const modal = Component::getCurrentlyModalComponent (0);
  233099. if (modal != 0)
  233100. modal->inputAttemptWhenModal();
  233101. }
  233102. return true;
  233103. }
  233104. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  233105. {
  233106. const ScopedAutoReleasePool pool;
  233107. jassert (isThisTheMessageThread()); // must only be called by the message thread
  233108. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  233109. while (! quitMessagePosted)
  233110. {
  233111. const ScopedAutoReleasePool pool2;
  233112. CFRunLoopRunInMode (kCFRunLoopDefaultMode, 0.001, true);
  233113. NSEvent* e = [NSApp nextEventMatchingMask: NSAnyEventMask
  233114. untilDate: [NSDate dateWithTimeIntervalSinceNow: 0.001]
  233115. inMode: NSDefaultRunLoopMode
  233116. dequeue: YES];
  233117. if (e != 0 && ! isEventBlockedByModalComps (e))
  233118. [NSApp sendEvent: e];
  233119. if (Time::getMillisecondCounter() >= endTime)
  233120. break;
  233121. }
  233122. return ! quitMessagePosted;
  233123. }
  233124. void MessageManager::doPlatformSpecificInitialisation()
  233125. {
  233126. if (juceAppDelegate == 0)
  233127. juceAppDelegate = [[JuceAppDelegate alloc] init];
  233128. // This launches a dummy thread, which forces Cocoa to initialise NSThreads
  233129. // correctly (needed prior to 10.5)
  233130. if (! [NSThread isMultiThreaded])
  233131. [NSThread detachNewThreadSelector: @selector (dummyMethod)
  233132. toTarget: juceAppDelegate
  233133. withObject: nil];
  233134. initialiseMainMenu();
  233135. }
  233136. void MessageManager::doPlatformSpecificShutdown()
  233137. {
  233138. if (juceAppDelegate != 0)
  233139. {
  233140. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceAppDelegate];
  233141. [[NSNotificationCenter defaultCenter] removeObserver: juceAppDelegate];
  233142. [juceAppDelegate release];
  233143. juceAppDelegate = 0;
  233144. }
  233145. }
  233146. bool juce_postMessageToSystemQueue (void* message)
  233147. {
  233148. juceAppDelegate->redirector->postMessage (message);
  233149. return true;
  233150. }
  233151. void MessageManager::broadcastMessage (const String& value) throw()
  233152. {
  233153. }
  233154. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  233155. void* data)
  233156. {
  233157. if (isThisTheMessageThread())
  233158. {
  233159. return (*callback) (data);
  233160. }
  233161. else
  233162. {
  233163. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  233164. // deadlock because the message manager is blocked from running, so can never
  233165. // call your function..
  233166. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  233167. const ScopedAutoReleasePool pool;
  233168. AppDelegateRedirector::CallbackMessagePayload cmp;
  233169. cmp.function = callback;
  233170. cmp.parameter = data;
  233171. cmp.result = 0;
  233172. cmp.hasBeenExecuted = false;
  233173. [juceAppDelegate performSelectorOnMainThread: @selector (performCallback:)
  233174. withObject: [NSData dataWithBytesNoCopy: &cmp
  233175. length: sizeof (cmp)
  233176. freeWhenDone: NO]
  233177. waitUntilDone: YES];
  233178. return cmp.result;
  233179. }
  233180. }
  233181. #endif
  233182. /*** End of inlined file: juce_mac_MessageManager.mm ***/
  233183. /*** Start of inlined file: juce_mac_WebBrowserComponent.mm ***/
  233184. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233185. // compiled on its own).
  233186. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  233187. #if JUCE_MAC
  233188. END_JUCE_NAMESPACE
  233189. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  233190. @interface DownloadClickDetector : NSObject
  233191. {
  233192. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  233193. }
  233194. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  233195. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  233196. request: (NSURLRequest*) request
  233197. frame: (WebFrame*) frame
  233198. decisionListener: (id<WebPolicyDecisionListener>) listener;
  233199. @end
  233200. @implementation DownloadClickDetector
  233201. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  233202. {
  233203. [super init];
  233204. ownerComponent = ownerComponent_;
  233205. return self;
  233206. }
  233207. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  233208. request: (NSURLRequest*) request
  233209. frame: (WebFrame*) frame
  233210. decisionListener: (id <WebPolicyDecisionListener>) listener
  233211. {
  233212. (void) sender;
  233213. (void) request;
  233214. (void) frame;
  233215. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  233216. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  233217. [listener use];
  233218. else
  233219. [listener ignore];
  233220. }
  233221. @end
  233222. BEGIN_JUCE_NAMESPACE
  233223. class WebBrowserComponentInternal : public NSViewComponent
  233224. {
  233225. public:
  233226. WebBrowserComponentInternal (WebBrowserComponent* owner)
  233227. {
  233228. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  233229. frameName: @""
  233230. groupName: @""];
  233231. setView (webView);
  233232. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  233233. [webView setPolicyDelegate: clickListener];
  233234. }
  233235. ~WebBrowserComponentInternal()
  233236. {
  233237. [webView setPolicyDelegate: nil];
  233238. [clickListener release];
  233239. setView (0);
  233240. }
  233241. void goToURL (const String& url,
  233242. const StringArray* headers,
  233243. const MemoryBlock* postData)
  233244. {
  233245. NSMutableURLRequest* r
  233246. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  233247. cachePolicy: NSURLRequestUseProtocolCachePolicy
  233248. timeoutInterval: 30.0];
  233249. if (postData != 0 && postData->getSize() > 0)
  233250. {
  233251. [r setHTTPMethod: @"POST"];
  233252. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  233253. length: postData->getSize()]];
  233254. }
  233255. if (headers != 0)
  233256. {
  233257. for (int i = 0; i < headers->size(); ++i)
  233258. {
  233259. const String headerName ((*headers)[i].upToFirstOccurrenceOf (":", false, false).trim());
  233260. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (":", false, false).trim());
  233261. [r setValue: juceStringToNS (headerValue)
  233262. forHTTPHeaderField: juceStringToNS (headerName)];
  233263. }
  233264. }
  233265. stop();
  233266. [[webView mainFrame] loadRequest: r];
  233267. }
  233268. void goBack()
  233269. {
  233270. [webView goBack];
  233271. }
  233272. void goForward()
  233273. {
  233274. [webView goForward];
  233275. }
  233276. void stop()
  233277. {
  233278. [webView stopLoading: nil];
  233279. }
  233280. void refresh()
  233281. {
  233282. [webView reload: nil];
  233283. }
  233284. private:
  233285. WebView* webView;
  233286. DownloadClickDetector* clickListener;
  233287. };
  233288. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  233289. : browser (0),
  233290. blankPageShown (false),
  233291. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  233292. {
  233293. setOpaque (true);
  233294. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  233295. }
  233296. WebBrowserComponent::~WebBrowserComponent()
  233297. {
  233298. deleteAndZero (browser);
  233299. }
  233300. void WebBrowserComponent::goToURL (const String& url,
  233301. const StringArray* headers,
  233302. const MemoryBlock* postData)
  233303. {
  233304. lastURL = url;
  233305. lastHeaders.clear();
  233306. if (headers != 0)
  233307. lastHeaders = *headers;
  233308. lastPostData.setSize (0);
  233309. if (postData != 0)
  233310. lastPostData = *postData;
  233311. blankPageShown = false;
  233312. browser->goToURL (url, headers, postData);
  233313. }
  233314. void WebBrowserComponent::stop()
  233315. {
  233316. browser->stop();
  233317. }
  233318. void WebBrowserComponent::goBack()
  233319. {
  233320. lastURL = String::empty;
  233321. blankPageShown = false;
  233322. browser->goBack();
  233323. }
  233324. void WebBrowserComponent::goForward()
  233325. {
  233326. lastURL = String::empty;
  233327. browser->goForward();
  233328. }
  233329. void WebBrowserComponent::refresh()
  233330. {
  233331. browser->refresh();
  233332. }
  233333. void WebBrowserComponent::paint (Graphics&)
  233334. {
  233335. }
  233336. void WebBrowserComponent::checkWindowAssociation()
  233337. {
  233338. if (isShowing())
  233339. {
  233340. if (blankPageShown)
  233341. goBack();
  233342. }
  233343. else
  233344. {
  233345. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  233346. {
  233347. // when the component becomes invisible, some stuff like flash
  233348. // carries on playing audio, so we need to force it onto a blank
  233349. // page to avoid this, (and send it back when it's made visible again).
  233350. blankPageShown = true;
  233351. browser->goToURL ("about:blank", 0, 0);
  233352. }
  233353. }
  233354. }
  233355. void WebBrowserComponent::reloadLastURL()
  233356. {
  233357. if (lastURL.isNotEmpty())
  233358. {
  233359. goToURL (lastURL, &lastHeaders, &lastPostData);
  233360. lastURL = String::empty;
  233361. }
  233362. }
  233363. void WebBrowserComponent::parentHierarchyChanged()
  233364. {
  233365. checkWindowAssociation();
  233366. }
  233367. void WebBrowserComponent::resized()
  233368. {
  233369. browser->setSize (getWidth(), getHeight());
  233370. }
  233371. void WebBrowserComponent::visibilityChanged()
  233372. {
  233373. checkWindowAssociation();
  233374. }
  233375. bool WebBrowserComponent::pageAboutToLoad (const String&)
  233376. {
  233377. return true;
  233378. }
  233379. #else
  233380. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  233381. {
  233382. }
  233383. WebBrowserComponent::~WebBrowserComponent()
  233384. {
  233385. }
  233386. void WebBrowserComponent::goToURL (const String& url,
  233387. const StringArray* headers,
  233388. const MemoryBlock* postData)
  233389. {
  233390. }
  233391. void WebBrowserComponent::stop()
  233392. {
  233393. }
  233394. void WebBrowserComponent::goBack()
  233395. {
  233396. }
  233397. void WebBrowserComponent::goForward()
  233398. {
  233399. }
  233400. void WebBrowserComponent::refresh()
  233401. {
  233402. }
  233403. void WebBrowserComponent::paint (Graphics& g)
  233404. {
  233405. }
  233406. void WebBrowserComponent::checkWindowAssociation()
  233407. {
  233408. }
  233409. void WebBrowserComponent::reloadLastURL()
  233410. {
  233411. }
  233412. void WebBrowserComponent::parentHierarchyChanged()
  233413. {
  233414. }
  233415. void WebBrowserComponent::resized()
  233416. {
  233417. }
  233418. void WebBrowserComponent::visibilityChanged()
  233419. {
  233420. }
  233421. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  233422. {
  233423. return true;
  233424. }
  233425. #endif
  233426. #endif
  233427. /*** End of inlined file: juce_mac_WebBrowserComponent.mm ***/
  233428. /*** Start of inlined file: juce_mac_CoreAudio.cpp ***/
  233429. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233430. // compiled on its own).
  233431. #if JUCE_INCLUDED_FILE
  233432. #ifndef JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  233433. #define JUCE_COREAUDIO_ERROR_LOGGING_ENABLED 1
  233434. #endif
  233435. #undef log
  233436. #if JUCE_COREAUDIO_LOGGING_ENABLED
  233437. #define log(a) Logger::writeToLog (a)
  233438. #else
  233439. #define log(a)
  233440. #endif
  233441. #undef OK
  233442. #if JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  233443. static bool logAnyErrors_CoreAudio (const OSStatus err, const int lineNum)
  233444. {
  233445. if (err == noErr)
  233446. return true;
  233447. Logger::writeToLog ("CoreAudio error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  233448. jassertfalse;
  233449. return false;
  233450. }
  233451. #define OK(a) logAnyErrors_CoreAudio (a, __LINE__)
  233452. #else
  233453. #define OK(a) (a == noErr)
  233454. #endif
  233455. class CoreAudioInternal : public Timer
  233456. {
  233457. public:
  233458. CoreAudioInternal (AudioDeviceID id)
  233459. : inputLatency (0),
  233460. outputLatency (0),
  233461. callback (0),
  233462. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  233463. audioProcID (0),
  233464. #endif
  233465. isSlaveDevice (false),
  233466. deviceID (id),
  233467. started (false),
  233468. sampleRate (0),
  233469. bufferSize (512),
  233470. numInputChans (0),
  233471. numOutputChans (0),
  233472. callbacksAllowed (true),
  233473. numInputChannelInfos (0),
  233474. numOutputChannelInfos (0)
  233475. {
  233476. jassert (deviceID != 0);
  233477. updateDetailsFromDevice();
  233478. AudioObjectPropertyAddress pa;
  233479. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  233480. pa.mScope = kAudioObjectPropertyScopeWildcard;
  233481. pa.mElement = kAudioObjectPropertyElementWildcard;
  233482. AudioObjectAddPropertyListener (deviceID, &pa, deviceListenerProc, this);
  233483. }
  233484. ~CoreAudioInternal()
  233485. {
  233486. AudioObjectPropertyAddress pa;
  233487. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  233488. pa.mScope = kAudioObjectPropertyScopeWildcard;
  233489. pa.mElement = kAudioObjectPropertyElementWildcard;
  233490. AudioObjectRemovePropertyListener (deviceID, &pa, deviceListenerProc, this);
  233491. stop (false);
  233492. }
  233493. void allocateTempBuffers()
  233494. {
  233495. const int tempBufSize = bufferSize + 4;
  233496. audioBuffer.calloc ((numInputChans + numOutputChans) * tempBufSize);
  233497. tempInputBuffers.calloc (numInputChans + 2);
  233498. tempOutputBuffers.calloc (numOutputChans + 2);
  233499. int i, count = 0;
  233500. for (i = 0; i < numInputChans; ++i)
  233501. tempInputBuffers[i] = audioBuffer + count++ * tempBufSize;
  233502. for (i = 0; i < numOutputChans; ++i)
  233503. tempOutputBuffers[i] = audioBuffer + count++ * tempBufSize;
  233504. }
  233505. // returns the number of actual available channels
  233506. void fillInChannelInfo (const bool input)
  233507. {
  233508. int chanNum = 0;
  233509. UInt32 size;
  233510. AudioObjectPropertyAddress pa;
  233511. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  233512. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  233513. pa.mElement = kAudioObjectPropertyElementMaster;
  233514. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  233515. {
  233516. HeapBlock <AudioBufferList> bufList;
  233517. bufList.calloc (size, 1);
  233518. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  233519. {
  233520. const int numStreams = bufList->mNumberBuffers;
  233521. for (int i = 0; i < numStreams; ++i)
  233522. {
  233523. const AudioBuffer& b = bufList->mBuffers[i];
  233524. for (unsigned int j = 0; j < b.mNumberChannels; ++j)
  233525. {
  233526. String name;
  233527. {
  233528. char channelName [256];
  233529. zerostruct (channelName);
  233530. UInt32 nameSize = sizeof (channelName);
  233531. UInt32 channelNum = chanNum + 1;
  233532. pa.mSelector = kAudioDevicePropertyChannelName;
  233533. if (AudioObjectGetPropertyData (deviceID, &pa, sizeof (channelNum), &channelNum, &nameSize, channelName) == noErr)
  233534. name = String::fromUTF8 (channelName, nameSize);
  233535. }
  233536. if (input)
  233537. {
  233538. if (activeInputChans[chanNum])
  233539. {
  233540. inputChannelInfo [numInputChannelInfos].streamNum = i;
  233541. inputChannelInfo [numInputChannelInfos].dataOffsetSamples = j;
  233542. inputChannelInfo [numInputChannelInfos].dataStrideSamples = b.mNumberChannels;
  233543. ++numInputChannelInfos;
  233544. }
  233545. if (name.isEmpty())
  233546. name << "Input " << (chanNum + 1);
  233547. inChanNames.add (name);
  233548. }
  233549. else
  233550. {
  233551. if (activeOutputChans[chanNum])
  233552. {
  233553. outputChannelInfo [numOutputChannelInfos].streamNum = i;
  233554. outputChannelInfo [numOutputChannelInfos].dataOffsetSamples = j;
  233555. outputChannelInfo [numOutputChannelInfos].dataStrideSamples = b.mNumberChannels;
  233556. ++numOutputChannelInfos;
  233557. }
  233558. if (name.isEmpty())
  233559. name << "Output " << (chanNum + 1);
  233560. outChanNames.add (name);
  233561. }
  233562. ++chanNum;
  233563. }
  233564. }
  233565. }
  233566. }
  233567. }
  233568. void updateDetailsFromDevice()
  233569. {
  233570. stopTimer();
  233571. if (deviceID == 0)
  233572. return;
  233573. const ScopedLock sl (callbackLock);
  233574. Float64 sr;
  233575. UInt32 size = sizeof (Float64);
  233576. AudioObjectPropertyAddress pa;
  233577. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  233578. pa.mScope = kAudioObjectPropertyScopeWildcard;
  233579. pa.mElement = kAudioObjectPropertyElementMaster;
  233580. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &sr)))
  233581. sampleRate = sr;
  233582. UInt32 framesPerBuf;
  233583. size = sizeof (framesPerBuf);
  233584. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  233585. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &framesPerBuf)))
  233586. {
  233587. bufferSize = framesPerBuf;
  233588. allocateTempBuffers();
  233589. }
  233590. bufferSizes.clear();
  233591. pa.mSelector = kAudioDevicePropertyBufferFrameSizeRange;
  233592. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  233593. {
  233594. HeapBlock <AudioValueRange> ranges;
  233595. ranges.calloc (size, 1);
  233596. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  233597. {
  233598. bufferSizes.add ((int) ranges[0].mMinimum);
  233599. for (int i = 32; i < 2048; i += 32)
  233600. {
  233601. for (int j = size / (int) sizeof (AudioValueRange); --j >= 0;)
  233602. {
  233603. if (i >= ranges[j].mMinimum && i <= ranges[j].mMaximum)
  233604. {
  233605. bufferSizes.addIfNotAlreadyThere (i);
  233606. break;
  233607. }
  233608. }
  233609. }
  233610. if (bufferSize > 0)
  233611. bufferSizes.addIfNotAlreadyThere (bufferSize);
  233612. }
  233613. }
  233614. if (bufferSizes.size() == 0 && bufferSize > 0)
  233615. bufferSizes.add (bufferSize);
  233616. sampleRates.clear();
  233617. const double possibleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  233618. String rates;
  233619. pa.mSelector = kAudioDevicePropertyAvailableNominalSampleRates;
  233620. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  233621. {
  233622. HeapBlock <AudioValueRange> ranges;
  233623. ranges.calloc (size, 1);
  233624. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  233625. {
  233626. for (int i = 0; i < numElementsInArray (possibleRates); ++i)
  233627. {
  233628. bool ok = false;
  233629. for (int j = size / (int) sizeof (AudioValueRange); --j >= 0;)
  233630. if (possibleRates[i] >= ranges[j].mMinimum - 2 && possibleRates[i] <= ranges[j].mMaximum + 2)
  233631. ok = true;
  233632. if (ok)
  233633. {
  233634. sampleRates.add (possibleRates[i]);
  233635. rates << possibleRates[i] << ' ';
  233636. }
  233637. }
  233638. }
  233639. }
  233640. if (sampleRates.size() == 0 && sampleRate > 0)
  233641. {
  233642. sampleRates.add (sampleRate);
  233643. rates << sampleRate;
  233644. }
  233645. log ("sr: " + rates);
  233646. inputLatency = 0;
  233647. outputLatency = 0;
  233648. UInt32 lat;
  233649. size = sizeof (lat);
  233650. pa.mSelector = kAudioDevicePropertyLatency;
  233651. pa.mScope = kAudioDevicePropertyScopeInput;
  233652. //if (AudioDeviceGetProperty (deviceID, 0, true, kAudioDevicePropertyLatency, &size, &lat) == noErr)
  233653. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  233654. inputLatency = (int) lat;
  233655. pa.mScope = kAudioDevicePropertyScopeOutput;
  233656. size = sizeof (lat);
  233657. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  233658. outputLatency = (int) lat;
  233659. log ("lat: " + String (inputLatency) + " " + String (outputLatency));
  233660. inChanNames.clear();
  233661. outChanNames.clear();
  233662. inputChannelInfo.calloc (numInputChans + 2);
  233663. numInputChannelInfos = 0;
  233664. outputChannelInfo.calloc (numOutputChans + 2);
  233665. numOutputChannelInfos = 0;
  233666. fillInChannelInfo (true);
  233667. fillInChannelInfo (false);
  233668. }
  233669. const StringArray getSources (bool input)
  233670. {
  233671. StringArray s;
  233672. HeapBlock <OSType> types;
  233673. const int num = getAllDataSourcesForDevice (deviceID, types);
  233674. for (int i = 0; i < num; ++i)
  233675. {
  233676. AudioValueTranslation avt;
  233677. char buffer[256];
  233678. avt.mInputData = &(types[i]);
  233679. avt.mInputDataSize = sizeof (UInt32);
  233680. avt.mOutputData = buffer;
  233681. avt.mOutputDataSize = 256;
  233682. UInt32 transSize = sizeof (avt);
  233683. AudioObjectPropertyAddress pa;
  233684. pa.mSelector = kAudioDevicePropertyDataSourceNameForID;
  233685. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  233686. pa.mElement = kAudioObjectPropertyElementMaster;
  233687. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &transSize, &avt)))
  233688. {
  233689. DBG (buffer);
  233690. s.add (buffer);
  233691. }
  233692. }
  233693. return s;
  233694. }
  233695. int getCurrentSourceIndex (bool input) const
  233696. {
  233697. OSType currentSourceID = 0;
  233698. UInt32 size = sizeof (currentSourceID);
  233699. int result = -1;
  233700. AudioObjectPropertyAddress pa;
  233701. pa.mSelector = kAudioDevicePropertyDataSource;
  233702. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  233703. pa.mElement = kAudioObjectPropertyElementMaster;
  233704. if (deviceID != 0)
  233705. {
  233706. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &currentSourceID)))
  233707. {
  233708. HeapBlock <OSType> types;
  233709. const int num = getAllDataSourcesForDevice (deviceID, types);
  233710. for (int i = 0; i < num; ++i)
  233711. {
  233712. if (types[num] == currentSourceID)
  233713. {
  233714. result = i;
  233715. break;
  233716. }
  233717. }
  233718. }
  233719. }
  233720. return result;
  233721. }
  233722. void setCurrentSourceIndex (int index, bool input)
  233723. {
  233724. if (deviceID != 0)
  233725. {
  233726. HeapBlock <OSType> types;
  233727. const int num = getAllDataSourcesForDevice (deviceID, types);
  233728. if (((unsigned int) index) < (unsigned int) num)
  233729. {
  233730. AudioObjectPropertyAddress pa;
  233731. pa.mSelector = kAudioDevicePropertyDataSource;
  233732. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  233733. pa.mElement = kAudioObjectPropertyElementMaster;
  233734. OSType typeId = types[index];
  233735. OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (typeId), &typeId));
  233736. }
  233737. }
  233738. }
  233739. const String reopen (const BigInteger& inputChannels,
  233740. const BigInteger& outputChannels,
  233741. double newSampleRate,
  233742. int bufferSizeSamples)
  233743. {
  233744. String error;
  233745. log ("CoreAudio reopen");
  233746. callbacksAllowed = false;
  233747. stopTimer();
  233748. stop (false);
  233749. activeInputChans = inputChannels;
  233750. activeInputChans.setRange (inChanNames.size(),
  233751. activeInputChans.getHighestBit() + 1 - inChanNames.size(),
  233752. false);
  233753. activeOutputChans = outputChannels;
  233754. activeOutputChans.setRange (outChanNames.size(),
  233755. activeOutputChans.getHighestBit() + 1 - outChanNames.size(),
  233756. false);
  233757. numInputChans = activeInputChans.countNumberOfSetBits();
  233758. numOutputChans = activeOutputChans.countNumberOfSetBits();
  233759. // set sample rate
  233760. AudioObjectPropertyAddress pa;
  233761. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  233762. pa.mScope = kAudioObjectPropertyScopeWildcard;
  233763. pa.mElement = kAudioObjectPropertyElementMaster;
  233764. Float64 sr = newSampleRate;
  233765. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (sr), &sr)))
  233766. {
  233767. error = "Couldn't change sample rate";
  233768. }
  233769. else
  233770. {
  233771. // change buffer size
  233772. UInt32 framesPerBuf = bufferSizeSamples;
  233773. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  233774. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (framesPerBuf), &framesPerBuf)))
  233775. {
  233776. error = "Couldn't change buffer size";
  233777. }
  233778. else
  233779. {
  233780. // Annoyingly, after changing the rate and buffer size, some devices fail to
  233781. // correctly report their new settings until some random time in the future, so
  233782. // after calling updateDetailsFromDevice, we need to manually bodge these values
  233783. // to make sure we're using the correct numbers..
  233784. updateDetailsFromDevice();
  233785. sampleRate = newSampleRate;
  233786. bufferSize = bufferSizeSamples;
  233787. if (sampleRates.size() == 0)
  233788. error = "Device has no available sample-rates";
  233789. else if (bufferSizes.size() == 0)
  233790. error = "Device has no available buffer-sizes";
  233791. else if (inputDevice != 0)
  233792. error = inputDevice->reopen (inputChannels,
  233793. outputChannels,
  233794. newSampleRate,
  233795. bufferSizeSamples);
  233796. }
  233797. }
  233798. callbacksAllowed = true;
  233799. return error;
  233800. }
  233801. bool start (AudioIODeviceCallback* cb)
  233802. {
  233803. if (! started)
  233804. {
  233805. callback = 0;
  233806. if (deviceID != 0)
  233807. {
  233808. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  233809. if (OK (AudioDeviceAddIOProc (deviceID, audioIOProc, this)))
  233810. #else
  233811. if (OK (AudioDeviceCreateIOProcID (deviceID, audioIOProc, this, &audioProcID)))
  233812. #endif
  233813. {
  233814. if (OK (AudioDeviceStart (deviceID, audioIOProc)))
  233815. {
  233816. started = true;
  233817. }
  233818. else
  233819. {
  233820. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  233821. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  233822. #else
  233823. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  233824. audioProcID = 0;
  233825. #endif
  233826. }
  233827. }
  233828. }
  233829. }
  233830. if (started)
  233831. {
  233832. const ScopedLock sl (callbackLock);
  233833. callback = cb;
  233834. }
  233835. if (inputDevice != 0)
  233836. return started && inputDevice->start (cb);
  233837. else
  233838. return started;
  233839. }
  233840. void stop (bool leaveInterruptRunning)
  233841. {
  233842. {
  233843. const ScopedLock sl (callbackLock);
  233844. callback = 0;
  233845. }
  233846. if (started
  233847. && (deviceID != 0)
  233848. && ! leaveInterruptRunning)
  233849. {
  233850. OK (AudioDeviceStop (deviceID, audioIOProc));
  233851. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  233852. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  233853. #else
  233854. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  233855. audioProcID = 0;
  233856. #endif
  233857. started = false;
  233858. { const ScopedLock sl (callbackLock); }
  233859. // wait until it's definately stopped calling back..
  233860. for (int i = 40; --i >= 0;)
  233861. {
  233862. Thread::sleep (50);
  233863. UInt32 running = 0;
  233864. UInt32 size = sizeof (running);
  233865. AudioObjectPropertyAddress pa;
  233866. pa.mSelector = kAudioDevicePropertyDeviceIsRunning;
  233867. pa.mScope = kAudioObjectPropertyScopeWildcard;
  233868. pa.mElement = kAudioObjectPropertyElementMaster;
  233869. OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &running));
  233870. if (running == 0)
  233871. break;
  233872. }
  233873. const ScopedLock sl (callbackLock);
  233874. }
  233875. if (inputDevice != 0)
  233876. inputDevice->stop (leaveInterruptRunning);
  233877. }
  233878. double getSampleRate() const
  233879. {
  233880. return sampleRate;
  233881. }
  233882. int getBufferSize() const
  233883. {
  233884. return bufferSize;
  233885. }
  233886. void audioCallback (const AudioBufferList* inInputData,
  233887. AudioBufferList* outOutputData)
  233888. {
  233889. int i;
  233890. const ScopedLock sl (callbackLock);
  233891. if (callback != 0)
  233892. {
  233893. if (inputDevice == 0)
  233894. {
  233895. for (i = numInputChans; --i >= 0;)
  233896. {
  233897. const CallbackDetailsForChannel& info = inputChannelInfo[i];
  233898. float* dest = tempInputBuffers [i];
  233899. const float* src = ((const float*) inInputData->mBuffers[info.streamNum].mData)
  233900. + info.dataOffsetSamples;
  233901. const int stride = info.dataStrideSamples;
  233902. if (stride != 0) // if this is zero, info is invalid
  233903. {
  233904. for (int j = bufferSize; --j >= 0;)
  233905. {
  233906. *dest++ = *src;
  233907. src += stride;
  233908. }
  233909. }
  233910. }
  233911. }
  233912. if (! isSlaveDevice)
  233913. {
  233914. if (inputDevice == 0)
  233915. {
  233916. callback->audioDeviceIOCallback (const_cast<const float**> (tempInputBuffers.getData()),
  233917. numInputChans,
  233918. tempOutputBuffers,
  233919. numOutputChans,
  233920. bufferSize);
  233921. }
  233922. else
  233923. {
  233924. jassert (inputDevice->bufferSize == bufferSize);
  233925. // Sometimes the two linked devices seem to get their callbacks in
  233926. // parallel, so we need to lock both devices to stop the input data being
  233927. // changed while inside our callback..
  233928. const ScopedLock sl2 (inputDevice->callbackLock);
  233929. callback->audioDeviceIOCallback (const_cast<const float**> (inputDevice->tempInputBuffers.getData()),
  233930. inputDevice->numInputChans,
  233931. tempOutputBuffers,
  233932. numOutputChans,
  233933. bufferSize);
  233934. }
  233935. for (i = numOutputChans; --i >= 0;)
  233936. {
  233937. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  233938. const float* src = tempOutputBuffers [i];
  233939. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  233940. + info.dataOffsetSamples;
  233941. const int stride = info.dataStrideSamples;
  233942. if (stride != 0) // if this is zero, info is invalid
  233943. {
  233944. for (int j = bufferSize; --j >= 0;)
  233945. {
  233946. *dest = *src++;
  233947. dest += stride;
  233948. }
  233949. }
  233950. }
  233951. }
  233952. }
  233953. else
  233954. {
  233955. for (i = jmin (numOutputChans, numOutputChannelInfos); --i >= 0;)
  233956. {
  233957. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  233958. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  233959. + info.dataOffsetSamples;
  233960. const int stride = info.dataStrideSamples;
  233961. if (stride != 0) // if this is zero, info is invalid
  233962. {
  233963. for (int j = bufferSize; --j >= 0;)
  233964. {
  233965. *dest = 0.0f;
  233966. dest += stride;
  233967. }
  233968. }
  233969. }
  233970. }
  233971. }
  233972. // called by callbacks
  233973. void deviceDetailsChanged()
  233974. {
  233975. if (callbacksAllowed)
  233976. startTimer (100);
  233977. }
  233978. void timerCallback()
  233979. {
  233980. stopTimer();
  233981. log ("CoreAudio device changed callback");
  233982. const double oldSampleRate = sampleRate;
  233983. const int oldBufferSize = bufferSize;
  233984. updateDetailsFromDevice();
  233985. if (oldBufferSize != bufferSize || oldSampleRate != sampleRate)
  233986. {
  233987. callbacksAllowed = false;
  233988. stop (false);
  233989. updateDetailsFromDevice();
  233990. callbacksAllowed = true;
  233991. }
  233992. }
  233993. CoreAudioInternal* getRelatedDevice() const
  233994. {
  233995. UInt32 size = 0;
  233996. ScopedPointer <CoreAudioInternal> result;
  233997. AudioObjectPropertyAddress pa;
  233998. pa.mSelector = kAudioDevicePropertyRelatedDevices;
  233999. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234000. pa.mElement = kAudioObjectPropertyElementMaster;
  234001. if (deviceID != 0
  234002. && AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size) == noErr
  234003. && size > 0)
  234004. {
  234005. HeapBlock <AudioDeviceID> devs;
  234006. devs.calloc (size, 1);
  234007. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, devs)))
  234008. {
  234009. for (unsigned int i = 0; i < size / sizeof (AudioDeviceID); ++i)
  234010. {
  234011. if (devs[i] != deviceID && devs[i] != 0)
  234012. {
  234013. result = new CoreAudioInternal (devs[i]);
  234014. const bool thisIsInput = inChanNames.size() > 0 && outChanNames.size() == 0;
  234015. const bool otherIsInput = result->inChanNames.size() > 0 && result->outChanNames.size() == 0;
  234016. if (thisIsInput != otherIsInput
  234017. || (inChanNames.size() + outChanNames.size() == 0)
  234018. || (result->inChanNames.size() + result->outChanNames.size()) == 0)
  234019. break;
  234020. result = 0;
  234021. }
  234022. }
  234023. }
  234024. }
  234025. return result.release();
  234026. }
  234027. juce_UseDebuggingNewOperator
  234028. int inputLatency, outputLatency;
  234029. BigInteger activeInputChans, activeOutputChans;
  234030. StringArray inChanNames, outChanNames;
  234031. Array <double> sampleRates;
  234032. Array <int> bufferSizes;
  234033. AudioIODeviceCallback* callback;
  234034. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  234035. AudioDeviceIOProcID audioProcID;
  234036. #endif
  234037. ScopedPointer<CoreAudioInternal> inputDevice;
  234038. bool isSlaveDevice;
  234039. private:
  234040. CriticalSection callbackLock;
  234041. AudioDeviceID deviceID;
  234042. bool started;
  234043. double sampleRate;
  234044. int bufferSize;
  234045. HeapBlock <float> audioBuffer;
  234046. int numInputChans, numOutputChans;
  234047. bool callbacksAllowed;
  234048. struct CallbackDetailsForChannel
  234049. {
  234050. int streamNum;
  234051. int dataOffsetSamples;
  234052. int dataStrideSamples;
  234053. };
  234054. int numInputChannelInfos, numOutputChannelInfos;
  234055. HeapBlock <CallbackDetailsForChannel> inputChannelInfo, outputChannelInfo;
  234056. HeapBlock <float*> tempInputBuffers, tempOutputBuffers;
  234057. CoreAudioInternal (const CoreAudioInternal&);
  234058. CoreAudioInternal& operator= (const CoreAudioInternal&);
  234059. static OSStatus audioIOProc (AudioDeviceID /*inDevice*/,
  234060. const AudioTimeStamp* /*inNow*/,
  234061. const AudioBufferList* inInputData,
  234062. const AudioTimeStamp* /*inInputTime*/,
  234063. AudioBufferList* outOutputData,
  234064. const AudioTimeStamp* /*inOutputTime*/,
  234065. void* device)
  234066. {
  234067. static_cast <CoreAudioInternal*> (device)->audioCallback (inInputData, outOutputData);
  234068. return noErr;
  234069. }
  234070. static OSStatus deviceListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  234071. {
  234072. CoreAudioInternal* const intern = static_cast <CoreAudioInternal*> (inClientData);
  234073. switch (pa->mSelector)
  234074. {
  234075. case kAudioDevicePropertyBufferSize:
  234076. case kAudioDevicePropertyBufferFrameSize:
  234077. case kAudioDevicePropertyNominalSampleRate:
  234078. case kAudioDevicePropertyStreamFormat:
  234079. case kAudioDevicePropertyDeviceIsAlive:
  234080. intern->deviceDetailsChanged();
  234081. break;
  234082. case kAudioDevicePropertyBufferSizeRange:
  234083. case kAudioDevicePropertyVolumeScalar:
  234084. case kAudioDevicePropertyMute:
  234085. case kAudioDevicePropertyPlayThru:
  234086. case kAudioDevicePropertyDataSource:
  234087. case kAudioDevicePropertyDeviceIsRunning:
  234088. break;
  234089. }
  234090. return noErr;
  234091. }
  234092. static int getAllDataSourcesForDevice (AudioDeviceID deviceID, HeapBlock <OSType>& types)
  234093. {
  234094. AudioObjectPropertyAddress pa;
  234095. pa.mSelector = kAudioDevicePropertyDataSources;
  234096. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234097. pa.mElement = kAudioObjectPropertyElementMaster;
  234098. UInt32 size = 0;
  234099. if (deviceID != 0
  234100. && OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  234101. {
  234102. types.calloc (size, 1);
  234103. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, types)))
  234104. return size / (int) sizeof (OSType);
  234105. }
  234106. return 0;
  234107. }
  234108. };
  234109. class CoreAudioIODevice : public AudioIODevice
  234110. {
  234111. public:
  234112. CoreAudioIODevice (const String& deviceName,
  234113. AudioDeviceID inputDeviceId,
  234114. const int inputIndex_,
  234115. AudioDeviceID outputDeviceId,
  234116. const int outputIndex_)
  234117. : AudioIODevice (deviceName, "CoreAudio"),
  234118. inputIndex (inputIndex_),
  234119. outputIndex (outputIndex_),
  234120. isOpen_ (false),
  234121. isStarted (false)
  234122. {
  234123. CoreAudioInternal* device = 0;
  234124. if (outputDeviceId == 0 || outputDeviceId == inputDeviceId)
  234125. {
  234126. jassert (inputDeviceId != 0);
  234127. device = new CoreAudioInternal (inputDeviceId);
  234128. }
  234129. else
  234130. {
  234131. device = new CoreAudioInternal (outputDeviceId);
  234132. if (inputDeviceId != 0)
  234133. {
  234134. CoreAudioInternal* secondDevice = new CoreAudioInternal (inputDeviceId);
  234135. device->inputDevice = secondDevice;
  234136. secondDevice->isSlaveDevice = true;
  234137. }
  234138. }
  234139. internal = device;
  234140. AudioObjectPropertyAddress pa;
  234141. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  234142. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234143. pa.mElement = kAudioObjectPropertyElementWildcard;
  234144. AudioObjectAddPropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  234145. }
  234146. ~CoreAudioIODevice()
  234147. {
  234148. AudioObjectPropertyAddress pa;
  234149. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  234150. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234151. pa.mElement = kAudioObjectPropertyElementWildcard;
  234152. AudioObjectRemovePropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  234153. }
  234154. const StringArray getOutputChannelNames()
  234155. {
  234156. return internal->outChanNames;
  234157. }
  234158. const StringArray getInputChannelNames()
  234159. {
  234160. if (internal->inputDevice != 0)
  234161. return internal->inputDevice->inChanNames;
  234162. else
  234163. return internal->inChanNames;
  234164. }
  234165. int getNumSampleRates()
  234166. {
  234167. return internal->sampleRates.size();
  234168. }
  234169. double getSampleRate (int index)
  234170. {
  234171. return internal->sampleRates [index];
  234172. }
  234173. int getNumBufferSizesAvailable()
  234174. {
  234175. return internal->bufferSizes.size();
  234176. }
  234177. int getBufferSizeSamples (int index)
  234178. {
  234179. return internal->bufferSizes [index];
  234180. }
  234181. int getDefaultBufferSize()
  234182. {
  234183. for (int i = 0; i < getNumBufferSizesAvailable(); ++i)
  234184. if (getBufferSizeSamples(i) >= 512)
  234185. return getBufferSizeSamples(i);
  234186. return 512;
  234187. }
  234188. const String open (const BigInteger& inputChannels,
  234189. const BigInteger& outputChannels,
  234190. double sampleRate,
  234191. int bufferSizeSamples)
  234192. {
  234193. isOpen_ = true;
  234194. if (bufferSizeSamples <= 0)
  234195. bufferSizeSamples = getDefaultBufferSize();
  234196. lastError = internal->reopen (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  234197. isOpen_ = lastError.isEmpty();
  234198. return lastError;
  234199. }
  234200. void close()
  234201. {
  234202. isOpen_ = false;
  234203. internal->stop (false);
  234204. }
  234205. bool isOpen()
  234206. {
  234207. return isOpen_;
  234208. }
  234209. int getCurrentBufferSizeSamples()
  234210. {
  234211. return internal != 0 ? internal->getBufferSize() : 512;
  234212. }
  234213. double getCurrentSampleRate()
  234214. {
  234215. return internal != 0 ? internal->getSampleRate() : 0;
  234216. }
  234217. int getCurrentBitDepth()
  234218. {
  234219. return 32; // no way to find out, so just assume it's high..
  234220. }
  234221. const BigInteger getActiveOutputChannels() const
  234222. {
  234223. return internal != 0 ? internal->activeOutputChans : BigInteger();
  234224. }
  234225. const BigInteger getActiveInputChannels() const
  234226. {
  234227. BigInteger chans;
  234228. if (internal != 0)
  234229. {
  234230. chans = internal->activeInputChans;
  234231. if (internal->inputDevice != 0)
  234232. chans |= internal->inputDevice->activeInputChans;
  234233. }
  234234. return chans;
  234235. }
  234236. int getOutputLatencyInSamples()
  234237. {
  234238. if (internal == 0)
  234239. return 0;
  234240. // this seems like a good guess at getting the latency right - comparing
  234241. // this with a round-trip measurement, it gets it to within a few millisecs
  234242. // for the built-in mac soundcard
  234243. return internal->outputLatency + internal->getBufferSize() * 2;
  234244. }
  234245. int getInputLatencyInSamples()
  234246. {
  234247. if (internal == 0)
  234248. return 0;
  234249. return internal->inputLatency + internal->getBufferSize() * 2;
  234250. }
  234251. void start (AudioIODeviceCallback* callback)
  234252. {
  234253. if (internal != 0 && ! isStarted)
  234254. {
  234255. if (callback != 0)
  234256. callback->audioDeviceAboutToStart (this);
  234257. isStarted = true;
  234258. internal->start (callback);
  234259. }
  234260. }
  234261. void stop()
  234262. {
  234263. if (isStarted && internal != 0)
  234264. {
  234265. AudioIODeviceCallback* const lastCallback = internal->callback;
  234266. isStarted = false;
  234267. internal->stop (true);
  234268. if (lastCallback != 0)
  234269. lastCallback->audioDeviceStopped();
  234270. }
  234271. }
  234272. bool isPlaying()
  234273. {
  234274. if (internal->callback == 0)
  234275. isStarted = false;
  234276. return isStarted;
  234277. }
  234278. const String getLastError()
  234279. {
  234280. return lastError;
  234281. }
  234282. int inputIndex, outputIndex;
  234283. juce_UseDebuggingNewOperator
  234284. private:
  234285. ScopedPointer<CoreAudioInternal> internal;
  234286. bool isOpen_, isStarted;
  234287. String lastError;
  234288. static OSStatus hardwareListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  234289. {
  234290. CoreAudioInternal* const intern = static_cast <CoreAudioInternal*> (inClientData);
  234291. switch (pa->mSelector)
  234292. {
  234293. case kAudioHardwarePropertyDevices:
  234294. intern->deviceDetailsChanged();
  234295. break;
  234296. case kAudioHardwarePropertyDefaultOutputDevice:
  234297. case kAudioHardwarePropertyDefaultInputDevice:
  234298. case kAudioHardwarePropertyDefaultSystemOutputDevice:
  234299. break;
  234300. }
  234301. return noErr;
  234302. }
  234303. CoreAudioIODevice (const CoreAudioIODevice&);
  234304. CoreAudioIODevice& operator= (const CoreAudioIODevice&);
  234305. };
  234306. class CoreAudioIODeviceType : public AudioIODeviceType
  234307. {
  234308. public:
  234309. CoreAudioIODeviceType()
  234310. : AudioIODeviceType ("CoreAudio"),
  234311. hasScanned (false)
  234312. {
  234313. }
  234314. ~CoreAudioIODeviceType()
  234315. {
  234316. }
  234317. void scanForDevices()
  234318. {
  234319. hasScanned = true;
  234320. inputDeviceNames.clear();
  234321. outputDeviceNames.clear();
  234322. inputIds.clear();
  234323. outputIds.clear();
  234324. UInt32 size;
  234325. AudioObjectPropertyAddress pa;
  234326. pa.mSelector = kAudioHardwarePropertyDevices;
  234327. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234328. pa.mElement = kAudioObjectPropertyElementMaster;
  234329. if (OK (AudioObjectGetPropertyDataSize (kAudioObjectSystemObject, &pa, 0, 0, &size)))
  234330. {
  234331. HeapBlock <AudioDeviceID> devs;
  234332. devs.calloc (size, 1);
  234333. if (OK (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, devs)))
  234334. {
  234335. static bool alreadyLogged = false;
  234336. const int num = size / (int) sizeof (AudioDeviceID);
  234337. for (int i = 0; i < num; ++i)
  234338. {
  234339. char name [1024];
  234340. size = sizeof (name);
  234341. pa.mSelector = kAudioDevicePropertyDeviceName;
  234342. if (OK (AudioObjectGetPropertyData (devs[i], &pa, 0, 0, &size, name)))
  234343. {
  234344. const String nameString (String::fromUTF8 (name, (int) strlen (name)));
  234345. if (! alreadyLogged)
  234346. log ("CoreAudio device: " + nameString);
  234347. const int numIns = getNumChannels (devs[i], true);
  234348. const int numOuts = getNumChannels (devs[i], false);
  234349. if (numIns > 0)
  234350. {
  234351. inputDeviceNames.add (nameString);
  234352. inputIds.add (devs[i]);
  234353. }
  234354. if (numOuts > 0)
  234355. {
  234356. outputDeviceNames.add (nameString);
  234357. outputIds.add (devs[i]);
  234358. }
  234359. }
  234360. }
  234361. alreadyLogged = true;
  234362. }
  234363. }
  234364. inputDeviceNames.appendNumbersToDuplicates (false, true);
  234365. outputDeviceNames.appendNumbersToDuplicates (false, true);
  234366. }
  234367. const StringArray getDeviceNames (bool wantInputNames) const
  234368. {
  234369. jassert (hasScanned); // need to call scanForDevices() before doing this
  234370. if (wantInputNames)
  234371. return inputDeviceNames;
  234372. else
  234373. return outputDeviceNames;
  234374. }
  234375. int getDefaultDeviceIndex (bool forInput) const
  234376. {
  234377. jassert (hasScanned); // need to call scanForDevices() before doing this
  234378. AudioDeviceID deviceID;
  234379. UInt32 size = sizeof (deviceID);
  234380. // if they're asking for any input channels at all, use the default input, so we
  234381. // get the built-in mic rather than the built-in output with no inputs..
  234382. AudioObjectPropertyAddress pa;
  234383. pa.mSelector = forInput ? kAudioHardwarePropertyDefaultInputDevice : kAudioHardwarePropertyDefaultOutputDevice;
  234384. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234385. pa.mElement = kAudioObjectPropertyElementMaster;
  234386. if (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, &deviceID) == noErr)
  234387. {
  234388. if (forInput)
  234389. {
  234390. for (int i = inputIds.size(); --i >= 0;)
  234391. if (inputIds[i] == deviceID)
  234392. return i;
  234393. }
  234394. else
  234395. {
  234396. for (int i = outputIds.size(); --i >= 0;)
  234397. if (outputIds[i] == deviceID)
  234398. return i;
  234399. }
  234400. }
  234401. return 0;
  234402. }
  234403. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  234404. {
  234405. jassert (hasScanned); // need to call scanForDevices() before doing this
  234406. CoreAudioIODevice* const d = dynamic_cast <CoreAudioIODevice*> (device);
  234407. if (d == 0)
  234408. return -1;
  234409. return asInput ? d->inputIndex
  234410. : d->outputIndex;
  234411. }
  234412. bool hasSeparateInputsAndOutputs() const { return true; }
  234413. AudioIODevice* createDevice (const String& outputDeviceName,
  234414. const String& inputDeviceName)
  234415. {
  234416. jassert (hasScanned); // need to call scanForDevices() before doing this
  234417. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  234418. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  234419. String deviceName (outputDeviceName);
  234420. if (deviceName.isEmpty())
  234421. deviceName = inputDeviceName;
  234422. if (index >= 0)
  234423. return new CoreAudioIODevice (deviceName,
  234424. inputIds [inputIndex],
  234425. inputIndex,
  234426. outputIds [outputIndex],
  234427. outputIndex);
  234428. return 0;
  234429. }
  234430. juce_UseDebuggingNewOperator
  234431. private:
  234432. StringArray inputDeviceNames, outputDeviceNames;
  234433. Array <AudioDeviceID> inputIds, outputIds;
  234434. bool hasScanned;
  234435. static int getNumChannels (AudioDeviceID deviceID, bool input)
  234436. {
  234437. int total = 0;
  234438. UInt32 size;
  234439. AudioObjectPropertyAddress pa;
  234440. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  234441. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  234442. pa.mElement = kAudioObjectPropertyElementMaster;
  234443. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  234444. {
  234445. HeapBlock <AudioBufferList> bufList;
  234446. bufList.calloc (size, 1);
  234447. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  234448. {
  234449. const int numStreams = bufList->mNumberBuffers;
  234450. for (int i = 0; i < numStreams; ++i)
  234451. {
  234452. const AudioBuffer& b = bufList->mBuffers[i];
  234453. total += b.mNumberChannels;
  234454. }
  234455. }
  234456. }
  234457. return total;
  234458. }
  234459. CoreAudioIODeviceType (const CoreAudioIODeviceType&);
  234460. CoreAudioIODeviceType& operator= (const CoreAudioIODeviceType&);
  234461. };
  234462. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio()
  234463. {
  234464. return new CoreAudioIODeviceType();
  234465. }
  234466. #undef log
  234467. #endif
  234468. /*** End of inlined file: juce_mac_CoreAudio.cpp ***/
  234469. /*** Start of inlined file: juce_mac_CoreMidi.cpp ***/
  234470. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234471. // compiled on its own).
  234472. #if JUCE_INCLUDED_FILE
  234473. #if JUCE_MAC
  234474. #undef log
  234475. #define log(a) Logger::writeToLog(a)
  234476. static bool logAnyErrorsMidi (const OSStatus err, const int lineNum)
  234477. {
  234478. if (err == noErr)
  234479. return true;
  234480. log ("CoreMidi error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  234481. jassertfalse;
  234482. return false;
  234483. }
  234484. #undef OK
  234485. #define OK(a) logAnyErrorsMidi(a, __LINE__)
  234486. static const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  234487. {
  234488. String result;
  234489. CFStringRef str = 0;
  234490. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  234491. if (str != 0)
  234492. {
  234493. result = PlatformUtilities::cfStringToJuceString (str);
  234494. CFRelease (str);
  234495. str = 0;
  234496. }
  234497. MIDIEntityRef entity = 0;
  234498. MIDIEndpointGetEntity (endpoint, &entity);
  234499. if (entity == 0)
  234500. return result; // probably virtual
  234501. if (result.isEmpty())
  234502. {
  234503. // endpoint name has zero length - try the entity
  234504. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  234505. if (str != 0)
  234506. {
  234507. result += PlatformUtilities::cfStringToJuceString (str);
  234508. CFRelease (str);
  234509. str = 0;
  234510. }
  234511. }
  234512. // now consider the device's name
  234513. MIDIDeviceRef device = 0;
  234514. MIDIEntityGetDevice (entity, &device);
  234515. if (device == 0)
  234516. return result;
  234517. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  234518. if (str != 0)
  234519. {
  234520. const String s (PlatformUtilities::cfStringToJuceString (str));
  234521. CFRelease (str);
  234522. // if an external device has only one entity, throw away
  234523. // the endpoint name and just use the device name
  234524. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  234525. {
  234526. result = s;
  234527. }
  234528. else if (! result.startsWithIgnoreCase (s))
  234529. {
  234530. // prepend the device name to the entity name
  234531. result = (s + " " + result).trimEnd();
  234532. }
  234533. }
  234534. return result;
  234535. }
  234536. static const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  234537. {
  234538. String result;
  234539. // Does the endpoint have connections?
  234540. CFDataRef connections = 0;
  234541. int numConnections = 0;
  234542. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  234543. if (connections != 0)
  234544. {
  234545. numConnections = (int) (CFDataGetLength (connections) / sizeof (MIDIUniqueID));
  234546. if (numConnections > 0)
  234547. {
  234548. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  234549. for (int i = 0; i < numConnections; ++i, ++pid)
  234550. {
  234551. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  234552. MIDIObjectRef connObject;
  234553. MIDIObjectType connObjectType;
  234554. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  234555. if (err == noErr)
  234556. {
  234557. String s;
  234558. if (connObjectType == kMIDIObjectType_ExternalSource
  234559. || connObjectType == kMIDIObjectType_ExternalDestination)
  234560. {
  234561. // Connected to an external device's endpoint (10.3 and later).
  234562. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  234563. }
  234564. else
  234565. {
  234566. // Connected to an external device (10.2) (or something else, catch-all)
  234567. CFStringRef str = 0;
  234568. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  234569. if (str != 0)
  234570. {
  234571. s = PlatformUtilities::cfStringToJuceString (str);
  234572. CFRelease (str);
  234573. }
  234574. }
  234575. if (s.isNotEmpty())
  234576. {
  234577. if (result.isNotEmpty())
  234578. result += ", ";
  234579. result += s;
  234580. }
  234581. }
  234582. }
  234583. }
  234584. CFRelease (connections);
  234585. }
  234586. if (result.isNotEmpty())
  234587. return result;
  234588. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  234589. return getEndpointName (endpoint, false);
  234590. }
  234591. const StringArray MidiOutput::getDevices()
  234592. {
  234593. StringArray s;
  234594. const ItemCount num = MIDIGetNumberOfDestinations();
  234595. for (ItemCount i = 0; i < num; ++i)
  234596. {
  234597. MIDIEndpointRef dest = MIDIGetDestination (i);
  234598. if (dest != 0)
  234599. {
  234600. String name (getConnectedEndpointName (dest));
  234601. if (name.isEmpty())
  234602. name = "<error>";
  234603. s.add (name);
  234604. }
  234605. else
  234606. {
  234607. s.add ("<error>");
  234608. }
  234609. }
  234610. return s;
  234611. }
  234612. int MidiOutput::getDefaultDeviceIndex()
  234613. {
  234614. return 0;
  234615. }
  234616. static MIDIClientRef globalMidiClient;
  234617. static bool hasGlobalClientBeenCreated = false;
  234618. static bool makeSureClientExists()
  234619. {
  234620. if (! hasGlobalClientBeenCreated)
  234621. {
  234622. String name ("JUCE");
  234623. if (JUCEApplication::getInstance() != 0)
  234624. name = JUCEApplication::getInstance()->getApplicationName();
  234625. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  234626. hasGlobalClientBeenCreated = OK (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  234627. CFRelease (appName);
  234628. }
  234629. return hasGlobalClientBeenCreated;
  234630. }
  234631. class MidiPortAndEndpoint
  234632. {
  234633. public:
  234634. MidiPortAndEndpoint (MIDIPortRef port_, MIDIEndpointRef endPoint_)
  234635. : port (port_), endPoint (endPoint_)
  234636. {
  234637. }
  234638. ~MidiPortAndEndpoint()
  234639. {
  234640. if (port != 0)
  234641. MIDIPortDispose (port);
  234642. if (port == 0 && endPoint != 0) // if port == 0, it means we created the endpoint, so it's safe to delete it
  234643. MIDIEndpointDispose (endPoint);
  234644. }
  234645. MIDIPortRef port;
  234646. MIDIEndpointRef endPoint;
  234647. };
  234648. MidiOutput* MidiOutput::openDevice (int index)
  234649. {
  234650. MidiOutput* mo = 0;
  234651. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfDestinations())
  234652. {
  234653. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  234654. CFStringRef pname;
  234655. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  234656. {
  234657. log ("CoreMidi - opening out: " + PlatformUtilities::cfStringToJuceString (pname));
  234658. if (makeSureClientExists())
  234659. {
  234660. MIDIPortRef port;
  234661. if (OK (MIDIOutputPortCreate (globalMidiClient, pname, &port)))
  234662. {
  234663. mo = new MidiOutput();
  234664. mo->internal = new MidiPortAndEndpoint (port, endPoint);
  234665. }
  234666. }
  234667. CFRelease (pname);
  234668. }
  234669. }
  234670. return mo;
  234671. }
  234672. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  234673. {
  234674. MidiOutput* mo = 0;
  234675. if (makeSureClientExists())
  234676. {
  234677. MIDIEndpointRef endPoint;
  234678. CFStringRef name = PlatformUtilities::juceStringToCFString (deviceName);
  234679. if (OK (MIDISourceCreate (globalMidiClient, name, &endPoint)))
  234680. {
  234681. mo = new MidiOutput();
  234682. mo->internal = new MidiPortAndEndpoint (0, endPoint);
  234683. }
  234684. CFRelease (name);
  234685. }
  234686. return mo;
  234687. }
  234688. MidiOutput::~MidiOutput()
  234689. {
  234690. delete (MidiPortAndEndpoint*) internal;
  234691. }
  234692. void MidiOutput::reset()
  234693. {
  234694. }
  234695. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  234696. {
  234697. return false;
  234698. }
  234699. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  234700. {
  234701. }
  234702. void MidiOutput::sendMessageNow (const MidiMessage& message)
  234703. {
  234704. MidiPortAndEndpoint* const mpe = (MidiPortAndEndpoint*) internal;
  234705. if (message.isSysEx())
  234706. {
  234707. const int maxPacketSize = 256;
  234708. int pos = 0, bytesLeft = message.getRawDataSize();
  234709. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  234710. HeapBlock <MIDIPacketList> packets;
  234711. packets.malloc (32 * numPackets + message.getRawDataSize(), 1);
  234712. packets->numPackets = numPackets;
  234713. MIDIPacket* p = packets->packet;
  234714. for (int i = 0; i < numPackets; ++i)
  234715. {
  234716. p->timeStamp = 0;
  234717. p->length = jmin (maxPacketSize, bytesLeft);
  234718. memcpy (p->data, message.getRawData() + pos, p->length);
  234719. pos += p->length;
  234720. bytesLeft -= p->length;
  234721. p = MIDIPacketNext (p);
  234722. }
  234723. if (mpe->port != 0)
  234724. MIDISend (mpe->port, mpe->endPoint, packets);
  234725. else
  234726. MIDIReceived (mpe->endPoint, packets);
  234727. }
  234728. else
  234729. {
  234730. MIDIPacketList packets;
  234731. packets.numPackets = 1;
  234732. packets.packet[0].timeStamp = 0;
  234733. packets.packet[0].length = message.getRawDataSize();
  234734. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  234735. if (mpe->port != 0)
  234736. MIDISend (mpe->port, mpe->endPoint, &packets);
  234737. else
  234738. MIDIReceived (mpe->endPoint, &packets);
  234739. }
  234740. }
  234741. const StringArray MidiInput::getDevices()
  234742. {
  234743. StringArray s;
  234744. const ItemCount num = MIDIGetNumberOfSources();
  234745. for (ItemCount i = 0; i < num; ++i)
  234746. {
  234747. MIDIEndpointRef source = MIDIGetSource (i);
  234748. if (source != 0)
  234749. {
  234750. String name (getConnectedEndpointName (source));
  234751. if (name.isEmpty())
  234752. name = "<error>";
  234753. s.add (name);
  234754. }
  234755. else
  234756. {
  234757. s.add ("<error>");
  234758. }
  234759. }
  234760. return s;
  234761. }
  234762. int MidiInput::getDefaultDeviceIndex()
  234763. {
  234764. return 0;
  234765. }
  234766. struct MidiPortAndCallback
  234767. {
  234768. MidiInput* input;
  234769. MidiPortAndEndpoint* portAndEndpoint;
  234770. MidiInputCallback* callback;
  234771. MemoryBlock pendingData;
  234772. int pendingBytes;
  234773. double pendingDataTime;
  234774. bool active;
  234775. void processSysex (const uint8*& d, int& size, const double time)
  234776. {
  234777. if (*d == 0xf0)
  234778. {
  234779. pendingBytes = 0;
  234780. pendingDataTime = time;
  234781. }
  234782. pendingData.ensureSize (pendingBytes + size, false);
  234783. uint8* totalMessage = (uint8*) pendingData.getData();
  234784. uint8* dest = totalMessage + pendingBytes;
  234785. while (size > 0)
  234786. {
  234787. if (pendingBytes > 0 && *d >= 0x80)
  234788. {
  234789. if (*d >= 0xfa || *d == 0xf8)
  234790. {
  234791. callback->handleIncomingMidiMessage (input, MidiMessage (*d, time));
  234792. ++d;
  234793. --size;
  234794. }
  234795. else
  234796. {
  234797. if (*d == 0xf7)
  234798. {
  234799. *dest++ = *d++;
  234800. pendingBytes++;
  234801. --size;
  234802. }
  234803. break;
  234804. }
  234805. }
  234806. else
  234807. {
  234808. *dest++ = *d++;
  234809. pendingBytes++;
  234810. --size;
  234811. }
  234812. }
  234813. if (totalMessage [pendingBytes - 1] == 0xf7)
  234814. {
  234815. callback->handleIncomingMidiMessage (input, MidiMessage (totalMessage, pendingBytes, pendingDataTime));
  234816. pendingBytes = 0;
  234817. }
  234818. else
  234819. {
  234820. callback->handlePartialSysexMessage (input, totalMessage, pendingBytes, pendingDataTime);
  234821. }
  234822. }
  234823. };
  234824. namespace CoreMidiCallbacks
  234825. {
  234826. static CriticalSection callbackLock;
  234827. static Array<void*> activeCallbacks;
  234828. }
  234829. static void midiInputProc (const MIDIPacketList* pktlist,
  234830. void* readProcRefCon,
  234831. void* /*srcConnRefCon*/)
  234832. {
  234833. double time = Time::getMillisecondCounterHiRes() * 0.001;
  234834. const double originalTime = time;
  234835. MidiPortAndCallback* const mpc = (MidiPortAndCallback*) readProcRefCon;
  234836. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  234837. if (CoreMidiCallbacks::activeCallbacks.contains (mpc) && mpc->active)
  234838. {
  234839. const MIDIPacket* packet = &pktlist->packet[0];
  234840. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  234841. {
  234842. const uint8* d = (const uint8*) (packet->data);
  234843. int size = packet->length;
  234844. while (size > 0)
  234845. {
  234846. time = originalTime;
  234847. if (mpc->pendingBytes > 0 || d[0] == 0xf0)
  234848. {
  234849. mpc->processSysex (d, size, time);
  234850. }
  234851. else
  234852. {
  234853. int used = 0;
  234854. const MidiMessage m (d, size, used, 0, time);
  234855. if (used <= 0)
  234856. {
  234857. jassertfalse; // malformed midi message
  234858. break;
  234859. }
  234860. else
  234861. {
  234862. mpc->callback->handleIncomingMidiMessage (mpc->input, m);
  234863. }
  234864. size -= used;
  234865. d += used;
  234866. }
  234867. }
  234868. packet = MIDIPacketNext (packet);
  234869. }
  234870. }
  234871. }
  234872. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  234873. {
  234874. MidiInput* mi = 0;
  234875. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfSources())
  234876. {
  234877. MIDIEndpointRef endPoint = MIDIGetSource (index);
  234878. if (endPoint != 0)
  234879. {
  234880. CFStringRef pname;
  234881. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  234882. {
  234883. log ("CoreMidi - opening inp: " + PlatformUtilities::cfStringToJuceString (pname));
  234884. if (makeSureClientExists())
  234885. {
  234886. MIDIPortRef port;
  234887. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback());
  234888. mpc->active = false;
  234889. if (OK (MIDIInputPortCreate (globalMidiClient, pname, midiInputProc, mpc, &port)))
  234890. {
  234891. if (OK (MIDIPortConnectSource (port, endPoint, 0)))
  234892. {
  234893. mpc->portAndEndpoint = new MidiPortAndEndpoint (port, endPoint);
  234894. mpc->callback = callback;
  234895. mpc->pendingBytes = 0;
  234896. mpc->pendingData.ensureSize (128);
  234897. mi = new MidiInput (getDevices() [index]);
  234898. mpc->input = mi;
  234899. mi->internal = mpc;
  234900. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  234901. CoreMidiCallbacks::activeCallbacks.add (mpc.release());
  234902. }
  234903. else
  234904. {
  234905. OK (MIDIPortDispose (port));
  234906. }
  234907. }
  234908. }
  234909. }
  234910. CFRelease (pname);
  234911. }
  234912. }
  234913. return mi;
  234914. }
  234915. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  234916. {
  234917. MidiInput* mi = 0;
  234918. if (makeSureClientExists())
  234919. {
  234920. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback());
  234921. mpc->active = false;
  234922. MIDIEndpointRef endPoint;
  234923. CFStringRef name = PlatformUtilities::juceStringToCFString(deviceName);
  234924. if (OK (MIDIDestinationCreate (globalMidiClient, name, midiInputProc, mpc, &endPoint)))
  234925. {
  234926. mpc->portAndEndpoint = new MidiPortAndEndpoint (0, endPoint);
  234927. mpc->callback = callback;
  234928. mpc->pendingBytes = 0;
  234929. mpc->pendingData.ensureSize (128);
  234930. mi = new MidiInput (deviceName);
  234931. mpc->input = mi;
  234932. mi->internal = mpc;
  234933. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  234934. CoreMidiCallbacks::activeCallbacks.add (mpc.release());
  234935. }
  234936. CFRelease (name);
  234937. }
  234938. return mi;
  234939. }
  234940. MidiInput::MidiInput (const String& name_)
  234941. : name (name_)
  234942. {
  234943. }
  234944. MidiInput::~MidiInput()
  234945. {
  234946. MidiPortAndCallback* const mpc = (MidiPortAndCallback*) internal;
  234947. mpc->active = false;
  234948. {
  234949. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  234950. CoreMidiCallbacks::activeCallbacks.removeValue (mpc);
  234951. }
  234952. if (mpc->portAndEndpoint->port != 0)
  234953. OK (MIDIPortDisconnectSource (mpc->portAndEndpoint->port, mpc->portAndEndpoint->endPoint));
  234954. delete mpc->portAndEndpoint;
  234955. delete mpc;
  234956. }
  234957. void MidiInput::start()
  234958. {
  234959. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  234960. ((MidiPortAndCallback*) internal)->active = true;
  234961. }
  234962. void MidiInput::stop()
  234963. {
  234964. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  234965. ((MidiPortAndCallback*) internal)->active = false;
  234966. }
  234967. #undef log
  234968. #else
  234969. MidiOutput::~MidiOutput()
  234970. {
  234971. }
  234972. void MidiOutput::reset()
  234973. {
  234974. }
  234975. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  234976. {
  234977. return false;
  234978. }
  234979. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  234980. {
  234981. }
  234982. void MidiOutput::sendMessageNow (const MidiMessage& message)
  234983. {
  234984. }
  234985. const StringArray MidiOutput::getDevices()
  234986. {
  234987. return StringArray();
  234988. }
  234989. MidiOutput* MidiOutput::openDevice (int index)
  234990. {
  234991. return 0;
  234992. }
  234993. const StringArray MidiInput::getDevices()
  234994. {
  234995. return StringArray();
  234996. }
  234997. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  234998. {
  234999. return 0;
  235000. }
  235001. #endif
  235002. #endif
  235003. /*** End of inlined file: juce_mac_CoreMidi.cpp ***/
  235004. /*** Start of inlined file: juce_mac_CameraDevice.mm ***/
  235005. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  235006. // compiled on its own).
  235007. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  235008. #if ! JUCE_QUICKTIME
  235009. #error "On the Mac, cameras use Quicktime, so if you turn on JUCE_USE_CAMERA, you also need to enable JUCE_QUICKTIME"
  235010. #endif
  235011. #define QTCaptureCallbackDelegate MakeObjCClassName(QTCaptureCallbackDelegate)
  235012. class QTCameraDeviceInteral;
  235013. END_JUCE_NAMESPACE
  235014. @interface QTCaptureCallbackDelegate : NSObject
  235015. {
  235016. @public
  235017. CameraDevice* owner;
  235018. QTCameraDeviceInteral* internal;
  235019. int64 firstPresentationTime;
  235020. int64 averageTimeOffset;
  235021. }
  235022. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner internalDev: (QTCameraDeviceInteral*) d;
  235023. - (void) dealloc;
  235024. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  235025. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  235026. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  235027. fromConnection: (QTCaptureConnection*) connection;
  235028. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  235029. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  235030. fromConnection: (QTCaptureConnection*) connection;
  235031. @end
  235032. BEGIN_JUCE_NAMESPACE
  235033. class QTCameraDeviceInteral
  235034. {
  235035. public:
  235036. QTCameraDeviceInteral (CameraDevice* owner, int index)
  235037. {
  235038. const ScopedAutoReleasePool pool;
  235039. session = [[QTCaptureSession alloc] init];
  235040. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  235041. device = (QTCaptureDevice*) [devs objectAtIndex: index];
  235042. input = 0;
  235043. audioInput = 0;
  235044. audioDevice = 0;
  235045. fileOutput = 0;
  235046. imageOutput = 0;
  235047. callbackDelegate = [[QTCaptureCallbackDelegate alloc] initWithOwner: owner
  235048. internalDev: this];
  235049. NSError* err = 0;
  235050. [device retain];
  235051. [device open: &err];
  235052. if (err == 0)
  235053. {
  235054. input = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  235055. audioInput = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  235056. [session addInput: input error: &err];
  235057. if (err == 0)
  235058. {
  235059. resetFile();
  235060. imageOutput = [[QTCaptureDecompressedVideoOutput alloc] init];
  235061. [imageOutput setDelegate: callbackDelegate];
  235062. if (err == 0)
  235063. {
  235064. [session startRunning];
  235065. return;
  235066. }
  235067. }
  235068. }
  235069. openingError = nsStringToJuce ([err description]);
  235070. DBG (openingError);
  235071. }
  235072. ~QTCameraDeviceInteral()
  235073. {
  235074. [session stopRunning];
  235075. [session removeOutput: imageOutput];
  235076. [session release];
  235077. [input release];
  235078. [device release];
  235079. [audioDevice release];
  235080. [audioInput release];
  235081. [fileOutput release];
  235082. [imageOutput release];
  235083. [callbackDelegate release];
  235084. }
  235085. void resetFile()
  235086. {
  235087. [fileOutput recordToOutputFileURL: nil];
  235088. [session removeOutput: fileOutput];
  235089. [fileOutput release];
  235090. fileOutput = [[QTCaptureMovieFileOutput alloc] init];
  235091. [session removeInput: audioInput];
  235092. [audioInput release];
  235093. audioInput = 0;
  235094. [audioDevice release];
  235095. audioDevice = 0;
  235096. [fileOutput setDelegate: callbackDelegate];
  235097. }
  235098. void addDefaultAudioInput()
  235099. {
  235100. NSError* err = nil;
  235101. audioDevice = [QTCaptureDevice defaultInputDeviceWithMediaType: QTMediaTypeSound];
  235102. if ([audioDevice open: &err])
  235103. [audioDevice retain];
  235104. else
  235105. audioDevice = nil;
  235106. if (audioDevice != 0)
  235107. {
  235108. audioInput = [[QTCaptureDeviceInput alloc] initWithDevice: audioDevice];
  235109. [session addInput: audioInput error: &err];
  235110. }
  235111. }
  235112. void addListener (CameraImageListener* listenerToAdd)
  235113. {
  235114. const ScopedLock sl (listenerLock);
  235115. if (listeners.size() == 0)
  235116. [session addOutput: imageOutput error: nil];
  235117. listeners.addIfNotAlreadyThere (listenerToAdd);
  235118. }
  235119. void removeListener (CameraImageListener* listenerToRemove)
  235120. {
  235121. const ScopedLock sl (listenerLock);
  235122. listeners.removeValue (listenerToRemove);
  235123. if (listeners.size() == 0)
  235124. [session removeOutput: imageOutput];
  235125. }
  235126. void callListeners (CIImage* frame, int w, int h)
  235127. {
  235128. CoreGraphicsImage* cgImage = new CoreGraphicsImage (Image::ARGB, w, h, false);
  235129. Image image (cgImage);
  235130. CIContext* cic = [CIContext contextWithCGContext: cgImage->context options: nil];
  235131. [cic drawImage: frame inRect: CGRectMake (0, 0, w, h) fromRect: CGRectMake (0, 0, w, h)];
  235132. CGContextFlush (cgImage->context);
  235133. const ScopedLock sl (listenerLock);
  235134. for (int i = listeners.size(); --i >= 0;)
  235135. {
  235136. CameraImageListener* const l = listeners[i];
  235137. if (l != 0)
  235138. l->imageReceived (image);
  235139. }
  235140. }
  235141. QTCaptureDevice* device;
  235142. QTCaptureDeviceInput* input;
  235143. QTCaptureDevice* audioDevice;
  235144. QTCaptureDeviceInput* audioInput;
  235145. QTCaptureSession* session;
  235146. QTCaptureMovieFileOutput* fileOutput;
  235147. QTCaptureDecompressedVideoOutput* imageOutput;
  235148. QTCaptureCallbackDelegate* callbackDelegate;
  235149. String openingError;
  235150. Array<CameraImageListener*> listeners;
  235151. CriticalSection listenerLock;
  235152. };
  235153. END_JUCE_NAMESPACE
  235154. @implementation QTCaptureCallbackDelegate
  235155. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner_
  235156. internalDev: (QTCameraDeviceInteral*) d
  235157. {
  235158. [super init];
  235159. owner = owner_;
  235160. internal = d;
  235161. firstPresentationTime = 0;
  235162. averageTimeOffset = 0;
  235163. return self;
  235164. }
  235165. - (void) dealloc
  235166. {
  235167. [super dealloc];
  235168. }
  235169. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  235170. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  235171. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  235172. fromConnection: (QTCaptureConnection*) connection
  235173. {
  235174. if (internal->listeners.size() > 0)
  235175. {
  235176. const ScopedAutoReleasePool pool;
  235177. internal->callListeners ([CIImage imageWithCVImageBuffer: videoFrame],
  235178. CVPixelBufferGetWidth (videoFrame),
  235179. CVPixelBufferGetHeight (videoFrame));
  235180. }
  235181. }
  235182. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  235183. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  235184. fromConnection: (QTCaptureConnection*) connection
  235185. {
  235186. const Time now (Time::getCurrentTime());
  235187. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  235188. NSNumber* hosttime = (NSNumber*) [sampleBuffer attributeForKey: QTSampleBufferHostTimeAttribute];
  235189. #else
  235190. NSNumber* hosttime = (NSNumber*) [sampleBuffer attributeForKey: @"hostTime"];
  235191. #endif
  235192. int64 presentationTime = (hosttime != nil)
  235193. ? ((int64) AudioConvertHostTimeToNanos ([hosttime unsignedLongLongValue]) / 1000000 + 40)
  235194. : (([sampleBuffer presentationTime].timeValue * 1000) / [sampleBuffer presentationTime].timeScale + 50);
  235195. const int64 timeDiff = now.toMilliseconds() - presentationTime;
  235196. if (firstPresentationTime == 0)
  235197. {
  235198. firstPresentationTime = presentationTime;
  235199. averageTimeOffset = timeDiff;
  235200. }
  235201. else
  235202. {
  235203. averageTimeOffset = (averageTimeOffset * 120 + timeDiff * 8) / 128;
  235204. }
  235205. }
  235206. @end
  235207. BEGIN_JUCE_NAMESPACE
  235208. class QTCaptureViewerComp : public NSViewComponent
  235209. {
  235210. public:
  235211. QTCaptureViewerComp (CameraDevice* const cameraDevice, QTCameraDeviceInteral* const internal)
  235212. {
  235213. const ScopedAutoReleasePool pool;
  235214. captureView = [[QTCaptureView alloc] init];
  235215. [captureView setCaptureSession: internal->session];
  235216. setSize (640, 480); // xxx need to somehow get the movie size - how?
  235217. setView (captureView);
  235218. }
  235219. ~QTCaptureViewerComp()
  235220. {
  235221. setView (0);
  235222. [captureView setCaptureSession: nil];
  235223. [captureView release];
  235224. }
  235225. QTCaptureView* captureView;
  235226. };
  235227. CameraDevice::CameraDevice (const String& name_, int index)
  235228. : name (name_)
  235229. {
  235230. isRecording = false;
  235231. internal = new QTCameraDeviceInteral (this, index);
  235232. }
  235233. CameraDevice::~CameraDevice()
  235234. {
  235235. stopRecording();
  235236. delete static_cast <QTCameraDeviceInteral*> (internal);
  235237. internal = 0;
  235238. }
  235239. Component* CameraDevice::createViewerComponent()
  235240. {
  235241. return new QTCaptureViewerComp (this, static_cast <QTCameraDeviceInteral*> (internal));
  235242. }
  235243. const String CameraDevice::getFileExtension()
  235244. {
  235245. return ".mov";
  235246. }
  235247. void CameraDevice::startRecordingToFile (const File& file, int quality)
  235248. {
  235249. stopRecording();
  235250. QTCameraDeviceInteral* const d = static_cast <QTCameraDeviceInteral*> (internal);
  235251. d->callbackDelegate->firstPresentationTime = 0;
  235252. file.deleteFile();
  235253. // In some versions of QT (e.g. on 10.5), if you record video without audio, the speed comes
  235254. // out wrong, so we'll put some audio in there too..,
  235255. d->addDefaultAudioInput();
  235256. [d->session addOutput: d->fileOutput error: nil];
  235257. NSEnumerator* connectionEnumerator = [[d->fileOutput connections] objectEnumerator];
  235258. for (;;)
  235259. {
  235260. QTCaptureConnection* connection = [connectionEnumerator nextObject];
  235261. if (connection == 0)
  235262. break;
  235263. QTCompressionOptions* options = 0;
  235264. NSString* mediaType = [connection mediaType];
  235265. if ([mediaType isEqualToString: QTMediaTypeVideo])
  235266. options = [QTCompressionOptions compressionOptionsWithIdentifier:
  235267. quality >= 1 ? @"QTCompressionOptionsSD480SizeH264Video"
  235268. : @"QTCompressionOptions240SizeH264Video"];
  235269. else if ([mediaType isEqualToString: QTMediaTypeSound])
  235270. options = [QTCompressionOptions compressionOptionsWithIdentifier: @"QTCompressionOptionsHighQualityAACAudio"];
  235271. [d->fileOutput setCompressionOptions: options forConnection: connection];
  235272. }
  235273. [d->fileOutput recordToOutputFileURL: [NSURL fileURLWithPath: juceStringToNS (file.getFullPathName())]];
  235274. isRecording = true;
  235275. }
  235276. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  235277. {
  235278. QTCameraDeviceInteral* const d = static_cast <QTCameraDeviceInteral*> (internal);
  235279. if (d->callbackDelegate->firstPresentationTime != 0)
  235280. return Time (d->callbackDelegate->firstPresentationTime + d->callbackDelegate->averageTimeOffset);
  235281. return Time();
  235282. }
  235283. void CameraDevice::stopRecording()
  235284. {
  235285. if (isRecording)
  235286. {
  235287. static_cast <QTCameraDeviceInteral*> (internal)->resetFile();
  235288. isRecording = false;
  235289. }
  235290. }
  235291. void CameraDevice::addListener (CameraImageListener* listenerToAdd)
  235292. {
  235293. if (listenerToAdd != 0)
  235294. static_cast <QTCameraDeviceInteral*> (internal)->addListener (listenerToAdd);
  235295. }
  235296. void CameraDevice::removeListener (CameraImageListener* listenerToRemove)
  235297. {
  235298. if (listenerToRemove != 0)
  235299. static_cast <QTCameraDeviceInteral*> (internal)->removeListener (listenerToRemove);
  235300. }
  235301. const StringArray CameraDevice::getAvailableDevices()
  235302. {
  235303. const ScopedAutoReleasePool pool;
  235304. StringArray results;
  235305. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  235306. for (int i = 0; i < (int) [devs count]; ++i)
  235307. {
  235308. QTCaptureDevice* dev = (QTCaptureDevice*) [devs objectAtIndex: i];
  235309. results.add (nsStringToJuce ([dev localizedDisplayName]));
  235310. }
  235311. return results;
  235312. }
  235313. CameraDevice* CameraDevice::openDevice (int index,
  235314. int minWidth, int minHeight,
  235315. int maxWidth, int maxHeight)
  235316. {
  235317. ScopedPointer <CameraDevice> d (new CameraDevice (getAvailableDevices() [index], index));
  235318. if (static_cast <QTCameraDeviceInteral*> (d->internal)->openingError.isEmpty())
  235319. return d.release();
  235320. return 0;
  235321. }
  235322. #endif
  235323. /*** End of inlined file: juce_mac_CameraDevice.mm ***/
  235324. #endif
  235325. #endif
  235326. END_JUCE_NAMESPACE
  235327. #endif
  235328. /*** End of inlined file: juce_mac_NativeCode.mm ***/
  235329. #endif
  235330. #endif